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