-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmvwin
executable file
·568 lines (495 loc) · 23.4 KB
/
mvwin
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#!/usr/bin/env python3
r"""
This script moves windows between monitors supporting:
- XFCE4 (which provides no shortcuts for doing so).
- Plasma
- cinnimon
- mate
It requires python 3.4 or later.
Theory of operation... uses
- wmctrl -l # to learn ids of all windows
- xrandr | egrep '\<connected\>' # to learn geometry of displays
- xwininfo -id {ID} -all # to learn geometry of windows and window state
Written by joedefen / 2020 to 2021 - Public domain
"""
# pylint: disable=invalid-name,line-too-long
import subprocess
import re
import sys
from functools import cmp_to_key
def calc_center_x(geo):
"""Return the x of the center of the geo."""
return geo.x + geo.w//2
def calc_center_y(geo):
"""Return the y of the center of the geo."""
return geo.y + geo.h//2
class MoveWin:
"""The class that encapsulates the logic for moving windows between
monitors."""
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-arguments
directions = ['left', 'right', 'up', 'down', 'next', 'prev', 'here']
@staticmethod
def parse_args():
"""Handle all the arguments"""
# pylint: disable=import-outside-toplevel
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--ratio', action='store_true',
help='keep window ratio')
parser.add_argument('-d', '--disable-mouse', action='store_true',
help='disable moving the mouse', default=False)
parser.add_argument('-p', '--post_sort', type=str, default=False, choices=['x', 'y'],
help='Sorts displays by coordinate')
parser.add_argument('-P', '--no-panel-adjust', action='store_true',
help='defeat adjustment for desktop panels')
parser.add_argument('--DB', action='store_true',
help='print debugging info')
parser.add_argument('-w', '--win-id', type=str, default=None,
help='specify ID of window')
parser.add_argument('direction', nargs=1, choices=MoveWin.directions,
help='choose direction of movement')
args = parser.parse_args()
if args.DB:
print('args:', args)
return args
def __init__(self, args):
self.disps = {} # all display geometries key by their 'tag'
self.ordered_disps = [] # all disp in 'next' order
self.center_x, self.center_y = 0, 0 # center of all (unadjusted) displays
self.all_horizontal, self.all_vertical = True, True # all displays are vert or horiz?
self.relatives = {} # relatives of displays key by display tag
self.states = [] # state of window (e.g., fullscreen)
self.ogeo = None # old window geometry
self.ngeo = None # now window geometry
self.panels = [] # all xcfe4-panels on desktop of window
self.wm = 'unknown' # window manager starts as unknown
self.windows = {}
# translate args to control variables
self.DB = args.DB # print debug info?
self.win_id = args.win_id # window ID (find active if not given)
self.dir = args.direction[0] # direction to move (e.g, up or next)
self.use_ratio = args.ratio # preserved window/display ratio, not size
self.disable_mouse = args.disable_mouse
self.post_sort = args.post_sort
self.adjust_panel = not args.no_panel_adjust # consider panels?
def find_target_window(self):
"""Get the ID of the active window.... And the relevant panels.
"""
# learn all windows...
windows = {}
out = subprocess.check_output(['wmctrl', '-Gl']).decode('ascii', 'ignore')
for line in out.splitlines():
ns = MoveWin.namespace()
ns.win_id, ns.desktop, ns.x, ns.y, ns.w, ns.h, *more = line.split(maxsplit=7)
ns.x, ns.y, ns.w, ns.h = int(ns.x), int(ns.y), int(ns.w), int(ns.h)
ns.machine = more[0] if len(more) > 0 else ''
ns.title = more[1] if len(more) > 1 else ''
windows[int(ns.win_id, 0)] = ns
if ns.title in ('nemo-desktop', ):
self.wm = 'cinnamon'
self.windows = windows
# get active window (unless specified)...
if self.win_id is None:
out = subprocess.check_output(['xprop', '-root',
'_NET_ACTIVE_WINDOW']).decode('ascii', 'ignore')
# expecting: _NET_ACTIVE_WINDOW(WINDOW): window id # 0x48003f2, 0x0
self.win_id = re.search(r"window id # (0x[0-9a-f]+)", out).group(1)
if self.DB:
print('win_id:', self.win_id)
win = windows.get(int(self.win_id, 0), None)
if not win:
sys.exit(7)
# learn all panels panels on the selected desktop
for panel in windows.values():
if panel.desktop == '-1' or panel.desktop == win.desktop:
if panel.title in ('xfce4-panel', ): # XFCE
self.wm = 'xfce4'
self.panels.append(panel)
elif panel.title in ('Plasma', ): # KDE
self.panels.append(panel)
self.wm = 'plasma'
elif panel.title in ('Top Panel', 'Left Panel', 'Right Panel', 'Bottom Panel'): # mate
self.panels.append(panel)
self.wm = 'mate'
if self.DB:
print('wm:', self.wm, '#wins:', len(windows), '#panels:', len(self.panels),
'win:', vars(win))
def get_displays(self):
"""Get display information using xrandr...
- looking for: DVI-0 connected 1920x1080+0+0 (normal left ...
- disps[] is forced into geo namespace (.w, .x, .y)
"""
if self.wm in ('cinnamon',):
for win in self.windows.values():
if win.title in ('Desktop', 'nemo-desktop'):
# NOTE: unsure why the //2 is required for cinnamon
tag = f'disp{len(self.disps)}'
ns = self.make_geo(w=win.w, h=win.h, x=win.x//2, y=win.y//2, tag=tag)
self.disps[tag] = ns
self.center_x += calc_center_x(ns)
self.center_y += calc_center_y(ns)
else:
out = subprocess.check_output(['xrandr']).decode('ascii', 'ignore')
reg = re.compile(r'^(.*) connected( primary)? ([0-9]+)x([0-9]+)\+([0-9]+)\+([0-9]+)')
for line in out.splitlines():
match = reg.search(line)
if match:
tag = match.group(1)
ns = self.make_geo(
int(match.group(3)),
int(match.group(4)),
int(match.group(5)),
int(match.group(6)),
tag=tag)
self.disps[tag] = ns
self.center_x += calc_center_x(ns)
self.center_y += calc_center_y(ns)
if len(self.disps) > 0:
self.center_x //= len(self.disps)
self.center_y //= len(self.disps)
if self.DB:
print('disps:', '\n '.join([str(vars(s)) for s in self.disps.values()]))
def adjust_displays(self):
"""Adjust disps by removing panels from their area."""
# pylint: disable=too-many-nested-blocks
for panel in self.panels:
if self.wm in ('mate', ):
# not sure why, but for mate, cannot count on 'xwininfo' for geometry.
# thus, using the 'wmctrl' values (divided by two)
# NOTE: unsure why the //2 is required for mate
ogeo = self.make_geo(w=panel.w, h=panel.h, x=panel.x//2, y=panel.y//2, tag=str(panel.desktop))
elif self.wm in ('plasma', 'xfce4'):
ogeo = self.make_geo(w=panel.w, h=panel.h, x=panel.x, y=panel.y, tag=str(panel.desktop))
else:
ogeo, _ = self.get_window_info(panel.win_id)
if self.DB:
print('panel:', panel.title, vars(ogeo))
for display in self.disps.values():
if self.inside(ogeo, display):
ogeo.tag = display.tag
if ogeo.w < ogeo.h // 3: # vertical panel
if ogeo.h <= (7 * display.h) // 10:
pass # not much of a vertical panel
elif ogeo.x == display.x:
display.x += ogeo.w
display.w -= ogeo.w
if self.DB:
print(' LEFT adj', vars(display))
elif ogeo.x + ogeo.w == display.x + display.w:
display.w -= ogeo.w
if self.DB:
print(' RIGHT adj', vars(display))
elif ogeo.h < ogeo.w // 3: # horizontal panel
if ogeo.w <= (7 * display.w) // 10:
pass # not much of a horizontal panel
elif ogeo.y == display.y:
display.y += ogeo.h
display.h -= ogeo.h
if self.DB:
print(' TOP adj', vars(display))
elif ogeo.y + ogeo.h == display.y + display.h:
display.h -= ogeo.h
if self.DB:
print(' BOTTOM adj', vars(display))
@staticmethod
def overlap(a, b):
"""Compute area of overlapping windows."""
tlx = max(a.x, b.x)
tly = max(a.y, b.y)
brx = min(a.x + a.w, b.x + b.w)
bry = min(a.y + a.h, b.y + b.h)
return max(0, brx - tlx) * max(0, bry - tly)
@staticmethod
def inside(a, b):
""" Compute top left and bottom right coords in disps format: [w h x y] """
return MoveWin.overlap(a, b) == a.w * a.h
def find_relatives(self):
""" relatives will hold a dict of how disps are disposed between themselves,
using their idx; e.g. if disps[0] is at left of 1,
then relatives[1].left == 0 and relatives[0].right == 1
"""
for tag in self.disps:
self.relatives[tag] = MoveWin.namespace(
{'right_area': 0, 'down_area': 0})
relatives = self.relatives
all_horizontal, all_vertical = True, True # until proven otherwise
for ta, sa in self.disps.items():
for tb, sb in self.disps.items():
if ta != tb:
# Duplicate display on right then bottom, and check intersection
# If several, choose biggest for best choice presumably
area = self.overlap(self.dup_geo(sa, x=sa.x + sa.w), sb)
if area > relatives[ta].right_area:
relatives[ta].right_area = area
relatives[ta].right = tb
all_vertical = False
if area > relatives[tb].right_area:
relatives[tb].right_area = area
relatives[tb].left = ta
all_vertical = False
area = self.overlap(self.dup_geo(sa, y=sa.y + sa.h), sb)
if area > relatives[ta].down_area:
relatives[ta].down_area = area
relatives[ta].down = tb
all_horizontal = False
if area > relatives[tb].down_area:
relatives[tb].down_area = area
relatives[tb].up = ta
all_horizontal = False
self.all_horizontal, self.all_vertical = all_horizontal, all_vertical
for relative in relatives.values():
delattr(relative, 'right_area')
delattr(relative, 'down_area')
if self.DB:
for tag in relatives:
print(tag, vars(relatives[tag]))
def order_displays(self):
"""Put the displays in a "logical" order for next/prev.
- if horizontal (or forced), sort by its center-x
- if vertical (or forced), sort by its center-y
- sort radially (i.e., clockwise)
"""
def clockwiseof(a, b):
"""Inspired by: https://alltodev.com/sort-points-in-clockwise-order."""
nonlocal self
center_x, center_y = self.center_x, self.center_y
acx, bcx = calc_center_x(a), calc_center_x(b)
acy, bcy = calc_center_y(a), calc_center_y(b)
if acx - center_x >= 0 and bcx - center_x < 0:
return 1
if acx - center_x < 0 and bcx - center_x >= 0:
return -1
if acx - center_x == 0 and bcx - center_x == 0:
if acy - center_y >= 0 or bcy - center_y >= 0:
return acy > bcy
return bcy > acy
# compute the cross product of vectors (center -> a) x (center -> b)
det = (acx - center_x) * (bcy - center_y) - (bcx - center_x) * (acy - center_y)
if det < 0:
return 1
if det > 0:
return -1
# points a and b are on the same line from the center
# check which point is closer to the center
d1 = (acx - center_x) * (acx - center_x) + (acy - center_y) * (acy - center_y)
d2 = (bcx - center_x) * (bcx - center_x) + (bcy - center_y) * (bcy - center_y)
return d1 > d2
ordered_disps = list(self.disps.values())
if self.DB:
print("pre-order:", [d.tag for d in ordered_disps])
if self.post_sort:
ordered_disps.sort(key=lambda d: (d.y if self.post_sort.lower() == 'y' else d.x))
elif self.all_horizontal:
ordered_disps.sort(key=calc_center_x)
elif self.all_vertical:
ordered_disps.sort(key=calc_center_y)
else: # sort in clockwise order
ordered_disps.sort(key=cmp_to_key(clockwiseof))
if self.DB:
print("post-order:", [d.tag for d in ordered_disps])
relatives = self.relatives
for ii in range(len(ordered_disps)):
tag = ordered_disps[ii].tag
relatives[tag].here = tag
relatives[tag].next = ordered_disps[(ii + 1) % len(self.disps)].tag
relatives[tag].prev = ordered_disps[(ii - 1) % len(self.disps)].tag
self.ordered_disps = ordered_disps
def get_window_info(self, win_id):
""" Get focused window info"""
# pylint: disable=no-member
out = subprocess.check_output(['xwininfo', '-id',
win_id, '-all']).decode('ascii', 'ignore')
geo_str = (('w', "Width:"), ('h', "Height:"),
('x', "Absolute upper-left X:"), ('y', "Absolute upper-left Y:"),
('rx', "Relative upper-left X:"), ('ry', "Relative upper-left Y:"), ('', ""))
state_str = ("Maximized Vert", "Maximized Horz", "Fullscreen", )
ogeo = MoveWin.namespace({'w': None, 'h': None, 'x': None, 'y': None,
'rx': None, 'ry': None, 'tag': ''})
states = []
# Replace each ogeo elem with matching int, add states/types in state, converted for wmctrl
frame_extents_str = '' # e.g., Frame extents: 4, 4, 21, 4 for l in out.splitlines():
for l in out.splitlines():
l = l.strip()
idx = next(i for i, s in enumerate(geo_str) if l.startswith(s[1]))
if geo_str[idx][1] != "":
setattr(ogeo, geo_str[idx][0], int(l.split()[-1]))
elif l in state_str:
states += [l.lower().replace(' ', '_')]
elif l.startswith('Frame extents: '):
frame_extents_str = l[len('Frame extents: '):] # e.g., trim to "4, 4, 21, 4"
elif l == "Desktop":
# Top level window
sys.exit(2)
# for whatever reasons, XFCE4's rx, ry conventions are unique to it.
# Generally, infer from frame extents
if self.wm not in ('xfce4', ) and frame_extents_str:
nums = frame_extents_str.split(', ', 4)
ogeo.rx, ogeo.ry = int(nums[0]), int(nums[2])
# NOTE: adjust the geometry to include the whole window, borders and
# title included. This makes for much easier transformation of the
# window; when the moved is finally implemented, these adjustments
# will be reversed.
ogeo.x -= ogeo.rx # make x the upper left corner include border
ogeo.y -= ogeo.ry # make y the upper left corner include window title bar
ogeo.w += ogeo.rx + ogeo.rx # incr width to include borders
ogeo.h += ogeo.ry + ogeo.rx # incr height to include border and title bar
return ogeo, states
def get_chosen_window_info(self):
""" Get info for the chosen window. """
self.ogeo, self.states = self.get_window_info(self.win_id)
if self.DB:
print('ogeo:', vars(self.ogeo))
print('states:', self.states)
def pick_new_display(self):
""" Find display of active window from the max area. """
areas = list(map(lambda s: self.overlap(self.ogeo, s), self.ordered_disps))
try:
cur_idx = areas.index(max(areas + [1]))
except ValueError:
sys.exit(3)
ogeo = self.ogeo
ogeo.tag = self.ordered_disps[cur_idx].tag
if self.DB:
print('self.dir:', self.dir, 'ogeo.tag:', ogeo.tag)
ntag = getattr(self.relatives[ogeo.tag], self.dir, None)
self.ngeo = self.dup_geo(ogeo) # fix w,h,x,y later
self.ngeo.tag = ogeo.tag if ntag is None else ntag
if self.DB:
print('ngeo:', vars(self.ngeo))
def plan_move(self):
""" Compute the new window geometry. """
ngeo = self.ngeo
odisp = self.disps[self.ogeo.tag]
ndisp = self.disps[ngeo.tag]
if self.DB:
print('odisp:', vars(odisp))
print('ndisp:', vars(ndisp))
if self.use_ratio:
# scale window by keeping same ratio of space and size
wratio = 1.0 * ndisp.w / odisp.w
ngeo.w = int(0.5 + ngeo.w * wratio)
ngeo.x = int(0.5 + (ngeo.x - odisp.x) * wratio) + odisp.x
hratio = 1.0 * ndisp.h / odisp.h
ngeo.h = int(0.5 + ngeo.h * hratio)
ngeo.y = int(0.5 + (ngeo.y - odisp.y) * hratio) + odisp.y
else:
# OR give/take space around based on display size diffs
ngeo.x += (ndisp.w-odisp.w)//2
ngeo.y += (ndisp.h-odisp.h)//2
# now, shift into new display (but never left/above of left/top edges)
ngeo.x = ndisp.x + max(0, (ngeo.x - odisp.x))
ngeo.y = ndisp.y + max(0, (ngeo.y - odisp.y))
# now, if extends over right edge of new display, then constrain
over = (ngeo.x + ngeo.w) - (ndisp.x + ndisp.w)
if over > 0:
ngeo.x -= min(ngeo.x-ndisp.x, over)
ngeo.w = min(ngeo.w, ndisp.w)
if self.DB:
print('over-x:', over)
# now, if extends below bottom edge of new display, then constrain
over = (ngeo.y + ngeo.h) - (ndisp.y + ndisp.h)
if over > 0:
ngeo.y -= min(ngeo.y-ndisp.y, over)
ngeo.h = min(ngeo.h, ndisp.h)
if self.DB:
print('over-y:', over)
# all done
self.ngeo = ngeo
if self.DB:
print('ngeo:', vars(self.ngeo))
def do_move(self):
"""Set window info given the planned move"""
# pylint: disable=no-member
win_id = self.win_id
ngeo = self.ngeo
# Execute move command, preserving the states
def wmctrl(win_id, ops):
for op in ops:
cmd = ['wmctrl', '-i', '-R', win_id] + op
subprocess.call(cmd)
# wmctrl is iffy with -b argument (so, specify one state per command)
if self.wm in ('plasma', 'xmate'):
# this kludge to break possible tiled window is per:
# unix.stackexchange.com/questions/353205/wmctrl-doesnt-move-window-when-snapped-or-tiled
wmctrl(win_id, [['-b', 'toggle,' + s] for s in ['maximized_vert', 'maximized_vert']])
wmctrl(win_id, [['-b', 'toggle,' + s] for s in self.states])
x = ngeo.x + (ngeo.rx if self.wm in ('plasma', ) else 0)
y = ngeo.y + (ngeo.ry if self.wm in ('plasma', ) else 0)
w = ngeo.w - ngeo.rx - ngeo.rx
h = ngeo.h - ngeo.ry - ngeo.rx
spec = '0,%d,%d,%d,%d' % (x, y, w, h)
if self.DB:
print('wmctrl:', win_id, '-e', spec, 'states:', self.states)
wmctrl(win_id, [['-e', spec]])
wmctrl(win_id, [['-b', 'toggle,' + s] for s in self.states])
if not self.disable_mouse:
# put mouse in moved window
subprocess.call(['xdotool', 'mousemove',
str(ngeo.x + ngeo.w//2), str(ngeo.y + self.ogeo.ry + 2)])
# ensure on top
subprocess.call(['xdotool', 'windowraise', win_id])
def DB_method(self, func):
""" print method sections for debugging """
# pylint: disable=eval-used
if self.DB:
print('-------', func, '-------')
return eval('self.{}'.format(func))
def go(self):
""" Implement the window move. """
self.DB_method('find_target_window()')
self.DB_method('get_displays()')
self.DB_method('find_relatives()')
self.DB_method('order_displays()')
self.DB_method('get_chosen_window_info()')
if 'fullscreen' not in self.states and self.adjust_panel:
self.DB_method('adjust_displays()')
self.DB_method('pick_new_display()')
self.DB_method('plan_move()')
self.DB_method('do_move()')
@staticmethod
def make_geo(w, h, x, y, rx=0, ry=0, tag=''):
"""Make a geo from its component values (w, h, x, y, ...) to namespace."""
return MoveWin.namespace({'w': w, 'h': h, 'x': x, 'y': y,
'rx': rx, 'ry': ry, 'tag':tag})
@staticmethod
def dup_geo(o, w=None, h=None, x=None, y=None, rx=None, ry=None, tag=None):
"""Copy one 'geo' to another with optional overrides."""
# print('ogeo:', vars(o))
ns = MoveWin.namespace({
'w': o.w if w is None else w,
'h': o.h if h is None else h,
'x': o.x if x is None else x,
'y': o.y if y is None else y,
'tag': o.tag if tag is None else tag,
'rx': o.rx if rx is None else rx,
'ry': o.ry if ry is None else ry})
return ns
@staticmethod
def namespace(avDict=None):
"""
Create a module to be used as generic namespace.
The attribute/values given at creation is extendable. Arguments:
- avDict - dict of name/value pairs to seed the namespace.
Examples
>>> ns = namespace({'a':1,'b':2})
>>> dir(ns)
['a','b']
>>> ns.member = 'value'
>>> vars(ns.member)
{'a': 1, 'b': 2, 'member': 'value'}
"""
# pylint: disable=import-outside-toplevel
import types
ns = types.ModuleType('')
for attr in dir(ns):
delattr(ns, attr)
if avDict:
if not isinstance(avDict, dict):
raise Exception("namespace(dict) abuse [arg is {}]"
. format(str(type(avDict))))
for attr in avDict:
setattr(ns, attr, avDict[attr])
return ns
if __name__ == "__main__":
MoveWin(MoveWin.parse_args()).go()