1 /* See LICENSE for licence details. */
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
24 #include <X11/Xatom.h>
26 #include <X11/Xutil.h>
27 #include <X11/cursorfont.h>
28 #include <X11/keysym.h>
29 #include <X11/Xft/Xft.h>
30 #include <X11/XKBlib.h>
31 #include <fontconfig/fontconfig.h>
43 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
45 #elif defined(__FreeBSD__) || defined(__DragonFly__)
51 #define XEMBED_FOCUS_IN 4
52 #define XEMBED_FOCUS_OUT 5
55 #define UTF_INVALID 0xFFFD
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)
67 #define MIN(a, b) ((a) < (b) ? (a) : (b))
68 #define MAX(a, b) ((a) < (b) ? (b) : (a))
69 #define LEN(a) (sizeof(a) / sizeof(a)[0])
70 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
71 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
72 #define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == '\177')
73 #define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
74 #define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
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_nsec-t2.tv_nsec)/1E6)
79 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
81 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
82 #define IS_TRUECOL(x) (1 << 24 & (x))
83 #define TRUERED(x) (((x) & 0xff0000) >> 8)
84 #define TRUEGREEN(x) (((x) & 0xff00))
85 #define TRUEBLUE(x) (((x) & 0xff) << 8)
86 #define TLINE(y) ((y) < term.scr ? term.hist[((y) + term.histi - term.scr \
87 + histsize + 1) % histsize] : term.line[(y) - term.scr])
90 enum glyph_attribute {
95 ATTR_UNDERLINE = 1 << 3,
97 ATTR_REVERSE = 1 << 5,
98 ATTR_INVISIBLE = 1 << 6,
102 ATTR_WDUMMY = 1 << 10,
105 enum cursor_movement {
118 MODE_INSERT = 1 << 1,
119 MODE_APPKEYPAD = 1 << 2,
120 MODE_ALTSCREEN = 1 << 3,
122 MODE_MOUSEBTN = 1 << 5,
123 MODE_MOUSEMOTION = 1 << 6,
124 MODE_REVERSE = 1 << 7,
125 MODE_KBDLOCK = 1 << 8,
128 MODE_APPCURSOR = 1 << 11,
129 MODE_MOUSESGR = 1 << 12,
131 MODE_BLINK = 1 << 14,
132 MODE_FBLINK = 1 << 15,
133 MODE_FOCUS = 1 << 16,
134 MODE_MOUSEX10 = 1 << 17,
135 MODE_MOUSEMANY = 1 << 18,
136 MODE_BRCKTPASTE = 1 << 19,
137 MODE_PRINT = 1 << 20,
138 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
155 ESC_STR = 4, /* DCS, OSC, PM, APC */
157 ESC_STR_END = 16, /* a final string was encountered */
158 ESC_TEST = 32, /* Enter in test mode */
167 enum selection_type {
172 enum selection_snap {
177 typedef unsigned char uchar;
178 typedef unsigned int uint;
179 typedef unsigned long ulong;
180 typedef unsigned short ushort;
182 typedef XftDraw *Draw;
183 typedef XftColor Color;
186 char c[UTF_SIZ]; /* character code */
187 ushort mode; /* attribute flags */
188 uint32_t fg; /* foreground */
189 uint32_t bg; /* background */
195 Glyph attr; /* current char attributes */
201 /* CSI Escape sequence structs */
202 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
204 char buf[ESC_BUF_SIZ]; /* raw string */
205 int len; /* raw string length */
207 int arg[ESC_ARG_SIZ];
208 int narg; /* nb of args */
212 /* STR Escape sequence structs */
213 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
215 char type; /* ESC type ... */
216 char buf[STR_BUF_SIZ]; /* raw string */
217 int len; /* raw string length */
218 char *args[STR_ARG_SIZ];
219 int narg; /* nb of args */
222 /* Internal representation of the screen */
224 int row; /* nb row */
225 int col; /* nb col */
226 Line *line; /* screen */
227 Line *alt; /* alternate screen */
228 Line *hist; /* history buffer */
229 int histi; /* history index */
230 int scr; /* scroll back */
231 bool *dirty; /* dirtyness of lines */
232 TCursor c; /* cursor */
233 int top; /* top scroll limit */
234 int bot; /* bottom scroll limit */
235 int mode; /* terminal mode flags */
236 int esc; /* escape state flags */
237 char trantbl[4]; /* charset table translation */
238 int charset; /* current charset */
239 int icharset; /* selected charset for sequence */
240 bool numlock; /* lock numbers in keyboard */
244 /* Purely graphic info */
250 Atom xembed, wmdeletewin, netwmname, netwmpid;
255 XSetWindowAttributes attrs;
257 bool isfixed; /* is fixed geometry? */
258 int l, t; /* left and top offset */
259 int gm; /* geometry mask */
260 int tw, th; /* tty width and height */
261 int w, h; /* window width and height */
262 int ch; /* char height */
263 int cw; /* char width */
264 char state; /* focus, redraw, visible */
265 int cursor; /* cursor style */
278 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
279 signed char appkey; /* application keypad */
280 signed char appcursor; /* application cursor */
281 signed char crlf; /* crlf mode */
289 * Selection variables:
290 * nb – normalized coordinates of the beginning of the selection
291 * ne – normalized coordinates of the end of the selection
292 * ob – original coordinates of the beginning of the selection
293 * oe – original coordinates of the end of the selection
299 char *primary, *clipboard;
302 struct timespec tclick1;
303 struct timespec tclick2;
316 void (*func)(const Arg *);
320 /* function definitions used in config.h */
321 static void clipcopy(const Arg *);
322 static void clippaste(const Arg *);
323 static void kscrolldown(const Arg *);
324 static void kscrollup(const Arg *);
325 static void numlock(const Arg *);
326 static void selpaste(const Arg *);
327 static void xzoom(const Arg *);
328 static void xzoomabs(const Arg *);
329 static void xzoomreset(const Arg *);
330 static void printsel(const Arg *);
331 static void printscreen(const Arg *) ;
332 static void toggleprinter(const Arg *);
334 /* Config.h for applying patches and the configuration. */
350 /* Drawing Context */
352 Color col[MAX(LEN(colorname), 256)];
353 Font font, bfont, ifont, ibfont;
357 static void die(const char *, ...);
358 static void draw(void);
359 static void redraw(void);
360 static void drawregion(int, int, int, int);
361 static void execsh(void);
362 static void sigchld(int);
363 static void run(void);
365 static void csidump(void);
366 static void csihandle(void);
367 static void csiparse(void);
368 static void csireset(void);
369 static int eschandle(uchar ascii);
370 static void strdump(void);
371 static void strhandle(void);
372 static void strparse(void);
373 static void strreset(void);
375 static int tattrset(int);
376 static void tprinter(char *, size_t);
377 static void tdumpsel(void);
378 static void tdumpline(int);
379 static void tdump(void);
380 static void tclearregion(int, int, int, int);
381 static void tcursor(int);
382 static void tdeletechar(int);
383 static void tdeleteline(int);
384 static void tinsertblank(int);
385 static void tinsertblankline(int);
386 static int tlinelen(int);
387 static void tmoveto(int, int);
388 static void tmoveato(int, int);
389 static void tnew(int, int);
390 static void tnewline(int);
391 static void tputtab(int);
392 static void tputc(char *, int);
393 static void treset(void);
394 static void tresize(int, int);
395 static void tscrollup(int, int, bool);
396 static void tscrolldown(int, int, bool);
397 static void tsetattr(int *, int);
398 static void tsetchar(char *, Glyph *, int, int);
399 static void tsetscroll(int, int);
400 static void tswapscreen(void);
401 static void tsetdirt(int, int);
402 static void tsetdirtattr(int);
403 static void tsetmode(bool, bool, int *, int);
404 static void tfulldirt(void);
405 static void techo(char *, int);
406 static void tcontrolcode(uchar );
407 static void tdectest(char );
408 static int32_t tdefcolor(int *, int *, int);
409 static void tdeftran(char);
410 static inline bool match(uint, uint);
411 static void ttynew(void);
412 static void ttyread(void);
413 static void ttyresize(void);
414 static void ttysend(char *, size_t);
415 static void ttywrite(const char *, size_t);
416 static void tstrsequence(uchar c);
418 static void xdraws(char *, Glyph, int, int, int, int);
419 static void xhints(void);
420 static void xclear(int, int, int, int);
421 static void xdrawcursor(void);
422 static void xinit(void);
423 static void xloadcols(void);
424 static int xsetcolorname(int, const char *);
425 static int xgeommasktogravity(int);
426 static int xloadfont(Font *, FcPattern *);
427 static void xloadfonts(char *, double);
428 static int xloadfontset(Font *);
429 static void xsettitle(char *);
430 static void xresettitle(void);
431 static void xsetpointermotion(int);
432 static void xseturgency(int);
433 static void xsetsel(char *);
434 static void xtermclear(int, int, int, int);
435 static void xunloadfont(Font *);
436 static void xunloadfonts(void);
437 static void xresize(int, int);
439 static void expose(XEvent *);
440 static void visibility(XEvent *);
441 static void unmap(XEvent *);
442 static char *kmap(KeySym, uint);
443 static void kpress(XEvent *);
444 static void cmessage(XEvent *);
445 static void cresize(int, int);
446 static void resize(XEvent *);
447 static void focus(XEvent *);
448 static void brelease(XEvent *);
449 static void bpress(XEvent *);
450 static void bmotion(XEvent *);
451 static void selnotify(XEvent *);
452 static void selclear(XEvent *);
453 static void selrequest(XEvent *);
455 static void selinit(void);
456 static void selnormalize(void);
457 static inline bool selected(int, int);
458 static char *getsel(void);
459 static void selcopy(void);
460 static void selscroll(int, int);
461 static void selsnap(int, int *, int *, int);
462 static void getbuttoninfo(XEvent *);
463 static void mousereport(XEvent *);
465 static size_t utf8decode(char *, long *, size_t);
466 static long utf8decodebyte(char, size_t *);
467 static size_t utf8encode(long, char *, size_t);
468 static char utf8encodebyte(long, size_t);
469 static size_t utf8len(char *);
470 static size_t utf8validate(long *, size_t);
472 static ssize_t xwrite(int, const char *, size_t);
473 static void *xmalloc(size_t);
474 static void *xrealloc(void *, size_t);
475 static char *xstrdup(char *);
477 static void usage(void);
479 static void (*handler[LASTEvent])(XEvent *) = {
481 [ClientMessage] = cmessage,
482 [ConfigureNotify] = resize,
483 [VisibilityNotify] = visibility,
484 [UnmapNotify] = unmap,
488 [MotionNotify] = bmotion,
489 [ButtonPress] = bpress,
490 [ButtonRelease] = brelease,
492 * Uncomment if you want the selection to disappear when you select something
493 * different in another window.
495 /* [SelectionClear] = selclear, */
496 [SelectionNotify] = selnotify,
497 [SelectionRequest] = selrequest,
504 static CSIEscape csiescseq;
505 static STREscape strescseq;
508 static Selection sel;
509 static int iofd = STDOUT_FILENO;
510 static char **opt_cmd = NULL;
511 static char *opt_io = NULL;
512 static char *opt_title = NULL;
513 static char *opt_embed = NULL;
514 static char *opt_class = NULL;
515 static char *opt_font = NULL;
516 static int oldbutton = 3; /* button event on startup: 3 = release */
518 static char *usedfont = NULL;
519 static double usedfontsize = 0;
520 static double defaultfontsize = 0;
522 static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
523 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
524 static long utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
525 static long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
527 /* Font Ring Cache */
541 /* Fontcache is an array now. A new font will be appended to the array. */
542 static Fontcache frc[16];
543 static int frclen = 0;
546 xwrite(int fd, const char *s, size_t len) {
550 ssize_t r = write(fd, s, len);
560 xmalloc(size_t len) {
561 void *p = malloc(len);
564 die("Out of memory\n");
570 xrealloc(void *p, size_t len) {
571 if((p = realloc(p, len)) == NULL)
572 die("Out of memory\n");
579 if((s = strdup(s)) == NULL)
580 die("Out of memory\n");
586 utf8decode(char *c, long *u, size_t clen) {
587 size_t i, j, len, type;
593 udecoded = utf8decodebyte(c[0], &len);
594 if(!BETWEEN(len, 1, UTF_SIZ))
596 for(i = 1, j = 1; i < clen && j < len; ++i, ++j) {
597 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
604 utf8validate(u, len);
609 utf8decodebyte(char c, size_t *i) {
610 for(*i = 0; *i < LEN(utfmask); ++(*i))
611 if(((uchar)c & utfmask[*i]) == utfbyte[*i])
612 return (uchar)c & ~utfmask[*i];
617 utf8encode(long u, char *c, size_t clen) {
620 len = utf8validate(&u, 0);
623 for(i = len - 1; i != 0; --i) {
624 c[i] = utf8encodebyte(u, 0);
627 c[0] = utf8encodebyte(u, len);
632 utf8encodebyte(long u, size_t i) {
633 return utfbyte[i] | (u & ~utfmask[i]);
638 return utf8decode(c, &(long){0}, UTF_SIZ);
642 utf8validate(long *u, size_t i) {
643 if(!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
645 for(i = 1; *u > utfmax[i]; ++i)
652 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
653 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
657 sel.clipboard = NULL;
658 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
659 if(sel.xtarget == None)
660 sel.xtarget = XA_STRING;
668 return LIMIT(x, 0, term.col-1);
676 return LIMIT(y, 0, term.row-1);
679 static int tlinelen(int y) {
682 if(TLINE(y)[i - 1].mode & ATTR_WRAP)
685 while(i > 0 && TLINE(y)[i - 1].c[0] == ' ')
695 if(sel.ob.y == sel.oe.y || sel.type == SEL_RECTANGULAR) {
696 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
697 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
699 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
700 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
702 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
703 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
705 selsnap(sel.snap, &sel.nb.x, &sel.nb.y, -1);
706 selsnap(sel.snap, &sel.ne.x, &sel.ne.y, +1);
708 /* expand selection over line breaks */
709 if (sel.type == SEL_RECTANGULAR)
711 i = tlinelen(sel.nb.y);
714 if (tlinelen(sel.ne.y) <= sel.ne.x)
715 sel.ne.x = term.col - 1;
719 selected(int x, int y) {
720 if(sel.type == SEL_RECTANGULAR)
721 return BETWEEN(y, sel.nb.y, sel.ne.y)
722 && BETWEEN(x, sel.nb.x, sel.ne.x);
724 return BETWEEN(y, sel.nb.y, sel.ne.y)
725 && (y != sel.nb.y || x >= sel.nb.x)
726 && (y != sel.ne.y || x <= sel.ne.x);
730 selsnap(int mode, int *x, int *y, int direction) {
731 int newx, newy, xt, yt;
732 bool delim, prevdelim;
738 * Snap around if the word wraps around at the end or
739 * beginning of a line.
741 prevgp = &TLINE(*y)[*x];
742 prevdelim = strchr(worddelimiters, prevgp->c[0]) != NULL;
744 newx = *x + direction;
746 if(!BETWEEN(newx, 0, term.col - 1)) {
748 newx = (newx + term.col) % term.col;
749 if (!BETWEEN(newy, 0, term.row - 1))
755 yt = newy, xt = newx;
756 if(!(TLINE(yt)[xt].mode & ATTR_WRAP))
760 if (newx >= tlinelen(newy))
763 gp = &TLINE(newy)[newx];
764 delim = strchr(worddelimiters, gp->c[0]) != NULL;
765 if(!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
766 || (delim && gp->c[0] != prevgp->c[0])))
777 * Snap around if the the previous line or the current one
778 * has set ATTR_WRAP at its end. Then the whole next or
779 * previous line will be selected.
781 *x = (direction < 0) ? 0 : term.col - 1;
782 if(direction < 0 && *y > 0) {
783 for(; *y > 0; *y += direction) {
784 if(!(TLINE(*y-1)[term.col-1].mode
789 } else if(direction > 0 && *y < term.row-1) {
790 for(; *y < term.row; *y += direction) {
791 if(!(TLINE(*y)[term.col-1].mode
802 getbuttoninfo(XEvent *e) {
804 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
806 sel.alt = IS_SET(MODE_ALTSCREEN);
808 sel.oe.x = x2col(e->xbutton.x);
809 sel.oe.y = y2row(e->xbutton.y);
812 sel.type = SEL_REGULAR;
813 for(type = 1; type < LEN(selmasks); ++type) {
814 if(match(selmasks[type], state)) {
822 mousereport(XEvent *e) {
824 // int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
825 // button = e->xbutton.button, state = e->xbutton.state,
828 // static int ox, oy;
831 // if(e->xbutton.type == MotionNotify) {
832 // if(x == ox && y == oy)
834 // if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
836 // /* MOUSE_MOTION: no reporting if no button is pressed */
837 // if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
840 // button = oldbutton + 32;
844 // if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
847 // button -= Button1;
851 // if(e->xbutton.type == ButtonPress) {
852 // oldbutton = button;
855 // } else if(e->xbutton.type == ButtonRelease) {
857 // /* MODE_MOUSEX10: no button release reporting */
858 // if(IS_SET(MODE_MOUSEX10))
860 // if (button == 64 || button == 65)
865 // if(!IS_SET(MODE_MOUSEX10)) {
866 // button += (state & ShiftMask ? 4 : 0)
867 // + (state & Mod4Mask ? 8 : 0)
868 // + (state & ControlMask ? 16 : 0);
872 // if(IS_SET(MODE_MOUSESGR)) {
873 // len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
875 // e->xbutton.type == ButtonRelease ? 'm' : 'M');
876 // } else if(x < 223 && y < 223) {
877 // len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
878 // 32+button, 32+x+1, 32+y+1);
883 // ttywrite(buf, len);
891 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
896 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
897 if(e->xbutton.button == mk->b
898 && match(mk->mask, e->xbutton.state)) {
899 ttysend(mk->s, strlen(mk->s));
904 if(e->xbutton.button == Button1) {
905 clock_gettime(CLOCK_MONOTONIC, &now);
907 /* Clear previous selection, logically and visually. */
910 sel.type = SEL_REGULAR;
911 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
912 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
915 * If the user clicks below predefined timeouts specific
916 * snapping behaviour is exposed.
918 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
919 sel.snap = SNAP_LINE;
920 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
921 sel.snap = SNAP_WORD;
928 * Draw selection, unless it's regular and we don't want to
929 * make clicks visible
933 tsetdirt(sel.nb.y, sel.ne.y);
935 sel.tclick2 = sel.tclick1;
943 int y, bufsize, size, lastx, linelen;
949 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
950 ptr = str = xmalloc(bufsize);
952 /* append every set & selected glyph to the selection */
953 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
954 linelen = tlinelen(y);
956 if(sel.type == SEL_RECTANGULAR) {
957 gp = &TLINE(y)[sel.nb.x];
960 gp = &TLINE(y)[sel.nb.y == y ? sel.nb.x : 0];
961 lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
963 last = &TLINE(y)[MIN(lastx, linelen-1)];
964 while(last >= gp && last->c[0] == ' ')
967 for( ; gp <= last; ++gp) {
968 if(gp->mode & ATTR_WDUMMY)
971 size = utf8len(gp->c);
972 memcpy(ptr, gp->c, size);
977 * Copy and pasting of line endings is inconsistent
978 * in the inconsistent terminal and GUI world.
979 * The best solution seems like to produce '\n' when
980 * something is copied from st and convert '\n' to
981 * '\r', when something to be pasted is received by
983 * FIXME: Fix the computer world.
985 if((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
998 selnotify(XEvent *e) {
999 ulong nitems, ofs, rem;
1001 uchar *data, *last, *repl;
1003 XSelectionEvent *xsev;
1006 xsev = (XSelectionEvent *)e;
1007 if (xsev->property == None)
1010 if(XGetWindowProperty(xw.dpy, xw.win, xsev->property, ofs,
1011 BUFSIZ/4, False, AnyPropertyType,
1012 &type, &format, &nitems, &rem,
1014 fprintf(stderr, "Clipboard allocation failed\n");
1019 * As seen in getsel:
1020 * Line endings are inconsistent in the terminal and GUI world
1021 * copy and pasting. When receiving some selection data,
1022 * replace all '\n' with '\r'.
1023 * FIXME: Fix the computer world.
1026 last = data + nitems * format / 8;
1027 while((repl = memchr(repl, '\n', last - repl))) {
1031 if(IS_SET(MODE_BRCKTPASTE))
1032 ttywrite("\033[200~", 6);
1033 ttysend((char *)data, nitems * format / 8);
1034 if(IS_SET(MODE_BRCKTPASTE))
1035 ttywrite("\033[201~", 6);
1037 /* number of 32-bit chunks returned */
1038 ofs += nitems * format / 32;
1043 selpaste(const Arg *dummy) {
1044 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1045 xw.win, CurrentTime);
1049 clipcopy(const Arg *dummy) {
1052 if(sel.clipboard != NULL)
1053 free(sel.clipboard);
1055 if(sel.primary != NULL) {
1056 sel.clipboard = xstrdup(sel.primary);
1057 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1058 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1063 clippaste(const Arg *dummy) {
1066 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1067 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1068 xw.win, CurrentTime);
1072 selclear(XEvent *e) {
1076 tsetdirt(sel.nb.y, sel.ne.y);
1080 selrequest(XEvent *e) {
1081 XSelectionRequestEvent *xsre;
1082 XSelectionEvent xev;
1083 Atom xa_targets, string, clipboard;
1086 xsre = (XSelectionRequestEvent *) e;
1087 xev.type = SelectionNotify;
1088 xev.requestor = xsre->requestor;
1089 xev.selection = xsre->selection;
1090 xev.target = xsre->target;
1091 xev.time = xsre->time;
1093 xev.property = None;
1095 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1096 if(xsre->target == xa_targets) {
1097 /* respond with the supported type */
1098 string = sel.xtarget;
1099 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1100 XA_ATOM, 32, PropModeReplace,
1101 (uchar *) &string, 1);
1102 xev.property = xsre->property;
1103 } else if(xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1105 * xith XA_STRING non ascii characters may be incorrect in the
1106 * requestor. It is not our problem, use utf8.
1108 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1109 if(xsre->selection == XA_PRIMARY) {
1110 seltext = sel.primary;
1111 } else if(xsre->selection == clipboard) {
1112 seltext = sel.clipboard;
1115 "Unhandled clipboard selection 0x%lx\n",
1119 if(seltext != NULL) {
1120 XChangeProperty(xsre->display, xsre->requestor,
1121 xsre->property, xsre->target,
1123 (uchar *)seltext, strlen(seltext));
1124 xev.property = xsre->property;
1128 /* all done, send a notification to the listener */
1129 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1130 fprintf(stderr, "Error sending SelectionNotify event\n");
1134 xsetsel(char *str) {
1138 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1142 brelease(XEvent *e) {
1143 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1148 if(e->xbutton.button == Button2) {
1150 } else if(e->xbutton.button == Button1) {
1158 tsetdirt(sel.nb.y, sel.ne.y);
1163 bmotion(XEvent *e) {
1164 int oldey, oldex, oldsby, oldsey;
1166 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1181 if(oldey != sel.oe.y || oldex != sel.oe.x)
1182 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1186 die(const char *errstr, ...) {
1189 va_start(ap, errstr);
1190 vfprintf(stderr, errstr, ap);
1197 char **args, *sh, *prog;
1198 const struct passwd *pw;
1199 char buf[sizeof(long) * 8 + 1];
1202 if((pw = getpwuid(getuid())) == NULL) {
1204 die("getpwuid:%s\n", strerror(errno));
1206 die("who are you?\n");
1209 if (!(sh = getenv("SHELL"))) {
1210 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1219 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1221 snprintf(buf, sizeof(buf), "%lu", xw.win);
1223 unsetenv("COLUMNS");
1225 unsetenv("TERMCAP");
1226 setenv("LOGNAME", pw->pw_name, 1);
1227 setenv("USER", pw->pw_name, 1);
1228 setenv("SHELL", sh, 1);
1229 setenv("HOME", pw->pw_dir, 1);
1230 setenv("TERM", termname, 1);
1231 setenv("WINDOWID", buf, 1);
1233 signal(SIGCHLD, SIG_DFL);
1234 signal(SIGHUP, SIG_DFL);
1235 signal(SIGINT, SIG_DFL);
1236 signal(SIGQUIT, SIG_DFL);
1237 signal(SIGTERM, SIG_DFL);
1238 signal(SIGALRM, SIG_DFL);
1241 _exit(EXIT_FAILURE);
1248 if(waitpid(pid, &stat, 0) < 0)
1249 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1251 ret = WIFEXITED(stat) ? WEXITSTATUS(stat) : EXIT_FAILURE;
1252 if (ret != EXIT_SUCCESS)
1253 die("child finished with error '%d'\n", stat);
1260 struct winsize w = {term.row, term.col, 0, 0};
1262 /* seems to work fine on linux, openbsd and freebsd */
1263 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1264 die("openpty failed: %s\n", strerror(errno));
1266 switch(pid = fork()) {
1268 die("fork failed\n");
1271 setsid(); /* create a new process group */
1272 dup2(s, STDIN_FILENO);
1273 dup2(s, STDOUT_FILENO);
1274 dup2(s, STDERR_FILENO);
1275 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1276 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1284 signal(SIGCHLD, sigchld);
1286 term.mode |= MODE_PRINT;
1287 iofd = (!strcmp(opt_io, "-")) ?
1289 open(opt_io, O_WRONLY | O_CREAT, 0666);
1291 fprintf(stderr, "Error opening %s:%s\n",
1292 opt_io, strerror(errno));
1301 static char buf[BUFSIZ];
1302 static int buflen = 0;
1305 int charsize; /* size of utf8 char in bytes */
1309 /* append read bytes to unprocessed bytes */
1310 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1311 die("Couldn't read from shell: %s\n", strerror(errno));
1313 /* process every complete utf8 char */
1316 while((charsize = utf8decode(ptr, &unicodep, buflen))) {
1317 utf8encode(unicodep, s, UTF_SIZ);
1323 /* keep any uncomplete utf8 char for the next call */
1324 memmove(buf, ptr, buflen);
1325 if(term.scr > 0 && term.scr < histsize-1) term.scr++;
1329 ttywrite(const char *s, size_t n) {
1330 Arg arg = (Arg){ .i = term.scr };
1334 if(xwrite(cmdfd, s, n) == -1)
1335 die("write error on tty: %s\n", strerror(errno));
1339 ttysend(char *s, size_t n) {
1341 if(IS_SET(MODE_ECHO))
1349 w.ws_row = term.row;
1350 w.ws_col = term.col;
1351 w.ws_xpixel = xw.tw;
1352 w.ws_ypixel = xw.th;
1353 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1354 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1358 tattrset(int attr) {
1361 for(i = 0; i < term.row-1; i++) {
1362 for(j = 0; j < term.col-1; j++) {
1363 if(term.line[i][j].mode & attr)
1372 tsetdirt(int top, int bot) {
1375 LIMIT(top, 0, term.row-1);
1376 LIMIT(bot, 0, term.row-1);
1378 for(i = top; i <= bot; i++)
1383 tsetdirtattr(int attr) {
1386 for(i = 0; i < term.row-1; i++) {
1387 for(j = 0; j < term.col-1; j++) {
1388 if(term.line[i][j].mode & attr) {
1398 tsetdirt(0, term.row-1);
1403 static TCursor c[2];
1404 bool alt = IS_SET(MODE_ALTSCREEN);
1406 if(mode == CURSOR_SAVE) {
1408 } else if(mode == CURSOR_LOAD) {
1410 tmoveto(c[alt].x, c[alt].y);
1418 term.c = (TCursor){{
1422 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1424 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1425 for(i = tabspaces; i < term.col; i += tabspaces)
1428 term.bot = term.row - 1;
1429 term.mode = MODE_WRAP;
1430 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1433 for(i = 0; i < 2; i++) {
1435 tcursor(CURSOR_SAVE);
1436 tclearregion(0, 0, term.col-1, term.row-1);
1442 tnew(int col, int row) {
1443 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1452 Line *tmp = term.line;
1454 term.line = term.alt;
1456 term.mode ^= MODE_ALTSCREEN;
1461 kscrolldown(const Arg* a) {
1478 kscrollup(const Arg* a) {
1484 if(term.scr <= histsize - n) {
1492 tscrolldown(int orig, int n, bool copyhist) {
1496 LIMIT(n, 0, term.bot-orig+1);
1498 tsetdirt(orig, term.bot-n);
1500 term.histi = (term.histi - 1 + histsize) % histsize;
1501 temp = term.hist[term.histi];
1502 term.hist[term.histi] = term.line[term.bot];
1503 term.line[term.bot] = temp;
1506 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1508 for(i = term.bot; i >= orig+n; i--) {
1509 temp = term.line[i];
1510 term.line[i] = term.line[i-n];
1511 term.line[i-n] = temp;
1518 tscrollup(int orig, int n, bool copyhist) {
1522 LIMIT(n, 0, term.bot-orig+1);
1525 term.histi = (term.histi + 1) % histsize;
1526 temp = term.hist[term.histi];
1527 term.hist[term.histi] = term.line[orig];
1528 term.line[orig] = temp;
1531 tclearregion(0, orig, term.col-1, orig+n-1);
1532 tsetdirt(orig+n, term.bot);
1534 for(i = orig; i <= term.bot-n; i++) {
1535 temp = term.line[i];
1536 term.line[i] = term.line[i+n];
1537 term.line[i+n] = temp;
1540 selscroll(orig, -n);
1544 selscroll(int orig, int n) {
1548 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1549 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1553 if(sel.type == SEL_RECTANGULAR) {
1554 if(sel.ob.y < term.top)
1555 sel.ob.y = term.top;
1556 if(sel.oe.y > term.bot)
1557 sel.oe.y = term.bot;
1559 if(sel.ob.y < term.top) {
1560 sel.ob.y = term.top;
1563 if(sel.oe.y > term.bot) {
1564 sel.oe.y = term.bot;
1565 sel.oe.x = term.col;
1573 tnewline(int first_col) {
1577 tscrollup(term.top, 1, true);
1581 tmoveto(first_col ? 0 : term.c.x, y);
1586 char *p = csiescseq.buf, *np;
1595 csiescseq.buf[csiescseq.len] = '\0';
1596 while(p < csiescseq.buf+csiescseq.len) {
1598 v = strtol(p, &np, 10);
1601 if(v == LONG_MAX || v == LONG_MIN)
1603 csiescseq.arg[csiescseq.narg++] = v;
1605 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1609 csiescseq.mode[0] = *p++;
1610 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1613 /* for absolute user moves, when decom is set */
1615 tmoveato(int x, int y) {
1616 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1620 tmoveto(int x, int y) {
1623 if(term.c.state & CURSOR_ORIGIN) {
1628 maxy = term.row - 1;
1630 LIMIT(x, 0, term.col-1);
1631 LIMIT(y, miny, maxy);
1632 term.c.state &= ~CURSOR_WRAPNEXT;
1638 tsetchar(char *c, Glyph *attr, int x, int y) {
1639 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1640 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1641 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1642 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1643 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1644 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1645 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1646 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1647 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1651 * The table is proudly stolen from rxvt.
1653 if(term.trantbl[term.charset] == CS_GRAPHIC0) {
1654 if(BETWEEN(c[0], 0x41, 0x7e) && vt100_0[c[0] - 0x41]) {
1655 c = vt100_0[c[0] - 0x41];
1659 if(term.line[y][x].mode & ATTR_WIDE) {
1660 if(x+1 < term.col) {
1661 term.line[y][x+1].c[0] = ' ';
1662 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1664 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1665 term.line[y][x-1].c[0] = ' ';
1666 term.line[y][x-1].mode &= ~ATTR_WIDE;
1670 term.line[y][x] = *attr;
1671 memcpy(term.line[y][x].c, c, UTF_SIZ);
1675 tclearregion(int x1, int y1, int x2, int y2) {
1680 temp = x1, x1 = x2, x2 = temp;
1682 temp = y1, y1 = y2, y2 = temp;
1684 LIMIT(x1, 0, term.col-1);
1685 LIMIT(x2, 0, term.col-1);
1686 LIMIT(y1, 0, term.row-1);
1687 LIMIT(y2, 0, term.row-1);
1689 for(y = y1; y <= y2; y++) {
1691 for(x = x1; x <= x2; x++) {
1692 gp = &term.line[y][x];
1695 gp->fg = term.c.attr.fg;
1696 gp->bg = term.c.attr.bg;
1698 memcpy(gp->c, " ", 2);
1704 tdeletechar(int n) {
1708 LIMIT(n, 0, term.col - term.c.x);
1712 size = term.col - src;
1713 line = term.line[term.c.y];
1715 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1716 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1720 tinsertblank(int n) {
1724 LIMIT(n, 0, term.col - term.c.x);
1728 size = term.col - dst;
1729 line = term.line[term.c.y];
1731 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1732 tclearregion(src, term.c.y, dst - 1, term.c.y);
1736 tinsertblankline(int n) {
1737 if(BETWEEN(term.c.y, term.top, term.bot))
1738 tscrolldown(term.c.y, n, false);
1742 tdeleteline(int n) {
1743 if(BETWEEN(term.c.y, term.top, term.bot))
1744 tscrollup(term.c.y, n, false);
1748 tdefcolor(int *attr, int *npar, int l) {
1752 switch (attr[*npar + 1]) {
1753 case 2: /* direct color in RGB space */
1754 if (*npar + 4 >= l) {
1756 "erresc(38): Incorrect number of parameters (%d)\n",
1760 r = attr[*npar + 2];
1761 g = attr[*npar + 3];
1762 b = attr[*npar + 4];
1764 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1765 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1768 idx = TRUECOLOR(r, g, b);
1770 case 5: /* indexed color */
1771 if (*npar + 2 >= l) {
1773 "erresc(38): Incorrect number of parameters (%d)\n",
1778 if(!BETWEEN(attr[*npar], 0, 255))
1779 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1783 case 0: /* implemented defined (only foreground) */
1784 case 1: /* transparent */
1785 case 3: /* direct color in CMY space */
1786 case 4: /* direct color in CMYK space */
1789 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1797 tsetattr(int *attr, int l) {
1801 for(i = 0; i < l; i++) {
1804 term.c.attr.mode &= ~(
1813 term.c.attr.fg = defaultfg;
1814 term.c.attr.bg = defaultbg;
1817 term.c.attr.mode |= ATTR_BOLD;
1820 term.c.attr.mode |= ATTR_FAINT;
1823 term.c.attr.mode |= ATTR_ITALIC;
1826 term.c.attr.mode |= ATTR_UNDERLINE;
1828 case 5: /* slow blink */
1830 case 6: /* rapid blink */
1831 term.c.attr.mode |= ATTR_BLINK;
1834 term.c.attr.mode |= ATTR_REVERSE;
1837 term.c.attr.mode |= ATTR_INVISIBLE;
1840 term.c.attr.mode |= ATTR_STRUCK;
1843 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
1846 term.c.attr.mode &= ~ATTR_ITALIC;
1849 term.c.attr.mode &= ~ATTR_UNDERLINE;
1852 term.c.attr.mode &= ~ATTR_BLINK;
1855 term.c.attr.mode &= ~ATTR_REVERSE;
1858 term.c.attr.mode &= ~ATTR_INVISIBLE;
1861 term.c.attr.mode &= ~ATTR_STRUCK;
1864 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1865 term.c.attr.fg = idx;
1868 term.c.attr.fg = defaultfg;
1871 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1872 term.c.attr.bg = idx;
1875 term.c.attr.bg = defaultbg;
1878 if(BETWEEN(attr[i], 30, 37)) {
1879 term.c.attr.fg = attr[i] - 30;
1880 } else if(BETWEEN(attr[i], 40, 47)) {
1881 term.c.attr.bg = attr[i] - 40;
1882 } else if(BETWEEN(attr[i], 90, 97)) {
1883 term.c.attr.fg = attr[i] - 90 + 8;
1884 } else if(BETWEEN(attr[i], 100, 107)) {
1885 term.c.attr.bg = attr[i] - 100 + 8;
1888 "erresc(default): gfx attr %d unknown\n",
1889 attr[i]), csidump();
1897 tsetscroll(int t, int b) {
1900 LIMIT(t, 0, term.row-1);
1901 LIMIT(b, 0, term.row-1);
1912 tsetmode(bool priv, bool set, int *args, int narg) {
1916 for(lim = args + narg; args < lim; ++args) {
1919 case 1: /* DECCKM -- Cursor key */
1920 MODBIT(term.mode, set, MODE_APPCURSOR);
1922 case 5: /* DECSCNM -- Reverse video */
1924 MODBIT(term.mode, set, MODE_REVERSE);
1925 if(mode != term.mode)
1928 case 6: /* DECOM -- Origin */
1929 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1932 case 7: /* DECAWM -- Auto wrap */
1933 MODBIT(term.mode, set, MODE_WRAP);
1935 case 0: /* Error (IGNORED) */
1936 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1937 case 3: /* DECCOLM -- Column (IGNORED) */
1938 case 4: /* DECSCLM -- Scroll (IGNORED) */
1939 case 8: /* DECARM -- Auto repeat (IGNORED) */
1940 case 18: /* DECPFF -- Printer feed (IGNORED) */
1941 case 19: /* DECPEX -- Printer extent (IGNORED) */
1942 case 42: /* DECNRCM -- National characters (IGNORED) */
1943 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1945 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1946 MODBIT(term.mode, !set, MODE_HIDE);
1948 case 9: /* X10 mouse compatibility mode */
1949 xsetpointermotion(0);
1950 MODBIT(term.mode, 0, MODE_MOUSE);
1951 MODBIT(term.mode, set, MODE_MOUSEX10);
1953 case 1000: /* 1000: report button press */
1954 xsetpointermotion(0);
1955 MODBIT(term.mode, 0, MODE_MOUSE);
1956 MODBIT(term.mode, set, MODE_MOUSEBTN);
1958 case 1002: /* 1002: report motion on button press */
1959 xsetpointermotion(0);
1960 MODBIT(term.mode, 0, MODE_MOUSE);
1961 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1963 case 1003: /* 1003: enable all mouse motions */
1964 xsetpointermotion(set);
1965 MODBIT(term.mode, 0, MODE_MOUSE);
1966 MODBIT(term.mode, set, MODE_MOUSEMANY);
1968 case 1004: /* 1004: send focus events to tty */
1969 MODBIT(term.mode, set, MODE_FOCUS);
1971 case 1006: /* 1006: extended reporting mode */
1972 MODBIT(term.mode, set, MODE_MOUSESGR);
1975 MODBIT(term.mode, set, MODE_8BIT);
1977 case 1049: /* swap screen & set/restore cursor as xterm */
1978 if (!allowaltscreen)
1980 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1982 case 47: /* swap screen */
1984 if (!allowaltscreen)
1986 alt = IS_SET(MODE_ALTSCREEN);
1988 tclearregion(0, 0, term.col-1,
1991 if(set ^ alt) /* set is always 1 or 0 */
1997 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1999 case 2004: /* 2004: bracketed paste mode */
2000 MODBIT(term.mode, set, MODE_BRCKTPASTE);
2002 /* Not implemented mouse modes. See comments there. */
2003 case 1001: /* mouse highlight mode; can hang the
2004 terminal by design when implemented. */
2005 case 1005: /* UTF-8 mouse mode; will confuse
2006 applications not supporting UTF-8
2008 case 1015: /* urxvt mangled mouse mode; incompatible
2009 and can be mistaken for other control
2013 "erresc: unknown private set/reset mode %d\n",
2019 case 0: /* Error (IGNORED) */
2021 case 2: /* KAM -- keyboard action */
2022 MODBIT(term.mode, set, MODE_KBDLOCK);
2024 case 4: /* IRM -- Insertion-replacement */
2025 MODBIT(term.mode, set, MODE_INSERT);
2027 case 12: /* SRM -- Send/Receive */
2028 MODBIT(term.mode, !set, MODE_ECHO);
2030 case 20: /* LNM -- Linefeed/new line */
2031 MODBIT(term.mode, set, MODE_CRLF);
2035 "erresc: unknown set/reset mode %d\n",
2048 switch(csiescseq.mode[0]) {
2051 fprintf(stderr, "erresc: unknown csi ");
2055 case '@': /* ICH -- Insert <n> blank char */
2056 DEFAULT(csiescseq.arg[0], 1);
2057 tinsertblank(csiescseq.arg[0]);
2059 case 'A': /* CUU -- Cursor <n> Up */
2060 DEFAULT(csiescseq.arg[0], 1);
2061 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2063 case 'B': /* CUD -- Cursor <n> Down */
2064 case 'e': /* VPR --Cursor <n> Down */
2065 DEFAULT(csiescseq.arg[0], 1);
2066 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2068 case 'i': /* MC -- Media Copy */
2069 switch(csiescseq.arg[0]) {
2074 tdumpline(term.c.y);
2080 term.mode &= ~MODE_PRINT;
2083 term.mode |= MODE_PRINT;
2087 case 'c': /* DA -- Device Attributes */
2088 if(csiescseq.arg[0] == 0)
2089 ttywrite(vtiden, sizeof(vtiden) - 1);
2091 case 'C': /* CUF -- Cursor <n> Forward */
2092 case 'a': /* HPR -- Cursor <n> Forward */
2093 DEFAULT(csiescseq.arg[0], 1);
2094 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2096 case 'D': /* CUB -- Cursor <n> Backward */
2097 DEFAULT(csiescseq.arg[0], 1);
2098 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2100 case 'E': /* CNL -- Cursor <n> Down and first col */
2101 DEFAULT(csiescseq.arg[0], 1);
2102 tmoveto(0, term.c.y+csiescseq.arg[0]);
2104 case 'F': /* CPL -- Cursor <n> Up and first col */
2105 DEFAULT(csiescseq.arg[0], 1);
2106 tmoveto(0, term.c.y-csiescseq.arg[0]);
2108 case 'g': /* TBC -- Tabulation clear */
2109 switch(csiescseq.arg[0]) {
2110 case 0: /* clear current tab stop */
2111 term.tabs[term.c.x] = 0;
2113 case 3: /* clear all the tabs */
2114 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2120 case 'G': /* CHA -- Move to <col> */
2122 DEFAULT(csiescseq.arg[0], 1);
2123 tmoveto(csiescseq.arg[0]-1, term.c.y);
2125 case 'H': /* CUP -- Move to <row> <col> */
2127 DEFAULT(csiescseq.arg[0], 1);
2128 DEFAULT(csiescseq.arg[1], 1);
2129 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2131 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2132 DEFAULT(csiescseq.arg[0], 1);
2133 tputtab(csiescseq.arg[0]);
2135 case 'J': /* ED -- Clear screen */
2137 switch(csiescseq.arg[0]) {
2139 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2140 if(term.c.y < term.row-1) {
2141 tclearregion(0, term.c.y+1, term.col-1,
2147 tclearregion(0, 0, term.col-1, term.c.y-1);
2148 tclearregion(0, term.c.y, term.c.x, term.c.y);
2151 tclearregion(0, 0, term.col-1, term.row-1);
2157 case 'K': /* EL -- Clear line */
2158 switch(csiescseq.arg[0]) {
2160 tclearregion(term.c.x, term.c.y, term.col-1,
2164 tclearregion(0, term.c.y, term.c.x, term.c.y);
2167 tclearregion(0, term.c.y, term.col-1, term.c.y);
2171 case 'S': /* SU -- Scroll <n> line up */
2172 DEFAULT(csiescseq.arg[0], 1);
2173 tscrollup(term.top, csiescseq.arg[0], false);
2175 case 'T': /* SD -- Scroll <n> line down */
2176 DEFAULT(csiescseq.arg[0], 1);
2177 tscrolldown(term.top, csiescseq.arg[0], false);
2179 case 'L': /* IL -- Insert <n> blank lines */
2180 DEFAULT(csiescseq.arg[0], 1);
2181 tinsertblankline(csiescseq.arg[0]);
2183 case 'l': /* RM -- Reset Mode */
2184 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2186 case 'M': /* DL -- Delete <n> lines */
2187 DEFAULT(csiescseq.arg[0], 1);
2188 tdeleteline(csiescseq.arg[0]);
2190 case 'X': /* ECH -- Erase <n> char */
2191 DEFAULT(csiescseq.arg[0], 1);
2192 tclearregion(term.c.x, term.c.y,
2193 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2195 case 'P': /* DCH -- Delete <n> char */
2196 DEFAULT(csiescseq.arg[0], 1);
2197 tdeletechar(csiescseq.arg[0]);
2199 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2200 DEFAULT(csiescseq.arg[0], 1);
2201 tputtab(-csiescseq.arg[0]);
2203 case 'd': /* VPA -- Move to <row> */
2204 DEFAULT(csiescseq.arg[0], 1);
2205 tmoveato(term.c.x, csiescseq.arg[0]-1);
2207 case 'h': /* SM -- Set terminal mode */
2208 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2210 case 'm': /* SGR -- Terminal attribute (color) */
2211 tsetattr(csiescseq.arg, csiescseq.narg);
2213 case 'n': /* DSR – Device Status Report (cursor position) */
2214 if (csiescseq.arg[0] == 6) {
2215 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2216 term.c.y+1, term.c.x+1);
2220 case 'r': /* DECSTBM -- Set Scrolling Region */
2221 if(csiescseq.priv) {
2224 DEFAULT(csiescseq.arg[0], 1);
2225 DEFAULT(csiescseq.arg[1], term.row);
2226 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2230 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2231 tcursor(CURSOR_SAVE);
2233 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2234 tcursor(CURSOR_LOAD);
2237 switch (csiescseq.mode[1]) {
2238 case 'q': /* DECSCUSR -- Set Cursor Style */
2239 DEFAULT(csiescseq.arg[0], 1);
2240 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2243 xw.cursor = csiescseq.arg[0];
2258 for(i = 0; i < csiescseq.len; i++) {
2259 c = csiescseq.buf[i] & 0xff;
2262 } else if(c == '\n') {
2264 } else if(c == '\r') {
2266 } else if(c == 0x1b) {
2269 printf("(%02x)", c);
2277 memset(&csiescseq, 0, sizeof(csiescseq));
2285 term.esc &= ~(ESC_STR_END|ESC_STR);
2287 narg = strescseq.narg;
2288 par = atoi(strescseq.args[0]);
2290 switch(strescseq.type) {
2291 case ']': /* OSC -- Operating System Command */
2297 xsettitle(strescseq.args[1]);
2299 case 4: /* color set */
2302 p = strescseq.args[2];
2304 case 104: /* color reset, here p = NULL */
2305 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2306 if(xsetcolorname(j, p)) {
2307 fprintf(stderr, "erresc: invalid color %s\n", p);
2310 * TODO if defaultbg color is changed, borders
2318 case 'k': /* old title set compatibility */
2319 xsettitle(strescseq.args[0]);
2321 case 'P': /* DCS -- Device Control String */
2322 case '_': /* APC -- Application Program Command */
2323 case '^': /* PM -- Privacy Message */
2327 fprintf(stderr, "erresc: unknown str ");
2334 char *p = strescseq.buf;
2337 strescseq.buf[strescseq.len] = '\0';
2342 while(strescseq.narg < STR_ARG_SIZ) {
2343 strescseq.args[strescseq.narg++] = p;
2344 while((c = *p) != ';' && c != '\0')
2357 printf("ESC%c", strescseq.type);
2358 for(i = 0; i < strescseq.len; i++) {
2359 c = strescseq.buf[i] & 0xff;
2362 } else if(isprint(c)) {
2364 } else if(c == '\n') {
2366 } else if(c == '\r') {
2368 } else if(c == 0x1b) {
2371 printf("(%02x)", c);
2379 memset(&strescseq, 0, sizeof(strescseq));
2383 tprinter(char *s, size_t len) {
2384 if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2385 fprintf(stderr, "Error writing in %s:%s\n",
2386 opt_io, strerror(errno));
2393 toggleprinter(const Arg *arg) {
2394 term.mode ^= MODE_PRINT;
2398 printscreen(const Arg *arg) {
2403 printsel(const Arg *arg) {
2411 if((ptr = getsel())) {
2412 tprinter(ptr, strlen(ptr));
2421 bp = &term.line[n][0];
2422 end = &bp[MIN(tlinelen(n), term.col) - 1];
2423 if(bp != end || bp->c[0] != ' ') {
2424 for( ;bp <= end; ++bp)
2425 tprinter(bp->c, utf8len(bp->c));
2434 for(i = 0; i < term.row; ++i)
2443 while(x < term.col && n--)
2444 for(++x; x < term.col && !term.tabs[x]; ++x)
2448 for(--x; x > 0 && !term.tabs[x]; --x)
2451 tmoveto(x, term.c.y);
2455 techo(char *buf, int len) {
2456 for(; len > 0; buf++, len--) {
2459 if(ISCONTROL((uchar) c)) { /* control code */
2464 } else if(c != '\n' && c != '\r' && c != '\t') {
2478 tdeftran(char ascii) {
2479 static char cs[] = "0B";
2480 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2483 if((p = strchr(cs, ascii)) == NULL) {
2484 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2486 term.trantbl[term.icharset] = vcs[p - cs];
2492 static char E[UTF_SIZ] = "E";
2495 if(c == '8') { /* DEC screen alignment test. */
2496 for(x = 0; x < term.col; ++x) {
2497 for(y = 0; y < term.row; ++y)
2498 tsetchar(E, &term.c.attr, x, y);
2504 tstrsequence(uchar c) {
2507 case 0x90: /* DCS -- Device Control String */
2510 case 0x9f: /* APC -- Application Program Command */
2513 case 0x9e: /* PM -- Privacy Message */
2516 case 0x9d: /* OSC -- Operating System Command */
2523 term.esc |= ESC_STR;
2528 tcontrolcode(uchar ascii) {
2529 static char question[UTF_SIZ] = "?";
2536 tmoveto(term.c.x-1, term.c.y);
2539 tmoveto(0, term.c.y);
2544 /* go to first col if the mode is set */
2545 tnewline(IS_SET(MODE_CRLF));
2547 case '\a': /* BEL */
2548 if(term.esc & ESC_STR_END) {
2549 /* backwards compatibility to xterm */
2552 if(!(xw.state & WIN_FOCUSED))
2555 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2558 case '\033': /* ESC */
2560 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2561 term.esc |= ESC_START;
2563 case '\016': /* SO (LS1 -- Locking shift 1) */
2564 case '\017': /* SI (LS0 -- Locking shift 0) */
2565 term.charset = 1 - (ascii - '\016');
2567 case '\032': /* SUB */
2568 tsetchar(question, &term.c.attr, term.c.x, term.c.y);
2569 case '\030': /* CAN */
2572 case '\005': /* ENQ (IGNORED) */
2573 case '\000': /* NUL (IGNORED) */
2574 case '\021': /* XON (IGNORED) */
2575 case '\023': /* XOFF (IGNORED) */
2576 case 0177: /* DEL (IGNORED) */
2578 case 0x84: /* TODO: IND */
2580 case 0x85: /* NEL -- Next line */
2581 tnewline(1); /* always go to first col */
2583 case 0x88: /* HTS -- Horizontal tab stop */
2584 term.tabs[term.c.x] = 1;
2586 case 0x8d: /* TODO: RI */
2587 case 0x8e: /* TODO: SS2 */
2588 case 0x8f: /* TODO: SS3 */
2589 case 0x98: /* TODO: SOS */
2591 case 0x9a: /* DECID -- Identify Terminal */
2592 ttywrite(vtiden, sizeof(vtiden) - 1);
2594 case 0x9b: /* TODO: CSI */
2595 case 0x9c: /* TODO: ST */
2597 case 0x90: /* DCS -- Device Control String */
2598 case 0x9f: /* APC -- Application Program Command */
2599 case 0x9e: /* PM -- Privacy Message */
2600 case 0x9d: /* OSC -- Operating System Command */
2601 tstrsequence(ascii);
2604 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2605 term.esc &= ~(ESC_STR_END|ESC_STR);
2610 * returns 1 when the sequence is finished and it hasn't to read
2611 * more characters for this sequence, otherwise 0
2614 eschandle(uchar ascii) {
2617 term.esc |= ESC_CSI;
2620 term.esc |= ESC_TEST;
2622 case 'P': /* DCS -- Device Control String */
2623 case '_': /* APC -- Application Program Command */
2624 case '^': /* PM -- Privacy Message */
2625 case ']': /* OSC -- Operating System Command */
2626 case 'k': /* old title set compatibility */
2627 tstrsequence(ascii);
2629 case 'n': /* LS2 -- Locking shift 2 */
2630 case 'o': /* LS3 -- Locking shift 3 */
2631 term.charset = 2 + (ascii - 'n');
2633 case '(': /* GZD4 -- set primary charset G0 */
2634 case ')': /* G1D4 -- set secondary charset G1 */
2635 case '*': /* G2D4 -- set tertiary charset G2 */
2636 case '+': /* G3D4 -- set quaternary charset G3 */
2637 term.icharset = ascii - '(';
2638 term.esc |= ESC_ALTCHARSET;
2640 case 'D': /* IND -- Linefeed */
2641 if(term.c.y == term.bot) {
2642 tscrollup(term.top, 1, true);
2644 tmoveto(term.c.x, term.c.y+1);
2647 case 'E': /* NEL -- Next line */
2648 tnewline(1); /* always go to first col */
2650 case 'H': /* HTS -- Horizontal tab stop */
2651 term.tabs[term.c.x] = 1;
2653 case 'M': /* RI -- Reverse index */
2654 if(term.c.y == term.top) {
2655 tscrolldown(term.top, 1, true);
2657 tmoveto(term.c.x, term.c.y-1);
2660 case 'Z': /* DECID -- Identify Terminal */
2661 ttywrite(vtiden, sizeof(vtiden) - 1);
2663 case 'c': /* RIS -- Reset to inital state */
2668 case '=': /* DECPAM -- Application keypad */
2669 term.mode |= MODE_APPKEYPAD;
2671 case '>': /* DECPNM -- Normal keypad */
2672 term.mode &= ~MODE_APPKEYPAD;
2674 case '7': /* DECSC -- Save Cursor */
2675 tcursor(CURSOR_SAVE);
2677 case '8': /* DECRC -- Restore Cursor */
2678 tcursor(CURSOR_LOAD);
2680 case '\\': /* ST -- String Terminator */
2681 if(term.esc & ESC_STR_END)
2685 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2686 (uchar) ascii, isprint(ascii)? ascii:'.');
2693 tputc(char *c, int len) {
2702 unicodep = ascii = *c;
2704 utf8decode(c, &unicodep, UTF_SIZ);
2705 if ((width = wcwidth(unicodep)) == -1) {
2706 c = "\357\277\275"; /* UTF_INVALID */
2709 control = ISCONTROLC1(unicodep);
2713 if(IS_SET(MODE_PRINT))
2715 control = ISCONTROL(unicodep);
2718 * STR sequence must be checked before anything else
2719 * because it uses all following characters until it
2720 * receives a ESC, a SUB, a ST or any other C1 control
2723 if(term.esc & ESC_STR) {
2725 (ascii == '\a' || ascii == 030 ||
2726 ascii == 032 || ascii == 033 ||
2727 ISCONTROLC1(unicodep))) {
2728 term.esc &= ~(ESC_START|ESC_STR);
2729 term.esc |= ESC_STR_END;
2730 } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2731 memmove(&strescseq.buf[strescseq.len], c, len);
2732 strescseq.len += len;
2736 * Here is a bug in terminals. If the user never sends
2737 * some code to stop the str or esc command, then st
2738 * will stop responding. But this is better than
2739 * silently failing with unknown characters. At least
2740 * then users will report back.
2742 * In the case users ever get fixed, here is the code:
2753 * Actions of control codes must be performed as soon they arrive
2754 * because they can be embedded inside a control sequence, and
2755 * they must not cause conflicts with sequences.
2758 tcontrolcode(ascii);
2760 * control codes are not shown ever
2763 } else if(term.esc & ESC_START) {
2764 if(term.esc & ESC_CSI) {
2765 csiescseq.buf[csiescseq.len++] = ascii;
2766 if(BETWEEN(ascii, 0x40, 0x7E)
2767 || csiescseq.len >= \
2768 sizeof(csiescseq.buf)-1) {
2774 } else if(term.esc & ESC_ALTCHARSET) {
2776 } else if(term.esc & ESC_TEST) {
2779 if (!eschandle(ascii))
2781 /* sequence already finished */
2785 * All characters which form part of a sequence are not
2790 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2793 gp = &term.line[term.c.y][term.c.x];
2794 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2795 gp->mode |= ATTR_WRAP;
2797 gp = &term.line[term.c.y][term.c.x];
2800 if(IS_SET(MODE_INSERT) && term.c.x+width < term.col)
2801 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
2803 if(term.c.x+width > term.col) {
2805 gp = &term.line[term.c.y][term.c.x];
2808 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2811 gp->mode |= ATTR_WIDE;
2812 if(term.c.x+1 < term.col) {
2814 gp[1].mode = ATTR_WDUMMY;
2817 if(term.c.x+width < term.col) {
2818 tmoveto(term.c.x+width, term.c.y);
2820 term.c.state |= CURSOR_WRAPNEXT;
2825 tresize(int col, int row) {
2827 int minrow = MIN(row, term.row);
2828 int mincol = MIN(col, term.col);
2829 int slide = term.c.y - row + 1;
2833 if(col < 1 || row < 1) {
2835 "tresize: error resizing to %dx%d\n", col, row);
2839 /* free unneeded rows */
2843 * slide screen to keep cursor where we expect it -
2844 * tscrollup would work here, but we can optimize to
2845 * memmove because we're freeing the earlier lines
2847 for(/* i = 0 */; i < slide; i++) {
2851 memmove(term.line, term.line + slide, row * sizeof(Line));
2852 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2854 for(i += row; i < term.row; i++) {
2859 /* resize to new height */
2860 term.line = xrealloc(term.line, row * sizeof(Line));
2861 term.alt = xrealloc(term.alt, row * sizeof(Line));
2862 term.hist = xrealloc(term.hist, histsize * sizeof(Line));
2863 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2864 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2866 for(i = 0; i < histsize; i++) {
2867 term.hist[i] = xrealloc(term.hist[i], col * sizeof(Glyph));
2868 for(j = mincol; j < col; j++) {
2869 term.hist[i][j] = term.c.attr;
2870 memcpy(term.hist[i][j].c, " ", 2);
2874 /* resize each row to new width, zero-pad if needed */
2875 for(i = 0; i < minrow; i++) {
2876 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2877 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2880 /* allocate any new rows */
2881 for(/* i == minrow */; i < row; i++) {
2882 term.line[i] = xmalloc(col * sizeof(Glyph));
2883 term.alt[i] = xmalloc(col * sizeof(Glyph));
2885 if(col > term.col) {
2886 bp = term.tabs + term.col;
2888 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2889 while(--bp > term.tabs && !*bp)
2891 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2894 /* update terminal size */
2897 /* reset scrolling region */
2898 tsetscroll(0, row-1);
2899 /* make use of the LIMIT in tmoveto */
2900 tmoveto(term.c.x, term.c.y);
2901 /* Clearing both screens (it makes dirty all lines) */
2903 for(i = 0; i < 2; i++) {
2904 if(mincol < col && 0 < minrow) {
2905 tclearregion(mincol, 0, col - 1, minrow - 1);
2907 if(0 < col && minrow < row) {
2908 tclearregion(0, minrow, col - 1, row - 1);
2911 tcursor(CURSOR_LOAD);
2917 xresize(int col, int row) {
2918 xw.tw = MAX(1, col * xw.cw);
2919 xw.th = MAX(1, row * xw.ch);
2921 XFreePixmap(xw.dpy, xw.buf);
2922 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2923 DefaultDepth(xw.dpy, xw.scr));
2924 XftDrawChange(xw.draw, xw.buf);
2925 xclear(0, 0, xw.w, xw.h);
2928 static inline ushort
2929 sixd_to_16bit(int x) {
2930 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2936 XRenderColor color = { .alpha = 0xffff };
2941 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2942 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2945 /* load colors [0-15] and [256-LEN(colorname)] (config.h) */
2946 for(i = 0; i < LEN(colorname); i++) {
2949 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2950 die("Could not allocate color '%s'\n", colorname[i]);
2954 /* load colors [16-231] ; same colors as xterm */
2955 for(i = 16; i < 6*6*6+16; i++) {
2956 color.red = sixd_to_16bit( ((i-16)/36)%6 );
2957 color.green = sixd_to_16bit( ((i-16)/6) %6 );
2958 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
2959 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
2960 die("Could not allocate color %d\n", i);
2963 /* load colors [232-255] ; grayscale */
2964 for(; i < 256; i++) {
2965 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (i-(6*6*6+16));
2966 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
2967 die("Could not allocate color %d\n", i);
2973 xsetcolorname(int x, const char *name) {
2974 XRenderColor color = { .alpha = 0xffff };
2977 if(!BETWEEN(x, 0, LEN(colorname)))
2981 if(BETWEEN(x, 16, 16 + 215)) { /* 256 color */
2982 color.red = sixd_to_16bit( ((x-16)/36)%6 );
2983 color.green = sixd_to_16bit( ((x-16)/6) %6 );
2984 color.blue = sixd_to_16bit( ((x-16)/1) %6 );
2985 if(!XftColorAllocValue(xw.dpy, xw.vis,
2986 xw.cmap, &color, &ncolor)) {
2990 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2993 } else if(BETWEEN(x, 16 + 216, 255)) { /* greyscale */
2994 color.red = color.green = color.blue = \
2995 0x0808 + 0x0a0a * (x - (16 + 216));
2996 if(!XftColorAllocValue(xw.dpy, xw.vis,
2997 xw.cmap, &color, &ncolor)) {
3001 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
3004 } else { /* system colors */
3005 name = colorname[x];
3008 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &ncolor))
3011 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
3017 xtermclear(int col1, int row1, int col2, int row2) {
3018 XftDrawRect(xw.draw,
3019 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
3020 borderpx + col1 * xw.cw,
3021 borderpx + row1 * xw.ch,
3022 (col2-col1+1) * xw.cw,
3023 (row2-row1+1) * xw.ch);
3027 * Absolute coordinates.
3030 xclear(int x1, int y1, int x2, int y2) {
3031 XftDrawRect(xw.draw,
3032 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
3033 x1, y1, x2-x1, y2-y1);
3038 XClassHint class = {opt_class ? opt_class : termname, termname};
3039 XWMHints wm = {.flags = InputHint, .input = 1};
3040 XSizeHints *sizeh = NULL;
3042 sizeh = XAllocSizeHints();
3044 sizeh->flags = PSize | PResizeInc | PBaseSize;
3045 sizeh->height = xw.h;
3046 sizeh->width = xw.w;
3047 sizeh->height_inc = xw.ch;
3048 sizeh->width_inc = xw.cw;
3049 sizeh->base_height = 2 * borderpx;
3050 sizeh->base_width = 2 * borderpx;
3051 if(xw.isfixed == True) {
3052 sizeh->flags |= PMaxSize | PMinSize;
3053 sizeh->min_width = sizeh->max_width = xw.w;
3054 sizeh->min_height = sizeh->max_height = xw.h;
3056 if(xw.gm & (XValue|YValue)) {
3057 sizeh->flags |= USPosition | PWinGravity;
3060 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3063 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3069 xgeommasktogravity(int mask) {
3070 switch(mask & (XNegative|YNegative)) {
3072 return NorthWestGravity;
3074 return NorthEastGravity;
3076 return SouthWestGravity;
3078 return SouthEastGravity;
3082 xloadfont(Font *f, FcPattern *pattern) {
3086 match = FcFontMatch(NULL, pattern, &result);
3090 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3091 FcPatternDestroy(match);
3096 f->pattern = FcPatternDuplicate(pattern);
3098 f->ascent = f->match->ascent;
3099 f->descent = f->match->descent;
3101 f->rbearing = f->match->max_advance_width;
3103 f->height = f->ascent + f->descent;
3104 f->width = f->lbearing + f->rbearing;
3110 xloadfonts(char *fontstr, double fontsize) {
3112 FcResult r_sz, r_psz;
3116 if(fontstr[0] == '-') {
3117 pattern = XftXlfdParse(fontstr, False, False);
3119 pattern = FcNameParse((FcChar8 *)fontstr);
3123 die("st: can't open font %s\n", fontstr);
3126 FcPatternDel(pattern, FC_PIXEL_SIZE);
3127 FcPatternDel(pattern, FC_SIZE);
3128 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3129 usedfontsize = fontsize;
3131 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
3132 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
3133 if(r_psz == FcResultMatch) {
3134 usedfontsize = fontval;
3135 } else if(r_sz == FcResultMatch) {
3139 * Default font size is 12, if none given. This is to
3140 * have a known usedfontsize value.
3142 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3145 defaultfontsize = usedfontsize;
3148 FcConfigSubstitute(0, pattern, FcMatchPattern);
3149 FcDefaultSubstitute(pattern);
3151 if(xloadfont(&dc.font, pattern))
3152 die("st: can't open font %s\n", fontstr);
3154 if(usedfontsize < 0) {
3155 FcPatternGetDouble(dc.font.match->pattern,
3156 FC_PIXEL_SIZE, 0, &fontval);
3157 usedfontsize = fontval;
3159 defaultfontsize = fontval;
3162 /* Setting character width and height. */
3163 xw.cw = ceilf(dc.font.width * cwscale);
3164 xw.ch = ceilf(dc.font.height * chscale);
3166 FcPatternDel(pattern, FC_SLANT);
3167 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3168 if(xloadfont(&dc.ifont, pattern))
3169 die("st: can't open font %s\n", fontstr);
3171 FcPatternDel(pattern, FC_WEIGHT);
3172 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3173 if(xloadfont(&dc.ibfont, pattern))
3174 die("st: can't open font %s\n", fontstr);
3176 FcPatternDel(pattern, FC_SLANT);
3177 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3178 if(xloadfont(&dc.bfont, pattern))
3179 die("st: can't open font %s\n", fontstr);
3181 FcPatternDestroy(pattern);
3185 xloadfontset(Font *f) {
3188 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
3194 xunloadfont(Font *f) {
3195 XftFontClose(xw.dpy, f->match);
3196 FcPatternDestroy(f->pattern);
3198 FcFontSetDestroy(f->set);
3202 xunloadfonts(void) {
3203 /* Free the loaded fonts in the font cache. */
3205 XftFontClose(xw.dpy, frc[--frclen].font);
3207 xunloadfont(&dc.font);
3208 xunloadfont(&dc.bfont);
3209 xunloadfont(&dc.ifont);
3210 xunloadfont(&dc.ibfont);
3214 xzoom(const Arg *arg) {
3217 larg.i = usedfontsize + arg->i;
3222 xzoomabs(const Arg *arg) {
3224 xloadfonts(usedfont, arg->i);
3231 xzoomreset(const Arg *arg) {
3234 if(defaultfontsize > 0) {
3235 larg.i = defaultfontsize;
3245 pid_t thispid = getpid();
3247 if(!(xw.dpy = XOpenDisplay(NULL)))
3248 die("Can't open display\n");
3249 xw.scr = XDefaultScreen(xw.dpy);
3250 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3254 die("Could not init fontconfig.\n");
3256 usedfont = (opt_font == NULL)? font : opt_font;
3257 xloadfonts(usedfont, 0);
3260 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3263 /* adjust fixed window geometry */
3264 xw.w = 2 * borderpx + term.col * xw.cw;
3265 xw.h = 2 * borderpx + term.row * xw.ch;
3266 if(xw.gm & XNegative)
3267 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3268 if(xw.gm & YNegative)
3269 xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
3272 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3273 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3274 xw.attrs.bit_gravity = NorthWestGravity;
3275 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3276 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3277 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3278 xw.attrs.colormap = xw.cmap;
3280 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3281 parent = XRootWindow(xw.dpy, xw.scr);
3282 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3283 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3284 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3285 | CWEventMask | CWColormap, &xw.attrs);
3287 memset(&gcvalues, 0, sizeof(gcvalues));
3288 gcvalues.graphics_exposures = False;
3289 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3291 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3292 DefaultDepth(xw.dpy, xw.scr));
3293 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3294 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3296 /* Xft rendering context */
3297 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3300 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3301 XSetLocaleModifiers("@im=local");
3302 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3303 XSetLocaleModifiers("@im=");
3304 if((xw.xim = XOpenIM(xw.dpy,
3305 NULL, NULL, NULL)) == NULL) {
3306 die("XOpenIM failed. Could not open input"
3311 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3312 | XIMStatusNothing, XNClientWindow, xw.win,
3313 XNFocusWindow, xw.win, NULL);
3315 die("XCreateIC failed. Could not obtain input method.\n");
3317 /* white cursor, black outline */
3318 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3319 XDefineCursor(xw.dpy, xw.win, cursor);
3320 XRecolorCursor(xw.dpy, cursor,
3321 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3322 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3324 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3325 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3326 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3327 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3329 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3330 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3331 PropModeReplace, (uchar *)&thispid, 1);
3334 XMapWindow(xw.dpy, xw.win);
3336 XSync(xw.dpy, False);
3340 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3341 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3342 width = charlen * xw.cw, xp, i;
3343 int frcflags, charexists;
3344 int u8fl, u8fblen, u8cblen, doesexist;
3347 Font *font = &dc.font;
3349 FcPattern *fcpattern, *fontpattern;
3350 FcFontSet *fcsets[] = { NULL };
3351 FcCharSet *fccharset;
3352 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3353 XRenderColor colfg, colbg;
3357 frcflags = FRC_NORMAL;
3359 if(base.mode & ATTR_ITALIC) {
3360 if(base.fg == defaultfg)
3361 base.fg = defaultitalic;
3363 frcflags = FRC_ITALIC;
3364 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3365 if(base.fg == defaultfg)
3366 base.fg = defaultitalic;
3368 frcflags = FRC_ITALICBOLD;
3369 } else if(base.mode & ATTR_UNDERLINE) {
3370 if(base.fg == defaultfg)
3371 base.fg = defaultunderline;
3374 if(IS_TRUECOL(base.fg)) {
3375 colfg.alpha = 0xffff;
3376 colfg.red = TRUERED(base.fg);
3377 colfg.green = TRUEGREEN(base.fg);
3378 colfg.blue = TRUEBLUE(base.fg);
3379 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3382 fg = &dc.col[base.fg];
3385 if(IS_TRUECOL(base.bg)) {
3386 colbg.alpha = 0xffff;
3387 colbg.green = TRUEGREEN(base.bg);
3388 colbg.red = TRUERED(base.bg);
3389 colbg.blue = TRUEBLUE(base.bg);
3390 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3393 bg = &dc.col[base.bg];
3396 if(base.mode & ATTR_BOLD) {
3398 * change basic system colors [0-7]
3399 * to bright system colors [8-15]
3401 if(BETWEEN(base.fg, 0, 7) && !(base.mode & ATTR_FAINT))
3402 fg = &dc.col[base.fg + 8];
3404 if(base.mode & ATTR_ITALIC) {
3406 frcflags = FRC_ITALICBOLD;
3409 frcflags = FRC_BOLD;
3413 if(IS_SET(MODE_REVERSE)) {
3414 if(fg == &dc.col[defaultfg]) {
3415 fg = &dc.col[defaultbg];
3417 colfg.red = ~fg->color.red;
3418 colfg.green = ~fg->color.green;
3419 colfg.blue = ~fg->color.blue;
3420 colfg.alpha = fg->color.alpha;
3421 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3426 if(bg == &dc.col[defaultbg]) {
3427 bg = &dc.col[defaultfg];
3429 colbg.red = ~bg->color.red;
3430 colbg.green = ~bg->color.green;
3431 colbg.blue = ~bg->color.blue;
3432 colbg.alpha = bg->color.alpha;
3433 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3439 if(base.mode & ATTR_REVERSE) {
3445 if(base.mode & ATTR_FAINT && !(base.mode & ATTR_BOLD)) {
3446 colfg.red = fg->color.red / 2;
3447 colfg.green = fg->color.green / 2;
3448 colfg.blue = fg->color.blue / 2;
3449 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3453 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3456 if(base.mode & ATTR_INVISIBLE)
3459 /* Intelligent cleaning up of the borders. */
3461 xclear(0, (y == 0)? 0 : winy, borderpx,
3462 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3464 if(x + charlen >= term.col) {
3465 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3466 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3469 xclear(winx, 0, winx + width, borderpx);
3471 xclear(winx, winy + xw.ch, winx + width, xw.h);
3473 /* Clean up the region we want to draw to. */
3474 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3476 /* Set the clip region because Xft is sometimes dirty. */
3481 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3483 for(xp = winx; bytelen > 0;) {
3485 * Search for the range in the to be printed string of glyphs
3486 * that are in the main font. Then print that range. If
3487 * some glyph is found that is not in the font, do the
3493 oneatatime = font->width != xw.cw;
3496 u8cblen = utf8decode(s, &unicodep, UTF_SIZ);
3500 doesexist = XftCharExists(xw.dpy, font->match, unicodep);
3504 if(!oneatatime && bytelen > 0)
3509 XftDrawStringUtf8(xw.draw, fg,
3511 winy + font->ascent,
3524 /* Search the font cache. */
3525 for(i = 0; i < frclen; i++) {
3526 charexists = XftCharExists(xw.dpy, frc[i].font, unicodep);
3527 /* Everything correct. */
3528 if(charexists && frc[i].flags == frcflags)
3530 /* We got a default font for a not found glyph. */
3531 if(!charexists && frc[i].flags == frcflags \
3532 && frc[i].unicodep == unicodep) {
3537 /* Nothing was found. */
3541 fcsets[0] = font->set;
3544 * Nothing was found in the cache. Now use
3545 * some dozen of Fontconfig calls to get the
3546 * font for one single character.
3548 * Xft and fontconfig are design failures.
3550 fcpattern = FcPatternDuplicate(font->pattern);
3551 fccharset = FcCharSetCreate();
3553 FcCharSetAddChar(fccharset, unicodep);
3554 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3556 FcPatternAddBool(fcpattern, FC_SCALABLE,
3559 FcConfigSubstitute(0, fcpattern,
3561 FcDefaultSubstitute(fcpattern);
3563 fontpattern = FcFontSetMatch(0, fcsets, 1,
3567 * Overwrite or create the new cache entry.
3569 if(frclen >= LEN(frc)) {
3570 frclen = LEN(frc) - 1;
3571 XftFontClose(xw.dpy, frc[frclen].font);
3572 frc[frclen].unicodep = 0;
3575 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3577 frc[frclen].flags = frcflags;
3578 frc[frclen].unicodep = unicodep;
3583 FcPatternDestroy(fcpattern);
3584 FcCharSetDestroy(fccharset);
3587 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3588 xp, winy + frc[i].font->ascent,
3589 (FcChar8 *)u8c, u8cblen);
3591 xp += xw.cw * wcwidth(unicodep);
3595 * This is how the loop above actually should be. Why does the
3596 * application have to care about font details?
3598 * I have to repeat: Xft and Fontconfig are design failures.
3601 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3602 winy + font->ascent, (FcChar8 *)s, bytelen);
3605 if(base.mode & ATTR_UNDERLINE) {
3606 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3610 if(base.mode & ATTR_STRUCK) {
3611 XftDrawRect(xw.draw, fg, winx, winy + 2 * font->ascent / 3,
3615 /* Reset clip to none. */
3616 XftDrawSetClip(xw.draw, 0);
3621 static int oldx = 0, oldy = 0;
3622 int sl, width, curx;
3623 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3625 LIMIT(oldx, 0, term.col-1);
3626 LIMIT(oldy, 0, term.row-1);
3630 /* adjust position if in dummy */
3631 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3633 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3636 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3638 /* remove the old cursor */
3639 sl = utf8len(term.line[oldy][oldx].c);
3640 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3641 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3644 if(IS_SET(MODE_HIDE))
3647 /* draw the new one */
3648 if(xw.state & WIN_FOCUSED) {
3649 switch (xw.cursor) {
3650 case 0: /* Blinking Block */
3651 case 1: /* Blinking Block (Default) */
3652 case 2: /* Steady Block */
3653 if(IS_SET(MODE_REVERSE)) {
3654 g.mode |= ATTR_REVERSE;
3660 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3662 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3664 case 3: /* Blinking Underline */
3665 case 4: /* Steady Underline */
3666 XftDrawRect(xw.draw, &dc.col[defaultcs],
3667 borderpx + curx * xw.cw,
3668 borderpx + (term.c.y + 1) * xw.ch - 1,
3671 case 5: /* Blinking bar */
3672 case 6: /* Steady bar */
3673 XftDrawRect(xw.draw, &dc.col[defaultcs],
3674 borderpx + curx * xw.cw,
3675 borderpx + term.c.y * xw.ch,
3680 XftDrawRect(xw.draw, &dc.col[defaultcs],
3681 borderpx + curx * xw.cw,
3682 borderpx + term.c.y * xw.ch,
3684 XftDrawRect(xw.draw, &dc.col[defaultcs],
3685 borderpx + curx * xw.cw,
3686 borderpx + term.c.y * xw.ch,
3688 XftDrawRect(xw.draw, &dc.col[defaultcs],
3689 borderpx + (curx + 1) * xw.cw - 1,
3690 borderpx + term.c.y * xw.ch,
3692 XftDrawRect(xw.draw, &dc.col[defaultcs],
3693 borderpx + curx * xw.cw,
3694 borderpx + (term.c.y + 1) * xw.ch - 1,
3697 oldx = curx, oldy = term.c.y;
3702 xsettitle(char *p) {
3705 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3707 XSetWMName(xw.dpy, xw.win, &prop);
3708 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3714 xsettitle(opt_title ? opt_title : "st");
3725 drawregion(0, 0, term.col, term.row);
3726 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3728 XSetForeground(xw.dpy, dc.gc,
3729 dc.col[IS_SET(MODE_REVERSE)?
3730 defaultfg : defaultbg].pixel);
3734 drawregion(int x1, int y1, int x2, int y2) {
3735 int ic, ib, x, y, ox, sl;
3737 char buf[DRAW_BUF_SIZ];
3738 bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3741 if(!(xw.state & WIN_VISIBLE))
3744 for(y = y1; y < y2; y++) {
3748 xtermclear(0, y, term.col, y);
3752 for(x = x1; x < x2; x++) {
3754 if(new.mode == ATTR_WDUMMY)
3756 if(ena_sel && selected(x, y))
3757 new.mode ^= ATTR_REVERSE;
3758 if(ib > 0 && (ATTRCMP(base, new)
3759 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3760 xdraws(buf, base, ox, y, ic, ib);
3768 sl = utf8decode(new.c, &unicodep, UTF_SIZ);
3769 memcpy(buf+ib, new.c, sl);
3771 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3774 xdraws(buf, base, ox, y, ic, ib);
3781 expose(XEvent *ev) {
3782 XExposeEvent *e = &ev->xexpose;
3784 if(xw.state & WIN_REDRAW) {
3786 xw.state &= ~WIN_REDRAW;
3792 visibility(XEvent *ev) {
3793 XVisibilityEvent *e = &ev->xvisibility;
3795 if(e->state == VisibilityFullyObscured) {
3796 xw.state &= ~WIN_VISIBLE;
3797 } else if(!(xw.state & WIN_VISIBLE)) {
3798 /* need a full redraw for next Expose, not just a buf copy */
3799 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3805 xw.state &= ~WIN_VISIBLE;
3809 xsetpointermotion(int set) {
3810 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3811 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3815 xseturgency(int add) {
3816 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3818 MODBIT(h->flags, add, XUrgencyHint);
3819 XSetWMHints(xw.dpy, xw.win, h);
3825 XFocusChangeEvent *e = &ev->xfocus;
3827 if(e->mode == NotifyGrab)
3830 if(ev->type == FocusIn) {
3831 XSetICFocus(xw.xic);
3832 xw.state |= WIN_FOCUSED;
3834 if(IS_SET(MODE_FOCUS))
3835 ttywrite("\033[I", 3);
3837 XUnsetICFocus(xw.xic);
3838 xw.state &= ~WIN_FOCUSED;
3839 if(IS_SET(MODE_FOCUS))
3840 ttywrite("\033[O", 3);
3845 match(uint mask, uint state) {
3846 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3850 numlock(const Arg *dummy) {
3855 kmap(KeySym k, uint state) {
3859 /* Check for mapped keys out of X11 function keys. */
3860 for(i = 0; i < LEN(mappedkeys); i++) {
3861 if(mappedkeys[i] == k)
3864 if(i == LEN(mappedkeys)) {
3865 if((k & 0xFFFF) < 0xFD00)
3869 for(kp = key; kp < key + LEN(key); kp++) {
3873 if(!match(kp->mask, state))
3876 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3878 if(term.numlock && kp->appkey == 2)
3881 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3884 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3894 kpress(XEvent *ev) {
3895 XKeyEvent *e = &ev->xkey;
3897 char buf[32], *customkey;
3903 if(IS_SET(MODE_KBDLOCK))
3906 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3908 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3909 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3910 bp->func(&(bp->arg));
3915 /* 2. custom keys from config.h */
3916 if((customkey = kmap(ksym, e->state))) {
3917 ttysend(customkey, strlen(customkey));
3921 /* 3. composed string from input method */
3924 if(len == 1 && e->state & Mod1Mask) {
3925 if(IS_SET(MODE_8BIT)) {
3928 len = utf8encode(c, buf, UTF_SIZ);
3941 cmessage(XEvent *e) {
3944 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3946 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3947 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3948 xw.state |= WIN_FOCUSED;
3950 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3951 xw.state &= ~WIN_FOCUSED;
3953 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3954 /* Send SIGHUP to shell */
3961 cresize(int width, int height) {
3969 col = (xw.w - 2 * borderpx) / xw.cw;
3970 row = (xw.h - 2 * borderpx) / xw.ch;
3979 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3982 cresize(e->xconfigure.width, e->xconfigure.height);
3988 int w = xw.w, h = xw.h;
3990 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3991 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
3994 /* Waiting for window mapping */
3996 XNextEvent(xw.dpy, &ev);
3997 if(XFilterEvent(&ev, None))
3999 if(ev.type == ConfigureNotify) {
4000 w = ev.xconfigure.width;
4001 h = ev.xconfigure.height;
4002 } else if(ev.type == MapNotify) {
4010 clock_gettime(CLOCK_MONOTONIC, &last);
4013 for(xev = actionfps;;) {
4015 FD_SET(cmdfd, &rfd);
4018 if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
4021 die("select failed: %s\n", strerror(errno));
4023 if(FD_ISSET(cmdfd, &rfd)) {
4027 if(FD_ISSET(xfd, &rfd)) {
4031 MODBIT(term.mode, 1, MODE_BLINK);
4036 clock_gettime(CLOCK_MONOTONIC, &now);
4037 drawtimeout.tv_sec = 0;
4038 drawtimeout.tv_nsec = (1000/xfps) * 1E6;
4042 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
4043 tsetdirtattr(ATTR_BLINK);
4044 term.mode ^= MODE_BLINK;
4048 deltatime = TIMEDIFF(now, last);
4049 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
4056 while(XPending(xw.dpy)) {
4057 XNextEvent(xw.dpy, &ev);
4058 if(XFilterEvent(&ev, None))
4060 if(handler[ev.type])
4061 (handler[ev.type])(&ev);
4067 if(xev && !FD_ISSET(xfd, &rfd))
4069 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
4071 if(TIMEDIFF(now, lastblink) \
4073 drawtimeout.tv_nsec = 1000;
4075 drawtimeout.tv_nsec = (1E6 * \
4080 drawtimeout.tv_sec = \
4081 drawtimeout.tv_nsec / 1E9;
4082 drawtimeout.tv_nsec %= (long)1E9;
4093 die("%s " VERSION " (c) 2010-2015 st engineers\n" \
4094 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4095 " [-i] [-t title] [-w windowid] [-e command ...]\n", argv0);
4099 main(int argc, char *argv[]) {
4101 uint cols = 80, rows = 24;
4109 allowaltscreen = false;
4112 opt_class = EARGF(usage());
4115 /* eat all remaining arguments */
4118 if(argv[1] != NULL && opt_title == NULL) {
4119 titles = xstrdup(argv[1]);
4120 opt_title = basename(titles);
4125 opt_font = EARGF(usage());
4128 xw.gm = XParseGeometry(EARGF(usage()),
4129 &xw.l, &xw.t, &cols, &rows);
4135 opt_io = EARGF(usage());
4138 opt_title = EARGF(usage());
4141 opt_embed = EARGF(usage());
4149 setlocale(LC_CTYPE, "");
4150 XSetLocaleModifiers("");
4151 tnew(cols? cols : 1, rows? rows : 1);