Debian Codegraph @

pTk/mTk/win/tkWinFont.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 * tkWinFont.c --
3 *
4 * Contains the Windows implementation of the platform-independant
5 * font package interface.
6 *
7 * Copyright (c) 1994 Software Research Associates, Inc.
8 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
9 * Copyright (c) 1998-1999 by Scriptics Corporation.
10 *
11 * See the file "license.terms" for information on usage and redistribution
12 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 *
14 * RCS: @(#) $Id: tkWinFont.c,v 1.17 2003/02/26 02:47:05 hobbs Exp $
15 */
16
17 #include "tkWinInt.h"
18 #include "tkFont.h"
19
20 /*
21 * The following structure represents a font family. It is assumed that
22 * all screen fonts constructed from the same "font family" share certain
23 * properties; all screen fonts with the same "font family" point to a
24 * shared instance of this structure. The most important shared property
25 * is the character existence metrics, used to determine if a screen font
26 * can display a given Unicode character.
27 *
28 * Under Windows, a "font family" is uniquely identified by its face name.
29 */
30
31 #define FONTMAP_SHIFT 10
32
33 #define FONTMAP_PAGES (1 << (sizeof(Tcl_UniChar)*8 - FONTMAP_SHIFT))
34 #define FONTMAP_BITSPERPAGE (1 << FONTMAP_SHIFT)
35
36 typedef struct FontFamily {
37 struct FontFamily *nextPtr; /* Next in list of all known font families. */
38 int refCount; /* How many SubFonts are referring to this
39 * FontFamily. When the refCount drops to
40 * zero, this FontFamily may be freed. */
41 /*
42 * Key.
43 */
44
45 Tk_Uid faceName; /* Face name key for this FontFamily. */
46
47 /*
48 * Derived properties.
49 */
50
51 Tcl_Encoding encoding; /* Encoding for this font family. */
52 int isSymbolFont; /* Non-zero if this is a symbol font. */
53 int isWideFont; /* 1 if this is a double-byte font, 0
54 * otherwise. */
55 BOOL (WINAPI *textOutProc)(HDC, int, int, TCHAR *, int);
56 /* The procedure to use to draw text after
57 * it has been converted from UTF-8 to the
58 * encoding of this font. */
59 BOOL (WINAPI *getTextExtentPoint32Proc)(HDC, TCHAR *, int, LPSIZE);
60 /* The procedure to use to measure text after
61 * it has been converted from UTF-8 to the
62 * encoding of this font. */
63
64 char *fontMap[FONTMAP_PAGES];
65 /* Two-level sparse table used to determine
66 * quickly if the specified character exists.
67 * As characters are encountered, more pages
68 * in this table are dynamically added. The
69 * contents of each page is a bitmask
70 * consisting of FONTMAP_BITSPERPAGE bits,
71 * representing whether this font can be used
72 * to display the given character at the
73 * corresponding bit position. The high bits
74 * of the character are used to pick which
75 * page of the table is used. */
76
77 /*
78 * Cached Truetype font info.
79 */
80
81 int segCount; /* The length of the following arrays. */
82 USHORT *startCount; /* Truetype information about the font, */
83 USHORT *endCount; /* indicating which characters this font
84 * can display (malloced). The format of
85 * this information is (relatively) compact,
86 * but would take longer to search than
87 * indexing into the fontMap[][] table. */
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 HFONT hFont; /* 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 } SubFont;
104
105 /*
106 * The following structure represents Windows' implementation of a font
107 * object.
108 */
109
110 #define SUBFONT_SPACE 3
111 #define BASE_CHARS 128
112
113 typedef struct WinFont {
114 TkFont font; /* Stuff used by generic font package. Must
115 * be first in structure. */
116 SubFont staticSubFonts[SUBFONT_SPACE];
117 /* Builtin space for a limited number of
118 * SubFonts. */
119 int numSubFonts; /* Length of following array. */
120 SubFont *subFontArray; /* Array of SubFonts that have been loaded
121 * in order to draw/measure all the characters
122 * encountered by this font so far. All fonts
123 * start off with one SubFont initialized by
124 * AllocFont() from the original set of font
125 * attributes. Usually points to
126 * staticSubFonts, but may point to malloced
127 * space if there are lots of SubFonts. */
128
129 HWND hwnd; /* Toplevel window of application that owns
130 * this font, used for getting HDC for
131 * offscreen measurements. */
132 int pixelSize; /* Original pixel size used when font was
133 * constructed. */
134 int widths[BASE_CHARS]; /* Widths of first 128 chars in the base
135 * font, for handling common case. The base
136 * font is always used to draw characters
137 * between 0x0000 and 0x007f. */
138 } WinFont;
139
140 /*
141 * The following structure is passed as the LPARAM when calling the font
142 * enumeration procedure to determine if a font can support the given
143 * character.
144 */
145
146 typedef struct CanUse {
147 HDC hdc;
148 WinFont *fontPtr;
149 Tcl_DString *nameTriedPtr;
150 int ch;
151 SubFont *subFontPtr;
152 } CanUse;
153
154 /*
155 * The following structure is used to map between the Tcl strings that
156 * represent the system fonts and the numbers used by Windows.
157 */
158
159 static TkStateMap systemMap[] = {
160 {ANSI_FIXED_FONT, "ansifixed"},
161 {ANSI_VAR_FONT, "ansi"},
162 {DEVICE_DEFAULT_FONT, "device"},
163 {OEM_FIXED_FONT, "oemfixed"},
164 {SYSTEM_FIXED_FONT, "systemfixed"},
165 {SYSTEM_FONT, "system"},
166 {-1, NULL}
167 };
168
169 typedef struct ThreadSpecificData {
170 FontFamily *fontFamilyList; /* The list of font families that are
171 * currently loaded. As screen fonts
172 * are loaded, this list grows to hold
173 * information about what characters
174 * exist in each font family. */
175 Tcl_HashTable uidTable;
176 } ThreadSpecificData;
177 static Tcl_ThreadDataKey dataKey;
178
179 /*
180 * Information cached about the system at startup time.
181 */
182
183 static Tcl_Encoding systemEncoding;
184
185 /*
186 * Procedures used only in this file.
187 */
188
189 static FontFamily * AllocFontFamily(HDC hdc, HFONT hFont, int base);
190 static SubFont * CanUseFallback(HDC hdc, WinFont *fontPtr,
191 char *fallbackName, int ch);
192 static SubFont * CanUseFallbackWithAliases(HDC hdc, WinFont *fontPtr,
193 char *faceName, int ch, Tcl_DString *nameTriedPtr);
194 static int FamilyExists(HDC hdc, CONST char *faceName);
195 static char * FamilyOrAliasExists(HDC hdc, CONST char *faceName);
196 static SubFont * FindSubFontForChar(WinFont *fontPtr, int ch);
197 static void FontMapInsert(SubFont *subFontPtr, int ch);
198 static void FontMapLoadPage(SubFont *subFontPtr, int row);
199 static int FontMapLookup(SubFont *subFontPtr, int ch);
200 static void FreeFontFamily(FontFamily *familyPtr);
201 static HFONT GetScreenFont(CONST TkFontAttributes *faPtr,
202 CONST char *faceName, int pixelSize);
203 static void InitFont(Tk_Window tkwin, HFONT hFont,
204 int overstrike, WinFont *tkFontPtr);
205 static void InitSubFont(HDC hdc, HFONT hFont, int base,
206 SubFont *subFontPtr);
207 static int LoadFontRanges(HDC hdc, HFONT hFont,
208 USHORT **startCount, USHORT **endCount,
209 int *symbolPtr);
210 static void MultiFontTextOut(HDC hdc, WinFont *fontPtr,
211 CONST char *source, int numBytes, int x, int y);
212 static void ReleaseFont(WinFont *fontPtr);
213 static void ReleaseSubFont(SubFont *subFontPtr);
214 static int SeenName(CONST char *name, Tcl_DString *dsPtr);
215 static void SwapLong(PULONG p);
216 static void SwapShort(USHORT *p);
217 static int CALLBACK WinFontCanUseProc(ENUMLOGFONT *lfPtr,
218 NEWTEXTMETRIC *tmPtr, int fontType,
219 LPARAM lParam);
220 static int CALLBACK WinFontExistProc(ENUMLOGFONT *lfPtr,
221 NEWTEXTMETRIC *tmPtr, int fontType,
222 LPARAM lParam);
223 static int CALLBACK WinFontFamilyEnumProc(ENUMLOGFONT *lfPtr,
224 NEWTEXTMETRIC *tmPtr, int fontType,
225 LPARAM lParam);
226
227 /*
228 *-------------------------------------------------------------------------
229 *
230 * TkpFontPkgInit --
231 *
232 * This procedure is called when an application is created. It
233 * initializes all the structures that are used by the
234 * platform-dependent code on a per application basis.
235 *
236 * Results:
237 * None.
238 *
239 * Side effects:
240 *
241 * None.
242 *
243 *-------------------------------------------------------------------------
244 */
245
246 void
247 TkpFontPkgInit(
248 TkMainInfo *mainPtr) /* The application being created. */
249 {
250 if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
251 /*
252 * If running NT, then we will be calling some Unicode functions
•253 * explicitly. So, even if the Tcl system encoding isn't Unicode,
254 * make sure we convert to/from the Unicode char set.
255 */
256
257 systemEncoding = TkWinGetUnicodeEncoding();
258 }
259 }
260
261 /*
262 *---------------------------------------------------------------------------
263 *
264 * TkpGetNativeFont --
265 *
266 * Map a platform-specific native font name to a TkFont.
267 *
268 * Results:
269 * The return value is a pointer to a TkFont that represents the
270 * native font. If a native font by the given name could not be
271 * found, the return value is NULL.
272 *
273 * Every call to this procedure returns a new TkFont structure,
274 * even if the name has already been seen before. The caller should
275 * call TkpDeleteFont() when the font is no longer needed.
276 *
277 * The caller is responsible for initializing the memory associated
278 * with the generic TkFont when this function returns and releasing
279 * the contents of the generic TkFont before calling TkpDeleteFont().
280 *
281 * Side effects:
282 * Memory allocated.
283 *
284 *---------------------------------------------------------------------------
285 */
286
287 TkFont *
288 TkpGetNativeFont(
289 Tk_Window tkwin, /* For display where font will be used. */
290 CONST char *name) /* Platform-specific font name. */
291 {
292 int object;
293 WinFont *fontPtr;
294
295 object = TkFindStateNum(NULL, NULL, systemMap, name);
296 if (object < 0) {
297 return NULL;
298 }
299
300 tkwin = (Tk_Window) ((TkWindow *) tkwin)->mainPtr->winPtr;
301 fontPtr = (WinFont *) ckalloc(sizeof(WinFont));
302 InitFont(tkwin, GetStockObject(object), 0, fontPtr);
303
304 return (TkFont *) fontPtr;
305 }
306
307 /*
308 *---------------------------------------------------------------------------
309 *
310 * TkpGetFontFromAttributes --
311 *
312 * Given a desired set of attributes for a font, find a font with
313 * the closest matching attributes.
314 *
315 * Results:
316 * The return value is a pointer to a TkFont that represents the
317 * font with the desired attributes. If a font with the desired
318 * attributes could not be constructed, some other font will be
319 * substituted automatically. NULL is never returned.
320 *
321 * Every call to this procedure returns a new TkFont structure,
322 * even if the specified attributes have already been seen before.
323 * The caller should call TkpDeleteFont() to free the platform-
324 * specific data when the font is no longer needed.
325 *
326 * The caller is responsible for initializing the memory associated
327 * with the generic TkFont when this function returns and releasing
328 * the contents of the generic TkFont before calling TkpDeleteFont().
329 *
330 * Side effects:
331 * Memory allocated.
332 *
333 *---------------------------------------------------------------------------
334 */
335
336 TkFont *
337 TkpGetFontFromAttributes(
338 TkFont *tkFontPtr, /* If non-NULL, store the information in
339 * this existing TkFont structure, rather than
340 * allocating a new structure to hold the
341 * font; the existing contents of the font
342 * will be released. If NULL, a new TkFont
343 * structure is allocated. */
344 Tk_Window tkwin, /* For display where font will be used. */
345 CONST TkFontAttributes *faPtr)
346 /* Set of attributes to match. */
347 {
348 int i, j;
349 HDC hdc;
350 HWND hwnd;
351 HFONT hFont;
352 Window window;
353 WinFont *fontPtr;
354 char ***fontFallbacks;
355 Tk_Uid faceName, fallback, actualName;
356
357 tkwin = (Tk_Window) ((TkWindow *) tkwin)->mainPtr->winPtr;
358 window = Tk_WindowId(tkwin);
359 hwnd = (window == None) ? NULL : TkWinGetHWND(window);
360 hdc = GetDC(hwnd);
361
362 /*
363 * Algorithm to get the closest font name to the one requested.
364 *
365 * try fontname
366 * try all aliases for fontname
367 * foreach fallback for fontname
368 * try the fallback
369 * try all aliases for the fallback
370 */
371
372 faceName = faPtr->family;
373 if (faceName != NULL) {
374 actualName = FamilyOrAliasExists(hdc, faceName);
375 if (actualName != NULL) {
376 faceName = actualName;
377 goto found;
378 }
379 fontFallbacks = TkFontGetFallbacks();
380 for (i = 0; fontFallbacks[i] != NULL; i++) {
381 for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) {
382 if (strcasecmp(faceName, fallback) == 0) {
383 break;
384 }
385 }
386 if (fallback != NULL) {
387 for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) {
388 actualName = FamilyOrAliasExists(hdc, fallback);
389 if (actualName != NULL) {
390 faceName = actualName;
391 goto found;
392 }
393 }
394 }
395 }
396 }
397
398 found:
399 ReleaseDC(hwnd, hdc);
400
401 hFont = GetScreenFont(faPtr, faceName, TkFontGetPixels(Tk_Screen(tkwin), faPtr->size));
402 if (tkFontPtr == NULL) {
403 fontPtr = (WinFont *) ckalloc(sizeof(WinFont));
404 } else {
405 fontPtr = (WinFont *) tkFontPtr;
406 ReleaseFont(fontPtr);
407 }
408 InitFont(tkwin, hFont, faPtr->overstrike, fontPtr);
409
410 return (TkFont *) fontPtr;
411 }
412
413 /*
414 *---------------------------------------------------------------------------
415 *
416 * TkpDeleteFont --
417 *
418 * Called to release a font allocated by TkpGetNativeFont() or
419 * TkpGetFontFromAttributes(). The caller should have already
420 * released the fields of the TkFont that are used exclusively by
421 * the generic TkFont code.
422 *
423 * Results:
424 * None.
425 *
426 * Side effects:
427 * TkFont is deallocated.
428 *
429 *---------------------------------------------------------------------------
430 */
431
432 void
433 TkpDeleteFont(
434 TkFont *tkFontPtr) /* Token of font to be deleted. */
435 {
436 WinFont *fontPtr;
437
438 fontPtr = (WinFont *) tkFontPtr;
439 ReleaseFont(fontPtr);
440 }
441
442 /*
443 *---------------------------------------------------------------------------
444 *
445 * TkpGetFontFamilies, WinFontFamilyEnumProc --
446 *
447 * Return information about the font families that are available
448 * on the display of the given window.
449 *
450 * Results:
451 * Modifies interp's result object to hold a list of all the available
452 * font families.
453 *
454 * Side effects:
455 * None.
456 *
457 *---------------------------------------------------------------------------
458 */
459
460 void
461 TkpGetFontFamilies(
462 Tcl_Interp *interp, /* Interp to hold result. */
463 Tk_Window tkwin) /* For display to query. */
464 {
465 HDC hdc;
466 HWND hwnd;
467 Window window;
468
469 window = Tk_WindowId(tkwin);
470 hwnd = (window == None) ? NULL : TkWinGetHWND(window);
471 hdc = GetDC(hwnd);
472
473 /*
474 * On any version NT, there may fonts with international names.
475 * Use the NT-only Unicode version of EnumFontFamilies to get the
476 * font names. If we used the ANSI version on a non-internationalized
477 * version of NT, we would get font names with '?' replacing all
478 * the international characters.
479 *
480 * On a non-internationalized verson of 95, fonts with international
481 * names are not allowed, so the ANSI version of EnumFontFamilies will
482 * work. On an internationalized version of 95, there may be fonts with
483 * international names; the ANSI version will work, fetching the
484 * name in the system code page. Can't use the Unicode version of
485 * EnumFontFamilies because it only exists under NT.
486 */
487
488 if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
489 EnumFontFamiliesW(hdc, NULL, (FONTENUMPROCW) WinFontFamilyEnumProc,
490 (LPARAM) interp);
491 } else {
492 EnumFontFamiliesA(hdc, NULL, (FONTENUMPROCA) WinFontFamilyEnumProc,
493 (LPARAM) interp);
494 }
495 ReleaseDC(hwnd, hdc);
496 }
497
498 static int CALLBACK
499 WinFontFamilyEnumProc(
500 ENUMLOGFONT *lfPtr, /* Logical-font data. */
501 NEWTEXTMETRIC *tmPtr, /* Physical-font data (not used). */
502 int fontType, /* Type of font (not used). */
503 LPARAM lParam) /* Result object to hold result. */
504 {
505 char *faceName;
506 Tcl_DString faceString;
507 Tcl_Obj *strPtr;
508 Tcl_Interp *interp;
509
510 interp = (Tcl_Interp *) lParam;
511 faceName = lfPtr->elfLogFont.lfFaceName;
512 Tcl_ExternalToUtfDString(systemEncoding, faceName, -1, &faceString);
513 strPtr = Tcl_NewStringObj(Tcl_DStringValue(&faceString),
514 Tcl_DStringLength(&faceString));
515 Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp), strPtr);
516 Tcl_DStringFree(&faceString);
517 return 1;
518 }
519
520 /*
521 *-------------------------------------------------------------------------
522 *
523 * TkpGetSubFonts --
524 *
525 * A function used by the testing package for querying the actual
526 * screen fonts that make up a font object.
527 *
528 * Results:
529 * Modifies interp's result object to hold a list containing the
530 * names of the screen fonts that make up the given font object.
531 *
532 * Side effects:
533 * None.
534 *
535 *-------------------------------------------------------------------------
536 */
537
538 void
539 TkpGetSubFonts(
540 Tcl_Interp *interp, /* Interp to hold result. */
541 Tk_Font tkfont) /* Font object to query. */
542 {
543 int i;
544 WinFont *fontPtr;
545 FontFamily *familyPtr;
546 Tcl_Obj *resultPtr;
547 Tcl_Obj *values[2];
548
549 resultPtr = Tcl_GetObjResult(interp);
550 fontPtr = (WinFont *) tkfont;
551 for (i = 0; i < fontPtr->numSubFonts; i++) {
552 familyPtr = fontPtr->subFontArray[i].familyPtr;
553 values[0] = Tcl_NewStringObj(familyPtr->faceName, -1);
554 values[1] = Tcl_NewStringObj(Tcl_GetEncodingName(familyPtr->encoding),-1);
555 Tcl_ListObjAppendElement(interp, resultPtr, Tcl_NewListObj(2,values));
556 }
557 }
558
559 /*
560 *---------------------------------------------------------------------------
561 *
562 * Tk_MeasureChars --
563 *
564 * Determine the number of bytes from the string that will fit
565 * in the given horizontal span. The measurement is done under the
566 * assumption that Tk_DrawChars() will be used to actually display
567 * the characters.
568 *
569 * Results:
570 * The return value is the number of bytes from source that
571 * fit into the span that extends from 0 to maxLength. *lengthPtr is
572 * filled with the x-coordinate of the right edge of the last
573 * character that did fit.
574 *
575 * Side effects:
576 * None.
577 *
578 *---------------------------------------------------------------------------
579 */
580
581 int
582 Tk_MeasureChars(
583 Tk_Font tkfont, /* Font in which characters will be drawn. */
584 CONST char *source, /* UTF-8 string to be displayed. Need not be
585 * '\0' terminated. */
586 int numBytes, /* Maximum number of bytes to consider
587 * from source string. */
588 int maxLength, /* If >= 0, maxLength specifies the longest
589 * permissible line length in pixels; don't
590 * consider any character that would cross
591 * this x-position. If < 0, then line length
592 * is unbounded and the flags argument is
593 * ignored. */
594 int flags, /* Various flag bits OR-ed together:
595 * TK_PARTIAL_OK means include the last char
596 * which only partially fit on this line.
597 * TK_WHOLE_WORDS means stop on a word
598 * boundary, if possible.
599 * TK_AT_LEAST_ONE means return at least one
600 * character even if no characters fit. */
601 int *lengthPtr) /* Filled with x-location just after the
602 * terminating character. */
603 {
604 HDC hdc;
605 HFONT oldFont;
606 WinFont *fontPtr;
607 int curX, curByte;
608 SubFont *lastSubFontPtr;
609
610 /*
611 * According to Microsoft tech support, Windows does not use kerning
612 * or fractional character widths when displaying text on the screen.
613 * So that means we can safely measure individual characters or spans
614 * of characters and add up the widths w/o any "off-by-one-pixel"
615 * errors.
616 */
617
618 fontPtr = (WinFont *) tkfont;
619
620 hdc = GetDC(fontPtr->hwnd);
621 lastSubFontPtr = &fontPtr->subFontArray[0];
622 oldFont = SelectObject(hdc, lastSubFontPtr->hFont);
623
624 if (numBytes == 0) {
625 curX = 0;
626 curByte = 0;
627 } else if (maxLength < 0) {
628 Tcl_UniChar ch;
629 SIZE size;
630 FontFamily *familyPtr;
631 Tcl_DString runString;
632 SubFont *thisSubFontPtr;
633 CONST char *p, *end, *next;
634
635 /*
636 * A three step process:
637 * 1. Find a contiguous range of characters that can all be
638 * represented by a single screen font.
639 * 2. Convert those chars to the encoding of that font.
640 * 3. Measure converted chars.
641 */
642
643 curX = 0;
644 end = source + numBytes;
645 for (p = source; p < end; ) {
646 next = p + Tcl_UtfToUniChar(p, &ch);
647 thisSubFontPtr = FindSubFontForChar(fontPtr, ch);
648 if (thisSubFontPtr != lastSubFontPtr) {
649 familyPtr = lastSubFontPtr->familyPtr;
650 Tcl_UtfToExternalDString(familyPtr->encoding, source,
651 (int) (p - source), &runString);
652 (*familyPtr->getTextExtentPoint32Proc)(hdc,
653 Tcl_DStringValue(&runString),
654 Tcl_DStringLength(&runString) >> familyPtr->isWideFont,
655 &size);
656 curX += size.cx;
657 Tcl_DStringFree(&runString);
658 lastSubFontPtr = thisSubFontPtr;
659 source = p;
660
661 SelectObject(hdc, lastSubFontPtr->hFont);
662 }
663 p = next;
664 }
665 familyPtr = lastSubFontPtr->familyPtr;
666 Tcl_UtfToExternalDString(familyPtr->encoding, source,
667 (int) (p - source), &runString);
668 (*familyPtr->getTextExtentPoint32Proc)(hdc,
669 Tcl_DStringValue(&runString),
670 Tcl_DStringLength(&runString) >> familyPtr->isWideFont,
671 &size);
672 curX += size.cx;
673 Tcl_DStringFree(&runString);
674 curByte = numBytes;
675 } else {
676 Tcl_UniChar ch;
677 SIZE size;
678 char buf[16];
679 FontFamily *familyPtr;
680 SubFont *thisSubFontPtr;
681 CONST char *term, *end, *p, *next;
682 int newX, termX, sawNonSpace, dstWrote;
683
684 /*
685 * How many chars will fit in the space allotted?
686 * This first version may be inefficient because it measures
687 * every character individually. There is a function call that
688 * can measure multiple characters at once and return the
689 * offset of each of them, but it only works on NT, even though
690 * the documentation claims it works for 95.
691 * TODO: verify that GetTextExtentExPoint is still broken in '95, and
692 * possibly use it for NT anyway since it should be much faster and
693 * more accurate.
694 */
695
696 next = source + Tcl_UtfToUniChar(source, &ch);
697 newX = curX = termX = 0;
698
699 term = source;
700 end = source + numBytes;
701
702 sawNonSpace = (ch > 255) || !isspace(ch);
703 for (p = source; ; ) {
704 if (ch < BASE_CHARS) {
705 newX += fontPtr->widths[ch];
706 } else {
707 thisSubFontPtr = FindSubFontForChar(fontPtr, ch);
708 if (thisSubFontPtr != lastSubFontPtr) {
709 SelectObject(hdc, thisSubFontPtr->hFont);
710 lastSubFontPtr = thisSubFontPtr;
711 }
712 familyPtr = lastSubFontPtr->familyPtr;
713 Tcl_UtfToExternal(NULL, familyPtr->encoding, p,
714 (int) (next - p), 0, NULL, buf, sizeof(buf), NULL,
715 &dstWrote, NULL);
716 (*familyPtr->getTextExtentPoint32Proc)(hdc, buf,
717 dstWrote >> familyPtr->isWideFont, &size);
718 newX += size.cx;
719 }
720 if (newX > maxLength) {
721 break;
722 }
723 curX = newX;
724 p = next;
725 if (p >= end) {
726 term = end;
727 termX = curX;
728 break;
729 }
730
731 next += Tcl_UtfToUniChar(next, &ch);
732 if ((ch < 256) && isspace(ch)) {
733 if (sawNonSpace) {
734 term = p;
735 termX = curX;
736 sawNonSpace = 0;
737 }
738 } else {
739 sawNonSpace = 1;
740 }
741 }
742
743 /*
744 * P points to the first character that doesn't fit in the desired
745 * span. Use the flags to figure out what to return.
746 */
747
748 if ((flags & TK_PARTIAL_OK) && (p < end) && (curX < maxLength)) {
749 /*
750 * Include the first character that didn't quite fit in the desired
751 * span. The width returned will include the width of that extra
752 * character.
753 */
754
755 curX = newX;
756 p += Tcl_UtfToUniChar(p, &ch);
757 }
758 if ((flags & TK_AT_LEAST_ONE) && (term == source) && (p < end)) {
759 term = p;
760 termX = curX;
761 if (term == source) {
762 term += Tcl_UtfToUniChar(term, &ch);
763 termX = newX;
764 }
765 } else if ((p >= end) || !(flags & TK_WHOLE_WORDS)) {
766 term = p;
767 termX = curX;
768 }
769
770 curX = termX;
771 curByte = (int) (term - source);
772 }
773
774 SelectObject(hdc, oldFont);
775 ReleaseDC(fontPtr->hwnd, hdc);
776
777 *lengthPtr = curX;
778 return curByte;
779 }
780
781 /*
782 *---------------------------------------------------------------------------
783 *
784 * Tk_DrawChars --
785 *
786 * Draw a string of characters on the screen.
787 *
788 * Results:
789 * None.
790 *
791 * Side effects:
792 * Information gets drawn on the screen.
793 *
794 *---------------------------------------------------------------------------
795 */
796
797 void
798 Tk_DrawChars(
799 Display *display, /* Display on which to draw. */
800 Drawable drawable, /* Window or pixmap in which to draw. */
801 GC gc, /* Graphics context for drawing characters. */
802 Tk_Font tkfont, /* Font in which characters will be drawn;
803 * must be the same as font used in GC. */
804 CONST char *source, /* UTF-8 string to be displayed. Need not be
805 * '\0' terminated. All Tk meta-characters
806 * (tabs, control characters, and newlines)
807 * should be stripped out of the string that
808 * is passed to this function. If they are
809 * not stripped out, they will be displayed as
810 * regular printing characters. */
811 int numBytes, /* Number of bytes in string. */
812 int x, int y) /* Coordinates at which to place origin of
813 * string when drawing. */
814 {
815 HDC dc;
816 WinFont *fontPtr;
817 TkWinDCState state;
818
819 fontPtr = (WinFont *) gc->font;
820 display->request++;
821
822 if (drawable == None) {
823 return;
824 }
825
826 dc = TkWinGetDrawableDC(display, drawable, &state);
827
828 SetROP2(dc, tkpWinRopModes[gc->function]);
829
830 if ((gc->clip_mask != None) &&
831 ((TkpClipMask*)gc->clip_mask)->type == TKP_CLIP_REGION) {
832 SelectClipRgn(dc, (HRGN)((TkpClipMask*)gc->clip_mask)->value.region);
833 }
834
835 if ((gc->fill_style == FillStippled
836 || gc->fill_style == FillOpaqueStippled)
837 && gc->stipple != None) {
838 TkWinDrawable *twdPtr = (TkWinDrawable *)gc->stipple;
839 HBRUSH oldBrush, stipple;
840 HBITMAP oldBitmap, bitmap;
841 HDC dcMem;
842 TEXTMETRIC tm;
843 SIZE size;
844
845 if (twdPtr->type != TWD_BITMAP) {
846 panic("unexpected drawable type in stipple");
847 }
848
849 /*
850 * Select stipple pattern into destination dc.
851 */
852
853 dcMem = CreateCompatibleDC(dc);
854
855 stipple = CreatePatternBrush(twdPtr->bitmap.handle);
856 SetBrushOrgEx(dc, gc->ts_x_origin, gc->ts_y_origin, NULL);
857 oldBrush = SelectObject(dc, stipple);
858
859 SetTextAlign(dcMem, TA_LEFT | TA_BASELINE);
860 SetTextColor(dcMem, gc->foreground);
861 SetBkMode(dcMem, TRANSPARENT);
862 SetBkColor(dcMem, RGB(0, 0, 0));
863
864 /*
865 * Compute the bounding box and create a compatible bitmap.
866 */
867
868 GetTextExtentPoint(dcMem, source, numBytes, &size);
869 GetTextMetrics(dcMem, &tm);
870 size.cx -= tm.tmOverhang;
871 bitmap = CreateCompatibleBitmap(dc, size.cx, size.cy);
872 oldBitmap = SelectObject(dcMem, bitmap);
873
874 /*
875 * The following code is tricky because fonts are rendered in multiple
876 * colors. First we draw onto a black background and copy the white
877 * bits. Then we draw onto a white background and copy the black bits.
878 * Both the foreground and background bits of the font are ANDed with
879 * the stipple pattern as they are copied.
880 */
881
882 PatBlt(dcMem, 0, 0, size.cx, size.cy, BLACKNESS);
883 MultiFontTextOut(dc, fontPtr, source, numBytes, x, y);
884 BitBlt(dc, x, y - tm.tmAscent, size.cx, size.cy, dcMem,
885 0, 0, 0xEA02E9);
886 PatBlt(dcMem, 0, 0, size.cx, size.cy, WHITENESS);
887 MultiFontTextOut(dc, fontPtr, source, numBytes, x, y);
888 BitBlt(dc, x, y - tm.tmAscent, size.cx, size.cy, dcMem,
889 0, 0, 0x8A0E06);
890
891 /*
892 * Destroy the temporary bitmap and restore the device context.
893 */
894
895 SelectObject(dcMem, oldBitmap);
896 DeleteObject(bitmap);
897 DeleteDC(dcMem);
898 SelectObject(dc, oldBrush);
899 DeleteObject(stipple);
900 } else if (gc->function == GXcopy) {
901 SetTextAlign(dc, TA_LEFT | TA_BASELINE);
902 SetTextColor(dc, gc->foreground);
903 SetBkMode(dc, TRANSPARENT);
904 MultiFontTextOut(dc, fontPtr, source, numBytes, x, y);
905 } else {
906 HBITMAP oldBitmap, bitmap;
907 HDC dcMem;
908 TEXTMETRIC tm;
909 SIZE size;
910
911 dcMem = CreateCompatibleDC(dc);
912
913 SetTextAlign(dcMem, TA_LEFT | TA_BASELINE);
914 SetTextColor(dcMem, gc->foreground);
915 SetBkMode(dcMem, TRANSPARENT);
916 SetBkColor(dcMem, RGB(0, 0, 0));
917
918 /*
919 * Compute the bounding box and create a compatible bitmap.
920 */
921
922 GetTextExtentPoint(dcMem, source, numBytes, &size);
923 GetTextMetrics(dcMem, &tm);
924 size.cx -= tm.tmOverhang;
925 bitmap = CreateCompatibleBitmap(dc, size.cx, size.cy);
926 oldBitmap = SelectObject(dcMem, bitmap);
927
928 MultiFontTextOut(dcMem, fontPtr, source, numBytes, 0, tm.tmAscent);
929 BitBlt(dc, x, y - tm.tmAscent, size.cx, size.cy, dcMem,
930 0, 0, tkpWinBltModes[gc->function]);
931
932 /*
933 * Destroy the temporary bitmap and restore the device context.
934 */
935
936 SelectObject(dcMem, oldBitmap);
937 DeleteObject(bitmap);
938 DeleteDC(dcMem);
939 }
940 TkWinReleaseDrawableDC(drawable, dc, &state);
941 }
942
943 /*
944 *-------------------------------------------------------------------------
945 *
946 * MultiFontTextOut --
947 *
948 * Helper function for Tk_DrawChars. Draws characters, using the
949 * various screen fonts in fontPtr to draw multilingual characters.
950 * Note: No bidirectional support.
951 *
952 * Results:
953 * None.
954 *
955 * Side effects:
956 * Information gets drawn on the screen.
957 * Contents of fontPtr may be modified if more subfonts were loaded
958 * in order to draw all the multilingual characters in the given
959 * string.
960 *
961 *-------------------------------------------------------------------------
962 */
963
964 static void
965 MultiFontTextOut(
966 HDC hdc, /* HDC to draw into. */
967 WinFont *fontPtr, /* Contains set of fonts to use when drawing
968 * following string. */
969 CONST char *source, /* Potentially multilingual UTF-8 string. */
970 int numBytes, /* Length of string in bytes. */
971 int x, int y) /* Coordinates at which to place origin *
972 * of string when drawing. */
973 {
974 Tcl_UniChar ch;
975 SIZE size;
976 HFONT oldFont;
977 FontFamily *familyPtr;
978 Tcl_DString runString;
979 CONST char *p, *end, *next;
980 SubFont *lastSubFontPtr, *thisSubFontPtr;
981
982 lastSubFontPtr = &fontPtr->subFontArray[0];
983 oldFont = SelectObject(hdc, lastSubFontPtr->hFont);
984
985 end = source + numBytes;
986 for (p = source; p < end; ) {
987 next = p + Tcl_UtfToUniChar(p, &ch);
988 thisSubFontPtr = FindSubFontForChar(fontPtr, ch);
989 if (thisSubFontPtr != lastSubFontPtr) {
990 if (p > source) {
991 familyPtr = lastSubFontPtr->familyPtr;
992 Tcl_UtfToExternalDString(familyPtr->encoding, source,
993 (int) (p - source), &runString);
994 (*familyPtr->textOutProc)(hdc, x, y,
995 Tcl_DStringValue(&runString),
996 Tcl_DStringLength(&runString) >> familyPtr->isWideFont);
997 (*familyPtr->getTextExtentPoint32Proc)(hdc,
998 Tcl_DStringValue(&runString),
999 Tcl_DStringLength(&runString) >> familyPtr->isWideFont,
1000 &size);
1001 x += size.cx;
1002 Tcl_DStringFree(&runString);
1003 }
1004 lastSubFontPtr = thisSubFontPtr;
1005 source = p;
1006 SelectObject(hdc, lastSubFontPtr->hFont);
1007 }
1008 p = next;
1009 }
1010 if (p > source) {
1011 familyPtr = lastSubFontPtr->familyPtr;
1012 Tcl_UtfToExternalDString(familyPtr->encoding, source,
1013 (int) (p - source), &runString);
1014 (*familyPtr->textOutProc)(hdc, x, y, Tcl_DStringValue(&runString),
1015 Tcl_DStringLength(&runString) >> familyPtr->isWideFont);
1016 Tcl_DStringFree(&runString);
1017 }
1018 SelectObject(hdc, oldFont);
1019 }
1020
1021 /*
1022 *---------------------------------------------------------------------------
1023 *
1024 * InitFont --
1025 *
1026 * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes().
1027 * Initializes the memory for a new WinFont that wraps the
1028 * platform-specific data.
1029 *
1030 * The caller is responsible for initializing the fields of the
1031 * WinFont that are used exclusively by the generic TkFont code, and
1032 * for releasing those fields before calling TkpDeleteFont().
1033 *
1034 * Results:
1035 * Fills the WinFont structure.
1036 *
1037 * Side effects:
1038 * Memory allocated.
1039 *
1040 *---------------------------------------------------------------------------
1041 */
1042
1043 static void
1044 InitFont(
1045 Tk_Window tkwin, /* Main window of interp in which font will
1046 * be used, for getting HDC. */
1047 HFONT hFont, /* Windows token for font. */
1048 int overstrike, /* The overstrike attribute of logfont used
1049 * to allocate this font. For some reason,
1050 * the TEXTMETRICs may contain incorrect info
1051 * in the tmStruckOut field. */
1052 WinFont *fontPtr) /* Filled with information constructed from
1053 * the above arguments. */
1054 {
1055 HDC hdc;
1056 HWND hwnd;
1057 HFONT oldFont;
1058 TEXTMETRIC tm;
1059 Window window;
1060 TkFontMetrics *fmPtr;
1061 Tcl_Encoding encoding;
1062 Tcl_DString faceString;
1063 TkFontAttributes *faPtr;
1064 char buf[LF_FACESIZE * sizeof(WCHAR)];
1065
1066 window = Tk_WindowId(tkwin);
1067 hwnd = (window == None) ? NULL : TkWinGetHWND(window);
1068 hdc = GetDC(hwnd);
1069 oldFont = SelectObject(hdc, hFont);
1070
1071 GetTextMetrics(hdc, &tm);
1072
1073 /*
1074 * On any version NT, there may fonts with international names.
1075 * Use the NT-only Unicode version of GetTextFace to get the font's
1076 * name. If we used the ANSI version on a non-internationalized
1077 * version of NT, we would get a font name with '?' replacing all
1078 * the international characters.
1079 *
1080 * On a non-internationalized verson of 95, fonts with international
1081 * names are not allowed, so the ANSI version of GetTextFace will work.
1082 * On an internationalized version of 95, there may be fonts with
1083 * international names; the ANSI version will work, fetching the
1084 * name in the international system code page. Can't use the Unicode
1085 * version of GetTextFace because it only exists under NT.
1086 */
1087
1088 if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
1089 GetTextFaceW(hdc, LF_FACESIZE, (WCHAR *) buf);
1090 } else {
1091 GetTextFaceA(hdc, LF_FACESIZE, (char *) buf);
1092 }
1093 Tcl_ExternalToUtfDString(systemEncoding, buf, -1, &faceString);
1094
1095 fontPtr->font.fid = (Font) fontPtr;
1096
1097 faPtr = &fontPtr->font.fa;
1098 faPtr->family = Tk_GetUid(Tcl_DStringValue(&faceString));
1099 #if 0
1100 faPtr->size = TkFontGetPoints(Tk_Screen(tkwin), -(tm.tmHeight - tm.tmInternalLeading));
1101 #else
1102 faPtr->size = -(tm.tmHeight - tm.tmInternalLeading);
1103 #endif
1104 faPtr->weight = (tm.tmWeight > FW_MEDIUM) ? TK_FW_BOLD : TK_FW_NORMAL;
1105 faPtr->slant = (tm.tmItalic != 0) ? TK_FS_ITALIC : TK_FS_ROMAN;
1106 faPtr->underline = (tm.tmUnderlined != 0) ? 1 : 0;
1107 faPtr->overstrike = overstrike;
1108
1109 fmPtr = &fontPtr->font.fm;
1110 fmPtr->ascent = tm.tmAscent;
1111 fmPtr->descent = tm.tmDescent;
1112 fmPtr->maxWidth = tm.tmMaxCharWidth;
1113 fmPtr->fixed = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH);
1114
1115 fontPtr->hwnd = hwnd;
1116 fontPtr->pixelSize = tm.tmHeight - tm.tmInternalLeading;
1117
1118 fontPtr->numSubFonts = 1;
1119 fontPtr->subFontArray = fontPtr->staticSubFonts;
1120 InitSubFont(hdc, hFont, 1, &fontPtr->subFontArray[0]);
1121
1122 encoding = fontPtr->subFontArray[0].familyPtr->encoding;
1123 if (encoding == TkWinGetUnicodeEncoding()) {
1124 GetCharWidthW(hdc, 0, BASE_CHARS - 1, fontPtr->widths);
1125 } else {
1126 GetCharWidthA(hdc, 0, BASE_CHARS - 1, fontPtr->widths);
1127 }
1128 Tcl_DStringFree(&faceString);
1129
1130 SelectObject(hdc, oldFont);
1131 ReleaseDC(hwnd, hdc);
1132 }
1133
1134 /*
1135 *-------------------------------------------------------------------------
1136 *
1137 * ReleaseFont --
1138 *
1139 * Called to release the windows-specific contents of a TkFont.
1140 * The caller is responsible for freeing the memory used by the
1141 * font itself.
1142 *
1143 * Results:
1144 * None.
1145 *
1146 * Side effects:
1147 * Memory is freed.
1148 *
1149 *---------------------------------------------------------------------------
1150 */
1151
1152 static void
1153 ReleaseFont(
1154 WinFont *fontPtr) /* The font to delete. */
1155 {
1156 int i;
1157
1158 for (i = 0; i < fontPtr->numSubFonts; i++) {
1159 ReleaseSubFont(&fontPtr->subFontArray[i]);
1160 }
1161 if (fontPtr->subFontArray != fontPtr->staticSubFonts) {
1162 ckfree((char *) fontPtr->subFontArray);
1163 }
1164 }
1165
1166 /*
1167 *-------------------------------------------------------------------------
1168 *
1169 * InitSubFont --
1170 *
1171 * Wrap a screen font and load the FontFamily that represents
1172 * it. Used to prepare a SubFont so that characters can be mapped
1173 * from UTF-8 to the charset of the font.
1174 *
1175 * Results:
1176 * The subFontPtr is filled with information about the font.
1177 *
1178 * Side effects:
1179 * None.
1180 *
1181 *-------------------------------------------------------------------------
1182 */
1183
1184 static void
1185 InitSubFont(
1186 HDC hdc, /* HDC in which font can be selected. */
1187 HFONT hFont, /* The screen font. */
1188 int base, /* Non-zero if this SubFont is being used
1189 * as the base font for a font object. */
1190 SubFont *subFontPtr) /* Filled with SubFont constructed from
1191 * above attributes. */
1192 {
1193 subFontPtr->hFont = hFont;
1194 subFontPtr->familyPtr = AllocFontFamily(hdc, hFont, base);
1195 subFontPtr->fontMap = subFontPtr->familyPtr->fontMap;
1196 }
1197
1198 /*
1199 *-------------------------------------------------------------------------
1200 *
1201 * ReleaseSubFont --
1202 *
1203 * Called to release the contents of a SubFont. The caller is
1204 * responsible for freeing the memory used by the SubFont itself.
1205 *
1206 * Results:
1207 * None.
1208 *
1209 * Side effects:
1210 * Memory and resources are freed.
1211 *
1212 *---------------------------------------------------------------------------
1213 */
1214
1215 static void
1216 ReleaseSubFont(
1217 SubFont *subFontPtr) /* The SubFont to delete. */
1218 {
1219 DeleteObject(subFontPtr->hFont);
1220 FreeFontFamily(subFontPtr->familyPtr);
1221 }
1222
1223 /*
1224 *-------------------------------------------------------------------------
1225 *
1226 * AllocFontFamily --
1227 *
1228 * Find the FontFamily structure associated with the given font
1229 * name. The information should be stored by the caller in a
1230 * SubFont and used when determining if that SubFont supports a
1231 * character.
1232 *
1233 * Cannot use the string name used to construct the font as the
1234 * key, because the capitalization may not be canonical. Therefore
1235 * use the face name actually retrieved from the font metrics as
1236 * the key.
1237 *
1238 * Results:
1239 * A pointer to a FontFamily. The reference count in the FontFamily
1240 * is automatically incremented. When the SubFont is released, the
1241 * reference count is decremented. When no SubFont is using this
1242 * FontFamily, it may be deleted.
1243 *
1244 * Side effects:
1245 * A new FontFamily structure will be allocated if this font family
1246 * has not been seen. TrueType character existence metrics are
1247 * loaded into the FontFamily structure.
1248 *
1249 *-------------------------------------------------------------------------
1250 */
1251
1252 static FontFamily *
1253 AllocFontFamily(
1254 HDC hdc, /* HDC in which font can be selected. */
1255 HFONT hFont, /* Screen font whose FontFamily is to be
1256 * returned. */
1257 int base) /* Non-zero if this font family is to be
1258 * used in the base font of a font object. */
1259 {
1260 Tk_Uid faceName;
1261 FontFamily *familyPtr;
1262 Tcl_DString faceString;
1263 Tcl_Encoding encoding;
1264 char buf[LF_FACESIZE * sizeof(WCHAR)];
1265 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1266 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1267
1268 hFont = SelectObject(hdc, hFont);
1269 if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
1270 GetTextFaceW(hdc, LF_FACESIZE, (WCHAR *) buf);
1271 } else {
1272 GetTextFaceA(hdc, LF_FACESIZE, (char *) buf);
1273 }
1274 Tcl_ExternalToUtfDString(systemEncoding, buf, -1, &faceString);
1275 faceName = Tk_GetUid(Tcl_DStringValue(&faceString));
1276 Tcl_DStringFree(&faceString);
1277 hFont = SelectObject(hdc, hFont);
1278
1279 familyPtr = tsdPtr->fontFamilyList;
1280 for ( ; familyPtr != NULL; familyPtr = familyPtr->nextPtr) {
1281 if (familyPtr->faceName == faceName) {
1282 familyPtr->refCount++;
1283 return familyPtr;
1284 }
1285 }
1286
1287 familyPtr = (FontFamily *) ckalloc(sizeof(FontFamily));
1288 memset(familyPtr, 0, sizeof(FontFamily));
1289 familyPtr->nextPtr = tsdPtr->fontFamilyList;
1290 tsdPtr->fontFamilyList = familyPtr;
1291
1292 /*
1293 * Set key for this FontFamily.
1294 */
1295
1296 familyPtr->faceName = faceName;
1297
1298 /*
1299 * An initial refCount of 2 means that FontFamily information will
1300 * persist even when the SubFont that loaded the FontFamily is released.
1301 * Change it to 1 to cause FontFamilies to be unloaded when not in use.
1302 */
1303
1304 familyPtr->refCount = 2;
1305
1306 familyPtr->segCount = LoadFontRanges(hdc, hFont, &familyPtr->startCount,
1307 &familyPtr->endCount, &familyPtr->isSymbolFont);
1308
1309 encoding = NULL;
1310 if (familyPtr->isSymbolFont != 0) {
1311 /*
1312 * Symbol fonts are handled specially. For instance, Unicode 0393
1313 * (GREEK CAPITAL GAMMA) must be mapped to Symbol character 0047
1314 * (GREEK CAPITAL GAMMA), because the Symbol font doesn't have a
1315 * GREEK CAPITAL GAMMA at location 0393. If Tk interpreted the
1316 * Symbol font using the Unicode encoding, it would decide that
1317 * the Symbol font has no GREEK CAPITAL GAMMA, because the Symbol
1318 * encoding (of course) reports that character 0393 doesn't exist.
1319 *
1320 * With non-symbol Windows fonts, such as Times New Roman, if the
1321 * font has a GREEK CAPITAL GAMMA, it will be found in the correct
1322 * Unicode location (0393); the GREEK CAPITAL GAMMA will not be off
1323 * hiding at some other location.
1324 */
1325
1326 encoding = Tcl_GetEncoding(NULL, faceName);
1327 }
1328
1329 if (encoding == NULL) {
1330 encoding = Tcl_GetEncoding(NULL, "unicode");
1331 familyPtr->textOutProc =
1332 (BOOL (WINAPI *)(HDC, int, int, TCHAR *, int)) TextOutW;
1333 familyPtr->getTextExtentPoint32Proc =
1334 (BOOL (WINAPI *)(HDC, TCHAR *, int, LPSIZE)) GetTextExtentPoint32W;
1335 familyPtr->isWideFont = 1;
1336 } else {
1337 familyPtr->textOutProc =
1338 (BOOL (WINAPI *)(HDC, int, int, TCHAR *, int)) TextOutA;
1339 familyPtr->getTextExtentPoint32Proc =
1340 (BOOL (WINAPI *)(HDC, TCHAR *, int, LPSIZE)) GetTextExtentPoint32A;
1341 familyPtr->isWideFont = 0;
1342 }
1343
1344 familyPtr->encoding = encoding;
1345
1346 return familyPtr;
1347 }
1348
1349 /*
1350 *-------------------------------------------------------------------------
1351 *
1352 * FreeFontFamily --
1353 *
1354 * Called to free a FontFamily when the SubFont is finished using it.
1355 * Frees the contents of the FontFamily and the memory used by the
1356 * FontFamily itself.
1357 *
1358 * Results:
1359 * None.
1360 *
1361 * Side effects:
1362 * None.
1363 *
1364 *-------------------------------------------------------------------------
1365 */
1366
1367 static void
1368 FreeFontFamily(
1369 FontFamily *familyPtr) /* The FontFamily to delete. */
1370 {
1371 int i;
1372 FontFamily **familyPtrPtr;
1373 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1374 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1375
1376 if (familyPtr == NULL) {
1377 return;
1378 }
1379 familyPtr->refCount--;
1380 if (familyPtr->refCount > 0) {
1381 return;
1382 }
1383 for (i = 0; i < FONTMAP_PAGES; i++) {
1384 if (familyPtr->fontMap[i] != NULL) {
1385 ckfree(familyPtr->fontMap[i]);
1386 }
1387 }
1388 if (familyPtr->startCount != NULL) {
1389 ckfree((char *) familyPtr->startCount);
1390 }
1391 if (familyPtr->endCount != NULL) {
1392 ckfree((char *) familyPtr->endCount);
1393 }
1394 if (familyPtr->encoding != TkWinGetUnicodeEncoding()) {
1395 Tcl_FreeEncoding(familyPtr->encoding);
1396 }
1397
1398 /*
1399 * Delete from list.
1400 */
1401
1402 for (familyPtrPtr = &tsdPtr->fontFamilyList; ; ) {
1403 if (*familyPtrPtr == familyPtr) {
1404 *familyPtrPtr = familyPtr->nextPtr;
1405 break;
1406 }
1407 familyPtrPtr = &(*familyPtrPtr)->nextPtr;
1408 }
1409
1410 ckfree((char *) familyPtr);
1411 }
1412
1413 /*
1414 *-------------------------------------------------------------------------
1415 *
1416 * FindSubFontForChar --
1417 *
1418 * Determine which screen font is necessary to use to display the
1419 * given character. If the font object does not have a screen font
1420 * that can display the character, another screen font may be loaded
1421 * into the font object, following a set of preferred fallback rules.
1422 *
1423 * Results:
1424 * The return value is the SubFont to use to display the given
1425 * character.
1426 *
1427 * Side effects:
1428 * The contents of fontPtr are modified to cache the results
1429 * of the lookup and remember any SubFonts that were dynamically
1430 * loaded.
1431 *
1432 *-------------------------------------------------------------------------
1433 */
1434
1435 static SubFont *
1436 FindSubFontForChar(
1437 WinFont *fontPtr, /* The font object with which the character
1438 * will be displayed. */
1439 int ch) /* The Unicode character to be displayed. */
1440 {
1441 HDC hdc;
1442 int i, j, k;
1443 CanUse canUse;
1444 char **aliases, **anyFallbacks;
1445 char ***fontFallbacks;
1446 char *fallbackName;
1447 SubFont *subFontPtr;
1448 Tcl_DString ds;
1449
1450 if (ch < BASE_CHARS) {
1451 return &fontPtr->subFontArray[0];
1452 }
1453
1454 for (i = 0; i < fontPtr->numSubFonts; i++) {
1455 if (FontMapLookup(&fontPtr->subFontArray[i], ch)) {
1456 return &fontPtr->subFontArray[i];
1457 }
1458 }
1459
1460 /*
1461 * Keep track of all face names that we check, so we don't check some
1462 * name multiple times if it can be reached by multiple paths.
1463 */
1464
1465 Tcl_DStringInit(&ds);
1466 hdc = GetDC(fontPtr->hwnd);
1467
1468 aliases = TkFontGetAliasList(fontPtr->font.fa.family);
1469
1470 fontFallbacks = TkFontGetFallbacks();
1471 for (i = 0; fontFallbacks[i] != NULL; i++) {
1472 for (j = 0; fontFallbacks[i][j] != NULL; j++) {
1473 fallbackName = fontFallbacks[i][j];
1474 if (strcasecmp(fallbackName, fontPtr->font.fa.family) == 0) {
1475 /*
1476 * If the base font has a fallback...
1477 */
1478
1479 goto tryfallbacks;
1480 } else if (aliases != NULL) {
1481 /*
1482 * Or if an alias for the base font has a fallback...
1483 */
1484
1485 for (k = 0; aliases[k] != NULL; k++) {
1486 if (strcasecmp(aliases[k], fallbackName) == 0) {
1487 goto tryfallbacks;
1488 }
1489 }
1490 }
1491 }
1492 continue;
1493
1494 /*
1495 * ...then see if we can use one of the fallbacks, or an
1496 * alias for one of the fallbacks.
1497 */
1498
1499 tryfallbacks:
1500 for (j = 0; fontFallbacks[i][j] != NULL; j++) {
1501 fallbackName = fontFallbacks[i][j];
1502 subFontPtr = CanUseFallbackWithAliases(hdc, fontPtr, fallbackName,
1503 ch, &ds);
1504 if (subFontPtr != NULL) {
1505 goto end;
1506 }
1507 }
1508 }
1509
1510 /*
1511 * See if we can use something from the global fallback list.
1512 */
1513
1514 anyFallbacks = TkFontGetGlobalClass();
1515 for (i = 0; anyFallbacks[i] != NULL; i++) {
1516 fallbackName = anyFallbacks[i];
1517 subFontPtr = CanUseFallbackWithAliases(hdc, fontPtr, fallbackName,
1518 ch, &ds);
1519 if (subFontPtr != NULL) {
1520 goto end;
1521 }
1522 }
1523
1524 /*
1525 * Try all face names available in the whole system until we
1526 * find one that can be used.
1527 */
1528
1529 canUse.hdc = hdc;
1530 canUse.fontPtr = fontPtr;
1531 canUse.nameTriedPtr = &ds;
1532 canUse.ch = ch;
1533 canUse.subFontPtr = NULL;
1534 if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
1535 EnumFontFamiliesW(hdc, NULL, (FONTENUMPROCW) WinFontCanUseProc,
1536 (LPARAM) &canUse);
1537 } else {
1538 EnumFontFamiliesA(hdc, NULL, (FONTENUMPROCA) WinFontCanUseProc,
1539 (LPARAM) &canUse);
1540 }
1541 subFontPtr = canUse.subFontPtr;
1542
1543 end:
1544 Tcl_DStringFree(&ds);
1545
1546 if (subFontPtr == NULL) {
1547 /*
1548 * No font can display this character. We will use the base font
1549 * and have it display the "unknown" character.
1550 */
1551
1552 subFontPtr = &fontPtr->subFontArray[0];
1553 FontMapInsert(subFontPtr, ch);
1554 }
1555 ReleaseDC(fontPtr->hwnd, hdc);
1556 return subFontPtr;
1557 }
1558
1559 static int CALLBACK
1560 WinFontCanUseProc(
1561 ENUMLOGFONT *lfPtr, /* Logical-font data. */
1562 NEWTEXTMETRIC *tmPtr, /* Physical-font data (not used). */
1563 int fontType, /* Type of font (not used). */
1564 LPARAM lParam) /* Result object to hold result. */
1565 {
1566 int ch;
1567 HDC hdc;
1568 WinFont *fontPtr;
1569 CanUse *canUsePtr;
1570 char *fallbackName;
1571 SubFont *subFontPtr;
1572 Tcl_DString faceString;
1573 Tcl_DString *nameTriedPtr;
1574
1575 canUsePtr = (CanUse *) lParam;
1576 ch = canUsePtr->ch;
1577 hdc = canUsePtr->hdc;
1578 fontPtr = canUsePtr->fontPtr;
1579 nameTriedPtr = canUsePtr->nameTriedPtr;
1580
1581 fallbackName = lfPtr->elfLogFont.lfFaceName;
1582 Tcl_ExternalToUtfDString(systemEncoding, fallbackName, -1, &faceString);
1583 fallbackName = Tcl_DStringValue(&faceString);
1584
1585 if (SeenName(fallbackName, nameTriedPtr) == 0) {
1586 subFontPtr = CanUseFallback(hdc, fontPtr, fallbackName, ch);
1587 if (subFontPtr != NULL) {
1588 canUsePtr->subFontPtr = subFontPtr;
1589 Tcl_DStringFree(&faceString);
1590 return 0;
1591 }
1592 }
1593 Tcl_DStringFree(&faceString);
1594 return 1;
1595 }
1596
1597 /*
1598 *-------------------------------------------------------------------------
1599 *
1600 * FontMapLookup --
1601 *
1602 * See if the screen font can display the given character.
1603 *
1604 * Results:
1605 * The return value is 0 if the screen font cannot display the
1606 * character, non-zero otherwise.
1607 *
1608 * Side effects:
1609 * New pages are added to the font mapping cache whenever the
1610 * character belongs to a page that hasn't been seen before.
1611 * When a page is loaded, information about all the characters on
1612 * that page is stored, not just for the single character in
1613 * question.
1614 *
1615 *-------------------------------------------------------------------------
1616 */
1617
1618 static int
1619 FontMapLookup(
1620 SubFont *subFontPtr, /* Contains font mapping cache to be queried
1621 * and possibly updated. */
1622 int ch) /* Character to be tested. */
1623 {
1624 int row, bitOffset;
1625
1626 row = ch >> FONTMAP_SHIFT;
1627 if (subFontPtr->fontMap[row] == NULL) {
1628 FontMapLoadPage(subFontPtr, row);
1629 }
1630 bitOffset = ch & (FONTMAP_BITSPERPAGE - 1);
1631 return (subFontPtr->fontMap[row][bitOffset >> 3] >> (bitOffset & 7)) & 1;
1632 }
1633
1634 /*
1635 *-------------------------------------------------------------------------
1636 *
1637 * FontMapInsert --
1638 *
1639 * Tell the font mapping cache that the given screen font should be
1640 * used to display the specified character. This is called when no
1641 * font on the system can be be found that can display that
1642 * character; we lie to the font and tell it that it can display
1643 * the character, otherwise we would end up re-searching the entire
1644 * fallback hierarchy every time that character was seen.
1645 *
1646 * Results:
1647 * None.
1648 *
1649 * Side effects:
1650 * New pages are added to the font mapping cache whenever the
1651 * character belongs to a page that hasn't been seen before.
1652 * When a page is loaded, information about all the characters on
1653 * that page is stored, not just for the single character in
1654 * question.
1655 *
1656 *-------------------------------------------------------------------------
1657 */
1658
1659 static void
1660 FontMapInsert(
1661 SubFont *subFontPtr, /* Contains font mapping cache to be
1662 * updated. */
1663 int ch) /* Character to be added to cache. */
1664 {
1665 int row, bitOffset;
1666
1667 row = ch >> FONTMAP_SHIFT;
1668 if (subFontPtr->fontMap[row] == NULL) {
1669 FontMapLoadPage(subFontPtr, row);
1670 }
1671 bitOffset = ch & (FONTMAP_BITSPERPAGE - 1);
1672 subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7);
1673 }
1674
1675 /*
1676 *-------------------------------------------------------------------------
1677 *
1678 * FontMapLoadPage --
1679 *
1680 * Load information about all the characters on a given page.
1681 * This information consists of one bit per character that indicates
1682 * whether the associated HFONT can (1) or cannot (0) display the
1683 * characters on the page.
1684 *
1685 * Results:
1686 * None.
1687 *
1688 * Side effects:
1689 * Mempry allocated.
1690 *
1691 *-------------------------------------------------------------------------
1692 */
1693 static void
1694 FontMapLoadPage(
1695 SubFont *subFontPtr, /* Contains font mapping cache to be
1696 * updated. */
1697 int row) /* Index of the page to be loaded into
1698 * the cache. */
1699 {
1700 FontFamily *familyPtr;
1701 Tcl_Encoding encoding;
1702 char src[TCL_UTF_MAX], buf[16];
1703 USHORT *startCount, *endCount;
1704 int i, j, bitOffset, end, segCount;
1705
1706 subFontPtr->fontMap[row] = (char *) ckalloc(FONTMAP_BITSPERPAGE / 8);
1707 memset(subFontPtr->fontMap[row], 0, FONTMAP_BITSPERPAGE / 8);
1708
1709 familyPtr = subFontPtr->familyPtr;
1710 encoding = familyPtr->encoding;
1711
1712 if (familyPtr->encoding == TkWinGetUnicodeEncoding()) {
1713 /*
1714 * Font is Unicode. Few fonts are going to have all characters, so
1715 * examine the TrueType character existence metrics to determine
1716 * what characters actually exist in this font.
1717 */
1718
1719 segCount = familyPtr->segCount;
1720 startCount = familyPtr->startCount;
1721 endCount = familyPtr->endCount;
1722
1723 j = 0;
1724 end = (row + 1) << FONTMAP_SHIFT;
1725 for (i = row << FONTMAP_SHIFT; i < end; i++) {
1726 for ( ; j < segCount; j++) {
1727 if (endCount[j] >= i) {
1728 if (startCount[j] <= i) {
1729 bitOffset = i & (FONTMAP_BITSPERPAGE - 1);
1730 subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7);
1731 }
1732 break;
1733 }
1734 }
1735 }
1736 } else if (familyPtr->isSymbolFont) {
1737 /*
1738 * Assume that a symbol font with a known encoding has all the
1739 * characters that its encoding claims it supports.
1740 *
1741 * The test for "encoding == unicodeEncoding"
1742 * must occur before this case, to catch all symbol fonts (such
1743 * as {Comic Sans MS} or Wingdings) for which we don't have
1744 * encoding information; those symbol fonts are treated as if
1745 * they were in the Unicode encoding and their symbolic
1746 * character existence metrics are treated as if they were Unicode
1747 * character existence metrics. This way, although we don't know
1748 * the proper Unicode -> symbol font mapping, we can install the
1749 * symbol font as the base font and access its glyphs.
1750 */
1751
1752 end = (row + 1) << FONTMAP_SHIFT;
1753 for (i = row << FONTMAP_SHIFT; i < end; i++) {
1754 if (Tcl_UtfToExternal(NULL, encoding, src,
1755 Tcl_UniCharToUtf(i, src), TCL_ENCODING_STOPONERROR, NULL,
1756 buf, sizeof(buf), NULL, NULL, NULL) != TCL_OK) {
1757 continue;
1758 }
1759 bitOffset = i & (FONTMAP_BITSPERPAGE - 1);
1760 subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7);
1761 }
1762 }
1763 }
1764
1765 /*
1766 *---------------------------------------------------------------------------
1767 *
1768 * CanUseFallbackWithAliases --
1769 *
1770 * Helper function for FindSubFontForChar. Determine if the
1771 * specified face name (or an alias of the specified face name)
1772 * can be used to construct a screen font that can display the
1773 * given character.
1774 *
1775 * Results:
1776 * See CanUseFallback().
1777 *
1778 * Side effects:
1779 * If the name and/or one of its aliases was rejected, the
1780 * rejected string is recorded in nameTriedPtr so that it won't
1781 * be tried again.
1782 *
1783 *---------------------------------------------------------------------------
1784 */
1785
1786 static SubFont *
1787 CanUseFallbackWithAliases(
1788 HDC hdc, /* HDC in which font can be selected. */
1789 WinFont *fontPtr, /* The font object that will own the new
1790 * screen font. */
1791 char *faceName, /* Desired face name for new screen font. */
1792 int ch, /* The Unicode character that the new
1793 * screen font must be able to display. */
1794 Tcl_DString *nameTriedPtr) /* Records face names that have already
1795 * been tried. It is possible for the same
1796 * face name to be queried multiple times when
1797 * trying to find a suitable screen font. */
1798 {
1799 int i;
1800 char **aliases;
1801 SubFont *subFontPtr;
1802
1803 if (SeenName(faceName, nameTriedPtr) == 0) {
1804 subFontPtr = CanUseFallback(hdc, fontPtr, faceName, ch);
1805 if (subFontPtr != NULL) {
1806 return subFontPtr;
1807 }
1808 }
1809 aliases = TkFontGetAliasList(faceName);
1810 if (aliases != NULL) {
1811 for (i = 0; aliases[i] != NULL; i++) {
1812 if (SeenName(aliases[i], nameTriedPtr) == 0) {
1813 subFontPtr = CanUseFallback(hdc, fontPtr, aliases[i], ch);
1814 if (subFontPtr != NULL) {
1815 return subFontPtr;
1816 }
1817 }
1818 }
1819 }
1820 return NULL;
1821 }
1822
1823 /*
1824 *---------------------------------------------------------------------------
1825 *
1826 * SeenName --
1827 *
1828 * Used to determine we have already tried and rejected the given
1829 * face name when looking for a screen font that can support some
1830 * Unicode character.
1831 *
1832 * Results:
1833 * The return value is 0 if this face name has not already been seen,
1834 * non-zero otherwise.
1835 *
1836 * Side effects:
1837 * None.
1838 *
1839 *---------------------------------------------------------------------------
1840 */
1841
1842 static int
1843 SeenName(
1844 CONST char *name, /* The name to check. */
1845 Tcl_DString *dsPtr) /* Contains names that have already been
1846 * seen. */
1847 {
1848 CONST char *seen, *end;
1849
1850 seen = Tcl_DStringValue(dsPtr);
1851 end = seen + Tcl_DStringLength(dsPtr);
1852 while (seen < end) {
1853 if (strcasecmp(seen, name) == 0) {
1854 return 1;
1855 }
1856 seen += strlen(seen) + 1;
1857 }
1858 Tcl_DStringAppend(dsPtr, (char *) name, (int) (strlen(name) + 1));
1859 return 0;
1860 }
1861
1862 /*
1863 *-------------------------------------------------------------------------
1864 *
1865 * CanUseFallback --
1866 *
1867 * If the specified screen font has not already been loaded into
1868 * the font object, determine if it can display the given character.
1869 *
1870 * Results:
1871 * The return value is a pointer to a newly allocated SubFont, owned
1872 * by the font object. This SubFont can be used to display the given
1873 * character. The SubFont represents the screen font with the base set
1874 * of font attributes from the font object, but using the specified
1875 * font name. NULL is returned if the font object already holds
1876 * a reference to the specified physical font or if the specified
1877 * physical font cannot display the given character.
1878 *
1879 * Side effects:
1880 * The font object's subFontArray is updated to contain a reference
1881 * to the newly allocated SubFont.
1882 *
1883 *-------------------------------------------------------------------------
1884 */
1885
1886 static SubFont *
1887 CanUseFallback(
1888 HDC hdc, /* HDC in which font can be selected. */
1889 WinFont *fontPtr, /* The font object that will own the new
1890 * screen font. */
1891 char *faceName, /* Desired face name for new screen font. */
1892 int ch) /* The Unicode character that the new
1893 * screen font must be able to display. */
1894 {
1895 int i;
1896 HFONT hFont;
1897 SubFont subFont;
1898
1899 if (FamilyExists(hdc, faceName) == 0) {
1900 return NULL;
1901 }
1902
1903 /*
1904 * Skip all fonts we've already used.
1905 */
1906
1907 for (i = 0; i < fontPtr->numSubFonts; i++) {
1908 if (faceName == fontPtr->subFontArray[i].familyPtr->faceName) {
1909 return NULL;
1910 }
1911 }
1912
1913 /*
1914 * Load this font and see if it has the desired character.
1915 */
1916
1917 hFont = GetScreenFont(&fontPtr->font.fa, faceName, fontPtr->pixelSize);
1918 InitSubFont(hdc, hFont, 0, &subFont);
1919 if (((ch < 256) && (subFont.familyPtr->isSymbolFont))
1920 || (FontMapLookup(&subFont, ch) == 0)) {
1921 /*
1922 * Don't use a symbol font as a fallback font for characters below
1923 * 256.
1924 */
1925
1926 ReleaseSubFont(&subFont);
1927 return NULL;
1928 }
1929
1930 if (fontPtr->numSubFonts >= SUBFONT_SPACE) {
1931 SubFont *newPtr;
1932
1933 newPtr = (SubFont *) ckalloc(sizeof(SubFont)
1934 * (fontPtr->numSubFonts + 1));
1935 memcpy((char *) newPtr, fontPtr->subFontArray,
1936 fontPtr->numSubFonts * sizeof(SubFont));
1937 if (fontPtr->subFontArray != fontPtr->staticSubFonts) {
1938 ckfree((char *) fontPtr->subFontArray);
1939 }
1940 fontPtr->subFontArray = newPtr;
1941 }
1942 fontPtr->subFontArray[fontPtr->numSubFonts] = subFont;
1943 fontPtr->numSubFonts++;
1944 return &fontPtr->subFontArray[fontPtr->numSubFonts - 1];
1945 }
1946
1947 /*
1948 *---------------------------------------------------------------------------
1949 *
1950 * GetScreenFont --
1951 *
1952 * Given the name and other attributes, construct an HFONT.
1953 * This is where all the alias and fallback substitution bottoms
1954 * out.
1955 *
1956 * Results:
1957 * The screen font that corresponds to the attributes.
1958 *
1959 * Side effects:
1960 * None.
1961 *
1962 *---------------------------------------------------------------------------
1963 */
1964
1965 static HFONT
1966 GetScreenFont(
1967 CONST TkFontAttributes *faPtr,
1968 /* Desired font attributes for new HFONT. */
1969 CONST char *faceName, /* Overrides font family specified in font
1970 * attributes. */
1971 int pixelSize) /* Overrides size specified in font
1972 * attributes. */
1973 {
1974 Tcl_DString ds;
1975 HFONT hFont;
1976 LOGFONTW lf;
1977
1978 memset(&lf, 0, sizeof(lf));
1979 lf.lfHeight = -pixelSize;
1980 lf.lfWidth = 0;
1981 lf.lfEscapement = 0;
1982 lf.lfOrientation = 0;
1983 lf.lfWeight = (faPtr->weight == TK_FW_NORMAL) ? FW_NORMAL : FW_BOLD;
1984 lf.lfItalic = faPtr->slant;
1985 lf.lfUnderline = faPtr->underline;
1986 lf.lfStrikeOut = faPtr->overstrike;
1987 lf.lfCharSet = DEFAULT_CHARSET;
1988 lf.lfOutPrecision = OUT_TT_PRECIS;
1989 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1990 lf.lfQuality = DEFAULT_QUALITY;
1991 lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
1992
1993 Tcl_UtfToExternalDString(systemEncoding, faceName, -1, &ds);
1994
1995 if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
1996 Tcl_UniChar *src, *dst;
1997
1998 /*
1999 * We can only store up to LF_FACESIZE wide characters
2000 */
2001 if (Tcl_DStringLength(&ds) >= (LF_FACESIZE * sizeof(WCHAR))) {
2002 Tcl_DStringSetLength(&ds, LF_FACESIZE);
2003 }
2004 src = (Tcl_UniChar *) Tcl_DStringValue(&ds);
2005 dst = (Tcl_UniChar *) lf.lfFaceName;
2006 while (*src != '\0') {
2007 *dst++ = *src++;
2008 }
2009 *dst = '\0';
2010 hFont = CreateFontIndirectW(&lf);
2011 } else {
2012 /*
2013 * We can only store up to LF_FACESIZE characters
2014 */
2015 if (Tcl_DStringLength(&ds) >= LF_FACESIZE) {
2016 Tcl_DStringSetLength(&ds, LF_FACESIZE);
2017 }
2018 strcpy((char *) lf.lfFaceName, Tcl_DStringValue(&ds));
2019 hFont = CreateFontIndirectA((LOGFONTA *) &lf);
2020 }
2021 Tcl_DStringFree(&ds);
2022 return hFont;
2023 }
2024
2025 /*
2026 *-------------------------------------------------------------------------
2027 *
2028 * FamilyExists, FamilyOrAliasExists, WinFontExistsProc --
2029 *
2030 * Determines if any physical screen font exists on the system with
2031 * the given family name. If the family exists, then it should be
2032 * possible to construct some physical screen font with that family
2033 * name.
2034 *
2035 * Results:
2036 * The return value is 0 if the specified font family does not exist,
2037 * non-zero otherwise.
2038 *
2039 * Side effects:
2040 * None.
2041 *
2042 *-------------------------------------------------------------------------
2043 */
2044
2045 static int
2046 FamilyExists(
2047 HDC hdc, /* HDC in which font family will be used. */
2048 CONST char *faceName) /* Font family to query. */
2049 {
2050 int result;
2051 Tcl_DString faceString;
2052
2053 /*
2054 * Just immediately rule out the following fonts, because they look so
2055 * ugly on windows. The caller's fallback mechanism will cause the
2056 * corresponding appropriate TrueType fonts to be selected.
2057 */
2058
2059 if (strcasecmp(faceName, "Courier") == 0) {
2060 return 0;
2061 }
2062 if (strcasecmp(faceName, "Times") == 0) {
2063 return 0;
2064 }
2065 if (strcasecmp(faceName, "Helvetica") == 0) {
2066 return 0;
2067 }
2068
2069 Tcl_UtfToExternalDString(systemEncoding, faceName, -1, &faceString);
2070
2071 /*
2072 * If the family exists, WinFontExistProc() will be called and
2073 * EnumFontFamilies() will return whatever WinFontExistProc() returns.
2074 * If the family doesn't exist, EnumFontFamilies() will just return a
2075 * non-zero value.
2076 */
2077
2078 if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) {
2079 result = EnumFontFamiliesW(hdc, (WCHAR *) Tcl_DStringValue(&faceString),
2080 (FONTENUMPROCW) WinFontExistProc, 0);
2081 } else {
2082 result = EnumFontFamiliesA(hdc, (char *) Tcl_DStringValue(&faceString),
2083 (FONTENUMPROCA) WinFontExistProc, 0);
2084 }
2085 Tcl_DStringFree(&faceString);
2086 return (result == 0);
2087 }
2088
2089 static char *
2090 FamilyOrAliasExists(
2091 HDC hdc,
2092 CONST char *faceName)
2093 {
2094 char **aliases;
2095 int i;
2096
2097 if (FamilyExists(hdc, faceName) != 0) {
2098 return (char *) faceName;
2099 }
2100 aliases = TkFontGetAliasList(faceName);
2101 if (aliases != NULL) {
2102 for (i = 0; aliases[i] != NULL; i++) {
2103 if (FamilyExists(hdc, aliases[i]) != 0) {
2104 return aliases[i];
2105 }
2106 }
2107 }
2108 return NULL;
2109 }
2110
2111 static int CALLBACK
2112 WinFontExistProc(
2113 ENUMLOGFONT *lfPtr, /* Logical-font data. */
2114 NEWTEXTMETRIC *tmPtr, /* Physical-font data (not used). */
2115 int fontType, /* Type of font (not used). */
2116 LPARAM lParam) /* EnumFontData to hold result. */
2117 {
2118 return 0;
2119 }
2120
2121 /*
2122 * The following data structures are used when querying a TrueType font file
2123 * to determine which characters the font supports.
2124 */
2125
2126 #pragma pack(1) /* Structures are byte aligned in file. */
2127
2128 #define CMAPHEX 0x636d6170 /* Key for character map resource. */
2129
2130 typedef struct CMAPTABLE {
2131 USHORT version; /* Table version number (0). */
2132 USHORT numTables; /* Number of encoding tables following. */
2133 } CMAPTABLE;
2134
2135 typedef struct ENCODINGTABLE {
2136 USHORT platform; /* Platform for which data is targeted.
2137 * 3 means data is for Windows. */
2138 USHORT encoding; /* How characters in font are encoded.
2139 * 1 means that the following subtable is
2140 * keyed based on Unicode. */
2141 ULONG offset; /* Byte offset from beginning of CMAPTABLE
2142 * to the subtable for this encoding. */
2143 } ENCODINGTABLE;
2144
2145 typedef struct ANYTABLE {
2146 USHORT format; /* Format number. */
2147 USHORT length; /* The actual length in bytes of this
2148 * subtable. */
2149 USHORT version; /* Version number (starts at 0). */
2150 } ANYTABLE;
2151
2152 typedef struct BYTETABLE {
2153 USHORT format; /* Format number is set to 0. */
2154 USHORT length; /* The actual length in bytes of this
2155 * subtable. */
2156 USHORT version; /* Version number (starts at 0). */
2157 BYTE glyphIdArray[256]; /* Array that maps up to 256 single-byte char
2158 * codes to glyph indices. */
2159 } BYTETABLE;
2160
2161 typedef struct SUBHEADER {
2162 USHORT firstCode; /* First valid low byte for subHeader. */
2163 USHORT entryCount; /* Number valid low bytes for subHeader. */
2164 SHORT idDelta; /* Constant adder to get base glyph index. */
2165 USHORT idRangeOffset; /* Byte offset from here to appropriate
2166 * glyphIndexArray. */
2167 } SUBHEADER;
2168
2169 typedef struct HIBYTETABLE {
2170 USHORT format; /* Format number is set to 2. */
2171 USHORT length; /* The actual length in bytes of this
2172 * subtable. */
2173 USHORT version; /* Version number (starts at 0). */
2174 USHORT subHeaderKeys[256]; /* Maps high bytes to subHeaders: value is
2175 * subHeader index * 8. */
2176 #if 0
2177 SUBHEADER subHeaders[]; /* Variable-length array of SUBHEADERs. */
2178 USHORT glyphIndexArray[]; /* Variable-length array containing subarrays
2179 * used for mapping the low byte of 2-byte
2180 * characters. */
2181 #endif
2182 } HIBYTETABLE;
2183
2184 typedef struct SEGMENTTABLE {
2185 USHORT format; /* Format number is set to 4. */
2186 USHORT length; /* The actual length in bytes of this
2187 * subtable. */
2188 USHORT version; /* Version number (starts at 0). */
2189 USHORT segCountX2; /* 2 x segCount. */
2190 USHORT searchRange; /* 2 x (2**floor(log2(segCount))). */
2191 USHORT entrySelector; /* log2(searchRange/2). */
2192 USHORT rangeShift; /* 2 x segCount - searchRange. */
2193 #if 0
2194 USHORT endCount[segCount] /* End characterCode for each segment. */
2195 USHORT reservedPad; /* Set to 0. */
2196 USHORT startCount[segCount];/* Start character code for each segment. */
2197 USHORT idDelta[segCount]; /* Delta for all character in segment. */
2198 USHORT idRangeOffset[segCount]; /* Offsets into glyphIdArray or 0. */
2199 USHORT glyphIdArray[] /* Glyph index array. */
2200 #endif
2201 } SEGMENTTABLE;
2202
2203 typedef struct TRIMMEDTABLE {
2204 USHORT format; /* Format number is set to 6. */
2205 USHORT length; /* The actual length in bytes of this
2206 * subtable. */
2207 USHORT version; /* Version number (starts at 0). */
2208 USHORT firstCode; /* First character code of subrange. */
2209 USHORT entryCount; /* Number of character codes in subrange. */
2210 #if 0
2211 USHORT glyphIdArray[]; /* Array of glyph index values for
2212 character codes in the range. */
2213 #endif
2214 } TRIMMEDTABLE;
2215
2216 typedef union SUBTABLE {
2217 ANYTABLE any;
2218 BYTETABLE byte;
2219 HIBYTETABLE hiByte;
2220 SEGMENTTABLE segment;
2221 TRIMMEDTABLE trimmed;
2222 } SUBTABLE;
2223
2224 #pragma pack()
2225
2226 /*
2227 *-------------------------------------------------------------------------
2228 *
2229 * LoadFontRanges --
2230 *
2231 * Given an HFONT, get the information about the characters that
2232 * this font can display.
2233 *
2234 * Results:
2235 * If the font has no Unicode character information, the return value
2236 * is 0 and *startCountPtr and *endCountPtr are filled with NULL.
2237 * Otherwise, *startCountPtr and *endCountPtr are set to pointers to
2238 * arrays of TrueType character existence information and the return
2239 * value is the length of the arrays (the two arrays are always the
2240 * same length as each other).
2241 *
2242 * Side effects:
2243 * None.
2244 *
2245 *-------------------------------------------------------------------------
2246 */
2247
2248 static int
2249 LoadFontRanges(
2250 HDC hdc, /* HDC into which font can be selected. */
2251 HFONT hFont, /* HFONT to query. */
2252 USHORT **startCountPtr, /* Filled with malloced pointer to
2253 * character range information. */
2254 USHORT **endCountPtr, /* Filled with malloced pointer to
2255 * character range information. */
2256 int *symbolPtr)
2257 {
2258 int n, i, swapped, offset, cbData, segCount;
2259 DWORD cmapKey;
2260 USHORT *startCount, *endCount;
2261 CMAPTABLE cmapTable;
2262 ENCODINGTABLE encTable;
2263 SUBTABLE subTable;
2264 char *s;
2265
2266 segCount = 0;
2267 startCount = NULL;
2268 endCount = NULL;
2269 *symbolPtr = 0;
2270
2271 hFont = SelectObject(hdc, hFont);
2272
2273 i = 0;
2274 s = (char *) &i;
2275 *s = '\1';
2276 swapped = 0;
2277
2278 if (i == 1) {
2279 swapped = 1;
2280 }
2281
2282 cmapKey = CMAPHEX;
2283 if (swapped) {
2284 SwapLong(&cmapKey);
2285 }
2286
2287 n = GetFontData(hdc, cmapKey, 0, &cmapTable, sizeof(cmapTable));
2288 if (n != GDI_ERROR) {
2289 if (swapped) {
2290 SwapShort(&cmapTable.numTables);
2291 }
2292 for (i = 0; i < cmapTable.numTables; i++) {
2293 offset = sizeof(cmapTable) + i * sizeof(encTable);
2294 GetFontData(hdc, cmapKey, offset, &encTable, sizeof(encTable));
2295 if (swapped) {
2296 SwapShort(&encTable.platform);
2297 SwapShort(&encTable.encoding);
2298 SwapLong(&encTable.offset);
2299 }
2300 if (encTable.platform != 3) {
2301 /*
2302 * Not Microsoft encoding.
2303 */
2304
2305 continue;
2306 }
2307 if (encTable.encoding == 0) {
2308 *symbolPtr = 1;
2309 } else if (encTable.encoding != 1) {
2310 continue;
2311 }
2312
2313 GetFontData(hdc, cmapKey, encTable.offset, &subTable,
2314 sizeof(subTable));
2315 if (swapped) {
2316 SwapShort(&subTable.any.format);
2317 }
2318 if (subTable.any.format == 4) {
2319 if (swapped) {
2320 SwapShort(&subTable.segment.segCountX2);
2321 }
2322 segCount = subTable.segment.segCountX2 / 2;
2323 cbData = segCount * sizeof(USHORT);
2324
2325 startCount = (USHORT *) ckalloc(cbData);
2326 endCount = (USHORT *) ckalloc(cbData);
2327
2328 offset = encTable.offset + sizeof(subTable.segment);
2329 GetFontData(hdc, cmapKey, offset, endCount, cbData);
2330 offset += cbData + sizeof(USHORT);
2331 GetFontData(hdc, cmapKey, offset, startCount, cbData);
2332 if (swapped) {
2333 for (i = 0; i < segCount; i++) {
2334 SwapShort(&endCount[i]);
2335 SwapShort(&startCount[i]);
2336 }
2337 }
2338 if (*symbolPtr != 0) {
2339 /*
2340 * Empirically determined: When a symbol font is
2341 * loaded, the character existence metrics obtained
2342 * from the system are mildly wrong. If the real range
2343 * of the symbol font is from 0020 to 00FE, then the
2344 * metrics are reported as F020 to F0FE. When we load
2345 * a symbol font, we must fix the character existence
2346 * metrics.
2347 *
2348 * Symbol fonts should only use the symbol encoding
2349 * for 8-bit characters [note Bug: 2406]
2350 */
2351
2352 for (i = 0; i < segCount; i++) {
2353 if (((startCount[i] & 0xff00) == 0xf000)
2354 && ((endCount[i] & 0xff00) == 0xf000)) {
2355 startCount[i] &= 0xff;
2356 endCount[i] &= 0xff;
2357 }
2358 }
2359 }
2360 }
2361 }
2362 } else if (GetTextCharset(hdc) == ANSI_CHARSET) {
2363 /*
2364 * Bitmap font. We should also support ranges for the other
2365 * *_CHARSET values.
2366 */
2367 segCount = 1;
2368 cbData = segCount * sizeof(USHORT);
2369 startCount = (USHORT *) ckalloc(cbData);
2370 endCount = (USHORT *) ckalloc(cbData);
2371 startCount[0] = 0x0000;
2372 endCount[0] = 0x00ff;
2373 }
2374 SelectObject(hdc, hFont);
2375
2376 *startCountPtr = startCount;
2377 *endCountPtr = endCount;
2378 return segCount;
2379 }
2380
2381 /*
2382 *-------------------------------------------------------------------------
2383 *
2384 * SwapShort, SwapLong --
2385 *
2386 * Helper functions to convert the data loaded from TrueType font
2387 * files to Intel byte ordering.
2388 *
2389 * Results:
2390 * Bytes of input value are swapped and stored back in argument.
2391 *
2392 * Side effects:
2393 * None.
2394 *
2395 *-------------------------------------------------------------------------
2396 */
2397
2398 static void
2399 SwapShort(PUSHORT p)
2400 {
2401 *p = (SHORT)(HIBYTE(*p) + (LOBYTE(*p) << 8));
2402 }
2403
2404 static void
2405 SwapLong(PULONG p)
2406 {
2407 ULONG temp;
2408
2409 temp = (LONG) ((BYTE) *p);
2410 temp <<= 8;
2411 *p >>=8;
2412
2413 temp += (LONG) ((BYTE) *p);
2414 temp <<= 8;
2415 *p >>=8;
2416
2417 temp += (LONG) ((BYTE) *p);
2418 temp <<= 8;
2419 *p >>=8;
2420
2421 temp += (LONG) ((BYTE) *p);
2422 *p = temp;
2423 }