forked from kenoh/arandr-autoconfig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharandr-autoconfig.py
executable file
·298 lines (243 loc) · 9.12 KB
/
arandr-autoconfig.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
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
#!/usr/bin/env python3
import click
import tendo.singleton
import time
import os.path
import glob
import subprocess
import re
import base64
import hashlib
import datetime
LAPTOP_ONLY_SCRIPT = "/home/serge/bin/screenlayout/laptop_eDP1_4-OlRZBeYC.sh"
def _debug(msg):
msg = str(msg)
message = [str(timestamp()), "DEBUG", msg]
print(" ".join(message))
def timestamp(ts=None):
if ts:
ts = int(ts)
else:
ts = time.time()
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
def parse_xrandr_output(text):
pattern = re.compile(
r"^([\w-]+)\sconnected\s(primary)?\s?([0-9+x]+)?\s?(left|right)?.*"
)
ret = filter(lambda x: pattern.match(x), text.decode("utf-8").splitlines())
ret = map(lambda x: pattern.match(x).group(1, 2, 3, 4), ret)
displays = sorted(ret, key=lambda x: x[0])
dimpattern = re.compile(r"([0-9]+)x([0-9]+)[+]([0-9]+)[+]([0-9]+)")
displayslist = []
for display in displays:
display = list(display)
try:
dimension = dimpattern.match(display[2])
w, h, x, y = dimension.group(1, 2, 3, 4)
ratio = int(w) / int(h)
orientation = display.pop()
if ratio > 2:
if orientation in ("left", "right"): # portrait
display.append("portrait")
display.append("splitv")
else:
display.append("ultrawide")
display.append("splith")
elif ratio > 0:
if orientation in ("left", "right"): # portrait
display.append("portrait")
display.append("splitv")
else:
display.append("landscape")
display.append("tabbed")
except TypeError:
display.append(None)
display.append(None)
displayslist.append(display)
displays = displayslist
return displays
def order_displays(displays):
# order displays from left to right, top to bottom
# smallest return number comes first
def _xsort(item):
if item[2]:
dimpattern = re.compile(r"([0-9]+)x([0-9]+)[+]([0-9]+)[+]([0-9]+)")
dimension = dimpattern.match(item[2])
[w, h, x, y] = [int(_) for _ in dimension.group(1, 2, 3, 4)]
order = (y + 1) * x
# print(item[0], "\t", w, h, x, y, "\t", order, "\t", (y+1)*x)
return order
else:
return 0
ret = sorted(displays, key=_xsort)
print(timestamp(), " Ordered: ", ret)
# now, keep the primary screen first, and rotate the ones before it to the
# end
for item in ret.copy():
if item[1] == "primary":
break
else:
ret.append(ret.pop(0))
return ret
def current_connected_displays(primary=False):
proc = subprocess.run(["xrandr"], stdout=subprocess.PIPE)
output = proc.stdout
ret = parse_xrandr_output(output)
if primary:
ret = order_displays(ret)
return ret
def get_edid():
def _hash(string):
hasher = hashlib.sha1(string)
return base64.urlsafe_b64encode(hasher.digest()).decode("utf-8")[:10]
_xrandr = """xrandr -q --verbose | awk '/^[^ ]+ (dis)?connected / { DEV=$1; } $1 ~ /^[a-f0-9]+$/ { ID[DEV] = ID[DEV] $1 } END { for (X in ID) { print X "," ID[X]; } }'"""
process = subprocess.Popen(_xrandr, stdout=subprocess.PIPE, shell=True)
output, error = process.communicate()
dispedid = output.decode("utf-8").splitlines()
dispedid = (x.split(",") for x in dispedid)
dispedid = dict((x, _hash(y.encode("utf-8"))) for x, y in dispedid)
return dispedid
def script_name(displays):
if len(displays) == 1:
return LAPTOP_ONLY_SCRIPT
edid = get_edid()
displays = [x[0] + "_" + edid[x[0]] for x in displays]
displays_name = "_".join(displays)
path = os.path.expanduser(os.path.join("~", ".screenlayout"))
script_pattern = os.path.join(path, '*' + displays_name + '*.sh')
print(script_pattern)
for script in sorted(glob.glob(script_pattern)):
print(script)
if os.path.isfile(script):
return script
return os.path.join(path, displays_name + ".sh")
def write_xresource(displays, noop):
xresourcefile = os.path.expanduser(os.path.join("~", ".Xresources.d", "i3"))
data = """
! ~/.Xresources.d/i3
! Make sure to include this file from ~/.Xresources by adding
! #include "~/.Xresources.d/i3"
! if there is just a single monitor, all indexes point to the first
! if there are only two monitors, 0 and 1 point to the first and 2 points to the second
"""
# remove display from list if not connected
_displays = []
for display in displays:
if display[2]:
_displays += [display]
displays = _displays
numdisplays = len(displays)
display0 = displays[0]
if numdisplays == 1:
display1 = displays[0]
display2 = displays[0]
elif numdisplays == 2:
display1 = displays[0]
display2 = displays[1]
elif numdisplays >= 3:
display1 = displays[1]
display2 = displays[2]
else:
raise (Exception)
primary = display0[0]
for display in displays:
if display[1] == "primary":
primary = display[0]
break
data += "\ni3.output.0.name: {}".format(display0[0])
data += "\ni3.output.0.primary: {}".format(display0[1])
data += "\ni3.output.0.geometry: {}".format(display0[2])
data += "\ni3.output.0.orientation: {}".format(display0[3])
data += "\ni3.output.0.layout: {}".format(display0[4])
data += "\n"
data += "\ni3.output.1.name: {}".format(display1[0])
data += "\ni3.output.1.primary: {}".format(display1[1])
data += "\ni3.output.1.geometry: {}".format(display1[2])
data += "\ni3.output.1.orientation: {}".format(display1[3])
data += "\ni3.output.1.layout: {}".format(display1[4])
data += "\n"
data += "\ni3.output.2.name: {}".format(display2[0])
data += "\ni3.output.2.primary: {}".format(display2[1])
data += "\ni3.output.2.geometry: {}".format(display2[2])
data += "\ni3.output.2.orientation: {}".format(display2[3])
data += "\ni3.output.2.layout: {}".format(display2[4])
data += "\n"
data += "\ni3.output.primary: {}".format(primary)
if numdisplays == 1:
data += "\ni3.output.secondary: {}".format(display1[0])
data += "\ni3.output.third: {}".format(display2[0])
elif numdisplays == 2:
data += "\ni3.output.secondary_bar: {}".format(display2[0])
else:
data += "\ni3.output.secondary: {}".format(display1[0])
data += "\ni3.output.third: {}".format(display2[0])
data += "\n"
print(data)
f = open(xresourcefile, "w")
f.write(data)
f.close()
# Reloading X server resource database utility
if noop:
print(timestamp(), "Would reload xrdb and i3wm but dry-run is set")
else:
subprocess.run(
["xrdb", os.path.expanduser("-I$HOME"), os.path.expanduser("~/.Xresources")],
stdout=subprocess.PIPE,
)
subprocess.run(["i3-msg", "reload"], stdout=subprocess.PIPE)
def loop(post, once, script, noop):
if once:
new = current_connected_displays()
handle_x(new, post, script, noop)
else:
previous = ""
while True:
new = current_connected_displays()
if new != previous:
previous = new
handle_x(new, post, script, noop)
time.sleep(3)
def run_script(path, noop):
if noop:
print(timestamp(), "Would execute %s but dry-run is set" % path)
else:
try:
subprocess.run([path])
except Exception:
print(timestamp(), " Not found: ", path)
return False
return True
def handle_x(displays, post, script, noop):
if script:
arandr_script = script
else:
arandr_script = script_name(displays)
print("########################################")
print("")
print(timestamp(), " New: ", displays)
print(timestamp(), " Executing: ", arandr_script)
if run_script(arandr_script, noop):
displays = current_connected_displays(primary=True)
print(timestamp(), " Updating i3 Xresources")
write_xresource(displays, noop)
if post:
print(timestamp(), " Executing: ", post)
if not run_script(post, noop):
print(timestamp(), " Failed running: ", post)
else:
print(timestamp(), " Failed running: ", arandr_script)
print(timestamp(), " Finished executing: ", arandr_script)
print("")
@click.option("--script", default=None, help="run specific script, don't autodetect; includes implicit --once")
@click.option("--post", default=None, help="program to run after a change")
@click.option("--once", is_flag=True, help="just run once and update")
@click.option("--noop", is_flag=True, help="dry-run")
@click.command()
def main(post, once, script, noop):
if script:
once = True
if not once:
instance = tendo.singleton.SingleInstance() # NOQA
loop(post, once, script, noop)
if __name__ == "__main__":
main()