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