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