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/Xatom.h>
21 #include <X11/keysym.h>
22 #include <X11/Xutil.h>
26 #elif defined(__OpenBSD__) || defined(__NetBSD__)
28 #elif defined(__FreeBSD__) || defined(__DragonFly__)
33 "st-" VERSION ", (c) 2010 st engineers\n" \
34 "usage: st [-t title] [-e cmd] [-v]\n"
37 #define ESC_TITLE_SIZ 256
38 #define ESC_BUF_SIZ 256
39 #define ESC_ARG_SIZ 16
40 #define DRAW_BUF_SIZ 1024
42 #define SERRNO strerror(errno)
43 #define MIN(a, b) ((a) < (b) ? (a) : (b))
44 #define MAX(a, b) ((a) < (b) ? (b) : (a))
45 #define LEN(a) (sizeof(a) / sizeof(a[0]))
46 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
47 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
48 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
49 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
50 #define IS_SET(flag) (term.mode & (flag))
52 /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
53 enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
54 enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT,
55 CURSOR_SAVE, CURSOR_LOAD };
56 enum { CURSOR_DEFAULT = 0, CURSOR_HIDE = 1, CURSOR_WRAPNEXT = 2 };
57 enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
58 enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4, MODE_ALTSCREEN=8 };
59 enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
60 enum { SCREEN_UPDATE, SCREEN_REDRAW };
63 char c; /* character code */
64 char mode; /* attribute flags */
65 int fg; /* foreground */
66 int bg; /* background */
67 char state; /* state flags */
73 Glyph attr; /* current char attributes */
79 /* CSI Escape sequence structs */
80 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
82 char buf[ESC_BUF_SIZ]; /* raw string */
83 int len; /* raw string length */
86 int narg; /* nb of args */
90 /* Internal representation of the screen */
94 Line* line; /* screen */
95 Line* alt; /* alternate screen */
96 TCursor c; /* cursor */
97 int top; /* top scroll limit */
98 int bot; /* bottom scroll limit */
99 int mode; /* terminal mode flags */
100 int esc; /* escape state flags */
101 char title[ESC_TITLE_SIZ];
105 /* Purely graphic info */
114 int w; /* window width */
115 int h; /* window height */
116 int bufw; /* pixmap width */
117 int bufh; /* pixmap height */
118 int ch; /* char height */
119 int cw; /* char width */
121 int vis; /* is visible */
129 /* Drawing Context */
131 unsigned long col[256];
137 /* TODO: use better name for vars... */
142 struct {int x, y;} b, e;
148 static void die(const char *errstr, ...);
149 static void draw(int);
150 static void execsh(void);
151 static void sigchld(int);
152 static void run(void);
154 static void csidump(void);
155 static void csihandle(void);
156 static void csiparse(void);
157 static void csireset(void);
159 static void tclearregion(int, int, int, int);
160 static void tcursor(int);
161 static void tdeletechar(int);
162 static void tdeleteline(int);
163 static void tinsertblank(int);
164 static void tinsertblankline(int);
165 static void tmoveto(int, int);
166 static void tnew(int, int);
167 static void tnewline(void);
168 static void tputtab(void);
169 static void tputc(char);
170 static void tputs(char*, int);
171 static void treset(void);
172 static void tresize(int, int);
173 static void tscrollup(int, int);
174 static void tscrolldown(int, int);
175 static void tsetattr(int*, int);
176 static void tsetchar(char);
177 static void tsetscroll(int, int);
178 static void tswapscreen(void);
180 static void ttynew(void);
181 static void ttyread(void);
182 static void ttyresize(int, int);
183 static void ttywrite(const char *, size_t);
185 static void xdraws(char *, Glyph, int, int, int);
186 static void xhints(void);
187 static void xclear(int, int, int, int);
188 static void xdrawcursor(void);
189 static void xinit(void);
190 static void xloadcols(void);
191 static void xseturgency(int);
193 static void expose(XEvent *);
194 static void visibility(XEvent *);
195 static void unmap(XEvent *);
196 static char* kmap(KeySym);
197 static void kpress(XEvent *);
198 static void resize(XEvent *);
199 static void focus(XEvent *);
200 static void brelease(XEvent *);
201 static void bpress(XEvent *);
202 static void bmotion(XEvent *);
203 static void selection_notify(XEvent *);
204 static void selection_request(XEvent *);
206 static void (*handler[LASTEvent])(XEvent *) = {
208 [ConfigureNotify] = resize,
209 [VisibilityNotify] = visibility,
210 [UnmapNotify] = unmap,
214 [MotionNotify] = bmotion,
215 [ButtonPress] = bpress,
216 [ButtonRelease] = brelease,
217 [SelectionNotify] = selection_notify,
218 [SelectionRequest] = selection_request,
225 static CSIEscape escseq;
228 static Selection sel;
229 static char *opt_cmd = NULL;
230 static char *opt_title = NULL;
239 static inline int selected(int x, int y) {
240 if(sel.ey == y && sel.by == y) {
241 int bx = MIN(sel.bx, sel.ex);
242 int ex = MAX(sel.bx, sel.ex);
243 return BETWEEN(x, bx, ex);
245 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
246 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
249 static void getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
251 *b = e->xbutton.button;
253 *x = e->xbutton.x/xw.cw;
254 *y = e->xbutton.y/xw.ch;
255 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
256 sel.b.y = MIN(sel.by, sel.ey);
257 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
258 sel.e.y = MAX(sel.by, sel.ey);
261 static void bpress(XEvent *e) {
263 sel.ex = sel.bx = e->xbutton.x/xw.cw;
264 sel.ey = sel.by = e->xbutton.y/xw.ch;
267 static char *getseltext() {
272 sz = (term.col+1) * (sel.e.y-sel.b.y+1);
273 ptr = str = malloc(sz);
274 for(y = 0; y < term.row; y++) {
275 for(x = 0; x < term.col; x++)
276 if(term.line[y][x].state & GLYPH_SET && (ls = selected(x, y)))
277 *ptr = term.line[y][x].c, ptr++;
285 static void selection_notify(XEvent *e) {
286 unsigned long nitems;
287 unsigned long length;
292 res = XGetWindowProperty(xw.dis, xw.win, XA_PRIMARY, 0, 0, False,
293 AnyPropertyType, &type, &format, &nitems, &length, &data);
298 fprintf(stderr, "Invalid paste, XGetWindowProperty0");
302 res = XGetWindowProperty(xw.dis, xw.win, XA_PRIMARY, 0, length, False,
303 AnyPropertyType, &type, &format, &nitems, &length, &data);
308 fprintf(stderr, "Invalid paste, XGetWindowProperty0");
313 ttywrite((const char *) data, nitems * format / 8);
318 static void selpaste() {
319 XConvertSelection(xw.dis, XA_PRIMARY, XA_STRING, XA_PRIMARY, xw.win, CurrentTime);
322 static void selection_request(XEvent *e)
324 XSelectionRequestEvent *xsre;
329 xsre = (XSelectionRequestEvent *) e;
330 xev.type = SelectionNotify;
331 xev.requestor = xsre->requestor;
332 xev.selection = xsre->selection;
333 xev.target = xsre->target;
334 xev.time = xsre->time;
338 xa_targets = XInternAtom(xw.dis, "TARGETS", 0);
339 if(xsre->target == xa_targets) {
340 /* respond with the supported type */
341 Atom string = XA_STRING;
342 res = XChangeProperty(xsre->display, xsre->requestor, xsre->property, XA_ATOM, 32,
343 PropModeReplace, (unsigned char *) &string, 1);
350 fprintf(stderr, "Error in selection_request, TARGETS");
353 xev.property = xsre->property;
355 } else if(xsre->target == XA_STRING) {
356 res = XChangeProperty(xsre->display, xsre->requestor, xsre->property,
357 xsre->target, 8, PropModeReplace, (unsigned char *) sel.clip,
365 fprintf(stderr, "Error in selection_request, XA_STRING");
368 xev.property = xsre->property;
372 /* all done, send a notification to the listener */
373 res = XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev);
378 fprintf(stderr, "Error in selection_requested, XSendEvent");
382 static void selcopy(char *str) {
383 /* register the selection for both the clipboard and the primary */
390 res = XSetSelectionOwner(xw.dis, XA_PRIMARY, xw.win, CurrentTime);
394 fprintf(stderr, "Invalid copy, XSetSelectionOwner");
398 clipboard = XInternAtom(xw.dis, "CLIPBOARD", 0);
399 res = XSetSelectionOwner(xw.dis, clipboard, xw.win, CurrentTime);
403 fprintf(stderr, "Invalid copy, XSetSelectionOwner");
410 /* TODO: doubleclick to select word */
411 static void brelease(XEvent *e) {
414 getbuttoninfo(e, &b, &sel.ex, &sel.ey);
415 if(sel.bx==sel.ex && sel.by==sel.ey) {
421 selcopy(getseltext());
426 static void bmotion(XEvent *e) {
428 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
439 for(row = 0; row < term.row; row++) {
440 for(col = 0; col < term.col; col++) {
441 if(col == term.c.x && row == term.c.y)
444 c = term.line[row][col];
445 putchar(c.state & GLYPH_SET ? c.c : '.');
454 die(const char *errstr, ...) {
457 va_start(ap, errstr);
458 vfprintf(stderr, errstr, ap);
465 char *args[] = {getenv("SHELL"), "-i", NULL};
467 args[0] = opt_cmd, args[1] = NULL;
469 DEFAULT(args[0], SHELL);
470 putenv("TERM="TNAME);
471 execvp(args[0], args);
477 if(waitpid(pid, &stat, 0) < 0)
478 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
480 exit(WEXITSTATUS(stat));
489 /* seems to work fine on linux, openbsd and freebsd */
490 struct winsize w = {term.row, term.col, 0, 0};
491 if(openpty(&m, &s, NULL, NULL, &w) < 0)
492 die("openpty failed: %s\n", SERRNO);
494 switch(pid = fork()) {
496 die("fork failed\n");
499 setsid(); /* create a new process group */
500 dup2(s, STDIN_FILENO);
501 dup2(s, STDOUT_FILENO);
502 dup2(s, STDERR_FILENO);
503 if(ioctl(s, TIOCSCTTY, NULL) < 0)
504 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
512 signal(SIGCHLD, sigchld);
519 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
521 fprintf(stderr, "\n");
529 if((ret = read(cmdfd, buf, LEN(buf))) < 0)
530 die("Couldn't read from shell: %s\n", SERRNO);
536 ttywrite(const char *s, size_t n) {
537 if(write(cmdfd, s, n) == -1)
538 die("write error on tty: %s\n", SERRNO);
542 ttyresize(int x, int y) {
547 w.ws_xpixel = w.ws_ypixel = 0;
548 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
549 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
556 if(mode == CURSOR_SAVE)
558 else if(mode == CURSOR_LOAD)
559 term.c = c, tmoveto(c.x, c.y);
568 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
570 term.top = 0, term.bot = term.row - 1;
571 term.mode = MODE_WRAP;
572 tclearregion(0, 0, term.col-1, term.row-1);
576 tnew(int col, int row) {
577 /* set screen size */
578 term.row = row, term.col = col;
579 term.line = malloc(term.row * sizeof(Line));
580 term.alt = malloc(term.row * sizeof(Line));
581 for(row = 0 ; row < term.row; row++) {
582 term.line[row] = malloc(term.col * sizeof(Glyph));
583 term.alt [row] = malloc(term.col * sizeof(Glyph));
591 Line* tmp = term.line;
592 term.line = term.alt;
594 term.mode ^= MODE_ALTSCREEN;
598 tscrolldown(int orig, int n) {
602 LIMIT(n, 0, term.bot-orig+1);
604 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
606 for(i = term.bot; i >= orig+n; i--) {
608 term.line[i] = term.line[i-n];
609 term.line[i-n] = temp;
614 tscrollup(int orig, int n) {
617 LIMIT(n, 0, term.bot-orig+1);
619 tclearregion(0, orig, term.col-1, orig+n-1);
621 for(i = orig; i <= term.bot-n; i++) {
623 term.line[i] = term.line[i+n];
624 term.line[i+n] = temp;
631 if(term.c.y == term.bot)
632 tscrollup(term.top, 1);
641 char *p = escseq.buf;
645 escseq.priv = 1, p++;
647 while(p < escseq.buf+escseq.len) {
649 escseq.arg[escseq.narg] *= 10;
650 escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
652 if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
663 tmoveto(int x, int y) {
664 LIMIT(x, 0, term.col-1);
665 LIMIT(y, 0, term.row-1);
666 term.c.state &= ~CURSOR_WRAPNEXT;
673 term.line[term.c.y][term.c.x] = term.c.attr;
674 term.line[term.c.y][term.c.x].c = c;
675 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
679 tclearregion(int x1, int y1, int x2, int y2) {
683 temp = x1, x1 = x2, x2 = temp;
685 temp = y1, y1 = y2, y2 = temp;
687 LIMIT(x1, 0, term.col-1);
688 LIMIT(x2, 0, term.col-1);
689 LIMIT(y1, 0, term.row-1);
690 LIMIT(y2, 0, term.row-1);
692 for(y = y1; y <= y2; y++)
693 for(x = x1; x <= x2; x++)
694 term.line[y][x].state = 0;
699 int src = term.c.x + n;
701 int size = term.col - src;
703 if(src >= term.col) {
704 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
707 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
708 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
712 tinsertblank(int n) {
715 int size = term.col - dst;
717 if(dst >= term.col) {
718 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
721 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
722 tclearregion(src, term.c.y, dst - 1, term.c.y);
726 tinsertblankline(int n) {
727 if(term.c.y < term.top || term.c.y > term.bot)
730 tscrolldown(term.c.y, n);
735 if(term.c.y < term.top || term.c.y > term.bot)
738 tscrollup(term.c.y, n);
742 tsetattr(int *attr, int l) {
745 for(i = 0; i < l; i++) {
748 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
749 term.c.attr.fg = DefaultFG;
750 term.c.attr.bg = DefaultBG;
753 term.c.attr.mode |= ATTR_BOLD;
756 term.c.attr.mode |= ATTR_UNDERLINE;
759 term.c.attr.mode |= ATTR_REVERSE;
762 term.c.attr.mode &= ~ATTR_BOLD;
765 term.c.attr.mode &= ~ATTR_UNDERLINE;
768 term.c.attr.mode &= ~ATTR_REVERSE;
771 if (i + 2 < l && attr[i + 1] == 5) {
773 if (BETWEEN(attr[i], 0, 255))
774 term.c.attr.fg = attr[i];
776 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
779 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
782 term.c.attr.fg = DefaultFG;
785 if (i + 2 < l && attr[i + 1] == 5) {
787 if (BETWEEN(attr[i], 0, 255))
788 term.c.attr.bg = attr[i];
790 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
793 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
796 term.c.attr.bg = DefaultBG;
799 if(BETWEEN(attr[i], 30, 37))
800 term.c.attr.fg = attr[i] - 30;
801 else if(BETWEEN(attr[i], 40, 47))
802 term.c.attr.bg = attr[i] - 40;
803 else if(BETWEEN(attr[i], 90, 97))
804 term.c.attr.fg = attr[i] - 90 + 8;
805 else if(BETWEEN(attr[i], 100, 107))
806 term.c.attr.fg = attr[i] - 100 + 8;
808 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
816 tsetscroll(int t, int b) {
819 LIMIT(t, 0, term.row-1);
820 LIMIT(b, 0, term.row-1);
832 switch(escseq.mode) {
835 printf("erresc: unknown csi ");
839 case '@': /* ICH -- Insert <n> blank char */
840 DEFAULT(escseq.arg[0], 1);
841 tinsertblank(escseq.arg[0]);
843 case 'A': /* CUU -- Cursor <n> Up */
845 DEFAULT(escseq.arg[0], 1);
846 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
848 case 'B': /* CUD -- Cursor <n> Down */
849 DEFAULT(escseq.arg[0], 1);
850 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
852 case 'C': /* CUF -- Cursor <n> Forward */
854 DEFAULT(escseq.arg[0], 1);
855 tmoveto(term.c.x+escseq.arg[0], term.c.y);
857 case 'D': /* CUB -- Cursor <n> Backward */
858 DEFAULT(escseq.arg[0], 1);
859 tmoveto(term.c.x-escseq.arg[0], term.c.y);
861 case 'E': /* CNL -- Cursor <n> Down and first col */
862 DEFAULT(escseq.arg[0], 1);
863 tmoveto(0, term.c.y+escseq.arg[0]);
865 case 'F': /* CPL -- Cursor <n> Up and first col */
866 DEFAULT(escseq.arg[0], 1);
867 tmoveto(0, term.c.y-escseq.arg[0]);
869 case 'G': /* CHA -- Move to <col> */
870 case '`': /* XXX: HPA -- same? */
871 DEFAULT(escseq.arg[0], 1);
872 tmoveto(escseq.arg[0]-1, term.c.y);
874 case 'H': /* CUP -- Move to <row> <col> */
875 case 'f': /* XXX: HVP -- same? */
876 DEFAULT(escseq.arg[0], 1);
877 DEFAULT(escseq.arg[1], 1);
878 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
880 /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
881 case 'J': /* ED -- Clear screen */
882 switch(escseq.arg[0]) {
884 tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
887 tclearregion(0, 0, term.c.x, term.c.y);
890 tclearregion(0, 0, term.col-1, term.row-1);
896 case 'K': /* EL -- Clear line */
897 switch(escseq.arg[0]) {
899 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
902 tclearregion(0, term.c.y, term.c.x, term.c.y);
905 tclearregion(0, term.c.y, term.col-1, term.c.y);
909 case 'S': /* SU -- Scroll <n> line up */
910 DEFAULT(escseq.arg[0], 1);
911 tscrollup(term.top, escseq.arg[0]);
913 case 'T': /* SD -- Scroll <n> line down */
914 DEFAULT(escseq.arg[0], 1);
915 tscrolldown(term.top, escseq.arg[0]);
917 case 'L': /* IL -- Insert <n> blank lines */
918 DEFAULT(escseq.arg[0], 1);
919 tinsertblankline(escseq.arg[0]);
921 case 'l': /* RM -- Reset Mode */
923 switch(escseq.arg[0]) {
925 term.mode &= ~MODE_APPKEYPAD;
927 case 5: /* TODO: DECSCNM -- Remove reverse video */
930 term.mode &= ~MODE_WRAP;
932 case 12: /* att610 -- Stop blinking cursor (IGNORED) */
935 term.c.state |= CURSOR_HIDE;
937 case 1049: /* = 1047 and 1048 */
939 if(IS_SET(MODE_ALTSCREEN)) {
940 tclearregion(0, 0, term.col-1, term.row-1);
943 if(escseq.arg[0] == 1047)
946 tcursor(CURSOR_LOAD);
952 switch(escseq.arg[0]) {
954 term.mode &= ~MODE_INSERT;
961 case 'M': /* DL -- Delete <n> lines */
962 DEFAULT(escseq.arg[0], 1);
963 tdeleteline(escseq.arg[0]);
965 case 'X': /* ECH -- Erase <n> char */
966 DEFAULT(escseq.arg[0], 1);
967 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
969 case 'P': /* DCH -- Delete <n> char */
970 DEFAULT(escseq.arg[0], 1);
971 tdeletechar(escseq.arg[0]);
973 /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
974 case 'd': /* VPA -- Move to <row> */
975 DEFAULT(escseq.arg[0], 1);
976 tmoveto(term.c.x, escseq.arg[0]-1);
978 case 'h': /* SM -- Set terminal mode */
980 switch(escseq.arg[0]) {
982 term.mode |= MODE_APPKEYPAD;
984 case 5: /* DECSCNM -- Reverve video */
985 /* TODO: set REVERSE on the whole screen (f) */
988 term.mode |= MODE_WRAP;
990 case 12: /* att610 -- Start blinking cursor (IGNORED) */
991 /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
992 if(escseq.narg > 1 && escseq.arg[1] != 25)
995 term.c.state &= ~CURSOR_HIDE;
997 case 1049: /* = 1047 and 1048 */
999 if(IS_SET(MODE_ALTSCREEN))
1000 tclearregion(0, 0, term.col-1, term.row-1);
1003 if(escseq.arg[0] == 1047)
1006 tcursor(CURSOR_SAVE);
1008 default: goto unknown;
1011 switch(escseq.arg[0]) {
1013 term.mode |= MODE_INSERT;
1015 default: goto unknown;
1019 case 'm': /* SGR -- Terminal attribute (color) */
1020 tsetattr(escseq.arg, escseq.narg);
1022 case 'r': /* DECSTBM -- Set Scrolling Region */
1026 DEFAULT(escseq.arg[0], 1);
1027 DEFAULT(escseq.arg[1], term.row);
1028 tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
1032 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1033 tcursor(CURSOR_SAVE);
1035 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1036 tcursor(CURSOR_LOAD);
1044 printf("ESC [ %s", escseq.priv ? "? " : "");
1046 for(i = 0; i < escseq.narg; i++)
1047 printf("%d ", escseq.arg[i]);
1049 putchar(escseq.mode);
1055 memset(&escseq, 0, sizeof(escseq));
1060 int space = TAB - term.c.x % TAB;
1061 tmoveto(term.c.x + space, term.c.y);
1066 if(term.esc & ESC_START) {
1067 if(term.esc & ESC_CSI) {
1068 escseq.buf[escseq.len++] = c;
1069 if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
1071 csiparse(), csihandle();
1073 /* TODO: handle other OSC */
1074 } else if(term.esc & ESC_OSC) {
1077 term.esc = ESC_START | ESC_TITLE;
1079 } else if(term.esc & ESC_TITLE) {
1080 if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
1082 term.title[term.titlelen] = '\0';
1083 XStoreName(xw.dis, xw.win, term.title);
1085 term.title[term.titlelen++] = c;
1087 } else if(term.esc & ESC_ALTCHARSET) {
1089 case '0': /* Line drawing crap */
1090 term.c.attr.mode |= ATTR_GFX;
1092 case 'B': /* Back to regular text */
1093 term.c.attr.mode &= ~ATTR_GFX;
1096 printf("esc unhandled charset: ESC ( %c\n", c);
1102 term.esc |= ESC_CSI;
1105 term.esc |= ESC_OSC;
1108 term.esc |= ESC_ALTCHARSET;
1110 case 'D': /* IND -- Linefeed */
1111 if(term.c.y == term.bot)
1112 tscrollup(term.top, 1);
1114 tmoveto(term.c.x, term.c.y+1);
1117 case 'E': /* NEL -- Next line */
1121 case 'M': /* RI -- Reverse index */
1122 if(term.c.y == term.top)
1123 tscrolldown(term.top, 1);
1125 tmoveto(term.c.x, term.c.y-1);
1128 case 'c': /* RIS -- Reset to inital state */
1132 case '=': /* DECPAM -- Application keypad */
1133 term.mode |= MODE_APPKEYPAD;
1136 case '>': /* DECPNM -- Normal keypad */
1137 term.mode &= ~MODE_APPKEYPAD;
1140 case '7': /* DECSC -- Save Cursor */
1141 tcursor(CURSOR_SAVE);
1144 case '8': /* DECRC -- Restore Cursor */
1145 tcursor(CURSOR_LOAD);
1149 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
1159 tmoveto(term.c.x-1, term.c.y);
1162 tmoveto(0, term.c.y);
1173 term.esc = ESC_START;
1176 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1179 if(term.c.x+1 < term.col)
1180 tmoveto(term.c.x+1, term.c.y);
1182 term.c.state |= CURSOR_WRAPNEXT;
1189 tputs(char *s, int len) {
1190 for(; len > 0; len--)
1195 tresize(int col, int row) {
1197 int minrow = MIN(row, term.row);
1198 int mincol = MIN(col, term.col);
1199 int slide = term.c.y - row + 1;
1201 if(col < 1 || row < 1)
1204 /* free unneeded rows */
1207 /* slide screen to keep cursor where we expect it -
1208 * tscrollup would work here, but we can optimize to
1209 * memmove because we're freeing the earlier lines */
1210 for(/* i = 0 */; i < slide; i++) {
1214 memmove(term.line, term.line + slide, row * sizeof(Line));
1215 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1217 for(i += row; i < term.row; i++) {
1222 /* resize to new height */
1223 term.line = realloc(term.line, row * sizeof(Line));
1224 term.alt = realloc(term.alt, row * sizeof(Line));
1226 /* resize each row to new width, zero-pad if needed */
1227 for(i = 0; i < minrow; i++) {
1228 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1229 term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
1230 for(x = mincol; x < col; x++) {
1231 term.line[i][x].state = 0;
1232 term.alt[i][x].state = 0;
1236 /* allocate any new rows */
1237 for(/* i == minrow */; i < row; i++) {
1238 term.line[i] = calloc(col, sizeof(Glyph));
1239 term.alt [i] = calloc(col, sizeof(Glyph));
1242 /* update terminal size */
1243 term.col = col, term.row = row;
1244 /* make use of the LIMIT in tmoveto */
1245 tmoveto(term.c.x, term.c.y);
1246 /* reset scrolling region */
1247 tsetscroll(0, row-1);
1254 unsigned long white = WhitePixel(xw.dis, xw.scr);
1256 for(i = 0; i < 16; i++) {
1257 if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
1259 fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1261 dc.col[i] = color.pixel;
1264 /* same colors as xterm */
1265 for(r = 0; r < 6; r++)
1266 for(g = 0; g < 6; g++)
1267 for(b = 0; b < 6; b++) {
1268 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1269 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1270 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1271 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1273 fprintf(stderr, "Could not allocate color %d\n", i);
1275 dc.col[i] = color.pixel;
1279 for(r = 0; r < 24; r++, i++) {
1280 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1281 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1283 fprintf(stderr, "Could not allocate color %d\n", i);
1285 dc.col[i] = color.pixel;
1290 xclear(int x1, int y1, int x2, int y2) {
1291 XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1292 XFillRectangle(xw.dis, xw.buf, dc.gc,
1293 x1 * xw.cw, y1 * xw.ch,
1294 (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1300 XClassHint class = {TNAME, TNAME};
1301 XWMHints wm = {.flags = InputHint, .input = 1};
1303 .flags = PSize | PResizeInc | PBaseSize,
1306 .height_inc = xw.ch,
1308 .base_height = 2*BORDER,
1309 .base_width = 2*BORDER,
1311 XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1316 XSetWindowAttributes attrs;
1318 if(!(xw.dis = XOpenDisplay(NULL)))
1319 die("Can't open display\n");
1320 xw.scr = XDefaultScreen(xw.dis);
1323 if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
1324 die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
1326 /* XXX: Assuming same size for bold font */
1327 xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
1328 xw.ch = dc.font->ascent + dc.font->descent;
1331 xw.cmap = XDefaultColormap(xw.dis, xw.scr);
1334 /* window - default size */
1335 xw.bufh = 24 * xw.ch;
1336 xw.bufw = 80 * xw.cw;
1337 xw.h = xw.bufh + 2*BORDER;
1338 xw.w = xw.bufw + 2*BORDER;
1340 attrs.background_pixel = dc.col[DefaultBG];
1341 attrs.border_pixel = dc.col[DefaultBG];
1342 attrs.bit_gravity = NorthWestGravity;
1343 attrs.event_mask = FocusChangeMask | KeyPressMask
1344 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1345 | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
1346 attrs.colormap = xw.cmap;
1348 xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
1349 xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
1350 XDefaultVisual(xw.dis, xw.scr),
1351 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
1354 xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1358 xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
1359 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1360 | XIMStatusNothing, XNClientWindow, xw.win,
1361 XNFocusWindow, xw.win, NULL);
1363 dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
1365 XMapWindow(xw.dis, xw.win);
1367 XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
1372 xdraws(char *s, Glyph base, int x, int y, int len) {
1373 unsigned long xfg, xbg;
1374 int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
1377 if(base.mode & ATTR_REVERSE)
1378 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
1380 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
1382 XSetBackground(xw.dis, dc.gc, xbg);
1383 XSetForeground(xw.dis, dc.gc, xfg);
1385 if(base.mode & ATTR_GFX)
1386 for(i = 0; i < len; i++) {
1387 char c = gfx[(unsigned int)s[i] % 256];
1390 else if(s[i] > 0x5f)
1394 XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1395 XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
1397 if(base.mode & ATTR_UNDERLINE)
1398 XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1403 static int oldx = 0;
1404 static int oldy = 0;
1405 Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
1407 LIMIT(oldx, 0, term.col-1);
1408 LIMIT(oldy, 0, term.row-1);
1410 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1411 g.c = term.line[term.c.y][term.c.x].c;
1413 /* remove the old cursor */
1414 if(term.line[oldy][oldx].state & GLYPH_SET)
1415 xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
1417 xclear(oldx, oldy, oldx, oldy);
1419 /* draw the new one */
1420 if(!(term.c.state & CURSOR_HIDE) && xw.focus) {
1421 xdraws(&g.c, g, term.c.x, term.c.y, 1);
1422 oldx = term.c.x, oldy = term.c.y;
1427 /* basic drawing routines */
1429 xdrawc(int x, int y, Glyph g) {
1430 XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
1431 XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
1432 XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
1433 XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1434 XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
1441 xclear(0, 0, term.col-1, term.row-1);
1442 for(y = 0; y < term.row; y++)
1443 for(x = 0; x < term.col; x++)
1444 if(term.line[y][x].state & GLYPH_SET)
1445 xdrawc(x, y, term.line[y][x]);
1448 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1453 /* optimized drawing routine */
1455 draw(int redraw_all) {
1458 char buf[DRAW_BUF_SIZ];
1463 xclear(0, 0, term.col-1, term.row-1);
1464 for(y = 0; y < term.row; y++) {
1465 base = term.line[y][0];
1467 for(x = 0; x < term.col; x++) {
1468 new = term.line[y][x];
1469 if(sel.bx!=-1 && new.c && selected(x, y))
1470 new.mode ^= ATTR_REVERSE;
1471 if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
1472 i >= DRAW_BUF_SIZ)) {
1473 xdraws(buf, base, ox, y, i);
1476 if(new.state & GLYPH_SET) {
1485 xdraws(buf, base, ox, y, i);
1488 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1495 expose(XEvent *ev) {
1496 draw(SCREEN_REDRAW);
1500 visibility(XEvent *ev) {
1501 XVisibilityEvent *e = &ev->xvisibility;
1502 /* XXX if this goes from 0 to 1, need a full redraw for next Expose,
1503 * not just a buf copy */
1504 xw.vis = e->state != VisibilityFullyObscured;
1513 xseturgency(int add) {
1514 XWMHints *h = XGetWMHints(xw.dis, xw.win);
1515 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
1516 XSetWMHints(xw.dis, xw.win, h);
1522 if((xw.focus = ev->type == FocusIn))
1524 draw(SCREEN_UPDATE);
1530 for(i = 0; i < LEN(key); i++)
1532 return (char*)key[i].s;
1537 kpress(XEvent *ev) {
1538 XKeyEvent *e = &ev->xkey;
1547 meta = e->state & Mod1Mask;
1548 shift = e->state & ShiftMask;
1549 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
1551 if((customkey = kmap(ksym)))
1552 ttywrite(customkey, strlen(customkey));
1554 buf[sizeof(buf)-1] = '\0';
1555 if(meta && len == 1)
1556 ttywrite("\033", 1);
1564 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
1572 fprintf(stderr, "errkey: %d\n", (int)ksym);
1581 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1584 xw.w = e->xconfigure.width;
1585 xw.h = e->xconfigure.height;
1586 xw.bufw = xw.w - 2*BORDER;
1587 xw.bufh = xw.h - 2*BORDER;
1588 col = xw.bufw / xw.cw;
1589 row = xw.bufh / xw.ch;
1591 ttyresize(col, row);
1592 xw.bufh = MAX(1, xw.bufh);
1593 xw.bufw = MAX(1, xw.bufw);
1594 XFreePixmap(xw.dis, xw.buf);
1595 xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1602 int xfd = XConnectionNumber(xw.dis);
1606 FD_SET(cmdfd, &rfd);
1608 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
1611 die("select failed: %s\n", SERRNO);
1613 if(FD_ISSET(cmdfd, &rfd)) {
1615 draw(SCREEN_UPDATE);
1617 while(XPending(xw.dis)) {
1618 XNextEvent(xw.dis, &ev);
1619 if (XFilterEvent(&ev, xw.win))
1621 if(handler[ev.type])
1622 (handler[ev.type])(&ev);
1628 main(int argc, char *argv[]) {
1631 for(i = 1; i < argc; i++) {
1632 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
1634 if(++i < argc) opt_title = argv[i];
1637 if(++i < argc) opt_cmd = argv[i];
1644 setlocale(LC_CTYPE, "");