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>
28 #include <X11/Xft/Xft.h>
34 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
36 #elif defined(__FreeBSD__) || defined(__DragonFly__)
41 "st " VERSION " (c) 2010-2012 st engineers\n" \
42 "usage: st [-t title] [-c class] [-g geometry]" \
43 " [-w windowid] [-v] [-f file] [-e command...]\n"
46 #define XEMBED_FOCUS_IN 4
47 #define XEMBED_FOCUS_OUT 5
50 #define ESC_BUF_SIZ 256
51 #define ESC_ARG_SIZ 16
52 #define STR_BUF_SIZ 256
53 #define STR_ARG_SIZ 16
54 #define DRAW_BUF_SIZ 20*1024
56 #define XK_NO_MOD UINT_MAX
59 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
61 #define SERRNO strerror(errno)
62 #define MIN(a, b) ((a) < (b) ? (a) : (b))
63 #define MAX(a, b) ((a) < (b) ? (b) : (a))
64 #define LEN(a) (sizeof(a) / sizeof(a[0]))
65 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
66 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
67 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
68 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
69 #define IS_SET(flag) (term.mode & (flag))
70 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
71 #define X2COL(x) (((x) - BORDER)/xw.cw)
72 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
74 enum glyph_attribute {
84 enum cursor_movement {
111 MODE_MOUSEMOTION = 64,
119 ESC_STR = 4, /* DSC, OSC, PM, APC */
121 ESC_STR_END = 16, /* a final string was encountered */
132 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
134 typedef unsigned char uchar;
135 typedef unsigned int uint;
136 typedef unsigned long ulong;
137 typedef unsigned short ushort;
140 char c[UTF_SIZ]; /* character code */
141 uchar mode; /* attribute flags */
142 ushort fg; /* foreground */
143 ushort bg; /* background */
144 uchar state; /* state flags */
150 Glyph attr; /* current char attributes */
156 /* CSI Escape sequence structs */
157 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
159 char buf[ESC_BUF_SIZ]; /* raw string */
160 int len; /* raw string length */
162 int arg[ESC_ARG_SIZ];
163 int narg; /* nb of args */
167 /* STR Escape sequence structs */
168 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
170 char type; /* ESC type ... */
171 char buf[STR_BUF_SIZ]; /* raw string */
172 int len; /* raw string length */
173 char *args[STR_ARG_SIZ];
174 int narg; /* nb of args */
177 /* Internal representation of the screen */
179 int row; /* nb row */
180 int col; /* nb col */
181 Line* line; /* screen */
182 Line* alt; /* alternate screen */
183 bool* dirty; /* dirtyness of lines */
184 TCursor c; /* cursor */
185 int top; /* top scroll limit */
186 int bot; /* bottom scroll limit */
187 int mode; /* terminal mode flags */
188 int esc; /* escape state flags */
192 /* Purely graphic info */
204 bool isfixed; /* is fixed geometry? */
205 int fx, fy, fw, fh; /* fixed geometry */
206 int tw, th; /* tty width and height */
207 int w; /* window width */
208 int h; /* window height */
209 int ch; /* char height */
210 int cw; /* char width */
211 char state; /* focus, redraw, visible */
220 /* TODO: use better name for vars... */
225 struct {int x, y;} b, e;
229 struct timeval tclick1;
230 struct timeval tclick2;
245 /* Drawing Context */
247 ulong col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
248 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
250 Font font, bfont, ifont, ibfont;
253 static void die(const char*, ...);
254 static void draw(void);
255 static void redraw(void);
256 static void drawregion(int, int, int, int);
257 static void execsh(void);
258 static void sigchld(int);
259 static void run(void);
261 static void csidump(void);
262 static void csihandle(void);
263 static void csiparse(void);
264 static void csireset(void);
265 static void strdump(void);
266 static void strhandle(void);
267 static void strparse(void);
268 static void strreset(void);
270 static void tclearregion(int, int, int, int);
271 static void tcursor(int);
272 static void tdeletechar(int);
273 static void tdeleteline(int);
274 static void tinsertblank(int);
275 static void tinsertblankline(int);
276 static void tmoveto(int, int);
277 static void tnew(int, int);
278 static void tnewline(int);
279 static void tputtab(bool);
280 static void tputc(char*);
281 static void treset(void);
282 static int tresize(int, int);
283 static void tscrollup(int, int);
284 static void tscrolldown(int, int);
285 static void tsetattr(int*, int);
286 static void tsetchar(char*);
287 static void tsetscroll(int, int);
288 static void tswapscreen(void);
289 static void tsetdirt(int, int);
290 static void tsetmode(bool, bool, int *, int);
291 static void tfulldirt(void);
293 static void ttynew(void);
294 static void ttyread(void);
295 static void ttyresize(int, int);
296 static void ttywrite(const char *, size_t);
298 static void xdraws(char *, Glyph, int, int, int, int);
299 static void xhints(void);
300 static void xclear(int, int, int, int);
301 static void xdrawcursor(void);
302 static void xinit(void);
303 static void xloadcols(void);
304 static void xresettitle(void);
305 static void xseturgency(int);
306 static void xsetsel(char*);
307 static void xresize(int, int);
309 static void expose(XEvent *);
310 static void visibility(XEvent *);
311 static void unmap(XEvent *);
312 static char* kmap(KeySym, uint);
313 static void kpress(XEvent *);
314 static void cmessage(XEvent *);
315 static void resize(XEvent *);
316 static void focus(XEvent *);
317 static void brelease(XEvent *);
318 static void bpress(XEvent *);
319 static void bmotion(XEvent *);
320 static void selnotify(XEvent *);
321 static void selclear(XEvent *);
322 static void selrequest(XEvent *);
324 static void selinit(void);
325 static inline bool selected(int, int);
326 static void selcopy(void);
327 static void selpaste(void);
328 static void selscroll(int, int);
330 static int utf8decode(char *, long *);
331 static int utf8encode(long *, char *);
332 static int utf8size(char *);
333 static int isfullutf8(char *, int);
335 static void *xmalloc(size_t);
336 static void *xrealloc(void *, size_t);
337 static void *xcalloc(size_t nmemb, size_t size);
339 static void (*handler[LASTEvent])(XEvent *) = {
341 [ClientMessage] = cmessage,
342 [ConfigureNotify] = resize,
343 [VisibilityNotify] = visibility,
344 [UnmapNotify] = unmap,
348 [MotionNotify] = bmotion,
349 [ButtonPress] = bpress,
350 [ButtonRelease] = brelease,
351 [SelectionClear] = selclear,
352 [SelectionNotify] = selnotify,
353 [SelectionRequest] = selrequest,
360 static CSIEscape csiescseq;
361 static STREscape strescseq;
364 static Selection sel;
365 static int iofd = -1;
366 static char **opt_cmd = NULL;
367 static char *opt_io = NULL;
368 static char *opt_title = NULL;
369 static char *opt_embed = NULL;
370 static char *opt_class = NULL;
373 xmalloc(size_t len) {
374 void *p = malloc(len);
376 die("Out of memory\n");
381 xrealloc(void *p, size_t len) {
382 if((p = realloc(p, len)) == NULL)
383 die("Out of memory\n");
388 xcalloc(size_t nmemb, size_t size) {
389 void *p = calloc(nmemb, size);
391 die("Out of memory\n");
396 utf8decode(char *s, long *u) {
402 if(~c & B7) { /* 0xxxxxxx */
405 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
406 *u = c&(B4|B3|B2|B1|B0);
408 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
409 *u = c&(B3|B2|B1|B0);
411 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
416 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
418 if((c & (B7|B6)) != B7) /* 10xxxxxx */
421 *u |= c & (B5|B4|B3|B2|B1|B0);
423 if((n == 1 && *u < 0x80) ||
424 (n == 2 && *u < 0x800) ||
425 (n == 3 && *u < 0x10000) ||
426 (*u >= 0xD800 && *u <= 0xDFFF))
435 utf8encode(long *u, char *s) {
443 *sp = uc; /* 0xxxxxxx */
445 } else if(*u < 0x800) {
446 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
448 } else if(uc < 0x10000) {
449 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
451 } else if(uc <= 0x10FFFF) {
452 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
457 for(i=n,++sp; i>0; --i,++sp)
458 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
468 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
469 UTF-8 otherwise return 0 */
471 isfullutf8(char *s, int b) {
479 else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
481 else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
483 ((b == 2) && (*c2&(B7|B6)) == B7)))
485 else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
487 ((b == 2) && (*c2&(B7|B6)) == B7) ||
488 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
500 else if((c&(B7|B6|B5)) == (B7|B6))
502 else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
510 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
511 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
515 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
516 if(sel.xtarget == None)
517 sel.xtarget = XA_STRING;
521 selected(int x, int y) {
522 if(sel.ey == y && sel.by == y) {
523 int bx = MIN(sel.bx, sel.ex);
524 int ex = MAX(sel.bx, sel.ex);
525 return BETWEEN(x, bx, ex);
527 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
528 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
532 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
534 *b = e->xbutton.button;
536 *x = X2COL(e->xbutton.x);
537 *y = Y2ROW(e->xbutton.y);
538 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
539 sel.b.y = MIN(sel.by, sel.ey);
540 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
541 sel.e.y = MAX(sel.by, sel.ey);
545 mousereport(XEvent *e) {
546 int x = X2COL(e->xbutton.x);
547 int y = Y2ROW(e->xbutton.y);
548 int button = e->xbutton.button;
549 int state = e->xbutton.state;
550 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
551 static int ob, ox, oy;
554 if(e->xbutton.type == MotionNotify) {
555 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
559 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
565 if(e->xbutton.type == ButtonPress) {
571 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
572 + (state & Mod4Mask ? 8 : 0)
573 + (state & ControlMask ? 16 : 0);
575 ttywrite(buf, sizeof(buf));
580 if(IS_SET(MODE_MOUSE))
582 else if(e->xbutton.button == Button1) {
585 tsetdirt(sel.b.y, sel.e.y);
589 sel.ex = sel.bx = X2COL(e->xbutton.x);
590 sel.ey = sel.by = Y2ROW(e->xbutton.y);
597 int x, y, bufsize, is_selected = 0;
603 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
604 ptr = str = xmalloc(bufsize);
606 /* append every set & selected glyph to the selection */
607 for(y = 0; y < term.row; y++) {
608 for(x = 0; x < term.col; x++) {
611 Glyph *gp = &term.line[y][x];
613 if(!(is_selected = selected(x, y)))
615 p = (gp->state & GLYPH_SET) ? gp->c : " ";
617 memcpy(ptr, p, size);
620 /* \n at the end of every selected line except for the last one */
621 if(is_selected && y < sel.e.y)
626 sel.alt = IS_SET(MODE_ALTSCREEN);
631 selnotify(XEvent *e) {
632 ulong nitems, ofs, rem;
639 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
640 False, AnyPropertyType, &type, &format,
641 &nitems, &rem, &data)) {
642 fprintf(stderr, "Clipboard allocation failed\n");
645 ttywrite((const char *) data, nitems * format / 8);
647 /* number of 32-bit chunks returned */
648 ofs += nitems * format / 32;
654 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
657 void selclear(XEvent *e) {
661 tsetdirt(sel.b.y, sel.e.y);
665 selrequest(XEvent *e) {
666 XSelectionRequestEvent *xsre;
670 xsre = (XSelectionRequestEvent *) e;
671 xev.type = SelectionNotify;
672 xev.requestor = xsre->requestor;
673 xev.selection = xsre->selection;
674 xev.target = xsre->target;
675 xev.time = xsre->time;
679 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
680 if(xsre->target == xa_targets) {
681 /* respond with the supported type */
682 Atom string = sel.xtarget;
683 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
684 XA_ATOM, 32, PropModeReplace,
685 (uchar *) &string, 1);
686 xev.property = xsre->property;
687 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
688 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
689 xsre->target, 8, PropModeReplace,
690 (uchar *) sel.clip, strlen(sel.clip));
691 xev.property = xsre->property;
694 /* all done, send a notification to the listener */
695 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
696 fprintf(stderr, "Error sending SelectionNotify event\n");
701 /* register the selection for both the clipboard and the primary */
707 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
709 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
710 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
714 brelease(XEvent *e) {
715 if(IS_SET(MODE_MOUSE)) {
719 if(e->xbutton.button == Button2)
721 else if(e->xbutton.button == Button1) {
723 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
724 term.dirty[sel.ey] = 1;
725 if(sel.bx == sel.ex && sel.by == sel.ey) {
728 gettimeofday(&now, NULL);
730 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
731 /* triple click on the line */
732 sel.b.x = sel.bx = 0;
733 sel.e.x = sel.ex = term.col;
734 sel.b.y = sel.e.y = sel.ey;
736 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
737 /* double click to select word */
739 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
740 term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
742 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
743 term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
745 sel.b.y = sel.e.y = sel.ey;
751 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
752 gettimeofday(&sel.tclick1, NULL);
757 if(IS_SET(MODE_MOUSE)) {
762 int oldey = sel.ey, oldex = sel.ex;
763 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
765 if(oldey != sel.ey || oldex != sel.ex) {
766 int starty = MIN(oldey, sel.ey);
767 int endy = MAX(oldey, sel.ey);
768 tsetdirt(starty, endy);
774 die(const char *errstr, ...) {
777 va_start(ap, errstr);
778 vfprintf(stderr, errstr, ap);
786 char *envshell = getenv("SHELL");
792 signal(SIGCHLD, SIG_DFL);
793 signal(SIGHUP, SIG_DFL);
794 signal(SIGINT, SIG_DFL);
795 signal(SIGQUIT, SIG_DFL);
796 signal(SIGTERM, SIG_DFL);
797 signal(SIGALRM, SIG_DFL);
799 DEFAULT(envshell, SHELL);
800 putenv("TERM="TNAME);
801 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
802 execvp(args[0], args);
809 if(waitpid(pid, &stat, 0) < 0)
810 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
812 exit(WEXITSTATUS(stat));
821 /* seems to work fine on linux, openbsd and freebsd */
822 struct winsize w = {term.row, term.col, 0, 0};
823 if(openpty(&m, &s, NULL, NULL, &w) < 0)
824 die("openpty failed: %s\n", SERRNO);
826 switch(pid = fork()) {
828 die("fork failed\n");
831 setsid(); /* create a new process group */
832 dup2(s, STDIN_FILENO);
833 dup2(s, STDOUT_FILENO);
834 dup2(s, STDERR_FILENO);
835 if(ioctl(s, TIOCSCTTY, NULL) < 0)
836 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
844 signal(SIGCHLD, sigchld);
846 if(!strcmp(opt_io, "-")) {
847 iofd = STDOUT_FILENO;
849 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
850 fprintf(stderr, "Error opening %s:%s\n",
851 opt_io, strerror(errno));
861 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
863 fprintf(stderr, "\n");
868 static char buf[BUFSIZ];
869 static int buflen = 0;
872 int charsize; /* size of utf8 char in bytes */
876 /* append read bytes to unprocessed bytes */
877 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
878 die("Couldn't read from shell: %s\n", SERRNO);
880 /* process every complete utf8 char */
883 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
884 charsize = utf8decode(ptr, &utf8c);
885 utf8encode(&utf8c, s);
891 /* keep any uncomplete utf8 char for the next call */
892 memmove(buf, ptr, buflen);
896 ttywrite(const char *s, size_t n) {
897 if(write(cmdfd, s, n) == -1)
898 die("write error on tty: %s\n", SERRNO);
902 ttyresize(int x, int y) {
909 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
910 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
914 tsetdirt(int top, int bot)
918 LIMIT(top, 0, term.row-1);
919 LIMIT(bot, 0, term.row-1);
921 for(i = top; i <= bot; i++)
928 tsetdirt(0, term.row-1);
935 if(mode == CURSOR_SAVE)
937 else if(mode == CURSOR_LOAD)
938 term.c = c, tmoveto(c.x, c.y);
948 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
950 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
951 for(i = TAB; i < term.col; i += TAB)
953 term.top = 0, term.bot = term.row - 1;
954 term.mode = MODE_WRAP;
955 xclear(0, 0, xw.w, xw.h);
956 tclearregion(0, 0, term.col-1, term.row-1);
960 tnew(int col, int row) {
961 /* set screen size */
962 term.row = row, term.col = col;
963 term.line = xmalloc(term.row * sizeof(Line));
964 term.alt = xmalloc(term.row * sizeof(Line));
965 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
966 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
968 for(row = 0; row < term.row; row++) {
969 term.line[row] = xmalloc(term.col * sizeof(Glyph));
970 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
973 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
980 Line* tmp = term.line;
981 term.line = term.alt;
983 term.mode ^= MODE_ALTSCREEN;
988 tscrolldown(int orig, int n) {
992 LIMIT(n, 0, term.bot-orig+1);
994 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
996 for(i = term.bot; i >= orig+n; i--) {
998 term.line[i] = term.line[i-n];
999 term.line[i-n] = temp;
1002 term.dirty[i-n] = 1;
1009 tscrollup(int orig, int n) {
1012 LIMIT(n, 0, term.bot-orig+1);
1014 tclearregion(0, orig, term.col-1, orig+n-1);
1016 for(i = orig; i <= term.bot-n; i++) {
1017 temp = term.line[i];
1018 term.line[i] = term.line[i+n];
1019 term.line[i+n] = temp;
1022 term.dirty[i+n] = 1;
1025 selscroll(orig, -n);
1029 selscroll(int orig, int n) {
1033 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1034 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1038 if(sel.by < term.top) {
1042 if(sel.ey > term.bot) {
1046 sel.b.y = sel.by, sel.b.x = sel.bx;
1047 sel.e.y = sel.ey, sel.e.x = sel.ex;
1052 tnewline(int first_col) {
1055 tscrollup(term.top, 1);
1058 tmoveto(first_col ? 0 : term.c.x, y);
1063 /* int noarg = 1; */
1064 char *p = csiescseq.buf;
1068 csiescseq.priv = 1, p++;
1070 while(p < csiescseq.buf+csiescseq.len) {
1071 while(isdigit(*p)) {
1072 csiescseq.arg[csiescseq.narg] *= 10;
1073 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1075 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1076 csiescseq.narg++, p++;
1078 csiescseq.mode = *p;
1086 tmoveto(int x, int y) {
1087 LIMIT(x, 0, term.col-1);
1088 LIMIT(y, 0, term.row-1);
1089 term.c.state &= ~CURSOR_WRAPNEXT;
1096 term.dirty[term.c.y] = 1;
1097 term.line[term.c.y][term.c.x] = term.c.attr;
1098 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1099 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1103 tclearregion(int x1, int y1, int x2, int y2) {
1107 temp = x1, x1 = x2, x2 = temp;
1109 temp = y1, y1 = y2, y2 = temp;
1111 LIMIT(x1, 0, term.col-1);
1112 LIMIT(x2, 0, term.col-1);
1113 LIMIT(y1, 0, term.row-1);
1114 LIMIT(y2, 0, term.row-1);
1116 for(y = y1; y <= y2; y++) {
1118 for(x = x1; x <= x2; x++)
1119 term.line[y][x].state = 0;
1124 tdeletechar(int n) {
1125 int src = term.c.x + n;
1127 int size = term.col - src;
1129 term.dirty[term.c.y] = 1;
1131 if(src >= term.col) {
1132 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1135 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1136 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1140 tinsertblank(int n) {
1143 int size = term.col - dst;
1145 term.dirty[term.c.y] = 1;
1147 if(dst >= term.col) {
1148 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1151 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1152 tclearregion(src, term.c.y, dst - 1, term.c.y);
1156 tinsertblankline(int n) {
1157 if(term.c.y < term.top || term.c.y > term.bot)
1160 tscrolldown(term.c.y, n);
1164 tdeleteline(int n) {
1165 if(term.c.y < term.top || term.c.y > term.bot)
1168 tscrollup(term.c.y, n);
1172 tsetattr(int *attr, int l) {
1175 for(i = 0; i < l; i++) {
1178 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1179 | ATTR_ITALIC | ATTR_BLINK);
1180 term.c.attr.fg = DefaultFG;
1181 term.c.attr.bg = DefaultBG;
1184 term.c.attr.mode |= ATTR_BOLD;
1186 case 3: /* enter standout (highlight) */
1187 term.c.attr.mode |= ATTR_ITALIC;
1190 term.c.attr.mode |= ATTR_UNDERLINE;
1193 term.c.attr.mode |= ATTR_BLINK;
1196 term.c.attr.mode |= ATTR_REVERSE;
1200 term.c.attr.mode &= ~ATTR_BOLD;
1202 case 23: /* leave standout (highlight) mode */
1203 term.c.attr.mode &= ~ATTR_ITALIC;
1206 term.c.attr.mode &= ~ATTR_UNDERLINE;
1209 term.c.attr.mode &= ~ATTR_BLINK;
1212 term.c.attr.mode &= ~ATTR_REVERSE;
1215 if(i + 2 < l && attr[i + 1] == 5) {
1217 if(BETWEEN(attr[i], 0, 255))
1218 term.c.attr.fg = attr[i];
1220 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1223 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1226 term.c.attr.fg = DefaultFG;
1229 if(i + 2 < l && attr[i + 1] == 5) {
1231 if(BETWEEN(attr[i], 0, 255))
1232 term.c.attr.bg = attr[i];
1234 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1237 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1240 term.c.attr.bg = DefaultBG;
1243 if(BETWEEN(attr[i], 30, 37))
1244 term.c.attr.fg = attr[i] - 30;
1245 else if(BETWEEN(attr[i], 40, 47))
1246 term.c.attr.bg = attr[i] - 40;
1247 else if(BETWEEN(attr[i], 90, 97))
1248 term.c.attr.fg = attr[i] - 90 + 8;
1249 else if(BETWEEN(attr[i], 100, 107))
1250 term.c.attr.bg = attr[i] - 100 + 8;
1252 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1259 tsetscroll(int t, int b) {
1262 LIMIT(t, 0, term.row-1);
1263 LIMIT(b, 0, term.row-1);
1273 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1276 tsetmode(bool priv, bool set, int *args, int narg) {
1279 for(lim = args + narg; args < lim; ++args) {
1283 MODBIT(term.mode, set, MODE_APPKEYPAD);
1285 case 5: /* DECSCNM -- Reverve video */
1287 MODBIT(term.mode,set, MODE_REVERSE);
1288 if(mode != term.mode)
1292 MODBIT(term.mode, set, MODE_WRAP);
1295 MODBIT(term.mode, set, MODE_CRLF);
1297 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1300 MODBIT(term.c.state, !set, CURSOR_HIDE);
1302 case 1000: /* 1000,1002: enable xterm mouse report */
1303 MODBIT(term.mode, set, MODE_MOUSEBTN);
1306 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1308 case 1049: /* = 1047 and 1048 */
1311 if(IS_SET(MODE_ALTSCREEN))
1312 tclearregion(0, 0, term.col-1, term.row-1);
1313 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1314 (!set && IS_SET(MODE_ALTSCREEN))) {
1321 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1325 "erresc: unknown private set/reset mode %d\n",
1332 MODBIT(term.mode, set, MODE_INSERT);
1336 "erresc: unknown set/reset mode %d\n",
1348 switch(csiescseq.mode) {
1351 fprintf(stderr, "erresc: unknown csi ");
1355 case '@': /* ICH -- Insert <n> blank char */
1356 DEFAULT(csiescseq.arg[0], 1);
1357 tinsertblank(csiescseq.arg[0]);
1359 case 'A': /* CUU -- Cursor <n> Up */
1361 DEFAULT(csiescseq.arg[0], 1);
1362 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1364 case 'B': /* CUD -- Cursor <n> Down */
1365 DEFAULT(csiescseq.arg[0], 1);
1366 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1368 case 'C': /* CUF -- Cursor <n> Forward */
1370 DEFAULT(csiescseq.arg[0], 1);
1371 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1373 case 'D': /* CUB -- Cursor <n> Backward */
1374 DEFAULT(csiescseq.arg[0], 1);
1375 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1377 case 'E': /* CNL -- Cursor <n> Down and first col */
1378 DEFAULT(csiescseq.arg[0], 1);
1379 tmoveto(0, term.c.y+csiescseq.arg[0]);
1381 case 'F': /* CPL -- Cursor <n> Up and first col */
1382 DEFAULT(csiescseq.arg[0], 1);
1383 tmoveto(0, term.c.y-csiescseq.arg[0]);
1385 case 'g': /* TBC -- Tabulation clear */
1386 switch (csiescseq.arg[0]) {
1387 case 0: /* clear current tab stop */
1388 term.tabs[term.c.x] = 0;
1390 case 3: /* clear all the tabs */
1391 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1397 case 'G': /* CHA -- Move to <col> */
1399 DEFAULT(csiescseq.arg[0], 1);
1400 tmoveto(csiescseq.arg[0]-1, term.c.y);
1402 case 'H': /* CUP -- Move to <row> <col> */
1404 DEFAULT(csiescseq.arg[0], 1);
1405 DEFAULT(csiescseq.arg[1], 1);
1406 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1408 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1409 DEFAULT(csiescseq.arg[0], 1);
1410 while(csiescseq.arg[0]--)
1413 case 'J': /* ED -- Clear screen */
1415 switch(csiescseq.arg[0]) {
1417 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1418 if(term.c.y < term.row-1)
1419 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1423 tclearregion(0, 0, term.col-1, term.c.y-1);
1424 tclearregion(0, term.c.y, term.c.x, term.c.y);
1427 tclearregion(0, 0, term.col-1, term.row-1);
1433 case 'K': /* EL -- Clear line */
1434 switch(csiescseq.arg[0]) {
1436 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1439 tclearregion(0, term.c.y, term.c.x, term.c.y);
1442 tclearregion(0, term.c.y, term.col-1, term.c.y);
1446 case 'S': /* SU -- Scroll <n> line up */
1447 DEFAULT(csiescseq.arg[0], 1);
1448 tscrollup(term.top, csiescseq.arg[0]);
1450 case 'T': /* SD -- Scroll <n> line down */
1451 DEFAULT(csiescseq.arg[0], 1);
1452 tscrolldown(term.top, csiescseq.arg[0]);
1454 case 'L': /* IL -- Insert <n> blank lines */
1455 DEFAULT(csiescseq.arg[0], 1);
1456 tinsertblankline(csiescseq.arg[0]);
1458 case 'l': /* RM -- Reset Mode */
1459 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1461 case 'M': /* DL -- Delete <n> lines */
1462 DEFAULT(csiescseq.arg[0], 1);
1463 tdeleteline(csiescseq.arg[0]);
1465 case 'X': /* ECH -- Erase <n> char */
1466 DEFAULT(csiescseq.arg[0], 1);
1467 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1469 case 'P': /* DCH -- Delete <n> char */
1470 DEFAULT(csiescseq.arg[0], 1);
1471 tdeletechar(csiescseq.arg[0]);
1473 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1474 DEFAULT(csiescseq.arg[0], 1);
1475 while(csiescseq.arg[0]--)
1478 case 'd': /* VPA -- Move to <row> */
1479 DEFAULT(csiescseq.arg[0], 1);
1480 tmoveto(term.c.x, csiescseq.arg[0]-1);
1482 case 'h': /* SM -- Set terminal mode */
1483 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1485 case 'm': /* SGR -- Terminal attribute (color) */
1486 tsetattr(csiescseq.arg, csiescseq.narg);
1488 case 'r': /* DECSTBM -- Set Scrolling Region */
1492 DEFAULT(csiescseq.arg[0], 1);
1493 DEFAULT(csiescseq.arg[1], term.row);
1494 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1498 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1499 tcursor(CURSOR_SAVE);
1501 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1502 tcursor(CURSOR_LOAD);
1511 for(i = 0; i < csiescseq.len; i++) {
1512 uint c = csiescseq.buf[i] & 0xff;
1513 if(isprint(c)) putchar(c);
1514 else if(c == '\n') printf("(\\n)");
1515 else if(c == '\r') printf("(\\r)");
1516 else if(c == 0x1b) printf("(\\e)");
1517 else printf("(%02x)", c);
1524 memset(&csiescseq, 0, sizeof(csiescseq));
1532 * TODO: make this being useful in case of color palette change.
1538 switch(strescseq.type) {
1539 case ']': /* OSC -- Operating System Command */
1545 * TODO: Handle special chars in string, like umlauts.
1548 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1552 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1554 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1557 fprintf(stderr, "erresc: unknown str ");
1562 case 'k': /* old title set compatibility */
1563 XStoreName(xw.dpy, xw.win, strescseq.buf);
1565 case 'P': /* DSC -- Device Control String */
1566 case '_': /* APC -- Application Program Command */
1567 case '^': /* PM -- Privacy Message */
1569 fprintf(stderr, "erresc: unknown str ");
1579 * TODO: Implement parsing like for CSI when required.
1580 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1588 printf("ESC%c", strescseq.type);
1589 for(i = 0; i < strescseq.len; i++) {
1590 uint c = strescseq.buf[i] & 0xff;
1591 if(isprint(c)) putchar(c);
1592 else if(c == '\n') printf("(\\n)");
1593 else if(c == '\r') printf("(\\r)");
1594 else if(c == 0x1b) printf("(\\e)");
1595 else printf("(%02x)", c);
1602 memset(&strescseq, 0, sizeof(strescseq));
1606 tputtab(bool forward) {
1612 for(++x; x < term.col && !term.tabs[x]; ++x)
1617 for(--x; x > 0 && !term.tabs[x]; --x)
1620 tmoveto(x, term.c.y);
1630 if(term.esc & ESC_START) {
1631 if(term.esc & ESC_CSI) {
1632 csiescseq.buf[csiescseq.len++] = ascii;
1633 if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1635 csiparse(), csihandle();
1637 } else if(term.esc & ESC_STR) {
1640 term.esc = ESC_START | ESC_STR_END;
1642 case '\a': /* backwards compatibility to xterm */
1647 strescseq.buf[strescseq.len++] = ascii;
1648 if(strescseq.len+1 >= STR_BUF_SIZ) {
1653 } else if(term.esc & ESC_STR_END) {
1657 } else if(term.esc & ESC_ALTCHARSET) {
1659 case '0': /* Line drawing crap */
1660 term.c.attr.mode |= ATTR_GFX;
1662 case 'B': /* Back to regular text */
1663 term.c.attr.mode &= ~ATTR_GFX;
1666 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1672 term.esc |= ESC_CSI;
1674 case 'P': /* DCS -- Device Control String */
1675 case '_': /* APC -- Application Program Command */
1676 case '^': /* PM -- Privacy Message */
1677 case ']': /* OSC -- Operating System Command */
1678 case 'k': /* old title set compatibility */
1680 strescseq.type = ascii;
1681 term.esc |= ESC_STR;
1684 term.esc |= ESC_ALTCHARSET;
1686 case 'D': /* IND -- Linefeed */
1687 if(term.c.y == term.bot)
1688 tscrollup(term.top, 1);
1690 tmoveto(term.c.x, term.c.y+1);
1693 case 'E': /* NEL -- Next line */
1694 tnewline(1); /* always go to first col */
1697 case 'H': /* HTS -- Horizontal tab stop */
1698 term.tabs[term.c.x] = 1;
1701 case 'M': /* RI -- Reverse index */
1702 if(term.c.y == term.top)
1703 tscrolldown(term.top, 1);
1705 tmoveto(term.c.x, term.c.y-1);
1708 case 'c': /* RIS -- Reset to inital state */
1713 case '=': /* DECPAM -- Application keypad */
1714 term.mode |= MODE_APPKEYPAD;
1717 case '>': /* DECPNM -- Normal keypad */
1718 term.mode &= ~MODE_APPKEYPAD;
1721 case '7': /* DECSC -- Save Cursor */
1722 tcursor(CURSOR_SAVE);
1725 case '8': /* DECRC -- Restore Cursor */
1726 tcursor(CURSOR_LOAD);
1729 case '\\': /* ST -- Stop */
1733 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1734 (uchar) ascii, isprint(ascii)?ascii:'.');
1739 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1742 case '\0': /* padding character, do nothing */
1748 tmoveto(term.c.x-1, term.c.y);
1751 tmoveto(0, term.c.y);
1756 /* go to first col if the mode is set */
1757 tnewline(IS_SET(MODE_CRLF));
1760 if(!(xw.state & WIN_FOCUSED))
1765 term.esc = ESC_START;
1768 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1769 tnewline(1); /* always go to first col */
1771 if(term.c.x+1 < term.col)
1772 tmoveto(term.c.x+1, term.c.y);
1774 term.c.state |= CURSOR_WRAPNEXT;
1780 tresize(int col, int row) {
1782 int minrow = MIN(row, term.row);
1783 int mincol = MIN(col, term.col);
1784 int slide = term.c.y - row + 1;
1786 if(col < 1 || row < 1)
1789 /* free unneeded rows */
1792 /* slide screen to keep cursor where we expect it -
1793 * tscrollup would work here, but we can optimize to
1794 * memmove because we're freeing the earlier lines */
1795 for(/* i = 0 */; i < slide; i++) {
1799 memmove(term.line, term.line + slide, row * sizeof(Line));
1800 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1802 for(i += row; i < term.row; i++) {
1807 /* resize to new height */
1808 term.line = xrealloc(term.line, row * sizeof(Line));
1809 term.alt = xrealloc(term.alt, row * sizeof(Line));
1810 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1811 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1813 /* resize each row to new width, zero-pad if needed */
1814 for(i = 0; i < minrow; i++) {
1816 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1817 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
1818 for(x = mincol; x < col; x++) {
1819 term.line[i][x].state = 0;
1820 term.alt[i][x].state = 0;
1824 /* allocate any new rows */
1825 for(/* i == minrow */; i < row; i++) {
1827 term.line[i] = xcalloc(col, sizeof(Glyph));
1828 term.alt [i] = xcalloc(col, sizeof(Glyph));
1830 if(col > term.col) {
1831 bool *bp = term.tabs + term.col;
1833 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1834 while(--bp > term.tabs && !*bp)
1836 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1839 /* update terminal size */
1840 term.col = col, term.row = row;
1841 /* make use of the LIMIT in tmoveto */
1842 tmoveto(term.c.x, term.c.y);
1843 /* reset scrolling region */
1844 tsetscroll(0, row-1);
1850 xresize(int col, int row) {
1851 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
1852 xw.th = MAX(1, 2*BORDER + row * xw.ch);
1854 XftDrawChange(xw.xft_draw, xw.buf);
1860 XRenderColor xft_color = { .alpha = 0 };
1861 ulong white = WhitePixel(xw.dpy, xw.scr);
1863 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1864 for(i = 0; i < LEN(colorname); i++) {
1867 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
1869 fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1871 dc.col[i] = dc.xft_col[i].pixel;
1874 /* load colors [16-255] ; same colors as xterm */
1875 for(i = 16, r = 0; r < 6; r++)
1876 for(g = 0; g < 6; g++)
1877 for(b = 0; b < 6; b++) {
1878 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1879 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1880 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1881 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1883 fprintf(stderr, "Could not allocate color %d\n", i);
1885 dc.col[i] = dc.xft_col[i].pixel;
1889 for(r = 0; r < 24; r++, i++) {
1890 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
1891 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1893 fprintf(stderr, "Could not allocate color %d\n", i);
1895 dc.col[i] = dc.xft_col[i].pixel;
1900 xclear(int x1, int y1, int x2, int y2) {
1901 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
1902 XFillRectangle(xw.dpy, xw.buf, dc.gc,
1903 BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
1904 (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1909 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
1910 XWMHints wm = {.flags = InputHint, .input = 1};
1911 XSizeHints *sizeh = NULL;
1913 sizeh = XAllocSizeHints();
1914 if(xw.isfixed == False) {
1915 sizeh->flags = PSize | PResizeInc | PBaseSize;
1916 sizeh->height = xw.h;
1917 sizeh->width = xw.w;
1918 sizeh->height_inc = xw.ch;
1919 sizeh->width_inc = xw.cw;
1920 sizeh->base_height = 2*BORDER;
1921 sizeh->base_width = 2*BORDER;
1923 sizeh->flags = PMaxSize | PMinSize;
1924 sizeh->min_width = sizeh->max_width = xw.fw;
1925 sizeh->min_height = sizeh->max_height = xw.fh;
1928 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
1933 xinitfont(Font *f, char *fontstr) {
1934 f->xft_set = XftFontOpenName(xw.dpy, xw.scr, fontstr);
1937 die("st: can't open font %s.\n", fontstr);
1939 f->ascent = f->xft_set->ascent;
1940 f->descent = f->xft_set->descent;
1942 f->rbearing = f->xft_set->max_advance_width;
1946 initfonts(char *fontstr, char *bfontstr, char *ifontstr, char *ibfontstr) {
1947 xinitfont(&dc.font, fontstr);
1948 xinitfont(&dc.bfont, bfontstr);
1949 xinitfont(&dc.ifont, ifontstr);
1950 xinitfont(&dc.ibfont, ibfontstr);
1955 XSetWindowAttributes attrs;
1958 int sw, sh, major, minor;
1960 if(!(xw.dpy = XOpenDisplay(NULL)))
1961 die("Can't open display\n");
1962 xw.scr = XDefaultScreen(xw.dpy);
1963 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1966 initfonts(FONT, BOLDFONT, ITALICFONT, ITALICBOLDFONT);
1968 /* XXX: Assuming same size for bold font */
1969 xw.cw = dc.font.rbearing - dc.font.lbearing;
1970 xw.ch = dc.font.ascent + dc.font.descent;
1973 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1976 /* adjust fixed window geometry */
1978 sw = DisplayWidth(xw.dpy, xw.scr);
1979 sh = DisplayHeight(xw.dpy, xw.scr);
1981 xw.fx = sw + xw.fx - xw.fw - 1;
1983 xw.fy = sh + xw.fy - xw.fh - 1;
1988 /* window - default size */
1989 xw.h = 2*BORDER + term.row * xw.ch;
1990 xw.w = 2*BORDER + term.col * xw.cw;
1995 attrs.background_pixel = dc.col[DefaultBG];
1996 attrs.border_pixel = dc.col[DefaultBG];
1997 attrs.bit_gravity = NorthWestGravity;
1998 attrs.event_mask = FocusChangeMask | KeyPressMask
1999 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2000 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2001 attrs.colormap = xw.cmap;
2003 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2004 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2005 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2007 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2011 /* double buffering */
2012 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2013 die("Xdbe extension is not present\n");
2014 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2016 /* Xft rendering context */
2017 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2020 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2021 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2022 | XIMStatusNothing, XNClientWindow, xw.win,
2023 XNFocusWindow, xw.win, NULL);
2025 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2027 /* white cursor, black outline */
2028 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2029 XDefineCursor(xw.dpy, xw.win, cursor);
2030 XRecolorCursor(xw.dpy, cursor,
2031 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2032 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2034 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2037 XMapWindow(xw.dpy, xw.win);
2043 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2044 int fg = base.fg, bg = base.bg, temp;
2045 int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
2046 Font *font = &dc.font;
2050 /* only switch default fg/bg if term is in RV mode */
2051 if(IS_SET(MODE_REVERSE)) {
2058 if(base.mode & ATTR_REVERSE)
2059 temp = fg, fg = bg, bg = temp;
2061 if(base.mode & ATTR_BOLD) {
2066 if(base.mode & ATTR_ITALIC)
2068 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2071 XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
2072 XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
2074 if(base.mode & ATTR_GFX) {
2075 for(i = 0; i < bytelen; i++) {
2076 char c = gfx[(uint)s[i] % 256];
2079 else if(s[i] > 0x5f)
2084 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen, &extents);
2085 width = extents.xOff;
2086 XftDrawRect(xw.xft_draw, &dc.xft_col[bg], winx, winy - font->ascent, width, xw.ch);
2087 XftDrawStringUtf8(xw.xft_draw, &dc.xft_col[fg], font->xft_set, winx, winy, (FcChar8 *)s, bytelen);
2089 if(base.mode & ATTR_UNDERLINE)
2090 XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
2095 static int oldx = 0;
2096 static int oldy = 0;
2098 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2100 LIMIT(oldx, 0, term.col-1);
2101 LIMIT(oldy, 0, term.row-1);
2103 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2104 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2106 /* remove the old cursor */
2107 if(term.line[oldy][oldx].state & GLYPH_SET) {
2108 sl = utf8size(term.line[oldy][oldx].c);
2109 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2111 xclear(oldx, oldy, oldx, oldy);
2113 /* draw the new one */
2114 if(!(term.c.state & CURSOR_HIDE)) {
2115 if(!(xw.state & WIN_FOCUSED))
2118 if(IS_SET(MODE_REVERSE))
2119 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2122 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2123 oldx = term.c.x, oldy = term.c.y;
2129 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2134 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2136 xclear(0, 0, xw.w, xw.h);
2139 XSync(xw.dpy, False); /* necessary for a good tput flash */
2140 nanosleep(&tv, NULL);
2145 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2147 drawregion(0, 0, term.col, term.row);
2148 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2152 drawregion(int x1, int y1, int x2, int y2) {
2153 int ic, ib, x, y, ox, sl;
2155 char buf[DRAW_BUF_SIZ];
2156 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2158 if((sel.alt && !alt) || (!sel.alt && alt))
2160 if(!(xw.state & WIN_VISIBLE))
2163 for(y = y1; y < y2; y++) {
2166 xclear(0, y, term.col, y);
2168 base = term.line[y][0];
2170 for(x = x1; x < x2; x++) {
2171 new = term.line[y][x];
2172 if(ena_sel && *(new.c) && selected(x, y))
2173 new.mode ^= ATTR_REVERSE;
2174 if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2175 ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2176 xdraws(buf, base, ox, y, ic, ib);
2179 if(new.state & GLYPH_SET) {
2184 sl = utf8size(new.c);
2185 memcpy(buf+ib, new.c, sl);
2191 xdraws(buf, base, ox, y, ic, ib);
2197 expose(XEvent *ev) {
2198 XExposeEvent *e = &ev->xexpose;
2199 if(xw.state & WIN_REDRAW) {
2201 xw.state &= ~WIN_REDRAW;
2206 visibility(XEvent *ev) {
2207 XVisibilityEvent *e = &ev->xvisibility;
2208 if(e->state == VisibilityFullyObscured)
2209 xw.state &= ~WIN_VISIBLE;
2210 else if(!(xw.state & WIN_VISIBLE))
2211 /* need a full redraw for next Expose, not just a buf copy */
2212 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2217 xw.state &= ~WIN_VISIBLE;
2221 xseturgency(int add) {
2222 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2223 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2224 XSetWMHints(xw.dpy, xw.win, h);
2230 if(ev->type == FocusIn) {
2231 xw.state |= WIN_FOCUSED;
2234 xw.state &= ~WIN_FOCUSED;
2238 kmap(KeySym k, uint state) {
2241 for(i = 0; i < LEN(key); i++) {
2242 uint mask = key[i].mask;
2243 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2244 return (char*)key[i].s;
2250 kpress(XEvent *ev) {
2251 XKeyEvent *e = &ev->xkey;
2260 meta = e->state & Mod1Mask;
2261 shift = e->state & ShiftMask;
2262 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2264 /* 1. custom keys from config.h */
2265 if((customkey = kmap(ksym, e->state)))
2266 ttywrite(customkey, strlen(customkey));
2267 /* 2. hardcoded (overrides X lookup) */
2274 /* XXX: shift up/down doesn't work */
2275 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2283 if(IS_SET(MODE_CRLF))
2284 ttywrite("\r\n", 2);
2291 if(meta && len == 1)
2292 ttywrite("\033", 1);
2300 cmessage(XEvent *e) {
2302 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2303 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2304 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2305 xw.state |= WIN_FOCUSED;
2307 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2308 xw.state &= ~WIN_FOCUSED;
2317 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2320 xw.w = e->xconfigure.width;
2321 xw.h = e->xconfigure.height;
2322 col = (xw.w - 2*BORDER) / xw.cw;
2323 row = (xw.h - 2*BORDER) / xw.ch;
2324 if(col == term.col && row == term.row)
2327 xclear(0, 0, xw.w, xw.h);
2330 ttyresize(col, row);
2337 int xfd = XConnectionNumber(xw.dpy), i;
2338 struct timeval drawtimeout, *tv = NULL;
2342 FD_SET(cmdfd, &rfd);
2344 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2347 die("select failed: %s\n", SERRNO);
2351 * Stop after a certain number of reads so the user does not
2352 * feel like the system is stuttering.
2354 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2358 * Just wait a bit so it isn't disturbing the
2359 * user and the system is able to write something.
2361 drawtimeout.tv_sec = 0;
2362 drawtimeout.tv_usec = 5;
2369 while(XPending(xw.dpy)) {
2370 XNextEvent(xw.dpy, &ev);
2371 if(XFilterEvent(&ev, xw.win))
2373 if(handler[ev.type])
2374 (handler[ev.type])(&ev);
2383 main(int argc, char *argv[]) {
2384 int i, bitm, xr, yr;
2387 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2390 for(i = 1; i < argc; i++) {
2391 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2393 if(++i < argc) opt_title = argv[i];
2396 if(++i < argc) opt_class = argv[i];
2399 if(++i < argc) opt_embed = argv[i];
2402 if(++i < argc) opt_io = argv[i];
2405 /* eat every remaining arguments */
2406 if(++i < argc) opt_cmd = &argv[i];
2412 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2417 if(bitm & WidthValue)
2419 if(bitm & HeightValue)
2421 if(bitm & XNegative && xw.fx == 0)
2423 if(bitm & XNegative && xw.fy == 0)
2426 if(xw.fh != 0 && xw.fw != 0)
2436 setlocale(LC_CTYPE, "");