| 71 | return keycodes |
| 72 | |
| 73 | class EventQueue: |
| 74 | def __init__(self, fd: int, encoding: str) -> None: |
| 75 | self.keycodes = get_terminal_keycodes() |
| 76 | if os.isatty(fd): |
| 77 | backspace = tcgetattr(fd)[6][VERASE] |
| 78 | self.keycodes[backspace] = "backspace" |
| 79 | self.compiled_keymap = keymap.compile_keymap(self.keycodes) |
| 80 | self.keymap = self.compiled_keymap |
| 81 | trace("keymap {k!r}", k=self.keymap) |
| 82 | self.encoding = encoding |
| 83 | self.events: deque[Event] = deque() |
| 84 | self.buf = bytearray() |
| 85 | |
| 86 | def get(self) -> Event | None: |
| 87 | """ |
| 88 | Retrieves the next event from the queue. |
| 89 | """ |
| 90 | if self.events: |
| 91 | return self.events.popleft() |
| 92 | else: |
| 93 | return None |
| 94 | |
| 95 | def empty(self) -> bool: |
| 96 | """ |
| 97 | Checks if the queue is empty. |
| 98 | """ |
| 99 | return not self.events |
| 100 | |
| 101 | def flush_buf(self) -> bytearray: |
| 102 | """ |
| 103 | Flushes the buffer and returns its contents. |
| 104 | """ |
| 105 | old = self.buf |
| 106 | self.buf = bytearray() |
| 107 | return old |
| 108 | |
| 109 | def insert(self, event: Event) -> None: |
| 110 | """ |
| 111 | Inserts an event into the queue. |
| 112 | """ |
| 113 | trace('added event {event}', event=event) |
| 114 | self.events.append(event) |
| 115 | |
| 116 | def push(self, char: int | bytes) -> None: |
| 117 | """ |
| 118 | Processes a character by updating the buffer and handling special key mappings. |
| 119 | """ |
| 120 | ord_char = char if isinstance(char, int) else ord(char) |
| 121 | char = bytes(bytearray((ord_char,))) |
| 122 | self.buf.append(ord_char) |
| 123 | if char in self.keymap: |
| 124 | if self.keymap is self.compiled_keymap: |
| 125 | #sanity check, buffer is empty when a special key comes |
| 126 | assert len(self.buf) == 1 |
| 127 | k = self.keymap[char] |
| 128 | trace('found map {k!r}', k=k) |
| 129 | if isinstance(k, dict): |
| 130 | self.keymap = k |