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