Moved server.h to include/wine.
[wine] / graphics / x11drv / xfont.c
1 /*
2  * X11 physical font objects
3  *
4  * Copyright 1997 Alex Korobka
5  *
6  * TODO: Mapping algorithm tweaks, FO_SYNTH_... flags (ExtTextOut() will
7  *       have to be changed for that), dynamic font loading (FreeType).
8  */
9
10 #include "config.h"
11
12 #include <X11/Xatom.h>
13
14 #include "ts_xlib.h"
15
16 #include <ctype.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <sys/types.h>
22 #include <fcntl.h>
23 #include <math.h>
24
25 #include "windef.h"
26 #include "wingdi.h"
27 #include "winnls.h"
28 #include "winreg.h"
29 #include "heap.h"
30 #include "font.h"
31 #include "debugtools.h"
32 #include "user.h" /* for TWEAK_WineLook (FIXME) */
33 #include "x11font.h"
34 #include "wine/server.h"
35
36 DEFAULT_DEBUG_CHANNEL(font);
37
38 #define X_PFONT_MAGIC           (0xFADE0000)
39 #define X_FMC_MAGIC             (0x0000CAFE)
40
41 #define MAX_FONTS               1024*16
42 #define MAX_LFD_LENGTH          256
43 #define TILDE                   '~'
44 #define HYPHEN                  '-'
45
46 #define DEF_POINT_SIZE          8      /* CreateFont(0 .. ) gets this */
47 #define DEF_SCALABLE_HEIGHT     100    /* pixels */
48 #define MIN_FONT_SIZE           2      /* Min size in pixels */
49 #define MAX_FONT_SIZE           1000   /* Max size in pixels */
50
51 #define REMOVE_SUBSETS          1
52 #define UNMARK_SUBSETS          0
53
54
55 #define FF_FAMILY       (FF_MODERN | FF_SWISS | FF_ROMAN | FF_DECORATIVE | FF_SCRIPT)
56
57 typedef struct __fontAlias
58 {
59   LPSTR                 faTypeFace;
60   LPSTR                 faAlias;
61   struct __fontAlias*   next;
62 } fontAlias;
63
64 static fontAlias *aliasTable = NULL;
65
66 UINT16                  XTextCaps = TC_OP_CHARACTER | TC_OP_STROKE |
67 TC_CP_STROKE | TC_CR_ANY |
68                                     TC_SA_DOUBLE | TC_SA_INTEGER | TC_SA_CONTIN |
69                                     TC_UA_ABLE | TC_SO_ABLE | TC_RA_ABLE;
70
71                         /* X11R6 adds TC_SF_X_YINDEP, maybe more... */
72
73 static const char*      INIFontMetrics = "/cachedmetrics.";
74 static const char*      INIFontSection = "Software\\Wine\\Wine\\Config\\fonts";
75 static const char*      INIAliasSection = "Alias";
76 static const char*      INIIgnoreSection = "Ignore";
77 static const char*      INIDefault = "Default";
78 static const char*      INIDefaultFixed = "DefaultFixed";
79 static const char*      INIResolution = "Resolution";
80 static const char*      INIGlobalMetrics = "FontMetrics";
81 static const char*      INIDefaultSerif = "DefaultSerif";
82 static const char*      INIDefaultSansSerif = "DefaultSansSerif";
83
84
85 /* FIXME - are there any more Latin charsets ? */
86 /* FIXME - RUSSIAN, ARABIC, GREEK, HEBREW are NOT Latin */
87 #define IS_LATIN_CHARSET(ch) \
88   ((ch)==ANSI_CHARSET ||\
89    (ch)==EE_CHARSET ||\
90    (ch)==ISO3_CHARSET ||\
91    (ch)==ISO4_CHARSET ||\
92    (ch)==RUSSIAN_CHARSET ||\
93    (ch)==ARABIC_CHARSET ||\
94    (ch)==GREEK_CHARSET ||\
95    (ch)==HEBREW_CHARSET ||\
96    (ch)==TURKISH_CHARSET ||\
97    (ch)==ISO10_CHARSET ||\
98    (ch)==BALTIC_CHARSET ||\
99    (ch)==CELTIC_CHARSET)
100
101 /* suffix-charset mapping tables - must be less than 254 entries long */
102
103 typedef struct __sufch
104 {
105   LPCSTR        psuffix;
106   WORD          charset; /* hibyte != 0 means *internal* charset */
107   WORD          codepage;
108   WORD          cptable;
109 } SuffixCharset;
110
111 static const SuffixCharset sufch_ansi[] = {
112     {  "0", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
113     { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
114
115 static const SuffixCharset sufch_iso646[] = {
116     { "irv", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
117     { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
118
119 static const SuffixCharset sufch_iso8859[] = {
120     {  "1", ANSI_CHARSET, 28591, X11DRV_CPTABLE_SBCS },
121     {  "2", EE_CHARSET, 28592, X11DRV_CPTABLE_SBCS },
122     {  "3", ISO3_CHARSET, 28593, X11DRV_CPTABLE_SBCS }, 
123     {  "4", ISO4_CHARSET, 28594, X11DRV_CPTABLE_SBCS }, 
124     {  "5", RUSSIAN_CHARSET, 28595, X11DRV_CPTABLE_SBCS },
125     {  "6", ARABIC_CHARSET, 28596, X11DRV_CPTABLE_SBCS },
126     {  "7", GREEK_CHARSET, 28597, X11DRV_CPTABLE_SBCS },
127     {  "8", HEBREW_CHARSET, 28598, X11DRV_CPTABLE_SBCS }, 
128     {  "9", TURKISH_CHARSET, 28599, X11DRV_CPTABLE_SBCS },
129     { "10", ISO10_CHARSET, 28600, X11DRV_CPTABLE_SBCS },
130     { "11", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
131     { "12", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
132     { "13", BALTIC_CHARSET, 28603, X11DRV_CPTABLE_SBCS },
133     { "14", CELTIC_CHARSET, 28604, X11DRV_CPTABLE_SBCS },
134     { "15", ANSI_CHARSET, 28605, X11DRV_CPTABLE_SBCS },
135     { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
136
137 static const SuffixCharset sufch_microsoft[] = {
138     { "cp1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
139     { "cp1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
140     { "cp1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
141     { "cp1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
142     { "cp1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
143     { "cp1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
144     { "cp1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
145     { "cp1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
146     { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
147     { "symbol", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
148     {   NULL,   ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
149
150 static const SuffixCharset sufch_tcvn[] = {
151     {  "0", TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
152     { NULL, TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
153
154 static const SuffixCharset sufch_tis620[] = {
155     {  "0", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
156     { NULL, THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }};
157
158 static const SuffixCharset sufch_viscii[] = {
159     {  "1", VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
160     { NULL, VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
161
162 static const SuffixCharset sufch_windows[] = {
163     { "1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
164     { "1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
165     { "1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
166     { "1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
167     { "1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS }, 
168     { "1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS }, 
169     { "1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
170     { "1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
171     {  NULL,  ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
172
173 static const SuffixCharset sufch_koi8[] = {
174     { "r", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
175     { "ru", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
176     { "u", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
177     { NULL, RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS }};
178
179 static const SuffixCharset sufch_jisx0201[] = {
180     { "0", X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS },
181     { NULL, X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS }};
182
183 static const SuffixCharset sufch_jisx0208[] = {
184     { "0", SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 },
185     { NULL, SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
186
187 static const SuffixCharset sufch_jisx0212[] = {
188     { "0", X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 },
189     { NULL, X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
190
191 static const SuffixCharset sufch_ksc5601[] = {
192     { "0", HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 },
193     { NULL, HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 }};
194
195 static const SuffixCharset sufch_gb2312[] = {
196     { "0", GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 },
197     { NULL, GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 }};
198
199 static const SuffixCharset sufch_big5[] = {
200     { "0", CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 },
201     { NULL, CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 }};
202
203 static const SuffixCharset sufch_unicode[] = {
204     { "0", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
205     { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
206
207 static const SuffixCharset sufch_iso10646[] = {
208     { "1", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
209     { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
210
211 /* Each of these must be matched explicitly */
212 static const SuffixCharset sufch_any[] = {
213     { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
214     { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
215
216
217 typedef struct __fet
218 {
219   LPSTR          prefix;
220   const SuffixCharset* sufch;
221   struct __fet*  next;
222 } fontEncodingTemplate;
223
224 /* Note: we can attach additional encoding mappings to the end
225  *       of this table at runtime.
226  */
227 static fontEncodingTemplate __fETTable[] = {
228                         { "ansi",         sufch_ansi,         &__fETTable[1] },
229                         { "ascii",        sufch_ansi,         &__fETTable[2] },
230                         { "iso646.1991",  sufch_iso646,       &__fETTable[3] },
231                         { "iso8859",      sufch_iso8859,      &__fETTable[4] },
232                         { "microsoft",    sufch_microsoft,    &__fETTable[5] },
233                         { "tcvn",         sufch_tcvn,         &__fETTable[6] },
234                         { "tis620.2533",  sufch_tis620,       &__fETTable[7] },
235                         { "viscii1.1",    sufch_viscii,       &__fETTable[8] },
236                         { "windows",      sufch_windows,      &__fETTable[9] },
237                         { "koi8",         sufch_koi8,         &__fETTable[10]},
238                         { "jisx0201.1976",sufch_jisx0201,     &__fETTable[11]},
239                         { "jisc6226.1978",sufch_jisx0208,     &__fETTable[12]},
240                         { "jisx0208.1983",sufch_jisx0208,     &__fETTable[13]},
241                         { "jisx0208.1990",sufch_jisx0208,     &__fETTable[14]},
242                         { "jisx0212.1990",sufch_jisx0212,     &__fETTable[15]},
243                         { "ksc5601.1987", sufch_ksc5601,      &__fETTable[16]},
244                         { "gb2312.1980",  sufch_gb2312,       &__fETTable[17]},
245                         { "big5",         sufch_big5,         &__fETTable[18]},
246                         { "unicode",      sufch_unicode,      &__fETTable[19]},
247                         { "iso10646",     sufch_iso10646,     &__fETTable[20]},
248                         { "cp",           sufch_windows,      &__fETTable[21]},
249                         /* NULL prefix matches anything so put it last */
250                         {   NULL,         sufch_any,          NULL },
251 };
252 static fontEncodingTemplate* fETTable = __fETTable;
253
254 /* a charset database for known facenames */
255 struct CharsetBindingInfo
256 {
257         const char*     pszFaceName;
258         BYTE            charset;
259 };
260 static const struct CharsetBindingInfo charsetbindings[] =
261 {
262         /* special facenames */
263         { "System", DEFAULT_CHARSET },
264         { "FixedSys", DEFAULT_CHARSET },
265
266         /* known facenames */
267         { "MS Serif", ANSI_CHARSET },
268         { "MS Sans Serif", ANSI_CHARSET },
269         { "Courier", ANSI_CHARSET },
270         { "Symbol", SYMBOL_CHARSET },
271
272         { "Arial", ANSI_CHARSET },
273         { "Arial Greek", GREEK_CHARSET },
274         { "Arial Tur", TURKISH_CHARSET },
275         { "Arial Baltic", BALTIC_CHARSET },
276         { "Arial CE", EASTEUROPE_CHARSET },
277         { "Arial Cyr", RUSSIAN_CHARSET },
278         { "Courier New", ANSI_CHARSET },
279         { "Courier New Greek", GREEK_CHARSET },
280         { "Courier New Tur", TURKISH_CHARSET },
281         { "Courier New Baltic", BALTIC_CHARSET },
282         { "Courier New CE", EASTEUROPE_CHARSET },
283         { "Courier New Cyr", RUSSIAN_CHARSET },
284         { "Times New Roman", ANSI_CHARSET },
285         { "Times New Roman Greek", GREEK_CHARSET },
286         { "Times New Roman Tur", TURKISH_CHARSET },
287         { "Times New Roman Baltic", BALTIC_CHARSET },
288         { "Times New Roman CE", EASTEUROPE_CHARSET },
289         { "Times New Roman Cyr", RUSSIAN_CHARSET },
290
291         { "\x82\x6c\x82\x72 \x83\x53\x83\x56\x83\x62\x83\x4e",
292                         SHIFTJIS_CHARSET }, /* MS gothic */
293         { "\x82\x6c\x82\x72 \x82\x6f\x83\x53\x83\x56\x83\x62\x83\x4e",
294                         SHIFTJIS_CHARSET }, /* MS P gothic */
295         { "\x82\x6c\x82\x72 \x96\xbe\x92\xa9",
296                         SHIFTJIS_CHARSET }, /* MS mincho */
297         { "\x82\x6c\x82\x72 \x82\x6f\x96\xbe\x92\xa9",
298                         SHIFTJIS_CHARSET }, /* MS P mincho */
299         { "GulimChe", HANGEUL_CHARSET },
300         { "MS Song", GB2312_CHARSET },
301         { "MS Hei", GB2312_CHARSET },
302         { "\xb7\x73\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },/*MS Mingliu*/
303         { "\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },
304
305         { NULL, 0 }
306 };
307
308
309 static int              DefResolution = 0;
310
311 static CRITICAL_SECTION crtsc_fonts_X11 = CRITICAL_SECTION_INIT;
312
313 static fontResource*    fontList = NULL;
314 static fontObject*      fontCache = NULL;               /* array */
315 static int              fontCacheSize = FONTCACHE;
316 static int              fontLF = -1, fontMRU = -1;      /* last free, most recently used */
317
318 #define __PFONT(pFont)     ( fontCache + ((UINT)(pFont) & 0x0000FFFF) )
319 #define CHECK_PFONT(pFont) ( (((UINT)(pFont) & 0xFFFF0000) == X_PFONT_MAGIC) &&\
320                              (((UINT)(pFont) & 0x0000FFFF) < fontCacheSize) )
321
322 static Atom RAW_ASCENT;
323 static Atom RAW_DESCENT;
324
325 /***********************************************************************
326  *           Helper macros from X distribution
327  */
328
329 #define CI_NONEXISTCHAR(cs) (((cs)->width == 0) && \
330                              (((cs)->rbearing|(cs)->lbearing| \
331                                (cs)->ascent|(cs)->descent) == 0))
332
333 #define CI_GET_CHAR_INFO(fs,col,def,cs) \
334 { \
335     cs = def; \
336     if (col >= fs->min_char_or_byte2 && col <= fs->max_char_or_byte2) { \
337         if (fs->per_char == NULL) { \
338             cs = &fs->min_bounds; \
339         } else { \
340             cs = &fs->per_char[(col - fs->min_char_or_byte2)]; \
341             if (CI_NONEXISTCHAR(cs)) cs = def; \
342         } \
343     } \
344 }
345
346 #define CI_GET_DEFAULT_INFO(fs,cs) \
347   CI_GET_CHAR_INFO(fs, fs->default_char, NULL, cs)
348
349 /***********************************************************************
350  *           Checksums
351  */
352 static UINT16   __lfCheckSum( LPLOGFONT16 plf )
353 {
354     CHAR        font[LF_FACESIZE];
355     UINT16      checksum = 0;
356     UINT16 *ptr;
357     int i;
358
359     ptr = (UINT16 *)plf;
360     for (i = 0; i < 9; i++) checksum ^= *ptr++;
361     for (i = 0; i < LF_FACESIZE; i++)
362     {
363         font[i] = tolower(plf->lfFaceName[i]);
364         if (!font[i] || font[i] == ' ') break;
365     }
366     for (ptr = (UINT16 *)font, i >>= 1; i > 0; i-- ) checksum ^= *ptr++;
367    return checksum;
368 }
369
370 static UINT16   __genericCheckSum( const void *ptr, int size )
371 {
372    unsigned int checksum = 0;
373    const char *p = (const char *)ptr;
374    while (size-- > 0)
375      checksum ^= (checksum << 3) + (checksum >> 29) + *p++;
376
377    return checksum & 0xffff;
378 }
379
380 /*************************************************************************
381  *           LFD parse/compose routines
382  *
383  * NB. LFD_Parse will use lpFont for its own ends, so if you want to keep it
384  *     make a copy first
385  *
386  * These functions also do TILDE to HYPHEN conversion
387  */
388 static LFD* LFD_Parse(LPSTR lpFont)
389 {
390     LFD* lfd;
391     char *lpch = lpFont, *lfd_fld[LFD_FIELDS], *field_start;
392     int i;
393     if (*lpch != HYPHEN)
394     {
395         WARN("font '%s' doesn't begin with '%c'\n", lpFont, HYPHEN);
396         return NULL;
397     }
398
399     field_start = ++lpch;
400     for( i = 0; i < LFD_FIELDS; )
401     {
402         if (*lpch == HYPHEN)
403         {
404             *lpch = '\0';
405             lfd_fld[i] = field_start;
406             i++;
407             field_start = ++lpch;
408         }
409         else if (!*lpch)
410         {
411             lfd_fld[i] = field_start;
412             i++;
413             break;
414         }
415         else if (*lpch == TILDE)
416         {
417             *lpch = HYPHEN;
418             ++lpch;
419         }
420         else
421             ++lpch;
422     }
423     /* Fill in the empty fields with NULLS */
424     for (; i< LFD_FIELDS; i++)
425         lfd_fld[i] = NULL;
426     if (*lpch)
427         WARN("Extra ignored in font '%s'\n", lpFont);
428     
429     lfd = HeapAlloc( GetProcessHeap(), 0, sizeof(LFD) );
430     if (lfd)
431     {
432         lfd->foundry = lfd_fld[0];
433         lfd->family = lfd_fld[1];
434         lfd->weight = lfd_fld[2];
435         lfd->slant = lfd_fld[3];
436         lfd->set_width = lfd_fld[4];
437         lfd->add_style = lfd_fld[5];
438         lfd->pixel_size = lfd_fld[6];
439         lfd->point_size = lfd_fld[7];
440         lfd->resolution_x = lfd_fld[8];
441         lfd->resolution_y = lfd_fld[9];
442         lfd->spacing = lfd_fld[10];
443         lfd->average_width = lfd_fld[11];
444         lfd->charset_registry = lfd_fld[12];
445         lfd->charset_encoding = lfd_fld[13];
446     }
447     return lfd;
448 }
449
450
451 static void LFD_UnParse(LPSTR dp, UINT buf_size, LFD* lfd)
452 {
453     const char* lfd_fld[LFD_FIELDS];
454     int i;
455
456     if (!buf_size)
457         return; /* Dont be silly */
458
459     lfd_fld[0]  = lfd->foundry;
460     lfd_fld[1]  = lfd->family;
461     lfd_fld[2]  = lfd->weight ;
462     lfd_fld[3]  = lfd->slant ;
463     lfd_fld[4]  = lfd->set_width ;
464     lfd_fld[5]  = lfd->add_style;
465     lfd_fld[6]  = lfd->pixel_size;
466     lfd_fld[7]  = lfd->point_size;
467     lfd_fld[8]  = lfd->resolution_x;
468     lfd_fld[9]  = lfd->resolution_y ;
469     lfd_fld[10] = lfd->spacing ;
470     lfd_fld[11] = lfd->average_width ;
471     lfd_fld[12] = lfd->charset_registry ;
472     lfd_fld[13] = lfd->charset_encoding ;
473
474     buf_size--; /* Room for the terminator */
475
476     for (i = 0; i < LFD_FIELDS; i++)
477     {
478         const char* sp = lfd_fld[i];
479         if (!sp || !buf_size)
480             break;
481         
482         *dp++ = HYPHEN;
483         buf_size--;
484         while (buf_size > 0 && *sp)
485         {
486             *dp = (*sp == HYPHEN) ? TILDE : *sp;
487             buf_size--;
488             dp++; sp++;
489         }
490     }
491     *dp = '\0';
492 }
493
494
495 static void LFD_GetWeight( fontInfo* fi, LPCSTR lpStr)
496 {
497     int j = strlen(lpStr);
498     if( j == 1 && *lpStr == '0') 
499         fi->fi_flags |= FI_POLYWEIGHT;
500     else if( j == 4 )
501     {
502         if( !strcasecmp( "bold", lpStr) )
503             fi->df.dfWeight = FW_BOLD; 
504         else if( !strcasecmp( "demi", lpStr) )
505         {
506             fi->fi_flags |= FI_FW_DEMI;
507             fi->df.dfWeight = FW_DEMIBOLD;
508         }
509         else if( !strcasecmp( "book", lpStr) )
510         {
511             fi->fi_flags |= FI_FW_BOOK;
512             fi->df.dfWeight = FW_REGULAR;
513         }
514     }
515     else if( j == 5 )
516     {
517         if( !strcasecmp( "light", lpStr) )
518             fi->df.dfWeight = FW_LIGHT;
519         else if( !strcasecmp( "black", lpStr) )
520             fi->df.dfWeight = FW_BLACK;
521     }
522     else if( j == 6 && !strcasecmp( "medium", lpStr) )
523         fi->df.dfWeight = FW_REGULAR; 
524     else if( j == 8 && !strcasecmp( "demibold", lpStr) )
525         fi->df.dfWeight = FW_DEMIBOLD; 
526     else
527         fi->df.dfWeight = FW_DONTCARE; /* FIXME: try to get something
528                                         * from the weight property */
529 }
530
531 static BOOL LFD_GetSlant( fontInfo* fi, LPCSTR lpStr)
532 {
533     int l = strlen(lpStr);
534     if( l == 1 )
535     {
536         switch( tolower( *lpStr ) )
537         {
538             case '0':  fi->fi_flags |= FI_POLYSLANT;    /* haven't seen this one yet */
539             default:
540             case 'r':  fi->df.dfItalic = 0;
541                        break;
542             case 'o':
543                        fi->fi_flags |= FI_OBLIQUE;
544             case 'i':  fi->df.dfItalic = 1;
545                        break;
546         }
547         return FALSE;
548     }
549     return TRUE;
550 }
551
552 static void LFD_GetStyle( fontInfo* fi, LPCSTR lpstr, int dec_style_check)
553 {
554     int j = strlen(lpstr);
555     if( j > 3 ) /* find out is there "sans" or "script" */
556     {
557         j = 0;
558         
559         if( strstr(lpstr, "sans") ) 
560         { 
561             fi->df.dfPitchAndFamily |= FF_SWISS; 
562             j = 1; 
563         }
564         if( strstr(lpstr, "script") ) 
565         { 
566             fi->df.dfPitchAndFamily |= FF_SCRIPT; 
567             j = 1; 
568         }
569         if( !j && dec_style_check ) 
570             fi->df.dfPitchAndFamily |= FF_DECORATIVE;
571    }
572 }
573
574 /*************************************************************************
575  *           LFD_InitFontInfo
576  *
577  * INIT ONLY
578  *
579  * Fill in some fields in the fontInfo struct.
580  */
581 static int LFD_InitFontInfo( fontInfo* fi, const LFD* lfd, LPCSTR fullname )
582 {
583    int          i, j, dec_style_check, scalability;
584    fontEncodingTemplate* boba;
585    const char* ridiculous = "font '%s' has ridiculous %s\n";
586    const char* lpstr;
587
588    if (!lfd->charset_registry)
589    {
590        WARN("font '%s' does not have enough fields\n", fullname);
591        return FALSE;
592    }
593
594    memset(fi, 0, sizeof(fontInfo) );
595
596 /* weight name - */
597    LFD_GetWeight( fi, lfd->weight);
598
599 /* slant - */
600    dec_style_check = LFD_GetSlant( fi, lfd->slant);
601
602 /* width name - */
603    lpstr = lfd->set_width;
604    if( strcasecmp( "normal", lpstr) )   /* XXX 'narrow', 'condensed', etc... */
605        dec_style_check = TRUE;
606    else
607        fi->fi_flags |= FI_NORMAL;
608
609 /* style - */
610    LFD_GetStyle(fi, lfd->add_style, dec_style_check);
611
612 /* pixel & decipoint height, and res_x & y */
613
614    scalability = 0;
615
616    j = strlen(lfd->pixel_size);
617    if( j == 0 || j > 3 )
618    {
619        WARN(ridiculous, fullname, "pixel_size");
620        return FALSE;
621    }
622    if( !(fi->lfd_height = atoi(lfd->pixel_size)) )
623        scalability++;
624
625    j = strlen(lfd->point_size);
626    if( j == 0 || j > 3 )
627    {
628        WARN(ridiculous, fullname, "point_size");
629        return FALSE;
630    }
631    if( !(atoi(lfd->point_size)) )
632        scalability++;
633
634    j = strlen(lfd->resolution_x);
635    if( j == 0 || j > 3 )
636    {
637        WARN(ridiculous, fullname, "resolution_x");
638        return FALSE;
639    }
640    if( !(fi->lfd_resolution = atoi(lfd->resolution_x)) )
641        scalability++;
642
643    j = strlen(lfd->resolution_y);
644    if( j == 0 || j > 3 )
645    {
646        WARN(ridiculous, fullname, "resolution_y");
647        return FALSE;
648    }
649    if( !(atoi(lfd->resolution_y)) )
650        scalability++;
651
652    /* Check scalability */
653    switch (scalability)
654    {
655    case 0: /* Bitmap */
656        break;
657    case 4: /* Scalable */
658        fi->fi_flags |= FI_SCALABLE;
659        break;
660    case 2:
661        /* #$%^!!! X11R6 mutant garbage (scalable bitmap) */
662        TRACE("Skipping scalable bitmap '%s'\n", fullname);
663        return FALSE;
664    default:
665        WARN("Font '%s' has weird scalability\n", fullname);
666        return FALSE;
667    }
668
669 /* spacing - */
670    lpstr = lfd->spacing;
671    switch( *lpstr )
672    {
673      case '\0':
674          WARN("font '%s' has no spacing\n", fullname);
675          return FALSE;
676
677      case 'p': fi->fi_flags |= FI_VARIABLEPITCH;
678                break;
679      case 'c': fi->df.dfPitchAndFamily |= FF_MODERN;
680                fi->fi_flags |= FI_FIXEDEX;
681                /* fall through */
682      case 'm': fi->fi_flags |= FI_FIXEDPITCH;
683                break;
684      default:
685                /* Of course this line does nothing */
686                fi->df.dfPitchAndFamily |= DEFAULT_PITCH | FF_DONTCARE;
687    }
688
689 /* average width - */
690    lpstr = lfd->average_width;
691    j = strlen(lpstr);
692    if( j == 0 || j > 3 )
693    {
694        WARN(ridiculous, fullname, "average_width");
695        return FALSE;
696    }
697
698    if( !(atoi(lpstr)) && !scalability )
699    {
700        WARN("font '%s' has average_width 0 but is not scalable!!\n", fullname);
701        return FALSE;
702    }
703
704 /* charset registry, charset encoding - */
705    lpstr = lfd->charset_registry;
706    if( strstr(lpstr, "ksc") || 
707        strstr(lpstr, "gb2312") ||
708        strstr(lpstr, "big5") )
709    {
710        FIXME("DBCS fonts like '%s' are not working correctly now.\n", fullname);
711    }
712
713    fi->df.dfCharSet = ANSI_CHARSET;
714
715    for( i = 0, boba = fETTable; boba; boba = boba->next, i++ )
716    {
717        if (!boba->prefix || !strcasecmp(lpstr, boba->prefix))
718        {
719            if (lfd->charset_encoding)
720            {
721                for( j = 0; boba->sufch[j].psuffix; j++ )
722                {
723                    if( !strcasecmp(lfd->charset_encoding, boba->sufch[j].psuffix ))
724                    {
725                        fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
726                        fi->internal_charset = boba->sufch[j].charset;
727                        fi->codepage = boba->sufch[j].codepage;
728                        fi->cptable = boba->sufch[j].cptable;
729                        goto done;
730                    }
731                }
732
733                fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
734                fi->internal_charset = boba->sufch[j].charset;
735                fi->codepage = boba->sufch[j].codepage;
736                fi->cptable = boba->sufch[j].cptable;
737                if (boba->prefix)
738                {
739                   FIXME("font '%s' has unknown character encoding '%s' in known registry '%s'\n",
740                        fullname, lfd->charset_encoding, boba->prefix);
741                   j = 254;
742                }
743                else
744                {
745                   FIXME("font '%s' has unknown registry '%s' and character encoding '%s' \n",
746                        fullname, lfd->charset_registry, lfd->charset_encoding);
747                   j = 255;
748                }
749
750                WARN("Defaulting to: df.dfCharSet = %d,  internal_charset = %d, codepage = %d, cptable = %d\n",
751                     fi->df.dfCharSet,fi->internal_charset, fi->codepage, fi->cptable);
752                goto done;
753            }
754            else if (boba->prefix)
755            {
756                WARN("font '%s' has known registry '%s' and no character encoding\n",
757                     fullname, lpstr);
758                for( j = 0; boba->sufch[j].psuffix; j++ )
759                    ;
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                j = 255;
765                goto done;
766            }
767        }
768    }
769    WARN("font '%s' has unknown character set '%s'\n", fullname, lpstr);
770    return FALSE;
771
772 done:
773    /* i - index into fETTable
774     * j - index into suffix array for fETTable[i]
775     *     except:
776     *     254 - found encoding prefix, unknown suffix
777     *     255 - no encoding match at all.
778     */
779    fi->fi_encoding = 256 * (UINT16)i + (UINT16)j;
780
781    return TRUE;                                 
782 }
783
784
785 /*************************************************************************
786  *           LFD_AngleMatrix
787  *
788  * make a matrix suitable for LFD based on theta radians
789  */
790 static void LFD_AngleMatrix( char* buffer, int h, double theta)
791 {
792     double matrix[4];
793     matrix[0] = h*cos(theta);
794     matrix[1] = h*sin(theta);
795     matrix[2] = -h*sin(theta);
796     matrix[3] = h*cos(theta);
797     sprintf(buffer, "[%+f%+f%+f%+f]", matrix[0], matrix[1], matrix[2], matrix[3]);
798 }
799
800 /*************************************************************************
801  *           LFD_ComposeLFD
802  *
803  * Note: uRelax is a treatment not a cure. Font mapping algorithm
804  *       should be bulletproof enough to allow us to avoid hacks like
805  *       this despite LFD being so braindead.
806  */
807 static BOOL LFD_ComposeLFD( const fontObject* fo, 
808                             INT height, LPSTR lpLFD, UINT uRelax )
809 {
810    int          i, h;
811    char         *any = "*";
812    char         h_string[64], resx_string[64], resy_string[64];
813    LFD          aLFD;
814
815 /* Get the worst case over with first */
816
817 /* RealizeFont() will call us repeatedly with increasing uRelax 
818  * until XLoadFont() succeeds. 
819  * to avoid an infinite loop; these will always match
820  */
821    if (uRelax >= 5)
822    {
823        if (uRelax == 5)
824            sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-1" );
825        else
826            sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*" );
827        return TRUE;
828    }
829
830 /* read foundry + family from fo */
831    aLFD.foundry = fo->fr->resource->foundry;
832    aLFD.family  = fo->fr->resource->family;
833
834 /* add weight */
835    switch( fo->fi->df.dfWeight )
836    {
837         case FW_BOLD:
838                 aLFD.weight = "bold"; break;
839         case FW_REGULAR:
840                 if( fo->fi->fi_flags & FI_FW_BOOK )
841                     aLFD.weight = "book";
842                 else
843                     aLFD.weight = "medium";
844                 break;
845         case FW_DEMIBOLD:
846                 aLFD.weight = "demi";
847                 if( !( fo->fi->fi_flags & FI_FW_DEMI) )
848                      aLFD.weight = "bold";
849                 break;
850         case FW_BLACK:
851                 aLFD.weight = "black"; break;
852         case FW_LIGHT:
853                 aLFD.weight = "light"; break;
854         default:
855                 aLFD.weight = any;
856    }
857
858 /* add slant */
859    if( fo->fi->df.dfItalic )
860        if( fo->fi->fi_flags & FI_OBLIQUE )
861            aLFD.slant = "o";
862        else
863            aLFD.slant = "i";
864    else 
865        aLFD.slant = (uRelax < 1) ? "r" : any;
866
867 /* add width */
868    if( fo->fi->fi_flags & FI_NORMAL )
869        aLFD.set_width = "normal";
870    else
871        aLFD.set_width = any;
872
873 /* ignore style */
874    aLFD.add_style = any;
875
876 /* add pixelheight 
877  *
878  * FIXME: fill in lpXForm and lpPixmap for rotated fonts
879  */
880    if( fo->fo_flags & FO_SYNTH_HEIGHT )
881        h = fo->fi->lfd_height;
882    else
883    {
884        h = (fo->fi->lfd_height * height + (fo->fi->df.dfPixHeight>>1));
885        h /= fo->fi->df.dfPixHeight;
886    } 
887    if (h < MIN_FONT_SIZE) /* Resist rounding down to 0 */
888        h = MIN_FONT_SIZE;
889    else if (h > MAX_FONT_SIZE) /* Sanity check as huge fonts can lock up the font server */
890    {
891        WARN("Huge font size %d pixels has been reduced to %d\n", h, MAX_FONT_SIZE);
892        h = MAX_FONT_SIZE;
893    }
894        
895    if (uRelax <= 2)
896        /* handle rotated fonts */
897        if (fo->lf.lfEscapement) {
898            /* escapement is in tenths of degrees, theta is in radians */
899            double theta = M_PI*fo->lf.lfEscapement/1800.;  
900            LFD_AngleMatrix(h_string, h, theta);
901        }
902        else
903        {
904            sprintf(h_string, "%d", h);
905        }
906    else
907        sprintf(h_string, "%d", fo->fi->lfd_height);
908
909    aLFD.pixel_size = h_string;
910    aLFD.point_size = any;
911
912 /* resolution_x,y, average width */
913    /* FOX ME - Why do some font servers ignore average width ?
914     * so that you have to mess around with res_y
915     */
916    aLFD.average_width = any;
917    if (uRelax <= 3)
918    {
919        sprintf(resx_string, "%d", fo->fi->lfd_resolution);
920        aLFD.resolution_x = resx_string;
921
922        strcpy(resy_string, resx_string);
923        if( uRelax == 0  && XTextCaps & TC_SF_X_YINDEP ) 
924        {
925            if( fo->lf.lfWidth && !(fo->fo_flags & FO_SYNTH_WIDTH))
926            {
927                int resy = 0.5 + fo->fi->lfd_resolution *        
928                    (fo->fi->df.dfAvgWidth * height) /
929                    (fo->lf.lfWidth * fo->fi->df.dfPixHeight) ;
930                sprintf(resy_string,  "%d", resy);
931            }
932            else
933            {
934                /* FIXME - synth width */
935            }
936        }           
937        aLFD.resolution_y = resy_string;
938    }
939    else
940    {
941        aLFD.resolution_x = aLFD.resolution_y = any;
942    }
943
944 /* spacing */
945    {
946        char* w;
947
948        if( fo->fi->fi_flags & FI_FIXEDPITCH ) 
949            w = ( fo->fi->fi_flags & FI_FIXEDEX ) ? "c" : "m";
950        else 
951            w = ( fo->fi->fi_flags & FI_VARIABLEPITCH ) ? "p" : any; 
952        
953        aLFD.spacing = (uRelax <= 1) ? w : any;
954    }
955
956 /* encoding */
957
958    if (uRelax <= 4)
959    {
960        fontEncodingTemplate* boba = fETTable;
961
962        for(i = fo->fi->fi_encoding >> 8; i; i--) boba = boba->next;
963        aLFD.charset_registry = boba->prefix ? boba->prefix : any;
964        
965        i = fo->fi->fi_encoding & 255;
966        switch( i )
967        {
968        default:
969            aLFD.charset_encoding = boba->sufch[i].psuffix;
970            break;
971            
972        case 254:
973            aLFD.charset_encoding = any;
974            break;
975            
976        case 255: /* no suffix - it ends eg "-ascii" */
977            aLFD.charset_encoding = NULL;
978            break;
979        }
980    }
981    else
982    {
983        aLFD.charset_registry = any;
984        aLFD.charset_encoding = any;
985    }
986     
987    LFD_UnParse(lpLFD, MAX_LFD_LENGTH, &aLFD);
988
989    TRACE("\tLFD(uRelax=%d): %s\n", uRelax, lpLFD );
990    return TRUE;
991 }
992
993
994 /***********************************************************************
995  *              X Font Resources
996  *
997  * font info            - http://www.microsoft.com/kb/articles/q65/1/23.htm
998  * Windows font metrics - http://www.microsoft.com/kb/articles/q32/6/67.htm
999  */
1000 static void XFONT_GetLeading( const LPIFONTINFO16 pFI, const XFontStruct* x_fs, 
1001                               INT16* pIL, INT16* pEL, const XFONTTRANS *XFT )
1002 {
1003     unsigned long height;
1004     unsigned min = (unsigned char)pFI->dfFirstChar;
1005     BOOL bIsLatin = IS_LATIN_CHARSET(pFI->dfCharSet);
1006
1007     if( pEL ) *pEL = 0;
1008
1009     if(XFT) {
1010         Atom RAW_CAP_HEIGHT = TSXInternAtom(gdi_display, "RAW_CAP_HEIGHT", TRUE);
1011         if(TSXGetFontProperty((XFontStruct*)x_fs, RAW_CAP_HEIGHT, &height))
1012             *pIL = XFT->ascent - 
1013                             (INT)(XFT->pixelsize / 1000.0 * height);
1014         else
1015             *pIL = 0;
1016         return;
1017     }
1018        
1019     if( TSXGetFontProperty((XFontStruct*)x_fs, XA_CAP_HEIGHT, &height) == FALSE )
1020     {
1021         if( x_fs->per_char )
1022             if( bIsLatin )
1023                     height = x_fs->per_char['X' - min].ascent;
1024             else
1025                 if (x_fs->ascent >= x_fs->max_bounds.ascent)
1026                     height = x_fs->max_bounds.ascent;
1027                 else
1028                 {
1029                     height = x_fs->ascent;
1030                     if( pEL )
1031                         *pEL = x_fs->max_bounds.ascent - height;
1032                 }
1033         else 
1034             height = x_fs->min_bounds.ascent;
1035     }
1036
1037     *pIL = x_fs->ascent - height;
1038 }
1039
1040 /***********************************************************************
1041  *           XFONT_CharWidth
1042  */
1043 static int XFONT_CharWidth(const XFontStruct* x_fs,
1044                            const XFONTTRANS *XFT, int ch)
1045 {   
1046     if(!XFT)
1047         return x_fs->per_char[ch].width;
1048     else
1049         return x_fs->per_char[ch].attributes * XFT->pixelsize / 1000.0;
1050 }
1051
1052 /***********************************************************************
1053  *           XFONT_GetAvgCharWidth
1054  */
1055 static INT XFONT_GetAvgCharWidth( LPIFONTINFO16 pFI, const XFontStruct* x_fs,
1056                                     const XFONTTRANS *XFT)
1057 {
1058     unsigned min = (unsigned char)pFI->dfFirstChar;
1059     unsigned max = (unsigned char)pFI->dfLastChar;
1060
1061     INT avg;
1062
1063     if( x_fs->per_char )
1064     {
1065         int  width = 0, chars = 0, j;
1066         if( IS_LATIN_CHARSET(pFI->dfCharSet) ||
1067             pFI->dfCharSet == DEFAULT_CHARSET )
1068         {
1069             /* FIXME - should use a weighted average */
1070             for( j = 0; j < 26; j++ )
1071                 width += XFONT_CharWidth(x_fs, XFT, 'a' + j - min) +
1072                          XFONT_CharWidth(x_fs, XFT, 'A' + j - min);         
1073             chars = 52;
1074         }
1075         else /* unweighted average of everything */
1076         {
1077             for( j = 0,  max -= min; j <= max; j++ )
1078                 if( !CI_NONEXISTCHAR(x_fs->per_char + j) )
1079                 {
1080                     width += XFONT_CharWidth(x_fs, XFT, j);
1081                     chars++;
1082                 }
1083         }
1084         if (chars) avg = (width + (chars>>1))/ chars;
1085         else       avg = 0; /* No characters exist at all */ 
1086     }
1087     else /* uniform width */
1088         avg = x_fs->min_bounds.width;
1089
1090     return avg;
1091 }
1092
1093 /***********************************************************************
1094  *           XFONT_GetMaxCharWidth
1095  */
1096 static INT XFONT_GetMaxCharWidth(const XFontStruct* xfs, const XFONTTRANS *XFT)
1097 {
1098     unsigned min = (unsigned char)xfs->min_char_or_byte2;
1099     unsigned max = (unsigned char)xfs->max_char_or_byte2;
1100     int  maxwidth, j;
1101
1102     if(!XFT || !xfs->per_char)
1103         return abs(xfs->max_bounds.width);
1104
1105     for( j = 0, maxwidth = 0, max -= min; j <= max; j++ )
1106         if( !CI_NONEXISTCHAR(xfs->per_char + j) )
1107             if(maxwidth < xfs->per_char[j].attributes)
1108                 maxwidth = xfs->per_char[j].attributes;
1109     
1110     maxwidth *= XFT->pixelsize / 1000.0;
1111     return maxwidth;
1112 }
1113
1114 /***********************************************************************
1115  *              XFONT_SetFontMetric
1116  *
1117  * INIT ONLY
1118  *
1119  * Initializes IFONTINFO16.
1120  */
1121 static void XFONT_SetFontMetric(fontInfo* fi, const fontResource* fr, XFontStruct* xfs)
1122 {
1123     unsigned min, max;
1124     fi->df.dfFirstChar = (BYTE)(min = xfs->min_char_or_byte2);
1125     fi->df.dfLastChar = (BYTE)(max = xfs->max_char_or_byte2);
1126
1127     fi->df.dfDefaultChar = (BYTE)xfs->default_char;
1128     fi->df.dfBreakChar = (BYTE)(( ' ' < min || ' ' > max) ? xfs->default_char: ' ');
1129
1130     fi->df.dfPixHeight = (INT16)((fi->df.dfAscent = (INT16)xfs->ascent) + xfs->descent);
1131     fi->df.dfPixWidth = (xfs->per_char) ? 0 : xfs->min_bounds.width;
1132
1133     XFONT_GetLeading( &fi->df, xfs, &fi->df.dfInternalLeading, &fi->df.dfExternalLeading, NULL );
1134     fi->df.dfAvgWidth = (INT16)XFONT_GetAvgCharWidth(&fi->df, xfs, NULL );
1135     fi->df.dfMaxWidth = (INT16)XFONT_GetMaxCharWidth(xfs, NULL);
1136
1137     if( xfs->min_bounds.width != xfs->max_bounds.width )
1138         fi->df.dfPitchAndFamily |= TMPF_FIXED_PITCH; /* au contraire! */
1139     if( fi->fi_flags & FI_SCALABLE ) 
1140     {
1141         fi->df.dfType = DEVICE_FONTTYPE;
1142         fi->df.dfPitchAndFamily |= TMPF_DEVICE;
1143     } 
1144     else if( fi->fi_flags & FI_TRUETYPE )
1145         fi->df.dfType = TRUETYPE_FONTTYPE;
1146     else
1147         fi->df.dfType = RASTER_FONTTYPE;
1148
1149     fi->df.dfFace = fr->lfFaceName;
1150 }
1151
1152 /***********************************************************************
1153  *              XFONT_GetFontMetric
1154  *
1155  * Retrieve font metric info (enumeration).
1156  */
1157 static UINT XFONT_GetFontMetric( const fontInfo* pfi,
1158                                  const LPENUMLOGFONTEXW pLF,
1159                                  const LPNEWTEXTMETRICEXW pTM )
1160 {
1161     memset( pLF, 0, sizeof(*pLF) );
1162     memset( pTM, 0, sizeof(*pTM) );
1163
1164 #define plf ((LPLOGFONTW)pLF)
1165 #define ptm ((LPNEWTEXTMETRICW)pTM)
1166     plf->lfHeight    = ptm->tmHeight       = pfi->df.dfPixHeight;
1167     plf->lfWidth     = ptm->tmAveCharWidth = pfi->df.dfAvgWidth;
1168     plf->lfWeight    = ptm->tmWeight       = pfi->df.dfWeight;
1169     plf->lfItalic    = ptm->tmItalic       = pfi->df.dfItalic;
1170     plf->lfUnderline = ptm->tmUnderlined   = pfi->df.dfUnderline;
1171     plf->lfStrikeOut = ptm->tmStruckOut    = pfi->df.dfStrikeOut;
1172     plf->lfCharSet   = ptm->tmCharSet      = pfi->df.dfCharSet;
1173
1174     /* convert pitch values */
1175
1176     ptm->tmPitchAndFamily = pfi->df.dfPitchAndFamily;
1177     plf->lfPitchAndFamily = (pfi->df.dfPitchAndFamily & 0xF1) + 1;
1178
1179     MultiByteToWideChar(CP_ACP, 0, pfi->df.dfFace, -1,
1180                         plf->lfFaceName, LF_FACESIZE);
1181
1182     /* FIXME: fill in rest of plF values */
1183     strcpyW(pLF->elfFullName, plf->lfFaceName);
1184     MultiByteToWideChar(CP_ACP, 0, "Regular", -1,
1185                         pLF->elfStyle, LF_FACESIZE);
1186     MultiByteToWideChar(CP_ACP, 0, plf->lfCharSet == SYMBOL_CHARSET ?
1187                         "Symbol" : "Roman", -1,
1188                         pLF->elfScript, LF_FACESIZE);
1189
1190 #undef plf
1191
1192     ptm->tmAscent = pfi->df.dfAscent;
1193     ptm->tmDescent = ptm->tmHeight - ptm->tmAscent;
1194     ptm->tmInternalLeading = pfi->df.dfInternalLeading;
1195     ptm->tmMaxCharWidth = pfi->df.dfMaxWidth;
1196     ptm->tmDigitizedAspectX = pfi->df.dfHorizRes;
1197     ptm->tmDigitizedAspectY = pfi->df.dfVertRes;
1198
1199     ptm->tmFirstChar = pfi->df.dfFirstChar;
1200     ptm->tmLastChar = pfi->df.dfLastChar;
1201     ptm->tmDefaultChar = pfi->df.dfDefaultChar;
1202     ptm->tmBreakChar = pfi->df.dfBreakChar;
1203  
1204     TRACE("Calling Enum proc with FaceName %s FullName %s\n",
1205           debugstr_w(pLF->elfLogFont.lfFaceName),
1206           debugstr_w(pLF->elfFullName));
1207
1208    TRACE("CharSet = %d type = %d\n", ptm->tmCharSet, pfi->df.dfType);
1209     /* return font type */
1210     return pfi->df.dfType;
1211 #undef ptm
1212 }
1213
1214
1215 /***********************************************************************
1216  *           XFONT_FixupFlags
1217  *
1218  * INIT ONLY
1219  * 
1220  * dfPitchAndFamily flags for some common typefaces.
1221  */
1222 static BYTE XFONT_FixupFlags( LPCSTR lfFaceName )
1223 {
1224    switch( lfFaceName[0] )
1225    {
1226         case 'a':
1227         case 'A': if(!strncasecmp(lfFaceName, "Arial", 5) )
1228                     return FF_SWISS;
1229                   break;
1230         case 'h':
1231         case 'H': if(!strcasecmp(lfFaceName, "Helvetica") )
1232                     return FF_SWISS;
1233                   break;
1234         case 'c':
1235         case 'C': if(!strncasecmp(lfFaceName, "Courier", 7))
1236                     return FF_MODERN;
1237         
1238                   if (!strcasecmp(lfFaceName, "Charter") )
1239                       return FF_ROMAN;
1240                   break;
1241         case 'p':
1242         case 'P': if( !strcasecmp(lfFaceName,"Palatino") )
1243                     return FF_ROMAN;
1244                   break;
1245         case 't':
1246         case 'T': if(!strncasecmp(lfFaceName, "Times", 5) )
1247                     return FF_ROMAN;
1248                   break;
1249         case 'u':
1250         case 'U': if(!strcasecmp(lfFaceName, "Utopia") )
1251                     return FF_ROMAN;
1252                   break;
1253         case 'z':
1254         case 'Z': if(!strcasecmp(lfFaceName, "Zapf Dingbats") )
1255                     return FF_DECORATIVE;
1256    }
1257    return 0;
1258 }
1259
1260 /***********************************************************************
1261  *           XFONT_SameFoundryAndFamily
1262  *
1263  * INIT ONLY
1264  */
1265 static BOOL XFONT_SameFoundryAndFamily( const LFD* lfd1, const LFD* lfd2 )
1266 {
1267     return ( !strcasecmp( lfd1->foundry, lfd2->foundry ) && 
1268              !strcasecmp( lfd1->family,  lfd2->family ) );
1269 }
1270
1271 /***********************************************************************
1272  *           XFONT_InitialCapitals
1273  *
1274  * INIT ONLY
1275  *
1276  * Upper case first letters of words & remove multiple spaces
1277  */
1278 static void XFONT_InitialCapitals(LPSTR lpch)
1279 {
1280     int i;
1281     BOOL up;
1282     char* lpstr = lpch;
1283
1284     for( i = 0, up = TRUE; *lpch; lpch++, i++ )
1285     {
1286         if( isspace(*lpch) ) 
1287         {
1288             if (!up)  /* Not already got one */
1289             {
1290                 *lpstr++ = ' ';
1291                 up = TRUE;
1292             }
1293         }
1294         else if( isalpha(*lpch) && up )
1295         { 
1296             *lpstr++ = toupper(*lpch); 
1297             up = FALSE;
1298         }
1299         else 
1300         {
1301             *lpstr++ = *lpch;
1302             up = FALSE;
1303         }
1304     }
1305
1306     /* Remove possible trailing space */
1307     if (up && i > 0)
1308         --lpstr;
1309     *lpstr = '\0';
1310 }
1311
1312
1313 /***********************************************************************
1314  *           XFONT_WindowsNames
1315  *
1316  * INIT ONLY
1317  *
1318  * Build generic Windows aliases for X font names.
1319  *
1320  * -misc-fixed- -> "Fixed"
1321  * -sony-fixed- -> "Sony Fixed", etc...
1322  */
1323 static void XFONT_WindowsNames(void)
1324 {
1325     fontResource* fr;
1326
1327     for( fr = fontList; fr ; fr = fr->next )
1328     {
1329         fontResource* pfr;
1330         char*         lpch;
1331
1332         if( fr->fr_flags & FR_NAMESET ) continue;     /* skip already assigned */
1333
1334         for( pfr = fontList; pfr != fr ; pfr = pfr->next )
1335             if( pfr->fr_flags & FR_NAMESET )
1336             {
1337                 if (!strcasecmp( pfr->resource->family, fr->resource->family))
1338                     break;
1339             }
1340
1341         lpch = fr->lfFaceName;
1342         snprintf( fr->lfFaceName, sizeof(fr->lfFaceName), "%s %s",
1343                                           /* prepend vendor name */
1344                                           (pfr==fr) ? "" : fr->resource->foundry,
1345                                           fr->resource->family);
1346         XFONT_InitialCapitals(fr->lfFaceName);
1347         {
1348             BYTE bFamilyStyle = XFONT_FixupFlags( fr->lfFaceName );
1349             if( bFamilyStyle)
1350             {
1351                 fontInfo* fi;
1352                 for( fi = fr->fi ; fi ; fi = fi->next )
1353                     fi->df.dfPitchAndFamily |= bFamilyStyle;
1354             }
1355         }
1356             
1357         TRACE("typeface '%s'\n", fr->lfFaceName);
1358         
1359         fr->fr_flags |= FR_NAMESET;
1360     }
1361 }
1362
1363 /***********************************************************************
1364  *           XFONT_LoadDefaultLFD
1365  *
1366  * Move lfd to the head of fontList to make it more likely to be matched
1367  */
1368 static void XFONT_LoadDefaultLFD(LFD* lfd, LPCSTR fonttype)
1369 {
1370     {
1371         fontResource *fr, *pfr;
1372         for( fr = NULL, pfr = fontList; pfr; pfr = pfr->next )
1373         {
1374             if( XFONT_SameFoundryAndFamily(pfr->resource, lfd) )
1375             {
1376                 if( fr )
1377                 {
1378                     fr->next = pfr->next;
1379                     pfr->next = fontList;
1380                     fontList = pfr;
1381                 }
1382                 break;
1383             }
1384             fr = pfr;
1385         }
1386         if (!pfr)
1387             WARN("Default %sfont '-%s-%s-' not available\n", fonttype, 
1388                  lfd->foundry, lfd->family);
1389     }
1390 }
1391
1392 /***********************************************************************
1393  *           XFONT_LoadDefault
1394  */
1395 static void XFONT_LoadDefault(LPCSTR ini, LPCSTR fonttype)
1396 {
1397     char buffer[MAX_LFD_LENGTH];
1398     HKEY hkey;
1399
1400     buffer[0] = 0;
1401     if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1402     {
1403         DWORD type, count = sizeof(buffer);
1404         RegQueryValueExA(hkey, ini, 0, &type, buffer, &count);
1405         RegCloseKey(hkey);
1406
1407         if (*buffer)
1408         {
1409             LFD* lfd;
1410             char* pch = buffer;
1411             while( *pch && isspace(*pch) ) pch++;
1412             
1413             TRACE("Using '%s' as default %sfont\n", pch, fonttype);
1414             lfd = LFD_Parse(pch);
1415             if (lfd && lfd->foundry && lfd->family)
1416                 XFONT_LoadDefaultLFD(lfd, fonttype);
1417             else
1418                 WARN("Ini section [%s]%s is malformed\n", INIFontSection, ini);
1419             HeapFree(GetProcessHeap(), 0, lfd);
1420         }
1421     }
1422 }
1423
1424 /***********************************************************************
1425  *           XFONT_LoadDefaults
1426  */
1427 static void XFONT_LoadDefaults(void)
1428 {
1429     XFONT_LoadDefault(INIDefaultFixed, "fixed ");
1430     XFONT_LoadDefault(INIDefault, "");
1431 }
1432
1433 /***********************************************************************
1434  *           XFONT_CreateAlias
1435  */
1436 static fontAlias* XFONT_CreateAlias( LPCSTR lpTypeFace, LPCSTR lpAlias )
1437 {
1438     int j;
1439     fontAlias *pfa, *prev = NULL;
1440
1441     for(pfa = aliasTable; pfa; pfa = pfa->next)
1442     {
1443         /* check if we already got one */
1444         if( !strcasecmp( pfa->faTypeFace, lpAlias ) )
1445         {
1446             TRACE("redundant alias '%s' -> '%s'\n", 
1447                   lpAlias, lpTypeFace );
1448             return NULL;
1449         }
1450         prev = pfa;
1451     }
1452
1453     j = strlen(lpTypeFace) + 1;
1454     pfa = HeapAlloc( GetProcessHeap(), 0, sizeof(fontAlias) +
1455                                j + strlen(lpAlias) + 1 );
1456     if (pfa)
1457     {
1458         if (!prev)
1459             aliasTable = pfa;
1460         else
1461             prev->next = pfa;
1462     
1463         pfa->next = NULL;
1464         pfa->faTypeFace = (LPSTR)(pfa + 1);
1465         strcpy( pfa->faTypeFace, lpTypeFace );
1466         pfa->faAlias = pfa->faTypeFace + j;
1467         strcpy( pfa->faAlias, lpAlias );
1468
1469         TRACE("added alias '%s' for '%s'\n", lpAlias, lpTypeFace );
1470
1471         return pfa;
1472     }
1473     return NULL;
1474 }
1475
1476
1477 /***********************************************************************
1478  *           XFONT_LoadAlias
1479  */
1480 static void XFONT_LoadAlias(const LFD* lfd, LPCSTR lpAlias, BOOL bSubst)
1481 {
1482     fontResource *fr, *frMatch = NULL;
1483     if (!lfd->foundry || ! lfd->family)
1484     {
1485         WARN("Malformed font resource for alias '%s'\n", lpAlias);
1486         return;
1487     }
1488     for (fr = fontList; fr ; fr = fr->next)
1489     {
1490         if(!strcasecmp(fr->resource->family, lpAlias))
1491         {
1492             /* alias is not needed since the real font is present */
1493             TRACE("Ignoring font alias '%s' as it is already available as a real font\n", lpAlias);
1494             return;
1495         }
1496         if( XFONT_SameFoundryAndFamily( fr->resource, lfd ) )
1497         {
1498             frMatch = fr;
1499             break;
1500         }
1501     }
1502
1503     if( frMatch )
1504     {
1505         if( bSubst )
1506         {
1507             fontAlias *pfa, *prev = NULL;
1508
1509             for(pfa = aliasTable; pfa; pfa = pfa->next)
1510             {
1511                 /* Remove lpAlias from aliasTable - we should free the old entry */
1512                 if(!strcmp(lpAlias, pfa->faAlias))
1513                 {
1514                     if(prev)
1515                         prev->next = pfa->next;
1516                     else
1517                         aliasTable = pfa->next;
1518                 }
1519
1520                 /* Update any references to the substituted font in aliasTable */
1521                 if(!strcmp(frMatch->lfFaceName, pfa->faTypeFace))
1522                     pfa->faTypeFace = HEAP_strdupA( GetProcessHeap(), 0, lpAlias );
1523                 prev = pfa;
1524             }
1525                                                 
1526             TRACE("\tsubstituted '%s' with '%s'\n", frMatch->lfFaceName, lpAlias );
1527                 
1528             lstrcpynA( frMatch->lfFaceName, lpAlias, LF_FACESIZE );
1529             frMatch->fr_flags |= FR_NAMESET;
1530         }
1531         else
1532         {
1533             /* create new entry in the alias table */
1534             XFONT_CreateAlias( frMatch->lfFaceName, lpAlias );
1535         }
1536     }
1537     else
1538     {
1539         WARN("Font alias '-%s-%s-' is not available\n", lfd->foundry, lfd->family);
1540     }
1541
1542
1543 /***********************************************************************
1544  *  Just a copy of PROFILE_GetStringItem
1545  *
1546  *  Convenience function that turns a string 'xxx, yyy, zzz' into 
1547  *  the 'xxx\0 yyy, zzz' and returns a pointer to the 'yyy, zzz'.
1548  */
1549 static char *XFONT_GetStringItem( char *start )
1550 {
1551 #define XFONT_isspace(c) (isspace(c) || (c == '\r') || (c == 0x1a))
1552     char *lpchX, *lpch;
1553
1554     for (lpchX = start, lpch = NULL; *lpchX != '\0'; lpchX++ )
1555     {
1556         if( *lpchX == ',' )
1557         {
1558             if( lpch ) *lpch = '\0'; else *lpchX = '\0';
1559             while( *(++lpchX) )
1560                 if( !XFONT_isspace(*lpchX) ) return lpchX;
1561         }
1562         else if( XFONT_isspace( *lpchX ) && !lpch ) lpch = lpchX;
1563              else lpch = NULL;
1564     }
1565     if( lpch ) *lpch = '\0';
1566     return NULL;
1567 #undef XFONT_isspace
1568 }
1569
1570 /***********************************************************************
1571  *           XFONT_LoadAliases
1572  *
1573  * INIT ONLY 
1574  *
1575  * Create font aliases for some standard windows fonts using user's
1576  * default choice of (sans-)serif fonts
1577  *
1578  * Read user-defined aliases from wine.conf. Format is as follows
1579  *
1580  * Alias# = [Windows font name],[LFD font name], <substitute original name>
1581  *
1582  * Example:
1583  *   Alias0 = Arial, -adobe-helvetica- 
1584  *   Alias1 = Times New Roman, -bitstream-courier-, 1
1585  *   ...
1586  *
1587  * Note that from 970817 and on we have built-in alias templates that take
1588  * care of the necessary Windows typefaces.
1589  */
1590 typedef struct
1591 {
1592   LPSTR                 fatResource;
1593   LPSTR                 fatAlias;
1594 } aliasTemplate;
1595
1596 static void XFONT_LoadAliases(void)
1597 {
1598     char *lpResource;
1599     char buffer[MAX_LFD_LENGTH];
1600     int i = 0;
1601     LFD* lfd;
1602     HKEY hkey;
1603
1604     /* built-ins first */
1605     strcpy(buffer, "-bitstream-charter-");
1606     if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1607     {
1608         DWORD type, count = sizeof(buffer);
1609         RegQueryValueExA(hkey, INIDefaultSerif, 0, &type, buffer, &count);
1610         RegCloseKey(hkey);
1611     }
1612     TRACE("Using '%s' as default serif font\n", buffer);
1613     lfd = LFD_Parse(buffer);
1614     /* NB XFONT_InitialCapitals should not change these standard aliases */
1615     if (lfd)
1616     {
1617         XFONT_LoadAlias( lfd, "Tms Roman", FALSE);
1618         XFONT_LoadAlias( lfd, "MS Serif", FALSE);
1619         XFONT_LoadAlias( lfd, "Times New Roman", FALSE);
1620
1621         XFONT_LoadDefaultLFD( lfd, "serif ");
1622         HeapFree(GetProcessHeap(), 0, lfd);
1623     }
1624         
1625     strcpy(buffer, "-adobe-helvetica-");
1626     if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1627     {
1628         DWORD type, count = sizeof(buffer);
1629         RegQueryValueExA(hkey, INIDefaultSansSerif, 0, &type, buffer, &count);
1630         RegCloseKey(hkey);
1631     }
1632     TRACE("Using '%s' as default sans serif font\n", buffer);
1633     lfd = LFD_Parse(buffer);
1634     if (lfd)
1635     {
1636         XFONT_LoadAlias( lfd, "Helv", FALSE);
1637         XFONT_LoadAlias( lfd, "MS Sans Serif", FALSE);
1638         XFONT_LoadAlias( lfd, "MS Shell Dlg", FALSE);
1639         XFONT_LoadAlias( lfd, "System", FALSE);
1640         XFONT_LoadAlias( lfd, "Arial", FALSE);
1641
1642         XFONT_LoadDefaultLFD( lfd, "sans serif ");
1643         HeapFree(GetProcessHeap(), 0, lfd);
1644     }
1645
1646     /* then user specified aliases */
1647     do
1648     {
1649         BOOL bSubst;
1650         char subsection[32];
1651         snprintf( subsection, sizeof subsection, "%s%i", INIAliasSection, i++ );
1652
1653         buffer[0] = 0;
1654         if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1655         {
1656             DWORD type, count = sizeof(buffer);
1657             RegQueryValueExA(hkey, subsection, 0, &type, buffer, &count);
1658             RegCloseKey(hkey);
1659         }
1660
1661         if (!buffer[0])
1662             break;
1663
1664         XFONT_InitialCapitals(buffer);
1665         lpResource = XFONT_GetStringItem( buffer );
1666         bSubst = (XFONT_GetStringItem( lpResource )) ? TRUE : FALSE;
1667         if( lpResource && *lpResource )
1668         {
1669             lfd = LFD_Parse(lpResource);
1670             if (lfd)
1671             {
1672                 XFONT_LoadAlias(lfd, buffer, bSubst);
1673                 HeapFree(GetProcessHeap(), 0, lfd);
1674             }
1675         }
1676         else
1677             WARN("malformed font alias '%s'\n", buffer );
1678     }
1679     while(TRUE);
1680 }
1681
1682 /***********************************************************************
1683  *           XFONT_UnAlias
1684  *
1685  * Convert an (potential) alias into a real windows name
1686  *
1687  */
1688 static LPCSTR XFONT_UnAlias(char* font)
1689 {
1690     if (font[0])
1691     {
1692         fontAlias* fa;
1693         XFONT_InitialCapitals(font); /* to remove extra white space */
1694     
1695         for( fa = aliasTable; fa; fa = fa->next )
1696             /* use case insensitive matching to handle eg "MS Sans Serif" */
1697             if( !strcasecmp( fa->faAlias, font ) ) 
1698             {
1699                 TRACE("found alias '%s'->%s'\n", font, fa->faTypeFace );
1700                 strcpy(font, fa->faTypeFace);
1701                 return fa->faAlias;
1702                 break;
1703             }
1704     }
1705     return NULL;
1706 }
1707
1708 /***********************************************************************
1709  *           XFONT_RemoveFontResource
1710  *
1711  * Caller should check if the font resource is in use. If it is it should
1712  * set FR_REMOVED flag to delay removal until the resource is not in use
1713  * any more.
1714  */
1715 void XFONT_RemoveFontResource( fontResource** ppfr )
1716 {
1717     fontResource* pfr = *ppfr;
1718 #if 0
1719     fontInfo* pfi;
1720
1721     /* FIXME - if fonts were read from a cache, these HeapFrees will fail */
1722     while( pfr->fi )
1723     {
1724         pfi = pfr->fi->next;
1725         HeapFree( GetProcessHeap(), 0, pfr->fi );
1726         pfr->fi = pfi;
1727     }
1728     HeapFree( GetProcessHeap(), 0, pfr );
1729 #endif
1730     *ppfr = pfr->next;
1731 }
1732
1733 /***********************************************************************
1734  *           XFONT_LoadIgnores
1735  *
1736  * INIT ONLY 
1737  *
1738  * Removes specified fonts from the font table to prevent Wine from
1739  * using it.
1740  *
1741  * Ignore# = [LFD font name]
1742  *
1743  * Example:
1744  *   Ignore0 = -misc-nil-
1745  *   Ignore1 = -sun-open look glyph-
1746  *   ...
1747  *
1748  */
1749 static void XFONT_LoadIgnore(char* lfdname)
1750 {
1751     fontResource** ppfr;
1752
1753     LFD* lfd = LFD_Parse(lfdname);
1754     if (lfd && lfd->foundry && lfd->family)
1755     {
1756         for( ppfr = &fontList; *ppfr ; ppfr = &((*ppfr)->next))
1757         {
1758             if( XFONT_SameFoundryAndFamily( (*ppfr)->resource, lfd) )
1759             {
1760                 TRACE("Ignoring '-%s-%s-'\n",
1761                       (*ppfr)->resource->foundry, (*ppfr)->resource->family  );
1762                         
1763                 XFONT_RemoveFontResource( ppfr );
1764                 break;
1765             }
1766         }
1767     }
1768     else
1769         WARN("Malformed font resource\n");
1770     
1771     HeapFree(GetProcessHeap(), 0, lfd);
1772 }
1773
1774 static void XFONT_LoadIgnores(void)
1775 {
1776     int i = 0;
1777     char  subsection[32];
1778     char buffer[MAX_LFD_LENGTH];
1779
1780     /* Standard one that noone wants */
1781     strcpy(buffer, "-misc-nil-");
1782     XFONT_LoadIgnore(buffer);
1783
1784     /* Others from INI file */
1785     do
1786     {
1787         HKEY hkey;
1788         sprintf( subsection, "%s%i", INIIgnoreSection, i++ );
1789
1790         buffer[0] = 0;
1791         if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1792         {
1793             DWORD type, count = sizeof(buffer);
1794             RegQueryValueExA(hkey, subsection, 0, &type, buffer, &count);
1795             RegCloseKey(hkey);
1796         }
1797
1798         if( buffer[0] )
1799         {
1800             char* pch = buffer;
1801             while( *pch && isspace(*pch) ) pch++;
1802             XFONT_LoadIgnore(pch);
1803         }
1804         else 
1805             break;
1806     } while(TRUE);
1807 }
1808
1809
1810 /***********************************************************************
1811  *           XFONT_UserMetricsCache
1812  * 
1813  * Returns expanded name for the cachedmetrics file.
1814  * Now it also appends the current value of the $DISPLAY variable.
1815  */
1816 static char* XFONT_UserMetricsCache( char* buffer, int* buf_size )
1817 {
1818     const char *confdir = get_config_dir();
1819     const char *display_name = XDisplayName(NULL);
1820     int len = strlen(confdir) + strlen(INIFontMetrics) + strlen(display_name) + 2;
1821
1822     if ((len > *buf_size) &&
1823         !(buffer = HeapReAlloc( GetProcessHeap(), 0, buffer, *buf_size = len )))
1824     {
1825         ERR("out of memory\n");
1826         ExitProcess(1);
1827     }
1828
1829     sprintf( buffer, "%s/%s%s", confdir, INIFontMetrics, display_name );
1830     return buffer;
1831 }
1832
1833
1834 /***********************************************************************
1835  *           X Font Matching
1836  *
1837  * Compare two fonts (only parameters set by the XFONT_InitFontInfo()).
1838  */
1839 static INT XFONT_IsSubset(const fontInfo* match, const fontInfo* fi)
1840 {
1841   INT           m;
1842
1843   /* 0 - keep both, 1 - keep match, -1 - keep fi */
1844
1845   /* Compare dfItalic, Underline, Strikeout, Weight, Charset */
1846   m = (BYTE*)&fi->df.dfPixWidth - (BYTE*)&fi->df.dfItalic;
1847   if( memcmp(&match->df.dfItalic, &fi->df.dfItalic, m )) return 0;
1848
1849   if( (!((fi->fi_flags & FI_SCALABLE) + (match->fi_flags & FI_SCALABLE))
1850        && fi->lfd_height != match->lfd_height) ||
1851       (!((fi->fi_flags & FI_POLYWEIGHT) + (match->fi_flags & FI_POLYWEIGHT))
1852        && fi->df.dfWeight != match->df.dfWeight) ) return 0;
1853
1854   m = (int)(match->fi_flags & (FI_POLYWEIGHT | FI_SCALABLE)) -
1855       (int)(fi->fi_flags & (FI_SCALABLE | FI_POLYWEIGHT));
1856
1857   if( m == (FI_POLYWEIGHT - FI_SCALABLE) ||
1858       m == (FI_SCALABLE - FI_POLYWEIGHT) ) return 0;    /* keep both */
1859   else if( m >= 0 ) return 1;   /* 'match' is better */
1860
1861   return -1;                    /* 'fi' is better */
1862 }
1863
1864 /***********************************************************************
1865  *            XFONT_CheckFIList
1866  *
1867  * REMOVE_SUBSETS - attach new fi and purge subsets
1868  * UNMARK_SUBSETS - remove subset flags from all fi entries
1869  */
1870 static void XFONT_CheckFIList( fontResource* fr, fontInfo* fi, int action)
1871 {
1872   int           i = 0;
1873   fontInfo*     pfi, *prev;
1874
1875   for( prev = NULL, pfi = fr->fi; pfi; )
1876   {
1877     if( action == REMOVE_SUBSETS )
1878     {
1879         if( pfi->fi_flags & FI_SUBSET )
1880         {
1881             fontInfo* subset = pfi;
1882
1883             i++;
1884             fr->fi_count--;
1885             if( prev ) prev->next = pfi = pfi->next;
1886             else fr->fi = pfi = pfi->next;
1887             HeapFree( GetProcessHeap(), 0, subset );
1888             continue;
1889         }
1890     }
1891     else pfi->fi_flags &= ~FI_SUBSET;
1892
1893     prev = pfi; 
1894     pfi = pfi->next;
1895   }
1896
1897   if( action == REMOVE_SUBSETS )        /* also add the superset */
1898   {
1899     if( fi->fi_flags & FI_SCALABLE )
1900     {
1901         fi->next = fr->fi;
1902         fr->fi = fi;
1903     }
1904     else if( prev ) prev->next = fi; else fr->fi = fi;
1905     fr->fi_count++;
1906   }
1907
1908   if( i ) TRACE("\t    purged %i subsets [%i]\n", i , fr->fi_count);
1909 }
1910
1911 /***********************************************************************
1912  *            XFONT_FindFIList
1913  */
1914 static fontResource* XFONT_FindFIList( fontResource* pfr, const char* pTypeFace )
1915 {
1916   while( pfr )
1917   {
1918     if( !strcasecmp( pfr->lfFaceName, pTypeFace ) ) break;
1919     pfr = pfr->next;
1920   }
1921   /* Give the app back the font name it asked for. Encarta checks this. */
1922   if (pfr) strcpy(pfr->lfFaceName,pTypeFace);
1923   return pfr;
1924 }
1925
1926 /***********************************************************************
1927  *           XFONT_FixupPointSize
1928  */
1929 static void XFONT_FixupPointSize(fontInfo* fi)
1930 {
1931 #define df (fi->df)
1932     df.dfHorizRes = df.dfVertRes = fi->lfd_resolution;
1933     df.dfPoints = (INT16)
1934         (((INT)(df.dfPixHeight - df.dfInternalLeading) * 72 + (df.dfVertRes >> 1)) /
1935          df.dfVertRes );
1936 #undef df
1937 }
1938
1939 /***********************************************************************
1940  *           XFONT_BuildMetrics
1941  * 
1942  * Build font metrics from X font
1943  */
1944 static int XFONT_BuildMetrics(char** x_pattern, int res, unsigned x_checksum, int x_count)
1945 {
1946     int           i;
1947     fontInfo*     fi = NULL;
1948     fontResource* fr, *pfr;
1949     int           n_ff = 0;
1950
1951     MESSAGE("Building font metrics. This may take some time...\n");
1952     for( i = 0; i < x_count; i++ )
1953     {
1954         char*         typeface;
1955         LFD*          lfd;
1956         int           j;
1957         char          buffer[MAX_LFD_LENGTH];
1958         char*         lpstr;
1959         XFontStruct*  x_fs;
1960         fontInfo*    pfi;
1961
1962         typeface = HEAP_strdupA(GetProcessHeap(), 0, x_pattern[i]);
1963         if (!typeface)
1964             break;
1965
1966         lfd = LFD_Parse(typeface);
1967         if (!lfd)
1968         {
1969             HeapFree(GetProcessHeap(), 0, typeface);
1970             continue;
1971         }
1972
1973         /* find a family to insert into */
1974           
1975         for( pfr = NULL, fr = fontList; fr; fr = fr->next )
1976         {
1977             if( XFONT_SameFoundryAndFamily(fr->resource, lfd))
1978                 break;
1979             pfr = fr;
1980         }  
1981         
1982         if( !fi ) fi = (fontInfo*) HeapAlloc(GetProcessHeap(), 0, sizeof(fontInfo));
1983         
1984         if( !LFD_InitFontInfo( fi, lfd, x_pattern[i]) )
1985             goto nextfont;
1986             
1987         if( !fr ) /* add new family */
1988         {
1989             n_ff++;
1990             fr = (fontResource*) HeapAlloc(GetProcessHeap(), 0, sizeof(fontResource)); 
1991             if (fr)
1992             {
1993                 memset(fr, 0, sizeof(fontResource));
1994               
1995                 fr->resource = (LFD*) HeapAlloc(GetProcessHeap(), 0, sizeof(LFD)); 
1996                 memset(fr->resource, 0, sizeof(LFD));
1997               
1998                 TRACE("family: -%s-%s-\n", lfd->foundry, lfd->family );
1999                 fr->resource->foundry = HEAP_strdupA(GetProcessHeap(), 0, lfd->foundry);
2000                 fr->resource->family = HEAP_strdupA(GetProcessHeap(), 0, lfd->family);
2001                 fr->resource->weight = "";
2002
2003                 if( pfr ) pfr->next = fr;
2004                 else fontList = fr;
2005             }
2006             else
2007                 WARN("Not enough memory for a new font family\n");
2008         }
2009
2010         /* check if we already have something better than "fi" */
2011         
2012         for( pfi = fr->fi, j = 0; pfi && j <= 0; pfi = pfi->next ) 
2013             if( (j = XFONT_IsSubset( pfi, fi )) < 0 ) 
2014                 pfi->fi_flags |= FI_SUBSET; /* superseded by "fi" */
2015         if( j > 0 ) goto nextfont;
2016         
2017         /* add new font instance "fi" to the "fr" font resource */
2018         
2019         if( fi->fi_flags & FI_SCALABLE )
2020         {
2021             LFD lfd1;
2022             char pxl_string[4], res_string[4]; 
2023             /* set scalable font height to get an basis for extrapolation */
2024
2025             fi->lfd_height = DEF_SCALABLE_HEIGHT;
2026             fi->lfd_resolution = res;
2027
2028             sprintf(pxl_string, "%d", fi->lfd_height);
2029             sprintf(res_string, "%d", fi->lfd_resolution);
2030            
2031             lfd1 = *lfd;
2032             lfd1.pixel_size = pxl_string;
2033             lfd1.point_size = "*";
2034             lfd1.resolution_x = res_string;
2035             lfd1.resolution_y = res_string;
2036
2037             LFD_UnParse(buffer, sizeof buffer, &lfd1);
2038             
2039             lpstr = buffer;
2040         }
2041         else lpstr = x_pattern[i];
2042
2043         if( (x_fs = TSXLoadQueryFont(gdi_display, lpstr)) )
2044         {             
2045             XFONT_SetFontMetric( fi, fr, x_fs );
2046             TSXFreeFont( gdi_display, x_fs );
2047
2048             XFONT_FixupPointSize(fi);
2049
2050             TRACE("\t[% 2ipt] '%s'\n", fi->df.dfPoints, x_pattern[i] );
2051               
2052             XFONT_CheckFIList( fr, fi, REMOVE_SUBSETS );
2053             fi = NULL;  /* preventing reuse */
2054         }
2055         else
2056         {
2057             ERR("failed to load %s\n", lpstr );
2058
2059             XFONT_CheckFIList( fr, fi, UNMARK_SUBSETS );
2060         }
2061     nextfont:
2062         HeapFree(GetProcessHeap(), 0, lfd);
2063         HeapFree(GetProcessHeap(), 0, typeface);
2064     }
2065     if( fi ) HeapFree(GetProcessHeap(), 0, fi);
2066
2067     /* Scan through the font list and remove FontResorce(s) (fr) 
2068      * that have no associated Fontinfo(s) (fi). 
2069      * This code is necessary because XFONT_ReadCachedMetrics
2070      * assumes that there is at least one fi associated with a fr.  
2071      * This assumption is invalid for TT font
2072      *  -altsys-ms outlook-medium-r-normal--0-0-0-0-p-0-microsoft-symbol.
2073      */
2074     
2075     fr = fontList;
2076     
2077     while (!fr->fi_count) 
2078     {
2079        fontList = fr->next;
2080     
2081        HeapFree(GetProcessHeap(), 0, fr->resource);
2082        HeapFree(GetProcessHeap(), 0, fr);
2083        
2084        fr = fontList;
2085        n_ff--;
2086     }
2087             
2088     fr = fontList;
2089     
2090     while (fr->next)
2091     {
2092         if (!fr->next->fi_count)
2093         {
2094             pfr = fr->next;
2095             fr->next = fr->next->next;
2096                             
2097             HeapFree(GetProcessHeap(), 0, pfr->resource);
2098             HeapFree(GetProcessHeap(), 0, pfr);
2099         
2100             n_ff--;
2101         }
2102         else 
2103             fr = fr->next; 
2104     }  
2105           
2106     return n_ff;
2107 }
2108
2109 /***********************************************************************
2110  *           XFONT_ReadCachedMetrics
2111  *
2112  * INIT ONLY
2113  */
2114 static BOOL XFONT_ReadCachedMetrics( int fd, int res, unsigned x_checksum, int x_count )
2115 {
2116     if( fd >= 0 )
2117     {
2118         unsigned u;
2119         int i, j;
2120
2121         /* read checksums */
2122         read( fd, &u, sizeof(unsigned) );
2123         read( fd, &i, sizeof(int) );
2124
2125         if( u == x_checksum && i == x_count )
2126         {
2127             off_t length, offset = 3 * sizeof(int);
2128
2129             /* read total size */
2130             read( fd, &i, sizeof(int) );
2131             length = lseek( fd, 0, SEEK_END );
2132
2133             if( length == (i + offset) )
2134             {
2135                 lseek( fd, offset, SEEK_SET );
2136                 fontList = (fontResource*)HeapAlloc( GetProcessHeap(), 0, i);
2137                 if( fontList )
2138                 {
2139                     fontResource*       pfr = fontList;
2140                     fontInfo*           pfi = NULL;
2141
2142                     TRACE("Reading cached font metrics:\n");
2143
2144                     read( fd, fontList, i); /* read all metrics at once */
2145                     while( offset < length )
2146                     {
2147                         offset += sizeof(fontResource) + sizeof(fontInfo);
2148                         pfr->fi = pfi = (fontInfo*)(pfr + 1);
2149                         j = 1;
2150                         while( TRUE )
2151                         {
2152                            if( offset > length ||
2153                                pfi->cptable >= (UINT16)X11DRV_CPTABLE_COUNT ||
2154                               (int)(pfi->next) != j++ ) goto fail;
2155
2156                            if( pfi->df.dfPixHeight == 0 ) goto fail;
2157
2158                            pfi->df.dfFace = pfr->lfFaceName;
2159                            if( pfi->fi_flags & FI_SCALABLE )
2160                            {
2161                                /* we can pretend we got this font for any resolution */
2162                                pfi->lfd_resolution = res;
2163                                XFONT_FixupPointSize(pfi);
2164                            }
2165                            pfi->next = pfi + 1;
2166
2167                            if( j > pfr->fi_count ) break;
2168
2169                            pfi = pfi->next;
2170                            offset += sizeof(fontInfo);
2171                         }
2172                         pfi->next = NULL;
2173                         if( pfr->next )
2174                         {
2175                             pfr->next = (fontResource*)(pfi + 1);
2176                             pfr = pfr->next;
2177                         } 
2178                         else break;
2179                     }
2180                     if( pfr->next == NULL &&
2181                         *(int*)(pfi + 1) == X_FMC_MAGIC )
2182                     {
2183                         /* read LFD stubs */
2184                         char* lpch = (char*)((int*)(pfi + 1) + 1);
2185                         offset += sizeof(int);
2186                         for( pfr = fontList; pfr; pfr = pfr->next )
2187                         {
2188                             size_t len = strlen(lpch) + 1;
2189                             TRACE("\t%s, %i instances\n", lpch, pfr->fi_count );
2190                             pfr->resource = LFD_Parse(lpch);
2191                             lpch += len;
2192                             offset += len;
2193                             if (offset > length)
2194                                 goto fail;
2195                         }
2196                         close( fd );
2197                         return TRUE;
2198                     }
2199                 }
2200             }
2201         }
2202 fail:
2203         if( fontList ) HeapFree( GetProcessHeap(), 0, fontList );
2204         fontList = NULL;
2205         close( fd );
2206     }
2207     return FALSE;
2208 }
2209
2210 /***********************************************************************
2211  *           XFONT_WriteCachedMetrics
2212  *
2213  * INIT ONLY
2214  */
2215 static BOOL XFONT_WriteCachedMetrics( int fd, unsigned x_checksum, int x_count, int n_ff )
2216 {
2217     fontResource* pfr;
2218     fontInfo* pfi;
2219
2220     if( fd >= 0 )
2221     {
2222         int  i, j, k;
2223         char buffer[MAX_LFD_LENGTH];
2224
2225         /* font metrics file:
2226          *
2227          * +0000 x_checksum
2228          * +0004 x_count
2229          * +0008 total size to load
2230          * +000C prepackaged font metrics
2231          * ...
2232          * +...x        X_FMC_MAGIC
2233          * +...x + 4    LFD stubs
2234          */
2235
2236         write( fd, &x_checksum, sizeof(unsigned) );
2237         write( fd, &x_count, sizeof(int) );
2238
2239         for( j = i = 0, pfr = fontList; pfr; pfr = pfr->next ) 
2240         {
2241             LFD_UnParse(buffer, sizeof buffer, pfr->resource);
2242             i += strlen( buffer) + 1;
2243             j += pfr->fi_count;
2244         }
2245         i += n_ff * sizeof(fontResource) + j * sizeof(fontInfo) + sizeof(int);
2246         write( fd, &i, sizeof(int) );
2247
2248         TRACE("Writing font cache:\n");
2249
2250         for( pfr = fontList; pfr; pfr = pfr->next )
2251         {
2252             fontInfo fi;
2253
2254             TRACE("\t-%s-%s-, %i instances\n", pfr->resource->foundry, pfr->resource->family, pfr->fi_count );
2255
2256             i = write( fd, pfr, sizeof(fontResource) );
2257             if( i == sizeof(fontResource) ) 
2258             {
2259                 for( k = 1, pfi = pfr->fi; pfi; pfi = pfi->next )
2260                 {
2261                     fi = *pfi;
2262
2263                     fi.df.dfFace = NULL;
2264                     fi.next = (fontInfo*)k;     /* loader checks this */
2265
2266                     j = write( fd, &fi, sizeof(fi) );
2267                     k++;
2268                 }
2269                 if( j == sizeof(fontInfo) ) continue;
2270             }
2271             break;
2272         }
2273         if( i == sizeof(fontResource) && j == sizeof(fontInfo) )
2274         {
2275             i = j = X_FMC_MAGIC;
2276             write( fd, &i, sizeof(int) );
2277             for( pfr = fontList; pfr && i == j; pfr = pfr->next )
2278             {
2279                 LFD_UnParse(buffer, sizeof buffer, pfr->resource);
2280                 i = strlen( buffer ) + 1;
2281                 j = write( fd, buffer, i );
2282             }
2283         }
2284         close( fd );
2285         return ( i == j );
2286     }
2287     return FALSE;
2288 }
2289
2290 /***********************************************************************
2291  *           XFONT_GetPointResolution()
2292  *
2293  * INIT ONLY
2294  *
2295  * Here we initialize DefResolution which is used in the
2296  * XFONT_Match() penalty function. We also load the point
2297  * resolution value (higher values result in larger fonts).
2298  */
2299 static int XFONT_GetPointResolution( DeviceCaps* pDevCaps )
2300 {
2301     int i, j, point_resolution, num = 3; 
2302     int allowed_xfont_resolutions[3] = { 72, 75, 100 };
2303     int best = 0, best_diff = 65536;
2304     HKEY hkey;
2305
2306     point_resolution = 0;
2307
2308     if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
2309     {
2310         char buffer[20];
2311         DWORD type, count = sizeof(buffer);
2312         if(!RegQueryValueExA(hkey, INIResolution, 0, &type, buffer, &count))
2313             point_resolution = atoi(buffer);
2314         RegCloseKey(hkey);
2315     }
2316
2317     if( !point_resolution )
2318         point_resolution = pDevCaps->logPixelsY;
2319     else
2320         pDevCaps->logPixelsX = pDevCaps->logPixelsY = point_resolution;
2321
2322
2323     /* FIXME We can only really guess at a best DefResolution
2324      * - this should be configurable
2325      */
2326     for( i = best = 0; i < num; i++ )
2327     {
2328         j = abs( point_resolution - allowed_xfont_resolutions[i] );
2329         if( j < best_diff )
2330         {
2331             best = i;
2332             best_diff = j;
2333         }
2334     }
2335     DefResolution = allowed_xfont_resolutions[best];
2336
2337     /* FIXME - do win95,nt40,... do this as well ? */
2338     if (TWEAK_WineLook == WIN98_LOOK)
2339     {
2340         /* Lie about the screen size, so that eg MM_LOMETRIC becomes MM_logical_LOMETRIC */
2341         int denom;
2342         denom = pDevCaps->logPixelsX * 10;
2343         pDevCaps->horzSize = (pDevCaps->horzRes * 254 + (denom>>1)) / denom;
2344         denom = pDevCaps->logPixelsY * 10;
2345         pDevCaps->vertSize = (pDevCaps->vertRes * 254 + (denom>>1)) / denom;
2346     }
2347
2348     return point_resolution;
2349 }
2350
2351
2352 /***********************************************************************
2353  *            XFONT_Match
2354  *
2355  * Compute the matching score between the logical font and the device font.
2356  *
2357  * contributions from highest to lowest:
2358  *      charset
2359  *      fixed pitch
2360  *      height
2361  *      family flags (only when the facename is not present)
2362  *      width
2363  *      weight, italics, underlines, strikeouts
2364  *
2365  * NOTE: you can experiment with different penalty weights to see what happens.
2366  * http://premium.microsoft.com/msdn/library/techart/f365/f36b/f37b/d38b/sa8bf.htm
2367  */
2368 static UINT XFONT_Match( fontMatch* pfm )
2369 {
2370    fontInfo*    pfi = pfm->pfi;         /* device font to match */
2371    LPLOGFONT16  plf = pfm->plf;         /* wanted logical font */
2372    UINT       penalty = 0;
2373    BOOL       bR6 = pfm->flags & FO_MATCH_XYINDEP;    /* from TextCaps */
2374    BOOL       bScale = pfi->fi_flags & FI_SCALABLE;
2375    int d = 0, height;
2376
2377    TRACE("\t[ %-2ipt h=%-3i w=%-3i %s%s]\n", pfi->df.dfPoints,
2378                  pfi->df.dfPixHeight, pfi->df.dfAvgWidth,
2379                 (pfi->df.dfWeight > FW_NORMAL) ? "Bold " : "Normal ",
2380                 (pfi->df.dfItalic) ? "Italic" : "" );
2381
2382    pfm->flags &= FO_MATCH_MASK;
2383
2384 /* Charset */
2385    /* pfm->internal_charset: given(required) charset */
2386    /* pfi->internal_charset: charset of this font */
2387    if (pfi->internal_charset == DEFAULT_CHARSET)
2388    {
2389       /* special case(unicode font) */
2390       /* priority: unmatched charset < unicode < matched charset */
2391       penalty += 0x50;
2392    }
2393    else
2394    {
2395      if( pfm->internal_charset == DEFAULT_CHARSET )
2396      {
2397         /*
2398          if (pfi->internal_charset != ANSI_CHARSET)
2399             penalty += 0x200;
2400         */
2401         if ( pfi->codepage != GetACP() )
2402             penalty += 0x200;
2403      }
2404      else if (pfm->internal_charset != pfi->internal_charset)
2405      {
2406        if ( pfi->internal_charset & 0xff00 )
2407          penalty += 0x1000; /* internal charset - should not be used */
2408        else
2409          penalty += 0x200;
2410      }
2411    }
2412
2413 /* Height */
2414    height = -1;
2415    {
2416        if( plf->lfHeight > 0 )
2417        {
2418            int h = pfi->df.dfPixHeight;
2419            d = h - plf->lfHeight;
2420            height = plf->lfHeight;
2421        }
2422        else
2423        {
2424            int h = pfi->df.dfPixHeight - pfi->df.dfInternalLeading;
2425            if (h)
2426            {
2427                d = h + plf->lfHeight;
2428                height = (-plf->lfHeight * pfi->df.dfPixHeight) / h;
2429            }
2430            else
2431            {
2432                ERR("PixHeight == InternalLeading\n");
2433                penalty += 0x1000; /* dont want this */
2434            }
2435        }
2436    }
2437
2438    if( height == 0 )
2439        pfm->height = 1; /* Very small */
2440    else if( d )
2441    {
2442        if( bScale )
2443            pfm->height = height;
2444        else if( (plf->lfQuality != PROOF_QUALITY) && bR6 )
2445        {
2446            if( d > 0 )  /* do not shrink raster fonts */
2447            {
2448                pfm->height = pfi->df.dfPixHeight;
2449                penalty += (pfi->df.dfPixHeight - height) * 0x4;
2450            }
2451            else         /* expand only in integer multiples */
2452            {
2453                pfm->height = height - height%pfi->df.dfPixHeight;
2454                penalty += (height - pfm->height + 1) * height / pfi->df.dfPixHeight;
2455            }
2456        }
2457        else /* can't be scaled at all */
2458        {
2459            if( plf->lfQuality != PROOF_QUALITY) pfm->flags |= FO_SYNTH_HEIGHT;
2460            pfm->height = pfi->df.dfPixHeight;
2461            penalty += (d > 0)? d * 0x8 : -d * 0x10;
2462        }
2463    }
2464    else
2465        pfm->height = pfi->df.dfPixHeight;
2466
2467 /* Pitch and Family */
2468    if( pfm->flags & FO_MATCH_PAF ) {
2469        int family = plf->lfPitchAndFamily & FF_FAMILY;
2470
2471        /* TMPF_FIXED_PITCH means exactly the opposite */
2472        if( plf->lfPitchAndFamily & FIXED_PITCH ) {
2473            if( pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH ) penalty += 0x100;
2474        } else /* Variable is the default */
2475            if( !(pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH) ) penalty += 0x2;
2476
2477        if (family != FF_DONTCARE && family != (pfi->df.dfPitchAndFamily & FF_FAMILY) )
2478            penalty += 0x10;
2479    }
2480
2481 /* Width */
2482    if( plf->lfWidth )
2483    {
2484        int h;
2485        if( bR6 || bScale ) h = 0; 
2486        else
2487        {
2488            /* FIXME: not complete */
2489
2490            pfm->flags |= FO_SYNTH_WIDTH;
2491            h = abs(plf->lfWidth - (pfm->height * pfi->df.dfAvgWidth)/pfi->df.dfPixHeight);
2492        }
2493        penalty += h * ( d ) ? 0x2 : 0x1 ;
2494    }
2495    else if( !(pfi->fi_flags & FI_NORMAL) ) penalty++;
2496
2497 /* Weight */
2498    if( plf->lfWeight != FW_DONTCARE )
2499    {
2500        penalty += abs(plf->lfWeight - pfi->df.dfWeight) / 40;
2501        if( plf->lfWeight > pfi->df.dfWeight ) pfm->flags |= FO_SYNTH_BOLD;
2502    } else if( pfi->df.dfWeight >= FW_BOLD ) penalty++;  /* choose normal by default */
2503
2504 /* Italic */
2505    if( plf->lfItalic != pfi->df.dfItalic )
2506    {
2507        penalty += 0x4;
2508        pfm->flags |= FO_SYNTH_ITALIC;
2509    }
2510 /* Underline */
2511    if( plf->lfUnderline ) pfm->flags |= FO_SYNTH_UNDERLINE;
2512
2513 /* Strikeout */   
2514    if( plf->lfStrikeOut ) pfm->flags |= FO_SYNTH_STRIKEOUT;
2515
2516
2517    if( penalty && !bScale && pfi->lfd_resolution != DefResolution ) 
2518        penalty++;
2519
2520    TRACE("  returning %i\n", penalty );
2521
2522    return penalty;
2523 }
2524
2525 /***********************************************************************
2526  *            XFONT_MatchFIList
2527  *
2528  * Scan a particular font resource for the best match.
2529  */
2530 static UINT XFONT_MatchFIList( fontMatch* pfm )
2531 {
2532   BOOL        skipRaster = (pfm->flags & FO_MATCH_NORASTER);
2533   UINT        current_score, score = (UINT)(-1);
2534   fontMatch   fm = *pfm;
2535
2536   for( fm.pfi = pfm->pfr->fi; fm.pfi && score; fm.pfi = fm.pfi->next)
2537   {
2538      if( skipRaster && !(fm.pfi->fi_flags & FI_SCALABLE) )
2539          continue;
2540
2541      current_score = XFONT_Match( &fm );
2542      if( score > current_score )
2543      {
2544         *pfm = fm;
2545         score = current_score;
2546      }
2547   }
2548   return score;
2549 }
2550
2551 /***********************************************************************
2552  *          XFONT_MatchDeviceFont
2553  *
2554  * Scan font resource tree.
2555  *
2556  */
2557 static void XFONT_MatchDeviceFont( fontResource* start, fontMatch* pfm)
2558 {
2559     fontMatch           fm = *pfm;
2560     UINT          current_score, score = (UINT)(-1);
2561     fontResource**      ppfr;
2562     
2563     TRACE("(%u) '%s' h=%i weight=%i %s\n",
2564           pfm->plf->lfCharSet, pfm->plf->lfFaceName, pfm->plf->lfHeight, 
2565           pfm->plf->lfWeight, (pfm->plf->lfItalic) ? "Italic" : "" );
2566
2567     pfm->pfi = NULL;
2568     if( fm.plf->lfFaceName[0] ) 
2569     {
2570         fm.pfr = XFONT_FindFIList( start, fm.plf->lfFaceName);
2571         if( fm.pfr ) /* match family */
2572         {
2573             TRACE("found facename '%s'\n", fm.pfr->lfFaceName );
2574             
2575             if( fm.pfr->fr_flags & FR_REMOVED )
2576                 fm.pfr = 0;
2577             else
2578             {
2579                 XFONT_MatchFIList( &fm );
2580                 *pfm = fm;
2581                 if (pfm->pfi)
2582                     return;
2583             }
2584         }
2585
2586         /* get charset if lfFaceName is one of known facenames. */
2587         {
2588             const struct CharsetBindingInfo* pcharsetbindings;
2589
2590             pcharsetbindings = &charsetbindings[0];
2591             while ( pcharsetbindings->pszFaceName != NULL )
2592             {
2593                 if ( !strcmp( pcharsetbindings->pszFaceName,
2594                               fm.plf->lfFaceName ) )
2595                 {
2596                     fm.internal_charset = pcharsetbindings->charset;
2597                     break;
2598                 }
2599                 pcharsetbindings ++;
2600             }
2601             TRACE( "%s charset %u\n", fm.plf->lfFaceName, fm.internal_charset );
2602         }
2603     }
2604
2605     /* match all available fonts */
2606
2607     fm.flags |= FO_MATCH_PAF;
2608     for( ppfr = &fontList; *ppfr && score; ppfr = &(*ppfr)->next )
2609     {
2610         if( (*ppfr)->fr_flags & FR_REMOVED )
2611         {
2612             if( (*ppfr)->fo_count == 0 )
2613                 XFONT_RemoveFontResource( ppfr );
2614             continue;
2615         }
2616         
2617         fm.pfr = *ppfr;
2618         
2619         TRACE("%s\n", fm.pfr->lfFaceName );
2620             
2621         current_score = XFONT_MatchFIList( &fm );
2622         if( current_score < score )
2623         {
2624             score = current_score;
2625             *pfm = fm;
2626         }
2627     }
2628 }
2629
2630
2631 /***********************************************************************
2632  *           X Font Cache
2633  */
2634 static void XFONT_GrowFreeList(int start, int end)
2635 {
2636    /* add all entries from 'start' up to and including 'end' */
2637
2638    memset( fontCache + start, 0, (end - start + 1) * sizeof(fontObject) );
2639
2640    fontCache[end].lru = fontLF;
2641    fontCache[end].count = -1;
2642    fontLF = start;
2643    while( start < end )
2644    {
2645         fontCache[start].count = -1;
2646         fontCache[start].lru = start + 1;
2647         start++;
2648    } 
2649 }
2650
2651 static fontObject* XFONT_LookupCachedFont( const LPLOGFONT16 plf, UINT16* checksum )
2652 {
2653     UINT16      cs = __lfCheckSum( plf );
2654     int         i = fontMRU, prev = -1;
2655    
2656    *checksum = cs;
2657     while( i >= 0 )
2658     {
2659         if( fontCache[i].lfchecksum == cs &&
2660           !(fontCache[i].fo_flags & FO_REMOVED) )
2661         {
2662             /* FIXME: something more intelligent here ? */
2663
2664             if( !memcmp( plf, &fontCache[i].lf,
2665                          sizeof(LOGFONT16) - LF_FACESIZE ) &&
2666                 !strcmp( plf->lfFaceName, fontCache[i].lf.lfFaceName) )
2667             {
2668                 /* remove temporarily from the lru list */
2669                 if( prev >= 0 )
2670                     fontCache[prev].lru = fontCache[i].lru;
2671                 else 
2672                     fontMRU = (INT16)fontCache[i].lru;
2673                 return (fontCache + i);
2674             }
2675         }
2676         prev = i;
2677         i = (INT16)fontCache[i].lru;
2678     }
2679     return NULL;
2680 }
2681
2682 static fontObject* XFONT_GetCacheEntry(void)
2683 {
2684     int         i;
2685
2686     if( fontLF == -1 )
2687     {
2688         int     prev_i, prev_j, j;
2689
2690         TRACE("font cache is full\n");
2691
2692         /* lookup the least recently used font */
2693
2694         for( prev_i = prev_j = j = -1, i = fontMRU; i >= 0; i = (INT16)fontCache[i].lru )
2695         {
2696             if( fontCache[i].count <= 0 &&
2697               !(fontCache[i].fo_flags & FO_SYSTEM) )
2698             {
2699                 prev_j = prev_i;
2700                 j = i;
2701             }
2702             prev_i = i;
2703         }
2704
2705         if( j >= 0 )    /* unload font */
2706         {
2707             /* detach from the lru list */
2708
2709             TRACE("\tfreeing entry %i\n", j );
2710
2711             fontCache[j].fr->fo_count--;
2712
2713             if( prev_j >= 0 )
2714                 fontCache[prev_j].lru = fontCache[j].lru;
2715             else fontMRU = (INT16)fontCache[j].lru;
2716
2717             /* FIXME: lpXForm, lpPixmap */
2718             if(fontCache[j].lpX11Trans)
2719                 HeapFree( GetProcessHeap(), 0, fontCache[j].lpX11Trans );
2720
2721             TSXFreeFont( gdi_display, fontCache[j].fs );
2722
2723             memset( fontCache + j, 0, sizeof(fontObject) );
2724             return (fontCache + j);
2725         }
2726         else            /* expand cache */
2727         {
2728             fontObject* newCache;
2729
2730             prev_i = fontCacheSize + FONTCACHE;
2731
2732             TRACE("\tgrowing font cache from %i to %i\n", fontCacheSize, prev_i );
2733
2734             if( (newCache = (fontObject*)HeapReAlloc(GetProcessHeap(), 0,  
2735                                                      fontCache, prev_i)) )
2736             {
2737                 i = fontCacheSize;
2738                 fontCacheSize  = prev_i;
2739                 fontCache = newCache;
2740                 XFONT_GrowFreeList( i, fontCacheSize - 1);
2741             } 
2742             else return NULL;
2743         }
2744     }
2745
2746     /* detach from the free list */
2747
2748     i = fontLF;
2749     fontLF = (INT16)fontCache[i].lru;
2750     fontCache[i].count = 0;
2751     return (fontCache + i);
2752 }
2753
2754 static int XFONT_ReleaseCacheEntry(const fontObject* pfo)
2755 {
2756     UINT        u = (UINT)(pfo - fontCache);
2757     int         i;
2758     int         ret;
2759
2760     if( u < fontCacheSize )
2761     {
2762         ret = --fontCache[u].count;
2763         if ( ret == 0 )
2764         {
2765             for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
2766             {
2767                 if( CHECK_PFONT(pfo->prefobjs[i]) )
2768                     XFONT_ReleaseCacheEntry(__PFONT(pfo->prefobjs[i]));
2769             }
2770         }
2771
2772         return ret;
2773     }
2774
2775     return -1;
2776 }
2777
2778 /***********************************************************************
2779  *           X11DRV_FONT_Init
2780  *
2781  * Initialize font resource list and allocate font cache.
2782  */
2783 BOOL X11DRV_FONT_Init( DeviceCaps* pDevCaps )
2784 {
2785   char**    x_pattern;
2786   unsigned  x_checksum;
2787   int       i,res, x_count, fd, buf_size;
2788   char      *buffer;
2789   HKEY hkey;
2790
2791   res = XFONT_GetPointResolution( pDevCaps );
2792       
2793   x_pattern = TSXListFonts(gdi_display, "*", MAX_FONTS, &x_count );
2794
2795   TRACE("Font Mapper: initializing %i fonts [logical dpi=%i, default dpi=%i]\n", 
2796                                     x_count, res, DefResolution);
2797   if (x_count == MAX_FONTS)      
2798       MESSAGE("There may be more fonts available - try increasing the value of MAX_FONTS\n");
2799
2800   for( i = x_checksum = 0; i < x_count; i++ )
2801   {
2802      int j;
2803 #if 0
2804      printf("%i\t: %s\n", i, x_pattern[i] );
2805 #endif
2806
2807      j = strlen( x_pattern[i] );
2808      if( j ) x_checksum ^= __genericCheckSum( x_pattern[i], j );
2809   }
2810   x_checksum |= X_PFONT_MAGIC;
2811   buf_size = 128;
2812   buffer = HeapAlloc( GetProcessHeap(), 0, buf_size );
2813
2814   /* deal with systemwide font metrics cache */
2815
2816   buffer[0] = 0;
2817   if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
2818   {
2819         DWORD type, count = buf_size;
2820         RegQueryValueExA(hkey, INIGlobalMetrics, 0, &type, buffer, &count);
2821         RegCloseKey(hkey);
2822   }
2823
2824   if( buffer[0] )
2825   {
2826       fd = open( buffer, O_RDONLY );
2827       XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2828   }
2829   if (fontList == NULL)
2830   {
2831       /* try per-user */
2832       buffer = XFONT_UserMetricsCache( buffer, &buf_size );
2833       if( buffer[0] )
2834       {
2835           fd = open( buffer, O_RDONLY );
2836           XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2837       }
2838   }
2839
2840   if( fontList == NULL )        /* build metrics from scratch */
2841   {
2842       int n_ff = XFONT_BuildMetrics(x_pattern, DefResolution, x_checksum, x_count);
2843       if( buffer[0] )    /* update cached metrics */
2844       {
2845           fd = open( buffer, O_CREAT | O_TRUNC | O_RDWR, 0644 ); /* -rw-r--r-- */
2846           if( XFONT_WriteCachedMetrics( fd, x_checksum, x_count, n_ff ) == FALSE )
2847           {
2848               WARN("Unable to write to fontcache '%s'\n", buffer);
2849               if( fd >= 0) remove( buffer );    /* couldn't write entire file */
2850           }
2851       }
2852   }
2853
2854   TSXFreeFontNames(x_pattern);
2855
2856   /* check if we're dealing with X11 R6 server */
2857   {
2858       XFontStruct*  x_fs;
2859       strcpy(buffer, "-*-*-*-*-normal-*-[12 0 0 12]-*-72-*-*-*-iso8859-1");
2860       if( (x_fs = TSXLoadQueryFont(gdi_display, buffer)) )
2861       {
2862           XTextCaps |= TC_SF_X_YINDEP;
2863           TSXFreeFont(gdi_display, x_fs);
2864       }
2865   }
2866   HeapFree(GetProcessHeap(), 0, buffer);
2867
2868   XFONT_WindowsNames();
2869   XFONT_LoadAliases();
2870   XFONT_LoadDefaults();
2871   XFONT_LoadIgnores();
2872
2873   /* fontList initialization is over, allocate X font cache */
2874
2875   fontCache = (fontObject*) HeapAlloc(GetProcessHeap(), 0, fontCacheSize * sizeof(fontObject));
2876   XFONT_GrowFreeList(0, fontCacheSize - 1);
2877
2878   TRACE("done!\n");
2879
2880   /* update text caps parameter */
2881
2882   pDevCaps->textCaps = XTextCaps;
2883
2884   RAW_ASCENT  = TSXInternAtom(gdi_display, "RAW_ASCENT", TRUE);
2885   RAW_DESCENT = TSXInternAtom(gdi_display, "RAW_DESCENT", TRUE);
2886   
2887   return TRUE;
2888 }
2889
2890 /**********************************************************************
2891  *      XFONT_SetX11Trans
2892  */
2893 static BOOL XFONT_SetX11Trans( fontObject *pfo )
2894 {
2895   char *fontName;
2896   Atom nameAtom;
2897   LFD* lfd;
2898
2899   TSXGetFontProperty( pfo->fs, XA_FONT, &nameAtom );
2900   fontName = TSXGetAtomName( gdi_display, nameAtom );
2901   lfd = LFD_Parse(fontName);
2902   if (!lfd)
2903   {
2904       TSXFree(fontName);
2905       return FALSE;
2906   }
2907
2908   if (lfd->pixel_size[0] != '[') {
2909       HeapFree(GetProcessHeap(), 0, lfd);
2910       TSXFree(fontName);
2911       return FALSE;
2912   }
2913
2914 #define PX pfo->lpX11Trans
2915
2916   sscanf(lfd->pixel_size, "[%f%f%f%f]", &PX->a, &PX->b, &PX->c, &PX->d);
2917   TSXFree(fontName);
2918   HeapFree(GetProcessHeap(), 0, lfd);
2919
2920   TSXGetFontProperty( pfo->fs, RAW_ASCENT, &PX->RAW_ASCENT );
2921   TSXGetFontProperty( pfo->fs, RAW_DESCENT, &PX->RAW_DESCENT );
2922
2923   PX->pixelsize = hypot(PX->a, PX->b);
2924   PX->ascent = PX->pixelsize / 1000.0 * PX->RAW_ASCENT;
2925   PX->descent = PX->pixelsize / 1000.0 * PX->RAW_DESCENT;
2926
2927   TRACE("[%f %f %f %f] RA = %ld RD = %ld\n",
2928         PX->a, PX->b, PX->c, PX->d,
2929         PX->RAW_ASCENT, PX->RAW_DESCENT);
2930
2931 #undef PX
2932   return TRUE;
2933 }
2934
2935 /***********************************************************************
2936  *           X Device Font Objects
2937  */
2938 static X_PHYSFONT XFONT_RealizeFont( const LPLOGFONT16 plf,
2939                                      LPCSTR* faceMatched, BOOL bSubFont,
2940                                      WORD internal_charset,
2941                                      WORD* pcharsetMatched )
2942 {
2943     UINT16      checksum;
2944     INT         index = 0;
2945     fontObject* pfo;
2946
2947     pfo = XFONT_LookupCachedFont( plf, &checksum );
2948     if( !pfo )
2949     {
2950         fontMatch       fm;
2951         INT             i;
2952
2953         fm.pfr = NULL;
2954         fm.pfi = NULL;
2955         fm.height = 0;
2956         fm.flags = 0;
2957         fm.plf = plf;
2958         fm.internal_charset = internal_charset;
2959
2960         if( XTextCaps & TC_SF_X_YINDEP ) fm.flags = FO_MATCH_XYINDEP;
2961
2962         /* allocate new font cache entry */
2963
2964         if( (pfo = XFONT_GetCacheEntry()) )
2965         {
2966             /* initialize entry and load font */
2967             char lpLFD[MAX_LFD_LENGTH];
2968             UINT uRelaxLevel = 0;
2969
2970             if(abs(plf->lfHeight) > MAX_FONT_SIZE) {
2971                 ERR(
2972   "plf->lfHeight = %d, Creating a 100 pixel font and rescaling metrics \n", 
2973                     plf->lfHeight);
2974                 pfo->rescale = fabs(plf->lfHeight / 100.0);
2975                 if(plf->lfHeight > 0) plf->lfHeight = 100;
2976                 else plf->lfHeight = -100;
2977             } else
2978                 pfo->rescale = 1.0;
2979             
2980             XFONT_MatchDeviceFont( fontList, &fm );
2981             pfo->fr = fm.pfr;
2982             pfo->fi = fm.pfi;
2983             pfo->fr->fo_count++;
2984             pfo->fo_flags = fm.flags & ~FO_MATCH_MASK;
2985
2986             pfo->lf = *plf;
2987             pfo->lfchecksum = checksum;
2988
2989             do
2990             {
2991                 LFD_ComposeLFD( pfo, fm.height, lpLFD, uRelaxLevel++ );
2992                 if( (pfo->fs = TSXLoadQueryFont( gdi_display, lpLFD )) ) break;
2993             } while( uRelaxLevel );
2994
2995                 
2996             if(pfo->lf.lfEscapement != 0) {
2997                 pfo->lpX11Trans = HeapAlloc(GetProcessHeap(), 0, sizeof(XFONTTRANS));
2998                 if(!XFONT_SetX11Trans( pfo )) {
2999                     HeapFree(GetProcessHeap(), 0, pfo->lpX11Trans);
3000                     pfo->lpX11Trans = NULL;
3001                 }
3002             }
3003             XFONT_GetLeading( &pfo->fi->df, pfo->fs,
3004                               &pfo->foInternalLeading, NULL, pfo->lpX11Trans );
3005             pfo->foAvgCharWidth = (INT16)XFONT_GetAvgCharWidth(&pfo->fi->df, pfo->fs, pfo->lpX11Trans );
3006             pfo->foMaxCharWidth = (INT16)XFONT_GetMaxCharWidth(pfo->fs, pfo->lpX11Trans);
3007             
3008             /* FIXME: If we've got a soft font or
3009              * there are FO_SYNTH_... flags for the
3010              * non PROOF_QUALITY request, the engine
3011              * should rasterize characters into mono
3012              * pixmaps and store them in the pfo->lpPixmap
3013              * array (pfo->fs should be updated as well).
3014              * array (pfo->fs should be updated as well).
3015              * X11DRV_ExtTextOut() must be heavily modified 
3016              * to support pixmap blitting and FO_SYNTH_...
3017              * styles.
3018              */
3019
3020             pfo->lpPixmap = NULL;
3021
3022             for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3023                 pfo->prefobjs[i] = (X_PHYSFONT)0xffffffff; /* invalid value */
3024
3025             /* special treatment for DBCS that needs multiple fonts */
3026             /* All member of pfo must be set correctly. */
3027             if ( bSubFont == FALSE )
3028             {
3029                 WORD charset_sub;
3030                 WORD charsetMatchedSub;
3031                 LOGFONT16 lfSub;
3032                 LPCSTR faceMatchedSub;
3033
3034                 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3035                 {
3036                     charset_sub = X11DRV_cptable[pfo->fi->cptable].
3037                                 penum_subfont_charset( i );
3038                     if ( charset_sub == DEFAULT_CHARSET ) break;
3039
3040                     lfSub = *plf;
3041                     lfSub.lfWidth = 0;
3042                    lfSub.lfHeight=plf->lfHeight;
3043                     lfSub.lfCharSet = (BYTE)(charset_sub & 0xff);
3044                     lfSub.lfFaceName[0] = '\0'; /* FIXME? */
3045                     /* this font has sub font */
3046                     if ( i == 0 ) pfo->prefobjs[0] = (X_PHYSFONT)0;
3047                     pfo->prefobjs[i] =
3048                         XFONT_RealizeFont( &lfSub, &faceMatchedSub,
3049                                            TRUE, charset_sub,
3050                                            &charsetMatchedSub );
3051                     /* FIXME: check charsetMatchedSub */
3052                 }
3053             }
3054         }
3055
3056         if( !pfo ) /* couldn't get a new entry, get one of the cached fonts */
3057         {
3058             UINT                current_score, score = (UINT)(-1);
3059
3060             i = index = fontMRU; 
3061             fm.flags |= FO_MATCH_PAF;
3062             do
3063             {
3064                 pfo = fontCache + i;
3065                 fm.pfr = pfo->fr; fm.pfi = pfo->fi;
3066
3067                 current_score = XFONT_Match( &fm );
3068                 if( current_score < score ) index = i;
3069
3070                 i =  pfo->lru;
3071             } while( i >= 0 );
3072             pfo = fontCache + index;
3073             goto END;
3074         }
3075     }
3076
3077     /* attach at the head of the lru list */
3078     pfo->lru = fontMRU;
3079     index = fontMRU = (pfo - fontCache);
3080  
3081 END:
3082     pfo->count++;
3083
3084     TRACE("physfont %i\n", index);
3085     *faceMatched = pfo->fi->df.dfFace;
3086     *pcharsetMatched = pfo->fi->internal_charset;
3087
3088     return (X_PHYSFONT)(X_PFONT_MAGIC | index);
3089 }
3090
3091 /***********************************************************************
3092  *           XFONT_GetFontObject
3093  */
3094 fontObject* XFONT_GetFontObject( X_PHYSFONT pFont )
3095 {
3096     if( CHECK_PFONT(pFont) ) return __PFONT(pFont);
3097     return NULL;
3098 }
3099
3100 /***********************************************************************
3101  *           XFONT_GetFontStruct
3102  */
3103 XFontStruct* XFONT_GetFontStruct( X_PHYSFONT pFont )
3104 {
3105     if( CHECK_PFONT(pFont) ) return __PFONT(pFont)->fs;
3106     return NULL;
3107 }
3108
3109 /***********************************************************************
3110  *           XFONT_GetFontInfo
3111  */
3112 LPIFONTINFO16 XFONT_GetFontInfo( X_PHYSFONT pFont )
3113 {
3114     if( CHECK_PFONT(pFont) ) return &(__PFONT(pFont)->fi->df);
3115     return NULL;
3116 }
3117
3118
3119
3120 /* X11DRV Interface ****************************************************
3121  *                                                                     *
3122  * Exposed via the dc->funcs dispatch table.                           *
3123  *                                                                     *
3124  ***********************************************************************/
3125 /***********************************************************************
3126  *           X11DRV_FONT_SelectObject
3127  */
3128 HFONT X11DRV_FONT_SelectObject( DC* dc, HFONT hfont, FONTOBJ* font )
3129 {
3130     HFONT hPrevFont = 0;
3131     LOGFONT16 lf;
3132     X11DRV_PDEVICE *physDev = (X11DRV_PDEVICE *)dc->physDev;
3133
3134     EnterCriticalSection( &crtsc_fonts_X11 );
3135
3136     if( CHECK_PFONT(physDev->font) ) 
3137         XFONT_ReleaseCacheEntry( __PFONT(physDev->font) );
3138
3139     FONT_LogFontWTo16(&font->logfont, &lf);
3140
3141     /* Make sure we don't change the sign when converting to device coords */
3142     /* FIXME - check that the other drivers do this correctly */
3143     if (lf.lfWidth)
3144     {
3145         lf.lfWidth = GDI_ROUND((FLOAT)lf.lfWidth * fabs(dc->xformWorld2Vport.eM11));
3146         if (lf.lfWidth == 0)
3147             lf.lfWidth = 1; /* Minimum width */
3148     }
3149     if (lf.lfHeight)
3150     {
3151         lf.lfHeight = GDI_ROUND((FLOAT)lf.lfHeight * fabs(dc->xformWorld2Vport.eM22));
3152
3153         if (lf.lfHeight == 0)
3154             lf.lfHeight = MIN_FONT_SIZE;
3155     }
3156     else
3157         lf.lfHeight = -(DEF_POINT_SIZE * dc->devCaps->logPixelsY + (72>>1)) / 72;
3158     
3159     {
3160         /* Fixup aliases before passing to RealizeFont */
3161         /* alias = Windows name in the alias table */
3162         LPCSTR alias = XFONT_UnAlias( lf.lfFaceName );
3163         LPCSTR faceMatched;
3164         WORD charsetMatched;
3165
3166         TRACE("hfont=%04x\n", hfont); /* to connect with the trace from RealizeFont */
3167         physDev->font = XFONT_RealizeFont( &lf, &faceMatched,
3168                                            FALSE, lf.lfCharSet,
3169                                            &charsetMatched );
3170
3171         /* set face to the requested facename if it matched 
3172          * so that GetTextFace can get the correct face name
3173          */
3174         if (alias && !strcmp(faceMatched, lf.lfFaceName))
3175             MultiByteToWideChar(CP_ACP, 0, alias, -1,
3176                                 font->logfont.lfFaceName, LF_FACESIZE);
3177         else
3178             MultiByteToWideChar(CP_ACP, 0, faceMatched, -1,
3179                               font->logfont.lfFaceName, LF_FACESIZE);
3180
3181         /*
3182          * In X, some encodings may have the same lfFaceName.
3183          * for example:
3184          *   -misc-fixed-*-iso8859-1
3185          *   -misc-fixed-*-jisx0208.1990-0
3186          * so charset should be saved...
3187          */
3188         font->logfont.lfCharSet = charsetMatched;
3189     }
3190
3191     hPrevFont = dc->hFont;
3192     dc->hFont = hfont;
3193
3194     LeaveCriticalSection( &crtsc_fonts_X11 );
3195
3196     return hPrevFont;
3197 }
3198
3199
3200 /***********************************************************************
3201  *
3202  *           X11DRV_EnumDeviceFonts
3203  */
3204 BOOL X11DRV_EnumDeviceFonts( HDC hdc, LPLOGFONTW plf, 
3205                              DEVICEFONTENUMPROC proc, LPARAM lp )
3206 {
3207     ENUMLOGFONTEXW      lf;
3208     NEWTEXTMETRICEXW    tm;
3209     fontResource*       pfr = fontList;
3210     BOOL                b, bRet = 0;
3211     LOGFONT16           lf16;
3212
3213
3214     FONT_LogFontWTo16(plf, &lf16);
3215
3216     if( lf16.lfFaceName[0] )
3217     {
3218         /* enum all entries in this resource */
3219         pfr = XFONT_FindFIList( pfr, lf16.lfFaceName );
3220         if( pfr )
3221         {
3222             fontInfo*   pfi;
3223             for( pfi = pfr->fi; pfi; pfi = pfi->next )
3224             {
3225                 /* Note: XFONT_GetFontMetric() will have to
3226                    release the crit section, font list will
3227                    have to be retraversed on return */
3228
3229                 if(lf16.lfCharSet == DEFAULT_CHARSET ||
3230                    lf16.lfCharSet == pfi->df.dfCharSet) {
3231                     if( (b = (*proc)( &lf, &tm, 
3232                                XFONT_GetFontMetric( pfi, &lf, &tm ), lp )) )
3233                         bRet = b;
3234                     else break;
3235                 }
3236             }
3237         }
3238     }
3239     else /* enum first entry in each resource */
3240         for( ; pfr ; pfr = pfr->next )
3241         {
3242             if(pfr->fi)
3243             {
3244                 if( (b = (*proc)( &lf, &tm, 
3245                            XFONT_GetFontMetric( pfr->fi, &lf, &tm ), lp )) )
3246                     bRet = b;
3247                 else break;
3248             }
3249         }
3250     return bRet;
3251 }
3252
3253
3254 /***********************************************************************
3255  *           X11DRV_GetTextMetrics
3256  */
3257 BOOL X11DRV_GetTextMetrics(DC *dc, TEXTMETRICW *metrics)
3258 {
3259     X11DRV_PDEVICE *physDev = (X11DRV_PDEVICE *)dc->physDev;
3260     TEXTMETRICA tmA;
3261
3262     if( CHECK_PFONT(physDev->font) )
3263     {
3264         fontObject* pfo = __PFONT(physDev->font);
3265         X11DRV_cptable[pfo->fi->cptable].pGetTextMetricsA( pfo, &tmA );
3266         FONT_TextMetricAToW(&tmA, metrics);
3267         return TRUE;
3268     }
3269     return FALSE;
3270 }
3271
3272
3273 /***********************************************************************
3274  *           X11DRV_GetCharWidth
3275  */
3276 BOOL X11DRV_GetCharWidth( DC *dc, UINT firstChar, UINT lastChar,
3277                             LPINT buffer )
3278 {
3279     X11DRV_PDEVICE *physDev = (X11DRV_PDEVICE *)dc->physDev;
3280     fontObject* pfo = XFONT_GetFontObject( physDev->font );
3281
3282     if( pfo )
3283     {
3284         int i;
3285
3286         if (pfo->fs->per_char == NULL)
3287             for (i = firstChar; i <= lastChar; i++)
3288                 if(pfo->lpX11Trans)
3289                     *buffer++ = pfo->fs->min_bounds.attributes *
3290                       pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3291                 else
3292                     *buffer++ = pfo->fs->min_bounds.width * pfo->rescale;
3293         else
3294         {
3295             XCharStruct *cs, *def;
3296             static XCharStruct  __null_char = { 0, 0, 0, 0, 0, 0 };
3297
3298             CI_GET_CHAR_INFO(pfo->fs, pfo->fs->default_char, &__null_char,
3299                              def);
3300
3301             for (i = firstChar; i <= lastChar; i++)
3302             {
3303                 if (i >= pfo->fs->min_char_or_byte2 && 
3304                     i <= pfo->fs->max_char_or_byte2)
3305                 {
3306                     cs = &pfo->fs->per_char[(i - pfo->fs->min_char_or_byte2)]; 
3307                     if (CI_NONEXISTCHAR(cs)) cs = def; 
3308                 } else cs = def;
3309                 if(pfo->lpX11Trans)
3310                     *buffer++ = max(cs->attributes, 0) *
3311                       pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3312                 else
3313                     *buffer++ = max(cs->width, 0 ) * pfo->rescale;
3314             }
3315         }
3316
3317         return TRUE;
3318     }
3319     return FALSE;
3320 }