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 clock_gettime(CLOCK_MONOTONIC, &sel.tclick1);
653 clock_gettime(CLOCK_MONOTONIC, &sel.tclick2);
658 sel.clipboard = NULL;
659 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
660 if(sel.xtarget == None)
661 sel.xtarget = XA_STRING;
669 return LIMIT(x, 0, term.col-1);
677 return LIMIT(y, 0, term.row-1);
680 static int tlinelen(int y) {
683 if(TLINE(y)[i - 1].mode & ATTR_WRAP)
686 while(i > 0 && TLINE(y)[i - 1].c[0] == ' ')
696 if(sel.ob.y == sel.oe.y || sel.type == SEL_RECTANGULAR) {
697 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
698 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
700 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
701 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
703 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
704 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
706 selsnap(sel.snap, &sel.nb.x, &sel.nb.y, -1);
707 selsnap(sel.snap, &sel.ne.x, &sel.ne.y, +1);
709 /* expand selection over line breaks */
710 if (sel.type == SEL_RECTANGULAR)
712 i = tlinelen(sel.nb.y);
715 if (tlinelen(sel.ne.y) <= sel.ne.x)
716 sel.ne.x = term.col - 1;
720 selected(int x, int y) {
721 if(sel.type == SEL_RECTANGULAR)
722 return BETWEEN(y, sel.nb.y, sel.ne.y)
723 && BETWEEN(x, sel.nb.x, sel.ne.x);
725 return BETWEEN(y, sel.nb.y, sel.ne.y)
726 && (y != sel.nb.y || x >= sel.nb.x)
727 && (y != sel.ne.y || x <= sel.ne.x);
731 selsnap(int mode, int *x, int *y, int direction) {
732 int newx, newy, xt, yt;
733 bool delim, prevdelim;
739 * Snap around if the word wraps around at the end or
740 * beginning of a line.
742 prevgp = &TLINE(*y)[*x];
743 prevdelim = strchr(worddelimiters, prevgp->c[0]) != NULL;
745 newx = *x + direction;
747 if(!BETWEEN(newx, 0, term.col - 1)) {
749 newx = (newx + term.col) % term.col;
750 if (!BETWEEN(newy, 0, term.row - 1))
756 yt = newy, xt = newx;
757 if(!(TLINE(yt)[xt].mode & ATTR_WRAP))
761 if (newx >= tlinelen(newy))
764 gp = &TLINE(newy)[newx];
765 delim = strchr(worddelimiters, gp->c[0]) != NULL;
766 if(!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
767 || (delim && gp->c[0] != prevgp->c[0])))
778 * Snap around if the the previous line or the current one
779 * has set ATTR_WRAP at its end. Then the whole next or
780 * previous line will be selected.
782 *x = (direction < 0) ? 0 : term.col - 1;
783 if(direction < 0 && *y > 0) {
784 for(; *y > 0; *y += direction) {
785 if(!(TLINE(*y-1)[term.col-1].mode
790 } else if(direction > 0 && *y < term.row-1) {
791 for(; *y < term.row; *y += direction) {
792 if(!(TLINE(*y)[term.col-1].mode
803 getbuttoninfo(XEvent *e) {
805 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
807 sel.alt = IS_SET(MODE_ALTSCREEN);
809 sel.oe.x = x2col(e->xbutton.x);
810 sel.oe.y = y2row(e->xbutton.y);
813 sel.type = SEL_REGULAR;
814 for(type = 1; type < LEN(selmasks); ++type) {
815 if(match(selmasks[type], state)) {
823 mousereport(XEvent *e) {
832 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
833 if(e->xbutton.button == mk->b
834 && match(mk->mask, e->xbutton.state)) {
835 ttysend(mk->s, strlen(mk->s));
840 if(e->xbutton.button == Button1) {
841 clock_gettime(CLOCK_MONOTONIC, &now);
843 /* Clear previous selection, logically and visually. */
846 sel.type = SEL_REGULAR;
847 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
848 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
851 * If the user clicks below predefined timeouts specific
852 * snapping behaviour is exposed.
854 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
855 sel.snap = SNAP_LINE;
856 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
857 sel.snap = SNAP_WORD;
864 * Draw selection, unless it's regular and we don't want to
865 * make clicks visible
869 tsetdirt(sel.nb.y, sel.ne.y);
871 sel.tclick2 = sel.tclick1;
879 int y, bufsize, size, lastx, linelen;
885 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
886 ptr = str = xmalloc(bufsize);
888 /* append every set & selected glyph to the selection */
889 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
890 linelen = tlinelen(y);
892 if(sel.type == SEL_RECTANGULAR) {
893 gp = &TLINE(y)[sel.nb.x];
896 gp = &TLINE(y)[sel.nb.y == y ? sel.nb.x : 0];
897 lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
899 last = &TLINE(y)[MIN(lastx, linelen-1)];
900 while(last >= gp && last->c[0] == ' ')
903 for( ; gp <= last; ++gp) {
904 if(gp->mode & ATTR_WDUMMY)
907 size = utf8len(gp->c);
908 memcpy(ptr, gp->c, size);
913 * Copy and pasting of line endings is inconsistent
914 * in the inconsistent terminal and GUI world.
915 * The best solution seems like to produce '\n' when
916 * something is copied from st and convert '\n' to
917 * '\r', when something to be pasted is received by
919 * FIXME: Fix the computer world.
921 if((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
934 selnotify(XEvent *e) {
935 ulong nitems, ofs, rem;
937 uchar *data, *last, *repl;
939 XSelectionEvent *xsev;
942 xsev = (XSelectionEvent *)e;
943 if (xsev->property == None)
946 if(XGetWindowProperty(xw.dpy, xw.win, xsev->property, ofs,
947 BUFSIZ/4, False, AnyPropertyType,
948 &type, &format, &nitems, &rem,
950 fprintf(stderr, "Clipboard allocation failed\n");
956 * Line endings are inconsistent in the terminal and GUI world
957 * copy and pasting. When receiving some selection data,
958 * replace all '\n' with '\r'.
959 * FIXME: Fix the computer world.
962 last = data + nitems * format / 8;
963 while((repl = memchr(repl, '\n', last - repl))) {
967 if(IS_SET(MODE_BRCKTPASTE))
968 ttywrite("\033[200~", 6);
969 ttysend((char *)data, nitems * format / 8);
970 if(IS_SET(MODE_BRCKTPASTE))
971 ttywrite("\033[201~", 6);
973 /* number of 32-bit chunks returned */
974 ofs += nitems * format / 32;
979 selpaste(const Arg *dummy) {
980 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
981 xw.win, CurrentTime);
985 clipcopy(const Arg *dummy) {
988 if(sel.clipboard != NULL)
991 if(sel.primary != NULL) {
992 sel.clipboard = xstrdup(sel.primary);
993 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
994 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
999 clippaste(const Arg *dummy) {
1002 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1003 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1004 xw.win, CurrentTime);
1008 selclear(XEvent *e) {
1012 tsetdirt(sel.nb.y, sel.ne.y);
1016 selrequest(XEvent *e) {
1017 XSelectionRequestEvent *xsre;
1018 XSelectionEvent xev;
1019 Atom xa_targets, string, clipboard;
1022 xsre = (XSelectionRequestEvent *) e;
1023 xev.type = SelectionNotify;
1024 xev.requestor = xsre->requestor;
1025 xev.selection = xsre->selection;
1026 xev.target = xsre->target;
1027 xev.time = xsre->time;
1029 xev.property = None;
1031 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1032 if(xsre->target == xa_targets) {
1033 /* respond with the supported type */
1034 string = sel.xtarget;
1035 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1036 XA_ATOM, 32, PropModeReplace,
1037 (uchar *) &string, 1);
1038 xev.property = xsre->property;
1039 } else if(xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1041 * xith XA_STRING non ascii characters may be incorrect in the
1042 * requestor. It is not our problem, use utf8.
1044 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1045 if(xsre->selection == XA_PRIMARY) {
1046 seltext = sel.primary;
1047 } else if(xsre->selection == clipboard) {
1048 seltext = sel.clipboard;
1051 "Unhandled clipboard selection 0x%lx\n",
1055 if(seltext != NULL) {
1056 XChangeProperty(xsre->display, xsre->requestor,
1057 xsre->property, xsre->target,
1059 (uchar *)seltext, strlen(seltext));
1060 xev.property = xsre->property;
1064 /* all done, send a notification to the listener */
1065 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1066 fprintf(stderr, "Error sending SelectionNotify event\n");
1070 xsetsel(char *str) {
1074 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1078 brelease(XEvent *e) {
1079 if(e->xbutton.button == Button2) {
1081 } else if(e->xbutton.button == Button1) {
1089 tsetdirt(sel.nb.y, sel.ne.y);
1094 bmotion(XEvent *e) {
1095 int oldey, oldex, oldsby, oldsey;
1107 if(oldey != sel.oe.y || oldex != sel.oe.x)
1108 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1112 die(const char *errstr, ...) {
1115 va_start(ap, errstr);
1116 vfprintf(stderr, errstr, ap);
1123 char **args, *sh, *prog;
1124 const struct passwd *pw;
1125 char buf[sizeof(long) * 8 + 1];
1128 if((pw = getpwuid(getuid())) == NULL) {
1130 die("getpwuid:%s\n", strerror(errno));
1132 die("who are you?\n");
1135 if (!(sh = getenv("SHELL"))) {
1136 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1145 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1147 snprintf(buf, sizeof(buf), "%lu", xw.win);
1149 unsetenv("COLUMNS");
1151 unsetenv("TERMCAP");
1152 setenv("LOGNAME", pw->pw_name, 1);
1153 setenv("USER", pw->pw_name, 1);
1154 setenv("SHELL", sh, 1);
1155 setenv("HOME", pw->pw_dir, 1);
1156 setenv("TERM", termname, 1);
1157 setenv("WINDOWID", buf, 1);
1159 signal(SIGCHLD, SIG_DFL);
1160 signal(SIGHUP, SIG_DFL);
1161 signal(SIGINT, SIG_DFL);
1162 signal(SIGQUIT, SIG_DFL);
1163 signal(SIGTERM, SIG_DFL);
1164 signal(SIGALRM, SIG_DFL);
1167 _exit(EXIT_FAILURE);
1174 if(waitpid(pid, &stat, 0) < 0)
1175 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1177 ret = WIFEXITED(stat) ? WEXITSTATUS(stat) : EXIT_FAILURE;
1178 if (ret != EXIT_SUCCESS)
1179 die("child finished with error '%d'\n", stat);
1186 struct winsize w = {term.row, term.col, 0, 0};
1188 /* seems to work fine on linux, openbsd and freebsd */
1189 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1190 die("openpty failed: %s\n", strerror(errno));
1192 switch(pid = fork()) {
1194 die("fork failed\n");
1197 setsid(); /* create a new process group */
1198 dup2(s, STDIN_FILENO);
1199 dup2(s, STDOUT_FILENO);
1200 dup2(s, STDERR_FILENO);
1201 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1202 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1210 signal(SIGCHLD, sigchld);
1212 term.mode |= MODE_PRINT;
1213 iofd = (!strcmp(opt_io, "-")) ?
1215 open(opt_io, O_WRONLY | O_CREAT, 0666);
1217 fprintf(stderr, "Error opening %s:%s\n",
1218 opt_io, strerror(errno));
1227 static char buf[BUFSIZ];
1228 static int buflen = 0;
1231 int charsize; /* size of utf8 char in bytes */
1235 /* append read bytes to unprocessed bytes */
1236 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1237 die("Couldn't read from shell: %s\n", strerror(errno));
1239 /* process every complete utf8 char */
1242 while((charsize = utf8decode(ptr, &unicodep, buflen))) {
1243 utf8encode(unicodep, s, UTF_SIZ);
1249 /* keep any uncomplete utf8 char for the next call */
1250 memmove(buf, ptr, buflen);
1251 if(term.scr > 0 && term.scr < histsize-1) term.scr++;
1255 ttywrite(const char *s, size_t n) {
1256 Arg arg = (Arg){ .i = term.scr };
1260 if(xwrite(cmdfd, s, n) == -1)
1261 die("write error on tty: %s\n", strerror(errno));
1265 ttysend(char *s, size_t n) {
1267 if(IS_SET(MODE_ECHO))
1275 w.ws_row = term.row;
1276 w.ws_col = term.col;
1277 w.ws_xpixel = xw.tw;
1278 w.ws_ypixel = xw.th;
1279 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1280 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1284 tattrset(int attr) {
1287 for(i = 0; i < term.row-1; i++) {
1288 for(j = 0; j < term.col-1; j++) {
1289 if(term.line[i][j].mode & attr)
1298 tsetdirt(int top, int bot) {
1301 LIMIT(top, 0, term.row-1);
1302 LIMIT(bot, 0, term.row-1);
1304 for(i = top; i <= bot; i++)
1309 tsetdirtattr(int attr) {
1312 for(i = 0; i < term.row-1; i++) {
1313 for(j = 0; j < term.col-1; j++) {
1314 if(term.line[i][j].mode & attr) {
1324 tsetdirt(0, term.row-1);
1329 static TCursor c[2];
1330 bool alt = IS_SET(MODE_ALTSCREEN);
1332 if(mode == CURSOR_SAVE) {
1334 } else if(mode == CURSOR_LOAD) {
1336 tmoveto(c[alt].x, c[alt].y);
1344 term.c = (TCursor){{
1348 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1350 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1351 for(i = tabspaces; i < term.col; i += tabspaces)
1354 term.bot = term.row - 1;
1355 term.mode = MODE_WRAP;
1356 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1359 for(i = 0; i < 2; i++) {
1361 tcursor(CURSOR_SAVE);
1362 tclearregion(0, 0, term.col-1, term.row-1);
1368 tnew(int col, int row) {
1369 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1378 Line *tmp = term.line;
1380 term.line = term.alt;
1382 term.mode ^= MODE_ALTSCREEN;
1387 kscrolldown(const Arg* a) {
1404 kscrollup(const Arg* a) {
1410 if(term.scr <= histsize - n) {
1418 tscrolldown(int orig, int n, bool copyhist) {
1422 LIMIT(n, 0, term.bot-orig+1);
1424 tsetdirt(orig, term.bot-n);
1426 term.histi = (term.histi - 1 + histsize) % histsize;
1427 temp = term.hist[term.histi];
1428 term.hist[term.histi] = term.line[term.bot];
1429 term.line[term.bot] = temp;
1432 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1434 for(i = term.bot; i >= orig+n; i--) {
1435 temp = term.line[i];
1436 term.line[i] = term.line[i-n];
1437 term.line[i-n] = temp;
1444 tscrollup(int orig, int n, bool copyhist) {
1448 LIMIT(n, 0, term.bot-orig+1);
1451 term.histi = (term.histi + 1) % histsize;
1452 temp = term.hist[term.histi];
1453 term.hist[term.histi] = term.line[orig];
1454 term.line[orig] = temp;
1457 tclearregion(0, orig, term.col-1, orig+n-1);
1458 tsetdirt(orig+n, term.bot);
1460 for(i = orig; i <= term.bot-n; i++) {
1461 temp = term.line[i];
1462 term.line[i] = term.line[i+n];
1463 term.line[i+n] = temp;
1466 selscroll(orig, -n);
1470 selscroll(int orig, int n) {
1474 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1475 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1479 if(sel.type == SEL_RECTANGULAR) {
1480 if(sel.ob.y < term.top)
1481 sel.ob.y = term.top;
1482 if(sel.oe.y > term.bot)
1483 sel.oe.y = term.bot;
1485 if(sel.ob.y < term.top) {
1486 sel.ob.y = term.top;
1489 if(sel.oe.y > term.bot) {
1490 sel.oe.y = term.bot;
1491 sel.oe.x = term.col;
1499 tnewline(int first_col) {
1503 tscrollup(term.top, 1, true);
1507 tmoveto(first_col ? 0 : term.c.x, y);
1512 char *p = csiescseq.buf, *np;
1521 csiescseq.buf[csiescseq.len] = '\0';
1522 while(p < csiescseq.buf+csiescseq.len) {
1524 v = strtol(p, &np, 10);
1527 if(v == LONG_MAX || v == LONG_MIN)
1529 csiescseq.arg[csiescseq.narg++] = v;
1531 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1535 csiescseq.mode[0] = *p++;
1536 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1539 /* for absolute user moves, when decom is set */
1541 tmoveato(int x, int y) {
1542 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1546 tmoveto(int x, int y) {
1549 if(term.c.state & CURSOR_ORIGIN) {
1554 maxy = term.row - 1;
1556 LIMIT(x, 0, term.col-1);
1557 LIMIT(y, miny, maxy);
1558 term.c.state &= ~CURSOR_WRAPNEXT;
1564 tsetchar(char *c, Glyph *attr, int x, int y) {
1565 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1566 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1567 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1568 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1569 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1570 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1571 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1572 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1573 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1577 * The table is proudly stolen from rxvt.
1579 if(term.trantbl[term.charset] == CS_GRAPHIC0) {
1580 if(BETWEEN(c[0], 0x41, 0x7e) && vt100_0[c[0] - 0x41]) {
1581 c = vt100_0[c[0] - 0x41];
1585 if(term.line[y][x].mode & ATTR_WIDE) {
1586 if(x+1 < term.col) {
1587 term.line[y][x+1].c[0] = ' ';
1588 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1590 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1591 term.line[y][x-1].c[0] = ' ';
1592 term.line[y][x-1].mode &= ~ATTR_WIDE;
1596 term.line[y][x] = *attr;
1597 memcpy(term.line[y][x].c, c, UTF_SIZ);
1601 tclearregion(int x1, int y1, int x2, int y2) {
1606 temp = x1, x1 = x2, x2 = temp;
1608 temp = y1, y1 = y2, y2 = temp;
1610 LIMIT(x1, 0, term.col-1);
1611 LIMIT(x2, 0, term.col-1);
1612 LIMIT(y1, 0, term.row-1);
1613 LIMIT(y2, 0, term.row-1);
1615 for(y = y1; y <= y2; y++) {
1617 for(x = x1; x <= x2; x++) {
1618 gp = &term.line[y][x];
1621 gp->fg = term.c.attr.fg;
1622 gp->bg = term.c.attr.bg;
1624 memcpy(gp->c, " ", 2);
1630 tdeletechar(int n) {
1634 LIMIT(n, 0, term.col - term.c.x);
1638 size = term.col - src;
1639 line = term.line[term.c.y];
1641 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1642 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1646 tinsertblank(int n) {
1650 LIMIT(n, 0, term.col - term.c.x);
1654 size = term.col - dst;
1655 line = term.line[term.c.y];
1657 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1658 tclearregion(src, term.c.y, dst - 1, term.c.y);
1662 tinsertblankline(int n) {
1663 if(BETWEEN(term.c.y, term.top, term.bot))
1664 tscrolldown(term.c.y, n, false);
1668 tdeleteline(int n) {
1669 if(BETWEEN(term.c.y, term.top, term.bot))
1670 tscrollup(term.c.y, n, false);
1674 tdefcolor(int *attr, int *npar, int l) {
1678 switch (attr[*npar + 1]) {
1679 case 2: /* direct color in RGB space */
1680 if (*npar + 4 >= l) {
1682 "erresc(38): Incorrect number of parameters (%d)\n",
1686 r = attr[*npar + 2];
1687 g = attr[*npar + 3];
1688 b = attr[*npar + 4];
1690 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1691 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1694 idx = TRUECOLOR(r, g, b);
1696 case 5: /* indexed color */
1697 if (*npar + 2 >= l) {
1699 "erresc(38): Incorrect number of parameters (%d)\n",
1704 if(!BETWEEN(attr[*npar], 0, 255))
1705 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1709 case 0: /* implemented defined (only foreground) */
1710 case 1: /* transparent */
1711 case 3: /* direct color in CMY space */
1712 case 4: /* direct color in CMYK space */
1715 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1723 tsetattr(int *attr, int l) {
1727 for(i = 0; i < l; i++) {
1730 term.c.attr.mode &= ~(
1739 term.c.attr.fg = defaultfg;
1740 term.c.attr.bg = defaultbg;
1743 term.c.attr.mode |= ATTR_BOLD;
1746 term.c.attr.mode |= ATTR_FAINT;
1749 term.c.attr.mode |= ATTR_ITALIC;
1752 term.c.attr.mode |= ATTR_UNDERLINE;
1754 case 5: /* slow blink */
1756 case 6: /* rapid blink */
1757 term.c.attr.mode |= ATTR_BLINK;
1760 term.c.attr.mode |= ATTR_REVERSE;
1763 term.c.attr.mode |= ATTR_INVISIBLE;
1766 term.c.attr.mode |= ATTR_STRUCK;
1769 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
1772 term.c.attr.mode &= ~ATTR_ITALIC;
1775 term.c.attr.mode &= ~ATTR_UNDERLINE;
1778 term.c.attr.mode &= ~ATTR_BLINK;
1781 term.c.attr.mode &= ~ATTR_REVERSE;
1784 term.c.attr.mode &= ~ATTR_INVISIBLE;
1787 term.c.attr.mode &= ~ATTR_STRUCK;
1790 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1791 term.c.attr.fg = idx;
1794 term.c.attr.fg = defaultfg;
1797 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1798 term.c.attr.bg = idx;
1801 term.c.attr.bg = defaultbg;
1804 if(BETWEEN(attr[i], 30, 37)) {
1805 term.c.attr.fg = attr[i] - 30;
1806 } else if(BETWEEN(attr[i], 40, 47)) {
1807 term.c.attr.bg = attr[i] - 40;
1808 } else if(BETWEEN(attr[i], 90, 97)) {
1809 term.c.attr.fg = attr[i] - 90 + 8;
1810 } else if(BETWEEN(attr[i], 100, 107)) {
1811 term.c.attr.bg = attr[i] - 100 + 8;
1814 "erresc(default): gfx attr %d unknown\n",
1815 attr[i]), csidump();
1823 tsetscroll(int t, int b) {
1826 LIMIT(t, 0, term.row-1);
1827 LIMIT(b, 0, term.row-1);
1838 tsetmode(bool priv, bool set, int *args, int narg) {
1842 for(lim = args + narg; args < lim; ++args) {
1845 case 1: /* DECCKM -- Cursor key */
1846 MODBIT(term.mode, set, MODE_APPCURSOR);
1848 case 5: /* DECSCNM -- Reverse video */
1850 MODBIT(term.mode, set, MODE_REVERSE);
1851 if(mode != term.mode)
1854 case 6: /* DECOM -- Origin */
1855 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1858 case 7: /* DECAWM -- Auto wrap */
1859 MODBIT(term.mode, set, MODE_WRAP);
1861 case 0: /* Error (IGNORED) */
1862 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1863 case 3: /* DECCOLM -- Column (IGNORED) */
1864 case 4: /* DECSCLM -- Scroll (IGNORED) */
1865 case 8: /* DECARM -- Auto repeat (IGNORED) */
1866 case 18: /* DECPFF -- Printer feed (IGNORED) */
1867 case 19: /* DECPEX -- Printer extent (IGNORED) */
1868 case 42: /* DECNRCM -- National characters (IGNORED) */
1869 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1871 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1872 MODBIT(term.mode, !set, MODE_HIDE);
1874 case 9: /* X10 mouse compatibility mode */
1875 xsetpointermotion(0);
1876 MODBIT(term.mode, 0, MODE_MOUSE);
1877 MODBIT(term.mode, set, MODE_MOUSEX10);
1879 case 1000: /* 1000: report button press */
1880 xsetpointermotion(0);
1881 MODBIT(term.mode, 0, MODE_MOUSE);
1882 MODBIT(term.mode, set, MODE_MOUSEBTN);
1884 case 1002: /* 1002: report motion on button press */
1885 xsetpointermotion(0);
1886 MODBIT(term.mode, 0, MODE_MOUSE);
1887 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1889 case 1003: /* 1003: enable all mouse motions */
1890 xsetpointermotion(set);
1891 MODBIT(term.mode, 0, MODE_MOUSE);
1892 MODBIT(term.mode, set, MODE_MOUSEMANY);
1894 case 1004: /* 1004: send focus events to tty */
1895 MODBIT(term.mode, set, MODE_FOCUS);
1897 case 1006: /* 1006: extended reporting mode */
1898 MODBIT(term.mode, set, MODE_MOUSESGR);
1901 MODBIT(term.mode, set, MODE_8BIT);
1903 case 1049: /* swap screen & set/restore cursor as xterm */
1904 if (!allowaltscreen)
1906 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1908 case 47: /* swap screen */
1910 if (!allowaltscreen)
1912 alt = IS_SET(MODE_ALTSCREEN);
1914 tclearregion(0, 0, term.col-1,
1917 if(set ^ alt) /* set is always 1 or 0 */
1923 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1925 case 2004: /* 2004: bracketed paste mode */
1926 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1928 /* Not implemented mouse modes. See comments there. */
1929 case 1001: /* mouse highlight mode; can hang the
1930 terminal by design when implemented. */
1931 case 1005: /* UTF-8 mouse mode; will confuse
1932 applications not supporting UTF-8
1934 case 1015: /* urxvt mangled mouse mode; incompatible
1935 and can be mistaken for other control
1939 "erresc: unknown private set/reset mode %d\n",
1945 case 0: /* Error (IGNORED) */
1947 case 2: /* KAM -- keyboard action */
1948 MODBIT(term.mode, set, MODE_KBDLOCK);
1950 case 4: /* IRM -- Insertion-replacement */
1951 MODBIT(term.mode, set, MODE_INSERT);
1953 case 12: /* SRM -- Send/Receive */
1954 MODBIT(term.mode, !set, MODE_ECHO);
1956 case 20: /* LNM -- Linefeed/new line */
1957 MODBIT(term.mode, set, MODE_CRLF);
1961 "erresc: unknown set/reset mode %d\n",
1974 switch(csiescseq.mode[0]) {
1977 fprintf(stderr, "erresc: unknown csi ");
1981 case '@': /* ICH -- Insert <n> blank char */
1982 DEFAULT(csiescseq.arg[0], 1);
1983 tinsertblank(csiescseq.arg[0]);
1985 case 'A': /* CUU -- Cursor <n> Up */
1986 DEFAULT(csiescseq.arg[0], 1);
1987 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1989 case 'B': /* CUD -- Cursor <n> Down */
1990 case 'e': /* VPR --Cursor <n> Down */
1991 DEFAULT(csiescseq.arg[0], 1);
1992 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1994 case 'i': /* MC -- Media Copy */
1995 switch(csiescseq.arg[0]) {
2000 tdumpline(term.c.y);
2006 term.mode &= ~MODE_PRINT;
2009 term.mode |= MODE_PRINT;
2013 case 'c': /* DA -- Device Attributes */
2014 if(csiescseq.arg[0] == 0)
2015 ttywrite(vtiden, sizeof(vtiden) - 1);
2017 case 'C': /* CUF -- Cursor <n> Forward */
2018 case 'a': /* HPR -- Cursor <n> Forward */
2019 DEFAULT(csiescseq.arg[0], 1);
2020 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2022 case 'D': /* CUB -- Cursor <n> Backward */
2023 DEFAULT(csiescseq.arg[0], 1);
2024 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2026 case 'E': /* CNL -- Cursor <n> Down and first col */
2027 DEFAULT(csiescseq.arg[0], 1);
2028 tmoveto(0, term.c.y+csiescseq.arg[0]);
2030 case 'F': /* CPL -- Cursor <n> Up and first col */
2031 DEFAULT(csiescseq.arg[0], 1);
2032 tmoveto(0, term.c.y-csiescseq.arg[0]);
2034 case 'g': /* TBC -- Tabulation clear */
2035 switch(csiescseq.arg[0]) {
2036 case 0: /* clear current tab stop */
2037 term.tabs[term.c.x] = 0;
2039 case 3: /* clear all the tabs */
2040 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2046 case 'G': /* CHA -- Move to <col> */
2048 DEFAULT(csiescseq.arg[0], 1);
2049 tmoveto(csiescseq.arg[0]-1, term.c.y);
2051 case 'H': /* CUP -- Move to <row> <col> */
2053 DEFAULT(csiescseq.arg[0], 1);
2054 DEFAULT(csiescseq.arg[1], 1);
2055 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2057 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2058 DEFAULT(csiescseq.arg[0], 1);
2059 tputtab(csiescseq.arg[0]);
2061 case 'J': /* ED -- Clear screen */
2063 switch(csiescseq.arg[0]) {
2065 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2066 if(term.c.y < term.row-1) {
2067 tclearregion(0, term.c.y+1, term.col-1,
2073 tclearregion(0, 0, term.col-1, term.c.y-1);
2074 tclearregion(0, term.c.y, term.c.x, term.c.y);
2077 tclearregion(0, 0, term.col-1, term.row-1);
2083 case 'K': /* EL -- Clear line */
2084 switch(csiescseq.arg[0]) {
2086 tclearregion(term.c.x, term.c.y, term.col-1,
2090 tclearregion(0, term.c.y, term.c.x, term.c.y);
2093 tclearregion(0, term.c.y, term.col-1, term.c.y);
2097 case 'S': /* SU -- Scroll <n> line up */
2098 DEFAULT(csiescseq.arg[0], 1);
2099 tscrollup(term.top, csiescseq.arg[0], false);
2101 case 'T': /* SD -- Scroll <n> line down */
2102 DEFAULT(csiescseq.arg[0], 1);
2103 tscrolldown(term.top, csiescseq.arg[0], false);
2105 case 'L': /* IL -- Insert <n> blank lines */
2106 DEFAULT(csiescseq.arg[0], 1);
2107 tinsertblankline(csiescseq.arg[0]);
2109 case 'l': /* RM -- Reset Mode */
2110 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2112 case 'M': /* DL -- Delete <n> lines */
2113 DEFAULT(csiescseq.arg[0], 1);
2114 tdeleteline(csiescseq.arg[0]);
2116 case 'X': /* ECH -- Erase <n> char */
2117 DEFAULT(csiescseq.arg[0], 1);
2118 tclearregion(term.c.x, term.c.y,
2119 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2121 case 'P': /* DCH -- Delete <n> char */
2122 DEFAULT(csiescseq.arg[0], 1);
2123 tdeletechar(csiescseq.arg[0]);
2125 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2126 DEFAULT(csiescseq.arg[0], 1);
2127 tputtab(-csiescseq.arg[0]);
2129 case 'd': /* VPA -- Move to <row> */
2130 DEFAULT(csiescseq.arg[0], 1);
2131 tmoveato(term.c.x, csiescseq.arg[0]-1);
2133 case 'h': /* SM -- Set terminal mode */
2134 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2136 case 'm': /* SGR -- Terminal attribute (color) */
2137 tsetattr(csiescseq.arg, csiescseq.narg);
2139 case 'n': /* DSR – Device Status Report (cursor position) */
2140 if (csiescseq.arg[0] == 6) {
2141 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2142 term.c.y+1, term.c.x+1);
2146 case 'r': /* DECSTBM -- Set Scrolling Region */
2147 if(csiescseq.priv) {
2150 DEFAULT(csiescseq.arg[0], 1);
2151 DEFAULT(csiescseq.arg[1], term.row);
2152 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2156 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2157 tcursor(CURSOR_SAVE);
2159 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2160 tcursor(CURSOR_LOAD);
2163 switch (csiescseq.mode[1]) {
2164 case 'q': /* DECSCUSR -- Set Cursor Style */
2165 DEFAULT(csiescseq.arg[0], 1);
2166 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2169 xw.cursor = csiescseq.arg[0];
2184 for(i = 0; i < csiescseq.len; i++) {
2185 c = csiescseq.buf[i] & 0xff;
2188 } else if(c == '\n') {
2190 } else if(c == '\r') {
2192 } else if(c == 0x1b) {
2195 printf("(%02x)", c);
2203 memset(&csiescseq, 0, sizeof(csiescseq));
2211 term.esc &= ~(ESC_STR_END|ESC_STR);
2213 narg = strescseq.narg;
2214 par = atoi(strescseq.args[0]);
2216 switch(strescseq.type) {
2217 case ']': /* OSC -- Operating System Command */
2223 xsettitle(strescseq.args[1]);
2225 case 4: /* color set */
2228 p = strescseq.args[2];
2230 case 104: /* color reset, here p = NULL */
2231 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2232 if(xsetcolorname(j, p)) {
2233 fprintf(stderr, "erresc: invalid color %s\n", p);
2236 * TODO if defaultbg color is changed, borders
2244 case 'k': /* old title set compatibility */
2245 xsettitle(strescseq.args[0]);
2247 case 'P': /* DCS -- Device Control String */
2248 case '_': /* APC -- Application Program Command */
2249 case '^': /* PM -- Privacy Message */
2253 fprintf(stderr, "erresc: unknown str ");
2260 char *p = strescseq.buf;
2263 strescseq.buf[strescseq.len] = '\0';
2268 while(strescseq.narg < STR_ARG_SIZ) {
2269 strescseq.args[strescseq.narg++] = p;
2270 while((c = *p) != ';' && c != '\0')
2283 printf("ESC%c", strescseq.type);
2284 for(i = 0; i < strescseq.len; i++) {
2285 c = strescseq.buf[i] & 0xff;
2288 } else if(isprint(c)) {
2290 } else if(c == '\n') {
2292 } else if(c == '\r') {
2294 } else if(c == 0x1b) {
2297 printf("(%02x)", c);
2305 memset(&strescseq, 0, sizeof(strescseq));
2309 tprinter(char *s, size_t len) {
2310 if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2311 fprintf(stderr, "Error writing in %s:%s\n",
2312 opt_io, strerror(errno));
2319 toggleprinter(const Arg *arg) {
2320 term.mode ^= MODE_PRINT;
2324 printscreen(const Arg *arg) {
2329 printsel(const Arg *arg) {
2337 if((ptr = getsel())) {
2338 tprinter(ptr, strlen(ptr));
2347 bp = &term.line[n][0];
2348 end = &bp[MIN(tlinelen(n), term.col) - 1];
2349 if(bp != end || bp->c[0] != ' ') {
2350 for( ;bp <= end; ++bp)
2351 tprinter(bp->c, utf8len(bp->c));
2360 for(i = 0; i < term.row; ++i)
2369 while(x < term.col && n--)
2370 for(++x; x < term.col && !term.tabs[x]; ++x)
2374 for(--x; x > 0 && !term.tabs[x]; --x)
2377 tmoveto(x, term.c.y);
2381 techo(char *buf, int len) {
2382 for(; len > 0; buf++, len--) {
2385 if(ISCONTROL((uchar) c)) { /* control code */
2390 } else if(c != '\n' && c != '\r' && c != '\t') {
2404 tdeftran(char ascii) {
2405 static char cs[] = "0B";
2406 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2409 if((p = strchr(cs, ascii)) == NULL) {
2410 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2412 term.trantbl[term.icharset] = vcs[p - cs];
2418 static char E[UTF_SIZ] = "E";
2421 if(c == '8') { /* DEC screen alignment test. */
2422 for(x = 0; x < term.col; ++x) {
2423 for(y = 0; y < term.row; ++y)
2424 tsetchar(E, &term.c.attr, x, y);
2430 tstrsequence(uchar c) {
2433 case 0x90: /* DCS -- Device Control String */
2436 case 0x9f: /* APC -- Application Program Command */
2439 case 0x9e: /* PM -- Privacy Message */
2442 case 0x9d: /* OSC -- Operating System Command */
2449 term.esc |= ESC_STR;
2454 tcontrolcode(uchar ascii) {
2455 static char question[UTF_SIZ] = "?";
2462 tmoveto(term.c.x-1, term.c.y);
2465 tmoveto(0, term.c.y);
2470 /* go to first col if the mode is set */
2471 tnewline(IS_SET(MODE_CRLF));
2473 case '\a': /* BEL */
2474 if(term.esc & ESC_STR_END) {
2475 /* backwards compatibility to xterm */
2478 if(!(xw.state & WIN_FOCUSED))
2481 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2484 case '\033': /* ESC */
2486 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2487 term.esc |= ESC_START;
2489 case '\016': /* SO (LS1 -- Locking shift 1) */
2490 case '\017': /* SI (LS0 -- Locking shift 0) */
2491 term.charset = 1 - (ascii - '\016');
2493 case '\032': /* SUB */
2494 tsetchar(question, &term.c.attr, term.c.x, term.c.y);
2495 case '\030': /* CAN */
2498 case '\005': /* ENQ (IGNORED) */
2499 case '\000': /* NUL (IGNORED) */
2500 case '\021': /* XON (IGNORED) */
2501 case '\023': /* XOFF (IGNORED) */
2502 case 0177: /* DEL (IGNORED) */
2504 case 0x84: /* TODO: IND */
2506 case 0x85: /* NEL -- Next line */
2507 tnewline(1); /* always go to first col */
2509 case 0x88: /* HTS -- Horizontal tab stop */
2510 term.tabs[term.c.x] = 1;
2512 case 0x8d: /* TODO: RI */
2513 case 0x8e: /* TODO: SS2 */
2514 case 0x8f: /* TODO: SS3 */
2515 case 0x98: /* TODO: SOS */
2517 case 0x9a: /* DECID -- Identify Terminal */
2518 ttywrite(vtiden, sizeof(vtiden) - 1);
2520 case 0x9b: /* TODO: CSI */
2521 case 0x9c: /* TODO: ST */
2523 case 0x90: /* DCS -- Device Control String */
2524 case 0x9f: /* APC -- Application Program Command */
2525 case 0x9e: /* PM -- Privacy Message */
2526 case 0x9d: /* OSC -- Operating System Command */
2527 tstrsequence(ascii);
2530 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2531 term.esc &= ~(ESC_STR_END|ESC_STR);
2536 * returns 1 when the sequence is finished and it hasn't to read
2537 * more characters for this sequence, otherwise 0
2540 eschandle(uchar ascii) {
2543 term.esc |= ESC_CSI;
2546 term.esc |= ESC_TEST;
2548 case 'P': /* DCS -- Device Control String */
2549 case '_': /* APC -- Application Program Command */
2550 case '^': /* PM -- Privacy Message */
2551 case ']': /* OSC -- Operating System Command */
2552 case 'k': /* old title set compatibility */
2553 tstrsequence(ascii);
2555 case 'n': /* LS2 -- Locking shift 2 */
2556 case 'o': /* LS3 -- Locking shift 3 */
2557 term.charset = 2 + (ascii - 'n');
2559 case '(': /* GZD4 -- set primary charset G0 */
2560 case ')': /* G1D4 -- set secondary charset G1 */
2561 case '*': /* G2D4 -- set tertiary charset G2 */
2562 case '+': /* G3D4 -- set quaternary charset G3 */
2563 term.icharset = ascii - '(';
2564 term.esc |= ESC_ALTCHARSET;
2566 case 'D': /* IND -- Linefeed */
2567 if(term.c.y == term.bot) {
2568 tscrollup(term.top, 1, true);
2570 tmoveto(term.c.x, term.c.y+1);
2573 case 'E': /* NEL -- Next line */
2574 tnewline(1); /* always go to first col */
2576 case 'H': /* HTS -- Horizontal tab stop */
2577 term.tabs[term.c.x] = 1;
2579 case 'M': /* RI -- Reverse index */
2580 if(term.c.y == term.top) {
2581 tscrolldown(term.top, 1, true);
2583 tmoveto(term.c.x, term.c.y-1);
2586 case 'Z': /* DECID -- Identify Terminal */
2587 ttywrite(vtiden, sizeof(vtiden) - 1);
2589 case 'c': /* RIS -- Reset to inital state */
2594 case '=': /* DECPAM -- Application keypad */
2595 term.mode |= MODE_APPKEYPAD;
2597 case '>': /* DECPNM -- Normal keypad */
2598 term.mode &= ~MODE_APPKEYPAD;
2600 case '7': /* DECSC -- Save Cursor */
2601 tcursor(CURSOR_SAVE);
2603 case '8': /* DECRC -- Restore Cursor */
2604 tcursor(CURSOR_LOAD);
2606 case '\\': /* ST -- String Terminator */
2607 if(term.esc & ESC_STR_END)
2611 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2612 (uchar) ascii, isprint(ascii)? ascii:'.');
2619 tputc(char *c, int len) {
2628 unicodep = ascii = *c;
2630 utf8decode(c, &unicodep, UTF_SIZ);
2631 if ((width = wcwidth(unicodep)) == -1) {
2632 c = "\357\277\275"; /* UTF_INVALID */
2635 control = ISCONTROLC1(unicodep);
2639 if(IS_SET(MODE_PRINT))
2641 control = ISCONTROL(unicodep);
2644 * STR sequence must be checked before anything else
2645 * because it uses all following characters until it
2646 * receives a ESC, a SUB, a ST or any other C1 control
2649 if(term.esc & ESC_STR) {
2651 (ascii == '\a' || ascii == 030 ||
2652 ascii == 032 || ascii == 033 ||
2653 ISCONTROLC1(unicodep))) {
2654 term.esc &= ~(ESC_START|ESC_STR);
2655 term.esc |= ESC_STR_END;
2656 } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2657 memmove(&strescseq.buf[strescseq.len], c, len);
2658 strescseq.len += len;
2662 * Here is a bug in terminals. If the user never sends
2663 * some code to stop the str or esc command, then st
2664 * will stop responding. But this is better than
2665 * silently failing with unknown characters. At least
2666 * then users will report back.
2668 * In the case users ever get fixed, here is the code:
2679 * Actions of control codes must be performed as soon they arrive
2680 * because they can be embedded inside a control sequence, and
2681 * they must not cause conflicts with sequences.
2684 tcontrolcode(ascii);
2686 * control codes are not shown ever
2689 } else if(term.esc & ESC_START) {
2690 if(term.esc & ESC_CSI) {
2691 csiescseq.buf[csiescseq.len++] = ascii;
2692 if(BETWEEN(ascii, 0x40, 0x7E)
2693 || csiescseq.len >= \
2694 sizeof(csiescseq.buf)-1) {
2700 } else if(term.esc & ESC_ALTCHARSET) {
2702 } else if(term.esc & ESC_TEST) {
2705 if (!eschandle(ascii))
2707 /* sequence already finished */
2711 * All characters which form part of a sequence are not
2716 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2719 gp = &term.line[term.c.y][term.c.x];
2720 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2721 gp->mode |= ATTR_WRAP;
2723 gp = &term.line[term.c.y][term.c.x];
2726 if(IS_SET(MODE_INSERT) && term.c.x+width < term.col)
2727 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
2729 if(term.c.x+width > term.col) {
2731 gp = &term.line[term.c.y][term.c.x];
2734 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2737 gp->mode |= ATTR_WIDE;
2738 if(term.c.x+1 < term.col) {
2740 gp[1].mode = ATTR_WDUMMY;
2743 if(term.c.x+width < term.col) {
2744 tmoveto(term.c.x+width, term.c.y);
2746 term.c.state |= CURSOR_WRAPNEXT;
2751 tresize(int col, int row) {
2753 int minrow = MIN(row, term.row);
2754 int mincol = MIN(col, term.col);
2755 int slide = term.c.y - row + 1;
2759 if(col < 1 || row < 1) {
2761 "tresize: error resizing to %dx%d\n", col, row);
2765 /* free unneeded rows */
2769 * slide screen to keep cursor where we expect it -
2770 * tscrollup would work here, but we can optimize to
2771 * memmove because we're freeing the earlier lines
2773 for(/* i = 0 */; i < slide; i++) {
2777 memmove(term.line, term.line + slide, row * sizeof(Line));
2778 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2780 for(i += row; i < term.row; i++) {
2785 /* resize to new height */
2786 term.line = xrealloc(term.line, row * sizeof(Line));
2787 term.alt = xrealloc(term.alt, row * sizeof(Line));
2788 term.hist = xrealloc(term.hist, histsize * sizeof(Line));
2789 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2790 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2792 for(i = 0; i < histsize; i++) {
2793 term.hist[i] = xrealloc(term.hist[i], col * sizeof(Glyph));
2794 for(j = mincol; j < col; j++) {
2795 term.hist[i][j] = term.c.attr;
2796 memcpy(term.hist[i][j].c, " ", 2);
2800 /* resize each row to new width, zero-pad if needed */
2801 for(i = 0; i < minrow; i++) {
2802 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2803 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2806 /* allocate any new rows */
2807 for(/* i == minrow */; i < row; i++) {
2808 term.line[i] = xmalloc(col * sizeof(Glyph));
2809 term.alt[i] = xmalloc(col * sizeof(Glyph));
2811 if(col > term.col) {
2812 bp = term.tabs + term.col;
2814 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2815 while(--bp > term.tabs && !*bp)
2817 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2820 /* update terminal size */
2823 /* reset scrolling region */
2824 tsetscroll(0, row-1);
2825 /* make use of the LIMIT in tmoveto */
2826 tmoveto(term.c.x, term.c.y);
2827 /* Clearing both screens (it makes dirty all lines) */
2829 for(i = 0; i < 2; i++) {
2830 if(mincol < col && 0 < minrow) {
2831 tclearregion(mincol, 0, col - 1, minrow - 1);
2833 if(0 < col && minrow < row) {
2834 tclearregion(0, minrow, col - 1, row - 1);
2837 tcursor(CURSOR_LOAD);
2843 xresize(int col, int row) {
2844 xw.tw = MAX(1, col * xw.cw);
2845 xw.th = MAX(1, row * xw.ch);
2847 XFreePixmap(xw.dpy, xw.buf);
2848 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2849 DefaultDepth(xw.dpy, xw.scr));
2850 XftDrawChange(xw.draw, xw.buf);
2851 xclear(0, 0, xw.w, xw.h);
2854 static inline ushort
2855 sixd_to_16bit(int x) {
2856 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2862 XRenderColor color = { .alpha = 0xffff };
2867 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2868 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2871 /* load colors [0-15] and [256-LEN(colorname)] (config.h) */
2872 for(i = 0; i < LEN(colorname); i++) {
2875 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2876 die("Could not allocate color '%s'\n", colorname[i]);
2880 /* load colors [16-231] ; same colors as xterm */
2881 for(i = 16; i < 6*6*6+16; i++) {
2882 color.red = sixd_to_16bit( ((i-16)/36)%6 );
2883 color.green = sixd_to_16bit( ((i-16)/6) %6 );
2884 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
2885 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
2886 die("Could not allocate color %d\n", i);
2889 /* load colors [232-255] ; grayscale */
2890 for(; i < 256; i++) {
2891 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (i-(6*6*6+16));
2892 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
2893 die("Could not allocate color %d\n", i);
2899 xsetcolorname(int x, const char *name) {
2900 XRenderColor color = { .alpha = 0xffff };
2903 if(!BETWEEN(x, 0, LEN(colorname)))
2907 if(BETWEEN(x, 16, 16 + 215)) { /* 256 color */
2908 color.red = sixd_to_16bit( ((x-16)/36)%6 );
2909 color.green = sixd_to_16bit( ((x-16)/6) %6 );
2910 color.blue = sixd_to_16bit( ((x-16)/1) %6 );
2911 if(!XftColorAllocValue(xw.dpy, xw.vis,
2912 xw.cmap, &color, &ncolor)) {
2916 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2919 } else if(BETWEEN(x, 16 + 216, 255)) { /* greyscale */
2920 color.red = color.green = color.blue = \
2921 0x0808 + 0x0a0a * (x - (16 + 216));
2922 if(!XftColorAllocValue(xw.dpy, xw.vis,
2923 xw.cmap, &color, &ncolor)) {
2927 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2930 } else { /* system colors */
2931 name = colorname[x];
2934 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &ncolor))
2937 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2943 xtermclear(int col1, int row1, int col2, int row2) {
2944 XftDrawRect(xw.draw,
2945 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2946 borderpx + col1 * xw.cw,
2947 borderpx + row1 * xw.ch,
2948 (col2-col1+1) * xw.cw,
2949 (row2-row1+1) * xw.ch);
2953 * Absolute coordinates.
2956 xclear(int x1, int y1, int x2, int y2) {
2957 XftDrawRect(xw.draw,
2958 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2959 x1, y1, x2-x1, y2-y1);
2964 XClassHint class = {opt_class ? opt_class : termname, termname};
2965 XWMHints wm = {.flags = InputHint, .input = 1};
2966 XSizeHints *sizeh = NULL;
2968 sizeh = XAllocSizeHints();
2970 sizeh->flags = PSize | PResizeInc | PBaseSize;
2971 sizeh->height = xw.h;
2972 sizeh->width = xw.w;
2973 sizeh->height_inc = xw.ch;
2974 sizeh->width_inc = xw.cw;
2975 sizeh->base_height = 2 * borderpx;
2976 sizeh->base_width = 2 * borderpx;
2977 if(xw.isfixed == True) {
2978 sizeh->flags |= PMaxSize | PMinSize;
2979 sizeh->min_width = sizeh->max_width = xw.w;
2980 sizeh->min_height = sizeh->max_height = xw.h;
2982 if(xw.gm & (XValue|YValue)) {
2983 sizeh->flags |= USPosition | PWinGravity;
2986 sizeh->win_gravity = xgeommasktogravity(xw.gm);
2989 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
2995 xgeommasktogravity(int mask) {
2996 switch(mask & (XNegative|YNegative)) {
2998 return NorthWestGravity;
3000 return NorthEastGravity;
3002 return SouthWestGravity;
3004 return SouthEastGravity;
3008 xloadfont(Font *f, FcPattern *pattern) {
3012 match = FcFontMatch(NULL, pattern, &result);
3016 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3017 FcPatternDestroy(match);
3022 f->pattern = FcPatternDuplicate(pattern);
3024 f->ascent = f->match->ascent;
3025 f->descent = f->match->descent;
3027 f->rbearing = f->match->max_advance_width;
3029 f->height = f->ascent + f->descent;
3030 f->width = f->lbearing + f->rbearing;
3036 xloadfonts(char *fontstr, double fontsize) {
3038 FcResult r_sz, r_psz;
3042 if(fontstr[0] == '-') {
3043 pattern = XftXlfdParse(fontstr, False, False);
3045 pattern = FcNameParse((FcChar8 *)fontstr);
3049 die("st: can't open font %s\n", fontstr);
3052 FcPatternDel(pattern, FC_PIXEL_SIZE);
3053 FcPatternDel(pattern, FC_SIZE);
3054 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3055 usedfontsize = fontsize;
3057 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
3058 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
3059 if(r_psz == FcResultMatch) {
3060 usedfontsize = fontval;
3061 } else if(r_sz == FcResultMatch) {
3065 * Default font size is 12, if none given. This is to
3066 * have a known usedfontsize value.
3068 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3071 defaultfontsize = usedfontsize;
3074 FcConfigSubstitute(0, pattern, FcMatchPattern);
3075 FcDefaultSubstitute(pattern);
3077 if(xloadfont(&dc.font, pattern))
3078 die("st: can't open font %s\n", fontstr);
3080 if(usedfontsize < 0) {
3081 FcPatternGetDouble(dc.font.match->pattern,
3082 FC_PIXEL_SIZE, 0, &fontval);
3083 usedfontsize = fontval;
3085 defaultfontsize = fontval;
3088 /* Setting character width and height. */
3089 xw.cw = ceilf(dc.font.width * cwscale);
3090 xw.ch = ceilf(dc.font.height * chscale);
3092 FcPatternDel(pattern, FC_SLANT);
3093 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3094 if(xloadfont(&dc.ifont, pattern))
3095 die("st: can't open font %s\n", fontstr);
3097 FcPatternDel(pattern, FC_WEIGHT);
3098 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3099 if(xloadfont(&dc.ibfont, pattern))
3100 die("st: can't open font %s\n", fontstr);
3102 FcPatternDel(pattern, FC_SLANT);
3103 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3104 if(xloadfont(&dc.bfont, pattern))
3105 die("st: can't open font %s\n", fontstr);
3107 FcPatternDestroy(pattern);
3111 xloadfontset(Font *f) {
3114 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
3120 xunloadfont(Font *f) {
3121 XftFontClose(xw.dpy, f->match);
3122 FcPatternDestroy(f->pattern);
3124 FcFontSetDestroy(f->set);
3128 xunloadfonts(void) {
3129 /* Free the loaded fonts in the font cache. */
3131 XftFontClose(xw.dpy, frc[--frclen].font);
3133 xunloadfont(&dc.font);
3134 xunloadfont(&dc.bfont);
3135 xunloadfont(&dc.ifont);
3136 xunloadfont(&dc.ibfont);
3140 xzoom(const Arg *arg) {
3143 larg.i = usedfontsize + arg->i;
3148 xzoomabs(const Arg *arg) {
3150 xloadfonts(usedfont, arg->i);
3157 xzoomreset(const Arg *arg) {
3160 if(defaultfontsize > 0) {
3161 larg.i = defaultfontsize;
3171 pid_t thispid = getpid();
3173 if(!(xw.dpy = XOpenDisplay(NULL)))
3174 die("Can't open display\n");
3175 xw.scr = XDefaultScreen(xw.dpy);
3176 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3180 die("Could not init fontconfig.\n");
3182 usedfont = (opt_font == NULL)? font : opt_font;
3183 xloadfonts(usedfont, 0);
3186 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3189 /* adjust fixed window geometry */
3190 xw.w = 2 * borderpx + term.col * xw.cw;
3191 xw.h = 2 * borderpx + term.row * xw.ch;
3192 if(xw.gm & XNegative)
3193 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3194 if(xw.gm & YNegative)
3195 xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
3198 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3199 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3200 xw.attrs.bit_gravity = NorthWestGravity;
3201 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3202 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3203 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3204 xw.attrs.colormap = xw.cmap;
3206 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3207 parent = XRootWindow(xw.dpy, xw.scr);
3208 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3209 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3210 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3211 | CWEventMask | CWColormap, &xw.attrs);
3213 memset(&gcvalues, 0, sizeof(gcvalues));
3214 gcvalues.graphics_exposures = False;
3215 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3217 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3218 DefaultDepth(xw.dpy, xw.scr));
3219 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3220 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3222 /* Xft rendering context */
3223 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3226 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3227 XSetLocaleModifiers("@im=local");
3228 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3229 XSetLocaleModifiers("@im=");
3230 if((xw.xim = XOpenIM(xw.dpy,
3231 NULL, NULL, NULL)) == NULL) {
3232 die("XOpenIM failed. Could not open input"
3237 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3238 | XIMStatusNothing, XNClientWindow, xw.win,
3239 XNFocusWindow, xw.win, NULL);
3241 die("XCreateIC failed. Could not obtain input method.\n");
3243 /* white cursor, black outline */
3244 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3245 XDefineCursor(xw.dpy, xw.win, cursor);
3246 XRecolorCursor(xw.dpy, cursor,
3247 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3248 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3250 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3251 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3252 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3253 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3255 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3256 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3257 PropModeReplace, (uchar *)&thispid, 1);
3260 XMapWindow(xw.dpy, xw.win);
3262 XSync(xw.dpy, False);
3266 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3267 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3268 width = charlen * xw.cw, xp, i;
3269 int frcflags, charexists;
3270 int u8fl, u8fblen, u8cblen, doesexist;
3273 Font *font = &dc.font;
3275 FcPattern *fcpattern, *fontpattern;
3276 FcFontSet *fcsets[] = { NULL };
3277 FcCharSet *fccharset;
3278 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3279 XRenderColor colfg, colbg;
3283 frcflags = FRC_NORMAL;
3285 if(base.mode & ATTR_ITALIC) {
3286 if(base.fg == defaultfg)
3287 base.fg = defaultitalic;
3289 frcflags = FRC_ITALIC;
3290 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3291 if(base.fg == defaultfg)
3292 base.fg = defaultitalic;
3294 frcflags = FRC_ITALICBOLD;
3295 } else if(base.mode & ATTR_UNDERLINE) {
3296 if(base.fg == defaultfg)
3297 base.fg = defaultunderline;
3300 if(IS_TRUECOL(base.fg)) {
3301 colfg.alpha = 0xffff;
3302 colfg.red = TRUERED(base.fg);
3303 colfg.green = TRUEGREEN(base.fg);
3304 colfg.blue = TRUEBLUE(base.fg);
3305 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3308 fg = &dc.col[base.fg];
3311 if(IS_TRUECOL(base.bg)) {
3312 colbg.alpha = 0xffff;
3313 colbg.green = TRUEGREEN(base.bg);
3314 colbg.red = TRUERED(base.bg);
3315 colbg.blue = TRUEBLUE(base.bg);
3316 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3319 bg = &dc.col[base.bg];
3322 if(base.mode & ATTR_BOLD) {
3324 * change basic system colors [0-7]
3325 * to bright system colors [8-15]
3327 if(BETWEEN(base.fg, 0, 7) && !(base.mode & ATTR_FAINT))
3328 fg = &dc.col[base.fg + 8];
3330 if(base.mode & ATTR_ITALIC) {
3332 frcflags = FRC_ITALICBOLD;
3335 frcflags = FRC_BOLD;
3339 if(IS_SET(MODE_REVERSE)) {
3340 if(fg == &dc.col[defaultfg]) {
3341 fg = &dc.col[defaultbg];
3343 colfg.red = ~fg->color.red;
3344 colfg.green = ~fg->color.green;
3345 colfg.blue = ~fg->color.blue;
3346 colfg.alpha = fg->color.alpha;
3347 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3352 if(bg == &dc.col[defaultbg]) {
3353 bg = &dc.col[defaultfg];
3355 colbg.red = ~bg->color.red;
3356 colbg.green = ~bg->color.green;
3357 colbg.blue = ~bg->color.blue;
3358 colbg.alpha = bg->color.alpha;
3359 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3365 if(base.mode & ATTR_REVERSE) {
3371 if(base.mode & ATTR_FAINT && !(base.mode & ATTR_BOLD)) {
3372 colfg.red = fg->color.red / 2;
3373 colfg.green = fg->color.green / 2;
3374 colfg.blue = fg->color.blue / 2;
3375 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3379 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3382 if(base.mode & ATTR_INVISIBLE)
3385 /* Intelligent cleaning up of the borders. */
3387 xclear(0, (y == 0)? 0 : winy, borderpx,
3388 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3390 if(x + charlen >= term.col) {
3391 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3392 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3395 xclear(winx, 0, winx + width, borderpx);
3397 xclear(winx, winy + xw.ch, winx + width, xw.h);
3399 /* Clean up the region we want to draw to. */
3400 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3402 /* Set the clip region because Xft is sometimes dirty. */
3407 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3409 for(xp = winx; bytelen > 0;) {
3411 * Search for the range in the to be printed string of glyphs
3412 * that are in the main font. Then print that range. If
3413 * some glyph is found that is not in the font, do the
3419 oneatatime = font->width != xw.cw;
3422 u8cblen = utf8decode(s, &unicodep, UTF_SIZ);
3426 doesexist = XftCharExists(xw.dpy, font->match, unicodep);
3430 if(!oneatatime && bytelen > 0)
3435 XftDrawStringUtf8(xw.draw, fg,
3437 winy + font->ascent,
3450 /* Search the font cache. */
3451 for(i = 0; i < frclen; i++) {
3452 charexists = XftCharExists(xw.dpy, frc[i].font, unicodep);
3453 /* Everything correct. */
3454 if(charexists && frc[i].flags == frcflags)
3456 /* We got a default font for a not found glyph. */
3457 if(!charexists && frc[i].flags == frcflags \
3458 && frc[i].unicodep == unicodep) {
3463 /* Nothing was found. */
3467 fcsets[0] = font->set;
3470 * Nothing was found in the cache. Now use
3471 * some dozen of Fontconfig calls to get the
3472 * font for one single character.
3474 * Xft and fontconfig are design failures.
3476 fcpattern = FcPatternDuplicate(font->pattern);
3477 fccharset = FcCharSetCreate();
3479 FcCharSetAddChar(fccharset, unicodep);
3480 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3482 FcPatternAddBool(fcpattern, FC_SCALABLE,
3485 FcConfigSubstitute(0, fcpattern,
3487 FcDefaultSubstitute(fcpattern);
3489 fontpattern = FcFontSetMatch(0, fcsets, 1,
3493 * Overwrite or create the new cache entry.
3495 if(frclen >= LEN(frc)) {
3496 frclen = LEN(frc) - 1;
3497 XftFontClose(xw.dpy, frc[frclen].font);
3498 frc[frclen].unicodep = 0;
3501 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3503 frc[frclen].flags = frcflags;
3504 frc[frclen].unicodep = unicodep;
3509 FcPatternDestroy(fcpattern);
3510 FcCharSetDestroy(fccharset);
3513 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3514 xp, winy + frc[i].font->ascent,
3515 (FcChar8 *)u8c, u8cblen);
3517 xp += xw.cw * wcwidth(unicodep);
3521 * This is how the loop above actually should be. Why does the
3522 * application have to care about font details?
3524 * I have to repeat: Xft and Fontconfig are design failures.
3527 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3528 winy + font->ascent, (FcChar8 *)s, bytelen);
3531 if(base.mode & ATTR_UNDERLINE) {
3532 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3536 if(base.mode & ATTR_STRUCK) {
3537 XftDrawRect(xw.draw, fg, winx, winy + 2 * font->ascent / 3,
3541 /* Reset clip to none. */
3542 XftDrawSetClip(xw.draw, 0);
3547 static int oldx = 0, oldy = 0;
3548 int sl, width, curx;
3549 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3551 LIMIT(oldx, 0, term.col-1);
3552 LIMIT(oldy, 0, term.row-1);
3556 /* adjust position if in dummy */
3557 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3559 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3562 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3564 /* remove the old cursor */
3565 sl = utf8len(term.line[oldy][oldx].c);
3566 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3567 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
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;
3586 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3588 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3590 case 3: /* Blinking Underline */
3591 case 4: /* Steady Underline */
3592 XftDrawRect(xw.draw, &dc.col[defaultcs],
3593 borderpx + curx * xw.cw,
3594 borderpx + (term.c.y + 1) * xw.ch - 1,
3597 case 5: /* Blinking bar */
3598 case 6: /* Steady bar */
3599 XftDrawRect(xw.draw, &dc.col[defaultcs],
3600 borderpx + curx * xw.cw,
3601 borderpx + term.c.y * xw.ch,
3606 XftDrawRect(xw.draw, &dc.col[defaultcs],
3607 borderpx + curx * xw.cw,
3608 borderpx + term.c.y * xw.ch,
3610 XftDrawRect(xw.draw, &dc.col[defaultcs],
3611 borderpx + curx * xw.cw,
3612 borderpx + term.c.y * xw.ch,
3614 XftDrawRect(xw.draw, &dc.col[defaultcs],
3615 borderpx + (curx + 1) * xw.cw - 1,
3616 borderpx + term.c.y * xw.ch,
3618 XftDrawRect(xw.draw, &dc.col[defaultcs],
3619 borderpx + curx * xw.cw,
3620 borderpx + (term.c.y + 1) * xw.ch - 1,
3623 oldx = curx, oldy = term.c.y;
3628 xsettitle(char *p) {
3631 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3633 XSetWMName(xw.dpy, xw.win, &prop);
3634 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3640 xsettitle(opt_title ? opt_title : "st");
3651 drawregion(0, 0, term.col, term.row);
3652 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3654 XSetForeground(xw.dpy, dc.gc,
3655 dc.col[IS_SET(MODE_REVERSE)?
3656 defaultfg : defaultbg].pixel);
3660 drawregion(int x1, int y1, int x2, int y2) {
3661 int ic, ib, x, y, ox, sl;
3663 char buf[DRAW_BUF_SIZ];
3664 bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3667 if(!(xw.state & WIN_VISIBLE))
3670 for(y = y1; y < y2; y++) {
3674 xtermclear(0, y, term.col, y);
3678 for(x = x1; x < x2; x++) {
3680 if(new.mode == ATTR_WDUMMY)
3682 if(ena_sel && selected(x, y))
3683 new.mode ^= ATTR_REVERSE;
3684 if(ib > 0 && (ATTRCMP(base, new)
3685 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3686 xdraws(buf, base, ox, y, ic, ib);
3694 sl = utf8decode(new.c, &unicodep, UTF_SIZ);
3695 memcpy(buf+ib, new.c, sl);
3697 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3700 xdraws(buf, base, ox, y, ic, ib);
3707 expose(XEvent *ev) {
3708 XExposeEvent *e = &ev->xexpose;
3710 if(xw.state & WIN_REDRAW) {
3712 xw.state &= ~WIN_REDRAW;
3718 visibility(XEvent *ev) {
3719 XVisibilityEvent *e = &ev->xvisibility;
3721 if(e->state == VisibilityFullyObscured) {
3722 xw.state &= ~WIN_VISIBLE;
3723 } else if(!(xw.state & WIN_VISIBLE)) {
3724 /* need a full redraw for next Expose, not just a buf copy */
3725 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3731 xw.state &= ~WIN_VISIBLE;
3735 xsetpointermotion(int set) {
3736 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3737 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3741 xseturgency(int add) {
3742 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3744 MODBIT(h->flags, add, XUrgencyHint);
3745 XSetWMHints(xw.dpy, xw.win, h);
3751 XFocusChangeEvent *e = &ev->xfocus;
3753 if(e->mode == NotifyGrab)
3756 if(ev->type == FocusIn) {
3757 XSetICFocus(xw.xic);
3758 xw.state |= WIN_FOCUSED;
3760 if(IS_SET(MODE_FOCUS))
3761 ttywrite("\033[I", 3);
3763 XUnsetICFocus(xw.xic);
3764 xw.state &= ~WIN_FOCUSED;
3765 if(IS_SET(MODE_FOCUS))
3766 ttywrite("\033[O", 3);
3771 match(uint mask, uint state) {
3772 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3776 numlock(const Arg *dummy) {
3781 kmap(KeySym k, uint state) {
3785 /* Check for mapped keys out of X11 function keys. */
3786 for(i = 0; i < LEN(mappedkeys); i++) {
3787 if(mappedkeys[i] == k)
3790 if(i == LEN(mappedkeys)) {
3791 if((k & 0xFFFF) < 0xFD00)
3795 for(kp = key; kp < key + LEN(key); kp++) {
3799 if(!match(kp->mask, state))
3802 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3804 if(term.numlock && kp->appkey == 2)
3807 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3810 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3820 kpress(XEvent *ev) {
3821 XKeyEvent *e = &ev->xkey;
3823 char buf[32], *customkey;
3829 if(IS_SET(MODE_KBDLOCK))
3832 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3834 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3835 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3836 bp->func(&(bp->arg));
3841 /* 2. custom keys from config.h */
3842 if((customkey = kmap(ksym, e->state))) {
3843 ttysend(customkey, strlen(customkey));
3847 /* 3. composed string from input method */
3850 if(len == 1 && e->state & Mod1Mask) {
3851 if(IS_SET(MODE_8BIT)) {
3854 len = utf8encode(c, buf, UTF_SIZ);
3867 cmessage(XEvent *e) {
3870 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3872 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3873 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3874 xw.state |= WIN_FOCUSED;
3876 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3877 xw.state &= ~WIN_FOCUSED;
3879 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3880 /* Send SIGHUP to shell */
3887 cresize(int width, int height) {
3895 col = (xw.w - 2 * borderpx) / xw.cw;
3896 row = (xw.h - 2 * borderpx) / xw.ch;
3905 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3908 cresize(e->xconfigure.width, e->xconfigure.height);
3914 int w = xw.w, h = xw.h;
3916 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3917 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
3920 /* Waiting for window mapping */
3922 XNextEvent(xw.dpy, &ev);
3923 if(XFilterEvent(&ev, None))
3925 if(ev.type == ConfigureNotify) {
3926 w = ev.xconfigure.width;
3927 h = ev.xconfigure.height;
3928 } else if(ev.type == MapNotify) {
3936 clock_gettime(CLOCK_MONOTONIC, &last);
3939 for(xev = actionfps;;) {
3941 FD_SET(cmdfd, &rfd);
3944 if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
3947 die("select failed: %s\n", strerror(errno));
3949 if(FD_ISSET(cmdfd, &rfd)) {
3953 if(FD_ISSET(xfd, &rfd)) {
3957 MODBIT(term.mode, 1, MODE_BLINK);
3962 clock_gettime(CLOCK_MONOTONIC, &now);
3963 drawtimeout.tv_sec = 0;
3964 drawtimeout.tv_nsec = (1000/xfps) * 1E6;
3968 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3969 tsetdirtattr(ATTR_BLINK);
3970 term.mode ^= MODE_BLINK;
3974 deltatime = TIMEDIFF(now, last);
3975 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3982 while(XPending(xw.dpy)) {
3983 XNextEvent(xw.dpy, &ev);
3984 if(XFilterEvent(&ev, None))
3986 if(handler[ev.type])
3987 (handler[ev.type])(&ev);
3993 if(xev && !FD_ISSET(xfd, &rfd))
3995 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3997 if(TIMEDIFF(now, lastblink) \
3999 drawtimeout.tv_nsec = 1000;
4001 drawtimeout.tv_nsec = (1E6 * \
4006 drawtimeout.tv_sec = \
4007 drawtimeout.tv_nsec / 1E9;
4008 drawtimeout.tv_nsec %= (long)1E9;
4019 die("%s " VERSION " (c) 2010-2015 st engineers\n" \
4020 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4021 " [-i] [-t title] [-w windowid] [-e command ...]\n", argv0);
4025 main(int argc, char *argv[]) {
4027 uint cols = 80, rows = 24;
4035 allowaltscreen = false;
4038 opt_class = EARGF(usage());
4041 /* eat all remaining arguments */
4044 if(argv[1] != NULL && opt_title == NULL) {
4045 titles = xstrdup(argv[1]);
4046 opt_title = basename(titles);
4051 opt_font = EARGF(usage());
4054 xw.gm = XParseGeometry(EARGF(usage()),
4055 &xw.l, &xw.t, &cols, &rows);
4061 opt_io = EARGF(usage());
4064 opt_title = EARGF(usage());
4067 opt_embed = EARGF(usage());
4075 setlocale(LC_CTYPE, "");
4076 XSetLocaleModifiers("");
4077 tnew(cols? cols : 1, rows? rows : 1);