forked from olemartinorg/i3-alternating-layout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alternating_layouts.py
executable file
·121 lines (99 loc) · 2.77 KB
/
alternating_layouts.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
#!/usr/bin/env python
import time
import i3
import re
import subprocess
import getopt
import sys
import os
import logging
from socket import error as SocketError
def find_parent(window_id):
"""
Find the parent of a given window id
"""
root_window = i3.get_tree()
result = [None]
def finder(n, p=None):
if result[0] is not None:
return
for node in n:
if node['id'] == window_id:
result[0] = p
return
if len(node['nodes']):
finder(node['nodes'], node)
finder(root_window['nodes'])
return result[0]
def set_layout():
"""
Set the layout/split for the currently
focused window to either vertical or
horizontal, depending on its width/height
"""
current_win = i3.filter(nodes=[], focused=True)
for win in current_win:
parent = find_parent(win['id'])
if (parent and "rect" in parent
and parent['layout'] != 'tabbed'
and parent['layout'] != 'stacked'):
height = parent['rect']['height']
width = parent['rect']['width']
if height > width:
new_layout = 'vertical'
else:
new_layout = 'horizontal'
i3.split(new_layout)
def print_help():
print("Usage: " + sys.argv[0] + " [-p path/to/pid.file]")
print("")
print("Options:")
print(" -p path/to/pid.file Saves the PID for this program in the filename specified")
print("")
def run():
"""
Main function - listen for window focus
changes and call set_layout when focus
changes
"""
opt_list, args = getopt.getopt(sys.argv[1:], 'hp:')
pid_file = None
for opt in opt_list:
if opt[0] == "-h":
print_help()
sys.exit()
if opt[0] == "-p":
pid_file = opt[1]
if pid_file:
with open(pid_file, 'w') as f:
f.write(str(os.getpid()))
process = subprocess.Popen(
['xprop', '-root', '-spy'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
regex = re.compile(b'^_NET_CLIENT_LIST_STACKING|^_NET_ACTIVE_WINDOW')
last_line = ""
while True:
time.sleep(0.5)
line = process.stdout.readline()
if line == b'': #X is dead
logging.warn('X is dead, continue')
continue
if line == last_line:
continue
if regex.match(line):
set_layout()
last_line = line
process.kill()
sys.exit()
def main():
while True:
try:
run()
except SocketError:
logging.error('socket error')
time.sleep(0.5)
continue
if __name__ == "__main__":
main()