push 583922ece91f6a3e6a32c772f3574cd16e6257fa
[wine/hacks.git] / dlls / winex11.drv / xfont.c
blob0ef18fc86aa85ac20652938a17942fdc042927d5
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 { "MS Song", GB2312_CHARSET },
312 { "MS Hei", GB2312_CHARSET },
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 eg "-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 * font info - http://www.microsoft.com/kb/articles/q65/1/23.htm
1034 * Windows font metrics - http://www.microsoft.com/kb/articles/q32/6/67.htm
1036 static void XFONT_GetLeading( const IFONTINFO16 *pFI, const XFontStruct* x_fs,
1037 INT16* pIL, INT16* pEL, const XFONTTRANS *XFT )
1039 unsigned long height;
1040 unsigned min = (unsigned char)pFI->dfFirstChar;
1041 unsigned max = (unsigned char)pFI->dfLastChar;
1042 BOOL bIsLatin = IS_LATIN_CHARSET(pFI->dfCharSet);
1044 if( pEL ) *pEL = 0;
1046 if(XFT) {
1047 wine_tsx11_lock();
1048 if(XGetFontProperty((XFontStruct*)x_fs, x11drv_atom(RAW_CAP_HEIGHT), &height))
1049 *pIL = XFT->ascent -
1050 (INT)(XFT->pixelsize / 1000.0 * height);
1051 else
1052 *pIL = 0;
1053 wine_tsx11_unlock();
1054 return;
1057 wine_tsx11_lock();
1058 if( XGetFontProperty((XFontStruct*)x_fs, XA_CAP_HEIGHT, &height) == FALSE )
1060 if( x_fs->per_char )
1061 if( bIsLatin && ((unsigned char)'X' <= (max - min)) )
1062 height = x_fs->per_char['X' - min].ascent;
1063 else
1064 if (x_fs->ascent >= x_fs->max_bounds.ascent)
1065 height = x_fs->max_bounds.ascent;
1066 else
1068 height = x_fs->ascent;
1069 if( pEL )
1070 *pEL = x_fs->max_bounds.ascent - height;
1072 else
1073 height = x_fs->min_bounds.ascent;
1075 wine_tsx11_unlock();
1077 *pIL = x_fs->ascent - height;
1080 /***********************************************************************
1081 * XFONT_CharWidth
1083 static int XFONT_CharWidth(const XFontStruct* x_fs,
1084 const XFONTTRANS *XFT, int ch)
1086 if(!XFT)
1087 return x_fs->per_char[ch].width;
1088 else
1089 return x_fs->per_char[ch].attributes * XFT->pixelsize / 1000.0;
1092 /***********************************************************************
1093 * XFONT_GetAvgCharWidth
1095 static INT XFONT_GetAvgCharWidth( LPIFONTINFO16 pFI, const XFontStruct* x_fs,
1096 const XFONTTRANS *XFT)
1098 unsigned min = (unsigned char)pFI->dfFirstChar;
1099 unsigned max = (unsigned char)pFI->dfLastChar;
1101 INT avg;
1103 if( x_fs->per_char )
1105 unsigned int width = 0, chars = 0, j;
1106 if( (IS_LATIN_CHARSET(pFI->dfCharSet) ||
1107 pFI->dfCharSet == DEFAULT_CHARSET) &&
1108 (max - min) >= (unsigned char)'z' )
1110 /* FIXME - should use a weighted average */
1111 for( j = 0; j < 26; j++ )
1112 width += XFONT_CharWidth(x_fs, XFT, 'a' + j - min) +
1113 XFONT_CharWidth(x_fs, XFT, 'A' + j - min);
1114 chars = 52;
1116 else /* unweighted average of everything */
1118 for( j = 0, max -= min; j <= max; j++ )
1119 if( !CI_NONEXISTCHAR(x_fs->per_char + j) )
1121 width += XFONT_CharWidth(x_fs, XFT, j);
1122 chars++;
1125 if (chars) avg = (width + (chars-1))/ chars; /* always round up*/
1126 else avg = 0; /* No characters exist at all */
1128 else /* uniform width */
1129 avg = x_fs->min_bounds.width;
1131 TRACE(" retuning %d\n",avg);
1132 return avg;
1135 /***********************************************************************
1136 * XFONT_GetMaxCharWidth
1138 static INT XFONT_GetMaxCharWidth(const XFontStruct* xfs, const XFONTTRANS *XFT)
1140 unsigned min = (unsigned char)xfs->min_char_or_byte2;
1141 unsigned max = (unsigned char)xfs->max_char_or_byte2;
1142 unsigned int maxwidth, j;
1144 if(!XFT || !xfs->per_char)
1145 return abs(xfs->max_bounds.width);
1147 for( j = 0, maxwidth = 0, max -= min; j <= max; j++ )
1148 if( !CI_NONEXISTCHAR(xfs->per_char + j) )
1149 if(maxwidth < xfs->per_char[j].attributes)
1150 maxwidth = xfs->per_char[j].attributes;
1152 maxwidth *= XFT->pixelsize / 1000.0;
1153 return maxwidth;
1156 /***********************************************************************
1157 * XFONT_SetFontMetric
1159 * INIT ONLY
1161 * Initializes IFONTINFO16.
1163 static void XFONT_SetFontMetric(fontInfo* fi, const fontResource* fr, XFontStruct* xfs)
1165 unsigned min, max;
1166 fi->df.dfFirstChar = (BYTE)(min = xfs->min_char_or_byte2);
1167 fi->df.dfLastChar = (BYTE)(max = xfs->max_char_or_byte2);
1169 fi->df.dfDefaultChar = (BYTE)xfs->default_char;
1170 fi->df.dfBreakChar = (BYTE)(( ' ' < min || ' ' > max) ? xfs->default_char: ' ');
1172 fi->df.dfPixHeight = (INT16)((fi->df.dfAscent = (INT16)xfs->ascent) + xfs->descent);
1173 fi->df.dfPixWidth = (xfs->per_char) ? 0 : xfs->min_bounds.width;
1175 XFONT_GetLeading( &fi->df, xfs, &fi->df.dfInternalLeading, &fi->df.dfExternalLeading, NULL );
1176 fi->df.dfAvgWidth = (INT16)XFONT_GetAvgCharWidth(&fi->df, xfs, NULL );
1177 fi->df.dfMaxWidth = (INT16)XFONT_GetMaxCharWidth(xfs, NULL);
1179 if( xfs->min_bounds.width != xfs->max_bounds.width )
1180 fi->df.dfPitchAndFamily |= TMPF_FIXED_PITCH; /* au contraire! */
1181 if( fi->fi_flags & FI_SCALABLE )
1183 fi->df.dfType = DEVICE_FONTTYPE;
1184 fi->df.dfPitchAndFamily |= TMPF_DEVICE;
1186 else if( fi->fi_flags & FI_TRUETYPE )
1187 fi->df.dfType = TRUETYPE_FONTTYPE;
1188 else
1189 fi->df.dfType = RASTER_FONTTYPE;
1191 fi->df.dfFace = fr->lfFaceName;
1194 /***********************************************************************
1195 * XFONT_GetFontMetric
1197 * Retrieve font metric info (enumeration).
1199 static UINT XFONT_GetFontMetric( const fontInfo* pfi,
1200 LPENUMLOGFONTEXW pLF,
1201 NEWTEXTMETRICEXW *pTM )
1203 memset( pLF, 0, sizeof(*pLF) );
1204 memset( pTM, 0, sizeof(*pTM) );
1206 #define plf ((LPLOGFONTW)pLF)
1207 #define ptm ((LPNEWTEXTMETRICW)pTM)
1208 plf->lfHeight = ptm->tmHeight = pfi->df.dfPixHeight;
1209 plf->lfWidth = ptm->tmAveCharWidth = pfi->df.dfAvgWidth;
1210 plf->lfWeight = ptm->tmWeight = pfi->df.dfWeight;
1211 plf->lfItalic = ptm->tmItalic = pfi->df.dfItalic;
1212 plf->lfUnderline = ptm->tmUnderlined = pfi->df.dfUnderline;
1213 plf->lfStrikeOut = ptm->tmStruckOut = pfi->df.dfStrikeOut;
1214 plf->lfCharSet = ptm->tmCharSet = pfi->df.dfCharSet;
1216 /* convert pitch values */
1218 ptm->tmPitchAndFamily = pfi->df.dfPitchAndFamily;
1219 plf->lfPitchAndFamily = (pfi->df.dfPitchAndFamily & 0xF1) + 1;
1221 MultiByteToWideChar(CP_ACP, 0, pfi->df.dfFace, -1,
1222 plf->lfFaceName, LF_FACESIZE);
1224 /* FIXME: fill in rest of plF values */
1225 strcpyW(pLF->elfFullName, plf->lfFaceName);
1226 MultiByteToWideChar(CP_ACP, 0, "Regular", -1,
1227 pLF->elfStyle, LF_FACESIZE);
1228 MultiByteToWideChar(CP_ACP, 0, plf->lfCharSet == SYMBOL_CHARSET ?
1229 "Symbol" : "Roman", -1,
1230 pLF->elfScript, LF_FACESIZE);
1232 #undef plf
1234 ptm->tmAscent = pfi->df.dfAscent;
1235 ptm->tmDescent = ptm->tmHeight - ptm->tmAscent;
1236 ptm->tmInternalLeading = pfi->df.dfInternalLeading;
1237 ptm->tmMaxCharWidth = pfi->df.dfMaxWidth;
1238 ptm->tmDigitizedAspectX = pfi->df.dfHorizRes;
1239 ptm->tmDigitizedAspectY = pfi->df.dfVertRes;
1241 ptm->tmFirstChar = pfi->df.dfFirstChar;
1242 ptm->tmLastChar = pfi->df.dfLastChar;
1243 ptm->tmDefaultChar = pfi->df.dfDefaultChar;
1244 ptm->tmBreakChar = pfi->df.dfBreakChar;
1246 TRACE("Calling Enum proc with FaceName %s FullName %s\n",
1247 debugstr_w(pLF->elfLogFont.lfFaceName),
1248 debugstr_w(pLF->elfFullName));
1250 TRACE("CharSet = %d type = %d\n", ptm->tmCharSet, pfi->df.dfType);
1251 /* return font type */
1252 return pfi->df.dfType;
1253 #undef ptm
1257 /***********************************************************************
1258 * XFONT_FixupFlags
1260 * INIT ONLY
1262 * dfPitchAndFamily flags for some common typefaces.
1264 static BYTE XFONT_FixupFlags( LPCSTR lfFaceName )
1266 switch( lfFaceName[0] )
1268 case 'a':
1269 case 'A': if(!strncasecmp(lfFaceName, "Arial", 5) )
1270 return FF_SWISS;
1271 break;
1272 case 'h':
1273 case 'H': if(!strcasecmp(lfFaceName, "Helvetica") )
1274 return FF_SWISS;
1275 break;
1276 case 'c':
1277 case 'C': if(!strncasecmp(lfFaceName, "Courier", 7))
1278 return FF_MODERN;
1280 if (!strcasecmp(lfFaceName, "Charter") )
1281 return FF_ROMAN;
1282 break;
1283 case 'p':
1284 case 'P': if( !strcasecmp(lfFaceName,"Palatino") )
1285 return FF_ROMAN;
1286 break;
1287 case 't':
1288 case 'T': if(!strncasecmp(lfFaceName, "Times", 5) )
1289 return FF_ROMAN;
1290 break;
1291 case 'u':
1292 case 'U': if(!strcasecmp(lfFaceName, "Utopia") )
1293 return FF_ROMAN;
1294 break;
1295 case 'z':
1296 case 'Z': if(!strcasecmp(lfFaceName, "Zapf Dingbats") )
1297 return FF_DECORATIVE;
1299 return 0;
1302 /***********************************************************************
1303 * XFONT_SameFoundryAndFamily
1305 * INIT ONLY
1307 static BOOL XFONT_SameFoundryAndFamily( const LFD* lfd1, const LFD* lfd2 )
1309 return ( !strcasecmp( lfd1->foundry, lfd2->foundry ) &&
1310 !strcasecmp( lfd1->family, lfd2->family ) );
1313 /***********************************************************************
1314 * XFONT_InitialCapitals
1316 * INIT ONLY
1318 * Upper case first letters of words & remove multiple spaces
1320 static void XFONT_InitialCapitals(LPSTR lpch)
1322 int i;
1323 BOOL up;
1324 char* lpstr = lpch;
1326 for( i = 0, up = TRUE; *lpch; lpch++, i++ )
1328 if( isspace(*lpch) )
1330 if (!up) /* Not already got one */
1332 *lpstr++ = ' ';
1333 up = TRUE;
1336 else if( isalpha(*lpch) && up )
1338 *lpstr++ = toupper(*lpch);
1339 up = FALSE;
1341 else
1343 *lpstr++ = *lpch;
1344 up = FALSE;
1348 /* Remove possible trailing space */
1349 if (up && i > 0)
1350 --lpstr;
1351 *lpstr = '\0';
1355 /***********************************************************************
1356 * XFONT_WindowsNames
1358 * INIT ONLY
1360 * Build generic Windows aliases for X font names.
1362 * -misc-fixed- -> "Fixed"
1363 * -sony-fixed- -> "Sony Fixed", etc...
1365 static void XFONT_WindowsNames(void)
1367 fontResource* fr;
1369 for( fr = fontList; fr ; fr = fr->next )
1371 fontResource* pfr;
1372 char* lpch;
1374 if( fr->fr_flags & FR_NAMESET ) continue; /* skip already assigned */
1376 for( pfr = fontList; pfr != fr ; pfr = pfr->next )
1377 if( pfr->fr_flags & FR_NAMESET )
1379 if (!strcasecmp( pfr->resource->family, fr->resource->family))
1380 break;
1383 lpch = fr->lfFaceName;
1384 snprintf( fr->lfFaceName, sizeof(fr->lfFaceName), "%s %s",
1385 /* prepend vendor name */
1386 (pfr==fr) ? "" : fr->resource->foundry,
1387 fr->resource->family);
1388 XFONT_InitialCapitals(fr->lfFaceName);
1390 BYTE bFamilyStyle = XFONT_FixupFlags( fr->lfFaceName );
1391 if( bFamilyStyle)
1393 fontInfo* fi;
1394 for( fi = fr->fi ; fi ; fi = fi->next )
1395 fi->df.dfPitchAndFamily |= bFamilyStyle;
1399 TRACE("typeface '%s'\n", fr->lfFaceName);
1401 fr->fr_flags |= FR_NAMESET;
1405 /***********************************************************************
1406 * XFONT_LoadDefaultLFD
1408 * Move lfd to the head of fontList to make it more likely to be matched
1410 static void XFONT_LoadDefaultLFD(LFD* lfd, LPCSTR fonttype)
1413 fontResource *fr, *pfr;
1414 for( fr = NULL, pfr = fontList; pfr; pfr = pfr->next )
1416 if( XFONT_SameFoundryAndFamily(pfr->resource, lfd) )
1418 if( fr )
1420 fr->next = pfr->next;
1421 pfr->next = fontList;
1422 fontList = pfr;
1424 break;
1426 fr = pfr;
1428 if (!pfr)
1429 WARN("Default %sfont '-%s-%s-' not available\n", fonttype,
1430 lfd->foundry, lfd->family);
1434 /***********************************************************************
1435 * XFONT_LoadDefault
1437 static void XFONT_LoadDefault( HKEY hkey, LPCSTR ini, LPCSTR fonttype)
1439 char buffer[MAX_LFD_LENGTH];
1440 DWORD type, count = sizeof(buffer);
1442 buffer[0] = 0;
1443 RegQueryValueExA(hkey, ini, 0, &type, (LPBYTE)buffer, &count);
1445 if (*buffer)
1447 LFD lfd;
1448 char* pch = buffer;
1449 while( *pch && isspace(*pch) ) pch++;
1451 TRACE("Using '%s' as default %sfont\n", pch, fonttype);
1452 if (LFD_Parse(pch, &lfd) && lfd.foundry && lfd.family)
1453 XFONT_LoadDefaultLFD(&lfd, fonttype);
1454 else
1455 WARN("Ini section [%s]%s is malformed\n", INIFontSection, ini);
1459 /***********************************************************************
1460 * XFONT_LoadDefaults
1462 static void XFONT_LoadDefaults( HKEY hkey )
1464 XFONT_LoadDefault( hkey, INIDefaultFixed, "fixed ");
1465 XFONT_LoadDefault( hkey, INIDefault, "");
1468 /***********************************************************************
1469 * XFONT_CreateAlias
1471 static fontAlias* XFONT_CreateAlias( LPCSTR lpTypeFace, LPCSTR lpAlias )
1473 int j;
1474 fontAlias *pfa, *prev = NULL;
1476 for(pfa = aliasTable; pfa; pfa = pfa->next)
1478 /* check if we already got one */
1479 if( !strcasecmp( pfa->faTypeFace, lpAlias ) )
1481 TRACE("redundant alias '%s' -> '%s'\n",
1482 lpAlias, lpTypeFace );
1483 return NULL;
1485 prev = pfa;
1488 j = strlen(lpTypeFace) + 1;
1489 pfa = HeapAlloc( GetProcessHeap(), 0, sizeof(fontAlias) +
1490 j + strlen(lpAlias) + 1 );
1491 if (pfa)
1493 if (!prev)
1494 aliasTable = pfa;
1495 else
1496 prev->next = pfa;
1498 pfa->next = NULL;
1499 pfa->faTypeFace = (LPSTR)(pfa + 1);
1500 strcpy( pfa->faTypeFace, lpTypeFace );
1501 pfa->faAlias = pfa->faTypeFace + j;
1502 strcpy( pfa->faAlias, lpAlias );
1504 TRACE("added alias '%s' for '%s'\n", lpAlias, lpTypeFace );
1506 return pfa;
1508 return NULL;
1512 /***********************************************************************
1513 * XFONT_LoadAlias
1515 static void XFONT_LoadAlias(const LFD* lfd, LPCSTR lpAlias, BOOL bSubst)
1517 fontResource *fr, *frMatch = NULL;
1518 if (!lfd->foundry || ! lfd->family)
1520 WARN("Malformed font resource for alias '%s'\n", lpAlias);
1521 return;
1523 for (fr = fontList; fr ; fr = fr->next)
1525 if(!strcasecmp(fr->resource->family, lpAlias))
1527 /* alias is not needed since the real font is present */
1528 TRACE("Ignoring font alias '%s' as it is already available as a real font\n", lpAlias);
1529 return;
1531 if( XFONT_SameFoundryAndFamily( fr->resource, lfd ) )
1533 frMatch = fr;
1534 break;
1538 if( frMatch )
1540 if( bSubst )
1542 fontAlias *pfa, *prev = NULL;
1544 for(pfa = aliasTable; pfa; pfa = pfa->next)
1546 /* Remove lpAlias from aliasTable - we should free the old entry */
1547 if(!strcmp(lpAlias, pfa->faAlias))
1549 if(prev)
1550 prev->next = pfa->next;
1551 else
1552 aliasTable = pfa->next;
1555 /* Update any references to the substituted font in aliasTable */
1556 if(!strcmp(frMatch->lfFaceName, pfa->faTypeFace))
1558 pfa->faTypeFace = HeapAlloc( GetProcessHeap(), 0, strlen(lpAlias)+1 );
1559 strcpy( pfa->faTypeFace, lpAlias );
1561 prev = pfa;
1564 TRACE("\tsubstituted '%s' with '%s'\n", frMatch->lfFaceName, lpAlias );
1566 lstrcpynA( frMatch->lfFaceName, lpAlias, LF_FACESIZE );
1567 frMatch->fr_flags |= FR_NAMESET;
1569 else
1571 /* create new entry in the alias table */
1572 XFONT_CreateAlias( frMatch->lfFaceName, lpAlias );
1575 else
1577 WARN("Font alias '-%s-%s-' is not available\n", lfd->foundry, lfd->family);
1581 /***********************************************************************
1582 * Just a copy of PROFILE_GetStringItem
1584 * Convenience function that turns a string 'xxx, yyy, zzz' into
1585 * the 'xxx\0 yyy, zzz' and returns a pointer to the 'yyy, zzz'.
1587 static char *XFONT_GetStringItem( char *start )
1589 #define XFONT_isspace(c) (isspace(c) || (c == '\r') || (c == 0x1a))
1590 char *lpchX, *lpch;
1592 for (lpchX = start, lpch = NULL; *lpchX != '\0'; lpchX++ )
1594 if( *lpchX == ',' )
1596 if( lpch ) *lpch = '\0'; else *lpchX = '\0';
1597 while( *(++lpchX) )
1598 if( !XFONT_isspace(*lpchX) ) return lpchX;
1600 else if( XFONT_isspace( *lpchX ) && !lpch ) lpch = lpchX;
1601 else lpch = NULL;
1603 if( lpch ) *lpch = '\0';
1604 return NULL;
1605 #undef XFONT_isspace
1608 /***********************************************************************
1609 * XFONT_LoadAliases
1611 * INIT ONLY
1613 * Create font aliases for some standard windows fonts using user's
1614 * default choice of (sans-)serif fonts
1616 * Read user-defined aliases from config file. Format is as follows
1618 * Alias# = [Windows font name],[LFD font name], <substitute original name>
1620 * Example:
1621 * Alias0 = Arial, -adobe-helvetica-
1622 * Alias1 = Times New Roman, -bitstream-courier-, 1
1623 * ...
1625 * Note that from 970817 and on we have built-in alias templates that take
1626 * care of the necessary Windows typefaces.
1628 typedef struct
1630 LPSTR fatResource;
1631 LPSTR fatAlias;
1632 } aliasTemplate;
1634 static void XFONT_LoadAliases( HKEY hkey )
1636 char *lpResource;
1637 char buffer[MAX_LFD_LENGTH];
1638 int i = 0;
1639 LFD lfd;
1641 /* built-ins first */
1642 strcpy(buffer, "-bitstream-charter-");
1643 if (hkey)
1645 DWORD type, count = sizeof(buffer);
1646 RegQueryValueExA(hkey, INIDefaultSerif, 0, &type, (LPBYTE)buffer, &count);
1648 TRACE("Using '%s' as default serif font\n", buffer);
1649 if (LFD_Parse(buffer, &lfd))
1651 /* NB XFONT_InitialCapitals should not change these standard aliases */
1652 XFONT_LoadAlias( &lfd, "Tms Roman", FALSE);
1653 XFONT_LoadAlias( &lfd, "MS Serif", FALSE);
1654 XFONT_LoadAlias( &lfd, "Times New Roman", FALSE);
1656 XFONT_LoadDefaultLFD( &lfd, "serif ");
1659 strcpy(buffer, "-adobe-helvetica-");
1660 if (hkey)
1662 DWORD type, count = sizeof(buffer);
1663 RegQueryValueExA(hkey, INIDefaultSansSerif, 0, &type, (LPBYTE)buffer, &count);
1665 TRACE("Using '%s' as default sans serif font\n", buffer);
1666 if (LFD_Parse(buffer, &lfd))
1668 XFONT_LoadAlias( &lfd, "Helv", FALSE);
1669 XFONT_LoadAlias( &lfd, "MS Sans Serif", FALSE);
1670 XFONT_LoadAlias( &lfd, "MS Shell Dlg", FALSE);
1671 XFONT_LoadAlias( &lfd, "System", FALSE);
1672 XFONT_LoadAlias( &lfd, "Arial", FALSE);
1674 XFONT_LoadDefaultLFD( &lfd, "sans serif ");
1677 /* then user specified aliases */
1680 BOOL bSubst;
1681 char subsection[32];
1682 snprintf( subsection, sizeof(subsection), "%s%i", INIAliasSection, i++ );
1684 buffer[0] = 0;
1685 if (hkey)
1687 DWORD type, count = sizeof(buffer);
1688 RegQueryValueExA(hkey, subsection, 0, &type, (LPBYTE)buffer, &count);
1691 if (!buffer[0])
1692 break;
1694 XFONT_InitialCapitals(buffer);
1695 lpResource = XFONT_GetStringItem( buffer );
1696 bSubst = (XFONT_GetStringItem( lpResource )) ? TRUE : FALSE;
1697 if( lpResource && *lpResource )
1699 if (LFD_Parse(lpResource, &lfd)) XFONT_LoadAlias(&lfd, buffer, bSubst);
1701 else
1702 WARN("malformed font alias '%s'\n", buffer );
1704 while(TRUE);
1707 /***********************************************************************
1708 * XFONT_UnAlias
1710 * Convert an (potential) alias into a real windows name
1713 static LPCSTR XFONT_UnAlias(char* font)
1715 if (font[0])
1717 fontAlias* fa;
1718 XFONT_InitialCapitals(font); /* to remove extra white space */
1720 for( fa = aliasTable; fa; fa = fa->next )
1721 /* use case insensitive matching to handle eg "MS Sans Serif" */
1722 if( !strcasecmp( fa->faAlias, font ) )
1724 TRACE("found alias '%s'->%s'\n", font, fa->faTypeFace );
1725 strcpy(font, fa->faTypeFace);
1726 return fa->faAlias;
1729 return NULL;
1732 /***********************************************************************
1733 * XFONT_RemoveFontResource
1735 * Caller should check if the font resource is in use. If it is it should
1736 * set FR_REMOVED flag to delay removal until the resource is not in use
1737 * any more.
1739 static void XFONT_RemoveFontResource( fontResource** ppfr )
1741 fontResource* pfr = *ppfr;
1742 #if 0
1743 fontInfo* pfi;
1745 /* FIXME - if fonts were read from a cache, these HeapFrees will fail */
1746 while( pfr->fi )
1748 pfi = pfr->fi->next;
1749 HeapFree( GetProcessHeap(), 0, pfr->fi );
1750 pfr->fi = pfi;
1752 HeapFree( GetProcessHeap(), 0, pfr );
1753 #endif
1754 *ppfr = pfr->next;
1757 /***********************************************************************
1758 * XFONT_LoadIgnores
1760 * INIT ONLY
1762 * Removes specified fonts from the font table to prevent Wine from
1763 * using it.
1765 * Ignore# = [LFD font name]
1767 * Example:
1768 * Ignore0 = -misc-nil-
1769 * Ignore1 = -sun-open look glyph-
1770 * ...
1773 static void XFONT_LoadIgnore(char* lfdname)
1775 fontResource** ppfr;
1776 LFD lfd;
1778 if (LFD_Parse(lfdname, &lfd) && lfd.foundry && lfd.family)
1780 for( ppfr = &fontList; *ppfr ; ppfr = &((*ppfr)->next))
1782 if( XFONT_SameFoundryAndFamily( (*ppfr)->resource, &lfd) )
1784 TRACE("Ignoring '-%s-%s-'\n",
1785 (*ppfr)->resource->foundry, (*ppfr)->resource->family );
1787 XFONT_RemoveFontResource( ppfr );
1788 break;
1792 else
1793 WARN("Malformed font resource\n");
1796 static void XFONT_LoadIgnores( HKEY hkey )
1798 int i = 0;
1799 char subsection[32];
1800 char buffer[MAX_LFD_LENGTH];
1802 /* Standard one that no one wants */
1803 strcpy(buffer, "-misc-nil-");
1804 XFONT_LoadIgnore(buffer);
1806 /* Others from INI file */
1807 if (!hkey) return;
1810 DWORD type, count = sizeof(buffer);
1811 sprintf( subsection, "%s%i", INIIgnoreSection, i++ );
1813 if (!RegQueryValueExA(hkey, subsection, 0, &type, (LPBYTE)buffer, &count))
1815 char* pch = buffer;
1816 while( *pch && isspace(*pch) ) pch++;
1817 XFONT_LoadIgnore(pch);
1819 else
1820 break;
1821 } while(TRUE);
1825 /***********************************************************************
1826 * XFONT_UserMetricsCache
1828 * Returns expanded name for the cachedmetrics file.
1829 * Now it also appends the current value of the $DISPLAY variable.
1831 static char* XFONT_UserMetricsCache( char* buffer, int* buf_size )
1833 const char *confdir = wine_get_config_dir();
1834 const char *display_name = XDisplayName(NULL);
1835 int len = strlen(confdir) + strlen(INIFontMetrics) + strlen(display_name) + 8;
1836 int display = 0;
1837 int screen = 0;
1838 char *p, *ext;
1841 ** Normalize the display name, since on Red Hat systems, DISPLAY
1842 ** is commonly set to one of either 'unix:0.0' or ':0' or ':0.0'.
1843 ** after this code, all of the above will resolve to ':0.0'.
1845 if (!strncmp( display_name, "unix:", 5 )) display_name += 4;
1846 p = strchr(display_name, ':');
1847 if (p) sscanf(p + 1, "%d.%d", &display, &screen);
1849 if ((len > *buf_size) &&
1850 !(buffer = HeapReAlloc( GetProcessHeap(), 0, buffer, *buf_size = len )))
1852 ERR("out of memory\n");
1853 ExitProcess(1);
1855 sprintf( buffer, "%s/%s", confdir, INIFontMetrics );
1857 ext = buffer + strlen(buffer);
1858 strcpy( ext, display_name );
1860 if (!(p = strchr( ext, ':' ))) p = ext + strlen(ext);
1861 sprintf( p, ":%d.%d", display, screen );
1862 return buffer;
1866 /***********************************************************************
1867 * X Font Matching
1869 * Compare two fonts (only parameters set by the XFONT_InitFontInfo()).
1871 static INT XFONT_IsSubset(const fontInfo* match, const fontInfo* fi)
1873 INT m;
1875 /* 0 - keep both, 1 - keep match, -1 - keep fi */
1877 /* Compare dfItalic, Underline, Strikeout, Weight, Charset */
1878 m = (const BYTE*)&fi->df.dfPixWidth - (const BYTE*)&fi->df.dfItalic;
1879 if( memcmp(&match->df.dfItalic, &fi->df.dfItalic, m )) return 0;
1881 if( (!((fi->fi_flags & FI_SCALABLE) + (match->fi_flags & FI_SCALABLE))
1882 && fi->lfd_height != match->lfd_height) ||
1883 (!((fi->fi_flags & FI_POLYWEIGHT) + (match->fi_flags & FI_POLYWEIGHT))
1884 && fi->df.dfWeight != match->df.dfWeight) ) return 0;
1886 m = (int)(match->fi_flags & (FI_POLYWEIGHT | FI_SCALABLE)) -
1887 (int)(fi->fi_flags & (FI_SCALABLE | FI_POLYWEIGHT));
1889 if( m == (FI_POLYWEIGHT - FI_SCALABLE) ||
1890 m == (FI_SCALABLE - FI_POLYWEIGHT) ) return 0; /* keep both */
1891 else if( m >= 0 ) return 1; /* 'match' is better */
1893 return -1; /* 'fi' is better */
1896 /***********************************************************************
1897 * XFONT_CheckFIList
1899 * REMOVE_SUBSETS - attach new fi and purge subsets
1900 * UNMARK_SUBSETS - remove subset flags from all fi entries
1902 static void XFONT_CheckFIList( fontResource* fr, fontInfo* fi, int action)
1904 int i = 0;
1905 fontInfo* pfi, *prev;
1907 for( prev = NULL, pfi = fr->fi; pfi; )
1909 if( action == REMOVE_SUBSETS )
1911 if( pfi->fi_flags & FI_SUBSET )
1913 fontInfo* subset = pfi;
1915 i++;
1916 fr->fi_count--;
1917 if( prev ) prev->next = pfi = pfi->next;
1918 else fr->fi = pfi = pfi->next;
1919 HeapFree( GetProcessHeap(), 0, subset );
1920 continue;
1923 else pfi->fi_flags &= ~FI_SUBSET;
1925 prev = pfi;
1926 pfi = pfi->next;
1929 if( action == REMOVE_SUBSETS ) /* also add the superset */
1931 if( fi->fi_flags & FI_SCALABLE )
1933 fi->next = fr->fi;
1934 fr->fi = fi;
1936 else if( prev ) prev->next = fi; else fr->fi = fi;
1937 fr->fi_count++;
1940 if( i ) TRACE("\t purged %i subsets [%i]\n", i , fr->fi_count);
1943 /***********************************************************************
1944 * XFONT_FindFIList
1946 static fontResource* XFONT_FindFIList( fontResource* pfr, const char* pTypeFace )
1948 while( pfr )
1950 if( !strcasecmp( pfr->lfFaceName, pTypeFace ) ) break;
1951 pfr = pfr->next;
1953 /* Give the app back the font name it asked for. Encarta checks this. */
1954 if (pfr) strcpy(pfr->lfFaceName,pTypeFace);
1955 return pfr;
1958 /***********************************************************************
1959 * XFONT_FixupPointSize
1961 static void XFONT_FixupPointSize(fontInfo* fi)
1963 #define df (fi->df)
1964 df.dfHorizRes = df.dfVertRes = fi->lfd_resolution;
1965 df.dfPoints = (INT16)
1966 (((INT)(df.dfPixHeight - df.dfInternalLeading) * 72 + (df.dfVertRes >> 1)) /
1967 df.dfVertRes );
1968 #undef df
1971 /***********************************************************************
1972 * XFONT_BuildMetrics
1974 * Build font metrics from X font
1976 static int XLoadQueryFont_ErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
1978 return 1;
1981 /* XLoadQueryFont has the bad habit of crashing when loading a bad font... */
1982 static XFontStruct *safe_XLoadQueryFont(Display *display, char *name)
1984 XFontStruct *ret;
1986 X11DRV_expect_error(display, XLoadQueryFont_ErrorHandler, NULL);
1987 ret = XLoadQueryFont(display, name);
1988 if (X11DRV_check_error()) ret = NULL;
1989 return ret;
1993 static int XFONT_BuildMetrics(char** x_pattern, int res, unsigned x_checksum, int x_count)
1995 int i;
1996 fontInfo* fi = NULL;
1997 fontResource* fr, *pfr;
1998 int n_ff = 0;
2000 MESSAGE("Building font metrics. This may take some time...\n");
2001 for( i = 0; i < x_count; i++ )
2003 char* typeface;
2004 LFD lfd;
2005 int j;
2006 char buffer[MAX_LFD_LENGTH];
2007 char* lpstr;
2008 XFontStruct* x_fs;
2009 fontInfo* pfi;
2011 if (!(typeface = HeapAlloc(GetProcessHeap(), 0, strlen(x_pattern[i])+1))) break;
2012 strcpy( typeface, x_pattern[i] );
2013 if (i % 10 == 0) MESSAGE("Font metrics: %.1f%% done\n", 100.0 * i / x_count);
2015 if (!LFD_Parse(typeface, &lfd))
2017 HeapFree(GetProcessHeap(), 0, typeface);
2018 continue;
2021 /* find a family to insert into */
2023 for( pfr = NULL, fr = fontList; fr; fr = fr->next )
2025 if( XFONT_SameFoundryAndFamily(fr->resource, &lfd))
2026 break;
2027 pfr = fr;
2030 if( !fi ) fi = HeapAlloc(GetProcessHeap(), 0, sizeof(fontInfo));
2032 if( !LFD_InitFontInfo( fi, &lfd, x_pattern[i]) )
2033 goto nextfont;
2035 if( !fr ) /* add new family */
2037 n_ff++;
2038 fr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(fontResource));
2039 if (fr)
2041 fr->resource = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(LFD));
2043 TRACE("family: -%s-%s-\n", lfd.foundry, lfd.family );
2044 fr->resource->foundry = HeapAlloc(GetProcessHeap(), 0, strlen(lfd.foundry)+1);
2045 strcpy( (char *)fr->resource->foundry, lfd.foundry );
2046 fr->resource->family = HeapAlloc(GetProcessHeap(), 0, strlen(lfd.family)+1);
2047 strcpy( (char *)fr->resource->family, lfd.family );
2048 fr->resource->weight = "";
2050 if( pfr ) pfr->next = fr;
2051 else fontList = fr;
2053 else
2054 WARN("Not enough memory for a new font family\n");
2057 /* check if we already have something better than "fi" */
2059 for( pfi = fr->fi, j = 0; pfi && j <= 0; pfi = pfi->next )
2060 if( (j = XFONT_IsSubset( pfi, fi )) < 0 )
2061 pfi->fi_flags |= FI_SUBSET; /* superseded by "fi" */
2062 if( j > 0 ) goto nextfont;
2064 /* add new font instance "fi" to the "fr" font resource */
2066 if( fi->fi_flags & FI_SCALABLE )
2068 LFD lfd1;
2069 char pxl_string[4], res_string[4];
2070 /* set scalable font height to get a basis for extrapolation */
2072 fi->lfd_height = DEF_SCALABLE_HEIGHT;
2073 fi->lfd_resolution = res;
2075 sprintf(pxl_string, "%d", fi->lfd_height);
2076 sprintf(res_string, "%d", fi->lfd_resolution);
2078 lfd1 = lfd;
2079 lfd1.pixel_size = pxl_string;
2080 lfd1.point_size = "*";
2081 lfd1.resolution_x = res_string;
2082 lfd1.resolution_y = res_string;
2084 LFD_UnParse(buffer, sizeof(buffer), &lfd1);
2086 lpstr = buffer;
2088 else lpstr = x_pattern[i];
2090 /* X11 may return an error on some bad fonts... So be prepared to handle these. */
2091 if ((x_fs = safe_XLoadQueryFont(gdi_display, lpstr)) != 0)
2093 XFONT_SetFontMetric( fi, fr, x_fs );
2094 wine_tsx11_lock();
2095 XFreeFont( gdi_display, x_fs );
2096 wine_tsx11_unlock();
2098 XFONT_FixupPointSize(fi);
2100 TRACE("\t[% 2ipt] '%s'\n", fi->df.dfPoints, x_pattern[i] );
2102 XFONT_CheckFIList( fr, fi, REMOVE_SUBSETS );
2103 fi = NULL; /* preventing reuse */
2105 else
2107 ERR("failed to load %s\n", lpstr );
2109 XFONT_CheckFIList( fr, fi, UNMARK_SUBSETS );
2111 nextfont:
2112 HeapFree(GetProcessHeap(), 0, typeface);
2114 HeapFree(GetProcessHeap(), 0, fi);
2116 /* Scan through the font list and remove FontResource(s) (fr)
2117 * that have no associated Fontinfo(s) (fi).
2118 * This code is necessary because XFONT_ReadCachedMetrics
2119 * assumes that there is at least one fi associated with a fr.
2120 * This assumption is invalid for TT font
2121 * -altsys-ms outlook-medium-r-normal--0-0-0-0-p-0-microsoft-symbol.
2124 fr = fontList;
2126 while (!fr->fi_count)
2128 fontList = fr->next;
2130 HeapFree(GetProcessHeap(), 0, fr->resource);
2131 HeapFree(GetProcessHeap(), 0, fr);
2133 fr = fontList;
2134 n_ff--;
2137 fr = fontList;
2139 while (fr->next)
2141 if (!fr->next->fi_count)
2143 pfr = fr->next;
2144 fr->next = fr->next->next;
2146 HeapFree(GetProcessHeap(), 0, pfr->resource);
2147 HeapFree(GetProcessHeap(), 0, pfr);
2149 n_ff--;
2151 else
2152 fr = fr->next;
2155 MESSAGE("Font metrics: 100.0%% done\n");
2156 return n_ff;
2159 /***********************************************************************
2160 * XFONT_ReadCachedMetrics
2162 * INIT ONLY
2164 static BOOL XFONT_ReadCachedMetrics( int fd, int res, unsigned x_checksum, int x_count )
2166 if( fd >= 0 )
2168 unsigned u;
2169 int i, j;
2171 /* read checksums */
2172 read( fd, &u, sizeof(unsigned) );
2173 read( fd, &i, sizeof(int) );
2175 if( u == x_checksum && i == x_count )
2177 off_t length, offset = 3 * sizeof(int);
2179 /* read total size */
2180 read( fd, &i, sizeof(int) );
2181 length = lseek( fd, 0, SEEK_END );
2183 if( length == (i + offset) )
2185 lseek( fd, offset, SEEK_SET );
2186 fontList = HeapAlloc( GetProcessHeap(), 0, i);
2187 if( fontList )
2189 fontResource* pfr = fontList;
2190 fontInfo* pfi = NULL;
2192 TRACE("Reading cached font metrics:\n");
2194 read( fd, fontList, i); /* read all metrics at once */
2195 while( offset < length )
2197 offset += sizeof(fontResource) + sizeof(fontInfo);
2198 pfr->fi = pfi = (fontInfo*)(pfr + 1);
2199 j = 1;
2200 while( TRUE )
2202 if( offset > length ||
2203 pfi->cptable >= (UINT16)X11DRV_CPTABLE_COUNT ||
2204 PtrToInt(pfi->next) != j++ )
2206 TRACE("error: offset=%ld length=%ld cptable=%d pfi->next=%p j=%d\n",
2207 (long)offset, (long)length, pfi->cptable, 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 = HeapAlloc(GetProcessHeap(),0,sizeof(LFD));
2250 if (!LFD_Parse(lpch, pfr->resource))
2252 HeapFree( GetProcessHeap(), 0, pfr->resource );
2253 pfr->resource = NULL;
2255 lpch += len;
2256 offset += len;
2257 if (offset > length)
2259 TRACE("error: offset=%ld length=%ld\n",(long)offset,(long)length);
2260 goto fail;
2263 close( fd );
2264 return TRUE;
2267 } else {
2268 TRACE("Wrong length: %ld!=%ld\n",(long)length,(long)(i+offset));
2270 } else {
2271 TRACE("Checksum (%x vs. %x) or count (%d vs. %d) mismatch\n",
2272 u,x_checksum,i,x_count);
2274 fail:
2275 HeapFree( GetProcessHeap(), 0, fontList );
2276 fontList = NULL;
2277 close( fd );
2279 return FALSE;
2282 /***********************************************************************
2283 * XFONT_WriteCachedMetrics
2285 * INIT ONLY
2287 static BOOL XFONT_WriteCachedMetrics( int fd, unsigned x_checksum, int x_count, int n_ff )
2289 fontResource* pfr;
2290 fontInfo* pfi;
2292 if( fd >= 0 )
2294 int i, j, k;
2295 char buffer[MAX_LFD_LENGTH];
2297 /* font metrics file:
2299 * +0000 x_checksum
2300 * +0004 x_count
2301 * +0008 total size to load
2302 * +000C prepackaged font metrics
2303 * ...
2304 * +...x X_FMC_MAGIC
2305 * +...x + 4 LFD stubs
2308 write( fd, &x_checksum, sizeof(unsigned) );
2309 write( fd, &x_count, sizeof(int) );
2311 for( j = i = 0, pfr = fontList; pfr; pfr = pfr->next )
2313 LFD_UnParse(buffer, sizeof(buffer), pfr->resource);
2314 i += strlen( buffer) + 1;
2315 j += pfr->fi_count;
2317 i += n_ff * sizeof(fontResource) + j * sizeof(fontInfo) + sizeof(int);
2318 write( fd, &i, sizeof(int) );
2320 TRACE("Writing font cache:\n");
2322 for( pfr = fontList; pfr; pfr = pfr->next )
2324 fontInfo fi;
2326 TRACE("\t-%s-%s-, %i instances\n", pfr->resource->foundry, pfr->resource->family, pfr->fi_count );
2328 i = write( fd, pfr, sizeof(fontResource) );
2329 if( i == sizeof(fontResource) )
2331 for( k = 1, pfi = pfr->fi; pfi; pfi = pfi->next )
2333 fi = *pfi;
2335 fi.df.dfFace = NULL;
2336 fi.next = IntToPtr(k); /* loader checks this */
2338 j = write( fd, &fi, sizeof(fi) );
2339 k++;
2341 if( j == sizeof(fontInfo) ) continue;
2343 break;
2345 if( i == sizeof(fontResource) && j == sizeof(fontInfo) )
2347 i = j = X_FMC_MAGIC;
2348 write( fd, &i, sizeof(int) );
2349 for( pfr = fontList; pfr && i == j; pfr = pfr->next )
2351 LFD_UnParse(buffer, sizeof(buffer), pfr->resource);
2352 i = strlen( buffer ) + 1;
2353 j = write( fd, buffer, i );
2356 close( fd );
2357 return ( i == j );
2359 return FALSE;
2362 /***********************************************************************
2363 * XFONT_GetDefResolution()
2365 * INIT ONLY
2367 * Here we initialize DefResolution which is used in the
2368 * XFONT_Match() penalty function, based on the values of log_pixels
2370 static int XFONT_GetDefResolution( int log_pixels_x, int log_pixels_y )
2372 int i, j, num = 3;
2373 int allowed_xfont_resolutions[3] = { 72, 75, 100 };
2374 int best = 0, best_diff = 65536;
2376 /* FIXME We can only really guess at a best DefResolution
2377 * - this should be configurable
2379 for( i = best = 0; i < num; i++ )
2381 j = abs( log_pixels_x - allowed_xfont_resolutions[i] );
2382 if( j < best_diff )
2384 best = i;
2385 best_diff = j;
2388 DefResolution = allowed_xfont_resolutions[best];
2389 return DefResolution;
2393 /***********************************************************************
2394 * XFONT_Match
2396 * Compute the matching score between the logical font and the device font.
2398 * contributions from highest to lowest:
2399 * charset
2400 * fixed pitch
2401 * height
2402 * family flags (only when the facename is not present)
2403 * width
2404 * weight, italics, underlines, strikeouts
2406 * NOTE: you can experiment with different penalty weights to see what happens.
2407 * http://premium.microsoft.com/msdn/library/techart/f365/f36b/f37b/d38b/sa8bf.htm
2409 static UINT XFONT_Match( fontMatch* pfm )
2411 fontInfo* pfi = pfm->pfi; /* device font to match */
2412 LPLOGFONT16 plf = pfm->plf; /* wanted logical font */
2413 UINT penalty = 0;
2414 BOOL bR6 = pfm->flags & FO_MATCH_XYINDEP; /* from text_caps */
2415 BOOL bScale = pfi->fi_flags & FI_SCALABLE;
2416 int d = 0, height;
2418 TRACE("\t[ %-2ipt h=%-3i w=%-3i %s%s]\n", pfi->df.dfPoints,
2419 pfi->df.dfPixHeight, pfi->df.dfAvgWidth,
2420 (pfi->df.dfWeight > FW_NORMAL) ? "Bold " : "Normal ",
2421 (pfi->df.dfItalic) ? "Italic" : "" );
2423 pfm->flags &= FO_MATCH_MASK;
2425 /* Charset */
2426 /* pfm->internal_charset: given(required) charset */
2427 /* pfi->internal_charset: charset of this font */
2428 if (pfi->internal_charset == DEFAULT_CHARSET)
2430 /* special case(unicode font) */
2431 /* priority: unmatched charset < unicode < matched charset */
2432 penalty += 0x50;
2434 else
2436 if( pfm->internal_charset == DEFAULT_CHARSET )
2439 if (pfi->internal_charset != ANSI_CHARSET)
2440 penalty += 0x200;
2442 if ( pfi->codepage != GetACP() )
2443 penalty += 0x200;
2445 else if (pfm->internal_charset != pfi->internal_charset)
2447 if ( pfi->internal_charset & 0xff00 )
2448 penalty += 0x1000; /* internal charset - should not be used */
2449 else
2450 penalty += 0x200;
2454 /* Height */
2455 height = -1;
2457 if( plf->lfHeight > 0 )
2459 int h = pfi->df.dfPixHeight;
2460 d = h - plf->lfHeight;
2461 height = plf->lfHeight;
2463 else
2465 int h = pfi->df.dfPixHeight - pfi->df.dfInternalLeading;
2466 if (h)
2468 d = h + plf->lfHeight;
2469 height = (-plf->lfHeight * pfi->df.dfPixHeight) / h;
2471 else
2473 ERR("PixHeight == InternalLeading\n");
2474 penalty += 0x1000; /* don't want this */
2479 if( height == 0 )
2480 pfm->height = 1; /* Very small */
2481 else if( d )
2483 if( bScale )
2484 pfm->height = height;
2485 else if( (plf->lfQuality != PROOF_QUALITY) && bR6 )
2487 if( d > 0 ) /* do not shrink raster fonts */
2489 pfm->height = pfi->df.dfPixHeight;
2490 penalty += (pfi->df.dfPixHeight - height) * 0x4;
2492 else /* expand only in integer multiples */
2494 pfm->height = height - height%pfi->df.dfPixHeight;
2495 penalty += (height - pfm->height + 1) * height / pfi->df.dfPixHeight;
2498 else /* can't be scaled at all */
2500 if( plf->lfQuality != PROOF_QUALITY) pfm->flags |= FO_SYNTH_HEIGHT;
2501 pfm->height = pfi->df.dfPixHeight;
2502 penalty += (d > 0)? d * 0x8 : -d * 0x10;
2505 else
2506 pfm->height = pfi->df.dfPixHeight;
2508 /* Pitch and Family */
2509 if( pfm->flags & FO_MATCH_PAF ) {
2510 int family = plf->lfPitchAndFamily & FF_FAMILY;
2512 /* TMPF_FIXED_PITCH means exactly the opposite */
2513 if( plf->lfPitchAndFamily & FIXED_PITCH ) {
2514 if( pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH ) penalty += 0x100;
2515 } else /* Variable is the default */
2516 if( !(pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH) ) penalty += 0x2;
2518 if (family != FF_DONTCARE && family != (pfi->df.dfPitchAndFamily & FF_FAMILY) )
2519 penalty += 0x10;
2522 /* Width */
2523 if( plf->lfWidth )
2525 int h;
2526 if( bR6 || bScale ) h = 0;
2527 else
2529 /* FIXME: not complete */
2531 pfm->flags |= FO_SYNTH_WIDTH;
2532 h = abs(plf->lfWidth - (pfm->height * pfi->df.dfAvgWidth)/pfi->df.dfPixHeight);
2534 penalty += h * ( d ) ? 0x2 : 0x1 ;
2536 else if( !(pfi->fi_flags & FI_NORMAL) ) penalty++;
2538 /* Weight */
2539 if( plf->lfWeight != FW_DONTCARE )
2541 penalty += abs(plf->lfWeight - pfi->df.dfWeight) / 40;
2542 if( plf->lfWeight > pfi->df.dfWeight ) pfm->flags |= FO_SYNTH_BOLD;
2543 } else if( pfi->df.dfWeight >= FW_BOLD ) penalty++; /* choose normal by default */
2545 /* Italic */
2546 if( plf->lfItalic != pfi->df.dfItalic )
2548 penalty += 0x4;
2549 pfm->flags |= FO_SYNTH_ITALIC;
2551 /* Underline */
2552 if( plf->lfUnderline ) pfm->flags |= FO_SYNTH_UNDERLINE;
2554 /* Strikeout */
2555 if( plf->lfStrikeOut ) pfm->flags |= FO_SYNTH_STRIKEOUT;
2558 if( penalty && !bScale && pfi->lfd_resolution != DefResolution )
2559 penalty++;
2561 TRACE(" returning %i\n", penalty );
2563 return penalty;
2566 /***********************************************************************
2567 * XFONT_MatchFIList
2569 * Scan a particular font resource for the best match.
2571 static UINT XFONT_MatchFIList( fontMatch* pfm )
2573 BOOL skipRaster = (pfm->flags & FO_MATCH_NORASTER);
2574 UINT current_score, score = (UINT)(-1);
2575 fontMatch fm = *pfm;
2577 for( fm.pfi = pfm->pfr->fi; fm.pfi && score; fm.pfi = fm.pfi->next)
2579 if( skipRaster && !(fm.pfi->fi_flags & FI_SCALABLE) )
2580 continue;
2582 current_score = XFONT_Match( &fm );
2583 if( score > current_score )
2585 *pfm = fm;
2586 score = current_score;
2589 return score;
2592 /***********************************************************************
2593 * XFONT_is_ansi_charset
2595 * returns TRUE if the given charset is ANSI_CHARSET.
2597 static BOOL XFONT_is_ansi_charset( UINT charset )
2599 return ((charset == ANSI_CHARSET) ||
2600 (charset == DEFAULT_CHARSET && GetACP() == 1252));
2603 /***********************************************************************
2604 * XFONT_MatchDeviceFont
2606 * Scan font resource tree.
2609 static void XFONT_MatchDeviceFont( fontResource* start, fontMatch* pfm)
2611 fontMatch fm = *pfm;
2612 UINT current_score, score = (UINT)(-1);
2613 fontResource** ppfr;
2615 TRACE("(%u) '%s' h=%i weight=%i %s\n",
2616 pfm->plf->lfCharSet, pfm->plf->lfFaceName, pfm->plf->lfHeight,
2617 pfm->plf->lfWeight, (pfm->plf->lfItalic) ? "Italic" : "" );
2619 pfm->pfi = NULL;
2621 /* the following hard-coded font binding assumes 'ANSI_CHARSET'. */
2622 if( !fm.plf->lfFaceName[0] &&
2623 XFONT_is_ansi_charset(fm.plf->lfCharSet) )
2625 switch(fm.plf->lfPitchAndFamily & 0xf0)
2627 case FF_MODERN:
2628 strcpy(fm.plf->lfFaceName, "Courier New");
2629 break;
2630 case FF_ROMAN:
2631 strcpy(fm.plf->lfFaceName, "Times New Roman");
2632 break;
2633 case FF_SWISS:
2634 strcpy(fm.plf->lfFaceName, "Arial");
2635 break;
2636 default:
2637 if((fm.plf->lfPitchAndFamily & 0x0f) == FIXED_PITCH)
2638 strcpy(fm.plf->lfFaceName, "Courier New");
2639 else
2640 strcpy(fm.plf->lfFaceName, "Arial");
2641 break;
2645 if( fm.plf->lfFaceName[0] )
2647 fm.pfr = XFONT_FindFIList( start, fm.plf->lfFaceName);
2648 if( fm.pfr ) /* match family */
2650 TRACE("found facename '%s'\n", fm.pfr->lfFaceName );
2652 if( fm.pfr->fr_flags & FR_REMOVED )
2653 fm.pfr = 0;
2654 else
2656 XFONT_MatchFIList( &fm );
2657 *pfm = fm;
2658 if (pfm->pfi)
2659 return;
2663 /* get charset if lfFaceName is one of known facenames. */
2665 const struct CharsetBindingInfo* pcharsetbindings;
2667 pcharsetbindings = &charsetbindings[0];
2668 while ( pcharsetbindings->pszFaceName != NULL )
2670 if ( !strcmp( pcharsetbindings->pszFaceName,
2671 fm.plf->lfFaceName ) )
2673 fm.internal_charset = pcharsetbindings->charset;
2674 break;
2676 pcharsetbindings ++;
2678 TRACE( "%s charset %u\n", fm.plf->lfFaceName, fm.internal_charset );
2682 /* match all available fonts */
2684 fm.flags |= FO_MATCH_PAF;
2685 for( ppfr = &fontList; *ppfr && score; ppfr = &(*ppfr)->next )
2687 if( (*ppfr)->fr_flags & FR_REMOVED )
2689 if( (*ppfr)->fo_count == 0 )
2690 XFONT_RemoveFontResource( ppfr );
2691 continue;
2694 fm.pfr = *ppfr;
2696 TRACE("%s\n", fm.pfr->lfFaceName );
2698 current_score = XFONT_MatchFIList( &fm );
2699 if( current_score < score )
2701 score = current_score;
2702 *pfm = fm;
2708 /***********************************************************************
2709 * X Font Cache
2711 static void XFONT_GrowFreeList(int start, int end)
2713 /* add all entries from 'start' up to and including 'end' */
2715 memset( fontCache + start, 0, (end - start + 1) * sizeof(fontObject) );
2717 fontCache[end].lru = fontLF;
2718 fontCache[end].count = -1;
2719 fontLF = start;
2720 while( start < end )
2722 fontCache[start].count = -1;
2723 fontCache[start].lru = start + 1;
2724 start++;
2728 static fontObject* XFONT_LookupCachedFont( const LOGFONT16 *plf, UINT16* checksum )
2730 UINT16 cs = __lfCheckSum( plf );
2731 int i = fontMRU, prev = -1;
2733 *checksum = cs;
2734 while( i >= 0 )
2736 if( fontCache[i].lfchecksum == cs &&
2737 !(fontCache[i].fo_flags & FO_REMOVED) )
2739 /* FIXME: something more intelligent here ? */
2741 if( !memcmp( plf, &fontCache[i].lf,
2742 sizeof(LOGFONT16) - LF_FACESIZE ) &&
2743 !strcmp( plf->lfFaceName, fontCache[i].lf.lfFaceName) )
2745 /* remove temporarily from the lru list */
2746 if( prev >= 0 )
2747 fontCache[prev].lru = fontCache[i].lru;
2748 else
2749 fontMRU = (INT16)fontCache[i].lru;
2750 return (fontCache + i);
2753 prev = i;
2754 i = (INT16)fontCache[i].lru;
2756 return NULL;
2759 static fontObject* XFONT_GetCacheEntry(void)
2761 int i;
2763 if( fontLF == -1 )
2765 int prev_i, prev_j, j;
2767 TRACE("font cache is full\n");
2769 /* lookup the least recently used font */
2771 for( prev_i = prev_j = j = -1, i = fontMRU; i >= 0; i = (INT16)fontCache[i].lru )
2773 if( fontCache[i].count <= 0 &&
2774 !(fontCache[i].fo_flags & FO_SYSTEM) )
2776 prev_j = prev_i;
2777 j = i;
2779 prev_i = i;
2782 if( j >= 0 ) /* unload font */
2784 /* detach from the lru list */
2786 TRACE("\tfreeing entry %i\n", j );
2788 fontCache[j].fr->fo_count--;
2790 if( prev_j >= 0 )
2791 fontCache[prev_j].lru = fontCache[j].lru;
2792 else fontMRU = (INT16)fontCache[j].lru;
2794 /* FIXME: lpXForm, lpPixmap */
2795 HeapFree( GetProcessHeap(), 0, fontCache[j].lpX11Trans );
2797 wine_tsx11_lock();
2798 XFreeFont( gdi_display, fontCache[j].fs );
2799 wine_tsx11_unlock();
2801 memset( fontCache + j, 0, sizeof(fontObject) );
2802 return (fontCache + j);
2804 else /* expand cache */
2806 fontObject* newCache;
2808 prev_i = fontCacheSize + FONTCACHE;
2810 TRACE("\tgrowing font cache from %i to %i\n", fontCacheSize, prev_i );
2812 if( (newCache = HeapReAlloc(GetProcessHeap(), 0, fontCache, prev_i * sizeof(fontObject))) )
2814 i = fontCacheSize;
2815 fontCacheSize = prev_i;
2816 fontCache = newCache;
2817 XFONT_GrowFreeList( i, fontCacheSize - 1);
2819 else return NULL;
2823 /* detach from the free list */
2825 i = fontLF;
2826 fontLF = (INT16)fontCache[i].lru;
2827 fontCache[i].count = 0;
2828 return (fontCache + i);
2831 static int XFONT_ReleaseCacheEntry(const fontObject* pfo)
2833 UINT u = (UINT)(pfo - fontCache);
2834 int i;
2835 int ret;
2837 if( u < fontCacheSize )
2839 ret = --fontCache[u].count;
2840 if ( ret == 0 )
2842 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
2844 if( CHECK_PFONT(pfo->prefobjs[i]) )
2845 XFONT_ReleaseCacheEntry(__PFONT(pfo->prefobjs[i]));
2849 return ret;
2852 return -1;
2855 /***********************************************************************
2856 * X11DRV_FONT_InitX11Metrics
2858 * Initialize font resource list and allocate font cache.
2860 static void X11DRV_FONT_InitX11Metrics( void )
2862 char** x_pattern;
2863 unsigned x_checksum;
2864 int i, x_count, fd, buf_size;
2865 char *buffer;
2866 HKEY hkey;
2869 wine_tsx11_lock();
2870 x_pattern = XListFonts(gdi_display, "*", MAX_FONTS, &x_count );
2871 wine_tsx11_unlock();
2873 TRACE("Font Mapper: initializing %i x11 fonts\n", x_count);
2874 if (x_count == MAX_FONTS)
2875 MESSAGE("There may be more fonts available - try increasing the value of MAX_FONTS\n");
2877 for( i = x_checksum = 0; i < x_count; i++ )
2879 int j;
2880 #if 0
2881 printf("%i\t: %s\n", i, x_pattern[i] );
2882 #endif
2884 j = strlen( x_pattern[i] );
2885 if( j ) x_checksum ^= __genericCheckSum( x_pattern[i], j );
2887 x_checksum |= X_PFONT_MAGIC;
2888 buf_size = 128;
2889 buffer = HeapAlloc( GetProcessHeap(), 0, buf_size );
2891 /* deal with systemwide font metrics cache */
2893 buffer[0] = 0;
2894 /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver\Fonts */
2895 if (RegOpenKeyA(HKEY_CURRENT_USER, INIFontSection, &hkey)) hkey = 0;
2896 if (hkey)
2898 DWORD type, count = buf_size;
2899 RegQueryValueExA(hkey, INIGlobalMetrics, 0, &type, (LPBYTE)buffer, &count);
2902 if( buffer[0] )
2904 fd = open( buffer, O_RDONLY );
2905 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2907 if (fontList == NULL)
2909 /* try per-user */
2910 buffer = XFONT_UserMetricsCache( buffer, &buf_size );
2911 if( buffer[0] )
2913 fd = open( buffer, O_RDONLY );
2914 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2918 if( fontList == NULL ) /* build metrics from scratch */
2920 int n_ff = XFONT_BuildMetrics(x_pattern, DefResolution, x_checksum, x_count);
2921 if( buffer[0] ) /* update cached metrics */
2923 fd = open( buffer, O_CREAT | O_TRUNC | O_RDWR, 0644 ); /* -rw-r--r-- */
2924 if( XFONT_WriteCachedMetrics( fd, x_checksum, x_count, n_ff ) == FALSE )
2926 WARN("Unable to write to fontcache '%s'\n", buffer);
2927 if( fd >= 0) remove( buffer ); /* couldn't write entire file */
2932 wine_tsx11_lock();
2933 XFreeFontNames(x_pattern);
2935 /* check if we're dealing with X11 R6 server */
2937 XFontStruct* x_fs;
2938 strcpy(buffer, "-*-*-*-*-normal-*-[12 0 0 12]-*-72-*-*-*-iso8859-1");
2939 if( (x_fs = safe_XLoadQueryFont(gdi_display, buffer)) )
2941 text_caps |= TC_SF_X_YINDEP;
2942 XFreeFont(gdi_display, x_fs);
2945 wine_tsx11_unlock();
2947 HeapFree(GetProcessHeap(), 0, buffer);
2949 XFONT_WindowsNames();
2950 XFONT_LoadAliases( hkey );
2951 if (hkey) XFONT_LoadDefaults( hkey );
2952 XFONT_LoadIgnores( hkey );
2954 /* fontList initialization is over, allocate X font cache */
2956 fontCache = HeapAlloc(GetProcessHeap(), 0, fontCacheSize * sizeof(fontObject));
2957 XFONT_GrowFreeList(0, fontCacheSize - 1);
2959 TRACE("done!\n");
2960 if (hkey) RegCloseKey(hkey);
2963 /***********************************************************************
2964 * X11DRV_FONT_Init
2966 void X11DRV_FONT_Init( int log_pixels_x, int log_pixels_y )
2968 XFONT_GetDefResolution( log_pixels_x, log_pixels_y );
2970 if(using_client_side_fonts)
2971 text_caps |= TC_VA_ABLE;
2973 return;
2976 /**********************************************************************
2977 * XFONT_SetX11Trans
2979 static BOOL XFONT_SetX11Trans( fontObject *pfo )
2981 char *fontName;
2982 Atom nameAtom;
2983 LFD lfd;
2985 wine_tsx11_lock();
2986 XGetFontProperty( pfo->fs, XA_FONT, &nameAtom );
2987 fontName = XGetAtomName( gdi_display, nameAtom );
2988 if (!LFD_Parse(fontName, &lfd) || lfd.pixel_size[0] != '[')
2990 XFree(fontName);
2991 wine_tsx11_unlock();
2992 return FALSE;
2994 #define PX pfo->lpX11Trans
2996 sscanf(lfd.pixel_size, "[%f%f%f%f]", &PX->a, &PX->b, &PX->c, &PX->d);
2997 XFree(fontName);
2999 XGetFontProperty( pfo->fs, x11drv_atom(RAW_ASCENT), &PX->RAW_ASCENT );
3000 XGetFontProperty( pfo->fs, x11drv_atom(RAW_DESCENT), &PX->RAW_DESCENT );
3001 wine_tsx11_unlock();
3003 PX->pixelsize = hypot(PX->a, PX->b);
3004 PX->ascent = PX->pixelsize / 1000.0 * PX->RAW_ASCENT;
3005 PX->descent = PX->pixelsize / 1000.0 * PX->RAW_DESCENT;
3007 TRACE("[%f %f %f %f] RA = %ld RD = %ld\n",
3008 PX->a, PX->b, PX->c, PX->d,
3009 PX->RAW_ASCENT, PX->RAW_DESCENT);
3011 #undef PX
3012 return TRUE;
3015 /***********************************************************************
3016 * X Device Font Objects
3018 static X_PHYSFONT XFONT_RealizeFont( LPLOGFONT16 plf,
3019 LPCSTR* faceMatched, BOOL bSubFont,
3020 WORD internal_charset,
3021 WORD* pcharsetMatched )
3023 UINT16 checksum;
3024 INT index = 0;
3025 fontObject* pfo;
3027 pfo = XFONT_LookupCachedFont( plf, &checksum );
3028 if( !pfo )
3030 fontMatch fm;
3031 INT i;
3033 fm.pfr = NULL;
3034 fm.pfi = NULL;
3035 fm.height = 0;
3036 fm.flags = 0;
3037 fm.plf = plf;
3038 fm.internal_charset = internal_charset;
3040 if( text_caps & TC_SF_X_YINDEP ) fm.flags = FO_MATCH_XYINDEP;
3042 /* allocate new font cache entry */
3044 if( (pfo = XFONT_GetCacheEntry()) )
3046 /* initialize entry and load font */
3047 char lpLFD[MAX_LFD_LENGTH];
3048 UINT uRelaxLevel = 0;
3050 if(abs(plf->lfHeight) > MAX_FONT_SIZE) {
3051 ERR(
3052 "plf->lfHeight = %d, Creating a 100 pixel font and rescaling metrics\n",
3053 plf->lfHeight);
3054 pfo->rescale = fabs(plf->lfHeight / 100.0);
3055 if(plf->lfHeight > 0) plf->lfHeight = 100;
3056 else plf->lfHeight = -100;
3057 } else
3058 pfo->rescale = 1.0;
3060 XFONT_MatchDeviceFont( fontList, &fm );
3061 pfo->fr = fm.pfr;
3062 pfo->fi = fm.pfi;
3063 pfo->fr->fo_count++;
3064 pfo->fo_flags = fm.flags & ~FO_MATCH_MASK;
3066 pfo->lf = *plf;
3067 pfo->lfchecksum = checksum;
3071 LFD_ComposeLFD( pfo, fm.height, lpLFD, uRelaxLevel++ );
3072 if( (pfo->fs = safe_XLoadQueryFont( gdi_display, lpLFD )) ) break;
3073 } while( uRelaxLevel );
3076 if(pfo->lf.lfEscapement != 0) {
3077 pfo->lpX11Trans = HeapAlloc(GetProcessHeap(), 0, sizeof(XFONTTRANS));
3078 if(!XFONT_SetX11Trans( pfo )) {
3079 HeapFree(GetProcessHeap(), 0, pfo->lpX11Trans);
3080 pfo->lpX11Trans = NULL;
3083 XFONT_GetLeading( &pfo->fi->df, pfo->fs,
3084 &pfo->foInternalLeading, NULL, pfo->lpX11Trans );
3085 pfo->foAvgCharWidth = (INT16)XFONT_GetAvgCharWidth(&pfo->fi->df, pfo->fs, pfo->lpX11Trans );
3086 pfo->foMaxCharWidth = (INT16)XFONT_GetMaxCharWidth(pfo->fs, pfo->lpX11Trans);
3088 /* FIXME: If we've got a soft font or
3089 * there are FO_SYNTH_... flags for the
3090 * non PROOF_QUALITY request, the engine
3091 * should rasterize characters into mono
3092 * pixmaps and store them in the pfo->lpPixmap
3093 * array (pfo->fs should be updated as well).
3094 * array (pfo->fs should be updated as well).
3095 * X11DRV_ExtTextOut() must be heavily modified
3096 * to support pixmap blitting and FO_SYNTH_...
3097 * styles.
3100 pfo->lpPixmap = NULL;
3102 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3103 pfo->prefobjs[i] = (X_PHYSFONT)0xffffffff; /* invalid value */
3105 /* special treatment for DBCS that needs multiple fonts */
3106 /* All member of pfo must be set correctly. */
3107 if ( bSubFont == FALSE )
3109 WORD charset_sub;
3110 WORD charsetMatchedSub;
3111 LOGFONT16 lfSub;
3112 LPCSTR faceMatchedSub;
3114 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3116 charset_sub = X11DRV_cptable[pfo->fi->cptable].
3117 penum_subfont_charset( i );
3118 if ( charset_sub == DEFAULT_CHARSET ) break;
3120 lfSub = *plf;
3121 lfSub.lfWidth = 0;
3122 lfSub.lfHeight=plf->lfHeight;
3123 lfSub.lfCharSet = (BYTE)(charset_sub & 0xff);
3124 lfSub.lfFaceName[0] = '\0'; /* FIXME? */
3125 /* this font has sub font */
3126 if ( i == 0 ) pfo->prefobjs[0] = (X_PHYSFONT)0;
3127 pfo->prefobjs[i] =
3128 XFONT_RealizeFont( &lfSub, &faceMatchedSub,
3129 TRUE, charset_sub,
3130 &charsetMatchedSub );
3131 /* FIXME: check charsetMatchedSub */
3136 if( !pfo ) /* couldn't get a new entry, get one of the cached fonts */
3138 UINT current_score, score = (UINT)(-1);
3140 i = index = fontMRU;
3141 fm.flags |= FO_MATCH_PAF;
3144 pfo = fontCache + i;
3145 fm.pfr = pfo->fr; fm.pfi = pfo->fi;
3147 current_score = XFONT_Match( &fm );
3148 if( current_score < score ) index = i;
3150 i = pfo->lru;
3151 } while( i >= 0 );
3152 pfo = fontCache + index;
3153 goto END;
3157 /* attach at the head of the lru list */
3158 pfo->lru = fontMRU;
3159 index = fontMRU = (pfo - fontCache);
3161 END:
3162 pfo->count++;
3164 TRACE("physfont %i\n", index);
3165 *faceMatched = pfo->fi->df.dfFace;
3166 *pcharsetMatched = pfo->fi->internal_charset;
3168 return (X_PHYSFONT)(X_PFONT_MAGIC | index);
3171 /***********************************************************************
3172 * XFONT_GetFontObject
3174 fontObject* XFONT_GetFontObject( X_PHYSFONT pFont )
3176 if( CHECK_PFONT(pFont) ) return __PFONT(pFont);
3177 return NULL;
3180 /***********************************************************************
3181 * XFONT_GetFontStruct
3183 XFontStruct* XFONT_GetFontStruct( X_PHYSFONT pFont )
3185 if( CHECK_PFONT(pFont) ) return __PFONT(pFont)->fs;
3186 return NULL;
3189 /***********************************************************************
3190 * XFONT_GetFontInfo
3192 LPIFONTINFO16 XFONT_GetFontInfo( X_PHYSFONT pFont )
3194 if( CHECK_PFONT(pFont) ) return &(__PFONT(pFont)->fi->df);
3195 return NULL;
3200 /* X11DRV Interface ****************************************************
3202 * Exposed via the dc->funcs dispatch table. *
3204 ***********************************************************************/
3205 /***********************************************************************
3206 * SelectFont (X11DRV.@)
3208 HFONT X11DRV_SelectFont( X11DRV_PDEVICE *physDev, HFONT hfont, HANDLE gdiFont )
3210 LOGFONTW logfont;
3211 LOGFONT16 lf;
3213 TRACE("hdc=%p, hfont=%p\n", physDev->hdc, hfont);
3215 if (!GetObjectW( hfont, sizeof(logfont), &logfont )) return HGDI_ERROR;
3217 TRACE("gdiFont = %p\n", gdiFont);
3219 if(gdiFont && using_client_side_fonts) {
3220 X11DRV_XRender_SelectFont(physDev, hfont);
3221 physDev->has_gdi_font = TRUE;
3222 return FALSE;
3225 EnterCriticalSection( &crtsc_fonts_X11 );
3227 if(fontList == NULL) X11DRV_FONT_InitX11Metrics();
3229 if( CHECK_PFONT(physDev->font) )
3230 XFONT_ReleaseCacheEntry( __PFONT(physDev->font) );
3232 FONT_LogFontWTo16(&logfont, &lf);
3234 /* stock fonts ignore the mapping mode */
3235 if (!is_stock_font( hfont ))
3237 /* Make sure we don't change the sign when converting to device coords */
3238 /* FIXME - check that the other drivers do this correctly */
3239 if (lf.lfWidth)
3241 INT width = X11DRV_XWStoDS( physDev, lf.lfWidth );
3242 lf.lfWidth = (lf.lfWidth < 0) ? -abs(width) : abs(width);
3243 if (lf.lfWidth == 0)
3244 lf.lfWidth = 1; /* Minimum width */
3246 if (lf.lfHeight)
3248 INT height = X11DRV_YWStoDS( physDev, lf.lfHeight );
3249 lf.lfHeight = (lf.lfHeight < 0) ? -abs(height) : abs(height);
3250 if (lf.lfHeight == 0)
3251 lf.lfHeight = MIN_FONT_SIZE;
3255 if (!lf.lfHeight)
3256 lf.lfHeight = -(DEF_POINT_SIZE * GetDeviceCaps(physDev->hdc,LOGPIXELSY) + (72>>1)) / 72;
3259 /* Fixup aliases before passing to RealizeFont */
3260 /* alias = Windows name in the alias table */
3261 LPCSTR alias = XFONT_UnAlias( lf.lfFaceName );
3262 LPCSTR faceMatched;
3263 WORD charsetMatched;
3265 TRACE("hfont=%p\n", hfont); /* to connect with the trace from RealizeFont */
3266 physDev->font = XFONT_RealizeFont( &lf, &faceMatched,
3267 FALSE, lf.lfCharSet,
3268 &charsetMatched );
3270 /* set face to the requested facename if it matched
3271 * so that GetTextFace can get the correct face name
3273 if (alias && !strcmp(faceMatched, lf.lfFaceName))
3274 MultiByteToWideChar(CP_ACP, 0, alias, -1,
3275 logfont.lfFaceName, LF_FACESIZE);
3276 else
3277 MultiByteToWideChar(CP_ACP, 0, faceMatched, -1,
3278 logfont.lfFaceName, LF_FACESIZE);
3281 * In X, some encodings may have the same lfFaceName.
3282 * for example:
3283 * -misc-fixed-*-iso8859-1
3284 * -misc-fixed-*-jisx0208.1990-0
3285 * so charset should be saved...
3287 logfont.lfCharSet = charsetMatched;
3290 LeaveCriticalSection( &crtsc_fonts_X11 );
3292 physDev->has_gdi_font = FALSE;
3293 return (HFONT)1; /* Use a device font */
3297 /***********************************************************************
3299 * X11DRV_EnumDeviceFonts
3301 BOOL X11DRV_EnumDeviceFonts( X11DRV_PDEVICE *physDev, LPLOGFONTW plf,
3302 FONTENUMPROCW proc, LPARAM lp )
3304 ENUMLOGFONTEXW lf;
3305 NEWTEXTMETRICEXW tm;
3306 fontResource* pfr = fontList;
3307 BOOL b, bRet = 0;
3309 /* don't enumerate x11 fonts if we're using client side fonts */
3310 if (physDev->has_gdi_font) return FALSE;
3312 if( plf->lfFaceName[0] )
3314 char facename[LF_FACESIZE+1];
3315 WideCharToMultiByte( CP_ACP, 0, plf->lfFaceName, -1,
3316 facename, sizeof(facename), NULL, NULL );
3317 /* enum all entries in this resource */
3318 pfr = XFONT_FindFIList( pfr, facename );
3319 if( pfr )
3321 fontInfo* pfi;
3322 for( pfi = pfr->fi; pfi; pfi = pfi->next )
3324 /* Note: XFONT_GetFontMetric() will have to
3325 release the crit section, font list will
3326 have to be retraversed on return */
3328 if(plf->lfCharSet == DEFAULT_CHARSET ||
3329 plf->lfCharSet == pfi->df.dfCharSet) {
3330 if( (b = (*proc)( &lf.elfLogFont, (TEXTMETRICW *)&tm,
3331 XFONT_GetFontMetric( pfi, &lf, &tm ), lp )) )
3332 bRet = b;
3333 else break;
3338 else /* enum first entry in each resource */
3339 for( ; pfr ; pfr = pfr->next )
3341 if(pfr->fi)
3343 if( (b = (*proc)( &lf.elfLogFont, (TEXTMETRICW *)&tm,
3344 XFONT_GetFontMetric( pfr->fi, &lf, &tm ), lp )) )
3345 bRet = b;
3346 else break;
3349 return bRet;
3353 /***********************************************************************
3354 * X11DRV_GetTextMetrics
3356 BOOL X11DRV_GetTextMetrics(X11DRV_PDEVICE *physDev, TEXTMETRICW *metrics)
3358 if( CHECK_PFONT(physDev->font) )
3360 fontObject* pfo = __PFONT(physDev->font);
3361 X11DRV_cptable[pfo->fi->cptable].pGetTextMetricsW( pfo, metrics );
3362 return TRUE;
3364 return FALSE;
3368 /***********************************************************************
3369 * X11DRV_GetCharWidth
3371 BOOL X11DRV_GetCharWidth( X11DRV_PDEVICE *physDev, UINT firstChar, UINT lastChar,
3372 LPINT buffer )
3374 fontObject* pfo = XFONT_GetFontObject( physDev->font );
3376 if( pfo )
3378 unsigned int i;
3380 if (pfo->fs->per_char == NULL)
3381 for (i = firstChar; i <= lastChar; i++)
3382 if(pfo->lpX11Trans)
3383 *buffer++ = pfo->fs->min_bounds.attributes *
3384 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3385 else
3386 *buffer++ = pfo->fs->min_bounds.width * pfo->rescale;
3387 else
3389 XCharStruct *cs, *def;
3390 static XCharStruct __null_char = { 0, 0, 0, 0, 0, 0 };
3392 CI_GET_CHAR_INFO(pfo->fs, pfo->fs->default_char, &__null_char,
3393 def);
3395 for (i = firstChar; i <= lastChar; i++)
3397 WCHAR wch = i;
3398 BYTE ch;
3399 UINT ch_f; /* character code in the font encoding */
3400 WideCharToMultiByte( pfo->fi->codepage, 0, &wch, 1, (LPSTR)&ch, 1, NULL, NULL );
3401 ch_f = ch;
3402 if (ch_f >= pfo->fs->min_char_or_byte2 &&
3403 ch_f <= pfo->fs->max_char_or_byte2)
3405 cs = &pfo->fs->per_char[(ch_f - pfo->fs->min_char_or_byte2)];
3406 if (CI_NONEXISTCHAR(cs)) cs = def;
3407 } else cs = def;
3408 if(pfo->lpX11Trans)
3409 *buffer++ = max(cs->attributes, 0) *
3410 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3411 else
3412 *buffer++ = max(cs->width, 0 ) * pfo->rescale;
3416 return TRUE;
3418 return FALSE;