]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkfont.c
Fix x11font_has_glyph so it doesn't get caught out by signed chars.
[PuTTY.git] / unix / gtkfont.c
1 /*
2  * Unified font management for GTK.
3  * 
4  * PuTTY is willing to use both old-style X server-side bitmap
5  * fonts _and_ GTK2/Pango client-side fonts. This requires us to
6  * do a bit of work to wrap the two wildly different APIs into
7  * forms the rest of the code can switch between seamlessly, and
8  * also requires a custom font selector capable of handling both
9  * types of font.
10  */
11
12 #include <assert.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <gtk/gtk.h>
16 #include <gdk/gdkkeysyms.h>
17 #include <gdk/gdkx.h>
18 #include <X11/Xlib.h>
19 #include <X11/Xutil.h>
20 #include <X11/Xatom.h>
21
22 #include "putty.h"
23 #include "gtkfont.h"
24 #include "tree234.h"
25
26 /*
27  * Future work:
28  * 
29  *  - it would be nice to have a display of the current font name,
30  *    and in particular whether it's client- or server-side,
31  *    during the progress of the font selector.
32  * 
33  *  - it would be nice if we could move the processing of
34  *    underline and VT100 double width into this module, so that
35  *    instead of using the ghastly pixmap-stretching technique
36  *    everywhere we could tell the Pango backend to scale its
37  *    fonts to double size properly and at full resolution.
38  *    However, this requires me to learn how to make Pango stretch
39  *    text to an arbitrary aspect ratio (for double-width only
40  *    text, which perversely is harder than DW+DH), and right now
41  *    I haven't the energy.
42  */
43
44 /*
45  * Ad-hoc vtable mechanism to allow font structures to be
46  * polymorphic.
47  * 
48  * Any instance of `unifont' used in the vtable functions will
49  * actually be the first element of a larger structure containing
50  * data specific to the subtype. This is permitted by the ISO C
51  * provision that one may safely cast between a pointer to a
52  * structure and a pointer to its first element.
53  */
54
55 #define FONTFLAG_CLIENTSIDE    0x0001
56 #define FONTFLAG_SERVERSIDE    0x0002
57 #define FONTFLAG_SERVERALIAS   0x0004
58 #define FONTFLAG_NONMONOSPACED 0x0008
59
60 #define FONTFLAG_SORT_MASK     0x0007 /* used to disambiguate font families */
61
62 typedef void (*fontsel_add_entry)(void *ctx, const char *realfontname,
63                                   const char *family, const char *charset,
64                                   const char *style, const char *stylekey,
65                                   int size, int flags,
66                                   const struct unifont_vtable *fontclass);
67
68 struct unifont_vtable {
69     /*
70      * `Methods' of the `class'.
71      */
72     unifont *(*create)(GtkWidget *widget, const char *name, int wide, int bold,
73                        int shadowoffset, int shadowalways);
74     unifont *(*create_fallback)(GtkWidget *widget, int height, int wide,
75                                 int bold, int shadowoffset, int shadowalways);
76     void (*destroy)(unifont *font);
77     int (*has_glyph)(unifont *font, wchar_t glyph);
78     void (*draw_text)(GdkDrawable *target, GdkGC *gc, unifont *font,
79                       int x, int y, const wchar_t *string, int len, int wide,
80                       int bold, int cellwidth);
81     void (*enum_fonts)(GtkWidget *widget,
82                        fontsel_add_entry callback, void *callback_ctx);
83     char *(*canonify_fontname)(GtkWidget *widget, const char *name, int *size,
84                                int *flags, int resolve_aliases);
85     char *(*scale_fontname)(GtkWidget *widget, const char *name, int size);
86
87     /*
88      * `Static data members' of the `class'.
89      */
90     const char *prefix;
91 };
92
93 /* ----------------------------------------------------------------------
94  * X11 font implementation, directly using Xlib calls.
95  */
96
97 static int x11font_has_glyph(unifont *font, wchar_t glyph);
98 static void x11font_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
99                               int x, int y, const wchar_t *string, int len,
100                               int wide, int bold, int cellwidth);
101 static unifont *x11font_create(GtkWidget *widget, const char *name,
102                                int wide, int bold,
103                                int shadowoffset, int shadowalways);
104 static void x11font_destroy(unifont *font);
105 static void x11font_enum_fonts(GtkWidget *widget,
106                                fontsel_add_entry callback, void *callback_ctx);
107 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
108                                        int *size, int *flags,
109                                        int resolve_aliases);
110 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
111                                     int size);
112
113 struct x11font {
114     struct unifont u;
115     /*
116      * Actual font objects. We store a number of these, for
117      * automatically guessed bold and wide variants.
118      * 
119      * The parallel array `allocated' indicates whether we've
120      * tried to fetch a subfont already (thus distinguishing NULL
121      * because we haven't tried yet from NULL because we tried and
122      * failed, so that we don't keep trying and failing
123      * subsequently).
124      */
125     XFontStruct *fonts[4];
126     int allocated[4];
127     /*
128      * `sixteen_bit' is true iff the font object is indexed by
129      * values larger than a byte. That is, this flag tells us
130      * whether we use XDrawString or XDrawString16, etc.
131      */
132     int sixteen_bit;
133     /*
134      * `variable' is true iff the font is non-fixed-pitch. This
135      * enables some code which takes greater care over character
136      * positioning during text drawing.
137      */
138     int variable;
139     /*
140      * real_charset is the charset used when translating text into the
141      * font's internal encoding inside draw_text(). This need not be
142      * the same as the public_charset provided to the client; for
143      * example, public_charset might be CS_ISO8859_1 while
144      * real_charset is CS_ISO8859_1_X11.
145      */
146     int real_charset;
147     /*
148      * Data passed in to unifont_create().
149      */
150     int wide, bold, shadowoffset, shadowalways;
151 };
152
153 static const struct unifont_vtable x11font_vtable = {
154     x11font_create,
155     NULL,                              /* no fallback fonts in X11 */
156     x11font_destroy,
157     x11font_has_glyph,
158     x11font_draw_text,
159     x11font_enum_fonts,
160     x11font_canonify_fontname,
161     x11font_scale_fontname,
162     "server",
163 };
164
165 static char *x11_guess_derived_font_name(XFontStruct *xfs, int bold, int wide)
166 {
167     Display *disp = GDK_DISPLAY();
168     Atom fontprop = XInternAtom(disp, "FONT", False);
169     unsigned long ret;
170     if (XGetFontProperty(xfs, fontprop, &ret)) {
171         char *name = XGetAtomName(disp, (Atom)ret);
172         if (name && name[0] == '-') {
173             char *strings[13];
174             char *dupname, *extrafree = NULL, *ret;
175             char *p, *q;
176             int nstr;
177
178             p = q = dupname = dupstr(name); /* skip initial minus */
179             nstr = 0;
180
181             while (*p && nstr < lenof(strings)) {
182                 if (*p == '-') {
183                     *p = '\0';
184                     strings[nstr++] = p+1;
185                 }
186                 p++;
187             }
188
189             if (nstr < lenof(strings))
190                 return NULL;           /* XLFD was malformed */
191
192             if (bold)
193                 strings[2] = "bold";
194
195             if (wide) {
196                 /* 4 is `wideness', which obviously may have changed. */
197                 /* 5 is additional style, which may be e.g. `ja' or `ko'. */
198                 strings[4] = strings[5] = "*";
199                 strings[11] = extrafree = dupprintf("%d", 2*atoi(strings[11]));
200             }
201
202             ret = dupcat("-", strings[ 0], "-", strings[ 1], "-", strings[ 2],
203                          "-", strings[ 3], "-", strings[ 4], "-", strings[ 5],
204                          "-", strings[ 6], "-", strings[ 7], "-", strings[ 8],
205                          "-", strings[ 9], "-", strings[10], "-", strings[11],
206                          "-", strings[12], NULL);
207             sfree(extrafree);
208             sfree(dupname);
209
210             return ret;
211         }
212     }
213     return NULL;
214 }
215
216 static int x11_font_width(XFontStruct *xfs, int sixteen_bit)
217 {
218     if (sixteen_bit) {
219         XChar2b space;
220         space.byte1 = 0;
221         space.byte2 = '0';
222         return XTextWidth16(xfs, &space, 1);
223     } else {
224         return XTextWidth(xfs, "0", 1);
225     }
226 }
227
228 static int x11_font_has_glyph(XFontStruct *xfs, int byte1, int byte2)
229 {
230     int index;
231
232     /*
233      * Not to be confused with x11font_has_glyph, which is a method of
234      * the x11font 'class' and hence takes a unifont as argument. This
235      * is the low-level function which grubs about in an actual
236      * XFontStruct to see if a given glyph exists.
237      *
238      * We must do this ourselves rather than letting Xlib's
239      * XTextExtents16 do the job, because XTextExtents will helpfully
240      * substitute the font's default_char for any missing glyph and
241      * not tell us it did so, which precisely won't help us find out
242      * which glyphs _are_ missing.
243      *
244      * The man page for XQueryFont is rather confusing about how the
245      * per_char array in the XFontStruct is laid out, because it gives
246      * formulae for determining the two-byte X character code _from_
247      * an index into the per_char array. Going the other way, it's
248      * rather simpler:
249      *
250      * The valid character codes have byte1 between min_byte1 and
251      * max_byte1 inclusive, and byte2 between min_char_or_byte2 and
252      * max_char_or_byte2 inclusive. This gives a rectangle of size
253      * (max_byte2-min_byte1+1) by
254      * (max_char_or_byte2-min_char_or_byte2+1), which is precisely the
255      * rectangle encoded in the per_char array. Hence, given a
256      * character code which is valid in the sense that it falls
257      * somewhere in that rectangle, its index in per_char is given by
258      * setting
259      *
260      *   x = byte2 - min_char_or_byte2
261      *   y = byte1 - min_byte1
262      *   index = y * (max_char_or_byte2-min_char_or_byte2+1) + x
263      *
264      * If min_byte1 and min_byte2 are both zero, that's a special case
265      * which can be treated as if min_byte2 was 1 instead, i.e. the
266      * per_char array just runs from min_char_or_byte2 to
267      * max_char_or_byte2 inclusive, and byte1 should always be zero.
268      */
269
270     if (byte2 < xfs->min_char_or_byte2 || byte2 > xfs->max_char_or_byte2)
271         return FALSE;
272
273     if (xfs->min_byte1 == 0 && xfs->max_byte1 == 0) {
274         index = byte2 - xfs->min_char_or_byte2;
275     } else {
276         if (byte1 < xfs->min_byte1 || byte1 > xfs->max_byte1)
277             return FALSE;
278         index = ((byte2 - xfs->min_char_or_byte2) +
279                  ((byte1 - xfs->min_byte1) *
280                   (xfs->max_char_or_byte2 - xfs->min_char_or_byte2 + 1)));
281     }
282
283     return (xfs->per_char[index].ascent + xfs->per_char[index].descent > 0 ||
284             xfs->per_char[index].width > 0);
285 }
286
287 static unifont *x11font_create(GtkWidget *widget, const char *name,
288                                int wide, int bold,
289                                int shadowoffset, int shadowalways)
290 {
291     struct x11font *xfont;
292     XFontStruct *xfs;
293     Display *disp = GDK_DISPLAY();
294     Atom charset_registry, charset_encoding, spacing;
295     unsigned long registry_ret, encoding_ret, spacing_ret;
296     int pubcs, realcs, sixteen_bit, variable;
297     int i;
298
299     xfs = XLoadQueryFont(disp, name);
300     if (!xfs)
301         return NULL;
302
303     charset_registry = XInternAtom(disp, "CHARSET_REGISTRY", False);
304     charset_encoding = XInternAtom(disp, "CHARSET_ENCODING", False);
305
306     pubcs = realcs = CS_NONE;
307     sixteen_bit = FALSE;
308     variable = TRUE;
309
310     if (XGetFontProperty(xfs, charset_registry, &registry_ret) &&
311         XGetFontProperty(xfs, charset_encoding, &encoding_ret)) {
312         char *reg, *enc;
313         reg = XGetAtomName(disp, (Atom)registry_ret);
314         enc = XGetAtomName(disp, (Atom)encoding_ret);
315         if (reg && enc) {
316             char *encoding = dupcat(reg, "-", enc, NULL);
317             pubcs = realcs = charset_from_xenc(encoding);
318
319             /*
320              * iso10646-1 is the only wide font encoding we
321              * support. In this case, we expect clients to give us
322              * UTF-8, which this module must internally convert
323              * into 16-bit Unicode.
324              */
325             if (!strcasecmp(encoding, "iso10646-1")) {
326                 sixteen_bit = TRUE;
327                 pubcs = realcs = CS_UTF8;
328             }
329
330             /*
331              * Hack for X line-drawing characters: if the primary font
332              * is encoded as ISO-8859-1, and has valid glyphs in the
333              * low character positions, it is assumed that those
334              * glyphs are the VT100 line-drawing character set.
335              */
336             if (pubcs == CS_ISO8859_1) {
337                 int ch;
338                 for (ch = 1; ch < 32; ch++)
339                     if (!x11_font_has_glyph(xfs, 0, ch))
340                         break;
341                 if (ch == 32)
342                     realcs = CS_ISO8859_1_X11;
343             }
344
345             sfree(encoding);
346         }
347     }
348
349     spacing = XInternAtom(disp, "SPACING", False);
350     if (XGetFontProperty(xfs, spacing, &spacing_ret)) {
351         char *spc;
352         spc = XGetAtomName(disp, (Atom)spacing_ret);
353
354         if (spc && strchr("CcMm", spc[0]))
355             variable = FALSE;
356     }
357
358     xfont = snew(struct x11font);
359     xfont->u.vt = &x11font_vtable;
360     xfont->u.width = x11_font_width(xfs, sixteen_bit);
361     xfont->u.ascent = xfs->ascent;
362     xfont->u.descent = xfs->descent;
363     xfont->u.height = xfont->u.ascent + xfont->u.descent;
364     xfont->u.public_charset = pubcs;
365     xfont->u.want_fallback = TRUE;
366     xfont->real_charset = realcs;
367     xfont->fonts[0] = xfs;
368     xfont->allocated[0] = TRUE;
369     xfont->sixteen_bit = sixteen_bit;
370     xfont->variable = variable;
371     xfont->wide = wide;
372     xfont->bold = bold;
373     xfont->shadowoffset = shadowoffset;
374     xfont->shadowalways = shadowalways;
375
376     for (i = 1; i < lenof(xfont->fonts); i++) {
377         xfont->fonts[i] = NULL;
378         xfont->allocated[i] = FALSE;
379     }
380
381     return (unifont *)xfont;
382 }
383
384 static void x11font_destroy(unifont *font)
385 {
386     Display *disp = GDK_DISPLAY();
387     struct x11font *xfont = (struct x11font *)font;
388     int i;
389
390     for (i = 0; i < lenof(xfont->fonts); i++)
391         if (xfont->fonts[i])
392             XFreeFont(disp, xfont->fonts[i]);
393     sfree(font);
394 }
395
396 static void x11_alloc_subfont(struct x11font *xfont, int sfid)
397 {
398     Display *disp = GDK_DISPLAY();
399     char *derived_name = x11_guess_derived_font_name
400         (xfont->fonts[0], sfid & 1, !!(sfid & 2));
401     xfont->fonts[sfid] = XLoadQueryFont(disp, derived_name);
402     xfont->allocated[sfid] = TRUE;
403     sfree(derived_name);
404     /* Note that xfont->fonts[sfid] may still be NULL, if XLQF failed. */
405 }
406
407 static int x11font_has_glyph(unifont *font, wchar_t glyph)
408 {
409     struct x11font *xfont = (struct x11font *)font;
410
411     if (xfont->sixteen_bit) {
412         /*
413          * This X font has 16-bit character indices, which means
414          * we can directly use our Unicode input value.
415          */
416         return x11_font_has_glyph(xfont->fonts[0], glyph >> 8, glyph & 0xFF);
417     } else {
418         /*
419          * This X font has 8-bit indices, so we must convert to the
420          * appropriate character set.
421          */
422         char sbstring[2];
423         int sblen = wc_to_mb(xfont->real_charset, 0, &glyph, 1,
424                              sbstring, 2, "", NULL, NULL);
425         if (!sbstring[0])
426             return FALSE;              /* not even in the charset */
427
428         return x11_font_has_glyph(xfont->fonts[0], 0,
429                                   (unsigned char)sbstring[0]);
430     }
431 }
432
433 #if !GTK_CHECK_VERSION(2,0,0)
434 #define GDK_DRAWABLE_XID(d) GDK_WINDOW_XWINDOW(d) /* GTK1's name for this */
435 #endif
436
437 static void x11font_really_draw_text_16(GdkDrawable *target, XFontStruct *xfs,
438                                         GC gc, int x, int y,
439                                         const XChar2b *string, int nchars,
440                                         int shadowoffset,
441                                         int fontvariable, int cellwidth)
442 {
443     Display *disp = GDK_DISPLAY();
444     int step, nsteps, centre;
445
446     if (fontvariable) {
447         /*
448          * In a variable-pitch font, we draw one character at a
449          * time, and centre it in the character cell.
450          */
451         step = 1;
452         nsteps = nchars;
453         centre = TRUE;
454     } else {
455         /*
456          * In a fixed-pitch font, we can draw the whole lot in one go.
457          */
458         step = nchars;
459         nsteps = 1;
460         centre = FALSE;
461     }
462
463     while (nsteps-- > 0) {
464         int X = x;
465         if (centre)
466             X += (cellwidth - XTextWidth16(xfs, string, step)) / 2;
467
468         XDrawString16(disp, GDK_DRAWABLE_XID(target), gc,
469                       X, y, string, step);
470         if (shadowoffset)
471             XDrawString16(disp, GDK_DRAWABLE_XID(target), gc,
472                           X + shadowoffset, y, string, step);
473
474         x += cellwidth;
475         string += step;
476     }
477 }
478
479 static void x11font_really_draw_text(GdkDrawable *target, XFontStruct *xfs,
480                                      GC gc, int x, int y,
481                                      const char *string, int nchars,
482                                      int shadowoffset,
483                                      int fontvariable, int cellwidth)
484 {
485     Display *disp = GDK_DISPLAY();
486     int step, nsteps, centre;
487
488     if (fontvariable) {
489         /*
490          * In a variable-pitch font, we draw one character at a
491          * time, and centre it in the character cell.
492          */
493         step = 1;
494         nsteps = nchars;
495         centre = TRUE;
496     } else {
497         /*
498          * In a fixed-pitch font, we can draw the whole lot in one go.
499          */
500         step = nchars;
501         nsteps = 1;
502         centre = FALSE;
503     }
504
505     while (nsteps-- > 0) {
506         int X = x;
507         if (centre)
508             X += (cellwidth - XTextWidth(xfs, string, step)) / 2;
509
510         XDrawString(disp, GDK_DRAWABLE_XID(target), gc,
511                     X, y, string, step);
512         if (shadowoffset)
513             XDrawString(disp, GDK_DRAWABLE_XID(target), gc,
514                         X + shadowoffset, y, string, step);
515
516         x += cellwidth;
517         string += step;
518     }
519 }
520
521 static void x11font_draw_text(GdkDrawable *target, GdkGC *gdkgc, unifont *font,
522                               int x, int y, const wchar_t *string, int len,
523                               int wide, int bold, int cellwidth)
524 {
525     Display *disp = GDK_DISPLAY();
526     struct x11font *xfont = (struct x11font *)font;
527     GC gc = GDK_GC_XGC(gdkgc);
528     int sfid;
529     int shadowoffset = 0;
530     int mult = (wide ? 2 : 1);
531
532     wide -= xfont->wide;
533     bold -= xfont->bold;
534
535     /*
536      * Decide which subfont we're using, and whether we have to
537      * use shadow bold.
538      */
539     if (xfont->shadowalways && bold) {
540         shadowoffset = xfont->shadowoffset;
541         bold = 0;
542     }
543     sfid = 2 * wide + bold;
544     if (!xfont->allocated[sfid])
545         x11_alloc_subfont(xfont, sfid);
546     if (bold && !xfont->fonts[sfid]) {
547         bold = 0;
548         shadowoffset = xfont->shadowoffset;
549         sfid = 2 * wide + bold;
550         if (!xfont->allocated[sfid])
551             x11_alloc_subfont(xfont, sfid);
552     }
553
554     if (!xfont->fonts[sfid])
555         return;                        /* we've tried our best, but no luck */
556
557     XSetFont(disp, gc, xfont->fonts[sfid]->fid);
558
559     if (xfont->sixteen_bit) {
560         /*
561          * This X font has 16-bit character indices, which means
562          * we can directly use our Unicode input string.
563          */
564         XChar2b *xcs;
565         int i;
566
567         xcs = snewn(len, XChar2b);
568         for (i = 0; i < len; i++) {
569             xcs[i].byte1 = string[i] >> 8;
570             xcs[i].byte2 = string[i];
571         }
572
573         x11font_really_draw_text_16(target, xfont->fonts[sfid], gc, x, y,
574                                     xcs, len, shadowoffset,
575                                     xfont->variable, cellwidth * mult);
576         sfree(xcs);
577     } else {
578         /*
579          * This X font has 8-bit indices, so we must convert to the
580          * appropriate character set.
581          */
582         char *sbstring = snewn(len+1, char);
583         int sblen = wc_to_mb(xfont->real_charset, 0, string, len,
584                              sbstring, len+1, ".", NULL, NULL);
585         x11font_really_draw_text(target, xfont->fonts[sfid], gc, x, y,
586                                  sbstring, sblen, shadowoffset,
587                                  xfont->variable, cellwidth * mult);
588         sfree(sbstring);
589     }
590 }
591
592 static void x11font_enum_fonts(GtkWidget *widget,
593                                fontsel_add_entry callback, void *callback_ctx)
594 {
595     char **fontnames;
596     char *tmp = NULL;
597     int nnames, i, max, tmpsize;
598
599     max = 32768;
600     while (1) {
601         fontnames = XListFonts(GDK_DISPLAY(), "*", max, &nnames);
602         if (nnames >= max) {
603             XFreeFontNames(fontnames);
604             max *= 2;
605         } else
606             break;
607     }
608
609     tmpsize = 0;
610
611     for (i = 0; i < nnames; i++) {
612         if (fontnames[i][0] == '-') {
613             /*
614              * Dismember an XLFD and convert it into the format
615              * we'll be using in the font selector.
616              */
617             char *components[14];
618             char *p, *font, *style, *stylekey, *charset;
619             int j, weightkey, slantkey, setwidthkey;
620             int thistmpsize, fontsize, flags;
621
622             thistmpsize = 4 * strlen(fontnames[i]) + 256;
623             if (tmpsize < thistmpsize) {
624                 tmpsize = thistmpsize;
625                 tmp = sresize(tmp, tmpsize, char);
626             }
627             strcpy(tmp, fontnames[i]);
628
629             p = tmp;
630             for (j = 0; j < 14; j++) {
631                 if (*p)
632                     *p++ = '\0';
633                 components[j] = p;
634                 while (*p && *p != '-')
635                     p++;
636             }
637             *p++ = '\0';
638
639             /*
640              * Font name is made up of fields 0 and 1, in reverse
641              * order with parentheses. (This is what the GTK 1.2 X
642              * font selector does, and it seems to come out
643              * looking reasonably sensible.)
644              */
645             font = p;
646             p += 1 + sprintf(p, "%s (%s)", components[1], components[0]);
647
648             /*
649              * Charset is made up of fields 12 and 13.
650              */
651             charset = p;
652             p += 1 + sprintf(p, "%s-%s", components[12], components[13]);
653
654             /*
655              * Style is a mixture of quite a lot of the fields,
656              * with some strange formatting.
657              */
658             style = p;
659             p += sprintf(p, "%s", components[2][0] ? components[2] :
660                          "regular");
661             if (!g_strcasecmp(components[3], "i"))
662                 p += sprintf(p, " italic");
663             else if (!g_strcasecmp(components[3], "o"))
664                 p += sprintf(p, " oblique");
665             else if (!g_strcasecmp(components[3], "ri"))
666                 p += sprintf(p, " reverse italic");
667             else if (!g_strcasecmp(components[3], "ro"))
668                 p += sprintf(p, " reverse oblique");
669             else if (!g_strcasecmp(components[3], "ot"))
670                 p += sprintf(p, " other-slant");
671             if (components[4][0] && g_strcasecmp(components[4], "normal"))
672                 p += sprintf(p, " %s", components[4]);
673             if (!g_strcasecmp(components[10], "m"))
674                 p += sprintf(p, " [M]");
675             if (!g_strcasecmp(components[10], "c"))
676                 p += sprintf(p, " [C]");
677             if (components[5][0])
678                 p += sprintf(p, " %s", components[5]);
679
680             /*
681              * Style key is the same stuff as above, but with a
682              * couple of transformations done on it to make it
683              * sort more sensibly.
684              */
685             p++;
686             stylekey = p;
687             if (!g_strcasecmp(components[2], "medium") ||
688                 !g_strcasecmp(components[2], "regular") ||
689                 !g_strcasecmp(components[2], "normal") ||
690                 !g_strcasecmp(components[2], "book"))
691                 weightkey = 0;
692             else if (!g_strncasecmp(components[2], "demi", 4) ||
693                      !g_strncasecmp(components[2], "semi", 4))
694                 weightkey = 1;
695             else
696                 weightkey = 2;
697             if (!g_strcasecmp(components[3], "r"))
698                 slantkey = 0;
699             else if (!g_strncasecmp(components[3], "r", 1))
700                 slantkey = 2;
701             else
702                 slantkey = 1;
703             if (!g_strcasecmp(components[4], "normal"))
704                 setwidthkey = 0;
705             else
706                 setwidthkey = 1;
707
708             p += sprintf(p, "%04d%04d%s%04d%04d%s%04d%04d%s%04d%s%04d%s",
709                          weightkey,
710                          (int)strlen(components[2]), components[2],
711                          slantkey,
712                          (int)strlen(components[3]), components[3],
713                          setwidthkey,
714                          (int)strlen(components[4]), components[4],
715                          (int)strlen(components[10]), components[10],
716                          (int)strlen(components[5]), components[5]);
717
718             assert(p - tmp < thistmpsize);
719
720             /*
721              * Size is in pixels, for our application, so we
722              * derive it directly from the pixel size field,
723              * number 6.
724              */
725             fontsize = atoi(components[6]);
726
727             /*
728              * Flags: we need to know whether this is a monospaced
729              * font, which we do by examining the spacing field
730              * again.
731              */
732             flags = FONTFLAG_SERVERSIDE;
733             if (!strchr("CcMm", components[10][0]))
734                 flags |= FONTFLAG_NONMONOSPACED;
735
736             /*
737              * Not sure why, but sometimes the X server will
738              * deliver dummy font types in which fontsize comes
739              * out as zero. Filter those out.
740              */
741             if (fontsize)
742                 callback(callback_ctx, fontnames[i], font, charset,
743                          style, stylekey, fontsize, flags, &x11font_vtable);
744         } else {
745             /*
746              * This isn't an XLFD, so it must be an alias.
747              * Transmit it with mostly null data.
748              * 
749              * It would be nice to work out if it's monospaced
750              * here, but at the moment I can't see that being
751              * anything but computationally hideous. Ah well.
752              */
753             callback(callback_ctx, fontnames[i], fontnames[i], NULL,
754                      NULL, NULL, 0, FONTFLAG_SERVERALIAS, &x11font_vtable);
755         }
756     }
757     XFreeFontNames(fontnames);
758 }
759
760 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
761                                        int *size, int *flags,
762                                        int resolve_aliases)
763 {
764     /*
765      * When given an X11 font name to try to make sense of for a
766      * font selector, we must attempt to load it (to see if it
767      * exists), and then canonify it by extracting its FONT
768      * property, which should give its full XLFD even if what we
769      * originally had was a wildcard.
770      * 
771      * However, we must carefully avoid canonifying font
772      * _aliases_, unless specifically asked to, because the font
773      * selector treats them as worthwhile in their own right.
774      */
775     XFontStruct *xfs;
776     Display *disp = GDK_DISPLAY();
777     Atom fontprop, fontprop2;
778     unsigned long ret;
779
780     xfs = XLoadQueryFont(disp, name);
781
782     if (!xfs)
783         return NULL;                   /* didn't make sense to us, sorry */
784
785     fontprop = XInternAtom(disp, "FONT", False);
786
787     if (XGetFontProperty(xfs, fontprop, &ret)) {
788         char *newname = XGetAtomName(disp, (Atom)ret);
789         if (newname) {
790             unsigned long fsize = 12;
791
792             fontprop2 = XInternAtom(disp, "PIXEL_SIZE", False);
793             if (XGetFontProperty(xfs, fontprop2, &fsize) && fsize > 0) {
794                 *size = fsize;
795                 XFreeFont(disp, xfs);
796                 if (flags) {
797                     if (name[0] == '-' || resolve_aliases)
798                         *flags = FONTFLAG_SERVERSIDE;
799                     else
800                         *flags = FONTFLAG_SERVERALIAS;
801                 }
802                 return dupstr(name[0] == '-' || resolve_aliases ?
803                               newname : name);
804             }
805         }
806     }
807
808     XFreeFont(disp, xfs);
809
810     return NULL;                       /* something went wrong */
811 }
812
813 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
814                                     int size)
815 {
816     return NULL;                       /* shan't */
817 }
818
819 #if GTK_CHECK_VERSION(2,0,0)
820
821 /* ----------------------------------------------------------------------
822  * Pango font implementation (for GTK 2 only).
823  */
824
825 #if defined PANGO_PRE_1POINT4 && !defined PANGO_PRE_1POINT6
826 #define PANGO_PRE_1POINT6              /* make life easier for pre-1.4 folk */
827 #endif
828
829 static int pangofont_has_glyph(unifont *font, wchar_t glyph);
830 static void pangofont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
831                                 int x, int y, const wchar_t *string, int len,
832                                 int wide, int bold, int cellwidth);
833 static unifont *pangofont_create(GtkWidget *widget, const char *name,
834                                  int wide, int bold,
835                                  int shadowoffset, int shadowalways);
836 static unifont *pangofont_create_fallback(GtkWidget *widget, int height,
837                                           int wide, int bold,
838                                           int shadowoffset, int shadowalways);
839 static void pangofont_destroy(unifont *font);
840 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback,
841                                  void *callback_ctx);
842 static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name,
843                                          int *size, int *flags,
844                                          int resolve_aliases);
845 static char *pangofont_scale_fontname(GtkWidget *widget, const char *name,
846                                       int size);
847
848 struct pangofont {
849     struct unifont u;
850     /*
851      * Pango objects.
852      */
853     PangoFontDescription *desc;
854     PangoFontset *fset;
855     /*
856      * The containing widget.
857      */
858     GtkWidget *widget;
859     /*
860      * Data passed in to unifont_create().
861      */
862     int bold, shadowoffset, shadowalways;
863 };
864
865 static const struct unifont_vtable pangofont_vtable = {
866     pangofont_create,
867     pangofont_create_fallback,
868     pangofont_destroy,
869     pangofont_has_glyph,
870     pangofont_draw_text,
871     pangofont_enum_fonts,
872     pangofont_canonify_fontname,
873     pangofont_scale_fontname,
874     "client",
875 };
876
877 /*
878  * This function is used to rigorously validate a
879  * PangoFontDescription. Later versions of Pango have a nasty
880  * habit of accepting _any_ old string as input to
881  * pango_font_description_from_string and returning a font
882  * description which can actually be used to display text, even if
883  * they have to do it by falling back to their most default font.
884  * This is doubtless helpful in some situations, but not here,
885  * because we need to know if a Pango font string actually _makes
886  * sense_ in order to fall back to treating it as an X font name
887  * if it doesn't. So we check that the font family is actually one
888  * supported by Pango.
889  */
890 static int pangofont_check_desc_makes_sense(PangoContext *ctx,
891                                             PangoFontDescription *desc)
892 {
893 #ifndef PANGO_PRE_1POINT6
894     PangoFontMap *map;
895 #endif
896     PangoFontFamily **families;
897     int i, nfamilies, matched;
898
899     /*
900      * Ask Pango for a list of font families, and iterate through
901      * them to see if one of them matches the family in the
902      * PangoFontDescription.
903      */
904 #ifndef PANGO_PRE_1POINT6
905     map = pango_context_get_font_map(ctx);
906     if (!map)
907         return FALSE;
908     pango_font_map_list_families(map, &families, &nfamilies);
909 #else
910     pango_context_list_families(ctx, &families, &nfamilies);
911 #endif
912
913     matched = FALSE;
914     for (i = 0; i < nfamilies; i++) {
915         if (!g_strcasecmp(pango_font_family_get_name(families[i]),
916                           pango_font_description_get_family(desc))) {
917             matched = TRUE;
918             break;
919         }
920     }
921     g_free(families);
922
923     return matched;
924 }
925
926 static unifont *pangofont_create_internal(GtkWidget *widget,
927                                           PangoContext *ctx,
928                                           PangoFontDescription *desc,
929                                           int wide, int bold,
930                                           int shadowoffset, int shadowalways)
931 {
932     struct pangofont *pfont;
933 #ifndef PANGO_PRE_1POINT6
934     PangoFontMap *map;
935 #endif
936     PangoFontset *fset;
937     PangoFontMetrics *metrics;
938
939 #ifndef PANGO_PRE_1POINT6
940     map = pango_context_get_font_map(ctx);
941     if (!map) {
942         pango_font_description_free(desc);
943         return NULL;
944     }
945     fset = pango_font_map_load_fontset(map, ctx, desc,
946                                        pango_context_get_language(ctx));
947 #else
948     fset = pango_context_load_fontset(ctx, desc,
949                                       pango_context_get_language(ctx));
950 #endif
951     if (!fset) {
952         pango_font_description_free(desc);
953         return NULL;
954     }
955     metrics = pango_fontset_get_metrics(fset);
956     if (!metrics ||
957         pango_font_metrics_get_approximate_digit_width(metrics) == 0) {
958         pango_font_description_free(desc);
959         g_object_unref(fset);
960         return NULL;
961     }
962
963     pfont = snew(struct pangofont);
964     pfont->u.vt = &pangofont_vtable;
965     pfont->u.width =
966         PANGO_PIXELS(pango_font_metrics_get_approximate_digit_width(metrics));
967     pfont->u.ascent = PANGO_PIXELS(pango_font_metrics_get_ascent(metrics));
968     pfont->u.descent = PANGO_PIXELS(pango_font_metrics_get_descent(metrics));
969     pfont->u.height = pfont->u.ascent + pfont->u.descent;
970     pfont->u.want_fallback = FALSE;
971     /* The Pango API is hardwired to UTF-8 */
972     pfont->u.public_charset = CS_UTF8;
973     pfont->desc = desc;
974     pfont->fset = fset;
975     pfont->widget = widget;
976     pfont->bold = bold;
977     pfont->shadowoffset = shadowoffset;
978     pfont->shadowalways = shadowalways;
979
980     pango_font_metrics_unref(metrics);
981
982     return (unifont *)pfont;
983 }
984
985 static unifont *pangofont_create(GtkWidget *widget, const char *name,
986                                  int wide, int bold,
987                                  int shadowoffset, int shadowalways)
988 {
989     PangoContext *ctx;
990     PangoFontDescription *desc;
991
992     desc = pango_font_description_from_string(name);
993     if (!desc)
994         return NULL;
995     ctx = gtk_widget_get_pango_context(widget);
996     if (!ctx) {
997         pango_font_description_free(desc);
998         return NULL;
999     }
1000     if (!pangofont_check_desc_makes_sense(ctx, desc)) {
1001         pango_font_description_free(desc);
1002         return NULL;
1003     }
1004     return pangofont_create_internal(widget, ctx, desc, wide, bold,
1005                                      shadowoffset, shadowalways);
1006 }
1007
1008 static unifont *pangofont_create_fallback(GtkWidget *widget, int height,
1009                                           int wide, int bold,
1010                                           int shadowoffset, int shadowalways)
1011 {
1012     PangoContext *ctx;
1013     PangoFontDescription *desc;
1014
1015     desc = pango_font_description_from_string("Monospace");
1016     if (!desc)
1017         return NULL;
1018     ctx = gtk_widget_get_pango_context(widget);
1019     if (!ctx) {
1020         pango_font_description_free(desc);
1021         return NULL;
1022     }
1023     pango_font_description_set_absolute_size(desc, height * PANGO_SCALE);
1024     return pangofont_create_internal(widget, ctx, desc, wide, bold,
1025                                      shadowoffset, shadowalways);
1026 }
1027
1028 static void pangofont_destroy(unifont *font)
1029 {
1030     struct pangofont *pfont = (struct pangofont *)font;
1031     pango_font_description_free(pfont->desc);
1032     g_object_unref(pfont->fset);
1033     sfree(font);
1034 }
1035
1036 static int pangofont_has_glyph(unifont *font, wchar_t glyph)
1037 {
1038     /* Pango implements font fallback, so assume it has everything */
1039     return TRUE;
1040 }
1041
1042 static void pangofont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
1043                                 int x, int y, const wchar_t *string, int len,
1044                                 int wide, int bold, int cellwidth)
1045 {
1046     struct pangofont *pfont = (struct pangofont *)font;
1047     PangoLayout *layout;
1048     PangoRectangle rect;
1049     char *utfstring, *utfptr;
1050     int utflen;
1051     int shadowbold = FALSE;
1052
1053     if (wide)
1054         cellwidth *= 2;
1055
1056     y -= pfont->u.ascent;
1057
1058     layout = pango_layout_new(gtk_widget_get_pango_context(pfont->widget));
1059     pango_layout_set_font_description(layout, pfont->desc);
1060     if (bold > pfont->bold) {
1061         if (pfont->shadowalways)
1062             shadowbold = TRUE;
1063         else {
1064             PangoFontDescription *desc2 =
1065                 pango_font_description_copy_static(pfont->desc);
1066             pango_font_description_set_weight(desc2, PANGO_WEIGHT_BOLD);
1067             pango_layout_set_font_description(layout, desc2);
1068         }
1069     }
1070
1071     /*
1072      * Pango always expects UTF-8, so convert the input wide character
1073      * string to UTF-8.
1074      */
1075     utfstring = snewn(len*6+1, char); /* UTF-8 has max 6 bytes/char */
1076     utflen = wc_to_mb(CS_UTF8, 0, string, len,
1077                       utfstring, len*6+1, ".", NULL, NULL);
1078
1079     utfptr = utfstring;
1080     while (utflen > 0) {
1081         int clen, n;
1082
1083         /*
1084          * We want to display every character from this string in
1085          * the centre of its own character cell. In the worst case,
1086          * this requires a separate text-drawing call for each
1087          * character; but in the common case where the font is
1088          * properly fixed-width, we can draw many characters in one
1089          * go which is much faster.
1090          *
1091          * This still isn't really ideal. If you look at what
1092          * happens in the X protocol as a result of all of this, you
1093          * find - naturally enough - that each call to
1094          * gdk_draw_layout() generates a separate set of X RENDER
1095          * operations involving creating a picture, setting a clip
1096          * rectangle, doing some drawing and undoing the whole lot.
1097          * In an ideal world, we should _always_ be able to turn the
1098          * contents of this loop into a single RenderCompositeGlyphs
1099          * operation which internally specifies inter-character
1100          * deltas to get the spacing right, which would give us full
1101          * speed _even_ in the worst case of a non-fixed-width font.
1102          * However, Pango's architecture and documentation are so
1103          * unhelpful that I have no idea how if at all to persuade
1104          * them to do that.
1105          */
1106
1107         /*
1108          * Start by extracting a single UTF-8 character from the
1109          * string.
1110          */
1111         clen = 1;
1112         while (clen < utflen &&
1113                (unsigned char)utfptr[clen] >= 0x80 &&
1114                (unsigned char)utfptr[clen] < 0xC0)
1115             clen++;
1116         n = 1;
1117
1118         /*
1119          * If it's a right-to-left character, we must display it on
1120          * its own, to stop Pango helpfully re-reversing our already
1121          * reversed text.
1122          */
1123         if (!is_rtl(string[0])) {
1124
1125             /*
1126              * See if that character has the width we expect.
1127              */
1128             pango_layout_set_text(layout, utfptr, clen);
1129             pango_layout_get_pixel_extents(layout, NULL, &rect);
1130
1131             if (rect.width == cellwidth) {
1132                 /*
1133                  * Try extracting more characters, for as long as they
1134                  * stay well-behaved.
1135                  */
1136                 while (clen < utflen) {
1137                     int oldclen = clen;
1138                     clen++;                    /* skip UTF-8 introducer byte */
1139                     while (clen < utflen &&
1140                            (unsigned char)utfptr[clen] >= 0x80 &&
1141                            (unsigned char)utfptr[clen] < 0xC0)
1142                         clen++;
1143                     n++;
1144                     pango_layout_set_text(layout, utfptr, clen);
1145                     pango_layout_get_pixel_extents(layout, NULL, &rect);
1146                     if (rect.width != n * cellwidth) {
1147                         clen = oldclen;
1148                         n--;
1149                         break;
1150                     }
1151                 }
1152             }
1153         }
1154
1155         pango_layout_set_text(layout, utfptr, clen);
1156         pango_layout_get_pixel_extents(layout, NULL, &rect);
1157         gdk_draw_layout(target, gc, x + (n*cellwidth - rect.width)/2,
1158                         y + (pfont->u.height - rect.height)/2, layout);
1159         if (shadowbold)
1160             gdk_draw_layout(target, gc, x + (n*cellwidth - rect.width)/2 + pfont->shadowoffset,
1161                             y + (pfont->u.height - rect.height)/2, layout);
1162
1163         utflen -= clen;
1164         utfptr += clen;
1165         string += n;
1166         x += n * cellwidth;
1167     }
1168
1169     sfree(utfstring);
1170
1171     g_object_unref(layout);
1172 }
1173
1174 /*
1175  * Dummy size value to be used when converting a
1176  * PangoFontDescription of a scalable font to a string for
1177  * internal use.
1178  */
1179 #define PANGO_DUMMY_SIZE 12
1180
1181 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback,
1182                                  void *callback_ctx)
1183 {
1184     PangoContext *ctx;
1185 #ifndef PANGO_PRE_1POINT6
1186     PangoFontMap *map;
1187 #endif
1188     PangoFontFamily **families;
1189     int i, nfamilies;
1190
1191     ctx = gtk_widget_get_pango_context(widget);
1192     if (!ctx)
1193         return;
1194
1195     /*
1196      * Ask Pango for a list of font families, and iterate through
1197      * them.
1198      */
1199 #ifndef PANGO_PRE_1POINT6
1200     map = pango_context_get_font_map(ctx);
1201     if (!map)
1202         return;
1203     pango_font_map_list_families(map, &families, &nfamilies);
1204 #else
1205     pango_context_list_families(ctx, &families, &nfamilies);
1206 #endif
1207     for (i = 0; i < nfamilies; i++) {
1208         PangoFontFamily *family = families[i];
1209         const char *familyname;
1210         int flags;
1211         PangoFontFace **faces;
1212         int j, nfaces;
1213
1214         /*
1215          * Set up our flags for this font family, and get the name
1216          * string.
1217          */
1218         flags = FONTFLAG_CLIENTSIDE;
1219 #ifndef PANGO_PRE_1POINT4
1220         /*
1221          * In very early versions of Pango, we can't tell
1222          * monospaced fonts from non-monospaced.
1223          */
1224         if (!pango_font_family_is_monospace(family))
1225             flags |= FONTFLAG_NONMONOSPACED;
1226 #endif
1227         familyname = pango_font_family_get_name(family);
1228
1229         /*
1230          * Go through the available font faces in this family.
1231          */
1232         pango_font_family_list_faces(family, &faces, &nfaces);
1233         for (j = 0; j < nfaces; j++) {
1234             PangoFontFace *face = faces[j];
1235             PangoFontDescription *desc;
1236             const char *facename;
1237             int *sizes;
1238             int k, nsizes, dummysize;
1239
1240             /*
1241              * Get the face name string.
1242              */
1243             facename = pango_font_face_get_face_name(face);
1244
1245             /*
1246              * Set up a font description with what we've got so
1247              * far. We'll fill in the size field manually and then
1248              * call pango_font_description_to_string() to give the
1249              * full real name of the specific font.
1250              */
1251             desc = pango_font_face_describe(face);
1252
1253             /*
1254              * See if this font has a list of specific sizes.
1255              */
1256 #ifndef PANGO_PRE_1POINT4
1257             pango_font_face_list_sizes(face, &sizes, &nsizes);
1258 #else
1259             /*
1260              * In early versions of Pango, that call wasn't
1261              * supported; we just have to assume everything is
1262              * scalable.
1263              */
1264             sizes = NULL;
1265 #endif
1266             if (!sizes) {
1267                 /*
1268                  * Write a single entry with a dummy size.
1269                  */
1270                 dummysize = PANGO_DUMMY_SIZE * PANGO_SCALE;
1271                 sizes = &dummysize;
1272                 nsizes = 1;
1273             }
1274
1275             /*
1276              * If so, go through them one by one.
1277              */
1278             for (k = 0; k < nsizes; k++) {
1279                 char *fullname;
1280                 char stylekey[128];
1281
1282                 pango_font_description_set_size(desc, sizes[k]);
1283
1284                 fullname = pango_font_description_to_string(desc);
1285
1286                 /*
1287                  * Construct the sorting key for font styles.
1288                  */
1289                 {
1290                     char *p = stylekey;
1291                     int n;
1292
1293                     n = pango_font_description_get_weight(desc);
1294                     /* Weight: normal, then lighter, then bolder */
1295                     if (n <= PANGO_WEIGHT_NORMAL)
1296                         n = PANGO_WEIGHT_NORMAL - n;
1297                     p += sprintf(p, "%4d", n);
1298
1299                     n = pango_font_description_get_style(desc);
1300                     p += sprintf(p, " %2d", n);
1301
1302                     n = pango_font_description_get_stretch(desc);
1303                     /* Stretch: closer to normal sorts earlier */
1304                     n = 2 * abs(PANGO_STRETCH_NORMAL - n) +
1305                         (n < PANGO_STRETCH_NORMAL);
1306                     p += sprintf(p, " %2d", n);
1307
1308                     n = pango_font_description_get_variant(desc);
1309                     p += sprintf(p, " %2d", n);
1310                     
1311                 }
1312
1313                 /*
1314                  * Got everything. Hand off to the callback.
1315                  * (The charset string is NULL, because only
1316                  * server-side X fonts use it.)
1317                  */
1318                 callback(callback_ctx, fullname, familyname, NULL, facename,
1319                          stylekey,
1320                          (sizes == &dummysize ? 0 : PANGO_PIXELS(sizes[k])),
1321                          flags, &pangofont_vtable);
1322
1323                 g_free(fullname);
1324             }
1325             if (sizes != &dummysize)
1326                 g_free(sizes);
1327
1328             pango_font_description_free(desc);
1329         }
1330         g_free(faces);
1331     }
1332     g_free(families);
1333 }
1334
1335 static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name,
1336                                          int *size, int *flags,
1337                                          int resolve_aliases)
1338 {
1339     /*
1340      * When given a Pango font name to try to make sense of for a
1341      * font selector, we must normalise it to PANGO_DUMMY_SIZE and
1342      * extract its original size (in pixels) into the `size' field.
1343      */
1344     PangoContext *ctx;
1345 #ifndef PANGO_PRE_1POINT6
1346     PangoFontMap *map;
1347 #endif
1348     PangoFontDescription *desc;
1349     PangoFontset *fset;
1350     PangoFontMetrics *metrics;
1351     char *newname, *retname;
1352
1353     desc = pango_font_description_from_string(name);
1354     if (!desc)
1355         return NULL;
1356     ctx = gtk_widget_get_pango_context(widget);
1357     if (!ctx) {
1358         pango_font_description_free(desc);
1359         return NULL;
1360     }
1361     if (!pangofont_check_desc_makes_sense(ctx, desc)) {
1362         pango_font_description_free(desc);
1363         return NULL;
1364     }
1365 #ifndef PANGO_PRE_1POINT6
1366     map = pango_context_get_font_map(ctx);
1367     if (!map) {
1368         pango_font_description_free(desc);
1369         return NULL;
1370     }
1371     fset = pango_font_map_load_fontset(map, ctx, desc,
1372                                        pango_context_get_language(ctx));
1373 #else
1374     fset = pango_context_load_fontset(ctx, desc,
1375                                       pango_context_get_language(ctx));
1376 #endif
1377     if (!fset) {
1378         pango_font_description_free(desc);
1379         return NULL;
1380     }
1381     metrics = pango_fontset_get_metrics(fset);
1382     if (!metrics ||
1383         pango_font_metrics_get_approximate_digit_width(metrics) == 0) {
1384         pango_font_description_free(desc);
1385         g_object_unref(fset);
1386         return NULL;
1387     }
1388
1389     *size = PANGO_PIXELS(pango_font_description_get_size(desc));
1390     *flags = FONTFLAG_CLIENTSIDE;
1391     pango_font_description_set_size(desc, PANGO_DUMMY_SIZE * PANGO_SCALE);
1392     newname = pango_font_description_to_string(desc);
1393     retname = dupstr(newname);
1394     g_free(newname);
1395
1396     pango_font_metrics_unref(metrics);
1397     pango_font_description_free(desc);
1398     g_object_unref(fset);
1399
1400     return retname;
1401 }
1402
1403 static char *pangofont_scale_fontname(GtkWidget *widget, const char *name,
1404                                       int size)
1405 {
1406     PangoFontDescription *desc;
1407     char *newname, *retname;
1408
1409     desc = pango_font_description_from_string(name);
1410     if (!desc)
1411         return NULL;
1412     pango_font_description_set_size(desc, size * PANGO_SCALE);
1413     newname = pango_font_description_to_string(desc);
1414     retname = dupstr(newname);
1415     g_free(newname);
1416     pango_font_description_free(desc);
1417
1418     return retname;
1419 }
1420
1421 #endif /* GTK_CHECK_VERSION(2,0,0) */
1422
1423 /* ----------------------------------------------------------------------
1424  * Outermost functions which do the vtable dispatch.
1425  */
1426
1427 /*
1428  * Complete list of font-type subclasses. Listed in preference
1429  * order for unifont_create(). (That is, in the extremely unlikely
1430  * event that the same font name is valid as both a Pango and an
1431  * X11 font, it will be interpreted as the former in the absence
1432  * of an explicit type-disambiguating prefix.)
1433  *
1434  * The 'multifont' subclass is omitted here, as discussed above.
1435  */
1436 static const struct unifont_vtable *unifont_types[] = {
1437 #if GTK_CHECK_VERSION(2,0,0)
1438     &pangofont_vtable,
1439 #endif
1440     &x11font_vtable,
1441 };
1442
1443 /*
1444  * Function which takes a font name and processes the optional
1445  * scheme prefix. Returns the tail of the font name suitable for
1446  * passing to individual font scheme functions, and also provides
1447  * a subrange of the unifont_types[] array above.
1448  * 
1449  * The return values `start' and `end' denote a half-open interval
1450  * in unifont_types[]; that is, the correct way to iterate over
1451  * them is
1452  * 
1453  *   for (i = start; i < end; i++) {...}
1454  */
1455 static const char *unifont_do_prefix(const char *name, int *start, int *end)
1456 {
1457     int colonpos = strcspn(name, ":");
1458     int i;
1459
1460     if (name[colonpos]) {
1461         /*
1462          * There's a colon prefix on the font name. Use it to work
1463          * out which subclass to use.
1464          */
1465         for (i = 0; i < lenof(unifont_types); i++) {
1466             if (strlen(unifont_types[i]->prefix) == colonpos &&
1467                 !strncmp(unifont_types[i]->prefix, name, colonpos)) {
1468                 *start = i;
1469                 *end = i+1;
1470                 return name + colonpos + 1;
1471             }
1472         }
1473         /*
1474          * None matched, so return an empty scheme list to prevent
1475          * any scheme from being called at all.
1476          */
1477         *start = *end = 0;
1478         return name + colonpos + 1;
1479     } else {
1480         /*
1481          * No colon prefix, so just use all the subclasses.
1482          */
1483         *start = 0;
1484         *end = lenof(unifont_types);
1485         return name;
1486     }
1487 }
1488
1489 unifont *unifont_create(GtkWidget *widget, const char *name, int wide,
1490                         int bold, int shadowoffset, int shadowalways)
1491 {
1492     int i, start, end;
1493
1494     name = unifont_do_prefix(name, &start, &end);
1495
1496     for (i = start; i < end; i++) {
1497         unifont *ret = unifont_types[i]->create(widget, name, wide, bold,
1498                                                 shadowoffset, shadowalways);
1499         if (ret)
1500             return ret;
1501     }
1502     return NULL;                       /* font not found in any scheme */
1503 }
1504
1505 void unifont_destroy(unifont *font)
1506 {
1507     font->vt->destroy(font);
1508 }
1509
1510 void unifont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
1511                        int x, int y, const wchar_t *string, int len,
1512                        int wide, int bold, int cellwidth)
1513 {
1514     font->vt->draw_text(target, gc, font, x, y, string, len,
1515                         wide, bold, cellwidth);
1516 }
1517
1518 /* ----------------------------------------------------------------------
1519  * Multiple-font wrapper. This is a type of unifont which encapsulates
1520  * up to two other unifonts, permitting missing glyphs in the main
1521  * font to be filled in by a fallback font.
1522  *
1523  * This is a type of unifont just like the previous two, but it has a
1524  * separate constructor which is manually called by the client, so it
1525  * doesn't appear in the list of available font types enumerated by
1526  * unifont_create. This means it's not used by unifontsel either, so
1527  * it doesn't need to support any methods except draw_text and
1528  * destroy.
1529  */
1530
1531 static void multifont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
1532                                 int x, int y, const wchar_t *string, int len,
1533                                 int wide, int bold, int cellwidth);
1534 static void multifont_destroy(unifont *font);
1535
1536 struct multifont {
1537     struct unifont u;
1538     unifont *main;
1539     unifont *fallback;
1540 };
1541
1542 static const struct unifont_vtable multifont_vtable = {
1543     NULL,                             /* creation is done specially */
1544     NULL,
1545     multifont_destroy,
1546     NULL,
1547     multifont_draw_text,
1548     NULL,
1549     NULL,
1550     NULL,
1551     "client",
1552 };
1553
1554 unifont *multifont_create(GtkWidget *widget, const char *name,
1555                           int wide, int bold,
1556                           int shadowoffset, int shadowalways)
1557 {
1558     int i;
1559     unifont *font, *fallback;
1560     struct multifont *mfont;
1561
1562     font = unifont_create(widget, name, wide, bold,
1563                           shadowoffset, shadowalways);
1564     if (!font)
1565         return NULL;
1566
1567     if (font->want_fallback) {
1568         for (i = 0; i < lenof(unifont_types); i++) {
1569             if (unifont_types[i]->create_fallback) {
1570                 fallback = unifont_types[i]->create_fallback
1571                     (widget, font->height, wide, bold,
1572                      shadowoffset, shadowalways);
1573                 if (fallback)
1574                     break;
1575             }
1576         }
1577     }
1578
1579     /*
1580      * Construct our multifont. Public members are all copied from the
1581      * primary font we're wrapping.
1582      */
1583     mfont = snew(struct multifont);
1584     mfont->u.vt = &multifont_vtable;
1585     mfont->u.width = font->width;
1586     mfont->u.ascent = font->ascent;
1587     mfont->u.descent = font->descent;
1588     mfont->u.height = font->height;
1589     mfont->u.public_charset = font->public_charset;
1590     mfont->u.want_fallback = FALSE; /* shouldn't be needed, but just in case */
1591     mfont->main = font;
1592     mfont->fallback = fallback;
1593
1594     return (unifont *)mfont;
1595 }
1596
1597 static void multifont_destroy(unifont *font)
1598 {
1599     struct multifont *mfont = (struct multifont *)font;
1600     unifont_destroy(mfont->main);
1601     if (mfont->fallback)
1602         unifont_destroy(mfont->fallback);
1603     sfree(font);
1604 }
1605
1606 static void multifont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
1607                                 int x, int y, const wchar_t *string, int len,
1608                                 int wide, int bold, int cellwidth)
1609 {
1610     struct multifont *mfont = (struct multifont *)font;
1611     int ok, i;
1612
1613     while (len > 0) {
1614         /*
1615          * Find a maximal sequence of characters which are, or are
1616          * not, supported by our main font.
1617          */
1618         ok = mfont->main->vt->has_glyph(mfont->main, string[0]);
1619         for (i = 1;
1620              i < len &&
1621              !mfont->main->vt->has_glyph(mfont->main, string[i]) == !ok;
1622              i++);
1623
1624         /*
1625          * Now display it.
1626          */
1627         unifont_draw_text(target, gc, ok ? mfont->main : mfont->fallback,
1628                           x, y, string, i, wide, bold, cellwidth);
1629         string += i;
1630         len -= i;
1631         x += i * cellwidth;
1632     }
1633 }
1634
1635 #if GTK_CHECK_VERSION(2,0,0)
1636
1637 /* ----------------------------------------------------------------------
1638  * Implementation of a unified font selector. Used on GTK 2 only;
1639  * for GTK 1 we still use the standard font selector.
1640  */
1641
1642 typedef struct fontinfo fontinfo;
1643
1644 typedef struct unifontsel_internal {
1645     /* This must be the structure's first element, for cross-casting */
1646     unifontsel u;
1647     GtkListStore *family_model, *style_model, *size_model;
1648     GtkWidget *family_list, *style_list, *size_entry, *size_list;
1649     GtkWidget *filter_buttons[4];
1650     GtkWidget *preview_area;
1651     GdkPixmap *preview_pixmap;
1652     int preview_width, preview_height;
1653     GdkColor preview_fg, preview_bg;
1654     int filter_flags;
1655     tree234 *fonts_by_realname, *fonts_by_selorder;
1656     fontinfo *selected;
1657     int selsize, intendedsize;
1658     int inhibit_response;  /* inhibit callbacks when we change GUI controls */
1659 } unifontsel_internal;
1660
1661 /*
1662  * The structure held in the tree234s. All the string members are
1663  * part of the same allocated area, so don't need freeing
1664  * separately.
1665  */
1666 struct fontinfo {
1667     char *realname;
1668     char *family, *charset, *style, *stylekey;
1669     int size, flags;
1670     /*
1671      * Fallback sorting key, to permit multiple identical entries
1672      * to exist in the selorder tree.
1673      */
1674     int index;
1675     /*
1676      * Indices mapping fontinfo structures to indices in the list
1677      * boxes. sizeindex is irrelevant if the font is scalable
1678      * (size==0).
1679      */
1680     int familyindex, styleindex, sizeindex;
1681     /*
1682      * The class of font.
1683      */
1684     const struct unifont_vtable *fontclass;
1685 };
1686
1687 struct fontinfo_realname_find {
1688     const char *realname;
1689     int flags;
1690 };
1691
1692 static int strnullcasecmp(const char *a, const char *b)
1693 {
1694     int i;
1695
1696     /*
1697      * If exactly one of the inputs is NULL, it compares before
1698      * the other one.
1699      */
1700     if ((i = (!b) - (!a)) != 0)
1701         return i;
1702
1703     /*
1704      * NULL compares equal.
1705      */
1706     if (!a)
1707         return 0;
1708
1709     /*
1710      * Otherwise, ordinary strcasecmp.
1711      */
1712     return g_strcasecmp(a, b);
1713 }
1714
1715 static int fontinfo_realname_compare(void *av, void *bv)
1716 {
1717     fontinfo *a = (fontinfo *)av;
1718     fontinfo *b = (fontinfo *)bv;
1719     int i;
1720
1721     if ((i = strnullcasecmp(a->realname, b->realname)) != 0)
1722         return i;
1723     if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK))
1724         return ((a->flags & FONTFLAG_SORT_MASK) <
1725                 (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1);
1726     return 0;
1727 }
1728
1729 static int fontinfo_realname_find(void *av, void *bv)
1730 {
1731     struct fontinfo_realname_find *a = (struct fontinfo_realname_find *)av;
1732     fontinfo *b = (fontinfo *)bv;
1733     int i;
1734
1735     if ((i = strnullcasecmp(a->realname, b->realname)) != 0)
1736         return i;
1737     if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK))
1738         return ((a->flags & FONTFLAG_SORT_MASK) <
1739                 (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1);
1740     return 0;
1741 }
1742
1743 static int fontinfo_selorder_compare(void *av, void *bv)
1744 {
1745     fontinfo *a = (fontinfo *)av;
1746     fontinfo *b = (fontinfo *)bv;
1747     int i;
1748     if ((i = strnullcasecmp(a->family, b->family)) != 0)
1749         return i;
1750     /*
1751      * Font class comes immediately after family, so that fonts
1752      * from different classes with the same family
1753      */
1754     if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK))
1755         return ((a->flags & FONTFLAG_SORT_MASK) <
1756                 (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1);
1757     if ((i = strnullcasecmp(a->charset, b->charset)) != 0)
1758         return i;
1759     if ((i = strnullcasecmp(a->stylekey, b->stylekey)) != 0)
1760         return i;
1761     if ((i = strnullcasecmp(a->style, b->style)) != 0)
1762         return i;
1763     if (a->size != b->size)
1764         return (a->size < b->size ? -1 : +1);
1765     if (a->index != b->index)
1766         return (a->index < b->index ? -1 : +1);
1767     return 0;
1768 }
1769
1770 static void unifontsel_deselect(unifontsel_internal *fs)
1771 {
1772     fs->selected = NULL;
1773     gtk_list_store_clear(fs->style_model);
1774     gtk_list_store_clear(fs->size_model);
1775     gtk_widget_set_sensitive(fs->u.ok_button, FALSE);
1776     gtk_widget_set_sensitive(fs->size_entry, FALSE);
1777 }
1778
1779 static void unifontsel_setup_familylist(unifontsel_internal *fs)
1780 {
1781     GtkTreeIter iter;
1782     int i, listindex, minpos = -1, maxpos = -1;
1783     char *currfamily = NULL;
1784     int currflags = -1;
1785     fontinfo *info;
1786
1787     gtk_list_store_clear(fs->family_model);
1788     listindex = 0;
1789
1790     /*
1791      * Search through the font tree for anything matching our
1792      * current filter criteria. When we find one, add its font
1793      * name to the list box.
1794      */
1795     for (i = 0 ;; i++) {
1796         info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1797         /*
1798          * info may be NULL if we've just run off the end of the
1799          * tree. We must still do a processing pass in that
1800          * situation, in case we had an unfinished font record in
1801          * progress.
1802          */
1803         if (info && (info->flags &~ fs->filter_flags)) {
1804             info->familyindex = -1;
1805             continue;                  /* we're filtering out this font */
1806         }
1807         if (!info || strnullcasecmp(currfamily, info->family) ||
1808             currflags != (info->flags & FONTFLAG_SORT_MASK)) {
1809             /*
1810              * We've either finished a family, or started a new
1811              * one, or both.
1812              */
1813             if (currfamily) {
1814                 gtk_list_store_append(fs->family_model, &iter);
1815                 gtk_list_store_set(fs->family_model, &iter,
1816                                    0, currfamily, 1, minpos, 2, maxpos+1, -1);
1817                 listindex++;
1818             }
1819             if (info) {
1820                 minpos = i;
1821                 currfamily = info->family;
1822                 currflags = info->flags & FONTFLAG_SORT_MASK;
1823             }
1824         }
1825         if (!info)
1826             break;                     /* now we're done */
1827         info->familyindex = listindex;
1828         maxpos = i;
1829     }
1830
1831     /*
1832      * If we've just filtered out the previously selected font,
1833      * deselect it thoroughly.
1834      */
1835     if (fs->selected && fs->selected->familyindex < 0)
1836         unifontsel_deselect(fs);
1837 }
1838
1839 static void unifontsel_setup_stylelist(unifontsel_internal *fs,
1840                                        int start, int end)
1841 {
1842     GtkTreeIter iter;
1843     int i, listindex, minpos = -1, maxpos = -1, started = FALSE;
1844     char *currcs = NULL, *currstyle = NULL;
1845     fontinfo *info;
1846
1847     gtk_list_store_clear(fs->style_model);
1848     listindex = 0;
1849     started = FALSE;
1850
1851     /*
1852      * Search through the font tree for anything matching our
1853      * current filter criteria. When we find one, add its charset
1854      * and/or style name to the list box.
1855      */
1856     for (i = start; i <= end; i++) {
1857         if (i == end)
1858             info = NULL;
1859         else
1860             info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1861         /*
1862          * info may be NULL if we've just run off the end of the
1863          * relevant data. We must still do a processing pass in
1864          * that situation, in case we had an unfinished font
1865          * record in progress.
1866          */
1867         if (info && (info->flags &~ fs->filter_flags)) {
1868             info->styleindex = -1;
1869             continue;                  /* we're filtering out this font */
1870         }
1871         if (!info || !started || strnullcasecmp(currcs, info->charset) ||
1872              strnullcasecmp(currstyle, info->style)) {
1873             /*
1874              * We've either finished a style/charset, or started a
1875              * new one, or both.
1876              */
1877             started = TRUE;
1878             if (currstyle) {
1879                 gtk_list_store_append(fs->style_model, &iter);
1880                 gtk_list_store_set(fs->style_model, &iter,
1881                                    0, currstyle, 1, minpos, 2, maxpos+1,
1882                                    3, TRUE, -1);
1883                 listindex++;
1884             }
1885             if (info) {
1886                 minpos = i;
1887                 if (info->charset && strnullcasecmp(currcs, info->charset)) {
1888                     gtk_list_store_append(fs->style_model, &iter);
1889                     gtk_list_store_set(fs->style_model, &iter,
1890                                        0, info->charset, 1, -1, 2, -1,
1891                                        3, FALSE, -1);
1892                     listindex++;
1893                 }
1894                 currcs = info->charset;
1895                 currstyle = info->style;
1896             }
1897         }
1898         if (!info)
1899             break;                     /* now we're done */
1900         info->styleindex = listindex;
1901         maxpos = i;
1902     }
1903 }
1904
1905 static const int unifontsel_default_sizes[] = { 10, 12, 14, 16, 20, 24, 32 };
1906
1907 static void unifontsel_setup_sizelist(unifontsel_internal *fs,
1908                                       int start, int end)
1909 {
1910     GtkTreeIter iter;
1911     int i, listindex;
1912     char sizetext[40];
1913     fontinfo *info;
1914
1915     gtk_list_store_clear(fs->size_model);
1916     listindex = 0;
1917
1918     /*
1919      * Search through the font tree for anything matching our
1920      * current filter criteria. When we find one, add its font
1921      * name to the list box.
1922      */
1923     for (i = start; i < end; i++) {
1924         info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1925         if (info->flags &~ fs->filter_flags) {
1926             info->sizeindex = -1;
1927             continue;                  /* we're filtering out this font */
1928         }
1929         if (info->size) {
1930             sprintf(sizetext, "%d", info->size);
1931             info->sizeindex = listindex;
1932             gtk_list_store_append(fs->size_model, &iter);
1933             gtk_list_store_set(fs->size_model, &iter,
1934                                0, sizetext, 1, i, 2, info->size, -1);
1935             listindex++;
1936         } else {
1937             int j;
1938
1939             assert(i == start);
1940             assert(i+1 == end);
1941
1942             for (j = 0; j < lenof(unifontsel_default_sizes); j++) {
1943                 sprintf(sizetext, "%d", unifontsel_default_sizes[j]);
1944                 gtk_list_store_append(fs->size_model, &iter);
1945                 gtk_list_store_set(fs->size_model, &iter, 0, sizetext, 1, i,
1946                                    2, unifontsel_default_sizes[j], -1);
1947                 listindex++;
1948             }
1949         }
1950     }
1951 }
1952
1953 static void unifontsel_set_filter_buttons(unifontsel_internal *fs)
1954 {
1955     int i;
1956
1957     for (i = 0; i < lenof(fs->filter_buttons); i++) {
1958         int flagbit = GPOINTER_TO_INT(gtk_object_get_data
1959                                       (GTK_OBJECT(fs->filter_buttons[i]),
1960                                        "user-data"));
1961         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fs->filter_buttons[i]),
1962                                      !!(fs->filter_flags & flagbit));
1963     }
1964 }
1965
1966 static void unifontsel_draw_preview_text(unifontsel_internal *fs)
1967 {
1968     unifont *font;
1969     char *sizename = NULL;
1970     fontinfo *info = fs->selected;
1971
1972     if (info) {
1973         sizename = info->fontclass->scale_fontname
1974             (GTK_WIDGET(fs->u.window), info->realname, fs->selsize);
1975         font = info->fontclass->create(GTK_WIDGET(fs->u.window),
1976                                        sizename ? sizename : info->realname,
1977                                        FALSE, FALSE, 0, 0);
1978     } else
1979         font = NULL;
1980
1981     if (fs->preview_pixmap) {
1982         GdkGC *gc = gdk_gc_new(fs->preview_pixmap);
1983         gdk_gc_set_foreground(gc, &fs->preview_bg);
1984         gdk_draw_rectangle(fs->preview_pixmap, gc, 1, 0, 0,
1985                            fs->preview_width, fs->preview_height);
1986         gdk_gc_set_foreground(gc, &fs->preview_fg);
1987         if (font) {
1988             /*
1989              * The pangram used here is rather carefully
1990              * constructed: it contains a sequence of very narrow
1991              * letters (`jil') and a pair of adjacent very wide
1992              * letters (`wm').
1993              *
1994              * If the user selects a proportional font, it will be
1995              * coerced into fixed-width character cells when used
1996              * in the actual terminal window. We therefore display
1997              * it the same way in the preview pane, so as to show
1998              * it the way it will actually be displayed - and we
1999              * deliberately pick a pangram which will show the
2000              * resulting miskerning at its worst.
2001              *
2002              * We aren't trying to sell people these fonts; we're
2003              * trying to let them make an informed choice. Better
2004              * that they find out the problems with using
2005              * proportional fonts in terminal windows here than
2006              * that they go to the effort of selecting their font
2007              * and _then_ realise it was a mistake.
2008              */
2009             info->fontclass->draw_text(fs->preview_pixmap, gc, font,
2010                                        0, font->ascent,
2011                                        L"bankrupt jilted showmen quiz convex fogey",
2012                                        41, FALSE, FALSE, font->width);
2013             info->fontclass->draw_text(fs->preview_pixmap, gc, font,
2014                                        0, font->ascent + font->height,
2015                                        L"BANKRUPT JILTED SHOWMEN QUIZ CONVEX FOGEY",
2016                                        41, FALSE, FALSE, font->width);
2017             /*
2018              * The ordering of punctuation here is also selected
2019              * with some specific aims in mind. I put ` and '
2020              * together because some software (and people) still
2021              * use them as matched quotes no matter what Unicode
2022              * might say on the matter, so people can quickly
2023              * check whether they look silly in a candidate font.
2024              * The sequence #_@ is there to let people judge the
2025              * suitability of the underscore as an effectively
2026              * alphabetic character (since that's how it's often
2027              * used in practice, at least by programmers).
2028              */
2029             info->fontclass->draw_text(fs->preview_pixmap, gc, font,
2030                                        0, font->ascent + font->height * 2,
2031                                        L"0123456789!?,.:;<>()[]{}\\/`'\"+*-=~#_@|%&^$",
2032                                        42, FALSE, FALSE, font->width);
2033         }
2034         gdk_gc_unref(gc);
2035         gdk_window_invalidate_rect(fs->preview_area->window, NULL, FALSE);
2036     }
2037     if (font)
2038         info->fontclass->destroy(font);
2039
2040     sfree(sizename);
2041 }
2042
2043 static void unifontsel_select_font(unifontsel_internal *fs,
2044                                    fontinfo *info, int size, int leftlist,
2045                                    int size_is_explicit)
2046 {
2047     int index;
2048     int minval, maxval;
2049     GtkTreePath *treepath;
2050     GtkTreeIter iter;
2051
2052     fs->inhibit_response = TRUE;
2053
2054     fs->selected = info;
2055     fs->selsize = size;
2056     if (size_is_explicit)
2057         fs->intendedsize = size;
2058
2059     gtk_widget_set_sensitive(fs->u.ok_button, TRUE);
2060
2061     /*
2062      * Find the index of this fontinfo in the selorder list. 
2063      */
2064     index = -1;
2065     findpos234(fs->fonts_by_selorder, info, NULL, &index);
2066     assert(index >= 0);
2067
2068     /*
2069      * Adjust the font selector flags and redo the font family
2070      * list box, if necessary.
2071      */
2072     if (leftlist <= 0 &&
2073         (fs->filter_flags | info->flags) != fs->filter_flags) {
2074         fs->filter_flags |= info->flags;
2075         unifontsel_set_filter_buttons(fs);
2076         unifontsel_setup_familylist(fs);
2077     }
2078
2079     /*
2080      * Find the appropriate family name and select it in the list.
2081      */
2082     assert(info->familyindex >= 0);
2083     treepath = gtk_tree_path_new_from_indices(info->familyindex, -1);
2084     gtk_tree_selection_select_path
2085         (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->family_list)),
2086          treepath);
2087     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->family_list),
2088                                  treepath, NULL, FALSE, 0.0, 0.0);
2089     gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, treepath);
2090     gtk_tree_path_free(treepath);
2091
2092     /*
2093      * Now set up the font style list.
2094      */
2095     gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter,
2096                        1, &minval, 2, &maxval, -1);
2097     if (leftlist <= 1)
2098         unifontsel_setup_stylelist(fs, minval, maxval);
2099
2100     /*
2101      * Find the appropriate style name and select it in the list.
2102      */
2103     if (info->style) {
2104         assert(info->styleindex >= 0);
2105         treepath = gtk_tree_path_new_from_indices(info->styleindex, -1);
2106         gtk_tree_selection_select_path
2107             (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->style_list)),
2108              treepath);
2109         gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->style_list),
2110                                      treepath, NULL, FALSE, 0.0, 0.0);
2111         gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->style_model),
2112                                 &iter, treepath);
2113         gtk_tree_path_free(treepath);
2114
2115         /*
2116          * And set up the size list.
2117          */
2118         gtk_tree_model_get(GTK_TREE_MODEL(fs->style_model), &iter,
2119                            1, &minval, 2, &maxval, -1);
2120         if (leftlist <= 2)
2121             unifontsel_setup_sizelist(fs, minval, maxval);
2122
2123         /*
2124          * Find the appropriate size, and select it in the list.
2125          */
2126         if (info->size) {
2127             assert(info->sizeindex >= 0);
2128             treepath = gtk_tree_path_new_from_indices(info->sizeindex, -1);
2129             gtk_tree_selection_select_path
2130                 (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->size_list)),
2131                  treepath);
2132             gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
2133                                          treepath, NULL, FALSE, 0.0, 0.0);
2134             gtk_tree_path_free(treepath);
2135             size = info->size;
2136         } else {
2137             int j;
2138             for (j = 0; j < lenof(unifontsel_default_sizes); j++)
2139                 if (unifontsel_default_sizes[j] == size) {
2140                     treepath = gtk_tree_path_new_from_indices(j, -1);
2141                     gtk_tree_view_set_cursor(GTK_TREE_VIEW(fs->size_list),
2142                                              treepath, NULL, FALSE);
2143                     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
2144                                                  treepath, NULL, FALSE, 0.0,
2145                                                  0.0);
2146                     gtk_tree_path_free(treepath);
2147                 }
2148         }
2149
2150         /*
2151          * And set up the font size text entry box.
2152          */
2153         {
2154             char sizetext[40];
2155             sprintf(sizetext, "%d", size);
2156             gtk_entry_set_text(GTK_ENTRY(fs->size_entry), sizetext);
2157         }
2158     } else {
2159         if (leftlist <= 2)
2160             unifontsel_setup_sizelist(fs, 0, 0);
2161         gtk_entry_set_text(GTK_ENTRY(fs->size_entry), "");
2162     }
2163
2164     /*
2165      * Grey out the font size edit box if we're not using a
2166      * scalable font.
2167      */
2168     gtk_entry_set_editable(GTK_ENTRY(fs->size_entry), fs->selected->size == 0);
2169     gtk_widget_set_sensitive(fs->size_entry, fs->selected->size == 0);
2170
2171     unifontsel_draw_preview_text(fs);
2172
2173     fs->inhibit_response = FALSE;
2174 }
2175
2176 static void unifontsel_button_toggled(GtkToggleButton *tb, gpointer data)
2177 {
2178     unifontsel_internal *fs = (unifontsel_internal *)data;
2179     int newstate = gtk_toggle_button_get_active(tb);
2180     int newflags;
2181     int flagbit = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(tb),
2182                                                       "user-data"));
2183
2184     if (newstate)
2185         newflags = fs->filter_flags | flagbit;
2186     else
2187         newflags = fs->filter_flags & ~flagbit;
2188
2189     if (fs->filter_flags != newflags) {
2190         fs->filter_flags = newflags;
2191         unifontsel_setup_familylist(fs);
2192     }
2193 }
2194
2195 static void unifontsel_add_entry(void *ctx, const char *realfontname,
2196                                  const char *family, const char *charset,
2197                                  const char *style, const char *stylekey,
2198                                  int size, int flags,
2199                                  const struct unifont_vtable *fontclass)
2200 {
2201     unifontsel_internal *fs = (unifontsel_internal *)ctx;
2202     fontinfo *info;
2203     int totalsize;
2204     char *p;
2205
2206     totalsize = sizeof(fontinfo) + strlen(realfontname) +
2207         (family ? strlen(family) : 0) + (charset ? strlen(charset) : 0) +
2208         (style ? strlen(style) : 0) + (stylekey ? strlen(stylekey) : 0) + 10;
2209     info = (fontinfo *)smalloc(totalsize);
2210     info->fontclass = fontclass;
2211     p = (char *)info + sizeof(fontinfo);
2212     info->realname = p;
2213     strcpy(p, realfontname);
2214     p += 1+strlen(p);
2215     if (family) {
2216         info->family = p;
2217         strcpy(p, family);
2218         p += 1+strlen(p);
2219     } else
2220         info->family = NULL;
2221     if (charset) {
2222         info->charset = p;
2223         strcpy(p, charset);
2224         p += 1+strlen(p);
2225     } else
2226         info->charset = NULL;
2227     if (style) {
2228         info->style = p;
2229         strcpy(p, style);
2230         p += 1+strlen(p);
2231     } else
2232         info->style = NULL;
2233     if (stylekey) {
2234         info->stylekey = p;
2235         strcpy(p, stylekey);
2236         p += 1+strlen(p);
2237     } else
2238         info->stylekey = NULL;
2239     assert(p - (char *)info <= totalsize);
2240     info->size = size;
2241     info->flags = flags;
2242     info->index = count234(fs->fonts_by_selorder);
2243
2244     /*
2245      * It's just conceivable that a misbehaving font enumerator
2246      * might tell us about the same font real name more than once,
2247      * in which case we should silently drop the new one.
2248      */
2249     if (add234(fs->fonts_by_realname, info) != info) {
2250         sfree(info);
2251         return;
2252     }
2253     /*
2254      * However, we should never get a duplicate key in the
2255      * selorder tree, because the index field carefully
2256      * disambiguates otherwise identical records.
2257      */
2258     add234(fs->fonts_by_selorder, info);
2259 }
2260
2261 static fontinfo *update_for_intended_size(unifontsel_internal *fs,
2262                                           fontinfo *info)
2263 {
2264     fontinfo info2, *below, *above;
2265     int pos;
2266
2267     /*
2268      * Copy the info structure. This doesn't copy its dynamic
2269      * string fields, but that's unimportant because all we're
2270      * going to do is to adjust the size field and use it in one
2271      * tree search.
2272      */
2273     info2 = *info;
2274     info2.size = fs->intendedsize;
2275
2276     /*
2277      * Search in the tree to find the fontinfo structure which
2278      * best approximates the size the user last requested.
2279      */
2280     below = findrelpos234(fs->fonts_by_selorder, &info2, NULL,
2281                           REL234_LE, &pos);
2282     above = index234(fs->fonts_by_selorder, pos+1);
2283
2284     /*
2285      * See if we've found it exactly, which is an easy special
2286      * case. If we have, it'll be in `below' and not `above',
2287      * because we did a REL234_LE rather than REL234_LT search.
2288      */
2289     if (!fontinfo_selorder_compare(&info2, below))
2290         return below;
2291
2292     /*
2293      * Now we've either found two suitable fonts, one smaller and
2294      * one larger, or we're at one or other extreme end of the
2295      * scale. Find out which, by NULLing out either of below and
2296      * above if it differs from this one in any respect but size
2297      * (and the disambiguating index field). Bear in mind, also,
2298      * that either one might _already_ be NULL if we're at the
2299      * extreme ends of the font list.
2300      */
2301     if (below) {
2302         info2.size = below->size;
2303         info2.index = below->index;
2304         if (fontinfo_selorder_compare(&info2, below))
2305             below = NULL;
2306     }
2307     if (above) {
2308         info2.size = above->size;
2309         info2.index = above->index;
2310         if (fontinfo_selorder_compare(&info2, above))
2311             above = NULL;
2312     }
2313
2314     /*
2315      * Now return whichever of above and below is non-NULL, if
2316      * that's unambiguous.
2317      */
2318     if (!above)
2319         return below;
2320     if (!below)
2321         return above;
2322
2323     /*
2324      * And now we really do have to make a choice about whether to
2325      * round up or down. We'll do it by rounding to nearest,
2326      * breaking ties by rounding up.
2327      */
2328     if (above->size - fs->intendedsize <= fs->intendedsize - below->size)
2329         return above;
2330     else
2331         return below;
2332 }
2333
2334 static void family_changed(GtkTreeSelection *treeselection, gpointer data)
2335 {
2336     unifontsel_internal *fs = (unifontsel_internal *)data;
2337     GtkTreeModel *treemodel;
2338     GtkTreeIter treeiter;
2339     int minval;
2340     fontinfo *info;
2341
2342     if (fs->inhibit_response)          /* we made this change ourselves */
2343         return;
2344
2345     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
2346         return;
2347
2348     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
2349     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
2350     info = update_for_intended_size(fs, info);
2351     if (!info)
2352         return; /* _shouldn't_ happen unless font list is completely funted */
2353     if (!info->size)
2354         fs->selsize = fs->intendedsize;   /* font is scalable */
2355     unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize,
2356                            1, FALSE);
2357 }
2358
2359 static void style_changed(GtkTreeSelection *treeselection, gpointer data)
2360 {
2361     unifontsel_internal *fs = (unifontsel_internal *)data;
2362     GtkTreeModel *treemodel;
2363     GtkTreeIter treeiter;
2364     int minval;
2365     fontinfo *info;
2366
2367     if (fs->inhibit_response)          /* we made this change ourselves */
2368         return;
2369
2370     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
2371         return;
2372
2373     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
2374     if (minval < 0)
2375         return;                    /* somehow a charset heading got clicked */
2376     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
2377     info = update_for_intended_size(fs, info);
2378     if (!info)
2379         return; /* _shouldn't_ happen unless font list is completely funted */
2380     if (!info->size)
2381         fs->selsize = fs->intendedsize;   /* font is scalable */
2382     unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize,
2383                            2, FALSE);
2384 }
2385
2386 static void size_changed(GtkTreeSelection *treeselection, gpointer data)
2387 {
2388     unifontsel_internal *fs = (unifontsel_internal *)data;
2389     GtkTreeModel *treemodel;
2390     GtkTreeIter treeiter;
2391     int minval, size;
2392     fontinfo *info;
2393
2394     if (fs->inhibit_response)          /* we made this change ourselves */
2395         return;
2396
2397     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
2398         return;
2399
2400     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, 2, &size, -1);
2401     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
2402     unifontsel_select_font(fs, info, info->size ? info->size : size, 3, TRUE);
2403 }
2404
2405 static void size_entry_changed(GtkEditable *ed, gpointer data)
2406 {
2407     unifontsel_internal *fs = (unifontsel_internal *)data;
2408     const char *text;
2409     int size;
2410
2411     if (fs->inhibit_response)          /* we made this change ourselves */
2412         return;
2413
2414     text = gtk_entry_get_text(GTK_ENTRY(ed));
2415     size = atoi(text);
2416
2417     if (size > 0) {
2418         assert(fs->selected->size == 0);
2419         unifontsel_select_font(fs, fs->selected, size, 3, TRUE);
2420     }
2421 }
2422
2423 static void alias_resolve(GtkTreeView *treeview, GtkTreePath *path,
2424                           GtkTreeViewColumn *column, gpointer data)
2425 {
2426     unifontsel_internal *fs = (unifontsel_internal *)data;
2427     GtkTreeIter iter;
2428     int minval, newsize;
2429     fontinfo *info, *newinfo;
2430     char *newname;
2431
2432     if (fs->inhibit_response)          /* we made this change ourselves */
2433         return;
2434
2435     gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, path);
2436     gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter, 1,&minval, -1);
2437     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
2438     if (info) {
2439         int flags;
2440         struct fontinfo_realname_find f;
2441
2442         newname = info->fontclass->canonify_fontname
2443             (GTK_WIDGET(fs->u.window), info->realname, &newsize, &flags, TRUE);
2444
2445         f.realname = newname;
2446         f.flags = flags;
2447         newinfo = find234(fs->fonts_by_realname, &f, fontinfo_realname_find);
2448
2449         sfree(newname);
2450         if (!newinfo)
2451             return;                    /* font name not in our index */
2452         if (newinfo == info)
2453             return;   /* didn't change under canonification => not an alias */
2454         unifontsel_select_font(fs, newinfo,
2455                                newinfo->size ? newinfo->size : newsize,
2456                                1, TRUE);
2457     }
2458 }
2459
2460 static gint unifontsel_expose_area(GtkWidget *widget, GdkEventExpose *event,
2461                                    gpointer data)
2462 {
2463     unifontsel_internal *fs = (unifontsel_internal *)data;
2464
2465     if (fs->preview_pixmap) {
2466         gdk_draw_pixmap(widget->window,
2467                         widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
2468                         fs->preview_pixmap,
2469                         event->area.x, event->area.y,
2470                         event->area.x, event->area.y,
2471                         event->area.width, event->area.height);
2472     }
2473     return TRUE;
2474 }
2475
2476 static gint unifontsel_configure_area(GtkWidget *widget,
2477                                       GdkEventConfigure *event, gpointer data)
2478 {
2479     unifontsel_internal *fs = (unifontsel_internal *)data;
2480     int ox, oy, nx, ny, x, y;
2481
2482     /*
2483      * Enlarge the pixmap, but never shrink it.
2484      */
2485     ox = fs->preview_width;
2486     oy = fs->preview_height;
2487     x = event->width;
2488     y = event->height;
2489     if (x > ox || y > oy) {
2490         if (fs->preview_pixmap)
2491             gdk_pixmap_unref(fs->preview_pixmap);
2492         
2493         nx = (x > ox ? x : ox);
2494         ny = (y > oy ? y : oy);
2495         fs->preview_pixmap = gdk_pixmap_new(widget->window, nx, ny, -1);
2496         fs->preview_width = nx;
2497         fs->preview_height = ny;
2498
2499         unifontsel_draw_preview_text(fs);
2500     }
2501
2502     gdk_window_invalidate_rect(widget->window, NULL, FALSE);
2503
2504     return TRUE;
2505 }
2506
2507 unifontsel *unifontsel_new(const char *wintitle)
2508 {
2509     unifontsel_internal *fs = snew(unifontsel_internal);
2510     GtkWidget *table, *label, *w, *ww, *scroll;
2511     GtkListStore *model;
2512     GtkTreeViewColumn *column;
2513     int lists_height, preview_height, font_width, style_width, size_width;
2514     int i;
2515
2516     fs->inhibit_response = FALSE;
2517     fs->selected = NULL;
2518
2519     {
2520         /*
2521          * Invent some magic size constants.
2522          */
2523         GtkRequisition req;
2524         label = gtk_label_new("Quite Long Font Name (Foundry)");
2525         gtk_widget_size_request(label, &req);
2526         font_width = req.width;
2527         lists_height = 14 * req.height;
2528         preview_height = 5 * req.height;
2529         gtk_label_set_text(GTK_LABEL(label), "Italic Extra Condensed");
2530         gtk_widget_size_request(label, &req);
2531         style_width = req.width;
2532         gtk_label_set_text(GTK_LABEL(label), "48000");
2533         gtk_widget_size_request(label, &req);
2534         size_width = req.width;
2535 #if GTK_CHECK_VERSION(2,10,0)
2536         g_object_ref_sink(label);
2537         g_object_unref(label);
2538 #else
2539         gtk_object_sink(GTK_OBJECT(label));
2540 #endif
2541     }
2542
2543     /*
2544      * Create the dialog box and initialise the user-visible
2545      * fields in the returned structure.
2546      */
2547     fs->u.user_data = NULL;
2548     fs->u.window = GTK_WINDOW(gtk_dialog_new());
2549     gtk_window_set_title(fs->u.window, wintitle);
2550     fs->u.cancel_button = gtk_dialog_add_button
2551         (GTK_DIALOG(fs->u.window), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
2552     fs->u.ok_button = gtk_dialog_add_button
2553         (GTK_DIALOG(fs->u.window), GTK_STOCK_OK, GTK_RESPONSE_OK);
2554     gtk_widget_grab_default(fs->u.ok_button);
2555
2556     /*
2557      * Now set up the internal fields, including in particular all
2558      * the controls that actually allow the user to select fonts.
2559      */
2560     table = gtk_table_new(8, 3, FALSE);
2561     gtk_widget_show(table);
2562     gtk_table_set_col_spacings(GTK_TABLE(table), 8);
2563 #if GTK_CHECK_VERSION(2,4,0)
2564     /* GtkAlignment seems to be the simplest way to put padding round things */
2565     w = gtk_alignment_new(0, 0, 1, 1);
2566     gtk_alignment_set_padding(GTK_ALIGNMENT(w), 8, 8, 8, 8);
2567     gtk_container_add(GTK_CONTAINER(w), table);
2568     gtk_widget_show(w);
2569 #else
2570     w = table;
2571 #endif
2572     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(fs->u.window)->vbox),
2573                        w, TRUE, TRUE, 0);
2574
2575     label = gtk_label_new_with_mnemonic("_Font:");
2576     gtk_widget_show(label);
2577     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2578     gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_FILL, 0, 0, 0);
2579
2580     /*
2581      * The Font list box displays only a string, but additionally
2582      * stores two integers which give the limits within the
2583      * tree234 of the font entries covered by this list entry.
2584      */
2585     model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
2586     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2587     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2588     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2589     gtk_widget_show(w);
2590     column = gtk_tree_view_column_new_with_attributes
2591         ("Font", gtk_cell_renderer_text_new(),
2592          "text", 0, (char *)NULL);
2593     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2594     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2595     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2596                      "changed", G_CALLBACK(family_changed), fs);
2597     g_signal_connect(G_OBJECT(w), "row-activated",
2598                      G_CALLBACK(alias_resolve), fs);
2599
2600     scroll = gtk_scrolled_window_new(NULL, NULL);
2601     gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
2602                                         GTK_SHADOW_IN);
2603     gtk_container_add(GTK_CONTAINER(scroll), w);
2604     gtk_widget_show(scroll);
2605     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2606                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2607     gtk_widget_set_size_request(scroll, font_width, lists_height);
2608     gtk_table_attach(GTK_TABLE(table), scroll, 0, 1, 1, 3, GTK_FILL,
2609                      GTK_EXPAND | GTK_FILL, 0, 0);
2610     fs->family_model = model;
2611     fs->family_list = w;
2612
2613     label = gtk_label_new_with_mnemonic("_Style:");
2614     gtk_widget_show(label);
2615     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2616     gtk_table_attach(GTK_TABLE(table), label, 1, 2, 0, 1, GTK_FILL, 0, 0, 0);
2617
2618     /*
2619      * The Style list box can contain insensitive elements
2620      * (character set headings for server-side fonts), so we add
2621      * an extra column to the list store to hold that information.
2622      */
2623     model = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT,
2624                                G_TYPE_BOOLEAN);
2625     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2626     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2627     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2628     gtk_widget_show(w);
2629     column = gtk_tree_view_column_new_with_attributes
2630         ("Style", gtk_cell_renderer_text_new(),
2631          "text", 0, "sensitive", 3, (char *)NULL);
2632     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2633     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2634     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2635                      "changed", G_CALLBACK(style_changed), fs);
2636
2637     scroll = gtk_scrolled_window_new(NULL, NULL);
2638     gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
2639                                         GTK_SHADOW_IN);
2640     gtk_container_add(GTK_CONTAINER(scroll), w);
2641     gtk_widget_show(scroll);
2642     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2643                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2644     gtk_widget_set_size_request(scroll, style_width, lists_height);
2645     gtk_table_attach(GTK_TABLE(table), scroll, 1, 2, 1, 3, GTK_FILL,
2646                      GTK_EXPAND | GTK_FILL, 0, 0);
2647     fs->style_model = model;
2648     fs->style_list = w;
2649
2650     label = gtk_label_new_with_mnemonic("Si_ze:");
2651     gtk_widget_show(label);
2652     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2653     gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, GTK_FILL, 0, 0, 0);
2654
2655     /*
2656      * The Size label attaches primarily to a text input box so
2657      * that the user can select a size of their choice. The list
2658      * of available sizes is secondary.
2659      */
2660     fs->size_entry = w = gtk_entry_new();
2661     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2662     gtk_widget_set_size_request(w, size_width, -1);
2663     gtk_widget_show(w);
2664     gtk_table_attach(GTK_TABLE(table), w, 2, 3, 1, 2, GTK_FILL, 0, 0, 0);
2665     g_signal_connect(G_OBJECT(w), "changed", G_CALLBACK(size_entry_changed),
2666                      fs);
2667
2668     model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
2669     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2670     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2671     gtk_widget_show(w);
2672     column = gtk_tree_view_column_new_with_attributes
2673         ("Size", gtk_cell_renderer_text_new(),
2674          "text", 0, (char *)NULL);
2675     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2676     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2677     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2678                      "changed", G_CALLBACK(size_changed), fs);
2679
2680     scroll = gtk_scrolled_window_new(NULL, NULL);
2681     gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
2682                                         GTK_SHADOW_IN);
2683     gtk_container_add(GTK_CONTAINER(scroll), w);
2684     gtk_widget_show(scroll);
2685     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2686                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2687     gtk_table_attach(GTK_TABLE(table), scroll, 2, 3, 2, 3, GTK_FILL,
2688                      GTK_EXPAND | GTK_FILL, 0, 0);
2689     fs->size_model = model;
2690     fs->size_list = w;
2691
2692     /*
2693      * Preview widget.
2694      */
2695     fs->preview_area = gtk_drawing_area_new();
2696     fs->preview_pixmap = NULL;
2697     fs->preview_width = 0;
2698     fs->preview_height = 0;
2699     fs->preview_fg.pixel = fs->preview_bg.pixel = 0;
2700     fs->preview_fg.red = fs->preview_fg.green = fs->preview_fg.blue = 0x0000;
2701     fs->preview_bg.red = fs->preview_bg.green = fs->preview_bg.blue = 0xFFFF;
2702     gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_fg,
2703                              FALSE, FALSE);
2704     gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_bg,
2705                              FALSE, FALSE);
2706     gtk_signal_connect(GTK_OBJECT(fs->preview_area), "expose_event",
2707                        GTK_SIGNAL_FUNC(unifontsel_expose_area), fs);
2708     gtk_signal_connect(GTK_OBJECT(fs->preview_area), "configure_event",
2709                        GTK_SIGNAL_FUNC(unifontsel_configure_area), fs);
2710     gtk_widget_set_size_request(fs->preview_area, 1, preview_height);
2711     gtk_widget_show(fs->preview_area);
2712     ww = fs->preview_area;
2713     w = gtk_frame_new(NULL);
2714     gtk_container_add(GTK_CONTAINER(w), ww);
2715     gtk_widget_show(w);
2716 #if GTK_CHECK_VERSION(2,4,0)
2717     ww = w;
2718     /* GtkAlignment seems to be the simplest way to put padding round things */
2719     w = gtk_alignment_new(0, 0, 1, 1);
2720     gtk_alignment_set_padding(GTK_ALIGNMENT(w), 8, 8, 8, 8);
2721     gtk_container_add(GTK_CONTAINER(w), ww);
2722     gtk_widget_show(w);
2723 #endif
2724     ww = w;
2725     w = gtk_frame_new("Preview of font");
2726     gtk_container_add(GTK_CONTAINER(w), ww);
2727     gtk_widget_show(w);
2728     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 3, 4,
2729                      GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 8);
2730
2731     i = 0;
2732     w = gtk_check_button_new_with_label("Show client-side fonts");
2733     gtk_object_set_data(GTK_OBJECT(w), "user-data",
2734                         GINT_TO_POINTER(FONTFLAG_CLIENTSIDE));
2735     gtk_signal_connect(GTK_OBJECT(w), "toggled",
2736                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2737     gtk_widget_show(w);
2738     fs->filter_buttons[i++] = w;
2739     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 4, 5, GTK_FILL, 0, 0, 0);
2740     w = gtk_check_button_new_with_label("Show server-side fonts");
2741     gtk_object_set_data(GTK_OBJECT(w), "user-data",
2742                         GINT_TO_POINTER(FONTFLAG_SERVERSIDE));
2743     gtk_signal_connect(GTK_OBJECT(w), "toggled",
2744                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2745     gtk_widget_show(w);
2746     fs->filter_buttons[i++] = w;
2747     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 5, 6, GTK_FILL, 0, 0, 0);
2748     w = gtk_check_button_new_with_label("Show server-side font aliases");
2749     gtk_object_set_data(GTK_OBJECT(w), "user-data",
2750                         GINT_TO_POINTER(FONTFLAG_SERVERALIAS));
2751     gtk_signal_connect(GTK_OBJECT(w), "toggled",
2752                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2753     gtk_widget_show(w);
2754     fs->filter_buttons[i++] = w;
2755     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 6, 7, GTK_FILL, 0, 0, 0);
2756     w = gtk_check_button_new_with_label("Show non-monospaced fonts");
2757     gtk_object_set_data(GTK_OBJECT(w), "user-data",
2758                         GINT_TO_POINTER(FONTFLAG_NONMONOSPACED));
2759     gtk_signal_connect(GTK_OBJECT(w), "toggled",
2760                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2761     gtk_widget_show(w);
2762     fs->filter_buttons[i++] = w;
2763     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 7, 8, GTK_FILL, 0, 0, 0);
2764
2765     assert(i == lenof(fs->filter_buttons));
2766     fs->filter_flags = FONTFLAG_CLIENTSIDE | FONTFLAG_SERVERSIDE |
2767         FONTFLAG_SERVERALIAS;
2768     unifontsel_set_filter_buttons(fs);
2769
2770     /*
2771      * Go and find all the font names, and set up our master font
2772      * list.
2773      */
2774     fs->fonts_by_realname = newtree234(fontinfo_realname_compare);
2775     fs->fonts_by_selorder = newtree234(fontinfo_selorder_compare);
2776     for (i = 0; i < lenof(unifont_types); i++)
2777         unifont_types[i]->enum_fonts(GTK_WIDGET(fs->u.window),
2778                                      unifontsel_add_entry, fs);
2779
2780     /*
2781      * And set up the initial font names list.
2782      */
2783     unifontsel_setup_familylist(fs);
2784
2785     fs->selsize = fs->intendedsize = 13;   /* random default */
2786     gtk_widget_set_sensitive(fs->u.ok_button, FALSE);
2787
2788     return (unifontsel *)fs;
2789 }
2790
2791 void unifontsel_destroy(unifontsel *fontsel)
2792 {
2793     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2794     fontinfo *info;
2795
2796     if (fs->preview_pixmap)
2797         gdk_pixmap_unref(fs->preview_pixmap);
2798
2799     freetree234(fs->fonts_by_selorder);
2800     while ((info = delpos234(fs->fonts_by_realname, 0)) != NULL)
2801         sfree(info);
2802     freetree234(fs->fonts_by_realname);
2803
2804     gtk_widget_destroy(GTK_WIDGET(fs->u.window));
2805     sfree(fs);
2806 }
2807
2808 void unifontsel_set_name(unifontsel *fontsel, const char *fontname)
2809 {
2810     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2811     int i, start, end, size, flags;
2812     const char *fontname2 = NULL;
2813     fontinfo *info;
2814
2815     /*
2816      * Provide a default if given an empty or null font name.
2817      */
2818     if (!fontname || !*fontname)
2819         fontname = "server:fixed";
2820
2821     /*
2822      * Call the canonify_fontname function.
2823      */
2824     fontname = unifont_do_prefix(fontname, &start, &end);
2825     for (i = start; i < end; i++) {
2826         fontname2 = unifont_types[i]->canonify_fontname
2827             (GTK_WIDGET(fs->u.window), fontname, &size, &flags, FALSE);
2828         if (fontname2)
2829             break;
2830     }
2831     if (i == end)
2832         return;                        /* font name not recognised */
2833
2834     /*
2835      * Now look up the canonified font name in our index.
2836      */
2837     {
2838         struct fontinfo_realname_find f;
2839         f.realname = fontname2;
2840         f.flags = flags;
2841         info = find234(fs->fonts_by_realname, &f, fontinfo_realname_find);
2842     }
2843
2844     /*
2845      * If we've found the font, and its size field is either
2846      * correct or zero (the latter indicating a scalable font),
2847      * then we're done. Otherwise, try looking up the original
2848      * font name instead.
2849      */
2850     if (!info || (info->size != size && info->size != 0)) {
2851         struct fontinfo_realname_find f;
2852         f.realname = fontname;
2853         f.flags = flags;
2854
2855         info = find234(fs->fonts_by_realname, &f, fontinfo_realname_find);
2856         if (!info || info->size != size)
2857             return;                    /* font name not in our index */
2858     }
2859
2860     /*
2861      * Now we've got a fontinfo structure and a font size, so we
2862      * know everything we need to fill in all the fields in the
2863      * dialog.
2864      */
2865     unifontsel_select_font(fs, info, size, 0, TRUE);
2866 }
2867
2868 char *unifontsel_get_name(unifontsel *fontsel)
2869 {
2870     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2871     char *name;
2872
2873     if (!fs->selected)
2874         return NULL;
2875
2876     if (fs->selected->size == 0) {
2877         name = fs->selected->fontclass->scale_fontname
2878             (GTK_WIDGET(fs->u.window), fs->selected->realname, fs->selsize);
2879         if (name) {
2880             char *ret = dupcat(fs->selected->fontclass->prefix, ":",
2881                                name, NULL);
2882             sfree(name);
2883             return ret;
2884         }
2885     }
2886
2887     return dupcat(fs->selected->fontclass->prefix, ":",
2888                   fs->selected->realname, NULL);
2889 }
2890
2891 #endif /* GTK_CHECK_VERSION(2,0,0) */