My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2065 lines
46 KiB

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