-
Notifications
You must be signed in to change notification settings - Fork 20
/
_pywinctl_linux.py
1491 lines (1257 loc) · 56.9 KB
/
_pywinctl_linux.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/python
# -*- coding: utf-8 -*-
from __future__ import annotations
import os
import sys
import threading
assert sys.platform == "linux"
import math
import platform
import re
import subprocess
import time
from ctypes import Structure, byref, c_ulong, cdll, c_uint32, c_int32
from ctypes.util import find_library
from typing import Iterable, TYPE_CHECKING, cast, Any
import tkinter as tk
if TYPE_CHECKING:
from typing_extensions import TypedDict
else:
# Only needed if the import from typing_extensions is used outside of annotations
from typing import TypedDict
import Xlib.display
import Xlib.error
import Xlib.protocol
import Xlib.X
import Xlib.Xatom
import Xlib.Xutil
from Xlib.xobject.drawable import Window
from pywinctl import BaseWindow, Point, Re, Rect, Size, _WatchDog, pointInRect
# WARNING: Changes are not immediately applied, specially for hide/show (unmap/map)
# You may set wait to True in case you need to effectively know if/when change has been applied.
WAIT_ATTEMPTS = 10
WAIT_DELAY = 0.025 # Will be progressively increased on every retry
# These values are documented at https://specifications.freedesktop.org/wm-spec/wm-spec-1.3.html
# WM_STATE values
WM_CHANGE_STATE = 'WM_CHANGE_STATE'
WM_STATE = '_NET_WM_STATE'
STATE_MODAL = '_NET_WM_STATE_MODAL'
STATE_STICKY = '_NET_WM_STATE_STICKY'
STATE_MAX_VERT = '_NET_WM_STATE_MAXIMIZED_VERT'
STATE_MAX_HORZ = '_NET_WM_STATE_MAXIMIZED_HORZ'
STATE_SHADED = '_NET_WM_STATE_SHADED'
STATE_SKIP_TASKBAR = '_NET_WM_STATE_SKIP_TASKBAR'
STATE_SKIP_PAGER = '_NET_WM_STATE_SKIP_PAGER'
STATE_HIDDEN = '_NET_WM_STATE_HIDDEN'
STATE_FULLSCREEN = '_NET_WM_STATE_FULLSCREEN'
STATE_ABOVE = '_NET_WM_STATE_ABOVE'
STATE_BELOW = '_NET_WM_STATE_BELOW'
STATE_ATTENTION = '_NET_WM_STATE_DEMANDS_ATTENTION'
STATE_FOCUSED = '_NET_WM_STATE_FOCUSED'
STATE_NULL = 0
# Set state actions
ACTION_UNSET = 0 # Remove state
ACTION_SET = 1 # Add state
ACTION_TOGGLE = 2 # Toggle state
# WM_WINDOW_TYPE values
WM_WINDOW_TYPE = '_NET_WM_WINDOW_TYPE'
WINDOW_DESKTOP = '_NET_WM_WINDOW_TYPE_DESKTOP'
WINDOW_NORMAL = '_NET_WM_WINDOW_TYPE_NORMAL'
# State Hints
HINT_STATE_WITHDRAWN = 0
HINT_STATE_NORMAL = 1
HINT_STATE_ICONIC = 3
# Stacking and Misc Atoms
WINDOW_LIST_STACKING = '_NET_CLIENT_LIST_STACKING'
ACTIVE_WINDOW = '_NET_ACTIVE_WINDOW'
WM_PID = '_NET_WM_PID'
WORKAREA = '_NET_WORKAREA'
MOVERESIZE_WINDOW = '_NET_MOVERESIZE_WINDOW'
CLOSE_WINDOW = '_NET_CLOSE_WINDOW'
def checkPermissions(activate: bool = False):
"""
macOS ONLY: Check Apple Script permissions for current script/app and, optionally, shows a
warning dialog and opens security preferences
:param activate: If ''True'' and if permissions are not granted, shows a dialog and opens security preferences.
Defaults to ''False''
:return: returns ''True'' if permissions are already granted or platform is not macOS
"""
return True
def getActiveWindow() -> LinuxWindow | None:
"""
Get the currently active (focused) Window
:return: Window object or None
"""
dsp = Xlib.display.Display()
root = dsp.screen().root
win: Xlib.protocol.request.GetProperty = root.get_full_property(dsp.get_atom(ACTIVE_WINDOW), Xlib.Xatom.WINDOW)
dsp.close()
if win:
win_id = win.value
if win_id:
return LinuxWindow(win_id[0])
return None
def getActiveWindowTitle():
"""
Get the title of the currently active (focused) Window
:return: window title as string or empty
"""
win = getActiveWindow()
if win:
return win.title
else:
return ""
def __remove_bad_windows(windows: Iterable[Window | int | None]):
"""
:param windows: Xlib Windows
:return: A generator of LinuxWindow that filters out BadWindows
"""
for window in windows:
try:
yield LinuxWindow(window) # type: ignore[arg-type] # pyright: ignore[reportGeneralTypeIssues] # We expect an error here
except Xlib.error.XResourceError:
pass
def _getWindowListStacking():
dsp = Xlib.display.Display()
root = dsp.screen().root
atom: int = dsp.get_atom(WINDOW_LIST_STACKING)
properties: Xlib.protocol.request.GetProperty = root.get_full_property(atom, Xlib.X.AnyPropertyType)
dsp.close()
if properties:
return [p for p in properties.value]
def getAllWindows():
"""
Get the list of Window objects for all visible windows
:return: list of Window objects
"""
return [window for window in __remove_bad_windows(_getWindowListStacking())]
def getAllTitles() -> list[str]:
"""
Get the list of titles of all visible windows
:return: list of titles as strings
"""
return [window.title for window in getAllWindows()]
def getWindowsWithTitle(title: str | re.Pattern[str], app: tuple[str, ...] | None = (), condition: int = Re.IS, flags: int = 0):
"""
Get the list of window objects whose title match the given string with condition and flags.
Use ''condition'' to delimit the search. Allowed values are stored in pywinctl.Re sub-class (e.g. pywinctl.Re.CONTAINS)
Use ''flags'' to define additional values according to each condition type:
- IS -- window title is equal to given title (allowed flags: Re.IGNORECASE)
- CONTAINS -- window title contains given string (allowed flags: Re.IGNORECASE)
- STARTSWITH -- window title starts by given string (allowed flags: Re.IGNORECASE)
- ENDSWITH -- window title ends by given string (allowed flags: Re.IGNORECASE)
- NOTIS -- window title is not equal to given title (allowed flags: Re.IGNORECASE)
- NOTCONTAINS -- window title does NOT contains given string (allowed flags: Re.IGNORECASE)
- NOTSTARTSWITH -- window title does NOT starts by given string (allowed flags: Re.IGNORECASE)
- NOTENDSWITH -- window title does NOT ends by given string (allowed flags: Re.IGNORECASE)
- MATCH -- window title matched by given regex pattern (allowed flags: regex flags, see https://docs.python.org/3/library/re.html)
- NOTMATCH -- window title NOT matched by given regex pattern (allowed flags: regex flags, see https://docs.python.org/3/library/re.html)
- EDITDISTANCE -- window title matched using Levenshtein edit distance to a given similarity percentage (allowed flags: 0-100. Defaults to 90)
- DIFFRATIO -- window title matched using difflib similarity ratio (allowed flags: 0-100. Defaults to 90)
:param title: title or regex pattern to match, as string
:param app: (optional) tuple of app names. Defaults to ALL (empty list)
:param condition: (optional) condition to apply when searching the window. Defaults to ''Re.IS'' (is equal to)
:param flags: (optional) specific flags to apply to condition. Defaults to 0 (no flags)
:return: list of Window objects
"""
matches: list[LinuxWindow] = []
if title and condition in Re._cond_dic:
lower = False
if condition in (Re.MATCH, Re.NOTMATCH):
title = re.compile(title, flags)
elif condition in (Re.EDITDISTANCE, Re.DIFFRATIO):
if not isinstance(flags, int) or not (0 < flags <= 100):
flags = 90
elif flags == Re.IGNORECASE:
lower = True
if isinstance(title, re.Pattern):
title = title.pattern
title = title.lower()
for win in getAllWindows():
if win.title and Re._cond_dic[condition](title, win.title.lower() if lower else win.title, flags) \
and (not app or (app and win.getAppName() in app)):
matches.append(win)
return matches
def getAllAppsNames() -> list[str]:
"""
Get the list of names of all visible apps
:return: list of names as strings
"""
return list(getAllAppsWindowsTitles())
def getAppsWithName(name: str | re.Pattern[str], condition: int = Re.IS, flags: int = 0):
"""
Get the list of app names which match the given string using the given condition and flags.
Use ''condition'' to delimit the search. Allowed values are stored in pywinctl.Re sub-class (e.g. pywinctl.Re.CONTAINS)
Use ''flags'' to define additional values according to each condition type:
- IS -- app name is equal to given title (allowed flags: Re.IGNORECASE)
- CONTAINS -- app name contains given string (allowed flags: Re.IGNORECASE)
- STARTSWITH -- app name starts by given string (allowed flags: Re.IGNORECASE)
- ENDSWITH -- app name ends by given string (allowed flags: Re.IGNORECASE)
- NOTIS -- app name is not equal to given title (allowed flags: Re.IGNORECASE)
- NOTCONTAINS -- app name does NOT contains given string (allowed flags: Re.IGNORECASE)
- NOTSTARTSWITH -- app name does NOT starts by given string (allowed flags: Re.IGNORECASE)
- NOTENDSWITH -- app name does NOT ends by given string (allowed flags: Re.IGNORECASE)
- MATCH -- app name matched by given regex pattern (allowed flags: regex flags, see https://docs.python.org/3/library/re.html)
- NOTMATCH -- app name NOT matched by given regex pattern (allowed flags: regex flags, see https://docs.python.org/3/library/re.html)
- EDITDISTANCE -- app name matched using Levenshtein edit distance to a given similarity percentage (allowed flags: 0-100. Defaults to 90)
- DIFFRATIO -- app name matched using difflib similarity ratio (allowed flags: 0-100. Defaults to 90)
:param name: name or regex pattern to match, as string
:param condition: (optional) condition to apply when searching the app. Defaults to ''Re.IS'' (is equal to)
:param flags: (optional) specific flags to apply to condition. Defaults to 0 (no flags)
:return: list of app names
"""
matches: list[str] = []
if name and condition in Re._cond_dic:
lower = False
if condition in (Re.MATCH, Re.NOTMATCH):
name = re.compile(name, flags)
elif condition in (Re.EDITDISTANCE, Re.DIFFRATIO):
if not isinstance(flags, int) or not (0 < flags <= 100):
flags = 90
elif flags == Re.IGNORECASE:
lower = True
if isinstance(name, re.Pattern):
name = name.pattern
name = name.lower()
for title in getAllAppsNames():
if title and Re._cond_dic[condition](name, title.lower() if lower else title, flags):
matches.append(title)
return matches
def getAllAppsWindowsTitles():
"""
Get all visible apps names and their open windows titles
Format:
Key: app name
Values: list of window titles as strings
:return: python dictionary
"""
result: dict[str, list[str]] = {}
for win in getAllWindows():
appName = win.getAppName()
if appName in result.keys():
result[appName].append(win.title)
else:
result[appName] = [win.title]
return result
def getWindowsAt(x: int, y: int):
"""
Get the list of Window objects whose windows contain the point ``(x, y)`` on screen
:param x: X screen coordinate of the window(s)
:param y: Y screen coordinate of the window(s)
:return: list of Window objects
"""
return [
window for window
in getAllWindows()
if pointInRect(x, y, window.left, window.top, window.width, window.height)]
def getTopWindowAt(x: int, y: int):
"""
Get the Window object at the top of the stack at the point ``(x, y)`` on screen
:param x: X screen coordinate of the window
:param y: Y screen coordinate of the window
:return: Window object or None
"""
windows: list[LinuxWindow] = getAllWindows()
for window in reversed(windows):
if pointInRect(x, y, window.left, window.top, window.width, window.height):
return window
else:
return None
class LinuxWindow(BaseWindow):
@property
def _rect(self) -> Rect:
return self.__rect
def __init__(self, hWnd: Window | int | str):
super().__init__()
self._windowWrapper = _XWindowWrapper(hWnd)
self._hWnd: int = self._windowWrapper.id
self._windowObject = self._windowWrapper.getWindow()
assert isinstance(self._hWnd, int)
assert isinstance(self._windowObject, Window)
self.__rect: Rect = self._rectFactory()
self.watchdog = _WatchDog(self)
def _getWindowRect(self) -> Rect:
# https://stackoverflow.com/questions/12775136/get-window-position-and-size-in-python-with-xlib - mgalgs
return self._windowWrapper.getWindowRect()
def getExtraFrameSize(self, includeBorder: bool = True) -> tuple[int, int, int, int]:
"""
Get the extra space, in pixels, around the window, including or not the border.
Notice not all applications/windows will use this property values
:param includeBorder: set to ''False'' to avoid including borders
:return: (left, top, right, bottom) additional frame size in pixels, as a tuple of int
"""
return self._windowWrapper.getExtraFrameSize()
def getClientFrame(self) -> Rect:
"""
Get the client area of window including scroll, menu and status bars, as a Rect (x, y, right, bottom)
Notice that this method won't match non-standard window decoration sizes
:return: Rect struct
"""
return self._windowWrapper.getClientFrame()
def __repr__(self):
return '%s(hWnd=%s)' % (self.__class__.__name__, self._hWnd)
def __eq__(self, other: object) -> bool:
return isinstance(other, LinuxWindow) and self._hWnd == other._hWnd
def close(self) -> bool:
"""
Closes this window. This may trigger "Are you sure you want to
quit?" dialogs or other actions that prevent the window from
actually closing. This is identical to clicking the X button on the
window.
:return: ''True'' if window is closed
"""
self._windowWrapper.close()
ids = [w._hWnd for w in getAllWindows()]
return self._hWnd not in ids
def minimize(self, wait: bool = False) -> bool:
"""
Minimizes this window
:param wait: set to ''True'' to confirm action requested (in a reasonable time)
:return: ''True'' if window minimized
"""
if not self.isMinimized:
self._windowWrapper.sendMessage(WM_CHANGE_STATE, [Xlib.Xutil.IconicState])
retries = 0
while wait and retries < WAIT_ATTEMPTS and not self.isMinimized:
retries += 1
time.sleep(WAIT_DELAY * retries)
return self.isMinimized
def maximize(self, wait: bool = False) -> bool:
"""
Maximizes this window
:param wait: set to ''True'' to confirm action requested (in a reasonable time)
:return: ''True'' if window maximized
"""
if not self.isMaximized:
self._windowWrapper.setWmState(ACTION_SET, STATE_MAX_VERT, STATE_MAX_HORZ)
retries = 0
while wait and retries < WAIT_ATTEMPTS and not self.isMaximized:
retries += 1
time.sleep(WAIT_DELAY * retries)
return self.isMaximized
def restore(self, wait: bool = False, user: bool = False) -> bool:
"""
If maximized or minimized, restores the window to it's normal size
:param wait: set to ''True'' to confirm action requested (in a reasonable time)
:param user: ignored on Windows platform
:return: ''True'' if window restored
"""
if self.isMinimized:
# self._windowWrapper.sendMessage(WM_CHANGE_STATE, [Xlib.Xutil.NormalState])
self.activate()
elif self.isMaximized:
self._windowWrapper.setWmState(ACTION_UNSET, STATE_MAX_VERT, STATE_MAX_HORZ)
retries = 0
while wait and retries < WAIT_ATTEMPTS and (self.isMaximized or self.isMinimized):
retries += 1
time.sleep(WAIT_DELAY * retries)
return bool(not self.isMaximized and not self.isMinimized)
def show(self, wait: bool = False) -> bool:
"""
If hidden or showing, shows the window on screen and in title bar
:param wait: set to ''True'' to wait until action is confirmed (in a reasonable time lap)
:return: ''True'' if window showed
"""
self._windowWrapper.show()
retries = 0
while wait and retries < WAIT_ATTEMPTS and not self._isMapped:
retries += 1
time.sleep(WAIT_DELAY * retries)
return self._isMapped
def hide(self, wait: bool = False) -> bool:
"""
If hidden or showing, hides the window from screen and title bar
:param wait: set to ''True'' to wait until action is confirmed (in a reasonable time lap)
:return: ''True'' if window hidden
"""
self._windowWrapper.hide()
retries = 0
while wait and retries < WAIT_ATTEMPTS and self._isMapped:
retries += 1
time.sleep(WAIT_DELAY * retries)
return not self._isMapped
def activate(self, wait: bool = False, user: bool = False, ) -> bool:
"""
Activate this window and make it the foreground (focused) window
:param wait: set to ''True'' to wait until action is confirmed (in a reasonable time lap)
:param user: ''True'' indicates a direct user request, as required by some WMs to comply.
:return: ''True'' if window activated
"""
if "arm" in platform.platform():
self._windowWrapper.setWmState(ACTION_UNSET, STATE_BELOW, STATE_NULL)
self._windowWrapper.setWmState(ACTION_SET, STATE_ABOVE, STATE_FOCUSED)
else:
# This was not working as expected in Unity
# Thanks to MestreLion (https://github.com/MestreLion) for his solution!!!!
sourceInd = 2 if user else 1
self._windowWrapper.sendMessage(ACTIVE_WINDOW, [sourceInd, Xlib.X.CurrentTime, self._hWnd])
retries = 0
while wait and retries < WAIT_ATTEMPTS and not self.isActive:
retries += 1
time.sleep(WAIT_DELAY * retries)
return bool(self.isActive)
def resize(self, widthOffset: int, heightOffset: int, wait: bool = False):
"""
Resizes the window relative to its current size
:param wait: set to ''True'' to wait until action is confirmed (in a reasonable time lap)
:return: ''True'' if window resized to the given size
"""
return self.resizeTo(int(self.width + widthOffset), int(self.height + heightOffset), wait)
resizeRel = resize # resizeRel is an alias for the resize() method.
def resizeTo(self, newWidth: int, newHeight: int, wait: bool = False):
"""
Resizes the window to a new width and height
:param wait: set to ''True'' to wait until action is confirmed (in a reasonable time lap)
:return: ''True'' if window resized to the given size
"""
self._windowWrapper.setMoveResize(x=self.left, y=self.top, width=newWidth, height=newHeight)
retries = 0
while wait and retries < WAIT_ATTEMPTS and (self.width != newWidth or self.height != newHeight):
retries += 1
time.sleep(WAIT_DELAY * retries)
return self.width == newWidth and self.height == newHeight
def move(self, xOffset: int, yOffset: int, wait: bool = False):
"""
Moves the window relative to its current position
:param wait: set to ''True'' to wait until action is confirmed (in a reasonable time lap)
:return: ''True'' if window moved to the given position
"""
newLeft = max(0, self.left + xOffset) # Xlib won't accept negative positions
newTop = max(0, self.top + yOffset)
return self.moveTo(int(newLeft), int(newTop), wait)
moveRel = move # moveRel is an alias for the move() method.
def moveTo(self, newLeft: int, newTop: int, wait: bool = False):
"""
Moves the window to new coordinates on the screen
:param wait: set to ''True'' to wait until action is confirmed (in a reasonable time lap)
:return: ''True'' if window moved to the given position
"""
newLeft = max(0, newLeft) # Xlib won't accept negative positions
newTop = max(0, newTop)
self._windowWrapper.setMoveResize(x=newLeft, y=newTop, width=self.width, height=self.height)
retries = 0
while wait and retries < WAIT_ATTEMPTS and (self.left != newLeft or self.top != newTop):
retries += 1
time.sleep(WAIT_DELAY * retries)
return self.left == newLeft and self.top == newTop
def _moveResizeTo(self, newLeft: int, newTop: int, newWidth: int, newHeight: int):
newLeft = max(0, newLeft) # Xlib won't accept negative positions
newTop = max(0, newTop)
self._windowWrapper.setMoveResize(x=newLeft, y=newTop, width=newWidth, height=newHeight)
return newLeft == self.left and newTop == self.top and newWidth == self.width and newHeight == self.height
def alwaysOnTop(self, aot: bool = True) -> bool:
"""
Keeps window on top of all others.
:param aot: set to ''False'' to deactivate always-on-top behavior
:return: ''True'' if command succeeded
"""
action = ACTION_SET if aot else ACTION_UNSET
self._windowWrapper.setWmState(action, STATE_ABOVE)
return STATE_ABOVE in self._windowWrapper.getWmState()
def alwaysOnBottom(self, aob: bool = True) -> bool:
"""
Keeps window below of all others, but on top of desktop icons and keeping all window properties
:param aob: set to ''False'' to deactivate always-on-bottom behavior
:return: ''True'' if command succeeded
"""
action = ACTION_SET if aob else ACTION_UNSET
self._windowWrapper.setWmState(action, STATE_BELOW)
return STATE_BELOW in self._windowWrapper.getWmState()
def lowerWindow(self) -> bool:
"""
Lowers the window to the bottom so that it does not obscure any sibling windows
:return: ''True'' if window lowered
"""
self._windowWrapper.setStacking(stack_mode=Xlib.X.Below)
windows = [w for w in _getWindowListStacking()]
return bool(windows and self._hWnd == windows[-1])
def raiseWindow(self) -> bool:
"""
Raises the window to top so that it is not obscured by any sibling windows.
:return: ''True'' if window raised
"""
self._windowWrapper.setStacking(stack_mode=Xlib.X.Above)
windows = [w for w in _getWindowListStacking()]
return bool(windows and self._hWnd == windows[0])
def sendBehind(self, sb: bool = True) -> bool:
"""
Sends the window to the very bottom, below all other windows, including desktop icons.
It may also cause that the window does not accept focus nor keyboard/mouse events as well as
make the window disappear from taskbar and/or pager.
:param sb: set to ''False'' to bring the window back to front
:return: ''True'' if window sent behind desktop icons
Notes:
- On GNOME it will obscure desktop icons... by the moment
"""
if sb and WINDOW_DESKTOP not in self._windowWrapper.getWmWindowType():
# https://stackoverflow.com/questions/58885803/can-i-use-net-wm-window-type-dock-ewhm-extension-in-openbox
# This sends window below all others, but not behind the desktop icons
self._windowWrapper.setWmType(WINDOW_DESKTOP)
# This will try to raise the desktop icons layer on top of the window
# Ubuntu: "@!0,0;BDHF" is the new desktop icons NG extension on Ubuntu
# Mint: "Desktop" name is language-dependent. Using its class instead
# TODO: Test / find in other OS
desktop = _xlibGetAllWindows(title="@!0,0;BDHF", klass=('nemo-desktop', 'Nemo-desktop'))
# if not desktop:
# for win in _getRooTPropertty(ROOT, WINDOW_LIST_STACKING): --> Should _xlibGetWindows() be used instead?
# state = _getWmState(win)
# winType = _getWmWindowType(win)
# if STATE_SKIP_PAGER in state and STATE_SKIP_TASKBAR in state and WINDOW_DESKTOP in winType:
# desktop.append(win)
dsp = Xlib.display.Display()
for d in desktop:
w: Window = dsp.create_resource_object('window', d.id)
w.raise_window()
dsp.close()
return WINDOW_DESKTOP in self._windowWrapper.getWmWindowType()
else:
pos = self.topleft
self._windowWrapper.setWmType(WINDOW_NORMAL)
self.activate(user=True)
self.moveTo(pos.x, pos.y)
return WINDOW_NORMAL in self._windowWrapper.getWmWindowType() and self.isActive
def acceptInput(self, setTo: bool = True) -> None:
"""Toggles the window transparent to input and focus
:param setTo: True/False to toggle window transparent to input and focus
:return: None
"""
self._windowWrapper.setAcceptInput(setTo)
def getAppName(self) -> str:
"""
Get the name of the app current window belongs to
:return: name of the app as string
"""
pids = self._windowWrapper.getProperty(WM_PID)
pid = 0
if pids:
pid = pids[0]
if pid != 0:
with subprocess.Popen(f"ps -q {pid} -o comm=", shell=True, stdout=subprocess.PIPE) as p:
stdout, stderr = p.communicate()
name = stdout.decode(encoding="utf8").replace("\n", "")
else:
name = ""
return name
def getParent(self) -> Window:
"""
Get the handle of the current window parent. It can be another window or an application
:return: handle of the window parent
"""
return self._windowWrapper.query_tree().parent # type: ignore[no-any-return]
def setParent(self, parent) -> bool:
"""
Current window will become child of given parent
WARNIG: Not implemented in AppleScript (not possible in macOS for foreign (other apps') windows)
:param parent: window to set as current window parent
:return: ''True'' if current window is now child of given parent
"""
self._windowObject.reparent(parent, 0, 0)
return bool(self.isChild(parent))
def getChildren(self) -> list[int]:
"""
Get the children handles of current window
:return: list of handles
"""
return self._windowWrapper.query_tree().children # type: ignore[no-any-return]
def getHandle(self) -> int:
"""
Get the current window handle
:return: window handle
"""
return self._hWnd
def isParent(self, child: Window) -> bool:
"""Returns ''True'' if the window is parent of the given window as input argument
Args:
----
''child'' handle of the window you want to check if the current window is parent of
"""
return bool(child.query_tree().parent.id == self._hWnd) # type: ignore[no-any-return]
isParentOf = isParent # isParentOf is an alias of isParent method
def isChild(self, parent: Window):
"""
Check if current window is child of given window/app (handle)
:param parent: handle of the window/app you want to check if the current window is child of
:return: ''True'' if current window is child of the given window
"""
return bool(parent.id == self.getParent().id)
isChildOf = isChild # isChildOf is an alias of isParent method
def getDisplay(self):
"""
Get display name in which current window space is mostly visible
:return: display name as string
"""
screens = getAllScreens()
name = ""
for key in screens:
if pointInRect(self.centerx, self.centery, screens[key]["pos"].x, screens[key]["pos"].y, screens[key]["size"].width, screens[key]["size"].height):
name = key
break
return name
@property
def isMinimized(self) -> bool:
"""
Check if current window is currently minimized
:return: ``True`` if the window is minimized
"""
state = self._windowWrapper.getWmState()
return bool(STATE_HIDDEN in state)
@property
def isMaximized(self) -> bool:
"""
Check if current window is currently maximized
:return: ``True`` if the window is maximized
"""
state = self._windowWrapper.getWmState()
return bool(STATE_MAX_VERT in state and STATE_MAX_HORZ in state)
@property
def isActive(self):
"""
Check if current window is currently the active, foreground window
:return: ``True`` if the window is the active, foreground window
"""
win = getActiveWindow()
return bool(win and win.getHandle() == self._hWnd)
@property
def title(self) -> str:
"""
Get the current window title, as string
:return: title as a string
"""
name: str | bytes = self._windowWrapper.getWmName()
if isinstance(name, bytes):
name = name.decode()
return name
@property
def visible(self) -> bool:
"""
Check if current window is visible (minimized windows are also visible)
:return: ``True`` if the window is currently visible
"""
attr = self._windowWrapper.getAttributes()
state = attr.map_state
return bool(state == Xlib.X.IsViewable) # type: ignore[no-any-return]
isVisible: bool = cast(bool, visible) # isVisible is an alias for the visible property.
@property
def isAlive(self) -> bool:
"""
Check if window (and application) still exists (minimized and hidden windows are included as existing)
:return: ''True'' if window exists
"""
try:
_ = self._windowWrapper.getAttributes().map_state
except Xlib.error.BadWindow:
return False
else:
return True
@property
def isAlerting(self) -> bool:
"""Check if window is flashing/bouncing/demanding attetion on taskbar while demanding user attention
:return: ''True'' if window is demanding attention
"""
return bool(STATE_ATTENTION in self._windowWrapper.getWmState())
@property
def _isMapped(self) -> bool:
# Returns ``True`` if the window is currently mapped
state: int = self._windowWrapper.getAttributes().map_state
return bool(state != Xlib.X.IsUnmapped)
class _XWindowWrapper:
def __init__(self, win: str | int | Window = None, display: Xlib.display.Display = None, root: Window = None):
if not display:
display = Xlib.display.Display()
self.display = display
if not root:
root = self.display.screen().root
self.root = root
self.rid = self.root.id
self.xlib = None
if not win:
win = self.display.create_resource_object('window', self.rid)
elif isinstance(win, int):
win = self.display.create_resource_object('window', win)
elif isinstance(win, str):
win = display.create_resource_object('window', int(win, base=16))
self.win: Window = win
assert isinstance(self.win, Window)
self.id = self.win.id
# self._saveWindowInitValues() # Store initial Window parameters to allow reset and other actions
self.transientWindow: _XWindowWrapper | None = None
self.keepCheckin: bool = False
def _saveWindowInitValues(self) -> None:
# Saves initial rect values to allow reset to original position, size, state and hints.
self._init_rect = self.getWindowRect()
self._init_state = self.getWmState()
self._init_hints = self.win.get_wm_hints()
self._init_normal_hints = self.win.get_wm_normal_hints()
self._init_attributes = self.getAttributes() # can't be modified
self._init_xAttributes = self.XlibAttributes()
self._init_wm_prots = self.win.get_wm_protocols()
self._init_states = self.getWmState()
self._init_types = self.getWmWindowType()
def renewWindowObject(self) -> _XWindowWrapper:
# Not sure if this is necessary.
# - Window object may change (I can't remember in which cases, but it did)
# - It's assuming at least id doesn't change... if it does, well, nothing to do with that window anymore
self.display.close() # -> Is this necessary... and when?
self.display = Xlib.display.Display()
self.root = self.display.screen().root
self.rid = self.root.id
self.win = self.display.create_resource_object('window', self.id)
return self
def getWindow(self) -> Window:
return self.win
def getDisplay(self) -> Xlib.display.Display:
return self.display
def getScreen(self) -> Xlib.protocol.rq.DictWrapper:
return cast(Xlib.protocol.rq.DictWrapper, self.display.screen())
def getRoot(self) -> Window:
return self.root
def getProperty(self, name: str, prop_type: int = Xlib.X.AnyPropertyType) -> list[int]:
atom: int = self.display.get_atom(name)
properties: Xlib.protocol.request.GetProperty = self.win.get_full_property(atom, prop_type)
if properties:
props: list[int] = properties.value
return [p for p in props]
return []
def getWmState(self, text: bool = True) -> list[str] | list[int] | list[Any]:
states = self.win.get_full_property(self.display.get_atom(WM_STATE, False), Xlib.X.AnyPropertyType)
if states:
stats: list[int] = states.value
if not text:
return [s for s in stats]
else:
return [self.display.get_atom_name(s) for s in stats]
return []
def getWmWindowType(self, text: bool = True) -> list[str] | list[int]:
types = self.getProperty(WM_WINDOW_TYPE)
if not text:
return [t for t in types]
else:
return [self.display.get_atom_name(t) for t in types]
def sendMessage(self, prop: str | int, data: list[int]):
if isinstance(prop, str):
prop = self.display.get_atom(prop)
if type(data) is str:
dataSize = 8
else:
data = (data + [0] * (5 - len(data)))[:5]
dataSize = 32
ev = Xlib.protocol.event.ClientMessage(window=self.win, client_type=prop, data=(dataSize, data))
mask = Xlib.X.SubstructureRedirectMask | Xlib.X.SubstructureNotifyMask
self.display.send_event(destination=self.rid, event=ev, event_mask=mask)
self.display.flush()
def setProperty(self, prop: str | int, data: list[int], mode: int = Xlib.X.PropModeReplace):
if isinstance(prop, str):
prop = self.display.get_atom(prop)
# Format value can be 8, 16 or 32... depending on the content of data
format = 32
self.win.change_property(prop, Xlib.Xatom.ATOM, format, data, mode)
self.display.flush()
def setWmState(self, action: int, state: str | int, state2: str | int = 0):
if isinstance(state, str):
state = self.display.get_atom(state, True)
if isinstance(state2, str):
state2 = self.display.get_atom(state2, True)
self.setProperty(WM_STATE, [action, state, state2, 1])
self.display.flush()
def setWmType(self, prop: str | int, mode: int = Xlib.X.PropModeReplace):
if isinstance(prop, str):
prop = self.display.get_atom(prop, False)
geom = self.win.get_geometry()
self.win.unmap()
self.setProperty(WM_WINDOW_TYPE, [prop], mode)
self.win.map()
self.display.flush()
self.setMoveResize(x=geom.x, y=geom.y, width=geom.width, height=geom.height)
def setMoveResize(self, x: int, y: int, width: int, height: int):
self.win.configure(x=x, y=y, width=width, height=height)
self.display.flush()
def setStacking(self, stack_mode: int):
self.win.configure(stack_mode=stack_mode)
self.display.flush()
def hide(self):
self.win.unmap_sub_windows()
self.display.flush()
self.win.unmap()
self.display.flush()
def show(self):
self.win.map()
self.display.flush()
self.win.map_sub_windows()
self.display.flush()
def close(self):
self.sendMessage(CLOSE_WINDOW, [])
def getWmName(self) -> str | None:
return self.win.get_wm_name()
# def _globalEventListener(self, events):
#
# from Xlib import X
# from Xlib.ext import record
# from Xlib.display import Display
# from Xlib.protocol import rq
#
# def handler(reply):
# data = reply.data
# while len(data):
# event, data = rq.EventField(None).parse_binary_value(data, display.display, None, None)
#
# if event.type == X.KeyPress:
# print('pressed')
# elif event.type == X.KeyRelease:
# print('released')
#
# display = Display()
# context = display.record_create_context(0, [record.AllClients], [{
# 'core_requests': (0, 0),
# 'core_replies': (0, 0),
# 'ext_requests': (0, 0, 0, 0),
# 'ext_replies': (0, 0, 0, 0),
# 'delivered_events': (0, 0),
# 'device_events': (X.KeyReleaseMask, X.ButtonReleaseMask),
# 'errors': (0, 0),
# 'client_started': False,
# 'client_died': False,
# }])
# display.record_enable_context(context, handler)
# display.record_free_context(context)
#
# while True:
# display.screen().root.display.next_event()
def _createTransient(self, parent, d):
if self.transientWindow is not None:
self._closeTransientWindow(d)
geom = self.win.get_geometry()
window = self.xlib.XCreateSimpleWindow(