birdwm

birdwm - mrgrouse's daily driver fork of suckless' dwm. Contains many patches and is currently loosely maintained.
Log | Files | Refs | README | LICENSE

drw.c (14000B)


      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 #include <Imlib2.h>
      8 
      9 #include "drw.h"
     10 #include "util.h"
     11 
     12 #define UTF_INVALID 0xFFFD
     13 
     14 static int
     15 utf8decode(const char *s_in, long *u, int *err)
     16 {
     17 	static const unsigned char lens[] = {
     18 		/* 0XXXX */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
     19 		/* 10XXX */ 0, 0, 0, 0, 0, 0, 0, 0,  /* invalid */
     20 		/* 110XX */ 2, 2, 2, 2,
     21 		/* 1110X */ 3, 3,
     22 		/* 11110 */ 4,
     23 		/* 11111 */ 0,  /* invalid */
     24 	};
     25 	static const unsigned char leading_mask[] = { 0x7F, 0x1F, 0x0F, 0x07 };
     26 	static const unsigned int overlong[] = { 0x0, 0x80, 0x0800, 0x10000 };
     27 
     28 	const unsigned char *s = (const unsigned char *)s_in;
     29 	int len = lens[*s >> 3];
     30 	*u = UTF_INVALID;
     31 	*err = 1;
     32 	if (len == 0)
     33 		return 1;
     34 
     35 	long cp = s[0] & leading_mask[len - 1];
     36 	for (int i = 1; i < len; ++i) {
     37 		if (s[i] == '\0' || (s[i] & 0xC0) != 0x80)
     38 			return i;
     39 		cp = (cp << 6) | (s[i] & 0x3F);
     40 	}
     41 	/* out of range, surrogate, overlong encoding */
     42 	if (cp > 0x10FFFF || (cp >> 11) == 0x1B || cp < overlong[len - 1])
     43 		return len;
     44 
     45 	*err = 0;
     46 	*u = cp;
     47 	return len;
     48 }
     49 
     50 Drw *
     51 drw_create(Display *dpy, int screen, Window root, unsigned int w, unsigned int h)
     52 {
     53 	Drw *drw = ecalloc(1, sizeof(Drw));
     54 
     55 	drw->dpy = dpy;
     56 	drw->screen = screen;
     57 	drw->root = root;
     58 	drw->w = w;
     59 	drw->h = h;
     60 	drw->drawable = XCreatePixmap(dpy, root, w, h, DefaultDepth(dpy, screen));
     61 	drw->picture = XRenderCreatePicture(dpy, drw->drawable, XRenderFindVisualFormat(dpy, DefaultVisual(dpy, screen)), 0, NULL);
     62 	drw->gc = XCreateGC(dpy, root, 0, NULL);
     63 	XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter);
     64 
     65 	return drw;
     66 }
     67 
     68 void
     69 drw_resize(Drw *drw, unsigned int w, unsigned int h)
     70 {
     71 	if (!drw)
     72 		return;
     73 
     74 	drw->w = w;
     75 	drw->h = h;
     76 	if (drw->picture)
     77 		XRenderFreePicture(drw->dpy, drw->picture);
     78 	if (drw->drawable)
     79 		XFreePixmap(drw->dpy, drw->drawable);
     80 	drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, DefaultDepth(drw->dpy, drw->screen));
     81 	drw->picture = XRenderCreatePicture(drw->dpy, drw->drawable, XRenderFindVisualFormat(drw->dpy, DefaultVisual(drw->dpy, drw->screen)), 0, NULL);
     82 }
     83 
     84 void
     85 drw_free(Drw *drw)
     86 {
     87 	XRenderFreePicture(drw->dpy, drw->picture);
     88 	XFreePixmap(drw->dpy, drw->drawable);
     89 	XFreeGC(drw->dpy, drw->gc);
     90 	drw_fontset_free(drw->fonts);
     91 	free(drw);
     92 }
     93 
     94 /* This function is an implementation detail. Library users should use
     95  * drw_fontset_create instead.
     96  */
     97 static Fnt *
     98 xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern)
     99 {
    100 	Fnt *font;
    101 	XftFont *xfont = NULL;
    102 	FcPattern *pattern = NULL;
    103 
    104 	if (fontname) {
    105 		/* Using the pattern found at font->xfont->pattern does not yield the
    106 		 * same substitution results as using the pattern returned by
    107 		 * FcNameParse; using the latter results in the desired fallback
    108 		 * behaviour whereas the former just results in missing-character
    109 		 * rectangles being drawn, at least with some fonts. */
    110 		if (!(xfont = XftFontOpenName(drw->dpy, drw->screen, fontname))) {
    111 			fprintf(stderr, "error, cannot load font from name: '%s'\n", fontname);
    112 			return NULL;
    113 		}
    114 		if (!(pattern = FcNameParse((FcChar8 *) fontname))) {
    115 			fprintf(stderr, "error, cannot parse font name to pattern: '%s'\n", fontname);
    116 			XftFontClose(drw->dpy, xfont);
    117 			return NULL;
    118 		}
    119 	} else if (fontpattern) {
    120 		if (!(xfont = XftFontOpenPattern(drw->dpy, fontpattern))) {
    121 			fprintf(stderr, "error, cannot load font from pattern.\n");
    122 			return NULL;
    123 		}
    124 	} else {
    125 		die("no font specified.");
    126 	}
    127 
    128 	font = ecalloc(1, sizeof(Fnt));
    129 	font->xfont = xfont;
    130 	font->pattern = pattern;
    131 	font->h = xfont->ascent + xfont->descent;
    132 	font->dpy = drw->dpy;
    133 
    134 	return font;
    135 }
    136 
    137 static void
    138 xfont_free(Fnt *font)
    139 {
    140 	if (!font)
    141 		return;
    142 	if (font->pattern)
    143 		FcPatternDestroy(font->pattern);
    144 	XftFontClose(font->dpy, font->xfont);
    145 	free(font);
    146 }
    147 
    148 Fnt*
    149 drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount)
    150 {
    151 	Fnt *cur, *ret = NULL;
    152 	size_t i;
    153 
    154 	if (!drw || !fonts)
    155 		return NULL;
    156 
    157 	for (i = 1; i <= fontcount; i++) {
    158 		if ((cur = xfont_create(drw, fonts[fontcount - i], NULL))) {
    159 			cur->next = ret;
    160 			ret = cur;
    161 		}
    162 	}
    163 	return (drw->fonts = ret);
    164 }
    165 
    166 void
    167 drw_fontset_free(Fnt *font)
    168 {
    169 	if (font) {
    170 		drw_fontset_free(font->next);
    171 		xfont_free(font);
    172 	}
    173 }
    174 
    175 void
    176 drw_clr_create(Drw *drw, Clr *dest, const char *clrname)
    177 {
    178 	if (!drw || !dest || !clrname)
    179 		return;
    180 
    181 	if (!XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen),
    182 	                       DefaultColormap(drw->dpy, drw->screen),
    183 	                       clrname, dest))
    184 		die("error, cannot allocate color '%s'", clrname);
    185 }
    186 
    187 /* Wrapper to create color schemes. The caller has to call free(3) on the
    188  * returned color scheme when done using it. */
    189 Clr *
    190 drw_scm_create(Drw *drw, char *clrnames[], size_t clrcount)
    191 {
    192 	size_t i;
    193 	Clr *ret;
    194 
    195 	/* need at least two colors for a scheme */
    196 	if (!drw || !clrnames || clrcount < 2 || !(ret = ecalloc(clrcount, sizeof(XftColor))))
    197 		return NULL;
    198 
    199 	for (i = 0; i < clrcount; i++)
    200 		drw_clr_create(drw, &ret[i], clrnames[i]);
    201 	return ret;
    202 }
    203 
    204 void
    205 drw_setfontset(Drw *drw, Fnt *set)
    206 {
    207 	if (drw)
    208 		drw->fonts = set;
    209 }
    210 
    211 void
    212 drw_setscheme(Drw *drw, Clr *scm)
    213 {
    214 	if (drw)
    215 		drw->scheme = scm;
    216 }
    217 
    218 Picture
    219 drw_picture_create_resized(Drw *drw, char *src, unsigned int srcw, unsigned int srch, unsigned int dstw, unsigned int dsth) {
    220 	Pixmap pm;
    221 	Picture pic;
    222 	GC gc;
    223 
    224 	if (srcw <= (dstw << 1u) && srch <= (dsth << 1u)) {
    225 		XImage img = {
    226 			srcw, srch, 0, ZPixmap, src,
    227 			ImageByteOrder(drw->dpy), BitmapUnit(drw->dpy), BitmapBitOrder(drw->dpy), 32,
    228 			32, 0, 32,
    229 			0, 0, 0
    230 		};
    231 		XInitImage(&img);
    232 
    233 		pm = XCreatePixmap(drw->dpy, drw->root, srcw, srch, 32);
    234 		gc = XCreateGC(drw->dpy, pm, 0, NULL);
    235 		XPutImage(drw->dpy, pm, gc, &img, 0, 0, 0, 0, srcw, srch);
    236 		XFreeGC(drw->dpy, gc);
    237 
    238 		pic = XRenderCreatePicture(drw->dpy, pm, XRenderFindStandardFormat(drw->dpy, PictStandardARGB32), 0, NULL);
    239 		XFreePixmap(drw->dpy, pm);
    240 
    241 		XRenderSetPictureFilter(drw->dpy, pic, FilterBilinear, NULL, 0);
    242 		XTransform xf;
    243 		xf.matrix[0][0] = (srcw << 16u) / dstw; xf.matrix[0][1] = 0; xf.matrix[0][2] = 0;
    244 		xf.matrix[1][0] = 0; xf.matrix[1][1] = (srch << 16u) / dsth; xf.matrix[1][2] = 0;
    245 		xf.matrix[2][0] = 0; xf.matrix[2][1] = 0; xf.matrix[2][2] = 65536;
    246 		XRenderSetPictureTransform(drw->dpy, pic, &xf);
    247 	} else {
    248 		Imlib_Image origin = imlib_create_image_using_data(srcw, srch, (DATA32 *)src);
    249 		if (!origin) return None;
    250 		imlib_context_set_image(origin);
    251 		imlib_image_set_has_alpha(1);
    252 		Imlib_Image scaled = imlib_create_cropped_scaled_image(0, 0, srcw, srch, dstw, dsth);
    253 		imlib_free_image_and_decache();
    254 		if (!scaled) return None;
    255 		imlib_context_set_image(scaled);
    256 		imlib_image_set_has_alpha(1);
    257 
    258 		XImage img = {
    259 		    dstw, dsth, 0, ZPixmap, (char *)imlib_image_get_data_for_reading_only(),
    260 		    ImageByteOrder(drw->dpy), BitmapUnit(drw->dpy), BitmapBitOrder(drw->dpy), 32,
    261 		    32, 0, 32,
    262 		    0, 0, 0
    263 		};
    264 		XInitImage(&img);
    265 
    266 		pm = XCreatePixmap(drw->dpy, drw->root, dstw, dsth, 32);
    267 		gc = XCreateGC(drw->dpy, pm, 0, NULL);
    268 		XPutImage(drw->dpy, pm, gc, &img, 0, 0, 0, 0, dstw, dsth);
    269 		imlib_free_image_and_decache();
    270 		XFreeGC(drw->dpy, gc);
    271 
    272 		pic = XRenderCreatePicture(drw->dpy, pm, XRenderFindStandardFormat(drw->dpy, PictStandardARGB32), 0, NULL);
    273 		XFreePixmap(drw->dpy, pm);
    274 	}
    275 
    276 	return pic;
    277 }
    278 
    279 void
    280 drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert)
    281 {
    282 	if (!drw || !drw->scheme)
    283 		return;
    284 	XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel);
    285 	if (filled)
    286 		XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
    287 	else
    288 		XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1);
    289 }
    290 
    291 int
    292 drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert)
    293 {
    294 	int ty, ellipsis_x = 0;
    295 	unsigned int tmpw, ew, ellipsis_w = 0, ellipsis_len, hash, h0, h1;
    296 	XftDraw *d = NULL;
    297 	Fnt *usedfont, *curfont, *nextfont;
    298 	int utf8strlen, utf8charlen, utf8err, render = x || y || w || h;
    299 	long utf8codepoint = 0;
    300 	const char *utf8str;
    301 	FcCharSet *fccharset;
    302 	FcPattern *fcpattern;
    303 	FcPattern *match;
    304 	XftResult result;
    305 	int charexists = 0, overflow = 0;
    306 	/* keep track of a couple codepoints for which we have no match. */
    307 	static unsigned int nomatches[128], ellipsis_width, invalid_width;
    308 	static const char invalid[] = "�";
    309 
    310 	if (!drw || (render && (!drw->scheme || !w)) || !text || !drw->fonts)
    311 		return 0;
    312 
    313 	if (!render) {
    314 		w = invert ? invert : ~invert;
    315 	} else {
    316 		XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel);
    317 		XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h);
    318 		if (w < lpad)
    319 			return x + w;
    320 		d = XftDrawCreate(drw->dpy, drw->drawable,
    321 		                  DefaultVisual(drw->dpy, drw->screen),
    322 		                  DefaultColormap(drw->dpy, drw->screen));
    323 		x += lpad;
    324 		w -= lpad;
    325 	}
    326 
    327 	usedfont = drw->fonts;
    328 	if (!ellipsis_width && render)
    329 		ellipsis_width = drw_fontset_getwidth(drw, "...");
    330 	if (!invalid_width && render)
    331 		invalid_width = drw_fontset_getwidth(drw, invalid);
    332 	while (1) {
    333 		ew = ellipsis_len = utf8err = utf8charlen = utf8strlen = 0;
    334 		utf8str = text;
    335 		nextfont = NULL;
    336 		while (*text) {
    337 			utf8charlen = utf8decode(text, &utf8codepoint, &utf8err);
    338 			for (curfont = drw->fonts; curfont; curfont = curfont->next) {
    339 				charexists = charexists || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint);
    340 				if (charexists) {
    341 					drw_font_getexts(curfont, text, utf8charlen, &tmpw, NULL);
    342 					if (ew + ellipsis_width <= w) {
    343 						/* keep track where the ellipsis still fits */
    344 						ellipsis_x = x + ew;
    345 						ellipsis_w = w - ew;
    346 						ellipsis_len = utf8strlen;
    347 					}
    348 
    349 					if (ew + tmpw > w) {
    350 						overflow = 1;
    351 						/* called from drw_fontset_getwidth_clamp():
    352 						 * it wants the width AFTER the overflow
    353 						 */
    354 						if (!render)
    355 							x += tmpw;
    356 						else
    357 							utf8strlen = ellipsis_len;
    358 					} else if (curfont == usedfont) {
    359 						text += utf8charlen;
    360 						utf8strlen += utf8err ? 0 : utf8charlen;
    361 						ew += utf8err ? 0 : tmpw;
    362 					} else {
    363 						nextfont = curfont;
    364 					}
    365 					break;
    366 				}
    367 			}
    368 
    369 			if (overflow || !charexists || nextfont || utf8err)
    370 				break;
    371 			else
    372 				charexists = 0;
    373 		}
    374 
    375 		if (utf8strlen) {
    376 			if (render) {
    377 				ty = y + (h - usedfont->h) / 2 + usedfont->xfont->ascent;
    378 				XftDrawStringUtf8(d, &drw->scheme[invert ? ColBg : ColFg],
    379 				                  usedfont->xfont, x, ty, (XftChar8 *)utf8str, utf8strlen);
    380 			}
    381 			x += ew;
    382 			w -= ew;
    383 		}
    384 		if (utf8err && (!render || invalid_width < w)) {
    385 			if (render)
    386 				drw_text(drw, x, y, w, h, 0, invalid, invert);
    387 			x += invalid_width;
    388 			w -= invalid_width;
    389 		}
    390 		if (render && overflow)
    391 			drw_text(drw, ellipsis_x, y, ellipsis_w, h, 0, "...", invert);
    392 
    393 		if (!*text || overflow) {
    394 			break;
    395 		} else if (nextfont) {
    396 			charexists = 0;
    397 			usedfont = nextfont;
    398 		} else {
    399 			/* Regardless of whether or not a fallback font is found, the
    400 			 * character must be drawn. */
    401 			charexists = 1;
    402 
    403 			hash = (unsigned int)utf8codepoint;
    404 			hash = ((hash >> 16) ^ hash) * 0x21F0AAAD;
    405 			hash = ((hash >> 15) ^ hash) * 0xD35A2D97;
    406 			h0 = ((hash >> 15) ^ hash) % LENGTH(nomatches);
    407 			h1 = (hash >> 17) % LENGTH(nomatches);
    408 			/* avoid expensive XftFontMatch call when we know we won't find a match */
    409 			if (nomatches[h0] == utf8codepoint || nomatches[h1] == utf8codepoint)
    410 				goto no_match;
    411 
    412 			fccharset = FcCharSetCreate();
    413 			FcCharSetAddChar(fccharset, utf8codepoint);
    414 
    415 			if (!drw->fonts->pattern) {
    416 				/* Refer to the comment in xfont_create for more information. */
    417 				die("the first font in the cache must be loaded from a font string.");
    418 			}
    419 
    420 			fcpattern = FcPatternDuplicate(drw->fonts->pattern);
    421 			FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
    422 			FcPatternAddBool(fcpattern, FC_SCALABLE, FcTrue);
    423 
    424 			FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
    425 			FcDefaultSubstitute(fcpattern);
    426 			match = XftFontMatch(drw->dpy, drw->screen, fcpattern, &result);
    427 
    428 			FcCharSetDestroy(fccharset);
    429 			FcPatternDestroy(fcpattern);
    430 
    431 			if (match) {
    432 				usedfont = xfont_create(drw, NULL, match);
    433 				if (usedfont && XftCharExists(drw->dpy, usedfont->xfont, utf8codepoint)) {
    434 					for (curfont = drw->fonts; curfont->next; curfont = curfont->next)
    435 						; /* NOP */
    436 					curfont->next = usedfont;
    437 				} else {
    438 					xfont_free(usedfont);
    439 					nomatches[nomatches[h0] ? h1 : h0] = utf8codepoint;
    440 no_match:
    441 					usedfont = drw->fonts;
    442 				}
    443 			}
    444 		}
    445 	}
    446 	if (d)
    447 		XftDrawDestroy(d);
    448 
    449 	return x + (render ? w : 0);
    450 }
    451 
    452 void
    453 drw_pic(Drw *drw, int x, int y, unsigned int w, unsigned int h, Picture pic)
    454 {
    455 	if (!drw)
    456 		return;
    457 	XRenderComposite(drw->dpy, PictOpOver, pic, None, drw->picture, 0, 0, 0, 0, x, y, w, h);
    458 }
    459 
    460 void
    461 drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h)
    462 {
    463 	if (!drw)
    464 		return;
    465 
    466 	XCopyArea(drw->dpy, drw->drawable, win, drw->gc, x, y, w, h, x, y);
    467 	XSync(drw->dpy, False);
    468 }
    469 
    470 unsigned int
    471 drw_fontset_getwidth(Drw *drw, const char *text)
    472 {
    473 	if (!drw || !drw->fonts || !text)
    474 		return 0;
    475 	return drw_text(drw, 0, 0, 0, 0, 0, text, 0);
    476 }
    477 
    478 unsigned int
    479 drw_fontset_getwidth_clamp(Drw *drw, const char *text, unsigned int n)
    480 {
    481 	unsigned int tmp = 0;
    482 	if (drw && drw->fonts && text && n)
    483 		tmp = drw_text(drw, 0, 0, 0, 0, 0, text, n);
    484 	return MIN(n, tmp);
    485 }
    486 
    487 void
    488 drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h)
    489 {
    490 	XGlyphInfo ext;
    491 
    492 	if (!font || !text)
    493 		return;
    494 
    495 	XftTextExtentsUtf8(font->dpy, font->xfont, (XftChar8 *)text, len, &ext);
    496 	if (w)
    497 		*w = ext.xOff;
    498 	if (h)
    499 		*h = font->h;
    500 }
    501 
    502 Cur *
    503 drw_cur_create(Drw *drw, int shape)
    504 {
    505 	Cur *cur;
    506 
    507 	if (!drw || !(cur = ecalloc(1, sizeof(Cur))))
    508 		return NULL;
    509 
    510 	cur->cursor = XCreateFontCursor(drw->dpy, shape);
    511 
    512 	return cur;
    513 }
    514 
    515 void
    516 drw_cur_free(Drw *drw, Cur *cursor)
    517 {
    518 	if (!cursor)
    519 		return;
    520 
    521 	XFreeCursor(drw->dpy, cursor->cursor);
    522 	free(cursor);
    523 }