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 memset(&term.line[y][x1], 0, sizeof(Glyph)*(x2-x1+1));
698 int src = term.c.x + n;
700 int size = term.col - src;
702 if(src >= term.col) {
703 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
706 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
707 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
711 tinsertblank(int n) {
714 int size = term.col - dst;
716 if(dst >= term.col) {
717 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
720 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
721 tclearregion(src, term.c.y, dst - 1, term.c.y);
725 tinsertblankline(int n) {
726 if(term.c.y < term.top || term.c.y > term.bot)
729 tscrolldown(term.c.y, n);
734 if(term.c.y < term.top || term.c.y > term.bot)
737 tscrollup(term.c.y, n);
741 tsetattr(int *attr, int l) {
744 for(i = 0; i < l; i++) {
747 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
748 term.c.attr.fg = DefaultFG;
749 term.c.attr.bg = DefaultBG;
752 term.c.attr.mode |= ATTR_BOLD;
755 term.c.attr.mode |= ATTR_UNDERLINE;
758 term.c.attr.mode |= ATTR_REVERSE;
761 term.c.attr.mode &= ~ATTR_BOLD;
764 term.c.attr.mode &= ~ATTR_UNDERLINE;
767 term.c.attr.mode &= ~ATTR_REVERSE;
770 if (i + 2 < l && attr[i + 1] == 5) {
772 if (BETWEEN(attr[i], 0, 255))
773 term.c.attr.fg = attr[i];
775 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
778 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
781 term.c.attr.fg = DefaultFG;
784 if (i + 2 < l && attr[i + 1] == 5) {
786 if (BETWEEN(attr[i], 0, 255))
787 term.c.attr.bg = attr[i];
789 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
792 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
795 term.c.attr.bg = DefaultBG;
798 if(BETWEEN(attr[i], 30, 37))
799 term.c.attr.fg = attr[i] - 30;
800 else if(BETWEEN(attr[i], 40, 47))
801 term.c.attr.bg = attr[i] - 40;
802 else if(BETWEEN(attr[i], 90, 97))
803 term.c.attr.fg = attr[i] - 90 + 8;
804 else if(BETWEEN(attr[i], 100, 107))
805 term.c.attr.fg = attr[i] - 100 + 8;
807 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
815 tsetscroll(int t, int b) {
818 LIMIT(t, 0, term.row-1);
819 LIMIT(b, 0, term.row-1);
831 switch(escseq.mode) {
834 printf("erresc: unknown csi ");
838 case '@': /* ICH -- Insert <n> blank char */
839 DEFAULT(escseq.arg[0], 1);
840 tinsertblank(escseq.arg[0]);
842 case 'A': /* CUU -- Cursor <n> Up */
844 DEFAULT(escseq.arg[0], 1);
845 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
847 case 'B': /* CUD -- Cursor <n> Down */
848 DEFAULT(escseq.arg[0], 1);
849 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
851 case 'C': /* CUF -- Cursor <n> Forward */
853 DEFAULT(escseq.arg[0], 1);
854 tmoveto(term.c.x+escseq.arg[0], term.c.y);
856 case 'D': /* CUB -- Cursor <n> Backward */
857 DEFAULT(escseq.arg[0], 1);
858 tmoveto(term.c.x-escseq.arg[0], term.c.y);
860 case 'E': /* CNL -- Cursor <n> Down and first col */
861 DEFAULT(escseq.arg[0], 1);
862 tmoveto(0, term.c.y+escseq.arg[0]);
864 case 'F': /* CPL -- Cursor <n> Up and first col */
865 DEFAULT(escseq.arg[0], 1);
866 tmoveto(0, term.c.y-escseq.arg[0]);
868 case 'G': /* CHA -- Move to <col> */
869 case '`': /* XXX: HPA -- same? */
870 DEFAULT(escseq.arg[0], 1);
871 tmoveto(escseq.arg[0]-1, term.c.y);
873 case 'H': /* CUP -- Move to <row> <col> */
874 case 'f': /* XXX: HVP -- same? */
875 DEFAULT(escseq.arg[0], 1);
876 DEFAULT(escseq.arg[1], 1);
877 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
879 /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
880 case 'J': /* ED -- Clear screen */
881 switch(escseq.arg[0]) {
883 tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
886 tclearregion(0, 0, term.c.x, term.c.y);
889 tclearregion(0, 0, term.col-1, term.row-1);
895 case 'K': /* EL -- Clear line */
896 switch(escseq.arg[0]) {
898 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
901 tclearregion(0, term.c.y, term.c.x, term.c.y);
904 tclearregion(0, term.c.y, term.col-1, term.c.y);
908 case 'S': /* SU -- Scroll <n> line up */
909 DEFAULT(escseq.arg[0], 1);
910 tscrollup(term.top, escseq.arg[0]);
912 case 'T': /* SD -- Scroll <n> line down */
913 DEFAULT(escseq.arg[0], 1);
914 tscrolldown(term.top, escseq.arg[0]);
916 case 'L': /* IL -- Insert <n> blank lines */
917 DEFAULT(escseq.arg[0], 1);
918 tinsertblankline(escseq.arg[0]);
920 case 'l': /* RM -- Reset Mode */
922 switch(escseq.arg[0]) {
924 term.mode &= ~MODE_APPKEYPAD;
926 case 5: /* TODO: DECSCNM -- Remove reverse video */
929 term.mode &= ~MODE_WRAP;
931 case 12: /* att610 -- Stop blinking cursor (IGNORED) */
934 term.c.state |= CURSOR_HIDE;
936 case 1049: /* = 1047 and 1048 */
938 if(IS_SET(MODE_ALTSCREEN)) {
939 tclearregion(0, 0, term.col-1, term.row-1);
942 if(escseq.arg[0] == 1047)
945 tcursor(CURSOR_LOAD);
951 switch(escseq.arg[0]) {
953 term.mode &= ~MODE_INSERT;
960 case 'M': /* DL -- Delete <n> lines */
961 DEFAULT(escseq.arg[0], 1);
962 tdeleteline(escseq.arg[0]);
964 case 'X': /* ECH -- Erase <n> char */
965 DEFAULT(escseq.arg[0], 1);
966 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
968 case 'P': /* DCH -- Delete <n> char */
969 DEFAULT(escseq.arg[0], 1);
970 tdeletechar(escseq.arg[0]);
972 /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
973 case 'd': /* VPA -- Move to <row> */
974 DEFAULT(escseq.arg[0], 1);
975 tmoveto(term.c.x, escseq.arg[0]-1);
977 case 'h': /* SM -- Set terminal mode */
979 switch(escseq.arg[0]) {
981 term.mode |= MODE_APPKEYPAD;
983 case 5: /* DECSCNM -- Reverve video */
984 /* TODO: set REVERSE on the whole screen (f) */
987 term.mode |= MODE_WRAP;
989 case 12: /* att610 -- Start blinking cursor (IGNORED) */
990 /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
991 if(escseq.narg > 1 && escseq.arg[1] != 25)
994 term.c.state &= ~CURSOR_HIDE;
996 case 1049: /* = 1047 and 1048 */
998 if(IS_SET(MODE_ALTSCREEN))
999 tclearregion(0, 0, term.col-1, term.row-1);
1002 if(escseq.arg[0] == 1047)
1005 tcursor(CURSOR_SAVE);
1007 default: goto unknown;
1010 switch(escseq.arg[0]) {
1012 term.mode |= MODE_INSERT;
1014 default: goto unknown;
1018 case 'm': /* SGR -- Terminal attribute (color) */
1019 tsetattr(escseq.arg, escseq.narg);
1021 case 'r': /* DECSTBM -- Set Scrolling Region */
1025 DEFAULT(escseq.arg[0], 1);
1026 DEFAULT(escseq.arg[1], term.row);
1027 tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
1031 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1032 tcursor(CURSOR_SAVE);
1034 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1035 tcursor(CURSOR_LOAD);
1043 printf("ESC [ %s", escseq.priv ? "? " : "");
1045 for(i = 0; i < escseq.narg; i++)
1046 printf("%d ", escseq.arg[i]);
1048 putchar(escseq.mode);
1054 memset(&escseq, 0, sizeof(escseq));
1059 int space = TAB - term.c.x % TAB;
1060 tmoveto(term.c.x + space, term.c.y);
1065 if(term.esc & ESC_START) {
1066 if(term.esc & ESC_CSI) {
1067 escseq.buf[escseq.len++] = c;
1068 if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
1070 csiparse(), csihandle();
1072 /* TODO: handle other OSC */
1073 } else if(term.esc & ESC_OSC) {
1076 term.esc = ESC_START | ESC_TITLE;
1078 } else if(term.esc & ESC_TITLE) {
1079 if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
1081 term.title[term.titlelen] = '\0';
1082 XStoreName(xw.dis, xw.win, term.title);
1084 term.title[term.titlelen++] = c;
1086 } else if(term.esc & ESC_ALTCHARSET) {
1088 case '0': /* Line drawing crap */
1089 term.c.attr.mode |= ATTR_GFX;
1091 case 'B': /* Back to regular text */
1092 term.c.attr.mode &= ~ATTR_GFX;
1095 printf("esc unhandled charset: ESC ( %c\n", c);
1101 term.esc |= ESC_CSI;
1104 term.esc |= ESC_OSC;
1107 term.esc |= ESC_ALTCHARSET;
1109 case 'D': /* IND -- Linefeed */
1110 if(term.c.y == term.bot)
1111 tscrollup(term.top, 1);
1113 tmoveto(term.c.x, term.c.y+1);
1116 case 'E': /* NEL -- Next line */
1120 case 'M': /* RI -- Reverse index */
1121 if(term.c.y == term.top)
1122 tscrolldown(term.top, 1);
1124 tmoveto(term.c.x, term.c.y-1);
1127 case 'c': /* RIS -- Reset to inital state */
1131 case '=': /* DECPAM -- Application keypad */
1132 term.mode |= MODE_APPKEYPAD;
1135 case '>': /* DECPNM -- Normal keypad */
1136 term.mode &= ~MODE_APPKEYPAD;
1139 case '7': /* DECSC -- Save Cursor */
1140 tcursor(CURSOR_SAVE);
1143 case '8': /* DECRC -- Restore Cursor */
1144 tcursor(CURSOR_LOAD);
1148 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
1158 tmoveto(term.c.x-1, term.c.y);
1161 tmoveto(0, term.c.y);
1172 term.esc = ESC_START;
1175 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1178 if(term.c.x+1 < term.col)
1179 tmoveto(term.c.x+1, term.c.y);
1181 term.c.state |= CURSOR_WRAPNEXT;
1188 tputs(char *s, int len) {
1189 for(; len > 0; len--)
1194 tresize(int col, int row) {
1196 int minrow = MIN(row, term.row);
1197 int mincol = MIN(col, term.col);
1198 int slide = term.c.y - row + 1;
1200 if(col < 1 || row < 1)
1203 /* free unneeded rows */
1206 /* slide screen to keep cursor where we expect it -
1207 * tscrollup would work here, but we can optimize to
1208 * memmove because we're freeing the earlier lines */
1209 for(/* i = 0 */; i < slide; i++) {
1213 memmove(term.line, term.line + slide, row * sizeof(Line));
1214 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1216 for(i += row; i < term.row; i++) {
1221 /* resize to new height */
1222 term.line = realloc(term.line, row * sizeof(Line));
1223 term.alt = realloc(term.alt, row * sizeof(Line));
1225 /* resize each row to new width, zero-pad if needed */
1226 for(i = 0; i < minrow; i++) {
1227 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1228 term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
1229 memset(term.line[i] + mincol, 0, (col - mincol) * sizeof(Glyph));
1230 memset(term.alt[i] + mincol, 0, (col - mincol) * sizeof(Glyph));
1233 /* allocate any new rows */
1234 for(/* i == minrow */; i < row; i++) {
1235 term.line[i] = calloc(col, sizeof(Glyph));
1236 term.alt [i] = calloc(col, sizeof(Glyph));
1239 /* update terminal size */
1240 term.col = col, term.row = row;
1241 /* make use of the LIMIT in tmoveto */
1242 tmoveto(term.c.x, term.c.y);
1243 /* reset scrolling region */
1244 tsetscroll(0, row-1);
1251 unsigned long white = WhitePixel(xw.dis, xw.scr);
1253 for(i = 0; i < 16; i++) {
1254 if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
1256 fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1258 dc.col[i] = color.pixel;
1261 /* same colors as xterm */
1262 for(r = 0; r < 6; r++)
1263 for(g = 0; g < 6; g++)
1264 for(b = 0; b < 6; b++) {
1265 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1266 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1267 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1268 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1270 fprintf(stderr, "Could not allocate color %d\n", i);
1272 dc.col[i] = color.pixel;
1276 for(r = 0; r < 24; r++, i++) {
1277 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1278 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1280 fprintf(stderr, "Could not allocate color %d\n", i);
1282 dc.col[i] = color.pixel;
1287 xclear(int x1, int y1, int x2, int y2) {
1288 XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1289 XFillRectangle(xw.dis, xw.buf, dc.gc,
1290 x1 * xw.cw, y1 * xw.ch,
1291 (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1297 XClassHint class = {TNAME, TNAME};
1298 XWMHints wm = {.flags = InputHint, .input = 1};
1300 .flags = PSize | PResizeInc | PBaseSize,
1303 .height_inc = xw.ch,
1305 .base_height = 2*BORDER,
1306 .base_width = 2*BORDER,
1308 XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1313 XSetWindowAttributes attrs;
1315 if(!(xw.dis = XOpenDisplay(NULL)))
1316 die("Can't open display\n");
1317 xw.scr = XDefaultScreen(xw.dis);
1320 if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
1321 die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
1323 /* XXX: Assuming same size for bold font */
1324 xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
1325 xw.ch = dc.font->ascent + dc.font->descent;
1328 xw.cmap = XDefaultColormap(xw.dis, xw.scr);
1331 /* window - default size */
1332 xw.bufh = 24 * xw.ch;
1333 xw.bufw = 80 * xw.cw;
1334 xw.h = xw.bufh + 2*BORDER;
1335 xw.w = xw.bufw + 2*BORDER;
1337 attrs.background_pixel = dc.col[DefaultBG];
1338 attrs.border_pixel = dc.col[DefaultBG];
1339 attrs.bit_gravity = NorthWestGravity;
1340 attrs.event_mask = FocusChangeMask | KeyPressMask
1341 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1342 | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
1343 attrs.colormap = xw.cmap;
1345 xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
1346 xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
1347 XDefaultVisual(xw.dis, xw.scr),
1348 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
1351 xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1355 xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
1356 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1357 | XIMStatusNothing, XNClientWindow, xw.win,
1358 XNFocusWindow, xw.win, NULL);
1360 dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
1362 XMapWindow(xw.dis, xw.win);
1364 XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
1369 xdraws(char *s, Glyph base, int x, int y, int len) {
1370 unsigned long xfg, xbg;
1371 int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
1374 if(base.mode & ATTR_REVERSE)
1375 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
1377 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
1379 XSetBackground(xw.dis, dc.gc, xbg);
1380 XSetForeground(xw.dis, dc.gc, xfg);
1382 if(base.mode & ATTR_GFX)
1383 for(i = 0; i < len; i++) {
1384 char c = gfx[(unsigned int)s[i] % 256];
1387 else if(s[i] > 0x5f)
1391 XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1392 XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
1394 if(base.mode & ATTR_UNDERLINE)
1395 XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1400 static int oldx = 0;
1401 static int oldy = 0;
1402 Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
1404 LIMIT(oldx, 0, term.col-1);
1405 LIMIT(oldy, 0, term.row-1);
1407 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1408 g.c = term.line[term.c.y][term.c.x].c;
1410 /* remove the old cursor */
1411 if(term.line[oldy][oldx].state & GLYPH_SET)
1412 xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
1414 xclear(oldx, oldy, oldx, oldy);
1416 /* draw the new one */
1417 if(!(term.c.state & CURSOR_HIDE) && xw.focus) {
1418 xdraws(&g.c, g, term.c.x, term.c.y, 1);
1419 oldx = term.c.x, oldy = term.c.y;
1424 /* basic drawing routines */
1426 xdrawc(int x, int y, Glyph g) {
1427 XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
1428 XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
1429 XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
1430 XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1431 XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
1438 xclear(0, 0, term.col-1, term.row-1);
1439 for(y = 0; y < term.row; y++)
1440 for(x = 0; x < term.col; x++)
1441 if(term.line[y][x].state & GLYPH_SET)
1442 xdrawc(x, y, term.line[y][x]);
1445 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1450 /* optimized drawing routine */
1452 draw(int redraw_all) {
1455 char buf[DRAW_BUF_SIZ];
1460 xclear(0, 0, term.col-1, term.row-1);
1461 for(y = 0; y < term.row; y++) {
1462 base = term.line[y][0];
1464 for(x = 0; x < term.col; x++) {
1465 new = term.line[y][x];
1466 if(sel.bx!=-1 && new.c && selected(x, y))
1467 new.mode ^= ATTR_REVERSE;
1468 if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
1469 i >= DRAW_BUF_SIZ)) {
1470 xdraws(buf, base, ox, y, i);
1473 if(new.state & GLYPH_SET) {
1482 xdraws(buf, base, ox, y, i);
1485 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1492 expose(XEvent *ev) {
1493 draw(SCREEN_REDRAW);
1497 visibility(XEvent *ev) {
1498 XVisibilityEvent *e = &ev->xvisibility;
1499 /* XXX if this goes from 0 to 1, need a full redraw for next Expose,
1500 * not just a buf copy */
1501 xw.vis = e->state != VisibilityFullyObscured;
1510 xseturgency(int add) {
1511 XWMHints *h = XGetWMHints(xw.dis, xw.win);
1512 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
1513 XSetWMHints(xw.dis, xw.win, h);
1519 if((xw.focus = ev->type == FocusIn))
1521 draw(SCREEN_UPDATE);
1527 for(i = 0; i < LEN(key); i++)
1529 return (char*)key[i].s;
1534 kpress(XEvent *ev) {
1535 XKeyEvent *e = &ev->xkey;
1544 meta = e->state & Mod1Mask;
1545 shift = e->state & ShiftMask;
1546 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
1548 if((customkey = kmap(ksym)))
1549 ttywrite(customkey, strlen(customkey));
1551 buf[sizeof(buf)-1] = '\0';
1552 if(meta && len == 1)
1553 ttywrite("\033", 1);
1561 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
1569 fprintf(stderr, "errkey: %d\n", (int)ksym);
1578 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1581 xw.w = e->xconfigure.width;
1582 xw.h = e->xconfigure.height;
1583 xw.bufw = xw.w - 2*BORDER;
1584 xw.bufh = xw.h - 2*BORDER;
1585 col = xw.bufw / xw.cw;
1586 row = xw.bufh / xw.ch;
1588 ttyresize(col, row);
1589 xw.bufh = MAX(1, xw.bufh);
1590 xw.bufw = MAX(1, xw.bufw);
1591 XFreePixmap(xw.dis, xw.buf);
1592 xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1599 int xfd = XConnectionNumber(xw.dis);
1603 FD_SET(cmdfd, &rfd);
1605 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
1608 die("select failed: %s\n", SERRNO);
1610 if(FD_ISSET(cmdfd, &rfd)) {
1612 draw(SCREEN_UPDATE);
1614 while(XPending(xw.dis)) {
1615 XNextEvent(xw.dis, &ev);
1616 if (XFilterEvent(&ev, xw.win))
1618 if(handler[ev.type])
1619 (handler[ev.type])(&ev);
1625 main(int argc, char *argv[]) {
1628 for(i = 1; i < argc; i++) {
1629 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
1631 if(++i < argc) opt_title = argv[i];
1634 if(++i < argc) opt_cmd = argv[i];
1641 setlocale(LC_CTYPE, "");