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