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