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