Debian Codegraph @

pTk/mTk/unix/tkUnixFont.c

raw symbols SCIP
1 /*
2 * tkUnixFont.c --
3 *
4 * Contains the Unix implementation of the platform-independant
5 * font package interface.
6 *
7 * Copyright (c) 1996-1997 Sun Microsystems, Inc.
8 *
9 * See the file "license.terms" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 *
12 * RCS: @(#) $Id: tkUnixFont.c,v 1.18.2.3 2003/10/29 01:07:46 hobbs Exp $
13 */
14
15 #include "tkUnixInt.h"
16 #include "tkFont.h"
17
18 #ifndef USE_XFT_FONTS
19
20 #include <netinet/in.h> /* for htons() prototype */
21 #include <arpa/inet.h> /* inet_ntoa() */
22
23 /*
24 * The preferred font encodings.
25 */
26
27 static CONST char *encodingList[] = {
28 "iso8859-1", "jis0208", "jis0212", "ksc5601", "big5", "ucs-2be", NULL
29 };
30
31 /*
32 * The following structure represents a font family. It is assumed that
33 * all screen fonts constructed from the same "font family" share certain
34 * properties; all screen fonts with the same "font family" point to a
35 * shared instance of this structure. The most important shared property
36 * is the character existence metrics, used to determine if a screen font
37 * can display a given Unicode character.
38 *
39 * Under Unix, there are three attributes that uniquely identify a "font
40 * family": the foundry, face name, and charset.
41
42 * FIXME: the existance assumption above does _NOT_ hold for UNICODE fonts
43 * e.g. -misc-fixed-*-*-*-*-*-*-*-*-*-*-iso10646-1 has smaller repertoire
44 * in bold/italic than in regular forms
45
46 */
47
48 #if TCL_UTF_MAX <= 3
49 #define FONTMAP_SHIFT 8
50 #else
51 #define FONTMAP_SHIFT 10
52 #endif
53
54 #define FONTMAP_PAGES (1 << (sizeof(Tcl_UniChar)*8 - FONTMAP_SHIFT))
55 #define FONTMAP_BITSPERPAGE (1 << FONTMAP_SHIFT)
56
57 typedef struct FontFamily {
58 struct FontFamily *nextPtr; /* Next in list of all known font families. */
59 int refCount; /* How many SubFonts are referring to this
60 * FontFamily. When the refCount drops to
61 * zero, this FontFamily may be freed. */
62 /*
63 * Key.
64 */
65
66 Tk_Uid foundry; /* Foundry key for this FontFamily. */
67 Tk_Uid faceName; /* Face name key for this FontFamily. */
68 Tcl_Encoding encoding; /* Encoding key for this FontFamily. */
69
70 /*
71 * Derived properties.
72 */
73
74 int isTwoByteFont; /* 1 if this is a double-byte font, 0
75 * otherwise. */
76 char *fontMap[FONTMAP_PAGES];
77 /* Two-level sparse table used to determine
78 * quickly if the specified character exists.
79 * As characters are encountered, more pages
80 * in this table are dynamically alloced. The
81 * contents of each page is a bitmask
82 * consisting of FONTMAP_BITSPERPAGE bits,
83 * representing whether this font can be used
84 * to display the given character at the
85 * corresponding bit position. The high bits
86 * of the character are used to pick which
87 * page of the table is used. */
88 } FontFamily;
89
90 /*
91 * The following structure encapsulates an individual screen font. A font
92 * object is made up of however many SubFonts are necessary to display a
93 * stream of multilingual characters.
94 */
95
96 typedef struct SubFont {
97 char **fontMap; /* Pointer to font map from the FontFamily,
98 * cached here to save a dereference. */
99 XFontStruct *fontStructPtr; /* The specific screen font that will be
100 * used when displaying/measuring chars
101 * belonging to the FontFamily. */
102 FontFamily *familyPtr; /* The FontFamily for this SubFont. */
103 char *name; /* Name used (malloc-ed) */
104 int trigger; /* Character which caused us to load this subfont */
105 } SubFont;
106
107 /*
108 * The following structure represents Unix's implementation of a font
109 * object.
110 */
111
112 #define SUBFONT_SPACE 3
113 #define BASE_CHARS 256
114
115 typedef struct UnixFont {
116 TkFont font; /* Stuff used by generic font package. Must
117 * be first in structure. */
118 SubFont staticSubFonts[SUBFONT_SPACE];
119 /* Builtin space for a limited number of
120 * SubFonts. */
121 int numSubFonts; /* Length of following array. */
122 SubFont *subFontArray; /* Array of SubFonts that have been loaded
123 * in order to draw/measure all the characters
124 * encountered by this font so far. All fonts
125 * start off with one SubFont initialized by
126 * AllocFont() from the original set of font
127 * attributes. Usually points to
128 * staticSubFonts, but may point to malloced
129 * space if there are lots of SubFonts. */
130 SubFont controlSubFont; /* Font to use to display control-character
131 * expansions. */
132
133 Display *display; /* Display that owns font. */
134 int pixelSize; /* Original pixel size used when font was
135 * constructed. */
136 TkXLFDAttributes xa; /* Additional attributes that specify the
137 * preferred foundry and encoding to use when
138 * constructing additional SubFonts. */
139 int widths[BASE_CHARS]; /* Widths of first 256 chars in the base
140 * font, for handling common case. */
141 int underlinePos; /* Offset from baseline to origin of
142 * underline bar (used when drawing underlined
143 * font) (pixels). */
144 int barHeight; /* Height of underline or overstrike bar
145 * (used when drawing underlined or strikeout
146 * font) (pixels). */
147 } UnixFont;
148
149 /*
150 * The following structure and definition is used to keep track of the
151 * alternative names for various encodings. Asking for an encoding that
152 * matches one of the alias patterns will result in actually getting the
153 * encoding by its real name.
154 */
155
156 typedef struct EncodingAlias {
157 char *realName; /* The real name of the encoding to load if
158 * the provided name matched the pattern. */
159 char *aliasPattern; /* Pattern for encoding name, of the form
160 * that is acceptable to Tcl_StringMatch. */
161 } EncodingAlias;
162
163 /*
164 * Just some utility structures used for passing around values in helper
165 * procedures.
166 */
167
168 typedef struct FontAttributes {
169 TkFontAttributes fa;
170 TkXLFDAttributes xa;
171 } FontAttributes;
172
173
174 typedef struct ThreadSpecificData {
175 FontFamily *fontFamilyList; /* The list of font families that are
176 * currently loaded. As screen fonts
177 * are loaded, this list grows to hold
178 * information about what characters
179 * exist in each font family. */
180 FontFamily controlFamily; /* FontFamily used to handle control
181 * character expansions. The encoding
182 * of this FontFamily converts UTF-8 to
183 * backslashed escape sequences. */
184 } ThreadSpecificData;
185 static Tcl_ThreadDataKey dataKey;
186
187 /*
188 * The set of builtin encoding alises to convert the XLFD names for the
189 * encodings into the names expected by the Tcl encoding package.
190 */
191
192 static EncodingAlias encodingAliases[] = {
193 {"gb2312-raw", "gb2312*"},
194 {"big5", "big5*"},
195 {"cns11643-1", "cns11643*-1"},
196 {"cns11643-1", "cns11643*.1-0"},
197 {"cns11643-2", "cns11643*-2"},
198 {"cns11643-2", "cns11643*.2-0"},
199 {"jis0201", "jisx0201*"},
200 {"jis0201", "jisx0202*"},
201 {"jis0208", "jisc6226*"},
202 {"jis0208", "jisx0208*"},
203 {"jis0212", "jisx0212*"},
204 {"tis620", "tis620*"},
205 {"ksc5601", "ksc5601*"},
206 {"dingbats", "*dingbats"},
207 {"ucs-2be", "iso10646-1"},
208 {NULL, NULL}
209 };
210
211 /*
212 * Procedures used only in this file.
213 */
214
215 static void FontPkgCleanup _ANSI_ARGS_((ClientData clientData));
216 static FontFamily * AllocFontFamily _ANSI_ARGS_((Display *display,
217 XFontStruct *fontStructPtr, int base));
218 static SubFont * CanUseFallback _ANSI_ARGS_((UnixFont *fontPtr,
219 CONST char *fallbackName, int ch,
220 SubFont **fixSubFontPtrPtr));
221 static SubFont * CanUseFallbackWithAliases _ANSI_ARGS_((
222 UnixFont *fontPtr, char *fallbackName,
223 int ch, Tcl_DString *nameTriedPtr,
224 SubFont **fixSubFontPtrPtr));
225 static int ControlUtfProc _ANSI_ARGS_((ClientData clientData,
226 CONST char *src, int srcLen, int flags,
227 Tcl_EncodingState *statePtr, char *dst,
228 int dstLen, int *srcReadPtr, int *dstWrotePtr,
229 int *dstCharsPtr));
230 static XFontStruct * CreateClosestFont _ANSI_ARGS_((Tk_Window tkwin,
231 CONST TkFontAttributes *faPtr,
232 CONST TkXLFDAttributes *xaPtr));
233 static SubFont * FindSubFontForChar _ANSI_ARGS_((UnixFont *fontPtr,
234 int ch, SubFont **fixSubFontPtrPtr));
235 static void FontMapInsert _ANSI_ARGS_((SubFont *subFontPtr,
236 int ch));
237 static void FontMapLoadPage _ANSI_ARGS_((SubFont *subFontPtr,
238 int row));
239 static int FontMapLookup _ANSI_ARGS_((SubFont *subFontPtr,
240 int ch));
241 static void FreeFontFamily _ANSI_ARGS_((FontFamily *afPtr));
242 static CONST char * GetEncodingAlias _ANSI_ARGS_((CONST char *name));
243 static int GetFontAttributes _ANSI_ARGS_((Display *display,
244 XFontStruct *fontStructPtr, FontAttributes *faPtr));
245 static XFontStruct * GetScreenFont _ANSI_ARGS_((Display *display,
246 FontAttributes *wantPtr, char **nameList,
247 int bestIdx[], unsigned int bestScore[], int *indexPtr));
248 static XFontStruct * GetSystemFont _ANSI_ARGS_((Display *display));
249 static int IdentifySymbolEncodings _ANSI_ARGS_((
250 FontAttributes *faPtr));
251 static void InitFont _ANSI_ARGS_((Tk_Window tkwin,
252 XFontStruct *fontStructPtr, UnixFont *fontPtr));
253 static void InitSubFont _ANSI_ARGS_((Display *display,
254 XFontStruct *fontStructPtr, int base,
255 SubFont *subFontPtr));
256 static char ** ListFonts _ANSI_ARGS_((Display *display,
257 CONST char *faceName, int *numNamesPtr));
258 static char ** ListFontOrAlias _ANSI_ARGS_((Display *display,
259 CONST char *faceName, int *numNamesPtr));
260 static unsigned int RankAttributes _ANSI_ARGS_((FontAttributes *wantPtr,
261 FontAttributes *gotPtr, int ch, const char *name));
262 static void ReleaseFont _ANSI_ARGS_((UnixFont *fontPtr));
263 static void ReleaseSubFont _ANSI_ARGS_((Display *display,
264 SubFont *subFontPtr));
265 static int SeenName _ANSI_ARGS_((CONST char *name,
266 Tcl_DString *dsPtr));
267 static int Ucs2beToUtfProc _ANSI_ARGS_((ClientData clientData,
268 CONST char *src, int srcLen, int flags,
269 Tcl_EncodingState *statePtr, char *dst, int dstLen,
270 int *srcReadPtr, int *dstWrotePtr,
271 int *dstCharsPtr));
272 static int UtfToUcs2beProc _ANSI_ARGS_((ClientData clientData,
273 CONST char *src, int srcLen, int flags,
274 Tcl_EncodingState *statePtr, char *dst, int dstLen,
275 int *srcReadPtr, int *dstWrotePtr,
276 int *dstCharsPtr));
277
278
279 /*
280 *-------------------------------------------------------------------------
281 *
282 * FontPkgCleanup --
283 *
284 * This procedure is called when an application is created. It
285 * initializes all the structures that are used by the
286 * platform-dependent code on a per application basis.
287 *
288 * Results:
289 * None.
290 *
291 * Side effects:
292 * Releases thread-specific resources used by font pkg.
293 *
294 *-------------------------------------------------------------------------
295 */
296
297 static void
298 FontPkgCleanup(ClientData clientData)
299 {
300 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
301 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
302
303 if (tsdPtr->controlFamily.encoding != NULL) {
304 FontFamily *familyPtr = &tsdPtr->controlFamily;
305 int i;
306
307 Tcl_FreeEncoding(familyPtr->encoding);
308 for (i = 0; i < FONTMAP_PAGES; i++) {
309 if (familyPtr->fontMap[i] != NULL) {
310 ckfree(familyPtr->fontMap[i]);
311 }
312 }
313 tsdPtr->controlFamily.encoding = NULL;
314 }
315 }
316
317 /*
318 *-------------------------------------------------------------------------
319 *
320 * TkpFontPkgInit --
321 *
322 * This procedure is called when an application is created. It
323 * initializes all the structures that are used by the
324 * platform-dependent code on a per application basis.
325 *
326 * Results:
327 * None.
328 *
329 * Side effects:
330 * None.
331 *
332 *-------------------------------------------------------------------------
333 */
334
335 void
336 TkpFontPkgInit(mainPtr)
337 TkMainInfo *mainPtr; /* The application being created. */
338 {
339 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
340 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
341 SubFont dummy;
342 int i;
343
344 if (tsdPtr->controlFamily.encoding == NULL) {
345 tsdPtr->controlFamily.refCount = 2;
346 tsdPtr->controlFamily.encoding = Lang_CreateEncoding(
347 "X11ControlChars", /* encodingName */
348 ControlUtfProc, /* toUtfProc */
349 ControlUtfProc, /* fromUtfProc */
350 NULL, /* freeProc */
351 NULL, /* clientData */
352 0 /* nullSize */
353 );
354 tsdPtr->controlFamily.isTwoByteFont = 0;
355
356 dummy.familyPtr = &tsdPtr->controlFamily;
357 dummy.fontMap = tsdPtr->controlFamily.fontMap;
358 for (i = 0x00; i < 0x20; i++) {
359 FontMapInsert(&dummy, i);
360 FontMapInsert(&dummy, i + 0x80);
361 }
362
363 /*
364 * UCS-2BE is unicode in big-endian format.
365 * It is used in iso10646 fonts.
366 */
367
368 #ifndef _LANG
369 type.encodingName = "ucs-2be";
370 type.toUtfProc = Ucs2beToUtfProc;
371 type.fromUtfProc = UtfToUcs2beProc;
372 type.freeProc = NULL;
373 type.clientData = NULL;
374 type.nullSize = 2;
375 Tcl_CreateEncoding(&type);
376 Tcl_CreateThreadExitHandler(FontPkgCleanup, NULL);
377 #else
378 Lang_CreateEncoding(
379 "ucs-2be",
380 Ucs2beToUtfProc,
381 UtfToUcs2beProc,
382 NULL,
383 NULL,
384 2);
385
386 #endif
387 }
388 }
389
390 /*
391 *-------------------------------------------------------------------------
392 *
393 * ControlUtfProc --
394 *
395 * Convert from UTF-8 into the ASCII expansion of a control
396 * character.
397 *
398 * Results:
399 * Returns TCL_OK if conversion was successful.
400 *
401 * Side effects:
402 * None.
403 *
404 *-------------------------------------------------------------------------
405 */
406
407 static int
408 ControlUtfProc(clientData, src, srcLen, flags, statePtr, dst, dstLen,
409 srcReadPtr, dstWrotePtr, dstCharsPtr)
410 ClientData clientData; /* Not used. */
411 CONST char *src; /* Source string in UTF-8. */
412 int srcLen; /* Source string length in bytes. */
413 int flags; /* Conversion control flags. */
414 Tcl_EncodingState *statePtr;/* Place for conversion routine to store
415 * state information used during a piecewise
416 * conversion. Contents of statePtr are
417 * initialized and/or reset by conversion
418 * routine under control of flags argument. */
419 char *dst; /* Output buffer in which converted string
420 * is stored. */
421 int dstLen; /* The maximum length of output buffer in
422 * bytes. */
423 int *srcReadPtr; /* Filled with the number of bytes from the
424 * source string that were converted. This
425 * may be less than the original source length
426 * if there was a problem converting some
427 * source characters. */
428 int *dstWrotePtr; /* Filled with the number of bytes that were
429 * stored in the output buffer as a result of
430 * the conversion. */
431 int *dstCharsPtr; /* Filled with the number of characters that
432 * correspond to the bytes stored in the
433 * output buffer. */
434 {
435 CONST char *srcStart, *srcEnd;
436 char *dstStart, *dstEnd;
437 Tcl_UniChar ch;
438 int result;
439 static char hexChars[] = "0123456789abcdef";
440 static char mapChars[] = {
441 0, 0, 0, 0, 0, 0, 0,
442 'a', 'b', 't', 'n', 'v', 'f', 'r'
443 };
444
445 result = TCL_OK;
446
447 srcStart = src;
448 srcEnd = src + srcLen;
449
450 dstStart = dst;
451 dstEnd = dst + dstLen - 6;
452
453 for ( ; src < srcEnd; ) {
454 if (dst > dstEnd) {
455 result = TCL_CONVERT_NOSPACE;
456 break;
457 }
458 src += Tcl_UtfToUniChar(src, &ch);
459 dst[0] = '\\';
460 if ((ch < sizeof(mapChars)) && (mapChars[ch] != 0)) {
461 dst[1] = mapChars[ch];
462 dst += 2;
463 } else if (ch < 256) {
464 dst[1] = 'x';
465 dst[2] = hexChars[(ch >> 4) & 0xf];
466 dst[3] = hexChars[ch & 0xf];
467 dst += 4;
468 } else {
469 dst[1] = 'u';
470 dst[2] = hexChars[(ch >> 12) & 0xf];
471 dst[3] = hexChars[(ch >> 8) & 0xf];
472 dst[4] = hexChars[(ch >> 4) & 0xf];
473 dst[5] = hexChars[ch & 0xf];
474 dst += 6;
475 }
476 }
477 *srcReadPtr = src - srcStart;
478 *dstWrotePtr = dst - dstStart;
479 *dstCharsPtr = dst - dstStart;
480 return result;
481 }
482
483 /*
484 *-------------------------------------------------------------------------
485 *
486 * Ucs2beToUtfProc --
487 *
488 * Convert from UCS-2BE (big-endian 16-bit Unicode) to UTF-8.
489 *
490 * Results:
491 * Returns TCL_OK if conversion was successful.
492 *
493 * Side effects:
494 * None.
495 *
496 *-------------------------------------------------------------------------
497 */
498
499 static int
500 Ucs2beToUtfProc(clientData, src, srcLen, flags, statePtr, dst, dstLen,
501 srcReadPtr, dstWrotePtr, dstCharsPtr)
502 ClientData clientData; /* Not used. */
503 CONST char *src; /* Source string in Unicode. */
504 int srcLen; /* Source string length in bytes. */
505 int flags; /* Conversion control flags. */
506 Tcl_EncodingState *statePtr;/* Place for conversion routine to store
507 * state information used during a piecewise
508 * conversion. Contents of statePtr are
509 * initialized and/or reset by conversion
510 * routine under control of flags argument. */
511 char *dst; /* Output buffer in which converted string
512 * is stored. */
513 int dstLen; /* The maximum length of output buffer in
514 * bytes. */
515 int *srcReadPtr; /* Filled with the number of bytes from the
516 * source string that were converted. This
517 * may be less than the original source length
518 * if there was a problem converting some
519 * source characters. */
520 int *dstWrotePtr; /* Filled with the number of bytes that were
521 * stored in the output buffer as a result of
522 * the conversion. */
523 int *dstCharsPtr; /* Filled with the number of characters that
524 * correspond to the bytes stored in the
525 * output buffer. */
526 {
527 CONST Tcl_UniChar *wSrc, *wSrcStart, *wSrcEnd;
528 char *dstEnd, *dstStart;
529 int result, numChars;
530
531 result = TCL_OK;
532 if ((srcLen % sizeof(Tcl_UniChar)) != 0) {
533 result = TCL_CONVERT_MULTIBYTE;
534 srcLen /= sizeof(Tcl_UniChar);
535 srcLen *= sizeof(Tcl_UniChar);
536 }
537
538 wSrc = (Tcl_UniChar *) src;
539
540 wSrcStart = (Tcl_UniChar *) src;
541 wSrcEnd = (Tcl_UniChar *) (src + srcLen);
542
543 dstStart = dst;
544 dstEnd = dst + dstLen - TCL_UTF_MAX;
545
546 for (numChars = 0; wSrc < wSrcEnd; numChars++) {
547 if (dst > dstEnd) {
548 result = TCL_CONVERT_NOSPACE;
549 break;
550 }
551 /*
552 * On a little-endian machine (Intel) the UCS-2BE is in the
553 * wrong byte-order in comparison to "unicode", which is
554 * in native host order.
555 */
556 dst += Tcl_UniCharToUtf(htons(*wSrc), dst);
557 wSrc++;
558 }
559
560 *srcReadPtr = (char *) wSrc - (char *) wSrcStart;
561 *dstWrotePtr = dst - dstStart;
562 *dstCharsPtr = numChars;
563 return result;
564 }
565
566 /*
567 *-------------------------------------------------------------------------
568 *
569 * UtfToUcs2beProc --
570 *
571 * Convert from UTF-8 to UCS-2BE.
572 *
573 * Results:
574 * Returns TCL_OK if conversion was successful.
575 *
576 * Side effects:
577 * None.
578 *
579 *-------------------------------------------------------------------------
580 */
581
582 static int
583 UtfToUcs2beProc(clientData, src, srcLen, flags, statePtr, dst, dstLen,
584 srcReadPtr, dstWrotePtr, dstCharsPtr)
585 ClientData clientData; /* TableEncodingData that specifies encoding. */
586 CONST char *src; /* Source string in UTF-8. */
587 int srcLen; /* Source string length in bytes. */
588 int flags; /* Conversion control flags. */
589 Tcl_EncodingState *statePtr;/* Place for conversion routine to store
590 * state information used during a piecewise
591 * conversion. Contents of statePtr are
592 * initialized and/or reset by conversion
593 * routine under control of flags argument. */
594 char *dst; /* Output buffer in which converted string
595 * is stored. */
596 int dstLen; /* The maximum length of output buffer in
597 * bytes. */
598 int *srcReadPtr; /* Filled with the number of bytes from the
599 * source string that were converted. This
600 * may be less than the original source length
601 * if there was a problem converting some
602 * source characters. */
603 int *dstWrotePtr; /* Filled with the number of bytes that were
604 * stored in the output buffer as a result of
605 * the conversion. */
606 int *dstCharsPtr; /* Filled with the number of characters that
607 * correspond to the bytes stored in the
608 * output buffer. */
609 {
610 CONST char *srcStart, *srcEnd, *srcClose;
611 Tcl_UniChar *wDst, *wDstStart, *wDstEnd;
612 int result, numChars;
613
614 srcStart = src;
615 srcEnd = src + srcLen;
616 srcClose = srcEnd;
617 if ((flags & TCL_ENCODING_END) == 0) {
618 srcClose -= TCL_UTF_MAX;
619 }
620
621 wDst = (Tcl_UniChar *) dst;
622 wDstStart = (Tcl_UniChar *) dst;
623 wDstEnd = (Tcl_UniChar *) (dst + dstLen - sizeof(Tcl_UniChar));
624
625 result = TCL_OK;
626 for (numChars = 0; src < srcEnd; numChars++) {
627 if ((src > srcClose) && (!Tcl_UtfCharComplete(src, srcEnd - src))) {
628 /*
629 * If there is more string to follow, this will ensure that the
630 * last UTF-8 character in the source buffer hasn't been cut off.
631 */
632
633 result = TCL_CONVERT_MULTIBYTE;
634 break;
635 }
636 if (wDst > wDstEnd) {
637 result = TCL_CONVERT_NOSPACE;
638 break;
639 }
640 src += Tcl_UtfToUniChar(src, wDst);
641 /*
642 * Byte swap for little-endian machines.
643 */
644 *wDst = htons(*wDst);
645 wDst++;
646 }
647 *srcReadPtr = src - srcStart;
648 *dstWrotePtr = (char *) wDst - (char *) wDstStart;
649 *dstCharsPtr = numChars;
650 return result;
651 }
652
653 /*
654 *---------------------------------------------------------------------------
655 *
656 * TkpGetNativeFont --
657 *
658 * Map a platform-specific native font name to a TkFont.
659 *
660 * Results:
661 * The return value is a pointer to a TkFont that represents the
662 * native font. If a native font by the given name could not be
663 * found, the return value is NULL.
664 *
665 * Every call to this procedure returns a new TkFont structure,
666 * even if the name has already been seen before. The caller should
667 * call TkpDeleteFont() when the font is no longer needed.
668 *
669 * The caller is responsible for initializing the memory associated
670 * with the generic TkFont when this function returns and releasing
671 * the contents of the generic TkFont before calling TkpDeleteFont().
672 *
673 * Side effects:
674 * Memory allocated.
675 *
676 *---------------------------------------------------------------------------
677 */
678
679 TkFont *
680 TkpGetNativeFont(tkwin, name)
681 Tk_Window tkwin; /* For display where font will be used. */
682 CONST char *name; /* Platform-specific font name. */
683 {
684 UnixFont *fontPtr;
685 XFontStruct *fontStructPtr;
686 FontAttributes fa;
687 CONST char *p;
688 int hasSpace, dashes, hasWild;
689
690 /*
691 * The behavior of X when given a name that isn't an XLFD is unspecified.
692 * For example, Exceed 6 returns a valid font for any random string. This
693 * is awkward since system names have higher priority than the other Tk
694 * font syntaxes. So, we need to perform a quick sanity check on the
695 * name and fail if it looks suspicious. We fail if the name:
696 * - contains a space immediately before a dash
697 * - contains a space, but no '*' characters and fewer than 14 dashes
698 */
699
700 hasSpace = dashes = hasWild = 0;
701 for (p = name; *p != '\0'; p++) {
702 if (*p == ' ') {
703 if (p[1] == '-') {
704 return NULL;
705 }
706 hasSpace = 1;
707 } else if (*p == '-') {
708 dashes++;
709 } else if (*p == '*') {
710 hasWild = 1;
711 }
712 }
713 if ((dashes < 14) && !hasWild && hasSpace) {
714 return NULL;
715 }
716
717 fontStructPtr = XLoadQueryFont(Tk_Display(tkwin), name);
718 if (fontStructPtr == NULL) {
719 /*
720 * Handle all names that look like XLFDs here. Otherwise, when
721 * TkpGetFontFromAttributes is called from generic code, any
722 * foundry or encoding information specified in the XLFD will have
723 * been parsed out and lost. But make sure we don't have an
724 * "-option value" string since TkFontParseXLFD would return a
725 * false success when attempting to parse it.
726 */
727
728 if (name[0] == '-') {
729 if (name[1] != '*') {
730 char *dash;
731
732 dash = strchr(name + 1, '-');
733 if ((dash == NULL) || (isspace(UCHAR(dash[-1])))) {
734 return NULL;
735 }
736 }
737 } else if (name[0] != '*') {
738 return NULL;
739 }
740 if (TkFontParseXLFD(name, &fa.fa, &fa.xa) != TCL_OK) {
741 return NULL;
742 }
743 fontStructPtr = CreateClosestFont(tkwin, &fa.fa, &fa.xa);
744 }
745 fontPtr = (UnixFont *) ckalloc(sizeof(UnixFont));
746 InitFont(tkwin, fontStructPtr, fontPtr);
747
748 return (TkFont *) fontPtr;
749 }
750
751 /*
752 *---------------------------------------------------------------------------
753 *
754 * TkpGetFontFromAttributes --
755 *
756 * Given a desired set of attributes for a font, find a font with
757 * the closest matching attributes.
758 *
759 * Results:
760 * The return value is a pointer to a TkFont that represents the
761 * font with the desired attributes. If a font with the desired
762 * attributes could not be constructed, some other font will be
763 * substituted automatically.
764 *
765 * Every call to this procedure returns a new TkFont structure,
766 * even if the specified attributes have already been seen before.
767 * The caller should call TkpDeleteFont() to free the platform-
768 * specific data when the font is no longer needed.
769 *
770 * The caller is responsible for initializing the memory associated
771 * with the generic TkFont when this function returns and releasing
772 * the contents of the generic TkFont before calling TkpDeleteFont().
773 *
774 * Side effects:
775 * Memory allocated.
776 *
777 *---------------------------------------------------------------------------
778 */
779 TkFont *
780 TkpGetFontFromAttributes(tkFontPtr, tkwin, faPtr)
781 TkFont *tkFontPtr; /* If non-NULL, store the information in
782 * this existing TkFont structure, rather than
783 * allocating a new structure to hold the
784 * font; the existing contents of the font
785 * will be released. If NULL, a new TkFont
786 * structure is allocated. */
787 Tk_Window tkwin; /* For display where font will be used. */
788 CONST TkFontAttributes *faPtr;
789 /* Set of attributes to match. */
790 {
791 UnixFont *fontPtr;
792 TkXLFDAttributes xa;
793 XFontStruct *fontStructPtr;
794
795 TkInitXLFDAttributes(&xa);
796 fontStructPtr = CreateClosestFont(tkwin, faPtr, &xa);
797
798 fontPtr = (UnixFont *) tkFontPtr;
799 if (fontPtr == NULL) {
800 fontPtr = (UnixFont *) ckalloc(sizeof(UnixFont));
801 } else {
802 ReleaseFont(fontPtr);
803 }
804 InitFont(tkwin, fontStructPtr, fontPtr);
805
806 fontPtr->font.fa.underline = faPtr->underline;
807 fontPtr->font.fa.overstrike = faPtr->overstrike;
808
809 return (TkFont *) fontPtr;
810 }
811
812 /*
813 *---------------------------------------------------------------------------
814 *
815 * TkpDeleteFont --
816 *
817 * Called to release a font allocated by TkpGetNativeFont() or
818 * TkpGetFontFromAttributes(). The caller should have already
819 * released the fields of the TkFont that are used exclusively by
820 * the generic TkFont code.
821 *
822 * Results:
823 * None.
824 *
825 * Side effects:
826 * TkFont is deallocated.
827 *
828 *---------------------------------------------------------------------------
829 */
830
831 void
832 TkpDeleteFont(tkFontPtr)
833 TkFont *tkFontPtr; /* Token of font to be deleted. */
834 {
835 UnixFont *fontPtr;
836
837 fontPtr = (UnixFont *) tkFontPtr;
838 ReleaseFont(fontPtr);
839 }
840
841 /*
842 *---------------------------------------------------------------------------
843 *
844 * TkpGetFontFamilies --
845 *
846 * Return information about the font families that are available
847 * on the display of the given window.
848 *
849 * Results:
850 * Modifies interp's result object to hold a list of all the available
851 * font families.
852 *
853 * Side effects:
854 * None.
855 *
856 *---------------------------------------------------------------------------
857 */
858
859 void
860 TkpGetFontFamilies(interp, tkwin)
861 Tcl_Interp *interp; /* Interp to hold result. */
862 Tk_Window tkwin; /* For display to query. */
863 {
864 int i, new, numNames;
865 char *family;
866 Tcl_HashTable familyTable;
867 Tcl_HashEntry *hPtr;
868 Tcl_HashSearch search;
869 char **nameList;
870 Tcl_Obj *resultPtr, *strPtr;
871
872 resultPtr = Tcl_GetObjResult(interp);
873
874 Tcl_InitHashTable(&familyTable, TCL_STRING_KEYS);
875 nameList = ListFonts(Tk_Display(tkwin), "*", &numNames);
876 for (i = 0; i < numNames; i++) {
877 family = strchr(nameList[i] + 1, '-') + 1;
878 strchr(family, '-')[0] = '\0';
879 Tcl_CreateHashEntry(&familyTable, family, &new);
880 }
881 XFreeFontNames(nameList);
882
883 hPtr = Tcl_FirstHashEntry(&familyTable, &search);
884 while (hPtr != NULL) {
885 strPtr = Tcl_NewStringObj(Tcl_GetHashKey(&familyTable, hPtr), -1);
886 Tcl_ListObjAppendElement(NULL, resultPtr, strPtr);
887 hPtr = Tcl_NextHashEntry(&search);
888 }
889
890 Tcl_DeleteHashTable(&familyTable);
891 }
892
893 /*
894 *-------------------------------------------------------------------------
895 *
896 * TkpGetSubFonts --
897 *
898 * A function used by the testing package for querying the actual
899 * screen fonts that make up a font object.
900 *
901 * Results:
902 * Modifies interp's result object to hold a list containing the
903 * names of the screen fonts that make up the given font object.
904 *
905 * Side effects:
906 * None.
907 *
908 *-------------------------------------------------------------------------
909 */
910
911 void
912 TkpGetSubFonts(interp, tkfont)
913 Tcl_Interp *interp;
914 Tk_Font tkfont;
915 {
916 int i;
917 Tcl_Obj *objv[4];
918 Tcl_Obj *resultPtr, *listPtr;
919 UnixFont *fontPtr;
920 FontFamily *familyPtr;
921
922 resultPtr = Tcl_GetObjResult(interp);
923 fontPtr = (UnixFont *) tkfont;
924 for (i = 0; i < fontPtr->numSubFonts; i++) {
925 familyPtr = fontPtr->subFontArray[i].familyPtr;
926 objv[0] = Tcl_NewStringObj(familyPtr->faceName, -1);
927 objv[1] = Tcl_NewStringObj(familyPtr->foundry, -1);
928 objv[2] = Tcl_NewStringObj(Tcl_GetEncodingName(familyPtr->encoding), -1);
929 objv[3] = Tcl_NewIntObj(fontPtr->subFontArray[i].trigger);
930 listPtr = Tcl_NewListObj(4, objv);
931 if (fontPtr->subFontArray[i].name) {
932 Tcl_ListObjAppendElement(interp, listPtr,
933 Tcl_NewStringObj(fontPtr->subFontArray[i].name, -1));
934 }
935 Tcl_ListObjAppendElement(interp, resultPtr, listPtr);
936 }
937 }
938
939 /*
940 *---------------------------------------------------------------------------
941 *
942 * Tk_MeasureChars --
943 *
944 * Determine the number of characters from the string that will fit
945 * in the given horizontal span. The measurement is done under the
946 * assumption that Tk_DrawChars() will be used to actually display
947 * the characters.
948 *
949 * Results:
950 * The return value is the number of bytes from source that
951 * fit into the span that extends from 0 to maxLength. *lengthPtr is
952 * filled with the x-coordinate of the right edge of the last
953 * character that did fit.
954 *
955 * Side effects:
956 * None.
957 *
958 *---------------------------------------------------------------------------
959 */
960
961 int
962 Tk_MeasureChars(tkfont, source, numBytes, maxLength, flags, lengthPtr)
963 Tk_Font tkfont; /* Font in which characters will be drawn. */
964 CONST char *source; /* UTF-8 string to be displayed. Need not be
965 * '\0' terminated. */
966 int numBytes; /* Maximum number of bytes to consider
967 * from source string. */
968 int maxLength; /* If >= 0, maxLength specifies the longest
969 * permissible line length in pixels; don't
970 * consider any character that would cross
971 * this x-position. If < 0, then line length
972 * is unbounded and the flags argument is
973 * ignored. */
974 int flags; /* Various flag bits OR-ed together:
975 * TK_PARTIAL_OK means include the last char
976 * which only partially fit on this line.
977 * TK_WHOLE_WORDS means stop on a word
978 * boundary, if possible.
979 * TK_AT_LEAST_ONE means return at least one
980 * character even if no characters fit. */
981 int *lengthPtr; /* Filled with x-location just after the
982 * terminating character. */
983 {
984 UnixFont *fontPtr;
985 SubFont *lastSubFontPtr;
986 int curX, curByte;
987
988 /*
989 * Unix does not use kerning or fractional character widths when
990 * displaying text on the screen. So that means we can safely measure
991 * individual characters or spans of characters and add up the widths
992 * w/o any "off-by-one-pixel" errors.
993 */
994
995 fontPtr = (UnixFont *) tkfont;
996
997 lastSubFontPtr = &fontPtr->subFontArray[0];
998
999 if (numBytes == 0) {
1000 curX = 0;
1001 curByte = 0;
1002 } else if (maxLength < 0) {
1003 CONST char *p, *end, *next;
1004 Tcl_UniChar ch;
1005 SubFont *thisSubFontPtr;
1006 FontFamily *familyPtr;
1007 Tcl_DString runString;
1008
1009 /*
1010 * A three step process:
1011 * 1. Find a contiguous range of characters that can all be
1012 * represented by a single screen font.
1013 * 2. Convert those chars to the encoding of that font.
1014 * 3. Measure converted chars.
1015 */
1016
1017 curX = 0;
1018 end = source + numBytes;
1019 for (p = source; p < end; ) {
1020 next = p + Tcl_UtfToUniChar(p, &ch);
1021 thisSubFontPtr = FindSubFontForChar(fontPtr, ch, &lastSubFontPtr);
1022 if (thisSubFontPtr != lastSubFontPtr) {
1023 familyPtr = lastSubFontPtr->familyPtr;
1024 Tcl_UtfToExternalDString(familyPtr->encoding, source,
1025 p - source, &runString);
1026 if (familyPtr->isTwoByteFont) {
1027 curX += XTextWidth16(lastSubFontPtr->fontStructPtr,
1028 (XChar2b *) Tcl_DStringValue(&runString),
1029 Tcl_DStringLength(&runString) / 2);
1030 } else {
1031 curX += XTextWidth(lastSubFontPtr->fontStructPtr,
1032 Tcl_DStringValue(&runString),
1033 Tcl_DStringLength(&runString));
1034 }
1035 Tcl_DStringFree(&runString);
1036 lastSubFontPtr = thisSubFontPtr;
1037 source = p;
1038 }
1039 p = next;
1040 }
1041 familyPtr = lastSubFontPtr->familyPtr;
1042 Tcl_UtfToExternalDString(familyPtr->encoding, source, p - source,
1043 &runString);
1044 if (familyPtr->isTwoByteFont) {
1045 curX += XTextWidth16(lastSubFontPtr->fontStructPtr,
1046 (XChar2b *) Tcl_DStringValue(&runString),
1047 Tcl_DStringLength(&runString) >> 1);
1048 } else {
1049 curX += XTextWidth(lastSubFontPtr->fontStructPtr,
1050 Tcl_DStringValue(&runString),
1051 Tcl_DStringLength(&runString));
1052 }
1053 Tcl_DStringFree(&runString);
1054 curByte = numBytes;
1055 } else {
1056 CONST char *p, *end, *next, *term;
1057 int newX, termX, sawNonSpace, dstWrote;
1058 Tcl_UniChar ch;
1059 FontFamily *familyPtr;
1060 char buf[16];
1061
1062 /*
1063 * How many chars will fit in the space allotted?
1064 * This first version may be inefficient because it measures
1065 * every character individually.
1066 */
1067
1068 next = source + Tcl_UtfToUniChar(source, &ch);
1069 newX = curX = termX = 0;
1070
1071 term = source;
1072 end = source + numBytes;
1073
1074 sawNonSpace = (ch > 255) || !isspace(ch);
1075 familyPtr = lastSubFontPtr->familyPtr;
1076 for (p = source; ; ) {
1077 if ((ch < BASE_CHARS) && (fontPtr->widths[ch] != 0)) {
1078 newX += fontPtr->widths[ch];
1079 } else {
1080 lastSubFontPtr = FindSubFontForChar(fontPtr, ch, NULL);
1081 familyPtr = lastSubFontPtr->familyPtr;
1082 Tcl_UtfToExternal(NULL, familyPtr->encoding, p, next - p,
1083 0, NULL, buf, sizeof(buf), NULL, &dstWrote, NULL);
1084 if (familyPtr->isTwoByteFont) {
1085 newX += XTextWidth16(lastSubFontPtr->fontStructPtr,
1086 (XChar2b *) buf, dstWrote >> 1);
1087 } else {
1088 newX += XTextWidth(lastSubFontPtr->fontStructPtr, buf,
1089 dstWrote);
1090 }
1091 }
1092 if (newX > maxLength) {
1093 break;
1094 }
1095 curX = newX;
1096 p = next;
1097 if (p >= end) {
1098 term = end;
1099 termX = curX;
1100 break;
1101 }
1102
1103 next += Tcl_UtfToUniChar(next, &ch);
1104 if ((ch < 256) && isspace(ch)) {
1105 if (sawNonSpace) {
1106 term = p;
1107 termX = curX;
1108 sawNonSpace = 0;
1109 }
1110 } else {
1111 sawNonSpace = 1;
1112 }
1113 }
1114
1115 /*
1116 * P points to the first character that doesn't fit in the desired
1117 * span. Use the flags to figure out what to return.
1118 */
1119
1120 if ((flags & TK_PARTIAL_OK) && (p < end) && (curX < maxLength)) {
1121 /*
1122 * Include the first character that didn't quite fit in the desired
1123 * span. The width returned will include the width of that extra
1124 * character.
1125 */
1126
1127 curX = newX;
1128 p += Tcl_UtfToUniChar(p, &ch);
1129 }
1130 if ((flags & TK_AT_LEAST_ONE) && (term == source) && (p < end)) {
1131 term = p;
1132 termX = curX;
1133 if (term == source) {
1134 term += Tcl_UtfToUniChar(term, &ch);
1135 termX = newX;
1136 }
1137 } else if ((p >= end) || !(flags & TK_WHOLE_WORDS)) {
1138 term = p;
1139 termX = curX;
1140 }
1141
1142 curX = termX;
1143 curByte = term - source;
1144 }
1145
1146 *lengthPtr = curX;
1147 return curByte;
1148 }
1149
1150 /*
1151 *---------------------------------------------------------------------------
1152 *
1153 * Tk_DrawChars --
1154 *
1155 * Draw a string of characters on the screen. Tk_DrawChars()
1156 * expands control characters that occur in the string to
1157 * \xNN sequences.
1158 *
1159 * Results:
1160 * None.
1161 *
1162 * Side effects:
1163 * Information gets drawn on the screen.
1164 *
1165 *---------------------------------------------------------------------------
1166 */
1167
1168 void
1169 Tk_DrawChars(display, drawable, gc, tkfont, source, numBytes, x, y)
1170 Display *display; /* Display on which to draw. */
1171 Drawable drawable; /* Window or pixmap in which to draw. */
1172 GC gc; /* Graphics context for drawing characters. */
1173 Tk_Font tkfont; /* Font in which characters will be drawn;
1174 * must be the same as font used in GC. */
1175 CONST char *source; /* UTF-8 string to be displayed. Need not be
1176 * '\0' terminated. All Tk meta-characters
1177 * (tabs, control characters, and newlines)
1178 * should be stripped out of the string that
1179 * is passed to this function. If they are
1180 * not stripped out, they will be displayed as
1181 * regular printing characters. */
1182 int numBytes; /* Number of bytes in string. */
1183 int x, y; /* Coordinates at which to place origin of
1184 * string when drawing. */
1185 {
1186 UnixFont *fontPtr;
1187 SubFont *thisSubFontPtr, *lastSubFontPtr;
1188 Tcl_DString runString;
1189 CONST char *p, *end, *next;
1190 int xStart, needWidth, window_width, do_width;
1191 Tcl_UniChar ch;
1192 FontFamily *familyPtr;
1193 #ifdef TK_DRAW_CHAR_XWINDOW_CHECK
1194 int rx, ry;
1195 unsigned int width, height, border_width, depth;
1196 Drawable root;
1197 #endif
1198
1199 fontPtr = (UnixFont *) tkfont;
1200 lastSubFontPtr = &fontPtr->subFontArray[0];
1201
1202 xStart = x;
1203
1204 #ifdef TK_DRAW_CHAR_XWINDOW_CHECK
1205 /*
1206 * Get the window width so we can abort drawing outside of the window
1207 */
1208 if (XGetGeometry(display, drawable, &root, &rx, &ry, &width, &height,
1209 &border_width, &depth) == False) {
1210 window_width = INT_MAX;
1211 } else {
1212 window_width = width;
1213 }
1214 #else
1215 /*
1216 * This is used by default until we find a solution that doesn't
1217 * round-trip to the X server (need to get Tk cached window width).
1218 */
1219 window_width = 32768;
1220 #endif
1221
1222 end = source + numBytes;
1223 needWidth = fontPtr->font.fa.underline + fontPtr->font.fa.overstrike;
1224 for (p = source; p <= end; ) {
1225 if (p < end) {
1226 next = p + Tcl_UtfToUniChar(p, &ch);
1227 thisSubFontPtr = FindSubFontForChar(fontPtr, ch, &lastSubFontPtr);
1228 } else {
1229 next = p + 1;
1230 thisSubFontPtr = lastSubFontPtr;
1231 }
1232 if ((thisSubFontPtr != lastSubFontPtr)
1233 || (p == end) || (p-source > 200)) {
1234 if (p > source) {
1235 do_width = (needWidth || (p != end)) ? 1 : 0;
1236 familyPtr = lastSubFontPtr->familyPtr;
1237
1238 Tcl_UtfToExternalDString(familyPtr->encoding, source,
1239 p - source, &runString);
1240 if (familyPtr->isTwoByteFont) {
1241 XDrawString16(display, drawable, gc, x, y,
1242 (XChar2b *) Tcl_DStringValue(&runString),
1243 Tcl_DStringLength(&runString) / 2);
1244 if (do_width) {
1245 x += XTextWidth16(lastSubFontPtr->fontStructPtr,
1246 (XChar2b *) Tcl_DStringValue(&runString),
1247 Tcl_DStringLength(&runString) / 2);
1248 }
1249 } else {
1250 XDrawString(display, drawable, gc, x, y,
1251 Tcl_DStringValue(&runString),
1252 Tcl_DStringLength(&runString));
1253 if (do_width) {
1254 x += XTextWidth(lastSubFontPtr->fontStructPtr,
1255 Tcl_DStringValue(&runString),
1256 Tcl_DStringLength(&runString));
1257 }
1258 }
1259 Tcl_DStringFree(&runString);
1260 }
1261 lastSubFontPtr = thisSubFontPtr;
1262 source = p;
1263 XSetFont(display, gc, lastSubFontPtr->fontStructPtr->fid);
1264 if (x > window_width) {
1265 break;
1266 }
1267 }
1268 p = next;
1269 }
1270
1271 if (lastSubFontPtr != &fontPtr->subFontArray[0]) {
1272 XSetFont(display, gc, fontPtr->subFontArray[0].fontStructPtr->fid);
1273 }
1274
1275 if (fontPtr->font.fa.underline != 0) {
1276 XFillRectangle(display, drawable, gc, xStart,
1277 y + fontPtr->underlinePos,
1278 (unsigned) (x - xStart), (unsigned) fontPtr->barHeight);
1279 }
1280 if (fontPtr->font.fa.overstrike != 0) {
1281 y -= fontPtr->font.fm.descent + (fontPtr->font.fm.ascent) / 10;
1282 XFillRectangle(display, drawable, gc, xStart, y,
1283 (unsigned) (x - xStart), (unsigned) fontPtr->barHeight);
1284 }
1285 }
1286
1287
1288
1289
1290 /*
1291 *-------------------------------------------------------------------------
1292 *
1293 * CreateClosestFont --
1294 *
1295 * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes().
1296 * Given a set of font attributes, construct a close XFontStruct.
1297 * If requested face name is not available, automatically
1298 * substitutes an alias for requested face name. If encoding is
1299 * not specified (or the requested one is not available),
1300 * automatically chooses another encoding from the list of
1301 * preferred encodings. If the foundry is not specified (or
1302 * is not available) automatically prefers "adobe" foundry.
1303 * For all other attributes, if the requested value was not
1304 * available, the appropriate "close" value will be used.
1305 *
1306 * Results:
1307 * Return value is the XFontStruct that best matched the
1308 * requested attributes. The return value is never NULL; some
1309 * font will always be returned.
1310 *
1311 * Side effects:
1312 * None.
1313 *
1314 *-------------------------------------------------------------------------
1315 */
1316
1317 static XFontStruct *
1318 CreateClosestFont(tkwin, faPtr, xaPtr)
1319 Tk_Window tkwin; /* For display where font will be used. */
1320 CONST TkFontAttributes *faPtr;
1321 /* Set of generic attributes to match. */
1322 CONST TkXLFDAttributes *xaPtr;
1323 /* Set of X-specific attributes to match. */
1324 {
1325 FontAttributes want;
1326 char **nameList;
1327 int numNames, nameIdx;
1328 Display *display;
1329 XFontStruct *fontStructPtr;
1330 int bestIdx[2];
1331 unsigned int bestScore[2];
1332
1333 want.fa = *faPtr;
1334 want.xa = *xaPtr;
1335
1336 if (want.xa.foundry == NULL) {
1337 want.xa.foundry = Tk_GetUid("adobe");
1338 }
1339 if (want.fa.family == NULL) {
1340 want.fa.family = Tk_GetUid("fixed");
1341 }
1342 want.fa.size = -TkFontGetPixels(Tk_Screen(tkwin), faPtr->size);
1343 if (want.xa.charset == NULL || *want.xa.charset == '\0') {
1344 want.xa.charset = Tk_GetUid("iso8859-1"); /* locale. */
1345 }
1346
1347 display = Tk_Display(tkwin);
1348
1349 /*
1350 * Algorithm to get the closest font to the name requested.
1351 *
1352 * try fontname
1353 * try all aliases for fontname
1354 * foreach fallback for fontname
1355 * try the fallback
1356 * try all aliases for the fallback
1357 */
1358
1359 nameList = ListFontOrAlias(display, want.fa.family, &numNames);
1360 if (numNames == 0) {
1361 char ***fontFallbacks;
1362 int i, j;
1363 char *fallback;
1364
1365 fontFallbacks = TkFontGetFallbacks();
1366 for (i = 0; fontFallbacks[i] != NULL; i++) {
1367 for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) {
1368 if (strcasecmp(want.fa.family, fallback) == 0) {
1369 break;
1370 }
1371 }
1372 if (fallback != NULL) {
1373 for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) {
1374 nameList = ListFontOrAlias(display, fallback, &numNames);
1375 if (numNames != 0) {
1376 goto found;
1377 }
1378 }
1379 }
1380 }
1381 nameList = ListFonts(display, "fixed", &numNames);
1382 if (numNames == 0) {
1383 nameList = ListFonts(display, "*", &numNames);
1384 }
1385 if (numNames == 0) {
1386 return GetSystemFont(display);
1387 }
1388 }
1389 found:
1390 bestIdx[0] = -1;
1391 bestIdx[1] = -1;
1392 bestScore[0] = (unsigned int) -1;
1393 bestScore[1] = (unsigned int) -1;
1394 for (nameIdx = 0; nameIdx < numNames; nameIdx++) {
1395 FontAttributes got;
1396 int scalable;
1397 unsigned int score;
1398
1399 if (TkFontParseXLFD(nameList[nameIdx], &got.fa, &got.xa) != TCL_OK) {
1400 continue;
1401 }
1402 IdentifySymbolEncodings(&got);
1403 scalable = (got.fa.size == 0);
1404 score = RankAttributes(&want, &got, ' ', nameList[nameIdx]);
1405 if (score < bestScore[scalable]) {
1406 bestIdx[scalable] = nameIdx;
1407 bestScore[scalable] = score;
1408 }
1409 if (score == 0) {
1410 break;
1411 }
1412 }
1413
1414 fontStructPtr = GetScreenFont(display, &want, nameList, bestIdx, bestScore, &nameIdx);
1415 XFreeFontNames(nameList);
1416
1417 if (fontStructPtr == NULL) {
1418 return GetSystemFont(display);
1419 }
1420 return fontStructPtr;
1421 }
1422
1423 /*
1424 *---------------------------------------------------------------------------
1425 *
1426 * InitFont --
1427 *
1428 * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes().
1429 * Initializes the memory for a new UnixFont that wraps the
1430 * platform-specific data.
1431 *
1432 * The caller is responsible for initializing the fields of the
1433 * TkFont that are used exclusively by the generic TkFont code, and
1434 * for releasing those fields before calling TkpDeleteFont().
1435 *
1436 * Results:
1437 * Fills the WinFont structure.
1438 *
1439 * Side effects:
1440 * Memory allocated.
1441 *
1442 *---------------------------------------------------------------------------
1443 */
1444
1445 static void
1446 InitFont(tkwin, fontStructPtr, fontPtr)
1447 Tk_Window tkwin; /* For screen where font will be used. */
1448 XFontStruct *fontStructPtr; /* X information about font. */
1449 UnixFont *fontPtr; /* Filled with information constructed from
1450 * the above arguments. */
1451 {
1452 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1453 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1454 unsigned long value;
1455 int minHi, maxHi, minLo, maxLo, fixed, width, limit, i, n;
1456 FontAttributes fa;
1457 TkFontAttributes *faPtr;
1458 TkFontMetrics *fmPtr;
1459 SubFont *controlPtr, *subFontPtr;
1460 char *pageMap;
1461 Display *display;
1462
1463 /*
1464 * Get all font attributes and metrics.
1465 */
1466
1467 display = Tk_Display(tkwin);
1468 GetFontAttributes(display, fontStructPtr, &fa);
1469
1470 minHi = fontStructPtr->min_byte1;
1471 maxHi = fontStructPtr->max_byte1;
1472 minLo = fontStructPtr->min_char_or_byte2;
1473 maxLo = fontStructPtr->max_char_or_byte2;
1474
1475 fixed = 1;
1476 if (fontStructPtr->per_char != NULL) {
1477 width = 0;
1478 limit = (maxHi - minHi + 1) * (maxLo - minLo + 1);
1479 for (i = 0; i < limit; i++) {
1480 n = fontStructPtr->per_char[i].width;
1481 if (n != 0) {
1482 if (width == 0) {
1483 width = n;
1484 } else if (width != n) {
1485 fixed = 0;
1486 break;
1487 }
1488 }
1489 }
1490 }
1491
1492 fontPtr->font.fid = fontStructPtr->fid;
1493
1494 faPtr = &fontPtr->font.fa;
1495 faPtr->family = fa.fa.family;
1496 #if 0
1497 faPtr->size = TkFontGetPoints(Tk_Screen(tkwin), fa.fa.size);
1498 #else
1499 /* Actuals are in pixels - says NI-S */
1500 faPtr->size = -TkFontGetPixels(Tk_Screen(tkwin), fa.fa.size);
1501 #endif
1502 faPtr->weight = fa.fa.weight;
1503 faPtr->slant = fa.fa.slant;
1504 faPtr->underline = 0;
1505 faPtr->overstrike = 0;
1506
1507 fmPtr = &fontPtr->font.fm;
1508 fmPtr->ascent = fontStructPtr->ascent;
1509 fmPtr->descent = fontStructPtr->descent;
1510 fmPtr->maxWidth = fontStructPtr->max_bounds.width;
1511 fmPtr->fixed = fixed;
1512
1513 fontPtr->display = display;
1514 fontPtr->pixelSize = TkFontGetPixels(Tk_Screen(tkwin), fa.fa.size);
1515 fontPtr->xa = fa.xa;
1516
1517 fontPtr->numSubFonts = 1;
1518 fontPtr->subFontArray = fontPtr->staticSubFonts;
1519 InitSubFont(display, fontStructPtr, 1, &fontPtr->subFontArray[0]);
1520
1521 fontPtr->controlSubFont = fontPtr->subFontArray[0];
1522 subFontPtr = FindSubFontForChar(fontPtr, '0', NULL);
1523 controlPtr = &fontPtr->controlSubFont;
1524 controlPtr->fontStructPtr = subFontPtr->fontStructPtr;
1525 controlPtr->familyPtr = &tsdPtr->controlFamily;
1526 controlPtr->fontMap = tsdPtr->controlFamily.fontMap;
1527
1528 pageMap = fontPtr->subFontArray[0].fontMap[0];
1529 for (i = 0; i < 256; i++) {
1530 if ((minHi > 0) || (i < minLo) || (i > maxLo) ||
1531 (((pageMap[i >> 3] >> (i & 7)) & 1) == 0)) {
1532 n = 0;
1533 } else if (fontStructPtr->per_char == NULL) {
1534 n = fontStructPtr->max_bounds.width;
1535 } else {
1536 n = fontStructPtr->per_char[i - minLo].width;
1537 }
1538 fontPtr->widths[i] = n;
1539 }
1540
1541
1542 if (XGetFontProperty(fontStructPtr, XA_UNDERLINE_POSITION, &value)) {
1543 fontPtr->underlinePos = value;
1544 } else {
1545 /*
1546 * If the XA_UNDERLINE_POSITION property does not exist, the X
1547 * manual recommends using the following value:
1548 */
1549
1550 fontPtr->underlinePos = fontStructPtr->descent / 2;
1551 }
1552 fontPtr->barHeight = 0;
1553 if (XGetFontProperty(fontStructPtr, XA_UNDERLINE_THICKNESS, &value)) {
1554 fontPtr->barHeight = value;
1555 }
1556 if (fontPtr->barHeight == 0) {
1557 /*
1558 * If the XA_UNDERLINE_THICKNESS property does not exist, the X
1559 * manual recommends using the width of the stem on a capital
1560 * letter. I don't know of a way to get the stem width of a letter,
1561 * so guess and use 1/3 the width of a capital I.
1562 */
1563
1564 fontPtr->barHeight = fontPtr->widths['I'] / 3;
1565 if (fontPtr->barHeight == 0) {
1566 fontPtr->barHeight = 1;
1567 }
1568 }
1569 if (fontPtr->underlinePos + fontPtr->barHeight > fontStructPtr->descent) {
1570 /*
1571 * If this set of cobbled together values would cause the bottom of
1572 * the underline bar to stick below the descent of the font, jack
1573 * the underline up a bit higher.
1574 */
1575
1576 fontPtr->barHeight = fontStructPtr->descent - fontPtr->underlinePos;
1577 if (fontPtr->barHeight == 0) {
1578 fontPtr->underlinePos--;
1579 fontPtr->barHeight = 1;
1580 }
1581 }
1582 }
1583
1584 /*
1585 *-------------------------------------------------------------------------
1586 *
1587 * ReleaseFont --
1588 *
1589 * Called to release the unix-specific contents of a TkFont.
1590 * The caller is responsible for freeing the memory used by the
1591 * font itself.
1592 *
1593 * Results:
1594 * None.
1595 *
1596 * Side effects:
1597 * Memory is freed.
1598 *
1599 *---------------------------------------------------------------------------
1600 */
1601
1602 static void
1603 ReleaseFont(fontPtr)
1604 UnixFont *fontPtr; /* The font to delete. */
1605 {
1606 int i;
1607
1608 for (i = 0; i < fontPtr->numSubFonts; i++) {
1609 ReleaseSubFont(fontPtr->display, &fontPtr->subFontArray[i]);
1610 }
1611 if (fontPtr->subFontArray != fontPtr->staticSubFonts) {
1612 ckfree((char *) fontPtr->subFontArray);
1613 }
1614 }
1615
1616 /*
1617 *-------------------------------------------------------------------------
1618 *
1619 * InitSubFont --
1620 *
1621 * Wrap a screen font and load the FontFamily that represents
1622 * it. Used to prepare a SubFont so that characters can be mapped
1623 * from UTF-8 to the charset of the font.
1624 *
1625 * Results:
1626 * The subFontPtr is filled with information about the font.
1627 *
1628 * Side effects:
1629 * None.
1630 *
1631 *-------------------------------------------------------------------------
1632 */
1633
1634 static void
1635 InitSubFont(display, fontStructPtr, base, subFontPtr)
1636 Display *display; /* Display in which font will be used. */
1637 XFontStruct *fontStructPtr; /* The screen font. */
1638 int base; /* Non-zero if this SubFont is being used
1639 * as the base font for a font object. */
1640 SubFont *subFontPtr; /* Filled with SubFont constructed from
1641 * above attributes. */
1642 {
1643 subFontPtr->fontStructPtr = fontStructPtr;
1644 subFontPtr->familyPtr = AllocFontFamily(display, fontStructPtr, base);
1645 subFontPtr->fontMap = subFontPtr->familyPtr->fontMap;
1646 subFontPtr->name = NULL;
1647 subFontPtr->trigger = -1;
1648 }
1649
1650 /*
1651 *-------------------------------------------------------------------------
1652 *
1653 * ReleaseSubFont --
1654 *
1655 * Called to release the contents of a SubFont. The caller is
1656 * responsible for freeing the memory used by the SubFont itself.
1657 *
1658 * Results:
1659 * None.
1660 *
1661 * Side effects:
1662 * Memory and resources are freed.
1663 *
1664 *---------------------------------------------------------------------------
1665 */
1666
1667 static void
1668 ReleaseSubFont(display, subFontPtr)
1669 Display *display; /* Display which owns screen font. */
1670 SubFont *subFontPtr; /* The SubFont to delete. */
1671 {
1672 XFreeFont(display, subFontPtr->fontStructPtr);
1673 FreeFontFamily(subFontPtr->familyPtr);
1674 if (subFontPtr->name) {
1675 ckfree(subFontPtr->name);
1676 }
1677 }
1678
1679 /*
1680 *-------------------------------------------------------------------------
1681 *
1682 * AllocFontFamily --
1683 *
1684 * Find the FontFamily structure associated with the given font
1685 * name. The information should be stored by the caller in a
1686 * SubFont and used when determining if that SubFont supports a
1687 * character.
1688 *
1689 * Cannot use the string name used to construct the font as the
1690 * key, because the capitalization may not be canonical. Therefore
1691 * use the face name actually retrieved from the font metrics as
1692 * the key.
1693 *
1694 * Results:
1695 * A pointer to a FontFamily. The reference count in the FontFamily
1696 * is automatically incremented. When the SubFont is released, the
1697 * reference count is decremented. When no SubFont is using this
1698 * FontFamily, it may be deleted.
1699 *
1700 * Side effects:
1701 * A new FontFamily structure will be allocated if this font family
1702 * has not been seen. TrueType character existence metrics are
1703 * loaded into the FontFamily structure.
1704 *
1705 *-------------------------------------------------------------------------
1706 */
1707
1708 static FontFamily *
1709 AllocFontFamily(display, fontStructPtr, base)
1710 Display *display; /* Display in which font will be used. */
1711 XFontStruct *fontStructPtr; /* Screen font whose FontFamily is to be
1712 * returned. */
1713 int base; /* Non-zero if this font family is to be
1714 * used in the base font of a font object. */
1715 {
1716 FontFamily *familyPtr;
1717 FontAttributes fa;
1718 Tcl_Encoding encoding;
1719 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1720 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1721
1722 GetFontAttributes(display, fontStructPtr, &fa);
1723 encoding = Tcl_GetEncoding(NULL, GetEncodingAlias(fa.xa.charset));
1724
1725 familyPtr = tsdPtr->fontFamilyList;
1726 for (; familyPtr != NULL; familyPtr = familyPtr->nextPtr) {
1727 if ((familyPtr->faceName == fa.fa.family)
1728 && (familyPtr->foundry == fa.xa.foundry)
1729 && (familyPtr->encoding == encoding)) {
1730 Tcl_FreeEncoding(encoding);
1731 familyPtr->refCount++;
1732 return familyPtr;
1733 }
1734 }
1735
1736 familyPtr = (FontFamily *) ckalloc(sizeof(FontFamily));
1737 memset(familyPtr, 0, sizeof(FontFamily));
1738 familyPtr->nextPtr = tsdPtr->fontFamilyList;
1739 tsdPtr->fontFamilyList = familyPtr;
1740
1741 /*
1742 * Set key for this FontFamily.
1743 */
1744
1745 familyPtr->foundry = fa.xa.foundry;
1746 familyPtr->faceName = fa.fa.family;
1747 familyPtr->encoding = encoding;
1748
1749 /*
1750 * An initial refCount of 2 means that FontFamily information will
1751 * persist even when the SubFont that loaded the FontFamily is released.
1752 * Change it to 1 to cause FontFamilies to be unloaded when not in use.
1753 */
1754
1755 #ifndef _LANG
1756 familyPtr->refCount = 2;
1757 #else
1758 familyPtr->refCount = 1;
1759 #endif
1760
1761 /*
1762 * One byte/character fonts have both min_byte1 and max_byte1 0,
1763 * and max_char_or_byte2 <= 255.
1764 * Anything else specifies a two byte/character font.
1765 */
1766
1767 familyPtr->isTwoByteFont = !(
1768 (fontStructPtr->min_byte1 == 0) &&
1769 (fontStructPtr->max_byte1 == 0) &&
1770 (fontStructPtr->max_char_or_byte2 < 256));
1771 return familyPtr;
1772 }
1773
1774 /*
1775 *-------------------------------------------------------------------------
1776 *
1777 * FreeFontFamily --
1778 *
1779 * Called to free an FontFamily when the SubFont is finished using
1780 * it. Frees the contents of the FontFamily and the memory used by
1781 * the FontFamily itself.
1782 *
1783 * Results:
1784 * None.
1785 *
1786 * Side effects:
1787 * None.
1788 *
1789 *-------------------------------------------------------------------------
1790 */
1791
1792 static void
1793 FreeFontFamily(familyPtr)
1794 FontFamily *familyPtr; /* The FontFamily to delete. */
1795 {
1796 FontFamily **familyPtrPtr;
1797 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1798 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1799 int i;
1800
1801 if (familyPtr == NULL) {
1802 return;
1803 }
1804 familyPtr->refCount--;
1805 if (familyPtr->refCount > 0) {
1806 return;
1807 }
1808
1809 Tcl_FreeEncoding(familyPtr->encoding);
1810 for (i = 0; i < FONTMAP_PAGES; i++) {
1811 if (familyPtr->fontMap[i] != NULL) {
1812 ckfree(familyPtr->fontMap[i]);
1813 }
1814 }
1815 /*
1816 * Delete from list.
1817 */
1818
1819 for (familyPtrPtr = &tsdPtr->fontFamilyList; ; ) {
1820 if (*familyPtrPtr == familyPtr) {
1821 *familyPtrPtr = familyPtr->nextPtr;
1822 break;
1823 }
1824 familyPtrPtr = &(*familyPtrPtr)->nextPtr;
1825 }
1826
1827 ckfree((char *) familyPtr);
1828 }
1829
1830 /*
1831 *-------------------------------------------------------------------------
1832 *
1833 * FindSubFontForChar --
1834 *
1835 * Determine which screen font is necessary to use to
1836 * display the given character. If the font object does not have
1837 * a screen font that can display the character, another screen font
1838 * may be loaded into the font object, following a set of preferred
1839 * fallback rules.
1840 *
1841 * Results:
1842 * The return value is the SubFont to use to display the given
1843 * character.
1844 *
1845 * Side effects:
1846 * The contents of fontPtr are modified to cache the results
1847 * of the lookup and remember any SubFonts that were dynamically
1848 * loaded. The table of SubFonts might be extended, and if a non-NULL
1849 * reference to a subfont pointer is available, it is updated if it
1850 * previously pointed into the old subfont table.
1851 *
1852 *-------------------------------------------------------------------------
1853 */
1854
1855 static SubFont *
1856 FindSubFontForChar(fontPtr, ch, fixSubFontPtrPtr)
1857 UnixFont *fontPtr; /* The font object with which the character
1858 * will be displayed. */
1859 int ch; /* The Unicode character to be displayed. */
1860 SubFont **fixSubFontPtrPtr; /* Subfont reference to fix up if we
1861 * reallocate our subfont table. */
1862 {
1863 int i, j, k, numNames;
1864 Tk_Uid faceName;
1865 char *fallback;
1866 char **aliases, **nameList, **anyFallbacks;
1867 char ***fontFallbacks;
1868 SubFont *subFontPtr;
1869 Tcl_DString ds;
1870
1871 if (FontMapLookup(&fontPtr->subFontArray[0], ch)) {
1872 return &fontPtr->subFontArray[0];
1873 }
1874
1875 for (i = 1; i < fontPtr->numSubFonts; i++) {
1876 if (FontMapLookup(&fontPtr->subFontArray[i], ch)) {
1877 return &fontPtr->subFontArray[i];
1878 }
1879 }
1880
1881 if (FontMapLookup(&fontPtr->controlSubFont, ch)) {
1882 return &fontPtr->controlSubFont;
1883 }
1884
1885 /*
1886 * Keep track of all face names that we check, so we don't check some
1887 * name multiple times if it can be reached by multiple paths.
1888 */
1889
1890 /* Why not use a hash table ! */
1891 Tcl_DStringInit(&ds);
1892
1893 /*
1894 * Are there any other fonts with the same face name as the base
1895 * font that could display this character, e.g., if the base font
1896 * is adobe:fixed:iso8859-1, we could might be able to use
1897 * misc:fixed:iso8859-8 or sony:fixed:jisx0208.1983-0
1898 */
1899
1900 faceName = fontPtr->font.fa.family;
1901 if (SeenName(faceName, &ds) == 0) {
1902 subFontPtr = CanUseFallback(fontPtr, faceName, ch, fixSubFontPtrPtr);
1903 if (subFontPtr != NULL) {
1904 goto end;
1905 }
1906 }
1907
1908 aliases = TkFontGetAliasList(faceName);
1909
1910 subFontPtr = NULL;
1911 fontFallbacks = TkFontGetFallbacks();
1912 for (i = 0; fontFallbacks[i] != NULL; i++) {
1913 for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) {
1914 if (strcasecmp(fallback, faceName) == 0) {
1915 /*
1916 * If the base font has a fallback...
1917 */
1918
1919 goto tryfallbacks;
1920 } else if (aliases != NULL) {
1921 /*
1922 * Or if an alias for the base font has a fallback...
1923 */
1924
1925 for (k = 0; aliases[k] != NULL; k++) {
1926 if (strcasecmp(fallback, aliases[k]) == 0) {
1927 goto tryfallbacks;
1928 }
1929 }
1930 }
1931 }
1932 continue;
1933
1934 tryfallbacks:
1935
1936 /*
1937 * ...then see if we can use one of the fallbacks, or an
1938 * alias for one of the fallbacks.
1939 */
1940
1941 for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) {
1942 subFontPtr = CanUseFallbackWithAliases(fontPtr, fallback, ch, &ds,
1943 fixSubFontPtrPtr);
1944 if (subFontPtr != NULL) {
1945 goto end;
1946 }
1947 }
1948 }
1949
1950 /*
1951 * See if we can use something from the global fallback list.
1952 */
1953
1954 anyFallbacks = TkFontGetGlobalClass();
1955 for (i = 0; (fallback = anyFallbacks[i]) != NULL; i++) {
1956 subFontPtr = CanUseFallbackWithAliases(fontPtr, fallback, ch, &ds,
1957 fixSubFontPtrPtr);
1958 if (subFontPtr != NULL) {
1959 goto end;
1960 }
1961 }
1962
1963 /*
1964 * Try all face names available in the whole system until we
1965 * find one that can be used.
1966 */
1967
1968 nameList = ListFonts(fontPtr->display, "*", &numNames);
1969 for (i = 0; i < numNames; i++) {
1970 fallback = strchr(nameList[i] + 1, '-') + 1;
1971 strchr(fallback, '-')[0] = '\0';
1972 if (SeenName(fallback, &ds) == 0) {
1973 subFontPtr = CanUseFallback(fontPtr, fallback, ch,
1974 fixSubFontPtrPtr);
1975 if (subFontPtr != NULL) {
1976 XFreeFontNames(nameList);
1977 goto end;
1978 }
1979 }
1980 }
1981 XFreeFontNames(nameList);
1982
1983 end:
1984 Tcl_DStringFree(&ds);
1985
1986 if (subFontPtr == NULL) {
1987 /*
1988 * No font can display this character, so it will be displayed as a
1989 * control character expansion.
1990 */
1991
1992 subFontPtr = &fontPtr->controlSubFont;
1993 FontMapInsert(subFontPtr, ch);
1994 }
1995 return subFontPtr;
1996 }
1997
1998 /*
1999 *-------------------------------------------------------------------------
2000 *
2001 * FontMapLookup --
2002 *
2003 * See if the screen font can display the given character.
2004 *
2005 * Results:
2006 * The return value is 0 if the screen font cannot display the
2007 * character, non-zero otherwise.
2008 *
2009 * Side effects:
2010 * New pages are added to the font mapping cache whenever the
2011 * character belongs to a page that hasn't been seen before.
2012 * When a page is loaded, information about all the characters on
2013 * that page is stored, not just for the single character in
2014 * question.
2015 *
2016 *-------------------------------------------------------------------------
2017 */
2018
2019 static int
2020 FontMapLookup(subFontPtr, ch)
2021 SubFont *subFontPtr; /* Contains font mapping cache to be queried
2022 * and possibly updated. */
2023 int ch; /* Character to be tested. */
2024 {
2025 int row, bitOffset;
2026
2027 row = ch >> FONTMAP_SHIFT;
2028 if (subFontPtr->fontMap[row] == NULL) {
2029 FontMapLoadPage(subFontPtr, row);
2030 }
2031 bitOffset = ch & (FONTMAP_BITSPERPAGE - 1);
2032 return (subFontPtr->fontMap[row][bitOffset >> 3] >> (bitOffset & 7)) & 1;
2033 }
2034
2035 /*
2036 *-------------------------------------------------------------------------
2037 *
2038 * FontMapInsert --
2039 *
2040 * Tell the font mapping cache that the given screen font should be
2041 * used to display the specified character. This is called when no
2042 * font on the system can be be found that can display that
2043 * character; we lie to the font and tell it that it can display
2044 * the character, otherwise we would end up re-searching the entire
2045 * fallback hierarchy every time that character was seen.
2046 *
2047 * Results:
2048 * None.
2049 *
2050 * Side effects:
2051 * New pages are added to the font mapping cache whenever the
2052 * character belongs to a page that hasn't been seen before.
2053 * When a page is loaded, information about all the characters on
2054 * that page is stored, not just for the single character in
2055 * question.
2056 *
2057 *-------------------------------------------------------------------------
2058 */
2059
2060 static void
2061 FontMapInsert(subFontPtr, ch)
2062 SubFont *subFontPtr; /* Contains font mapping cache to be
2063 * updated. */
2064 int ch; /* Character to be added to cache. */
2065 {
2066 int row, bitOffset;
2067
2068 row = ch >> FONTMAP_SHIFT;
2069 if (subFontPtr->fontMap[row] == NULL) {
2070 FontMapLoadPage(subFontPtr, row);
2071 }
2072 bitOffset = ch & (FONTMAP_BITSPERPAGE - 1);
2073 subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7);
2074 }
2075
2076 /*
2077 *-------------------------------------------------------------------------
2078 *
2079 * FontMapLoadPage --
2080 *
2081 * Load information about all the characters on a given page.
2082 * This information consists of one bit per character that indicates
2083 * whether the associated screen font can (1) or cannot (0) display
2084 * the characters on the page.
2085 *
2086 * Results:
2087 * None.
2088 *
2089 * Side effects:
2090 * Mempry allocated.
2091 *
2092 *-------------------------------------------------------------------------
2093 */
2094 static void
2095 FontMapLoadPage(subFontPtr, row)
2096 SubFont *subFontPtr; /* Contains font mapping cache to be
2097 * updated. */
2098 int row; /* Index of the page to be loaded into
2099 * the cache. */
2100 {
2101 char src[TCL_UTF_MAX], buf[16];
2102 int minHi, maxHi, minLo, maxLo, scale, checkLo;
2103 int i, end, bitOffset, isTwoByteFont, n;
2104 Tcl_Encoding encoding;
2105 XFontStruct *fontStructPtr;
2106 XCharStruct *widths;
2107 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
2108 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
2109 int unicode = 0;
2110
2111 subFontPtr->fontMap[row] = (char *) ckalloc(FONTMAP_BITSPERPAGE / 8);
2112 memset(subFontPtr->fontMap[row], 0, FONTMAP_BITSPERPAGE / 8);
2113
2114 if (subFontPtr->familyPtr == &tsdPtr->controlFamily) {
2115 return;
2116 }
2117
2118 fontStructPtr = subFontPtr->fontStructPtr;
2119 encoding = subFontPtr->familyPtr->encoding;
2120 isTwoByteFont = subFontPtr->familyPtr->isTwoByteFont;
2121
2122 widths = fontStructPtr->per_char;
2123 minHi = fontStructPtr->min_byte1;
2124 maxHi = fontStructPtr->max_byte1;
2125 minLo = fontStructPtr->min_char_or_byte2;
2126 maxLo = fontStructPtr->max_char_or_byte2;
2127 scale = maxLo - minLo + 1;
2128 checkLo = minLo;
2129
2130 if (! isTwoByteFont) {
2131 if (minLo < 32) {
2132 checkLo = 32;
2133 }
2134 }
2135 else {
2136 unicode = strstr(Tcl_GetEncodingName(encoding),"ucs-2") ? 1 : 0;
2137 }
2138
2139 end = (row + 1) << FONTMAP_SHIFT;
2140 for (i = row << FONTMAP_SHIFT; i < end; i++) {
2141 int hi, lo;
2142
2143 if (unicode) {
2144 buf[0] = (i >> 8);
2145 buf[1] = (i & 0xFF);
2146 }
2147 else if (Tcl_UtfToExternal(NULL, encoding, src, Tcl_UniCharToUtf(i, src),
2148 TCL_ENCODING_STOPONERROR, NULL, buf, sizeof(buf), NULL,
2149 NULL, NULL) != TCL_OK) {
2150 continue;
2151 }
2152 if (isTwoByteFont) {
2153 hi = ((unsigned char *) buf)[0];
2154 lo = ((unsigned char *) buf)[1];
2155 } else {
2156 hi = 0;
2157 lo = ((unsigned char *) buf)[0];
2158 }
2159 n = (hi - minHi) * scale + lo - minLo;
2160 if ((hi < minHi) || (hi > maxHi) || (lo < checkLo) || (lo > maxLo)) {
2161 continue;
2162 }
2163 if ((widths == NULL) || ((widths[n].width + widths[n].rbearing) != 0)) {
2164 bitOffset = i & (FONTMAP_BITSPERPAGE - 1);
2165 subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7);
2166 }
2167 }
2168 }
2169
2170 /*
2171 *---------------------------------------------------------------------------
2172 *
2173 * CanUseFallbackWithAliases --
2174 *
2175 * Helper function for FindSubFontForChar. Determine if the
2176 * specified face name (or an alias of the specified face name)
2177 * can be used to construct a screen font that can display the
2178 * given character.
2179 *
2180 * Results:
2181 * See CanUseFallback().
2182 *
2183 * Side effects:
2184 * If the name and/or one of its aliases was rejected, the
2185 * rejected string is recorded in nameTriedPtr so that it won't
2186 * be tried again. The table of SubFonts might be extended, and if
2187 * a non-NULL reference to a subfont pointer is available, it is
2188 * updated if it previously pointed into the old subfont table.
2189 *
2190 *---------------------------------------------------------------------------
2191 */
2192
2193 static SubFont *
2194 CanUseFallbackWithAliases(fontPtr, faceName, ch, nameTriedPtr,
2195 fixSubFontPtrPtr)
2196 UnixFont *fontPtr; /* The font object that will own the new
2197 * screen font. */
2198 char *faceName; /* Desired face name for new screen font. */
2199 int ch; /* The Unicode character that the new
2200 * screen font must be able to display. */
2201 Tcl_DString *nameTriedPtr; /* Records face names that have already
2202 * been tried. It is possible for the same
2203 * face name to be queried multiple times when
2204 * trying to find a suitable screen font. */
2205 SubFont **fixSubFontPtrPtr; /* Subfont reference to fix up if we
2206 * reallocate our subfont table. */
2207 {
2208 SubFont *subFontPtr;
2209 char **aliases;
2210 int i;
2211
2212 if (SeenName(faceName, nameTriedPtr) == 0) {
2213 subFontPtr = CanUseFallback(fontPtr, faceName, ch, fixSubFontPtrPtr);
2214 if (subFontPtr != NULL) {
2215 return subFontPtr;
2216 }
2217 }
2218 aliases = TkFontGetAliasList(faceName);
2219 if (aliases != NULL) {
2220 for (i = 0; aliases[i] != NULL; i++) {
2221 if (SeenName(aliases[i], nameTriedPtr) == 0) {
2222 subFontPtr = CanUseFallback(fontPtr, aliases[i], ch,
2223 fixSubFontPtrPtr);
2224 if (subFontPtr != NULL) {
2225 return subFontPtr;
2226 }
2227 }
2228 }
2229 }
2230 return NULL;
2231 }
2232
2233 /*
2234 *---------------------------------------------------------------------------
2235 *
2236 * SeenName --
2237 *
2238 * Used to determine we have already tried and rejected the given
2239 * face name when looking for a screen font that can support some
2240 * Unicode character.
2241 *
2242 * Results:
2243 * The return value is 0 if this face name has not already been seen,
2244 * non-zero otherwise.
2245 *
2246 * Side effects:
2247 * None.
2248 *
2249 *---------------------------------------------------------------------------
2250 */
2251
2252 static int
2253 SeenName(name, dsPtr)
2254 CONST char *name; /* The name to check. */
2255 Tcl_DString *dsPtr; /* Contains names that have already been
2256 * seen. */
2257 {
2258 CONST char *seen, *end;
2259
2260 seen = Tcl_DStringValue(dsPtr);
2261 end = seen + Tcl_DStringLength(dsPtr);
2262 while (seen < end) {
2263 if (strcasecmp(seen, name) == 0) {
2264 return 1;
2265 }
2266 seen += strlen(seen) + 1;
2267 }
2268 Tcl_DStringAppend(dsPtr, (char *) name, (int) (strlen(name) + 1));
2269 return 0;
2270 }
2271
2272 /*
2273 *-------------------------------------------------------------------------
2274 *
2275 * CanUseFallback --
2276 *
2277 * If the specified screen font has not already been loaded
2278 * into the font object, determine if the specified screen
2279 * font can display the given character.
2280 *
2281 * Results:
2282 * The return value is a pointer to a newly allocated SubFont,
2283 * owned by the font object. This SubFont can be used to display
2284 * the given character. The SubFont represents the screen font
2285 * with the base set of font attributes from the font object, but
2286 * using the specified face name. NULL is returned if the font
2287 * object already holds a reference to the specified font or if
2288 * the specified font doesn't exist or cannot display the given
2289 * character.
2290 *
2291 * Side effects:
2292 * The font object's subFontArray is updated to contain a reference
2293 * to the newly allocated SubFont. The table of SubFonts might be
2294 * extended, and if a non-NULL reference to a subfont pointer is
2295 * available, it is updated if it previously pointed into the old
2296 * subfont table.
2297 *
2298 *-------------------------------------------------------------------------
2299 */
2300
2301 static SubFont *
2302 CanUseFallback(fontPtr, faceName, ch, fixSubFontPtrPtr)
2303 UnixFont *fontPtr; /* The font object that will own the new
2304 * screen font. */
2305 CONST char *faceName; /* Desired face name for new screen font. */
2306 int ch; /* The Unicode character that the new
2307 * screen font must be able to display. */
2308 SubFont **fixSubFontPtrPtr; /* Subfont reference to fix up if we
2309 * reallocate our subfont table. */
2310 {
2311 int i, nameIdx, numNames, srcLen;
2312 Tk_Uid hateFoundry;
2313 int bestIdx[2];
2314 CONST char *charset, *hateCharset;
2315 unsigned int bestScore[2];
2316 char **nameList, **nameListOrig;
2317 FontAttributes want, got;
2318 char src[TCL_UTF_MAX];
2319 Display *display;
2320 SubFont subFont;
2321 XFontStruct *fontStructPtr;
2322 Tcl_DString dsEncodings;
2323 int numEncodings;
2324 Tcl_Encoding *encodingCachePtr;
2325
2326 /*
2327 * Assume: the face name is times.
2328 * Assume: adobe:times:iso8859-1 has already been used.
2329 *
2330 * Are there any versions of times that can display this
2331 * character (e.g., perhaps linotype:times:iso8859-2)?
2332 * a. Get list of all times fonts.
2333 * b1. Cross out all names whose encodings we've already used.
2334 * b2. Cross out all names whose foundry & encoding we've already seen.
2335 * c. Cross out all names whose encoding cannot handle the character.
2336 * d. Rank each name and pick the best match.
2337 * e. If that font cannot actually display the character, cross
2338 * out all names with the same foundry and encoding and go
2339 * back to (c).
2340 */
2341
2342 display = fontPtr->display;
2343 nameList = ListFonts(display, faceName, &numNames);
2344 if (numNames == 0) {
2345 return NULL;
2346 }
2347 nameListOrig = nameList;
2348
2349 srcLen = Tcl_UniCharToUtf(ch, src);
2350
2351 want.fa = fontPtr->font.fa;
2352 want.xa = fontPtr->xa;
2353
2354 want.fa.family = Tk_GetUid(faceName);
2355 want.fa.size = -fontPtr->pixelSize;
2356
2357 hateFoundry = NULL;
2358 hateCharset = NULL;
2359 numEncodings = 0;
2360 Tcl_DStringInit(&dsEncodings);
2361
2362 charset = NULL; /* lint, since numNames must be > 0 to get here. */
2363
2364 retry:
2365 bestIdx[0] = -1;
2366 bestIdx[1] = -1;
2367 bestScore[0] = (unsigned int) -1;
2368 bestScore[1] = (unsigned int) -1;
2369 for (nameIdx = 0; nameIdx < numNames; nameIdx++) {
2370 Tcl_Encoding encoding;
2371 char dst[16];
2372 int scalable, srcRead, dstWrote;
2373 unsigned int score;
2374
2375 if (nameList[nameIdx] == NULL) {
2376 continue;
2377 }
2378 if (TkFontParseXLFD(nameList[nameIdx], &got.fa, &got.xa) != TCL_OK) {
2379 goto crossout;
2380 }
2381 IdentifySymbolEncodings(&got);
2382 charset = GetEncodingAlias(got.xa.charset);
2383 if (hateFoundry != NULL) {
2384 /*
2385 * E. If the font we picked cannot actually display the
2386 * character, cross out all names with the same foundry and
2387 * encoding.
2388 */
2389
2390 if ((hateFoundry == got.xa.foundry)
2391 && (strcmp(hateCharset, charset) == 0)) {
2392 /* not clear this is correct for Unicode
2393 foundry may not always use same subset
2394 on the other hand if it isn't in foundary's
2395 -iso10646-1 font it probably isn't in their
2396 -iso8859-* fonts either.
2397 It is less clear with oriental and symbol fonts
2398 that other encodings might not handle
2399 */
2400 if (1 || strcmp(hateCharset, "ucs-2be") != 0)
2401 goto crossout;
2402 }
2403 } else {
2404 /*
2405 * B. Cross out all names whose encodings we've already used.
2406 */
2407 if (strcmp(charset,"ucs-2be") == 0) {
2408 if ((unsigned int) ch <= 0xffff)
2409 goto do_ranking;
2410 goto crossout;
2411 }
2412
2413 for (i = 0; i < fontPtr->numSubFonts; i++) {
2414 encoding = fontPtr->subFontArray[i].familyPtr->encoding;
2415 if (strcmp(charset, Tcl_GetEncodingName(encoding)) == 0) {
2416 goto crossout;
2417 }
2418 }
2419 }
2420
2421 do_ranking:
2422 /*
2423 * C. Cross out all names whose encoding cannot handle the character.
2424 */
2425
2426 encodingCachePtr = (Tcl_Encoding *) Tcl_DStringValue(&dsEncodings);
2427 for (i = numEncodings; --i >= 0; encodingCachePtr++) {
2428 encoding = *encodingCachePtr;
2429 if (strcmp(Tcl_GetEncodingName(encoding), charset) == 0) {
2430 break;
2431 }
2432 }
2433 if (i < 0) {
2434 encoding = Tcl_GetEncoding(NULL, charset);
2435 if (encoding == NULL) {
2436 goto crossout;
2437 }
2438
2439 Tcl_DStringAppend(&dsEncodings, (char *) &encoding,
2440 sizeof(encoding));
2441 numEncodings++;
2442 }
2443 Tcl_UtfToExternal(NULL, encoding, src, srcLen,
2444 TCL_ENCODING_STOPONERROR, NULL, dst, sizeof(dst), &srcRead,
2445 &dstWrote, NULL);
2446 if (dstWrote == 0) {
2447 goto crossout;
2448 }
2449
2450 /*
2451 * D. Rank each name and pick the best match.
2452 */
2453
2454 scalable = (got.fa.size == 0);
2455 score = RankAttributes(&want, &got, ch, nameList[nameIdx]);
2456 if (score < bestScore[scalable]) {
2457 bestIdx[scalable] = nameIdx;
2458 bestScore[scalable] = score;
2459 }
2460 if (score == 0) {
2461 break;
2462 }
2463 /* Allow ranking to have a veto */
2464 else if (score == (unsigned int) -1) {
2465 hateFoundry = got.xa.foundry;
2466 hateCharset = charset;
2467 goto crossout;
2468 }
2469 else if (score == (unsigned int) -2) {
2470 goto crossout;
2471 }
2472 continue;
2473
2474 crossout:
2475 if (nameList == nameListOrig) {
2476 /*
2477 * Not allowed to change pointers to memory that X gives you,
2478 * so make a copy.
2479 */
2480
2481 nameList = (char **) ckalloc(numNames * sizeof(char *));
2482 memcpy(nameList, nameListOrig, numNames * sizeof(char *));
2483 }
2484 nameList[nameIdx] = NULL;
2485 }
2486
2487 /* There may be merit in a version of this which just does XQueryFont()
2488 rather than load it server-side until we know it is of use
2489 */
2490 fontStructPtr = GetScreenFont(display, &want, nameList, bestIdx, bestScore, &nameIdx);
2491
2492 encodingCachePtr = (Tcl_Encoding *) Tcl_DStringValue(&dsEncodings);
2493 for (i = numEncodings; --i >= 0; encodingCachePtr++) {
2494 Tcl_FreeEncoding(*encodingCachePtr);
2495 }
2496 Tcl_DStringFree(&dsEncodings);
2497 numEncodings = 0;
2498
2499 if (fontStructPtr == NULL || nameList[nameIdx] == NULL) {
2500 if (nameList != nameListOrig) {
2501 ckfree((char *) nameList);
2502 }
2503 XFreeFontNames(nameListOrig);
2504 return NULL;
2505 }
2506 #ifdef _LANG
2507 TkFontParseXLFD(nameList[nameIdx], &got.fa, &got.xa);
2508 IdentifySymbolEncodings(&got);
2509 #endif
2510 InitSubFont(display, fontStructPtr, 0, &subFont);
2511 if (FontMapLookup(&subFont, ch) == 0) {
2512 /*
2513 * E. If the font we picked cannot actually display the character,
2514 * cross out all names with the same foundry and encoding and pick
2515 * another font.
2516 */
2517 hateFoundry = got.xa.foundry;
2518 hateCharset = GetEncodingAlias(got.xa.charset);
2519 ReleaseSubFont(display, &subFont);
2520 #ifdef _LANG
2521 LangFontRank((unsigned int ) -1, ch, nameList[nameIdx],
2522 want.xa.foundry, &want.fa, want.xa.charset,
2523 got.xa.foundry, &got.fa, got.xa.charset);
2524 #endif
2525 goto retry;
2526 }
2527 #ifdef _LANG
2528 LangFontRank(0, ch, nameList[nameIdx],
2529 want.xa.foundry, &want.fa, want.xa.charset,
2530 got.xa.foundry, &got.fa, got.xa.charset);
2531 #endif
2532 subFont.name = ckalloc(strlen(nameList[nameIdx])+1);
2533 subFont.trigger = ch;
2534 if (subFont.name) {
2535 strcpy(subFont.name,nameList[nameIdx]);
2536 }
2537 if (nameList != nameListOrig) {
2538 ckfree((char *) nameList);
2539 }
2540 XFreeFontNames(nameListOrig);
2541
2542 if (fontPtr->numSubFonts >= SUBFONT_SPACE) {
2543 SubFont *newPtr;
2544
2545 newPtr = (SubFont *) ckalloc(sizeof(SubFont) * (fontPtr->numSubFonts + 1));
2546 memcpy((char *) newPtr, fontPtr->subFontArray,
2547 fontPtr->numSubFonts * sizeof(SubFont));
2548 if (fixSubFontPtrPtr != NULL) {
2549 register SubFont *fixSubFontPtr = *fixSubFontPtrPtr;
2550
2551 if (fixSubFontPtr != &fontPtr->controlSubFont) {
2552 *fixSubFontPtrPtr =
2553 newPtr + (fixSubFontPtr - fontPtr->subFontArray);
2554 }
2555 }
2556 if (fontPtr->subFontArray != fontPtr->staticSubFonts) {
2557 ckfree((char *) fontPtr->subFontArray);
2558 }
2559 fontPtr->subFontArray = newPtr;
2560 }
2561 fontPtr->subFontArray[fontPtr->numSubFonts] = subFont;
2562 fontPtr->numSubFonts++;
2563 return &fontPtr->subFontArray[fontPtr->numSubFonts - 1];
2564 }
2565
2566 /*
2567 *---------------------------------------------------------------------------
2568 *
2569 * RankAttributes --
2570 *
2571 * Determine how close the attributes of the font in question match
2572 * the attributes that we want.
2573 *
2574 * Results:
2575 * The return value is the score; lower numbers are better.
2576 * *scalablePtr is set to 0 if the font was not scalable, 1 otherwise.
2577 *
2578 * Side effects:
2579 * None.
2580 *
2581 *---------------------------------------------------------------------------
2582 */
2583
2584 static unsigned int
2585 RankAttributes(wantPtr, gotPtr, ch, name)
2586 FontAttributes *wantPtr; /* The desired attributes. */
2587 FontAttributes *gotPtr; /* The attributes we have to live with. */
2588 int ch; /* character we want */
2589 const char *name; /* Font we are trying */
2590 {
2591 unsigned int penalty;
2592
2593 penalty = 0;
2594 if (gotPtr->xa.foundry != wantPtr->xa.foundry) {
2595 penalty += 4500;
2596 }
2597 if (gotPtr->fa.family != wantPtr->fa.family) {
2598 penalty += 9000;
2599 }
2600 if (gotPtr->fa.weight != wantPtr->fa.weight) {
2601 penalty += 90;
2602 }
2603 if (gotPtr->fa.slant != wantPtr->fa.slant) {
2604 penalty += 60;
2605 }
2606 if (gotPtr->xa.slant != wantPtr->xa.slant) {
2607 penalty += 10;
2608 }
2609 if (gotPtr->xa.setwidth != wantPtr->xa.setwidth) {
2610 penalty += 1000;
2611 }
2612
2613 if (gotPtr->fa.size == 0) {
2614 /*
2615 * A scalable font is almost always acceptable, but the
2616 * corresponding bitmapped font would be better.
2617 */
2618
2619 penalty += 10;
2620 } else {
2621 int diff;
2622
2623 /*
2624 * It's worse to be too large than to be too small.
2625 */
2626
2627 diff = (-gotPtr->fa.size - -wantPtr->fa.size);
2628 if (diff > 0) {
2629 penalty += 600;
2630 } else if (diff < 0) {
2631 penalty += 150;
2632 diff = -diff;
2633 }
2634 penalty += 150 * diff;
2635 }
2636 if (gotPtr->xa.charset != wantPtr->xa.charset) {
2637 int i;
2638 CONST char *gotAlias, *wantAlias;
2639
2640 penalty += 65000;
2641 gotAlias = GetEncodingAlias(gotPtr->xa.charset);
2642 wantAlias = GetEncodingAlias(wantPtr->xa.charset);
2643 if (strcmp(gotAlias, wantAlias) != 0) {
2644 penalty += 30000;
2645 for (i = 0; encodingList[i] != NULL; i++) {
2646 if (strcmp(gotAlias, encodingList[i]) == 0) {
2647 penalty -= 30000;
2648 break;
2649 }
2650 /* Penalty increases as we go down prefered list */
2651 penalty += 20000;
2652 }
2653 }
2654 }
2655 #ifdef _LANG
2656 penalty = LangFontRank(penalty, ch, name,
2657 wantPtr->xa.foundry,&wantPtr->fa, wantPtr->xa.charset,
2658 gotPtr->xa.foundry,&gotPtr->fa, gotPtr->xa.charset);
2659 #endif
2660 return penalty;
2661 }
2662
2663 /*
2664 *---------------------------------------------------------------------------
2665 *
2666 * GetScreenFont --
2667 *
2668 * Given the names for the best scalable and best bitmapped font,
2669 * actually construct an XFontStruct based on the best XLFD.
2670 * This is where all the alias and fallback substitution bottoms
2671 * out.
2672 *
2673 * Results:
2674 * The screen font that best corresponds to the set of attributes.
2675 *
2676 * Side effects:
2677 * None.
2678 *
2679 *---------------------------------------------------------------------------
2680 */
2681
2682 static XFontStruct *
2683 GetScreenFont(display, wantPtr, nameList, bestIdx, bestScore, indexPtr)
2684 Display *display; /* Display for new XFontStruct. */
2685 FontAttributes *wantPtr; /* Contains desired actual pixel-size if the
2686 * best font was scalable. */
2687 char **nameList; /* Array of XLFDs. */
2688 int bestIdx[2]; /* Indices into above array for XLFD of
2689 * best bitmapped and best scalable font. */
2690 unsigned int bestScore[2]; /* Scores of best bitmapped and best
2691 * scalable font. XLFD corresponding to
2692 * lowest score will be constructed. */
2693 int *indexPtr; /* Return index of name we used */
2694 {
2695 XFontStruct *fontStructPtr;
2696
2697 if ((bestIdx[0] < 0) && (bestIdx[1] < 0)) {
2698 return NULL;
2699 }
2700
2701 /*
2702 * Now we know which is the closest matching scalable font and the
2703 * closest matching bitmapped font. If the scalable font was a
2704 * better match, try getting the scalable font; however, if the
2705 * scalable font was not actually available in the desired
2706 * pointsize, fall back to the closest bitmapped font.
2707 */
2708
2709 fontStructPtr = NULL;
2710 if (bestScore[1] < bestScore[0] && bestScore[1] < (unsigned int) -2) {
2711 char *str, *rest;
2712 char buf[256];
2713 int i;
2714
2715 /*
2716 * Fill in the desired pixel size for this font.
2717 */
2718
2719 tryscale:
2720 str = nameList[bestIdx[1]];
2721 for (i = 0; i < XLFD_PIXEL_SIZE; i++) {
2722 str = strchr(str + 1, '-');
2723 }
2724 rest = str;
2725 for (i = XLFD_PIXEL_SIZE; i < XLFD_CHARSET; i++) {
2726 rest = strchr(rest + 1, '-');
2727 }
2728 *str = '\0';
2729 sprintf(buf, "%.200s-%d-*-*-*-*-*%s", nameList[bestIdx[1]],
2730 -wantPtr->fa.size, rest);
2731 *str = '-';
2732 fontStructPtr = XLoadQueryFont(display, buf);
2733 if (fontStructPtr != NULL) {
2734 *indexPtr = bestIdx[1];
2735 }
2736 bestScore[1] = (unsigned int) -1;
2737 }
2738 if (fontStructPtr == NULL && bestScore[0] < (unsigned int) -2) {
2739 fontStructPtr = XLoadQueryFont(display, nameList[bestIdx[0]]);
2740 if (fontStructPtr == NULL) {
2741 /*
2742 * This shouldn't happen because the font name is one of the
2743 * names that X gave us to use, but it does anyhow.
2744 */
2745
2746 if (bestScore[1] < (unsigned int) -2) {
2747 goto tryscale;
2748 }
2749 return GetSystemFont(display);
2750 }
2751 else {
2752 *indexPtr = bestIdx[0];
2753 }
2754 }
2755 return fontStructPtr;
2756 }
2757
2758 /*
2759 *---------------------------------------------------------------------------
2760 *
2761 * GetSystemFont --
2762 *
2763 * Absolute fallback mechanism, called when we need a font and no
2764 * other font can be found and/or instantiated.
2765 *
2766 * Results:
2767 * A pointer to a font. Never NULL.
2768 *
2769 * Side effects:
2770 * If there are NO fonts installed on the system, this call will
2771 * panic, but how did you get X running in that case?
2772 *
2773 *---------------------------------------------------------------------------
2774 */
2775
2776 static XFontStruct *
2777 GetSystemFont(display)
2778 Display *display; /* Display for new XFontStruct. */
2779 {
2780 XFontStruct *fontStructPtr;
2781
2782 fontStructPtr = XLoadQueryFont(display, "fixed");
2783 if (fontStructPtr == NULL) {
2784 fontStructPtr = XLoadQueryFont(display, "*");
2785 if (fontStructPtr == NULL) {
2786 panic("TkpGetFontFromAttributes: cannot get any font");
2787 }
2788 }
2789 return fontStructPtr;
2790 }
2791
2792 /*
2793 *---------------------------------------------------------------------------
2794 *
2795 * GetFontAttributes --
2796 *
2797 * Given a screen font, determine its actual attributes, which are
2798 * not necessarily the attributes that were used to construct it.
2799 *
2800 * Results:
2801 * *faPtr is filled with the screen font's attributes.
2802 *
2803 * Side effects:
2804 * None.
2805 *
2806 *---------------------------------------------------------------------------
2807 */
2808
2809 static int
2810 GetFontAttributes(display, fontStructPtr, faPtr)
2811 Display *display; /* Display that owns the screen font. */
2812 XFontStruct *fontStructPtr; /* Screen font to query. */
2813 FontAttributes *faPtr; /* For storing attributes of screen font. */
2814 {
2815 unsigned long value;
2816 char *name;
2817
2818 if ((XGetFontProperty(fontStructPtr, XA_FONT, &value) != False) &&
2819 (value != 0)) {
2820 name = XGetAtomName(display, (Atom) value);
2821 if (TkFontParseXLFD(name, &faPtr->fa, &faPtr->xa) != TCL_OK) {
2822 faPtr->fa.family = Tk_GetUid(name);
2823 faPtr->xa.foundry = Tk_GetUid("");
2824 faPtr->xa.charset = Tk_GetUid("");
2825 }
2826 XFree(name);
2827 } else {
2828 TkInitFontAttributes(&faPtr->fa);
2829 TkInitXLFDAttributes(&faPtr->xa);
2830 }
2831 /*
2832 * Do last ditch check for family. It seems that some X servers can
2833 * fail on the X font calls above, slipping through earlier checks.
2834 * X-Win32 5.4 is one of these.
2835 */
2836 if (faPtr->fa.family == NULL) {
2837 faPtr->fa.family = Tk_GetUid("");
2838 faPtr->xa.foundry = Tk_GetUid("");
2839 faPtr->xa.charset = Tk_GetUid("");
2840 }
2841 return IdentifySymbolEncodings(faPtr);
2842 }
2843
2844 /*
2845 *---------------------------------------------------------------------------
2846 *
2847 * ListFonts --
2848 *
2849 * Utility function to return the array of all XLFDs on the system
2850 * with the specified face name.
2851 *
2852 * Results:
2853 * The return value is an array of XLFDs, which should be freed with
2854 * XFreeFontNames(), or NULL if no XLFDs matched the requested name.
2855 *
2856 * Side effects:
2857 * None.
2858 *
2859 *---------------------------------------------------------------------------
2860 */
2861
2862 static char **
2863 ListFonts(display, faceName, numNamesPtr)
2864 Display *display; /* Display to query. */
2865 CONST char *faceName; /* Desired face name, or "*" for all. */
2866 int *numNamesPtr; /* Filled with length of returned array, or
2867 * 0 if no names were found. */
2868 {
2869 char buf[256];
2870
2871 sprintf(buf, "-*-%.80s-*-*-*-*-*-*-*-*-*-*-*-*", faceName);
2872 return XListFonts(display, buf, 10000, numNamesPtr);
2873 }
2874
2875 static char **
2876 ListFontOrAlias(display, faceName, numNamesPtr)
2877 Display *display; /* Display to query. */
2878 CONST char *faceName; /* Desired face name, or "*" for all. */
2879 int *numNamesPtr; /* Filled with length of returned array, or
2880 * 0 if no names were found. */
2881 {
2882 char **nameList, **aliases;
2883 int i;
2884
2885 nameList = ListFonts(display, faceName, numNamesPtr);
2886 if (nameList != NULL) {
2887 return nameList;
2888 }
2889 aliases = TkFontGetAliasList(faceName);
2890 if (aliases != NULL) {
2891 for (i = 0; aliases[i] != NULL; i++) {
2892 nameList = ListFonts(display, aliases[i], numNamesPtr);
2893 if (nameList != NULL) {
2894 return nameList;
2895 }
2896 }
2897 }
2898 *numNamesPtr = 0;
2899 return NULL;
2900 }
2901
2902 /*
2903 *---------------------------------------------------------------------------
2904 *
2905 * IdentifySymbolEncodings --
2906 *
2907 * If the font attributes refer to a symbol font, update the
2908 * charset field of the font attributes so that it reflects the
2909 * encoding of that symbol font. In general, the raw value for
2910 * the charset field parsed from an XLFD is meaningless for symbol
2911 * fonts.
2912 *
2913 * Symbol fonts are all fonts whose name appears in the symbolClass.
2914 *
2915 * Results:
2916 * The return value is non-zero if the font attributes specify a
2917 * symbol font, or 0 otherwise. If a non-zero value is returned
2918 * the charset field of the font attributes will be changed to
2919 * the string that represents the actual encoding for the symbol font.
2920 *
2921 * Side effects:
2922 * None.
2923 *
2924 *---------------------------------------------------------------------------
2925 */
2926
2927 static int
2928 IdentifySymbolEncodings(faPtr)
2929 FontAttributes *faPtr;
2930 {
2931 int i, j;
2932 char **aliases, **symbolClass;
2933
2934 symbolClass = TkFontGetSymbolClass();
2935 for (i = 0; symbolClass[i] != NULL; i++) {
2936 if (strcasecmp(faPtr->fa.family, symbolClass[i]) == 0) {
2937 faPtr->xa.charset = Tk_GetUid(GetEncodingAlias(symbolClass[i]));
2938 return 1;
2939 }
2940 aliases = TkFontGetAliasList(symbolClass[i]);
2941 for (j = 0; (aliases != NULL) && (aliases[j] != NULL); j++) {
2942 if (strcasecmp(faPtr->fa.family, aliases[j]) == 0) {
2943 faPtr->xa.charset = Tk_GetUid(GetEncodingAlias(aliases[j]));
2944 return 1;
2945 }
2946 }
2947 }
2948 return 0;
2949 }
2950
2951 /*
2952 *---------------------------------------------------------------------------
2953 *
2954 * GetEncodingAlias --
2955 *
2956 * Map the name of an encoding to another name that should be used
2957 * when actually loading the encoding. For instance, the encodings
2958 * "jisc6226.1978", "jisx0208.1983", "jisx0208.1990", and
2959 * "jisx0208.1996" are well-known names for the same encoding and
2960 * are represented by one encoding table: "jis0208".
2961 *
2962 * Results:
2963 * As above. If the name has no alias, the original name is returned.
2964 *
2965 * Side effects:
2966 * None.
2967 *
2968 *---------------------------------------------------------------------------
2969 */
2970
2971 static CONST char *
2972 GetEncodingAlias(name)
2973 CONST char *name; /* The name to look up. */
2974 {
2975 EncodingAlias *aliasPtr;
2976
2977 for (aliasPtr = encodingAliases; aliasPtr->aliasPattern != NULL; ) {
2978 if (Tcl_StringMatch((char *) name, aliasPtr->aliasPattern)) {
2979 return aliasPtr->realName;
2980 }
2981 aliasPtr++;
2982 }
2983 return name;
2984 }
2985
2986 #endif /* USE_XFT_FONTS */