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