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.

2067 lines
46 KiB

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