]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkfont.c
Tune the sorting of the style list box for X fonts.
[PuTTY.git] / unix / gtkfont.c
1 /*
2  * Unified font management for GTK.
3  * 
4  * PuTTY is willing to use both old-style X server-side bitmap
5  * fonts _and_ GTK2/Pango client-side fonts. This requires us to
6  * do a bit of work to wrap the two wildly different APIs into
7  * forms the rest of the code can switch between seamlessly, and
8  * also requires a custom font selector capable of handling both
9  * types of font.
10  */
11
12 #include <assert.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <gtk/gtk.h>
16 #include <gdk/gdkkeysyms.h>
17 #include <gdk/gdkx.h>
18 #include <X11/Xlib.h>
19 #include <X11/Xutil.h>
20 #include <X11/Xatom.h>
21
22 #include "putty.h"
23 #include "gtkfont.h"
24 #include "tree234.h"
25
26 /*
27  * TODO on fontsel
28  * ---------------
29  * 
30  *  - implement the preview pane
31  * 
32  *  - extend the font style language for X11 fonts so that we
33  *    never get unexplained double size elements? Or, at least, so
34  *    that _my_ font collection never produces them; that'd be a
35  *    decent start.
36  * 
37  *  - decide what _should_ happen about font aliases. Should we
38  *    resolve them as soon as they're clicked? Or be able to
39  *    resolve them on demand, er, somehow? Or resolve them on exit
40  *    from the function? Or what? If we resolve on demand, should
41  *    we stop canonifying them on input, on the basis that we'd
42  *    prefer to let the user _tell_ us when to canonify them?
43  * 
44  *  - think about points versus pixels, harder than I already have
45  * 
46  *  - work out why the list boxes don't go all the way to the RHS
47  *    of the dialog box
48  * 
49  *  - big testing and shakedown!
50  */
51
52 /*
53  * Future work:
54  * 
55  *  - all the GDK font functions used in the x11font subclass are
56  *    deprecated, so one day they may go away. When this happens -
57  *    or before, if I'm feeling proactive - it oughtn't to be too
58  *    difficult in principle to convert the whole thing to use
59  *    actual Xlib font calls.
60  * 
61  *  - it would be nice if we could move the processing of
62  *    underline and VT100 double width into this module, so that
63  *    instead of using the ghastly pixmap-stretching technique
64  *    everywhere we could tell the Pango backend to scale its
65  *    fonts to double size properly and at full resolution.
66  *    However, this requires me to learn how to make Pango stretch
67  *    text to an arbitrary aspect ratio (for double-width only
68  *    text, which perversely is harder than DW+DH), and right now
69  *    I haven't the energy.
70  */
71
72 /*
73  * Ad-hoc vtable mechanism to allow font structures to be
74  * polymorphic.
75  * 
76  * Any instance of `unifont' used in the vtable functions will
77  * actually be the first element of a larger structure containing
78  * data specific to the subtype. This is permitted by the ISO C
79  * provision that one may safely cast between a pointer to a
80  * structure and a pointer to its first element.
81  */
82
83 #define FONTFLAG_CLIENTSIDE    0x0001
84 #define FONTFLAG_SERVERSIDE    0x0002
85 #define FONTFLAG_SERVERALIAS   0x0004
86 #define FONTFLAG_NONMONOSPACED 0x0008
87
88 typedef void (*fontsel_add_entry)(void *ctx, const char *realfontname,
89                                   const char *family, const char *charset,
90                                   const char *style, const char *stylekey,
91                                   int size, int flags,
92                                   const struct unifont_vtable *fontclass);
93
94 struct unifont_vtable {
95     /*
96      * `Methods' of the `class'.
97      */
98     unifont *(*create)(GtkWidget *widget, const char *name, int wide, int bold,
99                        int shadowoffset, int shadowalways);
100     void (*destroy)(unifont *font);
101     void (*draw_text)(GdkDrawable *target, GdkGC *gc, unifont *font,
102                       int x, int y, const char *string, int len, int wide,
103                       int bold, int cellwidth);
104     void (*enum_fonts)(GtkWidget *widget,
105                        fontsel_add_entry callback, void *callback_ctx);
106     char *(*canonify_fontname)(GtkWidget *widget, const char *name, int *size);
107     char *(*scale_fontname)(GtkWidget *widget, const char *name, int size);
108
109     /*
110      * `Static data members' of the `class'.
111      */
112     const char *prefix;
113 };
114
115 /* ----------------------------------------------------------------------
116  * GDK-based X11 font implementation.
117  */
118
119 static void x11font_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
120                               int x, int y, const char *string, int len,
121                               int wide, int bold, int cellwidth);
122 static unifont *x11font_create(GtkWidget *widget, const char *name,
123                                int wide, int bold,
124                                int shadowoffset, int shadowalways);
125 static void x11font_destroy(unifont *font);
126 static void x11font_enum_fonts(GtkWidget *widget,
127                                fontsel_add_entry callback, void *callback_ctx);
128 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
129                                        int *size);
130 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
131                                     int size);
132
133 struct x11font {
134     struct unifont u;
135     /*
136      * Actual font objects. We store a number of these, for
137      * automatically guessed bold and wide variants.
138      * 
139      * The parallel array `allocated' indicates whether we've
140      * tried to fetch a subfont already (thus distinguishing NULL
141      * because we haven't tried yet from NULL because we tried and
142      * failed, so that we don't keep trying and failing
143      * subsequently).
144      */
145     GdkFont *fonts[4];
146     int allocated[4];
147     /*
148      * `sixteen_bit' is true iff the font object is indexed by
149      * values larger than a byte. That is, this flag tells us
150      * whether we use gdk_draw_text_wc() or gdk_draw_text().
151      */
152     int sixteen_bit;
153     /*
154      * Data passed in to unifont_create().
155      */
156     int wide, bold, shadowoffset, shadowalways;
157 };
158
159 static const struct unifont_vtable x11font_vtable = {
160     x11font_create,
161     x11font_destroy,
162     x11font_draw_text,
163     x11font_enum_fonts,
164     x11font_canonify_fontname,
165     x11font_scale_fontname,
166     "server"
167 };
168
169 char *x11_guess_derived_font_name(GdkFont *font, int bold, int wide)
170 {
171     XFontStruct *xfs = GDK_FONT_XFONT(font);
172     Display *disp = GDK_FONT_XDISPLAY(font);
173     Atom fontprop = XInternAtom(disp, "FONT", False);
174     unsigned long ret;
175     if (XGetFontProperty(xfs, fontprop, &ret)) {
176         char *name = XGetAtomName(disp, (Atom)ret);
177         if (name && name[0] == '-') {
178             char *strings[13];
179             char *dupname, *extrafree = NULL, *ret;
180             char *p, *q;
181             int nstr;
182
183             p = q = dupname = dupstr(name); /* skip initial minus */
184             nstr = 0;
185
186             while (*p && nstr < lenof(strings)) {
187                 if (*p == '-') {
188                     *p = '\0';
189                     strings[nstr++] = p+1;
190                 }
191                 p++;
192             }
193
194             if (nstr < lenof(strings))
195                 return NULL;           /* XLFD was malformed */
196
197             if (bold)
198                 strings[2] = "bold";
199
200             if (wide) {
201                 /* 4 is `wideness', which obviously may have changed. */
202                 /* 5 is additional style, which may be e.g. `ja' or `ko'. */
203                 strings[4] = strings[5] = "*";
204                 strings[11] = extrafree = dupprintf("%d", 2*atoi(strings[11]));
205             }
206
207             ret = dupcat("-", strings[ 0], "-", strings[ 1], "-", strings[ 2],
208                          "-", strings[ 3], "-", strings[ 4], "-", strings[ 5],
209                          "-", strings[ 6], "-", strings[ 7], "-", strings[ 8],
210                          "-", strings[ 9], "-", strings[10], "-", strings[11],
211                          "-", strings[12], NULL);
212             sfree(extrafree);
213             sfree(dupname);
214
215             return ret;
216         }
217     }
218     return NULL;
219 }
220
221 static int x11_font_width(GdkFont *font, int sixteen_bit)
222 {
223     if (sixteen_bit) {
224         XChar2b space;
225         space.byte1 = 0;
226         space.byte2 = ' ';
227         return gdk_text_width(font, (const gchar *)&space, 2);
228     } else {
229         return gdk_char_width(font, ' ');
230     }
231 }
232
233 static unifont *x11font_create(GtkWidget *widget, const char *name,
234                                int wide, int bold,
235                                int shadowoffset, int shadowalways)
236 {
237     struct x11font *xfont;
238     GdkFont *font;
239     XFontStruct *xfs;
240     Display *disp;
241     Atom charset_registry, charset_encoding;
242     unsigned long registry_ret, encoding_ret;
243     int pubcs, realcs, sixteen_bit;
244     int i;
245
246     font = gdk_font_load(name);
247     if (!font)
248         return NULL;
249
250     xfs = GDK_FONT_XFONT(font);
251     disp = GDK_FONT_XDISPLAY(font);
252
253     charset_registry = XInternAtom(disp, "CHARSET_REGISTRY", False);
254     charset_encoding = XInternAtom(disp, "CHARSET_ENCODING", False);
255
256     pubcs = realcs = CS_NONE;
257     sixteen_bit = FALSE;
258
259     if (XGetFontProperty(xfs, charset_registry, &registry_ret) &&
260         XGetFontProperty(xfs, charset_encoding, &encoding_ret)) {
261         char *reg, *enc;
262         reg = XGetAtomName(disp, (Atom)registry_ret);
263         enc = XGetAtomName(disp, (Atom)encoding_ret);
264         if (reg && enc) {
265             char *encoding = dupcat(reg, "-", enc, NULL);
266             pubcs = realcs = charset_from_xenc(encoding);
267
268             /*
269              * iso10646-1 is the only wide font encoding we
270              * support. In this case, we expect clients to give us
271              * UTF-8, which this module must internally convert
272              * into 16-bit Unicode.
273              */
274             if (!strcasecmp(encoding, "iso10646-1")) {
275                 sixteen_bit = TRUE;
276                 pubcs = realcs = CS_UTF8;
277             }
278
279             /*
280              * Hack for X line-drawing characters: if the primary
281              * font is encoded as ISO-8859-1, and has valid glyphs
282              * in the first 32 char positions, it is assumed that
283              * those glyphs are the VT100 line-drawing character
284              * set.
285              * 
286              * Actually, we'll hack even harder by only checking
287              * position 0x19 (vertical line, VT100 linedrawing
288              * `x'). Then we can check it easily by seeing if the
289              * ascent and descent differ.
290              */
291             if (pubcs == CS_ISO8859_1) {
292                 int lb, rb, wid, asc, desc;
293                 gchar text[2];
294
295                 text[1] = '\0';
296                 text[0] = '\x12';
297                 gdk_string_extents(font, text, &lb, &rb, &wid, &asc, &desc);
298                 if (asc != desc)
299                     realcs = CS_ISO8859_1_X11;
300             }
301
302             sfree(encoding);
303         }
304     }
305
306     xfont = snew(struct x11font);
307     xfont->u.vt = &x11font_vtable;
308     xfont->u.width = x11_font_width(font, sixteen_bit);
309     xfont->u.ascent = font->ascent;
310     xfont->u.descent = font->descent;
311     xfont->u.height = xfont->u.ascent + xfont->u.descent;
312     xfont->u.public_charset = pubcs;
313     xfont->u.real_charset = realcs;
314     xfont->fonts[0] = font;
315     xfont->allocated[0] = TRUE;
316     xfont->sixteen_bit = sixteen_bit;
317     xfont->wide = wide;
318     xfont->bold = bold;
319     xfont->shadowoffset = shadowoffset;
320     xfont->shadowalways = shadowalways;
321
322     for (i = 1; i < lenof(xfont->fonts); i++) {
323         xfont->fonts[i] = NULL;
324         xfont->allocated[i] = FALSE;
325     }
326
327     return (unifont *)xfont;
328 }
329
330 static void x11font_destroy(unifont *font)
331 {
332     struct x11font *xfont = (struct x11font *)font;
333     int i;
334
335     for (i = 0; i < lenof(xfont->fonts); i++)
336         if (xfont->fonts[i])
337             gdk_font_unref(xfont->fonts[i]);
338     sfree(font);
339 }
340
341 static void x11_alloc_subfont(struct x11font *xfont, int sfid)
342 {
343     char *derived_name = x11_guess_derived_font_name
344         (xfont->fonts[0], sfid & 1, !!(sfid & 2));
345     xfont->fonts[sfid] = gdk_font_load(derived_name);   /* may be NULL */
346     xfont->allocated[sfid] = TRUE;
347     sfree(derived_name);
348 }
349
350 static void x11font_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
351                               int x, int y, const char *string, int len,
352                               int wide, int bold, int cellwidth)
353 {
354     struct x11font *xfont = (struct x11font *)font;
355     int sfid;
356     int shadowbold = FALSE;
357
358     wide -= xfont->wide;
359     bold -= xfont->bold;
360
361     /*
362      * Decide which subfont we're using, and whether we have to
363      * use shadow bold.
364      */
365     if (xfont->shadowalways && bold) {
366         shadowbold = TRUE;
367         bold = 0;
368     }
369     sfid = 2 * wide + bold;
370     if (!xfont->allocated[sfid])
371         x11_alloc_subfont(xfont, sfid);
372     if (bold && !xfont->fonts[sfid]) {
373         bold = 0;
374         shadowbold = TRUE;
375         sfid = 2 * wide + bold;
376         if (!xfont->allocated[sfid])
377             x11_alloc_subfont(xfont, sfid);
378     }
379
380     if (!xfont->fonts[sfid])
381         return;                        /* we've tried our best, but no luck */
382
383     if (xfont->sixteen_bit) {
384         /*
385          * This X font has 16-bit character indices, which means
386          * we expect our string to have been passed in UTF-8.
387          */
388         XChar2b *xcs;
389         wchar_t *wcs;
390         int nchars, maxchars, i;
391
392         /*
393          * Convert the input string to wide-character Unicode.
394          */
395         maxchars = 0;
396         for (i = 0; i < len; i++)
397             if ((unsigned char)string[i] <= 0x7F ||
398                 (unsigned char)string[i] >= 0xC0)
399                 maxchars++;
400         wcs = snewn(maxchars+1, wchar_t);
401         nchars = charset_to_unicode((char **)&string, &len, wcs, maxchars,
402                                     CS_UTF8, NULL, NULL, 0);
403         assert(nchars <= maxchars);
404         wcs[nchars] = L'\0';
405
406         xcs = snewn(nchars, XChar2b);
407         for (i = 0; i < nchars; i++) {
408             xcs[i].byte1 = wcs[i] >> 8;
409             xcs[i].byte2 = wcs[i];
410         }
411
412         gdk_draw_text(target, xfont->fonts[sfid], gc,
413                       x, y, (gchar *)xcs, nchars*2);
414         if (shadowbold)
415             gdk_draw_text(target, xfont->fonts[sfid], gc,
416                           x + xfont->shadowoffset, y, (gchar *)xcs, nchars*2);
417         sfree(xcs);
418         sfree(wcs);
419     } else {
420         gdk_draw_text(target, xfont->fonts[sfid], gc, x, y, string, len);
421         if (shadowbold)
422             gdk_draw_text(target, xfont->fonts[sfid], gc,
423                           x + xfont->shadowoffset, y, string, len);
424     }
425 }
426
427 static void x11font_enum_fonts(GtkWidget *widget,
428                                fontsel_add_entry callback, void *callback_ctx)
429 {
430     char **fontnames;
431     char *tmp = NULL;
432     int nnames, i, max, tmpsize;
433
434     max = 32768;
435     while (1) {
436         fontnames = XListFonts(GDK_DISPLAY(), "*", max, &nnames);
437         if (nnames >= max) {
438             XFreeFontNames(fontnames);
439             max *= 2;
440         } else
441             break;
442     }
443
444     tmpsize = 0;
445
446     for (i = 0; i < nnames; i++) {
447         if (fontnames[i][0] == '-') {
448             /*
449              * Dismember an XLFD and convert it into the format
450              * we'll be using in the font selector.
451              */
452             char *components[14];
453             char *p, *font, *style, *stylekey, *charset;
454             int j, weightkey, slantkey, setwidthkey;
455             int thistmpsize, fontsize, flags;
456
457             thistmpsize = 4 * strlen(fontnames[i]) + 256;
458             if (tmpsize < thistmpsize) {
459                 tmpsize = thistmpsize;
460                 tmp = sresize(tmp, tmpsize, char);
461             }
462             strcpy(tmp, fontnames[i]);
463
464             p = tmp;
465             for (j = 0; j < 14; j++) {
466                 if (*p)
467                     *p++ = '\0';
468                 components[j] = p;
469                 while (*p && *p != '-')
470                     p++;
471             }
472             *p++ = '\0';
473
474             /*
475              * Font name is made up of fields 0 and 1, in reverse
476              * order with parentheses. (This is what the GTK 1.2 X
477              * font selector does, and it seems to come out
478              * looking reasonably sensible.)
479              */
480             font = p;
481             p += 1 + sprintf(p, "%s (%s)", components[1], components[0]);
482
483             /*
484              * Charset is made up of fields 12 and 13.
485              */
486             charset = p;
487             p += 1 + sprintf(p, "%s-%s", components[12], components[13]);
488
489             /*
490              * Style is a mixture of quite a lot of the fields,
491              * with some strange formatting.
492              */
493             style = p;
494             p += sprintf(p, "%s", components[2][0] ? components[2] :
495                          "regular");
496             if (!g_strcasecmp(components[3], "i"))
497                 p += sprintf(p, " italic");
498             else if (!g_strcasecmp(components[3], "o"))
499                 p += sprintf(p, " oblique");
500             else if (!g_strcasecmp(components[3], "ri"))
501                 p += sprintf(p, " reverse italic");
502             else if (!g_strcasecmp(components[3], "ro"))
503                 p += sprintf(p, " reverse oblique");
504             else if (!g_strcasecmp(components[3], "ot"))
505                 p += sprintf(p, " other-slant");
506             if (components[4][0] && g_strcasecmp(components[4], "normal"))
507                 p += sprintf(p, " %s", components[4]);
508             if (!g_strcasecmp(components[10], "m"))
509                 p += sprintf(p, " [M]");
510             if (!g_strcasecmp(components[10], "c"))
511                 p += sprintf(p, " [C]");
512             if (components[5][0])
513                 p += sprintf(p, " %s", components[5]);
514
515             /*
516              * Style key is the same stuff as above, but with a
517              * couple of transformations done on it to make it
518              * sort more sensibly.
519              */
520             p++;
521             stylekey = p;
522             if (!g_strcasecmp(components[2], "medium") ||
523                 !g_strcasecmp(components[2], "regular") ||
524                 !g_strcasecmp(components[2], "normal") ||
525                 !g_strcasecmp(components[2], "book"))
526                 weightkey = 0;
527             else if (!g_strncasecmp(components[2], "demi", 4) ||
528                      !g_strncasecmp(components[2], "semi", 4))
529                 weightkey = 1;
530             else
531                 weightkey = 2;
532             if (!g_strcasecmp(components[3], "r"))
533                 slantkey = 0;
534             else if (!g_strncasecmp(components[3], "r", 1))
535                 slantkey = 2;
536             else
537                 slantkey = 1;
538             if (!g_strcasecmp(components[4], "normal"))
539                 setwidthkey = 0;
540             else
541                 setwidthkey = 1;
542
543             p += sprintf(p, "%04d%04d%s%04d%04d%s%04d%04d%s%04d%s%04d%s",
544                          weightkey,
545                          strlen(components[2]), components[2],
546                          slantkey,
547                          strlen(components[3]), components[3],
548                          setwidthkey,
549                          strlen(components[4]), components[4],
550                          strlen(components[10]), components[10],
551                          strlen(components[5]), components[5]);
552
553             assert(p - tmp < thistmpsize);
554
555             /*
556              * Size is in pixels, for our application, so we
557              * derive it directly from the pixel size field,
558              * number 6.
559              */
560             fontsize = atoi(components[6]);
561
562             /*
563              * Flags: we need to know whether this is a monospaced
564              * font, which we do by examining the spacing field
565              * again.
566              */
567             flags = FONTFLAG_SERVERSIDE;
568             if (!strchr("CcMm", components[10][0]))
569                 flags |= FONTFLAG_NONMONOSPACED;
570
571             /*
572              * Not sure why, but sometimes the X server will
573              * deliver dummy font types in which fontsize comes
574              * out as zero. Filter those out.
575              */
576             if (fontsize)
577                 callback(callback_ctx, fontnames[i], font, charset,
578                          style, stylekey, fontsize, flags, &x11font_vtable);
579         } else {
580             /*
581              * This isn't an XLFD, so it must be an alias.
582              * Transmit it with mostly null data.
583              * 
584              * It would be nice to work out if it's monospaced
585              * here, but at the moment I can't see that being
586              * anything but computationally hideous. Ah well.
587              */
588             callback(callback_ctx, fontnames[i], fontnames[i], NULL,
589                      NULL, NULL, 0, FONTFLAG_SERVERALIAS, &x11font_vtable);
590         }
591     }
592     XFreeFontNames(fontnames);
593 }
594
595 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
596                                        int *size)
597 {
598     /*
599      * When given an X11 font name to try to make sense of for a
600      * font selector, we must attempt to load it (to see if it
601      * exists), and then canonify it by extracting its FONT
602      * property, which should give its full XLFD even if what we
603      * originally had was an alias.
604      */
605     GdkFont *font = gdk_font_load(name);
606     XFontStruct *xfs;
607     Display *disp;
608     Atom fontprop, fontprop2;
609     unsigned long ret;
610
611     if (!font)
612         return NULL;                   /* didn't make sense to us, sorry */
613
614     gdk_font_ref(font);
615
616     xfs = GDK_FONT_XFONT(font);
617     disp = GDK_FONT_XDISPLAY(font);
618     fontprop = XInternAtom(disp, "FONT", False);
619
620     if (XGetFontProperty(xfs, fontprop, &ret)) {
621         char *name = XGetAtomName(disp, (Atom)ret);
622         if (name) {
623             unsigned long fsize = 12;
624
625             fontprop2 = XInternAtom(disp, "PIXEL_SIZE", False);
626             if (XGetFontProperty(xfs, fontprop2, &fsize)) {
627                 *size = fsize;
628                 gdk_font_unref(font);
629                 return dupstr(name);
630             }
631         }
632     }
633
634     gdk_font_unref(font);
635     return NULL;                       /* something went wrong */
636 }
637
638 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
639                                     int size)
640 {
641     return NULL;                       /* shan't */
642 }
643
644 /* ----------------------------------------------------------------------
645  * Pango font implementation.
646  */
647
648 static void pangofont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
649                                 int x, int y, const char *string, int len,
650                                 int wide, int bold, int cellwidth);
651 static unifont *pangofont_create(GtkWidget *widget, const char *name,
652                                  int wide, int bold,
653                                  int shadowoffset, int shadowalways);
654 static void pangofont_destroy(unifont *font);
655 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback,
656                                  void *callback_ctx);
657 static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name,
658                                          int *size);
659 static char *pangofont_scale_fontname(GtkWidget *widget, const char *name,
660                                       int size);
661
662 struct pangofont {
663     struct unifont u;
664     /*
665      * Pango objects.
666      */
667     PangoFontDescription *desc;
668     PangoFontset *fset;
669     /*
670      * The containing widget.
671      */
672     GtkWidget *widget;
673     /*
674      * Data passed in to unifont_create().
675      */
676     int bold, shadowoffset, shadowalways;
677 };
678
679 static const struct unifont_vtable pangofont_vtable = {
680     pangofont_create,
681     pangofont_destroy,
682     pangofont_draw_text,
683     pangofont_enum_fonts,
684     pangofont_canonify_fontname,
685     pangofont_scale_fontname,
686     "client"
687 };
688
689 static unifont *pangofont_create(GtkWidget *widget, const char *name,
690                                  int wide, int bold,
691                                  int shadowoffset, int shadowalways)
692 {
693     struct pangofont *pfont;
694     PangoContext *ctx;
695 #ifndef PANGO_PRE_1POINT6
696     PangoFontMap *map;
697 #endif
698     PangoFontDescription *desc;
699     PangoFontset *fset;
700     PangoFontMetrics *metrics;
701
702     desc = pango_font_description_from_string(name);
703     if (!desc)
704         return NULL;
705     ctx = gtk_widget_get_pango_context(widget);
706     if (!ctx) {
707         pango_font_description_free(desc);
708         return NULL;
709     }
710 #ifndef PANGO_PRE_1POINT6
711     map = pango_context_get_font_map(ctx);
712     if (!map) {
713         pango_font_description_free(desc);
714         return NULL;
715     }
716     fset = pango_font_map_load_fontset(map, ctx, desc,
717                                        pango_context_get_language(ctx));
718 #else
719     fset = pango_context_load_fontset(ctx, desc,
720                                       pango_context_get_language(ctx));
721 #endif
722     if (!fset) {
723         pango_font_description_free(desc);
724         return NULL;
725     }
726     metrics = pango_fontset_get_metrics(fset);
727     if (!metrics ||
728         pango_font_metrics_get_approximate_digit_width(metrics) == 0) {
729         pango_font_description_free(desc);
730         g_object_unref(fset);
731         return NULL;
732     }
733
734     pfont = snew(struct pangofont);
735     pfont->u.vt = &pangofont_vtable;
736     pfont->u.width =
737         PANGO_PIXELS(pango_font_metrics_get_approximate_digit_width(metrics));
738     pfont->u.ascent = PANGO_PIXELS(pango_font_metrics_get_ascent(metrics));
739     pfont->u.descent = PANGO_PIXELS(pango_font_metrics_get_descent(metrics));
740     pfont->u.height = pfont->u.ascent + pfont->u.descent;
741     /* The Pango API is hardwired to UTF-8 */
742     pfont->u.public_charset = CS_UTF8;
743     pfont->u.real_charset = CS_UTF8;
744     pfont->desc = desc;
745     pfont->fset = fset;
746     pfont->widget = widget;
747     pfont->bold = bold;
748     pfont->shadowoffset = shadowoffset;
749     pfont->shadowalways = shadowalways;
750
751     pango_font_metrics_unref(metrics);
752
753     return (unifont *)pfont;
754 }
755
756 static void pangofont_destroy(unifont *font)
757 {
758     struct pangofont *pfont = (struct pangofont *)font;
759     pango_font_description_free(pfont->desc);
760     g_object_unref(pfont->fset);
761     sfree(font);
762 }
763
764 static void pangofont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
765                                 int x, int y, const char *string, int len,
766                                 int wide, int bold, int cellwidth)
767 {
768     struct pangofont *pfont = (struct pangofont *)font;
769     PangoLayout *layout;
770     PangoRectangle rect;
771     int shadowbold = FALSE;
772
773     if (wide)
774         cellwidth *= 2;
775
776     y -= pfont->u.ascent;
777
778     layout = pango_layout_new(gtk_widget_get_pango_context(pfont->widget));
779     pango_layout_set_font_description(layout, pfont->desc);
780     if (bold > pfont->bold) {
781         if (pfont->shadowalways)
782             shadowbold = TRUE;
783         else {
784             PangoFontDescription *desc2 =
785                 pango_font_description_copy_static(pfont->desc);
786             pango_font_description_set_weight(desc2, PANGO_WEIGHT_BOLD);
787             pango_layout_set_font_description(layout, desc2);
788         }
789     }
790
791     while (len > 0) {
792         int clen;
793
794         /*
795          * Extract a single UTF-8 character from the string.
796          */
797         clen = 1;
798         while (clen < len &&
799                (unsigned char)string[clen] >= 0x80 &&
800                (unsigned char)string[clen] < 0xC0)
801             clen++;
802
803         pango_layout_set_text(layout, string, clen);
804         pango_layout_get_pixel_extents(layout, NULL, &rect);
805         gdk_draw_layout(target, gc, x + (cellwidth - rect.width)/2,
806                         y + (pfont->u.height - rect.height)/2, layout);
807         if (shadowbold)
808             gdk_draw_layout(target, gc, x + (cellwidth - rect.width)/2 + pfont->shadowoffset,
809                             y + (pfont->u.height - rect.height)/2, layout);
810
811         len -= clen;
812         string += clen;
813         x += cellwidth;
814     }
815
816     g_object_unref(layout);
817 }
818
819 /*
820  * Dummy size value to be used when converting a
821  * PangoFontDescription of a scalable font to a string for
822  * internal use.
823  */
824 #define PANGO_DUMMY_SIZE 12
825
826 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback,
827                                  void *callback_ctx)
828 {
829     PangoContext *ctx;
830 #ifndef PANGO_PRE_1POINT6
831     PangoFontMap *map;
832 #endif
833     PangoFontFamily **families;
834     int i, nfamilies;
835
836     ctx = gtk_widget_get_pango_context(widget);
837     if (!ctx)
838         return;
839
840     /*
841      * Ask Pango for a list of font families, and iterate through
842      * them.
843      */
844 #ifndef PANGO_PRE_1POINT6
845     map = pango_context_get_font_map(ctx);
846     if (!map)
847         return;
848     pango_font_map_list_families(map, &families, &nfamilies);
849 #else
850     pango_context_list_families(ctx, &families, &nfamilies);
851 #endif
852     for (i = 0; i < nfamilies; i++) {
853         PangoFontFamily *family = families[i];
854         const char *familyname;
855         int flags;
856         PangoFontFace **faces;
857         int j, nfaces;
858
859         /*
860          * Set up our flags for this font family, and get the name
861          * string.
862          */
863         flags = FONTFLAG_CLIENTSIDE;
864 #ifndef PANGO_PRE_1POINT4
865         /*
866          * In very early versions of Pango, we can't tell
867          * monospaced fonts from non-monospaced.
868          */
869         if (!pango_font_family_is_monospace(family))
870             flags |= FONTFLAG_NONMONOSPACED;
871 #endif
872         familyname = pango_font_family_get_name(family);
873
874         /*
875          * Go through the available font faces in this family.
876          */
877         pango_font_family_list_faces(family, &faces, &nfaces);
878         for (j = 0; j < nfaces; j++) {
879             PangoFontFace *face = faces[j];
880             PangoFontDescription *desc;
881             const char *facename;
882             int *sizes;
883             int k, nsizes, dummysize;
884
885             /*
886              * Get the face name string.
887              */
888             facename = pango_font_face_get_face_name(face);
889
890             /*
891              * Set up a font description with what we've got so
892              * far. We'll fill in the size field manually and then
893              * call pango_font_description_to_string() to give the
894              * full real name of the specific font.
895              */
896             desc = pango_font_face_describe(face);
897
898             /*
899              * See if this font has a list of specific sizes.
900              */
901 #ifndef PANGO_PRE_1POINT4
902             pango_font_face_list_sizes(face, &sizes, &nsizes);
903 #else
904             /*
905              * In early versions of Pango, that call wasn't
906              * supported; we just have to assume everything is
907              * scalable.
908              */
909             sizes = NULL;
910 #endif
911             if (!sizes) {
912                 /*
913                  * Write a single entry with a dummy size.
914                  */
915                 dummysize = PANGO_DUMMY_SIZE * PANGO_SCALE;
916                 sizes = &dummysize;
917                 nsizes = 1;
918             }
919
920             /*
921              * If so, go through them one by one.
922              */
923             for (k = 0; k < nsizes; k++) {
924                 char *fullname;
925                 char stylekey[128];
926
927                 pango_font_description_set_size(desc, sizes[k]);
928
929                 fullname = pango_font_description_to_string(desc);
930
931                 /*
932                  * Construct the sorting key for font styles.
933                  */
934                 {
935                     char *p = stylekey;
936                     int n;
937
938                     n = pango_font_description_get_weight(desc);
939                     /* Weight: normal, then lighter, then bolder */
940                     if (n <= PANGO_WEIGHT_NORMAL)
941                         n = PANGO_WEIGHT_NORMAL - n;
942                     p += sprintf(p, "%4d", n);
943
944                     n = pango_font_description_get_style(desc);
945                     p += sprintf(p, " %2d", n);
946
947                     n = pango_font_description_get_stretch(desc);
948                     /* Stretch: closer to normal sorts earlier */
949                     n = 2 * abs(PANGO_STRETCH_NORMAL - n) +
950                         (n < PANGO_STRETCH_NORMAL);
951                     p += sprintf(p, " %2d", n);
952
953                     n = pango_font_description_get_variant(desc);
954                     p += sprintf(p, " %2d", n);
955                     
956                 }
957
958                 /*
959                  * Got everything. Hand off to the callback.
960                  * (The charset string is NULL, because only
961                  * server-side X fonts use it.)
962                  */
963                 callback(callback_ctx, fullname, familyname, NULL, facename,
964                          stylekey,
965                          (sizes == &dummysize ? 0 : PANGO_PIXELS(sizes[k])),
966                          flags, &pangofont_vtable);
967
968                 g_free(fullname);
969             }
970             if (sizes != &dummysize)
971                 g_free(sizes);
972
973             pango_font_description_free(desc);
974         }
975         g_free(faces);
976     }
977     g_free(families);
978 }
979
980 static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name,
981                                          int *size)
982 {
983     /*
984      * When given a Pango font name to try to make sense of for a
985      * font selector, we must normalise it to PANGO_DUMMY_SIZE and
986      * extract its original size (in pixels) into the `size' field.
987      */
988     PangoContext *ctx;
989 #ifndef PANGO_PRE_1POINT6
990     PangoFontMap *map;
991 #endif
992     PangoFontDescription *desc;
993     PangoFontset *fset;
994     PangoFontMetrics *metrics;
995     char *newname, *retname;
996
997     desc = pango_font_description_from_string(name);
998     if (!desc)
999         return NULL;
1000     ctx = gtk_widget_get_pango_context(widget);
1001     if (!ctx) {
1002         pango_font_description_free(desc);
1003         return NULL;
1004     }
1005 #ifndef PANGO_PRE_1POINT6
1006     map = pango_context_get_font_map(ctx);
1007     if (!map) {
1008         pango_font_description_free(desc);
1009         return NULL;
1010     }
1011     fset = pango_font_map_load_fontset(map, ctx, desc,
1012                                        pango_context_get_language(ctx));
1013 #else
1014     fset = pango_context_load_fontset(ctx, desc,
1015                                       pango_context_get_language(ctx));
1016 #endif
1017     if (!fset) {
1018         pango_font_description_free(desc);
1019         return NULL;
1020     }
1021     metrics = pango_fontset_get_metrics(fset);
1022     if (!metrics ||
1023         pango_font_metrics_get_approximate_digit_width(metrics) == 0) {
1024         pango_font_description_free(desc);
1025         g_object_unref(fset);
1026         return NULL;
1027     }
1028
1029     *size = PANGO_PIXELS(pango_font_description_get_size(desc));
1030     pango_font_description_set_size(desc, PANGO_DUMMY_SIZE * PANGO_SCALE);
1031     newname = pango_font_description_to_string(desc);
1032     retname = dupstr(newname);
1033     g_free(newname);
1034
1035     pango_font_metrics_unref(metrics);
1036     pango_font_description_free(desc);
1037     g_object_unref(fset);
1038
1039     return retname;
1040 }
1041
1042 static char *pangofont_scale_fontname(GtkWidget *widget, const char *name,
1043                                       int size)
1044 {
1045     PangoFontDescription *desc;
1046     char *newname, *retname;
1047
1048     desc = pango_font_description_from_string(name);
1049     if (!desc)
1050         return NULL;
1051     pango_font_description_set_size(desc, size * PANGO_SCALE);
1052     newname = pango_font_description_to_string(desc);
1053     retname = dupstr(newname);
1054     g_free(newname);
1055     pango_font_description_free(desc);
1056
1057     return retname;
1058 }
1059
1060 /* ----------------------------------------------------------------------
1061  * Outermost functions which do the vtable dispatch.
1062  */
1063
1064 /*
1065  * Complete list of font-type subclasses. Listed in preference
1066  * order for unifont_create(). (That is, in the extremely unlikely
1067  * event that the same font name is valid as both a Pango and an
1068  * X11 font, it will be interpreted as the former in the absence
1069  * of an explicit type-disambiguating prefix.)
1070  */
1071 static const struct unifont_vtable *unifont_types[] = {
1072     &pangofont_vtable,
1073     &x11font_vtable,
1074 };
1075
1076 /*
1077  * Function which takes a font name and processes the optional
1078  * scheme prefix. Returns the tail of the font name suitable for
1079  * passing to individual font scheme functions, and also provides
1080  * a subrange of the unifont_types[] array above.
1081  * 
1082  * The return values `start' and `end' denote a half-open interval
1083  * in unifont_types[]; that is, the correct way to iterate over
1084  * them is
1085  * 
1086  *   for (i = start; i < end; i++) {...}
1087  */
1088 static const char *unifont_do_prefix(const char *name, int *start, int *end)
1089 {
1090     int colonpos = strcspn(name, ":");
1091     int i;
1092
1093     if (name[colonpos]) {
1094         /*
1095          * There's a colon prefix on the font name. Use it to work
1096          * out which subclass to use.
1097          */
1098         for (i = 0; i < lenof(unifont_types); i++) {
1099             if (strlen(unifont_types[i]->prefix) == colonpos &&
1100                 !strncmp(unifont_types[i]->prefix, name, colonpos)) {
1101                 *start = i;
1102                 *end = i+1;
1103                 return name + colonpos + 1;
1104             }
1105         }
1106         /*
1107          * None matched, so return an empty scheme list to prevent
1108          * any scheme from being called at all.
1109          */
1110         *start = *end = 0;
1111         return name + colonpos + 1;
1112     } else {
1113         /*
1114          * No colon prefix, so just use all the subclasses.
1115          */
1116         *start = 0;
1117         *end = lenof(unifont_types);
1118         return name;
1119     }
1120 }
1121
1122 unifont *unifont_create(GtkWidget *widget, const char *name, int wide,
1123                         int bold, int shadowoffset, int shadowalways)
1124 {
1125     int i, start, end;
1126
1127     name = unifont_do_prefix(name, &start, &end);
1128
1129     for (i = start; i < end; i++) {
1130         unifont *ret = unifont_types[i]->create(widget, name, wide, bold,
1131                                                 shadowoffset, shadowalways);
1132         if (ret)
1133             return ret;
1134     }
1135     return NULL;                       /* font not found in any scheme */
1136 }
1137
1138 void unifont_destroy(unifont *font)
1139 {
1140     font->vt->destroy(font);
1141 }
1142
1143 void unifont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
1144                        int x, int y, const char *string, int len,
1145                        int wide, int bold, int cellwidth)
1146 {
1147     font->vt->draw_text(target, gc, font, x, y, string, len,
1148                         wide, bold, cellwidth);
1149 }
1150
1151 /* ----------------------------------------------------------------------
1152  * Implementation of a unified font selector.
1153  */
1154
1155 typedef struct fontinfo fontinfo;
1156
1157 typedef struct unifontsel_internal {
1158     /* This must be the structure's first element, for cross-casting */
1159     unifontsel u;
1160     GtkListStore *family_model, *style_model, *size_model;
1161     GtkWidget *family_list, *style_list, *size_entry, *size_list;
1162     GtkWidget *filter_buttons[4];
1163     int filter_flags;
1164     tree234 *fonts_by_realname, *fonts_by_selorder;
1165     fontinfo *selected;
1166     int selsize;
1167     int inhibit_response;  /* inhibit callbacks when we change GUI controls */
1168 } unifontsel_internal;
1169
1170 /*
1171  * The structure held in the tree234s. All the string members are
1172  * part of the same allocated area, so don't need freeing
1173  * separately.
1174  */
1175 struct fontinfo {
1176     char *realname;
1177     char *family, *charset, *style, *stylekey;
1178     int size, flags;
1179     /*
1180      * Fallback sorting key, to permit multiple identical entries
1181      * to exist in the selorder tree.
1182      */
1183     int index;
1184     /*
1185      * Indices mapping fontinfo structures to indices in the list
1186      * boxes. sizeindex is irrelevant if the font is scalable
1187      * (size==0).
1188      */
1189     int familyindex, styleindex, sizeindex;
1190     /*
1191      * The class of font.
1192      */
1193     const struct unifont_vtable *fontclass;
1194 };
1195
1196 static int fontinfo_realname_compare(void *av, void *bv)
1197 {
1198     fontinfo *a = (fontinfo *)av;
1199     fontinfo *b = (fontinfo *)bv;
1200     return g_strcasecmp(a->realname, b->realname);
1201 }
1202
1203 static int fontinfo_realname_find(void *av, void *bv)
1204 {
1205     const char *a = (const char *)av;
1206     fontinfo *b = (fontinfo *)bv;
1207     return g_strcasecmp(a, b->realname);
1208 }
1209
1210 static int strnullcasecmp(const char *a, const char *b)
1211 {
1212     int i;
1213
1214     /*
1215      * If exactly one of the inputs is NULL, it compares before
1216      * the other one.
1217      */
1218     if ((i = (!b) - (!a)) != 0)
1219         return i;
1220
1221     /*
1222      * NULL compares equal.
1223      */
1224     if (!a)
1225         return 0;
1226
1227     /*
1228      * Otherwise, ordinary strcasecmp.
1229      */
1230     return g_strcasecmp(a, b);
1231 }
1232
1233 static int fontinfo_selorder_compare(void *av, void *bv)
1234 {
1235     fontinfo *a = (fontinfo *)av;
1236     fontinfo *b = (fontinfo *)bv;
1237     int i;
1238     if ((i = strnullcasecmp(a->family, b->family)) != 0)
1239         return i;
1240     if ((i = strnullcasecmp(a->charset, b->charset)) != 0)
1241         return i;
1242     if ((i = strnullcasecmp(a->stylekey, b->stylekey)) != 0)
1243         return i;
1244     if ((i = strnullcasecmp(a->style, b->style)) != 0)
1245         return i;
1246     if (a->size != b->size)
1247         return (a->size < b->size ? -1 : +1);
1248     if (a->index != b->index)
1249         return (a->index < b->index ? -1 : +1);
1250     return 0;
1251 }
1252
1253 static void unifontsel_setup_familylist(unifontsel_internal *fs)
1254 {
1255     GtkTreeIter iter;
1256     int i, listindex, minpos = -1, maxpos = -1;
1257     char *currfamily = NULL;
1258     fontinfo *info;
1259
1260     gtk_list_store_clear(fs->family_model);
1261     listindex = 0;
1262
1263     /*
1264      * Search through the font tree for anything matching our
1265      * current filter criteria. When we find one, add its font
1266      * name to the list box.
1267      */
1268     for (i = 0 ;; i++) {
1269         info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1270         /*
1271          * info may be NULL if we've just run off the end of the
1272          * tree. We must still do a processing pass in that
1273          * situation, in case we had an unfinished font record in
1274          * progress.
1275          */
1276         if (info && (info->flags &~ fs->filter_flags)) {
1277             info->familyindex = -1;
1278             continue;                  /* we're filtering out this font */
1279         }
1280         if (!info || strnullcasecmp(currfamily, info->family)) {
1281             /*
1282              * We've either finished a family, or started a new
1283              * one, or both.
1284              */
1285             if (currfamily) {
1286                 gtk_list_store_append(fs->family_model, &iter);
1287                 gtk_list_store_set(fs->family_model, &iter,
1288                                    0, currfamily, 1, minpos, 2, maxpos+1, -1);
1289                 listindex++;
1290             }
1291             if (info) {
1292                 minpos = i;
1293                 currfamily = info->family;
1294             }
1295         }
1296         if (!info)
1297             break;                     /* now we're done */
1298         info->familyindex = listindex;
1299         maxpos = i;
1300     }
1301 }
1302
1303 static void unifontsel_setup_stylelist(unifontsel_internal *fs,
1304                                        int start, int end)
1305 {
1306     GtkTreeIter iter;
1307     int i, listindex, minpos = -1, maxpos = -1, started = FALSE;
1308     char *currcs = NULL, *currstyle = NULL;
1309     fontinfo *info;
1310
1311     gtk_list_store_clear(fs->style_model);
1312     listindex = 0;
1313     started = FALSE;
1314
1315     /*
1316      * Search through the font tree for anything matching our
1317      * current filter criteria. When we find one, add its charset
1318      * and/or style name to the list box.
1319      */
1320     for (i = start; i <= end; i++) {
1321         if (i == end)
1322             info = NULL;
1323         else
1324             info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1325         /*
1326          * info may be NULL if we've just run off the end of the
1327          * relevant data. We must still do a processing pass in
1328          * that situation, in case we had an unfinished font
1329          * record in progress.
1330          */
1331         if (info && (info->flags &~ fs->filter_flags)) {
1332             info->styleindex = -1;
1333             continue;                  /* we're filtering out this font */
1334         }
1335         if (!info || !started || strnullcasecmp(currcs, info->charset) ||
1336              strnullcasecmp(currstyle, info->style)) {
1337             /*
1338              * We've either finished a style/charset, or started a
1339              * new one, or both.
1340              */
1341             started = TRUE;
1342             if (currstyle) {
1343                 gtk_list_store_append(fs->style_model, &iter);
1344                 gtk_list_store_set(fs->style_model, &iter,
1345                                    0, currstyle, 1, minpos, 2, maxpos+1,
1346                                    3, TRUE, -1);
1347                 listindex++;
1348             }
1349             if (info) {
1350                 minpos = i;
1351                 if (info->charset && strnullcasecmp(currcs, info->charset)) {
1352                     gtk_list_store_append(fs->style_model, &iter);
1353                     gtk_list_store_set(fs->style_model, &iter,
1354                                        0, info->charset, 1, -1, 2, -1,
1355                                        3, FALSE, -1);
1356                     listindex++;
1357                 }
1358                 currcs = info->charset;
1359                 currstyle = info->style;
1360             }
1361         }
1362         if (!info)
1363             break;                     /* now we're done */
1364         info->styleindex = listindex;
1365         maxpos = i;
1366     }
1367 }
1368
1369 static const int unifontsel_default_sizes[] = { 10, 12, 14, 16, 20, 24, 32 };
1370
1371 static void unifontsel_setup_sizelist(unifontsel_internal *fs,
1372                                       int start, int end)
1373 {
1374     GtkTreeIter iter;
1375     int i, listindex;
1376     char sizetext[40];
1377     fontinfo *info;
1378
1379     gtk_list_store_clear(fs->size_model);
1380     listindex = 0;
1381
1382     /*
1383      * Search through the font tree for anything matching our
1384      * current filter criteria. When we find one, add its font
1385      * name to the list box.
1386      */
1387     for (i = start; i < end; i++) {
1388         info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1389         if (info->flags &~ fs->filter_flags) {
1390             info->sizeindex = -1;
1391             continue;                  /* we're filtering out this font */
1392         }
1393         if (info->size) {
1394             sprintf(sizetext, "%d", info->size);
1395             info->sizeindex = listindex;
1396             gtk_list_store_append(fs->size_model, &iter);
1397             gtk_list_store_set(fs->size_model, &iter,
1398                                0, sizetext, 1, i, 2, info->size, -1);
1399             listindex++;
1400         } else {
1401             int j;
1402
1403             assert(i == start);
1404             assert(i+1 == end);
1405
1406             for (j = 0; j < lenof(unifontsel_default_sizes); j++) {
1407                 sprintf(sizetext, "%d", unifontsel_default_sizes[j]);
1408                 gtk_list_store_append(fs->size_model, &iter);
1409                 gtk_list_store_set(fs->size_model, &iter, 0, sizetext, 1, i,
1410                                    2, unifontsel_default_sizes[j], -1);
1411                 listindex++;
1412             }
1413         }
1414     }
1415 }
1416
1417 static void unifontsel_set_filter_buttons(unifontsel_internal *fs)
1418 {
1419     int i;
1420
1421     for (i = 0; i < lenof(fs->filter_buttons); i++) {
1422         int flagbit = GPOINTER_TO_INT(gtk_object_get_data
1423                                       (GTK_OBJECT(fs->filter_buttons[i]),
1424                                        "user-data"));
1425         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fs->filter_buttons[i]),
1426                                      !!(fs->filter_flags & flagbit));
1427     }
1428 }
1429
1430 static void unifontsel_select_font(unifontsel_internal *fs,
1431                                    fontinfo *info, int size, int leftlist)
1432 {
1433     int index;
1434     int minval, maxval;
1435     GtkTreePath *treepath;
1436     GtkTreeIter iter;
1437
1438     fs->inhibit_response = TRUE;
1439
1440     fs->selected = info;
1441     fs->selsize = size;
1442
1443     /*
1444      * Find the index of this fontinfo in the selorder list. 
1445      */
1446     index = -1;
1447     findpos234(fs->fonts_by_selorder, info, NULL, &index);
1448     assert(index >= 0);
1449
1450     /*
1451      * Adjust the font selector flags and redo the font family
1452      * list box, if necessary.
1453      */
1454     if (leftlist <= 0 &&
1455         (fs->filter_flags | info->flags) != fs->filter_flags) {
1456         fs->filter_flags |= info->flags;
1457         unifontsel_set_filter_buttons(fs);
1458         unifontsel_setup_familylist(fs);
1459     }
1460
1461     /*
1462      * Find the appropriate family name and select it in the list.
1463      */
1464     assert(info->familyindex >= 0);
1465     treepath = gtk_tree_path_new_from_indices(info->familyindex, -1);
1466     gtk_tree_selection_select_path
1467         (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->family_list)),
1468          treepath);
1469     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->family_list),
1470                                  treepath, NULL, FALSE, 0.0, 0.0);
1471     gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, treepath);
1472     gtk_tree_path_free(treepath);
1473
1474     /*
1475      * Now set up the font style list.
1476      */
1477     gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter,
1478                        1, &minval, 2, &maxval, -1);
1479     if (leftlist <= 1)
1480         unifontsel_setup_stylelist(fs, minval, maxval);
1481
1482     /*
1483      * Find the appropriate style name and select it in the list.
1484      */
1485     if (info->style) {
1486         assert(info->styleindex >= 0);
1487         treepath = gtk_tree_path_new_from_indices(info->styleindex, -1);
1488         gtk_tree_selection_select_path
1489             (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->style_list)),
1490              treepath);
1491         gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->style_list),
1492                                      treepath, NULL, FALSE, 0.0, 0.0);
1493         gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->style_model),
1494                                 &iter, treepath);
1495         gtk_tree_path_free(treepath);
1496
1497         /*
1498          * And set up the size list.
1499          */
1500         gtk_tree_model_get(GTK_TREE_MODEL(fs->style_model), &iter,
1501                            1, &minval, 2, &maxval, -1);
1502         if (leftlist <= 2)
1503             unifontsel_setup_sizelist(fs, minval, maxval);
1504
1505         /*
1506          * Find the appropriate size, and select it in the list.
1507          */
1508         if (info->size) {
1509             assert(info->sizeindex >= 0);
1510             treepath = gtk_tree_path_new_from_indices(info->sizeindex, -1);
1511             gtk_tree_selection_select_path
1512                 (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->size_list)),
1513                  treepath);
1514             gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
1515                                          treepath, NULL, FALSE, 0.0, 0.0);
1516             gtk_tree_path_free(treepath);
1517             size = info->size;
1518         } else {
1519             int j;
1520             for (j = 0; j < lenof(unifontsel_default_sizes); j++)
1521                 if (unifontsel_default_sizes[j] == size) {
1522                     treepath = gtk_tree_path_new_from_indices(j, -1);
1523                     gtk_tree_view_set_cursor(GTK_TREE_VIEW(fs->size_list),
1524                                              treepath, NULL, FALSE);
1525                     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
1526                                                  treepath, NULL, FALSE, 0.0,
1527                                                  0.0);
1528                     gtk_tree_path_free(treepath);
1529                 }
1530         }
1531
1532         /*
1533          * And set up the font size text entry box.
1534          */
1535         {
1536             char sizetext[40];
1537             sprintf(sizetext, "%d", size);
1538             gtk_entry_set_text(GTK_ENTRY(fs->size_entry), sizetext);
1539         }
1540     } else {
1541         if (leftlist <= 2)
1542             unifontsel_setup_sizelist(fs, 0, 0);
1543         gtk_entry_set_text(GTK_ENTRY(fs->size_entry), "");
1544     }
1545
1546     /*
1547      * Grey out the font size edit box if we're not using a
1548      * scalable font.
1549      */
1550     gtk_entry_set_editable(GTK_ENTRY(fs->size_entry), fs->selected->size == 0);
1551     gtk_widget_set_sensitive(fs->size_entry, fs->selected->size == 0);
1552
1553     fs->inhibit_response = FALSE;
1554 }
1555
1556 static void unifontsel_button_toggled(GtkToggleButton *tb, gpointer data)
1557 {
1558     unifontsel_internal *fs = (unifontsel_internal *)data;
1559     int newstate = gtk_toggle_button_get_active(tb);
1560     int newflags;
1561     int flagbit = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(tb),
1562                                                       "user-data"));
1563
1564     if (newstate)
1565         newflags = fs->filter_flags | flagbit;
1566     else
1567         newflags = fs->filter_flags & ~flagbit;
1568
1569     if (fs->filter_flags != newflags) {
1570         fs->filter_flags = newflags;
1571         unifontsel_setup_familylist(fs);
1572     }
1573 }
1574
1575 static void unifontsel_add_entry(void *ctx, const char *realfontname,
1576                                  const char *family, const char *charset,
1577                                  const char *style, const char *stylekey,
1578                                  int size, int flags,
1579                                  const struct unifont_vtable *fontclass)
1580 {
1581     unifontsel_internal *fs = (unifontsel_internal *)ctx;
1582     fontinfo *info;
1583     int totalsize;
1584     char *p;
1585
1586     totalsize = sizeof(fontinfo) + strlen(realfontname) +
1587         (family ? strlen(family) : 0) + (charset ? strlen(charset) : 0) +
1588         (style ? strlen(style) : 0) + (stylekey ? strlen(stylekey) : 0) + 10;
1589     info = (fontinfo *)smalloc(totalsize);
1590     info->fontclass = fontclass;
1591     p = (char *)info + sizeof(fontinfo);
1592     info->realname = p;
1593     strcpy(p, realfontname);
1594     p += 1+strlen(p);
1595     if (family) {
1596         info->family = p;
1597         strcpy(p, family);
1598         p += 1+strlen(p);
1599     } else
1600         info->family = NULL;
1601     if (charset) {
1602         info->charset = p;
1603         strcpy(p, charset);
1604         p += 1+strlen(p);
1605     } else
1606         info->charset = NULL;
1607     if (style) {
1608         info->style = p;
1609         strcpy(p, style);
1610         p += 1+strlen(p);
1611     } else
1612         info->style = NULL;
1613     if (stylekey) {
1614         info->stylekey = p;
1615         strcpy(p, stylekey);
1616         p += 1+strlen(p);
1617     } else
1618         info->stylekey = NULL;
1619     assert(p - (char *)info <= totalsize);
1620     info->size = size;
1621     info->flags = flags;
1622     info->index = count234(fs->fonts_by_selorder);
1623
1624     /*
1625      * It's just conceivable that a misbehaving font enumerator
1626      * might tell us about the same font real name more than once,
1627      * in which case we should silently drop the new one.
1628      */
1629     if (add234(fs->fonts_by_realname, info) != info) {
1630         sfree(info);
1631         return;
1632     }
1633     /*
1634      * However, we should never get a duplicate key in the
1635      * selorder tree, because the index field carefully
1636      * disambiguates otherwise identical records.
1637      */
1638     add234(fs->fonts_by_selorder, info);
1639 }
1640
1641 static void family_changed(GtkTreeSelection *treeselection, gpointer data)
1642 {
1643     unifontsel_internal *fs = (unifontsel_internal *)data;
1644     GtkTreeModel *treemodel;
1645     GtkTreeIter treeiter;
1646     int minval;
1647     fontinfo *info;
1648
1649     if (fs->inhibit_response)          /* we made this change ourselves */
1650         return;
1651
1652     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1653         return;
1654
1655     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
1656     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1657     unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize, 1);
1658 }
1659
1660 static void style_changed(GtkTreeSelection *treeselection, gpointer data)
1661 {
1662     unifontsel_internal *fs = (unifontsel_internal *)data;
1663     GtkTreeModel *treemodel;
1664     GtkTreeIter treeiter;
1665     int minval;
1666     fontinfo *info;
1667
1668     if (fs->inhibit_response)          /* we made this change ourselves */
1669         return;
1670
1671     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1672         return;
1673
1674     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
1675     if (minval < 0)
1676         return;                    /* somehow a charset heading got clicked */
1677     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1678     unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize, 2);
1679 }
1680
1681 static void size_changed(GtkTreeSelection *treeselection, gpointer data)
1682 {
1683     unifontsel_internal *fs = (unifontsel_internal *)data;
1684     GtkTreeModel *treemodel;
1685     GtkTreeIter treeiter;
1686     int minval, size;
1687     fontinfo *info;
1688
1689     if (fs->inhibit_response)          /* we made this change ourselves */
1690         return;
1691
1692     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1693         return;
1694
1695     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, 2, &size, -1);
1696     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1697     unifontsel_select_font(fs, info, info->size ? info->size : size, 3);
1698 }
1699
1700 static void size_entry_changed(GtkEditable *ed, gpointer data)
1701 {
1702     unifontsel_internal *fs = (unifontsel_internal *)data;
1703     const char *text;
1704     int size;
1705
1706     if (fs->inhibit_response)          /* we made this change ourselves */
1707         return;
1708
1709     text = gtk_entry_get_text(GTK_ENTRY(ed));
1710     size = atoi(text);
1711
1712     if (size > 0) {
1713         assert(fs->selected->size == 0);
1714         unifontsel_select_font(fs, fs->selected, size, 3);
1715     }
1716 }
1717
1718 unifontsel *unifontsel_new(const char *wintitle)
1719 {
1720     unifontsel_internal *fs = snew(unifontsel_internal);
1721     GtkWidget *table, *label, *w, *scroll;
1722     GtkListStore *model;
1723     GtkTreeViewColumn *column;
1724     int lists_height, font_width, style_width, size_width;
1725     int i;
1726
1727     fs->inhibit_response = FALSE;
1728
1729     {
1730         /*
1731          * Invent some magic size constants.
1732          */
1733         GtkRequisition req;
1734         label = gtk_label_new("Quite Long Font Name (Foundry)");
1735         gtk_widget_size_request(label, &req);
1736         font_width = req.width;
1737         lists_height = 14 * req.height;
1738         gtk_label_set_text(GTK_LABEL(label), "Italic Extra Condensed");
1739         gtk_widget_size_request(label, &req);
1740         style_width = req.width;
1741         gtk_label_set_text(GTK_LABEL(label), "48000");
1742         gtk_widget_size_request(label, &req);
1743         size_width = req.width;
1744 #if GTK_CHECK_VERSION(2,10,0)
1745         g_object_ref_sink(label);
1746         g_object_unref(label);
1747 #else
1748         gtk_object_sink(GTK_OBJECT(label));
1749 #endif
1750     }
1751
1752     /*
1753      * Create the dialog box and initialise the user-visible
1754      * fields in the returned structure.
1755      */
1756     fs->u.user_data = NULL;
1757     fs->u.window = GTK_WINDOW(gtk_dialog_new());
1758     gtk_window_set_title(fs->u.window, wintitle);
1759     fs->u.cancel_button = gtk_dialog_add_button
1760         (GTK_DIALOG(fs->u.window), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
1761     fs->u.ok_button = gtk_dialog_add_button
1762         (GTK_DIALOG(fs->u.window), GTK_STOCK_OK, GTK_RESPONSE_OK);
1763     gtk_widget_grab_default(fs->u.ok_button);
1764
1765     /*
1766      * Now set up the internal fields, including in particular all
1767      * the controls that actually allow the user to select fonts.
1768      */
1769     table = gtk_table_new(3, 8, FALSE);
1770     gtk_widget_show(table);
1771     gtk_table_set_col_spacings(GTK_TABLE(table), 8);
1772     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(fs->u.window)->vbox),
1773                        table, TRUE, TRUE, 0);
1774
1775     label = gtk_label_new_with_mnemonic("_Font:");
1776     gtk_widget_show(label);
1777     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
1778     gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_FILL, 0, 0, 0);
1779
1780     /*
1781      * The Font list box displays only a string, but additionally
1782      * stores two integers which give the limits within the
1783      * tree234 of the font entries covered by this list entry.
1784      */
1785     model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
1786     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
1787     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
1788     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
1789     gtk_widget_show(w);
1790     column = gtk_tree_view_column_new_with_attributes
1791         ("Font", gtk_cell_renderer_text_new(),
1792          "text", 0, (char *)NULL);
1793     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
1794     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
1795     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
1796                      "changed", G_CALLBACK(family_changed), fs);
1797
1798     scroll = gtk_scrolled_window_new(NULL, NULL);
1799     gtk_container_add(GTK_CONTAINER(scroll), w);
1800     gtk_widget_show(scroll);
1801     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1802                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
1803     gtk_widget_set_size_request(scroll, font_width, lists_height);
1804     gtk_table_attach(GTK_TABLE(table), scroll, 0, 1, 1, 3, GTK_FILL, 0, 0, 0);
1805     fs->family_model = model;
1806     fs->family_list = w;
1807
1808     label = gtk_label_new_with_mnemonic("_Style:");
1809     gtk_widget_show(label);
1810     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
1811     gtk_table_attach(GTK_TABLE(table), label, 1, 2, 0, 1, GTK_FILL, 0, 0, 0);
1812
1813     /*
1814      * The Style list box can contain insensitive elements
1815      * (character set headings for server-side fonts), so we add
1816      * an extra column to the list store to hold that information.
1817      */
1818     model = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT,
1819                                G_TYPE_BOOLEAN);
1820     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
1821     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
1822     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
1823     gtk_widget_show(w);
1824     column = gtk_tree_view_column_new_with_attributes
1825         ("Style", gtk_cell_renderer_text_new(),
1826          "text", 0, "sensitive", 3, (char *)NULL);
1827     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
1828     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
1829     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
1830                      "changed", G_CALLBACK(style_changed), fs);
1831
1832     scroll = gtk_scrolled_window_new(NULL, NULL);
1833     gtk_container_add(GTK_CONTAINER(scroll), w);
1834     gtk_widget_show(scroll);
1835     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1836                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
1837     gtk_widget_set_size_request(scroll, style_width, lists_height);
1838     gtk_table_attach(GTK_TABLE(table), scroll, 1, 2, 1, 3, GTK_FILL, 0, 0, 0);
1839     fs->style_model = model;
1840     fs->style_list = w;
1841
1842     label = gtk_label_new_with_mnemonic("Si_ze:");
1843     gtk_widget_show(label);
1844     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
1845     gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, GTK_FILL, 0, 0, 0);
1846
1847     /*
1848      * The Size label attaches primarily to a text input box so
1849      * that the user can select a size of their choice. The list
1850      * of available sizes is secondary.
1851      */
1852     fs->size_entry = w = gtk_entry_new();
1853     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
1854     gtk_widget_set_size_request(w, size_width, -1);
1855     gtk_widget_show(w);
1856     gtk_table_attach(GTK_TABLE(table), w, 2, 3, 1, 2, GTK_FILL, 0, 0, 0);
1857     g_signal_connect(G_OBJECT(w), "changed", G_CALLBACK(size_entry_changed),
1858                      fs);
1859
1860     model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
1861     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
1862     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
1863     gtk_widget_show(w);
1864     column = gtk_tree_view_column_new_with_attributes
1865         ("Size", gtk_cell_renderer_text_new(),
1866          "text", 0, (char *)NULL);
1867     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
1868     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
1869     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
1870                      "changed", G_CALLBACK(size_changed), fs);
1871
1872     scroll = gtk_scrolled_window_new(NULL, NULL);
1873     gtk_container_add(GTK_CONTAINER(scroll), w);
1874     gtk_widget_show(scroll);
1875     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1876                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
1877     gtk_table_attach(GTK_TABLE(table), scroll, 2, 3, 2, 3, GTK_FILL,
1878                      GTK_EXPAND | GTK_FILL, 0, 0);
1879     fs->size_model = model;
1880     fs->size_list = w;
1881
1882     /*
1883      * FIXME: preview widget
1884      */
1885     i = 0;
1886     w = gtk_check_button_new_with_label("Show client-side fonts");
1887     gtk_object_set_data(GTK_OBJECT(w), "user-data",
1888                         GINT_TO_POINTER(FONTFLAG_CLIENTSIDE));
1889     gtk_signal_connect(GTK_OBJECT(w), "toggled",
1890                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
1891     gtk_widget_show(w);
1892     fs->filter_buttons[i++] = w;
1893     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 4, 5, GTK_FILL, 0, 0, 0);
1894     w = gtk_check_button_new_with_label("Show server-side fonts");
1895     gtk_object_set_data(GTK_OBJECT(w), "user-data",
1896                         GINT_TO_POINTER(FONTFLAG_SERVERSIDE));
1897     gtk_signal_connect(GTK_OBJECT(w), "toggled",
1898                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
1899     gtk_widget_show(w);
1900     fs->filter_buttons[i++] = w;
1901     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 5, 6, GTK_FILL, 0, 0, 0);
1902     w = gtk_check_button_new_with_label("Show server-side font aliases");
1903     gtk_object_set_data(GTK_OBJECT(w), "user-data",
1904                         GINT_TO_POINTER(FONTFLAG_SERVERALIAS));
1905     gtk_signal_connect(GTK_OBJECT(w), "toggled",
1906                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
1907     gtk_widget_show(w);
1908     fs->filter_buttons[i++] = w;
1909     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 6, 7, GTK_FILL, 0, 0, 0);
1910     w = gtk_check_button_new_with_label("Show non-monospaced fonts");
1911     gtk_object_set_data(GTK_OBJECT(w), "user-data",
1912                         GINT_TO_POINTER(FONTFLAG_NONMONOSPACED));
1913     gtk_signal_connect(GTK_OBJECT(w), "toggled",
1914                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
1915     gtk_widget_show(w);
1916     fs->filter_buttons[i++] = w;
1917     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 7, 8, GTK_FILL, 0, 0, 0);
1918
1919     assert(i == lenof(fs->filter_buttons));
1920     fs->filter_flags = FONTFLAG_CLIENTSIDE | FONTFLAG_SERVERSIDE;
1921     unifontsel_set_filter_buttons(fs);
1922
1923     /*
1924      * Go and find all the font names, and set up our master font
1925      * list.
1926      */
1927     fs->fonts_by_realname = newtree234(fontinfo_realname_compare);
1928     fs->fonts_by_selorder = newtree234(fontinfo_selorder_compare);
1929     for (i = 0; i < lenof(unifont_types); i++)
1930         unifont_types[i]->enum_fonts(GTK_WIDGET(fs->u.window),
1931                                      unifontsel_add_entry, fs);
1932
1933     /*
1934      * And set up the initial font names list.
1935      */
1936     unifontsel_setup_familylist(fs);
1937
1938     fs->selected = NULL;
1939
1940     return (unifontsel *)fs;
1941 }
1942
1943 void unifontsel_destroy(unifontsel *fontsel)
1944 {
1945     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
1946     fontinfo *info;
1947
1948     freetree234(fs->fonts_by_selorder);
1949     while ((info = delpos234(fs->fonts_by_realname, 0)) != NULL)
1950         sfree(info);
1951     freetree234(fs->fonts_by_realname);
1952
1953     gtk_widget_destroy(GTK_WIDGET(fs->u.window));
1954     sfree(fs);
1955 }
1956
1957 void unifontsel_set_name(unifontsel *fontsel, const char *fontname)
1958 {
1959     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
1960     int i, start, end, size;
1961     const char *fontname2 = NULL;
1962     fontinfo *info;
1963
1964     /*
1965      * Provide a default if given an empty or null font name.
1966      */
1967     if (!fontname || !*fontname)
1968         fontname = "fixed";   /* Pango zealots might prefer "Monospace 12" */
1969
1970     /*
1971      * Call the canonify_fontname function.
1972      */
1973     fontname = unifont_do_prefix(fontname, &start, &end);
1974     for (i = start; i < end; i++) {
1975         fontname2 = unifont_types[i]->canonify_fontname
1976             (GTK_WIDGET(fs->u.window), fontname, &size);
1977         if (fontname2)
1978             break;
1979     }
1980     if (i == end)
1981         return;                        /* font name not recognised */
1982
1983     /*
1984      * Now look up the canonified font name in our index.
1985      */
1986     info = find234(fs->fonts_by_realname, (char *)fontname2,
1987                    fontinfo_realname_find);
1988
1989     /*
1990      * If we've found the font, and its size field is either
1991      * correct or zero (the latter indicating a scalable font),
1992      * then we're done. Otherwise, try looking up the original
1993      * font name instead.
1994      */
1995     if (!info || (info->size != size && info->size != 0)) {
1996         info = find234(fs->fonts_by_realname, (char *)fontname,
1997                        fontinfo_realname_find);
1998         if (!info || info->size != size)
1999             return;                    /* font name not in our index */
2000     }
2001
2002     /*
2003      * Now we've got a fontinfo structure and a font size, so we
2004      * know everything we need to fill in all the fields in the
2005      * dialog.
2006      */
2007     unifontsel_select_font(fs, info, size, 0);
2008 }
2009
2010 char *unifontsel_get_name(unifontsel *fontsel)
2011 {
2012     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2013     char *name;
2014
2015     assert(fs->selected);
2016
2017     if (fs->selected->size == 0) {
2018         name = fs->selected->fontclass->scale_fontname
2019             (GTK_WIDGET(fs->u.window), fs->selected->realname, fs->selsize);
2020         if (name)
2021             return name;
2022     }
2023
2024     return dupstr(fs->selected->realname);
2025 }