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