1 /* See LICENSE for licence details. */
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/Xft/Xft.h>
28 #include <fontconfig/fontconfig.h>
36 #define Draw XftDraw *
37 #define Colour XftColor
38 #define Colourmap Colormap
42 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
44 #elif defined(__FreeBSD__) || defined(__DragonFly__)
50 #define XEMBED_FOCUS_IN 4
51 #define XEMBED_FOCUS_OUT 5
55 #define ESC_BUF_SIZ (128*UTF_SIZ)
56 #define ESC_ARG_SIZ 16
57 #define STR_BUF_SIZ ESC_BUF_SIZ
58 #define STR_ARG_SIZ ESC_ARG_SIZ
59 #define DRAW_BUF_SIZ 20*1024
60 #define XK_ANY_MOD UINT_MAX
62 #define XK_SWITCH_MOD (1<<13)
64 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
67 #define SERRNO strerror(errno)
68 #define MIN(a, b) ((a) < (b) ? (a) : (b))
69 #define MAX(a, b) ((a) < (b) ? (b) : (a))
70 #define LEN(a) (sizeof(a) / sizeof(a[0]))
71 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
72 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
73 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
74 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
75 #define IS_SET(flag) ((term.mode & (flag)) != 0)
76 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
78 #define VT102ID "\033[?6c"
80 enum glyph_attribute {
91 enum cursor_movement {
109 MODE_MOUSEMOTION = 64,
115 MODE_APPCURSOR = 2048,
116 MODE_MOUSESGR = 4096,
122 ESC_STR = 4, /* DSC, OSC, PM, APC */
124 ESC_STR_END = 16, /* a final string was encountered */
125 ESC_TEST = 32, /* Enter in test mode */
134 enum selection_type {
139 enum selection_snap {
146 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
148 typedef unsigned char uchar;
149 typedef unsigned int uint;
150 typedef unsigned long ulong;
151 typedef unsigned short ushort;
154 char c[UTF_SIZ]; /* character code */
155 uchar mode; /* attribute flags */
156 ushort fg; /* foreground */
157 ushort bg; /* background */
163 Glyph attr; /* current char attributes */
169 /* CSI Escape sequence structs */
170 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
172 char buf[ESC_BUF_SIZ]; /* raw string */
173 int len; /* raw string length */
175 int arg[ESC_ARG_SIZ];
176 int narg; /* nb of args */
180 /* STR Escape sequence structs */
181 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
183 char type; /* ESC type ... */
184 char buf[STR_BUF_SIZ]; /* raw string */
185 int len; /* raw string length */
186 char *args[STR_ARG_SIZ];
187 int narg; /* nb of args */
190 /* Internal representation of the screen */
192 int row; /* nb row */
193 int col; /* nb col */
194 Line *line; /* screen */
195 Line *alt; /* alternate screen */
196 bool *dirty; /* dirtyness of lines */
197 TCursor c; /* cursor */
198 int top; /* top scroll limit */
199 int bot; /* bottom scroll limit */
200 int mode; /* terminal mode flags */
201 int esc; /* escape state flags */
202 bool numlock; /* lock numbers in keyboard */
206 /* Purely graphic info */
212 Atom xembed, wmdeletewin;
218 bool isfixed; /* is fixed geometry? */
219 int fx, fy, fw, fh; /* fixed geometry */
220 int tw, th; /* tty width and height */
221 int w, h; /* window width and height */
222 int ch; /* char height */
223 int cw; /* char width */
224 char state; /* focus, redraw, visible */
231 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
232 signed char appkey; /* application keypad */
233 signed char appcursor; /* application cursor */
234 signed char crlf; /* crlf mode */
237 /* TODO: use better name for vars... */
250 struct timeval tclick1;
251 struct timeval tclick2;
264 void (*func)(const Arg *);
268 /* function definitions used in config.h */
269 static void clippaste(const Arg *);
270 static void numlock(const Arg *);
271 static void selpaste(const Arg *);
272 static void xzoom(const Arg *);
274 /* Config.h for applying patches and the configuration. */
290 /* Drawing Context */
292 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
293 Font font, bfont, ifont, ibfont;
297 static void die(const char *, ...);
298 static void draw(void);
299 static void redraw(int);
300 static void drawregion(int, int, int, int);
301 static void execsh(void);
302 static void sigchld(int);
303 static void run(void);
305 static void csidump(void);
306 static void csihandle(void);
307 static void csiparse(void);
308 static void csireset(void);
309 static void strdump(void);
310 static void strhandle(void);
311 static void strparse(void);
312 static void strreset(void);
314 static void tclearregion(int, int, int, int);
315 static void tcursor(int);
316 static void tdeletechar(int);
317 static void tdeleteline(int);
318 static void tinsertblank(int);
319 static void tinsertblankline(int);
320 static void tmoveto(int, int);
321 static void tmoveato(int x, int y);
322 static void tnew(int, int);
323 static void tnewline(int);
324 static void tputtab(bool);
325 static void tputc(char *, int);
326 static void treset(void);
327 static int tresize(int, int);
328 static void tscrollup(int, int);
329 static void tscrolldown(int, int);
330 static void tsetattr(int*, int);
331 static void tsetchar(char *, Glyph *, int, int);
332 static void tsetscroll(int, int);
333 static void tswapscreen(void);
334 static void tsetdirt(int, int);
335 static void tsetmode(bool, bool, int *, int);
336 static void tfulldirt(void);
337 static void techo(char *, int);
339 static inline bool match(uint, uint);
340 static void ttynew(void);
341 static void ttyread(void);
342 static void ttyresize(void);
343 static void ttywrite(const char *, size_t);
345 static void xdraws(char *, Glyph, int, int, int, int);
346 static void xhints(void);
347 static void xclear(int, int, int, int);
348 static void xdrawcursor(void);
349 static void xinit(void);
350 static void xloadcols(void);
351 static int xsetcolorname(int, const char *);
352 static int xloadfont(Font *, FcPattern *);
353 static void xloadfonts(char *, int);
354 static void xsettitle(char *);
355 static void xresettitle(void);
356 static void xseturgency(int);
357 static void xsetsel(char*);
358 static void xtermclear(int, int, int, int);
359 static void xunloadfonts(void);
360 static void xresize(int, int);
362 static void expose(XEvent *);
363 static void visibility(XEvent *);
364 static void unmap(XEvent *);
365 static char *kmap(KeySym, uint);
366 static void kpress(XEvent *);
367 static void cmessage(XEvent *);
368 static void cresize(int, int);
369 static void resize(XEvent *);
370 static void focus(XEvent *);
371 static void brelease(XEvent *);
372 static void bpress(XEvent *);
373 static void bmotion(XEvent *);
374 static void selnotify(XEvent *);
375 static void selclear(XEvent *);
376 static void selrequest(XEvent *);
378 static void selinit(void);
379 static inline bool selected(int, int);
380 static void selcopy(void);
381 static void selscroll(int, int);
382 static void selsnap(int, int *, int *, int);
384 static int utf8decode(char *, long *);
385 static int utf8encode(long *, char *);
386 static int utf8size(char *);
387 static int isfullutf8(char *, int);
389 static ssize_t xwrite(int, char *, size_t);
390 static void *xmalloc(size_t);
391 static void *xrealloc(void *, size_t);
392 static void *xcalloc(size_t, size_t);
394 static void (*handler[LASTEvent])(XEvent *) = {
396 [ClientMessage] = cmessage,
397 [ConfigureNotify] = resize,
398 [VisibilityNotify] = visibility,
399 [UnmapNotify] = unmap,
403 [MotionNotify] = bmotion,
404 [ButtonPress] = bpress,
405 [ButtonRelease] = brelease,
406 [SelectionClear] = selclear,
407 [SelectionNotify] = selnotify,
408 [SelectionRequest] = selrequest,
415 static CSIEscape csiescseq;
416 static STREscape strescseq;
419 static Selection sel;
420 static int iofd = -1;
421 static char **opt_cmd = NULL;
422 static char *opt_io = NULL;
423 static char *opt_title = NULL;
424 static char *opt_embed = NULL;
425 static char *opt_class = NULL;
426 static char *opt_font = NULL;
428 static char *usedfont = NULL;
429 static int usedfontsize = 0;
431 /* Font Ring Cache */
446 * Fontcache is a ring buffer, with frccur as current position and frclen as
447 * the current length of used elements.
450 static Fontcache frc[1024];
451 static int frccur = -1, frclen = 0;
454 xwrite(int fd, char *s, size_t len) {
458 ssize_t r = write(fd, s, len);
468 xmalloc(size_t len) {
469 void *p = malloc(len);
472 die("Out of memory\n");
478 xrealloc(void *p, size_t len) {
479 if((p = realloc(p, len)) == NULL)
480 die("Out of memory\n");
486 xcalloc(size_t nmemb, size_t size) {
487 void *p = calloc(nmemb, size);
490 die("Out of memory\n");
496 utf8decode(char *s, long *u) {
502 if(~c & B7) { /* 0xxxxxxx */
505 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
506 *u = c&(B4|B3|B2|B1|B0);
508 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
509 *u = c&(B3|B2|B1|B0);
511 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
518 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
520 if((c & (B7|B6)) != B7) /* 10xxxxxx */
523 *u |= c & (B5|B4|B3|B2|B1|B0);
526 if((n == 1 && *u < 0x80) ||
527 (n == 2 && *u < 0x800) ||
528 (n == 3 && *u < 0x10000) ||
529 (*u >= 0xD800 && *u <= 0xDFFF)) {
541 utf8encode(long *u, char *s) {
549 *sp = uc; /* 0xxxxxxx */
551 } else if(*u < 0x800) {
552 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
554 } else if(uc < 0x10000) {
555 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
557 } else if(uc <= 0x10FFFF) {
558 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
564 for(i=n,++sp; i>0; --i,++sp)
565 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
577 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
578 UTF-8 otherwise return 0 */
580 isfullutf8(char *s, int b) {
588 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
590 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
592 ((b == 2) && (*c2&(B7|B6)) == B7))) {
594 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
596 ((b == 2) && (*c2&(B7|B6)) == B7) ||
597 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
610 } else if((c&(B7|B6|B5)) == (B7|B6)) {
612 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
621 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
622 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
626 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
627 if(sel.xtarget == None)
628 sel.xtarget = XA_STRING;
636 return LIMIT(x, 0, term.col-1);
644 return LIMIT(y, 0, term.row-1);
648 selected(int x, int y) {
651 if(sel.ey == y && sel.by == y) {
652 bx = MIN(sel.bx, sel.ex);
653 ex = MAX(sel.bx, sel.ex);
655 return BETWEEN(x, bx, ex);
658 if(sel.type == SEL_RECTANGULAR) {
659 return ((sel.b.y <= y && y <= sel.e.y)
660 && (sel.b.x <= x && x <= sel.e.x));
662 return ((sel.b.y < y && y < sel.e.y)
663 || (y == sel.e.y && x <= sel.e.x))
664 || (y == sel.b.y && x >= sel.b.x
665 && (x <= sel.e.x || sel.b.y != sel.e.y));
669 selsnap(int mode, int *x, int *y, int direction) {
672 while(*x > 0 && *x < term.col-1
673 && term.line[*y][*x + direction].c[0] != ' ') {
678 *x = (direction < 0) ? 0 : term.col - 1;
686 getbuttoninfo(XEvent *e) {
688 uint state = e->xbutton.state &~Button1Mask;
690 sel.alt = IS_SET(MODE_ALTSCREEN);
692 sel.ex = x2col(e->xbutton.x);
693 sel.ey = y2row(e->xbutton.y);
696 || (sel.by == sel.ey && sel.bx < sel.ex)) {
697 selsnap(sel.snap, &sel.bx, &sel.by, -1);
698 selsnap(sel.snap, &sel.ex, &sel.ey, +1);
700 selsnap(sel.snap, &sel.ex, &sel.ey, -1);
701 selsnap(sel.snap, &sel.bx, &sel.by, +1);
704 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
705 sel.b.y = MIN(sel.by, sel.ey);
706 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
707 sel.e.y = MAX(sel.by, sel.ey);
709 sel.type = SEL_REGULAR;
710 for(type = 1; type < LEN(selmasks); ++type) {
711 if(match(selmasks[type], state)) {
719 mousereport(XEvent *e) {
720 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
721 button = e->xbutton.button, state = e->xbutton.state,
724 static int ob, ox, oy;
727 if(e->xbutton.type == MotionNotify) {
728 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
732 } else if(!IS_SET(MODE_MOUSESGR)
733 && (e->xbutton.type == ButtonRelease
734 || button == AnyButton)) {
740 if(e->xbutton.type == ButtonPress) {
746 button += (state & ShiftMask ? 4 : 0)
747 + (state & Mod4Mask ? 8 : 0)
748 + (state & ControlMask ? 16 : 0);
751 if(IS_SET(MODE_MOUSESGR)) {
752 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
754 e->xbutton.type == ButtonRelease ? 'm' : 'M');
755 } else if(x < 223 && y < 223) {
756 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
757 32+button, 32+x+1, 32+y+1);
769 if(IS_SET(MODE_MOUSE)) {
771 } else if(e->xbutton.button == Button1) {
772 gettimeofday(&now, NULL);
774 /* Clear previous selection, logically and visually. */
777 tsetdirt(sel.b.y, sel.e.y);
781 sel.type = SEL_REGULAR;
782 sel.ex = sel.bx = x2col(e->xbutton.x);
783 sel.ey = sel.by = y2row(e->xbutton.y);
787 * If user clicks are fasst enough (e.g. below timeouts),
788 * we ignore if his hand slipped left or down and accidentally
789 * selected more; we are just snapping to whatever we're
792 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
793 sel.snap = SNAP_LINE;
794 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
795 sel.snap = SNAP_WORD;
799 selsnap(sel.snap, &sel.bx, &sel.by, -1);
800 selsnap(sel.snap, &sel.ex, &sel.ey, 1);
807 * Draw selection, unless it's regular and we don't want to
808 * make clicks visible
811 tsetdirt(sel.b.y, sel.e.y);
814 sel.tclick2 = sel.tclick1;
816 } else if(e->xbutton.button == Button4) {
818 } else if(e->xbutton.button == Button5) {
826 int x, y, bufsize, size;
832 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
833 ptr = str = xmalloc(bufsize);
835 /* append every set & selected glyph to the selection */
836 for(y = sel.b.y; y < sel.e.y + 1; y++) {
837 gp = &term.line[y][0];
838 last = gp + term.col;
840 while(--last >= gp && !(selected(last - gp, y) && \
841 strcmp(last->c, " ") != 0))
844 for(x = 0; gp <= last; x++, ++gp) {
848 size = utf8size(gp->c);
849 memcpy(ptr, gp->c, size);
854 * Copy and pasting of line endings is inconsistent
855 * in the inconsistent terminal and GUI world.
856 * The best solution seems like to produce '\n' when
857 * something is copied from st and convert '\n' to
858 * '\r', when something to be pasted is received by
860 * FIXME: Fix the computer world.
862 if(y < sel.e.y && !((gp-1)->mode & ATTR_WRAP))
871 selnotify(XEvent *e) {
872 ulong nitems, ofs, rem;
874 uchar *data, *last, *repl;
879 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
880 False, AnyPropertyType, &type, &format,
881 &nitems, &rem, &data)) {
882 fprintf(stderr, "Clipboard allocation failed\n");
887 * As seen in selcopy:
888 * Line endings are inconsistent in the terminal and GUI world
889 * copy and pasting. When receiving some selection data,
890 * replace all '\n' with '\r'.
891 * FIXME: Fix the computer world.
894 last = data + nitems * format / 8;
895 while((repl = memchr(repl, '\n', last - repl))) {
899 ttywrite((const char *)data, nitems * format / 8);
901 /* number of 32-bit chunks returned */
902 ofs += nitems * format / 32;
907 selpaste(const Arg *dummy) {
908 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
909 xw.win, CurrentTime);
913 clippaste(const Arg *dummy) {
916 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
917 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
918 xw.win, CurrentTime);
922 selclear(XEvent *e) {
926 tsetdirt(sel.b.y, sel.e.y);
930 selrequest(XEvent *e) {
931 XSelectionRequestEvent *xsre;
933 Atom xa_targets, string;
935 xsre = (XSelectionRequestEvent *) e;
936 xev.type = SelectionNotify;
937 xev.requestor = xsre->requestor;
938 xev.selection = xsre->selection;
939 xev.target = xsre->target;
940 xev.time = xsre->time;
944 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
945 if(xsre->target == xa_targets) {
946 /* respond with the supported type */
947 string = sel.xtarget;
948 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
949 XA_ATOM, 32, PropModeReplace,
950 (uchar *) &string, 1);
951 xev.property = xsre->property;
952 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
953 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
954 xsre->target, 8, PropModeReplace,
955 (uchar *) sel.clip, strlen(sel.clip));
956 xev.property = xsre->property;
959 /* all done, send a notification to the listener */
960 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
961 fprintf(stderr, "Error sending SelectionNotify event\n");
966 /* register the selection for both the clipboard and the primary */
972 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
974 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
975 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
979 brelease(XEvent *e) {
980 if(IS_SET(MODE_MOUSE)) {
985 if(e->xbutton.button == Button2) {
987 } else if(e->xbutton.button == Button1) {
990 term.dirty[sel.ey] = 1;
991 if(sel.bx == sel.ex && sel.by == sel.ey) {
1000 bmotion(XEvent *e) {
1001 int oldey, oldex, oldsby, oldsey;
1003 if(IS_SET(MODE_MOUSE)) {
1017 if(oldey != sel.ey || oldex != sel.ex) {
1018 tsetdirt(MIN(sel.b.y, oldsby), MAX(sel.e.y, oldsey));
1023 die(const char *errstr, ...) {
1026 va_start(ap, errstr);
1027 vfprintf(stderr, errstr, ap);
1035 char *envshell = getenv("SHELL");
1036 const struct passwd *pass = getpwuid(getuid());
1037 char buf[sizeof(long) * 8 + 1];
1039 unsetenv("COLUMNS");
1041 unsetenv("TERMCAP");
1044 setenv("LOGNAME", pass->pw_name, 1);
1045 setenv("USER", pass->pw_name, 1);
1046 setenv("SHELL", pass->pw_shell, 0);
1047 setenv("HOME", pass->pw_dir, 0);
1050 snprintf(buf, sizeof(buf), "%lu", xw.win);
1051 setenv("WINDOWID", buf, 1);
1053 signal(SIGCHLD, SIG_DFL);
1054 signal(SIGHUP, SIG_DFL);
1055 signal(SIGINT, SIG_DFL);
1056 signal(SIGQUIT, SIG_DFL);
1057 signal(SIGTERM, SIG_DFL);
1058 signal(SIGALRM, SIG_DFL);
1060 DEFAULT(envshell, shell);
1061 setenv("TERM", termname, 1);
1062 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1063 execvp(args[0], args);
1071 if(waitpid(pid, &stat, 0) < 0)
1072 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1074 if(WIFEXITED(stat)) {
1075 exit(WEXITSTATUS(stat));
1084 struct winsize w = {term.row, term.col, 0, 0};
1086 /* seems to work fine on linux, openbsd and freebsd */
1087 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1088 die("openpty failed: %s\n", SERRNO);
1090 switch(pid = fork()) {
1092 die("fork failed\n");
1095 setsid(); /* create a new process group */
1096 dup2(s, STDIN_FILENO);
1097 dup2(s, STDOUT_FILENO);
1098 dup2(s, STDERR_FILENO);
1099 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1100 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1108 signal(SIGCHLD, sigchld);
1110 iofd = (!strcmp(opt_io, "-")) ?
1112 open(opt_io, O_WRONLY | O_CREAT, 0666);
1114 fprintf(stderr, "Error opening %s:%s\n",
1115 opt_io, strerror(errno));
1125 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1127 fprintf(stderr, "\n");
1132 static char buf[BUFSIZ];
1133 static int buflen = 0;
1136 int charsize; /* size of utf8 char in bytes */
1140 /* append read bytes to unprocessed bytes */
1141 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1142 die("Couldn't read from shell: %s\n", SERRNO);
1144 /* process every complete utf8 char */
1147 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1148 charsize = utf8decode(ptr, &utf8c);
1149 utf8encode(&utf8c, s);
1155 /* keep any uncomplete utf8 char for the next call */
1156 memmove(buf, ptr, buflen);
1160 ttywrite(const char *s, size_t n) {
1161 if(write(cmdfd, s, n) == -1)
1162 die("write error on tty: %s\n", SERRNO);
1169 w.ws_row = term.row;
1170 w.ws_col = term.col;
1171 w.ws_xpixel = xw.tw;
1172 w.ws_ypixel = xw.th;
1173 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1174 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1178 tsetdirt(int top, int bot) {
1181 LIMIT(top, 0, term.row-1);
1182 LIMIT(bot, 0, term.row-1);
1184 for(i = top; i <= bot; i++)
1190 tsetdirt(0, term.row-1);
1197 if(mode == CURSOR_SAVE) {
1199 } else if(mode == CURSOR_LOAD) {
1209 term.c = (TCursor){{
1213 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1215 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1216 for(i = tabspaces; i < term.col; i += tabspaces)
1219 term.bot = term.row - 1;
1220 term.mode = MODE_WRAP;
1222 tclearregion(0, 0, term.col-1, term.row-1);
1224 tcursor(CURSOR_SAVE);
1228 tnew(int col, int row) {
1229 memset(&term, 0, sizeof(Term));
1238 Line *tmp = term.line;
1240 term.line = term.alt;
1242 term.mode ^= MODE_ALTSCREEN;
1247 tscrolldown(int orig, int n) {
1251 LIMIT(n, 0, term.bot-orig+1);
1253 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1255 for(i = term.bot; i >= orig+n; i--) {
1256 temp = term.line[i];
1257 term.line[i] = term.line[i-n];
1258 term.line[i-n] = temp;
1261 term.dirty[i-n] = 1;
1268 tscrollup(int orig, int n) {
1271 LIMIT(n, 0, term.bot-orig+1);
1273 tclearregion(0, orig, term.col-1, orig+n-1);
1275 for(i = orig; i <= term.bot-n; i++) {
1276 temp = term.line[i];
1277 term.line[i] = term.line[i+n];
1278 term.line[i+n] = temp;
1281 term.dirty[i+n] = 1;
1284 selscroll(orig, -n);
1288 selscroll(int orig, int n) {
1292 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1293 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1297 if(sel.type == SEL_RECTANGULAR) {
1298 if(sel.by < term.top)
1300 if(sel.ey > term.bot)
1303 if(sel.by < term.top) {
1307 if(sel.ey > term.bot) {
1312 sel.b.y = sel.by, sel.b.x = sel.bx;
1313 sel.e.y = sel.ey, sel.e.x = sel.ex;
1318 tnewline(int first_col) {
1322 tscrollup(term.top, 1);
1326 tmoveto(first_col ? 0 : term.c.x, y);
1331 char *p = csiescseq.buf, *np;
1340 csiescseq.buf[csiescseq.len] = '\0';
1341 while(p < csiescseq.buf+csiescseq.len) {
1343 v = strtol(p, &np, 10);
1346 if(v == LONG_MAX || v == LONG_MIN)
1348 csiescseq.arg[csiescseq.narg++] = v;
1350 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1354 csiescseq.mode = *p;
1357 /* for absolute user moves, when decom is set */
1359 tmoveato(int x, int y) {
1360 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1364 tmoveto(int x, int y) {
1367 if(term.c.state & CURSOR_ORIGIN) {
1372 maxy = term.row - 1;
1374 LIMIT(x, 0, term.col-1);
1375 LIMIT(y, miny, maxy);
1376 term.c.state &= ~CURSOR_WRAPNEXT;
1382 tsetchar(char *c, Glyph *attr, int x, int y) {
1383 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1384 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1385 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1386 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1387 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1388 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1389 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1390 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1391 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1395 * The table is proudly stolen from rxvt.
1397 if(attr->mode & ATTR_GFX) {
1398 if(c[0] >= 0x41 && c[0] <= 0x7e
1399 && vt100_0[c[0] - 0x41]) {
1400 c = vt100_0[c[0] - 0x41];
1405 term.line[y][x] = *attr;
1406 memcpy(term.line[y][x].c, c, UTF_SIZ);
1410 tclearregion(int x1, int y1, int x2, int y2) {
1414 temp = x1, x1 = x2, x2 = temp;
1416 temp = y1, y1 = y2, y2 = temp;
1418 LIMIT(x1, 0, term.col-1);
1419 LIMIT(x2, 0, term.col-1);
1420 LIMIT(y1, 0, term.row-1);
1421 LIMIT(y2, 0, term.row-1);
1423 for(y = y1; y <= y2; y++) {
1425 for(x = x1; x <= x2; x++) {
1426 term.line[y][x] = term.c.attr;
1427 memcpy(term.line[y][x].c, " ", 2);
1433 tdeletechar(int n) {
1434 int src = term.c.x + n;
1436 int size = term.col - src;
1438 term.dirty[term.c.y] = 1;
1440 if(src >= term.col) {
1441 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1445 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1446 size * sizeof(Glyph));
1447 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1451 tinsertblank(int n) {
1454 int size = term.col - dst;
1456 term.dirty[term.c.y] = 1;
1458 if(dst >= term.col) {
1459 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1463 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1464 size * sizeof(Glyph));
1465 tclearregion(src, term.c.y, dst - 1, term.c.y);
1469 tinsertblankline(int n) {
1470 if(term.c.y < term.top || term.c.y > term.bot)
1473 tscrolldown(term.c.y, n);
1477 tdeleteline(int n) {
1478 if(term.c.y < term.top || term.c.y > term.bot)
1481 tscrollup(term.c.y, n);
1485 tsetattr(int *attr, int l) {
1488 for(i = 0; i < l; i++) {
1491 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1492 | ATTR_BOLD | ATTR_ITALIC \
1494 term.c.attr.fg = defaultfg;
1495 term.c.attr.bg = defaultbg;
1498 term.c.attr.mode |= ATTR_BOLD;
1501 term.c.attr.mode |= ATTR_ITALIC;
1504 term.c.attr.mode |= ATTR_UNDERLINE;
1506 case 5: /* slow blink */
1507 case 6: /* rapid blink */
1508 term.c.attr.mode |= ATTR_BLINK;
1511 term.c.attr.mode |= ATTR_REVERSE;
1515 term.c.attr.mode &= ~ATTR_BOLD;
1518 term.c.attr.mode &= ~ATTR_ITALIC;
1521 term.c.attr.mode &= ~ATTR_UNDERLINE;
1525 term.c.attr.mode &= ~ATTR_BLINK;
1528 term.c.attr.mode &= ~ATTR_REVERSE;
1531 if(i + 2 < l && attr[i + 1] == 5) {
1533 if(BETWEEN(attr[i], 0, 255)) {
1534 term.c.attr.fg = attr[i];
1537 "erresc: bad fgcolor %d\n",
1542 "erresc(38): gfx attr %d unknown\n",
1547 term.c.attr.fg = defaultfg;
1550 if(i + 2 < l && attr[i + 1] == 5) {
1552 if(BETWEEN(attr[i], 0, 255)) {
1553 term.c.attr.bg = attr[i];
1556 "erresc: bad bgcolor %d\n",
1561 "erresc(48): gfx attr %d unknown\n",
1566 term.c.attr.bg = defaultbg;
1569 if(BETWEEN(attr[i], 30, 37)) {
1570 term.c.attr.fg = attr[i] - 30;
1571 } else if(BETWEEN(attr[i], 40, 47)) {
1572 term.c.attr.bg = attr[i] - 40;
1573 } else if(BETWEEN(attr[i], 90, 97)) {
1574 term.c.attr.fg = attr[i] - 90 + 8;
1575 } else if(BETWEEN(attr[i], 100, 107)) {
1576 term.c.attr.bg = attr[i] - 100 + 8;
1579 "erresc(default): gfx attr %d unknown\n",
1580 attr[i]), csidump();
1588 tsetscroll(int t, int b) {
1591 LIMIT(t, 0, term.row-1);
1592 LIMIT(b, 0, term.row-1);
1602 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1605 tsetmode(bool priv, bool set, int *args, int narg) {
1609 for(lim = args + narg; args < lim; ++args) {
1613 case 1: /* DECCKM -- Cursor key */
1614 MODBIT(term.mode, set, MODE_APPCURSOR);
1616 case 5: /* DECSCNM -- Reverse video */
1618 MODBIT(term.mode, set, MODE_REVERSE);
1619 if(mode != term.mode)
1620 redraw(REDRAW_TIMEOUT);
1622 case 6: /* DECOM -- Origin */
1623 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1626 case 7: /* DECAWM -- Auto wrap */
1627 MODBIT(term.mode, set, MODE_WRAP);
1629 case 0: /* Error (IGNORED) */
1630 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1631 case 3: /* DECCOLM -- Column (IGNORED) */
1632 case 4: /* DECSCLM -- Scroll (IGNORED) */
1633 case 8: /* DECARM -- Auto repeat (IGNORED) */
1634 case 18: /* DECPFF -- Printer feed (IGNORED) */
1635 case 19: /* DECPEX -- Printer extent (IGNORED) */
1636 case 42: /* DECNRCM -- National characters (IGNORED) */
1637 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1639 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1640 MODBIT(term.mode, !set, MODE_HIDE);
1642 case 1000: /* 1000,1002: enable xterm mouse report */
1643 MODBIT(term.mode, set, MODE_MOUSEBTN);
1644 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1647 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1648 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1651 MODBIT(term.mode, set, MODE_MOUSESGR);
1653 case 1049: /* = 1047 and 1048 */
1656 if (!allowaltscreen)
1659 alt = IS_SET(MODE_ALTSCREEN);
1661 tclearregion(0, 0, term.col-1,
1664 if(set ^ alt) /* set is always 1 or 0 */
1670 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1674 "erresc: unknown private set/reset mode %d\n",
1680 case 0: /* Error (IGNORED) */
1682 case 2: /* KAM -- keyboard action */
1683 MODBIT(term.mode, set, MODE_KBDLOCK);
1685 case 4: /* IRM -- Insertion-replacement */
1686 MODBIT(term.mode, set, MODE_INSERT);
1688 case 12: /* SRM -- Send/Receive */
1689 MODBIT(term.mode, !set, MODE_ECHO);
1691 case 20: /* LNM -- Linefeed/new line */
1692 MODBIT(term.mode, set, MODE_CRLF);
1696 "erresc: unknown set/reset mode %d\n",
1708 switch(csiescseq.mode) {
1711 fprintf(stderr, "erresc: unknown csi ");
1715 case '@': /* ICH -- Insert <n> blank char */
1716 DEFAULT(csiescseq.arg[0], 1);
1717 tinsertblank(csiescseq.arg[0]);
1719 case 'A': /* CUU -- Cursor <n> Up */
1720 DEFAULT(csiescseq.arg[0], 1);
1721 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1723 case 'B': /* CUD -- Cursor <n> Down */
1724 case 'e': /* VPR --Cursor <n> Down */
1725 DEFAULT(csiescseq.arg[0], 1);
1726 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1728 case 'c': /* DA -- Device Attributes */
1729 if(csiescseq.arg[0] == 0)
1730 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1732 case 'C': /* CUF -- Cursor <n> Forward */
1733 case 'a': /* HPR -- Cursor <n> Forward */
1734 DEFAULT(csiescseq.arg[0], 1);
1735 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1737 case 'D': /* CUB -- Cursor <n> Backward */
1738 DEFAULT(csiescseq.arg[0], 1);
1739 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1741 case 'E': /* CNL -- Cursor <n> Down and first col */
1742 DEFAULT(csiescseq.arg[0], 1);
1743 tmoveto(0, term.c.y+csiescseq.arg[0]);
1745 case 'F': /* CPL -- Cursor <n> Up and first col */
1746 DEFAULT(csiescseq.arg[0], 1);
1747 tmoveto(0, term.c.y-csiescseq.arg[0]);
1749 case 'g': /* TBC -- Tabulation clear */
1750 switch(csiescseq.arg[0]) {
1751 case 0: /* clear current tab stop */
1752 term.tabs[term.c.x] = 0;
1754 case 3: /* clear all the tabs */
1755 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1761 case 'G': /* CHA -- Move to <col> */
1763 DEFAULT(csiescseq.arg[0], 1);
1764 tmoveto(csiescseq.arg[0]-1, term.c.y);
1766 case 'H': /* CUP -- Move to <row> <col> */
1768 DEFAULT(csiescseq.arg[0], 1);
1769 DEFAULT(csiescseq.arg[1], 1);
1770 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1772 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1773 DEFAULT(csiescseq.arg[0], 1);
1774 while(csiescseq.arg[0]--)
1777 case 'J': /* ED -- Clear screen */
1779 switch(csiescseq.arg[0]) {
1781 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1782 if(term.c.y < term.row-1) {
1783 tclearregion(0, term.c.y+1, term.col-1,
1789 tclearregion(0, 0, term.col-1, term.c.y-1);
1790 tclearregion(0, term.c.y, term.c.x, term.c.y);
1793 tclearregion(0, 0, term.col-1, term.row-1);
1799 case 'K': /* EL -- Clear line */
1800 switch(csiescseq.arg[0]) {
1802 tclearregion(term.c.x, term.c.y, term.col-1,
1806 tclearregion(0, term.c.y, term.c.x, term.c.y);
1809 tclearregion(0, term.c.y, term.col-1, term.c.y);
1813 case 'S': /* SU -- Scroll <n> line up */
1814 DEFAULT(csiescseq.arg[0], 1);
1815 tscrollup(term.top, csiescseq.arg[0]);
1817 case 'T': /* SD -- Scroll <n> line down */
1818 DEFAULT(csiescseq.arg[0], 1);
1819 tscrolldown(term.top, csiescseq.arg[0]);
1821 case 'L': /* IL -- Insert <n> blank lines */
1822 DEFAULT(csiescseq.arg[0], 1);
1823 tinsertblankline(csiescseq.arg[0]);
1825 case 'l': /* RM -- Reset Mode */
1826 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1828 case 'M': /* DL -- Delete <n> lines */
1829 DEFAULT(csiescseq.arg[0], 1);
1830 tdeleteline(csiescseq.arg[0]);
1832 case 'X': /* ECH -- Erase <n> char */
1833 DEFAULT(csiescseq.arg[0], 1);
1834 tclearregion(term.c.x, term.c.y,
1835 term.c.x + csiescseq.arg[0] - 1, term.c.y);
1837 case 'P': /* DCH -- Delete <n> char */
1838 DEFAULT(csiescseq.arg[0], 1);
1839 tdeletechar(csiescseq.arg[0]);
1841 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1842 DEFAULT(csiescseq.arg[0], 1);
1843 while(csiescseq.arg[0]--)
1846 case 'd': /* VPA -- Move to <row> */
1847 DEFAULT(csiescseq.arg[0], 1);
1848 tmoveato(term.c.x, csiescseq.arg[0]-1);
1850 case 'h': /* SM -- Set terminal mode */
1851 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1853 case 'm': /* SGR -- Terminal attribute (color) */
1854 tsetattr(csiescseq.arg, csiescseq.narg);
1856 case 'r': /* DECSTBM -- Set Scrolling Region */
1857 if(csiescseq.priv) {
1860 DEFAULT(csiescseq.arg[0], 1);
1861 DEFAULT(csiescseq.arg[1], term.row);
1862 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1866 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1867 tcursor(CURSOR_SAVE);
1869 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1870 tcursor(CURSOR_LOAD);
1881 for(i = 0; i < csiescseq.len; i++) {
1882 c = csiescseq.buf[i] & 0xff;
1885 } else if(c == '\n') {
1887 } else if(c == '\r') {
1889 } else if(c == 0x1b) {
1892 printf("(%02x)", c);
1900 memset(&csiescseq, 0, sizeof(csiescseq));
1909 narg = strescseq.narg;
1911 switch(strescseq.type) {
1912 case ']': /* OSC -- Operating System Command */
1913 switch(i = atoi(strescseq.args[0])) {
1918 xsettitle(strescseq.args[1]);
1920 case 4: /* color set */
1923 p = strescseq.args[2];
1925 case 104: /* color reset, here p = NULL */
1926 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
1927 if (!xsetcolorname(j, p)) {
1928 fprintf(stderr, "erresc: invalid color %s\n", p);
1931 * TODO if defaultbg color is changed, borders
1938 fprintf(stderr, "erresc: unknown str ");
1943 case 'k': /* old title set compatibility */
1944 xsettitle(strescseq.args[0]);
1946 case 'P': /* DSC -- Device Control String */
1947 case '_': /* APC -- Application Program Command */
1948 case '^': /* PM -- Privacy Message */
1950 fprintf(stderr, "erresc: unknown str ");
1959 char *p = strescseq.buf;
1962 strescseq.buf[strescseq.len] = '\0';
1963 while(p && strescseq.narg < STR_ARG_SIZ)
1964 strescseq.args[strescseq.narg++] = strsep(&p, ";");
1972 printf("ESC%c", strescseq.type);
1973 for(i = 0; i < strescseq.len; i++) {
1974 c = strescseq.buf[i] & 0xff;
1977 } else if(isprint(c)) {
1979 } else if(c == '\n') {
1981 } else if(c == '\r') {
1983 } else if(c == 0x1b) {
1986 printf("(%02x)", c);
1994 memset(&strescseq, 0, sizeof(strescseq));
1998 tputtab(bool forward) {
2004 for(++x; x < term.col && !term.tabs[x]; ++x)
2009 for(--x; x > 0 && !term.tabs[x]; --x)
2012 tmoveto(x, term.c.y);
2016 techo(char *buf, int len) {
2017 for(; len > 0; buf++, len--) {
2020 if(c == '\033') { /* escape */
2023 } else if(c < '\x20') { /* control code */
2024 if(c != '\n' && c != '\r' && c != '\t') {
2038 tputc(char *c, int len) {
2040 bool control = ascii < '\x20' || ascii == 0177;
2043 if(xwrite(iofd, c, len) < 0) {
2044 fprintf(stderr, "Error writing in %s:%s\n",
2045 opt_io, strerror(errno));
2052 * STR sequences must be checked before anything else
2053 * because it can use some control codes as part of the sequence.
2055 if(term.esc & ESC_STR) {
2058 term.esc = ESC_START | ESC_STR_END;
2060 case '\a': /* backwards compatibility to xterm */
2065 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2066 memmove(&strescseq.buf[strescseq.len], c, len);
2067 strescseq.len += len;
2070 * Here is a bug in terminals. If the user never sends
2071 * some code to stop the str or esc command, then st
2072 * will stop responding. But this is better than
2073 * silently failing with unknown characters. At least
2074 * then users will report back.
2076 * In the case users ever get fixed, here is the code:
2088 * Actions of control codes must be performed as soon they arrive
2089 * because they can be embedded inside a control sequence, and
2090 * they must not cause conflicts with sequences.
2098 tmoveto(term.c.x-1, term.c.y);
2101 tmoveto(0, term.c.y);
2106 /* go to first col if the mode is set */
2107 tnewline(IS_SET(MODE_CRLF));
2109 case '\a': /* BEL */
2110 if(!(xw.state & WIN_FOCUSED))
2113 case '\033': /* ESC */
2115 term.esc = ESC_START;
2117 case '\016': /* SO */
2118 case '\017': /* SI */
2120 * Different charsets are hard to handle. Applications
2121 * should use the right alt charset escapes for the
2122 * only reason they still exist: line drawing. The
2123 * rest is incompatible history st should not support.
2126 case '\032': /* SUB */
2127 case '\030': /* CAN */
2130 case '\005': /* ENQ (IGNORED) */
2131 case '\000': /* NUL (IGNORED) */
2132 case '\021': /* XON (IGNORED) */
2133 case '\023': /* XOFF (IGNORED) */
2134 case 0177: /* DEL (IGNORED) */
2137 } else if(term.esc & ESC_START) {
2138 if(term.esc & ESC_CSI) {
2139 csiescseq.buf[csiescseq.len++] = ascii;
2140 if(BETWEEN(ascii, 0x40, 0x7E)
2141 || csiescseq.len >= \
2142 sizeof(csiescseq.buf)-1) {
2147 } else if(term.esc & ESC_STR_END) {
2151 } else if(term.esc & ESC_ALTCHARSET) {
2153 case '0': /* Line drawing set */
2154 term.c.attr.mode |= ATTR_GFX;
2156 case 'B': /* USASCII */
2157 term.c.attr.mode &= ~ATTR_GFX;
2159 case 'A': /* UK (IGNORED) */
2160 case '<': /* multinational charset (IGNORED) */
2161 case '5': /* Finnish (IGNORED) */
2162 case 'C': /* Finnish (IGNORED) */
2163 case 'K': /* German (IGNORED) */
2166 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2169 } else if(term.esc & ESC_TEST) {
2170 if(ascii == '8') { /* DEC screen alignment test. */
2171 char E[UTF_SIZ] = "E";
2174 for(x = 0; x < term.col; ++x) {
2175 for(y = 0; y < term.row; ++y)
2176 tsetchar(E, &term.c.attr, x, y);
2183 term.esc |= ESC_CSI;
2186 term.esc |= ESC_TEST;
2188 case 'P': /* DCS -- Device Control String */
2189 case '_': /* APC -- Application Program Command */
2190 case '^': /* PM -- Privacy Message */
2191 case ']': /* OSC -- Operating System Command */
2192 case 'k': /* old title set compatibility */
2194 strescseq.type = ascii;
2195 term.esc |= ESC_STR;
2197 case '(': /* set primary charset G0 */
2198 term.esc |= ESC_ALTCHARSET;
2200 case ')': /* set secondary charset G1 (IGNORED) */
2201 case '*': /* set tertiary charset G2 (IGNORED) */
2202 case '+': /* set quaternary charset G3 (IGNORED) */
2205 case 'D': /* IND -- Linefeed */
2206 if(term.c.y == term.bot) {
2207 tscrollup(term.top, 1);
2209 tmoveto(term.c.x, term.c.y+1);
2213 case 'E': /* NEL -- Next line */
2214 tnewline(1); /* always go to first col */
2217 case 'H': /* HTS -- Horizontal tab stop */
2218 term.tabs[term.c.x] = 1;
2221 case 'M': /* RI -- Reverse index */
2222 if(term.c.y == term.top) {
2223 tscrolldown(term.top, 1);
2225 tmoveto(term.c.x, term.c.y-1);
2229 case 'Z': /* DECID -- Identify Terminal */
2230 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2233 case 'c': /* RIS -- Reset to inital state */
2238 case '=': /* DECPAM -- Application keypad */
2239 term.mode |= MODE_APPKEYPAD;
2242 case '>': /* DECPNM -- Normal keypad */
2243 term.mode &= ~MODE_APPKEYPAD;
2246 case '7': /* DECSC -- Save Cursor */
2247 tcursor(CURSOR_SAVE);
2250 case '8': /* DECRC -- Restore Cursor */
2251 tcursor(CURSOR_LOAD);
2254 case '\\': /* ST -- Stop */
2258 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2259 (uchar) ascii, isprint(ascii)? ascii:'.');
2264 * All characters which form part of a sequence are not
2270 * Display control codes only if we are in graphic mode
2272 if(control && !(term.c.attr.mode & ATTR_GFX))
2274 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2276 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2277 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2281 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2282 memmove(&term.line[term.c.y][term.c.x+1],
2283 &term.line[term.c.y][term.c.x],
2284 (term.col - term.c.x - 1) * sizeof(Glyph));
2287 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2288 if(term.c.x+1 < term.col) {
2289 tmoveto(term.c.x+1, term.c.y);
2291 term.c.state |= CURSOR_WRAPNEXT;
2296 tresize(int col, int row) {
2298 int minrow = MIN(row, term.row);
2299 int mincol = MIN(col, term.col);
2300 int slide = term.c.y - row + 1;
2304 if(col < 1 || row < 1)
2307 /* free unneeded rows */
2311 * slide screen to keep cursor where we expect it -
2312 * tscrollup would work here, but we can optimize to
2313 * memmove because we're freeing the earlier lines
2315 for(/* i = 0 */; i < slide; i++) {
2319 memmove(term.line, term.line + slide, row * sizeof(Line));
2320 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2322 for(i += row; i < term.row; i++) {
2327 /* resize to new height */
2328 term.line = xrealloc(term.line, row * sizeof(Line));
2329 term.alt = xrealloc(term.alt, row * sizeof(Line));
2330 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2331 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2333 /* resize each row to new width, zero-pad if needed */
2334 for(i = 0; i < minrow; i++) {
2336 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2337 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2340 /* allocate any new rows */
2341 for(/* i == minrow */; i < row; i++) {
2343 term.line[i] = xcalloc(col, sizeof(Glyph));
2344 term.alt [i] = xcalloc(col, sizeof(Glyph));
2346 if(col > term.col) {
2347 bp = term.tabs + term.col;
2349 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2350 while(--bp > term.tabs && !*bp)
2352 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2355 /* update terminal size */
2358 /* reset scrolling region */
2359 tsetscroll(0, row-1);
2360 /* make use of the LIMIT in tmoveto */
2361 tmoveto(term.c.x, term.c.y);
2362 /* Clearing both screens */
2365 if(mincol < col && 0 < minrow) {
2366 tclearregion(mincol, 0, col - 1, minrow - 1);
2368 if(0 < col && minrow < row) {
2369 tclearregion(0, minrow, col - 1, row - 1);
2372 } while(orig != term.line);
2378 xresize(int col, int row) {
2379 xw.tw = MAX(1, col * xw.cw);
2380 xw.th = MAX(1, row * xw.ch);
2382 XFreePixmap(xw.dpy, xw.buf);
2383 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2384 DefaultDepth(xw.dpy, xw.scr));
2385 XftDrawChange(xw.draw, xw.buf);
2386 xclear(0, 0, xw.w, xw.h);
2389 static inline ushort
2390 sixd_to_16bit(int x) {
2391 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2397 XRenderColor color = { .alpha = 0xffff };
2399 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2400 for(i = 0; i < LEN(colorname); i++) {
2403 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2404 die("Could not allocate color '%s'\n", colorname[i]);
2408 /* load colors [16-255] ; same colors as xterm */
2409 for(i = 16, r = 0; r < 6; r++) {
2410 for(g = 0; g < 6; g++) {
2411 for(b = 0; b < 6; b++) {
2412 color.red = sixd_to_16bit(r);
2413 color.green = sixd_to_16bit(g);
2414 color.blue = sixd_to_16bit(b);
2415 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2416 die("Could not allocate color %d\n", i);
2423 for(r = 0; r < 24; r++, i++) {
2424 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2425 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2427 die("Could not allocate color %d\n", i);
2433 xsetcolorname(int x, const char *name) {
2434 XRenderColor color = { .alpha = 0xffff };
2436 if (x < 0 || x > LEN(colorname))
2439 if(16 <= x && x < 16 + 216) {
2440 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2441 color.red = sixd_to_16bit(r);
2442 color.green = sixd_to_16bit(g);
2443 color.blue = sixd_to_16bit(b);
2444 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2445 return 0; /* something went wrong */
2448 } else if (16 + 216 <= x && x < 256) {
2449 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2450 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2451 return 0; /* something went wrong */
2455 name = colorname[x];
2458 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2465 xtermclear(int col1, int row1, int col2, int row2) {
2466 XftDrawRect(xw.draw,
2467 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2468 borderpx + col1 * xw.cw,
2469 borderpx + row1 * xw.ch,
2470 (col2-col1+1) * xw.cw,
2471 (row2-row1+1) * xw.ch);
2475 * Absolute coordinates.
2478 xclear(int x1, int y1, int x2, int y2) {
2479 XftDrawRect(xw.draw,
2480 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2481 x1, y1, x2-x1, y2-y1);
2486 XClassHint class = {opt_class ? opt_class : termname, termname};
2487 XWMHints wm = {.flags = InputHint, .input = 1};
2488 XSizeHints *sizeh = NULL;
2490 sizeh = XAllocSizeHints();
2491 if(xw.isfixed == False) {
2492 sizeh->flags = PSize | PResizeInc | PBaseSize;
2493 sizeh->height = xw.h;
2494 sizeh->width = xw.w;
2495 sizeh->height_inc = xw.ch;
2496 sizeh->width_inc = xw.cw;
2497 sizeh->base_height = 2 * borderpx;
2498 sizeh->base_width = 2 * borderpx;
2500 sizeh->flags = PMaxSize | PMinSize;
2501 sizeh->min_width = sizeh->max_width = xw.fw;
2502 sizeh->min_height = sizeh->max_height = xw.fh;
2505 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2510 xloadfont(Font *f, FcPattern *pattern) {
2514 match = FcFontMatch(NULL, pattern, &result);
2518 if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2519 FcPatternDestroy(match);
2523 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2524 FcPatternDestroy(match);
2528 f->pattern = FcPatternDuplicate(pattern);
2530 f->ascent = f->match->ascent;
2531 f->descent = f->match->descent;
2533 f->rbearing = f->match->max_advance_width;
2535 f->height = f->ascent + f->descent;
2536 f->width = f->lbearing + f->rbearing;
2542 xloadfonts(char *fontstr, int fontsize) {
2547 if(fontstr[0] == '-') {
2548 pattern = XftXlfdParse(fontstr, False, False);
2550 pattern = FcNameParse((FcChar8 *)fontstr);
2554 die("st: can't open font %s\n", fontstr);
2557 FcPatternDel(pattern, FC_PIXEL_SIZE);
2558 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2559 usedfontsize = fontsize;
2561 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2562 if(result == FcResultMatch) {
2563 usedfontsize = (int)fontval;
2566 * Default font size is 12, if none given. This is to
2567 * have a known usedfontsize value.
2569 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2574 FcConfigSubstitute(0, pattern, FcMatchPattern);
2575 FcDefaultSubstitute(pattern);
2577 if(xloadfont(&dc.font, pattern))
2578 die("st: can't open font %s\n", fontstr);
2580 /* Setting character width and height. */
2581 xw.cw = dc.font.width;
2582 xw.ch = dc.font.height;
2584 FcPatternDel(pattern, FC_SLANT);
2585 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2586 if(xloadfont(&dc.ifont, pattern))
2587 die("st: can't open font %s\n", fontstr);
2589 FcPatternDel(pattern, FC_WEIGHT);
2590 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2591 if(xloadfont(&dc.ibfont, pattern))
2592 die("st: can't open font %s\n", fontstr);
2594 FcPatternDel(pattern, FC_SLANT);
2595 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2596 if(xloadfont(&dc.bfont, pattern))
2597 die("st: can't open font %s\n", fontstr);
2599 FcPatternDestroy(pattern);
2603 xunloadfonts(void) {
2607 * Free the loaded fonts in the font cache. This is done backwards
2610 for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2613 XftFontClose(xw.dpy, frc[ip].font);
2618 XftFontClose(xw.dpy, dc.font.match);
2619 FcPatternDestroy(dc.font.pattern);
2620 FcFontSetDestroy(dc.font.set);
2621 XftFontClose(xw.dpy, dc.bfont.match);
2622 FcPatternDestroy(dc.bfont.pattern);
2623 FcFontSetDestroy(dc.bfont.set);
2624 XftFontClose(xw.dpy, dc.ifont.match);
2625 FcPatternDestroy(dc.ifont.pattern);
2626 FcFontSetDestroy(dc.ifont.set);
2627 XftFontClose(xw.dpy, dc.ibfont.match);
2628 FcPatternDestroy(dc.ibfont.pattern);
2629 FcFontSetDestroy(dc.ibfont.set);
2633 xzoom(const Arg *arg) {
2635 xloadfonts(usedfont, usedfontsize + arg->i);
2642 XSetWindowAttributes attrs;
2648 if(!(xw.dpy = XOpenDisplay(NULL)))
2649 die("Can't open display\n");
2650 xw.scr = XDefaultScreen(xw.dpy);
2651 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2655 die("Could not init fontconfig.\n");
2657 usedfont = (opt_font == NULL)? font : opt_font;
2658 xloadfonts(usedfont, 0);
2661 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2664 /* adjust fixed window geometry */
2666 sw = DisplayWidth(xw.dpy, xw.scr);
2667 sh = DisplayHeight(xw.dpy, xw.scr);
2669 xw.fx = sw + xw.fx - xw.fw - 1;
2671 xw.fy = sh + xw.fy - xw.fh - 1;
2676 /* window - default size */
2677 xw.h = 2 * borderpx + term.row * xw.ch;
2678 xw.w = 2 * borderpx + term.col * xw.cw;
2684 attrs.background_pixel = dc.col[defaultbg].pixel;
2685 attrs.border_pixel = dc.col[defaultbg].pixel;
2686 attrs.bit_gravity = NorthWestGravity;
2687 attrs.event_mask = FocusChangeMask | KeyPressMask
2688 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2689 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2690 attrs.colormap = xw.cmap;
2692 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2693 XRootWindow(xw.dpy, xw.scr);
2694 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2695 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2697 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2701 memset(&gcvalues, 0, sizeof(gcvalues));
2702 gcvalues.graphics_exposures = False;
2703 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2705 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2706 DefaultDepth(xw.dpy, xw.scr));
2707 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2708 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2710 /* Xft rendering context */
2711 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2714 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2715 XSetLocaleModifiers("@im=local");
2716 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2717 XSetLocaleModifiers("@im=");
2718 if((xw.xim = XOpenIM(xw.dpy,
2719 NULL, NULL, NULL)) == NULL) {
2720 die("XOpenIM failed. Could not open input"
2725 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2726 | XIMStatusNothing, XNClientWindow, xw.win,
2727 XNFocusWindow, xw.win, NULL);
2729 die("XCreateIC failed. Could not obtain input method.\n");
2731 /* white cursor, black outline */
2732 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2733 XDefineCursor(xw.dpy, xw.win, cursor);
2734 XRecolorCursor(xw.dpy, cursor,
2735 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2736 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2738 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2739 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2740 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2743 XMapWindow(xw.dpy, xw.win);
2749 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2750 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2751 width = charlen * xw.cw, xp, i;
2753 int u8fl, u8fblen, u8cblen, doesexist;
2756 Font *font = &dc.font;
2758 FcPattern *fcpattern, *fontpattern;
2759 FcFontSet *fcsets[] = { NULL };
2760 FcCharSet *fccharset;
2761 Colour *fg, *bg, *temp, revfg, revbg;
2762 XRenderColor colfg, colbg;
2764 frcflags = FRC_NORMAL;
2766 if(base.mode & ATTR_ITALIC) {
2767 if(base.fg == defaultfg)
2768 base.fg = defaultitalic;
2770 frcflags = FRC_ITALIC;
2771 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2772 if(base.fg == defaultfg)
2773 base.fg = defaultitalic;
2775 frcflags = FRC_ITALICBOLD;
2776 } else if(base.mode & ATTR_UNDERLINE) {
2777 if(base.fg == defaultfg)
2778 base.fg = defaultunderline;
2780 fg = &dc.col[base.fg];
2781 bg = &dc.col[base.bg];
2783 if(base.mode & ATTR_BOLD) {
2784 if(BETWEEN(base.fg, 0, 7)) {
2785 /* basic system colors */
2786 fg = &dc.col[base.fg + 8];
2787 } else if(BETWEEN(base.fg, 16, 195)) {
2789 fg = &dc.col[base.fg + 36];
2790 } else if(BETWEEN(base.fg, 232, 251)) {
2792 fg = &dc.col[base.fg + 4];
2795 * Those ranges will not be brightened:
2796 * 8 - 15 – bright system colors
2797 * 196 - 231 – highest 256 color cube
2798 * 252 - 255 – brightest colors in greyscale
2801 frcflags = FRC_BOLD;
2804 if(IS_SET(MODE_REVERSE)) {
2805 if(fg == &dc.col[defaultfg]) {
2806 fg = &dc.col[defaultbg];
2808 colfg.red = ~fg->color.red;
2809 colfg.green = ~fg->color.green;
2810 colfg.blue = ~fg->color.blue;
2811 colfg.alpha = fg->color.alpha;
2812 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2816 if(bg == &dc.col[defaultbg]) {
2817 bg = &dc.col[defaultfg];
2819 colbg.red = ~bg->color.red;
2820 colbg.green = ~bg->color.green;
2821 colbg.blue = ~bg->color.blue;
2822 colbg.alpha = bg->color.alpha;
2823 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2828 if(base.mode & ATTR_REVERSE) {
2834 /* Intelligent cleaning up of the borders. */
2836 xclear(0, (y == 0)? 0 : winy, borderpx,
2837 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2839 if(x + charlen >= term.col) {
2840 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2841 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2844 xclear(winx, 0, winx + width, borderpx);
2846 xclear(winx, winy + xw.ch, winx + width, xw.h);
2848 /* Clean up the region we want to draw to. */
2849 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2851 fcsets[0] = font->set;
2852 for(xp = winx; bytelen > 0;) {
2854 * Search for the range in the to be printed string of glyphs
2855 * that are in the main font. Then print that range. If
2856 * some glyph is found that is not in the font, do the
2864 u8cblen = utf8decode(s, &u8char);
2868 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2869 if(!doesexist || bytelen <= 0) {
2878 XftDrawStringUtf8(xw.draw, fg,
2880 winy + font->ascent,
2883 xp += font->width * u8fl;
2895 /* Search the font cache. */
2896 for(i = 0; i < frclen; i++, frp--) {
2900 if(frc[frp].c == u8char
2901 && frc[frp].flags == frcflags) {
2906 /* Nothing was found. */
2909 * Nothing was found in the cache. Now use
2910 * some dozen of Fontconfig calls to get the
2911 * font for one single character.
2913 fcpattern = FcPatternDuplicate(font->pattern);
2914 fccharset = FcCharSetCreate();
2916 FcCharSetAddChar(fccharset, u8char);
2917 FcPatternAddCharSet(fcpattern, FC_CHARSET,
2919 FcPatternAddBool(fcpattern, FC_SCALABLE,
2922 FcConfigSubstitute(0, fcpattern,
2924 FcDefaultSubstitute(fcpattern);
2926 fontpattern = FcFontSetMatch(0, fcsets,
2927 FcTrue, fcpattern, &fcres);
2930 * Overwrite or create the new cache entry.
2934 if(frccur >= LEN(frc))
2936 if(frclen > LEN(frc)) {
2938 XftFontClose(xw.dpy, frc[frccur].font);
2941 frc[frccur].font = XftFontOpenPattern(xw.dpy,
2943 frc[frccur].c = u8char;
2944 frc[frccur].flags = frcflags;
2946 FcPatternDestroy(fcpattern);
2947 FcCharSetDestroy(fccharset);
2952 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2953 xp, winy + frc[frp].font->ascent,
2954 (FcChar8 *)u8c, u8cblen);
2960 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2961 winy + font->ascent, (FcChar8 *)s, bytelen);
2964 if(base.mode & ATTR_UNDERLINE) {
2965 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2972 static int oldx = 0, oldy = 0;
2974 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
2976 LIMIT(oldx, 0, term.col-1);
2977 LIMIT(oldy, 0, term.row-1);
2979 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2981 /* remove the old cursor */
2982 sl = utf8size(term.line[oldy][oldx].c);
2983 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2986 /* draw the new one */
2987 if(!(IS_SET(MODE_HIDE))) {
2988 if(xw.state & WIN_FOCUSED) {
2989 if(IS_SET(MODE_REVERSE)) {
2990 g.mode |= ATTR_REVERSE;
2996 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2998 XftDrawRect(xw.draw, &dc.col[defaultcs],
2999 borderpx + term.c.x * xw.cw,
3000 borderpx + term.c.y * xw.ch,
3002 XftDrawRect(xw.draw, &dc.col[defaultcs],
3003 borderpx + term.c.x * xw.cw,
3004 borderpx + term.c.y * xw.ch,
3006 XftDrawRect(xw.draw, &dc.col[defaultcs],
3007 borderpx + (term.c.x + 1) * xw.cw - 1,
3008 borderpx + term.c.y * xw.ch,
3010 XftDrawRect(xw.draw, &dc.col[defaultcs],
3011 borderpx + term.c.x * xw.cw,
3012 borderpx + (term.c.y + 1) * xw.ch - 1,
3015 oldx = term.c.x, oldy = term.c.y;
3021 xsettitle(char *p) {
3024 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3026 XSetWMName(xw.dpy, xw.win, &prop);
3031 xsettitle(opt_title ? opt_title : "st");
3035 redraw(int timeout) {
3036 struct timespec tv = {0, timeout * 1000};
3042 nanosleep(&tv, NULL);
3043 XSync(xw.dpy, False); /* necessary for a good tput flash */
3049 drawregion(0, 0, term.col, term.row);
3050 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3052 XSetForeground(xw.dpy, dc.gc,
3053 dc.col[IS_SET(MODE_REVERSE)?
3054 defaultfg : defaultbg].pixel);
3058 drawregion(int x1, int y1, int x2, int y2) {
3059 int ic, ib, x, y, ox, sl;
3061 char buf[DRAW_BUF_SIZ];
3062 bool ena_sel = sel.bx != -1;
3064 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3067 if(!(xw.state & WIN_VISIBLE))
3070 for(y = y1; y < y2; y++) {
3074 xtermclear(0, y, term.col, y);
3076 base = term.line[y][0];
3078 for(x = x1; x < x2; x++) {
3079 new = term.line[y][x];
3080 if(ena_sel && *(new.c) && selected(x, y))
3081 new.mode ^= ATTR_REVERSE;
3082 if(ib > 0 && (ATTRCMP(base, new)
3083 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3084 xdraws(buf, base, ox, y, ic, ib);
3092 sl = utf8size(new.c);
3093 memcpy(buf+ib, new.c, sl);
3098 xdraws(buf, base, ox, y, ic, ib);
3104 expose(XEvent *ev) {
3105 XExposeEvent *e = &ev->xexpose;
3107 if(xw.state & WIN_REDRAW) {
3109 xw.state &= ~WIN_REDRAW;
3115 visibility(XEvent *ev) {
3116 XVisibilityEvent *e = &ev->xvisibility;
3118 if(e->state == VisibilityFullyObscured) {
3119 xw.state &= ~WIN_VISIBLE;
3120 } else if(!(xw.state & WIN_VISIBLE)) {
3121 /* need a full redraw for next Expose, not just a buf copy */
3122 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3128 xw.state &= ~WIN_VISIBLE;
3132 xseturgency(int add) {
3133 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3135 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3136 XSetWMHints(xw.dpy, xw.win, h);
3142 XFocusChangeEvent *e = &ev->xfocus;
3144 if(e->mode == NotifyGrab)
3147 if(ev->type == FocusIn) {
3148 XSetICFocus(xw.xic);
3149 xw.state |= WIN_FOCUSED;
3152 XUnsetICFocus(xw.xic);
3153 xw.state &= ~WIN_FOCUSED;
3158 match(uint mask, uint state) {
3159 state &= ~(ignoremod);
3161 if(mask == XK_NO_MOD && state)
3163 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3165 if((state & mask) != state)
3171 numlock(const Arg *dummy) {
3176 kmap(KeySym k, uint state) {
3181 /* Check for mapped keys out of X11 function keys. */
3182 for(i = 0; i < LEN(mappedkeys); i++) {
3183 if(mappedkeys[i] == k)
3186 if(i == LEN(mappedkeys)) {
3187 if((k & 0xFFFF) < 0xFD00)
3191 for(kp = key; kp < key + LEN(key); kp++) {
3197 if(!match(mask, state))
3200 if(kp->appkey > 0) {
3201 if(!IS_SET(MODE_APPKEYPAD))
3203 if(term.numlock && kp->appkey == 2)
3205 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3209 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3211 && !IS_SET(MODE_APPCURSOR))) {
3215 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3216 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3227 kpress(XEvent *ev) {
3228 XKeyEvent *e = &ev->xkey;
3230 char xstr[31], buf[32], *customkey, *cp = buf;
3235 if(IS_SET(MODE_KBDLOCK))
3238 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3239 e->state &= ~Mod2Mask;
3241 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3242 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3243 bp->func(&(bp->arg));
3248 /* 2. custom keys from config.h */
3249 if((customkey = kmap(ksym, e->state))) {
3250 len = strlen(customkey);
3251 memcpy(buf, customkey, len);
3252 /* 2. hardcoded (overrides X lookup) */
3257 if(len == 1 && e->state & Mod1Mask)
3260 memcpy(cp, xstr, len);
3261 len = cp - buf + len;
3265 if(IS_SET(MODE_ECHO))
3271 cmessage(XEvent *e) {
3274 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3276 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3277 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3278 xw.state |= WIN_FOCUSED;
3280 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3281 xw.state &= ~WIN_FOCUSED;
3283 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3284 /* Send SIGHUP to shell */
3291 cresize(int width, int height) {
3299 col = (xw.w - 2 * borderpx) / xw.cw;
3300 row = (xw.h - 2 * borderpx) / xw.ch;
3309 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3312 cresize(e->xconfigure.width, e->xconfigure.height);
3319 int xfd = XConnectionNumber(xw.dpy), xev;
3320 struct timeval drawtimeout, *tv = NULL, now, last;
3322 gettimeofday(&last, NULL);
3324 for(xev = actionfps;;) {
3326 FD_SET(cmdfd, &rfd);
3328 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3331 die("select failed: %s\n", SERRNO);
3334 gettimeofday(&now, NULL);
3335 drawtimeout.tv_sec = 0;
3336 drawtimeout.tv_usec = (1000/xfps) * 1000;
3339 if(FD_ISSET(cmdfd, &rfd))
3342 if(FD_ISSET(xfd, &rfd))
3345 if(TIMEDIFF(now, last) > \
3346 (xev ? (1000/xfps) : (1000/actionfps))) {
3347 while(XPending(xw.dpy)) {
3348 XNextEvent(xw.dpy, &ev);
3349 if(XFilterEvent(&ev, None))
3351 if(handler[ev.type])
3352 (handler[ev.type])(&ev);
3359 if(xev && !FD_ISSET(xfd, &rfd))
3361 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
3369 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3370 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3371 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3375 main(int argc, char *argv[]) {
3379 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3384 allowaltscreen = false;
3387 opt_class = EARGF(usage());
3390 /* eat all remaining arguments */
3395 opt_font = EARGF(usage());
3398 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3403 if(bitm & WidthValue)
3405 if(bitm & HeightValue)
3407 if(bitm & XNegative && xw.fx == 0)
3409 if(bitm & XNegative && xw.fy == 0)
3412 if(xw.fh != 0 && xw.fw != 0)
3416 opt_io = EARGF(usage());
3419 opt_title = EARGF(usage());
3422 opt_embed = EARGF(usage());
3430 setlocale(LC_CTYPE, "");
3431 XSetLocaleModifiers("");
3437 cresize(xw.h, xw.w);