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