-
Notifications
You must be signed in to change notification settings - Fork 1
/
i3_automark_daemon.py
executable file
·184 lines (155 loc) · 5.67 KB
/
i3_automark_daemon.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
#!/usr/bin/env python3
import itertools
import json
import os
import socket
import struct
import subprocess
import sys
import time
class SocketClosedException(Exception):
pass
# MARKS = '1234567890qwertyuiopasdfghjklzxcvbnm'
MARKS = ''
with open(
os.path.expanduser('~') + '/.config/i3/share/i3_automark_list.txt',
'r') as automark_txt:
for mark in automark_txt.readlines():
MARKS += mark.strip('\n')
COMMANDS = [
'run_command',
'get_workspaces',
'subscribe',
'get_outputs',
'get_tree',
'get_marks',
'get_bar_config',
'get_version',
'get_binding_modes',
'send_tick',
]
EVENTS = [
'workspace',
'output',
'mode',
'window',
'barconfig_update',
'binding',
'shutdown',
'tick',
]
def recv(sock, length):
buf = b''
while length:
data = sock.recv(length)
if not data:
break
buf += data
length -= len(data)
return buf
def send_msg(sock, command, payload=''):
payload = payload.encode('utf-8')
msg = struct.pack('II', len(payload), COMMANDS.index(command))
sock.sendall(b'i3-ipc' + msg + payload)
while True:
type, response = read_msg(sock)
if type == command:
if command == 'run_command':
response = response[0]
if isinstance(response,
dict) and not response.get('success', True):
raise Exception(response.get('error'))
return response
def read_msg(sock):
reply = recv(sock, 14)
if not reply:
raise SocketClosedException
length, type = struct.unpack('ii', reply[6:])
if type & 0x80000000:
type = EVENTS[type & 0x7fffffff]
else:
type = COMMANDS[type]
return type, json.loads(recv(sock, length))
def delete_all_marks(sock, marks):
existing_marks = send_msg(sock, 'get_marks')
for mark in marks:
if mark in existing_marks:
send_msg(sock, 'run_command', 'unmark {}'.format(mark))
def add_all_marks(sock, marks):
# # Sort workspace in x-dir (left to right) and y-dir (top to bottom)
# workspaces = sorted(send_msg(sock, 'get_workspaces'),
# key=lambda w: (w['rect']['x'], w['rect']['y']))
# Sort workspace in y-dir (top to bottom) and x-dir (left to right)
# workspaces = sorted(send_msg(sock, 'get_workspaces'),
# key=lambda w: (w['rect']['y'], w['rect']['x']))
# Sort workspace in workspace name (A1 -> A2 -> ... -> B1 -> ...)
workspaces = sorted(
send_msg(sock, 'get_workspaces'),
key=lambda w: w['name']
if len(w['name'].split(':')) <= 1 else w['name'].split(':')[1])
visible_ws = [w['name'] for w in workspaces if w['visible']]
tree = send_msg(sock, 'get_tree')
windows = itertools.chain.from_iterable(
get_windows(tree, workspace) for workspace in visible_ws)
for mark, id in zip(marks, windows):
send_msg(sock, 'run_command',
'[con_id="{}"] mark --add {}'.format(id, mark))
def get_windows(node, workspace):
if node['window']:
yield node['id']
elif node['type'] == 'dockarea':
return
elif node['type'] == 'workspace' and node['name'] != workspace:
return
else:
for child in node['nodes'] + node['floating_nodes']:
yield from get_windows(child, workspace)
if __name__ == '__main__':
no_socket_counter = 0
marks = sys.argv[1] if len(sys.argv) > 1 else MARKS
while True:
try:
socketpath = subprocess.check_output(['i3', '--get-socketpath'
]).rstrip(b'\n')
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.connect(socketpath)
no_socket_counter = 0
send_msg(sock, 'subscribe',
json.dumps(['workspace', 'output', 'window']))
# Initialize marks for all windows
add_all_marks(sock, marks)
send_msg(sock, 'run_command', 'mark --add " "')
send_msg(sock, 'run_command', 'mark --add \'')
while True:
type, event = read_msg(sock)
print("{}: {}".format(type, event['change']))
# Delete all marks when window is close
if (type == 'window' and event['change']
== 'close') or (type == 'workspace'
and event['change'] == 'focus'):
delete_all_marks(sock, marks)
if type in {'workspace', 'output'
} or (type == 'window' and event['change']
in {'new', 'close', 'move', 'focus'}):
# Mark all exising windows
add_all_marks(sock, marks)
# Mark last window with single quotation ('),
try:
send_msg(sock, 'run_command',
'[con_mark=" "] mark --add \'')
except:
print('No markable window for mark \'')
# Mark current window with space (" ").
try:
send_msg(sock, 'run_command', 'mark --add " "')
except:
print('No markable window for mark \" \"')
except SocketClosedException:
pass
except FileNotFoundError:
no_socket_counter += 1
if no_socket_counter > 10:
raise
time.sleep(0.1)
except KeyboardInterrupt:
break