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.

2063 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, 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 >= 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. xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
  1026. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  1027. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  1028. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  1029. PropModeReplace, (uchar *)&thispid, 1);
  1030. win.mode = MODE_NUMLOCK;
  1031. resettitle();
  1032. xhints();
  1033. XMapWindow(xw.dpy, xw.win);
  1034. XSync(xw.dpy, False);
  1035. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
  1036. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
  1037. xsel.primary = NULL;
  1038. xsel.clipboard = NULL;
  1039. xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  1040. if (xsel.xtarget == None)
  1041. xsel.xtarget = XA_STRING;
  1042. }
  1043. int
  1044. xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
  1045. {
  1046. float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
  1047. ushort mode, prevmode = USHRT_MAX;
  1048. Font *font = &dc.font;
  1049. int frcflags = FRC_NORMAL;
  1050. float runewidth = win.cw;
  1051. Rune rune;
  1052. FT_UInt glyphidx;
  1053. FcResult fcres;
  1054. FcPattern *fcpattern, *fontpattern;
  1055. FcFontSet *fcsets[] = { NULL };
  1056. FcCharSet *fccharset;
  1057. int i, f, numspecs = 0;
  1058. for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
  1059. /* Fetch rune and mode for current glyph. */
  1060. rune = glyphs[i].u;
  1061. mode = glyphs[i].mode;
  1062. /* Skip dummy wide-character spacing. */
  1063. if (mode == ATTR_WDUMMY)
  1064. continue;
  1065. /* Determine font for glyph if different from previous glyph. */
  1066. if (prevmode != mode) {
  1067. prevmode = mode;
  1068. font = &dc.font;
  1069. frcflags = FRC_NORMAL;
  1070. runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
  1071. if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
  1072. font = &dc.ibfont;
  1073. frcflags = FRC_ITALICBOLD;
  1074. } else if (mode & ATTR_ITALIC) {
  1075. font = &dc.ifont;
  1076. frcflags = FRC_ITALIC;
  1077. } else if (mode & ATTR_BOLD) {
  1078. font = &dc.bfont;
  1079. frcflags = FRC_BOLD;
  1080. }
  1081. yp = winy + font->ascent;
  1082. }
  1083. /* Lookup character index with default font. */
  1084. glyphidx = XftCharIndex(xw.dpy, font->match, rune);
  1085. if (glyphidx) {
  1086. specs[numspecs].font = font->match;
  1087. specs[numspecs].glyph = glyphidx;
  1088. specs[numspecs].x = (short)xp;
  1089. specs[numspecs].y = (short)yp;
  1090. xp += runewidth;
  1091. numspecs++;
  1092. continue;
  1093. }
  1094. /* Fallback on font cache, search the font cache for match. */
  1095. for (f = 0; f < frclen; f++) {
  1096. glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
  1097. /* Everything correct. */
  1098. if (glyphidx && frc[f].flags == frcflags)
  1099. break;
  1100. /* We got a default font for a not found glyph. */
  1101. if (!glyphidx && frc[f].flags == frcflags
  1102. && frc[f].unicodep == rune) {
  1103. break;
  1104. }
  1105. }
  1106. /* Nothing was found. Use fontconfig to find matching font. */
  1107. if (f >= frclen) {
  1108. if (!font->set)
  1109. font->set = FcFontSort(0, font->pattern,
  1110. 1, 0, &fcres);
  1111. fcsets[0] = font->set;
  1112. /*
  1113. * Nothing was found in the cache. Now use
  1114. * some dozen of Fontconfig calls to get the
  1115. * font for one single character.
  1116. *
  1117. * Xft and fontconfig are design failures.
  1118. */
  1119. fcpattern = FcPatternDuplicate(font->pattern);
  1120. fccharset = FcCharSetCreate();
  1121. FcCharSetAddChar(fccharset, rune);
  1122. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  1123. fccharset);
  1124. FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
  1125. FcConfigSubstitute(0, fcpattern,
  1126. FcMatchPattern);
  1127. FcDefaultSubstitute(fcpattern);
  1128. fontpattern = FcFontSetMatch(0, fcsets, 1,
  1129. fcpattern, &fcres);
  1130. /* Allocate memory for the new cache entry. */
  1131. if (frclen >= frccap) {
  1132. frccap += 16;
  1133. frc = xrealloc(frc, frccap * sizeof(Fontcache));
  1134. }
  1135. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  1136. fontpattern);
  1137. if (!frc[frclen].font)
  1138. die("XftFontOpenPattern failed seeking fallback font: %s\n",
  1139. strerror(errno));
  1140. frc[frclen].flags = frcflags;
  1141. frc[frclen].unicodep = rune;
  1142. glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
  1143. f = frclen;
  1144. frclen++;
  1145. FcPatternDestroy(fcpattern);
  1146. FcCharSetDestroy(fccharset);
  1147. }
  1148. specs[numspecs].font = frc[f].font;
  1149. specs[numspecs].glyph = glyphidx;
  1150. specs[numspecs].x = (short)xp;
  1151. specs[numspecs].y = (short)yp;
  1152. xp += runewidth;
  1153. numspecs++;
  1154. }
  1155. return numspecs;
  1156. }
  1157. void
  1158. xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
  1159. {
  1160. int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
  1161. int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
  1162. width = charlen * win.cw;
  1163. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  1164. XRenderColor colfg, colbg;
  1165. XRectangle r;
  1166. /* Fallback on color display for attributes not supported by the font */
  1167. if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
  1168. if (dc.ibfont.badslant || dc.ibfont.badweight)
  1169. base.fg = defaultattr;
  1170. } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
  1171. (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
  1172. base.fg = defaultattr;
  1173. }
  1174. if (IS_TRUECOL(base.fg)) {
  1175. colfg.alpha = 0xffff;
  1176. colfg.red = TRUERED(base.fg);
  1177. colfg.green = TRUEGREEN(base.fg);
  1178. colfg.blue = TRUEBLUE(base.fg);
  1179. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  1180. fg = &truefg;
  1181. } else {
  1182. fg = &dc.col[base.fg];
  1183. }
  1184. if (IS_TRUECOL(base.bg)) {
  1185. colbg.alpha = 0xffff;
  1186. colbg.green = TRUEGREEN(base.bg);
  1187. colbg.red = TRUERED(base.bg);
  1188. colbg.blue = TRUEBLUE(base.bg);
  1189. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  1190. bg = &truebg;
  1191. } else {
  1192. bg = &dc.col[base.bg];
  1193. }
  1194. /* Change basic system colors [0-7] to bright system colors [8-15] */
  1195. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
  1196. fg = &dc.col[base.fg + 8];
  1197. if (IS_SET(MODE_REVERSE)) {
  1198. if (fg == &dc.col[defaultfg]) {
  1199. fg = &dc.col[defaultbg];
  1200. } else {
  1201. colfg.red = ~fg->color.red;
  1202. colfg.green = ~fg->color.green;
  1203. colfg.blue = ~fg->color.blue;
  1204. colfg.alpha = fg->color.alpha;
  1205. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  1206. &revfg);
  1207. fg = &revfg;
  1208. }
  1209. if (bg == &dc.col[defaultbg]) {
  1210. bg = &dc.col[defaultfg];
  1211. } else {
  1212. colbg.red = ~bg->color.red;
  1213. colbg.green = ~bg->color.green;
  1214. colbg.blue = ~bg->color.blue;
  1215. colbg.alpha = bg->color.alpha;
  1216. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  1217. &revbg);
  1218. bg = &revbg;
  1219. }
  1220. }
  1221. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
  1222. colfg.red = fg->color.red / 2;
  1223. colfg.green = fg->color.green / 2;
  1224. colfg.blue = fg->color.blue / 2;
  1225. colfg.alpha = fg->color.alpha;
  1226. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  1227. fg = &revfg;
  1228. }
  1229. if (base.mode & ATTR_REVERSE) {
  1230. temp = fg;
  1231. fg = bg;
  1232. bg = temp;
  1233. }
  1234. if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
  1235. fg = bg;
  1236. if (base.mode & ATTR_INVISIBLE)
  1237. fg = bg;
  1238. /* Intelligent cleaning up of the borders. */
  1239. if (x == 0) {
  1240. xclear(0, (y == 0)? 0 : winy, borderpx,
  1241. winy + win.ch +
  1242. ((winy + win.ch >= borderpx + win.th)? win.h : 0));
  1243. }
  1244. if (winx + width >= borderpx + win.tw) {
  1245. xclear(winx + width, (y == 0)? 0 : winy, win.w,
  1246. ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
  1247. }
  1248. if (y == 0)
  1249. xclear(winx, 0, winx + width, borderpx);
  1250. if (winy + win.ch >= borderpx + win.th)
  1251. xclear(winx, winy + win.ch, winx + width, win.h);
  1252. /* Clean up the region we want to draw to. */
  1253. XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
  1254. /* Set the clip region because Xft is sometimes dirty. */
  1255. r.x = 0;
  1256. r.y = 0;
  1257. r.height = win.ch;
  1258. r.width = width;
  1259. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  1260. /* Render the glyphs. */
  1261. XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
  1262. /* Render underline and strikethrough. */
  1263. if (base.mode & ATTR_UNDERLINE) {
  1264. XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
  1265. width, 1);
  1266. }
  1267. if (base.mode & ATTR_STRUCK) {
  1268. XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
  1269. width, 1);
  1270. }
  1271. /* Reset clip to none. */
  1272. XftDrawSetClip(xw.draw, 0);
  1273. }
  1274. void
  1275. xdrawglyph(Glyph g, int x, int y)
  1276. {
  1277. int numspecs;
  1278. XftGlyphFontSpec spec;
  1279. numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
  1280. xdrawglyphfontspecs(&spec, g, numspecs, x, y);
  1281. }
  1282. void
  1283. xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
  1284. {
  1285. Color drawcol;
  1286. /* remove the old cursor */
  1287. if (selected(ox, oy))
  1288. og.mode ^= ATTR_REVERSE;
  1289. xdrawglyph(og, ox, oy);
  1290. if (IS_SET(MODE_HIDE))
  1291. return;
  1292. /*
  1293. * Select the right color for the right mode.
  1294. */
  1295. g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
  1296. if (IS_SET(MODE_REVERSE)) {
  1297. g.mode |= ATTR_REVERSE;
  1298. g.bg = defaultfg;
  1299. if (selected(cx, cy)) {
  1300. drawcol = dc.col[defaultcs];
  1301. g.fg = defaultrcs;
  1302. } else {
  1303. drawcol = dc.col[defaultrcs];
  1304. g.fg = defaultcs;
  1305. }
  1306. } else {
  1307. if (selected(cx, cy)) {
  1308. g.fg = defaultfg;
  1309. g.bg = defaultrcs;
  1310. } else {
  1311. g.fg = defaultbg;
  1312. g.bg = defaultcs;
  1313. }
  1314. drawcol = dc.col[g.bg];
  1315. }
  1316. /* draw the new one */
  1317. if (IS_SET(MODE_FOCUSED)) {
  1318. switch (win.cursor) {
  1319. case 7: /* st extension */
  1320. g.u = 0x2603; /* snowman (U+2603) */
  1321. /* FALLTHROUGH */
  1322. case 0: /* Blinking Block */
  1323. case 1: /* Blinking Block (Default) */
  1324. case 2: /* Steady Block */
  1325. xdrawglyph(g, cx, cy);
  1326. break;
  1327. case 3: /* Blinking Underline */
  1328. case 4: /* Steady Underline */
  1329. XftDrawRect(xw.draw, &drawcol,
  1330. borderpx + cx * win.cw,
  1331. borderpx + (cy + 1) * win.ch - \
  1332. cursorthickness,
  1333. win.cw, cursorthickness);
  1334. break;
  1335. case 5: /* Blinking bar */
  1336. case 6: /* Steady bar */
  1337. XftDrawRect(xw.draw, &drawcol,
  1338. borderpx + cx * win.cw,
  1339. borderpx + cy * win.ch,
  1340. cursorthickness, win.ch);
  1341. break;
  1342. }
  1343. } else {
  1344. XftDrawRect(xw.draw, &drawcol,
  1345. borderpx + cx * win.cw,
  1346. borderpx + cy * win.ch,
  1347. win.cw - 1, 1);
  1348. XftDrawRect(xw.draw, &drawcol,
  1349. borderpx + cx * win.cw,
  1350. borderpx + cy * win.ch,
  1351. 1, win.ch - 1);
  1352. XftDrawRect(xw.draw, &drawcol,
  1353. borderpx + (cx + 1) * win.cw - 1,
  1354. borderpx + cy * win.ch,
  1355. 1, win.ch - 1);
  1356. XftDrawRect(xw.draw, &drawcol,
  1357. borderpx + cx * win.cw,
  1358. borderpx + (cy + 1) * win.ch - 1,
  1359. win.cw, 1);
  1360. }
  1361. }
  1362. void
  1363. xsetenv(void)
  1364. {
  1365. char buf[sizeof(long) * 8 + 1];
  1366. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1367. setenv("WINDOWID", buf, 1);
  1368. }
  1369. void
  1370. xseticontitle(char *p)
  1371. {
  1372. XTextProperty prop;
  1373. DEFAULT(p, opt_title);
  1374. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1375. &prop);
  1376. XSetWMIconName(xw.dpy, xw.win, &prop);
  1377. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
  1378. XFree(prop.value);
  1379. }
  1380. void
  1381. xsettitle(char *p)
  1382. {
  1383. XTextProperty prop;
  1384. DEFAULT(p, opt_title);
  1385. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1386. &prop);
  1387. XSetWMName(xw.dpy, xw.win, &prop);
  1388. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  1389. XFree(prop.value);
  1390. }
  1391. int
  1392. xstartdraw(void)
  1393. {
  1394. return IS_SET(MODE_VISIBLE);
  1395. }
  1396. void
  1397. xdrawline(Line line, int x1, int y1, int x2)
  1398. {
  1399. int i, x, ox, numspecs;
  1400. Glyph base, new;
  1401. XftGlyphFontSpec *specs = xw.specbuf;
  1402. numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
  1403. i = ox = 0;
  1404. for (x = x1; x < x2 && i < numspecs; x++) {
  1405. new = line[x];
  1406. if (new.mode == ATTR_WDUMMY)
  1407. continue;
  1408. if (selected(x, y1))
  1409. new.mode ^= ATTR_REVERSE;
  1410. if (i > 0 && ATTRCMP(base, new)) {
  1411. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1412. specs += i;
  1413. numspecs -= i;
  1414. i = 0;
  1415. }
  1416. if (i == 0) {
  1417. ox = x;
  1418. base = new;
  1419. }
  1420. i++;
  1421. }
  1422. if (i > 0)
  1423. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1424. }
  1425. void
  1426. xfinishdraw(void)
  1427. {
  1428. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
  1429. win.h, 0, 0);
  1430. XSetForeground(xw.dpy, dc.gc,
  1431. dc.col[IS_SET(MODE_REVERSE)?
  1432. defaultfg : defaultbg].pixel);
  1433. }
  1434. void
  1435. xximspot(int x, int y)
  1436. {
  1437. if (xw.ime.xic == NULL)
  1438. return;
  1439. xw.ime.spot.x = borderpx + x * win.cw;
  1440. xw.ime.spot.y = borderpx + (y + 1) * win.ch;
  1441. XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
  1442. }
  1443. void
  1444. expose(XEvent *ev)
  1445. {
  1446. redraw();
  1447. }
  1448. void
  1449. visibility(XEvent *ev)
  1450. {
  1451. XVisibilityEvent *e = &ev->xvisibility;
  1452. MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
  1453. }
  1454. void
  1455. unmap(XEvent *ev)
  1456. {
  1457. win.mode &= ~MODE_VISIBLE;
  1458. }
  1459. void
  1460. xsetpointermotion(int set)
  1461. {
  1462. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  1463. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  1464. }
  1465. void
  1466. xsetmode(int set, unsigned int flags)
  1467. {
  1468. int mode = win.mode;
  1469. MODBIT(win.mode, set, flags);
  1470. if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
  1471. redraw();
  1472. }
  1473. int
  1474. xsetcursor(int cursor)
  1475. {
  1476. if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
  1477. return 1;
  1478. win.cursor = cursor;
  1479. return 0;
  1480. }
  1481. void
  1482. xseturgency(int add)
  1483. {
  1484. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1485. MODBIT(h->flags, add, XUrgencyHint);
  1486. XSetWMHints(xw.dpy, xw.win, h);
  1487. XFree(h);
  1488. }
  1489. void
  1490. xbell(void)
  1491. {
  1492. if (!(IS_SET(MODE_FOCUSED)))
  1493. xseturgency(1);
  1494. if (bellvolume)
  1495. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  1496. }
  1497. void
  1498. focus(XEvent *ev)
  1499. {
  1500. XFocusChangeEvent *e = &ev->xfocus;
  1501. if (e->mode == NotifyGrab)
  1502. return;
  1503. if (ev->type == FocusIn) {
  1504. if (xw.ime.xic)
  1505. XSetICFocus(xw.ime.xic);
  1506. win.mode |= MODE_FOCUSED;
  1507. xseturgency(0);
  1508. if (IS_SET(MODE_FOCUS))
  1509. ttywrite("\033[I", 3, 0);
  1510. } else {
  1511. if (xw.ime.xic)
  1512. XUnsetICFocus(xw.ime.xic);
  1513. win.mode &= ~MODE_FOCUSED;
  1514. if (IS_SET(MODE_FOCUS))
  1515. ttywrite("\033[O", 3, 0);
  1516. }
  1517. }
  1518. int
  1519. match(uint mask, uint state)
  1520. {
  1521. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  1522. }
  1523. char*
  1524. kmap(KeySym k, uint state)
  1525. {
  1526. Key *kp;
  1527. int i;
  1528. /* Check for mapped keys out of X11 function keys. */
  1529. for (i = 0; i < LEN(mappedkeys); i++) {
  1530. if (mappedkeys[i] == k)
  1531. break;
  1532. }
  1533. if (i == LEN(mappedkeys)) {
  1534. if ((k & 0xFFFF) < 0xFD00)
  1535. return NULL;
  1536. }
  1537. for (kp = key; kp < key + LEN(key); kp++) {
  1538. if (kp->k != k)
  1539. continue;
  1540. if (!match(kp->mask, state))
  1541. continue;
  1542. if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  1543. continue;
  1544. if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
  1545. continue;
  1546. if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  1547. continue;
  1548. return kp->s;
  1549. }
  1550. return NULL;
  1551. }
  1552. void
  1553. kpress(XEvent *ev)
  1554. {
  1555. XKeyEvent *e = &ev->xkey;
  1556. KeySym ksym;
  1557. char buf[64], *customkey;
  1558. int len;
  1559. Rune c;
  1560. Status status;
  1561. Shortcut *bp;
  1562. if (IS_SET(MODE_KBDLOCK))
  1563. return;
  1564. if (xw.ime.xic)
  1565. len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
  1566. else
  1567. len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
  1568. /* 1. shortcuts */
  1569. for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  1570. if (ksym == bp->keysym && match(bp->mod, e->state)) {
  1571. bp->func(&(bp->arg));
  1572. return;
  1573. }
  1574. }
  1575. /* 2. custom keys from config.h */
  1576. if ((customkey = kmap(ksym, e->state))) {
  1577. ttywrite(customkey, strlen(customkey), 1);
  1578. return;
  1579. }
  1580. /* 3. composed string from input method */
  1581. if (len == 0)
  1582. return;
  1583. if (len == 1 && e->state & Mod1Mask) {
  1584. if (IS_SET(MODE_8BIT)) {
  1585. if (*buf < 0177) {
  1586. c = *buf | 0x80;
  1587. len = utf8encode(c, buf);
  1588. }
  1589. } else {
  1590. buf[1] = buf[0];
  1591. buf[0] = '\033';
  1592. len = 2;
  1593. }
  1594. }
  1595. ttywrite(buf, len, 1);
  1596. }
  1597. void
  1598. cmessage(XEvent *e)
  1599. {
  1600. /*
  1601. * See xembed specs
  1602. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  1603. */
  1604. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1605. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1606. win.mode |= MODE_FOCUSED;
  1607. xseturgency(0);
  1608. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1609. win.mode &= ~MODE_FOCUSED;
  1610. }
  1611. } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
  1612. ttyhangup();
  1613. exit(0);
  1614. }
  1615. }
  1616. void
  1617. resize(XEvent *e)
  1618. {
  1619. if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
  1620. return;
  1621. cresize(e->xconfigure.width, e->xconfigure.height);
  1622. }
  1623. void
  1624. run(void)
  1625. {
  1626. XEvent ev;
  1627. int w = win.w, h = win.h;
  1628. fd_set rfd;
  1629. int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
  1630. struct timespec seltv, *tv, now, lastblink, trigger;
  1631. double timeout;
  1632. /* Waiting for window mapping */
  1633. do {
  1634. XNextEvent(xw.dpy, &ev);
  1635. /*
  1636. * This XFilterEvent call is required because of XOpenIM. It
  1637. * does filter out the key event and some client message for
  1638. * the input method too.
  1639. */
  1640. if (XFilterEvent(&ev, None))
  1641. continue;
  1642. if (ev.type == ConfigureNotify) {
  1643. w = ev.xconfigure.width;
  1644. h = ev.xconfigure.height;
  1645. }
  1646. } while (ev.type != MapNotify);
  1647. ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
  1648. cresize(w, h);
  1649. for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
  1650. FD_ZERO(&rfd);
  1651. FD_SET(ttyfd, &rfd);
  1652. FD_SET(xfd, &rfd);
  1653. if (XPending(xw.dpy))
  1654. timeout = 0; /* existing events might not set xfd */
  1655. seltv.tv_sec = timeout / 1E3;
  1656. seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
  1657. tv = timeout >= 0 ? &seltv : NULL;
  1658. if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  1659. if (errno == EINTR)
  1660. continue;
  1661. die("select failed: %s\n", strerror(errno));
  1662. }
  1663. clock_gettime(CLOCK_MONOTONIC, &now);
  1664. if (FD_ISSET(ttyfd, &rfd))
  1665. ttyread();
  1666. xev = 0;
  1667. while (XPending(xw.dpy)) {
  1668. xev = 1;
  1669. XNextEvent(xw.dpy, &ev);
  1670. if (XFilterEvent(&ev, None))
  1671. continue;
  1672. if (handler[ev.type])
  1673. (handler[ev.type])(&ev);
  1674. }
  1675. /*
  1676. * To reduce flicker and tearing, when new content or event
  1677. * triggers drawing, we first wait a bit to ensure we got
  1678. * everything, and if nothing new arrives - we draw.
  1679. * We start with trying to wait minlatency ms. If more content
  1680. * arrives sooner, we retry with shorter and shorter periods,
  1681. * and eventually draw even without idle after maxlatency ms.
  1682. * Typically this results in low latency while interacting,
  1683. * maximum latency intervals during `cat huge.txt`, and perfect
  1684. * sync with periodic updates from animations/key-repeats/etc.
  1685. */
  1686. if (FD_ISSET(ttyfd, &rfd) || xev) {
  1687. if (!drawing) {
  1688. trigger = now;
  1689. drawing = 1;
  1690. }
  1691. timeout = (maxlatency - TIMEDIFF(now, trigger)) \
  1692. / maxlatency * minlatency;
  1693. if (timeout > 0)
  1694. continue; /* we have time, try to find idle */
  1695. }
  1696. /* idle detected or maxlatency exhausted -> draw */
  1697. timeout = -1;
  1698. if (blinktimeout && tattrset(ATTR_BLINK)) {
  1699. timeout = blinktimeout - TIMEDIFF(now, lastblink);
  1700. if (timeout <= 0) {
  1701. if (-timeout > blinktimeout) /* start visible */
  1702. win.mode |= MODE_BLINK;
  1703. win.mode ^= MODE_BLINK;
  1704. tsetdirtattr(ATTR_BLINK);
  1705. lastblink = now;
  1706. timeout = blinktimeout;
  1707. }
  1708. }
  1709. draw();
  1710. XFlush(xw.dpy);
  1711. drawing = 0;
  1712. }
  1713. }
  1714. void
  1715. usage(void)
  1716. {
  1717. die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
  1718. " [-n name] [-o file]\n"
  1719. " [-T title] [-t title] [-w windowid]"
  1720. " [[-e] command [args ...]]\n"
  1721. " %s [-aiv] [-c class] [-f font] [-g geometry]"
  1722. " [-n name] [-o file]\n"
  1723. " [-T title] [-t title] [-w windowid] -l line"
  1724. " [stty_args ...]\n", argv0, argv0);
  1725. }
  1726. int
  1727. main(int argc, char *argv[])
  1728. {
  1729. xw.l = xw.t = 0;
  1730. xw.isfixed = False;
  1731. xsetcursor(cursorshape);
  1732. ARGBEGIN {
  1733. case 'a':
  1734. allowaltscreen = 0;
  1735. break;
  1736. case 'c':
  1737. opt_class = EARGF(usage());
  1738. break;
  1739. case 'e':
  1740. if (argc > 0)
  1741. --argc, ++argv;
  1742. goto run;
  1743. case 'f':
  1744. opt_font = EARGF(usage());
  1745. break;
  1746. case 'g':
  1747. xw.gm = XParseGeometry(EARGF(usage()),
  1748. &xw.l, &xw.t, &cols, &rows);
  1749. break;
  1750. case 'i':
  1751. xw.isfixed = 1;
  1752. break;
  1753. case 'o':
  1754. opt_io = EARGF(usage());
  1755. break;
  1756. case 'l':
  1757. opt_line = EARGF(usage());
  1758. break;
  1759. case 'n':
  1760. opt_name = EARGF(usage());
  1761. break;
  1762. case 't':
  1763. case 'T':
  1764. opt_title = EARGF(usage());
  1765. break;
  1766. case 'w':
  1767. opt_embed = EARGF(usage());
  1768. break;
  1769. case 'v':
  1770. die("%s " VERSION "\n", argv0);
  1771. break;
  1772. default:
  1773. usage();
  1774. } ARGEND;
  1775. run:
  1776. if (argc > 0) /* eat all remaining arguments */
  1777. opt_cmd = argv;
  1778. if (!opt_title)
  1779. opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
  1780. setlocale(LC_CTYPE, "");
  1781. XSetLocaleModifiers("");
  1782. cols = MAX(cols, 1);
  1783. rows = MAX(rows, 1);
  1784. tnew(cols, rows);
  1785. xinit(cols, rows);
  1786. xsetenv();
  1787. selinit();
  1788. run();
  1789. return 0;
  1790. }