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 */
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);
382 die("Out of memory\n");
387 xrealloc(void *p, size_t len) {
388 if((p = realloc(p, len)) == NULL)
389 die("Out of memory\n");
394 xcalloc(size_t nmemb, size_t size) {
395 void *p = calloc(nmemb, size);
397 die("Out of memory\n");
402 smstrcat(char *src, ...)
408 len = slen = strlen(src);
410 va_start(fmtargs, src);
412 v = va_arg(fmtargs, char *);
419 p = ret = xmalloc(len+1);
420 memmove(p, src, slen);
423 va_start(fmtargs, src);
425 v = va_arg(fmtargs, char *);
440 utf8decode(char *s, long *u) {
446 if(~c & B7) { /* 0xxxxxxx */
449 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
450 *u = c&(B4|B3|B2|B1|B0);
452 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
453 *u = c&(B3|B2|B1|B0);
455 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
460 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
462 if((c & (B7|B6)) != B7) /* 10xxxxxx */
465 *u |= c & (B5|B4|B3|B2|B1|B0);
467 if((n == 1 && *u < 0x80) ||
468 (n == 2 && *u < 0x800) ||
469 (n == 3 && *u < 0x10000) ||
470 (*u >= 0xD800 && *u <= 0xDFFF))
479 utf8encode(long *u, char *s) {
487 *sp = uc; /* 0xxxxxxx */
489 } else if(*u < 0x800) {
490 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
492 } else if(uc < 0x10000) {
493 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
495 } else if(uc <= 0x10FFFF) {
496 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
501 for(i=n,++sp; i>0; --i,++sp)
502 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
512 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
513 UTF-8 otherwise return 0 */
515 isfullutf8(char *s, int b) {
523 else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
525 else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
527 ((b == 2) && (*c2&(B7|B6)) == B7)))
529 else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
531 ((b == 2) && (*c2&(B7|B6)) == B7) ||
532 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
544 else if((c&(B7|B6|B5)) == (B7|B6))
546 else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
554 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
555 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
559 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
560 if(sel.xtarget == None)
561 sel.xtarget = XA_STRING;
565 selected(int x, int y) {
566 if(sel.ey == y && sel.by == y) {
567 int bx = MIN(sel.bx, sel.ex);
568 int ex = MAX(sel.bx, sel.ex);
569 return BETWEEN(x, bx, ex);
571 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
572 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
576 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
578 *b = e->xbutton.button;
580 *x = X2COL(e->xbutton.x);
581 *y = Y2ROW(e->xbutton.y);
582 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
583 sel.b.y = MIN(sel.by, sel.ey);
584 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
585 sel.e.y = MAX(sel.by, sel.ey);
589 mousereport(XEvent *e) {
590 int x = X2COL(e->xbutton.x);
591 int y = Y2ROW(e->xbutton.y);
592 int button = e->xbutton.button;
593 int state = e->xbutton.state;
594 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
595 static int ob, ox, oy;
598 if(e->xbutton.type == MotionNotify) {
599 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
603 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
609 if(e->xbutton.type == ButtonPress) {
615 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
616 + (state & Mod4Mask ? 8 : 0)
617 + (state & ControlMask ? 16 : 0);
619 ttywrite(buf, sizeof(buf));
624 if(IS_SET(MODE_MOUSE))
626 else if(e->xbutton.button == Button1) {
629 tsetdirt(sel.b.y, sel.e.y);
633 sel.ex = sel.bx = X2COL(e->xbutton.x);
634 sel.ey = sel.by = Y2ROW(e->xbutton.y);
641 int x, y, bufsize, is_selected = 0;
647 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
648 ptr = str = xmalloc(bufsize);
650 /* append every set & selected glyph to the selection */
651 for(y = 0; y < term.row; y++) {
652 for(x = 0; x < term.col; x++) {
655 Glyph *gp = &term.line[y][x];
657 if(!(is_selected = selected(x, y)))
659 p = (gp->state & GLYPH_SET) ? gp->c : " ";
661 memcpy(ptr, p, size);
664 /* \n at the end of every selected line except for the last one */
665 if(is_selected && y < sel.e.y)
670 sel.alt = IS_SET(MODE_ALTSCREEN);
675 selnotify(XEvent *e) {
676 ulong nitems, ofs, rem;
683 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
684 False, AnyPropertyType, &type, &format,
685 &nitems, &rem, &data)) {
686 fprintf(stderr, "Clipboard allocation failed\n");
689 ttywrite((const char *) data, nitems * format / 8);
691 /* number of 32-bit chunks returned */
692 ofs += nitems * format / 32;
698 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
701 void selclear(XEvent *e) {
705 tsetdirt(sel.b.y, sel.e.y);
709 selrequest(XEvent *e) {
710 XSelectionRequestEvent *xsre;
714 xsre = (XSelectionRequestEvent *) e;
715 xev.type = SelectionNotify;
716 xev.requestor = xsre->requestor;
717 xev.selection = xsre->selection;
718 xev.target = xsre->target;
719 xev.time = xsre->time;
723 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
724 if(xsre->target == xa_targets) {
725 /* respond with the supported type */
726 Atom string = sel.xtarget;
727 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
728 XA_ATOM, 32, PropModeReplace,
729 (uchar *) &string, 1);
730 xev.property = xsre->property;
731 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
732 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
733 xsre->target, 8, PropModeReplace,
734 (uchar *) sel.clip, strlen(sel.clip));
735 xev.property = xsre->property;
738 /* all done, send a notification to the listener */
739 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
740 fprintf(stderr, "Error sending SelectionNotify event\n");
745 /* register the selection for both the clipboard and the primary */
751 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
753 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
754 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
758 brelease(XEvent *e) {
759 if(IS_SET(MODE_MOUSE)) {
763 if(e->xbutton.button == Button2)
765 else if(e->xbutton.button == Button1) {
767 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
768 term.dirty[sel.ey] = 1;
769 if(sel.bx == sel.ex && sel.by == sel.ey) {
772 gettimeofday(&now, NULL);
774 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
775 /* triple click on the line */
776 sel.b.x = sel.bx = 0;
777 sel.e.x = sel.ex = term.col;
778 sel.b.y = sel.e.y = sel.ey;
780 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
781 /* double click to select word */
783 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
784 term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
786 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
787 term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
789 sel.b.y = sel.e.y = sel.ey;
795 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
796 gettimeofday(&sel.tclick1, NULL);
801 if(IS_SET(MODE_MOUSE)) {
806 int oldey = sel.ey, oldex = sel.ex;
807 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
809 if(oldey != sel.ey || oldex != sel.ex) {
810 int starty = MIN(oldey, sel.ey);
811 int endy = MAX(oldey, sel.ey);
812 tsetdirt(starty, endy);
818 die(const char *errstr, ...) {
821 va_start(ap, errstr);
822 vfprintf(stderr, errstr, ap);
830 char *envshell = getenv("SHELL");
836 signal(SIGCHLD, SIG_DFL);
837 signal(SIGHUP, SIG_DFL);
838 signal(SIGINT, SIG_DFL);
839 signal(SIGQUIT, SIG_DFL);
840 signal(SIGTERM, SIG_DFL);
841 signal(SIGALRM, SIG_DFL);
843 DEFAULT(envshell, SHELL);
844 putenv("TERM="TNAME);
845 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
846 execvp(args[0], args);
853 if(waitpid(pid, &stat, 0) < 0)
854 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
856 exit(WEXITSTATUS(stat));
865 /* seems to work fine on linux, openbsd and freebsd */
866 struct winsize w = {term.row, term.col, 0, 0};
867 if(openpty(&m, &s, NULL, NULL, &w) < 0)
868 die("openpty failed: %s\n", SERRNO);
870 switch(pid = fork()) {
872 die("fork failed\n");
875 setsid(); /* create a new process group */
876 dup2(s, STDIN_FILENO);
877 dup2(s, STDOUT_FILENO);
878 dup2(s, STDERR_FILENO);
879 if(ioctl(s, TIOCSCTTY, NULL) < 0)
880 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
888 signal(SIGCHLD, sigchld);
890 if(!strcmp(opt_io, "-")) {
891 iofd = STDOUT_FILENO;
893 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
894 fprintf(stderr, "Error opening %s:%s\n",
895 opt_io, strerror(errno));
905 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
907 fprintf(stderr, "\n");
912 static char buf[BUFSIZ];
913 static int buflen = 0;
916 int charsize; /* size of utf8 char in bytes */
920 /* append read bytes to unprocessed bytes */
921 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
922 die("Couldn't read from shell: %s\n", SERRNO);
924 /* process every complete utf8 char */
927 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
928 charsize = utf8decode(ptr, &utf8c);
929 utf8encode(&utf8c, s);
935 /* keep any uncomplete utf8 char for the next call */
936 memmove(buf, ptr, buflen);
940 ttywrite(const char *s, size_t n) {
941 if(write(cmdfd, s, n) == -1)
942 die("write error on tty: %s\n", SERRNO);
953 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
954 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
958 tsetdirt(int top, int bot)
962 LIMIT(top, 0, term.row-1);
963 LIMIT(bot, 0, term.row-1);
965 for(i = top; i <= bot; i++)
972 tsetdirt(0, term.row-1);
979 if(mode == CURSOR_SAVE)
981 else if(mode == CURSOR_LOAD)
982 term.c = c, tmoveto(c.x, c.y);
992 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
994 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
995 for(i = TAB; i < term.col; i += TAB)
997 term.top = 0, term.bot = term.row - 1;
998 term.mode = MODE_WRAP;
1000 tclearregion(0, 0, term.col-1, term.row-1);
1004 tnew(int col, int row) {
1005 /* set screen size */
1006 term.row = row, term.col = col;
1007 term.line = xmalloc(term.row * sizeof(Line));
1008 term.alt = xmalloc(term.row * sizeof(Line));
1009 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1010 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1012 for(row = 0; row < term.row; row++) {
1013 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1014 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1015 term.dirty[row] = 0;
1017 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1024 Line* tmp = term.line;
1025 term.line = term.alt;
1027 term.mode ^= MODE_ALTSCREEN;
1032 tscrolldown(int orig, int n) {
1036 LIMIT(n, 0, term.bot-orig+1);
1038 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1040 for(i = term.bot; i >= orig+n; i--) {
1041 temp = term.line[i];
1042 term.line[i] = term.line[i-n];
1043 term.line[i-n] = temp;
1046 term.dirty[i-n] = 1;
1053 tscrollup(int orig, int n) {
1056 LIMIT(n, 0, term.bot-orig+1);
1058 tclearregion(0, orig, term.col-1, orig+n-1);
1060 for(i = orig; i <= term.bot-n; i++) {
1061 temp = term.line[i];
1062 term.line[i] = term.line[i+n];
1063 term.line[i+n] = temp;
1066 term.dirty[i+n] = 1;
1069 selscroll(orig, -n);
1073 selscroll(int orig, int n) {
1077 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1078 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1082 if(sel.by < term.top) {
1086 if(sel.ey > term.bot) {
1090 sel.b.y = sel.by, sel.b.x = sel.bx;
1091 sel.e.y = sel.ey, sel.e.x = sel.ex;
1096 tnewline(int first_col) {
1099 tscrollup(term.top, 1);
1102 tmoveto(first_col ? 0 : term.c.x, y);
1107 /* int noarg = 1; */
1108 char *p = csiescseq.buf;
1112 csiescseq.priv = 1, p++;
1114 while(p < csiescseq.buf+csiescseq.len) {
1115 while(isdigit(*p)) {
1116 csiescseq.arg[csiescseq.narg] *= 10;
1117 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1119 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1120 csiescseq.narg++, p++;
1122 csiescseq.mode = *p;
1130 tmoveto(int x, int y) {
1131 LIMIT(x, 0, term.col-1);
1132 LIMIT(y, 0, term.row-1);
1133 term.c.state &= ~CURSOR_WRAPNEXT;
1141 * The table is proudly stolen from rxvt.
1143 if(term.c.attr.mode & ATTR_GFX) {
1144 char *vt100_0[62] = { /* 0x41 - 0x7e */
1145 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1146 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1147 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1148 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1149 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1150 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1151 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1152 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1155 if(c[0] >= 0x41 && c[0] <= 0x7e
1156 && vt100_0[c[0] - 0x41]) {
1157 c = vt100_0[c[0] - 0x41];
1161 term.dirty[term.c.y] = 1;
1162 term.line[term.c.y][term.c.x] = term.c.attr;
1163 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1164 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1168 tclearregion(int x1, int y1, int x2, int y2) {
1172 temp = x1, x1 = x2, x2 = temp;
1174 temp = y1, y1 = y2, y2 = temp;
1176 LIMIT(x1, 0, term.col-1);
1177 LIMIT(x2, 0, term.col-1);
1178 LIMIT(y1, 0, term.row-1);
1179 LIMIT(y2, 0, term.row-1);
1181 for(y = y1; y <= y2; y++) {
1183 for(x = x1; x <= x2; x++)
1184 term.line[y][x].state = 0;
1189 tdeletechar(int n) {
1190 int src = term.c.x + n;
1192 int size = term.col - src;
1194 term.dirty[term.c.y] = 1;
1196 if(src >= term.col) {
1197 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1200 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1201 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1205 tinsertblank(int n) {
1208 int size = term.col - dst;
1210 term.dirty[term.c.y] = 1;
1212 if(dst >= term.col) {
1213 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1216 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1217 tclearregion(src, term.c.y, dst - 1, term.c.y);
1221 tinsertblankline(int n) {
1222 if(term.c.y < term.top || term.c.y > term.bot)
1225 tscrolldown(term.c.y, n);
1229 tdeleteline(int n) {
1230 if(term.c.y < term.top || term.c.y > term.bot)
1233 tscrollup(term.c.y, n);
1237 tsetattr(int *attr, int l) {
1240 for(i = 0; i < l; i++) {
1243 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1244 | ATTR_ITALIC | ATTR_BLINK);
1245 term.c.attr.fg = DefaultFG;
1246 term.c.attr.bg = DefaultBG;
1249 term.c.attr.mode |= ATTR_BOLD;
1251 case 3: /* enter standout (highlight) */
1252 term.c.attr.mode |= ATTR_ITALIC;
1255 term.c.attr.mode |= ATTR_UNDERLINE;
1258 term.c.attr.mode |= ATTR_BLINK;
1261 term.c.attr.mode |= ATTR_REVERSE;
1265 term.c.attr.mode &= ~ATTR_BOLD;
1267 case 23: /* leave standout (highlight) mode */
1268 term.c.attr.mode &= ~ATTR_ITALIC;
1271 term.c.attr.mode &= ~ATTR_UNDERLINE;
1274 term.c.attr.mode &= ~ATTR_BLINK;
1277 term.c.attr.mode &= ~ATTR_REVERSE;
1280 if(i + 2 < l && attr[i + 1] == 5) {
1282 if(BETWEEN(attr[i], 0, 255))
1283 term.c.attr.fg = attr[i];
1285 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1288 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1291 term.c.attr.fg = DefaultFG;
1294 if(i + 2 < l && attr[i + 1] == 5) {
1296 if(BETWEEN(attr[i], 0, 255))
1297 term.c.attr.bg = attr[i];
1299 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1302 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1305 term.c.attr.bg = DefaultBG;
1308 if(BETWEEN(attr[i], 30, 37))
1309 term.c.attr.fg = attr[i] - 30;
1310 else if(BETWEEN(attr[i], 40, 47))
1311 term.c.attr.bg = attr[i] - 40;
1312 else if(BETWEEN(attr[i], 90, 97))
1313 term.c.attr.fg = attr[i] - 90 + 8;
1314 else if(BETWEEN(attr[i], 100, 107))
1315 term.c.attr.bg = attr[i] - 100 + 8;
1317 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1324 tsetscroll(int t, int b) {
1327 LIMIT(t, 0, term.row-1);
1328 LIMIT(b, 0, term.row-1);
1338 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1341 tsetmode(bool priv, bool set, int *args, int narg) {
1344 for(lim = args + narg; args < lim; ++args) {
1348 case 1: /* DECCKM -- Cursor key */
1349 MODBIT(term.mode, set, MODE_APPKEYPAD);
1351 case 5: /* DECSCNM -- Reverse video */
1353 MODBIT(term.mode, set, MODE_REVERSE);
1354 if(mode != term.mode)
1357 case 6: /* XXX: DECOM -- Origin */
1359 case 7: /* DECAWM -- Auto wrap */
1360 MODBIT(term.mode, set, MODE_WRAP);
1362 case 8: /* XXX: DECARM -- Auto repeat */
1364 case 0: /* Error (IGNORED) */
1365 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1368 MODBIT(term.c.state, !set, CURSOR_HIDE);
1370 case 1000: /* 1000,1002: enable xterm mouse report */
1371 MODBIT(term.mode, set, MODE_MOUSEBTN);
1374 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1376 case 1049: /* = 1047 and 1048 */
1379 if(IS_SET(MODE_ALTSCREEN))
1380 tclearregion(0, 0, term.col-1, term.row-1);
1381 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1382 (!set && IS_SET(MODE_ALTSCREEN))) {
1389 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1392 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1393 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1394 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1395 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1396 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1397 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1399 "erresc: unknown private set/reset mode %d\n",
1405 case 0: /* Error (IGNORED) */
1407 case 2: /* KAM -- keyboard action */
1408 MODBIT(term.mode, set, MODE_KBDLOCK);
1410 case 4: /* IRM -- Insertion-replacement */
1411 MODBIT(term.mode, set, MODE_INSERT);
1413 case 12: /* XXX: SRM -- Send/Receive */
1415 case 20: /* LNM -- Linefeed/new line */
1416 MODBIT(term.mode, set, MODE_CRLF);
1420 "erresc: unknown set/reset mode %d\n",
1432 switch(csiescseq.mode) {
1435 fprintf(stderr, "erresc: unknown csi ");
1439 case '@': /* ICH -- Insert <n> blank char */
1440 DEFAULT(csiescseq.arg[0], 1);
1441 tinsertblank(csiescseq.arg[0]);
1443 case 'A': /* CUU -- Cursor <n> Up */
1445 DEFAULT(csiescseq.arg[0], 1);
1446 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1448 case 'B': /* CUD -- Cursor <n> Down */
1449 DEFAULT(csiescseq.arg[0], 1);
1450 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1452 case 'C': /* CUF -- Cursor <n> Forward */
1454 DEFAULT(csiescseq.arg[0], 1);
1455 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1457 case 'D': /* CUB -- Cursor <n> Backward */
1458 DEFAULT(csiescseq.arg[0], 1);
1459 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1461 case 'E': /* CNL -- Cursor <n> Down and first col */
1462 DEFAULT(csiescseq.arg[0], 1);
1463 tmoveto(0, term.c.y+csiescseq.arg[0]);
1465 case 'F': /* CPL -- Cursor <n> Up and first col */
1466 DEFAULT(csiescseq.arg[0], 1);
1467 tmoveto(0, term.c.y-csiescseq.arg[0]);
1469 case 'g': /* TBC -- Tabulation clear */
1470 switch (csiescseq.arg[0]) {
1471 case 0: /* clear current tab stop */
1472 term.tabs[term.c.x] = 0;
1474 case 3: /* clear all the tabs */
1475 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1481 case 'G': /* CHA -- Move to <col> */
1483 DEFAULT(csiescseq.arg[0], 1);
1484 tmoveto(csiescseq.arg[0]-1, term.c.y);
1486 case 'H': /* CUP -- Move to <row> <col> */
1488 DEFAULT(csiescseq.arg[0], 1);
1489 DEFAULT(csiescseq.arg[1], 1);
1490 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1492 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1493 DEFAULT(csiescseq.arg[0], 1);
1494 while(csiescseq.arg[0]--)
1497 case 'J': /* ED -- Clear screen */
1499 switch(csiescseq.arg[0]) {
1501 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1502 if(term.c.y < term.row-1)
1503 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1507 tclearregion(0, 0, term.col-1, term.c.y-1);
1508 tclearregion(0, term.c.y, term.c.x, term.c.y);
1511 tclearregion(0, 0, term.col-1, term.row-1);
1517 case 'K': /* EL -- Clear line */
1518 switch(csiescseq.arg[0]) {
1520 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1523 tclearregion(0, term.c.y, term.c.x, term.c.y);
1526 tclearregion(0, term.c.y, term.col-1, term.c.y);
1530 case 'S': /* SU -- Scroll <n> line up */
1531 DEFAULT(csiescseq.arg[0], 1);
1532 tscrollup(term.top, csiescseq.arg[0]);
1534 case 'T': /* SD -- Scroll <n> line down */
1535 DEFAULT(csiescseq.arg[0], 1);
1536 tscrolldown(term.top, csiescseq.arg[0]);
1538 case 'L': /* IL -- Insert <n> blank lines */
1539 DEFAULT(csiescseq.arg[0], 1);
1540 tinsertblankline(csiescseq.arg[0]);
1542 case 'l': /* RM -- Reset Mode */
1543 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1545 case 'M': /* DL -- Delete <n> lines */
1546 DEFAULT(csiescseq.arg[0], 1);
1547 tdeleteline(csiescseq.arg[0]);
1549 case 'X': /* ECH -- Erase <n> char */
1550 DEFAULT(csiescseq.arg[0], 1);
1551 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1553 case 'P': /* DCH -- Delete <n> char */
1554 DEFAULT(csiescseq.arg[0], 1);
1555 tdeletechar(csiescseq.arg[0]);
1557 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1558 DEFAULT(csiescseq.arg[0], 1);
1559 while(csiescseq.arg[0]--)
1562 case 'd': /* VPA -- Move to <row> */
1563 DEFAULT(csiescseq.arg[0], 1);
1564 tmoveto(term.c.x, csiescseq.arg[0]-1);
1566 case 'h': /* SM -- Set terminal mode */
1567 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1569 case 'm': /* SGR -- Terminal attribute (color) */
1570 tsetattr(csiescseq.arg, csiescseq.narg);
1572 case 'r': /* DECSTBM -- Set Scrolling Region */
1576 DEFAULT(csiescseq.arg[0], 1);
1577 DEFAULT(csiescseq.arg[1], term.row);
1578 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1582 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1583 tcursor(CURSOR_SAVE);
1585 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1586 tcursor(CURSOR_LOAD);
1595 for(i = 0; i < csiescseq.len; i++) {
1596 uint c = csiescseq.buf[i] & 0xff;
1597 if(isprint(c)) putchar(c);
1598 else if(c == '\n') printf("(\\n)");
1599 else if(c == '\r') printf("(\\r)");
1600 else if(c == 0x1b) printf("(\\e)");
1601 else printf("(%02x)", c);
1608 memset(&csiescseq, 0, sizeof(csiescseq));
1616 * TODO: make this being useful in case of color palette change.
1622 switch(strescseq.type) {
1623 case ']': /* OSC -- Operating System Command */
1629 * TODO: Handle special chars in string, like umlauts.
1632 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1636 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1638 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1641 fprintf(stderr, "erresc: unknown str ");
1646 case 'k': /* old title set compatibility */
1647 XStoreName(xw.dpy, xw.win, strescseq.buf);
1649 case 'P': /* DSC -- Device Control String */
1650 case '_': /* APC -- Application Program Command */
1651 case '^': /* PM -- Privacy Message */
1653 fprintf(stderr, "erresc: unknown str ");
1663 * TODO: Implement parsing like for CSI when required.
1664 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1672 printf("ESC%c", strescseq.type);
1673 for(i = 0; i < strescseq.len; i++) {
1674 uint c = strescseq.buf[i] & 0xff;
1675 if(isprint(c)) putchar(c);
1676 else if(c == '\n') printf("(\\n)");
1677 else if(c == '\r') printf("(\\r)");
1678 else if(c == 0x1b) printf("(\\e)");
1679 else printf("(%02x)", c);
1686 memset(&strescseq, 0, sizeof(strescseq));
1690 tputtab(bool forward) {
1696 for(++x; x < term.col && !term.tabs[x]; ++x)
1701 for(--x; x > 0 && !term.tabs[x]; --x)
1704 tmoveto(x, term.c.y);
1708 tputc(char *c, int len) {
1712 write(iofd, c, len);
1719 tmoveto(term.c.x-1, term.c.y);
1722 tmoveto(0, term.c.y);
1727 /* go to first col if the mode is set */
1728 tnewline(IS_SET(MODE_CRLF));
1731 if(term.esc & ESC_STR)
1734 if(!(xw.state & WIN_FOCUSED))
1739 term.esc = ESC_START;
1743 if(term.esc & ESC_START) {
1744 if(term.esc & ESC_CSI) {
1745 csiescseq.buf[csiescseq.len++] = ascii;
1746 if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1748 csiparse(), csihandle();
1750 } else if(term.esc & ESC_STR) {
1753 term.esc = ESC_START | ESC_STR_END;
1755 case '\a': /* backwards compatibility to xterm */
1760 strescseq.buf[strescseq.len++] = ascii;
1761 if(strescseq.len+1 >= STR_BUF_SIZ) {
1766 } else if(term.esc & ESC_STR_END) {
1770 } else if(term.esc & ESC_ALTCHARSET) {
1772 case '0': /* Line drawing set */
1773 term.c.attr.mode |= ATTR_GFX;
1775 case 'B': /* USASCII */
1776 term.c.attr.mode &= ~ATTR_GFX;
1778 case 'A': /* UK (IGNORED) */
1779 case '<': /* multinational charset (IGNORED) */
1780 case '5': /* Finnish (IGNORED) */
1781 case 'C': /* Finnish (IGNORED) */
1782 case 'K': /* German (IGNORED) */
1785 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1791 term.esc |= ESC_CSI;
1793 case 'P': /* DCS -- Device Control String */
1794 case '_': /* APC -- Application Program Command */
1795 case '^': /* PM -- Privacy Message */
1796 case ']': /* OSC -- Operating System Command */
1797 case 'k': /* old title set compatibility */
1799 strescseq.type = ascii;
1800 term.esc |= ESC_STR;
1802 case '(': /* set primary charset G0 */
1803 term.esc |= ESC_ALTCHARSET;
1805 case ')': /* set secondary charset G1 (IGNORED) */
1806 case '*': /* set tertiary charset G2 (IGNORED) */
1807 case '+': /* set quaternary charset G3 (IGNORED) */
1810 case 'D': /* IND -- Linefeed */
1811 if(term.c.y == term.bot)
1812 tscrollup(term.top, 1);
1814 tmoveto(term.c.x, term.c.y+1);
1817 case 'E': /* NEL -- Next line */
1818 tnewline(1); /* always go to first col */
1821 case 'H': /* HTS -- Horizontal tab stop */
1822 term.tabs[term.c.x] = 1;
1825 case 'M': /* RI -- Reverse index */
1826 if(term.c.y == term.top)
1827 tscrolldown(term.top, 1);
1829 tmoveto(term.c.x, term.c.y-1);
1832 case 'c': /* RIS -- Reset to inital state */
1838 case '=': /* DECPAM -- Application keypad */
1839 term.mode |= MODE_APPKEYPAD;
1842 case '>': /* DECPNM -- Normal keypad */
1843 term.mode &= ~MODE_APPKEYPAD;
1846 case '7': /* DECSC -- Save Cursor */
1847 tcursor(CURSOR_SAVE);
1850 case '8': /* DECRC -- Restore Cursor */
1851 tcursor(CURSOR_LOAD);
1854 case '\\': /* ST -- Stop */
1858 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1859 (uchar) ascii, isprint(ascii)?ascii:'.');
1864 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1866 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1867 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1868 tnewline(1); /* always go to first col */
1870 if(term.c.x+1 < term.col)
1871 tmoveto(term.c.x+1, term.c.y);
1873 term.c.state |= CURSOR_WRAPNEXT;
1879 tresize(int col, int row) {
1881 int minrow = MIN(row, term.row);
1882 int mincol = MIN(col, term.col);
1883 int slide = term.c.y - row + 1;
1885 if(col < 1 || row < 1)
1888 /* free unneeded rows */
1891 /* slide screen to keep cursor where we expect it -
1892 * tscrollup would work here, but we can optimize to
1893 * memmove because we're freeing the earlier lines */
1894 for(/* i = 0 */; i < slide; i++) {
1898 memmove(term.line, term.line + slide, row * sizeof(Line));
1899 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1901 for(i += row; i < term.row; i++) {
1906 /* resize to new height */
1907 term.line = xrealloc(term.line, row * sizeof(Line));
1908 term.alt = xrealloc(term.alt, row * sizeof(Line));
1909 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1910 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1912 /* resize each row to new width, zero-pad if needed */
1913 for(i = 0; i < minrow; i++) {
1915 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1916 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
1917 for(x = mincol; x < col; x++) {
1918 term.line[i][x].state = 0;
1919 term.alt[i][x].state = 0;
1923 /* allocate any new rows */
1924 for(/* i == minrow */; i < row; i++) {
1926 term.line[i] = xcalloc(col, sizeof(Glyph));
1927 term.alt [i] = xcalloc(col, sizeof(Glyph));
1929 if(col > term.col) {
1930 bool *bp = term.tabs + term.col;
1932 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1933 while(--bp > term.tabs && !*bp)
1935 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1938 /* update terminal size */
1939 term.col = col, term.row = row;
1940 /* make use of the LIMIT in tmoveto */
1941 tmoveto(term.c.x, term.c.y);
1942 /* reset scrolling region */
1943 tsetscroll(0, row-1);
1949 xresize(int col, int row) {
1950 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
1951 xw.th = MAX(1, 2*BORDER + row * xw.ch);
1953 XftDrawChange(xw.xft_draw, xw.buf);
1959 XRenderColor xft_color = { .alpha = 0 };
1961 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1962 for(i = 0; i < LEN(colorname); i++) {
1965 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
1966 die("Could not allocate color '%s'\n", colorname[i]);
1970 /* load colors [16-255] ; same colors as xterm */
1971 for(i = 16, r = 0; r < 6; r++) {
1972 for(g = 0; g < 6; g++) {
1973 for(b = 0; b < 6; b++) {
1974 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1975 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1976 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1977 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1978 die("Could not allocate color %d\n", i);
1985 for(r = 0; r < 24; r++, i++) {
1986 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
1987 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1988 die("Could not allocate color %d\n", i);
1994 xtermclear(int col1, int row1, int col2, int row2) {
1995 XftDrawRect(xw.xft_draw,
1996 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
1997 BORDER + col1 * xw.cw,
1998 BORDER + row1 * xw.ch,
1999 (col2-col1+1) * xw.cw,
2000 (row2-row1+1) * xw.ch);
2004 * Absolute coordinates.
2007 xclear(int x1, int y1, int x2, int y2) {
2008 XftDrawRect(xw.xft_draw,
2009 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2010 x1, y1, x2-x1, y2-y1);
2014 xclearborders(void) {
2015 /* top and left border */
2016 xclear(0, 0, BORDER, xw.h);
2017 xclear(0, 0, xw.w, BORDER);
2019 /* lower and right border */
2020 xclear(BORDER, xw.th - 1, xw.w, xw.h);
2021 /* Will just draw what hasn't been drawn by the previous call. */
2022 xclear(xw.tw - 1, BORDER, xw.w, xw.h - xw.th - 2);
2027 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2028 XWMHints wm = {.flags = InputHint, .input = 1};
2029 XSizeHints *sizeh = NULL;
2031 sizeh = XAllocSizeHints();
2032 if(xw.isfixed == False) {
2033 sizeh->flags = PSize | PResizeInc | PBaseSize;
2034 sizeh->height = xw.h;
2035 sizeh->width = xw.w;
2036 sizeh->height_inc = xw.ch;
2037 sizeh->width_inc = xw.cw;
2038 sizeh->base_height = 2*BORDER;
2039 sizeh->base_width = 2*BORDER;
2041 sizeh->flags = PMaxSize | PMinSize;
2042 sizeh->min_width = sizeh->max_width = xw.fw;
2043 sizeh->min_height = sizeh->max_height = xw.fh;
2046 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2051 xinitfont(Font *f, char *fontstr) {
2052 FcPattern *pattern, *match;
2055 pattern = FcNameParse((FcChar8 *)fontstr);
2057 die("st: can't open font %s\n", fontstr);
2059 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2060 FcPatternDestroy(pattern);
2062 die("st: can't open font %s\n", fontstr);
2063 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2064 FcPatternDestroy(match);
2065 die("st: can't open font %s.\n", fontstr);
2068 f->ascent = f->xft_set->ascent;
2069 f->descent = f->xft_set->descent;
2071 f->rbearing = f->xft_set->max_advance_width;
2073 f->height = f->xft_set->height;
2074 f->width = f->lbearing + f->rbearing;
2078 initfonts(char *fontstr) {
2081 xinitfont(&dc.font, fontstr);
2082 xw.cw = dc.font.width;
2083 xw.ch = dc.font.height;
2085 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2086 xinitfont(&dc.bfont, fstr);
2089 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2090 xinitfont(&dc.ifont, fstr);
2093 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2094 xinitfont(&dc.ibfont, fstr);
2100 XSetWindowAttributes attrs;
2103 int sw, sh, major, minor;
2105 if(!(xw.dpy = XOpenDisplay(NULL)))
2106 die("Can't open display\n");
2107 xw.scr = XDefaultScreen(xw.dpy);
2108 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2111 initfonts((opt_font != NULL)? opt_font : FONT);
2114 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2117 /* adjust fixed window geometry */
2119 sw = DisplayWidth(xw.dpy, xw.scr);
2120 sh = DisplayHeight(xw.dpy, xw.scr);
2122 xw.fx = sw + xw.fx - xw.fw - 1;
2124 xw.fy = sh + xw.fy - xw.fh - 1;
2129 /* window - default size */
2130 xw.h = 2*BORDER + term.row * xw.ch;
2131 xw.w = 2*BORDER + term.col * xw.cw;
2136 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2137 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2138 attrs.bit_gravity = NorthWestGravity;
2139 attrs.event_mask = FocusChangeMask | KeyPressMask
2140 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2141 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2142 attrs.colormap = xw.cmap;
2144 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2145 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2146 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2148 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2152 /* double buffering */
2153 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2154 die("Xdbe extension is not present\n");
2155 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2157 /* Xft rendering context */
2158 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2161 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2162 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2163 | XIMStatusNothing, XNClientWindow, xw.win,
2164 XNFocusWindow, xw.win, NULL);
2166 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2168 /* white cursor, black outline */
2169 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2170 XDefineCursor(xw.dpy, xw.win, cursor);
2171 XRecolorCursor(xw.dpy, cursor,
2172 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2173 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2175 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2178 XMapWindow(xw.dpy, xw.win);
2184 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2185 int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch,
2186 width = charlen*xw.cw;
2187 Font *font = &dc.font;
2189 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2190 *temp, revfg, revbg;
2191 XRenderColor colfg, colbg;
2193 if(base.mode & ATTR_REVERSE)
2194 temp = fg, fg = bg, bg = temp;
2195 if(base.mode & ATTR_BOLD) {
2196 fg = &dc.xft_col[base.fg + 8];
2199 if(base.mode & ATTR_ITALIC)
2201 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2204 if(IS_SET(MODE_REVERSE)) {
2205 if(fg == &dc.xft_col[DefaultFG]) {
2206 fg = &dc.xft_col[DefaultBG];
2208 colfg.red = ~fg->color.red;
2209 colfg.green = ~fg->color.green;
2210 colfg.blue = ~fg->color.blue;
2211 colfg.alpha = fg->color.alpha;
2212 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2216 if(bg == &dc.xft_col[DefaultBG]) {
2217 bg = &dc.xft_col[DefaultFG];
2219 colbg.red = ~bg->color.red;
2220 colbg.green = ~bg->color.green;
2221 colbg.blue = ~bg->color.blue;
2222 colbg.alpha = bg->color.alpha;
2223 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2228 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2230 width = extents.xOff;
2232 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2233 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2234 winy + font->ascent, (FcChar8 *)s, bytelen);
2236 if(base.mode & ATTR_UNDERLINE) {
2237 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2244 static int oldx = 0;
2245 static int oldy = 0;
2247 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2249 LIMIT(oldx, 0, term.col-1);
2250 LIMIT(oldy, 0, term.row-1);
2252 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2253 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2255 /* remove the old cursor */
2256 if(term.line[oldy][oldx].state & GLYPH_SET) {
2257 sl = utf8size(term.line[oldy][oldx].c);
2258 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2260 xtermclear(oldx, oldy, oldx, oldy);
2262 /* draw the new one */
2263 if(!(term.c.state & CURSOR_HIDE)) {
2264 if(!(xw.state & WIN_FOCUSED))
2267 if(IS_SET(MODE_REVERSE))
2268 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2271 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2272 oldx = term.c.x, oldy = term.c.y;
2278 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2283 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2288 XSync(xw.dpy, False); /* necessary for a good tput flash */
2289 nanosleep(&tv, NULL);
2294 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2296 drawregion(0, 0, term.col, term.row);
2297 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2301 drawregion(int x1, int y1, int x2, int y2) {
2302 int ic, ib, x, y, ox, sl;
2304 char buf[DRAW_BUF_SIZ];
2305 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2307 if((sel.alt && !alt) || (!sel.alt && alt))
2309 if(!(xw.state & WIN_VISIBLE))
2312 for(y = y1; y < y2; y++) {
2315 xtermclear(0, y, term.col, y);
2317 base = term.line[y][0];
2319 for(x = x1; x < x2; x++) {
2320 new = term.line[y][x];
2321 if(ena_sel && *(new.c) && selected(x, y))
2322 new.mode ^= ATTR_REVERSE;
2323 if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2324 ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2325 xdraws(buf, base, ox, y, ic, ib);
2328 if(new.state & GLYPH_SET) {
2333 sl = utf8size(new.c);
2334 memcpy(buf+ib, new.c, sl);
2340 xdraws(buf, base, ox, y, ic, ib);
2346 expose(XEvent *ev) {
2347 XExposeEvent *e = &ev->xexpose;
2348 if(xw.state & WIN_REDRAW) {
2350 xw.state &= ~WIN_REDRAW;
2355 visibility(XEvent *ev) {
2356 XVisibilityEvent *e = &ev->xvisibility;
2357 if(e->state == VisibilityFullyObscured)
2358 xw.state &= ~WIN_VISIBLE;
2359 else if(!(xw.state & WIN_VISIBLE))
2360 /* need a full redraw for next Expose, not just a buf copy */
2361 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2366 xw.state &= ~WIN_VISIBLE;
2370 xseturgency(int add) {
2371 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2372 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2373 XSetWMHints(xw.dpy, xw.win, h);
2379 if(ev->type == FocusIn) {
2380 xw.state |= WIN_FOCUSED;
2383 xw.state &= ~WIN_FOCUSED;
2387 kmap(KeySym k, uint state) {
2390 for(i = 0; i < LEN(key); i++) {
2391 uint mask = key[i].mask;
2392 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2393 return (char*)key[i].s;
2399 kpress(XEvent *ev) {
2400 XKeyEvent *e = &ev->xkey;
2409 if (IS_SET(MODE_KBDLOCK))
2411 meta = e->state & Mod1Mask;
2412 shift = e->state & ShiftMask;
2413 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2415 /* 1. custom keys from config.h */
2416 if((customkey = kmap(ksym, e->state)))
2417 ttywrite(customkey, strlen(customkey));
2418 /* 2. hardcoded (overrides X lookup) */
2425 /* XXX: shift up/down doesn't work */
2426 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2434 if(IS_SET(MODE_CRLF))
2435 ttywrite("\r\n", 2);
2442 if(meta && len == 1)
2443 ttywrite("\033", 1);
2451 cmessage(XEvent *e) {
2453 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2454 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2455 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2456 xw.state |= WIN_FOCUSED;
2458 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2459 xw.state &= ~WIN_FOCUSED;
2468 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2471 xw.w = e->xconfigure.width;
2472 xw.h = e->xconfigure.height;
2473 col = (xw.w - 2*BORDER) / xw.cw;
2474 row = (xw.h - 2*BORDER) / xw.ch;
2475 if(col == term.col && row == term.row)
2488 int xfd = XConnectionNumber(xw.dpy), i;
2489 struct timeval drawtimeout, *tv = NULL;
2493 FD_SET(cmdfd, &rfd);
2495 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2498 die("select failed: %s\n", SERRNO);
2502 * Stop after a certain number of reads so the user does not
2503 * feel like the system is stuttering.
2505 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2509 * Just wait a bit so it isn't disturbing the
2510 * user and the system is able to write something.
2512 drawtimeout.tv_sec = 0;
2513 drawtimeout.tv_usec = 5;
2520 while(XPending(xw.dpy)) {
2521 XNextEvent(xw.dpy, &ev);
2522 if(XFilterEvent(&ev, xw.win))
2524 if(handler[ev.type])
2525 (handler[ev.type])(&ev);
2534 main(int argc, char *argv[]) {
2535 int i, bitm, xr, yr;
2538 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2541 for(i = 1; i < argc; i++) {
2542 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2545 opt_class = argv[i];
2548 /* eat every remaining arguments */
2560 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2565 if(bitm & WidthValue)
2567 if(bitm & HeightValue)
2569 if(bitm & XNegative && xw.fx == 0)
2571 if(bitm & XNegative && xw.fy == 0)
2574 if(xw.fh != 0 && xw.fw != 0)
2583 opt_title = argv[i];
2590 opt_embed = argv[i];
2596 setlocale(LC_CTYPE, "");