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