janitorial: Pass HEAP_ZERO_MEMORY as flag to HeapAlloc() instead of zeroing out the...
[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 static inline BOOL is_stock_font( HFONT font )
369 {
370     int i;
371     for (i = OEM_FIXED_FONT; i <= DEFAULT_GUI_FONT; i++)
372     {
373         if (i != DEFAULT_PALETTE && font == GetStockObject(i)) return TRUE;
374     }
375     return FALSE;
376 }
377
378
379 static void FONT_LogFontWTo16( const LOGFONTW* font32, LPLOGFONT16 font16 )
380 {
381     font16->lfHeight = font32->lfHeight;
382     font16->lfWidth = font32->lfWidth;
383     font16->lfEscapement = font32->lfEscapement;
384     font16->lfOrientation = font32->lfOrientation;
385     font16->lfWeight = font32->lfWeight;
386     font16->lfItalic = font32->lfItalic;
387     font16->lfUnderline = font32->lfUnderline;
388     font16->lfStrikeOut = font32->lfStrikeOut;
389     font16->lfCharSet = font32->lfCharSet;
390     font16->lfOutPrecision = font32->lfOutPrecision;
391     font16->lfClipPrecision = font32->lfClipPrecision;
392     font16->lfQuality = font32->lfQuality;
393     font16->lfPitchAndFamily = font32->lfPitchAndFamily;
394     WideCharToMultiByte( CP_ACP, 0, font32->lfFaceName, -1,
395                          font16->lfFaceName, LF_FACESIZE, NULL, NULL );
396     font16->lfFaceName[LF_FACESIZE-1] = 0;
397 }
398
399
400 /***********************************************************************
401  *           Checksums
402  */
403 static UINT16   __lfCheckSum( const LOGFONT16 *plf )
404 {
405     CHAR        font[LF_FACESIZE];
406     UINT16      checksum = 0;
407     const UINT16 *ptr;
408     int i;
409
410     ptr = (const UINT16 *)plf;
411     for (i = 0; i < 9; i++) checksum ^= *ptr++;
412     for (i = 0; i < LF_FACESIZE; i++)
413     {
414         font[i] = tolower(plf->lfFaceName[i]);
415         if (!font[i] || font[i] == ' ') break;
416     }
417     for (ptr = (UINT16 *)font, i >>= 1; i > 0; i-- ) checksum ^= *ptr++;
418    return checksum;
419 }
420
421 static UINT16   __genericCheckSum( const void *ptr, int size )
422 {
423    unsigned int checksum = 0;
424    const char *p = (const char *)ptr;
425    while (size-- > 0)
426      checksum ^= (checksum << 3) + (checksum >> 29) + *p++;
427
428    return checksum & 0xffff;
429 }
430
431 /*************************************************************************
432  *           LFD parse/compose routines
433  *
434  * NB. LFD_Parse will use lpFont for its own ends, so if you want to keep it
435  *     make a copy first
436  *
437  * These functions also do TILDE to HYPHEN conversion
438  */
439 static BOOL LFD_Parse(LPSTR lpFont, LFD *lfd)
440 {
441     char *lpch = lpFont, *lfd_fld[LFD_FIELDS], *field_start;
442     int i;
443     if (*lpch != HYPHEN)
444     {
445         WARN("font '%s' doesn't begin with '%c'\n", lpFont, HYPHEN);
446         return FALSE;
447     }
448
449     field_start = ++lpch;
450     for( i = 0; i < LFD_FIELDS; )
451     {
452         if (*lpch == HYPHEN)
453         {
454             *lpch = '\0';
455             lfd_fld[i] = field_start;
456             i++;
457             field_start = ++lpch;
458         }
459         else if (!*lpch)
460         {
461             lfd_fld[i] = field_start;
462             i++;
463             break;
464         }
465         else if (*lpch == TILDE)
466         {
467             *lpch = HYPHEN;
468             ++lpch;
469         }
470         else
471             ++lpch;
472     }
473     /* Fill in the empty fields with NULLS */
474     for (; i< LFD_FIELDS; i++)
475         lfd_fld[i] = NULL;
476     if (*lpch)
477         WARN("Extra ignored in font '%s'\n", lpFont);
478
479     lfd->foundry = lfd_fld[0];
480     lfd->family = lfd_fld[1];
481     lfd->weight = lfd_fld[2];
482     lfd->slant = lfd_fld[3];
483     lfd->set_width = lfd_fld[4];
484     lfd->add_style = lfd_fld[5];
485     lfd->pixel_size = lfd_fld[6];
486     lfd->point_size = lfd_fld[7];
487     lfd->resolution_x = lfd_fld[8];
488     lfd->resolution_y = lfd_fld[9];
489     lfd->spacing = lfd_fld[10];
490     lfd->average_width = lfd_fld[11];
491     lfd->charset_registry = lfd_fld[12];
492     lfd->charset_encoding = lfd_fld[13];
493     return TRUE;
494 }
495
496
497 static void LFD_UnParse(LPSTR dp, UINT buf_size, LFD* lfd)
498 {
499     const char* lfd_fld[LFD_FIELDS];
500     int i;
501
502     if (!buf_size)
503         return; /* Don't be silly */
504
505     lfd_fld[0]  = lfd->foundry;
506     lfd_fld[1]  = lfd->family;
507     lfd_fld[2]  = lfd->weight ;
508     lfd_fld[3]  = lfd->slant ;
509     lfd_fld[4]  = lfd->set_width ;
510     lfd_fld[5]  = lfd->add_style;
511     lfd_fld[6]  = lfd->pixel_size;
512     lfd_fld[7]  = lfd->point_size;
513     lfd_fld[8]  = lfd->resolution_x;
514     lfd_fld[9]  = lfd->resolution_y ;
515     lfd_fld[10] = lfd->spacing ;
516     lfd_fld[11] = lfd->average_width ;
517     lfd_fld[12] = lfd->charset_registry ;
518     lfd_fld[13] = lfd->charset_encoding ;
519
520     buf_size--; /* Room for the terminator */
521
522     for (i = 0; i < LFD_FIELDS; i++)
523     {
524         const char* sp = lfd_fld[i];
525         if (!sp || !buf_size)
526             break;
527
528         *dp++ = HYPHEN;
529         buf_size--;
530         while (buf_size > 0 && *sp)
531         {
532             *dp = (*sp == HYPHEN) ? TILDE : *sp;
533             buf_size--;
534             dp++; sp++;
535         }
536     }
537     *dp = '\0';
538 }
539
540
541 static void LFD_GetWeight( fontInfo* fi, LPCSTR lpStr)
542 {
543     int j = strlen(lpStr);
544     if( j == 1 && *lpStr == '0')
545         fi->fi_flags |= FI_POLYWEIGHT;
546     else if( j == 4 )
547     {
548         if( !strcasecmp( "bold", lpStr) )
549             fi->df.dfWeight = FW_BOLD;
550         else if( !strcasecmp( "demi", lpStr) )
551         {
552             fi->fi_flags |= FI_FW_DEMI;
553             fi->df.dfWeight = FW_DEMIBOLD;
554         }
555         else if( !strcasecmp( "book", lpStr) )
556         {
557             fi->fi_flags |= FI_FW_BOOK;
558             fi->df.dfWeight = FW_REGULAR;
559         }
560     }
561     else if( j == 5 )
562     {
563         if( !strcasecmp( "light", lpStr) )
564             fi->df.dfWeight = FW_LIGHT;
565         else if( !strcasecmp( "black", lpStr) )
566             fi->df.dfWeight = FW_BLACK;
567     }
568     else if( j == 6 && !strcasecmp( "medium", lpStr) )
569         fi->df.dfWeight = FW_REGULAR;
570     else if( j == 8 && !strcasecmp( "demibold", lpStr) )
571         fi->df.dfWeight = FW_DEMIBOLD;
572     else
573         fi->df.dfWeight = FW_DONTCARE; /* FIXME: try to get something
574                                         * from the weight property */
575 }
576
577 static BOOL LFD_GetSlant( fontInfo* fi, LPCSTR lpStr)
578 {
579     int l = strlen(lpStr);
580     if( l == 1 )
581     {
582         switch( tolower( *lpStr ) )
583         {
584             case '0':  fi->fi_flags |= FI_POLYSLANT;    /* haven't seen this one yet */
585             default:
586             case 'r':  fi->df.dfItalic = 0;
587                        break;
588             case 'o':
589                        fi->fi_flags |= FI_OBLIQUE;
590             case 'i':  fi->df.dfItalic = 1;
591                        break;
592         }
593         return FALSE;
594     }
595     return TRUE;
596 }
597
598 static void LFD_GetStyle( fontInfo* fi, LPCSTR lpstr, int dec_style_check)
599 {
600     int j = strlen(lpstr);
601     if( j > 3 ) /* find out is there "sans" or "script" */
602     {
603         j = 0;
604
605         if( strstr(lpstr, "sans") )
606         {
607             fi->df.dfPitchAndFamily |= FF_SWISS;
608             j = 1;
609         }
610         if( strstr(lpstr, "script") )
611         {
612             fi->df.dfPitchAndFamily |= FF_SCRIPT;
613             j = 1;
614         }
615         if( !j && dec_style_check )
616             fi->df.dfPitchAndFamily |= FF_DECORATIVE;
617    }
618 }
619
620 /*************************************************************************
621  *           LFD_InitFontInfo
622  *
623  * INIT ONLY
624  *
625  * Fill in some fields in the fontInfo struct.
626  */
627 static int LFD_InitFontInfo( fontInfo* fi, const LFD* lfd, LPCSTR fullname )
628 {
629    int          i, j, dec_style_check, scalability;
630    const fontEncodingTemplate* boba;
631    const char* ridiculous = "font '%s' has ridiculous %s\n";
632    const char* lpstr;
633
634    if (!lfd->charset_registry)
635    {
636        WARN("font '%s' does not have enough fields\n", fullname);
637        return FALSE;
638    }
639
640    memset(fi, 0, sizeof(fontInfo) );
641
642 /* weight name - */
643    LFD_GetWeight( fi, lfd->weight);
644
645 /* slant - */
646    dec_style_check = LFD_GetSlant( fi, lfd->slant);
647
648 /* width name - */
649    lpstr = lfd->set_width;
650    if( strcasecmp( "normal", lpstr) )   /* XXX 'narrow', 'condensed', etc... */
651        dec_style_check = TRUE;
652    else
653        fi->fi_flags |= FI_NORMAL;
654
655 /* style - */
656    LFD_GetStyle(fi, lfd->add_style, dec_style_check);
657
658 /* pixel & decipoint height, and res_x & y */
659
660    scalability = 0;
661
662    j = strlen(lfd->pixel_size);
663    if( j == 0 || j > 3 )
664    {
665        WARN(ridiculous, fullname, "pixel_size");
666        return FALSE;
667    }
668    if( !(fi->lfd_height = atoi(lfd->pixel_size)) )
669        scalability++;
670
671    j = strlen(lfd->point_size);
672    if( j == 0 || j > 3 )
673    {
674        WARN(ridiculous, fullname, "point_size");
675        return FALSE;
676    }
677    if( !(atoi(lfd->point_size)) )
678        scalability++;
679
680    j = strlen(lfd->resolution_x);
681    if( j == 0 || j > 3 )
682    {
683        WARN(ridiculous, fullname, "resolution_x");
684        return FALSE;
685    }
686    if( !(fi->lfd_resolution = atoi(lfd->resolution_x)) )
687        scalability++;
688
689    j = strlen(lfd->resolution_y);
690    if( j == 0 || j > 3 )
691    {
692        WARN(ridiculous, fullname, "resolution_y");
693        return FALSE;
694    }
695    if( !(atoi(lfd->resolution_y)) )
696        scalability++;
697
698    /* Check scalability */
699    switch (scalability)
700    {
701    case 0: /* Bitmap */
702        break;
703    case 4: /* Scalable */
704        fi->fi_flags |= FI_SCALABLE;
705        break;
706    case 2:
707        /* #$%^!!! X11R6 mutant garbage (scalable bitmap) */
708        TRACE("Skipping scalable bitmap '%s'\n", fullname);
709        return FALSE;
710    default:
711        WARN("Font '%s' has weird scalability\n", fullname);
712        return FALSE;
713    }
714
715 /* spacing - */
716    lpstr = lfd->spacing;
717    switch( *lpstr )
718    {
719      case '\0':
720          WARN("font '%s' has no spacing\n", fullname);
721          return FALSE;
722
723      case 'p': fi->fi_flags |= FI_VARIABLEPITCH;
724                break;
725      case 'c': fi->df.dfPitchAndFamily |= FF_MODERN;
726                fi->fi_flags |= FI_FIXEDEX;
727                /* fall through */
728      case 'm': fi->fi_flags |= FI_FIXEDPITCH;
729                break;
730      default:
731                /* Of course this line does nothing */
732                fi->df.dfPitchAndFamily |= DEFAULT_PITCH | FF_DONTCARE;
733    }
734
735 /* average width - */
736    lpstr = lfd->average_width;
737    j = strlen(lpstr);
738    if( j == 0 || j > 3 )
739    {
740        WARN(ridiculous, fullname, "average_width");
741        return FALSE;
742    }
743
744    if( !(atoi(lpstr)) && !scalability )
745    {
746        WARN("font '%s' has average_width 0 but is not scalable!!\n", fullname);
747        return FALSE;
748    }
749
750 /* charset registry, charset encoding - */
751    lpstr = lfd->charset_registry;
752    if( strstr(lpstr, "ksc") ||
753        strstr(lpstr, "gb2312") ||
754        strstr(lpstr, "big5") )
755    {
756        FIXME("DBCS fonts like '%s' are not working correctly now.\n", fullname);
757    }
758
759    fi->df.dfCharSet = ANSI_CHARSET;
760
761    for( i = 0, boba = &fETTable[0]; boba; boba = boba->next, i++ )
762    {
763        if (!boba->prefix || !strcasecmp(lpstr, boba->prefix))
764        {
765            if (lfd->charset_encoding)
766            {
767                for( j = 0; boba->sufch[j].psuffix; j++ )
768                {
769                    if( !strcasecmp(lfd->charset_encoding, boba->sufch[j].psuffix ))
770                    {
771                        fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
772                        fi->internal_charset = boba->sufch[j].charset;
773                        fi->codepage = boba->sufch[j].codepage;
774                        fi->cptable = boba->sufch[j].cptable;
775                        goto done;
776                    }
777                }
778
779                fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
780                fi->internal_charset = boba->sufch[j].charset;
781                fi->codepage = boba->sufch[j].codepage;
782                fi->cptable = boba->sufch[j].cptable;
783                if (boba->prefix)
784                {
785                   FIXME("font '%s' has unknown character encoding '%s' in known registry '%s'\n",
786                        fullname, lfd->charset_encoding, boba->prefix);
787                   j = 254;
788                }
789                else
790                {
791                   FIXME("font '%s' has unknown registry '%s' and character encoding '%s'\n",
792                        fullname, lfd->charset_registry, lfd->charset_encoding);
793                   j = 255;
794                }
795
796                WARN("Defaulting to: df.dfCharSet = %d,  internal_charset = %d, codepage = %d, cptable = %d\n",
797                     fi->df.dfCharSet,fi->internal_charset, fi->codepage, fi->cptable);
798                goto done;
799            }
800            else if (boba->prefix)
801            {
802                WARN("font '%s' has known registry '%s' and no character encoding\n",
803                     fullname, lpstr);
804                for( j = 0; boba->sufch[j].psuffix; j++ )
805                    ;
806                fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
807                fi->internal_charset = boba->sufch[j].charset;
808                fi->codepage = boba->sufch[j].codepage;
809                fi->cptable = boba->sufch[j].cptable;
810                j = 255;
811                goto done;
812            }
813        }
814    }
815    WARN("font '%s' has unknown character set '%s'\n", fullname, lpstr);
816    return FALSE;
817
818 done:
819    /* i - index into fETTable
820     * j - index into suffix array for fETTable[i]
821     *     except:
822     *     254 - found encoding prefix, unknown suffix
823     *     255 - no encoding match at all.
824     */
825    fi->fi_encoding = 256 * (UINT16)i + (UINT16)j;
826
827    return TRUE;
828 }
829
830
831 /*************************************************************************
832  *           LFD_AngleMatrix
833  *
834  * make a matrix suitable for LFD based on theta radians
835  */
836 static void LFD_AngleMatrix( char* buffer, int h, double theta)
837 {
838     double matrix[4];
839     matrix[0] = h*cos(theta);
840     matrix[1] = h*sin(theta);
841     matrix[2] = -h*sin(theta);
842     matrix[3] = h*cos(theta);
843     sprintf(buffer, "[%+f%+f%+f%+f]", matrix[0], matrix[1], matrix[2], matrix[3]);
844 }
845
846 /*************************************************************************
847  *           LFD_ComposeLFD
848  *
849  * Note: uRelax is a treatment not a cure. Font mapping algorithm
850  *       should be bulletproof enough to allow us to avoid hacks like
851  *       this despite LFD being so braindead.
852  */
853 static BOOL LFD_ComposeLFD( const fontObject* fo,
854                             INT height, LPSTR lpLFD, UINT uRelax )
855 {
856    int          i, h;
857    const char   *any = "*";
858    char         h_string[64], resx_string[64], resy_string[64];
859    LFD          aLFD;
860    const fontEncodingTemplate* boba = &fETTable[0];
861
862 /* Get the worst case over with first */
863
864 /* RealizeFont() will call us repeatedly with increasing uRelax
865  * until XLoadFont() succeeds.
866  * to avoid an infinite loop; these will always match
867  */
868    if (uRelax >= 6)
869    {
870        if (uRelax == 6)
871            sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-1" );
872        else
873            sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*" );
874        return TRUE;
875    }
876
877 /* read foundry + family from fo */
878    aLFD.foundry = fo->fr->resource->foundry;
879    aLFD.family  = fo->fr->resource->family;
880
881 /* add weight */
882    switch( fo->fi->df.dfWeight )
883    {
884         case FW_BOLD:
885                 aLFD.weight = "bold"; break;
886         case FW_REGULAR:
887                 if( fo->fi->fi_flags & FI_FW_BOOK )
888                     aLFD.weight = "book";
889                 else
890                     aLFD.weight = "medium";
891                 break;
892         case FW_DEMIBOLD:
893                 aLFD.weight = "demi";
894                 if( !( fo->fi->fi_flags & FI_FW_DEMI) )
895                      aLFD.weight = "bold";
896                 break;
897         case FW_BLACK:
898                 aLFD.weight = "black"; break;
899         case FW_LIGHT:
900                 aLFD.weight = "light"; break;
901         default:
902                 aLFD.weight = any;
903    }
904
905 /* add slant */
906    if( fo->fi->df.dfItalic )
907        if( fo->fi->fi_flags & FI_OBLIQUE )
908            aLFD.slant = "o";
909        else
910            aLFD.slant = "i";
911    else
912        aLFD.slant = (uRelax <= 1) ? "r" : any;
913
914 /* add width */
915    if( fo->fi->fi_flags & FI_NORMAL )
916        aLFD.set_width = "normal";
917    else
918        aLFD.set_width = any;
919
920 /* ignore style */
921    aLFD.add_style = any;
922
923 /* add pixelheight
924  *
925  * FIXME: fill in lpXForm and lpPixmap for rotated fonts
926  */
927    if( fo->fo_flags & FO_SYNTH_HEIGHT )
928        h = fo->fi->lfd_height;
929    else
930    {
931        h = (fo->fi->lfd_height * height + (fo->fi->df.dfPixHeight>>1));
932        h /= fo->fi->df.dfPixHeight;
933    }
934    if (h < MIN_FONT_SIZE) /* Resist rounding down to 0 */
935        h = MIN_FONT_SIZE;
936    else if (h > MAX_FONT_SIZE) /* Sanity check as huge fonts can lock up the font server */
937    {
938        WARN("Huge font size %d pixels has been reduced to %d\n", h, MAX_FONT_SIZE);
939        h = MAX_FONT_SIZE;
940    }
941
942    if (uRelax <= 3)
943        /* handle rotated fonts */
944        if (fo->lf.lfEscapement) {
945            /* escapement is in tenths of degrees, theta is in radians */
946            double theta = M_PI*fo->lf.lfEscapement/1800.;
947            LFD_AngleMatrix(h_string, h, theta);
948        }
949        else
950        {
951            sprintf(h_string, "%d", h);
952        }
953    else
954        sprintf(h_string, "%d", fo->fi->lfd_height);
955
956    aLFD.pixel_size = h_string;
957    aLFD.point_size = any;
958
959 /* resolution_x,y, average width */
960    /* FIXME - Why do some font servers ignore average width ?
961     * so that you have to mess around with res_y
962     */
963    aLFD.average_width = any;
964    if (uRelax <= 4)
965    {
966        sprintf(resx_string, "%d", fo->fi->lfd_resolution);
967        aLFD.resolution_x = resx_string;
968
969        strcpy(resy_string, resx_string);
970        if( uRelax == 0  && text_caps & TC_SF_X_YINDEP )
971        {
972            if( fo->lf.lfWidth && !(fo->fo_flags & FO_SYNTH_WIDTH))
973            {
974                int resy = 0.5 + fo->fi->lfd_resolution *
975                    (fo->fi->df.dfAvgWidth * height) /
976                    (fo->lf.lfWidth * fo->fi->df.dfPixHeight) ;
977                sprintf(resy_string,  "%d", resy);
978            }
979            else
980            {
981                /* FIXME - synth width */
982            }
983        }
984        aLFD.resolution_y = resy_string;
985    }
986    else
987    {
988        aLFD.resolution_x = aLFD.resolution_y = any;
989    }
990
991 /* spacing */
992    {
993        const char* w;
994
995        if( fo->fi->fi_flags & FI_FIXEDPITCH )
996            w = ( fo->fi->fi_flags & FI_FIXEDEX ) ? "c" : "m";
997        else
998            w = ( fo->fi->fi_flags & FI_VARIABLEPITCH ) ? "p" : any;
999
1000        aLFD.spacing = (uRelax <= 2) ? w : any;
1001    }
1002
1003 /* encoding */
1004
1005    for(i = fo->fi->fi_encoding >> 8; i; i--) boba = boba->next;
1006    aLFD.charset_registry = boba->prefix ? boba->prefix : any;
1007
1008    i = fo->fi->fi_encoding & 255;
1009    switch( i ) {
1010    default:
1011        aLFD.charset_encoding = boba->sufch[i].psuffix;
1012        break;
1013
1014    case 254:
1015        aLFD.charset_encoding = any;
1016        break;
1017
1018    case 255: /* no suffix - it ends eg "-ascii" */
1019        aLFD.charset_encoding = NULL;
1020        break;
1021    }
1022
1023    LFD_UnParse(lpLFD, MAX_LFD_LENGTH, &aLFD);
1024
1025    TRACE("\tLFD(uRelax=%d): %s\n", uRelax, lpLFD );
1026    return TRUE;
1027 }
1028
1029
1030 /***********************************************************************
1031  *              X Font Resources
1032  *
1033  * 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(), HEAP_ZERO_MEMORY, sizeof(fontResource));
2039             if (fr)
2040             {
2041                 fr->resource = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(LFD));
2042
2043                 TRACE("family: -%s-%s-\n", lfd.foundry, lfd.family );
2044                 fr->resource->foundry = HeapAlloc(GetProcessHeap(), 0, strlen(lfd.foundry)+1);
2045                 strcpy( (char *)fr->resource->foundry, lfd.foundry );
2046                 fr->resource->family = HeapAlloc(GetProcessHeap(), 0, strlen(lfd.family)+1);
2047                 strcpy( (char *)fr->resource->family, lfd.family );
2048                 fr->resource->weight = "";
2049
2050                 if( pfr ) pfr->next = fr;
2051                 else fontList = fr;
2052             }
2053             else
2054                 WARN("Not enough memory for a new font family\n");
2055         }
2056
2057         /* check if we already have something better than "fi" */
2058
2059         for( pfi = fr->fi, j = 0; pfi && j <= 0; pfi = pfi->next )
2060             if( (j = XFONT_IsSubset( pfi, fi )) < 0 )
2061                 pfi->fi_flags |= FI_SUBSET; /* superseded by "fi" */
2062         if( j > 0 ) goto nextfont;
2063
2064         /* add new font instance "fi" to the "fr" font resource */
2065
2066         if( fi->fi_flags & FI_SCALABLE )
2067         {
2068             LFD lfd1;
2069             char pxl_string[4], res_string[4];
2070             /* set scalable font height to get a basis for extrapolation */
2071
2072             fi->lfd_height = DEF_SCALABLE_HEIGHT;
2073             fi->lfd_resolution = res;
2074
2075             sprintf(pxl_string, "%d", fi->lfd_height);
2076             sprintf(res_string, "%d", fi->lfd_resolution);
2077
2078             lfd1 = lfd;
2079             lfd1.pixel_size = pxl_string;
2080             lfd1.point_size = "*";
2081             lfd1.resolution_x = res_string;
2082             lfd1.resolution_y = res_string;
2083
2084             LFD_UnParse(buffer, sizeof(buffer), &lfd1);
2085
2086             lpstr = buffer;
2087         }
2088         else lpstr = x_pattern[i];
2089
2090         /* X11 may return an error on some bad fonts... So be prepared to handle these. */
2091         if ((x_fs = safe_XLoadQueryFont(gdi_display, lpstr)) != 0)
2092         {
2093             XFONT_SetFontMetric( fi, fr, x_fs );
2094             wine_tsx11_lock();
2095             XFreeFont( gdi_display, x_fs );
2096             wine_tsx11_unlock();
2097
2098             XFONT_FixupPointSize(fi);
2099
2100             TRACE("\t[% 2ipt] '%s'\n", fi->df.dfPoints, x_pattern[i] );
2101
2102             XFONT_CheckFIList( fr, fi, REMOVE_SUBSETS );
2103             fi = NULL;  /* preventing reuse */
2104         }
2105         else
2106         {
2107             ERR("failed to load %s\n", lpstr );
2108
2109             XFONT_CheckFIList( fr, fi, UNMARK_SUBSETS );
2110         }
2111     nextfont:
2112         HeapFree(GetProcessHeap(), 0, typeface);
2113     }
2114     HeapFree(GetProcessHeap(), 0, fi);
2115
2116     /* Scan through the font list and remove FontResource(s) (fr)
2117      * that have no associated Fontinfo(s) (fi).
2118      * This code is necessary because XFONT_ReadCachedMetrics
2119      * assumes that there is at least one fi associated with a fr.
2120      * This assumption is invalid for TT font
2121      *  -altsys-ms outlook-medium-r-normal--0-0-0-0-p-0-microsoft-symbol.
2122      */
2123
2124     fr = fontList;
2125
2126     while (!fr->fi_count)
2127     {
2128        fontList = fr->next;
2129
2130        HeapFree(GetProcessHeap(), 0, fr->resource);
2131        HeapFree(GetProcessHeap(), 0, fr);
2132
2133        fr = fontList;
2134        n_ff--;
2135     }
2136
2137     fr = fontList;
2138
2139     while (fr->next)
2140     {
2141         if (!fr->next->fi_count)
2142         {
2143             pfr = fr->next;
2144             fr->next = fr->next->next;
2145
2146             HeapFree(GetProcessHeap(), 0, pfr->resource);
2147             HeapFree(GetProcessHeap(), 0, pfr);
2148
2149             n_ff--;
2150         }
2151         else
2152             fr = fr->next;
2153     }
2154
2155     MESSAGE("Font metrics: 100.0%% done\n");
2156     return n_ff;
2157 }
2158
2159 /***********************************************************************
2160  *           XFONT_ReadCachedMetrics
2161  *
2162  * INIT ONLY
2163  */
2164 static BOOL XFONT_ReadCachedMetrics( int fd, int res, unsigned x_checksum, int x_count )
2165 {
2166     if( fd >= 0 )
2167     {
2168         unsigned u;
2169         int i, j;
2170
2171         /* read checksums */
2172         read( fd, &u, sizeof(unsigned) );
2173         read( fd, &i, sizeof(int) );
2174
2175         if( u == x_checksum && i == x_count )
2176         {
2177             off_t length, offset = 3 * sizeof(int);
2178
2179             /* read total size */
2180             read( fd, &i, sizeof(int) );
2181             length = lseek( fd, 0, SEEK_END );
2182
2183             if( length == (i + offset) )
2184             {
2185                 lseek( fd, offset, SEEK_SET );
2186                 fontList = HeapAlloc( GetProcessHeap(), 0, i);
2187                 if( fontList )
2188                 {
2189                     fontResource*       pfr = fontList;
2190                     fontInfo*           pfi = NULL;
2191
2192                     TRACE("Reading cached font metrics:\n");
2193
2194                     read( fd, fontList, i); /* read all metrics at once */
2195                     while( offset < length )
2196                     {
2197                         offset += sizeof(fontResource) + sizeof(fontInfo);
2198                         pfr->fi = pfi = (fontInfo*)(pfr + 1);
2199                         j = 1;
2200                         while( TRUE )
2201                         {
2202                            if( offset > length ||
2203                                pfi->cptable >= (UINT16)X11DRV_CPTABLE_COUNT ||
2204                               (int)(pfi->next) != j++ )
2205                            {
2206                                TRACE("error: offset=%ld length=%ld cptable=%d pfi->next=%d j=%d\n",(long)offset,(long)length,pfi->cptable,(int)pfi->next,j-1);
2207                                goto fail;
2208                            }
2209
2210                            if( pfi->df.dfPixHeight == 0 )
2211                            {
2212                                TRACE("error: dfPixHeight==0\n");
2213                                goto fail;
2214                            }
2215
2216                            pfi->df.dfFace = pfr->lfFaceName;
2217                            if( pfi->fi_flags & FI_SCALABLE )
2218                            {
2219                                /* we can pretend we got this font for any resolution */
2220                                pfi->lfd_resolution = res;
2221                                XFONT_FixupPointSize(pfi);
2222                            }
2223                            pfi->next = pfi + 1;
2224
2225                            if( j > pfr->fi_count ) break;
2226
2227                            pfi = pfi->next;
2228                            offset += sizeof(fontInfo);
2229                         }
2230                         pfi->next = NULL;
2231                         if( pfr->next )
2232                         {
2233                             pfr->next = (fontResource*)(pfi + 1);
2234                             pfr = pfr->next;
2235                         }
2236                         else break;
2237                     }
2238                     if( pfr->next == NULL &&
2239                         *(int*)(pfi + 1) == X_FMC_MAGIC )
2240                     {
2241                         /* read LFD stubs */
2242                         char* lpch = (char*)((int*)(pfi + 1) + 1);
2243                         offset += sizeof(int);
2244                         for( pfr = fontList; pfr; pfr = pfr->next )
2245                         {
2246                             size_t len = strlen(lpch) + 1;
2247                             TRACE("\t%s, %i instances\n", lpch, pfr->fi_count );
2248                             pfr->resource = HeapAlloc(GetProcessHeap(),0,sizeof(LFD));
2249                             if (!LFD_Parse(lpch, pfr->resource))
2250                             {
2251                                 HeapFree( GetProcessHeap(), 0, pfr->resource );
2252                                 pfr->resource = NULL;
2253                             }
2254                             lpch += len;
2255                             offset += len;
2256                             if (offset > length)
2257                             {
2258                                 TRACE("error: offset=%ld length=%ld\n",(long)offset,(long)length);
2259                                 goto fail;
2260                             }
2261                         }
2262                         close( fd );
2263                         return TRUE;
2264                     }
2265                 }
2266             } else {
2267                 TRACE("Wrong length: %ld!=%ld\n",(long)length,(long)(i+offset));
2268             }
2269         } else {
2270             TRACE("Checksum (%x vs. %x) or count (%d vs. %d) mismatch\n",
2271                   u,x_checksum,i,x_count);
2272         }
2273 fail:
2274         HeapFree( GetProcessHeap(), 0, fontList );
2275         fontList = NULL;
2276         close( fd );
2277     }
2278     return FALSE;
2279 }
2280
2281 /***********************************************************************
2282  *           XFONT_WriteCachedMetrics
2283  *
2284  * INIT ONLY
2285  */
2286 static BOOL XFONT_WriteCachedMetrics( int fd, unsigned x_checksum, int x_count, int n_ff )
2287 {
2288     fontResource* pfr;
2289     fontInfo* pfi;
2290
2291     if( fd >= 0 )
2292     {
2293         int  i, j, k;
2294         char buffer[MAX_LFD_LENGTH];
2295
2296         /* font metrics file:
2297          *
2298          * +0000 x_checksum
2299          * +0004 x_count
2300          * +0008 total size to load
2301          * +000C prepackaged font metrics
2302          * ...
2303          * +...x        X_FMC_MAGIC
2304          * +...x + 4    LFD stubs
2305          */
2306
2307         write( fd, &x_checksum, sizeof(unsigned) );
2308         write( fd, &x_count, sizeof(int) );
2309
2310         for( j = i = 0, pfr = fontList; pfr; pfr = pfr->next )
2311         {
2312             LFD_UnParse(buffer, sizeof(buffer), pfr->resource);
2313             i += strlen( buffer) + 1;
2314             j += pfr->fi_count;
2315         }
2316         i += n_ff * sizeof(fontResource) + j * sizeof(fontInfo) + sizeof(int);
2317         write( fd, &i, sizeof(int) );
2318
2319         TRACE("Writing font cache:\n");
2320
2321         for( pfr = fontList; pfr; pfr = pfr->next )
2322         {
2323             fontInfo fi;
2324
2325             TRACE("\t-%s-%s-, %i instances\n", pfr->resource->foundry, pfr->resource->family, pfr->fi_count );
2326
2327             i = write( fd, pfr, sizeof(fontResource) );
2328             if( i == sizeof(fontResource) )
2329             {
2330                 for( k = 1, pfi = pfr->fi; pfi; pfi = pfi->next )
2331                 {
2332                     fi = *pfi;
2333
2334                     fi.df.dfFace = NULL;
2335                     fi.next = (fontInfo*)k;     /* loader checks this */
2336
2337                     j = write( fd, &fi, sizeof(fi) );
2338                     k++;
2339                 }
2340                 if( j == sizeof(fontInfo) ) continue;
2341             }
2342             break;
2343         }
2344         if( i == sizeof(fontResource) && j == sizeof(fontInfo) )
2345         {
2346             i = j = X_FMC_MAGIC;
2347             write( fd, &i, sizeof(int) );
2348             for( pfr = fontList; pfr && i == j; pfr = pfr->next )
2349             {
2350                 LFD_UnParse(buffer, sizeof(buffer), pfr->resource);
2351                 i = strlen( buffer ) + 1;
2352                 j = write( fd, buffer, i );
2353             }
2354         }
2355         close( fd );
2356         return ( i == j );
2357     }
2358     return FALSE;
2359 }
2360
2361 /***********************************************************************
2362  *           XFONT_GetDefResolution()
2363  *
2364  * INIT ONLY
2365  *
2366  * Here we initialize DefResolution which is used in the
2367  * XFONT_Match() penalty function, based on the values of log_pixels
2368  */
2369 static int XFONT_GetDefResolution( int log_pixels_x, int log_pixels_y )
2370 {
2371     int i, j, num = 3;
2372     int allowed_xfont_resolutions[3] = { 72, 75, 100 };
2373     int best = 0, best_diff = 65536;
2374
2375     /* FIXME We can only really guess at a best DefResolution
2376      * - this should be configurable
2377      */
2378     for( i = best = 0; i < num; i++ )
2379     {
2380         j = abs( log_pixels_x - allowed_xfont_resolutions[i] );
2381         if( j < best_diff )
2382         {
2383             best = i;
2384             best_diff = j;
2385         }
2386     }
2387     DefResolution = allowed_xfont_resolutions[best];
2388     return DefResolution;
2389 }
2390
2391
2392 /***********************************************************************
2393  *            XFONT_Match
2394  *
2395  * Compute the matching score between the logical font and the device font.
2396  *
2397  * contributions from highest to lowest:
2398  *      charset
2399  *      fixed pitch
2400  *      height
2401  *      family flags (only when the facename is not present)
2402  *      width
2403  *      weight, italics, underlines, strikeouts
2404  *
2405  * NOTE: you can experiment with different penalty weights to see what happens.
2406  * http://premium.microsoft.com/msdn/library/techart/f365/f36b/f37b/d38b/sa8bf.htm
2407  */
2408 static UINT XFONT_Match( fontMatch* pfm )
2409 {
2410    fontInfo*    pfi = pfm->pfi;         /* device font to match */
2411    LPLOGFONT16  plf = pfm->plf;         /* wanted logical font */
2412    UINT       penalty = 0;
2413    BOOL       bR6 = pfm->flags & FO_MATCH_XYINDEP;    /* from text_caps */
2414    BOOL       bScale = pfi->fi_flags & FI_SCALABLE;
2415    int d = 0, height;
2416
2417    TRACE("\t[ %-2ipt h=%-3i w=%-3i %s%s]\n", pfi->df.dfPoints,
2418                  pfi->df.dfPixHeight, pfi->df.dfAvgWidth,
2419                 (pfi->df.dfWeight > FW_NORMAL) ? "Bold " : "Normal ",
2420                 (pfi->df.dfItalic) ? "Italic" : "" );
2421
2422    pfm->flags &= FO_MATCH_MASK;
2423
2424 /* Charset */
2425    /* pfm->internal_charset: given(required) charset */
2426    /* pfi->internal_charset: charset of this font */
2427    if (pfi->internal_charset == DEFAULT_CHARSET)
2428    {
2429       /* special case(unicode font) */
2430       /* priority: unmatched charset < unicode < matched charset */
2431       penalty += 0x50;
2432    }
2433    else
2434    {
2435      if( pfm->internal_charset == DEFAULT_CHARSET )
2436      {
2437         /*
2438          if (pfi->internal_charset != ANSI_CHARSET)
2439             penalty += 0x200;
2440         */
2441         if ( pfi->codepage != GetACP() )
2442             penalty += 0x200;
2443      }
2444      else if (pfm->internal_charset != pfi->internal_charset)
2445      {
2446        if ( pfi->internal_charset & 0xff00 )
2447          penalty += 0x1000; /* internal charset - should not be used */
2448        else
2449          penalty += 0x200;
2450      }
2451    }
2452
2453 /* Height */
2454    height = -1;
2455    {
2456        if( plf->lfHeight > 0 )
2457        {
2458            int h = pfi->df.dfPixHeight;
2459            d = h - plf->lfHeight;
2460            height = plf->lfHeight;
2461        }
2462        else
2463        {
2464            int h = pfi->df.dfPixHeight - pfi->df.dfInternalLeading;
2465            if (h)
2466            {
2467                d = h + plf->lfHeight;
2468                height = (-plf->lfHeight * pfi->df.dfPixHeight) / h;
2469            }
2470            else
2471            {
2472                ERR("PixHeight == InternalLeading\n");
2473                penalty += 0x1000; /* don't want this */
2474            }
2475        }
2476    }
2477
2478    if( height == 0 )
2479        pfm->height = 1; /* Very small */
2480    else if( d )
2481    {
2482        if( bScale )
2483            pfm->height = height;
2484        else if( (plf->lfQuality != PROOF_QUALITY) && bR6 )
2485        {
2486            if( d > 0 )  /* do not shrink raster fonts */
2487            {
2488                pfm->height = pfi->df.dfPixHeight;
2489                penalty += (pfi->df.dfPixHeight - height) * 0x4;
2490            }
2491            else         /* expand only in integer multiples */
2492            {
2493                pfm->height = height - height%pfi->df.dfPixHeight;
2494                penalty += (height - pfm->height + 1) * height / pfi->df.dfPixHeight;
2495            }
2496        }
2497        else /* can't be scaled at all */
2498        {
2499            if( plf->lfQuality != PROOF_QUALITY) pfm->flags |= FO_SYNTH_HEIGHT;
2500            pfm->height = pfi->df.dfPixHeight;
2501            penalty += (d > 0)? d * 0x8 : -d * 0x10;
2502        }
2503    }
2504    else
2505        pfm->height = pfi->df.dfPixHeight;
2506
2507 /* Pitch and Family */
2508    if( pfm->flags & FO_MATCH_PAF ) {
2509        int family = plf->lfPitchAndFamily & FF_FAMILY;
2510
2511        /* TMPF_FIXED_PITCH means exactly the opposite */
2512        if( plf->lfPitchAndFamily & FIXED_PITCH ) {
2513            if( pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH ) penalty += 0x100;
2514        } else /* Variable is the default */
2515            if( !(pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH) ) penalty += 0x2;
2516
2517        if (family != FF_DONTCARE && family != (pfi->df.dfPitchAndFamily & FF_FAMILY) )
2518            penalty += 0x10;
2519    }
2520
2521 /* Width */
2522    if( plf->lfWidth )
2523    {
2524        int h;
2525        if( bR6 || bScale ) h = 0;
2526        else
2527        {
2528            /* FIXME: not complete */
2529
2530            pfm->flags |= FO_SYNTH_WIDTH;
2531            h = abs(plf->lfWidth - (pfm->height * pfi->df.dfAvgWidth)/pfi->df.dfPixHeight);
2532        }
2533        penalty += h * ( d ) ? 0x2 : 0x1 ;
2534    }
2535    else if( !(pfi->fi_flags & FI_NORMAL) ) penalty++;
2536
2537 /* Weight */
2538    if( plf->lfWeight != FW_DONTCARE )
2539    {
2540        penalty += abs(plf->lfWeight - pfi->df.dfWeight) / 40;
2541        if( plf->lfWeight > pfi->df.dfWeight ) pfm->flags |= FO_SYNTH_BOLD;
2542    } else if( pfi->df.dfWeight >= FW_BOLD ) penalty++;  /* choose normal by default */
2543
2544 /* Italic */
2545    if( plf->lfItalic != pfi->df.dfItalic )
2546    {
2547        penalty += 0x4;
2548        pfm->flags |= FO_SYNTH_ITALIC;
2549    }
2550 /* Underline */
2551    if( plf->lfUnderline ) pfm->flags |= FO_SYNTH_UNDERLINE;
2552
2553 /* Strikeout */
2554    if( plf->lfStrikeOut ) pfm->flags |= FO_SYNTH_STRIKEOUT;
2555
2556
2557    if( penalty && !bScale && pfi->lfd_resolution != DefResolution )
2558        penalty++;
2559
2560    TRACE("  returning %i\n", penalty );
2561
2562    return penalty;
2563 }
2564
2565 /***********************************************************************
2566  *            XFONT_MatchFIList
2567  *
2568  * Scan a particular font resource for the best match.
2569  */
2570 static UINT XFONT_MatchFIList( fontMatch* pfm )
2571 {
2572   BOOL        skipRaster = (pfm->flags & FO_MATCH_NORASTER);
2573   UINT        current_score, score = (UINT)(-1);
2574   fontMatch   fm = *pfm;
2575
2576   for( fm.pfi = pfm->pfr->fi; fm.pfi && score; fm.pfi = fm.pfi->next)
2577   {
2578      if( skipRaster && !(fm.pfi->fi_flags & FI_SCALABLE) )
2579          continue;
2580
2581      current_score = XFONT_Match( &fm );
2582      if( score > current_score )
2583      {
2584         *pfm = fm;
2585         score = current_score;
2586      }
2587   }
2588   return score;
2589 }
2590
2591 /***********************************************************************
2592  *      XFONT_is_ansi_charset
2593  *
2594  *  returns TRUE if the given charset is ANSI_CHARSET.
2595  */
2596 static BOOL XFONT_is_ansi_charset( UINT charset )
2597 {
2598         return ((charset == ANSI_CHARSET) ||
2599                 (charset == DEFAULT_CHARSET && GetACP() == 1252));
2600 }
2601
2602 /***********************************************************************
2603  *          XFONT_MatchDeviceFont
2604  *
2605  * Scan font resource tree.
2606  *
2607  */
2608 static void XFONT_MatchDeviceFont( fontResource* start, fontMatch* pfm)
2609 {
2610     fontMatch           fm = *pfm;
2611     UINT          current_score, score = (UINT)(-1);
2612     fontResource**      ppfr;
2613
2614     TRACE("(%u) '%s' h=%i weight=%i %s\n",
2615           pfm->plf->lfCharSet, pfm->plf->lfFaceName, pfm->plf->lfHeight,
2616           pfm->plf->lfWeight, (pfm->plf->lfItalic) ? "Italic" : "" );
2617
2618     pfm->pfi = NULL;
2619
2620     /* the following hard-coded font binding assumes 'ANSI_CHARSET'. */
2621     if( !fm.plf->lfFaceName[0] &&
2622         XFONT_is_ansi_charset(fm.plf->lfCharSet) )
2623     {
2624         switch(fm.plf->lfPitchAndFamily & 0xf0)
2625         {
2626         case FF_MODERN:
2627             strcpy(fm.plf->lfFaceName, "Courier New");
2628             break;
2629         case FF_ROMAN:
2630             strcpy(fm.plf->lfFaceName, "Times New Roman");
2631             break;
2632         case FF_SWISS:
2633             strcpy(fm.plf->lfFaceName, "Arial");
2634             break;
2635         default:
2636             if((fm.plf->lfPitchAndFamily & 0x0f) == FIXED_PITCH)
2637                 strcpy(fm.plf->lfFaceName, "Courier New");
2638             else
2639                 strcpy(fm.plf->lfFaceName, "Arial");
2640             break;
2641         }
2642     }
2643
2644     if( fm.plf->lfFaceName[0] )
2645     {
2646         fm.pfr = XFONT_FindFIList( start, fm.plf->lfFaceName);
2647         if( fm.pfr ) /* match family */
2648         {
2649             TRACE("found facename '%s'\n", fm.pfr->lfFaceName );
2650
2651             if( fm.pfr->fr_flags & FR_REMOVED )
2652                 fm.pfr = 0;
2653             else
2654             {
2655                 XFONT_MatchFIList( &fm );
2656                 *pfm = fm;
2657                 if (pfm->pfi)
2658                     return;
2659             }
2660         }
2661
2662         /* get charset if lfFaceName is one of known facenames. */
2663         {
2664             const struct CharsetBindingInfo* pcharsetbindings;
2665
2666             pcharsetbindings = &charsetbindings[0];
2667             while ( pcharsetbindings->pszFaceName != NULL )
2668             {
2669                 if ( !strcmp( pcharsetbindings->pszFaceName,
2670                               fm.plf->lfFaceName ) )
2671                 {
2672                     fm.internal_charset = pcharsetbindings->charset;
2673                     break;
2674                 }
2675                 pcharsetbindings ++;
2676             }
2677             TRACE( "%s charset %u\n", fm.plf->lfFaceName, fm.internal_charset );
2678         }
2679     }
2680
2681     /* match all available fonts */
2682
2683     fm.flags |= FO_MATCH_PAF;
2684     for( ppfr = &fontList; *ppfr && score; ppfr = &(*ppfr)->next )
2685     {
2686         if( (*ppfr)->fr_flags & FR_REMOVED )
2687         {
2688             if( (*ppfr)->fo_count == 0 )
2689                 XFONT_RemoveFontResource( ppfr );
2690             continue;
2691         }
2692
2693         fm.pfr = *ppfr;
2694
2695         TRACE("%s\n", fm.pfr->lfFaceName );
2696
2697         current_score = XFONT_MatchFIList( &fm );
2698         if( current_score < score )
2699         {
2700             score = current_score;
2701             *pfm = fm;
2702         }
2703     }
2704 }
2705
2706
2707 /***********************************************************************
2708  *           X Font Cache
2709  */
2710 static void XFONT_GrowFreeList(int start, int end)
2711 {
2712    /* add all entries from 'start' up to and including 'end' */
2713
2714    memset( fontCache + start, 0, (end - start + 1) * sizeof(fontObject) );
2715
2716    fontCache[end].lru = fontLF;
2717    fontCache[end].count = -1;
2718    fontLF = start;
2719    while( start < end )
2720    {
2721         fontCache[start].count = -1;
2722         fontCache[start].lru = start + 1;
2723         start++;
2724    }
2725 }
2726
2727 static fontObject* XFONT_LookupCachedFont( const LOGFONT16 *plf, UINT16* checksum )
2728 {
2729     UINT16      cs = __lfCheckSum( plf );
2730     int         i = fontMRU, prev = -1;
2731
2732    *checksum = cs;
2733     while( i >= 0 )
2734     {
2735         if( fontCache[i].lfchecksum == cs &&
2736           !(fontCache[i].fo_flags & FO_REMOVED) )
2737         {
2738             /* FIXME: something more intelligent here ? */
2739
2740             if( !memcmp( plf, &fontCache[i].lf,
2741                          sizeof(LOGFONT16) - LF_FACESIZE ) &&
2742                 !strcmp( plf->lfFaceName, fontCache[i].lf.lfFaceName) )
2743             {
2744                 /* remove temporarily from the lru list */
2745                 if( prev >= 0 )
2746                     fontCache[prev].lru = fontCache[i].lru;
2747                 else
2748                     fontMRU = (INT16)fontCache[i].lru;
2749                 return (fontCache + i);
2750             }
2751         }
2752         prev = i;
2753         i = (INT16)fontCache[i].lru;
2754     }
2755     return NULL;
2756 }
2757
2758 static fontObject* XFONT_GetCacheEntry(void)
2759 {
2760     int         i;
2761
2762     if( fontLF == -1 )
2763     {
2764         int     prev_i, prev_j, j;
2765
2766         TRACE("font cache is full\n");
2767
2768         /* lookup the least recently used font */
2769
2770         for( prev_i = prev_j = j = -1, i = fontMRU; i >= 0; i = (INT16)fontCache[i].lru )
2771         {
2772             if( fontCache[i].count <= 0 &&
2773               !(fontCache[i].fo_flags & FO_SYSTEM) )
2774             {
2775                 prev_j = prev_i;
2776                 j = i;
2777             }
2778             prev_i = i;
2779         }
2780
2781         if( j >= 0 )    /* unload font */
2782         {
2783             /* detach from the lru list */
2784
2785             TRACE("\tfreeing entry %i\n", j );
2786
2787             fontCache[j].fr->fo_count--;
2788
2789             if( prev_j >= 0 )
2790                 fontCache[prev_j].lru = fontCache[j].lru;
2791             else fontMRU = (INT16)fontCache[j].lru;
2792
2793             /* FIXME: lpXForm, lpPixmap */
2794             HeapFree( GetProcessHeap(), 0, fontCache[j].lpX11Trans );
2795
2796             wine_tsx11_lock();
2797             XFreeFont( gdi_display, fontCache[j].fs );
2798             wine_tsx11_unlock();
2799
2800             memset( fontCache + j, 0, sizeof(fontObject) );
2801             return (fontCache + j);
2802         }
2803         else            /* expand cache */
2804         {
2805             fontObject* newCache;
2806
2807             prev_i = fontCacheSize + FONTCACHE;
2808
2809             TRACE("\tgrowing font cache from %i to %i\n", fontCacheSize, prev_i );
2810
2811             if( (newCache = HeapReAlloc(GetProcessHeap(), 0, fontCache, prev_i * sizeof(fontObject))) )
2812             {
2813                 i = fontCacheSize;
2814                 fontCacheSize  = prev_i;
2815                 fontCache = newCache;
2816                 XFONT_GrowFreeList( i, fontCacheSize - 1);
2817             }
2818             else return NULL;
2819         }
2820     }
2821
2822     /* detach from the free list */
2823
2824     i = fontLF;
2825     fontLF = (INT16)fontCache[i].lru;
2826     fontCache[i].count = 0;
2827     return (fontCache + i);
2828 }
2829
2830 static int XFONT_ReleaseCacheEntry(const fontObject* pfo)
2831 {
2832     UINT        u = (UINT)(pfo - fontCache);
2833     int         i;
2834     int         ret;
2835
2836     if( u < fontCacheSize )
2837     {
2838         ret = --fontCache[u].count;
2839         if ( ret == 0 )
2840         {
2841             for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
2842             {
2843                 if( CHECK_PFONT(pfo->prefobjs[i]) )
2844                     XFONT_ReleaseCacheEntry(__PFONT(pfo->prefobjs[i]));
2845             }
2846         }
2847
2848         return ret;
2849     }
2850
2851     return -1;
2852 }
2853
2854 /***********************************************************************
2855  *           X11DRV_FONT_InitX11Metrics
2856  *
2857  * Initialize font resource list and allocate font cache.
2858  */
2859 static void X11DRV_FONT_InitX11Metrics( void )
2860 {
2861   char**    x_pattern;
2862   unsigned  x_checksum;
2863   int       i, x_count, fd, buf_size;
2864   char      *buffer;
2865   HKEY hkey;
2866
2867
2868   wine_tsx11_lock();
2869   x_pattern = XListFonts(gdi_display, "*", MAX_FONTS, &x_count );
2870   wine_tsx11_unlock();
2871
2872   TRACE("Font Mapper: initializing %i x11 fonts\n", x_count);
2873   if (x_count == MAX_FONTS)
2874       MESSAGE("There may be more fonts available - try increasing the value of MAX_FONTS\n");
2875
2876   for( i = x_checksum = 0; i < x_count; i++ )
2877   {
2878      int j;
2879 #if 0
2880      printf("%i\t: %s\n", i, x_pattern[i] );
2881 #endif
2882
2883      j = strlen( x_pattern[i] );
2884      if( j ) x_checksum ^= __genericCheckSum( x_pattern[i], j );
2885   }
2886   x_checksum |= X_PFONT_MAGIC;
2887   buf_size = 128;
2888   buffer = HeapAlloc( GetProcessHeap(), 0, buf_size );
2889
2890   /* deal with systemwide font metrics cache */
2891
2892   buffer[0] = 0;
2893   /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver\Fonts */
2894   if (RegOpenKeyA(HKEY_CURRENT_USER, INIFontSection, &hkey)) hkey = 0;
2895   if (hkey)
2896   {
2897         DWORD type, count = buf_size;
2898         RegQueryValueExA(hkey, INIGlobalMetrics, 0, &type, (LPBYTE)buffer, &count);
2899   }
2900
2901   if( buffer[0] )
2902   {
2903       fd = open( buffer, O_RDONLY );
2904       XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2905   }
2906   if (fontList == NULL)
2907   {
2908       /* try per-user */
2909       buffer = XFONT_UserMetricsCache( buffer, &buf_size );
2910       if( buffer[0] )
2911       {
2912           fd = open( buffer, O_RDONLY );
2913           XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2914       }
2915   }
2916
2917   if( fontList == NULL )        /* build metrics from scratch */
2918   {
2919       int n_ff = XFONT_BuildMetrics(x_pattern, DefResolution, x_checksum, x_count);
2920       if( buffer[0] )    /* update cached metrics */
2921       {
2922           fd = open( buffer, O_CREAT | O_TRUNC | O_RDWR, 0644 ); /* -rw-r--r-- */
2923           if( XFONT_WriteCachedMetrics( fd, x_checksum, x_count, n_ff ) == FALSE )
2924           {
2925               WARN("Unable to write to fontcache '%s'\n", buffer);
2926               if( fd >= 0) remove( buffer );    /* couldn't write entire file */
2927           }
2928       }
2929   }
2930
2931   wine_tsx11_lock();
2932   XFreeFontNames(x_pattern);
2933
2934   /* check if we're dealing with X11 R6 server */
2935   {
2936       XFontStruct*  x_fs;
2937       strcpy(buffer, "-*-*-*-*-normal-*-[12 0 0 12]-*-72-*-*-*-iso8859-1");
2938       if( (x_fs = safe_XLoadQueryFont(gdi_display, buffer)) )
2939       {
2940           text_caps |= TC_SF_X_YINDEP;
2941           XFreeFont(gdi_display, x_fs);
2942       }
2943   }
2944   wine_tsx11_unlock();
2945
2946   HeapFree(GetProcessHeap(), 0, buffer);
2947
2948   XFONT_WindowsNames();
2949   XFONT_LoadAliases( hkey );
2950   if (hkey) XFONT_LoadDefaults( hkey );
2951   XFONT_LoadIgnores( hkey );
2952
2953   /* fontList initialization is over, allocate X font cache */
2954
2955   fontCache = HeapAlloc(GetProcessHeap(), 0, fontCacheSize * sizeof(fontObject));
2956   XFONT_GrowFreeList(0, fontCacheSize - 1);
2957
2958   TRACE("done!\n");
2959   if (hkey) RegCloseKey(hkey);
2960 }
2961
2962 /***********************************************************************
2963  *           X11DRV_FONT_Init
2964  */
2965 void X11DRV_FONT_Init( int log_pixels_x, int log_pixels_y )
2966 {
2967     XFONT_GetDefResolution( log_pixels_x, log_pixels_y );
2968
2969     if(using_client_side_fonts)
2970         text_caps |= TC_VA_ABLE;
2971
2972     return;
2973 }
2974
2975 /**********************************************************************
2976  *      XFONT_SetX11Trans
2977  */
2978 static BOOL XFONT_SetX11Trans( fontObject *pfo )
2979 {
2980   char *fontName;
2981   Atom nameAtom;
2982   LFD lfd;
2983
2984   wine_tsx11_lock();
2985   XGetFontProperty( pfo->fs, XA_FONT, &nameAtom );
2986   fontName = XGetAtomName( gdi_display, nameAtom );
2987   if (!LFD_Parse(fontName, &lfd) || lfd.pixel_size[0] != '[')
2988   {
2989       XFree(fontName);
2990       wine_tsx11_unlock();
2991       return FALSE;
2992   }
2993 #define PX pfo->lpX11Trans
2994
2995   sscanf(lfd.pixel_size, "[%f%f%f%f]", &PX->a, &PX->b, &PX->c, &PX->d);
2996   XFree(fontName);
2997
2998   XGetFontProperty( pfo->fs, x11drv_atom(RAW_ASCENT), &PX->RAW_ASCENT );
2999   XGetFontProperty( pfo->fs, x11drv_atom(RAW_DESCENT), &PX->RAW_DESCENT );
3000   wine_tsx11_unlock();
3001
3002   PX->pixelsize = hypot(PX->a, PX->b);
3003   PX->ascent = PX->pixelsize / 1000.0 * PX->RAW_ASCENT;
3004   PX->descent = PX->pixelsize / 1000.0 * PX->RAW_DESCENT;
3005
3006   TRACE("[%f %f %f %f] RA = %ld RD = %ld\n",
3007         PX->a, PX->b, PX->c, PX->d,
3008         PX->RAW_ASCENT, PX->RAW_DESCENT);
3009
3010 #undef PX
3011   return TRUE;
3012 }
3013
3014 /***********************************************************************
3015  *           X Device Font Objects
3016  */
3017 static X_PHYSFONT XFONT_RealizeFont( LPLOGFONT16 plf,
3018                                      LPCSTR* faceMatched, BOOL bSubFont,
3019                                      WORD internal_charset,
3020                                      WORD* pcharsetMatched )
3021 {
3022     UINT16      checksum;
3023     INT         index = 0;
3024     fontObject* pfo;
3025
3026     pfo = XFONT_LookupCachedFont( plf, &checksum );
3027     if( !pfo )
3028     {
3029         fontMatch       fm;
3030         INT             i;
3031
3032         fm.pfr = NULL;
3033         fm.pfi = NULL;
3034         fm.height = 0;
3035         fm.flags = 0;
3036         fm.plf = plf;
3037         fm.internal_charset = internal_charset;
3038
3039         if( text_caps & TC_SF_X_YINDEP ) fm.flags = FO_MATCH_XYINDEP;
3040
3041         /* allocate new font cache entry */
3042
3043         if( (pfo = XFONT_GetCacheEntry()) )
3044         {
3045             /* initialize entry and load font */
3046             char lpLFD[MAX_LFD_LENGTH];
3047             UINT uRelaxLevel = 0;
3048
3049             if(abs(plf->lfHeight) > MAX_FONT_SIZE) {
3050                 ERR(
3051   "plf->lfHeight = %d, Creating a 100 pixel font and rescaling metrics\n",
3052                     plf->lfHeight);
3053                 pfo->rescale = fabs(plf->lfHeight / 100.0);
3054                 if(plf->lfHeight > 0) plf->lfHeight = 100;
3055                 else plf->lfHeight = -100;
3056             } else
3057                 pfo->rescale = 1.0;
3058
3059             XFONT_MatchDeviceFont( fontList, &fm );
3060             pfo->fr = fm.pfr;
3061             pfo->fi = fm.pfi;
3062             pfo->fr->fo_count++;
3063             pfo->fo_flags = fm.flags & ~FO_MATCH_MASK;
3064
3065             pfo->lf = *plf;
3066             pfo->lfchecksum = checksum;
3067
3068             do
3069             {
3070                 LFD_ComposeLFD( pfo, fm.height, lpLFD, uRelaxLevel++ );
3071                 if( (pfo->fs = safe_XLoadQueryFont( gdi_display, lpLFD )) ) break;
3072             } while( uRelaxLevel );
3073
3074
3075             if(pfo->lf.lfEscapement != 0) {
3076                 pfo->lpX11Trans = HeapAlloc(GetProcessHeap(), 0, sizeof(XFONTTRANS));
3077                 if(!XFONT_SetX11Trans( pfo )) {
3078                     HeapFree(GetProcessHeap(), 0, pfo->lpX11Trans);
3079                     pfo->lpX11Trans = NULL;
3080                 }
3081             }
3082             XFONT_GetLeading( &pfo->fi->df, pfo->fs,
3083                               &pfo->foInternalLeading, NULL, pfo->lpX11Trans );
3084             pfo->foAvgCharWidth = (INT16)XFONT_GetAvgCharWidth(&pfo->fi->df, pfo->fs, pfo->lpX11Trans );
3085             pfo->foMaxCharWidth = (INT16)XFONT_GetMaxCharWidth(pfo->fs, pfo->lpX11Trans);
3086
3087             /* FIXME: If we've got a soft font or
3088              * there are FO_SYNTH_... flags for the
3089              * non PROOF_QUALITY request, the engine
3090              * should rasterize characters into mono
3091              * pixmaps and store them in the pfo->lpPixmap
3092              * array (pfo->fs should be updated as well).
3093              * array (pfo->fs should be updated as well).
3094              * X11DRV_ExtTextOut() must be heavily modified
3095              * to support pixmap blitting and FO_SYNTH_...
3096              * styles.
3097              */
3098
3099             pfo->lpPixmap = NULL;
3100
3101             for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3102                 pfo->prefobjs[i] = (X_PHYSFONT)0xffffffff; /* invalid value */
3103
3104             /* special treatment for DBCS that needs multiple fonts */
3105             /* All member of pfo must be set correctly. */
3106             if ( bSubFont == FALSE )
3107             {
3108                 WORD charset_sub;
3109                 WORD charsetMatchedSub;
3110                 LOGFONT16 lfSub;
3111                 LPCSTR faceMatchedSub;
3112
3113                 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3114                 {
3115                     charset_sub = X11DRV_cptable[pfo->fi->cptable].
3116                                 penum_subfont_charset( i );
3117                     if ( charset_sub == DEFAULT_CHARSET ) break;
3118
3119                     lfSub = *plf;
3120                     lfSub.lfWidth = 0;
3121                    lfSub.lfHeight=plf->lfHeight;
3122                     lfSub.lfCharSet = (BYTE)(charset_sub & 0xff);
3123                     lfSub.lfFaceName[0] = '\0'; /* FIXME? */
3124                     /* this font has sub font */
3125                     if ( i == 0 ) pfo->prefobjs[0] = (X_PHYSFONT)0;
3126                     pfo->prefobjs[i] =
3127                         XFONT_RealizeFont( &lfSub, &faceMatchedSub,
3128                                            TRUE, charset_sub,
3129                                            &charsetMatchedSub );
3130                     /* FIXME: check charsetMatchedSub */
3131                 }
3132             }
3133         }
3134
3135         if( !pfo ) /* couldn't get a new entry, get one of the cached fonts */
3136         {
3137             UINT                current_score, score = (UINT)(-1);
3138
3139             i = index = fontMRU;
3140             fm.flags |= FO_MATCH_PAF;
3141             do
3142             {
3143                 pfo = fontCache + i;
3144                 fm.pfr = pfo->fr; fm.pfi = pfo->fi;
3145
3146                 current_score = XFONT_Match( &fm );
3147                 if( current_score < score ) index = i;
3148
3149                 i =  pfo->lru;
3150             } while( i >= 0 );
3151             pfo = fontCache + index;
3152             goto END;
3153         }
3154     }
3155
3156     /* attach at the head of the lru list */
3157     pfo->lru = fontMRU;
3158     index = fontMRU = (pfo - fontCache);
3159
3160 END:
3161     pfo->count++;
3162
3163     TRACE("physfont %i\n", index);
3164     *faceMatched = pfo->fi->df.dfFace;
3165     *pcharsetMatched = pfo->fi->internal_charset;
3166
3167     return (X_PHYSFONT)(X_PFONT_MAGIC | index);
3168 }
3169
3170 /***********************************************************************
3171  *           XFONT_GetFontObject
3172  */
3173 fontObject* XFONT_GetFontObject( X_PHYSFONT pFont )
3174 {
3175     if( CHECK_PFONT(pFont) ) return __PFONT(pFont);
3176     return NULL;
3177 }
3178
3179 /***********************************************************************
3180  *           XFONT_GetFontStruct
3181  */
3182 XFontStruct* XFONT_GetFontStruct( X_PHYSFONT pFont )
3183 {
3184     if( CHECK_PFONT(pFont) ) return __PFONT(pFont)->fs;
3185     return NULL;
3186 }
3187
3188 /***********************************************************************
3189  *           XFONT_GetFontInfo
3190  */
3191 LPIFONTINFO16 XFONT_GetFontInfo( X_PHYSFONT pFont )
3192 {
3193     if( CHECK_PFONT(pFont) ) return &(__PFONT(pFont)->fi->df);
3194     return NULL;
3195 }
3196
3197
3198
3199 /* X11DRV Interface ****************************************************
3200  *                                                                     *
3201  * Exposed via the dc->funcs dispatch table.                           *
3202  *                                                                     *
3203  ***********************************************************************/
3204 /***********************************************************************
3205  *           SelectFont   (X11DRV.@)
3206  */
3207 HFONT X11DRV_SelectFont( X11DRV_PDEVICE *physDev, HFONT hfont, HANDLE gdiFont )
3208 {
3209     LOGFONTW logfont;
3210     LOGFONT16 lf;
3211
3212     TRACE("hdc=%p, hfont=%p\n", physDev->hdc, hfont);
3213
3214     if (!GetObjectW( hfont, sizeof(logfont), &logfont )) return HGDI_ERROR;
3215
3216     TRACE("gdiFont = %p\n", gdiFont);
3217
3218     if(gdiFont && using_client_side_fonts) {
3219         X11DRV_XRender_SelectFont(physDev, hfont);
3220         physDev->has_gdi_font = TRUE;
3221         return FALSE;
3222     }
3223
3224     EnterCriticalSection( &crtsc_fonts_X11 );
3225
3226     if(fontList == NULL) X11DRV_FONT_InitX11Metrics();
3227
3228     if( CHECK_PFONT(physDev->font) )
3229         XFONT_ReleaseCacheEntry( __PFONT(physDev->font) );
3230
3231     FONT_LogFontWTo16(&logfont, &lf);
3232
3233     /* stock fonts ignore the mapping mode */
3234     if (!is_stock_font( hfont ))
3235     {
3236         /* Make sure we don't change the sign when converting to device coords */
3237         /* FIXME - check that the other drivers do this correctly */
3238         if (lf.lfWidth)
3239         {
3240             INT width = X11DRV_XWStoDS( physDev, lf.lfWidth );
3241             lf.lfWidth = (lf.lfWidth < 0) ? -abs(width) : abs(width);
3242             if (lf.lfWidth == 0)
3243                 lf.lfWidth = 1; /* Minimum width */
3244         }
3245         if (lf.lfHeight)
3246         {
3247             INT height = X11DRV_YWStoDS( physDev, lf.lfHeight );
3248             lf.lfHeight = (lf.lfHeight < 0) ? -abs(height) : abs(height);
3249             if (lf.lfHeight == 0)
3250                 lf.lfHeight = MIN_FONT_SIZE;
3251         }
3252     }
3253
3254     if (!lf.lfHeight)
3255         lf.lfHeight = -(DEF_POINT_SIZE * GetDeviceCaps(physDev->hdc,LOGPIXELSY) + (72>>1)) / 72;
3256
3257     {
3258         /* Fixup aliases before passing to RealizeFont */
3259         /* alias = Windows name in the alias table */
3260         LPCSTR alias = XFONT_UnAlias( lf.lfFaceName );
3261         LPCSTR faceMatched;
3262         WORD charsetMatched;
3263
3264         TRACE("hfont=%p\n", hfont); /* to connect with the trace from RealizeFont */
3265         physDev->font = XFONT_RealizeFont( &lf, &faceMatched,
3266                                            FALSE, lf.lfCharSet,
3267                                            &charsetMatched );
3268
3269         /* set face to the requested facename if it matched
3270          * so that GetTextFace can get the correct face name
3271          */
3272         if (alias && !strcmp(faceMatched, lf.lfFaceName))
3273             MultiByteToWideChar(CP_ACP, 0, alias, -1,
3274                                 logfont.lfFaceName, LF_FACESIZE);
3275         else
3276             MultiByteToWideChar(CP_ACP, 0, faceMatched, -1,
3277                               logfont.lfFaceName, LF_FACESIZE);
3278
3279         /*
3280          * In X, some encodings may have the same lfFaceName.
3281          * for example:
3282          *   -misc-fixed-*-iso8859-1
3283          *   -misc-fixed-*-jisx0208.1990-0
3284          * so charset should be saved...
3285          */
3286         logfont.lfCharSet = charsetMatched;
3287     }
3288
3289     LeaveCriticalSection( &crtsc_fonts_X11 );
3290
3291     physDev->has_gdi_font = FALSE;
3292     return (HFONT)1; /* Use a device font */
3293 }
3294
3295
3296 /***********************************************************************
3297  *
3298  *           X11DRV_EnumDeviceFonts
3299  */
3300 BOOL X11DRV_EnumDeviceFonts( X11DRV_PDEVICE *physDev, LPLOGFONTW plf,
3301                              FONTENUMPROCW proc, LPARAM lp )
3302 {
3303     ENUMLOGFONTEXW      lf;
3304     NEWTEXTMETRICEXW    tm;
3305     fontResource*       pfr = fontList;
3306     BOOL                b, bRet = 0;
3307
3308     /* don't enumerate x11 fonts if we're using client side fonts */
3309     if (physDev->has_gdi_font) return FALSE;
3310
3311     if( plf->lfFaceName[0] )
3312     {
3313         char facename[LF_FACESIZE+1];
3314         WideCharToMultiByte( CP_ACP, 0, plf->lfFaceName, -1,
3315                              facename, sizeof(facename), NULL, NULL );
3316         /* enum all entries in this resource */
3317         pfr = XFONT_FindFIList( pfr, facename );
3318         if( pfr )
3319         {
3320             fontInfo*   pfi;
3321             for( pfi = pfr->fi; pfi; pfi = pfi->next )
3322             {
3323                 /* Note: XFONT_GetFontMetric() will have to
3324                    release the crit section, font list will
3325                    have to be retraversed on return */
3326
3327                 if(plf->lfCharSet == DEFAULT_CHARSET ||
3328                    plf->lfCharSet == pfi->df.dfCharSet) {
3329                     if( (b = (*proc)( &lf.elfLogFont, (TEXTMETRICW *)&tm,
3330                                XFONT_GetFontMetric( pfi, &lf, &tm ), lp )) )
3331                         bRet = b;
3332                     else break;
3333                 }
3334             }
3335         }
3336     }
3337     else /* enum first entry in each resource */
3338         for( ; pfr ; pfr = pfr->next )
3339         {
3340             if(pfr->fi)
3341             {
3342                 if( (b = (*proc)( &lf.elfLogFont, (TEXTMETRICW *)&tm,
3343                            XFONT_GetFontMetric( pfr->fi, &lf, &tm ), lp )) )
3344                     bRet = b;
3345                 else break;
3346             }
3347         }
3348     return bRet;
3349 }
3350
3351
3352 /***********************************************************************
3353  *           X11DRV_GetTextMetrics
3354  */
3355 BOOL X11DRV_GetTextMetrics(X11DRV_PDEVICE *physDev, TEXTMETRICW *metrics)
3356 {
3357     if( CHECK_PFONT(physDev->font) )
3358     {
3359         fontObject* pfo = __PFONT(physDev->font);
3360         X11DRV_cptable[pfo->fi->cptable].pGetTextMetricsW( pfo, metrics );
3361         return TRUE;
3362     }
3363     return FALSE;
3364 }
3365
3366
3367 /***********************************************************************
3368  *           X11DRV_GetCharWidth
3369  */
3370 BOOL X11DRV_GetCharWidth( X11DRV_PDEVICE *physDev, UINT firstChar, UINT lastChar,
3371                             LPINT buffer )
3372 {
3373     fontObject* pfo = XFONT_GetFontObject( physDev->font );
3374
3375     if( pfo )
3376     {
3377         unsigned int i;
3378
3379         if (pfo->fs->per_char == NULL)
3380             for (i = firstChar; i <= lastChar; i++)
3381                 if(pfo->lpX11Trans)
3382                     *buffer++ = pfo->fs->min_bounds.attributes *
3383                       pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3384                 else
3385                     *buffer++ = pfo->fs->min_bounds.width * pfo->rescale;
3386         else
3387         {
3388             XCharStruct *cs, *def;
3389             static XCharStruct  __null_char = { 0, 0, 0, 0, 0, 0 };
3390
3391             CI_GET_CHAR_INFO(pfo->fs, pfo->fs->default_char, &__null_char,
3392                              def);
3393
3394             for (i = firstChar; i <= lastChar; i++)
3395             {
3396                 WCHAR wch = i;
3397                 BYTE ch;
3398                 UINT ch_f; /* character code in the font encoding */
3399                 WideCharToMultiByte( pfo->fi->codepage, 0, &wch, 1, (LPSTR)&ch, 1, NULL, NULL );
3400                 ch_f = ch;
3401                 if (ch_f >= pfo->fs->min_char_or_byte2 &&
3402                     ch_f <= pfo->fs->max_char_or_byte2)
3403                 {
3404                     cs = &pfo->fs->per_char[(ch_f - pfo->fs->min_char_or_byte2)];
3405                     if (CI_NONEXISTCHAR(cs)) cs = def;
3406                 } else cs = def;
3407                 if(pfo->lpX11Trans)
3408                     *buffer++ = max(cs->attributes, 0) *
3409                       pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3410                 else
3411                     *buffer++ = max(cs->width, 0 ) * pfo->rescale;
3412             }
3413         }
3414
3415         return TRUE;
3416     }
3417     return FALSE;
3418 }