fix the PangoLanguage thing to get from locale
[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) 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     /* based on gtkmain.c gtk_get_default_language() */
128     PangoLanguage *ln;
129     gchar *locale, *p;
130     locale = g_strdup(setlocale(LC_CTYPE, NULL));
131     if ((p = strchr(locale, '.')))
132         *p = '\0';
133     if ((p = strchr(locale, '@')))
134         *p = '\0';
135     printf("%s\n", locale);
136     PangoFontMetrics *metrics = pango_context_get_metrics(context, out->pango_font_description, ln = pango_language_from_string(locale));
137     out->pango_ascent = pango_font_metrics_get_ascent(metrics);
138     out->pango_descent = pango_font_metrics_get_descent(metrics);
139     g_free(locale);
140     pango_font_metrics_unref(metrics);
141 #endif /* USE_PANGO */
142
143     if (FcPatternGetBool(match, OB_SHADOW, 0, &out->shadow) != FcResultMatch)
144         out->shadow = FALSE;
145
146     if (FcPatternGetInteger(match, OB_SHADOW_OFFSET, 0, &out->offset) !=
147         FcResultMatch)
148         out->offset = 1;
149
150     if (FcPatternGetInteger(match, OB_SHADOW_ALPHA, 0, &tint) != FcResultMatch)
151         tint = 25;
152     if (tint > 100) tint = 100;
153     else if (tint < -100) tint = -100;
154     out->tint = tint;
155
156     font = XftFontOpenPattern(RrDisplay(inst), match);
157     if (!font) {
158         FcPatternDestroy(match);
159         g_free(out);
160         return NULL;
161     } else
162         out->xftfont = font;
163
164 #ifdef USE_PANGO
165     /*        FcPatternDestroy(match); */
166 #endif /* USE_PANGO */
167     measure_font(out);
168
169     return out;
170 }
171
172 RrFont *RrFontOpen(const RrInstance *inst, gchar *fontstring)
173 {
174     RrFont *out;
175
176     if (!started) {
177         font_startup();
178         started = TRUE;
179     }
180
181     if ((out = openfont(inst, fontstring)))
182         return out;
183     g_warning(_("Unable to load font: %s\n"), fontstring);
184     g_warning(_("Trying fallback font: %s\n"), "sans");
185
186     if ((out = openfont(inst, "sans")))
187         return out;
188     g_warning(_("Unable to load font: %s\n"), "sans");
189
190     return NULL;
191 }
192
193 void RrFontClose(RrFont *f)
194 {
195     if (f) {
196         XftFontClose(RrDisplay(f->inst), f->xftfont);
197         g_free(f);
198     }
199 #ifdef USE_PANGO
200     pango_font_description_free(f->pango_font_description);
201 #endif
202 }
203
204 static void font_measure_full(const RrFont *f, const gchar *str,
205                               gint *x, gint *y)
206 {
207 #ifdef USE_PANGO
208     PangoLayout *pl;
209     PangoRectangle rect;
210     pl = pango_layout_new (context);
211     pango_layout_set_text(pl, str, -1);
212     pango_layout_set_font_description(pl, f->pango_font_description);
213     pango_layout_set_single_paragraph_mode(pl, TRUE);
214     pango_layout_get_pixel_extents(pl, NULL, &rect);
215     *x = rect.width + (f->shadow ? ABS(f->offset) : 0);
216     *y = rect.height + (f->shadow ? ABS(f->offset) : 0);
217     g_object_unref(pl);
218
219 #else
220     XGlyphInfo info;
221
222     XftTextExtentsUtf8(RrDisplay(f->inst), f->xftfont,
223                        (const FcChar8*)str, strlen(str), &info);
224
225     *x = (signed) info.xOff + (f->shadow ? ABS(f->offset) : 0);
226     *y = info.height + (f->shadow ? ABS(f->offset) : 0);
227 #endif /* USE_PANGO */
228 }
229
230 RrSize *RrFontMeasureString(const RrFont *f, const gchar *str)
231 {
232     RrSize *size;
233     size = g_new(RrSize, 1);
234     font_measure_full (f, str, &size->width, &size->height);
235     return size;
236 }
237
238 gint RrFontHeight(const RrFont *f)
239 {
240 #ifdef USE_PANGO
241     return (f->pango_ascent
242             + f->pango_descent
243            ) / PANGO_SCALE +
244            (f->shadow ? f->offset : 0);
245 #else
246     return f->xftfont->ascent + f->xftfont->descent +
247            (f->shadow ? f->offset : 0);
248 #endif
249 }
250
251 gint RrFontMaxCharWidth(const RrFont *f)
252 {
253     return (signed) f->xftfont->max_advance_width;
254 }
255
256 #ifdef USE_PANGO
257 static inline int font_calculate_baseline(RrFont *f, gint height)
258 {
259 /* For my own reference:
260  *   _________
261  *  ^space/2  ^height     ^baseline
262  *  v_________|_          |
263  *            | ^ascent   |   _           _
264  *            | |         |  | |_ _____ _| |_ _  _
265  *            | |         |  |  _/ -_) \ /  _| || |
266  *            | v_________v   \__\___/_\_\\__|\_, |
267  *            | ^descent                      |__/
268  *  __________|_v
269  *  ^space/2  |
270  *  V_________v
271  */
272     int asc = f->pango_ascent;
273     int ascdesc = asc + f->pango_descent;
274     int space = height * PANGO_SCALE - ascdesc;
275     int baseline = space / 2 + asc;
276     return baseline / PANGO_SCALE;
277 }
278 #endif
279
280 void RrFontDraw(XftDraw *d, RrTextureText *t, RrRect *area)
281 {
282     gint x,y,w,h;
283     XftColor c;
284     GString *text;
285     gint mw, mh;
286 #ifndef USE_PANGO
287     size_t l;
288     gboolean shortened = FALSE;
289 #else
290     PangoLayout *pl;
291     PangoRectangle rect;
292
293     pl = pango_layout_new (context);
294 #endif /* USE_PANGO */
295
296     /* center vertically
297      * for xft we pass the top edge of the text for positioning... */
298 #ifndef USE_PANGO
299     y = area->y +
300         (area->height - RrFontHeight(t->font)) / 2;
301 #else
302     /* but for pango we pass the baseline, since different fonts have
303      * different top edges. It looks stupid when the baseline of "normal"
304      * text jumps up and down when a "strange" character is just added
305      * to the end of the text */
306     y = area->y +
307         font_calculate_baseline(t->font, area->height);
308 #endif
309     /* the +2 and -4 leave a small blank edge on the sides */
310     x = area->x + 2;
311     w = area->width - 4;
312     h = area->height;
313
314     text = g_string_new(t->string);
315 #ifndef USE_PANGO
316     l = g_utf8_strlen(text->str, -1);
317     font_measure_full(t->font, text->str, &mw, &mh);
318     while (l && mw > area->width) {
319         shortened = TRUE;
320         /* remove a character from the middle */
321         text = g_string_erase(text, l-- / 2, 1);
322         /* if the elipses are too large, don't show them at all */
323         if (ELIPSES_LENGTH(t->font) > area->width)
324             shortened = FALSE;
325         font_measure_full(t->font, text->str, &mw, &mh);
326         mw += ELIPSES_LENGTH(t->font);
327     }
328     if (shortened) {
329         text = g_string_insert(text, (l + 1) / 2, ELIPSES);
330         l += 3;
331     }
332     if (!l) return;
333
334     l = strlen(text->str); /* number of bytes */
335
336 #else
337     pango_layout_set_text(pl, text->str, -1);
338     pango_layout_set_font_description(pl, t->font->pango_font_description);
339     pango_layout_set_single_paragraph_mode(pl, TRUE);
340     pango_layout_set_width(pl, w * PANGO_SCALE);
341     pango_layout_set_ellipsize(pl, PANGO_ELLIPSIZE_MIDDLE);
342     /* This doesn't work with layout_line() of course */
343 /*    pango_layout_set_alignment(pl, (PangoAlignment)(t->justify)); */
344     pango_layout_get_pixel_extents(pl, NULL, &rect);
345     mw = rect.width;
346
347 #endif /* USE_PANGO */
348
349     switch (t->justify) {
350     case RR_JUSTIFY_LEFT:
351         break;
352     case RR_JUSTIFY_RIGHT:
353         x += (w - mw);
354         break;
355     case RR_JUSTIFY_CENTER:
356         x += (w - mw) / 2;
357         break;
358     }
359
360     if (t->font->shadow) {
361         if (t->font->tint >= 0) {
362             c.color.red = 0;
363             c.color.green = 0;
364             c.color.blue = 0;
365             c.color.alpha = 0xffff * t->font->tint / 100;
366             c.pixel = BlackPixel(RrDisplay(t->font->inst),
367                                  RrScreen(t->font->inst));
368         } else {
369             c.color.red = 0xffff;
370             c.color.green = 0xffff;
371             c.color.blue = 0xffff;
372             c.color.alpha = 0xffff * -t->font->tint / 100;
373             c.pixel = WhitePixel(RrDisplay(t->font->inst),
374                                  RrScreen(t->font->inst));
375         }
376 #ifndef USE_PANGO
377         XftDrawStringUtf8(d, &c, t->font->xftfont, x + t->font->offset,
378                           t->font->xftfont->ascent + y + t->font->offset,
379                           (FcChar8*)text->str, l);
380 #else /* USE_PANGO */
381         /* see below... */
382         pango_xft_render_layout_line(d, &c, pango_layout_get_line(pl, 0),
383                                      (x + t->font->offset) * PANGO_SCALE,
384                                      (y + t->font->offset) * PANGO_SCALE);
385 #endif /* USE_PANGO */
386     }
387     c.color.red = t->color->r | t->color->r << 8;
388     c.color.green = t->color->g | t->color->g << 8;
389     c.color.blue = t->color->b | t->color->b << 8;
390     c.color.alpha = 0xff | 0xff << 8; /* fully opaque text */
391     c.pixel = t->color->pixel;
392
393 #ifndef USE_PANGO
394     XftDrawStringUtf8(d, &c, t->font->xftfont, x,
395                       t->font->xftfont->ascent + y,
396                       (FcChar8*)text->str, l);
397 #else /* USE_PANGO */
398     /* This looks retarded, but layout_line() bases y on the baseline, while
399      * layout() bases y on the top of the ink layout shit ass fucking crap.
400      * We want the baseline to always be in the same place, thusly, we use
401      * layout_line()
402      * The actual line doesn't need to be freed */
403     pango_xft_render_layout_line(d, &c, pango_layout_get_line(pl, 0),
404                                  x * PANGO_SCALE, y * PANGO_SCALE);
405     g_object_unref(pl);
406 #endif
407
408     g_string_free(text, TRUE);
409     return;
410 }