1 /* See LICENSE for licence details. */
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
22 #include <X11/Xatom.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/Xft/Xft.h>
28 #include <fontconfig/fontconfig.h>
36 #define Draw XftDraw *
37 #define Colour XftColor
38 #define Colourmap Colormap
39 #define Rectangle XRectangle
43 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
45 #elif defined(__FreeBSD__) || defined(__DragonFly__)
51 #define XEMBED_FOCUS_IN 4
52 #define XEMBED_FOCUS_OUT 5
56 #define ESC_BUF_SIZ (128*UTF_SIZ)
57 #define ESC_ARG_SIZ 16
58 #define STR_BUF_SIZ ESC_BUF_SIZ
59 #define STR_ARG_SIZ ESC_ARG_SIZ
60 #define DRAW_BUF_SIZ 20*1024
61 #define XK_ANY_MOD UINT_MAX
63 #define XK_SWITCH_MOD (1<<13)
65 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
68 #define SERRNO strerror(errno)
69 #define MIN(a, b) ((a) < (b) ? (a) : (b))
70 #define MAX(a, b) ((a) < (b) ? (b) : (a))
71 #define LEN(a) (sizeof(a) / sizeof(a[0]))
72 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
73 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
74 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
75 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
76 #define IS_SET(flag) ((term.mode & (flag)) != 0)
77 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
79 #define VT102ID "\033[?6c"
81 enum glyph_attribute {
92 enum cursor_movement {
110 MODE_MOUSEMOTION = 64,
116 MODE_APPCURSOR = 2048,
117 MODE_MOUSESGR = 4096,
126 ESC_STR = 4, /* DSC, OSC, PM, APC */
128 ESC_STR_END = 16, /* a final string was encountered */
129 ESC_TEST = 32, /* Enter in test mode */
138 enum selection_type {
143 enum selection_snap {
150 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
152 typedef unsigned char uchar;
153 typedef unsigned int uint;
154 typedef unsigned long ulong;
155 typedef unsigned short ushort;
158 char c[UTF_SIZ]; /* character code */
159 uchar mode; /* attribute flags */
160 ushort fg; /* foreground */
161 ushort bg; /* background */
167 Glyph attr; /* current char attributes */
173 /* CSI Escape sequence structs */
174 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
176 char buf[ESC_BUF_SIZ]; /* raw string */
177 int len; /* raw string length */
179 int arg[ESC_ARG_SIZ];
180 int narg; /* nb of args */
184 /* STR Escape sequence structs */
185 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
187 char type; /* ESC type ... */
188 char buf[STR_BUF_SIZ]; /* raw string */
189 int len; /* raw string length */
190 char *args[STR_ARG_SIZ];
191 int narg; /* nb of args */
194 /* Internal representation of the screen */
196 int row; /* nb row */
197 int col; /* nb col */
198 Line *line; /* screen */
199 Line *alt; /* alternate screen */
200 bool *dirty; /* dirtyness of lines */
201 TCursor c; /* cursor */
202 int top; /* top scroll limit */
203 int bot; /* bottom scroll limit */
204 int mode; /* terminal mode flags */
205 int esc; /* escape state flags */
206 bool numlock; /* lock numbers in keyboard */
210 /* Purely graphic info */
216 Atom xembed, wmdeletewin;
222 bool isfixed; /* is fixed geometry? */
223 int fx, fy, fw, fh; /* fixed geometry */
224 int tw, th; /* tty width and height */
225 int w, h; /* window width and height */
226 int ch; /* char height */
227 int cw; /* char width */
228 char state; /* focus, redraw, visible */
241 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
242 signed char appkey; /* application keypad */
243 signed char appcursor; /* application cursor */
244 signed char crlf; /* crlf mode */
247 /* TODO: use better name for vars... */
260 struct timeval tclick1;
261 struct timeval tclick2;
274 void (*func)(const Arg *);
278 /* function definitions used in config.h */
279 static void clippaste(const Arg *);
280 static void numlock(const Arg *);
281 static void selpaste(const Arg *);
282 static void xzoom(const Arg *);
284 /* Config.h for applying patches and the configuration. */
300 /* Drawing Context */
302 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
303 Font font, bfont, ifont, ibfont;
307 static void die(const char *, ...);
308 static void draw(void);
309 static void redraw(int);
310 static void drawregion(int, int, int, int);
311 static void execsh(void);
312 static void sigchld(int);
313 static void run(void);
315 static void csidump(void);
316 static void csihandle(void);
317 static void csiparse(void);
318 static void csireset(void);
319 static void strdump(void);
320 static void strhandle(void);
321 static void strparse(void);
322 static void strreset(void);
324 static int tattrset(int);
325 static void tclearregion(int, int, int, int);
326 static void tcursor(int);
327 static void tdeletechar(int);
328 static void tdeleteline(int);
329 static void tinsertblank(int);
330 static void tinsertblankline(int);
331 static void tmoveto(int, int);
332 static void tmoveato(int x, int y);
333 static void tnew(int, int);
334 static void tnewline(int);
335 static void tputtab(bool);
336 static void tputc(char *, int);
337 static void treset(void);
338 static int tresize(int, int);
339 static void tscrollup(int, int);
340 static void tscrolldown(int, int);
341 static void tsetattr(int*, int);
342 static void tsetchar(char *, Glyph *, int, int);
343 static void tsetscroll(int, int);
344 static void tswapscreen(void);
345 static void tsetdirt(int, int);
346 static void tsetdirtattr(int);
347 static void tsetmode(bool, bool, int *, int);
348 static void tfulldirt(void);
349 static void techo(char *, int);
351 static inline bool match(uint, uint);
352 static void ttynew(void);
353 static void ttyread(void);
354 static void ttyresize(void);
355 static void ttywrite(const char *, size_t);
357 static void xdraws(char *, Glyph, int, int, int, int);
358 static void xhints(void);
359 static void xclear(int, int, int, int);
360 static void xdrawcursor(void);
361 static void xinit(void);
362 static void xloadcols(void);
363 static int xsetcolorname(int, const char *);
364 static int xloadfont(Font *, FcPattern *);
365 static void xloadfonts(char *, int);
366 static void xsettitle(char *);
367 static void xresettitle(void);
368 static void xseturgency(int);
369 static void xsetsel(char*);
370 static void xtermclear(int, int, int, int);
371 static void xunloadfonts(void);
372 static void xresize(int, int);
374 static void expose(XEvent *);
375 static void visibility(XEvent *);
376 static void unmap(XEvent *);
377 static char *kmap(KeySym, uint);
378 static void kpress(XEvent *);
379 static void cmessage(XEvent *);
380 static void cresize(int, int);
381 static void resize(XEvent *);
382 static void focus(XEvent *);
383 static void brelease(XEvent *);
384 static void bpress(XEvent *);
385 static void bmotion(XEvent *);
386 static void selnotify(XEvent *);
387 static void selclear(XEvent *);
388 static void selrequest(XEvent *);
390 static void selinit(void);
391 static inline bool selected(int, int);
392 static void selcopy(void);
393 static void selscroll(int, int);
394 static void selsnap(int, int *, int *, int);
396 static int utf8decode(char *, long *);
397 static int utf8encode(long *, char *);
398 static int utf8size(char *);
399 static int isfullutf8(char *, int);
401 static ssize_t xwrite(int, char *, size_t);
402 static void *xmalloc(size_t);
403 static void *xrealloc(void *, size_t);
404 static void *xcalloc(size_t, size_t);
406 static void (*handler[LASTEvent])(XEvent *) = {
408 [ClientMessage] = cmessage,
409 [ConfigureNotify] = resize,
410 [VisibilityNotify] = visibility,
411 [UnmapNotify] = unmap,
415 [MotionNotify] = bmotion,
416 [ButtonPress] = bpress,
417 [ButtonRelease] = brelease,
418 [SelectionClear] = selclear,
419 [SelectionNotify] = selnotify,
420 [SelectionRequest] = selrequest,
427 static CSIEscape csiescseq;
428 static STREscape strescseq;
431 static Selection sel;
432 static int iofd = -1;
433 static char **opt_cmd = NULL;
434 static char *opt_io = NULL;
435 static char *opt_title = NULL;
436 static char *opt_embed = NULL;
437 static char *opt_class = NULL;
438 static char *opt_font = NULL;
440 static char *usedfont = NULL;
441 static int usedfontsize = 0;
443 /* Font Ring Cache */
458 * Fontcache is a ring buffer, with frccur as current position and frclen as
459 * the current length of used elements.
462 static Fontcache frc[1024];
463 static int frccur = -1, frclen = 0;
466 xwrite(int fd, char *s, size_t len) {
470 ssize_t r = write(fd, s, len);
480 xmalloc(size_t len) {
481 void *p = malloc(len);
484 die("Out of memory\n");
490 xrealloc(void *p, size_t len) {
491 if((p = realloc(p, len)) == NULL)
492 die("Out of memory\n");
498 xcalloc(size_t nmemb, size_t size) {
499 void *p = calloc(nmemb, size);
502 die("Out of memory\n");
508 utf8decode(char *s, long *u) {
514 if(~c & B7) { /* 0xxxxxxx */
517 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
518 *u = c&(B4|B3|B2|B1|B0);
520 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
521 *u = c&(B3|B2|B1|B0);
523 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
530 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
532 if((c & (B7|B6)) != B7) /* 10xxxxxx */
535 *u |= c & (B5|B4|B3|B2|B1|B0);
538 if((n == 1 && *u < 0x80) ||
539 (n == 2 && *u < 0x800) ||
540 (n == 3 && *u < 0x10000) ||
541 (*u >= 0xD800 && *u <= 0xDFFF)) {
553 utf8encode(long *u, char *s) {
561 *sp = uc; /* 0xxxxxxx */
563 } else if(*u < 0x800) {
564 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
566 } else if(uc < 0x10000) {
567 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
569 } else if(uc <= 0x10FFFF) {
570 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
576 for(i=n,++sp; i>0; --i,++sp)
577 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
589 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
590 UTF-8 otherwise return 0 */
592 isfullutf8(char *s, int b) {
600 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
602 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
604 ((b == 2) && (*c2&(B7|B6)) == B7))) {
606 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
608 ((b == 2) && (*c2&(B7|B6)) == B7) ||
609 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
622 } else if((c&(B7|B6|B5)) == (B7|B6)) {
624 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
633 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
634 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
638 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
639 if(sel.xtarget == None)
640 sel.xtarget = XA_STRING;
648 return LIMIT(x, 0, term.col-1);
656 return LIMIT(y, 0, term.row-1);
660 selected(int x, int y) {
663 if(sel.ey == y && sel.by == y) {
664 bx = MIN(sel.bx, sel.ex);
665 ex = MAX(sel.bx, sel.ex);
667 return BETWEEN(x, bx, ex);
670 if(sel.type == SEL_RECTANGULAR) {
671 return ((sel.b.y <= y && y <= sel.e.y)
672 && (sel.b.x <= x && x <= sel.e.x));
674 return ((sel.b.y < y && y < sel.e.y)
675 || (y == sel.e.y && x <= sel.e.x))
676 || (y == sel.b.y && x >= sel.b.x
677 && (x <= sel.e.x || sel.b.y != sel.e.y));
681 selsnap(int mode, int *x, int *y, int direction) {
685 * Snap around if the word wraps around at the end or
686 * beginning of a line.
689 if(direction < 0 && *x <= 0) {
690 if(*y > 0 && term.line[*y - 1][term.col-1].mode
698 if(direction > 0 && *x >= term.col-1) {
699 if(*y < term.row-1 && term.line[*y][*x].mode
708 if(term.line[*y][*x + direction].c[0] == ' ')
716 * Snap around if the the previous line or the current one
717 * has set ATTR_WRAP at its end. Then the whole next or
718 * previous line will be selected.
720 *x = (direction < 0) ? 0 : term.col - 1;
721 if(direction < 0 && *y > 0) {
722 for(; *y > 0; *y += direction) {
723 if(!(term.line[*y-1][term.col-1].mode
728 } else if(direction > 0 && *y < term.row-1) {
729 for(; *y < term.row; *y += direction) {
730 if(!(term.line[*y][term.col-1].mode
743 getbuttoninfo(XEvent *e) {
745 uint state = e->xbutton.state &~Button1Mask;
747 sel.alt = IS_SET(MODE_ALTSCREEN);
749 sel.ex = x2col(e->xbutton.x);
750 sel.ey = y2row(e->xbutton.y);
753 || (sel.by == sel.ey && sel.bx < sel.ex)) {
754 selsnap(sel.snap, &sel.bx, &sel.by, -1);
755 selsnap(sel.snap, &sel.ex, &sel.ey, +1);
757 selsnap(sel.snap, &sel.ex, &sel.ey, -1);
758 selsnap(sel.snap, &sel.bx, &sel.by, +1);
761 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
762 sel.b.y = MIN(sel.by, sel.ey);
763 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
764 sel.e.y = MAX(sel.by, sel.ey);
766 sel.type = SEL_REGULAR;
767 for(type = 1; type < LEN(selmasks); ++type) {
768 if(match(selmasks[type], state)) {
776 mousereport(XEvent *e) {
777 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
778 button = e->xbutton.button, state = e->xbutton.state,
781 static int ob, ox, oy;
784 if(e->xbutton.type == MotionNotify) {
785 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
789 } else if(!IS_SET(MODE_MOUSESGR)
790 && (e->xbutton.type == ButtonRelease
791 || button == AnyButton)) {
797 if(e->xbutton.type == ButtonPress) {
803 button += (state & ShiftMask ? 4 : 0)
804 + (state & Mod4Mask ? 8 : 0)
805 + (state & ControlMask ? 16 : 0);
808 if(IS_SET(MODE_MOUSESGR)) {
809 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
811 e->xbutton.type == ButtonRelease ? 'm' : 'M');
812 } else if(x < 223 && y < 223) {
813 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
814 32+button, 32+x+1, 32+y+1);
827 if(IS_SET(MODE_MOUSE)) {
832 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
833 if(e->xbutton.button == mk->b
834 && match(mk->mask, e->xbutton.state)) {
835 ttywrite(mk->s, strlen(mk->s));
836 if(IS_SET(MODE_ECHO))
837 techo(mk->s, strlen(mk->s));
842 if(e->xbutton.button == Button1) {
843 gettimeofday(&now, NULL);
845 /* Clear previous selection, logically and visually. */
848 tsetdirt(sel.b.y, sel.e.y);
852 sel.type = SEL_REGULAR;
853 sel.ex = sel.bx = x2col(e->xbutton.x);
854 sel.ey = sel.by = y2row(e->xbutton.y);
857 * If the user clicks below predefined timeouts specific
858 * snapping behaviour is exposed.
860 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
861 sel.snap = SNAP_LINE;
862 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
863 sel.snap = SNAP_WORD;
867 selsnap(sel.snap, &sel.bx, &sel.by, -1);
868 selsnap(sel.snap, &sel.ex, &sel.ey, +1);
875 * Draw selection, unless it's regular and we don't want to
876 * make clicks visible
880 tsetdirt(sel.b.y, sel.e.y);
883 sel.tclick2 = sel.tclick1;
891 int x, y, bufsize, size;
897 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
898 ptr = str = xmalloc(bufsize);
900 /* append every set & selected glyph to the selection */
901 for(y = sel.b.y; y < sel.e.y + 1; y++) {
902 gp = &term.line[y][0];
903 last = gp + term.col;
905 while(--last >= gp && !(selected(last - gp, y) && \
906 strcmp(last->c, " ") != 0))
909 for(x = 0; gp <= last; x++, ++gp) {
913 size = utf8size(gp->c);
914 memcpy(ptr, gp->c, size);
919 * Copy and pasting of line endings is inconsistent
920 * in the inconsistent terminal and GUI world.
921 * The best solution seems like to produce '\n' when
922 * something is copied from st and convert '\n' to
923 * '\r', when something to be pasted is received by
925 * FIXME: Fix the computer world.
927 if(y < sel.e.y && !((gp-1)->mode & ATTR_WRAP))
936 selnotify(XEvent *e) {
937 ulong nitems, ofs, rem;
939 uchar *data, *last, *repl;
944 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
945 False, AnyPropertyType, &type, &format,
946 &nitems, &rem, &data)) {
947 fprintf(stderr, "Clipboard allocation failed\n");
952 * As seen in selcopy:
953 * Line endings are inconsistent in the terminal and GUI world
954 * copy and pasting. When receiving some selection data,
955 * replace all '\n' with '\r'.
956 * FIXME: Fix the computer world.
959 last = data + nitems * format / 8;
960 while((repl = memchr(repl, '\n', last - repl))) {
964 ttywrite((const char *)data, nitems * format / 8);
966 /* number of 32-bit chunks returned */
967 ofs += nitems * format / 32;
972 selpaste(const Arg *dummy) {
973 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
974 xw.win, CurrentTime);
978 clippaste(const Arg *dummy) {
981 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
982 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
983 xw.win, CurrentTime);
987 selclear(XEvent *e) {
991 tsetdirt(sel.b.y, sel.e.y);
995 selrequest(XEvent *e) {
996 XSelectionRequestEvent *xsre;
998 Atom xa_targets, string;
1000 xsre = (XSelectionRequestEvent *) e;
1001 xev.type = SelectionNotify;
1002 xev.requestor = xsre->requestor;
1003 xev.selection = xsre->selection;
1004 xev.target = xsre->target;
1005 xev.time = xsre->time;
1007 xev.property = None;
1009 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1010 if(xsre->target == xa_targets) {
1011 /* respond with the supported type */
1012 string = sel.xtarget;
1013 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1014 XA_ATOM, 32, PropModeReplace,
1015 (uchar *) &string, 1);
1016 xev.property = xsre->property;
1017 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1018 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1019 xsre->target, 8, PropModeReplace,
1020 (uchar *) sel.clip, strlen(sel.clip));
1021 xev.property = xsre->property;
1024 /* all done, send a notification to the listener */
1025 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1026 fprintf(stderr, "Error sending SelectionNotify event\n");
1030 xsetsel(char *str) {
1031 /* register the selection for both the clipboard and the primary */
1037 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1039 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1040 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1044 brelease(XEvent *e) {
1045 if(IS_SET(MODE_MOUSE)) {
1050 if(e->xbutton.button == Button2) {
1052 } else if(e->xbutton.button == Button1) {
1060 term.dirty[sel.ey] = 1;
1065 bmotion(XEvent *e) {
1066 int oldey, oldex, oldsby, oldsey;
1068 if(IS_SET(MODE_MOUSE)) {
1083 if(oldey != sel.ey || oldex != sel.ex) {
1084 tsetdirt(MIN(sel.b.y, oldsby), MAX(sel.e.y, oldsey));
1089 die(const char *errstr, ...) {
1092 va_start(ap, errstr);
1093 vfprintf(stderr, errstr, ap);
1101 char *envshell = getenv("SHELL");
1102 const struct passwd *pass = getpwuid(getuid());
1103 char buf[sizeof(long) * 8 + 1];
1105 unsetenv("COLUMNS");
1107 unsetenv("TERMCAP");
1110 setenv("LOGNAME", pass->pw_name, 1);
1111 setenv("USER", pass->pw_name, 1);
1112 setenv("SHELL", pass->pw_shell, 0);
1113 setenv("HOME", pass->pw_dir, 0);
1116 snprintf(buf, sizeof(buf), "%lu", xw.win);
1117 setenv("WINDOWID", buf, 1);
1119 signal(SIGCHLD, SIG_DFL);
1120 signal(SIGHUP, SIG_DFL);
1121 signal(SIGINT, SIG_DFL);
1122 signal(SIGQUIT, SIG_DFL);
1123 signal(SIGTERM, SIG_DFL);
1124 signal(SIGALRM, SIG_DFL);
1126 DEFAULT(envshell, shell);
1127 setenv("TERM", termname, 1);
1128 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1129 execvp(args[0], args);
1137 if(waitpid(pid, &stat, 0) < 0)
1138 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1140 if(WIFEXITED(stat)) {
1141 exit(WEXITSTATUS(stat));
1150 struct winsize w = {term.row, term.col, 0, 0};
1152 /* seems to work fine on linux, openbsd and freebsd */
1153 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1154 die("openpty failed: %s\n", SERRNO);
1156 switch(pid = fork()) {
1158 die("fork failed\n");
1161 setsid(); /* create a new process group */
1162 dup2(s, STDIN_FILENO);
1163 dup2(s, STDOUT_FILENO);
1164 dup2(s, STDERR_FILENO);
1165 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1166 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1174 signal(SIGCHLD, sigchld);
1176 iofd = (!strcmp(opt_io, "-")) ?
1178 open(opt_io, O_WRONLY | O_CREAT, 0666);
1180 fprintf(stderr, "Error opening %s:%s\n",
1181 opt_io, strerror(errno));
1191 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1193 fprintf(stderr, "\n");
1198 static char buf[BUFSIZ];
1199 static int buflen = 0;
1202 int charsize; /* size of utf8 char in bytes */
1206 /* append read bytes to unprocessed bytes */
1207 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1208 die("Couldn't read from shell: %s\n", SERRNO);
1210 /* process every complete utf8 char */
1213 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1214 charsize = utf8decode(ptr, &utf8c);
1215 utf8encode(&utf8c, s);
1221 /* keep any uncomplete utf8 char for the next call */
1222 memmove(buf, ptr, buflen);
1226 ttywrite(const char *s, size_t n) {
1227 if(write(cmdfd, s, n) == -1)
1228 die("write error on tty: %s\n", SERRNO);
1235 w.ws_row = term.row;
1236 w.ws_col = term.col;
1237 w.ws_xpixel = xw.tw;
1238 w.ws_ypixel = xw.th;
1239 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1240 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1244 tattrset(int attr) {
1247 for(i = 0; i < term.row-1; i++) {
1248 for(j = 0; j < term.col-1; j++) {
1249 if(term.line[i][j].mode & attr)
1258 tsetdirt(int top, int bot) {
1261 LIMIT(top, 0, term.row-1);
1262 LIMIT(bot, 0, term.row-1);
1264 for(i = top; i <= bot; i++)
1269 tsetdirtattr(int attr) {
1272 for(i = 0; i < term.row-1; i++) {
1273 for(j = 0; j < term.col-1; j++) {
1274 if(term.line[i][j].mode & attr) {
1284 tsetdirt(0, term.row-1);
1291 if(mode == CURSOR_SAVE) {
1293 } else if(mode == CURSOR_LOAD) {
1303 term.c = (TCursor){{
1307 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1309 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1310 for(i = tabspaces; i < term.col; i += tabspaces)
1313 term.bot = term.row - 1;
1314 term.mode = MODE_WRAP;
1316 tclearregion(0, 0, term.col-1, term.row-1);
1318 tcursor(CURSOR_SAVE);
1322 tnew(int col, int row) {
1323 memset(&term, 0, sizeof(Term));
1332 Line *tmp = term.line;
1334 term.line = term.alt;
1336 term.mode ^= MODE_ALTSCREEN;
1341 tscrolldown(int orig, int n) {
1345 LIMIT(n, 0, term.bot-orig+1);
1347 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1349 for(i = term.bot; i >= orig+n; i--) {
1350 temp = term.line[i];
1351 term.line[i] = term.line[i-n];
1352 term.line[i-n] = temp;
1355 term.dirty[i-n] = 1;
1362 tscrollup(int orig, int n) {
1365 LIMIT(n, 0, term.bot-orig+1);
1367 tclearregion(0, orig, term.col-1, orig+n-1);
1369 for(i = orig; i <= term.bot-n; i++) {
1370 temp = term.line[i];
1371 term.line[i] = term.line[i+n];
1372 term.line[i+n] = temp;
1375 term.dirty[i+n] = 1;
1378 selscroll(orig, -n);
1382 selscroll(int orig, int n) {
1386 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1387 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1391 if(sel.type == SEL_RECTANGULAR) {
1392 if(sel.by < term.top)
1394 if(sel.ey > term.bot)
1397 if(sel.by < term.top) {
1401 if(sel.ey > term.bot) {
1406 sel.b.y = sel.by, sel.b.x = sel.bx;
1407 sel.e.y = sel.ey, sel.e.x = sel.ex;
1412 tnewline(int first_col) {
1416 tscrollup(term.top, 1);
1420 tmoveto(first_col ? 0 : term.c.x, y);
1425 char *p = csiescseq.buf, *np;
1434 csiescseq.buf[csiescseq.len] = '\0';
1435 while(p < csiescseq.buf+csiescseq.len) {
1437 v = strtol(p, &np, 10);
1440 if(v == LONG_MAX || v == LONG_MIN)
1442 csiescseq.arg[csiescseq.narg++] = v;
1444 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1448 csiescseq.mode = *p;
1451 /* for absolute user moves, when decom is set */
1453 tmoveato(int x, int y) {
1454 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1458 tmoveto(int x, int y) {
1461 if(term.c.state & CURSOR_ORIGIN) {
1466 maxy = term.row - 1;
1468 LIMIT(x, 0, term.col-1);
1469 LIMIT(y, miny, maxy);
1470 term.c.state &= ~CURSOR_WRAPNEXT;
1476 tsetchar(char *c, Glyph *attr, int x, int y) {
1477 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1478 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1479 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1480 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1481 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1482 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1483 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1484 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1485 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1489 * The table is proudly stolen from rxvt.
1491 if(attr->mode & ATTR_GFX) {
1492 if(c[0] >= 0x41 && c[0] <= 0x7e
1493 && vt100_0[c[0] - 0x41]) {
1494 c = vt100_0[c[0] - 0x41];
1499 term.line[y][x] = *attr;
1500 memcpy(term.line[y][x].c, c, UTF_SIZ);
1504 tclearregion(int x1, int y1, int x2, int y2) {
1508 temp = x1, x1 = x2, x2 = temp;
1510 temp = y1, y1 = y2, y2 = temp;
1512 LIMIT(x1, 0, term.col-1);
1513 LIMIT(x2, 0, term.col-1);
1514 LIMIT(y1, 0, term.row-1);
1515 LIMIT(y2, 0, term.row-1);
1517 for(y = y1; y <= y2; y++) {
1519 for(x = x1; x <= x2; x++) {
1522 term.line[y][x] = term.c.attr;
1523 memcpy(term.line[y][x].c, " ", 2);
1529 tdeletechar(int n) {
1530 int src = term.c.x + n;
1532 int size = term.col - src;
1534 term.dirty[term.c.y] = 1;
1536 if(src >= term.col) {
1537 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1541 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1542 size * sizeof(Glyph));
1543 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1547 tinsertblank(int n) {
1550 int size = term.col - dst;
1552 term.dirty[term.c.y] = 1;
1554 if(dst >= term.col) {
1555 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1559 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1560 size * sizeof(Glyph));
1561 tclearregion(src, term.c.y, dst - 1, term.c.y);
1565 tinsertblankline(int n) {
1566 if(term.c.y < term.top || term.c.y > term.bot)
1569 tscrolldown(term.c.y, n);
1573 tdeleteline(int n) {
1574 if(term.c.y < term.top || term.c.y > term.bot)
1577 tscrollup(term.c.y, n);
1581 tsetattr(int *attr, int l) {
1584 for(i = 0; i < l; i++) {
1587 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1588 | ATTR_BOLD | ATTR_ITALIC \
1590 term.c.attr.fg = defaultfg;
1591 term.c.attr.bg = defaultbg;
1594 term.c.attr.mode |= ATTR_BOLD;
1597 term.c.attr.mode |= ATTR_ITALIC;
1600 term.c.attr.mode |= ATTR_UNDERLINE;
1602 case 5: /* slow blink */
1603 case 6: /* rapid blink */
1604 term.c.attr.mode |= ATTR_BLINK;
1607 term.c.attr.mode |= ATTR_REVERSE;
1611 term.c.attr.mode &= ~ATTR_BOLD;
1614 term.c.attr.mode &= ~ATTR_ITALIC;
1617 term.c.attr.mode &= ~ATTR_UNDERLINE;
1621 term.c.attr.mode &= ~ATTR_BLINK;
1624 term.c.attr.mode &= ~ATTR_REVERSE;
1627 if(i + 2 < l && attr[i + 1] == 5) {
1629 if(BETWEEN(attr[i], 0, 255)) {
1630 term.c.attr.fg = attr[i];
1633 "erresc: bad fgcolor %d\n",
1638 "erresc(38): gfx attr %d unknown\n",
1643 term.c.attr.fg = defaultfg;
1646 if(i + 2 < l && attr[i + 1] == 5) {
1648 if(BETWEEN(attr[i], 0, 255)) {
1649 term.c.attr.bg = attr[i];
1652 "erresc: bad bgcolor %d\n",
1657 "erresc(48): gfx attr %d unknown\n",
1662 term.c.attr.bg = defaultbg;
1665 if(BETWEEN(attr[i], 30, 37)) {
1666 term.c.attr.fg = attr[i] - 30;
1667 } else if(BETWEEN(attr[i], 40, 47)) {
1668 term.c.attr.bg = attr[i] - 40;
1669 } else if(BETWEEN(attr[i], 90, 97)) {
1670 term.c.attr.fg = attr[i] - 90 + 8;
1671 } else if(BETWEEN(attr[i], 100, 107)) {
1672 term.c.attr.bg = attr[i] - 100 + 8;
1675 "erresc(default): gfx attr %d unknown\n",
1676 attr[i]), csidump();
1684 tsetscroll(int t, int b) {
1687 LIMIT(t, 0, term.row-1);
1688 LIMIT(b, 0, term.row-1);
1698 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1701 tsetmode(bool priv, bool set, int *args, int narg) {
1705 for(lim = args + narg; args < lim; ++args) {
1709 case 1: /* DECCKM -- Cursor key */
1710 MODBIT(term.mode, set, MODE_APPCURSOR);
1712 case 5: /* DECSCNM -- Reverse video */
1714 MODBIT(term.mode, set, MODE_REVERSE);
1715 if(mode != term.mode)
1716 redraw(REDRAW_TIMEOUT);
1718 case 6: /* DECOM -- Origin */
1719 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1722 case 7: /* DECAWM -- Auto wrap */
1723 MODBIT(term.mode, set, MODE_WRAP);
1725 case 0: /* Error (IGNORED) */
1726 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1727 case 3: /* DECCOLM -- Column (IGNORED) */
1728 case 4: /* DECSCLM -- Scroll (IGNORED) */
1729 case 8: /* DECARM -- Auto repeat (IGNORED) */
1730 case 18: /* DECPFF -- Printer feed (IGNORED) */
1731 case 19: /* DECPEX -- Printer extent (IGNORED) */
1732 case 42: /* DECNRCM -- National characters (IGNORED) */
1733 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1735 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1736 MODBIT(term.mode, !set, MODE_HIDE);
1738 case 1000: /* 1000,1002: enable xterm mouse report */
1739 MODBIT(term.mode, set, MODE_MOUSEBTN);
1740 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1743 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1744 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1747 MODBIT(term.mode, set, MODE_MOUSESGR);
1750 MODBIT(term.mode, set, MODE_8BIT);
1752 case 1049: /* = 1047 and 1048 */
1755 if (!allowaltscreen)
1758 alt = IS_SET(MODE_ALTSCREEN);
1760 tclearregion(0, 0, term.col-1,
1763 if(set ^ alt) /* set is always 1 or 0 */
1769 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1773 "erresc: unknown private set/reset mode %d\n",
1779 case 0: /* Error (IGNORED) */
1781 case 2: /* KAM -- keyboard action */
1782 MODBIT(term.mode, set, MODE_KBDLOCK);
1784 case 4: /* IRM -- Insertion-replacement */
1785 MODBIT(term.mode, set, MODE_INSERT);
1787 case 12: /* SRM -- Send/Receive */
1788 MODBIT(term.mode, !set, MODE_ECHO);
1790 case 20: /* LNM -- Linefeed/new line */
1791 MODBIT(term.mode, set, MODE_CRLF);
1795 "erresc: unknown set/reset mode %d\n",
1807 switch(csiescseq.mode) {
1810 fprintf(stderr, "erresc: unknown csi ");
1814 case '@': /* ICH -- Insert <n> blank char */
1815 DEFAULT(csiescseq.arg[0], 1);
1816 tinsertblank(csiescseq.arg[0]);
1818 case 'A': /* CUU -- Cursor <n> Up */
1819 DEFAULT(csiescseq.arg[0], 1);
1820 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1822 case 'B': /* CUD -- Cursor <n> Down */
1823 case 'e': /* VPR --Cursor <n> Down */
1824 DEFAULT(csiescseq.arg[0], 1);
1825 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1827 case 'c': /* DA -- Device Attributes */
1828 if(csiescseq.arg[0] == 0)
1829 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1831 case 'C': /* CUF -- Cursor <n> Forward */
1832 case 'a': /* HPR -- Cursor <n> Forward */
1833 DEFAULT(csiescseq.arg[0], 1);
1834 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1836 case 'D': /* CUB -- Cursor <n> Backward */
1837 DEFAULT(csiescseq.arg[0], 1);
1838 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1840 case 'E': /* CNL -- Cursor <n> Down and first col */
1841 DEFAULT(csiescseq.arg[0], 1);
1842 tmoveto(0, term.c.y+csiescseq.arg[0]);
1844 case 'F': /* CPL -- Cursor <n> Up and first col */
1845 DEFAULT(csiescseq.arg[0], 1);
1846 tmoveto(0, term.c.y-csiescseq.arg[0]);
1848 case 'g': /* TBC -- Tabulation clear */
1849 switch(csiescseq.arg[0]) {
1850 case 0: /* clear current tab stop */
1851 term.tabs[term.c.x] = 0;
1853 case 3: /* clear all the tabs */
1854 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1860 case 'G': /* CHA -- Move to <col> */
1862 DEFAULT(csiescseq.arg[0], 1);
1863 tmoveto(csiescseq.arg[0]-1, term.c.y);
1865 case 'H': /* CUP -- Move to <row> <col> */
1867 DEFAULT(csiescseq.arg[0], 1);
1868 DEFAULT(csiescseq.arg[1], 1);
1869 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1871 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1872 DEFAULT(csiescseq.arg[0], 1);
1873 while(csiescseq.arg[0]--)
1876 case 'J': /* ED -- Clear screen */
1878 switch(csiescseq.arg[0]) {
1880 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1881 if(term.c.y < term.row-1) {
1882 tclearregion(0, term.c.y+1, term.col-1,
1888 tclearregion(0, 0, term.col-1, term.c.y-1);
1889 tclearregion(0, term.c.y, term.c.x, term.c.y);
1892 tclearregion(0, 0, term.col-1, term.row-1);
1898 case 'K': /* EL -- Clear line */
1899 switch(csiescseq.arg[0]) {
1901 tclearregion(term.c.x, term.c.y, term.col-1,
1905 tclearregion(0, term.c.y, term.c.x, term.c.y);
1908 tclearregion(0, term.c.y, term.col-1, term.c.y);
1912 case 'S': /* SU -- Scroll <n> line up */
1913 DEFAULT(csiescseq.arg[0], 1);
1914 tscrollup(term.top, csiescseq.arg[0]);
1916 case 'T': /* SD -- Scroll <n> line down */
1917 DEFAULT(csiescseq.arg[0], 1);
1918 tscrolldown(term.top, csiescseq.arg[0]);
1920 case 'L': /* IL -- Insert <n> blank lines */
1921 DEFAULT(csiescseq.arg[0], 1);
1922 tinsertblankline(csiescseq.arg[0]);
1924 case 'l': /* RM -- Reset Mode */
1925 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1927 case 'M': /* DL -- Delete <n> lines */
1928 DEFAULT(csiescseq.arg[0], 1);
1929 tdeleteline(csiescseq.arg[0]);
1931 case 'X': /* ECH -- Erase <n> char */
1932 DEFAULT(csiescseq.arg[0], 1);
1933 tclearregion(term.c.x, term.c.y,
1934 term.c.x + csiescseq.arg[0] - 1, term.c.y);
1936 case 'P': /* DCH -- Delete <n> char */
1937 DEFAULT(csiescseq.arg[0], 1);
1938 tdeletechar(csiescseq.arg[0]);
1940 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1941 DEFAULT(csiescseq.arg[0], 1);
1942 while(csiescseq.arg[0]--)
1945 case 'd': /* VPA -- Move to <row> */
1946 DEFAULT(csiescseq.arg[0], 1);
1947 tmoveato(term.c.x, csiescseq.arg[0]-1);
1949 case 'h': /* SM -- Set terminal mode */
1950 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1952 case 'm': /* SGR -- Terminal attribute (color) */
1953 tsetattr(csiescseq.arg, csiescseq.narg);
1955 case 'r': /* DECSTBM -- Set Scrolling Region */
1956 if(csiescseq.priv) {
1959 DEFAULT(csiescseq.arg[0], 1);
1960 DEFAULT(csiescseq.arg[1], term.row);
1961 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1965 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1966 tcursor(CURSOR_SAVE);
1968 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1969 tcursor(CURSOR_LOAD);
1980 for(i = 0; i < csiescseq.len; i++) {
1981 c = csiescseq.buf[i] & 0xff;
1984 } else if(c == '\n') {
1986 } else if(c == '\r') {
1988 } else if(c == 0x1b) {
1991 printf("(%02x)", c);
1999 memset(&csiescseq, 0, sizeof(csiescseq));
2008 narg = strescseq.narg;
2010 switch(strescseq.type) {
2011 case ']': /* OSC -- Operating System Command */
2012 switch(i = atoi(strescseq.args[0])) {
2017 xsettitle(strescseq.args[1]);
2019 case 4: /* color set */
2022 p = strescseq.args[2];
2024 case 104: /* color reset, here p = NULL */
2025 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2026 if (!xsetcolorname(j, p)) {
2027 fprintf(stderr, "erresc: invalid color %s\n", p);
2030 * TODO if defaultbg color is changed, borders
2037 fprintf(stderr, "erresc: unknown str ");
2042 case 'k': /* old title set compatibility */
2043 xsettitle(strescseq.args[0]);
2045 case 'P': /* DSC -- Device Control String */
2046 case '_': /* APC -- Application Program Command */
2047 case '^': /* PM -- Privacy Message */
2049 fprintf(stderr, "erresc: unknown str ");
2058 char *p = strescseq.buf;
2061 strescseq.buf[strescseq.len] = '\0';
2062 while(p && strescseq.narg < STR_ARG_SIZ)
2063 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2071 printf("ESC%c", strescseq.type);
2072 for(i = 0; i < strescseq.len; i++) {
2073 c = strescseq.buf[i] & 0xff;
2076 } else if(isprint(c)) {
2078 } else if(c == '\n') {
2080 } else if(c == '\r') {
2082 } else if(c == 0x1b) {
2085 printf("(%02x)", c);
2093 memset(&strescseq, 0, sizeof(strescseq));
2097 tputtab(bool forward) {
2103 for(++x; x < term.col && !term.tabs[x]; ++x)
2108 for(--x; x > 0 && !term.tabs[x]; --x)
2111 tmoveto(x, term.c.y);
2115 techo(char *buf, int len) {
2116 for(; len > 0; buf++, len--) {
2119 if(c == '\033') { /* escape */
2122 } else if(c < '\x20') { /* control code */
2123 if(c != '\n' && c != '\r' && c != '\t') {
2137 tputc(char *c, int len) {
2139 bool control = ascii < '\x20' || ascii == 0177;
2142 if(xwrite(iofd, c, len) < 0) {
2143 fprintf(stderr, "Error writing in %s:%s\n",
2144 opt_io, strerror(errno));
2151 * STR sequences must be checked before anything else
2152 * because it can use some control codes as part of the sequence.
2154 if(term.esc & ESC_STR) {
2157 term.esc = ESC_START | ESC_STR_END;
2159 case '\a': /* backwards compatibility to xterm */
2164 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2165 memmove(&strescseq.buf[strescseq.len], c, len);
2166 strescseq.len += len;
2169 * Here is a bug in terminals. If the user never sends
2170 * some code to stop the str or esc command, then st
2171 * will stop responding. But this is better than
2172 * silently failing with unknown characters. At least
2173 * then users will report back.
2175 * In the case users ever get fixed, here is the code:
2187 * Actions of control codes must be performed as soon they arrive
2188 * because they can be embedded inside a control sequence, and
2189 * they must not cause conflicts with sequences.
2197 tmoveto(term.c.x-1, term.c.y);
2200 tmoveto(0, term.c.y);
2205 /* go to first col if the mode is set */
2206 tnewline(IS_SET(MODE_CRLF));
2208 case '\a': /* BEL */
2209 if(!(xw.state & WIN_FOCUSED))
2212 case '\033': /* ESC */
2214 term.esc = ESC_START;
2216 case '\016': /* SO */
2217 case '\017': /* SI */
2219 * Different charsets are hard to handle. Applications
2220 * should use the right alt charset escapes for the
2221 * only reason they still exist: line drawing. The
2222 * rest is incompatible history st should not support.
2225 case '\032': /* SUB */
2226 case '\030': /* CAN */
2229 case '\005': /* ENQ (IGNORED) */
2230 case '\000': /* NUL (IGNORED) */
2231 case '\021': /* XON (IGNORED) */
2232 case '\023': /* XOFF (IGNORED) */
2233 case 0177: /* DEL (IGNORED) */
2236 } else if(term.esc & ESC_START) {
2237 if(term.esc & ESC_CSI) {
2238 csiescseq.buf[csiescseq.len++] = ascii;
2239 if(BETWEEN(ascii, 0x40, 0x7E)
2240 || csiescseq.len >= \
2241 sizeof(csiescseq.buf)-1) {
2246 } else if(term.esc & ESC_STR_END) {
2250 } else if(term.esc & ESC_ALTCHARSET) {
2252 case '0': /* Line drawing set */
2253 term.c.attr.mode |= ATTR_GFX;
2255 case 'B': /* USASCII */
2256 term.c.attr.mode &= ~ATTR_GFX;
2258 case 'A': /* UK (IGNORED) */
2259 case '<': /* multinational charset (IGNORED) */
2260 case '5': /* Finnish (IGNORED) */
2261 case 'C': /* Finnish (IGNORED) */
2262 case 'K': /* German (IGNORED) */
2265 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2268 } else if(term.esc & ESC_TEST) {
2269 if(ascii == '8') { /* DEC screen alignment test. */
2270 char E[UTF_SIZ] = "E";
2273 for(x = 0; x < term.col; ++x) {
2274 for(y = 0; y < term.row; ++y)
2275 tsetchar(E, &term.c.attr, x, y);
2282 term.esc |= ESC_CSI;
2285 term.esc |= ESC_TEST;
2287 case 'P': /* DCS -- Device Control String */
2288 case '_': /* APC -- Application Program Command */
2289 case '^': /* PM -- Privacy Message */
2290 case ']': /* OSC -- Operating System Command */
2291 case 'k': /* old title set compatibility */
2293 strescseq.type = ascii;
2294 term.esc |= ESC_STR;
2296 case '(': /* set primary charset G0 */
2297 term.esc |= ESC_ALTCHARSET;
2299 case ')': /* set secondary charset G1 (IGNORED) */
2300 case '*': /* set tertiary charset G2 (IGNORED) */
2301 case '+': /* set quaternary charset G3 (IGNORED) */
2304 case 'D': /* IND -- Linefeed */
2305 if(term.c.y == term.bot) {
2306 tscrollup(term.top, 1);
2308 tmoveto(term.c.x, term.c.y+1);
2312 case 'E': /* NEL -- Next line */
2313 tnewline(1); /* always go to first col */
2316 case 'H': /* HTS -- Horizontal tab stop */
2317 term.tabs[term.c.x] = 1;
2320 case 'M': /* RI -- Reverse index */
2321 if(term.c.y == term.top) {
2322 tscrolldown(term.top, 1);
2324 tmoveto(term.c.x, term.c.y-1);
2328 case 'Z': /* DECID -- Identify Terminal */
2329 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2332 case 'c': /* RIS -- Reset to inital state */
2337 case '=': /* DECPAM -- Application keypad */
2338 term.mode |= MODE_APPKEYPAD;
2341 case '>': /* DECPNM -- Normal keypad */
2342 term.mode &= ~MODE_APPKEYPAD;
2345 case '7': /* DECSC -- Save Cursor */
2346 tcursor(CURSOR_SAVE);
2349 case '8': /* DECRC -- Restore Cursor */
2350 tcursor(CURSOR_LOAD);
2353 case '\\': /* ST -- Stop */
2357 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2358 (uchar) ascii, isprint(ascii)? ascii:'.');
2363 * All characters which form part of a sequence are not
2369 * Display control codes only if we are in graphic mode
2371 if(control && !(term.c.attr.mode & ATTR_GFX))
2373 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2375 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2376 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2380 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2381 memmove(&term.line[term.c.y][term.c.x+1],
2382 &term.line[term.c.y][term.c.x],
2383 (term.col - term.c.x - 1) * sizeof(Glyph));
2386 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2387 if(term.c.x+1 < term.col) {
2388 tmoveto(term.c.x+1, term.c.y);
2390 term.c.state |= CURSOR_WRAPNEXT;
2395 tresize(int col, int row) {
2397 int minrow = MIN(row, term.row);
2398 int mincol = MIN(col, term.col);
2399 int slide = term.c.y - row + 1;
2403 if(col < 1 || row < 1)
2406 /* free unneeded rows */
2410 * slide screen to keep cursor where we expect it -
2411 * tscrollup would work here, but we can optimize to
2412 * memmove because we're freeing the earlier lines
2414 for(/* i = 0 */; i < slide; i++) {
2418 memmove(term.line, term.line + slide, row * sizeof(Line));
2419 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2421 for(i += row; i < term.row; i++) {
2426 /* resize to new height */
2427 term.line = xrealloc(term.line, row * sizeof(Line));
2428 term.alt = xrealloc(term.alt, row * sizeof(Line));
2429 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2430 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2432 /* resize each row to new width, zero-pad if needed */
2433 for(i = 0; i < minrow; i++) {
2435 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2436 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2439 /* allocate any new rows */
2440 for(/* i == minrow */; i < row; i++) {
2442 term.line[i] = xcalloc(col, sizeof(Glyph));
2443 term.alt [i] = xcalloc(col, sizeof(Glyph));
2445 if(col > term.col) {
2446 bp = term.tabs + term.col;
2448 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2449 while(--bp > term.tabs && !*bp)
2451 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2454 /* update terminal size */
2457 /* reset scrolling region */
2458 tsetscroll(0, row-1);
2459 /* make use of the LIMIT in tmoveto */
2460 tmoveto(term.c.x, term.c.y);
2461 /* Clearing both screens */
2464 if(mincol < col && 0 < minrow) {
2465 tclearregion(mincol, 0, col - 1, minrow - 1);
2467 if(0 < col && minrow < row) {
2468 tclearregion(0, minrow, col - 1, row - 1);
2471 } while(orig != term.line);
2477 xresize(int col, int row) {
2478 xw.tw = MAX(1, col * xw.cw);
2479 xw.th = MAX(1, row * xw.ch);
2481 XFreePixmap(xw.dpy, xw.buf);
2482 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2483 DefaultDepth(xw.dpy, xw.scr));
2484 XftDrawChange(xw.draw, xw.buf);
2485 xclear(0, 0, xw.w, xw.h);
2488 static inline ushort
2489 sixd_to_16bit(int x) {
2490 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2496 XRenderColor color = { .alpha = 0xffff };
2498 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2499 for(i = 0; i < LEN(colorname); i++) {
2502 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2503 die("Could not allocate color '%s'\n", colorname[i]);
2507 /* load colors [16-255] ; same colors as xterm */
2508 for(i = 16, r = 0; r < 6; r++) {
2509 for(g = 0; g < 6; g++) {
2510 for(b = 0; b < 6; b++) {
2511 color.red = sixd_to_16bit(r);
2512 color.green = sixd_to_16bit(g);
2513 color.blue = sixd_to_16bit(b);
2514 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2515 die("Could not allocate color %d\n", i);
2522 for(r = 0; r < 24; r++, i++) {
2523 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2524 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2526 die("Could not allocate color %d\n", i);
2532 xsetcolorname(int x, const char *name) {
2533 XRenderColor color = { .alpha = 0xffff };
2535 if (x < 0 || x > LEN(colorname))
2538 if(16 <= x && x < 16 + 216) {
2539 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2540 color.red = sixd_to_16bit(r);
2541 color.green = sixd_to_16bit(g);
2542 color.blue = sixd_to_16bit(b);
2543 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2544 return 0; /* something went wrong */
2547 } else if (16 + 216 <= x && x < 256) {
2548 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2549 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2550 return 0; /* something went wrong */
2554 name = colorname[x];
2557 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2564 xtermclear(int col1, int row1, int col2, int row2) {
2565 XftDrawRect(xw.draw,
2566 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2567 borderpx + col1 * xw.cw,
2568 borderpx + row1 * xw.ch,
2569 (col2-col1+1) * xw.cw,
2570 (row2-row1+1) * xw.ch);
2574 * Absolute coordinates.
2577 xclear(int x1, int y1, int x2, int y2) {
2578 XftDrawRect(xw.draw,
2579 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2580 x1, y1, x2-x1, y2-y1);
2585 XClassHint class = {opt_class ? opt_class : termname, termname};
2586 XWMHints wm = {.flags = InputHint, .input = 1};
2587 XSizeHints *sizeh = NULL;
2589 sizeh = XAllocSizeHints();
2590 if(xw.isfixed == False) {
2591 sizeh->flags = PSize | PResizeInc | PBaseSize;
2592 sizeh->height = xw.h;
2593 sizeh->width = xw.w;
2594 sizeh->height_inc = xw.ch;
2595 sizeh->width_inc = xw.cw;
2596 sizeh->base_height = 2 * borderpx;
2597 sizeh->base_width = 2 * borderpx;
2599 sizeh->flags = PMaxSize | PMinSize;
2600 sizeh->min_width = sizeh->max_width = xw.fw;
2601 sizeh->min_height = sizeh->max_height = xw.fh;
2604 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2609 xloadfont(Font *f, FcPattern *pattern) {
2613 match = FcFontMatch(NULL, pattern, &result);
2617 if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2618 FcPatternDestroy(match);
2622 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2623 FcPatternDestroy(match);
2627 f->pattern = FcPatternDuplicate(pattern);
2629 f->ascent = f->match->ascent;
2630 f->descent = f->match->descent;
2632 f->rbearing = f->match->max_advance_width;
2634 f->height = f->ascent + f->descent;
2635 f->width = f->lbearing + f->rbearing;
2641 xloadfonts(char *fontstr, int fontsize) {
2646 if(fontstr[0] == '-') {
2647 pattern = XftXlfdParse(fontstr, False, False);
2649 pattern = FcNameParse((FcChar8 *)fontstr);
2653 die("st: can't open font %s\n", fontstr);
2656 FcPatternDel(pattern, FC_PIXEL_SIZE);
2657 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2658 usedfontsize = fontsize;
2660 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2661 if(result == FcResultMatch) {
2662 usedfontsize = (int)fontval;
2665 * Default font size is 12, if none given. This is to
2666 * have a known usedfontsize value.
2668 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2673 FcConfigSubstitute(0, pattern, FcMatchPattern);
2674 FcDefaultSubstitute(pattern);
2676 if(xloadfont(&dc.font, pattern))
2677 die("st: can't open font %s\n", fontstr);
2679 /* Setting character width and height. */
2680 xw.cw = dc.font.width;
2681 xw.ch = dc.font.height;
2683 FcPatternDel(pattern, FC_SLANT);
2684 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2685 if(xloadfont(&dc.ifont, pattern))
2686 die("st: can't open font %s\n", fontstr);
2688 FcPatternDel(pattern, FC_WEIGHT);
2689 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2690 if(xloadfont(&dc.ibfont, pattern))
2691 die("st: can't open font %s\n", fontstr);
2693 FcPatternDel(pattern, FC_SLANT);
2694 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2695 if(xloadfont(&dc.bfont, pattern))
2696 die("st: can't open font %s\n", fontstr);
2698 FcPatternDestroy(pattern);
2702 xunloadfonts(void) {
2706 * Free the loaded fonts in the font cache. This is done backwards
2709 for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2712 XftFontClose(xw.dpy, frc[ip].font);
2717 XftFontClose(xw.dpy, dc.font.match);
2718 FcPatternDestroy(dc.font.pattern);
2719 FcFontSetDestroy(dc.font.set);
2720 XftFontClose(xw.dpy, dc.bfont.match);
2721 FcPatternDestroy(dc.bfont.pattern);
2722 FcFontSetDestroy(dc.bfont.set);
2723 XftFontClose(xw.dpy, dc.ifont.match);
2724 FcPatternDestroy(dc.ifont.pattern);
2725 FcFontSetDestroy(dc.ifont.set);
2726 XftFontClose(xw.dpy, dc.ibfont.match);
2727 FcPatternDestroy(dc.ibfont.pattern);
2728 FcFontSetDestroy(dc.ibfont.set);
2732 xzoom(const Arg *arg) {
2734 xloadfonts(usedfont, usedfontsize + arg->i);
2741 XSetWindowAttributes attrs;
2747 if(!(xw.dpy = XOpenDisplay(NULL)))
2748 die("Can't open display\n");
2749 xw.scr = XDefaultScreen(xw.dpy);
2750 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2754 die("Could not init fontconfig.\n");
2756 usedfont = (opt_font == NULL)? font : opt_font;
2757 xloadfonts(usedfont, 0);
2760 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2763 /* adjust fixed window geometry */
2765 sw = DisplayWidth(xw.dpy, xw.scr);
2766 sh = DisplayHeight(xw.dpy, xw.scr);
2768 xw.fx = sw + xw.fx - xw.fw - 1;
2770 xw.fy = sh + xw.fy - xw.fh - 1;
2775 /* window - default size */
2776 xw.h = 2 * borderpx + term.row * xw.ch;
2777 xw.w = 2 * borderpx + term.col * xw.cw;
2783 attrs.background_pixel = dc.col[defaultbg].pixel;
2784 attrs.border_pixel = dc.col[defaultbg].pixel;
2785 attrs.bit_gravity = NorthWestGravity;
2786 attrs.event_mask = FocusChangeMask | KeyPressMask
2787 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2788 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2789 attrs.colormap = xw.cmap;
2791 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2792 XRootWindow(xw.dpy, xw.scr);
2793 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2794 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2796 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2800 memset(&gcvalues, 0, sizeof(gcvalues));
2801 gcvalues.graphics_exposures = False;
2802 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2804 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2805 DefaultDepth(xw.dpy, xw.scr));
2806 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2807 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2809 /* Xft rendering context */
2810 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2813 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2814 XSetLocaleModifiers("@im=local");
2815 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2816 XSetLocaleModifiers("@im=");
2817 if((xw.xim = XOpenIM(xw.dpy,
2818 NULL, NULL, NULL)) == NULL) {
2819 die("XOpenIM failed. Could not open input"
2824 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2825 | XIMStatusNothing, XNClientWindow, xw.win,
2826 XNFocusWindow, xw.win, NULL);
2828 die("XCreateIC failed. Could not obtain input method.\n");
2830 /* white cursor, black outline */
2831 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2832 XDefineCursor(xw.dpy, xw.win, cursor);
2833 XRecolorCursor(xw.dpy, cursor,
2834 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2835 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2837 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2838 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2839 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2842 XMapWindow(xw.dpy, xw.win);
2848 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2849 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2850 width = charlen * xw.cw, xp, i;
2852 int u8fl, u8fblen, u8cblen, doesexist;
2855 Font *font = &dc.font;
2857 FcPattern *fcpattern, *fontpattern;
2858 FcFontSet *fcsets[] = { NULL };
2859 FcCharSet *fccharset;
2860 Colour *fg, *bg, *temp, revfg, revbg;
2861 XRenderColor colfg, colbg;
2864 frcflags = FRC_NORMAL;
2866 if(base.mode & ATTR_ITALIC) {
2867 if(base.fg == defaultfg)
2868 base.fg = defaultitalic;
2870 frcflags = FRC_ITALIC;
2871 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2872 if(base.fg == defaultfg)
2873 base.fg = defaultitalic;
2875 frcflags = FRC_ITALICBOLD;
2876 } else if(base.mode & ATTR_UNDERLINE) {
2877 if(base.fg == defaultfg)
2878 base.fg = defaultunderline;
2880 fg = &dc.col[base.fg];
2881 bg = &dc.col[base.bg];
2883 if(base.mode & ATTR_BOLD) {
2884 if(BETWEEN(base.fg, 0, 7)) {
2885 /* basic system colors */
2886 fg = &dc.col[base.fg + 8];
2887 } else if(BETWEEN(base.fg, 16, 195)) {
2889 fg = &dc.col[base.fg + 36];
2890 } else if(BETWEEN(base.fg, 232, 251)) {
2892 fg = &dc.col[base.fg + 4];
2895 * Those ranges will not be brightened:
2896 * 8 - 15 – bright system colors
2897 * 196 - 231 – highest 256 color cube
2898 * 252 - 255 – brightest colors in greyscale
2901 frcflags = FRC_BOLD;
2904 if(IS_SET(MODE_REVERSE)) {
2905 if(fg == &dc.col[defaultfg]) {
2906 fg = &dc.col[defaultbg];
2908 colfg.red = ~fg->color.red;
2909 colfg.green = ~fg->color.green;
2910 colfg.blue = ~fg->color.blue;
2911 colfg.alpha = fg->color.alpha;
2912 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2916 if(bg == &dc.col[defaultbg]) {
2917 bg = &dc.col[defaultfg];
2919 colbg.red = ~bg->color.red;
2920 colbg.green = ~bg->color.green;
2921 colbg.blue = ~bg->color.blue;
2922 colbg.alpha = bg->color.alpha;
2923 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2928 if(base.mode & ATTR_REVERSE) {
2934 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
2937 /* Intelligent cleaning up of the borders. */
2939 xclear(0, (y == 0)? 0 : winy, borderpx,
2940 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2942 if(x + charlen >= term.col) {
2943 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2944 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2947 xclear(winx, 0, winx + width, borderpx);
2949 xclear(winx, winy + xw.ch, winx + width, xw.h);
2951 /* Clean up the region we want to draw to. */
2952 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2954 /* Set the clip region because Xft is sometimes dirty. */
2959 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
2961 fcsets[0] = font->set;
2962 for(xp = winx; bytelen > 0;) {
2964 * Search for the range in the to be printed string of glyphs
2965 * that are in the main font. Then print that range. If
2966 * some glyph is found that is not in the font, do the
2974 u8cblen = utf8decode(s, &u8char);
2978 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2979 if(!doesexist || bytelen <= 0) {
2988 XftDrawStringUtf8(xw.draw, fg,
2990 winy + font->ascent,
2993 xp += font->width * u8fl;
3006 /* Search the font cache. */
3007 for(i = 0; i < frclen; i++, frp--) {
3011 if(frc[frp].c == u8char
3012 && frc[frp].flags == frcflags) {
3017 /* Nothing was found. */
3020 * Nothing was found in the cache. Now use
3021 * some dozen of Fontconfig calls to get the
3022 * font for one single character.
3024 fcpattern = FcPatternDuplicate(font->pattern);
3025 fccharset = FcCharSetCreate();
3027 FcCharSetAddChar(fccharset, u8char);
3028 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3030 FcPatternAddBool(fcpattern, FC_SCALABLE,
3033 FcConfigSubstitute(0, fcpattern,
3035 FcDefaultSubstitute(fcpattern);
3037 fontpattern = FcFontSetMatch(0, fcsets,
3038 FcTrue, fcpattern, &fcres);
3041 * Overwrite or create the new cache entry.
3045 if(frccur >= LEN(frc))
3047 if(frclen > LEN(frc)) {
3049 XftFontClose(xw.dpy, frc[frccur].font);
3052 frc[frccur].font = XftFontOpenPattern(xw.dpy,
3054 frc[frccur].c = u8char;
3055 frc[frccur].flags = frcflags;
3057 FcPatternDestroy(fcpattern);
3058 FcCharSetDestroy(fccharset);
3063 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
3064 xp, winy + frc[frp].font->ascent,
3065 (FcChar8 *)u8c, u8cblen);
3071 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3072 winy + font->ascent, (FcChar8 *)s, bytelen);
3075 if(base.mode & ATTR_UNDERLINE) {
3076 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3080 /* Reset clip to none. */
3081 XftDrawSetClip(xw.draw, 0);
3086 static int oldx = 0, oldy = 0;
3088 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3090 LIMIT(oldx, 0, term.col-1);
3091 LIMIT(oldy, 0, term.row-1);
3093 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3095 /* remove the old cursor */
3096 sl = utf8size(term.line[oldy][oldx].c);
3097 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3100 /* draw the new one */
3101 if(!(IS_SET(MODE_HIDE))) {
3102 if(xw.state & WIN_FOCUSED) {
3103 if(IS_SET(MODE_REVERSE)) {
3104 g.mode |= ATTR_REVERSE;
3110 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
3112 XftDrawRect(xw.draw, &dc.col[defaultcs],
3113 borderpx + term.c.x * xw.cw,
3114 borderpx + term.c.y * xw.ch,
3116 XftDrawRect(xw.draw, &dc.col[defaultcs],
3117 borderpx + term.c.x * xw.cw,
3118 borderpx + term.c.y * xw.ch,
3120 XftDrawRect(xw.draw, &dc.col[defaultcs],
3121 borderpx + (term.c.x + 1) * xw.cw - 1,
3122 borderpx + term.c.y * xw.ch,
3124 XftDrawRect(xw.draw, &dc.col[defaultcs],
3125 borderpx + term.c.x * xw.cw,
3126 borderpx + (term.c.y + 1) * xw.ch - 1,
3129 oldx = term.c.x, oldy = term.c.y;
3135 xsettitle(char *p) {
3138 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3140 XSetWMName(xw.dpy, xw.win, &prop);
3145 xsettitle(opt_title ? opt_title : "st");
3149 redraw(int timeout) {
3150 struct timespec tv = {0, timeout * 1000};
3156 nanosleep(&tv, NULL);
3157 XSync(xw.dpy, False); /* necessary for a good tput flash */
3163 drawregion(0, 0, term.col, term.row);
3164 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3166 XSetForeground(xw.dpy, dc.gc,
3167 dc.col[IS_SET(MODE_REVERSE)?
3168 defaultfg : defaultbg].pixel);
3172 drawregion(int x1, int y1, int x2, int y2) {
3173 int ic, ib, x, y, ox, sl;
3175 char buf[DRAW_BUF_SIZ];
3176 bool ena_sel = sel.bx != -1;
3178 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3181 if(!(xw.state & WIN_VISIBLE))
3184 for(y = y1; y < y2; y++) {
3188 xtermclear(0, y, term.col, y);
3190 base = term.line[y][0];
3192 for(x = x1; x < x2; x++) {
3193 new = term.line[y][x];
3194 if(ena_sel && selected(x, y))
3195 new.mode ^= ATTR_REVERSE;
3196 if(ib > 0 && (ATTRCMP(base, new)
3197 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3198 xdraws(buf, base, ox, y, ic, ib);
3206 sl = utf8size(new.c);
3207 memcpy(buf+ib, new.c, sl);
3212 xdraws(buf, base, ox, y, ic, ib);
3218 expose(XEvent *ev) {
3219 XExposeEvent *e = &ev->xexpose;
3221 if(xw.state & WIN_REDRAW) {
3223 xw.state &= ~WIN_REDRAW;
3229 visibility(XEvent *ev) {
3230 XVisibilityEvent *e = &ev->xvisibility;
3232 if(e->state == VisibilityFullyObscured) {
3233 xw.state &= ~WIN_VISIBLE;
3234 } else if(!(xw.state & WIN_VISIBLE)) {
3235 /* need a full redraw for next Expose, not just a buf copy */
3236 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3242 xw.state &= ~WIN_VISIBLE;
3246 xseturgency(int add) {
3247 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3249 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3250 XSetWMHints(xw.dpy, xw.win, h);
3256 XFocusChangeEvent *e = &ev->xfocus;
3258 if(e->mode == NotifyGrab)
3261 if(ev->type == FocusIn) {
3262 XSetICFocus(xw.xic);
3263 xw.state |= WIN_FOCUSED;
3266 XUnsetICFocus(xw.xic);
3267 xw.state &= ~WIN_FOCUSED;
3272 match(uint mask, uint state) {
3273 state &= ~(ignoremod);
3275 if(mask == XK_NO_MOD && state)
3277 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3279 if((state & mask) != state)
3285 numlock(const Arg *dummy) {
3290 kmap(KeySym k, uint state) {
3295 /* Check for mapped keys out of X11 function keys. */
3296 for(i = 0; i < LEN(mappedkeys); i++) {
3297 if(mappedkeys[i] == k)
3300 if(i == LEN(mappedkeys)) {
3301 if((k & 0xFFFF) < 0xFD00)
3305 for(kp = key; kp < key + LEN(key); kp++) {
3311 if(!match(mask, state))
3314 if(kp->appkey > 0) {
3315 if(!IS_SET(MODE_APPKEYPAD))
3317 if(term.numlock && kp->appkey == 2)
3319 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3323 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3325 && !IS_SET(MODE_APPCURSOR))) {
3329 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3330 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3341 kpress(XEvent *ev) {
3342 XKeyEvent *e = &ev->xkey;
3344 char xstr[31], buf[32], *customkey, *cp = buf;
3350 if(IS_SET(MODE_KBDLOCK))
3353 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3354 e->state &= ~Mod2Mask;
3356 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3357 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3358 bp->func(&(bp->arg));
3363 /* 2. custom keys from config.h */
3364 if((customkey = kmap(ksym, e->state))) {
3365 len = strlen(customkey);
3366 memcpy(buf, customkey, len);
3367 /* 3. hardcoded (overrides X lookup) */
3372 if(len == 1 && e->state & Mod1Mask) {
3373 if(IS_SET(MODE_8BIT)) {
3376 ret = utf8encode(&c, cp);
3385 memcpy(cp, xstr, len);
3386 len = cp - buf + len;
3390 if(IS_SET(MODE_ECHO))
3396 cmessage(XEvent *e) {
3399 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3401 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3402 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3403 xw.state |= WIN_FOCUSED;
3405 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3406 xw.state &= ~WIN_FOCUSED;
3408 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3409 /* Send SIGHUP to shell */
3416 cresize(int width, int height) {
3424 col = (xw.w - 2 * borderpx) / xw.cw;
3425 row = (xw.h - 2 * borderpx) / xw.ch;
3434 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3437 cresize(e->xconfigure.width, e->xconfigure.height);
3444 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3445 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3447 gettimeofday(&lastblink, NULL);
3448 gettimeofday(&last, NULL);
3450 for(xev = actionfps;;) {
3452 FD_SET(cmdfd, &rfd);
3455 switch(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3459 die("select failed: %s\n", SERRNO);
3461 if(FD_ISSET(cmdfd, &rfd)) {
3464 blinkset = tattrset(ATTR_BLINK);
3465 if(!blinkset && term.mode & ATTR_BLINK)
3466 term.mode &= ~(MODE_BLINK);
3470 if(FD_ISSET(xfd, &rfd))
3474 gettimeofday(&now, NULL);
3475 drawtimeout.tv_sec = 0;
3476 drawtimeout.tv_usec = (1000/xfps) * 1000;
3480 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3481 tsetdirtattr(ATTR_BLINK);
3482 term.mode ^= MODE_BLINK;
3483 gettimeofday(&lastblink, NULL);
3486 if(TIMEDIFF(now, last) \
3487 > (xev? (1000/xfps) : (1000/actionfps))) {
3493 while(XPending(xw.dpy)) {
3494 XNextEvent(xw.dpy, &ev);
3495 if(XFilterEvent(&ev, None))
3497 if(handler[ev.type])
3498 (handler[ev.type])(&ev);
3504 if(xev && !FD_ISSET(xfd, &rfd))
3506 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3508 if(TIMEDIFF(now, lastblink) \
3510 drawtimeout.tv_usec = 1;
3512 drawtimeout.tv_usec = (1000 * \
3527 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3528 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3529 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3533 main(int argc, char *argv[]) {
3537 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3542 allowaltscreen = false;
3545 opt_class = EARGF(usage());
3548 /* eat all remaining arguments */
3553 opt_font = EARGF(usage());
3556 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3561 if(bitm & WidthValue)
3563 if(bitm & HeightValue)
3565 if(bitm & XNegative && xw.fx == 0)
3567 if(bitm & XNegative && xw.fy == 0)
3570 if(xw.fh != 0 && xw.fw != 0)
3574 opt_io = EARGF(usage());
3577 opt_title = EARGF(usage());
3580 opt_embed = EARGF(usage());
3588 setlocale(LC_CTYPE, "");
3589 XSetLocaleModifiers("");
3595 cresize(xw.h, xw.w);