-
-
Notifications
You must be signed in to change notification settings - Fork 692
/
window.py
1816 lines (1557 loc) · 60.8 KB
/
window.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
from __future__ import annotations
import array
import contextlib
import inspect
import traceback
from itertools import islice
from typing import TYPE_CHECKING
import xcffib
import xcffib.xproto
from xcffib.wrappers import GContextID, PixmapID
from xcffib.xproto import EventMask, SetMode, StackMode
from libqtile import hook, utils
from libqtile.backend import base
from libqtile.backend.base import FloatStates
from libqtile.backend.x11 import xcbq
from libqtile.backend.x11.drawer import Drawer
from libqtile.command.base import CommandError, ItemT
from libqtile.log_utils import logger
if TYPE_CHECKING:
from typing import Optional
# ICCM Constants
NoValue = 0x0000
XValue = 0x0001
YValue = 0x0002
WidthValue = 0x0004
HeightValue = 0x0008
AllValues = 0x000F
XNegative = 0x0010
YNegative = 0x0020
InputHint = (1 << 0)
StateHint = (1 << 1)
IconPixmapHint = (1 << 2)
IconWindowHint = (1 << 3)
IconPositionHint = (1 << 4)
IconMaskHint = (1 << 5)
WindowGroupHint = (1 << 6)
MessageHint = (1 << 7)
UrgencyHint = (1 << 8)
AllHints = (InputHint | StateHint | IconPixmapHint | IconWindowHint |
IconPositionHint | IconMaskHint | WindowGroupHint | MessageHint |
UrgencyHint)
WithdrawnState = 0
DontCareState = 0
NormalState = 1
ZoomState = 2
IconicState = 3
InactiveState = 4
RectangleOut = 0
RectangleIn = 1
RectanglePart = 2
VisualNoMask = 0x0
VisualIDMask = 0x1
VisualScreenMask = 0x2
VisualDepthMask = 0x4
VisualClassMask = 0x8
VisualRedMaskMask = 0x10
VisualGreenMaskMask = 0x20
VisualBlueMaskMask = 0x40
VisualColormapSizeMask = 0x80
VisualBitsPerRGBMask = 0x100
VisualAllMask = 0x1FF
ReleaseByFreeingColormap = 1
BitmapSuccess = 0
BitmapOpenFailed = 1
BitmapFileInvalid = 2
BitmapNoMemory = 3
XCSUCCESS = 0
XCNOMEM = 1
XCNOENT = 2
_NET_WM_STATE_REMOVE = 0
_NET_WM_STATE_ADD = 1
_NET_WM_STATE_TOGGLE = 2
def _geometry_getter(attr):
def get_attr(self):
if getattr(self, "_" + attr) is None:
g = self.window.get_geometry()
# trigger the geometry setter on all these
self.x = g.x
self.y = g.y
self.width = g.width
self.height = g.height
self.depth = g.depth
return getattr(self, "_" + attr)
return get_attr
def _geometry_setter(attr):
def f(self, value):
if not isinstance(value, int):
frame = inspect.currentframe()
stack_trace = traceback.format_stack(frame)
logger.error("!!!! setting %s to a non-int %s; please report this!", attr, value)
logger.error(''.join(stack_trace[:-1]))
value = int(value)
setattr(self, "_" + attr, value)
return f
class XWindow:
def __init__(self, conn, wid):
self.conn = conn
self.wid = wid
def _property_string(self, r):
"""Extract a string from a window property reply message"""
return r.value.to_string()
def _property_utf8(self, r):
return r.value.to_utf8()
def send_event(self, synthevent, mask=EventMask.NoEvent):
self.conn.conn.core.SendEvent(False, self.wid, mask, synthevent.pack())
def kill_client(self):
self.conn.conn.core.KillClient(self.wid)
def set_input_focus(self):
self.conn.conn.core.SetInputFocus(
xcffib.xproto.InputFocus.PointerRoot,
self.wid,
xcffib.xproto.Time.CurrentTime
)
def warp_pointer(self, x, y):
"""Warps the pointer to the location `x`, `y` on the window"""
self.conn.conn.core.WarpPointer(
0, self.wid, # src_window, dst_window
0, 0, # src_x, src_y
0, 0, # src_width, src_height
x, y # dest_x, dest_y
)
def get_name(self):
"""Tries to retrieve a canonical window name.
We test the following properties in order of preference:
- _NET_WM_VISIBLE_NAME
- _NET_WM_NAME
- WM_NAME.
"""
r = self.get_property("_NET_WM_VISIBLE_NAME", "UTF8_STRING")
if r:
return self._property_utf8(r)
r = self.get_property("_NET_WM_NAME", "UTF8_STRING")
if r:
return self._property_utf8(r)
r = self.get_property(xcffib.xproto.Atom.WM_NAME, "UTF8_STRING")
if r:
return self._property_utf8(r)
r = self.get_property(
xcffib.xproto.Atom.WM_NAME,
xcffib.xproto.GetPropertyType.Any
)
if r:
return self._property_string(r)
def get_wm_hints(self):
wm_hints = self.get_property("WM_HINTS", xcffib.xproto.GetPropertyType.Any)
if wm_hints:
atoms_list = wm_hints.value.to_atoms()
flags = {k for k, v in xcbq.HintsFlags.items() if atoms_list[0] & v}
return {
"flags": flags,
"input": atoms_list[1] if "InputHint" in flags else None,
"initial_state": atoms_list[2] if "StateHing" in flags else None,
"icon_pixmap": atoms_list[3] if "IconPixmapHint" in flags else None,
"icon_window": atoms_list[4] if "IconWindowHint" in flags else None,
"icon_x": atoms_list[5] if "IconPositionHint" in flags else None,
"icon_y": atoms_list[6] if "IconPositionHint" in flags else None,
"icon_mask": atoms_list[7] if "IconMaskHint" in flags else None,
"window_group": atoms_list[8] if 'WindowGroupHint' in flags else None,
}
def get_wm_normal_hints(self):
wm_normal_hints = self.get_property(
"WM_NORMAL_HINTS",
xcffib.xproto.GetPropertyType.Any
)
if wm_normal_hints:
atom_list = wm_normal_hints.value.to_atoms()
flags = {k for k, v in xcbq.NormalHintsFlags.items() if atom_list[0] & v}
hints = {
"flags": flags,
"min_width": atom_list[5],
"min_height": atom_list[6],
"max_width": atom_list[7],
"max_height": atom_list[8],
"width_inc": atom_list[9],
"height_inc": atom_list[10],
"min_aspect": (atom_list[11], atom_list[12]),
"max_aspect": (atom_list[13], atom_list[14])
}
# WM_SIZE_HINTS is potentially extensible (append to the end only)
iterator = islice(hints, 15, None)
hints["base_width"] = next(iterator, hints["min_width"])
hints["base_height"] = next(iterator, hints["min_height"])
hints["win_gravity"] = next(iterator, 1)
return hints
def get_wm_protocols(self):
wm_protocols = self.get_property("WM_PROTOCOLS", "ATOM", unpack=int)
if wm_protocols is not None:
return {self.conn.atoms.get_name(wm_protocol) for wm_protocol in wm_protocols}
return set()
def get_wm_state(self):
return self.get_property("WM_STATE", xcffib.xproto.GetPropertyType.Any, unpack=int)
def get_wm_class(self):
"""Return an (instance, class) tuple if WM_CLASS exists, or None"""
r = self.get_property("WM_CLASS", "STRING")
if r:
s = self._property_string(r)
return list(s.strip("\0").split("\0"))
return []
def get_wm_window_role(self):
r = self.get_property("WM_WINDOW_ROLE", "STRING")
if r:
return self._property_string(r)
def get_wm_transient_for(self):
"""Returns the WID of the parent window"""
r = self.get_property("WM_TRANSIENT_FOR", "WINDOW", unpack=int)
if r:
return r[0]
def get_wm_icon_name(self):
r = self.get_property("_NET_WM_ICON_NAME", "UTF8_STRING")
if r:
return self._property_utf8(r)
r = self.get_property("WM_ICON_NAME", "STRING")
if r:
return self._property_utf8(r)
def get_wm_client_machine(self):
r = self.get_property("WM_CLIENT_MACHINE", "STRING")
if r:
return self._property_utf8(r)
def get_geometry(self):
q = self.conn.conn.core.GetGeometry(self.wid)
return q.reply()
def get_wm_desktop(self):
r = self.get_property("_NET_WM_DESKTOP", "CARDINAL", unpack=int)
if r:
return r[0]
def get_wm_type(self):
"""
http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#id2551529
"""
r = self.get_property('_NET_WM_WINDOW_TYPE', "ATOM", unpack=int)
if r:
name = self.conn.atoms.get_name(r[0])
return xcbq.WindowTypes.get(name, name)
def get_net_wm_state(self):
r = self.get_property('_NET_WM_STATE', "ATOM", unpack=int)
if r:
names = [self.conn.atoms.get_name(p) for p in r]
return [xcbq.WindowStates.get(n, n) for n in names]
return []
def get_net_wm_pid(self):
r = self.get_property("_NET_WM_PID", unpack=int)
if r:
return r[0]
def configure(self, **kwargs):
"""
Arguments can be: x, y, width, height, borderwidth, sibling, stackmode
"""
mask, values = xcbq.ConfigureMasks(**kwargs)
# older versions of xcb pack everything into unsigned ints "=I"
# since 1.12, uses switches to pack things sensibly
if float(".".join(xcffib.__xcb_proto_version__.split(".")[0: 2])) < 1.12:
values = [i & 0xffffffff for i in values]
return self.conn.conn.core.ConfigureWindow(self.wid, mask, values)
def set_attribute(self, **kwargs):
mask, values = xcbq.AttributeMasks(**kwargs)
self.conn.conn.core.ChangeWindowAttributesChecked(
self.wid, mask, values
)
def set_cursor(self, name):
cursor_id = self.conn.cursors[name]
mask, values = xcbq.AttributeMasks(cursor=cursor_id)
self.conn.conn.core.ChangeWindowAttributesChecked(
self.wid, mask, values
)
def set_property(self, name, value, type=None, format=None):
"""
Parameters
==========
name: String Atom name
type: String Atom name
format: 8, 16, 32
"""
if name in xcbq.PropertyMap:
if type or format:
raise ValueError(
"Over-riding default type or format for property."
)
type, format = xcbq.PropertyMap[name]
else:
if None in (type, format):
raise ValueError(
"Must specify type and format for unknown property."
)
try:
if isinstance(value, str):
# xcffib will pack the bytes, but we should encode them properly
value = value.encode()
else:
# if this runs without error, the value is already a list, don't wrap it
next(iter(value))
except StopIteration:
# The value was an iterable, just empty
value = []
except TypeError:
# the value wasn't an iterable and wasn't a string, so let's
# wrap it.
value = [value]
try:
self.conn.conn.core.ChangePropertyChecked(
xcffib.xproto.PropMode.Replace,
self.wid,
self.conn.atoms[name],
self.conn.atoms[type],
format, # Format - 8, 16, 32
len(value),
value
).check()
except xcffib.xproto.WindowError:
logger.debug(
'X error in SetProperty (wid=%r, prop=%r), ignoring',
self.wid, name)
def get_property(self, prop, type=None, unpack=None):
"""Return the contents of a property as a GetPropertyReply
If unpack is specified, a tuple of values is returned. The type to
unpack, either `str` or `int` must be specified.
"""
if type is None:
if prop not in xcbq.PropertyMap:
raise ValueError(
"Must specify type for unknown property."
)
else:
type, _ = xcbq.PropertyMap[prop]
try:
r = self.conn.conn.core.GetProperty(
False, self.wid,
self.conn.atoms[prop]
if isinstance(prop, str)
else prop,
self.conn.atoms[type]
if isinstance(type, str)
else type,
0, (2 ** 32) - 1
).reply()
except (xcffib.xproto.WindowError, xcffib.xproto.AccessError):
logger.debug(
'X error in GetProperty (wid=%r, prop=%r), ignoring',
self.wid, prop)
if unpack:
return []
return None
if not r.value_len:
if unpack:
return []
return None
elif unpack:
# Should we allow more options for unpacking?
if unpack is int:
return r.value.to_atoms()
elif unpack is str:
return r.value.to_string()
else:
return r
def list_properties(self):
r = self.conn.conn.core.ListProperties(self.wid).reply()
return [self.conn.atoms.get_name(i) for i in r.atoms]
def map(self):
self.conn.conn.core.MapWindow(self.wid)
def unmap(self):
self.conn.conn.core.UnmapWindowUnchecked(self.wid)
def get_attributes(self):
return self.conn.conn.core.GetWindowAttributes(self.wid).reply()
def query_tree(self):
q = self.conn.conn.core.QueryTree(self.wid).reply()
root = None
parent = None
if q.root:
root = XWindow(self.conn, q.root)
if q.parent:
parent = XWindow(self.conn, q.parent)
return root, parent, [XWindow(self.conn, i) for i in q.children]
def paint_borders(self, depth, colors, borderwidth, width, height):
"""
This method is used only by the managing Window class.
"""
self.set_property('_NET_FRAME_EXTENTS', [borderwidth] * 4)
if not colors or not borderwidth:
return
if isinstance(colors, str):
self.set_attribute(borderpixel=self.conn.color_pixel(colors))
return
if len(colors) > borderwidth:
colors = colors[:borderwidth]
core = self.conn.conn.core
outer_w = width + borderwidth * 2
outer_h = height + borderwidth * 2
with PixmapID(self.conn.conn) as pixmap:
with GContextID(self.conn.conn) as gc:
core.CreatePixmap(
depth, pixmap, self.wid, outer_w, outer_h
)
core.CreateGC(gc, pixmap, 0, None)
borders = len(colors)
borderwidths = [borderwidth // borders] * borders
for i in range(borderwidth % borders):
borderwidths[i] += 1
coord = 0
for i in range(borders):
core.ChangeGC(
gc, xcffib.xproto.GC.Foreground, [self.conn.color_pixel(colors[i])]
)
rect = xcffib.xproto.RECTANGLE.synthetic(
coord, coord, outer_w - coord * 2, outer_h - coord * 2
)
core.PolyFillRectangle(pixmap, gc, 1, [rect])
coord += borderwidths[i]
self._set_borderpixmap(depth, pixmap, gc, borderwidth, width, height)
def _set_borderpixmap(self, depth, pixmap, gc, borderwidth, width, height):
core = self.conn.conn.core
outer_w = width + borderwidth * 2
outer_h = height + borderwidth * 2
with PixmapID(self.conn.conn) as border:
core.CreatePixmap(
depth, border, self.wid, outer_w, outer_h
)
most_w = outer_w - borderwidth
most_h = outer_h - borderwidth
core.CopyArea(pixmap, border, gc, borderwidth, borderwidth, 0, 0, most_w, most_h)
core.CopyArea(pixmap, border, gc, 0, 0, most_w, most_h, borderwidth, borderwidth)
core.CopyArea(pixmap, border, gc, borderwidth, 0, 0, most_h, most_w, borderwidth)
core.CopyArea(pixmap, border, gc, 0, borderwidth, most_w, 0, borderwidth, most_h)
core.ChangeWindowAttributes(self.wid, xcffib.xproto.CW.BorderPixmap, [border])
class _Window:
_window_mask = 0 # override in child class
def __init__(self, window, qtile):
base.Window.__init__(self)
self.window, self.qtile = window, qtile
self.hidden = True
self.icons = {}
window.set_attribute(eventmask=self._window_mask)
self._group = None
try:
g = self.window.get_geometry()
self._x = g.x
self._y = g.y
self._width = g.width
self._height = g.height
self._depth = g.depth
except xcffib.xproto.DrawableError:
# Whoops, we were too early, so let's ignore it for now and get the
# values on demand.
self._x = None
self._y = None
self._width = None
self._height = None
self._depth = None
self.float_x: Optional[int] = None
self.float_y: Optional[int] = None
self._float_width: int = self._width
self._float_height: int = self._height
self.bordercolor = None
self.state = NormalState
self._float_state = FloatStates.NOT_FLOATING
self._demands_attention = False
self.hints = {
'input': True,
'icon_pixmap': None,
'icon_window': None,
'icon_x': 0,
'icon_y': 0,
'icon_mask': 0,
'window_group': None,
'urgent': False,
# normal or size hints
'width_inc': None,
'height_inc': None,
'base_width': 0,
'base_height': 0,
}
self.update_hints()
x = property(fset=_geometry_setter("x"), fget=_geometry_getter("x"))
y = property(fset=_geometry_setter("y"), fget=_geometry_getter("y"))
width = property(
fset=_geometry_setter("width"),
fget=_geometry_getter("width"),
)
height = property(
fset=_geometry_setter("height"),
fget=_geometry_getter("height"),
)
depth = property(
fset=_geometry_setter("depth"),
fget=_geometry_getter("depth"),
)
@property
def wid(self):
return self.window.wid
@property
def group(self):
return self._group
def has_fixed_ratio(self) -> bool:
try:
if ('PAspect' in self.hints['flags'] and
self.hints["min_aspect"] == self.hints["max_aspect"]):
return True
except KeyError:
pass
return False
def has_fixed_size(self) -> bool:
try:
if ('PMinSize' in self.hints['flags'] and
'PMaxSize' in self.hints['flags'] and
0 < self.hints["min_width"] == self.hints["max_width"] and
0 < self.hints["min_height"] == self.hints["max_height"]):
return True
except KeyError:
pass
return False
def has_user_set_position(self):
try:
if 'USPosition' in self.hints['flags'] or 'PPosition' in self.hints['flags']:
return True
except KeyError:
pass
return False
def update_name(self):
try:
self.name = self.window.get_name()
except (xcffib.xproto.WindowError, xcffib.xproto.AccessError):
return
hook.fire('client_name_updated', self)
def get_wm_class(self):
return self.window.get_wm_class()
def get_wm_type(self):
return self.window.get_wm_type()
def get_wm_role(self):
return self.window.get_wm_window_role()
def is_transient_for(self):
"""What window is this window a transient windor for?"""
wid = self.window.get_wm_transient_for()
return self.qtile.windows_map.get(wid)
def update_hints(self):
"""Update the local copy of the window's WM_HINTS
See http://tronche.com/gui/x/icccm/sec-4.html#WM_HINTS
"""
try:
h = self.window.get_wm_hints()
normh = self.window.get_wm_normal_hints()
except (xcffib.xproto.WindowError, xcffib.xproto.AccessError):
return
if normh:
self.hints.update(normh)
if h and 'UrgencyHint' in h['flags']:
if self.qtile.current_window != self:
self.hints['urgent'] = True
hook.fire('client_urgent_hint_changed', self)
elif self.urgent:
self.hints['urgent'] = False
hook.fire('client_urgent_hint_changed', self)
if h and 'InputHint' in h['flags']:
self.hints['input'] = h['input']
if getattr(self, 'group', None):
if self.group.floating_layout.match(self):
self.floating = True
self.group.layout_all()
return
def update_state(self):
triggered = ['urgent']
if self.qtile.config.auto_fullscreen:
triggered.append('fullscreen')
state = self.window.get_net_wm_state()
for s in triggered:
setattr(self, s, (s in state))
@property
def urgent(self):
return self.hints['urgent'] or self._demands_attention
@urgent.setter
def urgent(self, val):
self._demands_attention = val
# TODO unset window hint as well?
if not val:
self.hints['urgent'] = False
def info(self):
if self.group:
group = self.group.name
else:
group = None
float_info = {
"x": self.float_x,
"y": self.float_y,
"width": self._float_width,
"height": self._float_height,
}
return dict(
name=self.name,
x=self.x,
y=self.y,
width=self.width,
height=self.height,
group=group,
id=self.window.wid,
floating=self._float_state != FloatStates.NOT_FLOATING,
float_info=float_info,
maximized=self._float_state == FloatStates.MAXIMIZED,
minimized=self._float_state == FloatStates.MINIMIZED,
fullscreen=self._float_state == FloatStates.FULLSCREEN
)
@property
def state(self):
return self.window.get_wm_state()[0]
@state.setter
def state(self, val):
if val in (WithdrawnState, NormalState, IconicState):
self.window.set_property('WM_STATE', [val, 0])
@property
def opacity(self):
assert hasattr(self, "window")
opacity = self.window.get_property(
"_NET_WM_WINDOW_OPACITY", unpack=int
)
if not opacity:
return 1.0
else:
value = opacity[0]
# 2 decimal places
as_float = round(value / 0xffffffff, 2)
return as_float
@opacity.setter
def opacity(self, opacity: float) -> None:
if 0.0 <= opacity <= 1.0:
real_opacity = int(opacity * 0xffffffff)
assert hasattr(self, "window")
self.window.set_property('_NET_WM_WINDOW_OPACITY', real_opacity)
def kill(self):
if "WM_DELETE_WINDOW" in self.window.get_wm_protocols():
data = [
self.qtile.core.conn.atoms["WM_DELETE_WINDOW"],
xcffib.xproto.Time.CurrentTime,
0,
0,
0
]
u = xcffib.xproto.ClientMessageData.synthetic(data, "I" * 5)
e = xcffib.xproto.ClientMessageEvent.synthetic(
format=32,
window=self.window.wid,
type=self.qtile.core.conn.atoms["WM_PROTOCOLS"],
data=u
)
self.window.send_event(e)
else:
self.window.kill_client()
self.qtile.core.conn.flush()
def hide(self):
# We don't want to get the UnmapNotify for this unmap
with self.disable_mask(EventMask.StructureNotify):
with self.qtile.core.disable_unmap_events():
self.window.unmap()
self.hidden = True
def unhide(self):
self.window.map()
self.state = NormalState
self.hidden = False
@contextlib.contextmanager
def disable_mask(self, mask):
self._disable_mask(mask)
yield
self._reset_mask()
def _disable_mask(self, mask):
self.window.set_attribute(
eventmask=self._window_mask & (~mask)
)
def _reset_mask(self):
self.window.set_attribute(
eventmask=self._window_mask
)
def _grab_click(self):
# Grab button 1 to focus upon click when unfocussed
for amask in self.qtile.core._auto_modmasks():
self.qtile.core.conn.conn.core.GrabButton(
True,
self.window.wid,
EventMask.ButtonPress,
xcffib.xproto.GrabMode.Sync,
xcffib.xproto.GrabMode.Async,
xcffib.xproto.Atom._None,
xcffib.xproto.Atom._None,
1,
amask,
)
def _ungrab_click(self):
# Ungrab button 1 when focussed
self.qtile.core.conn.conn.core.UngrabButton(
xcffib.xproto.Atom.Any,
self.window.wid,
xcffib.xproto.ModMask.Any,
)
def get_pid(self):
return self.window.get_net_wm_pid()
def place(self, x, y, width, height, borderwidth, bordercolor,
above=False, margin=None, respect_hints=False):
"""
Places the window at the specified location with the given size.
Parameters
==========
x: int
y: int
width: int
height: int
borderwidth: int
bordercolor: string
above: bool, optional
margin: int or list, optional
space around window as int or list of ints [N E S W]
above: bool, optional
If True, the geometry will be adjusted to respect hints provided by the
client.
"""
# TODO: self.x/y/height/width are updated BEFORE
# place is called, so there's no way to know if only
# the position is changed, so we are sending
# the ConfigureNotify every time place is called
#
# # if position change and size don't
# # send a configure notify. See ICCCM 4.2.3
# send_notify = False
# if (self.x != x or self.y != y) and \
# (self.width == width and self.height == height):
# send_notify = True
# #for now, we just:
send_notify = True
# Adjust the placement to account for layout margins, if there are any.
if margin is not None:
if isinstance(margin, int):
margin = [margin] * 4
x += margin[3]
y += margin[0]
width -= margin[1] + margin[3]
height -= margin[0] + margin[2]
# Optionally adjust geometry to respect client hints
if respect_hints:
flags = self.hints.get("flags", {})
if "PMinSize" in flags:
width = max(width, self.hints.get('min_width', 0))
height = max(height, self.hints.get('min_height', 0))
if "PMaxSize" in flags:
width = min(width, self.hints.get('max_width', 0)) or width
height = min(height, self.hints.get('max_height', 0)) or height
if "PAspect" in flags and self._float_state == FloatStates.FLOATING:
min_aspect = self.hints["min_aspect"]
max_aspect = self.hints["max_aspect"]
if width / height < min_aspect[0] / min_aspect[1]:
height = width * min_aspect[1] // min_aspect[0]
elif width / height > max_aspect[0] / max_aspect[1]:
height = width * max_aspect[1] // max_aspect[0]
if self.hints['base_width'] and self.hints['width_inc']:
width_adjustment = (width - self.hints['base_width']) % self.hints['width_inc']
width -= width_adjustment
if self.fullscreen:
x += int(width_adjustment / 2)
if self.hints['base_height'] and self.hints['height_inc']:
height_adjustment = (height - self.hints['base_height']) % self.hints['height_inc']
height -= height_adjustment
if self.fullscreen:
y += int(height_adjustment / 2)
# save x and y float offset
if self.group is not None and self.group.screen is not None:
self.float_x = x - self.group.screen.x
self.float_y = y - self.group.screen.y
self.x = x
self.y = y
self.width = width
self.height = height
kwarg = dict(
x=x,
y=y,
width=width,
height=height,
)
if above:
kwarg['stackmode'] = StackMode.Above
self.window.configure(**kwarg)
self.paint_borders(bordercolor, borderwidth)
if send_notify:
self.send_configure_notify(x, y, width, height)
def paint_borders(self, color, width):
self.borderwidth = width
self.bordercolor = color
self.window.configure(borderwidth=width)
self.window.paint_borders(self.depth, color, width, self.width, self.height)
def send_configure_notify(self, x, y, width, height):
"""Send a synthetic ConfigureNotify"""
window = self.window.wid
above_sibling = False
override_redirect = False
event = xcffib.xproto.ConfigureNotifyEvent.synthetic(
event=window,
window=window,
above_sibling=above_sibling,
x=x,
y=y,
width=width,
height=height,
border_width=self.borderwidth,
override_redirect=override_redirect
)
self.window.send_event(event, mask=EventMask.StructureNotify)
@property
def can_steal_focus(self):
return self.window.get_wm_type() != 'notification'
def _do_focus(self):
"""
Focus the window if we can, and return whether or not it was successful.
"""
# don't focus hidden windows, they should be mapped. this is generally
# a bug somewhere in the qtile code, but some of the tests do it, so we
# just have to let it slide for now.
if self.hidden:
return False
# if the window can be focused, just focus it.
if self.hints['input']:
self.window.set_input_focus()
return True
# does the window want us to ask it about focus?
if "WM_TAKE_FOCUS" in self.window.get_wm_protocols():
data = [
self.qtile.core.conn.atoms["WM_TAKE_FOCUS"],
# The timestamp here must be a valid timestamp, not CurrentTime.
#
# see https://tronche.com/gui/x/icccm/sec-4.html#s-4.1.7
# > Windows with the atom WM_TAKE_FOCUS in their WM_PROTOCOLS
# > property may receive a ClientMessage event from the
# > window manager (as described in section 4.2.8) with
# > WM_TAKE_FOCUS in its data[0] field and a valid timestamp
# > (i.e. not *CurrentTime* ) in its data[1] field.
self.qtile.core.get_valid_timestamp(),
0,
0,
0
]
u = xcffib.xproto.ClientMessageData.synthetic(data, "I" * 5)
e = xcffib.xproto.ClientMessageEvent.synthetic(
format=32,
window=self.window.wid,
type=self.qtile.core.conn.atoms["WM_PROTOCOLS"],
data=u
)
self.window.send_event(e)
# we didn't focus this time. but now the window knows if it wants
# focus, it should SetFocus() itself; we'll get another notification
# about this.
return False
def focus(self, warp: bool) -> None:
did_focus = self._do_focus()
if not did_focus:
return
if isinstance(self, base.Internal):
# self._do_focus is enough for internal windows
return
# now, do all the other WM stuff since the focus actually changed
if warp and self.qtile.config.cursor_warp:
self.window.warp_pointer(self.width // 2, self.height // 2)
if self.urgent:
self.urgent = False
atom = self.qtile.core.conn.atoms["_NET_WM_STATE_DEMANDS_ATTENTION"]
state = list(self.window.get_property('_NET_WM_STATE', 'ATOM', unpack=int))
if atom in state:
state.remove(atom)