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