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