terml-spawner 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
terml/__init__.py ADDED
@@ -0,0 +1,414 @@
1
+ """terml - YAML based spawner for Terminator"""
2
+
3
+ import os
4
+ import re
5
+ import shlex
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ from argparse import ArgumentParser
10
+ from hashlib import sha1
11
+ from importlib.metadata import version
12
+ from pathlib import Path
13
+
14
+ import yaml
15
+ from configobj import ConfigObj
16
+
17
+ INHERITED = ("cwd", "font-size", "keep")
18
+ NODE_KEYS = {"split", "ratio", "children", "command", "disabled", *INHERITED}
19
+ WINDOW_KEYS = {
20
+ "name",
21
+ "pos",
22
+ "size",
23
+ "fullscreen",
24
+ "maximize",
25
+ "force-x11",
26
+ *NODE_KEYS,
27
+ }
28
+ ROOT_KEYS = {"children", "disabled", *INHERITED}
29
+ PANED = {"vertical": "VPaned", "horizontal": "HPaned"}
30
+ LAYOUT = "terml"
31
+ SHELL = "${SHELL:-sh}" # unquoted: keeps the config free of nested quotes
32
+
33
+
34
+ def present(mapping):
35
+ return {key: value for key, value in mapping.items() if value is not None}
36
+
37
+
38
+ def fraction(ratio):
39
+ return float(str(ratio).rstrip("%")) / 100
40
+
41
+
42
+ def greedy(children):
43
+ return any(
44
+ not 0 < fraction(child["ratio"]) < 1
45
+ for child in children[:-1]
46
+ if isinstance(child, dict) and "ratio" in child
47
+ )
48
+
49
+
50
+ def enabled(nodes):
51
+ return [
52
+ (index, node or {})
53
+ for index, node in enumerate(nodes or [])
54
+ if not (isinstance(node, dict) and node.get("disabled"))
55
+ ]
56
+
57
+
58
+ def pair(value):
59
+ return (
60
+ isinstance(value, list)
61
+ and len(value) == 2
62
+ and all(isinstance(item, int) or relative(item) for item in value)
63
+ )
64
+
65
+
66
+ def relative(value):
67
+ return isinstance(value, str) and bool(re.fullmatch(r"\d+(\.\d+)?%", value))
68
+
69
+
70
+ def problems(node, allowed, where):
71
+ if not isinstance(node, dict):
72
+ return [f"{where}: expected a mapping"]
73
+ children = enabled(node.get("children"))
74
+ unknown = sorted(map(str, set(node) - allowed))
75
+ return [
76
+ *(
77
+ f"{where}: {message}"
78
+ for failed, message in (
79
+ (unknown, f"unknown keys {unknown}"),
80
+ (
81
+ {"command", "children"} <= set(node),
82
+ "'command' and 'children' exclude each other",
83
+ ),
84
+ (
85
+ node.get("split", "vertical") not in PANED,
86
+ f"'split' must be one of {sorted(PANED)}",
87
+ ),
88
+ (
89
+ any(not pair(node[key]) for key in ("pos", "size") if key in node),
90
+ "'pos' and 'size' take two integers or percentages",
91
+ ),
92
+ (
93
+ greedy([child for _, child in children]),
94
+ "'ratio' must be more than 0% and less than 100%",
95
+ ),
96
+ )
97
+ if failed
98
+ ),
99
+ *(
100
+ problem
101
+ for index, child in children
102
+ for problem in problems(child, NODE_KEYS, f"{where}.children[{index}]")
103
+ ),
104
+ ]
105
+
106
+
107
+ def resolved(node, parent, base):
108
+ own = {
109
+ **{key: parent[key] for key in INHERITED if key in parent},
110
+ **node,
111
+ **(
112
+ {
113
+ "cwd": str(
114
+ Path(parent.get("cwd", base))
115
+ / Path(str(node["cwd"] or "~")).expanduser()
116
+ )
117
+ }
118
+ if "cwd" in node
119
+ else {}
120
+ ),
121
+ }
122
+ return {
123
+ **own,
124
+ "children": [
125
+ resolved(child, own, base)
126
+ for _, child in enabled(node.get("children"))
127
+ ],
128
+ }
129
+
130
+
131
+ def source(path):
132
+ return sys.stdin.read() if str(path) == "-" else path.read_text()
133
+
134
+
135
+ def root(path):
136
+ content = yaml.safe_load(source(path)) or []
137
+ return {"children": content} if isinstance(content, list) else content
138
+
139
+
140
+ def root_problems(node, where):
141
+ if not isinstance(node, dict):
142
+ return [f"{where}: top level must be a list or a map"]
143
+ unknown = sorted(map(str, set(node) - ROOT_KEYS))
144
+ return [
145
+ *[f"{where}: unknown top level keys {unknown}"][: bool(unknown)],
146
+ *(
147
+ problem
148
+ for index, win in enabled(node.get("children"))
149
+ for problem in problems(win, WINDOW_KEYS, f"{where}[{index}]")
150
+ ),
151
+ ]
152
+
153
+
154
+ def windows(paths):
155
+ roots = [(path, node) for path in paths for _, node in enabled([root(path)])]
156
+ found = [
157
+ problem
158
+ for path, node in roots
159
+ for problem in root_problems(node, {"-": "<stdin>"}.get(f"{path}", f"{path}"))
160
+ ]
161
+ if found:
162
+ raise ValueError("\n".join(found))
163
+ return [
164
+ win
165
+ for path, node in roots
166
+ for win in resolved(node, {"keep": True}, path.parent.resolve())["children"]
167
+ ]
168
+
169
+
170
+ def leaves(node):
171
+ return [leaf for child in node["children"] for leaf in leaves(child)] or [node]
172
+
173
+
174
+ def profile_name(size):
175
+ return f"{LAYOUT}-{size}"
176
+
177
+
178
+ def command(node):
179
+ # interactive shell: rc files get sourced, so functions and aliases work
180
+ return node.get("command") and f"exec {SHELL} -ic " + shlex.quote(
181
+ node["command"] + (f"; exec {SHELL}" if node["keep"] else "")
182
+ )
183
+
184
+
185
+ def terminal(node, name, parent, order):
186
+ return {
187
+ name: present(
188
+ {
189
+ "type": "Terminal",
190
+ "parent": parent,
191
+ "order": order,
192
+ "directory": node.get("cwd"),
193
+ "command": command(node),
194
+ "profile": node.get("font-size") and profile_name(node["font-size"]),
195
+ }
196
+ )
197
+ }
198
+
199
+
200
+ def paned(kind, children, name, parent, order):
201
+ head, *tail = children
202
+ return {
203
+ name: {
204
+ "type": kind,
205
+ "parent": parent,
206
+ "order": order,
207
+ "ratio": round(
208
+ fraction(head["ratio"]) if "ratio" in head else 1 / len(children), 4
209
+ ),
210
+ },
211
+ **items(head, f"{name}-0", name, 0),
212
+ **(
213
+ items(tail[0], f"{name}-1", name, 1)
214
+ if len(tail) == 1
215
+ else paned(kind, tail, f"{name}-1", name, 1)
216
+ ),
217
+ }
218
+
219
+
220
+ def items(node, name, parent, order):
221
+ children = node["children"]
222
+ return (
223
+ paned(
224
+ PANED[node.get("split", "vertical")],
225
+ children,
226
+ name,
227
+ parent,
228
+ order,
229
+ )
230
+ if len(children) > 1
231
+ else items(children[0], name, parent, order)
232
+ if children
233
+ else terminal(node, name, parent, order)
234
+ )
235
+
236
+
237
+ def window(node, name):
238
+ return {
239
+ name: present(
240
+ {
241
+ "type": "Window",
242
+ "parent": "",
243
+ "order": 0,
244
+ "title": node.get("name"),
245
+ "position": node.get("pos") and "{}:{}".format(*node["pos"]),
246
+ "size": node.get("size"),
247
+ "fullscreen": node.get("fullscreen") or None,
248
+ "maximised": node.get("maximize") or None,
249
+ }
250
+ ),
251
+ **items(node, f"{name}-0", name, 0),
252
+ }
253
+
254
+
255
+ def layout(wins):
256
+ return {
257
+ name: item
258
+ for index, win in enumerate(wins)
259
+ for name, item in window(win, f"window{index}").items()
260
+ }
261
+
262
+
263
+ def monitor(xrandr):
264
+ found = re.search(
265
+ r" connected primary (\d+)x(\d+)\+(\d+)\+(\d+)", xrandr
266
+ ) or re.search(r" connected (\d+)x(\d+)\+(\d+)\+(\d+)", xrandr)
267
+ if not found:
268
+ raise ValueError("percentages in 'pos' / 'size' need a working `xrandr`")
269
+ width, height, x, y = map(int, found.groups())
270
+ return {"pos": ((x, width), (y, height)), "size": ((0, width), (0, height))}
271
+
272
+
273
+ def primary_monitor():
274
+ return monitor(
275
+ subprocess.run(
276
+ "xrandr --current", shell=True, capture_output=True, text=True
277
+ ).stdout
278
+ )
279
+
280
+
281
+ def floating(win):
282
+ return any(relative(value) for key in ("pos", "size") for value in win.get(key, []))
283
+
284
+
285
+ def placed(win, screen):
286
+ return {
287
+ **win,
288
+ **{
289
+ key: [
290
+ offset + round(total * fraction(value)) if relative(value) else value
291
+ for value, (offset, total) in zip(win[key], screen[key])
292
+ ]
293
+ for key in ("pos", "size")
294
+ if key in win
295
+ },
296
+ }
297
+
298
+
299
+ def system_font():
300
+ return (
301
+ subprocess.run(
302
+ "gsettings get org.gnome.desktop.interface monospace-font-name",
303
+ shell=True,
304
+ capture_output=True,
305
+ text=True,
306
+ ).stdout.strip(" '\n")
307
+ or "Mono 10"
308
+ )
309
+
310
+
311
+ def font_family(default):
312
+ font = (
313
+ default.get("font", "Mono 10")
314
+ if str(default.get("use_system_font", True)) == "False"
315
+ else system_font()
316
+ )
317
+ return re.sub(r"\s+[\d.]+(px)?$", "", font)
318
+
319
+
320
+ def profiles(default, sizes):
321
+ family = sizes and font_family(default)
322
+ return {
323
+ profile_name(size): {
324
+ **default,
325
+ "use_system_font": False,
326
+ "font": f"{family} {size}",
327
+ }
328
+ for size in sizes
329
+ }
330
+
331
+
332
+ def config(base, wins):
333
+ known = base.get("profiles", {})
334
+ sizes = sorted(
335
+ {
336
+ str(leaf["font-size"])
337
+ for win in wins
338
+ for leaf in leaves(win)
339
+ if leaf.get("font-size")
340
+ }
341
+ )
342
+ return {
343
+ **base,
344
+ "profiles": {**known, **profiles(known.get("default", {}), sizes)},
345
+ "layouts": {**base.get("layouts", {}), LAYOUT: layout(wins)},
346
+ }
347
+
348
+
349
+ def rendered(cfg):
350
+ return "\n".join(ConfigObj(cfg, interpolation=False).write()) + "\n"
351
+
352
+
353
+ def user_config():
354
+ path = (
355
+ Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
356
+ / "terminator"
357
+ / "config"
358
+ )
359
+ return ConfigObj(str(path), interpolation=False, encoding="utf-8").dict()
360
+
361
+
362
+ def spawn(text, x11):
363
+ path = (
364
+ Path(os.environ.get("XDG_RUNTIME_DIR") or tempfile.gettempdir())
365
+ / "terml"
366
+ / f"{sha1(text.encode()).hexdigest()[:12]}.config"
367
+ )
368
+ path.parent.mkdir(parents=True, exist_ok=True)
369
+ path.write_text(text)
370
+ subprocess.Popen(
371
+ ["terminator", "--no-dbus", "--config", str(path), "--layout", LAYOUT],
372
+ env={**os.environ, **({"GDK_BACKEND": "x11"} if x11 else {})},
373
+ start_new_session=True,
374
+ stdin=subprocess.DEVNULL,
375
+ stdout=subprocess.DEVNULL,
376
+ stderr=subprocess.DEVNULL,
377
+ )
378
+
379
+
380
+ def run(args):
381
+ loaded = windows(args.files)
382
+ screen = any(map(floating, loaded)) and primary_monitor()
383
+ wins = [placed(win, screen) if floating(win) else win for win in loaded]
384
+ base = user_config()
385
+ for x11 in (False, True):
386
+ group = [win for win in wins if bool(win.get("force-x11")) == x11]
387
+ text = group and rendered(config(base, group))
388
+ if text and args.print_config:
389
+ print(text, end="")
390
+ elif text:
391
+ spawn(text, x11)
392
+
393
+
394
+ def main():
395
+ parser = ArgumentParser(prog="terml", description=__doc__)
396
+ parser.add_argument(
397
+ "--version", action="version", version=f"%(prog)s {version('pyterml')}"
398
+ )
399
+ parser.add_argument(
400
+ "files",
401
+ nargs="+",
402
+ metavar="FILE",
403
+ type=Path,
404
+ help="session file, `-` reads from stdin",
405
+ )
406
+ parser.add_argument(
407
+ "--print-config",
408
+ action="store_true",
409
+ help="print the generated Terminator config instead of spawning",
410
+ )
411
+ try:
412
+ run(parser.parse_args())
413
+ except (ValueError, OSError, yaml.YAMLError) as error:
414
+ sys.exit(f"terml: {error}")
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.5
2
+ Name: terml-spawner
3
+ Version: 0.1.0
4
+ Summary: YAML based spawner for Terminator
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: configobj>=5.0.8
7
+ Requires-Dist: pyyaml>=6
8
+ Description-Content-Type: text/markdown
9
+
10
+ # terml
11
+
12
+ YAML based spawner for [Terminator](https://github.com/gnome-terminator/terminator):
13
+ describe windows, splits, ratios, font sizes, working directories and commands
14
+ in a YAML file and let `terml` open them all at once.
15
+
16
+
17
+ ## Usage
18
+
19
+ terml FILE [FILE ...] # open all windows, return immediately
20
+ terml - # read the session from stdin
21
+ terml --print-config FILE ... # show the generated Terminator config
22
+ terml --version
23
+
24
+ Run it from the project folder without installing:
25
+
26
+ uv run terml example-session.yaml
27
+
28
+ Or install it:
29
+
30
+ uv tool install .
31
+
32
+ With `terml` on your `PATH` a session file starting with
33
+ `#!/usr/bin/env terml` can be made executable and started directly.
34
+
35
+ `-` instead of a file reads from stdin, which goes well with a here-document.
36
+ A relative `cwd` is then relative to the current directory:
37
+
38
+ terml - <<'EOF'
39
+ - {command: htop}
40
+ - {cwd: ~/src, children: [{}, {}]}
41
+ EOF
42
+
43
+
44
+ ## Session files
45
+
46
+ The top level is a list. Every entry is a window. An entry with `children`
47
+ is split, an entry without is a terminal. See `example-session.yaml`.
48
+
49
+ The top level may also be a map with the windows as `children`. Next to
50
+ `children` it takes the inherited keys (see below) and `disabled`, which then
51
+ apply to all windows of the file:
52
+
53
+ font-size: 20
54
+ cwd: ~/src
55
+ children:
56
+ - name: first window
57
+ - name: second window
58
+
59
+ - name: projects
60
+ size: [400, 800]
61
+ cwd: ~/src
62
+ children:
63
+ - command: htop
64
+ ratio: 30%
65
+ - split: horizontal
66
+ children:
67
+ - command: git status
68
+ - font-size: 8px
69
+
70
+ | Key | Where | Meaning |
71
+ |-------------|-----------|--------------------------------------------------|
72
+ | `name` | window | window title |
73
+ | `pos` | window | `[x, y]` in pixels or percent (see limitations) |
74
+ | `size` | window | `[width, height]` in pixels or percent |
75
+ | `fullscreen`| window | `true` makes the window fullscreen |
76
+ | `maximize` | window | `true` maximizes the window |
77
+ | `force-x11` | window | `true` starts Terminator with `GDK_BACKEND=x11` |
78
+ | `children` | anywhere | list of nested entries |
79
+ | `split` | anywhere | how `children` are arranged: `vertical` stacks |
80
+ | | | them top to bottom (default), `horizontal` puts |
81
+ | | | them side by side |
82
+ | `ratio` | child | share of the space left over by the children |
83
+ | | | before it, e.g. `40%` |
84
+ | `command` | terminal | command to run in an interactive `$SHELL` |
85
+ | `cwd` | inherited | working directory |
86
+ | `font-size` | inherited | `8` means points, `8px` means pixels |
87
+ | `keep` | inherited | `true` (default): drop into a shell after the |
88
+ | | | command. `false`: Terminator decides, by default |
89
+ | | | the terminal closes |
90
+ | `disabled` | anywhere | `true` ignores the entry and all its children |
91
+
92
+ Details:
93
+
94
+ - "inherited" keys apply to all children unless a child overrides them.
95
+ - Children are placed in the order they are written. `ratio` is a share of
96
+ what the children before left over: `50%`, `50%`, rest gives 50%, 25% and
97
+ 25% of the parent. The last child always takes the rest, its `ratio` is
98
+ ignored.
99
+ - A child without `ratio` takes an equal share: one third of the rest if
100
+ three children are still to be placed (itself included). So children
101
+ without any `ratio` split their parent equally.
102
+ - A relative `cwd` is relative to the parent's `cwd`, or to the session file
103
+ at the top level. `cwd: ~` means home.
104
+ - Note that `vertical` and `horizontal` name the direction in which the
105
+ children are laid out. Terminator's menu names it the other way round.
106
+ - Commands run via `$SHELL -ic`, so `.bashrc` / `.zshrc` are sourced and
107
+ your functions and aliases are available.
108
+ - `pos` and `size` accept percentages, also mixed with pixels:
109
+ `size: [300, 100%]`. They refer to the primary monitor as reported by
110
+ `xrandr`, to its full size including panels and docks. A `pos` in
111
+ percent starts at the top left corner of that monitor, a `pos` in pixels
112
+ at the top left corner of the whole desktop.
113
+ - A `disabled` entry is treated as if it wasn't there: it takes no space,
114
+ and its content isn't even checked.
115
+ - Unknown keys are errors.
116
+
117
+
118
+ ## How it works
119
+
120
+ `terml` copies your Terminator config (`~/.config/terminator/config`), adds a
121
+ layout `terml` plus one profile per font size (copies of your `default`
122
+ profile), writes the result to `$XDG_RUNTIME_DIR/terml/` and starts
123
+
124
+ terminator --no-dbus --config <generated config> --layout terml
125
+
126
+ Your own config is never modified.
127
+
128
+
129
+ ## Limitations
130
+
131
+ - `pos` is ignored on Wayland unless `force-x11: true` is set for the window.
132
+ - Percentages need `xrandr`. With display scaling the pixels reported by
133
+ `xrandr` may not be the pixels Terminator counts in.
134
+ - Windows opened by `terml` run in their own Terminator process without DBus.
135
+ `remotinator` and `terminator --new-tab` don't reach them.
136
+ - Preferences saved from within such a window end up in the generated config
137
+ and are gone after logout.
138
+
139
+
140
+ ## Development
141
+
142
+ uv run pytest
@@ -0,0 +1,5 @@
1
+ terml/__init__.py,sha256=x2NKs4hXSs98n9nklHIm0_weFFUqoW1wFk46M3jNC7E,11243
2
+ terml_spawner-0.1.0.dist-info/METADATA,sha256=fglXsYDU-OFfRufs6f8dyfnCvCbga1CtNva4k9BNZKk,5713
3
+ terml_spawner-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ terml_spawner-0.1.0.dist-info/entry_points.txt,sha256=PCg2f-Ek3TD-PHkmDldweXKDOZv5llOJLi4hHN_OEPY,58
5
+ terml_spawner-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ pyterml = terml:main
3
+ terml = terml:main