dmenu

Mahdi's build of dmenu
git clone git://mahdi.pw/dmenu.git
Log | Files | Refs | README | LICENSE

drw.c (11063B)


      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, Visual *visual, unsigned int depth, Colormap cmap)
     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->visual = visual;
     74 	drw->depth = depth;
     75 	drw->cmap = cmap;
     76 	drw->drawable = XCreatePixmap(dpy, root, w, h, depth);
     77 	drw->gc = XCreateGC(dpy, drw->drawable, 0, NULL);
     78 	XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter);
     79 
     80 	return drw;
     81 }
     82 
     83 void
     84 drw_resize(Drw *drw, unsigned int w, unsigned int h)
     85 {
     86 	if (!drw)
     87 		return;
     88 
     89 	drw->w = w;
     90 	drw->h = h;
     91 	if (drw->drawable)
     92 		XFreePixmap(drw->dpy, drw->drawable);
     93 	drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, drw->depth);
     94 }
     95 
     96 void
     97 drw_free(Drw *drw)
     98 {
     99 	XFreePixmap(drw->dpy, drw->drawable);
    100 	XFreeGC(drw->dpy, drw->gc);
    101 	drw_fontset_free(drw->fonts);
    102 	free(drw);
    103 }
    104 
    105 /* This function is an implementation detail. Library users should use
    106  * drw_fontset_create instead.
    107  */
    108 static Fnt *
    109 xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern)
    110 {
    111 	Fnt *font;
    112 	XftFont *xfont = NULL;
    113 	FcPattern *pattern = NULL;
    114 
    115 	if (fontname) {
    116 		/* Using the pattern found at font->xfont->pattern does not yield the
    117 		 * same substitution results as using the pattern returned by
    118 		 * FcNameParse; using the latter results in the desired fallback
    119 		 * behaviour whereas the former just results in missing-character
    120 		 * rectangles being drawn, at least with some fonts. */
    121 		if (!(xfont = XftFontOpenName(drw->dpy, drw->screen, fontname))) {
    122 			fprintf(stderr, "error, cannot load font from name: '%s'\n", fontname);
    123 			return NULL;
    124 		}
    125 		if (!(pattern = FcNameParse((FcChar8 *) fontname))) {
    126 			fprintf(stderr, "error, cannot parse font name to pattern: '%s'\n", fontname);
    127 			XftFontClose(drw->dpy, xfont);
    128 			return NULL;
    129 		}
    130 	} else if (fontpattern) {
    131 		if (!(xfont = XftFontOpenPattern(drw->dpy, fontpattern))) {
    132 			fprintf(stderr, "error, cannot load font from pattern.\n");
    133 			return NULL;
    134 		}
    135 	} else {
    136 		die("no font specified.");
    137 	}
    138 
    139 	font = ecalloc(1, sizeof(Fnt));
    140 	font->xfont = xfont;
    141 	font->pattern = pattern;
    142 	font->h = xfont->ascent + xfont->descent;
    143 	font->dpy = drw->dpy;
    144 
    145 	return font;
    146 }
    147 
    148 static void
    149 xfont_free(Fnt *font)
    150 {
    151 	if (!font)
    152 		return;
    153 	if (font->pattern)
    154 		FcPatternDestroy(font->pattern);
    155 	XftFontClose(font->dpy, font->xfont);
    156 	free(font);
    157 }
    158 
    159 Fnt*
    160 drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount)
    161 {
    162 	Fnt *cur, *ret = NULL;
    163 	size_t i;
    164 
    165 	if (!drw || !fonts)
    166 		return NULL;
    167 
    168 	for (i = 1; i <= fontcount; i++) {
    169 		if ((cur = xfont_create(drw, fonts[fontcount - i], NULL))) {
    170 			cur->next = ret;
    171 			ret = cur;
    172 		}
    173 	}
    174 	return (drw->fonts = ret);
    175 }
    176 
    177 void
    178 drw_fontset_free(Fnt *font)
    179 {
    180 	if (font) {
    181 		drw_fontset_free(font->next);
    182 		xfont_free(font);
    183 	}
    184 }
    185 
    186 void
    187 drw_clr_create(Drw *drw, Clr *dest, const char *clrname, unsigned int alpha)
    188 {
    189 	if (!drw || !dest || !clrname)
    190 		return;
    191 
    192 	if (!XftColorAllocName(drw->dpy, drw->visual, drw->cmap,
    193 	                       clrname, dest))
    194 		die("error, cannot allocate color '%s'", clrname);
    195 
    196 	dest->pixel = (dest->pixel & 0x00ffffffU) | (alpha << 24);
    197 }
    198 
    199 /* Wrapper to create color schemes. The caller has to call free(3) on the
    200  * returned color scheme when done using it. */
    201 Clr *
    202 drw_scm_create(Drw *drw, char *clrnames[], const unsigned int alphas[], size_t clrcount)
    203 {
    204 	size_t i;
    205 	Clr *ret;
    206 
    207 	/* need at least two colors for a scheme */
    208 	if (!drw || !clrnames || clrcount < 2 || !(ret = ecalloc(clrcount, sizeof(XftColor))))
    209 		return NULL;
    210 
    211 	for (i = 0; i < clrcount; i++)
    212 		drw_clr_create(drw, &ret[i], clrnames[i], alphas[i]);
    213 	return ret;
    214 }
    215 
    216 void
    217 drw_setfontset(Drw *drw, Fnt *set)
    218 {
    219 	if (drw)
    220 		drw->fonts = set;
    221 }
    222 
    223 void
    224 drw_setscheme(Drw *drw, Clr *scm)
    225 {
    226 	if (drw)
    227 		drw->scheme = scm;
    228 }
    229 
    230 void
    231 drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert)
    232 {
    233 	if (!drw || !drw->scheme)
    234 		return;
    235 	XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel);
    236 	if (filled)
    237 		XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
    238 	else
    239 		XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1);
    240 }
    241 
    242 int
    243 drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert)
    244 {
    245 	int i, ty, ellipsis_x = 0;
    246 	unsigned int tmpw, ew, ellipsis_w = 0, ellipsis_len;
    247 	XftDraw *d = NULL;
    248 	Fnt *usedfont, *curfont, *nextfont;
    249 	int utf8strlen, utf8charlen, render = x || y || w || h;
    250 	long utf8codepoint = 0;
    251 	const char *utf8str;
    252 	FcCharSet *fccharset;
    253 	FcPattern *fcpattern;
    254 	FcPattern *match;
    255 	XftResult result;
    256 	int charexists = 0, overflow = 0;
    257 	/* keep track of a couple codepoints for which we have no match. */
    258 	enum { nomatches_len = 64 };
    259 	static struct { long codepoint[nomatches_len]; unsigned int idx; } nomatches;
    260 	static unsigned int ellipsis_width = 0;
    261 
    262 	if (!drw || (render && (!drw->scheme || !w)) || !text || !drw->fonts)
    263 		return 0;
    264 
    265 	if (!render) {
    266 		w = invert ? invert : ~invert;
    267 	} else {
    268 		XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel);
    269 		XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
    270 		d = XftDrawCreate(drw->dpy, drw->drawable, drw->visual, drw->cmap);
    271 		x += lpad;
    272 		w -= lpad;
    273 	}
    274 
    275 	usedfont = drw->fonts;
    276 	if (!ellipsis_width && render)
    277 		ellipsis_width = drw_fontset_getwidth(drw, "...");
    278 	while (1) {
    279 		ew = ellipsis_len = utf8strlen = 0;
    280 		utf8str = text;
    281 		nextfont = NULL;
    282 		while (*text) {
    283 			utf8charlen = utf8decode(text, &utf8codepoint, UTF_SIZ);
    284 			for (curfont = drw->fonts; curfont; curfont = curfont->next) {
    285 				charexists = charexists || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint);
    286 				if (charexists) {
    287 					drw_font_getexts(curfont, text, utf8charlen, &tmpw, NULL);
    288 					if (ew + ellipsis_width <= w) {
    289 						/* keep track where the ellipsis still fits */
    290 						ellipsis_x = x + ew;
    291 						ellipsis_w = w - ew;
    292 						ellipsis_len = utf8strlen;
    293 					}
    294 
    295 					if (ew + tmpw > w) {
    296 						overflow = 1;
    297 						/* called from drw_fontset_getwidth_clamp():
    298 						 * it wants the width AFTER the overflow
    299 						 */
    300 						if (!render)
    301 							x += tmpw;
    302 						else
    303 							utf8strlen = ellipsis_len;
    304 					} else if (curfont == usedfont) {
    305 						utf8strlen += utf8charlen;
    306 						text += utf8charlen;
    307 						ew += tmpw;
    308 					} else {
    309 						nextfont = curfont;
    310 					}
    311 					break;
    312 				}
    313 			}
    314 
    315 			if (overflow || !charexists || nextfont)
    316 				break;
    317 			else
    318 				charexists = 0;
    319 		}
    320 
    321 		if (utf8strlen) {
    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 *)utf8str, utf8strlen);
    326 			}
    327 			x += ew;
    328 			w -= ew;
    329 		}
    330 		if (render && overflow)
    331 			drw_text(drw, ellipsis_x, y, ellipsis_w, h, 0, "...", invert);
    332 
    333 		if (!*text || overflow) {
    334 			break;
    335 		} else if (nextfont) {
    336 			charexists = 0;
    337 			usedfont = nextfont;
    338 		} else {
    339 			/* Regardless of whether or not a fallback font is found, the
    340 			 * character must be drawn. */
    341 			charexists = 1;
    342 
    343 			for (i = 0; i < nomatches_len; ++i) {
    344 				/* avoid calling XftFontMatch if we know we won't find a match */
    345 				if (utf8codepoint == nomatches.codepoint[i])
    346 					goto no_match;
    347 			}
    348 
    349 			fccharset = FcCharSetCreate();
    350 			FcCharSetAddChar(fccharset, utf8codepoint);
    351 
    352 			if (!drw->fonts->pattern) {
    353 				/* Refer to the comment in xfont_create for more information. */
    354 				die("the first font in the cache must be loaded from a font string.");
    355 			}
    356 
    357 			fcpattern = FcPatternDuplicate(drw->fonts->pattern);
    358 			FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
    359 			FcPatternAddBool(fcpattern, FC_SCALABLE, FcTrue);
    360 
    361 			FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
    362 			FcDefaultSubstitute(fcpattern);
    363 			match = XftFontMatch(drw->dpy, drw->screen, fcpattern, &result);
    364 
    365 			FcCharSetDestroy(fccharset);
    366 			FcPatternDestroy(fcpattern);
    367 
    368 			if (match) {
    369 				usedfont = xfont_create(drw, NULL, match);
    370 				if (usedfont && XftCharExists(drw->dpy, usedfont->xfont, utf8codepoint)) {
    371 					for (curfont = drw->fonts; curfont->next; curfont = curfont->next)
    372 						; /* NOP */
    373 					curfont->next = usedfont;
    374 				} else {
    375 					xfont_free(usedfont);
    376 					nomatches.codepoint[++nomatches.idx % nomatches_len] = utf8codepoint;
    377 no_match:
    378 					usedfont = drw->fonts;
    379 				}
    380 			}
    381 		}
    382 	}
    383 	if (d)
    384 		XftDrawDestroy(d);
    385 
    386 	return x + (render ? w : 0);
    387 }
    388 
    389 void
    390 drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h)
    391 {
    392 	if (!drw)
    393 		return;
    394 
    395 	XCopyArea(drw->dpy, drw->drawable, win, drw->gc, x, y, w, h, x, y);
    396 	XSync(drw->dpy, False);
    397 }
    398 
    399 unsigned int
    400 drw_fontset_getwidth(Drw *drw, const char *text)
    401 {
    402 	if (!drw || !drw->fonts || !text)
    403 		return 0;
    404 	return drw_text(drw, 0, 0, 0, 0, 0, text, 0);
    405 }
    406 
    407 unsigned int
    408 drw_fontset_getwidth_clamp(Drw *drw, const char *text, unsigned int n)
    409 {
    410 	unsigned int tmp = 0;
    411 	if (drw && drw->fonts && text && n)
    412 		tmp = drw_text(drw, 0, 0, 0, 0, 0, text, n);
    413 	return MIN(n, tmp);
    414 }
    415 
    416 void
    417 drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h)
    418 {
    419 	XGlyphInfo ext;
    420 
    421 	if (!font || !text)
    422 		return;
    423 
    424 	XftTextExtentsUtf8(font->dpy, font->xfont, (XftChar8 *)text, len, &ext);
    425 	if (w)
    426 		*w = ext.xOff;
    427 	if (h)
    428 		*h = font->h;
    429 }
    430 
    431 Cur *
    432 drw_cur_create(Drw *drw, int shape)
    433 {
    434 	Cur *cur;
    435 
    436 	if (!drw || !(cur = ecalloc(1, sizeof(Cur))))
    437 		return NULL;
    438 
    439 	cur->cursor = XCreateFontCursor(drw->dpy, shape);
    440 
    441 	return cur;
    442 }
    443 
    444 void
    445 drw_cur_free(Drw *drw, Cur *cursor)
    446 {
    447 	if (!cursor)
    448 		return;
    449 
    450 	XFreeCursor(drw->dpy, cursor->cursor);
    451 	free(cursor);
    452 }
    453