drawstring.c (2079B)
1 /* Copyright ©2007-2010 Kris Maglione <maglione.k at Gmail> 2 * See LICENSE file for license details. 3 */ 4 #include <string.h> 5 #include "../x11.h" 6 7 uint 8 fillstring(Image *dst, Font *font, 9 Rectangle r, Align align, 10 const char *text, CTuple *col, int borderw) { 11 12 fill(dst, r, &col->bg); 13 if(borderw) 14 border(dst, r, borderw, &col->border); 15 return drawstring(dst, font, r, align, text, &col->fg); 16 } 17 18 uint 19 drawstring(Image *dst, Font *font, 20 Rectangle r, Align align, 21 const char *text, Color *col) { 22 Rectangle tr; 23 char *buf; 24 uint x, y, width, height, len; 25 int shortened; 26 27 shortened = 0; 28 29 len = strlen(text); 30 buf = emalloc(len+1); 31 memcpy(buf, text, len+1); 32 33 r.max.y -= font->pad.min.y; 34 r.min.y += font->pad.max.y; 35 36 height = font->ascent + font->descent; 37 y = r.min.y + Dy(r) / 2 - height / 2 + font->ascent; 38 39 width = Dx(r) - font->pad.min.x - font->pad.max.x - (font->height & ~1); 40 41 r.min.x += font->pad.min.x; 42 r.max.x -= font->pad.max.x; 43 44 /* shorten text if necessary */ 45 tr = ZR; 46 while(len > 0) { 47 tr = textextents_l(font, buf, len + min(shortened, 3), nil); 48 if(Dx(tr) <= width) 49 break; 50 while(len > 0 && (buf[--len]&0xC0) == 0x80) 51 buf[len] = '.'; 52 buf[len] = '.'; 53 shortened++; 54 } 55 56 if(len == 0 || Dx(tr) > width) 57 goto done; 58 59 /* mark shortened info in the string */ 60 if(shortened) 61 len += min(shortened, 3); 62 63 switch (align) { 64 case East: 65 x = r.max.x - (tr.max.x + (font->height / 2)); 66 break; 67 case Center: 68 x = r.min.x + (Dx(r) - Dx(tr)) / 2 - tr.min.x; 69 break; 70 default: 71 x = r.min.x + (font->height / 2) - tr.min.x; 72 break; 73 } 74 75 setgccol(dst, col); 76 switch(font->type) { 77 case FFontSet: 78 Xutf8DrawString(display, dst->xid, 79 font->font.set, dst->gc, 80 x, y, 81 buf, len); 82 break; 83 case FXft: 84 xft->drawstring(xftdrawable(dst), xftcolor(dst, col), 85 font->font.xft, 86 x, y, buf, len); 87 break; 88 case FX11: 89 XSetFont(display, dst->gc, font->font.x11->fid); 90 XDrawString(display, dst->xid, dst->gc, 91 x, y, buf, len); 92 break; 93 default: 94 die("Invalid font type."); 95 } 96 97 done: 98 free(buf); 99 return Dx(tr); 100 }