]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkfont.c
d236c6f41819045ffc1245d325c40745f8cd44f4
[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  *  - start drawing X fonts one character at a time, at least if
31  *    they're not fixed-width? Now we have that helpful pangram,
32  *    we should make it work for everyone.
33  * 
34  *  - think about points versus pixels, harder than I already have
35  * 
36  *  - generalised style and padding polish
37  *     + gtk_scrolled_window_set_shadow_type(foo, GTK_SHADOW_IN);
38  *       might be worth considering
39  *     + work out why the list boxes don't go all the way to the
40  *       RHS of the dialog box
41  *     + sort out the behaviour when resizing the dialog box
42  * 
43  *  - big testing and shakedown!
44  */
45
46 /*
47  * Future work:
48  * 
49  *  - all the GDK font functions used in the x11font subclass are
50  *    deprecated, so one day they may go away. When this happens -
51  *    or before, if I'm feeling proactive - it oughtn't to be too
52  *    difficult in principle to convert the whole thing to use
53  *    actual Xlib font calls.
54  * 
55  *  - it would be nice if we could move the processing of
56  *    underline and VT100 double width into this module, so that
57  *    instead of using the ghastly pixmap-stretching technique
58  *    everywhere we could tell the Pango backend to scale its
59  *    fonts to double size properly and at full resolution.
60  *    However, this requires me to learn how to make Pango stretch
61  *    text to an arbitrary aspect ratio (for double-width only
62  *    text, which perversely is harder than DW+DH), and right now
63  *    I haven't the energy.
64  */
65
66 /*
67  * Ad-hoc vtable mechanism to allow font structures to be
68  * polymorphic.
69  * 
70  * Any instance of `unifont' used in the vtable functions will
71  * actually be the first element of a larger structure containing
72  * data specific to the subtype. This is permitted by the ISO C
73  * provision that one may safely cast between a pointer to a
74  * structure and a pointer to its first element.
75  */
76
77 #define FONTFLAG_CLIENTSIDE    0x0001
78 #define FONTFLAG_SERVERSIDE    0x0002
79 #define FONTFLAG_SERVERALIAS   0x0004
80 #define FONTFLAG_NONMONOSPACED 0x0008
81
82 typedef void (*fontsel_add_entry)(void *ctx, const char *realfontname,
83                                   const char *family, const char *charset,
84                                   const char *style, const char *stylekey,
85                                   int size, int flags,
86                                   const struct unifont_vtable *fontclass);
87
88 struct unifont_vtable {
89     /*
90      * `Methods' of the `class'.
91      */
92     unifont *(*create)(GtkWidget *widget, const char *name, int wide, int bold,
93                        int shadowoffset, int shadowalways);
94     void (*destroy)(unifont *font);
95     void (*draw_text)(GdkDrawable *target, GdkGC *gc, unifont *font,
96                       int x, int y, const char *string, int len, int wide,
97                       int bold, int cellwidth);
98     void (*enum_fonts)(GtkWidget *widget,
99                        fontsel_add_entry callback, void *callback_ctx);
100     char *(*canonify_fontname)(GtkWidget *widget, const char *name, int *size,
101                                int resolve_aliases);
102     char *(*scale_fontname)(GtkWidget *widget, const char *name, int size);
103
104     /*
105      * `Static data members' of the `class'.
106      */
107     const char *prefix;
108 };
109
110 /* ----------------------------------------------------------------------
111  * GDK-based X11 font implementation.
112  */
113
114 static void x11font_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
115                               int x, int y, const char *string, int len,
116                               int wide, int bold, int cellwidth);
117 static unifont *x11font_create(GtkWidget *widget, const char *name,
118                                int wide, int bold,
119                                int shadowoffset, int shadowalways);
120 static void x11font_destroy(unifont *font);
121 static void x11font_enum_fonts(GtkWidget *widget,
122                                fontsel_add_entry callback, void *callback_ctx);
123 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
124                                        int *size, int resolve_aliases);
125 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
126                                     int size);
127
128 struct x11font {
129     struct unifont u;
130     /*
131      * Actual font objects. We store a number of these, for
132      * automatically guessed bold and wide variants.
133      * 
134      * The parallel array `allocated' indicates whether we've
135      * tried to fetch a subfont already (thus distinguishing NULL
136      * because we haven't tried yet from NULL because we tried and
137      * failed, so that we don't keep trying and failing
138      * subsequently).
139      */
140     GdkFont *fonts[4];
141     int allocated[4];
142     /*
143      * `sixteen_bit' is true iff the font object is indexed by
144      * values larger than a byte. That is, this flag tells us
145      * whether we use gdk_draw_text_wc() or gdk_draw_text().
146      */
147     int sixteen_bit;
148     /*
149      * Data passed in to unifont_create().
150      */
151     int wide, bold, shadowoffset, shadowalways;
152 };
153
154 static const struct unifont_vtable x11font_vtable = {
155     x11font_create,
156     x11font_destroy,
157     x11font_draw_text,
158     x11font_enum_fonts,
159     x11font_canonify_fontname,
160     x11font_scale_fontname,
161     "server"
162 };
163
164 char *x11_guess_derived_font_name(GdkFont *font, int bold, int wide)
165 {
166     XFontStruct *xfs = GDK_FONT_XFONT(font);
167     Display *disp = GDK_FONT_XDISPLAY(font);
168     Atom fontprop = XInternAtom(disp, "FONT", False);
169     unsigned long ret;
170     if (XGetFontProperty(xfs, fontprop, &ret)) {
171         char *name = XGetAtomName(disp, (Atom)ret);
172         if (name && name[0] == '-') {
173             char *strings[13];
174             char *dupname, *extrafree = NULL, *ret;
175             char *p, *q;
176             int nstr;
177
178             p = q = dupname = dupstr(name); /* skip initial minus */
179             nstr = 0;
180
181             while (*p && nstr < lenof(strings)) {
182                 if (*p == '-') {
183                     *p = '\0';
184                     strings[nstr++] = p+1;
185                 }
186                 p++;
187             }
188
189             if (nstr < lenof(strings))
190                 return NULL;           /* XLFD was malformed */
191
192             if (bold)
193                 strings[2] = "bold";
194
195             if (wide) {
196                 /* 4 is `wideness', which obviously may have changed. */
197                 /* 5 is additional style, which may be e.g. `ja' or `ko'. */
198                 strings[4] = strings[5] = "*";
199                 strings[11] = extrafree = dupprintf("%d", 2*atoi(strings[11]));
200             }
201
202             ret = dupcat("-", strings[ 0], "-", strings[ 1], "-", strings[ 2],
203                          "-", strings[ 3], "-", strings[ 4], "-", strings[ 5],
204                          "-", strings[ 6], "-", strings[ 7], "-", strings[ 8],
205                          "-", strings[ 9], "-", strings[10], "-", strings[11],
206                          "-", strings[12], NULL);
207             sfree(extrafree);
208             sfree(dupname);
209
210             return ret;
211         }
212     }
213     return NULL;
214 }
215
216 static int x11_font_width(GdkFont *font, int sixteen_bit)
217 {
218     if (sixteen_bit) {
219         XChar2b space;
220         space.byte1 = 0;
221         space.byte2 = ' ';
222         return gdk_text_width(font, (const gchar *)&space, 2);
223     } else {
224         return gdk_char_width(font, ' ');
225     }
226 }
227
228 static unifont *x11font_create(GtkWidget *widget, const char *name,
229                                int wide, int bold,
230                                int shadowoffset, int shadowalways)
231 {
232     struct x11font *xfont;
233     GdkFont *font;
234     XFontStruct *xfs;
235     Display *disp;
236     Atom charset_registry, charset_encoding;
237     unsigned long registry_ret, encoding_ret;
238     int pubcs, realcs, sixteen_bit;
239     int i;
240
241     font = gdk_font_load(name);
242     if (!font)
243         return NULL;
244
245     xfs = GDK_FONT_XFONT(font);
246     disp = GDK_FONT_XDISPLAY(font);
247
248     charset_registry = XInternAtom(disp, "CHARSET_REGISTRY", False);
249     charset_encoding = XInternAtom(disp, "CHARSET_ENCODING", False);
250
251     pubcs = realcs = CS_NONE;
252     sixteen_bit = FALSE;
253
254     if (XGetFontProperty(xfs, charset_registry, &registry_ret) &&
255         XGetFontProperty(xfs, charset_encoding, &encoding_ret)) {
256         char *reg, *enc;
257         reg = XGetAtomName(disp, (Atom)registry_ret);
258         enc = XGetAtomName(disp, (Atom)encoding_ret);
259         if (reg && enc) {
260             char *encoding = dupcat(reg, "-", enc, NULL);
261             pubcs = realcs = charset_from_xenc(encoding);
262
263             /*
264              * iso10646-1 is the only wide font encoding we
265              * support. In this case, we expect clients to give us
266              * UTF-8, which this module must internally convert
267              * into 16-bit Unicode.
268              */
269             if (!strcasecmp(encoding, "iso10646-1")) {
270                 sixteen_bit = TRUE;
271                 pubcs = realcs = CS_UTF8;
272             }
273
274             /*
275              * Hack for X line-drawing characters: if the primary
276              * font is encoded as ISO-8859-1, and has valid glyphs
277              * in the first 32 char positions, it is assumed that
278              * those glyphs are the VT100 line-drawing character
279              * set.
280              * 
281              * Actually, we'll hack even harder by only checking
282              * position 0x19 (vertical line, VT100 linedrawing
283              * `x'). Then we can check it easily by seeing if the
284              * ascent and descent differ.
285              */
286             if (pubcs == CS_ISO8859_1) {
287                 int lb, rb, wid, asc, desc;
288                 gchar text[2];
289
290                 text[1] = '\0';
291                 text[0] = '\x12';
292                 gdk_string_extents(font, text, &lb, &rb, &wid, &asc, &desc);
293                 if (asc != desc)
294                     realcs = CS_ISO8859_1_X11;
295             }
296
297             sfree(encoding);
298         }
299     }
300
301     xfont = snew(struct x11font);
302     xfont->u.vt = &x11font_vtable;
303     xfont->u.width = x11_font_width(font, sixteen_bit);
304     xfont->u.ascent = font->ascent;
305     xfont->u.descent = font->descent;
306     xfont->u.height = xfont->u.ascent + xfont->u.descent;
307     xfont->u.public_charset = pubcs;
308     xfont->u.real_charset = realcs;
309     xfont->fonts[0] = font;
310     xfont->allocated[0] = TRUE;
311     xfont->sixteen_bit = sixteen_bit;
312     xfont->wide = wide;
313     xfont->bold = bold;
314     xfont->shadowoffset = shadowoffset;
315     xfont->shadowalways = shadowalways;
316
317     for (i = 1; i < lenof(xfont->fonts); i++) {
318         xfont->fonts[i] = NULL;
319         xfont->allocated[i] = FALSE;
320     }
321
322     return (unifont *)xfont;
323 }
324
325 static void x11font_destroy(unifont *font)
326 {
327     struct x11font *xfont = (struct x11font *)font;
328     int i;
329
330     for (i = 0; i < lenof(xfont->fonts); i++)
331         if (xfont->fonts[i])
332             gdk_font_unref(xfont->fonts[i]);
333     sfree(font);
334 }
335
336 static void x11_alloc_subfont(struct x11font *xfont, int sfid)
337 {
338     char *derived_name = x11_guess_derived_font_name
339         (xfont->fonts[0], sfid & 1, !!(sfid & 2));
340     xfont->fonts[sfid] = gdk_font_load(derived_name);   /* may be NULL */
341     xfont->allocated[sfid] = TRUE;
342     sfree(derived_name);
343 }
344
345 static void x11font_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
346                               int x, int y, const char *string, int len,
347                               int wide, int bold, int cellwidth)
348 {
349     struct x11font *xfont = (struct x11font *)font;
350     int sfid;
351     int shadowbold = FALSE;
352
353     wide -= xfont->wide;
354     bold -= xfont->bold;
355
356     /*
357      * Decide which subfont we're using, and whether we have to
358      * use shadow bold.
359      */
360     if (xfont->shadowalways && bold) {
361         shadowbold = TRUE;
362         bold = 0;
363     }
364     sfid = 2 * wide + bold;
365     if (!xfont->allocated[sfid])
366         x11_alloc_subfont(xfont, sfid);
367     if (bold && !xfont->fonts[sfid]) {
368         bold = 0;
369         shadowbold = TRUE;
370         sfid = 2 * wide + bold;
371         if (!xfont->allocated[sfid])
372             x11_alloc_subfont(xfont, sfid);
373     }
374
375     if (!xfont->fonts[sfid])
376         return;                        /* we've tried our best, but no luck */
377
378     if (xfont->sixteen_bit) {
379         /*
380          * This X font has 16-bit character indices, which means
381          * we expect our string to have been passed in UTF-8.
382          */
383         XChar2b *xcs;
384         wchar_t *wcs;
385         int nchars, maxchars, i;
386
387         /*
388          * Convert the input string to wide-character Unicode.
389          */
390         maxchars = 0;
391         for (i = 0; i < len; i++)
392             if ((unsigned char)string[i] <= 0x7F ||
393                 (unsigned char)string[i] >= 0xC0)
394                 maxchars++;
395         wcs = snewn(maxchars+1, wchar_t);
396         nchars = charset_to_unicode((char **)&string, &len, wcs, maxchars,
397                                     CS_UTF8, NULL, NULL, 0);
398         assert(nchars <= maxchars);
399         wcs[nchars] = L'\0';
400
401         xcs = snewn(nchars, XChar2b);
402         for (i = 0; i < nchars; i++) {
403             xcs[i].byte1 = wcs[i] >> 8;
404             xcs[i].byte2 = wcs[i];
405         }
406
407         gdk_draw_text(target, xfont->fonts[sfid], gc,
408                       x, y, (gchar *)xcs, nchars*2);
409         if (shadowbold)
410             gdk_draw_text(target, xfont->fonts[sfid], gc,
411                           x + xfont->shadowoffset, y, (gchar *)xcs, nchars*2);
412         sfree(xcs);
413         sfree(wcs);
414     } else {
415         gdk_draw_text(target, xfont->fonts[sfid], gc, x, y, string, len);
416         if (shadowbold)
417             gdk_draw_text(target, xfont->fonts[sfid], gc,
418                           x + xfont->shadowoffset, y, string, len);
419     }
420 }
421
422 static void x11font_enum_fonts(GtkWidget *widget,
423                                fontsel_add_entry callback, void *callback_ctx)
424 {
425     char **fontnames;
426     char *tmp = NULL;
427     int nnames, i, max, tmpsize;
428
429     max = 32768;
430     while (1) {
431         fontnames = XListFonts(GDK_DISPLAY(), "*", max, &nnames);
432         if (nnames >= max) {
433             XFreeFontNames(fontnames);
434             max *= 2;
435         } else
436             break;
437     }
438
439     tmpsize = 0;
440
441     for (i = 0; i < nnames; i++) {
442         if (fontnames[i][0] == '-') {
443             /*
444              * Dismember an XLFD and convert it into the format
445              * we'll be using in the font selector.
446              */
447             char *components[14];
448             char *p, *font, *style, *stylekey, *charset;
449             int j, weightkey, slantkey, setwidthkey;
450             int thistmpsize, fontsize, flags;
451
452             thistmpsize = 4 * strlen(fontnames[i]) + 256;
453             if (tmpsize < thistmpsize) {
454                 tmpsize = thistmpsize;
455                 tmp = sresize(tmp, tmpsize, char);
456             }
457             strcpy(tmp, fontnames[i]);
458
459             p = tmp;
460             for (j = 0; j < 14; j++) {
461                 if (*p)
462                     *p++ = '\0';
463                 components[j] = p;
464                 while (*p && *p != '-')
465                     p++;
466             }
467             *p++ = '\0';
468
469             /*
470              * Font name is made up of fields 0 and 1, in reverse
471              * order with parentheses. (This is what the GTK 1.2 X
472              * font selector does, and it seems to come out
473              * looking reasonably sensible.)
474              */
475             font = p;
476             p += 1 + sprintf(p, "%s (%s)", components[1], components[0]);
477
478             /*
479              * Charset is made up of fields 12 and 13.
480              */
481             charset = p;
482             p += 1 + sprintf(p, "%s-%s", components[12], components[13]);
483
484             /*
485              * Style is a mixture of quite a lot of the fields,
486              * with some strange formatting.
487              */
488             style = p;
489             p += sprintf(p, "%s", components[2][0] ? components[2] :
490                          "regular");
491             if (!g_strcasecmp(components[3], "i"))
492                 p += sprintf(p, " italic");
493             else if (!g_strcasecmp(components[3], "o"))
494                 p += sprintf(p, " oblique");
495             else if (!g_strcasecmp(components[3], "ri"))
496                 p += sprintf(p, " reverse italic");
497             else if (!g_strcasecmp(components[3], "ro"))
498                 p += sprintf(p, " reverse oblique");
499             else if (!g_strcasecmp(components[3], "ot"))
500                 p += sprintf(p, " other-slant");
501             if (components[4][0] && g_strcasecmp(components[4], "normal"))
502                 p += sprintf(p, " %s", components[4]);
503             if (!g_strcasecmp(components[10], "m"))
504                 p += sprintf(p, " [M]");
505             if (!g_strcasecmp(components[10], "c"))
506                 p += sprintf(p, " [C]");
507             if (components[5][0])
508                 p += sprintf(p, " %s", components[5]);
509
510             /*
511              * Style key is the same stuff as above, but with a
512              * couple of transformations done on it to make it
513              * sort more sensibly.
514              */
515             p++;
516             stylekey = p;
517             if (!g_strcasecmp(components[2], "medium") ||
518                 !g_strcasecmp(components[2], "regular") ||
519                 !g_strcasecmp(components[2], "normal") ||
520                 !g_strcasecmp(components[2], "book"))
521                 weightkey = 0;
522             else if (!g_strncasecmp(components[2], "demi", 4) ||
523                      !g_strncasecmp(components[2], "semi", 4))
524                 weightkey = 1;
525             else
526                 weightkey = 2;
527             if (!g_strcasecmp(components[3], "r"))
528                 slantkey = 0;
529             else if (!g_strncasecmp(components[3], "r", 1))
530                 slantkey = 2;
531             else
532                 slantkey = 1;
533             if (!g_strcasecmp(components[4], "normal"))
534                 setwidthkey = 0;
535             else
536                 setwidthkey = 1;
537
538             p += sprintf(p, "%04d%04d%s%04d%04d%s%04d%04d%s%04d%s%04d%s",
539                          weightkey,
540                          strlen(components[2]), components[2],
541                          slantkey,
542                          strlen(components[3]), components[3],
543                          setwidthkey,
544                          strlen(components[4]), components[4],
545                          strlen(components[10]), components[10],
546                          strlen(components[5]), components[5]);
547
548             assert(p - tmp < thistmpsize);
549
550             /*
551              * Size is in pixels, for our application, so we
552              * derive it directly from the pixel size field,
553              * number 6.
554              */
555             fontsize = atoi(components[6]);
556
557             /*
558              * Flags: we need to know whether this is a monospaced
559              * font, which we do by examining the spacing field
560              * again.
561              */
562             flags = FONTFLAG_SERVERSIDE;
563             if (!strchr("CcMm", components[10][0]))
564                 flags |= FONTFLAG_NONMONOSPACED;
565
566             /*
567              * Not sure why, but sometimes the X server will
568              * deliver dummy font types in which fontsize comes
569              * out as zero. Filter those out.
570              */
571             if (fontsize)
572                 callback(callback_ctx, fontnames[i], font, charset,
573                          style, stylekey, fontsize, flags, &x11font_vtable);
574         } else {
575             /*
576              * This isn't an XLFD, so it must be an alias.
577              * Transmit it with mostly null data.
578              * 
579              * It would be nice to work out if it's monospaced
580              * here, but at the moment I can't see that being
581              * anything but computationally hideous. Ah well.
582              */
583             callback(callback_ctx, fontnames[i], fontnames[i], NULL,
584                      NULL, NULL, 0, FONTFLAG_SERVERALIAS, &x11font_vtable);
585         }
586     }
587     XFreeFontNames(fontnames);
588 }
589
590 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
591                                        int *size, int resolve_aliases)
592 {
593     /*
594      * When given an X11 font name to try to make sense of for a
595      * font selector, we must attempt to load it (to see if it
596      * exists), and then canonify it by extracting its FONT
597      * property, which should give its full XLFD even if what we
598      * originally had was a wildcard.
599      * 
600      * However, we must carefully avoid canonifying font
601      * _aliases_, unless specifically asked to, because the font
602      * selector treats them as worthwhile in their own right.
603      */
604     GdkFont *font = gdk_font_load(name);
605     XFontStruct *xfs;
606     Display *disp;
607     Atom fontprop, fontprop2;
608     unsigned long ret;
609
610     if (!font)
611         return NULL;                   /* didn't make sense to us, sorry */
612
613     gdk_font_ref(font);
614
615     xfs = GDK_FONT_XFONT(font);
616     disp = GDK_FONT_XDISPLAY(font);
617     fontprop = XInternAtom(disp, "FONT", False);
618
619     if (XGetFontProperty(xfs, fontprop, &ret)) {
620         char *newname = XGetAtomName(disp, (Atom)ret);
621         if (newname) {
622             unsigned long fsize = 12;
623
624             fontprop2 = XInternAtom(disp, "PIXEL_SIZE", False);
625             if (XGetFontProperty(xfs, fontprop2, &fsize) && fsize > 0) {
626                 *size = fsize;
627                 gdk_font_unref(font);
628                 return dupstr(name[0] == '-' || resolve_aliases ?
629                               newname : 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, int resolve_aliases);
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, int resolve_aliases)
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     GtkWidget *preview_area;
1164     GdkPixmap *preview_pixmap;
1165     int preview_width, preview_height;
1166     GdkColor preview_fg, preview_bg;
1167     int filter_flags;
1168     tree234 *fonts_by_realname, *fonts_by_selorder;
1169     fontinfo *selected;
1170     int selsize, intendedsize;
1171     int inhibit_response;  /* inhibit callbacks when we change GUI controls */
1172 } unifontsel_internal;
1173
1174 /*
1175  * The structure held in the tree234s. All the string members are
1176  * part of the same allocated area, so don't need freeing
1177  * separately.
1178  */
1179 struct fontinfo {
1180     char *realname;
1181     char *family, *charset, *style, *stylekey;
1182     int size, flags;
1183     /*
1184      * Fallback sorting key, to permit multiple identical entries
1185      * to exist in the selorder tree.
1186      */
1187     int index;
1188     /*
1189      * Indices mapping fontinfo structures to indices in the list
1190      * boxes. sizeindex is irrelevant if the font is scalable
1191      * (size==0).
1192      */
1193     int familyindex, styleindex, sizeindex;
1194     /*
1195      * The class of font.
1196      */
1197     const struct unifont_vtable *fontclass;
1198 };
1199
1200 static int fontinfo_realname_compare(void *av, void *bv)
1201 {
1202     fontinfo *a = (fontinfo *)av;
1203     fontinfo *b = (fontinfo *)bv;
1204     return g_strcasecmp(a->realname, b->realname);
1205 }
1206
1207 static int fontinfo_realname_find(void *av, void *bv)
1208 {
1209     const char *a = (const char *)av;
1210     fontinfo *b = (fontinfo *)bv;
1211     return g_strcasecmp(a, b->realname);
1212 }
1213
1214 static int strnullcasecmp(const char *a, const char *b)
1215 {
1216     int i;
1217
1218     /*
1219      * If exactly one of the inputs is NULL, it compares before
1220      * the other one.
1221      */
1222     if ((i = (!b) - (!a)) != 0)
1223         return i;
1224
1225     /*
1226      * NULL compares equal.
1227      */
1228     if (!a)
1229         return 0;
1230
1231     /*
1232      * Otherwise, ordinary strcasecmp.
1233      */
1234     return g_strcasecmp(a, b);
1235 }
1236
1237 static int fontinfo_selorder_compare(void *av, void *bv)
1238 {
1239     fontinfo *a = (fontinfo *)av;
1240     fontinfo *b = (fontinfo *)bv;
1241     int i;
1242     if ((i = strnullcasecmp(a->family, b->family)) != 0)
1243         return i;
1244     if ((i = strnullcasecmp(a->charset, b->charset)) != 0)
1245         return i;
1246     if ((i = strnullcasecmp(a->stylekey, b->stylekey)) != 0)
1247         return i;
1248     if ((i = strnullcasecmp(a->style, b->style)) != 0)
1249         return i;
1250     if (a->size != b->size)
1251         return (a->size < b->size ? -1 : +1);
1252     if (a->index != b->index)
1253         return (a->index < b->index ? -1 : +1);
1254     return 0;
1255 }
1256
1257 static void unifontsel_setup_familylist(unifontsel_internal *fs)
1258 {
1259     GtkTreeIter iter;
1260     int i, listindex, minpos = -1, maxpos = -1;
1261     char *currfamily = NULL;
1262     fontinfo *info;
1263
1264     gtk_list_store_clear(fs->family_model);
1265     listindex = 0;
1266
1267     /*
1268      * Search through the font tree for anything matching our
1269      * current filter criteria. When we find one, add its font
1270      * name to the list box.
1271      */
1272     for (i = 0 ;; i++) {
1273         info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1274         /*
1275          * info may be NULL if we've just run off the end of the
1276          * tree. We must still do a processing pass in that
1277          * situation, in case we had an unfinished font record in
1278          * progress.
1279          */
1280         if (info && (info->flags &~ fs->filter_flags)) {
1281             info->familyindex = -1;
1282             continue;                  /* we're filtering out this font */
1283         }
1284         if (!info || strnullcasecmp(currfamily, info->family)) {
1285             /*
1286              * We've either finished a family, or started a new
1287              * one, or both.
1288              */
1289             if (currfamily) {
1290                 gtk_list_store_append(fs->family_model, &iter);
1291                 gtk_list_store_set(fs->family_model, &iter,
1292                                    0, currfamily, 1, minpos, 2, maxpos+1, -1);
1293                 listindex++;
1294             }
1295             if (info) {
1296                 minpos = i;
1297                 currfamily = info->family;
1298             }
1299         }
1300         if (!info)
1301             break;                     /* now we're done */
1302         info->familyindex = listindex;
1303         maxpos = i;
1304     }
1305 }
1306
1307 static void unifontsel_setup_stylelist(unifontsel_internal *fs,
1308                                        int start, int end)
1309 {
1310     GtkTreeIter iter;
1311     int i, listindex, minpos = -1, maxpos = -1, started = FALSE;
1312     char *currcs = NULL, *currstyle = NULL;
1313     fontinfo *info;
1314
1315     gtk_list_store_clear(fs->style_model);
1316     listindex = 0;
1317     started = FALSE;
1318
1319     /*
1320      * Search through the font tree for anything matching our
1321      * current filter criteria. When we find one, add its charset
1322      * and/or style name to the list box.
1323      */
1324     for (i = start; i <= end; i++) {
1325         if (i == end)
1326             info = NULL;
1327         else
1328             info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1329         /*
1330          * info may be NULL if we've just run off the end of the
1331          * relevant data. We must still do a processing pass in
1332          * that situation, in case we had an unfinished font
1333          * record in progress.
1334          */
1335         if (info && (info->flags &~ fs->filter_flags)) {
1336             info->styleindex = -1;
1337             continue;                  /* we're filtering out this font */
1338         }
1339         if (!info || !started || strnullcasecmp(currcs, info->charset) ||
1340              strnullcasecmp(currstyle, info->style)) {
1341             /*
1342              * We've either finished a style/charset, or started a
1343              * new one, or both.
1344              */
1345             started = TRUE;
1346             if (currstyle) {
1347                 gtk_list_store_append(fs->style_model, &iter);
1348                 gtk_list_store_set(fs->style_model, &iter,
1349                                    0, currstyle, 1, minpos, 2, maxpos+1,
1350                                    3, TRUE, -1);
1351                 listindex++;
1352             }
1353             if (info) {
1354                 minpos = i;
1355                 if (info->charset && strnullcasecmp(currcs, info->charset)) {
1356                     gtk_list_store_append(fs->style_model, &iter);
1357                     gtk_list_store_set(fs->style_model, &iter,
1358                                        0, info->charset, 1, -1, 2, -1,
1359                                        3, FALSE, -1);
1360                     listindex++;
1361                 }
1362                 currcs = info->charset;
1363                 currstyle = info->style;
1364             }
1365         }
1366         if (!info)
1367             break;                     /* now we're done */
1368         info->styleindex = listindex;
1369         maxpos = i;
1370     }
1371 }
1372
1373 static const int unifontsel_default_sizes[] = { 10, 12, 14, 16, 20, 24, 32 };
1374
1375 static void unifontsel_setup_sizelist(unifontsel_internal *fs,
1376                                       int start, int end)
1377 {
1378     GtkTreeIter iter;
1379     int i, listindex;
1380     char sizetext[40];
1381     fontinfo *info;
1382
1383     gtk_list_store_clear(fs->size_model);
1384     listindex = 0;
1385
1386     /*
1387      * Search through the font tree for anything matching our
1388      * current filter criteria. When we find one, add its font
1389      * name to the list box.
1390      */
1391     for (i = start; i < end; i++) {
1392         info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1393         if (info->flags &~ fs->filter_flags) {
1394             info->sizeindex = -1;
1395             continue;                  /* we're filtering out this font */
1396         }
1397         if (info->size) {
1398             sprintf(sizetext, "%d", info->size);
1399             info->sizeindex = listindex;
1400             gtk_list_store_append(fs->size_model, &iter);
1401             gtk_list_store_set(fs->size_model, &iter,
1402                                0, sizetext, 1, i, 2, info->size, -1);
1403             listindex++;
1404         } else {
1405             int j;
1406
1407             assert(i == start);
1408             assert(i+1 == end);
1409
1410             for (j = 0; j < lenof(unifontsel_default_sizes); j++) {
1411                 sprintf(sizetext, "%d", unifontsel_default_sizes[j]);
1412                 gtk_list_store_append(fs->size_model, &iter);
1413                 gtk_list_store_set(fs->size_model, &iter, 0, sizetext, 1, i,
1414                                    2, unifontsel_default_sizes[j], -1);
1415                 listindex++;
1416             }
1417         }
1418     }
1419 }
1420
1421 static void unifontsel_set_filter_buttons(unifontsel_internal *fs)
1422 {
1423     int i;
1424
1425     for (i = 0; i < lenof(fs->filter_buttons); i++) {
1426         int flagbit = GPOINTER_TO_INT(gtk_object_get_data
1427                                       (GTK_OBJECT(fs->filter_buttons[i]),
1428                                        "user-data"));
1429         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fs->filter_buttons[i]),
1430                                      !!(fs->filter_flags & flagbit));
1431     }
1432 }
1433
1434 static void unifontsel_draw_preview_text(unifontsel_internal *fs)
1435 {
1436     unifont *font;
1437     char *sizename;
1438     fontinfo *info = fs->selected;
1439
1440     sizename = info->fontclass->scale_fontname
1441         (GTK_WIDGET(fs->u.window), info->realname, fs->selsize);
1442
1443     font = info->fontclass->create(GTK_WIDGET(fs->u.window),
1444                                    sizename ? sizename : info->realname,
1445                                    FALSE, FALSE, 0, 0);
1446     if (fs->preview_pixmap) {
1447         GdkGC *gc = gdk_gc_new(fs->preview_pixmap);
1448         gdk_gc_set_foreground(gc, &fs->preview_bg);
1449         gdk_draw_rectangle(fs->preview_pixmap, gc, 1, 0, 0,
1450                            fs->preview_width, fs->preview_height);
1451         gdk_gc_set_foreground(gc, &fs->preview_fg);
1452         if (font) {
1453             /*
1454              * The pangram used here is rather carefully
1455              * constructed: it contains a sequence of very narrow
1456              * letters (`jil') and a pair of adjacent very wide
1457              * letters (`wm').
1458              *
1459              * If the user selects a proportional font, it will be
1460              * coerced into fixed-width character cells when used
1461              * in the actual terminal window. We therefore display
1462              * it the same way in the preview pane, so as to show
1463              * it the way it will actually be displayed - and we
1464              * deliberately pick a pangram which will show the
1465              * resulting miskerning at its worst.
1466              *
1467              * We aren't trying to sell people these fonts; we're
1468              * trying to let them make an informed choice. Better
1469              * that they find out the problems with using
1470              * proportional fonts in terminal windows here than
1471              * that they go to the effort of selecting their font
1472              * and _then_ realise it was a mistake.
1473              */
1474             info->fontclass->draw_text(fs->preview_pixmap, gc, font,
1475                                        0, font->ascent,
1476                                        "bankrupt jilted showmen quiz convex fogey",
1477                                        41, FALSE, FALSE, font->width);
1478             info->fontclass->draw_text(fs->preview_pixmap, gc, font,
1479                                        0, font->ascent + font->height,
1480                                        "BANKRUPT JILTED SHOWMEN QUIZ CONVEX FOGEY",
1481                                        41, FALSE, FALSE, font->width);
1482             /*
1483              * The ordering of punctuation here is also selected
1484              * with some specific aims in mind. I put ` and '
1485              * together because some software (and people) still
1486              * use them as matched quotes no matter what Unicode
1487              * might say on the matter, so people can quickly
1488              * check whether they look silly in a candidate font.
1489              * The sequence #_@ is there to let people judge the
1490              * suitability of the underscore as an effectively
1491              * alphabetic character (since that's how it's often
1492              * used in practice, at least by programmers).
1493              */
1494             info->fontclass->draw_text(fs->preview_pixmap, gc, font,
1495                                        0, font->ascent + font->height * 2,
1496                                        "0123456789!?,.:;<>()[]{}\\/`'\"+*-=~#_@|%&^$",
1497                                        42, FALSE, FALSE, font->width);
1498         }
1499         gdk_gc_unref(gc);
1500         gdk_window_invalidate_rect(fs->preview_area->window, NULL, FALSE);
1501     }
1502     if (font)
1503         info->fontclass->destroy(font);
1504
1505     sfree(sizename);
1506 }
1507
1508 static void unifontsel_select_font(unifontsel_internal *fs,
1509                                    fontinfo *info, int size, int leftlist,
1510                                    int size_is_explicit)
1511 {
1512     int index;
1513     int minval, maxval;
1514     GtkTreePath *treepath;
1515     GtkTreeIter iter;
1516
1517     fs->inhibit_response = TRUE;
1518
1519     fs->selected = info;
1520     fs->selsize = size;
1521     if (size_is_explicit)
1522         fs->intendedsize = size;
1523
1524     /*
1525      * Find the index of this fontinfo in the selorder list. 
1526      */
1527     index = -1;
1528     findpos234(fs->fonts_by_selorder, info, NULL, &index);
1529     assert(index >= 0);
1530
1531     /*
1532      * Adjust the font selector flags and redo the font family
1533      * list box, if necessary.
1534      */
1535     if (leftlist <= 0 &&
1536         (fs->filter_flags | info->flags) != fs->filter_flags) {
1537         fs->filter_flags |= info->flags;
1538         unifontsel_set_filter_buttons(fs);
1539         unifontsel_setup_familylist(fs);
1540     }
1541
1542     /*
1543      * Find the appropriate family name and select it in the list.
1544      */
1545     assert(info->familyindex >= 0);
1546     treepath = gtk_tree_path_new_from_indices(info->familyindex, -1);
1547     gtk_tree_selection_select_path
1548         (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->family_list)),
1549          treepath);
1550     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->family_list),
1551                                  treepath, NULL, FALSE, 0.0, 0.0);
1552     gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, treepath);
1553     gtk_tree_path_free(treepath);
1554
1555     /*
1556      * Now set up the font style list.
1557      */
1558     gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter,
1559                        1, &minval, 2, &maxval, -1);
1560     if (leftlist <= 1)
1561         unifontsel_setup_stylelist(fs, minval, maxval);
1562
1563     /*
1564      * Find the appropriate style name and select it in the list.
1565      */
1566     if (info->style) {
1567         assert(info->styleindex >= 0);
1568         treepath = gtk_tree_path_new_from_indices(info->styleindex, -1);
1569         gtk_tree_selection_select_path
1570             (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->style_list)),
1571              treepath);
1572         gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->style_list),
1573                                      treepath, NULL, FALSE, 0.0, 0.0);
1574         gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->style_model),
1575                                 &iter, treepath);
1576         gtk_tree_path_free(treepath);
1577
1578         /*
1579          * And set up the size list.
1580          */
1581         gtk_tree_model_get(GTK_TREE_MODEL(fs->style_model), &iter,
1582                            1, &minval, 2, &maxval, -1);
1583         if (leftlist <= 2)
1584             unifontsel_setup_sizelist(fs, minval, maxval);
1585
1586         /*
1587          * Find the appropriate size, and select it in the list.
1588          */
1589         if (info->size) {
1590             assert(info->sizeindex >= 0);
1591             treepath = gtk_tree_path_new_from_indices(info->sizeindex, -1);
1592             gtk_tree_selection_select_path
1593                 (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->size_list)),
1594                  treepath);
1595             gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
1596                                          treepath, NULL, FALSE, 0.0, 0.0);
1597             gtk_tree_path_free(treepath);
1598             size = info->size;
1599         } else {
1600             int j;
1601             for (j = 0; j < lenof(unifontsel_default_sizes); j++)
1602                 if (unifontsel_default_sizes[j] == size) {
1603                     treepath = gtk_tree_path_new_from_indices(j, -1);
1604                     gtk_tree_view_set_cursor(GTK_TREE_VIEW(fs->size_list),
1605                                              treepath, NULL, FALSE);
1606                     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
1607                                                  treepath, NULL, FALSE, 0.0,
1608                                                  0.0);
1609                     gtk_tree_path_free(treepath);
1610                 }
1611         }
1612
1613         /*
1614          * And set up the font size text entry box.
1615          */
1616         {
1617             char sizetext[40];
1618             sprintf(sizetext, "%d", size);
1619             gtk_entry_set_text(GTK_ENTRY(fs->size_entry), sizetext);
1620         }
1621     } else {
1622         if (leftlist <= 2)
1623             unifontsel_setup_sizelist(fs, 0, 0);
1624         gtk_entry_set_text(GTK_ENTRY(fs->size_entry), "");
1625     }
1626
1627     /*
1628      * Grey out the font size edit box if we're not using a
1629      * scalable font.
1630      */
1631     gtk_entry_set_editable(GTK_ENTRY(fs->size_entry), fs->selected->size == 0);
1632     gtk_widget_set_sensitive(fs->size_entry, fs->selected->size == 0);
1633
1634     unifontsel_draw_preview_text(fs);
1635
1636     fs->inhibit_response = FALSE;
1637 }
1638
1639 static void unifontsel_button_toggled(GtkToggleButton *tb, gpointer data)
1640 {
1641     unifontsel_internal *fs = (unifontsel_internal *)data;
1642     int newstate = gtk_toggle_button_get_active(tb);
1643     int newflags;
1644     int flagbit = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(tb),
1645                                                       "user-data"));
1646
1647     if (newstate)
1648         newflags = fs->filter_flags | flagbit;
1649     else
1650         newflags = fs->filter_flags & ~flagbit;
1651
1652     if (fs->filter_flags != newflags) {
1653         fs->filter_flags = newflags;
1654         unifontsel_setup_familylist(fs);
1655     }
1656 }
1657
1658 static void unifontsel_add_entry(void *ctx, const char *realfontname,
1659                                  const char *family, const char *charset,
1660                                  const char *style, const char *stylekey,
1661                                  int size, int flags,
1662                                  const struct unifont_vtable *fontclass)
1663 {
1664     unifontsel_internal *fs = (unifontsel_internal *)ctx;
1665     fontinfo *info;
1666     int totalsize;
1667     char *p;
1668
1669     totalsize = sizeof(fontinfo) + strlen(realfontname) +
1670         (family ? strlen(family) : 0) + (charset ? strlen(charset) : 0) +
1671         (style ? strlen(style) : 0) + (stylekey ? strlen(stylekey) : 0) + 10;
1672     info = (fontinfo *)smalloc(totalsize);
1673     info->fontclass = fontclass;
1674     p = (char *)info + sizeof(fontinfo);
1675     info->realname = p;
1676     strcpy(p, realfontname);
1677     p += 1+strlen(p);
1678     if (family) {
1679         info->family = p;
1680         strcpy(p, family);
1681         p += 1+strlen(p);
1682     } else
1683         info->family = NULL;
1684     if (charset) {
1685         info->charset = p;
1686         strcpy(p, charset);
1687         p += 1+strlen(p);
1688     } else
1689         info->charset = NULL;
1690     if (style) {
1691         info->style = p;
1692         strcpy(p, style);
1693         p += 1+strlen(p);
1694     } else
1695         info->style = NULL;
1696     if (stylekey) {
1697         info->stylekey = p;
1698         strcpy(p, stylekey);
1699         p += 1+strlen(p);
1700     } else
1701         info->stylekey = NULL;
1702     assert(p - (char *)info <= totalsize);
1703     info->size = size;
1704     info->flags = flags;
1705     info->index = count234(fs->fonts_by_selorder);
1706
1707     /*
1708      * It's just conceivable that a misbehaving font enumerator
1709      * might tell us about the same font real name more than once,
1710      * in which case we should silently drop the new one.
1711      */
1712     if (add234(fs->fonts_by_realname, info) != info) {
1713         sfree(info);
1714         return;
1715     }
1716     /*
1717      * However, we should never get a duplicate key in the
1718      * selorder tree, because the index field carefully
1719      * disambiguates otherwise identical records.
1720      */
1721     add234(fs->fonts_by_selorder, info);
1722 }
1723
1724 static fontinfo *update_for_intended_size(unifontsel_internal *fs,
1725                                           fontinfo *info)
1726 {
1727     fontinfo info2, *below, *above;
1728     int pos;
1729
1730     /*
1731      * Copy the info structure. This doesn't copy its dynamic
1732      * string fields, but that's unimportant because all we're
1733      * going to do is to adjust the size field and use it in one
1734      * tree search.
1735      */
1736     info2 = *info;
1737     info2.size = fs->intendedsize;
1738
1739     /*
1740      * Search in the tree to find the fontinfo structure which
1741      * best approximates the size the user last requested.
1742      */
1743     below = findrelpos234(fs->fonts_by_selorder, &info2, NULL,
1744                           REL234_LE, &pos);
1745     above = index234(fs->fonts_by_selorder, pos+1);
1746
1747     /*
1748      * See if we've found it exactly, which is an easy special
1749      * case. If we have, it'll be in `below' and not `above',
1750      * because we did a REL234_LE rather than REL234_LT search.
1751      */
1752     if (!fontinfo_selorder_compare(&info2, below))
1753         return below;
1754
1755     /*
1756      * Now we've either found two suitable fonts, one smaller and
1757      * one larger, or we're at one or other extreme end of the
1758      * scale. Find out which, by NULLing out either of below and
1759      * above if it differs from this one in any respect but size
1760      * (and the disambiguating index field). Bear in mind, also,
1761      * that either one might _already_ be NULL if we're at the
1762      * extreme ends of the font list.
1763      */
1764     if (below) {
1765         info2.size = below->size;
1766         info2.index = below->index;
1767         if (fontinfo_selorder_compare(&info2, below))
1768             below = NULL;
1769     }
1770     if (above) {
1771         info2.size = above->size;
1772         info2.index = above->index;
1773         if (fontinfo_selorder_compare(&info2, above))
1774             above = NULL;
1775     }
1776
1777     /*
1778      * Now return whichever of above and below is non-NULL, if
1779      * that's unambiguous.
1780      */
1781     if (!above)
1782         return below;
1783     if (!below)
1784         return above;
1785
1786     /*
1787      * And now we really do have to make a choice about whether to
1788      * round up or down. We'll do it by rounding to nearest,
1789      * breaking ties by rounding up.
1790      */
1791     if (above->size - fs->intendedsize <= fs->intendedsize - below->size)
1792         return above;
1793     else
1794         return below;
1795 }
1796
1797 static void family_changed(GtkTreeSelection *treeselection, gpointer data)
1798 {
1799     unifontsel_internal *fs = (unifontsel_internal *)data;
1800     GtkTreeModel *treemodel;
1801     GtkTreeIter treeiter;
1802     int minval;
1803     fontinfo *info;
1804
1805     if (fs->inhibit_response)          /* we made this change ourselves */
1806         return;
1807
1808     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1809         return;
1810
1811     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
1812     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1813     info = update_for_intended_size(fs, info);
1814     if (!info)
1815         return; /* _shouldn't_ happen unless font list is completely funted */
1816     if (!info->size)
1817         fs->selsize = fs->intendedsize;   /* font is scalable */
1818     unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize,
1819                            1, FALSE);
1820 }
1821
1822 static void style_changed(GtkTreeSelection *treeselection, gpointer data)
1823 {
1824     unifontsel_internal *fs = (unifontsel_internal *)data;
1825     GtkTreeModel *treemodel;
1826     GtkTreeIter treeiter;
1827     int minval;
1828     fontinfo *info;
1829
1830     if (fs->inhibit_response)          /* we made this change ourselves */
1831         return;
1832
1833     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1834         return;
1835
1836     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
1837     if (minval < 0)
1838         return;                    /* somehow a charset heading got clicked */
1839     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1840     info = update_for_intended_size(fs, info);
1841     if (!info)
1842         return; /* _shouldn't_ happen unless font list is completely funted */
1843     if (!info->size)
1844         fs->selsize = fs->intendedsize;   /* font is scalable */
1845     unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize,
1846                            2, FALSE);
1847 }
1848
1849 static void size_changed(GtkTreeSelection *treeselection, gpointer data)
1850 {
1851     unifontsel_internal *fs = (unifontsel_internal *)data;
1852     GtkTreeModel *treemodel;
1853     GtkTreeIter treeiter;
1854     int minval, size;
1855     fontinfo *info;
1856
1857     if (fs->inhibit_response)          /* we made this change ourselves */
1858         return;
1859
1860     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1861         return;
1862
1863     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, 2, &size, -1);
1864     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1865     unifontsel_select_font(fs, info, info->size ? info->size : size, 3, TRUE);
1866 }
1867
1868 static void size_entry_changed(GtkEditable *ed, gpointer data)
1869 {
1870     unifontsel_internal *fs = (unifontsel_internal *)data;
1871     const char *text;
1872     int size;
1873
1874     if (fs->inhibit_response)          /* we made this change ourselves */
1875         return;
1876
1877     text = gtk_entry_get_text(GTK_ENTRY(ed));
1878     size = atoi(text);
1879
1880     if (size > 0) {
1881         assert(fs->selected->size == 0);
1882         unifontsel_select_font(fs, fs->selected, size, 3, TRUE);
1883     }
1884 }
1885
1886 static void alias_resolve(GtkTreeView *treeview, GtkTreePath *path,
1887                           GtkTreeViewColumn *column, gpointer data)
1888 {
1889     unifontsel_internal *fs = (unifontsel_internal *)data;
1890     GtkTreeIter iter;
1891     int minval, newsize;
1892     fontinfo *info, *newinfo;
1893     char *newname;
1894
1895     if (fs->inhibit_response)          /* we made this change ourselves */
1896         return;
1897
1898     gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, path);
1899     gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter, 1,&minval, -1);
1900     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1901     if (info) {
1902         newname = info->fontclass->canonify_fontname
1903             (GTK_WIDGET(fs->u.window), info->realname, &newsize, TRUE);
1904         newinfo = find234(fs->fonts_by_realname, (char *)newname,
1905                           fontinfo_realname_find);
1906         sfree(newname);
1907         if (!newinfo)
1908             return;                    /* font name not in our index */
1909         if (newinfo == info)
1910             return;   /* didn't change under canonification => not an alias */
1911         unifontsel_select_font(fs, newinfo,
1912                                newinfo->size ? newinfo->size : newsize,
1913                                1, TRUE);
1914     }
1915 }
1916
1917 static gint unifontsel_expose_area(GtkWidget *widget, GdkEventExpose *event,
1918                                    gpointer data)
1919 {
1920     unifontsel_internal *fs = (unifontsel_internal *)data;
1921
1922     if (fs->preview_pixmap) {
1923         gdk_draw_pixmap(widget->window,
1924                         widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
1925                         fs->preview_pixmap,
1926                         event->area.x, event->area.y,
1927                         event->area.x, event->area.y,
1928                         event->area.width, event->area.height);
1929     }
1930     return TRUE;
1931 }
1932
1933 static gint unifontsel_configure_area(GtkWidget *widget,
1934                                       GdkEventConfigure *event, gpointer data)
1935 {
1936     unifontsel_internal *fs = (unifontsel_internal *)data;
1937     int ox, oy, nx, ny, x, y;
1938
1939     /*
1940      * Enlarge the pixmap, but never shrink it.
1941      */
1942     ox = fs->preview_width;
1943     oy = fs->preview_height;
1944     x = event->width;
1945     y = event->height;
1946     if (x > ox || y > oy) {
1947         if (fs->preview_pixmap)
1948             gdk_pixmap_unref(fs->preview_pixmap);
1949         
1950         nx = (x > ox ? x : ox);
1951         ny = (y > oy ? y : oy);
1952         fs->preview_pixmap = gdk_pixmap_new(widget->window, nx, ny, -1);
1953         fs->preview_width = nx;
1954         fs->preview_height = ny;
1955
1956         unifontsel_draw_preview_text(fs);
1957     }
1958
1959     gdk_window_invalidate_rect(widget->window, NULL, FALSE);
1960
1961     return TRUE;
1962 }
1963
1964 unifontsel *unifontsel_new(const char *wintitle)
1965 {
1966     unifontsel_internal *fs = snew(unifontsel_internal);
1967     GtkWidget *table, *label, *w, *scroll;
1968     GtkListStore *model;
1969     GtkTreeViewColumn *column;
1970     int lists_height, preview_height, font_width, style_width, size_width;
1971     int i;
1972
1973     fs->inhibit_response = FALSE;
1974
1975     {
1976         /*
1977          * Invent some magic size constants.
1978          */
1979         GtkRequisition req;
1980         label = gtk_label_new("Quite Long Font Name (Foundry)");
1981         gtk_widget_size_request(label, &req);
1982         font_width = req.width;
1983         lists_height = 14 * req.height;
1984         preview_height = 5 * req.height;
1985         gtk_label_set_text(GTK_LABEL(label), "Italic Extra Condensed");
1986         gtk_widget_size_request(label, &req);
1987         style_width = req.width;
1988         gtk_label_set_text(GTK_LABEL(label), "48000");
1989         gtk_widget_size_request(label, &req);
1990         size_width = req.width;
1991 #if GTK_CHECK_VERSION(2,10,0)
1992         g_object_ref_sink(label);
1993         g_object_unref(label);
1994 #else
1995         gtk_object_sink(GTK_OBJECT(label));
1996 #endif
1997     }
1998
1999     /*
2000      * Create the dialog box and initialise the user-visible
2001      * fields in the returned structure.
2002      */
2003     fs->u.user_data = NULL;
2004     fs->u.window = GTK_WINDOW(gtk_dialog_new());
2005     gtk_window_set_title(fs->u.window, wintitle);
2006     fs->u.cancel_button = gtk_dialog_add_button
2007         (GTK_DIALOG(fs->u.window), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
2008     fs->u.ok_button = gtk_dialog_add_button
2009         (GTK_DIALOG(fs->u.window), GTK_STOCK_OK, GTK_RESPONSE_OK);
2010     gtk_widget_grab_default(fs->u.ok_button);
2011
2012     /*
2013      * Now set up the internal fields, including in particular all
2014      * the controls that actually allow the user to select fonts.
2015      */
2016     table = gtk_table_new(3, 8, FALSE);
2017     gtk_widget_show(table);
2018     gtk_table_set_col_spacings(GTK_TABLE(table), 8);
2019     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(fs->u.window)->vbox),
2020                        table, TRUE, TRUE, 0);
2021
2022     label = gtk_label_new_with_mnemonic("_Font:");
2023     gtk_widget_show(label);
2024     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2025     gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_FILL, 0, 0, 0);
2026
2027     /*
2028      * The Font list box displays only a string, but additionally
2029      * stores two integers which give the limits within the
2030      * tree234 of the font entries covered by this list entry.
2031      */
2032     model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
2033     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2034     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2035     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2036     gtk_widget_show(w);
2037     column = gtk_tree_view_column_new_with_attributes
2038         ("Font", gtk_cell_renderer_text_new(),
2039          "text", 0, (char *)NULL);
2040     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2041     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2042     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2043                      "changed", G_CALLBACK(family_changed), fs);
2044     g_signal_connect(G_OBJECT(w), "row-activated",
2045                      G_CALLBACK(alias_resolve), fs);
2046
2047     scroll = gtk_scrolled_window_new(NULL, NULL);
2048     gtk_container_add(GTK_CONTAINER(scroll), w);
2049     gtk_widget_show(scroll);
2050     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2051                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2052     gtk_widget_set_size_request(scroll, font_width, lists_height);
2053     gtk_table_attach(GTK_TABLE(table), scroll, 0, 1, 1, 3, GTK_FILL, 0, 0, 0);
2054     fs->family_model = model;
2055     fs->family_list = w;
2056
2057     label = gtk_label_new_with_mnemonic("_Style:");
2058     gtk_widget_show(label);
2059     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2060     gtk_table_attach(GTK_TABLE(table), label, 1, 2, 0, 1, GTK_FILL, 0, 0, 0);
2061
2062     /*
2063      * The Style list box can contain insensitive elements
2064      * (character set headings for server-side fonts), so we add
2065      * an extra column to the list store to hold that information.
2066      */
2067     model = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT,
2068                                G_TYPE_BOOLEAN);
2069     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2070     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2071     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2072     gtk_widget_show(w);
2073     column = gtk_tree_view_column_new_with_attributes
2074         ("Style", gtk_cell_renderer_text_new(),
2075          "text", 0, "sensitive", 3, (char *)NULL);
2076     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2077     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2078     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2079                      "changed", G_CALLBACK(style_changed), fs);
2080
2081     scroll = gtk_scrolled_window_new(NULL, NULL);
2082     gtk_container_add(GTK_CONTAINER(scroll), w);
2083     gtk_widget_show(scroll);
2084     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2085                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2086     gtk_widget_set_size_request(scroll, style_width, lists_height);
2087     gtk_table_attach(GTK_TABLE(table), scroll, 1, 2, 1, 3, GTK_FILL, 0, 0, 0);
2088     fs->style_model = model;
2089     fs->style_list = w;
2090
2091     label = gtk_label_new_with_mnemonic("Si_ze:");
2092     gtk_widget_show(label);
2093     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2094     gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, GTK_FILL, 0, 0, 0);
2095
2096     /*
2097      * The Size label attaches primarily to a text input box so
2098      * that the user can select a size of their choice. The list
2099      * of available sizes is secondary.
2100      */
2101     fs->size_entry = w = gtk_entry_new();
2102     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2103     gtk_widget_set_size_request(w, size_width, -1);
2104     gtk_widget_show(w);
2105     gtk_table_attach(GTK_TABLE(table), w, 2, 3, 1, 2, GTK_FILL, 0, 0, 0);
2106     g_signal_connect(G_OBJECT(w), "changed", G_CALLBACK(size_entry_changed),
2107                      fs);
2108
2109     model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
2110     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2111     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2112     gtk_widget_show(w);
2113     column = gtk_tree_view_column_new_with_attributes
2114         ("Size", gtk_cell_renderer_text_new(),
2115          "text", 0, (char *)NULL);
2116     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2117     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2118     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2119                      "changed", G_CALLBACK(size_changed), fs);
2120
2121     scroll = gtk_scrolled_window_new(NULL, NULL);
2122     gtk_container_add(GTK_CONTAINER(scroll), w);
2123     gtk_widget_show(scroll);
2124     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2125                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2126     gtk_table_attach(GTK_TABLE(table), scroll, 2, 3, 2, 3, GTK_FILL,
2127                      GTK_EXPAND | GTK_FILL, 0, 0);
2128     fs->size_model = model;
2129     fs->size_list = w;
2130
2131     fs->preview_area = gtk_drawing_area_new();
2132     fs->preview_pixmap = NULL;
2133     fs->preview_width = 0;
2134     fs->preview_height = 0;
2135     fs->preview_fg.pixel = fs->preview_bg.pixel = 0;
2136     fs->preview_fg.red = fs->preview_fg.green = fs->preview_fg.blue = 0x0000;
2137     fs->preview_bg.red = fs->preview_bg.green = fs->preview_bg.blue = 0xFFFF;
2138     gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_fg,
2139                              FALSE, FALSE);
2140     gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_bg,
2141                              FALSE, FALSE);
2142     gtk_signal_connect(GTK_OBJECT(fs->preview_area), "expose_event",
2143                        GTK_SIGNAL_FUNC(unifontsel_expose_area), fs);
2144     gtk_signal_connect(GTK_OBJECT(fs->preview_area), "configure_event",
2145                        GTK_SIGNAL_FUNC(unifontsel_configure_area), fs);
2146     gtk_widget_set_size_request(fs->preview_area, 1, preview_height);
2147     gtk_widget_show(fs->preview_area);
2148     gtk_table_attach(GTK_TABLE(table), fs->preview_area, 0, 3, 3, 4,
2149                      GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0);
2150
2151     /*
2152      * FIXME: preview widget
2153      */
2154     i = 0;
2155     w = gtk_check_button_new_with_label("Show client-side fonts");
2156     gtk_object_set_data(GTK_OBJECT(w), "user-data",
2157                         GINT_TO_POINTER(FONTFLAG_CLIENTSIDE));
2158     gtk_signal_connect(GTK_OBJECT(w), "toggled",
2159                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2160     gtk_widget_show(w);
2161     fs->filter_buttons[i++] = w;
2162     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 4, 5, GTK_FILL, 0, 0, 0);
2163     w = gtk_check_button_new_with_label("Show server-side fonts");
2164     gtk_object_set_data(GTK_OBJECT(w), "user-data",
2165                         GINT_TO_POINTER(FONTFLAG_SERVERSIDE));
2166     gtk_signal_connect(GTK_OBJECT(w), "toggled",
2167                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2168     gtk_widget_show(w);
2169     fs->filter_buttons[i++] = w;
2170     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 5, 6, GTK_FILL, 0, 0, 0);
2171     w = gtk_check_button_new_with_label("Show server-side font aliases");
2172     gtk_object_set_data(GTK_OBJECT(w), "user-data",
2173                         GINT_TO_POINTER(FONTFLAG_SERVERALIAS));
2174     gtk_signal_connect(GTK_OBJECT(w), "toggled",
2175                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2176     gtk_widget_show(w);
2177     fs->filter_buttons[i++] = w;
2178     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 6, 7, GTK_FILL, 0, 0, 0);
2179     w = gtk_check_button_new_with_label("Show non-monospaced fonts");
2180     gtk_object_set_data(GTK_OBJECT(w), "user-data",
2181                         GINT_TO_POINTER(FONTFLAG_NONMONOSPACED));
2182     gtk_signal_connect(GTK_OBJECT(w), "toggled",
2183                        GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2184     gtk_widget_show(w);
2185     fs->filter_buttons[i++] = w;
2186     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 7, 8, GTK_FILL, 0, 0, 0);
2187
2188     assert(i == lenof(fs->filter_buttons));
2189     fs->filter_flags = FONTFLAG_CLIENTSIDE | FONTFLAG_SERVERSIDE;
2190     unifontsel_set_filter_buttons(fs);
2191
2192     /*
2193      * Go and find all the font names, and set up our master font
2194      * list.
2195      */
2196     fs->fonts_by_realname = newtree234(fontinfo_realname_compare);
2197     fs->fonts_by_selorder = newtree234(fontinfo_selorder_compare);
2198     for (i = 0; i < lenof(unifont_types); i++)
2199         unifont_types[i]->enum_fonts(GTK_WIDGET(fs->u.window),
2200                                      unifontsel_add_entry, fs);
2201
2202     /*
2203      * And set up the initial font names list.
2204      */
2205     unifontsel_setup_familylist(fs);
2206
2207     fs->selected = NULL;
2208
2209     return (unifontsel *)fs;
2210 }
2211
2212 void unifontsel_destroy(unifontsel *fontsel)
2213 {
2214     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2215     fontinfo *info;
2216
2217     if (fs->preview_pixmap)
2218         gdk_pixmap_unref(fs->preview_pixmap);
2219
2220     freetree234(fs->fonts_by_selorder);
2221     while ((info = delpos234(fs->fonts_by_realname, 0)) != NULL)
2222         sfree(info);
2223     freetree234(fs->fonts_by_realname);
2224
2225     gtk_widget_destroy(GTK_WIDGET(fs->u.window));
2226     sfree(fs);
2227 }
2228
2229 void unifontsel_set_name(unifontsel *fontsel, const char *fontname)
2230 {
2231     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2232     int i, start, end, size;
2233     const char *fontname2 = NULL;
2234     fontinfo *info;
2235
2236     /*
2237      * Provide a default if given an empty or null font name.
2238      */
2239     if (!fontname || !*fontname)
2240         fontname = "fixed";   /* Pango zealots might prefer "Monospace 12" */
2241
2242     /*
2243      * Call the canonify_fontname function.
2244      */
2245     fontname = unifont_do_prefix(fontname, &start, &end);
2246     for (i = start; i < end; i++) {
2247         fontname2 = unifont_types[i]->canonify_fontname
2248             (GTK_WIDGET(fs->u.window), fontname, &size, FALSE);
2249         if (fontname2)
2250             break;
2251     }
2252     if (i == end)
2253         return;                        /* font name not recognised */
2254
2255     /*
2256      * Now look up the canonified font name in our index.
2257      */
2258     info = find234(fs->fonts_by_realname, (char *)fontname2,
2259                    fontinfo_realname_find);
2260
2261     /*
2262      * If we've found the font, and its size field is either
2263      * correct or zero (the latter indicating a scalable font),
2264      * then we're done. Otherwise, try looking up the original
2265      * font name instead.
2266      */
2267     if (!info || (info->size != size && info->size != 0)) {
2268         info = find234(fs->fonts_by_realname, (char *)fontname,
2269                        fontinfo_realname_find);
2270         if (!info || info->size != size)
2271             return;                    /* font name not in our index */
2272     }
2273
2274     /*
2275      * Now we've got a fontinfo structure and a font size, so we
2276      * know everything we need to fill in all the fields in the
2277      * dialog.
2278      */
2279     unifontsel_select_font(fs, info, size, 0, TRUE);
2280 }
2281
2282 char *unifontsel_get_name(unifontsel *fontsel)
2283 {
2284     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2285     char *name;
2286
2287     assert(fs->selected);
2288
2289     if (fs->selected->size == 0) {
2290         name = fs->selected->fontclass->scale_fontname
2291             (GTK_WIDGET(fs->u.window), fs->selected->realname, fs->selsize);
2292         if (name)
2293             return name;
2294     }
2295
2296     return dupstr(fs->selected->realname);
2297 }