2 * Unified font management for GTK.
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
16 #include <gdk/gdkkeysyms.h>
19 #include <X11/Xutil.h>
20 #include <X11/Xatom.h>
29 * - all the GDK font functions used in the x11font subclass are
30 * deprecated, so one day they may go away. When this happens -
31 * or before, if I'm feeling proactive - it oughtn't to be too
32 * difficult in principle to convert the whole thing to use
33 * actual Xlib font calls.
35 * - it would be nice if we could move the processing of
36 * underline and VT100 double width into this module, so that
37 * instead of using the ghastly pixmap-stretching technique
38 * everywhere we could tell the Pango backend to scale its
39 * fonts to double size properly and at full resolution.
40 * However, this requires me to learn how to make Pango stretch
41 * text to an arbitrary aspect ratio (for double-width only
42 * text, which perversely is harder than DW+DH), and right now
43 * I haven't the energy.
47 * Ad-hoc vtable mechanism to allow font structures to be
50 * Any instance of `unifont' used in the vtable functions will
51 * actually be the first element of a larger structure containing
52 * data specific to the subtype. This is permitted by the ISO C
53 * provision that one may safely cast between a pointer to a
54 * structure and a pointer to its first element.
57 #define FONTFLAG_CLIENTSIDE 0x0001
58 #define FONTFLAG_SERVERSIDE 0x0002
59 #define FONTFLAG_SERVERALIAS 0x0004
60 #define FONTFLAG_NONMONOSPACED 0x0008
62 typedef void (*fontsel_add_entry)(void *ctx, const char *realfontname,
63 const char *family, const char *charset,
64 const char *style, const char *stylekey,
66 const struct unifont_vtable *fontclass);
68 struct unifont_vtable {
70 * `Methods' of the `class'.
72 unifont *(*create)(GtkWidget *widget, const char *name, int wide, int bold,
73 int shadowoffset, int shadowalways);
74 void (*destroy)(unifont *font);
75 void (*draw_text)(GdkDrawable *target, GdkGC *gc, unifont *font,
76 int x, int y, const char *string, int len, int wide,
77 int bold, int cellwidth);
78 void (*enum_fonts)(GtkWidget *widget,
79 fontsel_add_entry callback, void *callback_ctx);
80 char *(*canonify_fontname)(GtkWidget *widget, const char *name, int *size,
82 char *(*scale_fontname)(GtkWidget *widget, const char *name, int size);
85 * `Static data members' of the `class'.
90 /* ----------------------------------------------------------------------
91 * GDK-based X11 font implementation.
94 static void x11font_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
95 int x, int y, const char *string, int len,
96 int wide, int bold, int cellwidth);
97 static unifont *x11font_create(GtkWidget *widget, const char *name,
99 int shadowoffset, int shadowalways);
100 static void x11font_destroy(unifont *font);
101 static void x11font_enum_fonts(GtkWidget *widget,
102 fontsel_add_entry callback, void *callback_ctx);
103 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
104 int *size, int resolve_aliases);
105 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
111 * Actual font objects. We store a number of these, for
112 * automatically guessed bold and wide variants.
114 * The parallel array `allocated' indicates whether we've
115 * tried to fetch a subfont already (thus distinguishing NULL
116 * because we haven't tried yet from NULL because we tried and
117 * failed, so that we don't keep trying and failing
123 * `sixteen_bit' is true iff the font object is indexed by
124 * values larger than a byte. That is, this flag tells us
125 * whether we use gdk_draw_text_wc() or gdk_draw_text().
129 * `variable' is true iff the font is non-fixed-pitch. This
130 * enables some code which takes greater care over character
131 * positioning during text drawing.
135 * Data passed in to unifont_create().
137 int wide, bold, shadowoffset, shadowalways;
140 static const struct unifont_vtable x11font_vtable = {
145 x11font_canonify_fontname,
146 x11font_scale_fontname,
150 char *x11_guess_derived_font_name(GdkFont *font, int bold, int wide)
152 XFontStruct *xfs = GDK_FONT_XFONT(font);
153 Display *disp = GDK_FONT_XDISPLAY(font);
154 Atom fontprop = XInternAtom(disp, "FONT", False);
156 if (XGetFontProperty(xfs, fontprop, &ret)) {
157 char *name = XGetAtomName(disp, (Atom)ret);
158 if (name && name[0] == '-') {
160 char *dupname, *extrafree = NULL, *ret;
164 p = q = dupname = dupstr(name); /* skip initial minus */
167 while (*p && nstr < lenof(strings)) {
170 strings[nstr++] = p+1;
175 if (nstr < lenof(strings))
176 return NULL; /* XLFD was malformed */
182 /* 4 is `wideness', which obviously may have changed. */
183 /* 5 is additional style, which may be e.g. `ja' or `ko'. */
184 strings[4] = strings[5] = "*";
185 strings[11] = extrafree = dupprintf("%d", 2*atoi(strings[11]));
188 ret = dupcat("-", strings[ 0], "-", strings[ 1], "-", strings[ 2],
189 "-", strings[ 3], "-", strings[ 4], "-", strings[ 5],
190 "-", strings[ 6], "-", strings[ 7], "-", strings[ 8],
191 "-", strings[ 9], "-", strings[10], "-", strings[11],
192 "-", strings[12], NULL);
202 static int x11_font_width(GdkFont *font, int sixteen_bit)
208 return gdk_text_width(font, (const gchar *)&space, 2);
210 return gdk_char_width(font, '0');
214 static unifont *x11font_create(GtkWidget *widget, const char *name,
216 int shadowoffset, int shadowalways)
218 struct x11font *xfont;
222 Atom charset_registry, charset_encoding, spacing;
223 unsigned long registry_ret, encoding_ret, spacing_ret;
224 int pubcs, realcs, sixteen_bit, variable;
227 font = gdk_font_load(name);
231 xfs = GDK_FONT_XFONT(font);
232 disp = GDK_FONT_XDISPLAY(font);
234 charset_registry = XInternAtom(disp, "CHARSET_REGISTRY", False);
235 charset_encoding = XInternAtom(disp, "CHARSET_ENCODING", False);
237 pubcs = realcs = CS_NONE;
241 if (XGetFontProperty(xfs, charset_registry, ®istry_ret) &&
242 XGetFontProperty(xfs, charset_encoding, &encoding_ret)) {
244 reg = XGetAtomName(disp, (Atom)registry_ret);
245 enc = XGetAtomName(disp, (Atom)encoding_ret);
247 char *encoding = dupcat(reg, "-", enc, NULL);
248 pubcs = realcs = charset_from_xenc(encoding);
251 * iso10646-1 is the only wide font encoding we
252 * support. In this case, we expect clients to give us
253 * UTF-8, which this module must internally convert
254 * into 16-bit Unicode.
256 if (!strcasecmp(encoding, "iso10646-1")) {
258 pubcs = realcs = CS_UTF8;
262 * Hack for X line-drawing characters: if the primary
263 * font is encoded as ISO-8859-1, and has valid glyphs
264 * in the first 32 char positions, it is assumed that
265 * those glyphs are the VT100 line-drawing character
268 * Actually, we'll hack even harder by only checking
269 * position 0x19 (vertical line, VT100 linedrawing
270 * `x'). Then we can check it easily by seeing if the
271 * ascent and descent differ.
273 if (pubcs == CS_ISO8859_1) {
274 int lb, rb, wid, asc, desc;
279 gdk_string_extents(font, text, &lb, &rb, &wid, &asc, &desc);
281 realcs = CS_ISO8859_1_X11;
288 spacing = XInternAtom(disp, "SPACING", False);
289 if (XGetFontProperty(xfs, spacing, &spacing_ret)) {
291 spc = XGetAtomName(disp, (Atom)spacing_ret);
293 if (spc && strchr("CcMm", spc[0]))
297 xfont = snew(struct x11font);
298 xfont->u.vt = &x11font_vtable;
299 xfont->u.width = x11_font_width(font, sixteen_bit);
300 xfont->u.ascent = font->ascent;
301 xfont->u.descent = font->descent;
302 xfont->u.height = xfont->u.ascent + xfont->u.descent;
303 xfont->u.public_charset = pubcs;
304 xfont->u.real_charset = realcs;
305 xfont->fonts[0] = font;
306 xfont->allocated[0] = TRUE;
307 xfont->sixteen_bit = sixteen_bit;
308 xfont->variable = variable;
311 xfont->shadowoffset = shadowoffset;
312 xfont->shadowalways = shadowalways;
314 for (i = 1; i < lenof(xfont->fonts); i++) {
315 xfont->fonts[i] = NULL;
316 xfont->allocated[i] = FALSE;
319 return (unifont *)xfont;
322 static void x11font_destroy(unifont *font)
324 struct x11font *xfont = (struct x11font *)font;
327 for (i = 0; i < lenof(xfont->fonts); i++)
329 gdk_font_unref(xfont->fonts[i]);
333 static void x11_alloc_subfont(struct x11font *xfont, int sfid)
335 char *derived_name = x11_guess_derived_font_name
336 (xfont->fonts[0], sfid & 1, !!(sfid & 2));
337 xfont->fonts[sfid] = gdk_font_load(derived_name); /* may be NULL */
338 xfont->allocated[sfid] = TRUE;
342 static void x11font_really_draw_text(GdkDrawable *target, GdkFont *font,
343 GdkGC *gc, int x, int y,
344 const gchar *string, int clen, int nchars,
345 int shadowbold, int shadowoffset,
346 int fontvariable, int cellwidth)
348 int step = clen * nchars, nsteps = 1, centre = FALSE;
352 * In a variable-pitch font, we draw one character at a
353 * time, and centre it in the character cell.
360 while (nsteps-- > 0) {
363 X += (cellwidth - gdk_text_width(font, string, step)) / 2;
365 gdk_draw_text(target, font, gc, X, y, string, step);
367 gdk_draw_text(target, font, gc, X + shadowoffset, y, string, step);
374 static void x11font_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
375 int x, int y, const char *string, int len,
376 int wide, int bold, int cellwidth)
378 struct x11font *xfont = (struct x11font *)font;
380 int shadowbold = FALSE;
381 int mult = (wide ? 2 : 1);
387 * Decide which subfont we're using, and whether we have to
390 if (xfont->shadowalways && bold) {
394 sfid = 2 * wide + bold;
395 if (!xfont->allocated[sfid])
396 x11_alloc_subfont(xfont, sfid);
397 if (bold && !xfont->fonts[sfid]) {
400 sfid = 2 * wide + bold;
401 if (!xfont->allocated[sfid])
402 x11_alloc_subfont(xfont, sfid);
405 if (!xfont->fonts[sfid])
406 return; /* we've tried our best, but no luck */
408 if (xfont->sixteen_bit) {
410 * This X font has 16-bit character indices, which means
411 * we expect our string to have been passed in UTF-8.
415 int nchars, maxchars, i;
418 * Convert the input string to wide-character Unicode.
421 for (i = 0; i < len; i++)
422 if ((unsigned char)string[i] <= 0x7F ||
423 (unsigned char)string[i] >= 0xC0)
425 wcs = snewn(maxchars+1, wchar_t);
426 nchars = charset_to_unicode((char **)&string, &len, wcs, maxchars,
427 CS_UTF8, NULL, NULL, 0);
428 assert(nchars <= maxchars);
431 xcs = snewn(nchars, XChar2b);
432 for (i = 0; i < nchars; i++) {
433 xcs[i].byte1 = wcs[i] >> 8;
434 xcs[i].byte2 = wcs[i];
437 x11font_really_draw_text(target, xfont->fonts[sfid], gc, x, y,
438 (gchar *)xcs, 2, nchars,
439 shadowbold, xfont->shadowoffset,
440 xfont->variable, cellwidth * mult);
444 x11font_really_draw_text(target, xfont->fonts[sfid], gc, x, y,
446 shadowbold, xfont->shadowoffset,
447 xfont->variable, cellwidth * mult);
451 static void x11font_enum_fonts(GtkWidget *widget,
452 fontsel_add_entry callback, void *callback_ctx)
456 int nnames, i, max, tmpsize;
460 fontnames = XListFonts(GDK_DISPLAY(), "*", max, &nnames);
462 XFreeFontNames(fontnames);
470 for (i = 0; i < nnames; i++) {
471 if (fontnames[i][0] == '-') {
473 * Dismember an XLFD and convert it into the format
474 * we'll be using in the font selector.
476 char *components[14];
477 char *p, *font, *style, *stylekey, *charset;
478 int j, weightkey, slantkey, setwidthkey;
479 int thistmpsize, fontsize, flags;
481 thistmpsize = 4 * strlen(fontnames[i]) + 256;
482 if (tmpsize < thistmpsize) {
483 tmpsize = thistmpsize;
484 tmp = sresize(tmp, tmpsize, char);
486 strcpy(tmp, fontnames[i]);
489 for (j = 0; j < 14; j++) {
493 while (*p && *p != '-')
499 * Font name is made up of fields 0 and 1, in reverse
500 * order with parentheses. (This is what the GTK 1.2 X
501 * font selector does, and it seems to come out
502 * looking reasonably sensible.)
505 p += 1 + sprintf(p, "%s (%s)", components[1], components[0]);
508 * Charset is made up of fields 12 and 13.
511 p += 1 + sprintf(p, "%s-%s", components[12], components[13]);
514 * Style is a mixture of quite a lot of the fields,
515 * with some strange formatting.
518 p += sprintf(p, "%s", components[2][0] ? components[2] :
520 if (!g_strcasecmp(components[3], "i"))
521 p += sprintf(p, " italic");
522 else if (!g_strcasecmp(components[3], "o"))
523 p += sprintf(p, " oblique");
524 else if (!g_strcasecmp(components[3], "ri"))
525 p += sprintf(p, " reverse italic");
526 else if (!g_strcasecmp(components[3], "ro"))
527 p += sprintf(p, " reverse oblique");
528 else if (!g_strcasecmp(components[3], "ot"))
529 p += sprintf(p, " other-slant");
530 if (components[4][0] && g_strcasecmp(components[4], "normal"))
531 p += sprintf(p, " %s", components[4]);
532 if (!g_strcasecmp(components[10], "m"))
533 p += sprintf(p, " [M]");
534 if (!g_strcasecmp(components[10], "c"))
535 p += sprintf(p, " [C]");
536 if (components[5][0])
537 p += sprintf(p, " %s", components[5]);
540 * Style key is the same stuff as above, but with a
541 * couple of transformations done on it to make it
542 * sort more sensibly.
546 if (!g_strcasecmp(components[2], "medium") ||
547 !g_strcasecmp(components[2], "regular") ||
548 !g_strcasecmp(components[2], "normal") ||
549 !g_strcasecmp(components[2], "book"))
551 else if (!g_strncasecmp(components[2], "demi", 4) ||
552 !g_strncasecmp(components[2], "semi", 4))
556 if (!g_strcasecmp(components[3], "r"))
558 else if (!g_strncasecmp(components[3], "r", 1))
562 if (!g_strcasecmp(components[4], "normal"))
567 p += sprintf(p, "%04d%04d%s%04d%04d%s%04d%04d%s%04d%s%04d%s",
569 strlen(components[2]), components[2],
571 strlen(components[3]), components[3],
573 strlen(components[4]), components[4],
574 strlen(components[10]), components[10],
575 strlen(components[5]), components[5]);
577 assert(p - tmp < thistmpsize);
580 * Size is in pixels, for our application, so we
581 * derive it directly from the pixel size field,
584 fontsize = atoi(components[6]);
587 * Flags: we need to know whether this is a monospaced
588 * font, which we do by examining the spacing field
591 flags = FONTFLAG_SERVERSIDE;
592 if (!strchr("CcMm", components[10][0]))
593 flags |= FONTFLAG_NONMONOSPACED;
596 * Not sure why, but sometimes the X server will
597 * deliver dummy font types in which fontsize comes
598 * out as zero. Filter those out.
601 callback(callback_ctx, fontnames[i], font, charset,
602 style, stylekey, fontsize, flags, &x11font_vtable);
605 * This isn't an XLFD, so it must be an alias.
606 * Transmit it with mostly null data.
608 * It would be nice to work out if it's monospaced
609 * here, but at the moment I can't see that being
610 * anything but computationally hideous. Ah well.
612 callback(callback_ctx, fontnames[i], fontnames[i], NULL,
613 NULL, NULL, 0, FONTFLAG_SERVERALIAS, &x11font_vtable);
616 XFreeFontNames(fontnames);
619 static char *x11font_canonify_fontname(GtkWidget *widget, const char *name,
620 int *size, int resolve_aliases)
623 * When given an X11 font name to try to make sense of for a
624 * font selector, we must attempt to load it (to see if it
625 * exists), and then canonify it by extracting its FONT
626 * property, which should give its full XLFD even if what we
627 * originally had was a wildcard.
629 * However, we must carefully avoid canonifying font
630 * _aliases_, unless specifically asked to, because the font
631 * selector treats them as worthwhile in their own right.
633 GdkFont *font = gdk_font_load(name);
636 Atom fontprop, fontprop2;
640 return NULL; /* didn't make sense to us, sorry */
644 xfs = GDK_FONT_XFONT(font);
645 disp = GDK_FONT_XDISPLAY(font);
646 fontprop = XInternAtom(disp, "FONT", False);
648 if (XGetFontProperty(xfs, fontprop, &ret)) {
649 char *newname = XGetAtomName(disp, (Atom)ret);
651 unsigned long fsize = 12;
653 fontprop2 = XInternAtom(disp, "PIXEL_SIZE", False);
654 if (XGetFontProperty(xfs, fontprop2, &fsize) && fsize > 0) {
656 gdk_font_unref(font);
657 return dupstr(name[0] == '-' || resolve_aliases ?
663 gdk_font_unref(font);
664 return NULL; /* something went wrong */
667 static char *x11font_scale_fontname(GtkWidget *widget, const char *name,
670 return NULL; /* shan't */
673 /* ----------------------------------------------------------------------
674 * Pango font implementation.
677 static void pangofont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
678 int x, int y, const char *string, int len,
679 int wide, int bold, int cellwidth);
680 static unifont *pangofont_create(GtkWidget *widget, const char *name,
682 int shadowoffset, int shadowalways);
683 static void pangofont_destroy(unifont *font);
684 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback,
686 static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name,
687 int *size, int resolve_aliases);
688 static char *pangofont_scale_fontname(GtkWidget *widget, const char *name,
696 PangoFontDescription *desc;
699 * The containing widget.
703 * Data passed in to unifont_create().
705 int bold, shadowoffset, shadowalways;
708 static const struct unifont_vtable pangofont_vtable = {
712 pangofont_enum_fonts,
713 pangofont_canonify_fontname,
714 pangofont_scale_fontname,
719 * This function is used to rigorously validate a
720 * PangoFontDescription. Later versions of Pango have a nasty
721 * habit of accepting _any_ old string as input to
722 * pango_font_description_from_string and returning a font
723 * description which can actually be used to display text, even if
724 * they have to do it by falling back to their most default font.
725 * This is doubtless helpful in some situations, but not here,
726 * because we need to know if a Pango font string actually _makes
727 * sense_ in order to fall back to treating it as an X font name
728 * if it doesn't. So we check that the font family is actually one
729 * supported by Pango.
731 static int pangofont_check_desc_makes_sense(PangoContext *ctx,
732 PangoFontDescription *desc)
734 #ifndef PANGO_PRE_1POINT6
737 PangoFontFamily **families;
738 int i, nfamilies, matched;
741 * Ask Pango for a list of font families, and iterate through
742 * them to see if one of them matches the family in the
743 * PangoFontDescription.
745 #ifndef PANGO_PRE_1POINT6
746 map = pango_context_get_font_map(ctx);
749 pango_font_map_list_families(map, &families, &nfamilies);
751 pango_context_list_families(ctx, &families, &nfamilies);
755 for (i = 0; i < nfamilies; i++) {
756 if (!g_strcasecmp(pango_font_family_get_name(families[i]),
757 pango_font_description_get_family(desc))) {
767 static unifont *pangofont_create(GtkWidget *widget, const char *name,
769 int shadowoffset, int shadowalways)
771 struct pangofont *pfont;
773 #ifndef PANGO_PRE_1POINT6
776 PangoFontDescription *desc;
778 PangoFontMetrics *metrics;
780 desc = pango_font_description_from_string(name);
783 ctx = gtk_widget_get_pango_context(widget);
785 pango_font_description_free(desc);
788 if (!pangofont_check_desc_makes_sense(ctx, desc)) {
789 pango_font_description_free(desc);
792 #ifndef PANGO_PRE_1POINT6
793 map = pango_context_get_font_map(ctx);
795 pango_font_description_free(desc);
798 fset = pango_font_map_load_fontset(map, ctx, desc,
799 pango_context_get_language(ctx));
801 fset = pango_context_load_fontset(ctx, desc,
802 pango_context_get_language(ctx));
805 pango_font_description_free(desc);
808 metrics = pango_fontset_get_metrics(fset);
810 pango_font_metrics_get_approximate_digit_width(metrics) == 0) {
811 pango_font_description_free(desc);
812 g_object_unref(fset);
816 pfont = snew(struct pangofont);
817 pfont->u.vt = &pangofont_vtable;
819 PANGO_PIXELS(pango_font_metrics_get_approximate_digit_width(metrics));
820 pfont->u.ascent = PANGO_PIXELS(pango_font_metrics_get_ascent(metrics));
821 pfont->u.descent = PANGO_PIXELS(pango_font_metrics_get_descent(metrics));
822 pfont->u.height = pfont->u.ascent + pfont->u.descent;
823 /* The Pango API is hardwired to UTF-8 */
824 pfont->u.public_charset = CS_UTF8;
825 pfont->u.real_charset = CS_UTF8;
828 pfont->widget = widget;
830 pfont->shadowoffset = shadowoffset;
831 pfont->shadowalways = shadowalways;
833 pango_font_metrics_unref(metrics);
835 return (unifont *)pfont;
838 static void pangofont_destroy(unifont *font)
840 struct pangofont *pfont = (struct pangofont *)font;
841 pango_font_description_free(pfont->desc);
842 g_object_unref(pfont->fset);
846 static void pangofont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
847 int x, int y, const char *string, int len,
848 int wide, int bold, int cellwidth)
850 struct pangofont *pfont = (struct pangofont *)font;
853 int shadowbold = FALSE;
858 y -= pfont->u.ascent;
860 layout = pango_layout_new(gtk_widget_get_pango_context(pfont->widget));
861 pango_layout_set_font_description(layout, pfont->desc);
862 if (bold > pfont->bold) {
863 if (pfont->shadowalways)
866 PangoFontDescription *desc2 =
867 pango_font_description_copy_static(pfont->desc);
868 pango_font_description_set_weight(desc2, PANGO_WEIGHT_BOLD);
869 pango_layout_set_font_description(layout, desc2);
877 * Extract a single UTF-8 character from the string.
881 (unsigned char)string[clen] >= 0x80 &&
882 (unsigned char)string[clen] < 0xC0)
885 pango_layout_set_text(layout, string, clen);
886 pango_layout_get_pixel_extents(layout, NULL, &rect);
887 gdk_draw_layout(target, gc, x + (cellwidth - rect.width)/2,
888 y + (pfont->u.height - rect.height)/2, layout);
890 gdk_draw_layout(target, gc, x + (cellwidth - rect.width)/2 + pfont->shadowoffset,
891 y + (pfont->u.height - rect.height)/2, layout);
898 g_object_unref(layout);
902 * Dummy size value to be used when converting a
903 * PangoFontDescription of a scalable font to a string for
906 #define PANGO_DUMMY_SIZE 12
908 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback,
912 #ifndef PANGO_PRE_1POINT6
915 PangoFontFamily **families;
918 ctx = gtk_widget_get_pango_context(widget);
923 * Ask Pango for a list of font families, and iterate through
926 #ifndef PANGO_PRE_1POINT6
927 map = pango_context_get_font_map(ctx);
930 pango_font_map_list_families(map, &families, &nfamilies);
932 pango_context_list_families(ctx, &families, &nfamilies);
934 for (i = 0; i < nfamilies; i++) {
935 PangoFontFamily *family = families[i];
936 const char *familyname;
938 PangoFontFace **faces;
942 * Set up our flags for this font family, and get the name
945 flags = FONTFLAG_CLIENTSIDE;
946 #ifndef PANGO_PRE_1POINT4
948 * In very early versions of Pango, we can't tell
949 * monospaced fonts from non-monospaced.
951 if (!pango_font_family_is_monospace(family))
952 flags |= FONTFLAG_NONMONOSPACED;
954 familyname = pango_font_family_get_name(family);
957 * Go through the available font faces in this family.
959 pango_font_family_list_faces(family, &faces, &nfaces);
960 for (j = 0; j < nfaces; j++) {
961 PangoFontFace *face = faces[j];
962 PangoFontDescription *desc;
963 const char *facename;
965 int k, nsizes, dummysize;
968 * Get the face name string.
970 facename = pango_font_face_get_face_name(face);
973 * Set up a font description with what we've got so
974 * far. We'll fill in the size field manually and then
975 * call pango_font_description_to_string() to give the
976 * full real name of the specific font.
978 desc = pango_font_face_describe(face);
981 * See if this font has a list of specific sizes.
983 #ifndef PANGO_PRE_1POINT4
984 pango_font_face_list_sizes(face, &sizes, &nsizes);
987 * In early versions of Pango, that call wasn't
988 * supported; we just have to assume everything is
995 * Write a single entry with a dummy size.
997 dummysize = PANGO_DUMMY_SIZE * PANGO_SCALE;
1003 * If so, go through them one by one.
1005 for (k = 0; k < nsizes; k++) {
1009 pango_font_description_set_size(desc, sizes[k]);
1011 fullname = pango_font_description_to_string(desc);
1014 * Construct the sorting key for font styles.
1020 n = pango_font_description_get_weight(desc);
1021 /* Weight: normal, then lighter, then bolder */
1022 if (n <= PANGO_WEIGHT_NORMAL)
1023 n = PANGO_WEIGHT_NORMAL - n;
1024 p += sprintf(p, "%4d", n);
1026 n = pango_font_description_get_style(desc);
1027 p += sprintf(p, " %2d", n);
1029 n = pango_font_description_get_stretch(desc);
1030 /* Stretch: closer to normal sorts earlier */
1031 n = 2 * abs(PANGO_STRETCH_NORMAL - n) +
1032 (n < PANGO_STRETCH_NORMAL);
1033 p += sprintf(p, " %2d", n);
1035 n = pango_font_description_get_variant(desc);
1036 p += sprintf(p, " %2d", n);
1041 * Got everything. Hand off to the callback.
1042 * (The charset string is NULL, because only
1043 * server-side X fonts use it.)
1045 callback(callback_ctx, fullname, familyname, NULL, facename,
1047 (sizes == &dummysize ? 0 : PANGO_PIXELS(sizes[k])),
1048 flags, &pangofont_vtable);
1052 if (sizes != &dummysize)
1055 pango_font_description_free(desc);
1062 static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name,
1063 int *size, int resolve_aliases)
1066 * When given a Pango font name to try to make sense of for a
1067 * font selector, we must normalise it to PANGO_DUMMY_SIZE and
1068 * extract its original size (in pixels) into the `size' field.
1071 #ifndef PANGO_PRE_1POINT6
1074 PangoFontDescription *desc;
1076 PangoFontMetrics *metrics;
1077 char *newname, *retname;
1079 desc = pango_font_description_from_string(name);
1082 ctx = gtk_widget_get_pango_context(widget);
1084 pango_font_description_free(desc);
1087 if (!pangofont_check_desc_makes_sense(ctx, desc)) {
1088 pango_font_description_free(desc);
1091 #ifndef PANGO_PRE_1POINT6
1092 map = pango_context_get_font_map(ctx);
1094 pango_font_description_free(desc);
1097 fset = pango_font_map_load_fontset(map, ctx, desc,
1098 pango_context_get_language(ctx));
1100 fset = pango_context_load_fontset(ctx, desc,
1101 pango_context_get_language(ctx));
1104 pango_font_description_free(desc);
1107 metrics = pango_fontset_get_metrics(fset);
1109 pango_font_metrics_get_approximate_digit_width(metrics) == 0) {
1110 pango_font_description_free(desc);
1111 g_object_unref(fset);
1115 *size = PANGO_PIXELS(pango_font_description_get_size(desc));
1116 pango_font_description_set_size(desc, PANGO_DUMMY_SIZE * PANGO_SCALE);
1117 newname = pango_font_description_to_string(desc);
1118 retname = dupstr(newname);
1121 pango_font_metrics_unref(metrics);
1122 pango_font_description_free(desc);
1123 g_object_unref(fset);
1128 static char *pangofont_scale_fontname(GtkWidget *widget, const char *name,
1131 PangoFontDescription *desc;
1132 char *newname, *retname;
1134 desc = pango_font_description_from_string(name);
1137 pango_font_description_set_size(desc, size * PANGO_SCALE);
1138 newname = pango_font_description_to_string(desc);
1139 retname = dupstr(newname);
1141 pango_font_description_free(desc);
1146 /* ----------------------------------------------------------------------
1147 * Outermost functions which do the vtable dispatch.
1151 * Complete list of font-type subclasses. Listed in preference
1152 * order for unifont_create(). (That is, in the extremely unlikely
1153 * event that the same font name is valid as both a Pango and an
1154 * X11 font, it will be interpreted as the former in the absence
1155 * of an explicit type-disambiguating prefix.)
1157 static const struct unifont_vtable *unifont_types[] = {
1163 * Function which takes a font name and processes the optional
1164 * scheme prefix. Returns the tail of the font name suitable for
1165 * passing to individual font scheme functions, and also provides
1166 * a subrange of the unifont_types[] array above.
1168 * The return values `start' and `end' denote a half-open interval
1169 * in unifont_types[]; that is, the correct way to iterate over
1172 * for (i = start; i < end; i++) {...}
1174 static const char *unifont_do_prefix(const char *name, int *start, int *end)
1176 int colonpos = strcspn(name, ":");
1179 if (name[colonpos]) {
1181 * There's a colon prefix on the font name. Use it to work
1182 * out which subclass to use.
1184 for (i = 0; i < lenof(unifont_types); i++) {
1185 if (strlen(unifont_types[i]->prefix) == colonpos &&
1186 !strncmp(unifont_types[i]->prefix, name, colonpos)) {
1189 return name + colonpos + 1;
1193 * None matched, so return an empty scheme list to prevent
1194 * any scheme from being called at all.
1197 return name + colonpos + 1;
1200 * No colon prefix, so just use all the subclasses.
1203 *end = lenof(unifont_types);
1208 unifont *unifont_create(GtkWidget *widget, const char *name, int wide,
1209 int bold, int shadowoffset, int shadowalways)
1213 name = unifont_do_prefix(name, &start, &end);
1215 for (i = start; i < end; i++) {
1216 unifont *ret = unifont_types[i]->create(widget, name, wide, bold,
1217 shadowoffset, shadowalways);
1221 return NULL; /* font not found in any scheme */
1224 void unifont_destroy(unifont *font)
1226 font->vt->destroy(font);
1229 void unifont_draw_text(GdkDrawable *target, GdkGC *gc, unifont *font,
1230 int x, int y, const char *string, int len,
1231 int wide, int bold, int cellwidth)
1233 font->vt->draw_text(target, gc, font, x, y, string, len,
1234 wide, bold, cellwidth);
1237 /* ----------------------------------------------------------------------
1238 * Implementation of a unified font selector.
1241 typedef struct fontinfo fontinfo;
1243 typedef struct unifontsel_internal {
1244 /* This must be the structure's first element, for cross-casting */
1246 GtkListStore *family_model, *style_model, *size_model;
1247 GtkWidget *family_list, *style_list, *size_entry, *size_list;
1248 GtkWidget *filter_buttons[4];
1249 GtkWidget *preview_area;
1250 GdkPixmap *preview_pixmap;
1251 int preview_width, preview_height;
1252 GdkColor preview_fg, preview_bg;
1254 tree234 *fonts_by_realname, *fonts_by_selorder;
1256 int selsize, intendedsize;
1257 int inhibit_response; /* inhibit callbacks when we change GUI controls */
1258 } unifontsel_internal;
1261 * The structure held in the tree234s. All the string members are
1262 * part of the same allocated area, so don't need freeing
1267 char *family, *charset, *style, *stylekey;
1270 * Fallback sorting key, to permit multiple identical entries
1271 * to exist in the selorder tree.
1275 * Indices mapping fontinfo structures to indices in the list
1276 * boxes. sizeindex is irrelevant if the font is scalable
1279 int familyindex, styleindex, sizeindex;
1281 * The class of font.
1283 const struct unifont_vtable *fontclass;
1286 static int fontinfo_realname_compare(void *av, void *bv)
1288 fontinfo *a = (fontinfo *)av;
1289 fontinfo *b = (fontinfo *)bv;
1290 return g_strcasecmp(a->realname, b->realname);
1293 static int fontinfo_realname_find(void *av, void *bv)
1295 const char *a = (const char *)av;
1296 fontinfo *b = (fontinfo *)bv;
1297 return g_strcasecmp(a, b->realname);
1300 static int strnullcasecmp(const char *a, const char *b)
1305 * If exactly one of the inputs is NULL, it compares before
1308 if ((i = (!b) - (!a)) != 0)
1312 * NULL compares equal.
1318 * Otherwise, ordinary strcasecmp.
1320 return g_strcasecmp(a, b);
1323 static int fontinfo_selorder_compare(void *av, void *bv)
1325 fontinfo *a = (fontinfo *)av;
1326 fontinfo *b = (fontinfo *)bv;
1328 if ((i = strnullcasecmp(a->family, b->family)) != 0)
1330 if ((i = strnullcasecmp(a->charset, b->charset)) != 0)
1332 if ((i = strnullcasecmp(a->stylekey, b->stylekey)) != 0)
1334 if ((i = strnullcasecmp(a->style, b->style)) != 0)
1336 if (a->size != b->size)
1337 return (a->size < b->size ? -1 : +1);
1338 if (a->index != b->index)
1339 return (a->index < b->index ? -1 : +1);
1343 static void unifontsel_setup_familylist(unifontsel_internal *fs)
1346 int i, listindex, minpos = -1, maxpos = -1;
1347 char *currfamily = NULL;
1350 gtk_list_store_clear(fs->family_model);
1354 * Search through the font tree for anything matching our
1355 * current filter criteria. When we find one, add its font
1356 * name to the list box.
1358 for (i = 0 ;; i++) {
1359 info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1361 * info may be NULL if we've just run off the end of the
1362 * tree. We must still do a processing pass in that
1363 * situation, in case we had an unfinished font record in
1366 if (info && (info->flags &~ fs->filter_flags)) {
1367 info->familyindex = -1;
1368 continue; /* we're filtering out this font */
1370 if (!info || strnullcasecmp(currfamily, info->family)) {
1372 * We've either finished a family, or started a new
1376 gtk_list_store_append(fs->family_model, &iter);
1377 gtk_list_store_set(fs->family_model, &iter,
1378 0, currfamily, 1, minpos, 2, maxpos+1, -1);
1383 currfamily = info->family;
1387 break; /* now we're done */
1388 info->familyindex = listindex;
1393 static void unifontsel_setup_stylelist(unifontsel_internal *fs,
1397 int i, listindex, minpos = -1, maxpos = -1, started = FALSE;
1398 char *currcs = NULL, *currstyle = NULL;
1401 gtk_list_store_clear(fs->style_model);
1406 * Search through the font tree for anything matching our
1407 * current filter criteria. When we find one, add its charset
1408 * and/or style name to the list box.
1410 for (i = start; i <= end; i++) {
1414 info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1416 * info may be NULL if we've just run off the end of the
1417 * relevant data. We must still do a processing pass in
1418 * that situation, in case we had an unfinished font
1419 * record in progress.
1421 if (info && (info->flags &~ fs->filter_flags)) {
1422 info->styleindex = -1;
1423 continue; /* we're filtering out this font */
1425 if (!info || !started || strnullcasecmp(currcs, info->charset) ||
1426 strnullcasecmp(currstyle, info->style)) {
1428 * We've either finished a style/charset, or started a
1433 gtk_list_store_append(fs->style_model, &iter);
1434 gtk_list_store_set(fs->style_model, &iter,
1435 0, currstyle, 1, minpos, 2, maxpos+1,
1441 if (info->charset && strnullcasecmp(currcs, info->charset)) {
1442 gtk_list_store_append(fs->style_model, &iter);
1443 gtk_list_store_set(fs->style_model, &iter,
1444 0, info->charset, 1, -1, 2, -1,
1448 currcs = info->charset;
1449 currstyle = info->style;
1453 break; /* now we're done */
1454 info->styleindex = listindex;
1459 static const int unifontsel_default_sizes[] = { 10, 12, 14, 16, 20, 24, 32 };
1461 static void unifontsel_setup_sizelist(unifontsel_internal *fs,
1469 gtk_list_store_clear(fs->size_model);
1473 * Search through the font tree for anything matching our
1474 * current filter criteria. When we find one, add its font
1475 * name to the list box.
1477 for (i = start; i < end; i++) {
1478 info = (fontinfo *)index234(fs->fonts_by_selorder, i);
1479 if (info->flags &~ fs->filter_flags) {
1480 info->sizeindex = -1;
1481 continue; /* we're filtering out this font */
1484 sprintf(sizetext, "%d", info->size);
1485 info->sizeindex = listindex;
1486 gtk_list_store_append(fs->size_model, &iter);
1487 gtk_list_store_set(fs->size_model, &iter,
1488 0, sizetext, 1, i, 2, info->size, -1);
1496 for (j = 0; j < lenof(unifontsel_default_sizes); j++) {
1497 sprintf(sizetext, "%d", unifontsel_default_sizes[j]);
1498 gtk_list_store_append(fs->size_model, &iter);
1499 gtk_list_store_set(fs->size_model, &iter, 0, sizetext, 1, i,
1500 2, unifontsel_default_sizes[j], -1);
1507 static void unifontsel_set_filter_buttons(unifontsel_internal *fs)
1511 for (i = 0; i < lenof(fs->filter_buttons); i++) {
1512 int flagbit = GPOINTER_TO_INT(gtk_object_get_data
1513 (GTK_OBJECT(fs->filter_buttons[i]),
1515 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fs->filter_buttons[i]),
1516 !!(fs->filter_flags & flagbit));
1520 static void unifontsel_draw_preview_text(unifontsel_internal *fs)
1523 char *sizename = NULL;
1524 fontinfo *info = fs->selected;
1527 sizename = info->fontclass->scale_fontname
1528 (GTK_WIDGET(fs->u.window), info->realname, fs->selsize);
1529 font = info->fontclass->create(GTK_WIDGET(fs->u.window),
1530 sizename ? sizename : info->realname,
1531 FALSE, FALSE, 0, 0);
1535 if (fs->preview_pixmap) {
1536 GdkGC *gc = gdk_gc_new(fs->preview_pixmap);
1537 gdk_gc_set_foreground(gc, &fs->preview_bg);
1538 gdk_draw_rectangle(fs->preview_pixmap, gc, 1, 0, 0,
1539 fs->preview_width, fs->preview_height);
1540 gdk_gc_set_foreground(gc, &fs->preview_fg);
1543 * The pangram used here is rather carefully
1544 * constructed: it contains a sequence of very narrow
1545 * letters (`jil') and a pair of adjacent very wide
1548 * If the user selects a proportional font, it will be
1549 * coerced into fixed-width character cells when used
1550 * in the actual terminal window. We therefore display
1551 * it the same way in the preview pane, so as to show
1552 * it the way it will actually be displayed - and we
1553 * deliberately pick a pangram which will show the
1554 * resulting miskerning at its worst.
1556 * We aren't trying to sell people these fonts; we're
1557 * trying to let them make an informed choice. Better
1558 * that they find out the problems with using
1559 * proportional fonts in terminal windows here than
1560 * that they go to the effort of selecting their font
1561 * and _then_ realise it was a mistake.
1563 info->fontclass->draw_text(fs->preview_pixmap, gc, font,
1565 "bankrupt jilted showmen quiz convex fogey",
1566 41, FALSE, FALSE, font->width);
1567 info->fontclass->draw_text(fs->preview_pixmap, gc, font,
1568 0, font->ascent + font->height,
1569 "BANKRUPT JILTED SHOWMEN QUIZ CONVEX FOGEY",
1570 41, FALSE, FALSE, font->width);
1572 * The ordering of punctuation here is also selected
1573 * with some specific aims in mind. I put ` and '
1574 * together because some software (and people) still
1575 * use them as matched quotes no matter what Unicode
1576 * might say on the matter, so people can quickly
1577 * check whether they look silly in a candidate font.
1578 * The sequence #_@ is there to let people judge the
1579 * suitability of the underscore as an effectively
1580 * alphabetic character (since that's how it's often
1581 * used in practice, at least by programmers).
1583 info->fontclass->draw_text(fs->preview_pixmap, gc, font,
1584 0, font->ascent + font->height * 2,
1585 "0123456789!?,.:;<>()[]{}\\/`'\"+*-=~#_@|%&^$",
1586 42, FALSE, FALSE, font->width);
1589 gdk_window_invalidate_rect(fs->preview_area->window, NULL, FALSE);
1592 info->fontclass->destroy(font);
1597 static void unifontsel_select_font(unifontsel_internal *fs,
1598 fontinfo *info, int size, int leftlist,
1599 int size_is_explicit)
1603 GtkTreePath *treepath;
1606 fs->inhibit_response = TRUE;
1608 fs->selected = info;
1610 if (size_is_explicit)
1611 fs->intendedsize = size;
1613 gtk_widget_set_sensitive(fs->u.ok_button, TRUE);
1616 * Find the index of this fontinfo in the selorder list.
1619 findpos234(fs->fonts_by_selorder, info, NULL, &index);
1623 * Adjust the font selector flags and redo the font family
1624 * list box, if necessary.
1626 if (leftlist <= 0 &&
1627 (fs->filter_flags | info->flags) != fs->filter_flags) {
1628 fs->filter_flags |= info->flags;
1629 unifontsel_set_filter_buttons(fs);
1630 unifontsel_setup_familylist(fs);
1634 * Find the appropriate family name and select it in the list.
1636 assert(info->familyindex >= 0);
1637 treepath = gtk_tree_path_new_from_indices(info->familyindex, -1);
1638 gtk_tree_selection_select_path
1639 (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->family_list)),
1641 gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->family_list),
1642 treepath, NULL, FALSE, 0.0, 0.0);
1643 gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, treepath);
1644 gtk_tree_path_free(treepath);
1647 * Now set up the font style list.
1649 gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter,
1650 1, &minval, 2, &maxval, -1);
1652 unifontsel_setup_stylelist(fs, minval, maxval);
1655 * Find the appropriate style name and select it in the list.
1658 assert(info->styleindex >= 0);
1659 treepath = gtk_tree_path_new_from_indices(info->styleindex, -1);
1660 gtk_tree_selection_select_path
1661 (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->style_list)),
1663 gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->style_list),
1664 treepath, NULL, FALSE, 0.0, 0.0);
1665 gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->style_model),
1667 gtk_tree_path_free(treepath);
1670 * And set up the size list.
1672 gtk_tree_model_get(GTK_TREE_MODEL(fs->style_model), &iter,
1673 1, &minval, 2, &maxval, -1);
1675 unifontsel_setup_sizelist(fs, minval, maxval);
1678 * Find the appropriate size, and select it in the list.
1681 assert(info->sizeindex >= 0);
1682 treepath = gtk_tree_path_new_from_indices(info->sizeindex, -1);
1683 gtk_tree_selection_select_path
1684 (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->size_list)),
1686 gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
1687 treepath, NULL, FALSE, 0.0, 0.0);
1688 gtk_tree_path_free(treepath);
1692 for (j = 0; j < lenof(unifontsel_default_sizes); j++)
1693 if (unifontsel_default_sizes[j] == size) {
1694 treepath = gtk_tree_path_new_from_indices(j, -1);
1695 gtk_tree_view_set_cursor(GTK_TREE_VIEW(fs->size_list),
1696 treepath, NULL, FALSE);
1697 gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list),
1698 treepath, NULL, FALSE, 0.0,
1700 gtk_tree_path_free(treepath);
1705 * And set up the font size text entry box.
1709 sprintf(sizetext, "%d", size);
1710 gtk_entry_set_text(GTK_ENTRY(fs->size_entry), sizetext);
1714 unifontsel_setup_sizelist(fs, 0, 0);
1715 gtk_entry_set_text(GTK_ENTRY(fs->size_entry), "");
1719 * Grey out the font size edit box if we're not using a
1722 gtk_entry_set_editable(GTK_ENTRY(fs->size_entry), fs->selected->size == 0);
1723 gtk_widget_set_sensitive(fs->size_entry, fs->selected->size == 0);
1725 unifontsel_draw_preview_text(fs);
1727 fs->inhibit_response = FALSE;
1730 static void unifontsel_button_toggled(GtkToggleButton *tb, gpointer data)
1732 unifontsel_internal *fs = (unifontsel_internal *)data;
1733 int newstate = gtk_toggle_button_get_active(tb);
1735 int flagbit = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(tb),
1739 newflags = fs->filter_flags | flagbit;
1741 newflags = fs->filter_flags & ~flagbit;
1743 if (fs->filter_flags != newflags) {
1744 fs->filter_flags = newflags;
1745 unifontsel_setup_familylist(fs);
1749 static void unifontsel_add_entry(void *ctx, const char *realfontname,
1750 const char *family, const char *charset,
1751 const char *style, const char *stylekey,
1752 int size, int flags,
1753 const struct unifont_vtable *fontclass)
1755 unifontsel_internal *fs = (unifontsel_internal *)ctx;
1760 totalsize = sizeof(fontinfo) + strlen(realfontname) +
1761 (family ? strlen(family) : 0) + (charset ? strlen(charset) : 0) +
1762 (style ? strlen(style) : 0) + (stylekey ? strlen(stylekey) : 0) + 10;
1763 info = (fontinfo *)smalloc(totalsize);
1764 info->fontclass = fontclass;
1765 p = (char *)info + sizeof(fontinfo);
1767 strcpy(p, realfontname);
1774 info->family = NULL;
1780 info->charset = NULL;
1789 strcpy(p, stylekey);
1792 info->stylekey = NULL;
1793 assert(p - (char *)info <= totalsize);
1795 info->flags = flags;
1796 info->index = count234(fs->fonts_by_selorder);
1799 * It's just conceivable that a misbehaving font enumerator
1800 * might tell us about the same font real name more than once,
1801 * in which case we should silently drop the new one.
1803 if (add234(fs->fonts_by_realname, info) != info) {
1808 * However, we should never get a duplicate key in the
1809 * selorder tree, because the index field carefully
1810 * disambiguates otherwise identical records.
1812 add234(fs->fonts_by_selorder, info);
1815 static fontinfo *update_for_intended_size(unifontsel_internal *fs,
1818 fontinfo info2, *below, *above;
1822 * Copy the info structure. This doesn't copy its dynamic
1823 * string fields, but that's unimportant because all we're
1824 * going to do is to adjust the size field and use it in one
1828 info2.size = fs->intendedsize;
1831 * Search in the tree to find the fontinfo structure which
1832 * best approximates the size the user last requested.
1834 below = findrelpos234(fs->fonts_by_selorder, &info2, NULL,
1836 above = index234(fs->fonts_by_selorder, pos+1);
1839 * See if we've found it exactly, which is an easy special
1840 * case. If we have, it'll be in `below' and not `above',
1841 * because we did a REL234_LE rather than REL234_LT search.
1843 if (!fontinfo_selorder_compare(&info2, below))
1847 * Now we've either found two suitable fonts, one smaller and
1848 * one larger, or we're at one or other extreme end of the
1849 * scale. Find out which, by NULLing out either of below and
1850 * above if it differs from this one in any respect but size
1851 * (and the disambiguating index field). Bear in mind, also,
1852 * that either one might _already_ be NULL if we're at the
1853 * extreme ends of the font list.
1856 info2.size = below->size;
1857 info2.index = below->index;
1858 if (fontinfo_selorder_compare(&info2, below))
1862 info2.size = above->size;
1863 info2.index = above->index;
1864 if (fontinfo_selorder_compare(&info2, above))
1869 * Now return whichever of above and below is non-NULL, if
1870 * that's unambiguous.
1878 * And now we really do have to make a choice about whether to
1879 * round up or down. We'll do it by rounding to nearest,
1880 * breaking ties by rounding up.
1882 if (above->size - fs->intendedsize <= fs->intendedsize - below->size)
1888 static void family_changed(GtkTreeSelection *treeselection, gpointer data)
1890 unifontsel_internal *fs = (unifontsel_internal *)data;
1891 GtkTreeModel *treemodel;
1892 GtkTreeIter treeiter;
1896 if (fs->inhibit_response) /* we made this change ourselves */
1899 if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1902 gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
1903 info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1904 info = update_for_intended_size(fs, info);
1906 return; /* _shouldn't_ happen unless font list is completely funted */
1908 fs->selsize = fs->intendedsize; /* font is scalable */
1909 unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize,
1913 static void style_changed(GtkTreeSelection *treeselection, gpointer data)
1915 unifontsel_internal *fs = (unifontsel_internal *)data;
1916 GtkTreeModel *treemodel;
1917 GtkTreeIter treeiter;
1921 if (fs->inhibit_response) /* we made this change ourselves */
1924 if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1927 gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1);
1929 return; /* somehow a charset heading got clicked */
1930 info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1931 info = update_for_intended_size(fs, info);
1933 return; /* _shouldn't_ happen unless font list is completely funted */
1935 fs->selsize = fs->intendedsize; /* font is scalable */
1936 unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize,
1940 static void size_changed(GtkTreeSelection *treeselection, gpointer data)
1942 unifontsel_internal *fs = (unifontsel_internal *)data;
1943 GtkTreeModel *treemodel;
1944 GtkTreeIter treeiter;
1948 if (fs->inhibit_response) /* we made this change ourselves */
1951 if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
1954 gtk_tree_model_get(treemodel, &treeiter, 1, &minval, 2, &size, -1);
1955 info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1956 unifontsel_select_font(fs, info, info->size ? info->size : size, 3, TRUE);
1959 static void size_entry_changed(GtkEditable *ed, gpointer data)
1961 unifontsel_internal *fs = (unifontsel_internal *)data;
1965 if (fs->inhibit_response) /* we made this change ourselves */
1968 text = gtk_entry_get_text(GTK_ENTRY(ed));
1972 assert(fs->selected->size == 0);
1973 unifontsel_select_font(fs, fs->selected, size, 3, TRUE);
1977 static void alias_resolve(GtkTreeView *treeview, GtkTreePath *path,
1978 GtkTreeViewColumn *column, gpointer data)
1980 unifontsel_internal *fs = (unifontsel_internal *)data;
1982 int minval, newsize;
1983 fontinfo *info, *newinfo;
1986 if (fs->inhibit_response) /* we made this change ourselves */
1989 gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, path);
1990 gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter, 1,&minval, -1);
1991 info = (fontinfo *)index234(fs->fonts_by_selorder, minval);
1993 newname = info->fontclass->canonify_fontname
1994 (GTK_WIDGET(fs->u.window), info->realname, &newsize, TRUE);
1995 newinfo = find234(fs->fonts_by_realname, (char *)newname,
1996 fontinfo_realname_find);
1999 return; /* font name not in our index */
2000 if (newinfo == info)
2001 return; /* didn't change under canonification => not an alias */
2002 unifontsel_select_font(fs, newinfo,
2003 newinfo->size ? newinfo->size : newsize,
2008 static gint unifontsel_expose_area(GtkWidget *widget, GdkEventExpose *event,
2011 unifontsel_internal *fs = (unifontsel_internal *)data;
2013 if (fs->preview_pixmap) {
2014 gdk_draw_pixmap(widget->window,
2015 widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
2017 event->area.x, event->area.y,
2018 event->area.x, event->area.y,
2019 event->area.width, event->area.height);
2024 static gint unifontsel_configure_area(GtkWidget *widget,
2025 GdkEventConfigure *event, gpointer data)
2027 unifontsel_internal *fs = (unifontsel_internal *)data;
2028 int ox, oy, nx, ny, x, y;
2031 * Enlarge the pixmap, but never shrink it.
2033 ox = fs->preview_width;
2034 oy = fs->preview_height;
2037 if (x > ox || y > oy) {
2038 if (fs->preview_pixmap)
2039 gdk_pixmap_unref(fs->preview_pixmap);
2041 nx = (x > ox ? x : ox);
2042 ny = (y > oy ? y : oy);
2043 fs->preview_pixmap = gdk_pixmap_new(widget->window, nx, ny, -1);
2044 fs->preview_width = nx;
2045 fs->preview_height = ny;
2047 unifontsel_draw_preview_text(fs);
2050 gdk_window_invalidate_rect(widget->window, NULL, FALSE);
2055 unifontsel *unifontsel_new(const char *wintitle)
2057 unifontsel_internal *fs = snew(unifontsel_internal);
2058 GtkWidget *table, *label, *w, *ww, *scroll;
2059 GtkListStore *model;
2060 GtkTreeViewColumn *column;
2061 int lists_height, preview_height, font_width, style_width, size_width;
2064 fs->inhibit_response = FALSE;
2068 * Invent some magic size constants.
2071 label = gtk_label_new("Quite Long Font Name (Foundry)");
2072 gtk_widget_size_request(label, &req);
2073 font_width = req.width;
2074 lists_height = 14 * req.height;
2075 preview_height = 5 * req.height;
2076 gtk_label_set_text(GTK_LABEL(label), "Italic Extra Condensed");
2077 gtk_widget_size_request(label, &req);
2078 style_width = req.width;
2079 gtk_label_set_text(GTK_LABEL(label), "48000");
2080 gtk_widget_size_request(label, &req);
2081 size_width = req.width;
2082 #if GTK_CHECK_VERSION(2,10,0)
2083 g_object_ref_sink(label);
2084 g_object_unref(label);
2086 gtk_object_sink(GTK_OBJECT(label));
2091 * Create the dialog box and initialise the user-visible
2092 * fields in the returned structure.
2094 fs->u.user_data = NULL;
2095 fs->u.window = GTK_WINDOW(gtk_dialog_new());
2096 gtk_window_set_title(fs->u.window, wintitle);
2097 fs->u.cancel_button = gtk_dialog_add_button
2098 (GTK_DIALOG(fs->u.window), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
2099 fs->u.ok_button = gtk_dialog_add_button
2100 (GTK_DIALOG(fs->u.window), GTK_STOCK_OK, GTK_RESPONSE_OK);
2101 gtk_widget_grab_default(fs->u.ok_button);
2104 * Now set up the internal fields, including in particular all
2105 * the controls that actually allow the user to select fonts.
2107 table = gtk_table_new(8, 3, FALSE);
2108 gtk_widget_show(table);
2109 gtk_table_set_col_spacings(GTK_TABLE(table), 8);
2110 /* GtkAlignment seems to be the simplest way to put padding round things */
2111 w = gtk_alignment_new(0, 0, 1, 1);
2112 gtk_alignment_set_padding(GTK_ALIGNMENT(w), 8, 8, 8, 8);
2113 gtk_container_add(GTK_CONTAINER(w), table);
2115 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(fs->u.window)->vbox),
2118 label = gtk_label_new_with_mnemonic("_Font:");
2119 gtk_widget_show(label);
2120 gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2121 gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_FILL, 0, 0, 0);
2124 * The Font list box displays only a string, but additionally
2125 * stores two integers which give the limits within the
2126 * tree234 of the font entries covered by this list entry.
2128 model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
2129 w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2130 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2131 gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2133 column = gtk_tree_view_column_new_with_attributes
2134 ("Font", gtk_cell_renderer_text_new(),
2135 "text", 0, (char *)NULL);
2136 gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2137 gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2138 g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2139 "changed", G_CALLBACK(family_changed), fs);
2140 g_signal_connect(G_OBJECT(w), "row-activated",
2141 G_CALLBACK(alias_resolve), fs);
2143 scroll = gtk_scrolled_window_new(NULL, NULL);
2144 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
2146 gtk_container_add(GTK_CONTAINER(scroll), w);
2147 gtk_widget_show(scroll);
2148 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2149 GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2150 gtk_widget_set_size_request(scroll, font_width, lists_height);
2151 gtk_table_attach(GTK_TABLE(table), scroll, 0, 1, 1, 3, GTK_FILL,
2152 GTK_EXPAND | GTK_FILL, 0, 0);
2153 fs->family_model = model;
2154 fs->family_list = w;
2156 label = gtk_label_new_with_mnemonic("_Style:");
2157 gtk_widget_show(label);
2158 gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2159 gtk_table_attach(GTK_TABLE(table), label, 1, 2, 0, 1, GTK_FILL, 0, 0, 0);
2162 * The Style list box can contain insensitive elements
2163 * (character set headings for server-side fonts), so we add
2164 * an extra column to the list store to hold that information.
2166 model = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT,
2168 w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2169 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2170 gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2172 column = gtk_tree_view_column_new_with_attributes
2173 ("Style", gtk_cell_renderer_text_new(),
2174 "text", 0, "sensitive", 3, (char *)NULL);
2175 gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2176 gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2177 g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2178 "changed", G_CALLBACK(style_changed), fs);
2180 scroll = gtk_scrolled_window_new(NULL, NULL);
2181 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
2183 gtk_container_add(GTK_CONTAINER(scroll), w);
2184 gtk_widget_show(scroll);
2185 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2186 GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2187 gtk_widget_set_size_request(scroll, style_width, lists_height);
2188 gtk_table_attach(GTK_TABLE(table), scroll, 1, 2, 1, 3, GTK_FILL,
2189 GTK_EXPAND | GTK_FILL, 0, 0);
2190 fs->style_model = model;
2193 label = gtk_label_new_with_mnemonic("Si_ze:");
2194 gtk_widget_show(label);
2195 gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
2196 gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, GTK_FILL, 0, 0, 0);
2199 * The Size label attaches primarily to a text input box so
2200 * that the user can select a size of their choice. The list
2201 * of available sizes is secondary.
2203 fs->size_entry = w = gtk_entry_new();
2204 gtk_label_set_mnemonic_widget(GTK_LABEL(label), w);
2205 gtk_widget_set_size_request(w, size_width, -1);
2207 gtk_table_attach(GTK_TABLE(table), w, 2, 3, 1, 2, GTK_FILL, 0, 0, 0);
2208 g_signal_connect(G_OBJECT(w), "changed", G_CALLBACK(size_entry_changed),
2211 model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
2212 w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
2213 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2215 column = gtk_tree_view_column_new_with_attributes
2216 ("Size", gtk_cell_renderer_text_new(),
2217 "text", 0, (char *)NULL);
2218 gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
2219 gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2220 g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))),
2221 "changed", G_CALLBACK(size_changed), fs);
2223 scroll = gtk_scrolled_window_new(NULL, NULL);
2224 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
2226 gtk_container_add(GTK_CONTAINER(scroll), w);
2227 gtk_widget_show(scroll);
2228 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2229 GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
2230 gtk_table_attach(GTK_TABLE(table), scroll, 2, 3, 2, 3, GTK_FILL,
2231 GTK_EXPAND | GTK_FILL, 0, 0);
2232 fs->size_model = model;
2238 fs->preview_area = gtk_drawing_area_new();
2239 fs->preview_pixmap = NULL;
2240 fs->preview_width = 0;
2241 fs->preview_height = 0;
2242 fs->preview_fg.pixel = fs->preview_bg.pixel = 0;
2243 fs->preview_fg.red = fs->preview_fg.green = fs->preview_fg.blue = 0x0000;
2244 fs->preview_bg.red = fs->preview_bg.green = fs->preview_bg.blue = 0xFFFF;
2245 gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_fg,
2247 gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_bg,
2249 gtk_signal_connect(GTK_OBJECT(fs->preview_area), "expose_event",
2250 GTK_SIGNAL_FUNC(unifontsel_expose_area), fs);
2251 gtk_signal_connect(GTK_OBJECT(fs->preview_area), "configure_event",
2252 GTK_SIGNAL_FUNC(unifontsel_configure_area), fs);
2253 gtk_widget_set_size_request(fs->preview_area, 1, preview_height);
2254 gtk_widget_show(fs->preview_area);
2255 ww = fs->preview_area;
2256 w = gtk_frame_new(NULL);
2257 gtk_container_add(GTK_CONTAINER(w), ww);
2260 /* GtkAlignment seems to be the simplest way to put padding round things */
2261 w = gtk_alignment_new(0, 0, 1, 1);
2262 gtk_alignment_set_padding(GTK_ALIGNMENT(w), 8, 8, 8, 8);
2263 gtk_container_add(GTK_CONTAINER(w), ww);
2266 w = gtk_frame_new("Preview of font");
2267 gtk_container_add(GTK_CONTAINER(w), ww);
2269 gtk_table_attach(GTK_TABLE(table), w, 0, 3, 3, 4,
2270 GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 8);
2273 w = gtk_check_button_new_with_label("Show client-side fonts");
2274 gtk_object_set_data(GTK_OBJECT(w), "user-data",
2275 GINT_TO_POINTER(FONTFLAG_CLIENTSIDE));
2276 gtk_signal_connect(GTK_OBJECT(w), "toggled",
2277 GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2279 fs->filter_buttons[i++] = w;
2280 gtk_table_attach(GTK_TABLE(table), w, 0, 3, 4, 5, GTK_FILL, 0, 0, 0);
2281 w = gtk_check_button_new_with_label("Show server-side fonts");
2282 gtk_object_set_data(GTK_OBJECT(w), "user-data",
2283 GINT_TO_POINTER(FONTFLAG_SERVERSIDE));
2284 gtk_signal_connect(GTK_OBJECT(w), "toggled",
2285 GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2287 fs->filter_buttons[i++] = w;
2288 gtk_table_attach(GTK_TABLE(table), w, 0, 3, 5, 6, GTK_FILL, 0, 0, 0);
2289 w = gtk_check_button_new_with_label("Show server-side font aliases");
2290 gtk_object_set_data(GTK_OBJECT(w), "user-data",
2291 GINT_TO_POINTER(FONTFLAG_SERVERALIAS));
2292 gtk_signal_connect(GTK_OBJECT(w), "toggled",
2293 GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2295 fs->filter_buttons[i++] = w;
2296 gtk_table_attach(GTK_TABLE(table), w, 0, 3, 6, 7, GTK_FILL, 0, 0, 0);
2297 w = gtk_check_button_new_with_label("Show non-monospaced fonts");
2298 gtk_object_set_data(GTK_OBJECT(w), "user-data",
2299 GINT_TO_POINTER(FONTFLAG_NONMONOSPACED));
2300 gtk_signal_connect(GTK_OBJECT(w), "toggled",
2301 GTK_SIGNAL_FUNC(unifontsel_button_toggled), fs);
2303 fs->filter_buttons[i++] = w;
2304 gtk_table_attach(GTK_TABLE(table), w, 0, 3, 7, 8, GTK_FILL, 0, 0, 0);
2306 assert(i == lenof(fs->filter_buttons));
2307 fs->filter_flags = FONTFLAG_CLIENTSIDE | FONTFLAG_SERVERSIDE;
2308 unifontsel_set_filter_buttons(fs);
2311 * Go and find all the font names, and set up our master font
2314 fs->fonts_by_realname = newtree234(fontinfo_realname_compare);
2315 fs->fonts_by_selorder = newtree234(fontinfo_selorder_compare);
2316 for (i = 0; i < lenof(unifont_types); i++)
2317 unifont_types[i]->enum_fonts(GTK_WIDGET(fs->u.window),
2318 unifontsel_add_entry, fs);
2321 * And set up the initial font names list.
2323 unifontsel_setup_familylist(fs);
2325 fs->selected = NULL;
2326 fs->selsize = fs->intendedsize = 13; /* random default */
2327 gtk_widget_set_sensitive(fs->u.ok_button, FALSE);
2329 return (unifontsel *)fs;
2332 void unifontsel_destroy(unifontsel *fontsel)
2334 unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2337 if (fs->preview_pixmap)
2338 gdk_pixmap_unref(fs->preview_pixmap);
2340 freetree234(fs->fonts_by_selorder);
2341 while ((info = delpos234(fs->fonts_by_realname, 0)) != NULL)
2343 freetree234(fs->fonts_by_realname);
2345 gtk_widget_destroy(GTK_WIDGET(fs->u.window));
2349 void unifontsel_set_name(unifontsel *fontsel, const char *fontname)
2351 unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2352 int i, start, end, size;
2353 const char *fontname2 = NULL;
2357 * Provide a default if given an empty or null font name.
2359 if (!fontname || !*fontname)
2360 fontname = "fixed"; /* Pango zealots might prefer "Monospace 12" */
2363 * Call the canonify_fontname function.
2365 fontname = unifont_do_prefix(fontname, &start, &end);
2366 for (i = start; i < end; i++) {
2367 fontname2 = unifont_types[i]->canonify_fontname
2368 (GTK_WIDGET(fs->u.window), fontname, &size, FALSE);
2373 return; /* font name not recognised */
2376 * Now look up the canonified font name in our index.
2378 info = find234(fs->fonts_by_realname, (char *)fontname2,
2379 fontinfo_realname_find);
2382 * If we've found the font, and its size field is either
2383 * correct or zero (the latter indicating a scalable font),
2384 * then we're done. Otherwise, try looking up the original
2385 * font name instead.
2387 if (!info || (info->size != size && info->size != 0)) {
2388 info = find234(fs->fonts_by_realname, (char *)fontname,
2389 fontinfo_realname_find);
2390 if (!info || info->size != size)
2391 return; /* font name not in our index */
2395 * Now we've got a fontinfo structure and a font size, so we
2396 * know everything we need to fill in all the fields in the
2399 unifontsel_select_font(fs, info, size, 0, TRUE);
2402 char *unifontsel_get_name(unifontsel *fontsel)
2404 unifontsel_internal *fs = (unifontsel_internal *)fontsel;
2410 if (fs->selected->size == 0) {
2411 name = fs->selected->fontclass->scale_fontname
2412 (GTK_WIDGET(fs->u.window), fs->selected->realname, fs->selsize);
2417 return dupstr(fs->selected->realname);