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