/
i3altlayout.py
executable file
·111 lines (91 loc) · 2.48 KB
/
i3altlayout.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
#!/usr/bin/env python3
# author: deadc0de6
"""
author: deadc0de6 (https://github.com/deadc0de6)
Copyright (c) 2019, deadc0de6
i3wm efficient screen real estate
"""
import sys
import os
import i3ipc
from docopt import docopt
NAME = 'i3altlayout'
VERSION = '1.1.2'
DEBUG = False
USAGE = f"""
{NAME}
Usage:
{NAME} [-d] [--pid=<path>] [--socket=<path>]
{NAME} --help
{NAME} --version
Options:
-d --debug Enable debug logs.
-p --pid=<path> Write pid to file.
-s --socket=<path> i3 socket path.
-v --version Show version.
-h --help Show this screen.
"""
def log(string):
"""write logs to stderr"""
if not DEBUG:
return
sys.stderr.write(f'{string}\n')
def on_window_focus(i3vm, _event):
"""split depending on window size"""
window = i3vm.get_tree().find_focused()
log(f'new focused window: {window}')
if not window:
return
if not window.rect:
return
if window.layout in ['stacked', 'tabbed']:
return
log('is a valid window')
height = window.rect.height
width = window.rect.width
log(f'height: {height}, width: {width}')
# aspect ratio rule BUT always split vertical if the screen is portrait.
# Rationale: it's uncommon to have applications that
# work well on very tiny width
workspace_height = window.workspace().rect.height
workspace_width = window.workspace().rect.width
if workspace_height > workspace_width:
layout = 'vertical'
else:
if height > width:
layout = 'vertical'
else:
layout = 'horizontal'
cmd = f'split {layout}'
log(f'running command: {cmd}')
i3vm.command(cmd)
log('\n')
def write_pid(path):
"""write our pid to file"""
if not path:
return
pid = str(os.getpid())
with open(path, 'w', encoding='utf-8') as file:
file.write(pid)
def main(spath, ppath):
"""entry point"""
write_pid(ppath)
try:
i3vm = i3ipc.Connection(socket_path=spath)
except Exception as exc: # pylint: disable=W0718,W0703
print(exc)
return False
i3vm.on('window::focus', on_window_focus)
try:
i3vm.main()
except KeyboardInterrupt:
pass
return True
if __name__ == "__main__":
args = docopt(USAGE, version=VERSION)
DEBUG = args['--debug']
socket_path = args['--socket']
pid_path = args['--pid']
if main(socket_path, pid_path):
sys.exit(0)
sys.exit(1)