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