x.c (53909B)
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, netwmicon, 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 /* use a png-image to set _NET_WM_ICON */ 1339 FILE* file = fopen(ICON, "r"); 1340 if (file) { 1341 /* load image in rgba-format */ 1342 const gdImagePtr icon_rgba = gdImageCreateFromPng(file); 1343 fclose(file); 1344 /* declare icon-variable which will store the image in argb-format */ 1345 const int width = gdImageSX(icon_rgba); 1346 const int height = gdImageSY(icon_rgba); 1347 const int icon_n = width * height + 2; 1348 long icon_argb[icon_n]; 1349 /* set width and height of the icon */ 1350 int i = 0; 1351 icon_argb[i++] = width; 1352 icon_argb[i++] = height; 1353 /* rgba -> argb */ 1354 for (int y = 0; y < height; y++) { 1355 for (int x = 0; x < width; x++) { 1356 const int pixel_rgba = gdImageGetPixel(icon_rgba, x, y); 1357 unsigned char *pixel_argb = (unsigned char *) &icon_argb[i++]; 1358 pixel_argb[0] = gdImageBlue(icon_rgba, pixel_rgba); 1359 pixel_argb[1] = gdImageGreen(icon_rgba, pixel_rgba); 1360 pixel_argb[2] = gdImageRed(icon_rgba, pixel_rgba); 1361 /* scale alpha from 0-127 to 0-255 */ 1362 const unsigned char alpha = 127 - gdImageAlpha(icon_rgba, pixel_rgba); 1363 pixel_argb[3] = alpha == 127 ? 255 : alpha * 2; 1364 } 1365 } 1366 gdImageDestroy(icon_rgba); 1367 /* set _NET_WM_ICON */ 1368 xw.netwmicon = XInternAtom(xw.dpy, "_NET_WM_ICON", False); 1369 XChangeProperty(xw.dpy, xw.win, xw.netwmicon, XA_CARDINAL, 32, 1370 PropModeReplace, (uchar *) icon_argb, icon_n); 1371 } 1372 1373 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False); 1374 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32, 1375 PropModeReplace, (uchar *)&thispid, 1); 1376 1377 win.mode = MODE_NUMLOCK; 1378 resettitle(); 1379 xhints(); 1380 XMapWindow(xw.dpy, xw.win); 1381 XSync(xw.dpy, False); 1382 1383 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1); 1384 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2); 1385 xsel.primary = NULL; 1386 xsel.clipboard = NULL; 1387 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0); 1388 if (xsel.xtarget == None) 1389 xsel.xtarget = XA_STRING; 1390 1391 boxdraw_xinit(xw.dpy, xw.cmap, xw.draw, xw.vis); 1392 } 1393 1394 int 1395 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y) 1396 { 1397 float winx = win.hborderpx + x * win.cw, winy = win.vborderpx + y * win.ch, xp, yp; 1398 ushort mode, prevmode = USHRT_MAX; 1399 Font *font = &dc.font; 1400 int frcflags = FRC_NORMAL; 1401 float runewidth = win.cw; 1402 Rune rune; 1403 FT_UInt glyphidx; 1404 FcResult fcres; 1405 FcPattern *fcpattern, *fontpattern; 1406 FcFontSet *fcsets[] = { NULL }; 1407 FcCharSet *fccharset; 1408 int i, f, numspecs = 0; 1409 1410 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) { 1411 /* Fetch rune and mode for current glyph. */ 1412 rune = glyphs[i].u; 1413 mode = glyphs[i].mode; 1414 1415 /* Skip dummy wide-character spacing. */ 1416 if (mode == ATTR_WDUMMY) 1417 continue; 1418 1419 /* Determine font for glyph if different from previous glyph. */ 1420 if (prevmode != mode) { 1421 prevmode = mode; 1422 font = &dc.font; 1423 frcflags = FRC_NORMAL; 1424 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f); 1425 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) { 1426 font = &dc.ibfont; 1427 frcflags = FRC_ITALICBOLD; 1428 } else if (mode & ATTR_ITALIC) { 1429 font = &dc.ifont; 1430 frcflags = FRC_ITALIC; 1431 } else if (mode & ATTR_BOLD) { 1432 font = &dc.bfont; 1433 frcflags = FRC_BOLD; 1434 } 1435 yp = winy + font->ascent; 1436 } 1437 1438 if (mode & ATTR_BOXDRAW) { 1439 /* minor shoehorning: boxdraw uses only this ushort */ 1440 glyphidx = boxdrawindex(&glyphs[i]); 1441 } else { 1442 /* Lookup character index with default font. */ 1443 glyphidx = XftCharIndex(xw.dpy, font->match, rune); 1444 } 1445 if (glyphidx) { 1446 specs[numspecs].font = font->match; 1447 specs[numspecs].glyph = glyphidx; 1448 specs[numspecs].x = (short)xp; 1449 specs[numspecs].y = (short)yp; 1450 xp += runewidth; 1451 numspecs++; 1452 continue; 1453 } 1454 1455 /* Fallback on font cache, search the font cache for match. */ 1456 for (f = 0; f < frclen; f++) { 1457 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune); 1458 /* Everything correct. */ 1459 if (glyphidx && frc[f].flags == frcflags) 1460 break; 1461 /* We got a default font for a not found glyph. */ 1462 if (!glyphidx && frc[f].flags == frcflags 1463 && frc[f].unicodep == rune) { 1464 break; 1465 } 1466 } 1467 1468 /* Nothing was found. Use fontconfig to find matching font. */ 1469 if (f >= frclen) { 1470 if (!font->set) 1471 font->set = FcFontSort(0, font->pattern, 1472 1, 0, &fcres); 1473 fcsets[0] = font->set; 1474 1475 /* 1476 * Nothing was found in the cache. Now use 1477 * some dozen of Fontconfig calls to get the 1478 * font for one single character. 1479 * 1480 * Xft and fontconfig are design failures. 1481 */ 1482 fcpattern = FcPatternDuplicate(font->pattern); 1483 fccharset = FcCharSetCreate(); 1484 1485 FcCharSetAddChar(fccharset, rune); 1486 FcPatternAddCharSet(fcpattern, FC_CHARSET, 1487 fccharset); 1488 FcPatternAddBool(fcpattern, FC_SCALABLE, 1); 1489 1490 FcConfigSubstitute(0, fcpattern, 1491 FcMatchPattern); 1492 FcDefaultSubstitute(fcpattern); 1493 1494 fontpattern = FcFontSetMatch(0, fcsets, 1, 1495 fcpattern, &fcres); 1496 1497 /* Allocate memory for the new cache entry. */ 1498 if (frclen >= frccap) { 1499 frccap += 16; 1500 frc = xrealloc(frc, frccap * sizeof(Fontcache)); 1501 } 1502 1503 frc[frclen].font = XftFontOpenPattern(xw.dpy, 1504 fontpattern); 1505 if (!frc[frclen].font) 1506 die("XftFontOpenPattern failed seeking fallback font: %s\n", 1507 strerror(errno)); 1508 frc[frclen].flags = frcflags; 1509 frc[frclen].unicodep = rune; 1510 1511 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune); 1512 1513 f = frclen; 1514 frclen++; 1515 1516 FcPatternDestroy(fcpattern); 1517 FcCharSetDestroy(fccharset); 1518 } 1519 1520 specs[numspecs].font = frc[f].font; 1521 specs[numspecs].glyph = glyphidx; 1522 specs[numspecs].x = (short)xp; 1523 specs[numspecs].y = (short)yp; 1524 xp += runewidth; 1525 numspecs++; 1526 } 1527 1528 return numspecs; 1529 } 1530 1531 void 1532 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y, int dmode) 1533 { 1534 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1); 1535 int winx = win.hborderpx + x * win.cw, winy = win.vborderpx + y * win.ch, 1536 width = charlen * win.cw; 1537 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg; 1538 XRenderColor colfg, colbg; 1539 XRectangle r; 1540 1541 /* Fallback on color display for attributes not supported by the font */ 1542 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) { 1543 if (dc.ibfont.badslant || dc.ibfont.badweight) 1544 base.fg = defaultattr; 1545 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) || 1546 (base.mode & ATTR_BOLD && dc.bfont.badweight)) { 1547 base.fg = defaultattr; 1548 } 1549 1550 if (IS_TRUECOL(base.fg)) { 1551 colfg.alpha = 0xffff; 1552 colfg.red = TRUERED(base.fg); 1553 colfg.green = TRUEGREEN(base.fg); 1554 colfg.blue = TRUEBLUE(base.fg); 1555 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg); 1556 fg = &truefg; 1557 } else { 1558 fg = &dc.col[base.fg]; 1559 } 1560 1561 if (IS_TRUECOL(base.bg)) { 1562 colbg.alpha = 0xffff; 1563 colbg.green = TRUEGREEN(base.bg); 1564 colbg.red = TRUERED(base.bg); 1565 colbg.blue = TRUEBLUE(base.bg); 1566 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg); 1567 bg = &truebg; 1568 } else { 1569 bg = &dc.col[base.bg]; 1570 } 1571 1572 /* Change basic system colors [0-7] to bright system colors [8-15] */ 1573 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7)) 1574 fg = &dc.col[base.fg + 8]; 1575 1576 if (IS_SET(MODE_REVERSE)) { 1577 if (fg == &dc.col[defaultfg]) { 1578 fg = &dc.col[defaultbg]; 1579 } else { 1580 colfg.red = ~fg->color.red; 1581 colfg.green = ~fg->color.green; 1582 colfg.blue = ~fg->color.blue; 1583 colfg.alpha = fg->color.alpha; 1584 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, 1585 &revfg); 1586 fg = &revfg; 1587 } 1588 1589 if (bg == &dc.col[defaultbg]) { 1590 bg = &dc.col[defaultfg]; 1591 } else { 1592 colbg.red = ~bg->color.red; 1593 colbg.green = ~bg->color.green; 1594 colbg.blue = ~bg->color.blue; 1595 colbg.alpha = bg->color.alpha; 1596 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, 1597 &revbg); 1598 bg = &revbg; 1599 } 1600 } 1601 1602 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) { 1603 colfg.red = fg->color.red / 2; 1604 colfg.green = fg->color.green / 2; 1605 colfg.blue = fg->color.blue / 2; 1606 colfg.alpha = fg->color.alpha; 1607 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg); 1608 fg = &revfg; 1609 } 1610 1611 if (base.mode & ATTR_REVERSE) { 1612 temp = fg; 1613 fg = bg; 1614 bg = temp; 1615 } 1616 1617 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK) 1618 fg = bg; 1619 1620 if (base.mode & ATTR_INVISIBLE) 1621 fg = bg; 1622 1623 if (dmode & DRAW_BG) { 1624 /* Intelligent cleaning up of the borders. */ 1625 if (x == 0) { 1626 xclear(0, (y == 0)? 0 : winy, borderpx, 1627 winy + win.ch + 1628 ((winy + win.ch >= borderpx + win.th)? win.h : 0)); 1629 } 1630 if (winx + width >= borderpx + win.tw) { 1631 xclear(winx + width, (y == 0)? 0 : winy, win.w, 1632 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch))); 1633 } 1634 if (y == 0) 1635 xclear(winx, 0, winx + width, borderpx); 1636 if (winy + win.ch >= borderpx + win.th) 1637 xclear(winx, winy + win.ch, winx + width, win.h); 1638 /* Fill the background */ 1639 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch); 1640 } 1641 1642 if (dmode & DRAW_FG) { 1643 if (base.mode & ATTR_BOXDRAW) { 1644 drawboxes(winx, winy, width / len, win.ch, fg, bg, specs, len); 1645 } else { 1646 /* Render the glyphs. */ 1647 XftDrawGlyphFontSpec(xw.draw, fg, specs, len); 1648 } 1649 1650 /* Render underline and strikethrough. */ 1651 if (base.mode & ATTR_UNDERLINE) { 1652 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1, 1653 width, 1); 1654 } 1655 if (base.mode & ATTR_STRUCK) { 1656 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3, 1657 width, 1); 1658 } 1659 } 1660 } 1661 1662 void 1663 xdrawglyph(Glyph g, int x, int y) 1664 { 1665 int numspecs; 1666 XftGlyphFontSpec spec; 1667 1668 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y); 1669 xdrawglyphfontspecs(&spec, g, numspecs, x, y, DRAW_BG | DRAW_FG); 1670 } 1671 1672 void 1673 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og) 1674 { 1675 Color drawcol; 1676 1677 /* remove the old cursor */ 1678 if (selected(ox, oy)) 1679 og.mode ^= ATTR_REVERSE; 1680 xdrawglyph(og, ox, oy); 1681 1682 if (IS_SET(MODE_HIDE)) 1683 return; 1684 1685 /* 1686 * Select the right color for the right mode. 1687 */ 1688 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE|ATTR_BOXDRAW; 1689 1690 if (IS_SET(MODE_REVERSE)) { 1691 g.mode |= ATTR_REVERSE; 1692 g.bg = defaultfg; 1693 if (selected(cx, cy)) { 1694 drawcol = dc.col[defaultcs]; 1695 g.fg = defaultrcs; 1696 } else { 1697 drawcol = dc.col[defaultrcs]; 1698 g.fg = defaultcs; 1699 } 1700 } else { 1701 if (selected(cx, cy)) { 1702 g.fg = defaultfg; 1703 g.bg = defaultrcs; 1704 } else { 1705 g.fg = defaultbg; 1706 g.bg = defaultcs; 1707 } 1708 drawcol = dc.col[g.bg]; 1709 } 1710 1711 /* draw the new one */ 1712 if (IS_SET(MODE_FOCUSED)) { 1713 switch (win.cursor) { 1714 case 7: /* st extension */ 1715 g.u = 0x2603; /* snowman (U+2603) */ 1716 /* FALLTHROUGH */ 1717 case 0: /* Blinking Block */ 1718 case 1: /* Blinking Block (Default) */ 1719 case 2: /* Steady Block */ 1720 xdrawglyph(g, cx, cy); 1721 break; 1722 case 3: /* Blinking Underline */ 1723 case 4: /* Steady Underline */ 1724 XftDrawRect(xw.draw, &drawcol, 1725 win.hborderpx + cx * win.cw, 1726 win.vborderpx + (cy + 1) * win.ch - \ 1727 cursorthickness, 1728 win.cw, cursorthickness); 1729 break; 1730 case 5: /* Blinking bar */ 1731 case 6: /* Steady bar */ 1732 XftDrawRect(xw.draw, &drawcol, 1733 win.hborderpx + cx * win.cw, 1734 win.vborderpx + cy * win.ch, 1735 cursorthickness, win.ch); 1736 break; 1737 } 1738 } else { 1739 XftDrawRect(xw.draw, &drawcol, 1740 win.hborderpx + cx * win.cw, 1741 win.vborderpx + cy * win.ch, 1742 win.cw - 1, 1); 1743 XftDrawRect(xw.draw, &drawcol, 1744 win.hborderpx + cx * win.cw, 1745 win.vborderpx + cy * win.ch, 1746 1, win.ch - 1); 1747 XftDrawRect(xw.draw, &drawcol, 1748 win.hborderpx + (cx + 1) * win.cw - 1, 1749 win.vborderpx + cy * win.ch, 1750 1, win.ch - 1); 1751 XftDrawRect(xw.draw, &drawcol, 1752 win.hborderpx + cx * win.cw, 1753 win.vborderpx + (cy + 1) * win.ch - 1, 1754 win.cw, 1); 1755 } 1756 } 1757 1758 void 1759 xsetenv(void) 1760 { 1761 char buf[sizeof(long) * 8 + 1]; 1762 1763 snprintf(buf, sizeof(buf), "%lu", xw.win); 1764 setenv("WINDOWID", buf, 1); 1765 } 1766 1767 void 1768 xseticontitle(char *p) 1769 { 1770 XTextProperty prop; 1771 DEFAULT(p, opt_title); 1772 1773 if (p[0] == '\0') 1774 p = opt_title; 1775 1776 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle, 1777 &prop) != Success) 1778 return; 1779 XSetWMIconName(xw.dpy, xw.win, &prop); 1780 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname); 1781 XFree(prop.value); 1782 } 1783 1784 void 1785 xsettitle(char *p) 1786 { 1787 if (titlechanged && !allowchangingtitle) return; 1788 titlechanged = 1; 1789 1790 XTextProperty prop; 1791 DEFAULT(p, opt_title); 1792 1793 if (p[0] == '\0') 1794 p = opt_title; 1795 1796 if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle, 1797 &prop) != Success) 1798 return; 1799 XSetWMName(xw.dpy, xw.win, &prop); 1800 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname); 1801 XFree(prop.value); 1802 } 1803 1804 int 1805 xstartdraw(void) 1806 { 1807 if (IS_SET(MODE_VISIBLE)) 1808 XCopyArea(xw.dpy, xw.win, xw.buf, dc.gc, 0, 0, win.w, win.h, 0, 0); 1809 return IS_SET(MODE_VISIBLE); 1810 } 1811 1812 void 1813 xdrawline(Line line, int x1, int y1, int x2) 1814 { 1815 int i, x, ox, numspecs, numspecs_cached; 1816 Glyph base, new; 1817 XftGlyphFontSpec *specs; 1818 1819 numspecs_cached = xmakeglyphfontspecs(xw.specbuf, &line[x1], x2 - x1, x1, y1); 1820 1821 /* Draw line in 2 passes: background and foreground. This way wide glyphs 1822 won't get truncated (#223) */ 1823 for (int dmode = DRAW_BG; dmode <= DRAW_FG; dmode <<= 1) { 1824 specs = xw.specbuf; 1825 numspecs = numspecs_cached; 1826 i = ox = 0; 1827 for (x = x1; x < x2 && i < numspecs; x++) { 1828 new = line[x]; 1829 if (new.mode == ATTR_WDUMMY) 1830 continue; 1831 if (selected(x, y1)) 1832 new.mode ^= ATTR_REVERSE; 1833 if (i > 0 && ATTRCMP(base, new)) { 1834 xdrawglyphfontspecs(specs, base, i, ox, y1, dmode); 1835 specs += i; 1836 numspecs -= i; 1837 i = 0; 1838 } 1839 if (i == 0) { 1840 ox = x; 1841 base = new; 1842 } 1843 i++; 1844 } 1845 if (i > 0) 1846 xdrawglyphfontspecs(specs, base, i, ox, y1, dmode); 1847 } 1848 } 1849 1850 void 1851 xfinishdraw(void) 1852 { 1853 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w, 1854 win.h, 0, 0); 1855 XSetForeground(xw.dpy, dc.gc, 1856 dc.col[IS_SET(MODE_REVERSE)? 1857 defaultfg : defaultbg].pixel); 1858 } 1859 1860 void 1861 xximspot(int x, int y) 1862 { 1863 if (xw.ime.xic == NULL) 1864 return; 1865 1866 xw.ime.spot.x = borderpx + x * win.cw; 1867 xw.ime.spot.y = borderpx + (y + 1) * win.ch; 1868 1869 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL); 1870 } 1871 1872 void 1873 expose(XEvent *ev) 1874 { 1875 redraw(); 1876 } 1877 1878 void 1879 visibility(XEvent *ev) 1880 { 1881 XVisibilityEvent *e = &ev->xvisibility; 1882 1883 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE); 1884 } 1885 1886 void 1887 unmap(XEvent *ev) 1888 { 1889 win.mode &= ~MODE_VISIBLE; 1890 } 1891 1892 void 1893 xsetpointermotion(int set) 1894 { 1895 MODBIT(xw.attrs.event_mask, set, PointerMotionMask); 1896 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); 1897 } 1898 1899 void 1900 xsetmode(int set, unsigned int flags) 1901 { 1902 int mode = win.mode; 1903 MODBIT(win.mode, set, flags); 1904 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE)) 1905 redraw(); 1906 } 1907 1908 int 1909 xsetcursor(int cursor) 1910 { 1911 if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */ 1912 return 1; 1913 win.cursor = cursor; 1914 return 0; 1915 } 1916 1917 void 1918 xseturgency(int add) 1919 { 1920 XWMHints *h = XGetWMHints(xw.dpy, xw.win); 1921 1922 MODBIT(h->flags, add, XUrgencyHint); 1923 XSetWMHints(xw.dpy, xw.win, h); 1924 XFree(h); 1925 } 1926 1927 void 1928 xbell(void) 1929 { 1930 if (!(IS_SET(MODE_FOCUSED))) 1931 xseturgency(1); 1932 if (bellvolume) 1933 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL); 1934 } 1935 1936 void 1937 focus(XEvent *ev) 1938 { 1939 XFocusChangeEvent *e = &ev->xfocus; 1940 1941 if (e->mode == NotifyGrab) 1942 return; 1943 1944 if (ev->type == FocusIn) { 1945 if (xw.ime.xic) 1946 XSetICFocus(xw.ime.xic); 1947 win.mode |= MODE_FOCUSED; 1948 xseturgency(0); 1949 if (IS_SET(MODE_FOCUS)) 1950 ttywrite("\033[I", 3, 0); 1951 } else { 1952 if (xw.ime.xic) 1953 XUnsetICFocus(xw.ime.xic); 1954 win.mode &= ~MODE_FOCUSED; 1955 if (IS_SET(MODE_FOCUS)) 1956 ttywrite("\033[O", 3, 0); 1957 } 1958 } 1959 1960 int 1961 match(uint mask, uint state) 1962 { 1963 return mask == XK_ANY_MOD || mask == (state & ~ignoremod); 1964 } 1965 1966 char* 1967 kmap(KeySym k, uint state) 1968 { 1969 Key *kp; 1970 int i; 1971 1972 /* Check for mapped keys out of X11 function keys. */ 1973 for (i = 0; i < LEN(mappedkeys); i++) { 1974 if (mappedkeys[i] == k) 1975 break; 1976 } 1977 if (i == LEN(mappedkeys)) { 1978 if ((k & 0xFFFF) < 0xFD00) 1979 return NULL; 1980 } 1981 1982 for (kp = key; kp < key + LEN(key); kp++) { 1983 if (kp->k != k) 1984 continue; 1985 1986 if (!match(kp->mask, state)) 1987 continue; 1988 1989 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0) 1990 continue; 1991 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2) 1992 continue; 1993 1994 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0) 1995 continue; 1996 1997 return kp->s; 1998 } 1999 2000 return NULL; 2001 } 2002 2003 void 2004 kpress(XEvent *ev) 2005 { 2006 XKeyEvent *e = &ev->xkey; 2007 KeySym ksym = NoSymbol; 2008 char buf[64], *customkey; 2009 int len; 2010 Rune c; 2011 Status status; 2012 Shortcut *bp; 2013 2014 if (IS_SET(MODE_KBDLOCK)) 2015 return; 2016 2017 if (xw.ime.xic) { 2018 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status); 2019 if (status == XBufferOverflow) 2020 return; 2021 } else { 2022 len = XLookupString(e, buf, sizeof buf, &ksym, NULL); 2023 } 2024 /* 1. shortcuts */ 2025 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) { 2026 if (ksym == bp->keysym && match(bp->mod, e->state)) { 2027 bp->func(&(bp->arg)); 2028 return; 2029 } 2030 } 2031 2032 /* 2. custom keys from config.h */ 2033 if ((customkey = kmap(ksym, e->state))) { 2034 ttywrite(customkey, strlen(customkey), 1); 2035 return; 2036 } 2037 2038 /* 3. composed string from input method */ 2039 if (len == 0) 2040 return; 2041 if (len == 1 && e->state & Mod1Mask) { 2042 if (IS_SET(MODE_8BIT)) { 2043 if (*buf < 0177) { 2044 c = *buf | 0x80; 2045 len = utf8encode(c, buf); 2046 } 2047 } else { 2048 buf[1] = buf[0]; 2049 buf[0] = '\033'; 2050 len = 2; 2051 } 2052 } 2053 ttywrite(buf, len, 1); 2054 } 2055 2056 void 2057 cmessage(XEvent *e) 2058 { 2059 /* 2060 * See xembed specs 2061 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html 2062 */ 2063 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) { 2064 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) { 2065 win.mode |= MODE_FOCUSED; 2066 xseturgency(0); 2067 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) { 2068 win.mode &= ~MODE_FOCUSED; 2069 } 2070 } else if (e->xclient.data.l[0] == xw.wmdeletewin) { 2071 ttyhangup(); 2072 exit(0); 2073 } 2074 } 2075 2076 void 2077 resize(XEvent *e) 2078 { 2079 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h) 2080 return; 2081 2082 cresize(e->xconfigure.width, e->xconfigure.height); 2083 } 2084 2085 int tinsync(uint); 2086 int ttyread_pending(); 2087 2088 void 2089 run(void) 2090 { 2091 XEvent ev; 2092 int w = win.w, h = win.h; 2093 fd_set rfd; 2094 int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing; 2095 struct timespec seltv, *tv, now, lastblink, trigger; 2096 double timeout; 2097 2098 /* Waiting for window mapping */ 2099 do { 2100 XNextEvent(xw.dpy, &ev); 2101 /* 2102 * This XFilterEvent call is required because of XOpenIM. It 2103 * does filter out the key event and some client message for 2104 * the input method too. 2105 */ 2106 if (XFilterEvent(&ev, None)) 2107 continue; 2108 if (ev.type == ConfigureNotify) { 2109 w = ev.xconfigure.width; 2110 h = ev.xconfigure.height; 2111 } 2112 } while (ev.type != MapNotify); 2113 2114 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd); 2115 cresize(w, h); 2116 2117 for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) { 2118 FD_ZERO(&rfd); 2119 FD_SET(ttyfd, &rfd); 2120 FD_SET(xfd, &rfd); 2121 2122 if (XPending(xw.dpy) || ttyread_pending()) 2123 timeout = 0; /* existing events might not set xfd */ 2124 2125 seltv.tv_sec = timeout / 1E3; 2126 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec); 2127 tv = timeout >= 0 ? &seltv : NULL; 2128 2129 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) { 2130 if (errno == EINTR) 2131 continue; 2132 die("select failed: %s\n", strerror(errno)); 2133 } 2134 clock_gettime(CLOCK_MONOTONIC, &now); 2135 2136 int ttyin = FD_ISSET(ttyfd, &rfd) || ttyread_pending(); 2137 if (ttyin) 2138 ttyread(); 2139 2140 xev = 0; 2141 while (XPending(xw.dpy)) { 2142 xev = 1; 2143 XNextEvent(xw.dpy, &ev); 2144 if (XFilterEvent(&ev, None)) 2145 continue; 2146 if (handler[ev.type]) 2147 (handler[ev.type])(&ev); 2148 } 2149 2150 /* 2151 * To reduce flicker and tearing, when new content or event 2152 * triggers drawing, we first wait a bit to ensure we got 2153 * everything, and if nothing new arrives - we draw. 2154 * We start with trying to wait minlatency ms. If more content 2155 * arrives sooner, we retry with shorter and shorter periods, 2156 * and eventually draw even without idle after maxlatency ms. 2157 * Typically this results in low latency while interacting, 2158 * maximum latency intervals during `cat huge.txt`, and perfect 2159 * sync with periodic updates from animations/key-repeats/etc. 2160 */ 2161 if (ttyin || xev) { 2162 if (!drawing) { 2163 trigger = now; 2164 drawing = 1; 2165 } 2166 timeout = (maxlatency - TIMEDIFF(now, trigger)) \ 2167 / maxlatency * minlatency; 2168 if (timeout > 0) 2169 continue; /* we have time, try to find idle */ 2170 } 2171 2172 if (tinsync(su_timeout)) { 2173 /* 2174 * on synchronized-update draw-suspension: don't reset 2175 * drawing so that we draw ASAP once we can (just after 2176 * ESU). it won't be too soon because we already can 2177 * draw now but we skip. we set timeout > 0 to draw on 2178 * SU-timeout even without new content. 2179 */ 2180 timeout = minlatency; 2181 continue; 2182 } 2183 2184 /* idle detected or maxlatency exhausted -> draw */ 2185 timeout = -1; 2186 if (blinktimeout && tattrset(ATTR_BLINK)) { 2187 timeout = blinktimeout - TIMEDIFF(now, lastblink); 2188 if (timeout <= 0) { 2189 if (-timeout > blinktimeout) /* start visible */ 2190 win.mode |= MODE_BLINK; 2191 win.mode ^= MODE_BLINK; 2192 tsetdirtattr(ATTR_BLINK); 2193 lastblink = now; 2194 timeout = blinktimeout; 2195 } 2196 } 2197 2198 draw(); 2199 XFlush(xw.dpy); 2200 drawing = 0; 2201 } 2202 } 2203 2204 void 2205 usage(void) 2206 { 2207 die("usage: %s [-aiv] [-c class] [-d path] [-f font]" 2208 " [-g geometry] [-n name] [-o file]\n" 2209 " [-T title] [-t title] [-w windowid]" 2210 " [[-e] command [args ...]]\n" 2211 " %s [-aiv] [-c class] [-d path] [-f font]" 2212 " [-g geometry] [-n name] [-o file]\n" 2213 " [-T title] [-t title] [-w windowid] -l line" 2214 " [stty_args ...]\n", argv0, argv0); 2215 } 2216 2217 int 2218 main(int argc, char *argv[]) 2219 { 2220 xw.l = xw.t = 0; 2221 xw.isfixed = False; 2222 xsetcursor(cursorshape); 2223 2224 ARGBEGIN { 2225 case 'a': 2226 allowaltscreen = 0; 2227 break; 2228 case 'c': 2229 opt_class = EARGF(usage()); 2230 break; 2231 case 'e': 2232 if (argc > 0) 2233 --argc, ++argv; 2234 goto run; 2235 case 'f': 2236 opt_font = EARGF(usage()); 2237 break; 2238 case 'g': 2239 xw.gm = XParseGeometry(EARGF(usage()), 2240 &xw.l, &xw.t, &cols, &rows); 2241 break; 2242 case 'i': 2243 xw.isfixed = 1; 2244 break; 2245 case 'o': 2246 opt_io = EARGF(usage()); 2247 break; 2248 case 'l': 2249 opt_line = EARGF(usage()); 2250 break; 2251 case 'n': 2252 opt_name = EARGF(usage()); 2253 break; 2254 case 't': 2255 case 'T': 2256 opt_title = EARGF(usage()); 2257 break; 2258 case 'w': 2259 opt_embed = EARGF(usage()); 2260 break; 2261 case 'v': 2262 die("%s " VERSION "\n", argv0); 2263 break; 2264 case 'd': 2265 opt_dir = EARGF(usage()); 2266 break; 2267 default: 2268 usage(); 2269 } ARGEND; 2270 2271 run: 2272 if (argc > 0) /* eat all remaining arguments */ 2273 opt_cmd = argv; 2274 2275 if (!opt_title) 2276 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0]; 2277 2278 setlocale(LC_CTYPE, ""); 2279 XSetLocaleModifiers(""); 2280 cols = MAX(cols, 1); 2281 rows = MAX(rows, 1); 2282 tnew(cols, rows); 2283 xinit(cols, rows); 2284 xsetenv(); 2285 selinit(); 2286 chdir(opt_dir); 2287 run(); 2288 2289 return 0; 2290 }