1 /* See LICENSE for licence details. */
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
23 #include <X11/Xatom.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/Xft/Xft.h>
29 #include <fontconfig/fontconfig.h>
38 #define Draw XftDraw *
39 #define Colour XftColor
40 #define Colourmap Colormap
41 #define Rectangle XRectangle
45 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
47 #elif defined(__FreeBSD__) || defined(__DragonFly__)
53 #define XEMBED_FOCUS_IN 4
54 #define XEMBED_FOCUS_OUT 5
58 #define ESC_BUF_SIZ (128*UTF_SIZ)
59 #define ESC_ARG_SIZ 16
60 #define STR_BUF_SIZ ESC_BUF_SIZ
61 #define STR_ARG_SIZ ESC_ARG_SIZ
62 #define DRAW_BUF_SIZ 20*1024
63 #define XK_ANY_MOD UINT_MAX
65 #define XK_SWITCH_MOD (1<<13)
67 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
70 #define SERRNO strerror(errno)
71 #define MIN(a, b) ((a) < (b) ? (a) : (b))
72 #define MAX(a, b) ((a) < (b) ? (b) : (a))
73 #define LEN(a) (sizeof(a) / sizeof(a[0]))
74 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
75 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
76 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
77 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
78 #define IS_SET(flag) ((term.mode & (flag)) != 0)
79 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
80 #define CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
82 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
83 #define IS_TRUECOL(x) (1 << 24 & (x))
84 #define TRUERED(x) (((x) & 0xff0000) >> 8)
85 #define TRUEGREEN(x) (((x) & 0xff00))
86 #define TRUEBLUE(x) (((x) & 0xff) << 8)
89 #define VT102ID "\033[?6c"
91 enum glyph_attribute {
104 enum cursor_movement {
122 MODE_MOUSEMOTION = 64,
127 MODE_APPCURSOR = 2048,
128 MODE_MOUSESGR = 4096,
133 MODE_MOUSEX10 = 131072,
134 MODE_MOUSEMANY = 262144,
135 MODE_BRCKTPASTE = 524288,
136 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
153 ESC_STR = 4, /* DSC, OSC, PM, APC */
155 ESC_STR_END = 16, /* a final string was encountered */
156 ESC_TEST = 32, /* Enter in test mode */
165 enum selection_type {
170 enum selection_snap {
175 typedef unsigned char uchar;
176 typedef unsigned int uint;
177 typedef unsigned long ulong;
178 typedef unsigned short ushort;
181 char c[UTF_SIZ]; /* character code */
182 ushort mode; /* attribute flags */
183 ulong fg; /* foreground */
184 ulong bg; /* background */
190 Glyph attr; /* current char attributes */
196 /* CSI Escape sequence structs */
197 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
199 char buf[ESC_BUF_SIZ]; /* raw string */
200 int len; /* raw string length */
202 int arg[ESC_ARG_SIZ];
203 int narg; /* nb of args */
207 /* STR Escape sequence structs */
208 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
210 char type; /* ESC type ... */
211 char buf[STR_BUF_SIZ]; /* raw string */
212 int len; /* raw string length */
213 char *args[STR_ARG_SIZ];
214 int narg; /* nb of args */
217 /* Internal representation of the screen */
219 int row; /* nb row */
220 int col; /* nb col */
221 Line *line; /* screen */
222 Line *alt; /* alternate screen */
223 bool *dirty; /* dirtyness of lines */
224 TCursor c; /* cursor */
225 int top; /* top scroll limit */
226 int bot; /* bottom scroll limit */
227 int mode; /* terminal mode flags */
228 int esc; /* escape state flags */
229 char trantbl[4]; /* charset table translation */
230 int charset; /* current charset */
231 int icharset; /* selected charset for sequence */
232 bool numlock; /* lock numbers in keyboard */
236 /* Purely graphic info */
242 Atom xembed, wmdeletewin;
247 XSetWindowAttributes attrs;
249 bool isfixed; /* is fixed geometry? */
250 int fx, fy, fw, fh; /* fixed geometry */
251 int tw, th; /* tty width and height */
252 int w, h; /* window width and height */
253 int ch; /* char height */
254 int cw; /* char width */
255 char state; /* focus, redraw, visible */
268 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
269 signed char appkey; /* application keypad */
270 signed char appcursor; /* application cursor */
271 signed char crlf; /* crlf mode */
279 * Selection variables:
280 * nb – normalized coordinates of the beginning of the selection
281 * ne – normalized coordinates of the end of the selection
282 * ob – original coordinates of the beginning of the selection
283 * oe – original coordinates of the end of the selection
292 struct timeval tclick1;
293 struct timeval tclick2;
306 void (*func)(const Arg *);
310 /* function definitions used in config.h */
311 static void clippaste(const Arg *);
312 static void numlock(const Arg *);
313 static void selpaste(const Arg *);
314 static void xzoom(const Arg *);
316 /* Config.h for applying patches and the configuration. */
332 /* Drawing Context */
334 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
335 Font font, bfont, ifont, ibfont;
339 static void die(const char *, ...);
340 static void draw(void);
341 static void redraw(int);
342 static void drawregion(int, int, int, int);
343 static void execsh(void);
344 static void sigchld(int);
345 static void run(void);
347 static void csidump(void);
348 static void csihandle(void);
349 static void csiparse(void);
350 static void csireset(void);
351 static void strdump(void);
352 static void strhandle(void);
353 static void strparse(void);
354 static void strreset(void);
356 static int tattrset(int);
357 static void tclearregion(int, int, int, int);
358 static void tcursor(int);
359 static void tdeletechar(int);
360 static void tdeleteline(int);
361 static void tinsertblank(int);
362 static void tinsertblankline(int);
363 static void tmoveto(int, int);
364 static void tmoveato(int x, int y);
365 static void tnew(int, int);
366 static void tnewline(int);
367 static void tputtab(bool);
368 static void tputc(char *, int);
369 static void treset(void);
370 static int tresize(int, int);
371 static void tscrollup(int, int);
372 static void tscrolldown(int, int);
373 static void tsetattr(int*, int);
374 static void tsetchar(char *, Glyph *, int, int);
375 static void tsetscroll(int, int);
376 static void tswapscreen(void);
377 static void tsetdirt(int, int);
378 static void tsetdirtattr(int);
379 static void tsetmode(bool, bool, int *, int);
380 static void tfulldirt(void);
381 static void techo(char *, int);
382 static long tdefcolor(int *, int *, int);
383 static void tselcs(void);
384 static void tdeftran(char);
385 static inline bool match(uint, uint);
386 static void ttynew(void);
387 static void ttyread(void);
388 static void ttyresize(void);
389 static void ttysend(char *, size_t);
390 static void ttywrite(const char *, size_t);
392 static void xdraws(char *, Glyph, int, int, int, int);
393 static void xhints(void);
394 static void xclear(int, int, int, int);
395 static void xdrawcursor(void);
396 static void xinit(void);
397 static void xloadcols(void);
398 static int xsetcolorname(int, const char *);
399 static int xloadfont(Font *, FcPattern *);
400 static void xloadfonts(char *, int);
401 static int xloadfontset(Font *);
402 static void xsettitle(char *);
403 static void xresettitle(void);
404 static void xsetpointermotion(int);
405 static void xseturgency(int);
406 static void xsetsel(char*);
407 static void xtermclear(int, int, int, int);
408 static void xunloadfont(Font *f);
409 static void xunloadfonts(void);
410 static void xresize(int, int);
412 static void expose(XEvent *);
413 static void visibility(XEvent *);
414 static void unmap(XEvent *);
415 static char *kmap(KeySym, uint);
416 static void kpress(XEvent *);
417 static void cmessage(XEvent *);
418 static void cresize(int, int);
419 static void resize(XEvent *);
420 static void focus(XEvent *);
421 static void brelease(XEvent *);
422 static void bpress(XEvent *);
423 static void bmotion(XEvent *);
424 static void selnotify(XEvent *);
425 static void selclear(XEvent *);
426 static void selrequest(XEvent *);
428 static void selinit(void);
429 static void selsort(void);
430 static inline bool selected(int, int);
431 static void selcopy(void);
432 static void selscroll(int, int);
433 static void selsnap(int, int *, int *, int);
435 static int utf8decode(char *, long *);
436 static int utf8encode(long *, char *);
437 static int utf8size(char *);
438 static int isfullutf8(char *, int);
440 static ssize_t xwrite(int, char *, size_t);
441 static void *xmalloc(size_t);
442 static void *xrealloc(void *, size_t);
444 static void (*handler[LASTEvent])(XEvent *) = {
446 [ClientMessage] = cmessage,
447 [ConfigureNotify] = resize,
448 [VisibilityNotify] = visibility,
449 [UnmapNotify] = unmap,
453 [MotionNotify] = bmotion,
454 [ButtonPress] = bpress,
455 [ButtonRelease] = brelease,
456 [SelectionClear] = selclear,
457 [SelectionNotify] = selnotify,
458 [SelectionRequest] = selrequest,
465 static CSIEscape csiescseq;
466 static STREscape strescseq;
469 static Selection sel;
470 static int iofd = -1;
471 static char **opt_cmd = NULL;
472 static char *opt_io = NULL;
473 static char *opt_title = NULL;
474 static char *opt_embed = NULL;
475 static char *opt_class = NULL;
476 static char *opt_font = NULL;
477 static int oldbutton = 3; /* button event on startup: 3 = release */
479 static char *usedfont = NULL;
480 static int usedfontsize = 0;
482 /* Font Ring Cache */
495 /* Fontcache is an array now. A new font will be appended to the array. */
496 static Fontcache frc[16];
497 static int frclen = 0;
500 xwrite(int fd, char *s, size_t len) {
504 ssize_t r = write(fd, s, len);
514 xmalloc(size_t len) {
515 void *p = malloc(len);
518 die("Out of memory\n");
524 xrealloc(void *p, size_t len) {
525 if((p = realloc(p, len)) == NULL)
526 die("Out of memory\n");
532 utf8decode(char *s, long *u) {
538 if(~c & 0x80) { /* 0xxxxxxx */
541 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
544 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
547 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
554 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
556 if((c & 0xC0) != 0x80) /* 10xxxxxx */
562 if((n == 1 && *u < 0x80) ||
563 (n == 2 && *u < 0x800) ||
564 (n == 3 && *u < 0x10000) ||
565 (*u >= 0xD800 && *u <= 0xDFFF)) {
577 utf8encode(long *u, char *s) {
585 *sp = uc; /* 0xxxxxxx */
587 } else if(*u < 0x800) {
588 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
590 } else if(uc < 0x10000) {
591 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
593 } else if(uc <= 0x10FFFF) {
594 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
600 for(i=n,++sp; i>0; --i,++sp)
601 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
613 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
614 UTF-8 otherwise return 0 */
616 isfullutf8(char *s, int b) {
624 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
626 } else if((*c1 & 0xF0) == 0xE0 &&
628 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
630 } else if((*c1 & 0xF8) == 0xF0 &&
632 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
633 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
646 } else if((c & 0xE0) == 0xC0) {
648 } else if((c & 0xF0) == 0xE0) {
657 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
658 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
662 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
663 if(sel.xtarget == None)
664 sel.xtarget = XA_STRING;
672 return LIMIT(x, 0, term.col-1);
680 return LIMIT(y, 0, term.row-1);
685 if(sel.ob.y == sel.oe.y) {
686 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
687 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
689 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
690 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
692 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
693 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
697 selected(int x, int y) {
698 if(sel.ne.y == y && sel.nb.y == y)
699 return BETWEEN(x, sel.nb.x, sel.ne.x);
701 if(sel.type == SEL_RECTANGULAR) {
702 return ((sel.nb.y <= y && y <= sel.ne.y)
703 && (sel.nb.x <= x && x <= sel.ne.x));
706 return ((sel.nb.y < y && y < sel.ne.y)
707 || (y == sel.ne.y && x <= sel.ne.x))
708 || (y == sel.nb.y && x >= sel.nb.x
709 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
713 selsnap(int mode, int *x, int *y, int direction) {
719 * Snap around if the word wraps around at the end or
720 * beginning of a line.
723 if(direction < 0 && *x <= 0) {
724 if(*y > 0 && term.line[*y - 1][term.col-1].mode
732 if(direction > 0 && *x >= term.col-1) {
733 if(*y < term.row-1 && term.line[*y][*x].mode
742 if(term.line[*y][*x+direction].mode & ATTR_WDUMMY) {
747 if(strchr(worddelimiters,
748 term.line[*y][*x+direction].c[0])) {
757 * Snap around if the the previous line or the current one
758 * has set ATTR_WRAP at its end. Then the whole next or
759 * previous line will be selected.
761 *x = (direction < 0) ? 0 : term.col - 1;
762 if(direction < 0 && *y > 0) {
763 for(; *y > 0; *y += direction) {
764 if(!(term.line[*y-1][term.col-1].mode
769 } else if(direction > 0 && *y < term.row-1) {
770 for(; *y < term.row; *y += direction) {
771 if(!(term.line[*y][term.col-1].mode
780 * Select the whole line when the end of line is reached.
784 while(--i > 0 && term.line[*y][i].c[0] == ' ')
794 getbuttoninfo(XEvent *e) {
796 uint state = e->xbutton.state &~Button1Mask;
798 sel.alt = IS_SET(MODE_ALTSCREEN);
800 sel.oe.x = x2col(e->xbutton.x);
801 sel.oe.y = y2row(e->xbutton.y);
803 if(sel.ob.y < sel.oe.y
804 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
805 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
806 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
808 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
809 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
813 sel.type = SEL_REGULAR;
814 for(type = 1; type < LEN(selmasks); ++type) {
815 if(match(selmasks[type], state)) {
823 mousereport(XEvent *e) {
824 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
825 button = e->xbutton.button, state = e->xbutton.state,
831 if(e->xbutton.type == MotionNotify) {
832 if(x == ox && y == oy)
834 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
836 /* MOUSE_MOTION: no reporting if no button is pressed */
837 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
840 button = oldbutton + 32;
844 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
851 if(e->xbutton.type == ButtonPress) {
855 } else if(e->xbutton.type == ButtonRelease) {
857 /* MODE_MOUSEX10: no button release reporting */
858 if(IS_SET(MODE_MOUSEX10))
863 if(!IS_SET(MODE_MOUSEX10)) {
864 button += (state & ShiftMask ? 4 : 0)
865 + (state & Mod4Mask ? 8 : 0)
866 + (state & ControlMask ? 16 : 0);
870 if(IS_SET(MODE_MOUSESGR)) {
871 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
873 e->xbutton.type == ButtonRelease ? 'm' : 'M');
874 } else if(x < 223 && y < 223) {
875 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
876 32+button, 32+x+1, 32+y+1);
889 if(IS_SET(MODE_MOUSE)) {
894 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
895 if(e->xbutton.button == mk->b
896 && match(mk->mask, e->xbutton.state)) {
897 ttysend(mk->s, strlen(mk->s));
902 if(e->xbutton.button == Button1) {
903 gettimeofday(&now, NULL);
905 /* Clear previous selection, logically and visually. */
908 sel.type = SEL_REGULAR;
909 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
910 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
913 * If the user clicks below predefined timeouts specific
914 * snapping behaviour is exposed.
916 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
917 sel.snap = SNAP_LINE;
918 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
919 sel.snap = SNAP_WORD;
923 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
924 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
928 * Draw selection, unless it's regular and we don't want to
929 * make clicks visible
933 tsetdirt(sel.nb.y, sel.ne.y);
935 sel.tclick2 = sel.tclick1;
943 int x, y, bufsize, size, i, ex;
949 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
950 ptr = str = xmalloc(bufsize);
952 /* append every set & selected glyph to the selection */
953 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
954 gp = &term.line[y][0];
955 last = gp + term.col;
957 while(--last >= gp && !(selected(last - gp, y) && \
958 strcmp(last->c, " ") != 0))
961 for(x = 0; gp <= last; x++, ++gp) {
962 if(!selected(x, y) || (gp->mode & ATTR_WDUMMY))
965 size = utf8size(gp->c);
966 memcpy(ptr, gp->c, size);
971 * Copy and pasting of line endings is inconsistent
972 * in the inconsistent terminal and GUI world.
973 * The best solution seems like to produce '\n' when
974 * something is copied from st and convert '\n' to
975 * '\r', when something to be pasted is received by
977 * FIXME: Fix the computer world.
979 if(y < sel.ne.y && x > 0 && !((gp-1)->mode & ATTR_WRAP))
983 * If the last selected line expands in the selection
984 * after the visible text '\n' is appended.
988 while(--i > 0 && term.line[y][i].c[0] == ' ')
991 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
1003 selnotify(XEvent *e) {
1004 ulong nitems, ofs, rem;
1006 uchar *data, *last, *repl;
1011 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
1012 False, AnyPropertyType, &type, &format,
1013 &nitems, &rem, &data)) {
1014 fprintf(stderr, "Clipboard allocation failed\n");
1019 * As seen in selcopy:
1020 * Line endings are inconsistent in the terminal and GUI world
1021 * copy and pasting. When receiving some selection data,
1022 * replace all '\n' with '\r'.
1023 * FIXME: Fix the computer world.
1026 last = data + nitems * format / 8;
1027 while((repl = memchr(repl, '\n', last - repl))) {
1031 if(IS_SET(MODE_BRCKTPASTE))
1032 ttywrite("\033[200~", 6);
1033 ttysend((char *)data, nitems * format / 8);
1034 if(IS_SET(MODE_BRCKTPASTE))
1035 ttywrite("\033[201~", 6);
1037 /* number of 32-bit chunks returned */
1038 ofs += nitems * format / 32;
1043 selpaste(const Arg *dummy) {
1044 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1045 xw.win, CurrentTime);
1049 clippaste(const Arg *dummy) {
1052 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1053 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1054 xw.win, CurrentTime);
1058 selclear(XEvent *e) {
1062 tsetdirt(sel.nb.y, sel.ne.y);
1066 selrequest(XEvent *e) {
1067 XSelectionRequestEvent *xsre;
1068 XSelectionEvent xev;
1069 Atom xa_targets, string;
1071 xsre = (XSelectionRequestEvent *) e;
1072 xev.type = SelectionNotify;
1073 xev.requestor = xsre->requestor;
1074 xev.selection = xsre->selection;
1075 xev.target = xsre->target;
1076 xev.time = xsre->time;
1078 xev.property = None;
1080 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1081 if(xsre->target == xa_targets) {
1082 /* respond with the supported type */
1083 string = sel.xtarget;
1084 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1085 XA_ATOM, 32, PropModeReplace,
1086 (uchar *) &string, 1);
1087 xev.property = xsre->property;
1088 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1089 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1090 xsre->target, 8, PropModeReplace,
1091 (uchar *) sel.clip, strlen(sel.clip));
1092 xev.property = xsre->property;
1095 /* all done, send a notification to the listener */
1096 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1097 fprintf(stderr, "Error sending SelectionNotify event\n");
1101 xsetsel(char *str) {
1102 /* register the selection for both the clipboard and the primary */
1108 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1110 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1111 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1115 brelease(XEvent *e) {
1116 if(IS_SET(MODE_MOUSE)) {
1121 if(e->xbutton.button == Button2) {
1123 } else if(e->xbutton.button == Button1) {
1131 tsetdirt(sel.nb.y, sel.ne.y);
1136 bmotion(XEvent *e) {
1137 int oldey, oldex, oldsby, oldsey;
1139 if(IS_SET(MODE_MOUSE)) {
1154 if(oldey != sel.oe.y || oldex != sel.oe.x)
1155 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1159 die(const char *errstr, ...) {
1162 va_start(ap, errstr);
1163 vfprintf(stderr, errstr, ap);
1171 char *envshell = getenv("SHELL");
1172 const struct passwd *pass = getpwuid(getuid());
1173 char buf[sizeof(long) * 8 + 1];
1175 unsetenv("COLUMNS");
1177 unsetenv("TERMCAP");
1180 setenv("LOGNAME", pass->pw_name, 1);
1181 setenv("USER", pass->pw_name, 1);
1182 setenv("SHELL", pass->pw_shell, 0);
1183 setenv("HOME", pass->pw_dir, 0);
1186 snprintf(buf, sizeof(buf), "%lu", xw.win);
1187 setenv("WINDOWID", buf, 1);
1189 signal(SIGCHLD, SIG_DFL);
1190 signal(SIGHUP, SIG_DFL);
1191 signal(SIGINT, SIG_DFL);
1192 signal(SIGQUIT, SIG_DFL);
1193 signal(SIGTERM, SIG_DFL);
1194 signal(SIGALRM, SIG_DFL);
1196 DEFAULT(envshell, shell);
1197 setenv("TERM", termname, 1);
1198 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1199 execvp(args[0], args);
1207 if(waitpid(pid, &stat, 0) < 0)
1208 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1210 if(WIFEXITED(stat)) {
1211 exit(WEXITSTATUS(stat));
1220 struct winsize w = {term.row, term.col, 0, 0};
1222 /* seems to work fine on linux, openbsd and freebsd */
1223 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1224 die("openpty failed: %s\n", SERRNO);
1226 switch(pid = fork()) {
1228 die("fork failed\n");
1231 setsid(); /* create a new process group */
1232 dup2(s, STDIN_FILENO);
1233 dup2(s, STDOUT_FILENO);
1234 dup2(s, STDERR_FILENO);
1235 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1236 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1244 signal(SIGCHLD, sigchld);
1246 iofd = (!strcmp(opt_io, "-")) ?
1248 open(opt_io, O_WRONLY | O_CREAT, 0666);
1250 fprintf(stderr, "Error opening %s:%s\n",
1251 opt_io, strerror(errno));
1261 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1263 fprintf(stderr, "\n");
1268 static char buf[BUFSIZ];
1269 static int buflen = 0;
1272 int charsize; /* size of utf8 char in bytes */
1276 /* append read bytes to unprocessed bytes */
1277 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1278 die("Couldn't read from shell: %s\n", SERRNO);
1280 /* process every complete utf8 char */
1283 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1284 charsize = utf8decode(ptr, &utf8c);
1285 utf8encode(&utf8c, s);
1291 /* keep any uncomplete utf8 char for the next call */
1292 memmove(buf, ptr, buflen);
1296 ttywrite(const char *s, size_t n) {
1297 if(write(cmdfd, s, n) == -1)
1298 die("write error on tty: %s\n", SERRNO);
1302 ttysend(char *s, size_t n) {
1304 if(IS_SET(MODE_ECHO))
1312 w.ws_row = term.row;
1313 w.ws_col = term.col;
1314 w.ws_xpixel = xw.tw;
1315 w.ws_ypixel = xw.th;
1316 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1317 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1321 tattrset(int attr) {
1324 for(i = 0; i < term.row-1; i++) {
1325 for(j = 0; j < term.col-1; j++) {
1326 if(term.line[i][j].mode & attr)
1335 tsetdirt(int top, int bot) {
1338 LIMIT(top, 0, term.row-1);
1339 LIMIT(bot, 0, term.row-1);
1341 for(i = top; i <= bot; i++)
1346 tsetdirtattr(int attr) {
1349 for(i = 0; i < term.row-1; i++) {
1350 for(j = 0; j < term.col-1; j++) {
1351 if(term.line[i][j].mode & attr) {
1361 tsetdirt(0, term.row-1);
1366 static TCursor c[2];
1367 bool alt = IS_SET(MODE_ALTSCREEN);
1369 if(mode == CURSOR_SAVE) {
1371 } else if(mode == CURSOR_LOAD) {
1373 tmoveto(c[alt].x, c[alt].y);
1381 term.c = (TCursor){{
1385 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1387 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1388 for(i = tabspaces; i < term.col; i += tabspaces)
1391 term.bot = term.row - 1;
1392 term.mode = MODE_WRAP;
1393 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1396 tclearregion(0, 0, term.col-1, term.row-1);
1398 tcursor(CURSOR_SAVE);
1402 tnew(int col, int row) {
1403 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1412 Line *tmp = term.line;
1414 term.line = term.alt;
1416 term.mode ^= MODE_ALTSCREEN;
1421 tscrolldown(int orig, int n) {
1425 LIMIT(n, 0, term.bot-orig+1);
1427 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1429 for(i = term.bot; i >= orig+n; i--) {
1430 temp = term.line[i];
1431 term.line[i] = term.line[i-n];
1432 term.line[i-n] = temp;
1435 term.dirty[i-n] = 1;
1442 tscrollup(int orig, int n) {
1445 LIMIT(n, 0, term.bot-orig+1);
1447 tclearregion(0, orig, term.col-1, orig+n-1);
1449 for(i = orig; i <= term.bot-n; i++) {
1450 temp = term.line[i];
1451 term.line[i] = term.line[i+n];
1452 term.line[i+n] = temp;
1455 term.dirty[i+n] = 1;
1458 selscroll(orig, -n);
1462 selscroll(int orig, int n) {
1466 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1467 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1471 if(sel.type == SEL_RECTANGULAR) {
1472 if(sel.ob.y < term.top)
1473 sel.ob.y = term.top;
1474 if(sel.oe.y > term.bot)
1475 sel.oe.y = term.bot;
1477 if(sel.ob.y < term.top) {
1478 sel.ob.y = term.top;
1481 if(sel.oe.y > term.bot) {
1482 sel.oe.y = term.bot;
1483 sel.oe.x = term.col;
1491 tnewline(int first_col) {
1495 tscrollup(term.top, 1);
1499 tmoveto(first_col ? 0 : term.c.x, y);
1504 char *p = csiescseq.buf, *np;
1513 csiescseq.buf[csiescseq.len] = '\0';
1514 while(p < csiescseq.buf+csiescseq.len) {
1516 v = strtol(p, &np, 10);
1519 if(v == LONG_MAX || v == LONG_MIN)
1521 csiescseq.arg[csiescseq.narg++] = v;
1523 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1527 csiescseq.mode = *p;
1530 /* for absolute user moves, when decom is set */
1532 tmoveato(int x, int y) {
1533 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1537 tmoveto(int x, int y) {
1540 if(term.c.state & CURSOR_ORIGIN) {
1545 maxy = term.row - 1;
1547 LIMIT(x, 0, term.col-1);
1548 LIMIT(y, miny, maxy);
1549 term.c.state &= ~CURSOR_WRAPNEXT;
1555 tsetchar(char *c, Glyph *attr, int x, int y) {
1556 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1557 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1558 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1559 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1560 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1561 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1562 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1563 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1564 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1568 * The table is proudly stolen from rxvt.
1570 if(attr->mode & ATTR_GFX) {
1571 if(c[0] >= 0x41 && c[0] <= 0x7e
1572 && vt100_0[c[0] - 0x41]) {
1573 c = vt100_0[c[0] - 0x41];
1577 if(term.line[y][x].mode & ATTR_WIDE) {
1578 if(x+1 < term.col) {
1579 term.line[y][x+1].c[0] = ' ';
1580 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1582 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1583 term.line[y][x-1].c[0] = ' ';
1584 term.line[y][x-1].mode &= ~ATTR_WIDE;
1588 term.line[y][x] = *attr;
1589 memcpy(term.line[y][x].c, c, UTF_SIZ);
1593 tclearregion(int x1, int y1, int x2, int y2) {
1597 temp = x1, x1 = x2, x2 = temp;
1599 temp = y1, y1 = y2, y2 = temp;
1601 LIMIT(x1, 0, term.col-1);
1602 LIMIT(x2, 0, term.col-1);
1603 LIMIT(y1, 0, term.row-1);
1604 LIMIT(y2, 0, term.row-1);
1606 for(y = y1; y <= y2; y++) {
1608 for(x = x1; x <= x2; x++) {
1611 term.line[y][x] = term.c.attr;
1612 memcpy(term.line[y][x].c, " ", 2);
1618 tdeletechar(int n) {
1619 int src = term.c.x + n;
1621 int size = term.col - src;
1623 term.dirty[term.c.y] = 1;
1625 if(src >= term.col) {
1626 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1630 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1631 size * sizeof(Glyph));
1632 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1636 tinsertblank(int n) {
1639 int size = term.col - dst;
1641 term.dirty[term.c.y] = 1;
1643 if(dst >= term.col) {
1644 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1648 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1649 size * sizeof(Glyph));
1650 tclearregion(src, term.c.y, dst - 1, term.c.y);
1654 tinsertblankline(int n) {
1655 if(term.c.y < term.top || term.c.y > term.bot)
1658 tscrolldown(term.c.y, n);
1662 tdeleteline(int n) {
1663 if(term.c.y < term.top || term.c.y > term.bot)
1666 tscrollup(term.c.y, n);
1670 tdefcolor(int *attr, int *npar, int l) {
1674 switch (attr[*npar + 1]) {
1675 case 2: /* direct colour in RGB space */
1676 if (*npar + 4 >= l) {
1678 "erresc(38): Incorrect number of parameters (%d)\n",
1682 r = attr[*npar + 2];
1683 g = attr[*npar + 3];
1684 b = attr[*npar + 4];
1686 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1687 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1690 idx = TRUECOLOR(r, g, b);
1692 case 5: /* indexed colour */
1693 if (*npar + 2 >= l) {
1695 "erresc(38): Incorrect number of parameters (%d)\n",
1700 if(!BETWEEN(attr[*npar], 0, 255))
1701 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1705 case 0: /* implemented defined (only foreground) */
1706 case 1: /* transparent */
1707 case 3: /* direct colour in CMY space */
1708 case 4: /* direct colour in CMYK space */
1711 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1718 tsetattr(int *attr, int l) {
1722 for(i = 0; i < l; i++) {
1725 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1726 | ATTR_BOLD | ATTR_ITALIC \
1728 term.c.attr.fg = defaultfg;
1729 term.c.attr.bg = defaultbg;
1732 term.c.attr.mode |= ATTR_BOLD;
1735 term.c.attr.mode |= ATTR_ITALIC;
1738 term.c.attr.mode |= ATTR_UNDERLINE;
1740 case 5: /* slow blink */
1741 case 6: /* rapid blink */
1742 term.c.attr.mode |= ATTR_BLINK;
1745 term.c.attr.mode |= ATTR_REVERSE;
1749 term.c.attr.mode &= ~ATTR_BOLD;
1752 term.c.attr.mode &= ~ATTR_ITALIC;
1755 term.c.attr.mode &= ~ATTR_UNDERLINE;
1759 term.c.attr.mode &= ~ATTR_BLINK;
1762 term.c.attr.mode &= ~ATTR_REVERSE;
1765 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1766 term.c.attr.fg = idx;
1769 term.c.attr.fg = defaultfg;
1772 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1773 term.c.attr.bg = idx;
1776 term.c.attr.bg = defaultbg;
1779 if(BETWEEN(attr[i], 30, 37)) {
1780 term.c.attr.fg = attr[i] - 30;
1781 } else if(BETWEEN(attr[i], 40, 47)) {
1782 term.c.attr.bg = attr[i] - 40;
1783 } else if(BETWEEN(attr[i], 90, 97)) {
1784 term.c.attr.fg = attr[i] - 90 + 8;
1785 } else if(BETWEEN(attr[i], 100, 107)) {
1786 term.c.attr.bg = attr[i] - 100 + 8;
1789 "erresc(default): gfx attr %d unknown\n",
1790 attr[i]), csidump();
1798 tsetscroll(int t, int b) {
1801 LIMIT(t, 0, term.row-1);
1802 LIMIT(b, 0, term.row-1);
1812 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1815 tsetmode(bool priv, bool set, int *args, int narg) {
1819 for(lim = args + narg; args < lim; ++args) {
1823 case 1: /* DECCKM -- Cursor key */
1824 MODBIT(term.mode, set, MODE_APPCURSOR);
1826 case 5: /* DECSCNM -- Reverse video */
1828 MODBIT(term.mode, set, MODE_REVERSE);
1829 if(mode != term.mode)
1830 redraw(REDRAW_TIMEOUT);
1832 case 6: /* DECOM -- Origin */
1833 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1836 case 7: /* DECAWM -- Auto wrap */
1837 MODBIT(term.mode, set, MODE_WRAP);
1839 case 0: /* Error (IGNORED) */
1840 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1841 case 3: /* DECCOLM -- Column (IGNORED) */
1842 case 4: /* DECSCLM -- Scroll (IGNORED) */
1843 case 8: /* DECARM -- Auto repeat (IGNORED) */
1844 case 18: /* DECPFF -- Printer feed (IGNORED) */
1845 case 19: /* DECPEX -- Printer extent (IGNORED) */
1846 case 42: /* DECNRCM -- National characters (IGNORED) */
1847 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1849 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1850 MODBIT(term.mode, !set, MODE_HIDE);
1852 case 9: /* X10 mouse compatibility mode */
1853 xsetpointermotion(0);
1854 MODBIT(term.mode, 0, MODE_MOUSE);
1855 MODBIT(term.mode, set, MODE_MOUSEX10);
1857 case 1000: /* 1000: report button press */
1858 xsetpointermotion(0);
1859 MODBIT(term.mode, 0, MODE_MOUSE);
1860 MODBIT(term.mode, set, MODE_MOUSEBTN);
1862 case 1002: /* 1002: report motion on button press */
1863 xsetpointermotion(0);
1864 MODBIT(term.mode, 0, MODE_MOUSE);
1865 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1867 case 1003: /* 1003: enable all mouse motions */
1868 xsetpointermotion(set);
1869 MODBIT(term.mode, 0, MODE_MOUSE);
1870 MODBIT(term.mode, set, MODE_MOUSEMANY);
1872 case 1004: /* 1004: send focus events to tty */
1873 MODBIT(term.mode, set, MODE_FOCUS);
1875 case 1006: /* 1006: extended reporting mode */
1876 MODBIT(term.mode, set, MODE_MOUSESGR);
1879 MODBIT(term.mode, set, MODE_8BIT);
1881 case 1049: /* swap screen & set/restore cursor as xterm */
1882 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1883 case 47: /* swap screen */
1885 if (!allowaltscreen)
1887 alt = IS_SET(MODE_ALTSCREEN);
1889 tclearregion(0, 0, term.col-1,
1892 if(set ^ alt) /* set is always 1 or 0 */
1898 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1900 case 2004: /* 2004: bracketed paste mode */
1901 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1903 /* Not implemented mouse modes. See comments there. */
1904 case 1001: /* mouse highlight mode; can hang the
1905 terminal by design when implemented. */
1906 case 1005: /* UTF-8 mouse mode; will confuse
1907 applications not supporting UTF-8
1909 case 1015: /* urxvt mangled mouse mode; incompatible
1910 and can be mistaken for other control
1914 "erresc: unknown private set/reset mode %d\n",
1920 case 0: /* Error (IGNORED) */
1922 case 2: /* KAM -- keyboard action */
1923 MODBIT(term.mode, set, MODE_KBDLOCK);
1925 case 4: /* IRM -- Insertion-replacement */
1926 MODBIT(term.mode, set, MODE_INSERT);
1928 case 12: /* SRM -- Send/Receive */
1929 MODBIT(term.mode, !set, MODE_ECHO);
1931 case 20: /* LNM -- Linefeed/new line */
1932 MODBIT(term.mode, set, MODE_CRLF);
1936 "erresc: unknown set/reset mode %d\n",
1949 switch(csiescseq.mode) {
1952 fprintf(stderr, "erresc: unknown csi ");
1956 case '@': /* ICH -- Insert <n> blank char */
1957 DEFAULT(csiescseq.arg[0], 1);
1958 tinsertblank(csiescseq.arg[0]);
1960 case 'A': /* CUU -- Cursor <n> Up */
1961 DEFAULT(csiescseq.arg[0], 1);
1962 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1964 case 'B': /* CUD -- Cursor <n> Down */
1965 case 'e': /* VPR --Cursor <n> Down */
1966 DEFAULT(csiescseq.arg[0], 1);
1967 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1969 case 'c': /* DA -- Device Attributes */
1970 if(csiescseq.arg[0] == 0)
1971 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1973 case 'C': /* CUF -- Cursor <n> Forward */
1974 case 'a': /* HPR -- Cursor <n> Forward */
1975 DEFAULT(csiescseq.arg[0], 1);
1976 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1978 case 'D': /* CUB -- Cursor <n> Backward */
1979 DEFAULT(csiescseq.arg[0], 1);
1980 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1982 case 'E': /* CNL -- Cursor <n> Down and first col */
1983 DEFAULT(csiescseq.arg[0], 1);
1984 tmoveto(0, term.c.y+csiescseq.arg[0]);
1986 case 'F': /* CPL -- Cursor <n> Up and first col */
1987 DEFAULT(csiescseq.arg[0], 1);
1988 tmoveto(0, term.c.y-csiescseq.arg[0]);
1990 case 'g': /* TBC -- Tabulation clear */
1991 switch(csiescseq.arg[0]) {
1992 case 0: /* clear current tab stop */
1993 term.tabs[term.c.x] = 0;
1995 case 3: /* clear all the tabs */
1996 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2002 case 'G': /* CHA -- Move to <col> */
2004 DEFAULT(csiescseq.arg[0], 1);
2005 tmoveto(csiescseq.arg[0]-1, term.c.y);
2007 case 'H': /* CUP -- Move to <row> <col> */
2009 DEFAULT(csiescseq.arg[0], 1);
2010 DEFAULT(csiescseq.arg[1], 1);
2011 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2013 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2014 DEFAULT(csiescseq.arg[0], 1);
2015 while(csiescseq.arg[0]--)
2018 case 'J': /* ED -- Clear screen */
2020 switch(csiescseq.arg[0]) {
2022 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2023 if(term.c.y < term.row-1) {
2024 tclearregion(0, term.c.y+1, term.col-1,
2030 tclearregion(0, 0, term.col-1, term.c.y-1);
2031 tclearregion(0, term.c.y, term.c.x, term.c.y);
2034 tclearregion(0, 0, term.col-1, term.row-1);
2040 case 'K': /* EL -- Clear line */
2041 switch(csiescseq.arg[0]) {
2043 tclearregion(term.c.x, term.c.y, term.col-1,
2047 tclearregion(0, term.c.y, term.c.x, term.c.y);
2050 tclearregion(0, term.c.y, term.col-1, term.c.y);
2054 case 'S': /* SU -- Scroll <n> line up */
2055 DEFAULT(csiescseq.arg[0], 1);
2056 tscrollup(term.top, csiescseq.arg[0]);
2058 case 'T': /* SD -- Scroll <n> line down */
2059 DEFAULT(csiescseq.arg[0], 1);
2060 tscrolldown(term.top, csiescseq.arg[0]);
2062 case 'L': /* IL -- Insert <n> blank lines */
2063 DEFAULT(csiescseq.arg[0], 1);
2064 tinsertblankline(csiescseq.arg[0]);
2066 case 'l': /* RM -- Reset Mode */
2067 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2069 case 'M': /* DL -- Delete <n> lines */
2070 DEFAULT(csiescseq.arg[0], 1);
2071 tdeleteline(csiescseq.arg[0]);
2073 case 'X': /* ECH -- Erase <n> char */
2074 DEFAULT(csiescseq.arg[0], 1);
2075 tclearregion(term.c.x, term.c.y,
2076 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2078 case 'P': /* DCH -- Delete <n> char */
2079 DEFAULT(csiescseq.arg[0], 1);
2080 tdeletechar(csiescseq.arg[0]);
2082 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2083 DEFAULT(csiescseq.arg[0], 1);
2084 while(csiescseq.arg[0]--)
2087 case 'd': /* VPA -- Move to <row> */
2088 DEFAULT(csiescseq.arg[0], 1);
2089 tmoveato(term.c.x, csiescseq.arg[0]-1);
2091 case 'h': /* SM -- Set terminal mode */
2092 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2094 case 'm': /* SGR -- Terminal attribute (color) */
2095 tsetattr(csiescseq.arg, csiescseq.narg);
2097 case 'n': /* DSR – Device Status Report (cursor position) */
2098 if (csiescseq.arg[0] == 6) {
2099 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2100 term.c.y+1, term.c.x+1);
2104 case 'r': /* DECSTBM -- Set Scrolling Region */
2105 if(csiescseq.priv) {
2108 DEFAULT(csiescseq.arg[0], 1);
2109 DEFAULT(csiescseq.arg[1], term.row);
2110 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2114 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2115 tcursor(CURSOR_SAVE);
2117 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2118 tcursor(CURSOR_LOAD);
2129 for(i = 0; i < csiescseq.len; i++) {
2130 c = csiescseq.buf[i] & 0xff;
2133 } else if(c == '\n') {
2135 } else if(c == '\r') {
2137 } else if(c == 0x1b) {
2140 printf("(%02x)", c);
2148 memset(&csiescseq, 0, sizeof(csiescseq));
2157 narg = strescseq.narg;
2159 switch(strescseq.type) {
2160 case ']': /* OSC -- Operating System Command */
2161 switch(i = atoi(strescseq.args[0])) {
2166 xsettitle(strescseq.args[1]);
2168 case 4: /* color set */
2171 p = strescseq.args[2];
2173 case 104: /* color reset, here p = NULL */
2174 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2175 if (!xsetcolorname(j, p)) {
2176 fprintf(stderr, "erresc: invalid color %s\n", p);
2179 * TODO if defaultbg color is changed, borders
2186 fprintf(stderr, "erresc: unknown str ");
2191 case 'k': /* old title set compatibility */
2192 xsettitle(strescseq.args[0]);
2194 case 'P': /* DSC -- Device Control String */
2195 case '_': /* APC -- Application Program Command */
2196 case '^': /* PM -- Privacy Message */
2198 fprintf(stderr, "erresc: unknown str ");
2207 char *p = strescseq.buf;
2210 strescseq.buf[strescseq.len] = '\0';
2211 while(p && strescseq.narg < STR_ARG_SIZ)
2212 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2220 printf("ESC%c", strescseq.type);
2221 for(i = 0; i < strescseq.len; i++) {
2222 c = strescseq.buf[i] & 0xff;
2225 } else if(isprint(c)) {
2227 } else if(c == '\n') {
2229 } else if(c == '\r') {
2231 } else if(c == 0x1b) {
2234 printf("(%02x)", c);
2242 memset(&strescseq, 0, sizeof(strescseq));
2246 tputtab(bool forward) {
2252 for(++x; x < term.col && !term.tabs[x]; ++x)
2257 for(--x; x > 0 && !term.tabs[x]; --x)
2260 tmoveto(x, term.c.y);
2264 techo(char *buf, int len) {
2265 for(; len > 0; buf++, len--) {
2268 if(c == '\033') { /* escape */
2271 } else if(c < '\x20') { /* control code */
2272 if(c != '\n' && c != '\r' && c != '\t') {
2286 tdeftran(char ascii) {
2288 static char tbl[][2] = {
2289 {'0', CS_GRAPHIC0}, {'1', CS_GRAPHIC1}, {'A', CS_UK},
2290 {'B', CS_USA}, {'<', CS_MULTI}, {'K', CS_GER},
2291 {'5', CS_FIN}, {'C', CS_FIN},
2295 for (bp = &tbl[0]; (c = (*bp)[0]) && c != ascii; ++bp)
2299 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2301 term.trantbl[term.icharset] = (*bp)[1];
2306 if (term.trantbl[term.charset] == CS_GRAPHIC0)
2307 term.c.attr.mode |= ATTR_GFX;
2309 term.c.attr.mode &= ~ATTR_GFX;
2313 tputc(char *c, int len) {
2315 bool control = ascii < '\x20' || ascii == 0177;
2322 utf8decode(c, &u8char);
2323 width = wcwidth(u8char);
2327 if(xwrite(iofd, c, len) < 0) {
2328 fprintf(stderr, "Error writing in %s:%s\n",
2329 opt_io, strerror(errno));
2336 * STR sequences must be checked before anything else
2337 * because it can use some control codes as part of the sequence.
2339 if(term.esc & ESC_STR) {
2342 term.esc = ESC_START | ESC_STR_END;
2344 case '\a': /* backwards compatibility to xterm */
2349 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2350 memmove(&strescseq.buf[strescseq.len], c, len);
2351 strescseq.len += len;
2354 * Here is a bug in terminals. If the user never sends
2355 * some code to stop the str or esc command, then st
2356 * will stop responding. But this is better than
2357 * silently failing with unknown characters. At least
2358 * then users will report back.
2360 * In the case users ever get fixed, here is the code:
2372 * Actions of control codes must be performed as soon they arrive
2373 * because they can be embedded inside a control sequence, and
2374 * they must not cause conflicts with sequences.
2382 tmoveto(term.c.x-1, term.c.y);
2385 tmoveto(0, term.c.y);
2390 /* go to first col if the mode is set */
2391 tnewline(IS_SET(MODE_CRLF));
2393 case '\a': /* BEL */
2394 if(!(xw.state & WIN_FOCUSED))
2397 XBell(xw.dpy, bellvolume);
2399 case '\033': /* ESC */
2401 term.esc = ESC_START;
2403 case '\016': /* SO */
2407 case '\017': /* SI */
2411 case '\032': /* SUB */
2412 case '\030': /* CAN */
2415 case '\005': /* ENQ (IGNORED) */
2416 case '\000': /* NUL (IGNORED) */
2417 case '\021': /* XON (IGNORED) */
2418 case '\023': /* XOFF (IGNORED) */
2419 case 0177: /* DEL (IGNORED) */
2422 } else if(term.esc & ESC_START) {
2423 if(term.esc & ESC_CSI) {
2424 csiescseq.buf[csiescseq.len++] = ascii;
2425 if(BETWEEN(ascii, 0x40, 0x7E)
2426 || csiescseq.len >= \
2427 sizeof(csiescseq.buf)-1) {
2432 } else if(term.esc & ESC_STR_END) {
2436 } else if(term.esc & ESC_ALTCHARSET) {
2440 } else if(term.esc & ESC_TEST) {
2441 if(ascii == '8') { /* DEC screen alignment test. */
2442 char E[UTF_SIZ] = "E";
2445 for(x = 0; x < term.col; ++x) {
2446 for(y = 0; y < term.row; ++y)
2447 tsetchar(E, &term.c.attr, x, y);
2454 term.esc |= ESC_CSI;
2457 term.esc |= ESC_TEST;
2459 case 'P': /* DCS -- Device Control String */
2460 case '_': /* APC -- Application Program Command */
2461 case '^': /* PM -- Privacy Message */
2462 case ']': /* OSC -- Operating System Command */
2463 case 'k': /* old title set compatibility */
2465 strescseq.type = ascii;
2466 term.esc |= ESC_STR;
2468 case '(': /* set primary charset G0 */
2469 case ')': /* set secondary charset G1 */
2470 case '*': /* set tertiary charset G2 */
2471 case '+': /* set quaternary charset G3 */
2472 term.icharset = ascii - '(';
2473 term.esc |= ESC_ALTCHARSET;
2475 case 'D': /* IND -- Linefeed */
2476 if(term.c.y == term.bot) {
2477 tscrollup(term.top, 1);
2479 tmoveto(term.c.x, term.c.y+1);
2483 case 'E': /* NEL -- Next line */
2484 tnewline(1); /* always go to first col */
2487 case 'H': /* HTS -- Horizontal tab stop */
2488 term.tabs[term.c.x] = 1;
2491 case 'M': /* RI -- Reverse index */
2492 if(term.c.y == term.top) {
2493 tscrolldown(term.top, 1);
2495 tmoveto(term.c.x, term.c.y-1);
2499 case 'Z': /* DECID -- Identify Terminal */
2500 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2503 case 'c': /* RIS -- Reset to inital state */
2509 case '=': /* DECPAM -- Application keypad */
2510 term.mode |= MODE_APPKEYPAD;
2513 case '>': /* DECPNM -- Normal keypad */
2514 term.mode &= ~MODE_APPKEYPAD;
2517 case '7': /* DECSC -- Save Cursor */
2518 tcursor(CURSOR_SAVE);
2521 case '8': /* DECRC -- Restore Cursor */
2522 tcursor(CURSOR_LOAD);
2525 case '\\': /* ST -- Stop */
2529 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2530 (uchar) ascii, isprint(ascii)? ascii:'.');
2535 * All characters which form part of a sequence are not
2541 * Display control codes only if we are in graphic mode
2543 if(control && !(term.c.attr.mode & ATTR_GFX))
2545 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2547 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2548 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2552 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2553 memmove(&term.line[term.c.y][term.c.x+1],
2554 &term.line[term.c.y][term.c.x],
2555 (term.col - term.c.x - 1) * sizeof(Glyph));
2558 if(term.c.x+width > term.col)
2561 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2564 term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
2565 if(term.c.x+1 < term.col) {
2566 term.line[term.c.y][term.c.x+1].c[0] = '\0';
2567 term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
2570 if(term.c.x+width < term.col) {
2571 tmoveto(term.c.x+width, term.c.y);
2573 term.c.state |= CURSOR_WRAPNEXT;
2578 tresize(int col, int row) {
2580 int minrow = MIN(row, term.row);
2581 int mincol = MIN(col, term.col);
2582 int slide = term.c.y - row + 1;
2586 if(col < 1 || row < 1)
2589 /* free unneeded rows */
2593 * slide screen to keep cursor where we expect it -
2594 * tscrollup would work here, but we can optimize to
2595 * memmove because we're freeing the earlier lines
2597 for(/* i = 0 */; i < slide; i++) {
2601 memmove(term.line, term.line + slide, row * sizeof(Line));
2602 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2604 for(i += row; i < term.row; i++) {
2609 /* resize to new height */
2610 term.line = xrealloc(term.line, row * sizeof(Line));
2611 term.alt = xrealloc(term.alt, row * sizeof(Line));
2612 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2613 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2615 /* resize each row to new width, zero-pad if needed */
2616 for(i = 0; i < minrow; i++) {
2618 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2619 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2622 /* allocate any new rows */
2623 for(/* i == minrow */; i < row; i++) {
2625 term.line[i] = xmalloc(col * sizeof(Glyph));
2626 term.alt[i] = xmalloc(col * sizeof(Glyph));
2628 if(col > term.col) {
2629 bp = term.tabs + term.col;
2631 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2632 while(--bp > term.tabs && !*bp)
2634 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2637 /* update terminal size */
2640 /* reset scrolling region */
2641 tsetscroll(0, row-1);
2642 /* make use of the LIMIT in tmoveto */
2643 tmoveto(term.c.x, term.c.y);
2644 /* Clearing both screens */
2647 if(mincol < col && 0 < minrow) {
2648 tclearregion(mincol, 0, col - 1, minrow - 1);
2650 if(0 < col && minrow < row) {
2651 tclearregion(0, minrow, col - 1, row - 1);
2654 } while(orig != term.line);
2660 xresize(int col, int row) {
2661 xw.tw = MAX(1, col * xw.cw);
2662 xw.th = MAX(1, row * xw.ch);
2664 XFreePixmap(xw.dpy, xw.buf);
2665 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2666 DefaultDepth(xw.dpy, xw.scr));
2667 XftDrawChange(xw.draw, xw.buf);
2668 xclear(0, 0, xw.w, xw.h);
2671 static inline ushort
2672 sixd_to_16bit(int x) {
2673 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2679 XRenderColor color = { .alpha = 0xffff };
2684 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2685 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2688 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2689 for(i = 0; i < LEN(colorname); i++) {
2692 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2693 die("Could not allocate color '%s'\n", colorname[i]);
2697 /* load colors [16-255] ; same colors as xterm */
2698 for(i = 16, r = 0; r < 6; r++) {
2699 for(g = 0; g < 6; g++) {
2700 for(b = 0; b < 6; b++) {
2701 color.red = sixd_to_16bit(r);
2702 color.green = sixd_to_16bit(g);
2703 color.blue = sixd_to_16bit(b);
2704 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2705 die("Could not allocate color %d\n", i);
2712 for(r = 0; r < 24; r++, i++) {
2713 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2714 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2716 die("Could not allocate color %d\n", i);
2723 xsetcolorname(int x, const char *name) {
2724 XRenderColor color = { .alpha = 0xffff };
2726 if (x < 0 || x > LEN(colorname))
2729 if(16 <= x && x < 16 + 216) {
2730 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2731 color.red = sixd_to_16bit(r);
2732 color.green = sixd_to_16bit(g);
2733 color.blue = sixd_to_16bit(b);
2734 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2735 return 0; /* something went wrong */
2738 } else if (16 + 216 <= x && x < 256) {
2739 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2740 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2741 return 0; /* something went wrong */
2745 name = colorname[x];
2748 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2755 xtermclear(int col1, int row1, int col2, int row2) {
2756 XftDrawRect(xw.draw,
2757 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2758 borderpx + col1 * xw.cw,
2759 borderpx + row1 * xw.ch,
2760 (col2-col1+1) * xw.cw,
2761 (row2-row1+1) * xw.ch);
2765 * Absolute coordinates.
2768 xclear(int x1, int y1, int x2, int y2) {
2769 XftDrawRect(xw.draw,
2770 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2771 x1, y1, x2-x1, y2-y1);
2776 XClassHint class = {opt_class ? opt_class : termname, termname};
2777 XWMHints wm = {.flags = InputHint, .input = 1};
2778 XSizeHints *sizeh = NULL;
2780 sizeh = XAllocSizeHints();
2781 if(xw.isfixed == False) {
2782 sizeh->flags = PSize | PResizeInc | PBaseSize;
2783 sizeh->height = xw.h;
2784 sizeh->width = xw.w;
2785 sizeh->height_inc = xw.ch;
2786 sizeh->width_inc = xw.cw;
2787 sizeh->base_height = 2 * borderpx;
2788 sizeh->base_width = 2 * borderpx;
2790 sizeh->flags = PMaxSize | PMinSize;
2791 sizeh->min_width = sizeh->max_width = xw.fw;
2792 sizeh->min_height = sizeh->max_height = xw.fh;
2795 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2800 xloadfont(Font *f, FcPattern *pattern) {
2804 match = FcFontMatch(NULL, pattern, &result);
2808 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2809 FcPatternDestroy(match);
2814 f->pattern = FcPatternDuplicate(pattern);
2816 f->ascent = f->match->ascent;
2817 f->descent = f->match->descent;
2819 f->rbearing = f->match->max_advance_width;
2821 f->height = f->ascent + f->descent;
2822 f->width = f->lbearing + f->rbearing;
2828 xloadfonts(char *fontstr, int fontsize) {
2833 if(fontstr[0] == '-') {
2834 pattern = XftXlfdParse(fontstr, False, False);
2836 pattern = FcNameParse((FcChar8 *)fontstr);
2840 die("st: can't open font %s\n", fontstr);
2843 FcPatternDel(pattern, FC_PIXEL_SIZE);
2844 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2845 usedfontsize = fontsize;
2847 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2848 if(result == FcResultMatch) {
2849 usedfontsize = (int)fontval;
2852 * Default font size is 12, if none given. This is to
2853 * have a known usedfontsize value.
2855 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2860 FcConfigSubstitute(0, pattern, FcMatchPattern);
2861 FcDefaultSubstitute(pattern);
2863 if(xloadfont(&dc.font, pattern))
2864 die("st: can't open font %s\n", fontstr);
2866 /* Setting character width and height. */
2867 xw.cw = CEIL(dc.font.width * cwscale);
2868 xw.ch = CEIL(dc.font.height * chscale);
2870 FcPatternDel(pattern, FC_SLANT);
2871 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2872 if(xloadfont(&dc.ifont, pattern))
2873 die("st: can't open font %s\n", fontstr);
2875 FcPatternDel(pattern, FC_WEIGHT);
2876 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2877 if(xloadfont(&dc.ibfont, pattern))
2878 die("st: can't open font %s\n", fontstr);
2880 FcPatternDel(pattern, FC_SLANT);
2881 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2882 if(xloadfont(&dc.bfont, pattern))
2883 die("st: can't open font %s\n", fontstr);
2885 FcPatternDestroy(pattern);
2889 xloadfontset(Font *f) {
2892 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2898 xunloadfont(Font *f) {
2899 XftFontClose(xw.dpy, f->match);
2900 FcPatternDestroy(f->pattern);
2902 FcFontSetDestroy(f->set);
2906 xunloadfonts(void) {
2909 /* Free the loaded fonts in the font cache. */
2910 for(i = 0; i < frclen; i++) {
2911 XftFontClose(xw.dpy, frc[i].font);
2915 xunloadfont(&dc.font);
2916 xunloadfont(&dc.bfont);
2917 xunloadfont(&dc.ifont);
2918 xunloadfont(&dc.ibfont);
2922 xzoom(const Arg *arg) {
2924 xloadfonts(usedfont, usedfontsize + arg->i);
2936 if(!(xw.dpy = XOpenDisplay(NULL)))
2937 die("Can't open display\n");
2938 xw.scr = XDefaultScreen(xw.dpy);
2939 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2943 die("Could not init fontconfig.\n");
2945 usedfont = (opt_font == NULL)? font : opt_font;
2946 xloadfonts(usedfont, 0);
2949 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2952 /* adjust fixed window geometry */
2954 sw = DisplayWidth(xw.dpy, xw.scr);
2955 sh = DisplayHeight(xw.dpy, xw.scr);
2957 xw.fx = sw + xw.fx - xw.fw - 1;
2959 xw.fy = sh + xw.fy - xw.fh - 1;
2964 /* window - default size */
2965 xw.h = 2 * borderpx + term.row * xw.ch;
2966 xw.w = 2 * borderpx + term.col * xw.cw;
2972 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2973 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2974 xw.attrs.bit_gravity = NorthWestGravity;
2975 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2976 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2977 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2978 xw.attrs.colormap = xw.cmap;
2980 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2981 XRootWindow(xw.dpy, xw.scr);
2982 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2983 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2984 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
2985 | CWEventMask | CWColormap, &xw.attrs);
2987 memset(&gcvalues, 0, sizeof(gcvalues));
2988 gcvalues.graphics_exposures = False;
2989 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2991 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2992 DefaultDepth(xw.dpy, xw.scr));
2993 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2994 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2996 /* Xft rendering context */
2997 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3000 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3001 XSetLocaleModifiers("@im=local");
3002 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3003 XSetLocaleModifiers("@im=");
3004 if((xw.xim = XOpenIM(xw.dpy,
3005 NULL, NULL, NULL)) == NULL) {
3006 die("XOpenIM failed. Could not open input"
3011 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3012 | XIMStatusNothing, XNClientWindow, xw.win,
3013 XNFocusWindow, xw.win, NULL);
3015 die("XCreateIC failed. Could not obtain input method.\n");
3017 /* white cursor, black outline */
3018 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3019 XDefineCursor(xw.dpy, xw.win, cursor);
3020 XRecolorCursor(xw.dpy, cursor,
3021 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3022 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3024 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3025 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3026 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3029 XMapWindow(xw.dpy, xw.win);
3035 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3036 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3037 width = charlen * xw.cw, xp, i;
3039 int u8fl, u8fblen, u8cblen, doesexist;
3042 Font *font = &dc.font;
3044 FcPattern *fcpattern, *fontpattern;
3045 FcFontSet *fcsets[] = { NULL };
3046 FcCharSet *fccharset;
3047 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3048 XRenderColor colfg, colbg;
3052 frcflags = FRC_NORMAL;
3054 if(base.mode & ATTR_ITALIC) {
3055 if(base.fg == defaultfg)
3056 base.fg = defaultitalic;
3058 frcflags = FRC_ITALIC;
3059 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3060 if(base.fg == defaultfg)
3061 base.fg = defaultitalic;
3063 frcflags = FRC_ITALICBOLD;
3064 } else if(base.mode & ATTR_UNDERLINE) {
3065 if(base.fg == defaultfg)
3066 base.fg = defaultunderline;
3068 if(IS_TRUECOL(base.fg)) {
3069 colfg.red = TRUERED(base.fg);
3070 colfg.green = TRUEGREEN(base.fg);
3071 colfg.blue = TRUEBLUE(base.fg);
3072 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3075 fg = &dc.col[base.fg];
3078 if(IS_TRUECOL(base.bg)) {
3079 colbg.green = TRUEGREEN(base.bg);
3080 colbg.red = TRUERED(base.bg);
3081 colbg.blue = TRUEBLUE(base.bg);
3082 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3085 bg = &dc.col[base.bg];
3090 if(base.mode & ATTR_BOLD) {
3091 if(BETWEEN(base.fg, 0, 7)) {
3092 /* basic system colors */
3093 fg = &dc.col[base.fg + 8];
3094 } else if(BETWEEN(base.fg, 16, 195)) {
3096 fg = &dc.col[base.fg + 36];
3097 } else if(BETWEEN(base.fg, 232, 251)) {
3099 fg = &dc.col[base.fg + 4];
3102 * Those ranges will not be brightened:
3103 * 8 - 15 – bright system colors
3104 * 196 - 231 – highest 256 color cube
3105 * 252 - 255 – brightest colors in greyscale
3108 frcflags = FRC_BOLD;
3111 if(IS_SET(MODE_REVERSE)) {
3112 if(fg == &dc.col[defaultfg]) {
3113 fg = &dc.col[defaultbg];
3115 colfg.red = ~fg->color.red;
3116 colfg.green = ~fg->color.green;
3117 colfg.blue = ~fg->color.blue;
3118 colfg.alpha = fg->color.alpha;
3119 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3123 if(bg == &dc.col[defaultbg]) {
3124 bg = &dc.col[defaultfg];
3126 colbg.red = ~bg->color.red;
3127 colbg.green = ~bg->color.green;
3128 colbg.blue = ~bg->color.blue;
3129 colbg.alpha = bg->color.alpha;
3130 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3135 if(base.mode & ATTR_REVERSE) {
3141 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3144 /* Intelligent cleaning up of the borders. */
3146 xclear(0, (y == 0)? 0 : winy, borderpx,
3147 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3149 if(x + charlen >= term.col) {
3150 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3151 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3154 xclear(winx, 0, winx + width, borderpx);
3156 xclear(winx, winy + xw.ch, winx + width, xw.h);
3158 /* Clean up the region we want to draw to. */
3159 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3161 /* Set the clip region because Xft is sometimes dirty. */
3166 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3168 for(xp = winx; bytelen > 0;) {
3170 * Search for the range in the to be printed string of glyphs
3171 * that are in the main font. Then print that range. If
3172 * some glyph is found that is not in the font, do the
3178 oneatatime = font->width != xw.cw;
3181 u8cblen = utf8decode(s, &u8char);
3185 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3186 if(oneatatime || !doesexist || bytelen <= 0) {
3187 if(oneatatime || bytelen <= 0) {
3195 XftDrawStringUtf8(xw.draw, fg,
3197 winy + font->ascent,
3215 /* Search the font cache. */
3216 for(i = 0; i < frclen; i++) {
3217 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3218 && frc[i].flags == frcflags) {
3223 /* Nothing was found. */
3227 fcsets[0] = font->set;
3230 * Nothing was found in the cache. Now use
3231 * some dozen of Fontconfig calls to get the
3232 * font for one single character.
3234 fcpattern = FcPatternDuplicate(font->pattern);
3235 fccharset = FcCharSetCreate();
3237 FcCharSetAddChar(fccharset, u8char);
3238 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3240 FcPatternAddBool(fcpattern, FC_SCALABLE,
3243 FcConfigSubstitute(0, fcpattern,
3245 FcDefaultSubstitute(fcpattern);
3247 fontpattern = FcFontSetMatch(0, fcsets,
3248 FcTrue, fcpattern, &fcres);
3251 * Overwrite or create the new cache entry.
3253 if(frclen >= LEN(frc)) {
3254 frclen = LEN(frc) - 1;
3255 XftFontClose(xw.dpy, frc[frclen].font);
3258 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3260 frc[frclen].flags = frcflags;
3265 FcPatternDestroy(fcpattern);
3266 FcCharSetDestroy(fccharset);
3269 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3270 xp, winy + frc[i].font->ascent,
3271 (FcChar8 *)u8c, u8cblen);
3273 xp += xw.cw * wcwidth(u8char);
3277 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3278 winy + font->ascent, (FcChar8 *)s, bytelen);
3281 if(base.mode & ATTR_UNDERLINE) {
3282 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3286 /* Reset clip to none. */
3287 XftDrawSetClip(xw.draw, 0);
3292 static int oldx = 0, oldy = 0;
3293 int sl, width, curx;
3294 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3296 LIMIT(oldx, 0, term.col-1);
3297 LIMIT(oldy, 0, term.row-1);
3301 /* adjust position if in dummy */
3302 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3304 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3307 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3309 /* remove the old cursor */
3310 sl = utf8size(term.line[oldy][oldx].c);
3311 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3312 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3315 /* draw the new one */
3316 if(!(IS_SET(MODE_HIDE))) {
3317 if(xw.state & WIN_FOCUSED) {
3318 if(IS_SET(MODE_REVERSE)) {
3319 g.mode |= ATTR_REVERSE;
3325 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3327 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3329 XftDrawRect(xw.draw, &dc.col[defaultcs],
3330 borderpx + curx * xw.cw,
3331 borderpx + term.c.y * xw.ch,
3333 XftDrawRect(xw.draw, &dc.col[defaultcs],
3334 borderpx + curx * xw.cw,
3335 borderpx + term.c.y * xw.ch,
3337 XftDrawRect(xw.draw, &dc.col[defaultcs],
3338 borderpx + (curx + 1) * xw.cw - 1,
3339 borderpx + term.c.y * xw.ch,
3341 XftDrawRect(xw.draw, &dc.col[defaultcs],
3342 borderpx + curx * xw.cw,
3343 borderpx + (term.c.y + 1) * xw.ch - 1,
3346 oldx = curx, oldy = term.c.y;
3352 xsettitle(char *p) {
3355 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3357 XSetWMName(xw.dpy, xw.win, &prop);
3363 xsettitle(opt_title ? opt_title : "st");
3367 redraw(int timeout) {
3368 struct timespec tv = {0, timeout * 1000};
3374 nanosleep(&tv, NULL);
3375 XSync(xw.dpy, False); /* necessary for a good tput flash */
3381 drawregion(0, 0, term.col, term.row);
3382 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3384 XSetForeground(xw.dpy, dc.gc,
3385 dc.col[IS_SET(MODE_REVERSE)?
3386 defaultfg : defaultbg].pixel);
3390 drawregion(int x1, int y1, int x2, int y2) {
3391 int ic, ib, x, y, ox, sl;
3393 char buf[DRAW_BUF_SIZ];
3394 bool ena_sel = sel.ob.x != -1;
3397 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3400 if(!(xw.state & WIN_VISIBLE))
3403 for(y = y1; y < y2; y++) {
3407 xtermclear(0, y, term.col, y);
3409 base = term.line[y][0];
3411 for(x = x1; x < x2; x++) {
3412 new = term.line[y][x];
3413 if(new.mode == ATTR_WDUMMY)
3415 if(ena_sel && selected(x, y))
3416 new.mode ^= ATTR_REVERSE;
3417 if(ib > 0 && (ATTRCMP(base, new)
3418 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3419 xdraws(buf, base, ox, y, ic, ib);
3427 sl = utf8decode(new.c, &u8char);
3428 memcpy(buf+ib, new.c, sl);
3430 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3433 xdraws(buf, base, ox, y, ic, ib);
3439 expose(XEvent *ev) {
3440 XExposeEvent *e = &ev->xexpose;
3442 if(xw.state & WIN_REDRAW) {
3444 xw.state &= ~WIN_REDRAW;
3450 visibility(XEvent *ev) {
3451 XVisibilityEvent *e = &ev->xvisibility;
3453 if(e->state == VisibilityFullyObscured) {
3454 xw.state &= ~WIN_VISIBLE;
3455 } else if(!(xw.state & WIN_VISIBLE)) {
3456 /* need a full redraw for next Expose, not just a buf copy */
3457 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3463 xw.state &= ~WIN_VISIBLE;
3467 xsetpointermotion(int set) {
3468 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3469 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3473 xseturgency(int add) {
3474 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3476 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3477 XSetWMHints(xw.dpy, xw.win, h);
3483 XFocusChangeEvent *e = &ev->xfocus;
3485 if(e->mode == NotifyGrab)
3488 if(ev->type == FocusIn) {
3489 XSetICFocus(xw.xic);
3490 xw.state |= WIN_FOCUSED;
3492 if(IS_SET(MODE_FOCUS))
3493 ttywrite("\033[I", 3);
3495 XUnsetICFocus(xw.xic);
3496 xw.state &= ~WIN_FOCUSED;
3497 if(IS_SET(MODE_FOCUS))
3498 ttywrite("\033[O", 3);
3503 match(uint mask, uint state) {
3504 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3508 numlock(const Arg *dummy) {
3513 kmap(KeySym k, uint state) {
3517 /* Check for mapped keys out of X11 function keys. */
3518 for(i = 0; i < LEN(mappedkeys); i++) {
3519 if(mappedkeys[i] == k)
3522 if(i == LEN(mappedkeys)) {
3523 if((k & 0xFFFF) < 0xFD00)
3527 for(kp = key; kp < key + LEN(key); kp++) {
3531 if(!match(kp->mask, state))
3534 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3536 if(term.numlock && kp->appkey == 2)
3539 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3542 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3552 kpress(XEvent *ev) {
3553 XKeyEvent *e = &ev->xkey;
3555 char buf[32], *customkey;
3561 if(IS_SET(MODE_KBDLOCK))
3564 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3566 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3567 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3568 bp->func(&(bp->arg));
3573 /* 2. custom keys from config.h */
3574 if((customkey = kmap(ksym, e->state))) {
3575 ttysend(customkey, strlen(customkey));
3579 /* 3. composed string from input method */
3582 if(len == 1 && e->state & Mod1Mask) {
3583 if(IS_SET(MODE_8BIT)) {
3586 len = utf8encode(&c, buf);
3599 cmessage(XEvent *e) {
3602 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3604 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3605 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3606 xw.state |= WIN_FOCUSED;
3608 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3609 xw.state &= ~WIN_FOCUSED;
3611 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3612 /* Send SIGHUP to shell */
3619 cresize(int width, int height) {
3627 col = (xw.w - 2 * borderpx) / xw.cw;
3628 row = (xw.h - 2 * borderpx) / xw.ch;
3637 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3640 cresize(e->xconfigure.width, e->xconfigure.height);
3646 int w = xw.w, h = xw.h;
3648 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3649 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3651 /* Waiting for window mapping */
3653 XNextEvent(xw.dpy, &ev);
3654 if(ev.type == ConfigureNotify) {
3655 w = ev.xconfigure.width;
3656 h = ev.xconfigure.height;
3657 } else if(ev.type == MapNotify) {
3665 cresize(xw.fw, xw.fh);
3668 gettimeofday(&lastblink, NULL);
3669 gettimeofday(&last, NULL);
3671 for(xev = actionfps;;) {
3675 FD_SET(cmdfd, &rfd);
3678 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3681 die("select failed: %s\n", SERRNO);
3683 if(FD_ISSET(cmdfd, &rfd)) {
3686 blinkset = tattrset(ATTR_BLINK);
3688 MODBIT(term.mode, 0, MODE_BLINK);
3692 if(FD_ISSET(xfd, &rfd))
3695 gettimeofday(&now, NULL);
3696 drawtimeout.tv_sec = 0;
3697 drawtimeout.tv_usec = (1000/xfps) * 1000;
3701 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3702 tsetdirtattr(ATTR_BLINK);
3703 term.mode ^= MODE_BLINK;
3704 gettimeofday(&lastblink, NULL);
3707 deltatime = TIMEDIFF(now, last);
3708 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3715 while(XPending(xw.dpy)) {
3716 XNextEvent(xw.dpy, &ev);
3717 if(XFilterEvent(&ev, None))
3719 if(handler[ev.type])
3720 (handler[ev.type])(&ev);
3726 if(xev && !FD_ISSET(xfd, &rfd))
3728 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3730 if(TIMEDIFF(now, lastblink) \
3732 drawtimeout.tv_usec = 1;
3734 drawtimeout.tv_usec = (1000 * \
3749 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3750 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3751 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3755 main(int argc, char *argv[]) {
3760 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3765 allowaltscreen = false;
3768 opt_class = EARGF(usage());
3771 /* eat all remaining arguments */
3774 if(argv[1] != NULL && opt_title == NULL) {
3775 titles = strdup(argv[1]);
3776 opt_title = basename(titles);
3781 opt_font = EARGF(usage());
3784 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3789 if(bitm & WidthValue)
3791 if(bitm & HeightValue)
3793 if(bitm & XNegative && xw.fx == 0)
3795 if(bitm & YNegative && xw.fy == 0)
3798 if(xw.fh != 0 && xw.fw != 0)
3802 opt_io = EARGF(usage());
3805 opt_title = EARGF(usage());
3808 opt_embed = EARGF(usage());
3816 setlocale(LC_CTYPE, "");
3817 XSetLocaleModifiers("");