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