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>
29 #include <fontconfig/fontconfig.h>
35 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
37 #elif defined(__FreeBSD__) || defined(__DragonFly__)
42 "st " VERSION " (c) 2010-2012 st engineers\n" \
43 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
44 " [-t title] [-w windowid] [-e command ...]\n"
47 #define XEMBED_FOCUS_IN 4
48 #define XEMBED_FOCUS_OUT 5
51 #define ESC_BUF_SIZ 256
52 #define ESC_ARG_SIZ 16
53 #define STR_BUF_SIZ 256
54 #define STR_ARG_SIZ 16
55 #define DRAW_BUF_SIZ 20*1024
57 #define XK_NO_MOD UINT_MAX
60 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
62 #define SERRNO strerror(errno)
63 #define MIN(a, b) ((a) < (b) ? (a) : (b))
64 #define MAX(a, b) ((a) < (b) ? (b) : (a))
65 #define LEN(a) (sizeof(a) / sizeof(a[0]))
66 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
67 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
68 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
69 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
70 #define IS_SET(flag) (term.mode & (flag))
71 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
72 #define X2COL(x) (((x) - BORDER)/xw.cw)
73 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
75 enum glyph_attribute {
85 enum cursor_movement {
112 MODE_MOUSEMOTION = 64,
121 ESC_STR = 4, /* DSC, OSC, PM, APC */
123 ESC_STR_END = 16, /* a final string was encountered */
134 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
136 typedef unsigned char uchar;
137 typedef unsigned int uint;
138 typedef unsigned long ulong;
139 typedef unsigned short ushort;
142 char c[UTF_SIZ]; /* character code */
143 uchar mode; /* attribute flags */
144 ushort fg; /* foreground */
145 ushort bg; /* background */
146 uchar state; /* state flags */
152 Glyph attr; /* current char attributes */
158 /* CSI Escape sequence structs */
159 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
161 char buf[ESC_BUF_SIZ]; /* raw string */
162 int len; /* raw string length */
164 int arg[ESC_ARG_SIZ];
165 int narg; /* nb of args */
169 /* STR Escape sequence structs */
170 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
172 char type; /* ESC type ... */
173 char buf[STR_BUF_SIZ]; /* raw string */
174 int len; /* raw string length */
175 char *args[STR_ARG_SIZ];
176 int narg; /* nb of args */
179 /* Internal representation of the screen */
181 int row; /* nb row */
182 int col; /* nb col */
183 Line *line; /* screen */
184 Line *alt; /* alternate screen */
185 bool *dirty; /* dirtyness of lines */
186 TCursor c; /* cursor */
187 int top; /* top scroll limit */
188 int bot; /* bottom scroll limit */
189 int mode; /* terminal mode flags */
190 int esc; /* escape state flags */
194 /* Purely graphic info */
200 Atom xembed, wmdeletewin;
206 bool isfixed; /* is fixed geometry? */
207 int fx, fy, fw, fh; /* fixed geometry */
208 int tw, th; /* tty width and height */
209 int w; /* window width */
210 int h; /* window height */
211 int ch; /* char height */
212 int cw; /* char width */
213 char state; /* focus, redraw, visible */
222 /* TODO: use better name for vars... */
233 struct timeval tclick1;
234 struct timeval tclick2;
250 /* Drawing Context */
252 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
254 Font font, bfont, ifont, ibfont;
257 static void die(const char *, ...);
258 static void draw(void);
259 static void redraw(void);
260 static void drawregion(int, int, int, int);
261 static void execsh(void);
262 static void sigchld(int);
263 static void run(void);
265 static void csidump(void);
266 static void csihandle(void);
267 static void csiparse(void);
268 static void csireset(void);
269 static void strdump(void);
270 static void strhandle(void);
271 static void strparse(void);
272 static void strreset(void);
274 static void tclearregion(int, int, int, int);
275 static void tcursor(int);
276 static void tdeletechar(int);
277 static void tdeleteline(int);
278 static void tinsertblank(int);
279 static void tinsertblankline(int);
280 static void tmoveto(int, int);
281 static void tnew(int, int);
282 static void tnewline(int);
283 static void tputtab(bool);
284 static void tputc(char *, int);
285 static void treset(void);
286 static int tresize(int, int);
287 static void tscrollup(int, int);
288 static void tscrolldown(int, int);
289 static void tsetattr(int*, int);
290 static void tsetchar(char*);
291 static void tsetscroll(int, int);
292 static void tswapscreen(void);
293 static void tsetdirt(int, int);
294 static void tsetmode(bool, bool, int *, int);
295 static void tfulldirt(void);
297 static void ttynew(void);
298 static void ttyread(void);
299 static void ttyresize(void);
300 static void ttywrite(const char *, size_t);
302 static void xdraws(char *, Glyph, int, int, int, int);
303 static void xhints(void);
304 static void xclear(int, int, int, int);
305 static void xclearborders(void);
306 static void xdrawcursor(void);
307 static void xinit(void);
308 static void xloadcols(void);
309 static void xresettitle(void);
310 static void xseturgency(int);
311 static void xsetsel(char*);
312 static void xtermclear(int, int, int, int);
313 static void xresize(int, int);
315 static void expose(XEvent *);
316 static void visibility(XEvent *);
317 static void unmap(XEvent *);
318 static char *kmap(KeySym, uint);
319 static void kpress(XEvent *);
320 static void cmessage(XEvent *);
321 static void resize(XEvent *);
322 static void focus(XEvent *);
323 static void brelease(XEvent *);
324 static void bpress(XEvent *);
325 static void bmotion(XEvent *);
326 static void selnotify(XEvent *);
327 static void selclear(XEvent *);
328 static void selrequest(XEvent *);
330 static void selinit(void);
331 static inline bool selected(int, int);
332 static void selcopy(void);
333 static void selpaste(void);
334 static void selscroll(int, int);
336 static int utf8decode(char *, long *);
337 static int utf8encode(long *, char *);
338 static int utf8size(char *);
339 static int isfullutf8(char *, int);
341 static void *xmalloc(size_t);
342 static void *xrealloc(void *, size_t);
343 static void *xcalloc(size_t nmemb, size_t size);
344 static char *smstrcat(char *, ...);
346 static void (*handler[LASTEvent])(XEvent *) = {
348 [ClientMessage] = cmessage,
349 [ConfigureNotify] = resize,
350 [VisibilityNotify] = visibility,
351 [UnmapNotify] = unmap,
355 [MotionNotify] = bmotion,
356 [ButtonPress] = bpress,
357 [ButtonRelease] = brelease,
358 [SelectionClear] = selclear,
359 [SelectionNotify] = selnotify,
360 [SelectionRequest] = selrequest,
367 static CSIEscape csiescseq;
368 static STREscape strescseq;
371 static Selection sel;
372 static int iofd = -1;
373 static char **opt_cmd = NULL;
374 static char *opt_io = NULL;
375 static char *opt_title = NULL;
376 static char *opt_embed = NULL;
377 static char *opt_class = NULL;
378 static char *opt_font = NULL;
381 xmalloc(size_t len) {
382 void *p = malloc(len);
385 die("Out of memory\n");
391 xrealloc(void *p, size_t len) {
392 if((p = realloc(p, len)) == NULL)
393 die("Out of memory\n");
399 xcalloc(size_t nmemb, size_t size) {
400 void *p = calloc(nmemb, size);
403 die("Out of memory\n");
409 smstrcat(char *src, ...)
415 len = slen = strlen(src);
417 va_start(fmtargs, src);
419 v = va_arg(fmtargs, char *);
426 p = ret = xmalloc(len+1);
427 memmove(p, src, slen);
430 va_start(fmtargs, src);
432 v = va_arg(fmtargs, char *);
447 utf8decode(char *s, long *u) {
453 if(~c & B7) { /* 0xxxxxxx */
456 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
457 *u = c&(B4|B3|B2|B1|B0);
459 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
460 *u = c&(B3|B2|B1|B0);
462 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
469 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
471 if((c & (B7|B6)) != B7) /* 10xxxxxx */
474 *u |= c & (B5|B4|B3|B2|B1|B0);
477 if((n == 1 && *u < 0x80) ||
478 (n == 2 && *u < 0x800) ||
479 (n == 3 && *u < 0x10000) ||
480 (*u >= 0xD800 && *u <= 0xDFFF)) {
492 utf8encode(long *u, char *s) {
500 *sp = uc; /* 0xxxxxxx */
502 } else if(*u < 0x800) {
503 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
505 } else if(uc < 0x10000) {
506 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
508 } else if(uc <= 0x10FFFF) {
509 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
515 for(i=n,++sp; i>0; --i,++sp)
516 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
528 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
529 UTF-8 otherwise return 0 */
531 isfullutf8(char *s, int b) {
539 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
541 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
543 ((b == 2) && (*c2&(B7|B6)) == B7))) {
545 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
547 ((b == 2) && (*c2&(B7|B6)) == B7) ||
548 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
561 } else if((c&(B7|B6|B5)) == (B7|B6)) {
563 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
572 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
573 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
577 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
578 if(sel.xtarget == None)
579 sel.xtarget = XA_STRING;
583 selected(int x, int y) {
586 if(sel.ey == y && sel.by == y) {
587 bx = MIN(sel.bx, sel.ex);
588 ex = MAX(sel.bx, sel.ex);
589 return BETWEEN(x, bx, ex);
592 return ((sel.b.y < y && y < sel.e.y)
593 || (y == sel.e.y && x <= sel.e.x))
594 || (y == sel.b.y && x >= sel.b.x
595 && (x <= sel.e.x || sel.b.y != sel.e.y));
599 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
601 *b = e->xbutton.button;
603 *x = X2COL(e->xbutton.x);
604 *y = Y2ROW(e->xbutton.y);
605 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
606 sel.b.y = MIN(sel.by, sel.ey);
607 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
608 sel.e.y = MAX(sel.by, sel.ey);
612 mousereport(XEvent *e) {
613 int x = X2COL(e->xbutton.x);
614 int y = Y2ROW(e->xbutton.y);
615 int button = e->xbutton.button;
616 int state = e->xbutton.state;
617 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
618 static int ob, ox, oy;
621 if(e->xbutton.type == MotionNotify) {
622 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
626 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
632 if(e->xbutton.type == ButtonPress) {
638 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
639 + (state & Mod4Mask ? 8 : 0)
640 + (state & ControlMask ? 16 : 0);
642 ttywrite(buf, sizeof(buf));
647 if(IS_SET(MODE_MOUSE)) {
649 } else if(e->xbutton.button == Button1) {
652 tsetdirt(sel.b.y, sel.e.y);
656 sel.ex = sel.bx = X2COL(e->xbutton.x);
657 sel.ey = sel.by = Y2ROW(e->xbutton.y);
664 int x, y, bufsize, is_selected = 0, size;
670 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
671 ptr = str = xmalloc(bufsize);
673 /* append every set & selected glyph to the selection */
674 for(y = 0; y < term.row; y++) {
675 for(x = 0; x < term.col; x++) {
676 gp = &term.line[y][x];
678 if(!(is_selected = selected(x, y)))
680 p = (gp->state & GLYPH_SET) ? gp->c : " ";
682 memcpy(ptr, p, size);
685 /* \n at the end of every selected line except for the last one */
686 if(is_selected && y < sel.e.y)
691 sel.alt = IS_SET(MODE_ALTSCREEN);
696 selnotify(XEvent *e) {
697 ulong nitems, ofs, rem;
704 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
705 False, AnyPropertyType, &type, &format,
706 &nitems, &rem, &data)) {
707 fprintf(stderr, "Clipboard allocation failed\n");
710 ttywrite((const char *) data, nitems * format / 8);
712 /* number of 32-bit chunks returned */
713 ofs += nitems * format / 32;
719 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
720 xw.win, CurrentTime);
723 void selclear(XEvent *e) {
727 tsetdirt(sel.b.y, sel.e.y);
731 selrequest(XEvent *e) {
732 XSelectionRequestEvent *xsre;
734 Atom xa_targets, string;
736 xsre = (XSelectionRequestEvent *) e;
737 xev.type = SelectionNotify;
738 xev.requestor = xsre->requestor;
739 xev.selection = xsre->selection;
740 xev.target = xsre->target;
741 xev.time = xsre->time;
745 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
746 if(xsre->target == xa_targets) {
747 /* respond with the supported type */
748 string = sel.xtarget;
749 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
750 XA_ATOM, 32, PropModeReplace,
751 (uchar *) &string, 1);
752 xev.property = xsre->property;
753 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
754 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
755 xsre->target, 8, PropModeReplace,
756 (uchar *) sel.clip, strlen(sel.clip));
757 xev.property = xsre->property;
760 /* all done, send a notification to the listener */
761 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
762 fprintf(stderr, "Error sending SelectionNotify event\n");
767 /* register the selection for both the clipboard and the primary */
773 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
775 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
776 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
780 brelease(XEvent *e) {
783 if(IS_SET(MODE_MOUSE)) {
788 if(e->xbutton.button == Button2) {
790 } else if(e->xbutton.button == Button1) {
792 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
793 term.dirty[sel.ey] = 1;
794 if(sel.bx == sel.ex && sel.by == sel.ey) {
796 gettimeofday(&now, NULL);
798 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
799 /* triple click on the line */
800 sel.b.x = sel.bx = 0;
801 sel.e.x = sel.ex = term.col;
802 sel.b.y = sel.e.y = sel.ey;
804 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
805 /* double click to select word */
807 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
808 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
812 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
813 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
817 sel.b.y = sel.e.y = sel.ey;
825 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
826 gettimeofday(&sel.tclick1, NULL);
831 int starty, endy, oldey, oldex;
833 if(IS_SET(MODE_MOUSE)) {
841 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
843 if(oldey != sel.ey || oldex != sel.ex) {
844 starty = MIN(oldey, sel.ey);
845 endy = MAX(oldey, sel.ey);
846 tsetdirt(starty, endy);
852 die(const char *errstr, ...) {
855 va_start(ap, errstr);
856 vfprintf(stderr, errstr, ap);
864 char *envshell = getenv("SHELL");
870 signal(SIGCHLD, SIG_DFL);
871 signal(SIGHUP, SIG_DFL);
872 signal(SIGINT, SIG_DFL);
873 signal(SIGQUIT, SIG_DFL);
874 signal(SIGTERM, SIG_DFL);
875 signal(SIGALRM, SIG_DFL);
877 DEFAULT(envshell, SHELL);
878 putenv("TERM="TNAME);
879 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
880 execvp(args[0], args);
888 if(waitpid(pid, &stat, 0) < 0)
889 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
891 if(WIFEXITED(stat)) {
892 exit(WEXITSTATUS(stat));
901 struct winsize w = {term.row, term.col, 0, 0};
903 /* seems to work fine on linux, openbsd and freebsd */
904 if(openpty(&m, &s, NULL, NULL, &w) < 0)
905 die("openpty failed: %s\n", SERRNO);
907 switch(pid = fork()) {
909 die("fork failed\n");
912 setsid(); /* create a new process group */
913 dup2(s, STDIN_FILENO);
914 dup2(s, STDOUT_FILENO);
915 dup2(s, STDERR_FILENO);
916 if(ioctl(s, TIOCSCTTY, NULL) < 0)
917 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
925 signal(SIGCHLD, sigchld);
927 if(!strcmp(opt_io, "-")) {
928 iofd = STDOUT_FILENO;
930 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
931 fprintf(stderr, "Error opening %s:%s\n",
932 opt_io, strerror(errno));
943 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
945 fprintf(stderr, "\n");
950 static char buf[BUFSIZ];
951 static int buflen = 0;
954 int charsize; /* size of utf8 char in bytes */
958 /* append read bytes to unprocessed bytes */
959 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
960 die("Couldn't read from shell: %s\n", SERRNO);
962 /* process every complete utf8 char */
965 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
966 charsize = utf8decode(ptr, &utf8c);
967 utf8encode(&utf8c, s);
973 /* keep any uncomplete utf8 char for the next call */
974 memmove(buf, ptr, buflen);
978 ttywrite(const char *s, size_t n) {
979 if(write(cmdfd, s, n) == -1)
980 die("write error on tty: %s\n", SERRNO);
991 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
992 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
996 tsetdirt(int top, int bot) {
999 LIMIT(top, 0, term.row-1);
1000 LIMIT(bot, 0, term.row-1);
1002 for(i = top; i <= bot; i++)
1008 tsetdirt(0, term.row-1);
1015 if(mode == CURSOR_SAVE) {
1017 } else if(mode == CURSOR_LOAD) {
1027 term.c = (TCursor){{
1031 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1033 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1034 for(i = TAB; i < term.col; i += TAB)
1037 term.bot = term.row - 1;
1038 term.mode = MODE_WRAP;
1040 tclearregion(0, 0, term.col-1, term.row-1);
1044 tnew(int col, int row) {
1045 /* set screen size */
1048 term.line = xmalloc(term.row * sizeof(Line));
1049 term.alt = xmalloc(term.row * sizeof(Line));
1050 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1051 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1053 for(row = 0; row < term.row; row++) {
1054 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1055 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1056 term.dirty[row] = 0;
1058 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1065 Line *tmp = term.line;
1067 term.line = term.alt;
1069 term.mode ^= MODE_ALTSCREEN;
1074 tscrolldown(int orig, int n) {
1078 LIMIT(n, 0, term.bot-orig+1);
1080 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1082 for(i = term.bot; i >= orig+n; i--) {
1083 temp = term.line[i];
1084 term.line[i] = term.line[i-n];
1085 term.line[i-n] = temp;
1088 term.dirty[i-n] = 1;
1095 tscrollup(int orig, int n) {
1098 LIMIT(n, 0, term.bot-orig+1);
1100 tclearregion(0, orig, term.col-1, orig+n-1);
1102 for(i = orig; i <= term.bot-n; i++) {
1103 temp = term.line[i];
1104 term.line[i] = term.line[i+n];
1105 term.line[i+n] = temp;
1108 term.dirty[i+n] = 1;
1111 selscroll(orig, -n);
1115 selscroll(int orig, int n) {
1119 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1120 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1124 if(sel.by < term.top) {
1128 if(sel.ey > term.bot) {
1132 sel.b.y = sel.by, sel.b.x = sel.bx;
1133 sel.e.y = sel.ey, sel.e.x = sel.ex;
1138 tnewline(int first_col) {
1142 tscrollup(term.top, 1);
1146 tmoveto(first_col ? 0 : term.c.x, y);
1151 /* int noarg = 1; */
1152 char *p = csiescseq.buf;
1156 csiescseq.priv = 1, p++;
1158 while(p < csiescseq.buf+csiescseq.len) {
1159 while(isdigit(*p)) {
1160 csiescseq.arg[csiescseq.narg] *= 10;
1161 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1163 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1164 csiescseq.narg++, p++;
1166 csiescseq.mode = *p;
1175 tmoveto(int x, int y) {
1176 LIMIT(x, 0, term.col-1);
1177 LIMIT(y, 0, term.row-1);
1178 term.c.state &= ~CURSOR_WRAPNEXT;
1185 char *vt100_0[62] = { /* 0x41 - 0x7e */
1186 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1187 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1188 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1189 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1190 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1191 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1192 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1193 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1197 * The table is proudly stolen from rxvt.
1199 if(term.c.attr.mode & ATTR_GFX) {
1200 if(c[0] >= 0x41 && c[0] <= 0x7e
1201 && vt100_0[c[0] - 0x41]) {
1202 c = vt100_0[c[0] - 0x41];
1206 term.dirty[term.c.y] = 1;
1207 term.line[term.c.y][term.c.x] = term.c.attr;
1208 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1209 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1213 tclearregion(int x1, int y1, int x2, int y2) {
1217 temp = x1, x1 = x2, x2 = temp;
1219 temp = y1, y1 = y2, y2 = temp;
1221 LIMIT(x1, 0, term.col-1);
1222 LIMIT(x2, 0, term.col-1);
1223 LIMIT(y1, 0, term.row-1);
1224 LIMIT(y2, 0, term.row-1);
1226 for(y = y1; y <= y2; y++) {
1228 for(x = x1; x <= x2; x++)
1229 term.line[y][x].state = 0;
1234 tdeletechar(int n) {
1235 int src = term.c.x + n;
1237 int size = term.col - src;
1239 term.dirty[term.c.y] = 1;
1241 if(src >= term.col) {
1242 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1246 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1247 size * sizeof(Glyph));
1248 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1252 tinsertblank(int n) {
1255 int size = term.col - dst;
1257 term.dirty[term.c.y] = 1;
1259 if(dst >= term.col) {
1260 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1264 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1265 size * sizeof(Glyph));
1266 tclearregion(src, term.c.y, dst - 1, term.c.y);
1270 tinsertblankline(int n) {
1271 if(term.c.y < term.top || term.c.y > term.bot)
1274 tscrolldown(term.c.y, n);
1278 tdeleteline(int n) {
1279 if(term.c.y < term.top || term.c.y > term.bot)
1282 tscrollup(term.c.y, n);
1286 tsetattr(int *attr, int l) {
1289 for(i = 0; i < l; i++) {
1292 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1293 | ATTR_ITALIC | ATTR_BLINK);
1294 term.c.attr.fg = DefaultFG;
1295 term.c.attr.bg = DefaultBG;
1298 term.c.attr.mode |= ATTR_BOLD;
1300 case 3: /* enter standout (highlight) */
1301 term.c.attr.mode |= ATTR_ITALIC;
1304 term.c.attr.mode |= ATTR_UNDERLINE;
1307 term.c.attr.mode |= ATTR_BLINK;
1310 term.c.attr.mode |= ATTR_REVERSE;
1314 term.c.attr.mode &= ~ATTR_BOLD;
1316 case 23: /* leave standout (highlight) mode */
1317 term.c.attr.mode &= ~ATTR_ITALIC;
1320 term.c.attr.mode &= ~ATTR_UNDERLINE;
1323 term.c.attr.mode &= ~ATTR_BLINK;
1326 term.c.attr.mode &= ~ATTR_REVERSE;
1329 if(i + 2 < l && attr[i + 1] == 5) {
1331 if(BETWEEN(attr[i], 0, 255)) {
1332 term.c.attr.fg = attr[i];
1335 "erresc: bad fgcolor %d\n",
1340 "erresc(38): gfx attr %d unknown\n",
1345 term.c.attr.fg = DefaultFG;
1348 if(i + 2 < l && attr[i + 1] == 5) {
1350 if(BETWEEN(attr[i], 0, 255)) {
1351 term.c.attr.bg = attr[i];
1354 "erresc: bad bgcolor %d\n",
1359 "erresc(48): gfx attr %d unknown\n",
1364 term.c.attr.bg = DefaultBG;
1367 if(BETWEEN(attr[i], 30, 37)) {
1368 term.c.attr.fg = attr[i] - 30;
1369 } else if(BETWEEN(attr[i], 40, 47)) {
1370 term.c.attr.bg = attr[i] - 40;
1371 } else if(BETWEEN(attr[i], 90, 97)) {
1372 term.c.attr.fg = attr[i] - 90 + 8;
1373 } else if(BETWEEN(attr[i], 100, 107)) {
1374 term.c.attr.bg = attr[i] - 100 + 8;
1377 "erresc(default): gfx attr %d unknown\n",
1378 attr[i]), csidump();
1386 tsetscroll(int t, int b) {
1389 LIMIT(t, 0, term.row-1);
1390 LIMIT(b, 0, term.row-1);
1400 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1403 tsetmode(bool priv, bool set, int *args, int narg) {
1406 for(lim = args + narg; args < lim; ++args) {
1410 case 1: /* DECCKM -- Cursor key */
1411 MODBIT(term.mode, set, MODE_APPKEYPAD);
1413 case 5: /* DECSCNM -- Reverse video */
1415 MODBIT(term.mode, set, MODE_REVERSE);
1416 if(mode != term.mode)
1419 case 6: /* XXX: DECOM -- Origin */
1421 case 7: /* DECAWM -- Auto wrap */
1422 MODBIT(term.mode, set, MODE_WRAP);
1424 case 8: /* XXX: DECARM -- Auto repeat */
1426 case 0: /* Error (IGNORED) */
1427 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1430 MODBIT(term.c.state, !set, CURSOR_HIDE);
1432 case 1000: /* 1000,1002: enable xterm mouse report */
1433 MODBIT(term.mode, set, MODE_MOUSEBTN);
1436 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1438 case 1049: /* = 1047 and 1048 */
1441 if(IS_SET(MODE_ALTSCREEN))
1442 tclearregion(0, 0, term.col-1, term.row-1);
1443 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1444 (!set && IS_SET(MODE_ALTSCREEN))) {
1451 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1454 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1455 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1456 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1457 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1458 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1459 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1461 "erresc: unknown private set/reset mode %d\n",
1467 case 0: /* Error (IGNORED) */
1469 case 2: /* KAM -- keyboard action */
1470 MODBIT(term.mode, set, MODE_KBDLOCK);
1472 case 4: /* IRM -- Insertion-replacement */
1473 MODBIT(term.mode, set, MODE_INSERT);
1475 case 12: /* XXX: SRM -- Send/Receive */
1477 case 20: /* LNM -- Linefeed/new line */
1478 MODBIT(term.mode, set, MODE_CRLF);
1482 "erresc: unknown set/reset mode %d\n",
1494 switch(csiescseq.mode) {
1497 fprintf(stderr, "erresc: unknown csi ");
1501 case '@': /* ICH -- Insert <n> blank char */
1502 DEFAULT(csiescseq.arg[0], 1);
1503 tinsertblank(csiescseq.arg[0]);
1505 case 'A': /* CUU -- Cursor <n> Up */
1507 DEFAULT(csiescseq.arg[0], 1);
1508 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1510 case 'B': /* CUD -- Cursor <n> Down */
1511 DEFAULT(csiescseq.arg[0], 1);
1512 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1514 case 'C': /* CUF -- Cursor <n> Forward */
1516 DEFAULT(csiescseq.arg[0], 1);
1517 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1519 case 'D': /* CUB -- Cursor <n> Backward */
1520 DEFAULT(csiescseq.arg[0], 1);
1521 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1523 case 'E': /* CNL -- Cursor <n> Down and first col */
1524 DEFAULT(csiescseq.arg[0], 1);
1525 tmoveto(0, term.c.y+csiescseq.arg[0]);
1527 case 'F': /* CPL -- Cursor <n> Up and first col */
1528 DEFAULT(csiescseq.arg[0], 1);
1529 tmoveto(0, term.c.y-csiescseq.arg[0]);
1531 case 'g': /* TBC -- Tabulation clear */
1532 switch (csiescseq.arg[0]) {
1533 case 0: /* clear current tab stop */
1534 term.tabs[term.c.x] = 0;
1536 case 3: /* clear all the tabs */
1537 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1543 case 'G': /* CHA -- Move to <col> */
1545 DEFAULT(csiescseq.arg[0], 1);
1546 tmoveto(csiescseq.arg[0]-1, term.c.y);
1548 case 'H': /* CUP -- Move to <row> <col> */
1550 DEFAULT(csiescseq.arg[0], 1);
1551 DEFAULT(csiescseq.arg[1], 1);
1552 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1554 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1555 DEFAULT(csiescseq.arg[0], 1);
1556 while(csiescseq.arg[0]--)
1559 case 'J': /* ED -- Clear screen */
1561 switch(csiescseq.arg[0]) {
1563 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1564 if(term.c.y < term.row-1)
1565 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1569 tclearregion(0, 0, term.col-1, term.c.y-1);
1570 tclearregion(0, term.c.y, term.c.x, term.c.y);
1573 tclearregion(0, 0, term.col-1, term.row-1);
1579 case 'K': /* EL -- Clear line */
1580 switch(csiescseq.arg[0]) {
1582 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1585 tclearregion(0, term.c.y, term.c.x, term.c.y);
1588 tclearregion(0, term.c.y, term.col-1, term.c.y);
1592 case 'S': /* SU -- Scroll <n> line up */
1593 DEFAULT(csiescseq.arg[0], 1);
1594 tscrollup(term.top, csiescseq.arg[0]);
1596 case 'T': /* SD -- Scroll <n> line down */
1597 DEFAULT(csiescseq.arg[0], 1);
1598 tscrolldown(term.top, csiescseq.arg[0]);
1600 case 'L': /* IL -- Insert <n> blank lines */
1601 DEFAULT(csiescseq.arg[0], 1);
1602 tinsertblankline(csiescseq.arg[0]);
1604 case 'l': /* RM -- Reset Mode */
1605 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1607 case 'M': /* DL -- Delete <n> lines */
1608 DEFAULT(csiescseq.arg[0], 1);
1609 tdeleteline(csiescseq.arg[0]);
1611 case 'X': /* ECH -- Erase <n> char */
1612 DEFAULT(csiescseq.arg[0], 1);
1613 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1615 case 'P': /* DCH -- Delete <n> char */
1616 DEFAULT(csiescseq.arg[0], 1);
1617 tdeletechar(csiescseq.arg[0]);
1619 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1620 DEFAULT(csiescseq.arg[0], 1);
1621 while(csiescseq.arg[0]--)
1624 case 'd': /* VPA -- Move to <row> */
1625 DEFAULT(csiescseq.arg[0], 1);
1626 tmoveto(term.c.x, csiescseq.arg[0]-1);
1628 case 'h': /* SM -- Set terminal mode */
1629 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1631 case 'm': /* SGR -- Terminal attribute (color) */
1632 tsetattr(csiescseq.arg, csiescseq.narg);
1634 case 'r': /* DECSTBM -- Set Scrolling Region */
1635 if(csiescseq.priv) {
1638 DEFAULT(csiescseq.arg[0], 1);
1639 DEFAULT(csiescseq.arg[1], term.row);
1640 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1644 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1645 tcursor(CURSOR_SAVE);
1647 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1648 tcursor(CURSOR_LOAD);
1659 for(i = 0; i < csiescseq.len; i++) {
1660 c = csiescseq.buf[i] & 0xff;
1663 } else if(c == '\n') {
1665 } else if(c == '\r') {
1667 } else if(c == 0x1b) {
1670 printf("(%02x)", c);
1678 memset(&csiescseq, 0, sizeof(csiescseq));
1686 * TODO: make this being useful in case of color palette change.
1692 switch(strescseq.type) {
1693 case ']': /* OSC -- Operating System Command */
1699 * TODO: Handle special chars in string, like umlauts.
1702 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1706 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1708 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1711 fprintf(stderr, "erresc: unknown str ");
1716 case 'k': /* old title set compatibility */
1717 XStoreName(xw.dpy, xw.win, strescseq.buf);
1719 case 'P': /* DSC -- Device Control String */
1720 case '_': /* APC -- Application Program Command */
1721 case '^': /* PM -- Privacy Message */
1723 fprintf(stderr, "erresc: unknown str ");
1733 * TODO: Implement parsing like for CSI when required.
1734 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1744 printf("ESC%c", strescseq.type);
1745 for(i = 0; i < strescseq.len; i++) {
1746 c = strescseq.buf[i] & 0xff;
1749 } else if(c == '\n') {
1751 } else if(c == '\r') {
1753 } else if(c == 0x1b) {
1756 printf("(%02x)", c);
1764 memset(&strescseq, 0, sizeof(strescseq));
1768 tputtab(bool forward) {
1774 for(++x; x < term.col && !term.tabs[x]; ++x)
1779 for(--x; x > 0 && !term.tabs[x]; --x)
1782 tmoveto(x, term.c.y);
1786 tputc(char *c, int len) {
1790 write(iofd, c, len);
1797 tmoveto(term.c.x-1, term.c.y);
1800 tmoveto(0, term.c.y);
1805 /* go to first col if the mode is set */
1806 tnewline(IS_SET(MODE_CRLF));
1809 if(term.esc & ESC_STR)
1812 if(!(xw.state & WIN_FOCUSED))
1817 term.esc = ESC_START;
1821 if(term.esc & ESC_START) {
1822 if(term.esc & ESC_CSI) {
1823 csiescseq.buf[csiescseq.len++] = ascii;
1824 if(BETWEEN(ascii, 0x40, 0x7E)
1825 || csiescseq.len >= ESC_BUF_SIZ) {
1827 csiparse(), csihandle();
1829 } else if(term.esc & ESC_STR) {
1832 term.esc = ESC_START | ESC_STR_END;
1834 case '\a': /* backwards compatibility to xterm */
1839 strescseq.buf[strescseq.len++] = ascii;
1840 if(strescseq.len+1 >= STR_BUF_SIZ) {
1845 } else if(term.esc & ESC_STR_END) {
1849 } else if(term.esc & ESC_ALTCHARSET) {
1851 case '0': /* Line drawing set */
1852 term.c.attr.mode |= ATTR_GFX;
1854 case 'B': /* USASCII */
1855 term.c.attr.mode &= ~ATTR_GFX;
1857 case 'A': /* UK (IGNORED) */
1858 case '<': /* multinational charset (IGNORED) */
1859 case '5': /* Finnish (IGNORED) */
1860 case 'C': /* Finnish (IGNORED) */
1861 case 'K': /* German (IGNORED) */
1864 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1870 term.esc |= ESC_CSI;
1872 case 'P': /* DCS -- Device Control String */
1873 case '_': /* APC -- Application Program Command */
1874 case '^': /* PM -- Privacy Message */
1875 case ']': /* OSC -- Operating System Command */
1876 case 'k': /* old title set compatibility */
1878 strescseq.type = ascii;
1879 term.esc |= ESC_STR;
1881 case '(': /* set primary charset G0 */
1882 term.esc |= ESC_ALTCHARSET;
1884 case ')': /* set secondary charset G1 (IGNORED) */
1885 case '*': /* set tertiary charset G2 (IGNORED) */
1886 case '+': /* set quaternary charset G3 (IGNORED) */
1889 case 'D': /* IND -- Linefeed */
1890 if(term.c.y == term.bot) {
1891 tscrollup(term.top, 1);
1893 tmoveto(term.c.x, term.c.y+1);
1897 case 'E': /* NEL -- Next line */
1898 tnewline(1); /* always go to first col */
1901 case 'H': /* HTS -- Horizontal tab stop */
1902 term.tabs[term.c.x] = 1;
1905 case 'M': /* RI -- Reverse index */
1906 if(term.c.y == term.top) {
1907 tscrolldown(term.top, 1);
1909 tmoveto(term.c.x, term.c.y-1);
1913 case 'c': /* RIS -- Reset to inital state */
1918 case '=': /* DECPAM -- Application keypad */
1919 term.mode |= MODE_APPKEYPAD;
1922 case '>': /* DECPNM -- Normal keypad */
1923 term.mode &= ~MODE_APPKEYPAD;
1926 case '7': /* DECSC -- Save Cursor */
1927 tcursor(CURSOR_SAVE);
1930 case '8': /* DECRC -- Restore Cursor */
1931 tcursor(CURSOR_LOAD);
1934 case '\\': /* ST -- Stop */
1938 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1939 (uchar) ascii, isprint(ascii)? ascii:'.');
1944 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1946 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1947 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1948 tnewline(1); /* always go to first col */
1950 if(term.c.x+1 < term.col) {
1951 tmoveto(term.c.x+1, term.c.y);
1953 term.c.state |= CURSOR_WRAPNEXT;
1960 tresize(int col, int row) {
1962 int minrow = MIN(row, term.row);
1963 int mincol = MIN(col, term.col);
1964 int slide = term.c.y - row + 1;
1967 if(col < 1 || row < 1)
1970 /* free unneeded rows */
1973 /* slide screen to keep cursor where we expect it -
1974 * tscrollup would work here, but we can optimize to
1975 * memmove because we're freeing the earlier lines */
1976 for(/* i = 0 */; i < slide; i++) {
1980 memmove(term.line, term.line + slide, row * sizeof(Line));
1981 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1983 for(i += row; i < term.row; i++) {
1988 /* resize to new height */
1989 term.line = xrealloc(term.line, row * sizeof(Line));
1990 term.alt = xrealloc(term.alt, row * sizeof(Line));
1991 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1992 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1994 /* resize each row to new width, zero-pad if needed */
1995 for(i = 0; i < minrow; i++) {
1997 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1998 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
1999 for(x = mincol; x < col; x++) {
2000 term.line[i][x].state = 0;
2001 term.alt[i][x].state = 0;
2005 /* allocate any new rows */
2006 for(/* i == minrow */; i < row; i++) {
2008 term.line[i] = xcalloc(col, sizeof(Glyph));
2009 term.alt [i] = xcalloc(col, sizeof(Glyph));
2011 if(col > term.col) {
2012 bp = term.tabs + term.col;
2014 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2015 while(--bp > term.tabs && !*bp)
2017 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2020 /* update terminal size */
2021 term.col = col, term.row = row;
2022 /* make use of the LIMIT in tmoveto */
2023 tmoveto(term.c.x, term.c.y);
2024 /* reset scrolling region */
2025 tsetscroll(0, row-1);
2031 xresize(int col, int row) {
2032 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2033 xw.th = MAX(1, 2*BORDER + row * xw.ch);
2035 XftDrawChange(xw.xft_draw, xw.buf);
2041 XRenderColor xft_color = { .alpha = 0 };
2043 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2044 for(i = 0; i < LEN(colorname); i++) {
2047 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2048 die("Could not allocate color '%s'\n", colorname[i]);
2052 /* load colors [16-255] ; same colors as xterm */
2053 for(i = 16, r = 0; r < 6; r++) {
2054 for(g = 0; g < 6; g++) {
2055 for(b = 0; b < 6; b++) {
2056 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2057 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2058 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2059 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2060 die("Could not allocate color %d\n", i);
2067 for(r = 0; r < 24; r++, i++) {
2068 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2069 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2071 die("Could not allocate color %d\n", i);
2077 xtermclear(int col1, int row1, int col2, int row2) {
2078 XftDrawRect(xw.xft_draw,
2079 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2080 BORDER + col1 * xw.cw,
2081 BORDER + row1 * xw.ch,
2082 (col2-col1+1) * xw.cw,
2083 (row2-row1+1) * xw.ch);
2087 * Absolute coordinates.
2090 xclear(int x1, int y1, int x2, int y2) {
2091 XftDrawRect(xw.xft_draw,
2092 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2093 x1, y1, x2-x1, y2-y1);
2098 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2099 XWMHints wm = {.flags = InputHint, .input = 1};
2100 XSizeHints *sizeh = NULL;
2102 sizeh = XAllocSizeHints();
2103 if(xw.isfixed == False) {
2104 sizeh->flags = PSize | PResizeInc | PBaseSize;
2105 sizeh->height = xw.h;
2106 sizeh->width = xw.w;
2107 sizeh->height_inc = xw.ch;
2108 sizeh->width_inc = xw.cw;
2109 sizeh->base_height = 2*BORDER;
2110 sizeh->base_width = 2*BORDER;
2112 sizeh->flags = PMaxSize | PMinSize;
2113 sizeh->min_width = sizeh->max_width = xw.fw;
2114 sizeh->min_height = sizeh->max_height = xw.fh;
2117 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2122 xinitfont(Font *f, char *fontstr) {
2123 FcPattern *pattern, *match;
2126 pattern = FcNameParse((FcChar8 *)fontstr);
2128 die("st: can't open font %s\n", fontstr);
2130 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2131 FcPatternDestroy(pattern);
2133 die("st: can't open font %s\n", fontstr);
2134 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2135 FcPatternDestroy(match);
2136 die("st: can't open font %s.\n", fontstr);
2139 f->ascent = f->xft_set->ascent;
2140 f->descent = f->xft_set->descent;
2142 f->rbearing = f->xft_set->max_advance_width;
2144 f->height = f->xft_set->height;
2145 f->width = f->lbearing + f->rbearing;
2149 initfonts(char *fontstr) {
2152 xinitfont(&dc.font, fontstr);
2153 xw.cw = dc.font.width;
2154 xw.ch = dc.font.height;
2156 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2157 xinitfont(&dc.bfont, fstr);
2160 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2161 xinitfont(&dc.ifont, fstr);
2164 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2165 xinitfont(&dc.ibfont, fstr);
2171 XSetWindowAttributes attrs;
2174 int sw, sh, major, minor;
2176 if(!(xw.dpy = XOpenDisplay(NULL)))
2177 die("Can't open display\n");
2178 xw.scr = XDefaultScreen(xw.dpy);
2179 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2182 initfonts((opt_font != NULL)? opt_font : FONT);
2185 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2188 /* adjust fixed window geometry */
2190 sw = DisplayWidth(xw.dpy, xw.scr);
2191 sh = DisplayHeight(xw.dpy, xw.scr);
2193 xw.fx = sw + xw.fx - xw.fw - 1;
2195 xw.fy = sh + xw.fy - xw.fh - 1;
2200 /* window - default size */
2201 xw.h = 2*BORDER + term.row * xw.ch;
2202 xw.w = 2*BORDER + term.col * xw.cw;
2207 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2208 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2209 attrs.bit_gravity = NorthWestGravity;
2210 attrs.event_mask = FocusChangeMask | KeyPressMask
2211 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2212 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2213 attrs.colormap = xw.cmap;
2215 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2216 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2217 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2219 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2223 /* double buffering */
2224 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2225 die("Xdbe extension is not present\n");
2226 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2228 /* Xft rendering context */
2229 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2232 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2233 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2234 | XIMStatusNothing, XNClientWindow, xw.win,
2235 XNFocusWindow, xw.win, NULL);
2237 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2239 /* white cursor, black outline */
2240 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2241 XDefineCursor(xw.dpy, xw.win, cursor);
2242 XRecolorCursor(xw.dpy, cursor,
2243 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2244 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2246 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2247 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2248 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2251 XMapWindow(xw.dpy, xw.win);
2257 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2258 int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2259 width = charlen * xw.cw;
2260 Font *font = &dc.font;
2262 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2263 *temp, revfg, revbg;
2264 XRenderColor colfg, colbg;
2266 if(base.mode & ATTR_REVERSE)
2267 temp = fg, fg = bg, bg = temp;
2269 if(base.mode & ATTR_BOLD) {
2270 if(BETWEEN(base.fg, 0, 7)) {
2271 /* basic system colors */
2272 fg = &dc.xft_col[base.fg + 8];
2273 } else if(BETWEEN(base.fg, 16, 195)) {
2275 fg = &dc.xft_col[base.fg + 36];
2276 } else if(BETWEEN(base.fg, 232, 251)) {
2278 fg = &dc.xft_col[base.fg + 4];
2281 * Those ranges will not be brightened:
2282 * 8 - 15 – bright system colors
2283 * 196 - 231 – highest 256 color cube
2284 * 252 - 255 – brightest colors in grescale
2289 if(base.mode & ATTR_ITALIC)
2291 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2294 if(IS_SET(MODE_REVERSE)) {
2295 if(fg == &dc.xft_col[DefaultFG]) {
2296 fg = &dc.xft_col[DefaultBG];
2298 colfg.red = ~fg->color.red;
2299 colfg.green = ~fg->color.green;
2300 colfg.blue = ~fg->color.blue;
2301 colfg.alpha = fg->color.alpha;
2302 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2306 if(bg == &dc.xft_col[DefaultBG]) {
2307 bg = &dc.xft_col[DefaultFG];
2309 colbg.red = ~bg->color.red;
2310 colbg.green = ~bg->color.green;
2311 colbg.blue = ~bg->color.blue;
2312 colbg.alpha = bg->color.alpha;
2313 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2318 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2320 width = extents.xOff;
2322 /* Intelligent cleaning up of the borders. */
2324 xclear(0, (y == 0)? 0 : winy, BORDER,
2325 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2327 if(x + charlen >= term.col-1) {
2328 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2329 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2332 xclear(winx, 0, winx + width, BORDER);
2334 xclear(winx, winy + xw.ch, winx + width, xw.h);
2336 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2337 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2338 winy + font->ascent, (FcChar8 *)s, bytelen);
2340 if(base.mode & ATTR_UNDERLINE) {
2341 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2348 static int oldx = 0, oldy = 0;
2350 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2352 LIMIT(oldx, 0, term.col-1);
2353 LIMIT(oldy, 0, term.row-1);
2355 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2356 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2358 /* remove the old cursor */
2359 if(term.line[oldy][oldx].state & GLYPH_SET) {
2360 sl = utf8size(term.line[oldy][oldx].c);
2361 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2364 xtermclear(oldx, oldy, oldx, oldy);
2367 /* draw the new one */
2368 if(!(term.c.state & CURSOR_HIDE)) {
2369 if(!(xw.state & WIN_FOCUSED))
2372 if(IS_SET(MODE_REVERSE))
2373 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2376 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2377 oldx = term.c.x, oldy = term.c.y;
2383 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2388 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2392 XSync(xw.dpy, False); /* necessary for a good tput flash */
2393 nanosleep(&tv, NULL);
2398 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2400 drawregion(0, 0, term.col, term.row);
2401 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2405 drawregion(int x1, int y1, int x2, int y2) {
2406 int ic, ib, x, y, ox, sl;
2408 char buf[DRAW_BUF_SIZ];
2409 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2411 if((sel.alt && !alt) || (!sel.alt && alt))
2413 if(!(xw.state & WIN_VISIBLE))
2416 for(y = y1; y < y2; y++) {
2420 xtermclear(0, y, term.col, y);
2422 base = term.line[y][0];
2424 for(x = x1; x < x2; x++) {
2425 new = term.line[y][x];
2426 if(ena_sel && *(new.c) && selected(x, y))
2427 new.mode ^= ATTR_REVERSE;
2428 if(ib > 0 && (!(new.state & GLYPH_SET)
2429 || ATTRCMP(base, new)
2430 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2431 xdraws(buf, base, ox, y, ic, ib);
2434 if(new.state & GLYPH_SET) {
2439 sl = utf8size(new.c);
2440 memcpy(buf+ib, new.c, sl);
2446 xdraws(buf, base, ox, y, ic, ib);
2452 expose(XEvent *ev) {
2453 XExposeEvent *e = &ev->xexpose;
2455 if(xw.state & WIN_REDRAW) {
2457 xw.state &= ~WIN_REDRAW;
2462 visibility(XEvent *ev) {
2463 XVisibilityEvent *e = &ev->xvisibility;
2465 if(e->state == VisibilityFullyObscured) {
2466 xw.state &= ~WIN_VISIBLE;
2467 } else if(!(xw.state & WIN_VISIBLE)) {
2468 /* need a full redraw for next Expose, not just a buf copy */
2469 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2475 xw.state &= ~WIN_VISIBLE;
2479 xseturgency(int add) {
2480 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2482 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2483 XSetWMHints(xw.dpy, xw.win, h);
2489 if(ev->type == FocusIn) {
2490 xw.state |= WIN_FOCUSED;
2493 xw.state &= ~WIN_FOCUSED;
2498 kmap(KeySym k, uint state) {
2503 for(i = 0; i < LEN(key); i++) {
2506 if(key[i].k == k && ((state & mask) == mask
2507 || (mask == XK_NO_MOD && !state))) {
2508 return (char*)key[i].s;
2515 kpress(XEvent *ev) {
2516 XKeyEvent *e = &ev->xkey;
2525 if (IS_SET(MODE_KBDLOCK))
2528 meta = e->state & Mod1Mask;
2529 shift = e->state & ShiftMask;
2530 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2532 /* 1. custom keys from config.h */
2533 if((customkey = kmap(ksym, e->state))) {
2534 ttywrite(customkey, strlen(customkey));
2535 /* 2. hardcoded (overrides X lookup) */
2542 /* XXX: shift up/down doesn't work */
2543 sprintf(buf, "\033%c%c",
2544 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2545 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2553 if(IS_SET(MODE_CRLF)) {
2554 ttywrite("\r\n", 2);
2562 if(meta && len == 1)
2563 ttywrite("\033", 1);
2572 cmessage(XEvent *e) {
2574 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2575 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2576 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2577 xw.state |= WIN_FOCUSED;
2579 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2580 xw.state &= ~WIN_FOCUSED;
2582 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2583 /* Send SIGHUP to shell */
2593 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2596 xw.w = e->xconfigure.width;
2597 xw.h = e->xconfigure.height;
2598 col = (xw.w - 2*BORDER) / xw.cw;
2599 row = (xw.h - 2*BORDER) / xw.ch;
2600 if(col == term.col && row == term.row)
2612 int xfd = XConnectionNumber(xw.dpy), i;
2613 struct timeval drawtimeout, *tv = NULL;
2617 FD_SET(cmdfd, &rfd);
2619 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2622 die("select failed: %s\n", SERRNO);
2626 * Stop after a certain number of reads so the user does not
2627 * feel like the system is stuttering.
2629 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2633 * Just wait a bit so it isn't disturbing the
2634 * user and the system is able to write something.
2636 drawtimeout.tv_sec = 0;
2637 drawtimeout.tv_usec = 5;
2644 while(XPending(xw.dpy)) {
2645 XNextEvent(xw.dpy, &ev);
2646 if(XFilterEvent(&ev, xw.win))
2648 if(handler[ev.type])
2649 (handler[ev.type])(&ev);
2658 main(int argc, char *argv[]) {
2659 int i, bitm, xr, yr;
2662 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2665 for(i = 1; i < argc; i++) {
2666 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2669 opt_class = argv[i];
2672 /* eat every remaining arguments */
2684 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2689 if(bitm & WidthValue)
2691 if(bitm & HeightValue)
2693 if(bitm & XNegative && xw.fx == 0)
2695 if(bitm & XNegative && xw.fy == 0)
2698 if(xw.fh != 0 && xw.fw != 0)
2707 opt_title = argv[i];
2714 opt_embed = argv[i];
2720 setlocale(LC_CTYPE, "");