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 [-v] [-c class] [-f font] [-g geometry] [-o file]" \
43 " [-t title] [-w windowid] [-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;
373 static char *opt_font = NULL;
376 xmalloc(size_t len) {
377 void *p = malloc(len);
379 die("Out of memory\n");
384 xrealloc(void *p, size_t len) {
385 if((p = realloc(p, len)) == NULL)
386 die("Out of memory\n");
391 xcalloc(size_t nmemb, size_t size) {
392 void *p = calloc(nmemb, size);
394 die("Out of memory\n");
399 smstrcat(char *src, ...)
405 len = slen = strlen(src);
407 va_start(fmtargs, src);
409 v = va_arg(fmtargs, char *);
416 p = ret = xmalloc(len+1);
417 memmove(p, src, slen);
420 va_start(fmtargs, src);
422 v = va_arg(fmtargs, char *);
437 utf8decode(char *s, long *u) {
443 if(~c & B7) { /* 0xxxxxxx */
446 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
447 *u = c&(B4|B3|B2|B1|B0);
449 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
450 *u = c&(B3|B2|B1|B0);
452 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
457 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
459 if((c & (B7|B6)) != B7) /* 10xxxxxx */
462 *u |= c & (B5|B4|B3|B2|B1|B0);
464 if((n == 1 && *u < 0x80) ||
465 (n == 2 && *u < 0x800) ||
466 (n == 3 && *u < 0x10000) ||
467 (*u >= 0xD800 && *u <= 0xDFFF))
476 utf8encode(long *u, char *s) {
484 *sp = uc; /* 0xxxxxxx */
486 } else if(*u < 0x800) {
487 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
489 } else if(uc < 0x10000) {
490 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
492 } else if(uc <= 0x10FFFF) {
493 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
498 for(i=n,++sp; i>0; --i,++sp)
499 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
509 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
510 UTF-8 otherwise return 0 */
512 isfullutf8(char *s, int b) {
520 else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
522 else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
524 ((b == 2) && (*c2&(B7|B6)) == B7)))
526 else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
528 ((b == 2) && (*c2&(B7|B6)) == B7) ||
529 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
541 else if((c&(B7|B6|B5)) == (B7|B6))
543 else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
551 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
552 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
556 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
557 if(sel.xtarget == None)
558 sel.xtarget = XA_STRING;
562 selected(int x, int y) {
563 if(sel.ey == y && sel.by == y) {
564 int bx = MIN(sel.bx, sel.ex);
565 int ex = MAX(sel.bx, sel.ex);
566 return BETWEEN(x, bx, ex);
568 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
569 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
573 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
575 *b = e->xbutton.button;
577 *x = X2COL(e->xbutton.x);
578 *y = Y2ROW(e->xbutton.y);
579 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
580 sel.b.y = MIN(sel.by, sel.ey);
581 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
582 sel.e.y = MAX(sel.by, sel.ey);
586 mousereport(XEvent *e) {
587 int x = X2COL(e->xbutton.x);
588 int y = Y2ROW(e->xbutton.y);
589 int button = e->xbutton.button;
590 int state = e->xbutton.state;
591 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
592 static int ob, ox, oy;
595 if(e->xbutton.type == MotionNotify) {
596 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
600 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
606 if(e->xbutton.type == ButtonPress) {
612 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
613 + (state & Mod4Mask ? 8 : 0)
614 + (state & ControlMask ? 16 : 0);
616 ttywrite(buf, sizeof(buf));
621 if(IS_SET(MODE_MOUSE))
623 else if(e->xbutton.button == Button1) {
626 tsetdirt(sel.b.y, sel.e.y);
630 sel.ex = sel.bx = X2COL(e->xbutton.x);
631 sel.ey = sel.by = Y2ROW(e->xbutton.y);
638 int x, y, bufsize, is_selected = 0;
644 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
645 ptr = str = xmalloc(bufsize);
647 /* append every set & selected glyph to the selection */
648 for(y = 0; y < term.row; y++) {
649 for(x = 0; x < term.col; x++) {
652 Glyph *gp = &term.line[y][x];
654 if(!(is_selected = selected(x, y)))
656 p = (gp->state & GLYPH_SET) ? gp->c : " ";
658 memcpy(ptr, p, size);
661 /* \n at the end of every selected line except for the last one */
662 if(is_selected && y < sel.e.y)
667 sel.alt = IS_SET(MODE_ALTSCREEN);
672 selnotify(XEvent *e) {
673 ulong nitems, ofs, rem;
680 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
681 False, AnyPropertyType, &type, &format,
682 &nitems, &rem, &data)) {
683 fprintf(stderr, "Clipboard allocation failed\n");
686 ttywrite((const char *) data, nitems * format / 8);
688 /* number of 32-bit chunks returned */
689 ofs += nitems * format / 32;
695 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
698 void selclear(XEvent *e) {
702 tsetdirt(sel.b.y, sel.e.y);
706 selrequest(XEvent *e) {
707 XSelectionRequestEvent *xsre;
711 xsre = (XSelectionRequestEvent *) e;
712 xev.type = SelectionNotify;
713 xev.requestor = xsre->requestor;
714 xev.selection = xsre->selection;
715 xev.target = xsre->target;
716 xev.time = xsre->time;
720 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
721 if(xsre->target == xa_targets) {
722 /* respond with the supported type */
723 Atom string = sel.xtarget;
724 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
725 XA_ATOM, 32, PropModeReplace,
726 (uchar *) &string, 1);
727 xev.property = xsre->property;
728 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
729 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
730 xsre->target, 8, PropModeReplace,
731 (uchar *) sel.clip, strlen(sel.clip));
732 xev.property = xsre->property;
735 /* all done, send a notification to the listener */
736 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
737 fprintf(stderr, "Error sending SelectionNotify event\n");
742 /* register the selection for both the clipboard and the primary */
748 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
750 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
751 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
755 brelease(XEvent *e) {
756 if(IS_SET(MODE_MOUSE)) {
760 if(e->xbutton.button == Button2)
762 else if(e->xbutton.button == Button1) {
764 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
765 term.dirty[sel.ey] = 1;
766 if(sel.bx == sel.ex && sel.by == sel.ey) {
769 gettimeofday(&now, NULL);
771 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
772 /* triple click on the line */
773 sel.b.x = sel.bx = 0;
774 sel.e.x = sel.ex = term.col;
775 sel.b.y = sel.e.y = sel.ey;
777 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
778 /* double click to select word */
780 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
781 term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
783 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
784 term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
786 sel.b.y = sel.e.y = sel.ey;
792 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
793 gettimeofday(&sel.tclick1, NULL);
798 if(IS_SET(MODE_MOUSE)) {
803 int oldey = sel.ey, oldex = sel.ex;
804 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
806 if(oldey != sel.ey || oldex != sel.ex) {
807 int starty = MIN(oldey, sel.ey);
808 int endy = MAX(oldey, sel.ey);
809 tsetdirt(starty, endy);
815 die(const char *errstr, ...) {
818 va_start(ap, errstr);
819 vfprintf(stderr, errstr, ap);
827 char *envshell = getenv("SHELL");
833 signal(SIGCHLD, SIG_DFL);
834 signal(SIGHUP, SIG_DFL);
835 signal(SIGINT, SIG_DFL);
836 signal(SIGQUIT, SIG_DFL);
837 signal(SIGTERM, SIG_DFL);
838 signal(SIGALRM, SIG_DFL);
840 DEFAULT(envshell, SHELL);
841 putenv("TERM="TNAME);
842 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
843 execvp(args[0], args);
850 if(waitpid(pid, &stat, 0) < 0)
851 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
853 exit(WEXITSTATUS(stat));
862 /* seems to work fine on linux, openbsd and freebsd */
863 struct winsize w = {term.row, term.col, 0, 0};
864 if(openpty(&m, &s, NULL, NULL, &w) < 0)
865 die("openpty failed: %s\n", SERRNO);
867 switch(pid = fork()) {
869 die("fork failed\n");
872 setsid(); /* create a new process group */
873 dup2(s, STDIN_FILENO);
874 dup2(s, STDOUT_FILENO);
875 dup2(s, STDERR_FILENO);
876 if(ioctl(s, TIOCSCTTY, NULL) < 0)
877 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
885 signal(SIGCHLD, sigchld);
887 if(!strcmp(opt_io, "-")) {
888 iofd = STDOUT_FILENO;
890 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
891 fprintf(stderr, "Error opening %s:%s\n",
892 opt_io, strerror(errno));
902 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
904 fprintf(stderr, "\n");
909 static char buf[BUFSIZ];
910 static int buflen = 0;
913 int charsize; /* size of utf8 char in bytes */
917 /* append read bytes to unprocessed bytes */
918 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
919 die("Couldn't read from shell: %s\n", SERRNO);
921 /* process every complete utf8 char */
924 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
925 charsize = utf8decode(ptr, &utf8c);
926 utf8encode(&utf8c, s);
932 /* keep any uncomplete utf8 char for the next call */
933 memmove(buf, ptr, buflen);
937 ttywrite(const char *s, size_t n) {
938 if(write(cmdfd, s, n) == -1)
939 die("write error on tty: %s\n", SERRNO);
950 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
951 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
955 tsetdirt(int top, int bot)
959 LIMIT(top, 0, term.row-1);
960 LIMIT(bot, 0, term.row-1);
962 for(i = top; i <= bot; i++)
969 tsetdirt(0, term.row-1);
976 if(mode == CURSOR_SAVE)
978 else if(mode == CURSOR_LOAD)
979 term.c = c, tmoveto(c.x, c.y);
989 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
991 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
992 for(i = TAB; i < term.col; i += TAB)
994 term.top = 0, term.bot = term.row - 1;
995 term.mode = MODE_WRAP;
997 tclearregion(0, 0, term.col-1, term.row-1);
1001 tnew(int col, int row) {
1002 /* set screen size */
1003 term.row = row, term.col = col;
1004 term.line = xmalloc(term.row * sizeof(Line));
1005 term.alt = xmalloc(term.row * sizeof(Line));
1006 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1007 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1009 for(row = 0; row < term.row; row++) {
1010 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1011 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1012 term.dirty[row] = 0;
1014 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1021 Line* tmp = term.line;
1022 term.line = term.alt;
1024 term.mode ^= MODE_ALTSCREEN;
1029 tscrolldown(int orig, int n) {
1033 LIMIT(n, 0, term.bot-orig+1);
1035 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1037 for(i = term.bot; i >= orig+n; i--) {
1038 temp = term.line[i];
1039 term.line[i] = term.line[i-n];
1040 term.line[i-n] = temp;
1043 term.dirty[i-n] = 1;
1050 tscrollup(int orig, int n) {
1053 LIMIT(n, 0, term.bot-orig+1);
1055 tclearregion(0, orig, term.col-1, orig+n-1);
1057 for(i = orig; i <= term.bot-n; i++) {
1058 temp = term.line[i];
1059 term.line[i] = term.line[i+n];
1060 term.line[i+n] = temp;
1063 term.dirty[i+n] = 1;
1066 selscroll(orig, -n);
1070 selscroll(int orig, int n) {
1074 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1075 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1079 if(sel.by < term.top) {
1083 if(sel.ey > term.bot) {
1087 sel.b.y = sel.by, sel.b.x = sel.bx;
1088 sel.e.y = sel.ey, sel.e.x = sel.ex;
1093 tnewline(int first_col) {
1096 tscrollup(term.top, 1);
1099 tmoveto(first_col ? 0 : term.c.x, y);
1104 /* int noarg = 1; */
1105 char *p = csiescseq.buf;
1109 csiescseq.priv = 1, p++;
1111 while(p < csiescseq.buf+csiescseq.len) {
1112 while(isdigit(*p)) {
1113 csiescseq.arg[csiescseq.narg] *= 10;
1114 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1116 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1117 csiescseq.narg++, p++;
1119 csiescseq.mode = *p;
1127 tmoveto(int x, int y) {
1128 LIMIT(x, 0, term.col-1);
1129 LIMIT(y, 0, term.row-1);
1130 term.c.state &= ~CURSOR_WRAPNEXT;
1138 * The table is proudly stolen from rxvt.
1140 if(term.c.attr.mode & ATTR_GFX) {
1141 char *vt100_0[62] = { /* 0x41 - 0x7e */
1142 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1143 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1144 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1145 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1146 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1147 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1148 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1149 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1152 if(c[0] >= 0x41 && c[0] <= 0x7e
1153 && vt100_0[c[0] - 0x41]) {
1154 c = vt100_0[c[0] - 0x41];
1158 term.dirty[term.c.y] = 1;
1159 term.line[term.c.y][term.c.x] = term.c.attr;
1160 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1161 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1165 tclearregion(int x1, int y1, int x2, int y2) {
1169 temp = x1, x1 = x2, x2 = temp;
1171 temp = y1, y1 = y2, y2 = temp;
1173 LIMIT(x1, 0, term.col-1);
1174 LIMIT(x2, 0, term.col-1);
1175 LIMIT(y1, 0, term.row-1);
1176 LIMIT(y2, 0, term.row-1);
1178 for(y = y1; y <= y2; y++) {
1180 for(x = x1; x <= x2; x++)
1181 term.line[y][x].state = 0;
1186 tdeletechar(int n) {
1187 int src = term.c.x + n;
1189 int size = term.col - src;
1191 term.dirty[term.c.y] = 1;
1193 if(src >= term.col) {
1194 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1197 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1198 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1202 tinsertblank(int n) {
1205 int size = term.col - dst;
1207 term.dirty[term.c.y] = 1;
1209 if(dst >= term.col) {
1210 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1213 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1214 tclearregion(src, term.c.y, dst - 1, term.c.y);
1218 tinsertblankline(int n) {
1219 if(term.c.y < term.top || term.c.y > term.bot)
1222 tscrolldown(term.c.y, n);
1226 tdeleteline(int n) {
1227 if(term.c.y < term.top || term.c.y > term.bot)
1230 tscrollup(term.c.y, n);
1234 tsetattr(int *attr, int l) {
1237 for(i = 0; i < l; i++) {
1240 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1241 | ATTR_ITALIC | ATTR_BLINK);
1242 term.c.attr.fg = DefaultFG;
1243 term.c.attr.bg = DefaultBG;
1246 term.c.attr.mode |= ATTR_BOLD;
1248 case 3: /* enter standout (highlight) */
1249 term.c.attr.mode |= ATTR_ITALIC;
1252 term.c.attr.mode |= ATTR_UNDERLINE;
1255 term.c.attr.mode |= ATTR_BLINK;
1258 term.c.attr.mode |= ATTR_REVERSE;
1262 term.c.attr.mode &= ~ATTR_BOLD;
1264 case 23: /* leave standout (highlight) mode */
1265 term.c.attr.mode &= ~ATTR_ITALIC;
1268 term.c.attr.mode &= ~ATTR_UNDERLINE;
1271 term.c.attr.mode &= ~ATTR_BLINK;
1274 term.c.attr.mode &= ~ATTR_REVERSE;
1277 if(i + 2 < l && attr[i + 1] == 5) {
1279 if(BETWEEN(attr[i], 0, 255))
1280 term.c.attr.fg = attr[i];
1282 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1285 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1288 term.c.attr.fg = DefaultFG;
1291 if(i + 2 < l && attr[i + 1] == 5) {
1293 if(BETWEEN(attr[i], 0, 255))
1294 term.c.attr.bg = attr[i];
1296 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1299 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1302 term.c.attr.bg = DefaultBG;
1305 if(BETWEEN(attr[i], 30, 37))
1306 term.c.attr.fg = attr[i] - 30;
1307 else if(BETWEEN(attr[i], 40, 47))
1308 term.c.attr.bg = attr[i] - 40;
1309 else if(BETWEEN(attr[i], 90, 97))
1310 term.c.attr.fg = attr[i] - 90 + 8;
1311 else if(BETWEEN(attr[i], 100, 107))
1312 term.c.attr.bg = attr[i] - 100 + 8;
1314 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1321 tsetscroll(int t, int b) {
1324 LIMIT(t, 0, term.row-1);
1325 LIMIT(b, 0, term.row-1);
1335 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1338 tsetmode(bool priv, bool set, int *args, int narg) {
1341 for(lim = args + narg; args < lim; ++args) {
1345 case 1: /* DECCKM -- Cursor key */
1346 MODBIT(term.mode, set, MODE_APPKEYPAD);
1348 case 5: /* DECSCNM -- Reverve video */
1350 MODBIT(term.mode, set, MODE_REVERSE);
1351 if(mode != term.mode)
1354 case 6: /* XXX: DECOM -- Origin */
1356 case 7: /* DECAWM -- Auto wrap */
1357 MODBIT(term.mode, set, MODE_WRAP);
1359 case 8: /* XXX: DECARM -- Auto repeat */
1361 case 0: /* Error (IGNORED) */
1362 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1365 MODBIT(term.c.state, !set, CURSOR_HIDE);
1367 case 1000: /* 1000,1002: enable xterm mouse report */
1368 MODBIT(term.mode, set, MODE_MOUSEBTN);
1371 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1373 case 1049: /* = 1047 and 1048 */
1376 if(IS_SET(MODE_ALTSCREEN))
1377 tclearregion(0, 0, term.col-1, term.row-1);
1378 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1379 (!set && IS_SET(MODE_ALTSCREEN))) {
1386 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1389 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1390 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1391 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1392 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1393 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1394 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1396 "erresc: unknown private set/reset mode %d\n",
1402 case 0: /* Error (IGNORED) */
1404 case 2: /* KAM -- keyboard action */
1405 MODBIT(term.mode, set, MODE_KBDLOCK);
1407 case 4: /* IRM -- Insertion-replacement */
1408 MODBIT(term.mode, set, MODE_INSERT);
1410 case 12: /* XXX: SRM -- Send/Receive */
1412 case 20: /* LNM -- Linefeed/new line */
1413 MODBIT(term.mode, set, MODE_CRLF);
1417 "erresc: unknown set/reset mode %d\n",
1429 switch(csiescseq.mode) {
1432 fprintf(stderr, "erresc: unknown csi ");
1436 case '@': /* ICH -- Insert <n> blank char */
1437 DEFAULT(csiescseq.arg[0], 1);
1438 tinsertblank(csiescseq.arg[0]);
1440 case 'A': /* CUU -- Cursor <n> Up */
1442 DEFAULT(csiescseq.arg[0], 1);
1443 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1445 case 'B': /* CUD -- Cursor <n> Down */
1446 DEFAULT(csiescseq.arg[0], 1);
1447 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1449 case 'C': /* CUF -- Cursor <n> Forward */
1451 DEFAULT(csiescseq.arg[0], 1);
1452 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1454 case 'D': /* CUB -- Cursor <n> Backward */
1455 DEFAULT(csiescseq.arg[0], 1);
1456 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1458 case 'E': /* CNL -- Cursor <n> Down and first col */
1459 DEFAULT(csiescseq.arg[0], 1);
1460 tmoveto(0, term.c.y+csiescseq.arg[0]);
1462 case 'F': /* CPL -- Cursor <n> Up and first col */
1463 DEFAULT(csiescseq.arg[0], 1);
1464 tmoveto(0, term.c.y-csiescseq.arg[0]);
1466 case 'g': /* TBC -- Tabulation clear */
1467 switch (csiescseq.arg[0]) {
1468 case 0: /* clear current tab stop */
1469 term.tabs[term.c.x] = 0;
1471 case 3: /* clear all the tabs */
1472 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1478 case 'G': /* CHA -- Move to <col> */
1480 DEFAULT(csiescseq.arg[0], 1);
1481 tmoveto(csiescseq.arg[0]-1, term.c.y);
1483 case 'H': /* CUP -- Move to <row> <col> */
1485 DEFAULT(csiescseq.arg[0], 1);
1486 DEFAULT(csiescseq.arg[1], 1);
1487 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1489 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1490 DEFAULT(csiescseq.arg[0], 1);
1491 while(csiescseq.arg[0]--)
1494 case 'J': /* ED -- Clear screen */
1496 switch(csiescseq.arg[0]) {
1498 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1499 if(term.c.y < term.row-1)
1500 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1504 tclearregion(0, 0, term.col-1, term.c.y-1);
1505 tclearregion(0, term.c.y, term.c.x, term.c.y);
1508 tclearregion(0, 0, term.col-1, term.row-1);
1514 case 'K': /* EL -- Clear line */
1515 switch(csiescseq.arg[0]) {
1517 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1520 tclearregion(0, term.c.y, term.c.x, term.c.y);
1523 tclearregion(0, term.c.y, term.col-1, term.c.y);
1527 case 'S': /* SU -- Scroll <n> line up */
1528 DEFAULT(csiescseq.arg[0], 1);
1529 tscrollup(term.top, csiescseq.arg[0]);
1531 case 'T': /* SD -- Scroll <n> line down */
1532 DEFAULT(csiescseq.arg[0], 1);
1533 tscrolldown(term.top, csiescseq.arg[0]);
1535 case 'L': /* IL -- Insert <n> blank lines */
1536 DEFAULT(csiescseq.arg[0], 1);
1537 tinsertblankline(csiescseq.arg[0]);
1539 case 'l': /* RM -- Reset Mode */
1540 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1542 case 'M': /* DL -- Delete <n> lines */
1543 DEFAULT(csiescseq.arg[0], 1);
1544 tdeleteline(csiescseq.arg[0]);
1546 case 'X': /* ECH -- Erase <n> char */
1547 DEFAULT(csiescseq.arg[0], 1);
1548 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1550 case 'P': /* DCH -- Delete <n> char */
1551 DEFAULT(csiescseq.arg[0], 1);
1552 tdeletechar(csiescseq.arg[0]);
1554 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1555 DEFAULT(csiescseq.arg[0], 1);
1556 while(csiescseq.arg[0]--)
1559 case 'd': /* VPA -- Move to <row> */
1560 DEFAULT(csiescseq.arg[0], 1);
1561 tmoveto(term.c.x, csiescseq.arg[0]-1);
1563 case 'h': /* SM -- Set terminal mode */
1564 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1566 case 'm': /* SGR -- Terminal attribute (color) */
1567 tsetattr(csiescseq.arg, csiescseq.narg);
1569 case 'r': /* DECSTBM -- Set Scrolling Region */
1573 DEFAULT(csiescseq.arg[0], 1);
1574 DEFAULT(csiescseq.arg[1], term.row);
1575 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1579 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1580 tcursor(CURSOR_SAVE);
1582 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1583 tcursor(CURSOR_LOAD);
1592 for(i = 0; i < csiescseq.len; i++) {
1593 uint c = csiescseq.buf[i] & 0xff;
1594 if(isprint(c)) putchar(c);
1595 else if(c == '\n') printf("(\\n)");
1596 else if(c == '\r') printf("(\\r)");
1597 else if(c == 0x1b) printf("(\\e)");
1598 else printf("(%02x)", c);
1605 memset(&csiescseq, 0, sizeof(csiescseq));
1613 * TODO: make this being useful in case of color palette change.
1619 switch(strescseq.type) {
1620 case ']': /* OSC -- Operating System Command */
1626 * TODO: Handle special chars in string, like umlauts.
1629 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1633 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1635 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1638 fprintf(stderr, "erresc: unknown str ");
1643 case 'k': /* old title set compatibility */
1644 XStoreName(xw.dpy, xw.win, strescseq.buf);
1646 case 'P': /* DSC -- Device Control String */
1647 case '_': /* APC -- Application Program Command */
1648 case '^': /* PM -- Privacy Message */
1650 fprintf(stderr, "erresc: unknown str ");
1660 * TODO: Implement parsing like for CSI when required.
1661 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1669 printf("ESC%c", strescseq.type);
1670 for(i = 0; i < strescseq.len; i++) {
1671 uint c = strescseq.buf[i] & 0xff;
1672 if(isprint(c)) putchar(c);
1673 else if(c == '\n') printf("(\\n)");
1674 else if(c == '\r') printf("(\\r)");
1675 else if(c == 0x1b) printf("(\\e)");
1676 else printf("(%02x)", c);
1683 memset(&strescseq, 0, sizeof(strescseq));
1687 tputtab(bool forward) {
1693 for(++x; x < term.col && !term.tabs[x]; ++x)
1698 for(--x; x > 0 && !term.tabs[x]; --x)
1701 tmoveto(x, term.c.y);
1705 tputc(char *c, int len) {
1709 write(iofd, c, len);
1716 tmoveto(term.c.x-1, term.c.y);
1719 tmoveto(0, term.c.y);
1724 /* go to first col if the mode is set */
1725 tnewline(IS_SET(MODE_CRLF));
1728 if(term.esc & ESC_STR)
1731 if(!(xw.state & WIN_FOCUSED))
1736 term.esc = ESC_START;
1740 if(term.esc & ESC_START) {
1741 if(term.esc & ESC_CSI) {
1742 csiescseq.buf[csiescseq.len++] = ascii;
1743 if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1745 csiparse(), csihandle();
1747 } else if(term.esc & ESC_STR) {
1750 term.esc = ESC_START | ESC_STR_END;
1752 case '\a': /* backwards compatibility to xterm */
1757 strescseq.buf[strescseq.len++] = ascii;
1758 if(strescseq.len+1 >= STR_BUF_SIZ) {
1763 } else if(term.esc & ESC_STR_END) {
1767 } else if(term.esc & ESC_ALTCHARSET) {
1769 case '0': /* Line drawing set */
1770 term.c.attr.mode |= ATTR_GFX;
1772 case 'B': /* USASCII */
1773 term.c.attr.mode &= ~ATTR_GFX;
1775 case 'A': /* UK (IGNORED) */
1776 case '<': /* multinational charset (IGNORED) */
1777 case '5': /* Finnish (IGNORED) */
1778 case 'C': /* Finnish (IGNORED) */
1779 case 'K': /* German (IGNORED) */
1782 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1788 term.esc |= ESC_CSI;
1790 case 'P': /* DCS -- Device Control String */
1791 case '_': /* APC -- Application Program Command */
1792 case '^': /* PM -- Privacy Message */
1793 case ']': /* OSC -- Operating System Command */
1794 case 'k': /* old title set compatibility */
1796 strescseq.type = ascii;
1797 term.esc |= ESC_STR;
1799 case '(': /* set primary charset G0 */
1800 term.esc |= ESC_ALTCHARSET;
1802 case ')': /* set secondary charset G1 (IGNORED) */
1803 case '*': /* set tertiary charset G2 (IGNORED) */
1804 case '+': /* set quaternary charset G3 (IGNORED) */
1807 case 'D': /* IND -- Linefeed */
1808 if(term.c.y == term.bot)
1809 tscrollup(term.top, 1);
1811 tmoveto(term.c.x, term.c.y+1);
1814 case 'E': /* NEL -- Next line */
1815 tnewline(1); /* always go to first col */
1818 case 'H': /* HTS -- Horizontal tab stop */
1819 term.tabs[term.c.x] = 1;
1822 case 'M': /* RI -- Reverse index */
1823 if(term.c.y == term.top)
1824 tscrolldown(term.top, 1);
1826 tmoveto(term.c.x, term.c.y-1);
1829 case 'c': /* RIS -- Reset to inital state */
1835 case '=': /* DECPAM -- Application keypad */
1836 term.mode |= MODE_APPKEYPAD;
1839 case '>': /* DECPNM -- Normal keypad */
1840 term.mode &= ~MODE_APPKEYPAD;
1843 case '7': /* DECSC -- Save Cursor */
1844 tcursor(CURSOR_SAVE);
1847 case '8': /* DECRC -- Restore Cursor */
1848 tcursor(CURSOR_LOAD);
1851 case '\\': /* ST -- Stop */
1855 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1856 (uchar) ascii, isprint(ascii)?ascii:'.');
1861 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1863 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1864 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1865 tnewline(1); /* always go to first col */
1867 if(term.c.x+1 < term.col)
1868 tmoveto(term.c.x+1, term.c.y);
1870 term.c.state |= CURSOR_WRAPNEXT;
1876 tresize(int col, int row) {
1878 int minrow = MIN(row, term.row);
1879 int mincol = MIN(col, term.col);
1880 int slide = term.c.y - row + 1;
1882 if(col < 1 || row < 1)
1885 /* free unneeded rows */
1888 /* slide screen to keep cursor where we expect it -
1889 * tscrollup would work here, but we can optimize to
1890 * memmove because we're freeing the earlier lines */
1891 for(/* i = 0 */; i < slide; i++) {
1895 memmove(term.line, term.line + slide, row * sizeof(Line));
1896 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1898 for(i += row; i < term.row; i++) {
1903 /* resize to new height */
1904 term.line = xrealloc(term.line, row * sizeof(Line));
1905 term.alt = xrealloc(term.alt, row * sizeof(Line));
1906 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1907 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1909 /* resize each row to new width, zero-pad if needed */
1910 for(i = 0; i < minrow; i++) {
1912 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1913 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
1914 for(x = mincol; x < col; x++) {
1915 term.line[i][x].state = 0;
1916 term.alt[i][x].state = 0;
1920 /* allocate any new rows */
1921 for(/* i == minrow */; i < row; i++) {
1923 term.line[i] = xcalloc(col, sizeof(Glyph));
1924 term.alt [i] = xcalloc(col, sizeof(Glyph));
1926 if(col > term.col) {
1927 bool *bp = term.tabs + term.col;
1929 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1930 while(--bp > term.tabs && !*bp)
1932 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1935 /* update terminal size */
1936 term.col = col, term.row = row;
1937 /* make use of the LIMIT in tmoveto */
1938 tmoveto(term.c.x, term.c.y);
1939 /* reset scrolling region */
1940 tsetscroll(0, row-1);
1946 xresize(int col, int row) {
1947 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
1948 xw.th = MAX(1, 2*BORDER + row * xw.ch);
1950 XftDrawChange(xw.xft_draw, xw.buf);
1956 XRenderColor xft_color = { .alpha = 0 };
1958 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1959 for(i = 0; i < LEN(colorname); i++) {
1962 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
1963 die("Could not allocate color '%s'\n", colorname[i]);
1967 /* load colors [16-255] ; same colors as xterm */
1968 for(i = 16, r = 0; r < 6; r++)
1969 for(g = 0; g < 6; g++)
1970 for(b = 0; b < 6; b++) {
1971 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1972 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1973 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1974 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1975 die("Could not allocate color %d\n", i);
1980 for(r = 0; r < 24; r++, i++) {
1981 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
1982 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1983 dc.xft_col[i] = dc.xft_col[256];
1984 fprintf(stderr, "Could not allocate color %d\n", i);
1990 xtermclear(int col1, int row1, int col2, int row2) {
1991 XftDrawRect(xw.xft_draw,
1992 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
1993 BORDER + col1 * xw.cw,
1994 BORDER + row1 * xw.ch,
1995 (col2-col1+1) * xw.cw,
1996 (row2-row1+1) * xw.ch);
2000 * Absolute coordinates.
2003 xclear(int x1, int y1, int x2, int y2) {
2004 XftDrawRect(xw.xft_draw,
2005 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2006 x1, y1, x2-x1, y2-y1);
2010 xclearborders(void) {
2011 /* top and left border */
2012 xclear(0, 0, BORDER, xw.h);
2013 xclear(0, 0, xw.w, BORDER);
2015 /* lower and right border */
2016 xclear(BORDER, xw.th - 1, xw.w, xw.h);
2017 /* Will just draw what hasn't been drawn by the previous call. */
2018 xclear(xw.tw - 1, BORDER, xw.w, xw.h - xw.th - 2);
2023 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2024 XWMHints wm = {.flags = InputHint, .input = 1};
2025 XSizeHints *sizeh = NULL;
2027 sizeh = XAllocSizeHints();
2028 if(xw.isfixed == False) {
2029 sizeh->flags = PSize | PResizeInc | PBaseSize;
2030 sizeh->height = xw.h;
2031 sizeh->width = xw.w;
2032 sizeh->height_inc = xw.ch;
2033 sizeh->width_inc = xw.cw;
2034 sizeh->base_height = 2*BORDER;
2035 sizeh->base_width = 2*BORDER;
2037 sizeh->flags = PMaxSize | PMinSize;
2038 sizeh->min_width = sizeh->max_width = xw.fw;
2039 sizeh->min_height = sizeh->max_height = xw.fh;
2042 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2047 xinitfont(Font *f, char *fontstr) {
2048 f->xft_set = XftFontOpenName(xw.dpy, xw.scr, fontstr);
2051 die("st: can't open font %s.\n", fontstr);
2053 f->ascent = f->xft_set->ascent;
2054 f->descent = f->xft_set->descent;
2056 f->rbearing = f->xft_set->max_advance_width;
2060 initfonts(char *fontstr) {
2063 xinitfont(&dc.font, fontstr);
2065 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2066 xinitfont(&dc.bfont, fstr);
2069 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2070 xinitfont(&dc.ifont, fstr);
2073 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2074 xinitfont(&dc.ibfont, fstr);
2080 XSetWindowAttributes attrs;
2083 int sw, sh, major, minor;
2085 if(!(xw.dpy = XOpenDisplay(NULL)))
2086 die("Can't open display\n");
2087 xw.scr = XDefaultScreen(xw.dpy);
2088 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2091 initfonts((opt_font != NULL)? opt_font : FONT);
2093 /* XXX: Assuming same size for bold font */
2094 xw.cw = dc.font.rbearing - dc.font.lbearing;
2095 xw.ch = dc.font.ascent + dc.font.descent;
2098 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2101 /* adjust fixed window geometry */
2103 sw = DisplayWidth(xw.dpy, xw.scr);
2104 sh = DisplayHeight(xw.dpy, xw.scr);
2106 xw.fx = sw + xw.fx - xw.fw - 1;
2108 xw.fy = sh + xw.fy - xw.fh - 1;
2113 /* window - default size */
2114 xw.h = 2*BORDER + term.row * xw.ch;
2115 xw.w = 2*BORDER + term.col * xw.cw;
2120 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2121 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2122 attrs.bit_gravity = NorthWestGravity;
2123 attrs.event_mask = FocusChangeMask | KeyPressMask
2124 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2125 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2126 attrs.colormap = xw.cmap;
2128 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2129 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2130 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2132 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2136 /* double buffering */
2137 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2138 die("Xdbe extension is not present\n");
2139 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2141 /* Xft rendering context */
2142 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2145 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2146 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2147 | XIMStatusNothing, XNClientWindow, xw.win,
2148 XNFocusWindow, xw.win, NULL);
2150 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2152 /* white cursor, black outline */
2153 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2154 XDefineCursor(xw.dpy, xw.win, cursor);
2155 XRecolorCursor(xw.dpy, cursor,
2156 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2157 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2159 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2162 XMapWindow(xw.dpy, xw.win);
2168 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2169 int fg = base.fg, bg = base.bg, temp;
2170 int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
2171 Font *font = &dc.font;
2174 /* only switch default fg/bg if term is in RV mode */
2175 if(IS_SET(MODE_REVERSE)) {
2182 if(base.mode & ATTR_REVERSE)
2183 temp = fg, fg = bg, bg = temp;
2185 if(base.mode & ATTR_BOLD)
2188 if(base.mode & ATTR_ITALIC)
2190 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2193 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen, &extents);
2194 width = extents.xOff;
2195 XftDrawRect(xw.xft_draw, &dc.xft_col[bg], winx, winy - font->ascent, width, xw.ch);
2196 XftDrawStringUtf8(xw.xft_draw, &dc.xft_col[fg], font->xft_set, winx, winy, (FcChar8 *)s, bytelen);
2198 if(base.mode & ATTR_UNDERLINE) {
2199 XftDrawRect(xw.xft_draw, &dc.xft_col[fg], winx, winy+1,
2206 static int oldx = 0;
2207 static int oldy = 0;
2209 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2211 LIMIT(oldx, 0, term.col-1);
2212 LIMIT(oldy, 0, term.row-1);
2214 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2215 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2217 /* remove the old cursor */
2218 if(term.line[oldy][oldx].state & GLYPH_SET) {
2219 sl = utf8size(term.line[oldy][oldx].c);
2220 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2222 xtermclear(oldx, oldy, oldx, oldy);
2224 /* draw the new one */
2225 if(!(term.c.state & CURSOR_HIDE)) {
2226 if(!(xw.state & WIN_FOCUSED))
2229 if(IS_SET(MODE_REVERSE))
2230 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2233 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2234 oldx = term.c.x, oldy = term.c.y;
2240 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2245 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2250 XSync(xw.dpy, False); /* necessary for a good tput flash */
2251 nanosleep(&tv, NULL);
2256 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2258 drawregion(0, 0, term.col, term.row);
2259 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2263 drawregion(int x1, int y1, int x2, int y2) {
2264 int ic, ib, x, y, ox, sl;
2266 char buf[DRAW_BUF_SIZ];
2267 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2269 if((sel.alt && !alt) || (!sel.alt && alt))
2271 if(!(xw.state & WIN_VISIBLE))
2274 for(y = y1; y < y2; y++) {
2277 xtermclear(0, y, term.col, y);
2279 base = term.line[y][0];
2281 for(x = x1; x < x2; x++) {
2282 new = term.line[y][x];
2283 if(ena_sel && *(new.c) && selected(x, y))
2284 new.mode ^= ATTR_REVERSE;
2285 if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2286 ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2287 xdraws(buf, base, ox, y, ic, ib);
2290 if(new.state & GLYPH_SET) {
2295 sl = utf8size(new.c);
2296 memcpy(buf+ib, new.c, sl);
2302 xdraws(buf, base, ox, y, ic, ib);
2308 expose(XEvent *ev) {
2309 XExposeEvent *e = &ev->xexpose;
2310 if(xw.state & WIN_REDRAW) {
2312 xw.state &= ~WIN_REDRAW;
2317 visibility(XEvent *ev) {
2318 XVisibilityEvent *e = &ev->xvisibility;
2319 if(e->state == VisibilityFullyObscured)
2320 xw.state &= ~WIN_VISIBLE;
2321 else if(!(xw.state & WIN_VISIBLE))
2322 /* need a full redraw for next Expose, not just a buf copy */
2323 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2328 xw.state &= ~WIN_VISIBLE;
2332 xseturgency(int add) {
2333 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2334 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2335 XSetWMHints(xw.dpy, xw.win, h);
2341 if(ev->type == FocusIn) {
2342 xw.state |= WIN_FOCUSED;
2345 xw.state &= ~WIN_FOCUSED;
2349 kmap(KeySym k, uint state) {
2352 for(i = 0; i < LEN(key); i++) {
2353 uint mask = key[i].mask;
2354 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2355 return (char*)key[i].s;
2361 kpress(XEvent *ev) {
2362 XKeyEvent *e = &ev->xkey;
2371 if (IS_SET(MODE_KBDLOCK))
2373 meta = e->state & Mod1Mask;
2374 shift = e->state & ShiftMask;
2375 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2377 /* 1. custom keys from config.h */
2378 if((customkey = kmap(ksym, e->state)))
2379 ttywrite(customkey, strlen(customkey));
2380 /* 2. hardcoded (overrides X lookup) */
2387 /* XXX: shift up/down doesn't work */
2388 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2396 if(IS_SET(MODE_CRLF))
2397 ttywrite("\r\n", 2);
2404 if(meta && len == 1)
2405 ttywrite("\033", 1);
2413 cmessage(XEvent *e) {
2415 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2416 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2417 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2418 xw.state |= WIN_FOCUSED;
2420 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2421 xw.state &= ~WIN_FOCUSED;
2430 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2433 xw.w = e->xconfigure.width;
2434 xw.h = e->xconfigure.height;
2435 col = (xw.w - 2*BORDER) / xw.cw;
2436 row = (xw.h - 2*BORDER) / xw.ch;
2437 if(col == term.col && row == term.row)
2450 int xfd = XConnectionNumber(xw.dpy), i;
2451 struct timeval drawtimeout, *tv = NULL;
2455 FD_SET(cmdfd, &rfd);
2457 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2460 die("select failed: %s\n", SERRNO);
2464 * Stop after a certain number of reads so the user does not
2465 * feel like the system is stuttering.
2467 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2471 * Just wait a bit so it isn't disturbing the
2472 * user and the system is able to write something.
2474 drawtimeout.tv_sec = 0;
2475 drawtimeout.tv_usec = 5;
2482 while(XPending(xw.dpy)) {
2483 XNextEvent(xw.dpy, &ev);
2484 if(XFilterEvent(&ev, xw.win))
2486 if(handler[ev.type])
2487 (handler[ev.type])(&ev);
2496 main(int argc, char *argv[]) {
2497 int i, bitm, xr, yr;
2500 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2503 for(i = 1; i < argc; i++) {
2504 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2507 opt_class = argv[i];
2510 /* eat every remaining arguments */
2522 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2527 if(bitm & WidthValue)
2529 if(bitm & HeightValue)
2531 if(bitm & XNegative && xw.fx == 0)
2533 if(bitm & XNegative && xw.fy == 0)
2536 if(xw.fh != 0 && xw.fw != 0)
2545 opt_title = argv[i];
2552 opt_embed = argv[i];
2558 setlocale(LC_CTYPE, "");