+ /*
+ * 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();
+ 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.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
+ sel.bx = -1;
+ 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 };
+
+ /* 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);
+ }
+ }
+}
+
+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->set = FcFontSort(0, match, FcTrue, 0, &result))) {
+ FcPatternDestroy(match);
+ return 1;
+ }
+
+ if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
+ FcPatternDestroy(match);
+ return 1;
+ }
+
+ 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 = dc.font.width;
+ xw.ch = dc.font.height;
+
+ 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);
+}
+
+void
+xunloadfonts(void) {
+ int i, ip;
+
+ /*
+ * Free the loaded fonts in the font cache. This is done backwards
+ * from the frccur.
+ */
+ for(i = 0, ip = frccur; i < frclen; i++, ip--) {
+ if(ip < 0)
+ ip = LEN(frc) - 1;
+ XftFontClose(xw.dpy, frc[ip].font);
+ }
+ frccur = -1;
+ frclen = 0;
+
+ XftFontClose(xw.dpy, dc.font.match);
+ FcPatternDestroy(dc.font.pattern);
+ FcFontSetDestroy(dc.font.set);
+ XftFontClose(xw.dpy, dc.bfont.match);
+ FcPatternDestroy(dc.bfont.pattern);
+ FcFontSetDestroy(dc.bfont.set);
+ XftFontClose(xw.dpy, dc.ifont.match);
+ FcPatternDestroy(dc.ifont.pattern);
+ FcFontSetDestroy(dc.ifont.set);
+ XftFontClose(xw.dpy, dc.ibfont.match);
+ FcPatternDestroy(dc.ibfont.pattern);
+ FcFontSetDestroy(dc.ibfont.set);
+}
+
+void
+xzoom(const Arg *arg) {
+ xunloadfonts();
+ xloadfonts(usedfont, usedfontsize + arg->i);
+ cresize(0, 0);
+ redraw(0);
+}
+
+void
+xinit(void) {
+ XSetWindowAttributes attrs;
+ 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 */
+ attrs.background_pixel = dc.col[defaultbg].pixel;
+ attrs.border_pixel = dc.col[defaultbg].pixel;
+ attrs.bit_gravity = NorthWestGravity;
+ attrs.event_mask = FocusChangeMask | KeyPressMask
+ | ExposureMask | VisibilityChangeMask | StructureNotifyMask
+ | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
+ 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,
+ &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 frp, 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;
+ XRenderColor colfg, colbg;
+ Rectangle r;
+
+ 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;
+ }
+ fg = &dc.col[base.fg];
+ 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);
+
+ fcsets[0] = font->set;
+ 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;
+ for(;;) {
+ u8c = s;
+ u8cblen = utf8decode(s, &u8char);
+ s += u8cblen;
+ bytelen -= u8cblen;
+
+ doesexist = XftCharIndex(xw.dpy, font->match, u8char);
+ if(!doesexist || bytelen <= 0) {
+ if(bytelen <= 0) {
+ if(doesexist) {
+ u8fl++;
+ u8fblen += u8cblen;
+ }
+ }
+
+ if(u8fl > 0) {
+ XftDrawStringUtf8(xw.draw, fg,
+ font->match, xp,
+ winy + font->ascent,
+ (FcChar8 *)u8fs,
+ u8fblen);
+ xp += font->width * u8fl;
+
+ }
+ break;
+ }
+
+ u8fl++;
+ u8fblen += u8cblen;
+ }
+ if(doesexist)
+ break;
+
+ frp = frccur;
+ /* Search the font cache. */
+ for(i = 0; i < frclen; i++, frp--) {
+ if(frp <= 0)
+ frp = LEN(frc) - 1;
+
+ if(frc[frp].c == u8char
+ && frc[frp].flags == frcflags) {
+ break;
+ }
+ }
+
+ /* Nothing was found. */
+ if(i >= frclen) {
+ /*
+ * Nothing was found in the cache. Now use
+ * some dozen of Fontconfig calls to get the
+ * font for one single character.
+ */
+ fcpattern = FcPatternDuplicate(font->pattern);
+ fccharset = FcCharSetCreate();
+
+ FcCharSetAddChar(fccharset, u8char);
+ FcPatternAddCharSet(fcpattern, FC_CHARSET,
+ fccharset);
+ FcPatternAddBool(fcpattern, FC_SCALABLE,
+ FcTrue);
+
+ FcConfigSubstitute(0, fcpattern,
+ FcMatchPattern);
+ FcDefaultSubstitute(fcpattern);
+
+ fontpattern = FcFontSetMatch(0, fcsets,
+ FcTrue, fcpattern, &fcres);
+
+ /*
+ * Overwrite or create the new cache entry.
+ */
+ frccur++;
+ frclen++;
+ if(frccur >= LEN(frc))
+ frccur = 0;
+ if(frclen > LEN(frc)) {
+ frclen = LEN(frc);
+ XftFontClose(xw.dpy, frc[frccur].font);
+ }
+
+ frc[frccur].font = XftFontOpenPattern(xw.dpy,
+ fontpattern);
+ frc[frccur].c = u8char;
+ frc[frccur].flags = frcflags;
+
+ FcPatternDestroy(fcpattern);
+ FcCharSetDestroy(fccharset);
+
+ frp = frccur;
+ }
+
+ XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
+ xp, winy + frc[frp].font->ascent,
+ (FcChar8 *)u8c, u8cblen);
+
+ xp += font->width;
+ }
+
+ /*
+ XftDrawStringUtf8(xw.draw, fg, font->set, winx,
+ winy + font->ascent, (FcChar8 *)s, bytelen);
+ */
+
+ if(base.mode & ATTR_UNDERLINE) {
+ XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
+ width, 1);
+ }
+
+ /* Reset clip to none. */
+ XftDrawSetClip(xw.draw, 0);
+}
+
+void
+xdrawcursor(void) {
+ static int oldx = 0, oldy = 0;
+ int sl;
+ Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
+
+ LIMIT(oldx, 0, term.col-1);
+ LIMIT(oldy, 0, term.row-1);
+
+ memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
+
+ /* remove the old cursor */
+ sl = utf8size(term.line[oldy][oldx].c);
+ xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
+ oldy, 1, sl);
+
+ /* draw the new one */
+ if(!(IS_SET(MODE_HIDE))) {
+ if(xw.state & WIN_FOCUSED) {
+ if(IS_SET(MODE_REVERSE)) {
+ g.mode |= ATTR_REVERSE;
+ g.fg = defaultcs;
+ g.bg = defaultfg;
+ }
+
+ sl = utf8size(g.c);
+ xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
+ } else {
+ XftDrawRect(xw.draw, &dc.col[defaultcs],
+ borderpx + term.c.x * xw.cw,
+ borderpx + term.c.y * xw.ch,
+ xw.cw - 1, 1);
+ XftDrawRect(xw.draw, &dc.col[defaultcs],
+ borderpx + term.c.x * xw.cw,
+ borderpx + term.c.y * xw.ch,
+ 1, xw.ch - 1);
+ XftDrawRect(xw.draw, &dc.col[defaultcs],
+ borderpx + (term.c.x + 1) * xw.cw - 1,
+ borderpx + term.c.y * xw.ch,
+ 1, xw.ch - 1);
+ XftDrawRect(xw.draw, &dc.col[defaultcs],
+ borderpx + term.c.x * xw.cw,
+ borderpx + (term.c.y + 1) * xw.ch - 1,
+ xw.cw, 1);
+ }
+ oldx = term.c.x, oldy = term.c.y;
+ }
+}
+
+
+void
+xsettitle(char *p) {
+ XTextProperty prop;
+
+ Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
+ &prop);
+ XSetWMName(xw.dpy, xw.win, &prop);
+}
+
+void
+xresettitle(void) {
+ xsettitle(opt_title ? opt_title : "st");
+}
+
+void
+redraw(int timeout) {
+ struct timespec tv = {0, timeout * 1000};
+
+ tfulldirt();
+ draw();
+
+ if(timeout > 0) {
+ nanosleep(&tv, NULL);
+ XSync(xw.dpy, False); /* necessary for a good tput flash */
+ }
+}
+
+void
+draw(void) {
+ drawregion(0, 0, term.col, term.row);
+ XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
+ xw.h, 0, 0);
+ XSetForeground(xw.dpy, dc.gc,
+ dc.col[IS_SET(MODE_REVERSE)?
+ defaultfg : defaultbg].pixel);
+}
+
+void
+drawregion(int x1, int y1, int x2, int y2) {
+ int ic, ib, x, y, ox, sl;
+ Glyph base, new;
+ char buf[DRAW_BUF_SIZ];
+ bool ena_sel = sel.bx != -1;
+
+ if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
+ ena_sel = 0;
+
+ if(!(xw.state & WIN_VISIBLE))
+ return;
+
+ for(y = y1; y < y2; y++) {
+ if(!term.dirty[y])
+ continue;
+
+ xtermclear(0, y, term.col, y);
+ term.dirty[y] = 0;
+ base = term.line[y][0];
+ ic = ib = ox = 0;
+ for(x = x1; x < x2; x++) {
+ new = term.line[y][x];
+ if(ena_sel && selected(x, y))
+ new.mode ^= ATTR_REVERSE;
+ if(ib > 0 && (ATTRCMP(base, new)
+ || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
+ xdraws(buf, base, ox, y, ic, ib);
+ ic = ib = 0;
+ }
+ if(ib == 0) {
+ ox = x;
+ base = new;
+ }
+
+ sl = utf8size(new.c);
+ memcpy(buf+ib, new.c, sl);
+ ib += sl;
+ ++ic;
+ }
+ if(ib > 0)
+ xdraws(buf, base, ox, y, ic, ib);
+ }
+ xdrawcursor();
+}
+
+void
+expose(XEvent *ev) {
+ XExposeEvent *e = &ev->xexpose;
+
+ if(xw.state & WIN_REDRAW) {
+ if(!e->count)
+ xw.state &= ~WIN_REDRAW;
+ }
+ redraw(0);
+}
+
+void
+visibility(XEvent *ev) {
+ XVisibilityEvent *e = &ev->xvisibility;
+
+ if(e->state == VisibilityFullyObscured) {
+ xw.state &= ~WIN_VISIBLE;
+ } else if(!(xw.state & WIN_VISIBLE)) {
+ /* need a full redraw for next Expose, not just a buf copy */
+ xw.state |= WIN_VISIBLE | WIN_REDRAW;
+ }
+}
+
+void
+unmap(XEvent *ev) {
+ xw.state &= ~WIN_VISIBLE;
+}
+
+void
+xseturgency(int add) {
+ XWMHints *h = XGetWMHints(xw.dpy, xw.win);
+
+ h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
+ XSetWMHints(xw.dpy, xw.win, h);
+ XFree(h);
+}
+
+void
+focus(XEvent *ev) {
+ XFocusChangeEvent *e = &ev->xfocus;
+
+ if(e->mode == NotifyGrab)
+ return;
+
+ if(ev->type == FocusIn) {
+ XSetICFocus(xw.xic);
+ xw.state |= WIN_FOCUSED;
+ xseturgency(0);
+ } else {
+ XUnsetICFocus(xw.xic);
+ xw.state &= ~WIN_FOCUSED;
+ }
+}
+
+inline bool
+match(uint mask, uint state) {
+ state &= ~(ignoremod);
+
+ if(mask == XK_NO_MOD && state)
+ return false;
+ if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
+ return false;
+ if((state & mask) != state)
+ return false;
+ return true;
+}
+
+void
+numlock(const Arg *dummy) {
+ term.numlock ^= 1;
+}
+
+char*
+kmap(KeySym k, uint state) {
+ uint mask;
+ Key *kp;
+ int i;
+
+ /* Check for mapped keys out of X11 function keys. */
+ for(i = 0; i < LEN(mappedkeys); i++) {
+ if(mappedkeys[i] == k)
+ break;
+ }
+ if(i == LEN(mappedkeys)) {
+ if((k & 0xFFFF) < 0xFD00)
+ return NULL;
+ }
+
+ for(kp = key; kp < key + LEN(key); kp++) {
+ mask = kp->mask;
+
+ if(kp->k != k)
+ continue;
+
+ if(!match(mask, state))
+ continue;
+
+ if(kp->appkey > 0) {
+ if(!IS_SET(MODE_APPKEYPAD))
+ continue;
+ if(term.numlock && kp->appkey == 2)
+ continue;
+ } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
+ continue;
+ }
+
+ if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
+ (kp->appcursor > 0
+ && !IS_SET(MODE_APPCURSOR))) {
+ continue;
+ }
+
+ if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
+ (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
+ continue;
+ }
+
+ return kp->s;
+ }
+
+ return NULL;
+}
+
+void
+kpress(XEvent *ev) {
+ XKeyEvent *e = &ev->xkey;
+ KeySym ksym;
+ char xstr[31], buf[32], *customkey, *cp = buf;
+ int len, ret;
+ long c;
+ Status status;
+ Shortcut *bp;
+
+ if(IS_SET(MODE_KBDLOCK))
+ return;
+
+ len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
+ e->state &= ~Mod2Mask;
+ /* 1. shortcuts */
+ for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
+ if(ksym == bp->keysym && match(bp->mod, e->state)) {
+ bp->func(&(bp->arg));
+ return;
+ }
+ }
+
+ /* 2. custom keys from config.h */
+ if((customkey = kmap(ksym, e->state))) {
+ len = strlen(customkey);
+ memcpy(buf, customkey, len);
+ /* 3. hardcoded (overrides X lookup) */
+ } else {
+ if(len == 0)
+ return;
+
+ if(len == 1 && e->state & Mod1Mask) {
+ if(IS_SET(MODE_8BIT)) {
+ if(*xstr < 0177) {
+ c = *xstr | B7;
+ ret = utf8encode(&c, cp);
+ cp += ret;
+ len = 0;
+ }
+ } else {
+ *cp++ = '\033';
+ }
+ }
+
+ memcpy(cp, xstr, len);
+ len = cp - buf + len;
+ }
+
+ ttywrite(buf, len);
+ if(IS_SET(MODE_ECHO))
+ techo(buf, len);
+}
+
+
+void
+cmessage(XEvent *e) {
+ /*
+ * See xembed specs
+ * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
+ */
+ if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
+ if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
+ xw.state |= WIN_FOCUSED;
+ xseturgency(0);
+ } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
+ xw.state &= ~WIN_FOCUSED;
+ }
+ } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
+ /* Send SIGHUP to shell */
+ kill(pid, SIGHUP);
+ exit(EXIT_SUCCESS);
+ }
+}
+
+void
+cresize(int width, int height) {
+ int col, row;
+
+ if(width != 0)
+ xw.w = width;
+ if(height != 0)
+ xw.h = height;
+
+ col = (xw.w - 2 * borderpx) / xw.cw;
+ row = (xw.h - 2 * borderpx) / xw.ch;
+
+ tresize(col, row);
+ xresize(col, row);
+ ttyresize();
+}
+
+void
+resize(XEvent *e) {
+ if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
+ return;
+
+ cresize(e->xconfigure.width, e->xconfigure.height);
+}
+
+void
+run(void) {
+ XEvent ev;
+ fd_set rfd;
+ int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
+ struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
+
+ gettimeofday(&lastblink, NULL);
+ gettimeofday(&last, NULL);
+
+ for(xev = actionfps;;) {
+ FD_ZERO(&rfd);
+ FD_SET(cmdfd, &rfd);
+ FD_SET(xfd, &rfd);
+
+ switch(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
+ case -1:
+ if(errno == EINTR)
+ continue;
+ die("select failed: %s\n", SERRNO);
+ default:
+ if(FD_ISSET(cmdfd, &rfd)) {
+ ttyread();
+ if(blinktimeout) {
+ blinkset = tattrset(ATTR_BLINK);
+ if(!blinkset && term.mode & ATTR_BLINK)
+ term.mode &= ~(MODE_BLINK);
+ }
+ }
+
+ if(FD_ISSET(xfd, &rfd))
+ xev = actionfps;
+ break;
+ }
+ gettimeofday(&now, NULL);
+ drawtimeout.tv_sec = 0;
+ drawtimeout.tv_usec = (1000/xfps) * 1000;
+ tv = &drawtimeout;
+
+ dodraw = 0;
+ if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
+ tsetdirtattr(ATTR_BLINK);
+ term.mode ^= MODE_BLINK;
+ gettimeofday(&lastblink, NULL);
+ dodraw = 1;
+ }
+ if(TIMEDIFF(now, last) \
+ > (xev? (1000/xfps) : (1000/actionfps))) {
+ dodraw = 1;
+ last = now;
+ }
+
+ if(dodraw) {
+ while(XPending(xw.dpy)) {
+ XNextEvent(xw.dpy, &ev);
+ if(XFilterEvent(&ev, None))
+ continue;
+ if(handler[ev.type])
+ (handler[ev.type])(&ev);
+ }
+
+ draw();
+ XFlush(xw.dpy);
+
+ if(xev && !FD_ISSET(xfd, &rfd))
+ xev--;
+ if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
+ if(blinkset) {
+ if(TIMEDIFF(now, lastblink) \
+ > blinktimeout) {
+ drawtimeout.tv_usec = 1;
+ } else {
+ drawtimeout.tv_usec = (1000 * \
+ (blinktimeout - \
+ TIMEDIFF(now,
+ lastblink)));
+ }
+ } else {
+ tv = NULL;
+ }
+ }
+ }
+ }
+}
+
+void
+usage(void) {
+ die("%s " VERSION " (c) 2010-2013 st engineers\n" \
+ "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
+ " [-t title] [-w windowid] [-e command ...]\n", argv0);
+}
+
+int
+main(int argc, char *argv[]) {
+ int bitm, xr, yr;
+ uint wr, hr;
+
+ xw.fw = xw.fh = xw.fx = xw.fy = 0;
+ xw.isfixed = False;
+
+ ARGBEGIN {
+ case 'a':
+ allowaltscreen = false;
+ break;
+ case 'c':
+ opt_class = EARGF(usage());
+ break;
+ case 'e':
+ /* eat all remaining arguments */
+ if(argc > 1)
+ opt_cmd = &argv[1];
+ goto run;
+ case 'f':
+ opt_font = EARGF(usage());
+ break;
+ case 'g':
+ bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
+ if(bitm & XValue)
+ xw.fx = xr;
+ if(bitm & YValue)
+ xw.fy = yr;
+ if(bitm & WidthValue)
+ xw.fw = (int)wr;
+ if(bitm & HeightValue)
+ xw.fh = (int)hr;
+ if(bitm & XNegative && xw.fx == 0)
+ xw.fx = -1;
+ if(bitm & XNegative && xw.fy == 0)
+ xw.fy = -1;
+
+ if(xw.fh != 0 && xw.fw != 0)
+ xw.isfixed = True;
+ break;
+ case 'o':
+ opt_io = EARGF(usage());
+ break;
+ case 't':
+ opt_title = EARGF(usage());
+ break;
+ case 'w':
+ opt_embed = EARGF(usage());
+ break;
+ case 'v':
+ default:
+ usage();
+ } ARGEND;
+
+run:
+ setlocale(LC_CTYPE, "");
+ XSetLocaleModifiers("");
+ tnew(80, 24);
+ xinit();
+ ttynew();
+ selinit();
+ if(xw.isfixed)
+ cresize(xw.h, xw.w);
+ run();
+
+ return 0;
+}
+