]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkfont.c
Saw unifontsel_draw_preview_text() in half.
[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 #if !GTK_CHECK_VERSION(3,0,0)
17 #include <gdk/gdkkeysyms.h>
18 #endif
19 #ifndef NOT_X_WINDOWS
20 #include <gdk/gdkx.h>
21 #include <X11/Xlib.h>
22 #include <X11/Xutil.h>
23 #include <X11/Xatom.h>
24 #endif
25
26 #include "putty.h"
27 #include "gtkfont.h"
28 #include "tree234.h"
29
30 /*
31  * Future work:
32  * 
33  *  - it would be nice to have a display of the current font name,
34  *    and in particular whether it's client- or server-side,
35  *    during the progress of the font selector.
36  * 
37  *  - it would be nice if we could move the processing of
38  *    underline and VT100 double width into this module, so that
39  *    instead of using the ghastly pixmap-stretching technique
40  *    everywhere we could tell the Pango backend to scale its
41  *    fonts to double size properly and at full resolution.
42  *    However, this requires me to learn how to make Pango stretch
43  *    text to an arbitrary aspect ratio (for double-width only
44  *    text, which perversely is harder than DW+DH), and right now
45  *    I haven't the energy.
46  */
47
48 #if !GLIB_CHECK_VERSION(1,3,7)
49 #define g_ascii_strcasecmp g_strcasecmp
50 #define g_ascii_strncasecmp g_strncasecmp
51 #endif
52
53 /*
54  * Ad-hoc vtable mechanism to allow font structures to be
55  * polymorphic.
56  * 
57  * Any instance of `unifont' used in the vtable functions will
58  * actually be the first element of a larger structure containing
59  * data specific to the subtype. This is permitted by the ISO C
60  * provision that one may safely cast between a pointer to a
61  * structure and a pointer to its first element.
62  */
63
64 #define FONTFLAG_CLIENTSIDE    0x0001
65 #define FONTFLAG_SERVERSIDE    0x0002
66 #define FONTFLAG_SERVERALIAS   0x0004
67 #define FONTFLAG_NONMONOSPACED 0x0008
68
69 #define FONTFLAG_SORT_MASK     0x0007 /* used to disambiguate font families */
70
71 typedef void (*fontsel_add_entry)(void *ctx, const char *realfontname,
72                                   const char *family, const char *charset,
73                                   const char *style, const char *stylekey,
74                                   int size, int flags,
75                                   const struct unifont_vtable *fontclass);
76
77 struct unifont_vtable {
78     /*
79      * `Methods' of the `class'.
80      */
81     unifont *(*create)(GtkWidget *widget, const char *name, int wide, int bold,
82                        int shadowoffset, int shadowalways);
83     unifont *(*create_fallback)(GtkWidget *widget, int height, int wide,
84                                 int bold, int shadowoffset, int shadowalways);
85     void (*destroy)(unifont *font);
86     int (*has_glyph)(unifont *font, wchar_t glyph);
87     void (*draw_text)(unifont_drawctx *ctx, unifont *font,
88                       int x, int y, const wchar_t *string, int len,
89                       int wide, int bold, int cellwidth);
90     void (*enum_fonts)(GtkWidget *widget,
91                        fontsel_add_entry callback, void *callback_ctx);
92     char *(*canonify_fontname)(GtkWidget *widget, const char *name, int *size,
93                                int *flags, int resolve_aliases);
94     char *(*scale_fontname)(GtkWidget *widget, const char *name, int size);
95
96     /*
97      * `Static data members' of the `class'.
98      */
99     const char *prefix;
100 };
101
102 #ifndef NOT_X_WINDOWS
103
104 /* ----------------------------------------------------------------------
105  * X11 font implementation, directly using Xlib calls. Conditioned out
106  * if X11 fonts aren't available at all (e.g. building with GTK3 for a
107  * back end other than X).
108  */
109
110 static int x11font_has_glyph(unifont *font, wchar_t glyph);
111 static void x11font_draw_text(unifont_drawctx *ctx, unifont *font,
112                               int x, int y, const wchar_t *string, int len,
113                               int wide, int bold, int cellwidth);
114 static unifont *x11font_create(GtkWidget *widget, const char *name,
115                                int wide, int bold,
116                                int shadowoffset, int shadowalways);
117 static void x11font_destroy(unifont *font);
118 static void x11font_enum_fonts(GtkWidget *widget,
119                                fontsel_add_entry callback, void *callback_ctx);
120 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
121                                        int *size, int *flags,
122                                        int resolve_aliases);
123 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
124                                     int size);
125
126 #ifdef DRAW_TEXT_CAIRO
127 struct cairo_cached_glyph {
128     cairo_surface_t *surface;
129     unsigned char *bitmap;
130 };
131 #endif
132
133 /*
134  * Structure storing a single physical XFontStruct, plus associated
135  * data.
136  */
137 typedef struct x11font_individual {
138     /* The XFontStruct itself. */
139     XFontStruct *xfs;
140
141     /*
142      * The `allocated' flag indicates whether we've tried to fetch
143      * this subfont already (thus distinguishing xfs==NULL because we
144      * haven't tried yet from xfs==NULL because we tried and failed,
145      * so that we don't keep trying and failing subsequently).
146      */
147     int allocated;
148
149 #ifdef DRAW_TEXT_CAIRO
150     /*
151      * A cache of glyph bitmaps downloaded from the X server when
152      * we're in Cairo rendering mode. If glyphcache itself is
153      * non-NULL, then entries in [0,nglyphs) are expected to be
154      * initialised to either NULL or a bitmap pointer.
155      */
156     struct cairo_cached_glyph *glyphcache;
157     int nglyphs;
158
159     /*
160      * X server paraphernalia for actually downloading the glyphs.
161      */
162     Pixmap pixmap;
163     GC gc;
164     int pixwidth, pixheight, pixoriginx, pixoriginy;
165
166     /*
167      * Paraphernalia for loading the resulting bitmaps into Cairo.
168      */
169     int rowsize, allsize, indexflip;
170 #endif
171
172 } x11font_individual;
173
174 struct x11font {
175     struct unifont u;
176     /*
177      * Individual physical X fonts. We store a number of these, for
178      * automatically guessed bold and wide variants.
179      */
180     x11font_individual fonts[4];
181     /*
182      * `sixteen_bit' is true iff the font object is indexed by
183      * values larger than a byte. That is, this flag tells us
184      * whether we use XDrawString or XDrawString16, etc.
185      */
186     int sixteen_bit;
187     /*
188      * `variable' is true iff the font is non-fixed-pitch. This
189      * enables some code which takes greater care over character
190      * positioning during text drawing.
191      */
192     int variable;
193     /*
194      * real_charset is the charset used when translating text into the
195      * font's internal encoding inside draw_text(). This need not be
196      * the same as the public_charset provided to the client; for
197      * example, public_charset might be CS_ISO8859_1 while
198      * real_charset is CS_ISO8859_1_X11.
199      */
200     int real_charset;
201     /*
202      * Data passed in to unifont_create().
203      */
204     int wide, bold, shadowoffset, shadowalways;
205 };
206
207 static const struct unifont_vtable x11font_vtable = {
208     x11font_create,
209     NULL,                              /* no fallback fonts in X11 */
210     x11font_destroy,
211     x11font_has_glyph,
212     x11font_draw_text,
213     x11font_enum_fonts,
214     x11font_canonify_fontname,
215     x11font_scale_fontname,
216     "server",
217 };
218
219 static char *x11_guess_derived_font_name(XFontStruct *xfs, int bold, int wide)
220 {
221     Display *disp = GDK_DISPLAY();
222     Atom fontprop = XInternAtom(disp, "FONT", False);
223     unsigned long ret;
224     if (XGetFontProperty(xfs, fontprop, &ret)) {
225         char *name = XGetAtomName(disp, (Atom)ret);
226         if (name && name[0] == '-') {
227             const char *strings[13];
228             char *dupname, *extrafree = NULL, *ret;
229             char *p, *q;
230             int nstr;
231
232             p = q = dupname = dupstr(name); /* skip initial minus */
233             nstr = 0;
234
235             while (*p && nstr < lenof(strings)) {
236                 if (*p == '-') {
237                     *p = '\0';
238                     strings[nstr++] = p+1;
239                 }
240                 p++;
241             }
242
243             if (nstr < lenof(strings)) {
244                 sfree(dupname);
245                 return NULL;           /* XLFD was malformed */
246             }
247
248             if (bold)
249                 strings[2] = "bold";
250
251             if (wide) {
252                 /* 4 is `wideness', which obviously may have changed. */
253                 /* 5 is additional style, which may be e.g. `ja' or `ko'. */
254                 strings[4] = strings[5] = "*";
255                 strings[11] = extrafree = dupprintf("%d", 2*atoi(strings[11]));
256             }
257
258             ret = dupcat("-", strings[ 0], "-", strings[ 1], "-", strings[ 2],
259                          "-", strings[ 3], "-", strings[ 4], "-", strings[ 5],
260                          "-", strings[ 6], "-", strings[ 7], "-", strings[ 8],
261                          "-", strings[ 9], "-", strings[10], "-", strings[11],
262                          "-", strings[12], NULL);
263             sfree(extrafree);
264             sfree(dupname);
265
266             return ret;
267         }
268     }
269     return NULL;
270 }
271
272 static int x11_font_width(XFontStruct *xfs, int sixteen_bit)
273 {
274     if (sixteen_bit) {
275         XChar2b space;
276         space.byte1 = 0;
277         space.byte2 = '0';
278         return XTextWidth16(xfs, &space, 1);
279     } else {
280         return XTextWidth(xfs, "0", 1);
281     }
282 }
283
284 static int x11_font_has_glyph(XFontStruct *xfs, int byte1, int byte2)
285 {
286     int index;
287
288     /*
289      * Not to be confused with x11font_has_glyph, which is a method of
290      * the x11font 'class' and hence takes a unifont as argument. This
291      * is the low-level function which grubs about in an actual
292      * XFontStruct to see if a given glyph exists.
293      *
294      * We must do this ourselves rather than letting Xlib's
295      * XTextExtents16 do the job, because XTextExtents will helpfully
296      * substitute the font's default_char for any missing glyph and
297      * not tell us it did so, which precisely won't help us find out
298      * which glyphs _are_ missing.
299      *
300      * The man page for XQueryFont is rather confusing about how the
301      * per_char array in the XFontStruct is laid out, because it gives
302      * formulae for determining the two-byte X character code _from_
303      * an index into the per_char array. Going the other way, it's
304      * rather simpler:
305      *
306      * The valid character codes have byte1 between min_byte1 and
307      * max_byte1 inclusive, and byte2 between min_char_or_byte2 and
308      * max_char_or_byte2 inclusive. This gives a rectangle of size
309      * (max_byte2-min_byte1+1) by
310      * (max_char_or_byte2-min_char_or_byte2+1), which is precisely the
311      * rectangle encoded in the per_char array. Hence, given a
312      * character code which is valid in the sense that it falls
313      * somewhere in that rectangle, its index in per_char is given by
314      * setting
315      *
316      *   x = byte2 - min_char_or_byte2
317      *   y = byte1 - min_byte1
318      *   index = y * (max_char_or_byte2-min_char_or_byte2+1) + x
319      *
320      * If min_byte1 and min_byte2 are both zero, that's a special case
321      * which can be treated as if min_byte2 was 1 instead, i.e. the
322      * per_char array just runs from min_char_or_byte2 to
323      * max_char_or_byte2 inclusive, and byte1 should always be zero.
324      */
325
326     if (byte2 < xfs->min_char_or_byte2 || byte2 > xfs->max_char_or_byte2)
327         return FALSE;
328
329     if (xfs->min_byte1 == 0 && xfs->max_byte1 == 0) {
330         index = byte2 - xfs->min_char_or_byte2;
331     } else {
332         if (byte1 < xfs->min_byte1 || byte1 > xfs->max_byte1)
333             return FALSE;
334         index = ((byte2 - xfs->min_char_or_byte2) +
335                  ((byte1 - xfs->min_byte1) *
336                   (xfs->max_char_or_byte2 - xfs->min_char_or_byte2 + 1)));
337     }
338
339     if (!xfs->per_char)   /* per_char NULL => everything in range exists */
340         return TRUE;
341
342     return (xfs->per_char[index].ascent + xfs->per_char[index].descent > 0 ||
343             xfs->per_char[index].width > 0);
344 }
345
346 static unifont *x11font_create(GtkWidget *widget, const char *name,
347                                int wide, int bold,
348                                int shadowoffset, int shadowalways)
349 {
350     struct x11font *xfont;
351     XFontStruct *xfs;
352     Display *disp = GDK_DISPLAY();
353     Atom charset_registry, charset_encoding, spacing;
354     unsigned long registry_ret, encoding_ret, spacing_ret;
355     int pubcs, realcs, sixteen_bit, variable;
356     int i;
357
358     xfs = XLoadQueryFont(disp, name);
359     if (!xfs)
360         return NULL;
361
362     charset_registry = XInternAtom(disp, "CHARSET_REGISTRY", False);
363     charset_encoding = XInternAtom(disp, "CHARSET_ENCODING", False);
364
365     pubcs = realcs = CS_NONE;
366     sixteen_bit = FALSE;
367     variable = TRUE;
368
369     if (XGetFontProperty(xfs, charset_registry, &registry_ret) &&
370         XGetFontProperty(xfs, charset_encoding, &encoding_ret)) {
371         char *reg, *enc;
372         reg = XGetAtomName(disp, (Atom)registry_ret);
373         enc = XGetAtomName(disp, (Atom)encoding_ret);
374         if (reg && enc) {
375             char *encoding = dupcat(reg, "-", enc, NULL);
376             pubcs = realcs = charset_from_xenc(encoding);
377
378             /*
379              * iso10646-1 is the only wide font encoding we
380              * support. In this case, we expect clients to give us
381              * UTF-8, which this module must internally convert
382              * into 16-bit Unicode.
383              */
384             if (!strcasecmp(encoding, "iso10646-1")) {
385                 sixteen_bit = TRUE;
386                 pubcs = realcs = CS_UTF8;
387             }
388
389             /*
390              * Hack for X line-drawing characters: if the primary font
391              * is encoded as ISO-8859-1, and has valid glyphs in the
392              * low character positions, it is assumed that those
393              * glyphs are the VT100 line-drawing character set.
394              */
395             if (pubcs == CS_ISO8859_1) {
396                 int ch;
397                 for (ch = 1; ch < 32; ch++)
398                     if (!x11_font_has_glyph(xfs, 0, ch))
399                         break;
400                 if (ch == 32)
401                     realcs = CS_ISO8859_1_X11;
402             }
403
404             sfree(encoding);
405         }
406     }
407
408     spacing = XInternAtom(disp, "SPACING", False);
409     if (XGetFontProperty(xfs, spacing, &spacing_ret)) {
410         char *spc;
411         spc = XGetAtomName(disp, (Atom)spacing_ret);
412
413         if (spc && strchr("CcMm", spc[0]))
414             variable = FALSE;
415     }
416
417     xfont = snew(struct x11font);
418     xfont->u.vt = &x11font_vtable;
419     xfont->u.width = x11_font_width(xfs, sixteen_bit);
420     xfont->u.ascent = xfs->ascent;
421     xfont->u.descent = xfs->descent;
422     xfont->u.height = xfont->u.ascent + xfont->u.descent;
423     xfont->u.public_charset = pubcs;
424     xfont->u.want_fallback = TRUE;
425 #ifdef DRAW_TEXT_GDK
426     xfont->u.preferred_drawtype = DRAWTYPE_GDK;
427 #elif defined DRAW_TEXT_CAIRO
428     xfont->u.preferred_drawtype = DRAWTYPE_CAIRO;
429 #else
430 #error No drawtype available at all
431 #endif
432     xfont->real_charset = realcs;
433     xfont->sixteen_bit = sixteen_bit;
434     xfont->variable = variable;
435     xfont->wide = wide;
436     xfont->bold = bold;
437     xfont->shadowoffset = shadowoffset;
438     xfont->shadowalways = shadowalways;
439
440     for (i = 0; i < lenof(xfont->fonts); i++) {
441         xfont->fonts[i].xfs = NULL;
442         xfont->fonts[i].allocated = FALSE;
443 #ifdef DRAW_TEXT_CAIRO
444         xfont->fonts[i].glyphcache = NULL;
445         xfont->fonts[i].nglyphs = 0;
446         xfont->fonts[i].pixmap = None;
447         xfont->fonts[i].gc = None;
448 #endif
449     }
450     xfont->fonts[0].xfs = xfs;
451     xfont->fonts[0].allocated = TRUE;
452
453     return (unifont *)xfont;
454 }
455
456 static void x11font_destroy(unifont *font)
457 {
458     Display *disp = GDK_DISPLAY();
459     struct x11font *xfont = (struct x11font *)font;
460     int i;
461
462     for (i = 0; i < lenof(xfont->fonts); i++) {
463         if (xfont->fonts[i].xfs)
464             XFreeFont(disp, xfont->fonts[i].xfs);
465 #ifdef DRAW_TEXT_CAIRO
466         if (xfont->fonts[i].gc != None)
467             XFreeGC(disp, xfont->fonts[i].gc);
468         if (xfont->fonts[i].pixmap != None)
469             XFreePixmap(disp, xfont->fonts[i].pixmap);
470         if (xfont->fonts[i].glyphcache) {
471             int j;
472             for (j = 0; j < xfont->fonts[i].nglyphs; j++) {
473                 cairo_surface_destroy(xfont->fonts[i].glyphcache[j].surface);
474                 sfree(xfont->fonts[i].glyphcache[j].bitmap);
475             }
476             sfree(xfont->fonts[i].glyphcache);
477         }
478 #endif
479     }
480     sfree(font);
481 }
482
483 static void x11_alloc_subfont(struct x11font *xfont, int sfid)
484 {
485     Display *disp = GDK_DISPLAY();
486     char *derived_name = x11_guess_derived_font_name
487         (xfont->fonts[0].xfs, sfid & 1, !!(sfid & 2));
488     xfont->fonts[sfid].xfs = XLoadQueryFont(disp, derived_name);
489     xfont->fonts[sfid].allocated = TRUE;
490     sfree(derived_name);
491     /* Note that xfont->fonts[sfid].xfs may still be NULL, if XLQF failed. */
492 }
493
494 static int x11font_has_glyph(unifont *font, wchar_t glyph)
495 {
496     struct x11font *xfont = (struct x11font *)font;
497
498     if (xfont->sixteen_bit) {
499         /*
500          * This X font has 16-bit character indices, which means
501          * we can directly use our Unicode input value.
502          */
503         return x11_font_has_glyph(xfont->fonts[0].xfs,
504                                   glyph >> 8, glyph & 0xFF);
505     } else {
506         /*
507          * This X font has 8-bit indices, so we must convert to the
508          * appropriate character set.
509          */
510         char sbstring[2];
511         int sblen = wc_to_mb(xfont->real_charset, 0, &glyph, 1,
512                              sbstring, 2, "", NULL, NULL);
513         if (sblen == 0 || !sbstring[0])
514             return FALSE;              /* not even in the charset */
515
516         return x11_font_has_glyph(xfont->fonts[0].xfs, 0,
517                                   (unsigned char)sbstring[0]);
518     }
519 }
520
521 #if !GTK_CHECK_VERSION(2,0,0)
522 #define GDK_DRAWABLE_XID(d) GDK_WINDOW_XWINDOW(d) /* GTK1's name for this */
523 #endif
524
525 static int x11font_width_16(unifont_drawctx *ctx, x11font_individual *xfi,
526                             const void *vstring, int start, int length)
527 {
528     const XChar2b *string = (const XChar2b *)vstring;
529     return XTextWidth16(xfi->xfs, string+start, length);
530 }
531
532 static int x11font_width_8(unifont_drawctx *ctx, x11font_individual *xfi,
533                            const void *vstring, int start, int length)
534 {
535     const char *string = (const char *)vstring;
536     return XTextWidth(xfi->xfs, string+start, length);
537 }
538
539 #ifdef DRAW_TEXT_GDK
540 static void x11font_gdk_setup(unifont_drawctx *ctx, x11font_individual *xfi)
541 {
542     XSetFont(GDK_DISPLAY(), GDK_GC_XGC(ctx->u.gdk.gc), xfi->xfs->fid);
543 }
544
545 static void x11font_gdk_draw_16(unifont_drawctx *ctx,
546                                 x11font_individual *xfi, int x, int y,
547                                 const void *vstring, int start, int length)
548 {
549     const XChar2b *string = (const XChar2b *)vstring;
550     XDrawString16(GDK_DISPLAY(), GDK_DRAWABLE_XID(ctx->u.gdk.target),
551                   GDK_GC_XGC(ctx->u.gdk.gc), x, y, string+start, length);
552 }
553
554 static void x11font_gdk_draw_8(unifont_drawctx *ctx,
555                                x11font_individual *xfi, int x, int y,
556                                const void *vstring, int start, int length)
557 {
558     const char *string = (const char *)vstring;
559     XDrawString(GDK_DISPLAY(), GDK_DRAWABLE_XID(ctx->u.gdk.target),
560                 GDK_GC_XGC(ctx->u.gdk.gc), x, y, string+start, length);
561 }
562 #endif
563
564 #ifdef DRAW_TEXT_CAIRO
565 static void x11font_cairo_setup(unifont_drawctx *ctx, x11font_individual *xfi)
566 {
567     if (xfi->pixmap == None) {
568         XGCValues gcvals;
569         GdkWindow *widgetwin = gtk_widget_get_window(ctx->u.cairo.widget);
570         int widgetscr = GDK_SCREEN_XNUMBER(gdk_window_get_screen(widgetwin));
571
572         xfi->pixwidth =
573             xfi->xfs->max_bounds.rbearing - xfi->xfs->min_bounds.lbearing;
574         xfi->pixheight =
575             xfi->xfs->max_bounds.ascent + xfi->xfs->max_bounds.descent;
576         xfi->pixoriginx = -xfi->xfs->min_bounds.lbearing;
577         xfi->pixoriginy = xfi->xfs->max_bounds.ascent;
578
579         xfi->rowsize = cairo_format_stride_for_width(CAIRO_FORMAT_A1,
580                                                      xfi->pixwidth);
581         xfi->allsize = xfi->rowsize * xfi->pixheight;
582
583         {
584             /*
585              * Test host endianness and use it to set xfi->indexflip,
586              * which is XORed into our left-shift counts in order to
587              * implement the CAIRO_FORMAT_A1 specification, in which
588              * each bitmap byte is oriented LSB-first on little-endian
589              * platforms and MSB-first on big-endian ones.
590              *
591              * This is the same technique Cairo itself uses to test
592              * endianness, so hopefully it'll work in any situation
593              * where Cairo is usable at all.
594              */
595             static const int endianness_test = 1;
596             xfi->indexflip = (*((char *) &endianness_test) == 1) ? 0 : 7;
597         }
598
599         xfi->pixmap = XCreatePixmap
600             (GDK_DISPLAY(),
601              GDK_DRAWABLE_XID(gtk_widget_get_window(ctx->u.cairo.widget)),
602              xfi->pixwidth, xfi->pixheight, 1);
603         gcvals.foreground = WhitePixel(GDK_DISPLAY(), widgetscr);
604         gcvals.background = BlackPixel(GDK_DISPLAY(), widgetscr);
605         gcvals.font = xfi->xfs->fid;
606         xfi->gc = XCreateGC(GDK_DISPLAY(), xfi->pixmap,
607                             GCForeground | GCBackground | GCFont, &gcvals);
608     }
609 }
610
611 static void x11font_cairo_cache_glyph(x11font_individual *xfi, int glyphindex)
612 {
613     XImage *image;
614     int x, y;
615     unsigned char *bitmap;
616
617     bitmap = snewn(xfi->allsize, unsigned char);
618     memset(bitmap, 0, xfi->allsize);
619
620     image = XGetImage(GDK_DISPLAY(), xfi->pixmap, 0, 0,
621                       xfi->pixwidth, xfi->pixheight, AllPlanes, XYPixmap);
622     for (y = 0; y < xfi->pixheight; y++) {
623         for (x = 0; x < xfi->pixwidth; x++) {
624             unsigned long pixel = XGetPixel(image, x, y);
625             if (pixel) {
626                 int byteindex = y * xfi->rowsize + x/8;
627                 int bitindex = (x & 7) ^ xfi->indexflip;
628                 bitmap[byteindex] |= 1U << bitindex;
629             }
630         }
631     }
632     XDestroyImage(image);
633
634     if (xfi->nglyphs <= glyphindex) {
635         /* Round up to the next multiple of 256 on the general
636          * principle that Unicode characters come in contiguous blocks
637          * often used together */
638         int old_nglyphs = xfi->nglyphs;
639         xfi->nglyphs = (glyphindex + 0xFF) & ~0xFF;
640         xfi->glyphcache = sresize(xfi->glyphcache, xfi->nglyphs,
641                                   struct cairo_cached_glyph);
642
643         while (old_nglyphs < xfi->nglyphs) {
644             xfi->glyphcache[old_nglyphs].surface = NULL;
645             xfi->glyphcache[old_nglyphs].bitmap = NULL;
646             old_nglyphs++;
647         }
648     }
649     xfi->glyphcache[glyphindex].bitmap = bitmap;
650     xfi->glyphcache[glyphindex].surface = cairo_image_surface_create_for_data
651         (bitmap, CAIRO_FORMAT_A1, xfi->pixwidth, xfi->pixheight, xfi->rowsize);
652 }
653
654 static void x11font_cairo_draw_glyph(unifont_drawctx *ctx,
655                                      x11font_individual *xfi, int x, int y,
656                                      int glyphindex)
657 {
658     if (xfi->glyphcache[glyphindex].surface) {
659         cairo_mask_surface(ctx->u.cairo.cr,
660                            xfi->glyphcache[glyphindex].surface,
661                            x - xfi->pixoriginx, y - xfi->pixoriginy);
662     }
663 }
664
665 static void x11font_cairo_draw_16(unifont_drawctx *ctx,
666                                   x11font_individual *xfi, int x, int y,
667                                   const void *vstring, int start, int length)
668 {
669     const XChar2b *string = (const XChar2b *)vstring + start;
670     int i;
671     for (i = 0; i < length; i++) {
672         if (x11_font_has_glyph(xfi->xfs, string[i].byte1, string[i].byte2)) {
673             int glyphindex = (256 * (unsigned char)string[i].byte1 +
674                               (unsigned char)string[i].byte2);
675             if (glyphindex >= xfi->nglyphs ||
676                 !xfi->glyphcache[glyphindex].surface) {
677                 XDrawImageString16(GDK_DISPLAY(), xfi->pixmap, xfi->gc,
678                                    xfi->pixoriginx, xfi->pixoriginy,
679                                    string+i, 1);
680                 x11font_cairo_cache_glyph(xfi, glyphindex);
681             }
682             x11font_cairo_draw_glyph(ctx, xfi, x, y, glyphindex);
683             x += XTextWidth16(xfi->xfs, string+i, 1);
684         }
685     }
686 }
687
688 static void x11font_cairo_draw_8(unifont_drawctx *ctx,
689                                  x11font_individual *xfi, int x, int y,
690                                  const void *vstring, int start, int length)
691 {
692     const char *string = (const char *)vstring + start;
693     int i;
694     for (i = 0; i < length; i++) {
695         if (x11_font_has_glyph(xfi->xfs, 0, string[i])) {
696             int glyphindex = (unsigned char)string[i];
697             if (glyphindex >= xfi->nglyphs ||
698                 !xfi->glyphcache[glyphindex].surface) {
699                 XDrawImageString(GDK_DISPLAY(), xfi->pixmap, xfi->gc,
700                                  xfi->pixoriginx, xfi->pixoriginy,
701                                  string+i, 1);
702                 x11font_cairo_cache_glyph(xfi, glyphindex);
703             }
704             x11font_cairo_draw_glyph(ctx, xfi, x, y, glyphindex);
705             x += XTextWidth(xfi->xfs, string+i, 1);
706         }
707     }
708 }
709 #endif /* DRAW_TEXT_CAIRO */
710
711 struct x11font_drawfuncs {
712     int (*width)(unifont_drawctx *ctx, x11font_individual *xfi,
713                  const void *vstring, int start, int length);
714     void (*setup)(unifont_drawctx *ctx, x11font_individual *xfi);
715     void (*draw)(unifont_drawctx *ctx, x11font_individual *xfi, int x, int y,
716                  const void *vstring, int start, int length);
717 };
718
719 /*
720  * This array has two entries per compiled-in drawtype; of each pair,
721  * the first is for an 8-bit font and the second for 16-bit.
722  */
723 static const struct x11font_drawfuncs x11font_drawfuncs[2*DRAWTYPE_NTYPES] = {
724 #ifdef DRAW_TEXT_GDK
725     /* gdk, 8-bit */
726     {
727         x11font_width_8,
728         x11font_gdk_setup,
729         x11font_gdk_draw_8,
730     },
731     /* gdk, 16-bit */
732     {
733         x11font_width_16,
734         x11font_gdk_setup,
735         x11font_gdk_draw_16,
736     },
737 #endif
738 #ifdef DRAW_TEXT_CAIRO
739     /* cairo, 8-bit */
740     {
741         x11font_width_8,
742         x11font_cairo_setup,
743         x11font_cairo_draw_8,
744     },
745     /* [3] cairo, 16-bit */
746     {
747         x11font_width_16,
748         x11font_cairo_setup,
749         x11font_cairo_draw_16,
750     },
751 #endif
752 };
753
754 static void x11font_really_draw_text(const struct x11font_drawfuncs *dfns,
755                                      unifont_drawctx *ctx,
756                                      x11font_individual *xfi, int x, int y,
757                                      const void *string, int nchars,
758                                      int shadowoffset,
759                                      int fontvariable, int cellwidth)
760 {
761     int start = 0, step, nsteps, centre;
762
763     if (fontvariable) {
764         /*
765          * In a variable-pitch font, we draw one character at a
766          * time, and centre it in the character cell.
767          */
768         step = 1;
769         nsteps = nchars;
770         centre = TRUE;
771     } else {
772         /*
773          * In a fixed-pitch font, we can draw the whole lot in one go.
774          */
775         step = nchars;
776         nsteps = 1;
777         centre = FALSE;
778     }
779
780     dfns->setup(ctx, xfi);
781
782     while (nsteps-- > 0) {
783         int X = x;
784         if (centre)
785             X += (cellwidth - dfns->width(ctx, xfi, string, start, step)) / 2;
786
787         dfns->draw(ctx, xfi, X, y, string, start, step);
788         if (shadowoffset)
789             dfns->draw(ctx, xfi, X + shadowoffset, y, string, start, step);
790
791         x += cellwidth;
792         start += step;
793     }
794 }
795
796 static void x11font_draw_text(unifont_drawctx *ctx, unifont *font,
797                               int x, int y, const wchar_t *string, int len,
798                               int wide, int bold, int cellwidth)
799 {
800     struct x11font *xfont = (struct x11font *)font;
801     int sfid;
802     int shadowoffset = 0;
803     int mult = (wide ? 2 : 1);
804     int index = 2 * (int)ctx->type;
805
806     wide -= xfont->wide;
807     bold -= xfont->bold;
808
809     /*
810      * Decide which subfont we're using, and whether we have to
811      * use shadow bold.
812      */
813     if (xfont->shadowalways && bold) {
814         shadowoffset = xfont->shadowoffset;
815         bold = 0;
816     }
817     sfid = 2 * wide + bold;
818     if (!xfont->fonts[sfid].allocated)
819         x11_alloc_subfont(xfont, sfid);
820     if (bold && !xfont->fonts[sfid].xfs) {
821         bold = 0;
822         shadowoffset = xfont->shadowoffset;
823         sfid = 2 * wide + bold;
824         if (!xfont->fonts[sfid].allocated)
825             x11_alloc_subfont(xfont, sfid);
826     }
827
828     if (!xfont->fonts[sfid].xfs)
829         return;                        /* we've tried our best, but no luck */
830
831     if (xfont->sixteen_bit) {
832         /*
833          * This X font has 16-bit character indices, which means
834          * we can directly use our Unicode input string.
835          */
836         XChar2b *xcs;
837         int i;
838
839         xcs = snewn(len, XChar2b);
840         for (i = 0; i < len; i++) {
841             xcs[i].byte1 = string[i] >> 8;
842             xcs[i].byte2 = string[i];
843         }
844
845         x11font_really_draw_text(x11font_drawfuncs + index + 1, ctx,
846                                  &xfont->fonts[sfid], x, y,
847                                  xcs, len, shadowoffset,
848                                  xfont->variable, cellwidth * mult);
849         sfree(xcs);
850     } else {
851         /*
852          * This X font has 8-bit indices, so we must convert to the
853          * appropriate character set.
854          */
855         char *sbstring = snewn(len+1, char);
856         int sblen = wc_to_mb(xfont->real_charset, 0, string, len,
857                              sbstring, len+1, ".", NULL, NULL);
858         x11font_really_draw_text(x11font_drawfuncs + index + 0, ctx,
859                                  &xfont->fonts[sfid], x, y,
860                                  sbstring, sblen, shadowoffset,
861                                  xfont->variable, cellwidth * mult);
862         sfree(sbstring);
863     }
864 }
865
866 static void x11font_enum_fonts(GtkWidget *widget,
867                                fontsel_add_entry callback, void *callback_ctx)
868 {
869     char **fontnames;
870     char *tmp = NULL;
871     int nnames, i, max, tmpsize;
872
873     max = 32768;
874     while (1) {
875         fontnames = XListFonts(GDK_DISPLAY(), "*", max, &nnames);
876         if (nnames >= max) {
877             XFreeFontNames(fontnames);
878             max *= 2;
879         } else
880             break;
881     }
882
883     tmpsize = 0;
884
885     for (i = 0; i < nnames; i++) {
886         if (fontnames[i][0] == '-') {
887             /*
888              * Dismember an XLFD and convert it into the format
889              * we'll be using in the font selector.
890              */
891             char *components[14];
892             char *p, *font, *style, *stylekey, *charset;
893             int j, weightkey, slantkey, setwidthkey;
894             int thistmpsize, fontsize, flags;
895
896             thistmpsize = 4 * strlen(fontnames[i]) + 256;
897             if (tmpsize < thistmpsize) {
898                 tmpsize = thistmpsize;
899                 tmp = sresize(tmp, tmpsize, char);
900             }
901             strcpy(tmp, fontnames[i]);
902
903             p = tmp;
904             for (j = 0; j < 14; j++) {
905                 if (*p)
906                     *p++ = '\0';
907                 components[j] = p;
908                 while (*p && *p != '-')
909                     p++;
910             }
911             *p++ = '\0';
912
913             /*
914              * Font name is made up of fields 0 and 1, in reverse
915              * order with parentheses. (This is what the GTK 1.2 X
916              * font selector does, and it seems to come out
917              * looking reasonably sensible.)
918              */
919             font = p;
920             p += 1 + sprintf(p, "%s (%s)", components[1], components[0]);
921
922             /*
923              * Charset is made up of fields 12 and 13.
924              */
925             charset = p;
926             p += 1 + sprintf(p, "%s-%s", components[12], components[13]);
927
928             /*
929              * Style is a mixture of quite a lot of the fields,
930              * with some strange formatting.
931              */
932             style = p;
933             p += sprintf(p, "%s", components[2][0] ? components[2] :
934                          "regular");
935             if (!g_ascii_strcasecmp(components[3], "i"))
936                 p += sprintf(p, " italic");
937             else if (!g_ascii_strcasecmp(components[3], "o"))
938                 p += sprintf(p, " oblique");
939             else if (!g_ascii_strcasecmp(components[3], "ri"))
940                 p += sprintf(p, " reverse italic");
941             else if (!g_ascii_strcasecmp(components[3], "ro"))
942                 p += sprintf(p, " reverse oblique");
943             else if (!g_ascii_strcasecmp(components[3], "ot"))
944                 p += sprintf(p, " other-slant");
945             if (components[4][0] && g_ascii_strcasecmp(components[4], "normal"))
946                 p += sprintf(p, " %s", components[4]);
947             if (!g_ascii_strcasecmp(components[10], "m"))
948                 p += sprintf(p, " [M]");
949             if (!g_ascii_strcasecmp(components[10], "c"))
950                 p += sprintf(p, " [C]");
951             if (components[5][0])
952                 p += sprintf(p, " %s", components[5]);
953
954             /*
955              * Style key is the same stuff as above, but with a
956              * couple of transformations done on it to make it
957              * sort more sensibly.
958              */
959             p++;
960             stylekey = p;
961             if (!g_ascii_strcasecmp(components[2], "medium") ||
962                 !g_ascii_strcasecmp(components[2], "regular") ||
963                 !g_ascii_strcasecmp(components[2], "normal") ||
964                 !g_ascii_strcasecmp(components[2], "book"))
965                 weightkey = 0;
966             else if (!g_ascii_strncasecmp(components[2], "demi", 4) ||
967                      !g_ascii_strncasecmp(components[2], "semi", 4))
968                 weightkey = 1;
969             else
970                 weightkey = 2;
971             if (!g_ascii_strcasecmp(components[3], "r"))
972                 slantkey = 0;
973             else if (!g_ascii_strncasecmp(components[3], "r", 1))
974                 slantkey = 2;
975             else
976                 slantkey = 1;
977             if (!g_ascii_strcasecmp(components[4], "normal"))
978                 setwidthkey = 0;
979             else
980                 setwidthkey = 1;
981
982             p += sprintf(p, "%04d%04d%s%04d%04d%s%04d%04d%s%04d%s%04d%s",
983                          weightkey,
984                          (int)strlen(components[2]), components[2],
985                          slantkey,
986                          (int)strlen(components[3]), components[3],
987                          setwidthkey,
988                          (int)strlen(components[4]), components[4],
989                          (int)strlen(components[10]), components[10],
990                          (int)strlen(components[5]), components[5]);
991
992             assert(p - tmp < thistmpsize);
993
994             /*
995              * Size is in pixels, for our application, so we
996              * derive it directly from the pixel size field,
997              * number 6.
998              */
999             fontsize = atoi(components[6]);
1000
1001             /*
1002              * Flags: we need to know whether this is a monospaced
1003              * font, which we do by examining the spacing field
1004              * again.
1005              */
1006             flags = FONTFLAG_SERVERSIDE;
1007             if (!strchr("CcMm", components[10][0]))
1008                 flags |= FONTFLAG_NONMONOSPACED;
1009
1010             /*
1011              * Not sure why, but sometimes the X server will
1012              * deliver dummy font types in which fontsize comes
1013              * out as zero. Filter those out.
1014              */
1015             if (fontsize)
1016                 callback(callback_ctx, fontnames[i], font, charset,
1017                          style, stylekey, fontsize, flags, &x11font_vtable);
1018         } else {
1019             /*
1020              * This isn't an XLFD, so it must be an alias.
1021              * Transmit it with mostly null data.
1022              * 
1023              * It would be nice to work out if it's monospaced
1024              * here, but at the moment I can't see that being
1025              * anything but computationally hideous. Ah well.
1026              */
1027             callback(callback_ctx, fontnames[i], fontnames[i], NULL,
1028                      NULL, NULL, 0, FONTFLAG_SERVERALIAS, &x11font_vtable);
1029         }
1030     }
1031     XFreeFontNames(fontnames);
1032 }
1033
1034 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
1035                                        int *size, int *flags,
1036                                        int resolve_aliases)
1037 {
1038     /*
1039      * When given an X11 font name to try to make sense of for a
1040      * font selector, we must attempt to load it (to see if it
1041      * exists), and then canonify it by extracting its FONT
1042      * property, which should give its full XLFD even if what we
1043      * originally had was a wildcard.
1044      * 
1045      * However, we must carefully avoid canonifying font
1046      * _aliases_, unless specifically asked to, because the font
1047      * selector treats them as worthwhile in their own right.
1048      */
1049     XFontStruct *xfs;
1050     Display *disp = GDK_DISPLAY();
1051     Atom fontprop, fontprop2;
1052     unsigned long ret;
1053
1054     xfs = XLoadQueryFont(disp, name);
1055
1056     if (!xfs)
1057         return NULL;                   /* didn't make sense to us, sorry */
1058
1059     fontprop = XInternAtom(disp, "FONT", False);
1060
1061     if (XGetFontProperty(xfs, fontprop, &ret)) {
1062         char *newname = XGetAtomName(disp, (Atom)ret);
1063         if (newname) {
1064             unsigned long fsize = 12;
1065
1066             fontprop2 = XInternAtom(disp, "PIXEL_SIZE", False);
1067             if (XGetFontProperty(xfs, fontprop2, &fsize) && fsize > 0) {
1068                 *size = fsize;
1069                 XFreeFont(disp, xfs);
1070                 if (flags) {
1071                     if (name[0] == '-' || resolve_aliases)
1072                         *flags = FONTFLAG_SERVERSIDE;
1073                     else
1074                         *flags = FONTFLAG_SERVERALIAS;
1075                 }
1076                 return dupstr(name[0] == '-' || resolve_aliases ?
1077                               newname : name);
1078             }
1079         }
1080     }
1081
1082     XFreeFont(disp, xfs);
1083
1084     return NULL;                       /* something went wrong */
1085 }
1086
1087 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
1088                                     int size)
1089 {
1090     return NULL;                       /* shan't */
1091 }
1092
1093 #endif /* NOT_X_WINDOWS */
1094
1095 #if GTK_CHECK_VERSION(2,0,0)
1096
1097 /* ----------------------------------------------------------------------
1098  * Pango font implementation (for GTK 2 only).
1099  */
1100
1101 #if defined PANGO_PRE_1POINT4 && !defined PANGO_PRE_1POINT6
1102 #define PANGO_PRE_1POINT6              /* make life easier for pre-1.4 folk */
1103 #endif
1104
1105 static int pangofont_has_glyph(unifont *font, wchar_t glyph);
1106 static void pangofont_draw_text(unifont_drawctx *ctx, unifont *font,
1107                                 int x, int y, const wchar_t *string, int len,
1108                                 int wide, int bold, int cellwidth);
1109 static unifont *pangofont_create(GtkWidget *widget, const char *name,
1110                                  int wide, int bold,
1111                                  int shadowoffset, int shadowalways);
1112 static unifont *pangofont_create_fallback(GtkWidget *widget, int height,
1113                                           int wide, int bold,
1114                                           int shadowoffset, int shadowalways);
1115 static void pangofont_destroy(unifont *font);
1116 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback,
1117                                  void *callback_ctx);
1118 static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name,
1119                                          int *size, int *flags,
1120                                          int resolve_aliases);
1121 static char *pangofont_scale_fontname(GtkWidget *widget, const char *name,
1122                                       int size);
1123
1124 struct pangofont {
1125     struct unifont u;
1126     /*
1127      * Pango objects.
1128      */
1129     PangoFontDescription *desc;
1130     PangoFontset *fset;
1131     /*
1132      * The containing widget.
1133      */
1134     GtkWidget *widget;
1135     /*
1136      * Data passed in to unifont_create().
1137      */
1138     int bold, shadowoffset, shadowalways;
1139 };
1140
1141 static const struct unifont_vtable pangofont_vtable = {
1142     pangofont_create,
1143     pangofont_create_fallback,
1144     pangofont_destroy,
1145     pangofont_has_glyph,
1146     pangofont_draw_text,
1147     pangofont_enum_fonts,
1148     pangofont_canonify_fontname,
1149     pangofont_scale_fontname,
1150     "client",
1151 };
1152
1153 /*
1154  * This function is used to rigorously validate a
1155  * PangoFontDescription. Later versions of Pango have a nasty
1156  * habit of accepting _any_ old string as input to
1157  * pango_font_description_from_string and returning a font
1158  * description which can actually be used to display text, even if
1159  * they have to do it by falling back to their most default font.
1160  * This is doubtless helpful in some situations, but not here,
1161  * because we need to know if a Pango font string actually _makes
1162  * sense_ in order to fall back to treating it as an X font name
1163  * if it doesn't. So we check that the font family is actually one
1164  * supported by Pango.
1165  */
1166 static int pangofont_check_desc_makes_sense(PangoContext *ctx,
1167                                             PangoFontDescription *desc)
1168 {
1169 #ifndef PANGO_PRE_1POINT6
1170     PangoFontMap *map;
1171 #endif
1172     PangoFontFamily **families;
1173     int i, nfamilies, matched;
1174
1175     /*
1176      * Ask Pango for a list of font families, and iterate through
1177      * them to see if one of them matches the family in the
1178      * PangoFontDescription.
1179      */
1180 #ifndef PANGO_PRE_1POINT6
1181     map = pango_context_get_font_map(ctx);
1182     if (!map)
1183         return FALSE;
1184     pango_font_map_list_families(map, &families, &nfamilies);
1185 #else
1186     pango_context_list_families(ctx, &families, &nfamilies);
1187 #endif
1188
1189     matched = FALSE;
1190     for (i = 0; i < nfamilies; i++) {
1191         if (!g_ascii_strcasecmp(pango_font_family_get_name(families[i]),
1192                                 pango_font_description_get_family(desc))) {
1193             matched = TRUE;
1194             break;
1195         }
1196     }
1197     g_free(families);
1198
1199     return matched;
1200 }
1201
1202 static unifont *pangofont_create_internal(GtkWidget *widget,
1203                                           PangoContext *ctx,
1204                                           PangoFontDescription *desc,
1205                                           int wide, int bold,
1206                                           int shadowoffset, int shadowalways)
1207 {
1208     struct pangofont *pfont;
1209 #ifndef PANGO_PRE_1POINT6
1210     PangoFontMap *map;
1211 #endif
1212     PangoFontset *fset;
1213     PangoFontMetrics *metrics;
1214
1215 #ifndef PANGO_PRE_1POINT6
1216     map = pango_context_get_font_map(ctx);
1217     if (!map) {
1218         pango_font_description_free(desc);
1219         return NULL;
1220     }
1221     fset = pango_font_map_load_fontset(map, ctx, desc,
1222                                        pango_context_get_language(ctx));
1223 #else
1224     fset = pango_context_load_fontset(ctx, desc,
1225                                       pango_context_get_language(ctx));
1226 #endif
1227     if (!fset) {
1228         pango_font_description_free(desc);
1229         return NULL;
1230     }
1231     metrics = pango_fontset_get_metrics(fset);
1232     if (!metrics ||
1233         pango_font_metrics_get_approximate_digit_width(metrics) == 0) {
1234         pango_font_description_free(desc);
1235         g_object_unref(fset);
1236         return NULL;
1237     }
1238
1239     pfont = snew(struct pangofont);
1240     pfont->u.vt = &pangofont_vtable;
1241     pfont->u.width =
1242         PANGO_PIXELS(pango_font_metrics_get_approximate_digit_width(metrics));
1243     pfont->u.ascent = PANGO_PIXELS(pango_font_metrics_get_ascent(metrics));
1244     pfont->u.descent = PANGO_PIXELS(pango_font_metrics_get_descent(metrics));
1245     pfont->u.height = pfont->u.ascent + pfont->u.descent;
1246     pfont->u.want_fallback = FALSE;
1247 #ifdef DRAW_TEXT_CAIRO
1248     pfont->u.preferred_drawtype = DRAWTYPE_CAIRO;
1249 #elif defined DRAW_TEXT_GDK
1250     pfont->u.preferred_drawtype = DRAWTYPE_GDK;
1251 #else
1252 #error No drawtype available at all
1253 #endif
1254     /* The Pango API is hardwired to UTF-8 */
1255     pfont->u.public_charset = CS_UTF8;
1256     pfont->desc = desc;
1257     pfont->fset = fset;
1258     pfont->widget = widget;
1259     pfont->bold = bold;
1260     pfont->shadowoffset = shadowoffset;
1261     pfont->shadowalways = shadowalways;
1262
1263     pango_font_metrics_unref(metrics);
1264
1265     return (unifont *)pfont;
1266 }
1267
1268 static unifont *pangofont_create(GtkWidget *widget, const char *name,
1269                                  int wide, int bold,
1270                                  int shadowoffset, int shadowalways)
1271 {
1272     PangoContext *ctx;
1273     PangoFontDescription *desc;
1274
1275     desc = pango_font_description_from_string(name);
1276     if (!desc)
1277         return NULL;
1278     ctx = gtk_widget_get_pango_context(widget);
1279     if (!ctx) {
1280         pango_font_description_free(desc);
1281         return NULL;
1282     }
1283     if (!pangofont_check_desc_makes_sense(ctx, desc)) {
1284         pango_font_description_free(desc);
1285         return NULL;
1286     }
1287     return pangofont_create_internal(widget, ctx, desc, wide, bold,
1288                                      shadowoffset, shadowalways);
1289 }
1290
1291 static unifont *pangofont_create_fallback(GtkWidget *widget, int height,
1292                                           int wide, int bold,
1293                                           int shadowoffset, int shadowalways)
1294 {
1295     PangoContext *ctx;
1296     PangoFontDescription *desc;
1297
1298     desc = pango_font_description_from_string("Monospace");
1299     if (!desc)
1300         return NULL;
1301     ctx = gtk_widget_get_pango_context(widget);
1302     if (!ctx) {
1303         pango_font_description_free(desc);
1304         return NULL;
1305     }
1306     pango_font_description_set_absolute_size(desc, height * PANGO_SCALE);
1307     return pangofont_create_internal(widget, ctx, desc, wide, bold,
1308                                      shadowoffset, shadowalways);
1309 }
1310
1311 static void pangofont_destroy(unifont *font)
1312 {
1313     struct pangofont *pfont = (struct pangofont *)font;
1314     pango_font_description_free(pfont->desc);
1315     g_object_unref(pfont->fset);
1316     sfree(font);
1317 }
1318
1319 static int pangofont_has_glyph(unifont *font, wchar_t glyph)
1320 {
1321     /* Pango implements font fallback, so assume it has everything */
1322     return TRUE;
1323 }
1324
1325 #ifdef DRAW_TEXT_GDK
1326 static void pango_gdk_draw_layout(unifont_drawctx *ctx,
1327                                   gint x, gint y, PangoLayout *layout)
1328 {
1329     gdk_draw_layout(ctx->u.gdk.target, ctx->u.gdk.gc, x, y, layout);
1330 }
1331 #endif
1332
1333 #ifdef DRAW_TEXT_CAIRO
1334 static void pango_cairo_draw_layout(unifont_drawctx *ctx,
1335                                     gint x, gint y, PangoLayout *layout)
1336 {
1337     cairo_move_to(ctx->u.cairo.cr, x, y);
1338     pango_cairo_show_layout(ctx->u.cairo.cr, layout);
1339 }
1340 #endif
1341
1342 static void pangofont_draw_text(unifont_drawctx *ctx, unifont *font,
1343                                 int x, int y, const wchar_t *string, int len,
1344                                 int wide, int bold, int cellwidth)
1345 {
1346     struct pangofont *pfont = (struct pangofont *)font;
1347     PangoLayout *layout;
1348     PangoRectangle rect;
1349     char *utfstring, *utfptr;
1350     int utflen;
1351     int shadowbold = FALSE;
1352     void (*draw_layout)(unifont_drawctx *ctx,
1353                         gint x, gint y, PangoLayout *layout) = NULL;
1354
1355 #ifdef DRAW_TEXT_GDK
1356     if (ctx->type == DRAWTYPE_GDK) {
1357         draw_layout = pango_gdk_draw_layout;
1358     }
1359 #endif
1360 #ifdef DRAW_TEXT_CAIRO
1361     if (ctx->type == DRAWTYPE_CAIRO) {
1362         draw_layout = pango_cairo_draw_layout;
1363     }
1364 #endif
1365
1366     if (wide)
1367         cellwidth *= 2;
1368
1369     y -= pfont->u.ascent;
1370
1371     layout = pango_layout_new(gtk_widget_get_pango_context(pfont->widget));
1372     pango_layout_set_font_description(layout, pfont->desc);
1373     if (bold > pfont->bold) {
1374         if (pfont->shadowalways)
1375             shadowbold = TRUE;
1376         else {
1377             PangoFontDescription *desc2 =
1378                 pango_font_description_copy_static(pfont->desc);
1379             pango_font_description_set_weight(desc2, PANGO_WEIGHT_BOLD);
1380             pango_layout_set_font_description(layout, desc2);
1381         }
1382     }
1383
1384     /*
1385      * Pango always expects UTF-8, so convert the input wide character
1386      * string to UTF-8.
1387      */
1388     utfstring = snewn(len*6+1, char); /* UTF-8 has max 6 bytes/char */
1389     utflen = wc_to_mb(CS_UTF8, 0, string, len,
1390                       utfstring, len*6+1, ".", NULL, NULL);
1391
1392     utfptr = utfstring;
1393     while (utflen > 0) {
1394         int clen, n;
1395
1396         /*
1397          * We want to display every character from this string in
1398          * the centre of its own character cell. In the worst case,
1399          * this requires a separate text-drawing call for each
1400          * character; but in the common case where the font is
1401          * properly fixed-width, we can draw many characters in one
1402          * go which is much faster.
1403          *
1404          * This still isn't really ideal. If you look at what
1405          * happens in the X protocol as a result of all of this, you
1406          * find - naturally enough - that each call to
1407          * gdk_draw_layout() generates a separate set of X RENDER
1408          * operations involving creating a picture, setting a clip
1409          * rectangle, doing some drawing and undoing the whole lot.
1410          * In an ideal world, we should _always_ be able to turn the
1411          * contents of this loop into a single RenderCompositeGlyphs
1412          * operation which internally specifies inter-character
1413          * deltas to get the spacing right, which would give us full
1414          * speed _even_ in the worst case of a non-fixed-width font.
1415          * However, Pango's architecture and documentation are so
1416          * unhelpful that I have no idea how if at all to persuade
1417          * them to do that.
1418          */
1419
1420         /*
1421          * Start by extracting a single UTF-8 character from the
1422          * string.
1423          */
1424         clen = 1;
1425         while (clen < utflen &&
1426                (unsigned char)utfptr[clen] >= 0x80 &&
1427                (unsigned char)utfptr[clen] < 0xC0)
1428             clen++;
1429         n = 1;
1430
1431         /*
1432          * If it's a right-to-left character, we must display it on
1433          * its own, to stop Pango helpfully re-reversing our already
1434          * reversed text.
1435          */
1436         if (!is_rtl(string[0])) {
1437
1438             /*
1439              * See if that character has the width we expect.
1440              */
1441             pango_layout_set_text(layout, utfptr, clen);
1442             pango_layout_get_pixel_extents(layout, NULL, &rect);
1443
1444             if (rect.width == cellwidth) {
1445                 /*
1446                  * Try extracting more characters, for as long as they
1447                  * stay well-behaved.
1448                  */
1449                 while (clen < utflen) {
1450                     int oldclen = clen;
1451                     clen++;                    /* skip UTF-8 introducer byte */
1452                     while (clen < utflen &&
1453                            (unsigned char)utfptr[clen] >= 0x80 &&
1454                            (unsigned char)utfptr[clen] < 0xC0)
1455                         clen++;
1456                     n++;
1457                     pango_layout_set_text(layout, utfptr, clen);
1458                     pango_layout_get_pixel_extents(layout, NULL, &rect);
1459                     if (rect.width != n * cellwidth) {
1460                         clen = oldclen;
1461                         n--;
1462                         break;
1463                     }
1464                 }
1465             }
1466         }
1467
1468         pango_layout_set_text(layout, utfptr, clen);
1469         pango_layout_get_pixel_extents(layout, NULL, &rect);
1470         
1471         draw_layout(ctx,
1472                     x + (n*cellwidth - rect.width)/2,
1473                     y + (pfont->u.height - rect.height)/2, layout);
1474         if (shadowbold)
1475             draw_layout(ctx,
1476                         x + (n*cellwidth - rect.width)/2 + pfont->shadowoffset,
1477                         y + (pfont->u.height - rect.height)/2, layout);
1478
1479         utflen -= clen;
1480         utfptr += clen;
1481         string += n;
1482         x += n * cellwidth;
1483     }
1484
1485     sfree(utfstring);
1486
1487     g_object_unref(layout);
1488 }
1489
1490 /*
1491  * Dummy size value to be used when converting a
1492  * PangoFontDescription of a scalable font to a string for
1493  * internal use.
1494  */
1495 #define PANGO_DUMMY_SIZE 12
1496
1497 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback,
1498                                  void *callback_ctx)
1499 {
1500     PangoContext *ctx;
1501 #ifndef PANGO_PRE_1POINT6
1502     PangoFontMap *map;
1503 #endif
1504     PangoFontFamily **families;
1505     int i, nfamilies;
1506
1507     ctx = gtk_widget_get_pango_context(widget);
1508     if (!ctx)
1509         return;
1510
1511     /*
1512      * Ask Pango for a list of font families, and iterate through
1513      * them.
1514      */
1515 #ifndef PANGO_PRE_1POINT6
1516     map = pango_context_get_font_map(ctx);
1517     if (!map)
1518         return;
1519     pango_font_map_list_families(map, &families, &nfamilies);
1520 #else
1521     pango_context_list_families(ctx, &families, &nfamilies);
1522 #endif
1523     for (i = 0; i < nfamilies; i++) {
1524         PangoFontFamily *family = families[i];
1525         const char *familyname;
1526         int flags;
1527         PangoFontFace **faces;
1528         int j, nfaces;
1529
1530         /*
1531          * Set up our flags for this font family, and get the name
1532          * string.
1533          */
1534         flags = FONTFLAG_CLIENTSIDE;
1535 #ifndef PANGO_PRE_1POINT4
1536         /*
1537          * In very early versions of Pango, we can't tell
1538          * monospaced fonts from non-monospaced.
1539          */
1540         if (!pango_font_family_is_monospace(family))
1541             flags |= FONTFLAG_NONMONOSPACED;
1542 #endif
1543         familyname = pango_font_family_get_name(family);
1544
1545         /*
1546          * Go through the available font faces in this family.
1547          */
1548         pango_font_family_list_faces(family, &faces, &nfaces);
1549         for (j = 0; j < nfaces; j++) {
1550             PangoFontFace *face = faces[j];
1551             PangoFontDescription *desc;
1552             const char *facename;
1553             int *sizes;
1554             int k, nsizes, dummysize;
1555
1556             /*
1557              * Get the face name string.
1558              */
1559             facename = pango_font_face_get_face_name(face);
1560
1561             /*
1562              * Set up a font description with what we've got so
1563              * far. We'll fill in the size field manually and then
1564              * call pango_font_description_to_string() to give the
1565              * full real name of the specific font.
1566              */
1567             desc = pango_font_face_describe(face);
1568
1569             /*
1570              * See if this font has a list of specific sizes.
1571              */
1572 #ifndef PANGO_PRE_1POINT4
1573             pango_font_face_list_sizes(face, &sizes, &nsizes);
1574 #else
1575             /*
1576              * In early versions of Pango, that call wasn't
1577              * supported; we just have to assume everything is
1578              * scalable.
1579              */
1580             sizes = NULL;
1581 #endif
1582             if (!sizes) {
1583                 /*
1584                  * Write a single entry with a dummy size.
1585                  */
1586                 dummysize = PANGO_DUMMY_SIZE * PANGO_SCALE;
1587                 sizes = &dummysize;
1588                 nsizes = 1;
1589             }
1590
1591             /*
1592              * If so, go through them one by one.
1593              */
1594             for (k = 0; k < nsizes; k++) {
1595                 char *fullname;
1596                 char stylekey[128];
1597
1598                 pango_font_description_set_size(desc, sizes[k]);
1599
1600                 fullname = pango_font_description_to_string(desc);
1601
1602                 /*
1603                  * Construct the sorting key for font styles.
1604                  */
1605                 {
1606                     char *p = stylekey;
1607                     int n;
1608
1609                     n = pango_font_description_get_weight(desc);
1610                     /* Weight: normal, then lighter, then bolder */
1611                     if (n <= PANGO_WEIGHT_NORMAL)
1612                         n = PANGO_WEIGHT_NORMAL - n;
1613                     p += sprintf(p, "%4d", n);
1614
1615                     n = pango_font_description_get_style(desc);
1616                     p += sprintf(p, " %2d", n);
1617
1618                     n = pango_font_description_get_stretch(desc);
1619                     /* Stretch: closer to normal sorts earlier */
1620                     n = 2 * abs(PANGO_STRETCH_NORMAL - n) +
1621                         (n < PANGO_STRETCH_NORMAL);
1622                     p += sprintf(p, " %2d", n);
1623
1624                     n = pango_font_description_get_variant(desc);
1625                     p += sprintf(p, " %2d", n);
1626                     
1627                 }
1628
1629                 /*
1630                  * Got everything. Hand off to the callback.
1631                  * (The charset string is NULL, because only
1632                  * server-side X fonts use it.)
1633                  */
1634                 callback(callback_ctx, fullname, familyname, NULL, facename,
1635                          stylekey,
1636                          (sizes == &dummysize ? 0 : PANGO_PIXELS(sizes[k])),
1637                          flags, &pangofont_vtable);
1638
1639                 g_free(fullname);
1640             }
1641             if (sizes != &dummysize)
1642                 g_free(sizes);
1643
1644             pango_font_description_free(desc);
1645         }
1646         g_free(faces);
1647     }
1648     g_free(families);
1649 }
1650
1651 static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name,
1652                                          int *size, int *flags,
1653                                          int resolve_aliases)
1654 {
1655     /*
1656      * When given a Pango font name to try to make sense of for a
1657      * font selector, we must normalise it to PANGO_DUMMY_SIZE and
1658      * extract its original size (in pixels) into the `size' field.
1659      */
1660     PangoContext *ctx;
1661 #ifndef PANGO_PRE_1POINT6
1662     PangoFontMap *map;
1663 #endif
1664     PangoFontDescription *desc;
1665     PangoFontset *fset;
1666     PangoFontMetrics *metrics;
1667     char *newname, *retname;
1668
1669     desc = pango_font_description_from_string(name);
1670     if (!desc)
1671         return NULL;
1672     ctx = gtk_widget_get_pango_context(widget);
1673     if (!ctx) {
1674         pango_font_description_free(desc);
1675         return NULL;
1676     }
1677     if (!pangofont_check_desc_makes_sense(ctx, desc)) {
1678         pango_font_description_free(desc);
1679         return NULL;
1680     }
1681 #ifndef PANGO_PRE_1POINT6
1682     map = pango_context_get_font_map(ctx);
1683     if (!map) {
1684         pango_font_description_free(desc);
1685         return NULL;
1686     }
1687     fset = pango_font_map_load_fontset(map, ctx, desc,
1688                                        pango_context_get_language(ctx));
1689 #else
1690     fset = pango_context_load_fontset(ctx, desc,
1691                                       pango_context_get_language(ctx));
1692 #endif
1693     if (!fset) {
1694         pango_font_description_free(desc);
1695         return NULL;
1696     }
1697     metrics = pango_fontset_get_metrics(fset);
1698     if (!metrics ||
1699         pango_font_metrics_get_approximate_digit_width(metrics) == 0) {
1700         pango_font_description_free(desc);
1701         g_object_unref(fset);
1702         return NULL;
1703     }
1704
1705     *size = PANGO_PIXELS(pango_font_description_get_size(desc));
1706     *flags = FONTFLAG_CLIENTSIDE;
1707     pango_font_description_set_size(desc, PANGO_DUMMY_SIZE * PANGO_SCALE);
1708     newname = pango_font_description_to_string(desc);
1709     retname = dupstr(newname);
1710     g_free(newname);
1711
1712     pango_font_metrics_unref(metrics);
1713     pango_font_description_free(desc);
1714     g_object_unref(fset);
1715
1716     return retname;
1717 }
1718
1719 static char *pangofont_scale_fontname(GtkWidget *widget, const char *name,
1720                                       int size)
1721 {
1722     PangoFontDescription *desc;
1723     char *newname, *retname;
1724
1725     desc = pango_font_description_from_string(name);
1726     if (!desc)
1727         return NULL;
1728     pango_font_description_set_size(desc, size * PANGO_SCALE);
1729     newname = pango_font_description_to_string(desc);
1730     retname = dupstr(newname);
1731     g_free(newname);
1732     pango_font_description_free(desc);
1733
1734     return retname;
1735 }
1736
1737 #endif /* GTK_CHECK_VERSION(2,0,0) */
1738
1739 /* ----------------------------------------------------------------------
1740  * Outermost functions which do the vtable dispatch.
1741  */
1742
1743 /*
1744  * Complete list of font-type subclasses. Listed in preference
1745  * order for unifont_create(). (That is, in the extremely unlikely
1746  * event that the same font name is valid as both a Pango and an
1747  * X11 font, it will be interpreted as the former in the absence
1748  * of an explicit type-disambiguating prefix.)
1749  *
1750  * The 'multifont' subclass is omitted here, as discussed above.
1751  */
1752 static const struct unifont_vtable *unifont_types[] = {
1753 #if GTK_CHECK_VERSION(2,0,0)
1754     &pangofont_vtable,
1755 #endif
1756 #ifndef NOT_X_WINDOWS
1757     &x11font_vtable,
1758 #endif
1759 };
1760
1761 /*
1762  * Function which takes a font name and processes the optional
1763  * scheme prefix. Returns the tail of the font name suitable for
1764  * passing to individual font scheme functions, and also provides
1765  * a subrange of the unifont_types[] array above.
1766  * 
1767  * The return values `start' and `end' denote a half-open interval
1768  * in unifont_types[]; that is, the correct way to iterate over
1769  * them is
1770  * 
1771  *   for (i = start; i < end; i++) {...}
1772  */
1773 static const char *unifont_do_prefix(const char *name, int *start, int *end)
1774 {
1775     int colonpos = strcspn(name, ":");
1776     int i;
1777
1778     if (name[colonpos]) {
1779         /*
1780          * There's a colon prefix on the font name. Use it to work
1781          * out which subclass to use.
1782          */
1783         for (i = 0; i < lenof(unifont_types); i++) {
1784             if (strlen(unifont_types[i]->prefix) == colonpos &&
1785                 !strncmp(unifont_types[i]->prefix, name, colonpos)) {
1786                 *start = i;
1787                 *end = i+1;
1788                 return name + colonpos + 1;
1789             }
1790         }
1791         /*
1792          * None matched, so return an empty scheme list to prevent
1793          * any scheme from being called at all.
1794          */
1795         *start = *end = 0;
1796         return name + colonpos + 1;
1797     } else {
1798         /*
1799          * No colon prefix, so just use all the subclasses.
1800          */
1801         *start = 0;
1802         *end = lenof(unifont_types);
1803         return name;
1804     }
1805 }
1806
1807 unifont *unifont_create(GtkWidget *widget, const char *name, int wide,
1808                         int bold, int shadowoffset, int shadowalways)
1809 {
1810     int i, start, end;
1811
1812     name = unifont_do_prefix(name, &start, &end);
1813
1814     for (i = start; i < end; i++) {
1815         unifont *ret = unifont_types[i]->create(widget, name, wide, bold,
1816                                                 shadowoffset, shadowalways);
1817         if (ret)
1818             return ret;
1819     }
1820     return NULL;                       /* font not found in any scheme */
1821 }
1822
1823 void unifont_destroy(unifont *font)
1824 {
1825     font->vt->destroy(font);
1826 }
1827
1828 void unifont_draw_text(unifont_drawctx *ctx, unifont *font,
1829                        int x, int y, const wchar_t *string, int len,
1830                        int wide, int bold, int cellwidth)
1831 {
1832     font->vt->draw_text(ctx, font, x, y, string, len, wide, bold, cellwidth);
1833 }
1834
1835 /* ----------------------------------------------------------------------
1836  * Multiple-font wrapper. This is a type of unifont which encapsulates
1837  * up to two other unifonts, permitting missing glyphs in the main
1838  * font to be filled in by a fallback font.
1839  *
1840  * This is a type of unifont just like the previous two, but it has a
1841  * separate constructor which is manually called by the client, so it
1842  * doesn't appear in the list of available font types enumerated by
1843  * unifont_create. This means it's not used by unifontsel either, so
1844  * it doesn't need to support any methods except draw_text and
1845  * destroy.
1846  */
1847
1848 static void multifont_draw_text(unifont_drawctx *ctx, unifont *font,
1849                                 int x, int y, const wchar_t *string, int len,
1850                                 int wide, int bold, int cellwidth);
1851 static void multifont_destroy(unifont *font);
1852
1853 struct multifont {
1854     struct unifont u;
1855     unifont *main;
1856     unifont *fallback;
1857 };
1858
1859 static const struct unifont_vtable multifont_vtable = {
1860     NULL,                             /* creation is done specially */
1861     NULL,
1862     multifont_destroy,
1863     NULL,
1864     multifont_draw_text,
1865     NULL,
1866     NULL,
1867     NULL,
1868     "client",
1869 };
1870
1871 unifont *multifont_create(GtkWidget *widget, const char *name,
1872                           int wide, int bold,
1873                           int shadowoffset, int shadowalways)
1874 {
1875     int i;
1876     unifont *font, *fallback;
1877     struct multifont *mfont;
1878
1879     font = unifont_create(widget, name, wide, bold,
1880                           shadowoffset, shadowalways);
1881     if (!font)
1882         return NULL;
1883
1884     fallback = NULL;
1885     if (font->want_fallback) {
1886         for (i = 0; i < lenof(unifont_types); i++) {
1887             if (unifont_types[i]->create_fallback) {
1888                 fallback = unifont_types[i]->create_fallback
1889                     (widget, font->height, wide, bold,
1890                      shadowoffset, shadowalways);
1891                 if (fallback)
1892                     break;
1893             }
1894         }
1895     }
1896
1897     /*
1898      * Construct our multifont. Public members are all copied from the
1899      * primary font we're wrapping.
1900      */
1901     mfont = snew(struct multifont);
1902     mfont->u.vt = &multifont_vtable;
1903     mfont->u.width = font->width;
1904     mfont->u.ascent = font->ascent;
1905     mfont->u.descent = font->descent;
1906     mfont->u.height = font->height;
1907     mfont->u.public_charset = font->public_charset;
1908     mfont->u.want_fallback = FALSE; /* shouldn't be needed, but just in case */
1909     mfont->u.preferred_drawtype = font->preferred_drawtype;
1910     mfont->main = font;
1911     mfont->fallback = fallback;
1912
1913     return (unifont *)mfont;
1914 }
1915
1916 static void multifont_destroy(unifont *font)
1917 {
1918     struct multifont *mfont = (struct multifont *)font;
1919     unifont_destroy(mfont->main);
1920     if (mfont->fallback)
1921         unifont_destroy(mfont->fallback);
1922     sfree(font);
1923 }
1924
1925 static void multifont_draw_text(unifont_drawctx *ctx, unifont *font, int x,
1926                                 int y, const wchar_t *string, int len,
1927                                 int wide, int bold, int cellwidth)
1928 {
1929     struct multifont *mfont = (struct multifont *)font;
1930     unifont *f;
1931     int ok, i;
1932
1933     while (len > 0) {
1934         /*
1935          * Find a maximal sequence of characters which are, or are
1936          * not, supported by our main font.
1937          */
1938         ok = mfont->main->vt->has_glyph(mfont->main, string[0]);
1939         for (i = 1;
1940              i < len &&
1941              !mfont->main->vt->has_glyph(mfont->main, string[i]) == !ok;
1942              i++);
1943
1944         /*
1945          * Now display it.
1946          */
1947         f = ok ? mfont->main : mfont->fallback;
1948         if (f)
1949             unifont_draw_text(ctx, f, x, y, string, i, wide, bold, cellwidth);
1950         string += i;
1951         len -= i;
1952         x += i * cellwidth;
1953     }
1954 }
1955
1956 #if GTK_CHECK_VERSION(2,0,0)
1957
1958 /* ----------------------------------------------------------------------
1959  * Implementation of a unified font selector. Used on GTK 2 only;
1960  * for GTK 1 we still use the standard font selector.
1961  */
1962
1963 typedef struct fontinfo fontinfo;
1964
1965 typedef struct unifontsel_internal {
1966     /* This must be the structure's first element, for cross-casting */
1967     unifontsel u;
1968     GtkListStore *family_model, *style_model, *size_model;
1969     GtkWidget *family_list, *style_list, *size_entry, *size_list;
1970     GtkWidget *filter_buttons[4];
1971     int n_filter_buttons;
1972     GtkWidget *preview_area;
1973     GdkPixmap *preview_pixmap;
1974     int preview_width, preview_height;
1975     GdkColor preview_fg, preview_bg;
1976     int filter_flags;
1977     tree234 *fonts_by_realname, *fonts_by_selorder;
1978     fontinfo *selected;
1979     int selsize, intendedsize;
1980     int inhibit_response;  /* inhibit callbacks when we change GUI controls */
1981 } unifontsel_internal;
1982
1983 /*
1984  * The structure held in the tree234s. All the string members are
1985  * part of the same allocated area, so don't need freeing
1986  * separately.
1987  */
1988 struct fontinfo {
1989     char *realname;
1990     char *family, *charset, *style, *stylekey;
1991     int size, flags;
1992     /*
1993      * Fallback sorting key, to permit multiple identical entries
1994      * to exist in the selorder tree.
1995      */
1996     int index;
1997     /*
1998      * Indices mapping fontinfo structures to indices in the list
1999      * boxes. sizeindex is irrelevant if the font is scalable
2000      * (size==0).
2001      */
2002     int familyindex, styleindex, sizeindex;
2003     /*
2004      * The class of font.
2005      */
2006     const struct unifont_vtable *fontclass;
2007 };
2008
2009 struct fontinfo_realname_find {
2010     const char *realname;
2011     int flags;
2012 };
2013
2014 static int strnullcasecmp(const char *a, const char *b)
2015 {
2016     int i;
2017
2018     /*
2019      * If exactly one of the inputs is NULL, it compares before
2020      * the other one.
2021      */
2022     if ((i = (!b) - (!a)) != 0)
2023         return i;
2024
2025     /*
2026      * NULL compares equal.
2027      */
2028     if (!a)
2029         return 0;
2030
2031     /*
2032      * Otherwise, ordinary strcasecmp.
2033      */
2034     return g_ascii_strcasecmp(a, b);
2035 }
2036
2037 static int fontinfo_realname_compare(void *av, void *bv)
2038 {
2039     fontinfo *a = (fontinfo *)av;
2040     fontinfo *b = (fontinfo *)bv;
2041     int i;
2042
2043     if ((i = strnullcasecmp(a->realname, b->realname)) != 0)
2044         return i;
2045     if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK))
2046         return ((a->flags & FONTFLAG_SORT_MASK) <
2047                 (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1);
2048     return 0;
2049 }
2050
2051 static int fontinfo_realname_find(void *av, void *bv)
2052 {
2053     struct fontinfo_realname_find *a = (struct fontinfo_realname_find *)av;
2054     fontinfo *b = (fontinfo *)bv;
2055     int i;
2056
2057     if ((i = strnullcasecmp(a->realname, b->realname)) != 0)
2058         return i;
2059     if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK))
2060         return ((a->flags & FONTFLAG_SORT_MASK) <
2061                 (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1);
2062     return 0;
2063 }
2064
2065 static int fontinfo_selorder_compare(void *av, void *bv)
2066 {
2067     fontinfo *a = (fontinfo *)av;
2068     fontinfo *b = (fontinfo *)bv;
2069     int i;
2070     if ((i = strnullcasecmp(a->family, b->family)) != 0)
2071         return i;
2072     /*
2073      * Font class comes immediately after family, so that fonts
2074      * from different classes with the same family
2075      */
2076     if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK))
2077         return ((a->flags & FONTFLAG_SORT_MASK) <
2078                 (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1);
2079     if ((i = strnullcasecmp(a->charset, b->charset)) != 0)
2080         return i;
2081     if ((i = strnullcasecmp(a->stylekey, b->stylekey)) != 0)
2082         return i;
2083     if ((i = strnullcasecmp(a->style, b->style)) != 0)
2084         return i;
2085     if (a->size != b->size)
2086         return (a->size < b->size ? -1 : +1);
2087     if (a->index != b->index)
2088         return (a->index < b->index ? -1 : +1);
2089     return 0;
2090 }
2091
2092 static void unifontsel_deselect(unifontsel_internal *fs)
2093 {
2094     fs->selected = NULL;
2095     gtk_list_store_clear(fs->style_model);
2096     gtk_list_store_clear(fs->size_model);
2097     gtk_widget_set_sensitive(fs->u.ok_button, FALSE);
2098     gtk_widget_set_sensitive(fs->size_entry, FALSE);
2099 }
2100
2101 static void unifontsel_setup_familylist(unifontsel_internal *fs)
2102 {
2103     GtkTreeIter iter;
2104     int i, listindex, minpos = -1, maxpos = -1;
2105     char *currfamily = NULL;
2106     int currflags = -1;
2107     fontinfo *info;
2108
2109     gtk_list_store_clear(fs->family_model);
2110     listindex = 0;
2111
2112     /*
2113      * Search through the font tree for anything matching our
2114      * current filter criteria. When we find one, add its font
2115      * name to the list box.
2116      */
2117     for (i = 0 ;; i++) {
2118         info = (fontinfo *)index234(fs->fonts_by_selorder, i);
2119         /*
2120          * info may be NULL if we've just run off the end of the
2121          * tree. We must still do a processing pass in that
2122          * situation, in case we had an unfinished font record in
2123          * progress.
2124          */
2125         if (info && (info->flags &~ fs->filter_flags)) {
2126             info->familyindex = -1;
2127             continue;                  /* we're filtering out this font */
2128         }
2129         if (!info || strnullcasecmp(currfamily, info->family) ||
2130             currflags != (info->flags & FONTFLAG_SORT_MASK)) {
2131             /*
2132              * We've either finished a family, or started a new
2133              * one, or both.
2134              */
2135             if (currfamily) {
2136                 gtk_list_store_append(fs->family_model, &iter);
2137                 gtk_list_store_set(fs->family_model, &iter,
2138                                    0, currfamily, 1, minpos, 2, maxpos+1, -1);
2139                 listindex++;
2140             }
2141             if (info) {
2142                 minpos = i;
2143                 currfamily = info->family;
2144                 currflags = info->flags & FONTFLAG_SORT_MASK;
2145             }
2146         }
2147         if (!info)
2148             break;                     /* now we're done */
2149         info->familyindex = listindex;
2150         maxpos = i;
2151     }
2152
2153     /*
2154      * If we've just filtered out the previously selected font,
2155      * deselect it thoroughly.
2156      */
2157     if (fs->selected && fs->selected->familyindex < 0)
2158         unifontsel_deselect(fs);
2159 }
2160
2161 static void unifontsel_setup_stylelist(unifontsel_internal *fs,
2162                                        int start, int end)
2163 {
2164     GtkTreeIter iter;
2165     int i, listindex, minpos = -1, maxpos = -1, started = FALSE;
2166     char *currcs = NULL, *currstyle = NULL;
2167     fontinfo *info;
2168
2169     gtk_list_store_clear(fs->style_model);
2170     listindex = 0;
2171     started = FALSE;
2172
2173     /*
2174      * Search through the font tree for anything matching our
2175      * current filter criteria. When we find one, add its charset
2176      * and/or style name to the list box.
2177      */
2178     for (i = start; i <= end; i++) {
2179         if (i == end)
2180             info = NULL;
2181         else
2182             info = (fontinfo *)index234(fs->fonts_by_selorder, i);
2183         /*
2184          * info may be NULL if we've just run off the end of the
2185          * relevant data. We must still do a processing pass in
2186          * that situation, in case we had an unfinished font
2187          * record in progress.
2188          */
2189         if (info && (info->flags &~ fs->filter_flags)) {
2190             info->styleindex = -1;
2191             continue;                  /* we're filtering out this font */
2192         }
2193         if (!info || !started || strnullcasecmp(currcs, info->charset) ||
2194              strnullcasecmp(currstyle, info->style)) {
2195             /*
2196              * We've either finished a style/charset, or started a
2197              * new one, or both.
2198              */
2199             started = TRUE;
2200             if (currstyle) {
2201                 gtk_list_store_append(fs->style_model, &iter);
2202                 gtk_list_store_set(fs->style_model, &iter,
2203                                    0, currstyle, 1, minpos, 2, maxpos+1,
2204                                    3, TRUE, -1);
2205                 listindex++;
2206             }
2207             if (info) {
2208                 minpos = i;
2209                 if (info->charset && strnullcasecmp(currcs, info->charset)) {
2210                     gtk_list_store_append(fs->style_model, &iter);
2211                     gtk_list_store_set(fs->style_model, &iter,
2212                                        0, info->charset, 1, -1, 2, -1,
2213                                        3, FALSE, -1);
2214                     listindex++;
2215                 }
2216                 currcs = info->charset;
2217                 currstyle = info->style;
2218             }
2219         }
2220         if (!info)
2221             break;                     /* now we're done */
2222         info->styleindex = listindex;
2223         maxpos = i;
2224     }
2225 }
2226
2227 static const int unifontsel_default_sizes[] = { 10, 12, 14, 16, 20, 24, 32 };
2228
2229 static void unifontsel_setup_sizelist(unifontsel_internal *fs,
2230                                       int start, int end)
2231 {
2232     GtkTreeIter iter;
2233     int i, listindex;
2234     char sizetext[40];
2235     fontinfo *info;
2236
2237     gtk_list_store_clear(fs->size_model);
2238     listindex = 0;
2239
2240     /*
2241      * Search through the font tree for anything matching our
2242      * current filter criteria. When we find one, add its font
2243      * name to the list box.
2244      */
2245     for (i = start; i < end; i++) {
2246         info = (fontinfo *)index234(fs->fonts_by_selorder, i);
2247         if (info->flags &~ fs->filter_flags) {
2248             info->sizeindex = -1;
2249             continue;                  /* we're filtering out this font */
2250         }
2251         if (info->size) {
2252             sprintf(sizetext, "%d", info->size);
2253             info->sizeindex = listindex;
2254             gtk_list_store_append(fs->size_model, &iter);
2255             gtk_list_store_set(fs->size_model, &iter,
2256                                0, sizetext, 1, i, 2, info->size, -1);
2257             listindex++;
2258         } else {
2259             int j;
2260
2261             assert(i == start);
2262             assert(i+1 == end);
2263
2264             for (j = 0; j < lenof(unifontsel_default_sizes); j++) {
2265                 sprintf(sizetext, "%d", unifontsel_default_sizes[j]);
2266                 gtk_list_store_append(fs->size_model, &iter);
2267                 gtk_list_store_set(fs->size_model, &iter, 0, sizetext, 1, i,
2268                                    2, unifontsel_default_sizes[j], -1);
2269                 listindex++;
2270             }
2271         }
2272     }
2273 }
2274
2275 static void unifontsel_set_filter_buttons(unifontsel_internal *fs)
2276 {
2277     int i;
2278
2279     for (i = 0; i < fs->n_filter_buttons; i++) {
2280         int flagbit = GPOINTER_TO_INT(g_object_get_data
2281                                       (G_OBJECT(fs->filter_buttons[i]),
2282                                        "user-data"));
2283         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fs->filter_buttons[i]),
2284                                      !!(fs->filter_flags & flagbit));
2285     }
2286 }
2287
2288 static void unifontsel_draw_preview_text_inner(unifont_drawctx *dctx,
2289                                                unifontsel_internal *fs)
2290 {
2291     unifont *font;
2292     char *sizename = NULL;
2293     fontinfo *info = fs->selected;
2294
2295     if (info) {
2296         sizename = info->fontclass->scale_fontname
2297             (GTK_WIDGET(fs->u.window), info->realname, fs->selsize);
2298         font = info->fontclass->create(GTK_WIDGET(fs->u.window),
2299                                        sizename ? sizename : info->realname,
2300                                        FALSE, FALSE, 0, 0);
2301     } else
2302         font = NULL;
2303
2304     if (font) {
2305 #ifdef DRAW_TEXT_GDK
2306         if (dctx->type == DRAWTYPE_GDK) {
2307             gdk_gc_set_foreground(dctx->u.gdk.gc, &fs->preview_bg);
2308             gdk_draw_rectangle(dctx->u.gdk.target, dctx->u.gdk.gc, 1, 0, 0,
2309                                fs->preview_width, fs->preview_height);
2310             gdk_gc_set_foreground(dctx->u.gdk.gc, &fs->preview_fg);
2311         }
2312 #endif
2313 #ifdef DRAW_TEXT_CAIRO
2314         if (dctx->type == DRAWTYPE_CAIRO) {
2315             cairo_set_source_rgb(dctx->u.cairo.cr,
2316                                  fs->preview_bg.red / 65535.0,
2317                                  fs->preview_bg.green / 65535.0,
2318                                  fs->preview_bg.blue / 65535.0);
2319             cairo_paint(dctx->u.cairo.cr);
2320             cairo_set_source_rgb(dctx->u.cairo.cr,
2321                                  fs->preview_fg.red / 65535.0,
2322                                  fs->preview_fg.green / 65535.0,
2323                                  fs->preview_fg.blue / 65535.0);
2324         }
2325 #endif
2326
2327         /*
2328          * The pangram used here is rather carefully
2329          * constructed: it contains a sequence of very narrow
2330          * letters (`jil') and a pair of adjacent very wide
2331          * letters (`wm').
2332          *
2333          * If the user selects a proportional font, it will be
2334          * coerced into fixed-width character cells when used
2335          * in the actual terminal window. We therefore display
2336          * it the same way in the preview pane, so as to show
2337          * it the way it will actually be displayed - and we
2338          * deliberately pick a pangram which will show the
2339          * resulting miskerning at its worst.
2340          *
2341          * We aren't trying to sell people these fonts; we're
2342          * trying to let them make an informed choice. Better
2343          * that they find out the problems with using
2344          * proportional fonts in terminal windows here than
2345          * that they go to the effort of selecting their font
2346          * and _then_ realise it was a mistake.
2347          */
2348         info->fontclass->draw_text(dctx, font,
2349                                    0, font->ascent,
2350                                    L"bankrupt jilted showmen quiz convex fogey",
2351                                    41, FALSE, FALSE, font->width);
2352         info->fontclass->draw_text(dctx, font,
2353                                    0, font->ascent + font->height,
2354                                    L"BANKRUPT JILTED SHOWMEN QUIZ CONVEX FOGEY",
2355                                    41, FALSE, FALSE, font->width);
2356         /*
2357          * The ordering of punctuation here is also selected
2358          * with some specific aims in mind. I put ` and '
2359          * together because some software (and people) still
2360          * use them as matched quotes no matter what Unicode
2361          * might say on the matter, so people can quickly
2362          * check whether they look silly in a candidate font.
2363          * The sequence #_@ is there to let people judge the
2364          * suitability of the underscore as an effectively
2365          * alphabetic character (since that's how it's often
2366          * used in practice, at least by programmers).
2367          */
2368         info->fontclass->draw_text(dctx, font,
2369                                    0, font->ascent + font->height * 2,
2370                                    L"0123456789!?,.:;<>()[]{}\\/`'\"+*-=~#_@|%&^$",
2371                                    42, FALSE, FALSE, font->width);
2372
2373         info->fontclass->destroy(font);
2374     }
2375
2376     sfree(sizename);
2377 }
2378
2379 static void unifontsel_draw_preview_text(unifontsel_internal *fs)
2380 {
2381     unifont_drawctx dctx;
2382
2383     if (!fs->preview_pixmap)
2384         return;
2385
2386     dctx.type = DRAWTYPE_DEFAULT;
2387 #ifdef DRAW_TEXT_GDK
2388     if (dctx.type == DRAWTYPE_GDK) {
2389         dctx.u.gdk.target = fs->preview_pixmap;
2390         dctx.u.gdk.gc = gdk_gc_new(fs->preview_pixmap);
2391     }
2392 #endif
2393 #ifdef DRAW_TEXT_CAIRO
2394     if (dctx.type == DRAWTYPE_CAIRO) {
2395         dctx.u.cairo.widget = GTK_WIDGET(fs->preview_area);
2396         dctx.u.cairo.cr = gdk_cairo_create(fs->preview_pixmap);
2397     }
2398 #endif
2399
2400     unifontsel_draw_preview_text_inner(&dctx, fs);
2401
2402 #ifdef DRAW_TEXT_GDK
2403     if (dctx.type == DRAWTYPE_GDK) {
2404         gdk_gc_unref(dctx.u.gdk.gc);
2405     }
2406 #endif
2407 #ifdef DRAW_TEXT_CAIRO
2408     if (dctx.type == DRAWTYPE_CAIRO) {
2409         cairo_destroy(dctx.u.cairo.cr);
2410     }
2411 #endif
2412
2413     gdk_window_invalidate_rect(gtk_widget_get_window(fs->preview_area),
2414                                NULL, FALSE);
2415 }
2416
2417 static void unifontsel_select_font(unifontsel_internal *fs,
2418                                    fontinfo *info, int size, int leftlist,
2419                                    int size_is_explicit)
2420 {
2421     int index;
2422     int minval, maxval;
2423     GtkTreePath *treepath;
2424     GtkTreeIter iter;
2425
2426     fs->inhibit_response = TRUE;
2427
2428     fs->selected = info;
2429     fs->selsize = size;
2430     if (size_is_explicit)
2431         fs->intendedsize = size;
2432
2433     gtk_widget_set_sensitive(fs->u.ok_button, TRUE);
2434
2435     /*
2436      * Find the index of this fontinfo in the selorder list. 
2437      */
2438     index = -1;
2439     findpos234(fs->fonts_by_selorder, info, NULL, &index);
2440     assert(index >= 0);
2441
2442     /*
2443      * Adjust the font selector flags and redo the font family
2444      * list box, if necessary.
2445      */
2446     if (leftlist <= 0 &&
2447         (fs->filter_flags | info->flags) != fs->filter_flags) {
2448         fs->filter_flags |= info->flags;
2449         unifontsel_set_filter_buttons(fs);
2450         unifontsel_setup_familylist(fs);
2451     }
2452
2453     /*
2454      * Find the appropriate family name and select it in the list.
2455      */
2456     assert(info->familyindex >= 0);
2457     treepath = gtk_tree_path_new_from_indices(info->familyindex, -1);
2458     gtk_tree_selection_select_path
2459         (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->family_list)),
2460          treepath);
2461     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->family_list),
2462                                  treepath, NULL, FALSE, 0.0, 0.0);
2463     gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, treepath);
2464     gtk_tree_path_free(treepath);
2465
2466     /*
2467      * Now set up the font style list.
2468      */
2469     gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter,
2470                        1, &minval, 2, &maxval, -1);
2471     if (leftlist <= 1)
2472         unifontsel_setup_stylelist(fs, minval, maxval);
2473
2474     /*
2475      * Find the appropriate style name and select it in the list.
2476      */
2477     if (info->style) {
2478         assert(info->styleindex >= 0);
2479         treepath = gtk_tree_path_new_from_indices(info->styleindex, -1);
2480         gtk_tree_selection_select_path
2481             (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->style_list)),
2482              treepath);
2483         gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->style_list),
2484                                      treepath, NULL, FALSE, 0.0, 0.0);
2485         gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->style_model),
2486                                 &iter, treepath);
2487         gtk_tree_path_free(treepath);
2488
2489         /*
2490          * And set up the size list.
2491          */
2492         gtk_tree_model_get(GTK_TREE_MODEL(fs->style_model), &iter,
2493                            1, &minval, 2, &maxval, -1);
2494         if (leftlist <= 2)
2495             unifontsel_setup_sizelist(fs, minval, maxval);
2496
2497         /*
2498          * Find the appropriate size, and select it in the list.
2499          */
2500         if (info->size) {
2501             assert(info->sizeindex >= 0);
2502             treepath = gtk_tree_path_new_from_indices(info->sizeindex, -1);
2503             gtk_tree_selection_select_path
2504                 (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->size_list)),
2505                  treepath);
2506             gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
2507                                          treepath, NULL, FALSE, 0.0, 0.0);
2508             gtk_tree_path_free(treepath);
2509             size = info->size;
2510         } else {
2511             int j;
2512             for (j = 0; j < lenof(unifontsel_default_sizes); j++)
2513                 if (unifontsel_default_sizes[j] == size) {
2514                     treepath = gtk_tree_path_new_from_indices(j, -1);
2515                     gtk_tree_view_set_cursor(GTK_TREE_VIEW(fs->size_list),
2516                                              treepath, NULL, FALSE);
2517                     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
2518                                                  treepath, NULL, FALSE, 0.0,
2519                                                  0.0);
2520                     gtk_tree_path_free(treepath);
2521                 }
2522         }
2523
2524         /*
2525          * And set up the font size text entry box.
2526          */
2527         {
2528             char sizetext[40];
2529             sprintf(sizetext, "%d", size);
2530             gtk_entry_set_text(GTK_ENTRY(fs->size_entry), sizetext);
2531         }
2532     } else {
2533         if (leftlist <= 2)
2534             unifontsel_setup_sizelist(fs, 0, 0);
2535         gtk_entry_set_text(GTK_ENTRY(fs->size_entry), "");
2536     }
2537
2538     /*
2539      * Grey out the font size edit box if we're not using a
2540      * scalable font.
2541      */
2542     gtk_editable_set_editable(GTK_EDITABLE(fs->size_entry),
2543                               fs->selected->size == 0);
2544     gtk_widget_set_sensitive(fs->size_entry, fs->selected->size == 0);
2545
2546     unifontsel_draw_preview_text(fs);
2547
2548     fs->inhibit_response = FALSE;
2549 }
2550
2551 static void unifontsel_button_toggled(GtkToggleButton *tb, gpointer data)
2552 {
2553     unifontsel_internal *fs = (unifontsel_internal *)data;
2554     int newstate = gtk_toggle_button_get_active(tb);
2555     int newflags;
2556     int flagbit = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(tb),
2557                                                     "user-data"));
2558
2559     if (newstate)
2560         newflags = fs->filter_flags | flagbit;
2561     else
2562         newflags = fs->filter_flags & ~flagbit;
2563
2564     if (fs->filter_flags != newflags) {
2565         fs->filter_flags = newflags;
2566         unifontsel_setup_familylist(fs);
2567     }
2568 }
2569
2570 static void unifontsel_add_entry(void *ctx, const char *realfontname,
2571                                  const char *family, const char *charset,
2572                                  const char *style, const char *stylekey,
2573                                  int size, int flags,
2574                                  const struct unifont_vtable *fontclass)
2575 {
2576     unifontsel_internal *fs = (unifontsel_internal *)ctx;
2577     fontinfo *info;
2578     int totalsize;
2579     char *p;
2580
2581     totalsize = sizeof(fontinfo) + strlen(realfontname) +
2582         (family ? strlen(family) : 0) + (charset ? strlen(charset) : 0) +
2583         (style ? strlen(style) : 0) + (stylekey ? strlen(stylekey) : 0) + 10;
2584     info = (fontinfo *)smalloc(totalsize);
2585     info->fontclass = fontclass;
2586     p = (char *)info + sizeof(fontinfo);
2587     info->realname = p;
2588     strcpy(p, realfontname);
2589     p += 1+strlen(p);
2590     if (family) {
2591         info->family = p;
2592         strcpy(p, family);
2593         p += 1+strlen(p);
2594     } else
2595         info->family = NULL;
2596     if (charset) {
2597         info->charset = p;
2598         strcpy(p, charset);
2599         p += 1+strlen(p);
2600     } else
2601         info->charset = NULL;
2602     if (style) {
2603         info->style = p;
2604         strcpy(p, style);
2605         p += 1+strlen(p);
2606     } else
2607         info->style = NULL;
2608     if (stylekey) {
2609         info->stylekey = p;
2610         strcpy(p, stylekey);
2611         p += 1+strlen(p);
2612     } else
2613         info->stylekey = NULL;
2614     assert(p - (char *)info <= totalsize);
2615     info->size = size;
2616     info->flags = flags;
2617     info->index = count234(fs->fonts_by_selorder);
2618
2619     /*
2620      * It's just conceivable that a misbehaving font enumerator
2621      * might tell us about the same font real name more than once,
2622      * in which case we should silently drop the new one.
2623      */
2624     if (add234(fs->fonts_by_realname, info) != info) {
2625         sfree(info);
2626         return;
2627     }
2628     /*
2629      * However, we should never get a duplicate key in the
2630      * selorder tree, because the index field carefully
2631      * disambiguates otherwise identical records.
2632      */
2633     add234(fs->fonts_by_selorder, info);
2634 }
2635
2636 static fontinfo *update_for_intended_size(unifontsel_internal *fs,
2637                                           fontinfo *info)
2638 {
2639     fontinfo info2, *below, *above;
2640     int pos;
2641
2642     /*
2643      * Copy the info structure. This doesn't copy its dynamic
2644      * string fields, but that's unimportant because all we're
2645      * going to do is to adjust the size field and use it in one
2646      * tree search.
2647      */
2648     info2 = *info;
2649     info2.size = fs->intendedsize;
2650
2651     /*
2652      * Search in the tree to find the fontinfo structure which
2653      * best approximates the size the user last requested.
2654      */
2655     below = findrelpos234(fs->fonts_by_selorder, &info2, NULL,
2656                           REL234_LE, &pos);
2657     if (!below)
2658         pos = -1;
2659     above = index234(fs->fonts_by_selorder, pos+1);
2660
2661     /*
2662      * See if we've found it exactly, which is an easy special
2663      * case. If we have, it'll be in `below' and not `above',
2664      * because we did a REL234_LE rather than REL234_LT search.
2665      */
2666     if (below && !fontinfo_selorder_compare(&info2, below))
2667         return below;
2668
2669     /*
2670      * Now we've either found two suitable fonts, one smaller and
2671      * one larger, or we're at one or other extreme end of the
2672      * scale. Find out which, by NULLing out either of below and
2673      * above if it differs from this one in any respect but size
2674      * (and the disambiguating index field). Bear in mind, also,
2675      * that either one might _already_ be NULL if we're at the
2676      * extreme ends of the font list.
2677      */
2678     if (below) {
2679         info2.size = below->size;
2680         info2.index = below->index;
2681         if (fontinfo_selorder_compare(&info2, below))
2682             below = NULL;
2683     }
2684     if (above) {
2685         info2.size = above->size;
2686         info2.index = above->index;
2687         if (fontinfo_selorder_compare(&info2, above))
2688             above = NULL;
2689     }
2690
2691     /*
2692      * Now return whichever of above and below is non-NULL, if
2693      * that's unambiguous.
2694      */
2695     if (!above)
2696         return below;
2697     if (!below)
2698         return above;
2699
2700     /*
2701      * And now we really do have to make a choice about whether to
2702      * round up or down. We'll do it by rounding to nearest,
2703      * breaking ties by rounding up.
2704      */
2705     if (above->size - fs->intendedsize <= fs->intendedsize - below->size)
2706         return above;
2707     else
2708         return below;
2709 }
2710
2711 static void family_changed(GtkTreeSelection *treeselection, gpointer data)
2712 {
2713     unifontsel_internal *fs = (unifontsel_internal *)data;
2714     GtkTreeModel *treemodel;
2715     GtkTreeIter treeiter;
2716     int minval;
2717     fontinfo *info;
2718
2719     if (fs->inhibit_response)          /* we made this change ourselves */
2720         return;
2721
2722     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
2723         return;
2724
2725     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
2726     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
2727     info = update_for_intended_size(fs, info);
2728     if (!info)
2729         return; /* _shouldn't_ happen unless font list is completely funted */
2730     if (!info->size)
2731         fs->selsize = fs->intendedsize;   /* font is scalable */
2732     unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize,
2733                            1, FALSE);
2734 }
2735
2736 static void style_changed(GtkTreeSelection *treeselection, gpointer data)
2737 {
2738     unifontsel_internal *fs = (unifontsel_internal *)data;
2739     GtkTreeModel *treemodel;
2740     GtkTreeIter treeiter;
2741     int minval;
2742     fontinfo *info;
2743
2744     if (fs->inhibit_response)          /* we made this change ourselves */
2745         return;
2746
2747     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
2748         return;
2749
2750     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
2751     if (minval < 0)
2752         return;                    /* somehow a charset heading got clicked */
2753     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
2754     info = update_for_intended_size(fs, info);
2755     if (!info)
2756         return; /* _shouldn't_ happen unless font list is completely funted */
2757     if (!info->size)
2758         fs->selsize = fs->intendedsize;   /* font is scalable */
2759     unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize,
2760                            2, FALSE);
2761 }
2762
2763 static void size_changed(GtkTreeSelection *treeselection, gpointer data)
2764 {
2765     unifontsel_internal *fs = (unifontsel_internal *)data;
2766     GtkTreeModel *treemodel;
2767     GtkTreeIter treeiter;
2768     int minval, size;
2769     fontinfo *info;
2770
2771     if (fs->inhibit_response)          /* we made this change ourselves */
2772         return;
2773
2774     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
2775         return;
2776
2777     gtk_tree_model_get(treemodel, &treeiter, 1, &minval, 2, &size, -1);
2778     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
2779     unifontsel_select_font(fs, info, info->size ? info->size : size, 3, TRUE);
2780 }
2781
2782 static void size_entry_changed(GtkEditable *ed, gpointer data)
2783 {
2784     unifontsel_internal *fs = (unifontsel_internal *)data;
2785     const char *text;
2786     int size;
2787
2788     if (fs->inhibit_response)          /* we made this change ourselves */
2789         return;
2790
2791     text = gtk_entry_get_text(GTK_ENTRY(ed));
2792     size = atoi(text);
2793
2794     if (size > 0) {
2795         assert(fs->selected->size == 0);
2796         unifontsel_select_font(fs, fs->selected, size, 3, TRUE);
2797     }
2798 }
2799
2800 static void alias_resolve(GtkTreeView *treeview, GtkTreePath *path,
2801                           GtkTreeViewColumn *column, gpointer data)
2802 {
2803     unifontsel_internal *fs = (unifontsel_internal *)data;
2804     GtkTreeIter iter;
2805     int minval, newsize;
2806     fontinfo *info, *newinfo;
2807     char *newname;
2808
2809     if (fs->inhibit_response)          /* we made this change ourselves */
2810         return;
2811
2812     gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, path);
2813     gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter, 1,&minval, -1);
2814     info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
2815     if (info) {
2816         int flags;
2817         struct fontinfo_realname_find f;
2818
2819         newname = info->fontclass->canonify_fontname
2820             (GTK_WIDGET(fs->u.window), info->realname, &newsize, &flags, TRUE);
2821
2822         f.realname = newname;
2823         f.flags = flags;
2824         newinfo = find234(fs->fonts_by_realname, &f, fontinfo_realname_find);
2825
2826         sfree(newname);
2827         if (!newinfo)
2828             return;                    /* font name not in our index */
2829         if (newinfo == info)
2830             return;   /* didn't change under canonification => not an alias */
2831         unifontsel_select_font(fs, newinfo,
2832                                newinfo->size ? newinfo->size : newsize,
2833                                1, TRUE);
2834     }
2835 }
2836
2837 static gint unifontsel_expose_area(GtkWidget *widget, GdkEventExpose *event,
2838                                    gpointer data)
2839 {
2840     unifontsel_internal *fs = (unifontsel_internal *)data;
2841
2842     if (fs->preview_pixmap) {
2843         gdk_draw_pixmap(gtk_widget_get_window(widget),
2844                         (gtk_widget_get_style(widget)->fg_gc
2845                          [gtk_widget_get_state(widget)]),
2846                         fs->preview_pixmap,
2847                         event->area.x, event->area.y,
2848                         event->area.x, event->area.y,
2849                         event->area.width, event->area.height);
2850     }
2851     return TRUE;
2852 }
2853
2854 static gint unifontsel_configure_area(GtkWidget *widget,
2855                                       GdkEventConfigure *event, gpointer data)
2856 {
2857     unifontsel_internal *fs = (unifontsel_internal *)data;
2858     int ox, oy, nx, ny, x, y;
2859
2860     /*
2861      * Enlarge the pixmap, but never shrink it.
2862      */
2863     ox = fs->preview_width;
2864     oy = fs->preview_height;
2865     x = event->width;
2866     y = event->height;
2867     if (x > ox || y > oy) {
2868         if (fs->preview_pixmap)
2869             gdk_pixmap_unref(fs->preview_pixmap);
2870         
2871         nx = (x > ox ? x : ox);
2872         ny = (y > oy ? y : oy);
2873         fs->preview_pixmap = gdk_pixmap_new(gtk_widget_get_window(widget),
2874                                             nx, ny, -1);
2875         fs->preview_width = nx;
2876         fs->preview_height = ny;
2877
2878         unifontsel_draw_preview_text(fs);
2879     }
2880
2881     gdk_window_invalidate_rect(gtk_widget_get_window(widget), NULL, FALSE);
2882
2883     return TRUE;
2884 }
2885
2886 unifontsel *unifontsel_new(const char *wintitle)
2887 {
2888     unifontsel_internal *fs = snew(unifontsel_internal);
2889     GtkWidget *table, *label, *w, *ww, *scroll;
2890     GtkListStore *model;
2891     GtkTreeViewColumn *column;
2892     int lists_height, preview_height, font_width, style_width, size_width;
2893     int i;
2894
2895     fs->inhibit_response = FALSE;
2896     fs->selected = NULL;
2897
2898     {
2899         /*
2900          * Invent some magic size constants.
2901          */
2902         GtkRequisition req;
2903         label = gtk_label_new("Quite Long Font Name (Foundry)");
2904         gtk_widget_size_request(label, &req);
2905         font_width = req.width;
2906         lists_height = 14 * req.height;
2907         preview_height = 5 * req.height;
2908         gtk_label_set_text(GTK_LABEL(label), "Italic Extra Condensed");
2909         gtk_widget_size_request(label, &req);
2910         style_width = req.width;
2911         gtk_label_set_text(GTK_LABEL(label), "48000");
2912         gtk_widget_size_request(label, &req);
2913         size_width = req.width;
2914         g_object_ref_sink(G_OBJECT(label));
2915 #if GTK_CHECK_VERSION(2,10,0)
2916         g_object_unref(label);
2917 #endif
2918     }
2919
2920     /*
2921      * Create the dialog box and initialise the user-visible
2922      * fields in the returned structure.
2923      */
2924     fs->u.user_data = NULL;
2925     fs->u.window = GTK_WINDOW(gtk_dialog_new());
2926     gtk_window_set_title(fs->u.window, wintitle);
2927     fs->u.cancel_button = gtk_dialog_add_button
2928         (GTK_DIALOG(fs->u.window), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
2929     fs->u.ok_button = gtk_dialog_add_button
2930         (GTK_DIALOG(fs->u.window), GTK_STOCK_OK, GTK_RESPONSE_OK);
2931     gtk_widget_grab_default(fs->u.ok_button);
2932
2933     /*
2934      * Now set up the internal fields, including in particular all
2935      * the controls that actually allow the user to select fonts.
2936      */
2937     table = gtk_table_new(8, 3, FALSE);
2938     gtk_widget_show(table);
2939     gtk_table_set_col_spacings(GTK_TABLE(table), 8);
2940 #if GTK_CHECK_VERSION(2,4,0)
2941     /* GtkAlignment seems to be the simplest way to put padding round things */
2942     w = gtk_alignment_new(0, 0, 1, 1);
2943     gtk_alignment_set_padding(GTK_ALIGNMENT(w), 8, 8, 8, 8);
2944     gtk_container_add(GTK_CONTAINER(w), table);
2945     gtk_widget_show(w);
2946 #else
2947     w = table;
2948 #endif
2949     gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area
2950                                (GTK_DIALOG(fs->u.window))),
2951                        w, TRUE, TRUE, 0);
2952
2953     label = gtk_label_new_with_mnemonic("_Font:");
2954     gtk_widget_show(label);
2955     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2956     gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_FILL, 0, 0, 0);
2957
2958     /*
2959      * The Font list box displays only a string, but additionally
2960      * stores two integers which give the limits within the
2961      * tree234 of the font entries covered by this list entry.
2962      */
2963     model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
2964     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2965     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2966     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2967     gtk_widget_show(w);
2968     column = gtk_tree_view_column_new_with_attributes
2969         ("Font", gtk_cell_renderer_text_new(),
2970          "text", 0, (char *)NULL);
2971     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2972     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2973     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2974                      "changed", G_CALLBACK(family_changed), fs);
2975     g_signal_connect(G_OBJECT(w), "row-activated",
2976                      G_CALLBACK(alias_resolve), fs);
2977
2978     scroll = gtk_scrolled_window_new(NULL, NULL);
2979     gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
2980                                         GTK_SHADOW_IN);
2981     gtk_container_add(GTK_CONTAINER(scroll), w);
2982     gtk_widget_show(scroll);
2983     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2984                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2985     gtk_widget_set_size_request(scroll, font_width, lists_height);
2986     gtk_table_attach(GTK_TABLE(table), scroll, 0, 1, 1, 3, GTK_FILL,
2987                      GTK_EXPAND | GTK_FILL, 0, 0);
2988     fs->family_model = model;
2989     fs->family_list = w;
2990
2991     label = gtk_label_new_with_mnemonic("_Style:");
2992     gtk_widget_show(label);
2993     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2994     gtk_table_attach(GTK_TABLE(table), label, 1, 2, 0, 1, GTK_FILL, 0, 0, 0);
2995
2996     /*
2997      * The Style list box can contain insensitive elements
2998      * (character set headings for server-side fonts), so we add
2999      * an extra column to the list store to hold that information.
3000      */
3001     model = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT,
3002                                G_TYPE_BOOLEAN);
3003     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
3004     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
3005     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
3006     gtk_widget_show(w);
3007     column = gtk_tree_view_column_new_with_attributes
3008         ("Style", gtk_cell_renderer_text_new(),
3009          "text", 0, "sensitive", 3, (char *)NULL);
3010     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
3011     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
3012     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
3013                      "changed", G_CALLBACK(style_changed), fs);
3014
3015     scroll = gtk_scrolled_window_new(NULL, NULL);
3016     gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
3017                                         GTK_SHADOW_IN);
3018     gtk_container_add(GTK_CONTAINER(scroll), w);
3019     gtk_widget_show(scroll);
3020     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
3021                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
3022     gtk_widget_set_size_request(scroll, style_width, lists_height);
3023     gtk_table_attach(GTK_TABLE(table), scroll, 1, 2, 1, 3, GTK_FILL,
3024                      GTK_EXPAND | GTK_FILL, 0, 0);
3025     fs->style_model = model;
3026     fs->style_list = w;
3027
3028     label = gtk_label_new_with_mnemonic("Si_ze:");
3029     gtk_widget_show(label);
3030     gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
3031     gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, GTK_FILL, 0, 0, 0);
3032
3033     /*
3034      * The Size label attaches primarily to a text input box so
3035      * that the user can select a size of their choice. The list
3036      * of available sizes is secondary.
3037      */
3038     fs->size_entry = w = gtk_entry_new();
3039     gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
3040     gtk_widget_set_size_request(w, size_width, -1);
3041     gtk_widget_show(w);
3042     gtk_table_attach(GTK_TABLE(table), w, 2, 3, 1, 2, GTK_FILL, 0, 0, 0);
3043     g_signal_connect(G_OBJECT(w), "changed", G_CALLBACK(size_entry_changed),
3044                      fs);
3045
3046     model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
3047     w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
3048     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
3049     gtk_widget_show(w);
3050     column = gtk_tree_view_column_new_with_attributes
3051         ("Size", gtk_cell_renderer_text_new(),
3052          "text", 0, (char *)NULL);
3053     gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
3054     gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
3055     g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
3056                      "changed", G_CALLBACK(size_changed), fs);
3057
3058     scroll = gtk_scrolled_window_new(NULL, NULL);
3059     gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
3060                                         GTK_SHADOW_IN);
3061     gtk_container_add(GTK_CONTAINER(scroll), w);
3062     gtk_widget_show(scroll);
3063     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
3064                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
3065     gtk_table_attach(GTK_TABLE(table), scroll, 2, 3, 2, 3, GTK_FILL,
3066                      GTK_EXPAND | GTK_FILL, 0, 0);
3067     fs->size_model = model;
3068     fs->size_list = w;
3069
3070     /*
3071      * Preview widget.
3072      */
3073     fs->preview_area = gtk_drawing_area_new();
3074     fs->preview_pixmap = NULL;
3075     fs->preview_width = 0;
3076     fs->preview_height = 0;
3077     fs->preview_fg.pixel = fs->preview_bg.pixel = 0;
3078     fs->preview_fg.red = fs->preview_fg.green = fs->preview_fg.blue = 0x0000;
3079     fs->preview_bg.red = fs->preview_bg.green = fs->preview_bg.blue = 0xFFFF;
3080     gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_fg,
3081                              FALSE, FALSE);
3082     gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_bg,
3083                              FALSE, FALSE);
3084     g_signal_connect(G_OBJECT(fs->preview_area), "expose_event",
3085                      G_CALLBACK(unifontsel_expose_area), fs);
3086     g_signal_connect(G_OBJECT(fs->preview_area), "configure_event",
3087                      G_CALLBACK(unifontsel_configure_area), fs);
3088     gtk_widget_set_size_request(fs->preview_area, 1, preview_height);
3089     gtk_widget_show(fs->preview_area);
3090     ww = fs->preview_area;
3091     w = gtk_frame_new(NULL);
3092     gtk_container_add(GTK_CONTAINER(w), ww);
3093     gtk_widget_show(w);
3094 #if GTK_CHECK_VERSION(2,4,0)
3095     ww = w;
3096     /* GtkAlignment seems to be the simplest way to put padding round things */
3097     w = gtk_alignment_new(0, 0, 1, 1);
3098     gtk_alignment_set_padding(GTK_ALIGNMENT(w), 8, 8, 8, 8);
3099     gtk_container_add(GTK_CONTAINER(w), ww);
3100     gtk_widget_show(w);
3101 #endif
3102     ww = w;
3103     w = gtk_frame_new("Preview of font");
3104     gtk_container_add(GTK_CONTAINER(w), ww);
3105     gtk_widget_show(w);
3106     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 3, 4,
3107                      GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 8);
3108
3109     /*
3110      * We only provide the checkboxes for client- and server-side
3111      * fonts if we have the X11 back end available, because that's the
3112      * only situation in which more than one class of font is
3113      * available anyway.
3114      */
3115     fs->n_filter_buttons = 0;
3116 #ifndef NOT_X_WINDOWS
3117     w = gtk_check_button_new_with_label("Show client-side fonts");
3118     g_object_set_data(G_OBJECT(w), "user-data",
3119                       GINT_TO_POINTER(FONTFLAG_CLIENTSIDE));
3120     g_signal_connect(G_OBJECT(w), "toggled",
3121                      G_CALLBACK(unifontsel_button_toggled), fs);
3122     gtk_widget_show(w);
3123     fs->filter_buttons[fs->n_filter_buttons++] = w;
3124     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 4, 5, GTK_FILL, 0, 0, 0);
3125     w = gtk_check_button_new_with_label("Show server-side fonts");
3126     g_object_set_data(G_OBJECT(w), "user-data",
3127                       GINT_TO_POINTER(FONTFLAG_SERVERSIDE));
3128     g_signal_connect(G_OBJECT(w), "toggled",
3129                      G_CALLBACK(unifontsel_button_toggled), fs);
3130     gtk_widget_show(w);
3131     fs->filter_buttons[fs->n_filter_buttons++] = w;
3132     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 5, 6, GTK_FILL, 0, 0, 0);
3133     w = gtk_check_button_new_with_label("Show server-side font aliases");
3134     g_object_set_data(G_OBJECT(w), "user-data",
3135                       GINT_TO_POINTER(FONTFLAG_SERVERALIAS));
3136     g_signal_connect(G_OBJECT(w), "toggled",
3137                      G_CALLBACK(unifontsel_button_toggled), fs);
3138     gtk_widget_show(w);
3139     fs->filter_buttons[fs->n_filter_buttons++] = w;
3140     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 6, 7, GTK_FILL, 0, 0, 0);
3141 #endif
3142     w = gtk_check_button_new_with_label("Show non-monospaced fonts");
3143     g_object_set_data(G_OBJECT(w), "user-data",
3144                       GINT_TO_POINTER(FONTFLAG_NONMONOSPACED));
3145     g_signal_connect(G_OBJECT(w), "toggled",
3146                      G_CALLBACK(unifontsel_button_toggled), fs);
3147     gtk_widget_show(w);
3148     fs->filter_buttons[fs->n_filter_buttons++] = w;
3149     gtk_table_attach(GTK_TABLE(table), w, 0, 3, 7, 8, GTK_FILL, 0, 0, 0);
3150
3151     assert(fs->n_filter_buttons <= lenof(fs->filter_buttons));
3152     fs->filter_flags = FONTFLAG_CLIENTSIDE | FONTFLAG_SERVERSIDE |
3153         FONTFLAG_SERVERALIAS;
3154     unifontsel_set_filter_buttons(fs);
3155
3156     /*
3157      * Go and find all the font names, and set up our master font
3158      * list.
3159      */
3160     fs->fonts_by_realname = newtree234(fontinfo_realname_compare);
3161     fs->fonts_by_selorder = newtree234(fontinfo_selorder_compare);
3162     for (i = 0; i < lenof(unifont_types); i++)
3163         unifont_types[i]->enum_fonts(GTK_WIDGET(fs->u.window),
3164                                      unifontsel_add_entry, fs);
3165
3166     /*
3167      * And set up the initial font names list.
3168      */
3169     unifontsel_setup_familylist(fs);
3170
3171     fs->selsize = fs->intendedsize = 13;   /* random default */
3172     gtk_widget_set_sensitive(fs->u.ok_button, FALSE);
3173
3174     return (unifontsel *)fs;
3175 }
3176
3177 void unifontsel_destroy(unifontsel *fontsel)
3178 {
3179     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
3180     fontinfo *info;
3181
3182     if (fs->preview_pixmap)
3183         gdk_pixmap_unref(fs->preview_pixmap);
3184
3185     freetree234(fs->fonts_by_selorder);
3186     while ((info = delpos234(fs->fonts_by_realname, 0)) != NULL)
3187         sfree(info);
3188     freetree234(fs->fonts_by_realname);
3189
3190     gtk_widget_destroy(GTK_WIDGET(fs->u.window));
3191     sfree(fs);
3192 }
3193
3194 void unifontsel_set_name(unifontsel *fontsel, const char *fontname)
3195 {
3196     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
3197     int i, start, end, size, flags;
3198     const char *fontname2 = NULL;
3199     fontinfo *info;
3200
3201     /*
3202      * Provide a default if given an empty or null font name.
3203      */
3204     if (!fontname || !*fontname)
3205         fontname = "server:fixed";
3206
3207     /*
3208      * Call the canonify_fontname function.
3209      */
3210     fontname = unifont_do_prefix(fontname, &start, &end);
3211     for (i = start; i < end; i++) {
3212         fontname2 = unifont_types[i]->canonify_fontname
3213             (GTK_WIDGET(fs->u.window), fontname, &size, &flags, FALSE);
3214         if (fontname2)
3215             break;
3216     }
3217     if (i == end)
3218         return;                        /* font name not recognised */
3219
3220     /*
3221      * Now look up the canonified font name in our index.
3222      */
3223     {
3224         struct fontinfo_realname_find f;
3225         f.realname = fontname2;
3226         f.flags = flags;
3227         info = find234(fs->fonts_by_realname, &f, fontinfo_realname_find);
3228     }
3229
3230     /*
3231      * If we've found the font, and its size field is either
3232      * correct or zero (the latter indicating a scalable font),
3233      * then we're done. Otherwise, try looking up the original
3234      * font name instead.
3235      */
3236     if (!info || (info->size != size && info->size != 0)) {
3237         struct fontinfo_realname_find f;
3238         f.realname = fontname;
3239         f.flags = flags;
3240
3241         info = find234(fs->fonts_by_realname, &f, fontinfo_realname_find);
3242         if (!info || info->size != size)
3243             return;                    /* font name not in our index */
3244     }
3245
3246     /*
3247      * Now we've got a fontinfo structure and a font size, so we
3248      * know everything we need to fill in all the fields in the
3249      * dialog.
3250      */
3251     unifontsel_select_font(fs, info, size, 0, TRUE);
3252 }
3253
3254 char *unifontsel_get_name(unifontsel *fontsel)
3255 {
3256     unifontsel_internal *fs = (unifontsel_internal *)fontsel;
3257     char *name;
3258
3259     if (!fs->selected)
3260         return NULL;
3261
3262     if (fs->selected->size == 0) {
3263         name = fs->selected->fontclass->scale_fontname
3264             (GTK_WIDGET(fs->u.window), fs->selected->realname, fs->selsize);
3265         if (name) {
3266             char *ret = dupcat(fs->selected->fontclass->prefix, ":",
3267                                name, NULL);
3268             sfree(name);
3269             return ret;
3270         }
3271     }
3272
3273     return dupcat(fs->selected->fontclass->prefix, ":",
3274                   fs->selected->realname, NULL);
3275 }
3276
3277 #endif /* GTK_CHECK_VERSION(2,0,0) */