1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
23 #include <X11/Xatom.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/extensions/Xdbe.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
34 #define Draw XftDraw *
35 #define Colour XftColor
36 #define Colourmap Colormap
40 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
42 #elif defined(__FreeBSD__) || defined(__DragonFly__)
47 "st " VERSION " (c) 2010-2013 st engineers\n" \
48 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
49 " [-t title] [-w windowid] [-e command ...]\n"
52 #define XEMBED_FOCUS_IN 4
53 #define XEMBED_FOCUS_OUT 5
57 #define ESC_BUF_SIZ (128*UTF_SIZ)
58 #define ESC_ARG_SIZ 16
59 #define STR_BUF_SIZ ESC_BUF_SIZ
60 #define STR_ARG_SIZ ESC_ARG_SIZ
61 #define DRAW_BUF_SIZ 20*1024
62 #define XK_ANY_MOD UINT_MAX
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 {
91 enum cursor_movement {
114 MODE_MOUSEMOTION = 64,
120 MODE_APPCURSOR = 2048
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 */
140 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
142 typedef unsigned char uchar;
143 typedef unsigned int uint;
144 typedef unsigned long ulong;
145 typedef unsigned short ushort;
148 char c[UTF_SIZ]; /* character code */
149 uchar mode; /* attribute flags */
150 ushort fg; /* foreground */
151 ushort bg; /* background */
152 uchar state; /* state flags */
158 Glyph attr; /* current char attributes */
164 /* CSI Escape sequence structs */
165 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
167 char buf[ESC_BUF_SIZ]; /* raw string */
168 int len; /* raw string length */
170 int arg[ESC_ARG_SIZ];
171 int narg; /* nb of args */
175 /* STR Escape sequence structs */
176 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
178 char type; /* ESC type ... */
179 char buf[STR_BUF_SIZ]; /* raw string */
180 int len; /* raw string length */
181 char *args[STR_ARG_SIZ];
182 int narg; /* nb of args */
185 /* Internal representation of the screen */
187 int row; /* nb row */
188 int col; /* nb col */
189 Line *line; /* screen */
190 Line *alt; /* alternate screen */
191 bool *dirty; /* dirtyness of lines */
192 TCursor c; /* cursor */
193 int top; /* top scroll limit */
194 int bot; /* bottom scroll limit */
195 int mode; /* terminal mode flags */
196 int esc; /* escape state flags */
197 bool numlock; /* lock numbers in keyboard */
201 /* Purely graphic info */
207 Atom xembed, wmdeletewin;
213 bool isfixed; /* is fixed geometry? */
214 int fx, fy, fw, fh; /* fixed geometry */
215 int tw, th; /* tty width and height */
216 int w, h; /* window width and height */
217 int ch; /* char height */
218 int cw; /* char width */
219 char state; /* focus, redraw, visible */
226 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
227 signed char appkey; /* application keypad */
228 signed char appcursor; /* application cursor */
229 signed char crlf; /* crlf mode */
232 /* TODO: use better name for vars... */
243 struct timeval tclick1;
244 struct timeval tclick2;
257 void (*func)(const Arg *);
261 /* function definitions used in config.h */
262 static void xzoom(const Arg *);
263 static void selpaste(const Arg *);
264 static void numlock(const Arg *);
266 /* Config.h for applying patches and the configuration. */
282 /* Drawing Context */
284 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
285 Font font, bfont, ifont, ibfont;
289 static void die(const char *, ...);
290 static void draw(void);
291 static void redraw(int);
292 static void drawregion(int, int, int, int);
293 static void execsh(void);
294 static void sigchld(int);
295 static void run(void);
297 static void csidump(void);
298 static void csihandle(void);
299 static void csiparse(void);
300 static void csireset(void);
301 static void strdump(void);
302 static void strhandle(void);
303 static void strparse(void);
304 static void strreset(void);
306 static void tclearregion(int, int, int, int, int);
307 static void tcursor(int);
308 static void tdeletechar(int);
309 static void tdeleteline(int);
310 static void tinsertblank(int);
311 static void tinsertblankline(int);
312 static void tmoveto(int, int);
313 static void tmoveato(int x, int y);
314 static void tnew(int, int);
315 static void tnewline(int);
316 static void tputtab(bool);
317 static void tputc(char *, int);
318 static void treset(void);
319 static int tresize(int, int);
320 static void tscrollup(int, int);
321 static void tscrolldown(int, int);
322 static void tsetattr(int*, int);
323 static void tsetchar(char *, Glyph *, int, int);
324 static void tsetscroll(int, int);
325 static void tswapscreen(void);
326 static void tsetdirt(int, int);
327 static void tsetmode(bool, bool, int *, int);
328 static void tfulldirt(void);
329 static void techo(char *, int);
331 static inline bool match(uint, uint);
332 static void ttynew(void);
333 static void ttyread(void);
334 static void ttyresize(void);
335 static void ttywrite(const char *, size_t);
337 static void xdraws(char *, Glyph, int, int, int, int);
338 static void xhints(void);
339 static void xclear(int, int, int, int);
340 static void xdrawcursor(void);
341 static void xinit(void);
342 static void xloadcols(void);
343 static int xloadfont(Font *, FcPattern *);
344 static void xloadfonts(char *, int);
345 static void xresettitle(void);
346 static void xseturgency(int);
347 static void xsetsel(char*);
348 static void xtermclear(int, int, int, int);
349 static void xunloadfonts(void);
350 static void xresize(int, int);
352 static void expose(XEvent *);
353 static void visibility(XEvent *);
354 static void unmap(XEvent *);
355 static char *kmap(KeySym, uint);
356 static void kpress(XEvent *);
357 static void cmessage(XEvent *);
358 static void cresize(int, int);
359 static void resize(XEvent *);
360 static void focus(XEvent *);
361 static void brelease(XEvent *);
362 static void bpress(XEvent *);
363 static void bmotion(XEvent *);
364 static void selnotify(XEvent *);
365 static void selclear(XEvent *);
366 static void selrequest(XEvent *);
368 static void selinit(void);
369 static inline bool selected(int, int);
370 static void selcopy(void);
371 static void selscroll(int, int);
373 static int utf8decode(char *, long *);
374 static int utf8encode(long *, char *);
375 static int utf8size(char *);
376 static int isfullutf8(char *, int);
378 static ssize_t xwrite(int, char *, size_t);
379 static void *xmalloc(size_t);
380 static void *xrealloc(void *, size_t);
381 static void *xcalloc(size_t, size_t);
383 static void (*handler[LASTEvent])(XEvent *) = {
385 [ClientMessage] = cmessage,
386 [ConfigureNotify] = resize,
387 [VisibilityNotify] = visibility,
388 [UnmapNotify] = unmap,
392 [MotionNotify] = bmotion,
393 [ButtonPress] = bpress,
394 [ButtonRelease] = brelease,
395 [SelectionClear] = selclear,
396 [SelectionNotify] = selnotify,
397 [SelectionRequest] = selrequest,
404 static CSIEscape csiescseq;
405 static STREscape strescseq;
408 static Selection sel;
409 static int iofd = -1;
410 static char **opt_cmd = NULL;
411 static char *opt_io = NULL;
412 static char *opt_title = NULL;
413 static char *opt_embed = NULL;
414 static char *opt_class = NULL;
415 static char *opt_font = NULL;
419 static char *usedfont = NULL;
420 static int usedfontsize = 0;
422 /* Font Ring Cache */
437 * Fontcache is a ring buffer, with frccur as current position and frclen as
438 * the current length of used elements.
441 static Fontcache frc[1024];
442 static int frccur = -1, frclen = 0;
445 xwrite(int fd, char *s, size_t len) {
449 ssize_t r = write(fd, s, len);
459 xmalloc(size_t len) {
460 void *p = malloc(len);
463 die("Out of memory\n");
469 xrealloc(void *p, size_t len) {
470 if((p = realloc(p, len)) == NULL)
471 die("Out of memory\n");
477 xcalloc(size_t nmemb, size_t size) {
478 void *p = calloc(nmemb, size);
481 die("Out of memory\n");
487 utf8decode(char *s, long *u) {
493 if(~c & B7) { /* 0xxxxxxx */
496 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
497 *u = c&(B4|B3|B2|B1|B0);
499 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
500 *u = c&(B3|B2|B1|B0);
502 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
509 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
511 if((c & (B7|B6)) != B7) /* 10xxxxxx */
514 *u |= c & (B5|B4|B3|B2|B1|B0);
517 if((n == 1 && *u < 0x80) ||
518 (n == 2 && *u < 0x800) ||
519 (n == 3 && *u < 0x10000) ||
520 (*u >= 0xD800 && *u <= 0xDFFF)) {
532 utf8encode(long *u, char *s) {
540 *sp = uc; /* 0xxxxxxx */
542 } else if(*u < 0x800) {
543 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
545 } else if(uc < 0x10000) {
546 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
548 } else if(uc <= 0x10FFFF) {
549 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
555 for(i=n,++sp; i>0; --i,++sp)
556 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
568 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
569 UTF-8 otherwise return 0 */
571 isfullutf8(char *s, int b) {
579 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
581 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
583 ((b == 2) && (*c2&(B7|B6)) == B7))) {
585 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
587 ((b == 2) && (*c2&(B7|B6)) == B7) ||
588 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
601 } else if((c&(B7|B6|B5)) == (B7|B6)) {
603 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
612 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
613 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
617 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
618 if(sel.xtarget == None)
619 sel.xtarget = XA_STRING;
627 return LIMIT(x, 0, term.col-1);
635 return LIMIT(y, 0, term.row-1);
639 selected(int x, int y) {
642 if(sel.ey == y && sel.by == y) {
643 bx = MIN(sel.bx, sel.ex);
644 ex = MAX(sel.bx, sel.ex);
645 return BETWEEN(x, bx, ex);
648 return ((sel.b.y < y && y < sel.e.y)
649 || (y == sel.e.y && x <= sel.e.x))
650 || (y == sel.b.y && x >= sel.b.x
651 && (x <= sel.e.x || sel.b.y != sel.e.y));
655 getbuttoninfo(XEvent *e) {
656 sel.alt = IS_SET(MODE_ALTSCREEN);
658 sel.ex = x2col(e->xbutton.x);
659 sel.ey = y2row(e->xbutton.y);
661 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
662 sel.b.y = MIN(sel.by, sel.ey);
663 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
664 sel.e.y = MAX(sel.by, sel.ey);
668 mousereport(XEvent *e) {
669 int x = x2col(e->xbutton.x);
670 int y = y2row(e->xbutton.y);
671 int button = e->xbutton.button;
672 int state = e->xbutton.state;
673 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
674 static int ob, ox, oy;
677 if(e->xbutton.type == MotionNotify) {
678 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
682 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
688 if(e->xbutton.type == ButtonPress) {
694 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
695 + (state & Mod4Mask ? 8 : 0)
696 + (state & ControlMask ? 16 : 0);
698 ttywrite(buf, sizeof(buf));
703 if(IS_SET(MODE_MOUSE)) {
705 } else if(e->xbutton.button == Button1) {
708 tsetdirt(sel.b.y, sel.e.y);
712 sel.ex = sel.bx = x2col(e->xbutton.x);
713 sel.ey = sel.by = y2row(e->xbutton.y);
714 } else if(e->xbutton.button == Button4) {
716 } else if(e->xbutton.button == Button5) {
724 int x, y, bufsize, is_selected = 0, size;
730 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
731 ptr = str = xmalloc(bufsize);
733 /* append every set & selected glyph to the selection */
734 for(y = 0; y < term.row; y++) {
735 gp = &term.line[y][0];
736 last = gp + term.col;
738 while(--last >= gp && !(last->state & GLYPH_SET))
741 for(x = 0; gp <= last; x++, ++gp) {
742 if(!(is_selected = selected(x, y)))
745 p = (gp->state & GLYPH_SET) ? gp->c : " ";
747 memcpy(ptr, p, size);
750 /* \n at the end of every selected line except for the last one */
751 if(is_selected && y < sel.e.y)
760 selnotify(XEvent *e) {
761 ulong nitems, ofs, rem;
768 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
769 False, AnyPropertyType, &type, &format,
770 &nitems, &rem, &data)) {
771 fprintf(stderr, "Clipboard allocation failed\n");
774 ttywrite((const char *) data, nitems * format / 8);
776 /* number of 32-bit chunks returned */
777 ofs += nitems * format / 32;
782 selpaste(const Arg *dummy) {
783 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
784 xw.win, CurrentTime);
787 void selclear(XEvent *e) {
791 tsetdirt(sel.b.y, sel.e.y);
795 selrequest(XEvent *e) {
796 fprintf(stderr, "selrequest\n");
797 XSelectionRequestEvent *xsre;
799 Atom xa_targets, string;
801 xsre = (XSelectionRequestEvent *) e;
802 xev.type = SelectionNotify;
803 xev.requestor = xsre->requestor;
804 xev.selection = xsre->selection;
805 xev.target = xsre->target;
806 xev.time = xsre->time;
810 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
811 if(xsre->target == xa_targets) {
812 /* respond with the supported type */
813 string = sel.xtarget;
814 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
815 XA_ATOM, 32, PropModeReplace,
816 (uchar *) &string, 1);
817 xev.property = xsre->property;
818 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
819 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
820 xsre->target, 8, PropModeReplace,
821 (uchar *) sel.clip, strlen(sel.clip));
822 xev.property = xsre->property;
825 /* all done, send a notification to the listener */
826 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
827 fprintf(stderr, "Error sending SelectionNotify event\n");
832 fprintf(stderr, "xsetsel: %s\n", str);
833 /* register the selection for both the clipboard and the primary */
839 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
841 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
842 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
846 brelease(XEvent *e) {
847 fprintf(stderr, "brelease\n");
850 if(IS_SET(MODE_MOUSE)) {
855 if(e->xbutton.button == Button2) {
857 } else if(e->xbutton.button == Button1) {
860 term.dirty[sel.ey] = 1;
861 if(sel.bx == sel.ex && sel.by == sel.ey) {
863 gettimeofday(&now, NULL);
865 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
866 /* triple click on the line */
867 sel.b.x = sel.bx = 0;
868 sel.e.x = sel.ex = term.col;
869 sel.b.y = sel.e.y = sel.ey;
871 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
872 /* double click to select word */
874 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
875 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
879 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
880 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
884 sel.b.y = sel.e.y = sel.ey;
892 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
893 gettimeofday(&sel.tclick1, NULL);
898 int starty, endy, oldey, oldex;
900 if(IS_SET(MODE_MOUSE)) {
912 if(oldey != sel.ey || oldex != sel.ex) {
913 starty = MIN(oldey, sel.ey);
914 endy = MAX(oldey, sel.ey);
915 tsetdirt(starty, endy);
920 die(const char *errstr, ...) {
923 va_start(ap, errstr);
924 vfprintf(stderr, errstr, ap);
932 char *envshell = getenv("SHELL");
933 const struct passwd *pass = getpwuid(getuid());
934 char buf[sizeof(long) * 8 + 1];
941 setenv("LOGNAME", pass->pw_name, 1);
942 setenv("USER", pass->pw_name, 1);
943 setenv("SHELL", pass->pw_shell, 0);
944 setenv("HOME", pass->pw_dir, 0);
947 snprintf(buf, sizeof(buf), "%lu", xw.win);
948 setenv("WINDOWID", buf, 1);
950 signal(SIGCHLD, SIG_DFL);
951 signal(SIGHUP, SIG_DFL);
952 signal(SIGINT, SIG_DFL);
953 signal(SIGQUIT, SIG_DFL);
954 signal(SIGTERM, SIG_DFL);
955 signal(SIGALRM, SIG_DFL);
957 DEFAULT(envshell, shell);
958 setenv("TERM", termname, 1);
959 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
960 execvp(args[0], args);
968 if(waitpid(pid, &stat, 0) < 0)
969 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
971 if(WIFEXITED(stat)) {
972 exit(WEXITSTATUS(stat));
981 struct winsize w = {term.row, term.col, 0, 0};
983 /* seems to work fine on linux, openbsd and freebsd */
984 if(openpty(&m, &s, NULL, NULL, &w) < 0)
985 die("openpty failed: %s\n", SERRNO);
987 switch(pid = fork()) {
989 die("fork failed\n");
992 setsid(); /* create a new process group */
993 dup2(s, STDIN_FILENO);
994 dup2(s, STDOUT_FILENO);
995 dup2(s, STDERR_FILENO);
996 if(ioctl(s, TIOCSCTTY, NULL) < 0)
997 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1005 signal(SIGCHLD, sigchld);
1007 iofd = (!strcmp(opt_io, "-")) ?
1009 open(opt_io, O_WRONLY | O_CREAT, 0666);
1011 fprintf(stderr, "Error opening %s:%s\n",
1012 opt_io, strerror(errno));
1022 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1024 fprintf(stderr, "\n");
1029 static char buf[BUFSIZ];
1030 static int buflen = 0;
1033 int charsize; /* size of utf8 char in bytes */
1037 /* append read bytes to unprocessed bytes */
1038 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1039 die("Couldn't read from shell: %s\n", SERRNO);
1041 /* process every complete utf8 char */
1044 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1045 charsize = utf8decode(ptr, &utf8c);
1046 utf8encode(&utf8c, s);
1052 /* keep any uncomplete utf8 char for the next call */
1053 memmove(buf, ptr, buflen);
1057 ttywrite(const char *s, size_t n) {
1058 if(write(cmdfd, s, n) == -1)
1059 die("write error on tty: %s\n", SERRNO);
1066 w.ws_row = term.row;
1067 w.ws_col = term.col;
1068 w.ws_xpixel = xw.tw;
1069 w.ws_ypixel = xw.th;
1070 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1071 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1075 tsetdirt(int top, int bot) {
1078 LIMIT(top, 0, term.row-1);
1079 LIMIT(bot, 0, term.row-1);
1081 for(i = top; i <= bot; i++)
1087 tsetdirt(0, term.row-1);
1094 if(mode == CURSOR_SAVE) {
1096 } else if(mode == CURSOR_LOAD) {
1106 term.c = (TCursor){{
1110 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1112 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1113 for(i = tabspaces; i < term.col; i += tabspaces)
1116 term.bot = term.row - 1;
1117 term.mode = MODE_WRAP;
1119 tclearregion(0, 0, term.col-1, term.row-1, 0);
1121 tcursor(CURSOR_SAVE);
1125 tnew(int col, int row) {
1126 /* set screen size */
1129 term.line = xmalloc(term.row * sizeof(Line));
1130 term.alt = xmalloc(term.row * sizeof(Line));
1131 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1132 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1134 for(row = 0; row < term.row; row++) {
1135 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1136 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1137 term.dirty[row] = 0;
1141 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1148 Line *tmp = term.line;
1150 term.line = term.alt;
1152 term.mode ^= MODE_ALTSCREEN;
1157 tscrolldown(int orig, int n) {
1161 LIMIT(n, 0, term.bot-orig+1);
1163 tclearregion(0, term.bot-n+1, term.col-1, term.bot, 0);
1165 for(i = term.bot; i >= orig+n; i--) {
1166 temp = term.line[i];
1167 term.line[i] = term.line[i-n];
1168 term.line[i-n] = temp;
1171 term.dirty[i-n] = 1;
1178 tscrollup(int orig, int n) {
1181 LIMIT(n, 0, term.bot-orig+1);
1183 tclearregion(0, orig, term.col-1, orig+n-1, 0);
1185 for(i = orig; i <= term.bot-n; i++) {
1186 temp = term.line[i];
1187 term.line[i] = term.line[i+n];
1188 term.line[i+n] = temp;
1191 term.dirty[i+n] = 1;
1194 selscroll(orig, -n);
1198 selscroll(int orig, int n) {
1202 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1203 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1207 if(sel.by < term.top) {
1211 if(sel.ey > term.bot) {
1215 sel.b.y = sel.by, sel.b.x = sel.bx;
1216 sel.e.y = sel.ey, sel.e.x = sel.ex;
1221 tnewline(int first_col) {
1225 tscrollup(term.top, 1);
1229 tmoveto(first_col ? 0 : term.c.x, y);
1234 /* int noarg = 1; */
1235 char *p = csiescseq.buf;
1239 csiescseq.priv = 1, p++;
1241 while(p < csiescseq.buf+csiescseq.len) {
1242 while(isdigit(*p)) {
1243 csiescseq.arg[csiescseq.narg] *= 10;
1244 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1246 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1247 csiescseq.narg++, p++;
1249 csiescseq.mode = *p;
1257 /* for absolute user moves, when decom is set */
1259 tmoveato(int x, int y) {
1260 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1264 tmoveto(int x, int y) {
1267 if(term.c.state & CURSOR_ORIGIN) {
1272 maxy = term.row - 1;
1274 LIMIT(x, 0, term.col-1);
1275 LIMIT(y, miny, maxy);
1276 term.c.state &= ~CURSOR_WRAPNEXT;
1282 tsetchar(char *c, Glyph *attr, int x, int y) {
1283 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1284 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1285 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1286 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1287 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1288 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1289 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1290 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1291 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1295 * The table is proudly stolen from rxvt.
1297 if(attr->mode & ATTR_GFX) {
1298 if(c[0] >= 0x41 && c[0] <= 0x7e
1299 && vt100_0[c[0] - 0x41]) {
1300 c = vt100_0[c[0] - 0x41];
1305 term.line[y][x] = *attr;
1306 memcpy(term.line[y][x].c, c, UTF_SIZ);
1307 term.line[y][x].state |= GLYPH_SET;
1311 tclearregion(int x1, int y1, int x2, int y2, int bce) {
1315 temp = x1, x1 = x2, x2 = temp;
1317 temp = y1, y1 = y2, y2 = temp;
1319 LIMIT(x1, 0, term.col-1);
1320 LIMIT(x2, 0, term.col-1);
1321 LIMIT(y1, 0, term.row-1);
1322 LIMIT(y2, 0, term.row-1);
1324 for(y = y1; y <= y2; y++) {
1326 for(x = x1; x <= x2; x++) {
1328 term.line[y][x] = term.c.attr;
1329 memcpy(term.line[y][x].c, " ", 2);
1330 term.line[y][x].state |= GLYPH_SET;
1332 term.line[y][x].state = 0;
1339 tdeletechar(int n) {
1340 int src = term.c.x + n;
1342 int size = term.col - src;
1344 term.dirty[term.c.y] = 1;
1346 if(src >= term.col) {
1347 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1351 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1352 size * sizeof(Glyph));
1353 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y, 0);
1357 tinsertblank(int n) {
1360 int size = term.col - dst;
1362 term.dirty[term.c.y] = 1;
1364 if(dst >= term.col) {
1365 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1369 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1370 size * sizeof(Glyph));
1371 tclearregion(src, term.c.y, dst - 1, term.c.y, 0);
1375 tinsertblankline(int n) {
1376 if(term.c.y < term.top || term.c.y > term.bot)
1379 tscrolldown(term.c.y, n);
1383 tdeleteline(int n) {
1384 if(term.c.y < term.top || term.c.y > term.bot)
1387 tscrollup(term.c.y, n);
1391 tsetattr(int *attr, int l) {
1394 for(i = 0; i < l; i++) {
1397 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1398 | ATTR_ITALIC | ATTR_BLINK);
1399 term.c.attr.fg = defaultfg;
1400 term.c.attr.bg = defaultbg;
1403 term.c.attr.mode |= ATTR_BOLD;
1406 term.c.attr.mode |= ATTR_ITALIC;
1409 term.c.attr.mode |= ATTR_UNDERLINE;
1412 term.c.attr.mode |= ATTR_BLINK;
1415 term.c.attr.mode |= ATTR_REVERSE;
1419 term.c.attr.mode &= ~ATTR_BOLD;
1422 term.c.attr.mode &= ~ATTR_ITALIC;
1425 term.c.attr.mode &= ~ATTR_UNDERLINE;
1428 term.c.attr.mode &= ~ATTR_BLINK;
1431 term.c.attr.mode &= ~ATTR_REVERSE;
1434 if(i + 2 < l && attr[i + 1] == 5) {
1436 if(BETWEEN(attr[i], 0, 255)) {
1437 term.c.attr.fg = attr[i];
1440 "erresc: bad fgcolor %d\n",
1445 "erresc(38): gfx attr %d unknown\n",
1450 term.c.attr.fg = defaultfg;
1453 if(i + 2 < l && attr[i + 1] == 5) {
1455 if(BETWEEN(attr[i], 0, 255)) {
1456 term.c.attr.bg = attr[i];
1459 "erresc: bad bgcolor %d\n",
1464 "erresc(48): gfx attr %d unknown\n",
1469 term.c.attr.bg = defaultbg;
1472 if(BETWEEN(attr[i], 30, 37)) {
1473 term.c.attr.fg = attr[i] - 30;
1474 } else if(BETWEEN(attr[i], 40, 47)) {
1475 term.c.attr.bg = attr[i] - 40;
1476 } else if(BETWEEN(attr[i], 90, 97)) {
1477 term.c.attr.fg = attr[i] - 90 + 8;
1478 } else if(BETWEEN(attr[i], 100, 107)) {
1479 term.c.attr.bg = attr[i] - 100 + 8;
1482 "erresc(default): gfx attr %d unknown\n",
1483 attr[i]), csidump();
1491 tsetscroll(int t, int b) {
1494 LIMIT(t, 0, term.row-1);
1495 LIMIT(b, 0, term.row-1);
1505 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1508 tsetmode(bool priv, bool set, int *args, int narg) {
1512 for(lim = args + narg; args < lim; ++args) {
1516 case 1: /* DECCKM -- Cursor key */
1517 MODBIT(term.mode, set, MODE_APPCURSOR);
1519 case 5: /* DECSCNM -- Reverse video */
1521 MODBIT(term.mode, set, MODE_REVERSE);
1522 if(mode != term.mode)
1523 redraw(REDRAW_TIMEOUT);
1525 case 6: /* DECOM -- Origin */
1526 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1529 case 7: /* DECAWM -- Auto wrap */
1530 MODBIT(term.mode, set, MODE_WRAP);
1532 case 0: /* Error (IGNORED) */
1533 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1534 case 3: /* DECCOLM -- Column (IGNORED) */
1535 case 4: /* DECSCLM -- Scroll (IGNORED) */
1536 case 8: /* DECARM -- Auto repeat (IGNORED) */
1537 case 18: /* DECPFF -- Printer feed (IGNORED) */
1538 case 19: /* DECPEX -- Printer extent (IGNORED) */
1539 case 42: /* DECNRCM -- National characters (IGNORED) */
1540 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1542 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1543 MODBIT(term.mode, !set, MODE_HIDE);
1545 case 1000: /* 1000,1002: enable xterm mouse report */
1546 MODBIT(term.mode, set, MODE_MOUSEBTN);
1549 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1551 case 1049: /* = 1047 and 1048 */
1554 alt = IS_SET(MODE_ALTSCREEN);
1556 tclearregion(0, 0, term.col-1,
1559 if(set ^ alt) /* set is always 1 or 0 */
1566 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1570 "erresc: unknown private set/reset mode %d\n",
1576 case 0: /* Error (IGNORED) */
1578 case 2: /* KAM -- keyboard action */
1579 MODBIT(term.mode, set, MODE_KBDLOCK);
1581 case 4: /* IRM -- Insertion-replacement */
1582 MODBIT(term.mode, set, MODE_INSERT);
1584 case 12: /* SRM -- Send/Receive */
1585 MODBIT(term.mode, !set, MODE_ECHO);
1587 case 20: /* LNM -- Linefeed/new line */
1588 MODBIT(term.mode, set, MODE_CRLF);
1592 "erresc: unknown set/reset mode %d\n",
1604 switch(csiescseq.mode) {
1607 fprintf(stderr, "erresc: unknown csi ");
1611 case '@': /* ICH -- Insert <n> blank char */
1612 DEFAULT(csiescseq.arg[0], 1);
1613 tinsertblank(csiescseq.arg[0]);
1615 case 'A': /* CUU -- Cursor <n> Up */
1616 DEFAULT(csiescseq.arg[0], 1);
1617 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1619 case 'B': /* CUD -- Cursor <n> Down */
1620 case 'e': /* VPR --Cursor <n> Down */
1621 DEFAULT(csiescseq.arg[0], 1);
1622 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1624 case 'c': /* DA -- Device Attributes */
1625 if(csiescseq.arg[0] == 0)
1626 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1628 case 'C': /* CUF -- Cursor <n> Forward */
1629 case 'a': /* HPR -- Cursor <n> Forward */
1630 DEFAULT(csiescseq.arg[0], 1);
1631 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1633 case 'D': /* CUB -- Cursor <n> Backward */
1634 DEFAULT(csiescseq.arg[0], 1);
1635 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1637 case 'E': /* CNL -- Cursor <n> Down and first col */
1638 DEFAULT(csiescseq.arg[0], 1);
1639 tmoveto(0, term.c.y+csiescseq.arg[0]);
1641 case 'F': /* CPL -- Cursor <n> Up and first col */
1642 DEFAULT(csiescseq.arg[0], 1);
1643 tmoveto(0, term.c.y-csiescseq.arg[0]);
1645 case 'g': /* TBC -- Tabulation clear */
1646 switch (csiescseq.arg[0]) {
1647 case 0: /* clear current tab stop */
1648 term.tabs[term.c.x] = 0;
1650 case 3: /* clear all the tabs */
1651 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1657 case 'G': /* CHA -- Move to <col> */
1659 DEFAULT(csiescseq.arg[0], 1);
1660 tmoveto(csiescseq.arg[0]-1, term.c.y);
1662 case 'H': /* CUP -- Move to <row> <col> */
1664 DEFAULT(csiescseq.arg[0], 1);
1665 DEFAULT(csiescseq.arg[1], 1);
1666 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1668 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1669 DEFAULT(csiescseq.arg[0], 1);
1670 while(csiescseq.arg[0]--)
1673 case 'J': /* ED -- Clear screen */
1675 switch(csiescseq.arg[0]) {
1677 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
1678 if(term.c.y < term.row-1) {
1679 tclearregion(0, term.c.y+1, term.col-1,
1685 tclearregion(0, 0, term.col-1, term.c.y-1, 1);
1686 tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1689 tclearregion(0, 0, term.col-1, term.row-1, 1);
1695 case 'K': /* EL -- Clear line */
1696 switch(csiescseq.arg[0]) {
1698 tclearregion(term.c.x, term.c.y, term.col-1,
1702 tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1705 tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
1709 case 'S': /* SU -- Scroll <n> line up */
1710 DEFAULT(csiescseq.arg[0], 1);
1711 tscrollup(term.top, csiescseq.arg[0]);
1713 case 'T': /* SD -- Scroll <n> line down */
1714 DEFAULT(csiescseq.arg[0], 1);
1715 tscrolldown(term.top, csiescseq.arg[0]);
1717 case 'L': /* IL -- Insert <n> blank lines */
1718 DEFAULT(csiescseq.arg[0], 1);
1719 tinsertblankline(csiescseq.arg[0]);
1721 case 'l': /* RM -- Reset Mode */
1722 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1724 case 'M': /* DL -- Delete <n> lines */
1725 DEFAULT(csiescseq.arg[0], 1);
1726 tdeleteline(csiescseq.arg[0]);
1728 case 'X': /* ECH -- Erase <n> char */
1729 DEFAULT(csiescseq.arg[0], 1);
1730 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0],
1733 case 'P': /* DCH -- Delete <n> char */
1734 DEFAULT(csiescseq.arg[0], 1);
1735 tdeletechar(csiescseq.arg[0]);
1737 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1738 DEFAULT(csiescseq.arg[0], 1);
1739 while(csiescseq.arg[0]--)
1742 case 'd': /* VPA -- Move to <row> */
1743 DEFAULT(csiescseq.arg[0], 1);
1744 tmoveato(term.c.x, csiescseq.arg[0]-1);
1746 case 'h': /* SM -- Set terminal mode */
1747 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1749 case 'm': /* SGR -- Terminal attribute (color) */
1750 tsetattr(csiescseq.arg, csiescseq.narg);
1752 case 'r': /* DECSTBM -- Set Scrolling Region */
1753 if(csiescseq.priv) {
1756 DEFAULT(csiescseq.arg[0], 1);
1757 DEFAULT(csiescseq.arg[1], term.row);
1758 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1762 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1763 tcursor(CURSOR_SAVE);
1765 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1766 tcursor(CURSOR_LOAD);
1777 for(i = 0; i < csiescseq.len; i++) {
1778 c = csiescseq.buf[i] & 0xff;
1781 } else if(c == '\n') {
1783 } else if(c == '\r') {
1785 } else if(c == 0x1b) {
1788 printf("(%02x)", c);
1796 memset(&csiescseq, 0, sizeof(csiescseq));
1804 * TODO: make this being useful in case of color palette change.
1810 switch(strescseq.type) {
1811 case ']': /* OSC -- Operating System Command */
1817 * TODO: Handle special chars in string, like umlauts.
1820 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1824 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1826 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1829 fprintf(stderr, "erresc: unknown str ");
1834 case 'k': /* old title set compatibility */
1835 XStoreName(xw.dpy, xw.win, strescseq.buf);
1837 case 'P': /* DSC -- Device Control String */
1838 case '_': /* APC -- Application Program Command */
1839 case '^': /* PM -- Privacy Message */
1841 fprintf(stderr, "erresc: unknown str ");
1851 * TODO: Implement parsing like for CSI when required.
1852 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1862 printf("ESC%c", strescseq.type);
1863 for(i = 0; i < strescseq.len; i++) {
1864 c = strescseq.buf[i] & 0xff;
1867 } else if(c == '\n') {
1869 } else if(c == '\r') {
1871 } else if(c == 0x1b) {
1874 printf("(%02x)", c);
1882 memset(&strescseq, 0, sizeof(strescseq));
1886 tputtab(bool forward) {
1892 for(++x; x < term.col && !term.tabs[x]; ++x)
1897 for(--x; x > 0 && !term.tabs[x]; --x)
1900 tmoveto(x, term.c.y);
1904 techo(char *buf, int len) {
1905 for(; len > 0; buf++, len--) {
1908 if(c == '\033') { /* escape */
1911 } else if (c < '\x20') { /* control code */
1912 if(c != '\n' && c != '\r' && c != '\t') {
1926 tputc(char *c, int len) {
1928 bool control = ascii < '\x20' || ascii == 0177;
1931 if (xwrite(iofd, c, len) < 0) {
1932 fprintf(stderr, "Error writing in %s:%s\n",
1933 opt_io, strerror(errno));
1940 * STR sequences must be checked before anything else
1941 * because it can use some control codes as part of the sequence.
1943 if(term.esc & ESC_STR) {
1946 term.esc = ESC_START | ESC_STR_END;
1948 case '\a': /* backwards compatibility to xterm */
1953 if(strescseq.len + len < sizeof(strescseq.buf)) {
1954 memmove(&strescseq.buf[strescseq.len], c, len);
1955 strescseq.len += len;
1958 * Here is a bug in terminals. If the user never sends
1959 * some code to stop the str or esc command, then st
1960 * will stop responding. But this is better than
1961 * silently failing with unknown characters. At least
1962 * then users will report back.
1964 * In the case users ever get fixed, here is the code:
1976 * Actions of control codes must be performed as soon they arrive
1977 * because they can be embedded inside a control sequence, and
1978 * they must not cause conflicts with sequences.
1986 tmoveto(term.c.x-1, term.c.y);
1989 tmoveto(0, term.c.y);
1994 /* go to first col if the mode is set */
1995 tnewline(IS_SET(MODE_CRLF));
1997 case '\a': /* BEL */
1998 if(!(xw.state & WIN_FOCUSED))
2001 case '\033': /* ESC */
2003 term.esc = ESC_START;
2005 case '\016': /* SO */
2006 case '\017': /* SI */
2008 * Different charsets are hard to handle. Applications
2009 * should use the right alt charset escapes for the
2010 * only reason they still exist: line drawing. The
2011 * rest is incompatible history st should not support.
2014 case '\032': /* SUB */
2015 case '\030': /* CAN */
2018 case '\005': /* ENQ (IGNORED) */
2019 case '\000': /* NUL (IGNORED) */
2020 case '\021': /* XON (IGNORED) */
2021 case '\023': /* XOFF (IGNORED) */
2022 case 0177: /* DEL (IGNORED) */
2025 } else if(term.esc & ESC_START) {
2026 if(term.esc & ESC_CSI) {
2027 csiescseq.buf[csiescseq.len++] = ascii;
2028 if(BETWEEN(ascii, 0x40, 0x7E)
2029 || csiescseq.len >= ESC_BUF_SIZ) {
2031 csiparse(), csihandle();
2033 } else if(term.esc & ESC_STR_END) {
2037 } else if(term.esc & ESC_ALTCHARSET) {
2039 case '0': /* Line drawing set */
2040 term.c.attr.mode |= ATTR_GFX;
2042 case 'B': /* USASCII */
2043 term.c.attr.mode &= ~ATTR_GFX;
2045 case 'A': /* UK (IGNORED) */
2046 case '<': /* multinational charset (IGNORED) */
2047 case '5': /* Finnish (IGNORED) */
2048 case 'C': /* Finnish (IGNORED) */
2049 case 'K': /* German (IGNORED) */
2052 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2055 } else if(term.esc & ESC_TEST) {
2056 if(ascii == '8') { /* DEC screen alignment test. */
2057 char E[UTF_SIZ] = "E";
2060 for(x = 0; x < term.col; ++x) {
2061 for(y = 0; y < term.row; ++y)
2062 tsetchar(E, &term.c.attr, x, y);
2069 term.esc |= ESC_CSI;
2072 term.esc |= ESC_TEST;
2074 case 'P': /* DCS -- Device Control String */
2075 case '_': /* APC -- Application Program Command */
2076 case '^': /* PM -- Privacy Message */
2077 case ']': /* OSC -- Operating System Command */
2078 case 'k': /* old title set compatibility */
2080 strescseq.type = ascii;
2081 term.esc |= ESC_STR;
2083 case '(': /* set primary charset G0 */
2084 term.esc |= ESC_ALTCHARSET;
2086 case ')': /* set secondary charset G1 (IGNORED) */
2087 case '*': /* set tertiary charset G2 (IGNORED) */
2088 case '+': /* set quaternary charset G3 (IGNORED) */
2091 case 'D': /* IND -- Linefeed */
2092 if(term.c.y == term.bot) {
2093 tscrollup(term.top, 1);
2095 tmoveto(term.c.x, term.c.y+1);
2099 case 'E': /* NEL -- Next line */
2100 tnewline(1); /* always go to first col */
2103 case 'H': /* HTS -- Horizontal tab stop */
2104 term.tabs[term.c.x] = 1;
2107 case 'M': /* RI -- Reverse index */
2108 if(term.c.y == term.top) {
2109 tscrolldown(term.top, 1);
2111 tmoveto(term.c.x, term.c.y-1);
2115 case 'Z': /* DECID -- Identify Terminal */
2116 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2119 case 'c': /* RIS -- Reset to inital state */
2124 case '=': /* DECPAM -- Application keypad */
2125 term.mode |= MODE_APPKEYPAD;
2128 case '>': /* DECPNM -- Normal keypad */
2129 term.mode &= ~MODE_APPKEYPAD;
2132 case '7': /* DECSC -- Save Cursor */
2133 tcursor(CURSOR_SAVE);
2136 case '8': /* DECRC -- Restore Cursor */
2137 tcursor(CURSOR_LOAD);
2140 case '\\': /* ST -- Stop */
2144 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2145 (uchar) ascii, isprint(ascii)? ascii:'.');
2150 * All characters which form part of a sequence are not
2156 * Display control codes only if we are in graphic mode
2158 if(control && !(term.c.attr.mode & ATTR_GFX))
2160 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2162 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2163 tnewline(1); /* always go to first col */
2165 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2166 memmove(&term.line[term.c.y][term.c.x+1],
2167 &term.line[term.c.y][term.c.x],
2168 (term.col - term.c.x - 1) * sizeof(Glyph));
2171 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2172 if(term.c.x+1 < term.col) {
2173 tmoveto(term.c.x+1, term.c.y);
2175 term.c.state |= CURSOR_WRAPNEXT;
2180 tresize(int col, int row) {
2182 int minrow = MIN(row, term.row);
2183 int mincol = MIN(col, term.col);
2184 int slide = term.c.y - row + 1;
2187 if(col < 1 || row < 1)
2190 /* free unneeded rows */
2193 /* slide screen to keep cursor where we expect it -
2194 * tscrollup would work here, but we can optimize to
2195 * memmove because we're freeing the earlier lines */
2196 for(/* i = 0 */; i < slide; i++) {
2200 memmove(term.line, term.line + slide, row * sizeof(Line));
2201 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2203 for(i += row; i < term.row; i++) {
2208 /* resize to new height */
2209 term.line = xrealloc(term.line, row * sizeof(Line));
2210 term.alt = xrealloc(term.alt, row * sizeof(Line));
2211 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2212 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2214 /* resize each row to new width, zero-pad if needed */
2215 for(i = 0; i < minrow; i++) {
2217 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2218 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2219 for(x = mincol; x < col; x++) {
2220 term.line[i][x].state = 0;
2221 term.alt[i][x].state = 0;
2225 /* allocate any new rows */
2226 for(/* i == minrow */; i < row; i++) {
2228 term.line[i] = xcalloc(col, sizeof(Glyph));
2229 term.alt [i] = xcalloc(col, sizeof(Glyph));
2231 if(col > term.col) {
2232 bp = term.tabs + term.col;
2234 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2235 while(--bp > term.tabs && !*bp)
2237 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2240 /* update terminal size */
2243 /* reset scrolling region */
2244 tsetscroll(0, row-1);
2245 /* make use of the LIMIT in tmoveto */
2246 tmoveto(term.c.x, term.c.y);
2252 xresize(int col, int row) {
2253 xw.tw = MAX(1, col * xw.cw);
2254 xw.th = MAX(1, row * xw.ch);
2257 XFreePixmap(xw.dpy, xw.buf);
2258 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2259 DefaultDepth(xw.dpy, xw.scr));
2260 XSetForeground(xw.dpy, dc.gc, 0);
2261 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2264 XftDrawChange(xw.draw, xw.buf);
2270 XRenderColor color = { .alpha = 0 };
2272 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2273 for(i = 0; i < LEN(colorname); i++) {
2276 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2277 die("Could not allocate color '%s'\n", colorname[i]);
2281 /* load colors [16-255] ; same colors as xterm */
2282 for(i = 16, r = 0; r < 6; r++) {
2283 for(g = 0; g < 6; g++) {
2284 for(b = 0; b < 6; b++) {
2285 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2286 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2287 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2288 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2289 die("Could not allocate color %d\n", i);
2296 for(r = 0; r < 24; r++, i++) {
2297 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2298 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2300 die("Could not allocate color %d\n", i);
2306 xtermclear(int col1, int row1, int col2, int row2) {
2307 XftDrawRect(xw.draw,
2308 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2309 borderpx + col1 * xw.cw,
2310 borderpx + row1 * xw.ch,
2311 (col2-col1+1) * xw.cw,
2312 (row2-row1+1) * xw.ch);
2316 * Absolute coordinates.
2319 xclear(int x1, int y1, int x2, int y2) {
2320 XftDrawRect(xw.draw,
2321 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2322 x1, y1, x2-x1, y2-y1);
2327 XClassHint class = {opt_class ? opt_class : termname, termname};
2328 XWMHints wm = {.flags = InputHint, .input = 1};
2329 XSizeHints *sizeh = NULL;
2331 sizeh = XAllocSizeHints();
2332 if(xw.isfixed == False) {
2333 sizeh->flags = PSize | PResizeInc | PBaseSize;
2334 sizeh->height = xw.h;
2335 sizeh->width = xw.w;
2336 sizeh->height_inc = xw.ch;
2337 sizeh->width_inc = xw.cw;
2338 sizeh->base_height = 2 * borderpx;
2339 sizeh->base_width = 2 * borderpx;
2341 sizeh->flags = PMaxSize | PMinSize;
2342 sizeh->min_width = sizeh->max_width = xw.fw;
2343 sizeh->min_height = sizeh->max_height = xw.fh;
2346 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2351 xloadfont(Font *f, FcPattern *pattern) {
2355 match = FcFontMatch(NULL, pattern, &result);
2359 if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2360 FcPatternDestroy(match);
2364 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2365 FcPatternDestroy(match);
2369 f->pattern = FcPatternDuplicate(pattern);
2371 f->ascent = f->match->ascent;
2372 f->descent = f->match->descent;
2374 f->rbearing = f->match->max_advance_width;
2376 f->height = f->match->height;
2377 f->width = f->lbearing + f->rbearing;
2383 xloadfonts(char *fontstr, int fontsize) {
2388 if(fontstr[0] == '-') {
2389 pattern = XftXlfdParse(fontstr, False, False);
2391 pattern = FcNameParse((FcChar8 *)fontstr);
2395 die("st: can't open font %s\n", fontstr);
2398 FcPatternDel(pattern, FC_PIXEL_SIZE);
2399 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2400 usedfontsize = fontsize;
2402 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2403 if(result == FcResultMatch) {
2404 usedfontsize = (int)fontval;
2407 * Default font size is 12, if none given. This is to
2408 * have a known usedfontsize value.
2410 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2415 FcConfigSubstitute(0, pattern, FcMatchPattern);
2416 FcDefaultSubstitute(pattern);
2418 if(xloadfont(&dc.font, pattern))
2419 die("st: can't open font %s\n", fontstr);
2421 /* Setting character width and height. */
2422 xw.cw = dc.font.width;
2423 xw.ch = dc.font.height;
2425 FcPatternDel(pattern, FC_WEIGHT);
2426 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2427 if(xloadfont(&dc.bfont, pattern))
2428 die("st: can't open font %s\n", fontstr);
2430 FcPatternDel(pattern, FC_SLANT);
2431 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2432 if(xloadfont(&dc.ibfont, pattern))
2433 die("st: can't open font %s\n", fontstr);
2435 FcPatternDel(pattern, FC_WEIGHT);
2436 if(xloadfont(&dc.ifont, pattern))
2437 die("st: can't open font %s\n", fontstr);
2439 FcPatternDestroy(pattern);
2448 * Free the loaded fonts in the font cache. This is done backwards
2451 for (i = 0, ip = frccur; i < frclen; i++, ip--) {
2454 XftFontClose(xw.dpy, frc[ip].font);
2459 XftFontClose(xw.dpy, dc.font.match);
2460 FcPatternDestroy(dc.font.pattern);
2461 FcFontSetDestroy(dc.font.set);
2462 XftFontClose(xw.dpy, dc.bfont.match);
2463 FcPatternDestroy(dc.bfont.pattern);
2464 FcFontSetDestroy(dc.bfont.set);
2465 XftFontClose(xw.dpy, dc.ifont.match);
2466 FcPatternDestroy(dc.ifont.pattern);
2467 FcFontSetDestroy(dc.ifont.set);
2468 XftFontClose(xw.dpy, dc.ibfont.match);
2469 FcPatternDestroy(dc.ibfont.pattern);
2470 FcFontSetDestroy(dc.ibfont.set);
2474 xzoom(const Arg *arg)
2477 xloadfonts(usedfont, usedfontsize + arg->i);
2484 XSetWindowAttributes attrs;
2488 int sw, sh, major, minor;
2490 if(!(xw.dpy = XOpenDisplay(NULL)))
2491 die("Can't open display\n");
2492 xw.scr = XDefaultScreen(xw.dpy);
2493 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2497 die("Could not init fontconfig.\n");
2499 usedfont = (opt_font == NULL)? font : opt_font;
2500 xloadfonts(usedfont, 0);
2503 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2506 /* adjust fixed window geometry */
2508 sw = DisplayWidth(xw.dpy, xw.scr);
2509 sh = DisplayHeight(xw.dpy, xw.scr);
2511 xw.fx = sw + xw.fx - xw.fw - 1;
2513 xw.fy = sh + xw.fy - xw.fh - 1;
2518 /* window - default size */
2519 xw.h = 2 * borderpx + term.row * xw.ch;
2520 xw.w = 2 * borderpx + term.col * xw.cw;
2526 attrs.background_pixel = dc.col[defaultbg].pixel;
2527 attrs.border_pixel = dc.col[defaultbg].pixel;
2528 attrs.bit_gravity = NorthWestGravity;
2529 attrs.event_mask = FocusChangeMask | KeyPressMask
2530 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2531 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2532 attrs.colormap = xw.cmap;
2534 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2535 XRootWindow(xw.dpy, xw.scr);
2536 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2537 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2539 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2543 /* double buffering */
2545 if(XdbeQueryExtension(xw.dpy, &major, &minor)) {
2546 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win,
2551 memset(&gcvalues, 0, sizeof(gcvalues));
2552 gcvalues.graphics_exposures = False;
2553 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2555 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2556 DefaultDepth(xw.dpy, xw.scr));
2557 XSetForeground(xw.dpy, dc.gc, 0);
2558 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2564 /* Xft rendering context */
2565 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2568 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2569 XSetLocaleModifiers("@im=local");
2570 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2571 XSetLocaleModifiers("@im=");
2572 if((xw.xim = XOpenIM(xw.dpy,
2573 NULL, NULL, NULL)) == NULL) {
2574 die("XOpenIM failed. Could not open input"
2579 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2580 | XIMStatusNothing, XNClientWindow, xw.win,
2581 XNFocusWindow, xw.win, NULL);
2583 die("XCreateIC failed. Could not obtain input method.\n");
2585 /* white cursor, black outline */
2586 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2587 XDefineCursor(xw.dpy, xw.win, cursor);
2588 XRecolorCursor(xw.dpy, cursor,
2589 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2590 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2592 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2593 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2594 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2597 XMapWindow(xw.dpy, xw.win);
2603 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2604 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2605 width = charlen * xw.cw, xp, i;
2607 int u8fl, u8fblen, u8cblen, doesexist;
2610 Font *font = &dc.font;
2612 FcPattern *fcpattern, *fontpattern;
2613 FcFontSet *fcsets[] = { NULL };
2614 FcCharSet *fccharset;
2615 Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2616 *temp, revfg, revbg;
2617 XRenderColor colfg, colbg;
2619 frcflags = FRC_NORMAL;
2621 if(base.mode & ATTR_BOLD) {
2622 if(BETWEEN(base.fg, 0, 7)) {
2623 /* basic system colors */
2624 fg = &dc.col[base.fg + 8];
2625 } else if(BETWEEN(base.fg, 16, 195)) {
2627 fg = &dc.col[base.fg + 36];
2628 } else if(BETWEEN(base.fg, 232, 251)) {
2630 fg = &dc.col[base.fg + 4];
2633 * Those ranges will not be brightened:
2634 * 8 - 15 – bright system colors
2635 * 196 - 231 – highest 256 color cube
2636 * 252 - 255 – brightest colors in greyscale
2639 frcflags = FRC_BOLD;
2642 if(base.mode & ATTR_ITALIC) {
2644 frcflags = FRC_ITALIC;
2646 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2648 frcflags = FRC_ITALICBOLD;
2651 if(IS_SET(MODE_REVERSE)) {
2652 if(fg == &dc.col[defaultfg]) {
2653 fg = &dc.col[defaultbg];
2655 colfg.red = ~fg->color.red;
2656 colfg.green = ~fg->color.green;
2657 colfg.blue = ~fg->color.blue;
2658 colfg.alpha = fg->color.alpha;
2659 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2663 if(bg == &dc.col[defaultbg]) {
2664 bg = &dc.col[defaultfg];
2666 colbg.red = ~bg->color.red;
2667 colbg.green = ~bg->color.green;
2668 colbg.blue = ~bg->color.blue;
2669 colbg.alpha = bg->color.alpha;
2670 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2675 if(base.mode & ATTR_REVERSE) {
2681 /* Intelligent cleaning up of the borders. */
2683 xclear(0, (y == 0)? 0 : winy, borderpx,
2684 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2686 if(x + charlen >= term.col) {
2687 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2688 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2691 xclear(winx, 0, winx + width, borderpx);
2693 xclear(winx, winy + xw.ch, winx + width, xw.h);
2695 /* Clean up the region we want to draw to. */
2696 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2698 fcsets[0] = font->set;
2699 for (xp = winx; bytelen > 0;) {
2701 * Search for the range in the to be printed string of glyphs
2702 * that are in the main font. Then print that range. If
2703 * some glyph is found that is not in the font, do the
2711 u8cblen = utf8decode(s, &u8char);
2715 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2716 if (!doesexist || bytelen <= 0) {
2725 XftDrawStringUtf8(xw.draw, fg,
2727 winy + font->ascent,
2730 xp += font->width * u8fl;
2742 /* Search the font cache. */
2743 for (i = 0; i < frclen; i++, frp--) {
2747 if (frc[frp].c == u8char
2748 && frc[frp].flags == frcflags) {
2753 /* Nothing was found. */
2756 * Nothing was found in the cache. Now use
2757 * some dozen of Fontconfig calls to get the
2758 * font for one single character.
2760 fcpattern = FcPatternDuplicate(font->pattern);
2761 fccharset = FcCharSetCreate();
2763 FcCharSetAddChar(fccharset, u8char);
2764 FcPatternAddCharSet(fcpattern, FC_CHARSET,
2766 FcPatternAddBool(fcpattern, FC_SCALABLE,
2769 FcConfigSubstitute(0, fcpattern,
2771 FcDefaultSubstitute(fcpattern);
2773 fontpattern = FcFontSetMatch(0, fcsets,
2774 FcTrue, fcpattern, &fcres);
2777 * Overwrite or create the new cache entry
2782 if (frccur >= LEN(frc))
2784 if (frclen > LEN(frc)) {
2786 XftFontClose(xw.dpy, frc[frccur].font);
2789 frc[frccur].font = XftFontOpenPattern(xw.dpy,
2791 frc[frccur].c = u8char;
2792 frc[frccur].flags = frcflags;
2794 FcPatternDestroy(fcpattern);
2795 FcCharSetDestroy(fccharset);
2800 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2801 xp, winy + frc[frp].font->ascent,
2802 (FcChar8 *)u8c, u8cblen);
2808 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2809 winy + font->ascent, (FcChar8 *)s, bytelen);
2812 if(base.mode & ATTR_UNDERLINE) {
2813 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2820 static int oldx = 0, oldy = 0;
2822 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2824 LIMIT(oldx, 0, term.col-1);
2825 LIMIT(oldy, 0, term.row-1);
2827 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2828 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2830 /* remove the old cursor */
2831 if(term.line[oldy][oldx].state & GLYPH_SET) {
2832 sl = utf8size(term.line[oldy][oldx].c);
2833 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2836 xtermclear(oldx, oldy, oldx, oldy);
2839 /* draw the new one */
2840 if(!(IS_SET(MODE_HIDE))) {
2841 if(!(xw.state & WIN_FOCUSED))
2844 if(IS_SET(MODE_REVERSE))
2845 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2848 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2849 oldx = term.c.x, oldy = term.c.y;
2855 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2859 redraw(int timeout) {
2860 struct timespec tv = {0, timeout * 1000};
2866 nanosleep(&tv, NULL);
2867 XSync(xw.dpy, False); /* necessary for a good tput flash */
2873 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2875 drawregion(0, 0, term.col, term.row);
2877 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2879 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
2881 XSetForeground(xw.dpy, dc.gc, 0);
2886 drawregion(int x1, int y1, int x2, int y2) {
2887 int ic, ib, x, y, ox, sl;
2889 char buf[DRAW_BUF_SIZ];
2890 bool ena_sel = sel.bx != -1;
2892 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
2895 if(!(xw.state & WIN_VISIBLE))
2898 for(y = y1; y < y2; y++) {
2902 xtermclear(0, y, term.col, y);
2904 base = term.line[y][0];
2906 for(x = x1; x < x2; x++) {
2907 new = term.line[y][x];
2908 if(ena_sel && *(new.c) && selected(x, y))
2909 new.mode ^= ATTR_REVERSE;
2910 if(ib > 0 && (!(new.state & GLYPH_SET)
2911 || ATTRCMP(base, new)
2912 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2913 xdraws(buf, base, ox, y, ic, ib);
2916 if(new.state & GLYPH_SET) {
2922 sl = utf8size(new.c);
2923 memcpy(buf+ib, new.c, sl);
2929 xdraws(buf, base, ox, y, ic, ib);
2935 expose(XEvent *ev) {
2936 XExposeEvent *e = &ev->xexpose;
2938 if(xw.state & WIN_REDRAW) {
2940 xw.state &= ~WIN_REDRAW;
2946 visibility(XEvent *ev) {
2947 XVisibilityEvent *e = &ev->xvisibility;
2949 if(e->state == VisibilityFullyObscured) {
2950 xw.state &= ~WIN_VISIBLE;
2951 } else if(!(xw.state & WIN_VISIBLE)) {
2952 /* need a full redraw for next Expose, not just a buf copy */
2953 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2959 xw.state &= ~WIN_VISIBLE;
2963 xseturgency(int add) {
2964 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2966 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2967 XSetWMHints(xw.dpy, xw.win, h);
2973 if(ev->type == FocusIn) {
2974 XSetICFocus(xw.xic);
2975 xw.state |= WIN_FOCUSED;
2978 XUnsetICFocus(xw.xic);
2979 xw.state &= ~WIN_FOCUSED;
2984 match(uint mask, uint state) {
2985 if(mask == XK_NO_MOD && state)
2987 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
2989 if((state & mask) != state)
2995 numlock(const Arg *dummy) {
3000 kmap(KeySym k, uint state) {
3005 /* Check for mapped keys out of X11 function keys. */
3006 for(i = 0; i < LEN(mappedkeys); i++) {
3007 if(mappedkeys[i] == k)
3010 if(i == LEN(mappedkeys)) {
3011 if((k & 0xFFFF) < 0xFD00)
3015 for(kp = key; kp < key + LEN(key); kp++) {
3021 if(!match(mask, state))
3024 if(kp->appkey > 0) {
3025 if(!IS_SET(MODE_APPKEYPAD))
3027 if(term.numlock && kp->appkey == 2)
3029 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3033 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3035 && !IS_SET(MODE_APPCURSOR))) {
3039 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3040 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3051 kpress(XEvent *ev) {
3052 XKeyEvent *e = &ev->xkey;
3054 char xstr[31], buf[32], *customkey, *cp = buf;
3059 if (IS_SET(MODE_KBDLOCK))
3062 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3063 e->state &= ~Mod2Mask;
3065 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3066 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3067 bp->func(&(bp->arg));
3072 /* 2. custom keys from config.h */
3073 if((customkey = kmap(ksym, e->state))) {
3074 len = strlen(customkey);
3075 memcpy(buf, customkey, len);
3076 /* 2. hardcoded (overrides X lookup) */
3081 if (len == 1 && e->state & Mod1Mask)
3084 memcpy(cp, xstr, len);
3085 len = cp - buf + len;
3089 if(IS_SET(MODE_ECHO))
3095 cmessage(XEvent *e) {
3097 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
3098 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3099 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3100 xw.state |= WIN_FOCUSED;
3102 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3103 xw.state &= ~WIN_FOCUSED;
3105 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3106 /* Send SIGHUP to shell */
3113 cresize(int width, int height)
3122 col = (xw.w - 2 * borderpx) / xw.cw;
3123 row = (xw.h - 2 * borderpx) / xw.ch;
3132 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3135 cresize(e->xconfigure.width, e->xconfigure.height);
3142 int xfd = XConnectionNumber(xw.dpy), i;
3143 struct timeval drawtimeout, *tv = NULL;
3147 FD_SET(cmdfd, &rfd);
3149 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3152 die("select failed: %s\n", SERRNO);
3156 * Stop after a certain number of reads so the user does not
3157 * feel like the system is stuttering.
3159 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
3163 * Just wait a bit so it isn't disturbing the
3164 * user and the system is able to write something.
3166 drawtimeout.tv_sec = 0;
3167 drawtimeout.tv_usec = 5;
3174 while(XPending(xw.dpy)) {
3175 XNextEvent(xw.dpy, &ev);
3176 if(XFilterEvent(&ev, None))
3178 fprintf(stderr, "ev.type = %d\n", ev.type);
3179 if(handler[ev.type])
3180 (handler[ev.type])(&ev);
3189 main(int argc, char *argv[]) {
3190 int i, bitm, xr, yr;
3193 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3196 for(i = 1; i < argc; i++) {
3197 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
3200 opt_class = argv[i];
3203 /* eat all remaining arguments */
3215 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
3220 if(bitm & WidthValue)
3222 if(bitm & HeightValue)
3224 if(bitm & XNegative && xw.fx == 0)
3226 if(bitm & XNegative && xw.fy == 0)
3229 if(xw.fh != 0 && xw.fw != 0)
3238 opt_title = argv[i];
3245 opt_embed = argv[i];
3251 setlocale(LC_CTYPE, "");
3252 XSetLocaleModifiers("");