swm

sigma window manager
git clone git://wolog.xyz/swm
Log | Files | Refs | README | LICENSE

drw.c (11311B)


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