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