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