Blog: Grid-based Tiling Window Management: quicktile

File quicktile, 20.7 KB (added by retracile, 20 months ago)

quicktile

Line 
1#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3import sys
4import os
5import subprocess
6import argparse
7import re
8import time
9import traceback
10from collections import namedtuple
11
12ENABLE_LOGGING = False
13
14# In the face of multiple screens with wildly different resolutions, there are
15# essentially two ways to approach the 'grid size'.
16# One is to take each screen and divide it into the same number of parts; so
17# you have a laptop screen, and it gets divided into a 4x4 gride, and you have
18# a 4K monitor, and it gets divided into a 4x4 grid.  This gives you the same
19# size grid on both screens.
20# The other is to divide the laptop screen into a 2x2 grid, and the 4K monitor
21# into a 4x4 grid; this gives you similar size grid _cells_ on both screens.
22# On my laptop monitor, I find a 4x4 grid to be awkwardly small.  So I think
23# aiming for similar sized grid cells is going to be the better approach.  But
24# then again, I could see a 3x3 grid on the laptop being reasonable, and is a
25# significant improvement in flexibility.
26#
27# So.  I think this boils down to 'we need a configuration file'... though I'm
28# not seeing a nice clean way to configure that...
29# screen geometry -> AxB grid
30#
31# We want windows to snap to the grid for their location, and for their size.
32# And we don't want windows to straddle screen boundaries.
33# So... we could generate all possible grid entities, then search them to find
34# the best target.
35
36# Eventually, I'll move this to a configuration file, likely YAML, but since
37# it's still in flux, just keep it here.
38# I might want to support doing a 3x3 grid when it's the laptop screen only,
39# but a 2x2 grid when it's with the 4k monitor
40CONFIG = {
41    'screen-grids': {
42        # For a given screen, what grid to chop it into
43        (1920, 1080): (2, 2), # Full HD
44        (3840, 2160): (4, 4), # 4K UHD
45    }
46}
47
48
49if ENABLE_LOGGING:
50    LOG_FILE = open(os.path.expanduser('~/quicktile.log'), 'a')
51    def LOG(message):
52        message = message.rstrip()
53        LOG_FILE.write("%s: %s\n" % (time.asctime(), message))
54        LOG_FILE.flush()
55else:
56    def LOG(message):
57        pass
58
59
60def get_active_window_id():
61    """gives the window ID of the currently active window"""
62    task = subprocess.Popen(['xdotool', 'getactivewindow'], stdout=subprocess.PIPE)
63    stdout, stderr = task.communicate()
64    return int(stdout)
65
66
67class Point(namedtuple('Point', ('X', 'Y'))):
68    def distance_squared(self, other):
69        return (self.X-other.X)**2 + (self.Y-other.Y)**2
70
71    def __repr__(self):
72        return "P(%s,%s)" % (self.X, self.Y)
73
74    def __add__(self, other):
75        summed = [s+o for s, o in zip(self, other)]
76        return Point(*summed)
77
78    def __sub__(self, other):
79        diff = [s-o for s, o in zip(self, other)]
80        return Point(*diff)
81
82    def __mul__(self, factor):
83        mul = [s * factor for s in self]
84        return Point(*mul)
85
86    def __rmul__(self, factor):
87        return self * factor
88
89
90class Geometry(namedtuple('Geometry', ('X', 'Y', 'W', 'H'))):
91    def distance_squared(self, other):
92        return (self.X-other.X)**2 + (self.Y-other.Y)**2
93
94    def location_difference_squared(self, other):
95        return (self.X-other.X)**2 + (self.Y-other.Y)**2
96
97    def size_difference_squared(self, other):
98        return (self.W-other.W)**2 + (self.H-other.H)**2
99
100    def location_size_difference_squared(self, other):
101        return (self.location_difference_squared(other), self.size_difference_squared(other))
102
103    def size_location_difference_squared(self, other):
104        """size is more important than distance"""
105        return (self.size_difference_squared(other), self.location_difference_squared(other))
106
107    def difference_squared(self, other):
108        """returns square of distance between centers plus square of difference in size
109        """
110        return self.center().distance_squared(other.center()) + self.size_difference_squared(other)
111
112    def __repr__(self):
113        return "G(%s,%s,%s,%s)" % (self.X, self.Y, self.W, self.H)
114
115    def __add__(self, other):
116        summed = [s+o for s, o in zip(self, other)]
117        return Geometry(*summed)
118
119    def __sub__(self, other):
120        diff = [s-o for s, o in zip(self, other)]
121        return Geometry(*diff)
122
123    def __mul__(self, factor):
124        mul = [s * factor for s in self]
125        return Geometry(*mul)
126
127    def __rmul__(self, factor):
128        return self * factor
129
130    def nw(self):
131        return Point(self.X, self.Y)
132
133    def se(self):
134        return Point(self.X+self.W, self.Y+self.H)
135
136    def center(self):
137        return Point(self.X+self.W//2, self.Y+self.H//2)
138
139    def left_center(self):
140        return Point(self.X, self.Y + self.H // 2)
141
142    def right_center(self):
143        return Point(self.X + self.W, self.Y + self.H // 2)
144
145    def top_center(self):
146        return Point(self.X + self.W // 2, self.Y)
147
148    def bottom_center(self):
149        return Point(self.X + self.W // 2, self.Y + self.H)
150
151
152class Window(object):
153    def __init__(self, id, desktop, X, Y, W, H, client, title):
154        self.id = int(id, 16)
155        self.desktop = int(desktop, 10)
156        self.X = int(X, 10)
157        self.Y = int(Y, 10)
158        self.W = int(W, 10)
159        self.H = int(H, 10)
160        self.client = client
161        self.title = title
162
163    def _geometry_frame_offset(self):
164        """Returns a Geometry for adjusting for the window frame.
165        """
166        # Normal maximized:
167        #_KDE_NET_WM_FRAME_STRUT(CARDINAL) = 0, 0, 24, 0
168        #_NET_FRAME_EXTENTS(CARDINAL) = 0, 0, 24, 0
169        # Not maximized:
170        #_KDE_NET_WM_FRAME_STRUT(CARDINAL) = 4, 4, 28, 4
171        #_NET_FRAME_EXTENTS(CARDINAL) = 4, 4, 28, 4
172        # left border, right border, title bar, bottom border
173        task = subprocess.Popen(['xprop', '-id', str(self.id), '_NET_FRAME_EXTENTS'], stdout=subprocess.PIPE)
174        stdout, stderr = task.communicate()
175        left_border, right_border, title_bar, bottom_border = [int(v, 10) for v in stdout.decode().split('=')[-1].strip().split(', ')]
176        return Geometry(-left_border, -title_bar, left_border+right_border, title_bar+bottom_border)
177
178    def set_geometry(self, geometry):
179        """Place a window at the given geometry, adjusting for window manager offsets.
180        """
181        orig_geometry = self.geometry()
182        if geometry == orig_geometry: # Avoid work if it's already where we want it
183            LOG( "Geometry already at %s" % (geometry, ))
184        else:
185            LOG( "Setting geometry to %s" % (geometry, ))
186            # NOTE: If the window is maximized, the xdotool will not be able to
187            # move/resize the window, and will hang for 15 seconds.
188
189            # We can detect a normal, maximized window:
190            # _NET_WM_STATE(ATOM) =  _NET_WM_STATE_MAXIMIZED_VERT, _NET_WM_STATE_MAXIMIZED_HORZ
191            # Windows can have just one of those set, so we detect either
192            task = subprocess.Popen(['xprop', '-id', str(self.id), '_NET_WM_STATE'], stdout=subprocess.PIPE)
193            stdout, stderr = task.communicate()
194            flags = set(stdout.decode().split('=')[-1].strip().split(', '))
195            LOG("flags=%r" % flags)
196            if flags.intersection(('_NET_WM_STATE_MAXIMIZED_VERT', '_NET_WM_STATE_MAXIMIZED_HORZ')):
197                LOG("DETECTED MAXIMIZED WINDOW")
198                subprocess.check_call(['wmctrl', '-i', '-r', hex(self.id), '-b', 'remove,maximized_vert,maximized_horz'])
199                time.sleep(0.10) # Give it a (longer) moment to resize
200            # But KDE's "Quick Tile" feature does not set anything that xprop
201            # displays, so it won't detect windows that have been "quick tiled".
202
203            frame_offset = self._geometry_frame_offset()
204            LOG("frame_offset=%s" % (frame_offset,))
205            offset_geometry = geometry - frame_offset
206            # offset_geometry does not include the frame
207            if self.client != 'N/A': # Bug workaround
208                # For windows that have the hostname as the client instead of
209                # 'N/A', when we set the geometry we have to provide the NW
210                # corner _including_ the frame, but the width and height
211                # _without_ the frame.
212                offset_geometry += Geometry(frame_offset.X, frame_offset.Y, 0, 0)
213            LOG("frame_offset fixup=%s" % (frame_offset,))
214            self._set_geometry(offset_geometry)
215            new_geometry = self.get_geometry()
216            if new_geometry == orig_geometry:
217                # It didn't move.  One of the ways this can happen is when KDE's
218                # native quick tiling or maximizing is in use on a window.
219                LOG( "Geometry unchanged; attempting to unmaximize")
220                self.unmaximize()
221                self._set_geometry(offset_geometry)
222                new_geometry = self.get_geometry()
223            if new_geometry != geometry: # The window manager is being a real pain
224                LOG( "\007Failed to set geometry to %s using %s; wound up with %s instead" % (geometry, offset_geometry, new_geometry))
225
226    def _set_geometry(self, geometry):
227        """Directly calls an xdotool command to size and move the window to the given coordinates.
228        """
229        # Move vs size order matters.  If shrinking, size then move.  If growing, move then size.
230        if geometry.W > self.geometry().W or geometry.H > self.geometry().H: # Growing
231            cmd = ['xdotool', 'windowmove', '--sync', str(self.id), str(geometry.X), str(geometry.Y), 'windowsize', '--sync', str(self.id), str(geometry.W), str(geometry.H)]
232        else: # Shrinking
233            cmd = ['xdotool', 'windowsize', '--sync', str(self.id), str(geometry.W), str(geometry.H), 'windowmove', '--sync', str(self.id), str(geometry.X), str(geometry.Y)]
234        start = time.time()
235        subprocess.check_call(cmd)
236        end = time.time()
237        if end-start > 1:
238            LOG("\007_set_geometry took %0.2fs" % (end-start))
239        time.sleep(0.05) # Without this sleep, xdotool will _sometimes_ fail to set the geometry.
240
241    def geometry(self):
242        return self._get_geometry() + self._geometry_frame_offset()
243
244    def get_geometry(self):
245        return self.geometry()
246
247    def _get_geometry(self):
248        task = subprocess.Popen(['xdotool', 'getwindowgeometry', str(self.id)], stdout=subprocess.PIPE)
249        stdout, stderr = task.communicate()
250        geoRE = re.compile('Window .*Position: (?P<X>-?[0-9]+),(?P<Y>-?[0-9]+) .*Geometry: (?P<W>[0-9]+)x(?P<H>[0-9]+)', re.DOTALL)
251        match = geoRE.match(stdout.decode('utf-8'))
252        result = dict((k, int(v)) for k, v in match.groupdict().items())
253        return Geometry(**result)
254
255    def unmaximize(self):
256        # Removing maximization is not sufficient; we have to add it and then
257        # remove it to get it to un-maximize.  Has the annoying side effect
258        # when a window is 'KDE quicktiled' to a half or quarter of the screen
259        # of maximizing the window for a brief flash before resizing to the
260        # desired size.
261        subprocess.check_call(['wmctrl', '-i', '-r', hex(self.id), '-b', 'add,maximized_vert,maximized_horz'])
262        subprocess.check_call(['wmctrl', '-i', '-r', hex(self.id), '-b', 'remove,maximized_vert,maximized_horz'])
263        time.sleep(0.05)
264
265    def __repr__(self):
266        return 'W(%s,%s,%s,%s,%s,%s,%s,%s)' % (self.id, self.desktop, self.X, self.Y, self.W, self.H, self.client, self.title)
267
268
269def get_current_windows():
270    task = subprocess.Popen(['wmctrl', '-l', '-G'], stdout=subprocess.PIPE)
271    stdout, stderr = task.communicate()
272    entry = re.compile('(?P<id>0x[0-9a-f]{8})\\s+(?P<desktop>[-0-9]+)\\s+'
273        '(?P<X>-?[0-9]+)\\s+'
274        '(?P<Y>-?[0-9]+)\\s+'
275        '(?P<W>[0-9]+)\\s+'
276        '(?P<H>[0-9]+)\\s+'
277        '(?P<client>[^ ]+)\\s(?P<title>.*)', re.M)
278    windows = []
279    for line in stdout.splitlines():
280        match = entry.match(line.decode('utf-8'))
281        if not match:
282            raise Exception("Failed to parse %r" % line)
283        windows.append(Window(**match.groupdict()))
284    return windows
285
286
287class Controller(object):
288    def __init__(self):
289        """Where grid is the number of cells in each direction on each desktop.
290        KDE's default quick tiling is equivalent to grid=2.
291        """
292        self.query_window_manager()
293        self._calculate_geometries()
294
295    def query_window_manager(self):
296        self.current_windows = get_current_windows()
297        self.windows_by_id = dict((w.id, w) for w in self.current_windows)
298        self.active = get_active_window_id()
299
300    def _generate_grid_cells_for_desktop(self, geometry, grid_x, grid_y):
301        """Returns a set of Geometry objects for all possible grid placements
302        on the given geometry, when divided into a grid_x-by-grid_y grid.
303        """
304        grid_cells = []
305        for grid_left in range(grid_x):
306            for grid_right in range(grid_left, grid_x):
307                for grid_top in range(grid_y):
308                    for grid_bottom in range(grid_top, grid_y):
309                        left = geometry.X + geometry.W * grid_left // grid_x
310                        right = geometry.X + geometry.W * (grid_right+1) // grid_x
311                        top = geometry.Y + geometry.H * grid_top // grid_y
312                        bottom = geometry.Y + geometry.H * (grid_bottom+1) // grid_y
313                        width = right - left
314                        height = bottom - top
315                        grid = Geometry(X=left,
316                                        Y=top,
317                                        W=width,
318                                        H=height)
319                        grid_cells.append(grid)
320        return grid_cells
321
322    def _splits_for_screen_size(self, width, height):
323        _, closest = min(((width-w)**2 + (height-h)**2, (w, h)) for w, h in CONFIG['screen-grids'].keys())
324        splits = CONFIG['screen-grids'].get(closest)
325        if not splits:
326            splits = (2, 2)
327            LOG("No split info found for %sx%s screen, defaulting to %sx%s" % (width, height, splits[0], splits[1]))
328        return splits
329
330    def _calculate_geometries(self):
331        self.plasma_windows = [w for w in self.current_windows if w.desktop == -1]
332        menubar = [w for w in self.plasma_windows if w.title == 'Plasma'][0]
333        desktops = [w for w in self.plasma_windows if w.title.startswith('Desktop')]
334        # KDE's logic for moving windows into a given location seems to think
335        # that the menubar is on all desktops, and will refuse to move a window
336        # down far enough to cover it, and will move the window if it is
337        # resized enough to cover it.
338        if False:
339            # For now, I'm going to assume the menu bar is on the bottom of the screen.
340            menubar_desktop = [w for w in desktops if w.X == menubar.X][0]
341            other_desktops = [w for w in desktops if w != menubar_desktop]
342            self.desktop_geometries = [
343                Geometry(menubar_desktop.X, menubar_desktop.Y, menubar_desktop.W, menubar_desktop.H-menubar.H),
344            ]
345            self.desktop_geometries.extend(Geometry(w.X, w.Y, w.W, w.H) for w in other_desktops)
346        else:
347            # So we're going to simply give up on the bottom 28px of the non-menubar screen, and act like it exists on all screens
348            self.desktop_geometries = [Geometry(d.X, d.Y, d.W, d.H-menubar.H) for d in desktops]
349        #LOG("Desktop geometries: %s\n" % self.desktop_geometries) # DEBUG
350
351        self.grid_tiles = []
352        for desktop_geometry in self.desktop_geometries:
353            x_splits, y_splits = self._splits_for_screen_size(desktop_geometry.W, desktop_geometry.H)
354            self.grid_tiles.extend(self._generate_grid_cells_for_desktop(desktop_geometry, x_splits, y_splits))
355        #LOG("GRID_TILES: %s" % self.grid_tiles) # DEBUG
356
357    def active_window(self):
358        return self.windows_by_id[self.active]
359
360    def window_action(self, action, direction):
361        window = self.active_window()
362        original_window_geometry = window.geometry()
363        LOG("Starting geometry = %s" % (original_window_geometry, ))
364        _, window_geometry = min([(original_window_geometry.location_size_difference_squared(g), g) for g in self.grid_tiles])
365        LOG("Snapped geometry = %s" % (window_geometry, ))
366        # Need to figure out the window's nearest grid-granular size
367        command = (action, direction)
368        # Move
369        # Only consider cells that overlap the area directly in the direction
370        # of the desired motion.  This means that a window at the top of one
371        # screen, when pushed up, won't move horizontally to another screen
372        # that is 'higher'.
373        if command == ('move', 'left'):
374            grids = [(window_geometry.right_center().distance_squared(g.right_center()) + window_geometry.size_difference_squared(g), g)
375                for g in self.grid_tiles if g.nw().X < window_geometry.nw().X and g.se().X < window_geometry.se().X
376                    and g.nw().Y < window_geometry.se().Y and g.se().Y > window_geometry.nw().Y]
377        elif command == ('move', 'right'):
378            grids = [(window_geometry.left_center().distance_squared(g.left_center()) + window_geometry.size_difference_squared(g), g)
379                for g in self.grid_tiles if g.nw().X > window_geometry.nw().X and g.se().X > window_geometry.se().X
380                    and g.nw().Y < window_geometry.se().Y and g.se().Y > window_geometry.nw().Y]
381        elif command == ('move', 'up'):
382            grids = [(window_geometry.bottom_center().distance_squared(g.bottom_center()) + window_geometry.size_difference_squared(g), g)
383                for g in self.grid_tiles if g.nw().Y < window_geometry.nw().Y and g.se().Y < window_geometry.se().Y
384                    and g.nw().X < window_geometry.se().X and g.se().X > window_geometry.nw().X]
385        elif command == ('move', 'down'):
386            grids = [(window_geometry.top_center().distance_squared(g.top_center()) + window_geometry.size_difference_squared(g), g)
387                for g in self.grid_tiles if g.nw().Y > window_geometry.nw().Y and g.se().Y > window_geometry.se().Y
388                    and g.nw().X < window_geometry.se().X and g.se().X > window_geometry.nw().X]
389        # Grow
390        elif command == ('grow', 'left'):
391            grids = [(window_geometry.X - g.X, g) for g in self.grid_tiles if g.H == window_geometry.H and g.W > window_geometry.W and g.se() == window_geometry.se()]
392        elif command == ('grow', 'right'):
393            grids = [(g.se().X - window_geometry.se().X, g) for g in self.grid_tiles if g.H == window_geometry.H and g.W > window_geometry.W and g.nw() == window_geometry.nw()]
394        elif command == ('grow', 'up'):
395            grids = [(window_geometry.Y - g.Y, g) for g in self.grid_tiles if g.H > window_geometry.H and g.W == window_geometry.W and g.se() == window_geometry.se()]
396        elif command == ('grow', 'down'):
397            grids = [(g.se().Y - window_geometry.se().Y, g) for g in self.grid_tiles if g.H > window_geometry.H and g.W == window_geometry.W and g.nw() == window_geometry.nw()]
398        # Shrink
399        elif command == ('shrink', 'left'):
400            grids = [(window_geometry.se().X - g.se().X, g) for g in self.grid_tiles if g.H == window_geometry.H and g.W < window_geometry.W and g.nw() == window_geometry.nw()]
401        elif command == ('shrink', 'right'):
402            grids = [(g.X - window_geometry.X, g) for g in self.grid_tiles if g.H == window_geometry.H and g.W < window_geometry.W and g.se() == window_geometry.se()]
403        elif command == ('shrink', 'up'):
404            grids = [(window_geometry.se().Y - g.se().Y, g) for g in self.grid_tiles if g.H < window_geometry.H and g.W == window_geometry.W and g.nw() == window_geometry.nw()]
405        elif command == ('shrink', 'down'):
406            grids = [(g.Y - window_geometry.Y, g) for g in self.grid_tiles if g.H < window_geometry.H and g.W == window_geometry.W and g.se() == window_geometry.se()]
407        # Snap
408        elif command == ('snap', 'here'):
409            grids = [(window_geometry.location_size_difference_squared(g), g) for g in self.grid_tiles]
410        else:
411            raise Exception("Bad command %s %s" % (action, direction))
412
413        if not grids:
414            LOG("No target identified, finding closest tile.")
415            grids = [(window_geometry.difference_squared(g), g) for g in self.grid_tiles]
416        else:
417            LOG("Sorted qualified grids: %s" % sorted(grids))
418        _difference, grid = min(grids)
419        window.set_geometry(grid)
420
421
422def main(argv):
423    parser = argparse.ArgumentParser()
424    parser.add_argument('action', choices=['move', 'grow', 'shrink', 'snap'])
425    parser.add_argument('direction', choices=['left', 'right', 'up', 'down', 'here'])
426    args = parser.parse_args(argv[1:])
427
428    LOG("start %s %s" % (args.action, args.direction))
429    try:
430        controller = Controller()
431        controller.window_action(args.action, args.direction)
432    except Exception as error:
433        LOG("ERROR: %s" % error)
434        LOG(traceback.format_exc())
435        raise
436    LOG("end %s %s" % (args.action, args.direction))
437
438    return 0
439
440
441if __name__ == '__main__':
442    sys.exit(main(sys.argv))