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