Do not compile in the block builtin graphics with --disable-frills.
[dana/urxvt.git] / src / rxvtfont.C
1 /*----------------------------------------------------------------------*
2  * File:        rxvtfont.C
3  *----------------------------------------------------------------------*
4  * Copyright (c) 2003-2006 Marc Lehmann <pcg@goof.com>
5  *                              - original version.
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  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  *---------------------------------------------------------------------*/
21
22 #include "../config.h"
23 #include "rxvt.h"
24 #include "rxvtlib.h"
25 #include "rxvtutil.h"
26 #include "rxvtfont.h"
27
28 #include <cstdlib>
29
30 #include <inttypes.h>
31
32 #define MAX_OVERLAP_ROMAN  (8 + 2)      // max. character width in 8ths of the base width
33 #define MAX_OVERLAP_ITALIC (8 + 3)      // max. overlap for italic fonts
34
35 #define OVERLAP_OK(w,wcw,prop) ((w) <= (                        \
36   (prop)->slant >= rxvt_fontprop::italic                        \
37     ? ((prop)->width * (wcw) * MAX_OVERLAP_ITALIC + 7) >> 3     \
38     : ((prop)->width * (wcw) * MAX_OVERLAP_ROMAN  + 7) >> 3     \
39   ))
40
41 const struct rxvt_fallback_font {
42   codeset cs;
43   const char *name;
44 } fallback_fonts[] = {
45   { CS_ISO8859_1,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-1"           },
46   { CS_ISO8859_15,   "-*-*-*-r-*--*-*-*-*-c-*-iso8859-15"          },
47   { CS_ISO8859_15,   "-*-*-*-r-*--*-*-*-*-c-*-fcd8859-15"          },
48
49 #if ENCODING_EU
50   // cyrillic
51   { CS_KOI8_R,        "-*-*-*-r-*--*-*-*-*-c-*-koi8-r"             },
52   { CS_KOI8_U,        "-*-*-*-r-*--*-*-*-*-c-*-koi8-u"             },
53
54   { CS_ISO8859_2,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-2"           },
55   { CS_ISO8859_3,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-3"           },
56   { CS_ISO8859_4,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-4"           },
57   { CS_ISO8859_5,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-5"           },
58   { CS_ISO8859_6,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-6"           },
59   { CS_ISO8859_7,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-7"           },
60   { CS_ISO8859_8,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-8"           },
61   { CS_ISO8859_9,    "-*-*-*-r-*--*-*-*-*-c-*-iso8859-9"           },
62   { CS_ISO8859_10,   "-*-*-*-r-*--*-*-*-*-c-*-iso8859-10"          },
63   { CS_ISO8859_11,   "-*-*-*-r-*--*-*-*-*-c-*-iso8859-11"          },
64   { CS_ISO8859_13,   "-*-*-*-r-*--*-*-*-*-c-*-iso8859-13"          },
65   { CS_ISO8859_14,   "-*-*-*-r-*--*-*-*-*-c-*-iso8859-14"          },
66   { CS_ISO8859_16,   "-*-*-*-r-*--*-*-*-*-c-*-iso8859-16"          },
67
68 # if XFT
69   { CS_KOI8_U,       "xft::lang=ru"                                },
70
71   { CS_ISO8859_5,    "xft::lang=ru"                                },
72   { CS_ISO8859_6,    "xft::lang=ar"                                },
73   { CS_ISO8859_7,    "xft::lang=el"                                },
74   { CS_ISO8859_8,    "xft::lang=he"                                },
75   { CS_ISO8859_9,    "xft::lang=tr"                                },
76   { CS_ISO8859_10,   "xft::lang=se"                                },
77   { CS_ISO8859_11,   "xft::lang=th"                                },
78 # endif
79 #endif
80
81   // japanese
82 #if ENCODING_JP || ENCODING_JP_EXT
83 # if XFT
84   // prefer xft for complex scripts
85   { CS_JIS0208_1990_0, "xft:Kochi Gothic:antialias=false"          },
86   { CS_JIS0208_1990_0, "xft:Sazanami Mincho:antialias=false"       },
87   { CS_JIS0208_1990_0, "xft:Mincho:antialias=false"                },
88   { CS_JIS0208_1990_0, "xft::lang=ja:antialias=false"              },
89 # endif
90   { CS_JIS0201_1976_0, "-*-mincho-*-r-*--*-*-*-*-c-*-jisx0201*-0"  },
91   { CS_JIS0208_1990_0, "-*-mincho-*-r-*--*-*-*-*-c-*-jisx0208*-0"  },
92   { CS_JIS0212_1990_0, "-*-mincho-*-r-*--*-*-*-*-c-*-jisx0212*-0"  },
93   { CS_JIS0201_1976_0, "-*-*-*-r-*--*-*-*-*-c-*-jisx0201*-0"       },
94   { CS_JIS0208_1990_0, "-*-*-*-r-*--*-*-*-*-c-*-jisx0208*-0"       },
95   { CS_JIS0212_1990_0, "-*-*-*-r-*--*-*-*-*-c-*-jisx0212*-0"       },
96 #endif
97
98 #if ENCODING_ZH || ENCODING_ZH_EXT
99 # if XFT
100   { CS_GBK_0,          "xft:AR PL KaitiM GB"                       },
101   { CS_GBK_0,          "xft:AR PL SungtiL GB"                      },
102   { CS_GBK_0,          "xft::lang=zh"                              },
103   { CS_BIG5_EXT,       "xft:AR PL Mingti2L Big5"                   },
104   { CS_BIG5_EXT,       "xft:AR PL KaitiM Big5"                     },
105   { CS_GB2312_1980_0,  "xft:AR PL KaitiM GB"                       },
106   { CS_GB2312_1980_0,  "xft:AR PL SungtiL GB"                      },
107   { CS_GB2312_1980_0,  "xft::lang=zh"                              },
108 # endif
109   { CS_GBK_0,           "-*-*-*-*-*-*-*-*-*-*-c-*-gbk*-0"          },
110   { CS_BIG5,            "-*-*-*-*-*-*-*-*-*-*-c-*-big5-0"          },
111   { CS_BIG5_PLUS,       "-*-*-*-*-*-*-*-*-*-*-c-*-big5p-0"         },
112   { CS_BIG5_EXT,        "-*-*-*-*-*-*-*-*-*-*-c-*-big5.eten-0"     },
113   { CS_GB2312_1980_0,   "-*-*-*-*-*-*-*-*-*-*-c-*-gb2312*-0"       },
114   { CS_CNS11643_1992_1, "-*-*-*-*-*-*-*-*-*-*-c-*-gb2312*-0"       },
115   { CS_CNS11643_1992_1, "-*-*-*-*-*-*-*-*-*-*-c-*-cns11643*-1"     },
116   { CS_CNS11643_1992_2, "-*-*-*-*-*-*-*-*-*-*-c-*-cns11643*-2"     },
117   { CS_CNS11643_1992_3, "-*-*-*-*-*-*-*-*-*-*-c-*-cns11643*-3"     },
118   { CS_CNS11643_1992_4, "-*-*-*-*-*-*-*-*-*-*-c-*-cns11643*-4"     },
119   { CS_CNS11643_1992_5, "-*-*-*-*-*-*-*-*-*-*-c-*-cns11643*-5"     },
120   { CS_CNS11643_1992_6, "-*-*-*-*-*-*-*-*-*-*-c-*-cns11643*-6"     },
121   { CS_CNS11643_1992_7, "-*-*-*-*-*-*-*-*-*-*-c-*-cns11643*-7"     },
122   { CS_CNS11643_1992_F, "-*-*-*-*-*-*-*-*-*-*-c-*-cns11643*-f"     },
123 #endif
124
125 #if ENCODING_KR
126   { CS_KSC5601_1987_0,  "-baekmuk-gulim-*-*-*-*-*-*-*-*-c-*-ksc5601*" },
127   { CS_KSC5601_1987_0,  "-*-*-*-*-*-*-*-*-*-*-c-*-ksc5601*"        },
128 # if XFT
129   { CS_KSC5601_1987_0,  "xft:Baekmuk Gulim:antialias=false"        },
130   { CS_KSC5601_1987_0,  "xft::lang=ko:antialias=false"             },
131 # endif
132 #endif
133
134   { CS_UNICODE,      "-*-lucidatypewriter-*-*-*-*-*-*-*-*-m-*-iso10646-1" },
135   //{ CS_UNICODE,      "-*-unifont-*-*-*-*-*-*-*-*-c-*-iso10646-1"   }, // this gem of a font has actual dotted circles within the combining character glyphs.
136 #if XFT
137   { CS_UNICODE,      "xft:Bitstream Vera Sans Mono:antialias=false:autohint=true" },
138   { CS_UNICODE,      "xft:Courier New:antialias=false:autohint=true"              },
139   { CS_UNICODE,      "xft:Andale Mono:antialias=false:autohint=false"             },
140   { CS_UNICODE,      "xft:Arial Unicode MS:antialias=false:autohint=false"        },
141
142   // FreeMono is usually uglier than x fonts, so try after the others
143   { CS_UNICODE,      "xft:FreeMono:autohint=true"                  },
144 #endif
145
146   // generic font fallback, put this last, as many iso10646 fonts have extents
147   // specified for all glyphs in the range they cover, but most are simply empty
148   //{ CS_UNICODE,      "-*-*-*-r-*-*-*-*-*-*-c-*-iso10646-1"         },
149   //{ CS_UNICODE,      "-*-*-*-r-*-*-*-*-*-*-m-*-iso10646-1"         },
150   { CS_UNKNOWN, 0 }
151 };
152
153 // these characters are used to guess the font height and width
154 // pango uses a similar algorithm and doesn't trust the font either.
155 static uint16_t extent_test_chars[] = {
156   '0', '1', '8', 'a', 'd', 'x', 'm', 'y', 'g', 'W', 'X', '\'', '_',
157   0x00cd, 0x00d5, 0x0114, 0x0177, 0x0643,       // ÍÕĔŷﻙ
158   0x304c, 0x672c,                               // が本
159 };
160
161 #define NUM_EXTENT_TEST_CHARS (sizeof (extent_test_chars) / sizeof (extent_test_chars[0]))
162
163 #define dTermDisplay Display *disp = term->dpy
164 #define dTermGC      GC gc = term->gc
165
166 /////////////////////////////////////////////////////////////////////////////
167
168 static const char *
169 enc_char (const text_t *text, uint32_t len, codeset cs, bool &zero)
170 {
171   uint8_t *buf = rxvt_temp_buf<uint8_t> (len);
172   uint8_t *res = buf;
173
174   while (len--)
175     {
176       uint32_t c = FROM_UNICODE (cs, *text++);
177
178       if (c == NOCHAR)
179         {
180           c = 0;
181           zero = true;
182         }
183
184       *buf++ = c;
185     }
186
187   return (const char *)res;
188 }
189
190 static const XChar2b *
191 enc_xchar2b (const text_t *text, uint32_t len, codeset cs, bool &zero)
192 {
193   XChar2b *buf = rxvt_temp_buf<XChar2b> (len);
194   XChar2b *res = buf;
195
196   while (len--)
197     {
198       uint32_t c = FROM_UNICODE (cs, *text++);
199
200       if (c == NOCHAR)
201         {
202           c = 0;
203           zero = true;
204         }
205
206       buf->byte1 = c >> 8;
207       buf->byte2 = c;
208       buf++;
209     }
210
211   return res;
212 }
213
214 /////////////////////////////////////////////////////////////////////////////
215
216 rxvt_font::rxvt_font ()
217 : name(0), width(rxvt_fontprop::unset), height(rxvt_fontprop::unset)
218 {
219 }
220
221 void
222 rxvt_font::set_name (char *name)
223 {
224   if (this->name == name)
225     return;
226
227   if (this->name) free (this->name); // let the compiler optimize
228   this->name = name;
229 }
230
231 void
232 rxvt_font::clear_rect (rxvt_drawable &d, int x, int y, int w, int h, int color) const
233 {
234   dTermDisplay;
235   dTermGC;
236
237   if (color == Color_bg || color == Color_transparent)
238     XClearArea (disp, d, x, y, w, h, false);
239   else if (color >= 0)
240     {
241 #if XFT
242       bool done = false;
243 #ifdef HAVE_BG_PIXMAP
244       if (term->bgPixmap.pixmap && color >= 0 && term->pix_colors[color].c.color.alpha < 0x0ff00)
245         {
246           Picture dst = XftDrawPicture (d);
247           if (dst != 0)
248             {
249               XClearArea (disp, d, x, y, w, h, false);
250               Picture solid_color_pict = XftDrawSrcPicture (d, &term->pix_colors[color].c);
251               XRenderComposite (disp, PictOpOver, solid_color_pict, None, dst, 0, 0, 0, 0, x, y, w, h);
252               done = true;
253             }
254         }
255 #endif
256       if (!done)
257         XftDrawRect (d, &term->pix_colors[color].c, x, y, w, h);
258 #else
259       XSetForeground (disp, gc, term->pix_colors[color]);
260       XFillRectangle (disp, d, gc, x, y, w, h);
261 #endif
262     }
263 }
264
265 /////////////////////////////////////////////////////////////////////////////
266
267 struct rxvt_font_default : rxvt_font {
268   struct rxvt_fontset *fs;
269
270   rxvt_font_default (rxvt_fontset *fs)
271   : rxvt_font ()
272   {
273     this->fs = fs;
274   }
275
276   rxvt_fontprop properties ()
277   {
278     rxvt_fontprop p;
279
280     p.width = p.height = 1;
281     p.ascent = rxvt_fontprop::unset;
282     p.weight = rxvt_fontprop::medium;
283     p.slant = rxvt_fontprop::roman;
284
285     return p;
286   }
287
288   bool load (const rxvt_fontprop &prop, bool force_prop)
289   {
290     width = 1; height = 1;
291     ascent = 1; descent = 0;
292
293     set_name (strdup ("built-in support font"));
294
295     return true;
296   }
297
298   bool has_char (unicode_t unicode, const rxvt_fontprop *prop, bool &careful) const
299   {
300     careful = false;
301
302     if (unicode <= 0x001f)
303       return true;
304
305     if (unicode <= 0x007f)
306       return false;
307
308     if (unicode <= 0x009f)
309       return true;
310
311     if (unicode >= 0x2500 && unicode <= 0x259f &&
312         !term->option (Opt_skipBuiltinGlyphs))
313       return true;
314
315     if (IS_COMPOSE (unicode))
316       return true;
317
318     switch (unicode)
319       {
320         case ZERO_WIDTH_CHAR:
321         case NOCHAR:
322           return true;
323       }
324
325     return false;
326   }
327
328   void draw (rxvt_drawable &d, int x, int y,
329              const text_t *text, int len,
330              int fg, int bg);
331 };
332
333 void
334 rxvt_font_default::draw (rxvt_drawable &d, int x, int y,
335                          const text_t *text, int len,
336                          int fg, int bg)
337 {
338   dTermDisplay;
339   dTermGC;
340
341   clear_rect (d, x, y, term->fwidth * len, term->fheight, bg);
342
343   XSetForeground (disp, gc, term->pix_colors[fg]);
344
345   while (len)
346     {
347 #if ENABLE_COMBINING
348       compose_char *cc;
349 #endif
350       const text_t *tp = text;
351       text_t t  = *tp;
352
353       while (++text, --len && *text == NOCHAR)
354         ;
355
356       int width = text - tp;
357       int fwidth = term->fwidth * width;
358
359 #ifdef BUILTIN_GLYPHS
360       if (0x2500 <= t && t <= 0x259f)
361         {
362 # include "table/linedraw.h"
363           uint16_t offs = linedraw_offs[t - 0x2500];
364           uint32_t *a = linedraw_command + (offs >> 4);
365           uint32_t *b = a + (offs & 15);
366
367           int W = fwidth;
368           int H = term->fheight;
369
370           int x_[16];
371           int y_[16];
372
373           for (int i = 0; i <= 8; i++)
374             {
375               x_[i] = x + ((W-1) * i + (i*7/8)) / 8;
376               y_[i] = y + ((H-1) * i + (i*7/8)) / 8;
377             }
378
379           x_[10] = x + (W - 1) / 2; x_[9] = x_[10] - 1; x_[11] = x_[10] + 1;
380           y_[10] = y + (H - 1) / 2; y_[9] = y_[10] - 1; y_[11] = y_[10] + 1;
381
382           XGCValues gcv;
383
384           gcv.cap_style = CapButt;
385           gcv.line_width = 0;
386           XChangeGC (disp, gc, GCLineWidth | GCCapStyle, &gcv);
387
388           while (a < b)
389             {
390               uint32_t command = *a++;
391
392               int op = (command >> 24) & 255;
393               int a  = (command >> 20) & 15;
394               int b  = (command >> 16) & 15;
395               int x1 = x_[(command >> 12) & 15];
396               int y1 = y_[(command >>  8) & 15];
397               int x2 = x_[(command >>  4) & 15];
398               int y2 = y_[(command >>  0) & 15];
399
400               switch (op)
401                 {
402                   case 0: // line
403                     XDrawLine (disp, d, gc, x1, y1, x2, y2);
404                     break;
405
406                   case 1: // rectangle, possibly stippled
407                     if (a)
408                       {
409                         static char bm[] = { 0,0 , 3,1 , 1,2 , 1,0 };
410
411                         gcv.fill_style = FillStippled;
412                         gcv.stipple = XCreateBitmapFromData (disp, d, bm + a * 2, 2, 2);
413                         gcv.ts_x_origin = x;
414                         gcv.ts_y_origin = y;
415
416                         XChangeGC (disp, gc,
417                                    GCFillStyle | GCStipple | GCTileStipXOrigin | GCTileStipYOrigin,
418                                    &gcv);
419                       }
420
421                     XFillRectangle (disp, d, gc, x1, y1, x2 - x1 + 1, y2 - y1 + 1);
422
423                     if (a)
424                       {
425                         XFreePixmap (disp, gcv.stipple);
426                         gcv.stipple = 0;
427                         gcv.fill_style = FillSolid;
428                         XChangeGC (disp, gc, GCFillStyle, &gcv);
429                       }
430                     break;
431                   case 2: // arc
432                     XDrawArc (disp, d, gc,
433                               x1 - W/2, y1 - H/2, W-1, H-1,
434                               (a - 1) * 90*64, (b - 1) * 90*64);
435                     break;
436                 }
437             }
438         }
439 #else
440       if (0)
441         ;
442 #endif
443 #if ENABLE_COMBINING
444       else if (IS_COMPOSE (t) && (cc = rxvt_composite[t]))
445         {
446           min_it (width, 2); // we only support wcwidth up to 2
447
448           text_t chrs[2];
449           chrs [1] = NOCHAR;
450
451           *chrs = cc->c1;
452           rxvt_font *f1 = (*fs)[fs->find_font (cc->c1)];
453           f1->draw (d, x, y, chrs, width, fg, bg);
454
455           if (cc->c2 != NOCHAR)
456             {
457               bool careful;
458
459               // prefer font of first character, for no good reasons
460               *chrs = cc->c2;
461               rxvt_font *f2 = (f1->has_char (cc->c2, 0, careful) && !careful)
462                                 ? f1
463                                 : (*fs)[fs->find_font (cc->c2)];
464
465               f2->draw (d, x, y, chrs, width, fg, Color_none);
466             }
467         }
468 #endif
469       else
470         switch (t)
471           {
472             case '\t':
473             case ZERO_WIDTH_CHAR:
474             case NOCHAR:
475               break;
476
477             default:
478               XDrawRectangle (disp, d, gc, x + 2, y + 2,
479                               fwidth - 4, term->fheight - 4);
480           }
481
482       x += fwidth;
483     }
484 }
485
486 /////////////////////////////////////////////////////////////////////////////
487
488 struct rxvt_font_x11 : rxvt_font {
489   rxvt_font_x11 () { f = 0; }
490
491   void clear ();
492
493   rxvt_fontprop properties ();
494
495   bool load (const rxvt_fontprop &prop, bool force_prop);
496
497   bool has_char (unicode_t unicode, const rxvt_fontprop *prop, bool &careful) const;
498
499   void draw (rxvt_drawable &d, int x, int y,
500              const text_t *text, int len,
501              int fg, int bg);
502
503   bool slow; // wether this is a proportional font or has other funny characteristics
504   XFontStruct *f;
505   bool enc2b, encm;
506
507   char *get_property (XFontStruct *f, Atom property, const char *repl) const;
508   bool set_properties (rxvt_fontprop &p, int height, const char *weight, const char *slant, int avgwidth);
509   bool set_properties (rxvt_fontprop &p, XFontStruct *f);
510   bool set_properties (rxvt_fontprop &p, const char *name);
511 };
512
513 char *
514 rxvt_font_x11::get_property (XFontStruct *f, Atom property, const char *repl) const
515 {
516   unsigned long value;
517
518   if (XGetFontProperty (f, property, &value))
519     return XGetAtomName (term->dpy, value);
520   else
521     return repl ? strdup (repl) : 0;
522 }
523
524 rxvt_fontprop
525 rxvt_font_x11::properties ()
526 {
527   rxvt_fontprop p;
528   set_properties (p, f);
529   return p;
530 }
531
532 bool
533 rxvt_font_x11::set_properties (rxvt_fontprop &p, int height, const char *weight, const char *slant, int avgwidth)
534 {
535   p.width  = width != rxvt_fontprop::unset ? width
536            : avgwidth                      ? (avgwidth + 1) / 10
537                                            : (height + 1) / 2;
538   p.height = height;
539   p.ascent = rxvt_fontprop::unset;
540   p.weight = *weight == 'B' || *weight == 'b' ? rxvt_fontprop::bold : rxvt_fontprop::medium;
541   p.slant  = *slant == 'r' || *slant == 'R' ? rxvt_fontprop::roman : rxvt_fontprop::italic;
542
543   return true;
544 }
545
546 bool
547 rxvt_font_x11::set_properties (rxvt_fontprop &p, XFontStruct *f)
548 {
549   unsigned long height;
550
551 #if 0
552   if (!XGetFontProperty (f, XInternAtom (term->dpy, "PIXEL_SIZE", 0), &height))
553     return false;
554 #else
555   height = f->ascent + f->descent;
556 #endif
557
558   unsigned long avgwidth;
559   if (!XGetFontProperty (f, term->xa [XA_AVERAGE_WIDTH], &avgwidth))
560     avgwidth = 0;
561
562   char *weight = get_property (f, term->xa [XA_WEIGHT_NAME], "medium");
563   char *slant  = get_property (f, term->xa [XA_SLANT], "r");
564
565   set_properties (p, height, weight, slant, avgwidth);
566
567   free (weight);
568   free (slant);
569
570   p.ascent = f->ascent;
571
572   return true;
573 }
574
575 bool
576 rxvt_font_x11::set_properties (rxvt_fontprop &p, const char *name)
577 {
578   dTermDisplay;
579   int slashes = 0;
580   const char *comp[13];
581
582   for (const char *c = name; *c; c++)
583     if (*c == '-')
584       {
585         comp[slashes++] = c + 1;
586         if (slashes >= 13)
587           break;
588       }
589
590   /* can we short-circuit the costly XLoadQueryFont? */
591   if (slashes >= 13
592       && (*comp[ 6] >= '1' && *comp[ 6] <= '9')
593       && (*comp[11] >= '0' && *comp[11] <= '9'))
594     return set_properties (p, atoi (comp[6]), comp[2], comp[3], atoi (comp[11]));
595
596   XFontStruct *f = XLoadQueryFont (disp, name);
597
598   if (f)
599     {
600       // the font should really exist now. if not, we have a problem
601       // (e.g. if the user did xset fp rehash just when we were searching fonts).
602       // in that case, just return garbage.
603       bool ret = set_properties (p, f);
604       XFreeFont (disp, f);
605       return ret;
606     }
607   else
608     return false;
609 }
610
611 // fix the size of scalable fonts
612 static bool
613 replace_field (char *buf, const char *name, int index, const char old, const char *replace)
614 {
615   int slashes = 0;
616   const char *field, *end;
617
618   for (const char *c = name; *c; c++)
619     if (*c == '-')
620       {
621         if (slashes == index)
622           field = c + 1;
623
624         if (slashes == index + 1)
625           end = c;
626
627         if (++slashes >= 13)
628           break;
629       }
630
631   if (slashes >= 13 && (!old || *field == old))
632     {
633       // TODO: check for overflow in font-name
634       strncpy (buf, name, field - name);
635       buf += field - name;
636       strcpy (buf, replace);
637       strcat (buf, end);
638
639       return true;
640     }
641   else
642     {
643       strcpy (buf, name);
644
645       return false;
646     }
647 }
648
649 bool
650 rxvt_font_x11::load (const rxvt_fontprop &prop, bool force_prop)
651 {
652   dTermDisplay;
653
654   clear ();
655
656   char field_str[64]; // enough for 128 bits
657
658   // first morph the font if required
659   if (force_prop)
660     {
661       char fname[1024];
662
663       if (name[0] != '-')
664         {
665           f = XLoadQueryFont (disp, name);
666
667           if (!f)
668             return false;
669
670           char *new_name = get_property (f, XA_FONT, name);
671
672           if (new_name)
673             set_name (new_name);
674           else
675             rxvt_warn ("font '%s' has no FONT property, continuing without.", name);
676
677           XFreeFont (disp, f);
678           f = 0;
679         }
680
681       if (prop.weight != rxvt_fontprop::unset)
682         {
683           replace_field (fname, name, 2, 0,
684                          prop.weight < rxvt_fontprop::bold
685                            ? "medium" : "bold");
686           set_name (strdup (fname));
687         }
688
689       if (prop.slant != rxvt_fontprop::unset)
690         {
691           replace_field (fname, name, 3, 0,
692                          prop.slant < rxvt_fontprop::italic
693                            ? "r" : "i"); // TODO: handle "o"blique, too
694           set_name (strdup (fname));
695         }
696     }
697
698   sprintf (field_str, "%d", prop.height == rxvt_fontprop::unset
699                               ? 0 : prop.height);
700
701   struct font_weight {
702     char *name;
703     int diff;
704
705     void clear ()
706     {
707       name = 0;
708       diff = 0x7fffffff;
709     }
710
711     font_weight () { clear (); }
712     ~font_weight () { free (name); }
713   };
714
715   char **list;
716   int count;
717   list = XListFonts (disp, name, 4000, &count);
718
719   set_name (0);
720
721   if (!list)
722     return false;
723
724   font_weight *fonts = new font_weight[count];
725
726   for (int i = 0; i < count; i++)
727     {
728       rxvt_fontprop p;
729       char fname[1024];
730
731       int diff = 0;
732
733       if (replace_field (fname, list[i], 6, '0', field_str))
734         diff += 10; // slightly penalize scalable fonts
735       else if (replace_field (fname, list[i], 11, '0', "0"))
736         diff += 300; // more heavily penalize what looks like scaled bitmap fonts
737
738       if (!set_properties (p, fname))
739         continue;
740
741       if (prop.height != rxvt_fontprop::unset
742           && p.height > prop.height) // weed out too large fonts
743         continue;
744
745       if (prop.height != rxvt_fontprop::unset) diff += (prop.height - p.height) * 128;
746       if (prop.weight != rxvt_fontprop::unset) diff += abs (prop.weight - p.weight);
747       if (prop.slant  != rxvt_fontprop::unset) diff += abs (prop.slant  - p.slant);
748       //if (prop.width  != rxvt_fontprop::unset) diff += abs (prop.width  - p.width);
749
750       fonts[i].name = strdup (fname);
751       fonts[i].diff = diff;
752     }
753
754   XFreeFontNames (list);
755
756   // this loop only iterates when the guessed font-size is too small
757   for (;;)
758     {
759       font_weight *best = fonts + count - 1;
760
761       for (font_weight *w = best; w-- > fonts; )
762         if (w->diff <= best->diff)
763           best = w;
764
765       if (!best->name
766           || !(f = XLoadQueryFont (disp, best->name)))
767         break;
768
769       set_name (best->name);
770       best->clear ();
771
772       ascent  = f->ascent;
773       descent = f->descent;
774       height  = ascent + descent;
775
776       if (prop.height == rxvt_fontprop::unset
777           || height <= prop.height)
778         break; // font is ready for use
779
780       // PIXEL_SIZE small enough, but real height too large
781       clear ();
782     }
783
784   delete [] fonts;
785
786   if (!f)
787     return false;
788
789   char *registry = get_property (f, term->xa [XA_CHARSET_REGISTRY], 0);
790   char *encoding = get_property (f, term->xa [XA_CHARSET_ENCODING], 0);
791
792   if (registry && encoding)
793     {
794       char charset[64];
795       snprintf (charset, 64, "%s-%s", registry, encoding);
796
797       cs = codeset_from_name (charset);
798     }
799   else
800     {
801       const char *charset = get_property (f, XA_FONT, 0);
802
803       if (!charset)
804         charset = name;
805
806       int count = 13;
807       while (*charset)
808         if (*charset++ == '-' && !--count)
809           break;
810
811       cs = codeset_from_name (charset);
812     }
813
814   free (registry);
815   free (encoding);
816
817   if (cs == CS_UNICODE)
818     cs = CS_UNICODE_16; // X11 can have a max. of 65536 chars per font
819
820   encm = f->min_byte1 != 0 || f->max_byte1 != 0;
821   enc2b = encm || f->max_char_or_byte2 > 255;
822
823   slow = false;
824
825 #if 1 // only used for slow detection, TODO optimize
826   if (f->min_bounds.width == f->max_bounds.width || !f->per_char)
827     width = f->max_bounds.width;
828   else
829     {
830       slow = true;
831
832       int N = f->max_char_or_byte2 - f->min_char_or_byte2;
833
834       if (encm)
835         N += (f->max_byte1 - f->min_byte1)
836              * (f->max_char_or_byte2 - f->min_char_or_byte2 + 1);
837
838       while (N)
839         {
840           if (f->per_char[N].width > width)
841             width = f->per_char[N].width;
842
843           --N;
844         }
845     }
846 #endif
847
848   width = 1;
849
850   for (uint16_t *t = extent_test_chars + NUM_EXTENT_TEST_CHARS; t-- > extent_test_chars; )
851     {
852       if (FROM_UNICODE (cs, *t) == NOCHAR)
853         continue;
854
855       // ignore characters we wouldn't use anyways
856       bool careful;
857       if (!has_char (*t, &prop, careful))
858         continue;
859
860       XChar2b ch = { *t >> 8, *t };
861
862       XCharStruct g;
863       int dir_ret, asc_ret, des_ret;
864       XTextExtents16 (f, &ch, 1, &dir_ret, &asc_ret, &des_ret, &g);
865
866       int wcw = WCWIDTH (*t);
867       if (wcw > 0) g.width = (g.width + wcw - 1) / wcw;
868
869       if (width < g.width) width = g.width;
870     }
871
872   if (cs == CS_UNKNOWN)
873     {
874       fprintf (stderr, "unable to deduce codeset, ignoring font '%s'\n", name);
875
876       clear ();
877       return false;
878     }
879
880 #if 0 // do it per-character
881   if (prop && width > prop->width)
882     {
883       clear ();
884       return false;
885     }
886 #endif
887
888   return true;
889 }
890
891 void
892 rxvt_font_x11::clear ()
893 {
894   if (f)
895     {
896       XFreeFont (term->dpy, f);
897       f = 0;
898     }
899 }
900
901 bool
902 rxvt_font_x11::has_char (unicode_t unicode, const rxvt_fontprop *prop, bool &careful) const
903 {
904   uint32_t ch = FROM_UNICODE (cs, unicode);
905
906   if (ch == NOCHAR)
907     return false;
908
909   /* check wether the character exists in _this_ font. horrible. */
910   XCharStruct *xcs;
911
912   if (encm)
913     {
914       unsigned char byte1 = ch >> 8;
915       unsigned char byte2 = ch & 255;
916
917       if (byte1 < f->min_byte1 || byte1 > f->max_byte1
918           || byte2 < f->min_char_or_byte2 || byte2 > f->max_char_or_byte2)
919         return false;
920
921       if (f->per_char)
922         {
923           int D = f->max_char_or_byte2 - f->min_char_or_byte2 + 1;
924           int N = (byte1 - f->min_byte1) * D + byte2 - f->min_char_or_byte2;
925
926           xcs = f->per_char + N;
927         }
928       else
929         xcs = &f->max_bounds;
930     }
931   else
932     {
933       if (ch < f->min_char_or_byte2 || ch > f->max_char_or_byte2)
934         return false;
935
936       if (f->per_char)
937         xcs = f->per_char + (ch - f->min_char_or_byte2);
938       else
939         xcs = &f->max_bounds;
940     }
941
942   if (xcs->lbearing == 0 && xcs->rbearing == 0 && xcs->width == 0
943       && xcs->ascent == 0 && xcs->descent == 0)
944     return false;
945
946   if (!prop || prop->width == rxvt_fontprop::unset)
947     return true;
948
949   // check wether character overlaps previous/next character
950   int w = xcs->rbearing - xcs->lbearing;
951   int wcw = max (WCWIDTH (unicode), 1);
952
953   careful = xcs->lbearing < 0 || xcs->rbearing > prop->width * wcw;
954
955   if (careful && !OVERLAP_OK (w, wcw, prop))
956     return false;
957
958   return true;
959 }
960
961 void
962 rxvt_font_x11::draw (rxvt_drawable &d, int x, int y,
963                      const text_t *text, int len,
964                      int fg, int bg)
965 {
966   // this looks like a mess /.
967   // and it is a mess /.
968   // yet we are trying to be perfect /.
969   // but the result still isn't perfect /.
970
971   dTermDisplay;
972   dTermGC;
973
974   bool slow = this->slow
975               || width  != term->fwidth
976               || height != term->fheight;
977
978   int base = ascent; // sorry, incorrect: term->fbase;
979
980   XGCValues v;
981   v.foreground = term->pix_colors[fg];
982   v.font = f->fid;
983
984   if (enc2b)
985     {
986       const XChar2b *xc = enc_xchar2b (text, len, cs, slow);
987
988       if (bg == Color_bg && !slow)
989         {
990           v.background = term->pix_colors[bg];
991           XChangeGC (disp, gc, GCForeground | GCBackground | GCFont, &v);
992           XDrawImageString16 (disp, d, gc, x, y + base, xc, len);
993         }
994       else
995         {
996           clear_rect (d, x, y, term->fwidth * len, term->fheight, bg);
997
998           XChangeGC (disp, gc, GCForeground | GCFont, &v);
999
1000           if (slow)
1001             {
1002               do
1003                 {
1004                   if (xc->byte1 || xc->byte2)
1005                     XDrawString16 (disp, d, gc, x, y + base, xc, 1);
1006
1007                   x += term->fwidth;
1008                   xc++; len--;
1009                 }
1010               while (len);
1011             }
1012           else
1013             XDrawString16 (disp, d, gc, x, y + base, xc, len);
1014         }
1015     }
1016   else
1017     {
1018       const char *xc = enc_char (text, len, cs, slow);
1019
1020       if (bg == Color_bg && !slow)
1021         {
1022           v.background = term->pix_colors[bg];
1023           XChangeGC (disp, gc, GCForeground | GCBackground | GCFont, &v);
1024           XDrawImageString (disp, d, gc, x, y + base, xc, len);
1025         }
1026       else
1027         {
1028           clear_rect (d, x, y, term->fwidth * len, term->fheight, bg);
1029
1030           XChangeGC (disp, gc, GCForeground | GCFont, &v);
1031
1032           if (slow)
1033             {
1034               do
1035                 {
1036                   if (*xc)
1037                     XDrawString (disp, d, gc, x, y + base, xc, 1);
1038
1039                   x += term->fwidth;
1040                   xc++; len--;
1041                 }
1042               while (len);
1043             }
1044           else
1045             XDrawString (disp, d, gc, x, y + base, xc, len);
1046         }
1047     }
1048 }
1049
1050 /////////////////////////////////////////////////////////////////////////////
1051
1052 #if XFT
1053
1054 struct rxvt_font_xft : rxvt_font {
1055   rxvt_font_xft () { f = 0; }
1056
1057   void clear ();
1058
1059   rxvt_fontprop properties ();
1060
1061   bool load (const rxvt_fontprop &prop, bool force_prop);
1062
1063   void draw (rxvt_drawable &d, int x, int y,
1064              const text_t *text, int len,
1065              int fg, int bg);
1066
1067   bool has_char (unicode_t unicode, const rxvt_fontprop *prop, bool &careful) const;
1068
1069 protected:
1070   XftFont *f;
1071 };
1072
1073 void
1074 rxvt_font_xft::clear ()
1075 {
1076   if (f)
1077     {
1078       XftFontClose (term->dpy, f);
1079       f = 0;
1080     }
1081 }
1082
1083 rxvt_fontprop
1084 rxvt_font_xft::properties ()
1085 {
1086   rxvt_fontprop p;
1087
1088   FT_Face face = XftLockFace (f);
1089
1090   p.width  = width;
1091   p.height = height;
1092   p.ascent = ascent;
1093   p.weight = face->style_flags & FT_STYLE_FLAG_BOLD
1094                ? rxvt_fontprop::bold : rxvt_fontprop::medium;
1095   p.slant  = face->style_flags & FT_STYLE_FLAG_ITALIC
1096                ? rxvt_fontprop::italic : rxvt_fontprop::roman;
1097
1098   XftUnlockFace (f);
1099
1100   return p;
1101 }
1102
1103 bool
1104 rxvt_font_xft::load (const rxvt_fontprop &prop, bool force_prop)
1105 {
1106   dTermDisplay;
1107
1108   clear ();
1109
1110   FcPattern *p = FcNameParse ((FcChar8 *) name);
1111
1112   if (!p)
1113     return false;
1114
1115   FcValue v;
1116
1117   if (prop.height != rxvt_fontprop::unset
1118       && (FcPatternGet (p, FC_PIXEL_SIZE, 0, &v) != FcResultMatch
1119           && FcPatternGet (p, FC_SIZE, 0, &v) != FcResultMatch))
1120     FcPatternAddInteger (p, FC_PIXEL_SIZE, prop.height);
1121
1122   if (prop.weight != rxvt_fontprop::unset
1123       && (force_prop || FcPatternGet (p, FC_WEIGHT, 0, &v) != FcResultMatch))
1124     FcPatternAddInteger (p, FC_WEIGHT, prop.weight);
1125
1126   if (prop.slant != rxvt_fontprop::unset
1127       && (force_prop || FcPatternGet (p, FC_SLANT, 0, &v) != FcResultMatch))
1128     FcPatternAddInteger (p, FC_SLANT, prop.slant);
1129
1130 #if 0 // clipping unfortunately destroys our precious double-width-characters
1131   // clip width, we can't do better, or can we?
1132   if (FcPatternGet (p, FC_CHAR_WIDTH, 0, &v) != FcResultMatch)
1133     FcPatternAddInteger (p, FC_CHAR_WIDTH, prop->width);
1134 #endif
1135
1136   if (FcPatternGet (p, FC_MINSPACE, 0, &v) != FcResultMatch)
1137     FcPatternAddBool (p, FC_MINSPACE, 1);
1138
1139   // store generated name so iso14755 view gives better results
1140   set_name ((char *)FcNameUnparse (p));
1141
1142   XftResult result;
1143   FcPattern *match = XftFontMatch (disp, term->display->screen, p, &result);
1144
1145   FcPatternDestroy (p);
1146
1147   if (!match)
1148     return false;
1149
1150   int ftheight = 0;
1151   bool success = true;
1152
1153   for (;;)
1154     {
1155       f = XftFontOpenPattern (disp, FcPatternDuplicate (match));
1156
1157       if (!f)
1158         {
1159           success = false;
1160           break;
1161         }
1162
1163       FT_Face face = XftLockFace (f);
1164
1165       ascent  = (face->size->metrics.ascender + 63) >> 6;
1166       descent = (-face->size->metrics.descender + 63) >> 6;
1167       height  = max (ascent + descent, (face->size->metrics.height + 63) >> 6);
1168       width   = 0;
1169
1170       bool scalable = face->face_flags & FT_FACE_FLAG_SCALABLE;
1171
1172       XftUnlockFace (f);
1173
1174       int glheight = height;
1175
1176       for (uint16_t *t = extent_test_chars + NUM_EXTENT_TEST_CHARS; t-- > extent_test_chars; )
1177         {
1178           FcChar16 ch = *t;
1179
1180           if (cs != CS_UNICODE
1181               && ch > 0x100
1182               && FROM_UNICODE (cs, ch) == NOCHAR)
1183             continue;
1184
1185           // ignore characters we wouldn't use anyways
1186           bool careful;
1187           if (!has_char (*t, &prop, careful))
1188             continue;
1189
1190           XGlyphInfo g;
1191           XftTextExtents16 (disp, f, &ch, 1, &g);
1192
1193           g.width -= g.x;
1194
1195           int wcw = WCWIDTH (ch);
1196           if (wcw > 0) g.width = (g.width + wcw - 1) / wcw;
1197
1198           if (width    < g.width       ) width    = g.width;
1199           if (height   < g.height      ) height   = g.height;
1200           if (glheight < g.height - g.y) glheight = g.height - g.y;
1201         }
1202
1203       if (!width)
1204         {
1205           rxvt_warn ("unable to calculate font width for '%s', ignoring.\n", name);
1206
1207           XftFontClose (disp, f);
1208           f = 0;
1209
1210           success = false;
1211           break;
1212         }
1213
1214       if (prop.height == rxvt_fontprop::unset
1215           || (height <= prop.height && glheight <= prop.height)
1216           || height <= 2
1217           || !scalable)
1218         break;
1219
1220       if (ftheight)
1221         {
1222           // take smaller steps near the end
1223           if (height > prop.height + 1) ftheight++;
1224           if (height > prop.height + 2) ftheight++;
1225           if (height > prop.height + 3) ftheight++;
1226
1227           ftheight -= height - prop.height;
1228         }
1229       else
1230         ftheight = prop.height - 1;
1231
1232       XftFontClose (disp, f);
1233       FcPatternDel (match, FC_PIXEL_SIZE);
1234       FcPatternAddInteger (match, FC_PIXEL_SIZE, ftheight);
1235     }
1236
1237   FcPatternDestroy (match);
1238
1239 #if 0 // do it per-character
1240   if (prop.width != rxvt_fontprop::unset && width > prop.width)
1241     {
1242       clear ();
1243       success = false;
1244     }
1245 #endif
1246
1247   return success;
1248 }
1249
1250 bool
1251 rxvt_font_xft::has_char (unicode_t unicode, const rxvt_fontprop *prop, bool &careful) const
1252 {
1253   careful = false;
1254
1255   if (!XftCharExists (term->dpy, f, unicode))
1256     return false;
1257
1258   if (!prop || prop->width == rxvt_fontprop::unset)
1259     return true;
1260
1261   // check character against base font bounding box
1262   FcChar32 ch = unicode;
1263   XGlyphInfo g;
1264   XftTextExtents32 (term->dpy, f, &ch, 1, &g);
1265
1266   int w = g.width - g.x;
1267   int wcw = max (WCWIDTH (unicode), 1);
1268
1269   careful = g.x > 0 || w > prop->width * wcw;
1270
1271   if (careful && !OVERLAP_OK (w, wcw, prop))
1272     return false;
1273
1274   // this weeds out _totally_ broken fonts, or glyphs
1275   if (!OVERLAP_OK (g.xOff, wcw, prop))
1276     return false;
1277
1278   return true;
1279 }
1280
1281 void
1282 rxvt_font_xft::draw (rxvt_drawable &d, int x, int y,
1283                      const text_t *text, int len,
1284                      int fg, int bg)
1285 {
1286   XGlyphInfo extents;
1287   XftGlyphSpec *enc = (XftGlyphSpec *)rxvt_temp_buf (len * sizeof (XftGlyphSpec));
1288   XftGlyphSpec *ep = enc;
1289
1290   dTermDisplay;
1291   dTermGC;
1292
1293   int w = term->fwidth * len;
1294   int h = term->fheight;
1295
1296   /* TODO: this logic needs some more thinking, since we no longer do pseudo-transparency.
1297    * Maybe make buffering into a resource flag? Compile time option doesn't seems like a
1298    * good idea from the perspective of packaging for wide variety of user configs.
1299    */
1300   bool buffered = true
1301 #ifdef FORCE_UNBUFFERED_XFT
1302                   && bg >= 0
1303 #endif
1304                   ;
1305   // cut trailing spaces
1306   while (len && text [len - 1] == ' ')
1307     len--;
1308
1309   int x_ = buffered ? 0 : x;
1310   int y_ = buffered ? 0 : y;
1311
1312   while (len)
1313     {
1314       int cwidth = term->fwidth;
1315       FcChar32 fc = *text++; len--;
1316
1317       while (len && *text == NOCHAR)
1318         text++, len--, cwidth += term->fwidth;
1319
1320       if (fc != ' ') // skip spaces
1321         {
1322           FT_UInt glyph = XftCharIndex (disp, f, fc);
1323           XftGlyphExtents (disp, f, &glyph, 1, &extents);
1324
1325           ep->glyph = glyph;
1326           ep->x = x_ + (cwidth - extents.xOff >> 1);
1327           ep->y = y_ + ascent;
1328
1329           if (extents.xOff == 0)
1330             ep->x = x_ + cwidth;
1331
1332           ep++;
1333         }
1334
1335       x_ += cwidth;
1336     }
1337
1338   if (buffered)
1339     {
1340       bool back_rendered = false;
1341       if (ep != enc)
1342         {
1343           rxvt_drawable &d2 = d.screen->scratch_drawable (w, h);
1344
1345 #ifdef HAVE_BG_PIXMAP
1346           if (term->bgPixmap.pixmap)
1347             {
1348               Picture dst = 0;
1349
1350               if (bg >= 0 && term->pix_colors[bg].c.color.alpha < 0x0ff00)
1351                 dst = XftDrawPicture (d2);
1352
1353               if (bg < 0 || dst != 0)
1354                 {
1355                   int src_x = x, src_y = y ;
1356
1357                   if (term->bgPixmap.is_parentOrigin ())
1358                     {
1359                       src_x += term->window_vt_x;
1360                       src_y += term->window_vt_y;
1361                     }
1362
1363                   if (term->bgPixmap.pmap_width >= src_x+w
1364                       && term->bgPixmap.pmap_height >= src_y+h)
1365                     {
1366                       XCopyArea (disp, term->bgPixmap.pixmap, d2, gc,
1367                                  src_x, src_y, w, h, 0, 0);
1368                     }
1369                   else
1370                     {
1371                       XGCValues gcv;
1372
1373                       gcv.fill_style  = FillTiled;
1374                       gcv.tile        = term->bgPixmap.pixmap;
1375                       gcv.ts_x_origin = -src_x;
1376                       gcv.ts_y_origin = -src_y;
1377
1378                       XChangeGC (disp, gc,
1379                                  GCTile | GCTileStipXOrigin | GCTileStipYOrigin | GCFillStyle,
1380                                  &gcv);
1381
1382                       XFillRectangle (disp, d2, gc, 0, 0, w, h);
1383
1384                       gcv.fill_style = FillSolid;
1385                       XChangeGC (disp, gc, GCFillStyle, &gcv);
1386                     }
1387
1388                   if (bg >= 0)
1389                     {
1390                       Picture solid_color_pict = XftDrawSrcPicture (d2, &term->pix_colors[bg].c);
1391                       XRenderComposite (disp, PictOpOver, solid_color_pict, None, dst, 0, 0, 0, 0, 0, 0, w, h);
1392                     }
1393
1394                   back_rendered = true;
1395                 }
1396             }
1397 #endif
1398
1399           if (bg >= 0 && !back_rendered)
1400             XftDrawRect (d2, &term->pix_colors[bg].c, 0, 0, w, h);
1401
1402           XftDrawGlyphSpec (d2, &term->pix_colors[fg].c, f, enc, ep - enc);
1403           XCopyArea (disp, d2, d, gc, 0, 0, w, h, x, y);
1404         }
1405       else
1406         clear_rect (d, x, y, w, h, bg);
1407     }
1408   else
1409     {
1410       clear_rect (d, x, y, w, h, bg);
1411       XftDrawGlyphSpec (d, &term->pix_colors[fg].c, f, enc, ep - enc);
1412     }
1413 }
1414
1415 #endif
1416
1417 /////////////////////////////////////////////////////////////////////////////
1418
1419 rxvt_fontset::rxvt_fontset (rxvt_term *term)
1420 : fontdesc (0), term (term)
1421 {
1422   clear ();
1423 }
1424
1425 rxvt_fontset::~rxvt_fontset ()
1426 {
1427   clear ();
1428 }
1429
1430 void
1431 rxvt_fontset::clear ()
1432 {
1433   prop.width = prop.height = prop.ascent = prop.weight = prop.slant
1434     = rxvt_fontprop::unset;
1435   force_prop = false;
1436
1437   for (rxvt_font **i = fonts.begin (); i != fonts.end (); i++)
1438     FONT_UNREF (*i);
1439
1440   for (pagemap **p = fmap.begin (); p != fmap.end (); p++)
1441     delete *p;
1442
1443   free (fontdesc); fontdesc = 0;
1444
1445   fonts.clear ();
1446
1447   fallback = fallback_fonts;
1448 }
1449
1450 rxvt_font *
1451 rxvt_fontset::new_font (const char *name, codeset cs)
1452 {
1453   rxvt_font *f;
1454
1455   if (!name || !*name)
1456     {
1457       name = "";
1458       f = new rxvt_font_default (this);
1459     }
1460 #if XFT
1461   else if (!strncmp (name, "xft:", 4))
1462     {
1463       name += 4;
1464       f = new rxvt_font_xft ();
1465     }
1466 #endif
1467   else if (!strncmp (name, "x:", 2))
1468     {
1469       name += 2;
1470       f = new rxvt_font_x11;
1471     }
1472   else
1473     f = new rxvt_font_x11;
1474
1475   f->set_term (term);
1476   f->set_name (strdup (name));
1477
1478   f->cs = cs;
1479   f->loaded = false;
1480
1481   return f;
1482 }
1483
1484 /////////////////////////////////////////////////////////////////////////////
1485
1486 void
1487 rxvt_fontset::add_fonts (const char *desc)
1488 {
1489   if (desc)
1490     {
1491       char buf[512];
1492       const char *end;
1493
1494       do
1495         {
1496           while (*desc && *desc <= ' ')
1497             desc++;
1498
1499           codeset cs = CS_UNICODE;
1500
1501           if (*desc == '[')
1502             {
1503               char spec[256];
1504               const char *extra = ++desc; // not yet used
1505
1506               desc = strchr (desc, ']');
1507
1508               if (!desc)
1509                 {
1510                   rxvt_warn ("ERROR: opening '[' without closing ']' in font specification, trying to continue.\n");
1511                   break;
1512                 }
1513
1514               memcpy (spec, extra, min (desc - extra, 255));
1515               spec[min (desc - extra, 255)] = 0;
1516
1517               if (!strncmp (extra, "codeset=", sizeof ("codeset=") - 1))
1518                 cs = codeset_from_name (spec + sizeof ("codeset=") - 1);
1519               else
1520                 rxvt_warn ("unknown parameter '%s' in font specification, skipping.\n", spec);
1521
1522               desc++;
1523               while (*desc <= ' ') desc++;
1524             }
1525
1526           end = strchr (desc, ',');
1527           if (!end)
1528             end = desc + strlen (desc);
1529
1530           if (end - desc < 511)
1531             {
1532               strncpy (buf, desc, end - desc);
1533               buf[end - desc] = 0;
1534
1535               fonts.push_back (new_font (buf, cs));
1536             }
1537           else
1538             rxvt_warn ("fontset element too long (>511 bytes), ignored.");
1539
1540           desc = end + 1;
1541         }
1542       while (*end);
1543     }
1544 }
1545
1546 bool
1547 rxvt_fontset::realize_font (int i)
1548 {
1549   if (i < 0 || i >= fonts.size ())
1550     return false;
1551
1552   if (fonts[i]->loaded)
1553     return true;
1554
1555   fonts[i]->loaded = true;
1556
1557   if (!fonts[i]->load (prop, force_prop))
1558     {
1559       fonts[i]->cs = CS_UNKNOWN;
1560       return false;
1561     }
1562
1563   return true;
1564 }
1565
1566 bool
1567 rxvt_fontset::populate (const char *desc)
1568 {
1569   clear ();
1570
1571   fontdesc = strdup (desc);
1572
1573   fonts.push_back (new_font (0, CS_UNICODE));
1574   realize_font (0);
1575
1576   add_fonts (desc);
1577
1578   return true;
1579 }
1580
1581 int
1582 rxvt_fontset::find_font (const char *name) const
1583 {
1584   for (rxvt_font *const *f = fonts.begin (); f < fonts.end (); f++)
1585     if ((*f)->name && !strcmp ((*f)->name, name))
1586       return f - fonts.begin ();
1587
1588   return -1;
1589 }
1590
1591 int
1592 rxvt_fontset::find_font (unicode_t unicode)
1593 {
1594   if (unicode >= 1<<20)
1595     return 0;
1596
1597   unicode_t hi = unicode >> 8;
1598
1599   if (hi < fmap.size ()
1600       && fmap[hi]
1601       && (*fmap[hi])[unicode & 0xff] != 0xff)
1602     return (*fmap[hi])[unicode & 0xff];
1603
1604   unsigned int i;
1605
1606   for (i = 0; i < fonts.size (); i++)
1607     {
1608       rxvt_font *f = fonts[i];
1609
1610       if (!f->loaded)
1611         {
1612           if (FROM_UNICODE (f->cs, unicode) == NOCHAR)
1613             goto next_font;
1614
1615           if (!realize_font (i))
1616             goto next_font;
1617
1618           if (prop.ascent != rxvt_fontprop::unset)
1619             max_it (f->ascent, prop.ascent);
1620         }
1621
1622       if (f->cs == CS_UNKNOWN)
1623         goto next_font;
1624
1625       bool careful;
1626       if (f->has_char (unicode, &prop, careful))
1627         {
1628           if (careful)
1629             i |= 128;
1630
1631           goto found;
1632         }
1633
1634     next_font:
1635       if (i == fonts.size () - 1)
1636         {
1637           if (fallback->name)
1638             {
1639               // search through the fallback list
1640               fonts.push_back (new_font (fallback->name, fallback->cs));
1641               fallback++;
1642             }
1643           else
1644             {
1645               // try to find a new font.
1646               // only xft currently supported, as there is no
1647               // way to configure this and xft is easier to hack in,
1648               // while x11 has more framework in place already.
1649               // TODO: this is a real resource hog, xft takes ages(?)
1650 #if XFT && USE_SLOW_LOOKUP
1651               // grab the first xft font that seems suitable
1652               FcPattern *p = FcPatternCreate ();
1653
1654               FcCharSet *s = FcCharSetCreate ();
1655               FcCharSetAddChar (s, unicode);
1656               FcPatternAddCharSet (p, FC_CHARSET, s);
1657               // charsets don't help that much, as xft might return
1658               // a non-matching font even if a better font is available :/
1659
1660               x x x x TODO prop might have unset contents
1661               FcPatternAddInteger (p, FC_PIXEL_SIZE, prop.height);
1662               FcPatternAddInteger (p, FC_WEIGHT, prop.weight);
1663               FcPatternAddInteger (p, FC_SLANT, prop.slant);
1664               FcPatternAddBool    (p, FC_MINSPACE, 1);
1665               //FcPatternAddBool    (p, FC_ANTIALIAS, 1);
1666
1667               XftResult result;
1668               FcPattern *match = XftFontMatch (term->dpy, term->display->screen, p, &result);
1669
1670               FcPatternDestroy (p);
1671
1672               if (match)
1673                 {
1674                   FcPatternDel (match, FC_CHARSET);
1675                   char *font = (char *)FcNameUnparse (match);
1676                   FcPatternDestroy (match);
1677
1678                   if (find_font (font) < 0)
1679                     {
1680                       char fontname[4096];
1681                       sprintf (fontname, "xft:%-.4090s", font);
1682
1683                       fonts.push_back (new_font (fontname, CS_UNICODE));
1684                     }
1685
1686                   free (font);
1687                 }
1688 #endif
1689             }
1690         }
1691     }
1692
1693   /* we must return SOME font */
1694   i = 0;
1695
1696 found:
1697   // found a font, cache it
1698   if (i < 255)
1699     {
1700       while (hi >= fmap.size ())
1701         fmap.push_back (0);
1702
1703       if (!fmap[hi])
1704         {
1705           fmap[hi] = (pagemap *)new pagemap;
1706           memset (fmap[hi], 0xff, sizeof (pagemap));
1707         }
1708
1709       (*fmap[hi])[unicode & 0xff] = i;
1710     }
1711
1712   return i;
1713 }
1714
1715
1716