]> icculus.org git repositories - dana/openbox.git/blob - render/font.c
maybe even better layouting (ie the previous was off by a few marks). memo to self...
[dana/openbox.git] / render / font.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2
3    font.c for the Openbox window manager
4    Copyright (c) 2003        Ben Jansens
5    Copyright (c) 2003        Derek Foreman
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    See the COPYING file for a copy of the GNU General Public License.
18 */
19
20 #include "font.h"
21 #include "color.h"
22 #include "mask.h"
23 #include "theme.h"
24 #include "geom.h"
25 #include "gettext.h"
26
27 #include <X11/Xft/Xft.h>
28 #include <glib.h>
29 #include <string.h>
30 #include <stdlib.h>
31
32 #define ELIPSES "..."
33 #define ELIPSES_LENGTH(font) \
34     (font->elipses_length + (font->shadow ? font->offset : 0))
35
36 #define OB_SHADOW "shadow"
37 #define OB_SHADOW_OFFSET "shadowoffset"
38 #define OB_SHADOW_ALPHA "shadowtint"
39
40 FcObjectType objs[] = {
41     { OB_SHADOW,        FcTypeBool    },
42     { OB_SHADOW_OFFSET, FcTypeInteger },
43     { OB_SHADOW_ALPHA,  FcTypeInteger  }
44 };
45
46 static PangoContext *context;
47 static gboolean started = FALSE;
48
49 static void font_startup(void)
50 {
51     if (!XftInit(0)) {
52         g_warning(_("Couldn't initialize Xft."));
53         exit(EXIT_FAILURE);
54     }
55
56 #ifdef USE_PANGO
57     g_type_init();
58     /* these will never be freed, but we will need them until we shut down anyway */
59     context = pango_xft_get_context(RrDisplay(NULL), RrScreen(NULL));
60 #endif /* USE_PANGO */
61     /* Here we are teaching xft about the shadow, shadowoffset & shadowtint */
62     FcNameRegisterObjectTypes(objs, (sizeof(objs) / sizeof(objs[0])));
63 }
64
65 static void measure_font(RrFont *f)
66 {
67     /* xOff, yOff is the normal spacing to the next glyph. */
68     XGlyphInfo info;
69
70     /* measure an elipses */
71     XftTextExtentsUtf8(RrDisplay(f->inst), f->xftfont,
72                        (FcChar8*)ELIPSES, strlen(ELIPSES), &info);
73     f->elipses_length = (signed) info.xOff;
74 }
75
76 static RrFont *openfont(const RrInstance *inst, gchar *fontstring)
77 {
78     /* This function is called for each font in the theme file. */
79     /* It returns a pointer to a RrFont struct after filling it. */
80     RrFont *out;
81     FcPattern *pat, *match;
82     XftFont *font;
83     FcResult res;
84     gint tint;
85 #ifdef USE_PANGO
86     guchar *tmp_string = NULL;
87     gint tmp_int;
88 #endif /* USE_PANGO */
89
90     if (!(pat = XftNameParse(fontstring)))
91         return NULL;
92
93     match = XftFontMatch(RrDisplay(inst), RrScreen(inst), pat, &res);
94     FcPatternDestroy(pat);
95     if (!match)
96         return NULL;
97
98     out = g_new(RrFont, 1);
99     out->inst = inst;
100 #ifdef USE_PANGO
101     /*    printf("\n\n%s\n\n",fontstring);
102           FcPatternPrint(match); */
103
104     out->pango_font_description = pango_font_description_new();
105
106     if (FcPatternGetString(match, "family", 0, &tmp_string) != FcResultTypeMismatch) {
107         pango_font_description_set_family(out->pango_font_description, (gchar *)tmp_string);
108         tmp_string = NULL;
109     }
110     if (FcPatternGetString(match, "style", 0, &tmp_string) != FcResultTypeMismatch) {
111         /* Bold ? */
112         if (!strcasecmp("bold", (gchar *)tmp_string)) {
113             pango_font_description_set_weight(out->pango_font_description, PANGO_WEIGHT_BOLD);
114         }
115         /* Italic ? */
116         else if (!strcasecmp("italic", (gchar *)tmp_string)) {
117             pango_font_description_set_style(out->pango_font_description, PANGO_STYLE_ITALIC);
118         }
119         tmp_string = NULL;
120     }
121
122     if (FcPatternGetInteger(match, "pixelsize", 0, &tmp_int) != FcResultTypeMismatch) {
123         /* TODO: is PANGO_SCALE correct ?? */
124         pango_font_description_set_size(out->pango_font_description, tmp_int*PANGO_SCALE);
125     }
126
127     PangoLanguage *ln;
128     PangoFontMetrics *metrics = pango_context_get_metrics(context, out->pango_font_description, ln = pango_language_from_string("en_US"));
129     out->pango_ascent = pango_font_metrics_get_ascent(metrics);
130     out->pango_descent = pango_font_metrics_get_descent(metrics);
131     pango_font_metrics_unref(metrics);
132 #endif /* USE_PANGO */
133
134     if (FcPatternGetBool(match, OB_SHADOW, 0, &out->shadow) != FcResultMatch)
135         out->shadow = FALSE;
136
137     if (FcPatternGetInteger(match, OB_SHADOW_OFFSET, 0, &out->offset) !=
138         FcResultMatch)
139         out->offset = 1;
140
141     if (FcPatternGetInteger(match, OB_SHADOW_ALPHA, 0, &tint) != FcResultMatch)
142         tint = 25;
143     if (tint > 100) tint = 100;
144     else if (tint < -100) tint = -100;
145     out->tint = tint;
146
147     font = XftFontOpenPattern(RrDisplay(inst), match);
148     if (!font) {
149         FcPatternDestroy(match);
150         g_free(out);
151         return NULL;
152     } else
153         out->xftfont = font;
154
155 #ifdef USE_PANGO
156     /*        FcPatternDestroy(match); */
157 #endif /* USE_PANGO */
158     measure_font(out);
159
160     return out;
161 }
162
163 RrFont *RrFontOpen(const RrInstance *inst, gchar *fontstring)
164 {
165     RrFont *out;
166
167     if (!started) {
168         font_startup();
169         started = TRUE;
170     }
171
172     if ((out = openfont(inst, fontstring)))
173         return out;
174     g_warning(_("Unable to load font: %s\n"), fontstring);
175     g_warning(_("Trying fallback font: %s\n"), "sans");
176
177     if ((out = openfont(inst, "sans")))
178         return out;
179     g_warning(_("Unable to load font: %s\n"), "sans");
180
181     return NULL;
182 }
183
184 void RrFontClose(RrFont *f)
185 {
186     if (f) {
187         XftFontClose(RrDisplay(f->inst), f->xftfont);
188         g_free(f);
189     }
190 #ifdef USE_PANGO
191     pango_font_description_free(f->pango_font_description);
192 #endif
193 }
194
195 static void font_measure_full(const RrFont *f, const gchar *str,
196                               gint *x, gint *y)
197 {
198 #ifdef USE_PANGO
199     PangoLayout *pl;
200     PangoRectangle rect;
201     pl = pango_layout_new (context);
202     pango_layout_set_text(pl, str, -1);
203     pango_layout_set_font_description(pl, f->pango_font_description);
204     pango_layout_set_single_paragraph_mode(pl, TRUE);
205     pango_layout_get_pixel_extents(pl, NULL, &rect);
206     *x = rect.width + (f->shadow ? ABS(f->offset) : 0);
207     *y = rect.height + (f->shadow ? ABS(f->offset) : 0);
208     g_object_unref(pl);
209
210 #else
211     XGlyphInfo info;
212
213     XftTextExtentsUtf8(RrDisplay(f->inst), f->xftfont,
214                        (const FcChar8*)str, strlen(str), &info);
215
216     *x = (signed) info.xOff + (f->shadow ? ABS(f->offset) : 0);
217     *y = info.height + (f->shadow ? ABS(f->offset) : 0);
218 #endif /* USE_PANGO */
219 }
220
221 RrSize *RrFontMeasureString(const RrFont *f, const gchar *str)
222 {
223     RrSize *size;
224     size = g_new(RrSize, 1);
225     font_measure_full (f, str, &size->width, &size->height);
226     return size;
227 }
228
229 gint RrFontHeight(const RrFont *f)
230 {
231 #ifdef USE_PANGO
232     return (f->pango_ascent
233             + f->pango_descent
234            ) / PANGO_SCALE +
235            (f->shadow ? f->offset : 0);
236 #else
237     return f->xftfont->ascent + f->xftfont->descent +
238            (f->shadow ? f->offset : 0);
239 #endif
240 }
241
242 gint RrFontMaxCharWidth(const RrFont *f)
243 {
244     return (signed) f->xftfont->max_advance_width;
245 }
246
247 #ifdef USE_PANGO
248 static inline int font_calculate_baseline(RrFont *f, gint height)
249 {
250 /* For my own reference:
251  *   _________
252  *  ^space/2  ^height     ^baseline
253  *  v_________|_          |
254  *            | ^ascent   |   _           _
255  *            | |         |  | |_ _____ _| |_ _  _
256  *            | |         |  |  _/ -_) \ /  _| || |
257  *            | v_________v   \__\___/_\_\\__|\_, |
258  *            | ^descent                      |__/
259  *  __________|_v
260  *  ^space/2  |
261  *  V_________v
262  */
263     int asc = f->pango_ascent;
264     int ascdesc = asc + f->pango_descent;
265     int space = height * PANGO_SCALE - ascdesc;
266     int baseline = space / 2 + asc;
267     return baseline / PANGO_SCALE;
268 }
269 #endif
270
271 void RrFontDraw(XftDraw *d, RrTextureText *t, RrRect *area)
272 {
273     gint x,y,w,h;
274     XftColor c;
275     GString *text;
276     gint mw, mh;
277 #ifndef USE_PANGO
278     size_t l;
279     gboolean shortened = FALSE;
280 #else
281     PangoLayout *pl;
282     PangoRectangle rect;
283
284     pl = pango_layout_new (context);
285 #endif /* USE_PANGO */
286
287     /* center vertically
288      * for xft we pass the top edge of the text for positioning... */
289 #ifndef USE_PANGO
290     y = area->y +
291         (area->height - RrFontHeight(t->font)) / 2;
292 #else
293     /* but for pango we pass the baseline, since different fonts have
294      * different top edges. It looks stupid when the baseline of "normal"
295      * text jumps up and down when a "strange" character is just added
296      * to the end of the text */
297     y = area->y +
298         font_calculate_baseline(t->font, area->height);
299 #endif
300     /* the +2 and -4 leave a small blank edge on the sides */
301     x = area->x + 2;
302     w = area->width - 4;
303     h = area->height;
304
305     text = g_string_new(t->string);
306 #ifndef USE_PANGO
307     l = g_utf8_strlen(text->str, -1);
308     font_measure_full(t->font, text->str, &mw, &mh);
309     while (l && mw > area->width) {
310         shortened = TRUE;
311         /* remove a character from the middle */
312         text = g_string_erase(text, l-- / 2, 1);
313         /* if the elipses are too large, don't show them at all */
314         if (ELIPSES_LENGTH(t->font) > area->width)
315             shortened = FALSE;
316         font_measure_full(t->font, text->str, &mw, &mh);
317         mw += ELIPSES_LENGTH(t->font);
318     }
319     if (shortened) {
320         text = g_string_insert(text, (l + 1) / 2, ELIPSES);
321         l += 3;
322     }
323     if (!l) return;
324
325     l = strlen(text->str); /* number of bytes */
326
327 #else
328     pango_layout_set_text(pl, text->str, -1);
329     pango_layout_set_font_description(pl, t->font->pango_font_description);
330     pango_layout_set_single_paragraph_mode(pl, TRUE);
331     pango_layout_set_width(pl, w * PANGO_SCALE);
332     pango_layout_set_ellipsize(pl, PANGO_ELLIPSIZE_MIDDLE);
333     /* This doesn't work with layout_line() of course */
334 /*    pango_layout_set_alignment(pl, (PangoAlignment)(t->justify)); */
335     pango_layout_get_pixel_extents(pl, NULL, &rect);
336     mw = rect.width;
337
338 #endif /* USE_PANGO */
339
340     switch (t->justify) {
341     case RR_JUSTIFY_LEFT:
342         break;
343     case RR_JUSTIFY_RIGHT:
344         x += (w - mw);
345         break;
346     case RR_JUSTIFY_CENTER:
347         x += (w - mw) / 2;
348         break;
349     }
350
351     if (t->font->shadow) {
352         if (t->font->tint >= 0) {
353             c.color.red = 0;
354             c.color.green = 0;
355             c.color.blue = 0;
356             c.color.alpha = 0xffff * t->font->tint / 100;
357             c.pixel = BlackPixel(RrDisplay(t->font->inst),
358                                  RrScreen(t->font->inst));
359         } else {
360             c.color.red = 0xffff;
361             c.color.green = 0xffff;
362             c.color.blue = 0xffff;
363             c.color.alpha = 0xffff * -t->font->tint / 100;
364             c.pixel = WhitePixel(RrDisplay(t->font->inst),
365                                  RrScreen(t->font->inst));
366         }
367 #ifndef USE_PANGO
368         XftDrawStringUtf8(d, &c, t->font->xftfont, x + t->font->offset,
369                           t->font->xftfont->ascent + y + t->font->offset,
370                           (FcChar8*)text->str, l);
371 #else /* USE_PANGO */
372         /* see below... */
373         pango_xft_render_layout_line(d, &c, pango_layout_get_line(pl, 0),
374                                      (x + t->font->offset) * PANGO_SCALE,
375                                      (y + t->font->offset) * PANGO_SCALE);
376 #endif /* USE_PANGO */
377     }
378     c.color.red = t->color->r | t->color->r << 8;
379     c.color.green = t->color->g | t->color->g << 8;
380     c.color.blue = t->color->b | t->color->b << 8;
381     c.color.alpha = 0xff | 0xff << 8; /* fully opaque text */
382     c.pixel = t->color->pixel;
383
384 #ifndef USE_PANGO
385     XftDrawStringUtf8(d, &c, t->font->xftfont, x,
386                       t->font->xftfont->ascent + y,
387                       (FcChar8*)text->str, l);
388 #else /* USE_PANGO */
389     /* This looks retarded, but layout_line() bases y on the baseline, while
390      * layout() bases y on the top of the ink layout shit ass fucking crap.
391      * We want the baseline to always be in the same place, thusly, we use
392      * layout_line()
393      * The actual line doesn't need to be freed */
394     pango_xft_render_layout_line(d, &c, pango_layout_get_line(pl, 0),
395                                  x * PANGO_SCALE, y * PANGO_SCALE);
396     g_object_unref(pl);
397 #endif
398
399     g_string_free(text, TRUE);
400     return;
401 }