1 /* See LICENSE for license 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 ISDELIM(u) (BETWEEN(u, 0, 127) && strchr(worddelimiters, u) != NULL)
76 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
77 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
78 #define IS_SET(flag) ((term.mode & (flag)) != 0)
79 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_nsec-t2.tv_nsec)/1E6)
80 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
82 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
83 #define IS_TRUECOL(x) (1 << 24 & (x))
84 #define TRUERED(x) (((x) & 0xff0000) >> 8)
85 #define TRUEGREEN(x) (((x) & 0xff00))
86 #define TRUEBLUE(x) (((x) & 0xff) << 8)
89 enum glyph_attribute {
94 ATTR_UNDERLINE = 1 << 3,
96 ATTR_REVERSE = 1 << 5,
97 ATTR_INVISIBLE = 1 << 6,
101 ATTR_WDUMMY = 1 << 10,
104 enum cursor_movement {
117 MODE_INSERT = 1 << 1,
118 MODE_APPKEYPAD = 1 << 2,
119 MODE_ALTSCREEN = 1 << 3,
121 MODE_MOUSEBTN = 1 << 5,
122 MODE_MOUSEMOTION = 1 << 6,
123 MODE_REVERSE = 1 << 7,
124 MODE_KBDLOCK = 1 << 8,
127 MODE_APPCURSOR = 1 << 11,
128 MODE_MOUSESGR = 1 << 12,
130 MODE_BLINK = 1 << 14,
131 MODE_FBLINK = 1 << 15,
132 MODE_FOCUS = 1 << 16,
133 MODE_MOUSEX10 = 1 << 17,
134 MODE_MOUSEMANY = 1 << 18,
135 MODE_BRCKTPASTE = 1 << 19,
136 MODE_PRINT = 1 << 20,
137 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
154 ESC_STR = 4, /* DCS, OSC, PM, APC */
156 ESC_STR_END = 16, /* a final string was encountered */
157 ESC_TEST = 32, /* Enter in test mode */
165 enum selection_mode {
171 enum selection_type {
176 enum selection_snap {
181 typedef unsigned char uchar;
182 typedef unsigned int uint;
183 typedef unsigned long ulong;
184 typedef unsigned short ushort;
186 typedef XftDraw *Draw;
187 typedef XftColor Color;
190 long u; /* character code */
191 ushort mode; /* attribute flags */
192 ushort fg; /* foreground */
193 ushort bg; /* background */
199 Glyph attr; /* current char attributes */
205 /* CSI Escape sequence structs */
206 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
208 char buf[ESC_BUF_SIZ]; /* raw string */
209 int len; /* raw string length */
211 int arg[ESC_ARG_SIZ];
212 int narg; /* nb of args */
216 /* STR Escape sequence structs */
217 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
219 char type; /* ESC type ... */
220 char buf[STR_BUF_SIZ]; /* raw string */
221 int len; /* raw string length */
222 char *args[STR_ARG_SIZ];
223 int narg; /* nb of args */
226 /* Internal representation of the screen */
228 int row; /* nb row */
229 int col; /* nb col */
230 Line *line; /* screen */
231 Line *alt; /* alternate screen */
232 bool *dirty; /* dirtyness of lines */
233 TCursor c; /* cursor */
234 int top; /* top scroll limit */
235 int bot; /* bottom scroll limit */
236 int mode; /* terminal mode flags */
237 int esc; /* escape state flags */
238 char trantbl[4]; /* charset table translation */
239 int charset; /* current charset */
240 int icharset; /* selected charset for sequence */
241 bool numlock; /* lock numbers in keyboard */
245 /* Purely graphic info */
251 Atom xembed, wmdeletewin, netwmname, netwmpid;
256 XSetWindowAttributes attrs;
258 bool isfixed; /* is fixed geometry? */
259 int l, t; /* left and top offset */
260 int gm; /* geometry mask */
261 int tw, th; /* tty width and height */
262 int w, h; /* window width and height */
263 int ch; /* char height */
264 int cw; /* char width */
265 char state; /* focus, redraw, visible */
266 int cursor; /* cursor style */
279 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
280 signed char appkey; /* application keypad */
281 signed char appcursor; /* application cursor */
282 signed char crlf; /* crlf mode */
290 * Selection variables:
291 * nb – normalized coordinates of the beginning of the selection
292 * ne – normalized coordinates of the end of the selection
293 * ob – original coordinates of the beginning of the selection
294 * oe – original coordinates of the end of the selection
300 char *primary, *clipboard;
303 struct timespec tclick1;
304 struct timespec tclick2;
317 void (*func)(const Arg *);
321 /* function definitions used in config.h */
322 static void clipcopy(const Arg *);
323 static void clippaste(const Arg *);
324 static void numlock(const Arg *);
325 static void selpaste(const Arg *);
326 static void xzoom(const Arg *);
327 static void xzoomabs(const Arg *);
328 static void xzoomreset(const Arg *);
329 static void printsel(const Arg *);
330 static void printscreen(const Arg *) ;
331 static void toggleprinter(const Arg *);
333 /* Config.h for applying patches and the configuration. */
349 /* Drawing Context */
351 Color col[MAX(LEN(colorname), 256)];
352 Font font, bfont, ifont, ibfont;
356 static void die(const char *, ...);
357 static void draw(void);
358 static void redraw(void);
359 static void drawregion(int, int, int, int);
360 static void execsh(void);
361 static void stty(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);
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(long);
393 static void treset(void);
394 static void tresize(int, int);
395 static void tscrollup(int, int);
396 static void tscrolldown(int, int);
397 static void tsetattr(int *, int);
398 static void tsetchar(long, 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(long);
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);
418 static inline ushort sixd_to_16bit(int);
419 static void xdraws(char *, Glyph, int, int, int, int);
420 static void xdrawglyph(Glyph, int, int);
421 static void xhints(void);
422 static void xclear(int, int, int, int);
423 static void xdrawcursor(void);
424 static void xinit(void);
425 static void xloadcols(void);
426 static int xsetcolorname(int, const char *);
427 static int xgeommasktogravity(int);
428 static int xloadfont(Font *, FcPattern *);
429 static void xloadfonts(char *, double);
430 static void xsettitle(char *);
431 static void xresettitle(void);
432 static void xsetpointermotion(int);
433 static void xseturgency(int);
434 static void xsetsel(char *, Time);
435 static void xtermclear(int, int, int, int);
436 static void xunloadfont(Font *);
437 static void xunloadfonts(void);
438 static void xresize(int, int);
440 static void expose(XEvent *);
441 static void visibility(XEvent *);
442 static void unmap(XEvent *);
443 static char *kmap(KeySym, uint);
444 static void kpress(XEvent *);
445 static void cmessage(XEvent *);
446 static void cresize(int, int);
447 static void resize(XEvent *);
448 static void focus(XEvent *);
449 static void brelease(XEvent *);
450 static void bpress(XEvent *);
451 static void bmotion(XEvent *);
452 static void selnotify(XEvent *);
453 static void selclear(XEvent *);
454 static void selrequest(XEvent *);
456 static void selinit(void);
457 static void selnormalize(void);
458 static inline bool selected(int, int);
459 static char *getsel(void);
460 static void selcopy(Time);
461 static void selscroll(int, int);
462 static void selsnap(int *, int *, int);
463 static int x2col(int);
464 static int y2row(int);
465 static void getbuttoninfo(XEvent *);
466 static void mousereport(XEvent *);
468 static size_t utf8decode(char *, long *, size_t);
469 static long utf8decodebyte(char, size_t *);
470 static size_t utf8encode(long, char *);
471 static char utf8encodebyte(long, size_t);
472 static size_t utf8validate(long *, size_t);
474 static ssize_t xwrite(int, const char *, size_t);
475 static void *xmalloc(size_t);
476 static void *xrealloc(void *, size_t);
477 static char *xstrdup(char *);
479 static void usage(void);
481 static void (*handler[LASTEvent])(XEvent *) = {
483 [ClientMessage] = cmessage,
484 [ConfigureNotify] = resize,
485 [VisibilityNotify] = visibility,
486 [UnmapNotify] = unmap,
490 [MotionNotify] = bmotion,
491 [ButtonPress] = bpress,
492 [ButtonRelease] = brelease,
494 * Uncomment if you want the selection to disappear when you select something
495 * different in another window.
497 /* [SelectionClear] = selclear, */
498 [SelectionNotify] = selnotify,
499 [SelectionRequest] = selrequest,
506 static CSIEscape csiescseq;
507 static STREscape strescseq;
510 static Selection sel;
511 static int iofd = STDOUT_FILENO;
512 static char **opt_cmd = NULL;
513 static char *opt_io = NULL;
514 static char *opt_title = NULL;
515 static char *opt_embed = NULL;
516 static char *opt_class = NULL;
517 static char *opt_font = NULL;
518 static char *opt_line = NULL;
519 static int oldbutton = 3; /* button event on startup: 3 = release */
521 static char *usedfont = NULL;
522 static double usedfontsize = 0;
523 static double defaultfontsize = 0;
525 static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
526 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
527 static long utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
528 static long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
530 /* Font Ring Cache */
544 /* Fontcache is an array now. A new font will be appended to the array. */
545 static Fontcache frc[16];
546 static int frclen = 0;
549 xwrite(int fd, const char *s, size_t len) {
553 ssize_t r = write(fd, s, len);
563 xmalloc(size_t len) {
564 void *p = malloc(len);
567 die("Out of memory\n");
573 xrealloc(void *p, size_t len) {
574 if((p = realloc(p, len)) == NULL)
575 die("Out of memory\n");
582 if((s = strdup(s)) == NULL)
583 die("Out of memory\n");
589 utf8decode(char *c, long *u, size_t clen) {
590 size_t i, j, len, type;
596 udecoded = utf8decodebyte(c[0], &len);
597 if(!BETWEEN(len, 1, UTF_SIZ))
599 for(i = 1, j = 1; i < clen && j < len; ++i, ++j) {
600 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
607 utf8validate(u, len);
612 utf8decodebyte(char c, size_t *i) {
613 for(*i = 0; *i < LEN(utfmask); ++(*i))
614 if(((uchar)c & utfmask[*i]) == utfbyte[*i])
615 return (uchar)c & ~utfmask[*i];
620 utf8encode(long u, char *c) {
623 len = utf8validate(&u, 0);
626 for(i = len - 1; i != 0; --i) {
627 c[i] = utf8encodebyte(u, 0);
630 c[0] = utf8encodebyte(u, len);
635 utf8encodebyte(long u, size_t i) {
636 return utfbyte[i] | (u & ~utfmask[i]);
640 utf8validate(long *u, size_t i) {
641 if(!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
643 for(i = 1; *u > utfmax[i]; ++i)
650 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
651 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
655 sel.clipboard = NULL;
656 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
657 if(sel.xtarget == None)
658 sel.xtarget = XA_STRING;
666 return LIMIT(x, 0, term.col-1);
674 return LIMIT(y, 0, term.row-1);
681 if(term.line[y][i - 1].mode & ATTR_WRAP)
684 while(i > 0 && term.line[y][i - 1].u == ' ')
694 if(sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
695 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
696 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
698 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
699 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
701 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
702 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
704 selsnap(&sel.nb.x, &sel.nb.y, -1);
705 selsnap(&sel.ne.x, &sel.ne.y, +1);
707 /* expand selection over line breaks */
708 if (sel.type == SEL_RECTANGULAR)
710 i = tlinelen(sel.nb.y);
713 if (tlinelen(sel.ne.y) <= sel.ne.x)
714 sel.ne.x = term.col - 1;
718 selected(int x, int y) {
719 if(sel.mode == SEL_EMPTY)
722 if(sel.type == SEL_RECTANGULAR)
723 return BETWEEN(y, sel.nb.y, sel.ne.y)
724 && BETWEEN(x, sel.nb.x, sel.ne.x);
726 return BETWEEN(y, sel.nb.y, sel.ne.y)
727 && (y != sel.nb.y || x >= sel.nb.x)
728 && (y != sel.ne.y || x <= sel.ne.x);
732 selsnap(int *x, int *y, int direction) {
733 int newx, newy, xt, yt;
734 bool delim, prevdelim;
740 * Snap around if the word wraps around at the end or
741 * beginning of a line.
743 prevgp = &term.line[*y][*x];
744 prevdelim = ISDELIM(prevgp->u);
746 newx = *x + direction;
748 if(!BETWEEN(newx, 0, term.col - 1)) {
750 newx = (newx + term.col) % term.col;
751 if (!BETWEEN(newy, 0, term.row - 1))
757 yt = newy, xt = newx;
758 if(!(term.line[yt][xt].mode & ATTR_WRAP))
762 if (newx >= tlinelen(newy))
765 gp = &term.line[newy][newx];
766 delim = ISDELIM(gp->u);
767 if(!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
768 || (delim && gp->u != prevgp->u)))
779 * Snap around if the the previous line or the current one
780 * has set ATTR_WRAP at its end. Then the whole next or
781 * previous line will be selected.
783 *x = (direction < 0) ? 0 : term.col - 1;
785 for(; *y > 0; *y += direction) {
786 if(!(term.line[*y-1][term.col-1].mode
791 } else if(direction > 0) {
792 for(; *y < term.row-1; *y += direction) {
793 if(!(term.line[*y][term.col-1].mode
804 getbuttoninfo(XEvent *e) {
806 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
808 sel.alt = IS_SET(MODE_ALTSCREEN);
810 sel.oe.x = x2col(e->xbutton.x);
811 sel.oe.y = y2row(e->xbutton.y);
814 sel.type = SEL_REGULAR;
815 for(type = 1; type < LEN(selmasks); ++type) {
816 if(match(selmasks[type], state)) {
824 mousereport(XEvent *e) {
825 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
826 button = e->xbutton.button, state = e->xbutton.state,
832 if(e->xbutton.type == MotionNotify) {
833 if(x == ox && y == oy)
835 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
837 /* MOUSE_MOTION: no reporting if no button is pressed */
838 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
841 button = oldbutton + 32;
845 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
852 if(e->xbutton.type == ButtonPress) {
856 } else if(e->xbutton.type == ButtonRelease) {
858 /* MODE_MOUSEX10: no button release reporting */
859 if(IS_SET(MODE_MOUSEX10))
861 if (button == 64 || button == 65)
866 if(!IS_SET(MODE_MOUSEX10)) {
867 button += ((state & ShiftMask ) ? 4 : 0)
868 + ((state & Mod4Mask ) ? 8 : 0)
869 + ((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);
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. */
909 sel.mode = SEL_EMPTY;
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 sel.mode = SEL_READY;
929 tsetdirt(sel.nb.y, sel.ne.y);
930 sel.tclick2 = sel.tclick1;
938 int y, bufsize, lastx, linelen;
944 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
945 ptr = str = xmalloc(bufsize);
947 /* append every set & selected glyph to the selection */
948 for(y = sel.nb.y; y <= sel.ne.y; y++) {
949 linelen = tlinelen(y);
951 if(sel.type == SEL_RECTANGULAR) {
952 gp = &term.line[y][sel.nb.x];
955 gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
956 lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
958 last = &term.line[y][MIN(lastx, linelen-1)];
959 while(last >= gp && last->u == ' ')
962 for( ; gp <= last; ++gp) {
963 if(gp->mode & ATTR_WDUMMY)
966 ptr += utf8encode(gp->u, ptr);
970 * Copy and pasting of line endings is inconsistent
971 * in the inconsistent terminal and GUI world.
972 * The best solution seems like to produce '\n' when
973 * something is copied from st and convert '\n' to
974 * '\r', when something to be pasted is received by
976 * FIXME: Fix the computer world.
978 if((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
987 xsetsel(getsel(), t);
991 selnotify(XEvent *e) {
992 ulong nitems, ofs, rem;
994 uchar *data, *last, *repl;
996 XSelectionEvent *xsev;
999 xsev = &e->xselection;
1000 if (xsev->property == None)
1003 if(XGetWindowProperty(xw.dpy, xw.win, xsev->property, ofs,
1004 BUFSIZ/4, False, AnyPropertyType,
1005 &type, &format, &nitems, &rem,
1007 fprintf(stderr, "Clipboard allocation failed\n");
1012 * As seen in getsel:
1013 * Line endings are inconsistent in the terminal and GUI world
1014 * copy and pasting. When receiving some selection data,
1015 * replace all '\n' with '\r'.
1016 * FIXME: Fix the computer world.
1019 last = data + nitems * format / 8;
1020 while((repl = memchr(repl, '\n', last - repl))) {
1024 if(IS_SET(MODE_BRCKTPASTE))
1025 ttywrite("\033[200~", 6);
1026 ttysend((char *)data, nitems * format / 8);
1027 if(IS_SET(MODE_BRCKTPASTE))
1028 ttywrite("\033[201~", 6);
1030 /* number of 32-bit chunks returned */
1031 ofs += nitems * format / 32;
1036 selpaste(const Arg *dummy) {
1037 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1038 xw.win, CurrentTime);
1042 clipcopy(const Arg *dummy) {
1045 if(sel.clipboard != NULL)
1046 free(sel.clipboard);
1048 if(sel.primary != NULL) {
1049 sel.clipboard = xstrdup(sel.primary);
1050 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1051 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1056 clippaste(const Arg *dummy) {
1059 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1060 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1061 xw.win, CurrentTime);
1065 selclear(XEvent *e) {
1069 tsetdirt(sel.nb.y, sel.ne.y);
1073 selrequest(XEvent *e) {
1074 XSelectionRequestEvent *xsre;
1075 XSelectionEvent xev;
1076 Atom xa_targets, string, clipboard;
1079 xsre = (XSelectionRequestEvent *) e;
1080 xev.type = SelectionNotify;
1081 xev.requestor = xsre->requestor;
1082 xev.selection = xsre->selection;
1083 xev.target = xsre->target;
1084 xev.time = xsre->time;
1085 if (xsre->property == None)
1086 xsre->property = xsre->target;
1089 xev.property = None;
1091 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1092 if(xsre->target == xa_targets) {
1093 /* respond with the supported type */
1094 string = sel.xtarget;
1095 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1096 XA_ATOM, 32, PropModeReplace,
1097 (uchar *) &string, 1);
1098 xev.property = xsre->property;
1099 } else if(xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1101 * xith XA_STRING non ascii characters may be incorrect in the
1102 * requestor. It is not our problem, use utf8.
1104 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1105 if(xsre->selection == XA_PRIMARY) {
1106 seltext = sel.primary;
1107 } else if(xsre->selection == clipboard) {
1108 seltext = sel.clipboard;
1111 "Unhandled clipboard selection 0x%lx\n",
1115 if(seltext != NULL) {
1116 XChangeProperty(xsre->display, xsre->requestor,
1117 xsre->property, xsre->target,
1119 (uchar *)seltext, strlen(seltext));
1120 xev.property = xsre->property;
1124 /* all done, send a notification to the listener */
1125 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1126 fprintf(stderr, "Error sending SelectionNotify event\n");
1130 xsetsel(char *str, Time t) {
1134 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
1135 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
1140 brelease(XEvent *e) {
1141 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1146 if(e->xbutton.button == Button2) {
1148 } else if(e->xbutton.button == Button1) {
1149 if(sel.mode == SEL_READY) {
1151 selcopy(e->xbutton.time);
1154 sel.mode = SEL_IDLE;
1155 tsetdirt(sel.nb.y, sel.ne.y);
1160 bmotion(XEvent *e) {
1161 int oldey, oldex, oldsby, oldsey;
1163 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1171 sel.mode = SEL_READY;
1178 if(oldey != sel.oe.y || oldex != sel.oe.x)
1179 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1183 die(const char *errstr, ...) {
1186 va_start(ap, errstr);
1187 vfprintf(stderr, errstr, ap);
1194 char **args, *sh, *prog;
1195 const struct passwd *pw;
1196 char buf[sizeof(long) * 8 + 1];
1199 if((pw = getpwuid(getuid())) == NULL) {
1201 die("getpwuid:%s\n", strerror(errno));
1203 die("who are you?\n");
1206 if (!(sh = getenv("SHELL"))) {
1207 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1216 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1218 snprintf(buf, sizeof(buf), "%lu", xw.win);
1220 unsetenv("COLUMNS");
1222 unsetenv("TERMCAP");
1223 setenv("LOGNAME", pw->pw_name, 1);
1224 setenv("USER", pw->pw_name, 1);
1225 setenv("SHELL", sh, 1);
1226 setenv("HOME", pw->pw_dir, 1);
1227 setenv("TERM", termname, 1);
1228 setenv("WINDOWID", buf, 1);
1230 signal(SIGCHLD, SIG_DFL);
1231 signal(SIGHUP, SIG_DFL);
1232 signal(SIGINT, SIG_DFL);
1233 signal(SIGQUIT, SIG_DFL);
1234 signal(SIGTERM, SIG_DFL);
1235 signal(SIGALRM, SIG_DFL);
1238 _exit(EXIT_FAILURE);
1246 if((p = waitpid(pid, &stat, WNOHANG)) < 0)
1247 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1252 ret = WIFEXITED(stat) ? WEXITSTATUS(stat) : EXIT_FAILURE;
1253 if (ret != EXIT_SUCCESS)
1254 die("child finished with error '%d'\n", stat);
1262 char cmd[_POSIX_ARG_MAX], **p, *q, *s;
1265 if((n = strlen(stty_args)) > sizeof(cmd)-1)
1266 die("incorrect stty parameters\n");
1267 memcpy(cmd, stty_args, n);
1269 siz = sizeof(cmd) - n;
1270 for(p = opt_cmd; p && (s = *p); ++p) {
1271 if((n = strlen(s)) > siz-1)
1272 die("stty parameter length too long\n");
1274 q = memcpy(q, s, n);
1279 if (system(cmd) != 0)
1280 perror("Couldn't call stty");
1286 struct winsize w = {term.row, term.col, 0, 0};
1289 term.mode |= MODE_PRINT;
1290 iofd = (!strcmp(opt_io, "-")) ?
1292 open(opt_io, O_WRONLY | O_CREAT, 0666);
1294 fprintf(stderr, "Error opening %s:%s\n",
1295 opt_io, strerror(errno));
1300 if((cmdfd = open(opt_line, O_RDWR)) < 0)
1301 die("open line failed: %s\n", strerror(errno));
1302 close(STDIN_FILENO);
1308 /* seems to work fine on linux, openbsd and freebsd */
1309 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1310 die("openpty failed: %s\n", strerror(errno));
1312 switch(pid = fork()) {
1314 die("fork failed\n");
1318 setsid(); /* create a new process group */
1319 dup2(s, STDIN_FILENO);
1320 dup2(s, STDOUT_FILENO);
1321 dup2(s, STDERR_FILENO);
1322 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1323 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1331 signal(SIGCHLD, sigchld);
1338 static char buf[BUFSIZ];
1339 static int buflen = 0;
1341 int charsize; /* size of utf8 char in bytes */
1345 /* append read bytes to unprocessed bytes */
1346 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1347 die("Couldn't read from shell: %s\n", strerror(errno));
1349 /* process every complete utf8 char */
1352 while((charsize = utf8decode(ptr, &unicodep, buflen))) {
1358 /* keep any uncomplete utf8 char for the next call */
1359 memmove(buf, ptr, buflen);
1363 ttywrite(const char *s, size_t n) {
1364 if(xwrite(cmdfd, s, n) == -1)
1365 die("write error on tty: %s\n", strerror(errno));
1369 ttysend(char *s, size_t n) {
1374 if(IS_SET(MODE_ECHO))
1375 while((len = utf8decode(s, &u, n)) > 0) {
1386 w.ws_row = term.row;
1387 w.ws_col = term.col;
1388 w.ws_xpixel = xw.tw;
1389 w.ws_ypixel = xw.th;
1390 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1391 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1395 tattrset(int attr) {
1398 for(i = 0; i < term.row-1; i++) {
1399 for(j = 0; j < term.col-1; j++) {
1400 if(term.line[i][j].mode & attr)
1409 tsetdirt(int top, int bot) {
1412 LIMIT(top, 0, term.row-1);
1413 LIMIT(bot, 0, term.row-1);
1415 for(i = top; i <= bot; i++)
1420 tsetdirtattr(int attr) {
1423 for(i = 0; i < term.row-1; i++) {
1424 for(j = 0; j < term.col-1; j++) {
1425 if(term.line[i][j].mode & attr) {
1435 tsetdirt(0, term.row-1);
1440 static TCursor c[2];
1441 bool alt = IS_SET(MODE_ALTSCREEN);
1443 if(mode == CURSOR_SAVE) {
1445 } else if(mode == CURSOR_LOAD) {
1447 tmoveto(c[alt].x, c[alt].y);
1455 term.c = (TCursor){{
1459 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1461 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1462 for(i = tabspaces; i < term.col; i += tabspaces)
1465 term.bot = term.row - 1;
1466 term.mode = MODE_WRAP;
1467 memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1470 for(i = 0; i < 2; i++) {
1472 tcursor(CURSOR_SAVE);
1473 tclearregion(0, 0, term.col-1, term.row-1);
1479 tnew(int col, int row) {
1480 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1489 Line *tmp = term.line;
1491 term.line = term.alt;
1493 term.mode ^= MODE_ALTSCREEN;
1498 tscrolldown(int orig, int n) {
1502 LIMIT(n, 0, term.bot-orig+1);
1504 tsetdirt(orig, term.bot-n);
1505 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1507 for(i = term.bot; i >= orig+n; i--) {
1508 temp = term.line[i];
1509 term.line[i] = term.line[i-n];
1510 term.line[i-n] = temp;
1517 tscrollup(int orig, int n) {
1521 LIMIT(n, 0, term.bot-orig+1);
1523 tclearregion(0, orig, term.col-1, orig+n-1);
1524 tsetdirt(orig+n, term.bot);
1526 for(i = orig; i <= term.bot-n; i++) {
1527 temp = term.line[i];
1528 term.line[i] = term.line[i+n];
1529 term.line[i+n] = temp;
1532 selscroll(orig, -n);
1536 selscroll(int orig, int n) {
1540 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1541 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1545 if(sel.type == SEL_RECTANGULAR) {
1546 if(sel.ob.y < term.top)
1547 sel.ob.y = term.top;
1548 if(sel.oe.y > term.bot)
1549 sel.oe.y = term.bot;
1551 if(sel.ob.y < term.top) {
1552 sel.ob.y = term.top;
1555 if(sel.oe.y > term.bot) {
1556 sel.oe.y = term.bot;
1557 sel.oe.x = term.col;
1565 tnewline(int first_col) {
1569 tscrollup(term.top, 1);
1573 tmoveto(first_col ? 0 : term.c.x, y);
1578 char *p = csiescseq.buf, *np;
1587 csiescseq.buf[csiescseq.len] = '\0';
1588 while(p < csiescseq.buf+csiescseq.len) {
1590 v = strtol(p, &np, 10);
1593 if(v == LONG_MAX || v == LONG_MIN)
1595 csiescseq.arg[csiescseq.narg++] = v;
1597 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1601 csiescseq.mode[0] = *p++;
1602 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1605 /* for absolute user moves, when decom is set */
1607 tmoveato(int x, int y) {
1608 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1612 tmoveto(int x, int y) {
1615 if(term.c.state & CURSOR_ORIGIN) {
1620 maxy = term.row - 1;
1622 term.c.state &= ~CURSOR_WRAPNEXT;
1623 term.c.x = LIMIT(x, 0, term.col-1);
1624 term.c.y = LIMIT(y, miny, maxy);
1628 tsetchar(long u, Glyph *attr, int x, int y) {
1629 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1630 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1631 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1632 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1633 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1634 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1635 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1636 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1637 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1641 * The table is proudly stolen from rxvt.
1643 if(term.trantbl[term.charset] == CS_GRAPHIC0 &&
1644 BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1645 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1647 if(term.line[y][x].mode & ATTR_WIDE) {
1648 if(x+1 < term.col) {
1649 term.line[y][x+1].u = ' ';
1650 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1652 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1653 term.line[y][x-1].u = ' ';
1654 term.line[y][x-1].mode &= ~ATTR_WIDE;
1658 term.line[y][x] = *attr;
1659 term.line[y][x].u = u;
1663 tclearregion(int x1, int y1, int x2, int y2) {
1668 temp = x1, x1 = x2, x2 = temp;
1670 temp = y1, y1 = y2, y2 = temp;
1672 LIMIT(x1, 0, term.col-1);
1673 LIMIT(x2, 0, term.col-1);
1674 LIMIT(y1, 0, term.row-1);
1675 LIMIT(y2, 0, term.row-1);
1677 for(y = y1; y <= y2; y++) {
1679 for(x = x1; x <= x2; x++) {
1680 gp = &term.line[y][x];
1683 gp->fg = term.c.attr.fg;
1684 gp->bg = term.c.attr.bg;
1692 tdeletechar(int n) {
1696 LIMIT(n, 0, term.col - term.c.x);
1700 size = term.col - src;
1701 line = term.line[term.c.y];
1703 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1704 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1708 tinsertblank(int n) {
1712 LIMIT(n, 0, term.col - term.c.x);
1716 size = term.col - dst;
1717 line = term.line[term.c.y];
1719 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1720 tclearregion(src, term.c.y, dst - 1, term.c.y);
1724 tinsertblankline(int n) {
1725 if(BETWEEN(term.c.y, term.top, term.bot))
1726 tscrolldown(term.c.y, n);
1730 tdeleteline(int n) {
1731 if(BETWEEN(term.c.y, term.top, term.bot))
1732 tscrollup(term.c.y, n);
1736 tdefcolor(int *attr, int *npar, int l) {
1740 switch (attr[*npar + 1]) {
1741 case 2: /* direct color in RGB space */
1742 if (*npar + 4 >= l) {
1744 "erresc(38): Incorrect number of parameters (%d)\n",
1748 r = attr[*npar + 2];
1749 g = attr[*npar + 3];
1750 b = attr[*npar + 4];
1752 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1753 fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1756 idx = TRUECOLOR(r, g, b);
1758 case 5: /* indexed color */
1759 if (*npar + 2 >= l) {
1761 "erresc(38): Incorrect number of parameters (%d)\n",
1766 if(!BETWEEN(attr[*npar], 0, 255))
1767 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1771 case 0: /* implemented defined (only foreground) */
1772 case 1: /* transparent */
1773 case 3: /* direct color in CMY space */
1774 case 4: /* direct color in CMYK space */
1777 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1785 tsetattr(int *attr, int l) {
1789 for(i = 0; i < l; i++) {
1792 term.c.attr.mode &= ~(
1801 term.c.attr.fg = defaultfg;
1802 term.c.attr.bg = defaultbg;
1805 term.c.attr.mode |= ATTR_BOLD;
1808 term.c.attr.mode |= ATTR_FAINT;
1811 term.c.attr.mode |= ATTR_ITALIC;
1814 term.c.attr.mode |= ATTR_UNDERLINE;
1816 case 5: /* slow blink */
1818 case 6: /* rapid blink */
1819 term.c.attr.mode |= ATTR_BLINK;
1822 term.c.attr.mode |= ATTR_REVERSE;
1825 term.c.attr.mode |= ATTR_INVISIBLE;
1828 term.c.attr.mode |= ATTR_STRUCK;
1831 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
1834 term.c.attr.mode &= ~ATTR_ITALIC;
1837 term.c.attr.mode &= ~ATTR_UNDERLINE;
1840 term.c.attr.mode &= ~ATTR_BLINK;
1843 term.c.attr.mode &= ~ATTR_REVERSE;
1846 term.c.attr.mode &= ~ATTR_INVISIBLE;
1849 term.c.attr.mode &= ~ATTR_STRUCK;
1852 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1853 term.c.attr.fg = idx;
1856 term.c.attr.fg = defaultfg;
1859 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1860 term.c.attr.bg = idx;
1863 term.c.attr.bg = defaultbg;
1866 if(BETWEEN(attr[i], 30, 37)) {
1867 term.c.attr.fg = attr[i] - 30;
1868 } else if(BETWEEN(attr[i], 40, 47)) {
1869 term.c.attr.bg = attr[i] - 40;
1870 } else if(BETWEEN(attr[i], 90, 97)) {
1871 term.c.attr.fg = attr[i] - 90 + 8;
1872 } else if(BETWEEN(attr[i], 100, 107)) {
1873 term.c.attr.bg = attr[i] - 100 + 8;
1876 "erresc(default): gfx attr %d unknown\n",
1877 attr[i]), csidump();
1885 tsetscroll(int t, int b) {
1888 LIMIT(t, 0, term.row-1);
1889 LIMIT(b, 0, term.row-1);
1900 tsetmode(bool priv, bool set, int *args, int narg) {
1904 for(lim = args + narg; args < lim; ++args) {
1907 case 1: /* DECCKM -- Cursor key */
1908 MODBIT(term.mode, set, MODE_APPCURSOR);
1910 case 5: /* DECSCNM -- Reverse video */
1912 MODBIT(term.mode, set, MODE_REVERSE);
1913 if(mode != term.mode)
1916 case 6: /* DECOM -- Origin */
1917 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1920 case 7: /* DECAWM -- Auto wrap */
1921 MODBIT(term.mode, set, MODE_WRAP);
1923 case 0: /* Error (IGNORED) */
1924 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1925 case 3: /* DECCOLM -- Column (IGNORED) */
1926 case 4: /* DECSCLM -- Scroll (IGNORED) */
1927 case 8: /* DECARM -- Auto repeat (IGNORED) */
1928 case 18: /* DECPFF -- Printer feed (IGNORED) */
1929 case 19: /* DECPEX -- Printer extent (IGNORED) */
1930 case 42: /* DECNRCM -- National characters (IGNORED) */
1931 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1933 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1934 MODBIT(term.mode, !set, MODE_HIDE);
1936 case 9: /* X10 mouse compatibility mode */
1937 xsetpointermotion(0);
1938 MODBIT(term.mode, 0, MODE_MOUSE);
1939 MODBIT(term.mode, set, MODE_MOUSEX10);
1941 case 1000: /* 1000: report button press */
1942 xsetpointermotion(0);
1943 MODBIT(term.mode, 0, MODE_MOUSE);
1944 MODBIT(term.mode, set, MODE_MOUSEBTN);
1946 case 1002: /* 1002: report motion on button press */
1947 xsetpointermotion(0);
1948 MODBIT(term.mode, 0, MODE_MOUSE);
1949 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1951 case 1003: /* 1003: enable all mouse motions */
1952 xsetpointermotion(set);
1953 MODBIT(term.mode, 0, MODE_MOUSE);
1954 MODBIT(term.mode, set, MODE_MOUSEMANY);
1956 case 1004: /* 1004: send focus events to tty */
1957 MODBIT(term.mode, set, MODE_FOCUS);
1959 case 1006: /* 1006: extended reporting mode */
1960 MODBIT(term.mode, set, MODE_MOUSESGR);
1963 MODBIT(term.mode, set, MODE_8BIT);
1965 case 1049: /* swap screen & set/restore cursor as xterm */
1966 if (!allowaltscreen)
1968 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1970 case 47: /* swap screen */
1972 if (!allowaltscreen)
1974 alt = IS_SET(MODE_ALTSCREEN);
1976 tclearregion(0, 0, term.col-1,
1979 if(set ^ alt) /* set is always 1 or 0 */
1985 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1987 case 2004: /* 2004: bracketed paste mode */
1988 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1990 /* Not implemented mouse modes. See comments there. */
1991 case 1001: /* mouse highlight mode; can hang the
1992 terminal by design when implemented. */
1993 case 1005: /* UTF-8 mouse mode; will confuse
1994 applications not supporting UTF-8
1996 case 1015: /* urxvt mangled mouse mode; incompatible
1997 and can be mistaken for other control
2001 "erresc: unknown private set/reset mode %d\n",
2007 case 0: /* Error (IGNORED) */
2009 case 2: /* KAM -- keyboard action */
2010 MODBIT(term.mode, set, MODE_KBDLOCK);
2012 case 4: /* IRM -- Insertion-replacement */
2013 MODBIT(term.mode, set, MODE_INSERT);
2015 case 12: /* SRM -- Send/Receive */
2016 MODBIT(term.mode, !set, MODE_ECHO);
2018 case 20: /* LNM -- Linefeed/new line */
2019 MODBIT(term.mode, set, MODE_CRLF);
2023 "erresc: unknown set/reset mode %d\n",
2036 switch(csiescseq.mode[0]) {
2039 fprintf(stderr, "erresc: unknown csi ");
2043 case '@': /* ICH -- Insert <n> blank char */
2044 DEFAULT(csiescseq.arg[0], 1);
2045 tinsertblank(csiescseq.arg[0]);
2047 case 'A': /* CUU -- Cursor <n> Up */
2048 DEFAULT(csiescseq.arg[0], 1);
2049 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2051 case 'B': /* CUD -- Cursor <n> Down */
2052 case 'e': /* VPR --Cursor <n> Down */
2053 DEFAULT(csiescseq.arg[0], 1);
2054 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2056 case 'i': /* MC -- Media Copy */
2057 switch(csiescseq.arg[0]) {
2062 tdumpline(term.c.y);
2068 term.mode &= ~MODE_PRINT;
2071 term.mode |= MODE_PRINT;
2075 case 'c': /* DA -- Device Attributes */
2076 if(csiescseq.arg[0] == 0)
2077 ttywrite(vtiden, sizeof(vtiden) - 1);
2079 case 'C': /* CUF -- Cursor <n> Forward */
2080 case 'a': /* HPR -- Cursor <n> Forward */
2081 DEFAULT(csiescseq.arg[0], 1);
2082 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2084 case 'D': /* CUB -- Cursor <n> Backward */
2085 DEFAULT(csiescseq.arg[0], 1);
2086 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2088 case 'E': /* CNL -- Cursor <n> Down and first col */
2089 DEFAULT(csiescseq.arg[0], 1);
2090 tmoveto(0, term.c.y+csiescseq.arg[0]);
2092 case 'F': /* CPL -- Cursor <n> Up and first col */
2093 DEFAULT(csiescseq.arg[0], 1);
2094 tmoveto(0, term.c.y-csiescseq.arg[0]);
2096 case 'g': /* TBC -- Tabulation clear */
2097 switch(csiescseq.arg[0]) {
2098 case 0: /* clear current tab stop */
2099 term.tabs[term.c.x] = 0;
2101 case 3: /* clear all the tabs */
2102 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2108 case 'G': /* CHA -- Move to <col> */
2110 DEFAULT(csiescseq.arg[0], 1);
2111 tmoveto(csiescseq.arg[0]-1, term.c.y);
2113 case 'H': /* CUP -- Move to <row> <col> */
2115 DEFAULT(csiescseq.arg[0], 1);
2116 DEFAULT(csiescseq.arg[1], 1);
2117 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2119 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2120 DEFAULT(csiescseq.arg[0], 1);
2121 tputtab(csiescseq.arg[0]);
2123 case 'J': /* ED -- Clear screen */
2125 switch(csiescseq.arg[0]) {
2127 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2128 if(term.c.y < term.row-1) {
2129 tclearregion(0, term.c.y+1, term.col-1,
2135 tclearregion(0, 0, term.col-1, term.c.y-1);
2136 tclearregion(0, term.c.y, term.c.x, term.c.y);
2139 tclearregion(0, 0, term.col-1, term.row-1);
2145 case 'K': /* EL -- Clear line */
2146 switch(csiescseq.arg[0]) {
2148 tclearregion(term.c.x, term.c.y, term.col-1,
2152 tclearregion(0, term.c.y, term.c.x, term.c.y);
2155 tclearregion(0, term.c.y, term.col-1, term.c.y);
2159 case 'S': /* SU -- Scroll <n> line up */
2160 DEFAULT(csiescseq.arg[0], 1);
2161 tscrollup(term.top, csiescseq.arg[0]);
2163 case 'T': /* SD -- Scroll <n> line down */
2164 DEFAULT(csiescseq.arg[0], 1);
2165 tscrolldown(term.top, csiescseq.arg[0]);
2167 case 'L': /* IL -- Insert <n> blank lines */
2168 DEFAULT(csiescseq.arg[0], 1);
2169 tinsertblankline(csiescseq.arg[0]);
2171 case 'l': /* RM -- Reset Mode */
2172 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2174 case 'M': /* DL -- Delete <n> lines */
2175 DEFAULT(csiescseq.arg[0], 1);
2176 tdeleteline(csiescseq.arg[0]);
2178 case 'X': /* ECH -- Erase <n> char */
2179 DEFAULT(csiescseq.arg[0], 1);
2180 tclearregion(term.c.x, term.c.y,
2181 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2183 case 'P': /* DCH -- Delete <n> char */
2184 DEFAULT(csiescseq.arg[0], 1);
2185 tdeletechar(csiescseq.arg[0]);
2187 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2188 DEFAULT(csiescseq.arg[0], 1);
2189 tputtab(-csiescseq.arg[0]);
2191 case 'd': /* VPA -- Move to <row> */
2192 DEFAULT(csiescseq.arg[0], 1);
2193 tmoveato(term.c.x, csiescseq.arg[0]-1);
2195 case 'h': /* SM -- Set terminal mode */
2196 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2198 case 'm': /* SGR -- Terminal attribute (color) */
2199 tsetattr(csiescseq.arg, csiescseq.narg);
2201 case 'n': /* DSR – Device Status Report (cursor position) */
2202 if (csiescseq.arg[0] == 6) {
2203 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2204 term.c.y+1, term.c.x+1);
2208 case 'r': /* DECSTBM -- Set Scrolling Region */
2209 if(csiescseq.priv) {
2212 DEFAULT(csiescseq.arg[0], 1);
2213 DEFAULT(csiescseq.arg[1], term.row);
2214 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2218 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2219 tcursor(CURSOR_SAVE);
2221 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2222 tcursor(CURSOR_LOAD);
2225 switch (csiescseq.mode[1]) {
2226 case 'q': /* DECSCUSR -- Set Cursor Style */
2227 DEFAULT(csiescseq.arg[0], 1);
2228 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2231 xw.cursor = csiescseq.arg[0];
2246 for(i = 0; i < csiescseq.len; i++) {
2247 c = csiescseq.buf[i] & 0xff;
2250 } else if(c == '\n') {
2252 } else if(c == '\r') {
2254 } else if(c == 0x1b) {
2257 printf("(%02x)", c);
2265 memset(&csiescseq, 0, sizeof(csiescseq));
2273 term.esc &= ~(ESC_STR_END|ESC_STR);
2275 par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2277 switch(strescseq.type) {
2278 case ']': /* OSC -- Operating System Command */
2284 xsettitle(strescseq.args[1]);
2286 case 4: /* color set */
2289 p = strescseq.args[2];
2291 case 104: /* color reset, here p = NULL */
2292 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2293 if(xsetcolorname(j, p)) {
2294 fprintf(stderr, "erresc: invalid color %s\n", p);
2297 * TODO if defaultbg color is changed, borders
2305 case 'k': /* old title set compatibility */
2306 xsettitle(strescseq.args[0]);
2308 case 'P': /* DCS -- Device Control String */
2309 case '_': /* APC -- Application Program Command */
2310 case '^': /* PM -- Privacy Message */
2314 fprintf(stderr, "erresc: unknown str ");
2321 char *p = strescseq.buf;
2324 strescseq.buf[strescseq.len] = '\0';
2329 while(strescseq.narg < STR_ARG_SIZ) {
2330 strescseq.args[strescseq.narg++] = p;
2331 while((c = *p) != ';' && c != '\0')
2344 printf("ESC%c", strescseq.type);
2345 for(i = 0; i < strescseq.len; i++) {
2346 c = strescseq.buf[i] & 0xff;
2349 } else if(isprint(c)) {
2351 } else if(c == '\n') {
2353 } else if(c == '\r') {
2355 } else if(c == 0x1b) {
2358 printf("(%02x)", c);
2366 memset(&strescseq, 0, sizeof(strescseq));
2370 tprinter(char *s, size_t len) {
2371 if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2372 fprintf(stderr, "Error writing in %s:%s\n",
2373 opt_io, strerror(errno));
2380 toggleprinter(const Arg *arg) {
2381 term.mode ^= MODE_PRINT;
2385 printscreen(const Arg *arg) {
2390 printsel(const Arg *arg) {
2398 if((ptr = getsel())) {
2399 tprinter(ptr, strlen(ptr));
2409 bp = &term.line[n][0];
2410 end = &bp[MIN(tlinelen(n), term.col) - 1];
2411 if(bp != end || bp->u != ' ') {
2412 for( ;bp <= end; ++bp)
2413 tprinter(buf, utf8encode(bp->u, buf));
2422 for(i = 0; i < term.row; ++i)
2431 while(x < term.col && n--)
2432 for(++x; x < term.col && !term.tabs[x]; ++x)
2436 for(--x; x > 0 && !term.tabs[x]; --x)
2439 term.c.x = LIMIT(x, 0, term.col-1);
2444 if(ISCONTROL(u)) { /* control code */
2449 } else if(u != '\n' && u != '\r' && u != '\t') {
2458 tdeftran(char ascii) {
2459 static char cs[] = "0B";
2460 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2463 if((p = strchr(cs, ascii)) == NULL) {
2464 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2466 term.trantbl[term.icharset] = vcs[p - cs];
2474 if(c == '8') { /* DEC screen alignment test. */
2475 for(x = 0; x < term.col; ++x) {
2476 for(y = 0; y < term.row; ++y)
2477 tsetchar('E', &term.c.attr, x, y);
2483 tstrsequence(uchar c) {
2485 case 0x90: /* DCS -- Device Control String */
2488 case 0x9f: /* APC -- Application Program Command */
2491 case 0x9e: /* PM -- Privacy Message */
2494 case 0x9d: /* OSC -- Operating System Command */
2500 term.esc |= ESC_STR;
2504 tcontrolcode(uchar ascii) {
2510 tmoveto(term.c.x-1, term.c.y);
2513 tmoveto(0, term.c.y);
2518 /* go to first col if the mode is set */
2519 tnewline(IS_SET(MODE_CRLF));
2521 case '\a': /* BEL */
2522 if(term.esc & ESC_STR_END) {
2523 /* backwards compatibility to xterm */
2526 if(!(xw.state & WIN_FOCUSED))
2529 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2532 case '\033': /* ESC */
2534 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2535 term.esc |= ESC_START;
2537 case '\016': /* SO (LS1 -- Locking shift 1) */
2538 case '\017': /* SI (LS0 -- Locking shift 0) */
2539 term.charset = 1 - (ascii - '\016');
2541 case '\032': /* SUB */
2542 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2543 case '\030': /* CAN */
2546 case '\005': /* ENQ (IGNORED) */
2547 case '\000': /* NUL (IGNORED) */
2548 case '\021': /* XON (IGNORED) */
2549 case '\023': /* XOFF (IGNORED) */
2550 case 0177: /* DEL (IGNORED) */
2552 case 0x84: /* TODO: IND */
2554 case 0x85: /* NEL -- Next line */
2555 tnewline(1); /* always go to first col */
2557 case 0x88: /* HTS -- Horizontal tab stop */
2558 term.tabs[term.c.x] = 1;
2560 case 0x8d: /* TODO: RI */
2561 case 0x8e: /* TODO: SS2 */
2562 case 0x8f: /* TODO: SS3 */
2563 case 0x98: /* TODO: SOS */
2565 case 0x9a: /* DECID -- Identify Terminal */
2566 ttywrite(vtiden, sizeof(vtiden) - 1);
2568 case 0x9b: /* TODO: CSI */
2569 case 0x9c: /* TODO: ST */
2571 case 0x90: /* DCS -- Device Control String */
2572 case 0x9f: /* APC -- Application Program Command */
2573 case 0x9e: /* PM -- Privacy Message */
2574 case 0x9d: /* OSC -- Operating System Command */
2575 tstrsequence(ascii);
2578 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2579 term.esc &= ~(ESC_STR_END|ESC_STR);
2583 * returns 1 when the sequence is finished and it hasn't to read
2584 * more characters for this sequence, otherwise 0
2587 eschandle(uchar ascii) {
2590 term.esc |= ESC_CSI;
2593 term.esc |= ESC_TEST;
2595 case 'P': /* DCS -- Device Control String */
2596 case '_': /* APC -- Application Program Command */
2597 case '^': /* PM -- Privacy Message */
2598 case ']': /* OSC -- Operating System Command */
2599 case 'k': /* old title set compatibility */
2600 tstrsequence(ascii);
2602 case 'n': /* LS2 -- Locking shift 2 */
2603 case 'o': /* LS3 -- Locking shift 3 */
2604 term.charset = 2 + (ascii - 'n');
2606 case '(': /* GZD4 -- set primary charset G0 */
2607 case ')': /* G1D4 -- set secondary charset G1 */
2608 case '*': /* G2D4 -- set tertiary charset G2 */
2609 case '+': /* G3D4 -- set quaternary charset G3 */
2610 term.icharset = ascii - '(';
2611 term.esc |= ESC_ALTCHARSET;
2613 case 'D': /* IND -- Linefeed */
2614 if(term.c.y == term.bot) {
2615 tscrollup(term.top, 1);
2617 tmoveto(term.c.x, term.c.y+1);
2620 case 'E': /* NEL -- Next line */
2621 tnewline(1); /* always go to first col */
2623 case 'H': /* HTS -- Horizontal tab stop */
2624 term.tabs[term.c.x] = 1;
2626 case 'M': /* RI -- Reverse index */
2627 if(term.c.y == term.top) {
2628 tscrolldown(term.top, 1);
2630 tmoveto(term.c.x, term.c.y-1);
2633 case 'Z': /* DECID -- Identify Terminal */
2634 ttywrite(vtiden, sizeof(vtiden) - 1);
2636 case 'c': /* RIS -- Reset to inital state */
2641 case '=': /* DECPAM -- Application keypad */
2642 term.mode |= MODE_APPKEYPAD;
2644 case '>': /* DECPNM -- Normal keypad */
2645 term.mode &= ~MODE_APPKEYPAD;
2647 case '7': /* DECSC -- Save Cursor */
2648 tcursor(CURSOR_SAVE);
2650 case '8': /* DECRC -- Restore Cursor */
2651 tcursor(CURSOR_LOAD);
2653 case '\\': /* ST -- String Terminator */
2654 if(term.esc & ESC_STR_END)
2658 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2659 (uchar) ascii, isprint(ascii)? ascii:'.');
2672 len = utf8encode(u, c);
2673 if((width = wcwidth(u)) == -1) {
2674 memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
2678 if(IS_SET(MODE_PRINT))
2680 control = ISCONTROL(u);
2683 * STR sequence must be checked before anything else
2684 * because it uses all following characters until it
2685 * receives a ESC, a SUB, a ST or any other C1 control
2688 if(term.esc & ESC_STR) {
2689 if(u == '\a' || u == 030 || u == 032 || u == 033 ||
2691 term.esc &= ~(ESC_START|ESC_STR);
2692 term.esc |= ESC_STR_END;
2693 } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2694 memmove(&strescseq.buf[strescseq.len], c, len);
2695 strescseq.len += len;
2699 * Here is a bug in terminals. If the user never sends
2700 * some code to stop the str or esc command, then st
2701 * will stop responding. But this is better than
2702 * silently failing with unknown characters. At least
2703 * then users will report back.
2705 * In the case users ever get fixed, here is the code:
2716 * Actions of control codes must be performed as soon they arrive
2717 * because they can be embedded inside a control sequence, and
2718 * they must not cause conflicts with sequences.
2723 * control codes are not shown ever
2726 } else if(term.esc & ESC_START) {
2727 if(term.esc & ESC_CSI) {
2728 csiescseq.buf[csiescseq.len++] = u;
2729 if(BETWEEN(u, 0x40, 0x7E)
2730 || csiescseq.len >= \
2731 sizeof(csiescseq.buf)-1) {
2737 } else if(term.esc & ESC_ALTCHARSET) {
2739 } else if(term.esc & ESC_TEST) {
2744 /* sequence already finished */
2748 * All characters which form part of a sequence are not
2753 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2756 gp = &term.line[term.c.y][term.c.x];
2757 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2758 gp->mode |= ATTR_WRAP;
2760 gp = &term.line[term.c.y][term.c.x];
2763 if(IS_SET(MODE_INSERT) && term.c.x+width < term.col)
2764 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
2766 if(term.c.x+width > term.col) {
2768 gp = &term.line[term.c.y][term.c.x];
2771 tsetchar(u, &term.c.attr, term.c.x, term.c.y);
2774 gp->mode |= ATTR_WIDE;
2775 if(term.c.x+1 < term.col) {
2777 gp[1].mode = ATTR_WDUMMY;
2780 if(term.c.x+width < term.col) {
2781 tmoveto(term.c.x+width, term.c.y);
2783 term.c.state |= CURSOR_WRAPNEXT;
2788 tresize(int col, int row) {
2790 int minrow = MIN(row, term.row);
2791 int mincol = MIN(col, term.col);
2795 if(col < 1 || row < 1) {
2797 "tresize: error resizing to %dx%d\n", col, row);
2802 * slide screen to keep cursor where we expect it -
2803 * tscrollup would work here, but we can optimize to
2804 * memmove because we're freeing the earlier lines
2806 for(i = 0; i <= term.c.y - row; i++) {
2810 /* ensure that both src and dst are not NULL */
2812 memmove(term.line, term.line + i, row * sizeof(Line));
2813 memmove(term.alt, term.alt + i, row * sizeof(Line));
2815 for(i += row; i < term.row; i++) {
2820 /* resize to new height */
2821 term.line = xrealloc(term.line, row * sizeof(Line));
2822 term.alt = xrealloc(term.alt, row * sizeof(Line));
2823 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2824 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2826 /* resize each row to new width, zero-pad if needed */
2827 for(i = 0; i < minrow; i++) {
2828 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2829 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2832 /* allocate any new rows */
2833 for(/* i == minrow */; i < row; i++) {
2834 term.line[i] = xmalloc(col * sizeof(Glyph));
2835 term.alt[i] = xmalloc(col * sizeof(Glyph));
2837 if(col > term.col) {
2838 bp = term.tabs + term.col;
2840 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2841 while(--bp > term.tabs && !*bp)
2843 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2846 /* update terminal size */
2849 /* reset scrolling region */
2850 tsetscroll(0, row-1);
2851 /* make use of the LIMIT in tmoveto */
2852 tmoveto(term.c.x, term.c.y);
2853 /* Clearing both screens (it makes dirty all lines) */
2855 for(i = 0; i < 2; i++) {
2856 if(mincol < col && 0 < minrow) {
2857 tclearregion(mincol, 0, col - 1, minrow - 1);
2859 if(0 < col && minrow < row) {
2860 tclearregion(0, minrow, col - 1, row - 1);
2863 tcursor(CURSOR_LOAD);
2869 xresize(int col, int row) {
2870 xw.tw = MAX(1, col * xw.cw);
2871 xw.th = MAX(1, row * xw.ch);
2873 XFreePixmap(xw.dpy, xw.buf);
2874 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2875 DefaultDepth(xw.dpy, xw.scr));
2876 XftDrawChange(xw.draw, xw.buf);
2877 xclear(0, 0, xw.w, xw.h);
2881 sixd_to_16bit(int x) {
2882 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2886 xloadcolor(int i, const char *name, Color *ncolor) {
2887 XRenderColor color = { .alpha = 0xffff };
2890 if(BETWEEN(i, 16, 255)) { /* 256 color */
2891 if(i < 6*6*6+16) { /* same colors as xterm */
2892 color.red = sixd_to_16bit( ((i-16)/36)%6 );
2893 color.green = sixd_to_16bit( ((i-16)/6) %6 );
2894 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
2895 } else { /* greyscale */
2896 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
2897 color.green = color.blue = color.red;
2899 return XftColorAllocValue(xw.dpy, xw.vis,
2900 xw.cmap, &color, ncolor);
2902 name = colorname[i];
2904 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
2914 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
2915 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2918 for(i = 0; i < LEN(dc.col); i++)
2919 if(!xloadcolor(i, NULL, &dc.col[i])) {
2921 die("Could not allocate color '%s'\n", colorname[i]);
2923 die("Could not allocate color %d\n", i);
2929 xsetcolorname(int x, const char *name) {
2932 if(!BETWEEN(x, 0, LEN(dc.col)))
2936 if(!xloadcolor(x, name, &ncolor))
2939 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2945 xtermclear(int col1, int row1, int col2, int row2) {
2946 XftDrawRect(xw.draw,
2947 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2948 borderpx + col1 * xw.cw,
2949 borderpx + row1 * xw.ch,
2950 (col2-col1+1) * xw.cw,
2951 (row2-row1+1) * xw.ch);
2955 * Absolute coordinates.
2958 xclear(int x1, int y1, int x2, int y2) {
2959 XftDrawRect(xw.draw,
2960 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2961 x1, y1, x2-x1, y2-y1);
2966 XClassHint class = {opt_class ? opt_class : termname, termname};
2967 XWMHints wm = {.flags = InputHint, .input = 1};
2968 XSizeHints *sizeh = NULL;
2970 sizeh = XAllocSizeHints();
2972 sizeh->flags = PSize | PResizeInc | PBaseSize;
2973 sizeh->height = xw.h;
2974 sizeh->width = xw.w;
2975 sizeh->height_inc = xw.ch;
2976 sizeh->width_inc = xw.cw;
2977 sizeh->base_height = 2 * borderpx;
2978 sizeh->base_width = 2 * borderpx;
2979 if(xw.isfixed == True) {
2980 sizeh->flags |= PMaxSize | PMinSize;
2981 sizeh->min_width = sizeh->max_width = xw.w;
2982 sizeh->min_height = sizeh->max_height = xw.h;
2984 if(xw.gm & (XValue|YValue)) {
2985 sizeh->flags |= USPosition | PWinGravity;
2988 sizeh->win_gravity = xgeommasktogravity(xw.gm);
2991 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
2997 xgeommasktogravity(int mask) {
2998 switch(mask & (XNegative|YNegative)) {
3000 return NorthWestGravity;
3002 return NorthEastGravity;
3004 return SouthWestGravity;
3006 return SouthEastGravity;
3010 xloadfont(Font *f, FcPattern *pattern) {
3014 match = FcFontMatch(NULL, pattern, &result);
3018 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3019 FcPatternDestroy(match);
3024 f->pattern = FcPatternDuplicate(pattern);
3026 f->ascent = f->match->ascent;
3027 f->descent = f->match->descent;
3029 f->rbearing = f->match->max_advance_width;
3031 f->height = f->ascent + f->descent;
3032 f->width = f->lbearing + f->rbearing;
3038 xloadfonts(char *fontstr, double fontsize) {
3040 FcResult r_sz, r_psz;
3044 if(fontstr[0] == '-') {
3045 pattern = XftXlfdParse(fontstr, False, False);
3047 pattern = FcNameParse((FcChar8 *)fontstr);
3051 die("st: can't open font %s\n", fontstr);
3054 FcPatternDel(pattern, FC_PIXEL_SIZE);
3055 FcPatternDel(pattern, FC_SIZE);
3056 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3057 usedfontsize = fontsize;
3059 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
3060 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
3061 if(r_psz == FcResultMatch) {
3062 usedfontsize = fontval;
3063 } else if(r_sz == FcResultMatch) {
3067 * Default font size is 12, if none given. This is to
3068 * have a known usedfontsize value.
3070 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3073 defaultfontsize = usedfontsize;
3076 FcConfigSubstitute(0, pattern, FcMatchPattern);
3077 FcDefaultSubstitute(pattern);
3079 if(xloadfont(&dc.font, pattern))
3080 die("st: can't open font %s\n", fontstr);
3082 if(usedfontsize < 0) {
3083 FcPatternGetDouble(dc.font.match->pattern,
3084 FC_PIXEL_SIZE, 0, &fontval);
3085 usedfontsize = fontval;
3087 defaultfontsize = fontval;
3090 /* Setting character width and height. */
3091 xw.cw = ceilf(dc.font.width * cwscale);
3092 xw.ch = ceilf(dc.font.height * chscale);
3094 FcPatternDel(pattern, FC_SLANT);
3095 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3096 if(xloadfont(&dc.ifont, pattern))
3097 die("st: can't open font %s\n", fontstr);
3099 FcPatternDel(pattern, FC_WEIGHT);
3100 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3101 if(xloadfont(&dc.ibfont, pattern))
3102 die("st: can't open font %s\n", fontstr);
3104 FcPatternDel(pattern, FC_SLANT);
3105 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3106 if(xloadfont(&dc.bfont, pattern))
3107 die("st: can't open font %s\n", fontstr);
3109 FcPatternDestroy(pattern);
3113 xunloadfont(Font *f) {
3114 XftFontClose(xw.dpy, f->match);
3115 FcPatternDestroy(f->pattern);
3117 FcFontSetDestroy(f->set);
3121 xunloadfonts(void) {
3122 /* Free the loaded fonts in the font cache. */
3124 XftFontClose(xw.dpy, frc[--frclen].font);
3126 xunloadfont(&dc.font);
3127 xunloadfont(&dc.bfont);
3128 xunloadfont(&dc.ifont);
3129 xunloadfont(&dc.ibfont);
3133 xzoom(const Arg *arg) {
3136 larg.i = usedfontsize + arg->i;
3141 xzoomabs(const Arg *arg) {
3143 xloadfonts(usedfont, arg->i);
3150 xzoomreset(const Arg *arg) {
3153 if(defaultfontsize > 0) {
3154 larg.i = defaultfontsize;
3164 pid_t thispid = getpid();
3166 if(!(xw.dpy = XOpenDisplay(NULL)))
3167 die("Can't open display\n");
3168 xw.scr = XDefaultScreen(xw.dpy);
3169 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3173 die("Could not init fontconfig.\n");
3175 usedfont = (opt_font == NULL)? font : opt_font;
3176 xloadfonts(usedfont, 0);
3179 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3182 /* adjust fixed window geometry */
3183 xw.w = 2 * borderpx + term.col * xw.cw;
3184 xw.h = 2 * borderpx + term.row * xw.ch;
3185 if(xw.gm & XNegative)
3186 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3187 if(xw.gm & YNegative)
3188 xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
3191 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3192 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3193 xw.attrs.bit_gravity = NorthWestGravity;
3194 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3195 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3196 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3197 xw.attrs.colormap = xw.cmap;
3199 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3200 parent = XRootWindow(xw.dpy, xw.scr);
3201 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3202 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3203 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3204 | CWEventMask | CWColormap, &xw.attrs);
3206 memset(&gcvalues, 0, sizeof(gcvalues));
3207 gcvalues.graphics_exposures = False;
3208 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3210 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3211 DefaultDepth(xw.dpy, xw.scr));
3212 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3213 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3215 /* Xft rendering context */
3216 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3219 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3220 XSetLocaleModifiers("@im=local");
3221 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3222 XSetLocaleModifiers("@im=");
3223 if((xw.xim = XOpenIM(xw.dpy,
3224 NULL, NULL, NULL)) == NULL) {
3225 die("XOpenIM failed. Could not open input"
3230 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3231 | XIMStatusNothing, XNClientWindow, xw.win,
3232 XNFocusWindow, xw.win, NULL);
3234 die("XCreateIC failed. Could not obtain input method.\n");
3236 /* white cursor, black outline */
3237 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3238 XDefineCursor(xw.dpy, xw.win, cursor);
3239 XRecolorCursor(xw.dpy, cursor,
3240 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3241 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3243 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3244 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3245 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3246 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3248 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3249 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3250 PropModeReplace, (uchar *)&thispid, 1);
3253 XMapWindow(xw.dpy, xw.win);
3255 XSync(xw.dpy, False);
3259 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3260 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3261 width = charlen * xw.cw, xp, i;
3262 int frcflags, charexists;
3263 int u8fl, u8fblen, u8cblen, doesexist;
3266 Font *font = &dc.font;
3268 FcPattern *fcpattern, *fontpattern;
3269 FcFontSet *fcsets[] = { NULL };
3270 FcCharSet *fccharset;
3271 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3272 XRenderColor colfg, colbg;
3276 frcflags = FRC_NORMAL;
3278 if(base.mode & ATTR_ITALIC) {
3279 if(base.fg == defaultfg)
3280 base.fg = defaultitalic;
3282 frcflags = FRC_ITALIC;
3283 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3284 if(base.fg == defaultfg)
3285 base.fg = defaultitalic;
3287 frcflags = FRC_ITALICBOLD;
3288 } else if(base.mode & ATTR_UNDERLINE) {
3289 if(base.fg == defaultfg)
3290 base.fg = defaultunderline;
3293 if(IS_TRUECOL(base.fg)) {
3294 colfg.alpha = 0xffff;
3295 colfg.red = TRUERED(base.fg);
3296 colfg.green = TRUEGREEN(base.fg);
3297 colfg.blue = TRUEBLUE(base.fg);
3298 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3301 fg = &dc.col[base.fg];
3304 if(IS_TRUECOL(base.bg)) {
3305 colbg.alpha = 0xffff;
3306 colbg.green = TRUEGREEN(base.bg);
3307 colbg.red = TRUERED(base.bg);
3308 colbg.blue = TRUEBLUE(base.bg);
3309 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3312 bg = &dc.col[base.bg];
3315 if(base.mode & ATTR_BOLD) {
3317 * change basic system colors [0-7]
3318 * to bright system colors [8-15]
3320 if(BETWEEN(base.fg, 0, 7) && !(base.mode & ATTR_FAINT))
3321 fg = &dc.col[base.fg + 8];
3323 if(base.mode & ATTR_ITALIC) {
3325 frcflags = FRC_ITALICBOLD;
3328 frcflags = FRC_BOLD;
3332 if(IS_SET(MODE_REVERSE)) {
3333 if(fg == &dc.col[defaultfg]) {
3334 fg = &dc.col[defaultbg];
3336 colfg.red = ~fg->color.red;
3337 colfg.green = ~fg->color.green;
3338 colfg.blue = ~fg->color.blue;
3339 colfg.alpha = fg->color.alpha;
3340 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3345 if(bg == &dc.col[defaultbg]) {
3346 bg = &dc.col[defaultfg];
3348 colbg.red = ~bg->color.red;
3349 colbg.green = ~bg->color.green;
3350 colbg.blue = ~bg->color.blue;
3351 colbg.alpha = bg->color.alpha;
3352 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3358 if(base.mode & ATTR_REVERSE) {
3364 if(base.mode & ATTR_FAINT && !(base.mode & ATTR_BOLD)) {
3365 colfg.red = fg->color.red / 2;
3366 colfg.green = fg->color.green / 2;
3367 colfg.blue = fg->color.blue / 2;
3368 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3372 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3375 if(base.mode & ATTR_INVISIBLE)
3378 /* Intelligent cleaning up of the borders. */
3380 xclear(0, (y == 0)? 0 : winy, borderpx,
3381 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3383 if(x + charlen >= term.col) {
3384 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3385 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3388 xclear(winx, 0, winx + width, borderpx);
3390 xclear(winx, winy + xw.ch, winx + width, xw.h);
3392 /* Clean up the region we want to draw to. */
3393 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3395 /* Set the clip region because Xft is sometimes dirty. */
3400 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3402 for(xp = winx; bytelen > 0;) {
3404 * Search for the range in the to be printed string of glyphs
3405 * that are in the main font. Then print that range. If
3406 * some glyph is found that is not in the font, do the
3412 oneatatime = font->width != xw.cw;
3415 u8cblen = utf8decode(s, &unicodep, UTF_SIZ);
3419 doesexist = XftCharExists(xw.dpy, font->match, unicodep);
3423 if(!oneatatime && bytelen > 0)
3428 XftDrawStringUtf8(xw.draw, fg,
3430 winy + font->ascent,
3443 /* Search the font cache. */
3444 for(i = 0; i < frclen; i++) {
3445 charexists = XftCharExists(xw.dpy, frc[i].font, unicodep);
3446 /* Everything correct. */
3447 if(charexists && frc[i].flags == frcflags)
3449 /* We got a default font for a not found glyph. */
3450 if(!charexists && frc[i].flags == frcflags \
3451 && frc[i].unicodep == unicodep) {
3456 /* Nothing was found. */
3459 font->set = FcFontSort(0, font->pattern,
3461 fcsets[0] = font->set;
3464 * Nothing was found in the cache. Now use
3465 * some dozen of Fontconfig calls to get the
3466 * font for one single character.
3468 * Xft and fontconfig are design failures.
3470 fcpattern = FcPatternDuplicate(font->pattern);
3471 fccharset = FcCharSetCreate();
3473 FcCharSetAddChar(fccharset, unicodep);
3474 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3476 FcPatternAddBool(fcpattern, FC_SCALABLE,
3479 FcConfigSubstitute(0, fcpattern,
3481 FcDefaultSubstitute(fcpattern);
3483 fontpattern = FcFontSetMatch(0, fcsets, 1,
3487 * Overwrite or create the new cache entry.
3489 if(frclen >= LEN(frc)) {
3490 frclen = LEN(frc) - 1;
3491 XftFontClose(xw.dpy, frc[frclen].font);
3492 frc[frclen].unicodep = 0;
3495 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3497 frc[frclen].flags = frcflags;
3498 frc[frclen].unicodep = unicodep;
3503 FcPatternDestroy(fcpattern);
3504 FcCharSetDestroy(fccharset);
3507 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3508 xp, winy + frc[i].font->ascent,
3509 (FcChar8 *)u8c, u8cblen);
3511 xp += xw.cw * wcwidth(unicodep);
3515 * This is how the loop above actually should be. Why does the
3516 * application have to care about font details?
3518 * I have to repeat: Xft and Fontconfig are design failures.
3521 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3522 winy + font->ascent, (FcChar8 *)s, bytelen);
3525 if(base.mode & ATTR_UNDERLINE) {
3526 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3530 if(base.mode & ATTR_STRUCK) {
3531 XftDrawRect(xw.draw, fg, winx, winy + 2 * font->ascent / 3,
3535 /* Reset clip to none. */
3536 XftDrawSetClip(xw.draw, 0);
3540 xdrawglyph(Glyph g, int x, int y) {
3541 static char buf[UTF_SIZ];
3542 size_t len = utf8encode(g.u, buf);
3543 int width = g.mode & ATTR_WIDE ? 2 : 1;
3545 xdraws(buf, g, x, y, width, len);
3550 static int oldx = 0, oldy = 0;
3552 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs};
3554 LIMIT(oldx, 0, term.col-1);
3555 LIMIT(oldy, 0, term.row-1);
3559 /* adjust position if in dummy */
3560 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3562 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3565 g.u = term.line[term.c.y][term.c.x].u;
3567 /* remove the old cursor */
3568 xdrawglyph(term.line[oldy][oldx], oldx, oldy);
3570 if(IS_SET(MODE_HIDE))
3573 /* draw the new one */
3574 if(xw.state & WIN_FOCUSED) {
3575 switch (xw.cursor) {
3576 case 0: /* Blinking Block */
3577 case 1: /* Blinking Block (Default) */
3578 case 2: /* Steady Block */
3579 if(IS_SET(MODE_REVERSE)) {
3580 g.mode |= ATTR_REVERSE;
3585 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
3586 xdrawglyph(g, term.c.x, term.c.y);
3588 case 3: /* Blinking Underline */
3589 case 4: /* Steady Underline */
3590 XftDrawRect(xw.draw, &dc.col[defaultcs],
3591 borderpx + curx * xw.cw,
3592 borderpx + (term.c.y + 1) * xw.ch - cursorthickness,
3593 xw.cw, cursorthickness);
3595 case 5: /* Blinking bar */
3596 case 6: /* Steady bar */
3597 XftDrawRect(xw.draw, &dc.col[defaultcs],
3598 borderpx + curx * xw.cw,
3599 borderpx + term.c.y * xw.ch,
3600 cursorthickness, xw.ch);
3604 XftDrawRect(xw.draw, &dc.col[defaultcs],
3605 borderpx + curx * xw.cw,
3606 borderpx + term.c.y * xw.ch,
3608 XftDrawRect(xw.draw, &dc.col[defaultcs],
3609 borderpx + curx * xw.cw,
3610 borderpx + term.c.y * xw.ch,
3612 XftDrawRect(xw.draw, &dc.col[defaultcs],
3613 borderpx + (curx + 1) * xw.cw - 1,
3614 borderpx + term.c.y * xw.ch,
3616 XftDrawRect(xw.draw, &dc.col[defaultcs],
3617 borderpx + curx * xw.cw,
3618 borderpx + (term.c.y + 1) * xw.ch - 1,
3621 oldx = curx, oldy = term.c.y;
3626 xsettitle(char *p) {
3629 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3631 XSetWMName(xw.dpy, xw.win, &prop);
3632 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3638 xsettitle(opt_title ? opt_title : "st");
3649 drawregion(0, 0, term.col, term.row);
3650 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3652 XSetForeground(xw.dpy, dc.gc,
3653 dc.col[IS_SET(MODE_REVERSE)?
3654 defaultfg : defaultbg].pixel);
3658 drawregion(int x1, int y1, int x2, int y2) {
3659 int ic, ib, x, y, ox;
3661 char buf[DRAW_BUF_SIZ];
3662 bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3664 if(!(xw.state & WIN_VISIBLE))
3667 for(y = y1; y < y2; y++) {
3671 xtermclear(0, y, term.col, y);
3673 base = term.line[y][0];
3675 for(x = x1; x < x2; x++) {
3676 new = term.line[y][x];
3677 if(new.mode == ATTR_WDUMMY)
3679 if(ena_sel && selected(x, y))
3680 new.mode ^= ATTR_REVERSE;
3681 if(ib > 0 && (ATTRCMP(base, new)
3682 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3683 xdraws(buf, base, ox, y, ic, ib);
3691 ib += utf8encode(new.u, buf+ib);
3692 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3695 xdraws(buf, base, ox, y, ic, ib);
3701 expose(XEvent *ev) {
3706 visibility(XEvent *ev) {
3707 XVisibilityEvent *e = &ev->xvisibility;
3709 MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
3714 xw.state &= ~WIN_VISIBLE;
3718 xsetpointermotion(int set) {
3719 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3720 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3724 xseturgency(int add) {
3725 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3727 MODBIT(h->flags, add, XUrgencyHint);
3728 XSetWMHints(xw.dpy, xw.win, h);
3734 XFocusChangeEvent *e = &ev->xfocus;
3736 if(e->mode == NotifyGrab)
3739 if(ev->type == FocusIn) {
3740 XSetICFocus(xw.xic);
3741 xw.state |= WIN_FOCUSED;
3743 if(IS_SET(MODE_FOCUS))
3744 ttywrite("\033[I", 3);
3746 XUnsetICFocus(xw.xic);
3747 xw.state &= ~WIN_FOCUSED;
3748 if(IS_SET(MODE_FOCUS))
3749 ttywrite("\033[O", 3);
3754 match(uint mask, uint state) {
3755 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3759 numlock(const Arg *dummy) {
3764 kmap(KeySym k, uint state) {
3768 /* Check for mapped keys out of X11 function keys. */
3769 for(i = 0; i < LEN(mappedkeys); i++) {
3770 if(mappedkeys[i] == k)
3773 if(i == LEN(mappedkeys)) {
3774 if((k & 0xFFFF) < 0xFD00)
3778 for(kp = key; kp < key + LEN(key); kp++) {
3782 if(!match(kp->mask, state))
3785 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3787 if(term.numlock && kp->appkey == 2)
3790 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3793 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3803 kpress(XEvent *ev) {
3804 XKeyEvent *e = &ev->xkey;
3806 char buf[32], *customkey;
3812 if(IS_SET(MODE_KBDLOCK))
3815 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3817 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3818 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3819 bp->func(&(bp->arg));
3824 /* 2. custom keys from config.h */
3825 if((customkey = kmap(ksym, e->state))) {
3826 ttysend(customkey, strlen(customkey));
3830 /* 3. composed string from input method */
3833 if(len == 1 && e->state & Mod1Mask) {
3834 if(IS_SET(MODE_8BIT)) {
3837 len = utf8encode(c, buf);
3850 cmessage(XEvent *e) {
3853 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3855 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3856 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3857 xw.state |= WIN_FOCUSED;
3859 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3860 xw.state &= ~WIN_FOCUSED;
3862 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3863 /* Send SIGHUP to shell */
3870 cresize(int width, int height) {
3878 col = (xw.w - 2 * borderpx) / xw.cw;
3879 row = (xw.h - 2 * borderpx) / xw.ch;
3888 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3891 cresize(e->xconfigure.width, e->xconfigure.height);
3897 int w = xw.w, h = xw.h;
3899 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3900 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
3903 /* Waiting for window mapping */
3905 XNextEvent(xw.dpy, &ev);
3906 if(ev.type == ConfigureNotify) {
3907 w = ev.xconfigure.width;
3908 h = ev.xconfigure.height;
3910 } while(ev.type != MapNotify);
3915 clock_gettime(CLOCK_MONOTONIC, &last);
3918 for(xev = actionfps;;) {
3920 FD_SET(cmdfd, &rfd);
3923 if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
3926 die("select failed: %s\n", strerror(errno));
3928 if(FD_ISSET(cmdfd, &rfd)) {
3931 blinkset = tattrset(ATTR_BLINK);
3933 MODBIT(term.mode, 0, MODE_BLINK);
3937 if(FD_ISSET(xfd, &rfd))
3940 clock_gettime(CLOCK_MONOTONIC, &now);
3941 drawtimeout.tv_sec = 0;
3942 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
3946 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3947 tsetdirtattr(ATTR_BLINK);
3948 term.mode ^= MODE_BLINK;
3952 deltatime = TIMEDIFF(now, last);
3953 if(deltatime > 1000 / (xev ? xfps : actionfps)) {
3959 while(XPending(xw.dpy)) {
3960 XNextEvent(xw.dpy, &ev);
3961 if(XFilterEvent(&ev, None))
3963 if(handler[ev.type])
3964 (handler[ev.type])(&ev);
3970 if(xev && !FD_ISSET(xfd, &rfd))
3972 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3974 if(TIMEDIFF(now, lastblink) \
3976 drawtimeout.tv_nsec = 1000;
3978 drawtimeout.tv_nsec = (1E6 * \
3983 drawtimeout.tv_sec = \
3984 drawtimeout.tv_nsec / 1E9;
3985 drawtimeout.tv_nsec %= (long)1E9;
3996 die("%s " VERSION " (c) 2010-2015 st engineers\n"
3997 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
3998 " [-i] [-t title] [-w windowid] [-e command ...] [command ...]\n"
3999 " st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4000 " [-i] [-t title] [-w windowid] [-l line] [stty_args ...]\n",
4005 main(int argc, char *argv[]) {
4006 uint cols = 80, rows = 24;
4014 allowaltscreen = false;
4017 opt_class = EARGF(usage());
4024 opt_font = EARGF(usage());
4027 xw.gm = XParseGeometry(EARGF(usage()),
4028 &xw.l, &xw.t, &cols, &rows);
4034 opt_io = EARGF(usage());
4037 opt_line = EARGF(usage());
4040 opt_title = EARGF(usage());
4043 opt_embed = EARGF(usage());
4052 /* eat all remaining arguments */
4054 if(!opt_title && !opt_line)
4055 opt_title = basename(xstrdup(argv[0]));
4057 setlocale(LC_CTYPE, "");
4058 XSetLocaleModifiers("");
4059 tnew(MAX(cols, 1), MAX(rows, 1));