Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2087 lines
47 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 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
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
3 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|1<<14)
  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 depth; /* bit depth */
  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(const 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_alpha = NULL;
  224. static char *opt_class = NULL;
  225. static char **opt_cmd = NULL;
  226. static char *opt_embed = NULL;
  227. static char *opt_font = NULL;
  228. static char *opt_io = NULL;
  229. static char *opt_line = NULL;
  230. static char *opt_name = NULL;
  231. static char *opt_title = NULL;
  232. static int oldbutton = 3; /* button event on startup: 3 = release */
  233. void
  234. clipcopy(const Arg *dummy)
  235. {
  236. Atom clipboard;
  237. free(xsel.clipboard);
  238. xsel.clipboard = NULL;
  239. if (xsel.primary != NULL) {
  240. xsel.clipboard = xstrdup(xsel.primary);
  241. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  242. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  243. }
  244. }
  245. void
  246. clippaste(const Arg *dummy)
  247. {
  248. Atom clipboard;
  249. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  250. XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
  251. xw.win, CurrentTime);
  252. }
  253. void
  254. selpaste(const Arg *dummy)
  255. {
  256. XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
  257. xw.win, CurrentTime);
  258. }
  259. void
  260. numlock(const Arg *dummy)
  261. {
  262. win.mode ^= MODE_NUMLOCK;
  263. }
  264. void
  265. zoom(const Arg *arg)
  266. {
  267. Arg larg;
  268. larg.f = usedfontsize + arg->f;
  269. zoomabs(&larg);
  270. }
  271. void
  272. zoomabs(const Arg *arg)
  273. {
  274. xunloadfonts();
  275. xloadfonts(usedfont, arg->f);
  276. cresize(0, 0);
  277. redraw();
  278. xhints();
  279. }
  280. void
  281. zoomreset(const Arg *arg)
  282. {
  283. Arg larg;
  284. if (defaultfontsize > 0) {
  285. larg.f = defaultfontsize;
  286. zoomabs(&larg);
  287. }
  288. }
  289. void
  290. ttysend(const Arg *arg)
  291. {
  292. ttywrite(arg->s, strlen(arg->s), 1);
  293. }
  294. int
  295. evcol(XEvent *e)
  296. {
  297. int x = e->xbutton.x - borderpx;
  298. LIMIT(x, 0, win.tw - 1);
  299. return x / win.cw;
  300. }
  301. int
  302. evrow(XEvent *e)
  303. {
  304. int y = e->xbutton.y - borderpx;
  305. LIMIT(y, 0, win.th - 1);
  306. return y / win.ch;
  307. }
  308. void
  309. mousesel(XEvent *e, int done)
  310. {
  311. int type, seltype = SEL_REGULAR;
  312. uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
  313. for (type = 1; type < LEN(selmasks); ++type) {
  314. if (match(selmasks[type], state)) {
  315. seltype = type;
  316. break;
  317. }
  318. }
  319. selextend(evcol(e), evrow(e), seltype, done);
  320. if (done)
  321. setsel(getsel(), e->xbutton.time);
  322. }
  323. void
  324. mousereport(XEvent *e)
  325. {
  326. int len, x = evcol(e), y = evrow(e),
  327. button = e->xbutton.button, state = e->xbutton.state;
  328. char buf[40];
  329. static int ox, oy;
  330. /* from urxvt */
  331. if (e->xbutton.type == MotionNotify) {
  332. if (x == ox && y == oy)
  333. return;
  334. if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
  335. return;
  336. /* MOUSE_MOTION: no reporting if no button is pressed */
  337. if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
  338. return;
  339. button = oldbutton + 32;
  340. ox = x;
  341. oy = y;
  342. } else {
  343. if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
  344. button = 3;
  345. } else {
  346. button -= Button1;
  347. if (button >= 7)
  348. button += 128 - 7;
  349. else if (button >= 3)
  350. button += 64 - 3;
  351. }
  352. if (e->xbutton.type == ButtonPress) {
  353. oldbutton = button;
  354. ox = x;
  355. oy = y;
  356. } else if (e->xbutton.type == ButtonRelease) {
  357. oldbutton = 3;
  358. /* MODE_MOUSEX10: no button release reporting */
  359. if (IS_SET(MODE_MOUSEX10))
  360. return;
  361. if (button == 64 || button == 65)
  362. return;
  363. }
  364. }
  365. if (!IS_SET(MODE_MOUSEX10)) {
  366. button += ((state & ShiftMask ) ? 4 : 0)
  367. + ((state & Mod4Mask ) ? 8 : 0)
  368. + ((state & ControlMask) ? 16 : 0);
  369. }
  370. if (IS_SET(MODE_MOUSESGR)) {
  371. len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
  372. button, x+1, y+1,
  373. e->xbutton.type == ButtonRelease ? 'm' : 'M');
  374. } else if (x < 223 && y < 223) {
  375. len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
  376. 32+button, 32+x+1, 32+y+1);
  377. } else {
  378. return;
  379. }
  380. ttywrite(buf, len, 0);
  381. }
  382. uint
  383. buttonmask(uint button)
  384. {
  385. return button == Button1 ? Button1Mask
  386. : button == Button2 ? Button2Mask
  387. : button == Button3 ? Button3Mask
  388. : button == Button4 ? Button4Mask
  389. : button == Button5 ? Button5Mask
  390. : 0;
  391. }
  392. int
  393. mouseaction(XEvent *e, uint release)
  394. {
  395. MouseShortcut *ms;
  396. /* ignore Button<N>mask for Button<N> - it's set on release */
  397. uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
  398. for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
  399. if (ms->release == release &&
  400. ms->button == e->xbutton.button &&
  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. xw.depth);
  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. /* set alpha value of bg color */
  702. if (opt_alpha)
  703. alpha = strtof(opt_alpha, NULL);
  704. dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha);
  705. dc.col[defaultbg].pixel &= 0x00FFFFFF;
  706. dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24;
  707. loaded = 1;
  708. }
  709. int
  710. xsetcolorname(int x, const char *name)
  711. {
  712. Color ncolor;
  713. if (!BETWEEN(x, 0, dc.collen))
  714. return 1;
  715. if (!xloadcolor(x, name, &ncolor))
  716. return 1;
  717. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  718. dc.col[x] = ncolor;
  719. return 0;
  720. }
  721. /*
  722. * Absolute coordinates.
  723. */
  724. void
  725. xclear(int x1, int y1, int x2, int y2)
  726. {
  727. XftDrawRect(xw.draw,
  728. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  729. x1, y1, x2-x1, y2-y1);
  730. }
  731. void
  732. xhints(void)
  733. {
  734. XClassHint class = {opt_name ? opt_name : termname,
  735. opt_class ? opt_class : termname};
  736. XWMHints wm = {.flags = InputHint, .input = 1};
  737. XSizeHints *sizeh;
  738. sizeh = XAllocSizeHints();
  739. sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
  740. sizeh->height = win.h;
  741. sizeh->width = win.w;
  742. sizeh->height_inc = win.ch;
  743. sizeh->width_inc = win.cw;
  744. sizeh->base_height = 2 * borderpx;
  745. sizeh->base_width = 2 * borderpx;
  746. sizeh->min_height = win.ch + 2 * borderpx;
  747. sizeh->min_width = win.cw + 2 * borderpx;
  748. if (xw.isfixed) {
  749. sizeh->flags |= PMaxSize;
  750. sizeh->min_width = sizeh->max_width = win.w;
  751. sizeh->min_height = sizeh->max_height = win.h;
  752. }
  753. if (xw.gm & (XValue|YValue)) {
  754. sizeh->flags |= USPosition | PWinGravity;
  755. sizeh->x = xw.l;
  756. sizeh->y = xw.t;
  757. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  758. }
  759. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  760. &class);
  761. XFree(sizeh);
  762. }
  763. int
  764. xgeommasktogravity(int mask)
  765. {
  766. switch (mask & (XNegative|YNegative)) {
  767. case 0:
  768. return NorthWestGravity;
  769. case XNegative:
  770. return NorthEastGravity;
  771. case YNegative:
  772. return SouthWestGravity;
  773. }
  774. return SouthEastGravity;
  775. }
  776. int
  777. xloadfont(Font *f, FcPattern *pattern)
  778. {
  779. FcPattern *configured;
  780. FcPattern *match;
  781. FcResult result;
  782. XGlyphInfo extents;
  783. int wantattr, haveattr;
  784. /*
  785. * Manually configure instead of calling XftMatchFont
  786. * so that we can use the configured pattern for
  787. * "missing glyph" lookups.
  788. */
  789. configured = FcPatternDuplicate(pattern);
  790. if (!configured)
  791. return 1;
  792. FcConfigSubstitute(NULL, configured, FcMatchPattern);
  793. XftDefaultSubstitute(xw.dpy, xw.scr, configured);
  794. match = FcFontMatch(NULL, configured, &result);
  795. if (!match) {
  796. FcPatternDestroy(configured);
  797. return 1;
  798. }
  799. if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  800. FcPatternDestroy(configured);
  801. FcPatternDestroy(match);
  802. return 1;
  803. }
  804. if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
  805. XftResultMatch)) {
  806. /*
  807. * Check if xft was unable to find a font with the appropriate
  808. * slant but gave us one anyway. Try to mitigate.
  809. */
  810. if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
  811. &haveattr) != XftResultMatch) || haveattr < wantattr) {
  812. f->badslant = 1;
  813. fputs("font slant does not match\n", stderr);
  814. }
  815. }
  816. if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
  817. XftResultMatch)) {
  818. if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
  819. &haveattr) != XftResultMatch) || haveattr != wantattr) {
  820. f->badweight = 1;
  821. fputs("font weight does not match\n", stderr);
  822. }
  823. }
  824. XftTextExtentsUtf8(xw.dpy, f->match,
  825. (const FcChar8 *) ascii_printable,
  826. strlen(ascii_printable), &extents);
  827. f->set = NULL;
  828. f->pattern = configured;
  829. f->ascent = f->match->ascent;
  830. f->descent = f->match->descent;
  831. f->lbearing = 0;
  832. f->rbearing = f->match->max_advance_width;
  833. f->height = f->ascent + f->descent;
  834. f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
  835. return 0;
  836. }
  837. void
  838. xloadfonts(const char *fontstr, double fontsize)
  839. {
  840. FcPattern *pattern;
  841. double fontval;
  842. if (fontstr[0] == '-')
  843. pattern = XftXlfdParse(fontstr, False, False);
  844. else
  845. pattern = FcNameParse((const FcChar8 *)fontstr);
  846. if (!pattern)
  847. die("can't open font %s\n", fontstr);
  848. if (fontsize > 1) {
  849. FcPatternDel(pattern, FC_PIXEL_SIZE);
  850. FcPatternDel(pattern, FC_SIZE);
  851. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  852. usedfontsize = fontsize;
  853. } else {
  854. if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
  855. FcResultMatch) {
  856. usedfontsize = fontval;
  857. } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
  858. FcResultMatch) {
  859. usedfontsize = -1;
  860. } else {
  861. /*
  862. * Default font size is 12, if none given. This is to
  863. * have a known usedfontsize value.
  864. */
  865. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  866. usedfontsize = 12;
  867. }
  868. defaultfontsize = usedfontsize;
  869. }
  870. if (xloadfont(&dc.font, pattern))
  871. die("can't open font %s\n", fontstr);
  872. if (usedfontsize < 0) {
  873. FcPatternGetDouble(dc.font.match->pattern,
  874. FC_PIXEL_SIZE, 0, &fontval);
  875. usedfontsize = fontval;
  876. if (fontsize == 0)
  877. defaultfontsize = fontval;
  878. }
  879. /* Setting character width and height. */
  880. win.cw = ceilf(dc.font.width * cwscale);
  881. win.ch = ceilf(dc.font.height * chscale);
  882. FcPatternDel(pattern, FC_SLANT);
  883. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  884. if (xloadfont(&dc.ifont, pattern))
  885. die("can't open font %s\n", fontstr);
  886. FcPatternDel(pattern, FC_WEIGHT);
  887. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  888. if (xloadfont(&dc.ibfont, pattern))
  889. die("can't open font %s\n", fontstr);
  890. FcPatternDel(pattern, FC_SLANT);
  891. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  892. if (xloadfont(&dc.bfont, pattern))
  893. die("can't open font %s\n", fontstr);
  894. FcPatternDestroy(pattern);
  895. }
  896. void
  897. xunloadfont(Font *f)
  898. {
  899. XftFontClose(xw.dpy, f->match);
  900. FcPatternDestroy(f->pattern);
  901. if (f->set)
  902. FcFontSetDestroy(f->set);
  903. }
  904. void
  905. xunloadfonts(void)
  906. {
  907. /* Free the loaded fonts in the font cache. */
  908. while (frclen > 0)
  909. XftFontClose(xw.dpy, frc[--frclen].font);
  910. xunloadfont(&dc.font);
  911. xunloadfont(&dc.bfont);
  912. xunloadfont(&dc.ifont);
  913. xunloadfont(&dc.ibfont);
  914. }
  915. int
  916. ximopen(Display *dpy)
  917. {
  918. XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
  919. XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
  920. xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  921. if (xw.ime.xim == NULL)
  922. return 0;
  923. if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
  924. fprintf(stderr, "XSetIMValues: "
  925. "Could not set XNDestroyCallback.\n");
  926. xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
  927. NULL);
  928. if (xw.ime.xic == NULL) {
  929. xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
  930. XIMPreeditNothing | XIMStatusNothing,
  931. XNClientWindow, xw.win,
  932. XNDestroyCallback, &icdestroy,
  933. NULL);
  934. }
  935. if (xw.ime.xic == NULL)
  936. fprintf(stderr, "XCreateIC: Could not create input context.\n");
  937. return 1;
  938. }
  939. void
  940. ximinstantiate(Display *dpy, XPointer client, XPointer call)
  941. {
  942. if (ximopen(dpy))
  943. XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
  944. ximinstantiate, NULL);
  945. }
  946. void
  947. ximdestroy(XIM xim, XPointer client, XPointer call)
  948. {
  949. xw.ime.xim = NULL;
  950. XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
  951. ximinstantiate, NULL);
  952. XFree(xw.ime.spotlist);
  953. }
  954. int
  955. xicdestroy(XIC xim, XPointer client, XPointer call)
  956. {
  957. xw.ime.xic = NULL;
  958. return 1;
  959. }
  960. void
  961. xinit(int cols, int rows)
  962. {
  963. XGCValues gcvalues;
  964. Cursor cursor;
  965. Window parent;
  966. pid_t thispid = getpid();
  967. XColor xmousefg, xmousebg;
  968. XWindowAttributes attr;
  969. XVisualInfo vis;
  970. if (!(xw.dpy = XOpenDisplay(NULL)))
  971. die("can't open display\n");
  972. xw.scr = XDefaultScreen(xw.dpy);
  973. if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) {
  974. parent = XRootWindow(xw.dpy, xw.scr);
  975. xw.depth = 32;
  976. } else {
  977. XGetWindowAttributes(xw.dpy, parent, &attr);
  978. xw.depth = attr.depth;
  979. }
  980. XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis);
  981. xw.vis = vis.visual;
  982. /* font */
  983. if (!FcInit())
  984. die("could not init fontconfig.\n");
  985. usedfont = (opt_font == NULL)? font : opt_font;
  986. xloadfonts(usedfont, 0);
  987. /* colors */
  988. xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None);
  989. xloadcols();
  990. /* adjust fixed window geometry */
  991. win.w = 2 * borderpx + cols * win.cw;
  992. win.h = 2 * borderpx + rows * win.ch;
  993. if (xw.gm & XNegative)
  994. xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
  995. if (xw.gm & YNegative)
  996. xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
  997. /* Events */
  998. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  999. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  1000. xw.attrs.bit_gravity = NorthWestGravity;
  1001. xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
  1002. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1003. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  1004. xw.attrs.colormap = xw.cmap;
  1005. xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
  1006. win.w, win.h, 0, xw.depth, InputOutput,
  1007. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  1008. | CWEventMask | CWColormap, &xw.attrs);
  1009. memset(&gcvalues, 0, sizeof(gcvalues));
  1010. gcvalues.graphics_exposures = False;
  1011. xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth);
  1012. dc.gc = XCreateGC(xw.dpy, xw.buf, GCGraphicsExposures, &gcvalues);
  1013. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  1014. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
  1015. /* font spec buffer */
  1016. xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
  1017. /* Xft rendering context */
  1018. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  1019. /* input methods */
  1020. if (!ximopen(xw.dpy)) {
  1021. XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
  1022. ximinstantiate, NULL);
  1023. }
  1024. /* white cursor, black outline */
  1025. cursor = XCreateFontCursor(xw.dpy, mouseshape);
  1026. XDefineCursor(xw.dpy, xw.win, cursor);
  1027. if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
  1028. xmousefg.red = 0xffff;
  1029. xmousefg.green = 0xffff;
  1030. xmousefg.blue = 0xffff;
  1031. }
  1032. if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
  1033. xmousebg.red = 0x0000;
  1034. xmousebg.green = 0x0000;
  1035. xmousebg.blue = 0x0000;
  1036. }
  1037. XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
  1038. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1039. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  1040. xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
  1041. xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
  1042. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  1043. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  1044. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  1045. PropModeReplace, (uchar *)&thispid, 1);
  1046. win.mode = MODE_NUMLOCK;
  1047. resettitle();
  1048. xhints();
  1049. XMapWindow(xw.dpy, xw.win);
  1050. XSync(xw.dpy, False);
  1051. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
  1052. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
  1053. xsel.primary = NULL;
  1054. xsel.clipboard = NULL;
  1055. xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  1056. if (xsel.xtarget == None)
  1057. xsel.xtarget = XA_STRING;
  1058. }
  1059. int
  1060. xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
  1061. {
  1062. float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
  1063. ushort mode, prevmode = USHRT_MAX;
  1064. Font *font = &dc.font;
  1065. int frcflags = FRC_NORMAL;
  1066. float runewidth = win.cw;
  1067. Rune rune;
  1068. FT_UInt glyphidx;
  1069. FcResult fcres;
  1070. FcPattern *fcpattern, *fontpattern;
  1071. FcFontSet *fcsets[] = { NULL };
  1072. FcCharSet *fccharset;
  1073. int i, f, numspecs = 0;
  1074. for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
  1075. /* Fetch rune and mode for current glyph. */
  1076. rune = glyphs[i].u;
  1077. mode = glyphs[i].mode;
  1078. /* Skip dummy wide-character spacing. */
  1079. if (mode == ATTR_WDUMMY)
  1080. continue;
  1081. /* Determine font for glyph if different from previous glyph. */
  1082. if (prevmode != mode) {
  1083. prevmode = mode;
  1084. font = &dc.font;
  1085. frcflags = FRC_NORMAL;
  1086. runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
  1087. if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
  1088. font = &dc.ibfont;
  1089. frcflags = FRC_ITALICBOLD;
  1090. } else if (mode & ATTR_ITALIC) {
  1091. font = &dc.ifont;
  1092. frcflags = FRC_ITALIC;
  1093. } else if (mode & ATTR_BOLD) {
  1094. font = &dc.bfont;
  1095. frcflags = FRC_BOLD;
  1096. }
  1097. yp = winy + font->ascent;
  1098. }
  1099. /* Lookup character index with default font. */
  1100. glyphidx = XftCharIndex(xw.dpy, font->match, rune);
  1101. if (glyphidx) {
  1102. specs[numspecs].font = font->match;
  1103. specs[numspecs].glyph = glyphidx;
  1104. specs[numspecs].x = (short)xp;
  1105. specs[numspecs].y = (short)yp;
  1106. xp += runewidth;
  1107. numspecs++;
  1108. continue;
  1109. }
  1110. /* Fallback on font cache, search the font cache for match. */
  1111. for (f = 0; f < frclen; f++) {
  1112. glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
  1113. /* Everything correct. */
  1114. if (glyphidx && frc[f].flags == frcflags)
  1115. break;
  1116. /* We got a default font for a not found glyph. */
  1117. if (!glyphidx && frc[f].flags == frcflags
  1118. && frc[f].unicodep == rune) {
  1119. break;
  1120. }
  1121. }
  1122. /* Nothing was found. Use fontconfig to find matching font. */
  1123. if (f >= frclen) {
  1124. if (!font->set)
  1125. font->set = FcFontSort(0, font->pattern,
  1126. 1, 0, &fcres);
  1127. fcsets[0] = font->set;
  1128. /*
  1129. * Nothing was found in the cache. Now use
  1130. * some dozen of Fontconfig calls to get the
  1131. * font for one single character.
  1132. *
  1133. * Xft and fontconfig are design failures.
  1134. */
  1135. fcpattern = FcPatternDuplicate(font->pattern);
  1136. fccharset = FcCharSetCreate();
  1137. FcCharSetAddChar(fccharset, rune);
  1138. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  1139. fccharset);
  1140. FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
  1141. FcConfigSubstitute(0, fcpattern,
  1142. FcMatchPattern);
  1143. FcDefaultSubstitute(fcpattern);
  1144. fontpattern = FcFontSetMatch(0, fcsets, 1,
  1145. fcpattern, &fcres);
  1146. /* Allocate memory for the new cache entry. */
  1147. if (frclen >= frccap) {
  1148. frccap += 16;
  1149. frc = xrealloc(frc, frccap * sizeof(Fontcache));
  1150. }
  1151. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  1152. fontpattern);
  1153. if (!frc[frclen].font)
  1154. die("XftFontOpenPattern failed seeking fallback font: %s\n",
  1155. strerror(errno));
  1156. frc[frclen].flags = frcflags;
  1157. frc[frclen].unicodep = rune;
  1158. glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
  1159. f = frclen;
  1160. frclen++;
  1161. FcPatternDestroy(fcpattern);
  1162. FcCharSetDestroy(fccharset);
  1163. }
  1164. specs[numspecs].font = frc[f].font;
  1165. specs[numspecs].glyph = glyphidx;
  1166. specs[numspecs].x = (short)xp;
  1167. specs[numspecs].y = (short)yp;
  1168. xp += runewidth;
  1169. numspecs++;
  1170. }
  1171. return numspecs;
  1172. }
  1173. void
  1174. xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
  1175. {
  1176. int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
  1177. int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
  1178. width = charlen * win.cw;
  1179. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  1180. XRenderColor colfg, colbg;
  1181. XRectangle r;
  1182. /* Fallback on color display for attributes not supported by the font */
  1183. if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
  1184. if (dc.ibfont.badslant || dc.ibfont.badweight)
  1185. base.fg = defaultattr;
  1186. } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
  1187. (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
  1188. base.fg = defaultattr;
  1189. }
  1190. if (IS_TRUECOL(base.fg)) {
  1191. colfg.alpha = 0xffff;
  1192. colfg.red = TRUERED(base.fg);
  1193. colfg.green = TRUEGREEN(base.fg);
  1194. colfg.blue = TRUEBLUE(base.fg);
  1195. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  1196. fg = &truefg;
  1197. } else {
  1198. fg = &dc.col[base.fg];
  1199. }
  1200. if (IS_TRUECOL(base.bg)) {
  1201. colbg.alpha = 0xffff;
  1202. colbg.green = TRUEGREEN(base.bg);
  1203. colbg.red = TRUERED(base.bg);
  1204. colbg.blue = TRUEBLUE(base.bg);
  1205. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  1206. bg = &truebg;
  1207. } else {
  1208. bg = &dc.col[base.bg];
  1209. }
  1210. /* Change basic system colors [0-7] to bright system colors [8-15] */
  1211. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
  1212. fg = &dc.col[base.fg + 8];
  1213. if (IS_SET(MODE_REVERSE)) {
  1214. if (fg == &dc.col[defaultfg]) {
  1215. fg = &dc.col[defaultbg];
  1216. } else {
  1217. colfg.red = ~fg->color.red;
  1218. colfg.green = ~fg->color.green;
  1219. colfg.blue = ~fg->color.blue;
  1220. colfg.alpha = fg->color.alpha;
  1221. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  1222. &revfg);
  1223. fg = &revfg;
  1224. }
  1225. if (bg == &dc.col[defaultbg]) {
  1226. bg = &dc.col[defaultfg];
  1227. } else {
  1228. colbg.red = ~bg->color.red;
  1229. colbg.green = ~bg->color.green;
  1230. colbg.blue = ~bg->color.blue;
  1231. colbg.alpha = bg->color.alpha;
  1232. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  1233. &revbg);
  1234. bg = &revbg;
  1235. }
  1236. }
  1237. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
  1238. colfg.red = fg->color.red / 2;
  1239. colfg.green = fg->color.green / 2;
  1240. colfg.blue = fg->color.blue / 2;
  1241. colfg.alpha = fg->color.alpha;
  1242. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  1243. fg = &revfg;
  1244. }
  1245. if (base.mode & ATTR_REVERSE) {
  1246. temp = fg;
  1247. fg = bg;
  1248. bg = temp;
  1249. }
  1250. if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
  1251. fg = bg;
  1252. if (base.mode & ATTR_INVISIBLE)
  1253. fg = bg;
  1254. /* Intelligent cleaning up of the borders. */
  1255. if (x == 0) {
  1256. xclear(0, (y == 0)? 0 : winy, borderpx,
  1257. winy + win.ch +
  1258. ((winy + win.ch >= borderpx + win.th)? win.h : 0));
  1259. }
  1260. if (winx + width >= borderpx + win.tw) {
  1261. xclear(winx + width, (y == 0)? 0 : winy, win.w,
  1262. ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
  1263. }
  1264. if (y == 0)
  1265. xclear(winx, 0, winx + width, borderpx);
  1266. if (winy + win.ch >= borderpx + win.th)
  1267. xclear(winx, winy + win.ch, winx + width, win.h);
  1268. /* Clean up the region we want to draw to. */
  1269. XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
  1270. /* Set the clip region because Xft is sometimes dirty. */
  1271. r.x = 0;
  1272. r.y = 0;
  1273. r.height = win.ch;
  1274. r.width = width;
  1275. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  1276. /* Render the glyphs. */
  1277. XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
  1278. /* Render underline and strikethrough. */
  1279. if (base.mode & ATTR_UNDERLINE) {
  1280. XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
  1281. width, 1);
  1282. }
  1283. if (base.mode & ATTR_STRUCK) {
  1284. XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
  1285. width, 1);
  1286. }
  1287. /* Reset clip to none. */
  1288. XftDrawSetClip(xw.draw, 0);
  1289. }
  1290. void
  1291. xdrawglyph(Glyph g, int x, int y)
  1292. {
  1293. int numspecs;
  1294. XftGlyphFontSpec spec;
  1295. numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
  1296. xdrawglyphfontspecs(&spec, g, numspecs, x, y);
  1297. }
  1298. void
  1299. xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
  1300. {
  1301. Color drawcol;
  1302. /* remove the old cursor */
  1303. if (selected(ox, oy))
  1304. og.mode ^= ATTR_REVERSE;
  1305. xdrawglyph(og, ox, oy);
  1306. if (IS_SET(MODE_HIDE))
  1307. return;
  1308. /*
  1309. * Select the right color for the right mode.
  1310. */
  1311. g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
  1312. if (IS_SET(MODE_REVERSE)) {
  1313. g.mode |= ATTR_REVERSE;
  1314. g.bg = defaultfg;
  1315. if (selected(cx, cy)) {
  1316. drawcol = dc.col[defaultcs];
  1317. g.fg = defaultrcs;
  1318. } else {
  1319. drawcol = dc.col[defaultrcs];
  1320. g.fg = defaultcs;
  1321. }
  1322. } else {
  1323. if (selected(cx, cy)) {
  1324. g.fg = defaultfg;
  1325. g.bg = defaultrcs;
  1326. } else {
  1327. g.fg = defaultbg;
  1328. g.bg = defaultcs;
  1329. }
  1330. drawcol = dc.col[g.bg];
  1331. }
  1332. /* draw the new one */
  1333. if (IS_SET(MODE_FOCUSED)) {
  1334. switch (win.cursor) {
  1335. case 7: /* st extension */
  1336. g.u = 0x2603; /* snowman (U+2603) */
  1337. /* FALLTHROUGH */
  1338. case 0: /* Blinking Block */
  1339. case 1: /* Blinking Block (Default) */
  1340. case 2: /* Steady Block */
  1341. xdrawglyph(g, cx, cy);
  1342. break;
  1343. case 3: /* Blinking Underline */
  1344. case 4: /* Steady Underline */
  1345. XftDrawRect(xw.draw, &drawcol,
  1346. borderpx + cx * win.cw,
  1347. borderpx + (cy + 1) * win.ch - \
  1348. cursorthickness,
  1349. win.cw, cursorthickness);
  1350. break;
  1351. case 5: /* Blinking bar */
  1352. case 6: /* Steady bar */
  1353. XftDrawRect(xw.draw, &drawcol,
  1354. borderpx + cx * win.cw,
  1355. borderpx + cy * win.ch,
  1356. cursorthickness, win.ch);
  1357. break;
  1358. }
  1359. } else {
  1360. XftDrawRect(xw.draw, &drawcol,
  1361. borderpx + cx * win.cw,
  1362. borderpx + cy * win.ch,
  1363. win.cw - 1, 1);
  1364. XftDrawRect(xw.draw, &drawcol,
  1365. borderpx + cx * win.cw,
  1366. borderpx + cy * win.ch,
  1367. 1, win.ch - 1);
  1368. XftDrawRect(xw.draw, &drawcol,
  1369. borderpx + (cx + 1) * win.cw - 1,
  1370. borderpx + cy * win.ch,
  1371. 1, win.ch - 1);
  1372. XftDrawRect(xw.draw, &drawcol,
  1373. borderpx + cx * win.cw,
  1374. borderpx + (cy + 1) * win.ch - 1,
  1375. win.cw, 1);
  1376. }
  1377. }
  1378. void
  1379. xsetenv(void)
  1380. {
  1381. char buf[sizeof(long) * 8 + 1];
  1382. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1383. setenv("WINDOWID", buf, 1);
  1384. }
  1385. void
  1386. xseticontitle(char *p)
  1387. {
  1388. XTextProperty prop;
  1389. DEFAULT(p, opt_title);
  1390. if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1391. &prop) != Success)
  1392. return;
  1393. XSetWMIconName(xw.dpy, xw.win, &prop);
  1394. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
  1395. XFree(prop.value);
  1396. }
  1397. void
  1398. xsettitle(char *p)
  1399. {
  1400. XTextProperty prop;
  1401. DEFAULT(p, opt_title);
  1402. if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1403. &prop) != Success)
  1404. return;
  1405. XSetWMName(xw.dpy, xw.win, &prop);
  1406. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  1407. XFree(prop.value);
  1408. }
  1409. int
  1410. xstartdraw(void)
  1411. {
  1412. return IS_SET(MODE_VISIBLE);
  1413. }
  1414. void
  1415. xdrawline(Line line, int x1, int y1, int x2)
  1416. {
  1417. int i, x, ox, numspecs;
  1418. Glyph base, new;
  1419. XftGlyphFontSpec *specs = xw.specbuf;
  1420. numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
  1421. i = ox = 0;
  1422. for (x = x1; x < x2 && i < numspecs; x++) {
  1423. new = line[x];
  1424. if (new.mode == ATTR_WDUMMY)
  1425. continue;
  1426. if (selected(x, y1))
  1427. new.mode ^= ATTR_REVERSE;
  1428. if (i > 0 && ATTRCMP(base, new)) {
  1429. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1430. specs += i;
  1431. numspecs -= i;
  1432. i = 0;
  1433. }
  1434. if (i == 0) {
  1435. ox = x;
  1436. base = new;
  1437. }
  1438. i++;
  1439. }
  1440. if (i > 0)
  1441. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1442. }
  1443. void
  1444. xfinishdraw(void)
  1445. {
  1446. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
  1447. win.h, 0, 0);
  1448. XSetForeground(xw.dpy, dc.gc,
  1449. dc.col[IS_SET(MODE_REVERSE)?
  1450. defaultfg : defaultbg].pixel);
  1451. }
  1452. void
  1453. xximspot(int x, int y)
  1454. {
  1455. if (xw.ime.xic == NULL)
  1456. return;
  1457. xw.ime.spot.x = borderpx + x * win.cw;
  1458. xw.ime.spot.y = borderpx + (y + 1) * win.ch;
  1459. XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
  1460. }
  1461. void
  1462. expose(XEvent *ev)
  1463. {
  1464. redraw();
  1465. }
  1466. void
  1467. visibility(XEvent *ev)
  1468. {
  1469. XVisibilityEvent *e = &ev->xvisibility;
  1470. MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
  1471. }
  1472. void
  1473. unmap(XEvent *ev)
  1474. {
  1475. win.mode &= ~MODE_VISIBLE;
  1476. }
  1477. void
  1478. xsetpointermotion(int set)
  1479. {
  1480. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  1481. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  1482. }
  1483. void
  1484. xsetmode(int set, unsigned int flags)
  1485. {
  1486. int mode = win.mode;
  1487. MODBIT(win.mode, set, flags);
  1488. if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
  1489. redraw();
  1490. }
  1491. int
  1492. xsetcursor(int cursor)
  1493. {
  1494. if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
  1495. return 1;
  1496. win.cursor = cursor;
  1497. return 0;
  1498. }
  1499. void
  1500. xseturgency(int add)
  1501. {
  1502. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1503. MODBIT(h->flags, add, XUrgencyHint);
  1504. XSetWMHints(xw.dpy, xw.win, h);
  1505. XFree(h);
  1506. }
  1507. void
  1508. xbell(void)
  1509. {
  1510. if (!(IS_SET(MODE_FOCUSED)))
  1511. xseturgency(1);
  1512. if (bellvolume)
  1513. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  1514. }
  1515. void
  1516. focus(XEvent *ev)
  1517. {
  1518. XFocusChangeEvent *e = &ev->xfocus;
  1519. if (e->mode == NotifyGrab)
  1520. return;
  1521. if (ev->type == FocusIn) {
  1522. if (xw.ime.xic)
  1523. XSetICFocus(xw.ime.xic);
  1524. win.mode |= MODE_FOCUSED;
  1525. xseturgency(0);
  1526. if (IS_SET(MODE_FOCUS))
  1527. ttywrite("\033[I", 3, 0);
  1528. } else {
  1529. if (xw.ime.xic)
  1530. XUnsetICFocus(xw.ime.xic);
  1531. win.mode &= ~MODE_FOCUSED;
  1532. if (IS_SET(MODE_FOCUS))
  1533. ttywrite("\033[O", 3, 0);
  1534. }
  1535. }
  1536. int
  1537. match(uint mask, uint state)
  1538. {
  1539. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  1540. }
  1541. char*
  1542. kmap(KeySym k, uint state)
  1543. {
  1544. Key *kp;
  1545. int i;
  1546. /* Check for mapped keys out of X11 function keys. */
  1547. for (i = 0; i < LEN(mappedkeys); i++) {
  1548. if (mappedkeys[i] == k)
  1549. break;
  1550. }
  1551. if (i == LEN(mappedkeys)) {
  1552. if ((k & 0xFFFF) < 0xFD00)
  1553. return NULL;
  1554. }
  1555. for (kp = key; kp < key + LEN(key); kp++) {
  1556. if (kp->k != k)
  1557. continue;
  1558. if (!match(kp->mask, state))
  1559. continue;
  1560. if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  1561. continue;
  1562. if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
  1563. continue;
  1564. if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  1565. continue;
  1566. return kp->s;
  1567. }
  1568. return NULL;
  1569. }
  1570. void
  1571. kpress(XEvent *ev)
  1572. {
  1573. XKeyEvent *e = &ev->xkey;
  1574. KeySym ksym;
  1575. char buf[64], *customkey;
  1576. int len;
  1577. Rune c;
  1578. Status status;
  1579. Shortcut *bp;
  1580. if (IS_SET(MODE_KBDLOCK))
  1581. return;
  1582. if (xw.ime.xic)
  1583. len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
  1584. else
  1585. len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
  1586. /* 1. shortcuts */
  1587. for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  1588. if (ksym == bp->keysym && match(bp->mod, e->state)) {
  1589. bp->func(&(bp->arg));
  1590. return;
  1591. }
  1592. }
  1593. /* 2. custom keys from config.h */
  1594. if ((customkey = kmap(ksym, e->state))) {
  1595. ttywrite(customkey, strlen(customkey), 1);
  1596. return;
  1597. }
  1598. /* 3. composed string from input method */
  1599. if (len == 0)
  1600. return;
  1601. if (len == 1 && e->state & Mod1Mask) {
  1602. if (IS_SET(MODE_8BIT)) {
  1603. if (*buf < 0177) {
  1604. c = *buf | 0x80;
  1605. len = utf8encode(c, buf);
  1606. }
  1607. } else {
  1608. buf[1] = buf[0];
  1609. buf[0] = '\033';
  1610. len = 2;
  1611. }
  1612. }
  1613. ttywrite(buf, len, 1);
  1614. }
  1615. void
  1616. cmessage(XEvent *e)
  1617. {
  1618. /*
  1619. * See xembed specs
  1620. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  1621. */
  1622. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1623. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1624. win.mode |= MODE_FOCUSED;
  1625. xseturgency(0);
  1626. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1627. win.mode &= ~MODE_FOCUSED;
  1628. }
  1629. } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
  1630. ttyhangup();
  1631. exit(0);
  1632. }
  1633. }
  1634. void
  1635. resize(XEvent *e)
  1636. {
  1637. if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
  1638. return;
  1639. cresize(e->xconfigure.width, e->xconfigure.height);
  1640. }
  1641. void
  1642. run(void)
  1643. {
  1644. XEvent ev;
  1645. int w = win.w, h = win.h;
  1646. fd_set rfd;
  1647. int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
  1648. struct timespec seltv, *tv, now, lastblink, trigger;
  1649. double timeout;
  1650. /* Waiting for window mapping */
  1651. do {
  1652. XNextEvent(xw.dpy, &ev);
  1653. /*
  1654. * This XFilterEvent call is required because of XOpenIM. It
  1655. * does filter out the key event and some client message for
  1656. * the input method too.
  1657. */
  1658. if (XFilterEvent(&ev, None))
  1659. continue;
  1660. if (ev.type == ConfigureNotify) {
  1661. w = ev.xconfigure.width;
  1662. h = ev.xconfigure.height;
  1663. }
  1664. } while (ev.type != MapNotify);
  1665. ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
  1666. cresize(w, h);
  1667. for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
  1668. FD_ZERO(&rfd);
  1669. FD_SET(ttyfd, &rfd);
  1670. FD_SET(xfd, &rfd);
  1671. if (XPending(xw.dpy))
  1672. timeout = 0; /* existing events might not set xfd */
  1673. seltv.tv_sec = timeout / 1E3;
  1674. seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
  1675. tv = timeout >= 0 ? &seltv : NULL;
  1676. if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  1677. if (errno == EINTR)
  1678. continue;
  1679. die("select failed: %s\n", strerror(errno));
  1680. }
  1681. clock_gettime(CLOCK_MONOTONIC, &now);
  1682. if (FD_ISSET(ttyfd, &rfd))
  1683. ttyread();
  1684. xev = 0;
  1685. while (XPending(xw.dpy)) {
  1686. xev = 1;
  1687. XNextEvent(xw.dpy, &ev);
  1688. if (XFilterEvent(&ev, None))
  1689. continue;
  1690. if (handler[ev.type])
  1691. (handler[ev.type])(&ev);
  1692. }
  1693. /*
  1694. * To reduce flicker and tearing, when new content or event
  1695. * triggers drawing, we first wait a bit to ensure we got
  1696. * everything, and if nothing new arrives - we draw.
  1697. * We start with trying to wait minlatency ms. If more content
  1698. * arrives sooner, we retry with shorter and shorter periods,
  1699. * and eventually draw even without idle after maxlatency ms.
  1700. * Typically this results in low latency while interacting,
  1701. * maximum latency intervals during `cat huge.txt`, and perfect
  1702. * sync with periodic updates from animations/key-repeats/etc.
  1703. */
  1704. if (FD_ISSET(ttyfd, &rfd) || xev) {
  1705. if (!drawing) {
  1706. trigger = now;
  1707. drawing = 1;
  1708. }
  1709. timeout = (maxlatency - TIMEDIFF(now, trigger)) \
  1710. / maxlatency * minlatency;
  1711. if (timeout > 0)
  1712. continue; /* we have time, try to find idle */
  1713. }
  1714. /* idle detected or maxlatency exhausted -> draw */
  1715. timeout = -1;
  1716. if (blinktimeout && tattrset(ATTR_BLINK)) {
  1717. timeout = blinktimeout - TIMEDIFF(now, lastblink);
  1718. if (timeout <= 0) {
  1719. if (-timeout > blinktimeout) /* start visible */
  1720. win.mode |= MODE_BLINK;
  1721. win.mode ^= MODE_BLINK;
  1722. tsetdirtattr(ATTR_BLINK);
  1723. lastblink = now;
  1724. timeout = blinktimeout;
  1725. }
  1726. }
  1727. draw();
  1728. XFlush(xw.dpy);
  1729. drawing = 0;
  1730. }
  1731. }
  1732. void
  1733. usage(void)
  1734. {
  1735. die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
  1736. " [-n name] [-o file]\n"
  1737. " [-T title] [-t title] [-w windowid]"
  1738. " [[-e] command [args ...]]\n"
  1739. " %s [-aiv] [-c class] [-f font] [-g geometry]"
  1740. " [-n name] [-o file]\n"
  1741. " [-T title] [-t title] [-w windowid] -l line"
  1742. " [stty_args ...]\n", argv0, argv0);
  1743. }
  1744. int
  1745. main(int argc, char *argv[])
  1746. {
  1747. xw.l = xw.t = 0;
  1748. xw.isfixed = False;
  1749. xsetcursor(cursorshape);
  1750. ARGBEGIN {
  1751. case 'a':
  1752. allowaltscreen = 0;
  1753. break;
  1754. case 'A':
  1755. opt_alpha = EARGF(usage());
  1756. break;
  1757. case 'c':
  1758. opt_class = EARGF(usage());
  1759. break;
  1760. case 'e':
  1761. if (argc > 0)
  1762. --argc, ++argv;
  1763. goto run;
  1764. case 'f':
  1765. opt_font = EARGF(usage());
  1766. break;
  1767. case 'g':
  1768. xw.gm = XParseGeometry(EARGF(usage()),
  1769. &xw.l, &xw.t, &cols, &rows);
  1770. break;
  1771. case 'i':
  1772. xw.isfixed = 1;
  1773. break;
  1774. case 'o':
  1775. opt_io = EARGF(usage());
  1776. break;
  1777. case 'l':
  1778. opt_line = EARGF(usage());
  1779. break;
  1780. case 'n':
  1781. opt_name = EARGF(usage());
  1782. break;
  1783. case 't':
  1784. case 'T':
  1785. opt_title = EARGF(usage());
  1786. break;
  1787. case 'w':
  1788. opt_embed = EARGF(usage());
  1789. break;
  1790. case 'v':
  1791. die("%s " VERSION "\n", argv0);
  1792. break;
  1793. default:
  1794. usage();
  1795. } ARGEND;
  1796. run:
  1797. if (argc > 0) /* eat all remaining arguments */
  1798. opt_cmd = argv;
  1799. if (!opt_title)
  1800. opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
  1801. setlocale(LC_CTYPE, "");
  1802. XSetLocaleModifiers("");
  1803. cols = MAX(cols, 1);
  1804. rows = MAX(rows, 1);
  1805. tnew(cols, rows);
  1806. xinit(cols, rows);
  1807. xsetenv();
  1808. selinit();
  1809. run();
  1810. return 0;
  1811. }