push 337eb2e2d902d84a5d689451984c5832d7e04fc4
[wine/hacks.git] / dlls / winex11.drv / xfont.c
blob9fcb9930858d3fe2060af619e192a12673fa4f8d
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 <ctype.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 #include <sys/types.h>
36 #include <fcntl.h>
37 #include <math.h>
39 #include "windef.h"
40 #include "winbase.h"
41 #include "wingdi.h"
42 #include "winnls.h"
43 #include "winreg.h"
44 #include "x11font.h"
45 #include "wine/library.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(font);
51 #define X_PFONT_MAGIC (0xFADE0000)
52 #define X_FMC_MAGIC (0x0000CAFE)
54 #define MAX_FONTS 1024*16
55 #define MAX_LFD_LENGTH 256
56 #define TILDE '~'
57 #define HYPHEN '-'
59 #define DEF_POINT_SIZE 8 /* CreateFont(0 .. ) gets this */
60 #define DEF_SCALABLE_HEIGHT 100 /* pixels */
61 #define MIN_FONT_SIZE 2 /* Min size in pixels */
62 #define MAX_FONT_SIZE 1000 /* Max size in pixels */
64 #define REMOVE_SUBSETS 1
65 #define UNMARK_SUBSETS 0
67 #define FONTCACHE 32 /* dynamic font cache size */
69 #define FF_FAMILY (FF_MODERN | FF_SWISS | FF_ROMAN | FF_DECORATIVE | FF_SCRIPT)
71 typedef struct __fontAlias
73 LPSTR faTypeFace;
74 LPSTR faAlias;
75 struct __fontAlias* next;
76 } fontAlias;
78 static fontAlias *aliasTable = NULL;
80 static const char INIFontMetrics[] = "cachedmetrics.";
81 static const char INIFontSection[] = "Software\\Wine\\X11 Driver\\Fonts";
82 static const char INIAliasSection[] = "Alias";
83 static const char INIIgnoreSection[] = "Ignore";
84 static const char INIDefault[] = "Default";
85 static const char INIDefaultFixed[] = "DefaultFixed";
86 static const char INIGlobalMetrics[] = "FontMetrics";
87 static const char INIDefaultSerif[] = "DefaultSerif";
88 static const char INIDefaultSansSerif[] = "DefaultSansSerif";
91 /* FIXME - are there any more Latin charsets ? */
92 /* FIXME - RUSSIAN, ARABIC, GREEK, HEBREW are NOT Latin */
93 #define IS_LATIN_CHARSET(ch) \
94 ((ch)==ANSI_CHARSET ||\
95 (ch)==EE_CHARSET ||\
96 (ch)==ISO3_CHARSET ||\
97 (ch)==ISO4_CHARSET ||\
98 (ch)==RUSSIAN_CHARSET ||\
99 (ch)==ARABIC_CHARSET ||\
100 (ch)==GREEK_CHARSET ||\
101 (ch)==HEBREW_CHARSET ||\
102 (ch)==TURKISH_CHARSET ||\
103 (ch)==ISO10_CHARSET ||\
104 (ch)==BALTIC_CHARSET ||\
105 (ch)==CELTIC_CHARSET)
107 /* suffix-charset mapping tables - must be less than 254 entries long */
109 typedef struct __sufch
111 LPCSTR psuffix;
112 WORD charset; /* hibyte != 0 means *internal* charset */
113 WORD codepage;
114 WORD cptable;
115 } SuffixCharset;
117 static const SuffixCharset sufch_ansi[] = {
118 { "0", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
119 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
121 static const SuffixCharset sufch_iso646[] = {
122 { "irv", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
123 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
125 static const SuffixCharset sufch_iso8859[] = {
126 { "1", ANSI_CHARSET, 28591, X11DRV_CPTABLE_SBCS },
127 { "2", EE_CHARSET, 28592, X11DRV_CPTABLE_SBCS },
128 { "3", ISO3_CHARSET, 28593, X11DRV_CPTABLE_SBCS },
129 { "4", ISO4_CHARSET, 28594, X11DRV_CPTABLE_SBCS },
130 { "5", RUSSIAN_CHARSET, 28595, X11DRV_CPTABLE_SBCS },
131 { "6", ARABIC_CHARSET, 28596, X11DRV_CPTABLE_SBCS },
132 { "7", GREEK_CHARSET, 28597, X11DRV_CPTABLE_SBCS },
133 { "8", HEBREW_CHARSET, 28598, X11DRV_CPTABLE_SBCS },
134 { "9", TURKISH_CHARSET, 28599, X11DRV_CPTABLE_SBCS },
135 { "10", ISO10_CHARSET, 28600, X11DRV_CPTABLE_SBCS },
136 { "11", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
137 { "12", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
138 { "13", BALTIC_CHARSET, 28603, X11DRV_CPTABLE_SBCS },
139 { "14", CELTIC_CHARSET, 28604, X11DRV_CPTABLE_SBCS },
140 { "15", ANSI_CHARSET, 28605, X11DRV_CPTABLE_SBCS },
141 { "16", ISO3_CHARSET, 28606, X11DRV_CPTABLE_SBCS },
142 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
144 static const SuffixCharset sufch_microsoft[] = {
145 { "cp1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
146 { "cp1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
147 { "cp1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
148 { "cp1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
149 { "cp1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
150 { "cp1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
151 { "cp1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
152 { "cp1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
153 { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SYMBOL },
154 { "symbol", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SYMBOL },
155 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
157 static const SuffixCharset sufch_tcvn[] = {
158 { "0", TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
159 { NULL, TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
161 static const SuffixCharset sufch_tis620[] = {
162 { "0", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
163 { NULL, THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }};
165 static const SuffixCharset sufch_viscii[] = {
166 { "1", VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
167 { NULL, VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
169 static const SuffixCharset sufch_windows[] = {
170 { "1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
171 { "1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
172 { "1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
173 { "1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
174 { "1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
175 { "1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
176 { "1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
177 { "1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
178 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
180 static const SuffixCharset sufch_koi8[] = {
181 { "r", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
182 { "ru", RUSSIAN_CHARSET, 21866, X11DRV_CPTABLE_SBCS },
183 { "u", RUSSIAN_CHARSET, 21866, X11DRV_CPTABLE_SBCS },
184 { NULL, RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS }};
186 static const SuffixCharset sufch_jisx0201[] = {
187 { "0", X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS },
188 { NULL, X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS }};
190 static const SuffixCharset sufch_jisx0208[] = {
191 { "0", SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 },
192 { NULL, SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
194 static const SuffixCharset sufch_jisx0212[] = {
195 { "0", X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 },
196 { NULL, X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
198 static const SuffixCharset sufch_ksc5601[] = {
199 { "0", HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 },
200 { NULL, HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 }};
202 static const SuffixCharset sufch_gb2312[] = {
203 { "0", GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 },
204 { NULL, GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 }};
206 static const SuffixCharset sufch_big5[] = {
207 { "0", CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 },
208 { NULL, CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 }};
210 static const SuffixCharset sufch_unicode[] = {
211 { "0", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
212 { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
214 static const SuffixCharset sufch_iso10646[] = {
215 { "1", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
216 { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
218 static const SuffixCharset sufch_dec[] = {
219 { "dectech", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
220 { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
222 /* Each of these must be matched explicitly */
223 static const SuffixCharset sufch_any[] = {
224 { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
225 { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
228 typedef struct __fet
230 LPCSTR prefix;
231 const SuffixCharset* sufch;
232 const struct __fet* next;
233 } fontEncodingTemplate;
235 /* Note: we can attach additional encoding mappings to the end
236 * of this table at runtime.
238 static const fontEncodingTemplate fETTable[] = {
239 { "ansi", sufch_ansi, &fETTable[1] },
240 { "ascii", sufch_ansi, &fETTable[2] },
241 { "iso646.1991", sufch_iso646, &fETTable[3] },
242 { "iso8859", sufch_iso8859, &fETTable[4] },
243 { "microsoft", sufch_microsoft, &fETTable[5] },
244 { "tcvn", sufch_tcvn, &fETTable[6] },
245 { "tis620.2533", sufch_tis620, &fETTable[7] },
246 { "viscii1.1", sufch_viscii, &fETTable[8] },
247 { "windows", sufch_windows, &fETTable[9] },
248 { "koi8", sufch_koi8, &fETTable[10]},
249 { "jisx0201.1976",sufch_jisx0201, &fETTable[11]},
250 { "jisc6226.1978",sufch_jisx0208, &fETTable[12]},
251 { "jisx0208.1983",sufch_jisx0208, &fETTable[13]},
252 { "jisx0208.1990",sufch_jisx0208, &fETTable[14]},
253 { "jisx0212.1990",sufch_jisx0212, &fETTable[15]},
254 { "ksc5601.1987", sufch_ksc5601, &fETTable[16]},
255 { "gb2312.1980", sufch_gb2312, &fETTable[17]},
256 { "big5", sufch_big5, &fETTable[18]},
257 { "unicode", sufch_unicode, &fETTable[19]},
258 { "iso10646", sufch_iso10646, &fETTable[20]},
259 { "cp", sufch_windows, &fETTable[21]},
260 { "dec", sufch_dec, &fETTable[22]},
261 /* NULL prefix matches anything so put it last */
262 { NULL, sufch_any, NULL },
265 /* a charset database for known facenames */
266 struct CharsetBindingInfo
268 const char* pszFaceName;
269 BYTE charset;
271 static const struct CharsetBindingInfo charsetbindings[] =
273 /* special facenames */
274 { "System", DEFAULT_CHARSET },
275 { "FixedSys", DEFAULT_CHARSET },
277 /* known facenames */
278 { "MS Serif", ANSI_CHARSET },
279 { "MS Sans Serif", ANSI_CHARSET },
280 { "Courier", ANSI_CHARSET },
281 { "Symbol", SYMBOL_CHARSET },
283 { "Arial", ANSI_CHARSET },
284 { "Arial Greek", GREEK_CHARSET },
285 { "Arial Tur", TURKISH_CHARSET },
286 { "Arial Baltic", BALTIC_CHARSET },
287 { "Arial CE", EASTEUROPE_CHARSET },
288 { "Arial Cyr", RUSSIAN_CHARSET },
289 { "Courier New", ANSI_CHARSET },
290 { "Courier New Greek", GREEK_CHARSET },
291 { "Courier New Tur", TURKISH_CHARSET },
292 { "Courier New Baltic", BALTIC_CHARSET },
293 { "Courier New CE", EASTEUROPE_CHARSET },
294 { "Courier New Cyr", RUSSIAN_CHARSET },
295 { "Times New Roman", ANSI_CHARSET },
296 { "Times New Roman Greek", GREEK_CHARSET },
297 { "Times New Roman Tur", TURKISH_CHARSET },
298 { "Times New Roman Baltic", BALTIC_CHARSET },
299 { "Times New Roman CE", EASTEUROPE_CHARSET },
300 { "Times New Roman Cyr", RUSSIAN_CHARSET },
302 { "\x82\x6c\x82\x72 \x83\x53\x83\x56\x83\x62\x83\x4e",
303 SHIFTJIS_CHARSET }, /* MS gothic */
304 { "\x82\x6c\x82\x72 \x82\x6f\x83\x53\x83\x56\x83\x62\x83\x4e",
305 SHIFTJIS_CHARSET }, /* MS P gothic */
306 { "\x82\x6c\x82\x72 \x96\xbe\x92\xa9",
307 SHIFTJIS_CHARSET }, /* MS mincho */
308 { "\x82\x6c\x82\x72 \x82\x6f\x96\xbe\x92\xa9",
309 SHIFTJIS_CHARSET }, /* MS P mincho */
310 { "GulimChe", HANGEUL_CHARSET },
311 { "\xcb\xce\xcc\xe5", GB2312_CHARSET }, /* SimSun */
312 { "\xba\xda\xcc\xe5", GB2312_CHARSET }, /* SimHei */
313 { "\xb7\x73\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },/*MS Mingliu*/
314 { "\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },
316 { NULL, 0 }
320 static int DefResolution = 0;
322 static CRITICAL_SECTION crtsc_fonts_X11;
323 static CRITICAL_SECTION_DEBUG critsect_debug =
325 0, 0, &crtsc_fonts_X11,
326 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
327 0, 0, { (DWORD_PTR)(__FILE__ ": crtsc_fonts_X11") }
329 static CRITICAL_SECTION crtsc_fonts_X11 = { &critsect_debug, -1, 0, 0, 0, 0 };
331 static fontResource* fontList = NULL;
332 static fontObject* fontCache = NULL; /* array */
333 static unsigned int fontCacheSize = FONTCACHE;
334 static int fontLF = -1, fontMRU = -1; /* last free, most recently used */
336 #define __PFONT(pFont) ( fontCache + ((UINT)(pFont) & 0x0000FFFF) )
337 #define CHECK_PFONT(pFont) ( (((UINT)(pFont) & 0xFFFF0000) == X_PFONT_MAGIC) &&\
338 (((UINT)(pFont) & 0x0000FFFF) < fontCacheSize) )
340 /***********************************************************************
341 * Helper macros from X distribution
344 #define CI_NONEXISTCHAR(cs) (((cs)->width == 0) && \
345 (((cs)->rbearing|(cs)->lbearing| \
346 (cs)->ascent|(cs)->descent) == 0))
348 #define CI_GET_CHAR_INFO(fs,col,def,cs) \
350 cs = def; \
351 if (col >= fs->min_char_or_byte2 && col <= fs->max_char_or_byte2) { \
352 if (fs->per_char == NULL) { \
353 cs = &fs->min_bounds; \
354 } else { \
355 cs = &fs->per_char[(col - fs->min_char_or_byte2)]; \
356 if (CI_NONEXISTCHAR(cs)) cs = def; \
361 #define CI_GET_DEFAULT_INFO(fs,cs) \
362 CI_GET_CHAR_INFO(fs, fs->default_char, NULL, cs)
365 /***********************************************************************
366 * is_stock_font
368 static inline BOOL is_stock_font( HFONT font )
370 int i;
371 for (i = OEM_FIXED_FONT; i <= DEFAULT_GUI_FONT; i++)
373 if (i != DEFAULT_PALETTE && font == GetStockObject(i)) return TRUE;
375 return FALSE;
379 static void FONT_LogFontWTo16( const LOGFONTW* font32, LPLOGFONT16 font16 )
381 font16->lfHeight = font32->lfHeight;
382 font16->lfWidth = font32->lfWidth;
383 font16->lfEscapement = font32->lfEscapement;
384 font16->lfOrientation = font32->lfOrientation;
385 font16->lfWeight = font32->lfWeight;
386 font16->lfItalic = font32->lfItalic;
387 font16->lfUnderline = font32->lfUnderline;
388 font16->lfStrikeOut = font32->lfStrikeOut;
389 font16->lfCharSet = font32->lfCharSet;
390 font16->lfOutPrecision = font32->lfOutPrecision;
391 font16->lfClipPrecision = font32->lfClipPrecision;
392 font16->lfQuality = font32->lfQuality;
393 font16->lfPitchAndFamily = font32->lfPitchAndFamily;
394 WideCharToMultiByte( CP_ACP, 0, font32->lfFaceName, -1,
395 font16->lfFaceName, LF_FACESIZE, NULL, NULL );
396 font16->lfFaceName[LF_FACESIZE-1] = 0;
400 /***********************************************************************
401 * Checksums
403 static UINT16 __lfCheckSum( const LOGFONT16 *plf )
405 CHAR font[LF_FACESIZE];
406 UINT16 checksum = 0;
407 const UINT16 *ptr;
408 int i;
410 ptr = (const UINT16 *)plf;
411 for (i = 0; i < 9; i++) checksum ^= *ptr++;
412 for (i = 0; i < LF_FACESIZE; i++)
414 font[i] = tolower(plf->lfFaceName[i]);
415 if (!font[i] || font[i] == ' ') break;
417 for (ptr = (UINT16 *)font, i >>= 1; i > 0; i-- ) checksum ^= *ptr++;
418 return checksum;
421 static UINT16 __genericCheckSum( const void *ptr, int size )
423 unsigned int checksum = 0;
424 const char *p = (const char *)ptr;
425 while (size-- > 0)
426 checksum ^= (checksum << 3) + (checksum >> 29) + *p++;
428 return checksum & 0xffff;
431 /*************************************************************************
432 * LFD parse/compose routines
434 * NB. LFD_Parse will use lpFont for its own ends, so if you want to keep it
435 * make a copy first
437 * These functions also do TILDE to HYPHEN conversion
439 static BOOL LFD_Parse(LPSTR lpFont, LFD *lfd)
441 char *lpch = lpFont, *lfd_fld[LFD_FIELDS], *field_start;
442 int i;
443 if (*lpch != HYPHEN)
445 WARN("font '%s' doesn't begin with '%c'\n", lpFont, HYPHEN);
446 return FALSE;
449 field_start = ++lpch;
450 for( i = 0; i < LFD_FIELDS; )
452 if (*lpch == HYPHEN)
454 *lpch = '\0';
455 lfd_fld[i] = field_start;
456 i++;
457 field_start = ++lpch;
459 else if (!*lpch)
461 lfd_fld[i] = field_start;
462 i++;
463 break;
465 else if (*lpch == TILDE)
467 *lpch = HYPHEN;
468 ++lpch;
470 else
471 ++lpch;
473 /* Fill in the empty fields with NULLS */
474 for (; i< LFD_FIELDS; i++)
475 lfd_fld[i] = NULL;
476 if (*lpch)
477 WARN("Extra ignored in font '%s'\n", lpFont);
479 lfd->foundry = lfd_fld[0];
480 lfd->family = lfd_fld[1];
481 lfd->weight = lfd_fld[2];
482 lfd->slant = lfd_fld[3];
483 lfd->set_width = lfd_fld[4];
484 lfd->add_style = lfd_fld[5];
485 lfd->pixel_size = lfd_fld[6];
486 lfd->point_size = lfd_fld[7];
487 lfd->resolution_x = lfd_fld[8];
488 lfd->resolution_y = lfd_fld[9];
489 lfd->spacing = lfd_fld[10];
490 lfd->average_width = lfd_fld[11];
491 lfd->charset_registry = lfd_fld[12];
492 lfd->charset_encoding = lfd_fld[13];
493 return TRUE;
497 static void LFD_UnParse(LPSTR dp, UINT buf_size, LFD* lfd)
499 const char* lfd_fld[LFD_FIELDS];
500 int i;
502 if (!buf_size)
503 return; /* Don't be silly */
505 lfd_fld[0] = lfd->foundry;
506 lfd_fld[1] = lfd->family;
507 lfd_fld[2] = lfd->weight ;
508 lfd_fld[3] = lfd->slant ;
509 lfd_fld[4] = lfd->set_width ;
510 lfd_fld[5] = lfd->add_style;
511 lfd_fld[6] = lfd->pixel_size;
512 lfd_fld[7] = lfd->point_size;
513 lfd_fld[8] = lfd->resolution_x;
514 lfd_fld[9] = lfd->resolution_y ;
515 lfd_fld[10] = lfd->spacing ;
516 lfd_fld[11] = lfd->average_width ;
517 lfd_fld[12] = lfd->charset_registry ;
518 lfd_fld[13] = lfd->charset_encoding ;
520 buf_size--; /* Room for the terminator */
522 for (i = 0; i < LFD_FIELDS; i++)
524 const char* sp = lfd_fld[i];
525 if (!sp || !buf_size)
526 break;
528 *dp++ = HYPHEN;
529 buf_size--;
530 while (buf_size > 0 && *sp)
532 *dp = (*sp == HYPHEN) ? TILDE : *sp;
533 buf_size--;
534 dp++; sp++;
537 *dp = '\0';
541 static void LFD_GetWeight( fontInfo* fi, LPCSTR lpStr)
543 int j = strlen(lpStr);
544 if( j == 1 && *lpStr == '0')
545 fi->fi_flags |= FI_POLYWEIGHT;
546 else if( j == 4 )
548 if( !strcasecmp( "bold", lpStr) )
549 fi->df.dfWeight = FW_BOLD;
550 else if( !strcasecmp( "demi", lpStr) )
552 fi->fi_flags |= FI_FW_DEMI;
553 fi->df.dfWeight = FW_DEMIBOLD;
555 else if( !strcasecmp( "book", lpStr) )
557 fi->fi_flags |= FI_FW_BOOK;
558 fi->df.dfWeight = FW_REGULAR;
561 else if( j == 5 )
563 if( !strcasecmp( "light", lpStr) )
564 fi->df.dfWeight = FW_LIGHT;
565 else if( !strcasecmp( "black", lpStr) )
566 fi->df.dfWeight = FW_BLACK;
568 else if( j == 6 && !strcasecmp( "medium", lpStr) )
569 fi->df.dfWeight = FW_REGULAR;
570 else if( j == 8 && !strcasecmp( "demibold", lpStr) )
571 fi->df.dfWeight = FW_DEMIBOLD;
572 else
573 fi->df.dfWeight = FW_DONTCARE; /* FIXME: try to get something
574 * from the weight property */
577 static BOOL LFD_GetSlant( fontInfo* fi, LPCSTR lpStr)
579 int l = strlen(lpStr);
580 if( l == 1 )
582 switch( tolower( *lpStr ) )
584 case '0': fi->fi_flags |= FI_POLYSLANT; /* haven't seen this one yet */
585 default:
586 case 'r': fi->df.dfItalic = 0;
587 break;
588 case 'o':
589 fi->fi_flags |= FI_OBLIQUE;
590 case 'i': fi->df.dfItalic = 1;
591 break;
593 return FALSE;
595 return TRUE;
598 static void LFD_GetStyle( fontInfo* fi, LPCSTR lpstr, int dec_style_check)
600 int j = strlen(lpstr);
601 if( j > 3 ) /* find out is there "sans" or "script" */
603 j = 0;
605 if( strstr(lpstr, "sans") )
607 fi->df.dfPitchAndFamily |= FF_SWISS;
608 j = 1;
610 if( strstr(lpstr, "script") )
612 fi->df.dfPitchAndFamily |= FF_SCRIPT;
613 j = 1;
615 if( !j && dec_style_check )
616 fi->df.dfPitchAndFamily |= FF_DECORATIVE;
620 /*************************************************************************
621 * LFD_InitFontInfo
623 * INIT ONLY
625 * Fill in some fields in the fontInfo struct.
627 static int LFD_InitFontInfo( fontInfo* fi, const LFD* lfd, LPCSTR fullname )
629 int i, j, dec_style_check, scalability;
630 const fontEncodingTemplate* boba;
631 const char* ridiculous = "font '%s' has ridiculous %s\n";
632 const char* lpstr;
634 if (!lfd->charset_registry)
636 WARN("font '%s' does not have enough fields\n", fullname);
637 return FALSE;
640 memset(fi, 0, sizeof(fontInfo) );
642 /* weight name - */
643 LFD_GetWeight( fi, lfd->weight);
645 /* slant - */
646 dec_style_check = LFD_GetSlant( fi, lfd->slant);
648 /* width name - */
649 lpstr = lfd->set_width;
650 if( strcasecmp( "normal", lpstr) ) /* XXX 'narrow', 'condensed', etc... */
651 dec_style_check = TRUE;
652 else
653 fi->fi_flags |= FI_NORMAL;
655 /* style - */
656 LFD_GetStyle(fi, lfd->add_style, dec_style_check);
658 /* pixel & decipoint height, and res_x & y */
660 scalability = 0;
662 j = strlen(lfd->pixel_size);
663 if( j == 0 || j > 3 )
665 WARN(ridiculous, fullname, "pixel_size");
666 return FALSE;
668 if( !(fi->lfd_height = atoi(lfd->pixel_size)) )
669 scalability++;
671 j = strlen(lfd->point_size);
672 if( j == 0 || j > 3 )
674 WARN(ridiculous, fullname, "point_size");
675 return FALSE;
677 if( !(atoi(lfd->point_size)) )
678 scalability++;
680 j = strlen(lfd->resolution_x);
681 if( j == 0 || j > 3 )
683 WARN(ridiculous, fullname, "resolution_x");
684 return FALSE;
686 if( !(fi->lfd_resolution = atoi(lfd->resolution_x)) )
687 scalability++;
689 j = strlen(lfd->resolution_y);
690 if( j == 0 || j > 3 )
692 WARN(ridiculous, fullname, "resolution_y");
693 return FALSE;
695 if( !(atoi(lfd->resolution_y)) )
696 scalability++;
698 /* Check scalability */
699 switch (scalability)
701 case 0: /* Bitmap */
702 break;
703 case 4: /* Scalable */
704 fi->fi_flags |= FI_SCALABLE;
705 break;
706 case 2:
707 /* #$%^!!! X11R6 mutant garbage (scalable bitmap) */
708 TRACE("Skipping scalable bitmap '%s'\n", fullname);
709 return FALSE;
710 default:
711 WARN("Font '%s' has weird scalability\n", fullname);
712 return FALSE;
715 /* spacing - */
716 lpstr = lfd->spacing;
717 switch( *lpstr )
719 case '\0':
720 WARN("font '%s' has no spacing\n", fullname);
721 return FALSE;
723 case 'p': fi->fi_flags |= FI_VARIABLEPITCH;
724 break;
725 case 'c': fi->df.dfPitchAndFamily |= FF_MODERN;
726 fi->fi_flags |= FI_FIXEDEX;
727 /* fall through */
728 case 'm': fi->fi_flags |= FI_FIXEDPITCH;
729 break;
730 default:
731 /* Of course this line does nothing */
732 fi->df.dfPitchAndFamily |= DEFAULT_PITCH | FF_DONTCARE;
735 /* average width - */
736 lpstr = lfd->average_width;
737 j = strlen(lpstr);
738 if( j == 0 || j > 3 )
740 WARN(ridiculous, fullname, "average_width");
741 return FALSE;
744 if( !(atoi(lpstr)) && !scalability )
746 WARN("font '%s' has average_width 0 but is not scalable!!\n", fullname);
747 return FALSE;
750 /* charset registry, charset encoding - */
751 lpstr = lfd->charset_registry;
752 if( strstr(lpstr, "ksc") ||
753 strstr(lpstr, "gb2312") ||
754 strstr(lpstr, "big5") )
756 FIXME("DBCS fonts like '%s' are not working correctly now.\n", fullname);
759 fi->df.dfCharSet = ANSI_CHARSET;
761 for( i = 0, boba = &fETTable[0]; boba; boba = boba->next, i++ )
763 if (!boba->prefix || !strcasecmp(lpstr, boba->prefix))
765 if (lfd->charset_encoding)
767 for( j = 0; boba->sufch[j].psuffix; j++ )
769 if( !strcasecmp(lfd->charset_encoding, boba->sufch[j].psuffix ))
771 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
772 fi->internal_charset = boba->sufch[j].charset;
773 fi->codepage = boba->sufch[j].codepage;
774 fi->cptable = boba->sufch[j].cptable;
775 goto done;
779 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
780 fi->internal_charset = boba->sufch[j].charset;
781 fi->codepage = boba->sufch[j].codepage;
782 fi->cptable = boba->sufch[j].cptable;
783 if (boba->prefix)
785 FIXME("font '%s' has unknown character encoding '%s' in known registry '%s'\n",
786 fullname, lfd->charset_encoding, boba->prefix);
787 j = 254;
789 else
791 FIXME("font '%s' has unknown registry '%s' and character encoding '%s'\n",
792 fullname, lfd->charset_registry, lfd->charset_encoding);
793 j = 255;
796 WARN("Defaulting to: df.dfCharSet = %d, internal_charset = %d, codepage = %d, cptable = %d\n",
797 fi->df.dfCharSet,fi->internal_charset, fi->codepage, fi->cptable);
798 goto done;
800 else if (boba->prefix)
802 WARN("font '%s' has known registry '%s' and no character encoding\n",
803 fullname, lpstr);
804 for( j = 0; boba->sufch[j].psuffix; j++ )
806 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
807 fi->internal_charset = boba->sufch[j].charset;
808 fi->codepage = boba->sufch[j].codepage;
809 fi->cptable = boba->sufch[j].cptable;
810 j = 255;
811 goto done;
815 WARN("font '%s' has unknown character set '%s'\n", fullname, lpstr);
816 return FALSE;
818 done:
819 /* i - index into fETTable
820 * j - index into suffix array for fETTable[i]
821 * except:
822 * 254 - found encoding prefix, unknown suffix
823 * 255 - no encoding match at all.
825 fi->fi_encoding = 256 * (UINT16)i + (UINT16)j;
827 return TRUE;
831 /*************************************************************************
832 * LFD_AngleMatrix
834 * make a matrix suitable for LFD based on theta radians
836 static void LFD_AngleMatrix( char* buffer, int h, double theta)
838 double matrix[4];
839 matrix[0] = h*cos(theta);
840 matrix[1] = h*sin(theta);
841 matrix[2] = -h*sin(theta);
842 matrix[3] = h*cos(theta);
843 sprintf(buffer, "[%+f%+f%+f%+f]", matrix[0], matrix[1], matrix[2], matrix[3]);
846 /*************************************************************************
847 * LFD_ComposeLFD
849 * Note: uRelax is a treatment not a cure. Font mapping algorithm
850 * should be bulletproof enough to allow us to avoid hacks like
851 * this despite LFD being so braindead.
853 static BOOL LFD_ComposeLFD( const fontObject* fo,
854 INT height, LPSTR lpLFD, UINT uRelax )
856 int i, h;
857 const char *any = "*";
858 char h_string[64], resx_string[64], resy_string[64];
859 LFD aLFD;
860 const fontEncodingTemplate* boba = &fETTable[0];
862 /* Get the worst case over with first */
864 /* RealizeFont() will call us repeatedly with increasing uRelax
865 * until XLoadFont() succeeds.
866 * to avoid an infinite loop; these will always match
868 if (uRelax >= 6)
870 if (uRelax == 6)
871 sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-1" );
872 else
873 sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*" );
874 return TRUE;
877 /* read foundry + family from fo */
878 aLFD.foundry = fo->fr->resource->foundry;
879 aLFD.family = fo->fr->resource->family;
881 /* add weight */
882 switch( fo->fi->df.dfWeight )
884 case FW_BOLD:
885 aLFD.weight = "bold"; break;
886 case FW_REGULAR:
887 if( fo->fi->fi_flags & FI_FW_BOOK )
888 aLFD.weight = "book";
889 else
890 aLFD.weight = "medium";
891 break;
892 case FW_DEMIBOLD:
893 aLFD.weight = "demi";
894 if( !( fo->fi->fi_flags & FI_FW_DEMI) )
895 aLFD.weight = "bold";
896 break;
897 case FW_BLACK:
898 aLFD.weight = "black"; break;
899 case FW_LIGHT:
900 aLFD.weight = "light"; break;
901 default:
902 aLFD.weight = any;
905 /* add slant */
906 if( fo->fi->df.dfItalic )
907 if( fo->fi->fi_flags & FI_OBLIQUE )
908 aLFD.slant = "o";
909 else
910 aLFD.slant = "i";
911 else
912 aLFD.slant = (uRelax <= 1) ? "r" : any;
914 /* add width */
915 if( fo->fi->fi_flags & FI_NORMAL )
916 aLFD.set_width = "normal";
917 else
918 aLFD.set_width = any;
920 /* ignore style */
921 aLFD.add_style = any;
923 /* add pixelheight
925 * FIXME: fill in lpXForm and lpPixmap for rotated fonts
927 if( fo->fo_flags & FO_SYNTH_HEIGHT )
928 h = fo->fi->lfd_height;
929 else
931 h = (fo->fi->lfd_height * height + (fo->fi->df.dfPixHeight>>1));
932 h /= fo->fi->df.dfPixHeight;
934 if (h < MIN_FONT_SIZE) /* Resist rounding down to 0 */
935 h = MIN_FONT_SIZE;
936 else if (h > MAX_FONT_SIZE) /* Sanity check as huge fonts can lock up the font server */
938 WARN("Huge font size %d pixels has been reduced to %d\n", h, MAX_FONT_SIZE);
939 h = MAX_FONT_SIZE;
942 if (uRelax <= 3)
943 /* handle rotated fonts */
944 if (fo->lf.lfEscapement) {
945 /* escapement is in tenths of degrees, theta is in radians */
946 double theta = M_PI*fo->lf.lfEscapement/1800.;
947 LFD_AngleMatrix(h_string, h, theta);
949 else
951 sprintf(h_string, "%d", h);
953 else
954 sprintf(h_string, "%d", fo->fi->lfd_height);
956 aLFD.pixel_size = h_string;
957 aLFD.point_size = any;
959 /* resolution_x,y, average width */
960 /* FIXME - Why do some font servers ignore average width ?
961 * so that you have to mess around with res_y
963 aLFD.average_width = any;
964 if (uRelax <= 4)
966 sprintf(resx_string, "%d", fo->fi->lfd_resolution);
967 aLFD.resolution_x = resx_string;
969 strcpy(resy_string, resx_string);
970 if( uRelax == 0 && text_caps & TC_SF_X_YINDEP )
972 if( fo->lf.lfWidth && !(fo->fo_flags & FO_SYNTH_WIDTH))
974 int resy = 0.5 + fo->fi->lfd_resolution *
975 (fo->fi->df.dfAvgWidth * height) /
976 (fo->lf.lfWidth * fo->fi->df.dfPixHeight) ;
977 sprintf(resy_string, "%d", resy);
979 else
981 /* FIXME - synth width */
984 aLFD.resolution_y = resy_string;
986 else
988 aLFD.resolution_x = aLFD.resolution_y = any;
991 /* spacing */
993 const char* w;
995 if( fo->fi->fi_flags & FI_FIXEDPITCH )
996 w = ( fo->fi->fi_flags & FI_FIXEDEX ) ? "c" : "m";
997 else
998 w = ( fo->fi->fi_flags & FI_VARIABLEPITCH ) ? "p" : any;
1000 aLFD.spacing = (uRelax <= 2) ? w : any;
1003 /* encoding */
1005 for(i = fo->fi->fi_encoding >> 8; i; i--) boba = boba->next;
1006 aLFD.charset_registry = boba->prefix ? boba->prefix : any;
1008 i = fo->fi->fi_encoding & 255;
1009 switch( i ) {
1010 default:
1011 aLFD.charset_encoding = boba->sufch[i].psuffix;
1012 break;
1014 case 254:
1015 aLFD.charset_encoding = any;
1016 break;
1018 case 255: /* no suffix - it ends, e.g., "-ascii" */
1019 aLFD.charset_encoding = NULL;
1020 break;
1023 LFD_UnParse(lpLFD, MAX_LFD_LENGTH, &aLFD);
1025 TRACE("\tLFD(uRelax=%d): %s\n", uRelax, lpLFD );
1026 return TRUE;
1030 /***********************************************************************
1031 * X Font Resources
1033 static void XFONT_GetLeading( const IFONTINFO16 *pFI, const XFontStruct* x_fs,
1034 INT16* pIL, INT16* pEL, const XFONTTRANS *XFT )
1036 unsigned long height;
1037 unsigned min = (unsigned char)pFI->dfFirstChar;
1038 unsigned max = (unsigned char)pFI->dfLastChar;
1039 BOOL bIsLatin = IS_LATIN_CHARSET(pFI->dfCharSet);
1041 if( pEL ) *pEL = 0;
1043 if(XFT) {
1044 wine_tsx11_lock();
1045 if(XGetFontProperty((XFontStruct*)x_fs, x11drv_atom(RAW_CAP_HEIGHT), &height))
1046 *pIL = XFT->ascent -
1047 (INT)(XFT->pixelsize / 1000.0 * height);
1048 else
1049 *pIL = 0;
1050 wine_tsx11_unlock();
1051 return;
1054 wine_tsx11_lock();
1055 if( XGetFontProperty((XFontStruct*)x_fs, XA_CAP_HEIGHT, &height) == FALSE )
1057 if( x_fs->per_char )
1058 if( bIsLatin && ((unsigned char)'X' <= (max - min)) )
1059 height = x_fs->per_char['X' - min].ascent;
1060 else
1061 if (x_fs->ascent >= x_fs->max_bounds.ascent)
1062 height = x_fs->max_bounds.ascent;
1063 else
1065 height = x_fs->ascent;
1066 if( pEL )
1067 *pEL = x_fs->max_bounds.ascent - height;
1069 else
1070 height = x_fs->min_bounds.ascent;
1072 wine_tsx11_unlock();
1074 *pIL = x_fs->ascent - height;
1077 /***********************************************************************
1078 * XFONT_CharWidth
1080 static int XFONT_CharWidth(const XFontStruct* x_fs,
1081 const XFONTTRANS *XFT, int ch)
1083 if(!XFT)
1084 return x_fs->per_char[ch].width;
1085 else
1086 return x_fs->per_char[ch].attributes * XFT->pixelsize / 1000.0;
1089 /***********************************************************************
1090 * XFONT_GetAvgCharWidth
1092 static INT XFONT_GetAvgCharWidth( LPIFONTINFO16 pFI, const XFontStruct* x_fs,
1093 const XFONTTRANS *XFT)
1095 unsigned min = (unsigned char)pFI->dfFirstChar;
1096 unsigned max = (unsigned char)pFI->dfLastChar;
1098 INT avg;
1100 if( x_fs->per_char )
1102 unsigned int width = 0, chars = 0, j;
1103 if( (IS_LATIN_CHARSET(pFI->dfCharSet) ||
1104 pFI->dfCharSet == DEFAULT_CHARSET) &&
1105 (max - min) >= (unsigned char)'z' )
1107 /* FIXME - should use a weighted average */
1108 for( j = 0; j < 26; j++ )
1109 width += XFONT_CharWidth(x_fs, XFT, 'a' + j - min) +
1110 XFONT_CharWidth(x_fs, XFT, 'A' + j - min);
1111 chars = 52;
1113 else /* unweighted average of everything */
1115 for( j = 0, max -= min; j <= max; j++ )
1116 if( !CI_NONEXISTCHAR(x_fs->per_char + j) )
1118 width += XFONT_CharWidth(x_fs, XFT, j);
1119 chars++;
1122 if (chars) avg = (width + (chars-1))/ chars; /* always round up*/
1123 else avg = 0; /* No characters exist at all */
1125 else /* uniform width */
1126 avg = x_fs->min_bounds.width;
1128 TRACE(" retuning %d\n",avg);
1129 return avg;
1132 /***********************************************************************
1133 * XFONT_GetMaxCharWidth
1135 static INT XFONT_GetMaxCharWidth(const XFontStruct* xfs, const XFONTTRANS *XFT)
1137 unsigned min = (unsigned char)xfs->min_char_or_byte2;
1138 unsigned max = (unsigned char)xfs->max_char_or_byte2;
1139 unsigned int maxwidth, j;
1141 if(!XFT || !xfs->per_char)
1142 return abs(xfs->max_bounds.width);
1144 for( j = 0, maxwidth = 0, max -= min; j <= max; j++ )
1145 if( !CI_NONEXISTCHAR(xfs->per_char + j) )
1146 if(maxwidth < xfs->per_char[j].attributes)
1147 maxwidth = xfs->per_char[j].attributes;
1149 maxwidth *= XFT->pixelsize / 1000.0;
1150 return maxwidth;
1153 /***********************************************************************
1154 * XFONT_SetFontMetric
1156 * INIT ONLY
1158 * Initializes IFONTINFO16.
1160 static void XFONT_SetFontMetric(fontInfo* fi, const fontResource* fr, XFontStruct* xfs)
1162 unsigned min, max;
1163 fi->df.dfFirstChar = (BYTE)(min = xfs->min_char_or_byte2);
1164 fi->df.dfLastChar = (BYTE)(max = xfs->max_char_or_byte2);
1166 fi->df.dfDefaultChar = (BYTE)xfs->default_char;
1167 fi->df.dfBreakChar = (BYTE)(( ' ' < min || ' ' > max) ? xfs->default_char: ' ');
1169 fi->df.dfPixHeight = (INT16)((fi->df.dfAscent = (INT16)xfs->ascent) + xfs->descent);
1170 fi->df.dfPixWidth = (xfs->per_char) ? 0 : xfs->min_bounds.width;
1172 XFONT_GetLeading( &fi->df, xfs, &fi->df.dfInternalLeading, &fi->df.dfExternalLeading, NULL );
1173 fi->df.dfAvgWidth = (INT16)XFONT_GetAvgCharWidth(&fi->df, xfs, NULL );
1174 fi->df.dfMaxWidth = (INT16)XFONT_GetMaxCharWidth(xfs, NULL);
1176 if( xfs->min_bounds.width != xfs->max_bounds.width )
1177 fi->df.dfPitchAndFamily |= TMPF_FIXED_PITCH; /* au contraire! */
1178 if( fi->fi_flags & FI_SCALABLE )
1180 fi->df.dfType = DEVICE_FONTTYPE;
1181 fi->df.dfPitchAndFamily |= TMPF_DEVICE;
1183 else if( fi->fi_flags & FI_TRUETYPE )
1184 fi->df.dfType = TRUETYPE_FONTTYPE;
1185 else
1186 fi->df.dfType = RASTER_FONTTYPE;
1188 fi->df.dfFace = fr->lfFaceName;
1191 /***********************************************************************
1192 * XFONT_GetFontMetric
1194 * Retrieve font metric info (enumeration).
1196 static UINT XFONT_GetFontMetric( const fontInfo* pfi,
1197 LPENUMLOGFONTEXW pLF,
1198 NEWTEXTMETRICEXW *pTM )
1200 memset( pLF, 0, sizeof(*pLF) );
1201 memset( pTM, 0, sizeof(*pTM) );
1203 #define plf ((LPLOGFONTW)pLF)
1204 #define ptm ((LPNEWTEXTMETRICW)pTM)
1205 plf->lfHeight = ptm->tmHeight = pfi->df.dfPixHeight;
1206 plf->lfWidth = ptm->tmAveCharWidth = pfi->df.dfAvgWidth;
1207 plf->lfWeight = ptm->tmWeight = pfi->df.dfWeight;
1208 plf->lfItalic = ptm->tmItalic = pfi->df.dfItalic;
1209 plf->lfUnderline = ptm->tmUnderlined = pfi->df.dfUnderline;
1210 plf->lfStrikeOut = ptm->tmStruckOut = pfi->df.dfStrikeOut;
1211 plf->lfCharSet = ptm->tmCharSet = pfi->df.dfCharSet;
1213 /* convert pitch values */
1215 ptm->tmPitchAndFamily = pfi->df.dfPitchAndFamily;
1216 plf->lfPitchAndFamily = (pfi->df.dfPitchAndFamily & 0xF1) + 1;
1218 MultiByteToWideChar(CP_ACP, 0, pfi->df.dfFace, -1,
1219 plf->lfFaceName, LF_FACESIZE);
1221 /* FIXME: fill in rest of plF values */
1222 strcpyW(pLF->elfFullName, plf->lfFaceName);
1223 MultiByteToWideChar(CP_ACP, 0, "Regular", -1,
1224 pLF->elfStyle, LF_FACESIZE);
1225 MultiByteToWideChar(CP_ACP, 0, plf->lfCharSet == SYMBOL_CHARSET ?
1226 "Symbol" : "Roman", -1,
1227 pLF->elfScript, LF_FACESIZE);
1229 #undef plf
1231 ptm->tmAscent = pfi->df.dfAscent;
1232 ptm->tmDescent = ptm->tmHeight - ptm->tmAscent;
1233 ptm->tmInternalLeading = pfi->df.dfInternalLeading;
1234 ptm->tmMaxCharWidth = pfi->df.dfMaxWidth;
1235 ptm->tmDigitizedAspectX = pfi->df.dfHorizRes;
1236 ptm->tmDigitizedAspectY = pfi->df.dfVertRes;
1238 ptm->tmFirstChar = pfi->df.dfFirstChar;
1239 ptm->tmLastChar = pfi->df.dfLastChar;
1240 ptm->tmDefaultChar = pfi->df.dfDefaultChar;
1241 ptm->tmBreakChar = pfi->df.dfBreakChar;
1243 TRACE("Calling Enum proc with FaceName %s FullName %s\n",
1244 debugstr_w(pLF->elfLogFont.lfFaceName),
1245 debugstr_w(pLF->elfFullName));
1247 TRACE("CharSet = %d type = %d\n", ptm->tmCharSet, pfi->df.dfType);
1248 /* return font type */
1249 return pfi->df.dfType;
1250 #undef ptm
1254 /***********************************************************************
1255 * XFONT_FixupFlags
1257 * INIT ONLY
1259 * dfPitchAndFamily flags for some common typefaces.
1261 static BYTE XFONT_FixupFlags( LPCSTR lfFaceName )
1263 switch( lfFaceName[0] )
1265 case 'a':
1266 case 'A': if(!strncasecmp(lfFaceName, "Arial", 5) )
1267 return FF_SWISS;
1268 break;
1269 case 'h':
1270 case 'H': if(!strcasecmp(lfFaceName, "Helvetica") )
1271 return FF_SWISS;
1272 break;
1273 case 'c':
1274 case 'C': if(!strncasecmp(lfFaceName, "Courier", 7))
1275 return FF_MODERN;
1277 if (!strcasecmp(lfFaceName, "Charter") )
1278 return FF_ROMAN;
1279 break;
1280 case 'p':
1281 case 'P': if( !strcasecmp(lfFaceName,"Palatino") )
1282 return FF_ROMAN;
1283 break;
1284 case 't':
1285 case 'T': if(!strncasecmp(lfFaceName, "Times", 5) )
1286 return FF_ROMAN;
1287 break;
1288 case 'u':
1289 case 'U': if(!strcasecmp(lfFaceName, "Utopia") )
1290 return FF_ROMAN;
1291 break;
1292 case 'z':
1293 case 'Z': if(!strcasecmp(lfFaceName, "Zapf Dingbats") )
1294 return FF_DECORATIVE;
1296 return 0;
1299 /***********************************************************************
1300 * XFONT_SameFoundryAndFamily
1302 * INIT ONLY
1304 static BOOL XFONT_SameFoundryAndFamily( const LFD* lfd1, const LFD* lfd2 )
1306 return ( !strcasecmp( lfd1->foundry, lfd2->foundry ) &&
1307 !strcasecmp( lfd1->family, lfd2->family ) );
1310 /***********************************************************************
1311 * XFONT_InitialCapitals
1313 * INIT ONLY
1315 * Upper case first letters of words & remove multiple spaces
1317 static void XFONT_InitialCapitals(LPSTR lpch)
1319 int i;
1320 BOOL up;
1321 char* lpstr = lpch;
1323 for( i = 0, up = TRUE; *lpch; lpch++, i++ )
1325 if( isspace(*lpch) )
1327 if (!up) /* Not already got one */
1329 *lpstr++ = ' ';
1330 up = TRUE;
1333 else if( isalpha(*lpch) && up )
1335 *lpstr++ = toupper(*lpch);
1336 up = FALSE;
1338 else
1340 *lpstr++ = *lpch;
1341 up = FALSE;
1345 /* Remove possible trailing space */
1346 if (up && i > 0)
1347 --lpstr;
1348 *lpstr = '\0';
1352 /***********************************************************************
1353 * XFONT_WindowsNames
1355 * INIT ONLY
1357 * Build generic Windows aliases for X font names.
1359 * -misc-fixed- -> "Fixed"
1360 * -sony-fixed- -> "Sony Fixed", etc...
1362 static void XFONT_WindowsNames(void)
1364 fontResource* fr;
1366 for( fr = fontList; fr ; fr = fr->next )
1368 fontResource* pfr;
1370 if( fr->fr_flags & FR_NAMESET ) continue; /* skip already assigned */
1372 for( pfr = fontList; pfr != fr ; pfr = pfr->next )
1373 if( pfr->fr_flags & FR_NAMESET )
1375 if (!strcasecmp( pfr->resource->family, fr->resource->family))
1376 break;
1379 snprintf( fr->lfFaceName, sizeof(fr->lfFaceName), "%s %s",
1380 /* prepend vendor name */
1381 (pfr==fr) ? "" : fr->resource->foundry,
1382 fr->resource->family);
1383 XFONT_InitialCapitals(fr->lfFaceName);
1385 BYTE bFamilyStyle = XFONT_FixupFlags( fr->lfFaceName );
1386 if( bFamilyStyle)
1388 fontInfo* fi;
1389 for( fi = fr->fi ; fi ; fi = fi->next )
1390 fi->df.dfPitchAndFamily |= bFamilyStyle;
1394 TRACE("typeface '%s'\n", fr->lfFaceName);
1396 fr->fr_flags |= FR_NAMESET;
1400 /***********************************************************************
1401 * XFONT_LoadDefaultLFD
1403 * Move lfd to the head of fontList to make it more likely to be matched
1405 static void XFONT_LoadDefaultLFD(LFD* lfd, LPCSTR fonttype)
1408 fontResource *fr, *pfr;
1409 for( fr = NULL, pfr = fontList; pfr; pfr = pfr->next )
1411 if( XFONT_SameFoundryAndFamily(pfr->resource, lfd) )
1413 if( fr )
1415 fr->next = pfr->next;
1416 pfr->next = fontList;
1417 fontList = pfr;
1419 break;
1421 fr = pfr;
1423 if (!pfr)
1424 WARN("Default %sfont '-%s-%s-' not available\n", fonttype,
1425 lfd->foundry, lfd->family);
1429 /***********************************************************************
1430 * XFONT_LoadDefault
1432 static void XFONT_LoadDefault( HKEY hkey, LPCSTR ini, LPCSTR fonttype)
1434 char buffer[MAX_LFD_LENGTH];
1435 DWORD type, count = sizeof(buffer);
1437 buffer[0] = 0;
1438 RegQueryValueExA(hkey, ini, 0, &type, (LPBYTE)buffer, &count);
1440 if (*buffer)
1442 LFD lfd;
1443 char* pch = buffer;
1444 while( *pch && isspace(*pch) ) pch++;
1446 TRACE("Using '%s' as default %sfont\n", pch, fonttype);
1447 if (LFD_Parse(pch, &lfd) && lfd.foundry && lfd.family)
1448 XFONT_LoadDefaultLFD(&lfd, fonttype);
1449 else
1450 WARN("Ini section [%s]%s is malformed\n", INIFontSection, ini);
1454 /***********************************************************************
1455 * XFONT_LoadDefaults
1457 static void XFONT_LoadDefaults( HKEY hkey )
1459 XFONT_LoadDefault( hkey, INIDefaultFixed, "fixed ");
1460 XFONT_LoadDefault( hkey, 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 config file. 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( HKEY hkey )
1631 char *lpResource;
1632 char buffer[MAX_LFD_LENGTH];
1633 int i = 0;
1634 LFD lfd;
1636 /* built-ins first */
1637 strcpy(buffer, "-bitstream-charter-");
1638 if (hkey)
1640 DWORD type, count = sizeof(buffer);
1641 RegQueryValueExA(hkey, INIDefaultSerif, 0, &type, (LPBYTE)buffer, &count);
1643 TRACE("Using '%s' as default serif font\n", buffer);
1644 if (LFD_Parse(buffer, &lfd))
1646 /* NB XFONT_InitialCapitals should not change these standard aliases */
1647 XFONT_LoadAlias( &lfd, "Tms Roman", FALSE);
1648 XFONT_LoadAlias( &lfd, "MS Serif", FALSE);
1649 XFONT_LoadAlias( &lfd, "Times New Roman", FALSE);
1651 XFONT_LoadDefaultLFD( &lfd, "serif ");
1654 strcpy(buffer, "-adobe-helvetica-");
1655 if (hkey)
1657 DWORD type, count = sizeof(buffer);
1658 RegQueryValueExA(hkey, INIDefaultSansSerif, 0, &type, (LPBYTE)buffer, &count);
1660 TRACE("Using '%s' as default sans serif font\n", buffer);
1661 if (LFD_Parse(buffer, &lfd))
1663 XFONT_LoadAlias( &lfd, "Helv", FALSE);
1664 XFONT_LoadAlias( &lfd, "MS Sans Serif", FALSE);
1665 XFONT_LoadAlias( &lfd, "MS Shell Dlg", FALSE);
1666 XFONT_LoadAlias( &lfd, "System", FALSE);
1667 XFONT_LoadAlias( &lfd, "Arial", FALSE);
1669 XFONT_LoadDefaultLFD( &lfd, "sans serif ");
1672 /* then user specified aliases */
1675 BOOL bSubst;
1676 char subsection[32];
1677 snprintf( subsection, sizeof(subsection), "%s%i", INIAliasSection, i++ );
1679 buffer[0] = 0;
1680 if (hkey)
1682 DWORD type, count = sizeof(buffer);
1683 RegQueryValueExA(hkey, subsection, 0, &type, (LPBYTE)buffer, &count);
1686 if (!buffer[0])
1687 break;
1689 XFONT_InitialCapitals(buffer);
1690 lpResource = XFONT_GetStringItem( buffer );
1691 bSubst = (XFONT_GetStringItem( lpResource )) ? TRUE : FALSE;
1692 if( lpResource && *lpResource )
1694 if (LFD_Parse(lpResource, &lfd)) XFONT_LoadAlias(&lfd, buffer, bSubst);
1696 else
1697 WARN("malformed font alias '%s'\n", buffer );
1699 while(TRUE);
1702 /***********************************************************************
1703 * XFONT_UnAlias
1705 * Convert an (potential) alias into a real windows name
1708 static LPCSTR XFONT_UnAlias(char* font)
1710 if (font[0])
1712 fontAlias* fa;
1713 XFONT_InitialCapitals(font); /* to remove extra white space */
1715 for( fa = aliasTable; fa; fa = fa->next )
1716 /* use case insensitive matching to handle, e.g., "MS Sans Serif" */
1717 if( !strcasecmp( fa->faAlias, font ) )
1719 TRACE("found alias '%s'->%s'\n", font, fa->faTypeFace );
1720 strcpy(font, fa->faTypeFace);
1721 return fa->faAlias;
1724 return NULL;
1727 /***********************************************************************
1728 * XFONT_RemoveFontResource
1730 * Caller should check if the font resource is in use. If it is it should
1731 * set FR_REMOVED flag to delay removal until the resource is not in use
1732 * any more.
1734 static void XFONT_RemoveFontResource( fontResource** ppfr )
1736 fontResource* pfr = *ppfr;
1737 #if 0
1738 fontInfo* pfi;
1740 /* FIXME - if fonts were read from a cache, these HeapFrees will fail */
1741 while( pfr->fi )
1743 pfi = pfr->fi->next;
1744 HeapFree( GetProcessHeap(), 0, pfr->fi );
1745 pfr->fi = pfi;
1747 HeapFree( GetProcessHeap(), 0, pfr );
1748 #endif
1749 *ppfr = pfr->next;
1752 /***********************************************************************
1753 * XFONT_LoadIgnores
1755 * INIT ONLY
1757 * Removes specified fonts from the font table to prevent Wine from
1758 * using it.
1760 * Ignore# = [LFD font name]
1762 * Example:
1763 * Ignore0 = -misc-nil-
1764 * Ignore1 = -sun-open look glyph-
1765 * ...
1768 static void XFONT_LoadIgnore(char* lfdname)
1770 fontResource** ppfr;
1771 LFD lfd;
1773 if (LFD_Parse(lfdname, &lfd) && lfd.foundry && lfd.family)
1775 for( ppfr = &fontList; *ppfr ; ppfr = &((*ppfr)->next))
1777 if( XFONT_SameFoundryAndFamily( (*ppfr)->resource, &lfd) )
1779 TRACE("Ignoring '-%s-%s-'\n",
1780 (*ppfr)->resource->foundry, (*ppfr)->resource->family );
1782 XFONT_RemoveFontResource( ppfr );
1783 break;
1787 else
1788 WARN("Malformed font resource\n");
1791 static void XFONT_LoadIgnores( HKEY hkey )
1793 int i = 0;
1794 char subsection[32];
1795 char buffer[MAX_LFD_LENGTH];
1797 /* Standard one that no one wants */
1798 strcpy(buffer, "-misc-nil-");
1799 XFONT_LoadIgnore(buffer);
1801 /* Others from INI file */
1802 if (!hkey) return;
1805 DWORD type, count = sizeof(buffer);
1806 sprintf( subsection, "%s%i", INIIgnoreSection, i++ );
1808 if (!RegQueryValueExA(hkey, subsection, 0, &type, (LPBYTE)buffer, &count))
1810 char* pch = buffer;
1811 while( *pch && isspace(*pch) ) pch++;
1812 XFONT_LoadIgnore(pch);
1814 else
1815 break;
1816 } while(TRUE);
1820 /***********************************************************************
1821 * XFONT_UserMetricsCache
1823 * Returns expanded name for the cachedmetrics file.
1824 * Now it also appends the current value of the $DISPLAY variable.
1826 static char* XFONT_UserMetricsCache( char* buffer, int* buf_size )
1828 const char *confdir = wine_get_config_dir();
1829 const char *display_name = XDisplayName(NULL);
1830 int len = strlen(confdir) + strlen(INIFontMetrics) + strlen(display_name) + 8;
1831 int display = 0;
1832 int screen = 0;
1833 char *p, *ext;
1836 ** Normalize the display name, since on Red Hat systems, DISPLAY
1837 ** is commonly set to one of either 'unix:0.0' or ':0' or ':0.0'.
1838 ** after this code, all of the above will resolve to ':0.0'.
1840 if (!strncmp( display_name, "unix:", 5 )) display_name += 4;
1841 p = strchr(display_name, ':');
1842 if (p) sscanf(p + 1, "%d.%d", &display, &screen);
1844 if ((len > *buf_size) &&
1845 !(buffer = HeapReAlloc( GetProcessHeap(), 0, buffer, *buf_size = len )))
1847 ERR("out of memory\n");
1848 ExitProcess(1);
1850 sprintf( buffer, "%s/%s", confdir, INIFontMetrics );
1852 ext = buffer + strlen(buffer);
1853 strcpy( ext, display_name );
1855 if (!(p = strchr( ext, ':' ))) p = ext + strlen(ext);
1856 sprintf( p, ":%d.%d", display, screen );
1857 return buffer;
1861 /***********************************************************************
1862 * X Font Matching
1864 * Compare two fonts (only parameters set by the XFONT_InitFontInfo()).
1866 static INT XFONT_IsSubset(const fontInfo* match, const fontInfo* fi)
1868 INT m;
1870 /* 0 - keep both, 1 - keep match, -1 - keep fi */
1872 /* Compare dfItalic, Underline, Strikeout, Weight, Charset */
1873 m = (const BYTE*)&fi->df.dfPixWidth - (const BYTE*)&fi->df.dfItalic;
1874 if( memcmp(&match->df.dfItalic, &fi->df.dfItalic, m )) return 0;
1876 if( (!((fi->fi_flags & FI_SCALABLE) + (match->fi_flags & FI_SCALABLE))
1877 && fi->lfd_height != match->lfd_height) ||
1878 (!((fi->fi_flags & FI_POLYWEIGHT) + (match->fi_flags & FI_POLYWEIGHT))
1879 && fi->df.dfWeight != match->df.dfWeight) ) return 0;
1881 m = (int)(match->fi_flags & (FI_POLYWEIGHT | FI_SCALABLE)) -
1882 (int)(fi->fi_flags & (FI_SCALABLE | FI_POLYWEIGHT));
1884 if( m == (FI_POLYWEIGHT - FI_SCALABLE) ||
1885 m == (FI_SCALABLE - FI_POLYWEIGHT) ) return 0; /* keep both */
1886 else if( m >= 0 ) return 1; /* 'match' is better */
1888 return -1; /* 'fi' is better */
1891 /***********************************************************************
1892 * XFONT_CheckFIList
1894 * REMOVE_SUBSETS - attach new fi and purge subsets
1895 * UNMARK_SUBSETS - remove subset flags from all fi entries
1897 static void XFONT_CheckFIList( fontResource* fr, fontInfo* fi, int action)
1899 int i = 0;
1900 fontInfo* pfi, *prev;
1902 for( prev = NULL, pfi = fr->fi; pfi; )
1904 if( action == REMOVE_SUBSETS )
1906 if( pfi->fi_flags & FI_SUBSET )
1908 fontInfo* subset = pfi;
1910 i++;
1911 fr->fi_count--;
1912 if( prev ) prev->next = pfi = pfi->next;
1913 else fr->fi = pfi = pfi->next;
1914 HeapFree( GetProcessHeap(), 0, subset );
1915 continue;
1918 else pfi->fi_flags &= ~FI_SUBSET;
1920 prev = pfi;
1921 pfi = pfi->next;
1924 if( action == REMOVE_SUBSETS ) /* also add the superset */
1926 if( fi->fi_flags & FI_SCALABLE )
1928 fi->next = fr->fi;
1929 fr->fi = fi;
1931 else if( prev ) prev->next = fi; else fr->fi = fi;
1932 fr->fi_count++;
1935 if( i ) TRACE("\t purged %i subsets [%i]\n", i , fr->fi_count);
1938 /***********************************************************************
1939 * XFONT_FindFIList
1941 static fontResource* XFONT_FindFIList( fontResource* pfr, const char* pTypeFace )
1943 while( pfr )
1945 if( !strcasecmp( pfr->lfFaceName, pTypeFace ) ) break;
1946 pfr = pfr->next;
1948 /* Give the app back the font name it asked for. Encarta checks this. */
1949 if (pfr) strcpy(pfr->lfFaceName,pTypeFace);
1950 return pfr;
1953 /***********************************************************************
1954 * XFONT_FixupPointSize
1956 static void XFONT_FixupPointSize(fontInfo* fi)
1958 #define df (fi->df)
1959 df.dfHorizRes = df.dfVertRes = fi->lfd_resolution;
1960 df.dfPoints = (INT16)
1961 (((INT)(df.dfPixHeight - df.dfInternalLeading) * 72 + (df.dfVertRes >> 1)) /
1962 df.dfVertRes );
1963 #undef df
1966 /***********************************************************************
1967 * XFONT_BuildMetrics
1969 * Build font metrics from X font
1971 static int XLoadQueryFont_ErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
1973 return 1;
1976 /* XLoadQueryFont has the bad habit of crashing when loading a bad font... */
1977 static XFontStruct *safe_XLoadQueryFont(Display *display, char *name)
1979 XFontStruct *ret;
1981 X11DRV_expect_error(display, XLoadQueryFont_ErrorHandler, NULL);
1982 ret = XLoadQueryFont(display, name);
1983 if (X11DRV_check_error()) ret = NULL;
1984 return ret;
1988 static int XFONT_BuildMetrics(char** x_pattern, int res, unsigned x_checksum, int x_count)
1990 int i;
1991 fontInfo* fi = NULL;
1992 fontResource* fr, *pfr;
1993 int n_ff = 0;
1995 MESSAGE("Building font metrics. This may take some time...\n");
1996 for( i = 0; i < x_count; i++ )
1998 char* typeface;
1999 LFD lfd;
2000 int j;
2001 char buffer[MAX_LFD_LENGTH];
2002 char* lpstr;
2003 XFontStruct* x_fs;
2004 fontInfo* pfi;
2006 if (!(typeface = HeapAlloc(GetProcessHeap(), 0, strlen(x_pattern[i])+1))) break;
2007 strcpy( typeface, x_pattern[i] );
2008 if (i % 10 == 0) MESSAGE("Font metrics: %.1f%% done\n", 100.0 * i / x_count);
2010 if (!LFD_Parse(typeface, &lfd))
2012 HeapFree(GetProcessHeap(), 0, typeface);
2013 continue;
2016 /* find a family to insert into */
2018 for( pfr = NULL, fr = fontList; fr; fr = fr->next )
2020 if( XFONT_SameFoundryAndFamily(fr->resource, &lfd))
2021 break;
2022 pfr = fr;
2025 if( !fi ) fi = HeapAlloc(GetProcessHeap(), 0, sizeof(fontInfo));
2027 if( !LFD_InitFontInfo( fi, &lfd, x_pattern[i]) )
2028 goto nextfont;
2030 if( !fr ) /* add new family */
2032 n_ff++;
2033 fr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(fontResource));
2034 if (fr)
2036 fr->resource = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(LFD));
2038 TRACE("family: -%s-%s-\n", lfd.foundry, lfd.family );
2039 fr->resource->foundry = HeapAlloc(GetProcessHeap(), 0, strlen(lfd.foundry)+1);
2040 strcpy( (char *)fr->resource->foundry, lfd.foundry );
2041 fr->resource->family = HeapAlloc(GetProcessHeap(), 0, strlen(lfd.family)+1);
2042 strcpy( (char *)fr->resource->family, lfd.family );
2043 fr->resource->weight = "";
2045 if( pfr ) pfr->next = fr;
2046 else fontList = fr;
2048 else
2049 WARN("Not enough memory for a new font family\n");
2052 /* check if we already have something better than "fi" */
2054 for( pfi = fr->fi, j = 0; pfi && j <= 0; pfi = pfi->next )
2055 if( (j = XFONT_IsSubset( pfi, fi )) < 0 )
2056 pfi->fi_flags |= FI_SUBSET; /* superseded by "fi" */
2057 if( j > 0 ) goto nextfont;
2059 /* add new font instance "fi" to the "fr" font resource */
2061 if( fi->fi_flags & FI_SCALABLE )
2063 LFD lfd1;
2064 char pxl_string[4], res_string[4];
2065 /* set scalable font height to get a basis for extrapolation */
2067 fi->lfd_height = DEF_SCALABLE_HEIGHT;
2068 fi->lfd_resolution = res;
2070 sprintf(pxl_string, "%d", fi->lfd_height);
2071 sprintf(res_string, "%d", fi->lfd_resolution);
2073 lfd1 = lfd;
2074 lfd1.pixel_size = pxl_string;
2075 lfd1.point_size = "*";
2076 lfd1.resolution_x = res_string;
2077 lfd1.resolution_y = res_string;
2079 LFD_UnParse(buffer, sizeof(buffer), &lfd1);
2081 lpstr = buffer;
2083 else lpstr = x_pattern[i];
2085 /* X11 may return an error on some bad fonts... So be prepared to handle these. */
2086 if ((x_fs = safe_XLoadQueryFont(gdi_display, lpstr)) != 0)
2088 XFONT_SetFontMetric( fi, fr, x_fs );
2089 wine_tsx11_lock();
2090 XFreeFont( gdi_display, x_fs );
2091 wine_tsx11_unlock();
2093 XFONT_FixupPointSize(fi);
2095 TRACE("\t[% 2ipt] '%s'\n", fi->df.dfPoints, x_pattern[i] );
2097 XFONT_CheckFIList( fr, fi, REMOVE_SUBSETS );
2098 fi = NULL; /* preventing reuse */
2100 else
2102 ERR("failed to load %s\n", lpstr );
2104 XFONT_CheckFIList( fr, fi, UNMARK_SUBSETS );
2106 nextfont:
2107 HeapFree(GetProcessHeap(), 0, typeface);
2109 HeapFree(GetProcessHeap(), 0, fi);
2111 /* Scan through the font list and remove FontResource(s) (fr)
2112 * that have no associated Fontinfo(s) (fi).
2113 * This code is necessary because XFONT_ReadCachedMetrics
2114 * assumes that there is at least one fi associated with a fr.
2115 * This assumption is invalid for TT font
2116 * -altsys-ms outlook-medium-r-normal--0-0-0-0-p-0-microsoft-symbol.
2119 fr = fontList;
2121 while (!fr->fi_count)
2123 fontList = fr->next;
2125 HeapFree(GetProcessHeap(), 0, fr->resource);
2126 HeapFree(GetProcessHeap(), 0, fr);
2128 fr = fontList;
2129 n_ff--;
2132 fr = fontList;
2134 while (fr->next)
2136 if (!fr->next->fi_count)
2138 pfr = fr->next;
2139 fr->next = fr->next->next;
2141 HeapFree(GetProcessHeap(), 0, pfr->resource);
2142 HeapFree(GetProcessHeap(), 0, pfr);
2144 n_ff--;
2146 else
2147 fr = fr->next;
2150 MESSAGE("Font metrics: 100.0%% done\n");
2151 return n_ff;
2154 /***********************************************************************
2155 * XFONT_ReadCachedMetrics
2157 * INIT ONLY
2159 static BOOL XFONT_ReadCachedMetrics( int fd, int res, unsigned x_checksum, int x_count )
2161 if( fd >= 0 )
2163 unsigned u;
2164 int i, j;
2166 /* read checksums */
2167 read( fd, &u, sizeof(unsigned) );
2168 read( fd, &i, sizeof(int) );
2170 if( u == x_checksum && i == x_count )
2172 off_t length, offset = 3 * sizeof(int);
2174 /* read total size */
2175 read( fd, &i, sizeof(int) );
2176 length = lseek( fd, 0, SEEK_END );
2178 if( length == (i + offset) )
2180 lseek( fd, offset, SEEK_SET );
2181 fontList = HeapAlloc( GetProcessHeap(), 0, i);
2182 if( fontList )
2184 fontResource* pfr = fontList;
2185 fontInfo* pfi = NULL;
2187 TRACE("Reading cached font metrics:\n");
2189 read( fd, fontList, i); /* read all metrics at once */
2190 while( offset < length )
2192 offset += sizeof(fontResource) + sizeof(fontInfo);
2193 pfr->fi = pfi = (fontInfo*)(pfr + 1);
2194 j = 1;
2195 while( TRUE )
2197 if( offset > length ||
2198 pfi->cptable >= (UINT16)X11DRV_CPTABLE_COUNT ||
2199 PtrToInt(pfi->next) != j++ )
2201 TRACE("error: offset=%ld length=%ld cptable=%d pfi->next=%p j=%d\n",
2202 (long)offset, (long)length, pfi->cptable, pfi->next, j-1);
2203 goto fail;
2206 if( pfi->df.dfPixHeight == 0 )
2208 TRACE("error: dfPixHeight==0\n");
2209 goto fail;
2212 pfi->df.dfFace = pfr->lfFaceName;
2213 if( pfi->fi_flags & FI_SCALABLE )
2215 /* we can pretend we got this font for any resolution */
2216 pfi->lfd_resolution = res;
2217 XFONT_FixupPointSize(pfi);
2219 pfi->next = pfi + 1;
2221 if( j > pfr->fi_count ) break;
2223 pfi = pfi->next;
2224 offset += sizeof(fontInfo);
2226 pfi->next = NULL;
2227 if( pfr->next )
2229 pfr->next = (fontResource*)(pfi + 1);
2230 pfr = pfr->next;
2232 else break;
2234 if( pfr->next == NULL &&
2235 *(int*)(pfi + 1) == X_FMC_MAGIC )
2237 /* read LFD stubs */
2238 char* lpch = (char*)((int*)(pfi + 1) + 1);
2239 offset += sizeof(int);
2240 for( pfr = fontList; pfr; pfr = pfr->next )
2242 size_t len = strlen(lpch) + 1;
2243 TRACE("\t%s, %i instances\n", lpch, pfr->fi_count );
2244 pfr->resource = HeapAlloc(GetProcessHeap(),0,sizeof(LFD));
2245 if (!LFD_Parse(lpch, pfr->resource))
2247 HeapFree( GetProcessHeap(), 0, pfr->resource );
2248 pfr->resource = NULL;
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 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 = IntToPtr(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_GetDefResolution()
2360 * INIT ONLY
2362 * Here we initialize DefResolution which is used in the
2363 * XFONT_Match() penalty function, based on the values of log_pixels
2365 static int XFONT_GetDefResolution( int log_pixels_x, int log_pixels_y )
2367 int i, j, num = 3;
2368 int allowed_xfont_resolutions[3] = { 72, 75, 100 };
2369 int best = 0, best_diff = 65536;
2371 /* FIXME We can only really guess at a best DefResolution
2372 * - this should be configurable
2374 for( i = best = 0; i < num; i++ )
2376 j = abs( log_pixels_x - allowed_xfont_resolutions[i] );
2377 if( j < best_diff )
2379 best = i;
2380 best_diff = j;
2383 DefResolution = allowed_xfont_resolutions[best];
2384 return DefResolution;
2388 /***********************************************************************
2389 * XFONT_Match
2391 * Compute the matching score between the logical font and the device font.
2393 * contributions from highest to lowest:
2394 * charset
2395 * fixed pitch
2396 * height
2397 * family flags (only when the facename is not present)
2398 * width
2399 * weight, italics, underlines, strikeouts
2401 * NOTE: you can experiment with different penalty weights to see what happens.
2403 static UINT XFONT_Match( fontMatch* pfm )
2405 fontInfo* pfi = pfm->pfi; /* device font to match */
2406 LPLOGFONT16 plf = pfm->plf; /* wanted logical font */
2407 UINT penalty = 0;
2408 BOOL bR6 = pfm->flags & FO_MATCH_XYINDEP; /* from text_caps */
2409 BOOL bScale = pfi->fi_flags & FI_SCALABLE;
2410 int d = 0, height;
2412 TRACE("\t[ %-2ipt h=%-3i w=%-3i %s%s]\n", pfi->df.dfPoints,
2413 pfi->df.dfPixHeight, pfi->df.dfAvgWidth,
2414 (pfi->df.dfWeight > FW_NORMAL) ? "Bold " : "Normal ",
2415 (pfi->df.dfItalic) ? "Italic" : "" );
2417 pfm->flags &= FO_MATCH_MASK;
2419 /* Charset */
2420 /* pfm->internal_charset: given(required) charset */
2421 /* pfi->internal_charset: charset of this font */
2422 if (pfi->internal_charset == DEFAULT_CHARSET)
2424 /* special case(unicode font) */
2425 /* priority: unmatched charset < unicode < matched charset */
2426 penalty += 0x50;
2428 else
2430 if( pfm->internal_charset == DEFAULT_CHARSET )
2433 if (pfi->internal_charset != ANSI_CHARSET)
2434 penalty += 0x200;
2436 if ( pfi->codepage != GetACP() )
2437 penalty += 0x200;
2439 else if (pfm->internal_charset != pfi->internal_charset)
2441 if ( pfi->internal_charset & 0xff00 )
2442 penalty += 0x1000; /* internal charset - should not be used */
2443 else
2444 penalty += 0x200;
2448 /* Height */
2449 height = -1;
2451 if( plf->lfHeight > 0 )
2453 int h = pfi->df.dfPixHeight;
2454 d = h - plf->lfHeight;
2455 height = plf->lfHeight;
2457 else
2459 int h = pfi->df.dfPixHeight - pfi->df.dfInternalLeading;
2460 if (h)
2462 d = h + plf->lfHeight;
2463 height = (-plf->lfHeight * pfi->df.dfPixHeight) / h;
2465 else
2467 ERR("PixHeight == InternalLeading\n");
2468 penalty += 0x1000; /* don't want this */
2473 if( height == 0 )
2474 pfm->height = 1; /* Very small */
2475 else if( d )
2477 if( bScale )
2478 pfm->height = height;
2479 else if( (plf->lfQuality != PROOF_QUALITY) && bR6 )
2481 if( d > 0 ) /* do not shrink raster fonts */
2483 pfm->height = pfi->df.dfPixHeight;
2484 penalty += (pfi->df.dfPixHeight - height) * 0x4;
2486 else /* expand only in integer multiples */
2488 pfm->height = height - height%pfi->df.dfPixHeight;
2489 penalty += (height - pfm->height + 1) * height / pfi->df.dfPixHeight;
2492 else /* can't be scaled at all */
2494 if( plf->lfQuality != PROOF_QUALITY) pfm->flags |= FO_SYNTH_HEIGHT;
2495 pfm->height = pfi->df.dfPixHeight;
2496 penalty += (d > 0)? d * 0x8 : -d * 0x10;
2499 else
2500 pfm->height = pfi->df.dfPixHeight;
2502 /* Pitch and Family */
2503 if( pfm->flags & FO_MATCH_PAF ) {
2504 int family = plf->lfPitchAndFamily & FF_FAMILY;
2506 /* TMPF_FIXED_PITCH means exactly the opposite */
2507 if( plf->lfPitchAndFamily & FIXED_PITCH ) {
2508 if( pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH ) penalty += 0x100;
2509 } else /* Variable is the default */
2510 if( !(pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH) ) penalty += 0x2;
2512 if (family != FF_DONTCARE && family != (pfi->df.dfPitchAndFamily & FF_FAMILY) )
2513 penalty += 0x10;
2516 /* Width */
2517 if( plf->lfWidth )
2519 int h;
2520 if( bR6 || bScale ) h = 0;
2521 else
2523 /* FIXME: not complete */
2525 pfm->flags |= FO_SYNTH_WIDTH;
2526 h = abs(plf->lfWidth - (pfm->height * pfi->df.dfAvgWidth)/pfi->df.dfPixHeight);
2528 penalty += h * ( d ) ? 0x2 : 0x1 ;
2530 else if( !(pfi->fi_flags & FI_NORMAL) ) penalty++;
2532 /* Weight */
2533 if( plf->lfWeight != FW_DONTCARE )
2535 penalty += abs(plf->lfWeight - pfi->df.dfWeight) / 40;
2536 if( plf->lfWeight > pfi->df.dfWeight ) pfm->flags |= FO_SYNTH_BOLD;
2537 } else if( pfi->df.dfWeight >= FW_BOLD ) penalty++; /* choose normal by default */
2539 /* Italic */
2540 if( plf->lfItalic != pfi->df.dfItalic )
2542 penalty += 0x4;
2543 pfm->flags |= FO_SYNTH_ITALIC;
2545 /* Underline */
2546 if( plf->lfUnderline ) pfm->flags |= FO_SYNTH_UNDERLINE;
2548 /* Strikeout */
2549 if( plf->lfStrikeOut ) pfm->flags |= FO_SYNTH_STRIKEOUT;
2552 if( penalty && !bScale && pfi->lfd_resolution != DefResolution )
2553 penalty++;
2555 TRACE(" returning %i\n", penalty );
2557 return penalty;
2560 /***********************************************************************
2561 * XFONT_MatchFIList
2563 * Scan a particular font resource for the best match.
2565 static UINT XFONT_MatchFIList( fontMatch* pfm )
2567 BOOL skipRaster = (pfm->flags & FO_MATCH_NORASTER);
2568 UINT current_score, score = (UINT)(-1);
2569 fontMatch fm = *pfm;
2571 for( fm.pfi = pfm->pfr->fi; fm.pfi && score; fm.pfi = fm.pfi->next)
2573 if( skipRaster && !(fm.pfi->fi_flags & FI_SCALABLE) )
2574 continue;
2576 current_score = XFONT_Match( &fm );
2577 if( score > current_score )
2579 *pfm = fm;
2580 score = current_score;
2583 return score;
2586 /***********************************************************************
2587 * XFONT_is_ansi_charset
2589 * returns TRUE if the given charset is ANSI_CHARSET.
2591 static BOOL XFONT_is_ansi_charset( UINT charset )
2593 return ((charset == ANSI_CHARSET) ||
2594 (charset == DEFAULT_CHARSET && GetACP() == 1252));
2597 /***********************************************************************
2598 * XFONT_MatchDeviceFont
2600 * Scan font resource tree.
2603 static void XFONT_MatchDeviceFont( fontResource* start, fontMatch* pfm)
2605 fontMatch fm = *pfm;
2606 UINT current_score, score = (UINT)(-1);
2607 fontResource** ppfr;
2609 TRACE("(%u) '%s' h=%i weight=%i %s\n",
2610 pfm->plf->lfCharSet, pfm->plf->lfFaceName, pfm->plf->lfHeight,
2611 pfm->plf->lfWeight, (pfm->plf->lfItalic) ? "Italic" : "" );
2613 pfm->pfi = NULL;
2615 /* the following hard-coded font binding assumes 'ANSI_CHARSET'. */
2616 if( !fm.plf->lfFaceName[0] &&
2617 XFONT_is_ansi_charset(fm.plf->lfCharSet) )
2619 switch(fm.plf->lfPitchAndFamily & 0xf0)
2621 case FF_MODERN:
2622 strcpy(fm.plf->lfFaceName, "Courier New");
2623 break;
2624 case FF_ROMAN:
2625 strcpy(fm.plf->lfFaceName, "Times New Roman");
2626 break;
2627 case FF_SWISS:
2628 strcpy(fm.plf->lfFaceName, "Arial");
2629 break;
2630 default:
2631 if((fm.plf->lfPitchAndFamily & 0x0f) == FIXED_PITCH)
2632 strcpy(fm.plf->lfFaceName, "Courier New");
2633 else
2634 strcpy(fm.plf->lfFaceName, "Arial");
2635 break;
2639 if( fm.plf->lfFaceName[0] )
2641 fm.pfr = XFONT_FindFIList( start, fm.plf->lfFaceName);
2642 if( fm.pfr ) /* match family */
2644 TRACE("found facename '%s'\n", fm.pfr->lfFaceName );
2646 if( fm.pfr->fr_flags & FR_REMOVED )
2647 fm.pfr = 0;
2648 else
2650 XFONT_MatchFIList( &fm );
2651 *pfm = fm;
2652 if (pfm->pfi)
2653 return;
2657 /* get charset if lfFaceName is one of known facenames. */
2659 const struct CharsetBindingInfo* pcharsetbindings;
2661 pcharsetbindings = &charsetbindings[0];
2662 while ( pcharsetbindings->pszFaceName != NULL )
2664 if ( !strcmp( pcharsetbindings->pszFaceName,
2665 fm.plf->lfFaceName ) )
2667 fm.internal_charset = pcharsetbindings->charset;
2668 break;
2670 pcharsetbindings ++;
2672 TRACE( "%s charset %u\n", fm.plf->lfFaceName, fm.internal_charset );
2676 /* match all available fonts */
2678 fm.flags |= FO_MATCH_PAF;
2679 for( ppfr = &fontList; *ppfr && score; ppfr = &(*ppfr)->next )
2681 if( (*ppfr)->fr_flags & FR_REMOVED )
2683 if( (*ppfr)->fo_count == 0 )
2684 XFONT_RemoveFontResource( ppfr );
2685 continue;
2688 fm.pfr = *ppfr;
2690 TRACE("%s\n", fm.pfr->lfFaceName );
2692 current_score = XFONT_MatchFIList( &fm );
2693 if( current_score < score )
2695 score = current_score;
2696 *pfm = fm;
2702 /***********************************************************************
2703 * X Font Cache
2705 static void XFONT_GrowFreeList(int start, int end)
2707 /* add all entries from 'start' up to and including 'end' */
2709 memset( fontCache + start, 0, (end - start + 1) * sizeof(fontObject) );
2711 fontCache[end].lru = fontLF;
2712 fontCache[end].count = -1;
2713 fontLF = start;
2714 while( start < end )
2716 fontCache[start].count = -1;
2717 fontCache[start].lru = start + 1;
2718 start++;
2722 static fontObject* XFONT_LookupCachedFont( const LOGFONT16 *plf, UINT16* checksum )
2724 UINT16 cs = __lfCheckSum( plf );
2725 int i = fontMRU, prev = -1;
2727 *checksum = cs;
2728 while( i >= 0 )
2730 if( fontCache[i].lfchecksum == cs &&
2731 !(fontCache[i].fo_flags & FO_REMOVED) )
2733 /* FIXME: something more intelligent here ? */
2735 if( !memcmp( plf, &fontCache[i].lf,
2736 sizeof(LOGFONT16) - LF_FACESIZE ) &&
2737 !strcmp( plf->lfFaceName, fontCache[i].lf.lfFaceName) )
2739 /* remove temporarily from the lru list */
2740 if( prev >= 0 )
2741 fontCache[prev].lru = fontCache[i].lru;
2742 else
2743 fontMRU = (INT16)fontCache[i].lru;
2744 return (fontCache + i);
2747 prev = i;
2748 i = (INT16)fontCache[i].lru;
2750 return NULL;
2753 static fontObject* XFONT_GetCacheEntry(void)
2755 int i;
2757 if( fontLF == -1 )
2759 int prev_i, prev_j, j;
2761 TRACE("font cache is full\n");
2763 /* lookup the least recently used font */
2765 for( prev_i = prev_j = j = -1, i = fontMRU; i >= 0; i = (INT16)fontCache[i].lru )
2767 if( fontCache[i].count <= 0 &&
2768 !(fontCache[i].fo_flags & FO_SYSTEM) )
2770 prev_j = prev_i;
2771 j = i;
2773 prev_i = i;
2776 if( j >= 0 ) /* unload font */
2778 /* detach from the lru list */
2780 TRACE("\tfreeing entry %i\n", j );
2782 fontCache[j].fr->fo_count--;
2784 if( prev_j >= 0 )
2785 fontCache[prev_j].lru = fontCache[j].lru;
2786 else fontMRU = (INT16)fontCache[j].lru;
2788 /* FIXME: lpXForm, lpPixmap */
2789 HeapFree( GetProcessHeap(), 0, fontCache[j].lpX11Trans );
2791 wine_tsx11_lock();
2792 XFreeFont( gdi_display, fontCache[j].fs );
2793 wine_tsx11_unlock();
2795 memset( fontCache + j, 0, sizeof(fontObject) );
2796 return (fontCache + j);
2798 else /* expand cache */
2800 fontObject* newCache;
2802 prev_i = fontCacheSize + FONTCACHE;
2804 TRACE("\tgrowing font cache from %i to %i\n", fontCacheSize, prev_i );
2806 if( (newCache = HeapReAlloc(GetProcessHeap(), 0, fontCache, prev_i * sizeof(fontObject))) )
2808 i = fontCacheSize;
2809 fontCacheSize = prev_i;
2810 fontCache = newCache;
2811 XFONT_GrowFreeList( i, fontCacheSize - 1);
2813 else return NULL;
2817 /* detach from the free list */
2819 i = fontLF;
2820 fontLF = (INT16)fontCache[i].lru;
2821 fontCache[i].count = 0;
2822 return (fontCache + i);
2825 static int XFONT_ReleaseCacheEntry(const fontObject* pfo)
2827 UINT u = (UINT)(pfo - fontCache);
2828 int i;
2829 int ret;
2831 if( u < fontCacheSize )
2833 ret = --fontCache[u].count;
2834 if ( ret == 0 )
2836 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
2838 if( CHECK_PFONT(pfo->prefobjs[i]) )
2839 XFONT_ReleaseCacheEntry(__PFONT(pfo->prefobjs[i]));
2843 return ret;
2846 return -1;
2849 /***********************************************************************
2850 * X11DRV_FONT_InitX11Metrics
2852 * Initialize font resource list and allocate font cache.
2854 static void X11DRV_FONT_InitX11Metrics( void )
2856 char** x_pattern;
2857 unsigned x_checksum;
2858 int i, x_count, fd, buf_size;
2859 char *buffer;
2860 HKEY hkey;
2863 wine_tsx11_lock();
2864 x_pattern = XListFonts(gdi_display, "*", MAX_FONTS, &x_count );
2865 wine_tsx11_unlock();
2867 TRACE("Font Mapper: initializing %i x11 fonts\n", x_count);
2868 if (x_count == MAX_FONTS)
2869 MESSAGE("There may be more fonts available - try increasing the value of MAX_FONTS\n");
2871 for( i = x_checksum = 0; i < x_count; i++ )
2873 int j;
2874 #if 0
2875 printf("%i\t: %s\n", i, x_pattern[i] );
2876 #endif
2878 j = strlen( x_pattern[i] );
2879 if( j ) x_checksum ^= __genericCheckSum( x_pattern[i], j );
2881 x_checksum |= X_PFONT_MAGIC;
2882 buf_size = 128;
2883 buffer = HeapAlloc( GetProcessHeap(), 0, buf_size );
2885 /* deal with systemwide font metrics cache */
2887 buffer[0] = 0;
2888 /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver\Fonts */
2889 if (RegOpenKeyA(HKEY_CURRENT_USER, INIFontSection, &hkey)) hkey = 0;
2890 if (hkey)
2892 DWORD type, count = buf_size;
2893 RegQueryValueExA(hkey, INIGlobalMetrics, 0, &type, (LPBYTE)buffer, &count);
2896 if( buffer[0] )
2898 fd = open( buffer, O_RDONLY );
2899 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2901 if (fontList == NULL)
2903 /* try per-user */
2904 buffer = XFONT_UserMetricsCache( buffer, &buf_size );
2905 if( buffer[0] )
2907 fd = open( buffer, O_RDONLY );
2908 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2912 if( fontList == NULL ) /* build metrics from scratch */
2914 int n_ff = XFONT_BuildMetrics(x_pattern, DefResolution, x_checksum, x_count);
2915 if( buffer[0] ) /* update cached metrics */
2917 fd = open( buffer, O_CREAT | O_TRUNC | O_RDWR, 0644 ); /* -rw-r--r-- */
2918 if( XFONT_WriteCachedMetrics( fd, x_checksum, x_count, n_ff ) == FALSE )
2920 WARN("Unable to write to fontcache '%s'\n", buffer);
2921 if( fd >= 0) remove( buffer ); /* couldn't write entire file */
2926 wine_tsx11_lock();
2927 XFreeFontNames(x_pattern);
2929 /* check if we're dealing with X11 R6 server */
2931 XFontStruct* x_fs;
2932 strcpy(buffer, "-*-*-*-*-normal-*-[12 0 0 12]-*-72-*-*-*-iso8859-1");
2933 if( (x_fs = safe_XLoadQueryFont(gdi_display, buffer)) )
2935 text_caps |= TC_SF_X_YINDEP;
2936 XFreeFont(gdi_display, x_fs);
2939 wine_tsx11_unlock();
2941 HeapFree(GetProcessHeap(), 0, buffer);
2943 XFONT_WindowsNames();
2944 XFONT_LoadAliases( hkey );
2945 if (hkey) XFONT_LoadDefaults( hkey );
2946 XFONT_LoadIgnores( hkey );
2948 /* fontList initialization is over, allocate X font cache */
2950 fontCache = HeapAlloc(GetProcessHeap(), 0, fontCacheSize * sizeof(fontObject));
2951 XFONT_GrowFreeList(0, fontCacheSize - 1);
2953 TRACE("done!\n");
2954 if (hkey) RegCloseKey(hkey);
2957 /***********************************************************************
2958 * X11DRV_FONT_Init
2960 void X11DRV_FONT_Init( int log_pixels_x, int log_pixels_y )
2962 XFONT_GetDefResolution( log_pixels_x, log_pixels_y );
2964 if(using_client_side_fonts)
2965 text_caps |= TC_VA_ABLE;
2967 return;
2970 /**********************************************************************
2971 * XFONT_SetX11Trans
2973 static BOOL XFONT_SetX11Trans( fontObject *pfo )
2975 char *fontName;
2976 Atom nameAtom;
2977 LFD lfd;
2979 wine_tsx11_lock();
2980 XGetFontProperty( pfo->fs, XA_FONT, &nameAtom );
2981 fontName = XGetAtomName( gdi_display, nameAtom );
2982 if (!LFD_Parse(fontName, &lfd) || lfd.pixel_size[0] != '[')
2984 XFree(fontName);
2985 wine_tsx11_unlock();
2986 return FALSE;
2988 #define PX pfo->lpX11Trans
2990 sscanf(lfd.pixel_size, "[%f%f%f%f]", &PX->a, &PX->b, &PX->c, &PX->d);
2991 XFree(fontName);
2993 XGetFontProperty( pfo->fs, x11drv_atom(RAW_ASCENT), &PX->RAW_ASCENT );
2994 XGetFontProperty( pfo->fs, x11drv_atom(RAW_DESCENT), &PX->RAW_DESCENT );
2995 wine_tsx11_unlock();
2997 PX->pixelsize = hypot(PX->a, PX->b);
2998 PX->ascent = PX->pixelsize / 1000.0 * PX->RAW_ASCENT;
2999 PX->descent = PX->pixelsize / 1000.0 * PX->RAW_DESCENT;
3001 TRACE("[%f %f %f %f] RA = %ld RD = %ld\n",
3002 PX->a, PX->b, PX->c, PX->d,
3003 PX->RAW_ASCENT, PX->RAW_DESCENT);
3005 #undef PX
3006 return TRUE;
3009 /***********************************************************************
3010 * X Device Font Objects
3012 static X_PHYSFONT XFONT_RealizeFont( LPLOGFONT16 plf,
3013 LPCSTR* faceMatched, BOOL bSubFont,
3014 WORD internal_charset,
3015 WORD* pcharsetMatched )
3017 UINT16 checksum;
3018 INT index = 0;
3019 fontObject* pfo;
3021 pfo = XFONT_LookupCachedFont( plf, &checksum );
3022 if( !pfo )
3024 fontMatch fm;
3025 INT i;
3027 fm.pfr = NULL;
3028 fm.pfi = NULL;
3029 fm.height = 0;
3030 fm.flags = 0;
3031 fm.plf = plf;
3032 fm.internal_charset = internal_charset;
3034 if( text_caps & TC_SF_X_YINDEP ) fm.flags = FO_MATCH_XYINDEP;
3036 /* allocate new font cache entry */
3038 if( (pfo = XFONT_GetCacheEntry()) )
3040 /* initialize entry and load font */
3041 char lpLFD[MAX_LFD_LENGTH];
3042 UINT uRelaxLevel = 0;
3044 if(abs(plf->lfHeight) > MAX_FONT_SIZE) {
3045 ERR(
3046 "plf->lfHeight = %d, Creating a 100 pixel font and rescaling metrics\n",
3047 plf->lfHeight);
3048 pfo->rescale = fabs(plf->lfHeight / 100.0);
3049 if(plf->lfHeight > 0) plf->lfHeight = 100;
3050 else plf->lfHeight = -100;
3051 } else
3052 pfo->rescale = 1.0;
3054 XFONT_MatchDeviceFont( fontList, &fm );
3055 pfo->fr = fm.pfr;
3056 pfo->fi = fm.pfi;
3057 pfo->fr->fo_count++;
3058 pfo->fo_flags = fm.flags & ~FO_MATCH_MASK;
3060 pfo->lf = *plf;
3061 pfo->lfchecksum = checksum;
3065 LFD_ComposeLFD( pfo, fm.height, lpLFD, uRelaxLevel++ );
3066 if( (pfo->fs = safe_XLoadQueryFont( gdi_display, lpLFD )) ) break;
3067 } while( uRelaxLevel );
3070 if(pfo->lf.lfEscapement != 0) {
3071 pfo->lpX11Trans = HeapAlloc(GetProcessHeap(), 0, sizeof(XFONTTRANS));
3072 if(!XFONT_SetX11Trans( pfo )) {
3073 HeapFree(GetProcessHeap(), 0, pfo->lpX11Trans);
3074 pfo->lpX11Trans = NULL;
3077 XFONT_GetLeading( &pfo->fi->df, pfo->fs,
3078 &pfo->foInternalLeading, NULL, pfo->lpX11Trans );
3079 pfo->foAvgCharWidth = (INT16)XFONT_GetAvgCharWidth(&pfo->fi->df, pfo->fs, pfo->lpX11Trans );
3080 pfo->foMaxCharWidth = (INT16)XFONT_GetMaxCharWidth(pfo->fs, pfo->lpX11Trans);
3082 /* FIXME: If we've got a soft font or
3083 * there are FO_SYNTH_... flags for the
3084 * non PROOF_QUALITY request, the engine
3085 * should rasterize characters into mono
3086 * pixmaps and store them in the pfo->lpPixmap
3087 * array (pfo->fs should be updated as well).
3088 * array (pfo->fs should be updated as well).
3089 * X11DRV_ExtTextOut() must be heavily modified
3090 * to support pixmap blitting and FO_SYNTH_...
3091 * styles.
3094 pfo->lpPixmap = NULL;
3096 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3097 pfo->prefobjs[i] = 0xffffffff; /* invalid value */
3099 /* special treatment for DBCS that needs multiple fonts */
3100 /* All member of pfo must be set correctly. */
3101 if ( bSubFont == FALSE )
3103 WORD charset_sub;
3104 WORD charsetMatchedSub;
3105 LOGFONT16 lfSub;
3106 LPCSTR faceMatchedSub;
3108 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3110 charset_sub = X11DRV_cptable[pfo->fi->cptable].
3111 penum_subfont_charset( i );
3112 if ( charset_sub == DEFAULT_CHARSET ) break;
3114 lfSub = *plf;
3115 lfSub.lfWidth = 0;
3116 lfSub.lfHeight=plf->lfHeight;
3117 lfSub.lfCharSet = (BYTE)(charset_sub & 0xff);
3118 lfSub.lfFaceName[0] = '\0'; /* FIXME? */
3119 /* this font has sub font */
3120 if ( i == 0 ) pfo->prefobjs[0] = 0;
3121 pfo->prefobjs[i] =
3122 XFONT_RealizeFont( &lfSub, &faceMatchedSub,
3123 TRUE, charset_sub,
3124 &charsetMatchedSub );
3125 /* FIXME: check charsetMatchedSub */
3130 if( !pfo ) /* couldn't get a new entry, get one of the cached fonts */
3132 UINT current_score, score = (UINT)(-1);
3134 i = index = fontMRU;
3135 fm.flags |= FO_MATCH_PAF;
3138 pfo = fontCache + i;
3139 fm.pfr = pfo->fr; fm.pfi = pfo->fi;
3141 current_score = XFONT_Match( &fm );
3142 if( current_score < score ) index = i;
3144 i = pfo->lru;
3145 } while( i >= 0 );
3146 pfo = fontCache + index;
3147 goto END;
3151 /* attach at the head of the lru list */
3152 pfo->lru = fontMRU;
3153 index = fontMRU = (pfo - fontCache);
3155 END:
3156 pfo->count++;
3158 TRACE("physfont %i\n", index);
3159 *faceMatched = pfo->fi->df.dfFace;
3160 *pcharsetMatched = pfo->fi->internal_charset;
3162 return X_PFONT_MAGIC | index;
3165 /***********************************************************************
3166 * XFONT_GetFontObject
3168 fontObject* XFONT_GetFontObject( X_PHYSFONT pFont )
3170 if( CHECK_PFONT(pFont) ) return __PFONT(pFont);
3171 return NULL;
3174 /***********************************************************************
3175 * XFONT_GetFontStruct
3177 XFontStruct* XFONT_GetFontStruct( X_PHYSFONT pFont )
3179 if( CHECK_PFONT(pFont) ) return __PFONT(pFont)->fs;
3180 return NULL;
3185 /* X11DRV Interface ****************************************************
3187 * Exposed via the dc->funcs dispatch table. *
3189 ***********************************************************************/
3190 /***********************************************************************
3191 * SelectFont (X11DRV.@)
3193 HFONT X11DRV_SelectFont( X11DRV_PDEVICE *physDev, HFONT hfont, HANDLE gdiFont )
3195 LOGFONTW logfont;
3196 LOGFONT16 lf;
3198 TRACE("hdc=%p, hfont=%p\n", physDev->hdc, hfont);
3200 if (!GetObjectW( hfont, sizeof(logfont), &logfont )) return HGDI_ERROR;
3202 TRACE("gdiFont = %p\n", gdiFont);
3204 if(gdiFont && using_client_side_fonts) {
3205 X11DRV_XRender_SelectFont(physDev, hfont);
3206 physDev->has_gdi_font = TRUE;
3207 return FALSE;
3210 EnterCriticalSection( &crtsc_fonts_X11 );
3212 if(fontList == NULL) X11DRV_FONT_InitX11Metrics();
3214 if( CHECK_PFONT(physDev->font) )
3215 XFONT_ReleaseCacheEntry( __PFONT(physDev->font) );
3217 FONT_LogFontWTo16(&logfont, &lf);
3219 /* stock fonts ignore the mapping mode */
3220 if (!is_stock_font( hfont ))
3222 /* Make sure we don't change the sign when converting to device coords */
3223 /* FIXME - check that the other drivers do this correctly */
3224 if (lf.lfWidth)
3226 INT width = X11DRV_XWStoDS( physDev, lf.lfWidth );
3227 lf.lfWidth = (lf.lfWidth < 0) ? -abs(width) : abs(width);
3228 if (lf.lfWidth == 0)
3229 lf.lfWidth = 1; /* Minimum width */
3231 if (lf.lfHeight)
3233 INT height = X11DRV_YWStoDS( physDev, lf.lfHeight );
3234 lf.lfHeight = (lf.lfHeight < 0) ? -abs(height) : abs(height);
3235 if (lf.lfHeight == 0)
3236 lf.lfHeight = MIN_FONT_SIZE;
3240 if (!lf.lfHeight)
3241 lf.lfHeight = -(DEF_POINT_SIZE * GetDeviceCaps(physDev->hdc,LOGPIXELSY) + (72>>1)) / 72;
3244 /* Fixup aliases before passing to RealizeFont */
3245 /* alias = Windows name in the alias table */
3246 LPCSTR alias = XFONT_UnAlias( lf.lfFaceName );
3247 LPCSTR faceMatched;
3248 WORD charsetMatched;
3250 TRACE("hfont=%p\n", hfont); /* to connect with the trace from RealizeFont */
3251 physDev->font = XFONT_RealizeFont( &lf, &faceMatched,
3252 FALSE, lf.lfCharSet,
3253 &charsetMatched );
3255 /* set face to the requested facename if it matched
3256 * so that GetTextFace can get the correct face name
3258 if (alias && !strcmp(faceMatched, lf.lfFaceName))
3259 MultiByteToWideChar(CP_ACP, 0, alias, -1,
3260 logfont.lfFaceName, LF_FACESIZE);
3261 else
3262 MultiByteToWideChar(CP_ACP, 0, faceMatched, -1,
3263 logfont.lfFaceName, LF_FACESIZE);
3266 * In X, some encodings may have the same lfFaceName.
3267 * for example:
3268 * -misc-fixed-*-iso8859-1
3269 * -misc-fixed-*-jisx0208.1990-0
3270 * so charset should be saved...
3272 logfont.lfCharSet = charsetMatched;
3275 LeaveCriticalSection( &crtsc_fonts_X11 );
3277 physDev->has_gdi_font = FALSE;
3278 return (HFONT)1; /* Use a device font */
3282 /***********************************************************************
3284 * X11DRV_EnumDeviceFonts
3286 BOOL X11DRV_EnumDeviceFonts( X11DRV_PDEVICE *physDev, LPLOGFONTW plf,
3287 FONTENUMPROCW proc, LPARAM lp )
3289 ENUMLOGFONTEXW lf;
3290 NEWTEXTMETRICEXW tm;
3291 fontResource* pfr = fontList;
3292 BOOL b, bRet = 0;
3293 LOGFONTW lfW;
3295 /* don't enumerate x11 fonts if we're using client side fonts */
3296 if (physDev->has_gdi_font) return FALSE;
3298 if (!plf)
3300 lfW.lfCharSet = DEFAULT_CHARSET;
3301 lfW.lfPitchAndFamily = 0;
3302 lfW.lfFaceName[0] = 0;
3303 plf = &lfW;
3306 if( plf->lfFaceName[0] )
3308 char facename[LF_FACESIZE+1];
3309 WideCharToMultiByte( CP_ACP, 0, plf->lfFaceName, -1,
3310 facename, sizeof(facename), NULL, NULL );
3311 /* enum all entries in this resource */
3312 pfr = XFONT_FindFIList( pfr, facename );
3313 if( pfr )
3315 fontInfo* pfi;
3316 for( pfi = pfr->fi; pfi; pfi = pfi->next )
3318 /* Note: XFONT_GetFontMetric() will have to
3319 release the crit section, font list will
3320 have to be retraversed on return */
3322 if(plf->lfCharSet == DEFAULT_CHARSET ||
3323 plf->lfCharSet == pfi->df.dfCharSet) {
3324 if( (b = (*proc)( &lf.elfLogFont, (TEXTMETRICW *)&tm,
3325 XFONT_GetFontMetric( pfi, &lf, &tm ), lp )) )
3326 bRet = b;
3327 else break;
3332 else /* enum first entry in each resource */
3333 for( ; pfr ; pfr = pfr->next )
3335 if(pfr->fi)
3337 if( (b = (*proc)( &lf.elfLogFont, (TEXTMETRICW *)&tm,
3338 XFONT_GetFontMetric( pfr->fi, &lf, &tm ), lp )) )
3339 bRet = b;
3340 else break;
3343 return bRet;
3347 /***********************************************************************
3348 * X11DRV_GetTextMetrics
3350 BOOL X11DRV_GetTextMetrics(X11DRV_PDEVICE *physDev, TEXTMETRICW *metrics)
3352 if( CHECK_PFONT(physDev->font) )
3354 fontObject* pfo = __PFONT(physDev->font);
3355 X11DRV_cptable[pfo->fi->cptable].pGetTextMetricsW( pfo, metrics );
3356 return TRUE;
3358 return FALSE;
3362 /***********************************************************************
3363 * X11DRV_GetCharWidth
3365 BOOL X11DRV_GetCharWidth( X11DRV_PDEVICE *physDev, UINT firstChar, UINT lastChar,
3366 LPINT buffer )
3368 fontObject* pfo = XFONT_GetFontObject( physDev->font );
3370 if( pfo )
3372 unsigned int i;
3374 if (pfo->fs->per_char == NULL)
3375 for (i = firstChar; i <= lastChar; i++)
3376 if(pfo->lpX11Trans)
3377 *buffer++ = pfo->fs->min_bounds.attributes *
3378 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3379 else
3380 *buffer++ = pfo->fs->min_bounds.width * pfo->rescale;
3381 else
3383 XCharStruct *cs, *def;
3384 static XCharStruct __null_char = { 0, 0, 0, 0, 0, 0 };
3386 CI_GET_CHAR_INFO(pfo->fs, pfo->fs->default_char, &__null_char,
3387 def);
3389 for (i = firstChar; i <= lastChar; i++)
3391 WCHAR wch = i;
3392 BYTE ch;
3393 UINT ch_f; /* character code in the font encoding */
3394 WideCharToMultiByte( pfo->fi->codepage, 0, &wch, 1, (LPSTR)&ch, 1, NULL, NULL );
3395 ch_f = ch;
3396 if (ch_f >= pfo->fs->min_char_or_byte2 &&
3397 ch_f <= pfo->fs->max_char_or_byte2)
3399 cs = &pfo->fs->per_char[(ch_f - pfo->fs->min_char_or_byte2)];
3400 if (CI_NONEXISTCHAR(cs)) cs = def;
3401 } else cs = def;
3402 if(pfo->lpX11Trans)
3403 *buffer++ = max(cs->attributes, 0) *
3404 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3405 else
3406 *buffer++ = max(cs->width, 0 ) * pfo->rescale;
3410 return TRUE;
3412 return FALSE;