4 ms·
Little anecdote time. Once upon a time I was writing a little terminal-based text editor (fun experience), and wanted to handle some additional keys for editin
by protomikron 10y ago
Little anecdote time.
Once upon a time I was writing a little terminal-based text editor (fun experience), and wanted to handle some additional keys for editing capabilities:
- Arrows Keyps (up, down, left, right)
- Delete Key
- Backspace Key
- Page-Up/Down
I do not remember the other special keys, but the point is that events for these keys are provided to your terminal using escape sequences (just run $ infocmp). In particular I did not want to use curses, so I parsed the raw escape sequences to find out the keys pressed. This worked reasonably (if you are OK to only support a subset of terminals), but was incredible more complicated than I thought, as there are subtle differences between xterm, linux-console, urxvt, minix, etc.
Running a terminal under X, as I understand the path of key events (on Linux) is a little bit like that:
0. User-Key-Press
1. Some-Magic
2. Keyboard-Interrupt
3. Keyboard-Driver
4. Linux-Input-System (see /usr/include/linux/input-event-codes.h)
5. x11-event
6. xterm-terminal-emulator
7. escape-encoded event at e.g. /dev/pts/{n}.
The escape sequence events at the end are harder to parse than the intermediate Linux input events.
The funny thing is, that the Linux input system knows exactly what key you pressed and exposes a fantastic API (/usr/include/linux/input.h), but it is actually harder to find out reliable for user-space applications. E.g. I built some basic mouse support (for positioning) for the editor, and this use case is actually not supported; Although it is possible to activate mouse support in your terminal (this might be xterm specific), this does not work across terminals (and is limited AFAIK to 255 rows/cols).
So I built a prototype using /dev/input/{...} (it's part of the Linux input system) and it was a breeze and just worked. This is obviously system wide, requires root privileges and ignores your WM, but from a dev point of view it was absolutely the best system to work with (both for keys and for mouse). In the end I went back to parsing escape sequences (a text editor should be usable by non-root users obviously), but it was an interesting experience (the abstraction making the API worse).
/edit:
Although this was just for fun and more of a learning experience, I wondered what is the best way to handle mouse in a terminal, and sadly concluded that there just is no sane way across terminals (at least you want to support xterm, urxvt, st and linux), as far as I understand. If somebody knows how to solve this issue (mouse-support across the mentioned terminals), I would be glad to hear or know what has to be done. In a perfect world I would like to have /dev/input local to my window - that sounds like a sane ... plan?