+selscroll(int orig, int n) {
+ if(sel.ob.x == -1)
+ return;
+
+ if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
+ if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
+ selclear(NULL);
+ return;
+ }
+ if(sel.type == SEL_RECTANGULAR) {
+ if(sel.ob.y < term.top)
+ sel.ob.y = term.top;
+ if(sel.oe.y > term.bot)
+ sel.oe.y = term.bot;
+ } else {
+ if(sel.ob.y < term.top) {
+ sel.ob.y = term.top;
+ sel.ob.x = 0;
+ }
+ if(sel.oe.y > term.bot) {
+ sel.oe.y = term.bot;
+ sel.oe.x = term.col;
+ }
+ }
+ selsort();
+ }
+}
+
+void
+tnewline(int first_col) {
+ int y = term.c.y;
+
+ if(y == term.bot) {
+ tscrollup(term.top, 1);
+ } else {
+ y++;
+ }
+ tmoveto(first_col ? 0 : term.c.x, y);
+}
+
+void
+csiparse(void) {
+ char *p = csiescseq.buf, *np;
+ long int v;
+
+ csiescseq.narg = 0;
+ if(*p == '?') {
+ csiescseq.priv = 1;
+ p++;
+ }
+
+ csiescseq.buf[csiescseq.len] = '\0';
+ while(p < csiescseq.buf+csiescseq.len) {
+ np = NULL;
+ v = strtol(p, &np, 10);
+ if(np == p)
+ v = 0;
+ if(v == LONG_MAX || v == LONG_MIN)
+ v = -1;
+ csiescseq.arg[csiescseq.narg++] = v;
+ p = np;
+ if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
+ break;
+ p++;
+ }
+ csiescseq.mode = *p;
+}
+
+/* for absolute user moves, when decom is set */
+void
+tmoveato(int x, int y) {
+ tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
+}
+
+void
+tmoveto(int x, int y) {
+ int miny, maxy;
+
+ if(term.c.state & CURSOR_ORIGIN) {
+ miny = term.top;
+ maxy = term.bot;
+ } else {
+ miny = 0;
+ maxy = term.row - 1;
+ }
+ LIMIT(x, 0, term.col-1);
+ LIMIT(y, miny, maxy);
+ term.c.state &= ~CURSOR_WRAPNEXT;
+ term.c.x = x;
+ term.c.y = y;
+}
+
+void
+tsetchar(char *c, Glyph *attr, int x, int y) {
+ static char *vt100_0[62] = { /* 0x41 - 0x7e */
+ "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
+ 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
+ 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
+ 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
+ "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
+ "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
+ "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
+ "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
+ };
+
+ /*
+ * The table is proudly stolen from rxvt.
+ */
+ if(attr->mode & ATTR_GFX) {
+ if(c[0] >= 0x41 && c[0] <= 0x7e
+ && vt100_0[c[0] - 0x41]) {
+ c = vt100_0[c[0] - 0x41];
+ }
+ }
+
+ term.dirty[y] = 1;
+ term.line[y][x] = *attr;
+ memcpy(term.line[y][x].c, c, UTF_SIZ);
+}
+
+void
+tclearregion(int x1, int y1, int x2, int y2) {
+ int x, y, temp;
+
+ if(x1 > x2)
+ temp = x1, x1 = x2, x2 = temp;
+ if(y1 > y2)
+ temp = y1, y1 = y2, y2 = temp;
+
+ LIMIT(x1, 0, term.col-1);
+ LIMIT(x2, 0, term.col-1);
+ LIMIT(y1, 0, term.row-1);
+ LIMIT(y2, 0, term.row-1);
+
+ for(y = y1; y <= y2; y++) {
+ term.dirty[y] = 1;
+ for(x = x1; x <= x2; x++) {
+ if(selected(x, y))
+ selclear(NULL);
+ term.line[y][x] = term.c.attr;
+ memcpy(term.line[y][x].c, " ", 2);
+ }
+ }
+}
+
+void
+tdeletechar(int n) {
+ int src = term.c.x + n;
+ int dst = term.c.x;
+ int size = term.col - src;
+
+ term.dirty[term.c.y] = 1;
+
+ if(src >= term.col) {
+ tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
+ return;
+ }
+
+ memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
+ size * sizeof(Glyph));
+ tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
+}
+
+void
+tinsertblank(int n) {
+ int src = term.c.x;
+ int dst = src + n;
+ int size = term.col - dst;
+
+ term.dirty[term.c.y] = 1;
+
+ if(dst >= term.col) {
+ tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
+ return;
+ }
+
+ memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
+ size * sizeof(Glyph));
+ tclearregion(src, term.c.y, dst - 1, term.c.y);
+}
+
+void
+tinsertblankline(int n) {
+ if(term.c.y < term.top || term.c.y > term.bot)
+ return;
+
+ tscrolldown(term.c.y, n);
+}
+
+void
+tdeleteline(int n) {
+ if(term.c.y < term.top || term.c.y > term.bot)
+ return;
+
+ tscrollup(term.c.y, n);
+}
+
+ulong
+tdefcolor(int *attr, int *npar, int l) {
+ long idx = -1;
+ uint r, g, b;
+
+ switch (attr[*npar + 1]) {
+ case 2: /* direct colour in RGB space */
+ if (*npar + 4 >= l) {
+ fprintf(stderr,
+ "erresc(38): Incorrect number of parameters (%d)\n",
+ *npar);
+ break;
+ }
+ r = attr[*npar + 2];
+ g = attr[*npar + 3];
+ b = attr[*npar + 4];
+ *npar += 4;
+ if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
+ fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
+ r, g, b);
+ else
+ idx = TRUECOLOR(r, g, b);
+ break;
+ case 5: /* indexed colour */
+ if (*npar + 2 >= l) {
+ fprintf(stderr,
+ "erresc(38): Incorrect number of parameters (%d)\n",
+ *npar);
+ break;
+ }
+ *npar += 2;
+ if(!BETWEEN(attr[*npar], 0, 255))
+ fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
+ else
+ idx = attr[*npar];
+ break;
+ case 0: /* implemented defined (only foreground) */
+ case 1: /* transparent */
+ case 3: /* direct colour in CMY space */
+ case 4: /* direct colour in CMYK space */
+ default:
+ fprintf(stderr,
+ "erresc(38): gfx attr %d unknown\n", attr[*npar]);
+ }
+
+ return idx;
+}
+
+void
+tsetattr(int *attr, int l) {
+ int i;
+ ulong idx;
+
+ for(i = 0; i < l; i++) {
+ switch(attr[i]) {
+ case 0:
+ term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
+ | ATTR_BOLD | ATTR_ITALIC \
+ | ATTR_BLINK);
+ term.c.attr.fg = defaultfg;
+ term.c.attr.bg = defaultbg;
+ break;
+ case 1:
+ term.c.attr.mode |= ATTR_BOLD;
+ break;
+ case 3:
+ term.c.attr.mode |= ATTR_ITALIC;
+ break;
+ case 4:
+ term.c.attr.mode |= ATTR_UNDERLINE;
+ break;
+ case 5: /* slow blink */
+ case 6: /* rapid blink */
+ term.c.attr.mode |= ATTR_BLINK;
+ break;
+ case 7:
+ term.c.attr.mode |= ATTR_REVERSE;
+ break;
+ case 21:
+ case 22:
+ term.c.attr.mode &= ~ATTR_BOLD;
+ break;
+ case 23:
+ term.c.attr.mode &= ~ATTR_ITALIC;
+ break;
+ case 24:
+ term.c.attr.mode &= ~ATTR_UNDERLINE;
+ break;
+ case 25:
+ case 26:
+ term.c.attr.mode &= ~ATTR_BLINK;
+ break;
+ case 27:
+ term.c.attr.mode &= ~ATTR_REVERSE;
+ break;
+ case 38:
+ if ((idx = tdefcolor(attr, &i, l)) >= 0)
+ term.c.attr.fg = idx;
+ break;
+ case 39:
+ term.c.attr.fg = defaultfg;
+ break;
+ case 48:
+ if ((idx = tdefcolor(attr, &i, l)) >= 0)
+ term.c.attr.bg = idx;
+ break;
+ case 49:
+ term.c.attr.bg = defaultbg;
+ break;
+ default:
+ if(BETWEEN(attr[i], 30, 37)) {
+ term.c.attr.fg = attr[i] - 30;
+ } else if(BETWEEN(attr[i], 40, 47)) {
+ term.c.attr.bg = attr[i] - 40;
+ } else if(BETWEEN(attr[i], 90, 97)) {
+ term.c.attr.fg = attr[i] - 90 + 8;
+ } else if(BETWEEN(attr[i], 100, 107)) {
+ term.c.attr.bg = attr[i] - 100 + 8;
+ } else {
+ fprintf(stderr,
+ "erresc(default): gfx attr %d unknown\n",
+ attr[i]), csidump();
+ }
+ break;
+ }
+ }
+}
+
+void
+tsetscroll(int t, int b) {
+ int temp;
+
+ LIMIT(t, 0, term.row-1);
+ LIMIT(b, 0, term.row-1);
+ if(t > b) {
+ temp = t;
+ t = b;
+ b = temp;
+ }
+ term.top = t;
+ term.bot = b;
+}
+
+#define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
+
+void
+tsetmode(bool priv, bool set, int *args, int narg) {
+ int *lim, mode;
+ bool alt;
+
+ for(lim = args + narg; args < lim; ++args) {
+ if(priv) {
+ switch(*args) {
+ break;
+ case 1: /* DECCKM -- Cursor key */
+ MODBIT(term.mode, set, MODE_APPCURSOR);
+ break;
+ case 5: /* DECSCNM -- Reverse video */
+ mode = term.mode;
+ MODBIT(term.mode, set, MODE_REVERSE);
+ if(mode != term.mode)
+ redraw(REDRAW_TIMEOUT);
+ break;
+ case 6: /* DECOM -- Origin */
+ MODBIT(term.c.state, set, CURSOR_ORIGIN);
+ tmoveato(0, 0);
+ break;
+ case 7: /* DECAWM -- Auto wrap */
+ MODBIT(term.mode, set, MODE_WRAP);
+ break;
+ case 0: /* Error (IGNORED) */
+ case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
+ case 3: /* DECCOLM -- Column (IGNORED) */
+ case 4: /* DECSCLM -- Scroll (IGNORED) */
+ case 8: /* DECARM -- Auto repeat (IGNORED) */
+ case 18: /* DECPFF -- Printer feed (IGNORED) */
+ case 19: /* DECPEX -- Printer extent (IGNORED) */
+ case 42: /* DECNRCM -- National characters (IGNORED) */
+ case 12: /* att610 -- Start blinking cursor (IGNORED) */
+ break;
+ case 25: /* DECTCEM -- Text Cursor Enable Mode */
+ MODBIT(term.mode, !set, MODE_HIDE);
+ break;
+ case 9: /* X10 mouse compatibility mode */
+ xsetpointermotion(0);
+ MODBIT(term.mode, 0, MODE_MOUSE);
+ MODBIT(term.mode, set, MODE_MOUSEX10);
+ break;
+ case 1000: /* 1000: report button press */
+ xsetpointermotion(0);
+ MODBIT(term.mode, 0, MODE_MOUSE);
+ MODBIT(term.mode, set, MODE_MOUSEBTN);
+ break;
+ case 1002: /* 1002: report motion on button press */
+ xsetpointermotion(0);
+ MODBIT(term.mode, 0, MODE_MOUSE);
+ MODBIT(term.mode, set, MODE_MOUSEMOTION);
+ break;
+ case 1003: /* 1003: enable all mouse motions */
+ xsetpointermotion(set);
+ MODBIT(term.mode, 0, MODE_MOUSE);
+ MODBIT(term.mode, set, MODE_MOUSEMANY);
+ break;
+ case 1004: /* 1004: send focus events to tty */
+ MODBIT(term.mode, set, MODE_FOCUS);
+ break;
+ case 1006: /* 1006: extended reporting mode */
+ MODBIT(term.mode, set, MODE_MOUSESGR);
+ break;
+ case 1034:
+ MODBIT(term.mode, set, MODE_8BIT);
+ break;
+ case 1049: /* = 1047 and 1048 */
+ case 47:
+ case 1047:
+ if (!allowaltscreen)
+ break;
+
+ alt = IS_SET(MODE_ALTSCREEN);
+ if(alt) {
+ tclearregion(0, 0, term.col-1,
+ term.row-1);
+ }
+ if(set ^ alt) /* set is always 1 or 0 */
+ tswapscreen();
+ if(*args != 1049)
+ break;
+ /* FALLTRU */
+ case 1048:
+ tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
+ break;
+ /* Not implemented mouse modes. See comments there. */
+ case 1001: /* mouse highlight mode; can hang the
+ terminal by design when implemented. */
+ case 1005: /* UTF-8 mouse mode; will confuse
+ applications not supporting UTF-8
+ and luit. */
+ case 1015: /* urxvt mangled mouse mode; incompatible
+ and can be mistaken for other control
+ codes. */
+ default:
+ fprintf(stderr,
+ "erresc: unknown private set/reset mode %d\n",
+ *args);
+ break;
+ }
+ } else {
+ switch(*args) {
+ case 0: /* Error (IGNORED) */
+ break;
+ case 2: /* KAM -- keyboard action */
+ MODBIT(term.mode, set, MODE_KBDLOCK);
+ break;
+ case 4: /* IRM -- Insertion-replacement */
+ MODBIT(term.mode, set, MODE_INSERT);
+ break;
+ case 12: /* SRM -- Send/Receive */
+ MODBIT(term.mode, !set, MODE_ECHO);
+ break;
+ case 20: /* LNM -- Linefeed/new line */
+ MODBIT(term.mode, set, MODE_CRLF);
+ break;
+ default:
+ fprintf(stderr,
+ "erresc: unknown set/reset mode %d\n",
+ *args);
+ break;
+ }
+ }
+ }
+}
+
+void
+csihandle(void) {
+ switch(csiescseq.mode) {
+ default:
+ unknown:
+ fprintf(stderr, "erresc: unknown csi ");
+ csidump();
+ /* die(""); */
+ break;
+ case '@': /* ICH -- Insert <n> blank char */
+ DEFAULT(csiescseq.arg[0], 1);
+ tinsertblank(csiescseq.arg[0]);
+ break;
+ case 'A': /* CUU -- Cursor <n> Up */
+ DEFAULT(csiescseq.arg[0], 1);
+ tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
+ break;
+ case 'B': /* CUD -- Cursor <n> Down */
+ case 'e': /* VPR --Cursor <n> Down */
+ DEFAULT(csiescseq.arg[0], 1);
+ tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
+ break;
+ case 'c': /* DA -- Device Attributes */
+ if(csiescseq.arg[0] == 0)
+ ttywrite(VT102ID, sizeof(VT102ID) - 1);
+ break;
+ case 'C': /* CUF -- Cursor <n> Forward */
+ case 'a': /* HPR -- Cursor <n> Forward */
+ DEFAULT(csiescseq.arg[0], 1);
+ tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
+ break;
+ case 'D': /* CUB -- Cursor <n> Backward */
+ DEFAULT(csiescseq.arg[0], 1);
+ tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
+ break;
+ case 'E': /* CNL -- Cursor <n> Down and first col */
+ DEFAULT(csiescseq.arg[0], 1);
+ tmoveto(0, term.c.y+csiescseq.arg[0]);
+ break;
+ case 'F': /* CPL -- Cursor <n> Up and first col */
+ DEFAULT(csiescseq.arg[0], 1);
+ tmoveto(0, term.c.y-csiescseq.arg[0]);
+ break;
+ case 'g': /* TBC -- Tabulation clear */
+ switch(csiescseq.arg[0]) {
+ case 0: /* clear current tab stop */
+ term.tabs[term.c.x] = 0;
+ break;
+ case 3: /* clear all the tabs */
+ memset(term.tabs, 0, term.col * sizeof(*term.tabs));
+ break;
+ default:
+ goto unknown;
+ }
+ break;
+ case 'G': /* CHA -- Move to <col> */
+ case '`': /* HPA */
+ DEFAULT(csiescseq.arg[0], 1);
+ tmoveto(csiescseq.arg[0]-1, term.c.y);
+ break;
+ case 'H': /* CUP -- Move to <row> <col> */
+ case 'f': /* HVP */
+ DEFAULT(csiescseq.arg[0], 1);
+ DEFAULT(csiescseq.arg[1], 1);
+ tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
+ break;
+ case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
+ DEFAULT(csiescseq.arg[0], 1);
+ while(csiescseq.arg[0]--)
+ tputtab(1);
+ break;
+ case 'J': /* ED -- Clear screen */
+ selclear(NULL);
+ switch(csiescseq.arg[0]) {
+ case 0: /* below */
+ tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
+ if(term.c.y < term.row-1) {
+ tclearregion(0, term.c.y+1, term.col-1,
+ term.row-1);
+ }
+ break;
+ case 1: /* above */
+ if(term.c.y > 1)
+ tclearregion(0, 0, term.col-1, term.c.y-1);
+ tclearregion(0, term.c.y, term.c.x, term.c.y);
+ break;
+ case 2: /* all */
+ tclearregion(0, 0, term.col-1, term.row-1);
+ break;
+ default:
+ goto unknown;
+ }
+ break;
+ case 'K': /* EL -- Clear line */
+ switch(csiescseq.arg[0]) {
+ case 0: /* right */
+ tclearregion(term.c.x, term.c.y, term.col-1,
+ term.c.y);
+ break;
+ case 1: /* left */
+ tclearregion(0, term.c.y, term.c.x, term.c.y);
+ break;
+ case 2: /* all */
+ tclearregion(0, term.c.y, term.col-1, term.c.y);
+ break;
+ }
+ break;
+ case 'S': /* SU -- Scroll <n> line up */
+ DEFAULT(csiescseq.arg[0], 1);
+ tscrollup(term.top, csiescseq.arg[0]);
+ break;
+ case 'T': /* SD -- Scroll <n> line down */
+ DEFAULT(csiescseq.arg[0], 1);
+ tscrolldown(term.top, csiescseq.arg[0]);
+ break;
+ case 'L': /* IL -- Insert <n> blank lines */
+ DEFAULT(csiescseq.arg[0], 1);
+ tinsertblankline(csiescseq.arg[0]);
+ break;
+ case 'l': /* RM -- Reset Mode */
+ tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
+ break;
+ case 'M': /* DL -- Delete <n> lines */
+ DEFAULT(csiescseq.arg[0], 1);
+ tdeleteline(csiescseq.arg[0]);
+ break;
+ case 'X': /* ECH -- Erase <n> char */
+ DEFAULT(csiescseq.arg[0], 1);
+ tclearregion(term.c.x, term.c.y,
+ term.c.x + csiescseq.arg[0] - 1, term.c.y);
+ break;
+ case 'P': /* DCH -- Delete <n> char */
+ DEFAULT(csiescseq.arg[0], 1);
+ tdeletechar(csiescseq.arg[0]);
+ break;
+ case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
+ DEFAULT(csiescseq.arg[0], 1);
+ while(csiescseq.arg[0]--)
+ tputtab(0);
+ break;
+ case 'd': /* VPA -- Move to <row> */
+ DEFAULT(csiescseq.arg[0], 1);
+ tmoveato(term.c.x, csiescseq.arg[0]-1);
+ break;
+ case 'h': /* SM -- Set terminal mode */
+ tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
+ break;
+ case 'm': /* SGR -- Terminal attribute (color) */
+ tsetattr(csiescseq.arg, csiescseq.narg);
+ break;
+ case 'r': /* DECSTBM -- Set Scrolling Region */
+ if(csiescseq.priv) {
+ goto unknown;
+ } else {
+ DEFAULT(csiescseq.arg[0], 1);
+ DEFAULT(csiescseq.arg[1], term.row);
+ tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
+ tmoveato(0, 0);
+ }
+ break;
+ case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
+ tcursor(CURSOR_SAVE);
+ break;
+ case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
+ tcursor(CURSOR_LOAD);
+ break;
+ }
+}
+
+void
+csidump(void) {
+ int i;
+ uint c;
+
+ printf("ESC[");
+ for(i = 0; i < csiescseq.len; i++) {
+ c = csiescseq.buf[i] & 0xff;
+ if(isprint(c)) {
+ putchar(c);
+ } else if(c == '\n') {
+ printf("(\\n)");
+ } else if(c == '\r') {
+ printf("(\\r)");
+ } else if(c == 0x1b) {
+ printf("(\\e)");
+ } else {
+ printf("(%02x)", c);
+ }
+ }
+ putchar('\n');
+}
+
+void
+csireset(void) {
+ memset(&csiescseq, 0, sizeof(csiescseq));
+}
+
+void
+strhandle(void) {
+ char *p = NULL;
+ int i, j, narg;
+
+ strparse();
+ narg = strescseq.narg;
+
+ switch(strescseq.type) {
+ case ']': /* OSC -- Operating System Command */
+ switch(i = atoi(strescseq.args[0])) {
+ case 0:
+ case 1:
+ case 2:
+ if(narg > 1)
+ xsettitle(strescseq.args[1]);
+ break;
+ case 4: /* color set */
+ if(narg < 3)
+ break;
+ p = strescseq.args[2];
+ /* fall through */
+ case 104: /* color reset, here p = NULL */
+ j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
+ if (!xsetcolorname(j, p)) {
+ fprintf(stderr, "erresc: invalid color %s\n", p);
+ } else {
+ /*
+ * TODO if defaultbg color is changed, borders
+ * are dirty
+ */
+ redraw(0);
+ }
+ break;
+ default:
+ fprintf(stderr, "erresc: unknown str ");
+ strdump();
+ break;
+ }
+ break;
+ case 'k': /* old title set compatibility */
+ xsettitle(strescseq.args[0]);
+ break;
+ case 'P': /* DSC -- Device Control String */
+ case '_': /* APC -- Application Program Command */
+ case '^': /* PM -- Privacy Message */
+ default:
+ fprintf(stderr, "erresc: unknown str ");
+ strdump();
+ /* die(""); */
+ break;
+ }
+}
+
+void
+strparse(void) {
+ char *p = strescseq.buf;
+
+ strescseq.narg = 0;
+ strescseq.buf[strescseq.len] = '\0';
+ while(p && strescseq.narg < STR_ARG_SIZ)
+ strescseq.args[strescseq.narg++] = strsep(&p, ";");
+}
+
+void
+strdump(void) {
+ int i;
+ uint c;
+
+ printf("ESC%c", strescseq.type);
+ for(i = 0; i < strescseq.len; i++) {
+ c = strescseq.buf[i] & 0xff;
+ if(c == '\0') {
+ return;
+ } else if(isprint(c)) {
+ putchar(c);
+ } else if(c == '\n') {
+ printf("(\\n)");
+ } else if(c == '\r') {
+ printf("(\\r)");
+ } else if(c == 0x1b) {
+ printf("(\\e)");
+ } else {
+ printf("(%02x)", c);
+ }
+ }
+ printf("ESC\\\n");
+}
+
+void
+strreset(void) {
+ memset(&strescseq, 0, sizeof(strescseq));
+}
+
+void
+tputtab(bool forward) {
+ uint x = term.c.x;
+
+ if(forward) {
+ if(x == term.col)
+ return;
+ for(++x; x < term.col && !term.tabs[x]; ++x)
+ /* nothing */ ;
+ } else {
+ if(x == 0)
+ return;
+ for(--x; x > 0 && !term.tabs[x]; --x)
+ /* nothing */ ;
+ }
+ tmoveto(x, term.c.y);
+}
+
+void
+techo(char *buf, int len) {
+ for(; len > 0; buf++, len--) {
+ char c = *buf;
+
+ if(c == '\033') { /* escape */
+ tputc("^", 1);
+ tputc("[", 1);
+ } else if(c < '\x20') { /* control code */
+ if(c != '\n' && c != '\r' && c != '\t') {
+ c |= '\x40';
+ tputc("^", 1);
+ }
+ tputc(&c, 1);
+ } else {
+ break;
+ }
+ }
+ if(len)
+ tputc(buf, len);
+}
+
+void
+tputc(char *c, int len) {
+ uchar ascii = *c;
+ bool control = ascii < '\x20' || ascii == 0177;
+
+ if(iofd != -1) {
+ if(xwrite(iofd, c, len) < 0) {
+ fprintf(stderr, "Error writing in %s:%s\n",
+ opt_io, strerror(errno));
+ close(iofd);
+ iofd = -1;
+ }
+ }
+
+ /*
+ * STR sequences must be checked before anything else
+ * because it can use some control codes as part of the sequence.
+ */
+ if(term.esc & ESC_STR) {
+ switch(ascii) {
+ case '\033':
+ term.esc = ESC_START | ESC_STR_END;
+ break;
+ case '\a': /* backwards compatibility to xterm */
+ term.esc = 0;
+ strhandle();
+ break;
+ default:
+ if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
+ memmove(&strescseq.buf[strescseq.len], c, len);
+ strescseq.len += len;
+ } else {
+ /*
+ * Here is a bug in terminals. If the user never sends
+ * some code to stop the str or esc command, then st
+ * will stop responding. But this is better than
+ * silently failing with unknown characters. At least
+ * then users will report back.
+ *
+ * In the case users ever get fixed, here is the code:
+ */
+ /*
+ * term.esc = 0;
+ * strhandle();
+ */
+ }
+ }
+ return;
+ }
+
+ /*
+ * Actions of control codes must be performed as soon they arrive
+ * because they can be embedded inside a control sequence, and
+ * they must not cause conflicts with sequences.
+ */
+ if(control) {
+ switch(ascii) {
+ case '\t': /* HT */
+ tputtab(1);
+ return;
+ case '\b': /* BS */
+ tmoveto(term.c.x-1, term.c.y);
+ return;
+ case '\r': /* CR */
+ tmoveto(0, term.c.y);
+ return;
+ case '\f': /* LF */
+ case '\v': /* VT */
+ case '\n': /* LF */
+ /* go to first col if the mode is set */
+ tnewline(IS_SET(MODE_CRLF));
+ return;
+ case '\a': /* BEL */
+ if(!(xw.state & WIN_FOCUSED))
+ xseturgency(1);
+ return;
+ case '\033': /* ESC */
+ csireset();
+ term.esc = ESC_START;
+ return;
+ case '\016': /* SO */
+ case '\017': /* SI */
+ /*
+ * Different charsets are hard to handle. Applications
+ * should use the right alt charset escapes for the
+ * only reason they still exist: line drawing. The
+ * rest is incompatible history st should not support.
+ */
+ return;
+ case '\032': /* SUB */
+ case '\030': /* CAN */
+ csireset();
+ return;
+ case '\005': /* ENQ (IGNORED) */
+ case '\000': /* NUL (IGNORED) */
+ case '\021': /* XON (IGNORED) */
+ case '\023': /* XOFF (IGNORED) */
+ case 0177: /* DEL (IGNORED) */
+ return;
+ }
+ } else if(term.esc & ESC_START) {
+ if(term.esc & ESC_CSI) {
+ csiescseq.buf[csiescseq.len++] = ascii;
+ if(BETWEEN(ascii, 0x40, 0x7E)
+ || csiescseq.len >= \
+ sizeof(csiescseq.buf)-1) {
+ term.esc = 0;
+ csiparse();
+ csihandle();
+ }
+ } else if(term.esc & ESC_STR_END) {
+ term.esc = 0;
+ if(ascii == '\\')
+ strhandle();
+ } else if(term.esc & ESC_ALTCHARSET) {
+ switch(ascii) {
+ case '0': /* Line drawing set */
+ term.c.attr.mode |= ATTR_GFX;
+ break;
+ case 'B': /* USASCII */
+ term.c.attr.mode &= ~ATTR_GFX;
+ break;
+ case 'A': /* UK (IGNORED) */
+ case '<': /* multinational charset (IGNORED) */
+ case '5': /* Finnish (IGNORED) */
+ case 'C': /* Finnish (IGNORED) */
+ case 'K': /* German (IGNORED) */
+ break;
+ default:
+ fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
+ }
+ term.esc = 0;
+ } else if(term.esc & ESC_TEST) {
+ if(ascii == '8') { /* DEC screen alignment test. */
+ char E[UTF_SIZ] = "E";
+ int x, y;
+
+ for(x = 0; x < term.col; ++x) {
+ for(y = 0; y < term.row; ++y)
+ tsetchar(E, &term.c.attr, x, y);
+ }
+ }
+ term.esc = 0;
+ } else {
+ switch(ascii) {
+ case '[':
+ term.esc |= ESC_CSI;
+ break;
+ case '#':
+ term.esc |= ESC_TEST;
+ break;
+ case 'P': /* DCS -- Device Control String */
+ case '_': /* APC -- Application Program Command */
+ case '^': /* PM -- Privacy Message */
+ case ']': /* OSC -- Operating System Command */
+ case 'k': /* old title set compatibility */
+ strreset();
+ strescseq.type = ascii;
+ term.esc |= ESC_STR;
+ break;
+ case '(': /* set primary charset G0 */
+ term.esc |= ESC_ALTCHARSET;
+ break;
+ case ')': /* set secondary charset G1 (IGNORED) */
+ case '*': /* set tertiary charset G2 (IGNORED) */
+ case '+': /* set quaternary charset G3 (IGNORED) */
+ term.esc = 0;
+ break;
+ case 'D': /* IND -- Linefeed */
+ if(term.c.y == term.bot) {
+ tscrollup(term.top, 1);
+ } else {
+ tmoveto(term.c.x, term.c.y+1);
+ }
+ term.esc = 0;
+ break;
+ case 'E': /* NEL -- Next line */
+ tnewline(1); /* always go to first col */
+ term.esc = 0;
+ break;
+ case 'H': /* HTS -- Horizontal tab stop */
+ term.tabs[term.c.x] = 1;
+ term.esc = 0;
+ break;
+ case 'M': /* RI -- Reverse index */
+ if(term.c.y == term.top) {
+ tscrolldown(term.top, 1);
+ } else {
+ tmoveto(term.c.x, term.c.y-1);
+ }
+ term.esc = 0;
+ break;
+ case 'Z': /* DECID -- Identify Terminal */
+ ttywrite(VT102ID, sizeof(VT102ID) - 1);
+ term.esc = 0;
+ break;
+ case 'c': /* RIS -- Reset to inital state */
+ treset();
+ term.esc = 0;
+ xresettitle();
+ xloadcols();
+ break;
+ case '=': /* DECPAM -- Application keypad */
+ term.mode |= MODE_APPKEYPAD;
+ term.esc = 0;
+ break;
+ case '>': /* DECPNM -- Normal keypad */
+ term.mode &= ~MODE_APPKEYPAD;
+ term.esc = 0;
+ break;
+ case '7': /* DECSC -- Save Cursor */
+ tcursor(CURSOR_SAVE);
+ term.esc = 0;
+ break;
+ case '8': /* DECRC -- Restore Cursor */
+ tcursor(CURSOR_LOAD);
+ term.esc = 0;
+ break;
+ case '\\': /* ST -- Stop */
+ term.esc = 0;
+ break;
+ default:
+ fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
+ (uchar) ascii, isprint(ascii)? ascii:'.');
+ term.esc = 0;
+ }
+ }
+ /*
+ * All characters which form part of a sequence are not
+ * printed
+ */
+ return;
+ }
+ /*
+ * Display control codes only if we are in graphic mode
+ */
+ if(control && !(term.c.attr.mode & ATTR_GFX))
+ return;
+ if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
+ selclear(NULL);
+ if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
+ term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
+ tnewline(1);
+ }
+
+ if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
+ memmove(&term.line[term.c.y][term.c.x+1],
+ &term.line[term.c.y][term.c.x],
+ (term.col - term.c.x - 1) * sizeof(Glyph));
+ }
+
+ tsetchar(c, &term.c.attr, term.c.x, term.c.y);
+ if(term.c.x+1 < term.col) {
+ tmoveto(term.c.x+1, term.c.y);
+ } else {
+ term.c.state |= CURSOR_WRAPNEXT;
+ }
+}
+
+int
+tresize(int col, int row) {
+ int i;
+ int minrow = MIN(row, term.row);
+ int mincol = MIN(col, term.col);
+ int slide = term.c.y - row + 1;
+ bool *bp;
+ Line *orig;
+
+ if(col < 1 || row < 1)
+ return 0;
+
+ /* free unneeded rows */
+ i = 0;
+ if(slide > 0) {
+ /*
+ * slide screen to keep cursor where we expect it -
+ * tscrollup would work here, but we can optimize to
+ * memmove because we're freeing the earlier lines
+ */
+ for(/* i = 0 */; i < slide; i++) {
+ free(term.line[i]);
+ free(term.alt[i]);
+ }
+ memmove(term.line, term.line + slide, row * sizeof(Line));
+ memmove(term.alt, term.alt + slide, row * sizeof(Line));
+ }
+ for(i += row; i < term.row; i++) {
+ free(term.line[i]);
+ free(term.alt[i]);
+ }
+
+ /* resize to new height */
+ term.line = xrealloc(term.line, row * sizeof(Line));
+ term.alt = xrealloc(term.alt, row * sizeof(Line));
+ term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
+ term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
+
+ /* resize each row to new width, zero-pad if needed */
+ for(i = 0; i < minrow; i++) {
+ term.dirty[i] = 1;
+ term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
+ term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
+ }
+
+ /* allocate any new rows */
+ for(/* i == minrow */; i < row; i++) {
+ term.dirty[i] = 1;
+ term.line[i] = xcalloc(col, sizeof(Glyph));
+ term.alt [i] = xcalloc(col, sizeof(Glyph));
+ }
+ if(col > term.col) {
+ bp = term.tabs + term.col;
+
+ memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
+ while(--bp > term.tabs && !*bp)
+ /* nothing */ ;
+ for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
+ *bp = 1;
+ }
+ /* update terminal size */
+ term.col = col;
+ term.row = row;
+ /* reset scrolling region */
+ tsetscroll(0, row-1);
+ /* make use of the LIMIT in tmoveto */
+ tmoveto(term.c.x, term.c.y);
+ /* Clearing both screens */
+ orig = term.line;
+ do {
+ if(mincol < col && 0 < minrow) {
+ tclearregion(mincol, 0, col - 1, minrow - 1);
+ }
+ if(0 < col && minrow < row) {
+ tclearregion(0, minrow, col - 1, row - 1);
+ }
+ tswapscreen();
+ } while(orig != term.line);
+
+ return (slide > 0);
+}
+
+void
+xresize(int col, int row) {
+ xw.tw = MAX(1, col * xw.cw);
+ xw.th = MAX(1, row * xw.ch);
+
+ XFreePixmap(xw.dpy, xw.buf);
+ xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
+ DefaultDepth(xw.dpy, xw.scr));
+ XftDrawChange(xw.draw, xw.buf);
+ xclear(0, 0, xw.w, xw.h);
+}
+
+static inline ushort
+sixd_to_16bit(int x) {
+ return x == 0 ? 0 : 0x3737 + 0x2828 * x;
+}
+
+void
+xloadcols(void) {
+ int i, r, g, b;
+ XRenderColor color = { .alpha = 0xffff };
+ static bool loaded;
+ Colour *cp;
+
+ if(loaded) {
+ for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
+ XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
+ }
+
+ /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
+ for(i = 0; i < LEN(colorname); i++) {
+ if(!colorname[i])
+ continue;
+ if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
+ die("Could not allocate color '%s'\n", colorname[i]);
+ }
+ }
+
+ /* load colors [16-255] ; same colors as xterm */
+ for(i = 16, r = 0; r < 6; r++) {
+ for(g = 0; g < 6; g++) {
+ for(b = 0; b < 6; b++) {
+ color.red = sixd_to_16bit(r);
+ color.green = sixd_to_16bit(g);
+ color.blue = sixd_to_16bit(b);
+ if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
+ die("Could not allocate color %d\n", i);
+ }
+ i++;
+ }
+ }
+ }
+
+ for(r = 0; r < 24; r++, i++) {
+ color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
+ if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
+ &dc.col[i])) {
+ die("Could not allocate color %d\n", i);
+ }
+ }
+ loaded = true;
+}
+
+int
+xsetcolorname(int x, const char *name) {
+ XRenderColor color = { .alpha = 0xffff };
+ Colour colour;
+ if (x < 0 || x > LEN(colorname))
+ return -1;
+ if(!name) {
+ if(16 <= x && x < 16 + 216) {
+ int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
+ color.red = sixd_to_16bit(r);
+ color.green = sixd_to_16bit(g);
+ color.blue = sixd_to_16bit(b);
+ if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
+ return 0; /* something went wrong */
+ dc.col[x] = colour;
+ return 1;
+ } else if (16 + 216 <= x && x < 256) {
+ color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
+ if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
+ return 0; /* something went wrong */
+ dc.col[x] = colour;
+ return 1;
+ } else {
+ name = colorname[x];
+ }
+ }
+ if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
+ return 0;
+ dc.col[x] = colour;
+ return 1;
+}
+
+void
+xtermclear(int col1, int row1, int col2, int row2) {
+ XftDrawRect(xw.draw,
+ &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
+ borderpx + col1 * xw.cw,
+ borderpx + row1 * xw.ch,
+ (col2-col1+1) * xw.cw,
+ (row2-row1+1) * xw.ch);
+}
+
+/*
+ * Absolute coordinates.
+ */
+void
+xclear(int x1, int y1, int x2, int y2) {
+ XftDrawRect(xw.draw,
+ &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
+ x1, y1, x2-x1, y2-y1);
+}
+
+void
+xhints(void) {
+ XClassHint class = {opt_class ? opt_class : termname, termname};
+ XWMHints wm = {.flags = InputHint, .input = 1};
+ XSizeHints *sizeh = NULL;
+
+ sizeh = XAllocSizeHints();
+ if(xw.isfixed == False) {
+ sizeh->flags = PSize | PResizeInc | PBaseSize;
+ sizeh->height = xw.h;
+ sizeh->width = xw.w;
+ sizeh->height_inc = xw.ch;
+ sizeh->width_inc = xw.cw;
+ sizeh->base_height = 2 * borderpx;
+ sizeh->base_width = 2 * borderpx;
+ } else {
+ sizeh->flags = PMaxSize | PMinSize;
+ sizeh->min_width = sizeh->max_width = xw.fw;
+ sizeh->min_height = sizeh->max_height = xw.fh;
+ }
+
+ XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
+ XFree(sizeh);
+}
+
+int
+xloadfont(Font *f, FcPattern *pattern) {
+ FcPattern *match;
+ FcResult result;
+
+ match = FcFontMatch(NULL, pattern, &result);
+ if(!match)
+ return 1;
+
+ if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
+ FcPatternDestroy(match);
+ return 1;
+ }
+
+ f->set = NULL;
+ f->pattern = FcPatternDuplicate(pattern);
+
+ f->ascent = f->match->ascent;
+ f->descent = f->match->descent;
+ f->lbearing = 0;
+ f->rbearing = f->match->max_advance_width;
+
+ f->height = f->ascent + f->descent;
+ f->width = f->lbearing + f->rbearing;
+
+ return 0;
+}
+
+void
+xloadfonts(char *fontstr, int fontsize) {
+ FcPattern *pattern;
+ FcResult result;
+ double fontval;
+
+ if(fontstr[0] == '-') {
+ pattern = XftXlfdParse(fontstr, False, False);
+ } else {
+ pattern = FcNameParse((FcChar8 *)fontstr);
+ }
+
+ if(!pattern)
+ die("st: can't open font %s\n", fontstr);
+
+ if(fontsize > 0) {
+ FcPatternDel(pattern, FC_PIXEL_SIZE);
+ FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
+ usedfontsize = fontsize;
+ } else {
+ result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
+ if(result == FcResultMatch) {
+ usedfontsize = (int)fontval;
+ } else {
+ /*
+ * Default font size is 12, if none given. This is to
+ * have a known usedfontsize value.
+ */
+ FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
+ usedfontsize = 12;
+ }
+ }
+
+ FcConfigSubstitute(0, pattern, FcMatchPattern);
+ FcDefaultSubstitute(pattern);
+
+ if(xloadfont(&dc.font, pattern))
+ die("st: can't open font %s\n", fontstr);
+
+ /* Setting character width and height. */
+ xw.cw = CEIL(dc.font.width * cwscale);
+ xw.ch = CEIL(dc.font.height * chscale);
+
+ FcPatternDel(pattern, FC_SLANT);
+ FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
+ if(xloadfont(&dc.ifont, pattern))
+ die("st: can't open font %s\n", fontstr);
+
+ FcPatternDel(pattern, FC_WEIGHT);
+ FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
+ if(xloadfont(&dc.ibfont, pattern))
+ die("st: can't open font %s\n", fontstr);
+
+ FcPatternDel(pattern, FC_SLANT);
+ FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
+ if(xloadfont(&dc.bfont, pattern))
+ die("st: can't open font %s\n", fontstr);
+
+ FcPatternDestroy(pattern);
+}
+
+int
+xloadfontset(Font *f) {
+ FcResult result;
+
+ if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
+ return 1;
+ return 0;
+}
+
+void
+xunloadfont(Font *f) {
+ XftFontClose(xw.dpy, f->match);
+ FcPatternDestroy(f->pattern);
+ if(f->set)
+ FcFontSetDestroy(f->set);
+}
+
+void
+xunloadfonts(void) {
+ int i;
+
+ /* Free the loaded fonts in the font cache. */
+ for(i = 0; i < frclen; i++) {
+ XftFontClose(xw.dpy, frc[i].font);
+ }
+ frclen = 0;
+
+ xunloadfont(&dc.font);
+ xunloadfont(&dc.bfont);
+ xunloadfont(&dc.ifont);
+ xunloadfont(&dc.ibfont);
+}
+
+void
+xzoom(const Arg *arg) {
+ xunloadfonts();
+ xloadfonts(usedfont, usedfontsize + arg->i);
+ cresize(0, 0);
+ redraw(0);
+}
+
+void
+xinit(void) {
+ XGCValues gcvalues;
+ Cursor cursor;
+ Window parent;
+ int sw, sh;
+
+ if(!(xw.dpy = XOpenDisplay(NULL)))
+ die("Can't open display\n");
+ xw.scr = XDefaultScreen(xw.dpy);
+ xw.vis = XDefaultVisual(xw.dpy, xw.scr);
+
+ /* font */
+ if(!FcInit())
+ die("Could not init fontconfig.\n");
+
+ usedfont = (opt_font == NULL)? font : opt_font;
+ xloadfonts(usedfont, 0);
+
+ /* colors */
+ xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
+ xloadcols();
+
+ /* adjust fixed window geometry */
+ if(xw.isfixed) {
+ sw = DisplayWidth(xw.dpy, xw.scr);
+ sh = DisplayHeight(xw.dpy, xw.scr);
+ if(xw.fx < 0)
+ xw.fx = sw + xw.fx - xw.fw - 1;
+ if(xw.fy < 0)
+ xw.fy = sh + xw.fy - xw.fh - 1;
+
+ xw.h = xw.fh;
+ xw.w = xw.fw;
+ } else {
+ /* window - default size */
+ xw.h = 2 * borderpx + term.row * xw.ch;
+ xw.w = 2 * borderpx + term.col * xw.cw;
+ xw.fx = 0;
+ xw.fy = 0;
+ }
+
+ /* Events */
+ xw.attrs.background_pixel = dc.col[defaultbg].pixel;
+ xw.attrs.border_pixel = dc.col[defaultbg].pixel;
+ xw.attrs.bit_gravity = NorthWestGravity;
+ xw.attrs.event_mask = FocusChangeMask | KeyPressMask
+ | ExposureMask | VisibilityChangeMask | StructureNotifyMask
+ | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
+ xw.attrs.colormap = xw.cmap;
+
+ parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
+ XRootWindow(xw.dpy, xw.scr);
+ xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
+ xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
+ xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
+ | CWEventMask | CWColormap, &xw.attrs);
+
+ memset(&gcvalues, 0, sizeof(gcvalues));
+ gcvalues.graphics_exposures = False;
+ dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
+ &gcvalues);
+ xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
+ DefaultDepth(xw.dpy, xw.scr));
+ XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
+ XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
+
+ /* Xft rendering context */
+ xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
+
+ /* input methods */
+ if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
+ XSetLocaleModifiers("@im=local");
+ if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
+ XSetLocaleModifiers("@im=");
+ if((xw.xim = XOpenIM(xw.dpy,
+ NULL, NULL, NULL)) == NULL) {
+ die("XOpenIM failed. Could not open input"
+ " device.\n");
+ }
+ }
+ }
+ xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
+ | XIMStatusNothing, XNClientWindow, xw.win,
+ XNFocusWindow, xw.win, NULL);
+ if(xw.xic == NULL)
+ die("XCreateIC failed. Could not obtain input method.\n");
+
+ /* white cursor, black outline */
+ cursor = XCreateFontCursor(xw.dpy, XC_xterm);
+ XDefineCursor(xw.dpy, xw.win, cursor);
+ XRecolorCursor(xw.dpy, cursor,
+ &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
+ &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
+
+ xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
+ xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
+ XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
+
+ xresettitle();
+ XMapWindow(xw.dpy, xw.win);
+ xhints();
+ XSync(xw.dpy, 0);
+}
+
+void
+xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
+ int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
+ width = charlen * xw.cw, xp, i;
+ int frcflags;
+ int u8fl, u8fblen, u8cblen, doesexist;
+ char *u8c, *u8fs;
+ long u8char;
+ Font *font = &dc.font;
+ FcResult fcres;
+ FcPattern *fcpattern, *fontpattern;
+ FcFontSet *fcsets[] = { NULL };
+ FcCharSet *fccharset;
+ Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
+ XRenderColor colfg, colbg;
+ Rectangle r;
+ int oneatatime;
+
+ frcflags = FRC_NORMAL;
+
+ if(base.mode & ATTR_ITALIC) {
+ if(base.fg == defaultfg)
+ base.fg = defaultitalic;
+ font = &dc.ifont;
+ frcflags = FRC_ITALIC;
+ } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
+ if(base.fg == defaultfg)
+ base.fg = defaultitalic;
+ font = &dc.ibfont;
+ frcflags = FRC_ITALICBOLD;
+ } else if(base.mode & ATTR_UNDERLINE) {
+ if(base.fg == defaultfg)
+ base.fg = defaultunderline;
+ }
+ if(IS_TRUECOL(base.fg)) {
+ colfg.red = TRUERED(base.fg);
+ colfg.green = TRUEGREEN(base.fg);
+ colfg.blue = TRUEBLUE(base.fg);
+ XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
+ fg = &truefg;
+ } else {
+ fg = &dc.col[base.fg];
+ }
+
+ if(IS_TRUECOL(base.bg)) {
+ colbg.green = TRUEGREEN(base.bg);
+ colbg.red = TRUERED(base.bg);
+ colbg.blue = TRUEBLUE(base.bg);
+ XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
+ bg = &truebg;
+ } else {
+ bg = &dc.col[base.bg];
+ }
+
+
+
+ if(base.mode & ATTR_BOLD) {
+ if(BETWEEN(base.fg, 0, 7)) {
+ /* basic system colors */
+ fg = &dc.col[base.fg + 8];
+ } else if(BETWEEN(base.fg, 16, 195)) {
+ /* 256 colors */
+ fg = &dc.col[base.fg + 36];
+ } else if(BETWEEN(base.fg, 232, 251)) {
+ /* greyscale */
+ fg = &dc.col[base.fg + 4];
+ }
+ /*
+ * Those ranges will not be brightened:
+ * 8 - 15 – bright system colors
+ * 196 - 231 – highest 256 color cube
+ * 252 - 255 – brightest colors in greyscale
+ */
+ font = &dc.bfont;
+ frcflags = FRC_BOLD;
+ }
+
+ if(IS_SET(MODE_REVERSE)) {
+ if(fg == &dc.col[defaultfg]) {
+ fg = &dc.col[defaultbg];
+ } else {
+ colfg.red = ~fg->color.red;
+ colfg.green = ~fg->color.green;
+ colfg.blue = ~fg->color.blue;
+ colfg.alpha = fg->color.alpha;
+ XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
+ fg = &revfg;
+ }
+
+ if(bg == &dc.col[defaultbg]) {
+ bg = &dc.col[defaultfg];
+ } else {
+ colbg.red = ~bg->color.red;
+ colbg.green = ~bg->color.green;
+ colbg.blue = ~bg->color.blue;
+ colbg.alpha = bg->color.alpha;
+ XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
+ bg = &revbg;
+ }
+ }
+
+ if(base.mode & ATTR_REVERSE) {
+ temp = fg;
+ fg = bg;
+ bg = temp;
+ }
+
+ if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
+ fg = bg;
+
+ /* Intelligent cleaning up of the borders. */
+ if(x == 0) {
+ xclear(0, (y == 0)? 0 : winy, borderpx,
+ winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
+ }
+ if(x + charlen >= term.col) {
+ xclear(winx + width, (y == 0)? 0 : winy, xw.w,
+ ((y >= term.row-1)? xw.h : (winy + xw.ch)));
+ }
+ if(y == 0)
+ xclear(winx, 0, winx + width, borderpx);
+ if(y == term.row-1)
+ xclear(winx, winy + xw.ch, winx + width, xw.h);
+
+ /* Clean up the region we want to draw to. */
+ XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
+
+ /* Set the clip region because Xft is sometimes dirty. */
+ r.x = 0;
+ r.y = 0;
+ r.height = xw.ch;
+ r.width = width;
+ XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
+
+ for(xp = winx; bytelen > 0;) {
+ /*
+ * Search for the range in the to be printed string of glyphs
+ * that are in the main font. Then print that range. If
+ * some glyph is found that is not in the font, do the
+ * fallback dance.
+ */
+ u8fs = s;
+ u8fblen = 0;
+ u8fl = 0;
+ oneatatime = font->width != xw.cw;
+ for(;;) {
+ u8c = s;
+ u8cblen = utf8decode(s, &u8char);
+ s += u8cblen;
+ bytelen -= u8cblen;
+
+ doesexist = XftCharExists(xw.dpy, font->match, u8char);
+ if(oneatatime || !doesexist || bytelen <= 0) {
+ if(oneatatime || bytelen <= 0) {
+ if(doesexist) {
+ u8fl++;
+ u8fblen += u8cblen;
+ }
+ }
+
+ if(u8fl > 0) {
+ XftDrawStringUtf8(xw.draw, fg,
+ font->match, xp,
+ winy + font->ascent,
+ (FcChar8 *)u8fs,
+ u8fblen);
+ xp += CEIL(font->width * cwscale * u8fl);
+
+ }
+ break;
+ }
+
+ u8fl++;
+ u8fblen += u8cblen;
+ }
+ if(doesexist) {
+ if (oneatatime);
+ continue;
+ break;
+ }
+
+ /* Search the font cache. */
+ for(i = 0; i < frclen; i++) {
+ if(XftCharExists(xw.dpy, frc[i].font, u8char)
+ && frc[i].flags == frcflags) {
+ break;
+ }
+ }