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>
29 #define MAXDRAWBUF 1024
31 #define SERRNO strerror(errno)
32 #define MIN(a, b) ((a) < (b) ? (a) : (b))
33 #define MAX(a, b) ((a) < (b) ? (b) : (a))
34 #define LEN(a) (sizeof(a) / sizeof(a[0]))
35 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
36 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
37 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
38 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
40 /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
41 enum { ATnone=0 , ATreverse=1 , ATunderline=2, ATbold=4 };
42 enum { CSup, CSdown, CSright, CSleft, CShide, CSdraw, CSwrap, CSsave, CSload };
43 enum { CRset=1, CRupdate=2 };
44 enum { TMwrap=1, TMinsert=2, TMtitle=4 };
45 enum { ESCin = 1, ESCcsi = 2, ESCosc = 4, ESCtitle = 8 };
46 enum { SCupdate, SCredraw };
51 char c; /* character code */
52 char mode; /* attribute flags */
53 Color fg; /* foreground */
54 Color bg; /* background */
55 char state; /* state flag */
61 Glyph attr; /* current char attributes */
67 /* CSI Escape sequence structs */
68 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
70 char buf[ESCSIZ]; /* raw string */
71 int len; /* raw string length */
74 int narg; /* nb of args */
78 /* Internal representation of the screen */
82 Line* line; /* screen */
83 TCursor c; /* cursor */
84 int top; /* top scroll limit */
85 int bot; /* bottom scroll limit */
86 int mode; /* terminal mode */
92 /* Purely graphic info */
97 int w; /* window width */
98 int h; /* window height */
99 int ch; /* char height */
100 int cw; /* char width */
110 /* Drawing Context */
112 unsigned long col[LEN(colorname)];
117 static void die(const char *errstr, ...);
118 static void draw(int);
119 static void execsh(void);
120 static void sigchld(int);
121 static void run(void);
123 static void csidump(void);
124 static void csihandle(void);
125 static void csiparse(void);
126 static void csireset(void);
128 static void tclearregion(int, int, int, int);
129 static void tcpos(int);
130 static void tcursor(int);
131 static void tdeletechar(int);
132 static void tdeleteline(int);
133 static void tinsertblank(int);
134 static void tinsertblankline(int);
135 static void tmoveto(int, int);
136 static void tnew(int, int);
137 static void tnewline(void);
138 static void tputc(char);
139 static void tputs(char*, int);
140 static void tresize(int, int);
141 static void tscroll(void);
142 static void tsetattr(int*, int);
143 static void tsetchar(char);
144 static void tsetscroll(int, int);
146 static void ttynew(void);
147 static void ttyread(void);
148 static void ttyresize(int, int);
149 static void ttywrite(const char *, size_t);
151 static unsigned long xgetcol(const char *);
152 static void xclear(int, int, int, int);
153 static void xcursor(int);
154 static void xdrawc(int, int, Glyph);
155 static void xinit(void);
156 static void xscroll(void);
158 static void expose(XEvent *);
159 static char * kmap(KeySym);
160 static void kpress(XEvent *);
161 static void resize(XEvent *);
163 static void (*handler[LASTEvent])(XEvent *) = {
166 [ConfigureNotify] = resize
173 static CSIEscape escseq;
184 for(row = 0; row < term.row; row++) {
185 for(col = 0; col < term.col; col++) {
186 if(col == term.c.x && row == term.c.y)
189 c = term.line[row][col];
190 putchar(c.state & CRset ? c.c : '.');
199 die(const char *errstr, ...) {
202 va_start(ap, errstr);
203 vfprintf(stderr, errstr, ap);
210 char *args[3] = {SHELL, "-i", NULL};
211 putenv("TERM=" TNAME);
216 xbell(void) { /* visual bell */
217 XRectangle r = { 0, 0, xw.w, xw.h };
218 XSetForeground(xw.dis, dc.gc, dc.col[BellCol]);
219 XFillRectangles(xw.dis, xw.win, dc.gc, &r, 1);
227 if(waitpid(pid, &stat, 0) < 0)
228 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
230 exit(WEXITSTATUS(stat));
240 if((m = posix_openpt(O_RDWR | O_NOCTTY)) < 0)
241 die("openpt failed: %s\n", SERRNO);
243 die("grandpt failed: %s\n", SERRNO);
245 die("unlockpt failed: %s\n", SERRNO);
246 if(!(pts = ptsname(m)))
247 die("ptsname failed: %s\n", SERRNO);
248 if((s = open(pts, O_RDWR | O_NOCTTY)) < 0)
249 die("Couldn't open slave: %s\n", SERRNO);
250 fcntl(s, F_SETFL, O_NDELAY);
251 switch(pid = fork()) {
253 die("fork failed\n");
256 setsid(); /* create a new process group */
257 dup2(s, STDIN_FILENO);
258 dup2(s, STDOUT_FILENO);
259 dup2(s, STDERR_FILENO);
260 if(ioctl(s, TIOCSCTTY, NULL) < 0)
261 die("ioctl TTIOCSTTY failed: %s\n", SERRNO);
267 signal(SIGCHLD, sigchld);
274 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
276 fprintf(stderr, "\n");
281 char buf[BUFSIZ] = {0};
284 switch(ret = read(cmdfd, buf, BUFSIZ)) {
286 die("Couldn't read from shell: %s\n", SERRNO);
294 ttywrite(const char *s, size_t n) {
295 if(write(cmdfd, s, n) == -1)
296 die("write error on tty: %s\n", SERRNO);
300 ttyresize(int x, int y) {
305 w.ws_xpixel = w.ws_ypixel = 0;
306 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
307 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
316 x = term.c.x, y = term.c.y;
317 else if(mode == CSload)
322 tnew(int col, int row) { /* screen size */
323 term.row = row, term.col = col;
324 term.top = 0, term.bot = term.row - 1;
328 term.c.attr.mode = ATnone;
329 term.c.attr.fg = DefaultFG;
330 term.c.attr.bg = DefaultBG;
331 term.c.x = term.c.y = 0;
333 /* allocate screen */
334 term.line = calloc(term.row, sizeof(Line));
335 for(row = 0 ; row < term.row; row++)
336 term.line[row] = calloc(term.col, sizeof(Glyph));
341 Line temp = term.line[term.top];
343 /* X stuff _before_ the line swapping (results in wrong line index) */
345 for(i = term.top; i < term.bot; i++)
346 term.line[i] = term.line[i+1];
347 memset(temp, 0, sizeof(Glyph) * term.col);
348 term.line[term.bot] = temp;
353 int y = term.c.y + 1;
355 tscroll(), y = term.bot;
362 char *p = escseq.buf;
366 escseq.priv = 1, p++;
368 while(p < escseq.buf+escseq.len) {
370 escseq.arg[escseq.narg] *= 10;
371 escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
373 if(*p == ';' && escseq.narg+1 < ESCARGSIZ)
384 tmoveto(int x, int y) {
385 term.c.x = x < 0 ? 0 : x >= term.col ? term.col-1 : x;
386 term.c.y = y < 0 ? 0 : y >= term.row ? term.row-1 : y;
391 int xf = term.c.x, yf = term.c.y;
403 xf = term.col-1, yf--;
405 yf = term.top, xf = 0;
413 yf = term.bot, tscroll();
422 term.line[term.c.y][term.c.x] = term.c.attr;
423 term.line[term.c.y][term.c.x].c = c;
424 term.line[term.c.y][term.c.x].state |= CRset | CRupdate;
428 tclearregion(int x1, int y1, int x2, int y2) {
431 LIMIT(x1, 0, term.col-1);
432 LIMIT(x2, 0, term.col-1);
433 LIMIT(y1, 0, term.row-1);
434 LIMIT(y2, 0, term.row-1);
436 /* XXX: could be optimized */
437 for(x = x1; x <= x2; x++)
438 for(y = y1; y <= y2; y++)
439 memset(&term.line[y][x], 0, sizeof(Glyph));
441 xclear(x1, y1, x2, y2);
446 int src = term.c.x + n;
448 int size = term.col - src;
450 if(src >= term.col) {
451 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
454 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
455 tclearregion(term.col-size, term.c.y, term.col-1, term.c.y);
459 tinsertblank(int n) {
462 int size = term.col - n - src;
464 if(dst >= term.col) {
465 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
468 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
469 tclearregion(src, term.c.y, dst, term.c.y);
473 tsetlinestate(int n, int state) {
475 for(i = 0; i < term.col; i++)
476 term.line[n][i].state |= state;
480 tinsertblankline (int n) {
485 if(term.c.y > term.bot)
487 else if(term.c.y < term.top)
489 if(term.c.y + n >= bot) {
490 tclearregion(0, term.c.y, term.col-1, bot);
493 for(i = bot; i >= term.c.y+n; i--) {
494 /* swap deleted line <-> blanked line */
495 blank = term.line[i];
496 term.line[i] = term.line[i-n];
497 term.line[i-n] = blank;
499 memset(blank, 0, term.col * sizeof(Glyph));
500 tsetlinestate(i, CRupdate);
501 tsetlinestate(i-n, CRupdate);
511 if(term.c.y > term.bot)
513 else if(term.c.y < term.top)
515 if(term.c.y + n >= bot) {
516 tclearregion(0, term.c.y, term.col-1, bot);
519 for(i = term.c.y; i <= bot-n; i++) {
520 /* swap deleted line <-> blanked line */
521 blank = term.line[i];
522 term.line[i] = term.line[i+n];
523 term.line[i+n] = blank;
525 memset(blank, 0, term.col * sizeof(Glyph));
526 tsetlinestate(i, CRupdate);
527 tsetlinestate(i-n, CRupdate);
532 tsetattr(int *attr, int l) {
535 for(i = 0; i < l; i++) {
538 memset(&term.c.attr, 0, sizeof(term.c.attr));
539 term.c.attr.fg = DefaultFG;
540 term.c.attr.bg = DefaultBG;
543 term.c.attr.mode |= ATbold;
546 term.c.attr.mode |= ATunderline;
549 term.c.attr.mode |= ATreverse;
552 term.c.hidden = CShide;
555 term.c.attr.mode &= ~ATbold;
558 term.c.attr.mode &= ~ATunderline;
561 term.c.attr.mode &= ~ATreverse;
564 term.c.attr.fg = DefaultFG;
567 term.c.attr.fg = DefaultBG;
570 if(BETWEEN(attr[i], 30, 37))
571 term.c.attr.fg = attr[i] - 30;
572 else if(BETWEEN(attr[i], 40, 47))
573 term.c.attr.bg = attr[i] - 40;
580 tsetscroll(int t, int b) {
583 LIMIT(t, 0, term.row-1);
584 LIMIT(b, 0, term.row-1);
596 switch(escseq.mode) {
598 fprintf(stderr, "erresc: unknown sequence\n");
602 case '@': /* Insert <n> blank char */
603 DEFAULT(escseq.arg[0], 1);
604 tinsertblank(escseq.arg[0]);
606 case 'A': /* Cursor <n> Up */
608 DEFAULT(escseq.arg[0], 1);
609 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
611 case 'B': /* Cursor <n> Down */
612 DEFAULT(escseq.arg[0], 1);
613 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
615 case 'C': /* Cursor <n> Forward */
617 DEFAULT(escseq.arg[0], 1);
618 tmoveto(term.c.x+escseq.arg[0], term.c.y);
620 case 'D': /* Cursor <n> Backward */
621 DEFAULT(escseq.arg[0], 1);
622 tmoveto(term.c.x-escseq.arg[0], term.c.y);
624 case 'E': /* Cursor <n> Down and first col */
625 DEFAULT(escseq.arg[0], 1);
626 tmoveto(0, term.c.y+escseq.arg[0]);
628 case 'F': /* Cursor <n> Up and first col */
629 DEFAULT(escseq.arg[0], 1);
630 tmoveto(0, term.c.y-escseq.arg[0]);
632 case 'G': /* Move to <col> */
634 DEFAULT(escseq.arg[0], 1);
635 tmoveto(escseq.arg[0]-1, term.c.y);
637 case 'H': /* Move to <row> <col> */
639 DEFAULT(escseq.arg[0], 1);
640 DEFAULT(escseq.arg[1], 1);
641 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
643 case 'J': /* Clear screen */
644 switch(escseq.arg[0]) {
646 tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
649 tclearregion(0, 0, term.c.x, term.c.y);
652 tclearregion(0, 0, term.col-1, term.row-1);
656 case 'K': /* Clear line */
657 switch(escseq.arg[0]) {
659 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
662 tclearregion(0, term.c.y, term.c.x, term.c.y);
665 tclearregion(0, term.c.y, term.col-1, term.c.y);
670 case 'L': /* Insert <n> blank lines */
671 DEFAULT(escseq.arg[0], 1);
672 tinsertblankline(escseq.arg[0]);
675 if(escseq.priv && escseq.arg[0] == 25)
678 case 'M': /* Delete <n> lines */
679 DEFAULT(escseq.arg[0], 1);
680 tdeleteline(escseq.arg[0]);
683 case 'P': /* Delete <n> char */
684 DEFAULT(escseq.arg[0], 1);
685 tdeletechar(escseq.arg[0]);
687 case 'd': /* Move to <row> */
688 DEFAULT(escseq.arg[0], 1);
689 tmoveto(term.c.x, escseq.arg[0]-1);
691 case 'h': /* Set terminal mode */
692 if(escseq.priv && escseq.arg[0] == 25)
695 case 'm': /* Terminal attribute (color) */
696 tsetattr(escseq.arg, escseq.narg);
702 DEFAULT(escseq.arg[0], 1);
703 DEFAULT(escseq.arg[1], term.row);
704 tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
707 case 's': /* Save cursor position */
710 case 'u': /* Load cursor position */
719 printf("ESC [ %s", escseq.priv ? "? " : "");
721 for(i = 0; i < escseq.narg; i++)
722 printf("%d ", escseq.arg[i]);
724 putchar(escseq.mode);
730 memset(&escseq, 0, sizeof(escseq));
735 int space = TAB - term.c.x % TAB;
737 if(term.c.x + space >= term.col)
740 for(; space > 0; space--)
749 if(term.esc & ESCin) {
750 if(term.esc & ESCcsi) {
751 escseq.buf[escseq.len++] = c;
752 if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESCSIZ) {
754 csiparse(), csihandle();
756 } else if (term.esc & ESCosc) {
759 term.esc = ESCin | ESCtitle;
761 } else if(term.esc & ESCtitle) {
762 if(c == '\a' || term.titlelen+1 >= TITLESIZ) {
764 term.title[term.titlelen] = '\0';
765 XStoreName(xw.dis, xw.win, term.title);
767 term.title[term.titlelen++] = c;
788 tmoveto(0, term.c.y);
809 tputs(char *s, int len) {
810 for(; len > 0; len--)
815 tresize(int col, int row) {
818 int minrow = MIN(row, term.row);
819 int mincol = MIN(col, term.col);
821 if(col < 1 || row < 1)
824 line = calloc(row, sizeof(Line));
825 for(i = 0 ; i < row; i++)
826 line[i] = calloc(col, sizeof(Glyph));
828 for(i = 0 ; i < minrow; i++)
829 memcpy(line[i], term.line[i], mincol * sizeof(Glyph));
831 for(i = 0; i < term.row; i++)
835 LIMIT(term.c.x, 0, col-1);
836 LIMIT(term.c.y, 0, row-1);
837 LIMIT(term.top, 0, row-1);
838 LIMIT(term.bot, 0, row-1);
842 term.col = col, term.row = row;
846 xgetcol(const char *s) {
848 Colormap cmap = DefaultColormap(xw.dis, xw.scr);
850 if(!XAllocNamedColor(xw.dis, cmap, s, &color, &color)) {
851 color.pixel = WhitePixel(xw.dis, xw.scr);
852 fprintf(stderr, "Could not allocate color '%s'\n", s);
858 xclear(int x1, int y1, int x2, int y2) {
859 XClearArea(xw.dis, xw.win,
860 x1 * xw.cw, y1 * xw.ch,
861 (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch,
867 int srcy = (term.top+1) * xw.ch;
868 int dsty = term.top * xw.ch;
869 int height = (term.bot-term.top) * xw.ch;
872 XCopyArea(xw.dis, xw.win, xw.win, dc.gc, 0, srcy, xw.w, height, 0, dsty);
873 xclear(0, term.bot, term.col-1, term.bot);
879 unsigned long valuemask;
883 char *args[] = {NULL};
886 xw.dis = XOpenDisplay(NULL);
887 xw.scr = XDefaultScreen(xw.dis);
889 die("Can't open display\n");
892 if(!(dc.font = XLoadQueryFont(xw.dis, FONT)))
893 die("Can't load font %s\n", FONT);
895 xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
896 xw.ch = dc.font->ascent + dc.font->descent + LINESPACE;
899 for(i = 0; i < LEN(colorname); i++)
900 dc.col[i] = xgetcol(colorname[i]);
902 term.c.attr.fg = DefaultFG;
903 term.c.attr.bg = DefaultBG;
904 term.c.attr.mode = ATnone;
906 xw.h = term.row * xw.ch;
907 xw.w = term.col * xw.cw;
908 /* XXX: this BORDER is useless after the first resize, handle it in xdraws() */
909 xw.win = XCreateSimpleWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
914 values.foreground = XWhitePixel(xw.dis, xw.scr);
915 values.font = dc.font->fid;
916 valuemask = GCForeground | GCFont;
917 dc.gc = XCreateGC(xw.dis, xw.win, valuemask, &values);
918 XMapWindow(xw.dis, xw.win);
920 chint.res_name = TNAME, chint.res_class = TNAME;
921 wmhint.input = 1, wmhint.flags = InputHint;
922 shint.height_inc = xw.ch, shint.width_inc = xw.cw;
923 shint.height = xw.h, shint.width = xw.w;
924 shint.flags = PSize | PResizeInc;
925 XSetWMProperties(xw.dis, xw.win, NULL, NULL, &args[0], 0, &shint, &wmhint, &chint);
926 XStoreName(xw.dis, xw.win, TNAME);
931 xdraws (char *s, Glyph base, int x, int y, int len) {
932 unsigned long xfg, xbg;
933 int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
934 if(base.mode & ATreverse)
935 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
937 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
939 XSetBackground(xw.dis, dc.gc, xbg);
940 XSetForeground(xw.dis, dc.gc, xfg);
941 XDrawImageString(xw.dis, xw.win, dc.gc, winx, winy, s, len);
943 if(base.mode & ATunderline)
944 XDrawLine(xw.dis, xw.win, dc.gc, winx, winy+1, winx+width-1, winy+1);
948 xdrawc(int x, int y, Glyph g) {
949 XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
950 unsigned long xfg, xbg;
953 if(g.mode & ATreverse)
954 xfg = dc.col[g.bg], xbg = dc.col[g.fg];
956 xfg = dc.col[g.fg], xbg = dc.col[g.bg];
958 XSetBackground(xw.dis, dc.gc, xbg);
959 XSetForeground(xw.dis, dc.gc, xfg);
960 XDrawImageString(xw.dis, xw.win, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
967 Glyph g = {' ', ATnone, DefaultBG, DefaultCS, 0};
969 LIMIT(oldx, 0, term.col-1);
970 LIMIT(oldy, 0, term.row-1);
972 if(term.line[term.c.y][term.c.x].state & CRset)
973 g.c = term.line[term.c.y][term.c.x].c;
974 /* remove the old cursor */
975 if(term.line[oldy][oldx].state & CRset)
976 xdrawc(oldx, oldy, term.line[oldy][oldx]);
978 xclear(oldx, oldy, oldx, oldy);
979 /* draw the new one */
981 xdrawc(term.c.x, term.c.y, g);
982 oldx = term.c.x, oldy = term.c.y;
987 draw(int redraw_all) {
990 char buf[MAXDRAWBUF];
992 for(y = 0; y < term.row; y++) {
993 base = term.line[y][0];
995 for(x = 0; x < term.col; x++) {
996 new = term.line[y][x];
997 if(!ATTRCMP(base, new) && i < MAXDRAWBUF)
1000 xdraws(buf, base, ox, y, i);
1007 xdraws(buf, base, ox, y, i);
1013 expose(XEvent *ev) {
1020 for(i = 0; i < LEN(key); i++)
1022 return (char*)key[i].s;
1027 kpress(XEvent *ev) {
1028 XKeyEvent *e = &ev->xkey;
1036 meta = e->state & Mod1Mask;
1037 shift = e->state & ShiftMask;
1038 len = XLookupString(e, buf, sizeof(buf), &ksym, NULL);
1040 if(customkey = kmap(ksym))
1041 ttywrite(customkey, strlen(customkey));
1043 buf[sizeof(buf)-1] = '\0';
1044 if(meta && len == 1)
1045 ttywrite("\033", 1);
1051 /* XXX: paste X clipboard */;
1054 fprintf(stderr, "errkey: %d\n", (int)ksym);
1062 col = e->xconfigure.width / xw.cw;
1063 row = e->xconfigure.height / xw.ch;
1065 if(term.col != col || term.row != row) {
1067 ttyresize(col, row);
1068 xw.w = e->xconfigure.width;
1069 xw.h = e->xconfigure.height;
1078 int xfd = XConnectionNumber(xw.dis);
1081 XSelectInput(xw.dis, xw.win, ExposureMask | KeyPressMask | StructureNotifyMask);
1082 XResizeWindow(xw.dis, xw.win, xw.w , xw.h); /* fix resize bug in wmii (?) */
1086 FD_SET(cmdfd, &rfd);
1088 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) == -1) {
1091 die("select failed: %s\n", SERRNO);
1093 if(FD_ISSET(cmdfd, &rfd)) {
1097 while(XPending(xw.dis)) {
1098 XNextEvent(xw.dis, &ev);
1099 if(handler[ev.type])
1100 (handler[ev.type])(&ev);
1106 main(int argc, char *argv[]) {
1107 if(argc == 2 && !strncmp("-v", argv[1], 3))
1108 die("st-" VERSION ", © 2009 st engineers\n");
1110 die("usage: st [-v]\n");
1111 setlocale(LC_CTYPE, "");