DeleteColumn should return success even for uOwnerData.
[wine/gsoc_dplay.git] / graphics / x11drv / xfont.c
blob186bde51878db1d5a2ceefedd4b1fb5e5a08228a
1 /*
2 * X11 physical font objects
4 * Copyright 1997 Alex Korobka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * TODO: Mapping algorithm tweaks, FO_SYNTH_... flags (ExtTextOut() will
21 * have to be changed for that), dynamic font loading (FreeType).
24 #include "config.h"
25 #include "wine/port.h"
27 #include <X11/Xatom.h>
29 #include "ts_xlib.h"
31 #include <ctype.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <sys/types.h>
37 #include <fcntl.h>
38 #include <math.h>
40 #include "windef.h"
41 #include "wingdi.h"
42 #include "winnls.h"
43 #include "winreg.h"
44 #include "font.h"
45 #include "user.h" /* for TWEAK_WineLook (FIXME) */
46 #include "x11font.h"
47 #include "wine/library.h"
48 #include "wine/unicode.h"
49 #include "wine/debug.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(font);
53 #define X_PFONT_MAGIC (0xFADE0000)
54 #define X_FMC_MAGIC (0x0000CAFE)
56 #define MAX_FONTS 1024*16
57 #define MAX_LFD_LENGTH 256
58 #define TILDE '~'
59 #define HYPHEN '-'
61 #define DEF_POINT_SIZE 8 /* CreateFont(0 .. ) gets this */
62 #define DEF_SCALABLE_HEIGHT 100 /* pixels */
63 #define MIN_FONT_SIZE 2 /* Min size in pixels */
64 #define MAX_FONT_SIZE 1000 /* Max size in pixels */
66 #define REMOVE_SUBSETS 1
67 #define UNMARK_SUBSETS 0
69 #define FONTCACHE 32 /* dynamic font cache size */
71 #define FF_FAMILY (FF_MODERN | FF_SWISS | FF_ROMAN | FF_DECORATIVE | FF_SCRIPT)
73 typedef struct __fontAlias
75 LPSTR faTypeFace;
76 LPSTR faAlias;
77 struct __fontAlias* next;
78 } fontAlias;
80 static fontAlias *aliasTable = NULL;
82 static const char* INIFontMetrics = "cachedmetrics.";
83 static const char* INIFontSection = "Software\\Wine\\Wine\\Config\\fonts";
84 static const char* INIAliasSection = "Alias";
85 static const char* INIIgnoreSection = "Ignore";
86 static const char* INIDefault = "Default";
87 static const char* INIDefaultFixed = "DefaultFixed";
88 static const char* INIResolution = "Resolution";
89 static const char* INIGlobalMetrics = "FontMetrics";
90 static const char* INIDefaultSerif = "DefaultSerif";
91 static const char* INIDefaultSansSerif = "DefaultSansSerif";
94 /* FIXME - are there any more Latin charsets ? */
95 /* FIXME - RUSSIAN, ARABIC, GREEK, HEBREW are NOT Latin */
96 #define IS_LATIN_CHARSET(ch) \
97 ((ch)==ANSI_CHARSET ||\
98 (ch)==EE_CHARSET ||\
99 (ch)==ISO3_CHARSET ||\
100 (ch)==ISO4_CHARSET ||\
101 (ch)==RUSSIAN_CHARSET ||\
102 (ch)==ARABIC_CHARSET ||\
103 (ch)==GREEK_CHARSET ||\
104 (ch)==HEBREW_CHARSET ||\
105 (ch)==TURKISH_CHARSET ||\
106 (ch)==ISO10_CHARSET ||\
107 (ch)==BALTIC_CHARSET ||\
108 (ch)==CELTIC_CHARSET)
110 /* suffix-charset mapping tables - must be less than 254 entries long */
112 typedef struct __sufch
114 LPCSTR psuffix;
115 WORD charset; /* hibyte != 0 means *internal* charset */
116 WORD codepage;
117 WORD cptable;
118 } SuffixCharset;
120 static const SuffixCharset sufch_ansi[] = {
121 { "0", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
122 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
124 static const SuffixCharset sufch_iso646[] = {
125 { "irv", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
126 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
128 static const SuffixCharset sufch_iso8859[] = {
129 { "1", ANSI_CHARSET, 28591, X11DRV_CPTABLE_SBCS },
130 { "2", EE_CHARSET, 28592, X11DRV_CPTABLE_SBCS },
131 { "3", ISO3_CHARSET, 28593, X11DRV_CPTABLE_SBCS },
132 { "4", ISO4_CHARSET, 28594, X11DRV_CPTABLE_SBCS },
133 { "5", RUSSIAN_CHARSET, 28595, X11DRV_CPTABLE_SBCS },
134 { "6", ARABIC_CHARSET, 28596, X11DRV_CPTABLE_SBCS },
135 { "7", GREEK_CHARSET, 28597, X11DRV_CPTABLE_SBCS },
136 { "8", HEBREW_CHARSET, 28598, X11DRV_CPTABLE_SBCS },
137 { "9", TURKISH_CHARSET, 28599, X11DRV_CPTABLE_SBCS },
138 { "10", ISO10_CHARSET, 28600, X11DRV_CPTABLE_SBCS },
139 { "11", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
140 { "12", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
141 { "13", BALTIC_CHARSET, 28603, X11DRV_CPTABLE_SBCS },
142 { "14", CELTIC_CHARSET, 28604, X11DRV_CPTABLE_SBCS },
143 { "15", ANSI_CHARSET, 28605, X11DRV_CPTABLE_SBCS },
144 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
146 static const SuffixCharset sufch_microsoft[] = {
147 { "cp1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
148 { "cp1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
149 { "cp1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
150 { "cp1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
151 { "cp1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
152 { "cp1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
153 { "cp1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
154 { "cp1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
155 { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SYMBOL },
156 { "symbol", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SYMBOL },
157 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
159 static const SuffixCharset sufch_tcvn[] = {
160 { "0", TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
161 { NULL, TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
163 static const SuffixCharset sufch_tis620[] = {
164 { "0", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
165 { NULL, THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }};
167 static const SuffixCharset sufch_viscii[] = {
168 { "1", VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
169 { NULL, VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
171 static const SuffixCharset sufch_windows[] = {
172 { "1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
173 { "1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
174 { "1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
175 { "1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
176 { "1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
177 { "1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
178 { "1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
179 { "1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
180 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
182 static const SuffixCharset sufch_koi8[] = {
183 { "r", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
184 { "ru", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
185 { "u", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
186 { NULL, RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS }};
188 static const SuffixCharset sufch_jisx0201[] = {
189 { "0", X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS },
190 { NULL, X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS }};
192 static const SuffixCharset sufch_jisx0208[] = {
193 { "0", SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 },
194 { NULL, SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
196 static const SuffixCharset sufch_jisx0212[] = {
197 { "0", X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 },
198 { NULL, X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
200 static const SuffixCharset sufch_ksc5601[] = {
201 { "0", HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 },
202 { NULL, HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 }};
204 static const SuffixCharset sufch_gb2312[] = {
205 { "0", GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 },
206 { NULL, GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 }};
208 static const SuffixCharset sufch_big5[] = {
209 { "0", CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 },
210 { NULL, CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 }};
212 static const SuffixCharset sufch_unicode[] = {
213 { "0", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
214 { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
216 static const SuffixCharset sufch_iso10646[] = {
217 { "1", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
218 { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
220 static const SuffixCharset sufch_dec[] = {
221 { "dectech", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
222 { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
224 /* Each of these must be matched explicitly */
225 static const SuffixCharset sufch_any[] = {
226 { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
227 { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
230 typedef struct __fet
232 LPSTR prefix;
233 const SuffixCharset* sufch;
234 struct __fet* next;
235 } fontEncodingTemplate;
237 /* Note: we can attach additional encoding mappings to the end
238 * of this table at runtime.
240 static fontEncodingTemplate __fETTable[] = {
241 { "ansi", sufch_ansi, &__fETTable[1] },
242 { "ascii", sufch_ansi, &__fETTable[2] },
243 { "iso646.1991", sufch_iso646, &__fETTable[3] },
244 { "iso8859", sufch_iso8859, &__fETTable[4] },
245 { "microsoft", sufch_microsoft, &__fETTable[5] },
246 { "tcvn", sufch_tcvn, &__fETTable[6] },
247 { "tis620.2533", sufch_tis620, &__fETTable[7] },
248 { "viscii1.1", sufch_viscii, &__fETTable[8] },
249 { "windows", sufch_windows, &__fETTable[9] },
250 { "koi8", sufch_koi8, &__fETTable[10]},
251 { "jisx0201.1976",sufch_jisx0201, &__fETTable[11]},
252 { "jisc6226.1978",sufch_jisx0208, &__fETTable[12]},
253 { "jisx0208.1983",sufch_jisx0208, &__fETTable[13]},
254 { "jisx0208.1990",sufch_jisx0208, &__fETTable[14]},
255 { "jisx0212.1990",sufch_jisx0212, &__fETTable[15]},
256 { "ksc5601.1987", sufch_ksc5601, &__fETTable[16]},
257 { "gb2312.1980", sufch_gb2312, &__fETTable[17]},
258 { "big5", sufch_big5, &__fETTable[18]},
259 { "unicode", sufch_unicode, &__fETTable[19]},
260 { "iso10646", sufch_iso10646, &__fETTable[20]},
261 { "cp", sufch_windows, &__fETTable[21]},
262 { "dec", sufch_dec, &__fETTable[22]},
263 /* NULL prefix matches anything so put it last */
264 { NULL, sufch_any, NULL },
266 static fontEncodingTemplate* fETTable = __fETTable;
268 /* a charset database for known facenames */
269 struct CharsetBindingInfo
271 const char* pszFaceName;
272 BYTE charset;
274 static const struct CharsetBindingInfo charsetbindings[] =
276 /* special facenames */
277 { "System", DEFAULT_CHARSET },
278 { "FixedSys", DEFAULT_CHARSET },
280 /* known facenames */
281 { "MS Serif", ANSI_CHARSET },
282 { "MS Sans Serif", ANSI_CHARSET },
283 { "Courier", ANSI_CHARSET },
284 { "Symbol", SYMBOL_CHARSET },
286 { "Arial", ANSI_CHARSET },
287 { "Arial Greek", GREEK_CHARSET },
288 { "Arial Tur", TURKISH_CHARSET },
289 { "Arial Baltic", BALTIC_CHARSET },
290 { "Arial CE", EASTEUROPE_CHARSET },
291 { "Arial Cyr", RUSSIAN_CHARSET },
292 { "Courier New", ANSI_CHARSET },
293 { "Courier New Greek", GREEK_CHARSET },
294 { "Courier New Tur", TURKISH_CHARSET },
295 { "Courier New Baltic", BALTIC_CHARSET },
296 { "Courier New CE", EASTEUROPE_CHARSET },
297 { "Courier New Cyr", RUSSIAN_CHARSET },
298 { "Times New Roman", ANSI_CHARSET },
299 { "Times New Roman Greek", GREEK_CHARSET },
300 { "Times New Roman Tur", TURKISH_CHARSET },
301 { "Times New Roman Baltic", BALTIC_CHARSET },
302 { "Times New Roman CE", EASTEUROPE_CHARSET },
303 { "Times New Roman Cyr", RUSSIAN_CHARSET },
305 { "\x82\x6c\x82\x72 \x83\x53\x83\x56\x83\x62\x83\x4e",
306 SHIFTJIS_CHARSET }, /* MS gothic */
307 { "\x82\x6c\x82\x72 \x82\x6f\x83\x53\x83\x56\x83\x62\x83\x4e",
308 SHIFTJIS_CHARSET }, /* MS P gothic */
309 { "\x82\x6c\x82\x72 \x96\xbe\x92\xa9",
310 SHIFTJIS_CHARSET }, /* MS mincho */
311 { "\x82\x6c\x82\x72 \x82\x6f\x96\xbe\x92\xa9",
312 SHIFTJIS_CHARSET }, /* MS P mincho */
313 { "GulimChe", HANGEUL_CHARSET },
314 { "MS Song", GB2312_CHARSET },
315 { "MS Hei", GB2312_CHARSET },
316 { "\xb7\x73\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },/*MS Mingliu*/
317 { "\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },
319 { NULL, 0 }
323 static int DefResolution = 0;
325 static CRITICAL_SECTION crtsc_fonts_X11 = CRITICAL_SECTION_INIT("crtsc_fonts_X11");
327 static fontResource* fontList = NULL;
328 static fontObject* fontCache = NULL; /* array */
329 static int fontCacheSize = FONTCACHE;
330 static int fontLF = -1, fontMRU = -1; /* last free, most recently used */
332 #define __PFONT(pFont) ( fontCache + ((UINT)(pFont) & 0x0000FFFF) )
333 #define CHECK_PFONT(pFont) ( (((UINT)(pFont) & 0xFFFF0000) == X_PFONT_MAGIC) &&\
334 (((UINT)(pFont) & 0x0000FFFF) < fontCacheSize) )
336 static Atom RAW_ASCENT;
337 static Atom RAW_DESCENT;
339 /***********************************************************************
340 * Helper macros from X distribution
343 #define CI_NONEXISTCHAR(cs) (((cs)->width == 0) && \
344 (((cs)->rbearing|(cs)->lbearing| \
345 (cs)->ascent|(cs)->descent) == 0))
347 #define CI_GET_CHAR_INFO(fs,col,def,cs) \
349 cs = def; \
350 if (col >= fs->min_char_or_byte2 && col <= fs->max_char_or_byte2) { \
351 if (fs->per_char == NULL) { \
352 cs = &fs->min_bounds; \
353 } else { \
354 cs = &fs->per_char[(col - fs->min_char_or_byte2)]; \
355 if (CI_NONEXISTCHAR(cs)) cs = def; \
360 #define CI_GET_DEFAULT_INFO(fs,cs) \
361 CI_GET_CHAR_INFO(fs, fs->default_char, NULL, cs)
364 /***********************************************************************
365 * is_stock_font
367 inline static BOOL is_stock_font( HFONT font )
369 int i;
370 for (i = OEM_FIXED_FONT; i <= DEFAULT_GUI_FONT; i++)
372 if (i != DEFAULT_PALETTE && font == GetStockObject(i)) return TRUE;
374 return FALSE;
378 /***********************************************************************
379 * Checksums
381 static UINT16 __lfCheckSum( LPLOGFONT16 plf )
383 CHAR font[LF_FACESIZE];
384 UINT16 checksum = 0;
385 UINT16 *ptr;
386 int i;
388 ptr = (UINT16 *)plf;
389 for (i = 0; i < 9; i++) checksum ^= *ptr++;
390 for (i = 0; i < LF_FACESIZE; i++)
392 font[i] = tolower(plf->lfFaceName[i]);
393 if (!font[i] || font[i] == ' ') break;
395 for (ptr = (UINT16 *)font, i >>= 1; i > 0; i-- ) checksum ^= *ptr++;
396 return checksum;
399 static UINT16 __genericCheckSum( const void *ptr, int size )
401 unsigned int checksum = 0;
402 const char *p = (const char *)ptr;
403 while (size-- > 0)
404 checksum ^= (checksum << 3) + (checksum >> 29) + *p++;
406 return checksum & 0xffff;
409 /*************************************************************************
410 * LFD parse/compose routines
412 * NB. LFD_Parse will use lpFont for its own ends, so if you want to keep it
413 * make a copy first
415 * These functions also do TILDE to HYPHEN conversion
417 static LFD* LFD_Parse(LPSTR lpFont)
419 LFD* lfd;
420 char *lpch = lpFont, *lfd_fld[LFD_FIELDS], *field_start;
421 int i;
422 if (*lpch != HYPHEN)
424 WARN("font '%s' doesn't begin with '%c'\n", lpFont, HYPHEN);
425 return NULL;
428 field_start = ++lpch;
429 for( i = 0; i < LFD_FIELDS; )
431 if (*lpch == HYPHEN)
433 *lpch = '\0';
434 lfd_fld[i] = field_start;
435 i++;
436 field_start = ++lpch;
438 else if (!*lpch)
440 lfd_fld[i] = field_start;
441 i++;
442 break;
444 else if (*lpch == TILDE)
446 *lpch = HYPHEN;
447 ++lpch;
449 else
450 ++lpch;
452 /* Fill in the empty fields with NULLS */
453 for (; i< LFD_FIELDS; i++)
454 lfd_fld[i] = NULL;
455 if (*lpch)
456 WARN("Extra ignored in font '%s'\n", lpFont);
458 lfd = HeapAlloc( GetProcessHeap(), 0, sizeof(LFD) );
459 if (lfd)
461 lfd->foundry = lfd_fld[0];
462 lfd->family = lfd_fld[1];
463 lfd->weight = lfd_fld[2];
464 lfd->slant = lfd_fld[3];
465 lfd->set_width = lfd_fld[4];
466 lfd->add_style = lfd_fld[5];
467 lfd->pixel_size = lfd_fld[6];
468 lfd->point_size = lfd_fld[7];
469 lfd->resolution_x = lfd_fld[8];
470 lfd->resolution_y = lfd_fld[9];
471 lfd->spacing = lfd_fld[10];
472 lfd->average_width = lfd_fld[11];
473 lfd->charset_registry = lfd_fld[12];
474 lfd->charset_encoding = lfd_fld[13];
476 return lfd;
480 static void LFD_UnParse(LPSTR dp, UINT buf_size, LFD* lfd)
482 const char* lfd_fld[LFD_FIELDS];
483 int i;
485 if (!buf_size)
486 return; /* Dont be silly */
488 lfd_fld[0] = lfd->foundry;
489 lfd_fld[1] = lfd->family;
490 lfd_fld[2] = lfd->weight ;
491 lfd_fld[3] = lfd->slant ;
492 lfd_fld[4] = lfd->set_width ;
493 lfd_fld[5] = lfd->add_style;
494 lfd_fld[6] = lfd->pixel_size;
495 lfd_fld[7] = lfd->point_size;
496 lfd_fld[8] = lfd->resolution_x;
497 lfd_fld[9] = lfd->resolution_y ;
498 lfd_fld[10] = lfd->spacing ;
499 lfd_fld[11] = lfd->average_width ;
500 lfd_fld[12] = lfd->charset_registry ;
501 lfd_fld[13] = lfd->charset_encoding ;
503 buf_size--; /* Room for the terminator */
505 for (i = 0; i < LFD_FIELDS; i++)
507 const char* sp = lfd_fld[i];
508 if (!sp || !buf_size)
509 break;
511 *dp++ = HYPHEN;
512 buf_size--;
513 while (buf_size > 0 && *sp)
515 *dp = (*sp == HYPHEN) ? TILDE : *sp;
516 buf_size--;
517 dp++; sp++;
520 *dp = '\0';
524 static void LFD_GetWeight( fontInfo* fi, LPCSTR lpStr)
526 int j = strlen(lpStr);
527 if( j == 1 && *lpStr == '0')
528 fi->fi_flags |= FI_POLYWEIGHT;
529 else if( j == 4 )
531 if( !strcasecmp( "bold", lpStr) )
532 fi->df.dfWeight = FW_BOLD;
533 else if( !strcasecmp( "demi", lpStr) )
535 fi->fi_flags |= FI_FW_DEMI;
536 fi->df.dfWeight = FW_DEMIBOLD;
538 else if( !strcasecmp( "book", lpStr) )
540 fi->fi_flags |= FI_FW_BOOK;
541 fi->df.dfWeight = FW_REGULAR;
544 else if( j == 5 )
546 if( !strcasecmp( "light", lpStr) )
547 fi->df.dfWeight = FW_LIGHT;
548 else if( !strcasecmp( "black", lpStr) )
549 fi->df.dfWeight = FW_BLACK;
551 else if( j == 6 && !strcasecmp( "medium", lpStr) )
552 fi->df.dfWeight = FW_REGULAR;
553 else if( j == 8 && !strcasecmp( "demibold", lpStr) )
554 fi->df.dfWeight = FW_DEMIBOLD;
555 else
556 fi->df.dfWeight = FW_DONTCARE; /* FIXME: try to get something
557 * from the weight property */
560 static BOOL LFD_GetSlant( fontInfo* fi, LPCSTR lpStr)
562 int l = strlen(lpStr);
563 if( l == 1 )
565 switch( tolower( *lpStr ) )
567 case '0': fi->fi_flags |= FI_POLYSLANT; /* haven't seen this one yet */
568 default:
569 case 'r': fi->df.dfItalic = 0;
570 break;
571 case 'o':
572 fi->fi_flags |= FI_OBLIQUE;
573 case 'i': fi->df.dfItalic = 1;
574 break;
576 return FALSE;
578 return TRUE;
581 static void LFD_GetStyle( fontInfo* fi, LPCSTR lpstr, int dec_style_check)
583 int j = strlen(lpstr);
584 if( j > 3 ) /* find out is there "sans" or "script" */
586 j = 0;
588 if( strstr(lpstr, "sans") )
590 fi->df.dfPitchAndFamily |= FF_SWISS;
591 j = 1;
593 if( strstr(lpstr, "script") )
595 fi->df.dfPitchAndFamily |= FF_SCRIPT;
596 j = 1;
598 if( !j && dec_style_check )
599 fi->df.dfPitchAndFamily |= FF_DECORATIVE;
603 /*************************************************************************
604 * LFD_InitFontInfo
606 * INIT ONLY
608 * Fill in some fields in the fontInfo struct.
610 static int LFD_InitFontInfo( fontInfo* fi, const LFD* lfd, LPCSTR fullname )
612 int i, j, dec_style_check, scalability;
613 fontEncodingTemplate* boba;
614 const char* ridiculous = "font '%s' has ridiculous %s\n";
615 const char* lpstr;
617 if (!lfd->charset_registry)
619 WARN("font '%s' does not have enough fields\n", fullname);
620 return FALSE;
623 memset(fi, 0, sizeof(fontInfo) );
625 /* weight name - */
626 LFD_GetWeight( fi, lfd->weight);
628 /* slant - */
629 dec_style_check = LFD_GetSlant( fi, lfd->slant);
631 /* width name - */
632 lpstr = lfd->set_width;
633 if( strcasecmp( "normal", lpstr) ) /* XXX 'narrow', 'condensed', etc... */
634 dec_style_check = TRUE;
635 else
636 fi->fi_flags |= FI_NORMAL;
638 /* style - */
639 LFD_GetStyle(fi, lfd->add_style, dec_style_check);
641 /* pixel & decipoint height, and res_x & y */
643 scalability = 0;
645 j = strlen(lfd->pixel_size);
646 if( j == 0 || j > 3 )
648 WARN(ridiculous, fullname, "pixel_size");
649 return FALSE;
651 if( !(fi->lfd_height = atoi(lfd->pixel_size)) )
652 scalability++;
654 j = strlen(lfd->point_size);
655 if( j == 0 || j > 3 )
657 WARN(ridiculous, fullname, "point_size");
658 return FALSE;
660 if( !(atoi(lfd->point_size)) )
661 scalability++;
663 j = strlen(lfd->resolution_x);
664 if( j == 0 || j > 3 )
666 WARN(ridiculous, fullname, "resolution_x");
667 return FALSE;
669 if( !(fi->lfd_resolution = atoi(lfd->resolution_x)) )
670 scalability++;
672 j = strlen(lfd->resolution_y);
673 if( j == 0 || j > 3 )
675 WARN(ridiculous, fullname, "resolution_y");
676 return FALSE;
678 if( !(atoi(lfd->resolution_y)) )
679 scalability++;
681 /* Check scalability */
682 switch (scalability)
684 case 0: /* Bitmap */
685 break;
686 case 4: /* Scalable */
687 fi->fi_flags |= FI_SCALABLE;
688 break;
689 case 2:
690 /* #$%^!!! X11R6 mutant garbage (scalable bitmap) */
691 TRACE("Skipping scalable bitmap '%s'\n", fullname);
692 return FALSE;
693 default:
694 WARN("Font '%s' has weird scalability\n", fullname);
695 return FALSE;
698 /* spacing - */
699 lpstr = lfd->spacing;
700 switch( *lpstr )
702 case '\0':
703 WARN("font '%s' has no spacing\n", fullname);
704 return FALSE;
706 case 'p': fi->fi_flags |= FI_VARIABLEPITCH;
707 break;
708 case 'c': fi->df.dfPitchAndFamily |= FF_MODERN;
709 fi->fi_flags |= FI_FIXEDEX;
710 /* fall through */
711 case 'm': fi->fi_flags |= FI_FIXEDPITCH;
712 break;
713 default:
714 /* Of course this line does nothing */
715 fi->df.dfPitchAndFamily |= DEFAULT_PITCH | FF_DONTCARE;
718 /* average width - */
719 lpstr = lfd->average_width;
720 j = strlen(lpstr);
721 if( j == 0 || j > 3 )
723 WARN(ridiculous, fullname, "average_width");
724 return FALSE;
727 if( !(atoi(lpstr)) && !scalability )
729 WARN("font '%s' has average_width 0 but is not scalable!!\n", fullname);
730 return FALSE;
733 /* charset registry, charset encoding - */
734 lpstr = lfd->charset_registry;
735 if( strstr(lpstr, "ksc") ||
736 strstr(lpstr, "gb2312") ||
737 strstr(lpstr, "big5") )
739 FIXME("DBCS fonts like '%s' are not working correctly now.\n", fullname);
742 fi->df.dfCharSet = ANSI_CHARSET;
744 for( i = 0, boba = fETTable; boba; boba = boba->next, i++ )
746 if (!boba->prefix || !strcasecmp(lpstr, boba->prefix))
748 if (lfd->charset_encoding)
750 for( j = 0; boba->sufch[j].psuffix; j++ )
752 if( !strcasecmp(lfd->charset_encoding, boba->sufch[j].psuffix ))
754 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
755 fi->internal_charset = boba->sufch[j].charset;
756 fi->codepage = boba->sufch[j].codepage;
757 fi->cptable = boba->sufch[j].cptable;
758 goto done;
762 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
763 fi->internal_charset = boba->sufch[j].charset;
764 fi->codepage = boba->sufch[j].codepage;
765 fi->cptable = boba->sufch[j].cptable;
766 if (boba->prefix)
768 FIXME("font '%s' has unknown character encoding '%s' in known registry '%s'\n",
769 fullname, lfd->charset_encoding, boba->prefix);
770 j = 254;
772 else
774 FIXME("font '%s' has unknown registry '%s' and character encoding '%s' \n",
775 fullname, lfd->charset_registry, lfd->charset_encoding);
776 j = 255;
779 WARN("Defaulting to: df.dfCharSet = %d, internal_charset = %d, codepage = %d, cptable = %d\n",
780 fi->df.dfCharSet,fi->internal_charset, fi->codepage, fi->cptable);
781 goto done;
783 else if (boba->prefix)
785 WARN("font '%s' has known registry '%s' and no character encoding\n",
786 fullname, lpstr);
787 for( j = 0; boba->sufch[j].psuffix; j++ )
789 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
790 fi->internal_charset = boba->sufch[j].charset;
791 fi->codepage = boba->sufch[j].codepage;
792 fi->cptable = boba->sufch[j].cptable;
793 j = 255;
794 goto done;
798 WARN("font '%s' has unknown character set '%s'\n", fullname, lpstr);
799 return FALSE;
801 done:
802 /* i - index into fETTable
803 * j - index into suffix array for fETTable[i]
804 * except:
805 * 254 - found encoding prefix, unknown suffix
806 * 255 - no encoding match at all.
808 fi->fi_encoding = 256 * (UINT16)i + (UINT16)j;
810 return TRUE;
814 /*************************************************************************
815 * LFD_AngleMatrix
817 * make a matrix suitable for LFD based on theta radians
819 static void LFD_AngleMatrix( char* buffer, int h, double theta)
821 double matrix[4];
822 matrix[0] = h*cos(theta);
823 matrix[1] = h*sin(theta);
824 matrix[2] = -h*sin(theta);
825 matrix[3] = h*cos(theta);
826 sprintf(buffer, "[%+f%+f%+f%+f]", matrix[0], matrix[1], matrix[2], matrix[3]);
829 /*************************************************************************
830 * LFD_ComposeLFD
832 * Note: uRelax is a treatment not a cure. Font mapping algorithm
833 * should be bulletproof enough to allow us to avoid hacks like
834 * this despite LFD being so braindead.
836 static BOOL LFD_ComposeLFD( const fontObject* fo,
837 INT height, LPSTR lpLFD, UINT uRelax )
839 int i, h;
840 char *any = "*";
841 char h_string[64], resx_string[64], resy_string[64];
842 LFD aLFD;
844 /* Get the worst case over with first */
846 /* RealizeFont() will call us repeatedly with increasing uRelax
847 * until XLoadFont() succeeds.
848 * to avoid an infinite loop; these will always match
850 if (uRelax >= 5)
852 if (uRelax == 5)
853 sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-1" );
854 else
855 sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*" );
856 return TRUE;
859 /* read foundry + family from fo */
860 aLFD.foundry = fo->fr->resource->foundry;
861 aLFD.family = fo->fr->resource->family;
863 /* add weight */
864 switch( fo->fi->df.dfWeight )
866 case FW_BOLD:
867 aLFD.weight = "bold"; break;
868 case FW_REGULAR:
869 if( fo->fi->fi_flags & FI_FW_BOOK )
870 aLFD.weight = "book";
871 else
872 aLFD.weight = "medium";
873 break;
874 case FW_DEMIBOLD:
875 aLFD.weight = "demi";
876 if( !( fo->fi->fi_flags & FI_FW_DEMI) )
877 aLFD.weight = "bold";
878 break;
879 case FW_BLACK:
880 aLFD.weight = "black"; break;
881 case FW_LIGHT:
882 aLFD.weight = "light"; break;
883 default:
884 aLFD.weight = any;
887 /* add slant */
888 if( fo->fi->df.dfItalic )
889 if( fo->fi->fi_flags & FI_OBLIQUE )
890 aLFD.slant = "o";
891 else
892 aLFD.slant = "i";
893 else
894 aLFD.slant = (uRelax < 1) ? "r" : any;
896 /* add width */
897 if( fo->fi->fi_flags & FI_NORMAL )
898 aLFD.set_width = "normal";
899 else
900 aLFD.set_width = any;
902 /* ignore style */
903 aLFD.add_style = any;
905 /* add pixelheight
907 * FIXME: fill in lpXForm and lpPixmap for rotated fonts
909 if( fo->fo_flags & FO_SYNTH_HEIGHT )
910 h = fo->fi->lfd_height;
911 else
913 h = (fo->fi->lfd_height * height + (fo->fi->df.dfPixHeight>>1));
914 h /= fo->fi->df.dfPixHeight;
916 if (h < MIN_FONT_SIZE) /* Resist rounding down to 0 */
917 h = MIN_FONT_SIZE;
918 else if (h > MAX_FONT_SIZE) /* Sanity check as huge fonts can lock up the font server */
920 WARN("Huge font size %d pixels has been reduced to %d\n", h, MAX_FONT_SIZE);
921 h = MAX_FONT_SIZE;
924 if (uRelax <= 2)
925 /* handle rotated fonts */
926 if (fo->lf.lfEscapement) {
927 /* escapement is in tenths of degrees, theta is in radians */
928 double theta = M_PI*fo->lf.lfEscapement/1800.;
929 LFD_AngleMatrix(h_string, h, theta);
931 else
933 sprintf(h_string, "%d", h);
935 else
936 sprintf(h_string, "%d", fo->fi->lfd_height);
938 aLFD.pixel_size = h_string;
939 aLFD.point_size = any;
941 /* resolution_x,y, average width */
942 /* FOX ME - Why do some font servers ignore average width ?
943 * so that you have to mess around with res_y
945 aLFD.average_width = any;
946 if (uRelax <= 3)
948 sprintf(resx_string, "%d", fo->fi->lfd_resolution);
949 aLFD.resolution_x = resx_string;
951 strcpy(resy_string, resx_string);
952 if( uRelax == 0 && text_caps & TC_SF_X_YINDEP )
954 if( fo->lf.lfWidth && !(fo->fo_flags & FO_SYNTH_WIDTH))
956 int resy = 0.5 + fo->fi->lfd_resolution *
957 (fo->fi->df.dfAvgWidth * height) /
958 (fo->lf.lfWidth * fo->fi->df.dfPixHeight) ;
959 sprintf(resy_string, "%d", resy);
961 else
963 /* FIXME - synth width */
966 aLFD.resolution_y = resy_string;
968 else
970 aLFD.resolution_x = aLFD.resolution_y = any;
973 /* spacing */
975 char* w;
977 if( fo->fi->fi_flags & FI_FIXEDPITCH )
978 w = ( fo->fi->fi_flags & FI_FIXEDEX ) ? "c" : "m";
979 else
980 w = ( fo->fi->fi_flags & FI_VARIABLEPITCH ) ? "p" : any;
982 aLFD.spacing = (uRelax <= 1) ? w : any;
985 /* encoding */
987 if (uRelax <= 4)
989 fontEncodingTemplate* boba = fETTable;
991 for(i = fo->fi->fi_encoding >> 8; i; i--) boba = boba->next;
992 aLFD.charset_registry = boba->prefix ? boba->prefix : any;
994 i = fo->fi->fi_encoding & 255;
995 switch( i )
997 default:
998 aLFD.charset_encoding = boba->sufch[i].psuffix;
999 break;
1001 case 254:
1002 aLFD.charset_encoding = any;
1003 break;
1005 case 255: /* no suffix - it ends eg "-ascii" */
1006 aLFD.charset_encoding = NULL;
1007 break;
1010 else
1012 aLFD.charset_registry = any;
1013 aLFD.charset_encoding = any;
1016 LFD_UnParse(lpLFD, MAX_LFD_LENGTH, &aLFD);
1018 TRACE("\tLFD(uRelax=%d): %s\n", uRelax, lpLFD );
1019 return TRUE;
1023 /***********************************************************************
1024 * X Font Resources
1026 * font info - http://www.microsoft.com/kb/articles/q65/1/23.htm
1027 * Windows font metrics - http://www.microsoft.com/kb/articles/q32/6/67.htm
1029 static void XFONT_GetLeading( const LPIFONTINFO16 pFI, const XFontStruct* x_fs,
1030 INT16* pIL, INT16* pEL, const XFONTTRANS *XFT )
1032 unsigned long height;
1033 unsigned min = (unsigned char)pFI->dfFirstChar;
1034 BOOL bIsLatin = IS_LATIN_CHARSET(pFI->dfCharSet);
1036 if( pEL ) *pEL = 0;
1038 if(XFT) {
1039 Atom RAW_CAP_HEIGHT = TSXInternAtom(gdi_display, "RAW_CAP_HEIGHT", TRUE);
1040 if(TSXGetFontProperty((XFontStruct*)x_fs, RAW_CAP_HEIGHT, &height))
1041 *pIL = XFT->ascent -
1042 (INT)(XFT->pixelsize / 1000.0 * height);
1043 else
1044 *pIL = 0;
1045 return;
1048 if( TSXGetFontProperty((XFontStruct*)x_fs, XA_CAP_HEIGHT, &height) == FALSE )
1050 if( x_fs->per_char )
1051 if( bIsLatin )
1052 height = x_fs->per_char['X' - min].ascent;
1053 else
1054 if (x_fs->ascent >= x_fs->max_bounds.ascent)
1055 height = x_fs->max_bounds.ascent;
1056 else
1058 height = x_fs->ascent;
1059 if( pEL )
1060 *pEL = x_fs->max_bounds.ascent - height;
1062 else
1063 height = x_fs->min_bounds.ascent;
1066 *pIL = x_fs->ascent - height;
1069 /***********************************************************************
1070 * XFONT_CharWidth
1072 static int XFONT_CharWidth(const XFontStruct* x_fs,
1073 const XFONTTRANS *XFT, int ch)
1075 if(!XFT)
1076 return x_fs->per_char[ch].width;
1077 else
1078 return x_fs->per_char[ch].attributes * XFT->pixelsize / 1000.0;
1081 /***********************************************************************
1082 * XFONT_GetAvgCharWidth
1084 static INT XFONT_GetAvgCharWidth( LPIFONTINFO16 pFI, const XFontStruct* x_fs,
1085 const XFONTTRANS *XFT)
1087 unsigned min = (unsigned char)pFI->dfFirstChar;
1088 unsigned max = (unsigned char)pFI->dfLastChar;
1090 INT avg;
1092 if( x_fs->per_char )
1094 int width = 0, chars = 0, j;
1095 if( IS_LATIN_CHARSET(pFI->dfCharSet) ||
1096 pFI->dfCharSet == DEFAULT_CHARSET )
1098 /* FIXME - should use a weighted average */
1099 for( j = 0; j < 26; j++ )
1100 width += XFONT_CharWidth(x_fs, XFT, 'a' + j - min) +
1101 XFONT_CharWidth(x_fs, XFT, 'A' + j - min);
1102 chars = 52;
1104 else /* unweighted average of everything */
1106 for( j = 0, max -= min; j <= max; j++ )
1107 if( !CI_NONEXISTCHAR(x_fs->per_char + j) )
1109 width += XFONT_CharWidth(x_fs, XFT, j);
1110 chars++;
1113 if (chars) avg = (width + (chars-1))/ chars; /* always round up*/
1114 else avg = 0; /* No characters exist at all */
1116 else /* uniform width */
1117 avg = x_fs->min_bounds.width;
1119 TRACE(" retuning %d\n",avg);
1120 return avg;
1123 /***********************************************************************
1124 * XFONT_GetMaxCharWidth
1126 static INT XFONT_GetMaxCharWidth(const XFontStruct* xfs, const XFONTTRANS *XFT)
1128 unsigned min = (unsigned char)xfs->min_char_or_byte2;
1129 unsigned max = (unsigned char)xfs->max_char_or_byte2;
1130 int maxwidth, j;
1132 if(!XFT || !xfs->per_char)
1133 return abs(xfs->max_bounds.width);
1135 for( j = 0, maxwidth = 0, max -= min; j <= max; j++ )
1136 if( !CI_NONEXISTCHAR(xfs->per_char + j) )
1137 if(maxwidth < xfs->per_char[j].attributes)
1138 maxwidth = xfs->per_char[j].attributes;
1140 maxwidth *= XFT->pixelsize / 1000.0;
1141 return maxwidth;
1144 /***********************************************************************
1145 * XFONT_SetFontMetric
1147 * INIT ONLY
1149 * Initializes IFONTINFO16.
1151 static void XFONT_SetFontMetric(fontInfo* fi, const fontResource* fr, XFontStruct* xfs)
1153 unsigned min, max;
1154 fi->df.dfFirstChar = (BYTE)(min = xfs->min_char_or_byte2);
1155 fi->df.dfLastChar = (BYTE)(max = xfs->max_char_or_byte2);
1157 fi->df.dfDefaultChar = (BYTE)xfs->default_char;
1158 fi->df.dfBreakChar = (BYTE)(( ' ' < min || ' ' > max) ? xfs->default_char: ' ');
1160 fi->df.dfPixHeight = (INT16)((fi->df.dfAscent = (INT16)xfs->ascent) + xfs->descent);
1161 fi->df.dfPixWidth = (xfs->per_char) ? 0 : xfs->min_bounds.width;
1163 XFONT_GetLeading( &fi->df, xfs, &fi->df.dfInternalLeading, &fi->df.dfExternalLeading, NULL );
1164 fi->df.dfAvgWidth = (INT16)XFONT_GetAvgCharWidth(&fi->df, xfs, NULL );
1165 fi->df.dfMaxWidth = (INT16)XFONT_GetMaxCharWidth(xfs, NULL);
1167 if( xfs->min_bounds.width != xfs->max_bounds.width )
1168 fi->df.dfPitchAndFamily |= TMPF_FIXED_PITCH; /* au contraire! */
1169 if( fi->fi_flags & FI_SCALABLE )
1171 fi->df.dfType = DEVICE_FONTTYPE;
1172 fi->df.dfPitchAndFamily |= TMPF_DEVICE;
1174 else if( fi->fi_flags & FI_TRUETYPE )
1175 fi->df.dfType = TRUETYPE_FONTTYPE;
1176 else
1177 fi->df.dfType = RASTER_FONTTYPE;
1179 fi->df.dfFace = fr->lfFaceName;
1182 /***********************************************************************
1183 * XFONT_GetFontMetric
1185 * Retrieve font metric info (enumeration).
1187 static UINT XFONT_GetFontMetric( const fontInfo* pfi,
1188 const LPENUMLOGFONTEXW pLF,
1189 const LPNEWTEXTMETRICEXW pTM )
1191 memset( pLF, 0, sizeof(*pLF) );
1192 memset( pTM, 0, sizeof(*pTM) );
1194 #define plf ((LPLOGFONTW)pLF)
1195 #define ptm ((LPNEWTEXTMETRICW)pTM)
1196 plf->lfHeight = ptm->tmHeight = pfi->df.dfPixHeight;
1197 plf->lfWidth = ptm->tmAveCharWidth = pfi->df.dfAvgWidth;
1198 plf->lfWeight = ptm->tmWeight = pfi->df.dfWeight;
1199 plf->lfItalic = ptm->tmItalic = pfi->df.dfItalic;
1200 plf->lfUnderline = ptm->tmUnderlined = pfi->df.dfUnderline;
1201 plf->lfStrikeOut = ptm->tmStruckOut = pfi->df.dfStrikeOut;
1202 plf->lfCharSet = ptm->tmCharSet = pfi->df.dfCharSet;
1204 /* convert pitch values */
1206 ptm->tmPitchAndFamily = pfi->df.dfPitchAndFamily;
1207 plf->lfPitchAndFamily = (pfi->df.dfPitchAndFamily & 0xF1) + 1;
1209 MultiByteToWideChar(CP_ACP, 0, pfi->df.dfFace, -1,
1210 plf->lfFaceName, LF_FACESIZE);
1212 /* FIXME: fill in rest of plF values */
1213 strcpyW(pLF->elfFullName, plf->lfFaceName);
1214 MultiByteToWideChar(CP_ACP, 0, "Regular", -1,
1215 pLF->elfStyle, LF_FACESIZE);
1216 MultiByteToWideChar(CP_ACP, 0, plf->lfCharSet == SYMBOL_CHARSET ?
1217 "Symbol" : "Roman", -1,
1218 pLF->elfScript, LF_FACESIZE);
1220 #undef plf
1222 ptm->tmAscent = pfi->df.dfAscent;
1223 ptm->tmDescent = ptm->tmHeight - ptm->tmAscent;
1224 ptm->tmInternalLeading = pfi->df.dfInternalLeading;
1225 ptm->tmMaxCharWidth = pfi->df.dfMaxWidth;
1226 ptm->tmDigitizedAspectX = pfi->df.dfHorizRes;
1227 ptm->tmDigitizedAspectY = pfi->df.dfVertRes;
1229 ptm->tmFirstChar = pfi->df.dfFirstChar;
1230 ptm->tmLastChar = pfi->df.dfLastChar;
1231 ptm->tmDefaultChar = pfi->df.dfDefaultChar;
1232 ptm->tmBreakChar = pfi->df.dfBreakChar;
1234 TRACE("Calling Enum proc with FaceName %s FullName %s\n",
1235 debugstr_w(pLF->elfLogFont.lfFaceName),
1236 debugstr_w(pLF->elfFullName));
1238 TRACE("CharSet = %d type = %d\n", ptm->tmCharSet, pfi->df.dfType);
1239 /* return font type */
1240 return pfi->df.dfType;
1241 #undef ptm
1245 /***********************************************************************
1246 * XFONT_FixupFlags
1248 * INIT ONLY
1250 * dfPitchAndFamily flags for some common typefaces.
1252 static BYTE XFONT_FixupFlags( LPCSTR lfFaceName )
1254 switch( lfFaceName[0] )
1256 case 'a':
1257 case 'A': if(!strncasecmp(lfFaceName, "Arial", 5) )
1258 return FF_SWISS;
1259 break;
1260 case 'h':
1261 case 'H': if(!strcasecmp(lfFaceName, "Helvetica") )
1262 return FF_SWISS;
1263 break;
1264 case 'c':
1265 case 'C': if(!strncasecmp(lfFaceName, "Courier", 7))
1266 return FF_MODERN;
1268 if (!strcasecmp(lfFaceName, "Charter") )
1269 return FF_ROMAN;
1270 break;
1271 case 'p':
1272 case 'P': if( !strcasecmp(lfFaceName,"Palatino") )
1273 return FF_ROMAN;
1274 break;
1275 case 't':
1276 case 'T': if(!strncasecmp(lfFaceName, "Times", 5) )
1277 return FF_ROMAN;
1278 break;
1279 case 'u':
1280 case 'U': if(!strcasecmp(lfFaceName, "Utopia") )
1281 return FF_ROMAN;
1282 break;
1283 case 'z':
1284 case 'Z': if(!strcasecmp(lfFaceName, "Zapf Dingbats") )
1285 return FF_DECORATIVE;
1287 return 0;
1290 /***********************************************************************
1291 * XFONT_SameFoundryAndFamily
1293 * INIT ONLY
1295 static BOOL XFONT_SameFoundryAndFamily( const LFD* lfd1, const LFD* lfd2 )
1297 return ( !strcasecmp( lfd1->foundry, lfd2->foundry ) &&
1298 !strcasecmp( lfd1->family, lfd2->family ) );
1301 /***********************************************************************
1302 * XFONT_InitialCapitals
1304 * INIT ONLY
1306 * Upper case first letters of words & remove multiple spaces
1308 static void XFONT_InitialCapitals(LPSTR lpch)
1310 int i;
1311 BOOL up;
1312 char* lpstr = lpch;
1314 for( i = 0, up = TRUE; *lpch; lpch++, i++ )
1316 if( isspace(*lpch) )
1318 if (!up) /* Not already got one */
1320 *lpstr++ = ' ';
1321 up = TRUE;
1324 else if( isalpha(*lpch) && up )
1326 *lpstr++ = toupper(*lpch);
1327 up = FALSE;
1329 else
1331 *lpstr++ = *lpch;
1332 up = FALSE;
1336 /* Remove possible trailing space */
1337 if (up && i > 0)
1338 --lpstr;
1339 *lpstr = '\0';
1343 /***********************************************************************
1344 * XFONT_WindowsNames
1346 * INIT ONLY
1348 * Build generic Windows aliases for X font names.
1350 * -misc-fixed- -> "Fixed"
1351 * -sony-fixed- -> "Sony Fixed", etc...
1353 static void XFONT_WindowsNames(void)
1355 fontResource* fr;
1357 for( fr = fontList; fr ; fr = fr->next )
1359 fontResource* pfr;
1360 char* lpch;
1362 if( fr->fr_flags & FR_NAMESET ) continue; /* skip already assigned */
1364 for( pfr = fontList; pfr != fr ; pfr = pfr->next )
1365 if( pfr->fr_flags & FR_NAMESET )
1367 if (!strcasecmp( pfr->resource->family, fr->resource->family))
1368 break;
1371 lpch = fr->lfFaceName;
1372 snprintf( fr->lfFaceName, sizeof(fr->lfFaceName), "%s %s",
1373 /* prepend vendor name */
1374 (pfr==fr) ? "" : fr->resource->foundry,
1375 fr->resource->family);
1376 XFONT_InitialCapitals(fr->lfFaceName);
1378 BYTE bFamilyStyle = XFONT_FixupFlags( fr->lfFaceName );
1379 if( bFamilyStyle)
1381 fontInfo* fi;
1382 for( fi = fr->fi ; fi ; fi = fi->next )
1383 fi->df.dfPitchAndFamily |= bFamilyStyle;
1387 TRACE("typeface '%s'\n", fr->lfFaceName);
1389 fr->fr_flags |= FR_NAMESET;
1393 /***********************************************************************
1394 * XFONT_LoadDefaultLFD
1396 * Move lfd to the head of fontList to make it more likely to be matched
1398 static void XFONT_LoadDefaultLFD(LFD* lfd, LPCSTR fonttype)
1401 fontResource *fr, *pfr;
1402 for( fr = NULL, pfr = fontList; pfr; pfr = pfr->next )
1404 if( XFONT_SameFoundryAndFamily(pfr->resource, lfd) )
1406 if( fr )
1408 fr->next = pfr->next;
1409 pfr->next = fontList;
1410 fontList = pfr;
1412 break;
1414 fr = pfr;
1416 if (!pfr)
1417 WARN("Default %sfont '-%s-%s-' not available\n", fonttype,
1418 lfd->foundry, lfd->family);
1422 /***********************************************************************
1423 * XFONT_LoadDefault
1425 static void XFONT_LoadDefault(LPCSTR ini, LPCSTR fonttype)
1427 char buffer[MAX_LFD_LENGTH];
1428 HKEY hkey;
1430 buffer[0] = 0;
1431 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1433 DWORD type, count = sizeof(buffer);
1434 RegQueryValueExA(hkey, ini, 0, &type, buffer, &count);
1435 RegCloseKey(hkey);
1437 if (*buffer)
1439 LFD* lfd;
1440 char* pch = buffer;
1441 while( *pch && isspace(*pch) ) pch++;
1443 TRACE("Using '%s' as default %sfont\n", pch, fonttype);
1444 lfd = LFD_Parse(pch);
1445 if (lfd && lfd->foundry && lfd->family)
1446 XFONT_LoadDefaultLFD(lfd, fonttype);
1447 else
1448 WARN("Ini section [%s]%s is malformed\n", INIFontSection, ini);
1449 HeapFree(GetProcessHeap(), 0, lfd);
1454 /***********************************************************************
1455 * XFONT_LoadDefaults
1457 static void XFONT_LoadDefaults(void)
1459 XFONT_LoadDefault(INIDefaultFixed, "fixed ");
1460 XFONT_LoadDefault(INIDefault, "");
1463 /***********************************************************************
1464 * XFONT_CreateAlias
1466 static fontAlias* XFONT_CreateAlias( LPCSTR lpTypeFace, LPCSTR lpAlias )
1468 int j;
1469 fontAlias *pfa, *prev = NULL;
1471 for(pfa = aliasTable; pfa; pfa = pfa->next)
1473 /* check if we already got one */
1474 if( !strcasecmp( pfa->faTypeFace, lpAlias ) )
1476 TRACE("redundant alias '%s' -> '%s'\n",
1477 lpAlias, lpTypeFace );
1478 return NULL;
1480 prev = pfa;
1483 j = strlen(lpTypeFace) + 1;
1484 pfa = HeapAlloc( GetProcessHeap(), 0, sizeof(fontAlias) +
1485 j + strlen(lpAlias) + 1 );
1486 if (pfa)
1488 if (!prev)
1489 aliasTable = pfa;
1490 else
1491 prev->next = pfa;
1493 pfa->next = NULL;
1494 pfa->faTypeFace = (LPSTR)(pfa + 1);
1495 strcpy( pfa->faTypeFace, lpTypeFace );
1496 pfa->faAlias = pfa->faTypeFace + j;
1497 strcpy( pfa->faAlias, lpAlias );
1499 TRACE("added alias '%s' for '%s'\n", lpAlias, lpTypeFace );
1501 return pfa;
1503 return NULL;
1507 /***********************************************************************
1508 * XFONT_LoadAlias
1510 static void XFONT_LoadAlias(const LFD* lfd, LPCSTR lpAlias, BOOL bSubst)
1512 fontResource *fr, *frMatch = NULL;
1513 if (!lfd->foundry || ! lfd->family)
1515 WARN("Malformed font resource for alias '%s'\n", lpAlias);
1516 return;
1518 for (fr = fontList; fr ; fr = fr->next)
1520 if(!strcasecmp(fr->resource->family, lpAlias))
1522 /* alias is not needed since the real font is present */
1523 TRACE("Ignoring font alias '%s' as it is already available as a real font\n", lpAlias);
1524 return;
1526 if( XFONT_SameFoundryAndFamily( fr->resource, lfd ) )
1528 frMatch = fr;
1529 break;
1533 if( frMatch )
1535 if( bSubst )
1537 fontAlias *pfa, *prev = NULL;
1539 for(pfa = aliasTable; pfa; pfa = pfa->next)
1541 /* Remove lpAlias from aliasTable - we should free the old entry */
1542 if(!strcmp(lpAlias, pfa->faAlias))
1544 if(prev)
1545 prev->next = pfa->next;
1546 else
1547 aliasTable = pfa->next;
1550 /* Update any references to the substituted font in aliasTable */
1551 if(!strcmp(frMatch->lfFaceName, pfa->faTypeFace))
1553 pfa->faTypeFace = HeapAlloc( GetProcessHeap(), 0, strlen(lpAlias)+1 );
1554 strcpy( pfa->faTypeFace, lpAlias );
1556 prev = pfa;
1559 TRACE("\tsubstituted '%s' with '%s'\n", frMatch->lfFaceName, lpAlias );
1561 lstrcpynA( frMatch->lfFaceName, lpAlias, LF_FACESIZE );
1562 frMatch->fr_flags |= FR_NAMESET;
1564 else
1566 /* create new entry in the alias table */
1567 XFONT_CreateAlias( frMatch->lfFaceName, lpAlias );
1570 else
1572 WARN("Font alias '-%s-%s-' is not available\n", lfd->foundry, lfd->family);
1576 /***********************************************************************
1577 * Just a copy of PROFILE_GetStringItem
1579 * Convenience function that turns a string 'xxx, yyy, zzz' into
1580 * the 'xxx\0 yyy, zzz' and returns a pointer to the 'yyy, zzz'.
1582 static char *XFONT_GetStringItem( char *start )
1584 #define XFONT_isspace(c) (isspace(c) || (c == '\r') || (c == 0x1a))
1585 char *lpchX, *lpch;
1587 for (lpchX = start, lpch = NULL; *lpchX != '\0'; lpchX++ )
1589 if( *lpchX == ',' )
1591 if( lpch ) *lpch = '\0'; else *lpchX = '\0';
1592 while( *(++lpchX) )
1593 if( !XFONT_isspace(*lpchX) ) return lpchX;
1595 else if( XFONT_isspace( *lpchX ) && !lpch ) lpch = lpchX;
1596 else lpch = NULL;
1598 if( lpch ) *lpch = '\0';
1599 return NULL;
1600 #undef XFONT_isspace
1603 /***********************************************************************
1604 * XFONT_LoadAliases
1606 * INIT ONLY
1608 * Create font aliases for some standard windows fonts using user's
1609 * default choice of (sans-)serif fonts
1611 * Read user-defined aliases from wine.conf. Format is as follows
1613 * Alias# = [Windows font name],[LFD font name], <substitute original name>
1615 * Example:
1616 * Alias0 = Arial, -adobe-helvetica-
1617 * Alias1 = Times New Roman, -bitstream-courier-, 1
1618 * ...
1620 * Note that from 970817 and on we have built-in alias templates that take
1621 * care of the necessary Windows typefaces.
1623 typedef struct
1625 LPSTR fatResource;
1626 LPSTR fatAlias;
1627 } aliasTemplate;
1629 static void XFONT_LoadAliases(void)
1631 char *lpResource;
1632 char buffer[MAX_LFD_LENGTH];
1633 int i = 0;
1634 LFD* lfd;
1635 HKEY hkey;
1637 /* built-ins first */
1638 strcpy(buffer, "-bitstream-charter-");
1639 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1641 DWORD type, count = sizeof(buffer);
1642 RegQueryValueExA(hkey, INIDefaultSerif, 0, &type, buffer, &count);
1643 RegCloseKey(hkey);
1645 TRACE("Using '%s' as default serif font\n", buffer);
1646 lfd = LFD_Parse(buffer);
1647 /* NB XFONT_InitialCapitals should not change these standard aliases */
1648 if (lfd)
1650 XFONT_LoadAlias( lfd, "Tms Roman", FALSE);
1651 XFONT_LoadAlias( lfd, "MS Serif", FALSE);
1652 XFONT_LoadAlias( lfd, "Times New Roman", FALSE);
1654 XFONT_LoadDefaultLFD( lfd, "serif ");
1655 HeapFree(GetProcessHeap(), 0, lfd);
1658 strcpy(buffer, "-adobe-helvetica-");
1659 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1661 DWORD type, count = sizeof(buffer);
1662 RegQueryValueExA(hkey, INIDefaultSansSerif, 0, &type, buffer, &count);
1663 RegCloseKey(hkey);
1665 TRACE("Using '%s' as default sans serif font\n", buffer);
1666 lfd = LFD_Parse(buffer);
1667 if (lfd)
1669 XFONT_LoadAlias( lfd, "Helv", FALSE);
1670 XFONT_LoadAlias( lfd, "MS Sans Serif", FALSE);
1671 XFONT_LoadAlias( lfd, "MS Shell Dlg", FALSE);
1672 XFONT_LoadAlias( lfd, "System", FALSE);
1673 XFONT_LoadAlias( lfd, "Arial", FALSE);
1675 XFONT_LoadDefaultLFD( lfd, "sans serif ");
1676 HeapFree(GetProcessHeap(), 0, lfd);
1679 /* then user specified aliases */
1682 BOOL bSubst;
1683 char subsection[32];
1684 snprintf( subsection, sizeof subsection, "%s%i", INIAliasSection, i++ );
1686 buffer[0] = 0;
1687 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1689 DWORD type, count = sizeof(buffer);
1690 RegQueryValueExA(hkey, subsection, 0, &type, buffer, &count);
1691 RegCloseKey(hkey);
1694 if (!buffer[0])
1695 break;
1697 XFONT_InitialCapitals(buffer);
1698 lpResource = XFONT_GetStringItem( buffer );
1699 bSubst = (XFONT_GetStringItem( lpResource )) ? TRUE : FALSE;
1700 if( lpResource && *lpResource )
1702 lfd = LFD_Parse(lpResource);
1703 if (lfd)
1705 XFONT_LoadAlias(lfd, buffer, bSubst);
1706 HeapFree(GetProcessHeap(), 0, lfd);
1709 else
1710 WARN("malformed font alias '%s'\n", buffer );
1712 while(TRUE);
1715 /***********************************************************************
1716 * XFONT_UnAlias
1718 * Convert an (potential) alias into a real windows name
1721 static LPCSTR XFONT_UnAlias(char* font)
1723 if (font[0])
1725 fontAlias* fa;
1726 XFONT_InitialCapitals(font); /* to remove extra white space */
1728 for( fa = aliasTable; fa; fa = fa->next )
1729 /* use case insensitive matching to handle eg "MS Sans Serif" */
1730 if( !strcasecmp( fa->faAlias, font ) )
1732 TRACE("found alias '%s'->%s'\n", font, fa->faTypeFace );
1733 strcpy(font, fa->faTypeFace);
1734 return fa->faAlias;
1735 break;
1738 return NULL;
1741 /***********************************************************************
1742 * XFONT_RemoveFontResource
1744 * Caller should check if the font resource is in use. If it is it should
1745 * set FR_REMOVED flag to delay removal until the resource is not in use
1746 * any more.
1748 void XFONT_RemoveFontResource( fontResource** ppfr )
1750 fontResource* pfr = *ppfr;
1751 #if 0
1752 fontInfo* pfi;
1754 /* FIXME - if fonts were read from a cache, these HeapFrees will fail */
1755 while( pfr->fi )
1757 pfi = pfr->fi->next;
1758 HeapFree( GetProcessHeap(), 0, pfr->fi );
1759 pfr->fi = pfi;
1761 HeapFree( GetProcessHeap(), 0, pfr );
1762 #endif
1763 *ppfr = pfr->next;
1766 /***********************************************************************
1767 * XFONT_LoadIgnores
1769 * INIT ONLY
1771 * Removes specified fonts from the font table to prevent Wine from
1772 * using it.
1774 * Ignore# = [LFD font name]
1776 * Example:
1777 * Ignore0 = -misc-nil-
1778 * Ignore1 = -sun-open look glyph-
1779 * ...
1782 static void XFONT_LoadIgnore(char* lfdname)
1784 fontResource** ppfr;
1786 LFD* lfd = LFD_Parse(lfdname);
1787 if (lfd && lfd->foundry && lfd->family)
1789 for( ppfr = &fontList; *ppfr ; ppfr = &((*ppfr)->next))
1791 if( XFONT_SameFoundryAndFamily( (*ppfr)->resource, lfd) )
1793 TRACE("Ignoring '-%s-%s-'\n",
1794 (*ppfr)->resource->foundry, (*ppfr)->resource->family );
1796 XFONT_RemoveFontResource( ppfr );
1797 break;
1801 else
1802 WARN("Malformed font resource\n");
1804 HeapFree(GetProcessHeap(), 0, lfd);
1807 static void XFONT_LoadIgnores(void)
1809 int i = 0;
1810 char subsection[32];
1811 char buffer[MAX_LFD_LENGTH];
1813 /* Standard one that noone wants */
1814 strcpy(buffer, "-misc-nil-");
1815 XFONT_LoadIgnore(buffer);
1817 /* Others from INI file */
1820 HKEY hkey;
1821 sprintf( subsection, "%s%i", INIIgnoreSection, i++ );
1823 buffer[0] = 0;
1824 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
1826 DWORD type, count = sizeof(buffer);
1827 RegQueryValueExA(hkey, subsection, 0, &type, buffer, &count);
1828 RegCloseKey(hkey);
1831 if( buffer[0] )
1833 char* pch = buffer;
1834 while( *pch && isspace(*pch) ) pch++;
1835 XFONT_LoadIgnore(pch);
1837 else
1838 break;
1839 } while(TRUE);
1843 /***********************************************************************
1844 * XFONT_UserMetricsCache
1846 * Returns expanded name for the cachedmetrics file.
1847 * Now it also appends the current value of the $DISPLAY variable.
1849 static char* XFONT_UserMetricsCache( char* buffer, int* buf_size )
1851 const char *confdir = wine_get_config_dir();
1852 const char *display_name = XDisplayName(NULL);
1853 int len = strlen(confdir) + strlen(INIFontMetrics) + strlen(display_name) + 8;
1854 int display = 0;
1855 int screen = 0;
1856 char *p, *ext;
1859 ** Normalize the display name, since on Red Hat systems, DISPLAY
1860 ** is commonly set to one of either 'unix:0.0' or ':0' or ':0.0'.
1861 ** after this code, all of the above will resolve to ':0.0'.
1863 if (!strncmp( display_name, "unix:", 5 )) display_name += 4;
1864 p = strchr(display_name, ':');
1865 if (p) sscanf(p + 1, "%d.%d", &display, &screen);
1867 if ((len > *buf_size) &&
1868 !(buffer = HeapReAlloc( GetProcessHeap(), 0, buffer, *buf_size = len )))
1870 ERR("out of memory\n");
1871 ExitProcess(1);
1873 sprintf( buffer, "%s/%s", confdir, INIFontMetrics );
1875 ext = buffer + strlen(buffer);
1876 strcpy( ext, display_name );
1878 if (!(p = strchr( ext, ':' ))) p = ext + strlen(ext);
1879 sprintf( p, ":%d.%d", display, screen );
1880 return buffer;
1884 /***********************************************************************
1885 * X Font Matching
1887 * Compare two fonts (only parameters set by the XFONT_InitFontInfo()).
1889 static INT XFONT_IsSubset(const fontInfo* match, const fontInfo* fi)
1891 INT m;
1893 /* 0 - keep both, 1 - keep match, -1 - keep fi */
1895 /* Compare dfItalic, Underline, Strikeout, Weight, Charset */
1896 m = (BYTE*)&fi->df.dfPixWidth - (BYTE*)&fi->df.dfItalic;
1897 if( memcmp(&match->df.dfItalic, &fi->df.dfItalic, m )) return 0;
1899 if( (!((fi->fi_flags & FI_SCALABLE) + (match->fi_flags & FI_SCALABLE))
1900 && fi->lfd_height != match->lfd_height) ||
1901 (!((fi->fi_flags & FI_POLYWEIGHT) + (match->fi_flags & FI_POLYWEIGHT))
1902 && fi->df.dfWeight != match->df.dfWeight) ) return 0;
1904 m = (int)(match->fi_flags & (FI_POLYWEIGHT | FI_SCALABLE)) -
1905 (int)(fi->fi_flags & (FI_SCALABLE | FI_POLYWEIGHT));
1907 if( m == (FI_POLYWEIGHT - FI_SCALABLE) ||
1908 m == (FI_SCALABLE - FI_POLYWEIGHT) ) return 0; /* keep both */
1909 else if( m >= 0 ) return 1; /* 'match' is better */
1911 return -1; /* 'fi' is better */
1914 /***********************************************************************
1915 * XFONT_CheckFIList
1917 * REMOVE_SUBSETS - attach new fi and purge subsets
1918 * UNMARK_SUBSETS - remove subset flags from all fi entries
1920 static void XFONT_CheckFIList( fontResource* fr, fontInfo* fi, int action)
1922 int i = 0;
1923 fontInfo* pfi, *prev;
1925 for( prev = NULL, pfi = fr->fi; pfi; )
1927 if( action == REMOVE_SUBSETS )
1929 if( pfi->fi_flags & FI_SUBSET )
1931 fontInfo* subset = pfi;
1933 i++;
1934 fr->fi_count--;
1935 if( prev ) prev->next = pfi = pfi->next;
1936 else fr->fi = pfi = pfi->next;
1937 HeapFree( GetProcessHeap(), 0, subset );
1938 continue;
1941 else pfi->fi_flags &= ~FI_SUBSET;
1943 prev = pfi;
1944 pfi = pfi->next;
1947 if( action == REMOVE_SUBSETS ) /* also add the superset */
1949 if( fi->fi_flags & FI_SCALABLE )
1951 fi->next = fr->fi;
1952 fr->fi = fi;
1954 else if( prev ) prev->next = fi; else fr->fi = fi;
1955 fr->fi_count++;
1958 if( i ) TRACE("\t purged %i subsets [%i]\n", i , fr->fi_count);
1961 /***********************************************************************
1962 * XFONT_FindFIList
1964 static fontResource* XFONT_FindFIList( fontResource* pfr, const char* pTypeFace )
1966 while( pfr )
1968 if( !strcasecmp( pfr->lfFaceName, pTypeFace ) ) break;
1969 pfr = pfr->next;
1971 /* Give the app back the font name it asked for. Encarta checks this. */
1972 if (pfr) strcpy(pfr->lfFaceName,pTypeFace);
1973 return pfr;
1976 /***********************************************************************
1977 * XFONT_FixupPointSize
1979 static void XFONT_FixupPointSize(fontInfo* fi)
1981 #define df (fi->df)
1982 df.dfHorizRes = df.dfVertRes = fi->lfd_resolution;
1983 df.dfPoints = (INT16)
1984 (((INT)(df.dfPixHeight - df.dfInternalLeading) * 72 + (df.dfVertRes >> 1)) /
1985 df.dfVertRes );
1986 #undef df
1989 /***********************************************************************
1990 * XFONT_BuildMetrics
1992 * Build font metrics from X font
1994 static int XFONT_BuildMetrics(char** x_pattern, int res, unsigned x_checksum, int x_count)
1996 int i;
1997 fontInfo* fi = NULL;
1998 fontResource* fr, *pfr;
1999 int n_ff = 0;
2001 MESSAGE("Building font metrics. This may take some time...\n");
2002 for( i = 0; i < x_count; i++ )
2004 char* typeface;
2005 LFD* lfd;
2006 int j;
2007 char buffer[MAX_LFD_LENGTH];
2008 char* lpstr;
2009 XFontStruct* x_fs;
2010 fontInfo* pfi;
2012 if (!(typeface = HeapAlloc(GetProcessHeap(), 0, strlen(x_pattern[i])+1))) break;
2013 strcpy( typeface, x_pattern[i] );
2015 lfd = LFD_Parse(typeface);
2016 if (!lfd)
2018 HeapFree(GetProcessHeap(), 0, typeface);
2019 continue;
2022 /* find a family to insert into */
2024 for( pfr = NULL, fr = fontList; fr; fr = fr->next )
2026 if( XFONT_SameFoundryAndFamily(fr->resource, lfd))
2027 break;
2028 pfr = fr;
2031 if( !fi ) fi = (fontInfo*) HeapAlloc(GetProcessHeap(), 0, sizeof(fontInfo));
2033 if( !LFD_InitFontInfo( fi, lfd, x_pattern[i]) )
2034 goto nextfont;
2036 if( !fr ) /* add new family */
2038 n_ff++;
2039 fr = (fontResource*) HeapAlloc(GetProcessHeap(), 0, sizeof(fontResource));
2040 if (fr)
2042 memset(fr, 0, sizeof(fontResource));
2044 fr->resource = (LFD*) HeapAlloc(GetProcessHeap(), 0, sizeof(LFD));
2045 memset(fr->resource, 0, sizeof(LFD));
2047 TRACE("family: -%s-%s-\n", lfd->foundry, lfd->family );
2048 fr->resource->foundry = HeapAlloc(GetProcessHeap(), 0, strlen(lfd->foundry)+1);
2049 strcpy( (char *)fr->resource->foundry, lfd->foundry );
2050 fr->resource->family = HeapAlloc(GetProcessHeap(), 0, strlen(lfd->family)+1);
2051 strcpy( (char *)fr->resource->family, lfd->family );
2052 fr->resource->weight = "";
2054 if( pfr ) pfr->next = fr;
2055 else fontList = fr;
2057 else
2058 WARN("Not enough memory for a new font family\n");
2061 /* check if we already have something better than "fi" */
2063 for( pfi = fr->fi, j = 0; pfi && j <= 0; pfi = pfi->next )
2064 if( (j = XFONT_IsSubset( pfi, fi )) < 0 )
2065 pfi->fi_flags |= FI_SUBSET; /* superseded by "fi" */
2066 if( j > 0 ) goto nextfont;
2068 /* add new font instance "fi" to the "fr" font resource */
2070 if( fi->fi_flags & FI_SCALABLE )
2072 LFD lfd1;
2073 char pxl_string[4], res_string[4];
2074 /* set scalable font height to get an basis for extrapolation */
2076 fi->lfd_height = DEF_SCALABLE_HEIGHT;
2077 fi->lfd_resolution = res;
2079 sprintf(pxl_string, "%d", fi->lfd_height);
2080 sprintf(res_string, "%d", fi->lfd_resolution);
2082 lfd1 = *lfd;
2083 lfd1.pixel_size = pxl_string;
2084 lfd1.point_size = "*";
2085 lfd1.resolution_x = res_string;
2086 lfd1.resolution_y = res_string;
2088 LFD_UnParse(buffer, sizeof buffer, &lfd1);
2090 lpstr = buffer;
2092 else lpstr = x_pattern[i];
2094 if( (x_fs = TSXLoadQueryFont(gdi_display, lpstr)) )
2096 XFONT_SetFontMetric( fi, fr, x_fs );
2097 TSXFreeFont( gdi_display, x_fs );
2099 XFONT_FixupPointSize(fi);
2101 TRACE("\t[% 2ipt] '%s'\n", fi->df.dfPoints, x_pattern[i] );
2103 XFONT_CheckFIList( fr, fi, REMOVE_SUBSETS );
2104 fi = NULL; /* preventing reuse */
2106 else
2108 ERR("failed to load %s\n", lpstr );
2110 XFONT_CheckFIList( fr, fi, UNMARK_SUBSETS );
2112 nextfont:
2113 HeapFree(GetProcessHeap(), 0, lfd);
2114 HeapFree(GetProcessHeap(), 0, typeface);
2116 if( fi ) HeapFree(GetProcessHeap(), 0, fi);
2118 /* Scan through the font list and remove FontResource(s) (fr)
2119 * that have no associated Fontinfo(s) (fi).
2120 * This code is necessary because XFONT_ReadCachedMetrics
2121 * assumes that there is at least one fi associated with a fr.
2122 * This assumption is invalid for TT font
2123 * -altsys-ms outlook-medium-r-normal--0-0-0-0-p-0-microsoft-symbol.
2126 fr = fontList;
2128 while (!fr->fi_count)
2130 fontList = fr->next;
2132 HeapFree(GetProcessHeap(), 0, fr->resource);
2133 HeapFree(GetProcessHeap(), 0, fr);
2135 fr = fontList;
2136 n_ff--;
2139 fr = fontList;
2141 while (fr->next)
2143 if (!fr->next->fi_count)
2145 pfr = fr->next;
2146 fr->next = fr->next->next;
2148 HeapFree(GetProcessHeap(), 0, pfr->resource);
2149 HeapFree(GetProcessHeap(), 0, pfr);
2151 n_ff--;
2153 else
2154 fr = fr->next;
2157 return n_ff;
2160 /***********************************************************************
2161 * XFONT_ReadCachedMetrics
2163 * INIT ONLY
2165 static BOOL XFONT_ReadCachedMetrics( int fd, int res, unsigned x_checksum, int x_count )
2167 if( fd >= 0 )
2169 unsigned u;
2170 int i, j;
2172 /* read checksums */
2173 read( fd, &u, sizeof(unsigned) );
2174 read( fd, &i, sizeof(int) );
2176 if( u == x_checksum && i == x_count )
2178 off_t length, offset = 3 * sizeof(int);
2180 /* read total size */
2181 read( fd, &i, sizeof(int) );
2182 length = lseek( fd, 0, SEEK_END );
2184 if( length == (i + offset) )
2186 lseek( fd, offset, SEEK_SET );
2187 fontList = (fontResource*)HeapAlloc( GetProcessHeap(), 0, i);
2188 if( fontList )
2190 fontResource* pfr = fontList;
2191 fontInfo* pfi = NULL;
2193 TRACE("Reading cached font metrics:\n");
2195 read( fd, fontList, i); /* read all metrics at once */
2196 while( offset < length )
2198 offset += sizeof(fontResource) + sizeof(fontInfo);
2199 pfr->fi = pfi = (fontInfo*)(pfr + 1);
2200 j = 1;
2201 while( TRUE )
2203 if( offset > length ||
2204 pfi->cptable >= (UINT16)X11DRV_CPTABLE_COUNT ||
2205 (int)(pfi->next) != j++ )
2207 TRACE("error: offset=%ld length=%ld cptable=%d pfi->next=%d j=%d\n",(long)offset,(long)length,pfi->cptable,(int)pfi->next,j-1);
2208 goto fail;
2211 if( pfi->df.dfPixHeight == 0 )
2213 TRACE("error: dfPixHeight==0\n");
2214 goto fail;
2217 pfi->df.dfFace = pfr->lfFaceName;
2218 if( pfi->fi_flags & FI_SCALABLE )
2220 /* we can pretend we got this font for any resolution */
2221 pfi->lfd_resolution = res;
2222 XFONT_FixupPointSize(pfi);
2224 pfi->next = pfi + 1;
2226 if( j > pfr->fi_count ) break;
2228 pfi = pfi->next;
2229 offset += sizeof(fontInfo);
2231 pfi->next = NULL;
2232 if( pfr->next )
2234 pfr->next = (fontResource*)(pfi + 1);
2235 pfr = pfr->next;
2237 else break;
2239 if( pfr->next == NULL &&
2240 *(int*)(pfi + 1) == X_FMC_MAGIC )
2242 /* read LFD stubs */
2243 char* lpch = (char*)((int*)(pfi + 1) + 1);
2244 offset += sizeof(int);
2245 for( pfr = fontList; pfr; pfr = pfr->next )
2247 size_t len = strlen(lpch) + 1;
2248 TRACE("\t%s, %i instances\n", lpch, pfr->fi_count );
2249 pfr->resource = LFD_Parse(lpch);
2250 lpch += len;
2251 offset += len;
2252 if (offset > length)
2254 TRACE("error: offset=%ld length=%ld\n",(long)offset,(long)length);
2255 goto fail;
2258 close( fd );
2259 return TRUE;
2262 } else {
2263 TRACE("Wrong length: %ld!=%ld\n",(long)length,(long)(i+offset));
2265 } else {
2266 TRACE("Checksum (%x vs. %x) or count (%d vs. %d) mismatch\n",
2267 u,x_checksum,i,x_count);
2269 fail:
2270 if( fontList ) HeapFree( GetProcessHeap(), 0, fontList );
2271 fontList = NULL;
2272 close( fd );
2274 return FALSE;
2277 /***********************************************************************
2278 * XFONT_WriteCachedMetrics
2280 * INIT ONLY
2282 static BOOL XFONT_WriteCachedMetrics( int fd, unsigned x_checksum, int x_count, int n_ff )
2284 fontResource* pfr;
2285 fontInfo* pfi;
2287 if( fd >= 0 )
2289 int i, j, k;
2290 char buffer[MAX_LFD_LENGTH];
2292 /* font metrics file:
2294 * +0000 x_checksum
2295 * +0004 x_count
2296 * +0008 total size to load
2297 * +000C prepackaged font metrics
2298 * ...
2299 * +...x X_FMC_MAGIC
2300 * +...x + 4 LFD stubs
2303 write( fd, &x_checksum, sizeof(unsigned) );
2304 write( fd, &x_count, sizeof(int) );
2306 for( j = i = 0, pfr = fontList; pfr; pfr = pfr->next )
2308 LFD_UnParse(buffer, sizeof buffer, pfr->resource);
2309 i += strlen( buffer) + 1;
2310 j += pfr->fi_count;
2312 i += n_ff * sizeof(fontResource) + j * sizeof(fontInfo) + sizeof(int);
2313 write( fd, &i, sizeof(int) );
2315 TRACE("Writing font cache:\n");
2317 for( pfr = fontList; pfr; pfr = pfr->next )
2319 fontInfo fi;
2321 TRACE("\t-%s-%s-, %i instances\n", pfr->resource->foundry, pfr->resource->family, pfr->fi_count );
2323 i = write( fd, pfr, sizeof(fontResource) );
2324 if( i == sizeof(fontResource) )
2326 for( k = 1, pfi = pfr->fi; pfi; pfi = pfi->next )
2328 fi = *pfi;
2330 fi.df.dfFace = NULL;
2331 fi.next = (fontInfo*)k; /* loader checks this */
2333 j = write( fd, &fi, sizeof(fi) );
2334 k++;
2336 if( j == sizeof(fontInfo) ) continue;
2338 break;
2340 if( i == sizeof(fontResource) && j == sizeof(fontInfo) )
2342 i = j = X_FMC_MAGIC;
2343 write( fd, &i, sizeof(int) );
2344 for( pfr = fontList; pfr && i == j; pfr = pfr->next )
2346 LFD_UnParse(buffer, sizeof buffer, pfr->resource);
2347 i = strlen( buffer ) + 1;
2348 j = write( fd, buffer, i );
2351 close( fd );
2352 return ( i == j );
2354 return FALSE;
2357 /***********************************************************************
2358 * XFONT_GetPointResolution()
2360 * INIT ONLY
2362 * Here we initialize DefResolution which is used in the
2363 * XFONT_Match() penalty function. We also load the point
2364 * resolution value (higher values result in larger fonts).
2366 static int XFONT_GetPointResolution( int *log_pixels_x, int *log_pixels_y )
2368 int i, j, point_resolution, num = 3;
2369 int allowed_xfont_resolutions[3] = { 72, 75, 100 };
2370 int best = 0, best_diff = 65536;
2371 HKEY hkey;
2373 point_resolution = 0;
2375 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
2377 char buffer[20];
2378 DWORD type, count = sizeof(buffer);
2379 if(!RegQueryValueExA(hkey, INIResolution, 0, &type, buffer, &count))
2380 point_resolution = atoi(buffer);
2381 RegCloseKey(hkey);
2384 if( !point_resolution )
2385 point_resolution = *log_pixels_y;
2386 else
2387 *log_pixels_x = *log_pixels_y = point_resolution;
2390 /* FIXME We can only really guess at a best DefResolution
2391 * - this should be configurable
2393 for( i = best = 0; i < num; i++ )
2395 j = abs( point_resolution - allowed_xfont_resolutions[i] );
2396 if( j < best_diff )
2398 best = i;
2399 best_diff = j;
2402 DefResolution = allowed_xfont_resolutions[best];
2403 return point_resolution;
2407 /***********************************************************************
2408 * XFONT_Match
2410 * Compute the matching score between the logical font and the device font.
2412 * contributions from highest to lowest:
2413 * charset
2414 * fixed pitch
2415 * height
2416 * family flags (only when the facename is not present)
2417 * width
2418 * weight, italics, underlines, strikeouts
2420 * NOTE: you can experiment with different penalty weights to see what happens.
2421 * http://premium.microsoft.com/msdn/library/techart/f365/f36b/f37b/d38b/sa8bf.htm
2423 static UINT XFONT_Match( fontMatch* pfm )
2425 fontInfo* pfi = pfm->pfi; /* device font to match */
2426 LPLOGFONT16 plf = pfm->plf; /* wanted logical font */
2427 UINT penalty = 0;
2428 BOOL bR6 = pfm->flags & FO_MATCH_XYINDEP; /* from text_caps */
2429 BOOL bScale = pfi->fi_flags & FI_SCALABLE;
2430 int d = 0, height;
2432 TRACE("\t[ %-2ipt h=%-3i w=%-3i %s%s]\n", pfi->df.dfPoints,
2433 pfi->df.dfPixHeight, pfi->df.dfAvgWidth,
2434 (pfi->df.dfWeight > FW_NORMAL) ? "Bold " : "Normal ",
2435 (pfi->df.dfItalic) ? "Italic" : "" );
2437 pfm->flags &= FO_MATCH_MASK;
2439 /* Charset */
2440 /* pfm->internal_charset: given(required) charset */
2441 /* pfi->internal_charset: charset of this font */
2442 if (pfi->internal_charset == DEFAULT_CHARSET)
2444 /* special case(unicode font) */
2445 /* priority: unmatched charset < unicode < matched charset */
2446 penalty += 0x50;
2448 else
2450 if( pfm->internal_charset == DEFAULT_CHARSET )
2453 if (pfi->internal_charset != ANSI_CHARSET)
2454 penalty += 0x200;
2456 if ( pfi->codepage != GetACP() )
2457 penalty += 0x200;
2459 else if (pfm->internal_charset != pfi->internal_charset)
2461 if ( pfi->internal_charset & 0xff00 )
2462 penalty += 0x1000; /* internal charset - should not be used */
2463 else
2464 penalty += 0x200;
2468 /* Height */
2469 height = -1;
2471 if( plf->lfHeight > 0 )
2473 int h = pfi->df.dfPixHeight;
2474 d = h - plf->lfHeight;
2475 height = plf->lfHeight;
2477 else
2479 int h = pfi->df.dfPixHeight - pfi->df.dfInternalLeading;
2480 if (h)
2482 d = h + plf->lfHeight;
2483 height = (-plf->lfHeight * pfi->df.dfPixHeight) / h;
2485 else
2487 ERR("PixHeight == InternalLeading\n");
2488 penalty += 0x1000; /* dont want this */
2493 if( height == 0 )
2494 pfm->height = 1; /* Very small */
2495 else if( d )
2497 if( bScale )
2498 pfm->height = height;
2499 else if( (plf->lfQuality != PROOF_QUALITY) && bR6 )
2501 if( d > 0 ) /* do not shrink raster fonts */
2503 pfm->height = pfi->df.dfPixHeight;
2504 penalty += (pfi->df.dfPixHeight - height) * 0x4;
2506 else /* expand only in integer multiples */
2508 pfm->height = height - height%pfi->df.dfPixHeight;
2509 penalty += (height - pfm->height + 1) * height / pfi->df.dfPixHeight;
2512 else /* can't be scaled at all */
2514 if( plf->lfQuality != PROOF_QUALITY) pfm->flags |= FO_SYNTH_HEIGHT;
2515 pfm->height = pfi->df.dfPixHeight;
2516 penalty += (d > 0)? d * 0x8 : -d * 0x10;
2519 else
2520 pfm->height = pfi->df.dfPixHeight;
2522 /* Pitch and Family */
2523 if( pfm->flags & FO_MATCH_PAF ) {
2524 int family = plf->lfPitchAndFamily & FF_FAMILY;
2526 /* TMPF_FIXED_PITCH means exactly the opposite */
2527 if( plf->lfPitchAndFamily & FIXED_PITCH ) {
2528 if( pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH ) penalty += 0x100;
2529 } else /* Variable is the default */
2530 if( !(pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH) ) penalty += 0x2;
2532 if (family != FF_DONTCARE && family != (pfi->df.dfPitchAndFamily & FF_FAMILY) )
2533 penalty += 0x10;
2536 /* Width */
2537 if( plf->lfWidth )
2539 int h;
2540 if( bR6 || bScale ) h = 0;
2541 else
2543 /* FIXME: not complete */
2545 pfm->flags |= FO_SYNTH_WIDTH;
2546 h = abs(plf->lfWidth - (pfm->height * pfi->df.dfAvgWidth)/pfi->df.dfPixHeight);
2548 penalty += h * ( d ) ? 0x2 : 0x1 ;
2550 else if( !(pfi->fi_flags & FI_NORMAL) ) penalty++;
2552 /* Weight */
2553 if( plf->lfWeight != FW_DONTCARE )
2555 penalty += abs(plf->lfWeight - pfi->df.dfWeight) / 40;
2556 if( plf->lfWeight > pfi->df.dfWeight ) pfm->flags |= FO_SYNTH_BOLD;
2557 } else if( pfi->df.dfWeight >= FW_BOLD ) penalty++; /* choose normal by default */
2559 /* Italic */
2560 if( plf->lfItalic != pfi->df.dfItalic )
2562 penalty += 0x4;
2563 pfm->flags |= FO_SYNTH_ITALIC;
2565 /* Underline */
2566 if( plf->lfUnderline ) pfm->flags |= FO_SYNTH_UNDERLINE;
2568 /* Strikeout */
2569 if( plf->lfStrikeOut ) pfm->flags |= FO_SYNTH_STRIKEOUT;
2572 if( penalty && !bScale && pfi->lfd_resolution != DefResolution )
2573 penalty++;
2575 TRACE(" returning %i\n", penalty );
2577 return penalty;
2580 /***********************************************************************
2581 * XFONT_MatchFIList
2583 * Scan a particular font resource for the best match.
2585 static UINT XFONT_MatchFIList( fontMatch* pfm )
2587 BOOL skipRaster = (pfm->flags & FO_MATCH_NORASTER);
2588 UINT current_score, score = (UINT)(-1);
2589 fontMatch fm = *pfm;
2591 for( fm.pfi = pfm->pfr->fi; fm.pfi && score; fm.pfi = fm.pfi->next)
2593 if( skipRaster && !(fm.pfi->fi_flags & FI_SCALABLE) )
2594 continue;
2596 current_score = XFONT_Match( &fm );
2597 if( score > current_score )
2599 *pfm = fm;
2600 score = current_score;
2603 return score;
2606 /***********************************************************************
2607 * XFONT_is_ansi_charset
2609 * returns TRUE if the given charset is ANSI_CHARSET.
2611 static BOOL XFONT_is_ansi_charset( UINT charset )
2613 return ((charset == ANSI_CHARSET) ||
2614 (charset == DEFAULT_CHARSET && GetACP() == 1252));
2617 /***********************************************************************
2618 * XFONT_MatchDeviceFont
2620 * Scan font resource tree.
2623 static void XFONT_MatchDeviceFont( fontResource* start, fontMatch* pfm)
2625 fontMatch fm = *pfm;
2626 UINT current_score, score = (UINT)(-1);
2627 fontResource** ppfr;
2629 TRACE("(%u) '%s' h=%i weight=%i %s\n",
2630 pfm->plf->lfCharSet, pfm->plf->lfFaceName, pfm->plf->lfHeight,
2631 pfm->plf->lfWeight, (pfm->plf->lfItalic) ? "Italic" : "" );
2633 pfm->pfi = NULL;
2635 /* the following hard-coded font binding assumes 'ANSI_CHARSET'. */
2636 if( !fm.plf->lfFaceName[0] &&
2637 XFONT_is_ansi_charset(fm.plf->lfCharSet) )
2639 switch(fm.plf->lfPitchAndFamily & 0xf0)
2641 case FF_MODERN:
2642 strcpy(fm.plf->lfFaceName, "Courier New");
2643 break;
2644 case FF_ROMAN:
2645 strcpy(fm.plf->lfFaceName, "Times New Roman");
2646 break;
2647 case FF_SWISS:
2648 strcpy(fm.plf->lfFaceName, "Arial");
2649 break;
2650 default:
2651 if((fm.plf->lfPitchAndFamily & 0x0f) == FIXED_PITCH)
2652 strcpy(fm.plf->lfFaceName, "Courier New");
2653 else
2654 strcpy(fm.plf->lfFaceName, "Arial");
2655 break;
2659 if( fm.plf->lfFaceName[0] )
2661 fm.pfr = XFONT_FindFIList( start, fm.plf->lfFaceName);
2662 if( fm.pfr ) /* match family */
2664 TRACE("found facename '%s'\n", fm.pfr->lfFaceName );
2666 if( fm.pfr->fr_flags & FR_REMOVED )
2667 fm.pfr = 0;
2668 else
2670 XFONT_MatchFIList( &fm );
2671 *pfm = fm;
2672 if (pfm->pfi)
2673 return;
2677 /* get charset if lfFaceName is one of known facenames. */
2679 const struct CharsetBindingInfo* pcharsetbindings;
2681 pcharsetbindings = &charsetbindings[0];
2682 while ( pcharsetbindings->pszFaceName != NULL )
2684 if ( !strcmp( pcharsetbindings->pszFaceName,
2685 fm.plf->lfFaceName ) )
2687 fm.internal_charset = pcharsetbindings->charset;
2688 break;
2690 pcharsetbindings ++;
2692 TRACE( "%s charset %u\n", fm.plf->lfFaceName, fm.internal_charset );
2696 /* match all available fonts */
2698 fm.flags |= FO_MATCH_PAF;
2699 for( ppfr = &fontList; *ppfr && score; ppfr = &(*ppfr)->next )
2701 if( (*ppfr)->fr_flags & FR_REMOVED )
2703 if( (*ppfr)->fo_count == 0 )
2704 XFONT_RemoveFontResource( ppfr );
2705 continue;
2708 fm.pfr = *ppfr;
2710 TRACE("%s\n", fm.pfr->lfFaceName );
2712 current_score = XFONT_MatchFIList( &fm );
2713 if( current_score < score )
2715 score = current_score;
2716 *pfm = fm;
2722 /***********************************************************************
2723 * X Font Cache
2725 static void XFONT_GrowFreeList(int start, int end)
2727 /* add all entries from 'start' up to and including 'end' */
2729 memset( fontCache + start, 0, (end - start + 1) * sizeof(fontObject) );
2731 fontCache[end].lru = fontLF;
2732 fontCache[end].count = -1;
2733 fontLF = start;
2734 while( start < end )
2736 fontCache[start].count = -1;
2737 fontCache[start].lru = start + 1;
2738 start++;
2742 static fontObject* XFONT_LookupCachedFont( const LPLOGFONT16 plf, UINT16* checksum )
2744 UINT16 cs = __lfCheckSum( plf );
2745 int i = fontMRU, prev = -1;
2747 *checksum = cs;
2748 while( i >= 0 )
2750 if( fontCache[i].lfchecksum == cs &&
2751 !(fontCache[i].fo_flags & FO_REMOVED) )
2753 /* FIXME: something more intelligent here ? */
2755 if( !memcmp( plf, &fontCache[i].lf,
2756 sizeof(LOGFONT16) - LF_FACESIZE ) &&
2757 !strcmp( plf->lfFaceName, fontCache[i].lf.lfFaceName) )
2759 /* remove temporarily from the lru list */
2760 if( prev >= 0 )
2761 fontCache[prev].lru = fontCache[i].lru;
2762 else
2763 fontMRU = (INT16)fontCache[i].lru;
2764 return (fontCache + i);
2767 prev = i;
2768 i = (INT16)fontCache[i].lru;
2770 return NULL;
2773 static fontObject* XFONT_GetCacheEntry(void)
2775 int i;
2777 if( fontLF == -1 )
2779 int prev_i, prev_j, j;
2781 TRACE("font cache is full\n");
2783 /* lookup the least recently used font */
2785 for( prev_i = prev_j = j = -1, i = fontMRU; i >= 0; i = (INT16)fontCache[i].lru )
2787 if( fontCache[i].count <= 0 &&
2788 !(fontCache[i].fo_flags & FO_SYSTEM) )
2790 prev_j = prev_i;
2791 j = i;
2793 prev_i = i;
2796 if( j >= 0 ) /* unload font */
2798 /* detach from the lru list */
2800 TRACE("\tfreeing entry %i\n", j );
2802 fontCache[j].fr->fo_count--;
2804 if( prev_j >= 0 )
2805 fontCache[prev_j].lru = fontCache[j].lru;
2806 else fontMRU = (INT16)fontCache[j].lru;
2808 /* FIXME: lpXForm, lpPixmap */
2809 if(fontCache[j].lpX11Trans)
2810 HeapFree( GetProcessHeap(), 0, fontCache[j].lpX11Trans );
2812 TSXFreeFont( gdi_display, fontCache[j].fs );
2814 memset( fontCache + j, 0, sizeof(fontObject) );
2815 return (fontCache + j);
2817 else /* expand cache */
2819 fontObject* newCache;
2821 prev_i = fontCacheSize + FONTCACHE;
2823 TRACE("\tgrowing font cache from %i to %i\n", fontCacheSize, prev_i );
2825 if( (newCache = (fontObject*)HeapReAlloc(GetProcessHeap(), 0,
2826 fontCache, prev_i)) )
2828 i = fontCacheSize;
2829 fontCacheSize = prev_i;
2830 fontCache = newCache;
2831 XFONT_GrowFreeList( i, fontCacheSize - 1);
2833 else return NULL;
2837 /* detach from the free list */
2839 i = fontLF;
2840 fontLF = (INT16)fontCache[i].lru;
2841 fontCache[i].count = 0;
2842 return (fontCache + i);
2845 static int XFONT_ReleaseCacheEntry(const fontObject* pfo)
2847 UINT u = (UINT)(pfo - fontCache);
2848 int i;
2849 int ret;
2851 if( u < fontCacheSize )
2853 ret = --fontCache[u].count;
2854 if ( ret == 0 )
2856 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
2858 if( CHECK_PFONT(pfo->prefobjs[i]) )
2859 XFONT_ReleaseCacheEntry(__PFONT(pfo->prefobjs[i]));
2863 return ret;
2866 return -1;
2869 /***********************************************************************
2870 * X11DRV_FONT_InitX11Metrics
2872 * Initialize font resource list and allocate font cache.
2874 void X11DRV_FONT_InitX11Metrics( void )
2876 char** x_pattern;
2877 unsigned x_checksum;
2878 int i, x_count, fd, buf_size;
2879 char *buffer;
2880 HKEY hkey;
2883 x_pattern = TSXListFonts(gdi_display, "*", MAX_FONTS, &x_count );
2885 TRACE("Font Mapper: initializing %i x11 fonts\n", x_count);
2886 if (x_count == MAX_FONTS)
2887 MESSAGE("There may be more fonts available - try increasing the value of MAX_FONTS\n");
2889 for( i = x_checksum = 0; i < x_count; i++ )
2891 int j;
2892 #if 0
2893 printf("%i\t: %s\n", i, x_pattern[i] );
2894 #endif
2896 j = strlen( x_pattern[i] );
2897 if( j ) x_checksum ^= __genericCheckSum( x_pattern[i], j );
2899 x_checksum |= X_PFONT_MAGIC;
2900 buf_size = 128;
2901 buffer = HeapAlloc( GetProcessHeap(), 0, buf_size );
2903 /* deal with systemwide font metrics cache */
2905 buffer[0] = 0;
2906 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, INIFontSection, &hkey))
2908 DWORD type, count = buf_size;
2909 RegQueryValueExA(hkey, INIGlobalMetrics, 0, &type, buffer, &count);
2910 RegCloseKey(hkey);
2913 if( buffer[0] )
2915 fd = open( buffer, O_RDONLY );
2916 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2918 if (fontList == NULL)
2920 /* try per-user */
2921 buffer = XFONT_UserMetricsCache( buffer, &buf_size );
2922 if( buffer[0] )
2924 fd = open( buffer, O_RDONLY );
2925 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2929 if( fontList == NULL ) /* build metrics from scratch */
2931 int n_ff = XFONT_BuildMetrics(x_pattern, DefResolution, x_checksum, x_count);
2932 if( buffer[0] ) /* update cached metrics */
2934 fd = open( buffer, O_CREAT | O_TRUNC | O_RDWR, 0644 ); /* -rw-r--r-- */
2935 if( XFONT_WriteCachedMetrics( fd, x_checksum, x_count, n_ff ) == FALSE )
2937 WARN("Unable to write to fontcache '%s'\n", buffer);
2938 if( fd >= 0) remove( buffer ); /* couldn't write entire file */
2943 TSXFreeFontNames(x_pattern);
2945 /* check if we're dealing with X11 R6 server */
2947 XFontStruct* x_fs;
2948 strcpy(buffer, "-*-*-*-*-normal-*-[12 0 0 12]-*-72-*-*-*-iso8859-1");
2949 if( (x_fs = TSXLoadQueryFont(gdi_display, buffer)) )
2951 text_caps |= TC_SF_X_YINDEP;
2952 TSXFreeFont(gdi_display, x_fs);
2955 HeapFree(GetProcessHeap(), 0, buffer);
2957 XFONT_WindowsNames();
2958 XFONT_LoadAliases();
2959 XFONT_LoadDefaults();
2960 XFONT_LoadIgnores();
2962 /* fontList initialization is over, allocate X font cache */
2964 fontCache = (fontObject*) HeapAlloc(GetProcessHeap(), 0, fontCacheSize * sizeof(fontObject));
2965 XFONT_GrowFreeList(0, fontCacheSize - 1);
2967 TRACE("done!\n");
2969 /* update text caps parameter */
2971 RAW_ASCENT = TSXInternAtom(gdi_display, "RAW_ASCENT", TRUE);
2972 RAW_DESCENT = TSXInternAtom(gdi_display, "RAW_DESCENT", TRUE);
2973 return;
2976 /***********************************************************************
2977 * X11DRV_FONT_Init
2979 void X11DRV_FONT_Init( int *log_pixels_x, int *log_pixels_y )
2981 XFONT_GetPointResolution( log_pixels_x, log_pixels_y );
2983 if(X11DRV_XRender_Installed)
2984 text_caps |= TC_VA_ABLE;
2986 return;
2989 /**********************************************************************
2990 * XFONT_SetX11Trans
2992 static BOOL XFONT_SetX11Trans( fontObject *pfo )
2994 char *fontName;
2995 Atom nameAtom;
2996 LFD* lfd;
2998 TSXGetFontProperty( pfo->fs, XA_FONT, &nameAtom );
2999 fontName = TSXGetAtomName( gdi_display, nameAtom );
3000 lfd = LFD_Parse(fontName);
3001 if (!lfd)
3003 TSXFree(fontName);
3004 return FALSE;
3007 if (lfd->pixel_size[0] != '[') {
3008 HeapFree(GetProcessHeap(), 0, lfd);
3009 TSXFree(fontName);
3010 return FALSE;
3013 #define PX pfo->lpX11Trans
3015 sscanf(lfd->pixel_size, "[%f%f%f%f]", &PX->a, &PX->b, &PX->c, &PX->d);
3016 TSXFree(fontName);
3017 HeapFree(GetProcessHeap(), 0, lfd);
3019 TSXGetFontProperty( pfo->fs, RAW_ASCENT, &PX->RAW_ASCENT );
3020 TSXGetFontProperty( pfo->fs, RAW_DESCENT, &PX->RAW_DESCENT );
3022 PX->pixelsize = hypot(PX->a, PX->b);
3023 PX->ascent = PX->pixelsize / 1000.0 * PX->RAW_ASCENT;
3024 PX->descent = PX->pixelsize / 1000.0 * PX->RAW_DESCENT;
3026 TRACE("[%f %f %f %f] RA = %ld RD = %ld\n",
3027 PX->a, PX->b, PX->c, PX->d,
3028 PX->RAW_ASCENT, PX->RAW_DESCENT);
3030 #undef PX
3031 return TRUE;
3034 /***********************************************************************
3035 * X Device Font Objects
3037 static X_PHYSFONT XFONT_RealizeFont( const LPLOGFONT16 plf,
3038 LPCSTR* faceMatched, BOOL bSubFont,
3039 WORD internal_charset,
3040 WORD* pcharsetMatched )
3042 UINT16 checksum;
3043 INT index = 0;
3044 fontObject* pfo;
3046 pfo = XFONT_LookupCachedFont( plf, &checksum );
3047 if( !pfo )
3049 fontMatch fm;
3050 INT i;
3052 fm.pfr = NULL;
3053 fm.pfi = NULL;
3054 fm.height = 0;
3055 fm.flags = 0;
3056 fm.plf = plf;
3057 fm.internal_charset = internal_charset;
3059 if( text_caps & TC_SF_X_YINDEP ) fm.flags = FO_MATCH_XYINDEP;
3061 /* allocate new font cache entry */
3063 if( (pfo = XFONT_GetCacheEntry()) )
3065 /* initialize entry and load font */
3066 char lpLFD[MAX_LFD_LENGTH];
3067 UINT uRelaxLevel = 0;
3069 if(abs(plf->lfHeight) > MAX_FONT_SIZE) {
3070 ERR(
3071 "plf->lfHeight = %d, Creating a 100 pixel font and rescaling metrics \n",
3072 plf->lfHeight);
3073 pfo->rescale = fabs(plf->lfHeight / 100.0);
3074 if(plf->lfHeight > 0) plf->lfHeight = 100;
3075 else plf->lfHeight = -100;
3076 } else
3077 pfo->rescale = 1.0;
3079 XFONT_MatchDeviceFont( fontList, &fm );
3080 pfo->fr = fm.pfr;
3081 pfo->fi = fm.pfi;
3082 pfo->fr->fo_count++;
3083 pfo->fo_flags = fm.flags & ~FO_MATCH_MASK;
3085 pfo->lf = *plf;
3086 pfo->lfchecksum = checksum;
3090 LFD_ComposeLFD( pfo, fm.height, lpLFD, uRelaxLevel++ );
3091 if( (pfo->fs = TSXLoadQueryFont( gdi_display, lpLFD )) ) break;
3092 } while( uRelaxLevel );
3095 if(pfo->lf.lfEscapement != 0) {
3096 pfo->lpX11Trans = HeapAlloc(GetProcessHeap(), 0, sizeof(XFONTTRANS));
3097 if(!XFONT_SetX11Trans( pfo )) {
3098 HeapFree(GetProcessHeap(), 0, pfo->lpX11Trans);
3099 pfo->lpX11Trans = NULL;
3102 XFONT_GetLeading( &pfo->fi->df, pfo->fs,
3103 &pfo->foInternalLeading, NULL, pfo->lpX11Trans );
3104 pfo->foAvgCharWidth = (INT16)XFONT_GetAvgCharWidth(&pfo->fi->df, pfo->fs, pfo->lpX11Trans );
3105 pfo->foMaxCharWidth = (INT16)XFONT_GetMaxCharWidth(pfo->fs, pfo->lpX11Trans);
3107 /* FIXME: If we've got a soft font or
3108 * there are FO_SYNTH_... flags for the
3109 * non PROOF_QUALITY request, the engine
3110 * should rasterize characters into mono
3111 * pixmaps and store them in the pfo->lpPixmap
3112 * array (pfo->fs should be updated as well).
3113 * array (pfo->fs should be updated as well).
3114 * X11DRV_ExtTextOut() must be heavily modified
3115 * to support pixmap blitting and FO_SYNTH_...
3116 * styles.
3119 pfo->lpPixmap = NULL;
3121 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3122 pfo->prefobjs[i] = (X_PHYSFONT)0xffffffff; /* invalid value */
3124 /* special treatment for DBCS that needs multiple fonts */
3125 /* All member of pfo must be set correctly. */
3126 if ( bSubFont == FALSE )
3128 WORD charset_sub;
3129 WORD charsetMatchedSub;
3130 LOGFONT16 lfSub;
3131 LPCSTR faceMatchedSub;
3133 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3135 charset_sub = X11DRV_cptable[pfo->fi->cptable].
3136 penum_subfont_charset( i );
3137 if ( charset_sub == DEFAULT_CHARSET ) break;
3139 lfSub = *plf;
3140 lfSub.lfWidth = 0;
3141 lfSub.lfHeight=plf->lfHeight;
3142 lfSub.lfCharSet = (BYTE)(charset_sub & 0xff);
3143 lfSub.lfFaceName[0] = '\0'; /* FIXME? */
3144 /* this font has sub font */
3145 if ( i == 0 ) pfo->prefobjs[0] = (X_PHYSFONT)0;
3146 pfo->prefobjs[i] =
3147 XFONT_RealizeFont( &lfSub, &faceMatchedSub,
3148 TRUE, charset_sub,
3149 &charsetMatchedSub );
3150 /* FIXME: check charsetMatchedSub */
3155 if( !pfo ) /* couldn't get a new entry, get one of the cached fonts */
3157 UINT current_score, score = (UINT)(-1);
3159 i = index = fontMRU;
3160 fm.flags |= FO_MATCH_PAF;
3163 pfo = fontCache + i;
3164 fm.pfr = pfo->fr; fm.pfi = pfo->fi;
3166 current_score = XFONT_Match( &fm );
3167 if( current_score < score ) index = i;
3169 i = pfo->lru;
3170 } while( i >= 0 );
3171 pfo = fontCache + index;
3172 goto END;
3176 /* attach at the head of the lru list */
3177 pfo->lru = fontMRU;
3178 index = fontMRU = (pfo - fontCache);
3180 END:
3181 pfo->count++;
3183 TRACE("physfont %i\n", index);
3184 *faceMatched = pfo->fi->df.dfFace;
3185 *pcharsetMatched = pfo->fi->internal_charset;
3187 return (X_PHYSFONT)(X_PFONT_MAGIC | index);
3190 /***********************************************************************
3191 * XFONT_GetFontObject
3193 fontObject* XFONT_GetFontObject( X_PHYSFONT pFont )
3195 if( CHECK_PFONT(pFont) ) return __PFONT(pFont);
3196 return NULL;
3199 /***********************************************************************
3200 * XFONT_GetFontStruct
3202 XFontStruct* XFONT_GetFontStruct( X_PHYSFONT pFont )
3204 if( CHECK_PFONT(pFont) ) return __PFONT(pFont)->fs;
3205 return NULL;
3208 /***********************************************************************
3209 * XFONT_GetFontInfo
3211 LPIFONTINFO16 XFONT_GetFontInfo( X_PHYSFONT pFont )
3213 if( CHECK_PFONT(pFont) ) return &(__PFONT(pFont)->fi->df);
3214 return NULL;
3219 /* X11DRV Interface ****************************************************
3221 * Exposed via the dc->funcs dispatch table. *
3223 ***********************************************************************/
3224 /***********************************************************************
3225 * SelectFont (X11DRV.@)
3227 HFONT X11DRV_SelectFont( X11DRV_PDEVICE *physDev, HFONT hfont )
3229 LOGFONTW logfont;
3230 LOGFONT16 lf;
3231 DC *dc = physDev->dc;
3233 TRACE("dc=%p, hfont=%04x\n", dc, hfont);
3235 if (!GetObjectW( hfont, sizeof(logfont), &logfont )) return GDI_ERROR;
3237 TRACE("dc->gdiFont = %p\n", dc->gdiFont);
3239 if(dc->gdiFont && X11DRV_XRender_Installed) {
3240 X11DRV_XRender_SelectFont(physDev, hfont);
3241 return FALSE;
3244 EnterCriticalSection( &crtsc_fonts_X11 );
3246 if(fontList == NULL) X11DRV_FONT_InitX11Metrics();
3248 if( CHECK_PFONT(physDev->font) )
3249 XFONT_ReleaseCacheEntry( __PFONT(physDev->font) );
3251 FONT_LogFontWTo16(&logfont, &lf);
3253 /* stock fonts ignore the mapping mode */
3254 if (!is_stock_font( hfont ))
3256 /* Make sure we don't change the sign when converting to device coords */
3257 /* FIXME - check that the other drivers do this correctly */
3258 if (lf.lfWidth)
3260 lf.lfWidth = GDI_ROUND((FLOAT)lf.lfWidth * fabs(dc->xformWorld2Vport.eM11));
3261 if (lf.lfWidth == 0)
3262 lf.lfWidth = 1; /* Minimum width */
3264 if (lf.lfHeight)
3266 lf.lfHeight = GDI_ROUND((FLOAT)lf.lfHeight * fabs(dc->xformWorld2Vport.eM22));
3268 if (lf.lfHeight == 0)
3269 lf.lfHeight = MIN_FONT_SIZE;
3273 if (!lf.lfHeight)
3274 lf.lfHeight = -(DEF_POINT_SIZE * GetDeviceCaps(dc->hSelf,LOGPIXELSY) + (72>>1)) / 72;
3277 /* Fixup aliases before passing to RealizeFont */
3278 /* alias = Windows name in the alias table */
3279 LPCSTR alias = XFONT_UnAlias( lf.lfFaceName );
3280 LPCSTR faceMatched;
3281 WORD charsetMatched;
3283 TRACE("hfont=%04x\n", hfont); /* to connect with the trace from RealizeFont */
3284 physDev->font = XFONT_RealizeFont( &lf, &faceMatched,
3285 FALSE, lf.lfCharSet,
3286 &charsetMatched );
3288 /* set face to the requested facename if it matched
3289 * so that GetTextFace can get the correct face name
3291 if (alias && !strcmp(faceMatched, lf.lfFaceName))
3292 MultiByteToWideChar(CP_ACP, 0, alias, -1,
3293 logfont.lfFaceName, LF_FACESIZE);
3294 else
3295 MultiByteToWideChar(CP_ACP, 0, faceMatched, -1,
3296 logfont.lfFaceName, LF_FACESIZE);
3299 * In X, some encodings may have the same lfFaceName.
3300 * for example:
3301 * -misc-fixed-*-iso8859-1
3302 * -misc-fixed-*-jisx0208.1990-0
3303 * so charset should be saved...
3305 logfont.lfCharSet = charsetMatched;
3308 LeaveCriticalSection( &crtsc_fonts_X11 );
3310 return TRUE; /* Use a device font */
3314 /***********************************************************************
3316 * X11DRV_EnumDeviceFonts
3318 BOOL X11DRV_EnumDeviceFonts( X11DRV_PDEVICE *physDev, LPLOGFONTW plf,
3319 DEVICEFONTENUMPROC proc, LPARAM lp )
3321 ENUMLOGFONTEXW lf;
3322 NEWTEXTMETRICEXW tm;
3323 fontResource* pfr = fontList;
3324 BOOL b, bRet = 0;
3325 LOGFONT16 lf16;
3327 /* don't enumerate x11 fonts if we're using client side fonts */
3328 if (physDev->dc->gdiFont) return FALSE;
3330 FONT_LogFontWTo16(plf, &lf16);
3332 if( lf16.lfFaceName[0] )
3334 /* enum all entries in this resource */
3335 pfr = XFONT_FindFIList( pfr, lf16.lfFaceName );
3336 if( pfr )
3338 fontInfo* pfi;
3339 for( pfi = pfr->fi; pfi; pfi = pfi->next )
3341 /* Note: XFONT_GetFontMetric() will have to
3342 release the crit section, font list will
3343 have to be retraversed on return */
3345 if(lf16.lfCharSet == DEFAULT_CHARSET ||
3346 lf16.lfCharSet == pfi->df.dfCharSet) {
3347 if( (b = (*proc)( &lf, &tm,
3348 XFONT_GetFontMetric( pfi, &lf, &tm ), lp )) )
3349 bRet = b;
3350 else break;
3355 else /* enum first entry in each resource */
3356 for( ; pfr ; pfr = pfr->next )
3358 if(pfr->fi)
3360 if( (b = (*proc)( &lf, &tm,
3361 XFONT_GetFontMetric( pfr->fi, &lf, &tm ), lp )) )
3362 bRet = b;
3363 else break;
3366 return bRet;
3370 /***********************************************************************
3371 * X11DRV_GetTextMetrics
3373 BOOL X11DRV_GetTextMetrics(X11DRV_PDEVICE *physDev, TEXTMETRICW *metrics)
3375 TEXTMETRICA tmA;
3377 if( CHECK_PFONT(physDev->font) )
3379 fontObject* pfo = __PFONT(physDev->font);
3380 X11DRV_cptable[pfo->fi->cptable].pGetTextMetricsA( pfo, &tmA );
3381 FONT_TextMetricAToW(&tmA, metrics);
3382 return TRUE;
3384 return FALSE;
3388 /***********************************************************************
3389 * X11DRV_GetCharWidth
3391 BOOL X11DRV_GetCharWidth( X11DRV_PDEVICE *physDev, UINT firstChar, UINT lastChar,
3392 LPINT buffer )
3394 fontObject* pfo = XFONT_GetFontObject( physDev->font );
3396 if( pfo )
3398 int i;
3400 if (pfo->fs->per_char == NULL)
3401 for (i = firstChar; i <= lastChar; i++)
3402 if(pfo->lpX11Trans)
3403 *buffer++ = pfo->fs->min_bounds.attributes *
3404 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3405 else
3406 *buffer++ = pfo->fs->min_bounds.width * pfo->rescale;
3407 else
3409 XCharStruct *cs, *def;
3410 static XCharStruct __null_char = { 0, 0, 0, 0, 0, 0 };
3412 CI_GET_CHAR_INFO(pfo->fs, pfo->fs->default_char, &__null_char,
3413 def);
3415 for (i = firstChar; i <= lastChar; i++)
3417 WCHAR wch = i;
3418 BYTE ch;
3419 UINT ch_f; /* character code in the font encoding */
3420 WideCharToMultiByte( pfo->fi->codepage, 0, &wch, 1, &ch, 1, NULL, NULL );
3421 ch_f = ch;
3422 if (ch_f >= pfo->fs->min_char_or_byte2 &&
3423 ch_f <= pfo->fs->max_char_or_byte2)
3425 cs = &pfo->fs->per_char[(ch_f - pfo->fs->min_char_or_byte2)];
3426 if (CI_NONEXISTCHAR(cs)) cs = def;
3427 } else cs = def;
3428 if(pfo->lpX11Trans)
3429 *buffer++ = max(cs->attributes, 0) *
3430 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3431 else
3432 *buffer++ = max(cs->width, 0 ) * pfo->rescale;
3436 return TRUE;
3438 return FALSE;