Debian Codegraph @

src/evdev/eventio_async.py

raw
1 import asyncio
2 import select
3 import sys
4
5 from . import eventio
6 from .events import InputEvent
7
8 # needed for compatibility
9 from .eventio import EvdevError
10
11 if sys.version_info >= (3, 11):
12 from typing import Self
13 else:
14 from typing import Any as Self
15
16
17 class ReadIterator:
18 def __init__(self, device: "EventIO"):
19 self.current_batch = iter(())
20 self.device = device
21
22 # Standard iterator protocol.
23 def __iter__(self) -> Self:
24 return self
25
26 def __next__(self) -> InputEvent:
27 try:
28 # Read from the previous batch of events.
29 return next(self.current_batch)
30 except StopIteration:
31 r, w, x = select.select([self.device.fd], [], [])
32 self.current_batch = self.device.read()
33 return next(self.current_batch)
34
35 def __aiter__(self) -> Self:
36 return self
37
38 def __anext__(self) -> "asyncio.Future[InputEvent]":
39 future = asyncio.get_running_loop().create_future()
40 try:
41 # Read from the previous batch of events.
42 future.set_result(next(self.current_batch))
43 except StopIteration:
44
45 def next_batch_ready(batch):
46 try:
47 self.current_batch = batch.result()
48 future.set_result(next(self.current_batch))
49 except Exception as e:
50 future.set_exception(e)
51
52 self.device.async_read().add_done_callback(next_batch_ready)
53 return future
54
55
56 class EventIO(eventio.EventIO):
57 # The event loop a reader was last registered on, or None if no async read
58 # has been awaited yet. Set in _do_when_readable, used by close().
59 _loop: "asyncio.AbstractEventLoop | None" = None
60
61 def _do_when_readable(self, callback) -> None:
62 # Remember the loop the reader is registered on so that close() can
63 # remove it later, even when called without a running event loop.
64 loop = asyncio.get_running_loop()
65 self._loop = loop
66
67 def ready():
68 loop.remove_reader(self.fileno())
69 callback()
70
71 loop.add_reader(self.fileno(), ready)
72
73 def _set_result(self, future, cb) -> None:
74 try:
75 future.set_result(cb())
76 except Exception as error:
77 future.set_exception(error)
78
79 def async_read_one(self) -> "asyncio.Future[InputEvent]":
80 """
81 Asyncio coroutine to read and return a single input event as
82 an instance of :class:`InputEvent <evdev.events.InputEvent>`.
83 """
84 future = asyncio.get_running_loop().create_future()
85 self._do_when_readable(lambda: self._set_result(future, self.read_one))
86 return future
87
88 def async_read(self) -> "asyncio.Future[InputEvent]":
89 """
90 Asyncio coroutine to read multiple input events from device. Return
91 a generator object that yields :class:`InputEvent <evdev.events.InputEvent>`
92 instances.
93 """
94 future = asyncio.get_running_loop().create_future()
95 self._do_when_readable(lambda: self._set_result(future, self.read))
96 return future
97
98 def async_read_loop(self) -> ReadIterator:
99 """
100 Return an iterator that yields input events. This iterator is
101 compatible with the ``async for`` syntax.
102
103 """
104 return ReadIterator(self)
105
106 def close(self) -> None:
107 # A reader is only registered once an async read has been awaited, in
108 # which case _do_when_readable recorded the loop it was added to.
109 loop = self._loop
110 if loop is None or loop.is_closed():
111 # No reader was ever registered, or its loop is already gone, so
112 # there is nothing to remove the reader from.
113 return
114 loop.remove_reader(self.fileno())