1 /* See LICENSE for license details. */
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #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 XK_ANY_MOD UINT_MAX
63 #define XK_SWITCH_MOD (1<<13)
66 #define MIN(a, b) ((a) < (b) ? (a) : (b))
67 #define MAX(a, b) ((a) < (b) ? (b) : (a))
68 #define LEN(a) (sizeof(a) / sizeof(a)[0])
69 #define NUMMAXLEN(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
70 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
71 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
72 #define DIVCEIL(n, d) (((n) + ((d) - 1)) / (d))
73 #define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == '\177')
74 #define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
75 #define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
76 #define ISDELIM(u) (utf8strchr(worddelimiters, u) != NULL)
77 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
78 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || \
80 #define IS_SET(flag) ((term.mode & (flag)) != 0)
81 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + \
82 (t1.tv_nsec-t2.tv_nsec)/1E6)
83 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
85 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
86 #define IS_TRUECOL(x) (1 << 24 & (x))
87 #define TRUERED(x) (((x) & 0xff0000) >> 8)
88 #define TRUEGREEN(x) (((x) & 0xff00))
89 #define TRUEBLUE(x) (((x) & 0xff) << 8)
92 #define ISO14755CMD "dmenu -w %lu -p codepoint: </dev/null"
94 enum glyph_attribute {
99 ATTR_UNDERLINE = 1 << 3,
101 ATTR_REVERSE = 1 << 5,
102 ATTR_INVISIBLE = 1 << 6,
103 ATTR_STRUCK = 1 << 7,
106 ATTR_WDUMMY = 1 << 10,
107 ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT,
110 enum cursor_movement {
123 MODE_INSERT = 1 << 1,
124 MODE_APPKEYPAD = 1 << 2,
125 MODE_ALTSCREEN = 1 << 3,
127 MODE_MOUSEBTN = 1 << 5,
128 MODE_MOUSEMOTION = 1 << 6,
129 MODE_REVERSE = 1 << 7,
130 MODE_KBDLOCK = 1 << 8,
133 MODE_APPCURSOR = 1 << 11,
134 MODE_MOUSESGR = 1 << 12,
136 MODE_BLINK = 1 << 14,
137 MODE_FBLINK = 1 << 15,
138 MODE_FOCUS = 1 << 16,
139 MODE_MOUSEX10 = 1 << 17,
140 MODE_MOUSEMANY = 1 << 18,
141 MODE_BRCKTPASTE = 1 << 19,
142 MODE_PRINT = 1 << 20,
144 MODE_SIXEL = 1 << 22,
145 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
162 ESC_STR = 4, /* OSC, PM, APC */
164 ESC_STR_END = 16, /* a final string was encountered */
165 ESC_TEST = 32, /* Enter in test mode */
175 enum selection_mode {
181 enum selection_type {
186 enum selection_snap {
191 typedef unsigned char uchar;
192 typedef unsigned int uint;
193 typedef unsigned long ulong;
194 typedef unsigned short ushort;
196 typedef uint_least32_t Rune;
198 typedef XftDraw *Draw;
199 typedef XftColor Color;
202 Rune u; /* character code */
203 ushort mode; /* attribute flags */
204 uint32_t fg; /* foreground */
205 uint32_t bg; /* background */
211 Glyph attr; /* current char attributes */
217 /* CSI Escape sequence structs */
218 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
220 char buf[ESC_BUF_SIZ]; /* raw string */
221 int len; /* raw string length */
223 int arg[ESC_ARG_SIZ];
224 int narg; /* nb of args */
228 /* STR Escape sequence structs */
229 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
231 char type; /* ESC type ... */
232 char buf[STR_BUF_SIZ]; /* raw string */
233 int len; /* raw string length */
234 char *args[STR_ARG_SIZ];
235 int narg; /* nb of args */
238 /* Internal representation of the screen */
240 int row; /* nb row */
241 int col; /* nb col */
242 Line *line; /* screen */
243 Line *alt; /* alternate screen */
244 int *dirty; /* dirtyness of lines */
245 XftGlyphFontSpec *specbuf; /* font spec buffer used for rendering */
246 TCursor c; /* cursor */
247 int top; /* top scroll limit */
248 int bot; /* bottom scroll limit */
249 int mode; /* terminal mode flags */
250 int esc; /* escape state flags */
251 char trantbl[4]; /* charset table translation */
252 int charset; /* current charset */
253 int icharset; /* selected charset for sequence */
254 int numlock; /* lock numbers in keyboard */
258 /* Purely graphic info */
264 Atom xembed, wmdeletewin, netwmname, netwmpid;
269 XSetWindowAttributes attrs;
271 int isfixed; /* is fixed geometry? */
272 int l, t; /* left and top offset */
273 int gm; /* geometry mask */
274 int tw, th; /* tty width and height */
275 int w, h; /* window width and height */
276 int ch; /* char height */
277 int cw; /* char width */
278 char state; /* focus, redraw, visible */
279 int cursor; /* cursor style */
292 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
293 signed char appkey; /* application keypad */
294 signed char appcursor; /* application cursor */
295 signed char crlf; /* crlf mode */
303 * Selection variables:
304 * nb – normalized coordinates of the beginning of the selection
305 * ne – normalized coordinates of the end of the selection
306 * ob – original coordinates of the beginning of the selection
307 * oe – original coordinates of the end of the selection
313 char *primary, *clipboard;
316 struct timespec tclick1;
317 struct timespec tclick2;
330 void (*func)(const Arg *);
334 /* function definitions used in config.h */
335 static void clipcopy(const Arg *);
336 static void clippaste(const Arg *);
337 static void numlock(const Arg *);
338 static void selpaste(const Arg *);
339 static void xzoom(const Arg *);
340 static void xzoomabs(const Arg *);
341 static void xzoomreset(const Arg *);
342 static void printsel(const Arg *);
343 static void printscreen(const Arg *) ;
344 static void iso14755(const Arg *);
345 static void toggleprinter(const Arg *);
346 static void sendbreak(const Arg *);
348 /* Config.h for applying patches and the configuration. */
366 /* Drawing Context */
368 Color col[MAX(LEN(colorname), 256)];
369 Font font, bfont, ifont, ibfont;
373 static void die(const char *, ...);
374 static void draw(void);
375 static void redraw(void);
376 static void drawregion(int, int, int, int);
377 static void execsh(void);
378 static void stty(void);
379 static void sigchld(int);
380 static void run(void);
382 static void csidump(void);
383 static void csihandle(void);
384 static void csiparse(void);
385 static void csireset(void);
386 static int eschandle(uchar);
387 static void strdump(void);
388 static void strhandle(void);
389 static void strparse(void);
390 static void strreset(void);
392 static int tattrset(int);
393 static void tprinter(char *, size_t);
394 static void tdumpsel(void);
395 static void tdumpline(int);
396 static void tdump(void);
397 static void tclearregion(int, int, int, int);
398 static void tcursor(int);
399 static void tdeletechar(int);
400 static void tdeleteline(int);
401 static void tinsertblank(int);
402 static void tinsertblankline(int);
403 static int tlinelen(int);
404 static void tmoveto(int, int);
405 static void tmoveato(int, int);
406 static void tnew(int, int);
407 static void tnewline(int);
408 static void tputtab(int);
409 static void tputc(Rune);
410 static void treset(void);
411 static void tresize(int, int);
412 static void tscrollup(int, int);
413 static void tscrolldown(int, int);
414 static void tsetattr(int *, int);
415 static void tsetchar(Rune, Glyph *, int, int);
416 static void tsetscroll(int, int);
417 static void tswapscreen(void);
418 static void tsetdirt(int, int);
419 static void tsetdirtattr(int);
420 static void tsetmode(int, int, int *, int);
421 static void tfulldirt(void);
422 static void techo(Rune);
423 static void tcontrolcode(uchar );
424 static void tdectest(char );
425 static void tdefutf8(char);
426 static int32_t tdefcolor(int *, int *, int);
427 static void tdeftran(char);
428 static inline int match(uint, uint);
429 static void ttynew(void);
430 static size_t ttyread(void);
431 static void ttyresize(void);
432 static void ttysend(char *, size_t);
433 static void ttywrite(const char *, size_t);
434 static void tstrsequence(uchar);
436 static inline ushort sixd_to_16bit(int);
437 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
438 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
439 static void xdrawglyph(Glyph, int, int);
440 static void xhints(void);
441 static void xclear(int, int, int, int);
442 static void xdrawcursor(void);
443 static void xinit(void);
444 static void xloadcols(void);
445 static int xsetcolorname(int, const char *);
446 static int xgeommasktogravity(int);
447 static int xloadfont(Font *, FcPattern *);
448 static void xloadfonts(char *, double);
449 static void xsettitle(char *);
450 static void xresettitle(void);
451 static void xsetpointermotion(int);
452 static void xseturgency(int);
453 static void xsetsel(char *, Time);
454 static void xunloadfont(Font *);
455 static void xunloadfonts(void);
456 static void xresize(int, int);
458 static void expose(XEvent *);
459 static void visibility(XEvent *);
460 static void unmap(XEvent *);
461 static char *kmap(KeySym, uint);
462 static void kpress(XEvent *);
463 static void cmessage(XEvent *);
464 static void cresize(int, int);
465 static void resize(XEvent *);
466 static void focus(XEvent *);
467 static void brelease(XEvent *);
468 static void bpress(XEvent *);
469 static void bmotion(XEvent *);
470 static void propnotify(XEvent *);
471 static void selnotify(XEvent *);
472 static void selclear(XEvent *);
473 static void selrequest(XEvent *);
475 static void selinit(void);
476 static void selnormalize(void);
477 static inline int selected(int, int);
478 static char *getsel(void);
479 static void selcopy(Time);
480 static void selscroll(int, int);
481 static void selsnap(int *, int *, int);
482 static int x2col(int);
483 static int y2row(int);
484 static void getbuttoninfo(XEvent *);
485 static void mousereport(XEvent *);
487 static size_t utf8decode(char *, Rune *, size_t);
488 static Rune utf8decodebyte(char, size_t *);
489 static size_t utf8encode(Rune, char *);
490 static char utf8encodebyte(Rune, size_t);
491 static char *utf8strchr(char *s, Rune u);
492 static size_t utf8validate(Rune *, size_t);
494 static ssize_t xwrite(int, const char *, size_t);
495 static void *xmalloc(size_t);
496 static void *xrealloc(void *, size_t);
497 static char *xstrdup(char *);
499 static void usage(void);
501 static void (*handler[LASTEvent])(XEvent *) = {
503 [ClientMessage] = cmessage,
504 [ConfigureNotify] = resize,
505 [VisibilityNotify] = visibility,
506 [UnmapNotify] = unmap,
510 [MotionNotify] = bmotion,
511 [ButtonPress] = bpress,
512 [ButtonRelease] = brelease,
514 * Uncomment if you want the selection to disappear when you select something
515 * different in another window.
517 /* [SelectionClear] = selclear, */
518 [SelectionNotify] = selnotify,
520 * PropertyNotify is only turned on when there is some INCR transfer happening
521 * for the selection retrieval.
523 [PropertyNotify] = propnotify,
524 [SelectionRequest] = selrequest,
531 static CSIEscape csiescseq;
532 static STREscape strescseq;
535 static Selection sel;
537 static char **opt_cmd = NULL;
538 static char *opt_class = NULL;
539 static char *opt_embed = NULL;
540 static char *opt_font = NULL;
541 static char *opt_io = NULL;
542 static char *opt_line = NULL;
543 static char *opt_name = NULL;
544 static char *opt_title = NULL;
545 static int oldbutton = 3; /* button event on startup: 3 = release */
547 static char *usedfont = NULL;
548 static double usedfontsize = 0;
549 static double defaultfontsize = 0;
551 static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
552 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
553 static Rune utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
554 static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
556 /* Font Ring Cache */
570 /* Fontcache is an array now. A new font will be appended to the array. */
571 static Fontcache frc[16];
572 static int frclen = 0;
575 xwrite(int fd, const char *s, size_t len)
581 r = write(fd, s, len);
594 void *p = malloc(len);
597 die("Out of memory\n");
603 xrealloc(void *p, size_t len)
605 if ((p = realloc(p, len)) == NULL)
606 die("Out of memory\n");
614 if ((s = strdup(s)) == NULL)
615 die("Out of memory\n");
621 utf8decode(char *c, Rune *u, size_t clen)
623 size_t i, j, len, type;
629 udecoded = utf8decodebyte(c[0], &len);
630 if (!BETWEEN(len, 1, UTF_SIZ))
632 for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
633 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
640 utf8validate(u, len);
646 utf8decodebyte(char c, size_t *i)
648 for (*i = 0; *i < LEN(utfmask); ++(*i))
649 if (((uchar)c & utfmask[*i]) == utfbyte[*i])
650 return (uchar)c & ~utfmask[*i];
656 utf8encode(Rune u, char *c)
660 len = utf8validate(&u, 0);
664 for (i = len - 1; i != 0; --i) {
665 c[i] = utf8encodebyte(u, 0);
668 c[0] = utf8encodebyte(u, len);
674 utf8encodebyte(Rune u, size_t i)
676 return utfbyte[i] | (u & ~utfmask[i]);
680 utf8strchr(char *s, Rune u)
686 for (i = 0, j = 0; i < len; i += j) {
687 if (!(j = utf8decode(&s[i], &r, len - i)))
697 utf8validate(Rune *u, size_t i)
699 if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
701 for (i = 1; *u > utfmax[i]; ++i)
710 clock_gettime(CLOCK_MONOTONIC, &sel.tclick1);
711 clock_gettime(CLOCK_MONOTONIC, &sel.tclick2);
716 sel.clipboard = NULL;
717 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
718 if (sel.xtarget == None)
719 sel.xtarget = XA_STRING;
728 return LIMIT(x, 0, term.col-1);
737 return LIMIT(y, 0, term.row-1);
745 if (term.line[y][i - 1].mode & ATTR_WRAP)
748 while (i > 0 && term.line[y][i - 1].u == ' ')
759 if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
760 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
761 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
763 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
764 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
766 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
767 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
769 selsnap(&sel.nb.x, &sel.nb.y, -1);
770 selsnap(&sel.ne.x, &sel.ne.y, +1);
772 /* expand selection over line breaks */
773 if (sel.type == SEL_RECTANGULAR)
775 i = tlinelen(sel.nb.y);
778 if (tlinelen(sel.ne.y) <= sel.ne.x)
779 sel.ne.x = term.col - 1;
783 selected(int x, int y)
785 if (sel.mode == SEL_EMPTY)
788 if (sel.type == SEL_RECTANGULAR)
789 return BETWEEN(y, sel.nb.y, sel.ne.y)
790 && BETWEEN(x, sel.nb.x, sel.ne.x);
792 return BETWEEN(y, sel.nb.y, sel.ne.y)
793 && (y != sel.nb.y || x >= sel.nb.x)
794 && (y != sel.ne.y || x <= sel.ne.x);
798 selsnap(int *x, int *y, int direction)
800 int newx, newy, xt, yt;
801 int delim, prevdelim;
807 * Snap around if the word wraps around at the end or
808 * beginning of a line.
810 prevgp = &term.line[*y][*x];
811 prevdelim = ISDELIM(prevgp->u);
813 newx = *x + direction;
815 if (!BETWEEN(newx, 0, term.col - 1)) {
817 newx = (newx + term.col) % term.col;
818 if (!BETWEEN(newy, 0, term.row - 1))
824 yt = newy, xt = newx;
825 if (!(term.line[yt][xt].mode & ATTR_WRAP))
829 if (newx >= tlinelen(newy))
832 gp = &term.line[newy][newx];
833 delim = ISDELIM(gp->u);
834 if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
835 || (delim && gp->u != prevgp->u)))
846 * Snap around if the the previous line or the current one
847 * has set ATTR_WRAP at its end. Then the whole next or
848 * previous line will be selected.
850 *x = (direction < 0) ? 0 : term.col - 1;
852 for (; *y > 0; *y += direction) {
853 if (!(term.line[*y-1][term.col-1].mode
858 } else if (direction > 0) {
859 for (; *y < term.row-1; *y += direction) {
860 if (!(term.line[*y][term.col-1].mode
871 getbuttoninfo(XEvent *e)
874 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
876 sel.alt = IS_SET(MODE_ALTSCREEN);
878 sel.oe.x = x2col(e->xbutton.x);
879 sel.oe.y = y2row(e->xbutton.y);
882 sel.type = SEL_REGULAR;
883 for (type = 1; type < LEN(selmasks); ++type) {
884 if (match(selmasks[type], state)) {
892 mousereport(XEvent *e)
894 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
895 button = e->xbutton.button, state = e->xbutton.state,
901 if (e->xbutton.type == MotionNotify) {
902 if (x == ox && y == oy)
904 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
906 /* MOUSE_MOTION: no reporting if no button is pressed */
907 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
910 button = oldbutton + 32;
914 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
921 if (e->xbutton.type == ButtonPress) {
925 } else if (e->xbutton.type == ButtonRelease) {
927 /* MODE_MOUSEX10: no button release reporting */
928 if (IS_SET(MODE_MOUSEX10))
930 if (button == 64 || button == 65)
935 if (!IS_SET(MODE_MOUSEX10)) {
936 button += ((state & ShiftMask ) ? 4 : 0)
937 + ((state & Mod4Mask ) ? 8 : 0)
938 + ((state & ControlMask) ? 16 : 0);
941 if (IS_SET(MODE_MOUSESGR)) {
942 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
944 e->xbutton.type == ButtonRelease ? 'm' : 'M');
945 } else if (x < 223 && y < 223) {
946 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
947 32+button, 32+x+1, 32+y+1);
961 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
966 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
967 if (e->xbutton.button == ms->b
968 && match(ms->mask, e->xbutton.state)) {
969 ttysend(ms->s, strlen(ms->s));
974 if (e->xbutton.button == Button1) {
975 clock_gettime(CLOCK_MONOTONIC, &now);
977 /* Clear previous selection, logically and visually. */
979 sel.mode = SEL_EMPTY;
980 sel.type = SEL_REGULAR;
981 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
982 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
985 * If the user clicks below predefined timeouts specific
986 * snapping behaviour is exposed.
988 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
989 sel.snap = SNAP_LINE;
990 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
991 sel.snap = SNAP_WORD;
998 sel.mode = SEL_READY;
999 tsetdirt(sel.nb.y, sel.ne.y);
1000 sel.tclick2 = sel.tclick1;
1009 int y, bufsize, lastx, linelen;
1015 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
1016 ptr = str = xmalloc(bufsize);
1018 /* append every set & selected glyph to the selection */
1019 for (y = sel.nb.y; y <= sel.ne.y; y++) {
1020 if ((linelen = tlinelen(y)) == 0) {
1025 if (sel.type == SEL_RECTANGULAR) {
1026 gp = &term.line[y][sel.nb.x];
1029 gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
1030 lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
1032 last = &term.line[y][MIN(lastx, linelen-1)];
1033 while (last >= gp && last->u == ' ')
1036 for ( ; gp <= last; ++gp) {
1037 if (gp->mode & ATTR_WDUMMY)
1040 ptr += utf8encode(gp->u, ptr);
1044 * Copy and pasting of line endings is inconsistent
1045 * in the inconsistent terminal and GUI world.
1046 * The best solution seems like to produce '\n' when
1047 * something is copied from st and convert '\n' to
1048 * '\r', when something to be pasted is received by
1050 * FIXME: Fix the computer world.
1052 if ((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
1062 xsetsel(getsel(), t);
1066 propnotify(XEvent *e)
1068 XPropertyEvent *xpev;
1069 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1071 xpev = &e->xproperty;
1072 if (xpev->state == PropertyNewValue &&
1073 (xpev->atom == XA_PRIMARY ||
1074 xpev->atom == clipboard)) {
1080 selnotify(XEvent *e)
1082 ulong nitems, ofs, rem;
1084 uchar *data, *last, *repl;
1085 Atom type, incratom, property;
1087 incratom = XInternAtom(xw.dpy, "INCR", 0);
1090 if (e->type == SelectionNotify) {
1091 property = e->xselection.property;
1092 } else if(e->type == PropertyNotify) {
1093 property = e->xproperty.atom;
1097 if (property == None)
1101 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
1102 BUFSIZ/4, False, AnyPropertyType,
1103 &type, &format, &nitems, &rem,
1105 fprintf(stderr, "Clipboard allocation failed\n");
1109 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
1111 * If there is some PropertyNotify with no data, then
1112 * this is the signal of the selection owner that all
1113 * data has been transferred. We won't need to receive
1114 * PropertyNotify events anymore.
1116 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
1117 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
1121 if (type == incratom) {
1123 * Activate the PropertyNotify events so we receive
1124 * when the selection owner does send us the next
1127 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
1128 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
1132 * Deleting the property is the transfer start signal.
1134 XDeleteProperty(xw.dpy, xw.win, (int)property);
1139 * As seen in getsel:
1140 * Line endings are inconsistent in the terminal and GUI world
1141 * copy and pasting. When receiving some selection data,
1142 * replace all '\n' with '\r'.
1143 * FIXME: Fix the computer world.
1146 last = data + nitems * format / 8;
1147 while ((repl = memchr(repl, '\n', last - repl))) {
1151 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
1152 ttywrite("\033[200~", 6);
1153 ttysend((char *)data, nitems * format / 8);
1154 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
1155 ttywrite("\033[201~", 6);
1157 /* number of 32-bit chunks returned */
1158 ofs += nitems * format / 32;
1162 * Deleting the property again tells the selection owner to send the
1163 * next data chunk in the property.
1165 XDeleteProperty(xw.dpy, xw.win, (int)property);
1169 selpaste(const Arg *dummy)
1171 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1172 xw.win, CurrentTime);
1176 clipcopy(const Arg *dummy)
1180 if (sel.clipboard != NULL)
1181 free(sel.clipboard);
1183 if (sel.primary != NULL) {
1184 sel.clipboard = xstrdup(sel.primary);
1185 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1186 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1191 clippaste(const Arg *dummy)
1195 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1196 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1197 xw.win, CurrentTime);
1205 sel.mode = SEL_IDLE;
1207 tsetdirt(sel.nb.y, sel.ne.y);
1211 selrequest(XEvent *e)
1213 XSelectionRequestEvent *xsre;
1214 XSelectionEvent xev;
1215 Atom xa_targets, string, clipboard;
1218 xsre = (XSelectionRequestEvent *) e;
1219 xev.type = SelectionNotify;
1220 xev.requestor = xsre->requestor;
1221 xev.selection = xsre->selection;
1222 xev.target = xsre->target;
1223 xev.time = xsre->time;
1224 if (xsre->property == None)
1225 xsre->property = xsre->target;
1228 xev.property = None;
1230 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1231 if (xsre->target == xa_targets) {
1232 /* respond with the supported type */
1233 string = sel.xtarget;
1234 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1235 XA_ATOM, 32, PropModeReplace,
1236 (uchar *) &string, 1);
1237 xev.property = xsre->property;
1238 } else if (xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1240 * xith XA_STRING non ascii characters may be incorrect in the
1241 * requestor. It is not our problem, use utf8.
1243 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1244 if (xsre->selection == XA_PRIMARY) {
1245 seltext = sel.primary;
1246 } else if (xsre->selection == clipboard) {
1247 seltext = sel.clipboard;
1250 "Unhandled clipboard selection 0x%lx\n",
1254 if (seltext != NULL) {
1255 XChangeProperty(xsre->display, xsre->requestor,
1256 xsre->property, xsre->target,
1258 (uchar *)seltext, strlen(seltext));
1259 xev.property = xsre->property;
1263 /* all done, send a notification to the listener */
1264 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
1265 fprintf(stderr, "Error sending SelectionNotify event\n");
1269 xsetsel(char *str, Time t)
1274 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
1275 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
1282 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1287 if (e->xbutton.button == Button2) {
1289 } else if (e->xbutton.button == Button1) {
1290 if (sel.mode == SEL_READY) {
1292 selcopy(e->xbutton.time);
1295 sel.mode = SEL_IDLE;
1296 tsetdirt(sel.nb.y, sel.ne.y);
1303 int oldey, oldex, oldsby, oldsey;
1305 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1313 sel.mode = SEL_READY;
1320 if (oldey != sel.oe.y || oldex != sel.oe.x)
1321 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1325 die(const char *errstr, ...)
1329 va_start(ap, errstr);
1330 vfprintf(stderr, errstr, ap);
1338 char **args, *sh, *prog;
1339 const struct passwd *pw;
1340 char buf[sizeof(long) * 8 + 1];
1343 if ((pw = getpwuid(getuid())) == NULL) {
1345 die("getpwuid:%s\n", strerror(errno));
1347 die("who are you?\n");
1350 if ((sh = getenv("SHELL")) == NULL)
1351 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1359 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1361 snprintf(buf, sizeof(buf), "%lu", xw.win);
1363 unsetenv("COLUMNS");
1365 unsetenv("TERMCAP");
1366 setenv("LOGNAME", pw->pw_name, 1);
1367 setenv("USER", pw->pw_name, 1);
1368 setenv("SHELL", sh, 1);
1369 setenv("HOME", pw->pw_dir, 1);
1370 setenv("TERM", termname, 1);
1371 setenv("WINDOWID", buf, 1);
1373 signal(SIGCHLD, SIG_DFL);
1374 signal(SIGHUP, SIG_DFL);
1375 signal(SIGINT, SIG_DFL);
1376 signal(SIGQUIT, SIG_DFL);
1377 signal(SIGTERM, SIG_DFL);
1378 signal(SIGALRM, SIG_DFL);
1390 if ((p = waitpid(pid, &stat, WNOHANG)) < 0)
1391 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1396 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
1397 die("child finished with error '%d'\n", stat);
1405 char cmd[_POSIX_ARG_MAX], **p, *q, *s;
1408 if ((n = strlen(stty_args)) > sizeof(cmd)-1)
1409 die("incorrect stty parameters\n");
1410 memcpy(cmd, stty_args, n);
1412 siz = sizeof(cmd) - n;
1413 for (p = opt_cmd; p && (s = *p); ++p) {
1414 if ((n = strlen(s)) > siz-1)
1415 die("stty parameter length too long\n");
1422 if (system(cmd) != 0)
1423 perror("Couldn't call stty");
1430 struct winsize w = {term.row, term.col, 0, 0};
1433 term.mode |= MODE_PRINT;
1434 iofd = (!strcmp(opt_io, "-")) ?
1435 1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
1437 fprintf(stderr, "Error opening %s:%s\n",
1438 opt_io, strerror(errno));
1443 if ((cmdfd = open(opt_line, O_RDWR)) < 0)
1444 die("open line failed: %s\n", strerror(errno));
1450 /* seems to work fine on linux, openbsd and freebsd */
1451 if (openpty(&m, &s, NULL, NULL, &w) < 0)
1452 die("openpty failed: %s\n", strerror(errno));
1454 switch (pid = fork()) {
1456 die("fork failed\n");
1460 setsid(); /* create a new process group */
1464 if (ioctl(s, TIOCSCTTY, NULL) < 0)
1465 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1473 signal(SIGCHLD, sigchld);
1481 static char buf[BUFSIZ];
1482 static int buflen = 0;
1484 int charsize; /* size of utf8 char in bytes */
1488 /* append read bytes to unprocessed bytes */
1489 if ((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1490 die("Couldn't read from shell: %s\n", strerror(errno));
1496 if (IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
1497 /* process a complete utf8 char */
1498 charsize = utf8decode(ptr, &unicodep, buflen);
1508 tputc(*ptr++ & 0xFF);
1512 /* keep any uncomplete utf8 char for the next call */
1514 memmove(buf, ptr, buflen);
1520 ttywrite(const char *s, size_t n)
1527 * Remember that we are using a pty, which might be a modem line.
1528 * Writing too much will clog the line. That's why we are doing this
1530 * FIXME: Migrate the world to Plan 9.
1535 FD_SET(cmdfd, &wfd);
1536 FD_SET(cmdfd, &rfd);
1538 /* Check if we can write. */
1539 if (pselect(cmdfd+1, &rfd, &wfd, NULL, NULL, NULL) < 0) {
1542 die("select failed: %s\n", strerror(errno));
1544 if (FD_ISSET(cmdfd, &wfd)) {
1546 * Only write the bytes written by ttywrite() or the
1547 * default of 256. This seems to be a reasonable value
1548 * for a serial line. Bigger values might clog the I/O.
1550 if ((r = write(cmdfd, s, (n < lim)? n : lim)) < 0)
1554 * We weren't able to write out everything.
1555 * This means the buffer is getting full
1563 /* All bytes have been written. */
1567 if (FD_ISSET(cmdfd, &rfd))
1573 die("write error on tty: %s\n", strerror(errno));
1577 ttysend(char *s, size_t n)
1584 if (!IS_SET(MODE_ECHO))
1588 for (t = s; t < lim; t += len) {
1589 if (IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
1590 len = utf8decode(t, &u, n);
1607 w.ws_row = term.row;
1608 w.ws_col = term.col;
1609 w.ws_xpixel = xw.tw;
1610 w.ws_ypixel = xw.th;
1611 if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1612 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1620 for (i = 0; i < term.row-1; i++) {
1621 for (j = 0; j < term.col-1; j++) {
1622 if (term.line[i][j].mode & attr)
1631 tsetdirt(int top, int bot)
1635 LIMIT(top, 0, term.row-1);
1636 LIMIT(bot, 0, term.row-1);
1638 for (i = top; i <= bot; i++)
1643 tsetdirtattr(int attr)
1647 for (i = 0; i < term.row-1; i++) {
1648 for (j = 0; j < term.col-1; j++) {
1649 if (term.line[i][j].mode & attr) {
1660 tsetdirt(0, term.row-1);
1666 static TCursor c[2];
1667 int alt = IS_SET(MODE_ALTSCREEN);
1669 if (mode == CURSOR_SAVE) {
1671 } else if (mode == CURSOR_LOAD) {
1673 tmoveto(c[alt].x, c[alt].y);
1682 term.c = (TCursor){{
1686 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1688 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1689 for (i = tabspaces; i < term.col; i += tabspaces)
1692 term.bot = term.row - 1;
1693 term.mode = MODE_WRAP|MODE_UTF8;
1694 memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1697 for (i = 0; i < 2; i++) {
1699 tcursor(CURSOR_SAVE);
1700 tclearregion(0, 0, term.col-1, term.row-1);
1706 tnew(int col, int row)
1708 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1718 Line *tmp = term.line;
1720 term.line = term.alt;
1722 term.mode ^= MODE_ALTSCREEN;
1727 tscrolldown(int orig, int n)
1732 LIMIT(n, 0, term.bot-orig+1);
1734 tsetdirt(orig, term.bot-n);
1735 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1737 for (i = term.bot; i >= orig+n; i--) {
1738 temp = term.line[i];
1739 term.line[i] = term.line[i-n];
1740 term.line[i-n] = temp;
1747 tscrollup(int orig, int n)
1752 LIMIT(n, 0, term.bot-orig+1);
1754 tclearregion(0, orig, term.col-1, orig+n-1);
1755 tsetdirt(orig+n, term.bot);
1757 for (i = orig; i <= term.bot-n; i++) {
1758 temp = term.line[i];
1759 term.line[i] = term.line[i+n];
1760 term.line[i+n] = temp;
1763 selscroll(orig, -n);
1767 selscroll(int orig, int n)
1772 if (BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1773 if ((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1777 if (sel.type == SEL_RECTANGULAR) {
1778 if (sel.ob.y < term.top)
1779 sel.ob.y = term.top;
1780 if (sel.oe.y > term.bot)
1781 sel.oe.y = term.bot;
1783 if (sel.ob.y < term.top) {
1784 sel.ob.y = term.top;
1787 if (sel.oe.y > term.bot) {
1788 sel.oe.y = term.bot;
1789 sel.oe.x = term.col;
1797 tnewline(int first_col)
1801 if (y == term.bot) {
1802 tscrollup(term.top, 1);
1806 tmoveto(first_col ? 0 : term.c.x, y);
1812 char *p = csiescseq.buf, *np;
1821 csiescseq.buf[csiescseq.len] = '\0';
1822 while (p < csiescseq.buf+csiescseq.len) {
1824 v = strtol(p, &np, 10);
1827 if (v == LONG_MAX || v == LONG_MIN)
1829 csiescseq.arg[csiescseq.narg++] = v;
1831 if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1835 csiescseq.mode[0] = *p++;
1836 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1839 /* for absolute user moves, when decom is set */
1841 tmoveato(int x, int y)
1843 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1847 tmoveto(int x, int y)
1851 if (term.c.state & CURSOR_ORIGIN) {
1856 maxy = term.row - 1;
1858 term.c.state &= ~CURSOR_WRAPNEXT;
1859 term.c.x = LIMIT(x, 0, term.col-1);
1860 term.c.y = LIMIT(y, miny, maxy);
1864 tsetchar(Rune u, Glyph *attr, int x, int y)
1866 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1867 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1868 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1869 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1870 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1871 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1872 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1873 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1874 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1878 * The table is proudly stolen from rxvt.
1880 if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
1881 BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1882 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1884 if (term.line[y][x].mode & ATTR_WIDE) {
1885 if (x+1 < term.col) {
1886 term.line[y][x+1].u = ' ';
1887 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1889 } else if (term.line[y][x].mode & ATTR_WDUMMY) {
1890 term.line[y][x-1].u = ' ';
1891 term.line[y][x-1].mode &= ~ATTR_WIDE;
1895 term.line[y][x] = *attr;
1896 term.line[y][x].u = u;
1900 tclearregion(int x1, int y1, int x2, int y2)
1906 temp = x1, x1 = x2, x2 = temp;
1908 temp = y1, y1 = y2, y2 = temp;
1910 LIMIT(x1, 0, term.col-1);
1911 LIMIT(x2, 0, term.col-1);
1912 LIMIT(y1, 0, term.row-1);
1913 LIMIT(y2, 0, term.row-1);
1915 for (y = y1; y <= y2; y++) {
1917 for (x = x1; x <= x2; x++) {
1918 gp = &term.line[y][x];
1921 gp->fg = term.c.attr.fg;
1922 gp->bg = term.c.attr.bg;
1935 LIMIT(n, 0, term.col - term.c.x);
1939 size = term.col - src;
1940 line = term.line[term.c.y];
1942 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1943 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1952 LIMIT(n, 0, term.col - term.c.x);
1956 size = term.col - dst;
1957 line = term.line[term.c.y];
1959 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1960 tclearregion(src, term.c.y, dst - 1, term.c.y);
1964 tinsertblankline(int n)
1966 if (BETWEEN(term.c.y, term.top, term.bot))
1967 tscrolldown(term.c.y, n);
1973 if (BETWEEN(term.c.y, term.top, term.bot))
1974 tscrollup(term.c.y, n);
1978 tdefcolor(int *attr, int *npar, int l)
1983 switch (attr[*npar + 1]) {
1984 case 2: /* direct color in RGB space */
1985 if (*npar + 4 >= l) {
1987 "erresc(38): Incorrect number of parameters (%d)\n",
1991 r = attr[*npar + 2];
1992 g = attr[*npar + 3];
1993 b = attr[*npar + 4];
1995 if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1996 fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1999 idx = TRUECOLOR(r, g, b);
2001 case 5: /* indexed color */
2002 if (*npar + 2 >= l) {
2004 "erresc(38): Incorrect number of parameters (%d)\n",
2009 if (!BETWEEN(attr[*npar], 0, 255))
2010 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
2014 case 0: /* implemented defined (only foreground) */
2015 case 1: /* transparent */
2016 case 3: /* direct color in CMY space */
2017 case 4: /* direct color in CMYK space */
2020 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
2028 tsetattr(int *attr, int l)
2033 for (i = 0; i < l; i++) {
2036 term.c.attr.mode &= ~(
2045 term.c.attr.fg = defaultfg;
2046 term.c.attr.bg = defaultbg;
2049 term.c.attr.mode |= ATTR_BOLD;
2052 term.c.attr.mode |= ATTR_FAINT;
2055 term.c.attr.mode |= ATTR_ITALIC;
2058 term.c.attr.mode |= ATTR_UNDERLINE;
2060 case 5: /* slow blink */
2062 case 6: /* rapid blink */
2063 term.c.attr.mode |= ATTR_BLINK;
2066 term.c.attr.mode |= ATTR_REVERSE;
2069 term.c.attr.mode |= ATTR_INVISIBLE;
2072 term.c.attr.mode |= ATTR_STRUCK;
2075 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
2078 term.c.attr.mode &= ~ATTR_ITALIC;
2081 term.c.attr.mode &= ~ATTR_UNDERLINE;
2084 term.c.attr.mode &= ~ATTR_BLINK;
2087 term.c.attr.mode &= ~ATTR_REVERSE;
2090 term.c.attr.mode &= ~ATTR_INVISIBLE;
2093 term.c.attr.mode &= ~ATTR_STRUCK;
2096 if ((idx = tdefcolor(attr, &i, l)) >= 0)
2097 term.c.attr.fg = idx;
2100 term.c.attr.fg = defaultfg;
2103 if ((idx = tdefcolor(attr, &i, l)) >= 0)
2104 term.c.attr.bg = idx;
2107 term.c.attr.bg = defaultbg;
2110 if (BETWEEN(attr[i], 30, 37)) {
2111 term.c.attr.fg = attr[i] - 30;
2112 } else if (BETWEEN(attr[i], 40, 47)) {
2113 term.c.attr.bg = attr[i] - 40;
2114 } else if (BETWEEN(attr[i], 90, 97)) {
2115 term.c.attr.fg = attr[i] - 90 + 8;
2116 } else if (BETWEEN(attr[i], 100, 107)) {
2117 term.c.attr.bg = attr[i] - 100 + 8;
2120 "erresc(default): gfx attr %d unknown\n",
2121 attr[i]), csidump();
2129 tsetscroll(int t, int b)
2133 LIMIT(t, 0, term.row-1);
2134 LIMIT(b, 0, term.row-1);
2145 tsetmode(int priv, int set, int *args, int narg)
2150 for (lim = args + narg; args < lim; ++args) {
2153 case 1: /* DECCKM -- Cursor key */
2154 MODBIT(term.mode, set, MODE_APPCURSOR);
2156 case 5: /* DECSCNM -- Reverse video */
2158 MODBIT(term.mode, set, MODE_REVERSE);
2159 if (mode != term.mode)
2162 case 6: /* DECOM -- Origin */
2163 MODBIT(term.c.state, set, CURSOR_ORIGIN);
2166 case 7: /* DECAWM -- Auto wrap */
2167 MODBIT(term.mode, set, MODE_WRAP);
2169 case 0: /* Error (IGNORED) */
2170 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
2171 case 3: /* DECCOLM -- Column (IGNORED) */
2172 case 4: /* DECSCLM -- Scroll (IGNORED) */
2173 case 8: /* DECARM -- Auto repeat (IGNORED) */
2174 case 18: /* DECPFF -- Printer feed (IGNORED) */
2175 case 19: /* DECPEX -- Printer extent (IGNORED) */
2176 case 42: /* DECNRCM -- National characters (IGNORED) */
2177 case 12: /* att610 -- Start blinking cursor (IGNORED) */
2179 case 25: /* DECTCEM -- Text Cursor Enable Mode */
2180 MODBIT(term.mode, !set, MODE_HIDE);
2182 case 9: /* X10 mouse compatibility mode */
2183 xsetpointermotion(0);
2184 MODBIT(term.mode, 0, MODE_MOUSE);
2185 MODBIT(term.mode, set, MODE_MOUSEX10);
2187 case 1000: /* 1000: report button press */
2188 xsetpointermotion(0);
2189 MODBIT(term.mode, 0, MODE_MOUSE);
2190 MODBIT(term.mode, set, MODE_MOUSEBTN);
2192 case 1002: /* 1002: report motion on button press */
2193 xsetpointermotion(0);
2194 MODBIT(term.mode, 0, MODE_MOUSE);
2195 MODBIT(term.mode, set, MODE_MOUSEMOTION);
2197 case 1003: /* 1003: enable all mouse motions */
2198 xsetpointermotion(set);
2199 MODBIT(term.mode, 0, MODE_MOUSE);
2200 MODBIT(term.mode, set, MODE_MOUSEMANY);
2202 case 1004: /* 1004: send focus events to tty */
2203 MODBIT(term.mode, set, MODE_FOCUS);
2205 case 1006: /* 1006: extended reporting mode */
2206 MODBIT(term.mode, set, MODE_MOUSESGR);
2209 MODBIT(term.mode, set, MODE_8BIT);
2211 case 1049: /* swap screen & set/restore cursor as xterm */
2212 if (!allowaltscreen)
2214 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2216 case 47: /* swap screen */
2218 if (!allowaltscreen)
2220 alt = IS_SET(MODE_ALTSCREEN);
2222 tclearregion(0, 0, term.col-1,
2225 if (set ^ alt) /* set is always 1 or 0 */
2231 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2233 case 2004: /* 2004: bracketed paste mode */
2234 MODBIT(term.mode, set, MODE_BRCKTPASTE);
2236 /* Not implemented mouse modes. See comments there. */
2237 case 1001: /* mouse highlight mode; can hang the
2238 terminal by design when implemented. */
2239 case 1005: /* UTF-8 mouse mode; will confuse
2240 applications not supporting UTF-8
2242 case 1015: /* urxvt mangled mouse mode; incompatible
2243 and can be mistaken for other control
2247 "erresc: unknown private set/reset mode %d\n",
2253 case 0: /* Error (IGNORED) */
2255 case 2: /* KAM -- keyboard action */
2256 MODBIT(term.mode, set, MODE_KBDLOCK);
2258 case 4: /* IRM -- Insertion-replacement */
2259 MODBIT(term.mode, set, MODE_INSERT);
2261 case 12: /* SRM -- Send/Receive */
2262 MODBIT(term.mode, !set, MODE_ECHO);
2264 case 20: /* LNM -- Linefeed/new line */
2265 MODBIT(term.mode, set, MODE_CRLF);
2269 "erresc: unknown set/reset mode %d\n",
2283 switch (csiescseq.mode[0]) {
2286 fprintf(stderr, "erresc: unknown csi ");
2290 case '@': /* ICH -- Insert <n> blank char */
2291 DEFAULT(csiescseq.arg[0], 1);
2292 tinsertblank(csiescseq.arg[0]);
2294 case 'A': /* CUU -- Cursor <n> Up */
2295 DEFAULT(csiescseq.arg[0], 1);
2296 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2298 case 'B': /* CUD -- Cursor <n> Down */
2299 case 'e': /* VPR --Cursor <n> Down */
2300 DEFAULT(csiescseq.arg[0], 1);
2301 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2303 case 'i': /* MC -- Media Copy */
2304 switch (csiescseq.arg[0]) {
2309 tdumpline(term.c.y);
2315 term.mode &= ~MODE_PRINT;
2318 term.mode |= MODE_PRINT;
2322 case 'c': /* DA -- Device Attributes */
2323 if (csiescseq.arg[0] == 0)
2324 ttywrite(vtiden, sizeof(vtiden) - 1);
2326 case 'C': /* CUF -- Cursor <n> Forward */
2327 case 'a': /* HPR -- Cursor <n> Forward */
2328 DEFAULT(csiescseq.arg[0], 1);
2329 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2331 case 'D': /* CUB -- Cursor <n> Backward */
2332 DEFAULT(csiescseq.arg[0], 1);
2333 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2335 case 'E': /* CNL -- Cursor <n> Down and first col */
2336 DEFAULT(csiescseq.arg[0], 1);
2337 tmoveto(0, term.c.y+csiescseq.arg[0]);
2339 case 'F': /* CPL -- Cursor <n> Up and first col */
2340 DEFAULT(csiescseq.arg[0], 1);
2341 tmoveto(0, term.c.y-csiescseq.arg[0]);
2343 case 'g': /* TBC -- Tabulation clear */
2344 switch (csiescseq.arg[0]) {
2345 case 0: /* clear current tab stop */
2346 term.tabs[term.c.x] = 0;
2348 case 3: /* clear all the tabs */
2349 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2355 case 'G': /* CHA -- Move to <col> */
2357 DEFAULT(csiescseq.arg[0], 1);
2358 tmoveto(csiescseq.arg[0]-1, term.c.y);
2360 case 'H': /* CUP -- Move to <row> <col> */
2362 DEFAULT(csiescseq.arg[0], 1);
2363 DEFAULT(csiescseq.arg[1], 1);
2364 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2366 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2367 DEFAULT(csiescseq.arg[0], 1);
2368 tputtab(csiescseq.arg[0]);
2370 case 'J': /* ED -- Clear screen */
2372 switch (csiescseq.arg[0]) {
2374 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2375 if (term.c.y < term.row-1) {
2376 tclearregion(0, term.c.y+1, term.col-1,
2382 tclearregion(0, 0, term.col-1, term.c.y-1);
2383 tclearregion(0, term.c.y, term.c.x, term.c.y);
2386 tclearregion(0, 0, term.col-1, term.row-1);
2392 case 'K': /* EL -- Clear line */
2393 switch (csiescseq.arg[0]) {
2395 tclearregion(term.c.x, term.c.y, term.col-1,
2399 tclearregion(0, term.c.y, term.c.x, term.c.y);
2402 tclearregion(0, term.c.y, term.col-1, term.c.y);
2406 case 'S': /* SU -- Scroll <n> line up */
2407 DEFAULT(csiescseq.arg[0], 1);
2408 tscrollup(term.top, csiescseq.arg[0]);
2410 case 'T': /* SD -- Scroll <n> line down */
2411 DEFAULT(csiescseq.arg[0], 1);
2412 tscrolldown(term.top, csiescseq.arg[0]);
2414 case 'L': /* IL -- Insert <n> blank lines */
2415 DEFAULT(csiescseq.arg[0], 1);
2416 tinsertblankline(csiescseq.arg[0]);
2418 case 'l': /* RM -- Reset Mode */
2419 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2421 case 'M': /* DL -- Delete <n> lines */
2422 DEFAULT(csiescseq.arg[0], 1);
2423 tdeleteline(csiescseq.arg[0]);
2425 case 'X': /* ECH -- Erase <n> char */
2426 DEFAULT(csiescseq.arg[0], 1);
2427 tclearregion(term.c.x, term.c.y,
2428 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2430 case 'P': /* DCH -- Delete <n> char */
2431 DEFAULT(csiescseq.arg[0], 1);
2432 tdeletechar(csiescseq.arg[0]);
2434 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2435 DEFAULT(csiescseq.arg[0], 1);
2436 tputtab(-csiescseq.arg[0]);
2438 case 'd': /* VPA -- Move to <row> */
2439 DEFAULT(csiescseq.arg[0], 1);
2440 tmoveato(term.c.x, csiescseq.arg[0]-1);
2442 case 'h': /* SM -- Set terminal mode */
2443 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2445 case 'm': /* SGR -- Terminal attribute (color) */
2446 tsetattr(csiescseq.arg, csiescseq.narg);
2448 case 'n': /* DSR – Device Status Report (cursor position) */
2449 if (csiescseq.arg[0] == 6) {
2450 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2451 term.c.y+1, term.c.x+1);
2455 case 'r': /* DECSTBM -- Set Scrolling Region */
2456 if (csiescseq.priv) {
2459 DEFAULT(csiescseq.arg[0], 1);
2460 DEFAULT(csiescseq.arg[1], term.row);
2461 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2465 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2466 tcursor(CURSOR_SAVE);
2468 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2469 tcursor(CURSOR_LOAD);
2472 switch (csiescseq.mode[1]) {
2473 case 'q': /* DECSCUSR -- Set Cursor Style */
2474 DEFAULT(csiescseq.arg[0], 1);
2475 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2478 xw.cursor = csiescseq.arg[0];
2493 fprintf(stderr, "ESC[");
2494 for (i = 0; i < csiescseq.len; i++) {
2495 c = csiescseq.buf[i] & 0xff;
2498 } else if (c == '\n') {
2499 fprintf(stderr, "(\\n)");
2500 } else if (c == '\r') {
2501 fprintf(stderr, "(\\r)");
2502 } else if (c == 0x1b) {
2503 fprintf(stderr, "(\\e)");
2505 fprintf(stderr, "(%02x)", c);
2514 memset(&csiescseq, 0, sizeof(csiescseq));
2523 term.esc &= ~(ESC_STR_END|ESC_STR);
2525 par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2527 switch (strescseq.type) {
2528 case ']': /* OSC -- Operating System Command */
2534 xsettitle(strescseq.args[1]);
2536 case 4: /* color set */
2539 p = strescseq.args[2];
2541 case 104: /* color reset, here p = NULL */
2542 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2543 if (xsetcolorname(j, p)) {
2544 fprintf(stderr, "erresc: invalid color %s\n", p);
2547 * TODO if defaultbg color is changed, borders
2555 case 'k': /* old title set compatibility */
2556 xsettitle(strescseq.args[0]);
2558 case 'P': /* DCS -- Device Control String */
2559 term.mode |= ESC_DCS;
2560 case '_': /* APC -- Application Program Command */
2561 case '^': /* PM -- Privacy Message */
2565 fprintf(stderr, "erresc: unknown str ");
2573 char *p = strescseq.buf;
2576 strescseq.buf[strescseq.len] = '\0';
2581 while (strescseq.narg < STR_ARG_SIZ) {
2582 strescseq.args[strescseq.narg++] = p;
2583 while ((c = *p) != ';' && c != '\0')
2597 fprintf(stderr, "ESC%c", strescseq.type);
2598 for (i = 0; i < strescseq.len; i++) {
2599 c = strescseq.buf[i] & 0xff;
2603 } else if (isprint(c)) {
2605 } else if (c == '\n') {
2606 fprintf(stderr, "(\\n)");
2607 } else if (c == '\r') {
2608 fprintf(stderr, "(\\r)");
2609 } else if (c == 0x1b) {
2610 fprintf(stderr, "(\\e)");
2612 fprintf(stderr, "(%02x)", c);
2615 fprintf(stderr, "ESC\\\n");
2621 memset(&strescseq, 0, sizeof(strescseq));
2625 sendbreak(const Arg *arg)
2627 if (tcsendbreak(cmdfd, 0))
2628 perror("Error sending break");
2632 tprinter(char *s, size_t len)
2634 if (iofd != -1 && xwrite(iofd, s, len) < 0) {
2635 fprintf(stderr, "Error writing in %s:%s\n",
2636 opt_io, strerror(errno));
2643 iso14755(const Arg *arg)
2645 char cmd[sizeof(ISO14755CMD) + NUMMAXLEN(xw.win)];
2647 char *us, *e, codepoint[9], uc[UTF_SIZ];
2648 unsigned long utf32;
2650 snprintf(cmd, sizeof(cmd), ISO14755CMD, xw.win);
2651 if (!(p = popen(cmd, "r")))
2654 us = fgets(codepoint, sizeof(codepoint), p);
2657 if (!us || *us == '\0' || *us == '-' || strlen(us) > 7)
2659 if ((utf32 = strtoul(us, &e, 16)) == ULONG_MAX ||
2660 (*e != '\n' && *e != '\0'))
2663 ttysend(uc, utf8encode(utf32, uc));
2667 toggleprinter(const Arg *arg)
2669 term.mode ^= MODE_PRINT;
2673 printscreen(const Arg *arg)
2679 printsel(const Arg *arg)
2689 if ((ptr = getsel())) {
2690 tprinter(ptr, strlen(ptr));
2701 bp = &term.line[n][0];
2702 end = &bp[MIN(tlinelen(n), term.col) - 1];
2703 if (bp != end || bp->u != ' ') {
2704 for ( ;bp <= end; ++bp)
2705 tprinter(buf, utf8encode(bp->u, buf));
2715 for (i = 0; i < term.row; ++i)
2725 while (x < term.col && n--)
2726 for (++x; x < term.col && !term.tabs[x]; ++x)
2729 while (x > 0 && n++)
2730 for (--x; x > 0 && !term.tabs[x]; --x)
2733 term.c.x = LIMIT(x, 0, term.col-1);
2739 if (ISCONTROL(u)) { /* control code */
2744 } else if (u != '\n' && u != '\r' && u != '\t') {
2753 tdefutf8(char ascii)
2756 term.mode |= MODE_UTF8;
2757 else if (ascii == '@')
2758 term.mode &= ~MODE_UTF8;
2762 tdeftran(char ascii)
2764 static char cs[] = "0B";
2765 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2768 if ((p = strchr(cs, ascii)) == NULL) {
2769 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2771 term.trantbl[term.icharset] = vcs[p - cs];
2780 if (c == '8') { /* DEC screen alignment test. */
2781 for (x = 0; x < term.col; ++x) {
2782 for (y = 0; y < term.row; ++y)
2783 tsetchar('E', &term.c.attr, x, y);
2789 tstrsequence(uchar c)
2794 case 0x90: /* DCS -- Device Control String */
2796 term.esc |= ESC_DCS;
2798 case 0x9f: /* APC -- Application Program Command */
2801 case 0x9e: /* PM -- Privacy Message */
2804 case 0x9d: /* OSC -- Operating System Command */
2809 term.esc |= ESC_STR;
2813 tcontrolcode(uchar ascii)
2820 tmoveto(term.c.x-1, term.c.y);
2823 tmoveto(0, term.c.y);
2828 /* go to first col if the mode is set */
2829 tnewline(IS_SET(MODE_CRLF));
2831 case '\a': /* BEL */
2832 if (term.esc & ESC_STR_END) {
2833 /* backwards compatibility to xterm */
2836 if (!(xw.state & WIN_FOCUSED))
2839 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2842 case '\033': /* ESC */
2844 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2845 term.esc |= ESC_START;
2847 case '\016': /* SO (LS1 -- Locking shift 1) */
2848 case '\017': /* SI (LS0 -- Locking shift 0) */
2849 term.charset = 1 - (ascii - '\016');
2851 case '\032': /* SUB */
2852 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2853 case '\030': /* CAN */
2856 case '\005': /* ENQ (IGNORED) */
2857 case '\000': /* NUL (IGNORED) */
2858 case '\021': /* XON (IGNORED) */
2859 case '\023': /* XOFF (IGNORED) */
2860 case 0177: /* DEL (IGNORED) */
2862 case 0x80: /* TODO: PAD */
2863 case 0x81: /* TODO: HOP */
2864 case 0x82: /* TODO: BPH */
2865 case 0x83: /* TODO: NBH */
2866 case 0x84: /* TODO: IND */
2868 case 0x85: /* NEL -- Next line */
2869 tnewline(1); /* always go to first col */
2871 case 0x86: /* TODO: SSA */
2872 case 0x87: /* TODO: ESA */
2874 case 0x88: /* HTS -- Horizontal tab stop */
2875 term.tabs[term.c.x] = 1;
2877 case 0x89: /* TODO: HTJ */
2878 case 0x8a: /* TODO: VTS */
2879 case 0x8b: /* TODO: PLD */
2880 case 0x8c: /* TODO: PLU */
2881 case 0x8d: /* TODO: RI */
2882 case 0x8e: /* TODO: SS2 */
2883 case 0x8f: /* TODO: SS3 */
2884 case 0x91: /* TODO: PU1 */
2885 case 0x92: /* TODO: PU2 */
2886 case 0x93: /* TODO: STS */
2887 case 0x94: /* TODO: CCH */
2888 case 0x95: /* TODO: MW */
2889 case 0x96: /* TODO: SPA */
2890 case 0x97: /* TODO: EPA */
2891 case 0x98: /* TODO: SOS */
2892 case 0x99: /* TODO: SGCI */
2894 case 0x9a: /* DECID -- Identify Terminal */
2895 ttywrite(vtiden, sizeof(vtiden) - 1);
2897 case 0x9b: /* TODO: CSI */
2898 case 0x9c: /* TODO: ST */
2900 case 0x90: /* DCS -- Device Control String */
2901 case 0x9d: /* OSC -- Operating System Command */
2902 case 0x9e: /* PM -- Privacy Message */
2903 case 0x9f: /* APC -- Application Program Command */
2904 tstrsequence(ascii);
2907 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2908 term.esc &= ~(ESC_STR_END|ESC_STR);
2912 * returns 1 when the sequence is finished and it hasn't to read
2913 * more characters for this sequence, otherwise 0
2916 eschandle(uchar ascii)
2920 term.esc |= ESC_CSI;
2923 term.esc |= ESC_TEST;
2926 term.esc |= ESC_UTF8;
2928 case 'P': /* DCS -- Device Control String */
2929 case '_': /* APC -- Application Program Command */
2930 case '^': /* PM -- Privacy Message */
2931 case ']': /* OSC -- Operating System Command */
2932 case 'k': /* old title set compatibility */
2933 tstrsequence(ascii);
2935 case 'n': /* LS2 -- Locking shift 2 */
2936 case 'o': /* LS3 -- Locking shift 3 */
2937 term.charset = 2 + (ascii - 'n');
2939 case '(': /* GZD4 -- set primary charset G0 */
2940 case ')': /* G1D4 -- set secondary charset G1 */
2941 case '*': /* G2D4 -- set tertiary charset G2 */
2942 case '+': /* G3D4 -- set quaternary charset G3 */
2943 term.icharset = ascii - '(';
2944 term.esc |= ESC_ALTCHARSET;
2946 case 'D': /* IND -- Linefeed */
2947 if (term.c.y == term.bot) {
2948 tscrollup(term.top, 1);
2950 tmoveto(term.c.x, term.c.y+1);
2953 case 'E': /* NEL -- Next line */
2954 tnewline(1); /* always go to first col */
2956 case 'H': /* HTS -- Horizontal tab stop */
2957 term.tabs[term.c.x] = 1;
2959 case 'M': /* RI -- Reverse index */
2960 if (term.c.y == term.top) {
2961 tscrolldown(term.top, 1);
2963 tmoveto(term.c.x, term.c.y-1);
2966 case 'Z': /* DECID -- Identify Terminal */
2967 ttywrite(vtiden, sizeof(vtiden) - 1);
2969 case 'c': /* RIS -- Reset to inital state */
2974 case '=': /* DECPAM -- Application keypad */
2975 term.mode |= MODE_APPKEYPAD;
2977 case '>': /* DECPNM -- Normal keypad */
2978 term.mode &= ~MODE_APPKEYPAD;
2980 case '7': /* DECSC -- Save Cursor */
2981 tcursor(CURSOR_SAVE);
2983 case '8': /* DECRC -- Restore Cursor */
2984 tcursor(CURSOR_LOAD);
2986 case '\\': /* ST -- String Terminator */
2987 if (term.esc & ESC_STR_END)
2991 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2992 (uchar) ascii, isprint(ascii)? ascii:'.');
3006 control = ISCONTROL(u);
3007 if (!IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
3011 len = utf8encode(u, c);
3012 if (!control && (width = wcwidth(u)) == -1) {
3013 memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
3018 if (IS_SET(MODE_PRINT))
3022 * STR sequence must be checked before anything else
3023 * because it uses all following characters until it
3024 * receives a ESC, a SUB, a ST or any other C1 control
3027 if (term.esc & ESC_STR) {
3028 if (u == '\a' || u == 030 || u == 032 || u == 033 ||
3030 term.esc &= ~(ESC_START|ESC_STR|ESC_DCS);
3031 if (IS_SET(MODE_SIXEL)) {
3032 /* TODO: render sixel */;
3033 term.mode &= ~MODE_SIXEL;
3036 term.esc |= ESC_STR_END;
3037 goto check_control_code;
3041 if (IS_SET(MODE_SIXEL)) {
3042 /* TODO: implement sixel mode */
3045 if (term.esc&ESC_DCS && strescseq.len == 0 && u == 'q')
3046 term.mode |= MODE_SIXEL;
3048 if (strescseq.len+len >= sizeof(strescseq.buf)-1) {
3050 * Here is a bug in terminals. If the user never sends
3051 * some code to stop the str or esc command, then st
3052 * will stop responding. But this is better than
3053 * silently failing with unknown characters. At least
3054 * then users will report back.
3056 * In the case users ever get fixed, here is the code:
3065 memmove(&strescseq.buf[strescseq.len], c, len);
3066 strescseq.len += len;
3072 * Actions of control codes must be performed as soon they arrive
3073 * because they can be embedded inside a control sequence, and
3074 * they must not cause conflicts with sequences.
3079 * control codes are not shown ever
3082 } else if (term.esc & ESC_START) {
3083 if (term.esc & ESC_CSI) {
3084 csiescseq.buf[csiescseq.len++] = u;
3085 if (BETWEEN(u, 0x40, 0x7E)
3086 || csiescseq.len >= \
3087 sizeof(csiescseq.buf)-1) {
3093 } else if (term.esc & ESC_UTF8) {
3095 } else if (term.esc & ESC_ALTCHARSET) {
3097 } else if (term.esc & ESC_TEST) {
3102 /* sequence already finished */
3106 * All characters which form part of a sequence are not
3111 if (sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
3114 gp = &term.line[term.c.y][term.c.x];
3115 if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
3116 gp->mode |= ATTR_WRAP;
3118 gp = &term.line[term.c.y][term.c.x];
3121 if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
3122 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
3124 if (term.c.x+width > term.col) {
3126 gp = &term.line[term.c.y][term.c.x];
3129 tsetchar(u, &term.c.attr, term.c.x, term.c.y);
3132 gp->mode |= ATTR_WIDE;
3133 if (term.c.x+1 < term.col) {
3135 gp[1].mode = ATTR_WDUMMY;
3138 if (term.c.x+width < term.col) {
3139 tmoveto(term.c.x+width, term.c.y);
3141 term.c.state |= CURSOR_WRAPNEXT;
3146 tresize(int col, int row)
3149 int minrow = MIN(row, term.row);
3150 int mincol = MIN(col, term.col);
3154 if (col < 1 || row < 1) {
3156 "tresize: error resizing to %dx%d\n", col, row);
3161 * slide screen to keep cursor where we expect it -
3162 * tscrollup would work here, but we can optimize to
3163 * memmove because we're freeing the earlier lines
3165 for (i = 0; i <= term.c.y - row; i++) {
3169 /* ensure that both src and dst are not NULL */
3171 memmove(term.line, term.line + i, row * sizeof(Line));
3172 memmove(term.alt, term.alt + i, row * sizeof(Line));
3174 for (i += row; i < term.row; i++) {
3179 /* resize to new width */
3180 term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
3182 /* resize to new height */
3183 term.line = xrealloc(term.line, row * sizeof(Line));
3184 term.alt = xrealloc(term.alt, row * sizeof(Line));
3185 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
3186 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
3188 /* resize each row to new width, zero-pad if needed */
3189 for (i = 0; i < minrow; i++) {
3190 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
3191 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
3194 /* allocate any new rows */
3195 for (/* i == minrow */; i < row; i++) {
3196 term.line[i] = xmalloc(col * sizeof(Glyph));
3197 term.alt[i] = xmalloc(col * sizeof(Glyph));
3199 if (col > term.col) {
3200 bp = term.tabs + term.col;
3202 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
3203 while (--bp > term.tabs && !*bp)
3205 for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
3208 /* update terminal size */
3211 /* reset scrolling region */
3212 tsetscroll(0, row-1);
3213 /* make use of the LIMIT in tmoveto */
3214 tmoveto(term.c.x, term.c.y);
3215 /* Clearing both screens (it makes dirty all lines) */
3217 for (i = 0; i < 2; i++) {
3218 if (mincol < col && 0 < minrow) {
3219 tclearregion(mincol, 0, col - 1, minrow - 1);
3221 if (0 < col && minrow < row) {
3222 tclearregion(0, minrow, col - 1, row - 1);
3225 tcursor(CURSOR_LOAD);
3231 xresize(int col, int row)
3233 xw.tw = MAX(1, col * xw.cw);
3234 xw.th = MAX(1, row * xw.ch);
3236 XFreePixmap(xw.dpy, xw.buf);
3237 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3238 DefaultDepth(xw.dpy, xw.scr));
3239 XftDrawChange(xw.draw, xw.buf);
3240 xclear(0, 0, xw.w, xw.h);
3244 sixd_to_16bit(int x)
3246 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
3250 xloadcolor(int i, const char *name, Color *ncolor)
3252 XRenderColor color = { .alpha = 0xffff };
3255 if (BETWEEN(i, 16, 255)) { /* 256 color */
3256 if (i < 6*6*6+16) { /* same colors as xterm */
3257 color.red = sixd_to_16bit( ((i-16)/36)%6 );
3258 color.green = sixd_to_16bit( ((i-16)/6) %6 );
3259 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
3260 } else { /* greyscale */
3261 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
3262 color.green = color.blue = color.red;
3264 return XftColorAllocValue(xw.dpy, xw.vis,
3265 xw.cmap, &color, ncolor);
3267 name = colorname[i];
3270 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
3281 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
3282 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
3285 for (i = 0; i < LEN(dc.col); i++)
3286 if (!xloadcolor(i, NULL, &dc.col[i])) {
3288 die("Could not allocate color '%s'\n", colorname[i]);
3290 die("Could not allocate color %d\n", i);
3296 xsetcolorname(int x, const char *name)
3300 if (!BETWEEN(x, 0, LEN(dc.col)))
3304 if (!xloadcolor(x, name, &ncolor))
3307 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
3314 * Absolute coordinates.
3317 xclear(int x1, int y1, int x2, int y2)
3319 XftDrawRect(xw.draw,
3320 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
3321 x1, y1, x2-x1, y2-y1);
3327 XClassHint class = {opt_name ? opt_name : termname,
3328 opt_class ? opt_class : termname};
3329 XWMHints wm = {.flags = InputHint, .input = 1};
3330 XSizeHints *sizeh = NULL;
3332 sizeh = XAllocSizeHints();
3334 sizeh->flags = PSize | PResizeInc | PBaseSize;
3335 sizeh->height = xw.h;
3336 sizeh->width = xw.w;
3337 sizeh->height_inc = xw.ch;
3338 sizeh->width_inc = xw.cw;
3339 sizeh->base_height = 2 * borderpx;
3340 sizeh->base_width = 2 * borderpx;
3342 sizeh->flags |= PMaxSize | PMinSize;
3343 sizeh->min_width = sizeh->max_width = xw.w;
3344 sizeh->min_height = sizeh->max_height = xw.h;
3346 if (xw.gm & (XValue|YValue)) {
3347 sizeh->flags |= USPosition | PWinGravity;
3350 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3353 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3359 xgeommasktogravity(int mask)
3361 switch (mask & (XNegative|YNegative)) {
3363 return NorthWestGravity;
3365 return NorthEastGravity;
3367 return SouthWestGravity;
3370 return SouthEastGravity;
3374 xloadfont(Font *f, FcPattern *pattern)
3376 FcPattern *configured;
3380 int wantattr, haveattr;
3383 * Manually configure instead of calling XftMatchFont
3384 * so that we can use the configured pattern for
3385 * "missing glyph" lookups.
3387 configured = FcPatternDuplicate(pattern);
3391 FcConfigSubstitute(NULL, configured, FcMatchPattern);
3392 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
3394 match = FcFontMatch(NULL, configured, &result);
3396 FcPatternDestroy(configured);
3400 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3401 FcPatternDestroy(configured);
3402 FcPatternDestroy(match);
3406 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
3409 * Check if xft was unable to find a font with the appropriate
3410 * slant but gave us one anyway. Try to mitigate.
3412 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
3413 &haveattr) != XftResultMatch) || haveattr < wantattr) {
3415 fputs("st: font slant does not match\n", stderr);
3419 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
3421 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
3422 &haveattr) != XftResultMatch) || haveattr != wantattr) {
3424 fputs("st: font weight does not match\n", stderr);
3428 XftTextExtentsUtf8(xw.dpy, f->match,
3429 (const FcChar8 *) ascii_printable,
3430 strlen(ascii_printable), &extents);
3433 f->pattern = configured;
3435 f->ascent = f->match->ascent;
3436 f->descent = f->match->descent;
3438 f->rbearing = f->match->max_advance_width;
3440 f->height = f->ascent + f->descent;
3441 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
3447 xloadfonts(char *fontstr, double fontsize)
3453 if (fontstr[0] == '-') {
3454 pattern = XftXlfdParse(fontstr, False, False);
3456 pattern = FcNameParse((FcChar8 *)fontstr);
3460 die("st: can't open font %s\n", fontstr);
3463 FcPatternDel(pattern, FC_PIXEL_SIZE);
3464 FcPatternDel(pattern, FC_SIZE);
3465 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3466 usedfontsize = fontsize;
3468 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
3470 usedfontsize = fontval;
3471 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
3476 * Default font size is 12, if none given. This is to
3477 * have a known usedfontsize value.
3479 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3482 defaultfontsize = usedfontsize;
3485 if (xloadfont(&dc.font, pattern))
3486 die("st: can't open font %s\n", fontstr);
3488 if (usedfontsize < 0) {
3489 FcPatternGetDouble(dc.font.match->pattern,
3490 FC_PIXEL_SIZE, 0, &fontval);
3491 usedfontsize = fontval;
3493 defaultfontsize = fontval;
3496 /* Setting character width and height. */
3497 xw.cw = ceilf(dc.font.width * cwscale);
3498 xw.ch = ceilf(dc.font.height * chscale);
3500 FcPatternDel(pattern, FC_SLANT);
3501 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3502 if (xloadfont(&dc.ifont, pattern))
3503 die("st: can't open font %s\n", fontstr);
3505 FcPatternDel(pattern, FC_WEIGHT);
3506 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3507 if (xloadfont(&dc.ibfont, pattern))
3508 die("st: can't open font %s\n", fontstr);
3510 FcPatternDel(pattern, FC_SLANT);
3511 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3512 if (xloadfont(&dc.bfont, pattern))
3513 die("st: can't open font %s\n", fontstr);
3515 FcPatternDestroy(pattern);
3519 xunloadfont(Font *f)
3521 XftFontClose(xw.dpy, f->match);
3522 FcPatternDestroy(f->pattern);
3524 FcFontSetDestroy(f->set);
3530 /* Free the loaded fonts in the font cache. */
3532 XftFontClose(xw.dpy, frc[--frclen].font);
3534 xunloadfont(&dc.font);
3535 xunloadfont(&dc.bfont);
3536 xunloadfont(&dc.ifont);
3537 xunloadfont(&dc.ibfont);
3541 xzoom(const Arg *arg)
3545 larg.f = usedfontsize + arg->f;
3550 xzoomabs(const Arg *arg)
3553 xloadfonts(usedfont, arg->f);
3561 xzoomreset(const Arg *arg)
3565 if (defaultfontsize > 0) {
3566 larg.f = defaultfontsize;
3577 pid_t thispid = getpid();
3578 XColor xmousefg, xmousebg;
3580 if (!(xw.dpy = XOpenDisplay(NULL)))
3581 die("Can't open display\n");
3582 xw.scr = XDefaultScreen(xw.dpy);
3583 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3587 die("Could not init fontconfig.\n");
3589 usedfont = (opt_font == NULL)? font : opt_font;
3590 xloadfonts(usedfont, 0);
3593 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3596 /* adjust fixed window geometry */
3597 xw.w = 2 * borderpx + term.col * xw.cw;
3598 xw.h = 2 * borderpx + term.row * xw.ch;
3599 if (xw.gm & XNegative)
3600 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3601 if (xw.gm & YNegative)
3602 xw.t += DisplayHeight(xw.dpy, xw.scr) - xw.h - 2;
3605 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3606 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3607 xw.attrs.bit_gravity = NorthWestGravity;
3608 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3609 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3610 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3611 xw.attrs.colormap = xw.cmap;
3613 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3614 parent = XRootWindow(xw.dpy, xw.scr);
3615 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3616 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3617 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3618 | CWEventMask | CWColormap, &xw.attrs);
3620 memset(&gcvalues, 0, sizeof(gcvalues));
3621 gcvalues.graphics_exposures = False;
3622 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3624 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3625 DefaultDepth(xw.dpy, xw.scr));
3626 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3627 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3629 /* Xft rendering context */
3630 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3633 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3634 XSetLocaleModifiers("@im=local");
3635 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3636 XSetLocaleModifiers("@im=");
3637 if ((xw.xim = XOpenIM(xw.dpy,
3638 NULL, NULL, NULL)) == NULL) {
3639 die("XOpenIM failed. Could not open input"
3644 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3645 | XIMStatusNothing, XNClientWindow, xw.win,
3646 XNFocusWindow, xw.win, NULL);
3648 die("XCreateIC failed. Could not obtain input method.\n");
3650 /* white cursor, black outline */
3651 cursor = XCreateFontCursor(xw.dpy, mouseshape);
3652 XDefineCursor(xw.dpy, xw.win, cursor);
3654 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
3655 xmousefg.red = 0xffff;
3656 xmousefg.green = 0xffff;
3657 xmousefg.blue = 0xffff;
3660 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
3661 xmousebg.red = 0x0000;
3662 xmousebg.green = 0x0000;
3663 xmousebg.blue = 0x0000;
3666 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
3668 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3669 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3670 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3671 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3673 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3674 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3675 PropModeReplace, (uchar *)&thispid, 1);
3678 XMapWindow(xw.dpy, xw.win);
3680 XSync(xw.dpy, False);
3684 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
3686 float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
3687 ushort mode, prevmode = USHRT_MAX;
3688 Font *font = &dc.font;
3689 int frcflags = FRC_NORMAL;
3690 float runewidth = xw.cw;
3694 FcPattern *fcpattern, *fontpattern;
3695 FcFontSet *fcsets[] = { NULL };
3696 FcCharSet *fccharset;
3697 int i, f, numspecs = 0;
3699 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
3700 /* Fetch rune and mode for current glyph. */
3702 mode = glyphs[i].mode;
3704 /* Skip dummy wide-character spacing. */
3705 if (mode == ATTR_WDUMMY)
3708 /* Determine font for glyph if different from previous glyph. */
3709 if (prevmode != mode) {
3712 frcflags = FRC_NORMAL;
3713 runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
3714 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
3716 frcflags = FRC_ITALICBOLD;
3717 } else if (mode & ATTR_ITALIC) {
3719 frcflags = FRC_ITALIC;
3720 } else if (mode & ATTR_BOLD) {
3722 frcflags = FRC_BOLD;
3724 yp = winy + font->ascent;
3727 /* Lookup character index with default font. */
3728 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
3730 specs[numspecs].font = font->match;
3731 specs[numspecs].glyph = glyphidx;
3732 specs[numspecs].x = (short)xp;
3733 specs[numspecs].y = (short)yp;
3739 /* Fallback on font cache, search the font cache for match. */
3740 for (f = 0; f < frclen; f++) {
3741 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
3742 /* Everything correct. */
3743 if (glyphidx && frc[f].flags == frcflags)
3745 /* We got a default font for a not found glyph. */
3746 if (!glyphidx && frc[f].flags == frcflags
3747 && frc[f].unicodep == rune) {
3752 /* Nothing was found. Use fontconfig to find matching font. */
3755 font->set = FcFontSort(0, font->pattern,
3757 fcsets[0] = font->set;
3760 * Nothing was found in the cache. Now use
3761 * some dozen of Fontconfig calls to get the
3762 * font for one single character.
3764 * Xft and fontconfig are design failures.
3766 fcpattern = FcPatternDuplicate(font->pattern);
3767 fccharset = FcCharSetCreate();
3769 FcCharSetAddChar(fccharset, rune);
3770 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3772 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
3774 FcConfigSubstitute(0, fcpattern,
3776 FcDefaultSubstitute(fcpattern);
3778 fontpattern = FcFontSetMatch(0, fcsets, 1,
3782 * Overwrite or create the new cache entry.
3784 if (frclen >= LEN(frc)) {
3785 frclen = LEN(frc) - 1;
3786 XftFontClose(xw.dpy, frc[frclen].font);
3787 frc[frclen].unicodep = 0;
3790 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3792 frc[frclen].flags = frcflags;
3793 frc[frclen].unicodep = rune;
3795 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
3800 FcPatternDestroy(fcpattern);
3801 FcCharSetDestroy(fccharset);
3804 specs[numspecs].font = frc[f].font;
3805 specs[numspecs].glyph = glyphidx;
3806 specs[numspecs].x = (short)xp;
3807 specs[numspecs].y = (short)yp;
3816 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
3818 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
3819 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3820 width = charlen * xw.cw;
3821 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3822 XRenderColor colfg, colbg;
3825 /* Fallback on color display for attributes not supported by the font */
3826 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
3827 if (dc.ibfont.badslant || dc.ibfont.badweight)
3828 base.fg = defaultattr;
3829 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
3830 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
3831 base.fg = defaultattr;
3834 if (IS_TRUECOL(base.fg)) {
3835 colfg.alpha = 0xffff;
3836 colfg.red = TRUERED(base.fg);
3837 colfg.green = TRUEGREEN(base.fg);
3838 colfg.blue = TRUEBLUE(base.fg);
3839 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3842 fg = &dc.col[base.fg];
3845 if (IS_TRUECOL(base.bg)) {
3846 colbg.alpha = 0xffff;
3847 colbg.green = TRUEGREEN(base.bg);
3848 colbg.red = TRUERED(base.bg);
3849 colbg.blue = TRUEBLUE(base.bg);
3850 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3853 bg = &dc.col[base.bg];
3856 /* Change basic system colors [0-7] to bright system colors [8-15] */
3857 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
3858 fg = &dc.col[base.fg + 8];
3860 if (IS_SET(MODE_REVERSE)) {
3861 if (fg == &dc.col[defaultfg]) {
3862 fg = &dc.col[defaultbg];
3864 colfg.red = ~fg->color.red;
3865 colfg.green = ~fg->color.green;
3866 colfg.blue = ~fg->color.blue;
3867 colfg.alpha = fg->color.alpha;
3868 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3873 if (bg == &dc.col[defaultbg]) {
3874 bg = &dc.col[defaultfg];
3876 colbg.red = ~bg->color.red;
3877 colbg.green = ~bg->color.green;
3878 colbg.blue = ~bg->color.blue;
3879 colbg.alpha = bg->color.alpha;
3880 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3886 if (base.mode & ATTR_REVERSE) {
3892 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
3893 colfg.red = fg->color.red / 2;
3894 colfg.green = fg->color.green / 2;
3895 colfg.blue = fg->color.blue / 2;
3896 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3900 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3903 if (base.mode & ATTR_INVISIBLE)
3906 /* Intelligent cleaning up of the borders. */
3908 xclear(0, (y == 0)? 0 : winy, borderpx,
3909 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3911 if (x + charlen >= term.col) {
3912 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3913 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3916 xclear(winx, 0, winx + width, borderpx);
3917 if (y == term.row-1)
3918 xclear(winx, winy + xw.ch, winx + width, xw.h);
3920 /* Clean up the region we want to draw to. */
3921 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3923 /* Set the clip region because Xft is sometimes dirty. */
3928 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3930 /* Render the glyphs. */
3931 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
3933 /* Render underline and strikethrough. */
3934 if (base.mode & ATTR_UNDERLINE) {
3935 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
3939 if (base.mode & ATTR_STRUCK) {
3940 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
3944 /* Reset clip to none. */
3945 XftDrawSetClip(xw.draw, 0);
3949 xdrawglyph(Glyph g, int x, int y)
3952 XftGlyphFontSpec spec;
3954 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
3955 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
3961 static int oldx = 0, oldy = 0;
3963 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
3964 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3967 LIMIT(oldx, 0, term.col-1);
3968 LIMIT(oldy, 0, term.row-1);
3972 /* adjust position if in dummy */
3973 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
3975 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3978 /* remove the old cursor */
3979 og = term.line[oldy][oldx];
3980 if (ena_sel && selected(oldx, oldy))
3981 og.mode ^= ATTR_REVERSE;
3982 xdrawglyph(og, oldx, oldy);
3984 g.u = term.line[term.c.y][term.c.x].u;
3987 * Select the right color for the right mode.
3989 if (IS_SET(MODE_REVERSE)) {
3990 g.mode |= ATTR_REVERSE;
3992 if (ena_sel && selected(term.c.x, term.c.y)) {
3993 drawcol = dc.col[defaultcs];
3996 drawcol = dc.col[defaultrcs];
4000 if (ena_sel && selected(term.c.x, term.c.y)) {
4001 drawcol = dc.col[defaultrcs];
4005 drawcol = dc.col[defaultcs];
4009 if (IS_SET(MODE_HIDE))
4012 /* draw the new one */
4013 if (xw.state & WIN_FOCUSED) {
4014 switch (xw.cursor) {
4015 case 7: /* st extension: snowman */
4016 utf8decode("☃", &g.u, UTF_SIZ);
4017 case 0: /* Blinking Block */
4018 case 1: /* Blinking Block (Default) */
4019 case 2: /* Steady Block */
4020 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
4021 xdrawglyph(g, term.c.x, term.c.y);
4023 case 3: /* Blinking Underline */
4024 case 4: /* Steady Underline */
4025 XftDrawRect(xw.draw, &drawcol,
4026 borderpx + curx * xw.cw,
4027 borderpx + (term.c.y + 1) * xw.ch - \
4029 xw.cw, cursorthickness);
4031 case 5: /* Blinking bar */
4032 case 6: /* Steady bar */
4033 XftDrawRect(xw.draw, &drawcol,
4034 borderpx + curx * xw.cw,
4035 borderpx + term.c.y * xw.ch,
4036 cursorthickness, xw.ch);
4040 XftDrawRect(xw.draw, &drawcol,
4041 borderpx + curx * xw.cw,
4042 borderpx + term.c.y * xw.ch,
4044 XftDrawRect(xw.draw, &drawcol,
4045 borderpx + curx * xw.cw,
4046 borderpx + term.c.y * xw.ch,
4048 XftDrawRect(xw.draw, &drawcol,
4049 borderpx + (curx + 1) * xw.cw - 1,
4050 borderpx + term.c.y * xw.ch,
4052 XftDrawRect(xw.draw, &drawcol,
4053 borderpx + curx * xw.cw,
4054 borderpx + (term.c.y + 1) * xw.ch - 1,
4057 oldx = curx, oldy = term.c.y;
4066 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
4068 XSetWMName(xw.dpy, xw.win, &prop);
4069 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
4076 xsettitle(opt_title ? opt_title : "st");
4089 drawregion(0, 0, term.col, term.row);
4090 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
4092 XSetForeground(xw.dpy, dc.gc,
4093 dc.col[IS_SET(MODE_REVERSE)?
4094 defaultfg : defaultbg].pixel);
4098 drawregion(int x1, int y1, int x2, int y2)
4100 int i, x, y, ox, numspecs;
4102 XftGlyphFontSpec *specs;
4103 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
4105 if (!(xw.state & WIN_VISIBLE))
4108 for (y = y1; y < y2; y++) {
4114 specs = term.specbuf;
4115 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
4118 for (x = x1; x < x2 && i < numspecs; x++) {
4119 new = term.line[y][x];
4120 if (new.mode == ATTR_WDUMMY)
4122 if (ena_sel && selected(x, y))
4123 new.mode ^= ATTR_REVERSE;
4124 if (i > 0 && ATTRCMP(base, new)) {
4125 xdrawglyphfontspecs(specs, base, i, ox, y);
4137 xdrawglyphfontspecs(specs, base, i, ox, y);
4149 visibility(XEvent *ev)
4151 XVisibilityEvent *e = &ev->xvisibility;
4153 MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
4159 xw.state &= ~WIN_VISIBLE;
4163 xsetpointermotion(int set)
4165 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
4166 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
4170 xseturgency(int add)
4172 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
4174 MODBIT(h->flags, add, XUrgencyHint);
4175 XSetWMHints(xw.dpy, xw.win, h);
4182 XFocusChangeEvent *e = &ev->xfocus;
4184 if (e->mode == NotifyGrab)
4187 if (ev->type == FocusIn) {
4188 XSetICFocus(xw.xic);
4189 xw.state |= WIN_FOCUSED;
4191 if (IS_SET(MODE_FOCUS))
4192 ttywrite("\033[I", 3);
4194 XUnsetICFocus(xw.xic);
4195 xw.state &= ~WIN_FOCUSED;
4196 if (IS_SET(MODE_FOCUS))
4197 ttywrite("\033[O", 3);
4202 match(uint mask, uint state)
4204 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
4208 numlock(const Arg *dummy)
4214 kmap(KeySym k, uint state)
4219 /* Check for mapped keys out of X11 function keys. */
4220 for (i = 0; i < LEN(mappedkeys); i++) {
4221 if (mappedkeys[i] == k)
4224 if (i == LEN(mappedkeys)) {
4225 if ((k & 0xFFFF) < 0xFD00)
4229 for (kp = key; kp < key + LEN(key); kp++) {
4233 if (!match(kp->mask, state))
4236 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
4238 if (term.numlock && kp->appkey == 2)
4241 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
4244 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
4256 XKeyEvent *e = &ev->xkey;
4258 char buf[32], *customkey;
4264 if (IS_SET(MODE_KBDLOCK))
4267 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
4269 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
4270 if (ksym == bp->keysym && match(bp->mod, e->state)) {
4271 bp->func(&(bp->arg));
4276 /* 2. custom keys from config.h */
4277 if ((customkey = kmap(ksym, e->state))) {
4278 ttysend(customkey, strlen(customkey));
4282 /* 3. composed string from input method */
4285 if (len == 1 && e->state & Mod1Mask) {
4286 if (IS_SET(MODE_8BIT)) {
4289 len = utf8encode(c, buf);
4306 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
4308 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
4309 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
4310 xw.state |= WIN_FOCUSED;
4312 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
4313 xw.state &= ~WIN_FOCUSED;
4315 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
4316 /* Send SIGHUP to shell */
4323 cresize(int width, int height)
4332 col = (xw.w - 2 * borderpx) / xw.cw;
4333 row = (xw.h - 2 * borderpx) / xw.ch;
4342 if (e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
4345 cresize(e->xconfigure.width, e->xconfigure.height);
4353 int w = xw.w, h = xw.h;
4355 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
4356 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
4359 /* Waiting for window mapping */
4361 XNextEvent(xw.dpy, &ev);
4363 * This XFilterEvent call is required because of XOpenIM. It
4364 * does filter out the key event and some client message for
4365 * the input method too.
4367 if (XFilterEvent(&ev, None))
4369 if (ev.type == ConfigureNotify) {
4370 w = ev.xconfigure.width;
4371 h = ev.xconfigure.height;
4373 } while (ev.type != MapNotify);
4379 clock_gettime(CLOCK_MONOTONIC, &last);
4382 for (xev = actionfps;;) {
4384 FD_SET(cmdfd, &rfd);
4387 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
4390 die("select failed: %s\n", strerror(errno));
4392 if (FD_ISSET(cmdfd, &rfd)) {
4395 blinkset = tattrset(ATTR_BLINK);
4397 MODBIT(term.mode, 0, MODE_BLINK);
4401 if (FD_ISSET(xfd, &rfd))
4404 clock_gettime(CLOCK_MONOTONIC, &now);
4405 drawtimeout.tv_sec = 0;
4406 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
4410 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
4411 tsetdirtattr(ATTR_BLINK);
4412 term.mode ^= MODE_BLINK;
4416 deltatime = TIMEDIFF(now, last);
4417 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
4423 while (XPending(xw.dpy)) {
4424 XNextEvent(xw.dpy, &ev);
4425 if (XFilterEvent(&ev, None))
4427 if (handler[ev.type])
4428 (handler[ev.type])(&ev);
4434 if (xev && !FD_ISSET(xfd, &rfd))
4436 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
4438 if (TIMEDIFF(now, lastblink) \
4440 drawtimeout.tv_nsec = 1000;
4442 drawtimeout.tv_nsec = (1E6 * \
4447 drawtimeout.tv_sec = \
4448 drawtimeout.tv_nsec / 1E9;
4449 drawtimeout.tv_nsec %= (long)1E9;
4461 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
4462 " [-n name] [-o file]\n"
4463 " [-T title] [-t title] [-w windowid]"
4464 " [[-e] command [args ...]]\n"
4465 " %s [-aiv] [-c class] [-f font] [-g geometry]"
4466 " [-n name] [-o file]\n"
4467 " [-T title] [-t title] [-w windowid] -l line"
4468 " [stty_args ...]\n", argv0, argv0);
4472 main(int argc, char *argv[])
4474 uint cols = 80, rows = 24;
4478 xw.cursor = cursorshape;
4485 opt_class = EARGF(usage());
4492 opt_font = EARGF(usage());
4495 xw.gm = XParseGeometry(EARGF(usage()),
4496 &xw.l, &xw.t, &cols, &rows);
4502 opt_io = EARGF(usage());
4505 opt_line = EARGF(usage());
4508 opt_name = EARGF(usage());
4512 opt_title = EARGF(usage());
4515 opt_embed = EARGF(usage());
4518 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
4526 /* eat all remaining arguments */
4528 if (!opt_title && !opt_line)
4529 opt_title = basename(xstrdup(argv[0]));
4531 setlocale(LC_CTYPE, "");
4532 XSetLocaleModifiers("");
4533 tnew(MAX(cols, 1), MAX(rows, 1));