crystallabs / tput.cr

Low-level component for building term/console applications in Crystal

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Reading responses from terminal escape sequences

docelic opened this issue · comments

Tput.cr's support for terminal sequences is based on Blessed. Blessed keeps its terminal sequences in file https://github.com/chjj/blessed/blob/master/lib/program.js , starting roughly at line 1818 and spanning the next ~3k lines.

A good majority of those functions was reimplemented in tput.cr, and also more conveniently organized into multiple files, to separate groups of functionality:

ls src/tput/output

bell.cr
charset.cr
colors.cr
cursor.cr
emulator.cr
misc.cr
mouse.cr
rectangles.cr
screen.cr
scrolling.cr
terminal.cr
text.cr

All functions that were ported over to tput.cr have one thing in common -- they just output sequences to the terminal, and don't read anything back (that's why they are in the "output/" subdirectory). For example, they output sequences to trigger an audio or visual bell on the terminal (tput.bell), to move cursor one row down (tput.cursor_down), to move cursor to a specific (y,x) position, to erase some rectangular area on the screen, etc. Terminal does not send any "response" back to the app on these calls, it just does what it is told.

(On a side note: working with raw terminal sequences is not ideal -- e.g. if a particular terminal does not support e.g. cud(amount) (cursor down), then the user would need to check whether terminal maybe supports cud1 sequence (and if yes, repeat it amount times), and so on. This overhead should not befall on the programmer -- programmer should just request a "cursor down", and it should happen. That's why blessed's/tput's functions already have those fallbacks built-in, for example see https://github.com/crystallabs/tput.cr/blob/master/src/tput/output/cursor.cr#L272 . There we see that it first tries cud(amount), then cud1 * amount, and then finally falls back to generic sequence \e[*amount*B.)

Most console programs get away with using just those sequences.

But apart from those write-only sequences, there are some that actually do send a response back to the program. So after writing/outputting a sequence to the terminal, the program should expect to read a response. All such functions are currently not implemented in tput.cr.

In Blessed, it seems to me that there is just one function for this, in which Blessed's author has added support for reading all kinds of responses that it supports. That's function https://github.com/chjj/blessed/blob/master/lib/program.js#L1040 .

If support for something like that was added to tput.cr, then it would be possible for the app to read the position of cursor (instead of only set it), probably read colors used, and other stuff.

As mentioned, my impression is that most apps don't use this, but having it would be nice.