1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
13 #include <sys/ioctl.h>
14 #include <sys/select.h>
16 #include <sys/types.h>
20 #include <X11/keysym.h>
21 #include <X11/Xutil.h>
28 #define MAXDRAWBUF 1024
30 #define SERRNO strerror(errno)
31 #define MIN(a, b) ((a) < (b) ? (a) : (b))
32 #define MAX(a, b) ((a) < (b) ? (b) : (a))
33 #define LEN(a) (sizeof(a) / sizeof(a[0]))
34 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
35 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
36 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
37 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
39 /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
40 enum { ATnone=0 , ATreverse=1 , ATunderline=2, ATbold=4 };
41 enum { CSup, CSdown, CSright, CSleft, CShide, CSdraw, CSwrap, CSsave, CSload };
42 enum { CRset=1, CRupdate=2 };
43 enum { TMwrap=1, TMinsert=2 };
44 enum { SCupdate, SCredraw };
49 char c; /* character code */
50 char mode; /* attribute flags */
51 Color fg; /* foreground */
52 Color bg; /* background */
53 char state; /* state flag */
59 Glyph attr; /* current char attributes */
65 /* Escape sequence structs */
66 /* ESC <pre> [[ [<priv>] <arg> [;]] <mode>] */
68 char buf[ESCSIZ+1]; /* raw string */
69 int len; /* raw string length */
73 int narg; /* nb of args */
77 /* Internal representation of the screen */
81 Line* line; /* screen */
82 TCursor c; /* cursor */
83 int top; /* top scroll limit */
84 int bot; /* bottom scroll limit */
85 int mode; /* terminal mode */
88 /* Purely graphic info */
93 int w; /* window width */
94 int h; /* window height */
95 int ch; /* char height */
96 int cw; /* char width */
106 /* Drawing Context */
108 unsigned long col[LEN(colorname)];
113 static void die(const char *errstr, ...);
114 static void draw(int);
115 static void execsh(void);
116 static void sigchld(int);
117 static void run(void);
119 static int escaddc(char);
120 static int escfinal(char);
121 static void escdump(void);
122 static void eschandle(void);
123 static void escparse(void);
124 static void escreset(void);
126 static void tclearregion(int, int, int, int);
127 static void tcpos(int);
128 static void tcursor(int);
129 static void tdeletechar(int);
130 static void tdeleteline(int);
131 static void tinsertblank(int);
132 static void tinsertblankline(int);
133 static void tmoveto(int, int);
134 static void tnew(int, int);
135 static void tnewline(void);
136 static void tputc(char);
137 static void tputs(char*, int);
138 static void tresize(int, int);
139 static void tscroll(void);
140 static void tsetattr(int*, int);
141 static void tsetchar(char);
142 static void tsetscroll(int, int);
144 static void ttynew(void);
145 static void ttyread(void);
146 static void ttyresize(int, int);
147 static void ttywrite(const char *, size_t);
149 static unsigned long xgetcol(const char *);
150 static void xclear(int, int, int, int);
151 static void xcursor(int);
152 static void xdrawc(int, int, Glyph);
153 static void xinit(void);
154 static void xscroll(void);
156 static void expose(XEvent *);
157 static char * kmap(KeySym);
158 static void kpress(XEvent *);
159 static void resize(XEvent *);
161 static void (*handler[LASTEvent])(XEvent *) = {
164 [ConfigureNotify] = resize
171 static Escseq escseq;
182 for(row = 0; row < term.row; row++) {
183 for(col = 0; col < term.col; col++) {
184 if(col == term.c.x && row == term.c.y)
187 c = term.line[row][col];
188 putchar(c.state & CRset ? c.c : '.');
197 die(const char *errstr, ...) {
200 va_start(ap, errstr);
201 vfprintf(stderr, errstr, ap);
208 char *args[3] = {SHELL, "-i", NULL};
209 putenv("TERM=" TNAME);
214 xbell(void) { /* visual bell */
215 XRectangle r = { 0, 0, xw.w, xw.h };
216 XSetForeground(xw.dis, dc.gc, dc.col[BellCol]);
217 XFillRectangles(xw.dis, xw.win, dc.gc, &r, 1);
225 if(waitpid(pid, &stat, 0) < 0)
226 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
228 exit(WEXITSTATUS(stat));
238 if((m = posix_openpt(O_RDWR | O_NOCTTY)) < 0)
239 die("openpt failed: %s\n", SERRNO);
241 die("grandpt failed: %s\n", SERRNO);
243 die("unlockpt failed: %s\n", SERRNO);
244 if(!(pts = ptsname(m)))
245 die("ptsname failed: %s\n", SERRNO);
246 if((s = open(pts, O_RDWR | O_NOCTTY)) < 0)
247 die("Couldn't open slave: %s\n", SERRNO);
248 fcntl(s, F_SETFL, O_NDELAY);
249 switch(pid = fork()) {
251 die("fork failed\n");
254 setsid(); /* create a new process group */
255 dup2(s, STDIN_FILENO);
256 dup2(s, STDOUT_FILENO);
257 dup2(s, STDERR_FILENO);
258 if(ioctl(s, TIOCSCTTY, NULL) < 0)
259 die("ioctl TTIOCSTTY failed: %s\n", SERRNO);
265 signal(SIGCHLD, sigchld);
272 fprintf(stderr, " %02x %c ", c, isprint(c)?c:'.');
274 fprintf(stderr, "\n");
279 char buf[BUFSIZ] = {0};
282 switch(ret = read(cmdfd, buf, BUFSIZ)) {
284 die("Couldn't read from shell: %s\n", SERRNO);
292 ttywrite(const char *s, size_t n) {
293 if(write(cmdfd, s, n) == -1)
294 die("write error on tty: %s\n", SERRNO);
298 ttyresize(int x, int y) {
303 w.ws_xpixel = w.ws_ypixel = 0;
304 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
305 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
321 else if(BETWEEN(c, 0x40, 0x7E))
332 x = term.c.x, y = term.c.y;
333 else if(mode == CSload)
338 tnew(int col, int row) { /* screen size */
339 term.row = row, term.col = col;
340 term.top = 0, term.bot = term.row - 1;
344 term.c.attr.mode = ATnone;
345 term.c.attr.fg = DefaultFG;
346 term.c.attr.bg = DefaultBG;
347 term.c.x = term.c.y = 0;
349 /* allocate screen */
350 term.line = calloc(term.row, sizeof(Line));
351 for(row = 0 ; row < term.row; row++)
352 term.line[row] = calloc(term.col, sizeof(Glyph));
357 Line temp = term.line[term.top];
359 /* X stuff _before_ the line swapping (results in wrong line index) */
361 for(i = term.top; i < term.bot; i++)
362 term.line[i] = term.line[i+1];
363 memset(temp, 0, sizeof(Glyph) * term.col);
364 term.line[term.bot] = temp;
369 int y = term.c.y + 1;
371 tscroll(), y = term.bot;
377 escseq.buf[escseq.len++] = c;
378 if(escfinal(c) || escseq.len >= ESCSIZ) {
379 escparse(), eschandle();
388 char *p = escseq.buf;
391 switch(escseq.pre = *p++) {
394 escseq.priv = 1, p++;
396 while(p < escseq.buf+escseq.len) {
398 escseq.arg[escseq.narg] *= 10;
399 escseq.arg[escseq.narg] += *(p++) - '0'/*, noarg = 0 */;
411 /* XXX: graphic character set */
417 tmoveto(int x, int y) {
418 term.c.x = x < 0 ? 0 : x >= term.col ? term.col-1 : x;
419 term.c.y = y < 0 ? 0 : y >= term.row ? term.row-1 : y;
424 int xf = term.c.x, yf = term.c.y;
436 xf = term.col-1, yf--;
438 yf = term.top, xf = 0;
446 yf = term.bot, tscroll();
455 term.line[term.c.y][term.c.x] = term.c.attr;
456 term.line[term.c.y][term.c.x].c = c;
457 term.line[term.c.y][term.c.x].state |= CRset | CRupdate;
461 tclearregion(int x1, int y1, int x2, int y2) {
464 LIMIT(x1, 0, term.col-1);
465 LIMIT(x2, 0, term.col-1);
466 LIMIT(y1, 0, term.row-1);
467 LIMIT(y2, 0, term.row-1);
469 /* XXX: could be optimized */
470 for(x = x1; x <= x2; x++)
471 for(y = y1; y <= y2; y++)
472 memset(&term.line[y][x], 0, sizeof(Glyph));
474 xclear(x1, y1, x2, y2);
479 int src = term.c.x + n;
481 int size = term.col - src;
483 if(src >= term.col) {
484 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
487 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
488 tclearregion(term.col-size, term.c.y, term.col-1, term.c.y);
492 tinsertblank(int n) {
495 int size = term.col - n - src;
497 if(dst >= term.col) {
498 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
501 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
502 tclearregion(src, term.c.y, dst, term.c.y);
506 tsetlinestate(int n, int state) {
508 for(i = 0; i < term.col; i++)
509 term.line[n][i].state |= state;
513 tinsertblankline (int n) {
518 if(term.c.y > term.bot)
520 else if(term.c.y < term.top)
522 if(term.c.y + n >= bot) {
523 tclearregion(0, term.c.y, term.col-1, bot);
526 for(i = bot; i >= term.c.y+n; i--) {
527 /* swap deleted line <-> blanked line */
528 blank = term.line[i];
529 term.line[i] = term.line[i-n];
530 term.line[i-n] = blank;
532 memset(blank, 0, term.col * sizeof(Glyph));
533 tsetlinestate(i, CRupdate);
534 tsetlinestate(i-n, CRupdate);
544 if(term.c.y > term.bot)
546 else if(term.c.y < term.top)
548 if(term.c.y + n >= bot) {
549 tclearregion(0, term.c.y, term.col-1, bot);
552 for(i = term.c.y; i <= bot-n; i++) {
553 /* swap deleted line <-> blanked line */
554 blank = term.line[i];
555 term.line[i] = term.line[i+n];
556 term.line[i+n] = blank;
558 memset(blank, 0, term.col * sizeof(Glyph));
559 tsetlinestate(i, CRupdate);
560 tsetlinestate(i-n, CRupdate);
565 tsetattr(int *attr, int l) {
568 for(i = 0; i < l; i++) {
571 memset(&term.c.attr, 0, sizeof(term.c.attr));
572 term.c.attr.fg = DefaultFG;
573 term.c.attr.bg = DefaultBG;
576 term.c.attr.mode |= ATbold;
579 term.c.attr.mode |= ATunderline;
582 term.c.attr.mode |= ATreverse;
585 term.c.hidden = CShide;
588 term.c.attr.mode &= ~ATbold;
591 term.c.attr.mode &= ~ATunderline;
594 term.c.attr.mode &= ~ATreverse;
597 term.c.attr.fg = DefaultFG;
600 term.c.attr.fg = DefaultBG;
603 if(BETWEEN(attr[i], 30, 37))
604 term.c.attr.fg = attr[i] - 30;
605 else if(BETWEEN(attr[i], 40, 47))
606 term.c.attr.bg = attr[i] - 40;
613 tsetscroll(int t, int b) {
616 LIMIT(t, 0, term.row-1);
617 LIMIT(b, 0, term.row-1);
633 switch(escseq.mode) {
636 fprintf(stderr, "erresc: unknown sequence\n");
639 case '@': /* Insert <n> blank char */
640 DEFAULT(escseq.arg[0], 1);
641 tinsertblank(escseq.arg[0]);
643 case 'A': /* Cursor <n> Up */
645 DEFAULT(escseq.arg[0], 1);
646 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
648 case 'B': /* Cursor <n> Down */
649 DEFAULT(escseq.arg[0], 1);
650 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
652 case 'C': /* Cursor <n> Forward */
654 DEFAULT(escseq.arg[0], 1);
655 tmoveto(term.c.x+escseq.arg[0], term.c.y);
657 case 'D': /* Cursor <n> Backward */
658 DEFAULT(escseq.arg[0], 1);
659 tmoveto(term.c.x-escseq.arg[0], term.c.y);
661 case 'E': /* Cursor <n> Down and first col */
662 DEFAULT(escseq.arg[0], 1);
663 tmoveto(0, term.c.y+escseq.arg[0]);
665 case 'F': /* Cursor <n> Up and first col */
666 DEFAULT(escseq.arg[0], 1);
667 tmoveto(0, term.c.y-escseq.arg[0]);
669 case 'G': /* Move to <col> */
671 DEFAULT(escseq.arg[0], 1);
672 tmoveto(escseq.arg[0]-1, term.c.y);
674 case 'H': /* Move to <row> <col> */
676 DEFAULT(escseq.arg[0], 1);
677 DEFAULT(escseq.arg[1], 1);
678 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
680 case 'J': /* Clear screen */
681 switch(escseq.arg[0]) {
683 tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
686 tclearregion(0, 0, term.c.x, term.c.y);
689 tclearregion(0, 0, term.col-1, term.row-1);
693 case 'K': /* Clear line */
694 switch(escseq.arg[0]) {
696 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
699 tclearregion(0, term.c.y, term.c.x, term.c.y);
702 tclearregion(0, term.c.y, term.col-1, term.c.y);
706 case 'L': /* Insert <n> blank lines */
707 DEFAULT(escseq.arg[0], 1);
708 tinsertblankline(escseq.arg[0]);
711 if(escseq.priv && escseq.arg[0] == 25)
714 case 'M': /* Delete <n> lines */
715 DEFAULT(escseq.arg[0], 1);
716 tdeleteline(escseq.arg[0]);
718 case 'P': /* Delete <n> char */
719 DEFAULT(escseq.arg[0], 1);
720 tdeletechar(escseq.arg[0]);
722 case 'd': /* Move to <row> */
723 DEFAULT(escseq.arg[0], 1);
724 tmoveto(term.c.x, escseq.arg[0]-1);
726 case 'h': /* Set terminal mode */
727 if(escseq.priv && escseq.arg[0] == 25)
730 case 'm': /* Terminal attribute (color) */
731 tsetattr(escseq.arg, escseq.narg);
737 DEFAULT(escseq.arg[0], 1);
738 DEFAULT(escseq.arg[1], term.row);
739 tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
742 case 's': /* Save cursor position */
745 case 'u': /* Load cursor position */
756 printf("rawbuf : %s\n", escseq.buf);
757 printf("prechar : %c\n", escseq.pre);
758 printf("private : %c\n", escseq.priv ? '?' : ' ');
759 printf("narg : %d\n", escseq.narg);
761 for(i = 0; i < escseq.narg; i++)
762 printf("\targ %d = %d\n", i, escseq.arg[i]);
763 printf("mode : %c\n", escseq.mode);
768 memset(&escseq, 0, sizeof(escseq));
773 int space = TAB - term.c.x % TAB;
775 if(term.c.x + space >= term.col)
778 for(; space > 0; space--)
784 static int inesc = 0;
788 /* start of escseq */
790 escreset(), inesc = 1;
806 tmoveto(0, term.c.y);
818 tputs(char *s, int len) {
819 for(; len > 0; len--)
824 tresize(int col, int row) {
827 int minrow = MIN(row, term.row);
828 int mincol = MIN(col, term.col);
830 if(col < 1 || row < 1)
833 line = calloc(row, sizeof(Line));
834 for(i = 0 ; i < row; i++)
835 line[i] = calloc(col, sizeof(Glyph));
837 for(i = 0 ; i < minrow; i++)
838 memcpy(line[i], term.line[i], mincol * sizeof(Glyph));
840 for(i = 0; i < term.row; i++)
844 LIMIT(term.c.x, 0, col-1);
845 LIMIT(term.c.y, 0, row-1);
846 LIMIT(term.top, 0, row-1);
847 LIMIT(term.bot, 0, row-1);
851 term.col = col, term.row = row;
855 xgetcol(const char *s) {
857 Colormap cmap = DefaultColormap(xw.dis, xw.scr);
859 if(!XAllocNamedColor(xw.dis, cmap, s, &color, &color)) {
860 color.pixel = WhitePixel(xw.dis, xw.scr);
861 fprintf(stderr, "Could not allocate color '%s'\n", s);
867 xclear(int x1, int y1, int x2, int y2) {
868 XClearArea(xw.dis, xw.win,
869 x1 * xw.cw, y1 * xw.ch,
870 (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch,
876 int srcy = (term.top+1) * xw.ch;
877 int dsty = term.top * xw.ch;
878 int height = (term.bot-term.top) * xw.ch;
881 XCopyArea(xw.dis, xw.win, xw.win, dc.gc, 0, srcy, xw.w, height, 0, dsty);
882 xclear(0, term.bot, term.col-1, term.bot);
888 unsigned long valuemask;
892 char *args[] = {NULL};
895 xw.dis = XOpenDisplay(NULL);
896 xw.scr = XDefaultScreen(xw.dis);
898 die("Can't open display\n");
901 if(!(dc.font = XLoadQueryFont(xw.dis, FONT)))
902 die("Can't load font %s\n", FONT);
904 xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
905 xw.ch = dc.font->ascent + dc.font->descent + LINESPACE;
908 for(i = 0; i < LEN(colorname); i++)
909 dc.col[i] = xgetcol(colorname[i]);
911 term.c.attr.fg = DefaultFG;
912 term.c.attr.bg = DefaultBG;
913 term.c.attr.mode = ATnone;
915 xw.h = term.row * xw.ch;
916 xw.w = term.col * xw.cw;
917 /* XXX: this BORDER is useless after the first resize, handle it in xdraws() */
918 xw.win = XCreateSimpleWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
923 values.foreground = XWhitePixel(xw.dis, xw.scr);
924 values.font = dc.font->fid;
925 valuemask = GCForeground | GCFont;
926 dc.gc = XCreateGC(xw.dis, xw.win, valuemask, &values);
927 XMapWindow(xw.dis, xw.win);
929 chint.res_name = TNAME, chint.res_class = TNAME;
930 wmhint.input = 1, wmhint.flags = InputHint;
931 shint.height_inc = xw.ch, shint.width_inc = xw.cw;
932 shint.height = xw.h, shint.width = xw.w;
933 shint.flags = PSize | PResizeInc;
934 XSetWMProperties(xw.dis, xw.win, NULL, NULL, &args[0], 0, &shint, &wmhint, &chint);
935 XStoreName(xw.dis, xw.win, TNAME);
940 xdraws (char *s, Glyph base, int x, int y, int len) {
941 unsigned long xfg, xbg;
942 int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
943 if(base.mode & ATreverse)
944 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
946 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
948 XSetBackground(xw.dis, dc.gc, xbg);
949 XSetForeground(xw.dis, dc.gc, xfg);
950 XDrawImageString(xw.dis, xw.win, dc.gc, winx, winy, s, len);
952 if(base.mode & ATunderline)
953 XDrawLine(xw.dis, xw.win, dc.gc, winx, winy+1, winx+width-1, winy+1);
957 xdrawc(int x, int y, Glyph g) {
958 XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
959 unsigned long xfg, xbg;
962 if(g.mode & ATreverse)
963 xfg = dc.col[g.bg], xbg = dc.col[g.fg];
965 xfg = dc.col[g.fg], xbg = dc.col[g.bg];
967 XSetBackground(xw.dis, dc.gc, xbg);
968 XSetForeground(xw.dis, dc.gc, xfg);
969 XDrawImageString(xw.dis, xw.win, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
976 Glyph g = {' ', ATnone, DefaultBG, DefaultCS, 0};
978 LIMIT(oldx, 0, term.col-1);
979 LIMIT(oldy, 0, term.row-1);
981 if(term.line[term.c.y][term.c.x].state & CRset)
982 g.c = term.line[term.c.y][term.c.x].c;
983 /* remove the old cursor */
984 if(term.line[oldy][oldx].state & CRset)
985 xdrawc(oldx, oldy, term.line[oldy][oldx]);
987 xclear(oldx, oldy, oldx, oldy);
988 /* draw the new one */
990 xdrawc(term.c.x, term.c.y, g);
991 oldx = term.c.x, oldy = term.c.y;
996 draw(int redraw_all) {
999 char buf[MAXDRAWBUF];
1001 for(y = 0; y < term.row; y++) {
1002 base = term.line[y][0];
1004 for(x = 0; x < term.col; x++) {
1005 new = term.line[y][x];
1006 if(!ATTRCMP(base, new) && i < MAXDRAWBUF)
1009 xdraws(buf, base, ox, y, i);
1016 xdraws(buf, base, ox, y, i);
1022 expose(XEvent *ev) {
1029 for(i = 0; i < LEN(key); i++)
1031 return (char*)key[i].s;
1036 kpress(XEvent *ev) {
1037 XKeyEvent *e = &ev->xkey;
1045 meta = e->state & Mod1Mask;
1046 shift = e->state & ShiftMask;
1047 len = XLookupString(e, buf, sizeof(buf), &ksym, NULL);
1049 if(customkey = kmap(ksym))
1050 ttywrite(customkey, strlen(customkey));
1052 buf[sizeof(buf)-1] = '\0';
1053 if(meta && len == 1)
1054 ttywrite("\033", 1);
1060 /* XXX: paste X clipboard */;
1063 fprintf(stderr, "errkey: %d\n", (int)ksym);
1071 col = e->xconfigure.width / xw.cw;
1072 row = e->xconfigure.height / xw.ch;
1074 if(term.col != col || term.row != row) {
1076 ttyresize(col, row);
1077 xw.w = e->xconfigure.width;
1078 xw.h = e->xconfigure.height;
1087 int xfd = XConnectionNumber(xw.dis);
1090 XSelectInput(xw.dis, xw.win, ExposureMask | KeyPressMask | StructureNotifyMask);
1091 XResizeWindow(xw.dis, xw.win, xw.w , xw.h); /* fix resize bug in wmii (?) */
1095 FD_SET(cmdfd, &rfd);
1097 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) == -1) {
1100 die("select failed: %s\n", SERRNO);
1102 if(FD_ISSET(cmdfd, &rfd)) {
1106 while(XPending(xw.dis)) {
1107 XNextEvent(xw.dis, &ev);
1108 if(handler[ev.type])
1109 (handler[ev.type])(&ev);
1115 main(int argc, char *argv[]) {
1116 if(argc == 2 && !strncmp("-v", argv[1], 3))
1117 die("st-" VERSION ", © 2009 st engineers\n");
1119 die("usage: st [-v]\n");
1120 setlocale(LC_CTYPE, "");