Published: 19. 12. 2012   Category: GNU/Linux

SHPaint – ANSI Art editor programmed in BASH

This geeky play is a result of small experiment I was inspired during reading Pro Bash Programming (Chris F.A. Johnson, Apress, 2009). There is a section describing how to read mouse status in X11 terminal.


So, let's go. First of all, this „editor“ is very simple. It has about 180 lines of code including comments. It has not many functions, just settings of foreground and background color, brush (UTF-8 char selection), eraser and save and load ability. Only one command line option is given, a name of edited file. This files than can be simply displayed in shell, e.g. cat example.ans, but only files creates in SHPaint can be again read and edited.

Another problem I found is, that not all mouse data are in proper format, sometimes some clicks generate randomly some stupid values. In this case, press Ctrl+C and run SHPaint again with same file. Ctrl+C ends program and saves image data.

Few details

For complete informations please check man page console_codes and wiki page about ANSI escape codes.

These codes – escape sequences driving how the terminal will do some special tasks, like changing of colors, screen clear or setting of position.

To enable mouse (in X10 mode), try printf "\e[?9h" (to disable printf "\e[?9l"). Every click than generates information about which button was pressed and his position. Read this data with:

read -N6 a; echo -n $a | hexdump -C

And that's all! The script reads the cursor position, if the position is same as some menu items, than it changes some internal variables, other clicks just displays each „pixels“.

To achieve load and save ability, each click also stores image data in hash array IMAGE, the key of array is "X;Y" and the value contains code of color and brush-char. This format can be easily parsed back to editor.