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,
124 ESC_STR = 4, /* DSC, OSC, PM, APC */
126 ESC_STR_END = 16, /* a final string was encountered */
127 ESC_TEST = 32, /* Enter in test mode */
136 enum selection_type {
141 enum selection_snap {
148 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
150 typedef unsigned char uchar;
151 typedef unsigned int uint;
152 typedef unsigned long ulong;
153 typedef unsigned short ushort;
156 char c[UTF_SIZ]; /* character code */
157 uchar mode; /* attribute flags */
158 ushort fg; /* foreground */
159 ushort bg; /* background */
165 Glyph attr; /* current char attributes */
171 /* CSI Escape sequence structs */
172 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
174 char buf[ESC_BUF_SIZ]; /* raw string */
175 int len; /* raw string length */
177 int arg[ESC_ARG_SIZ];
178 int narg; /* nb of args */
182 /* STR Escape sequence structs */
183 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
185 char type; /* ESC type ... */
186 char buf[STR_BUF_SIZ]; /* raw string */
187 int len; /* raw string length */
188 char *args[STR_ARG_SIZ];
189 int narg; /* nb of args */
192 /* Internal representation of the screen */
194 int row; /* nb row */
195 int col; /* nb col */
196 Line *line; /* screen */
197 Line *alt; /* alternate screen */
198 bool *dirty; /* dirtyness of lines */
199 TCursor c; /* cursor */
200 int top; /* top scroll limit */
201 int bot; /* bottom scroll limit */
202 int mode; /* terminal mode flags */
203 int esc; /* escape state flags */
204 bool numlock; /* lock numbers in keyboard */
208 /* Purely graphic info */
214 Atom xembed, wmdeletewin;
220 bool isfixed; /* is fixed geometry? */
221 int fx, fy, fw, fh; /* fixed geometry */
222 int tw, th; /* tty width and height */
223 int w, h; /* window width and height */
224 int ch; /* char height */
225 int cw; /* char width */
226 char state; /* focus, redraw, visible */
233 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
234 signed char appkey; /* application keypad */
235 signed char appcursor; /* application cursor */
236 signed char crlf; /* crlf mode */
239 /* TODO: use better name for vars... */
252 struct timeval tclick1;
253 struct timeval tclick2;
266 void (*func)(const Arg *);
270 /* function definitions used in config.h */
271 static void clippaste(const Arg *);
272 static void numlock(const Arg *);
273 static void selpaste(const Arg *);
274 static void xzoom(const Arg *);
276 /* Config.h for applying patches and the configuration. */
292 /* Drawing Context */
294 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
295 Font font, bfont, ifont, ibfont;
299 static void die(const char *, ...);
300 static void draw(void);
301 static void redraw(int);
302 static void drawregion(int, int, int, int);
303 static void execsh(void);
304 static void sigchld(int);
305 static void run(void);
307 static void csidump(void);
308 static void csihandle(void);
309 static void csiparse(void);
310 static void csireset(void);
311 static void strdump(void);
312 static void strhandle(void);
313 static void strparse(void);
314 static void strreset(void);
316 static void tclearregion(int, int, int, int);
317 static void tcursor(int);
318 static void tdeletechar(int);
319 static void tdeleteline(int);
320 static void tinsertblank(int);
321 static void tinsertblankline(int);
322 static void tmoveto(int, int);
323 static void tmoveato(int x, int y);
324 static void tnew(int, int);
325 static void tnewline(int);
326 static void tputtab(bool);
327 static void tputc(char *, int);
328 static void treset(void);
329 static int tresize(int, int);
330 static void tscrollup(int, int);
331 static void tscrolldown(int, int);
332 static void tsetattr(int*, int);
333 static void tsetchar(char *, Glyph *, int, int);
334 static void tsetscroll(int, int);
335 static void tswapscreen(void);
336 static void tsetdirt(int, int);
337 static void tsetmode(bool, bool, int *, int);
338 static void tfulldirt(void);
339 static void techo(char *, int);
341 static inline bool match(uint, uint);
342 static void ttynew(void);
343 static void ttyread(void);
344 static void ttyresize(void);
345 static void ttywrite(const char *, size_t);
347 static void xdraws(char *, Glyph, int, int, int, int);
348 static void xhints(void);
349 static void xclear(int, int, int, int);
350 static void xdrawcursor(void);
351 static void xinit(void);
352 static void xloadcols(void);
353 static int xsetcolorname(int, const char *);
354 static int xloadfont(Font *, FcPattern *);
355 static void xloadfonts(char *, int);
356 static void xsettitle(char *);
357 static void xresettitle(void);
358 static void xseturgency(int);
359 static void xsetsel(char*);
360 static void xtermclear(int, int, int, int);
361 static void xunloadfonts(void);
362 static void xresize(int, int);
364 static void expose(XEvent *);
365 static void visibility(XEvent *);
366 static void unmap(XEvent *);
367 static char *kmap(KeySym, uint);
368 static void kpress(XEvent *);
369 static void cmessage(XEvent *);
370 static void cresize(int, int);
371 static void resize(XEvent *);
372 static void focus(XEvent *);
373 static void brelease(XEvent *);
374 static void bpress(XEvent *);
375 static void bmotion(XEvent *);
376 static void selnotify(XEvent *);
377 static void selclear(XEvent *);
378 static void selrequest(XEvent *);
380 static void selinit(void);
381 static inline bool selected(int, int);
382 static void selcopy(void);
383 static void selscroll(int, int);
384 static void selsnap(int, int *, int *, int);
386 static int utf8decode(char *, long *);
387 static int utf8encode(long *, char *);
388 static int utf8size(char *);
389 static int isfullutf8(char *, int);
391 static ssize_t xwrite(int, char *, size_t);
392 static void *xmalloc(size_t);
393 static void *xrealloc(void *, size_t);
394 static void *xcalloc(size_t, size_t);
396 static void (*handler[LASTEvent])(XEvent *) = {
398 [ClientMessage] = cmessage,
399 [ConfigureNotify] = resize,
400 [VisibilityNotify] = visibility,
401 [UnmapNotify] = unmap,
405 [MotionNotify] = bmotion,
406 [ButtonPress] = bpress,
407 [ButtonRelease] = brelease,
408 [SelectionClear] = selclear,
409 [SelectionNotify] = selnotify,
410 [SelectionRequest] = selrequest,
417 static CSIEscape csiescseq;
418 static STREscape strescseq;
421 static Selection sel;
422 static int iofd = -1;
423 static char **opt_cmd = NULL;
424 static char *opt_io = NULL;
425 static char *opt_title = NULL;
426 static char *opt_embed = NULL;
427 static char *opt_class = NULL;
428 static char *opt_font = NULL;
430 static char *usedfont = NULL;
431 static int usedfontsize = 0;
433 /* Font Ring Cache */
448 * Fontcache is a ring buffer, with frccur as current position and frclen as
449 * the current length of used elements.
452 static Fontcache frc[1024];
453 static int frccur = -1, frclen = 0;
456 xwrite(int fd, char *s, size_t len) {
460 ssize_t r = write(fd, s, len);
470 xmalloc(size_t len) {
471 void *p = malloc(len);
474 die("Out of memory\n");
480 xrealloc(void *p, size_t len) {
481 if((p = realloc(p, len)) == NULL)
482 die("Out of memory\n");
488 xcalloc(size_t nmemb, size_t size) {
489 void *p = calloc(nmemb, size);
492 die("Out of memory\n");
498 utf8decode(char *s, long *u) {
504 if(~c & B7) { /* 0xxxxxxx */
507 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
508 *u = c&(B4|B3|B2|B1|B0);
510 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
511 *u = c&(B3|B2|B1|B0);
513 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
520 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
522 if((c & (B7|B6)) != B7) /* 10xxxxxx */
525 *u |= c & (B5|B4|B3|B2|B1|B0);
528 if((n == 1 && *u < 0x80) ||
529 (n == 2 && *u < 0x800) ||
530 (n == 3 && *u < 0x10000) ||
531 (*u >= 0xD800 && *u <= 0xDFFF)) {
543 utf8encode(long *u, char *s) {
551 *sp = uc; /* 0xxxxxxx */
553 } else if(*u < 0x800) {
554 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
556 } else if(uc < 0x10000) {
557 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
559 } else if(uc <= 0x10FFFF) {
560 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
566 for(i=n,++sp; i>0; --i,++sp)
567 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
579 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
580 UTF-8 otherwise return 0 */
582 isfullutf8(char *s, int b) {
590 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
592 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
594 ((b == 2) && (*c2&(B7|B6)) == B7))) {
596 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
598 ((b == 2) && (*c2&(B7|B6)) == B7) ||
599 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
612 } else if((c&(B7|B6|B5)) == (B7|B6)) {
614 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
623 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
624 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
628 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
629 if(sel.xtarget == None)
630 sel.xtarget = XA_STRING;
638 return LIMIT(x, 0, term.col-1);
646 return LIMIT(y, 0, term.row-1);
650 selected(int x, int y) {
653 if(sel.ey == y && sel.by == y) {
654 bx = MIN(sel.bx, sel.ex);
655 ex = MAX(sel.bx, sel.ex);
657 return BETWEEN(x, bx, ex);
660 if(sel.type == SEL_RECTANGULAR) {
661 return ((sel.b.y <= y && y <= sel.e.y)
662 && (sel.b.x <= x && x <= sel.e.x));
664 return ((sel.b.y < y && y < sel.e.y)
665 || (y == sel.e.y && x <= sel.e.x))
666 || (y == sel.b.y && x >= sel.b.x
667 && (x <= sel.e.x || sel.b.y != sel.e.y));
671 selsnap(int mode, int *x, int *y, int direction) {
674 while(*x > 0 && *x < term.col-1
675 && term.line[*y][*x + direction].c[0] != ' ') {
680 *x = (direction < 0) ? 0 : term.col - 1;
688 getbuttoninfo(XEvent *e) {
690 uint state = e->xbutton.state &~Button1Mask;
692 sel.alt = IS_SET(MODE_ALTSCREEN);
694 sel.ex = x2col(e->xbutton.x);
695 sel.ey = y2row(e->xbutton.y);
698 || (sel.by == sel.ey && sel.bx < sel.ex)) {
699 selsnap(sel.snap, &sel.bx, &sel.by, -1);
700 selsnap(sel.snap, &sel.ex, &sel.ey, +1);
702 selsnap(sel.snap, &sel.ex, &sel.ey, -1);
703 selsnap(sel.snap, &sel.bx, &sel.by, +1);
706 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
707 sel.b.y = MIN(sel.by, sel.ey);
708 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
709 sel.e.y = MAX(sel.by, sel.ey);
711 sel.type = SEL_REGULAR;
712 for(type = 1; type < LEN(selmasks); ++type) {
713 if(match(selmasks[type], state)) {
721 mousereport(XEvent *e) {
722 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
723 button = e->xbutton.button, state = e->xbutton.state,
726 static int ob, ox, oy;
729 if(e->xbutton.type == MotionNotify) {
730 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
734 } else if(!IS_SET(MODE_MOUSESGR)
735 && (e->xbutton.type == ButtonRelease
736 || button == AnyButton)) {
742 if(e->xbutton.type == ButtonPress) {
748 button += (state & ShiftMask ? 4 : 0)
749 + (state & Mod4Mask ? 8 : 0)
750 + (state & ControlMask ? 16 : 0);
753 if(IS_SET(MODE_MOUSESGR)) {
754 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
756 e->xbutton.type == ButtonRelease ? 'm' : 'M');
757 } else if(x < 223 && y < 223) {
758 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
759 32+button, 32+x+1, 32+y+1);
771 if(IS_SET(MODE_MOUSE)) {
773 } else if(e->xbutton.button == Button1) {
774 gettimeofday(&now, NULL);
776 /* Clear previous selection, logically and visually. */
779 tsetdirt(sel.b.y, sel.e.y);
783 sel.type = SEL_REGULAR;
784 sel.ex = sel.bx = x2col(e->xbutton.x);
785 sel.ey = sel.by = y2row(e->xbutton.y);
789 * If user clicks are fasst enough (e.g. below timeouts),
790 * we ignore if his hand slipped left or down and accidentally
791 * selected more; we are just snapping to whatever we're
794 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
795 sel.snap = SNAP_LINE;
796 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
797 sel.snap = SNAP_WORD;
801 selsnap(sel.snap, &sel.bx, &sel.by, -1);
802 selsnap(sel.snap, &sel.ex, &sel.ey, 1);
809 * Draw selection, unless it's regular and we don't want to
810 * make clicks visible
813 tsetdirt(sel.b.y, sel.e.y);
816 sel.tclick2 = sel.tclick1;
818 } else if(e->xbutton.button == Button4) {
820 } else if(e->xbutton.button == Button5) {
828 int x, y, bufsize, size;
834 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
835 ptr = str = xmalloc(bufsize);
837 /* append every set & selected glyph to the selection */
838 for(y = sel.b.y; y < sel.e.y + 1; y++) {
839 gp = &term.line[y][0];
840 last = gp + term.col;
842 while(--last >= gp && !(selected(last - gp, y) && \
843 strcmp(last->c, " ") != 0))
846 for(x = 0; gp <= last; x++, ++gp) {
850 size = utf8size(gp->c);
851 memcpy(ptr, gp->c, size);
856 * Copy and pasting of line endings is inconsistent
857 * in the inconsistent terminal and GUI world.
858 * The best solution seems like to produce '\n' when
859 * something is copied from st and convert '\n' to
860 * '\r', when something to be pasted is received by
862 * FIXME: Fix the computer world.
864 if(y < sel.e.y && !((gp-1)->mode & ATTR_WRAP))
873 selnotify(XEvent *e) {
874 ulong nitems, ofs, rem;
876 uchar *data, *last, *repl;
881 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
882 False, AnyPropertyType, &type, &format,
883 &nitems, &rem, &data)) {
884 fprintf(stderr, "Clipboard allocation failed\n");
889 * As seen in selcopy:
890 * Line endings are inconsistent in the terminal and GUI world
891 * copy and pasting. When receiving some selection data,
892 * replace all '\n' with '\r'.
893 * FIXME: Fix the computer world.
896 last = data + nitems * format / 8;
897 while((repl = memchr(repl, '\n', last - repl))) {
901 ttywrite((const char *)data, nitems * format / 8);
903 /* number of 32-bit chunks returned */
904 ofs += nitems * format / 32;
909 selpaste(const Arg *dummy) {
910 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
911 xw.win, CurrentTime);
915 clippaste(const Arg *dummy) {
918 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
919 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
920 xw.win, CurrentTime);
924 selclear(XEvent *e) {
928 tsetdirt(sel.b.y, sel.e.y);
932 selrequest(XEvent *e) {
933 XSelectionRequestEvent *xsre;
935 Atom xa_targets, string;
937 xsre = (XSelectionRequestEvent *) e;
938 xev.type = SelectionNotify;
939 xev.requestor = xsre->requestor;
940 xev.selection = xsre->selection;
941 xev.target = xsre->target;
942 xev.time = xsre->time;
946 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
947 if(xsre->target == xa_targets) {
948 /* respond with the supported type */
949 string = sel.xtarget;
950 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
951 XA_ATOM, 32, PropModeReplace,
952 (uchar *) &string, 1);
953 xev.property = xsre->property;
954 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
955 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
956 xsre->target, 8, PropModeReplace,
957 (uchar *) sel.clip, strlen(sel.clip));
958 xev.property = xsre->property;
961 /* all done, send a notification to the listener */
962 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
963 fprintf(stderr, "Error sending SelectionNotify event\n");
968 /* register the selection for both the clipboard and the primary */
974 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
976 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
977 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
981 brelease(XEvent *e) {
982 if(IS_SET(MODE_MOUSE)) {
987 if(e->xbutton.button == Button2) {
989 } else if(e->xbutton.button == Button1) {
992 term.dirty[sel.ey] = 1;
993 if(sel.bx == sel.ex && sel.by == sel.ey) {
1002 bmotion(XEvent *e) {
1003 int oldey, oldex, oldsby, oldsey;
1005 if(IS_SET(MODE_MOUSE)) {
1019 if(oldey != sel.ey || oldex != sel.ex) {
1020 tsetdirt(MIN(sel.b.y, oldsby), MAX(sel.e.y, oldsey));
1025 die(const char *errstr, ...) {
1028 va_start(ap, errstr);
1029 vfprintf(stderr, errstr, ap);
1037 char *envshell = getenv("SHELL");
1038 const struct passwd *pass = getpwuid(getuid());
1039 char buf[sizeof(long) * 8 + 1];
1041 unsetenv("COLUMNS");
1043 unsetenv("TERMCAP");
1046 setenv("LOGNAME", pass->pw_name, 1);
1047 setenv("USER", pass->pw_name, 1);
1048 setenv("SHELL", pass->pw_shell, 0);
1049 setenv("HOME", pass->pw_dir, 0);
1052 snprintf(buf, sizeof(buf), "%lu", xw.win);
1053 setenv("WINDOWID", buf, 1);
1055 signal(SIGCHLD, SIG_DFL);
1056 signal(SIGHUP, SIG_DFL);
1057 signal(SIGINT, SIG_DFL);
1058 signal(SIGQUIT, SIG_DFL);
1059 signal(SIGTERM, SIG_DFL);
1060 signal(SIGALRM, SIG_DFL);
1062 DEFAULT(envshell, shell);
1063 setenv("TERM", termname, 1);
1064 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1065 execvp(args[0], args);
1073 if(waitpid(pid, &stat, 0) < 0)
1074 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1076 if(WIFEXITED(stat)) {
1077 exit(WEXITSTATUS(stat));
1086 struct winsize w = {term.row, term.col, 0, 0};
1088 /* seems to work fine on linux, openbsd and freebsd */
1089 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1090 die("openpty failed: %s\n", SERRNO);
1092 switch(pid = fork()) {
1094 die("fork failed\n");
1097 setsid(); /* create a new process group */
1098 dup2(s, STDIN_FILENO);
1099 dup2(s, STDOUT_FILENO);
1100 dup2(s, STDERR_FILENO);
1101 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1102 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1110 signal(SIGCHLD, sigchld);
1112 iofd = (!strcmp(opt_io, "-")) ?
1114 open(opt_io, O_WRONLY | O_CREAT, 0666);
1116 fprintf(stderr, "Error opening %s:%s\n",
1117 opt_io, strerror(errno));
1127 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1129 fprintf(stderr, "\n");
1134 static char buf[BUFSIZ];
1135 static int buflen = 0;
1138 int charsize; /* size of utf8 char in bytes */
1142 /* append read bytes to unprocessed bytes */
1143 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1144 die("Couldn't read from shell: %s\n", SERRNO);
1146 /* process every complete utf8 char */
1149 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1150 charsize = utf8decode(ptr, &utf8c);
1151 utf8encode(&utf8c, s);
1157 /* keep any uncomplete utf8 char for the next call */
1158 memmove(buf, ptr, buflen);
1162 ttywrite(const char *s, size_t n) {
1163 if(write(cmdfd, s, n) == -1)
1164 die("write error on tty: %s\n", SERRNO);
1171 w.ws_row = term.row;
1172 w.ws_col = term.col;
1173 w.ws_xpixel = xw.tw;
1174 w.ws_ypixel = xw.th;
1175 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1176 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1180 tsetdirt(int top, int bot) {
1183 LIMIT(top, 0, term.row-1);
1184 LIMIT(bot, 0, term.row-1);
1186 for(i = top; i <= bot; i++)
1192 tsetdirt(0, term.row-1);
1199 if(mode == CURSOR_SAVE) {
1201 } else if(mode == CURSOR_LOAD) {
1211 term.c = (TCursor){{
1215 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1217 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1218 for(i = tabspaces; i < term.col; i += tabspaces)
1221 term.bot = term.row - 1;
1222 term.mode = MODE_WRAP;
1224 tclearregion(0, 0, term.col-1, term.row-1);
1226 tcursor(CURSOR_SAVE);
1230 tnew(int col, int row) {
1231 memset(&term, 0, sizeof(Term));
1240 Line *tmp = term.line;
1242 term.line = term.alt;
1244 term.mode ^= MODE_ALTSCREEN;
1249 tscrolldown(int orig, int n) {
1253 LIMIT(n, 0, term.bot-orig+1);
1255 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1257 for(i = term.bot; i >= orig+n; i--) {
1258 temp = term.line[i];
1259 term.line[i] = term.line[i-n];
1260 term.line[i-n] = temp;
1263 term.dirty[i-n] = 1;
1270 tscrollup(int orig, int n) {
1273 LIMIT(n, 0, term.bot-orig+1);
1275 tclearregion(0, orig, term.col-1, orig+n-1);
1277 for(i = orig; i <= term.bot-n; i++) {
1278 temp = term.line[i];
1279 term.line[i] = term.line[i+n];
1280 term.line[i+n] = temp;
1283 term.dirty[i+n] = 1;
1286 selscroll(orig, -n);
1290 selscroll(int orig, int n) {
1294 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1295 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1299 if(sel.type == SEL_RECTANGULAR) {
1300 if(sel.by < term.top)
1302 if(sel.ey > term.bot)
1305 if(sel.by < term.top) {
1309 if(sel.ey > term.bot) {
1314 sel.b.y = sel.by, sel.b.x = sel.bx;
1315 sel.e.y = sel.ey, sel.e.x = sel.ex;
1320 tnewline(int first_col) {
1324 tscrollup(term.top, 1);
1328 tmoveto(first_col ? 0 : term.c.x, y);
1333 char *p = csiescseq.buf, *np;
1342 csiescseq.buf[csiescseq.len] = '\0';
1343 while(p < csiescseq.buf+csiescseq.len) {
1345 v = strtol(p, &np, 10);
1348 if(v == LONG_MAX || v == LONG_MIN)
1350 csiescseq.arg[csiescseq.narg++] = v;
1352 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1356 csiescseq.mode = *p;
1359 /* for absolute user moves, when decom is set */
1361 tmoveato(int x, int y) {
1362 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1366 tmoveto(int x, int y) {
1369 if(term.c.state & CURSOR_ORIGIN) {
1374 maxy = term.row - 1;
1376 LIMIT(x, 0, term.col-1);
1377 LIMIT(y, miny, maxy);
1378 term.c.state &= ~CURSOR_WRAPNEXT;
1384 tsetchar(char *c, Glyph *attr, int x, int y) {
1385 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1386 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1387 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1388 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1389 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1390 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1391 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1392 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1393 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1397 * The table is proudly stolen from rxvt.
1399 if(attr->mode & ATTR_GFX) {
1400 if(c[0] >= 0x41 && c[0] <= 0x7e
1401 && vt100_0[c[0] - 0x41]) {
1402 c = vt100_0[c[0] - 0x41];
1407 term.line[y][x] = *attr;
1408 memcpy(term.line[y][x].c, c, UTF_SIZ);
1412 tclearregion(int x1, int y1, int x2, int y2) {
1416 temp = x1, x1 = x2, x2 = temp;
1418 temp = y1, y1 = y2, y2 = temp;
1420 LIMIT(x1, 0, term.col-1);
1421 LIMIT(x2, 0, term.col-1);
1422 LIMIT(y1, 0, term.row-1);
1423 LIMIT(y2, 0, term.row-1);
1425 for(y = y1; y <= y2; y++) {
1427 for(x = x1; x <= x2; x++) {
1428 term.line[y][x] = term.c.attr;
1429 memcpy(term.line[y][x].c, " ", 2);
1435 tdeletechar(int n) {
1436 int src = term.c.x + n;
1438 int size = term.col - src;
1440 term.dirty[term.c.y] = 1;
1442 if(src >= term.col) {
1443 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1447 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1448 size * sizeof(Glyph));
1449 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1453 tinsertblank(int n) {
1456 int size = term.col - dst;
1458 term.dirty[term.c.y] = 1;
1460 if(dst >= term.col) {
1461 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1465 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1466 size * sizeof(Glyph));
1467 tclearregion(src, term.c.y, dst - 1, term.c.y);
1471 tinsertblankline(int n) {
1472 if(term.c.y < term.top || term.c.y > term.bot)
1475 tscrolldown(term.c.y, n);
1479 tdeleteline(int n) {
1480 if(term.c.y < term.top || term.c.y > term.bot)
1483 tscrollup(term.c.y, n);
1487 tsetattr(int *attr, int l) {
1490 for(i = 0; i < l; i++) {
1493 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1494 | ATTR_BOLD | ATTR_ITALIC \
1496 term.c.attr.fg = defaultfg;
1497 term.c.attr.bg = defaultbg;
1500 term.c.attr.mode |= ATTR_BOLD;
1503 term.c.attr.mode |= ATTR_ITALIC;
1506 term.c.attr.mode |= ATTR_UNDERLINE;
1508 case 5: /* slow blink */
1509 case 6: /* rapid blink */
1510 term.c.attr.mode |= ATTR_BLINK;
1513 term.c.attr.mode |= ATTR_REVERSE;
1517 term.c.attr.mode &= ~ATTR_BOLD;
1520 term.c.attr.mode &= ~ATTR_ITALIC;
1523 term.c.attr.mode &= ~ATTR_UNDERLINE;
1527 term.c.attr.mode &= ~ATTR_BLINK;
1530 term.c.attr.mode &= ~ATTR_REVERSE;
1533 if(i + 2 < l && attr[i + 1] == 5) {
1535 if(BETWEEN(attr[i], 0, 255)) {
1536 term.c.attr.fg = attr[i];
1539 "erresc: bad fgcolor %d\n",
1544 "erresc(38): gfx attr %d unknown\n",
1549 term.c.attr.fg = defaultfg;
1552 if(i + 2 < l && attr[i + 1] == 5) {
1554 if(BETWEEN(attr[i], 0, 255)) {
1555 term.c.attr.bg = attr[i];
1558 "erresc: bad bgcolor %d\n",
1563 "erresc(48): gfx attr %d unknown\n",
1568 term.c.attr.bg = defaultbg;
1571 if(BETWEEN(attr[i], 30, 37)) {
1572 term.c.attr.fg = attr[i] - 30;
1573 } else if(BETWEEN(attr[i], 40, 47)) {
1574 term.c.attr.bg = attr[i] - 40;
1575 } else if(BETWEEN(attr[i], 90, 97)) {
1576 term.c.attr.fg = attr[i] - 90 + 8;
1577 } else if(BETWEEN(attr[i], 100, 107)) {
1578 term.c.attr.bg = attr[i] - 100 + 8;
1581 "erresc(default): gfx attr %d unknown\n",
1582 attr[i]), csidump();
1590 tsetscroll(int t, int b) {
1593 LIMIT(t, 0, term.row-1);
1594 LIMIT(b, 0, term.row-1);
1604 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1607 tsetmode(bool priv, bool set, int *args, int narg) {
1611 for(lim = args + narg; args < lim; ++args) {
1615 case 1: /* DECCKM -- Cursor key */
1616 MODBIT(term.mode, set, MODE_APPCURSOR);
1618 case 5: /* DECSCNM -- Reverse video */
1620 MODBIT(term.mode, set, MODE_REVERSE);
1621 if(mode != term.mode)
1622 redraw(REDRAW_TIMEOUT);
1624 case 6: /* DECOM -- Origin */
1625 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1628 case 7: /* DECAWM -- Auto wrap */
1629 MODBIT(term.mode, set, MODE_WRAP);
1631 case 0: /* Error (IGNORED) */
1632 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1633 case 3: /* DECCOLM -- Column (IGNORED) */
1634 case 4: /* DECSCLM -- Scroll (IGNORED) */
1635 case 8: /* DECARM -- Auto repeat (IGNORED) */
1636 case 18: /* DECPFF -- Printer feed (IGNORED) */
1637 case 19: /* DECPEX -- Printer extent (IGNORED) */
1638 case 42: /* DECNRCM -- National characters (IGNORED) */
1639 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1641 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1642 MODBIT(term.mode, !set, MODE_HIDE);
1644 case 1000: /* 1000,1002: enable xterm mouse report */
1645 MODBIT(term.mode, set, MODE_MOUSEBTN);
1646 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1649 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1650 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1653 MODBIT(term.mode, set, MODE_MOUSESGR);
1656 MODBIT(term.mode, set, MODE_8BIT);
1658 case 1049: /* = 1047 and 1048 */
1661 if (!allowaltscreen)
1664 alt = IS_SET(MODE_ALTSCREEN);
1666 tclearregion(0, 0, term.col-1,
1669 if(set ^ alt) /* set is always 1 or 0 */
1675 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1679 "erresc: unknown private set/reset mode %d\n",
1685 case 0: /* Error (IGNORED) */
1687 case 2: /* KAM -- keyboard action */
1688 MODBIT(term.mode, set, MODE_KBDLOCK);
1690 case 4: /* IRM -- Insertion-replacement */
1691 MODBIT(term.mode, set, MODE_INSERT);
1693 case 12: /* SRM -- Send/Receive */
1694 MODBIT(term.mode, !set, MODE_ECHO);
1696 case 20: /* LNM -- Linefeed/new line */
1697 MODBIT(term.mode, set, MODE_CRLF);
1701 "erresc: unknown set/reset mode %d\n",
1713 switch(csiescseq.mode) {
1716 fprintf(stderr, "erresc: unknown csi ");
1720 case '@': /* ICH -- Insert <n> blank char */
1721 DEFAULT(csiescseq.arg[0], 1);
1722 tinsertblank(csiescseq.arg[0]);
1724 case 'A': /* CUU -- Cursor <n> Up */
1725 DEFAULT(csiescseq.arg[0], 1);
1726 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1728 case 'B': /* CUD -- Cursor <n> Down */
1729 case 'e': /* VPR --Cursor <n> Down */
1730 DEFAULT(csiescseq.arg[0], 1);
1731 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1733 case 'c': /* DA -- Device Attributes */
1734 if(csiescseq.arg[0] == 0)
1735 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1737 case 'C': /* CUF -- Cursor <n> Forward */
1738 case 'a': /* HPR -- Cursor <n> Forward */
1739 DEFAULT(csiescseq.arg[0], 1);
1740 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1742 case 'D': /* CUB -- Cursor <n> Backward */
1743 DEFAULT(csiescseq.arg[0], 1);
1744 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1746 case 'E': /* CNL -- Cursor <n> Down and first col */
1747 DEFAULT(csiescseq.arg[0], 1);
1748 tmoveto(0, term.c.y+csiescseq.arg[0]);
1750 case 'F': /* CPL -- Cursor <n> Up and first col */
1751 DEFAULT(csiescseq.arg[0], 1);
1752 tmoveto(0, term.c.y-csiescseq.arg[0]);
1754 case 'g': /* TBC -- Tabulation clear */
1755 switch(csiescseq.arg[0]) {
1756 case 0: /* clear current tab stop */
1757 term.tabs[term.c.x] = 0;
1759 case 3: /* clear all the tabs */
1760 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1766 case 'G': /* CHA -- Move to <col> */
1768 DEFAULT(csiescseq.arg[0], 1);
1769 tmoveto(csiescseq.arg[0]-1, term.c.y);
1771 case 'H': /* CUP -- Move to <row> <col> */
1773 DEFAULT(csiescseq.arg[0], 1);
1774 DEFAULT(csiescseq.arg[1], 1);
1775 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1777 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1778 DEFAULT(csiescseq.arg[0], 1);
1779 while(csiescseq.arg[0]--)
1782 case 'J': /* ED -- Clear screen */
1784 switch(csiescseq.arg[0]) {
1786 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1787 if(term.c.y < term.row-1) {
1788 tclearregion(0, term.c.y+1, term.col-1,
1794 tclearregion(0, 0, term.col-1, term.c.y-1);
1795 tclearregion(0, term.c.y, term.c.x, term.c.y);
1798 tclearregion(0, 0, term.col-1, term.row-1);
1804 case 'K': /* EL -- Clear line */
1805 switch(csiescseq.arg[0]) {
1807 tclearregion(term.c.x, term.c.y, term.col-1,
1811 tclearregion(0, term.c.y, term.c.x, term.c.y);
1814 tclearregion(0, term.c.y, term.col-1, term.c.y);
1818 case 'S': /* SU -- Scroll <n> line up */
1819 DEFAULT(csiescseq.arg[0], 1);
1820 tscrollup(term.top, csiescseq.arg[0]);
1822 case 'T': /* SD -- Scroll <n> line down */
1823 DEFAULT(csiescseq.arg[0], 1);
1824 tscrolldown(term.top, csiescseq.arg[0]);
1826 case 'L': /* IL -- Insert <n> blank lines */
1827 DEFAULT(csiescseq.arg[0], 1);
1828 tinsertblankline(csiescseq.arg[0]);
1830 case 'l': /* RM -- Reset Mode */
1831 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1833 case 'M': /* DL -- Delete <n> lines */
1834 DEFAULT(csiescseq.arg[0], 1);
1835 tdeleteline(csiescseq.arg[0]);
1837 case 'X': /* ECH -- Erase <n> char */
1838 DEFAULT(csiescseq.arg[0], 1);
1839 tclearregion(term.c.x, term.c.y,
1840 term.c.x + csiescseq.arg[0] - 1, term.c.y);
1842 case 'P': /* DCH -- Delete <n> char */
1843 DEFAULT(csiescseq.arg[0], 1);
1844 tdeletechar(csiescseq.arg[0]);
1846 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1847 DEFAULT(csiescseq.arg[0], 1);
1848 while(csiescseq.arg[0]--)
1851 case 'd': /* VPA -- Move to <row> */
1852 DEFAULT(csiescseq.arg[0], 1);
1853 tmoveato(term.c.x, csiescseq.arg[0]-1);
1855 case 'h': /* SM -- Set terminal mode */
1856 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1858 case 'm': /* SGR -- Terminal attribute (color) */
1859 tsetattr(csiescseq.arg, csiescseq.narg);
1861 case 'r': /* DECSTBM -- Set Scrolling Region */
1862 if(csiescseq.priv) {
1865 DEFAULT(csiescseq.arg[0], 1);
1866 DEFAULT(csiescseq.arg[1], term.row);
1867 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1871 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1872 tcursor(CURSOR_SAVE);
1874 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1875 tcursor(CURSOR_LOAD);
1886 for(i = 0; i < csiescseq.len; i++) {
1887 c = csiescseq.buf[i] & 0xff;
1890 } else if(c == '\n') {
1892 } else if(c == '\r') {
1894 } else if(c == 0x1b) {
1897 printf("(%02x)", c);
1905 memset(&csiescseq, 0, sizeof(csiescseq));
1914 narg = strescseq.narg;
1916 switch(strescseq.type) {
1917 case ']': /* OSC -- Operating System Command */
1918 switch(i = atoi(strescseq.args[0])) {
1923 xsettitle(strescseq.args[1]);
1925 case 4: /* color set */
1928 p = strescseq.args[2];
1930 case 104: /* color reset, here p = NULL */
1931 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
1932 if (!xsetcolorname(j, p)) {
1933 fprintf(stderr, "erresc: invalid color %s\n", p);
1936 * TODO if defaultbg color is changed, borders
1943 fprintf(stderr, "erresc: unknown str ");
1948 case 'k': /* old title set compatibility */
1949 xsettitle(strescseq.args[0]);
1951 case 'P': /* DSC -- Device Control String */
1952 case '_': /* APC -- Application Program Command */
1953 case '^': /* PM -- Privacy Message */
1955 fprintf(stderr, "erresc: unknown str ");
1964 char *p = strescseq.buf;
1967 strescseq.buf[strescseq.len] = '\0';
1968 while(p && strescseq.narg < STR_ARG_SIZ)
1969 strescseq.args[strescseq.narg++] = strsep(&p, ";");
1977 printf("ESC%c", strescseq.type);
1978 for(i = 0; i < strescseq.len; i++) {
1979 c = strescseq.buf[i] & 0xff;
1982 } else if(isprint(c)) {
1984 } else if(c == '\n') {
1986 } else if(c == '\r') {
1988 } else if(c == 0x1b) {
1991 printf("(%02x)", c);
1999 memset(&strescseq, 0, sizeof(strescseq));
2003 tputtab(bool forward) {
2009 for(++x; x < term.col && !term.tabs[x]; ++x)
2014 for(--x; x > 0 && !term.tabs[x]; --x)
2017 tmoveto(x, term.c.y);
2021 techo(char *buf, int len) {
2022 for(; len > 0; buf++, len--) {
2025 if(c == '\033') { /* escape */
2028 } else if(c < '\x20') { /* control code */
2029 if(c != '\n' && c != '\r' && c != '\t') {
2043 tputc(char *c, int len) {
2045 bool control = ascii < '\x20' || ascii == 0177;
2048 if(xwrite(iofd, c, len) < 0) {
2049 fprintf(stderr, "Error writing in %s:%s\n",
2050 opt_io, strerror(errno));
2057 * STR sequences must be checked before anything else
2058 * because it can use some control codes as part of the sequence.
2060 if(term.esc & ESC_STR) {
2063 term.esc = ESC_START | ESC_STR_END;
2065 case '\a': /* backwards compatibility to xterm */
2070 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2071 memmove(&strescseq.buf[strescseq.len], c, len);
2072 strescseq.len += len;
2075 * Here is a bug in terminals. If the user never sends
2076 * some code to stop the str or esc command, then st
2077 * will stop responding. But this is better than
2078 * silently failing with unknown characters. At least
2079 * then users will report back.
2081 * In the case users ever get fixed, here is the code:
2093 * Actions of control codes must be performed as soon they arrive
2094 * because they can be embedded inside a control sequence, and
2095 * they must not cause conflicts with sequences.
2103 tmoveto(term.c.x-1, term.c.y);
2106 tmoveto(0, term.c.y);
2111 /* go to first col if the mode is set */
2112 tnewline(IS_SET(MODE_CRLF));
2114 case '\a': /* BEL */
2115 if(!(xw.state & WIN_FOCUSED))
2118 case '\033': /* ESC */
2120 term.esc = ESC_START;
2122 case '\016': /* SO */
2123 case '\017': /* SI */
2125 * Different charsets are hard to handle. Applications
2126 * should use the right alt charset escapes for the
2127 * only reason they still exist: line drawing. The
2128 * rest is incompatible history st should not support.
2131 case '\032': /* SUB */
2132 case '\030': /* CAN */
2135 case '\005': /* ENQ (IGNORED) */
2136 case '\000': /* NUL (IGNORED) */
2137 case '\021': /* XON (IGNORED) */
2138 case '\023': /* XOFF (IGNORED) */
2139 case 0177: /* DEL (IGNORED) */
2142 } else if(term.esc & ESC_START) {
2143 if(term.esc & ESC_CSI) {
2144 csiescseq.buf[csiescseq.len++] = ascii;
2145 if(BETWEEN(ascii, 0x40, 0x7E)
2146 || csiescseq.len >= \
2147 sizeof(csiescseq.buf)-1) {
2152 } else if(term.esc & ESC_STR_END) {
2156 } else if(term.esc & ESC_ALTCHARSET) {
2158 case '0': /* Line drawing set */
2159 term.c.attr.mode |= ATTR_GFX;
2161 case 'B': /* USASCII */
2162 term.c.attr.mode &= ~ATTR_GFX;
2164 case 'A': /* UK (IGNORED) */
2165 case '<': /* multinational charset (IGNORED) */
2166 case '5': /* Finnish (IGNORED) */
2167 case 'C': /* Finnish (IGNORED) */
2168 case 'K': /* German (IGNORED) */
2171 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2174 } else if(term.esc & ESC_TEST) {
2175 if(ascii == '8') { /* DEC screen alignment test. */
2176 char E[UTF_SIZ] = "E";
2179 for(x = 0; x < term.col; ++x) {
2180 for(y = 0; y < term.row; ++y)
2181 tsetchar(E, &term.c.attr, x, y);
2188 term.esc |= ESC_CSI;
2191 term.esc |= ESC_TEST;
2193 case 'P': /* DCS -- Device Control String */
2194 case '_': /* APC -- Application Program Command */
2195 case '^': /* PM -- Privacy Message */
2196 case ']': /* OSC -- Operating System Command */
2197 case 'k': /* old title set compatibility */
2199 strescseq.type = ascii;
2200 term.esc |= ESC_STR;
2202 case '(': /* set primary charset G0 */
2203 term.esc |= ESC_ALTCHARSET;
2205 case ')': /* set secondary charset G1 (IGNORED) */
2206 case '*': /* set tertiary charset G2 (IGNORED) */
2207 case '+': /* set quaternary charset G3 (IGNORED) */
2210 case 'D': /* IND -- Linefeed */
2211 if(term.c.y == term.bot) {
2212 tscrollup(term.top, 1);
2214 tmoveto(term.c.x, term.c.y+1);
2218 case 'E': /* NEL -- Next line */
2219 tnewline(1); /* always go to first col */
2222 case 'H': /* HTS -- Horizontal tab stop */
2223 term.tabs[term.c.x] = 1;
2226 case 'M': /* RI -- Reverse index */
2227 if(term.c.y == term.top) {
2228 tscrolldown(term.top, 1);
2230 tmoveto(term.c.x, term.c.y-1);
2234 case 'Z': /* DECID -- Identify Terminal */
2235 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2238 case 'c': /* RIS -- Reset to inital state */
2243 case '=': /* DECPAM -- Application keypad */
2244 term.mode |= MODE_APPKEYPAD;
2247 case '>': /* DECPNM -- Normal keypad */
2248 term.mode &= ~MODE_APPKEYPAD;
2251 case '7': /* DECSC -- Save Cursor */
2252 tcursor(CURSOR_SAVE);
2255 case '8': /* DECRC -- Restore Cursor */
2256 tcursor(CURSOR_LOAD);
2259 case '\\': /* ST -- Stop */
2263 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2264 (uchar) ascii, isprint(ascii)? ascii:'.');
2269 * All characters which form part of a sequence are not
2275 * Display control codes only if we are in graphic mode
2277 if(control && !(term.c.attr.mode & ATTR_GFX))
2279 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2281 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2282 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2286 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2287 memmove(&term.line[term.c.y][term.c.x+1],
2288 &term.line[term.c.y][term.c.x],
2289 (term.col - term.c.x - 1) * sizeof(Glyph));
2292 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2293 if(term.c.x+1 < term.col) {
2294 tmoveto(term.c.x+1, term.c.y);
2296 term.c.state |= CURSOR_WRAPNEXT;
2301 tresize(int col, int row) {
2303 int minrow = MIN(row, term.row);
2304 int mincol = MIN(col, term.col);
2305 int slide = term.c.y - row + 1;
2309 if(col < 1 || row < 1)
2312 /* free unneeded rows */
2316 * slide screen to keep cursor where we expect it -
2317 * tscrollup would work here, but we can optimize to
2318 * memmove because we're freeing the earlier lines
2320 for(/* i = 0 */; i < slide; i++) {
2324 memmove(term.line, term.line + slide, row * sizeof(Line));
2325 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2327 for(i += row; i < term.row; i++) {
2332 /* resize to new height */
2333 term.line = xrealloc(term.line, row * sizeof(Line));
2334 term.alt = xrealloc(term.alt, row * sizeof(Line));
2335 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2336 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2338 /* resize each row to new width, zero-pad if needed */
2339 for(i = 0; i < minrow; i++) {
2341 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2342 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2345 /* allocate any new rows */
2346 for(/* i == minrow */; i < row; i++) {
2348 term.line[i] = xcalloc(col, sizeof(Glyph));
2349 term.alt [i] = xcalloc(col, sizeof(Glyph));
2351 if(col > term.col) {
2352 bp = term.tabs + term.col;
2354 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2355 while(--bp > term.tabs && !*bp)
2357 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2360 /* update terminal size */
2363 /* reset scrolling region */
2364 tsetscroll(0, row-1);
2365 /* make use of the LIMIT in tmoveto */
2366 tmoveto(term.c.x, term.c.y);
2367 /* Clearing both screens */
2370 if(mincol < col && 0 < minrow) {
2371 tclearregion(mincol, 0, col - 1, minrow - 1);
2373 if(0 < col && minrow < row) {
2374 tclearregion(0, minrow, col - 1, row - 1);
2377 } while(orig != term.line);
2383 xresize(int col, int row) {
2384 xw.tw = MAX(1, col * xw.cw);
2385 xw.th = MAX(1, row * xw.ch);
2387 XFreePixmap(xw.dpy, xw.buf);
2388 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2389 DefaultDepth(xw.dpy, xw.scr));
2390 XftDrawChange(xw.draw, xw.buf);
2391 xclear(0, 0, xw.w, xw.h);
2394 static inline ushort
2395 sixd_to_16bit(int x) {
2396 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2402 XRenderColor color = { .alpha = 0xffff };
2404 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2405 for(i = 0; i < LEN(colorname); i++) {
2408 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2409 die("Could not allocate color '%s'\n", colorname[i]);
2413 /* load colors [16-255] ; same colors as xterm */
2414 for(i = 16, r = 0; r < 6; r++) {
2415 for(g = 0; g < 6; g++) {
2416 for(b = 0; b < 6; b++) {
2417 color.red = sixd_to_16bit(r);
2418 color.green = sixd_to_16bit(g);
2419 color.blue = sixd_to_16bit(b);
2420 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2421 die("Could not allocate color %d\n", i);
2428 for(r = 0; r < 24; r++, i++) {
2429 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2430 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2432 die("Could not allocate color %d\n", i);
2438 xsetcolorname(int x, const char *name) {
2439 XRenderColor color = { .alpha = 0xffff };
2441 if (x < 0 || x > LEN(colorname))
2444 if(16 <= x && x < 16 + 216) {
2445 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2446 color.red = sixd_to_16bit(r);
2447 color.green = sixd_to_16bit(g);
2448 color.blue = sixd_to_16bit(b);
2449 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2450 return 0; /* something went wrong */
2453 } else if (16 + 216 <= x && x < 256) {
2454 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2455 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2456 return 0; /* something went wrong */
2460 name = colorname[x];
2463 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2470 xtermclear(int col1, int row1, int col2, int row2) {
2471 XftDrawRect(xw.draw,
2472 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2473 borderpx + col1 * xw.cw,
2474 borderpx + row1 * xw.ch,
2475 (col2-col1+1) * xw.cw,
2476 (row2-row1+1) * xw.ch);
2480 * Absolute coordinates.
2483 xclear(int x1, int y1, int x2, int y2) {
2484 XftDrawRect(xw.draw,
2485 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2486 x1, y1, x2-x1, y2-y1);
2491 XClassHint class = {opt_class ? opt_class : termname, termname};
2492 XWMHints wm = {.flags = InputHint, .input = 1};
2493 XSizeHints *sizeh = NULL;
2495 sizeh = XAllocSizeHints();
2496 if(xw.isfixed == False) {
2497 sizeh->flags = PSize | PResizeInc | PBaseSize;
2498 sizeh->height = xw.h;
2499 sizeh->width = xw.w;
2500 sizeh->height_inc = xw.ch;
2501 sizeh->width_inc = xw.cw;
2502 sizeh->base_height = 2 * borderpx;
2503 sizeh->base_width = 2 * borderpx;
2505 sizeh->flags = PMaxSize | PMinSize;
2506 sizeh->min_width = sizeh->max_width = xw.fw;
2507 sizeh->min_height = sizeh->max_height = xw.fh;
2510 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2515 xloadfont(Font *f, FcPattern *pattern) {
2519 match = FcFontMatch(NULL, pattern, &result);
2523 if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2524 FcPatternDestroy(match);
2528 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2529 FcPatternDestroy(match);
2533 f->pattern = FcPatternDuplicate(pattern);
2535 f->ascent = f->match->ascent;
2536 f->descent = f->match->descent;
2538 f->rbearing = f->match->max_advance_width;
2540 f->height = f->ascent + f->descent;
2541 f->width = f->lbearing + f->rbearing;
2547 xloadfonts(char *fontstr, int fontsize) {
2552 if(fontstr[0] == '-') {
2553 pattern = XftXlfdParse(fontstr, False, False);
2555 pattern = FcNameParse((FcChar8 *)fontstr);
2559 die("st: can't open font %s\n", fontstr);
2562 FcPatternDel(pattern, FC_PIXEL_SIZE);
2563 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2564 usedfontsize = fontsize;
2566 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2567 if(result == FcResultMatch) {
2568 usedfontsize = (int)fontval;
2571 * Default font size is 12, if none given. This is to
2572 * have a known usedfontsize value.
2574 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2579 FcConfigSubstitute(0, pattern, FcMatchPattern);
2580 FcDefaultSubstitute(pattern);
2582 if(xloadfont(&dc.font, pattern))
2583 die("st: can't open font %s\n", fontstr);
2585 /* Setting character width and height. */
2586 xw.cw = dc.font.width;
2587 xw.ch = dc.font.height;
2589 FcPatternDel(pattern, FC_SLANT);
2590 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2591 if(xloadfont(&dc.ifont, pattern))
2592 die("st: can't open font %s\n", fontstr);
2594 FcPatternDel(pattern, FC_WEIGHT);
2595 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2596 if(xloadfont(&dc.ibfont, pattern))
2597 die("st: can't open font %s\n", fontstr);
2599 FcPatternDel(pattern, FC_SLANT);
2600 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2601 if(xloadfont(&dc.bfont, pattern))
2602 die("st: can't open font %s\n", fontstr);
2604 FcPatternDestroy(pattern);
2608 xunloadfonts(void) {
2612 * Free the loaded fonts in the font cache. This is done backwards
2615 for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2618 XftFontClose(xw.dpy, frc[ip].font);
2623 XftFontClose(xw.dpy, dc.font.match);
2624 FcPatternDestroy(dc.font.pattern);
2625 FcFontSetDestroy(dc.font.set);
2626 XftFontClose(xw.dpy, dc.bfont.match);
2627 FcPatternDestroy(dc.bfont.pattern);
2628 FcFontSetDestroy(dc.bfont.set);
2629 XftFontClose(xw.dpy, dc.ifont.match);
2630 FcPatternDestroy(dc.ifont.pattern);
2631 FcFontSetDestroy(dc.ifont.set);
2632 XftFontClose(xw.dpy, dc.ibfont.match);
2633 FcPatternDestroy(dc.ibfont.pattern);
2634 FcFontSetDestroy(dc.ibfont.set);
2638 xzoom(const Arg *arg) {
2640 xloadfonts(usedfont, usedfontsize + arg->i);
2647 XSetWindowAttributes attrs;
2653 if(!(xw.dpy = XOpenDisplay(NULL)))
2654 die("Can't open display\n");
2655 xw.scr = XDefaultScreen(xw.dpy);
2656 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2660 die("Could not init fontconfig.\n");
2662 usedfont = (opt_font == NULL)? font : opt_font;
2663 xloadfonts(usedfont, 0);
2666 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2669 /* adjust fixed window geometry */
2671 sw = DisplayWidth(xw.dpy, xw.scr);
2672 sh = DisplayHeight(xw.dpy, xw.scr);
2674 xw.fx = sw + xw.fx - xw.fw - 1;
2676 xw.fy = sh + xw.fy - xw.fh - 1;
2681 /* window - default size */
2682 xw.h = 2 * borderpx + term.row * xw.ch;
2683 xw.w = 2 * borderpx + term.col * xw.cw;
2689 attrs.background_pixel = dc.col[defaultbg].pixel;
2690 attrs.border_pixel = dc.col[defaultbg].pixel;
2691 attrs.bit_gravity = NorthWestGravity;
2692 attrs.event_mask = FocusChangeMask | KeyPressMask
2693 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2694 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2695 attrs.colormap = xw.cmap;
2697 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2698 XRootWindow(xw.dpy, xw.scr);
2699 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2700 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2702 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2706 memset(&gcvalues, 0, sizeof(gcvalues));
2707 gcvalues.graphics_exposures = False;
2708 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2710 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2711 DefaultDepth(xw.dpy, xw.scr));
2712 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2713 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2715 /* Xft rendering context */
2716 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2719 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2720 XSetLocaleModifiers("@im=local");
2721 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2722 XSetLocaleModifiers("@im=");
2723 if((xw.xim = XOpenIM(xw.dpy,
2724 NULL, NULL, NULL)) == NULL) {
2725 die("XOpenIM failed. Could not open input"
2730 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2731 | XIMStatusNothing, XNClientWindow, xw.win,
2732 XNFocusWindow, xw.win, NULL);
2734 die("XCreateIC failed. Could not obtain input method.\n");
2736 /* white cursor, black outline */
2737 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2738 XDefineCursor(xw.dpy, xw.win, cursor);
2739 XRecolorCursor(xw.dpy, cursor,
2740 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2741 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2743 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2744 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2745 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2748 XMapWindow(xw.dpy, xw.win);
2754 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2755 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2756 width = charlen * xw.cw, xp, i;
2758 int u8fl, u8fblen, u8cblen, doesexist;
2761 Font *font = &dc.font;
2763 FcPattern *fcpattern, *fontpattern;
2764 FcFontSet *fcsets[] = { NULL };
2765 FcCharSet *fccharset;
2766 Colour *fg, *bg, *temp, revfg, revbg;
2767 XRenderColor colfg, colbg;
2770 frcflags = FRC_NORMAL;
2772 if(base.mode & ATTR_ITALIC) {
2773 if(base.fg == defaultfg)
2774 base.fg = defaultitalic;
2776 frcflags = FRC_ITALIC;
2777 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2778 if(base.fg == defaultfg)
2779 base.fg = defaultitalic;
2781 frcflags = FRC_ITALICBOLD;
2782 } else if(base.mode & ATTR_UNDERLINE) {
2783 if(base.fg == defaultfg)
2784 base.fg = defaultunderline;
2786 fg = &dc.col[base.fg];
2787 bg = &dc.col[base.bg];
2789 if(base.mode & ATTR_BOLD) {
2790 if(BETWEEN(base.fg, 0, 7)) {
2791 /* basic system colors */
2792 fg = &dc.col[base.fg + 8];
2793 } else if(BETWEEN(base.fg, 16, 195)) {
2795 fg = &dc.col[base.fg + 36];
2796 } else if(BETWEEN(base.fg, 232, 251)) {
2798 fg = &dc.col[base.fg + 4];
2801 * Those ranges will not be brightened:
2802 * 8 - 15 – bright system colors
2803 * 196 - 231 – highest 256 color cube
2804 * 252 - 255 – brightest colors in greyscale
2807 frcflags = FRC_BOLD;
2810 if(IS_SET(MODE_REVERSE)) {
2811 if(fg == &dc.col[defaultfg]) {
2812 fg = &dc.col[defaultbg];
2814 colfg.red = ~fg->color.red;
2815 colfg.green = ~fg->color.green;
2816 colfg.blue = ~fg->color.blue;
2817 colfg.alpha = fg->color.alpha;
2818 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2822 if(bg == &dc.col[defaultbg]) {
2823 bg = &dc.col[defaultfg];
2825 colbg.red = ~bg->color.red;
2826 colbg.green = ~bg->color.green;
2827 colbg.blue = ~bg->color.blue;
2828 colbg.alpha = bg->color.alpha;
2829 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2834 if(base.mode & ATTR_REVERSE) {
2840 /* Intelligent cleaning up of the borders. */
2842 xclear(0, (y == 0)? 0 : winy, borderpx,
2843 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2845 if(x + charlen >= term.col) {
2846 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2847 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2850 xclear(winx, 0, winx + width, borderpx);
2852 xclear(winx, winy + xw.ch, winx + width, xw.h);
2854 /* Clean up the region we want to draw to. */
2855 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2860 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
2862 fcsets[0] = font->set;
2863 for(xp = winx; bytelen > 0;) {
2865 * Search for the range in the to be printed string of glyphs
2866 * that are in the main font. Then print that range. If
2867 * some glyph is found that is not in the font, do the
2875 u8cblen = utf8decode(s, &u8char);
2879 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2880 if(!doesexist || bytelen <= 0) {
2889 XftDrawStringUtf8(xw.draw, fg,
2891 winy + font->ascent,
2894 xp += font->width * u8fl;
2907 /* Search the font cache. */
2908 for(i = 0; i < frclen; i++, frp--) {
2912 if(frc[frp].c == u8char
2913 && frc[frp].flags == frcflags) {
2918 /* Nothing was found. */
2921 * Nothing was found in the cache. Now use
2922 * some dozen of Fontconfig calls to get the
2923 * font for one single character.
2925 fcpattern = FcPatternDuplicate(font->pattern);
2926 fccharset = FcCharSetCreate();
2928 FcCharSetAddChar(fccharset, u8char);
2929 FcPatternAddCharSet(fcpattern, FC_CHARSET,
2931 FcPatternAddBool(fcpattern, FC_SCALABLE,
2934 FcConfigSubstitute(0, fcpattern,
2936 FcDefaultSubstitute(fcpattern);
2938 fontpattern = FcFontSetMatch(0, fcsets,
2939 FcTrue, fcpattern, &fcres);
2942 * Overwrite or create the new cache entry.
2946 if(frccur >= LEN(frc))
2948 if(frclen > LEN(frc)) {
2950 XftFontClose(xw.dpy, frc[frccur].font);
2953 frc[frccur].font = XftFontOpenPattern(xw.dpy,
2955 frc[frccur].c = u8char;
2956 frc[frccur].flags = frcflags;
2958 FcPatternDestroy(fcpattern);
2959 FcCharSetDestroy(fccharset);
2964 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2965 xp, winy + frc[frp].font->ascent,
2966 (FcChar8 *)u8c, u8cblen);
2972 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2973 winy + font->ascent, (FcChar8 *)s, bytelen);
2976 if(base.mode & ATTR_UNDERLINE) {
2977 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2981 /* Reset clip to none. */
2982 XftDrawSetClip(xw.draw, 0);
2987 static int oldx = 0, oldy = 0;
2989 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
2991 LIMIT(oldx, 0, term.col-1);
2992 LIMIT(oldy, 0, term.row-1);
2994 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2996 /* remove the old cursor */
2997 sl = utf8size(term.line[oldy][oldx].c);
2998 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3001 /* draw the new one */
3002 if(!(IS_SET(MODE_HIDE))) {
3003 if(xw.state & WIN_FOCUSED) {
3004 if(IS_SET(MODE_REVERSE)) {
3005 g.mode |= ATTR_REVERSE;
3011 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
3013 XftDrawRect(xw.draw, &dc.col[defaultcs],
3014 borderpx + term.c.x * xw.cw,
3015 borderpx + term.c.y * xw.ch,
3017 XftDrawRect(xw.draw, &dc.col[defaultcs],
3018 borderpx + term.c.x * xw.cw,
3019 borderpx + term.c.y * xw.ch,
3021 XftDrawRect(xw.draw, &dc.col[defaultcs],
3022 borderpx + (term.c.x + 1) * xw.cw - 1,
3023 borderpx + term.c.y * xw.ch,
3025 XftDrawRect(xw.draw, &dc.col[defaultcs],
3026 borderpx + term.c.x * xw.cw,
3027 borderpx + (term.c.y + 1) * xw.ch - 1,
3030 oldx = term.c.x, oldy = term.c.y;
3036 xsettitle(char *p) {
3039 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3041 XSetWMName(xw.dpy, xw.win, &prop);
3046 xsettitle(opt_title ? opt_title : "st");
3050 redraw(int timeout) {
3051 struct timespec tv = {0, timeout * 1000};
3057 nanosleep(&tv, NULL);
3058 XSync(xw.dpy, False); /* necessary for a good tput flash */
3064 drawregion(0, 0, term.col, term.row);
3065 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3067 XSetForeground(xw.dpy, dc.gc,
3068 dc.col[IS_SET(MODE_REVERSE)?
3069 defaultfg : defaultbg].pixel);
3073 drawregion(int x1, int y1, int x2, int y2) {
3074 int ic, ib, x, y, ox, sl;
3076 char buf[DRAW_BUF_SIZ];
3077 bool ena_sel = sel.bx != -1;
3079 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3082 if(!(xw.state & WIN_VISIBLE))
3085 for(y = y1; y < y2; y++) {
3089 xtermclear(0, y, term.col, y);
3091 base = term.line[y][0];
3093 for(x = x1; x < x2; x++) {
3094 new = term.line[y][x];
3095 if(ena_sel && *(new.c) && selected(x, y))
3096 new.mode ^= ATTR_REVERSE;
3097 if(ib > 0 && (ATTRCMP(base, new)
3098 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3099 xdraws(buf, base, ox, y, ic, ib);
3107 sl = utf8size(new.c);
3108 memcpy(buf+ib, new.c, sl);
3113 xdraws(buf, base, ox, y, ic, ib);
3119 expose(XEvent *ev) {
3120 XExposeEvent *e = &ev->xexpose;
3122 if(xw.state & WIN_REDRAW) {
3124 xw.state &= ~WIN_REDRAW;
3130 visibility(XEvent *ev) {
3131 XVisibilityEvent *e = &ev->xvisibility;
3133 if(e->state == VisibilityFullyObscured) {
3134 xw.state &= ~WIN_VISIBLE;
3135 } else if(!(xw.state & WIN_VISIBLE)) {
3136 /* need a full redraw for next Expose, not just a buf copy */
3137 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3143 xw.state &= ~WIN_VISIBLE;
3147 xseturgency(int add) {
3148 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3150 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3151 XSetWMHints(xw.dpy, xw.win, h);
3157 XFocusChangeEvent *e = &ev->xfocus;
3159 if(e->mode == NotifyGrab)
3162 if(ev->type == FocusIn) {
3163 XSetICFocus(xw.xic);
3164 xw.state |= WIN_FOCUSED;
3167 XUnsetICFocus(xw.xic);
3168 xw.state &= ~WIN_FOCUSED;
3173 match(uint mask, uint state) {
3174 state &= ~(ignoremod);
3176 if(mask == XK_NO_MOD && state)
3178 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3180 if((state & mask) != state)
3186 numlock(const Arg *dummy) {
3191 kmap(KeySym k, uint state) {
3196 /* Check for mapped keys out of X11 function keys. */
3197 for(i = 0; i < LEN(mappedkeys); i++) {
3198 if(mappedkeys[i] == k)
3201 if(i == LEN(mappedkeys)) {
3202 if((k & 0xFFFF) < 0xFD00)
3206 for(kp = key; kp < key + LEN(key); kp++) {
3212 if(!match(mask, state))
3215 if(kp->appkey > 0) {
3216 if(!IS_SET(MODE_APPKEYPAD))
3218 if(term.numlock && kp->appkey == 2)
3220 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3224 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3226 && !IS_SET(MODE_APPCURSOR))) {
3230 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3231 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3242 kpress(XEvent *ev) {
3243 XKeyEvent *e = &ev->xkey;
3245 char xstr[31], buf[32], *customkey, *cp = buf;
3251 if(IS_SET(MODE_KBDLOCK))
3254 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3255 e->state &= ~Mod2Mask;
3257 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3258 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3259 bp->func(&(bp->arg));
3264 /* 2. custom keys from config.h */
3265 if((customkey = kmap(ksym, e->state))) {
3266 len = strlen(customkey);
3267 memcpy(buf, customkey, len);
3268 /* 3. hardcoded (overrides X lookup) */
3273 if(len == 1 && e->state & Mod1Mask) {
3274 if(IS_SET(MODE_8BIT)) {
3277 ret = utf8encode(&c, cp);
3286 memcpy(cp, xstr, len);
3287 len = cp - buf + len;
3291 if(IS_SET(MODE_ECHO))
3297 cmessage(XEvent *e) {
3300 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3302 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3303 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3304 xw.state |= WIN_FOCUSED;
3306 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3307 xw.state &= ~WIN_FOCUSED;
3309 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3310 /* Send SIGHUP to shell */
3317 cresize(int width, int height) {
3325 col = (xw.w - 2 * borderpx) / xw.cw;
3326 row = (xw.h - 2 * borderpx) / xw.ch;
3335 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3338 cresize(e->xconfigure.width, e->xconfigure.height);
3345 int xfd = XConnectionNumber(xw.dpy), xev;
3346 struct timeval drawtimeout, *tv = NULL, now, last;
3348 gettimeofday(&last, NULL);
3350 for(xev = actionfps;;) {
3352 FD_SET(cmdfd, &rfd);
3354 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3357 die("select failed: %s\n", SERRNO);
3360 gettimeofday(&now, NULL);
3361 drawtimeout.tv_sec = 0;
3362 drawtimeout.tv_usec = (1000/xfps) * 1000;
3365 if(FD_ISSET(cmdfd, &rfd))
3368 if(FD_ISSET(xfd, &rfd))
3371 if(TIMEDIFF(now, last) > \
3372 (xev ? (1000/xfps) : (1000/actionfps))) {
3373 while(XPending(xw.dpy)) {
3374 XNextEvent(xw.dpy, &ev);
3375 if(XFilterEvent(&ev, None))
3377 if(handler[ev.type])
3378 (handler[ev.type])(&ev);
3385 if(xev && !FD_ISSET(xfd, &rfd))
3387 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
3395 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3396 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3397 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3401 main(int argc, char *argv[]) {
3405 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3410 allowaltscreen = false;
3413 opt_class = EARGF(usage());
3416 /* eat all remaining arguments */
3421 opt_font = EARGF(usage());
3424 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3429 if(bitm & WidthValue)
3431 if(bitm & HeightValue)
3433 if(bitm & XNegative && xw.fx == 0)
3435 if(bitm & XNegative && xw.fy == 0)
3438 if(xw.fh != 0 && xw.fw != 0)
3442 opt_io = EARGF(usage());
3445 opt_title = EARGF(usage());
3448 opt_embed = EARGF(usage());
3456 setlocale(LC_CTYPE, "");
3457 XSetLocaleModifiers("");
3463 cresize(xw.h, xw.w);