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 xdrawcursor(void);
306 static void xinit(void);
307 static void xloadcols(void);
308 static void xresettitle(void);
309 static void xseturgency(int);
310 static void xsetsel(char*);
311 static void xtermclear(int, int, int, int);
312 static void xresize(int, int);
314 static void expose(XEvent *);
315 static void visibility(XEvent *);
316 static void unmap(XEvent *);
317 static char *kmap(KeySym, uint);
318 static void kpress(XEvent *);
319 static void cmessage(XEvent *);
320 static void resize(XEvent *);
321 static void focus(XEvent *);
322 static void brelease(XEvent *);
323 static void bpress(XEvent *);
324 static void bmotion(XEvent *);
325 static void selnotify(XEvent *);
326 static void selclear(XEvent *);
327 static void selrequest(XEvent *);
329 static void selinit(void);
330 static inline bool selected(int, int);
331 static void selcopy(void);
332 static void selpaste(void);
333 static void selscroll(int, int);
335 static int utf8decode(char *, long *);
336 static int utf8encode(long *, char *);
337 static int utf8size(char *);
338 static int isfullutf8(char *, int);
340 static void *xmalloc(size_t);
341 static void *xrealloc(void *, size_t);
342 static void *xcalloc(size_t nmemb, size_t size);
343 static char *smstrcat(char *, ...);
345 static void (*handler[LASTEvent])(XEvent *) = {
347 [ClientMessage] = cmessage,
348 [ConfigureNotify] = resize,
349 [VisibilityNotify] = visibility,
350 [UnmapNotify] = unmap,
354 [MotionNotify] = bmotion,
355 [ButtonPress] = bpress,
356 [ButtonRelease] = brelease,
357 [SelectionClear] = selclear,
358 [SelectionNotify] = selnotify,
359 [SelectionRequest] = selrequest,
366 static CSIEscape csiescseq;
367 static STREscape strescseq;
370 static Selection sel;
371 static int iofd = -1;
372 static char **opt_cmd = NULL;
373 static char *opt_io = NULL;
374 static char *opt_title = NULL;
375 static char *opt_embed = NULL;
376 static char *opt_class = NULL;
377 static char *opt_font = NULL;
380 xmalloc(size_t len) {
381 void *p = malloc(len);
384 die("Out of memory\n");
390 xrealloc(void *p, size_t len) {
391 if((p = realloc(p, len)) == NULL)
392 die("Out of memory\n");
398 xcalloc(size_t nmemb, size_t size) {
399 void *p = calloc(nmemb, size);
402 die("Out of memory\n");
408 smstrcat(char *src, ...)
414 len = slen = strlen(src);
416 va_start(fmtargs, src);
418 v = va_arg(fmtargs, char *);
425 p = ret = xmalloc(len+1);
426 memmove(p, src, slen);
429 va_start(fmtargs, src);
431 v = va_arg(fmtargs, char *);
446 utf8decode(char *s, long *u) {
452 if(~c & B7) { /* 0xxxxxxx */
455 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
456 *u = c&(B4|B3|B2|B1|B0);
458 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
459 *u = c&(B3|B2|B1|B0);
461 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
468 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
470 if((c & (B7|B6)) != B7) /* 10xxxxxx */
473 *u |= c & (B5|B4|B3|B2|B1|B0);
476 if((n == 1 && *u < 0x80) ||
477 (n == 2 && *u < 0x800) ||
478 (n == 3 && *u < 0x10000) ||
479 (*u >= 0xD800 && *u <= 0xDFFF)) {
491 utf8encode(long *u, char *s) {
499 *sp = uc; /* 0xxxxxxx */
501 } else if(*u < 0x800) {
502 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
504 } else if(uc < 0x10000) {
505 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
507 } else if(uc <= 0x10FFFF) {
508 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
514 for(i=n,++sp; i>0; --i,++sp)
515 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
527 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
528 UTF-8 otherwise return 0 */
530 isfullutf8(char *s, int b) {
538 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
540 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
542 ((b == 2) && (*c2&(B7|B6)) == B7))) {
544 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
546 ((b == 2) && (*c2&(B7|B6)) == B7) ||
547 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
560 } else if((c&(B7|B6|B5)) == (B7|B6)) {
562 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
571 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
572 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
576 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
577 if(sel.xtarget == None)
578 sel.xtarget = XA_STRING;
582 selected(int x, int y) {
585 if(sel.ey == y && sel.by == y) {
586 bx = MIN(sel.bx, sel.ex);
587 ex = MAX(sel.bx, sel.ex);
588 return BETWEEN(x, bx, ex);
591 return ((sel.b.y < y && y < sel.e.y)
592 || (y == sel.e.y && x <= sel.e.x))
593 || (y == sel.b.y && x >= sel.b.x
594 && (x <= sel.e.x || sel.b.y != sel.e.y));
598 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
600 *b = e->xbutton.button;
602 *x = X2COL(e->xbutton.x);
603 *y = Y2ROW(e->xbutton.y);
604 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
605 sel.b.y = MIN(sel.by, sel.ey);
606 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
607 sel.e.y = MAX(sel.by, sel.ey);
611 mousereport(XEvent *e) {
612 int x = X2COL(e->xbutton.x);
613 int y = Y2ROW(e->xbutton.y);
614 int button = e->xbutton.button;
615 int state = e->xbutton.state;
616 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
617 static int ob, ox, oy;
620 if(e->xbutton.type == MotionNotify) {
621 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
625 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
631 if(e->xbutton.type == ButtonPress) {
637 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
638 + (state & Mod4Mask ? 8 : 0)
639 + (state & ControlMask ? 16 : 0);
641 ttywrite(buf, sizeof(buf));
646 if(IS_SET(MODE_MOUSE)) {
648 } else if(e->xbutton.button == Button1) {
651 tsetdirt(sel.b.y, sel.e.y);
655 sel.ex = sel.bx = X2COL(e->xbutton.x);
656 sel.ey = sel.by = Y2ROW(e->xbutton.y);
663 int x, y, bufsize, is_selected = 0, size;
669 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
670 ptr = str = xmalloc(bufsize);
672 /* append every set & selected glyph to the selection */
673 for(y = 0; y < term.row; y++) {
674 for(x = 0; x < term.col; x++) {
675 gp = &term.line[y][x];
677 if(!(is_selected = selected(x, y)))
679 p = (gp->state & GLYPH_SET) ? gp->c : " ";
681 memcpy(ptr, p, size);
684 /* \n at the end of every selected line except for the last one */
685 if(is_selected && y < sel.e.y)
690 sel.alt = IS_SET(MODE_ALTSCREEN);
695 selnotify(XEvent *e) {
696 ulong nitems, ofs, rem;
703 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
704 False, AnyPropertyType, &type, &format,
705 &nitems, &rem, &data)) {
706 fprintf(stderr, "Clipboard allocation failed\n");
709 ttywrite((const char *) data, nitems * format / 8);
711 /* number of 32-bit chunks returned */
712 ofs += nitems * format / 32;
718 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
719 xw.win, CurrentTime);
722 void selclear(XEvent *e) {
726 tsetdirt(sel.b.y, sel.e.y);
730 selrequest(XEvent *e) {
731 XSelectionRequestEvent *xsre;
733 Atom xa_targets, string;
735 xsre = (XSelectionRequestEvent *) e;
736 xev.type = SelectionNotify;
737 xev.requestor = xsre->requestor;
738 xev.selection = xsre->selection;
739 xev.target = xsre->target;
740 xev.time = xsre->time;
744 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
745 if(xsre->target == xa_targets) {
746 /* respond with the supported type */
747 string = sel.xtarget;
748 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
749 XA_ATOM, 32, PropModeReplace,
750 (uchar *) &string, 1);
751 xev.property = xsre->property;
752 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
753 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
754 xsre->target, 8, PropModeReplace,
755 (uchar *) sel.clip, strlen(sel.clip));
756 xev.property = xsre->property;
759 /* all done, send a notification to the listener */
760 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
761 fprintf(stderr, "Error sending SelectionNotify event\n");
766 /* register the selection for both the clipboard and the primary */
772 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
774 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
775 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
779 brelease(XEvent *e) {
782 if(IS_SET(MODE_MOUSE)) {
787 if(e->xbutton.button == Button2) {
789 } else if(e->xbutton.button == Button1) {
791 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
792 term.dirty[sel.ey] = 1;
793 if(sel.bx == sel.ex && sel.by == sel.ey) {
795 gettimeofday(&now, NULL);
797 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
798 /* triple click on the line */
799 sel.b.x = sel.bx = 0;
800 sel.e.x = sel.ex = term.col;
801 sel.b.y = sel.e.y = sel.ey;
803 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
804 /* double click to select word */
806 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
807 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
811 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
812 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
816 sel.b.y = sel.e.y = sel.ey;
824 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
825 gettimeofday(&sel.tclick1, NULL);
830 int starty, endy, oldey, oldex;
832 if(IS_SET(MODE_MOUSE)) {
840 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
842 if(oldey != sel.ey || oldex != sel.ex) {
843 starty = MIN(oldey, sel.ey);
844 endy = MAX(oldey, sel.ey);
845 tsetdirt(starty, endy);
851 die(const char *errstr, ...) {
854 va_start(ap, errstr);
855 vfprintf(stderr, errstr, ap);
863 char *envshell = getenv("SHELL");
869 signal(SIGCHLD, SIG_DFL);
870 signal(SIGHUP, SIG_DFL);
871 signal(SIGINT, SIG_DFL);
872 signal(SIGQUIT, SIG_DFL);
873 signal(SIGTERM, SIG_DFL);
874 signal(SIGALRM, SIG_DFL);
876 DEFAULT(envshell, SHELL);
877 putenv("TERM="TNAME);
878 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
879 execvp(args[0], args);
887 if(waitpid(pid, &stat, 0) < 0)
888 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
890 if(WIFEXITED(stat)) {
891 exit(WEXITSTATUS(stat));
900 struct winsize w = {term.row, term.col, 0, 0};
902 /* seems to work fine on linux, openbsd and freebsd */
903 if(openpty(&m, &s, NULL, NULL, &w) < 0)
904 die("openpty failed: %s\n", SERRNO);
906 switch(pid = fork()) {
908 die("fork failed\n");
911 setsid(); /* create a new process group */
912 dup2(s, STDIN_FILENO);
913 dup2(s, STDOUT_FILENO);
914 dup2(s, STDERR_FILENO);
915 if(ioctl(s, TIOCSCTTY, NULL) < 0)
916 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
924 signal(SIGCHLD, sigchld);
926 if(!strcmp(opt_io, "-")) {
927 iofd = STDOUT_FILENO;
929 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
930 fprintf(stderr, "Error opening %s:%s\n",
931 opt_io, strerror(errno));
942 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
944 fprintf(stderr, "\n");
949 static char buf[BUFSIZ];
950 static int buflen = 0;
953 int charsize; /* size of utf8 char in bytes */
957 /* append read bytes to unprocessed bytes */
958 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
959 die("Couldn't read from shell: %s\n", SERRNO);
961 /* process every complete utf8 char */
964 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
965 charsize = utf8decode(ptr, &utf8c);
966 utf8encode(&utf8c, s);
972 /* keep any uncomplete utf8 char for the next call */
973 memmove(buf, ptr, buflen);
977 ttywrite(const char *s, size_t n) {
978 if(write(cmdfd, s, n) == -1)
979 die("write error on tty: %s\n", SERRNO);
990 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
991 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
995 tsetdirt(int top, int bot) {
998 LIMIT(top, 0, term.row-1);
999 LIMIT(bot, 0, term.row-1);
1001 for(i = top; i <= bot; i++)
1007 tsetdirt(0, term.row-1);
1014 if(mode == CURSOR_SAVE) {
1016 } else if(mode == CURSOR_LOAD) {
1026 term.c = (TCursor){{
1030 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1032 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1033 for(i = TAB; i < term.col; i += TAB)
1036 term.bot = term.row - 1;
1037 term.mode = MODE_WRAP;
1039 tclearregion(0, 0, term.col-1, term.row-1);
1043 tnew(int col, int row) {
1044 /* set screen size */
1047 term.line = xmalloc(term.row * sizeof(Line));
1048 term.alt = xmalloc(term.row * sizeof(Line));
1049 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1050 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1052 for(row = 0; row < term.row; row++) {
1053 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1054 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1055 term.dirty[row] = 0;
1057 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1064 Line *tmp = term.line;
1066 term.line = term.alt;
1068 term.mode ^= MODE_ALTSCREEN;
1073 tscrolldown(int orig, int n) {
1077 LIMIT(n, 0, term.bot-orig+1);
1079 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1081 for(i = term.bot; i >= orig+n; i--) {
1082 temp = term.line[i];
1083 term.line[i] = term.line[i-n];
1084 term.line[i-n] = temp;
1087 term.dirty[i-n] = 1;
1094 tscrollup(int orig, int n) {
1097 LIMIT(n, 0, term.bot-orig+1);
1099 tclearregion(0, orig, term.col-1, orig+n-1);
1101 for(i = orig; i <= term.bot-n; i++) {
1102 temp = term.line[i];
1103 term.line[i] = term.line[i+n];
1104 term.line[i+n] = temp;
1107 term.dirty[i+n] = 1;
1110 selscroll(orig, -n);
1114 selscroll(int orig, int n) {
1118 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1119 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1123 if(sel.by < term.top) {
1127 if(sel.ey > term.bot) {
1131 sel.b.y = sel.by, sel.b.x = sel.bx;
1132 sel.e.y = sel.ey, sel.e.x = sel.ex;
1137 tnewline(int first_col) {
1141 tscrollup(term.top, 1);
1145 tmoveto(first_col ? 0 : term.c.x, y);
1150 /* int noarg = 1; */
1151 char *p = csiescseq.buf;
1155 csiescseq.priv = 1, p++;
1157 while(p < csiescseq.buf+csiescseq.len) {
1158 while(isdigit(*p)) {
1159 csiescseq.arg[csiescseq.narg] *= 10;
1160 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1162 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1163 csiescseq.narg++, p++;
1165 csiescseq.mode = *p;
1174 tmoveto(int x, int y) {
1175 LIMIT(x, 0, term.col-1);
1176 LIMIT(y, 0, term.row-1);
1177 term.c.state &= ~CURSOR_WRAPNEXT;
1184 char *vt100_0[62] = { /* 0x41 - 0x7e */
1185 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1186 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1187 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1188 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1189 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1190 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1191 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1192 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1196 * The table is proudly stolen from rxvt.
1198 if(term.c.attr.mode & ATTR_GFX) {
1199 if(c[0] >= 0x41 && c[0] <= 0x7e
1200 && vt100_0[c[0] - 0x41]) {
1201 c = vt100_0[c[0] - 0x41];
1205 term.dirty[term.c.y] = 1;
1206 term.line[term.c.y][term.c.x] = term.c.attr;
1207 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1208 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1212 tclearregion(int x1, int y1, int x2, int y2) {
1216 temp = x1, x1 = x2, x2 = temp;
1218 temp = y1, y1 = y2, y2 = temp;
1220 LIMIT(x1, 0, term.col-1);
1221 LIMIT(x2, 0, term.col-1);
1222 LIMIT(y1, 0, term.row-1);
1223 LIMIT(y2, 0, term.row-1);
1225 for(y = y1; y <= y2; y++) {
1227 for(x = x1; x <= x2; x++)
1228 term.line[y][x].state = 0;
1233 tdeletechar(int n) {
1234 int src = term.c.x + n;
1236 int size = term.col - src;
1238 term.dirty[term.c.y] = 1;
1240 if(src >= term.col) {
1241 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1245 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1246 size * sizeof(Glyph));
1247 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1251 tinsertblank(int n) {
1254 int size = term.col - dst;
1256 term.dirty[term.c.y] = 1;
1258 if(dst >= term.col) {
1259 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1263 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1264 size * sizeof(Glyph));
1265 tclearregion(src, term.c.y, dst - 1, term.c.y);
1269 tinsertblankline(int n) {
1270 if(term.c.y < term.top || term.c.y > term.bot)
1273 tscrolldown(term.c.y, n);
1277 tdeleteline(int n) {
1278 if(term.c.y < term.top || term.c.y > term.bot)
1281 tscrollup(term.c.y, n);
1285 tsetattr(int *attr, int l) {
1288 for(i = 0; i < l; i++) {
1291 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1292 | ATTR_ITALIC | ATTR_BLINK);
1293 term.c.attr.fg = DefaultFG;
1294 term.c.attr.bg = DefaultBG;
1297 term.c.attr.mode |= ATTR_BOLD;
1299 case 3: /* enter standout (highlight) */
1300 term.c.attr.mode |= ATTR_ITALIC;
1303 term.c.attr.mode |= ATTR_UNDERLINE;
1306 term.c.attr.mode |= ATTR_BLINK;
1309 term.c.attr.mode |= ATTR_REVERSE;
1313 term.c.attr.mode &= ~ATTR_BOLD;
1315 case 23: /* leave standout (highlight) mode */
1316 term.c.attr.mode &= ~ATTR_ITALIC;
1319 term.c.attr.mode &= ~ATTR_UNDERLINE;
1322 term.c.attr.mode &= ~ATTR_BLINK;
1325 term.c.attr.mode &= ~ATTR_REVERSE;
1328 if(i + 2 < l && attr[i + 1] == 5) {
1330 if(BETWEEN(attr[i], 0, 255)) {
1331 term.c.attr.fg = attr[i];
1334 "erresc: bad fgcolor %d\n",
1339 "erresc(38): gfx attr %d unknown\n",
1344 term.c.attr.fg = DefaultFG;
1347 if(i + 2 < l && attr[i + 1] == 5) {
1349 if(BETWEEN(attr[i], 0, 255)) {
1350 term.c.attr.bg = attr[i];
1353 "erresc: bad bgcolor %d\n",
1358 "erresc(48): gfx attr %d unknown\n",
1363 term.c.attr.bg = DefaultBG;
1366 if(BETWEEN(attr[i], 30, 37)) {
1367 term.c.attr.fg = attr[i] - 30;
1368 } else if(BETWEEN(attr[i], 40, 47)) {
1369 term.c.attr.bg = attr[i] - 40;
1370 } else if(BETWEEN(attr[i], 90, 97)) {
1371 term.c.attr.fg = attr[i] - 90 + 8;
1372 } else if(BETWEEN(attr[i], 100, 107)) {
1373 term.c.attr.bg = attr[i] - 100 + 8;
1376 "erresc(default): gfx attr %d unknown\n",
1377 attr[i]), csidump();
1385 tsetscroll(int t, int b) {
1388 LIMIT(t, 0, term.row-1);
1389 LIMIT(b, 0, term.row-1);
1399 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1402 tsetmode(bool priv, bool set, int *args, int narg) {
1405 for(lim = args + narg; args < lim; ++args) {
1409 case 1: /* DECCKM -- Cursor key */
1410 MODBIT(term.mode, set, MODE_APPKEYPAD);
1412 case 5: /* DECSCNM -- Reverse video */
1414 MODBIT(term.mode, set, MODE_REVERSE);
1415 if(mode != term.mode)
1418 case 6: /* XXX: DECOM -- Origin */
1420 case 7: /* DECAWM -- Auto wrap */
1421 MODBIT(term.mode, set, MODE_WRAP);
1423 case 8: /* XXX: DECARM -- Auto repeat */
1425 case 0: /* Error (IGNORED) */
1426 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1429 MODBIT(term.c.state, !set, CURSOR_HIDE);
1431 case 1000: /* 1000,1002: enable xterm mouse report */
1432 MODBIT(term.mode, set, MODE_MOUSEBTN);
1435 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1437 case 1049: /* = 1047 and 1048 */
1440 if(IS_SET(MODE_ALTSCREEN))
1441 tclearregion(0, 0, term.col-1, term.row-1);
1442 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1443 (!set && IS_SET(MODE_ALTSCREEN))) {
1450 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1453 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1454 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1455 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1456 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1457 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1458 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1460 "erresc: unknown private set/reset mode %d\n",
1466 case 0: /* Error (IGNORED) */
1468 case 2: /* KAM -- keyboard action */
1469 MODBIT(term.mode, set, MODE_KBDLOCK);
1471 case 4: /* IRM -- Insertion-replacement */
1472 MODBIT(term.mode, set, MODE_INSERT);
1474 case 12: /* XXX: SRM -- Send/Receive */
1476 case 20: /* LNM -- Linefeed/new line */
1477 MODBIT(term.mode, set, MODE_CRLF);
1481 "erresc: unknown set/reset mode %d\n",
1493 switch(csiescseq.mode) {
1496 fprintf(stderr, "erresc: unknown csi ");
1500 case '@': /* ICH -- Insert <n> blank char */
1501 DEFAULT(csiescseq.arg[0], 1);
1502 tinsertblank(csiescseq.arg[0]);
1504 case 'A': /* CUU -- Cursor <n> Up */
1506 DEFAULT(csiescseq.arg[0], 1);
1507 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1509 case 'B': /* CUD -- Cursor <n> Down */
1510 DEFAULT(csiescseq.arg[0], 1);
1511 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1513 case 'C': /* CUF -- Cursor <n> Forward */
1515 DEFAULT(csiescseq.arg[0], 1);
1516 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1518 case 'D': /* CUB -- Cursor <n> Backward */
1519 DEFAULT(csiescseq.arg[0], 1);
1520 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1522 case 'E': /* CNL -- Cursor <n> Down and first col */
1523 DEFAULT(csiescseq.arg[0], 1);
1524 tmoveto(0, term.c.y+csiescseq.arg[0]);
1526 case 'F': /* CPL -- Cursor <n> Up and first col */
1527 DEFAULT(csiescseq.arg[0], 1);
1528 tmoveto(0, term.c.y-csiescseq.arg[0]);
1530 case 'g': /* TBC -- Tabulation clear */
1531 switch (csiescseq.arg[0]) {
1532 case 0: /* clear current tab stop */
1533 term.tabs[term.c.x] = 0;
1535 case 3: /* clear all the tabs */
1536 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1542 case 'G': /* CHA -- Move to <col> */
1544 DEFAULT(csiescseq.arg[0], 1);
1545 tmoveto(csiescseq.arg[0]-1, term.c.y);
1547 case 'H': /* CUP -- Move to <row> <col> */
1549 DEFAULT(csiescseq.arg[0], 1);
1550 DEFAULT(csiescseq.arg[1], 1);
1551 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1553 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1554 DEFAULT(csiescseq.arg[0], 1);
1555 while(csiescseq.arg[0]--)
1558 case 'J': /* ED -- Clear screen */
1560 switch(csiescseq.arg[0]) {
1562 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1563 if(term.c.y < term.row-1)
1564 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1568 tclearregion(0, 0, term.col-1, term.c.y-1);
1569 tclearregion(0, term.c.y, term.c.x, term.c.y);
1572 tclearregion(0, 0, term.col-1, term.row-1);
1578 case 'K': /* EL -- Clear line */
1579 switch(csiescseq.arg[0]) {
1581 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1584 tclearregion(0, term.c.y, term.c.x, term.c.y);
1587 tclearregion(0, term.c.y, term.col-1, term.c.y);
1591 case 'S': /* SU -- Scroll <n> line up */
1592 DEFAULT(csiescseq.arg[0], 1);
1593 tscrollup(term.top, csiescseq.arg[0]);
1595 case 'T': /* SD -- Scroll <n> line down */
1596 DEFAULT(csiescseq.arg[0], 1);
1597 tscrolldown(term.top, csiescseq.arg[0]);
1599 case 'L': /* IL -- Insert <n> blank lines */
1600 DEFAULT(csiescseq.arg[0], 1);
1601 tinsertblankline(csiescseq.arg[0]);
1603 case 'l': /* RM -- Reset Mode */
1604 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1606 case 'M': /* DL -- Delete <n> lines */
1607 DEFAULT(csiescseq.arg[0], 1);
1608 tdeleteline(csiescseq.arg[0]);
1610 case 'X': /* ECH -- Erase <n> char */
1611 DEFAULT(csiescseq.arg[0], 1);
1612 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1614 case 'P': /* DCH -- Delete <n> char */
1615 DEFAULT(csiescseq.arg[0], 1);
1616 tdeletechar(csiescseq.arg[0]);
1618 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1619 DEFAULT(csiescseq.arg[0], 1);
1620 while(csiescseq.arg[0]--)
1623 case 'd': /* VPA -- Move to <row> */
1624 DEFAULT(csiescseq.arg[0], 1);
1625 tmoveto(term.c.x, csiescseq.arg[0]-1);
1627 case 'h': /* SM -- Set terminal mode */
1628 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1630 case 'm': /* SGR -- Terminal attribute (color) */
1631 tsetattr(csiescseq.arg, csiescseq.narg);
1633 case 'r': /* DECSTBM -- Set Scrolling Region */
1634 if(csiescseq.priv) {
1637 DEFAULT(csiescseq.arg[0], 1);
1638 DEFAULT(csiescseq.arg[1], term.row);
1639 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1643 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1644 tcursor(CURSOR_SAVE);
1646 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1647 tcursor(CURSOR_LOAD);
1658 for(i = 0; i < csiescseq.len; i++) {
1659 c = csiescseq.buf[i] & 0xff;
1662 } else if(c == '\n') {
1664 } else if(c == '\r') {
1666 } else if(c == 0x1b) {
1669 printf("(%02x)", c);
1677 memset(&csiescseq, 0, sizeof(csiescseq));
1685 * TODO: make this being useful in case of color palette change.
1691 switch(strescseq.type) {
1692 case ']': /* OSC -- Operating System Command */
1698 * TODO: Handle special chars in string, like umlauts.
1701 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1705 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1707 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1710 fprintf(stderr, "erresc: unknown str ");
1715 case 'k': /* old title set compatibility */
1716 XStoreName(xw.dpy, xw.win, strescseq.buf);
1718 case 'P': /* DSC -- Device Control String */
1719 case '_': /* APC -- Application Program Command */
1720 case '^': /* PM -- Privacy Message */
1722 fprintf(stderr, "erresc: unknown str ");
1732 * TODO: Implement parsing like for CSI when required.
1733 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1743 printf("ESC%c", strescseq.type);
1744 for(i = 0; i < strescseq.len; i++) {
1745 c = strescseq.buf[i] & 0xff;
1748 } else if(c == '\n') {
1750 } else if(c == '\r') {
1752 } else if(c == 0x1b) {
1755 printf("(%02x)", c);
1763 memset(&strescseq, 0, sizeof(strescseq));
1767 tputtab(bool forward) {
1773 for(++x; x < term.col && !term.tabs[x]; ++x)
1778 for(--x; x > 0 && !term.tabs[x]; --x)
1781 tmoveto(x, term.c.y);
1785 tputc(char *c, int len) {
1787 bool control = ascii < '\x20' || ascii == 0177;
1790 write(iofd, c, len);
1792 * STR sequences must be checked before of anything
1793 * because it can use some control codes as part of the sequence
1795 if(term.esc & ESC_STR) {
1798 term.esc = ESC_START | ESC_STR_END;
1800 case '\a': /* backwards compatibility to xterm */
1805 strescseq.buf[strescseq.len++] = ascii;
1806 if(strescseq.len+1 >= STR_BUF_SIZ) {
1814 * Actions of control codes must be performed as soon they arrive
1815 * because they can be embedded inside a control sequence, and
1816 * they must not cause conflicts with sequences.
1824 tmoveto(term.c.x-1, term.c.y);
1827 tmoveto(0, term.c.y);
1832 /* go to first col if the mode is set */
1833 tnewline(IS_SET(MODE_CRLF));
1835 case '\a': /* BEL */
1836 if(!(xw.state & WIN_FOCUSED))
1839 case '\033': /* ESC */
1841 term.esc = ESC_START;
1843 case '\016': /* SO */
1844 term.c.attr.mode |= ATTR_GFX;
1846 case '\017': /* SI */
1847 term.c.attr.mode &= ~ATTR_GFX;
1849 case '\032': /* SUB */
1850 case '\030': /* CAN */
1853 case '\005': /* ENQ (IGNORED) */
1854 case '\000': /* NUL (IGNORED) */
1855 case '\021': /* XON (IGNORED) */
1856 case '\023': /* XOFF (IGNORED) */
1857 case 0177: /* DEL (IGNORED) */
1860 } else if(term.esc & ESC_START) {
1861 if(term.esc & ESC_CSI) {
1862 csiescseq.buf[csiescseq.len++] = ascii;
1863 if(BETWEEN(ascii, 0x40, 0x7E)
1864 || csiescseq.len >= ESC_BUF_SIZ) {
1866 csiparse(), csihandle();
1868 } else if(term.esc & ESC_STR_END) {
1872 } else if(term.esc & ESC_ALTCHARSET) {
1874 case '0': /* Line drawing set */
1875 term.c.attr.mode |= ATTR_GFX;
1877 case 'B': /* USASCII */
1878 term.c.attr.mode &= ~ATTR_GFX;
1880 case 'A': /* UK (IGNORED) */
1881 case '<': /* multinational charset (IGNORED) */
1882 case '5': /* Finnish (IGNORED) */
1883 case 'C': /* Finnish (IGNORED) */
1884 case 'K': /* German (IGNORED) */
1887 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1893 term.esc |= ESC_CSI;
1895 case 'P': /* DCS -- Device Control String */
1896 case '_': /* APC -- Application Program Command */
1897 case '^': /* PM -- Privacy Message */
1898 case ']': /* OSC -- Operating System Command */
1899 case 'k': /* old title set compatibility */
1901 strescseq.type = ascii;
1902 term.esc |= ESC_STR;
1904 case '(': /* set primary charset G0 */
1905 term.esc |= ESC_ALTCHARSET;
1907 case ')': /* set secondary charset G1 (IGNORED) */
1908 case '*': /* set tertiary charset G2 (IGNORED) */
1909 case '+': /* set quaternary charset G3 (IGNORED) */
1912 case 'D': /* IND -- Linefeed */
1913 if(term.c.y == term.bot) {
1914 tscrollup(term.top, 1);
1916 tmoveto(term.c.x, term.c.y+1);
1920 case 'E': /* NEL -- Next line */
1921 tnewline(1); /* always go to first col */
1924 case 'H': /* HTS -- Horizontal tab stop */
1925 term.tabs[term.c.x] = 1;
1928 case 'M': /* RI -- Reverse index */
1929 if(term.c.y == term.top) {
1930 tscrolldown(term.top, 1);
1932 tmoveto(term.c.x, term.c.y-1);
1936 case 'c': /* RIS -- Reset to inital state */
1941 case '=': /* DECPAM -- Application keypad */
1942 term.mode |= MODE_APPKEYPAD;
1945 case '>': /* DECPNM -- Normal keypad */
1946 term.mode &= ~MODE_APPKEYPAD;
1949 case '7': /* DECSC -- Save Cursor */
1950 tcursor(CURSOR_SAVE);
1953 case '8': /* DECRC -- Restore Cursor */
1954 tcursor(CURSOR_LOAD);
1957 case '\\': /* ST -- Stop */
1961 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1962 (uchar) ascii, isprint(ascii)? ascii:'.');
1967 * All characters which forms part of a sequence are not
1973 * Display control codes only if we are in graphic mode
1975 if(control && !(term.c.attr.mode & ATTR_GFX))
1977 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1979 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1980 tnewline(1); /* always go to first col */
1982 if(term.c.x+1 < term.col)
1983 tmoveto(term.c.x+1, term.c.y);
1985 term.c.state |= CURSOR_WRAPNEXT;
1989 tresize(int col, int row) {
1991 int minrow = MIN(row, term.row);
1992 int mincol = MIN(col, term.col);
1993 int slide = term.c.y - row + 1;
1996 if(col < 1 || row < 1)
1999 /* free unneeded rows */
2002 /* slide screen to keep cursor where we expect it -
2003 * tscrollup would work here, but we can optimize to
2004 * memmove because we're freeing the earlier lines */
2005 for(/* i = 0 */; i < slide; i++) {
2009 memmove(term.line, term.line + slide, row * sizeof(Line));
2010 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2012 for(i += row; i < term.row; i++) {
2017 /* resize to new height */
2018 term.line = xrealloc(term.line, row * sizeof(Line));
2019 term.alt = xrealloc(term.alt, row * sizeof(Line));
2020 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2021 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2023 /* resize each row to new width, zero-pad if needed */
2024 for(i = 0; i < minrow; i++) {
2026 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2027 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2028 for(x = mincol; x < col; x++) {
2029 term.line[i][x].state = 0;
2030 term.alt[i][x].state = 0;
2034 /* allocate any new rows */
2035 for(/* i == minrow */; i < row; i++) {
2037 term.line[i] = xcalloc(col, sizeof(Glyph));
2038 term.alt [i] = xcalloc(col, sizeof(Glyph));
2040 if(col > term.col) {
2041 bp = term.tabs + term.col;
2043 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2044 while(--bp > term.tabs && !*bp)
2046 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2049 /* update terminal size */
2050 term.col = col, term.row = row;
2051 /* make use of the LIMIT in tmoveto */
2052 tmoveto(term.c.x, term.c.y);
2053 /* reset scrolling region */
2054 tsetscroll(0, row-1);
2060 xresize(int col, int row) {
2061 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2062 xw.th = MAX(1, 2*BORDER + row * xw.ch);
2064 XftDrawChange(xw.xft_draw, xw.buf);
2070 XRenderColor xft_color = { .alpha = 0 };
2072 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2073 for(i = 0; i < LEN(colorname); i++) {
2076 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2077 die("Could not allocate color '%s'\n", colorname[i]);
2081 /* load colors [16-255] ; same colors as xterm */
2082 for(i = 16, r = 0; r < 6; r++) {
2083 for(g = 0; g < 6; g++) {
2084 for(b = 0; b < 6; b++) {
2085 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2086 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2087 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2088 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2089 die("Could not allocate color %d\n", i);
2096 for(r = 0; r < 24; r++, i++) {
2097 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2098 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2100 die("Could not allocate color %d\n", i);
2106 xtermclear(int col1, int row1, int col2, int row2) {
2107 XftDrawRect(xw.xft_draw,
2108 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2109 BORDER + col1 * xw.cw,
2110 BORDER + row1 * xw.ch,
2111 (col2-col1+1) * xw.cw,
2112 (row2-row1+1) * xw.ch);
2116 * Absolute coordinates.
2119 xclear(int x1, int y1, int x2, int y2) {
2120 XftDrawRect(xw.xft_draw,
2121 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2122 x1, y1, x2-x1, y2-y1);
2127 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2128 XWMHints wm = {.flags = InputHint, .input = 1};
2129 XSizeHints *sizeh = NULL;
2131 sizeh = XAllocSizeHints();
2132 if(xw.isfixed == False) {
2133 sizeh->flags = PSize | PResizeInc | PBaseSize;
2134 sizeh->height = xw.h;
2135 sizeh->width = xw.w;
2136 sizeh->height_inc = xw.ch;
2137 sizeh->width_inc = xw.cw;
2138 sizeh->base_height = 2*BORDER;
2139 sizeh->base_width = 2*BORDER;
2141 sizeh->flags = PMaxSize | PMinSize;
2142 sizeh->min_width = sizeh->max_width = xw.fw;
2143 sizeh->min_height = sizeh->max_height = xw.fh;
2146 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2151 xinitfont(Font *f, char *fontstr) {
2152 FcPattern *pattern, *match;
2155 pattern = FcNameParse((FcChar8 *)fontstr);
2157 die("st: can't open font %s\n", fontstr);
2159 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2160 FcPatternDestroy(pattern);
2162 die("st: can't open font %s\n", fontstr);
2163 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2164 FcPatternDestroy(match);
2165 die("st: can't open font %s.\n", fontstr);
2168 f->ascent = f->xft_set->ascent;
2169 f->descent = f->xft_set->descent;
2171 f->rbearing = f->xft_set->max_advance_width;
2173 f->height = f->xft_set->height;
2174 f->width = f->lbearing + f->rbearing;
2178 initfonts(char *fontstr) {
2181 xinitfont(&dc.font, fontstr);
2182 xw.cw = dc.font.width;
2183 xw.ch = dc.font.height;
2185 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2186 xinitfont(&dc.bfont, fstr);
2189 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2190 xinitfont(&dc.ifont, fstr);
2193 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2194 xinitfont(&dc.ibfont, fstr);
2200 XSetWindowAttributes attrs;
2203 int sw, sh, major, minor;
2205 if(!(xw.dpy = XOpenDisplay(NULL)))
2206 die("Can't open display\n");
2207 xw.scr = XDefaultScreen(xw.dpy);
2208 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2211 initfonts((opt_font != NULL)? opt_font : FONT);
2214 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2217 /* adjust fixed window geometry */
2219 sw = DisplayWidth(xw.dpy, xw.scr);
2220 sh = DisplayHeight(xw.dpy, xw.scr);
2222 xw.fx = sw + xw.fx - xw.fw - 1;
2224 xw.fy = sh + xw.fy - xw.fh - 1;
2229 /* window - default size */
2230 xw.h = 2*BORDER + term.row * xw.ch;
2231 xw.w = 2*BORDER + term.col * xw.cw;
2236 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2237 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2238 attrs.bit_gravity = NorthWestGravity;
2239 attrs.event_mask = FocusChangeMask | KeyPressMask
2240 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2241 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2242 attrs.colormap = xw.cmap;
2244 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2245 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2246 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2248 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2252 /* double buffering */
2253 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2254 die("Xdbe extension is not present\n");
2255 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2257 /* Xft rendering context */
2258 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2261 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2262 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2263 | XIMStatusNothing, XNClientWindow, xw.win,
2264 XNFocusWindow, xw.win, NULL);
2266 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2268 /* white cursor, black outline */
2269 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2270 XDefineCursor(xw.dpy, xw.win, cursor);
2271 XRecolorCursor(xw.dpy, cursor,
2272 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2273 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2275 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2276 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2277 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2280 XMapWindow(xw.dpy, xw.win);
2286 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2287 int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2288 width = charlen * xw.cw;
2289 Font *font = &dc.font;
2291 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2292 *temp, revfg, revbg;
2293 XRenderColor colfg, colbg;
2295 if(base.mode & ATTR_REVERSE)
2296 temp = fg, fg = bg, bg = temp;
2298 if(base.mode & ATTR_BOLD) {
2299 if(BETWEEN(base.fg, 0, 7)) {
2300 /* basic system colors */
2301 fg = &dc.xft_col[base.fg + 8];
2302 } else if(BETWEEN(base.fg, 16, 195)) {
2304 fg = &dc.xft_col[base.fg + 36];
2305 } else if(BETWEEN(base.fg, 232, 251)) {
2307 fg = &dc.xft_col[base.fg + 4];
2310 * Those ranges will not be brightened:
2311 * 8 - 15 – bright system colors
2312 * 196 - 231 – highest 256 color cube
2313 * 252 - 255 – brightest colors in greyscale
2318 if(base.mode & ATTR_ITALIC)
2320 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2323 if(IS_SET(MODE_REVERSE)) {
2324 if(fg == &dc.xft_col[DefaultFG]) {
2325 fg = &dc.xft_col[DefaultBG];
2327 colfg.red = ~fg->color.red;
2328 colfg.green = ~fg->color.green;
2329 colfg.blue = ~fg->color.blue;
2330 colfg.alpha = fg->color.alpha;
2331 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2335 if(bg == &dc.xft_col[DefaultBG]) {
2336 bg = &dc.xft_col[DefaultFG];
2338 colbg.red = ~bg->color.red;
2339 colbg.green = ~bg->color.green;
2340 colbg.blue = ~bg->color.blue;
2341 colbg.alpha = bg->color.alpha;
2342 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2347 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2349 width = extents.xOff;
2351 /* Intelligent cleaning up of the borders. */
2353 xclear(0, (y == 0)? 0 : winy, BORDER,
2354 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2356 if(x + charlen >= term.col-1) {
2357 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2358 (y == term.row-1)? xw.h : (winy + xw.ch));
2361 xclear(winx, 0, winx + width, BORDER);
2363 xclear(winx, winy + xw.ch, winx + width, xw.h);
2365 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2366 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2367 winy + font->ascent, (FcChar8 *)s, bytelen);
2369 if(base.mode & ATTR_UNDERLINE) {
2370 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2377 static int oldx = 0, oldy = 0;
2379 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2381 LIMIT(oldx, 0, term.col-1);
2382 LIMIT(oldy, 0, term.row-1);
2384 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2385 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2387 /* remove the old cursor */
2388 if(term.line[oldy][oldx].state & GLYPH_SET) {
2389 sl = utf8size(term.line[oldy][oldx].c);
2390 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2393 xtermclear(oldx, oldy, oldx, oldy);
2396 /* draw the new one */
2397 if(!(term.c.state & CURSOR_HIDE)) {
2398 if(!(xw.state & WIN_FOCUSED))
2401 if(IS_SET(MODE_REVERSE))
2402 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2405 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2406 oldx = term.c.x, oldy = term.c.y;
2412 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2417 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2421 XSync(xw.dpy, False); /* necessary for a good tput flash */
2422 nanosleep(&tv, NULL);
2427 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2429 drawregion(0, 0, term.col, term.row);
2430 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2434 drawregion(int x1, int y1, int x2, int y2) {
2435 int ic, ib, x, y, ox, sl;
2437 char buf[DRAW_BUF_SIZ];
2438 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2440 if((sel.alt && !alt) || (!sel.alt && alt))
2442 if(!(xw.state & WIN_VISIBLE))
2445 for(y = y1; y < y2; y++) {
2449 xtermclear(0, y, term.col, y);
2451 base = term.line[y][0];
2453 for(x = x1; x < x2; x++) {
2454 new = term.line[y][x];
2455 if(ena_sel && *(new.c) && selected(x, y))
2456 new.mode ^= ATTR_REVERSE;
2457 if(ib > 0 && (!(new.state & GLYPH_SET)
2458 || ATTRCMP(base, new)
2459 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2460 xdraws(buf, base, ox, y, ic, ib);
2463 if(new.state & GLYPH_SET) {
2468 sl = utf8size(new.c);
2469 memcpy(buf+ib, new.c, sl);
2475 xdraws(buf, base, ox, y, ic, ib);
2481 expose(XEvent *ev) {
2482 XExposeEvent *e = &ev->xexpose;
2484 if(xw.state & WIN_REDRAW) {
2486 xw.state &= ~WIN_REDRAW;
2491 visibility(XEvent *ev) {
2492 XVisibilityEvent *e = &ev->xvisibility;
2494 if(e->state == VisibilityFullyObscured) {
2495 xw.state &= ~WIN_VISIBLE;
2496 } else if(!(xw.state & WIN_VISIBLE)) {
2497 /* need a full redraw for next Expose, not just a buf copy */
2498 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2504 xw.state &= ~WIN_VISIBLE;
2508 xseturgency(int add) {
2509 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2511 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2512 XSetWMHints(xw.dpy, xw.win, h);
2518 if(ev->type == FocusIn) {
2519 xw.state |= WIN_FOCUSED;
2522 xw.state &= ~WIN_FOCUSED;
2527 kmap(KeySym k, uint state) {
2532 for(i = 0; i < LEN(key); i++) {
2535 if(key[i].k == k && ((state & mask) == mask
2536 || (mask == XK_NO_MOD && !state))) {
2537 return (char*)key[i].s;
2544 kpress(XEvent *ev) {
2545 XKeyEvent *e = &ev->xkey;
2554 if (IS_SET(MODE_KBDLOCK))
2557 meta = e->state & Mod1Mask;
2558 shift = e->state & ShiftMask;
2559 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2561 /* 1. custom keys from config.h */
2562 if((customkey = kmap(ksym, e->state))) {
2563 ttywrite(customkey, strlen(customkey));
2564 /* 2. hardcoded (overrides X lookup) */
2571 /* XXX: shift up/down doesn't work */
2572 sprintf(buf, "\033%c%c",
2573 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2574 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2582 if(IS_SET(MODE_CRLF)) {
2583 ttywrite("\r\n", 2);
2591 if(meta && len == 1)
2592 ttywrite("\033", 1);
2601 cmessage(XEvent *e) {
2603 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2604 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2605 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2606 xw.state |= WIN_FOCUSED;
2608 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2609 xw.state &= ~WIN_FOCUSED;
2611 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2612 /* Send SIGHUP to shell */
2622 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2625 xw.w = e->xconfigure.width;
2626 xw.h = e->xconfigure.height;
2627 col = (xw.w - 2*BORDER) / xw.cw;
2628 row = (xw.h - 2*BORDER) / xw.ch;
2629 if(col == term.col && row == term.row)
2641 int xfd = XConnectionNumber(xw.dpy), i;
2642 struct timeval drawtimeout, *tv = NULL;
2646 FD_SET(cmdfd, &rfd);
2648 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2651 die("select failed: %s\n", SERRNO);
2655 * Stop after a certain number of reads so the user does not
2656 * feel like the system is stuttering.
2658 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2662 * Just wait a bit so it isn't disturbing the
2663 * user and the system is able to write something.
2665 drawtimeout.tv_sec = 0;
2666 drawtimeout.tv_usec = 5;
2673 while(XPending(xw.dpy)) {
2674 XNextEvent(xw.dpy, &ev);
2675 if(XFilterEvent(&ev, xw.win))
2677 if(handler[ev.type])
2678 (handler[ev.type])(&ev);
2687 main(int argc, char *argv[]) {
2688 int i, bitm, xr, yr;
2691 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2694 for(i = 1; i < argc; i++) {
2695 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2698 opt_class = argv[i];
2701 /* eat every remaining arguments */
2713 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2718 if(bitm & WidthValue)
2720 if(bitm & HeightValue)
2722 if(bitm & XNegative && xw.fx == 0)
2724 if(bitm & XNegative && xw.fy == 0)
2727 if(xw.fh != 0 && xw.fw != 0)
2736 opt_title = argv[i];
2743 opt_embed = argv[i];
2749 setlocale(LC_CTYPE, "");