Debian Codegraph @

Lib/_pyrepl/unix_eventqueue.py

raw
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 .terminfo import TermInfo
22 from .trace import trace
23 from .base_eventqueue import BaseEventQueue
24 from termios import tcgetattr, VERASE
25 import os
26
27
28 # Mapping of human-readable key names to their terminal-specific codes
29 TERMINAL_KEYNAMES = {
30 "delete": "kdch1",
31 "down": "kcud1",
32 "end": "kend",
33 "enter": "kent",
34 "home": "khome",
35 "insert": "kich1",
36 "left": "kcub1",
37 "page down": "knp",
38 "page up": "kpp",
39 "right": "kcuf1",
40 "up": "kcuu1",
41 }
42
43
44 # Function keys F1-F20 mapping
45 TERMINAL_KEYNAMES.update(("f%d" % i, "kf%d" % i) for i in range(1, 21))
46
47 # Known CTRL-arrow keycodes
48 CTRL_ARROW_KEYCODES= {
49 # for xterm, gnome-terminal, xfce terminal, etc.
50 b'\033[1;5D': 'ctrl left',
51 b'\033[1;5C': 'ctrl right',
52 # for rxvt
53 b'\033Od': 'ctrl left',
54 b'\033Oc': 'ctrl right',
55 }
56
57 def get_terminal_keycodes(ti: TermInfo) -> dict[bytes, str]:
58 """
59 Generates a dictionary mapping terminal keycodes to human-readable names.
60 """
61 keycodes = {}
62 for key, terminal_code in TERMINAL_KEYNAMES.items():
63 keycode = ti.get(terminal_code)
64 trace('key {key} tiname {terminal_code} keycode {keycode!r}', **locals())
65 if keycode:
66 keycodes[keycode] = key
67 keycodes.update(CTRL_ARROW_KEYCODES)
68 return keycodes
69
70
71 class EventQueue(BaseEventQueue):
72 def __init__(self, fd: int, encoding: str, ti: TermInfo) -> None:
73 keycodes = get_terminal_keycodes(ti)
74 if os.isatty(fd):
75 backspace = tcgetattr(fd)[6][VERASE]
76 keycodes[backspace] = "backspace"
77 BaseEventQueue.__init__(self, encoding, keycodes)