Debian Codegraph @

lib_pypy/pyrepl/unix_eventqueue.py

raw symbols SCIP
1 # Copyright 2000-2008 Michael Hudson-Doyle <[email protected]>
2 # Armin Rigo
3 #
4 # All Rights Reserved
5 #
6 #
7 # Permission to use, copy, modify, and distribute this software and
8 # its documentation for any purpose is hereby granted without fee,
9 # provided that the above copyright notice appear in all copies and
10 # that both that copyright notice and this permission notice appear in
11 # supporting documentation.
12 #
13 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
14 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
16 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
17 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
18 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
19 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20
21 from collections import deque
22
23 from . import keymap
24 from .console import Event
25 from . import curses
26 from .trace import trace
27 from termios import tcgetattr, VERASE
28 import os
29
30
31 # Mapping of human-readable key names to their terminal-specific codes
32 TERMINAL_KEYNAMES = {
33 "delete": "kdch1",
34 "down": "kcud1",
35 "end": "kend",
36 "enter": "kent",
37 "home": "khome",
38 "insert": "kich1",
39 "left": "kcub1",
40 "page down": "knp",
41 "page up": "kpp",
42 "right": "kcuf1",
43 "up": "kcuu1",
44 }
45
46
47 # Function keys F1-F20 mapping
48 TERMINAL_KEYNAMES.update(("f%d" % i, "kf%d" % i) for i in range(1, 21))
49
50 # Known CTRL-arrow keycodes
51 CTRL_ARROW_KEYCODES= {
52 # for xterm, gnome-terminal, xfce terminal, etc.
53 b'\033[1;5D': 'ctrl left',
54 b'\033[1;5C': 'ctrl right',
55 # for rxvt
56 b'\033Od': 'ctrl left',
57 b'\033Oc': 'ctrl right',
58 }
59
60 def get_terminal_keycodes() -> dict[bytes, str]:
61 """
62 Generates a dictionary mapping terminal keycodes to human-readable names.
63 """
64 keycodes = {}
65 for key, terminal_code in TERMINAL_KEYNAMES.items():
66 keycode = curses.tigetstr(terminal_code)
67 trace('key {key} tiname {terminal_code} keycode {keycode!r}', **locals())
68 if keycode:
69 keycodes[keycode] = key
70 keycodes.update(CTRL_ARROW_KEYCODES)
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
131 else:
132 self.insert(Event('key', k, self.flush_buf()))
133 self.keymap = self.compiled_keymap
134
135 elif self.buf and self.buf[0] == 27: # escape
136 # escape sequence not recognized by our keymap: propagate it
137 # outside so that i can be recognized as an M-... key (see also
138 # the docstring in keymap.py
139 trace('unrecognized escape sequence, propagating...')
140 self.keymap = self.compiled_keymap
141 self.insert(Event('key', '\033', bytearray(b'\033')))
142 for _c in self.flush_buf()[1:]:
143 self.push(_c)
144
145 else:
146 try:
147 decoded = bytes(self.buf).decode(self.encoding)
148 except UnicodeError:
149 return
150 else:
151 self.insert(Event('key', decoded, self.flush_buf()))
152 self.keymap = self.compiled_keymap