1 /* See LICENSE for licence details. */
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
24 #include <X11/Xatom.h>
26 #include <X11/Xutil.h>
27 #include <X11/cursorfont.h>
28 #include <X11/keysym.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
39 #define Draw XftDraw *
40 #define Colour XftColor
41 #define Colourmap Colormap
42 #define Rectangle XRectangle
46 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
48 #elif defined(__FreeBSD__) || defined(__DragonFly__)
54 #define XEMBED_FOCUS_IN 4
55 #define XEMBED_FOCUS_OUT 5
59 #define ESC_BUF_SIZ (128*UTF_SIZ)
60 #define ESC_ARG_SIZ 16
61 #define STR_BUF_SIZ ESC_BUF_SIZ
62 #define STR_ARG_SIZ ESC_ARG_SIZ
63 #define DRAW_BUF_SIZ 20*1024
64 #define XK_ANY_MOD UINT_MAX
66 #define XK_SWITCH_MOD (1<<13)
68 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
71 #define SERRNO strerror(errno)
72 #define MIN(a, b) ((a) < (b) ? (a) : (b))
73 #define MAX(a, b) ((a) < (b) ? (b) : (a))
74 #define LEN(a) (sizeof(a) / sizeof(a[0]))
75 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
76 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
77 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
78 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
79 #define IS_SET(flag) ((term.mode & (flag)) != 0)
80 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
81 #define CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
83 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
84 #define IS_TRUECOL(x) (1 << 24 & (x))
85 #define TRUERED(x) (((x) & 0xff0000) >> 8)
86 #define TRUEGREEN(x) (((x) & 0xff00))
87 #define TRUEBLUE(x) (((x) & 0xff) << 8)
90 #define VT102ID "\033[?6c"
92 enum glyph_attribute {
105 enum cursor_movement {
123 MODE_MOUSEMOTION = 64,
128 MODE_APPCURSOR = 2048,
129 MODE_MOUSESGR = 4096,
134 MODE_MOUSEX10 = 131072,
135 MODE_MOUSEMANY = 262144,
136 MODE_BRCKTPASTE = 524288,
137 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
154 ESC_STR = 4, /* DSC, OSC, PM, APC */
156 ESC_STR_END = 16, /* a final string was encountered */
157 ESC_TEST = 32, /* Enter in test mode */
166 enum selection_type {
171 enum selection_snap {
176 typedef unsigned char uchar;
177 typedef unsigned int uint;
178 typedef unsigned long ulong;
179 typedef unsigned short ushort;
182 char c[UTF_SIZ]; /* character code */
183 ushort mode; /* attribute flags */
184 uint32_t fg; /* foreground */
185 uint32_t bg; /* background */
191 Glyph attr; /* current char attributes */
197 /* CSI Escape sequence structs */
198 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
200 char buf[ESC_BUF_SIZ]; /* raw string */
201 int len; /* raw string length */
203 int arg[ESC_ARG_SIZ];
204 int narg; /* nb of args */
208 /* STR Escape sequence structs */
209 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
211 char type; /* ESC type ... */
212 char buf[STR_BUF_SIZ]; /* raw string */
213 int len; /* raw string length */
214 char *args[STR_ARG_SIZ];
215 int narg; /* nb of args */
218 /* Internal representation of the screen */
220 int row; /* nb row */
221 int col; /* nb col */
222 Line *line; /* screen */
223 Line *alt; /* alternate screen */
224 bool *dirty; /* dirtyness of lines */
225 TCursor c; /* cursor */
226 int top; /* top scroll limit */
227 int bot; /* bottom scroll limit */
228 int mode; /* terminal mode flags */
229 int esc; /* escape state flags */
230 char trantbl[4]; /* charset table translation */
231 int charset; /* current charset */
232 int icharset; /* selected charset for sequence */
233 bool numlock; /* lock numbers in keyboard */
237 /* Purely graphic info */
243 Atom xembed, wmdeletewin, netwmname, netwmpid;
248 XSetWindowAttributes attrs;
250 bool isfixed; /* is fixed geometry? */
251 int fx, fy, fw, fh; /* fixed geometry */
252 int tw, th; /* tty width and height */
253 int w, h; /* window width and height */
254 int ch; /* char height */
255 int cw; /* char width */
256 char state; /* focus, redraw, visible */
269 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
270 signed char appkey; /* application keypad */
271 signed char appcursor; /* application cursor */
272 signed char crlf; /* crlf mode */
280 * Selection variables:
281 * nb – normalized coordinates of the beginning of the selection
282 * ne – normalized coordinates of the end of the selection
283 * ob – original coordinates of the beginning of the selection
284 * oe – original coordinates of the end of the selection
293 struct timeval tclick1;
294 struct timeval tclick2;
307 void (*func)(const Arg *);
311 /* function definitions used in config.h */
312 static void clippaste(const Arg *);
313 static void numlock(const Arg *);
314 static void selpaste(const Arg *);
315 static void xzoom(const Arg *);
317 /* Config.h for applying patches and the configuration. */
333 /* Drawing Context */
335 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
336 Font font, bfont, ifont, ibfont;
340 static void die(const char *, ...);
341 static void draw(void);
342 static void redraw(int);
343 static void drawregion(int, int, int, int);
344 static void execsh(void);
345 static void sigchld(int);
346 static void run(void);
348 static void csidump(void);
349 static void csihandle(void);
350 static void csiparse(void);
351 static void csireset(void);
352 static void strdump(void);
353 static void strhandle(void);
354 static void strparse(void);
355 static void strreset(void);
357 static int tattrset(int);
358 static void tclearregion(int, int, int, int);
359 static void tcursor(int);
360 static void tdeletechar(int);
361 static void tdeleteline(int);
362 static void tinsertblank(int);
363 static void tinsertblankline(int);
364 static void tmoveto(int, int);
365 static void tmoveato(int x, int y);
366 static void tnew(int, int);
367 static void tnewline(int);
368 static void tputtab(bool);
369 static void tputc(char *, int);
370 static void treset(void);
371 static int tresize(int, int);
372 static void tscrollup(int, int);
373 static void tscrolldown(int, int);
374 static void tsetattr(int*, int);
375 static void tsetchar(char *, Glyph *, int, int);
376 static void tsetscroll(int, int);
377 static void tswapscreen(void);
378 static void tsetdirt(int, int);
379 static void tsetdirtattr(int);
380 static void tsetmode(bool, bool, int *, int);
381 static void tfulldirt(void);
382 static void techo(char *, int);
383 static int32_t tdefcolor(int *, int *, int);
384 static void tselcs(void);
385 static void tdeftran(char);
386 static inline bool match(uint, uint);
387 static void ttynew(void);
388 static void ttyread(void);
389 static void ttyresize(void);
390 static void ttysend(char *, size_t);
391 static void ttywrite(const char *, size_t);
393 static void xdraws(char *, Glyph, int, int, int, int);
394 static void xhints(void);
395 static void xclear(int, int, int, int);
396 static void xdrawcursor(void);
397 static void xinit(void);
398 static void xloadcols(void);
399 static int xsetcolorname(int, const char *);
400 static int xloadfont(Font *, FcPattern *);
401 static void xloadfonts(char *, double);
402 static int xloadfontset(Font *);
403 static void xsettitle(char *);
404 static void xresettitle(void);
405 static void xsetpointermotion(int);
406 static void xseturgency(int);
407 static void xsetsel(char*);
408 static void xtermclear(int, int, int, int);
409 static void xunloadfont(Font *f);
410 static void xunloadfonts(void);
411 static void xresize(int, int);
413 static void expose(XEvent *);
414 static void visibility(XEvent *);
415 static void unmap(XEvent *);
416 static char *kmap(KeySym, uint);
417 static void kpress(XEvent *);
418 static void cmessage(XEvent *);
419 static void cresize(int, int);
420 static void resize(XEvent *);
421 static void focus(XEvent *);
422 static void brelease(XEvent *);
423 static void bpress(XEvent *);
424 static void bmotion(XEvent *);
425 static void selnotify(XEvent *);
426 static void selclear(XEvent *);
427 static void selrequest(XEvent *);
429 static void selinit(void);
430 static void selsort(void);
431 static inline bool selected(int, int);
432 static void selcopy(void);
433 static void selscroll(int, int);
434 static void selsnap(int, int *, int *, int);
436 static int utf8decode(char *, long *);
437 static int utf8encode(long *, char *);
438 static int utf8size(char *);
439 static int isfullutf8(char *, int);
441 static ssize_t xwrite(int, char *, size_t);
442 static void *xmalloc(size_t);
443 static void *xrealloc(void *, size_t);
444 static char *xstrdup(char *s);
446 static void (*handler[LASTEvent])(XEvent *) = {
448 [ClientMessage] = cmessage,
449 [ConfigureNotify] = resize,
450 [VisibilityNotify] = visibility,
451 [UnmapNotify] = unmap,
455 [MotionNotify] = bmotion,
456 [ButtonPress] = bpress,
457 [ButtonRelease] = brelease,
458 [SelectionClear] = selclear,
459 [SelectionNotify] = selnotify,
460 [SelectionRequest] = selrequest,
467 static CSIEscape csiescseq;
468 static STREscape strescseq;
471 static Selection sel;
472 static int iofd = -1;
473 static char **opt_cmd = NULL;
474 static char *opt_io = NULL;
475 static char *opt_title = NULL;
476 static char *opt_embed = NULL;
477 static char *opt_class = NULL;
478 static char *opt_font = NULL;
479 static int oldbutton = 3; /* button event on startup: 3 = release */
481 static char *usedfont = NULL;
482 static double usedfontsize = 0;
484 /* Font Ring Cache */
497 /* Fontcache is an array now. A new font will be appended to the array. */
498 static Fontcache frc[16];
499 static int frclen = 0;
502 xwrite(int fd, char *s, size_t len) {
506 ssize_t r = write(fd, s, len);
516 xmalloc(size_t len) {
517 void *p = malloc(len);
520 die("Out of memory\n");
526 xrealloc(void *p, size_t len) {
527 if((p = realloc(p, len)) == NULL)
528 die("Out of memory\n");
538 die("Out of memory\n");
544 utf8decode(char *s, long *u) {
550 if(~c & 0x80) { /* 0xxxxxxx */
553 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
556 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
559 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
566 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
568 if((c & 0xC0) != 0x80) /* 10xxxxxx */
574 if((n == 1 && *u < 0x80) ||
575 (n == 2 && *u < 0x800) ||
576 (n == 3 && *u < 0x10000) ||
577 (*u >= 0xD800 && *u <= 0xDFFF)) {
589 utf8encode(long *u, char *s) {
597 *sp = uc; /* 0xxxxxxx */
599 } else if(*u < 0x800) {
600 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
602 } else if(uc < 0x10000) {
603 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
605 } else if(uc <= 0x10FFFF) {
606 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
612 for(i=n,++sp; i>0; --i,++sp)
613 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
625 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
626 UTF-8 otherwise return 0 */
628 isfullutf8(char *s, int b) {
636 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
638 } else if((*c1 & 0xF0) == 0xE0 &&
640 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
642 } else if((*c1 & 0xF8) == 0xF0 &&
644 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
645 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
658 } else if((c & 0xE0) == 0xC0) {
660 } else if((c & 0xF0) == 0xE0) {
669 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
670 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
674 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
675 if(sel.xtarget == None)
676 sel.xtarget = XA_STRING;
684 return LIMIT(x, 0, term.col-1);
692 return LIMIT(y, 0, term.row-1);
697 if(sel.ob.y == sel.oe.y) {
698 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
699 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
701 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
702 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
704 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
705 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
709 selected(int x, int y) {
710 if(sel.ne.y == y && sel.nb.y == y)
711 return BETWEEN(x, sel.nb.x, sel.ne.x);
713 if(sel.type == SEL_RECTANGULAR) {
714 return ((sel.nb.y <= y && y <= sel.ne.y)
715 && (sel.nb.x <= x && x <= sel.ne.x));
718 return ((sel.nb.y < y && y < sel.ne.y)
719 || (y == sel.ne.y && x <= sel.ne.x))
720 || (y == sel.nb.y && x >= sel.nb.x
721 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
725 selsnap(int mode, int *x, int *y, int direction) {
731 * Snap around if the word wraps around at the end or
732 * beginning of a line.
735 if(direction < 0 && *x <= 0) {
736 if(*y > 0 && term.line[*y - 1][term.col-1].mode
744 if(direction > 0 && *x >= term.col-1) {
745 if(*y < term.row-1 && term.line[*y][*x].mode
754 if(term.line[*y][*x+direction].mode & ATTR_WDUMMY) {
759 if(strchr(worddelimiters,
760 term.line[*y][*x+direction].c[0])) {
769 * Snap around if the the previous line or the current one
770 * has set ATTR_WRAP at its end. Then the whole next or
771 * previous line will be selected.
773 *x = (direction < 0) ? 0 : term.col - 1;
774 if(direction < 0 && *y > 0) {
775 for(; *y > 0; *y += direction) {
776 if(!(term.line[*y-1][term.col-1].mode
781 } else if(direction > 0 && *y < term.row-1) {
782 for(; *y < term.row; *y += direction) {
783 if(!(term.line[*y][term.col-1].mode
792 * Select the whole line when the end of line is reached.
796 while(--i > 0 && term.line[*y][i].c[0] == ' ')
806 getbuttoninfo(XEvent *e) {
808 uint state = e->xbutton.state &~Button1Mask;
810 sel.alt = IS_SET(MODE_ALTSCREEN);
812 sel.oe.x = x2col(e->xbutton.x);
813 sel.oe.y = y2row(e->xbutton.y);
815 if(sel.ob.y < sel.oe.y
816 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
817 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
818 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
820 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
821 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
825 sel.type = SEL_REGULAR;
826 for(type = 1; type < LEN(selmasks); ++type) {
827 if(match(selmasks[type], state)) {
835 mousereport(XEvent *e) {
836 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
837 button = e->xbutton.button, state = e->xbutton.state,
843 if(e->xbutton.type == MotionNotify) {
844 if(x == ox && y == oy)
846 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
848 /* MOUSE_MOTION: no reporting if no button is pressed */
849 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
852 button = oldbutton + 32;
856 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
863 if(e->xbutton.type == ButtonPress) {
867 } else if(e->xbutton.type == ButtonRelease) {
869 /* MODE_MOUSEX10: no button release reporting */
870 if(IS_SET(MODE_MOUSEX10))
875 if(!IS_SET(MODE_MOUSEX10)) {
876 button += (state & ShiftMask ? 4 : 0)
877 + (state & Mod4Mask ? 8 : 0)
878 + (state & ControlMask ? 16 : 0);
882 if(IS_SET(MODE_MOUSESGR)) {
883 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
885 e->xbutton.type == ButtonRelease ? 'm' : 'M');
886 } else if(x < 223 && y < 223) {
887 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
888 32+button, 32+x+1, 32+y+1);
901 if(IS_SET(MODE_MOUSE)) {
906 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
907 if(e->xbutton.button == mk->b
908 && match(mk->mask, e->xbutton.state)) {
909 ttysend(mk->s, strlen(mk->s));
914 if(e->xbutton.button == Button1) {
915 gettimeofday(&now, NULL);
917 /* Clear previous selection, logically and visually. */
920 sel.type = SEL_REGULAR;
921 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
922 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
925 * If the user clicks below predefined timeouts specific
926 * snapping behaviour is exposed.
928 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
929 sel.snap = SNAP_LINE;
930 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
931 sel.snap = SNAP_WORD;
935 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
936 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
940 * Draw selection, unless it's regular and we don't want to
941 * make clicks visible
945 tsetdirt(sel.nb.y, sel.ne.y);
947 sel.tclick2 = sel.tclick1;
955 int x, y, bufsize, size, i, ex;
961 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
962 ptr = str = xmalloc(bufsize);
964 /* append every set & selected glyph to the selection */
965 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
966 gp = &term.line[y][0];
967 last = &gp[term.col-1];
969 while(last >= gp && !(selected(last - gp, y) &&
970 strcmp(last->c, " ") != 0)) {
974 for(x = 0; gp <= last; x++, ++gp) {
975 if(!selected(x, y) || (gp->mode & ATTR_WDUMMY))
978 size = utf8size(gp->c);
979 memcpy(ptr, gp->c, size);
984 * Copy and pasting of line endings is inconsistent
985 * in the inconsistent terminal and GUI world.
986 * The best solution seems like to produce '\n' when
987 * something is copied from st and convert '\n' to
988 * '\r', when something to be pasted is received by
990 * FIXME: Fix the computer world.
992 if(y < sel.ne.y && x > 0 && !((gp-1)->mode & ATTR_WRAP))
996 * If the last selected line expands in the selection
997 * after the visible text '\n' is appended.
1001 while(--i > 0 && term.line[y][i].c[0] == ' ')
1004 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
1016 selnotify(XEvent *e) {
1017 ulong nitems, ofs, rem;
1019 uchar *data, *last, *repl;
1024 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
1025 False, AnyPropertyType, &type, &format,
1026 &nitems, &rem, &data)) {
1027 fprintf(stderr, "Clipboard allocation failed\n");
1032 * As seen in selcopy:
1033 * Line endings are inconsistent in the terminal and GUI world
1034 * copy and pasting. When receiving some selection data,
1035 * replace all '\n' with '\r'.
1036 * FIXME: Fix the computer world.
1039 last = data + nitems * format / 8;
1040 while((repl = memchr(repl, '\n', last - repl))) {
1044 if(IS_SET(MODE_BRCKTPASTE))
1045 ttywrite("\033[200~", 6);
1046 ttysend((char *)data, nitems * format / 8);
1047 if(IS_SET(MODE_BRCKTPASTE))
1048 ttywrite("\033[201~", 6);
1050 /* number of 32-bit chunks returned */
1051 ofs += nitems * format / 32;
1056 selpaste(const Arg *dummy) {
1057 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1058 xw.win, CurrentTime);
1062 clippaste(const Arg *dummy) {
1065 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1066 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1067 xw.win, CurrentTime);
1071 selclear(XEvent *e) {
1075 tsetdirt(sel.nb.y, sel.ne.y);
1079 selrequest(XEvent *e) {
1080 XSelectionRequestEvent *xsre;
1081 XSelectionEvent xev;
1082 Atom xa_targets, string;
1084 xsre = (XSelectionRequestEvent *) e;
1085 xev.type = SelectionNotify;
1086 xev.requestor = xsre->requestor;
1087 xev.selection = xsre->selection;
1088 xev.target = xsre->target;
1089 xev.time = xsre->time;
1091 xev.property = None;
1093 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1094 if(xsre->target == xa_targets) {
1095 /* respond with the supported type */
1096 string = sel.xtarget;
1097 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1098 XA_ATOM, 32, PropModeReplace,
1099 (uchar *) &string, 1);
1100 xev.property = xsre->property;
1101 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1102 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1103 xsre->target, 8, PropModeReplace,
1104 (uchar *) sel.clip, strlen(sel.clip));
1105 xev.property = xsre->property;
1108 /* all done, send a notification to the listener */
1109 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1110 fprintf(stderr, "Error sending SelectionNotify event\n");
1114 xsetsel(char *str) {
1115 /* register the selection for both the clipboard and the primary */
1121 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1123 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1124 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1128 brelease(XEvent *e) {
1129 if(IS_SET(MODE_MOUSE)) {
1134 if(e->xbutton.button == Button2) {
1136 } else if(e->xbutton.button == Button1) {
1144 tsetdirt(sel.nb.y, sel.ne.y);
1149 bmotion(XEvent *e) {
1150 int oldey, oldex, oldsby, oldsey;
1152 if(IS_SET(MODE_MOUSE)) {
1167 if(oldey != sel.oe.y || oldex != sel.oe.x)
1168 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1172 die(const char *errstr, ...) {
1175 va_start(ap, errstr);
1176 vfprintf(stderr, errstr, ap);
1184 char *envshell = getenv("SHELL");
1185 const struct passwd *pass = getpwuid(getuid());
1186 char buf[sizeof(long) * 8 + 1];
1188 unsetenv("COLUMNS");
1190 unsetenv("TERMCAP");
1193 setenv("LOGNAME", pass->pw_name, 1);
1194 setenv("USER", pass->pw_name, 1);
1195 setenv("SHELL", pass->pw_shell, 0);
1196 setenv("HOME", pass->pw_dir, 0);
1199 snprintf(buf, sizeof(buf), "%lu", xw.win);
1200 setenv("WINDOWID", buf, 1);
1202 signal(SIGCHLD, SIG_DFL);
1203 signal(SIGHUP, SIG_DFL);
1204 signal(SIGINT, SIG_DFL);
1205 signal(SIGQUIT, SIG_DFL);
1206 signal(SIGTERM, SIG_DFL);
1207 signal(SIGALRM, SIG_DFL);
1209 DEFAULT(envshell, shell);
1210 setenv("TERM", termname, 1);
1211 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1212 execvp(args[0], args);
1220 if(waitpid(pid, &stat, 0) < 0)
1221 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1223 if(WIFEXITED(stat)) {
1224 exit(WEXITSTATUS(stat));
1233 struct winsize w = {term.row, term.col, 0, 0};
1235 /* seems to work fine on linux, openbsd and freebsd */
1236 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1237 die("openpty failed: %s\n", SERRNO);
1239 switch(pid = fork()) {
1241 die("fork failed\n");
1244 setsid(); /* create a new process group */
1245 dup2(s, STDIN_FILENO);
1246 dup2(s, STDOUT_FILENO);
1247 dup2(s, STDERR_FILENO);
1248 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1249 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1257 signal(SIGCHLD, sigchld);
1259 iofd = (!strcmp(opt_io, "-")) ?
1261 open(opt_io, O_WRONLY | O_CREAT, 0666);
1263 fprintf(stderr, "Error opening %s:%s\n",
1264 opt_io, strerror(errno));
1274 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1276 fprintf(stderr, "\n");
1281 static char buf[BUFSIZ];
1282 static int buflen = 0;
1285 int charsize; /* size of utf8 char in bytes */
1289 /* append read bytes to unprocessed bytes */
1290 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1291 die("Couldn't read from shell: %s\n", SERRNO);
1293 /* process every complete utf8 char */
1296 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1297 charsize = utf8decode(ptr, &utf8c);
1298 utf8encode(&utf8c, s);
1304 /* keep any uncomplete utf8 char for the next call */
1305 memmove(buf, ptr, buflen);
1309 ttywrite(const char *s, size_t n) {
1310 if(write(cmdfd, s, n) == -1)
1311 die("write error on tty: %s\n", SERRNO);
1315 ttysend(char *s, size_t n) {
1317 if(IS_SET(MODE_ECHO))
1325 w.ws_row = term.row;
1326 w.ws_col = term.col;
1327 w.ws_xpixel = xw.tw;
1328 w.ws_ypixel = xw.th;
1329 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1330 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1334 tattrset(int attr) {
1337 for(i = 0; i < term.row-1; i++) {
1338 for(j = 0; j < term.col-1; j++) {
1339 if(term.line[i][j].mode & attr)
1348 tsetdirt(int top, int bot) {
1351 LIMIT(top, 0, term.row-1);
1352 LIMIT(bot, 0, term.row-1);
1354 for(i = top; i <= bot; i++)
1359 tsetdirtattr(int attr) {
1362 for(i = 0; i < term.row-1; i++) {
1363 for(j = 0; j < term.col-1; j++) {
1364 if(term.line[i][j].mode & attr) {
1374 tsetdirt(0, term.row-1);
1379 static TCursor c[2];
1380 bool alt = IS_SET(MODE_ALTSCREEN);
1382 if(mode == CURSOR_SAVE) {
1384 } else if(mode == CURSOR_LOAD) {
1386 tmoveto(c[alt].x, c[alt].y);
1394 term.c = (TCursor){{
1398 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1400 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1401 for(i = tabspaces; i < term.col; i += tabspaces)
1404 term.bot = term.row - 1;
1405 term.mode = MODE_WRAP;
1406 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1409 tclearregion(0, 0, term.col-1, term.row-1);
1411 tcursor(CURSOR_SAVE);
1415 tnew(int col, int row) {
1416 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1425 Line *tmp = term.line;
1427 term.line = term.alt;
1429 term.mode ^= MODE_ALTSCREEN;
1434 tscrolldown(int orig, int n) {
1438 LIMIT(n, 0, term.bot-orig+1);
1440 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1442 for(i = term.bot; i >= orig+n; i--) {
1443 temp = term.line[i];
1444 term.line[i] = term.line[i-n];
1445 term.line[i-n] = temp;
1448 term.dirty[i-n] = 1;
1455 tscrollup(int orig, int n) {
1458 LIMIT(n, 0, term.bot-orig+1);
1460 tclearregion(0, orig, term.col-1, orig+n-1);
1462 for(i = orig; i <= term.bot-n; i++) {
1463 temp = term.line[i];
1464 term.line[i] = term.line[i+n];
1465 term.line[i+n] = temp;
1468 term.dirty[i+n] = 1;
1471 selscroll(orig, -n);
1475 selscroll(int orig, int n) {
1479 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1480 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1484 if(sel.type == SEL_RECTANGULAR) {
1485 if(sel.ob.y < term.top)
1486 sel.ob.y = term.top;
1487 if(sel.oe.y > term.bot)
1488 sel.oe.y = term.bot;
1490 if(sel.ob.y < term.top) {
1491 sel.ob.y = term.top;
1494 if(sel.oe.y > term.bot) {
1495 sel.oe.y = term.bot;
1496 sel.oe.x = term.col;
1504 tnewline(int first_col) {
1508 tscrollup(term.top, 1);
1512 tmoveto(first_col ? 0 : term.c.x, y);
1517 char *p = csiescseq.buf, *np;
1526 csiescseq.buf[csiescseq.len] = '\0';
1527 while(p < csiescseq.buf+csiescseq.len) {
1529 v = strtol(p, &np, 10);
1532 if(v == LONG_MAX || v == LONG_MIN)
1534 csiescseq.arg[csiescseq.narg++] = v;
1536 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1540 csiescseq.mode = *p;
1543 /* for absolute user moves, when decom is set */
1545 tmoveato(int x, int y) {
1546 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1550 tmoveto(int x, int y) {
1553 if(term.c.state & CURSOR_ORIGIN) {
1558 maxy = term.row - 1;
1560 LIMIT(x, 0, term.col-1);
1561 LIMIT(y, miny, maxy);
1562 term.c.state &= ~CURSOR_WRAPNEXT;
1568 tsetchar(char *c, Glyph *attr, int x, int y) {
1569 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1570 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1571 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1572 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1573 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1574 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1575 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1576 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1577 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1581 * The table is proudly stolen from rxvt.
1583 if(attr->mode & ATTR_GFX) {
1584 if(c[0] >= 0x41 && c[0] <= 0x7e
1585 && vt100_0[c[0] - 0x41]) {
1586 c = vt100_0[c[0] - 0x41];
1590 if(term.line[y][x].mode & ATTR_WIDE) {
1591 if(x+1 < term.col) {
1592 term.line[y][x+1].c[0] = ' ';
1593 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1595 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1596 term.line[y][x-1].c[0] = ' ';
1597 term.line[y][x-1].mode &= ~ATTR_WIDE;
1601 term.line[y][x] = *attr;
1602 memcpy(term.line[y][x].c, c, UTF_SIZ);
1606 tclearregion(int x1, int y1, int x2, int y2) {
1610 temp = x1, x1 = x2, x2 = temp;
1612 temp = y1, y1 = y2, y2 = temp;
1614 LIMIT(x1, 0, term.col-1);
1615 LIMIT(x2, 0, term.col-1);
1616 LIMIT(y1, 0, term.row-1);
1617 LIMIT(y2, 0, term.row-1);
1619 for(y = y1; y <= y2; y++) {
1621 for(x = x1; x <= x2; x++) {
1624 term.line[y][x] = term.c.attr;
1625 memcpy(term.line[y][x].c, " ", 2);
1631 tdeletechar(int n) {
1632 int src = term.c.x + n;
1634 int size = term.col - src;
1636 term.dirty[term.c.y] = 1;
1638 if(src >= term.col) {
1639 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1643 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1644 size * sizeof(Glyph));
1645 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1649 tinsertblank(int n) {
1652 int size = term.col - dst;
1654 term.dirty[term.c.y] = 1;
1656 if(dst >= term.col) {
1657 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1661 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1662 size * sizeof(Glyph));
1663 tclearregion(src, term.c.y, dst - 1, term.c.y);
1667 tinsertblankline(int n) {
1668 if(term.c.y < term.top || term.c.y > term.bot)
1671 tscrolldown(term.c.y, n);
1675 tdeleteline(int n) {
1676 if(term.c.y < term.top || term.c.y > term.bot)
1679 tscrollup(term.c.y, n);
1683 tdefcolor(int *attr, int *npar, int l) {
1687 switch (attr[*npar + 1]) {
1688 case 2: /* direct colour in RGB space */
1689 if (*npar + 4 >= l) {
1691 "erresc(38): Incorrect number of parameters (%d)\n",
1695 r = attr[*npar + 2];
1696 g = attr[*npar + 3];
1697 b = attr[*npar + 4];
1699 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1700 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1703 idx = TRUECOLOR(r, g, b);
1705 case 5: /* indexed colour */
1706 if (*npar + 2 >= l) {
1708 "erresc(38): Incorrect number of parameters (%d)\n",
1713 if(!BETWEEN(attr[*npar], 0, 255))
1714 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1718 case 0: /* implemented defined (only foreground) */
1719 case 1: /* transparent */
1720 case 3: /* direct colour in CMY space */
1721 case 4: /* direct colour in CMYK space */
1724 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1731 tsetattr(int *attr, int l) {
1735 for(i = 0; i < l; i++) {
1738 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1739 | ATTR_BOLD | ATTR_ITALIC \
1741 term.c.attr.fg = defaultfg;
1742 term.c.attr.bg = defaultbg;
1745 term.c.attr.mode |= ATTR_BOLD;
1748 term.c.attr.mode |= ATTR_ITALIC;
1751 term.c.attr.mode |= ATTR_UNDERLINE;
1753 case 5: /* slow blink */
1754 case 6: /* rapid blink */
1755 term.c.attr.mode |= ATTR_BLINK;
1758 term.c.attr.mode |= ATTR_REVERSE;
1762 term.c.attr.mode &= ~ATTR_BOLD;
1765 term.c.attr.mode &= ~ATTR_ITALIC;
1768 term.c.attr.mode &= ~ATTR_UNDERLINE;
1772 term.c.attr.mode &= ~ATTR_BLINK;
1775 term.c.attr.mode &= ~ATTR_REVERSE;
1778 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1779 term.c.attr.fg = idx;
1782 term.c.attr.fg = defaultfg;
1785 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1786 term.c.attr.bg = idx;
1789 term.c.attr.bg = defaultbg;
1792 if(BETWEEN(attr[i], 30, 37)) {
1793 term.c.attr.fg = attr[i] - 30;
1794 } else if(BETWEEN(attr[i], 40, 47)) {
1795 term.c.attr.bg = attr[i] - 40;
1796 } else if(BETWEEN(attr[i], 90, 97)) {
1797 term.c.attr.fg = attr[i] - 90 + 8;
1798 } else if(BETWEEN(attr[i], 100, 107)) {
1799 term.c.attr.bg = attr[i] - 100 + 8;
1802 "erresc(default): gfx attr %d unknown\n",
1803 attr[i]), csidump();
1811 tsetscroll(int t, int b) {
1814 LIMIT(t, 0, term.row-1);
1815 LIMIT(b, 0, term.row-1);
1825 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1828 tsetmode(bool priv, bool set, int *args, int narg) {
1832 for(lim = args + narg; args < lim; ++args) {
1836 case 1: /* DECCKM -- Cursor key */
1837 MODBIT(term.mode, set, MODE_APPCURSOR);
1839 case 5: /* DECSCNM -- Reverse video */
1841 MODBIT(term.mode, set, MODE_REVERSE);
1842 if(mode != term.mode)
1843 redraw(REDRAW_TIMEOUT);
1845 case 6: /* DECOM -- Origin */
1846 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1849 case 7: /* DECAWM -- Auto wrap */
1850 MODBIT(term.mode, set, MODE_WRAP);
1852 case 0: /* Error (IGNORED) */
1853 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1854 case 3: /* DECCOLM -- Column (IGNORED) */
1855 case 4: /* DECSCLM -- Scroll (IGNORED) */
1856 case 8: /* DECARM -- Auto repeat (IGNORED) */
1857 case 18: /* DECPFF -- Printer feed (IGNORED) */
1858 case 19: /* DECPEX -- Printer extent (IGNORED) */
1859 case 42: /* DECNRCM -- National characters (IGNORED) */
1860 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1862 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1863 MODBIT(term.mode, !set, MODE_HIDE);
1865 case 9: /* X10 mouse compatibility mode */
1866 xsetpointermotion(0);
1867 MODBIT(term.mode, 0, MODE_MOUSE);
1868 MODBIT(term.mode, set, MODE_MOUSEX10);
1870 case 1000: /* 1000: report button press */
1871 xsetpointermotion(0);
1872 MODBIT(term.mode, 0, MODE_MOUSE);
1873 MODBIT(term.mode, set, MODE_MOUSEBTN);
1875 case 1002: /* 1002: report motion on button press */
1876 xsetpointermotion(0);
1877 MODBIT(term.mode, 0, MODE_MOUSE);
1878 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1880 case 1003: /* 1003: enable all mouse motions */
1881 xsetpointermotion(set);
1882 MODBIT(term.mode, 0, MODE_MOUSE);
1883 MODBIT(term.mode, set, MODE_MOUSEMANY);
1885 case 1004: /* 1004: send focus events to tty */
1886 MODBIT(term.mode, set, MODE_FOCUS);
1888 case 1006: /* 1006: extended reporting mode */
1889 MODBIT(term.mode, set, MODE_MOUSESGR);
1892 MODBIT(term.mode, set, MODE_8BIT);
1894 case 1049: /* swap screen & set/restore cursor as xterm */
1895 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1896 case 47: /* swap screen */
1898 if (!allowaltscreen)
1900 alt = IS_SET(MODE_ALTSCREEN);
1902 tclearregion(0, 0, term.col-1,
1905 if(set ^ alt) /* set is always 1 or 0 */
1911 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1913 case 2004: /* 2004: bracketed paste mode */
1914 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1916 /* Not implemented mouse modes. See comments there. */
1917 case 1001: /* mouse highlight mode; can hang the
1918 terminal by design when implemented. */
1919 case 1005: /* UTF-8 mouse mode; will confuse
1920 applications not supporting UTF-8
1922 case 1015: /* urxvt mangled mouse mode; incompatible
1923 and can be mistaken for other control
1927 "erresc: unknown private set/reset mode %d\n",
1933 case 0: /* Error (IGNORED) */
1935 case 2: /* KAM -- keyboard action */
1936 MODBIT(term.mode, set, MODE_KBDLOCK);
1938 case 4: /* IRM -- Insertion-replacement */
1939 MODBIT(term.mode, set, MODE_INSERT);
1941 case 12: /* SRM -- Send/Receive */
1942 MODBIT(term.mode, !set, MODE_ECHO);
1944 case 20: /* LNM -- Linefeed/new line */
1945 MODBIT(term.mode, set, MODE_CRLF);
1949 "erresc: unknown set/reset mode %d\n",
1962 switch(csiescseq.mode) {
1965 fprintf(stderr, "erresc: unknown csi ");
1969 case '@': /* ICH -- Insert <n> blank char */
1970 DEFAULT(csiescseq.arg[0], 1);
1971 tinsertblank(csiescseq.arg[0]);
1973 case 'A': /* CUU -- Cursor <n> Up */
1974 DEFAULT(csiescseq.arg[0], 1);
1975 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1977 case 'B': /* CUD -- Cursor <n> Down */
1978 case 'e': /* VPR --Cursor <n> Down */
1979 DEFAULT(csiescseq.arg[0], 1);
1980 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1982 case 'c': /* DA -- Device Attributes */
1983 if(csiescseq.arg[0] == 0)
1984 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1986 case 'C': /* CUF -- Cursor <n> Forward */
1987 case 'a': /* HPR -- Cursor <n> Forward */
1988 DEFAULT(csiescseq.arg[0], 1);
1989 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1991 case 'D': /* CUB -- Cursor <n> Backward */
1992 DEFAULT(csiescseq.arg[0], 1);
1993 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1995 case 'E': /* CNL -- Cursor <n> Down and first col */
1996 DEFAULT(csiescseq.arg[0], 1);
1997 tmoveto(0, term.c.y+csiescseq.arg[0]);
1999 case 'F': /* CPL -- Cursor <n> Up and first col */
2000 DEFAULT(csiescseq.arg[0], 1);
2001 tmoveto(0, term.c.y-csiescseq.arg[0]);
2003 case 'g': /* TBC -- Tabulation clear */
2004 switch(csiescseq.arg[0]) {
2005 case 0: /* clear current tab stop */
2006 term.tabs[term.c.x] = 0;
2008 case 3: /* clear all the tabs */
2009 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2015 case 'G': /* CHA -- Move to <col> */
2017 DEFAULT(csiescseq.arg[0], 1);
2018 tmoveto(csiescseq.arg[0]-1, term.c.y);
2020 case 'H': /* CUP -- Move to <row> <col> */
2022 DEFAULT(csiescseq.arg[0], 1);
2023 DEFAULT(csiescseq.arg[1], 1);
2024 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2026 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2027 DEFAULT(csiescseq.arg[0], 1);
2028 while(csiescseq.arg[0]--)
2031 case 'J': /* ED -- Clear screen */
2033 switch(csiescseq.arg[0]) {
2035 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2036 if(term.c.y < term.row-1) {
2037 tclearregion(0, term.c.y+1, term.col-1,
2043 tclearregion(0, 0, term.col-1, term.c.y-1);
2044 tclearregion(0, term.c.y, term.c.x, term.c.y);
2047 tclearregion(0, 0, term.col-1, term.row-1);
2053 case 'K': /* EL -- Clear line */
2054 switch(csiescseq.arg[0]) {
2056 tclearregion(term.c.x, term.c.y, term.col-1,
2060 tclearregion(0, term.c.y, term.c.x, term.c.y);
2063 tclearregion(0, term.c.y, term.col-1, term.c.y);
2067 case 'S': /* SU -- Scroll <n> line up */
2068 DEFAULT(csiescseq.arg[0], 1);
2069 tscrollup(term.top, csiescseq.arg[0]);
2071 case 'T': /* SD -- Scroll <n> line down */
2072 DEFAULT(csiescseq.arg[0], 1);
2073 tscrolldown(term.top, csiescseq.arg[0]);
2075 case 'L': /* IL -- Insert <n> blank lines */
2076 DEFAULT(csiescseq.arg[0], 1);
2077 tinsertblankline(csiescseq.arg[0]);
2079 case 'l': /* RM -- Reset Mode */
2080 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2082 case 'M': /* DL -- Delete <n> lines */
2083 DEFAULT(csiescseq.arg[0], 1);
2084 tdeleteline(csiescseq.arg[0]);
2086 case 'X': /* ECH -- Erase <n> char */
2087 DEFAULT(csiescseq.arg[0], 1);
2088 tclearregion(term.c.x, term.c.y,
2089 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2091 case 'P': /* DCH -- Delete <n> char */
2092 DEFAULT(csiescseq.arg[0], 1);
2093 tdeletechar(csiescseq.arg[0]);
2095 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2096 DEFAULT(csiescseq.arg[0], 1);
2097 while(csiescseq.arg[0]--)
2100 case 'd': /* VPA -- Move to <row> */
2101 DEFAULT(csiescseq.arg[0], 1);
2102 tmoveato(term.c.x, csiescseq.arg[0]-1);
2104 case 'h': /* SM -- Set terminal mode */
2105 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2107 case 'm': /* SGR -- Terminal attribute (color) */
2108 tsetattr(csiescseq.arg, csiescseq.narg);
2110 case 'n': /* DSR – Device Status Report (cursor position) */
2111 if (csiescseq.arg[0] == 6) {
2112 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2113 term.c.y+1, term.c.x+1);
2117 case 'r': /* DECSTBM -- Set Scrolling Region */
2118 if(csiescseq.priv) {
2121 DEFAULT(csiescseq.arg[0], 1);
2122 DEFAULT(csiescseq.arg[1], term.row);
2123 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2127 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2128 tcursor(CURSOR_SAVE);
2130 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2131 tcursor(CURSOR_LOAD);
2142 for(i = 0; i < csiescseq.len; i++) {
2143 c = csiescseq.buf[i] & 0xff;
2146 } else if(c == '\n') {
2148 } else if(c == '\r') {
2150 } else if(c == 0x1b) {
2153 printf("(%02x)", c);
2161 memset(&csiescseq, 0, sizeof(csiescseq));
2170 narg = strescseq.narg;
2171 par = atoi(strescseq.args[0]);
2173 switch(strescseq.type) {
2174 case ']': /* OSC -- Operating System Command */
2180 xsettitle(strescseq.args[1]);
2182 case 4: /* color set */
2185 p = strescseq.args[2];
2187 case 104: /* color reset, here p = NULL */
2188 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2189 if (!xsetcolorname(j, p)) {
2190 fprintf(stderr, "erresc: invalid color %s\n", p);
2193 * TODO if defaultbg color is changed, borders
2201 case 'k': /* old title set compatibility */
2202 xsettitle(strescseq.args[0]);
2204 case 'P': /* DSC -- Device Control String */
2205 case '_': /* APC -- Application Program Command */
2206 case '^': /* PM -- Privacy Message */
2210 fprintf(stderr, "erresc: unknown str ");
2216 char *p = strescseq.buf;
2219 strescseq.buf[strescseq.len] = '\0';
2220 while(p && strescseq.narg < STR_ARG_SIZ)
2221 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2229 printf("ESC%c", strescseq.type);
2230 for(i = 0; i < strescseq.len; i++) {
2231 c = strescseq.buf[i] & 0xff;
2234 } else if(isprint(c)) {
2236 } else if(c == '\n') {
2238 } else if(c == '\r') {
2240 } else if(c == 0x1b) {
2243 printf("(%02x)", c);
2251 memset(&strescseq, 0, sizeof(strescseq));
2255 tputtab(bool forward) {
2261 for(++x; x < term.col && !term.tabs[x]; ++x)
2266 for(--x; x > 0 && !term.tabs[x]; --x)
2269 tmoveto(x, term.c.y);
2273 techo(char *buf, int len) {
2274 for(; len > 0; buf++, len--) {
2277 if(c == '\033') { /* escape */
2280 } else if(c < '\x20') { /* control code */
2281 if(c != '\n' && c != '\r' && c != '\t') {
2295 tdeftran(char ascii) {
2297 static char tbl[][2] = {
2298 {'0', CS_GRAPHIC0}, {'1', CS_GRAPHIC1}, {'A', CS_UK},
2299 {'B', CS_USA}, {'<', CS_MULTI}, {'K', CS_GER},
2300 {'5', CS_FIN}, {'C', CS_FIN},
2304 for (bp = &tbl[0]; (c = (*bp)[0]) && c != ascii; ++bp)
2308 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2310 term.trantbl[term.icharset] = (*bp)[1];
2315 if (term.trantbl[term.charset] == CS_GRAPHIC0)
2316 term.c.attr.mode |= ATTR_GFX;
2318 term.c.attr.mode &= ~ATTR_GFX;
2322 tputc(char *c, int len) {
2324 bool control = ascii < '\x20' || ascii == 0177;
2331 utf8decode(c, &u8char);
2332 width = wcwidth(u8char);
2336 if(xwrite(iofd, c, len) < 0) {
2337 fprintf(stderr, "Error writing in %s:%s\n",
2338 opt_io, strerror(errno));
2345 * STR sequences must be checked before anything else
2346 * because it can use some control codes as part of the sequence.
2348 if(term.esc & ESC_STR) {
2351 term.esc = ESC_START | ESC_STR_END;
2353 case '\a': /* backwards compatibility to xterm */
2358 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2359 memmove(&strescseq.buf[strescseq.len], c, len);
2360 strescseq.len += len;
2363 * Here is a bug in terminals. If the user never sends
2364 * some code to stop the str or esc command, then st
2365 * will stop responding. But this is better than
2366 * silently failing with unknown characters. At least
2367 * then users will report back.
2369 * In the case users ever get fixed, here is the code:
2381 * Actions of control codes must be performed as soon they arrive
2382 * because they can be embedded inside a control sequence, and
2383 * they must not cause conflicts with sequences.
2391 tmoveto(term.c.x-1, term.c.y);
2394 tmoveto(0, term.c.y);
2399 /* go to first col if the mode is set */
2400 tnewline(IS_SET(MODE_CRLF));
2402 case '\a': /* BEL */
2403 if(!(xw.state & WIN_FOCUSED))
2406 XBell(xw.dpy, bellvolume);
2408 case '\033': /* ESC */
2410 term.esc = ESC_START;
2412 case '\016': /* SO */
2416 case '\017': /* SI */
2420 case '\032': /* SUB */
2421 case '\030': /* CAN */
2424 case '\005': /* ENQ (IGNORED) */
2425 case '\000': /* NUL (IGNORED) */
2426 case '\021': /* XON (IGNORED) */
2427 case '\023': /* XOFF (IGNORED) */
2428 case 0177: /* DEL (IGNORED) */
2431 } else if(term.esc & ESC_START) {
2432 if(term.esc & ESC_CSI) {
2433 csiescseq.buf[csiescseq.len++] = ascii;
2434 if(BETWEEN(ascii, 0x40, 0x7E)
2435 || csiescseq.len >= \
2436 sizeof(csiescseq.buf)-1) {
2441 } else if(term.esc & ESC_STR_END) {
2445 } else if(term.esc & ESC_ALTCHARSET) {
2449 } else if(term.esc & ESC_TEST) {
2450 if(ascii == '8') { /* DEC screen alignment test. */
2451 char E[UTF_SIZ] = "E";
2454 for(x = 0; x < term.col; ++x) {
2455 for(y = 0; y < term.row; ++y)
2456 tsetchar(E, &term.c.attr, x, y);
2463 term.esc |= ESC_CSI;
2466 term.esc |= ESC_TEST;
2468 case 'P': /* DCS -- Device Control String */
2469 case '_': /* APC -- Application Program Command */
2470 case '^': /* PM -- Privacy Message */
2471 case ']': /* OSC -- Operating System Command */
2472 case 'k': /* old title set compatibility */
2474 strescseq.type = ascii;
2475 term.esc |= ESC_STR;
2477 case '(': /* set primary charset G0 */
2478 case ')': /* set secondary charset G1 */
2479 case '*': /* set tertiary charset G2 */
2480 case '+': /* set quaternary charset G3 */
2481 term.icharset = ascii - '(';
2482 term.esc |= ESC_ALTCHARSET;
2484 case 'D': /* IND -- Linefeed */
2485 if(term.c.y == term.bot) {
2486 tscrollup(term.top, 1);
2488 tmoveto(term.c.x, term.c.y+1);
2492 case 'E': /* NEL -- Next line */
2493 tnewline(1); /* always go to first col */
2496 case 'H': /* HTS -- Horizontal tab stop */
2497 term.tabs[term.c.x] = 1;
2500 case 'M': /* RI -- Reverse index */
2501 if(term.c.y == term.top) {
2502 tscrolldown(term.top, 1);
2504 tmoveto(term.c.x, term.c.y-1);
2508 case 'Z': /* DECID -- Identify Terminal */
2509 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2512 case 'c': /* RIS -- Reset to inital state */
2518 case '=': /* DECPAM -- Application keypad */
2519 term.mode |= MODE_APPKEYPAD;
2522 case '>': /* DECPNM -- Normal keypad */
2523 term.mode &= ~MODE_APPKEYPAD;
2526 case '7': /* DECSC -- Save Cursor */
2527 tcursor(CURSOR_SAVE);
2530 case '8': /* DECRC -- Restore Cursor */
2531 tcursor(CURSOR_LOAD);
2534 case '\\': /* ST -- Stop */
2538 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2539 (uchar) ascii, isprint(ascii)? ascii:'.');
2544 * All characters which form part of a sequence are not
2550 * Display control codes only if we are in graphic mode
2552 if(control && !(term.c.attr.mode & ATTR_GFX))
2554 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2556 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2557 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2561 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2562 memmove(&term.line[term.c.y][term.c.x+1],
2563 &term.line[term.c.y][term.c.x],
2564 (term.col - term.c.x - 1) * sizeof(Glyph));
2567 if(term.c.x+width > term.col)
2570 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2573 term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
2574 if(term.c.x+1 < term.col) {
2575 term.line[term.c.y][term.c.x+1].c[0] = '\0';
2576 term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
2579 if(term.c.x+width < term.col) {
2580 tmoveto(term.c.x+width, term.c.y);
2582 term.c.state |= CURSOR_WRAPNEXT;
2587 tresize(int col, int row) {
2589 int minrow = MIN(row, term.row);
2590 int mincol = MIN(col, term.col);
2591 int slide = term.c.y - row + 1;
2595 if(col < 1 || row < 1)
2598 /* free unneeded rows */
2602 * slide screen to keep cursor where we expect it -
2603 * tscrollup would work here, but we can optimize to
2604 * memmove because we're freeing the earlier lines
2606 for(/* i = 0 */; i < slide; i++) {
2610 memmove(term.line, term.line + slide, row * sizeof(Line));
2611 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2613 for(i += row; i < term.row; i++) {
2618 /* resize to new height */
2619 term.line = xrealloc(term.line, row * sizeof(Line));
2620 term.alt = xrealloc(term.alt, row * sizeof(Line));
2621 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2622 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2624 /* resize each row to new width, zero-pad if needed */
2625 for(i = 0; i < minrow; i++) {
2627 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2628 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2631 /* allocate any new rows */
2632 for(/* i == minrow */; i < row; i++) {
2634 term.line[i] = xmalloc(col * sizeof(Glyph));
2635 term.alt[i] = xmalloc(col * sizeof(Glyph));
2637 if(col > term.col) {
2638 bp = term.tabs + term.col;
2640 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2641 while(--bp > term.tabs && !*bp)
2643 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2646 /* update terminal size */
2649 /* reset scrolling region */
2650 tsetscroll(0, row-1);
2651 /* make use of the LIMIT in tmoveto */
2652 tmoveto(term.c.x, term.c.y);
2653 /* Clearing both screens */
2656 if(mincol < col && 0 < minrow) {
2657 tclearregion(mincol, 0, col - 1, minrow - 1);
2659 if(0 < col && minrow < row) {
2660 tclearregion(0, minrow, col - 1, row - 1);
2663 } while(orig != term.line);
2669 xresize(int col, int row) {
2670 xw.tw = MAX(1, col * xw.cw);
2671 xw.th = MAX(1, row * xw.ch);
2673 XFreePixmap(xw.dpy, xw.buf);
2674 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2675 DefaultDepth(xw.dpy, xw.scr));
2676 XftDrawChange(xw.draw, xw.buf);
2677 xclear(0, 0, xw.w, xw.h);
2680 static inline ushort
2681 sixd_to_16bit(int x) {
2682 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2688 XRenderColor color = { .alpha = 0xffff };
2693 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2694 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2697 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2698 for(i = 0; i < LEN(colorname); i++) {
2701 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2702 die("Could not allocate color '%s'\n", colorname[i]);
2706 /* load colors [16-255] ; same colors as xterm */
2707 for(i = 16, r = 0; r < 6; r++) {
2708 for(g = 0; g < 6; g++) {
2709 for(b = 0; b < 6; b++) {
2710 color.red = sixd_to_16bit(r);
2711 color.green = sixd_to_16bit(g);
2712 color.blue = sixd_to_16bit(b);
2713 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2714 die("Could not allocate color %d\n", i);
2721 for(r = 0; r < 24; r++, i++) {
2722 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2723 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2725 die("Could not allocate color %d\n", i);
2732 xsetcolorname(int x, const char *name) {
2733 XRenderColor color = { .alpha = 0xffff };
2735 if (x < 0 || x > LEN(colorname))
2738 if(16 <= x && x < 16 + 216) {
2739 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2740 color.red = sixd_to_16bit(r);
2741 color.green = sixd_to_16bit(g);
2742 color.blue = sixd_to_16bit(b);
2743 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2744 return 0; /* something went wrong */
2747 } else if (16 + 216 <= x && x < 256) {
2748 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2749 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2750 return 0; /* something went wrong */
2754 name = colorname[x];
2757 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2764 xtermclear(int col1, int row1, int col2, int row2) {
2765 XftDrawRect(xw.draw,
2766 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2767 borderpx + col1 * xw.cw,
2768 borderpx + row1 * xw.ch,
2769 (col2-col1+1) * xw.cw,
2770 (row2-row1+1) * xw.ch);
2774 * Absolute coordinates.
2777 xclear(int x1, int y1, int x2, int y2) {
2778 XftDrawRect(xw.draw,
2779 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2780 x1, y1, x2-x1, y2-y1);
2785 XClassHint class = {opt_class ? opt_class : termname, termname};
2786 XWMHints wm = {.flags = InputHint, .input = 1};
2787 XSizeHints *sizeh = NULL;
2789 sizeh = XAllocSizeHints();
2790 if(xw.isfixed == False) {
2791 sizeh->flags = PSize | PResizeInc | PBaseSize;
2792 sizeh->height = xw.h;
2793 sizeh->width = xw.w;
2794 sizeh->height_inc = xw.ch;
2795 sizeh->width_inc = xw.cw;
2796 sizeh->base_height = 2 * borderpx;
2797 sizeh->base_width = 2 * borderpx;
2799 sizeh->flags = PMaxSize | PMinSize;
2800 sizeh->min_width = sizeh->max_width = xw.fw;
2801 sizeh->min_height = sizeh->max_height = xw.fh;
2804 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
2810 xloadfont(Font *f, FcPattern *pattern) {
2814 match = FcFontMatch(NULL, pattern, &result);
2818 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2819 FcPatternDestroy(match);
2824 f->pattern = FcPatternDuplicate(pattern);
2826 f->ascent = f->match->ascent;
2827 f->descent = f->match->descent;
2829 f->rbearing = f->match->max_advance_width;
2831 f->height = f->ascent + f->descent;
2832 f->width = f->lbearing + f->rbearing;
2838 xloadfonts(char *fontstr, double fontsize) {
2840 FcResult r_sz, r_psz;
2843 if(fontstr[0] == '-') {
2844 pattern = XftXlfdParse(fontstr, False, False);
2846 pattern = FcNameParse((FcChar8 *)fontstr);
2850 die("st: can't open font %s\n", fontstr);
2853 FcPatternDel(pattern, FC_PIXEL_SIZE);
2854 FcPatternDel(pattern, FC_SIZE);
2855 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2856 usedfontsize = fontsize;
2858 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2859 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
2860 if(r_psz == FcResultMatch) {
2861 usedfontsize = fontval;
2862 } else if(r_sz == FcResultMatch) {
2866 * Default font size is 12, if none given. This is to
2867 * have a known usedfontsize value.
2869 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2874 FcConfigSubstitute(0, pattern, FcMatchPattern);
2875 FcDefaultSubstitute(pattern);
2877 if(xloadfont(&dc.font, pattern))
2878 die("st: can't open font %s\n", fontstr);
2880 if(usedfontsize < 0) {
2881 FcPatternGetDouble(dc.font.match->pattern,
2882 FC_PIXEL_SIZE, 0, &fontval);
2883 usedfontsize = fontval;
2886 /* Setting character width and height. */
2887 xw.cw = CEIL(dc.font.width * cwscale);
2888 xw.ch = CEIL(dc.font.height * chscale);
2890 FcPatternDel(pattern, FC_SLANT);
2891 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2892 if(xloadfont(&dc.ifont, pattern))
2893 die("st: can't open font %s\n", fontstr);
2895 FcPatternDel(pattern, FC_WEIGHT);
2896 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2897 if(xloadfont(&dc.ibfont, pattern))
2898 die("st: can't open font %s\n", fontstr);
2900 FcPatternDel(pattern, FC_SLANT);
2901 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2902 if(xloadfont(&dc.bfont, pattern))
2903 die("st: can't open font %s\n", fontstr);
2905 FcPatternDestroy(pattern);
2909 xloadfontset(Font *f) {
2912 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2918 xunloadfont(Font *f) {
2919 XftFontClose(xw.dpy, f->match);
2920 FcPatternDestroy(f->pattern);
2922 FcFontSetDestroy(f->set);
2926 xunloadfonts(void) {
2929 /* Free the loaded fonts in the font cache. */
2930 for(i = 0; i < frclen; i++) {
2931 XftFontClose(xw.dpy, frc[i].font);
2935 xunloadfont(&dc.font);
2936 xunloadfont(&dc.bfont);
2937 xunloadfont(&dc.ifont);
2938 xunloadfont(&dc.ibfont);
2942 xzoom(const Arg *arg) {
2944 xloadfonts(usedfont, usedfontsize + arg->i);
2955 pid_t thispid = getpid();
2957 if(!(xw.dpy = XOpenDisplay(NULL)))
2958 die("Can't open display\n");
2959 xw.scr = XDefaultScreen(xw.dpy);
2960 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2964 die("Could not init fontconfig.\n");
2966 usedfont = (opt_font == NULL)? font : opt_font;
2967 xloadfonts(usedfont, 0);
2970 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2973 /* adjust fixed window geometry */
2975 sw = DisplayWidth(xw.dpy, xw.scr);
2976 sh = DisplayHeight(xw.dpy, xw.scr);
2978 xw.fx = sw + xw.fx - xw.fw - 1;
2980 xw.fy = sh + xw.fy - xw.fh - 1;
2985 /* window - default size */
2986 xw.h = 2 * borderpx + term.row * xw.ch;
2987 xw.w = 2 * borderpx + term.col * xw.cw;
2993 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2994 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2995 xw.attrs.bit_gravity = NorthWestGravity;
2996 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2997 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2998 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2999 xw.attrs.colormap = xw.cmap;
3001 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
3002 XRootWindow(xw.dpy, xw.scr);
3003 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
3004 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3005 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3006 | CWEventMask | CWColormap, &xw.attrs);
3008 memset(&gcvalues, 0, sizeof(gcvalues));
3009 gcvalues.graphics_exposures = False;
3010 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3012 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3013 DefaultDepth(xw.dpy, xw.scr));
3014 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3015 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3017 /* Xft rendering context */
3018 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3021 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3022 XSetLocaleModifiers("@im=local");
3023 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3024 XSetLocaleModifiers("@im=");
3025 if((xw.xim = XOpenIM(xw.dpy,
3026 NULL, NULL, NULL)) == NULL) {
3027 die("XOpenIM failed. Could not open input"
3032 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3033 | XIMStatusNothing, XNClientWindow, xw.win,
3034 XNFocusWindow, xw.win, NULL);
3036 die("XCreateIC failed. Could not obtain input method.\n");
3038 /* white cursor, black outline */
3039 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3040 XDefineCursor(xw.dpy, xw.win, cursor);
3041 XRecolorCursor(xw.dpy, cursor,
3042 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3043 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3045 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3046 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3047 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3048 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3050 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3051 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3052 PropModeReplace, (unsigned char *)&thispid, 1);
3055 XMapWindow(xw.dpy, xw.win);
3061 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3062 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3063 width = charlen * xw.cw, xp, i;
3065 int u8fl, u8fblen, u8cblen, doesexist;
3068 Font *font = &dc.font;
3070 FcPattern *fcpattern, *fontpattern;
3071 FcFontSet *fcsets[] = { NULL };
3072 FcCharSet *fccharset;
3073 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3074 XRenderColor colfg, colbg;
3078 frcflags = FRC_NORMAL;
3080 if(base.mode & ATTR_ITALIC) {
3081 if(base.fg == defaultfg)
3082 base.fg = defaultitalic;
3084 frcflags = FRC_ITALIC;
3085 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3086 if(base.fg == defaultfg)
3087 base.fg = defaultitalic;
3089 frcflags = FRC_ITALICBOLD;
3090 } else if(base.mode & ATTR_UNDERLINE) {
3091 if(base.fg == defaultfg)
3092 base.fg = defaultunderline;
3095 if(IS_TRUECOL(base.fg)) {
3096 colfg.alpha = 0xffff;
3097 colfg.red = TRUERED(base.fg);
3098 colfg.green = TRUEGREEN(base.fg);
3099 colfg.blue = TRUEBLUE(base.fg);
3100 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3103 fg = &dc.col[base.fg];
3106 if(IS_TRUECOL(base.bg)) {
3107 colbg.alpha = 0xffff;
3108 colbg.green = TRUEGREEN(base.bg);
3109 colbg.red = TRUERED(base.bg);
3110 colbg.blue = TRUEBLUE(base.bg);
3111 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3114 bg = &dc.col[base.bg];
3117 if(base.mode & ATTR_BOLD) {
3118 if(BETWEEN(base.fg, 0, 7)) {
3119 /* basic system colors */
3120 fg = &dc.col[base.fg + 8];
3121 } else if(BETWEEN(base.fg, 16, 195)) {
3123 fg = &dc.col[base.fg + 36];
3124 } else if(BETWEEN(base.fg, 232, 251)) {
3126 fg = &dc.col[base.fg + 4];
3129 * Those ranges will not be brightened:
3130 * 8 - 15 – bright system colors
3131 * 196 - 231 – highest 256 color cube
3132 * 252 - 255 – brightest colors in greyscale
3135 frcflags = FRC_BOLD;
3138 if(IS_SET(MODE_REVERSE)) {
3139 if(fg == &dc.col[defaultfg]) {
3140 fg = &dc.col[defaultbg];
3142 colfg.red = ~fg->color.red;
3143 colfg.green = ~fg->color.green;
3144 colfg.blue = ~fg->color.blue;
3145 colfg.alpha = fg->color.alpha;
3146 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3151 if(bg == &dc.col[defaultbg]) {
3152 bg = &dc.col[defaultfg];
3154 colbg.red = ~bg->color.red;
3155 colbg.green = ~bg->color.green;
3156 colbg.blue = ~bg->color.blue;
3157 colbg.alpha = bg->color.alpha;
3158 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3164 if(base.mode & ATTR_REVERSE) {
3170 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3173 /* Intelligent cleaning up of the borders. */
3175 xclear(0, (y == 0)? 0 : winy, borderpx,
3176 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3178 if(x + charlen >= term.col) {
3179 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3180 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3183 xclear(winx, 0, winx + width, borderpx);
3185 xclear(winx, winy + xw.ch, winx + width, xw.h);
3187 /* Clean up the region we want to draw to. */
3188 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3190 /* Set the clip region because Xft is sometimes dirty. */
3195 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3197 for(xp = winx; bytelen > 0;) {
3199 * Search for the range in the to be printed string of glyphs
3200 * that are in the main font. Then print that range. If
3201 * some glyph is found that is not in the font, do the
3207 oneatatime = font->width != xw.cw;
3210 u8cblen = utf8decode(s, &u8char);
3214 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3215 if(oneatatime || !doesexist || bytelen <= 0) {
3216 if(oneatatime || bytelen <= 0) {
3224 XftDrawStringUtf8(xw.draw, fg,
3226 winy + font->ascent,
3244 /* Search the font cache. */
3245 for(i = 0; i < frclen; i++) {
3246 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3247 && frc[i].flags == frcflags) {
3252 /* Nothing was found. */
3256 fcsets[0] = font->set;
3259 * Nothing was found in the cache. Now use
3260 * some dozen of Fontconfig calls to get the
3261 * font for one single character.
3263 * Xft and fontconfig are design failures.
3265 fcpattern = FcPatternDuplicate(font->pattern);
3266 fccharset = FcCharSetCreate();
3268 FcCharSetAddChar(fccharset, u8char);
3269 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3271 FcPatternAddBool(fcpattern, FC_SCALABLE,
3274 FcConfigSubstitute(0, fcpattern,
3276 FcDefaultSubstitute(fcpattern);
3278 fontpattern = FcFontSetMatch(0, fcsets,
3279 FcTrue, fcpattern, &fcres);
3282 * Overwrite or create the new cache entry.
3284 if(frclen >= LEN(frc)) {
3285 frclen = LEN(frc) - 1;
3286 XftFontClose(xw.dpy, frc[frclen].font);
3289 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3291 frc[frclen].flags = frcflags;
3296 FcPatternDestroy(fcpattern);
3297 FcCharSetDestroy(fccharset);
3300 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3301 xp, winy + frc[i].font->ascent,
3302 (FcChar8 *)u8c, u8cblen);
3304 xp += xw.cw * wcwidth(u8char);
3308 * This is how the loop above actually should be. Why does the
3309 * application have to care about font details?
3311 * I have to repeat: Xft and Fontconfig are design failures.
3314 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3315 winy + font->ascent, (FcChar8 *)s, bytelen);
3318 if(base.mode & ATTR_UNDERLINE) {
3319 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3323 /* Reset clip to none. */
3324 XftDrawSetClip(xw.draw, 0);
3329 static int oldx = 0, oldy = 0;
3330 int sl, width, curx;
3331 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3333 LIMIT(oldx, 0, term.col-1);
3334 LIMIT(oldy, 0, term.row-1);
3338 /* adjust position if in dummy */
3339 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3341 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3344 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3346 /* remove the old cursor */
3347 sl = utf8size(term.line[oldy][oldx].c);
3348 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3349 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3352 /* draw the new one */
3353 if(!(IS_SET(MODE_HIDE))) {
3354 if(xw.state & WIN_FOCUSED) {
3355 if(IS_SET(MODE_REVERSE)) {
3356 g.mode |= ATTR_REVERSE;
3362 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3364 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3366 XftDrawRect(xw.draw, &dc.col[defaultcs],
3367 borderpx + curx * xw.cw,
3368 borderpx + term.c.y * xw.ch,
3370 XftDrawRect(xw.draw, &dc.col[defaultcs],
3371 borderpx + curx * xw.cw,
3372 borderpx + term.c.y * xw.ch,
3374 XftDrawRect(xw.draw, &dc.col[defaultcs],
3375 borderpx + (curx + 1) * xw.cw - 1,
3376 borderpx + term.c.y * xw.ch,
3378 XftDrawRect(xw.draw, &dc.col[defaultcs],
3379 borderpx + curx * xw.cw,
3380 borderpx + (term.c.y + 1) * xw.ch - 1,
3383 oldx = curx, oldy = term.c.y;
3389 xsettitle(char *p) {
3392 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3394 XSetWMName(xw.dpy, xw.win, &prop);
3395 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3401 xsettitle(opt_title ? opt_title : "st");
3405 redraw(int timeout) {
3406 struct timespec tv = {0, timeout * 1000};
3412 nanosleep(&tv, NULL);
3413 XSync(xw.dpy, False); /* necessary for a good tput flash */
3419 drawregion(0, 0, term.col, term.row);
3420 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3422 XSetForeground(xw.dpy, dc.gc,
3423 dc.col[IS_SET(MODE_REVERSE)?
3424 defaultfg : defaultbg].pixel);
3428 drawregion(int x1, int y1, int x2, int y2) {
3429 int ic, ib, x, y, ox, sl;
3431 char buf[DRAW_BUF_SIZ];
3432 bool ena_sel = sel.ob.x != -1;
3435 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3438 if(!(xw.state & WIN_VISIBLE))
3441 for(y = y1; y < y2; y++) {
3445 xtermclear(0, y, term.col, y);
3447 base = term.line[y][0];
3449 for(x = x1; x < x2; x++) {
3450 new = term.line[y][x];
3451 if(new.mode == ATTR_WDUMMY)
3453 if(ena_sel && selected(x, y))
3454 new.mode ^= ATTR_REVERSE;
3455 if(ib > 0 && (ATTRCMP(base, new)
3456 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3457 xdraws(buf, base, ox, y, ic, ib);
3465 sl = utf8decode(new.c, &u8char);
3466 memcpy(buf+ib, new.c, sl);
3468 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3471 xdraws(buf, base, ox, y, ic, ib);
3477 expose(XEvent *ev) {
3478 XExposeEvent *e = &ev->xexpose;
3480 if(xw.state & WIN_REDRAW) {
3482 xw.state &= ~WIN_REDRAW;
3488 visibility(XEvent *ev) {
3489 XVisibilityEvent *e = &ev->xvisibility;
3491 if(e->state == VisibilityFullyObscured) {
3492 xw.state &= ~WIN_VISIBLE;
3493 } else if(!(xw.state & WIN_VISIBLE)) {
3494 /* need a full redraw for next Expose, not just a buf copy */
3495 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3501 xw.state &= ~WIN_VISIBLE;
3505 xsetpointermotion(int set) {
3506 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3507 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3511 xseturgency(int add) {
3512 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3514 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3515 XSetWMHints(xw.dpy, xw.win, h);
3521 XFocusChangeEvent *e = &ev->xfocus;
3523 if(e->mode == NotifyGrab)
3526 if(ev->type == FocusIn) {
3527 XSetICFocus(xw.xic);
3528 xw.state |= WIN_FOCUSED;
3530 if(IS_SET(MODE_FOCUS))
3531 ttywrite("\033[I", 3);
3533 XUnsetICFocus(xw.xic);
3534 xw.state &= ~WIN_FOCUSED;
3535 if(IS_SET(MODE_FOCUS))
3536 ttywrite("\033[O", 3);
3541 match(uint mask, uint state) {
3542 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3546 numlock(const Arg *dummy) {
3551 kmap(KeySym k, uint state) {
3555 /* Check for mapped keys out of X11 function keys. */
3556 for(i = 0; i < LEN(mappedkeys); i++) {
3557 if(mappedkeys[i] == k)
3560 if(i == LEN(mappedkeys)) {
3561 if((k & 0xFFFF) < 0xFD00)
3565 for(kp = key; kp < key + LEN(key); kp++) {
3569 if(!match(kp->mask, state))
3572 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3574 if(term.numlock && kp->appkey == 2)
3577 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3580 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3590 kpress(XEvent *ev) {
3591 XKeyEvent *e = &ev->xkey;
3593 char buf[32], *customkey;
3599 if(IS_SET(MODE_KBDLOCK))
3602 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3604 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3605 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3606 bp->func(&(bp->arg));
3611 /* 2. custom keys from config.h */
3612 if((customkey = kmap(ksym, e->state))) {
3613 ttysend(customkey, strlen(customkey));
3617 /* 3. composed string from input method */
3620 if(len == 1 && e->state & Mod1Mask) {
3621 if(IS_SET(MODE_8BIT)) {
3624 len = utf8encode(&c, buf);
3637 cmessage(XEvent *e) {
3640 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3642 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3643 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3644 xw.state |= WIN_FOCUSED;
3646 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3647 xw.state &= ~WIN_FOCUSED;
3649 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3650 /* Send SIGHUP to shell */
3657 cresize(int width, int height) {
3665 col = (xw.w - 2 * borderpx) / xw.cw;
3666 row = (xw.h - 2 * borderpx) / xw.ch;
3675 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3678 cresize(e->xconfigure.width, e->xconfigure.height);
3684 int w = xw.w, h = xw.h;
3686 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3687 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3689 /* Waiting for window mapping */
3691 XNextEvent(xw.dpy, &ev);
3692 if(ev.type == ConfigureNotify) {
3693 w = ev.xconfigure.width;
3694 h = ev.xconfigure.height;
3695 } else if(ev.type == MapNotify) {
3704 cresize(xw.fw, xw.fh);
3706 gettimeofday(&lastblink, NULL);
3707 gettimeofday(&last, NULL);
3709 for(xev = actionfps;;) {
3713 FD_SET(cmdfd, &rfd);
3716 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3719 die("select failed: %s\n", SERRNO);
3721 if(FD_ISSET(cmdfd, &rfd)) {
3724 blinkset = tattrset(ATTR_BLINK);
3726 MODBIT(term.mode, 0, MODE_BLINK);
3730 if(FD_ISSET(xfd, &rfd))
3733 gettimeofday(&now, NULL);
3734 drawtimeout.tv_sec = 0;
3735 drawtimeout.tv_usec = (1000/xfps) * 1000;
3739 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3740 tsetdirtattr(ATTR_BLINK);
3741 term.mode ^= MODE_BLINK;
3742 gettimeofday(&lastblink, NULL);
3745 deltatime = TIMEDIFF(now, last);
3746 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3753 while(XPending(xw.dpy)) {
3754 XNextEvent(xw.dpy, &ev);
3755 if(XFilterEvent(&ev, None))
3757 if(handler[ev.type])
3758 (handler[ev.type])(&ev);
3764 if(xev && !FD_ISSET(xfd, &rfd))
3766 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3768 if(TIMEDIFF(now, lastblink) \
3770 drawtimeout.tv_usec = 1;
3772 drawtimeout.tv_usec = (1000 * \
3787 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3788 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3789 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3793 main(int argc, char *argv[]) {
3798 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3803 allowaltscreen = false;
3806 opt_class = EARGF(usage());
3809 /* eat all remaining arguments */
3812 if(argv[1] != NULL && opt_title == NULL) {
3813 titles = xstrdup(argv[1]);
3814 opt_title = basename(titles);
3819 opt_font = EARGF(usage());
3822 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3827 if(bitm & WidthValue)
3829 if(bitm & HeightValue)
3831 if(bitm & XNegative && xw.fx == 0)
3833 if(bitm & YNegative && xw.fy == 0)
3836 if(xw.fh != 0 && xw.fw != 0)
3840 opt_io = EARGF(usage());
3843 opt_title = EARGF(usage());
3846 opt_embed = EARGF(usage());
3854 setlocale(LC_CTYPE, "");
3855 XSetLocaleModifiers("");