Repository navigation
Expand file tree
/
Copy pathei.py
More file actions
1321 lines (1076 loc) · 48.4 KB
/
Copy pathei.py
File metadata and controls
1321 lines (1076 loc) · 48.4 KB
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
"""Pythonic wrapper around libei -- the EI *client* library.
An EI client is either a :class:`Sender` (injects input -- what a remote-
control or automation client wants) or a :class:`Receiver` (consumes input
-- what a compositor implementation wants). Both are :class:`Context`
subclasses.
Typical sender usage. Note the ``dispatch()`` call: :attr:`Context.events`
drains only what is already queued, so it yields nothing until
``dispatch()`` has read from the connection::
ctx = Sender.create_for_fd(eis_fd, name="my-app")
device = None
while device is None:
ctx.dispatch()
for event in ctx.events:
if event.event_type is EventType.SEAT_ADDED:
event.seat.bind((DeviceCapability.POINTER,))
elif event.event_type is EventType.DEVICE_RESUMED:
device = event.device
device.start_emulating().pointer_motion(5, 0).frame().stop_emulating()
Wait for ``DEVICE_RESUMED``, not ``DEVICE_ADDED``: a device arrives paused,
and libei calls sending events before it resumes "a client bug".
A real client should ``select()`` on :attr:`Context.fd` rather than
spinning, and give up after a timeout; see the README for that form.
Keys are raw Linux evdev keycodes -- key *positions*, not characters, and
no character or keysym mapping happens here. To type text under the user's
actual layout, either read :attr:`Device.keymap` and resolve through it
(e.g. with ``xkbcommon``), or use :meth:`Device.text_utf8` where libei 1.6
is available and the device has :attr:`DeviceCapability.TEXT`.
"""
from __future__ import annotations
import contextlib
import dataclasses
import enum
import itertools
import logging
import os
from collections.abc import Iterator
from ctypes import byref, c_double, c_int, c_void_p
from pathlib import Path
from typing import IO, TypeVar
from . import _capi
from ._capi.libei import log_handler_t
from ._capi.loader import LibraryNotFoundError
from ._cobject import CObject
logger = logging.getLogger("libei.ei")
# Process-wide rather than per-Device, deliberately. libei requires the
# emulation sequence to increase on every ei_device_start_emulating() call
# for a given device; a counter stored on the Python wrapper would restart
# at 1 whenever that wrapper was garbage-collected and later rebuilt from
# the same C pointer, repeating sequence numbers for a device that is very
# much still alive. Sharing one counter across all devices trivially
# satisfies the per-device requirement and has no such lifetime coupling.
# itertools.count().__next__ is atomic under CPython, so no lock is needed.
_emulating_sequence = itertools.count(1)
def _next_emulating_sequence() -> int:
"""The next emulating-event sequence number: 32-bit, and never 0."""
# Masked into uint32 to match the C parameter. libei asks callers to
# keep wraparound detection "reasonable"; skipping 0 keeps the value
# away from anything that might read as unset.
return (next(_emulating_sequence) % 0xFFFFFFFF) + 1
def is_available() -> bool:
"""Whether libei.so.1 can be loaded on this system."""
return _capi.libei.lib.is_available()
class Error(Exception):
"""A libei call failed.
``errno`` is the positive errno where libei reported one (its setup
functions return a negative errno rather than setting the global), and
``None`` where the failure was a NULL return with no code attached.
"""
def __init__(self, message: str, errno: int | None = None) -> None:
"""Record the failure message and, where libei reported one, errno."""
super().__init__(message)
self.message = message
self.errno = errno
class EventType(enum.IntEnum):
"""Mirrors ``enum ei_event_type`` from libei.h.
libei's own docs say this enum "is not exhaustive, future versions of
this library may add new event types" and that unknown events must
still be released with ``ei_event_unref()``. :attr:`Event.event_type`
honors that: a value not listed here is returned as a plain ``int``
rather than raising.
"""
CONNECT = 1
DISCONNECT = 2
SEAT_ADDED = 3
SEAT_REMOVED = 4
DEVICE_ADDED = 5
DEVICE_REMOVED = 6
DEVICE_PAUSED = 7
DEVICE_RESUMED = 8
KEYBOARD_MODIFIERS = 9
PONG = 90
SYNC = 91
FRAME = 100
DEVICE_START_EMULATING = 200
DEVICE_STOP_EMULATING = 201
POINTER_MOTION = 300
POINTER_MOTION_ABSOLUTE = 400
BUTTON_BUTTON = 500
SCROLL_DELTA = 600
SCROLL_STOP = 601
SCROLL_CANCEL = 602
SCROLL_DISCRETE = 603
KEYBOARD_KEY = 700
TOUCH_DOWN = 800
TOUCH_UP = 801
TOUCH_MOTION = 802
TEXT_KEYSYM = 900
TEXT_UTF8 = 901
# Everything below exists on libei's main branch but in NO released
# version -- 1.6.0's enum ei_event_type stops at EI_EVENT_TEXT_UTF8.
# The values match upstream main exactly, so they are ready for the
# release that adds them, but no shipping library can send these and
# this package binds none of main's gesture/stylus accessors (nothing
# released exports them to verify against). See docs/vs-snegg.md.
SWIPE_BEGIN = 1000
SWIPE_UPDATE = 1001
SWIPE_END = 1002
SWIPE_ABORTED = 1003
PINCH_BEGIN = 1010
PINCH_UPDATE = 1011
PINCH_END = 1012
PINCH_ABORTED = 1013
HOLD_BEGIN = 1020
HOLD_END = 1021
HOLD_ABORTED = 1022
STYLUS_PROXIMITY_IN = 1101
STYLUS_PROXIMITY_OUT = 1102
STYLUS_ERASE_START = 1103
STYLUS_ERASE_STOP = 1104
STYLUS_TIP_DOWN = 1105
STYLUS_TIP_UP = 1106
STYLUS_AXIS = 1107
class DeviceCapability(enum.IntFlag):
"""Mirrors ``enum ei_device_capability`` from libei.h.
An :class:`enum.IntFlag` so callers can talk about sets of them, but
note that libei's own functions never take an OR'd mask -- see
:meth:`Seat.bind`, which passes one value per vararg.
"""
POINTER = 1 << 0
POINTER_ABSOLUTE = 1 << 1
KEYBOARD = 1 << 2
TOUCH = 1 << 3
SCROLL = 1 << 4
BUTTON = 1 << 5
TEXT = 1 << 6
# On libei's main branch only: 1.6.0's enum ei_device_capability
# stops at TEXT. Binding one of these against a released library is a
# silent noop -- no error, no device.
GESTURES = 1 << 7
STYLUS = 1 << 8
class DeviceType(enum.IntEnum):
"""Whether a device is synthesised or backed by real hardware."""
VIRTUAL = 1
PHYSICAL = 2
class KeymapType(enum.IntEnum):
"""Keymap format. libei defines exactly one."""
XKB = 1
class _LogPriority(enum.IntEnum):
"""The log levels, as the integers the C library passes to its handler."""
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
@dataclasses.dataclass(frozen=True, slots=True)
class XkbModifiersEvent:
"""XKB modifier state from a KEYBOARD_MODIFIERS event.
``depressed``/``latched``/``locked`` are XKB's own mod-state bitmasks;
``group`` is the active keyboard layout group.
"""
depressed: int
latched: int
locked: int
group: int
@dataclasses.dataclass(frozen=True, slots=True)
class KeyEvent:
"""Key code and press state from a KEYBOARD_KEY event.
``key`` is a Linux ``KEY_*`` code, the same numbering
:meth:`Device.keyboard_key` sends.
"""
key: int
is_press: bool
@dataclasses.dataclass(frozen=True, slots=True)
class ButtonEvent:
"""Button code and press state from a BUTTON_BUTTON event.
``button`` is a Linux ``BTN_*`` code, the same numbering
:meth:`Device.button` sends.
"""
button: int
is_press: bool
@dataclasses.dataclass(frozen=True, slots=True)
class PointerEvent:
"""Relative motion deltas, in logical pixels, from a POINTER_MOTION event."""
dx: float
dy: float
@dataclasses.dataclass(frozen=True, slots=True)
class PointerAbsoluteEvent:
"""Absolute position from a POINTER_MOTION_ABSOLUTE event.
In the logical pixel space of the :class:`Region` the emitting device
covers -- see :meth:`Event.pointer_absolute_event`.
"""
x: float
y: float
@dataclasses.dataclass(frozen=True, slots=True)
class ScrollEvent:
"""Smooth scroll deltas from a SCROLL_DELTA event."""
dx: float
dy: float
@dataclasses.dataclass(frozen=True, slots=True)
class ScrollDiscreteEvent:
"""Detent scroll deltas (120 per detent) from a SCROLL_DISCRETE event."""
dx: int
dy: int
@dataclasses.dataclass(frozen=True, slots=True)
class ScrollStopEvent:
"""Which axes stopped scrolling, from a SCROLL_STOP/SCROLL_CANCEL event."""
stop_x: bool
stop_y: bool
@dataclasses.dataclass(frozen=True, slots=True)
class TouchEvent:
"""Touch id and position from a TOUCH_DOWN or TOUCH_MOTION event."""
touchid: int
x: float
y: float
@dataclasses.dataclass(frozen=True, slots=True)
class TouchUpEvent:
"""Touch id and cancellation flag from a TOUCH_UP event.
See :meth:`Event.touch_up_event` for when ``is_cancel`` is trustworthy.
"""
touchid: int
is_cancel: bool
@dataclasses.dataclass(frozen=True, slots=True)
class TextUtf8Event:
"""UTF-8 text carried by a TEXT_UTF8 event."""
text: str
@dataclasses.dataclass(frozen=True, slots=True)
class TextKeysymEvent:
"""Keysym and press state from a TEXT_KEYSYM event."""
keysym: int
is_press: bool
class Region(CObject):
"""A rectangular area of the desktop an absolute device maps onto.
A device with :attr:`DeviceCapability.POINTER_ABSOLUTE` or ``TOUCH``
covers one or more regions, and the coordinates passed to
:meth:`Device.pointer_motion_absolute` are in the desktop-wide logical
pixel space those regions sit in -- not relative to any one of them.
Use :meth:`convert_point` to go the other way.
"""
_ref_func = staticmethod(_capi.libei.region_ref)
_unref_func = staticmethod(_capi.libei.region_unref)
def __repr__(self) -> str:
"""The size and position, as WxH+X+Y."""
w, h = self.dimension
x, y = self.position
return f"<Region {w}x{h}+{x}+{y}>"
@property
def position(self) -> tuple[int, int]:
"""Top-left corner of the region, in logical pixels."""
return (
_capi.libei.region_get_x(self),
_capi.libei.region_get_y(self),
)
@property
def dimension(self) -> tuple[int, int]:
"""Width and height of the region, in logical pixels."""
return (
_capi.libei.region_get_width(self),
_capi.libei.region_get_height(self),
)
@property
def physical_scale(self) -> float:
"""Scale between logical pixels and this region's physical size."""
return _capi.libei.region_get_physical_scale(self)
@property
def mapping_id(self) -> str | None:
"""Identifier shared by regions that map to the same thing.
``None`` where the server set none. Requires libei 1.1.
"""
raw = _capi.libei.region_get_mapping_id(self)
return None if raw is None else raw.decode("utf-8")
def convert_point(self, x: float, y: float) -> tuple[float, float] | None:
"""Convert a desktop-wide point to one relative to this region.
Returns the point with the region's offset subtracted, or ``None``
if it falls outside the region -- which is also how you test
membership without a second :meth:`contains` call.
"""
# x/y are in-out parameters: libei overwrites them only when the
# point is inside, so the return value has to gate reading them.
cx, cy = c_double(x), c_double(y)
if not _capi.libei.region_convert_point(self, byref(cx), byref(cy)):
return None
return (cx.value, cy.value)
def contains(self, x: float, y: float) -> bool:
"""Whether the given logical-pixel point falls inside this region."""
return bool(_capi.libei.region_contains(self, x, y))
class Keymap(CObject):
"""The XKB keymap the server has assigned to a keyboard device.
Read :attr:`fd` and :attr:`size` to feed it to ``xkbcommon`` and work
out which keycode produces a given character -- see the module
docstring on why keycodes are positions rather than characters.
"""
_ref_func = staticmethod(_capi.libei.keymap_ref)
_unref_func = staticmethod(_capi.libei.keymap_unref)
@property
def keymap_type(self) -> KeymapType:
"""Keymap format; currently always XKB."""
return KeymapType(_capi.libei.keymap_get_type(self))
@property
def size(self) -> int:
"""Size of the keymap data, in bytes."""
return _capi.libei.keymap_get_size(self)
@property
def fd(self) -> IO[bytes]:
"""Memmap-able file descriptor holding the keymap data.
A fresh duplicate on each read, which the caller owns and should
close; the keymap keeps its own. Rewound to position 0 where the
fd allows it, so the data is simply readable.
"""
# ei_keymap_get_fd() is a plain field read; the keymap still owns
# that fd. os.fdopen() would make the returned file object close
# it, so duplicate it and hand out the copy.
raw_fd = _capi.libei.keymap_get_fd(self)
if raw_fd < 0:
# Without this, os.dup(-1) surfaces as a bare EBADF that says
# nothing about which object failed.
raise Error("ei_keymap_get_fd() reported no usable file descriptor")
duplicate = os.dup(raw_fd)
# dup(2) shares the file offset with the original, and libei's own
# fd is normally sitting at EOF -- reading straight from the copy
# returned zero bytes and no error, which looks exactly like an
# empty keymap. Rewind the copy; the offset is shared, so this
# also rewinds libei's, which is harmless for a memfd it only ever
# mmaps. A keymap fd is documented as memmap-able and so always
# seekable, but tolerate one that isn't rather than turning a
# readable fd into an exception.
with contextlib.suppress(OSError):
os.lseek(duplicate, 0, os.SEEK_SET)
return os.fdopen(duplicate, "rb")
@property
def device(self) -> Device:
"""The device this keymap belongs to."""
device = Device.wrap(_capi.libei.keymap_get_device(self))
# wrap() is typed `T | None` because the C API's getters may
# return NULL in general; this one is documented never to. The
# assert is here to narrow the type for mypy, not to enforce an
# invariant -- under `python -O` it vanishes and a surprise NULL
# surfaces as an AttributeError on None at the caller, which is
# survivable. Contrast _cobject.py's cross-class pointer check,
# which guards memory safety and so is a real `raise`. Every
# other `assert ... is not None` in this module is the same
# narrowing idiom.
assert device is not None
return device
class Touch(CObject):
"""One touch point, from :meth:`Device.touch_new` to up or cancel.
Created per touch rather than per device, so several can be in flight
at once for a multi-touch gesture. Like the :class:`Device` methods,
the calls here only queue -- :meth:`Device.frame` commits them.
"""
_unref_func = staticmethod(_capi.libei.touch_unref)
@property
def device(self) -> Device:
"""The device this touch belongs to."""
device = Device.wrap(_capi.libei.touch_get_device(self))
assert device is not None
return device
def down(self, x: float, y: float) -> Touch:
"""Begin the touch at the given point."""
_capi.libei.touch_down(self, x, y)
return self
def motion(self, x: float, y: float) -> Touch:
"""Move the in-progress touch to the given point."""
_capi.libei.touch_motion(self, x, y)
return self
def up(self) -> Touch:
"""End the touch."""
_capi.libei.touch_up(self)
return self
def cancel(self) -> Touch:
"""End the touch as cancelled rather than logically released.
Requires libei 1.4. It also needs version 2 or later of the
``ei_touchscreen`` interface on both sides -- against an older EIS
implementation the call succeeds but arrives as a plain release.
"""
_capi.libei.touch_cancel(self)
return self
class Device(CObject):
"""An input device the server has handed this client.
Never constructed directly: ask for capabilities with
:meth:`Seat.bind`, then take the device off the DEVICE_ADDED event and
wait for DEVICE_RESUMED before sending anything.
The sending methods queue an event and return ``self``, so a whole
input sequence chains: :meth:`start_emulating`, the events themselves,
:meth:`frame` to commit them as one logical hardware event, then
:meth:`stop_emulating`.
"""
_ref_func = staticmethod(_capi.libei.device_ref)
_unref_func = staticmethod(_capi.libei.device_unref)
def __repr__(self) -> str:
"""Name, device type and capabilities -- what tells two devices apart."""
caps = "|".join(c.name or str(c.value) for c in self.capabilities)
return f"<Device {self.name!r} {self.device_type.name} {caps}>"
@property
def device_type(self) -> DeviceType:
"""Whether the device is virtual or represents real hardware."""
return DeviceType(_capi.libei.device_get_type(self))
@property
def name(self) -> str:
"""The device name assigned by the server."""
return _capi.libei.device_get_name(self).decode("utf-8")
@property
def width(self) -> int:
"""Device width in logical pixels; 0 if unsized."""
return _capi.libei.device_get_width(self)
@property
def height(self) -> int:
"""Device height in logical pixels; 0 if unsized."""
return _capi.libei.device_get_height(self)
@property
def capabilities(self) -> tuple[DeviceCapability, ...]:
"""The capabilities this object actually has."""
return tuple(
c for c in DeviceCapability if _capi.libei.device_has_capability(self, c)
)
@property
def regions(self) -> tuple[Region, ...]:
"""The device's regions, in index order."""
regions = []
index = 0
while True:
pointer = _capi.libei.device_get_region(self, index)
if not pointer:
break
region = Region.wrap(pointer)
assert region is not None
regions.append(region)
index += 1
return tuple(regions)
@property
def seat(self) -> Seat:
"""The seat this device belongs to."""
seat = Seat.wrap(_capi.libei.device_get_seat(self))
assert seat is not None
return seat
@property
def keymap(self) -> Keymap | None:
"""The device's keymap, or None if it has no keyboard capability."""
return Keymap.wrap(_capi.libei.device_keyboard_get_keymap(self))
def close(self) -> None:
"""Ask the server to remove this device."""
_capi.libei.device_close(self)
def start_emulating(self, sequence: int | None = None) -> Device:
"""Begin an emulation transaction; pair with :meth:`stop_emulating`.
``sequence`` identifies the transaction and, per libei, "must go up
by at least 1 on each call". The default draws from a process-wide
counter that satisfies that for every device.
"""
if sequence is None:
sequence = _next_emulating_sequence()
_capi.libei.device_start_emulating(self, sequence)
return self
def stop_emulating(self) -> Device:
"""End the transaction opened by :meth:`start_emulating`."""
_capi.libei.device_stop_emulating(self)
return self
def frame(self, timestamp: int | None = None) -> Device:
"""Commit the events queued since the last frame as one logical hardware event.
``timestamp`` defaults to the context's current time.
"""
if timestamp is None:
timestamp = _capi.libei.now(_capi.libei.device_get_context(self))
_capi.libei.device_frame(self, timestamp)
return self
def pointer_motion(self, dx: float, dy: float) -> Device:
"""Queue a relative pointer motion, in logical pixels."""
_capi.libei.device_pointer_motion(self, dx, dy)
return self
def pointer_motion_absolute(self, x: float, y: float) -> Device:
"""Queue an absolute pointer motion, in the device's region."""
_capi.libei.device_pointer_motion_absolute(self, x, y)
return self
def button(self, button: int, is_press: bool) -> Device:
"""Queue a button press or release.
``button`` is a Linux ``BTN_*`` code (e.g. ``0x110`` for ``BTN_LEFT``).
"""
_capi.libei.device_button_button(self, button, is_press)
return self
def keyboard_key(self, key: int, is_press: bool) -> Device:
"""Queue a key press or release, by Linux ``KEY_*`` keycode."""
_capi.libei.device_keyboard_key(self, key, is_press)
return self
def scroll_delta(self, dx: float, dy: float) -> Device:
"""Queue a smooth scroll, in logical pixels."""
_capi.libei.device_scroll_delta(self, dx, dy)
return self
def scroll_discrete(self, dx: int, dy: int) -> Device:
"""Queue a discrete (detent) scroll; one detent is 120."""
_capi.libei.device_scroll_discrete(self, dx, dy)
return self
def scroll_stop(self, stop_x: bool, stop_y: bool) -> Device:
"""Signal that scrolling has stopped on the given axes."""
_capi.libei.device_scroll_stop(self, stop_x, stop_y)
return self
def scroll_cancel(self, cancel_x: bool, cancel_y: bool) -> Device:
"""Signal that scroll kinetics are cancelled on the given axes."""
_capi.libei.device_scroll_cancel(self, cancel_x, cancel_y)
return self
def region_at(self, x: float, y: float) -> Region | None:
"""The region containing this desktop-wide point, or None.
Requires libei 1.1.
"""
return Region.wrap(_capi.libei.device_get_region_at(self, x, y))
def text_utf8(self, text: str) -> Device:
"""Send text directly, for a device with the TEXT capability.
The compositor turns this into whatever key events its own layout
needs -- the one path here that types *characters* rather than key
positions. Requires libei 1.6 on both sides, and is silently
ignored by a device without :attr:`DeviceCapability.TEXT`.
"""
# Encoded here and passed with an explicit length: the plain
# ei_device_text_utf8() takes a NUL-terminated string, which would
# silently truncate a str containing a NUL.
data = text.encode("utf-8")
_capi.libei.device_text_utf8_with_length(self, data, len(data))
return self
def text_keysym(self, keysym: int, is_press: bool) -> Device:
"""Send an XKB keysym, for a device with the TEXT capability.
Requires libei 1.6 on both sides.
"""
_capi.libei.device_text_keysym(self, keysym, is_press)
return self
def touch_new(self) -> Touch:
"""Start a new touch on a device with the TOUCH capability."""
pointer = _capi.libei.device_touch_new(self)
if not pointer:
raise Error("ei_device_touch_new() returned NULL")
touch = Touch.adopt(pointer)
assert touch is not None
return touch
class Seat(CObject):
"""A group of devices the server offers, arriving as SEAT_ADDED.
A seat advertises capabilities; :meth:`bind` asks for the ones you
want, and the server answers with devices.
"""
_ref_func = staticmethod(_capi.libei.seat_ref)
_unref_func = staticmethod(_capi.libei.seat_unref)
def __repr__(self) -> str:
"""The seat's name and capabilities."""
caps = "|".join(c.name or str(c.value) for c in self.capabilities)
return f"<Seat {self.name!r} {caps}>"
@property
def name(self) -> str:
"""The seat name assigned by the server."""
return _capi.libei.seat_get_name(self).decode("utf-8")
@property
def capabilities(self) -> tuple[DeviceCapability, ...]:
"""The capabilities this object actually has."""
return tuple(
c for c in DeviceCapability if _capi.libei.seat_has_capability(self, c)
)
def bind(self, capabilities: tuple[DeviceCapability, ...]) -> None:
"""Request these capabilities from the seat.
The server responds by adding matching devices, surfacing as
DEVICE_ADDED events. Raises :class:`ValueError` if given no
capabilities: that would send nothing, and the caller would wait
for devices that are never coming.
"""
if not capabilities:
raise ValueError(
"bind() needs at least one capability; binding an empty set "
"sends nothing and no DEVICE_ADDED event will ever arrive"
)
# ei_seat_bind_capabilities is variadic, one *individual* capability
# value per vararg, sentinel-terminated -- the C side reads them
# with va_arg and switches on each exact value. Passing a single
# OR'd mask (e.g. POINTER|KEYBOARD) matches no case, silently binds
# nothing, and the caller hangs waiting for DEVICE_ADDED.
_capi.libei.seat_bind_capabilities(
self, *(c_int(c) for c in capabilities), c_int(0)
)
def request_device(self, capabilities: tuple[DeviceCapability, ...]) -> None:
"""Ask for another device with (a subset of) these capabilities.
For when the devices you have are no longer enough -- after
:meth:`Device.close`, say. The capabilities must be a subset of
what :meth:`bind` asked for, the server may answer with a device
whose capabilities differ, and it may not answer at all. Any
device it does create arrives as a DEVICE_ADDED event.
Requires libei 1.6. Raises :class:`ValueError` if given no
capabilities, for the same reason as :meth:`bind`.
"""
if not capabilities:
raise ValueError("request_device() needs at least one capability")
# Variadic and sentinel-terminated, exactly like bind() above --
# one capability per vararg, never an OR'd mask.
_capi.libei.seat_request_device_with_capabilities(
self, *(c_int(c) for c in capabilities), c_int(0)
)
def unbind(self, capabilities: tuple[DeviceCapability, ...]) -> None:
"""Release previously bound capabilities on this seat.
Raises :class:`ValueError` if given no capabilities, for the same
reason as :meth:`bind`.
"""
if not capabilities:
raise ValueError("unbind() needs at least one capability")
_capi.libei.seat_unbind_capabilities(
self, *(c_int(c) for c in capabilities), c_int(0)
)
class Ping(CObject):
"""A round trip to the EIS implementation, answered by a PONG event.
Create one with :meth:`Context.new_ping`, call :meth:`send`, then watch
for :attr:`EventType.PONG` and compare :attr:`Event.pong` against this
object (or its :attr:`id`). Requires libei 1.4.
"""
_ref_func = staticmethod(_capi.libei.ping_ref)
_unref_func = staticmethod(_capi.libei.ping_unref)
def __repr__(self) -> str:
"""The ping's id, which is all a ping carries."""
return f"<Ping {self.id}>"
@property
def id(self) -> int:
"""The identifier libei assigned to this round trip."""
return _capi.libei.ping_get_id(self)
def send(self) -> Ping:
"""Start the round trip. The reply arrives as a PONG event."""
_capi.libei.ping(self)
return self
class Event(CObject):
"""One event from :attr:`Context.events`.
:attr:`event_type` says which of the typed accessors below is valid;
reading the wrong one raises :class:`TypeError` rather than returning
the zeroes libei would hand back (see :meth:`_require`).
Valid only for the loop iteration that yielded it --
:attr:`Context.events` releases each event as it resumes.
"""
_unref_func = staticmethod(_capi.libei.event_unref)
def __repr__(self) -> str:
"""The event type by name, or the raw value for one we do not model."""
event_type = self.event_type
label = event_type.name if isinstance(event_type, EventType) else event_type
return f"<Event {label}>"
@property
def event_type(self) -> EventType | int:
"""The event's type.
Returns a raw int for a value newer than this package's
:class:`EventType` table -- see its docstring.
"""
raw = _capi.libei.event_get_type(self)
try:
return EventType(raw)
except ValueError:
return raw
@property
def time(self) -> int:
"""Event timestamp in microseconds, in the context's clock domain."""
return _capi.libei.event_get_time(self)
@property
def device(self) -> Device | None:
"""The device this event concerns, or None if it has none."""
return Device.wrap(_capi.libei.event_get_device(self))
@property
def seat(self) -> Seat | None:
"""The seat this event concerns, or None if it has none.
Connect/disconnect events carry no seat.
"""
return Seat.wrap(_capi.libei.event_get_seat(self))
def _require(self, getter: str, *valid: EventType) -> None:
"""Raise unless this event is one of ``valid``.
libei's accessors do not report a type mismatch to the caller:
reading ``key_event`` off a POINTER_MOTION event returns
``KeyEvent(key=0, is_press=False)``, logging an internal "Bug:"
line for some accessors and nothing at all for others. Checking
first turns a plausible-looking zero into an immediate error.
"""
actual = self.event_type
if actual in valid:
return
wanted = " or ".join(v.name for v in valid)
seen = actual.name if isinstance(actual, EventType) else str(actual)
raise TypeError(f"Event.{getter} is only valid for {wanted} events, not {seen}")
@property
def emulating_sequence(self) -> int:
"""Sequence number of the start_emulating transaction."""
self._require("emulating_sequence", EventType.DEVICE_START_EMULATING)
return _capi.libei.event_emulating_get_sequence(self)
@property
def keyboard_xkb_modifiers(self) -> XkbModifiersEvent:
"""XKB modifier state for a KEYBOARD_MODIFIERS event."""
self._require("keyboard_xkb_modifiers", EventType.KEYBOARD_MODIFIERS)
return XkbModifiersEvent(
depressed=_capi.libei.event_keyboard_get_xkb_mods_depressed(self),
latched=_capi.libei.event_keyboard_get_xkb_mods_latched(self),
locked=_capi.libei.event_keyboard_get_xkb_mods_locked(self),
group=_capi.libei.event_keyboard_get_xkb_group(self),
)
@property
def key_event(self) -> KeyEvent:
"""Key code and press/release state for a KEYBOARD_KEY event."""
self._require("key_event", EventType.KEYBOARD_KEY)
return KeyEvent(
key=_capi.libei.event_keyboard_get_key(self),
is_press=bool(_capi.libei.event_keyboard_get_key_is_press(self)),
)
@property
def button_event(self) -> ButtonEvent:
"""Button code and press/release state for a BUTTON_BUTTON event."""
self._require("button_event", EventType.BUTTON_BUTTON)
return ButtonEvent(
button=_capi.libei.event_button_get_button(self),
is_press=bool(_capi.libei.event_button_get_is_press(self)),
)
@property
def pointer_event(self) -> PointerEvent:
"""Relative motion deltas for a POINTER_MOTION event."""
self._require("pointer_event", EventType.POINTER_MOTION)
return PointerEvent(
dx=_capi.libei.event_pointer_get_dx(self),
dy=_capi.libei.event_pointer_get_dy(self),
)
@property
def pointer_absolute_event(self) -> PointerAbsoluteEvent:
"""Absolute position for a POINTER_MOTION_ABSOLUTE event."""
self._require("pointer_absolute_event", EventType.POINTER_MOTION_ABSOLUTE)
return PointerAbsoluteEvent(
x=_capi.libei.event_pointer_get_absolute_x(self),
y=_capi.libei.event_pointer_get_absolute_y(self),
)
@property
def scroll_event(self) -> ScrollEvent:
"""Smooth scroll deltas for a SCROLL_DELTA event."""
self._require("scroll_event", EventType.SCROLL_DELTA)
return ScrollEvent(
dx=_capi.libei.event_scroll_get_dx(self),
dy=_capi.libei.event_scroll_get_dy(self),
)
@property
def scroll_discrete_event(self) -> ScrollDiscreteEvent:
"""Detent deltas for a SCROLL_DISCRETE event (120 per detent)."""
self._require("scroll_discrete_event", EventType.SCROLL_DISCRETE)
return ScrollDiscreteEvent(
dx=_capi.libei.event_scroll_get_discrete_dx(self),
dy=_capi.libei.event_scroll_get_discrete_dy(self),
)
@property
def scroll_stop_event(self) -> ScrollStopEvent:
"""Which axes stopped, for a SCROLL_STOP/SCROLL_CANCEL event.
libei's header documents these accessors for SCROLL_CANCEL only,
but both event types are accepted -- confirmed by round-tripping
each through a real libeis server, with no internal "Bug:" log.
"""
self._require(
"scroll_stop_event", EventType.SCROLL_STOP, EventType.SCROLL_CANCEL
)
return ScrollStopEvent(
stop_x=bool(_capi.libei.event_scroll_get_stop_x(self)),
stop_y=bool(_capi.libei.event_scroll_get_stop_y(self)),
)
@property
def touch_event(self) -> TouchEvent:
"""Touch id and position for a TOUCH_DOWN or TOUCH_MOTION event.
Not TOUCH_UP: that event carries no position, so it has its own
accessor, :attr:`touch_up_event`.
"""
self._require("touch_event", EventType.TOUCH_DOWN, EventType.TOUCH_MOTION)
return TouchEvent(
touchid=_capi.libei.event_touch_get_id(self),
x=_capi.libei.event_touch_get_x(self),
y=_capi.libei.event_touch_get_y(self),
)
@property
def touch_up_event(self) -> TouchUpEvent:
"""Touch id and cancellation flag for a TOUCH_UP event.
``is_cancel`` distinguishes a touch the compositor cancelled from
one the user logically released. It is False on libei older than
1.4, which cannot express cancellation, and against an EIS
implementation older than ``ei_touchscreen`` version 2. The touch
id is available everywhere.
"""
self._require("touch_up_event", EventType.TOUCH_UP)
try:
is_cancel = bool(_capi.libei.event_touch_get_is_cancel(self))
except LibraryNotFoundError:
# ei_event_touch_get_is_cancel() arrived in libei 1.4.
# An older library has no way to express cancellation, so every
# TOUCH_UP it reports really is a plain release: False is the
# accurate answer, not a failure. Without this the whole
# accessor would raise on a 1.0-1.3 install, taking the touch
# id -- which those versions do provide -- down with it.
is_cancel = False
return TouchUpEvent(
touchid=_capi.libei.event_touch_get_id(self),
is_cancel=is_cancel,
)
@property
def text_utf8_event(self) -> TextUtf8Event:
"""The text carried by a TEXT_UTF8 event. Requires libei 1.6."""
self._require("text_utf8_event", EventType.TEXT_UTF8)
raw = _capi.libei.event_text_get_utf8(self)
return TextUtf8Event(text="" if raw is None else raw.decode("utf-8"))
@property
def text_keysym_event(self) -> TextKeysymEvent:
"""Keysym and press state for a TEXT_KEYSYM event. Requires libei 1.6."""
self._require("text_keysym_event", EventType.TEXT_KEYSYM)
return TextKeysymEvent(