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
64 #define XK_SWITCH_MOD (1<<13)
66 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
69 #define SERRNO strerror(errno)
70 #define MIN(a, b) ((a) < (b) ? (a) : (b))
71 #define MAX(a, b) ((a) < (b) ? (b) : (a))
72 #define LEN(a) (sizeof(a) / sizeof(a[0]))
73 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
74 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
75 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
76 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
77 #define IS_SET(flag) ((term.mode & (flag)) != 0)
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
80 #define VT102ID "\033[?6c"
82 enum glyph_attribute {
92 enum cursor_movement {
115 MODE_MOUSEMOTION = 64,
121 MODE_APPCURSOR = 2048,
122 MODE_MOUSESGR = 4096,
128 ESC_STR = 4, /* DSC, OSC, PM, APC */
130 ESC_STR_END = 16, /* a final string was encountered */
131 ESC_TEST = 32, /* Enter in test mode */
140 enum selection_type {
147 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
149 typedef unsigned char uchar;
150 typedef unsigned int uint;
151 typedef unsigned long ulong;
152 typedef unsigned short ushort;
155 char c[UTF_SIZ]; /* character code */
156 uchar mode; /* attribute flags */
157 ushort fg; /* foreground */
158 ushort bg; /* background */
159 uchar state; /* state flags */
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... */
251 struct timeval tclick1;
252 struct timeval tclick2;
265 void (*func)(const Arg *);
269 /* function definitions used in config.h */
270 static void xzoom(const Arg *);
271 static void selpaste(const Arg *);
272 static void numlock(const Arg *);
274 /* Config.h for applying patches and the configuration. */
290 /* Drawing Context */
292 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
293 Font font, bfont, ifont, ibfont;
297 static void die(const char *, ...);
298 static void draw(void);
299 static void redraw(int);
300 static void drawregion(int, int, int, int);
301 static void execsh(void);
302 static void sigchld(int);
303 static void run(void);
305 static void csidump(void);
306 static void csihandle(void);
307 static void csiparse(void);
308 static void csireset(void);
309 static void strdump(void);
310 static void strhandle(void);
311 static void strparse(void);
312 static void strreset(void);
314 static void tclearregion(int, int, int, int, int);
315 static void tcursor(int);
316 static void tdeletechar(int);
317 static void tdeleteline(int);
318 static void tinsertblank(int);
319 static void tinsertblankline(int);
320 static void tmoveto(int, int);
321 static void tmoveato(int x, int y);
322 static void tnew(int, int);
323 static void tnewline(int);
324 static void tputtab(bool);
325 static void tputc(char *, int);
326 static void treset(void);
327 static int tresize(int, int);
328 static void tscrollup(int, int);
329 static void tscrolldown(int, int);
330 static void tsetattr(int*, int);
331 static void tsetchar(char *, Glyph *, int, int);
332 static void tsetscroll(int, int);
333 static void tswapscreen(void);
334 static void tsetdirt(int, int);
335 static void tsetmode(bool, bool, int *, int);
336 static void tfulldirt(void);
337 static void techo(char *, int);
339 static inline bool match(uint, uint);
340 static void ttynew(void);
341 static void ttyread(void);
342 static void ttyresize(void);
343 static void ttywrite(const char *, size_t);
345 static void xdraws(char *, Glyph, int, int, int, int);
346 static void xhints(void);
347 static void xclear(int, int, int, int);
348 static void xdrawcursor(void);
349 static void xinit(void);
350 static void xloadcols(void);
351 static int xsetcolorname(int, const char *);
352 static int xloadfont(Font *, FcPattern *);
353 static void xloadfonts(char *, int);
354 static void xresettitle(void);
355 static void xseturgency(int);
356 static void xsetsel(char*);
357 static void xtermclear(int, int, int, int);
358 static void xunloadfonts(void);
359 static void xresize(int, int);
361 static void expose(XEvent *);
362 static void visibility(XEvent *);
363 static void unmap(XEvent *);
364 static char *kmap(KeySym, uint);
365 static void kpress(XEvent *);
366 static void cmessage(XEvent *);
367 static void cresize(int, int);
368 static void resize(XEvent *);
369 static void focus(XEvent *);
370 static void brelease(XEvent *);
371 static void bpress(XEvent *);
372 static void bmotion(XEvent *);
373 static void selnotify(XEvent *);
374 static void selclear(XEvent *);
375 static void selrequest(XEvent *);
377 static void selinit(void);
378 static inline bool selected(int, int);
379 static void selcopy(void);
380 static void selscroll(int, int);
382 static int utf8decode(char *, long *);
383 static int utf8encode(long *, char *);
384 static int utf8size(char *);
385 static int isfullutf8(char *, int);
387 static ssize_t xwrite(int, char *, size_t);
388 static void *xmalloc(size_t);
389 static void *xrealloc(void *, size_t);
390 static void *xcalloc(size_t, size_t);
392 static void (*handler[LASTEvent])(XEvent *) = {
394 [ClientMessage] = cmessage,
395 [ConfigureNotify] = resize,
396 [VisibilityNotify] = visibility,
397 [UnmapNotify] = unmap,
401 [MotionNotify] = bmotion,
402 [ButtonPress] = bpress,
403 [ButtonRelease] = brelease,
404 [SelectionClear] = selclear,
405 [SelectionNotify] = selnotify,
406 [SelectionRequest] = selrequest,
413 static CSIEscape csiescseq;
414 static STREscape strescseq;
417 static Selection sel;
418 static int iofd = -1;
419 static char **opt_cmd = NULL;
420 static char *opt_io = NULL;
421 static char *opt_title = NULL;
422 static char *opt_embed = NULL;
423 static char *opt_class = NULL;
424 static char *opt_font = NULL;
428 static char *usedfont = NULL;
429 static int usedfontsize = 0;
431 /* Font Ring Cache */
446 * Fontcache is a ring buffer, with frccur as current position and frclen as
447 * the current length of used elements.
450 static Fontcache frc[1024];
451 static int frccur = -1, frclen = 0;
454 xwrite(int fd, char *s, size_t len) {
458 ssize_t r = write(fd, s, len);
468 xmalloc(size_t len) {
469 void *p = malloc(len);
472 die("Out of memory\n");
478 xrealloc(void *p, size_t len) {
479 if((p = realloc(p, len)) == NULL)
480 die("Out of memory\n");
486 xcalloc(size_t nmemb, size_t size) {
487 void *p = calloc(nmemb, size);
490 die("Out of memory\n");
496 utf8decode(char *s, long *u) {
502 if(~c & B7) { /* 0xxxxxxx */
505 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
506 *u = c&(B4|B3|B2|B1|B0);
508 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
509 *u = c&(B3|B2|B1|B0);
511 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
518 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
520 if((c & (B7|B6)) != B7) /* 10xxxxxx */
523 *u |= c & (B5|B4|B3|B2|B1|B0);
526 if((n == 1 && *u < 0x80) ||
527 (n == 2 && *u < 0x800) ||
528 (n == 3 && *u < 0x10000) ||
529 (*u >= 0xD800 && *u <= 0xDFFF)) {
541 utf8encode(long *u, char *s) {
549 *sp = uc; /* 0xxxxxxx */
551 } else if(*u < 0x800) {
552 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
554 } else if(uc < 0x10000) {
555 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
557 } else if(uc <= 0x10FFFF) {
558 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
564 for(i=n,++sp; i>0; --i,++sp)
565 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
577 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
578 UTF-8 otherwise return 0 */
580 isfullutf8(char *s, int b) {
588 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
590 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
592 ((b == 2) && (*c2&(B7|B6)) == B7))) {
594 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
596 ((b == 2) && (*c2&(B7|B6)) == B7) ||
597 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
610 } else if((c&(B7|B6|B5)) == (B7|B6)) {
612 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
621 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
622 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
626 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
627 if(sel.xtarget == None)
628 sel.xtarget = XA_STRING;
636 return LIMIT(x, 0, term.col-1);
644 return LIMIT(y, 0, term.row-1);
648 selected(int x, int y) {
651 if(sel.ey == y && sel.by == y) {
652 bx = MIN(sel.bx, sel.ex);
653 ex = MAX(sel.bx, sel.ex);
654 return BETWEEN(x, bx, ex);
657 return ((sel.b.y < y && y < sel.e.y)
658 || (y == sel.e.y && x <= sel.e.x))
659 || (y == sel.b.y && x >= sel.b.x
660 && (x <= sel.e.x || sel.b.y != sel.e.y));
663 return ((sel.b.y < y && y < sel.e.y)
664 || (y == sel.e.y && x <= sel.e.x))
665 || (y == sel.b.y && x >= sel.b.x
666 && (x <= sel.e.x || sel.b.y != sel.e.y));
667 case SEL_RECTANGULAR:
668 return ((sel.b.y <= y && y <= sel.e.y)
669 && (sel.b.x <= x && x <= sel.e.x));
674 getbuttoninfo(XEvent *e) {
676 uint state = e->xbutton.state &~Button1Mask;
678 sel.alt = IS_SET(MODE_ALTSCREEN);
680 sel.ex = x2col(e->xbutton.x);
681 sel.ey = y2row(e->xbutton.y);
683 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
684 sel.b.y = MIN(sel.by, sel.ey);
685 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
686 sel.e.y = MAX(sel.by, sel.ey);
688 sel.type = SEL_REGULAR;
689 for(type = 1; type < LEN(selmasks); ++type) {
690 if(match(selmasks[type], state)) {
698 mousereport(XEvent *e) {
699 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
700 button = e->xbutton.button, state = e->xbutton.state,
703 static int ob, ox, oy;
706 if(e->xbutton.type == MotionNotify) {
707 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
711 } else if(!IS_SET(MODE_MOUSESGR)
712 && (e->xbutton.type == ButtonRelease
713 || button == AnyButton)) {
719 if(e->xbutton.type == ButtonPress) {
725 button += (state & ShiftMask ? 4 : 0)
726 + (state & Mod4Mask ? 8 : 0)
727 + (state & ControlMask ? 16 : 0);
730 if(IS_SET(MODE_MOUSESGR)) {
731 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
733 e->xbutton.type == ButtonRelease ? 'm' : 'M');
734 } else if(x < 223 && y < 223) {
735 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
736 32+button, 32+x+1, 32+y+1);
746 if(IS_SET(MODE_MOUSE)) {
748 } else if(e->xbutton.button == Button1) {
751 tsetdirt(sel.b.y, sel.e.y);
755 sel.type = SEL_REGULAR;
756 sel.ex = sel.bx = x2col(e->xbutton.x);
757 sel.ey = sel.by = y2row(e->xbutton.y);
758 } else if(e->xbutton.button == Button4) {
760 } else if(e->xbutton.button == Button5) {
768 int x, y, bufsize, is_selected = 0, size;
774 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
775 ptr = str = xmalloc(bufsize);
777 /* append every set & selected glyph to the selection */
778 for(y = sel.b.y; y < sel.e.y + 1; y++) {
780 gp = &term.line[y][0];
781 last = gp + term.col;
783 while(--last >= gp && !(last->state & GLYPH_SET))
786 for(x = 0; gp <= last; x++, ++gp) {
787 if(!selected(x, y)) {
793 p = (gp->state & GLYPH_SET) ? gp->c : " ";
795 memcpy(ptr, p, size);
798 /* \n at the end of every selected line except for the last one */
799 if(is_selected && y < sel.e.y)
808 selnotify(XEvent *e) {
809 ulong nitems, ofs, rem;
816 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
817 False, AnyPropertyType, &type, &format,
818 &nitems, &rem, &data)) {
819 fprintf(stderr, "Clipboard allocation failed\n");
822 ttywrite((const char *) data, nitems * format / 8);
824 /* number of 32-bit chunks returned */
825 ofs += nitems * format / 32;
830 selpaste(const Arg *dummy) {
831 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
832 xw.win, CurrentTime);
835 void selclear(XEvent *e) {
839 tsetdirt(sel.b.y, sel.e.y);
843 selrequest(XEvent *e) {
844 XSelectionRequestEvent *xsre;
846 Atom xa_targets, string;
848 xsre = (XSelectionRequestEvent *) e;
849 xev.type = SelectionNotify;
850 xev.requestor = xsre->requestor;
851 xev.selection = xsre->selection;
852 xev.target = xsre->target;
853 xev.time = xsre->time;
857 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
858 if(xsre->target == xa_targets) {
859 /* respond with the supported type */
860 string = sel.xtarget;
861 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
862 XA_ATOM, 32, PropModeReplace,
863 (uchar *) &string, 1);
864 xev.property = xsre->property;
865 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
866 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
867 xsre->target, 8, PropModeReplace,
868 (uchar *) sel.clip, strlen(sel.clip));
869 xev.property = xsre->property;
872 /* all done, send a notification to the listener */
873 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
874 fprintf(stderr, "Error sending SelectionNotify event\n");
879 /* register the selection for both the clipboard and the primary */
885 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
887 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
888 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
892 brelease(XEvent *e) {
895 if(IS_SET(MODE_MOUSE)) {
900 if(e->xbutton.button == Button2) {
902 } else if(e->xbutton.button == Button1) {
905 term.dirty[sel.ey] = 1;
906 if(sel.bx == sel.ex && sel.by == sel.ey) {
908 gettimeofday(&now, NULL);
910 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
911 /* triple click on the line */
912 sel.b.x = sel.bx = 0;
913 sel.e.x = sel.ex = term.col;
914 sel.b.y = sel.e.y = sel.ey;
916 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
917 /* double click to select word */
919 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
920 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
924 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
925 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
929 sel.b.y = sel.e.y = sel.ey;
937 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
938 gettimeofday(&sel.tclick1, NULL);
943 int oldey, oldex, oldsby, oldsey;
945 if(IS_SET(MODE_MOUSE)) {
959 if(oldey != sel.ey || oldex != sel.ex) {
960 tsetdirt(MIN(sel.b.y, oldsby), MAX(sel.e.y, oldsey));
965 die(const char *errstr, ...) {
968 va_start(ap, errstr);
969 vfprintf(stderr, errstr, ap);
977 char *envshell = getenv("SHELL");
978 const struct passwd *pass = getpwuid(getuid());
979 char buf[sizeof(long) * 8 + 1];
986 setenv("LOGNAME", pass->pw_name, 1);
987 setenv("USER", pass->pw_name, 1);
988 setenv("SHELL", pass->pw_shell, 0);
989 setenv("HOME", pass->pw_dir, 0);
992 snprintf(buf, sizeof(buf), "%lu", xw.win);
993 setenv("WINDOWID", buf, 1);
995 signal(SIGCHLD, SIG_DFL);
996 signal(SIGHUP, SIG_DFL);
997 signal(SIGINT, SIG_DFL);
998 signal(SIGQUIT, SIG_DFL);
999 signal(SIGTERM, SIG_DFL);
1000 signal(SIGALRM, SIG_DFL);
1002 DEFAULT(envshell, shell);
1003 setenv("TERM", termname, 1);
1004 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1005 execvp(args[0], args);
1013 if(waitpid(pid, &stat, 0) < 0)
1014 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1016 if(WIFEXITED(stat)) {
1017 exit(WEXITSTATUS(stat));
1026 struct winsize w = {term.row, term.col, 0, 0};
1028 /* seems to work fine on linux, openbsd and freebsd */
1029 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1030 die("openpty failed: %s\n", SERRNO);
1032 switch(pid = fork()) {
1034 die("fork failed\n");
1037 setsid(); /* create a new process group */
1038 dup2(s, STDIN_FILENO);
1039 dup2(s, STDOUT_FILENO);
1040 dup2(s, STDERR_FILENO);
1041 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1042 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1050 signal(SIGCHLD, sigchld);
1052 iofd = (!strcmp(opt_io, "-")) ?
1054 open(opt_io, O_WRONLY | O_CREAT, 0666);
1056 fprintf(stderr, "Error opening %s:%s\n",
1057 opt_io, strerror(errno));
1067 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1069 fprintf(stderr, "\n");
1074 static char buf[BUFSIZ];
1075 static int buflen = 0;
1078 int charsize; /* size of utf8 char in bytes */
1082 /* append read bytes to unprocessed bytes */
1083 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1084 die("Couldn't read from shell: %s\n", SERRNO);
1086 /* process every complete utf8 char */
1089 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1090 charsize = utf8decode(ptr, &utf8c);
1091 utf8encode(&utf8c, s);
1097 /* keep any uncomplete utf8 char for the next call */
1098 memmove(buf, ptr, buflen);
1102 ttywrite(const char *s, size_t n) {
1103 if(write(cmdfd, s, n) == -1)
1104 die("write error on tty: %s\n", SERRNO);
1111 w.ws_row = term.row;
1112 w.ws_col = term.col;
1113 w.ws_xpixel = xw.tw;
1114 w.ws_ypixel = xw.th;
1115 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1116 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1120 tsetdirt(int top, int bot) {
1123 LIMIT(top, 0, term.row-1);
1124 LIMIT(bot, 0, term.row-1);
1126 for(i = top; i <= bot; i++)
1132 tsetdirt(0, term.row-1);
1139 if(mode == CURSOR_SAVE) {
1141 } else if(mode == CURSOR_LOAD) {
1151 term.c = (TCursor){{
1155 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1157 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1158 for(i = tabspaces; i < term.col; i += tabspaces)
1161 term.bot = term.row - 1;
1162 term.mode = MODE_WRAP;
1164 tclearregion(0, 0, term.col-1, term.row-1, 0);
1166 tcursor(CURSOR_SAVE);
1170 tnew(int col, int row) {
1171 /* set screen size */
1174 term.line = xmalloc(term.row * sizeof(Line));
1175 term.alt = xmalloc(term.row * sizeof(Line));
1176 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1177 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1179 for(row = 0; row < term.row; row++) {
1180 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1181 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1182 term.dirty[row] = 0;
1186 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1193 Line *tmp = term.line;
1195 term.line = term.alt;
1197 term.mode ^= MODE_ALTSCREEN;
1202 tscrolldown(int orig, int n) {
1206 LIMIT(n, 0, term.bot-orig+1);
1208 tclearregion(0, term.bot-n+1, term.col-1, term.bot, 0);
1210 for(i = term.bot; i >= orig+n; i--) {
1211 temp = term.line[i];
1212 term.line[i] = term.line[i-n];
1213 term.line[i-n] = temp;
1216 term.dirty[i-n] = 1;
1223 tscrollup(int orig, int n) {
1226 LIMIT(n, 0, term.bot-orig+1);
1228 tclearregion(0, orig, term.col-1, orig+n-1, 0);
1230 for(i = orig; i <= term.bot-n; i++) {
1231 temp = term.line[i];
1232 term.line[i] = term.line[i+n];
1233 term.line[i+n] = temp;
1236 term.dirty[i+n] = 1;
1239 selscroll(orig, -n);
1243 selscroll(int orig, int n) {
1247 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1248 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1254 if(sel.by < term.top) {
1258 if(sel.ey > term.bot) {
1263 case SEL_RECTANGULAR:
1264 if(sel.by < term.top)
1266 if(sel.ey > term.bot)
1270 sel.b.y = sel.by, sel.b.x = sel.bx;
1271 sel.e.y = sel.ey, sel.e.x = sel.ex;
1276 tnewline(int first_col) {
1280 tscrollup(term.top, 1);
1284 tmoveto(first_col ? 0 : term.c.x, y);
1289 /* int noarg = 1; */
1290 char *p = csiescseq.buf;
1294 csiescseq.priv = 1, p++;
1296 while(p < csiescseq.buf+csiescseq.len) {
1297 while(isdigit(*p)) {
1298 csiescseq.arg[csiescseq.narg] *= 10;
1299 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1301 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1302 csiescseq.narg++, p++;
1304 csiescseq.mode = *p;
1312 /* for absolute user moves, when decom is set */
1314 tmoveato(int x, int y) {
1315 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1319 tmoveto(int x, int y) {
1322 if(term.c.state & CURSOR_ORIGIN) {
1327 maxy = term.row - 1;
1329 LIMIT(x, 0, term.col-1);
1330 LIMIT(y, miny, maxy);
1331 term.c.state &= ~CURSOR_WRAPNEXT;
1337 tsetchar(char *c, Glyph *attr, int x, int y) {
1338 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1339 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1340 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1341 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1342 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1343 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1344 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1345 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1346 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1350 * The table is proudly stolen from rxvt.
1352 if(attr->mode & ATTR_GFX) {
1353 if(c[0] >= 0x41 && c[0] <= 0x7e
1354 && vt100_0[c[0] - 0x41]) {
1355 c = vt100_0[c[0] - 0x41];
1360 term.line[y][x] = *attr;
1361 memcpy(term.line[y][x].c, c, UTF_SIZ);
1362 term.line[y][x].state |= GLYPH_SET;
1366 tclearregion(int x1, int y1, int x2, int y2, int bce) {
1370 temp = x1, x1 = x2, x2 = temp;
1372 temp = y1, y1 = y2, y2 = temp;
1374 LIMIT(x1, 0, term.col-1);
1375 LIMIT(x2, 0, term.col-1);
1376 LIMIT(y1, 0, term.row-1);
1377 LIMIT(y2, 0, term.row-1);
1379 for(y = y1; y <= y2; y++) {
1381 for(x = x1; x <= x2; x++) {
1383 term.line[y][x] = term.c.attr;
1384 memcpy(term.line[y][x].c, " ", 2);
1385 term.line[y][x].state |= GLYPH_SET;
1387 term.line[y][x].state = 0;
1394 tdeletechar(int n) {
1395 int src = term.c.x + n;
1397 int size = term.col - src;
1399 term.dirty[term.c.y] = 1;
1401 if(src >= term.col) {
1402 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1406 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1407 size * sizeof(Glyph));
1408 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y, 0);
1412 tinsertblank(int n) {
1415 int size = term.col - dst;
1417 term.dirty[term.c.y] = 1;
1419 if(dst >= term.col) {
1420 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1424 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1425 size * sizeof(Glyph));
1426 tclearregion(src, term.c.y, dst - 1, term.c.y, 0);
1430 tinsertblankline(int n) {
1431 if(term.c.y < term.top || term.c.y > term.bot)
1434 tscrolldown(term.c.y, n);
1438 tdeleteline(int n) {
1439 if(term.c.y < term.top || term.c.y > term.bot)
1442 tscrollup(term.c.y, n);
1446 tsetattr(int *attr, int l) {
1449 for(i = 0; i < l; i++) {
1452 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1453 | ATTR_ITALIC | ATTR_BLINK);
1454 term.c.attr.fg = defaultfg;
1455 term.c.attr.bg = defaultbg;
1458 term.c.attr.mode |= ATTR_BOLD;
1461 term.c.attr.mode |= ATTR_ITALIC;
1464 term.c.attr.mode |= ATTR_UNDERLINE;
1466 case 5: /* slow blink */
1467 case 6: /* rapid blink */
1468 term.c.attr.mode |= ATTR_BLINK;
1471 term.c.attr.mode |= ATTR_REVERSE;
1475 term.c.attr.mode &= ~ATTR_BOLD;
1478 term.c.attr.mode &= ~ATTR_ITALIC;
1481 term.c.attr.mode &= ~ATTR_UNDERLINE;
1485 term.c.attr.mode &= ~ATTR_BLINK;
1488 term.c.attr.mode &= ~ATTR_REVERSE;
1491 if(i + 2 < l && attr[i + 1] == 5) {
1493 if(BETWEEN(attr[i], 0, 255)) {
1494 term.c.attr.fg = attr[i];
1497 "erresc: bad fgcolor %d\n",
1502 "erresc(38): gfx attr %d unknown\n",
1507 term.c.attr.fg = defaultfg;
1510 if(i + 2 < l && attr[i + 1] == 5) {
1512 if(BETWEEN(attr[i], 0, 255)) {
1513 term.c.attr.bg = attr[i];
1516 "erresc: bad bgcolor %d\n",
1521 "erresc(48): gfx attr %d unknown\n",
1526 term.c.attr.bg = defaultbg;
1529 if(BETWEEN(attr[i], 30, 37)) {
1530 term.c.attr.fg = attr[i] - 30;
1531 } else if(BETWEEN(attr[i], 40, 47)) {
1532 term.c.attr.bg = attr[i] - 40;
1533 } else if(BETWEEN(attr[i], 90, 97)) {
1534 term.c.attr.fg = attr[i] - 90 + 8;
1535 } else if(BETWEEN(attr[i], 100, 107)) {
1536 term.c.attr.bg = attr[i] - 100 + 8;
1539 "erresc(default): gfx attr %d unknown\n",
1540 attr[i]), csidump();
1548 tsetscroll(int t, int b) {
1551 LIMIT(t, 0, term.row-1);
1552 LIMIT(b, 0, term.row-1);
1562 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1565 tsetmode(bool priv, bool set, int *args, int narg) {
1569 for(lim = args + narg; args < lim; ++args) {
1573 case 1: /* DECCKM -- Cursor key */
1574 MODBIT(term.mode, set, MODE_APPCURSOR);
1576 case 5: /* DECSCNM -- Reverse video */
1578 MODBIT(term.mode, set, MODE_REVERSE);
1579 if(mode != term.mode)
1580 redraw(REDRAW_TIMEOUT);
1582 case 6: /* DECOM -- Origin */
1583 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1586 case 7: /* DECAWM -- Auto wrap */
1587 MODBIT(term.mode, set, MODE_WRAP);
1589 case 0: /* Error (IGNORED) */
1590 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1591 case 3: /* DECCOLM -- Column (IGNORED) */
1592 case 4: /* DECSCLM -- Scroll (IGNORED) */
1593 case 8: /* DECARM -- Auto repeat (IGNORED) */
1594 case 18: /* DECPFF -- Printer feed (IGNORED) */
1595 case 19: /* DECPEX -- Printer extent (IGNORED) */
1596 case 42: /* DECNRCM -- National characters (IGNORED) */
1597 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1599 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1600 MODBIT(term.mode, !set, MODE_HIDE);
1602 case 1000: /* 1000,1002: enable xterm mouse report */
1603 MODBIT(term.mode, set, MODE_MOUSEBTN);
1604 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1607 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1608 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1611 MODBIT(term.mode, set, MODE_MOUSESGR);
1613 case 1049: /* = 1047 and 1048 */
1616 alt = IS_SET(MODE_ALTSCREEN);
1618 tclearregion(0, 0, term.col-1,
1621 if(set ^ alt) /* set is always 1 or 0 */
1628 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1632 "erresc: unknown private set/reset mode %d\n",
1638 case 0: /* Error (IGNORED) */
1640 case 2: /* KAM -- keyboard action */
1641 MODBIT(term.mode, set, MODE_KBDLOCK);
1643 case 4: /* IRM -- Insertion-replacement */
1644 MODBIT(term.mode, set, MODE_INSERT);
1646 case 12: /* SRM -- Send/Receive */
1647 MODBIT(term.mode, !set, MODE_ECHO);
1649 case 20: /* LNM -- Linefeed/new line */
1650 MODBIT(term.mode, set, MODE_CRLF);
1654 "erresc: unknown set/reset mode %d\n",
1666 switch(csiescseq.mode) {
1669 fprintf(stderr, "erresc: unknown csi ");
1673 case '@': /* ICH -- Insert <n> blank char */
1674 DEFAULT(csiescseq.arg[0], 1);
1675 tinsertblank(csiescseq.arg[0]);
1677 case 'A': /* CUU -- Cursor <n> Up */
1678 DEFAULT(csiescseq.arg[0], 1);
1679 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1681 case 'B': /* CUD -- Cursor <n> Down */
1682 case 'e': /* VPR --Cursor <n> Down */
1683 DEFAULT(csiescseq.arg[0], 1);
1684 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1686 case 'c': /* DA -- Device Attributes */
1687 if(csiescseq.arg[0] == 0)
1688 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1690 case 'C': /* CUF -- Cursor <n> Forward */
1691 case 'a': /* HPR -- Cursor <n> Forward */
1692 DEFAULT(csiescseq.arg[0], 1);
1693 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1695 case 'D': /* CUB -- Cursor <n> Backward */
1696 DEFAULT(csiescseq.arg[0], 1);
1697 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1699 case 'E': /* CNL -- Cursor <n> Down and first col */
1700 DEFAULT(csiescseq.arg[0], 1);
1701 tmoveto(0, term.c.y+csiescseq.arg[0]);
1703 case 'F': /* CPL -- Cursor <n> Up and first col */
1704 DEFAULT(csiescseq.arg[0], 1);
1705 tmoveto(0, term.c.y-csiescseq.arg[0]);
1707 case 'g': /* TBC -- Tabulation clear */
1708 switch(csiescseq.arg[0]) {
1709 case 0: /* clear current tab stop */
1710 term.tabs[term.c.x] = 0;
1712 case 3: /* clear all the tabs */
1713 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1719 case 'G': /* CHA -- Move to <col> */
1721 DEFAULT(csiescseq.arg[0], 1);
1722 tmoveto(csiescseq.arg[0]-1, term.c.y);
1724 case 'H': /* CUP -- Move to <row> <col> */
1726 DEFAULT(csiescseq.arg[0], 1);
1727 DEFAULT(csiescseq.arg[1], 1);
1728 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1730 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1731 DEFAULT(csiescseq.arg[0], 1);
1732 while(csiescseq.arg[0]--)
1735 case 'J': /* ED -- Clear screen */
1737 switch(csiescseq.arg[0]) {
1739 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
1740 if(term.c.y < term.row-1) {
1741 tclearregion(0, term.c.y+1, term.col-1,
1747 tclearregion(0, 0, term.col-1, term.c.y-1, 1);
1748 tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1751 tclearregion(0, 0, term.col-1, term.row-1, 1);
1757 case 'K': /* EL -- Clear line */
1758 switch(csiescseq.arg[0]) {
1760 tclearregion(term.c.x, term.c.y, term.col-1,
1764 tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1767 tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
1771 case 'S': /* SU -- Scroll <n> line up */
1772 DEFAULT(csiescseq.arg[0], 1);
1773 tscrollup(term.top, csiescseq.arg[0]);
1775 case 'T': /* SD -- Scroll <n> line down */
1776 DEFAULT(csiescseq.arg[0], 1);
1777 tscrolldown(term.top, csiescseq.arg[0]);
1779 case 'L': /* IL -- Insert <n> blank lines */
1780 DEFAULT(csiescseq.arg[0], 1);
1781 tinsertblankline(csiescseq.arg[0]);
1783 case 'l': /* RM -- Reset Mode */
1784 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1786 case 'M': /* DL -- Delete <n> lines */
1787 DEFAULT(csiescseq.arg[0], 1);
1788 tdeleteline(csiescseq.arg[0]);
1790 case 'X': /* ECH -- Erase <n> char */
1791 DEFAULT(csiescseq.arg[0], 1);
1792 tclearregion(term.c.x, term.c.y,
1793 term.c.x + csiescseq.arg[0] - 1, term.c.y, 1);
1795 case 'P': /* DCH -- Delete <n> char */
1796 DEFAULT(csiescseq.arg[0], 1);
1797 tdeletechar(csiescseq.arg[0]);
1799 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1800 DEFAULT(csiescseq.arg[0], 1);
1801 while(csiescseq.arg[0]--)
1804 case 'd': /* VPA -- Move to <row> */
1805 DEFAULT(csiescseq.arg[0], 1);
1806 tmoveato(term.c.x, csiescseq.arg[0]-1);
1808 case 'h': /* SM -- Set terminal mode */
1809 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1811 case 'm': /* SGR -- Terminal attribute (color) */
1812 tsetattr(csiescseq.arg, csiescseq.narg);
1814 case 'r': /* DECSTBM -- Set Scrolling Region */
1815 if(csiescseq.priv) {
1818 DEFAULT(csiescseq.arg[0], 1);
1819 DEFAULT(csiescseq.arg[1], term.row);
1820 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1824 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1825 tcursor(CURSOR_SAVE);
1827 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1828 tcursor(CURSOR_LOAD);
1839 for(i = 0; i < csiescseq.len; i++) {
1840 c = csiescseq.buf[i] & 0xff;
1843 } else if(c == '\n') {
1845 } else if(c == '\r') {
1847 } else if(c == 0x1b) {
1850 printf("(%02x)", c);
1858 memset(&csiescseq, 0, sizeof(csiescseq));
1868 * TODO: make this being useful in case of color palette change.
1871 narg = strescseq.narg;
1873 switch(strescseq.type) {
1874 case ']': /* OSC -- Operating System Command */
1875 switch(i = atoi(strescseq.args[0])) {
1880 * TODO: Handle special chars in string, like umlauts.
1883 XStoreName(xw.dpy, xw.win, strescseq.args[2]);
1885 case 4: /* color set */
1888 p = strescseq.args[2];
1890 case 104: /* color reset, here p = NULL */
1891 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
1892 if (!xsetcolorname(j, p)) {
1893 fprintf(stderr, "erresc: invalid color %s\n", p);
1895 redraw(0); /* TODO if defaultbg color is changed, borders are dirty */
1899 fprintf(stderr, "erresc: unknown str ");
1904 case 'k': /* old title set compatibility */
1905 XStoreName(xw.dpy, xw.win, strescseq.buf);
1907 case 'P': /* DSC -- Device Control String */
1908 case '_': /* APC -- Application Program Command */
1909 case '^': /* PM -- Privacy Message */
1911 fprintf(stderr, "erresc: unknown str ");
1921 * TODO: Implement parsing like for CSI when required.
1922 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1925 char *start = strescseq.buf, *end = start + strescseq.len;
1926 strescseq.args[0] = start;
1927 while(start < end && narg < LEN(strescseq.args)) {
1928 start = memchr(start, ';', end - start);
1933 strescseq.args[++narg] = start;
1936 strescseq.narg = narg + 1;
1944 printf("ESC%c", strescseq.type);
1945 for(i = 0; i < strescseq.len; i++) {
1946 c = strescseq.buf[i] & 0xff;
1949 } else if(c == '\n') {
1951 } else if(c == '\r') {
1953 } else if(c == 0x1b) {
1956 printf("(%02x)", c);
1964 memset(&strescseq, 0, sizeof(strescseq));
1968 tputtab(bool forward) {
1974 for(++x; x < term.col && !term.tabs[x]; ++x)
1979 for(--x; x > 0 && !term.tabs[x]; --x)
1982 tmoveto(x, term.c.y);
1986 techo(char *buf, int len) {
1987 for(; len > 0; buf++, len--) {
1990 if(c == '\033') { /* escape */
1993 } else if(c < '\x20') { /* control code */
1994 if(c != '\n' && c != '\r' && c != '\t') {
2008 tputc(char *c, int len) {
2010 bool control = ascii < '\x20' || ascii == 0177;
2013 if(xwrite(iofd, c, len) < 0) {
2014 fprintf(stderr, "Error writing in %s:%s\n",
2015 opt_io, strerror(errno));
2022 * STR sequences must be checked before anything else
2023 * because it can use some control codes as part of the sequence.
2025 if(term.esc & ESC_STR) {
2028 term.esc = ESC_START | ESC_STR_END;
2030 case '\a': /* backwards compatibility to xterm */
2035 if(strescseq.len + len < sizeof(strescseq.buf)) {
2036 memmove(&strescseq.buf[strescseq.len], c, len);
2037 strescseq.len += len;
2040 * Here is a bug in terminals. If the user never sends
2041 * some code to stop the str or esc command, then st
2042 * will stop responding. But this is better than
2043 * silently failing with unknown characters. At least
2044 * then users will report back.
2046 * In the case users ever get fixed, here is the code:
2058 * Actions of control codes must be performed as soon they arrive
2059 * because they can be embedded inside a control sequence, and
2060 * they must not cause conflicts with sequences.
2068 tmoveto(term.c.x-1, term.c.y);
2071 tmoveto(0, term.c.y);
2076 /* go to first col if the mode is set */
2077 tnewline(IS_SET(MODE_CRLF));
2079 case '\a': /* BEL */
2080 if(!(xw.state & WIN_FOCUSED))
2083 case '\033': /* ESC */
2085 term.esc = ESC_START;
2087 case '\016': /* SO */
2088 case '\017': /* SI */
2090 * Different charsets are hard to handle. Applications
2091 * should use the right alt charset escapes for the
2092 * only reason they still exist: line drawing. The
2093 * rest is incompatible history st should not support.
2096 case '\032': /* SUB */
2097 case '\030': /* CAN */
2100 case '\005': /* ENQ (IGNORED) */
2101 case '\000': /* NUL (IGNORED) */
2102 case '\021': /* XON (IGNORED) */
2103 case '\023': /* XOFF (IGNORED) */
2104 case 0177: /* DEL (IGNORED) */
2107 } else if(term.esc & ESC_START) {
2108 if(term.esc & ESC_CSI) {
2109 csiescseq.buf[csiescseq.len++] = ascii;
2110 if(BETWEEN(ascii, 0x40, 0x7E)
2111 || csiescseq.len >= ESC_BUF_SIZ) {
2113 csiparse(), csihandle();
2115 } else if(term.esc & ESC_STR_END) {
2119 } else if(term.esc & ESC_ALTCHARSET) {
2121 case '0': /* Line drawing set */
2122 term.c.attr.mode |= ATTR_GFX;
2124 case 'B': /* USASCII */
2125 term.c.attr.mode &= ~ATTR_GFX;
2127 case 'A': /* UK (IGNORED) */
2128 case '<': /* multinational charset (IGNORED) */
2129 case '5': /* Finnish (IGNORED) */
2130 case 'C': /* Finnish (IGNORED) */
2131 case 'K': /* German (IGNORED) */
2134 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2137 } else if(term.esc & ESC_TEST) {
2138 if(ascii == '8') { /* DEC screen alignment test. */
2139 char E[UTF_SIZ] = "E";
2142 for(x = 0; x < term.col; ++x) {
2143 for(y = 0; y < term.row; ++y)
2144 tsetchar(E, &term.c.attr, x, y);
2151 term.esc |= ESC_CSI;
2154 term.esc |= ESC_TEST;
2156 case 'P': /* DCS -- Device Control String */
2157 case '_': /* APC -- Application Program Command */
2158 case '^': /* PM -- Privacy Message */
2159 case ']': /* OSC -- Operating System Command */
2160 case 'k': /* old title set compatibility */
2162 strescseq.type = ascii;
2163 term.esc |= ESC_STR;
2165 case '(': /* set primary charset G0 */
2166 term.esc |= ESC_ALTCHARSET;
2168 case ')': /* set secondary charset G1 (IGNORED) */
2169 case '*': /* set tertiary charset G2 (IGNORED) */
2170 case '+': /* set quaternary charset G3 (IGNORED) */
2173 case 'D': /* IND -- Linefeed */
2174 if(term.c.y == term.bot) {
2175 tscrollup(term.top, 1);
2177 tmoveto(term.c.x, term.c.y+1);
2181 case 'E': /* NEL -- Next line */
2182 tnewline(1); /* always go to first col */
2185 case 'H': /* HTS -- Horizontal tab stop */
2186 term.tabs[term.c.x] = 1;
2189 case 'M': /* RI -- Reverse index */
2190 if(term.c.y == term.top) {
2191 tscrolldown(term.top, 1);
2193 tmoveto(term.c.x, term.c.y-1);
2197 case 'Z': /* DECID -- Identify Terminal */
2198 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2201 case 'c': /* RIS -- Reset to inital state */
2206 case '=': /* DECPAM -- Application keypad */
2207 term.mode |= MODE_APPKEYPAD;
2210 case '>': /* DECPNM -- Normal keypad */
2211 term.mode &= ~MODE_APPKEYPAD;
2214 case '7': /* DECSC -- Save Cursor */
2215 tcursor(CURSOR_SAVE);
2218 case '8': /* DECRC -- Restore Cursor */
2219 tcursor(CURSOR_LOAD);
2222 case '\\': /* ST -- Stop */
2226 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2227 (uchar) ascii, isprint(ascii)? ascii:'.');
2232 * All characters which form part of a sequence are not
2238 * Display control codes only if we are in graphic mode
2240 if(control && !(term.c.attr.mode & ATTR_GFX))
2242 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2244 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2245 tnewline(1); /* always go to first col */
2247 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2248 memmove(&term.line[term.c.y][term.c.x+1],
2249 &term.line[term.c.y][term.c.x],
2250 (term.col - term.c.x - 1) * sizeof(Glyph));
2253 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2254 if(term.c.x+1 < term.col) {
2255 tmoveto(term.c.x+1, term.c.y);
2257 term.c.state |= CURSOR_WRAPNEXT;
2262 tresize(int col, int row) {
2264 int minrow = MIN(row, term.row);
2265 int mincol = MIN(col, term.col);
2266 int slide = term.c.y - row + 1;
2269 if(col < 1 || row < 1)
2272 /* free unneeded rows */
2276 * slide screen to keep cursor where we expect it -
2277 * tscrollup would work here, but we can optimize to
2278 * memmove because we're freeing the earlier lines
2280 for(/* i = 0 */; i < slide; i++) {
2284 memmove(term.line, term.line + slide, row * sizeof(Line));
2285 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2287 for(i += row; i < term.row; i++) {
2292 /* resize to new height */
2293 term.line = xrealloc(term.line, row * sizeof(Line));
2294 term.alt = xrealloc(term.alt, row * sizeof(Line));
2295 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2296 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2298 /* resize each row to new width, zero-pad if needed */
2299 for(i = 0; i < minrow; i++) {
2301 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2302 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2303 for(x = mincol; x < col; x++) {
2304 term.line[i][x].state = 0;
2305 term.alt[i][x].state = 0;
2309 /* allocate any new rows */
2310 for(/* i == minrow */; i < row; i++) {
2312 term.line[i] = xcalloc(col, sizeof(Glyph));
2313 term.alt [i] = xcalloc(col, sizeof(Glyph));
2315 if(col > term.col) {
2316 bp = term.tabs + term.col;
2318 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2319 while(--bp > term.tabs && !*bp)
2321 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2324 /* update terminal size */
2327 /* reset scrolling region */
2328 tsetscroll(0, row-1);
2329 /* make use of the LIMIT in tmoveto */
2330 tmoveto(term.c.x, term.c.y);
2336 xresize(int col, int row) {
2337 xw.tw = MAX(1, col * xw.cw);
2338 xw.th = MAX(1, row * xw.ch);
2341 XFreePixmap(xw.dpy, xw.buf);
2342 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2343 DefaultDepth(xw.dpy, xw.scr));
2344 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
2345 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2348 XftDrawChange(xw.draw, xw.buf);
2351 static inline ushort
2352 sixd_to_16bit(int x) {
2353 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2359 XRenderColor color = { .alpha = 0xffff };
2361 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2362 for(i = 0; i < LEN(colorname); i++) {
2365 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2366 die("Could not allocate color '%s'\n", colorname[i]);
2370 /* load colors [16-255] ; same colors as xterm */
2371 for(i = 16, r = 0; r < 6; r++) {
2372 for(g = 0; g < 6; g++) {
2373 for(b = 0; b < 6; b++) {
2374 color.red = sixd_to_16bit(r);
2375 color.green = sixd_to_16bit(g);
2376 color.blue = sixd_to_16bit(b);
2377 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2378 die("Could not allocate color %d\n", i);
2385 for(r = 0; r < 24; r++, i++) {
2386 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2387 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2389 die("Could not allocate color %d\n", i);
2395 xsetcolorname(int x, const char *name) {
2396 XRenderColor color = { .alpha = 0xffff };
2398 if (x < 0 || x > LEN(colorname))
2401 if(16 <= x && x < 16 + 216) {
2402 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2403 color.red = sixd_to_16bit(r);
2404 color.green = sixd_to_16bit(g);
2405 color.blue = sixd_to_16bit(b);
2406 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2407 return 0; /* something went wrong */
2410 } else if (16 + 216 <= x && x < 256) {
2411 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2412 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2413 return 0; /* something went wrong */
2417 name = colorname[x];
2420 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2427 xtermclear(int col1, int row1, int col2, int row2) {
2428 XftDrawRect(xw.draw,
2429 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2430 borderpx + col1 * xw.cw,
2431 borderpx + row1 * xw.ch,
2432 (col2-col1+1) * xw.cw,
2433 (row2-row1+1) * xw.ch);
2437 * Absolute coordinates.
2440 xclear(int x1, int y1, int x2, int y2) {
2441 XftDrawRect(xw.draw,
2442 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2443 x1, y1, x2-x1, y2-y1);
2448 XClassHint class = {opt_class ? opt_class : termname, termname};
2449 XWMHints wm = {.flags = InputHint, .input = 1};
2450 XSizeHints *sizeh = NULL;
2452 sizeh = XAllocSizeHints();
2453 if(xw.isfixed == False) {
2454 sizeh->flags = PSize | PResizeInc | PBaseSize;
2455 sizeh->height = xw.h;
2456 sizeh->width = xw.w;
2457 sizeh->height_inc = xw.ch;
2458 sizeh->width_inc = xw.cw;
2459 sizeh->base_height = 2 * borderpx;
2460 sizeh->base_width = 2 * borderpx;
2462 sizeh->flags = PMaxSize | PMinSize;
2463 sizeh->min_width = sizeh->max_width = xw.fw;
2464 sizeh->min_height = sizeh->max_height = xw.fh;
2467 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2472 xloadfont(Font *f, FcPattern *pattern) {
2476 match = FcFontMatch(NULL, pattern, &result);
2480 if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2481 FcPatternDestroy(match);
2485 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2486 FcPatternDestroy(match);
2490 f->pattern = FcPatternDuplicate(pattern);
2492 f->ascent = f->match->ascent;
2493 f->descent = f->match->descent;
2495 f->rbearing = f->match->max_advance_width;
2497 f->height = f->match->height;
2498 f->width = f->lbearing + f->rbearing;
2504 xloadfonts(char *fontstr, int fontsize) {
2509 if(fontstr[0] == '-') {
2510 pattern = XftXlfdParse(fontstr, False, False);
2512 pattern = FcNameParse((FcChar8 *)fontstr);
2516 die("st: can't open font %s\n", fontstr);
2519 FcPatternDel(pattern, FC_PIXEL_SIZE);
2520 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2521 usedfontsize = fontsize;
2523 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2524 if(result == FcResultMatch) {
2525 usedfontsize = (int)fontval;
2528 * Default font size is 12, if none given. This is to
2529 * have a known usedfontsize value.
2531 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2536 FcConfigSubstitute(0, pattern, FcMatchPattern);
2537 FcDefaultSubstitute(pattern);
2539 if(xloadfont(&dc.font, pattern))
2540 die("st: can't open font %s\n", fontstr);
2542 /* Setting character width and height. */
2543 xw.cw = dc.font.width;
2544 xw.ch = dc.font.height;
2546 FcPatternDel(pattern, FC_SLANT);
2547 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2548 if(xloadfont(&dc.ifont, pattern))
2549 die("st: can't open font %s\n", fontstr);
2551 FcPatternDel(pattern, FC_WEIGHT);
2552 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2553 if(xloadfont(&dc.ibfont, pattern))
2554 die("st: can't open font %s\n", fontstr);
2556 FcPatternDel(pattern, FC_SLANT);
2557 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2558 if(xloadfont(&dc.bfont, pattern))
2559 die("st: can't open font %s\n", fontstr);
2561 FcPatternDestroy(pattern);
2565 xunloadfonts(void) {
2569 * Free the loaded fonts in the font cache. This is done backwards
2572 for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2575 XftFontClose(xw.dpy, frc[ip].font);
2580 XftFontClose(xw.dpy, dc.font.match);
2581 FcPatternDestroy(dc.font.pattern);
2582 FcFontSetDestroy(dc.font.set);
2583 XftFontClose(xw.dpy, dc.bfont.match);
2584 FcPatternDestroy(dc.bfont.pattern);
2585 FcFontSetDestroy(dc.bfont.set);
2586 XftFontClose(xw.dpy, dc.ifont.match);
2587 FcPatternDestroy(dc.ifont.pattern);
2588 FcFontSetDestroy(dc.ifont.set);
2589 XftFontClose(xw.dpy, dc.ibfont.match);
2590 FcPatternDestroy(dc.ibfont.pattern);
2591 FcFontSetDestroy(dc.ibfont.set);
2595 xzoom(const Arg *arg) {
2597 xloadfonts(usedfont, usedfontsize + arg->i);
2604 XSetWindowAttributes attrs;
2608 int sw, sh, major, minor;
2610 if(!(xw.dpy = XOpenDisplay(NULL)))
2611 die("Can't open display\n");
2612 xw.scr = XDefaultScreen(xw.dpy);
2613 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2617 die("Could not init fontconfig.\n");
2619 usedfont = (opt_font == NULL)? font : opt_font;
2620 xloadfonts(usedfont, 0);
2623 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2626 /* adjust fixed window geometry */
2628 sw = DisplayWidth(xw.dpy, xw.scr);
2629 sh = DisplayHeight(xw.dpy, xw.scr);
2631 xw.fx = sw + xw.fx - xw.fw - 1;
2633 xw.fy = sh + xw.fy - xw.fh - 1;
2638 /* window - default size */
2639 xw.h = 2 * borderpx + term.row * xw.ch;
2640 xw.w = 2 * borderpx + term.col * xw.cw;
2646 attrs.background_pixel = dc.col[defaultbg].pixel;
2647 attrs.border_pixel = dc.col[defaultbg].pixel;
2648 attrs.bit_gravity = NorthWestGravity;
2649 attrs.event_mask = FocusChangeMask | KeyPressMask
2650 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2651 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2652 attrs.colormap = xw.cmap;
2654 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2655 XRootWindow(xw.dpy, xw.scr);
2656 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2657 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2659 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2663 /* double buffering */
2665 if(XdbeQueryExtension(xw.dpy, &major, &minor)) {
2666 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win,
2671 memset(&gcvalues, 0, sizeof(gcvalues));
2672 gcvalues.graphics_exposures = False;
2673 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2675 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2676 DefaultDepth(xw.dpy, xw.scr));
2677 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2678 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2684 /* Xft rendering context */
2685 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2688 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2689 XSetLocaleModifiers("@im=local");
2690 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2691 XSetLocaleModifiers("@im=");
2692 if((xw.xim = XOpenIM(xw.dpy,
2693 NULL, NULL, NULL)) == NULL) {
2694 die("XOpenIM failed. Could not open input"
2699 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2700 | XIMStatusNothing, XNClientWindow, xw.win,
2701 XNFocusWindow, xw.win, NULL);
2703 die("XCreateIC failed. Could not obtain input method.\n");
2705 /* white cursor, black outline */
2706 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2707 XDefineCursor(xw.dpy, xw.win, cursor);
2708 XRecolorCursor(xw.dpy, cursor,
2709 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2710 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2712 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2713 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2714 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2717 XMapWindow(xw.dpy, xw.win);
2723 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2724 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2725 width = charlen * xw.cw, xp, i;
2727 int u8fl, u8fblen, u8cblen, doesexist;
2730 Font *font = &dc.font;
2732 FcPattern *fcpattern, *fontpattern;
2733 FcFontSet *fcsets[] = { NULL };
2734 FcCharSet *fccharset;
2735 Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2736 *temp, revfg, revbg;
2737 XRenderColor colfg, colbg;
2739 frcflags = FRC_NORMAL;
2741 if(base.mode & ATTR_BOLD) {
2742 if(BETWEEN(base.fg, 0, 7)) {
2743 /* basic system colors */
2744 fg = &dc.col[base.fg + 8];
2745 } else if(BETWEEN(base.fg, 16, 195)) {
2747 fg = &dc.col[base.fg + 36];
2748 } else if(BETWEEN(base.fg, 232, 251)) {
2750 fg = &dc.col[base.fg + 4];
2753 * Those ranges will not be brightened:
2754 * 8 - 15 – bright system colors
2755 * 196 - 231 – highest 256 color cube
2756 * 252 - 255 – brightest colors in greyscale
2759 frcflags = FRC_BOLD;
2762 if(base.mode & ATTR_ITALIC) {
2764 frcflags = FRC_ITALIC;
2766 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2768 frcflags = FRC_ITALICBOLD;
2771 if(IS_SET(MODE_REVERSE)) {
2772 if(fg == &dc.col[defaultfg]) {
2773 fg = &dc.col[defaultbg];
2775 colfg.red = ~fg->color.red;
2776 colfg.green = ~fg->color.green;
2777 colfg.blue = ~fg->color.blue;
2778 colfg.alpha = fg->color.alpha;
2779 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2783 if(bg == &dc.col[defaultbg]) {
2784 bg = &dc.col[defaultfg];
2786 colbg.red = ~bg->color.red;
2787 colbg.green = ~bg->color.green;
2788 colbg.blue = ~bg->color.blue;
2789 colbg.alpha = bg->color.alpha;
2790 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2795 if(base.mode & ATTR_REVERSE) {
2801 /* Intelligent cleaning up of the borders. */
2803 xclear(0, (y == 0)? 0 : winy, borderpx,
2804 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2806 if(x + charlen >= term.col) {
2807 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2808 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2811 xclear(winx, 0, winx + width, borderpx);
2813 xclear(winx, winy + xw.ch, winx + width, xw.h);
2815 /* Clean up the region we want to draw to. */
2816 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2818 fcsets[0] = font->set;
2819 for(xp = winx; bytelen > 0;) {
2821 * Search for the range in the to be printed string of glyphs
2822 * that are in the main font. Then print that range. If
2823 * some glyph is found that is not in the font, do the
2831 u8cblen = utf8decode(s, &u8char);
2835 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2836 if(!doesexist || bytelen <= 0) {
2845 XftDrawStringUtf8(xw.draw, fg,
2847 winy + font->ascent,
2850 xp += font->width * u8fl;
2862 /* Search the font cache. */
2863 for(i = 0; i < frclen; i++, frp--) {
2867 if(frc[frp].c == u8char
2868 && frc[frp].flags == frcflags) {
2873 /* Nothing was found. */
2876 * Nothing was found in the cache. Now use
2877 * some dozen of Fontconfig calls to get the
2878 * font for one single character.
2880 fcpattern = FcPatternDuplicate(font->pattern);
2881 fccharset = FcCharSetCreate();
2883 FcCharSetAddChar(fccharset, u8char);
2884 FcPatternAddCharSet(fcpattern, FC_CHARSET,
2886 FcPatternAddBool(fcpattern, FC_SCALABLE,
2889 FcConfigSubstitute(0, fcpattern,
2891 FcDefaultSubstitute(fcpattern);
2893 fontpattern = FcFontSetMatch(0, fcsets,
2894 FcTrue, fcpattern, &fcres);
2897 * Overwrite or create the new cache entry
2902 if(frccur >= LEN(frc))
2904 if(frclen > LEN(frc)) {
2906 XftFontClose(xw.dpy, frc[frccur].font);
2909 frc[frccur].font = XftFontOpenPattern(xw.dpy,
2911 frc[frccur].c = u8char;
2912 frc[frccur].flags = frcflags;
2914 FcPatternDestroy(fcpattern);
2915 FcCharSetDestroy(fccharset);
2920 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2921 xp, winy + frc[frp].font->ascent,
2922 (FcChar8 *)u8c, u8cblen);
2928 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2929 winy + font->ascent, (FcChar8 *)s, bytelen);
2932 if(base.mode & ATTR_UNDERLINE) {
2933 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2940 static int oldx = 0, oldy = 0;
2942 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2944 LIMIT(oldx, 0, term.col-1);
2945 LIMIT(oldy, 0, term.row-1);
2947 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2948 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2950 /* remove the old cursor */
2951 if(term.line[oldy][oldx].state & GLYPH_SET) {
2952 sl = utf8size(term.line[oldy][oldx].c);
2953 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2956 xtermclear(oldx, oldy, oldx, oldy);
2959 /* draw the new one */
2960 if(!(IS_SET(MODE_HIDE))) {
2961 if(!(xw.state & WIN_FOCUSED))
2964 if(IS_SET(MODE_REVERSE))
2965 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2968 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2969 oldx = term.c.x, oldy = term.c.y;
2975 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2979 redraw(int timeout) {
2980 struct timespec tv = {0, timeout * 1000};
2986 nanosleep(&tv, NULL);
2987 XSync(xw.dpy, False); /* necessary for a good tput flash */
2993 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2995 drawregion(0, 0, term.col, term.row);
2997 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2999 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3001 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
3006 drawregion(int x1, int y1, int x2, int y2) {
3007 int ic, ib, x, y, ox, sl;
3009 char buf[DRAW_BUF_SIZ];
3010 bool ena_sel = sel.bx != -1;
3012 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3015 if(!(xw.state & WIN_VISIBLE))
3018 for(y = y1; y < y2; y++) {
3022 xtermclear(0, y, term.col, y);
3024 base = term.line[y][0];
3026 for(x = x1; x < x2; x++) {
3027 new = term.line[y][x];
3028 if(ena_sel && *(new.c) && selected(x, y))
3029 new.mode ^= ATTR_REVERSE;
3030 if(ib > 0 && (!(new.state & GLYPH_SET)
3031 || ATTRCMP(base, new)
3032 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3033 xdraws(buf, base, ox, y, ic, ib);
3036 if(new.state & GLYPH_SET) {
3042 sl = utf8size(new.c);
3043 memcpy(buf+ib, new.c, sl);
3049 xdraws(buf, base, ox, y, ic, ib);
3055 expose(XEvent *ev) {
3056 XExposeEvent *e = &ev->xexpose;
3058 if(xw.state & WIN_REDRAW) {
3060 xw.state &= ~WIN_REDRAW;
3066 visibility(XEvent *ev) {
3067 XVisibilityEvent *e = &ev->xvisibility;
3069 if(e->state == VisibilityFullyObscured) {
3070 xw.state &= ~WIN_VISIBLE;
3071 } else if(!(xw.state & WIN_VISIBLE)) {
3072 /* need a full redraw for next Expose, not just a buf copy */
3073 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3079 xw.state &= ~WIN_VISIBLE;
3083 xseturgency(int add) {
3084 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3086 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3087 XSetWMHints(xw.dpy, xw.win, h);
3093 XFocusChangeEvent *e = &ev->xfocus;
3095 if(e->mode == NotifyGrab)
3098 if(ev->type == FocusIn) {
3099 XSetICFocus(xw.xic);
3100 xw.state |= WIN_FOCUSED;
3103 XUnsetICFocus(xw.xic);
3104 xw.state &= ~WIN_FOCUSED;
3109 match(uint mask, uint state) {
3110 state &= ~(ignoremod);
3112 if(mask == XK_NO_MOD && state)
3114 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3116 if((state & mask) != state)
3122 numlock(const Arg *dummy) {
3127 kmap(KeySym k, uint state) {
3132 /* Check for mapped keys out of X11 function keys. */
3133 for(i = 0; i < LEN(mappedkeys); i++) {
3134 if(mappedkeys[i] == k)
3137 if(i == LEN(mappedkeys)) {
3138 if((k & 0xFFFF) < 0xFD00)
3142 for(kp = key; kp < key + LEN(key); kp++) {
3148 if(!match(mask, state))
3151 if(kp->appkey > 0) {
3152 if(!IS_SET(MODE_APPKEYPAD))
3154 if(term.numlock && kp->appkey == 2)
3156 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3160 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3162 && !IS_SET(MODE_APPCURSOR))) {
3166 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3167 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3178 kpress(XEvent *ev) {
3179 XKeyEvent *e = &ev->xkey;
3181 char xstr[31], buf[32], *customkey, *cp = buf;
3186 if(IS_SET(MODE_KBDLOCK))
3189 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3190 e->state &= ~Mod2Mask;
3192 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3193 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3194 bp->func(&(bp->arg));
3199 /* 2. custom keys from config.h */
3200 if((customkey = kmap(ksym, e->state))) {
3201 len = strlen(customkey);
3202 memcpy(buf, customkey, len);
3203 /* 2. hardcoded (overrides X lookup) */
3208 if(len == 1 && e->state & Mod1Mask)
3211 memcpy(cp, xstr, len);
3212 len = cp - buf + len;
3216 if(IS_SET(MODE_ECHO))
3222 cmessage(XEvent *e) {
3225 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3227 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3228 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3229 xw.state |= WIN_FOCUSED;
3231 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3232 xw.state &= ~WIN_FOCUSED;
3234 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3235 /* Send SIGHUP to shell */
3242 cresize(int width, int height) {
3250 col = (xw.w - 2 * borderpx) / xw.cw;
3251 row = (xw.h - 2 * borderpx) / xw.ch;
3260 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3263 cresize(e->xconfigure.width, e->xconfigure.height);
3270 int xfd = XConnectionNumber(xw.dpy), xev;
3271 struct timeval drawtimeout, *tv = NULL, now, last;
3273 gettimeofday(&last, NULL);
3275 for(xev = actionfps;;) {
3277 FD_SET(cmdfd, &rfd);
3279 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3282 die("select failed: %s\n", SERRNO);
3285 gettimeofday(&now, NULL);
3286 drawtimeout.tv_sec = 0;
3287 drawtimeout.tv_usec = (1000/xfps) * 1000;
3290 if(FD_ISSET(cmdfd, &rfd))
3293 if(FD_ISSET(xfd, &rfd))
3296 if(TIMEDIFF(now, last) > \
3297 (xev ? (1000/xfps) : (1000/actionfps))) {
3298 while(XPending(xw.dpy)) {
3299 XNextEvent(xw.dpy, &ev);
3300 if(XFilterEvent(&ev, None))
3302 if(handler[ev.type])
3303 (handler[ev.type])(&ev);
3310 if(xev && !FD_ISSET(xfd, &rfd))
3312 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
3319 main(int argc, char *argv[]) {
3320 int i, bitm, xr, yr;
3323 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3326 for(i = 1; i < argc; i++) {
3327 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
3330 opt_class = argv[i];
3333 /* eat all remaining arguments */
3345 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
3350 if(bitm & WidthValue)
3352 if(bitm & HeightValue)
3354 if(bitm & XNegative && xw.fx == 0)
3356 if(bitm & XNegative && xw.fy == 0)
3359 if(xw.fh != 0 && xw.fw != 0)
3368 opt_title = argv[i];
3375 opt_embed = argv[i];
3381 setlocale(LC_CTYPE, "");
3382 XSetLocaleModifiers("");