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