Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / dlls / winex11.drv / xfont.c
blobdd9e1c644cd4a1dbe0d1f07fd5ed9763c29f87a7
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 "winerror.h"
45 #include "x11font.h"
46 #include "wine/library.h"
47 #include "wine/unicode.h"
48 #include "wine/debug.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(font);
52 #define X_PFONT_MAGIC (0xFADE0000)
53 #define X_FMC_MAGIC (0x0000CAFE)
55 #define MAX_FONTS 1024*16
56 #define MAX_LFD_LENGTH 256
57 #define TILDE '~'
58 #define HYPHEN '-'
60 #define DEF_POINT_SIZE 8 /* CreateFont(0 .. ) gets this */
61 #define DEF_SCALABLE_HEIGHT 100 /* pixels */
62 #define MIN_FONT_SIZE 2 /* Min size in pixels */
63 #define MAX_FONT_SIZE 1000 /* Max size in pixels */
65 #define REMOVE_SUBSETS 1
66 #define UNMARK_SUBSETS 0
68 #define FONTCACHE 32 /* dynamic font cache size */
70 #define FF_FAMILY (FF_MODERN | FF_SWISS | FF_ROMAN | FF_DECORATIVE | FF_SCRIPT)
72 typedef struct __fontAlias
74 LPSTR faTypeFace;
75 LPSTR faAlias;
76 struct __fontAlias* next;
77 } fontAlias;
79 static fontAlias *aliasTable = NULL;
81 static const char INIFontMetrics[] = "cachedmetrics.";
82 static const char INIFontSection[] = "Software\\Wine\\X11 Driver\\Fonts";
83 static const char INIFontPattern[] = "X11FontPattern";
84 static const char INIAliasSection[] = "Alias";
85 static const char INIIgnoreSection[] = "Ignore";
86 static const char INIDefault[] = "Default";
87 static const char INIDefaultFixed[] = "DefaultFixed";
88 static const char INIGlobalMetrics[] = "FontMetrics";
89 static const char INIDefaultSerif[] = "DefaultSerif";
90 static const char INIDefaultSansSerif[] = "DefaultSansSerif";
93 /* FIXME - are there any more Latin charsets ? */
94 /* FIXME - RUSSIAN, ARABIC, GREEK, HEBREW are NOT Latin */
95 #define IS_LATIN_CHARSET(ch) \
96 ((ch)==ANSI_CHARSET ||\
97 (ch)==EE_CHARSET ||\
98 (ch)==ISO3_CHARSET ||\
99 (ch)==ISO4_CHARSET ||\
100 (ch)==RUSSIAN_CHARSET ||\
101 (ch)==ARABIC_CHARSET ||\
102 (ch)==GREEK_CHARSET ||\
103 (ch)==HEBREW_CHARSET ||\
104 (ch)==TURKISH_CHARSET ||\
105 (ch)==ISO10_CHARSET ||\
106 (ch)==BALTIC_CHARSET ||\
107 (ch)==CELTIC_CHARSET)
109 /* suffix-charset mapping tables - must be less than 254 entries long */
111 typedef struct __sufch
113 LPCSTR psuffix;
114 WORD charset; /* hibyte != 0 means *internal* charset */
115 WORD codepage;
116 WORD cptable;
117 } SuffixCharset;
119 static const SuffixCharset sufch_ansi[] = {
120 { "0", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
121 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
123 static const SuffixCharset sufch_iso646[] = {
124 { "irv", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
125 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
127 static const SuffixCharset sufch_iso8859[] = {
128 { "1", ANSI_CHARSET, 28591, X11DRV_CPTABLE_SBCS },
129 { "2", EE_CHARSET, 28592, X11DRV_CPTABLE_SBCS },
130 { "3", ISO3_CHARSET, 28593, X11DRV_CPTABLE_SBCS },
131 { "4", ISO4_CHARSET, 28594, X11DRV_CPTABLE_SBCS },
132 { "5", RUSSIAN_CHARSET, 28595, X11DRV_CPTABLE_SBCS },
133 { "6", ARABIC_CHARSET, 28596, X11DRV_CPTABLE_SBCS },
134 { "7", GREEK_CHARSET, 28597, X11DRV_CPTABLE_SBCS },
135 { "8", HEBREW_CHARSET, 28598, X11DRV_CPTABLE_SBCS },
136 { "9", TURKISH_CHARSET, 28599, X11DRV_CPTABLE_SBCS },
137 { "10", ISO10_CHARSET, 28600, X11DRV_CPTABLE_SBCS },
138 { "11", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
139 { "12", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
140 { "13", BALTIC_CHARSET, 28603, X11DRV_CPTABLE_SBCS },
141 { "14", CELTIC_CHARSET, 28604, X11DRV_CPTABLE_SBCS },
142 { "15", ANSI_CHARSET, 28605, X11DRV_CPTABLE_SBCS },
143 { "16", ISO3_CHARSET, 28606, X11DRV_CPTABLE_SBCS },
144 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
146 static const SuffixCharset sufch_microsoft[] = {
147 { "cp1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
148 { "cp1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
149 { "cp1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
150 { "cp1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
151 { "cp1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
152 { "cp1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
153 { "cp1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
154 { "cp1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
155 { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SYMBOL },
156 { "symbol", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SYMBOL },
157 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
159 static const SuffixCharset sufch_tcvn[] = {
160 { "0", TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
161 { NULL, TCVN_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
163 static const SuffixCharset sufch_tis620[] = {
164 { "0", THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }, /* FIXME */
165 { NULL, THAI_CHARSET, 874, X11DRV_CPTABLE_SBCS }};
167 static const SuffixCharset sufch_viscii[] = {
168 { "1", VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }, /* FIXME */
169 { NULL, VISCII_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
171 static const SuffixCharset sufch_windows[] = {
172 { "1250", EE_CHARSET, 1250, X11DRV_CPTABLE_SBCS },
173 { "1251", RUSSIAN_CHARSET, 1251, X11DRV_CPTABLE_SBCS },
174 { "1252", ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS },
175 { "1253", GREEK_CHARSET, 1253, X11DRV_CPTABLE_SBCS },
176 { "1254", TURKISH_CHARSET, 1254, X11DRV_CPTABLE_SBCS },
177 { "1255", HEBREW_CHARSET, 1255, X11DRV_CPTABLE_SBCS },
178 { "1256", ARABIC_CHARSET, 1256, X11DRV_CPTABLE_SBCS },
179 { "1257", BALTIC_CHARSET, 1257, X11DRV_CPTABLE_SBCS },
180 { NULL, ANSI_CHARSET, 1252, X11DRV_CPTABLE_SBCS }};
182 static const SuffixCharset sufch_koi8[] = {
183 { "r", RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS },
184 { "ru", RUSSIAN_CHARSET, 21866, X11DRV_CPTABLE_SBCS },
185 { "u", RUSSIAN_CHARSET, 21866, X11DRV_CPTABLE_SBCS },
186 { NULL, RUSSIAN_CHARSET, 20866, X11DRV_CPTABLE_SBCS }};
188 static const SuffixCharset sufch_jisx0201[] = {
189 { "0", X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS },
190 { NULL, X11FONT_JISX0201_CHARSET, 932, X11DRV_CPTABLE_SBCS }};
192 static const SuffixCharset sufch_jisx0208[] = {
193 { "0", SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 },
194 { NULL, SHIFTJIS_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
196 static const SuffixCharset sufch_jisx0212[] = {
197 { "0", X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 },
198 { NULL, X11FONT_JISX0212_CHARSET, 932, X11DRV_CPTABLE_CP932 }};
200 static const SuffixCharset sufch_ksc5601[] = {
201 { "0", HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 },
202 { NULL, HANGEUL_CHARSET, 949, X11DRV_CPTABLE_CP949 }};
204 static const SuffixCharset sufch_gb2312[] = {
205 { "0", GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 },
206 { NULL, GB2312_CHARSET, 936, X11DRV_CPTABLE_CP936 }};
208 static const SuffixCharset sufch_big5[] = {
209 { "0", CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 },
210 { NULL, CHINESEBIG5_CHARSET, 950, X11DRV_CPTABLE_CP950 }};
212 static const SuffixCharset sufch_unicode[] = {
213 { "0", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
214 { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
216 static const SuffixCharset sufch_iso10646[] = {
217 { "1", DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE },
218 { NULL, DEFAULT_CHARSET, 0, X11DRV_CPTABLE_UNICODE }};
220 static const SuffixCharset sufch_dec[] = {
221 { "dectech", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
222 { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
224 /* Each of these must be matched explicitly */
225 static const SuffixCharset sufch_any[] = {
226 { "fontspecific", SYMBOL_CHARSET, CP_SYMBOL, X11DRV_CPTABLE_SBCS },
227 { NULL, 0, 0, X11DRV_CPTABLE_SBCS }};
230 typedef struct __fet
232 LPCSTR prefix;
233 const SuffixCharset* sufch;
234 const struct __fet* next;
235 } fontEncodingTemplate;
237 /* Note: we can attach additional encoding mappings to the end
238 * of this table at runtime.
240 static const fontEncodingTemplate fETTable[] = {
241 { "ansi", sufch_ansi, &fETTable[1] },
242 { "ascii", sufch_ansi, &fETTable[2] },
243 { "iso646.1991", sufch_iso646, &fETTable[3] },
244 { "iso8859", sufch_iso8859, &fETTable[4] },
245 { "microsoft", sufch_microsoft, &fETTable[5] },
246 { "tcvn", sufch_tcvn, &fETTable[6] },
247 { "tis620.2533", sufch_tis620, &fETTable[7] },
248 { "viscii1.1", sufch_viscii, &fETTable[8] },
249 { "windows", sufch_windows, &fETTable[9] },
250 { "koi8", sufch_koi8, &fETTable[10]},
251 { "jisx0201.1976",sufch_jisx0201, &fETTable[11]},
252 { "jisc6226.1978",sufch_jisx0208, &fETTable[12]},
253 { "jisx0208.1983",sufch_jisx0208, &fETTable[13]},
254 { "jisx0208.1990",sufch_jisx0208, &fETTable[14]},
255 { "jisx0212.1990",sufch_jisx0212, &fETTable[15]},
256 { "ksc5601.1987", sufch_ksc5601, &fETTable[16]},
257 { "gb2312.1980", sufch_gb2312, &fETTable[17]},
258 { "big5", sufch_big5, &fETTable[18]},
259 { "unicode", sufch_unicode, &fETTable[19]},
260 { "iso10646", sufch_iso10646, &fETTable[20]},
261 { "cp", sufch_windows, &fETTable[21]},
262 { "dec", sufch_dec, &fETTable[22]},
263 /* NULL prefix matches anything so put it last */
264 { NULL, sufch_any, NULL },
267 /* a charset database for known facenames */
268 struct CharsetBindingInfo
270 const char* pszFaceName;
271 BYTE charset;
273 static const struct CharsetBindingInfo charsetbindings[] =
275 /* special facenames */
276 { "System", DEFAULT_CHARSET },
277 { "FixedSys", DEFAULT_CHARSET },
279 /* known facenames */
280 { "MS Serif", ANSI_CHARSET },
281 { "MS Sans Serif", ANSI_CHARSET },
282 { "Courier", ANSI_CHARSET },
283 { "Symbol", SYMBOL_CHARSET },
285 { "Arial", ANSI_CHARSET },
286 { "Arial Greek", GREEK_CHARSET },
287 { "Arial Tur", TURKISH_CHARSET },
288 { "Arial Baltic", BALTIC_CHARSET },
289 { "Arial CE", EASTEUROPE_CHARSET },
290 { "Arial Cyr", RUSSIAN_CHARSET },
291 { "Courier New", ANSI_CHARSET },
292 { "Courier New Greek", GREEK_CHARSET },
293 { "Courier New Tur", TURKISH_CHARSET },
294 { "Courier New Baltic", BALTIC_CHARSET },
295 { "Courier New CE", EASTEUROPE_CHARSET },
296 { "Courier New Cyr", RUSSIAN_CHARSET },
297 { "Times New Roman", ANSI_CHARSET },
298 { "Times New Roman Greek", GREEK_CHARSET },
299 { "Times New Roman Tur", TURKISH_CHARSET },
300 { "Times New Roman Baltic", BALTIC_CHARSET },
301 { "Times New Roman CE", EASTEUROPE_CHARSET },
302 { "Times New Roman Cyr", RUSSIAN_CHARSET },
304 { "\x82\x6c\x82\x72 \x83\x53\x83\x56\x83\x62\x83\x4e",
305 SHIFTJIS_CHARSET }, /* MS gothic */
306 { "\x82\x6c\x82\x72 \x82\x6f\x83\x53\x83\x56\x83\x62\x83\x4e",
307 SHIFTJIS_CHARSET }, /* MS P gothic */
308 { "\x82\x6c\x82\x72 \x96\xbe\x92\xa9",
309 SHIFTJIS_CHARSET }, /* MS mincho */
310 { "\x82\x6c\x82\x72 \x82\x6f\x96\xbe\x92\xa9",
311 SHIFTJIS_CHARSET }, /* MS P mincho */
312 { "GulimChe", HANGEUL_CHARSET },
313 { "MS Song", GB2312_CHARSET },
314 { "MS Hei", GB2312_CHARSET },
315 { "\xb7\x73\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },/*MS Mingliu*/
316 { "\xb2\xd3\xa9\xfa\xc5\xe9", CHINESEBIG5_CHARSET },
318 { NULL, 0 }
322 static int DefResolution = 0;
324 static CRITICAL_SECTION crtsc_fonts_X11;
325 static CRITICAL_SECTION_DEBUG critsect_debug =
327 0, 0, &crtsc_fonts_X11,
328 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
329 0, 0, { (DWORD_PTR)(__FILE__ ": crtsc_fonts_X11") }
331 static CRITICAL_SECTION crtsc_fonts_X11 = { &critsect_debug, -1, 0, 0, 0, 0 };
333 static fontResource* fontList = NULL;
334 static fontObject* fontCache = NULL; /* array */
335 static unsigned int fontCacheSize = FONTCACHE;
336 static int fontLF = -1, fontMRU = -1; /* last free, most recently used */
338 #define __PFONT(pFont) ( fontCache + ((UINT)(pFont) & 0x0000FFFF) )
339 #define CHECK_PFONT(pFont) ( (((UINT)(pFont) & 0xFFFF0000) == X_PFONT_MAGIC) &&\
340 (((UINT)(pFont) & 0x0000FFFF) < fontCacheSize) )
342 /***********************************************************************
343 * Helper macros from X distribution
346 #define CI_NONEXISTCHAR(cs) (((cs)->width == 0) && \
347 (((cs)->rbearing|(cs)->lbearing| \
348 (cs)->ascent|(cs)->descent) == 0))
350 #define CI_GET_CHAR_INFO(fs,col,def,cs) \
352 cs = def; \
353 if (col >= fs->min_char_or_byte2 && col <= fs->max_char_or_byte2) { \
354 if (fs->per_char == NULL) { \
355 cs = &fs->min_bounds; \
356 } else { \
357 cs = &fs->per_char[(col - fs->min_char_or_byte2)]; \
358 if (CI_NONEXISTCHAR(cs)) cs = def; \
363 #define CI_GET_DEFAULT_INFO(fs,cs) \
364 CI_GET_CHAR_INFO(fs, fs->default_char, NULL, cs)
367 /***********************************************************************
368 * is_stock_font
370 static inline BOOL is_stock_font( HFONT font )
372 int i;
373 for (i = OEM_FIXED_FONT; i <= DEFAULT_GUI_FONT; i++)
375 if (i != DEFAULT_PALETTE && font == GetStockObject(i)) return TRUE;
377 return FALSE;
381 static void FONT_LogFontWTo16( const LOGFONTW* font32, LPLOGFONT16 font16 )
383 font16->lfHeight = font32->lfHeight;
384 font16->lfWidth = font32->lfWidth;
385 font16->lfEscapement = font32->lfEscapement;
386 font16->lfOrientation = font32->lfOrientation;
387 font16->lfWeight = font32->lfWeight;
388 font16->lfItalic = font32->lfItalic;
389 font16->lfUnderline = font32->lfUnderline;
390 font16->lfStrikeOut = font32->lfStrikeOut;
391 font16->lfCharSet = font32->lfCharSet;
392 font16->lfOutPrecision = font32->lfOutPrecision;
393 font16->lfClipPrecision = font32->lfClipPrecision;
394 font16->lfQuality = font32->lfQuality;
395 font16->lfPitchAndFamily = font32->lfPitchAndFamily;
396 WideCharToMultiByte( CP_ACP, 0, font32->lfFaceName, -1,
397 font16->lfFaceName, LF_FACESIZE, NULL, NULL );
398 font16->lfFaceName[LF_FACESIZE-1] = 0;
402 /***********************************************************************
403 * Checksums
405 static UINT16 __lfCheckSum( const LOGFONT16 *plf )
407 CHAR font[LF_FACESIZE];
408 UINT16 checksum = 0;
409 const UINT16 *ptr;
410 int i;
412 ptr = (const UINT16 *)plf;
413 for (i = 0; i < 9; i++) checksum ^= *ptr++;
414 for (i = 0; i < LF_FACESIZE; i++)
416 font[i] = tolower(plf->lfFaceName[i]);
417 if (!font[i] || font[i] == ' ') break;
419 for (ptr = (UINT16 *)font, i >>= 1; i > 0; i-- ) checksum ^= *ptr++;
420 return checksum;
423 static UINT16 __genericCheckSum( const void *ptr, int size )
425 unsigned int checksum = 0;
426 const char *p = (const char *)ptr;
427 while (size-- > 0)
428 checksum ^= (checksum << 3) + (checksum >> 29) + *p++;
430 return checksum & 0xffff;
433 /*************************************************************************
434 * LFD parse/compose routines
436 * NB. LFD_Parse will use lpFont for its own ends, so if you want to keep it
437 * make a copy first
439 * These functions also do TILDE to HYPHEN conversion
441 static BOOL LFD_Parse(LPSTR lpFont, LFD *lfd)
443 char *lpch = lpFont, *lfd_fld[LFD_FIELDS], *field_start;
444 int i;
445 if (*lpch != HYPHEN)
447 WARN("font '%s' doesn't begin with '%c'\n", lpFont, HYPHEN);
448 return FALSE;
451 field_start = ++lpch;
452 for( i = 0; i < LFD_FIELDS; )
454 if (*lpch == HYPHEN)
456 *lpch = '\0';
457 lfd_fld[i] = field_start;
458 i++;
459 field_start = ++lpch;
461 else if (!*lpch)
463 lfd_fld[i] = field_start;
464 i++;
465 break;
467 else if (*lpch == TILDE)
469 *lpch = HYPHEN;
470 ++lpch;
472 else
473 ++lpch;
475 /* Fill in the empty fields with NULLS */
476 for (; i< LFD_FIELDS; i++)
477 lfd_fld[i] = NULL;
478 if (*lpch)
479 WARN("Extra ignored in font '%s'\n", lpFont);
481 lfd->foundry = lfd_fld[0];
482 lfd->family = lfd_fld[1];
483 lfd->weight = lfd_fld[2];
484 lfd->slant = lfd_fld[3];
485 lfd->set_width = lfd_fld[4];
486 lfd->add_style = lfd_fld[5];
487 lfd->pixel_size = lfd_fld[6];
488 lfd->point_size = lfd_fld[7];
489 lfd->resolution_x = lfd_fld[8];
490 lfd->resolution_y = lfd_fld[9];
491 lfd->spacing = lfd_fld[10];
492 lfd->average_width = lfd_fld[11];
493 lfd->charset_registry = lfd_fld[12];
494 lfd->charset_encoding = lfd_fld[13];
495 return TRUE;
499 static void LFD_UnParse(LPSTR dp, UINT buf_size, LFD* lfd)
501 const char* lfd_fld[LFD_FIELDS];
502 int i;
504 if (!buf_size)
505 return; /* Don't be silly */
507 lfd_fld[0] = lfd->foundry;
508 lfd_fld[1] = lfd->family;
509 lfd_fld[2] = lfd->weight ;
510 lfd_fld[3] = lfd->slant ;
511 lfd_fld[4] = lfd->set_width ;
512 lfd_fld[5] = lfd->add_style;
513 lfd_fld[6] = lfd->pixel_size;
514 lfd_fld[7] = lfd->point_size;
515 lfd_fld[8] = lfd->resolution_x;
516 lfd_fld[9] = lfd->resolution_y ;
517 lfd_fld[10] = lfd->spacing ;
518 lfd_fld[11] = lfd->average_width ;
519 lfd_fld[12] = lfd->charset_registry ;
520 lfd_fld[13] = lfd->charset_encoding ;
522 buf_size--; /* Room for the terminator */
524 for (i = 0; i < LFD_FIELDS; i++)
526 const char* sp = lfd_fld[i];
527 if (!sp || !buf_size)
528 break;
530 *dp++ = HYPHEN;
531 buf_size--;
532 while (buf_size > 0 && *sp)
534 *dp = (*sp == HYPHEN) ? TILDE : *sp;
535 buf_size--;
536 dp++; sp++;
539 *dp = '\0';
543 static void LFD_GetWeight( fontInfo* fi, LPCSTR lpStr)
545 int j = strlen(lpStr);
546 if( j == 1 && *lpStr == '0')
547 fi->fi_flags |= FI_POLYWEIGHT;
548 else if( j == 4 )
550 if( !strcasecmp( "bold", lpStr) )
551 fi->df.dfWeight = FW_BOLD;
552 else if( !strcasecmp( "demi", lpStr) )
554 fi->fi_flags |= FI_FW_DEMI;
555 fi->df.dfWeight = FW_DEMIBOLD;
557 else if( !strcasecmp( "book", lpStr) )
559 fi->fi_flags |= FI_FW_BOOK;
560 fi->df.dfWeight = FW_REGULAR;
563 else if( j == 5 )
565 if( !strcasecmp( "light", lpStr) )
566 fi->df.dfWeight = FW_LIGHT;
567 else if( !strcasecmp( "black", lpStr) )
568 fi->df.dfWeight = FW_BLACK;
570 else if( j == 6 && !strcasecmp( "medium", lpStr) )
571 fi->df.dfWeight = FW_REGULAR;
572 else if( j == 8 && !strcasecmp( "demibold", lpStr) )
573 fi->df.dfWeight = FW_DEMIBOLD;
574 else
575 fi->df.dfWeight = FW_DONTCARE; /* FIXME: try to get something
576 * from the weight property */
579 static BOOL LFD_GetSlant( fontInfo* fi, LPCSTR lpStr)
581 int l = strlen(lpStr);
582 if( l == 1 )
584 switch( tolower( *lpStr ) )
586 case '0': fi->fi_flags |= FI_POLYSLANT; /* haven't seen this one yet */
587 default:
588 case 'r': fi->df.dfItalic = 0;
589 break;
590 case 'o':
591 fi->fi_flags |= FI_OBLIQUE;
592 case 'i': fi->df.dfItalic = 1;
593 break;
595 return FALSE;
597 return TRUE;
600 static void LFD_GetStyle( fontInfo* fi, LPCSTR lpstr, int dec_style_check)
602 int j = strlen(lpstr);
603 if( j > 3 ) /* find out is there "sans" or "script" */
605 j = 0;
607 if( strstr(lpstr, "sans") )
609 fi->df.dfPitchAndFamily |= FF_SWISS;
610 j = 1;
612 if( strstr(lpstr, "script") )
614 fi->df.dfPitchAndFamily |= FF_SCRIPT;
615 j = 1;
617 if( !j && dec_style_check )
618 fi->df.dfPitchAndFamily |= FF_DECORATIVE;
622 /*************************************************************************
623 * LFD_InitFontInfo
625 * INIT ONLY
627 * Fill in some fields in the fontInfo struct.
629 static int LFD_InitFontInfo( fontInfo* fi, const LFD* lfd, LPCSTR fullname )
631 int i, j, dec_style_check, scalability;
632 const fontEncodingTemplate* boba;
633 const char* ridiculous = "font '%s' has ridiculous %s\n";
634 const char* lpstr;
636 if (!lfd->charset_registry)
638 WARN("font '%s' does not have enough fields\n", fullname);
639 return FALSE;
642 memset(fi, 0, sizeof(fontInfo) );
644 /* weight name - */
645 LFD_GetWeight( fi, lfd->weight);
647 /* slant - */
648 dec_style_check = LFD_GetSlant( fi, lfd->slant);
650 /* width name - */
651 lpstr = lfd->set_width;
652 if( strcasecmp( "normal", lpstr) ) /* XXX 'narrow', 'condensed', etc... */
653 dec_style_check = TRUE;
654 else
655 fi->fi_flags |= FI_NORMAL;
657 /* style - */
658 LFD_GetStyle(fi, lfd->add_style, dec_style_check);
660 /* pixel & decipoint height, and res_x & y */
662 scalability = 0;
664 j = strlen(lfd->pixel_size);
665 if( j == 0 || j > 3 )
667 WARN(ridiculous, fullname, "pixel_size");
668 return FALSE;
670 if( !(fi->lfd_height = atoi(lfd->pixel_size)) )
671 scalability++;
673 j = strlen(lfd->point_size);
674 if( j == 0 || j > 3 )
676 WARN(ridiculous, fullname, "point_size");
677 return FALSE;
679 if( !(atoi(lfd->point_size)) )
680 scalability++;
682 j = strlen(lfd->resolution_x);
683 if( j == 0 || j > 3 )
685 WARN(ridiculous, fullname, "resolution_x");
686 return FALSE;
688 if( !(fi->lfd_resolution = atoi(lfd->resolution_x)) )
689 scalability++;
691 j = strlen(lfd->resolution_y);
692 if( j == 0 || j > 3 )
694 WARN(ridiculous, fullname, "resolution_y");
695 return FALSE;
697 if( !(atoi(lfd->resolution_y)) )
698 scalability++;
700 /* Check scalability */
701 switch (scalability)
703 case 0: /* Bitmap */
704 break;
705 case 4: /* Scalable */
706 fi->fi_flags |= FI_SCALABLE;
707 break;
708 case 2:
709 /* #$%^!!! X11R6 mutant garbage (scalable bitmap) */
710 TRACE("Skipping scalable bitmap '%s'\n", fullname);
711 return FALSE;
712 default:
713 WARN("Font '%s' has weird scalability\n", fullname);
714 return FALSE;
717 /* spacing - */
718 lpstr = lfd->spacing;
719 switch( *lpstr )
721 case '\0':
722 WARN("font '%s' has no spacing\n", fullname);
723 return FALSE;
725 case 'p': fi->fi_flags |= FI_VARIABLEPITCH;
726 break;
727 case 'c': fi->df.dfPitchAndFamily |= FF_MODERN;
728 fi->fi_flags |= FI_FIXEDEX;
729 /* fall through */
730 case 'm': fi->fi_flags |= FI_FIXEDPITCH;
731 break;
732 default:
733 /* Of course this line does nothing */
734 fi->df.dfPitchAndFamily |= DEFAULT_PITCH | FF_DONTCARE;
737 /* average width - */
738 lpstr = lfd->average_width;
739 j = strlen(lpstr);
740 if( j == 0 || j > 3 )
742 WARN(ridiculous, fullname, "average_width");
743 return FALSE;
746 if( !(atoi(lpstr)) && !scalability )
748 WARN("font '%s' has average_width 0 but is not scalable!!\n", fullname);
749 return FALSE;
752 /* charset registry, charset encoding - */
753 lpstr = lfd->charset_registry;
754 if( strstr(lpstr, "ksc") ||
755 strstr(lpstr, "gb2312") ||
756 strstr(lpstr, "big5") )
758 FIXME("DBCS fonts like '%s' are not working correctly now.\n", fullname);
761 fi->df.dfCharSet = ANSI_CHARSET;
763 for( i = 0, boba = &fETTable[0]; boba; boba = boba->next, i++ )
765 if (!boba->prefix || !strcasecmp(lpstr, boba->prefix))
767 if (lfd->charset_encoding)
769 for( j = 0; boba->sufch[j].psuffix; j++ )
771 if( !strcasecmp(lfd->charset_encoding, boba->sufch[j].psuffix ))
773 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
774 fi->internal_charset = boba->sufch[j].charset;
775 fi->codepage = boba->sufch[j].codepage;
776 fi->cptable = boba->sufch[j].cptable;
777 goto done;
781 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
782 fi->internal_charset = boba->sufch[j].charset;
783 fi->codepage = boba->sufch[j].codepage;
784 fi->cptable = boba->sufch[j].cptable;
785 if (boba->prefix)
787 FIXME("font '%s' has unknown character encoding '%s' in known registry '%s'\n",
788 fullname, lfd->charset_encoding, boba->prefix);
789 j = 254;
791 else
793 FIXME("font '%s' has unknown registry '%s' and character encoding '%s'\n",
794 fullname, lfd->charset_registry, lfd->charset_encoding);
795 j = 255;
798 WARN("Defaulting to: df.dfCharSet = %d, internal_charset = %d, codepage = %d, cptable = %d\n",
799 fi->df.dfCharSet,fi->internal_charset, fi->codepage, fi->cptable);
800 goto done;
802 else if (boba->prefix)
804 WARN("font '%s' has known registry '%s' and no character encoding\n",
805 fullname, lpstr);
806 for( j = 0; boba->sufch[j].psuffix; j++ )
808 fi->df.dfCharSet = (BYTE)(boba->sufch[j].charset & 0xff);
809 fi->internal_charset = boba->sufch[j].charset;
810 fi->codepage = boba->sufch[j].codepage;
811 fi->cptable = boba->sufch[j].cptable;
812 j = 255;
813 goto done;
817 WARN("font '%s' has unknown character set '%s'\n", fullname, lpstr);
818 return FALSE;
820 done:
821 /* i - index into fETTable
822 * j - index into suffix array for fETTable[i]
823 * except:
824 * 254 - found encoding prefix, unknown suffix
825 * 255 - no encoding match at all.
827 fi->fi_encoding = 256 * (UINT16)i + (UINT16)j;
829 return TRUE;
833 /*************************************************************************
834 * LFD_AngleMatrix
836 * make a matrix suitable for LFD based on theta radians
838 static void LFD_AngleMatrix( char* buffer, int h, double theta)
840 double matrix[4];
841 matrix[0] = h*cos(theta);
842 matrix[1] = h*sin(theta);
843 matrix[2] = -h*sin(theta);
844 matrix[3] = h*cos(theta);
845 sprintf(buffer, "[%+f%+f%+f%+f]", matrix[0], matrix[1], matrix[2], matrix[3]);
848 /*************************************************************************
849 * LFD_ComposeLFD
851 * Note: uRelax is a treatment not a cure. Font mapping algorithm
852 * should be bulletproof enough to allow us to avoid hacks like
853 * this despite LFD being so braindead.
855 static BOOL LFD_ComposeLFD( const fontObject* fo,
856 INT height, LPSTR lpLFD, UINT uRelax )
858 int i, h;
859 const char *any = "*";
860 char h_string[64], resx_string[64], resy_string[64];
861 LFD aLFD;
862 const fontEncodingTemplate* boba = &fETTable[0];
864 /* Get the worst case over with first */
866 /* RealizeFont() will call us repeatedly with increasing uRelax
867 * until XLoadFont() succeeds.
868 * to avoid an infinite loop; these will always match
870 if (uRelax >= 6)
872 if (uRelax == 6)
873 sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-1" );
874 else
875 sprintf( lpLFD, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*" );
876 return TRUE;
879 /* read foundry + family from fo */
880 aLFD.foundry = fo->fr->resource->foundry;
881 aLFD.family = fo->fr->resource->family;
883 /* add weight */
884 switch( fo->fi->df.dfWeight )
886 case FW_BOLD:
887 aLFD.weight = "bold"; break;
888 case FW_REGULAR:
889 if( fo->fi->fi_flags & FI_FW_BOOK )
890 aLFD.weight = "book";
891 else
892 aLFD.weight = "medium";
893 break;
894 case FW_DEMIBOLD:
895 aLFD.weight = "demi";
896 if( !( fo->fi->fi_flags & FI_FW_DEMI) )
897 aLFD.weight = "bold";
898 break;
899 case FW_BLACK:
900 aLFD.weight = "black"; break;
901 case FW_LIGHT:
902 aLFD.weight = "light"; break;
903 default:
904 aLFD.weight = any;
907 /* add slant */
908 if( fo->fi->df.dfItalic )
909 if( fo->fi->fi_flags & FI_OBLIQUE )
910 aLFD.slant = "o";
911 else
912 aLFD.slant = "i";
913 else
914 aLFD.slant = (uRelax <= 1) ? "r" : any;
916 /* add width */
917 if( fo->fi->fi_flags & FI_NORMAL )
918 aLFD.set_width = "normal";
919 else
920 aLFD.set_width = any;
922 /* ignore style */
923 aLFD.add_style = any;
925 /* add pixelheight
927 * FIXME: fill in lpXForm and lpPixmap for rotated fonts
929 if( fo->fo_flags & FO_SYNTH_HEIGHT )
930 h = fo->fi->lfd_height;
931 else
933 h = (fo->fi->lfd_height * height + (fo->fi->df.dfPixHeight>>1));
934 h /= fo->fi->df.dfPixHeight;
936 if (h < MIN_FONT_SIZE) /* Resist rounding down to 0 */
937 h = MIN_FONT_SIZE;
938 else if (h > MAX_FONT_SIZE) /* Sanity check as huge fonts can lock up the font server */
940 WARN("Huge font size %d pixels has been reduced to %d\n", h, MAX_FONT_SIZE);
941 h = MAX_FONT_SIZE;
944 if (uRelax <= 3)
945 /* handle rotated fonts */
946 if (fo->lf.lfEscapement) {
947 /* escapement is in tenths of degrees, theta is in radians */
948 double theta = M_PI*fo->lf.lfEscapement/1800.;
949 LFD_AngleMatrix(h_string, h, theta);
951 else
953 sprintf(h_string, "%d", h);
955 else
956 sprintf(h_string, "%d", fo->fi->lfd_height);
958 aLFD.pixel_size = h_string;
959 aLFD.point_size = any;
961 /* resolution_x,y, average width */
962 /* FIXME - Why do some font servers ignore average width ?
963 * so that you have to mess around with res_y
965 aLFD.average_width = any;
966 if (uRelax <= 4)
968 sprintf(resx_string, "%d", fo->fi->lfd_resolution);
969 aLFD.resolution_x = resx_string;
971 strcpy(resy_string, resx_string);
972 if( uRelax == 0 && text_caps & TC_SF_X_YINDEP )
974 if( fo->lf.lfWidth && !(fo->fo_flags & FO_SYNTH_WIDTH))
976 int resy = 0.5 + fo->fi->lfd_resolution *
977 (fo->fi->df.dfAvgWidth * height) /
978 (fo->lf.lfWidth * fo->fi->df.dfPixHeight) ;
979 sprintf(resy_string, "%d", resy);
981 else
983 /* FIXME - synth width */
986 aLFD.resolution_y = resy_string;
988 else
990 aLFD.resolution_x = aLFD.resolution_y = any;
993 /* spacing */
995 const char* w;
997 if( fo->fi->fi_flags & FI_FIXEDPITCH )
998 w = ( fo->fi->fi_flags & FI_FIXEDEX ) ? "c" : "m";
999 else
1000 w = ( fo->fi->fi_flags & FI_VARIABLEPITCH ) ? "p" : any;
1002 aLFD.spacing = (uRelax <= 2) ? w : any;
1005 /* encoding */
1007 for(i = fo->fi->fi_encoding >> 8; i; i--) boba = boba->next;
1008 aLFD.charset_registry = boba->prefix ? boba->prefix : any;
1010 i = fo->fi->fi_encoding & 255;
1011 switch( i ) {
1012 default:
1013 aLFD.charset_encoding = boba->sufch[i].psuffix;
1014 break;
1016 case 254:
1017 aLFD.charset_encoding = any;
1018 break;
1020 case 255: /* no suffix - it ends eg "-ascii" */
1021 aLFD.charset_encoding = NULL;
1022 break;
1025 LFD_UnParse(lpLFD, MAX_LFD_LENGTH, &aLFD);
1027 TRACE("\tLFD(uRelax=%d): %s\n", uRelax, lpLFD );
1028 return TRUE;
1032 /***********************************************************************
1033 * X Font Resources
1035 * font info - http://www.microsoft.com/kb/articles/q65/1/23.htm
1036 * Windows font metrics - http://www.microsoft.com/kb/articles/q32/6/67.htm
1038 static void XFONT_GetLeading( const IFONTINFO16 *pFI, const XFontStruct* x_fs,
1039 INT16* pIL, INT16* pEL, const XFONTTRANS *XFT )
1041 unsigned long height;
1042 unsigned min = (unsigned char)pFI->dfFirstChar;
1043 unsigned max = (unsigned char)pFI->dfLastChar;
1044 BOOL bIsLatin = IS_LATIN_CHARSET(pFI->dfCharSet);
1046 if( pEL ) *pEL = 0;
1048 if(XFT) {
1049 wine_tsx11_lock();
1050 if(XGetFontProperty((XFontStruct*)x_fs, x11drv_atom(RAW_CAP_HEIGHT), &height))
1051 *pIL = XFT->ascent -
1052 (INT)(XFT->pixelsize / 1000.0 * height);
1053 else
1054 *pIL = 0;
1055 wine_tsx11_unlock();
1056 return;
1059 wine_tsx11_lock();
1060 if( XGetFontProperty((XFontStruct*)x_fs, XA_CAP_HEIGHT, &height) == FALSE )
1062 if( x_fs->per_char )
1063 if( bIsLatin && ((unsigned char)'X' <= (max - min)) )
1064 height = x_fs->per_char['X' - min].ascent;
1065 else
1066 if (x_fs->ascent >= x_fs->max_bounds.ascent)
1067 height = x_fs->max_bounds.ascent;
1068 else
1070 height = x_fs->ascent;
1071 if( pEL )
1072 *pEL = x_fs->max_bounds.ascent - height;
1074 else
1075 height = x_fs->min_bounds.ascent;
1077 wine_tsx11_unlock();
1079 *pIL = x_fs->ascent - height;
1082 /***********************************************************************
1083 * XFONT_CharWidth
1085 static int XFONT_CharWidth(const XFontStruct* x_fs,
1086 const XFONTTRANS *XFT, int ch)
1088 if(!XFT)
1089 return x_fs->per_char[ch].width;
1090 else
1091 return x_fs->per_char[ch].attributes * XFT->pixelsize / 1000.0;
1094 /***********************************************************************
1095 * XFONT_GetAvgCharWidth
1097 static INT XFONT_GetAvgCharWidth( LPIFONTINFO16 pFI, const XFontStruct* x_fs,
1098 const XFONTTRANS *XFT)
1100 unsigned min = (unsigned char)pFI->dfFirstChar;
1101 unsigned max = (unsigned char)pFI->dfLastChar;
1103 INT avg;
1105 if( x_fs->per_char )
1107 unsigned int width = 0, chars = 0, j;
1108 if( (IS_LATIN_CHARSET(pFI->dfCharSet) ||
1109 pFI->dfCharSet == DEFAULT_CHARSET) &&
1110 (max - min) >= (unsigned char)'z' )
1112 /* FIXME - should use a weighted average */
1113 for( j = 0; j < 26; j++ )
1114 width += XFONT_CharWidth(x_fs, XFT, 'a' + j - min) +
1115 XFONT_CharWidth(x_fs, XFT, 'A' + j - min);
1116 chars = 52;
1118 else /* unweighted average of everything */
1120 for( j = 0, max -= min; j <= max; j++ )
1121 if( !CI_NONEXISTCHAR(x_fs->per_char + j) )
1123 width += XFONT_CharWidth(x_fs, XFT, j);
1124 chars++;
1127 if (chars) avg = (width + (chars-1))/ chars; /* always round up*/
1128 else avg = 0; /* No characters exist at all */
1130 else /* uniform width */
1131 avg = x_fs->min_bounds.width;
1133 TRACE(" retuning %d\n",avg);
1134 return avg;
1137 /***********************************************************************
1138 * XFONT_GetMaxCharWidth
1140 static INT XFONT_GetMaxCharWidth(const XFontStruct* xfs, const XFONTTRANS *XFT)
1142 unsigned min = (unsigned char)xfs->min_char_or_byte2;
1143 unsigned max = (unsigned char)xfs->max_char_or_byte2;
1144 unsigned int maxwidth, j;
1146 if(!XFT || !xfs->per_char)
1147 return abs(xfs->max_bounds.width);
1149 for( j = 0, maxwidth = 0, max -= min; j <= max; j++ )
1150 if( !CI_NONEXISTCHAR(xfs->per_char + j) )
1151 if(maxwidth < xfs->per_char[j].attributes)
1152 maxwidth = xfs->per_char[j].attributes;
1154 maxwidth *= XFT->pixelsize / 1000.0;
1155 return maxwidth;
1158 /***********************************************************************
1159 * XFONT_SetFontMetric
1161 * INIT ONLY
1163 * Initializes IFONTINFO16.
1165 static void XFONT_SetFontMetric(fontInfo* fi, const fontResource* fr, XFontStruct* xfs)
1167 unsigned min, max;
1168 fi->df.dfFirstChar = (BYTE)(min = xfs->min_char_or_byte2);
1169 fi->df.dfLastChar = (BYTE)(max = xfs->max_char_or_byte2);
1171 fi->df.dfDefaultChar = (BYTE)xfs->default_char;
1172 fi->df.dfBreakChar = (BYTE)(( ' ' < min || ' ' > max) ? xfs->default_char: ' ');
1174 fi->df.dfPixHeight = (INT16)((fi->df.dfAscent = (INT16)xfs->ascent) + xfs->descent);
1175 fi->df.dfPixWidth = (xfs->per_char) ? 0 : xfs->min_bounds.width;
1177 XFONT_GetLeading( &fi->df, xfs, &fi->df.dfInternalLeading, &fi->df.dfExternalLeading, NULL );
1178 fi->df.dfAvgWidth = (INT16)XFONT_GetAvgCharWidth(&fi->df, xfs, NULL );
1179 fi->df.dfMaxWidth = (INT16)XFONT_GetMaxCharWidth(xfs, NULL);
1181 if( xfs->min_bounds.width != xfs->max_bounds.width )
1182 fi->df.dfPitchAndFamily |= TMPF_FIXED_PITCH; /* au contraire! */
1183 if( fi->fi_flags & FI_SCALABLE )
1185 fi->df.dfType = DEVICE_FONTTYPE;
1186 fi->df.dfPitchAndFamily |= TMPF_DEVICE;
1188 else if( fi->fi_flags & FI_TRUETYPE )
1189 fi->df.dfType = TRUETYPE_FONTTYPE;
1190 else
1191 fi->df.dfType = RASTER_FONTTYPE;
1193 fi->df.dfFace = fr->lfFaceName;
1196 /***********************************************************************
1197 * XFONT_GetFontMetric
1199 * Retrieve font metric info (enumeration).
1201 static UINT XFONT_GetFontMetric( const fontInfo* pfi,
1202 LPENUMLOGFONTEXW pLF,
1203 NEWTEXTMETRICEXW *pTM )
1205 memset( pLF, 0, sizeof(*pLF) );
1206 memset( pTM, 0, sizeof(*pTM) );
1208 #define plf ((LPLOGFONTW)pLF)
1209 #define ptm ((LPNEWTEXTMETRICW)pTM)
1210 plf->lfHeight = ptm->tmHeight = pfi->df.dfPixHeight;
1211 plf->lfWidth = ptm->tmAveCharWidth = pfi->df.dfAvgWidth;
1212 plf->lfWeight = ptm->tmWeight = pfi->df.dfWeight;
1213 plf->lfItalic = ptm->tmItalic = pfi->df.dfItalic;
1214 plf->lfUnderline = ptm->tmUnderlined = pfi->df.dfUnderline;
1215 plf->lfStrikeOut = ptm->tmStruckOut = pfi->df.dfStrikeOut;
1216 plf->lfCharSet = ptm->tmCharSet = pfi->df.dfCharSet;
1218 /* convert pitch values */
1220 ptm->tmPitchAndFamily = pfi->df.dfPitchAndFamily;
1221 plf->lfPitchAndFamily = (pfi->df.dfPitchAndFamily & 0xF1) + 1;
1223 MultiByteToWideChar(CP_ACP, 0, pfi->df.dfFace, -1,
1224 plf->lfFaceName, LF_FACESIZE);
1226 /* FIXME: fill in rest of plF values */
1227 strcpyW(pLF->elfFullName, plf->lfFaceName);
1228 MultiByteToWideChar(CP_ACP, 0, "Regular", -1,
1229 pLF->elfStyle, LF_FACESIZE);
1230 MultiByteToWideChar(CP_ACP, 0, plf->lfCharSet == SYMBOL_CHARSET ?
1231 "Symbol" : "Roman", -1,
1232 pLF->elfScript, LF_FACESIZE);
1234 #undef plf
1236 ptm->tmAscent = pfi->df.dfAscent;
1237 ptm->tmDescent = ptm->tmHeight - ptm->tmAscent;
1238 ptm->tmInternalLeading = pfi->df.dfInternalLeading;
1239 ptm->tmMaxCharWidth = pfi->df.dfMaxWidth;
1240 ptm->tmDigitizedAspectX = pfi->df.dfHorizRes;
1241 ptm->tmDigitizedAspectY = pfi->df.dfVertRes;
1243 ptm->tmFirstChar = pfi->df.dfFirstChar;
1244 ptm->tmLastChar = pfi->df.dfLastChar;
1245 ptm->tmDefaultChar = pfi->df.dfDefaultChar;
1246 ptm->tmBreakChar = pfi->df.dfBreakChar;
1248 TRACE("Calling Enum proc with FaceName %s FullName %s\n",
1249 debugstr_w(pLF->elfLogFont.lfFaceName),
1250 debugstr_w(pLF->elfFullName));
1252 TRACE("CharSet = %d type = %d\n", ptm->tmCharSet, pfi->df.dfType);
1253 /* return font type */
1254 return pfi->df.dfType;
1255 #undef ptm
1259 /***********************************************************************
1260 * XFONT_FixupFlags
1262 * INIT ONLY
1264 * dfPitchAndFamily flags for some common typefaces.
1266 static BYTE XFONT_FixupFlags( LPCSTR lfFaceName )
1268 switch( lfFaceName[0] )
1270 case 'a':
1271 case 'A': if(!strncasecmp(lfFaceName, "Arial", 5) )
1272 return FF_SWISS;
1273 break;
1274 case 'h':
1275 case 'H': if(!strcasecmp(lfFaceName, "Helvetica") )
1276 return FF_SWISS;
1277 break;
1278 case 'c':
1279 case 'C': if(!strncasecmp(lfFaceName, "Courier", 7))
1280 return FF_MODERN;
1282 if (!strcasecmp(lfFaceName, "Charter") )
1283 return FF_ROMAN;
1284 break;
1285 case 'p':
1286 case 'P': if( !strcasecmp(lfFaceName,"Palatino") )
1287 return FF_ROMAN;
1288 break;
1289 case 't':
1290 case 'T': if(!strncasecmp(lfFaceName, "Times", 5) )
1291 return FF_ROMAN;
1292 break;
1293 case 'u':
1294 case 'U': if(!strcasecmp(lfFaceName, "Utopia") )
1295 return FF_ROMAN;
1296 break;
1297 case 'z':
1298 case 'Z': if(!strcasecmp(lfFaceName, "Zapf Dingbats") )
1299 return FF_DECORATIVE;
1301 return 0;
1304 /***********************************************************************
1305 * XFONT_SameFoundryAndFamily
1307 * INIT ONLY
1309 static BOOL XFONT_SameFoundryAndFamily( const LFD* lfd1, const LFD* lfd2 )
1311 return ( !strcasecmp( lfd1->foundry, lfd2->foundry ) &&
1312 !strcasecmp( lfd1->family, lfd2->family ) );
1315 /***********************************************************************
1316 * XFONT_InitialCapitals
1318 * INIT ONLY
1320 * Upper case first letters of words & remove multiple spaces
1322 static void XFONT_InitialCapitals(LPSTR lpch)
1324 int i;
1325 BOOL up;
1326 char* lpstr = lpch;
1328 for( i = 0, up = TRUE; *lpch; lpch++, i++ )
1330 if( isspace(*lpch) )
1332 if (!up) /* Not already got one */
1334 *lpstr++ = ' ';
1335 up = TRUE;
1338 else if( isalpha(*lpch) && up )
1340 *lpstr++ = toupper(*lpch);
1341 up = FALSE;
1343 else
1345 *lpstr++ = *lpch;
1346 up = FALSE;
1350 /* Remove possible trailing space */
1351 if (up && i > 0)
1352 --lpstr;
1353 *lpstr = '\0';
1357 /***********************************************************************
1358 * XFONT_WindowsNames
1360 * INIT ONLY
1362 * Build generic Windows aliases for X font names.
1364 * -misc-fixed- -> "Fixed"
1365 * -sony-fixed- -> "Sony Fixed", etc...
1367 static void XFONT_WindowsNames(void)
1369 fontResource* fr;
1371 for( fr = fontList; fr ; fr = fr->next )
1373 fontResource* pfr;
1374 char* lpch;
1376 if( fr->fr_flags & FR_NAMESET ) continue; /* skip already assigned */
1378 for( pfr = fontList; pfr != fr ; pfr = pfr->next )
1379 if( pfr->fr_flags & FR_NAMESET )
1381 if (!strcasecmp( pfr->resource->family, fr->resource->family))
1382 break;
1385 lpch = fr->lfFaceName;
1386 snprintf( fr->lfFaceName, sizeof(fr->lfFaceName), "%s %s",
1387 /* prepend vendor name */
1388 (pfr==fr) ? "" : fr->resource->foundry,
1389 fr->resource->family);
1390 XFONT_InitialCapitals(fr->lfFaceName);
1392 BYTE bFamilyStyle = XFONT_FixupFlags( fr->lfFaceName );
1393 if( bFamilyStyle)
1395 fontInfo* fi;
1396 for( fi = fr->fi ; fi ; fi = fi->next )
1397 fi->df.dfPitchAndFamily |= bFamilyStyle;
1401 TRACE("typeface '%s'\n", fr->lfFaceName);
1403 fr->fr_flags |= FR_NAMESET;
1407 /***********************************************************************
1408 * XFONT_LoadDefaultLFD
1410 * Move lfd to the head of fontList to make it more likely to be matched
1412 static void XFONT_LoadDefaultLFD(LFD* lfd, LPCSTR fonttype)
1415 fontResource *fr, *pfr;
1416 for( fr = NULL, pfr = fontList; pfr; pfr = pfr->next )
1418 if( XFONT_SameFoundryAndFamily(pfr->resource, lfd) )
1420 if( fr )
1422 fr->next = pfr->next;
1423 pfr->next = fontList;
1424 fontList = pfr;
1426 break;
1428 fr = pfr;
1430 if (!pfr)
1431 WARN("Default %sfont '-%s-%s-' not available\n", fonttype,
1432 lfd->foundry, lfd->family);
1436 /***********************************************************************
1437 * XFONT_LoadDefault
1439 static void XFONT_LoadDefault( HKEY hkey, LPCSTR ini, LPCSTR fonttype)
1441 char buffer[MAX_LFD_LENGTH];
1442 DWORD type, count = sizeof(buffer);
1444 buffer[0] = 0;
1445 RegQueryValueExA(hkey, ini, 0, &type, (LPBYTE)buffer, &count);
1447 if (*buffer)
1449 LFD lfd;
1450 char* pch = buffer;
1451 while( *pch && isspace(*pch) ) pch++;
1453 TRACE("Using '%s' as default %sfont\n", pch, fonttype);
1454 if (LFD_Parse(pch, &lfd) && lfd.foundry && lfd.family)
1455 XFONT_LoadDefaultLFD(&lfd, fonttype);
1456 else
1457 WARN("Ini section [%s]%s is malformed\n", INIFontSection, ini);
1461 /***********************************************************************
1462 * XFONT_LoadDefaults
1464 static void XFONT_LoadDefaults( HKEY hkey )
1466 XFONT_LoadDefault( hkey, INIDefaultFixed, "fixed ");
1467 XFONT_LoadDefault( hkey, INIDefault, "");
1470 /***********************************************************************
1471 * XFONT_CreateAlias
1473 static fontAlias* XFONT_CreateAlias( LPCSTR lpTypeFace, LPCSTR lpAlias )
1475 int j;
1476 fontAlias *pfa, *prev = NULL;
1478 for(pfa = aliasTable; pfa; pfa = pfa->next)
1480 /* check if we already got one */
1481 if( !strcasecmp( pfa->faTypeFace, lpAlias ) )
1483 TRACE("redundant alias '%s' -> '%s'\n",
1484 lpAlias, lpTypeFace );
1485 return NULL;
1487 prev = pfa;
1490 j = strlen(lpTypeFace) + 1;
1491 pfa = HeapAlloc( GetProcessHeap(), 0, sizeof(fontAlias) +
1492 j + strlen(lpAlias) + 1 );
1493 if (pfa)
1495 if (!prev)
1496 aliasTable = pfa;
1497 else
1498 prev->next = pfa;
1500 pfa->next = NULL;
1501 pfa->faTypeFace = (LPSTR)(pfa + 1);
1502 strcpy( pfa->faTypeFace, lpTypeFace );
1503 pfa->faAlias = pfa->faTypeFace + j;
1504 strcpy( pfa->faAlias, lpAlias );
1506 TRACE("added alias '%s' for '%s'\n", lpAlias, lpTypeFace );
1508 return pfa;
1510 return NULL;
1514 /***********************************************************************
1515 * XFONT_LoadAlias
1517 static void XFONT_LoadAlias(const LFD* lfd, LPCSTR lpAlias, BOOL bSubst)
1519 fontResource *fr, *frMatch = NULL;
1520 if (!lfd->foundry || ! lfd->family)
1522 WARN("Malformed font resource for alias '%s'\n", lpAlias);
1523 return;
1525 for (fr = fontList; fr ; fr = fr->next)
1527 if(!strcasecmp(fr->resource->family, lpAlias))
1529 /* alias is not needed since the real font is present */
1530 TRACE("Ignoring font alias '%s' as it is already available as a real font\n", lpAlias);
1531 return;
1533 if( XFONT_SameFoundryAndFamily( fr->resource, lfd ) )
1535 frMatch = fr;
1536 break;
1540 if( frMatch )
1542 if( bSubst )
1544 fontAlias *pfa, *prev = NULL;
1546 for(pfa = aliasTable; pfa; pfa = pfa->next)
1548 /* Remove lpAlias from aliasTable - we should free the old entry */
1549 if(!strcmp(lpAlias, pfa->faAlias))
1551 if(prev)
1552 prev->next = pfa->next;
1553 else
1554 aliasTable = pfa->next;
1557 /* Update any references to the substituted font in aliasTable */
1558 if(!strcmp(frMatch->lfFaceName, pfa->faTypeFace))
1560 pfa->faTypeFace = HeapAlloc( GetProcessHeap(), 0, strlen(lpAlias)+1 );
1561 strcpy( pfa->faTypeFace, lpAlias );
1563 prev = pfa;
1566 TRACE("\tsubstituted '%s' with '%s'\n", frMatch->lfFaceName, lpAlias );
1568 lstrcpynA( frMatch->lfFaceName, lpAlias, LF_FACESIZE );
1569 frMatch->fr_flags |= FR_NAMESET;
1571 else
1573 /* create new entry in the alias table */
1574 XFONT_CreateAlias( frMatch->lfFaceName, lpAlias );
1577 else
1579 WARN("Font alias '-%s-%s-' is not available\n", lfd->foundry, lfd->family);
1583 /***********************************************************************
1584 * Just a copy of PROFILE_GetStringItem
1586 * Convenience function that turns a string 'xxx, yyy, zzz' into
1587 * the 'xxx\0 yyy, zzz' and returns a pointer to the 'yyy, zzz'.
1589 static char *XFONT_GetStringItem( char *start )
1591 #define XFONT_isspace(c) (isspace(c) || (c == '\r') || (c == 0x1a))
1592 char *lpchX, *lpch;
1594 for (lpchX = start, lpch = NULL; *lpchX != '\0'; lpchX++ )
1596 if( *lpchX == ',' )
1598 if( lpch ) *lpch = '\0'; else *lpchX = '\0';
1599 while( *(++lpchX) )
1600 if( !XFONT_isspace(*lpchX) ) return lpchX;
1602 else if( XFONT_isspace( *lpchX ) && !lpch ) lpch = lpchX;
1603 else lpch = NULL;
1605 if( lpch ) *lpch = '\0';
1606 return NULL;
1607 #undef XFONT_isspace
1610 /***********************************************************************
1611 * XFONT_LoadAliases
1613 * INIT ONLY
1615 * Create font aliases for some standard windows fonts using user's
1616 * default choice of (sans-)serif fonts
1618 * Read user-defined aliases from config file. Format is as follows
1620 * Alias# = [Windows font name],[LFD font name], <substitute original name>
1622 * Example:
1623 * Alias0 = Arial, -adobe-helvetica-
1624 * Alias1 = Times New Roman, -bitstream-courier-, 1
1625 * ...
1627 * Note that from 970817 and on we have built-in alias templates that take
1628 * care of the necessary Windows typefaces.
1630 typedef struct
1632 LPSTR fatResource;
1633 LPSTR fatAlias;
1634 } aliasTemplate;
1636 static void XFONT_LoadAliases( HKEY hkey )
1638 char *lpResource;
1639 char buffer[MAX_LFD_LENGTH];
1640 int i = 0;
1641 LFD lfd;
1643 /* built-ins first */
1644 strcpy(buffer, "-bitstream-charter-");
1645 if (hkey)
1647 DWORD type, count = sizeof(buffer);
1648 RegQueryValueExA(hkey, INIDefaultSerif, 0, &type, (LPBYTE)buffer, &count);
1650 TRACE("Using '%s' as default serif font\n", buffer);
1651 if (LFD_Parse(buffer, &lfd))
1653 /* NB XFONT_InitialCapitals should not change these standard aliases */
1654 XFONT_LoadAlias( &lfd, "Tms Roman", FALSE);
1655 XFONT_LoadAlias( &lfd, "MS Serif", FALSE);
1656 XFONT_LoadAlias( &lfd, "Times New Roman", FALSE);
1658 XFONT_LoadDefaultLFD( &lfd, "serif ");
1661 strcpy(buffer, "-adobe-helvetica-");
1662 if (hkey)
1664 DWORD type, count = sizeof(buffer);
1665 RegQueryValueExA(hkey, INIDefaultSansSerif, 0, &type, (LPBYTE)buffer, &count);
1667 TRACE("Using '%s' as default sans serif font\n", buffer);
1668 if (LFD_Parse(buffer, &lfd))
1670 XFONT_LoadAlias( &lfd, "Helv", FALSE);
1671 XFONT_LoadAlias( &lfd, "MS Sans Serif", FALSE);
1672 XFONT_LoadAlias( &lfd, "MS Shell Dlg", FALSE);
1673 XFONT_LoadAlias( &lfd, "System", FALSE);
1674 XFONT_LoadAlias( &lfd, "Arial", FALSE);
1676 XFONT_LoadDefaultLFD( &lfd, "sans serif ");
1679 /* then user specified aliases */
1682 BOOL bSubst;
1683 char subsection[32];
1684 snprintf( subsection, sizeof(subsection), "%s%i", INIAliasSection, i++ );
1686 buffer[0] = 0;
1687 if (hkey)
1689 DWORD type, count = sizeof(buffer);
1690 RegQueryValueExA(hkey, subsection, 0, &type, (LPBYTE)buffer, &count);
1693 if (!buffer[0])
1694 break;
1696 XFONT_InitialCapitals(buffer);
1697 lpResource = XFONT_GetStringItem( buffer );
1698 bSubst = (XFONT_GetStringItem( lpResource )) ? TRUE : FALSE;
1699 if( lpResource && *lpResource )
1701 if (LFD_Parse(lpResource, &lfd)) XFONT_LoadAlias(&lfd, buffer, bSubst);
1703 else
1704 WARN("malformed font alias '%s'\n", buffer );
1706 while(TRUE);
1709 /***********************************************************************
1710 * XFONT_UnAlias
1712 * Convert an (potential) alias into a real windows name
1715 static LPCSTR XFONT_UnAlias(char* font)
1717 if (font[0])
1719 fontAlias* fa;
1720 XFONT_InitialCapitals(font); /* to remove extra white space */
1722 for( fa = aliasTable; fa; fa = fa->next )
1723 /* use case insensitive matching to handle eg "MS Sans Serif" */
1724 if( !strcasecmp( fa->faAlias, font ) )
1726 TRACE("found alias '%s'->%s'\n", font, fa->faTypeFace );
1727 strcpy(font, fa->faTypeFace);
1728 return fa->faAlias;
1731 return NULL;
1734 /***********************************************************************
1735 * XFONT_RemoveFontResource
1737 * Caller should check if the font resource is in use. If it is it should
1738 * set FR_REMOVED flag to delay removal until the resource is not in use
1739 * any more.
1741 static void XFONT_RemoveFontResource( fontResource** ppfr )
1743 fontResource* pfr = *ppfr;
1744 #if 0
1745 fontInfo* pfi;
1747 /* FIXME - if fonts were read from a cache, these HeapFrees will fail */
1748 while( pfr->fi )
1750 pfi = pfr->fi->next;
1751 HeapFree( GetProcessHeap(), 0, pfr->fi );
1752 pfr->fi = pfi;
1754 HeapFree( GetProcessHeap(), 0, pfr );
1755 #endif
1756 *ppfr = pfr->next;
1759 /***********************************************************************
1760 * XFONT_LoadIgnores
1762 * INIT ONLY
1764 * Removes specified fonts from the font table to prevent Wine from
1765 * using it.
1767 * Ignore# = [LFD font name]
1769 * Example:
1770 * Ignore0 = -misc-nil-
1771 * Ignore1 = -sun-open look glyph-
1772 * ...
1775 static void XFONT_LoadIgnore(char* lfdname)
1777 fontResource** ppfr;
1778 LFD lfd;
1780 if (LFD_Parse(lfdname, &lfd) && lfd.foundry && lfd.family)
1782 for( ppfr = &fontList; *ppfr ; ppfr = &((*ppfr)->next))
1784 if( XFONT_SameFoundryAndFamily( (*ppfr)->resource, &lfd) )
1786 TRACE("Ignoring '-%s-%s-'\n",
1787 (*ppfr)->resource->foundry, (*ppfr)->resource->family );
1789 XFONT_RemoveFontResource( ppfr );
1790 break;
1794 else
1795 WARN("Malformed font resource\n");
1798 static void XFONT_LoadIgnores( HKEY hkey )
1800 int i = 0;
1801 char subsection[32];
1802 char buffer[MAX_LFD_LENGTH];
1804 /* Standard one that no one wants */
1805 strcpy(buffer, "-misc-nil-");
1806 XFONT_LoadIgnore(buffer);
1808 /* Others from INI file */
1809 if (!hkey) return;
1812 DWORD type, count = sizeof(buffer);
1813 sprintf( subsection, "%s%i", INIIgnoreSection, i++ );
1815 if (!RegQueryValueExA(hkey, subsection, 0, &type, (LPBYTE)buffer, &count))
1817 char* pch = buffer;
1818 while( *pch && isspace(*pch) ) pch++;
1819 XFONT_LoadIgnore(pch);
1821 else
1822 break;
1823 } while(TRUE);
1827 /***********************************************************************
1828 * XFONT_UserMetricsCache
1830 * Returns expanded name for the cachedmetrics file.
1831 * Now it also appends the current value of the $DISPLAY variable.
1833 static char* XFONT_UserMetricsCache( char* buffer, int* buf_size )
1835 const char *confdir = wine_get_config_dir();
1836 const char *display_name = XDisplayName(NULL);
1837 int len = strlen(confdir) + strlen(INIFontMetrics) + strlen(display_name) + 8;
1838 int display = 0;
1839 int screen = 0;
1840 char *p, *ext;
1843 ** Normalize the display name, since on Red Hat systems, DISPLAY
1844 ** is commonly set to one of either 'unix:0.0' or ':0' or ':0.0'.
1845 ** after this code, all of the above will resolve to ':0.0'.
1847 if (!strncmp( display_name, "unix:", 5 )) display_name += 4;
1848 p = strchr(display_name, ':');
1849 if (p) sscanf(p + 1, "%d.%d", &display, &screen);
1851 if ((len > *buf_size) &&
1852 !(buffer = HeapReAlloc( GetProcessHeap(), 0, buffer, *buf_size = len )))
1854 ERR("out of memory\n");
1855 ExitProcess(1);
1857 sprintf( buffer, "%s/%s", confdir, INIFontMetrics );
1859 ext = buffer + strlen(buffer);
1860 strcpy( ext, display_name );
1862 if (!(p = strchr( ext, ':' ))) p = ext + strlen(ext);
1863 sprintf( p, ":%d.%d", display, screen );
1864 return buffer;
1868 /***********************************************************************
1869 * X Font Matching
1871 * Compare two fonts (only parameters set by the XFONT_InitFontInfo()).
1873 static INT XFONT_IsSubset(const fontInfo* match, const fontInfo* fi)
1875 INT m;
1877 /* 0 - keep both, 1 - keep match, -1 - keep fi */
1879 /* Compare dfItalic, Underline, Strikeout, Weight, Charset */
1880 m = (const BYTE*)&fi->df.dfPixWidth - (const BYTE*)&fi->df.dfItalic;
1881 if( memcmp(&match->df.dfItalic, &fi->df.dfItalic, m )) return 0;
1883 if( (!((fi->fi_flags & FI_SCALABLE) + (match->fi_flags & FI_SCALABLE))
1884 && fi->lfd_height != match->lfd_height) ||
1885 (!((fi->fi_flags & FI_POLYWEIGHT) + (match->fi_flags & FI_POLYWEIGHT))
1886 && fi->df.dfWeight != match->df.dfWeight) ) return 0;
1888 m = (int)(match->fi_flags & (FI_POLYWEIGHT | FI_SCALABLE)) -
1889 (int)(fi->fi_flags & (FI_SCALABLE | FI_POLYWEIGHT));
1891 if( m == (FI_POLYWEIGHT - FI_SCALABLE) ||
1892 m == (FI_SCALABLE - FI_POLYWEIGHT) ) return 0; /* keep both */
1893 else if( m >= 0 ) return 1; /* 'match' is better */
1895 return -1; /* 'fi' is better */
1898 /***********************************************************************
1899 * XFONT_CheckFIList
1901 * REMOVE_SUBSETS - attach new fi and purge subsets
1902 * UNMARK_SUBSETS - remove subset flags from all fi entries
1904 static void XFONT_CheckFIList( fontResource* fr, fontInfo* fi, int action)
1906 int i = 0;
1907 fontInfo* pfi, *prev;
1909 for( prev = NULL, pfi = fr->fi; pfi; )
1911 if( action == REMOVE_SUBSETS )
1913 if( pfi->fi_flags & FI_SUBSET )
1915 fontInfo* subset = pfi;
1917 i++;
1918 fr->fi_count--;
1919 if( prev ) prev->next = pfi = pfi->next;
1920 else fr->fi = pfi = pfi->next;
1921 HeapFree( GetProcessHeap(), 0, subset );
1922 continue;
1925 else pfi->fi_flags &= ~FI_SUBSET;
1927 prev = pfi;
1928 pfi = pfi->next;
1931 if( action == REMOVE_SUBSETS ) /* also add the superset */
1933 if( fi->fi_flags & FI_SCALABLE )
1935 fi->next = fr->fi;
1936 fr->fi = fi;
1938 else if( prev ) prev->next = fi; else fr->fi = fi;
1939 fr->fi_count++;
1942 if( i ) TRACE("\t purged %i subsets [%i]\n", i , fr->fi_count);
1945 /***********************************************************************
1946 * XFONT_FindFIList
1948 static fontResource* XFONT_FindFIList( fontResource* pfr, const char* pTypeFace )
1950 while( pfr )
1952 if( !strcasecmp( pfr->lfFaceName, pTypeFace ) ) break;
1953 pfr = pfr->next;
1955 /* Give the app back the font name it asked for. Encarta checks this. */
1956 if (pfr) strcpy(pfr->lfFaceName,pTypeFace);
1957 return pfr;
1960 /***********************************************************************
1961 * XFONT_FixupPointSize
1963 static void XFONT_FixupPointSize(fontInfo* fi)
1965 #define df (fi->df)
1966 df.dfHorizRes = df.dfVertRes = fi->lfd_resolution;
1967 df.dfPoints = (INT16)
1968 (((INT)(df.dfPixHeight - df.dfInternalLeading) * 72 + (df.dfVertRes >> 1)) /
1969 df.dfVertRes );
1970 #undef df
1973 /***********************************************************************
1974 * XFONT_BuildMetrics
1976 * Build font metrics from X font
1978 static int XLoadQueryFont_ErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
1980 return 1;
1983 /* XLoadQueryFont has the bad habit of crashing when loading a bad font... */
1984 static XFontStruct *safe_XLoadQueryFont(Display *display, char *name)
1986 XFontStruct *ret;
1988 X11DRV_expect_error(display, XLoadQueryFont_ErrorHandler, NULL);
1989 ret = XLoadQueryFont(display, name);
1990 if (X11DRV_check_error()) ret = NULL;
1991 return ret;
1995 static int XFONT_BuildMetrics(char** x_pattern, int res, unsigned x_checksum, int x_count)
1997 int i;
1998 fontInfo* fi = NULL;
1999 fontResource* fr, *pfr;
2000 int n_ff = 0;
2002 MESSAGE("Building font metrics. This may take some time...\n");
2003 for( i = 0; i < x_count; i++ )
2005 char* typeface;
2006 LFD lfd;
2007 int j;
2008 char buffer[MAX_LFD_LENGTH];
2009 char* lpstr;
2010 XFontStruct* x_fs;
2011 fontInfo* pfi;
2013 if (!(typeface = HeapAlloc(GetProcessHeap(), 0, strlen(x_pattern[i])+1))) break;
2014 strcpy( typeface, x_pattern[i] );
2016 if (!LFD_Parse(typeface, &lfd))
2018 HeapFree(GetProcessHeap(), 0, typeface);
2019 continue;
2022 /* find a family to insert into */
2024 for( pfr = NULL, fr = fontList; fr; fr = fr->next )
2026 if( XFONT_SameFoundryAndFamily(fr->resource, &lfd))
2027 break;
2028 pfr = fr;
2031 if( !fi ) fi = HeapAlloc(GetProcessHeap(), 0, sizeof(fontInfo));
2033 if( !LFD_InitFontInfo( fi, &lfd, x_pattern[i]) )
2034 goto nextfont;
2036 if( !fr ) /* add new family */
2038 n_ff++;
2039 fr = HeapAlloc(GetProcessHeap(), 0, sizeof(fontResource));
2040 if (fr)
2042 memset(fr, 0, sizeof(fontResource));
2044 fr->resource = HeapAlloc(GetProcessHeap(), 0, sizeof(LFD));
2045 memset(fr->resource, 0, sizeof(LFD));
2047 TRACE("family: -%s-%s-\n", lfd.foundry, lfd.family );
2048 fr->resource->foundry = HeapAlloc(GetProcessHeap(), 0, strlen(lfd.foundry)+1);
2049 strcpy( (char *)fr->resource->foundry, lfd.foundry );
2050 fr->resource->family = HeapAlloc(GetProcessHeap(), 0, strlen(lfd.family)+1);
2051 strcpy( (char *)fr->resource->family, lfd.family );
2052 fr->resource->weight = "";
2054 if( pfr ) pfr->next = fr;
2055 else fontList = fr;
2057 else
2058 WARN("Not enough memory for a new font family\n");
2061 /* check if we already have something better than "fi" */
2063 for( pfi = fr->fi, j = 0; pfi && j <= 0; pfi = pfi->next )
2064 if( (j = XFONT_IsSubset( pfi, fi )) < 0 )
2065 pfi->fi_flags |= FI_SUBSET; /* superseded by "fi" */
2066 if( j > 0 ) goto nextfont;
2068 /* add new font instance "fi" to the "fr" font resource */
2070 if( fi->fi_flags & FI_SCALABLE )
2072 LFD lfd1;
2073 char pxl_string[4], res_string[4];
2074 /* set scalable font height to get a basis for extrapolation */
2076 fi->lfd_height = DEF_SCALABLE_HEIGHT;
2077 fi->lfd_resolution = res;
2079 sprintf(pxl_string, "%d", fi->lfd_height);
2080 sprintf(res_string, "%d", fi->lfd_resolution);
2082 lfd1 = lfd;
2083 lfd1.pixel_size = pxl_string;
2084 lfd1.point_size = "*";
2085 lfd1.resolution_x = res_string;
2086 lfd1.resolution_y = res_string;
2088 LFD_UnParse(buffer, sizeof(buffer), &lfd1);
2090 lpstr = buffer;
2092 else lpstr = x_pattern[i];
2094 /* X11 may return an error on some bad fonts... So be prepared to handle these. */
2095 if ((x_fs = safe_XLoadQueryFont(gdi_display, lpstr)) != 0)
2097 XFONT_SetFontMetric( fi, fr, x_fs );
2098 wine_tsx11_lock();
2099 XFreeFont( gdi_display, x_fs );
2100 wine_tsx11_unlock();
2102 XFONT_FixupPointSize(fi);
2104 TRACE("\t[% 2ipt] '%s'\n", fi->df.dfPoints, x_pattern[i] );
2106 XFONT_CheckFIList( fr, fi, REMOVE_SUBSETS );
2107 fi = NULL; /* preventing reuse */
2109 else
2111 ERR("failed to load %s\n", lpstr );
2113 XFONT_CheckFIList( fr, fi, UNMARK_SUBSETS );
2115 nextfont:
2116 HeapFree(GetProcessHeap(), 0, typeface);
2118 HeapFree(GetProcessHeap(), 0, fi);
2120 /* Scan through the font list and remove FontResource(s) (fr)
2121 * that have no associated Fontinfo(s) (fi).
2122 * This code is necessary because XFONT_ReadCachedMetrics
2123 * assumes that there is at least one fi associated with a fr.
2124 * This assumption is invalid for TT font
2125 * -altsys-ms outlook-medium-r-normal--0-0-0-0-p-0-microsoft-symbol.
2128 fr = fontList;
2130 while (!fr->fi_count)
2132 fontList = fr->next;
2134 HeapFree(GetProcessHeap(), 0, fr->resource);
2135 HeapFree(GetProcessHeap(), 0, fr);
2137 fr = fontList;
2138 n_ff--;
2141 fr = fontList;
2143 while (fr->next)
2145 if (!fr->next->fi_count)
2147 pfr = fr->next;
2148 fr->next = fr->next->next;
2150 HeapFree(GetProcessHeap(), 0, pfr->resource);
2151 HeapFree(GetProcessHeap(), 0, pfr);
2153 n_ff--;
2155 else
2156 fr = fr->next;
2159 MESSAGE("Font metrics: 100.0%% done\n");
2160 return n_ff;
2163 /***********************************************************************
2164 * XFONT_ReadCachedMetrics
2166 * INIT ONLY
2168 static BOOL XFONT_ReadCachedMetrics( int fd, int res, unsigned x_checksum, int x_count )
2170 if( fd >= 0 )
2172 unsigned u;
2173 int i, j;
2175 /* read checksums */
2176 read( fd, &u, sizeof(unsigned) );
2177 read( fd, &i, sizeof(int) );
2179 if( u == x_checksum && i == x_count )
2181 off_t length, offset = 3 * sizeof(int);
2183 /* read total size */
2184 read( fd, &i, sizeof(int) );
2185 length = lseek( fd, 0, SEEK_END );
2187 if( length == (i + offset) )
2189 lseek( fd, offset, SEEK_SET );
2190 fontList = HeapAlloc( GetProcessHeap(), 0, i);
2191 if( fontList )
2193 fontResource* pfr = fontList;
2194 fontInfo* pfi = NULL;
2196 TRACE("Reading cached font metrics:\n");
2198 read( fd, fontList, i); /* read all metrics at once */
2199 while( offset < length )
2201 offset += sizeof(fontResource) + sizeof(fontInfo);
2202 pfr->fi = pfi = (fontInfo*)(pfr + 1);
2203 j = 1;
2204 while( TRUE )
2206 if( offset > length ||
2207 pfi->cptable >= (UINT16)X11DRV_CPTABLE_COUNT ||
2208 (int)(pfi->next) != j++ )
2210 TRACE("error: offset=%ld length=%ld cptable=%d pfi->next=%d j=%d\n",(long)offset,(long)length,pfi->cptable,(int)pfi->next,j-1);
2211 goto fail;
2214 if( pfi->df.dfPixHeight == 0 )
2216 TRACE("error: dfPixHeight==0\n");
2217 goto fail;
2220 pfi->df.dfFace = pfr->lfFaceName;
2221 if( pfi->fi_flags & FI_SCALABLE )
2223 /* we can pretend we got this font for any resolution */
2224 pfi->lfd_resolution = res;
2225 XFONT_FixupPointSize(pfi);
2227 pfi->next = pfi + 1;
2229 if( j > pfr->fi_count ) break;
2231 pfi = pfi->next;
2232 offset += sizeof(fontInfo);
2234 pfi->next = NULL;
2235 if( pfr->next )
2237 pfr->next = (fontResource*)(pfi + 1);
2238 pfr = pfr->next;
2240 else break;
2242 if( pfr->next == NULL &&
2243 *(int*)(pfi + 1) == X_FMC_MAGIC )
2245 /* read LFD stubs */
2246 char* lpch = (char*)((int*)(pfi + 1) + 1);
2247 offset += sizeof(int);
2248 for( pfr = fontList; pfr; pfr = pfr->next )
2250 size_t len = strlen(lpch) + 1;
2251 TRACE("\t%s, %i instances\n", lpch, pfr->fi_count );
2252 pfr->resource = HeapAlloc(GetProcessHeap(),0,sizeof(LFD));
2253 if (!LFD_Parse(lpch, pfr->resource))
2255 HeapFree( GetProcessHeap(), 0, pfr->resource );
2256 pfr->resource = NULL;
2258 lpch += len;
2259 offset += len;
2260 if (offset > length)
2262 TRACE("error: offset=%ld length=%ld\n",(long)offset,(long)length);
2263 goto fail;
2266 close( fd );
2267 return TRUE;
2270 } else {
2271 TRACE("Wrong length: %ld!=%ld\n",(long)length,(long)(i+offset));
2273 } else {
2274 TRACE("Checksum (%x vs. %x) or count (%d vs. %d) mismatch\n",
2275 u,x_checksum,i,x_count);
2277 fail:
2278 HeapFree( GetProcessHeap(), 0, fontList );
2279 fontList = NULL;
2280 close( fd );
2282 return FALSE;
2285 /***********************************************************************
2286 * XFONT_WriteCachedMetrics
2288 * INIT ONLY
2290 static BOOL XFONT_WriteCachedMetrics( int fd, unsigned x_checksum, int x_count, int n_ff )
2292 fontResource* pfr;
2293 fontInfo* pfi;
2295 if( fd >= 0 )
2297 int i, j, k;
2298 char buffer[MAX_LFD_LENGTH];
2300 /* font metrics file:
2302 * +0000 x_checksum
2303 * +0004 x_count
2304 * +0008 total size to load
2305 * +000C prepackaged font metrics
2306 * ...
2307 * +...x X_FMC_MAGIC
2308 * +...x + 4 LFD stubs
2311 write( fd, &x_checksum, sizeof(unsigned) );
2312 write( fd, &x_count, sizeof(int) );
2314 for( j = i = 0, pfr = fontList; pfr; pfr = pfr->next )
2316 LFD_UnParse(buffer, sizeof(buffer), pfr->resource);
2317 i += strlen( buffer) + 1;
2318 j += pfr->fi_count;
2320 i += n_ff * sizeof(fontResource) + j * sizeof(fontInfo) + sizeof(int);
2321 write( fd, &i, sizeof(int) );
2323 TRACE("Writing font cache:\n");
2325 for( pfr = fontList; pfr; pfr = pfr->next )
2327 fontInfo fi;
2329 TRACE("\t-%s-%s-, %i instances\n", pfr->resource->foundry, pfr->resource->family, pfr->fi_count );
2331 i = write( fd, pfr, sizeof(fontResource) );
2332 if( i == sizeof(fontResource) )
2334 for( k = 1, pfi = pfr->fi; pfi; pfi = pfi->next )
2336 fi = *pfi;
2338 fi.df.dfFace = NULL;
2339 fi.next = (fontInfo*)k; /* loader checks this */
2341 j = write( fd, &fi, sizeof(fi) );
2342 k++;
2344 if( j == sizeof(fontInfo) ) continue;
2346 break;
2348 if( i == sizeof(fontResource) && j == sizeof(fontInfo) )
2350 i = j = X_FMC_MAGIC;
2351 write( fd, &i, sizeof(int) );
2352 for( pfr = fontList; pfr && i == j; pfr = pfr->next )
2354 LFD_UnParse(buffer, sizeof(buffer), pfr->resource);
2355 i = strlen( buffer ) + 1;
2356 j = write( fd, buffer, i );
2359 close( fd );
2360 return ( i == j );
2362 return FALSE;
2365 /***********************************************************************
2366 * XFONT_GetDefResolution()
2368 * INIT ONLY
2370 * Here we initialize DefResolution which is used in the
2371 * XFONT_Match() penalty function, based on the values of log_pixels
2373 static int XFONT_GetDefResolution( int log_pixels_x, int log_pixels_y )
2375 int i, j, num = 3;
2376 int allowed_xfont_resolutions[3] = { 72, 75, 100 };
2377 int best = 0, best_diff = 65536;
2379 /* FIXME We can only really guess at a best DefResolution
2380 * - this should be configurable
2382 for( i = best = 0; i < num; i++ )
2384 j = abs( log_pixels_x - allowed_xfont_resolutions[i] );
2385 if( j < best_diff )
2387 best = i;
2388 best_diff = j;
2391 DefResolution = allowed_xfont_resolutions[best];
2392 return DefResolution;
2396 /***********************************************************************
2397 * XFONT_Match
2399 * Compute the matching score between the logical font and the device font.
2401 * contributions from highest to lowest:
2402 * charset
2403 * fixed pitch
2404 * height
2405 * family flags (only when the facename is not present)
2406 * width
2407 * weight, italics, underlines, strikeouts
2409 * NOTE: you can experiment with different penalty weights to see what happens.
2410 * http://premium.microsoft.com/msdn/library/techart/f365/f36b/f37b/d38b/sa8bf.htm
2412 static UINT XFONT_Match( fontMatch* pfm )
2414 fontInfo* pfi = pfm->pfi; /* device font to match */
2415 LPLOGFONT16 plf = pfm->plf; /* wanted logical font */
2416 UINT penalty = 0;
2417 BOOL bR6 = pfm->flags & FO_MATCH_XYINDEP; /* from text_caps */
2418 BOOL bScale = pfi->fi_flags & FI_SCALABLE;
2419 int d = 0, height;
2421 TRACE("\t[ %-2ipt h=%-3i w=%-3i %s%s]\n", pfi->df.dfPoints,
2422 pfi->df.dfPixHeight, pfi->df.dfAvgWidth,
2423 (pfi->df.dfWeight > FW_NORMAL) ? "Bold " : "Normal ",
2424 (pfi->df.dfItalic) ? "Italic" : "" );
2426 pfm->flags &= FO_MATCH_MASK;
2428 /* Charset */
2429 /* pfm->internal_charset: given(required) charset */
2430 /* pfi->internal_charset: charset of this font */
2431 if (pfi->internal_charset == DEFAULT_CHARSET)
2433 /* special case(unicode font) */
2434 /* priority: unmatched charset < unicode < matched charset */
2435 penalty += 0x50;
2437 else
2439 if( pfm->internal_charset == DEFAULT_CHARSET )
2442 if (pfi->internal_charset != ANSI_CHARSET)
2443 penalty += 0x200;
2445 if ( pfi->codepage != GetACP() )
2446 penalty += 0x200;
2448 else if (pfm->internal_charset != pfi->internal_charset)
2450 if ( pfi->internal_charset & 0xff00 )
2451 penalty += 0x1000; /* internal charset - should not be used */
2452 else
2453 penalty += 0x200;
2457 /* Height */
2458 height = -1;
2460 if( plf->lfHeight > 0 )
2462 int h = pfi->df.dfPixHeight;
2463 d = h - plf->lfHeight;
2464 height = plf->lfHeight;
2466 else
2468 int h = pfi->df.dfPixHeight - pfi->df.dfInternalLeading;
2469 if (h)
2471 d = h + plf->lfHeight;
2472 height = (-plf->lfHeight * pfi->df.dfPixHeight) / h;
2474 else
2476 ERR("PixHeight == InternalLeading\n");
2477 penalty += 0x1000; /* don't want this */
2482 if( height == 0 )
2483 pfm->height = 1; /* Very small */
2484 else if( d )
2486 if( bScale )
2487 pfm->height = height;
2488 else if( (plf->lfQuality != PROOF_QUALITY) && bR6 )
2490 if( d > 0 ) /* do not shrink raster fonts */
2492 pfm->height = pfi->df.dfPixHeight;
2493 penalty += (pfi->df.dfPixHeight - height) * 0x4;
2495 else /* expand only in integer multiples */
2497 pfm->height = height - height%pfi->df.dfPixHeight;
2498 penalty += (height - pfm->height + 1) * height / pfi->df.dfPixHeight;
2501 else /* can't be scaled at all */
2503 if( plf->lfQuality != PROOF_QUALITY) pfm->flags |= FO_SYNTH_HEIGHT;
2504 pfm->height = pfi->df.dfPixHeight;
2505 penalty += (d > 0)? d * 0x8 : -d * 0x10;
2508 else
2509 pfm->height = pfi->df.dfPixHeight;
2511 /* Pitch and Family */
2512 if( pfm->flags & FO_MATCH_PAF ) {
2513 int family = plf->lfPitchAndFamily & FF_FAMILY;
2515 /* TMPF_FIXED_PITCH means exactly the opposite */
2516 if( plf->lfPitchAndFamily & FIXED_PITCH ) {
2517 if( pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH ) penalty += 0x100;
2518 } else /* Variable is the default */
2519 if( !(pfi->df.dfPitchAndFamily & TMPF_FIXED_PITCH) ) penalty += 0x2;
2521 if (family != FF_DONTCARE && family != (pfi->df.dfPitchAndFamily & FF_FAMILY) )
2522 penalty += 0x10;
2525 /* Width */
2526 if( plf->lfWidth )
2528 int h;
2529 if( bR6 || bScale ) h = 0;
2530 else
2532 /* FIXME: not complete */
2534 pfm->flags |= FO_SYNTH_WIDTH;
2535 h = abs(plf->lfWidth - (pfm->height * pfi->df.dfAvgWidth)/pfi->df.dfPixHeight);
2537 penalty += h * ( d ) ? 0x2 : 0x1 ;
2539 else if( !(pfi->fi_flags & FI_NORMAL) ) penalty++;
2541 /* Weight */
2542 if( plf->lfWeight != FW_DONTCARE )
2544 penalty += abs(plf->lfWeight - pfi->df.dfWeight) / 40;
2545 if( plf->lfWeight > pfi->df.dfWeight ) pfm->flags |= FO_SYNTH_BOLD;
2546 } else if( pfi->df.dfWeight >= FW_BOLD ) penalty++; /* choose normal by default */
2548 /* Italic */
2549 if( plf->lfItalic != pfi->df.dfItalic )
2551 penalty += 0x4;
2552 pfm->flags |= FO_SYNTH_ITALIC;
2554 /* Underline */
2555 if( plf->lfUnderline ) pfm->flags |= FO_SYNTH_UNDERLINE;
2557 /* Strikeout */
2558 if( plf->lfStrikeOut ) pfm->flags |= FO_SYNTH_STRIKEOUT;
2561 if( penalty && !bScale && pfi->lfd_resolution != DefResolution )
2562 penalty++;
2564 TRACE(" returning %i\n", penalty );
2566 return penalty;
2569 /***********************************************************************
2570 * XFONT_MatchFIList
2572 * Scan a particular font resource for the best match.
2574 static UINT XFONT_MatchFIList( fontMatch* pfm )
2576 BOOL skipRaster = (pfm->flags & FO_MATCH_NORASTER);
2577 UINT current_score, score = (UINT)(-1);
2578 fontMatch fm = *pfm;
2580 for( fm.pfi = pfm->pfr->fi; fm.pfi && score; fm.pfi = fm.pfi->next)
2582 if( skipRaster && !(fm.pfi->fi_flags & FI_SCALABLE) )
2583 continue;
2585 current_score = XFONT_Match( &fm );
2586 if( score > current_score )
2588 *pfm = fm;
2589 score = current_score;
2592 return score;
2595 /***********************************************************************
2596 * XFONT_is_ansi_charset
2598 * returns TRUE if the given charset is ANSI_CHARSET.
2600 static BOOL XFONT_is_ansi_charset( UINT charset )
2602 return ((charset == ANSI_CHARSET) ||
2603 (charset == DEFAULT_CHARSET && GetACP() == 1252));
2606 /***********************************************************************
2607 * XFONT_MatchDeviceFont
2609 * Scan font resource tree.
2612 static void XFONT_MatchDeviceFont( fontResource* start, fontMatch* pfm)
2614 fontMatch fm = *pfm;
2615 UINT current_score, score = (UINT)(-1);
2616 fontResource** ppfr;
2618 TRACE("(%u) '%s' h=%i weight=%i %s\n",
2619 pfm->plf->lfCharSet, pfm->plf->lfFaceName, pfm->plf->lfHeight,
2620 pfm->plf->lfWeight, (pfm->plf->lfItalic) ? "Italic" : "" );
2622 pfm->pfi = NULL;
2624 /* the following hard-coded font binding assumes 'ANSI_CHARSET'. */
2625 if( !fm.plf->lfFaceName[0] &&
2626 XFONT_is_ansi_charset(fm.plf->lfCharSet) )
2628 switch(fm.plf->lfPitchAndFamily & 0xf0)
2630 case FF_MODERN:
2631 strcpy(fm.plf->lfFaceName, "Courier New");
2632 break;
2633 case FF_ROMAN:
2634 strcpy(fm.plf->lfFaceName, "Times New Roman");
2635 break;
2636 case FF_SWISS:
2637 strcpy(fm.plf->lfFaceName, "Arial");
2638 break;
2639 default:
2640 if((fm.plf->lfPitchAndFamily & 0x0f) == FIXED_PITCH)
2641 strcpy(fm.plf->lfFaceName, "Courier New");
2642 else
2643 strcpy(fm.plf->lfFaceName, "Arial");
2644 break;
2648 if( fm.plf->lfFaceName[0] )
2650 fm.pfr = XFONT_FindFIList( start, fm.plf->lfFaceName);
2651 if( fm.pfr ) /* match family */
2653 TRACE("found facename '%s'\n", fm.pfr->lfFaceName );
2655 if( fm.pfr->fr_flags & FR_REMOVED )
2656 fm.pfr = 0;
2657 else
2659 XFONT_MatchFIList( &fm );
2660 *pfm = fm;
2661 if (pfm->pfi)
2662 return;
2666 /* get charset if lfFaceName is one of known facenames. */
2668 const struct CharsetBindingInfo* pcharsetbindings;
2670 pcharsetbindings = &charsetbindings[0];
2671 while ( pcharsetbindings->pszFaceName != NULL )
2673 if ( !strcmp( pcharsetbindings->pszFaceName,
2674 fm.plf->lfFaceName ) )
2676 fm.internal_charset = pcharsetbindings->charset;
2677 break;
2679 pcharsetbindings ++;
2681 TRACE( "%s charset %u\n", fm.plf->lfFaceName, fm.internal_charset );
2685 /* match all available fonts */
2687 fm.flags |= FO_MATCH_PAF;
2688 for( ppfr = &fontList; *ppfr && score; ppfr = &(*ppfr)->next )
2690 if( (*ppfr)->fr_flags & FR_REMOVED )
2692 if( (*ppfr)->fo_count == 0 )
2693 XFONT_RemoveFontResource( ppfr );
2694 continue;
2697 fm.pfr = *ppfr;
2699 TRACE("%s\n", fm.pfr->lfFaceName );
2701 current_score = XFONT_MatchFIList( &fm );
2702 if( current_score < score )
2704 score = current_score;
2705 *pfm = fm;
2711 /***********************************************************************
2712 * X Font Cache
2714 static void XFONT_GrowFreeList(int start, int end)
2716 /* add all entries from 'start' up to and including 'end' */
2718 memset( fontCache + start, 0, (end - start + 1) * sizeof(fontObject) );
2720 fontCache[end].lru = fontLF;
2721 fontCache[end].count = -1;
2722 fontLF = start;
2723 while( start < end )
2725 fontCache[start].count = -1;
2726 fontCache[start].lru = start + 1;
2727 start++;
2731 static fontObject* XFONT_LookupCachedFont( const LOGFONT16 *plf, UINT16* checksum )
2733 UINT16 cs = __lfCheckSum( plf );
2734 int i = fontMRU, prev = -1;
2736 *checksum = cs;
2737 while( i >= 0 )
2739 if( fontCache[i].lfchecksum == cs &&
2740 !(fontCache[i].fo_flags & FO_REMOVED) )
2742 /* FIXME: something more intelligent here ? */
2744 if( !memcmp( plf, &fontCache[i].lf,
2745 sizeof(LOGFONT16) - LF_FACESIZE ) &&
2746 !strcmp( plf->lfFaceName, fontCache[i].lf.lfFaceName) )
2748 /* remove temporarily from the lru list */
2749 if( prev >= 0 )
2750 fontCache[prev].lru = fontCache[i].lru;
2751 else
2752 fontMRU = (INT16)fontCache[i].lru;
2753 return (fontCache + i);
2756 prev = i;
2757 i = (INT16)fontCache[i].lru;
2759 return NULL;
2762 static fontObject* XFONT_GetCacheEntry(void)
2764 int i;
2766 if( fontLF == -1 )
2768 int prev_i, prev_j, j;
2770 TRACE("font cache is full\n");
2772 /* lookup the least recently used font */
2774 for( prev_i = prev_j = j = -1, i = fontMRU; i >= 0; i = (INT16)fontCache[i].lru )
2776 if( fontCache[i].count <= 0 &&
2777 !(fontCache[i].fo_flags & FO_SYSTEM) )
2779 prev_j = prev_i;
2780 j = i;
2782 prev_i = i;
2785 if( j >= 0 ) /* unload font */
2787 /* detach from the lru list */
2789 TRACE("\tfreeing entry %i\n", j );
2791 fontCache[j].fr->fo_count--;
2793 if( prev_j >= 0 )
2794 fontCache[prev_j].lru = fontCache[j].lru;
2795 else fontMRU = (INT16)fontCache[j].lru;
2797 /* FIXME: lpXForm, lpPixmap */
2798 HeapFree( GetProcessHeap(), 0, fontCache[j].lpX11Trans );
2800 wine_tsx11_lock();
2801 XFreeFont( gdi_display, fontCache[j].fs );
2802 wine_tsx11_unlock();
2804 memset( fontCache + j, 0, sizeof(fontObject) );
2805 return (fontCache + j);
2807 else /* expand cache */
2809 fontObject* newCache;
2811 prev_i = fontCacheSize + FONTCACHE;
2813 TRACE("\tgrowing font cache from %i to %i\n", fontCacheSize, prev_i );
2815 if( (newCache = HeapReAlloc(GetProcessHeap(), 0, fontCache, prev_i * sizeof(fontObject))) )
2817 i = fontCacheSize;
2818 fontCacheSize = prev_i;
2819 fontCache = newCache;
2820 XFONT_GrowFreeList( i, fontCacheSize - 1);
2822 else return NULL;
2826 /* detach from the free list */
2828 i = fontLF;
2829 fontLF = (INT16)fontCache[i].lru;
2830 fontCache[i].count = 0;
2831 return (fontCache + i);
2834 static int XFONT_ReleaseCacheEntry(const fontObject* pfo)
2836 UINT u = (UINT)(pfo - fontCache);
2837 int i;
2838 int ret;
2840 if( u < fontCacheSize )
2842 ret = --fontCache[u].count;
2843 if ( ret == 0 )
2845 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
2847 if( CHECK_PFONT(pfo->prefobjs[i]) )
2848 XFONT_ReleaseCacheEntry(__PFONT(pfo->prefobjs[i]));
2852 return ret;
2855 return -1;
2858 /***********************************************************************
2859 * X11DRV_FONT_InitX11Metrics
2861 * Initialize font resource list and allocate font cache.
2863 static void X11DRV_FONT_InitX11Metrics( void )
2865 char** x_pattern = NULL;
2866 unsigned x_checksum;
2867 int i, x_count, fd, buf_size;
2868 char *buffer;
2869 HKEY hkey;
2872 /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver */
2873 if(RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Wine\\X11 Driver", &hkey) == ERROR_SUCCESS)
2875 DWORD type, size = 128, ret;
2876 char *pattern = HeapAlloc(GetProcessHeap(), 0, size);
2877 while((ret = RegQueryValueExA(hkey, INIFontPattern, 0, &type, (LPBYTE)pattern, &size) == ERROR_MORE_DATA))
2878 pattern = HeapReAlloc(GetProcessHeap(), 0, pattern, size);
2879 if(ret == ERROR_SUCCESS)
2881 wine_tsx11_lock();
2882 x_pattern = XListFonts(gdi_display, pattern, MAX_FONTS, &x_count);
2883 wine_tsx11_unlock();
2885 HeapFree(GetProcessHeap(), 0, pattern);
2886 RegCloseKey(hkey);
2888 if(!x_pattern)
2890 wine_tsx11_lock();
2891 x_pattern = XListFonts(gdi_display, "*", MAX_FONTS, &x_count );
2892 wine_tsx11_unlock();
2895 TRACE("Font Mapper: initializing %i x11 fonts\n", x_count);
2896 if (x_count == MAX_FONTS)
2897 MESSAGE("There may be more fonts available - try increasing the value of MAX_FONTS\n");
2899 for( i = x_checksum = 0; i < x_count; i++ )
2901 int j;
2902 #if 0
2903 printf("%i\t: %s\n", i, x_pattern[i] );
2904 #endif
2906 j = strlen( x_pattern[i] );
2907 if( j ) x_checksum ^= __genericCheckSum( x_pattern[i], j );
2909 x_checksum |= X_PFONT_MAGIC;
2910 buf_size = 128;
2911 buffer = HeapAlloc( GetProcessHeap(), 0, buf_size );
2913 /* deal with systemwide font metrics cache */
2915 buffer[0] = 0;
2916 /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver\Fonts */
2917 if (RegOpenKeyA(HKEY_CURRENT_USER, INIFontSection, &hkey)) hkey = 0;
2918 if (hkey)
2920 DWORD type, count = buf_size;
2921 RegQueryValueExA(hkey, INIGlobalMetrics, 0, &type, (LPBYTE)buffer, &count);
2924 if( buffer[0] )
2926 fd = open( buffer, O_RDONLY );
2927 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2929 if (fontList == NULL)
2931 /* try per-user */
2932 buffer = XFONT_UserMetricsCache( buffer, &buf_size );
2933 if( buffer[0] )
2935 fd = open( buffer, O_RDONLY );
2936 XFONT_ReadCachedMetrics(fd, DefResolution, x_checksum, x_count);
2940 if( fontList == NULL ) /* build metrics from scratch */
2942 int n_ff = XFONT_BuildMetrics(x_pattern, DefResolution, x_checksum, x_count);
2943 if( buffer[0] ) /* update cached metrics */
2945 fd = open( buffer, O_CREAT | O_TRUNC | O_RDWR, 0644 ); /* -rw-r--r-- */
2946 if( XFONT_WriteCachedMetrics( fd, x_checksum, x_count, n_ff ) == FALSE )
2948 WARN("Unable to write to fontcache '%s'\n", buffer);
2949 if( fd >= 0) remove( buffer ); /* couldn't write entire file */
2954 wine_tsx11_lock();
2955 XFreeFontNames(x_pattern);
2957 /* check if we're dealing with X11 R6 server */
2959 XFontStruct* x_fs;
2960 strcpy(buffer, "-*-*-*-*-normal-*-[12 0 0 12]-*-72-*-*-*-iso8859-1");
2961 if( (x_fs = safe_XLoadQueryFont(gdi_display, buffer)) )
2963 text_caps |= TC_SF_X_YINDEP;
2964 XFreeFont(gdi_display, x_fs);
2967 wine_tsx11_unlock();
2969 HeapFree(GetProcessHeap(), 0, buffer);
2971 XFONT_WindowsNames();
2972 XFONT_LoadAliases( hkey );
2973 if (hkey) XFONT_LoadDefaults( hkey );
2974 XFONT_LoadIgnores( hkey );
2976 /* fontList initialization is over, allocate X font cache */
2978 fontCache = HeapAlloc(GetProcessHeap(), 0, fontCacheSize * sizeof(fontObject));
2979 XFONT_GrowFreeList(0, fontCacheSize - 1);
2981 TRACE("done!\n");
2982 if (hkey) RegCloseKey(hkey);
2985 /***********************************************************************
2986 * X11DRV_FONT_Init
2988 void X11DRV_FONT_Init( int log_pixels_x, int log_pixels_y )
2990 XFONT_GetDefResolution( log_pixels_x, log_pixels_y );
2992 if(using_client_side_fonts)
2993 text_caps |= TC_VA_ABLE;
2995 return;
2998 /**********************************************************************
2999 * XFONT_SetX11Trans
3001 static BOOL XFONT_SetX11Trans( fontObject *pfo )
3003 char *fontName;
3004 Atom nameAtom;
3005 LFD lfd;
3007 wine_tsx11_lock();
3008 XGetFontProperty( pfo->fs, XA_FONT, &nameAtom );
3009 fontName = XGetAtomName( gdi_display, nameAtom );
3010 if (!LFD_Parse(fontName, &lfd) || lfd.pixel_size[0] != '[')
3012 XFree(fontName);
3013 wine_tsx11_unlock();
3014 return FALSE;
3016 #define PX pfo->lpX11Trans
3018 sscanf(lfd.pixel_size, "[%f%f%f%f]", &PX->a, &PX->b, &PX->c, &PX->d);
3019 XFree(fontName);
3021 XGetFontProperty( pfo->fs, x11drv_atom(RAW_ASCENT), &PX->RAW_ASCENT );
3022 XGetFontProperty( pfo->fs, x11drv_atom(RAW_DESCENT), &PX->RAW_DESCENT );
3023 wine_tsx11_unlock();
3025 PX->pixelsize = hypot(PX->a, PX->b);
3026 PX->ascent = PX->pixelsize / 1000.0 * PX->RAW_ASCENT;
3027 PX->descent = PX->pixelsize / 1000.0 * PX->RAW_DESCENT;
3029 TRACE("[%f %f %f %f] RA = %ld RD = %ld\n",
3030 PX->a, PX->b, PX->c, PX->d,
3031 PX->RAW_ASCENT, PX->RAW_DESCENT);
3033 #undef PX
3034 return TRUE;
3037 /***********************************************************************
3038 * X Device Font Objects
3040 static X_PHYSFONT XFONT_RealizeFont( LPLOGFONT16 plf,
3041 LPCSTR* faceMatched, BOOL bSubFont,
3042 WORD internal_charset,
3043 WORD* pcharsetMatched )
3045 UINT16 checksum;
3046 INT index = 0;
3047 fontObject* pfo;
3049 pfo = XFONT_LookupCachedFont( plf, &checksum );
3050 if( !pfo )
3052 fontMatch fm;
3053 INT i;
3055 fm.pfr = NULL;
3056 fm.pfi = NULL;
3057 fm.height = 0;
3058 fm.flags = 0;
3059 fm.plf = plf;
3060 fm.internal_charset = internal_charset;
3062 if( text_caps & TC_SF_X_YINDEP ) fm.flags = FO_MATCH_XYINDEP;
3064 /* allocate new font cache entry */
3066 if( (pfo = XFONT_GetCacheEntry()) )
3068 /* initialize entry and load font */
3069 char lpLFD[MAX_LFD_LENGTH];
3070 UINT uRelaxLevel = 0;
3072 if(abs(plf->lfHeight) > MAX_FONT_SIZE) {
3073 ERR(
3074 "plf->lfHeight = %d, Creating a 100 pixel font and rescaling metrics\n",
3075 plf->lfHeight);
3076 pfo->rescale = fabs(plf->lfHeight / 100.0);
3077 if(plf->lfHeight > 0) plf->lfHeight = 100;
3078 else plf->lfHeight = -100;
3079 } else
3080 pfo->rescale = 1.0;
3082 XFONT_MatchDeviceFont( fontList, &fm );
3083 pfo->fr = fm.pfr;
3084 pfo->fi = fm.pfi;
3085 pfo->fr->fo_count++;
3086 pfo->fo_flags = fm.flags & ~FO_MATCH_MASK;
3088 pfo->lf = *plf;
3089 pfo->lfchecksum = checksum;
3093 LFD_ComposeLFD( pfo, fm.height, lpLFD, uRelaxLevel++ );
3094 if( (pfo->fs = safe_XLoadQueryFont( gdi_display, lpLFD )) ) break;
3095 } while( uRelaxLevel );
3098 if(pfo->lf.lfEscapement != 0) {
3099 pfo->lpX11Trans = HeapAlloc(GetProcessHeap(), 0, sizeof(XFONTTRANS));
3100 if(!XFONT_SetX11Trans( pfo )) {
3101 HeapFree(GetProcessHeap(), 0, pfo->lpX11Trans);
3102 pfo->lpX11Trans = NULL;
3105 XFONT_GetLeading( &pfo->fi->df, pfo->fs,
3106 &pfo->foInternalLeading, NULL, pfo->lpX11Trans );
3107 pfo->foAvgCharWidth = (INT16)XFONT_GetAvgCharWidth(&pfo->fi->df, pfo->fs, pfo->lpX11Trans );
3108 pfo->foMaxCharWidth = (INT16)XFONT_GetMaxCharWidth(pfo->fs, pfo->lpX11Trans);
3110 /* FIXME: If we've got a soft font or
3111 * there are FO_SYNTH_... flags for the
3112 * non PROOF_QUALITY request, the engine
3113 * should rasterize characters into mono
3114 * pixmaps and store them in the pfo->lpPixmap
3115 * array (pfo->fs should be updated as well).
3116 * array (pfo->fs should be updated as well).
3117 * X11DRV_ExtTextOut() must be heavily modified
3118 * to support pixmap blitting and FO_SYNTH_...
3119 * styles.
3122 pfo->lpPixmap = NULL;
3124 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3125 pfo->prefobjs[i] = (X_PHYSFONT)0xffffffff; /* invalid value */
3127 /* special treatment for DBCS that needs multiple fonts */
3128 /* All member of pfo must be set correctly. */
3129 if ( bSubFont == FALSE )
3131 WORD charset_sub;
3132 WORD charsetMatchedSub;
3133 LOGFONT16 lfSub;
3134 LPCSTR faceMatchedSub;
3136 for ( i = 0; i < X11FONT_REFOBJS_MAX; i++ )
3138 charset_sub = X11DRV_cptable[pfo->fi->cptable].
3139 penum_subfont_charset( i );
3140 if ( charset_sub == DEFAULT_CHARSET ) break;
3142 lfSub = *plf;
3143 lfSub.lfWidth = 0;
3144 lfSub.lfHeight=plf->lfHeight;
3145 lfSub.lfCharSet = (BYTE)(charset_sub & 0xff);
3146 lfSub.lfFaceName[0] = '\0'; /* FIXME? */
3147 /* this font has sub font */
3148 if ( i == 0 ) pfo->prefobjs[0] = (X_PHYSFONT)0;
3149 pfo->prefobjs[i] =
3150 XFONT_RealizeFont( &lfSub, &faceMatchedSub,
3151 TRUE, charset_sub,
3152 &charsetMatchedSub );
3153 /* FIXME: check charsetMatchedSub */
3158 if( !pfo ) /* couldn't get a new entry, get one of the cached fonts */
3160 UINT current_score, score = (UINT)(-1);
3162 i = index = fontMRU;
3163 fm.flags |= FO_MATCH_PAF;
3166 pfo = fontCache + i;
3167 fm.pfr = pfo->fr; fm.pfi = pfo->fi;
3169 current_score = XFONT_Match( &fm );
3170 if( current_score < score ) index = i;
3172 i = pfo->lru;
3173 } while( i >= 0 );
3174 pfo = fontCache + index;
3175 goto END;
3179 /* attach at the head of the lru list */
3180 pfo->lru = fontMRU;
3181 index = fontMRU = (pfo - fontCache);
3183 END:
3184 pfo->count++;
3186 TRACE("physfont %i\n", index);
3187 *faceMatched = pfo->fi->df.dfFace;
3188 *pcharsetMatched = pfo->fi->internal_charset;
3190 return (X_PHYSFONT)(X_PFONT_MAGIC | index);
3193 /***********************************************************************
3194 * XFONT_GetFontObject
3196 fontObject* XFONT_GetFontObject( X_PHYSFONT pFont )
3198 if( CHECK_PFONT(pFont) ) return __PFONT(pFont);
3199 return NULL;
3202 /***********************************************************************
3203 * XFONT_GetFontStruct
3205 XFontStruct* XFONT_GetFontStruct( X_PHYSFONT pFont )
3207 if( CHECK_PFONT(pFont) ) return __PFONT(pFont)->fs;
3208 return NULL;
3211 /***********************************************************************
3212 * XFONT_GetFontInfo
3214 LPIFONTINFO16 XFONT_GetFontInfo( X_PHYSFONT pFont )
3216 if( CHECK_PFONT(pFont) ) return &(__PFONT(pFont)->fi->df);
3217 return NULL;
3222 /* X11DRV Interface ****************************************************
3224 * Exposed via the dc->funcs dispatch table. *
3226 ***********************************************************************/
3227 /***********************************************************************
3228 * SelectFont (X11DRV.@)
3230 HFONT X11DRV_SelectFont( X11DRV_PDEVICE *physDev, HFONT hfont, HANDLE gdiFont )
3232 LOGFONTW logfont;
3233 LOGFONT16 lf;
3235 TRACE("hdc=%p, hfont=%p\n", physDev->hdc, hfont);
3237 if (!GetObjectW( hfont, sizeof(logfont), &logfont )) return HGDI_ERROR;
3239 TRACE("gdiFont = %p\n", gdiFont);
3241 if(gdiFont && using_client_side_fonts) {
3242 X11DRV_XRender_SelectFont(physDev, hfont);
3243 physDev->has_gdi_font = TRUE;
3244 return FALSE;
3247 EnterCriticalSection( &crtsc_fonts_X11 );
3249 if(fontList == NULL) X11DRV_FONT_InitX11Metrics();
3251 if( CHECK_PFONT(physDev->font) )
3252 XFONT_ReleaseCacheEntry( __PFONT(physDev->font) );
3254 FONT_LogFontWTo16(&logfont, &lf);
3256 /* stock fonts ignore the mapping mode */
3257 if (!is_stock_font( hfont ))
3259 /* Make sure we don't change the sign when converting to device coords */
3260 /* FIXME - check that the other drivers do this correctly */
3261 if (lf.lfWidth)
3263 INT width = X11DRV_XWStoDS( physDev, lf.lfWidth );
3264 lf.lfWidth = (lf.lfWidth < 0) ? -abs(width) : abs(width);
3265 if (lf.lfWidth == 0)
3266 lf.lfWidth = 1; /* Minimum width */
3268 if (lf.lfHeight)
3270 INT height = X11DRV_YWStoDS( physDev, lf.lfHeight );
3271 lf.lfHeight = (lf.lfHeight < 0) ? -abs(height) : abs(height);
3272 if (lf.lfHeight == 0)
3273 lf.lfHeight = MIN_FONT_SIZE;
3277 if (!lf.lfHeight)
3278 lf.lfHeight = -(DEF_POINT_SIZE * GetDeviceCaps(physDev->hdc,LOGPIXELSY) + (72>>1)) / 72;
3281 /* Fixup aliases before passing to RealizeFont */
3282 /* alias = Windows name in the alias table */
3283 LPCSTR alias = XFONT_UnAlias( lf.lfFaceName );
3284 LPCSTR faceMatched;
3285 WORD charsetMatched;
3287 TRACE("hfont=%p\n", hfont); /* to connect with the trace from RealizeFont */
3288 physDev->font = XFONT_RealizeFont( &lf, &faceMatched,
3289 FALSE, lf.lfCharSet,
3290 &charsetMatched );
3292 /* set face to the requested facename if it matched
3293 * so that GetTextFace can get the correct face name
3295 if (alias && !strcmp(faceMatched, lf.lfFaceName))
3296 MultiByteToWideChar(CP_ACP, 0, alias, -1,
3297 logfont.lfFaceName, LF_FACESIZE);
3298 else
3299 MultiByteToWideChar(CP_ACP, 0, faceMatched, -1,
3300 logfont.lfFaceName, LF_FACESIZE);
3303 * In X, some encodings may have the same lfFaceName.
3304 * for example:
3305 * -misc-fixed-*-iso8859-1
3306 * -misc-fixed-*-jisx0208.1990-0
3307 * so charset should be saved...
3309 logfont.lfCharSet = charsetMatched;
3312 LeaveCriticalSection( &crtsc_fonts_X11 );
3314 physDev->has_gdi_font = FALSE;
3315 return (HFONT)1; /* Use a device font */
3319 /***********************************************************************
3321 * X11DRV_EnumDeviceFonts
3323 BOOL X11DRV_EnumDeviceFonts( X11DRV_PDEVICE *physDev, LPLOGFONTW plf,
3324 FONTENUMPROCW proc, LPARAM lp )
3326 ENUMLOGFONTEXW lf;
3327 NEWTEXTMETRICEXW tm;
3328 fontResource* pfr = fontList;
3329 BOOL b, bRet = 0;
3331 /* don't enumerate x11 fonts if we're using client side fonts */
3332 if (physDev->has_gdi_font) return FALSE;
3334 if( plf->lfFaceName[0] )
3336 char facename[LF_FACESIZE+1];
3337 WideCharToMultiByte( CP_ACP, 0, plf->lfFaceName, -1,
3338 facename, sizeof(facename), NULL, NULL );
3339 /* enum all entries in this resource */
3340 pfr = XFONT_FindFIList( pfr, facename );
3341 if( pfr )
3343 fontInfo* pfi;
3344 for( pfi = pfr->fi; pfi; pfi = pfi->next )
3346 /* Note: XFONT_GetFontMetric() will have to
3347 release the crit section, font list will
3348 have to be retraversed on return */
3350 if(plf->lfCharSet == DEFAULT_CHARSET ||
3351 plf->lfCharSet == pfi->df.dfCharSet) {
3352 if( (b = (*proc)( &lf.elfLogFont, (TEXTMETRICW *)&tm,
3353 XFONT_GetFontMetric( pfi, &lf, &tm ), lp )) )
3354 bRet = b;
3355 else break;
3360 else /* enum first entry in each resource */
3361 for( ; pfr ; pfr = pfr->next )
3363 if(pfr->fi)
3365 if( (b = (*proc)( &lf.elfLogFont, (TEXTMETRICW *)&tm,
3366 XFONT_GetFontMetric( pfr->fi, &lf, &tm ), lp )) )
3367 bRet = b;
3368 else break;
3371 return bRet;
3375 /***********************************************************************
3376 * X11DRV_GetTextMetrics
3378 BOOL X11DRV_GetTextMetrics(X11DRV_PDEVICE *physDev, TEXTMETRICW *metrics)
3380 if( CHECK_PFONT(physDev->font) )
3382 fontObject* pfo = __PFONT(physDev->font);
3383 X11DRV_cptable[pfo->fi->cptable].pGetTextMetricsW( pfo, metrics );
3384 return TRUE;
3386 return FALSE;
3390 /***********************************************************************
3391 * X11DRV_GetCharWidth
3393 BOOL X11DRV_GetCharWidth( X11DRV_PDEVICE *physDev, UINT firstChar, UINT lastChar,
3394 LPINT buffer )
3396 fontObject* pfo = XFONT_GetFontObject( physDev->font );
3398 if( pfo )
3400 unsigned int i;
3402 if (pfo->fs->per_char == NULL)
3403 for (i = firstChar; i <= lastChar; i++)
3404 if(pfo->lpX11Trans)
3405 *buffer++ = pfo->fs->min_bounds.attributes *
3406 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3407 else
3408 *buffer++ = pfo->fs->min_bounds.width * pfo->rescale;
3409 else
3411 XCharStruct *cs, *def;
3412 static XCharStruct __null_char = { 0, 0, 0, 0, 0, 0 };
3414 CI_GET_CHAR_INFO(pfo->fs, pfo->fs->default_char, &__null_char,
3415 def);
3417 for (i = firstChar; i <= lastChar; i++)
3419 WCHAR wch = i;
3420 BYTE ch;
3421 UINT ch_f; /* character code in the font encoding */
3422 WideCharToMultiByte( pfo->fi->codepage, 0, &wch, 1, (LPSTR)&ch, 1, NULL, NULL );
3423 ch_f = ch;
3424 if (ch_f >= pfo->fs->min_char_or_byte2 &&
3425 ch_f <= pfo->fs->max_char_or_byte2)
3427 cs = &pfo->fs->per_char[(ch_f - pfo->fs->min_char_or_byte2)];
3428 if (CI_NONEXISTCHAR(cs)) cs = def;
3429 } else cs = def;
3430 if(pfo->lpX11Trans)
3431 *buffer++ = max(cs->attributes, 0) *
3432 pfo->lpX11Trans->pixelsize / 1000.0 * pfo->rescale;
3433 else
3434 *buffer++ = max(cs->width, 0 ) * pfo->rescale;
3438 return TRUE;
3440 return FALSE;