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