Prepare 6.2 release.
[dwm.git] / drw.c
1 /* See LICENSE file for copyright and license details. */
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <X11/Xlib.h>
6 #include <X11/Xft/Xft.h>
7
8 #include "drw.h"
9 #include "util.h"
10
11 #define UTF_INVALID 0xFFFD
12 #define UTF_SIZ     4
13
14 static const unsigned char utfbyte[UTF_SIZ + 1] = {0x80,    0, 0xC0, 0xE0, 0xF0};
15 static const unsigned char utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
16 static const long utfmin[UTF_SIZ + 1] = {       0,    0,  0x80,  0x800,  0x10000};
17 static const long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
18
19 static long
20 utf8decodebyte(const char c, size_t *i)
21 {
22         for (*i = 0; *i < (UTF_SIZ + 1); ++(*i))
23                 if (((unsigned char)c & utfmask[*i]) == utfbyte[*i])
24                         return (unsigned char)c & ~utfmask[*i];
25         return 0;
26 }
27
28 static size_t
29 utf8validate(long *u, size_t i)
30 {
31         if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
32                 *u = UTF_INVALID;
33         for (i = 1; *u > utfmax[i]; ++i)
34                 ;
35         return i;
36 }
37
38 static size_t
39 utf8decode(const char *c, long *u, size_t clen)
40 {
41         size_t i, j, len, type;
42         long udecoded;
43
44         *u = UTF_INVALID;
45         if (!clen)
46                 return 0;
47         udecoded = utf8decodebyte(c[0], &len);
48         if (!BETWEEN(len, 1, UTF_SIZ))
49                 return 1;
50         for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
51                 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
52                 if (type)
53                         return j;
54         }
55         if (j < len)
56                 return 0;
57         *u = udecoded;
58         utf8validate(u, len);
59
60         return len;
61 }
62
63 Drw *
64 drw_create(Display *dpy, int screen, Window root, unsigned int w, unsigned int h)
65 {
66         Drw *drw = ecalloc(1, sizeof(Drw));
67
68         drw->dpy = dpy;
69         drw->screen = screen;
70         drw->root = root;
71         drw->w = w;
72         drw->h = h;
73         drw->drawable = XCreatePixmap(dpy, root, w, h, DefaultDepth(dpy, screen));
74         drw->gc = XCreateGC(dpy, root, 0, NULL);
75         XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter);
76
77         return drw;
78 }
79
80 void
81 drw_resize(Drw *drw, unsigned int w, unsigned int h)
82 {
83         if (!drw)
84                 return;
85
86         drw->w = w;
87         drw->h = h;
88         if (drw->drawable)
89                 XFreePixmap(drw->dpy, drw->drawable);
90         drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, DefaultDepth(drw->dpy, drw->screen));
91 }
92
93 void
94 drw_free(Drw *drw)
95 {
96         XFreePixmap(drw->dpy, drw->drawable);
97         XFreeGC(drw->dpy, drw->gc);
98         free(drw);
99 }
100
101 /* This function is an implementation detail. Library users should use
102  * drw_fontset_create instead.
103  */
104 static Fnt *
105 xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern)
106 {
107         Fnt *font;
108         XftFont *xfont = NULL;
109         FcPattern *pattern = NULL;
110
111         if (fontname) {
112                 /* Using the pattern found at font->xfont->pattern does not yield the
113                  * same substitution results as using the pattern returned by
114                  * FcNameParse; using the latter results in the desired fallback
115                  * behaviour whereas the former just results in missing-character
116                  * rectangles being drawn, at least with some fonts. */
117                 if (!(xfont = XftFontOpenName(drw->dpy, drw->screen, fontname))) {
118                         fprintf(stderr, "error, cannot load font from name: '%s'\n", fontname);
119                         return NULL;
120                 }
121                 if (!(pattern = FcNameParse((FcChar8 *) fontname))) {
122                         fprintf(stderr, "error, cannot parse font name to pattern: '%s'\n", fontname);
123                         XftFontClose(drw->dpy, xfont);
124                         return NULL;
125                 }
126         } else if (fontpattern) {
127                 if (!(xfont = XftFontOpenPattern(drw->dpy, fontpattern))) {
128                         fprintf(stderr, "error, cannot load font from pattern.\n");
129                         return NULL;
130                 }
131         } else {
132                 die("no font specified.");
133         }
134
135         /* Do not allow using color fonts. This is a workaround for a BadLength
136          * error from Xft with color glyphs. Modelled on the Xterm workaround. See
137          * https://bugzilla.redhat.com/show_bug.cgi?id=1498269
138          * https://lists.suckless.org/dev/1701/30932.html
139          * https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=916349
140          * and lots more all over the internet.
141          */
142         FcBool iscol;
143         if(FcPatternGetBool(xfont->pattern, FC_COLOR, 0, &iscol) == FcResultMatch && iscol) {
144                 XftFontClose(drw->dpy, xfont);
145                 return NULL;
146         }
147
148         font = ecalloc(1, sizeof(Fnt));
149         font->xfont = xfont;
150         font->pattern = pattern;
151         font->h = xfont->ascent + xfont->descent;
152         font->dpy = drw->dpy;
153
154         return font;
155 }
156
157 static void
158 xfont_free(Fnt *font)
159 {
160         if (!font)
161                 return;
162         if (font->pattern)
163                 FcPatternDestroy(font->pattern);
164         XftFontClose(font->dpy, font->xfont);
165         free(font);
166 }
167
168 Fnt*
169 drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount)
170 {
171         Fnt *cur, *ret = NULL;
172         size_t i;
173
174         if (!drw || !fonts)
175                 return NULL;
176
177         for (i = 1; i <= fontcount; i++) {
178                 if ((cur = xfont_create(drw, fonts[fontcount - i], NULL))) {
179                         cur->next = ret;
180                         ret = cur;
181                 }
182         }
183         return (drw->fonts = ret);
184 }
185
186 void
187 drw_fontset_free(Fnt *font)
188 {
189         if (font) {
190                 drw_fontset_free(font->next);
191                 xfont_free(font);
192         }
193 }
194
195 void
196 drw_clr_create(Drw *drw, Clr *dest, const char *clrname)
197 {
198         if (!drw || !dest || !clrname)
199                 return;
200
201         if (!XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen),
202                                DefaultColormap(drw->dpy, drw->screen),
203                                clrname, dest))
204                 die("error, cannot allocate color '%s'", clrname);
205 }
206
207 /* Wrapper to create color schemes. The caller has to call free(3) on the
208  * returned color scheme when done using it. */
209 Clr *
210 drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount)
211 {
212         size_t i;
213         Clr *ret;
214
215         /* need at least two colors for a scheme */
216         if (!drw || !clrnames || clrcount < 2 || !(ret = ecalloc(clrcount, sizeof(XftColor))))
217                 return NULL;
218
219         for (i = 0; i < clrcount; i++)
220                 drw_clr_create(drw, &ret[i], clrnames[i]);
221         return ret;
222 }
223
224 void
225 drw_setfontset(Drw *drw, Fnt *set)
226 {
227         if (drw)
228                 drw->fonts = set;
229 }
230
231 void
232 drw_setscheme(Drw *drw, Clr *scm)
233 {
234         if (drw)
235                 drw->scheme = scm;
236 }
237
238 void
239 drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert)
240 {
241         if (!drw || !drw->scheme)
242                 return;
243         XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel);
244         if (filled)
245                 XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
246         else
247                 XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1);
248 }
249
250 int
251 drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert)
252 {
253         char buf[1024];
254         int ty;
255         unsigned int ew;
256         XftDraw *d = NULL;
257         Fnt *usedfont, *curfont, *nextfont;
258         size_t i, len;
259         int utf8strlen, utf8charlen, render = x || y || w || h;
260         long utf8codepoint = 0;
261         const char *utf8str;
262         FcCharSet *fccharset;
263         FcPattern *fcpattern;
264         FcPattern *match;
265         XftResult result;
266         int charexists = 0;
267
268         if (!drw || (render && !drw->scheme) || !text || !drw->fonts)
269                 return 0;
270
271         if (!render) {
272                 w = ~w;
273         } else {
274                 XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel);
275                 XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
276                 d = XftDrawCreate(drw->dpy, drw->drawable,
277                                   DefaultVisual(drw->dpy, drw->screen),
278                                   DefaultColormap(drw->dpy, drw->screen));
279                 x += lpad;
280                 w -= lpad;
281         }
282
283         usedfont = drw->fonts;
284         while (1) {
285                 utf8strlen = 0;
286                 utf8str = text;
287                 nextfont = NULL;
288                 while (*text) {
289                         utf8charlen = utf8decode(text, &utf8codepoint, UTF_SIZ);
290                         for (curfont = drw->fonts; curfont; curfont = curfont->next) {
291                                 charexists = charexists || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint);
292                                 if (charexists) {
293                                         if (curfont == usedfont) {
294                                                 utf8strlen += utf8charlen;
295                                                 text += utf8charlen;
296                                         } else {
297                                                 nextfont = curfont;
298                                         }
299                                         break;
300                                 }
301                         }
302
303                         if (!charexists || nextfont)
304                                 break;
305                         else
306                                 charexists = 0;
307                 }
308
309                 if (utf8strlen) {
310                         drw_font_getexts(usedfont, utf8str, utf8strlen, &ew, NULL);
311                         /* shorten text if necessary */
312                         for (len = MIN(utf8strlen, sizeof(buf) - 1); len && ew > w; len--)
313                                 drw_font_getexts(usedfont, utf8str, len, &ew, NULL);
314
315                         if (len) {
316                                 memcpy(buf, utf8str, len);
317                                 buf[len] = '\0';
318                                 if (len < utf8strlen)
319                                         for (i = len; i && i > len - 3; buf[--i] = '.')
320                                                 ; /* NOP */
321
322                                 if (render) {
323                                         ty = y + (h - usedfont->h) / 2 + usedfont->xfont->ascent;
324                                         XftDrawStringUtf8(d, &drw->scheme[invert ? ColBg : ColFg],
325                                                           usedfont->xfont, x, ty, (XftChar8 *)buf, len);
326                                 }
327                                 x += ew;
328                                 w -= ew;
329                         }
330                 }
331
332                 if (!*text) {
333                         break;
334                 } else if (nextfont) {
335                         charexists = 0;
336                         usedfont = nextfont;
337                 } else {
338                         /* Regardless of whether or not a fallback font is found, the
339                          * character must be drawn. */
340                         charexists = 1;
341
342                         fccharset = FcCharSetCreate();
343                         FcCharSetAddChar(fccharset, utf8codepoint);
344
345                         if (!drw->fonts->pattern) {
346                                 /* Refer to the comment in xfont_create for more information. */
347                                 die("the first font in the cache must be loaded from a font string.");
348                         }
349
350                         fcpattern = FcPatternDuplicate(drw->fonts->pattern);
351                         FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
352                         FcPatternAddBool(fcpattern, FC_SCALABLE, FcTrue);
353                         FcPatternAddBool(fcpattern, FC_COLOR, FcFalse);
354
355                         FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
356                         FcDefaultSubstitute(fcpattern);
357                         match = XftFontMatch(drw->dpy, drw->screen, fcpattern, &result);
358
359                         FcCharSetDestroy(fccharset);
360                         FcPatternDestroy(fcpattern);
361
362                         if (match) {
363                                 usedfont = xfont_create(drw, NULL, match);
364                                 if (usedfont && XftCharExists(drw->dpy, usedfont->xfont, utf8codepoint)) {
365                                         for (curfont = drw->fonts; curfont->next; curfont = curfont->next)
366                                                 ; /* NOP */
367                                         curfont->next = usedfont;
368                                 } else {
369                                         xfont_free(usedfont);
370                                         usedfont = drw->fonts;
371                                 }
372                         }
373                 }
374         }
375         if (d)
376                 XftDrawDestroy(d);
377
378         return x + (render ? w : 0);
379 }
380
381 void
382 drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h)
383 {
384         if (!drw)
385                 return;
386
387         XCopyArea(drw->dpy, drw->drawable, win, drw->gc, x, y, w, h, x, y);
388         XSync(drw->dpy, False);
389 }
390
391 unsigned int
392 drw_fontset_getwidth(Drw *drw, const char *text)
393 {
394         if (!drw || !drw->fonts || !text)
395                 return 0;
396         return drw_text(drw, 0, 0, 0, 0, 0, text, 0);
397 }
398
399 void
400 drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h)
401 {
402         XGlyphInfo ext;
403
404         if (!font || !text)
405                 return;
406
407         XftTextExtentsUtf8(font->dpy, font->xfont, (XftChar8 *)text, len, &ext);
408         if (w)
409                 *w = ext.xOff;
410         if (h)
411                 *h = font->h;
412 }
413
414 Cur *
415 drw_cur_create(Drw *drw, int shape)
416 {
417         Cur *cur;
418
419         if (!drw || !(cur = ecalloc(1, sizeof(Cur))))
420                 return NULL;
421
422         cur->cursor = XCreateFontCursor(drw->dpy, shape);
423
424         return cur;
425 }
426
427 void
428 drw_cur_free(Drw *drw, Cur *cursor)
429 {
430         if (!cursor)
431                 return;
432
433         XFreeCursor(drw->dpy, cursor->cursor);
434         free(cursor);
435 }