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