1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
22 #include <X11/Xatom.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
28 #include <X11/Xft/Xft.h>
34 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
36 #elif defined(__FreeBSD__) || defined(__DragonFly__)
41 "st " VERSION " (c) 2010-2012 st engineers\n" \
42 "usage: st [-t title] [-c class] [-g geometry]" \
43 " [-w windowid] [-v] [-f file] [-e command...]\n"
46 #define XEMBED_FOCUS_IN 4
47 #define XEMBED_FOCUS_OUT 5
50 #define ESC_BUF_SIZ 256
51 #define ESC_ARG_SIZ 16
52 #define STR_BUF_SIZ 256
53 #define STR_ARG_SIZ 16
54 #define DRAW_BUF_SIZ 20*1024
56 #define XK_NO_MOD UINT_MAX
59 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
61 #define SERRNO strerror(errno)
62 #define MIN(a, b) ((a) < (b) ? (a) : (b))
63 #define MAX(a, b) ((a) < (b) ? (b) : (a))
64 #define LEN(a) (sizeof(a) / sizeof(a[0]))
65 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
66 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
67 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
68 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
69 #define IS_SET(flag) (term.mode & (flag))
70 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
71 #define X2COL(x) (((x) - BORDER)/xw.cw)
72 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
74 enum glyph_attribute {
84 enum cursor_movement {
111 MODE_MOUSEMOTION = 64,
120 ESC_STR = 4, /* DSC, OSC, PM, APC */
122 ESC_STR_END = 16, /* a final string was encountered */
133 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
135 typedef unsigned char uchar;
136 typedef unsigned int uint;
137 typedef unsigned long ulong;
138 typedef unsigned short ushort;
141 char c[UTF_SIZ]; /* character code */
142 uchar mode; /* attribute flags */
143 ushort fg; /* foreground */
144 ushort bg; /* background */
145 uchar state; /* state flags */
151 Glyph attr; /* current char attributes */
157 /* CSI Escape sequence structs */
158 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
160 char buf[ESC_BUF_SIZ]; /* raw string */
161 int len; /* raw string length */
163 int arg[ESC_ARG_SIZ];
164 int narg; /* nb of args */
168 /* STR Escape sequence structs */
169 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
171 char type; /* ESC type ... */
172 char buf[STR_BUF_SIZ]; /* raw string */
173 int len; /* raw string length */
174 char *args[STR_ARG_SIZ];
175 int narg; /* nb of args */
178 /* Internal representation of the screen */
180 int row; /* nb row */
181 int col; /* nb col */
182 Line* line; /* screen */
183 Line* alt; /* alternate screen */
184 bool* dirty; /* dirtyness of lines */
185 TCursor c; /* cursor */
186 int top; /* top scroll limit */
187 int bot; /* bottom scroll limit */
188 int mode; /* terminal mode flags */
189 int esc; /* escape state flags */
193 /* Purely graphic info */
205 bool isfixed; /* is fixed geometry? */
206 int fx, fy, fw, fh; /* fixed geometry */
207 int tw, th; /* tty width and height */
208 int w; /* window width */
209 int h; /* window height */
210 int ch; /* char height */
211 int cw; /* char width */
212 char state; /* focus, redraw, visible */
221 /* TODO: use better name for vars... */
226 struct {int x, y;} b, e;
230 struct timeval tclick1;
231 struct timeval tclick2;
245 /* Drawing Context */
247 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
249 Font font, bfont, ifont, ibfont;
252 static void die(const char*, ...);
253 static void draw(void);
254 static void redraw(void);
255 static void drawregion(int, int, int, int);
256 static void execsh(void);
257 static void sigchld(int);
258 static void run(void);
260 static void csidump(void);
261 static void csihandle(void);
262 static void csiparse(void);
263 static void csireset(void);
264 static void strdump(void);
265 static void strhandle(void);
266 static void strparse(void);
267 static void strreset(void);
269 static void tclearregion(int, int, int, int);
270 static void tcursor(int);
271 static void tdeletechar(int);
272 static void tdeleteline(int);
273 static void tinsertblank(int);
274 static void tinsertblankline(int);
275 static void tmoveto(int, int);
276 static void tnew(int, int);
277 static void tnewline(int);
278 static void tputtab(bool);
279 static void tputc(char*, int);
280 static void treset(void);
281 static int tresize(int, int);
282 static void tscrollup(int, int);
283 static void tscrolldown(int, int);
284 static void tsetattr(int*, int);
285 static void tsetchar(char*);
286 static void tsetscroll(int, int);
287 static void tswapscreen(void);
288 static void tsetdirt(int, int);
289 static void tsetmode(bool, bool, int *, int);
290 static void tfulldirt(void);
292 static void ttynew(void);
293 static void ttyread(void);
294 static void ttyresize(void);
295 static void ttywrite(const char *, size_t);
297 static void xdraws(char *, Glyph, int, int, int, int);
298 static void xhints(void);
299 static void xclear(int, int, int, int);
300 static void xclearborders(void);
301 static void xdrawcursor(void);
302 static void xinit(void);
303 static void xloadcols(void);
304 static void xresettitle(void);
305 static void xseturgency(int);
306 static void xsetsel(char*);
307 static void xtermclear(int, int, int, int);
308 static void xresize(int, int);
310 static void expose(XEvent *);
311 static void visibility(XEvent *);
312 static void unmap(XEvent *);
313 static char* kmap(KeySym, uint);
314 static void kpress(XEvent *);
315 static void cmessage(XEvent *);
316 static void resize(XEvent *);
317 static void focus(XEvent *);
318 static void brelease(XEvent *);
319 static void bpress(XEvent *);
320 static void bmotion(XEvent *);
321 static void selnotify(XEvent *);
322 static void selclear(XEvent *);
323 static void selrequest(XEvent *);
325 static void selinit(void);
326 static inline bool selected(int, int);
327 static void selcopy(void);
328 static void selpaste(void);
329 static void selscroll(int, int);
331 static int utf8decode(char *, long *);
332 static int utf8encode(long *, char *);
333 static int utf8size(char *);
334 static int isfullutf8(char *, int);
336 static void *xmalloc(size_t);
337 static void *xrealloc(void *, size_t);
338 static void *xcalloc(size_t nmemb, size_t size);
339 static char *smstrcat(char *, ...);
341 static void (*handler[LASTEvent])(XEvent *) = {
343 [ClientMessage] = cmessage,
344 [ConfigureNotify] = resize,
345 [VisibilityNotify] = visibility,
346 [UnmapNotify] = unmap,
350 [MotionNotify] = bmotion,
351 [ButtonPress] = bpress,
352 [ButtonRelease] = brelease,
353 [SelectionClear] = selclear,
354 [SelectionNotify] = selnotify,
355 [SelectionRequest] = selrequest,
362 static CSIEscape csiescseq;
363 static STREscape strescseq;
366 static Selection sel;
367 static int iofd = -1;
368 static char **opt_cmd = NULL;
369 static char *opt_io = NULL;
370 static char *opt_title = NULL;
371 static char *opt_embed = NULL;
372 static char *opt_class = NULL;
375 xmalloc(size_t len) {
376 void *p = malloc(len);
378 die("Out of memory\n");
383 xrealloc(void *p, size_t len) {
384 if((p = realloc(p, len)) == NULL)
385 die("Out of memory\n");
390 xcalloc(size_t nmemb, size_t size) {
391 void *p = calloc(nmemb, size);
393 die("Out of memory\n");
398 smstrcat(char *src, ...)
404 len = slen = strlen(src);
406 va_start(fmtargs, src);
408 v = va_arg(fmtargs, char *);
415 p = ret = xmalloc(len+1);
416 memmove(p, src, slen);
419 va_start(fmtargs, src);
421 v = va_arg(fmtargs, char *);
436 utf8decode(char *s, long *u) {
442 if(~c & B7) { /* 0xxxxxxx */
445 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
446 *u = c&(B4|B3|B2|B1|B0);
448 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
449 *u = c&(B3|B2|B1|B0);
451 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
456 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
458 if((c & (B7|B6)) != B7) /* 10xxxxxx */
461 *u |= c & (B5|B4|B3|B2|B1|B0);
463 if((n == 1 && *u < 0x80) ||
464 (n == 2 && *u < 0x800) ||
465 (n == 3 && *u < 0x10000) ||
466 (*u >= 0xD800 && *u <= 0xDFFF))
475 utf8encode(long *u, char *s) {
483 *sp = uc; /* 0xxxxxxx */
485 } else if(*u < 0x800) {
486 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
488 } else if(uc < 0x10000) {
489 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
491 } else if(uc <= 0x10FFFF) {
492 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
497 for(i=n,++sp; i>0; --i,++sp)
498 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
508 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
509 UTF-8 otherwise return 0 */
511 isfullutf8(char *s, int b) {
519 else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
521 else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
523 ((b == 2) && (*c2&(B7|B6)) == B7)))
525 else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
527 ((b == 2) && (*c2&(B7|B6)) == B7) ||
528 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
540 else if((c&(B7|B6|B5)) == (B7|B6))
542 else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
550 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
551 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
555 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
556 if(sel.xtarget == None)
557 sel.xtarget = XA_STRING;
561 selected(int x, int y) {
562 if(sel.ey == y && sel.by == y) {
563 int bx = MIN(sel.bx, sel.ex);
564 int ex = MAX(sel.bx, sel.ex);
565 return BETWEEN(x, bx, ex);
567 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
568 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
572 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
574 *b = e->xbutton.button;
576 *x = X2COL(e->xbutton.x);
577 *y = Y2ROW(e->xbutton.y);
578 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
579 sel.b.y = MIN(sel.by, sel.ey);
580 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
581 sel.e.y = MAX(sel.by, sel.ey);
585 mousereport(XEvent *e) {
586 int x = X2COL(e->xbutton.x);
587 int y = Y2ROW(e->xbutton.y);
588 int button = e->xbutton.button;
589 int state = e->xbutton.state;
590 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
591 static int ob, ox, oy;
594 if(e->xbutton.type == MotionNotify) {
595 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
599 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
605 if(e->xbutton.type == ButtonPress) {
611 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
612 + (state & Mod4Mask ? 8 : 0)
613 + (state & ControlMask ? 16 : 0);
615 ttywrite(buf, sizeof(buf));
620 if(IS_SET(MODE_MOUSE))
622 else if(e->xbutton.button == Button1) {
625 tsetdirt(sel.b.y, sel.e.y);
629 sel.ex = sel.bx = X2COL(e->xbutton.x);
630 sel.ey = sel.by = Y2ROW(e->xbutton.y);
637 int x, y, bufsize, is_selected = 0;
643 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
644 ptr = str = xmalloc(bufsize);
646 /* append every set & selected glyph to the selection */
647 for(y = 0; y < term.row; y++) {
648 for(x = 0; x < term.col; x++) {
651 Glyph *gp = &term.line[y][x];
653 if(!(is_selected = selected(x, y)))
655 p = (gp->state & GLYPH_SET) ? gp->c : " ";
657 memcpy(ptr, p, size);
660 /* \n at the end of every selected line except for the last one */
661 if(is_selected && y < sel.e.y)
666 sel.alt = IS_SET(MODE_ALTSCREEN);
671 selnotify(XEvent *e) {
672 ulong nitems, ofs, rem;
679 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
680 False, AnyPropertyType, &type, &format,
681 &nitems, &rem, &data)) {
682 fprintf(stderr, "Clipboard allocation failed\n");
685 ttywrite((const char *) data, nitems * format / 8);
687 /* number of 32-bit chunks returned */
688 ofs += nitems * format / 32;
694 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
697 void selclear(XEvent *e) {
701 tsetdirt(sel.b.y, sel.e.y);
705 selrequest(XEvent *e) {
706 XSelectionRequestEvent *xsre;
710 xsre = (XSelectionRequestEvent *) e;
711 xev.type = SelectionNotify;
712 xev.requestor = xsre->requestor;
713 xev.selection = xsre->selection;
714 xev.target = xsre->target;
715 xev.time = xsre->time;
719 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
720 if(xsre->target == xa_targets) {
721 /* respond with the supported type */
722 Atom string = sel.xtarget;
723 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
724 XA_ATOM, 32, PropModeReplace,
725 (uchar *) &string, 1);
726 xev.property = xsre->property;
727 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
728 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
729 xsre->target, 8, PropModeReplace,
730 (uchar *) sel.clip, strlen(sel.clip));
731 xev.property = xsre->property;
734 /* all done, send a notification to the listener */
735 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
736 fprintf(stderr, "Error sending SelectionNotify event\n");
741 /* register the selection for both the clipboard and the primary */
747 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
749 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
750 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
754 brelease(XEvent *e) {
755 if(IS_SET(MODE_MOUSE)) {
759 if(e->xbutton.button == Button2)
761 else if(e->xbutton.button == Button1) {
763 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
764 term.dirty[sel.ey] = 1;
765 if(sel.bx == sel.ex && sel.by == sel.ey) {
768 gettimeofday(&now, NULL);
770 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
771 /* triple click on the line */
772 sel.b.x = sel.bx = 0;
773 sel.e.x = sel.ex = term.col;
774 sel.b.y = sel.e.y = sel.ey;
776 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
777 /* double click to select word */
779 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
780 term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
782 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
783 term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
785 sel.b.y = sel.e.y = sel.ey;
791 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
792 gettimeofday(&sel.tclick1, NULL);
797 if(IS_SET(MODE_MOUSE)) {
802 int oldey = sel.ey, oldex = sel.ex;
803 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
805 if(oldey != sel.ey || oldex != sel.ex) {
806 int starty = MIN(oldey, sel.ey);
807 int endy = MAX(oldey, sel.ey);
808 tsetdirt(starty, endy);
814 die(const char *errstr, ...) {
817 va_start(ap, errstr);
818 vfprintf(stderr, errstr, ap);
826 char *envshell = getenv("SHELL");
832 signal(SIGCHLD, SIG_DFL);
833 signal(SIGHUP, SIG_DFL);
834 signal(SIGINT, SIG_DFL);
835 signal(SIGQUIT, SIG_DFL);
836 signal(SIGTERM, SIG_DFL);
837 signal(SIGALRM, SIG_DFL);
839 DEFAULT(envshell, SHELL);
840 putenv("TERM="TNAME);
841 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
842 execvp(args[0], args);
849 if(waitpid(pid, &stat, 0) < 0)
850 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
852 exit(WEXITSTATUS(stat));
861 /* seems to work fine on linux, openbsd and freebsd */
862 struct winsize w = {term.row, term.col, 0, 0};
863 if(openpty(&m, &s, NULL, NULL, &w) < 0)
864 die("openpty failed: %s\n", SERRNO);
866 switch(pid = fork()) {
868 die("fork failed\n");
871 setsid(); /* create a new process group */
872 dup2(s, STDIN_FILENO);
873 dup2(s, STDOUT_FILENO);
874 dup2(s, STDERR_FILENO);
875 if(ioctl(s, TIOCSCTTY, NULL) < 0)
876 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
884 signal(SIGCHLD, sigchld);
886 if(!strcmp(opt_io, "-")) {
887 iofd = STDOUT_FILENO;
889 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
890 fprintf(stderr, "Error opening %s:%s\n",
891 opt_io, strerror(errno));
901 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
903 fprintf(stderr, "\n");
908 static char buf[BUFSIZ];
909 static int buflen = 0;
912 int charsize; /* size of utf8 char in bytes */
916 /* append read bytes to unprocessed bytes */
917 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
918 die("Couldn't read from shell: %s\n", SERRNO);
920 /* process every complete utf8 char */
923 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
924 charsize = utf8decode(ptr, &utf8c);
925 utf8encode(&utf8c, s);
931 /* keep any uncomplete utf8 char for the next call */
932 memmove(buf, ptr, buflen);
936 ttywrite(const char *s, size_t n) {
937 if(write(cmdfd, s, n) == -1)
938 die("write error on tty: %s\n", SERRNO);
949 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
950 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
954 tsetdirt(int top, int bot)
958 LIMIT(top, 0, term.row-1);
959 LIMIT(bot, 0, term.row-1);
961 for(i = top; i <= bot; i++)
968 tsetdirt(0, term.row-1);
975 if(mode == CURSOR_SAVE)
977 else if(mode == CURSOR_LOAD)
978 term.c = c, tmoveto(c.x, c.y);
988 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
990 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
991 for(i = TAB; i < term.col; i += TAB)
993 term.top = 0, term.bot = term.row - 1;
994 term.mode = MODE_WRAP;
996 tclearregion(0, 0, term.col-1, term.row-1);
1000 tnew(int col, int row) {
1001 /* set screen size */
1002 term.row = row, term.col = col;
1003 term.line = xmalloc(term.row * sizeof(Line));
1004 term.alt = xmalloc(term.row * sizeof(Line));
1005 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1006 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1008 for(row = 0; row < term.row; row++) {
1009 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1010 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1011 term.dirty[row] = 0;
1013 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1020 Line* tmp = term.line;
1021 term.line = term.alt;
1023 term.mode ^= MODE_ALTSCREEN;
1028 tscrolldown(int orig, int n) {
1032 LIMIT(n, 0, term.bot-orig+1);
1034 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1036 for(i = term.bot; i >= orig+n; i--) {
1037 temp = term.line[i];
1038 term.line[i] = term.line[i-n];
1039 term.line[i-n] = temp;
1042 term.dirty[i-n] = 1;
1049 tscrollup(int orig, int n) {
1052 LIMIT(n, 0, term.bot-orig+1);
1054 tclearregion(0, orig, term.col-1, orig+n-1);
1056 for(i = orig; i <= term.bot-n; i++) {
1057 temp = term.line[i];
1058 term.line[i] = term.line[i+n];
1059 term.line[i+n] = temp;
1062 term.dirty[i+n] = 1;
1065 selscroll(orig, -n);
1069 selscroll(int orig, int n) {
1073 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1074 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1078 if(sel.by < term.top) {
1082 if(sel.ey > term.bot) {
1086 sel.b.y = sel.by, sel.b.x = sel.bx;
1087 sel.e.y = sel.ey, sel.e.x = sel.ex;
1092 tnewline(int first_col) {
1095 tscrollup(term.top, 1);
1098 tmoveto(first_col ? 0 : term.c.x, y);
1103 /* int noarg = 1; */
1104 char *p = csiescseq.buf;
1108 csiescseq.priv = 1, p++;
1110 while(p < csiescseq.buf+csiescseq.len) {
1111 while(isdigit(*p)) {
1112 csiescseq.arg[csiescseq.narg] *= 10;
1113 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1115 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1116 csiescseq.narg++, p++;
1118 csiescseq.mode = *p;
1126 tmoveto(int x, int y) {
1127 LIMIT(x, 0, term.col-1);
1128 LIMIT(y, 0, term.row-1);
1129 term.c.state &= ~CURSOR_WRAPNEXT;
1137 * The table is proudly stolen from rxvt.
1139 if(term.c.attr.mode & ATTR_GFX) {
1140 char *vt100_0[62] = { /* 0x41 - 0x7e */
1141 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1142 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1143 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1144 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1145 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1146 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1147 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1148 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1151 if(c[0] >= 0x41 && c[0] <= 0x7e
1152 && vt100_0[c[0] - 0x41]) {
1153 c = vt100_0[c[0] - 0x41];
1157 term.dirty[term.c.y] = 1;
1158 term.line[term.c.y][term.c.x] = term.c.attr;
1159 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1160 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1164 tclearregion(int x1, int y1, int x2, int y2) {
1168 temp = x1, x1 = x2, x2 = temp;
1170 temp = y1, y1 = y2, y2 = temp;
1172 LIMIT(x1, 0, term.col-1);
1173 LIMIT(x2, 0, term.col-1);
1174 LIMIT(y1, 0, term.row-1);
1175 LIMIT(y2, 0, term.row-1);
1177 for(y = y1; y <= y2; y++) {
1179 for(x = x1; x <= x2; x++)
1180 term.line[y][x].state = 0;
1185 tdeletechar(int n) {
1186 int src = term.c.x + n;
1188 int size = term.col - src;
1190 term.dirty[term.c.y] = 1;
1192 if(src >= term.col) {
1193 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1196 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1197 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1201 tinsertblank(int n) {
1204 int size = term.col - dst;
1206 term.dirty[term.c.y] = 1;
1208 if(dst >= term.col) {
1209 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1212 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1213 tclearregion(src, term.c.y, dst - 1, term.c.y);
1217 tinsertblankline(int n) {
1218 if(term.c.y < term.top || term.c.y > term.bot)
1221 tscrolldown(term.c.y, n);
1225 tdeleteline(int n) {
1226 if(term.c.y < term.top || term.c.y > term.bot)
1229 tscrollup(term.c.y, n);
1233 tsetattr(int *attr, int l) {
1236 for(i = 0; i < l; i++) {
1239 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1240 | ATTR_ITALIC | ATTR_BLINK);
1241 term.c.attr.fg = DefaultFG;
1242 term.c.attr.bg = DefaultBG;
1245 term.c.attr.mode |= ATTR_BOLD;
1247 case 3: /* enter standout (highlight) */
1248 term.c.attr.mode |= ATTR_ITALIC;
1251 term.c.attr.mode |= ATTR_UNDERLINE;
1254 term.c.attr.mode |= ATTR_BLINK;
1257 term.c.attr.mode |= ATTR_REVERSE;
1261 term.c.attr.mode &= ~ATTR_BOLD;
1263 case 23: /* leave standout (highlight) mode */
1264 term.c.attr.mode &= ~ATTR_ITALIC;
1267 term.c.attr.mode &= ~ATTR_UNDERLINE;
1270 term.c.attr.mode &= ~ATTR_BLINK;
1273 term.c.attr.mode &= ~ATTR_REVERSE;
1276 if(i + 2 < l && attr[i + 1] == 5) {
1278 if(BETWEEN(attr[i], 0, 255))
1279 term.c.attr.fg = attr[i];
1281 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1284 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1287 term.c.attr.fg = DefaultFG;
1290 if(i + 2 < l && attr[i + 1] == 5) {
1292 if(BETWEEN(attr[i], 0, 255))
1293 term.c.attr.bg = attr[i];
1295 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1298 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1301 term.c.attr.bg = DefaultBG;
1304 if(BETWEEN(attr[i], 30, 37))
1305 term.c.attr.fg = attr[i] - 30;
1306 else if(BETWEEN(attr[i], 40, 47))
1307 term.c.attr.bg = attr[i] - 40;
1308 else if(BETWEEN(attr[i], 90, 97))
1309 term.c.attr.fg = attr[i] - 90 + 8;
1310 else if(BETWEEN(attr[i], 100, 107))
1311 term.c.attr.bg = attr[i] - 100 + 8;
1313 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1320 tsetscroll(int t, int b) {
1323 LIMIT(t, 0, term.row-1);
1324 LIMIT(b, 0, term.row-1);
1334 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1337 tsetmode(bool priv, bool set, int *args, int narg) {
1340 for(lim = args + narg; args < lim; ++args) {
1344 case 1: /* DECCKM -- Cursor key */
1345 MODBIT(term.mode, set, MODE_APPKEYPAD);
1347 case 5: /* DECSCNM -- Reverve video */
1349 MODBIT(term.mode, set, MODE_REVERSE);
1350 if(mode != term.mode)
1353 case 6: /* XXX: DECOM -- Origin */
1355 case 7: /* DECAWM -- Auto wrap */
1356 MODBIT(term.mode, set, MODE_WRAP);
1358 case 8: /* XXX: DECARM -- Auto repeat */
1360 case 0: /* Error (IGNORED) */
1361 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1364 MODBIT(term.c.state, !set, CURSOR_HIDE);
1366 case 1000: /* 1000,1002: enable xterm mouse report */
1367 MODBIT(term.mode, set, MODE_MOUSEBTN);
1370 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1372 case 1049: /* = 1047 and 1048 */
1375 if(IS_SET(MODE_ALTSCREEN))
1376 tclearregion(0, 0, term.col-1, term.row-1);
1377 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1378 (!set && IS_SET(MODE_ALTSCREEN))) {
1385 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1388 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1389 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1390 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1391 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1392 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1393 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1395 "erresc: unknown private set/reset mode %d\n",
1401 case 0: /* Error (IGNORED) */
1403 case 2: /* KAM -- keyboard action */
1404 MODBIT(term.mode, set, MODE_KBDLOCK);
1406 case 4: /* IRM -- Insertion-replacement */
1407 MODBIT(term.mode, set, MODE_INSERT);
1409 case 12: /* XXX: SRM -- Send/Receive */
1411 case 20: /* LNM -- Linefeed/new line */
1412 MODBIT(term.mode, set, MODE_CRLF);
1416 "erresc: unknown set/reset mode %d\n",
1428 switch(csiescseq.mode) {
1431 fprintf(stderr, "erresc: unknown csi ");
1435 case '@': /* ICH -- Insert <n> blank char */
1436 DEFAULT(csiescseq.arg[0], 1);
1437 tinsertblank(csiescseq.arg[0]);
1439 case 'A': /* CUU -- Cursor <n> Up */
1441 DEFAULT(csiescseq.arg[0], 1);
1442 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1444 case 'B': /* CUD -- Cursor <n> Down */
1445 DEFAULT(csiescseq.arg[0], 1);
1446 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1448 case 'C': /* CUF -- Cursor <n> Forward */
1450 DEFAULT(csiescseq.arg[0], 1);
1451 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1453 case 'D': /* CUB -- Cursor <n> Backward */
1454 DEFAULT(csiescseq.arg[0], 1);
1455 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1457 case 'E': /* CNL -- Cursor <n> Down and first col */
1458 DEFAULT(csiescseq.arg[0], 1);
1459 tmoveto(0, term.c.y+csiescseq.arg[0]);
1461 case 'F': /* CPL -- Cursor <n> Up and first col */
1462 DEFAULT(csiescseq.arg[0], 1);
1463 tmoveto(0, term.c.y-csiescseq.arg[0]);
1465 case 'g': /* TBC -- Tabulation clear */
1466 switch (csiescseq.arg[0]) {
1467 case 0: /* clear current tab stop */
1468 term.tabs[term.c.x] = 0;
1470 case 3: /* clear all the tabs */
1471 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1477 case 'G': /* CHA -- Move to <col> */
1479 DEFAULT(csiescseq.arg[0], 1);
1480 tmoveto(csiescseq.arg[0]-1, term.c.y);
1482 case 'H': /* CUP -- Move to <row> <col> */
1484 DEFAULT(csiescseq.arg[0], 1);
1485 DEFAULT(csiescseq.arg[1], 1);
1486 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1488 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1489 DEFAULT(csiescseq.arg[0], 1);
1490 while(csiescseq.arg[0]--)
1493 case 'J': /* ED -- Clear screen */
1495 switch(csiescseq.arg[0]) {
1497 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1498 if(term.c.y < term.row-1)
1499 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1503 tclearregion(0, 0, term.col-1, term.c.y-1);
1504 tclearregion(0, term.c.y, term.c.x, term.c.y);
1507 tclearregion(0, 0, term.col-1, term.row-1);
1513 case 'K': /* EL -- Clear line */
1514 switch(csiescseq.arg[0]) {
1516 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1519 tclearregion(0, term.c.y, term.c.x, term.c.y);
1522 tclearregion(0, term.c.y, term.col-1, term.c.y);
1526 case 'S': /* SU -- Scroll <n> line up */
1527 DEFAULT(csiescseq.arg[0], 1);
1528 tscrollup(term.top, csiescseq.arg[0]);
1530 case 'T': /* SD -- Scroll <n> line down */
1531 DEFAULT(csiescseq.arg[0], 1);
1532 tscrolldown(term.top, csiescseq.arg[0]);
1534 case 'L': /* IL -- Insert <n> blank lines */
1535 DEFAULT(csiescseq.arg[0], 1);
1536 tinsertblankline(csiescseq.arg[0]);
1538 case 'l': /* RM -- Reset Mode */
1539 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1541 case 'M': /* DL -- Delete <n> lines */
1542 DEFAULT(csiescseq.arg[0], 1);
1543 tdeleteline(csiescseq.arg[0]);
1545 case 'X': /* ECH -- Erase <n> char */
1546 DEFAULT(csiescseq.arg[0], 1);
1547 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1549 case 'P': /* DCH -- Delete <n> char */
1550 DEFAULT(csiescseq.arg[0], 1);
1551 tdeletechar(csiescseq.arg[0]);
1553 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1554 DEFAULT(csiescseq.arg[0], 1);
1555 while(csiescseq.arg[0]--)
1558 case 'd': /* VPA -- Move to <row> */
1559 DEFAULT(csiescseq.arg[0], 1);
1560 tmoveto(term.c.x, csiescseq.arg[0]-1);
1562 case 'h': /* SM -- Set terminal mode */
1563 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1565 case 'm': /* SGR -- Terminal attribute (color) */
1566 tsetattr(csiescseq.arg, csiescseq.narg);
1568 case 'r': /* DECSTBM -- Set Scrolling Region */
1572 DEFAULT(csiescseq.arg[0], 1);
1573 DEFAULT(csiescseq.arg[1], term.row);
1574 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1578 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1579 tcursor(CURSOR_SAVE);
1581 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1582 tcursor(CURSOR_LOAD);
1591 for(i = 0; i < csiescseq.len; i++) {
1592 uint c = csiescseq.buf[i] & 0xff;
1593 if(isprint(c)) putchar(c);
1594 else if(c == '\n') printf("(\\n)");
1595 else if(c == '\r') printf("(\\r)");
1596 else if(c == 0x1b) printf("(\\e)");
1597 else printf("(%02x)", c);
1604 memset(&csiescseq, 0, sizeof(csiescseq));
1612 * TODO: make this being useful in case of color palette change.
1618 switch(strescseq.type) {
1619 case ']': /* OSC -- Operating System Command */
1625 * TODO: Handle special chars in string, like umlauts.
1628 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1632 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1634 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1637 fprintf(stderr, "erresc: unknown str ");
1642 case 'k': /* old title set compatibility */
1643 XStoreName(xw.dpy, xw.win, strescseq.buf);
1645 case 'P': /* DSC -- Device Control String */
1646 case '_': /* APC -- Application Program Command */
1647 case '^': /* PM -- Privacy Message */
1649 fprintf(stderr, "erresc: unknown str ");
1659 * TODO: Implement parsing like for CSI when required.
1660 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1668 printf("ESC%c", strescseq.type);
1669 for(i = 0; i < strescseq.len; i++) {
1670 uint c = strescseq.buf[i] & 0xff;
1671 if(isprint(c)) putchar(c);
1672 else if(c == '\n') printf("(\\n)");
1673 else if(c == '\r') printf("(\\r)");
1674 else if(c == 0x1b) printf("(\\e)");
1675 else printf("(%02x)", c);
1682 memset(&strescseq, 0, sizeof(strescseq));
1686 tputtab(bool forward) {
1692 for(++x; x < term.col && !term.tabs[x]; ++x)
1697 for(--x; x > 0 && !term.tabs[x]; --x)
1700 tmoveto(x, term.c.y);
1704 tputc(char *c, int len) {
1708 write(iofd, c, len);
1715 tmoveto(term.c.x-1, term.c.y);
1718 tmoveto(0, term.c.y);
1723 /* go to first col if the mode is set */
1724 tnewline(IS_SET(MODE_CRLF));
1727 if(term.esc & ESC_STR)
1730 if(!(xw.state & WIN_FOCUSED))
1735 term.esc = ESC_START;
1739 if(term.esc & ESC_START) {
1740 if(term.esc & ESC_CSI) {
1741 csiescseq.buf[csiescseq.len++] = ascii;
1742 if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1744 csiparse(), csihandle();
1746 } else if(term.esc & ESC_STR) {
1749 term.esc = ESC_START | ESC_STR_END;
1751 case '\a': /* backwards compatibility to xterm */
1756 strescseq.buf[strescseq.len++] = ascii;
1757 if(strescseq.len+1 >= STR_BUF_SIZ) {
1762 } else if(term.esc & ESC_STR_END) {
1766 } else if(term.esc & ESC_ALTCHARSET) {
1768 case '0': /* Line drawing set */
1769 term.c.attr.mode |= ATTR_GFX;
1771 case 'B': /* USASCII */
1772 term.c.attr.mode &= ~ATTR_GFX;
1774 case 'A': /* UK (IGNORED) */
1775 case '<': /* multinational charset (IGNORED) */
1776 case '5': /* Finnish (IGNORED) */
1777 case 'C': /* Finnish (IGNORED) */
1778 case 'K': /* German (IGNORED) */
1781 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1787 term.esc |= ESC_CSI;
1789 case 'P': /* DCS -- Device Control String */
1790 case '_': /* APC -- Application Program Command */
1791 case '^': /* PM -- Privacy Message */
1792 case ']': /* OSC -- Operating System Command */
1793 case 'k': /* old title set compatibility */
1795 strescseq.type = ascii;
1796 term.esc |= ESC_STR;
1798 case '(': /* set primary charset G0 */
1799 term.esc |= ESC_ALTCHARSET;
1801 case ')': /* set secondary charset G1 (IGNORED) */
1802 case '*': /* set tertiary charset G2 (IGNORED) */
1803 case '+': /* set quaternary charset G3 (IGNORED) */
1806 case 'D': /* IND -- Linefeed */
1807 if(term.c.y == term.bot)
1808 tscrollup(term.top, 1);
1810 tmoveto(term.c.x, term.c.y+1);
1813 case 'E': /* NEL -- Next line */
1814 tnewline(1); /* always go to first col */
1817 case 'H': /* HTS -- Horizontal tab stop */
1818 term.tabs[term.c.x] = 1;
1821 case 'M': /* RI -- Reverse index */
1822 if(term.c.y == term.top)
1823 tscrolldown(term.top, 1);
1825 tmoveto(term.c.x, term.c.y-1);
1828 case 'c': /* RIS -- Reset to inital state */
1834 case '=': /* DECPAM -- Application keypad */
1835 term.mode |= MODE_APPKEYPAD;
1838 case '>': /* DECPNM -- Normal keypad */
1839 term.mode &= ~MODE_APPKEYPAD;
1842 case '7': /* DECSC -- Save Cursor */
1843 tcursor(CURSOR_SAVE);
1846 case '8': /* DECRC -- Restore Cursor */
1847 tcursor(CURSOR_LOAD);
1850 case '\\': /* ST -- Stop */
1854 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1855 (uchar) ascii, isprint(ascii)?ascii:'.');
1860 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1862 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1863 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1864 tnewline(1); /* always go to first col */
1866 if(term.c.x+1 < term.col)
1867 tmoveto(term.c.x+1, term.c.y);
1869 term.c.state |= CURSOR_WRAPNEXT;
1875 tresize(int col, int row) {
1877 int minrow = MIN(row, term.row);
1878 int mincol = MIN(col, term.col);
1879 int slide = term.c.y - row + 1;
1881 if(col < 1 || row < 1)
1884 /* free unneeded rows */
1887 /* slide screen to keep cursor where we expect it -
1888 * tscrollup would work here, but we can optimize to
1889 * memmove because we're freeing the earlier lines */
1890 for(/* i = 0 */; i < slide; i++) {
1894 memmove(term.line, term.line + slide, row * sizeof(Line));
1895 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1897 for(i += row; i < term.row; i++) {
1902 /* resize to new height */
1903 term.line = xrealloc(term.line, row * sizeof(Line));
1904 term.alt = xrealloc(term.alt, row * sizeof(Line));
1905 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1906 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1908 /* resize each row to new width, zero-pad if needed */
1909 for(i = 0; i < minrow; i++) {
1911 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1912 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
1913 for(x = mincol; x < col; x++) {
1914 term.line[i][x].state = 0;
1915 term.alt[i][x].state = 0;
1919 /* allocate any new rows */
1920 for(/* i == minrow */; i < row; i++) {
1922 term.line[i] = xcalloc(col, sizeof(Glyph));
1923 term.alt [i] = xcalloc(col, sizeof(Glyph));
1925 if(col > term.col) {
1926 bool *bp = term.tabs + term.col;
1928 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1929 while(--bp > term.tabs && !*bp)
1931 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1934 /* update terminal size */
1935 term.col = col, term.row = row;
1936 /* make use of the LIMIT in tmoveto */
1937 tmoveto(term.c.x, term.c.y);
1938 /* reset scrolling region */
1939 tsetscroll(0, row-1);
1945 xresize(int col, int row) {
1946 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
1947 xw.th = MAX(1, 2*BORDER + row * xw.ch);
1949 XftDrawChange(xw.xft_draw, xw.buf);
1955 XRenderColor xft_color = { .alpha = 0 };
1957 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1958 for(i = 0; i < LEN(colorname); i++) {
1961 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
1962 die("Could not allocate color '%s'\n", colorname[i]);
1966 /* load colors [16-255] ; same colors as xterm */
1967 for(i = 16, r = 0; r < 6; r++)
1968 for(g = 0; g < 6; g++)
1969 for(b = 0; b < 6; b++) {
1970 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1971 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1972 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1973 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1974 die("Could not allocate color %d\n", i);
1979 for(r = 0; r < 24; r++, i++) {
1980 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
1981 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1982 dc.xft_col[i] = dc.xft_col[256];
1983 fprintf(stderr, "Could not allocate color %d\n", i);
1989 xtermclear(int col1, int row1, int col2, int row2) {
1990 XftDrawRect(xw.xft_draw,
1991 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
1992 BORDER + col1 * xw.cw,
1993 BORDER + row1 * xw.ch,
1994 (col2-col1+1) * xw.cw,
1995 (row2-row1+1) * xw.ch);
1999 * Absolute coordinates.
2002 xclear(int x1, int y1, int x2, int y2) {
2003 XftDrawRect(xw.xft_draw,
2004 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2005 x1, y1, x2-x1, y2-y1);
2009 xclearborders(void) {
2010 /* top and left border */
2011 xclear(0, 0, BORDER, xw.h);
2012 xclear(0, 0, xw.w, BORDER);
2014 /* lower and right border */
2015 xclear(BORDER, xw.th - 1, xw.w, xw.h);
2016 /* Will just draw what hasn't been drawn by the previous call. */
2017 xclear(xw.tw - 1, BORDER, xw.w, xw.h - xw.th - 2);
2022 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2023 XWMHints wm = {.flags = InputHint, .input = 1};
2024 XSizeHints *sizeh = NULL;
2026 sizeh = XAllocSizeHints();
2027 if(xw.isfixed == False) {
2028 sizeh->flags = PSize | PResizeInc | PBaseSize;
2029 sizeh->height = xw.h;
2030 sizeh->width = xw.w;
2031 sizeh->height_inc = xw.ch;
2032 sizeh->width_inc = xw.cw;
2033 sizeh->base_height = 2*BORDER;
2034 sizeh->base_width = 2*BORDER;
2036 sizeh->flags = PMaxSize | PMinSize;
2037 sizeh->min_width = sizeh->max_width = xw.fw;
2038 sizeh->min_height = sizeh->max_height = xw.fh;
2041 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2046 xinitfont(Font *f, char *fontstr) {
2047 f->xft_set = XftFontOpenName(xw.dpy, xw.scr, fontstr);
2050 die("st: can't open font %s.\n", fontstr);
2052 f->ascent = f->xft_set->ascent;
2053 f->descent = f->xft_set->descent;
2055 f->rbearing = f->xft_set->max_advance_width;
2059 initfonts(char *fontstr) {
2062 xinitfont(&dc.font, fontstr);
2064 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2065 xinitfont(&dc.bfont, fstr);
2068 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2069 xinitfont(&dc.ifont, fstr);
2072 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2073 xinitfont(&dc.ibfont, fstr);
2079 XSetWindowAttributes attrs;
2082 int sw, sh, major, minor;
2084 if(!(xw.dpy = XOpenDisplay(NULL)))
2085 die("Can't open display\n");
2086 xw.scr = XDefaultScreen(xw.dpy);
2087 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2092 /* XXX: Assuming same size for bold font */
2093 xw.cw = dc.font.rbearing - dc.font.lbearing;
2094 xw.ch = dc.font.ascent + dc.font.descent;
2097 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2100 /* adjust fixed window geometry */
2102 sw = DisplayWidth(xw.dpy, xw.scr);
2103 sh = DisplayHeight(xw.dpy, xw.scr);
2105 xw.fx = sw + xw.fx - xw.fw - 1;
2107 xw.fy = sh + xw.fy - xw.fh - 1;
2112 /* window - default size */
2113 xw.h = 2*BORDER + term.row * xw.ch;
2114 xw.w = 2*BORDER + term.col * xw.cw;
2119 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2120 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2121 attrs.bit_gravity = NorthWestGravity;
2122 attrs.event_mask = FocusChangeMask | KeyPressMask
2123 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2124 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2125 attrs.colormap = xw.cmap;
2127 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2128 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2129 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2131 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2135 /* double buffering */
2136 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2137 die("Xdbe extension is not present\n");
2138 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2140 /* Xft rendering context */
2141 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2144 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2145 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2146 | XIMStatusNothing, XNClientWindow, xw.win,
2147 XNFocusWindow, xw.win, NULL);
2149 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2151 /* white cursor, black outline */
2152 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2153 XDefineCursor(xw.dpy, xw.win, cursor);
2154 XRecolorCursor(xw.dpy, cursor,
2155 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2156 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2158 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2161 XMapWindow(xw.dpy, xw.win);
2167 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2168 int fg = base.fg, bg = base.bg, temp;
2169 int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
2170 Font *font = &dc.font;
2173 /* only switch default fg/bg if term is in RV mode */
2174 if(IS_SET(MODE_REVERSE)) {
2181 if(base.mode & ATTR_REVERSE)
2182 temp = fg, fg = bg, bg = temp;
2184 if(base.mode & ATTR_BOLD) {
2189 if(base.mode & ATTR_ITALIC)
2191 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2194 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen, &extents);
2195 width = extents.xOff;
2196 XftDrawRect(xw.xft_draw, &dc.xft_col[bg], winx, winy - font->ascent, width, xw.ch);
2197 XftDrawStringUtf8(xw.xft_draw, &dc.xft_col[fg], font->xft_set, winx, winy, (FcChar8 *)s, bytelen);
2199 if(base.mode & ATTR_UNDERLINE) {
2200 XftDrawRect(xw.xft_draw, &dc.xft_col[fg], winx, winy+1,
2207 static int oldx = 0;
2208 static int oldy = 0;
2210 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2212 LIMIT(oldx, 0, term.col-1);
2213 LIMIT(oldy, 0, term.row-1);
2215 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2216 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2218 /* remove the old cursor */
2219 if(term.line[oldy][oldx].state & GLYPH_SET) {
2220 sl = utf8size(term.line[oldy][oldx].c);
2221 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2223 xtermclear(oldx, oldy, oldx, oldy);
2225 /* draw the new one */
2226 if(!(term.c.state & CURSOR_HIDE)) {
2227 if(!(xw.state & WIN_FOCUSED))
2230 if(IS_SET(MODE_REVERSE))
2231 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2234 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2235 oldx = term.c.x, oldy = term.c.y;
2241 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2246 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2251 XSync(xw.dpy, False); /* necessary for a good tput flash */
2252 nanosleep(&tv, NULL);
2257 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2259 drawregion(0, 0, term.col, term.row);
2260 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2264 drawregion(int x1, int y1, int x2, int y2) {
2265 int ic, ib, x, y, ox, sl;
2267 char buf[DRAW_BUF_SIZ];
2268 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2270 if((sel.alt && !alt) || (!sel.alt && alt))
2272 if(!(xw.state & WIN_VISIBLE))
2275 for(y = y1; y < y2; y++) {
2278 xtermclear(0, y, term.col, y);
2280 base = term.line[y][0];
2282 for(x = x1; x < x2; x++) {
2283 new = term.line[y][x];
2284 if(ena_sel && *(new.c) && selected(x, y))
2285 new.mode ^= ATTR_REVERSE;
2286 if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2287 ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2288 xdraws(buf, base, ox, y, ic, ib);
2291 if(new.state & GLYPH_SET) {
2296 sl = utf8size(new.c);
2297 memcpy(buf+ib, new.c, sl);
2303 xdraws(buf, base, ox, y, ic, ib);
2309 expose(XEvent *ev) {
2310 XExposeEvent *e = &ev->xexpose;
2311 if(xw.state & WIN_REDRAW) {
2313 xw.state &= ~WIN_REDRAW;
2318 visibility(XEvent *ev) {
2319 XVisibilityEvent *e = &ev->xvisibility;
2320 if(e->state == VisibilityFullyObscured)
2321 xw.state &= ~WIN_VISIBLE;
2322 else if(!(xw.state & WIN_VISIBLE))
2323 /* need a full redraw for next Expose, not just a buf copy */
2324 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2329 xw.state &= ~WIN_VISIBLE;
2333 xseturgency(int add) {
2334 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2335 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2336 XSetWMHints(xw.dpy, xw.win, h);
2342 if(ev->type == FocusIn) {
2343 xw.state |= WIN_FOCUSED;
2346 xw.state &= ~WIN_FOCUSED;
2350 kmap(KeySym k, uint state) {
2353 for(i = 0; i < LEN(key); i++) {
2354 uint mask = key[i].mask;
2355 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2356 return (char*)key[i].s;
2362 kpress(XEvent *ev) {
2363 XKeyEvent *e = &ev->xkey;
2372 if (IS_SET(MODE_KBDLOCK))
2374 meta = e->state & Mod1Mask;
2375 shift = e->state & ShiftMask;
2376 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2378 /* 1. custom keys from config.h */
2379 if((customkey = kmap(ksym, e->state)))
2380 ttywrite(customkey, strlen(customkey));
2381 /* 2. hardcoded (overrides X lookup) */
2388 /* XXX: shift up/down doesn't work */
2389 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2397 if(IS_SET(MODE_CRLF))
2398 ttywrite("\r\n", 2);
2405 if(meta && len == 1)
2406 ttywrite("\033", 1);
2414 cmessage(XEvent *e) {
2416 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2417 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2418 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2419 xw.state |= WIN_FOCUSED;
2421 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2422 xw.state &= ~WIN_FOCUSED;
2431 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2434 xw.w = e->xconfigure.width;
2435 xw.h = e->xconfigure.height;
2436 col = (xw.w - 2*BORDER) / xw.cw;
2437 row = (xw.h - 2*BORDER) / xw.ch;
2438 if(col == term.col && row == term.row)
2451 int xfd = XConnectionNumber(xw.dpy), i;
2452 struct timeval drawtimeout, *tv = NULL;
2456 FD_SET(cmdfd, &rfd);
2458 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2461 die("select failed: %s\n", SERRNO);
2465 * Stop after a certain number of reads so the user does not
2466 * feel like the system is stuttering.
2468 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2472 * Just wait a bit so it isn't disturbing the
2473 * user and the system is able to write something.
2475 drawtimeout.tv_sec = 0;
2476 drawtimeout.tv_usec = 5;
2483 while(XPending(xw.dpy)) {
2484 XNextEvent(xw.dpy, &ev);
2485 if(XFilterEvent(&ev, xw.win))
2487 if(handler[ev.type])
2488 (handler[ev.type])(&ev);
2497 main(int argc, char *argv[]) {
2498 int i, bitm, xr, yr;
2501 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2504 for(i = 1; i < argc; i++) {
2505 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2507 if(++i < argc) opt_title = argv[i];
2510 if(++i < argc) opt_class = argv[i];
2513 if(++i < argc) opt_embed = argv[i];
2516 if(++i < argc) opt_io = argv[i];
2519 /* eat every remaining arguments */
2520 if(++i < argc) opt_cmd = &argv[i];
2526 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2531 if(bitm & WidthValue)
2533 if(bitm & HeightValue)
2535 if(bitm & XNegative && xw.fx == 0)
2537 if(bitm & XNegative && xw.fy == 0)
2540 if(xw.fh != 0 && xw.fw != 0)
2550 setlocale(LC_CTYPE, "");