Simple Terminal from SuckLess
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.

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