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