ST patched with stuff from https://st.suckless.org/patches/ to work as a lighter alternative to XTerm
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.

2259 lines
51 KiB

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