-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathxpytile.py
executable file
·1986 lines (1681 loc) · 87.2 KB
/
xpytile.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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
X-tiling helper
with simultaneous resizing of docked (side-by-side) windows
Copyright (C) 2021 jaywilkas <just4 [period] gmail [at] web [period] de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import configparser
import datetime
from functools import lru_cache
import os
import re
import shutil
import socket
import subprocess
import sys
import time
import Xlib.display, Xlib.XK, Xlib.error, Xlib.protocol
# ----------------------------------------------------------------------------------------------------------------------
class _list(object):
"""
Very simple "auto-expanding list like" - class
Purpose: Easily handle desktop-specific tilingInfo when there are more desktops
than the number of configured desktop-specfic entries (for example
when the number of desktops get increased at runtime).
"""
def __init__(self, args=[]):
self._list = args
self.default_value = None
def expand(self, i):
if self.default_value is None and len(self._list):
self.default_value = self._list[0]
for n in range(len(self._list), i + 1):
self._list.append(self.default_value)
def __getitem__(self, i):
if i >= len(self._list):
self.expand(i)
return self._list[i]
def __setitem__(self, i, val):
if i >= len(self._list):
self.expand(i - 1)
self._list[i] = val
def append(self, val):
self._list.append(val)
def set_default(self, val):
self.default_value = val
def __str__(self):
return str(self._list)
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def change_num_max_windows_by(deltaNum):
"""
Change the max number of windows to tile (limited between minimal 2 and maximal 9 windows)
:param deltaNum: increment number of max windows by this value
:return:
"""
global Xroot, NET_CURRENT_DESKTOP, ANY_PROPERTYTYPE
currentDesktop = Xroot.get_full_property(NET_CURRENT_DESKTOP, ANY_PROPERTYTYPE).value[0]
tilerNumber = tilingInfo['tiler'][currentDesktop]
tilerNames_dict = {1: 'masterAndStackVertic', 2: 'vertically', 3: 'masterAndStackHoriz', 4: 'horizontally'}
try:
tilerName = tilerNames_dict[tilerNumber]
except KeyError:
return
tilingInfo[tilerName]['maxNumWindows'] = min(max(tilingInfo[tilerName]['maxNumWindows'] + deltaNum, 2), 9)
notify(tilingInfo[tilerName]['maxNumWindows'])
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def cycle_windows():
"""
Cycles all -not minimized- windows of the current desktop
:return:
"""
global disp, Xroot, NET_CURRENT_DESKTOP, ANY_PROPERTYTYPE
# get a list of all -not minimized and not ignored- windows of the current desktop
currentDesktop = Xroot.get_full_property(NET_CURRENT_DESKTOP, ANY_PROPERTYTYPE).value[0]
winIDs = get_windows_on_desktop(currentDesktop)
if len(winIDs) < 2:
return
for i, winID in enumerate(winIDs):
try:
winID_next = winIDs[i + 1]
except IndexError as e:
winID_next = winIDs[0]
set_window_position(winID, x=windowsInfo[winID_next]['x'], y=windowsInfo[winID_next]['y'])
set_window_size(winID, width=windowsInfo[winID_next]['width'], height=windowsInfo[winID_next]['height'])
disp.sync()
update_windows_info()
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def get_moved_border(winID, window):
"""
Return which border(s) of the window have been moved
:param winID: ID of the window
:param window: window
:return: a number that indicates which window edges got shifted
"""
global windowsInfo
moved_border = 0
try:
winInfo = windowsInfo[winID]
geometry = get_window_geometry(window)
if geometry is None: # window vanished
return moved_border
except KeyError:
return moved_border
if winInfo['x'] != geometry.x:
moved_border += 1 # left border
if winInfo['y'] != geometry.y:
moved_border += 2 # upper border
if winInfo['x2'] != geometry.x + geometry.width - 1:
moved_border += 4 # right border
if winInfo['y2'] != geometry.y + geometry.height - 1:
moved_border += 8 # lower border
return moved_border
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def get_parent_window(window):
"""
Thanks to this post: stackoverflow.com/questions/60141048/
Because an X window is not necessarily just what one thinks of
as a window (the window manager may add an invisible frame, and
so on), we record not just the active window but its ancestors
up to the root, and treat a ConfigureNotify on any of those
ancestors as meaning that the active window has been moved or resized.
:param window: window
:return: parent window
"""
try:
pointer = window
while pointer.id != Xroot.id:
parentWindow = pointer
pointer = pointer.query_tree().parent
return parentWindow
except:
return None # window vanished
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def get_window_geometry(win):
"""
Return the geometry of the top most parent window.
See the comment in get_active_window_and_ancestors()
:param win: window
:return: geometry of the top most parent window
"""
try:
return get_parent_window(win).get_geometry()
except:
return None # window vanished
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def get_windows_name(winID, window):
"""
Get the application name of the window.
Tries at first to find the name in the windowsInfo structure.
If the winID is not yet known, get_wm_class() gets called.
:param winID: ID of the window
:param window: window
:return: name of the window / application
"""
global windowsInfo
try:
name = windowsInfo[winID]['name']
except KeyError:
try:
wmclass, name = window.get_wm_class()
except (TypeError, KeyError, Xlib.error.BadWindow):
name = "UNKNOWN"
return name
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def get_windows_on_desktop(desktop):
"""
Return a list of window-IDs of all -not minimized and not sticky-
windows from our list on the given desktop
:param desktop: number of desktop
:return: list of window-IDs
"""
global windowsInfo, NET_WM_STATE_HIDDEN, NET_WM_STATE_STICKY
winIDs = list()
for winID, winInfo in windowsInfo.items():
try:
if winInfo['desktop'] == desktop:
propertyList = windowsInfo[winID]['win'].get_full_property(NET_WM_STATE, 0).value.tolist()
if NET_WM_STATE_STICKY not in propertyList and NET_WM_STATE_HIDDEN not in propertyList:
winIDs.append(winID)
except Xlib.error.BadWindow:
pass # window vanished
return winIDs
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
@lru_cache
def get_windows_title(window):
"""
Get the title of the window.
:param window: window
:return: title of the window / application
"""
global NET_WM_NAME
try:
title = window.get_full_property(NET_WM_NAME, 0).value
if isinstance(title, bytes):
title = title.decode('UTF8', 'replace')
except:
title = '<unnamed?>'
return title
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def handle_key_event(keyCode, windowID_active, window_active):
"""
Perform the action associated with the hotkey
:param keyCode: The code of the pressed (to be precise: released) hotkey
:param windowID_active: ID of active window
:param window_active: active window
:return: windowID_active, window_active
"""
global hotkeys, tilingInfo, windowsInfo, disp
if keyCode == hotkeys['toggleresize']:
toggle_resize()
elif keyCode == hotkeys['toggletiling']:
if toggle_tiling():
update_windows_info()
tile_windows(window_active)
elif keyCode == hotkeys['toggleresizeandtiling']:
toggle_resize()
if toggle_tiling():
update_windows_info()
tile_windows(window_active)
elif keyCode == hotkeys['toggledecoration']:
toggle_window_decoration()
elif keyCode == hotkeys['enlargemaster']:
tile_windows(window_active, resizeMaster=tilingInfo['stepSize'])
elif keyCode == hotkeys['shrinkmaster']:
tile_windows(window_active, resizeMaster=-tilingInfo['stepSize'])
elif keyCode == hotkeys['togglemaximizewhenonewindowleft']:
toggle_maximize_when_one_window()
elif keyCode == hotkeys['cyclewindows']:
update_windows_info()
cycle_windows()
elif keyCode == hotkeys['cycletiler']:
update_windows_info()
tile_windows(window_active, manuallyTriggered=True, tilerNumber='next')
elif keyCode == hotkeys['swapwindows']:
update_windows_info()
swap_windows(windowID_active)
elif keyCode == hotkeys['tilemasterandstackvertically']:
update_windows_info()
tile_windows(window_active, manuallyTriggered=True, tilerNumber=1)
elif keyCode == hotkeys['tilevertically']:
update_windows_info()
tile_windows(window_active, manuallyTriggered=True, tilerNumber=2)
elif keyCode == hotkeys['tilemasterandstackhorizontally']:
update_windows_info()
tile_windows(window_active, manuallyTriggered=True, tilerNumber=3)
elif keyCode == hotkeys['tilehorizontally']:
update_windows_info()
tile_windows(window_active, manuallyTriggered=True, tilerNumber=4)
elif keyCode == hotkeys['tilemaximize']:
update_windows_info()
tile_windows(window_active, manuallyTriggered=True, tilerNumber=5)
elif keyCode == hotkeys['increasemaxnumwindows']:
change_num_max_windows_by(1)
update_windows_info()
tile_windows(window_active)
elif keyCode == hotkeys['decreasemaxnumwindows']:
change_num_max_windows_by(-1)
update_windows_info()
tile_windows(window_active)
elif keyCode == hotkeys['recreatewindowslayout']:
recreate_window_geometries()
elif keyCode == hotkeys['storecurrentwindowslayout']:
update_windows_info()
store_window_geometries()
elif keyCode == hotkeys['logactivewindow']:
log_active_window(windowID_active, window_active)
elif keyCode == hotkeys['focusup']:
windowID_active, window_active = set_window_focus(windowID_active, window_active, 'up')
elif keyCode == hotkeys['focusdown']:
windowID_active, window_active = set_window_focus(windowID_active, window_active, 'down')
elif keyCode == hotkeys['focusleft']:
windowID_active, window_active = set_window_focus(windowID_active, window_active, 'left')
elif keyCode == hotkeys['focusright']:
windowID_active, window_active = set_window_focus(windowID_active, window_active, 'right')
elif keyCode == hotkeys['focusprevious']:
windowID_active, window_active = set_window_focus_to_previous(windowID_active, window_active)
elif keyCode == hotkeys['togglegroup0']: # handling groups of windows is under development
toggle_group(windowID_active, 0)
elif keyCode == hotkeys['showgroup0']:
windowID_active, window_active = show_group(0)
elif keyCode == hotkeys['togglegroup1']:
toggle_group(windowID_active, 1)
elif keyCode == hotkeys['showgroup1']:
windowID_active, window_active = show_group(1)
elif keyCode == hotkeys['exit']:
# On exit, make sure all windows are decorated
update_windows_info()
for winID in windowsInfo:
set_window_decoration(winID, True)
disp.sync()
notify('exit')
quit()
return windowID_active, window_active
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def toggle_group(windowID_active, group):
# handling groups of windows is under development
global windowsInfo
if group in windowsInfo[windowID_active]['groups']:
windowsInfo[windowID_active]['groups'].remove(group)
else:
windowsInfo[windowID_active]['groups'].append(group)
#windowID_active, window_active = show_group(group)
print(windowsInfo[windowID_active]['name'], windowsInfo[windowID_active]['groups'])
#return windowID_active, window_active
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def show_group(group):
global windowsInfo, disp, Xroot, NET_CURRENT_DESKTOP, ANY_PROPERTYTYPE
currentDesktop = Xroot.get_full_property(NET_CURRENT_DESKTOP, ANY_PROPERTYTYPE).value[0]
for winID, winInfo in windowsInfo.items():
try:
if winInfo['desktop'] == currentDesktop:
propertyList = winInfo['win'].get_full_property(NET_WM_STATE, 0).value.tolist()
if NET_WM_STATE_STICKY not in propertyList:
if group in winInfo['groups']:
set_window_minimized_state(winInfo['win'], 0)
print(winInfo['name'], 0)
else:
set_window_minimized_state(winInfo['win'], 1)
print(winInfo['name'], 1)
except Xlib.error.BadWindow:
pass # window vanished
time.sleep(0.2)
window_active = disp.get_input_focus().focus
tile_windows(window_active, manuallyTriggered=True)
windowID_active = Xroot.get_full_property(NET_ACTIVE_WINDOW, ANY_PROPERTYTYPE).value[0]
return windowID_active, window_active
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def handle_remote_control_event(event, windowID_active, window_active):
"""
Perform the action associated with the command-number, given in the event details
:param event: The remote control event
:param windowID_active: ID of active window
:param window_active: active window
:return: windowID_active, window_active
"""
cmdNum = event._data['data'][1].tolist()[0]
cmdList= ('toggleresize', 'toggletiling', # 0, 1
'toggleresizeandtiling', 'togglemaximizewhenonewindowleft', # 2, 3
'toggledecoration', 'cyclewindows', # 4, 5
'cycletiler', 'swapwindows', # 6, 7
'storecurrentwindowslayout', 'recreatewindowslayout', # 8, 9
'tilemasterandstackvertically', 'tilevertically', # 10, 11
'tilemasterandstackhorizontally', 'tilehorizontally', # 12, 13
'tilemaximize', 'increasemaxnumwindows', # 14, 15
'decreasemaxnumwindows', 'exit', # 16, 17
'logactivewindow', 'shrinkmaster', # 18, 19
'enlargemaster', 'focusleft', # 20, 21
'focusright', 'focusup', # 22, 23
'focusdown', 'focusprevious', # 24, 25
'togglegroup0', 'showgroup0', # 26, 27
'togglegroup1', 'showgroup1') # 28, 29
cmd = cmdList[cmdNum]
# simply re-use function handle_key_event() here
try:
keyCode = hotkeys[cmd]
windowID_active, window_active = handle_key_event(keyCode, windowID_active, window_active)
except IndexError:
pass
return windowID_active, window_active
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def hightlight_mouse_cursor():
"""
Highlight mouse cursor, by hiding/showing several times
:return:
"""
global disp, Xroot
if not disp.has_extension('XFIXES') or disp.query_extension('XFIXES') is None:
return
disp.xfixes_query_version()
for i in range(3):
if i != 0:
time.sleep(0.05)
Xroot.xfixes_hide_cursor()
disp.sync()
time.sleep(0.05)
Xroot.xfixes_show_cursor()
disp.sync()
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def init(configFile='~/.config/xpytilerc'):
"""
Initialization
configFile: file-path of the config-file
:return: window_active, window_active_parent, windowID_active
"""
global disp, Xroot, screen
global windowsInfo
global NET_ACTIVE_WINDOW, NET_WM_DESKTOP, NET_CLIENT_LIST, NET_CURRENT_DESKTOP, NET_WM_STATE_MAXIMIZED_VERT
global NET_WM_STATE_MAXIMIZED_HORZ, NET_WM_STATE, NET_WM_STATE_HIDDEN, NET_WORKAREA, NET_WM_NAME, NET_WM_STATE_MODAL
global NET_WM_STATE_STICKY, MOTIF_WM_HINTS, ANY_PROPERTYTYPE, GTK_FRAME_EXTENTS
global XPYTILE_REMOTE
disp = Xlib.display.Display()
screen = disp.screen()
Xroot = screen.root
NET_ACTIVE_WINDOW = disp.get_atom('_NET_ACTIVE_WINDOW')
NET_WM_DESKTOP = disp.get_atom('_NET_WM_DESKTOP')
NET_CLIENT_LIST = disp.get_atom('_NET_CLIENT_LIST')
NET_CURRENT_DESKTOP = disp.get_atom('_NET_CURRENT_DESKTOP')
NET_WM_STATE_MAXIMIZED_VERT = disp.get_atom('_NET_WM_STATE_MAXIMIZED_VERT')
NET_WM_STATE_MAXIMIZED_HORZ = disp.get_atom('_NET_WM_STATE_MAXIMIZED_HORZ')
NET_WM_STATE = disp.get_atom('_NET_WM_STATE')
NET_WM_STATE_HIDDEN = disp.get_atom('_NET_WM_STATE_HIDDEN')
NET_WM_NAME = disp.get_atom('_NET_WM_NAME')
NET_WORKAREA = disp.get_atom('_NET_WORKAREA')
NET_WM_STATE_MODAL = disp.get_atom('_NET_WM_STATE_MODAL')
NET_WM_STATE_STICKY = disp.get_atom('_NET_WM_STATE_STICKY')
MOTIF_WM_HINTS = disp.get_atom('_MOTIF_WM_HINTS')
GTK_FRAME_EXTENTS = disp.get_atom('_GTK_FRAME_EXTENTS')
ANY_PROPERTYTYPE = Xlib.X.AnyPropertyType
XPYTILE_REMOTE = disp.get_atom('_XPYTILE_REMOTE')
config = configparser.ConfigParser()
config.read(os.path.expanduser(configFile))
init_tiling_info(config)
init_hotkeys_info(config)
init_notification_info(config)
# determine active window and its parent
window_active = disp.get_input_focus().focus
windowID_active = Xroot.get_full_property(NET_ACTIVE_WINDOW, ANY_PROPERTYTYPE).value[0]
window_active_parent = get_parent_window(window_active)
# dictionary to keep track of the windows, their geometry and other information
windowsInfo = dict()
update_windows_info(windowID_active)
# configure event-mask
Xroot.change_attributes(event_mask=Xlib.X.PropertyChangeMask | Xlib.X.SubstructureNotifyMask |
Xlib.X.KeyReleaseMask)
notify('start')
return window_active, window_active_parent, windowID_active
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def init_hotkeys_info(config):
"""
Read hotkey-config, fill hotkeys-dictionary and register key-combinations
:param config: parsed config-file
:return:
"""
global hotkeys, Xroot
modifier = config['Hotkeys'].getint('modifier')
if modifier == -1:
modifier = Xlib.X.AnyModifier
hotkeys = dict()
for item in config.items('Hotkeys'):
if item[0] != 'modifier':
hotkeys[item[0]] = int(item[1])
Xroot.grab_key(int(item[1]), modifier, 1, Xlib.X.GrabModeAsync, Xlib.X.GrabModeAsync)
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def init_notification_info(config):
"""
Create a dict with notification configuration
:param config: parsed config-file
:return:
"""
global notificationInfo
notificationInfo = dict()
for item in config.items('Notification'):
notificationInfo[item[0]] = item[1]
notificationInfo['active'] = notificationInfo['active'] != 'False'
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def init_tiling_info(config):
"""
Initialize the tiling info data structure
:param config: parsed config-file
:return:
"""
global tilingInfo
# ----------------------------------------------------------------------------
def getConfigValue(config, sectionName, entryName, fallBackValue, type='int'):
try:
if type == 'int':
value = config[sectionName].getint(entryName, fallback=fallBackValue)
elif type == 'float':
value = config[sectionName].getfloat(entryName, fallback=fallBackValue)
elif type == 'bool':
value = config[sectionName].getboolean(entryName, fallback=fallBackValue)
except ValueError:
value = fallBackValue
return value
# ----------------------------------------------------------------------------
def parseConfigIgnoreWindowEntry(entry):
retVal = {'name': None, 'title': None, '!title': None}
strPos_name = strPos_title = None
r = re.search('name: *".*"', entry)
if r: strPos_name = r.span()[0]
r = re.search('!{0,1}title: *".*"', entry)
if r: strPos_title = r.span()[0]
if strPos_name is None and strPos_title is None:
return None
if strPos_name is not None and (strPos_title is None or strPos_title > strPos_name):
if strPos_title is not None:
r = re.match('(name:\s*)(".*")(\s*)(!{0,1}title:\s*)(".*")', entry)
else:
r = re.match('(name:\s*)(".*")', entry)
if r:
retVal['name'] = re.compile(r.group(2)[1:-1])
if strPos_title is not None:
retVal['title'] = re.compile(r.group(5)[1:-1])
retVal['!title'] = not r.group(4).startswith('!')
return retVal
# ----------------------------------------------------------------------------
tilingInfo = dict()
# configured settings that define ...
# ... what windows should be ignored depending on their name and title.
tilingInfo['ignoreWindows'] = list()
for line in config['General']['ignoreWindows'].split('\n'):
entry = parseConfigIgnoreWindowEntry(line)
if entry is not None:
tilingInfo['ignoreWindows'].append(entry)
# ... what windows should be ignored regarding (un)decoratating depending on their name and title.
tilingInfo['ignoreWindowsForDecoration'] = list()
for line in config['General']['ignoreWindowsForDecoration'].split('\n'):
entry = parseConfigIgnoreWindowEntry(line)
if entry is not None:
tilingInfo['ignoreWindowsForDecoration'].append(entry)
# ... which application should be tiled after some delay, depending on their name.
tilingInfo['delayTilingWindowsWithNames'] = list()
for entry in config['General']['delayTilingWindowsWithNames'].split('\n'):
tilingInfo['delayTilingWindowsWithNames'].append(re.compile(entry[1:-1]))
tilingInfo['delayTimeTiling'] = getConfigValue(config, 'General', 'delayTimeTiling', 0.5, 'float')
# ... resize- , tiling- and window-decoration - status for each desktop.
tilingInfo['resizeWindows'] = _list([])
tilingInfo['resizeWindows'].set_default(True)
tilingInfo['tileWindows'] = _list([])
tilingInfo['tileWindows'].set_default(True)
tilingInfo['windowDecoration'] = _list([])
tilingInfo['windowDecoration'].set_default(True)
tilingInfo['tiler'] = _list([])
tilingInfo['tiler'].set_default(getConfigValue(config, 'General', 'defaultTiler', 1))
i = 1
while True:
_temp = getConfigValue(config, 'DefaultTilerPerDesktop', f'Desktop{i}', None)
if _temp is None:
break
tilingInfo['tiler'].append(_temp)
i += 1
tilingInfo['maximizeWhenOneWindowLeft'] = _list([])
_temp = getConfigValue(config, 'General', 'defaultMaximizeWhenOneWindowLeft', True, 'bool')
tilingInfo['maximizeWhenOneWindowLeft'].set_default(_temp)
i = 1
while True:
_temp = getConfigValue(config, 'maximizeWhenOneWindowLeft', f'Desktop{i}', None, 'bool')
if _temp is None:
break
tilingInfo['maximizeWhenOneWindowLeft'].append(_temp)
i += 1
# ... a margin, where edges with a distance smaller than that margin are considered docked.
tilingInfo['margin'] = getConfigValue(config, 'General', 'margin', 100)
# ... a minimal size, so not to shrink width or height of a window smaller than this.
tilingInfo['minSize'] = getConfigValue(config, 'General', 'minSize', 350)
# ... the increment when resizing the master window by hotkey.
tilingInfo['stepSize'] = getConfigValue(config, 'General', 'stepSize', 50)
# ... whether the mouse-cursor should follow a new active window (if selected by hotkey).
tilingInfo['moveMouseIntoActiveWindow'] = \
getConfigValue(config, 'General', 'moveMouseIntoActiveWindow', True, 'bool')
tilingInfo['masterAndStackVertic'] = dict()
tilingInfo['masterAndStackVertic']['maxNumWindows'] = \
getConfigValue(config, 'masterAndStackVertic', 'maxNumWindows', 3)
tilingInfo['masterAndStackVertic']['defaultWidthMaster'] = \
getConfigValue(config, 'masterAndStackVertic', 'defaultWidthMaster', 0.5, 'float')
tilingInfo['horizontally'] = dict()
tilingInfo['horizontally']['maxNumWindows'] = \
getConfigValue(config, 'horizontally', 'maxNumWindows', 3)
tilingInfo['vertically'] = dict()
tilingInfo['vertically']['maxNumWindows'] = \
getConfigValue(config, 'vertically', 'maxNumWindows', 3)
tilingInfo['masterAndStackHoriz'] = dict()
tilingInfo['masterAndStackHoriz']['maxNumWindows'] = \
getConfigValue(config, 'masterAndStackHoriz', 'maxNumWindows', 3)
tilingInfo['masterAndStackHoriz']['defaultHeightMaster'] = \
getConfigValue(config, 'masterAndStackHoriz', 'defaultHeightMaster', 0.5, 'float')
tilingInfo['userDefinedGeom'] = dict()
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def log_active_window(windowID_active, window_active):
"""
Prints the name and the title of the currently active window into a log-file.
The purpose of this function is to easily get the name and title of windows/applications
which should be ignored.
:param windowID_active: ID of active window
:param window_active: active window
:return:
"""
fileName = os.path.join('/tmp', f'xpytile_{os.environ["USER"]}.log')
with open(fileName, 'a') as f:
dateStr = datetime.datetime.strftime(datetime.datetime.now(), '%x %X')
f.write(f'[{dateStr}] name: {get_windows_name(windowID_active, window_active)},'
f' title: {get_windows_title(window_active)}\n')
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def match(compRexExList, string):
"""
Check whether the string matches any of the regexes
:param compRexExList: list of compiled regex-pattern
:param string: string to test
:return:
"""
for r in compRexExList:
if r.match(string):
return True
return False
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def match_ignore(ignoreWindows, name, title):
"""
Checks whether to ignore the window, depending on its name and title
:param ignoreWindows: list of dict, what combinations of name/title should be ignored
:param name: name of the window/application
:param title: title of the window
:return: status whether to ignore the window [True | False]
"""
for e in ignoreWindows:
if e['name'].match(name):
if e['title'] is None:
if verbosityLevel > 1:
print('Ignoring window:\t'
f'name "{name}" matches pattern "{e["name"].pattern}"\t'
f'title is irrelevant')
return True
if bool(e['title'].match(title)) == e['!title']:
if verbosityLevel > 1:
print('Ignoring window:\t'
f'name "{name}" matches pattern "{e["name"].pattern}"\t'
f'{"!" * (not e["!title"])}title "{title}" {("does not match", "matches")[e["!title"]]}'
f'pattern "{e["title"].pattern}"')
return True
return False
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def notify(case, status=None):
"""
Show a notification message (if active)
:param case: The circumstance
:param status: True / False (or None)
:return:
"""
global notificationInfo
if not notificationInfo['active']:
return
if isinstance(case, int):
summary = 'Num win handled'
message = str(case)
iconFilePath = ''
else:
case = case.lower()
if status is not None:
message = [notificationInfo['off_message'], notificationInfo['on_message']][int(status)]
status_str = ['off', 'on'][int(status)]
else:
message = notificationInfo[f'{case}_message']
status_str = ''
iconFilePath = notificationInfo[f'{case}{status_str}_icon']
summary = notificationInfo[f'{case}_summary']
try:
subprocess.Popen(['notify-send', '-t', notificationInfo['time'],
f'--icon={iconFilePath}', summary, message])
except FileNotFoundError as e:
pass
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def recreate_window_geometries():
"""
Re-creates the geometry of all -not minimized- windows of the current desktop
:return:
"""
global tilingInfo, disp, NET_CURRENT_DESKTOP, ANY_PROPERTYTYPE
# get a list of all -not minimized and not ignored- windows on the given desktop
currentDesktop = Xroot.get_full_property(NET_CURRENT_DESKTOP, ANY_PROPERTYTYPE).value[0]
winIDs = get_windows_on_desktop(currentDesktop)
for winID in winIDs:
try:
x = tilingInfo['userDefinedGeom'][currentDesktop][winID]['x']
y = tilingInfo['userDefinedGeom'][currentDesktop][winID]['y']
width = tilingInfo['userDefinedGeom'][currentDesktop][winID]['width']
height = tilingInfo['userDefinedGeom'][currentDesktop][winID]['height']
unmaximize_window(windowsInfo[winID]['win'])
windowsInfo[winID]['win'].set_input_focus(Xlib.X.RevertToParent, Xlib.X.CurrentTime)
windowsInfo[winID]['win'].configure(stack_mode=Xlib.X.Above)
set_window_position(winID, x=x, y=y)
set_window_size(winID, width=width, height=height)
disp.sync()
update_windows_info()
except KeyError:
pass # window is not present anymore (on this desktop)
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def resize_docked_windows(windowID_active, window_active, moved_border):
"""
Resize the side-by-side docked windwows.
The function deliberately retrieves the current window geometry of the active window
rather than using the already existing information of the event structure.
This saves a good amount of redrawing.
:param windowID_active: ID of the active window
:param window_active: active window
:param moved_border: points out which border of the active window got moved
:return:
"""
global disp, tilingInfo, NET_WORKAREA
global windowsInfo # dict with windows and their geometries (before last resize of the active window)
tolerance = 3
if moved_border not in [1, 2, 4, 8]: # 1: left, 2: upper, 4: right, 8: lower
return None
winInfo_active = windowsInfo[windowID_active]
# check whether resizing is active for the desktop of the resized window
desktop = winInfo_active['desktop']
if not tilingInfo['resizeWindows'][desktop]:
return
# geometry of work area (screen without taskbar)
workAreaWidth, workAreaHeight = Xroot.get_full_property(NET_WORKAREA, 0).value.tolist()[2:4]
for winID, winInfo in windowsInfo.items():
if winID == windowID_active or winInfo['desktop'] != desktop:
continue
if moved_border == 1: # left border
# check, whether the windows were docked,
# before the geometry of the active window changed
if abs(winInfo['x2'] + 1 - winInfo_active['x']) <= tilingInfo['margin'] + tolerance and \
winInfo_active['y'] <= max(winInfo['y'], 0) + tolerance and \
winInfo_active['y2'] >= min(winInfo['y2'], workAreaHeight) - tolerance:
geometry = get_window_geometry(window_active)
if geometry is None: # window vanished
return
newWidth = geometry.x - winInfo['x']
if newWidth >= tilingInfo['minSize']:
# resize, according to the new geometry of the active window
set_window_size(winID, width=newWidth)
disp.sync()
# update_windows_info()
elif moved_border == 2: # upper border
# check, whether the windows were docked,
# before the geometry of the active window got changed
if abs(winInfo['y2'] + 1 - winInfo_active['y']) <= tilingInfo['margin'] + tolerance and \
winInfo_active['x'] <= max(winInfo['x'], 0) + tolerance and \
winInfo_active['x2'] >= min(winInfo['x2'], workAreaWidth) - tolerance:
geometry = get_window_geometry(window_active)
if geometry is None: # window vanished
return
newHeight = geometry.y - winInfo['y']
if newHeight >= tilingInfo['minSize']:
# resize, according to the new geometry of the active window
set_window_size(winID, height=newHeight)
disp.sync()
# update_windows_info()
elif moved_border == 4: # right border
if abs(winInfo_active['x2'] + 1 - winInfo['x']) <= tilingInfo['margin'] + tolerance and \
winInfo_active['y'] <= max(winInfo['y'], 0) + tolerance and \
winInfo_active['y2'] >= min(winInfo['y2'], workAreaHeight) - tolerance:
winActiveGeom = get_window_geometry(window_active)
if winActiveGeom is None: # window vanished
return
winActive_x2 = winActiveGeom.x + winActiveGeom.width - 1
newWidth = winInfo['x2'] - winActive_x2
if newWidth >= tilingInfo['minSize']:
set_window_position(winID, x=winActive_x2 + 1)
set_window_size(winID, width=newWidth)
disp.sync()
# update_windows_info()
elif moved_border == 8: # lower border
if abs(winInfo_active['y2'] + 1 - winInfo['y']) <= tilingInfo['margin'] + tolerance and \
winInfo_active['x'] <= max(winInfo['x'], 0) + tolerance and \
winInfo_active['x2'] >= min(winInfo['x2'], workAreaWidth) - tolerance:
winActiveGeom = get_window_geometry(window_active)
if winActiveGeom is None: # window vanished
return
winActive_y2 = winActiveGeom.y + winActiveGeom.height - 1
newHeight = winInfo['y2'] - winActive_y2
if newHeight >= tilingInfo['minSize']:
set_window_position(winID, y=winActive_y2 + 1)
set_window_size(winID, height=newHeight)
disp.sync()
# update_windows_info()
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def set_setxy_win(winID):
"""
For some applications/windows the positioning works fine when using their parent window,
while for other applications this works when using their own window.
This function determines which of these windows to take for this operation
and stores this information in the windowsInfo - dictionary.
As a test, the function tries to temporarily move the window down by one pixel,
retrieves the actual position and then places it back.
Unfortunately the awesome emwh (https://github.com/parkouss/pyewmh) doesn't seem to be
a good option here, since it's use for resizing leads to a very annoying flickering
of some applications (e.g. the Vivaldi-browser) while resizing them.
TODO: Find a more elegant solution
:param winID: windows-ID
:return:
"""
global windowsInfo
try:
if windowsInfo[winID]['winSetXY'] is not None:
return # already set
except KeyError:
return
try:
unmaximize_window(windowsInfo[winID]['win'])
oldY = windowsInfo[winID]['y']
oldX = windowsInfo[winID]['x']
windowsInfo[winID]['winParent'].configure(y=oldY + 1)
disp.sync()
time.sleep(0.05)
newGeom = get_window_geometry(windowsInfo[winID]['winParent'])
if abs(oldY + 1 - newGeom.y) <= 1:
windowsInfo[winID]['winSetXY'] = windowsInfo[winID]['winParent']
else:
windowsInfo[winID]['winSetXY'] = windowsInfo[winID]['win']
# restore old position
windowsInfo[winID]['winSetXY'].configure(x=oldX, y=oldY)
disp.sync()
except (Xlib.error.BadWindow, AttributeError, KeyError) as e:
pass # window vanished
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def set_window_decoration(winID, status):
"""
Undecorate / decorate the given window (title-bar and border)
:param winID: ID of the window
:param status: controls whether to show the decoration (True | False)
:return:
"""
global windowsInfo, tilingInfo, MOTIF_WM_HINTS, ANY_PROPERTYTYPE, GTK_FRAME_EXTENTS
try: