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