1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
22 #include <X11/Xatom.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
31 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
33 #elif defined(__FreeBSD__) || defined(__DragonFly__)
38 "st " VERSION " (c) 2010-2012 st engineers\n" \
39 "usage: st [-t title] [-c class] [-w windowid] [-v] [-f file] [-e command...]\n"
42 #define XEMBED_FOCUS_IN 4
43 #define XEMBED_FOCUS_OUT 5
46 #define ESC_BUF_SIZ 256
47 #define ESC_ARG_SIZ 16
48 #define STR_BUF_SIZ 256
49 #define STR_ARG_SIZ 16
50 #define DRAW_BUF_SIZ 1024
52 #define XK_NO_MOD UINT_MAX
55 #define SELECT_TIMEOUT (20*1000) /* 20 ms */
56 #define DRAW_TIMEOUT (20*1000) /* 20 ms */
57 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
59 #define SERRNO strerror(errno)
60 #define MIN(a, b) ((a) < (b) ? (a) : (b))
61 #define MAX(a, b) ((a) < (b) ? (b) : (a))
62 #define LEN(a) (sizeof(a) / sizeof(a[0]))
63 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
64 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
65 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
66 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
67 #define IS_SET(flag) (term.mode & (flag))
68 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
69 #define X2COL(x) (((x) - BORDER)/xw.cw)
70 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
72 enum glyph_attribute {
80 enum cursor_movement {
107 MODE_MOUSEMOTION = 64,
115 ESC_STR = 4, /* DSC, OSC, PM, APC */
117 ESC_STR_END = 16, /* a final string was encountered */
128 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
130 typedef unsigned char uchar;
131 typedef unsigned int uint;
132 typedef unsigned long ulong;
133 typedef unsigned short ushort;
136 char c[UTF_SIZ]; /* character code */
137 uchar mode; /* attribute flags */
138 ushort fg; /* foreground */
139 ushort bg; /* background */
140 uchar state; /* state flags */
146 Glyph attr; /* current char attributes */
152 /* CSI Escape sequence structs */
153 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
155 char buf[ESC_BUF_SIZ]; /* raw string */
156 int len; /* raw string length */
158 int arg[ESC_ARG_SIZ];
159 int narg; /* nb of args */
163 /* STR Escape sequence structs */
164 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
166 char type; /* ESC type ... */
167 char buf[STR_BUF_SIZ]; /* raw string */
168 int len; /* raw string length */
169 char *args[STR_ARG_SIZ];
170 int narg; /* nb of args */
173 /* Internal representation of the screen */
175 int row; /* nb row */
176 int col; /* nb col */
177 Line* line; /* screen */
178 Line* alt; /* alternate screen */
179 bool* dirty; /* dirtyness of lines */
180 TCursor c; /* cursor */
181 int top; /* top scroll limit */
182 int bot; /* bottom scroll limit */
183 int mode; /* terminal mode flags */
184 int esc; /* escape state flags */
188 /* Purely graphic info */
198 int w; /* window width */
199 int h; /* window height */
200 int ch; /* char height */
201 int cw; /* char width */
202 char state; /* focus, redraw, visible */
203 struct timeval lastdraw;
213 /* TODO: use better name for vars... */
218 struct {int x, y;} b, e;
221 struct timeval tclick1;
222 struct timeval tclick2;
227 /* Drawing Context */
229 ulong col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
240 static void die(const char*, ...);
241 static void draw(void);
242 static void redraw(void);
243 static void drawregion(int, int, int, int);
244 static void execsh(void);
245 static void sigchld(int);
246 static void run(void);
247 static bool last_draw_too_old(void);
249 static void csidump(void);
250 static void csihandle(void);
251 static void csiparse(void);
252 static void csireset(void);
253 static void strdump(void);
254 static void strhandle(void);
255 static void strparse(void);
256 static void strreset(void);
258 static void tclearregion(int, int, int, int);
259 static void tcursor(int);
260 static void tdeletechar(int);
261 static void tdeleteline(int);
262 static void tinsertblank(int);
263 static void tinsertblankline(int);
264 static void tmoveto(int, int);
265 static void tnew(int, int);
266 static void tnewline(int);
267 static void tputtab(bool);
268 static void tputc(char*);
269 static void treset(void);
270 static int tresize(int, int);
271 static void tscrollup(int, int);
272 static void tscrolldown(int, int);
273 static void tsetattr(int*, int);
274 static void tsetchar(char*);
275 static void tsetscroll(int, int);
276 static void tswapscreen(void);
277 static void tsetdirt(int, int);
278 static void tsetmode(bool, bool, int *, int);
279 static void tfulldirt(void);
281 static void ttynew(void);
282 static void ttyread(void);
283 static void ttyresize(int, int);
284 static void ttywrite(const char *, size_t);
286 static void xdraws(char *, Glyph, int, int, int, int);
287 static void xhints(void);
288 static void xclear(int, int, int, int);
290 static void xdrawcursor(void);
291 static void xinit(void);
292 static void xloadcols(void);
293 static void xseturgency(int);
294 static void xsetsel(char*);
295 static void xresize(int, int);
297 static void expose(XEvent *);
298 static void visibility(XEvent *);
299 static void unmap(XEvent *);
300 static char* kmap(KeySym, uint);
301 static void kpress(XEvent *);
302 static void cmessage(XEvent *);
303 static void resize(XEvent *);
304 static void focus(XEvent *);
305 static void brelease(XEvent *);
306 static void bpress(XEvent *);
307 static void bmotion(XEvent *);
308 static void selnotify(XEvent *);
309 static void selrequest(XEvent *);
311 static void selinit(void);
312 static inline bool selected(int, int);
313 static void selcopy(void);
314 static void selpaste();
315 static void selscroll(int, int);
317 static int utf8decode(char *, long *);
318 static int utf8encode(long *, char *);
319 static int utf8size(char *);
320 static int isfullutf8(char *, int);
322 static void (*handler[LASTEvent])(XEvent *) = {
324 [ClientMessage] = cmessage,
325 [ConfigureNotify] = resize,
326 [VisibilityNotify] = visibility,
327 [UnmapNotify] = unmap,
331 [MotionNotify] = bmotion,
332 [ButtonPress] = bpress,
333 [ButtonRelease] = brelease,
334 [SelectionNotify] = selnotify,
335 [SelectionRequest] = selrequest,
342 static CSIEscape csiescseq;
343 static STREscape strescseq;
346 static Selection sel;
348 static char **opt_cmd = NULL;
349 static char *opt_io = NULL;
350 static char *opt_title = NULL;
351 static char *opt_embed = NULL;
352 static char *opt_class = NULL;
355 utf8decode(char *s, long *u) {
361 if(~c & B7) { /* 0xxxxxxx */
364 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
365 *u = c&(B4|B3|B2|B1|B0);
367 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
368 *u = c&(B3|B2|B1|B0);
370 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
375 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
377 if((c & (B7|B6)) != B7) /* 10xxxxxx */
380 *u |= c & (B5|B4|B3|B2|B1|B0);
382 if((n == 1 && *u < 0x80) ||
383 (n == 2 && *u < 0x800) ||
384 (n == 3 && *u < 0x10000) ||
385 (*u >= 0xD800 && *u <= 0xDFFF))
394 utf8encode(long *u, char *s) {
402 *sp = uc; /* 0xxxxxxx */
404 } else if(*u < 0x800) {
405 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
407 } else if(uc < 0x10000) {
408 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
410 } else if(uc <= 0x10FFFF) {
411 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
416 for(i=n,++sp; i>0; --i,++sp)
417 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
427 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
428 UTF-8 otherwise return 0 */
430 isfullutf8(char *s, int b) {
438 else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
440 else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
442 ((b == 2) && (*c2&(B7|B6)) == B7)))
444 else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
446 ((b == 2) && (*c2&(B7|B6)) == B7) ||
447 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
459 else if((c&(B7|B6|B5)) == (B7|B6))
461 else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
469 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
470 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
474 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
475 if(sel.xtarget == None)
476 sel.xtarget = XA_STRING;
480 selected(int x, int y) {
481 if(sel.ey == y && sel.by == y) {
482 int bx = MIN(sel.bx, sel.ex);
483 int ex = MAX(sel.bx, sel.ex);
484 return BETWEEN(x, bx, ex);
486 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
487 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
491 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
493 *b = e->xbutton.button;
495 *x = X2COL(e->xbutton.x);
496 *y = Y2ROW(e->xbutton.y);
497 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
498 sel.b.y = MIN(sel.by, sel.ey);
499 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
500 sel.e.y = MAX(sel.by, sel.ey);
504 mousereport(XEvent *e) {
505 int x = X2COL(e->xbutton.x);
506 int y = Y2ROW(e->xbutton.y);
507 int button = e->xbutton.button;
508 int state = e->xbutton.state;
509 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
510 static int ob, ox, oy;
513 if(e->xbutton.type == MotionNotify) {
514 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
518 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
524 if(e->xbutton.type == ButtonPress) {
530 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
531 + (state & Mod4Mask ? 8 : 0)
532 + (state & ControlMask ? 16 : 0);
534 ttywrite(buf, sizeof(buf));
539 if(IS_SET(MODE_MOUSE))
541 else if(e->xbutton.button == Button1) {
543 tsetdirt(sel.b.y, sel.e.y);
545 sel.ex = sel.bx = X2COL(e->xbutton.x);
546 sel.ey = sel.by = Y2ROW(e->xbutton.y);
553 int x, y, bufsize, is_selected = 0;
559 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
560 ptr = str = malloc(bufsize);
562 /* append every set & selected glyph to the selection */
563 for(y = 0; y < term.row; y++) {
564 for(x = 0; x < term.col; x++) {
565 is_selected = selected(x, y);
566 if((term.line[y][x].state & GLYPH_SET) && is_selected) {
567 int size = utf8size(term.line[y][x].c);
568 memcpy(ptr, term.line[y][x].c, size);
573 /* \n at the end of every selected line except for the last one */
574 if(is_selected && y < sel.e.y)
583 selnotify(XEvent *e) {
584 ulong nitems, ofs, rem;
591 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
592 False, AnyPropertyType, &type, &format,
593 &nitems, &rem, &data)) {
594 fprintf(stderr, "Clipboard allocation failed\n");
597 ttywrite((const char *) data, nitems * format / 8);
599 /* number of 32-bit chunks returned */
600 ofs += nitems * format / 32;
606 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
610 selrequest(XEvent *e) {
611 XSelectionRequestEvent *xsre;
615 xsre = (XSelectionRequestEvent *) e;
616 xev.type = SelectionNotify;
617 xev.requestor = xsre->requestor;
618 xev.selection = xsre->selection;
619 xev.target = xsre->target;
620 xev.time = xsre->time;
624 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
625 if(xsre->target == xa_targets) {
626 /* respond with the supported type */
627 Atom string = sel.xtarget;
628 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
629 XA_ATOM, 32, PropModeReplace,
630 (uchar *) &string, 1);
631 xev.property = xsre->property;
632 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
633 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
634 xsre->target, 8, PropModeReplace,
635 (uchar *) sel.clip, strlen(sel.clip));
636 xev.property = xsre->property;
639 /* all done, send a notification to the listener */
640 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
641 fprintf(stderr, "Error sending SelectionNotify event\n");
646 /* register the selection for both the clipboard and the primary */
652 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
654 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
655 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
661 brelease(XEvent *e) {
662 if(IS_SET(MODE_MOUSE)) {
666 if(e->xbutton.button == Button2)
668 else if(e->xbutton.button == Button1) {
670 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
671 term.dirty[sel.ey] = 1;
672 if(sel.bx == sel.ex && sel.by == sel.ey) {
675 gettimeofday(&now, NULL);
677 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
678 /* triple click on the line */
679 sel.b.x = sel.bx = 0;
680 sel.e.x = sel.ex = term.col;
681 sel.b.y = sel.e.y = sel.ey;
683 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
684 /* double click to select word */
686 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
687 term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
689 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
690 term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
692 sel.b.y = sel.e.y = sel.ey;
698 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
699 gettimeofday(&sel.tclick1, NULL);
705 if(IS_SET(MODE_MOUSE)) {
710 int oldey = sel.ey, oldex = sel.ex;
711 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
713 if(oldey != sel.ey || oldex != sel.ex) {
714 int starty = MIN(oldey, sel.ey);
715 int endy = MAX(oldey, sel.ey);
716 tsetdirt(starty, endy);
723 die(const char *errstr, ...) {
726 va_start(ap, errstr);
727 vfprintf(stderr, errstr, ap);
735 char *envshell = getenv("SHELL");
737 DEFAULT(envshell, SHELL);
738 putenv("TERM="TNAME);
739 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
740 execvp(args[0], args);
747 if(waitpid(pid, &stat, 0) < 0)
748 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
750 exit(WEXITSTATUS(stat));
759 /* seems to work fine on linux, openbsd and freebsd */
760 struct winsize w = {term.row, term.col, 0, 0};
761 if(openpty(&m, &s, NULL, NULL, &w) < 0)
762 die("openpty failed: %s\n", SERRNO);
764 switch(pid = fork()) {
766 die("fork failed\n");
769 setsid(); /* create a new process group */
770 dup2(s, STDIN_FILENO);
771 dup2(s, STDOUT_FILENO);
772 dup2(s, STDERR_FILENO);
773 if(ioctl(s, TIOCSCTTY, NULL) < 0)
774 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
782 signal(SIGCHLD, sigchld);
783 if (opt_io && !(fileio = fopen(opt_io, "w"))) {
784 fprintf(stderr, "Error opening %s:%s",
785 opt_io, strerror(errno));
793 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
795 fprintf(stderr, "\n");
800 static char buf[BUFSIZ];
801 static int buflen = 0;
804 int charsize; /* size of utf8 char in bytes */
808 /* append read bytes to unprocessed bytes */
809 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
810 die("Couldn't read from shell: %s\n", SERRNO);
812 /* process every complete utf8 char */
815 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
816 charsize = utf8decode(ptr, &utf8c);
817 utf8encode(&utf8c, s);
823 /* keep any uncomplete utf8 char for the next call */
824 memmove(buf, ptr, buflen);
828 ttywrite(const char *s, size_t n) {
829 if(write(cmdfd, s, n) == -1)
830 die("write error on tty: %s\n", SERRNO);
834 ttyresize(int x, int y) {
839 w.ws_xpixel = w.ws_ypixel = 0;
840 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
841 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
845 tsetdirt(int top, int bot)
849 LIMIT(top, 0, term.row-1);
850 LIMIT(bot, 0, term.row-1);
852 for(i = top; i <= bot; i++)
859 tsetdirt(0, term.row-1);
866 if(mode == CURSOR_SAVE)
868 else if(mode == CURSOR_LOAD)
869 term.c = c, tmoveto(c.x, c.y);
879 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
881 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
882 for (i = TAB; i < term.col; i += TAB)
884 term.top = 0, term.bot = term.row - 1;
885 term.mode = MODE_WRAP;
886 tclearregion(0, 0, term.col-1, term.row-1);
890 tnew(int col, int row) {
891 /* set screen size */
892 term.row = row, term.col = col;
893 term.line = malloc(term.row * sizeof(Line));
894 term.alt = malloc(term.row * sizeof(Line));
895 term.dirty = malloc(term.row * sizeof(*term.dirty));
896 term.tabs = malloc(term.col * sizeof(*term.tabs));
898 for(row = 0; row < term.row; row++) {
899 term.line[row] = malloc(term.col * sizeof(Glyph));
900 term.alt [row] = malloc(term.col * sizeof(Glyph));
903 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
910 Line* tmp = term.line;
911 term.line = term.alt;
913 term.mode ^= MODE_ALTSCREEN;
918 tscrolldown(int orig, int n) {
922 LIMIT(n, 0, term.bot-orig+1);
924 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
926 for(i = term.bot; i >= orig+n; i--) {
928 term.line[i] = term.line[i-n];
929 term.line[i-n] = temp;
939 tscrollup(int orig, int n) {
942 LIMIT(n, 0, term.bot-orig+1);
944 tclearregion(0, orig, term.col-1, orig+n-1);
946 for(i = orig; i <= term.bot-n; i++) {
948 term.line[i] = term.line[i+n];
949 term.line[i+n] = temp;
959 selscroll(int orig, int n) {
963 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
964 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
968 if(sel.by < term.top) {
972 if(sel.ey > term.bot) {
976 sel.b.y = sel.by, sel.b.x = sel.bx;
977 sel.e.y = sel.ey, sel.e.x = sel.ex;
982 tnewline(int first_col) {
985 tscrollup(term.top, 1);
988 tmoveto(first_col ? 0 : term.c.x, y);
994 char *p = csiescseq.buf;
998 csiescseq.priv = 1, p++;
1000 while(p < csiescseq.buf+csiescseq.len) {
1001 while(isdigit(*p)) {
1002 csiescseq.arg[csiescseq.narg] *= 10;
1003 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1005 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1006 csiescseq.narg++, p++;
1008 csiescseq.mode = *p;
1016 tmoveto(int x, int y) {
1017 LIMIT(x, 0, term.col-1);
1018 LIMIT(y, 0, term.row-1);
1019 term.c.state &= ~CURSOR_WRAPNEXT;
1026 term.dirty[term.c.y] = 1;
1027 term.line[term.c.y][term.c.x] = term.c.attr;
1028 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1029 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1033 tclearregion(int x1, int y1, int x2, int y2) {
1037 temp = x1, x1 = x2, x2 = temp;
1039 temp = y1, y1 = y2, y2 = temp;
1041 LIMIT(x1, 0, term.col-1);
1042 LIMIT(x2, 0, term.col-1);
1043 LIMIT(y1, 0, term.row-1);
1044 LIMIT(y2, 0, term.row-1);
1046 for(y = y1; y <= y2; y++) {
1048 for(x = x1; x <= x2; x++)
1049 term.line[y][x].state = 0;
1054 tdeletechar(int n) {
1055 int src = term.c.x + n;
1057 int size = term.col - src;
1059 term.dirty[term.c.y] = 1;
1061 if(src >= term.col) {
1062 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1065 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1066 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1070 tinsertblank(int n) {
1073 int size = term.col - dst;
1075 term.dirty[term.c.y] = 1;
1077 if(dst >= term.col) {
1078 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1081 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1082 tclearregion(src, term.c.y, dst - 1, term.c.y);
1086 tinsertblankline(int n) {
1087 if(term.c.y < term.top || term.c.y > term.bot)
1090 tscrolldown(term.c.y, n);
1094 tdeleteline(int n) {
1095 if(term.c.y < term.top || term.c.y > term.bot)
1098 tscrollup(term.c.y, n);
1102 tsetattr(int *attr, int l) {
1105 for(i = 0; i < l; i++) {
1108 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
1109 term.c.attr.fg = DefaultFG;
1110 term.c.attr.bg = DefaultBG;
1113 term.c.attr.mode |= ATTR_BOLD;
1115 case 3: /* enter standout (highlight) mode TODO: make it italic */
1116 term.c.attr.mode |= ATTR_REVERSE;
1119 term.c.attr.mode |= ATTR_UNDERLINE;
1122 term.c.attr.mode |= ATTR_REVERSE;
1125 term.c.attr.mode &= ~ATTR_BOLD;
1127 case 23: /* leave standout (highlight) mode TODO: make it italic */
1128 term.c.attr.mode &= ~ATTR_REVERSE;
1131 term.c.attr.mode &= ~ATTR_UNDERLINE;
1134 term.c.attr.mode &= ~ATTR_REVERSE;
1137 if(i + 2 < l && attr[i + 1] == 5) {
1139 if(BETWEEN(attr[i], 0, 255))
1140 term.c.attr.fg = attr[i];
1142 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1145 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1148 term.c.attr.fg = DefaultFG;
1151 if(i + 2 < l && attr[i + 1] == 5) {
1153 if(BETWEEN(attr[i], 0, 255))
1154 term.c.attr.bg = attr[i];
1156 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1159 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1162 term.c.attr.bg = DefaultBG;
1165 if(BETWEEN(attr[i], 30, 37))
1166 term.c.attr.fg = attr[i] - 30;
1167 else if(BETWEEN(attr[i], 40, 47))
1168 term.c.attr.bg = attr[i] - 40;
1169 else if(BETWEEN(attr[i], 90, 97))
1170 term.c.attr.fg = attr[i] - 90 + 8;
1171 else if(BETWEEN(attr[i], 100, 107))
1172 term.c.attr.fg = attr[i] - 100 + 8;
1174 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1181 tsetscroll(int t, int b) {
1184 LIMIT(t, 0, term.row-1);
1185 LIMIT(b, 0, term.row-1);
1195 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1198 tsetmode(bool priv, bool set, int *args, int narg) {
1201 for (lim = args + narg; args < lim; ++args) {
1205 MODBIT(term.mode, set, MODE_APPKEYPAD);
1207 case 5: /* DECSCNM -- Reverve video */
1209 MODBIT(term.mode,set, MODE_REVERSE);
1210 if (mode != term.mode)
1214 MODBIT(term.mode, set, MODE_WRAP);
1217 MODBIT(term.mode, set, MODE_CRLF);
1219 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1222 MODBIT(term.c.state, !set, CURSOR_HIDE);
1224 case 1000: /* 1000,1002: enable xterm mouse report */
1225 MODBIT(term.mode, set, MODE_MOUSEBTN);
1228 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1230 case 1049: /* = 1047 and 1048 */
1233 if(IS_SET(MODE_ALTSCREEN))
1234 tclearregion(0, 0, term.col-1, term.row-1);
1235 if ((set && !IS_SET(MODE_ALTSCREEN)) ||
1236 (!set && IS_SET(MODE_ALTSCREEN))) {
1243 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1247 "erresc: unknown private set/reset mode %d\n",
1254 MODBIT(term.mode, set, MODE_INSERT);
1258 "erresc: unknown set/reset mode %d\n",
1270 switch(csiescseq.mode) {
1273 fprintf(stderr, "erresc: unknown csi ");
1277 case '@': /* ICH -- Insert <n> blank char */
1278 DEFAULT(csiescseq.arg[0], 1);
1279 tinsertblank(csiescseq.arg[0]);
1281 case 'A': /* CUU -- Cursor <n> Up */
1283 DEFAULT(csiescseq.arg[0], 1);
1284 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1286 case 'B': /* CUD -- Cursor <n> Down */
1287 DEFAULT(csiescseq.arg[0], 1);
1288 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1290 case 'C': /* CUF -- Cursor <n> Forward */
1292 DEFAULT(csiescseq.arg[0], 1);
1293 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1295 case 'D': /* CUB -- Cursor <n> Backward */
1296 DEFAULT(csiescseq.arg[0], 1);
1297 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1299 case 'E': /* CNL -- Cursor <n> Down and first col */
1300 DEFAULT(csiescseq.arg[0], 1);
1301 tmoveto(0, term.c.y+csiescseq.arg[0]);
1303 case 'F': /* CPL -- Cursor <n> Up and first col */
1304 DEFAULT(csiescseq.arg[0], 1);
1305 tmoveto(0, term.c.y-csiescseq.arg[0]);
1307 case 'g': /* TBC -- Tabulation clear */
1308 switch (csiescseq.arg[0]) {
1309 case 0: /* clear current tab stop */
1310 term.tabs[term.c.x] = 0;
1312 case 3: /* clear all the tabs */
1313 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1319 case 'G': /* CHA -- Move to <col> */
1320 case '`': /* XXX: HPA -- same? */
1321 DEFAULT(csiescseq.arg[0], 1);
1322 tmoveto(csiescseq.arg[0]-1, term.c.y);
1324 case 'H': /* CUP -- Move to <row> <col> */
1325 case 'f': /* XXX: HVP -- same? */
1326 DEFAULT(csiescseq.arg[0], 1);
1327 DEFAULT(csiescseq.arg[1], 1);
1328 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1330 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1331 DEFAULT(csiescseq.arg[0], 1);
1332 while (csiescseq.arg[0]--)
1335 case 'J': /* ED -- Clear screen */
1337 switch(csiescseq.arg[0]) {
1339 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1340 if(term.c.y < term.row-1)
1341 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1345 tclearregion(0, 0, term.col-1, term.c.y-1);
1346 tclearregion(0, term.c.y, term.c.x, term.c.y);
1349 tclearregion(0, 0, term.col-1, term.row-1);
1355 case 'K': /* EL -- Clear line */
1356 switch(csiescseq.arg[0]) {
1358 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1361 tclearregion(0, term.c.y, term.c.x, term.c.y);
1364 tclearregion(0, term.c.y, term.col-1, term.c.y);
1368 case 'S': /* SU -- Scroll <n> line up */
1369 DEFAULT(csiescseq.arg[0], 1);
1370 tscrollup(term.top, csiescseq.arg[0]);
1372 case 'T': /* SD -- Scroll <n> line down */
1373 DEFAULT(csiescseq.arg[0], 1);
1374 tscrolldown(term.top, csiescseq.arg[0]);
1376 case 'L': /* IL -- Insert <n> blank lines */
1377 DEFAULT(csiescseq.arg[0], 1);
1378 tinsertblankline(csiescseq.arg[0]);
1380 case 'l': /* RM -- Reset Mode */
1381 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1383 case 'M': /* DL -- Delete <n> lines */
1384 DEFAULT(csiescseq.arg[0], 1);
1385 tdeleteline(csiescseq.arg[0]);
1387 case 'X': /* ECH -- Erase <n> char */
1388 DEFAULT(csiescseq.arg[0], 1);
1389 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1391 case 'P': /* DCH -- Delete <n> char */
1392 DEFAULT(csiescseq.arg[0], 1);
1393 tdeletechar(csiescseq.arg[0]);
1395 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1396 DEFAULT(csiescseq.arg[0], 1);
1397 while (csiescseq.arg[0]--)
1400 case 'd': /* VPA -- Move to <row> */
1401 DEFAULT(csiescseq.arg[0], 1);
1402 tmoveto(term.c.x, csiescseq.arg[0]-1);
1404 case 'h': /* SM -- Set terminal mode */
1405 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1407 case 'm': /* SGR -- Terminal attribute (color) */
1408 tsetattr(csiescseq.arg, csiescseq.narg);
1410 case 'r': /* DECSTBM -- Set Scrolling Region */
1414 DEFAULT(csiescseq.arg[0], 1);
1415 DEFAULT(csiescseq.arg[1], term.row);
1416 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1420 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1421 tcursor(CURSOR_SAVE);
1423 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1424 tcursor(CURSOR_LOAD);
1433 for(i = 0; i < csiescseq.len; i++) {
1434 uint c = csiescseq.buf[i] & 0xff;
1435 if(isprint(c)) putchar(c);
1436 else if(c == '\n') printf("(\\n)");
1437 else if(c == '\r') printf("(\\r)");
1438 else if(c == 0x1b) printf("(\\e)");
1439 else printf("(%02x)", c);
1446 memset(&csiescseq, 0, sizeof(csiescseq));
1454 * TODO: make this being useful in case of color palette change.
1460 switch(strescseq.type) {
1461 case ']': /* OSC -- Operating System Command */
1467 * TODO: Handle special chars in string, like umlauts.
1470 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1474 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1476 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1479 fprintf(stderr, "erresc: unknown str ");
1484 case 'P': /* DSC -- Device Control String */
1485 case '_': /* APC -- Application Program Command */
1486 case '^': /* PM -- Privacy Message */
1488 fprintf(stderr, "erresc: unknown str ");
1498 * TODO: Implement parsing like for CSI when required.
1499 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1507 printf("ESC%c", strescseq.type);
1508 for(i = 0; i < strescseq.len; i++) {
1509 uint c = strescseq.buf[i] & 0xff;
1510 if(isprint(c)) putchar(c);
1511 else if(c == '\n') printf("(\\n)");
1512 else if(c == '\r') printf("(\\r)");
1513 else if(c == 0x1b) printf("(\\e)");
1514 else printf("(%02x)", c);
1521 memset(&strescseq, 0, sizeof(strescseq));
1525 tputtab(bool forward) {
1526 unsigned x = term.c.x;
1531 for (++x; x < term.col && !term.tabs[x]; ++x)
1536 for (--x; x > 0 && !term.tabs[x]; --x)
1539 tmoveto(x, term.c.y);
1547 putc(ascii, fileio);
1548 if(term.esc & ESC_START) {
1549 if(term.esc & ESC_CSI) {
1550 csiescseq.buf[csiescseq.len++] = ascii;
1551 if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1553 csiparse(), csihandle();
1555 } else if(term.esc & ESC_STR) {
1558 term.esc = ESC_START | ESC_STR_END;
1560 case '\a': /* backwards compatibility to xterm */
1565 strescseq.buf[strescseq.len++] = ascii;
1566 if (strescseq.len+1 >= STR_BUF_SIZ) {
1571 } else if(term.esc & ESC_STR_END) {
1575 } else if(term.esc & ESC_ALTCHARSET) {
1577 case '0': /* Line drawing crap */
1578 term.c.attr.mode |= ATTR_GFX;
1580 case 'B': /* Back to regular text */
1581 term.c.attr.mode &= ~ATTR_GFX;
1584 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1590 term.esc |= ESC_CSI;
1592 case 'P': /* DCS -- Device Control String */
1593 case '_': /* APC -- Application Program Command */
1594 case '^': /* PM -- Privacy Message */
1595 case ']': /* OSC -- Operating System Command */
1597 strescseq.type = ascii;
1598 term.esc |= ESC_STR;
1601 term.esc |= ESC_ALTCHARSET;
1603 case 'D': /* IND -- Linefeed */
1604 if(term.c.y == term.bot)
1605 tscrollup(term.top, 1);
1607 tmoveto(term.c.x, term.c.y+1);
1610 case 'E': /* NEL -- Next line */
1611 tnewline(1); /* always go to first col */
1614 case 'H': /* HTS -- Horizontal tab stop */
1615 term.tabs[term.c.x] = 1;
1618 case 'M': /* RI -- Reverse index */
1619 if(term.c.y == term.top)
1620 tscrolldown(term.top, 1);
1622 tmoveto(term.c.x, term.c.y-1);
1625 case 'c': /* RIS -- Reset to inital state */
1629 case '=': /* DECPAM -- Application keypad */
1630 term.mode |= MODE_APPKEYPAD;
1633 case '>': /* DECPNM -- Normal keypad */
1634 term.mode &= ~MODE_APPKEYPAD;
1637 case '7': /* DECSC -- Save Cursor */
1638 tcursor(CURSOR_SAVE);
1641 case '8': /* DECRC -- Restore Cursor */
1642 tcursor(CURSOR_LOAD);
1645 case '\\': /* ST -- Stop */
1649 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1650 (uchar) ascii, isprint(ascii)?ascii:'.');
1655 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1662 tmoveto(term.c.x-1, term.c.y);
1665 tmoveto(0, term.c.y);
1670 /* go to first col if the mode is set */
1671 tnewline(IS_SET(MODE_CRLF));
1674 if(!(xw.state & WIN_FOCUSED))
1679 term.esc = ESC_START;
1682 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1683 tnewline(1); /* always go to first col */
1685 if(term.c.x+1 < term.col)
1686 tmoveto(term.c.x+1, term.c.y);
1688 term.c.state |= CURSOR_WRAPNEXT;
1694 tresize(int col, int row) {
1696 int minrow = MIN(row, term.row);
1697 int mincol = MIN(col, term.col);
1698 int slide = term.c.y - row + 1;
1700 if(col < 1 || row < 1)
1703 /* free unneeded rows */
1706 /* slide screen to keep cursor where we expect it -
1707 * tscrollup would work here, but we can optimize to
1708 * memmove because we're freeing the earlier lines */
1709 for(/* i = 0 */; i < slide; i++) {
1713 memmove(term.line, term.line + slide, row * sizeof(Line));
1714 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1716 for(i += row; i < term.row; i++) {
1721 /* resize to new height */
1722 term.line = realloc(term.line, row * sizeof(Line));
1723 term.alt = realloc(term.alt, row * sizeof(Line));
1724 term.dirty = realloc(term.dirty, row * sizeof(*term.dirty));
1725 term.tabs = realloc(term.tabs, col * sizeof(*term.tabs));
1727 /* resize each row to new width, zero-pad if needed */
1728 for(i = 0; i < minrow; i++) {
1730 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1731 term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
1732 for(x = mincol; x < col; x++) {
1733 term.line[i][x].state = 0;
1734 term.alt[i][x].state = 0;
1738 /* allocate any new rows */
1739 for(/* i == minrow */; i < row; i++) {
1741 term.line[i] = calloc(col, sizeof(Glyph));
1742 term.alt [i] = calloc(col, sizeof(Glyph));
1744 if (col > term.col) {
1745 bool *bp = term.tabs + term.col;
1747 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1748 while (--bp > term.tabs && !*bp)
1750 for (bp += TAB; bp < term.tabs + col; bp += TAB)
1753 /* update terminal size */
1754 term.col = col, term.row = row;
1755 /* make use of the LIMIT in tmoveto */
1756 tmoveto(term.c.x, term.c.y);
1757 /* reset scrolling region */
1758 tsetscroll(0, row-1);
1764 xresize(int col, int row) {
1765 xw.w = MAX(1, 2*BORDER + col * xw.cw);
1766 xw.h = MAX(1, 2*BORDER + row * xw.ch);
1773 ulong white = WhitePixel(xw.dpy, xw.scr);
1775 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1776 for(i = 0; i < LEN(colorname); i++) {
1779 if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
1781 fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1783 dc.col[i] = color.pixel;
1786 /* load colors [16-255] ; same colors as xterm */
1787 for(i = 16, r = 0; r < 6; r++)
1788 for(g = 0; g < 6; g++)
1789 for(b = 0; b < 6; b++) {
1790 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1791 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1792 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1793 if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
1795 fprintf(stderr, "Could not allocate color %d\n", i);
1797 dc.col[i] = color.pixel;
1801 for(r = 0; r < 24; r++, i++) {
1802 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1803 if (!XAllocColor(xw.dpy, xw.cmap, &color)) {
1805 fprintf(stderr, "Could not allocate color %d\n", i);
1807 dc.col[i] = color.pixel;
1812 xclear(int x1, int y1, int x2, int y2) {
1813 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
1814 XFillRectangle(xw.dpy, xw.buf, dc.gc,
1815 BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
1816 (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1821 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
1822 XWMHints wm = {.flags = InputHint, .input = 1};
1824 .flags = PSize | PResizeInc | PBaseSize,
1827 .height_inc = xw.ch,
1829 .base_height = 2*BORDER,
1830 .base_width = 2*BORDER,
1832 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1836 xinitfont(char *fontstr) {
1838 char *def, **missing;
1842 set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
1845 fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
1846 XFreeStringList(missing);
1852 xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
1853 XFontStruct **xfonts;
1857 *ascent = *descent = *lbearing = *rbearing = 0;
1858 n = XFontsOfFontSet(set, &xfonts, &font_names);
1859 for(i = 0; i < n; i++) {
1860 *ascent = MAX(*ascent, (*xfonts)->ascent);
1861 *descent = MAX(*descent, (*xfonts)->descent);
1862 *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
1863 *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
1869 initfonts(char *fontstr, char *bfontstr) {
1870 if((dc.font.set = xinitfont(fontstr)) == NULL ||
1871 (dc.bfont.set = xinitfont(bfontstr)) == NULL)
1872 die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
1873 xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
1874 &dc.font.lbearing, &dc.font.rbearing);
1875 xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
1876 &dc.bfont.lbearing, &dc.bfont.rbearing);
1881 XSetWindowAttributes attrs;
1885 if(!(xw.dpy = XOpenDisplay(NULL)))
1886 die("Can't open display\n");
1887 xw.scr = XDefaultScreen(xw.dpy);
1890 initfonts(FONT, BOLDFONT);
1892 /* XXX: Assuming same size for bold font */
1893 xw.cw = dc.font.rbearing - dc.font.lbearing;
1894 xw.ch = dc.font.ascent + dc.font.descent;
1897 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1900 /* window - default size */
1901 xw.h = 2*BORDER + term.row * xw.ch;
1902 xw.w = 2*BORDER + term.col * xw.cw;
1904 attrs.background_pixel = dc.col[DefaultBG];
1905 attrs.border_pixel = dc.col[DefaultBG];
1906 attrs.bit_gravity = NorthWestGravity;
1907 attrs.event_mask = FocusChangeMask | KeyPressMask
1908 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1909 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask
1910 | EnterWindowMask | LeaveWindowMask;
1911 attrs.colormap = xw.cmap;
1913 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
1914 xw.win = XCreateWindow(xw.dpy, parent, 0, 0,
1915 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1916 XDefaultVisual(xw.dpy, xw.scr),
1917 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
1920 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
1924 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1925 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1926 | XIMStatusNothing, XNClientWindow, xw.win,
1927 XNFocusWindow, xw.win, NULL);
1929 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
1931 /* white cursor, black outline */
1932 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
1933 XDefineCursor(xw.dpy, xw.win, cursor);
1934 XRecolorCursor(xw.dpy, cursor,
1935 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
1936 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
1938 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1940 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
1941 XMapWindow(xw.dpy, xw.win);
1947 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
1948 int fg = base.fg, bg = base.bg, temp;
1949 int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
1950 XFontSet fontset = dc.font.set;
1953 /* only switch default fg/bg if term is in RV mode */
1954 if(IS_SET(MODE_REVERSE)) {
1961 if(base.mode & ATTR_REVERSE)
1962 temp = fg, fg = bg, bg = temp;
1964 if(base.mode & ATTR_BOLD) {
1966 fontset = dc.bfont.set;
1969 XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
1970 XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
1972 if(base.mode & ATTR_GFX) {
1973 for(i = 0; i < bytelen; i++) {
1974 char c = gfx[(uint)s[i] % 256];
1977 else if(s[i] > 0x5f)
1982 XmbDrawImageString(xw.dpy, xw.buf, fontset, dc.gc, winx, winy, s, bytelen);
1984 if(base.mode & ATTR_UNDERLINE)
1985 XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1988 /* copy buffer pixmap to screen pixmap */
1991 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
1992 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
1998 static int oldx = 0;
1999 static int oldy = 0;
2001 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2003 LIMIT(oldx, 0, term.col-1);
2004 LIMIT(oldy, 0, term.row-1);
2006 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2007 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2009 /* remove the old cursor */
2010 if(term.line[oldy][oldx].state & GLYPH_SET) {
2011 sl = utf8size(term.line[oldy][oldx].c);
2012 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2014 xclear(oldx, oldy, oldx, oldy);
2016 xcopy(oldx, oldy, 1, 1);
2018 /* draw the new one */
2019 if(!(term.c.state & CURSOR_HIDE)) {
2020 if(!(xw.state & WIN_FOCUSED))
2023 if(IS_SET(MODE_REVERSE))
2024 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2027 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2028 oldx = term.c.x, oldy = term.c.y;
2031 xcopy(term.c.x, term.c.y, 1, 1);
2036 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2039 nanosleep(&tv, NULL);
2044 drawregion(0, 0, term.col, term.row);
2046 gettimeofday(&xw.lastdraw, NULL);
2050 drawregion(int x1, int y1, int x2, int y2) {
2051 int ic, ib, x, y, ox, sl;
2053 char buf[DRAW_BUF_SIZ];
2055 if(!(xw.state & WIN_VISIBLE))
2058 for(y = y1; y < y2; y++) {
2061 xclear(0, y, term.col, y);
2063 base = term.line[y][0];
2065 for(x = x1; x < x2; x++) {
2066 new = term.line[y][x];
2067 if(sel.bx != -1 && *(new.c) && selected(x, y))
2068 new.mode ^= ATTR_REVERSE;
2069 if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2070 ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2071 xdraws(buf, base, ox, y, ic, ib);
2074 if(new.state & GLYPH_SET) {
2079 sl = utf8size(new.c);
2080 memcpy(buf+ib, new.c, sl);
2086 xdraws(buf, base, ox, y, ic, ib);
2092 expose(XEvent *ev) {
2093 XExposeEvent *e = &ev->xexpose;
2094 if(xw.state & WIN_REDRAW) {
2096 xw.state &= ~WIN_REDRAW;
2102 visibility(XEvent *ev) {
2103 XVisibilityEvent *e = &ev->xvisibility;
2104 if(e->state == VisibilityFullyObscured)
2105 xw.state &= ~WIN_VISIBLE;
2106 else if(!(xw.state & WIN_VISIBLE))
2107 /* need a full redraw for next Expose, not just a buf copy */
2108 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2113 xw.state &= ~WIN_VISIBLE;
2117 xseturgency(int add) {
2118 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2119 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2120 XSetWMHints(xw.dpy, xw.win, h);
2126 if(ev->type == FocusIn) {
2127 xw.state |= WIN_FOCUSED;
2130 xw.state &= ~WIN_FOCUSED;
2135 kmap(KeySym k, uint state) {
2138 for(i = 0; i < LEN(key); i++) {
2139 uint mask = key[i].mask;
2140 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2141 return (char*)key[i].s;
2147 kpress(XEvent *ev) {
2148 XKeyEvent *e = &ev->xkey;
2157 meta = e->state & Mod1Mask;
2158 shift = e->state & ShiftMask;
2159 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2161 /* 1. custom keys from config.h */
2162 if((customkey = kmap(ksym, e->state)))
2163 ttywrite(customkey, strlen(customkey));
2164 /* 2. hardcoded (overrides X lookup) */
2171 /* XXX: shift up/down doesn't work */
2172 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2180 if(IS_SET(MODE_CRLF))
2181 ttywrite("\r\n", 2);
2188 if(meta && len == 1)
2189 ttywrite("\033", 1);
2197 cmessage(XEvent *e) {
2199 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2200 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2201 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2202 xw.state |= WIN_FOCUSED;
2204 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2205 xw.state &= ~WIN_FOCUSED;
2215 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2218 xw.w = e->xconfigure.width;
2219 xw.h = e->xconfigure.height;
2220 col = (xw.w - 2*BORDER) / xw.cw;
2221 row = (xw.h - 2*BORDER) / xw.ch;
2222 if(col == term.col && row == term.row)
2224 if(tresize(col, row))
2226 ttyresize(col, row);
2231 last_draw_too_old(void) {
2233 gettimeofday(&now, NULL);
2234 return TIMEDIFF(now, xw.lastdraw) >= DRAW_TIMEOUT/1000;
2241 int xfd = XConnectionNumber(xw.dpy);
2242 struct timeval timeout = {0};
2243 bool stuff_to_print = 0;
2247 FD_SET(cmdfd, &rfd);
2250 timeout.tv_usec = SELECT_TIMEOUT;
2251 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, &timeout) < 0) {
2254 die("select failed: %s\n", SERRNO);
2256 if(FD_ISSET(cmdfd, &rfd)) {
2261 if(stuff_to_print && last_draw_too_old()) {
2266 while(XPending(xw.dpy)) {
2267 XNextEvent(xw.dpy, &ev);
2268 if(XFilterEvent(&ev, xw.win))
2270 if(handler[ev.type])
2271 (handler[ev.type])(&ev);
2277 main(int argc, char *argv[]) {
2280 for(i = 1; i < argc; i++) {
2281 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2283 if(++i < argc) opt_title = argv[i];
2286 if(++i < argc) opt_class = argv[i];
2289 if(++i < argc) opt_embed = argv[i];
2292 if (++i < argc) opt_io = argv[i];
2295 /* eat every remaining arguments */
2296 if(++i < argc) opt_cmd = &argv[i];
2305 setlocale(LC_CTYPE, "");