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,
60 enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
61 enum { SCREEN_UPDATE, SCREEN_REDRAW };
62 enum { WIN_VISIBLE=1, WIN_REDRAW=2, WIN_FOCUSED=4 };
65 char c; /* character code */
66 char mode; /* attribute flags */
67 int fg; /* foreground */
68 int bg; /* background */
69 char state; /* state flags */
75 Glyph attr; /* current char attributes */
81 /* CSI Escape sequence structs */
82 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
84 char buf[ESC_BUF_SIZ]; /* raw string */
85 int len; /* raw string length */
88 int narg; /* nb of args */
92 /* Internal representation of the screen */
96 Line* line; /* screen */
97 Line* alt; /* alternate screen */
98 TCursor c; /* cursor */
99 int top; /* top scroll limit */
100 int bot; /* bottom scroll limit */
101 int mode; /* terminal mode flags */
102 int esc; /* escape state flags */
103 char title[ESC_TITLE_SIZ];
107 /* Purely graphic info */
116 int w; /* window width */
117 int h; /* window height */
118 int bufw; /* pixmap width */
119 int bufh; /* pixmap height */
120 int ch; /* char height */
121 int cw; /* char width */
122 char state; /* focus, redraw, visible */
130 /* Drawing Context */
132 unsigned long col[256];
138 /* TODO: use better name for vars... */
143 struct {int x, y;} b, e;
149 static void die(const char *errstr, ...);
150 static void draw(int);
151 static void execsh(void);
152 static void sigchld(int);
153 static void run(void);
155 static void csidump(void);
156 static void csihandle(void);
157 static void csiparse(void);
158 static void csireset(void);
160 static void tclearregion(int, int, int, int);
161 static void tcursor(int);
162 static void tdeletechar(int);
163 static void tdeleteline(int);
164 static void tinsertblank(int);
165 static void tinsertblankline(int);
166 static void tmoveto(int, int);
167 static void tnew(int, int);
168 static void tnewline(int);
169 static void tputtab(void);
170 static void tputc(char);
171 static void tputs(char*, int);
172 static void treset(void);
173 static int tresize(int, int);
174 static void tscrollup(int, int);
175 static void tscrolldown(int, int);
176 static void tsetattr(int*, int);
177 static void tsetchar(char);
178 static void tsetscroll(int, int);
179 static void tswapscreen(void);
181 static void ttynew(void);
182 static void ttyread(void);
183 static void ttyresize(int, int);
184 static void ttywrite(const char *, size_t);
186 static void xdraws(char *, Glyph, int, int, int);
187 static void xhints(void);
188 static void xclear(int, int, int, int);
189 static void xdrawcursor(void);
190 static void xinit(void);
191 static void xloadcols(void);
192 static void xseturgency(int);
193 static void xresize(int, int);
195 static void expose(XEvent *);
196 static void visibility(XEvent *);
197 static void unmap(XEvent *);
198 static char* kmap(KeySym);
199 static void kpress(XEvent *);
200 static void resize(XEvent *);
201 static void focus(XEvent *);
202 static void brelease(XEvent *);
203 static void bpress(XEvent *);
204 static void bmotion(XEvent *);
205 static void selection_notify(XEvent *);
206 static void selection_request(XEvent *);
208 static void (*handler[LASTEvent])(XEvent *) = {
210 [ConfigureNotify] = resize,
211 [VisibilityNotify] = visibility,
212 [UnmapNotify] = unmap,
216 [MotionNotify] = bmotion,
217 [ButtonPress] = bpress,
218 [ButtonRelease] = brelease,
219 [SelectionNotify] = selection_notify,
220 [SelectionRequest] = selection_request,
227 static CSIEscape escseq;
230 static Selection sel;
231 static char *opt_cmd = NULL;
232 static char *opt_title = NULL;
241 static inline int selected(int x, int y) {
242 if(sel.ey == y && sel.by == y) {
243 int bx = MIN(sel.bx, sel.ex);
244 int ex = MAX(sel.bx, sel.ex);
245 return BETWEEN(x, bx, ex);
247 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
248 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
251 static void getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
253 *b = e->xbutton.button;
255 *x = e->xbutton.x/xw.cw;
256 *y = e->xbutton.y/xw.ch;
257 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
258 sel.b.y = MIN(sel.by, sel.ey);
259 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
260 sel.e.y = MAX(sel.by, sel.ey);
263 static void bpress(XEvent *e) {
265 sel.ex = sel.bx = e->xbutton.x/xw.cw;
266 sel.ey = sel.by = e->xbutton.y/xw.ch;
269 static char *getseltext() {
274 sz = (term.col+1) * (sel.e.y-sel.b.y+1);
275 ptr = str = malloc(sz);
276 for(y = 0; y < term.row; y++) {
277 for(x = 0; x < term.col; x++)
278 if(term.line[y][x].state & GLYPH_SET && (ls = selected(x, y)))
279 *ptr = term.line[y][x].c, ptr++;
287 static void selection_notify(XEvent *e) {
288 unsigned long nitems;
289 unsigned long ofs, rem;
296 if(XGetWindowProperty(xw.dis, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
297 False, AnyPropertyType, &type, &format,
298 &nitems, &rem, &data)) {
299 fprintf(stderr, "Clipboard allocation failed\n");
302 ttywrite((const char *) data, nitems * format / 8);
304 /* number of 32-bit chunks returned */
305 ofs += nitems * format / 32;
309 static void selpaste() {
310 XConvertSelection(xw.dis, XA_PRIMARY, XA_STRING, XA_PRIMARY, xw.win, CurrentTime);
313 static void selection_request(XEvent *e)
315 XSelectionRequestEvent *xsre;
319 xsre = (XSelectionRequestEvent *) e;
320 xev.type = SelectionNotify;
321 xev.requestor = xsre->requestor;
322 xev.selection = xsre->selection;
323 xev.target = xsre->target;
324 xev.time = xsre->time;
328 xa_targets = XInternAtom(xw.dis, "TARGETS", 0);
329 if(xsre->target == xa_targets) {
330 /* respond with the supported type */
331 Atom string = XA_STRING;
332 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
333 XA_ATOM, 32, PropModeReplace,
334 (unsigned char *) &string, 1);
335 xev.property = xsre->property;
336 } else if(xsre->target == XA_STRING) {
337 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
338 xsre->target, 8, PropModeReplace,
339 (unsigned char *) sel.clip, strlen(sel.clip));
340 xev.property = xsre->property;
343 /* all done, send a notification to the listener */
344 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
345 fprintf(stderr, "Error sending SelectionNotify event\n");
348 static void selcopy(char *str) {
349 /* register the selection for both the clipboard and the primary */
355 XSetSelectionOwner(xw.dis, XA_PRIMARY, xw.win, CurrentTime);
357 clipboard = XInternAtom(xw.dis, "CLIPBOARD", 0);
358 XSetSelectionOwner(xw.dis, clipboard, xw.win, CurrentTime);
363 /* TODO: doubleclick to select word */
364 static void brelease(XEvent *e) {
367 getbuttoninfo(e, &b, &sel.ex, &sel.ey);
368 if(sel.bx==sel.ex && sel.by==sel.ey) {
374 selcopy(getseltext());
379 static void bmotion(XEvent *e) {
381 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
392 for(row = 0; row < term.row; row++) {
393 for(col = 0; col < term.col; col++) {
394 if(col == term.c.x && row == term.c.y)
397 c = term.line[row][col];
398 putchar(c.state & GLYPH_SET ? c.c : '.');
407 die(const char *errstr, ...) {
410 va_start(ap, errstr);
411 vfprintf(stderr, errstr, ap);
418 char *args[] = {getenv("SHELL"), "-i", NULL};
420 args[0] = opt_cmd, args[1] = NULL;
422 DEFAULT(args[0], SHELL);
423 putenv("TERM="TNAME);
424 execvp(args[0], args);
430 if(waitpid(pid, &stat, 0) < 0)
431 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
433 exit(WEXITSTATUS(stat));
442 /* seems to work fine on linux, openbsd and freebsd */
443 struct winsize w = {term.row, term.col, 0, 0};
444 if(openpty(&m, &s, NULL, NULL, &w) < 0)
445 die("openpty failed: %s\n", SERRNO);
447 switch(pid = fork()) {
449 die("fork failed\n");
452 setsid(); /* create a new process group */
453 dup2(s, STDIN_FILENO);
454 dup2(s, STDOUT_FILENO);
455 dup2(s, STDERR_FILENO);
456 if(ioctl(s, TIOCSCTTY, NULL) < 0)
457 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
465 signal(SIGCHLD, sigchld);
472 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
474 fprintf(stderr, "\n");
482 if((ret = read(cmdfd, buf, LEN(buf))) < 0)
483 die("Couldn't read from shell: %s\n", SERRNO);
489 ttywrite(const char *s, size_t n) {
490 if(write(cmdfd, s, n) == -1)
491 die("write error on tty: %s\n", SERRNO);
495 ttyresize(int x, int y) {
500 w.ws_xpixel = w.ws_ypixel = 0;
501 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
502 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
509 if(mode == CURSOR_SAVE)
511 else if(mode == CURSOR_LOAD)
512 term.c = c, tmoveto(c.x, c.y);
521 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
523 term.top = 0, term.bot = term.row - 1;
524 term.mode = MODE_WRAP;
525 tclearregion(0, 0, term.col-1, term.row-1);
529 tnew(int col, int row) {
530 /* set screen size */
531 term.row = row, term.col = col;
532 term.line = malloc(term.row * sizeof(Line));
533 term.alt = malloc(term.row * sizeof(Line));
534 for(row = 0 ; row < term.row; row++) {
535 term.line[row] = malloc(term.col * sizeof(Glyph));
536 term.alt [row] = malloc(term.col * sizeof(Glyph));
544 Line* tmp = term.line;
545 term.line = term.alt;
547 term.mode ^= MODE_ALTSCREEN;
551 tscrolldown(int orig, int n) {
555 LIMIT(n, 0, term.bot-orig+1);
557 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
559 for(i = term.bot; i >= orig+n; i--) {
561 term.line[i] = term.line[i-n];
562 term.line[i-n] = temp;
567 tscrollup(int orig, int n) {
570 LIMIT(n, 0, term.bot-orig+1);
572 tclearregion(0, orig, term.col-1, orig+n-1);
574 for(i = orig; i <= term.bot-n; i++) {
576 term.line[i] = term.line[i+n];
577 term.line[i+n] = temp;
582 tnewline(int first_col) {
585 tscrollup(term.top, 1);
588 tmoveto(first_col ? 0 : term.c.x, y);
594 char *p = escseq.buf;
598 escseq.priv = 1, p++;
600 while(p < escseq.buf+escseq.len) {
602 escseq.arg[escseq.narg] *= 10;
603 escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
605 if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
616 tmoveto(int x, int y) {
617 LIMIT(x, 0, term.col-1);
618 LIMIT(y, 0, term.row-1);
619 term.c.state &= ~CURSOR_WRAPNEXT;
626 term.line[term.c.y][term.c.x] = term.c.attr;
627 term.line[term.c.y][term.c.x].c = c;
628 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
632 tclearregion(int x1, int y1, int x2, int y2) {
636 temp = x1, x1 = x2, x2 = temp;
638 temp = y1, y1 = y2, y2 = temp;
640 LIMIT(x1, 0, term.col-1);
641 LIMIT(x2, 0, term.col-1);
642 LIMIT(y1, 0, term.row-1);
643 LIMIT(y2, 0, term.row-1);
645 for(y = y1; y <= y2; y++)
646 for(x = x1; x <= x2; x++)
647 term.line[y][x].state = 0;
652 int src = term.c.x + n;
654 int size = term.col - src;
656 if(src >= term.col) {
657 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
660 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
661 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
665 tinsertblank(int n) {
668 int size = term.col - dst;
670 if(dst >= term.col) {
671 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
674 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
675 tclearregion(src, term.c.y, dst - 1, term.c.y);
679 tinsertblankline(int n) {
680 if(term.c.y < term.top || term.c.y > term.bot)
683 tscrolldown(term.c.y, n);
688 if(term.c.y < term.top || term.c.y > term.bot)
691 tscrollup(term.c.y, n);
695 tsetattr(int *attr, int l) {
698 for(i = 0; i < l; i++) {
701 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
702 term.c.attr.fg = DefaultFG;
703 term.c.attr.bg = DefaultBG;
706 term.c.attr.mode |= ATTR_BOLD;
709 term.c.attr.mode |= ATTR_UNDERLINE;
712 term.c.attr.mode |= ATTR_REVERSE;
715 term.c.attr.mode &= ~ATTR_BOLD;
718 term.c.attr.mode &= ~ATTR_UNDERLINE;
721 term.c.attr.mode &= ~ATTR_REVERSE;
724 if (i + 2 < l && attr[i + 1] == 5) {
726 if (BETWEEN(attr[i], 0, 255))
727 term.c.attr.fg = attr[i];
729 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
732 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
735 term.c.attr.fg = DefaultFG;
738 if (i + 2 < l && attr[i + 1] == 5) {
740 if (BETWEEN(attr[i], 0, 255))
741 term.c.attr.bg = attr[i];
743 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
746 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
749 term.c.attr.bg = DefaultBG;
752 if(BETWEEN(attr[i], 30, 37))
753 term.c.attr.fg = attr[i] - 30;
754 else if(BETWEEN(attr[i], 40, 47))
755 term.c.attr.bg = attr[i] - 40;
756 else if(BETWEEN(attr[i], 90, 97))
757 term.c.attr.fg = attr[i] - 90 + 8;
758 else if(BETWEEN(attr[i], 100, 107))
759 term.c.attr.fg = attr[i] - 100 + 8;
761 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
769 tsetscroll(int t, int b) {
772 LIMIT(t, 0, term.row-1);
773 LIMIT(b, 0, term.row-1);
785 switch(escseq.mode) {
788 printf("erresc: unknown csi ");
792 case '@': /* ICH -- Insert <n> blank char */
793 DEFAULT(escseq.arg[0], 1);
794 tinsertblank(escseq.arg[0]);
796 case 'A': /* CUU -- Cursor <n> Up */
798 DEFAULT(escseq.arg[0], 1);
799 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
801 case 'B': /* CUD -- Cursor <n> Down */
802 DEFAULT(escseq.arg[0], 1);
803 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
805 case 'C': /* CUF -- Cursor <n> Forward */
807 DEFAULT(escseq.arg[0], 1);
808 tmoveto(term.c.x+escseq.arg[0], term.c.y);
810 case 'D': /* CUB -- Cursor <n> Backward */
811 DEFAULT(escseq.arg[0], 1);
812 tmoveto(term.c.x-escseq.arg[0], term.c.y);
814 case 'E': /* CNL -- Cursor <n> Down and first col */
815 DEFAULT(escseq.arg[0], 1);
816 tmoveto(0, term.c.y+escseq.arg[0]);
818 case 'F': /* CPL -- Cursor <n> Up and first col */
819 DEFAULT(escseq.arg[0], 1);
820 tmoveto(0, term.c.y-escseq.arg[0]);
822 case 'G': /* CHA -- Move to <col> */
823 case '`': /* XXX: HPA -- same? */
824 DEFAULT(escseq.arg[0], 1);
825 tmoveto(escseq.arg[0]-1, term.c.y);
827 case 'H': /* CUP -- Move to <row> <col> */
828 case 'f': /* XXX: HVP -- same? */
829 DEFAULT(escseq.arg[0], 1);
830 DEFAULT(escseq.arg[1], 1);
831 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
833 /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
834 case 'J': /* ED -- Clear screen */
835 switch(escseq.arg[0]) {
837 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
838 if(term.c.y < term.row-1)
839 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
843 tclearregion(0, 0, term.col-1, term.c.y-1);
844 tclearregion(0, term.c.y, term.c.x, term.c.y);
847 tclearregion(0, 0, term.col-1, term.row-1);
853 case 'K': /* EL -- Clear line */
854 switch(escseq.arg[0]) {
856 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
859 tclearregion(0, term.c.y, term.c.x, term.c.y);
862 tclearregion(0, term.c.y, term.col-1, term.c.y);
866 case 'S': /* SU -- Scroll <n> line up */
867 DEFAULT(escseq.arg[0], 1);
868 tscrollup(term.top, escseq.arg[0]);
870 case 'T': /* SD -- Scroll <n> line down */
871 DEFAULT(escseq.arg[0], 1);
872 tscrolldown(term.top, escseq.arg[0]);
874 case 'L': /* IL -- Insert <n> blank lines */
875 DEFAULT(escseq.arg[0], 1);
876 tinsertblankline(escseq.arg[0]);
878 case 'l': /* RM -- Reset Mode */
880 switch(escseq.arg[0]) {
882 term.mode &= ~MODE_APPKEYPAD;
884 case 5: /* TODO: DECSCNM -- Remove reverse video */
887 term.mode &= ~MODE_WRAP;
889 case 12: /* att610 -- Stop blinking cursor (IGNORED) */
892 term.mode &= ~MODE_CRLF;
895 term.c.state |= CURSOR_HIDE;
897 case 1049: /* = 1047 and 1048 */
899 if(IS_SET(MODE_ALTSCREEN)) {
900 tclearregion(0, 0, term.col-1, term.row-1);
903 if(escseq.arg[0] == 1047)
906 tcursor(CURSOR_LOAD);
912 switch(escseq.arg[0]) {
914 term.mode &= ~MODE_INSERT;
921 case 'M': /* DL -- Delete <n> lines */
922 DEFAULT(escseq.arg[0], 1);
923 tdeleteline(escseq.arg[0]);
925 case 'X': /* ECH -- Erase <n> char */
926 DEFAULT(escseq.arg[0], 1);
927 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
929 case 'P': /* DCH -- Delete <n> char */
930 DEFAULT(escseq.arg[0], 1);
931 tdeletechar(escseq.arg[0]);
933 /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
934 case 'd': /* VPA -- Move to <row> */
935 DEFAULT(escseq.arg[0], 1);
936 tmoveto(term.c.x, escseq.arg[0]-1);
938 case 'h': /* SM -- Set terminal mode */
940 switch(escseq.arg[0]) {
942 term.mode |= MODE_APPKEYPAD;
944 case 5: /* DECSCNM -- Reverve video */
945 /* TODO: set REVERSE on the whole screen (f) */
948 term.mode |= MODE_WRAP;
951 term.mode |= MODE_CRLF;
953 case 12: /* att610 -- Start blinking cursor (IGNORED) */
954 /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
955 if(escseq.narg > 1 && escseq.arg[1] != 25)
958 term.c.state &= ~CURSOR_HIDE;
960 case 1049: /* = 1047 and 1048 */
962 if(IS_SET(MODE_ALTSCREEN))
963 tclearregion(0, 0, term.col-1, term.row-1);
966 if(escseq.arg[0] == 1047)
969 tcursor(CURSOR_SAVE);
971 default: goto unknown;
974 switch(escseq.arg[0]) {
976 term.mode |= MODE_INSERT;
978 default: goto unknown;
982 case 'm': /* SGR -- Terminal attribute (color) */
983 tsetattr(escseq.arg, escseq.narg);
985 case 'r': /* DECSTBM -- Set Scrolling Region */
989 DEFAULT(escseq.arg[0], 1);
990 DEFAULT(escseq.arg[1], term.row);
991 tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
995 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
996 tcursor(CURSOR_SAVE);
998 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
999 tcursor(CURSOR_LOAD);
1007 printf("ESC [ %s", escseq.priv ? "? " : "");
1009 for(i = 0; i < escseq.narg; i++)
1010 printf("%d ", escseq.arg[i]);
1012 putchar(escseq.mode);
1018 memset(&escseq, 0, sizeof(escseq));
1023 int space = TAB - term.c.x % TAB;
1024 tmoveto(term.c.x + space, term.c.y);
1029 if(term.esc & ESC_START) {
1030 if(term.esc & ESC_CSI) {
1031 escseq.buf[escseq.len++] = c;
1032 if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
1034 csiparse(), csihandle();
1036 /* TODO: handle other OSC */
1037 } else if(term.esc & ESC_OSC) {
1040 term.esc = ESC_START | ESC_TITLE;
1042 } else if(term.esc & ESC_TITLE) {
1043 if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
1045 term.title[term.titlelen] = '\0';
1046 XStoreName(xw.dis, xw.win, term.title);
1048 term.title[term.titlelen++] = c;
1050 } else if(term.esc & ESC_ALTCHARSET) {
1052 case '0': /* Line drawing crap */
1053 term.c.attr.mode |= ATTR_GFX;
1055 case 'B': /* Back to regular text */
1056 term.c.attr.mode &= ~ATTR_GFX;
1059 printf("esc unhandled charset: ESC ( %c\n", c);
1065 term.esc |= ESC_CSI;
1068 term.esc |= ESC_OSC;
1071 term.esc |= ESC_ALTCHARSET;
1073 case 'D': /* IND -- Linefeed */
1074 if(term.c.y == term.bot)
1075 tscrollup(term.top, 1);
1077 tmoveto(term.c.x, term.c.y+1);
1080 case 'E': /* NEL -- Next line */
1081 tnewline(1); /* always go to first col */
1084 case 'M': /* RI -- Reverse index */
1085 if(term.c.y == term.top)
1086 tscrolldown(term.top, 1);
1088 tmoveto(term.c.x, term.c.y-1);
1091 case 'c': /* RIS -- Reset to inital state */
1095 case '=': /* DECPAM -- Application keypad */
1096 term.mode |= MODE_APPKEYPAD;
1099 case '>': /* DECPNM -- Normal keypad */
1100 term.mode &= ~MODE_APPKEYPAD;
1103 case '7': /* DECSC -- Save Cursor */
1104 tcursor(CURSOR_SAVE);
1107 case '8': /* DECRC -- Restore Cursor */
1108 tcursor(CURSOR_LOAD);
1112 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
1122 tmoveto(term.c.x-1, term.c.y);
1125 tmoveto(0, term.c.y);
1130 /* go to first col if the mode is set */
1131 tnewline(IS_SET(MODE_CRLF));
1134 if(!(xw.state & WIN_FOCUSED))
1139 term.esc = ESC_START;
1142 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1143 tnewline(1); /* always go to first col */
1145 if(term.c.x+1 < term.col)
1146 tmoveto(term.c.x+1, term.c.y);
1148 term.c.state |= CURSOR_WRAPNEXT;
1155 tputs(char *s, int len) {
1156 for(; len > 0; len--)
1161 tresize(int col, int row) {
1163 int minrow = MIN(row, term.row);
1164 int mincol = MIN(col, term.col);
1165 int slide = term.c.y - row + 1;
1167 if(col < 1 || row < 1)
1170 /* free unneeded rows */
1173 /* slide screen to keep cursor where we expect it -
1174 * tscrollup would work here, but we can optimize to
1175 * memmove because we're freeing the earlier lines */
1176 for(/* i = 0 */; i < slide; i++) {
1180 memmove(term.line, term.line + slide, row * sizeof(Line));
1181 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1183 for(i += row; i < term.row; i++) {
1188 /* resize to new height */
1189 term.line = realloc(term.line, row * sizeof(Line));
1190 term.alt = realloc(term.alt, row * sizeof(Line));
1192 /* resize each row to new width, zero-pad if needed */
1193 for(i = 0; i < minrow; i++) {
1194 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1195 term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
1196 for(x = mincol; x < col; x++) {
1197 term.line[i][x].state = 0;
1198 term.alt[i][x].state = 0;
1202 /* allocate any new rows */
1203 for(/* i == minrow */; i < row; i++) {
1204 term.line[i] = calloc(col, sizeof(Glyph));
1205 term.alt [i] = calloc(col, sizeof(Glyph));
1208 /* update terminal size */
1209 term.col = col, term.row = row;
1210 /* make use of the LIMIT in tmoveto */
1211 tmoveto(term.c.x, term.c.y);
1212 /* reset scrolling region */
1213 tsetscroll(0, row-1);
1218 xresize(int col, int row) {
1224 xw.bufw = MAX(1, col * xw.cw);
1225 xw.bufh = MAX(1, row * xw.ch);
1226 newbuf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1227 XCopyArea(xw.dis, xw.buf, newbuf, dc.gc, 0, 0, xw.bufw, xw.bufh, 0, 0);
1228 XFreePixmap(xw.dis, xw.buf);
1229 XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1231 XFillRectangle(xw.dis, newbuf, dc.gc, oldw, 0,
1232 xw.bufw-oldw, MIN(xw.bufh, oldh));
1233 else if(xw.bufw < oldw && (BORDER > 0 || xw.w > xw.bufw))
1234 XClearArea(xw.dis, xw.win, BORDER+xw.bufw, BORDER,
1235 xw.w-xw.bufh-BORDER, BORDER+MIN(xw.bufh, oldh),
1238 XFillRectangle(xw.dis, newbuf, dc.gc, 0, oldh,
1239 xw.bufw, xw.bufh-oldh);
1240 else if(xw.bufh < oldh && (BORDER > 0 || xw.h > xw.bufh))
1241 XClearArea(xw.dis, xw.win, BORDER, BORDER+xw.bufh,
1242 xw.w-2*BORDER, xw.h-xw.bufh-BORDER,
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.state & WIN_FOCUSED)) {
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];
1457 if(!(xw.state & WIN_VISIBLE))
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);
1491 expose(XEvent *ev) {
1492 XExposeEvent *e = &ev->xexpose;
1493 if(xw.state & WIN_REDRAW) {
1495 xw.state &= ~WIN_REDRAW;
1496 draw(SCREEN_REDRAW);
1499 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
1500 e->width, e->height, e->x, e->y);
1504 visibility(XEvent *ev) {
1505 XVisibilityEvent *e = &ev->xvisibility;
1506 if(e->state == VisibilityFullyObscured)
1507 xw.state &= ~WIN_VISIBLE;
1508 else if(!(xw.state & WIN_VISIBLE))
1509 /* need a full redraw for next Expose, not just a buf copy */
1510 xw.state |= WIN_VISIBLE | WIN_REDRAW;
1515 xw.state &= ~WIN_VISIBLE;
1519 xseturgency(int add) {
1520 XWMHints *h = XGetWMHints(xw.dis, xw.win);
1521 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
1522 XSetWMHints(xw.dis, xw.win, h);
1528 if(ev->type == FocusIn) {
1529 xw.state |= WIN_FOCUSED;
1532 xw.state &= ~WIN_FOCUSED;
1533 draw(SCREEN_UPDATE);
1539 for(i = 0; i < LEN(key); i++)
1541 return (char*)key[i].s;
1546 kpress(XEvent *ev) {
1547 XKeyEvent *e = &ev->xkey;
1556 meta = e->state & Mod1Mask;
1557 shift = e->state & ShiftMask;
1558 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
1560 /* 1. custom keys from config.h */
1561 if((customkey = kmap(ksym)))
1562 ttywrite(customkey, strlen(customkey));
1563 /* 2. hardcoded (overrides X lookup) */
1570 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
1578 if(IS_SET(MODE_CRLF))
1579 ttywrite("\r\n", 2);
1586 buf[sizeof(buf)-1] = '\0';
1587 if(meta && len == 1)
1588 ttywrite("\033", 1);
1590 } else /* 4. nothing to send */
1591 fprintf(stderr, "errkey: %d\n", (int)ksym);
1600 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1603 xw.w = e->xconfigure.width;
1604 xw.h = e->xconfigure.height;
1605 col = (xw.w - 2*BORDER) / xw.cw;
1606 row = (xw.h - 2*BORDER) / xw.ch;
1607 if(col == term.col && row == term.row)
1609 if(tresize(col, row))
1610 draw(SCREEN_REDRAW);
1611 ttyresize(col, row);
1619 int xfd = XConnectionNumber(xw.dis);
1623 FD_SET(cmdfd, &rfd);
1625 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
1628 die("select failed: %s\n", SERRNO);
1630 if(FD_ISSET(cmdfd, &rfd)) {
1632 draw(SCREEN_UPDATE);
1634 while(XPending(xw.dis)) {
1635 XNextEvent(xw.dis, &ev);
1636 if (XFilterEvent(&ev, xw.win))
1638 if(handler[ev.type])
1639 (handler[ev.type])(&ev);
1645 main(int argc, char *argv[]) {
1648 for(i = 1; i < argc; i++) {
1649 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
1651 if(++i < argc) opt_title = argv[i];
1654 if(++i < argc) opt_cmd = argv[i];
1661 setlocale(LC_CTYPE, "");