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