x.c (48588B)
1 /* See LICENSE for license details. */ 2 #include <errno.h> 3 #include <math.h> 4 #include <limits.h> 5 #include <locale.h> 6 #include <signal.h> 7 #include <sys/select.h> 8 #include <time.h> 9 #include <unistd.h> 10 #include <libgen.h> 11 #include <X11/Xatom.h> 12 #include <X11/Xlib.h> 13 #include <X11/cursorfont.h> 14 #include <X11/keysym.h> 15 #include <X11/Xft/Xft.h> 16 #include <X11/XKBlib.h> 17 18 char *argv0; 19 #include "arg.h" 20 #include "st.h" 21 #include "win.h" 22 23 /* types used in config.h */ 24 typedef struct { 25 uint mod; 26 KeySym keysym; 27 void (*func)(const Arg *); 28 const Arg arg; 29 } Shortcut; 30 31 typedef struct { 32 uint mod; 33 uint button; 34 void (*func)(const Arg *); 35 const Arg arg; 36 uint release; 37 } MouseShortcut; 38 39 typedef struct { 40 KeySym k; 41 uint mask; 42 char *s; 43 /* three-valued logic variables: 0 indifferent, 1 on, -1 off */ 44 signed char appkey; /* application keypad */ 45 signed char appcursor; /* application cursor */ 46 } Key; 47 48 /* X modifiers */ 49 #define XK_ANY_MOD UINT_MAX 50 #define XK_NO_MOD 0 51 #define XK_SWITCH_MOD (1<<13|1<<14) 52 53 /* function definitions used in config.h */ 54 static void clipcopy(const Arg *); 55 static void clippaste(const Arg *); 56 static void numlock(const Arg *); 57 static void selpaste(const Arg *); 58 static void zoom(const Arg *); 59 static void zoomabs(const Arg *); 60 static void zoomreset(const Arg *); 61 static void ttysend(const Arg *); 62 63 /* config.h for applying patches and the configuration. */ 64 #include "config.h" 65 66 /* XEMBED messages */ 67 #define XEMBED_FOCUS_IN 4 68 #define XEMBED_FOCUS_OUT 5 69 70 /* macros */ 71 #define IS_SET(flag) ((win.mode & (flag)) != 0) 72 #define TRUERED(x) (((x) & 0xff0000) >> 8) 73 #define TRUEGREEN(x) (((x) & 0xff00)) 74 #define TRUEBLUE(x) (((x) & 0xff) << 8) 75 76 typedef XftDraw *Draw; 77 typedef XftColor Color; 78 typedef XftGlyphFontSpec GlyphFontSpec; 79 80 /* Purely graphic info */ 81 typedef struct { 82 int tw, th; /* tty width and height */ 83 int w, h; /* window width and height */ 84 int ch; /* char height */ 85 int cw; /* char width */ 86 int mode; /* window state/mode flags */ 87 int cursor; /* cursor style */ 88 } TermWindow; 89 90 typedef struct { 91 Display *dpy; 92 Colormap cmap; 93 Window win; 94 Drawable buf; 95 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */ 96 Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid; 97 struct { 98 XIM xim; 99 XIC xic; 100 XPoint spot; 101 XVaNestedList spotlist; 102 } ime; 103 Draw draw; 104 Visual *vis; 105 XSetWindowAttributes attrs; 106 int scr; 107 int isfixed; /* is fixed geometry? */ 108 int depth; /* bit depth */ 109 int l, t; /* left and top offset */ 110 int gm; /* geometry mask */ 111 } XWindow; 112 113 typedef struct { 114 Atom xtarget; 115 char *primary, *clipboard; 116 struct timespec tclick1; 117 struct timespec tclick2; 118 } XSelection; 119 120 /* Font structure */ 121 #define Font Font_ 122 typedef struct { 123 int height; 124 int width; 125 int ascent; 126 int descent; 127 int badslant; 128 int badweight; 129 short lbearing; 130 short rbearing; 131 XftFont *match; 132 FcFontSet *set; 133 FcPattern *pattern; 134 } Font; 135 136 /* Drawing Context */ 137 typedef struct { 138 Color *col; 139 size_t collen; 140 Font font, bfont, ifont, ibfont; 141 GC gc; 142 } DC; 143 144 static inline ushort sixd_to_16bit(int); 145 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int); 146 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int); 147 static void xdrawglyph(Glyph, int, int); 148 static void xclear(int, int, int, int); 149 static int xgeommasktogravity(int); 150 static int ximopen(Display *); 151 static void ximinstantiate(Display *, XPointer, XPointer); 152 static void ximdestroy(XIM, XPointer, XPointer); 153 static int xicdestroy(XIC, XPointer, XPointer); 154 static void xinit(int, int); 155 static void cresize(int, int); 156 static void xresize(int, int); 157 static void xhints(void); 158 static int xloadcolor(int, const char *, Color *); 159 static int xloadfont(Font *, FcPattern *); 160 static void xloadfonts(const char *, double); 161 static void xunloadfont(Font *); 162 static void xunloadfonts(void); 163 static void xsetenv(void); 164 static void xseturgency(int); 165 static int evcol(XEvent *); 166 static int evrow(XEvent *); 167 168 static void expose(XEvent *); 169 static void visibility(XEvent *); 170 static void unmap(XEvent *); 171 static void kpress(XEvent *); 172 static void cmessage(XEvent *); 173 static void resize(XEvent *); 174 static void focus(XEvent *); 175 static uint buttonmask(uint); 176 static int mouseaction(XEvent *, uint); 177 static void brelease(XEvent *); 178 static void bpress(XEvent *); 179 static void bmotion(XEvent *); 180 static void propnotify(XEvent *); 181 static void selnotify(XEvent *); 182 static void selclear_(XEvent *); 183 static void selrequest(XEvent *); 184 static void setsel(char *, Time); 185 static void mousesel(XEvent *, int); 186 static void mousereport(XEvent *); 187 static char *kmap(KeySym, uint); 188 static int match(uint, uint); 189 190 static void run(void); 191 static void usage(void); 192 193 static void (*handler[LASTEvent])(XEvent *) = { 194 [KeyPress] = kpress, 195 [ClientMessage] = cmessage, 196 [ConfigureNotify] = resize, 197 [VisibilityNotify] = visibility, 198 [UnmapNotify] = unmap, 199 [Expose] = expose, 200 [FocusIn] = focus, 201 [FocusOut] = focus, 202 [MotionNotify] = bmotion, 203 [ButtonPress] = bpress, 204 [ButtonRelease] = brelease, 205 /* 206 * Uncomment if you want the selection to disappear when you select something 207 * different in another window. 208 */ 209 /* [SelectionClear] = selclear_, */ 210 [SelectionNotify] = selnotify, 211 /* 212 * PropertyNotify is only turned on when there is some INCR transfer happening 213 * for the selection retrieval. 214 */ 215 [PropertyNotify] = propnotify, 216 [SelectionRequest] = selrequest, 217 }; 218 219 /* Globals */ 220 static DC dc; 221 static XWindow xw; 222 static XSelection xsel; 223 static TermWindow win; 224 225 /* Font Ring Cache */ 226 enum { 227 FRC_NORMAL, 228 FRC_ITALIC, 229 FRC_BOLD, 230 FRC_ITALICBOLD 231 }; 232 233 typedef struct { 234 XftFont *font; 235 int flags; 236 Rune unicodep; 237 } Fontcache; 238 239 /* Fontcache is an array now. A new font will be appended to the array. */ 240 static Fontcache *frc = NULL; 241 static int frclen = 0; 242 static int frccap = 0; 243 static char *usedfont = NULL; 244 static double usedfontsize = 0; 245 static double defaultfontsize = 0; 246 247 static char *opt_alpha = NULL; 248 static char *opt_class = NULL; 249 static char **opt_cmd = NULL; 250 static char *opt_embed = NULL; 251 static char *opt_font = NULL; 252 static char *opt_io = NULL; 253 static char *opt_line = NULL; 254 static char *opt_name = NULL; 255 static char *opt_title = NULL; 256 257 static uint buttons; /* bit field of pressed buttons */ 258 259 void 260 clipcopy(const Arg *dummy) 261 { 262 Atom clipboard; 263 264 free(xsel.clipboard); 265 xsel.clipboard = NULL; 266 267 if (xsel.primary != NULL) { 268 xsel.clipboard = xstrdup(xsel.primary); 269 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); 270 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime); 271 } 272 } 273 274 void 275 clippaste(const Arg *dummy) 276 { 277 Atom clipboard; 278 279 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); 280 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard, 281 xw.win, CurrentTime); 282 } 283 284 void 285 selpaste(const Arg *dummy) 286 { 287 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY, 288 xw.win, CurrentTime); 289 } 290 291 void 292 numlock(const Arg *dummy) 293 { 294 win.mode ^= MODE_NUMLOCK; 295 } 296 297 void 298 zoom(const Arg *arg) 299 { 300 Arg larg; 301 302 larg.f = usedfontsize + arg->f; 303 zoomabs(&larg); 304 } 305 306 void 307 zoomabs(const Arg *arg) 308 { 309 xunloadfonts(); 310 xloadfonts(usedfont, arg->f); 311 cresize(0, 0); 312 redraw(); 313 xhints(); 314 } 315 316 void 317 zoomreset(const Arg *arg) 318 { 319 Arg larg; 320 321 if (defaultfontsize > 0) { 322 larg.f = defaultfontsize; 323 zoomabs(&larg); 324 } 325 } 326 327 void 328 ttysend(const Arg *arg) 329 { 330 ttywrite(arg->s, strlen(arg->s), 1); 331 } 332 333 int 334 evcol(XEvent *e) 335 { 336 int x = e->xbutton.x - borderpx; 337 LIMIT(x, 0, win.tw - 1); 338 return x / win.cw; 339 } 340 341 int 342 evrow(XEvent *e) 343 { 344 int y = e->xbutton.y - borderpx; 345 LIMIT(y, 0, win.th - 1); 346 return y / win.ch; 347 } 348 349 void 350 mousesel(XEvent *e, int done) 351 { 352 int type, seltype = SEL_REGULAR; 353 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod); 354 355 for (type = 1; type < LEN(selmasks); ++type) { 356 if (match(selmasks[type], state)) { 357 seltype = type; 358 break; 359 } 360 } 361 selextend(evcol(e), evrow(e), seltype, done); 362 if (done) 363 setsel(getsel(), e->xbutton.time); 364 } 365 366 void 367 mousereport(XEvent *e) 368 { 369 int len, btn, code; 370 int x = evcol(e), y = evrow(e); 371 int state = e->xbutton.state; 372 char buf[40]; 373 static int ox, oy; 374 375 if (e->type == MotionNotify) { 376 if (x == ox && y == oy) 377 return; 378 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY)) 379 return; 380 /* MODE_MOUSEMOTION: no reporting if no button is pressed */ 381 if (IS_SET(MODE_MOUSEMOTION) && buttons == 0) 382 return; 383 /* Set btn to lowest-numbered pressed button, or 12 if no 384 * buttons are pressed. */ 385 for (btn = 1; btn <= 11 && !(buttons & (1<<(btn-1))); btn++) 386 ; 387 code = 32; 388 } else { 389 btn = e->xbutton.button; 390 /* Only buttons 1 through 11 can be encoded */ 391 if (btn < 1 || btn > 11) 392 return; 393 if (e->type == ButtonRelease) { 394 /* MODE_MOUSEX10: no button release reporting */ 395 if (IS_SET(MODE_MOUSEX10)) 396 return; 397 /* Don't send release events for the scroll wheel */ 398 if (btn == 4 || btn == 5) 399 return; 400 } 401 code = 0; 402 } 403 404 ox = x; 405 oy = y; 406 407 /* Encode btn into code. If no button is pressed for a motion event in 408 * MODE_MOUSEMANY, then encode it as a release. */ 409 if ((!IS_SET(MODE_MOUSESGR) && e->type == ButtonRelease) || btn == 12) 410 code += 3; 411 else if (btn >= 8) 412 code += 128 + btn - 8; 413 else if (btn >= 4) 414 code += 64 + btn - 4; 415 else 416 code += btn - 1; 417 418 if (!IS_SET(MODE_MOUSEX10)) { 419 code += ((state & ShiftMask ) ? 4 : 0) 420 + ((state & Mod1Mask ) ? 8 : 0) /* meta key: alt */ 421 + ((state & ControlMask) ? 16 : 0); 422 } 423 424 if (IS_SET(MODE_MOUSESGR)) { 425 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c", 426 code, x+1, y+1, 427 e->type == ButtonRelease ? 'm' : 'M'); 428 } else if (x < 223 && y < 223) { 429 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c", 430 32+code, 32+x+1, 32+y+1); 431 } else { 432 return; 433 } 434 435 ttywrite(buf, len, 0); 436 } 437 438 uint 439 buttonmask(uint button) 440 { 441 return button == Button1 ? Button1Mask 442 : button == Button2 ? Button2Mask 443 : button == Button3 ? Button3Mask 444 : button == Button4 ? Button4Mask 445 : button == Button5 ? Button5Mask 446 : 0; 447 } 448 449 int 450 mouseaction(XEvent *e, uint release) 451 { 452 MouseShortcut *ms; 453 454 /* ignore Button<N>mask for Button<N> - it's set on release */ 455 uint state = e->xbutton.state & ~buttonmask(e->xbutton.button); 456 457 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) { 458 if (ms->release == release && 459 ms->button == e->xbutton.button && 460 (match(ms->mod, state) || /* exact or forced */ 461 match(ms->mod, state & ~forcemousemod))) { 462 ms->func(&(ms->arg)); 463 return 1; 464 } 465 } 466 467 return 0; 468 } 469 470 void 471 bpress(XEvent *e) 472 { 473 int btn = e->xbutton.button; 474 struct timespec now; 475 int snap; 476 477 if (1 <= btn && btn <= 11) 478 buttons |= 1 << (btn-1); 479 480 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { 481 mousereport(e); 482 return; 483 } 484 485 if (mouseaction(e, 0)) 486 return; 487 488 if (btn == Button1) { 489 /* 490 * If the user clicks below predefined timeouts specific 491 * snapping behaviour is exposed. 492 */ 493 clock_gettime(CLOCK_MONOTONIC, &now); 494 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) { 495 snap = SNAP_LINE; 496 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) { 497 snap = SNAP_WORD; 498 } else { 499 snap = 0; 500 } 501 xsel.tclick2 = xsel.tclick1; 502 xsel.tclick1 = now; 503 504 selstart(evcol(e), evrow(e), snap); 505 } 506 } 507 508 void 509 propnotify(XEvent *e) 510 { 511 XPropertyEvent *xpev; 512 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); 513 514 xpev = &e->xproperty; 515 if (xpev->state == PropertyNewValue && 516 (xpev->atom == XA_PRIMARY || 517 xpev->atom == clipboard)) { 518 selnotify(e); 519 } 520 } 521 522 void 523 selnotify(XEvent *e) 524 { 525 ulong nitems, ofs, rem; 526 int format; 527 uchar *data, *last, *repl; 528 Atom type, incratom, property = None; 529 530 incratom = XInternAtom(xw.dpy, "INCR", 0); 531 532 ofs = 0; 533 if (e->type == SelectionNotify) 534 property = e->xselection.property; 535 else if (e->type == PropertyNotify) 536 property = e->xproperty.atom; 537 538 if (property == None) 539 return; 540 541 do { 542 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs, 543 BUFSIZ/4, False, AnyPropertyType, 544 &type, &format, &nitems, &rem, 545 &data)) { 546 fprintf(stderr, "Clipboard allocation failed\n"); 547 return; 548 } 549 550 if (e->type == PropertyNotify && nitems == 0 && rem == 0) { 551 /* 552 * If there is some PropertyNotify with no data, then 553 * this is the signal of the selection owner that all 554 * data has been transferred. We won't need to receive 555 * PropertyNotify events anymore. 556 */ 557 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask); 558 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, 559 &xw.attrs); 560 } 561 562 if (type == incratom) { 563 /* 564 * Activate the PropertyNotify events so we receive 565 * when the selection owner does send us the next 566 * chunk of data. 567 */ 568 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask); 569 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, 570 &xw.attrs); 571 572 /* 573 * Deleting the property is the transfer start signal. 574 */ 575 XDeleteProperty(xw.dpy, xw.win, (int)property); 576 continue; 577 } 578 579 /* 580 * As seen in getsel: 581 * Line endings are inconsistent in the terminal and GUI world 582 * copy and pasting. When receiving some selection data, 583 * replace all '\n' with '\r'. 584 * FIXME: Fix the computer world. 585 */ 586 repl = data; 587 last = data + nitems * format / 8; 588 while ((repl = memchr(repl, '\n', last - repl))) { 589 *repl++ = '\r'; 590 } 591 592 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0) 593 ttywrite("\033[200~", 6, 0); 594 ttywrite((char *)data, nitems * format / 8, 1); 595 if (IS_SET(MODE_BRCKTPASTE) && rem == 0) 596 ttywrite("\033[201~", 6, 0); 597 XFree(data); 598 /* number of 32-bit chunks returned */ 599 ofs += nitems * format / 32; 600 } while (rem > 0); 601 602 /* 603 * Deleting the property again tells the selection owner to send the 604 * next data chunk in the property. 605 */ 606 XDeleteProperty(xw.dpy, xw.win, (int)property); 607 } 608 609 void 610 xclipcopy(void) 611 { 612 clipcopy(NULL); 613 } 614 615 void 616 selclear_(XEvent *e) 617 { 618 selclear(); 619 } 620 621 void 622 selrequest(XEvent *e) 623 { 624 XSelectionRequestEvent *xsre; 625 XSelectionEvent xev; 626 Atom xa_targets, string, clipboard; 627 char *seltext; 628 629 xsre = (XSelectionRequestEvent *) e; 630 xev.type = SelectionNotify; 631 xev.requestor = xsre->requestor; 632 xev.selection = xsre->selection; 633 xev.target = xsre->target; 634 xev.time = xsre->time; 635 if (xsre->property == None) 636 xsre->property = xsre->target; 637 638 /* reject */ 639 xev.property = None; 640 641 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0); 642 if (xsre->target == xa_targets) { 643 /* respond with the supported type */ 644 string = xsel.xtarget; 645 XChangeProperty(xsre->display, xsre->requestor, xsre->property, 646 XA_ATOM, 32, PropModeReplace, 647 (uchar *) &string, 1); 648 xev.property = xsre->property; 649 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) { 650 /* 651 * xith XA_STRING non ascii characters may be incorrect in the 652 * requestor. It is not our problem, use utf8. 653 */ 654 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); 655 if (xsre->selection == XA_PRIMARY) { 656 seltext = xsel.primary; 657 } else if (xsre->selection == clipboard) { 658 seltext = xsel.clipboard; 659 } else { 660 fprintf(stderr, 661 "Unhandled clipboard selection 0x%lx\n", 662 xsre->selection); 663 return; 664 } 665 if (seltext != NULL) { 666 XChangeProperty(xsre->display, xsre->requestor, 667 xsre->property, xsre->target, 668 8, PropModeReplace, 669 (uchar *)seltext, strlen(seltext)); 670 xev.property = xsre->property; 671 } 672 } 673 674 /* all done, send a notification to the listener */ 675 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev)) 676 fprintf(stderr, "Error sending SelectionNotify event\n"); 677 } 678 679 void 680 setsel(char *str, Time t) 681 { 682 if (!str) 683 return; 684 685 free(xsel.primary); 686 xsel.primary = str; 687 688 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t); 689 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win) 690 selclear(); 691 } 692 693 void 694 xsetsel(char *str) 695 { 696 setsel(str, CurrentTime); 697 } 698 699 void 700 brelease(XEvent *e) 701 { 702 int btn = e->xbutton.button; 703 704 if (1 <= btn && btn <= 11) 705 buttons &= ~(1 << (btn-1)); 706 707 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { 708 mousereport(e); 709 return; 710 } 711 712 if (mouseaction(e, 1)) 713 return; 714 if (btn == Button1) 715 mousesel(e, 1); 716 } 717 718 void 719 bmotion(XEvent *e) 720 { 721 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { 722 mousereport(e); 723 return; 724 } 725 726 mousesel(e, 0); 727 } 728 729 void 730 cresize(int width, int height) 731 { 732 int col, row; 733 734 if (width != 0) 735 win.w = width; 736 if (height != 0) 737 win.h = height; 738 739 col = (win.w - 2 * borderpx) / win.cw; 740 row = (win.h - 2 * borderpx) / win.ch; 741 col = MAX(1, col); 742 row = MAX(1, row); 743 744 tresize(col, row); 745 xresize(col, row); 746 ttyresize(win.tw, win.th); 747 } 748 749 void 750 xresize(int col, int row) 751 { 752 win.tw = col * win.cw; 753 win.th = row * win.ch; 754 755 XFreePixmap(xw.dpy, xw.buf); 756 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, 757 xw.depth); 758 XftDrawChange(xw.draw, xw.buf); 759 xclear(0, 0, win.w, win.h); 760 761 /* resize to new width */ 762 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec)); 763 } 764 765 ushort 766 sixd_to_16bit(int x) 767 { 768 return x == 0 ? 0 : 0x3737 + 0x2828 * x; 769 } 770 771 int 772 xloadcolor(int i, const char *name, Color *ncolor) 773 { 774 XRenderColor color = { .alpha = 0xffff }; 775 776 if (!name) { 777 if (BETWEEN(i, 16, 255)) { /* 256 color */ 778 if (i < 6*6*6+16) { /* same colors as xterm */ 779 color.red = sixd_to_16bit( ((i-16)/36)%6 ); 780 color.green = sixd_to_16bit( ((i-16)/6) %6 ); 781 color.blue = sixd_to_16bit( ((i-16)/1) %6 ); 782 } else { /* greyscale */ 783 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16)); 784 color.green = color.blue = color.red; 785 } 786 return XftColorAllocValue(xw.dpy, xw.vis, 787 xw.cmap, &color, ncolor); 788 } else 789 name = colorname[i]; 790 } 791 792 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor); 793 } 794 795 void 796 xloadcols(void) 797 { 798 int i; 799 static int loaded; 800 Color *cp; 801 802 if (loaded) { 803 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp) 804 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp); 805 } else { 806 dc.collen = MAX(LEN(colorname), 256); 807 dc.col = xmalloc(dc.collen * sizeof(Color)); 808 } 809 810 for (i = 0; i < dc.collen; i++) 811 if (!xloadcolor(i, NULL, &dc.col[i])) { 812 if (colorname[i]) 813 die("could not allocate color '%s'\n", colorname[i]); 814 else 815 die("could not allocate color %d\n", i); 816 } 817 818 /* set alpha value of bg color */ 819 if (opt_alpha) 820 alpha = strtof(opt_alpha, NULL); 821 dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha); 822 dc.col[defaultbg].pixel &= 0x00FFFFFF; 823 dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24; 824 loaded = 1; 825 } 826 827 int 828 xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b) 829 { 830 if (!BETWEEN(x, 0, dc.collen)) 831 return 1; 832 833 *r = dc.col[x].color.red >> 8; 834 *g = dc.col[x].color.green >> 8; 835 *b = dc.col[x].color.blue >> 8; 836 837 return 0; 838 } 839 840 int 841 xsetcolorname(int x, const char *name) 842 { 843 Color ncolor; 844 845 if (!BETWEEN(x, 0, dc.collen)) 846 return 1; 847 848 if (!xloadcolor(x, name, &ncolor)) 849 return 1; 850 851 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]); 852 dc.col[x] = ncolor; 853 854 return 0; 855 } 856 857 /* 858 * Absolute coordinates. 859 */ 860 void 861 xclear(int x1, int y1, int x2, int y2) 862 { 863 XftDrawRect(xw.draw, 864 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg], 865 x1, y1, x2-x1, y2-y1); 866 } 867 868 void 869 xhints(void) 870 { 871 XClassHint class = {opt_name ? opt_name : termname, 872 opt_class ? opt_class : termname}; 873 XWMHints wm = {.flags = InputHint, .input = 1}; 874 XSizeHints *sizeh; 875 876 sizeh = XAllocSizeHints(); 877 878 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize; 879 sizeh->height = win.h; 880 sizeh->width = win.w; 881 sizeh->height_inc = win.ch; 882 sizeh->width_inc = win.cw; 883 sizeh->base_height = 2 * borderpx; 884 sizeh->base_width = 2 * borderpx; 885 sizeh->min_height = win.ch + 2 * borderpx; 886 sizeh->min_width = win.cw + 2 * borderpx; 887 if (xw.isfixed) { 888 sizeh->flags |= PMaxSize; 889 sizeh->min_width = sizeh->max_width = win.w; 890 sizeh->min_height = sizeh->max_height = win.h; 891 } 892 if (xw.gm & (XValue|YValue)) { 893 sizeh->flags |= USPosition | PWinGravity; 894 sizeh->x = xw.l; 895 sizeh->y = xw.t; 896 sizeh->win_gravity = xgeommasktogravity(xw.gm); 897 } 898 899 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, 900 &class); 901 XFree(sizeh); 902 } 903 904 int 905 xgeommasktogravity(int mask) 906 { 907 switch (mask & (XNegative|YNegative)) { 908 case 0: 909 return NorthWestGravity; 910 case XNegative: 911 return NorthEastGravity; 912 case YNegative: 913 return SouthWestGravity; 914 } 915 916 return SouthEastGravity; 917 } 918 919 int 920 xloadfont(Font *f, FcPattern *pattern) 921 { 922 FcPattern *configured; 923 FcPattern *match; 924 FcResult result; 925 XGlyphInfo extents; 926 int wantattr, haveattr; 927 928 /* 929 * Manually configure instead of calling XftMatchFont 930 * so that we can use the configured pattern for 931 * "missing glyph" lookups. 932 */ 933 configured = FcPatternDuplicate(pattern); 934 if (!configured) 935 return 1; 936 937 FcConfigSubstitute(NULL, configured, FcMatchPattern); 938 XftDefaultSubstitute(xw.dpy, xw.scr, configured); 939 940 match = FcFontMatch(NULL, configured, &result); 941 if (!match) { 942 FcPatternDestroy(configured); 943 return 1; 944 } 945 946 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) { 947 FcPatternDestroy(configured); 948 FcPatternDestroy(match); 949 return 1; 950 } 951 952 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) == 953 XftResultMatch)) { 954 /* 955 * Check if xft was unable to find a font with the appropriate 956 * slant but gave us one anyway. Try to mitigate. 957 */ 958 if ((XftPatternGetInteger(f->match->pattern, "slant", 0, 959 &haveattr) != XftResultMatch) || haveattr < wantattr) { 960 f->badslant = 1; 961 fputs("font slant does not match\n", stderr); 962 } 963 } 964 965 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) == 966 XftResultMatch)) { 967 if ((XftPatternGetInteger(f->match->pattern, "weight", 0, 968 &haveattr) != XftResultMatch) || haveattr != wantattr) { 969 f->badweight = 1; 970 fputs("font weight does not match\n", stderr); 971 } 972 } 973 974 XftTextExtentsUtf8(xw.dpy, f->match, 975 (const FcChar8 *) ascii_printable, 976 strlen(ascii_printable), &extents); 977 978 f->set = NULL; 979 f->pattern = configured; 980 981 f->ascent = f->match->ascent; 982 f->descent = f->match->descent; 983 f->lbearing = 0; 984 f->rbearing = f->match->max_advance_width; 985 986 f->height = f->ascent + f->descent; 987 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable)); 988 989 return 0; 990 } 991 992 void 993 xloadfonts(const char *fontstr, double fontsize) 994 { 995 FcPattern *pattern; 996 double fontval; 997 998 if (fontstr[0] == '-') 999 pattern = XftXlfdParse(fontstr, False, False); 1000 else 1001 pattern = FcNameParse((const FcChar8 *)fontstr); 1002 1003 if (!pattern) 1004 die("can't open font %s\n", fontstr); 1005 1006 if (fontsize > 1) { 1007 FcPatternDel(pattern, FC_PIXEL_SIZE); 1008 FcPatternDel(pattern, FC_SIZE); 1009 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize); 1010 usedfontsize = fontsize; 1011 } else { 1012 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) == 1013 FcResultMatch) { 1014 usedfontsize = fontval; 1015 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) == 1016 FcResultMatch) { 1017 usedfontsize = -1; 1018 } else { 1019 /* 1020 * Default font size is 12, if none given. This is to 1021 * have a known usedfontsize value. 1022 */ 1023 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12); 1024 usedfontsize = 12; 1025 } 1026 defaultfontsize = usedfontsize; 1027 } 1028 1029 if (xloadfont(&dc.font, pattern)) 1030 die("can't open font %s\n", fontstr); 1031 1032 if (usedfontsize < 0) { 1033 FcPatternGetDouble(dc.font.match->pattern, 1034 FC_PIXEL_SIZE, 0, &fontval); 1035 usedfontsize = fontval; 1036 if (fontsize == 0) 1037 defaultfontsize = fontval; 1038 } 1039 1040 /* Setting character width and height. */ 1041 win.cw = ceilf(dc.font.width * cwscale); 1042 win.ch = ceilf(dc.font.height * chscale); 1043 1044 FcPatternDel(pattern, FC_SLANT); 1045 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC); 1046 if (xloadfont(&dc.ifont, pattern)) 1047 die("can't open font %s\n", fontstr); 1048 1049 FcPatternDel(pattern, FC_WEIGHT); 1050 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD); 1051 if (xloadfont(&dc.ibfont, pattern)) 1052 die("can't open font %s\n", fontstr); 1053 1054 FcPatternDel(pattern, FC_SLANT); 1055 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN); 1056 if (xloadfont(&dc.bfont, pattern)) 1057 die("can't open font %s\n", fontstr); 1058 1059 FcPatternDestroy(pattern); 1060 } 1061 1062 void 1063 xunloadfont(Font *f) 1064 { 1065 XftFontClose(xw.dpy, f->match); 1066 FcPatternDestroy(f->pattern); 1067 if (f->set) 1068 FcFontSetDestroy(f->set); 1069 } 1070 1071 void 1072 xunloadfonts(void) 1073 { 1074 /* Free the loaded fonts in the font cache. */ 1075 while (frclen > 0) 1076 XftFontClose(xw.dpy, frc[--frclen].font); 1077 1078 xunloadfont(&dc.font); 1079 xunloadfont(&dc.bfont); 1080 xunloadfont(&dc.ifont); 1081 xunloadfont(&dc.ibfont); 1082 } 1083 1084 int 1085 ximopen(Display *dpy) 1086 { 1087 XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy }; 1088 XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy }; 1089 1090 xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL); 1091 if (xw.ime.xim == NULL) 1092 return 0; 1093 1094 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL)) 1095 fprintf(stderr, "XSetIMValues: " 1096 "Could not set XNDestroyCallback.\n"); 1097 1098 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot, 1099 NULL); 1100 1101 if (xw.ime.xic == NULL) { 1102 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle, 1103 XIMPreeditNothing | XIMStatusNothing, 1104 XNClientWindow, xw.win, 1105 XNDestroyCallback, &icdestroy, 1106 NULL); 1107 } 1108 if (xw.ime.xic == NULL) 1109 fprintf(stderr, "XCreateIC: Could not create input context.\n"); 1110 1111 return 1; 1112 } 1113 1114 void 1115 ximinstantiate(Display *dpy, XPointer client, XPointer call) 1116 { 1117 if (ximopen(dpy)) 1118 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, 1119 ximinstantiate, NULL); 1120 } 1121 1122 void 1123 ximdestroy(XIM xim, XPointer client, XPointer call) 1124 { 1125 xw.ime.xim = NULL; 1126 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, 1127 ximinstantiate, NULL); 1128 XFree(xw.ime.spotlist); 1129 } 1130 1131 int 1132 xicdestroy(XIC xim, XPointer client, XPointer call) 1133 { 1134 xw.ime.xic = NULL; 1135 return 1; 1136 } 1137 1138 void 1139 xinit(int cols, int rows) 1140 { 1141 XGCValues gcvalues; 1142 Cursor cursor; 1143 Window parent; 1144 pid_t thispid = getpid(); 1145 XColor xmousefg, xmousebg; 1146 XWindowAttributes attr; 1147 XVisualInfo vis; 1148 1149 if (!(xw.dpy = XOpenDisplay(NULL))) 1150 die("can't open display\n"); 1151 xw.scr = XDefaultScreen(xw.dpy); 1152 1153 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) { 1154 parent = XRootWindow(xw.dpy, xw.scr); 1155 xw.depth = 32; 1156 } else { 1157 XGetWindowAttributes(xw.dpy, parent, &attr); 1158 xw.depth = attr.depth; 1159 } 1160 1161 XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis); 1162 xw.vis = vis.visual; 1163 1164 /* font */ 1165 if (!FcInit()) 1166 die("could not init fontconfig.\n"); 1167 1168 usedfont = (opt_font == NULL)? font : opt_font; 1169 xloadfonts(usedfont, 0); 1170 1171 /* colors */ 1172 xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None); 1173 xloadcols(); 1174 1175 /* adjust fixed window geometry */ 1176 win.w = 2 * borderpx + cols * win.cw; 1177 win.h = 2 * borderpx + rows * win.ch; 1178 if (xw.gm & XNegative) 1179 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2; 1180 if (xw.gm & YNegative) 1181 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2; 1182 1183 /* Events */ 1184 xw.attrs.background_pixel = dc.col[defaultbg].pixel; 1185 xw.attrs.border_pixel = dc.col[defaultbg].pixel; 1186 xw.attrs.bit_gravity = NorthWestGravity; 1187 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask 1188 | ExposureMask | VisibilityChangeMask | StructureNotifyMask 1189 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask; 1190 xw.attrs.colormap = xw.cmap; 1191 1192 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t, 1193 win.w, win.h, 0, xw.depth, InputOutput, 1194 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity 1195 | CWEventMask | CWColormap, &xw.attrs); 1196 1197 memset(&gcvalues, 0, sizeof(gcvalues)); 1198 gcvalues.graphics_exposures = False; 1199 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth); 1200 dc.gc = XCreateGC(xw.dpy, xw.buf, GCGraphicsExposures, &gcvalues); 1201 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel); 1202 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h); 1203 1204 /* font spec buffer */ 1205 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec)); 1206 1207 /* Xft rendering context */ 1208 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap); 1209 1210 /* input methods */ 1211 if (!ximopen(xw.dpy)) { 1212 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, 1213 ximinstantiate, NULL); 1214 } 1215 1216 /* white cursor, black outline */ 1217 cursor = XCreateFontCursor(xw.dpy, mouseshape); 1218 XDefineCursor(xw.dpy, xw.win, cursor); 1219 1220 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) { 1221 xmousefg.red = 0xffff; 1222 xmousefg.green = 0xffff; 1223 xmousefg.blue = 0xffff; 1224 } 1225 1226 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) { 1227 xmousebg.red = 0x0000; 1228 xmousebg.green = 0x0000; 1229 xmousebg.blue = 0x0000; 1230 } 1231 1232 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg); 1233 1234 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False); 1235 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False); 1236 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False); 1237 xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False); 1238 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1); 1239 1240 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False); 1241 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32, 1242 PropModeReplace, (uchar *)&thispid, 1); 1243 1244 win.mode = MODE_NUMLOCK; 1245 resettitle(); 1246 xhints(); 1247 XMapWindow(xw.dpy, xw.win); 1248 XSync(xw.dpy, False); 1249 1250 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1); 1251 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2); 1252 xsel.primary = NULL; 1253 xsel.clipboard = NULL; 1254 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0); 1255 if (xsel.xtarget == None) 1256 xsel.xtarget = XA_STRING; 1257 } 1258 1259 int 1260 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y) 1261 { 1262 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp; 1263 ushort mode, prevmode = USHRT_MAX; 1264 Font *font = &dc.font; 1265 int frcflags = FRC_NORMAL; 1266 float runewidth = win.cw; 1267 Rune rune; 1268 FT_UInt glyphidx; 1269 FcResult fcres; 1270 FcPattern *fcpattern, *fontpattern; 1271 FcFontSet *fcsets[] = { NULL }; 1272 FcCharSet *fccharset; 1273 int i, f, numspecs = 0; 1274 1275 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) { 1276 /* Fetch rune and mode for current glyph. */ 1277 rune = glyphs[i].u; 1278 mode = glyphs[i].mode; 1279 1280 /* Skip dummy wide-character spacing. */ 1281 if (mode == ATTR_WDUMMY) 1282 continue; 1283 1284 /* Determine font for glyph if different from previous glyph. */ 1285 if (prevmode != mode) { 1286 prevmode = mode; 1287 font = &dc.font; 1288 frcflags = FRC_NORMAL; 1289 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f); 1290 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) { 1291 font = &dc.ibfont; 1292 frcflags = FRC_ITALICBOLD; 1293 } else if (mode & ATTR_ITALIC) { 1294 font = &dc.ifont; 1295 frcflags = FRC_ITALIC; 1296 } else if (mode & ATTR_BOLD) { 1297 font = &dc.bfont; 1298 frcflags = FRC_BOLD; 1299 } 1300 yp = winy + font->ascent; 1301 } 1302 1303 /* Lookup character index with default font. */ 1304 glyphidx = XftCharIndex(xw.dpy, font->match, rune); 1305 if (glyphidx) { 1306 specs[numspecs].font = font->match; 1307 specs[numspecs].glyph = glyphidx; 1308 specs[numspecs].x = (short)xp; 1309 specs[numspecs].y = (short)yp; 1310 xp += runewidth; 1311 numspecs++; 1312 continue; 1313 } 1314 1315 /* Fallback on font cache, search the font cache for match. */ 1316 for (f = 0; f < frclen; f++) { 1317 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune); 1318 /* Everything correct. */ 1319 if (glyphidx && frc[f].flags == frcflags) 1320 break; 1321 /* We got a default font for a not found glyph. */ 1322 if (!glyphidx && frc[f].flags == frcflags 1323 && frc[f].unicodep == rune) { 1324 break; 1325 } 1326 } 1327 1328 /* Nothing was found. Use fontconfig to find matching font. */ 1329 if (f >= frclen) { 1330 if (!font->set) 1331 font->set = FcFontSort(0, font->pattern, 1332 1, 0, &fcres); 1333 fcsets[0] = font->set; 1334 1335 /* 1336 * Nothing was found in the cache. Now use 1337 * some dozen of Fontconfig calls to get the 1338 * font for one single character. 1339 * 1340 * Xft and fontconfig are design failures. 1341 */ 1342 fcpattern = FcPatternDuplicate(font->pattern); 1343 fccharset = FcCharSetCreate(); 1344 1345 FcCharSetAddChar(fccharset, rune); 1346 FcPatternAddCharSet(fcpattern, FC_CHARSET, 1347 fccharset); 1348 FcPatternAddBool(fcpattern, FC_SCALABLE, 1); 1349 1350 FcConfigSubstitute(0, fcpattern, 1351 FcMatchPattern); 1352 FcDefaultSubstitute(fcpattern); 1353 1354 fontpattern = FcFontSetMatch(0, fcsets, 1, 1355 fcpattern, &fcres); 1356 1357 /* Allocate memory for the new cache entry. */ 1358 if (frclen >= frccap) { 1359 frccap += 16; 1360 frc = xrealloc(frc, frccap * sizeof(Fontcache)); 1361 } 1362 1363 frc[frclen].font = XftFontOpenPattern(xw.dpy, 1364 fontpattern); 1365 if (!frc[frclen].font) 1366 die("XftFontOpenPattern failed seeking fallback font: %s\n", 1367 strerror(errno)); 1368 frc[frclen].flags = frcflags; 1369 frc[frclen].unicodep = rune; 1370 1371 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune); 1372 1373 f = frclen; 1374 frclen++; 1375 1376 FcPatternDestroy(fcpattern); 1377 FcCharSetDestroy(fccharset); 1378 } 1379 1380 specs[numspecs].font = frc[f].font; 1381 specs[numspecs].glyph = glyphidx; 1382 specs[numspecs].x = (short)xp; 1383 specs[numspecs].y = (short)yp; 1384 xp += runewidth; 1385 numspecs++; 1386 } 1387 1388 return numspecs; 1389 } 1390 1391 void 1392 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y) 1393 { 1394 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1); 1395 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, 1396 width = charlen * win.cw; 1397 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg; 1398 XRenderColor colfg, colbg; 1399 XRectangle r; 1400 1401 /* Fallback on color display for attributes not supported by the font */ 1402 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) { 1403 if (dc.ibfont.badslant || dc.ibfont.badweight) 1404 base.fg = defaultattr; 1405 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) || 1406 (base.mode & ATTR_BOLD && dc.bfont.badweight)) { 1407 base.fg = defaultattr; 1408 } 1409 1410 if (IS_TRUECOL(base.fg)) { 1411 colfg.alpha = 0xffff; 1412 colfg.red = TRUERED(base.fg); 1413 colfg.green = TRUEGREEN(base.fg); 1414 colfg.blue = TRUEBLUE(base.fg); 1415 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg); 1416 fg = &truefg; 1417 } else { 1418 fg = &dc.col[base.fg]; 1419 } 1420 1421 if (IS_TRUECOL(base.bg)) { 1422 colbg.alpha = 0xffff; 1423 colbg.green = TRUEGREEN(base.bg); 1424 colbg.red = TRUERED(base.bg); 1425 colbg.blue = TRUEBLUE(base.bg); 1426 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg); 1427 bg = &truebg; 1428 } else { 1429 bg = &dc.col[base.bg]; 1430 } 1431 1432 /* Change basic system colors [0-7] to bright system colors [8-15] */ 1433 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7)) 1434 fg = &dc.col[base.fg + 8]; 1435 1436 if (IS_SET(MODE_REVERSE)) { 1437 if (fg == &dc.col[defaultfg]) { 1438 fg = &dc.col[defaultbg]; 1439 } else { 1440 colfg.red = ~fg->color.red; 1441 colfg.green = ~fg->color.green; 1442 colfg.blue = ~fg->color.blue; 1443 colfg.alpha = fg->color.alpha; 1444 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, 1445 &revfg); 1446 fg = &revfg; 1447 } 1448 1449 if (bg == &dc.col[defaultbg]) { 1450 bg = &dc.col[defaultfg]; 1451 } else { 1452 colbg.red = ~bg->color.red; 1453 colbg.green = ~bg->color.green; 1454 colbg.blue = ~bg->color.blue; 1455 colbg.alpha = bg->color.alpha; 1456 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, 1457 &revbg); 1458 bg = &revbg; 1459 } 1460 } 1461 1462 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) { 1463 colfg.red = fg->color.red / 2; 1464 colfg.green = fg->color.green / 2; 1465 colfg.blue = fg->color.blue / 2; 1466 colfg.alpha = fg->color.alpha; 1467 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg); 1468 fg = &revfg; 1469 } 1470 1471 if (base.mode & ATTR_REVERSE) { 1472 temp = fg; 1473 fg = bg; 1474 bg = temp; 1475 } 1476 1477 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK) 1478 fg = bg; 1479 1480 if (base.mode & ATTR_INVISIBLE) 1481 fg = bg; 1482 1483 /* Intelligent cleaning up of the borders. */ 1484 if (x == 0) { 1485 xclear(0, (y == 0)? 0 : winy, borderpx, 1486 winy + win.ch + 1487 ((winy + win.ch >= borderpx + win.th)? win.h : 0)); 1488 } 1489 if (winx + width >= borderpx + win.tw) { 1490 xclear(winx + width, (y == 0)? 0 : winy, win.w, 1491 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch))); 1492 } 1493 if (y == 0) 1494 xclear(winx, 0, winx + width, borderpx); 1495 if (winy + win.ch >= borderpx + win.th) 1496 xclear(winx, winy + win.ch, winx + width, win.h); 1497 1498 /* Clean up the region we want to draw to. */ 1499 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch); 1500 1501 /* Set the clip region because Xft is sometimes dirty. */ 1502 r.x = 0; 1503 r.y = 0; 1504 r.height = win.ch; 1505 r.width = width; 1506 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1); 1507 1508 /* Render the glyphs. */ 1509 XftDrawGlyphFontSpec(xw.draw, fg, specs, len); 1510 1511 /* Render underline and strikethrough. */ 1512 if (base.mode & ATTR_UNDERLINE) { 1513 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1, 1514 width, 1); 1515 } 1516 1517 if (base.mode & ATTR_STRUCK) { 1518 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3, 1519 width, 1); 1520 } 1521 1522 /* Reset clip to none. */ 1523 XftDrawSetClip(xw.draw, 0); 1524 } 1525 1526 void 1527 xdrawglyph(Glyph g, int x, int y) 1528 { 1529 int numspecs; 1530 XftGlyphFontSpec spec; 1531 1532 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y); 1533 xdrawglyphfontspecs(&spec, g, numspecs, x, y); 1534 } 1535 1536 void 1537 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og) 1538 { 1539 Color drawcol; 1540 1541 /* remove the old cursor */ 1542 if (selected(ox, oy)) 1543 og.mode ^= ATTR_REVERSE; 1544 xdrawglyph(og, ox, oy); 1545 1546 if (IS_SET(MODE_HIDE)) 1547 return; 1548 1549 /* 1550 * Select the right color for the right mode. 1551 */ 1552 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE; 1553 1554 if (IS_SET(MODE_REVERSE)) { 1555 g.mode |= ATTR_REVERSE; 1556 g.bg = defaultfg; 1557 if (selected(cx, cy)) { 1558 drawcol = dc.col[defaultcs]; 1559 g.fg = defaultrcs; 1560 } else { 1561 drawcol = dc.col[defaultrcs]; 1562 g.fg = defaultcs; 1563 } 1564 } else { 1565 if (selected(cx, cy)) { 1566 g.fg = defaultfg; 1567 g.bg = defaultrcs; 1568 } else { 1569 g.fg = defaultbg; 1570 g.bg = defaultcs; 1571 } 1572 drawcol = dc.col[g.bg]; 1573 } 1574 1575 /* draw the new one */ 1576 if (IS_SET(MODE_FOCUSED)) { 1577 switch (win.cursor) { 1578 case 7: /* st extension */ 1579 g.u = 0x2603; /* snowman (U+2603) */ 1580 /* FALLTHROUGH */ 1581 case 0: /* Blinking Block */ 1582 case 1: /* Blinking Block (Default) */ 1583 case 2: /* Steady Block */ 1584 xdrawglyph(g, cx, cy); 1585 break; 1586 case 3: /* Blinking Underline */ 1587 case 4: /* Steady Underline */ 1588 XftDrawRect(xw.draw, &drawcol, 1589 borderpx + cx * win.cw, 1590 borderpx + (cy + 1) * win.ch - \ 1591 cursorthickness, 1592 win.cw, cursorthickness); 1593 break; 1594 case 5: /* Blinking bar */ 1595 case 6: /* Steady bar */ 1596 XftDrawRect(xw.draw, &drawcol, 1597 borderpx + cx * win.cw, 1598 borderpx + cy * win.ch, 1599 cursorthickness, win.ch); 1600 break; 1601 } 1602 } else { 1603 XftDrawRect(xw.draw, &drawcol, 1604 borderpx + cx * win.cw, 1605 borderpx + cy * win.ch, 1606 win.cw - 1, 1); 1607 XftDrawRect(xw.draw, &drawcol, 1608 borderpx + cx * win.cw, 1609 borderpx + cy * win.ch, 1610 1, win.ch - 1); 1611 XftDrawRect(xw.draw, &drawcol, 1612 borderpx + (cx + 1) * win.cw - 1, 1613 borderpx + cy * win.ch, 1614 1, win.ch - 1); 1615 XftDrawRect(xw.draw, &drawcol, 1616 borderpx + cx * win.cw, 1617 borderpx + (cy + 1) * win.ch - 1, 1618 win.cw, 1); 1619 } 1620 } 1621 1622 void 1623 xsetenv(void) 1624 { 1625 char buf[sizeof(long) * 8 + 1]; 1626 1627 snprintf(buf, sizeof(buf), "%lu", xw.win); 1628 setenv("WINDOWID", buf, 1); 1629 } 1630 1631 void 1632 xseticontitle(char *p) 1633 { 1634 XTextProperty prop; 1635 DEFAULT(p, opt_title); 1636 1637 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle, 1638 &prop) != Success) 1639 return; 1640 XSetWMIconName(xw.dpy, xw.win, &prop); 1641 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname); 1642 XFree(prop.value); 1643 } 1644 1645 void 1646 xsettitle(char *p) 1647 { 1648 XTextProperty prop; 1649 DEFAULT(p, opt_title); 1650 1651 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle, 1652 &prop) != Success) 1653 return; 1654 XSetWMName(xw.dpy, xw.win, &prop); 1655 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname); 1656 XFree(prop.value); 1657 } 1658 1659 int 1660 xstartdraw(void) 1661 { 1662 return IS_SET(MODE_VISIBLE); 1663 } 1664 1665 void 1666 xdrawline(Line line, int x1, int y1, int x2) 1667 { 1668 int i, x, ox, numspecs; 1669 Glyph base, new; 1670 XftGlyphFontSpec *specs = xw.specbuf; 1671 1672 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1); 1673 i = ox = 0; 1674 for (x = x1; x < x2 && i < numspecs; x++) { 1675 new = line[x]; 1676 if (new.mode == ATTR_WDUMMY) 1677 continue; 1678 if (selected(x, y1)) 1679 new.mode ^= ATTR_REVERSE; 1680 if (i > 0 && ATTRCMP(base, new)) { 1681 xdrawglyphfontspecs(specs, base, i, ox, y1); 1682 specs += i; 1683 numspecs -= i; 1684 i = 0; 1685 } 1686 if (i == 0) { 1687 ox = x; 1688 base = new; 1689 } 1690 i++; 1691 } 1692 if (i > 0) 1693 xdrawglyphfontspecs(specs, base, i, ox, y1); 1694 } 1695 1696 void 1697 xfinishdraw(void) 1698 { 1699 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w, 1700 win.h, 0, 0); 1701 XSetForeground(xw.dpy, dc.gc, 1702 dc.col[IS_SET(MODE_REVERSE)? 1703 defaultfg : defaultbg].pixel); 1704 } 1705 1706 void 1707 xximspot(int x, int y) 1708 { 1709 if (xw.ime.xic == NULL) 1710 return; 1711 1712 xw.ime.spot.x = borderpx + x * win.cw; 1713 xw.ime.spot.y = borderpx + (y + 1) * win.ch; 1714 1715 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL); 1716 } 1717 1718 void 1719 expose(XEvent *ev) 1720 { 1721 redraw(); 1722 } 1723 1724 void 1725 visibility(XEvent *ev) 1726 { 1727 XVisibilityEvent *e = &ev->xvisibility; 1728 1729 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE); 1730 } 1731 1732 void 1733 unmap(XEvent *ev) 1734 { 1735 win.mode &= ~MODE_VISIBLE; 1736 } 1737 1738 void 1739 xsetpointermotion(int set) 1740 { 1741 MODBIT(xw.attrs.event_mask, set, PointerMotionMask); 1742 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); 1743 } 1744 1745 void 1746 xsetmode(int set, unsigned int flags) 1747 { 1748 int mode = win.mode; 1749 MODBIT(win.mode, set, flags); 1750 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE)) 1751 redraw(); 1752 } 1753 1754 int 1755 xsetcursor(int cursor) 1756 { 1757 if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */ 1758 return 1; 1759 win.cursor = cursor; 1760 return 0; 1761 } 1762 1763 void 1764 xseturgency(int add) 1765 { 1766 XWMHints *h = XGetWMHints(xw.dpy, xw.win); 1767 1768 MODBIT(h->flags, add, XUrgencyHint); 1769 XSetWMHints(xw.dpy, xw.win, h); 1770 XFree(h); 1771 } 1772 1773 void 1774 xbell(void) 1775 { 1776 if (!(IS_SET(MODE_FOCUSED))) 1777 xseturgency(1); 1778 if (bellvolume) 1779 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL); 1780 } 1781 1782 void 1783 focus(XEvent *ev) 1784 { 1785 XFocusChangeEvent *e = &ev->xfocus; 1786 1787 if (e->mode == NotifyGrab) 1788 return; 1789 1790 if (ev->type == FocusIn) { 1791 if (xw.ime.xic) 1792 XSetICFocus(xw.ime.xic); 1793 win.mode |= MODE_FOCUSED; 1794 xseturgency(0); 1795 if (IS_SET(MODE_FOCUS)) 1796 ttywrite("\033[I", 3, 0); 1797 } else { 1798 if (xw.ime.xic) 1799 XUnsetICFocus(xw.ime.xic); 1800 win.mode &= ~MODE_FOCUSED; 1801 if (IS_SET(MODE_FOCUS)) 1802 ttywrite("\033[O", 3, 0); 1803 } 1804 } 1805 1806 int 1807 match(uint mask, uint state) 1808 { 1809 return mask == XK_ANY_MOD || mask == (state & ~ignoremod); 1810 } 1811 1812 char* 1813 kmap(KeySym k, uint state) 1814 { 1815 Key *kp; 1816 int i; 1817 1818 /* Check for mapped keys out of X11 function keys. */ 1819 for (i = 0; i < LEN(mappedkeys); i++) { 1820 if (mappedkeys[i] == k) 1821 break; 1822 } 1823 if (i == LEN(mappedkeys)) { 1824 if ((k & 0xFFFF) < 0xFD00) 1825 return NULL; 1826 } 1827 1828 for (kp = key; kp < key + LEN(key); kp++) { 1829 if (kp->k != k) 1830 continue; 1831 1832 if (!match(kp->mask, state)) 1833 continue; 1834 1835 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0) 1836 continue; 1837 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2) 1838 continue; 1839 1840 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0) 1841 continue; 1842 1843 return kp->s; 1844 } 1845 1846 return NULL; 1847 } 1848 1849 void 1850 kpress(XEvent *ev) 1851 { 1852 XKeyEvent *e = &ev->xkey; 1853 KeySym ksym; 1854 char buf[64], *customkey; 1855 int len; 1856 Rune c; 1857 Status status; 1858 Shortcut *bp; 1859 1860 if (IS_SET(MODE_KBDLOCK)) 1861 return; 1862 1863 if (xw.ime.xic) 1864 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status); 1865 else 1866 len = XLookupString(e, buf, sizeof buf, &ksym, NULL); 1867 /* 1. shortcuts */ 1868 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) { 1869 if (ksym == bp->keysym && match(bp->mod, e->state)) { 1870 bp->func(&(bp->arg)); 1871 return; 1872 } 1873 } 1874 1875 /* 2. custom keys from config.h */ 1876 if ((customkey = kmap(ksym, e->state))) { 1877 ttywrite(customkey, strlen(customkey), 1); 1878 return; 1879 } 1880 1881 /* 3. composed string from input method */ 1882 if (len == 0) 1883 return; 1884 if (len == 1 && e->state & Mod1Mask) { 1885 if (IS_SET(MODE_8BIT)) { 1886 if (*buf < 0177) { 1887 c = *buf | 0x80; 1888 len = utf8encode(c, buf); 1889 } 1890 } else { 1891 buf[1] = buf[0]; 1892 buf[0] = '\033'; 1893 len = 2; 1894 } 1895 } 1896 ttywrite(buf, len, 1); 1897 } 1898 1899 void 1900 cmessage(XEvent *e) 1901 { 1902 /* 1903 * See xembed specs 1904 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html 1905 */ 1906 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) { 1907 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) { 1908 win.mode |= MODE_FOCUSED; 1909 xseturgency(0); 1910 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) { 1911 win.mode &= ~MODE_FOCUSED; 1912 } 1913 } else if (e->xclient.data.l[0] == xw.wmdeletewin) { 1914 ttyhangup(); 1915 exit(0); 1916 } 1917 } 1918 1919 void 1920 resize(XEvent *e) 1921 { 1922 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h) 1923 return; 1924 1925 cresize(e->xconfigure.width, e->xconfigure.height); 1926 } 1927 1928 void 1929 run(void) 1930 { 1931 XEvent ev; 1932 int w = win.w, h = win.h; 1933 fd_set rfd; 1934 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing; 1935 struct timespec seltv, *tv, now, lastblink, trigger; 1936 double timeout; 1937 1938 /* Waiting for window mapping */ 1939 do { 1940 XNextEvent(xw.dpy, &ev); 1941 /* 1942 * This XFilterEvent call is required because of XOpenIM. It 1943 * does filter out the key event and some client message for 1944 * the input method too. 1945 */ 1946 if (XFilterEvent(&ev, None)) 1947 continue; 1948 if (ev.type == ConfigureNotify) { 1949 w = ev.xconfigure.width; 1950 h = ev.xconfigure.height; 1951 } 1952 } while (ev.type != MapNotify); 1953 1954 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd); 1955 cresize(w, h); 1956 1957 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) { 1958 FD_ZERO(&rfd); 1959 FD_SET(ttyfd, &rfd); 1960 FD_SET(xfd, &rfd); 1961 1962 if (XPending(xw.dpy)) 1963 timeout = 0; /* existing events might not set xfd */ 1964 1965 seltv.tv_sec = timeout / 1E3; 1966 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec); 1967 tv = timeout >= 0 ? &seltv : NULL; 1968 1969 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) { 1970 if (errno == EINTR) 1971 continue; 1972 die("select failed: %s\n", strerror(errno)); 1973 } 1974 clock_gettime(CLOCK_MONOTONIC, &now); 1975 1976 if (FD_ISSET(ttyfd, &rfd)) 1977 ttyread(); 1978 1979 xev = 0; 1980 while (XPending(xw.dpy)) { 1981 xev = 1; 1982 XNextEvent(xw.dpy, &ev); 1983 if (XFilterEvent(&ev, None)) 1984 continue; 1985 if (handler[ev.type]) 1986 (handler[ev.type])(&ev); 1987 } 1988 1989 /* 1990 * To reduce flicker and tearing, when new content or event 1991 * triggers drawing, we first wait a bit to ensure we got 1992 * everything, and if nothing new arrives - we draw. 1993 * We start with trying to wait minlatency ms. If more content 1994 * arrives sooner, we retry with shorter and shorter periods, 1995 * and eventually draw even without idle after maxlatency ms. 1996 * Typically this results in low latency while interacting, 1997 * maximum latency intervals during `cat huge.txt`, and perfect 1998 * sync with periodic updates from animations/key-repeats/etc. 1999 */ 2000 if (FD_ISSET(ttyfd, &rfd) || xev) { 2001 if (!drawing) { 2002 trigger = now; 2003 drawing = 1; 2004 } 2005 timeout = (maxlatency - TIMEDIFF(now, trigger)) \ 2006 / maxlatency * minlatency; 2007 if (timeout > 0) 2008 continue; /* we have time, try to find idle */ 2009 } 2010 2011 /* idle detected or maxlatency exhausted -> draw */ 2012 timeout = -1; 2013 if (blinktimeout && tattrset(ATTR_BLINK)) { 2014 timeout = blinktimeout - TIMEDIFF(now, lastblink); 2015 if (timeout <= 0) { 2016 if (-timeout > blinktimeout) /* start visible */ 2017 win.mode |= MODE_BLINK; 2018 win.mode ^= MODE_BLINK; 2019 tsetdirtattr(ATTR_BLINK); 2020 lastblink = now; 2021 timeout = blinktimeout; 2022 } 2023 } 2024 2025 draw(); 2026 XFlush(xw.dpy); 2027 drawing = 0; 2028 } 2029 } 2030 2031 void 2032 usage(void) 2033 { 2034 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]" 2035 " [-n name] [-o file]\n" 2036 " [-T title] [-t title] [-w windowid]" 2037 " [[-e] command [args ...]]\n" 2038 " %s [-aiv] [-c class] [-f font] [-g geometry]" 2039 " [-n name] [-o file]\n" 2040 " [-T title] [-t title] [-w windowid] -l line" 2041 " [stty_args ...]\n", argv0, argv0); 2042 } 2043 2044 int 2045 main(int argc, char *argv[]) 2046 { 2047 xw.l = xw.t = 0; 2048 xw.isfixed = False; 2049 xsetcursor(cursorshape); 2050 2051 ARGBEGIN { 2052 case 'a': 2053 allowaltscreen = 0; 2054 break; 2055 case 'A': 2056 opt_alpha = EARGF(usage()); 2057 break; 2058 case 'c': 2059 opt_class = EARGF(usage()); 2060 break; 2061 case 'e': 2062 if (argc > 0) 2063 --argc, ++argv; 2064 goto run; 2065 case 'f': 2066 opt_font = EARGF(usage()); 2067 break; 2068 case 'g': 2069 xw.gm = XParseGeometry(EARGF(usage()), 2070 &xw.l, &xw.t, &cols, &rows); 2071 break; 2072 case 'i': 2073 xw.isfixed = 1; 2074 break; 2075 case 'o': 2076 opt_io = EARGF(usage()); 2077 break; 2078 case 'l': 2079 opt_line = EARGF(usage()); 2080 break; 2081 case 'n': 2082 opt_name = EARGF(usage()); 2083 break; 2084 case 't': 2085 case 'T': 2086 opt_title = EARGF(usage()); 2087 break; 2088 case 'w': 2089 opt_embed = EARGF(usage()); 2090 break; 2091 case 'v': 2092 die("%s " VERSION "\n", argv0); 2093 break; 2094 default: 2095 usage(); 2096 } ARGEND; 2097 2098 run: 2099 if (argc > 0) /* eat all remaining arguments */ 2100 opt_cmd = argv; 2101 2102 if (!opt_title) 2103 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0]; 2104 2105 setlocale(LC_CTYPE, ""); 2106 XSetLocaleModifiers(""); 2107 cols = MAX(cols, 1); 2108 rows = MAX(rows, 1); 2109 tnew(cols, rows); 2110 xinit(cols, rows); 2111 xsetenv(); 2112 selinit(); 2113 run(); 2114 2115 return 0; 2116 }