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