Repository navigation
Expand file tree
/
Copy patheis.py
More file actions
1315 lines (1073 loc) · 45.7 KB
/
Copy patheis.py
File metadata and controls
1315 lines (1073 loc) · 45.7 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 libeis -- the EIS *server* library.
An EIS context represents the compositor side of the protocol: it accepts
client connections, advertises seats and devices, and receives the events an
:class:`libei.ei.Sender` injects. This is what a compositor implements, and
what a test harness for this package's own ``ei`` module drives instead of
a real compositor.
Typical usage (accepting one client via the fd backend)::
server = Eis.create_for_fd()
client_fd = server.add_client()
sender = ei.Sender.create_for_fd(client_fd, name="some-client")
for event in server.events:
if event.event_type is EventType.CLIENT_CONNECT:
event.client.connect()
seat = event.client.new_seat("default")
seat.configure_capabilities([DeviceCapability.POINTER])
seat.add()
"""
from __future__ import annotations
import contextlib
import dataclasses
import enum
import logging
import os
from collections.abc import Iterator, Sequence
from ctypes import c_void_p
from pathlib import Path
from typing import IO
from . import _capi
from ._capi.libei import log_handler_t
from ._capi.loader import LibraryNotFoundError
from ._cobject import CObject
from .ei import _next_emulating_sequence
logger = logging.getLogger("libei.eis")
def is_available() -> bool:
"""Whether libeis.so.1 can be loaded on this system."""
return _capi.libeis.lib.is_available()
class Error(Exception):
"""A libeis call failed.
``errno`` is the positive errno where libeis 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 libeis reported one, errno."""
super().__init__(message)
self.message = message
self.errno = errno
class EventType(enum.IntEnum):
"""Mirrors ``enum eis_event_type`` from libeis.h.
Like its ``ei`` counterpart, this enum is not exhaustive by libei's own
documented contract; :attr:`Event.event_type` returns a plain ``int``
for a value not listed here rather than raising.
"""
CLIENT_CONNECT = 1
CLIENT_DISCONNECT = 2
SEAT_BIND = 3
DEVICE_CLOSED = 4
DEVICE_READY = 5
SEAT_DEVICE_REQUESTED = 6
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
# As in ei.EventType: on libei's main branch, in no released version,
# values matching upstream main. No accessors are bound for them.
# See docs/vs-snegg.md.
SWIPE_BEGIN = 1000
SWIPE_UPDATE = 1001
SWIPE_END = 1002
PINCH_BEGIN = 1010
PINCH_UPDATE = 1011
PINCH_END = 1012
HOLD_BEGIN = 1020
HOLD_END = 1021
STYLUS_BIND_CAPABILITIES = 1100
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 eis_device_capability``.
Server-side counterpart of :class:`libei.ei.DeviceCapability`: these
are what :meth:`Device.configure` announces, rather than what a client
asks for.
"""
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. libeis defines exactly one."""
XKB = 1
class Flag(enum.IntEnum):
"""Context behavior toggles for :meth:`Eis.set_flag`."""
# Announce ei_device protocol version 3 or later. With this set, a
# device added via Device.add() must not be resumed until its
# DEVICE_READY event has arrived.
DEVICE_READY = 1
class _LogPriority(enum.IntEnum):
"""The log levels, as the integers libeis passes to its log handler."""
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
@dataclasses.dataclass(frozen=True, slots=True)
class KeyEvent:
"""Key code and press state received on a KEYBOARD_KEY event.
``key`` is a Linux ``KEY_*`` code, as sent by the client's
``ei.Device.keyboard_key``.
"""
key: int
is_press: bool
@dataclasses.dataclass(frozen=True, slots=True)
class ButtonEvent:
"""Button code and press state received on a BUTTON_BUTTON event.
``button`` is a Linux ``BTN_*`` code, as sent by the client's
``ei.Device.button``.
"""
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 region the sending device covers.
"""
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."""
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
@dataclasses.dataclass(frozen=True, slots=True)
class ConfigureRegion:
"""A region to create, in the form :meth:`Device.configure` wants.
Plain description rather than a live :class:`Region`, because
``configure()`` allocates, fills in and adds each region itself --
there is no point at which a caller holds one to set fields on.
"""
offset: tuple[int, int]
size: tuple[int, int]
physical_scale: float = 1.0
# Device.configure() creates, configures and adds each region itself,
# so a caller has no window in which to call Region.set_mapping_id() --
# it has to be part of the description handed in. Requires libei 1.1;
# left None, nothing is set and no 1.1 symbol is touched.
mapping_id: str | None = None
class Region(CObject):
"""A rectangular area of the desktop an absolute device maps onto.
Normally created for you from a :class:`ConfigureRegion` passed to
:meth:`Device.configure`; this class is what a getter hands back.
"""
_ref_func = staticmethod(_capi.libeis.region_ref)
_unref_func = staticmethod(_capi.libeis.region_unref)
@property
def position(self) -> tuple[int, int]:
"""Top-left corner of the region, in logical pixels."""
return (
_capi.libeis.region_get_x(self),
_capi.libeis.region_get_y(self),
)
@property
def dimension(self) -> tuple[int, int]:
"""Width and height of the region, in logical pixels."""
return (
_capi.libeis.region_get_width(self),
_capi.libeis.region_get_height(self),
)
@property
def physical_scale(self) -> float:
"""Scale between logical pixels and this region's physical size."""
return _capi.libeis.region_get_physical_scale(self)
@property
def mapping_id(self) -> str | None:
"""Identifier shared by regions that map to the same thing.
``None`` unless :meth:`set_mapping_id` has set one. Requires
libei 1.1.
"""
raw = _capi.libeis.region_get_mapping_id(self)
return None if raw is None else raw.decode("utf-8")
def set_mapping_id(self, mapping_id: str) -> Region:
"""Tag this region so clients can group it with others.
Call before :meth:`Device.add`, like the rest of a region's
configuration. Requires libei 1.1.
"""
_capi.libeis.region_set_mapping_id(self, mapping_id.encode("utf-8"))
return self
def contains(self, x: float, y: float) -> bool:
"""Whether the given logical-pixel point falls inside this region."""
return bool(_capi.libeis.region_contains(self, x, y))
class Keymap(CObject):
"""An XKB keymap to hand a client's keyboard device.
Build one with :meth:`Device.new_keymap` from an fd holding the keymap
text, then :meth:`add` it before adding the device.
"""
_ref_func = staticmethod(_capi.libeis.keymap_ref)
_unref_func = staticmethod(_capi.libeis.keymap_unref)
@property
def keymap_type(self) -> KeymapType:
"""Keymap format; currently always XKB."""
return KeymapType(_capi.libeis.keymap_get_type(self))
@property
def size(self) -> int:
"""Size of the keymap data, in bytes."""
return _capi.libeis.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.
"""
# See ei.Keymap.fd: eis_keymap_get_fd() is a plain field read, not
# a duped/transferred fd -- duplicate it so os.fdopen()'s file
# object doesn't close a fd the keymap still owns.
raw_fd = _capi.libeis.keymap_get_fd(self)
if raw_fd < 0:
raise Error("eis_keymap_get_fd() reported no usable file descriptor")
duplicate = os.dup(raw_fd)
# dup(2) shares the file offset with the original, which is
# normally at EOF -- without this rewind a read returns zero bytes
# and no error, indistinguishable from an empty keymap. See
# ei.Keymap.fd for why a non-seekable fd is tolerated here.
with contextlib.suppress(OSError):
os.lseek(duplicate, 0, os.SEEK_SET)
return os.fdopen(duplicate, "rb")
def add(self) -> None:
"""Publish this object to the client."""
_capi.libeis.keymap_add(self)
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. Like the :class:`Device` methods, these only queue --
:meth:`Device.frame` commits them.
"""
# No _ref_func: eis_device_touch_new() is the only function that ever
# returns a struct eis_touch* (aside from eis_touch_ref/unref
# themselves), and its docs say the caller already owns that
# reference -- there's no borrowed-pointer getter elsewhere that would
# need wrap()'s extra ref. See Device.touch_new(), which uses adopt().
_unref_func = staticmethod(_capi.libeis.touch_unref)
@property
def device(self) -> Device:
"""The device this touch belongs to."""
device = Device.wrap(_capi.libeis.touch_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
def down(self, x: float, y: float) -> Touch:
"""Begin the touch at the given point."""
_capi.libeis.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.libeis.touch_motion(self, x, y)
return self
def up(self) -> Touch:
"""End the touch."""
_capi.libeis.touch_up(self)
return self
def cancel(self) -> Touch:
"""End the touch as cancelled rather than logically released.
Requires libei 1.4, and version 2 or later of the
``ei_touchscreen`` interface on both sides; against an older client
it arrives as a plain release.
"""
_capi.libeis.touch_cancel(self)
return self
class Device(CObject):
"""A device this server offers to a client.
Create with :meth:`Seat.new_device`, describe it with
:meth:`configure`, then :meth:`add` and :meth:`resume` it before the
client may use it. For a receiving server the sending methods are
unused; they exist for a server that feeds input to a client.
"""
_ref_func = staticmethod(_capi.libeis.device_ref)
_unref_func = staticmethod(_capi.libeis.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}>"
def configure(
self,
name: str | None = None,
device_type: DeviceType = DeviceType.VIRTUAL,
size: tuple[int, int] | None = None,
capabilities: tuple[DeviceCapability, ...] = (),
regions: tuple[ConfigureRegion, ...] = (),
) -> Device:
"""Set the device's properties. Call before :meth:`add`."""
if name is not None:
_capi.libeis.device_configure_name(self, name.encode("utf-8"))
_capi.libeis.device_configure_type(self, device_type)
if size is not None:
_capi.libeis.device_configure_size(self, size[0], size[1])
for cap in capabilities:
_capi.libeis.device_configure_capability(self, cap)
for region in regions:
pointer = _capi.libeis.device_new_region(self)
if not pointer:
raise Error("eis_device_new_region() returned NULL")
# eis_device_new_region() returns an owned reference (initial
# refcount 1); eis_region_add() registers it with the device
# but doesn't consume that reference. Adopt it so we can
# release it explicitly once added -- the raw pointer used to
# be discarded here with nothing ever unref'ing it, leaking
# one region every call.
region_obj = Region.adopt(pointer)
assert region_obj is not None
_capi.libeis.region_set_size(region_obj, *region.size)
_capi.libeis.region_set_offset(region_obj, *region.offset)
_capi.libeis.region_set_physical_scale(region_obj, region.physical_scale)
if region.mapping_id is not None:
region_obj.set_mapping_id(region.mapping_id)
_capi.libeis.region_add(region_obj)
region_obj.release()
return self
def new_keymap(self, keymap_type: KeymapType, fd: IO[bytes], size: int) -> Keymap:
"""Attach an XKB keymap to this keyboard-capable device."""
pointer = _capi.libeis.device_new_keymap(self, keymap_type, fd.fileno(), size)
if not pointer:
raise Error("eis_device_new_keymap() returned NULL")
keymap = Keymap.adopt(pointer)
assert keymap is not None
return keymap
@property
def device_type(self) -> DeviceType:
"""Whether the device is virtual or represents real hardware."""
return DeviceType(_capi.libeis.device_get_type(self))
@property
def name(self) -> str:
"""The device name set via :meth:`configure`."""
return _capi.libeis.device_get_name(self).decode("utf-8")
@property
def width(self) -> int:
"""Device width in logical pixels; 0 if unsized."""
return _capi.libeis.device_get_width(self)
@property
def height(self) -> int:
"""Device height in logical pixels; 0 if unsized."""
return _capi.libeis.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.libeis.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.libeis.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.libeis.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.libeis.device_keyboard_get_keymap(self))
def add(self) -> Device:
"""Publish this object to the client."""
_capi.libeis.device_add(self)
return self
def remove(self) -> Device:
"""Withdraw this object from the client."""
_capi.libeis.device_remove(self)
return self
def pause(self) -> Device:
"""Suspend the device; the client may not send events while paused."""
_capi.libeis.device_pause(self)
return self
def resume(self) -> Device:
"""Resume a paused device, allowing the client to send events again."""
_capi.libeis.device_resume(self)
return self
def keyboard_xkb_modifiers(
self, depressed: int, latched: int, locked: int, group: int
) -> Device:
"""Notify the client of the current XKB modifier state.
Call this whenever the modifier state or effective group changes,
for every affected keyboard device.
"""
_capi.libeis.device_keyboard_send_xkb_modifiers(
self, depressed, latched, locked, group
)
return self
def start_emulating(self, sequence: int | None = None) -> Device:
"""Begin an emulation transaction; pair with :meth:`stop_emulating`.
``sequence`` must go up by at least 1 on each call; the default
draws from the same process-wide counter as
:meth:`libei.ei.Device.start_emulating`.
"""
if sequence is None:
sequence = _next_emulating_sequence()
_capi.libeis.device_start_emulating(self, sequence)
return self
def stop_emulating(self) -> Device:
"""End the transaction opened by :meth:`start_emulating`."""
_capi.libeis.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.libeis.now(_capi.libeis.device_get_context(self))
_capi.libeis.device_frame(self, timestamp)
return self
def pointer_motion(self, dx: float, dy: float) -> Device:
"""Send a relative pointer motion, in logical pixels."""
_capi.libeis.device_pointer_motion(self, dx, dy)
return self
def pointer_motion_absolute(self, x: float, y: float) -> Device:
"""Send an absolute pointer motion, in the device's region."""
_capi.libeis.device_pointer_motion_absolute(self, x, y)
return self
def button(self, button: int, is_press: bool) -> Device:
"""Send a button press or release, by Linux ``BTN_*`` code."""
_capi.libeis.device_button_button(self, button, is_press)
return self
def keyboard_key(self, key: int, is_press: bool) -> Device:
"""Send a key press or release, by Linux ``KEY_*`` keycode."""
_capi.libeis.device_keyboard_key(self, key, is_press)
return self
def scroll_delta(self, dx: float, dy: float) -> Device:
"""Send a smooth scroll, in logical pixels."""
_capi.libeis.device_scroll_delta(self, dx, dy)
return self
def scroll_discrete(self, dx: int, dy: int) -> Device:
"""Send a discrete (detent) scroll; one detent is 120."""
_capi.libeis.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.libeis.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.libeis.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.libeis.device_get_region_at(self, x, y))
def text_utf8(self, text: str) -> Device:
"""Send text to the client, for a device with the TEXT capability.
Requires libei 1.6 on both sides.
"""
# Encoded and passed with an explicit length: the plain
# eis_device_text_utf8() takes a NUL-terminated string, which
# would silently truncate a str containing a NUL.
data = text.encode("utf-8")
_capi.libeis.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.libeis.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.libeis.device_touch_new(self)
if not pointer:
raise Error("eis_device_touch_new() returned NULL")
touch = Touch.adopt(pointer)
assert touch is not None
return touch
class Seat(CObject):
"""A group of devices offered to one client.
Create with :meth:`Client.new_seat`, announce what it can do with
:meth:`configure_capabilities`, then :meth:`add` it. The client
answers by binding the capabilities it wants, which arrives as a
SEAT_BIND event.
"""
_ref_func = staticmethod(_capi.libeis.seat_ref)
_unref_func = staticmethod(_capi.libeis.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 this server gave the seat."""
return _capi.libeis.seat_get_name(self).decode("utf-8")
@property
def client(self) -> Client:
"""The client this object belongs to."""
client = Client.wrap(_capi.libeis.seat_get_client(self))
assert client is not None
return client
@property
def capabilities(self) -> tuple[DeviceCapability, ...]:
"""The capabilities this object actually has."""
return tuple(
c for c in DeviceCapability if _capi.libeis.seat_has_capability(self, c)
)
def configure_capabilities(
self, capabilities: tuple[DeviceCapability, ...]
) -> Seat:
"""Declare which capabilities this seat offers. Call before add()."""
for cap in capabilities:
_capi.libeis.seat_configure_capability(self, cap)
return self
def add(self) -> Seat:
"""Publish this object to the client."""
_capi.libeis.seat_add(self)
return self
def remove(self) -> Seat:
"""Withdraw this object from the client."""
_capi.libeis.seat_remove(self)
return self
def new_device(self) -> Device:
"""Create a device on this seat. Configure it, then add()."""
pointer = _capi.libeis.seat_new_device(self)
if not pointer:
raise Error("eis_seat_new_device() returned NULL")
device = Device.adopt(pointer)
assert device is not None
return device
class Client(CObject):
"""A client connection, arriving as a CLIENT_CONNECT event.
Call :meth:`connect` to accept it (or :meth:`disconnect` to refuse),
then offer it seats.
"""
_ref_func = staticmethod(_capi.libeis.client_ref)
_unref_func = staticmethod(_capi.libeis.client_unref)
def __repr__(self) -> str:
"""The client's name and which side of the protocol it is on."""
return f"<Client {self.name!r} sender={self.is_sender}>"
@property
def is_sender(self) -> bool:
"""Whether the client sends events (rather than receiving them)."""
return bool(_capi.libeis.client_is_sender(self))
@property
def name(self) -> str:
"""The name the client announced for itself."""
return _capi.libeis.client_get_name(self).decode("utf-8")
@property
def pid(self) -> int:
"""The client process's pid, via ``SO_PEERCRED``.
Requires libei 1.5. Socket-backend contexts only -- meaningless
for a context set up with :meth:`Eis.create_for_fd`, where there is
no peer socket to ask. Raises :class:`Error` if the library reports
a failure.
"""
result = _capi.libeis.backend_socket_get_client_pid(self)
if result < 0:
raise Error(
f"eis_backend_socket_get_client_pid() failed with errno {-result}"
)
return result
def connect(self) -> None:
"""Accept this client's connection."""
_capi.libeis.client_connect(self)
def disconnect(self) -> None:
"""Disconnect this client."""
_capi.libeis.client_disconnect(self)
def new_seat(self, name: str) -> Seat:
"""Create a seat to offer this client. Configure it, then add()."""
pointer = _capi.libeis.client_new_seat(self, name.encode("utf-8"))
if not pointer:
raise Error("eis_client_new_seat() returned NULL")
seat = Seat.adopt(pointer)
assert seat is not None
return seat
def new_ping(self) -> Ping:
"""Create a round trip to this client. Requires libei 1.4.
Call :meth:`Ping.send` to start it; the reply is a PONG event.
"""
pointer = _capi.libeis.client_new_ping(self)
if not pointer:
raise Error("eis_client_new_ping() returned NULL")
ping = Ping.adopt(pointer)
assert ping is not None
return ping
class Ping(CObject):
"""A round trip to a client, answered by a PONG event.
Create one with :meth:`Client.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.libeis.ping_ref)
_unref_func = staticmethod(_capi.libeis.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 libeis assigned to this round trip."""
return _capi.libeis.ping_get_id(self)
def send(self) -> Ping:
"""Start the round trip. The reply arrives as a PONG event."""
_capi.libeis.ping(self)
return self
class Event(CObject):
"""One event from :attr:`Eis.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 libeis would hand back.
Valid only for the loop iteration that yielded it -- :attr:`Eis.events`
releases each event as it resumes.
"""
_unref_func = staticmethod(_capi.libeis.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.libeis.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.libeis.event_get_time(self)
@property
def client(self) -> Client:
"""The client this object belongs to."""
client = Client.wrap(_capi.libeis.event_get_client(self))
assert client is not None
return client
@property
def device(self) -> Device | None:
"""The device this event concerns, or None if it has none."""
return Device.wrap(_capi.libeis.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.libeis.event_get_seat(self))
def _require(self, getter: str, *valid: EventType) -> None:
"""Raise unless this event is one of ``valid``.
libeis'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 seat_capabilities(self) -> tuple[DeviceCapability, ...]:
"""Capabilities the client requested, for a SEAT_BIND event."""
self._require("seat_capabilities", EventType.SEAT_BIND)
return tuple(
c
for c in DeviceCapability
if _capi.libeis.event_seat_has_capability(self, c)
)
@property
def emulating_sequence(self) -> int:
"""Sequence number of the start_emulating transaction.
Reads 0 on libei older than 1.6, whatever the client sent. libeis
queued the event without ever copying the sequence into it, so the
getter returned a zeroed struct field; upstream added the missing
assignment in libei 1.6.0. Every version from this package's 1.0.0
floor up exports the symbol, so there is nothing to raise and no
way to tell an old library apart from a client that genuinely sent
0 -- treat a 0 here as "unknown" unless you know both ends are on
1.6. :attr:`libei.ei.Event.emulating_sequence`, the receiver side
of the same transaction, is unaffected: libei has always stored it.
"""
self._require("emulating_sequence", EventType.DEVICE_START_EMULATING)
return _capi.libeis.event_emulating_get_sequence(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.libeis.event_keyboard_get_key(self),
is_press=bool(_capi.libeis.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.libeis.event_button_get_button(self),
is_press=bool(_capi.libeis.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.libeis.event_pointer_get_dx(self),
dy=_capi.libeis.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.libeis.event_pointer_get_absolute_x(self),
y=_capi.libeis.event_pointer_get_absolute_y(self),
)
@property
def scroll_event(self) -> ScrollEvent:
"""Smooth scroll deltas for a SCROLL_DELTA event."""