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... */
227 struct {int x, y;} b, e;
231 struct timeval tclick1;
232 struct timeval tclick2;
248 /* Drawing Context */
250 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
252 Font font, bfont, ifont, ibfont;
255 static void die(const char *, ...);
256 static void draw(void);
257 static void redraw(void);
258 static void drawregion(int, int, int, int);
259 static void execsh(void);
260 static void sigchld(int);
261 static void run(void);
263 static void csidump(void);
264 static void csihandle(void);
265 static void csiparse(void);
266 static void csireset(void);
267 static void strdump(void);
268 static void strhandle(void);
269 static void strparse(void);
270 static void strreset(void);
272 static void tclearregion(int, int, int, int);
273 static void tcursor(int);
274 static void tdeletechar(int);
275 static void tdeleteline(int);
276 static void tinsertblank(int);
277 static void tinsertblankline(int);
278 static void tmoveto(int, int);
279 static void tnew(int, int);
280 static void tnewline(int);
281 static void tputtab(bool);
282 static void tputc(char *, int);
283 static void treset(void);
284 static int tresize(int, int);
285 static void tscrollup(int, int);
286 static void tscrolldown(int, int);
287 static void tsetattr(int*, int);
288 static void tsetchar(char*);
289 static void tsetscroll(int, int);
290 static void tswapscreen(void);
291 static void tsetdirt(int, int);
292 static void tsetmode(bool, bool, int *, int);
293 static void tfulldirt(void);
295 static void ttynew(void);
296 static void ttyread(void);
297 static void ttyresize(void);
298 static void ttywrite(const char *, size_t);
300 static void xdraws(char *, Glyph, int, int, int, int);
301 static void xhints(void);
302 static void xclear(int, int, int, int);
303 static void xclearborders(void);
304 static void xdrawcursor(void);
305 static void xinit(void);
306 static void xloadcols(void);
307 static void xresettitle(void);
308 static void xseturgency(int);
309 static void xsetsel(char*);
310 static void xtermclear(int, int, int, int);
311 static void xresize(int, int);
313 static void expose(XEvent *);
314 static void visibility(XEvent *);
315 static void unmap(XEvent *);
316 static char *kmap(KeySym, uint);
317 static void kpress(XEvent *);
318 static void cmessage(XEvent *);
319 static void resize(XEvent *);
320 static void focus(XEvent *);
321 static void brelease(XEvent *);
322 static void bpress(XEvent *);
323 static void bmotion(XEvent *);
324 static void selnotify(XEvent *);
325 static void selclear(XEvent *);
326 static void selrequest(XEvent *);
328 static void selinit(void);
329 static inline bool selected(int, int);
330 static void selcopy(void);
331 static void selpaste(void);
332 static void selscroll(int, int);
334 static int utf8decode(char *, long *);
335 static int utf8encode(long *, char *);
336 static int utf8size(char *);
337 static int isfullutf8(char *, int);
339 static void *xmalloc(size_t);
340 static void *xrealloc(void *, size_t);
341 static void *xcalloc(size_t nmemb, size_t size);
342 static char *smstrcat(char *, ...);
344 static void (*handler[LASTEvent])(XEvent *) = {
346 [ClientMessage] = cmessage,
347 [ConfigureNotify] = resize,
348 [VisibilityNotify] = visibility,
349 [UnmapNotify] = unmap,
353 [MotionNotify] = bmotion,
354 [ButtonPress] = bpress,
355 [ButtonRelease] = brelease,
356 [SelectionClear] = selclear,
357 [SelectionNotify] = selnotify,
358 [SelectionRequest] = selrequest,
365 static CSIEscape csiescseq;
366 static STREscape strescseq;
369 static Selection sel;
370 static int iofd = -1;
371 static char **opt_cmd = NULL;
372 static char *opt_io = NULL;
373 static char *opt_title = NULL;
374 static char *opt_embed = NULL;
375 static char *opt_class = NULL;
376 static char *opt_font = NULL;
379 xmalloc(size_t len) {
380 void *p = malloc(len);
383 die("Out of memory\n");
389 xrealloc(void *p, size_t len) {
390 if((p = realloc(p, len)) == NULL)
391 die("Out of memory\n");
397 xcalloc(size_t nmemb, size_t size) {
398 void *p = calloc(nmemb, size);
401 die("Out of memory\n");
407 smstrcat(char *src, ...)
413 len = slen = strlen(src);
415 va_start(fmtargs, src);
417 v = va_arg(fmtargs, char *);
424 p = ret = xmalloc(len+1);
425 memmove(p, src, slen);
428 va_start(fmtargs, src);
430 v = va_arg(fmtargs, char *);
445 utf8decode(char *s, long *u) {
451 if(~c & B7) { /* 0xxxxxxx */
454 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
455 *u = c&(B4|B3|B2|B1|B0);
457 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
458 *u = c&(B3|B2|B1|B0);
460 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
467 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
469 if((c & (B7|B6)) != B7) /* 10xxxxxx */
472 *u |= c & (B5|B4|B3|B2|B1|B0);
475 if((n == 1 && *u < 0x80) ||
476 (n == 2 && *u < 0x800) ||
477 (n == 3 && *u < 0x10000) ||
478 (*u >= 0xD800 && *u <= 0xDFFF)) {
490 utf8encode(long *u, char *s) {
498 *sp = uc; /* 0xxxxxxx */
500 } else if(*u < 0x800) {
501 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
503 } else if(uc < 0x10000) {
504 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
506 } else if(uc <= 0x10FFFF) {
507 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
513 for(i=n,++sp; i>0; --i,++sp)
514 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
526 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
527 UTF-8 otherwise return 0 */
529 isfullutf8(char *s, int b) {
537 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
539 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
541 ((b == 2) && (*c2&(B7|B6)) == B7))) {
543 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
545 ((b == 2) && (*c2&(B7|B6)) == B7) ||
546 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
559 } else if((c&(B7|B6|B5)) == (B7|B6)) {
561 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
570 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
571 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
575 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
576 if(sel.xtarget == None)
577 sel.xtarget = XA_STRING;
581 selected(int x, int y) {
584 if(sel.ey == y && sel.by == y) {
585 bx = MIN(sel.bx, sel.ex);
586 ex = MAX(sel.bx, sel.ex);
587 return BETWEEN(x, bx, ex);
590 return ((sel.b.y < y&&y < sel.e.y)
591 || (y==sel.e.y && x<=sel.e.x))
592 || (y==sel.b.y && x>=sel.b.x
593 && (x<=sel.e.x || sel.b.y!=sel.e.y));
597 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
599 *b = e->xbutton.button;
601 *x = X2COL(e->xbutton.x);
602 *y = Y2ROW(e->xbutton.y);
603 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
604 sel.b.y = MIN(sel.by, sel.ey);
605 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
606 sel.e.y = MAX(sel.by, sel.ey);
610 mousereport(XEvent *e) {
611 int x = X2COL(e->xbutton.x);
612 int y = Y2ROW(e->xbutton.y);
613 int button = e->xbutton.button;
614 int state = e->xbutton.state;
615 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
616 static int ob, ox, oy;
619 if(e->xbutton.type == MotionNotify) {
620 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
624 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
630 if(e->xbutton.type == ButtonPress) {
636 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
637 + (state & Mod4Mask ? 8 : 0)
638 + (state & ControlMask ? 16 : 0);
640 ttywrite(buf, sizeof(buf));
645 if(IS_SET(MODE_MOUSE)) {
647 } else if(e->xbutton.button == Button1) {
650 tsetdirt(sel.b.y, sel.e.y);
654 sel.ex = sel.bx = X2COL(e->xbutton.x);
655 sel.ey = sel.by = Y2ROW(e->xbutton.y);
662 int x, y, bufsize, is_selected = 0, size;
668 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
669 ptr = str = xmalloc(bufsize);
671 /* append every set & selected glyph to the selection */
672 for(y = 0; y < term.row; y++) {
673 for(x = 0; x < term.col; x++) {
674 gp = &term.line[y][x];
676 if(!(is_selected = selected(x, y)))
678 p = (gp->state & GLYPH_SET) ? gp->c : " ";
680 memcpy(ptr, p, size);
683 /* \n at the end of every selected line except for the last one */
684 if(is_selected && y < sel.e.y)
689 sel.alt = IS_SET(MODE_ALTSCREEN);
694 selnotify(XEvent *e) {
695 ulong nitems, ofs, rem;
702 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
703 False, AnyPropertyType, &type, &format,
704 &nitems, &rem, &data)) {
705 fprintf(stderr, "Clipboard allocation failed\n");
708 ttywrite((const char *) data, nitems * format / 8);
710 /* number of 32-bit chunks returned */
711 ofs += nitems * format / 32;
717 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
718 xw.win, CurrentTime);
721 void selclear(XEvent *e) {
725 tsetdirt(sel.b.y, sel.e.y);
729 selrequest(XEvent *e) {
730 XSelectionRequestEvent *xsre;
732 Atom xa_targets, string;
734 xsre = (XSelectionRequestEvent *) e;
735 xev.type = SelectionNotify;
736 xev.requestor = xsre->requestor;
737 xev.selection = xsre->selection;
738 xev.target = xsre->target;
739 xev.time = xsre->time;
743 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
744 if(xsre->target == xa_targets) {
745 /* respond with the supported type */
746 string = sel.xtarget;
747 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
748 XA_ATOM, 32, PropModeReplace,
749 (uchar *) &string, 1);
750 xev.property = xsre->property;
751 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
752 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
753 xsre->target, 8, PropModeReplace,
754 (uchar *) sel.clip, strlen(sel.clip));
755 xev.property = xsre->property;
758 /* all done, send a notification to the listener */
759 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
760 fprintf(stderr, "Error sending SelectionNotify event\n");
765 /* register the selection for both the clipboard and the primary */
771 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
773 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
774 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
778 brelease(XEvent *e) {
781 if(IS_SET(MODE_MOUSE)) {
786 if(e->xbutton.button == Button2) {
788 } else if(e->xbutton.button == Button1) {
790 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
791 term.dirty[sel.ey] = 1;
792 if(sel.bx == sel.ex && sel.by == sel.ey) {
794 gettimeofday(&now, NULL);
796 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
797 /* triple click on the line */
798 sel.b.x = sel.bx = 0;
799 sel.e.x = sel.ex = term.col;
800 sel.b.y = sel.e.y = sel.ey;
802 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
803 /* double click to select word */
805 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
806 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
810 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
811 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
815 sel.b.y = sel.e.y = sel.ey;
823 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
824 gettimeofday(&sel.tclick1, NULL);
829 int starty, endy, oldey, oldex;
831 if(IS_SET(MODE_MOUSE)) {
839 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
841 if(oldey != sel.ey || oldex != sel.ex) {
842 starty = MIN(oldey, sel.ey);
843 endy = MAX(oldey, sel.ey);
844 tsetdirt(starty, endy);
850 die(const char *errstr, ...) {
853 va_start(ap, errstr);
854 vfprintf(stderr, errstr, ap);
862 char *envshell = getenv("SHELL");
868 signal(SIGCHLD, SIG_DFL);
869 signal(SIGHUP, SIG_DFL);
870 signal(SIGINT, SIG_DFL);
871 signal(SIGQUIT, SIG_DFL);
872 signal(SIGTERM, SIG_DFL);
873 signal(SIGALRM, SIG_DFL);
875 DEFAULT(envshell, SHELL);
876 putenv("TERM="TNAME);
877 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
878 execvp(args[0], args);
886 if(waitpid(pid, &stat, 0) < 0)
887 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
889 if(WIFEXITED(stat)) {
890 exit(WEXITSTATUS(stat));
899 struct winsize w = {term.row, term.col, 0, 0};
901 /* seems to work fine on linux, openbsd and freebsd */
902 if(openpty(&m, &s, NULL, NULL, &w) < 0)
903 die("openpty failed: %s\n", SERRNO);
905 switch(pid = fork()) {
907 die("fork failed\n");
910 setsid(); /* create a new process group */
911 dup2(s, STDIN_FILENO);
912 dup2(s, STDOUT_FILENO);
913 dup2(s, STDERR_FILENO);
914 if(ioctl(s, TIOCSCTTY, NULL) < 0)
915 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
923 signal(SIGCHLD, sigchld);
925 if(!strcmp(opt_io, "-")) {
926 iofd = STDOUT_FILENO;
928 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
929 fprintf(stderr, "Error opening %s:%s\n",
930 opt_io, strerror(errno));
941 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
943 fprintf(stderr, "\n");
948 static char buf[BUFSIZ];
949 static int buflen = 0;
952 int charsize; /* size of utf8 char in bytes */
956 /* append read bytes to unprocessed bytes */
957 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
958 die("Couldn't read from shell: %s\n", SERRNO);
960 /* process every complete utf8 char */
963 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
964 charsize = utf8decode(ptr, &utf8c);
965 utf8encode(&utf8c, s);
971 /* keep any uncomplete utf8 char for the next call */
972 memmove(buf, ptr, buflen);
976 ttywrite(const char *s, size_t n) {
977 if(write(cmdfd, s, n) == -1)
978 die("write error on tty: %s\n", SERRNO);
989 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
990 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
994 tsetdirt(int top, int bot) {
997 LIMIT(top, 0, term.row-1);
998 LIMIT(bot, 0, term.row-1);
1000 for(i = top; i <= bot; i++)
1006 tsetdirt(0, term.row-1);
1013 if(mode == CURSOR_SAVE) {
1015 } else if(mode == CURSOR_LOAD) {
1025 term.c = (TCursor){{
1029 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1031 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1032 for(i = TAB; i < term.col; i += TAB)
1034 term.top = 0, term.bot = term.row - 1;
1035 term.mode = MODE_WRAP;
1037 tclearregion(0, 0, term.col-1, term.row-1);
1041 tnew(int col, int row) {
1042 /* set screen size */
1043 term.row = row, term.col = col;
1044 term.line = xmalloc(term.row * sizeof(Line));
1045 term.alt = xmalloc(term.row * sizeof(Line));
1046 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1047 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1049 for(row = 0; row < term.row; row++) {
1050 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1051 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1052 term.dirty[row] = 0;
1054 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1061 Line *tmp = term.line;
1063 term.line = term.alt;
1065 term.mode ^= MODE_ALTSCREEN;
1070 tscrolldown(int orig, int n) {
1074 LIMIT(n, 0, term.bot-orig+1);
1076 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1078 for(i = term.bot; i >= orig+n; i--) {
1079 temp = term.line[i];
1080 term.line[i] = term.line[i-n];
1081 term.line[i-n] = temp;
1084 term.dirty[i-n] = 1;
1091 tscrollup(int orig, int n) {
1094 LIMIT(n, 0, term.bot-orig+1);
1096 tclearregion(0, orig, term.col-1, orig+n-1);
1098 for(i = orig; i <= term.bot-n; i++) {
1099 temp = term.line[i];
1100 term.line[i] = term.line[i+n];
1101 term.line[i+n] = temp;
1104 term.dirty[i+n] = 1;
1107 selscroll(orig, -n);
1111 selscroll(int orig, int n) {
1115 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1116 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1120 if(sel.by < term.top) {
1124 if(sel.ey > term.bot) {
1128 sel.b.y = sel.by, sel.b.x = sel.bx;
1129 sel.e.y = sel.ey, sel.e.x = sel.ex;
1134 tnewline(int first_col) {
1138 tscrollup(term.top, 1);
1142 tmoveto(first_col ? 0 : term.c.x, y);
1147 /* int noarg = 1; */
1148 char *p = csiescseq.buf;
1152 csiescseq.priv = 1, p++;
1154 while(p < csiescseq.buf+csiescseq.len) {
1155 while(isdigit(*p)) {
1156 csiescseq.arg[csiescseq.narg] *= 10;
1157 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1159 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1160 csiescseq.narg++, p++;
1162 csiescseq.mode = *p;
1171 tmoveto(int x, int y) {
1172 LIMIT(x, 0, term.col-1);
1173 LIMIT(y, 0, term.row-1);
1174 term.c.state &= ~CURSOR_WRAPNEXT;
1181 char *vt100_0[62] = { /* 0x41 - 0x7e */
1182 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1183 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1184 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1185 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1186 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1187 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1188 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1189 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1193 * The table is proudly stolen from rxvt.
1195 if(term.c.attr.mode & ATTR_GFX) {
1196 if(c[0] >= 0x41 && c[0] <= 0x7e
1197 && vt100_0[c[0] - 0x41]) {
1198 c = vt100_0[c[0] - 0x41];
1202 term.dirty[term.c.y] = 1;
1203 term.line[term.c.y][term.c.x] = term.c.attr;
1204 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1205 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1209 tclearregion(int x1, int y1, int x2, int y2) {
1213 temp = x1, x1 = x2, x2 = temp;
1215 temp = y1, y1 = y2, y2 = temp;
1217 LIMIT(x1, 0, term.col-1);
1218 LIMIT(x2, 0, term.col-1);
1219 LIMIT(y1, 0, term.row-1);
1220 LIMIT(y2, 0, term.row-1);
1222 for(y = y1; y <= y2; y++) {
1224 for(x = x1; x <= x2; x++)
1225 term.line[y][x].state = 0;
1230 tdeletechar(int n) {
1231 int src = term.c.x + n;
1233 int size = term.col - src;
1235 term.dirty[term.c.y] = 1;
1237 if(src >= term.col) {
1238 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1242 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1243 size * sizeof(Glyph));
1244 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1248 tinsertblank(int n) {
1251 int size = term.col - dst;
1253 term.dirty[term.c.y] = 1;
1255 if(dst >= term.col) {
1256 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1260 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1261 size * sizeof(Glyph));
1262 tclearregion(src, term.c.y, dst - 1, term.c.y);
1266 tinsertblankline(int n) {
1267 if(term.c.y < term.top || term.c.y > term.bot)
1270 tscrolldown(term.c.y, n);
1274 tdeleteline(int n) {
1275 if(term.c.y < term.top || term.c.y > term.bot)
1278 tscrollup(term.c.y, n);
1282 tsetattr(int *attr, int l) {
1285 for(i = 0; i < l; i++) {
1288 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1289 | ATTR_ITALIC | ATTR_BLINK);
1290 term.c.attr.fg = DefaultFG;
1291 term.c.attr.bg = DefaultBG;
1294 term.c.attr.mode |= ATTR_BOLD;
1296 case 3: /* enter standout (highlight) */
1297 term.c.attr.mode |= ATTR_ITALIC;
1300 term.c.attr.mode |= ATTR_UNDERLINE;
1303 term.c.attr.mode |= ATTR_BLINK;
1306 term.c.attr.mode |= ATTR_REVERSE;
1310 term.c.attr.mode &= ~ATTR_BOLD;
1312 case 23: /* leave standout (highlight) mode */
1313 term.c.attr.mode &= ~ATTR_ITALIC;
1316 term.c.attr.mode &= ~ATTR_UNDERLINE;
1319 term.c.attr.mode &= ~ATTR_BLINK;
1322 term.c.attr.mode &= ~ATTR_REVERSE;
1325 if(i + 2 < l && attr[i + 1] == 5) {
1327 if(BETWEEN(attr[i], 0, 255)) {
1328 term.c.attr.fg = attr[i];
1331 "erresc: bad fgcolor %d\n",
1336 "erresc(38): gfx attr %d unknown\n",
1341 term.c.attr.fg = DefaultFG;
1344 if(i + 2 < l && attr[i + 1] == 5) {
1346 if(BETWEEN(attr[i], 0, 255)) {
1347 term.c.attr.bg = attr[i];
1350 "erresc: bad bgcolor %d\n",
1355 "erresc(48): gfx attr %d unknown\n",
1360 term.c.attr.bg = DefaultBG;
1363 if(BETWEEN(attr[i], 30, 37)) {
1364 term.c.attr.fg = attr[i] - 30;
1365 } else if(BETWEEN(attr[i], 40, 47)) {
1366 term.c.attr.bg = attr[i] - 40;
1367 } else if(BETWEEN(attr[i], 90, 97)) {
1368 term.c.attr.fg = attr[i] - 90 + 8;
1369 } else if(BETWEEN(attr[i], 100, 107)) {
1370 term.c.attr.bg = attr[i] - 100 + 8;
1373 "erresc(default): gfx attr %d unknown\n",
1374 attr[i]), csidump();
1382 tsetscroll(int t, int b) {
1385 LIMIT(t, 0, term.row-1);
1386 LIMIT(b, 0, term.row-1);
1396 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1399 tsetmode(bool priv, bool set, int *args, int narg) {
1402 for(lim = args + narg; args < lim; ++args) {
1406 case 1: /* DECCKM -- Cursor key */
1407 MODBIT(term.mode, set, MODE_APPKEYPAD);
1409 case 5: /* DECSCNM -- Reverse video */
1411 MODBIT(term.mode, set, MODE_REVERSE);
1412 if(mode != term.mode)
1415 case 6: /* XXX: DECOM -- Origin */
1417 case 7: /* DECAWM -- Auto wrap */
1418 MODBIT(term.mode, set, MODE_WRAP);
1420 case 8: /* XXX: DECARM -- Auto repeat */
1422 case 0: /* Error (IGNORED) */
1423 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1426 MODBIT(term.c.state, !set, CURSOR_HIDE);
1428 case 1000: /* 1000,1002: enable xterm mouse report */
1429 MODBIT(term.mode, set, MODE_MOUSEBTN);
1432 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1434 case 1049: /* = 1047 and 1048 */
1437 if(IS_SET(MODE_ALTSCREEN))
1438 tclearregion(0, 0, term.col-1, term.row-1);
1439 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1440 (!set && IS_SET(MODE_ALTSCREEN))) {
1447 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1450 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1451 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1452 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1453 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1454 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1455 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1457 "erresc: unknown private set/reset mode %d\n",
1463 case 0: /* Error (IGNORED) */
1465 case 2: /* KAM -- keyboard action */
1466 MODBIT(term.mode, set, MODE_KBDLOCK);
1468 case 4: /* IRM -- Insertion-replacement */
1469 MODBIT(term.mode, set, MODE_INSERT);
1471 case 12: /* XXX: SRM -- Send/Receive */
1473 case 20: /* LNM -- Linefeed/new line */
1474 MODBIT(term.mode, set, MODE_CRLF);
1478 "erresc: unknown set/reset mode %d\n",
1490 switch(csiescseq.mode) {
1493 fprintf(stderr, "erresc: unknown csi ");
1497 case '@': /* ICH -- Insert <n> blank char */
1498 DEFAULT(csiescseq.arg[0], 1);
1499 tinsertblank(csiescseq.arg[0]);
1501 case 'A': /* CUU -- Cursor <n> Up */
1503 DEFAULT(csiescseq.arg[0], 1);
1504 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1506 case 'B': /* CUD -- Cursor <n> Down */
1507 DEFAULT(csiescseq.arg[0], 1);
1508 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1510 case 'C': /* CUF -- Cursor <n> Forward */
1512 DEFAULT(csiescseq.arg[0], 1);
1513 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1515 case 'D': /* CUB -- Cursor <n> Backward */
1516 DEFAULT(csiescseq.arg[0], 1);
1517 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1519 case 'E': /* CNL -- Cursor <n> Down and first col */
1520 DEFAULT(csiescseq.arg[0], 1);
1521 tmoveto(0, term.c.y+csiescseq.arg[0]);
1523 case 'F': /* CPL -- Cursor <n> Up and first col */
1524 DEFAULT(csiescseq.arg[0], 1);
1525 tmoveto(0, term.c.y-csiescseq.arg[0]);
1527 case 'g': /* TBC -- Tabulation clear */
1528 switch (csiescseq.arg[0]) {
1529 case 0: /* clear current tab stop */
1530 term.tabs[term.c.x] = 0;
1532 case 3: /* clear all the tabs */
1533 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1539 case 'G': /* CHA -- Move to <col> */
1541 DEFAULT(csiescseq.arg[0], 1);
1542 tmoveto(csiescseq.arg[0]-1, term.c.y);
1544 case 'H': /* CUP -- Move to <row> <col> */
1546 DEFAULT(csiescseq.arg[0], 1);
1547 DEFAULT(csiescseq.arg[1], 1);
1548 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1550 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1551 DEFAULT(csiescseq.arg[0], 1);
1552 while(csiescseq.arg[0]--)
1555 case 'J': /* ED -- Clear screen */
1557 switch(csiescseq.arg[0]) {
1559 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1560 if(term.c.y < term.row-1)
1561 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1565 tclearregion(0, 0, term.col-1, term.c.y-1);
1566 tclearregion(0, term.c.y, term.c.x, term.c.y);
1569 tclearregion(0, 0, term.col-1, term.row-1);
1575 case 'K': /* EL -- Clear line */
1576 switch(csiescseq.arg[0]) {
1578 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1581 tclearregion(0, term.c.y, term.c.x, term.c.y);
1584 tclearregion(0, term.c.y, term.col-1, term.c.y);
1588 case 'S': /* SU -- Scroll <n> line up */
1589 DEFAULT(csiescseq.arg[0], 1);
1590 tscrollup(term.top, csiescseq.arg[0]);
1592 case 'T': /* SD -- Scroll <n> line down */
1593 DEFAULT(csiescseq.arg[0], 1);
1594 tscrolldown(term.top, csiescseq.arg[0]);
1596 case 'L': /* IL -- Insert <n> blank lines */
1597 DEFAULT(csiescseq.arg[0], 1);
1598 tinsertblankline(csiescseq.arg[0]);
1600 case 'l': /* RM -- Reset Mode */
1601 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1603 case 'M': /* DL -- Delete <n> lines */
1604 DEFAULT(csiescseq.arg[0], 1);
1605 tdeleteline(csiescseq.arg[0]);
1607 case 'X': /* ECH -- Erase <n> char */
1608 DEFAULT(csiescseq.arg[0], 1);
1609 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1611 case 'P': /* DCH -- Delete <n> char */
1612 DEFAULT(csiescseq.arg[0], 1);
1613 tdeletechar(csiescseq.arg[0]);
1615 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1616 DEFAULT(csiescseq.arg[0], 1);
1617 while(csiescseq.arg[0]--)
1620 case 'd': /* VPA -- Move to <row> */
1621 DEFAULT(csiescseq.arg[0], 1);
1622 tmoveto(term.c.x, csiescseq.arg[0]-1);
1624 case 'h': /* SM -- Set terminal mode */
1625 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1627 case 'm': /* SGR -- Terminal attribute (color) */
1628 tsetattr(csiescseq.arg, csiescseq.narg);
1630 case 'r': /* DECSTBM -- Set Scrolling Region */
1631 if(csiescseq.priv) {
1634 DEFAULT(csiescseq.arg[0], 1);
1635 DEFAULT(csiescseq.arg[1], term.row);
1636 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1640 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1641 tcursor(CURSOR_SAVE);
1643 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1644 tcursor(CURSOR_LOAD);
1655 for(i = 0; i < csiescseq.len; i++) {
1656 c = csiescseq.buf[i] & 0xff;
1659 } else if(c == '\n') {
1661 } else if(c == '\r') {
1663 } else if(c == 0x1b) {
1666 printf("(%02x)", c);
1674 memset(&csiescseq, 0, sizeof(csiescseq));
1682 * TODO: make this being useful in case of color palette change.
1688 switch(strescseq.type) {
1689 case ']': /* OSC -- Operating System Command */
1695 * TODO: Handle special chars in string, like umlauts.
1698 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1702 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1704 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1707 fprintf(stderr, "erresc: unknown str ");
1712 case 'k': /* old title set compatibility */
1713 XStoreName(xw.dpy, xw.win, strescseq.buf);
1715 case 'P': /* DSC -- Device Control String */
1716 case '_': /* APC -- Application Program Command */
1717 case '^': /* PM -- Privacy Message */
1719 fprintf(stderr, "erresc: unknown str ");
1729 * TODO: Implement parsing like for CSI when required.
1730 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1740 printf("ESC%c", strescseq.type);
1741 for(i = 0; i < strescseq.len; i++) {
1742 c = strescseq.buf[i] & 0xff;
1745 } else if(c == '\n') {
1747 } else if(c == '\r') {
1749 } else if(c == 0x1b) {
1752 printf("(%02x)", c);
1760 memset(&strescseq, 0, sizeof(strescseq));
1764 tputtab(bool forward) {
1770 for(++x; x < term.col && !term.tabs[x]; ++x)
1775 for(--x; x > 0 && !term.tabs[x]; --x)
1778 tmoveto(x, term.c.y);
1782 tputc(char *c, int len) {
1786 write(iofd, c, len);
1793 tmoveto(term.c.x-1, term.c.y);
1796 tmoveto(0, term.c.y);
1801 /* go to first col if the mode is set */
1802 tnewline(IS_SET(MODE_CRLF));
1805 if(term.esc & ESC_STR)
1808 if(!(xw.state & WIN_FOCUSED))
1813 term.esc = ESC_START;
1817 if(term.esc & ESC_START) {
1818 if(term.esc & ESC_CSI) {
1819 csiescseq.buf[csiescseq.len++] = ascii;
1820 if(BETWEEN(ascii, 0x40, 0x7E)
1821 || csiescseq.len >= ESC_BUF_SIZ) {
1823 csiparse(), csihandle();
1825 } else if(term.esc & ESC_STR) {
1828 term.esc = ESC_START | ESC_STR_END;
1830 case '\a': /* backwards compatibility to xterm */
1835 strescseq.buf[strescseq.len++] = ascii;
1836 if(strescseq.len+1 >= STR_BUF_SIZ) {
1841 } else if(term.esc & ESC_STR_END) {
1845 } else if(term.esc & ESC_ALTCHARSET) {
1847 case '0': /* Line drawing set */
1848 term.c.attr.mode |= ATTR_GFX;
1850 case 'B': /* USASCII */
1851 term.c.attr.mode &= ~ATTR_GFX;
1853 case 'A': /* UK (IGNORED) */
1854 case '<': /* multinational charset (IGNORED) */
1855 case '5': /* Finnish (IGNORED) */
1856 case 'C': /* Finnish (IGNORED) */
1857 case 'K': /* German (IGNORED) */
1860 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1866 term.esc |= ESC_CSI;
1868 case 'P': /* DCS -- Device Control String */
1869 case '_': /* APC -- Application Program Command */
1870 case '^': /* PM -- Privacy Message */
1871 case ']': /* OSC -- Operating System Command */
1872 case 'k': /* old title set compatibility */
1874 strescseq.type = ascii;
1875 term.esc |= ESC_STR;
1877 case '(': /* set primary charset G0 */
1878 term.esc |= ESC_ALTCHARSET;
1880 case ')': /* set secondary charset G1 (IGNORED) */
1881 case '*': /* set tertiary charset G2 (IGNORED) */
1882 case '+': /* set quaternary charset G3 (IGNORED) */
1885 case 'D': /* IND -- Linefeed */
1886 if(term.c.y == term.bot) {
1887 tscrollup(term.top, 1);
1889 tmoveto(term.c.x, term.c.y+1);
1893 case 'E': /* NEL -- Next line */
1894 tnewline(1); /* always go to first col */
1897 case 'H': /* HTS -- Horizontal tab stop */
1898 term.tabs[term.c.x] = 1;
1901 case 'M': /* RI -- Reverse index */
1902 if(term.c.y == term.top) {
1903 tscrolldown(term.top, 1);
1905 tmoveto(term.c.x, term.c.y-1);
1909 case 'c': /* RIS -- Reset to inital state */
1915 case '=': /* DECPAM -- Application keypad */
1916 term.mode |= MODE_APPKEYPAD;
1919 case '>': /* DECPNM -- Normal keypad */
1920 term.mode &= ~MODE_APPKEYPAD;
1923 case '7': /* DECSC -- Save Cursor */
1924 tcursor(CURSOR_SAVE);
1927 case '8': /* DECRC -- Restore Cursor */
1928 tcursor(CURSOR_LOAD);
1931 case '\\': /* ST -- Stop */
1935 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1936 (uchar) ascii, isprint(ascii)? ascii:'.');
1941 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1943 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1944 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1945 tnewline(1); /* always go to first col */
1947 if(term.c.x+1 < term.col) {
1948 tmoveto(term.c.x+1, term.c.y);
1950 term.c.state |= CURSOR_WRAPNEXT;
1957 tresize(int col, int row) {
1959 int minrow = MIN(row, term.row);
1960 int mincol = MIN(col, term.col);
1961 int slide = term.c.y - row + 1;
1964 if(col < 1 || row < 1)
1967 /* free unneeded rows */
1970 /* slide screen to keep cursor where we expect it -
1971 * tscrollup would work here, but we can optimize to
1972 * memmove because we're freeing the earlier lines */
1973 for(/* i = 0 */; i < slide; i++) {
1977 memmove(term.line, term.line + slide, row * sizeof(Line));
1978 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1980 for(i += row; i < term.row; i++) {
1985 /* resize to new height */
1986 term.line = xrealloc(term.line, row * sizeof(Line));
1987 term.alt = xrealloc(term.alt, row * sizeof(Line));
1988 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1989 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1991 /* resize each row to new width, zero-pad if needed */
1992 for(i = 0; i < minrow; i++) {
1994 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1995 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
1996 for(x = mincol; x < col; x++) {
1997 term.line[i][x].state = 0;
1998 term.alt[i][x].state = 0;
2002 /* allocate any new rows */
2003 for(/* i == minrow */; i < row; i++) {
2005 term.line[i] = xcalloc(col, sizeof(Glyph));
2006 term.alt [i] = xcalloc(col, sizeof(Glyph));
2008 if(col > term.col) {
2009 bp = term.tabs + term.col;
2011 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2012 while(--bp > term.tabs && !*bp)
2014 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2017 /* update terminal size */
2018 term.col = col, term.row = row;
2019 /* make use of the LIMIT in tmoveto */
2020 tmoveto(term.c.x, term.c.y);
2021 /* reset scrolling region */
2022 tsetscroll(0, row-1);
2028 xresize(int col, int row) {
2029 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2030 xw.th = MAX(1, 2*BORDER + row * xw.ch);
2032 XftDrawChange(xw.xft_draw, xw.buf);
2038 XRenderColor xft_color = { .alpha = 0 };
2040 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2041 for(i = 0; i < LEN(colorname); i++) {
2044 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2045 die("Could not allocate color '%s'\n", colorname[i]);
2049 /* load colors [16-255] ; same colors as xterm */
2050 for(i = 16, r = 0; r < 6; r++) {
2051 for(g = 0; g < 6; g++) {
2052 for(b = 0; b < 6; b++) {
2053 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2054 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2055 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2056 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2057 die("Could not allocate color %d\n", i);
2064 for(r = 0; r < 24; r++, i++) {
2065 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2066 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2068 die("Could not allocate color %d\n", i);
2074 xtermclear(int col1, int row1, int col2, int row2) {
2075 XftDrawRect(xw.xft_draw,
2076 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2077 BORDER + col1 * xw.cw,
2078 BORDER + row1 * xw.ch,
2079 (col2-col1+1) * xw.cw,
2080 (row2-row1+1) * xw.ch);
2084 * Absolute coordinates.
2087 xclear(int x1, int y1, int x2, int y2) {
2088 XftDrawRect(xw.xft_draw,
2089 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2090 x1, y1, x2-x1, y2-y1);
2094 xclearborders(void) {
2095 /* top and left border */
2096 xclear(0, 0, BORDER, xw.h);
2097 xclear(0, 0, xw.w, BORDER);
2099 /* lower and right border */
2100 xclear(BORDER, xw.th - 1, xw.w, xw.h);
2101 /* Will just draw what hasn't been drawn by the previous call. */
2102 xclear(xw.tw - 1, BORDER, xw.w, xw.h - xw.th - 2);
2107 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2108 XWMHints wm = {.flags = InputHint, .input = 1};
2109 XSizeHints *sizeh = NULL;
2111 sizeh = XAllocSizeHints();
2112 if(xw.isfixed == False) {
2113 sizeh->flags = PSize | PResizeInc | PBaseSize;
2114 sizeh->height = xw.h;
2115 sizeh->width = xw.w;
2116 sizeh->height_inc = xw.ch;
2117 sizeh->width_inc = xw.cw;
2118 sizeh->base_height = 2*BORDER;
2119 sizeh->base_width = 2*BORDER;
2121 sizeh->flags = PMaxSize | PMinSize;
2122 sizeh->min_width = sizeh->max_width = xw.fw;
2123 sizeh->min_height = sizeh->max_height = xw.fh;
2126 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2131 xinitfont(Font *f, char *fontstr) {
2132 FcPattern *pattern, *match;
2135 pattern = FcNameParse((FcChar8 *)fontstr);
2137 die("st: can't open font %s\n", fontstr);
2139 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2140 FcPatternDestroy(pattern);
2142 die("st: can't open font %s\n", fontstr);
2143 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2144 FcPatternDestroy(match);
2145 die("st: can't open font %s.\n", fontstr);
2148 f->ascent = f->xft_set->ascent;
2149 f->descent = f->xft_set->descent;
2151 f->rbearing = f->xft_set->max_advance_width;
2153 f->height = f->xft_set->height;
2154 f->width = f->lbearing + f->rbearing;
2158 initfonts(char *fontstr) {
2161 xinitfont(&dc.font, fontstr);
2162 xw.cw = dc.font.width;
2163 xw.ch = dc.font.height;
2165 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2166 xinitfont(&dc.bfont, fstr);
2169 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2170 xinitfont(&dc.ifont, fstr);
2173 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2174 xinitfont(&dc.ibfont, fstr);
2180 XSetWindowAttributes attrs;
2183 int sw, sh, major, minor;
2185 if(!(xw.dpy = XOpenDisplay(NULL)))
2186 die("Can't open display\n");
2187 xw.scr = XDefaultScreen(xw.dpy);
2188 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2191 initfonts((opt_font != NULL)? opt_font : FONT);
2194 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2197 /* adjust fixed window geometry */
2199 sw = DisplayWidth(xw.dpy, xw.scr);
2200 sh = DisplayHeight(xw.dpy, xw.scr);
2202 xw.fx = sw + xw.fx - xw.fw - 1;
2204 xw.fy = sh + xw.fy - xw.fh - 1;
2209 /* window - default size */
2210 xw.h = 2*BORDER + term.row * xw.ch;
2211 xw.w = 2*BORDER + term.col * xw.cw;
2216 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2217 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2218 attrs.bit_gravity = NorthWestGravity;
2219 attrs.event_mask = FocusChangeMask | KeyPressMask
2220 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2221 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2222 attrs.colormap = xw.cmap;
2224 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2225 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2226 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2228 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2232 /* double buffering */
2233 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2234 die("Xdbe extension is not present\n");
2235 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2237 /* Xft rendering context */
2238 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2241 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2242 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2243 | XIMStatusNothing, XNClientWindow, xw.win,
2244 XNFocusWindow, xw.win, NULL);
2246 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2248 /* white cursor, black outline */
2249 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2250 XDefineCursor(xw.dpy, xw.win, cursor);
2251 XRecolorCursor(xw.dpy, cursor,
2252 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2253 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2255 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2256 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2257 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2260 XMapWindow(xw.dpy, xw.win);
2266 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2267 int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch,
2268 width = charlen*xw.cw;
2269 Font *font = &dc.font;
2271 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2272 *temp, revfg, revbg;
2273 XRenderColor colfg, colbg;
2275 if(base.mode & ATTR_REVERSE)
2276 temp = fg, fg = bg, bg = temp;
2278 if(base.mode & ATTR_BOLD) {
2279 if(BETWEEN(base.fg, 0, 7)) {
2280 /* basic system colors */
2281 fg = &dc.xft_col[base.fg + 8];
2282 } else if(BETWEEN(base.fg, 16, 195)) {
2284 fg = &dc.xft_col[base.fg + 36];
2285 } else if(BETWEEN(base.fg, 232, 251)) {
2287 fg = &dc.xft_col[base.fg + 4];
2290 * Those ranges will not be brightened:
2291 * 8 - 15 – bright system colors
2292 * 196 - 231 – highest 256 color cube
2293 * 252 - 255 – brightest colors in grescale
2298 if(base.mode & ATTR_ITALIC)
2300 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2303 if(IS_SET(MODE_REVERSE)) {
2304 if(fg == &dc.xft_col[DefaultFG]) {
2305 fg = &dc.xft_col[DefaultBG];
2307 colfg.red = ~fg->color.red;
2308 colfg.green = ~fg->color.green;
2309 colfg.blue = ~fg->color.blue;
2310 colfg.alpha = fg->color.alpha;
2311 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2315 if(bg == &dc.xft_col[DefaultBG]) {
2316 bg = &dc.xft_col[DefaultFG];
2318 colbg.red = ~bg->color.red;
2319 colbg.green = ~bg->color.green;
2320 colbg.blue = ~bg->color.blue;
2321 colbg.alpha = bg->color.alpha;
2322 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2327 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2329 width = extents.xOff;
2331 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2332 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2333 winy + font->ascent, (FcChar8 *)s, bytelen);
2335 if(base.mode & ATTR_UNDERLINE) {
2336 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2343 static int oldx = 0, oldy = 0;
2345 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2347 LIMIT(oldx, 0, term.col-1);
2348 LIMIT(oldy, 0, term.row-1);
2350 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2351 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2353 /* remove the old cursor */
2354 if(term.line[oldy][oldx].state & GLYPH_SET) {
2355 sl = utf8size(term.line[oldy][oldx].c);
2356 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2359 xtermclear(oldx, oldy, oldx, oldy);
2362 /* draw the new one */
2363 if(!(term.c.state & CURSOR_HIDE)) {
2364 if(!(xw.state & WIN_FOCUSED))
2367 if(IS_SET(MODE_REVERSE))
2368 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2371 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2372 oldx = term.c.x, oldy = term.c.y;
2378 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2383 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2388 XSync(xw.dpy, False); /* necessary for a good tput flash */
2389 nanosleep(&tv, NULL);
2394 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2396 drawregion(0, 0, term.col, term.row);
2397 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2401 drawregion(int x1, int y1, int x2, int y2) {
2402 int ic, ib, x, y, ox, sl;
2404 char buf[DRAW_BUF_SIZ];
2405 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2407 if((sel.alt && !alt) || (!sel.alt && alt))
2409 if(!(xw.state & WIN_VISIBLE))
2412 for(y = y1; y < y2; y++) {
2416 xtermclear(0, y, term.col, y);
2418 base = term.line[y][0];
2420 for(x = x1; x < x2; x++) {
2421 new = term.line[y][x];
2422 if(ena_sel && *(new.c) && selected(x, y))
2423 new.mode ^= ATTR_REVERSE;
2424 if(ib > 0 && (!(new.state & GLYPH_SET)
2425 || ATTRCMP(base, new)
2426 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2427 xdraws(buf, base, ox, y, ic, ib);
2430 if(new.state & GLYPH_SET) {
2435 sl = utf8size(new.c);
2436 memcpy(buf+ib, new.c, sl);
2442 xdraws(buf, base, ox, y, ic, ib);
2448 expose(XEvent *ev) {
2449 XExposeEvent *e = &ev->xexpose;
2451 if(xw.state & WIN_REDRAW) {
2453 xw.state &= ~WIN_REDRAW;
2458 visibility(XEvent *ev) {
2459 XVisibilityEvent *e = &ev->xvisibility;
2461 if(e->state == VisibilityFullyObscured) {
2462 xw.state &= ~WIN_VISIBLE;
2463 } else if(!(xw.state & WIN_VISIBLE)) {
2464 /* need a full redraw for next Expose, not just a buf copy */
2465 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2471 xw.state &= ~WIN_VISIBLE;
2475 xseturgency(int add) {
2476 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2478 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2479 XSetWMHints(xw.dpy, xw.win, h);
2485 if(ev->type == FocusIn) {
2486 xw.state |= WIN_FOCUSED;
2489 xw.state &= ~WIN_FOCUSED;
2494 kmap(KeySym k, uint state) {
2499 for(i = 0; i < LEN(key); i++) {
2502 if(key[i].k == k && ((state & mask) == mask
2503 || (mask == XK_NO_MOD && !state))) {
2504 return (char*)key[i].s;
2511 kpress(XEvent *ev) {
2512 XKeyEvent *e = &ev->xkey;
2521 if (IS_SET(MODE_KBDLOCK))
2524 meta = e->state & Mod1Mask;
2525 shift = e->state & ShiftMask;
2526 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2528 /* 1. custom keys from config.h */
2529 if((customkey = kmap(ksym, e->state))) {
2530 ttywrite(customkey, strlen(customkey));
2531 /* 2. hardcoded (overrides X lookup) */
2538 /* XXX: shift up/down doesn't work */
2539 sprintf(buf, "\033%c%c",
2540 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2541 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2549 if(IS_SET(MODE_CRLF)) {
2550 ttywrite("\r\n", 2);
2558 if(meta && len == 1)
2559 ttywrite("\033", 1);
2568 cmessage(XEvent *e) {
2570 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2571 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2572 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2573 xw.state |= WIN_FOCUSED;
2575 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2576 xw.state &= ~WIN_FOCUSED;
2578 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2579 /* Send SIGHUP to shell */
2589 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2592 xw.w = e->xconfigure.width;
2593 xw.h = e->xconfigure.height;
2594 col = (xw.w - 2*BORDER) / xw.cw;
2595 row = (xw.h - 2*BORDER) / xw.ch;
2596 if(col == term.col && row == term.row)
2609 int xfd = XConnectionNumber(xw.dpy), i;
2610 struct timeval drawtimeout, *tv = NULL;
2614 FD_SET(cmdfd, &rfd);
2616 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2619 die("select failed: %s\n", SERRNO);
2623 * Stop after a certain number of reads so the user does not
2624 * feel like the system is stuttering.
2626 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2630 * Just wait a bit so it isn't disturbing the
2631 * user and the system is able to write something.
2633 drawtimeout.tv_sec = 0;
2634 drawtimeout.tv_usec = 5;
2641 while(XPending(xw.dpy)) {
2642 XNextEvent(xw.dpy, &ev);
2643 if(XFilterEvent(&ev, xw.win))
2645 if(handler[ev.type])
2646 (handler[ev.type])(&ev);
2655 main(int argc, char *argv[]) {
2656 int i, bitm, xr, yr;
2659 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2662 for(i = 1; i < argc; i++) {
2663 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2666 opt_class = argv[i];
2669 /* eat every remaining arguments */
2681 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2686 if(bitm & WidthValue)
2688 if(bitm & HeightValue)
2690 if(bitm & XNegative && xw.fx == 0)
2692 if(bitm & XNegative && xw.fy == 0)
2695 if(xw.fh != 0 && xw.fw != 0)
2704 opt_title = argv[i];
2711 opt_embed = argv[i];
2717 setlocale(LC_CTYPE, "");