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>
37 #define Draw XftDraw *
38 #define Colour XftColor
39 #define Colourmap Colormap
40 #define Rectangle XRectangle
44 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
46 #elif defined(__FreeBSD__) || defined(__DragonFly__)
52 #define XEMBED_FOCUS_IN 4
53 #define XEMBED_FOCUS_OUT 5
57 #define ESC_BUF_SIZ (128*UTF_SIZ)
58 #define ESC_ARG_SIZ 16
59 #define STR_BUF_SIZ ESC_BUF_SIZ
60 #define STR_ARG_SIZ ESC_ARG_SIZ
61 #define DRAW_BUF_SIZ 20*1024
62 #define XK_ANY_MOD UINT_MAX
64 #define XK_SWITCH_MOD (1<<13)
66 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
69 #define SERRNO strerror(errno)
70 #define MIN(a, b) ((a) < (b) ? (a) : (b))
71 #define MAX(a, b) ((a) < (b) ? (b) : (a))
72 #define LEN(a) (sizeof(a) / sizeof(a[0]))
73 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
74 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
75 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
76 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
77 #define IS_SET(flag) ((term.mode & (flag)) != 0)
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
79 #define CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
81 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
82 #define IS_TRUECOL(x) (1 << 24 & (x))
83 #define TRUERED(x) (((x) & 0xff0000) >> 8)
84 #define TRUEGREEN(x) (((x) & 0xff00))
85 #define TRUEBLUE(x) (((x) & 0xff) << 8)
88 #define VT102ID "\033[?6c"
90 enum glyph_attribute {
101 enum cursor_movement {
119 MODE_MOUSEMOTION = 64,
124 MODE_APPCURSOR = 2048,
125 MODE_MOUSESGR = 4096,
130 MODE_MOUSEX10 = 131072,
131 MODE_MOUSEMANY = 262144,
132 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
139 ESC_STR = 4, /* DSC, OSC, PM, APC */
141 ESC_STR_END = 16, /* a final string was encountered */
142 ESC_TEST = 32, /* Enter in test mode */
151 enum selection_type {
156 enum selection_snap {
161 typedef unsigned char uchar;
162 typedef unsigned int uint;
163 typedef unsigned long ulong;
164 typedef unsigned short ushort;
167 char c[UTF_SIZ]; /* character code */
168 uchar mode; /* attribute flags */
169 ulong fg; /* foreground */
170 ulong bg; /* background */
176 Glyph attr; /* current char attributes */
182 /* CSI Escape sequence structs */
183 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
185 char buf[ESC_BUF_SIZ]; /* raw string */
186 int len; /* raw string length */
188 int arg[ESC_ARG_SIZ];
189 int narg; /* nb of args */
193 /* STR Escape sequence structs */
194 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
196 char type; /* ESC type ... */
197 char buf[STR_BUF_SIZ]; /* raw string */
198 int len; /* raw string length */
199 char *args[STR_ARG_SIZ];
200 int narg; /* nb of args */
203 /* Internal representation of the screen */
205 int row; /* nb row */
206 int col; /* nb col */
207 Line *line; /* screen */
208 Line *alt; /* alternate screen */
209 bool *dirty; /* dirtyness of lines */
210 TCursor c; /* cursor */
211 int top; /* top scroll limit */
212 int bot; /* bottom scroll limit */
213 int mode; /* terminal mode flags */
214 int esc; /* escape state flags */
215 bool numlock; /* lock numbers in keyboard */
219 /* Purely graphic info */
225 Atom xembed, wmdeletewin;
230 XSetWindowAttributes attrs;
232 bool isfixed; /* is fixed geometry? */
233 int fx, fy, fw, fh; /* fixed geometry */
234 int tw, th; /* tty width and height */
235 int w, h; /* window width and height */
236 int ch; /* char height */
237 int cw; /* char width */
238 char state; /* focus, redraw, visible */
251 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
252 signed char appkey; /* application keypad */
253 signed char appcursor; /* application cursor */
254 signed char crlf; /* crlf mode */
262 * Selection variables:
263 * nb – normalized coordinates of the beginning of the selection
264 * ne – normalized coordinates of the end of the selection
265 * ob – original coordinates of the beginning of the selection
266 * oe – original coordinates of the end of the selection
275 struct timeval tclick1;
276 struct timeval tclick2;
289 void (*func)(const Arg *);
293 /* function definitions used in config.h */
294 static void clippaste(const Arg *);
295 static void numlock(const Arg *);
296 static void selpaste(const Arg *);
297 static void xzoom(const Arg *);
299 /* Config.h for applying patches and the configuration. */
315 /* Drawing Context */
317 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
318 Font font, bfont, ifont, ibfont;
322 static void die(const char *, ...);
323 static void draw(void);
324 static void redraw(int);
325 static void drawregion(int, int, int, int);
326 static void execsh(void);
327 static void sigchld(int);
328 static void run(void);
330 static void csidump(void);
331 static void csihandle(void);
332 static void csiparse(void);
333 static void csireset(void);
334 static void strdump(void);
335 static void strhandle(void);
336 static void strparse(void);
337 static void strreset(void);
339 static int tattrset(int);
340 static void tclearregion(int, int, int, int);
341 static void tcursor(int);
342 static void tdeletechar(int);
343 static void tdeleteline(int);
344 static void tinsertblank(int);
345 static void tinsertblankline(int);
346 static void tmoveto(int, int);
347 static void tmoveato(int x, int y);
348 static void tnew(int, int);
349 static void tnewline(int);
350 static void tputtab(bool);
351 static void tputc(char *, int);
352 static void treset(void);
353 static int tresize(int, int);
354 static void tscrollup(int, int);
355 static void tscrolldown(int, int);
356 static void tsetattr(int*, int);
357 static void tsetchar(char *, Glyph *, int, int);
358 static void tsetscroll(int, int);
359 static void tswapscreen(void);
360 static void tsetdirt(int, int);
361 static void tsetdirtattr(int);
362 static void tsetmode(bool, bool, int *, int);
363 static void tfulldirt(void);
364 static void techo(char *, int);
365 static long tdefcolor(int *, int *, int);
366 static inline bool match(uint, uint);
367 static void ttynew(void);
368 static void ttyread(void);
369 static void ttyresize(void);
370 static void ttywrite(const char *, size_t);
372 static void xdraws(char *, Glyph, int, int, int, int);
373 static void xhints(void);
374 static void xclear(int, int, int, int);
375 static void xdrawcursor(void);
376 static void xinit(void);
377 static void xloadcols(void);
378 static int xsetcolorname(int, const char *);
379 static int xloadfont(Font *, FcPattern *);
380 static void xloadfonts(char *, int);
381 static int xloadfontset(Font *);
382 static void xsettitle(char *);
383 static void xresettitle(void);
384 static void xsetpointermotion(int);
385 static void xseturgency(int);
386 static void xsetsel(char*);
387 static void xtermclear(int, int, int, int);
388 static void xunloadfont(Font *f);
389 static void xunloadfonts(void);
390 static void xresize(int, int);
392 static void expose(XEvent *);
393 static void visibility(XEvent *);
394 static void unmap(XEvent *);
395 static char *kmap(KeySym, uint);
396 static void kpress(XEvent *);
397 static void cmessage(XEvent *);
398 static void cresize(int, int);
399 static void resize(XEvent *);
400 static void focus(XEvent *);
401 static void brelease(XEvent *);
402 static void bpress(XEvent *);
403 static void bmotion(XEvent *);
404 static void selnotify(XEvent *);
405 static void selclear(XEvent *);
406 static void selrequest(XEvent *);
408 static void selinit(void);
409 static void selsort(void);
410 static inline bool selected(int, int);
411 static void selcopy(void);
412 static void selscroll(int, int);
413 static void selsnap(int, int *, int *, int);
415 static int utf8decode(char *, long *);
416 static int utf8encode(long *, char *);
417 static int utf8size(char *);
418 static int isfullutf8(char *, int);
420 static ssize_t xwrite(int, char *, size_t);
421 static void *xmalloc(size_t);
422 static void *xrealloc(void *, size_t);
423 static void *xcalloc(size_t, size_t);
425 static void (*handler[LASTEvent])(XEvent *) = {
427 [ClientMessage] = cmessage,
428 [ConfigureNotify] = resize,
429 [VisibilityNotify] = visibility,
430 [UnmapNotify] = unmap,
434 [MotionNotify] = bmotion,
435 [ButtonPress] = bpress,
436 [ButtonRelease] = brelease,
437 [SelectionClear] = selclear,
438 [SelectionNotify] = selnotify,
439 [SelectionRequest] = selrequest,
446 static CSIEscape csiescseq;
447 static STREscape strescseq;
450 static Selection sel;
451 static int iofd = -1;
452 static char **opt_cmd = NULL;
453 static char *opt_io = NULL;
454 static char *opt_title = NULL;
455 static char *opt_embed = NULL;
456 static char *opt_class = NULL;
457 static char *opt_font = NULL;
458 static int oldbutton = 3; /* button event on startup: 3 = release */
460 static char *usedfont = NULL;
461 static int usedfontsize = 0;
463 /* Font Ring Cache */
476 /* Fontcache is an array now. A new font will be appended to the array. */
477 static Fontcache frc[16];
478 static int frclen = 0;
481 xwrite(int fd, char *s, size_t len) {
485 ssize_t r = write(fd, s, len);
495 xmalloc(size_t len) {
496 void *p = malloc(len);
499 die("Out of memory\n");
505 xrealloc(void *p, size_t len) {
506 if((p = realloc(p, len)) == NULL)
507 die("Out of memory\n");
513 xcalloc(size_t nmemb, size_t size) {
514 void *p = calloc(nmemb, size);
517 die("Out of memory\n");
523 utf8decode(char *s, long *u) {
529 if(~c & 0x80) { /* 0xxxxxxx */
532 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
535 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
538 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
545 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
547 if((c & 0xC0) != 0x80) /* 10xxxxxx */
553 if((n == 1 && *u < 0x80) ||
554 (n == 2 && *u < 0x800) ||
555 (n == 3 && *u < 0x10000) ||
556 (*u >= 0xD800 && *u <= 0xDFFF)) {
568 utf8encode(long *u, char *s) {
576 *sp = uc; /* 0xxxxxxx */
578 } else if(*u < 0x800) {
579 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
581 } else if(uc < 0x10000) {
582 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
584 } else if(uc <= 0x10FFFF) {
585 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
591 for(i=n,++sp; i>0; --i,++sp)
592 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
604 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
605 UTF-8 otherwise return 0 */
607 isfullutf8(char *s, int b) {
615 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
617 } else if((*c1 & 0xF0) == 0xE0 &&
619 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
621 } else if((*c1 & 0xF8) == 0xF0 &&
623 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
624 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
637 } else if((c & 0xE0) == 0xC0) {
639 } else if((c & 0xF0) == 0xE0) {
648 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
649 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
653 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
654 if(sel.xtarget == None)
655 sel.xtarget = XA_STRING;
663 return LIMIT(x, 0, term.col-1);
671 return LIMIT(y, 0, term.row-1);
676 if(sel.ob.y == sel.oe.y) {
677 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
678 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
680 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
681 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
683 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
684 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
688 selected(int x, int y) {
689 if(sel.ne.y == y && sel.nb.y == y)
690 return BETWEEN(x, sel.nb.x, sel.ne.x);
692 if(sel.type == SEL_RECTANGULAR) {
693 return ((sel.nb.y <= y && y <= sel.ne.y)
694 && (sel.nb.x <= x && x <= sel.ne.x));
697 return ((sel.nb.y < y && y < sel.ne.y)
698 || (y == sel.ne.y && x <= sel.ne.x))
699 || (y == sel.nb.y && x >= sel.nb.x
700 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
704 selsnap(int mode, int *x, int *y, int direction) {
710 * Snap around if the word wraps around at the end or
711 * beginning of a line.
714 if(direction < 0 && *x <= 0) {
715 if(*y > 0 && term.line[*y - 1][term.col-1].mode
723 if(direction > 0 && *x >= term.col-1) {
724 if(*y < term.row-1 && term.line[*y][*x].mode
733 if(strchr(worddelimiters,
734 term.line[*y][*x + direction].c[0])) {
743 * Snap around if the the previous line or the current one
744 * has set ATTR_WRAP at its end. Then the whole next or
745 * previous line will be selected.
747 *x = (direction < 0) ? 0 : term.col - 1;
748 if(direction < 0 && *y > 0) {
749 for(; *y > 0; *y += direction) {
750 if(!(term.line[*y-1][term.col-1].mode
755 } else if(direction > 0 && *y < term.row-1) {
756 for(; *y < term.row; *y += direction) {
757 if(!(term.line[*y][term.col-1].mode
766 * Select the whole line when the end of line is reached.
770 while(--i > 0 && term.line[*y][i].c[0] == ' ')
780 getbuttoninfo(XEvent *e) {
782 uint state = e->xbutton.state &~Button1Mask;
784 sel.alt = IS_SET(MODE_ALTSCREEN);
786 sel.oe.x = x2col(e->xbutton.x);
787 sel.oe.y = y2row(e->xbutton.y);
789 if(sel.ob.y < sel.oe.y
790 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
791 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
792 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
794 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
795 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
799 sel.type = SEL_REGULAR;
800 for(type = 1; type < LEN(selmasks); ++type) {
801 if(match(selmasks[type], state)) {
809 mousereport(XEvent *e) {
810 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
811 button = e->xbutton.button, state = e->xbutton.state,
817 if(e->xbutton.type == MotionNotify) {
818 if(x == ox && y == oy)
820 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
822 /* MOUSE_MOTION: no reporting if no button is pressed */
823 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
826 button = oldbutton + 32;
829 } else if(!IS_SET(MODE_MOUSESGR)
830 && (e->xbutton.type == ButtonRelease
831 || button == AnyButton)) {
837 if(e->xbutton.type == ButtonPress) {
844 if(!IS_SET(MODE_MOUSEX10)) {
845 button += (state & ShiftMask ? 4 : 0)
846 + (state & Mod4Mask ? 8 : 0)
847 + (state & ControlMask ? 16 : 0);
851 if(IS_SET(MODE_MOUSESGR)) {
852 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
854 e->xbutton.type == ButtonRelease ? 'm' : 'M');
855 } else if(x < 223 && y < 223) {
856 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
857 IS_SET(MODE_MOUSEX10)? button-1 : 32+button,
871 if(IS_SET(MODE_MOUSE)) {
876 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
877 if(e->xbutton.button == mk->b
878 && match(mk->mask, e->xbutton.state)) {
879 ttywrite(mk->s, strlen(mk->s));
880 if(IS_SET(MODE_ECHO))
881 techo(mk->s, strlen(mk->s));
886 if(e->xbutton.button == Button1) {
887 gettimeofday(&now, NULL);
889 /* Clear previous selection, logically and visually. */
892 sel.type = SEL_REGULAR;
893 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
894 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
897 * If the user clicks below predefined timeouts specific
898 * snapping behaviour is exposed.
900 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
901 sel.snap = SNAP_LINE;
902 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
903 sel.snap = SNAP_WORD;
907 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
908 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
912 * Draw selection, unless it's regular and we don't want to
913 * make clicks visible
917 tsetdirt(sel.nb.y, sel.ne.y);
919 sel.tclick2 = sel.tclick1;
927 int x, y, bufsize, size, i, ex;
933 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
934 ptr = str = xmalloc(bufsize);
936 /* append every set & selected glyph to the selection */
937 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
938 gp = &term.line[y][0];
939 last = gp + term.col;
941 while(--last >= gp && !(selected(last - gp, y) && \
942 strcmp(last->c, " ") != 0))
945 for(x = 0; gp <= last; x++, ++gp) {
949 size = utf8size(gp->c);
950 memcpy(ptr, gp->c, size);
955 * Copy and pasting of line endings is inconsistent
956 * in the inconsistent terminal and GUI world.
957 * The best solution seems like to produce '\n' when
958 * something is copied from st and convert '\n' to
959 * '\r', when something to be pasted is received by
961 * FIXME: Fix the computer world.
963 if(y < sel.ne.y && !((gp-1)->mode & ATTR_WRAP))
967 * If the last selected line expands in the selection
968 * after the visible text '\n' is appended.
972 while(--i > 0 && term.line[y][i].c[0] == ' ')
975 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
987 selnotify(XEvent *e) {
988 ulong nitems, ofs, rem;
990 uchar *data, *last, *repl;
995 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
996 False, AnyPropertyType, &type, &format,
997 &nitems, &rem, &data)) {
998 fprintf(stderr, "Clipboard allocation failed\n");
1003 * As seen in selcopy:
1004 * Line endings are inconsistent in the terminal and GUI world
1005 * copy and pasting. When receiving some selection data,
1006 * replace all '\n' with '\r'.
1007 * FIXME: Fix the computer world.
1010 last = data + nitems * format / 8;
1011 while((repl = memchr(repl, '\n', last - repl))) {
1015 ttywrite((const char *)data, nitems * format / 8);
1017 /* number of 32-bit chunks returned */
1018 ofs += nitems * format / 32;
1023 selpaste(const Arg *dummy) {
1024 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1025 xw.win, CurrentTime);
1029 clippaste(const Arg *dummy) {
1032 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1033 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1034 xw.win, CurrentTime);
1038 selclear(XEvent *e) {
1042 tsetdirt(sel.nb.y, sel.ne.y);
1046 selrequest(XEvent *e) {
1047 XSelectionRequestEvent *xsre;
1048 XSelectionEvent xev;
1049 Atom xa_targets, string;
1051 xsre = (XSelectionRequestEvent *) e;
1052 xev.type = SelectionNotify;
1053 xev.requestor = xsre->requestor;
1054 xev.selection = xsre->selection;
1055 xev.target = xsre->target;
1056 xev.time = xsre->time;
1058 xev.property = None;
1060 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1061 if(xsre->target == xa_targets) {
1062 /* respond with the supported type */
1063 string = sel.xtarget;
1064 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1065 XA_ATOM, 32, PropModeReplace,
1066 (uchar *) &string, 1);
1067 xev.property = xsre->property;
1068 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1069 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1070 xsre->target, 8, PropModeReplace,
1071 (uchar *) sel.clip, strlen(sel.clip));
1072 xev.property = xsre->property;
1075 /* all done, send a notification to the listener */
1076 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1077 fprintf(stderr, "Error sending SelectionNotify event\n");
1081 xsetsel(char *str) {
1082 /* register the selection for both the clipboard and the primary */
1088 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1090 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1091 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1095 brelease(XEvent *e) {
1096 if(IS_SET(MODE_MOUSE)) {
1101 if(e->xbutton.button == Button2) {
1103 } else if(e->xbutton.button == Button1) {
1111 tsetdirt(sel.nb.y, sel.ne.y);
1116 bmotion(XEvent *e) {
1117 int oldey, oldex, oldsby, oldsey;
1119 if(IS_SET(MODE_MOUSE)) {
1134 if(oldey != sel.oe.y || oldex != sel.oe.x)
1135 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1139 die(const char *errstr, ...) {
1142 va_start(ap, errstr);
1143 vfprintf(stderr, errstr, ap);
1151 char *envshell = getenv("SHELL");
1152 const struct passwd *pass = getpwuid(getuid());
1153 char buf[sizeof(long) * 8 + 1];
1155 unsetenv("COLUMNS");
1157 unsetenv("TERMCAP");
1160 setenv("LOGNAME", pass->pw_name, 1);
1161 setenv("USER", pass->pw_name, 1);
1162 setenv("SHELL", pass->pw_shell, 0);
1163 setenv("HOME", pass->pw_dir, 0);
1166 snprintf(buf, sizeof(buf), "%lu", xw.win);
1167 setenv("WINDOWID", buf, 1);
1169 signal(SIGCHLD, SIG_DFL);
1170 signal(SIGHUP, SIG_DFL);
1171 signal(SIGINT, SIG_DFL);
1172 signal(SIGQUIT, SIG_DFL);
1173 signal(SIGTERM, SIG_DFL);
1174 signal(SIGALRM, SIG_DFL);
1176 DEFAULT(envshell, shell);
1177 setenv("TERM", termname, 1);
1178 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1179 execvp(args[0], args);
1187 if(waitpid(pid, &stat, 0) < 0)
1188 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1190 if(WIFEXITED(stat)) {
1191 exit(WEXITSTATUS(stat));
1200 struct winsize w = {term.row, term.col, 0, 0};
1202 /* seems to work fine on linux, openbsd and freebsd */
1203 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1204 die("openpty failed: %s\n", SERRNO);
1206 switch(pid = fork()) {
1208 die("fork failed\n");
1211 setsid(); /* create a new process group */
1212 dup2(s, STDIN_FILENO);
1213 dup2(s, STDOUT_FILENO);
1214 dup2(s, STDERR_FILENO);
1215 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1216 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1224 signal(SIGCHLD, sigchld);
1226 iofd = (!strcmp(opt_io, "-")) ?
1228 open(opt_io, O_WRONLY | O_CREAT, 0666);
1230 fprintf(stderr, "Error opening %s:%s\n",
1231 opt_io, strerror(errno));
1241 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1243 fprintf(stderr, "\n");
1248 static char buf[BUFSIZ];
1249 static int buflen = 0;
1252 int charsize; /* size of utf8 char in bytes */
1256 /* append read bytes to unprocessed bytes */
1257 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1258 die("Couldn't read from shell: %s\n", SERRNO);
1260 /* process every complete utf8 char */
1263 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1264 charsize = utf8decode(ptr, &utf8c);
1265 utf8encode(&utf8c, s);
1271 /* keep any uncomplete utf8 char for the next call */
1272 memmove(buf, ptr, buflen);
1276 ttywrite(const char *s, size_t n) {
1277 if(write(cmdfd, s, n) == -1)
1278 die("write error on tty: %s\n", SERRNO);
1285 w.ws_row = term.row;
1286 w.ws_col = term.col;
1287 w.ws_xpixel = xw.tw;
1288 w.ws_ypixel = xw.th;
1289 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1290 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1294 tattrset(int attr) {
1297 for(i = 0; i < term.row-1; i++) {
1298 for(j = 0; j < term.col-1; j++) {
1299 if(term.line[i][j].mode & attr)
1308 tsetdirt(int top, int bot) {
1311 LIMIT(top, 0, term.row-1);
1312 LIMIT(bot, 0, term.row-1);
1314 for(i = top; i <= bot; i++)
1319 tsetdirtattr(int attr) {
1322 for(i = 0; i < term.row-1; i++) {
1323 for(j = 0; j < term.col-1; j++) {
1324 if(term.line[i][j].mode & attr) {
1334 tsetdirt(0, term.row-1);
1341 if(mode == CURSOR_SAVE) {
1343 } else if(mode == CURSOR_LOAD) {
1353 term.c = (TCursor){{
1357 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1359 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1360 for(i = tabspaces; i < term.col; i += tabspaces)
1363 term.bot = term.row - 1;
1364 term.mode = MODE_WRAP;
1366 tclearregion(0, 0, term.col-1, term.row-1);
1368 tcursor(CURSOR_SAVE);
1372 tnew(int col, int row) {
1373 memset(&term, 0, sizeof(Term));
1382 Line *tmp = term.line;
1384 term.line = term.alt;
1386 term.mode ^= MODE_ALTSCREEN;
1391 tscrolldown(int orig, int n) {
1395 LIMIT(n, 0, term.bot-orig+1);
1397 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1399 for(i = term.bot; i >= orig+n; i--) {
1400 temp = term.line[i];
1401 term.line[i] = term.line[i-n];
1402 term.line[i-n] = temp;
1405 term.dirty[i-n] = 1;
1412 tscrollup(int orig, int n) {
1415 LIMIT(n, 0, term.bot-orig+1);
1417 tclearregion(0, orig, term.col-1, orig+n-1);
1419 for(i = orig; i <= term.bot-n; i++) {
1420 temp = term.line[i];
1421 term.line[i] = term.line[i+n];
1422 term.line[i+n] = temp;
1425 term.dirty[i+n] = 1;
1428 selscroll(orig, -n);
1432 selscroll(int orig, int n) {
1436 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1437 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1441 if(sel.type == SEL_RECTANGULAR) {
1442 if(sel.ob.y < term.top)
1443 sel.ob.y = term.top;
1444 if(sel.oe.y > term.bot)
1445 sel.oe.y = term.bot;
1447 if(sel.ob.y < term.top) {
1448 sel.ob.y = term.top;
1451 if(sel.oe.y > term.bot) {
1452 sel.oe.y = term.bot;
1453 sel.oe.x = term.col;
1461 tnewline(int first_col) {
1465 tscrollup(term.top, 1);
1469 tmoveto(first_col ? 0 : term.c.x, y);
1474 char *p = csiescseq.buf, *np;
1483 csiescseq.buf[csiescseq.len] = '\0';
1484 while(p < csiescseq.buf+csiescseq.len) {
1486 v = strtol(p, &np, 10);
1489 if(v == LONG_MAX || v == LONG_MIN)
1491 csiescseq.arg[csiescseq.narg++] = v;
1493 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1497 csiescseq.mode = *p;
1500 /* for absolute user moves, when decom is set */
1502 tmoveato(int x, int y) {
1503 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1507 tmoveto(int x, int y) {
1510 if(term.c.state & CURSOR_ORIGIN) {
1515 maxy = term.row - 1;
1517 LIMIT(x, 0, term.col-1);
1518 LIMIT(y, miny, maxy);
1519 term.c.state &= ~CURSOR_WRAPNEXT;
1525 tsetchar(char *c, Glyph *attr, int x, int y) {
1526 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1527 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1528 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1529 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1530 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1531 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1532 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1533 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1534 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1538 * The table is proudly stolen from rxvt.
1540 if(attr->mode & ATTR_GFX) {
1541 if(c[0] >= 0x41 && c[0] <= 0x7e
1542 && vt100_0[c[0] - 0x41]) {
1543 c = vt100_0[c[0] - 0x41];
1548 term.line[y][x] = *attr;
1549 memcpy(term.line[y][x].c, c, UTF_SIZ);
1553 tclearregion(int x1, int y1, int x2, int y2) {
1557 temp = x1, x1 = x2, x2 = temp;
1559 temp = y1, y1 = y2, y2 = temp;
1561 LIMIT(x1, 0, term.col-1);
1562 LIMIT(x2, 0, term.col-1);
1563 LIMIT(y1, 0, term.row-1);
1564 LIMIT(y2, 0, term.row-1);
1566 for(y = y1; y <= y2; y++) {
1568 for(x = x1; x <= x2; x++) {
1571 term.line[y][x] = term.c.attr;
1572 memcpy(term.line[y][x].c, " ", 2);
1578 tdeletechar(int n) {
1579 int src = term.c.x + n;
1581 int size = term.col - src;
1583 term.dirty[term.c.y] = 1;
1585 if(src >= term.col) {
1586 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1590 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1591 size * sizeof(Glyph));
1592 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1596 tinsertblank(int n) {
1599 int size = term.col - dst;
1601 term.dirty[term.c.y] = 1;
1603 if(dst >= term.col) {
1604 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1608 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1609 size * sizeof(Glyph));
1610 tclearregion(src, term.c.y, dst - 1, term.c.y);
1614 tinsertblankline(int n) {
1615 if(term.c.y < term.top || term.c.y > term.bot)
1618 tscrolldown(term.c.y, n);
1622 tdeleteline(int n) {
1623 if(term.c.y < term.top || term.c.y > term.bot)
1626 tscrollup(term.c.y, n);
1630 tdefcolor(int *attr, int *npar, int l) {
1634 switch (attr[*npar + 1]) {
1635 case 2: /* direct colour in RGB space */
1636 if (*npar + 4 >= l) {
1638 "erresc(38): Incorrect number of parameters (%d)\n",
1642 r = attr[*npar + 2];
1643 g = attr[*npar + 3];
1644 b = attr[*npar + 4];
1646 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1647 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1650 idx = TRUECOLOR(r, g, b);
1652 case 5: /* indexed colour */
1653 if (*npar + 2 >= l) {
1655 "erresc(38): Incorrect number of parameters (%d)\n",
1660 if(!BETWEEN(attr[*npar], 0, 255))
1661 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1665 case 0: /* implemented defined (only foreground) */
1666 case 1: /* transparent */
1667 case 3: /* direct colour in CMY space */
1668 case 4: /* direct colour in CMYK space */
1671 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1678 tsetattr(int *attr, int l) {
1682 for(i = 0; i < l; i++) {
1685 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1686 | ATTR_BOLD | ATTR_ITALIC \
1688 term.c.attr.fg = defaultfg;
1689 term.c.attr.bg = defaultbg;
1692 term.c.attr.mode |= ATTR_BOLD;
1695 term.c.attr.mode |= ATTR_ITALIC;
1698 term.c.attr.mode |= ATTR_UNDERLINE;
1700 case 5: /* slow blink */
1701 case 6: /* rapid blink */
1702 term.c.attr.mode |= ATTR_BLINK;
1705 term.c.attr.mode |= ATTR_REVERSE;
1709 term.c.attr.mode &= ~ATTR_BOLD;
1712 term.c.attr.mode &= ~ATTR_ITALIC;
1715 term.c.attr.mode &= ~ATTR_UNDERLINE;
1719 term.c.attr.mode &= ~ATTR_BLINK;
1722 term.c.attr.mode &= ~ATTR_REVERSE;
1725 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1726 term.c.attr.fg = idx;
1729 term.c.attr.fg = defaultfg;
1732 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1733 term.c.attr.bg = idx;
1736 term.c.attr.bg = defaultbg;
1739 if(BETWEEN(attr[i], 30, 37)) {
1740 term.c.attr.fg = attr[i] - 30;
1741 } else if(BETWEEN(attr[i], 40, 47)) {
1742 term.c.attr.bg = attr[i] - 40;
1743 } else if(BETWEEN(attr[i], 90, 97)) {
1744 term.c.attr.fg = attr[i] - 90 + 8;
1745 } else if(BETWEEN(attr[i], 100, 107)) {
1746 term.c.attr.bg = attr[i] - 100 + 8;
1749 "erresc(default): gfx attr %d unknown\n",
1750 attr[i]), csidump();
1758 tsetscroll(int t, int b) {
1761 LIMIT(t, 0, term.row-1);
1762 LIMIT(b, 0, term.row-1);
1772 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1775 tsetmode(bool priv, bool set, int *args, int narg) {
1779 for(lim = args + narg; args < lim; ++args) {
1783 case 1: /* DECCKM -- Cursor key */
1784 MODBIT(term.mode, set, MODE_APPCURSOR);
1786 case 5: /* DECSCNM -- Reverse video */
1788 MODBIT(term.mode, set, MODE_REVERSE);
1789 if(mode != term.mode)
1790 redraw(REDRAW_TIMEOUT);
1792 case 6: /* DECOM -- Origin */
1793 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1796 case 7: /* DECAWM -- Auto wrap */
1797 MODBIT(term.mode, set, MODE_WRAP);
1799 case 0: /* Error (IGNORED) */
1800 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1801 case 3: /* DECCOLM -- Column (IGNORED) */
1802 case 4: /* DECSCLM -- Scroll (IGNORED) */
1803 case 8: /* DECARM -- Auto repeat (IGNORED) */
1804 case 18: /* DECPFF -- Printer feed (IGNORED) */
1805 case 19: /* DECPEX -- Printer extent (IGNORED) */
1806 case 42: /* DECNRCM -- National characters (IGNORED) */
1807 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1809 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1810 MODBIT(term.mode, !set, MODE_HIDE);
1812 case 9: /* X10 mouse compatibility mode */
1813 xsetpointermotion(0);
1814 MODBIT(term.mode, 0, MODE_MOUSE);
1815 MODBIT(term.mode, set, MODE_MOUSEX10);
1817 case 1000: /* 1000: report button press */
1818 xsetpointermotion(0);
1819 MODBIT(term.mode, 0, MODE_MOUSE);
1820 MODBIT(term.mode, set, MODE_MOUSEBTN);
1822 case 1002: /* 1002: report motion on button press */
1823 xsetpointermotion(0);
1824 MODBIT(term.mode, 0, MODE_MOUSE);
1825 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1827 case 1003: /* 1003: enable all mouse motions */
1828 xsetpointermotion(set);
1829 MODBIT(term.mode, 0, MODE_MOUSE);
1830 MODBIT(term.mode, set, MODE_MOUSEMANY);
1832 case 1004: /* 1004: send focus events to tty */
1833 MODBIT(term.mode, set, MODE_FOCUS);
1835 case 1006: /* 1006: extended reporting mode */
1836 MODBIT(term.mode, set, MODE_MOUSESGR);
1839 MODBIT(term.mode, set, MODE_8BIT);
1841 case 1049: /* = 1047 and 1048 */
1844 if (!allowaltscreen)
1847 alt = IS_SET(MODE_ALTSCREEN);
1849 tclearregion(0, 0, term.col-1,
1852 if(set ^ alt) /* set is always 1 or 0 */
1858 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1860 /* Not implemented mouse modes. See comments there. */
1861 case 1001: /* mouse highlight mode; can hang the
1862 terminal by design when implemented. */
1863 case 1005: /* UTF-8 mouse mode; will confuse
1864 applications not supporting UTF-8
1866 case 1015: /* urxvt mangled mouse mode; incompatible
1867 and can be mistaken for other control
1871 "erresc: unknown private set/reset mode %d\n",
1877 case 0: /* Error (IGNORED) */
1879 case 2: /* KAM -- keyboard action */
1880 MODBIT(term.mode, set, MODE_KBDLOCK);
1882 case 4: /* IRM -- Insertion-replacement */
1883 MODBIT(term.mode, set, MODE_INSERT);
1885 case 12: /* SRM -- Send/Receive */
1886 MODBIT(term.mode, !set, MODE_ECHO);
1888 case 20: /* LNM -- Linefeed/new line */
1889 MODBIT(term.mode, set, MODE_CRLF);
1893 "erresc: unknown set/reset mode %d\n",
1903 switch(csiescseq.mode) {
1906 fprintf(stderr, "erresc: unknown csi ");
1910 case '@': /* ICH -- Insert <n> blank char */
1911 DEFAULT(csiescseq.arg[0], 1);
1912 tinsertblank(csiescseq.arg[0]);
1914 case 'A': /* CUU -- Cursor <n> Up */
1915 DEFAULT(csiescseq.arg[0], 1);
1916 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1918 case 'B': /* CUD -- Cursor <n> Down */
1919 case 'e': /* VPR --Cursor <n> Down */
1920 DEFAULT(csiescseq.arg[0], 1);
1921 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1923 case 'c': /* DA -- Device Attributes */
1924 if(csiescseq.arg[0] == 0)
1925 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1927 case 'C': /* CUF -- Cursor <n> Forward */
1928 case 'a': /* HPR -- Cursor <n> Forward */
1929 DEFAULT(csiescseq.arg[0], 1);
1930 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1932 case 'D': /* CUB -- Cursor <n> Backward */
1933 DEFAULT(csiescseq.arg[0], 1);
1934 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1936 case 'E': /* CNL -- Cursor <n> Down and first col */
1937 DEFAULT(csiescseq.arg[0], 1);
1938 tmoveto(0, term.c.y+csiescseq.arg[0]);
1940 case 'F': /* CPL -- Cursor <n> Up and first col */
1941 DEFAULT(csiescseq.arg[0], 1);
1942 tmoveto(0, term.c.y-csiescseq.arg[0]);
1944 case 'g': /* TBC -- Tabulation clear */
1945 switch(csiescseq.arg[0]) {
1946 case 0: /* clear current tab stop */
1947 term.tabs[term.c.x] = 0;
1949 case 3: /* clear all the tabs */
1950 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1956 case 'G': /* CHA -- Move to <col> */
1958 DEFAULT(csiescseq.arg[0], 1);
1959 tmoveto(csiescseq.arg[0]-1, term.c.y);
1961 case 'H': /* CUP -- Move to <row> <col> */
1963 DEFAULT(csiescseq.arg[0], 1);
1964 DEFAULT(csiescseq.arg[1], 1);
1965 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1967 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1968 DEFAULT(csiescseq.arg[0], 1);
1969 while(csiescseq.arg[0]--)
1972 case 'J': /* ED -- Clear screen */
1974 switch(csiescseq.arg[0]) {
1976 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1977 if(term.c.y < term.row-1) {
1978 tclearregion(0, term.c.y+1, term.col-1,
1984 tclearregion(0, 0, term.col-1, term.c.y-1);
1985 tclearregion(0, term.c.y, term.c.x, term.c.y);
1988 tclearregion(0, 0, term.col-1, term.row-1);
1994 case 'K': /* EL -- Clear line */
1995 switch(csiescseq.arg[0]) {
1997 tclearregion(term.c.x, term.c.y, term.col-1,
2001 tclearregion(0, term.c.y, term.c.x, term.c.y);
2004 tclearregion(0, term.c.y, term.col-1, term.c.y);
2008 case 'S': /* SU -- Scroll <n> line up */
2009 DEFAULT(csiescseq.arg[0], 1);
2010 tscrollup(term.top, csiescseq.arg[0]);
2012 case 'T': /* SD -- Scroll <n> line down */
2013 DEFAULT(csiescseq.arg[0], 1);
2014 tscrolldown(term.top, csiescseq.arg[0]);
2016 case 'L': /* IL -- Insert <n> blank lines */
2017 DEFAULT(csiescseq.arg[0], 1);
2018 tinsertblankline(csiescseq.arg[0]);
2020 case 'l': /* RM -- Reset Mode */
2021 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2023 case 'M': /* DL -- Delete <n> lines */
2024 DEFAULT(csiescseq.arg[0], 1);
2025 tdeleteline(csiescseq.arg[0]);
2027 case 'X': /* ECH -- Erase <n> char */
2028 DEFAULT(csiescseq.arg[0], 1);
2029 tclearregion(term.c.x, term.c.y,
2030 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2032 case 'P': /* DCH -- Delete <n> char */
2033 DEFAULT(csiescseq.arg[0], 1);
2034 tdeletechar(csiescseq.arg[0]);
2036 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2037 DEFAULT(csiescseq.arg[0], 1);
2038 while(csiescseq.arg[0]--)
2041 case 'd': /* VPA -- Move to <row> */
2042 DEFAULT(csiescseq.arg[0], 1);
2043 tmoveato(term.c.x, csiescseq.arg[0]-1);
2045 case 'h': /* SM -- Set terminal mode */
2046 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2048 case 'm': /* SGR -- Terminal attribute (color) */
2049 tsetattr(csiescseq.arg, csiescseq.narg);
2051 case 'r': /* DECSTBM -- Set Scrolling Region */
2052 if(csiescseq.priv) {
2055 DEFAULT(csiescseq.arg[0], 1);
2056 DEFAULT(csiescseq.arg[1], term.row);
2057 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2061 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2062 tcursor(CURSOR_SAVE);
2064 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2065 tcursor(CURSOR_LOAD);
2076 for(i = 0; i < csiescseq.len; i++) {
2077 c = csiescseq.buf[i] & 0xff;
2080 } else if(c == '\n') {
2082 } else if(c == '\r') {
2084 } else if(c == 0x1b) {
2087 printf("(%02x)", c);
2095 memset(&csiescseq, 0, sizeof(csiescseq));
2104 narg = strescseq.narg;
2106 switch(strescseq.type) {
2107 case ']': /* OSC -- Operating System Command */
2108 switch(i = atoi(strescseq.args[0])) {
2113 xsettitle(strescseq.args[1]);
2115 case 4: /* color set */
2118 p = strescseq.args[2];
2120 case 104: /* color reset, here p = NULL */
2121 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2122 if (!xsetcolorname(j, p)) {
2123 fprintf(stderr, "erresc: invalid color %s\n", p);
2126 * TODO if defaultbg color is changed, borders
2133 fprintf(stderr, "erresc: unknown str ");
2138 case 'k': /* old title set compatibility */
2139 xsettitle(strescseq.args[0]);
2141 case 'P': /* DSC -- Device Control String */
2142 case '_': /* APC -- Application Program Command */
2143 case '^': /* PM -- Privacy Message */
2145 fprintf(stderr, "erresc: unknown str ");
2154 char *p = strescseq.buf;
2157 strescseq.buf[strescseq.len] = '\0';
2158 while(p && strescseq.narg < STR_ARG_SIZ)
2159 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2167 printf("ESC%c", strescseq.type);
2168 for(i = 0; i < strescseq.len; i++) {
2169 c = strescseq.buf[i] & 0xff;
2172 } else if(isprint(c)) {
2174 } else if(c == '\n') {
2176 } else if(c == '\r') {
2178 } else if(c == 0x1b) {
2181 printf("(%02x)", c);
2189 memset(&strescseq, 0, sizeof(strescseq));
2193 tputtab(bool forward) {
2199 for(++x; x < term.col && !term.tabs[x]; ++x)
2204 for(--x; x > 0 && !term.tabs[x]; --x)
2207 tmoveto(x, term.c.y);
2211 techo(char *buf, int len) {
2212 for(; len > 0; buf++, len--) {
2215 if(c == '\033') { /* escape */
2218 } else if(c < '\x20') { /* control code */
2219 if(c != '\n' && c != '\r' && c != '\t') {
2233 tputc(char *c, int len) {
2235 bool control = ascii < '\x20' || ascii == 0177;
2238 if(xwrite(iofd, c, len) < 0) {
2239 fprintf(stderr, "Error writing in %s:%s\n",
2240 opt_io, strerror(errno));
2247 * STR sequences must be checked before anything else
2248 * because it can use some control codes as part of the sequence.
2250 if(term.esc & ESC_STR) {
2253 term.esc = ESC_START | ESC_STR_END;
2255 case '\a': /* backwards compatibility to xterm */
2260 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2261 memmove(&strescseq.buf[strescseq.len], c, len);
2262 strescseq.len += len;
2265 * Here is a bug in terminals. If the user never sends
2266 * some code to stop the str or esc command, then st
2267 * will stop responding. But this is better than
2268 * silently failing with unknown characters. At least
2269 * then users will report back.
2271 * In the case users ever get fixed, here is the code:
2283 * Actions of control codes must be performed as soon they arrive
2284 * because they can be embedded inside a control sequence, and
2285 * they must not cause conflicts with sequences.
2293 tmoveto(term.c.x-1, term.c.y);
2296 tmoveto(0, term.c.y);
2301 /* go to first col if the mode is set */
2302 tnewline(IS_SET(MODE_CRLF));
2304 case '\a': /* BEL */
2305 if(!(xw.state & WIN_FOCUSED))
2308 case '\033': /* ESC */
2310 term.esc = ESC_START;
2312 case '\016': /* SO */
2313 case '\017': /* SI */
2315 * Different charsets are hard to handle. Applications
2316 * should use the right alt charset escapes for the
2317 * only reason they still exist: line drawing. The
2318 * rest is incompatible history st should not support.
2321 case '\032': /* SUB */
2322 case '\030': /* CAN */
2325 case '\005': /* ENQ (IGNORED) */
2326 case '\000': /* NUL (IGNORED) */
2327 case '\021': /* XON (IGNORED) */
2328 case '\023': /* XOFF (IGNORED) */
2329 case 0177: /* DEL (IGNORED) */
2332 } else if(term.esc & ESC_START) {
2333 if(term.esc & ESC_CSI) {
2334 csiescseq.buf[csiescseq.len++] = ascii;
2335 if(BETWEEN(ascii, 0x40, 0x7E)
2336 || csiescseq.len >= \
2337 sizeof(csiescseq.buf)-1) {
2342 } else if(term.esc & ESC_STR_END) {
2346 } else if(term.esc & ESC_ALTCHARSET) {
2348 case '0': /* Line drawing set */
2349 term.c.attr.mode |= ATTR_GFX;
2351 case 'B': /* USASCII */
2352 term.c.attr.mode &= ~ATTR_GFX;
2354 case 'A': /* UK (IGNORED) */
2355 case '<': /* multinational charset (IGNORED) */
2356 case '5': /* Finnish (IGNORED) */
2357 case 'C': /* Finnish (IGNORED) */
2358 case 'K': /* German (IGNORED) */
2361 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2364 } else if(term.esc & ESC_TEST) {
2365 if(ascii == '8') { /* DEC screen alignment test. */
2366 char E[UTF_SIZ] = "E";
2369 for(x = 0; x < term.col; ++x) {
2370 for(y = 0; y < term.row; ++y)
2371 tsetchar(E, &term.c.attr, x, y);
2378 term.esc |= ESC_CSI;
2381 term.esc |= ESC_TEST;
2383 case 'P': /* DCS -- Device Control String */
2384 case '_': /* APC -- Application Program Command */
2385 case '^': /* PM -- Privacy Message */
2386 case ']': /* OSC -- Operating System Command */
2387 case 'k': /* old title set compatibility */
2389 strescseq.type = ascii;
2390 term.esc |= ESC_STR;
2392 case '(': /* set primary charset G0 */
2393 term.esc |= ESC_ALTCHARSET;
2395 case ')': /* set secondary charset G1 (IGNORED) */
2396 case '*': /* set tertiary charset G2 (IGNORED) */
2397 case '+': /* set quaternary charset G3 (IGNORED) */
2400 case 'D': /* IND -- Linefeed */
2401 if(term.c.y == term.bot) {
2402 tscrollup(term.top, 1);
2404 tmoveto(term.c.x, term.c.y+1);
2408 case 'E': /* NEL -- Next line */
2409 tnewline(1); /* always go to first col */
2412 case 'H': /* HTS -- Horizontal tab stop */
2413 term.tabs[term.c.x] = 1;
2416 case 'M': /* RI -- Reverse index */
2417 if(term.c.y == term.top) {
2418 tscrolldown(term.top, 1);
2420 tmoveto(term.c.x, term.c.y-1);
2424 case 'Z': /* DECID -- Identify Terminal */
2425 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2428 case 'c': /* RIS -- Reset to inital state */
2434 case '=': /* DECPAM -- Application keypad */
2435 term.mode |= MODE_APPKEYPAD;
2438 case '>': /* DECPNM -- Normal keypad */
2439 term.mode &= ~MODE_APPKEYPAD;
2442 case '7': /* DECSC -- Save Cursor */
2443 tcursor(CURSOR_SAVE);
2446 case '8': /* DECRC -- Restore Cursor */
2447 tcursor(CURSOR_LOAD);
2450 case '\\': /* ST -- Stop */
2454 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2455 (uchar) ascii, isprint(ascii)? ascii:'.');
2460 * All characters which form part of a sequence are not
2466 * Display control codes only if we are in graphic mode
2468 if(control && !(term.c.attr.mode & ATTR_GFX))
2470 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2472 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2473 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2477 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2478 memmove(&term.line[term.c.y][term.c.x+1],
2479 &term.line[term.c.y][term.c.x],
2480 (term.col - term.c.x - 1) * sizeof(Glyph));
2483 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2484 if(term.c.x+1 < term.col) {
2485 tmoveto(term.c.x+1, term.c.y);
2487 term.c.state |= CURSOR_WRAPNEXT;
2492 tresize(int col, int row) {
2494 int minrow = MIN(row, term.row);
2495 int mincol = MIN(col, term.col);
2496 int slide = term.c.y - row + 1;
2500 if(col < 1 || row < 1)
2503 /* free unneeded rows */
2507 * slide screen to keep cursor where we expect it -
2508 * tscrollup would work here, but we can optimize to
2509 * memmove because we're freeing the earlier lines
2511 for(/* i = 0 */; i < slide; i++) {
2515 memmove(term.line, term.line + slide, row * sizeof(Line));
2516 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2518 for(i += row; i < term.row; i++) {
2523 /* resize to new height */
2524 term.line = xrealloc(term.line, row * sizeof(Line));
2525 term.alt = xrealloc(term.alt, row * sizeof(Line));
2526 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2527 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2529 /* resize each row to new width, zero-pad if needed */
2530 for(i = 0; i < minrow; i++) {
2532 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2533 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2536 /* allocate any new rows */
2537 for(/* i == minrow */; i < row; i++) {
2539 term.line[i] = xcalloc(col, sizeof(Glyph));
2540 term.alt [i] = xcalloc(col, sizeof(Glyph));
2542 if(col > term.col) {
2543 bp = term.tabs + term.col;
2545 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2546 while(--bp > term.tabs && !*bp)
2548 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2551 /* update terminal size */
2554 /* reset scrolling region */
2555 tsetscroll(0, row-1);
2556 /* make use of the LIMIT in tmoveto */
2557 tmoveto(term.c.x, term.c.y);
2558 /* Clearing both screens */
2561 if(mincol < col && 0 < minrow) {
2562 tclearregion(mincol, 0, col - 1, minrow - 1);
2564 if(0 < col && minrow < row) {
2565 tclearregion(0, minrow, col - 1, row - 1);
2568 } while(orig != term.line);
2574 xresize(int col, int row) {
2575 xw.tw = MAX(1, col * xw.cw);
2576 xw.th = MAX(1, row * xw.ch);
2578 XFreePixmap(xw.dpy, xw.buf);
2579 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2580 DefaultDepth(xw.dpy, xw.scr));
2581 XftDrawChange(xw.draw, xw.buf);
2582 xclear(0, 0, xw.w, xw.h);
2585 static inline ushort
2586 sixd_to_16bit(int x) {
2587 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2593 XRenderColor color = { .alpha = 0xffff };
2598 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2599 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2602 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2603 for(i = 0; i < LEN(colorname); i++) {
2606 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2607 die("Could not allocate color '%s'\n", colorname[i]);
2611 /* load colors [16-255] ; same colors as xterm */
2612 for(i = 16, r = 0; r < 6; r++) {
2613 for(g = 0; g < 6; g++) {
2614 for(b = 0; b < 6; b++) {
2615 color.red = sixd_to_16bit(r);
2616 color.green = sixd_to_16bit(g);
2617 color.blue = sixd_to_16bit(b);
2618 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2619 die("Could not allocate color %d\n", i);
2626 for(r = 0; r < 24; r++, i++) {
2627 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2628 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2630 die("Could not allocate color %d\n", i);
2637 xsetcolorname(int x, const char *name) {
2638 XRenderColor color = { .alpha = 0xffff };
2640 if (x < 0 || x > LEN(colorname))
2643 if(16 <= x && x < 16 + 216) {
2644 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2645 color.red = sixd_to_16bit(r);
2646 color.green = sixd_to_16bit(g);
2647 color.blue = sixd_to_16bit(b);
2648 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2649 return 0; /* something went wrong */
2652 } else if (16 + 216 <= x && x < 256) {
2653 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2654 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2655 return 0; /* something went wrong */
2659 name = colorname[x];
2662 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2669 xtermclear(int col1, int row1, int col2, int row2) {
2670 XftDrawRect(xw.draw,
2671 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2672 borderpx + col1 * xw.cw,
2673 borderpx + row1 * xw.ch,
2674 (col2-col1+1) * xw.cw,
2675 (row2-row1+1) * xw.ch);
2679 * Absolute coordinates.
2682 xclear(int x1, int y1, int x2, int y2) {
2683 XftDrawRect(xw.draw,
2684 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2685 x1, y1, x2-x1, y2-y1);
2690 XClassHint class = {opt_class ? opt_class : termname, termname};
2691 XWMHints wm = {.flags = InputHint, .input = 1};
2692 XSizeHints *sizeh = NULL;
2694 sizeh = XAllocSizeHints();
2695 if(xw.isfixed == False) {
2696 sizeh->flags = PSize | PResizeInc | PBaseSize;
2697 sizeh->height = xw.h;
2698 sizeh->width = xw.w;
2699 sizeh->height_inc = xw.ch;
2700 sizeh->width_inc = xw.cw;
2701 sizeh->base_height = 2 * borderpx;
2702 sizeh->base_width = 2 * borderpx;
2704 sizeh->flags = PMaxSize | PMinSize;
2705 sizeh->min_width = sizeh->max_width = xw.fw;
2706 sizeh->min_height = sizeh->max_height = xw.fh;
2709 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2714 xloadfont(Font *f, FcPattern *pattern) {
2718 match = FcFontMatch(NULL, pattern, &result);
2722 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2723 FcPatternDestroy(match);
2728 f->pattern = FcPatternDuplicate(pattern);
2730 f->ascent = f->match->ascent;
2731 f->descent = f->match->descent;
2733 f->rbearing = f->match->max_advance_width;
2735 f->height = f->ascent + f->descent;
2736 f->width = f->lbearing + f->rbearing;
2742 xloadfonts(char *fontstr, int fontsize) {
2747 if(fontstr[0] == '-') {
2748 pattern = XftXlfdParse(fontstr, False, False);
2750 pattern = FcNameParse((FcChar8 *)fontstr);
2754 die("st: can't open font %s\n", fontstr);
2757 FcPatternDel(pattern, FC_PIXEL_SIZE);
2758 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2759 usedfontsize = fontsize;
2761 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2762 if(result == FcResultMatch) {
2763 usedfontsize = (int)fontval;
2766 * Default font size is 12, if none given. This is to
2767 * have a known usedfontsize value.
2769 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2774 FcConfigSubstitute(0, pattern, FcMatchPattern);
2775 FcDefaultSubstitute(pattern);
2777 if(xloadfont(&dc.font, pattern))
2778 die("st: can't open font %s\n", fontstr);
2780 /* Setting character width and height. */
2781 xw.cw = CEIL(dc.font.width * cwscale);
2782 xw.ch = CEIL(dc.font.height * chscale);
2784 FcPatternDel(pattern, FC_SLANT);
2785 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2786 if(xloadfont(&dc.ifont, pattern))
2787 die("st: can't open font %s\n", fontstr);
2789 FcPatternDel(pattern, FC_WEIGHT);
2790 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2791 if(xloadfont(&dc.ibfont, pattern))
2792 die("st: can't open font %s\n", fontstr);
2794 FcPatternDel(pattern, FC_SLANT);
2795 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2796 if(xloadfont(&dc.bfont, pattern))
2797 die("st: can't open font %s\n", fontstr);
2799 FcPatternDestroy(pattern);
2803 xloadfontset(Font *f) {
2806 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2812 xunloadfont(Font *f) {
2813 XftFontClose(xw.dpy, f->match);
2814 FcPatternDestroy(f->pattern);
2816 FcFontSetDestroy(f->set);
2820 xunloadfonts(void) {
2823 /* Free the loaded fonts in the font cache. */
2824 for(i = 0; i < frclen; i++) {
2825 XftFontClose(xw.dpy, frc[i].font);
2829 xunloadfont(&dc.font);
2830 xunloadfont(&dc.bfont);
2831 xunloadfont(&dc.ifont);
2832 xunloadfont(&dc.ibfont);
2836 xzoom(const Arg *arg) {
2838 xloadfonts(usedfont, usedfontsize + arg->i);
2850 if(!(xw.dpy = XOpenDisplay(NULL)))
2851 die("Can't open display\n");
2852 xw.scr = XDefaultScreen(xw.dpy);
2853 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2857 die("Could not init fontconfig.\n");
2859 usedfont = (opt_font == NULL)? font : opt_font;
2860 xloadfonts(usedfont, 0);
2863 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2866 /* adjust fixed window geometry */
2868 sw = DisplayWidth(xw.dpy, xw.scr);
2869 sh = DisplayHeight(xw.dpy, xw.scr);
2871 xw.fx = sw + xw.fx - xw.fw - 1;
2873 xw.fy = sh + xw.fy - xw.fh - 1;
2878 /* window - default size */
2879 xw.h = 2 * borderpx + term.row * xw.ch;
2880 xw.w = 2 * borderpx + term.col * xw.cw;
2886 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2887 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2888 xw.attrs.bit_gravity = NorthWestGravity;
2889 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2890 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2891 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2892 xw.attrs.colormap = xw.cmap;
2894 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2895 XRootWindow(xw.dpy, xw.scr);
2896 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2897 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2898 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
2899 | CWEventMask | CWColormap, &xw.attrs);
2901 memset(&gcvalues, 0, sizeof(gcvalues));
2902 gcvalues.graphics_exposures = False;
2903 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2905 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2906 DefaultDepth(xw.dpy, xw.scr));
2907 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2908 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2910 /* Xft rendering context */
2911 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2914 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2915 XSetLocaleModifiers("@im=local");
2916 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2917 XSetLocaleModifiers("@im=");
2918 if((xw.xim = XOpenIM(xw.dpy,
2919 NULL, NULL, NULL)) == NULL) {
2920 die("XOpenIM failed. Could not open input"
2925 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2926 | XIMStatusNothing, XNClientWindow, xw.win,
2927 XNFocusWindow, xw.win, NULL);
2929 die("XCreateIC failed. Could not obtain input method.\n");
2931 /* white cursor, black outline */
2932 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2933 XDefineCursor(xw.dpy, xw.win, cursor);
2934 XRecolorCursor(xw.dpy, cursor,
2935 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2936 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2938 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2939 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2940 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2943 XMapWindow(xw.dpy, xw.win);
2949 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2950 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2951 width = charlen * xw.cw, xp, i;
2953 int u8fl, u8fblen, u8cblen, doesexist;
2956 Font *font = &dc.font;
2958 FcPattern *fcpattern, *fontpattern;
2959 FcFontSet *fcsets[] = { NULL };
2960 FcCharSet *fccharset;
2961 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
2962 XRenderColor colfg, colbg;
2966 frcflags = FRC_NORMAL;
2968 if(base.mode & ATTR_ITALIC) {
2969 if(base.fg == defaultfg)
2970 base.fg = defaultitalic;
2972 frcflags = FRC_ITALIC;
2973 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2974 if(base.fg == defaultfg)
2975 base.fg = defaultitalic;
2977 frcflags = FRC_ITALICBOLD;
2978 } else if(base.mode & ATTR_UNDERLINE) {
2979 if(base.fg == defaultfg)
2980 base.fg = defaultunderline;
2982 if(IS_TRUECOL(base.fg)) {
2983 colfg.red = TRUERED(base.fg);
2984 colfg.green = TRUEGREEN(base.fg);
2985 colfg.blue = TRUEBLUE(base.fg);
2986 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
2989 fg = &dc.col[base.fg];
2992 if(IS_TRUECOL(base.bg)) {
2993 colbg.green = TRUEGREEN(base.bg);
2994 colbg.red = TRUERED(base.bg);
2995 colbg.blue = TRUEBLUE(base.bg);
2996 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
2999 bg = &dc.col[base.bg];
3004 if(base.mode & ATTR_BOLD) {
3005 if(BETWEEN(base.fg, 0, 7)) {
3006 /* basic system colors */
3007 fg = &dc.col[base.fg + 8];
3008 } else if(BETWEEN(base.fg, 16, 195)) {
3010 fg = &dc.col[base.fg + 36];
3011 } else if(BETWEEN(base.fg, 232, 251)) {
3013 fg = &dc.col[base.fg + 4];
3016 * Those ranges will not be brightened:
3017 * 8 - 15 – bright system colors
3018 * 196 - 231 – highest 256 color cube
3019 * 252 - 255 – brightest colors in greyscale
3022 frcflags = FRC_BOLD;
3025 if(IS_SET(MODE_REVERSE)) {
3026 if(fg == &dc.col[defaultfg]) {
3027 fg = &dc.col[defaultbg];
3029 colfg.red = ~fg->color.red;
3030 colfg.green = ~fg->color.green;
3031 colfg.blue = ~fg->color.blue;
3032 colfg.alpha = fg->color.alpha;
3033 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3037 if(bg == &dc.col[defaultbg]) {
3038 bg = &dc.col[defaultfg];
3040 colbg.red = ~bg->color.red;
3041 colbg.green = ~bg->color.green;
3042 colbg.blue = ~bg->color.blue;
3043 colbg.alpha = bg->color.alpha;
3044 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3049 if(base.mode & ATTR_REVERSE) {
3055 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3058 /* Intelligent cleaning up of the borders. */
3060 xclear(0, (y == 0)? 0 : winy, borderpx,
3061 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3063 if(x + charlen >= term.col) {
3064 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3065 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3068 xclear(winx, 0, winx + width, borderpx);
3070 xclear(winx, winy + xw.ch, winx + width, xw.h);
3072 /* Clean up the region we want to draw to. */
3073 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3075 /* Set the clip region because Xft is sometimes dirty. */
3080 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3082 for(xp = winx; bytelen > 0;) {
3084 * Search for the range in the to be printed string of glyphs
3085 * that are in the main font. Then print that range. If
3086 * some glyph is found that is not in the font, do the
3092 oneatatime = font->width != xw.cw;
3095 u8cblen = utf8decode(s, &u8char);
3099 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3100 if(oneatatime || !doesexist || bytelen <= 0) {
3101 if(oneatatime || bytelen <= 0) {
3109 XftDrawStringUtf8(xw.draw, fg,
3111 winy + font->ascent,
3114 xp += CEIL(font->width * cwscale * u8fl);
3129 /* Search the font cache. */
3130 for(i = 0; i < frclen; i++) {
3131 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3132 && frc[i].flags == frcflags) {
3137 /* Nothing was found. */
3141 fcsets[0] = font->set;
3144 * Nothing was found in the cache. Now use
3145 * some dozen of Fontconfig calls to get the
3146 * font for one single character.
3148 fcpattern = FcPatternDuplicate(font->pattern);
3149 fccharset = FcCharSetCreate();
3151 FcCharSetAddChar(fccharset, u8char);
3152 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3154 FcPatternAddBool(fcpattern, FC_SCALABLE,
3157 FcConfigSubstitute(0, fcpattern,
3159 FcDefaultSubstitute(fcpattern);
3161 fontpattern = FcFontSetMatch(0, fcsets,
3162 FcTrue, fcpattern, &fcres);
3165 * Overwrite or create the new cache entry.
3167 if(frclen >= LEN(frc)) {
3168 frclen = LEN(frc) - 1;
3169 XftFontClose(xw.dpy, frc[frclen].font);
3172 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3174 frc[frclen].flags = frcflags;
3179 FcPatternDestroy(fcpattern);
3180 FcCharSetDestroy(fccharset);
3183 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3184 xp, winy + frc[i].font->ascent,
3185 (FcChar8 *)u8c, u8cblen);
3187 xp += CEIL(font->width * cwscale);
3191 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3192 winy + font->ascent, (FcChar8 *)s, bytelen);
3195 if(base.mode & ATTR_UNDERLINE) {
3196 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3200 /* Reset clip to none. */
3201 XftDrawSetClip(xw.draw, 0);
3206 static int oldx = 0, oldy = 0;
3208 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3210 LIMIT(oldx, 0, term.col-1);
3211 LIMIT(oldy, 0, term.row-1);
3213 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3215 /* remove the old cursor */
3216 sl = utf8size(term.line[oldy][oldx].c);
3217 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3220 /* draw the new one */
3221 if(!(IS_SET(MODE_HIDE))) {
3222 if(xw.state & WIN_FOCUSED) {
3223 if(IS_SET(MODE_REVERSE)) {
3224 g.mode |= ATTR_REVERSE;
3230 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
3232 XftDrawRect(xw.draw, &dc.col[defaultcs],
3233 borderpx + term.c.x * xw.cw,
3234 borderpx + term.c.y * xw.ch,
3236 XftDrawRect(xw.draw, &dc.col[defaultcs],
3237 borderpx + term.c.x * xw.cw,
3238 borderpx + term.c.y * xw.ch,
3240 XftDrawRect(xw.draw, &dc.col[defaultcs],
3241 borderpx + (term.c.x + 1) * xw.cw - 1,
3242 borderpx + term.c.y * xw.ch,
3244 XftDrawRect(xw.draw, &dc.col[defaultcs],
3245 borderpx + term.c.x * xw.cw,
3246 borderpx + (term.c.y + 1) * xw.ch - 1,
3249 oldx = term.c.x, oldy = term.c.y;
3255 xsettitle(char *p) {
3258 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3260 XSetWMName(xw.dpy, xw.win, &prop);
3266 xsettitle(opt_title ? opt_title : "st");
3270 redraw(int timeout) {
3271 struct timespec tv = {0, timeout * 1000};
3277 nanosleep(&tv, NULL);
3278 XSync(xw.dpy, False); /* necessary for a good tput flash */
3284 drawregion(0, 0, term.col, term.row);
3285 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3287 XSetForeground(xw.dpy, dc.gc,
3288 dc.col[IS_SET(MODE_REVERSE)?
3289 defaultfg : defaultbg].pixel);
3293 drawregion(int x1, int y1, int x2, int y2) {
3294 int ic, ib, x, y, ox, sl;
3296 char buf[DRAW_BUF_SIZ];
3297 bool ena_sel = sel.ob.x != -1;
3299 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3302 if(!(xw.state & WIN_VISIBLE))
3305 for(y = y1; y < y2; y++) {
3309 xtermclear(0, y, term.col, y);
3311 base = term.line[y][0];
3313 for(x = x1; x < x2; x++) {
3314 new = term.line[y][x];
3315 if(ena_sel && selected(x, y))
3316 new.mode ^= ATTR_REVERSE;
3317 if(ib > 0 && (ATTRCMP(base, new)
3318 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3319 xdraws(buf, base, ox, y, ic, ib);
3327 sl = utf8size(new.c);
3328 memcpy(buf+ib, new.c, sl);
3333 xdraws(buf, base, ox, y, ic, ib);
3339 expose(XEvent *ev) {
3340 XExposeEvent *e = &ev->xexpose;
3342 if(xw.state & WIN_REDRAW) {
3344 xw.state &= ~WIN_REDRAW;
3350 visibility(XEvent *ev) {
3351 XVisibilityEvent *e = &ev->xvisibility;
3353 if(e->state == VisibilityFullyObscured) {
3354 xw.state &= ~WIN_VISIBLE;
3355 } else if(!(xw.state & WIN_VISIBLE)) {
3356 /* need a full redraw for next Expose, not just a buf copy */
3357 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3363 xw.state &= ~WIN_VISIBLE;
3367 xsetpointermotion(int set) {
3368 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3369 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3373 xseturgency(int add) {
3374 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3376 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3377 XSetWMHints(xw.dpy, xw.win, h);
3383 XFocusChangeEvent *e = &ev->xfocus;
3385 if(e->mode == NotifyGrab)
3388 if(ev->type == FocusIn) {
3389 XSetICFocus(xw.xic);
3390 xw.state |= WIN_FOCUSED;
3392 if(IS_SET(MODE_FOCUS))
3393 ttywrite("\033[I", 3);
3395 XUnsetICFocus(xw.xic);
3396 xw.state &= ~WIN_FOCUSED;
3397 if(IS_SET(MODE_FOCUS))
3398 ttywrite("\033[O", 3);
3403 match(uint mask, uint state) {
3404 state &= ~ignoremod;
3406 if(mask == XK_NO_MOD && state)
3408 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3410 if(mask == XK_ANY_MOD)
3412 return state == mask;
3416 numlock(const Arg *dummy) {
3421 kmap(KeySym k, uint state) {
3425 /* Check for mapped keys out of X11 function keys. */
3426 for(i = 0; i < LEN(mappedkeys); i++) {
3427 if(mappedkeys[i] == k)
3430 if(i == LEN(mappedkeys)) {
3431 if((k & 0xFFFF) < 0xFD00)
3435 for(kp = key; kp < key + LEN(key); kp++) {
3439 if(!match(kp->mask, state))
3442 if(kp->appkey > 0) {
3443 if(!IS_SET(MODE_APPKEYPAD))
3445 if(term.numlock && kp->appkey == 2)
3447 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3451 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3453 && !IS_SET(MODE_APPCURSOR))) {
3457 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3458 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3469 kpress(XEvent *ev) {
3470 XKeyEvent *e = &ev->xkey;
3472 char xstr[31], buf[32], *customkey, *cp = buf;
3478 if(IS_SET(MODE_KBDLOCK))
3481 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3482 e->state &= ~Mod2Mask;
3484 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3485 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3486 bp->func(&(bp->arg));
3491 /* 2. custom keys from config.h */
3492 if((customkey = kmap(ksym, e->state))) {
3493 len = strlen(customkey);
3494 memcpy(buf, customkey, len);
3495 /* 3. hardcoded (overrides X lookup) */
3500 if(len == 1 && e->state & Mod1Mask) {
3501 if(IS_SET(MODE_8BIT)) {
3504 ret = utf8encode(&c, cp);
3513 memcpy(cp, xstr, len);
3514 len = cp - buf + len;
3518 if(IS_SET(MODE_ECHO))
3524 cmessage(XEvent *e) {
3527 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3529 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3530 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3531 xw.state |= WIN_FOCUSED;
3533 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3534 xw.state &= ~WIN_FOCUSED;
3536 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3537 /* Send SIGHUP to shell */
3544 cresize(int width, int height) {
3552 col = (xw.w - 2 * borderpx) / xw.cw;
3553 row = (xw.h - 2 * borderpx) / xw.ch;
3562 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3565 cresize(e->xconfigure.width, e->xconfigure.height);
3571 int w = xw.w, h = xw.h;
3573 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3574 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3576 /* Waiting for window mapping */
3578 XNextEvent(xw.dpy, &ev);
3579 if(ev.type == ConfigureNotify) {
3580 w = ev.xconfigure.width;
3581 h = ev.xconfigure.height;
3582 } else if(ev.type == MapNotify) {
3590 cresize(xw.fw, xw.fh);
3593 gettimeofday(&lastblink, NULL);
3594 gettimeofday(&last, NULL);
3596 for(xev = actionfps;;) {
3598 FD_SET(cmdfd, &rfd);
3601 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3604 die("select failed: %s\n", SERRNO);
3606 if(FD_ISSET(cmdfd, &rfd)) {
3609 blinkset = tattrset(ATTR_BLINK);
3611 MODBIT(term.mode, 0, MODE_BLINK);
3615 if(FD_ISSET(xfd, &rfd))
3618 gettimeofday(&now, NULL);
3619 drawtimeout.tv_sec = 0;
3620 drawtimeout.tv_usec = (1000/xfps) * 1000;
3624 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3625 tsetdirtattr(ATTR_BLINK);
3626 term.mode ^= MODE_BLINK;
3627 gettimeofday(&lastblink, NULL);
3630 if(TIMEDIFF(now, last) \
3631 > (xev? (1000/xfps) : (1000/actionfps))) {
3637 while(XPending(xw.dpy)) {
3638 XNextEvent(xw.dpy, &ev);
3639 if(XFilterEvent(&ev, None))
3641 if(handler[ev.type])
3642 (handler[ev.type])(&ev);
3648 if(xev && !FD_ISSET(xfd, &rfd))
3650 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3652 if(TIMEDIFF(now, lastblink) \
3654 drawtimeout.tv_usec = 1;
3656 drawtimeout.tv_usec = (1000 * \
3671 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3672 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3673 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3677 main(int argc, char *argv[]) {
3682 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3687 allowaltscreen = false;
3690 opt_class = EARGF(usage());
3693 /* eat all remaining arguments */
3696 if(argv[1] != NULL && opt_title == NULL) {
3697 titles = strdup(argv[1]);
3698 opt_title = basename(titles);
3703 opt_font = EARGF(usage());
3706 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3711 if(bitm & WidthValue)
3713 if(bitm & HeightValue)
3715 if(bitm & XNegative && xw.fx == 0)
3717 if(bitm & YNegative && xw.fy == 0)
3720 if(xw.fh != 0 && xw.fw != 0)
3724 opt_io = EARGF(usage());
3727 opt_title = EARGF(usage());
3730 opt_embed = EARGF(usage());
3738 setlocale(LC_CTYPE, "");
3739 XSetLocaleModifiers("");