Use hard-coded font name bindings only with the ANSI_CHARSET (non-US
[wine/multimedia.git] / graphics / x11drv / xfont.c
blobab81a5e221059d0937c5a21c0ff1e48030c5c631
1 /*
2 * X11 physical font objects
4 * Copyright 1997 Alex Korobka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * TODO: Mapping algorithm tweaks, FO_SYNTH_... flags (ExtTextOut() will
21 * have to be changed for that), dynamic font loading (FreeType).
24 #include "config.h"
26 #include <X11/Xatom.h>
28 #include "ts_xlib.h"
30 #include <ctype.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <sys/types.h>
36 #include <fcntl.h>
37 #include <math.h>
39 #include "windef.h"
40 #include "wingdi.h"
41 #include "winnls.h"
42 #include "winreg.h"
43 #include "font.h"
44 #include "wine/debug.h"
45 #include "user.h" /* for TWEAK_WineLook (FIXME) */
46 #include "x11font.h"
47 #include "wine/server.h"
48 #include "wine/unicode.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(font);
52 #define X_PFONT_MAGIC (0xFADE0000)
53 #define X_FMC_MAGIC (0x0000CAFE)
55 #define MAX_FONTS 1024*16
56 #define MAX_LFD_LENGTH 256
57 #define TILDE '~'
58 #define HYPHEN '-'
60 #define DEF_POINT_SIZE 8 /* CreateFont(0 .. ) gets this */
61 #define DEF_SCALABLE_HEIGHT 100 /* pixels */
62 #define MIN_FONT_SIZE 2 /* Min size in pixels */
63 #define MAX_FONT_SIZE 1000 /* Max size in pixels */
65 #define REMOVE_SUBSETS 1
66 #define UNMARK_SUBSETS 0
69 #define FF_FAMILY (FF_MODERN | FF_SWISS | FF_ROMAN | FF_DECORATIVE | FF_SCRIPT)
71 typedef struct __fontAlias
73 LPSTR faTypeFace;
74 LPSTR faAlias;
75 struct __fontAlias* next;
76 } fontAlias;
78 static fontAlias *aliasTable = NULL;
80 static const char* INIFontMetrics = "cachedmetrics.";
81 static const char* INIFontSection = "Software\\Wine\\Wine\\Config\\fonts";
82 static const char* INIAliasSection = "Alias";
83 static const char* INIIgnoreSection = "Ignore";
84 static const char* INIDefault = "Default";
85 static const char* INIDefaultFixed = "DefaultFixed";
86 static const char* INIResolution = "Resolution";
87 static const char* INIGlobalMetrics = "FontMetrics";
88 static const char* INIDefaultSerif = "DefaultSerif";
89 static const char* INIDefaultSansSerif = "DefaultSansSerif";
92 /* FIXME - are there any more Latin charsets ? */
93 /* FIXME - RUSSIAN, ARABIC, GREEK, HEBREW are NOT Latin */
94 #define IS_LATIN_CHARSET(ch) \
95 ((ch)==ANSI_CHARSET ||\
96 (ch)==EE_CHARSET ||\
97 (ch)==ISO3_CHARSET ||\
98 (ch)==ISO4_CHARSET ||\
99 (ch)==RUSSIAN_CHARSET ||\
100 (ch)==ARABIC_CHARSET ||\
101 (ch)==GREEK_CHARSET ||\
102 (ch)==HEBREW_CHARSET ||\
103 (ch)==TURKISH_CHARSET ||\
104 (ch)==ISO10_CHARSET ||\
105 (ch)==BALTIC_CHARSET ||\
106 (ch)==CELTIC_CHARSET)
108 /* suffix-charset mapping tables - must be less than 254 entries long */
110 typedef struct __sufch
112 LPCSTR psuffix;
113 WORD charset; /* hibyte != 0 means *internal* charset */
114 WORD codepage;
115 WORD cptable;
116 } SuffixCharset;
118 static const SuffixCharset sufch_ansi[] = {
119 { "0", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
120 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
122 static const SuffixCharset sufch_iso646[] = {
123 { "irv", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
124 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
126 static const SuffixCharset sufch_iso8859[] = {
127 { "1", ANSI_CHARSET, 28591, X11DRV_CPTABLE_SBCS },
128 { "2", EE_CHARSET, 28592, X11DRV_CPTABLE_SBCS },
129 { "3", ISO3_CHARSET, 28593, X11DRV_CPTABLE_SBCS },
130 { "4", ISO4_CHARSET, 28594, X11DRV_CPTABLE_SBCS },
131 { "5", RUSSIAN_CHARSET, 28595, X11DRV_CPTABLE_SBCS },
132 { "6", ARABIC_CHARSET, 28596, X11DRV_CPTABLE_SBCS },
133 { "7", GREEK_CHARSET, 28597, X11DRV_CPTABLE_SBCS },
134 { "8", HEBREW_CHARSET, 28598, X11DRV_CPTABLE_SBCS },
135 { "9", TURKISH_CHARSET, 28599, X11DRV_CPTABLE_SBCS },
136 { "10", ISO10_CHARSET, 28600, X11DRV_CPTABLE_SBCS },
137 { "11", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
138 { "12", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
139 { "13", BALTIC_CHARSET, 28603, X11DRV_CPTABLE_SBCS },
140 { "14", CELTIC_CHARSET, 28604, X11DRV_CPTABLE_SBCS },
141 { "15", ANSI_CHARSET, 28605, X11DRV_CPTABLE_SBCS },
142 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
144 static const SuffixCharset sufch_microsoft[] = {
145 { "cp1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
146 { "cp1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
147 { "cp1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
148 { "cp1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
149 { "cp1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
150 { "cp1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
151 { "cp1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
152 { "cp1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
153 { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SYMBOL },
154 { "symbol", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SYMBOL },
155 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
157 static const SuffixCharset sufch_tcvn[] = {
158 { "0", TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
159 { NULL, TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
161 static const SuffixCharset sufch_tis620[] = {
162 { "0", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
163 { NULL, THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }};
165 static const SuffixCharset sufch_viscii[] = {
166 { "1", VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
167 { NULL, VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
169 static const SuffixCharset sufch_windows[] = {
170 { "1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
171 { "1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
172 { "1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
173 { "1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
174 { "1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
175 { "1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
176 { "1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
177 { "1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
178 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
180 static const SuffixCharset sufch_koi8[] = {
181 { "r", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
182 { "ru", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
183 { "u", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
184 { NULL, RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS }};
186 static const SuffixCharset sufch_jisx0201[] = {
187 { "0", X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS },
188 { NULL, X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS }};
190 static const SuffixCharset sufch_jisx0208[] = {
191 { "0", SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 },
192 { NULL, SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
194 static const SuffixCharset sufch_jisx0212[] = {
195 { "0", X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 },
196 { NULL, X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
198 static const SuffixCharset sufch_ksc5601[] = {
199 { "0", HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 },
200 { NULL, HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 }};
202 static const SuffixCharset sufch_gb2312[] = {
203 { "0", GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 },
204 { NULL, GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 }};
206 static const SuffixCharset sufch_big5[] = {
207 { "0", CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 },
208 { NULL, CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 }};
210 static const SuffixCharset sufch_unicode[] = {
211 { "0", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
212 { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
214 static const SuffixCharset sufch_iso10646[] = {
215 { "1", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
216 { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
218 static const SuffixCharset sufch_dec[] = {
219 { "dectech", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
220 { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
222 /* Each of these must be matched explicitly */
223 static const SuffixCharset sufch_any[] = {
224 { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
225 { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
228 typedef struct __fet
230 LPSTR prefix;
231 const SuffixCharset* sufch;
232 struct __fet* next;
233 } fontEncodingTemplate;
235 /* Note: we can attach additional encoding mappings to the end
236 * of this table at runtime.
238 static fontEncodingTemplate __fETTable[] = {
239 { "ansi", sufch_ansi, &__fETTable[1] },
240 { "ascii", sufch_ansi, &__fETTable[2] },
241 { "iso646.1991", sufch_iso646, &__fETTable[3] },
242 { "iso8859", sufch_iso8859, &__fETTable[4] },
243 { "microsoft", sufch_microsoft, &__fETTable[5] },
244 { "tcvn", sufch_tcvn, &__fETTable[6] },
245 { "tis620.2533", sufch_tis620, &__fETTable[7] },
246 { "viscii1.1", sufch_viscii, &__fETTable[8] },
247 { "windows", sufch_windows, &__fETTable[9] },
248 { "koi8", sufch_koi8, &__fETTable[10]},
249 { "jisx0201.1976",sufch_jisx0201, &__fETTable[11]},
250 { "jisc6226.1978",sufch_jisx0208, &__fETTable[12]},
251 { "jisx0208.1983",sufch_jisx0208, &__fETTable[13]},
252 { "jisx0208.1990",sufch_jisx0208, &__fETTable[14]},
253 { "jisx0212.1990",sufch_jisx0212, &__fETTable[15]},
254 { "ksc5601.1987", sufch_ksc5601, &__fETTable[16]},
255 { "gb2312.1980", sufch_gb2312, &__fETTable[17]},
256 { "big5", sufch_big5, &__fETTable[18]},
257 { "unicode", sufch_unicode, &__fETTable[19]},
258 { "iso10646", sufch_iso10646, &__fETTable[20]},
259 { "cp", sufch_windows, &__fETTable[21]},
260 { "dec", sufch_dec, &__fETTable[22]},
261 /* NULL prefix matches anything so put it last */
262 { NULL, sufch_any, NULL },
264 static fontEncodingTemplate* fETTable = __fETTable;
266 /* a charset database for known facenames */
267 struct CharsetBindingInfo
269 const char* pszFaceName;
270 BYTE charset;
272 static const struct CharsetBindingInfo charsetbindings[] =
274 /* special facenames */
275 { "System", DEFAULT_CHARSET },
276 { "FixedSys", DEFAULT_CHARSET },
278 /* known facenames */
279 { "MS Serif", ANSI_CHARSET },
280 { "MS Sans Serif", ANSI_CHARSET },
281 { "Courier", ANSI_CHARSET },
282 { "Symbol", SYMBOL_CHARSET },
284 { "Arial", ANSI_CHARSET },
285 { "Arial Greek", GREEK_CHARSET },
286 { "Arial Tur", TURKISH_CHARSET },
287 { "Arial Baltic", BALTIC_CHARSET },
288 { "Arial CE", EASTEUROPE_CHARSET },
289 { "Arial Cyr", RUSSIAN_CHARSET },
290 { "Courier New", ANSI_CHARSET },
291 { "Courier New Greek", GREEK_CHARSET },
292 { "Courier New Tur", TURKISH_CHARSET },
293 { "Courier New Baltic", BALTIC_CHARSET },
294 { "Courier New CE", EASTEUROPE_CHARSET },
295 { "Courier New Cyr", RUSSIAN_CHARSET },
296 { "Times New Roman", ANSI_CHARSET },
297 { "Times New Roman Greek", GREEK_CHARSET },
298 { "Times New Roman Tur", TURKISH_CHARSET },
299 { "Times New Roman Baltic", BALTIC_CHARSET },
300 { "Times New Roman CE", EASTEUROPE_CHARSET },
301 { "Times New Roman Cyr", RUSSIAN_CHARSET },
303 { "\x82\x6c\x82\x72 \x83\x53\x83\x56\x83\x62\x83\x4e",
304 SHIFTJIS_CHARSET }, /* MS gothic */
305 { "\x82\x6c\x82\x72 \x82\x6f\x83\x53\x83\x56\x83\x62\x83\x4e",
306 SHIFTJIS_CHARSET }, /* MS P gothic */
307 { "\x82\x6c\x82\x72 \x96\xbe\x92\xa9",
308 SHIFTJIS_CHARSET }, /* MS mincho */
309 { "\x82\x6c\x82\x72 \x82\x6f\x96\xbe\x92\xa9",
310 SHIFTJIS_CHARSET }, /* MS P mincho */
311 { "GulimChe", HANGEUL_CHARSET },
312 { "MS Song", GB2312_CHARSET },
313 { "MS Hei", GB2312_CHARSET },
314 { "\xb7\x73\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },/*MS Mingliu*/
315 { "\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },
317 { NULL, 0 }
321 static int DefResolution = 0;
323 static CRITICAL_SECTION crtsc_fonts_X11 = CRITICAL_SECTION_INIT("crtsc_fonts_X11");
325 static fontResource* fontList = NULL;
326 static fontObject* fontCache = NULL; /* array */
327 static int fontCacheSize = FONTCACHE;
328 static int fontLF = -1, fontMRU = -1; /* last free, most recently used */
330 #define __PFONT(pFont) ( fontCache + ((UINT)(pFont) & 0x0000FFFF) )
331 #define CHECK_PFONT(pFont) ( (((UINT)(pFont) & 0xFFFF0000) == X_PFONT_MAGIC) &&\
332 (((UINT)(pFont) & 0x0000FFFF) < fontCacheSize) )
334 static Atom RAW_ASCENT;
335 static Atom RAW_DESCENT;
337 /***********************************************************************
338 * Helper macros from X distribution
341 #define CI_NONEXISTCHAR(cs) (((cs)->width == 0) && \
342 (((cs)->rbearing|(cs)->lbearing| \
343 (cs)->ascent|(cs)->descent) == 0))
345 #define CI_GET_CHAR_INFO(fs,col,def,cs) \
347 cs = def; \
348 if (col >= fs->min_char_or_byte2 && col <= fs->max_char_or_byte2) { \
349 if (fs->per_char == NULL) { \
350 cs = &fs->min_bounds; \
351 } else { \
352 cs = &fs->per_char[(col - fs->min_char_or_byte2)]; \
353 if (CI_NONEXISTCHAR(cs)) cs = def; \
358 #define CI_GET_DEFAULT_INFO(fs,cs) \
359 CI_GET_CHAR_INFO(fs, fs->default_char, NULL, cs)
362 /***********************************************************************
363 * is_stock_font
365 inline static BOOL is_stock_font( HFONT font )
367 int i;
368 for (i = OEM_FIXED_FONT; i <= DEFAULT_GUI_FONT; i++)
370 if (i != DEFAULT_PALETTE && font == GetStockObject(i)) return TRUE;
372 return FALSE;
376 /***********************************************************************
377 * Checksums
379 static UINT16 __lfCheckSum( LPLOGFONT16 plf )
381 CHAR font[LF_FACESIZE];
382 UINT16 checksum = 0;
383 UINT16 *ptr;
384 int i;
386 ptr = (UINT16 *)plf;
387 for (i = 0; i < 9; i++) checksum ^= *ptr++;
388 for (i = 0; i < LF_FACESIZE; i++)
390 font[i] = tolower(plf->lfFaceName[i]);
391 if (!font[i] || font[i] == ' ') break;
393 for (ptr = (UINT16 *)font, i >>= 1; i > 0; i-- ) checksum ^= *ptr++;
394 return checksum;
397 static UINT16 __genericCheckSum( const void *ptr, int size )
399 unsigned int checksum = 0;
400 const char *p = (const char *)ptr;
401 while (size-- > 0)
402 checksum ^= (checksum << 3) + (checksum >> 29) + *p++;
404 return checksum & 0xffff;
407 /*************************************************************************
408 * LFD parse/compose routines
410 * NB. LFD_Parse will use lpFont for its own ends, so if you want to keep it
411 * make a copy first
413 * These functions also do TILDE to HYPHEN conversion
415 static LFD* LFD_Parse(LPSTR lpFont)
417 LFD* lfd;
418 char *lpch = lpFont, *lfd_fld[LFD_FIELDS], *field_start;
419 int i;
420 if (*lpch != HYPHEN)
422 WARN("font '%s' doesn't begin with '%c'\n", lpFont, HYPHEN);
423 return NULL;
426 field_start = ++lpch;
427 for( i = 0; i < LFD_FIELDS; )
429 if (*lpch == HYPHEN)
431 *lpch = '\0';
432 lfd_fld[i] = field_start;
433 i++;
434 field_start = ++lpch;
436 else if (!*lpch)
438 lfd_fld[i] = field_start;
439 i++;
440 break;
442 else if (*lpch == TILDE)
444 *lpch = HYPHEN;
445 ++lpch;
447 else
448 ++lpch;
450 /* Fill in the empty fields with NULLS */
451 for (; i< LFD_FIELDS; i++)
452 lfd_fld[i] = NULL;
453 if (*lpch)
454 WARN("Extra ignored in font '%s'\n", lpFont);
456 lfd = HeapAlloc( GetProcessHeap(), 0, sizeof(LFD) );
457 if (lfd)
459 lfd->foundry = lfd_fld[0];
460 lfd->family = lfd_fld[1];
461 lfd->weight = lfd_fld[2];
462 lfd->slant = lfd_fld[3];
463 lfd->set_width = lfd_fld[4];
464 lfd->add_style = lfd_fld[5];
465 lfd->pixel_size = lfd_fld[6];
466 lfd->point_size = lfd_fld[7];
467 lfd->resolution_x = lfd_fld[8];
468 lfd->resolution_y = lfd_fld[9];
469 lfd->spacing = lfd_fld[10];
470 lfd->average_width = lfd_fld[11];
471 lfd->charset_registry = lfd_fld[12];
472 lfd->charset_encoding = lfd_fld[13];
474 return lfd;
478 static void LFD_UnParse(LPSTR dp, UINT buf_size, LFD* lfd)
480 const char* lfd_fld[LFD_FIELDS];
481 int i;
483 if (!buf_size)
484 return; /* Dont be silly */
486 lfd_fld[0] = lfd->foundry;
487 lfd_fld[1] = lfd->family;
488 lfd_fld[2] = lfd->weight ;
489 lfd_fld[3] = lfd->slant ;
490 lfd_fld[4] = lfd->set_width ;
491 lfd_fld[5] = lfd->add_style;
492 lfd_fld[6] = lfd->pixel_size;
493 lfd_fld[7] = lfd->point_size;
494 lfd_fld[8] = lfd->resolution_x;
495 lfd_fld[9] = lfd->resolution_y ;
496 lfd_fld[10] = lfd->spacing ;
497 lfd_fld[11] = lfd->average_width ;
498 lfd_fld[12] = lfd->charset_registry ;
499 lfd_fld[13] = lfd->charset_encoding ;
501 buf_size--; /* Room for the terminator */
503 for (i = 0; i < LFD_FIELDS; i++)
505 const char* sp = lfd_fld[i];
506 if (!sp || !buf_size)
507 break;
509 *dp++ = HYPHEN;
510 buf_size--;
511 while (buf_size > 0 && *sp)
513 *dp = (*sp == HYPHEN) ? TILDE : *sp;
514 buf_size--;
515 dp++; sp++;
518 *dp = '\0';
522 static void LFD_GetWeight( fontInfo* fi, LPCSTR lpStr)
524 int j = strlen(lpStr);
525 if( j == 1 && *lpStr == '0')
526 fi->fi_flags |= FI_POLYWEIGHT;
527 else if( j == 4 )
529 if( !strcasecmp( "bold", lpStr) )
530 fi->df.dfWeight = FW_BOLD;
531 else if( !strcasecmp( "demi", lpStr) )
533 fi->fi_flags |= FI_FW_DEMI;
534 fi->df.dfWeight = FW_DEMIBOLD;
536 else if( !strcasecmp( "book", lpStr) )
538 fi->fi_flags |= FI_FW_BOOK;
539 fi->df.dfWeight = FW_REGULAR;
542 else if( j == 5 )
544 if( !strcasecmp( "light", lpStr) )
545 fi->df.dfWeight = FW_LIGHT;
546 else if( !strcasecmp( "black", lpStr) )
547 fi->df.dfWeight = FW_BLACK;
549 else if( j == 6 && !strcasecmp( "medium", lpStr) )
550 fi->df.dfWeight = FW_REGULAR;
551 else if( j == 8 && !strcasecmp( "demibold", lpStr) )
552 fi->df.dfWeight = FW_DEMIBOLD;
553 else
554 fi->df.dfWeight = FW_DONTCARE; /* FIXME: try to get something
555 * from the weight property */
558 static BOOL LFD_GetSlant( fontInfo* fi, LPCSTR lpStr)
560 int l = strlen(lpStr);
561 if( l == 1 )
563 switch( tolower( *lpStr ) )
565 case '0': fi->fi_flags |= FI_POLYSLANT; /* haven't seen this one yet */
566 default:
567 case 'r': fi->df.dfItalic = 0;
568 break;
569 case 'o':
570 fi->fi_flags |= FI_OBLIQUE;
571 case 'i': fi->df.dfItalic = 1;
572 break;
574 return FALSE;
576 return TRUE;
579 static void LFD_GetStyle( fontInfo* fi, LPCSTR lpstr, int dec_style_check)
581 int j = strlen(lpstr);
582 if( j > 3 ) /* find out is there "sans" or "script" */
584 j = 0;
586 if( strstr(lpstr, "sans") )
588 fi->df.dfPitchAndFamily |= FF_SWISS;
589 j = 1;
591 if( strstr(lpstr, "script") )
593 fi->df.dfPitchAndFamily |= FF_SCRIPT;
594 j = 1;
596 if( !j && dec_style_check )
597 fi->df.dfPitchAndFamily |= FF_DECORATIVE;
601 /*************************************************************************
602 * LFD_InitFontInfo
604 * INIT ONLY
606 * Fill in some fields in the fontInfo struct.
608 static int LFD_InitFontInfo( fontInfo* fi, const LFD* lfd, LPCSTR fullname )
610 int i, j, dec_style_check, scalability;
611 fontEncodingTemplate* boba;
612 const char* ridiculous = "font '%s' has ridiculous %s\n";
613 const char* lpstr;
615 if (!lfd->charset_registry)
617 WARN("font '%s' does not have enough fields\n", fullname);
618 return FALSE;
621 memset(fi, 0, sizeof(fontInfo) );
623 /* weight name - */
624 LFD_GetWeight( fi, lfd->weight);
626 /* slant - */
627 dec_style_check = LFD_GetSlant( fi, lfd->slant);
629 /* width name - */
630 lpstr = lfd->set_width;
631 if( strcasecmp( "normal", lpstr) ) /* XXX 'narrow', 'condensed', etc... */
632 dec_style_check = TRUE;
633 else
634 fi->fi_flags |= FI_NORMAL;
636 /* style - */
637 LFD_GetStyle(fi, lfd->add_style, dec_style_check);
639 /* pixel & decipoint height, and res_x & y */
641 scalability = 0;
643 j = strlen(lfd->pixel_size);
644 if( j == 0 || j > 3 )
646 WARN(ridiculous, fullname, "pixel_size");
647 return FALSE;
649 if( !(fi->lfd_height = atoi(lfd->pixel_size)) )
650 scalability++;
652 j = strlen(lfd->point_size);
653 if( j == 0 || j > 3 )
655 WARN(ridiculous, fullname, "point_size");
656 return FALSE;
658 if( !(atoi(lfd->point_size)) )
659 scalability++;
661 j = strlen(lfd->resolution_x);
662 if( j == 0 || j > 3 )
664 WARN(ridiculous, fullname, "resolution_x");
665 return FALSE;
667 if( !(fi->lfd_resolution = atoi(lfd->resolution_x)) )
668 scalability++;
670 j = strlen(lfd->resolution_y);
671 if( j == 0 || j > 3 )
673 WARN(ridiculous, fullname, "resolution_y");
674 return FALSE;
676 if( !(atoi(lfd->resolution_y)) )
677 scalability++;
679 /* Check scalability */
680 switch (scalability)
682 case 0: /* Bitmap */
683 break;
684 case 4: /* Scalable */
685 fi->fi_flags |= FI_SCALABLE;
686 break;
687 case 2:
688 /* #$%^!!! X11R6 mutant garbage (scalable bitmap) */
689 TRACE("Skipping scalable bitmap '%s'\n", fullname);
690 return FALSE;
691 default:
692 WARN("Font '%s' has weird scalability\n", fullname);
693 return FALSE;
696 /* spacing - */
697 lpstr = lfd->spacing;
698 switch( *lpstr )
700 case '\0':
701 WARN("font '%s' has no spacing\n", fullname);
702 return FALSE;
704 case 'p': fi->fi_flags |= FI_VARIABLEPITCH;
705 break;
706 case 'c': fi->df.dfPitchAndFamily |= FF_MODERN;
707 fi->fi_flags |= FI_FIXEDEX;
708 /* fall through */
709 case 'm': fi->fi_flags |= FI_FIXEDPITCH;
710 break;
711 default:
712 /* Of course this line does nothing */
713 fi->df.dfPitchAndFamily |= DEFAULT_PITCH | FF_DONTCARE;
716 /* average width - */
717 lpstr = lfd->average_width;
718 j = strlen(lpstr);
719 if( j == 0 || j > 3 )
721 WARN(ridiculous, fullname, "average_width");
722 return FALSE;
725 if( !(atoi(lpstr)) && !scalability )
727 WARN("font '%s' has average_width 0 but is not scalable!!\n", fullname);
728 return FALSE;
731 /* charset registry, charset encoding - */
732 lpstr = lfd->charset_registry;
733 if( strstr(lpstr, "ksc") ||
734 strstr(lpstr, "gb2312") ||
735 strstr(lpstr, "big5") )
737 FIXME("DBCS fonts like '%s' are not working correctly now.\n", fullname);
740 fi->df.dfCharSet = ANSI_CHARSET;
742 for( i = 0, boba = fETTable; boba; boba = boba->next, i++ )
744 if (!boba->prefix || !strcasecmp(lpstr, boba->prefix))
746 if (lfd->charset_encoding)
748 for( j = 0; boba->sufch[j].psuffix; j++ )
750 if( !strcasecmp(lfd->charset_encoding, boba->sufch[j].psuffix ))
752 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
753 fi->internal_charset = boba->sufch[j].charset;
754 fi->codepage = boba->sufch[j].codepage;
755 fi->cptable = boba->sufch[j].cptable;
756 goto done;
760 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
761 fi->internal_charset = boba->sufch[j].charset;
762 fi->codepage = boba->sufch[j].codepage;
763 fi->cptable = boba->sufch[j].cptable;
764 if (boba->prefix)
766 FIXME("font '%s' has unknown character encoding '%s' in known registry '%s'\n",
767 fullname, lfd->charset_encoding, boba->prefix);
768 j = 254;
770 else
772 FIXME("font '%s' has unknown registry '%s' and character encoding '%s' \n",
773 fullname, lfd->charset_registry, lfd->charset_encoding);
774 j = 255;
777 WARN("Defaulting to: df.dfCharSet = %d, internal_charset = %d, codepage = %d, cptable = %d\n",
778 fi->df.dfCharSet,fi->internal_charset, fi->codepage, fi->cptable);
779 goto done;
781 else if (boba->prefix)
783 WARN("font '%s' has known registry '%s' and no character encoding\n",
784 fullname, lpstr);
785 for( j = 0; boba->sufch[j].psuffix; j++ )
787 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
788 fi->internal_charset = boba->sufch[j].charset;
789 fi->codepage = boba->sufch[j].codepage;
790 fi->cptable = boba->sufch[j].cptable;
791 j = 255;
792 goto done;
796 WARN("font '%s' has unknown character set '%s'\n", fullname, lpstr);
797 return FALSE;
799 done:
800 /* i - index into fETTable
801 * j - index into suffix array for fETTable[i]
802 * except:
803 * 254 - found encoding prefix, unknown suffix
804 * 255 - no encoding match at all.
806 fi->fi_encoding = 256 * (UINT16)i + (UINT16)j;
808 return TRUE;
812 /*************************************************************************
813 * LFD_AngleMatrix
815 * make a matrix suitable for LFD based on theta radians
817 static void LFD_AngleMatrix( char* buffer, int h, double theta)
819 double matrix[4];
820 matrix[0] = h*cos(theta);
821 matrix[1] = h*sin(theta);
822 matrix[2] = -h*sin(theta);
823 matrix[3] = h*cos(theta);
824 sprintf(buffer, "[%+f%+f%+f%+f]", matrix[0], matrix[1], matrix[2], matrix[3]);
827 /*************************************************************************
828 * LFD_ComposeLFD
830 * Note: uRelax is a treatment not a cure. Font mapping algorithm
831 * should be bulletproof enough to allow us to avoid hacks like
832 * this despite LFD being so braindead.
834 static BOOL LFD_ComposeLFD( const fontObject* fo,
835 INT height, LPSTR lpLFD, UINT uRelax )
837 int i, h;
838 char *any = "*";
839 char h_string[64], resx_string[64], resy_string[64];
840 LFD aLFD;
842 /* Get the worst case over with first */
844 /* RealizeFont() will call us repeatedly with increasing uRelax
845 * until XLoadFont() succeeds.
846 * to avoid an infinite loop; these will always match
848 if (uRelax >= 5)
850 if (uRelax == 5)
851 sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-1" );
852 else
853 sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*" );
854 return TRUE;
857 /* read foundry + family from fo */
858 aLFD.foundry = fo->fr->resource->foundry;
859 aLFD.family = fo->fr->resource->family;
861 /* add weight */
862 switch( fo->fi->df.dfWeight )
864 case FW_BOLD:
865 aLFD.weight = "bold"; break;
866 case FW_REGULAR:
867 if( fo->fi->fi_flags & FI_FW_BOOK )
868 aLFD.weight = "book";
869 else
870 aLFD.weight = "medium";
871 break;
872 case FW_DEMIBOLD:
873 aLFD.weight = "demi";
874 if( !( fo->fi->fi_flags & FI_FW_DEMI) )
875 aLFD.weight = "bold";
876 break;
877 case FW_BLACK:
878 aLFD.weight = "black"; break;
879 case FW_LIGHT:
880 aLFD.weight = "light"; break;
881 default:
882 aLFD.weight = any;
885 /* add slant */
886 if( fo->fi->df.dfItalic )
887 if( fo->fi->fi_flags & FI_OBLIQUE )
888 aLFD.slant = "o";
889 else
890 aLFD.slant = "i";
891 else
892 aLFD.slant = (uRelax < 1) ? "r" : any;
894 /* add width */
895 if( fo->fi->fi_flags & FI_NORMAL )
896 aLFD.set_width = "normal";
897 else
898 aLFD.set_width = any;
900 /* ignore style */
901 aLFD.add_style = any;
903 /* add pixelheight
905 * FIXME: fill in lpXForm and lpPixmap for rotated fonts
907 if( fo->fo_flags & FO_SYNTH_HEIGHT )
908 h = fo->fi->lfd_height;
909 else
911 h = (fo->fi->lfd_height * height + (fo->fi->df.dfPixHeight>>1));
912 h /= fo->fi->df.dfPixHeight;
914 if (h < MIN_FONT_SIZE) /* Resist rounding down to 0 */
915 h = MIN_FONT_SIZE;
916 else if (h > MAX_FONT_SIZE) /* Sanity check as huge fonts can lock up the font server */
918 WARN("Huge font size %d pixels has been reduced to %d\n", h, MAX_FONT_SIZE);
919 h = MAX_FONT_SIZE;
922 if (uRelax <= 2)
923 /* handle rotated fonts */
924 if (fo->lf.lfEscapement) {
925 /* escapement is in tenths of degrees, theta is in radians */
926 double theta = M_PI*fo->lf.lfEscapement/1800.;
927 LFD_AngleMatrix(h_string, h, theta);
929 else
931 sprintf(h_string, "%d", h);
933 else
934 sprintf(h_string, "%d", fo->fi->lfd_height);
936 aLFD.pixel_size = h_string;
937 aLFD.point_size = any;
939 /* resolution_x,y, average width */
940 /* FOX ME - Why do some font servers ignore average width ?
941 * so that you have to mess around with res_y
943 aLFD.average_width = any;
944 if (uRelax <= 3)
946 sprintf(resx_string, "%d", fo->fi->lfd_resolution);
947 aLFD.resolution_x = resx_string;
949 strcpy(resy_string, resx_string);
950 if( uRelax == 0 && text_caps & TC_SF_X_YINDEP )
952 if( fo->lf.lfWidth && !(fo->fo_flags & FO_SYNTH_WIDTH))
954 int resy = 0.5 + fo->fi->lfd_resolution *
955 (fo->fi->df.dfAvgWidth * height) /
956 (fo->lf.lfWidth * fo->fi->df.dfPixHeight) ;
957 sprintf(resy_string, "%d", resy);
959 else
961 /* FIXME - synth width */
964 aLFD.resolution_y = resy_string;
966 else
968 aLFD.resolution_x = aLFD.resolution_y = any;
971 /* spacing */
973 char* w;
975 if( fo->fi->fi_flags & FI_FIXEDPITCH )
976 w = ( fo->fi->fi_flags & FI_FIXEDEX ) ? "c" : "m";
977 else
978 w = ( fo->fi->fi_flags & FI_VARIABLEPITCH ) ? "p" : any;
980 aLFD.spacing = (uRelax <= 1) ? w : any;
983 /* encoding */
985 if (uRelax <= 4)
987 fontEncodingTemplate* boba = fETTable;
989 for(i = fo->fi->fi_encoding >> 8; i; i--) boba = boba->next;
990 aLFD.charset_registry = boba->prefix ? boba->prefix : any;
992 i = fo->fi->fi_encoding & 255;
993 switch( i )
995 default:
996 aLFD.charset_encoding = boba->sufch[i].psuffix;
997 break;
999 case 254:
1000 aLFD.charset_encoding = any;
1001 break;
1003 case 255: /* no suffix - it ends eg "-ascii" */
1004 aLFD.charset_encoding = NULL;
1005 break;
1008 else
1010 aLFD.charset_registry = any;
1011 aLFD.charset_encoding = any;
1014 LFD_UnParse(lpLFD, MAX_LFD_LENGTH, &aLFD);
1016 TRACE("\tLFD(uRelax=%d): %s\n", uRelax, lpLFD );
1017 return TRUE;
1021 /***********************************************************************
1022 * X Font Resources
1024 * font info - http://www.microsoft.com/kb/articles/q65/1/23.htm
1025 * Windows font metrics - http://www.microsoft.com/kb/articles/q32/6/67.htm
1027 static void XFONT_GetLeading( const LPIFONTINFO16 pFI, const XFontStruct* x_fs,
1028 INT16* pIL, INT16* pEL, const XFONTTRANS *XFT )
1030 unsigned long height;
1031 unsigned min = (unsigned char)pFI->dfFirstChar;
1032 BOOL bIsLatin = IS_LATIN_CHARSET(pFI->dfCharSet);
1034 if( pEL ) *pEL = 0;
1036 if(XFT) {
1037 Atom RAW_CAP_HEIGHT = TSXInternAtom(gdi_display, "RAW_CAP_HEIGHT", TRUE);
1038 if(TSXGetFontProperty((XFontStruct*)x_fs, RAW_CAP_HEIGHT, &height))
1039 *pIL = XFT->ascent -
1040 (INT)(XFT->pixelsize / 1000.0 * height);
1041 else
1042 *pIL = 0;
1043 return;
1046 if( TSXGetFontProperty((XFontStruct*)x_fs, XA_CAP_HEIGHT, &height) == FALSE )
1048 if( x_fs->per_char )
1049 if( bIsLatin )
1050 height = x_fs->per_char['X' - min].ascent;
1051 else
1052 if (x_fs->ascent >= x_fs->max_bounds.ascent)
1053 height = x_fs->max_bounds.ascent;
1054 else
1056 height = x_fs->ascent;
1057 if( pEL )
1058 *pEL = x_fs->max_bounds.ascent - height;
1060 else
1061 height = x_fs->min_bounds.ascent;
1064 *pIL = x_fs->ascent - height;
1067 /***********************************************************************
1068 * XFONT_CharWidth
1070 static int XFONT_CharWidth(const XFontStruct* x_fs,
1071 const XFONTTRANS *XFT, int ch)
1073 if(!XFT)
1074 return x_fs->per_char[ch].width;
1075 else
1076 return x_fs->per_char[ch].attributes * XFT->pixelsize / 1000.0;
1079 /***********************************************************************
1080 * XFONT_GetAvgCharWidth
1082 static INT XFONT_GetAvgCharWidth( LPIFONTINFO16 pFI, const XFontStruct* x_fs,
1083 const XFONTTRANS *XFT)
1085 unsigned min = (unsigned char)pFI->dfFirstChar;
1086 unsigned max = (unsigned char)pFI->dfLastChar;
1088 INT avg;
1090 if( x_fs->per_char )
1092 int width = 0, chars = 0, j;
1093 if( IS_LATIN_CHARSET(pFI->dfCharSet) ||
1094 pFI->dfCharSet == DEFAULT_CHARSET )
1096 /* FIXME - should use a weighted average */
1097 for( j = 0; j < 26; j++ )
1098 width += XFONT_CharWidth(x_fs, XFT, 'a' + j - min) +
1099 XFONT_CharWidth(x_fs, XFT, 'A' + j - min);
1100 chars = 52;
1102 else /* unweighted average of everything */
1104 for( j = 0, max -= min; j <= max; j++ )
1105 if( !CI_NONEXISTCHAR(x_fs->per_char + j) )
1107 width += XFONT_CharWidth(x_fs, XFT, j);
1108 chars++;
1111 if (chars) avg = (width + (chars-1))/ chars; /* always round up*/
1112 else avg = 0; /* No characters exist at all */
1114 else /* uniform width */
1115 avg = x_fs->min_bounds.width;
1117 TRACE(" retuning %d\n",avg);
1118 return avg;
1121 /***********************************************************************
1122 * XFONT_GetMaxCharWidth
1124 static INT XFONT_GetMaxCharWidth(const XFontStruct* xfs, const XFONTTRANS *XFT)
1126 unsigned min = (unsigned char)xfs->min_char_or_byte2;
1127 unsigned max = (unsigned char)xfs->max_char_or_byte2;
1128 int maxwidth, j;
1130 if(!XFT || !xfs->per_char)
1131 return abs(xfs->max_bounds.width);
1133 for( j = 0, maxwidth = 0, max -= min; j <= max; j++ )
1134 if( !CI_NONEXISTCHAR(xfs->per_char + j) )
1135 if(maxwidth < xfs->per_char[j].attributes)
1136 maxwidth = xfs->per_char[j].attributes;
1138 maxwidth *= XFT->pixelsize / 1000.0;
1139 return maxwidth;
1142 /***********************************************************************
1143 * XFONT_SetFontMetric
1145 * INIT ONLY
1147 * Initializes IFONTINFO16.
1149 static void XFONT_SetFontMetric(fontInfo* fi, const fontResource* fr, XFontStruct* xfs)
1151 unsigned min, max;
1152 fi->df.dfFirstChar = (BYTE)(min = xfs->min_char_or_byte2);
1153 fi->df.dfLastChar = (BYTE)(max = xfs->max_char_or_byte2);
1155 fi->df.dfDefaultChar = (BYTE)xfs->default_char;
1156 fi->df.dfBreakChar = (BYTE)(( ' ' < min || ' ' > max) ? xfs->default_char: ' ');
1158 fi->df.dfPixHeight = (INT16)((fi->df.dfAscent = (INT16)xfs->ascent) + xfs->descent);
1159 fi->df.dfPixWidth = (xfs->per_char) ? 0 : xfs->min_bounds.width;
1161 XFONT_GetLeading( &fi->df, xfs, &fi->df.dfInternalLeading, &fi->df.dfExternalLeading, NULL );
1162 fi->df.dfAvgWidth = (INT16)XFONT_GetAvgCharWidth(&fi->df, xfs, NULL );
1163 fi->df.dfMaxWidth = (INT16)XFONT_GetMaxCharWidth(xfs, NULL);
1165 if( xfs->min_bounds.width != xfs->max_bounds.width )
1166 fi->df.dfPitchAndFamily |= TMPF_FIXED_PITCH; /* au contraire! */
1167 if( fi->fi_flags & FI_SCALABLE )
1169 fi->df.dfType = DEVICE_FONTTYPE;
1170 fi->df.dfPitchAndFamily |= TMPF_DEVICE;
1172 else if( fi->fi_flags & FI_TRUETYPE )
1173 fi->df.dfType = TRUETYPE_FONTTYPE;
1174 else
1175 fi->df.dfType = RASTER_FONTTYPE;
1177 fi->df.dfFace = fr->lfFaceName;
1180 /***********************************************************************
1181 * XFONT_GetFontMetric
1183 * Retrieve font metric info (enumeration).
1185 static UINT XFONT_GetFontMetric( const fontInfo* pfi,
1186 const LPENUMLOGFONTEXW pLF,
1187 const LPNEWTEXTMETRICEXW pTM )
1189 memset( pLF, 0, sizeof(*pLF) );
1190 memset( pTM, 0, sizeof(*pTM) );
1192 #define plf ((LPLOGFONTW)pLF)
1193 #define ptm ((LPNEWTEXTMETRICW)pTM)
1194 plf->lfHeight = ptm->tmHeight = pfi->df.dfPixHeight;
1195 plf->lfWidth = ptm->tmAveCharWidth = pfi->df.dfAvgWidth;
1196 plf->lfWeight = ptm->tmWeight = pfi->df.dfWeight;
1197 plf->lfItalic = ptm->tmItalic = pfi->df.dfItalic;
1198 plf->lfUnderline = ptm->tmUnderlined = pfi->df.dfUnderline;
1199 plf->lfStrikeOut = ptm->tmStruckOut = pfi->df.dfStrikeOut;
1200 plf->lfCharSet = ptm->tmCharSet = pfi->df.dfCharSet;
1202 /* convert pitch values */
1204 ptm->tmPitchAndFamily = pfi->df.dfPitchAndFamily;
1205 plf->lfPitchAndFamily = (pfi->df.dfPitchAndFamily & 0xF1) + 1;
1207 MultiByteToWideChar(CP_ACP, 0, pfi->df.dfFace, -1,
1208 plf->lfFaceName, LF_FACESIZE);
1210 /* FIXME: fill in rest of plF values */
1211 strcpyW(pLF->elfFullName, plf->lfFaceName);
1212 MultiByteToWideChar(CP_ACP, 0, "Regular", -1,
1213 pLF->elfStyle, LF_FACESIZE);
1214 MultiByteToWideChar(CP_ACP, 0, plf->lfCharSet == SYMBOL_CHARSET ?
1215 "Symbol" : "Roman", -1,
1216 pLF->elfScript, LF_FACESIZE);
1218 #undef plf
1220 ptm->tmAscent = pfi->df.dfAscent;
1221 ptm->tmDescent = ptm->tmHeight - ptm->tmAscent;
1222 ptm->tmInternalLeading = pfi->df.dfInternalLeading;
1223 ptm->tmMaxCharWidth = pfi->df.dfMaxWidth;
1224 ptm->tmDigitizedAspectX = pfi->df.dfHorizRes;
1225 ptm->tmDigitizedAspectY = pfi->df.dfVertRes;
1227 ptm->tmFirstChar = pfi->df.dfFirstChar;
1228 ptm->tmLastChar = pfi->df.dfLastChar;
1229 ptm->tmDefaultChar = pfi->df.dfDefaultChar;
1230 ptm->tmBreakChar = pfi->df.dfBreakChar;
1232 TRACE("Calling Enum proc with FaceName %s FullName %s\n",
1233 debugstr_w(pLF->elfLogFont.lfFaceName),
1234 debugstr_w(pLF->elfFullName));
1236 TRACE("CharSet = %d type = %d\n", ptm->tmCharSet, pfi->df.dfType);
1237 /* return font type */
1238 return pfi->df.dfType;
1239 #undef ptm
1243 /***********************************************************************
1244 * XFONT_FixupFlags
1246 * INIT ONLY
1248 * dfPitchAndFamily flags for some common typefaces.
1250 static BYTE XFONT_FixupFlags( LPCSTR lfFaceName )
1252 switch( lfFaceName[0] )
1254 case 'a':
1255 case 'A': if(!strncasecmp(lfFaceName, "Arial", 5) )
1256 return FF_SWISS;
1257 break;
1258 case 'h':
1259 case 'H': if(!strcasecmp(lfFaceName, "Helvetica") )
1260 return FF_SWISS;
1261 break;
1262 case 'c':
1263 case 'C': if(!strncasecmp(lfFaceName, "Courier", 7))
1264 return FF_MODERN;
1266 if (!strcasecmp(lfFaceName, "Charter") )
1267 return FF_ROMAN;
1268 break;
1269 case 'p':
1270 case 'P': if( !strcasecmp(lfFaceName,"Palatino") )
1271 return FF_ROMAN;
1272 break;
1273 case 't':
1274 case 'T': if(!strncasecmp(lfFaceName, "Times", 5) )
1275 return FF_ROMAN;
1276 break;
1277 case 'u':
1278 case 'U': if(!strcasecmp(lfFaceName, "Utopia") )
1279 return FF_ROMAN;
1280 break;
1281 case 'z':
1282 case 'Z': if(!strcasecmp(lfFaceName, "Zapf Dingbats") )
1283 return FF_DECORATIVE;
1285 return 0;
1288 /***********************************************************************
1289 * XFONT_SameFoundryAndFamily
1291 * INIT ONLY
1293 static BOOL XFONT_SameFoundryAndFamily( const LFD* lfd1, const LFD* lfd2 )
1295 return ( !strcasecmp( lfd1->foundry, lfd2->foundry ) &&
1296 !strcasecmp( lfd1->family, lfd2->family ) );
1299 /***********************************************************************
1300 * XFONT_InitialCapitals
1302 * INIT ONLY
1304 * Upper case first letters of words & remove multiple spaces
1306 static void XFONT_InitialCapitals(LPSTR lpch)
1308 int i;
1309 BOOL up;
1310 char* lpstr = lpch;
1312 for( i = 0, up = TRUE; *lpch; lpch++, i++ )
1314 if( isspace(*lpch) )
1316 if (!up) /* Not already got one */
1318 *lpstr++ = ' ';
1319 up = TRUE;
1322 else if( isalpha(*lpch) && up )
1324 *lpstr++ = toupper(*lpch);
1325 up = FALSE;
1327 else
1329 *lpstr++ = *lpch;
1330 up = FALSE;
1334 /* Remove possible trailing space */
1335 if (up && i > 0)
1336 --lpstr;
1337 *lpstr = '\0';
1341 /***********************************************************************
1342 * XFONT_WindowsNames
1344 * INIT ONLY
1346 * Build generic Windows aliases for X font names.
1348 * -misc-fixed- -> "Fixed"
1349 * -sony-fixed- -> "Sony Fixed", etc...
1351 static void XFONT_WindowsNames(void)
1353 fontResource* fr;
1355 for( fr = fontList; fr ; fr = fr->next )
1357 fontResource* pfr;
1358 char* lpch;
1360 if( fr->fr_flags & FR_NAMESET ) continue; /* skip already assigned */
1362 for( pfr = fontList; pfr != fr ; pfr = pfr->next )
1363 if( pfr->fr_flags & FR_NAMESET )
1365 if (!strcasecmp( pfr->resource->family, fr->resource->family))
1366 break;
1369 lpch = fr->lfFaceName;
1370 snprintf( fr->lfFaceName, sizeof(fr->lfFaceName), "%s %s",
1371 /* prepend vendor name */
1372 (pfr==fr) ? "" : fr->resource->foundry,
1373 fr->resource->family);
1374 XFONT_InitialCapitals(fr->lfFaceName);
1376 BYTE bFamilyStyle = XFONT_FixupFlags( fr->lfFaceName );
1377 if( bFamilyStyle)
1379 fontInfo* fi;
1380 for( fi = fr->fi ; fi ; fi = fi->next )
1381 fi->df.dfPitchAndFamily |= bFamilyStyle;
1385 TRACE("typeface '%s'\n", fr->lfFaceName);
1387 fr->fr_flags |= FR_NAMESET;
1391 /***********************************************************************
1392 * XFONT_LoadDefaultLFD
1394 * Move lfd to the head of fontList to make it more likely to be matched
1396 static void XFONT_LoadDefaultLFD(LFD* lfd, LPCSTR fonttype)
1399 fontResource *fr, *pfr;
1400 for( fr = NULL, pfr = fontList; pfr; pfr = pfr->next )
1402 if( XFONT_SameFoundryAndFamily(pfr->resource, lfd) )
1404 if( fr )
1406 fr->next = pfr->next;
1407 pfr->next = fontList;
1408 fontList = pfr;
1410 break;
1412 fr = pfr;
1414 if (!pfr)
1415 WARN("Default %sfont '-%s-%s-' not available\n", fonttype,
1416 lfd->foundry, lfd->family);
1420 /***********************************************************************
1421 * XFONT_LoadDefault
1423 static void XFONT_LoadDefault(LPCSTR ini, LPCSTR fonttype)
1425 char buffer[MAX_LFD_LENGTH];
1426 HKEY hkey;
1428 buffer[0] = 0;
1429 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1431 DWORD type, count = sizeof(buffer);
1432 RegQueryValueExA(hkey, ini, 0, &type, buffer, &count);
1433 RegCloseKey(hkey);
1435 if (*buffer)
1437 LFD* lfd;
1438 char* pch = buffer;
1439 while( *pch && isspace(*pch) ) pch++;
1441 TRACE("Using '%s' as default %sfont\n", pch, fonttype);
1442 lfd = LFD_Parse(pch);
1443 if (lfd && lfd->foundry && lfd->family)
1444 XFONT_LoadDefaultLFD(lfd, fonttype);
1445 else
1446 WARN("Ini section [%s]%s is malformed\n", INIFontSection, ini);
1447 HeapFree(GetProcessHeap(), 0, lfd);
1452 /***********************************************************************
1453 * XFONT_LoadDefaults
1455 static void XFONT_LoadDefaults(void)
1457 XFONT_LoadDefault(INIDefaultFixed, "fixed ");
1458 XFONT_LoadDefault(INIDefault, "");
1461 /***********************************************************************
1462 * XFONT_CreateAlias
1464 static fontAlias* XFONT_CreateAlias( LPCSTR lpTypeFace, LPCSTR lpAlias )
1466 int j;
1467 fontAlias *pfa, *prev = NULL;
1469 for(pfa = aliasTable; pfa; pfa = pfa->next)
1471 /* check if we already got one */
1472 if( !strcasecmp( pfa->faTypeFace, lpAlias ) )
1474 TRACE("redundant alias '%s' -> '%s'\n",
1475 lpAlias, lpTypeFace );
1476 return NULL;
1478 prev = pfa;
1481 j = strlen(lpTypeFace) + 1;
1482 pfa = HeapAlloc( GetProcessHeap(), 0, sizeof(fontAlias) +
1483 j + strlen(lpAlias) + 1 );
1484 if (pfa)
1486 if (!prev)
1487 aliasTable = pfa;
1488 else
1489 prev->next = pfa;
1491 pfa->next = NULL;
1492 pfa->faTypeFace = (LPSTR)(pfa + 1);
1493 strcpy( pfa->faTypeFace, lpTypeFace );
1494 pfa->faAlias = pfa->faTypeFace + j;
1495 strcpy( pfa->faAlias, lpAlias );
1497 TRACE("added alias '%s' for '%s'\n", lpAlias, lpTypeFace );
1499 return pfa;
1501 return NULL;
1505 /***********************************************************************
1506 * XFONT_LoadAlias
1508 static void XFONT_LoadAlias(const LFD* lfd, LPCSTR lpAlias, BOOL bSubst)
1510 fontResource *fr, *frMatch = NULL;
1511 if (!lfd->foundry || ! lfd->family)
1513 WARN("Malformed font resource for alias '%s'\n", lpAlias);
1514 return;
1516 for (fr = fontList; fr ; fr = fr->next)
1518 if(!strcasecmp(fr->resource->family, lpAlias))
1520 /* alias is not needed since the real font is present */
1521 TRACE("Ignoring font alias '%s' as it is already available as a real font\n", lpAlias);
1522 return;
1524 if( XFONT_SameFoundryAndFamily( fr->resource, lfd ) )
1526 frMatch = fr;
1527 break;
1531 if( frMatch )
1533 if( bSubst )
1535 fontAlias *pfa, *prev = NULL;
1537 for(pfa = aliasTable; pfa; pfa = pfa->next)
1539 /* Remove lpAlias from aliasTable - we should free the old entry */
1540 if(!strcmp(lpAlias, pfa->faAlias))
1542 if(prev)
1543 prev->next = pfa->next;
1544 else
1545 aliasTable = pfa->next;
1548 /* Update any references to the substituted font in aliasTable */
1549 if(!strcmp(frMatch->lfFaceName, pfa->faTypeFace))
1551 pfa->faTypeFace = HeapAlloc( GetProcessHeap(), 0, strlen(lpAlias)+1 );
1552 strcpy( pfa->faTypeFace, lpAlias );
1554 prev = pfa;
1557 TRACE("\tsubstituted '%s' with '%s'\n", frMatch->lfFaceName, lpAlias );
1559 lstrcpynA( frMatch->lfFaceName, lpAlias, LF_FACESIZE );
1560 frMatch->fr_flags |= FR_NAMESET;
1562 else
1564 /* create new entry in the alias table */
1565 XFONT_CreateAlias( frMatch->lfFaceName, lpAlias );
1568 else
1570 WARN("Font alias '-%s-%s-' is not available\n", lfd->foundry, lfd->family);
1574 /***********************************************************************
1575 * Just a copy of PROFILE_GetStringItem
1577 * Convenience function that turns a string 'xxx, yyy, zzz' into
1578 * the 'xxx\0 yyy, zzz' and returns a pointer to the 'yyy, zzz'.
1580 static char *XFONT_GetStringItem( char *start )
1582 #define XFONT_isspace(c) (isspace(c) || (c == '\r') || (c == 0x1a))
1583 char *lpchX, *lpch;
1585 for (lpchX = start, lpch = NULL; *lpchX != '\0'; lpchX++ )
1587 if( *lpchX == ',' )
1589 if( lpch ) *lpch = '\0'; else *lpchX = '\0';
1590 while( *(++lpchX) )
1591 if( !XFONT_isspace(*lpchX) ) return lpchX;
1593 else if( XFONT_isspace( *lpchX ) && !lpch ) lpch = lpchX;
1594 else lpch = NULL;
1596 if( lpch ) *lpch = '\0';
1597 return NULL;
1598 #undef XFONT_isspace
1601 /***********************************************************************
1602 * XFONT_LoadAliases
1604 * INIT ONLY
1606 * Create font aliases for some standard windows fonts using user's
1607 * default choice of (sans-)serif fonts
1609 * Read user-defined aliases from wine.conf. Format is as follows
1611 * Alias# = [Windows font name],[LFD font name], <substitute original name>
1613 * Example:
1614 * Alias0 = Arial, -adobe-helvetica-
1615 * Alias1 = Times New Roman, -bitstream-courier-, 1
1616 * ...
1618 * Note that from 970817 and on we have built-in alias templates that take
1619 * care of the necessary Windows typefaces.
1621 typedef struct
1623 LPSTR fatResource;
1624 LPSTR fatAlias;
1625 } aliasTemplate;
1627 static void XFONT_LoadAliases(void)
1629 char *lpResource;
1630 char buffer[MAX_LFD_LENGTH];
1631 int i = 0;
1632 LFD* lfd;
1633 HKEY hkey;
1635 /* built-ins first */
1636 strcpy(buffer, "-bitstream-charter-");
1637 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1639 DWORD type, count = sizeof(buffer);
1640 RegQueryValueExA(hkey, INIDefaultSerif, 0, &type, buffer, &count);
1641 RegCloseKey(hkey);
1643 TRACE("Using '%s' as default serif font\n", buffer);
1644 lfd = LFD_Parse(buffer);
1645 /* NB XFONT_InitialCapitals should not change these standard aliases */
1646 if (lfd)
1648 XFONT_LoadAlias( lfd, "Tms Roman", FALSE);
1649 XFONT_LoadAlias( lfd, "MS Serif", FALSE);
1650 XFONT_LoadAlias( lfd, "Times New Roman", FALSE);
1652 XFONT_LoadDefaultLFD( lfd, "serif ");
1653 HeapFree(GetProcessHeap(), 0, lfd);
1656 strcpy(buffer, "-adobe-helvetica-");
1657 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1659 DWORD type, count = sizeof(buffer);
1660 RegQueryValueExA(hkey, INIDefaultSansSerif, 0, &type, buffer, &count);
1661 RegCloseKey(hkey);
1663 TRACE("Using '%s' as default sans serif font\n", buffer);
1664 lfd = LFD_Parse(buffer);
1665 if (lfd)
1667 XFONT_LoadAlias( lfd, "Helv", FALSE);
1668 XFONT_LoadAlias( lfd, "MS Sans Serif", FALSE);
1669 XFONT_LoadAlias( lfd, "MS Shell Dlg", FALSE);
1670 XFONT_LoadAlias( lfd, "System", FALSE);
1671 XFONT_LoadAlias( lfd, "Arial", FALSE);
1673 XFONT_LoadDefaultLFD( lfd, "sans serif ");
1674 HeapFree(GetProcessHeap(), 0, lfd);
1677 /* then user specified aliases */
1680 BOOL bSubst;
1681 char subsection[32];
1682 snprintf( subsection, sizeof subsection, "%s%i", INIAliasSection, i++ );
1684 buffer[0] = 0;
1685 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1687 DWORD type, count = sizeof(buffer);
1688 RegQueryValueExA(hkey, subsection, 0, &type, buffer, &count);
1689 RegCloseKey(hkey);
1692 if (!buffer[0])
1693 break;
1695 XFONT_InitialCapitals(buffer);
1696 lpResource = XFONT_GetStringItem( buffer );
1697 bSubst = (XFONT_GetStringItem( lpResource )) ? TRUE : FALSE;
1698 if( lpResource && *lpResource )
1700 lfd = LFD_Parse(lpResource);
1701 if (lfd)
1703 XFONT_LoadAlias(lfd, buffer, bSubst);
1704 HeapFree(GetProcessHeap(), 0, lfd);
1707 else
1708 WARN("malformed font alias '%s'\n", buffer );
1710 while(TRUE);
1713 /***********************************************************************
1714 * XFONT_UnAlias
1716 * Convert an (potential) alias into a real windows name
1719 static LPCSTR XFONT_UnAlias(char* font)
1721 if (font[0])
1723 fontAlias* fa;
1724 XFONT_InitialCapitals(font); /* to remove extra white space */
1726 for( fa = aliasTable; fa; fa = fa->next )
1727 /* use case insensitive matching to handle eg "MS Sans Serif" */
1728 if( !strcasecmp( fa->faAlias, font ) )
1730 TRACE("found alias '%s'->%s'\n", font, fa->faTypeFace );
1731 strcpy(font, fa->faTypeFace);
1732 return fa->faAlias;
1733 break;
1736 return NULL;
1739 /***********************************************************************
1740 * XFONT_RemoveFontResource
1742 * Caller should check if the font resource is in use. If it is it should
1743 * set FR_REMOVED flag to delay removal until the resource is not in use
1744 * any more.
1746 void XFONT_RemoveFontResource( fontResource** ppfr )
1748 fontResource* pfr = *ppfr;
1749 #if 0
1750 fontInfo* pfi;
1752 /* FIXME - if fonts were read from a cache, these HeapFrees will fail */
1753 while( pfr->fi )
1755 pfi = pfr->fi->next;
1756 HeapFree( GetProcessHeap(), 0, pfr->fi );
1757 pfr->fi = pfi;
1759 HeapFree( GetProcessHeap(), 0, pfr );
1760 #endif
1761 *ppfr = pfr->next;
1764 /***********************************************************************
1765 * XFONT_LoadIgnores
1767 * INIT ONLY
1769 * Removes specified fonts from the font table to prevent Wine from
1770 * using it.
1772 * Ignore# = [LFD font name]
1774 * Example:
1775 * Ignore0 = -misc-nil-
1776 * Ignore1 = -sun-open look glyph-
1777 * ...
1780 static void XFONT_LoadIgnore(char* lfdname)
1782 fontResource** ppfr;
1784 LFD* lfd = LFD_Parse(lfdname);
1785 if (lfd && lfd->foundry && lfd->family)
1787 for( ppfr = &fontList; *ppfr ; ppfr = &((*ppfr)->next))
1789 if( XFONT_SameFoundryAndFamily( (*ppfr)->resource, lfd) )
1791 TRACE("Ignoring '-%s-%s-'\n",
1792 (*ppfr)->resource->foundry, (*ppfr)->resource->family );
1794 XFONT_RemoveFontResource( ppfr );
1795 break;
1799 else
1800 WARN("Malformed font resource\n");
1802 HeapFree(GetProcessHeap(), 0, lfd);
1805 static void XFONT_LoadIgnores(void)
1807 int i = 0;
1808 char subsection[32];
1809 char buffer[MAX_LFD_LENGTH];
1811 /* Standard one that noone wants */
1812 strcpy(buffer, "-misc-nil-");
1813 XFONT_LoadIgnore(buffer);
1815 /* Others from INI file */
1818 HKEY hkey;
1819 sprintf( subsection, "%s%i", INIIgnoreSection, i++ );
1821 buffer[0] = 0;
1822 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1824 DWORD type, count = sizeof(buffer);
1825 RegQueryValueExA(hkey, subsection, 0, &type, buffer, &count);
1826 RegCloseKey(hkey);
1829 if( buffer[0] )
1831 char* pch = buffer;
1832 while( *pch && isspace(*pch) ) pch++;
1833 XFONT_LoadIgnore(pch);
1835 else
1836 break;
1837 } while(TRUE);
1841 /***********************************************************************
1842 * XFONT_UserMetricsCache
1844 * Returns expanded name for the cachedmetrics file.
1845 * Now it also appends the current value of the $DISPLAY variable.
1847 static char* XFONT_UserMetricsCache( char* buffer, int* buf_size )
1849 const char *confdir = get_config_dir();
1850 const char *display_name = XDisplayName(NULL);
1851 int len = strlen(confdir) + strlen(INIFontMetrics) + strlen(display_name) + 8;
1852 int display = 0;
1853 int screen = 0;
1854 char *p, *ext;
1857 ** Normalize the display name, since on Red Hat systems, DISPLAY
1858 ** is commonly set to one of either 'unix:0.0' or ':0' or ':0.0'.
1859 ** after this code, all of the above will resolve to ':0.0'.
1861 if (!strncmp( display_name, "unix:", 5 )) display_name += 4;
1862 p = strchr(display_name, ':');
1863 if (p) sscanf(p + 1, "%d.%d", &display, &screen);
1865 if ((len > *buf_size) &&
1866 !(buffer = HeapReAlloc( GetProcessHeap(), 0, buffer, *buf_size = len )))
1868 ERR("out of memory\n");
1869 ExitProcess(1);
1871 sprintf( buffer, "%s/%s", confdir, INIFontMetrics );
1873 ext = buffer + strlen(buffer);
1874 strcpy( ext, display_name );
1876 if (!(p = strchr( ext, ':' ))) p = ext + strlen(ext);
1877 sprintf( p, ":%d.%d", display, screen );
1878 return buffer;
1882 /***********************************************************************
1883 * X Font Matching
1885 * Compare two fonts (only parameters set by the XFONT_InitFontInfo()).
1887 static INT XFONT_IsSubset(const fontInfo* match, const fontInfo* fi)
1889 INT m;
1891 /* 0 - keep both, 1 - keep match, -1 - keep fi */
1893 /* Compare dfItalic, Underline, Strikeout, Weight, Charset */
1894 m = (BYTE*)&fi->df.dfPixWidth - (BYTE*)&fi->df.dfItalic;
1895 if( memcmp(&match->df.dfItalic, &fi->df.dfItalic, m )) return 0;
1897 if( (!((fi->fi_flags & FI_SCALABLE) + (match->fi_flags & FI_SCALABLE))
1898 && fi->lfd_height != match->lfd_height) ||
1899 (!((fi->fi_flags & FI_POLYWEIGHT) + (match->fi_flags & FI_POLYWEIGHT))
1900 && fi->df.dfWeight != match->df.dfWeight) ) return 0;
1902 m = (int)(match->fi_flags & (FI_POLYWEIGHT | FI_SCALABLE)) -
1903 (int)(fi->fi_flags & (FI_SCALABLE | FI_POLYWEIGHT));
1905 if( m == (FI_POLYWEIGHT - FI_SCALABLE) ||
1906 m == (FI_SCALABLE - FI_POLYWEIGHT) ) return 0; /* keep both */
1907 else if( m >= 0 ) return 1; /* 'match' is better */
1909 return -1; /* 'fi' is better */
1912 /***********************************************************************
1913 * XFONT_CheckFIList
1915 * REMOVE_SUBSETS - attach new fi and purge subsets
1916 * UNMARK_SUBSETS - remove subset flags from all fi entries
1918 static void XFONT_CheckFIList( fontResource* fr, fontInfo* fi, int action)
1920 int i = 0;
1921 fontInfo* pfi, *prev;
1923 for( prev = NULL, pfi = fr->fi; pfi; )
1925 if( action == REMOVE_SUBSETS )
1927 if( pfi->fi_flags & FI_SUBSET )
1929 fontInfo* subset = pfi;
1931 i++;
1932 fr->fi_count--;
1933 if( prev ) prev->next = pfi = pfi->next;
1934 else fr->fi = pfi = pfi->next;
1935 HeapFree( GetProcessHeap(), 0, subset );
1936 continue;
1939 else pfi->fi_flags &= ~FI_SUBSET;
1941 prev = pfi;
1942 pfi = pfi->next;
1945 if( action == REMOVE_SUBSETS ) /* also add the superset */
1947 if( fi->fi_flags & FI_SCALABLE )
1949 fi->next = fr->fi;
1950 fr->fi = fi;
1952 else if( prev ) prev->next = fi; else fr->fi = fi;
1953 fr->fi_count++;
1956 if( i ) TRACE("\t purged %i subsets [%i]\n", i , fr->fi_count);
1959 /***********************************************************************
1960 * XFONT_FindFIList
1962 static fontResource* XFONT_FindFIList( fontResource* pfr, const char* pTypeFace )
1964 while( pfr )
1966 if( !strcasecmp( pfr->lfFaceName, pTypeFace ) ) break;
1967 pfr = pfr->next;
1969 /* Give the app back the font name it asked for. Encarta checks this. */
1970 if (pfr) strcpy(pfr->lfFaceName,pTypeFace);
1971 return pfr;
1974 /***********************************************************************
1975 * XFONT_FixupPointSize
1977 static void XFONT_FixupPointSize(fontInfo* fi)
1979 #define df (fi->df)
1980 df.dfHorizRes = df.dfVertRes = fi->lfd_resolution;
1981 df.dfPoints = (INT16)
1982 (((INT)(df.dfPixHeight - df.dfInternalLeading) * 72 + (df.dfVertRes >> 1)) /
1983 df.dfVertRes );
1984 #undef df
1987 /***********************************************************************
1988 * XFONT_BuildMetrics
1990 * Build font metrics from X font
1992 static int XFONT_BuildMetrics(char** x_pattern, int res, unsigned x_checksum, int x_count)
1994 int i;
1995 fontInfo* fi = NULL;
1996 fontResource* fr, *pfr;
1997 int n_ff = 0;
1999 MESSAGE("Building font metrics. This may take some time...\n");
2000 for( i = 0; i < x_count; i++ )
2002 char* typeface;
2003 LFD* lfd;
2004 int j;
2005 char buffer[MAX_LFD_LENGTH];
2006 char* lpstr;
2007 XFontStruct* x_fs;
2008 fontInfo* pfi;
2010 if (!(typeface = HeapAlloc(GetProcessHeap(), 0, strlen(x_pattern[i])+1))) break;
2011 strcpy( typeface, x_pattern[i] );
2013 lfd = LFD_Parse(typeface);
2014 if (!lfd)
2016 HeapFree(GetProcessHeap(), 0, typeface);
2017 continue;
2020 /* find a family to insert into */
2022 for( pfr = NULL, fr = fontList; fr; fr = fr->next )
2024 if( XFONT_SameFoundryAndFamily(fr->resource, lfd))
2025 break;
2026 pfr = fr;
2029 if( !fi ) fi = (fontInfo*) HeapAlloc(GetProcessHeap(), 0, sizeof(fontInfo));
2031 if( !LFD_InitFontInfo( fi, lfd, x_pattern[i]) )
2032 goto nextfont;
2034 if( !fr ) /* add new family */
2036 n_ff++;
2037 fr = (fontResource*) HeapAlloc(GetProcessHeap(), 0, sizeof(fontResource));
2038 if (fr)
2040 memset(fr, 0, sizeof(fontResource));
2042 fr->resource = (LFD*) HeapAlloc(GetProcessHeap(), 0, sizeof(LFD));
2043 memset(fr->resource, 0, sizeof(LFD));
2045 TRACE("family: -%s-%s-\n", lfd->foundry, lfd->family );
2046 fr->resource->foundry = HeapAlloc(GetProcessHeap(), 0, strlen(lfd->foundry)+1);
2047 strcpy( (char *)fr->resource->foundry, lfd->foundry );
2048 fr->resource->family = HeapAlloc(GetProcessHeap(), 0, strlen(lfd->family)+1);
2049 strcpy( (char *)fr->resource->family, lfd->family );
2050 fr->resource->weight = "";
2052 if( pfr ) pfr->next = fr;
2053 else fontList = fr;
2055 else
2056 WARN("Not enough memory for a new font family\n");
2059 /* check if we already have something better than "fi" */
2061 for( pfi = fr->fi, j = 0; pfi && j <= 0; pfi = pfi->next )
2062 if( (j = XFONT_IsSubset( pfi, fi )) < 0 )
2063 pfi->fi_flags |= FI_SUBSET; /* superseded by "fi" */
2064 if( j > 0 ) goto nextfont;
2066 /* add new font instance "fi" to the "fr" font resource */
2068 if( fi->fi_flags & FI_SCALABLE )
2070 LFD lfd1;
2071 char pxl_string[4], res_string[4];
2072 /* set scalable font height to get an basis for extrapolation */
2074 fi->lfd_height = DEF_SCALABLE_HEIGHT;
2075 fi->lfd_resolution = res;
2077 sprintf(pxl_string, "%d", fi->lfd_height);
2078 sprintf(res_string, "%d", fi->lfd_resolution);
2080 lfd1 = *lfd;
2081 lfd1.pixel_size = pxl_string;
2082 lfd1.point_size = "*";
2083 lfd1.resolution_x = res_string;
2084 lfd1.resolution_y = res_string;
2086 LFD_UnParse(buffer, sizeof buffer, &lfd1);
2088 lpstr = buffer;
2090 else lpstr = x_pattern[i];
2092 if( (x_fs = TSXLoadQueryFont(gdi_display, lpstr)) )
2094 XFONT_SetFontMetric( fi, fr, x_fs );
2095 TSXFreeFont( gdi_display, x_fs );
2097 XFONT_FixupPointSize(fi);
2099 TRACE("\t[% 2ipt] '%s'\n", fi->df.dfPoints, x_pattern[i] );
2101 XFONT_CheckFIList( fr, fi, REMOVE_SUBSETS );
2102 fi = NULL; /* preventing reuse */
2104 else
2106 ERR("failed to load %s\n", lpstr );
2108 XFONT_CheckFIList( fr, fi, UNMARK_SUBSETS );
2110 nextfont:
2111 HeapFree(GetProcessHeap(), 0, lfd);
2112 HeapFree(GetProcessHeap(), 0, typeface);
2114 if( fi ) HeapFree(GetProcessHeap(), 0, fi);
2116 /* Scan through the font list and remove FontResource(s) (fr)
2117 * that have no associated Fontinfo(s) (fi).
2118 * This code is necessary because XFONT_ReadCachedMetrics
2119 * assumes that there is at least one fi associated with a fr.
2120 * This assumption is invalid for TT font
2121 * -altsys-ms outlook-medium-r-normal--0-0-0-0-p-0-microsoft-symbol.
2124 fr = fontList;
2126 while (!fr->fi_count)
2128 fontList = fr->next;
2130 HeapFree(GetProcessHeap(), 0, fr->resource);
2131 HeapFree(GetProcessHeap(), 0, fr);
2133 fr = fontList;
2134 n_ff--;
2137 fr = fontList;
2139 while (fr->next)
2141 if (!fr->next->fi_count)
2143 pfr = fr->next;
2144 fr->next = fr->next->next;
2146 HeapFree(GetProcessHeap(), 0, pfr->resource);
2147 HeapFree(GetProcessHeap(), 0, pfr);
2149 n_ff--;
2151 else
2152 fr = fr->next;
2155 return n_ff;
2158 /***********************************************************************
2159 * XFONT_ReadCachedMetrics
2161 * INIT ONLY
2163 static BOOL XFONT_ReadCachedMetrics( int fd, int res, unsigned x_checksum, int x_count )
2165 if( fd >= 0 )
2167 unsigned u;
2168 int i, j;
2170 /* read checksums */
2171 read( fd, &u, sizeof(unsigned) );
2172 read( fd, &i, sizeof(int) );
2174 if( u == x_checksum && i == x_count )
2176 off_t length, offset = 3 * sizeof(int);
2178 /* read total size */
2179 read( fd, &i, sizeof(int) );
2180 length = lseek( fd, 0, SEEK_END );
2182 if( length == (i + offset) )
2184 lseek( fd, offset, SEEK_SET );
2185 fontList = (fontResource*)HeapAlloc( GetProcessHeap(), 0, i);
2186 if( fontList )
2188 fontResource* pfr = fontList;
2189 fontInfo* pfi = NULL;
2191 TRACE("Reading cached font metrics:\n");
2193 read( fd, fontList, i); /* read all metrics at once */
2194 while( offset < length )
2196 offset += sizeof(fontResource) + sizeof(fontInfo);
2197 pfr->fi = pfi = (fontInfo*)(pfr + 1);
2198 j = 1;
2199 while( TRUE )
2201 if( offset > length ||
2202 pfi->cptable >= (UINT16)X11DRV_CPTABLE_COUNT ||
2203 (int)(pfi->next) != j++ )
2205 TRACE("error: offset=%ld length=%ld cptable=%d pfi->next=%d j=%d\n",(long)offset,(long)length,pfi->cptable,(int)pfi->next,j-1);
2206 goto fail;
2209 if( pfi->df.dfPixHeight == 0 )
2211 TRACE("error: dfPixHeight==0\n");
2212 goto fail;
2215 pfi->df.dfFace = pfr->lfFaceName;
2216 if( pfi->fi_flags & FI_SCALABLE )
2218 /* we can pretend we got this font for any resolution */
2219 pfi->lfd_resolution = res;
2220 XFONT_FixupPointSize(pfi);
2222 pfi->next = pfi + 1;
2224 if( j > pfr->fi_count ) break;
2226 pfi = pfi->next;
2227 offset += sizeof(fontInfo);
2229 pfi->next = NULL;
2230 if( pfr->next )
2232 pfr->next = (fontResource*)(pfi + 1);
2233 pfr = pfr->next;
2235 else break;
2237 if( pfr->next == NULL &&
2238 *(int*)(pfi + 1) == X_FMC_MAGIC )
2240 /* read LFD stubs */
2241 char* lpch = (char*)((int*)(pfi + 1) + 1);
2242 offset += sizeof(int);
2243 for( pfr = fontList; pfr; pfr = pfr->next )
2245 size_t len = strlen(lpch) + 1;
2246 TRACE("\t%s, %i instances\n", lpch, pfr->fi_count );
2247 pfr->resource = LFD_Parse(lpch);
2248 lpch += len;
2249 offset += len;
2250 if (offset > length)
2252 TRACE("error: offset=%ld length=%ld\n",(long)offset,(long)length);
2253 goto fail;
2256 close( fd );
2257 return TRUE;
2260 } else {
2261 TRACE("Wrong length: %ld!=%ld\n",(long)length,(long)(i+offset));
2263 } else {
2264 TRACE("Checksum (%x vs. %x) or count (%d vs. %d) mismatch\n",
2265 u,x_checksum,i,x_count);
2267 fail:
2268 if( fontList ) HeapFree( GetProcessHeap(), 0, fontList );
2269 fontList = NULL;
2270 close( fd );
2272 return FALSE;
2275 /***********************************************************************
2276 * XFONT_WriteCachedMetrics
2278 * INIT ONLY
2280 static BOOL XFONT_WriteCachedMetrics( int fd, unsigned x_checksum, int x_count, int n_ff )
2282 fontResource* pfr;
2283 fontInfo* pfi;
2285 if( fd >= 0 )
2287 int i, j, k;
2288 char buffer[MAX_LFD_LENGTH];
2290 /* font metrics file:
2292 * +0000 x_checksum
2293 * +0004 x_count
2294 * +0008 total size to load
2295 * +000C prepackaged font metrics
2296 * ...
2297 * +...x X_FMC_MAGIC
2298 * +...x + 4 LFD stubs
2301 write( fd, &x_checksum, sizeof(unsigned) );
2302 write( fd, &x_count, sizeof(int) );
2304 for( j = i = 0, pfr = fontList; pfr; pfr = pfr->next )
2306 LFD_UnParse(buffer, sizeof buffer, pfr->resource);
2307 i += strlen( buffer) + 1;
2308 j += pfr->fi_count;
2310 i += n_ff * sizeof(fontResource) + j * sizeof(fontInfo) + sizeof(int);
2311 write( fd, &i, sizeof(int) );
2313 TRACE("Writing font cache:\n");
2315 for( pfr = fontList; pfr; pfr = pfr->next )
2317 fontInfo fi;
2319 TRACE("\t-%s-%s-, %i instances\n", pfr->resource->foundry, pfr->resource->family, pfr->fi_count );
2321 i = write( fd, pfr, sizeof(fontResource) );
2322 if( i == sizeof(fontResource) )
2324 for( k = 1, pfi = pfr->fi; pfi; pfi = pfi->next )
2326 fi = *pfi;
2328 fi.df.dfFace = NULL;
2329 fi.next = (fontInfo*)k; /* loader checks this */
2331 j = write( fd, &fi, sizeof(fi) );
2332 k++;
2334 if( j == sizeof(fontInfo) ) continue;
2336 break;
2338 if( i == sizeof(fontResource) && j == sizeof(fontInfo) )
2340 i = j = X_FMC_MAGIC;
2341 write( fd, &i, sizeof(int) );
2342 for( pfr = fontList; pfr && i == j; pfr = pfr->next )
2344 LFD_UnParse(buffer, sizeof buffer, pfr->resource);
2345 i = strlen( buffer ) + 1;
2346 j = write( fd, buffer, i );
2349 close( fd );
2350 return ( i == j );
2352 return FALSE;
2355 /***********************************************************************
2356 * XFONT_GetPointResolution()
2358 * INIT ONLY
2360 * Here we initialize DefResolution which is used in the
2361 * XFONT_Match() penalty function. We also load the point
2362 * resolution value (higher values result in larger fonts).
2364 static int XFONT_GetPointResolution( int *log_pixels_x, int *log_pixels_y )
2366 int i, j, point_resolution, num = 3;
2367 int allowed_xfont_resolutions[3] = { 72, 75, 100 };
2368 int best = 0, best_diff = 65536;
2369 HKEY hkey;
2371 point_resolution = 0;
2373 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
2375 char buffer[20];
2376 DWORD type, count = sizeof(buffer);
2377 if(!RegQueryValueExA(hkey, INIResolution, 0, &type, buffer, &count))
2378 point_resolution = atoi(buffer);
2379 RegCloseKey(hkey);
2382 if( !point_resolution )
2383 point_resolution = *log_pixels_y;
2384 else
2385 *log_pixels_x = *log_pixels_y = point_resolution;
2388 /* FIXME We can only really guess at a best DefResolution
2389 * - this should be configurable
2391 for( i = best = 0; i < num; i++ )
2393 j = abs( point_resolution - allowed_xfont_resolutions[i] );
2394 if( j < best_diff )
2396 best = i;
2397 best_diff = j;
2400 DefResolution = allowed_xfont_resolutions[best];
2401 return point_resolution;
2405 /***********************************************************************
2406 * XFONT_Match
2408 * Compute the matching score between the logical font and the device font.
2410 * contributions from highest to lowest:
2411 * charset
2412 * fixed pitch
2413 * height
2414 * family flags (only when the facename is not present)
2415 * width
2416 * weight, italics, underlines, strikeouts
2418 * NOTE: you can experiment with different penalty weights to see what happens.
2419 * http://premium.microsoft.com/msdn/library/techart/f365/f36b/f37b/d38b/sa8bf.htm
2421 static UINT XFONT_Match( fontMatch* pfm )
2423 fontInfo* pfi = pfm->pfi; /* device font to match */
2424 LPLOGFONT16 plf = pfm->plf; /* wanted logical font */
2425 UINT penalty = 0;
2426 BOOL bR6 = pfm->flags & FO_MATCH_XYINDEP; /* from text_caps */
2427 BOOL bScale = pfi->fi_flags & FI_SCALABLE;
2428 int d = 0, height;
2430 TRACE("\t[ %-2ipt h=%-3i w=%-3i %s%s]\n", pfi->df.dfPoints,
2431 pfi->df.dfPixHeight, pfi->df.dfAvgWidth,
2432 (pfi->df.dfWeight > FW_NORMAL) ? "Bold " : "Normal ",
2433 (pfi->df.dfItalic) ? "Italic" : "" );
2435 pfm->flags &= FO_MATCH_MASK;
2437 /* Charset */
2438 /* pfm->internal_charset: given(required) charset */
2439 /* pfi->internal_charset: charset of this font */
2440 if (pfi->internal_charset == DEFAULT_CHARSET)
2442 /* special case(unicode font) */
2443 /* priority: unmatched charset < unicode < matched charset */
2444 penalty += 0x50;
2446 else
2448 if( pfm->internal_charset == DEFAULT_CHARSET )
2451 if (pfi->internal_charset != ANSI_CHARSET)
2452 penalty += 0x200;
2454 if ( pfi->codepage != GetACP() )
2455 penalty += 0x200;
2457 else if (pfm->internal_charset != pfi->internal_charset)
2459 if ( pfi->internal_charset & 0xff00 )
2460 penalty += 0x1000; /* internal charset - should not be used */
2461 else
2462 penalty += 0x200;
2466 /* Height */
2467 height = -1;
2469 if( plf->lfHeight > 0 )
2471 int h = pfi->df.dfPixHeight;
2472 d = h - plf->lfHeight;
2473 height = plf->lfHeight;
2475 else
2477 int h = pfi->df.dfPixHeight - pfi->df.dfInternalLeading;
2478 if (h)
2480 d = h + plf->lfHeight;
2481 height = (-plf->lfHeight * pfi->df.dfPixHeight) / h;
2483 else
2485 ERR("PixHeight == InternalLeading\n");
2486 penalty += 0x1000; /* dont want this */
2491 if( height == 0 )
2492 pfm->height = 1; /* Very small */
2493 else if( d )
2495 if( bScale )
2496 pfm->height = height;
2497 else if( (plf->lfQuality != PROOF_QUALITY) && bR6 )
2499 if( d > 0 ) /* do not shrink raster fonts */
2501 pfm->height = pfi->df.dfPixHeight;
2502 penalty += (pfi->df.dfPixHeight - height) * 0x4;
2504 else /* expand only in integer multiples */
2506 pfm->height = height - height%pfi->df.dfPixHeight;
2507 penalty += (height - pfm->height + 1) * height / pfi->df.dfPixHeight;
2510 else /* can't be scaled at all */
2512 if( plf->lfQuality != PROOF_QUALITY) pfm->flags |= FO_SYNTH_HEIGHT;
2513 pfm->height = pfi->df.dfPixHeight;
2514 penalty += (d > 0)? d * 0x8 : -d * 0x10;
2517 else
2518 pfm->height = pfi->df.dfPixHeight;
2520 /* Pitch and Family */
2521 if( pfm->flags & FO_MATCH_PAF ) {
2522 int family = plf->lfPitchAndFamily & FF_FAMILY;
2524 /* TMPF_FIXED_PITCH means exactly the opposite */
2525 if( plf->lfPitchAndFamily & FIXED_PITCH ) {
2526 if( pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH ) penalty += 0x100;
2527 } else /* Variable is the default */
2528 if( !(pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH) ) penalty += 0x2;
2530 if (family != FF_DONTCARE && family != (pfi->df.dfPitchAndFamily & FF_FAMILY) )
2531 penalty += 0x10;
2534 /* Width */
2535 if( plf->lfWidth )
2537 int h;
2538 if( bR6 || bScale ) h = 0;
2539 else
2541 /* FIXME: not complete */
2543 pfm->flags |= FO_SYNTH_WIDTH;
2544 h = abs(plf->lfWidth - (pfm->height * pfi->df.dfAvgWidth)/pfi->df.dfPixHeight);
2546 penalty += h * ( d ) ? 0x2 : 0x1 ;
2548 else if( !(pfi->fi_flags & FI_NORMAL) ) penalty++;
2550 /* Weight */
2551 if( plf->lfWeight != FW_DONTCARE )
2553 penalty += abs(plf->lfWeight - pfi->df.dfWeight) / 40;
2554 if( plf->lfWeight > pfi->df.dfWeight ) pfm->flags |= FO_SYNTH_BOLD;
2555 } else if( pfi->df.dfWeight >= FW_BOLD ) penalty++; /* choose normal by default */
2557 /* Italic */
2558 if( plf->lfItalic != pfi->df.dfItalic )
2560 penalty += 0x4;
2561 pfm->flags |= FO_SYNTH_ITALIC;
2563 /* Underline */
2564 if( plf->lfUnderline ) pfm->flags |= FO_SYNTH_UNDERLINE;
2566 /* Strikeout */
2567 if( plf->lfStrikeOut ) pfm->flags |= FO_SYNTH_STRIKEOUT;
2570 if( penalty && !bScale && pfi->lfd_resolution != DefResolution )
2571 penalty++;
2573 TRACE(" returning %i\n", penalty );
2575 return penalty;
2578 /***********************************************************************
2579 * XFONT_MatchFIList
2581 * Scan a particular font resource for the best match.
2583 static UINT XFONT_MatchFIList( fontMatch* pfm )
2585 BOOL skipRaster = (pfm->flags & FO_MATCH_NORASTER);
2586 UINT current_score, score = (UINT)(-1);
2587 fontMatch fm = *pfm;
2589 for( fm.pfi = pfm->pfr->fi; fm.pfi && score; fm.pfi = fm.pfi->next)
2591 if( skipRaster && !(fm.pfi->fi_flags & FI_SCALABLE) )
2592 continue;
2594 current_score = XFONT_Match( &fm );
2595 if( score > current_score )
2597 *pfm = fm;
2598 score = current_score;
2601 return score;
2604 /***********************************************************************
2605 * XFONT_is_ansi_charset
2607 * returns TRUE if the given charset is ANSI_CHARSET.
2609 static BOOL XFONT_is_ansi_charset( UINT charset )
2611 return ((charset == ANSI_CHARSET) ||
2612 (charset == DEFAULT_CHARSET && GetACP() == 1252));
2615 /***********************************************************************
2616 * XFONT_MatchDeviceFont
2618 * Scan font resource tree.
2621 static void XFONT_MatchDeviceFont( fontResource* start, fontMatch* pfm)
2623 fontMatch fm = *pfm;
2624 UINT current_score, score = (UINT)(-1);
2625 fontResource** ppfr;
2627 TRACE("(%u) '%s' h=%i weight=%i %s\n",
2628 pfm->plf->lfCharSet, pfm->plf->lfFaceName, pfm->plf->lfHeight,
2629 pfm->plf->lfWeight, (pfm->plf->lfItalic) ? "Italic" : "" );
2631 pfm->pfi = NULL;
2633 /* the following hard-coded font binding assumes 'ANSI_CHARSET'. */
2634 if( !fm.plf->lfFaceName[0] &&
2635 XFONT_is_ansi_charset(fm.plf->lfCharSet) )
2637 switch(fm.plf->lfPitchAndFamily & 0xf0)
2639 case FF_MODERN:
2640 strcpy(fm.plf->lfFaceName, "Courier New");
2641 break;
2642 case FF_ROMAN:
2643 strcpy(fm.plf->lfFaceName, "Times New Roman");
2644 break;
2645 case FF_SWISS:
2646 strcpy(fm.plf->lfFaceName, "Arial");
2647 break;
2648 default:
2649 if((fm.plf->lfPitchAndFamily & 0x0f) == FIXED_PITCH)
2650 strcpy(fm.plf->lfFaceName, "Courier New");
2651 else
2652 strcpy(fm.plf->lfFaceName, "Arial");
2653 break;
2657 if( fm.plf->lfFaceName[0] )
2659 fm.pfr = XFONT_FindFIList( start, fm.plf->lfFaceName);
2660 if( fm.pfr ) /* match family */
2662 TRACE("found facename '%s'\n", fm.pfr->lfFaceName );
2664 if( fm.pfr->fr_flags & FR_REMOVED )
2665 fm.pfr = 0;
2666 else
2668 XFONT_MatchFIList( &fm );
2669 *pfm = fm;
2670 if (pfm->pfi)
2671 return;
2675 /* get charset if lfFaceName is one of known facenames. */
2677 const struct CharsetBindingInfo* pcharsetbindings;
2679 pcharsetbindings = &charsetbindings[0];
2680 while ( pcharsetbindings->pszFaceName != NULL )
2682 if ( !strcmp( pcharsetbindings->pszFaceName,
2683 fm.plf->lfFaceName ) )
2685 fm.internal_charset = pcharsetbindings->charset;
2686 break;
2688 pcharsetbindings ++;
2690 TRACE( "%s charset %u\n", fm.plf->lfFaceName, fm.internal_charset );
2694 /* match all available fonts */
2696 fm.flags |= FO_MATCH_PAF;
2697 for( ppfr = &fontList; *ppfr && score; ppfr = &(*ppfr)->next )
2699 if( (*ppfr)->fr_flags & FR_REMOVED )
2701 if( (*ppfr)->fo_count == 0 )
2702 XFONT_RemoveFontResource( ppfr );
2703 continue;
2706 fm.pfr = *ppfr;
2708 TRACE("%s\n", fm.pfr->lfFaceName );
2710 current_score = XFONT_MatchFIList( &fm );
2711 if( current_score < score )
2713 score = current_score;
2714 *pfm = fm;
2720 /***********************************************************************
2721 * X Font Cache
2723 static void XFONT_GrowFreeList(int start, int end)
2725 /* add all entries from 'start' up to and including 'end' */
2727 memset( fontCache + start, 0, (end - start + 1) * sizeof(fontObject) );
2729 fontCache[end].lru = fontLF;
2730 fontCache[end].count = -1;
2731 fontLF = start;
2732 while( start < end )
2734 fontCache[start].count = -1;
2735 fontCache[start].lru = start + 1;
2736 start++;
2740 static fontObject* XFONT_LookupCachedFont( const LPLOGFONT16 plf, UINT16* checksum )
2742 UINT16 cs = __lfCheckSum( plf );
2743 int i = fontMRU, prev = -1;
2745 *checksum = cs;
2746 while( i >= 0 )
2748 if( fontCache[i].lfchecksum == cs &&
2749 !(fontCache[i].fo_flags & FO_REMOVED) )
2751 /* FIXME: something more intelligent here ? */
2753 if( !memcmp( plf, &fontCache[i].lf,
2754 sizeof(LOGFONT16) - LF_FACESIZE ) &&
2755 !strcmp( plf->lfFaceName, fontCache[i].lf.lfFaceName) )
2757 /* remove temporarily from the lru list */
2758 if( prev >= 0 )
2759 fontCache[prev].lru = fontCache[i].lru;
2760 else
2761 fontMRU = (INT16)fontCache[i].lru;
2762 return (fontCache + i);
2765 prev = i;
2766 i = (INT16)fontCache[i].lru;
2768 return NULL;
2771 static fontObject* XFONT_GetCacheEntry(void)
2773 int i;
2775 if( fontLF == -1 )
2777 int prev_i, prev_j, j;
2779 TRACE("font cache is full\n");
2781 /* lookup the least recently used font */
2783 for( prev_i = prev_j = j = -1, i = fontMRU; i >= 0; i = (INT16)fontCache[i].lru )
2785 if( fontCache[i].count <= 0 &&
2786 !(fontCache[i].fo_flags & FO_SYSTEM) )
2788 prev_j = prev_i;
2789 j = i;
2791 prev_i = i;
2794 if( j >= 0 ) /* unload font */
2796 /* detach from the lru list */
2798 TRACE("\tfreeing entry %i\n", j );
2800 fontCache[j].fr->fo_count--;
2802 if( prev_j >= 0 )
2803 fontCache[prev_j].lru = fontCache[j].lru;
2804 else fontMRU = (INT16)fontCache[j].lru;
2806 /* FIXME: lpXForm, lpPixmap */
2807 if(fontCache[j].lpX11Trans)
2808 HeapFree( GetProcessHeap(), 0, fontCache[j].lpX11Trans );
2810 TSXFreeFont( gdi_display, fontCache[j].fs );
2812 memset( fontCache + j, 0, sizeof(fontObject) );
2813 return (fontCache + j);
2815 else /* expand cache */
2817 fontObject* newCache;
2819 prev_i = fontCacheSize + FONTCACHE;
2821 TRACE("\tgrowing font cache from %i to %i\n", fontCacheSize, prev_i );
2823 if( (newCache = (fontObject*)HeapReAlloc(GetProcessHeap(), 0,
2824 fontCache, prev_i)) )
2826 i = fontCacheSize;
2827 fontCacheSize = prev_i;
2828 fontCache = newCache;
2829 XFONT_GrowFreeList( i, fontCacheSize - 1);
2831 else return NULL;
2835 /* detach from the free list */
2837 i = fontLF;
2838 fontLF = (INT16)fontCache[i].lru;
2839 fontCache[i].count = 0;
2840 return (fontCache + i);
2843 static int XFONT_ReleaseCacheEntry(const fontObject* pfo)
2845 UINT u = (UINT)(pfo - fontCache);
2846 int i;
2847 int ret;
2849 if( u < fontCacheSize )
2851 ret = --fontCache[u].count;
2852 if ( ret == 0 )
2854 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
2856 if( CHECK_PFONT(pfo->prefobjs[i]) )
2857 XFONT_ReleaseCacheEntry(__PFONT(pfo->prefobjs[i]));
2861 return ret;
2864 return -1;
2867 /***********************************************************************
2868 * X11DRV_FONT_InitX11Metrics
2870 * Initialize font resource list and allocate font cache.
2872 void X11DRV_FONT_InitX11Metrics( void )
2874 char** x_pattern;
2875 unsigned x_checksum;
2876 int i, x_count, fd, buf_size;
2877 char *buffer;
2878 HKEY hkey;
2881 x_pattern = TSXListFonts(gdi_display, "*", MAX_FONTS, &x_count );
2883 TRACE("Font Mapper: initializing %i x11 fonts\n", x_count);
2884 if (x_count == MAX_FONTS)
2885 MESSAGE("There may be more fonts available - try increasing the value of MAX_FONTS\n");
2887 for( i = x_checksum = 0; i < x_count; i++ )
2889 int j;
2890 #if 0
2891 printf("%i\t: %s\n", i, x_pattern[i] );
2892 #endif
2894 j = strlen( x_pattern[i] );
2895 if( j ) x_checksum ^= __genericCheckSum( x_pattern[i], j );
2897 x_checksum |= X_PFONT_MAGIC;
2898 buf_size = 128;
2899 buffer = HeapAlloc( GetProcessHeap(), 0, buf_size );
2901 /* deal with systemwide font metrics cache */
2903 buffer[0] = 0;
2904 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
2906 DWORD type, count = buf_size;
2907 RegQueryValueExA(hkey, INIGlobalMetrics, 0, &type, buffer, &count);
2908 RegCloseKey(hkey);
2911 if( buffer[0] )
2913 fd = open( buffer, O_RDONLY );
2914 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2916 if (fontList == NULL)
2918 /* try per-user */
2919 buffer = XFONT_UserMetricsCache( buffer, &buf_size );
2920 if( buffer[0] )
2922 fd = open( buffer, O_RDONLY );
2923 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2927 if( fontList == NULL ) /* build metrics from scratch */
2929 int n_ff = XFONT_BuildMetrics(x_pattern, DefResolution, x_checksum, x_count);
2930 if( buffer[0] ) /* update cached metrics */
2932 fd = open( buffer, O_CREAT | O_TRUNC | O_RDWR, 0644 ); /* -rw-r--r-- */
2933 if( XFONT_WriteCachedMetrics( fd, x_checksum, x_count, n_ff ) == FALSE )
2935 WARN("Unable to write to fontcache '%s'\n", buffer);
2936 if( fd >= 0) remove( buffer ); /* couldn't write entire file */
2941 TSXFreeFontNames(x_pattern);
2943 /* check if we're dealing with X11 R6 server */
2945 XFontStruct* x_fs;
2946 strcpy(buffer, "-*-*-*-*-normal-*-[12 0 0 12]-*-72-*-*-*-iso8859-1");
2947 if( (x_fs = TSXLoadQueryFont(gdi_display, buffer)) )
2949 text_caps |= TC_SF_X_YINDEP;
2950 TSXFreeFont(gdi_display, x_fs);
2953 HeapFree(GetProcessHeap(), 0, buffer);
2955 XFONT_WindowsNames();
2956 XFONT_LoadAliases();
2957 XFONT_LoadDefaults();
2958 XFONT_LoadIgnores();
2960 /* fontList initialization is over, allocate X font cache */
2962 fontCache = (fontObject*) HeapAlloc(GetProcessHeap(), 0, fontCacheSize * sizeof(fontObject));
2963 XFONT_GrowFreeList(0, fontCacheSize - 1);
2965 TRACE("done!\n");
2967 /* update text caps parameter */
2969 RAW_ASCENT = TSXInternAtom(gdi_display, "RAW_ASCENT", TRUE);
2970 RAW_DESCENT = TSXInternAtom(gdi_display, "RAW_DESCENT", TRUE);
2971 return;
2974 /***********************************************************************
2975 * X11DRV_FONT_Init
2977 void X11DRV_FONT_Init( int *log_pixels_x, int *log_pixels_y )
2979 XFONT_GetPointResolution( log_pixels_x, log_pixels_y );
2981 if(X11DRV_XRender_Installed)
2982 text_caps |= TC_VA_ABLE;
2984 return;
2987 /**********************************************************************
2988 * XFONT_SetX11Trans
2990 static BOOL XFONT_SetX11Trans( fontObject *pfo )
2992 char *fontName;
2993 Atom nameAtom;
2994 LFD* lfd;
2996 TSXGetFontProperty( pfo->fs, XA_FONT, &nameAtom );
2997 fontName = TSXGetAtomName( gdi_display, nameAtom );
2998 lfd = LFD_Parse(fontName);
2999 if (!lfd)
3001 TSXFree(fontName);
3002 return FALSE;
3005 if (lfd->pixel_size[0] != '[') {
3006 HeapFree(GetProcessHeap(), 0, lfd);
3007 TSXFree(fontName);
3008 return FALSE;
3011 #define PX pfo->lpX11Trans
3013 sscanf(lfd->pixel_size, "[%f%f%f%f]", &PX->a, &PX->b, &PX->c, &PX->d);
3014 TSXFree(fontName);
3015 HeapFree(GetProcessHeap(), 0, lfd);
3017 TSXGetFontProperty( pfo->fs, RAW_ASCENT, &PX->RAW_ASCENT );
3018 TSXGetFontProperty( pfo->fs, RAW_DESCENT, &PX->RAW_DESCENT );
3020 PX->pixelsize = hypot(PX->a, PX->b);
3021 PX->ascent = PX->pixelsize / 1000.0 * PX->RAW_ASCENT;
3022 PX->descent = PX->pixelsize / 1000.0 * PX->RAW_DESCENT;
3024 TRACE("[%f %f %f %f] RA = %ld RD = %ld\n",
3025 PX->a, PX->b, PX->c, PX->d,
3026 PX->RAW_ASCENT, PX->RAW_DESCENT);
3028 #undef PX
3029 return TRUE;
3032 /***********************************************************************
3033 * X Device Font Objects
3035 static X_PHYSFONT XFONT_RealizeFont( const LPLOGFONT16 plf,
3036 LPCSTR* faceMatched, BOOL bSubFont,
3037 WORD internal_charset,
3038 WORD* pcharsetMatched )
3040 UINT16 checksum;
3041 INT index = 0;
3042 fontObject* pfo;
3044 pfo = XFONT_LookupCachedFont( plf, &checksum );
3045 if( !pfo )
3047 fontMatch fm;
3048 INT i;
3050 fm.pfr = NULL;
3051 fm.pfi = NULL;
3052 fm.height = 0;
3053 fm.flags = 0;
3054 fm.plf = plf;
3055 fm.internal_charset = internal_charset;
3057 if( text_caps & TC_SF_X_YINDEP ) fm.flags = FO_MATCH_XYINDEP;
3059 /* allocate new font cache entry */
3061 if( (pfo = XFONT_GetCacheEntry()) )
3063 /* initialize entry and load font */
3064 char lpLFD[MAX_LFD_LENGTH];
3065 UINT uRelaxLevel = 0;
3067 if(abs(plf->lfHeight) > MAX_FONT_SIZE) {
3068 ERR(
3069 "plf->lfHeight = %d, Creating a 100 pixel font and rescaling metrics \n",
3070 plf->lfHeight);
3071 pfo->rescale = fabs(plf->lfHeight / 100.0);
3072 if(plf->lfHeight > 0) plf->lfHeight = 100;
3073 else plf->lfHeight = -100;
3074 } else
3075 pfo->rescale = 1.0;
3077 XFONT_MatchDeviceFont( fontList, &fm );
3078 pfo->fr = fm.pfr;
3079 pfo->fi = fm.pfi;
3080 pfo->fr->fo_count++;
3081 pfo->fo_flags = fm.flags & ~FO_MATCH_MASK;
3083 pfo->lf = *plf;
3084 pfo->lfchecksum = checksum;
3088 LFD_ComposeLFD( pfo, fm.height, lpLFD, uRelaxLevel++ );
3089 if( (pfo->fs = TSXLoadQueryFont( gdi_display, lpLFD )) ) break;
3090 } while( uRelaxLevel );
3093 if(pfo->lf.lfEscapement != 0) {
3094 pfo->lpX11Trans = HeapAlloc(GetProcessHeap(), 0, sizeof(XFONTTRANS));
3095 if(!XFONT_SetX11Trans( pfo )) {
3096 HeapFree(GetProcessHeap(), 0, pfo->lpX11Trans);
3097 pfo->lpX11Trans = NULL;
3100 XFONT_GetLeading( &pfo->fi->df, pfo->fs,
3101 &pfo->foInternalLeading, NULL, pfo->lpX11Trans );
3102 pfo->foAvgCharWidth = (INT16)XFONT_GetAvgCharWidth(&pfo->fi->df, pfo->fs, pfo->lpX11Trans );
3103 pfo->foMaxCharWidth = (INT16)XFONT_GetMaxCharWidth(pfo->fs, pfo->lpX11Trans);
3105 /* FIXME: If we've got a soft font or
3106 * there are FO_SYNTH_... flags for the
3107 * non PROOF_QUALITY request, the engine
3108 * should rasterize characters into mono
3109 * pixmaps and store them in the pfo->lpPixmap
3110 * array (pfo->fs should be updated as well).
3111 * array (pfo->fs should be updated as well).
3112 * X11DRV_ExtTextOut() must be heavily modified
3113 * to support pixmap blitting and FO_SYNTH_...
3114 * styles.
3117 pfo->lpPixmap = NULL;
3119 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3120 pfo->prefobjs[i] = (X_PHYSFONT)0xffffffff; /* invalid value */
3122 /* special treatment for DBCS that needs multiple fonts */
3123 /* All member of pfo must be set correctly. */
3124 if ( bSubFont == FALSE )
3126 WORD charset_sub;
3127 WORD charsetMatchedSub;
3128 LOGFONT16 lfSub;
3129 LPCSTR faceMatchedSub;
3131 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3133 charset_sub = X11DRV_cptable[pfo->fi->cptable].
3134 penum_subfont_charset( i );
3135 if ( charset_sub == DEFAULT_CHARSET ) break;
3137 lfSub = *plf;
3138 lfSub.lfWidth = 0;
3139 lfSub.lfHeight=plf->lfHeight;
3140 lfSub.lfCharSet = (BYTE)(charset_sub & 0xff);
3141 lfSub.lfFaceName[0] = '\0'; /* FIXME? */
3142 /* this font has sub font */
3143 if ( i == 0 ) pfo->prefobjs[0] = (X_PHYSFONT)0;
3144 pfo->prefobjs[i] =
3145 XFONT_RealizeFont( &lfSub, &faceMatchedSub,
3146 TRUE, charset_sub,
3147 &charsetMatchedSub );
3148 /* FIXME: check charsetMatchedSub */
3153 if( !pfo ) /* couldn't get a new entry, get one of the cached fonts */
3155 UINT current_score, score = (UINT)(-1);
3157 i = index = fontMRU;
3158 fm.flags |= FO_MATCH_PAF;
3161 pfo = fontCache + i;
3162 fm.pfr = pfo->fr; fm.pfi = pfo->fi;
3164 current_score = XFONT_Match( &fm );
3165 if( current_score < score ) index = i;
3167 i = pfo->lru;
3168 } while( i >= 0 );
3169 pfo = fontCache + index;
3170 goto END;
3174 /* attach at the head of the lru list */
3175 pfo->lru = fontMRU;
3176 index = fontMRU = (pfo - fontCache);
3178 END:
3179 pfo->count++;
3181 TRACE("physfont %i\n", index);
3182 *faceMatched = pfo->fi->df.dfFace;
3183 *pcharsetMatched = pfo->fi->internal_charset;
3185 return (X_PHYSFONT)(X_PFONT_MAGIC | index);
3188 /***********************************************************************
3189 * XFONT_GetFontObject
3191 fontObject* XFONT_GetFontObject( X_PHYSFONT pFont )
3193 if( CHECK_PFONT(pFont) ) return __PFONT(pFont);
3194 return NULL;
3197 /***********************************************************************
3198 * XFONT_GetFontStruct
3200 XFontStruct* XFONT_GetFontStruct( X_PHYSFONT pFont )
3202 if( CHECK_PFONT(pFont) ) return __PFONT(pFont)->fs;
3203 return NULL;
3206 /***********************************************************************
3207 * XFONT_GetFontInfo
3209 LPIFONTINFO16 XFONT_GetFontInfo( X_PHYSFONT pFont )
3211 if( CHECK_PFONT(pFont) ) return &(__PFONT(pFont)->fi->df);
3212 return NULL;
3217 /* X11DRV Interface ****************************************************
3219 * Exposed via the dc->funcs dispatch table. *
3221 ***********************************************************************/
3222 /***********************************************************************
3223 * SelectFont (X11DRV.@)
3225 HFONT X11DRV_SelectFont( X11DRV_PDEVICE *physDev, HFONT hfont )
3227 LOGFONTW logfont;
3228 LOGFONT16 lf;
3229 DC *dc = physDev->dc;
3231 TRACE("dc=%p, hfont=%04x\n", dc, hfont);
3233 if (!GetObjectW( hfont, sizeof(logfont), &logfont )) return GDI_ERROR;
3235 TRACE("dc->gdiFont = %p\n", dc->gdiFont);
3237 if(dc->gdiFont && X11DRV_XRender_Installed) {
3238 X11DRV_XRender_SelectFont(physDev, hfont);
3239 return FALSE;
3242 EnterCriticalSection( &crtsc_fonts_X11 );
3244 if(fontList == NULL) X11DRV_FONT_InitX11Metrics();
3246 if( CHECK_PFONT(physDev->font) )
3247 XFONT_ReleaseCacheEntry( __PFONT(physDev->font) );
3249 FONT_LogFontWTo16(&logfont, &lf);
3251 /* stock fonts ignore the mapping mode */
3252 if (!is_stock_font( hfont ))
3254 /* Make sure we don't change the sign when converting to device coords */
3255 /* FIXME - check that the other drivers do this correctly */
3256 if (lf.lfWidth)
3258 lf.lfWidth = GDI_ROUND((FLOAT)lf.lfWidth * fabs(dc->xformWorld2Vport.eM11));
3259 if (lf.lfWidth == 0)
3260 lf.lfWidth = 1; /* Minimum width */
3262 if (lf.lfHeight)
3264 lf.lfHeight = GDI_ROUND((FLOAT)lf.lfHeight * fabs(dc->xformWorld2Vport.eM22));
3266 if (lf.lfHeight == 0)
3267 lf.lfHeight = MIN_FONT_SIZE;
3271 if (!lf.lfHeight)
3272 lf.lfHeight = -(DEF_POINT_SIZE * GetDeviceCaps(dc->hSelf,LOGPIXELSY) + (72>>1)) / 72;
3275 /* Fixup aliases before passing to RealizeFont */
3276 /* alias = Windows name in the alias table */
3277 LPCSTR alias = XFONT_UnAlias( lf.lfFaceName );
3278 LPCSTR faceMatched;
3279 WORD charsetMatched;
3281 TRACE("hfont=%04x\n", hfont); /* to connect with the trace from RealizeFont */
3282 physDev->font = XFONT_RealizeFont( &lf, &faceMatched,
3283 FALSE, lf.lfCharSet,
3284 &charsetMatched );
3286 /* set face to the requested facename if it matched
3287 * so that GetTextFace can get the correct face name
3289 if (alias && !strcmp(faceMatched, lf.lfFaceName))
3290 MultiByteToWideChar(CP_ACP, 0, alias, -1,
3291 logfont.lfFaceName, LF_FACESIZE);
3292 else
3293 MultiByteToWideChar(CP_ACP, 0, faceMatched, -1,
3294 logfont.lfFaceName, LF_FACESIZE);
3297 * In X, some encodings may have the same lfFaceName.
3298 * for example:
3299 * -misc-fixed-*-iso8859-1
3300 * -misc-fixed-*-jisx0208.1990-0
3301 * so charset should be saved...
3303 logfont.lfCharSet = charsetMatched;
3306 LeaveCriticalSection( &crtsc_fonts_X11 );
3308 return TRUE; /* Use a device font */
3312 /***********************************************************************
3314 * X11DRV_EnumDeviceFonts
3316 BOOL X11DRV_EnumDeviceFonts( HDC hdc, LPLOGFONTW plf,
3317 DEVICEFONTENUMPROC proc, LPARAM lp )
3319 ENUMLOGFONTEXW lf;
3320 NEWTEXTMETRICEXW tm;
3321 fontResource* pfr = fontList;
3322 BOOL b, bRet = 0, using_gdi = 0;
3323 LOGFONT16 lf16;
3324 DC *dc;
3326 dc = DC_GetDCPtr(hdc);
3327 if(!dc) return FALSE;
3328 if(dc->gdiFont) using_gdi = TRUE;
3329 GDI_ReleaseObj(hdc);
3331 /* don't enumerate x11 fonts if we're using client side fonts */
3332 if(using_gdi) return FALSE;
3334 FONT_LogFontWTo16(plf, &lf16);
3336 if( lf16.lfFaceName[0] )
3338 /* enum all entries in this resource */
3339 pfr = XFONT_FindFIList( pfr, lf16.lfFaceName );
3340 if( pfr )
3342 fontInfo* pfi;
3343 for( pfi = pfr->fi; pfi; pfi = pfi->next )
3345 /* Note: XFONT_GetFontMetric() will have to
3346 release the crit section, font list will
3347 have to be retraversed on return */
3349 if(lf16.lfCharSet == DEFAULT_CHARSET ||
3350 lf16.lfCharSet == pfi->df.dfCharSet) {
3351 if( (b = (*proc)( &lf, &tm,
3352 XFONT_GetFontMetric( pfi, &lf, &tm ), lp )) )
3353 bRet = b;
3354 else break;
3359 else /* enum first entry in each resource */
3360 for( ; pfr ; pfr = pfr->next )
3362 if(pfr->fi)
3364 if( (b = (*proc)( &lf, &tm,
3365 XFONT_GetFontMetric( pfr->fi, &lf, &tm ), lp )) )
3366 bRet = b;
3367 else break;
3370 return bRet;
3374 /***********************************************************************
3375 * X11DRV_GetTextMetrics
3377 BOOL X11DRV_GetTextMetrics(X11DRV_PDEVICE *physDev, TEXTMETRICW *metrics)
3379 TEXTMETRICA tmA;
3381 if( CHECK_PFONT(physDev->font) )
3383 fontObject* pfo = __PFONT(physDev->font);
3384 X11DRV_cptable[pfo->fi->cptable].pGetTextMetricsA( pfo, &tmA );
3385 FONT_TextMetricAToW(&tmA, metrics);
3386 return TRUE;
3388 return FALSE;
3392 /***********************************************************************
3393 * X11DRV_GetCharWidth
3395 BOOL X11DRV_GetCharWidth( X11DRV_PDEVICE *physDev, UINT firstChar, UINT lastChar,
3396 LPINT buffer )
3398 fontObject* pfo = XFONT_GetFontObject( physDev->font );
3400 if( pfo )
3402 int i;
3404 if (pfo->fs->per_char == NULL)
3405 for (i = firstChar; i <= lastChar; i++)
3406 if(pfo->lpX11Trans)
3407 *buffer++ = pfo->fs->min_bounds.attributes *
3408 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3409 else
3410 *buffer++ = pfo->fs->min_bounds.width * pfo->rescale;
3411 else
3413 XCharStruct *cs, *def;
3414 static XCharStruct __null_char = { 0, 0, 0, 0, 0, 0 };
3416 CI_GET_CHAR_INFO(pfo->fs, pfo->fs->default_char, &__null_char,
3417 def);
3419 for (i = firstChar; i <= lastChar; i++)
3421 WCHAR wch = i;
3422 BYTE ch;
3423 UINT ch_f; /* character code in the font encoding */
3424 WideCharToMultiByte( pfo->fi->codepage, 0, &wch, 1, &ch, 1, NULL, NULL );
3425 ch_f = ch;
3426 if (ch_f >= pfo->fs->min_char_or_byte2 &&
3427 ch_f <= pfo->fs->max_char_or_byte2)
3429 cs = &pfo->fs->per_char[(ch_f - pfo->fs->min_char_or_byte2)];
3430 if (CI_NONEXISTCHAR(cs)) cs = def;
3431 } else cs = def;
3432 if(pfo->lpX11Trans)
3433 *buffer++ = max(cs->attributes, 0) *
3434 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3435 else
3436 *buffer++ = max(cs->width, 0 ) * pfo->rescale;
3440 return TRUE;
3442 return FALSE;