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