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);
424 static void (*handler[LASTEvent])(XEvent *) = {
426 [ClientMessage] = cmessage,
427 [ConfigureNotify] = resize,
428 [VisibilityNotify] = visibility,
429 [UnmapNotify] = unmap,
433 [MotionNotify] = bmotion,
434 [ButtonPress] = bpress,
435 [ButtonRelease] = brelease,
436 [SelectionClear] = selclear,
437 [SelectionNotify] = selnotify,
438 [SelectionRequest] = selrequest,
445 static CSIEscape csiescseq;
446 static STREscape strescseq;
449 static Selection sel;
450 static int iofd = -1;
451 static char **opt_cmd = NULL;
452 static char *opt_io = NULL;
453 static char *opt_title = NULL;
454 static char *opt_embed = NULL;
455 static char *opt_class = NULL;
456 static char *opt_font = NULL;
457 static int oldbutton = 3; /* button event on startup: 3 = release */
459 static char *usedfont = NULL;
460 static int usedfontsize = 0;
462 /* Font Ring Cache */
475 /* Fontcache is an array now. A new font will be appended to the array. */
476 static Fontcache frc[16];
477 static int frclen = 0;
480 xwrite(int fd, char *s, size_t len) {
484 ssize_t r = write(fd, s, len);
494 xmalloc(size_t len) {
495 void *p = malloc(len);
498 die("Out of memory\n");
504 xrealloc(void *p, size_t len) {
505 if((p = realloc(p, len)) == NULL)
506 die("Out of memory\n");
512 utf8decode(char *s, long *u) {
518 if(~c & 0x80) { /* 0xxxxxxx */
521 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
524 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
527 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
534 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
536 if((c & 0xC0) != 0x80) /* 10xxxxxx */
542 if((n == 1 && *u < 0x80) ||
543 (n == 2 && *u < 0x800) ||
544 (n == 3 && *u < 0x10000) ||
545 (*u >= 0xD800 && *u <= 0xDFFF)) {
557 utf8encode(long *u, char *s) {
565 *sp = uc; /* 0xxxxxxx */
567 } else if(*u < 0x800) {
568 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
570 } else if(uc < 0x10000) {
571 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
573 } else if(uc <= 0x10FFFF) {
574 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
580 for(i=n,++sp; i>0; --i,++sp)
581 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
593 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
594 UTF-8 otherwise return 0 */
596 isfullutf8(char *s, int b) {
604 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
606 } else if((*c1 & 0xF0) == 0xE0 &&
608 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
610 } else if((*c1 & 0xF8) == 0xF0 &&
612 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
613 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
626 } else if((c & 0xE0) == 0xC0) {
628 } else if((c & 0xF0) == 0xE0) {
637 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
638 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
642 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
643 if(sel.xtarget == None)
644 sel.xtarget = XA_STRING;
652 return LIMIT(x, 0, term.col-1);
660 return LIMIT(y, 0, term.row-1);
665 if(sel.ob.y == sel.oe.y) {
666 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
667 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
669 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
670 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
672 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
673 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
677 selected(int x, int y) {
678 if(sel.ne.y == y && sel.nb.y == y)
679 return BETWEEN(x, sel.nb.x, sel.ne.x);
681 if(sel.type == SEL_RECTANGULAR) {
682 return ((sel.nb.y <= y && y <= sel.ne.y)
683 && (sel.nb.x <= x && x <= sel.ne.x));
686 return ((sel.nb.y < y && y < sel.ne.y)
687 || (y == sel.ne.y && x <= sel.ne.x))
688 || (y == sel.nb.y && x >= sel.nb.x
689 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
693 selsnap(int mode, int *x, int *y, int direction) {
699 * Snap around if the word wraps around at the end or
700 * beginning of a line.
703 if(direction < 0 && *x <= 0) {
704 if(*y > 0 && term.line[*y - 1][term.col-1].mode
712 if(direction > 0 && *x >= term.col-1) {
713 if(*y < term.row-1 && term.line[*y][*x].mode
722 if(strchr(worddelimiters,
723 term.line[*y][*x + direction].c[0])) {
732 * Snap around if the the previous line or the current one
733 * has set ATTR_WRAP at its end. Then the whole next or
734 * previous line will be selected.
736 *x = (direction < 0) ? 0 : term.col - 1;
737 if(direction < 0 && *y > 0) {
738 for(; *y > 0; *y += direction) {
739 if(!(term.line[*y-1][term.col-1].mode
744 } else if(direction > 0 && *y < term.row-1) {
745 for(; *y < term.row; *y += direction) {
746 if(!(term.line[*y][term.col-1].mode
755 * Select the whole line when the end of line is reached.
759 while(--i > 0 && term.line[*y][i].c[0] == ' ')
769 getbuttoninfo(XEvent *e) {
771 uint state = e->xbutton.state &~Button1Mask;
773 sel.alt = IS_SET(MODE_ALTSCREEN);
775 sel.oe.x = x2col(e->xbutton.x);
776 sel.oe.y = y2row(e->xbutton.y);
778 if(sel.ob.y < sel.oe.y
779 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
780 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
781 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
783 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
784 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
788 sel.type = SEL_REGULAR;
789 for(type = 1; type < LEN(selmasks); ++type) {
790 if(match(selmasks[type], state)) {
798 mousereport(XEvent *e) {
799 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
800 button = e->xbutton.button, state = e->xbutton.state,
806 if(e->xbutton.type == MotionNotify) {
807 if(x == ox && y == oy)
809 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
811 /* MOUSE_MOTION: no reporting if no button is pressed */
812 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
815 button = oldbutton + 32;
818 } else if(!IS_SET(MODE_MOUSESGR)
819 && (e->xbutton.type == ButtonRelease
820 || button == AnyButton)) {
826 if(e->xbutton.type == ButtonPress) {
833 if(!IS_SET(MODE_MOUSEX10)) {
834 button += (state & ShiftMask ? 4 : 0)
835 + (state & Mod4Mask ? 8 : 0)
836 + (state & ControlMask ? 16 : 0);
840 if(IS_SET(MODE_MOUSESGR)) {
841 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
843 e->xbutton.type == ButtonRelease ? 'm' : 'M');
844 } else if(x < 223 && y < 223) {
845 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
846 IS_SET(MODE_MOUSEX10)? button-1 : 32+button,
860 if(IS_SET(MODE_MOUSE)) {
865 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
866 if(e->xbutton.button == mk->b
867 && match(mk->mask, e->xbutton.state)) {
868 ttywrite(mk->s, strlen(mk->s));
869 if(IS_SET(MODE_ECHO))
870 techo(mk->s, strlen(mk->s));
875 if(e->xbutton.button == Button1) {
876 gettimeofday(&now, NULL);
878 /* Clear previous selection, logically and visually. */
881 sel.type = SEL_REGULAR;
882 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
883 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
886 * If the user clicks below predefined timeouts specific
887 * snapping behaviour is exposed.
889 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
890 sel.snap = SNAP_LINE;
891 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
892 sel.snap = SNAP_WORD;
896 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
897 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
901 * Draw selection, unless it's regular and we don't want to
902 * make clicks visible
906 tsetdirt(sel.nb.y, sel.ne.y);
908 sel.tclick2 = sel.tclick1;
916 int x, y, bufsize, size, i, ex;
922 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
923 ptr = str = xmalloc(bufsize);
925 /* append every set & selected glyph to the selection */
926 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
927 gp = &term.line[y][0];
928 last = gp + term.col;
930 while(--last >= gp && !(selected(last - gp, y) && \
931 strcmp(last->c, " ") != 0))
934 for(x = 0; gp <= last; x++, ++gp) {
938 size = utf8size(gp->c);
939 memcpy(ptr, gp->c, size);
944 * Copy and pasting of line endings is inconsistent
945 * in the inconsistent terminal and GUI world.
946 * The best solution seems like to produce '\n' when
947 * something is copied from st and convert '\n' to
948 * '\r', when something to be pasted is received by
950 * FIXME: Fix the computer world.
952 if(y < sel.ne.y && !((gp-1)->mode & ATTR_WRAP))
956 * If the last selected line expands in the selection
957 * after the visible text '\n' is appended.
961 while(--i > 0 && term.line[y][i].c[0] == ' ')
964 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
976 selnotify(XEvent *e) {
977 ulong nitems, ofs, rem;
979 uchar *data, *last, *repl;
984 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
985 False, AnyPropertyType, &type, &format,
986 &nitems, &rem, &data)) {
987 fprintf(stderr, "Clipboard allocation failed\n");
992 * As seen in selcopy:
993 * Line endings are inconsistent in the terminal and GUI world
994 * copy and pasting. When receiving some selection data,
995 * replace all '\n' with '\r'.
996 * FIXME: Fix the computer world.
999 last = data + nitems * format / 8;
1000 while((repl = memchr(repl, '\n', last - repl))) {
1004 ttywrite((const char *)data, nitems * format / 8);
1006 /* number of 32-bit chunks returned */
1007 ofs += nitems * format / 32;
1012 selpaste(const Arg *dummy) {
1013 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1014 xw.win, CurrentTime);
1018 clippaste(const Arg *dummy) {
1021 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1022 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1023 xw.win, CurrentTime);
1027 selclear(XEvent *e) {
1031 tsetdirt(sel.nb.y, sel.ne.y);
1035 selrequest(XEvent *e) {
1036 XSelectionRequestEvent *xsre;
1037 XSelectionEvent xev;
1038 Atom xa_targets, string;
1040 xsre = (XSelectionRequestEvent *) e;
1041 xev.type = SelectionNotify;
1042 xev.requestor = xsre->requestor;
1043 xev.selection = xsre->selection;
1044 xev.target = xsre->target;
1045 xev.time = xsre->time;
1047 xev.property = None;
1049 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1050 if(xsre->target == xa_targets) {
1051 /* respond with the supported type */
1052 string = sel.xtarget;
1053 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1054 XA_ATOM, 32, PropModeReplace,
1055 (uchar *) &string, 1);
1056 xev.property = xsre->property;
1057 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1058 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1059 xsre->target, 8, PropModeReplace,
1060 (uchar *) sel.clip, strlen(sel.clip));
1061 xev.property = xsre->property;
1064 /* all done, send a notification to the listener */
1065 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1066 fprintf(stderr, "Error sending SelectionNotify event\n");
1070 xsetsel(char *str) {
1071 /* register the selection for both the clipboard and the primary */
1077 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1079 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1080 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1084 brelease(XEvent *e) {
1085 if(IS_SET(MODE_MOUSE)) {
1090 if(e->xbutton.button == Button2) {
1092 } else if(e->xbutton.button == Button1) {
1100 tsetdirt(sel.nb.y, sel.ne.y);
1105 bmotion(XEvent *e) {
1106 int oldey, oldex, oldsby, oldsey;
1108 if(IS_SET(MODE_MOUSE)) {
1123 if(oldey != sel.oe.y || oldex != sel.oe.x)
1124 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1128 die(const char *errstr, ...) {
1131 va_start(ap, errstr);
1132 vfprintf(stderr, errstr, ap);
1140 char *envshell = getenv("SHELL");
1141 const struct passwd *pass = getpwuid(getuid());
1142 char buf[sizeof(long) * 8 + 1];
1144 unsetenv("COLUMNS");
1146 unsetenv("TERMCAP");
1149 setenv("LOGNAME", pass->pw_name, 1);
1150 setenv("USER", pass->pw_name, 1);
1151 setenv("SHELL", pass->pw_shell, 0);
1152 setenv("HOME", pass->pw_dir, 0);
1155 snprintf(buf, sizeof(buf), "%lu", xw.win);
1156 setenv("WINDOWID", buf, 1);
1158 signal(SIGCHLD, SIG_DFL);
1159 signal(SIGHUP, SIG_DFL);
1160 signal(SIGINT, SIG_DFL);
1161 signal(SIGQUIT, SIG_DFL);
1162 signal(SIGTERM, SIG_DFL);
1163 signal(SIGALRM, SIG_DFL);
1165 DEFAULT(envshell, shell);
1166 setenv("TERM", termname, 1);
1167 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1168 execvp(args[0], args);
1176 if(waitpid(pid, &stat, 0) < 0)
1177 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1179 if(WIFEXITED(stat)) {
1180 exit(WEXITSTATUS(stat));
1189 struct winsize w = {term.row, term.col, 0, 0};
1191 /* seems to work fine on linux, openbsd and freebsd */
1192 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1193 die("openpty failed: %s\n", SERRNO);
1195 switch(pid = fork()) {
1197 die("fork failed\n");
1200 setsid(); /* create a new process group */
1201 dup2(s, STDIN_FILENO);
1202 dup2(s, STDOUT_FILENO);
1203 dup2(s, STDERR_FILENO);
1204 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1205 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1213 signal(SIGCHLD, sigchld);
1215 iofd = (!strcmp(opt_io, "-")) ?
1217 open(opt_io, O_WRONLY | O_CREAT, 0666);
1219 fprintf(stderr, "Error opening %s:%s\n",
1220 opt_io, strerror(errno));
1230 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1232 fprintf(stderr, "\n");
1237 static char buf[BUFSIZ];
1238 static int buflen = 0;
1241 int charsize; /* size of utf8 char in bytes */
1245 /* append read bytes to unprocessed bytes */
1246 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1247 die("Couldn't read from shell: %s\n", SERRNO);
1249 /* process every complete utf8 char */
1252 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1253 charsize = utf8decode(ptr, &utf8c);
1254 utf8encode(&utf8c, s);
1260 /* keep any uncomplete utf8 char for the next call */
1261 memmove(buf, ptr, buflen);
1265 ttywrite(const char *s, size_t n) {
1266 if(write(cmdfd, s, n) == -1)
1267 die("write error on tty: %s\n", SERRNO);
1274 w.ws_row = term.row;
1275 w.ws_col = term.col;
1276 w.ws_xpixel = xw.tw;
1277 w.ws_ypixel = xw.th;
1278 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1279 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1283 tattrset(int attr) {
1286 for(i = 0; i < term.row-1; i++) {
1287 for(j = 0; j < term.col-1; j++) {
1288 if(term.line[i][j].mode & attr)
1297 tsetdirt(int top, int bot) {
1300 LIMIT(top, 0, term.row-1);
1301 LIMIT(bot, 0, term.row-1);
1303 for(i = top; i <= bot; i++)
1308 tsetdirtattr(int attr) {
1311 for(i = 0; i < term.row-1; i++) {
1312 for(j = 0; j < term.col-1; j++) {
1313 if(term.line[i][j].mode & attr) {
1323 tsetdirt(0, term.row-1);
1330 if(mode == CURSOR_SAVE) {
1332 } else if(mode == CURSOR_LOAD) {
1342 term.c = (TCursor){{
1346 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1348 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1349 for(i = tabspaces; i < term.col; i += tabspaces)
1352 term.bot = term.row - 1;
1353 term.mode = MODE_WRAP;
1355 tclearregion(0, 0, term.col-1, term.row-1);
1357 tcursor(CURSOR_SAVE);
1361 tnew(int col, int row) {
1362 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1371 Line *tmp = term.line;
1373 term.line = term.alt;
1375 term.mode ^= MODE_ALTSCREEN;
1380 tscrolldown(int orig, int n) {
1384 LIMIT(n, 0, term.bot-orig+1);
1386 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1388 for(i = term.bot; i >= orig+n; i--) {
1389 temp = term.line[i];
1390 term.line[i] = term.line[i-n];
1391 term.line[i-n] = temp;
1394 term.dirty[i-n] = 1;
1401 tscrollup(int orig, int n) {
1404 LIMIT(n, 0, term.bot-orig+1);
1406 tclearregion(0, orig, term.col-1, orig+n-1);
1408 for(i = orig; i <= term.bot-n; i++) {
1409 temp = term.line[i];
1410 term.line[i] = term.line[i+n];
1411 term.line[i+n] = temp;
1414 term.dirty[i+n] = 1;
1417 selscroll(orig, -n);
1421 selscroll(int orig, int n) {
1425 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1426 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1430 if(sel.type == SEL_RECTANGULAR) {
1431 if(sel.ob.y < term.top)
1432 sel.ob.y = term.top;
1433 if(sel.oe.y > term.bot)
1434 sel.oe.y = term.bot;
1436 if(sel.ob.y < term.top) {
1437 sel.ob.y = term.top;
1440 if(sel.oe.y > term.bot) {
1441 sel.oe.y = term.bot;
1442 sel.oe.x = term.col;
1450 tnewline(int first_col) {
1454 tscrollup(term.top, 1);
1458 tmoveto(first_col ? 0 : term.c.x, y);
1463 char *p = csiescseq.buf, *np;
1472 csiescseq.buf[csiescseq.len] = '\0';
1473 while(p < csiescseq.buf+csiescseq.len) {
1475 v = strtol(p, &np, 10);
1478 if(v == LONG_MAX || v == LONG_MIN)
1480 csiescseq.arg[csiescseq.narg++] = v;
1482 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1486 csiescseq.mode = *p;
1489 /* for absolute user moves, when decom is set */
1491 tmoveato(int x, int y) {
1492 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1496 tmoveto(int x, int y) {
1499 if(term.c.state & CURSOR_ORIGIN) {
1504 maxy = term.row - 1;
1506 LIMIT(x, 0, term.col-1);
1507 LIMIT(y, miny, maxy);
1508 term.c.state &= ~CURSOR_WRAPNEXT;
1514 tsetchar(char *c, Glyph *attr, int x, int y) {
1515 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1516 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1517 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1518 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1519 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1520 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1521 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1522 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1523 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1527 * The table is proudly stolen from rxvt.
1529 if(attr->mode & ATTR_GFX) {
1530 if(c[0] >= 0x41 && c[0] <= 0x7e
1531 && vt100_0[c[0] - 0x41]) {
1532 c = vt100_0[c[0] - 0x41];
1537 term.line[y][x] = *attr;
1538 memcpy(term.line[y][x].c, c, UTF_SIZ);
1542 tclearregion(int x1, int y1, int x2, int y2) {
1546 temp = x1, x1 = x2, x2 = temp;
1548 temp = y1, y1 = y2, y2 = temp;
1550 LIMIT(x1, 0, term.col-1);
1551 LIMIT(x2, 0, term.col-1);
1552 LIMIT(y1, 0, term.row-1);
1553 LIMIT(y2, 0, term.row-1);
1555 for(y = y1; y <= y2; y++) {
1557 for(x = x1; x <= x2; x++) {
1560 term.line[y][x] = term.c.attr;
1561 memcpy(term.line[y][x].c, " ", 2);
1567 tdeletechar(int n) {
1568 int src = term.c.x + n;
1570 int size = term.col - src;
1572 term.dirty[term.c.y] = 1;
1574 if(src >= term.col) {
1575 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1579 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1580 size * sizeof(Glyph));
1581 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1585 tinsertblank(int n) {
1588 int size = term.col - dst;
1590 term.dirty[term.c.y] = 1;
1592 if(dst >= term.col) {
1593 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1597 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1598 size * sizeof(Glyph));
1599 tclearregion(src, term.c.y, dst - 1, term.c.y);
1603 tinsertblankline(int n) {
1604 if(term.c.y < term.top || term.c.y > term.bot)
1607 tscrolldown(term.c.y, n);
1611 tdeleteline(int n) {
1612 if(term.c.y < term.top || term.c.y > term.bot)
1615 tscrollup(term.c.y, n);
1619 tdefcolor(int *attr, int *npar, int l) {
1623 switch (attr[*npar + 1]) {
1624 case 2: /* direct colour in RGB space */
1625 if (*npar + 4 >= l) {
1627 "erresc(38): Incorrect number of parameters (%d)\n",
1631 r = attr[*npar + 2];
1632 g = attr[*npar + 3];
1633 b = attr[*npar + 4];
1635 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1636 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1639 idx = TRUECOLOR(r, g, b);
1641 case 5: /* indexed colour */
1642 if (*npar + 2 >= l) {
1644 "erresc(38): Incorrect number of parameters (%d)\n",
1649 if(!BETWEEN(attr[*npar], 0, 255))
1650 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1654 case 0: /* implemented defined (only foreground) */
1655 case 1: /* transparent */
1656 case 3: /* direct colour in CMY space */
1657 case 4: /* direct colour in CMYK space */
1660 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1667 tsetattr(int *attr, int l) {
1671 for(i = 0; i < l; i++) {
1674 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1675 | ATTR_BOLD | ATTR_ITALIC \
1677 term.c.attr.fg = defaultfg;
1678 term.c.attr.bg = defaultbg;
1681 term.c.attr.mode |= ATTR_BOLD;
1684 term.c.attr.mode |= ATTR_ITALIC;
1687 term.c.attr.mode |= ATTR_UNDERLINE;
1689 case 5: /* slow blink */
1690 case 6: /* rapid blink */
1691 term.c.attr.mode |= ATTR_BLINK;
1694 term.c.attr.mode |= ATTR_REVERSE;
1698 term.c.attr.mode &= ~ATTR_BOLD;
1701 term.c.attr.mode &= ~ATTR_ITALIC;
1704 term.c.attr.mode &= ~ATTR_UNDERLINE;
1708 term.c.attr.mode &= ~ATTR_BLINK;
1711 term.c.attr.mode &= ~ATTR_REVERSE;
1714 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1715 term.c.attr.fg = idx;
1718 term.c.attr.fg = defaultfg;
1721 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1722 term.c.attr.bg = idx;
1725 term.c.attr.bg = defaultbg;
1728 if(BETWEEN(attr[i], 30, 37)) {
1729 term.c.attr.fg = attr[i] - 30;
1730 } else if(BETWEEN(attr[i], 40, 47)) {
1731 term.c.attr.bg = attr[i] - 40;
1732 } else if(BETWEEN(attr[i], 90, 97)) {
1733 term.c.attr.fg = attr[i] - 90 + 8;
1734 } else if(BETWEEN(attr[i], 100, 107)) {
1735 term.c.attr.bg = attr[i] - 100 + 8;
1738 "erresc(default): gfx attr %d unknown\n",
1739 attr[i]), csidump();
1747 tsetscroll(int t, int b) {
1750 LIMIT(t, 0, term.row-1);
1751 LIMIT(b, 0, term.row-1);
1761 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1764 tsetmode(bool priv, bool set, int *args, int narg) {
1768 for(lim = args + narg; args < lim; ++args) {
1772 case 1: /* DECCKM -- Cursor key */
1773 MODBIT(term.mode, set, MODE_APPCURSOR);
1775 case 5: /* DECSCNM -- Reverse video */
1777 MODBIT(term.mode, set, MODE_REVERSE);
1778 if(mode != term.mode)
1779 redraw(REDRAW_TIMEOUT);
1781 case 6: /* DECOM -- Origin */
1782 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1785 case 7: /* DECAWM -- Auto wrap */
1786 MODBIT(term.mode, set, MODE_WRAP);
1788 case 0: /* Error (IGNORED) */
1789 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1790 case 3: /* DECCOLM -- Column (IGNORED) */
1791 case 4: /* DECSCLM -- Scroll (IGNORED) */
1792 case 8: /* DECARM -- Auto repeat (IGNORED) */
1793 case 18: /* DECPFF -- Printer feed (IGNORED) */
1794 case 19: /* DECPEX -- Printer extent (IGNORED) */
1795 case 42: /* DECNRCM -- National characters (IGNORED) */
1796 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1798 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1799 MODBIT(term.mode, !set, MODE_HIDE);
1801 case 9: /* X10 mouse compatibility mode */
1802 xsetpointermotion(0);
1803 MODBIT(term.mode, 0, MODE_MOUSE);
1804 MODBIT(term.mode, set, MODE_MOUSEX10);
1806 case 1000: /* 1000: report button press */
1807 xsetpointermotion(0);
1808 MODBIT(term.mode, 0, MODE_MOUSE);
1809 MODBIT(term.mode, set, MODE_MOUSEBTN);
1811 case 1002: /* 1002: report motion on button press */
1812 xsetpointermotion(0);
1813 MODBIT(term.mode, 0, MODE_MOUSE);
1814 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1816 case 1003: /* 1003: enable all mouse motions */
1817 xsetpointermotion(set);
1818 MODBIT(term.mode, 0, MODE_MOUSE);
1819 MODBIT(term.mode, set, MODE_MOUSEMANY);
1821 case 1004: /* 1004: send focus events to tty */
1822 MODBIT(term.mode, set, MODE_FOCUS);
1824 case 1006: /* 1006: extended reporting mode */
1825 MODBIT(term.mode, set, MODE_MOUSESGR);
1828 MODBIT(term.mode, set, MODE_8BIT);
1830 case 1049: /* = 1047 and 1048 */
1833 if (!allowaltscreen)
1836 alt = IS_SET(MODE_ALTSCREEN);
1838 tclearregion(0, 0, term.col-1,
1841 if(set ^ alt) /* set is always 1 or 0 */
1847 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1849 /* Not implemented mouse modes. See comments there. */
1850 case 1001: /* mouse highlight mode; can hang the
1851 terminal by design when implemented. */
1852 case 1005: /* UTF-8 mouse mode; will confuse
1853 applications not supporting UTF-8
1855 case 1015: /* urxvt mangled mouse mode; incompatible
1856 and can be mistaken for other control
1860 "erresc: unknown private set/reset mode %d\n",
1866 case 0: /* Error (IGNORED) */
1868 case 2: /* KAM -- keyboard action */
1869 MODBIT(term.mode, set, MODE_KBDLOCK);
1871 case 4: /* IRM -- Insertion-replacement */
1872 MODBIT(term.mode, set, MODE_INSERT);
1874 case 12: /* SRM -- Send/Receive */
1875 MODBIT(term.mode, !set, MODE_ECHO);
1877 case 20: /* LNM -- Linefeed/new line */
1878 MODBIT(term.mode, set, MODE_CRLF);
1882 "erresc: unknown set/reset mode %d\n",
1892 switch(csiescseq.mode) {
1895 fprintf(stderr, "erresc: unknown csi ");
1899 case '@': /* ICH -- Insert <n> blank char */
1900 DEFAULT(csiescseq.arg[0], 1);
1901 tinsertblank(csiescseq.arg[0]);
1903 case 'A': /* CUU -- Cursor <n> Up */
1904 DEFAULT(csiescseq.arg[0], 1);
1905 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1907 case 'B': /* CUD -- Cursor <n> Down */
1908 case 'e': /* VPR --Cursor <n> Down */
1909 DEFAULT(csiescseq.arg[0], 1);
1910 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1912 case 'c': /* DA -- Device Attributes */
1913 if(csiescseq.arg[0] == 0)
1914 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1916 case 'C': /* CUF -- Cursor <n> Forward */
1917 case 'a': /* HPR -- Cursor <n> Forward */
1918 DEFAULT(csiescseq.arg[0], 1);
1919 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1921 case 'D': /* CUB -- Cursor <n> Backward */
1922 DEFAULT(csiescseq.arg[0], 1);
1923 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1925 case 'E': /* CNL -- Cursor <n> Down and first col */
1926 DEFAULT(csiescseq.arg[0], 1);
1927 tmoveto(0, term.c.y+csiescseq.arg[0]);
1929 case 'F': /* CPL -- Cursor <n> Up and first col */
1930 DEFAULT(csiescseq.arg[0], 1);
1931 tmoveto(0, term.c.y-csiescseq.arg[0]);
1933 case 'g': /* TBC -- Tabulation clear */
1934 switch(csiescseq.arg[0]) {
1935 case 0: /* clear current tab stop */
1936 term.tabs[term.c.x] = 0;
1938 case 3: /* clear all the tabs */
1939 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1945 case 'G': /* CHA -- Move to <col> */
1947 DEFAULT(csiescseq.arg[0], 1);
1948 tmoveto(csiescseq.arg[0]-1, term.c.y);
1950 case 'H': /* CUP -- Move to <row> <col> */
1952 DEFAULT(csiescseq.arg[0], 1);
1953 DEFAULT(csiescseq.arg[1], 1);
1954 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1956 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1957 DEFAULT(csiescseq.arg[0], 1);
1958 while(csiescseq.arg[0]--)
1961 case 'J': /* ED -- Clear screen */
1963 switch(csiescseq.arg[0]) {
1965 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1966 if(term.c.y < term.row-1) {
1967 tclearregion(0, term.c.y+1, term.col-1,
1973 tclearregion(0, 0, term.col-1, term.c.y-1);
1974 tclearregion(0, term.c.y, term.c.x, term.c.y);
1977 tclearregion(0, 0, term.col-1, term.row-1);
1983 case 'K': /* EL -- Clear line */
1984 switch(csiescseq.arg[0]) {
1986 tclearregion(term.c.x, term.c.y, term.col-1,
1990 tclearregion(0, term.c.y, term.c.x, term.c.y);
1993 tclearregion(0, term.c.y, term.col-1, term.c.y);
1997 case 'S': /* SU -- Scroll <n> line up */
1998 DEFAULT(csiescseq.arg[0], 1);
1999 tscrollup(term.top, csiescseq.arg[0]);
2001 case 'T': /* SD -- Scroll <n> line down */
2002 DEFAULT(csiescseq.arg[0], 1);
2003 tscrolldown(term.top, csiescseq.arg[0]);
2005 case 'L': /* IL -- Insert <n> blank lines */
2006 DEFAULT(csiescseq.arg[0], 1);
2007 tinsertblankline(csiescseq.arg[0]);
2009 case 'l': /* RM -- Reset Mode */
2010 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2012 case 'M': /* DL -- Delete <n> lines */
2013 DEFAULT(csiescseq.arg[0], 1);
2014 tdeleteline(csiescseq.arg[0]);
2016 case 'X': /* ECH -- Erase <n> char */
2017 DEFAULT(csiescseq.arg[0], 1);
2018 tclearregion(term.c.x, term.c.y,
2019 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2021 case 'P': /* DCH -- Delete <n> char */
2022 DEFAULT(csiescseq.arg[0], 1);
2023 tdeletechar(csiescseq.arg[0]);
2025 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2026 DEFAULT(csiescseq.arg[0], 1);
2027 while(csiescseq.arg[0]--)
2030 case 'd': /* VPA -- Move to <row> */
2031 DEFAULT(csiescseq.arg[0], 1);
2032 tmoveato(term.c.x, csiescseq.arg[0]-1);
2034 case 'h': /* SM -- Set terminal mode */
2035 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2037 case 'm': /* SGR -- Terminal attribute (color) */
2038 tsetattr(csiescseq.arg, csiescseq.narg);
2040 case 'r': /* DECSTBM -- Set Scrolling Region */
2041 if(csiescseq.priv) {
2044 DEFAULT(csiescseq.arg[0], 1);
2045 DEFAULT(csiescseq.arg[1], term.row);
2046 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2050 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2051 tcursor(CURSOR_SAVE);
2053 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2054 tcursor(CURSOR_LOAD);
2065 for(i = 0; i < csiescseq.len; i++) {
2066 c = csiescseq.buf[i] & 0xff;
2069 } else if(c == '\n') {
2071 } else if(c == '\r') {
2073 } else if(c == 0x1b) {
2076 printf("(%02x)", c);
2084 memset(&csiescseq, 0, sizeof(csiescseq));
2093 narg = strescseq.narg;
2095 switch(strescseq.type) {
2096 case ']': /* OSC -- Operating System Command */
2097 switch(i = atoi(strescseq.args[0])) {
2102 xsettitle(strescseq.args[1]);
2104 case 4: /* color set */
2107 p = strescseq.args[2];
2109 case 104: /* color reset, here p = NULL */
2110 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2111 if (!xsetcolorname(j, p)) {
2112 fprintf(stderr, "erresc: invalid color %s\n", p);
2115 * TODO if defaultbg color is changed, borders
2122 fprintf(stderr, "erresc: unknown str ");
2127 case 'k': /* old title set compatibility */
2128 xsettitle(strescseq.args[0]);
2130 case 'P': /* DSC -- Device Control String */
2131 case '_': /* APC -- Application Program Command */
2132 case '^': /* PM -- Privacy Message */
2134 fprintf(stderr, "erresc: unknown str ");
2143 char *p = strescseq.buf;
2146 strescseq.buf[strescseq.len] = '\0';
2147 while(p && strescseq.narg < STR_ARG_SIZ)
2148 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2156 printf("ESC%c", strescseq.type);
2157 for(i = 0; i < strescseq.len; i++) {
2158 c = strescseq.buf[i] & 0xff;
2161 } else if(isprint(c)) {
2163 } else if(c == '\n') {
2165 } else if(c == '\r') {
2167 } else if(c == 0x1b) {
2170 printf("(%02x)", c);
2178 memset(&strescseq, 0, sizeof(strescseq));
2182 tputtab(bool forward) {
2188 for(++x; x < term.col && !term.tabs[x]; ++x)
2193 for(--x; x > 0 && !term.tabs[x]; --x)
2196 tmoveto(x, term.c.y);
2200 techo(char *buf, int len) {
2201 for(; len > 0; buf++, len--) {
2204 if(c == '\033') { /* escape */
2207 } else if(c < '\x20') { /* control code */
2208 if(c != '\n' && c != '\r' && c != '\t') {
2222 tputc(char *c, int len) {
2224 bool control = ascii < '\x20' || ascii == 0177;
2227 if(xwrite(iofd, c, len) < 0) {
2228 fprintf(stderr, "Error writing in %s:%s\n",
2229 opt_io, strerror(errno));
2236 * STR sequences must be checked before anything else
2237 * because it can use some control codes as part of the sequence.
2239 if(term.esc & ESC_STR) {
2242 term.esc = ESC_START | ESC_STR_END;
2244 case '\a': /* backwards compatibility to xterm */
2249 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2250 memmove(&strescseq.buf[strescseq.len], c, len);
2251 strescseq.len += len;
2254 * Here is a bug in terminals. If the user never sends
2255 * some code to stop the str or esc command, then st
2256 * will stop responding. But this is better than
2257 * silently failing with unknown characters. At least
2258 * then users will report back.
2260 * In the case users ever get fixed, here is the code:
2272 * Actions of control codes must be performed as soon they arrive
2273 * because they can be embedded inside a control sequence, and
2274 * they must not cause conflicts with sequences.
2282 tmoveto(term.c.x-1, term.c.y);
2285 tmoveto(0, term.c.y);
2290 /* go to first col if the mode is set */
2291 tnewline(IS_SET(MODE_CRLF));
2293 case '\a': /* BEL */
2294 if(!(xw.state & WIN_FOCUSED))
2297 case '\033': /* ESC */
2299 term.esc = ESC_START;
2301 case '\016': /* SO */
2302 case '\017': /* SI */
2304 * Different charsets are hard to handle. Applications
2305 * should use the right alt charset escapes for the
2306 * only reason they still exist: line drawing. The
2307 * rest is incompatible history st should not support.
2310 case '\032': /* SUB */
2311 case '\030': /* CAN */
2314 case '\005': /* ENQ (IGNORED) */
2315 case '\000': /* NUL (IGNORED) */
2316 case '\021': /* XON (IGNORED) */
2317 case '\023': /* XOFF (IGNORED) */
2318 case 0177: /* DEL (IGNORED) */
2321 } else if(term.esc & ESC_START) {
2322 if(term.esc & ESC_CSI) {
2323 csiescseq.buf[csiescseq.len++] = ascii;
2324 if(BETWEEN(ascii, 0x40, 0x7E)
2325 || csiescseq.len >= \
2326 sizeof(csiescseq.buf)-1) {
2331 } else if(term.esc & ESC_STR_END) {
2335 } else if(term.esc & ESC_ALTCHARSET) {
2337 case '0': /* Line drawing set */
2338 term.c.attr.mode |= ATTR_GFX;
2340 case 'B': /* USASCII */
2341 term.c.attr.mode &= ~ATTR_GFX;
2343 case 'A': /* UK (IGNORED) */
2344 case '<': /* multinational charset (IGNORED) */
2345 case '5': /* Finnish (IGNORED) */
2346 case 'C': /* Finnish (IGNORED) */
2347 case 'K': /* German (IGNORED) */
2350 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2353 } else if(term.esc & ESC_TEST) {
2354 if(ascii == '8') { /* DEC screen alignment test. */
2355 char E[UTF_SIZ] = "E";
2358 for(x = 0; x < term.col; ++x) {
2359 for(y = 0; y < term.row; ++y)
2360 tsetchar(E, &term.c.attr, x, y);
2367 term.esc |= ESC_CSI;
2370 term.esc |= ESC_TEST;
2372 case 'P': /* DCS -- Device Control String */
2373 case '_': /* APC -- Application Program Command */
2374 case '^': /* PM -- Privacy Message */
2375 case ']': /* OSC -- Operating System Command */
2376 case 'k': /* old title set compatibility */
2378 strescseq.type = ascii;
2379 term.esc |= ESC_STR;
2381 case '(': /* set primary charset G0 */
2382 term.esc |= ESC_ALTCHARSET;
2384 case ')': /* set secondary charset G1 (IGNORED) */
2385 case '*': /* set tertiary charset G2 (IGNORED) */
2386 case '+': /* set quaternary charset G3 (IGNORED) */
2389 case 'D': /* IND -- Linefeed */
2390 if(term.c.y == term.bot) {
2391 tscrollup(term.top, 1);
2393 tmoveto(term.c.x, term.c.y+1);
2397 case 'E': /* NEL -- Next line */
2398 tnewline(1); /* always go to first col */
2401 case 'H': /* HTS -- Horizontal tab stop */
2402 term.tabs[term.c.x] = 1;
2405 case 'M': /* RI -- Reverse index */
2406 if(term.c.y == term.top) {
2407 tscrolldown(term.top, 1);
2409 tmoveto(term.c.x, term.c.y-1);
2413 case 'Z': /* DECID -- Identify Terminal */
2414 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2417 case 'c': /* RIS -- Reset to inital state */
2423 case '=': /* DECPAM -- Application keypad */
2424 term.mode |= MODE_APPKEYPAD;
2427 case '>': /* DECPNM -- Normal keypad */
2428 term.mode &= ~MODE_APPKEYPAD;
2431 case '7': /* DECSC -- Save Cursor */
2432 tcursor(CURSOR_SAVE);
2435 case '8': /* DECRC -- Restore Cursor */
2436 tcursor(CURSOR_LOAD);
2439 case '\\': /* ST -- Stop */
2443 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2444 (uchar) ascii, isprint(ascii)? ascii:'.');
2449 * All characters which form part of a sequence are not
2455 * Display control codes only if we are in graphic mode
2457 if(control && !(term.c.attr.mode & ATTR_GFX))
2459 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2461 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2462 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2466 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2467 memmove(&term.line[term.c.y][term.c.x+1],
2468 &term.line[term.c.y][term.c.x],
2469 (term.col - term.c.x - 1) * sizeof(Glyph));
2472 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2473 if(term.c.x+1 < term.col) {
2474 tmoveto(term.c.x+1, term.c.y);
2476 term.c.state |= CURSOR_WRAPNEXT;
2481 tresize(int col, int row) {
2483 int minrow = MIN(row, term.row);
2484 int mincol = MIN(col, term.col);
2485 int slide = term.c.y - row + 1;
2489 if(col < 1 || row < 1)
2492 /* free unneeded rows */
2496 * slide screen to keep cursor where we expect it -
2497 * tscrollup would work here, but we can optimize to
2498 * memmove because we're freeing the earlier lines
2500 for(/* i = 0 */; i < slide; i++) {
2504 memmove(term.line, term.line + slide, row * sizeof(Line));
2505 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2507 for(i += row; i < term.row; i++) {
2512 /* resize to new height */
2513 term.line = xrealloc(term.line, row * sizeof(Line));
2514 term.alt = xrealloc(term.alt, row * sizeof(Line));
2515 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2516 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2518 /* resize each row to new width, zero-pad if needed */
2519 for(i = 0; i < minrow; i++) {
2521 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2522 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2525 /* allocate any new rows */
2526 for(/* i == minrow */; i < row; i++) {
2528 term.line[i] = xmalloc(col * sizeof(Glyph));
2529 term.alt[i] = xmalloc(col * sizeof(Glyph));
2531 if(col > term.col) {
2532 bp = term.tabs + term.col;
2534 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2535 while(--bp > term.tabs && !*bp)
2537 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2540 /* update terminal size */
2543 /* reset scrolling region */
2544 tsetscroll(0, row-1);
2545 /* make use of the LIMIT in tmoveto */
2546 tmoveto(term.c.x, term.c.y);
2547 /* Clearing both screens */
2550 if(mincol < col && 0 < minrow) {
2551 tclearregion(mincol, 0, col - 1, minrow - 1);
2553 if(0 < col && minrow < row) {
2554 tclearregion(0, minrow, col - 1, row - 1);
2557 } while(orig != term.line);
2563 xresize(int col, int row) {
2564 xw.tw = MAX(1, col * xw.cw);
2565 xw.th = MAX(1, row * xw.ch);
2567 XFreePixmap(xw.dpy, xw.buf);
2568 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2569 DefaultDepth(xw.dpy, xw.scr));
2570 XftDrawChange(xw.draw, xw.buf);
2571 xclear(0, 0, xw.w, xw.h);
2574 static inline ushort
2575 sixd_to_16bit(int x) {
2576 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2582 XRenderColor color = { .alpha = 0xffff };
2587 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2588 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2591 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2592 for(i = 0; i < LEN(colorname); i++) {
2595 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2596 die("Could not allocate color '%s'\n", colorname[i]);
2600 /* load colors [16-255] ; same colors as xterm */
2601 for(i = 16, r = 0; r < 6; r++) {
2602 for(g = 0; g < 6; g++) {
2603 for(b = 0; b < 6; b++) {
2604 color.red = sixd_to_16bit(r);
2605 color.green = sixd_to_16bit(g);
2606 color.blue = sixd_to_16bit(b);
2607 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2608 die("Could not allocate color %d\n", i);
2615 for(r = 0; r < 24; r++, i++) {
2616 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2617 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2619 die("Could not allocate color %d\n", i);
2626 xsetcolorname(int x, const char *name) {
2627 XRenderColor color = { .alpha = 0xffff };
2629 if (x < 0 || x > LEN(colorname))
2632 if(16 <= x && x < 16 + 216) {
2633 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2634 color.red = sixd_to_16bit(r);
2635 color.green = sixd_to_16bit(g);
2636 color.blue = sixd_to_16bit(b);
2637 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2638 return 0; /* something went wrong */
2641 } else if (16 + 216 <= x && x < 256) {
2642 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2643 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2644 return 0; /* something went wrong */
2648 name = colorname[x];
2651 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2658 xtermclear(int col1, int row1, int col2, int row2) {
2659 XftDrawRect(xw.draw,
2660 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2661 borderpx + col1 * xw.cw,
2662 borderpx + row1 * xw.ch,
2663 (col2-col1+1) * xw.cw,
2664 (row2-row1+1) * xw.ch);
2668 * Absolute coordinates.
2671 xclear(int x1, int y1, int x2, int y2) {
2672 XftDrawRect(xw.draw,
2673 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2674 x1, y1, x2-x1, y2-y1);
2679 XClassHint class = {opt_class ? opt_class : termname, termname};
2680 XWMHints wm = {.flags = InputHint, .input = 1};
2681 XSizeHints *sizeh = NULL;
2683 sizeh = XAllocSizeHints();
2684 if(xw.isfixed == False) {
2685 sizeh->flags = PSize | PResizeInc | PBaseSize;
2686 sizeh->height = xw.h;
2687 sizeh->width = xw.w;
2688 sizeh->height_inc = xw.ch;
2689 sizeh->width_inc = xw.cw;
2690 sizeh->base_height = 2 * borderpx;
2691 sizeh->base_width = 2 * borderpx;
2693 sizeh->flags = PMaxSize | PMinSize;
2694 sizeh->min_width = sizeh->max_width = xw.fw;
2695 sizeh->min_height = sizeh->max_height = xw.fh;
2698 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2703 xloadfont(Font *f, FcPattern *pattern) {
2707 match = FcFontMatch(NULL, pattern, &result);
2711 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2712 FcPatternDestroy(match);
2717 f->pattern = FcPatternDuplicate(pattern);
2719 f->ascent = f->match->ascent;
2720 f->descent = f->match->descent;
2722 f->rbearing = f->match->max_advance_width;
2724 f->height = f->ascent + f->descent;
2725 f->width = f->lbearing + f->rbearing;
2731 xloadfonts(char *fontstr, int fontsize) {
2736 if(fontstr[0] == '-') {
2737 pattern = XftXlfdParse(fontstr, False, False);
2739 pattern = FcNameParse((FcChar8 *)fontstr);
2743 die("st: can't open font %s\n", fontstr);
2746 FcPatternDel(pattern, FC_PIXEL_SIZE);
2747 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2748 usedfontsize = fontsize;
2750 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2751 if(result == FcResultMatch) {
2752 usedfontsize = (int)fontval;
2755 * Default font size is 12, if none given. This is to
2756 * have a known usedfontsize value.
2758 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2763 FcConfigSubstitute(0, pattern, FcMatchPattern);
2764 FcDefaultSubstitute(pattern);
2766 if(xloadfont(&dc.font, pattern))
2767 die("st: can't open font %s\n", fontstr);
2769 /* Setting character width and height. */
2770 xw.cw = CEIL(dc.font.width * cwscale);
2771 xw.ch = CEIL(dc.font.height * chscale);
2773 FcPatternDel(pattern, FC_SLANT);
2774 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2775 if(xloadfont(&dc.ifont, pattern))
2776 die("st: can't open font %s\n", fontstr);
2778 FcPatternDel(pattern, FC_WEIGHT);
2779 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2780 if(xloadfont(&dc.ibfont, pattern))
2781 die("st: can't open font %s\n", fontstr);
2783 FcPatternDel(pattern, FC_SLANT);
2784 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2785 if(xloadfont(&dc.bfont, pattern))
2786 die("st: can't open font %s\n", fontstr);
2788 FcPatternDestroy(pattern);
2792 xloadfontset(Font *f) {
2795 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2801 xunloadfont(Font *f) {
2802 XftFontClose(xw.dpy, f->match);
2803 FcPatternDestroy(f->pattern);
2805 FcFontSetDestroy(f->set);
2809 xunloadfonts(void) {
2812 /* Free the loaded fonts in the font cache. */
2813 for(i = 0; i < frclen; i++) {
2814 XftFontClose(xw.dpy, frc[i].font);
2818 xunloadfont(&dc.font);
2819 xunloadfont(&dc.bfont);
2820 xunloadfont(&dc.ifont);
2821 xunloadfont(&dc.ibfont);
2825 xzoom(const Arg *arg) {
2827 xloadfonts(usedfont, usedfontsize + arg->i);
2839 if(!(xw.dpy = XOpenDisplay(NULL)))
2840 die("Can't open display\n");
2841 xw.scr = XDefaultScreen(xw.dpy);
2842 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2846 die("Could not init fontconfig.\n");
2848 usedfont = (opt_font == NULL)? font : opt_font;
2849 xloadfonts(usedfont, 0);
2852 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2855 /* adjust fixed window geometry */
2857 sw = DisplayWidth(xw.dpy, xw.scr);
2858 sh = DisplayHeight(xw.dpy, xw.scr);
2860 xw.fx = sw + xw.fx - xw.fw - 1;
2862 xw.fy = sh + xw.fy - xw.fh - 1;
2867 /* window - default size */
2868 xw.h = 2 * borderpx + term.row * xw.ch;
2869 xw.w = 2 * borderpx + term.col * xw.cw;
2875 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2876 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2877 xw.attrs.bit_gravity = NorthWestGravity;
2878 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2879 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2880 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2881 xw.attrs.colormap = xw.cmap;
2883 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2884 XRootWindow(xw.dpy, xw.scr);
2885 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2886 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2887 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
2888 | CWEventMask | CWColormap, &xw.attrs);
2890 memset(&gcvalues, 0, sizeof(gcvalues));
2891 gcvalues.graphics_exposures = False;
2892 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2894 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2895 DefaultDepth(xw.dpy, xw.scr));
2896 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2897 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2899 /* Xft rendering context */
2900 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2903 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2904 XSetLocaleModifiers("@im=local");
2905 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2906 XSetLocaleModifiers("@im=");
2907 if((xw.xim = XOpenIM(xw.dpy,
2908 NULL, NULL, NULL)) == NULL) {
2909 die("XOpenIM failed. Could not open input"
2914 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2915 | XIMStatusNothing, XNClientWindow, xw.win,
2916 XNFocusWindow, xw.win, NULL);
2918 die("XCreateIC failed. Could not obtain input method.\n");
2920 /* white cursor, black outline */
2921 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2922 XDefineCursor(xw.dpy, xw.win, cursor);
2923 XRecolorCursor(xw.dpy, cursor,
2924 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2925 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2927 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2928 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2929 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2932 XMapWindow(xw.dpy, xw.win);
2938 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2939 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2940 width = charlen * xw.cw, xp, i;
2942 int u8fl, u8fblen, u8cblen, doesexist;
2945 Font *font = &dc.font;
2947 FcPattern *fcpattern, *fontpattern;
2948 FcFontSet *fcsets[] = { NULL };
2949 FcCharSet *fccharset;
2950 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
2951 XRenderColor colfg, colbg;
2955 frcflags = FRC_NORMAL;
2957 if(base.mode & ATTR_ITALIC) {
2958 if(base.fg == defaultfg)
2959 base.fg = defaultitalic;
2961 frcflags = FRC_ITALIC;
2962 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2963 if(base.fg == defaultfg)
2964 base.fg = defaultitalic;
2966 frcflags = FRC_ITALICBOLD;
2967 } else if(base.mode & ATTR_UNDERLINE) {
2968 if(base.fg == defaultfg)
2969 base.fg = defaultunderline;
2971 if(IS_TRUECOL(base.fg)) {
2972 colfg.red = TRUERED(base.fg);
2973 colfg.green = TRUEGREEN(base.fg);
2974 colfg.blue = TRUEBLUE(base.fg);
2975 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
2978 fg = &dc.col[base.fg];
2981 if(IS_TRUECOL(base.bg)) {
2982 colbg.green = TRUEGREEN(base.bg);
2983 colbg.red = TRUERED(base.bg);
2984 colbg.blue = TRUEBLUE(base.bg);
2985 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
2988 bg = &dc.col[base.bg];
2993 if(base.mode & ATTR_BOLD) {
2994 if(BETWEEN(base.fg, 0, 7)) {
2995 /* basic system colors */
2996 fg = &dc.col[base.fg + 8];
2997 } else if(BETWEEN(base.fg, 16, 195)) {
2999 fg = &dc.col[base.fg + 36];
3000 } else if(BETWEEN(base.fg, 232, 251)) {
3002 fg = &dc.col[base.fg + 4];
3005 * Those ranges will not be brightened:
3006 * 8 - 15 – bright system colors
3007 * 196 - 231 – highest 256 color cube
3008 * 252 - 255 – brightest colors in greyscale
3011 frcflags = FRC_BOLD;
3014 if(IS_SET(MODE_REVERSE)) {
3015 if(fg == &dc.col[defaultfg]) {
3016 fg = &dc.col[defaultbg];
3018 colfg.red = ~fg->color.red;
3019 colfg.green = ~fg->color.green;
3020 colfg.blue = ~fg->color.blue;
3021 colfg.alpha = fg->color.alpha;
3022 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3026 if(bg == &dc.col[defaultbg]) {
3027 bg = &dc.col[defaultfg];
3029 colbg.red = ~bg->color.red;
3030 colbg.green = ~bg->color.green;
3031 colbg.blue = ~bg->color.blue;
3032 colbg.alpha = bg->color.alpha;
3033 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3038 if(base.mode & ATTR_REVERSE) {
3044 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3047 /* Intelligent cleaning up of the borders. */
3049 xclear(0, (y == 0)? 0 : winy, borderpx,
3050 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3052 if(x + charlen >= term.col) {
3053 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3054 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3057 xclear(winx, 0, winx + width, borderpx);
3059 xclear(winx, winy + xw.ch, winx + width, xw.h);
3061 /* Clean up the region we want to draw to. */
3062 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3064 /* Set the clip region because Xft is sometimes dirty. */
3069 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3071 for(xp = winx; bytelen > 0;) {
3073 * Search for the range in the to be printed string of glyphs
3074 * that are in the main font. Then print that range. If
3075 * some glyph is found that is not in the font, do the
3081 oneatatime = font->width != xw.cw;
3084 u8cblen = utf8decode(s, &u8char);
3088 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3089 if(oneatatime || !doesexist || bytelen <= 0) {
3090 if(oneatatime || bytelen <= 0) {
3098 XftDrawStringUtf8(xw.draw, fg,
3100 winy + font->ascent,
3118 /* Search the font cache. */
3119 for(i = 0; i < frclen; i++) {
3120 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3121 && frc[i].flags == frcflags) {
3126 /* Nothing was found. */
3130 fcsets[0] = font->set;
3133 * Nothing was found in the cache. Now use
3134 * some dozen of Fontconfig calls to get the
3135 * font for one single character.
3137 fcpattern = FcPatternDuplicate(font->pattern);
3138 fccharset = FcCharSetCreate();
3140 FcCharSetAddChar(fccharset, u8char);
3141 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3143 FcPatternAddBool(fcpattern, FC_SCALABLE,
3146 FcConfigSubstitute(0, fcpattern,
3148 FcDefaultSubstitute(fcpattern);
3150 fontpattern = FcFontSetMatch(0, fcsets,
3151 FcTrue, fcpattern, &fcres);
3154 * Overwrite or create the new cache entry.
3156 if(frclen >= LEN(frc)) {
3157 frclen = LEN(frc) - 1;
3158 XftFontClose(xw.dpy, frc[frclen].font);
3161 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3163 frc[frclen].flags = frcflags;
3168 FcPatternDestroy(fcpattern);
3169 FcCharSetDestroy(fccharset);
3172 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3173 xp, winy + frc[i].font->ascent,
3174 (FcChar8 *)u8c, u8cblen);
3180 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3181 winy + font->ascent, (FcChar8 *)s, bytelen);
3184 if(base.mode & ATTR_UNDERLINE) {
3185 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3189 /* Reset clip to none. */
3190 XftDrawSetClip(xw.draw, 0);
3195 static int oldx = 0, oldy = 0;
3197 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3199 LIMIT(oldx, 0, term.col-1);
3200 LIMIT(oldy, 0, term.row-1);
3202 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3204 /* remove the old cursor */
3205 sl = utf8size(term.line[oldy][oldx].c);
3206 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3209 /* draw the new one */
3210 if(!(IS_SET(MODE_HIDE))) {
3211 if(xw.state & WIN_FOCUSED) {
3212 if(IS_SET(MODE_REVERSE)) {
3213 g.mode |= ATTR_REVERSE;
3219 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
3221 XftDrawRect(xw.draw, &dc.col[defaultcs],
3222 borderpx + term.c.x * xw.cw,
3223 borderpx + term.c.y * xw.ch,
3225 XftDrawRect(xw.draw, &dc.col[defaultcs],
3226 borderpx + term.c.x * xw.cw,
3227 borderpx + term.c.y * xw.ch,
3229 XftDrawRect(xw.draw, &dc.col[defaultcs],
3230 borderpx + (term.c.x + 1) * xw.cw - 1,
3231 borderpx + term.c.y * xw.ch,
3233 XftDrawRect(xw.draw, &dc.col[defaultcs],
3234 borderpx + term.c.x * xw.cw,
3235 borderpx + (term.c.y + 1) * xw.ch - 1,
3238 oldx = term.c.x, oldy = term.c.y;
3244 xsettitle(char *p) {
3247 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3249 XSetWMName(xw.dpy, xw.win, &prop);
3255 xsettitle(opt_title ? opt_title : "st");
3259 redraw(int timeout) {
3260 struct timespec tv = {0, timeout * 1000};
3266 nanosleep(&tv, NULL);
3267 XSync(xw.dpy, False); /* necessary for a good tput flash */
3273 drawregion(0, 0, term.col, term.row);
3274 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3276 XSetForeground(xw.dpy, dc.gc,
3277 dc.col[IS_SET(MODE_REVERSE)?
3278 defaultfg : defaultbg].pixel);
3282 drawregion(int x1, int y1, int x2, int y2) {
3283 int ic, ib, x, y, ox, sl;
3285 char buf[DRAW_BUF_SIZ];
3286 bool ena_sel = sel.ob.x != -1;
3288 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3291 if(!(xw.state & WIN_VISIBLE))
3294 for(y = y1; y < y2; y++) {
3298 xtermclear(0, y, term.col, y);
3300 base = term.line[y][0];
3302 for(x = x1; x < x2; x++) {
3303 new = term.line[y][x];
3304 if(ena_sel && selected(x, y))
3305 new.mode ^= ATTR_REVERSE;
3306 if(ib > 0 && (ATTRCMP(base, new)
3307 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3308 xdraws(buf, base, ox, y, ic, ib);
3316 sl = utf8size(new.c);
3317 memcpy(buf+ib, new.c, sl);
3322 xdraws(buf, base, ox, y, ic, ib);
3328 expose(XEvent *ev) {
3329 XExposeEvent *e = &ev->xexpose;
3331 if(xw.state & WIN_REDRAW) {
3333 xw.state &= ~WIN_REDRAW;
3339 visibility(XEvent *ev) {
3340 XVisibilityEvent *e = &ev->xvisibility;
3342 if(e->state == VisibilityFullyObscured) {
3343 xw.state &= ~WIN_VISIBLE;
3344 } else if(!(xw.state & WIN_VISIBLE)) {
3345 /* need a full redraw for next Expose, not just a buf copy */
3346 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3352 xw.state &= ~WIN_VISIBLE;
3356 xsetpointermotion(int set) {
3357 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3358 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3362 xseturgency(int add) {
3363 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3365 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3366 XSetWMHints(xw.dpy, xw.win, h);
3372 XFocusChangeEvent *e = &ev->xfocus;
3374 if(e->mode == NotifyGrab)
3377 if(ev->type == FocusIn) {
3378 XSetICFocus(xw.xic);
3379 xw.state |= WIN_FOCUSED;
3381 if(IS_SET(MODE_FOCUS))
3382 ttywrite("\033[I", 3);
3384 XUnsetICFocus(xw.xic);
3385 xw.state &= ~WIN_FOCUSED;
3386 if(IS_SET(MODE_FOCUS))
3387 ttywrite("\033[O", 3);
3392 match(uint mask, uint state) {
3393 state &= ~ignoremod;
3395 if(mask == XK_NO_MOD && state)
3397 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3399 if(mask == XK_ANY_MOD)
3401 return state == mask;
3405 numlock(const Arg *dummy) {
3410 kmap(KeySym k, uint state) {
3414 /* Check for mapped keys out of X11 function keys. */
3415 for(i = 0; i < LEN(mappedkeys); i++) {
3416 if(mappedkeys[i] == k)
3419 if(i == LEN(mappedkeys)) {
3420 if((k & 0xFFFF) < 0xFD00)
3424 for(kp = key; kp < key + LEN(key); kp++) {
3428 if(!match(kp->mask, state))
3431 if(kp->appkey > 0) {
3432 if(!IS_SET(MODE_APPKEYPAD))
3434 if(term.numlock && kp->appkey == 2)
3436 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3440 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3442 && !IS_SET(MODE_APPCURSOR))) {
3446 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3447 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3458 kpress(XEvent *ev) {
3459 XKeyEvent *e = &ev->xkey;
3461 char xstr[31], buf[32], *customkey, *cp = buf;
3467 if(IS_SET(MODE_KBDLOCK))
3470 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3471 e->state &= ~Mod2Mask;
3473 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3474 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3475 bp->func(&(bp->arg));
3480 /* 2. custom keys from config.h */
3481 if((customkey = kmap(ksym, e->state))) {
3482 len = strlen(customkey);
3483 memcpy(buf, customkey, len);
3484 /* 3. hardcoded (overrides X lookup) */
3489 if(len == 1 && e->state & Mod1Mask) {
3490 if(IS_SET(MODE_8BIT)) {
3493 ret = utf8encode(&c, cp);
3502 memcpy(cp, xstr, len);
3503 len = cp - buf + len;
3507 if(IS_SET(MODE_ECHO))
3513 cmessage(XEvent *e) {
3516 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3518 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3519 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3520 xw.state |= WIN_FOCUSED;
3522 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3523 xw.state &= ~WIN_FOCUSED;
3525 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3526 /* Send SIGHUP to shell */
3533 cresize(int width, int height) {
3541 col = (xw.w - 2 * borderpx) / xw.cw;
3542 row = (xw.h - 2 * borderpx) / xw.ch;
3551 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3554 cresize(e->xconfigure.width, e->xconfigure.height);
3560 int w = xw.w, h = xw.h;
3562 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3563 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3565 /* Waiting for window mapping */
3567 XNextEvent(xw.dpy, &ev);
3568 if(ev.type == ConfigureNotify) {
3569 w = ev.xconfigure.width;
3570 h = ev.xconfigure.height;
3571 } else if(ev.type == MapNotify) {
3579 cresize(xw.fw, xw.fh);
3582 gettimeofday(&lastblink, NULL);
3583 gettimeofday(&last, NULL);
3585 for(xev = actionfps;;) {
3587 FD_SET(cmdfd, &rfd);
3590 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3593 die("select failed: %s\n", SERRNO);
3595 if(FD_ISSET(cmdfd, &rfd)) {
3598 blinkset = tattrset(ATTR_BLINK);
3600 MODBIT(term.mode, 0, MODE_BLINK);
3604 if(FD_ISSET(xfd, &rfd))
3607 gettimeofday(&now, NULL);
3608 drawtimeout.tv_sec = 0;
3609 drawtimeout.tv_usec = (1000/xfps) * 1000;
3613 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3614 tsetdirtattr(ATTR_BLINK);
3615 term.mode ^= MODE_BLINK;
3616 gettimeofday(&lastblink, NULL);
3619 if(TIMEDIFF(now, last) \
3620 > (xev? (1000/xfps) : (1000/actionfps))) {
3626 while(XPending(xw.dpy)) {
3627 XNextEvent(xw.dpy, &ev);
3628 if(XFilterEvent(&ev, None))
3630 if(handler[ev.type])
3631 (handler[ev.type])(&ev);
3637 if(xev && !FD_ISSET(xfd, &rfd))
3639 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3641 if(TIMEDIFF(now, lastblink) \
3643 drawtimeout.tv_usec = 1;
3645 drawtimeout.tv_usec = (1000 * \
3660 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3661 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3662 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3666 main(int argc, char *argv[]) {
3671 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3676 allowaltscreen = false;
3679 opt_class = EARGF(usage());
3682 /* eat all remaining arguments */
3685 if(argv[1] != NULL && opt_title == NULL) {
3686 titles = strdup(argv[1]);
3687 opt_title = basename(titles);
3692 opt_font = EARGF(usage());
3695 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3700 if(bitm & WidthValue)
3702 if(bitm & HeightValue)
3704 if(bitm & XNegative && xw.fx == 0)
3706 if(bitm & YNegative && xw.fy == 0)
3709 if(xw.fh != 0 && xw.fw != 0)
3713 opt_io = EARGF(usage());
3716 opt_title = EARGF(usage());
3719 opt_embed = EARGF(usage());
3727 setlocale(LC_CTYPE, "");
3728 XSetLocaleModifiers("");