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