freetype.c 308 KB
Newer Older
1 2 3 4
/*
 * FreeType font engine interface
 *
 * Copyright 2001 Huw D M Davies for CodeWeavers.
5
 * Copyright 2006 Dmitry Timoshkov for CodeWeavers.
6 7
 *
 * This file contains the WineEng* functions.
8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 23 24
 */

#include "config.h"
25
#include "wine/port.h"
26

27 28
#include <stdarg.h>
#include <stdlib.h>
29 30 31
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
32 33 34
#ifdef HAVE_SYS_MMAN_H
# include <sys/mman.h>
#endif
35
#include <string.h>
36 37 38
#ifdef HAVE_DIRENT_H
# include <dirent.h>
#endif
39 40 41
#include <stdio.h>
#include <assert.h>

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#ifdef HAVE_CARBON_CARBON_H
#define LoadResource __carbon_LoadResource
#define CompareString __carbon_CompareString
#define GetCurrentThread __carbon_GetCurrentThread
#define GetCurrentProcess __carbon_GetCurrentProcess
#define AnimatePalette __carbon_AnimatePalette
#define EqualRgn __carbon_EqualRgn
#define FillRgn __carbon_FillRgn
#define FrameRgn __carbon_FrameRgn
#define GetPixel __carbon_GetPixel
#define InvertRgn __carbon_InvertRgn
#define LineTo __carbon_LineTo
#define OffsetRgn __carbon_OffsetRgn
#define PaintRgn __carbon_PaintRgn
#define Polygon __carbon_Polygon
#define ResizePalette __carbon_ResizePalette
#define SetRectRgn __carbon_SetRectRgn
#include <Carbon/Carbon.h>
#undef LoadResource
#undef CompareString
#undef GetCurrentThread
#undef _CDECL
#undef GetCurrentProcess
#undef AnimatePalette
#undef EqualRgn
#undef FillRgn
#undef FrameRgn
#undef GetPixel
#undef InvertRgn
#undef LineTo
#undef OffsetRgn
#undef PaintRgn
#undef Polygon
#undef ResizePalette
#undef SetRectRgn
#endif /* HAVE_CARBON_CARBON_H */

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
#ifdef HAVE_FT2BUILD_H
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include FT_TYPES_H
#include FT_TRUETYPE_TABLES_H
#include FT_SFNT_NAMES_H
#include FT_TRUETYPE_IDS_H
#include FT_OUTLINE_H
#include FT_TRIGONOMETRY_H
#include FT_MODULE_H
#include FT_WINFONTS_H
#ifdef FT_LCD_FILTER_H
#include FT_LCD_FILTER_H
#endif
#endif /* HAVE_FT2BUILD_H */

96
#include "windef.h"
97
#include "winbase.h"
98
#include "winternl.h"
99 100 101
#include "winerror.h"
#include "winreg.h"
#include "wingdi.h"
102
#include "gdi_private.h"
103
#include "wine/library.h"
104
#include "wine/unicode.h"
105
#include "wine/debug.h"
106
#include "wine/list.h"
107

108 109
#include "resource.h"

110
WINE_DEFAULT_DEBUG_CHANNEL(font);
111 112 113

#ifdef HAVE_FREETYPE

114 115 116 117 118 119 120
#ifndef HAVE_FT_TRUETYPEENGINETYPE
typedef enum
{
    FT_TRUETYPE_ENGINE_TYPE_NONE = 0,
    FT_TRUETYPE_ENGINE_TYPE_UNPATENTED,
    FT_TRUETYPE_ENGINE_TYPE_PATENTED
} FT_TrueTypeEngineType;
121 122
#endif

123
static FT_Library library = 0;
124 125 126 127 128 129 130
typedef struct
{
    FT_Int major;
    FT_Int minor;
    FT_Int patch;
} FT_Version_t;
static FT_Version_t FT_Version;
131
static DWORD FT_SimpleVersion;
132
#define FT_VERSION_VALUE(major, minor, patch) (((major) << 16) | ((minor) << 8) | (patch))
133

134 135
static void *ft_handle = NULL;

136 137 138
#define MAKE_FUNCPTR(f) static typeof(f) * p##f = NULL
MAKE_FUNCPTR(FT_Done_Face);
MAKE_FUNCPTR(FT_Get_Char_Index);
139 140
MAKE_FUNCPTR(FT_Get_First_Char);
MAKE_FUNCPTR(FT_Get_Next_Char);
141 142
MAKE_FUNCPTR(FT_Get_Sfnt_Name);
MAKE_FUNCPTR(FT_Get_Sfnt_Name_Count);
143
MAKE_FUNCPTR(FT_Get_Sfnt_Table);
144
MAKE_FUNCPTR(FT_Get_WinFNT_Header);
145
MAKE_FUNCPTR(FT_Init_FreeType);
146
MAKE_FUNCPTR(FT_Library_Version);
147
MAKE_FUNCPTR(FT_Load_Glyph);
148
MAKE_FUNCPTR(FT_Load_Sfnt_Table);
149
MAKE_FUNCPTR(FT_Matrix_Multiply);
150 151 152
#ifdef FT_MULFIX_INLINED
#define pFT_MulFix FT_MULFIX_INLINED
#else
153
MAKE_FUNCPTR(FT_MulFix);
154
#endif
155
MAKE_FUNCPTR(FT_New_Face);
156
MAKE_FUNCPTR(FT_New_Memory_Face);
157
MAKE_FUNCPTR(FT_Outline_Get_Bitmap);
158
MAKE_FUNCPTR(FT_Outline_Get_CBox);
159 160
MAKE_FUNCPTR(FT_Outline_Transform);
MAKE_FUNCPTR(FT_Outline_Translate);
161
MAKE_FUNCPTR(FT_Render_Glyph);
162
MAKE_FUNCPTR(FT_Set_Charmap);
163
MAKE_FUNCPTR(FT_Set_Pixel_Sizes);
164
MAKE_FUNCPTR(FT_Vector_Length);
165
MAKE_FUNCPTR(FT_Vector_Transform);
166
MAKE_FUNCPTR(FT_Vector_Unit);
167
static FT_Error (*pFT_Outline_Embolden)(FT_Outline *, FT_Pos);
168
static FT_TrueTypeEngineType (*pFT_Get_TrueType_Engine_Type)(FT_Library);
169
#ifdef FT_LCD_FILTER_H
170 171
static FT_Error (*pFT_Library_SetLcdFilter)(FT_Library, FT_LcdFilter);
#endif
172
static FT_Error (*pFT_Property_Set)(FT_Library, const FT_String *, const FT_String *, const void *);
173

174
#ifdef SONAME_LIBFONTCONFIG
175
#include <fontconfig/fontconfig.h>
176
MAKE_FUNCPTR(FcConfigSubstitute);
177
MAKE_FUNCPTR(FcDefaultSubstitute);
178
MAKE_FUNCPTR(FcFontList);
179
MAKE_FUNCPTR(FcFontMatch);
180 181
MAKE_FUNCPTR(FcFontSetDestroy);
MAKE_FUNCPTR(FcInit);
182
MAKE_FUNCPTR(FcPatternAddString);
183 184
MAKE_FUNCPTR(FcPatternCreate);
MAKE_FUNCPTR(FcPatternDestroy);
185
MAKE_FUNCPTR(FcPatternGetBool);
186
MAKE_FUNCPTR(FcPatternGetInteger);
187
MAKE_FUNCPTR(FcPatternGetString);
188 189
#ifndef FC_NAMELANG
#define FC_NAMELANG "namelang"
190
#endif
191 192 193 194
#ifndef FC_PRGNAME
#define FC_PRGNAME "prgname"
#endif
#endif /* SONAME_LIBFONTCONFIG */
195 196 197

#undef MAKE_FUNCPTR

198 199 200 201 202 203
#ifndef FT_MAKE_TAG
#define FT_MAKE_TAG( ch0, ch1, ch2, ch3 ) \
	( ((DWORD)(BYTE)(ch0) << 24) | ((DWORD)(BYTE)(ch1) << 16) | \
	  ((DWORD)(BYTE)(ch2) << 8) | (DWORD)(BYTE)(ch3) )
#endif

204
#ifndef ft_encoding_none
205 206
#define FT_ENCODING_NONE ft_encoding_none
#endif
207
#ifndef ft_encoding_ms_symbol
208 209
#define FT_ENCODING_MS_SYMBOL ft_encoding_symbol
#endif
210
#ifndef ft_encoding_unicode
211 212
#define FT_ENCODING_UNICODE ft_encoding_unicode
#endif
213
#ifndef ft_encoding_apple_roman
214 215
#define FT_ENCODING_APPLE_ROMAN ft_encoding_apple_roman
#endif
216

217 218
#ifdef WORDS_BIGENDIAN
#define GET_BE_WORD(x) (x)
219
#define GET_BE_DWORD(x) (x)
220 221
#else
#define GET_BE_WORD(x) RtlUshortByteSwap(x)
222
#define GET_BE_DWORD(x) RtlUlongByteSwap(x)
223
#endif
224

225 226 227 228 229 230 231 232 233
#define MS_MAKE_TAG( _x1, _x2, _x3, _x4 ) \
          ( ( (FT_ULong)_x4 << 24 ) |     \
            ( (FT_ULong)_x3 << 16 ) |     \
            ( (FT_ULong)_x2 <<  8 ) |     \
              (FT_ULong)_x1         )

#define MS_GASP_TAG MS_MAKE_TAG('g', 'a', 's', 'p')
#define MS_GSUB_TAG MS_MAKE_TAG('G', 'S', 'U', 'B')
#define MS_KERN_TAG MS_MAKE_TAG('k', 'e', 'r', 'n')
234
#define MS_TTCF_TAG MS_MAKE_TAG('t', 't', 'c', 'f')
235 236 237 238 239 240
#define MS_VDMX_TAG MS_MAKE_TAG('V', 'D', 'M', 'X')

/* 'gasp' flags */
#define GASP_GRIDFIT 0x01
#define GASP_DOGRAY  0x02

241 242 243 244
#ifndef WINE_FONT_DIR
#define WINE_FONT_DIR "fonts"
#endif

Austin English's avatar
Austin English committed
245
/* This is basically a copy of FT_Bitmap_Size with an extra element added */
246 247 248
typedef struct {
    FT_Short height;
    FT_Short width;
249
    FT_Pos size;
250 251 252 253 254
    FT_Pos x_ppem;
    FT_Pos y_ppem;
    FT_Short internal_leading;
} Bitmap_Size;

255 256 257 258 259 260 261 262
/* FT_Bitmap_Size gained 3 new elements between FreeType 2.1.4 and 2.1.5
   So to let this compile on older versions of FreeType we'll define the
   new structure here. */
typedef struct {
    FT_Short height, width;
    FT_Pos size, x_ppem, y_ppem;
} My_FT_Bitmap_Size;

263 264 265 266 267 268 269
struct enum_data
{
    ENUMLOGFONTEXW elf;
    NEWTEXTMETRICEXW ntm;
    DWORD type;
};

270
typedef struct tagFace {
271
    struct list entry;
272
    unsigned int refcount;
273
    WCHAR *StyleName;
274
    WCHAR *FullName;
275
    WCHAR *file;
276 277
    dev_t dev;
    ino_t ino;
278 279
    void *font_data_ptr;
    DWORD font_data_size;
280
    FT_Long face_index;
281
    FONTSIGNATURE fs;
282
    DWORD ntmFlags;
283
    FT_Fixed font_version;
284 285
    BOOL scalable;
    Bitmap_Size size;     /* set if face is a bitmap */
286
    DWORD flags;          /* ADDFONT flags */
287
    struct tagFamily *family;
288
    /* Cached data for Enum */
289
    struct enum_data *cached_enum_data;
290 291
} Face;

292 293 294 295
#define ADDFONT_EXTERNAL_FONT 0x01
#define ADDFONT_ALLOW_BITMAP  0x02
#define ADDFONT_ADD_TO_CACHE  0x04
#define ADDFONT_ADD_RESOURCE  0x08  /* added through AddFontResource */
296
#define ADDFONT_VERTICAL_FONT 0x10
297 298
#define ADDFONT_AA_FLAGS(flags) ((flags) << 16)

299
typedef struct tagFamily {
300
    struct list entry;
301
    unsigned int refcount;
302 303
    WCHAR *FamilyName;
    WCHAR *EnglishName;
304
    struct list faces;
305
    struct list *replacement;
306 307
} Family;

308 309
typedef struct {
    GLYPHMETRICS gm;
310 311
    ABC          abc;  /* metrics of the unrotated char */
    BOOL         init;
312 313
} GM;

314 315 316 317 318 319 320 321 322
typedef struct {
    FLOAT eM11, eM12;
    FLOAT eM21, eM22;
} FMAT2;

typedef struct {
    DWORD hash;
    LOGFONTW lf;
    FMAT2 matrix;
323
    BOOL can_use_bitmap;
324 325
} FONT_DESC;

326 327
typedef struct tagGdiFont GdiFont;

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
#define FIRST_FONT_HANDLE 1
#define MAX_FONT_HANDLES  256

struct font_handle_entry
{
    void *obj;
    WORD  generation; /* generation count for reusing handle values */
};

static struct font_handle_entry font_handles[MAX_FONT_HANDLES];
static struct font_handle_entry *next_free;
static struct font_handle_entry *next_unused = font_handles;

static inline DWORD entry_to_handle( struct font_handle_entry *entry )
{
    unsigned int idx = entry - font_handles + FIRST_FONT_HANDLE;
    return idx | (entry->generation << 16);
}

static inline struct font_handle_entry *handle_entry( DWORD handle )
{
    unsigned int idx = LOWORD(handle) - FIRST_FONT_HANDLE;

    if (idx < MAX_FONT_HANDLES)
    {
        if (!HIWORD( handle ) || HIWORD( handle ) == font_handles[idx].generation)
            return &font_handles[idx];
    }
    if (handle) WARN( "invalid handle 0x%08x\n", handle );
    return NULL;
}

static DWORD alloc_font_handle( void *obj )
{
    struct font_handle_entry *entry;

    entry = next_free;
    if (entry)
        next_free = entry->obj;
    else if (next_unused < font_handles + MAX_FONT_HANDLES)
        entry = next_unused++;
    else
    {
        ERR( "out of realized font handles\n" );
        return 0;
    }
    entry->obj = obj;
    if (++entry->generation == 0xffff) entry->generation = 1;
    return entry_to_handle( entry );
}

static void free_font_handle( DWORD handle )
{
    struct font_handle_entry *entry;

    if ((entry = handle_entry( handle )))
    {
        entry->obj = next_free;
        next_free = entry;
    }
}

390 391
typedef struct {
    struct list entry;
392
    Face *face;
393
    GdiFont *font;
394 395
} CHILD_FONT;

396 397 398 399 400 401
struct font_fileinfo {
    FILETIME writetime;
    LARGE_INTEGER size;
    WCHAR path[1];
};

402
struct tagGdiFont {
403
    struct list entry;
404 405
    struct list unused_entry;
    unsigned int refcount;
406 407 408 409 410 411 412 413
    GM **gm;
    DWORD gmsize;
    OUTLINETEXTMETRICW *potm;
    DWORD total_kern_pairs;
    KERNINGPAIR *kern_pairs;
    struct list child_fonts;

    /* the following members can be accessed without locking, they are never modified after creation */
414
    FT_Face ft_face;
415
    struct font_mapping *mapping;
416
    LPWSTR name;
417
    int charset;
418
    int codepage;
419 420
    BOOL fake_italic;
    BOOL fake_bold;
421 422
    BYTE underline;
    BYTE strikeout;
423
    INT orientation;
424
    FONT_DESC font_desc;
425
    LONG aveWidth, ppem;
426
    double scale_y;
427 428
    SHORT yMax;
    SHORT yMin;
429
    DWORD ntmFlags;
430
    DWORD aa_flags;
431
    UINT ntmCellHeight, ntmAvgWidth;
432
    FONTSIGNATURE fs;
433
    GdiFont *base_font;
434
    VOID *GSUB_Table;
435
    const VOID *vert_feature;
436
    ULONG ttc_item_offset; /* 0 if font is not a part of TrueType collection */
437
    DWORD cache_num;
438
    DWORD instance_id;
439
    struct font_fileinfo *fileinfo;
440 441
};

442 443
typedef struct {
    struct list entry;
444
    const WCHAR *font_name;
445
    FONTSIGNATURE fs;
446 447 448
    struct list links;
} SYSTEM_LINKS;

449 450 451
struct enum_charset_element {
    DWORD mask;
    DWORD charset;
452
    WCHAR name[LF_FACESIZE];
453 454 455 456 457 458 459
};

struct enum_charset_list {
    DWORD total;
    struct enum_charset_element element[32];
};

460 461
#define GM_BLOCK_SIZE 128
#define FONT_GM(font,idx) (&(font)->gm[(idx) / GM_BLOCK_SIZE][(idx) % GM_BLOCK_SIZE])
462

463
static struct list gdi_font_list = LIST_INIT(gdi_font_list);
464
static struct list unused_gdi_font_list = LIST_INIT(unused_gdi_font_list);
465
static unsigned int unused_font_count;
466
#define UNUSED_CACHE_SIZE 10
467
static struct list system_links = LIST_INIT(system_links);
468

469 470
static struct list font_subst_list = LIST_INIT(font_subst_list);

471
static struct list font_list = LIST_INIT(font_list);
472

473 474 475
struct freetype_physdev
{
    struct gdi_physdev dev;
476
    GdiFont           *font;
477 478 479 480 481 482 483 484 485
};

static inline struct freetype_physdev *get_freetype_dev( PHYSDEV dev )
{
    return (struct freetype_physdev *)dev;
}

static const struct gdi_dc_funcs freetype_funcs;

486
static const WCHAR fontsW[] = {'\\','f','o','n','t','s','\0'};
487 488 489 490 491 492 493 494 495 496
static const WCHAR win9x_font_reg_key[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
                                           'W','i','n','d','o','w','s','\\',
                                           'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                           'F','o','n','t','s','\0'};

static const WCHAR winnt_font_reg_key[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
                                           'W','i','n','d','o','w','s',' ','N','T','\\',
                                           'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                           'F','o','n','t','s','\0'};

497 498 499 500 501
static const WCHAR system_fonts_reg_key[] = {'S','o','f','t','w','a','r','e','\\','F','o','n','t','s','\0'};
static const WCHAR FixedSys_Value[] = {'F','I','X','E','D','F','O','N','.','F','O','N','\0'};
static const WCHAR System_Value[] = {'F','O','N','T','S','.','F','O','N','\0'};
static const WCHAR OEMFont_Value[] = {'O','E','M','F','O','N','T','.','F','O','N','\0'};

502
static const WCHAR * const SystemFontValues[] = {
503 504
    System_Value,
    OEMFont_Value,
505
    FixedSys_Value,
506 507 508
    NULL
};

509
static const WCHAR external_fonts_reg_key[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\',
510
                                               'F','o','n','t','s','\\','E','x','t','e','r','n','a','l',' ','F','o','n','t','s','\0'};
511

512 513 514 515 516 517 518 519 520 521
/* Interesting and well-known (frequently-assumed!) font names */
static const WCHAR Lucida_Sans_Unicode[] = {'L','u','c','i','d','a',' ','S','a','n','s',' ','U','n','i','c','o','d','e',0};
static const WCHAR Microsoft_Sans_Serif[] = {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0 };
static const WCHAR Tahoma[] = {'T','a','h','o','m','a',0};
static const WCHAR MS_UI_Gothic[] = {'M','S',' ','U','I',' ','G','o','t','h','i','c',0};
static const WCHAR SimSun[] = {'S','i','m','S','u','n',0};
static const WCHAR Gulim[] = {'G','u','l','i','m',0};
static const WCHAR PMingLiU[] = {'P','M','i','n','g','L','i','U',0};
static const WCHAR Batang[] = {'B','a','t','a','n','g',0};

522 523 524 525 526
static const WCHAR arial[] = {'A','r','i','a','l',0};
static const WCHAR bitstream_vera_sans[] = {'B','i','t','s','t','r','e','a','m',' ','V','e','r','a',' ','S','a','n','s',0};
static const WCHAR bitstream_vera_sans_mono[] = {'B','i','t','s','t','r','e','a','m',' ','V','e','r','a',' ','S','a','n','s',' ','M','o','n','o',0};
static const WCHAR bitstream_vera_serif[] = {'B','i','t','s','t','r','e','a','m',' ','V','e','r','a',' ','S','e','r','i','f',0};
static const WCHAR courier_new[] = {'C','o','u','r','i','e','r',' ','N','e','w',0};
527 528 529
static const WCHAR liberation_mono[] = {'L','i','b','e','r','a','t','i','o','n',' ','M','o','n','o',0};
static const WCHAR liberation_sans[] = {'L','i','b','e','r','a','t','i','o','n',' ','S','a','n','s',0};
static const WCHAR liberation_serif[] = {'L','i','b','e','r','a','t','i','o','n',' ','S','e','r','i','f',0};
530
static const WCHAR times_new_roman[] = {'T','i','m','e','s',' ','N','e','w',' ','R','o','m','a','n',0};
531
static const WCHAR SymbolW[] = {'S','y','m','b','o','l','\0'};
532 533 534 535

static const WCHAR *default_serif_list[] =
{
    times_new_roman,
536
    liberation_serif,
537 538 539 540 541 542 543
    bitstream_vera_serif,
    NULL
};

static const WCHAR *default_fixed_list[] =
{
    courier_new,
544
    liberation_mono,
545 546 547 548 549 550 551
    bitstream_vera_sans_mono,
    NULL
};

static const WCHAR *default_sans_list[] =
{
    arial,
552
    liberation_sans,
553 554 555 556
    bitstream_vera_sans,
    NULL
};

557 558 559 560
static const WCHAR *default_serif = times_new_roman;
static const WCHAR *default_fixed = courier_new;
static const WCHAR *default_sans = arial;

561
typedef struct {
562 563
    WCHAR *name;
    INT charset;
564 565 566
} NameCs;

typedef struct tagFontSubst {
567 568 569
    struct list entry;
    NameCs from;
    NameCs to;
570 571
} FontSubst;

572 573 574 575 576 577
/* Registry font cache key and value names */
static const WCHAR wine_fonts_key[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\',
                                       'F','o','n','t','s',0};
static const WCHAR wine_fonts_cache_key[] = {'C','a','c','h','e',0};
static const WCHAR english_name_value[] = {'E','n','g','l','i','s','h',' ','N','a','m','e',0};
static const WCHAR face_index_value[] = {'I','n','d','e','x',0};
578
static const WCHAR face_ntmflags_value[] = {'N','t','m','f','l','a','g','s',0};
579 580 581 582 583 584
static const WCHAR face_version_value[] = {'V','e','r','s','i','o','n',0};
static const WCHAR face_height_value[] = {'H','e','i','g','h','t',0};
static const WCHAR face_width_value[] = {'W','i','d','t','h',0};
static const WCHAR face_size_value[] = {'S','i','z','e',0};
static const WCHAR face_x_ppem_value[] = {'X','p','p','e','m',0};
static const WCHAR face_y_ppem_value[] = {'Y','p','p','e','m',0};
585
static const WCHAR face_flags_value[] = {'F','l','a','g','s',0};
586 587
static const WCHAR face_internal_leading_value[] = {'I','n','t','e','r','n','a','l',' ','L','e','a','d','i','n','g',0};
static const WCHAR face_font_sig_value[] = {'F','o','n','t',' ','S','i','g','n','a','t','u','r','e',0};
588
static const WCHAR face_file_name_value[] = {'F','i','l','e',' ','N','a','m','e','\0'};
589 590 591
static const WCHAR face_full_name_value[] = {'F','u','l','l',' ','N','a','m','e','\0'};


592 593 594 595 596 597 598 599 600 601 602 603
struct font_mapping
{
    struct list entry;
    int         refcount;
    dev_t       dev;
    ino_t       ino;
    void       *data;
    size_t      size;
};

static struct list mappings_list = LIST_INIT( mappings_list );

604
static UINT default_aa_flags;
605
static HKEY hkey_font_cache;
606
static BOOL antialias_fakes = TRUE;
607

608 609 610 611 612 613 614 615 616
static CRITICAL_SECTION freetype_cs;
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &freetype_cs,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": freetype_cs") }
};
static CRITICAL_SECTION freetype_cs = { &critsect_debug, -1, 0, 0, 0, 0 };

617 618
static const WCHAR font_mutex_nameW[] = {'_','_','W','I','N','E','_','F','O','N','T','_','M','U','T','E','X','_','_','\0'};

619 620 621
static const WCHAR szDefaultFallbackLink[] = {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0};
static BOOL use_default_fallback = FALSE;

622
static BOOL get_glyph_index_linked(GdiFont *font, UINT c, GdiFont **linked_font, FT_UInt *glyph, BOOL *vert);
623
static BOOL get_outline_text_metrics(GdiFont *font);
624
static BOOL get_bitmap_text_metrics(GdiFont *font);
625
static BOOL get_text_metrics(GdiFont *font, LPTEXTMETRICW ptm);
626
static void remove_face_from_cache( Face *face );
627

628 629 630 631
static const WCHAR system_link[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
                                    'W','i','n','d','o','w','s',' ','N','T','\\',
                                    'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','F','o','n','t','L','i','n','k','\\',
                                    'S','y','s','t','e','m','L','i','n','k',0};
632

633 634 635 636 637 638 639 640 641
/****************************************
 *   Notes on .fon files
 *
 * The fonts System, FixedSys and Terminal are special.  There are typically multiple
 * versions installed for different resolutions and codepages.  Windows stores which one to use
 * in HKEY_CURRENT_CONFIG\\Software\\Fonts.
 *    Key            Meaning
 *  FIXEDFON.FON    FixedSys
 *  FONTS.FON       System
Vitaly Lipatov's avatar
Vitaly Lipatov committed
642
 *  OEMFONT.FON     Terminal
643
 *  LogPixels       Current dpi set by the display control panel applet
Austin English's avatar
Austin English committed
644
 *                  (HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\FontDPI
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
 *                  also has a LogPixels value that appears to mirror this)
 *
 * On my system these values have data: vgafix.fon, vgasys.fon, vga850.fon and 96 respectively
 * (vgaoem.fon would be your oemfont.fon if you have a US setup).
 * If the resolution is changed to be >= 109dpi then the fonts goto 8514fix, 8514sys and 8514oem
 * (not sure what's happening to the oem codepage here). 109 is nicely halfway between 96 and 120dpi,
 * so that makes sense.
 *
 * Additionally Windows also loads the fonts listed in the [386enh] section of system.ini (this doesn't appear
 * to be mapped into the registry on Windows 2000 at least).
 * I have
 * woafont=app850.fon
 * ega80woa.fon=ega80850.fon
 * ega40woa.fon=ega40850.fon
 * cga80woa.fon=cga80850.fon
 * cga40woa.fon=cga40850.fon
 */

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
/* These are all structures needed for the GSUB table */


typedef struct {
    DWORD version;
    WORD ScriptList;
    WORD FeatureList;
    WORD LookupList;
} GSUB_Header;

typedef struct {
    CHAR ScriptTag[4];
    WORD Script;
} GSUB_ScriptRecord;

typedef struct {
    WORD ScriptCount;
    GSUB_ScriptRecord ScriptRecord[1];
} GSUB_ScriptList;

typedef struct {
    CHAR LangSysTag[4];
    WORD LangSys;
} GSUB_LangSysRecord;

typedef struct {
    WORD DefaultLangSys;
    WORD LangSysCount;
    GSUB_LangSysRecord LangSysRecord[1];
} GSUB_Script;

typedef struct {
    WORD LookupOrder; /* Reserved */
    WORD ReqFeatureIndex;
    WORD FeatureCount;
    WORD FeatureIndex[1];
} GSUB_LangSys;

typedef struct {
    CHAR FeatureTag[4];
    WORD Feature;
} GSUB_FeatureRecord;

typedef struct {
    WORD FeatureCount;
    GSUB_FeatureRecord FeatureRecord[1];
} GSUB_FeatureList;

typedef struct {
    WORD FeatureParams; /* Reserved */
    WORD LookupCount;
    WORD LookupListIndex[1];
} GSUB_Feature;

typedef struct {
    WORD LookupCount;
    WORD Lookup[1];
} GSUB_LookupList;

typedef struct {
    WORD LookupType;
    WORD LookupFlag;
    WORD SubTableCount;
    WORD SubTable[1];
} GSUB_LookupTable;

typedef struct {
    WORD CoverageFormat;
    WORD GlyphCount;
    WORD GlyphArray[1];
} GSUB_CoverageFormat1;

typedef struct {
    WORD Start;
    WORD End;
    WORD StartCoverageIndex;
} GSUB_RangeRecord;

typedef struct {
    WORD CoverageFormat;
    WORD RangeCount;
    GSUB_RangeRecord RangeRecord[1];
} GSUB_CoverageFormat2;

typedef struct {
    WORD SubstFormat; /* = 1 */
    WORD Coverage;
    WORD DeltaGlyphID;
} GSUB_SingleSubstFormat1;

typedef struct {
    WORD SubstFormat; /* = 2 */
    WORD Coverage;
    WORD GlyphCount;
    WORD Substitute[1];
}GSUB_SingleSubstFormat2;

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
#ifdef HAVE_CARBON_CARBON_H
static char *find_cache_dir(void)
{
    FSRef ref;
    OSErr err;
    static char cached_path[MAX_PATH];
    static const char *wine = "/Wine", *fonts = "/Fonts";

    if(*cached_path) return cached_path;

    err = FSFindFolder(kUserDomain, kCachedDataFolderType, kCreateFolder, &ref);
    if(err != noErr)
    {
        WARN("can't create cached data folder\n");
        return NULL;
    }
    err = FSRefMakePath(&ref, (unsigned char*)cached_path, sizeof(cached_path));
    if(err != noErr)
    {
        WARN("can't create cached data path\n");
        *cached_path = '\0';
        return NULL;
    }
    if(strlen(cached_path) + strlen(wine) + strlen(fonts) + 1 > sizeof(cached_path))
    {
        ERR("Could not create full path\n");
        *cached_path = '\0';
        return NULL;
    }
    strcat(cached_path, wine);

    if(mkdir(cached_path, 0700) == -1 && errno != EEXIST)
    {
        WARN("Couldn't mkdir %s\n", cached_path);
        *cached_path = '\0';
        return NULL;
    }
    strcat(cached_path, fonts);
    if(mkdir(cached_path, 0700) == -1 && errno != EEXIST)
    {
        WARN("Couldn't mkdir %s\n", cached_path);
        *cached_path = '\0';
        return NULL;
    }
    return cached_path;
}

/******************************************************************
 *            expand_mac_font
 *
 * Extracts individual TrueType font files from a Mac suitcase font
 * and saves them into the user's caches directory (see
 * find_cache_dir()).
 * Returns a NULL terminated array of filenames.
 *
 * We do this because they are apps that try to read ttf files
 * themselves and they don't like Mac suitcase files.
 */
static char **expand_mac_font(const char *path)
{
    FSRef ref;
821
    ResFileRefNum res_ref;
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    OSStatus s;
    unsigned int idx;
    const char *out_dir;
    const char *filename;
    int output_len;
    struct {
        char **array;
        unsigned int size, max_size;
    } ret;

    TRACE("path %s\n", path);

    s = FSPathMakeRef((unsigned char*)path, &ref, FALSE);
    if(s != noErr)
    {
        WARN("failed to get ref\n");
        return NULL;
    }

    s = FSOpenResourceFile(&ref, 0, NULL, fsRdPerm, &res_ref);
    if(s != noErr)
    {
        TRACE("no data fork, so trying resource fork\n");
        res_ref = FSOpenResFile(&ref, fsRdPerm);
        if(res_ref == -1)
        {
            TRACE("unable to open resource fork\n");
            return NULL;
        }
    }

    ret.size = 0;
    ret.max_size = 10;
    ret.array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ret.max_size * sizeof(*ret.array));
    if(!ret.array)
    {
        CloseResFile(res_ref);
        return NULL;
    }

    out_dir = find_cache_dir();

    filename = strrchr(path, '/');
    if(!filename) filename = path;
    else filename++;

    /* output filename has the form out_dir/filename_%04x.ttf */
    output_len = strlen(out_dir) + 1 + strlen(filename) + 5 + 5;

    UseResFile(res_ref);
    idx = 1;
    while(1)
    {
        FamRec *fam_rec;
        unsigned short *num_faces_ptr, num_faces, face;
        AsscEntry *assoc;
        Handle fond;
879
        ResType fond_res = FT_MAKE_TAG('F','O','N','D');
880

881
        fond = Get1IndResource(fond_res, idx);
882 883 884 885 886 887 888 889 890 891 892 893 894
        if(!fond) break;
        TRACE("got fond resource %d\n", idx);
        HLock(fond);

        fam_rec = *(FamRec**)fond;
        num_faces_ptr = (unsigned short *)(fam_rec + 1);
        num_faces = GET_BE_WORD(*num_faces_ptr);
        num_faces++;
        assoc = (AsscEntry*)(num_faces_ptr + 1);
        TRACE("num faces %04x\n", num_faces);
        for(face = 0; face < num_faces; face++, assoc++)
        {
            Handle sfnt;
895
            ResType sfnt_res = FT_MAKE_TAG('s','f','n','t');
896 897 898 899 900 901 902 903 904 905 906 907
            unsigned short size, font_id;
            char *output;

            size = GET_BE_WORD(assoc->fontSize);
            font_id = GET_BE_WORD(assoc->fontID);
            if(size != 0)
            {
                TRACE("skipping id %04x because it's not scalable (fixed size %d)\n", font_id, size);
                continue;
            }

            TRACE("trying to load sfnt id %04x\n", font_id);
908
            sfnt = GetResource(sfnt_res, font_id);
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
            if(!sfnt)
            {
                TRACE("can't get sfnt resource %04x\n", font_id);
                continue;
            }

            output = HeapAlloc(GetProcessHeap(), 0, output_len);
            if(output)
            {
                int fd;

                sprintf(output, "%s/%s_%04x.ttf", out_dir, filename, font_id);

                fd = open(output, O_CREAT | O_EXCL | O_WRONLY, 0600);
                if(fd != -1 || errno == EEXIST)
                {
                    if(fd != -1)
                    {
                        unsigned char *sfnt_data;

                        HLock(sfnt);
                        sfnt_data = *(unsigned char**)sfnt;
                        write(fd, sfnt_data, GetHandleSize(sfnt));
                        HUnlock(sfnt);
                        close(fd);
                    }
                    if(ret.size >= ret.max_size - 1) /* Always want the last element to be NULL */
                    {
                        ret.max_size *= 2;
                        ret.array = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ret.array, ret.max_size * sizeof(*ret.array));
                    }
                    ret.array[ret.size++] = output;
                }
                else
                {
                    WARN("unable to create %s\n", output);
                    HeapFree(GetProcessHeap(), 0, output);
                }
            }
            ReleaseResource(sfnt);
        }
        HUnlock(fond);
        ReleaseResource(fond);
        idx++;
    }
    CloseResFile(res_ref);

    return ret.array;
}

#endif /* HAVE_CARBON_CARBON_H */
960

961 962 963 964
static inline BOOL is_win9x(void)
{
    return GetVersion() & 0x80000000;
}
965
/* 
966 967
   This function builds an FT_Fixed from a double. It fails if the absolute
   value of the float number is greater than 32768.
968
*/
969
static inline FT_Fixed FT_FixedFromFloat(double f)
970
{
971
	return f * 0x10000;
972 973 974 975 976 977 978 979
}

/* 
   This function builds an FT_Fixed from a FIXED. It simply put f.value 
   in the highest 16 bits and f.fract in the lowest 16 bits of the FT_Fixed.
*/
static inline FT_Fixed FT_FixedFromFIXED(FIXED f)
{
980
    return (FT_Fixed)((int)f.value << 16 | (unsigned int)f.fract);
981 982
}

983 984 985 986 987 988 989 990 991 992 993 994 995
static BOOL is_hinting_enabled(void)
{
    static int enabled = -1;

    if (enabled == -1)
    {
        /* Use the >= 2.2.0 function if available */
        if (pFT_Get_TrueType_Engine_Type)
        {
            FT_TrueTypeEngineType type = pFT_Get_TrueType_Engine_Type(library);
            enabled = (type == FT_TRUETYPE_ENGINE_TYPE_PATENTED);
        }
        else enabled = FALSE;
996
        TRACE("hinting is %senabled\n", enabled ? "" : "NOT ");
997 998 999 1000 1001 1002 1003 1004
    }
    return enabled;
}

static BOOL is_subpixel_rendering_enabled( void )
{
    static int enabled = -1;
    if (enabled == -1)
1005
    {
1006
        /* FreeType >= 2.8.1 offers LCD-optimezed rendering without lcd filters. */
1007
        if (FT_SimpleVersion >= FT_VERSION_VALUE(2, 8, 1))
1008 1009 1010 1011 1012 1013 1014 1015
            enabled = TRUE;
#ifdef FT_LCD_FILTER_H
        else if (pFT_Library_SetLcdFilter &&
                 pFT_Library_SetLcdFilter( NULL, 0 ) != FT_Err_Unimplemented_Feature)
            enabled = TRUE;
#endif
        else enabled = FALSE;

1016 1017
        TRACE("subpixel rendering is %senabled\n", enabled ? "" : "NOT ");
    }
1018 1019 1020
    return enabled;
}

1021

1022 1023 1024 1025 1026 1027 1028 1029
static const struct list *get_face_list_from_family(const Family *family)
{
    if (!list_empty(&family->faces))
        return &family->faces;
    else
        return family->replacement;
}

1030
static Face *find_face_from_filename(const WCHAR *file_name, const WCHAR *face_name)
1031 1032 1033
{
    Family *family;
    Face *face;
1034
    const WCHAR *file;
1035

1036
    TRACE("looking for file %s name %s\n", debugstr_w(file_name), debugstr_w(face_name));
1037 1038 1039

    LIST_FOR_EACH_ENTRY(family, &font_list, Family, entry)
    {
1040
        const struct list *face_list;
1041
        if(face_name && strncmpiW(face_name, family->FamilyName, LF_FACESIZE - 1))
1042
            continue;
1043 1044
        face_list = get_face_list_from_family(family);
        LIST_FOR_EACH_ENTRY(face, face_list, Face, entry)
1045
        {
1046 1047
            if (!face->file)
                continue;
1048
            file = strrchrW(face->file, '/');
1049 1050 1051 1052
            if(!file)
                file = face->file;
            else
                file++;
1053 1054 1055
            if(strcmpiW(file, file_name)) continue;
            face->refcount++;
            return face;
1056 1057
	}
    }
1058
    return NULL;
1059 1060 1061 1062 1063 1064 1065 1066
}

static Family *find_family_from_name(const WCHAR *name)
{
    Family *family;

    LIST_FOR_EACH_ENTRY(family, &font_list, Family, entry)
    {
1067
        if(!strncmpiW(family->FamilyName, name, LF_FACESIZE -1))
1068 1069 1070 1071 1072
            return family;
    }

    return NULL;
}
1073

1074 1075 1076 1077 1078 1079
static Family *find_family_from_any_name(const WCHAR *name)
{
    Family *family;

    LIST_FOR_EACH_ENTRY(family, &font_list, Family, entry)
    {
1080
        if(!strncmpiW(family->FamilyName, name, LF_FACESIZE - 1))
1081
            return family;
1082
        if(family->EnglishName && !strncmpiW(family->EnglishName, name, LF_FACESIZE - 1))
1083 1084 1085 1086 1087 1088
            return family;
    }

    return NULL;
}

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
static void DumpSubstList(void)
{
    FontSubst *psub;

    LIST_FOR_EACH_ENTRY(psub, &font_subst_list, FontSubst, entry)
    {
        if(psub->from.charset != -1 || psub->to.charset != -1)
	    TRACE("%s:%d -> %s:%d\n", debugstr_w(psub->from.name),
	      psub->from.charset, debugstr_w(psub->to.name), psub->to.charset);
	else
	    TRACE("%s -> %s\n", debugstr_w(psub->from.name),
		  debugstr_w(psub->to.name));
    }
}

static LPWSTR strdupW(LPCWSTR p)
{
    LPWSTR ret;
    DWORD len = (strlenW(p) + 1) * sizeof(WCHAR);
    ret = HeapAlloc(GetProcessHeap(), 0, len);
    memcpy(ret, p, len);
    return ret;
}

static FontSubst *get_font_subst(const struct list *subst_list, const WCHAR *from_name,
                                 INT from_charset)
{
    FontSubst *element;

    LIST_FOR_EACH_ENTRY(element, subst_list, FontSubst, entry)
    {
        if(!strcmpiW(element->from.name, from_name) &&
           (element->from.charset == from_charset ||
            element->from.charset == -1))
            return element;
    }

    return NULL;
}

#define ADD_FONT_SUBST_FORCE  1

static BOOL add_font_subst(struct list *subst_list, FontSubst *subst, INT flags)
{
    FontSubst *from_exist, *to_exist;

    from_exist = get_font_subst(subst_list, subst->from.name, subst->from.charset);

    if(from_exist && (flags & ADD_FONT_SUBST_FORCE))
    {
        list_remove(&from_exist->entry);
1140 1141
        HeapFree(GetProcessHeap(), 0, from_exist->from.name);
        HeapFree(GetProcessHeap(), 0, from_exist->to.name);
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
        HeapFree(GetProcessHeap(), 0, from_exist);
        from_exist = NULL;
    }

    if(!from_exist)
    {
        to_exist = get_font_subst(subst_list, subst->to.name, subst->to.charset);

        if(to_exist)
        {
            HeapFree(GetProcessHeap(), 0, subst->to.name);
            subst->to.name = strdupW(to_exist->to.name);
        }
            
        list_add_tail(subst_list, &subst->entry);

        return TRUE;
    }

1161 1162 1163
    HeapFree(GetProcessHeap(), 0, subst->from.name);
    HeapFree(GetProcessHeap(), 0, subst->to.name);
    HeapFree(GetProcessHeap(), 0, subst);
1164 1165 1166
    return FALSE;
}

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
static WCHAR *towstr(UINT cp, const char *str)
{
    int len;
    WCHAR *wstr;

    len = MultiByteToWideChar(cp, 0, str, -1, NULL, 0);
    wstr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
    MultiByteToWideChar(cp, 0, str, -1, wstr, len);
    return wstr;
}

1178 1179 1180 1181 1182 1183 1184 1185
static char *strWtoA(UINT cp, const WCHAR *str)
{
    int len = WideCharToMultiByte( cp, 0, str, -1, NULL, 0, NULL, NULL );
    char *ret = HeapAlloc( GetProcessHeap(), 0, len );
    WideCharToMultiByte( cp, 0, str, -1, ret, len, NULL, NULL );
    return ret;
}

1186 1187 1188 1189 1190 1191 1192 1193 1194
static void split_subst_info(NameCs *nc, LPSTR str)
{
    CHAR *p = strrchr(str, ',');

    nc->charset = -1;
    if(p && *(p+1)) {
        nc->charset = strtol(p+1, NULL, 10);
	*p = '\0';
    }
1195
    nc->name = towstr(CP_ACP, str);
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
}

static void LoadSubstList(void)
{
    FontSubst *psub;
    HKEY hkey;
    DWORD valuelen, datalen, i = 0, type, dlen, vlen;
    LPSTR value;
    LPVOID data;

    if(RegOpenKeyA(HKEY_LOCAL_MACHINE,
		   "Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes",
		   &hkey) == ERROR_SUCCESS) {

        RegQueryInfoKeyA(hkey, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
			 &valuelen, &datalen, NULL, NULL);

	valuelen++; /* returned value doesn't include room for '\0' */
	value = HeapAlloc(GetProcessHeap(), 0, valuelen * sizeof(CHAR));
	data = HeapAlloc(GetProcessHeap(), 0, datalen);

	dlen = datalen;
	vlen = valuelen;
	while(RegEnumValueA(hkey, i++, value, &vlen, NULL, &type, data,
			    &dlen) == ERROR_SUCCESS) {
	    TRACE("Got %s=%s\n", debugstr_a(value), debugstr_a(data));

	    psub = HeapAlloc(GetProcessHeap(), 0, sizeof(*psub));
	    split_subst_info(&psub->from, value);
	    split_subst_info(&psub->to, data);

	    /* Win 2000 doesn't allow mapping between different charsets
	       or mapping of DEFAULT_CHARSET */
1229
	    if ((psub->from.charset && psub->to.charset != psub->from.charset) ||
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
	       psub->to.charset == DEFAULT_CHARSET) {
	        HeapFree(GetProcessHeap(), 0, psub->to.name);
		HeapFree(GetProcessHeap(), 0, psub->from.name);
		HeapFree(GetProcessHeap(), 0, psub);
	    } else {
	        add_font_subst(&font_subst_list, psub, 0);
	    }
	    /* reset dlen and vlen */
	    dlen = datalen;
	    vlen = valuelen;
	}
	HeapFree(GetProcessHeap(), 0, data);
	HeapFree(GetProcessHeap(), 0, value);
	RegCloseKey(hkey);
    }
}

1247

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
static const LANGID mac_langid_table[] =
{
    MAKELANGID(LANG_ENGLISH,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_ENGLISH */
    MAKELANGID(LANG_FRENCH,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_FRENCH */
    MAKELANGID(LANG_GERMAN,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_GERMAN */
    MAKELANGID(LANG_ITALIAN,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_ITALIAN */
    MAKELANGID(LANG_DUTCH,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_DUTCH */
    MAKELANGID(LANG_SWEDISH,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_SWEDISH */
    MAKELANGID(LANG_SPANISH,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_SPANISH */
    MAKELANGID(LANG_DANISH,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_DANISH */
    MAKELANGID(LANG_PORTUGUESE,SUBLANG_DEFAULT),             /* TT_MAC_LANGID_PORTUGUESE */
    MAKELANGID(LANG_NORWEGIAN,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_NORWEGIAN */
    MAKELANGID(LANG_HEBREW,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_HEBREW */
    MAKELANGID(LANG_JAPANESE,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_JAPANESE */
    MAKELANGID(LANG_ARABIC,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_ARABIC */
    MAKELANGID(LANG_FINNISH,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_FINNISH */
    MAKELANGID(LANG_GREEK,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_GREEK */
    MAKELANGID(LANG_ICELANDIC,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_ICELANDIC */
    MAKELANGID(LANG_MALTESE,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_MALTESE */
    MAKELANGID(LANG_TURKISH,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_TURKISH */
    MAKELANGID(LANG_CROATIAN,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_CROATIAN */
    MAKELANGID(LANG_CHINESE_TRADITIONAL,SUBLANG_DEFAULT),    /* TT_MAC_LANGID_CHINESE_TRADITIONAL */
    MAKELANGID(LANG_URDU,SUBLANG_DEFAULT),                   /* TT_MAC_LANGID_URDU */
    MAKELANGID(LANG_HINDI,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_HINDI */
    MAKELANGID(LANG_THAI,SUBLANG_DEFAULT),                   /* TT_MAC_LANGID_THAI */
    MAKELANGID(LANG_KOREAN,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_KOREAN */
    MAKELANGID(LANG_LITHUANIAN,SUBLANG_DEFAULT),             /* TT_MAC_LANGID_LITHUANIAN */
    MAKELANGID(LANG_POLISH,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_POLISH */
    MAKELANGID(LANG_HUNGARIAN,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_HUNGARIAN */
    MAKELANGID(LANG_ESTONIAN,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_ESTONIAN */
    MAKELANGID(LANG_LATVIAN,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_LETTISH */
    MAKELANGID(LANG_SAMI,SUBLANG_DEFAULT),                   /* TT_MAC_LANGID_SAAMISK */
    MAKELANGID(LANG_FAEROESE,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_FAEROESE */
    MAKELANGID(LANG_FARSI,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_FARSI */
    MAKELANGID(LANG_RUSSIAN,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_RUSSIAN */
    MAKELANGID(LANG_CHINESE_SIMPLIFIED,SUBLANG_DEFAULT),     /* TT_MAC_LANGID_CHINESE_SIMPLIFIED */
    MAKELANGID(LANG_DUTCH,SUBLANG_DUTCH_BELGIAN),            /* TT_MAC_LANGID_FLEMISH */
    MAKELANGID(LANG_IRISH,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_IRISH */
    MAKELANGID(LANG_ALBANIAN,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_ALBANIAN */
    MAKELANGID(LANG_ROMANIAN,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_ROMANIAN */
    MAKELANGID(LANG_CZECH,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_CZECH */
    MAKELANGID(LANG_SLOVAK,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_SLOVAK */
    MAKELANGID(LANG_SLOVENIAN,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_SLOVENIAN */
    0,                                                       /* TT_MAC_LANGID_YIDDISH */
    MAKELANGID(LANG_SERBIAN,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_SERBIAN */
    MAKELANGID(LANG_MACEDONIAN,SUBLANG_DEFAULT),             /* TT_MAC_LANGID_MACEDONIAN */
    MAKELANGID(LANG_BULGARIAN,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_BULGARIAN */
    MAKELANGID(LANG_UKRAINIAN,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_UKRAINIAN */
    MAKELANGID(LANG_BELARUSIAN,SUBLANG_DEFAULT),             /* TT_MAC_LANGID_BYELORUSSIAN */
    MAKELANGID(LANG_UZBEK,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_UZBEK */
    MAKELANGID(LANG_KAZAK,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_KAZAKH */
    MAKELANGID(LANG_AZERI,SUBLANG_AZERI_CYRILLIC),           /* TT_MAC_LANGID_AZERBAIJANI */
    0,                                                       /* TT_MAC_LANGID_AZERBAIJANI_ARABIC_SCRIPT */
    MAKELANGID(LANG_ARMENIAN,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_ARMENIAN */
    MAKELANGID(LANG_GEORGIAN,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_GEORGIAN */
    0,                                                       /* TT_MAC_LANGID_MOLDAVIAN */
    MAKELANGID(LANG_KYRGYZ,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_KIRGHIZ */
    MAKELANGID(LANG_TAJIK,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_TAJIKI */
    MAKELANGID(LANG_TURKMEN,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_TURKMEN */
    MAKELANGID(LANG_MONGOLIAN,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_MONGOLIAN */
    MAKELANGID(LANG_MONGOLIAN,SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA), /* TT_MAC_LANGID_MONGOLIAN_CYRILLIC_SCRIPT */
    MAKELANGID(LANG_PASHTO,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_PASHTO */
    0,                                                       /* TT_MAC_LANGID_KURDISH */
    MAKELANGID(LANG_KASHMIRI,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_KASHMIRI */
    MAKELANGID(LANG_SINDHI,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_SINDHI */
    MAKELANGID(LANG_TIBETAN,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_TIBETAN */
    MAKELANGID(LANG_NEPALI,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_NEPALI */
    MAKELANGID(LANG_SANSKRIT,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_SANSKRIT */
    MAKELANGID(LANG_MARATHI,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_MARATHI */
    MAKELANGID(LANG_BENGALI,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_BENGALI */
    MAKELANGID(LANG_ASSAMESE,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_ASSAMESE */
    MAKELANGID(LANG_GUJARATI,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_GUJARATI */
    MAKELANGID(LANG_PUNJABI,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_PUNJABI */
    MAKELANGID(LANG_ORIYA,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_ORIYA */
    MAKELANGID(LANG_MALAYALAM,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_MALAYALAM */
    MAKELANGID(LANG_KANNADA,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_KANNADA */
    MAKELANGID(LANG_TAMIL,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_TAMIL */
    MAKELANGID(LANG_TELUGU,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_TELUGU */
    MAKELANGID(LANG_SINHALESE,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_SINHALESE */
    0,                                                       /* TT_MAC_LANGID_BURMESE */
    MAKELANGID(LANG_KHMER,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_KHMER */
    MAKELANGID(LANG_LAO,SUBLANG_DEFAULT),                    /* TT_MAC_LANGID_LAO */
    MAKELANGID(LANG_VIETNAMESE,SUBLANG_DEFAULT),             /* TT_MAC_LANGID_VIETNAMESE */
    MAKELANGID(LANG_INDONESIAN,SUBLANG_DEFAULT),             /* TT_MAC_LANGID_INDONESIAN */
    0,                                                       /* TT_MAC_LANGID_TAGALOG */
    MAKELANGID(LANG_MALAY,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_MALAY_ROMAN_SCRIPT */
    0,                                                       /* TT_MAC_LANGID_MALAY_ARABIC_SCRIPT */
    MAKELANGID(LANG_AMHARIC,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_AMHARIC */
    MAKELANGID(LANG_TIGRIGNA,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_TIGRINYA */
    0,                                                       /* TT_MAC_LANGID_GALLA */
    0,                                                       /* TT_MAC_LANGID_SOMALI */
    MAKELANGID(LANG_SWAHILI,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_SWAHILI */
    0,                                                       /* TT_MAC_LANGID_RUANDA */
    0,                                                       /* TT_MAC_LANGID_RUNDI */
    0,                                                       /* TT_MAC_LANGID_CHEWA */
    MAKELANGID(LANG_MALAGASY,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_MALAGASY */
    MAKELANGID(LANG_ESPERANTO,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_ESPERANTO */
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,       /* 95-111 */
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,          /* 112-127 */
    MAKELANGID(LANG_WELSH,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_WELSH */
    MAKELANGID(LANG_BASQUE,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_BASQUE */
    MAKELANGID(LANG_CATALAN,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_CATALAN */
    0,                                                       /* TT_MAC_LANGID_LATIN */
    MAKELANGID(LANG_QUECHUA,SUBLANG_DEFAULT),                /* TT_MAC_LANGID_QUECHUA */
    0,                                                       /* TT_MAC_LANGID_GUARANI */
    0,                                                       /* TT_MAC_LANGID_AYMARA */
    MAKELANGID(LANG_TATAR,SUBLANG_DEFAULT),                  /* TT_MAC_LANGID_TATAR */
    MAKELANGID(LANG_UIGHUR,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_UIGHUR */
    0,                                                       /* TT_MAC_LANGID_DZONGKHA */
    0,                                                       /* TT_MAC_LANGID_JAVANESE */
    0,                                                       /* TT_MAC_LANGID_SUNDANESE */
    MAKELANGID(LANG_GALICIAN,SUBLANG_DEFAULT),               /* TT_MAC_LANGID_GALICIAN */
    MAKELANGID(LANG_AFRIKAANS,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_AFRIKAANS */
    MAKELANGID(LANG_BRETON,SUBLANG_DEFAULT),                 /* TT_MAC_LANGID_BRETON */
    MAKELANGID(LANG_INUKTITUT,SUBLANG_DEFAULT),              /* TT_MAC_LANGID_INUKTITUT */
    MAKELANGID(LANG_SCOTTISH_GAELIC,SUBLANG_DEFAULT),        /* TT_MAC_LANGID_SCOTTISH_GAELIC */
    MAKELANGID(LANG_MANX_GAELIC,SUBLANG_DEFAULT),            /* TT_MAC_LANGID_MANX_GAELIC */
    MAKELANGID(LANG_IRISH,SUBLANG_IRISH_IRELAND),            /* TT_MAC_LANGID_IRISH_GAELIC */
    0,                                                       /* TT_MAC_LANGID_TONGAN */
    0,                                                       /* TT_MAC_LANGID_GREEK_POLYTONIC */
    MAKELANGID(LANG_GREENLANDIC,SUBLANG_DEFAULT),            /* TT_MAC_LANGID_GREELANDIC */
    MAKELANGID(LANG_AZERI,SUBLANG_AZERI_LATIN),              /* TT_MAC_LANGID_AZERBAIJANI_ROMAN_SCRIPT */
};

static inline WORD get_mac_code_page( const FT_SfntName *name )
{
    if (name->encoding_id == TT_MAC_ID_SIMPLIFIED_CHINESE) return 10008;  /* special case */
    return 10000 + name->encoding_id;
}

1378
static int match_name_table_language( const FT_SfntName *name, LANGID lang )
1379
{
1380
    LANGID name_lang;
1381
    int res = 0;
1382

1383
    switch (name->platform_id)
1384
    {
1385
    case TT_PLATFORM_MICROSOFT:
1386
        res += 5;  /* prefer the Microsoft name */
1387
        switch (name->encoding_id)
1388
        {
1389 1390 1391 1392 1393 1394
        case TT_MS_ID_UNICODE_CS:
        case TT_MS_ID_SYMBOL_CS:
            name_lang = name->language_id;
            break;
        default:
            return 0;
1395
        }
1396
        break;
1397 1398
    case TT_PLATFORM_MACINTOSH:
        if (!IsValidCodePage( get_mac_code_page( name ))) return 0;
1399
        if (name->language_id >= ARRAY_SIZE( mac_langid_table )) return 0;
1400 1401
        name_lang = mac_langid_table[name->language_id];
        break;
1402
    case TT_PLATFORM_APPLE_UNICODE:
1403
        res += 2;  /* prefer Unicode encodings */
1404 1405 1406 1407 1408
        switch (name->encoding_id)
        {
        case TT_APPLE_ID_DEFAULT:
        case TT_APPLE_ID_ISO_10646:
        case TT_APPLE_ID_UNICODE_2_0:
1409
            if (name->language_id >= ARRAY_SIZE( mac_langid_table )) return 0;
1410 1411 1412 1413 1414 1415
            name_lang = mac_langid_table[name->language_id];
            break;
        default:
            return 0;
        }
        break;
1416 1417
    default:
        return 0;
1418
    }
1419 1420 1421 1422
    if (name_lang == lang) res += 30;
    else if (PRIMARYLANGID( name_lang ) == PRIMARYLANGID( lang )) res += 20;
    else if (name_lang == MAKELANGID( LANG_ENGLISH, SUBLANG_DEFAULT )) res += 10;
    return res;
1423 1424 1425 1426 1427
}

static WCHAR *copy_name_table_string( const FT_SfntName *name )
{
    WCHAR *ret;
1428
    WORD codepage;
1429 1430
    int i;

1431 1432
    switch (name->platform_id)
    {
1433
    case TT_PLATFORM_APPLE_UNICODE:
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
    case TT_PLATFORM_MICROSOFT:
        ret = HeapAlloc( GetProcessHeap(), 0, name->string_len + sizeof(WCHAR) );
        for (i = 0; i < name->string_len / 2; i++)
            ret[i] = (name->string[i * 2] << 8) | name->string[i * 2 + 1];
        ret[i] = 0;
        return ret;
    case TT_PLATFORM_MACINTOSH:
        codepage = get_mac_code_page( name );
        i = MultiByteToWideChar( codepage, 0, (char *)name->string, name->string_len, NULL, 0 );
        ret = HeapAlloc( GetProcessHeap(), 0, (i + 1) * sizeof(WCHAR) );
        MultiByteToWideChar( codepage, 0, (char *)name->string, name->string_len, ret, i );
        ret[i] = 0;
        return ret;
    }
    return NULL;
1449
}
1450

1451
static WCHAR *get_face_name(FT_Face ft_face, FT_UShort name_id, LANGID language_id)
1452 1453
{
    FT_SfntName name;
1454 1455
    FT_UInt num_names, name_index;
    int res, best_lang = 0, best_index = -1;
1456

1457
    if (!FT_IS_SFNT(ft_face)) return NULL;
1458

1459
    num_names = pFT_Get_Sfnt_Name_Count( ft_face );
1460

1461 1462 1463 1464 1465 1466
    for (name_index = 0; name_index < num_names; name_index++)
    {
        if (pFT_Get_Sfnt_Name( ft_face, name_index, &name )) continue;
        if (name.name_id != name_id) continue;
        res = match_name_table_language( &name, language_id );
        if (res > best_lang)
1467
        {
1468 1469
            best_lang = res;
            best_index = name_index;
1470 1471 1472
        }
    }

1473 1474 1475 1476 1477 1478 1479 1480
    if (best_index != -1 && !pFT_Get_Sfnt_Name( ft_face, best_index, &name ))
    {
        WCHAR *ret = copy_name_table_string( &name );
        TRACE( "name %u found platform %u lang %04x %s\n",
               name_id, name.platform_id, name.language_id, debugstr_w( ret ));
        return ret;
    }
    return NULL;
1481 1482
}

1483 1484 1485 1486
static inline BOOL faces_equal( const Face *f1, const Face *f2 )
{
    if (strcmpiW( f1->StyleName, f2->StyleName )) return FALSE;
    if (f1->scalable) return TRUE;
1487
    if (f1->size.y_ppem != f2->size.y_ppem) return FALSE;
1488 1489 1490
    return !memcmp( &f1->fs, &f2->fs, sizeof(f1->fs) );
}

1491
static void release_family( Family *family )
1492
{
1493 1494 1495 1496 1497 1498
    if (--family->refcount) return;
    assert( list_empty( &family->faces ));
    list_remove( &family->entry );
    HeapFree( GetProcessHeap(), 0, family->FamilyName );
    HeapFree( GetProcessHeap(), 0, family->EnglishName );
    HeapFree( GetProcessHeap(), 0, family );
1499 1500
}

1501
static void release_face( Face *face )
1502
{
1503 1504
    if (--face->refcount) return;
    if (face->family)
1505
    {
1506
        if (face->flags & ADDFONT_ADD_TO_CACHE) remove_face_from_cache( face );
1507
        list_remove( &face->entry );
1508
        release_family( face->family );
1509
    }
1510 1511 1512 1513 1514
    HeapFree( GetProcessHeap(), 0, face->file );
    HeapFree( GetProcessHeap(), 0, face->StyleName );
    HeapFree( GetProcessHeap(), 0, face->FullName );
    HeapFree( GetProcessHeap(), 0, face->cached_enum_data );
    HeapFree( GetProcessHeap(), 0, face );
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
}

static inline int style_order(const Face *face)
{
    switch (face->ntmFlags & (NTM_REGULAR | NTM_BOLD | NTM_ITALIC))
    {
    case NTM_REGULAR:
        return 0;
    case NTM_BOLD:
        return 1;
    case NTM_ITALIC:
        return 2;
    case NTM_BOLD | NTM_ITALIC:
        return 3;
    default:
        WARN("Don't know how to order font %s %s with flags 0x%08x\n",
             debugstr_w(face->family->FamilyName),
             debugstr_w(face->StyleName),
             face->ntmFlags);
        return 9999;
    }
}

static BOOL insert_face_in_family_list( Face *face, Family *family )
{
    Face *cursor;

    LIST_FOR_EACH_ENTRY( cursor, &family->faces, Face, entry )
    {
        if (faces_equal( face, cursor ))
        {
            TRACE("Already loaded font %s %s original version is %lx, this version is %lx\n",
                  debugstr_w(family->FamilyName), debugstr_w(face->StyleName),
                  cursor->font_version, face->font_version);

1550 1551 1552 1553 1554 1555 1556
            if (face->file && face->dev == cursor->dev && face->ino == cursor->ino)
            {
                cursor->refcount++;
                TRACE("Font %s already in list, refcount now %d\n",
                      debugstr_w(face->file), cursor->refcount);
                return FALSE;
            }
1557 1558
            if (face->font_version <= cursor->font_version)
            {
1559
                TRACE("Original font %s is newer so skipping %s\n",
1560
                      debugstr_w(cursor->file), debugstr_w(face->file));
1561 1562 1563 1564
                return FALSE;
            }
            else
            {
1565
                TRACE("Replacing original %s with %s\n",
1566
                      debugstr_w(cursor->file), debugstr_w(face->file));
1567 1568
                list_add_before( &cursor->entry, &face->entry );
                face->family = family;
1569 1570 1571
                family->refcount++;
                face->refcount++;
                release_face( cursor );
1572 1573 1574
                return TRUE;
            }
        }
1575
        else
1576
            TRACE("Adding new %s\n", debugstr_w(face->file));
1577 1578 1579 1580 1581 1582

        if (style_order( face ) < style_order( cursor )) break;
    }

    list_add_before( &cursor->entry, &face->entry );
    face->family = family;
1583 1584
    family->refcount++;
    face->refcount++;
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
    return TRUE;
}

/****************************************************************
 * NB This function stores the ptrs to the strings to save copying.
 * Don't free them after calling.
 */
static Family *create_family( WCHAR *name, WCHAR *english_name )
{
    Family * const family = HeapAlloc( GetProcessHeap(), 0, sizeof(*family) );
1595
    family->refcount = 1;
1596 1597 1598 1599
    family->FamilyName = name;
    family->EnglishName = english_name;
    list_init( &family->faces );
    family->replacement = &family->faces;
1600
    list_add_tail( &font_list, &family->entry );
1601 1602 1603 1604

    return family;
}

1605 1606
static LONG reg_load_dword(HKEY hkey, const WCHAR *value, DWORD *data)
{
1607 1608 1609 1610 1611 1612 1613 1614 1615
    DWORD type, size = sizeof(DWORD);

    if (RegQueryValueExW(hkey, value, NULL, &type, (BYTE *)data, &size) ||
        type != REG_DWORD || size != sizeof(DWORD))
    {
        *data = 0;
        return ERROR_BAD_CONFIGURATION;
    }
    return ERROR_SUCCESS;
1616 1617
}

1618 1619 1620 1621 1622 1623 1624 1625 1626
static inline LONG reg_load_ftlong(HKEY hkey, const WCHAR *value, FT_Long *data)
{
    DWORD dw;
    LONG ret = reg_load_dword(hkey, value, &dw);
    *data = dw;
    return ret;
}

static inline LONG reg_load_ftshort(HKEY hkey, const WCHAR *value, FT_Short *data)
1627 1628 1629 1630 1631 1632 1633
{
    DWORD dw;
    LONG ret = reg_load_dword(hkey, value, &dw);
    *data = dw;
    return ret;
}

1634 1635 1636 1637 1638
static inline LONG reg_save_dword(HKEY hkey, const WCHAR *value, DWORD data)
{
    return RegSetValueExW(hkey, value, 0, REG_DWORD, (BYTE*)&data, sizeof(DWORD));
}

1639
static void load_face(HKEY hkey_face, WCHAR *face_name, Family *family, void *buffer, DWORD buffer_size)
1640
{
1641 1642
    DWORD needed, strike_index = 0;
    HKEY hkey_strike;
1643 1644 1645

    /* If we have a File Name key then this is a real font, not just the parent
       key of a bunch of non-scalable strikes */
1646
    needed = buffer_size;
1647
    if (RegQueryValueExW(hkey_face, face_file_name_value, NULL, NULL, buffer, &needed) == ERROR_SUCCESS)
1648 1649 1650 1651
    {
        Face *face;
        face = HeapAlloc(GetProcessHeap(), 0, sizeof(*face));
        face->cached_enum_data = NULL;
1652
        face->family = NULL;
1653

1654
        face->refcount = 1;
1655
        face->file = strdupW( buffer );
1656 1657
        face->StyleName = strdupW(face_name);

1658 1659 1660
        needed = buffer_size;
        if(RegQueryValueExW(hkey_face, face_full_name_value, NULL, NULL, buffer, &needed) == ERROR_SUCCESS)
            face->FullName = strdupW( buffer );
1661 1662 1663
        else
            face->FullName = NULL;

1664
        reg_load_ftlong(hkey_face, face_index_value, &face->face_index);
1665
        reg_load_dword(hkey_face, face_ntmflags_value, &face->ntmFlags);
1666 1667
        reg_load_ftlong(hkey_face, face_version_value, &face->font_version);
        reg_load_dword(hkey_face, face_flags_value, &face->flags);
1668 1669 1670 1671

        needed = sizeof(face->fs);
        RegQueryValueExW(hkey_face, face_font_sig_value, NULL, NULL, (BYTE*)&face->fs, &needed);

1672
        if(reg_load_ftshort(hkey_face, face_height_value, &face->size.height) != ERROR_SUCCESS)
1673 1674 1675 1676 1677 1678 1679
        {
            face->scalable = TRUE;
            memset(&face->size, 0, sizeof(face->size));
        }
        else
        {
            face->scalable = FALSE;
1680
            reg_load_ftshort(hkey_face, face_width_value, &face->size.width);
1681 1682 1683
            reg_load_ftlong(hkey_face, face_size_value, &face->size.size);
            reg_load_ftlong(hkey_face, face_x_ppem_value, &face->size.x_ppem);
            reg_load_ftlong(hkey_face, face_y_ppem_value, &face->size.y_ppem);
1684
            reg_load_ftshort(hkey_face, face_internal_leading_value, &face->size.internal_leading);
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695

            TRACE("Adding bitmap size h %d w %d size %ld x_ppem %ld y_ppem %ld\n",
                  face->size.height, face->size.width, face->size.size >> 6,
                  face->size.x_ppem >> 6, face->size.y_ppem >> 6);
        }

        TRACE("fsCsb = %08x %08x/%08x %08x %08x %08x\n",
              face->fs.fsCsb[0], face->fs.fsCsb[1],
              face->fs.fsUsb[0], face->fs.fsUsb[1],
              face->fs.fsUsb[2], face->fs.fsUsb[3]);

1696 1697
        if (insert_face_in_family_list(face, family))
            TRACE("Added font %s %s\n", debugstr_w(family->FamilyName), debugstr_w(face->StyleName));
1698

1699
        release_face( face );
1700 1701
    }

1702
    /* load bitmap strikes */
1703

1704 1705 1706 1707
    needed = buffer_size;
    while (!RegEnumKeyExW(hkey_face, strike_index++, buffer, &needed, NULL, NULL, NULL, NULL))
    {
        if (!RegOpenKeyExW(hkey_face, buffer, 0, KEY_ALL_ACCESS, &hkey_strike))
1708
        {
1709
            load_face(hkey_strike, face_name, family, buffer, buffer_size);
1710 1711
            RegCloseKey(hkey_strike);
        }
1712
        needed = buffer_size;
1713 1714 1715
    }
}

1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
/* move vertical fonts after their horizontal counterpart */
/* assumes that font_list is already sorted by family name */
static void reorder_vertical_fonts(void)
{
    Family *family, *next, *vert_family;
    struct list *ptr, *vptr;
    struct list vertical_families = LIST_INIT( vertical_families );

    LIST_FOR_EACH_ENTRY_SAFE( family, next, &font_list, Family, entry )
    {
        if (family->FamilyName[0] != '@') continue;
        list_remove( &family->entry );
        list_add_tail( &vertical_families, &family->entry );
    }

    ptr = list_head( &font_list );
    vptr = list_head( &vertical_families );
    while (ptr && vptr)
    {
        family = LIST_ENTRY( ptr, Family, entry );
        vert_family = LIST_ENTRY( vptr, Family, entry );
        if (strcmpiW( family->FamilyName, vert_family->FamilyName + 1 ) > 0)
        {
            list_remove( vptr );
            list_add_before( ptr, vptr );
            vptr = list_head( &vertical_families );
        }
        else ptr = list_next( &font_list, ptr );
    }
    list_move_tail( &font_list, &vertical_families );
}

1748 1749
static void load_font_list_from_cache(HKEY hkey_font_cache)
{
1750
    DWORD size, family_index = 0;
1751 1752
    Family *family;
    HKEY hkey_family;
1753
    WCHAR buffer[4096];
1754

1755 1756
    size = sizeof(buffer);
    while (!RegEnumKeyExW(hkey_font_cache, family_index++, buffer, &size, NULL, NULL, NULL, NULL))
1757 1758
    {
        WCHAR *english_family = NULL;
1759
        WCHAR *family_name = strdupW( buffer );
1760 1761 1762 1763
        DWORD face_index = 0;

        RegOpenKeyExW(hkey_font_cache, family_name, 0, KEY_ALL_ACCESS, &hkey_family);
        TRACE("opened family key %s\n", debugstr_w(family_name));
1764 1765 1766
        size = sizeof(buffer);
        if (!RegQueryValueExW(hkey_family, english_name_value, NULL, NULL, (BYTE *)buffer, &size))
            english_family = strdupW( buffer );
1767

1768
        family = create_family(family_name, english_family);
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779

        if(english_family)
        {
            FontSubst *subst = HeapAlloc(GetProcessHeap(), 0, sizeof(*subst));
            subst->from.name = strdupW(english_family);
            subst->from.charset = -1;
            subst->to.name = strdupW(family_name);
            subst->to.charset = -1;
            add_font_subst(&font_subst_list, subst, 0);
        }

1780 1781
        size = sizeof(buffer);
        while (!RegEnumKeyExW(hkey_family, face_index++, buffer, &size, NULL, NULL, NULL, NULL))
1782
        {
1783
            WCHAR *face_name = strdupW( buffer );
1784 1785
            HKEY hkey_face;

1786 1787 1788 1789 1790 1791 1792
            if (!RegOpenKeyExW(hkey_family, face_name, 0, KEY_ALL_ACCESS, &hkey_face))
            {
                load_face(hkey_face, face_name, family, buffer, sizeof(buffer));
                RegCloseKey(hkey_face);
            }
            HeapFree( GetProcessHeap(), 0, face_name );
            size = sizeof(buffer);
1793 1794
        }
        RegCloseKey(hkey_family);
1795
        release_family( family );
1796
        size = sizeof(buffer);
1797
    }
1798 1799

    reorder_vertical_fonts();
1800 1801
}

1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
static LONG create_font_cache_key(HKEY *hkey, DWORD *disposition)
{
    LONG ret;
    HKEY hkey_wine_fonts;

    /* We don't want to create the fonts key as volatile, so open this first */
    ret = RegCreateKeyExW(HKEY_CURRENT_USER, wine_fonts_key, 0, NULL, 0,
                          KEY_ALL_ACCESS, NULL, &hkey_wine_fonts, NULL);
    if(ret != ERROR_SUCCESS)
    {
        WARN("Can't create %s\n", debugstr_w(wine_fonts_key));
        return ret;
    }

    ret = RegCreateKeyExW(hkey_wine_fonts, wine_fonts_cache_key, 0, NULL, REG_OPTION_VOLATILE,
                          KEY_ALL_ACCESS, NULL, hkey, disposition);
    RegCloseKey(hkey_wine_fonts);
    return ret;
}

static void add_face_to_cache(Face *face)
{
1824
    HKEY hkey_family, hkey_face;
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
    WCHAR *face_key_name;

    RegCreateKeyExW(hkey_font_cache, face->family->FamilyName, 0,
                    NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey_family, NULL);
    if(face->family->EnglishName)
        RegSetValueExW(hkey_family, english_name_value, 0, REG_SZ, (BYTE*)face->family->EnglishName,
                       (strlenW(face->family->EnglishName) + 1) * sizeof(WCHAR));

    if(face->scalable)
        face_key_name = face->StyleName;
    else
    {
        static const WCHAR fmtW[] = {'%','s','\\','%','d',0};
        face_key_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(face->StyleName) + 10) * sizeof(WCHAR));
        sprintfW(face_key_name, fmtW, face->StyleName, face->size.y_ppem);
    }
    RegCreateKeyExW(hkey_family, face_key_name, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL,
                    &hkey_face, NULL);
    if(!face->scalable)
        HeapFree(GetProcessHeap(), 0, face_key_name);

1846 1847
    RegSetValueExW(hkey_face, face_file_name_value, 0, REG_SZ, (BYTE *)face->file,
                   (strlenW(face->file) + 1) * sizeof(WCHAR));
1848 1849 1850 1851 1852
    if (face->FullName)
        RegSetValueExW(hkey_face, face_full_name_value, 0, REG_SZ, (BYTE*)face->FullName,
                       (strlenW(face->FullName) + 1) * sizeof(WCHAR));

    reg_save_dword(hkey_face, face_index_value, face->face_index);
1853
    reg_save_dword(hkey_face, face_ntmflags_value, face->ntmFlags);
1854
    reg_save_dword(hkey_face, face_version_value, face->font_version);
1855
    if (face->flags) reg_save_dword(hkey_face, face_flags_value, face->flags);
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870

    RegSetValueExW(hkey_face, face_font_sig_value, 0, REG_BINARY, (BYTE*)&face->fs, sizeof(face->fs));

    if(!face->scalable)
    {
        reg_save_dword(hkey_face, face_height_value, face->size.height);
        reg_save_dword(hkey_face, face_width_value, face->size.width);
        reg_save_dword(hkey_face, face_size_value, face->size.size);
        reg_save_dword(hkey_face, face_x_ppem_value, face->size.x_ppem);
        reg_save_dword(hkey_face, face_y_ppem_value, face->size.y_ppem);
        reg_save_dword(hkey_face, face_internal_leading_value, face->size.internal_leading);
    }
    RegCloseKey(hkey_face);
    RegCloseKey(hkey_family);
}
1871

1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
static void remove_face_from_cache( Face *face )
{
    HKEY hkey_family;

    RegOpenKeyExW( hkey_font_cache, face->family->FamilyName, 0, KEY_ALL_ACCESS, &hkey_family );

    if (face->scalable)
    {
        RegDeleteKeyW( hkey_family, face->StyleName );
    }
    else
    {
        static const WCHAR fmtW[] = {'%','s','\\','%','d',0};
        WCHAR *face_key_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(face->StyleName) + 10) * sizeof(WCHAR));
        sprintfW(face_key_name, fmtW, face->StyleName, face->size.y_ppem);
        RegDeleteKeyW( hkey_family, face_key_name );
        HeapFree(GetProcessHeap(), 0, face_key_name);
    }
    RegCloseKey(hkey_family);
}

1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
static WCHAR *prepend_at(WCHAR *family)
{
    WCHAR *str;

    if (!family)
        return NULL;

    str = HeapAlloc(GetProcessHeap(), 0, sizeof (WCHAR) * (strlenW(family) + 2));
    str[0] = '@';
    strcpyW(str + 1, family);
    HeapFree(GetProcessHeap(), 0, family);
    return str;
}

1907 1908
static void get_family_names( FT_Face ft_face, WCHAR **name, WCHAR **english, BOOL vertical )
{
1909
    *english = get_face_name( ft_face, TT_NAME_ID_FONT_FAMILY, MAKELANGID(LANG_ENGLISH,SUBLANG_DEFAULT) );
1910 1911
    if (!*english) *english = towstr( CP_ACP, ft_face->family_name );

1912
    *name = get_face_name( ft_face, TT_NAME_ID_FONT_FAMILY, GetSystemDefaultLCID() );
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
    if (!*name)
    {
        *name = *english;
        *english = NULL;
    }
    else if (!strcmpiW( *name, *english ))
    {
        HeapFree( GetProcessHeap(), 0, *english );
        *english = NULL;
    }

    if (vertical)
    {
        *name = prepend_at( *name );
        *english = prepend_at( *english );
    }
}

1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
static Family *get_family( FT_Face ft_face, BOOL vertical )
{
    Family *family;
    WCHAR *name, *english_name;

    get_family_names( ft_face, &name, &english_name, vertical );

    family = find_family_from_name( name );

    if (!family)
    {
1942
        family = create_family( name, english_name );
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
        if (english_name)
        {
            FontSubst *subst = HeapAlloc( GetProcessHeap(), 0, sizeof(*subst) );
            subst->from.name = strdupW( english_name );
            subst->from.charset = -1;
            subst->to.name = strdupW( name );
            subst->to.charset = -1;
            add_font_subst( &font_subst_list, subst, 0 );
        }
    }
1953 1954 1955 1956
    else
    {
        HeapFree( GetProcessHeap(), 0, name );
        HeapFree( GetProcessHeap(), 0, english_name );
1957
        family->refcount++;
1958
    }
1959 1960 1961 1962

    return family;
}

1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
static inline FT_Fixed get_font_version( FT_Face ft_face )
{
    FT_Fixed version = 0;
    TT_Header *header;

    header = pFT_Get_Sfnt_Table( ft_face, ft_sfnt_head );
    if (header) version = header->Font_Revision;

    return version;
}
1973

1974 1975 1976 1977
static inline DWORD get_ntm_flags( FT_Face ft_face )
{
    DWORD flags = 0;
    FT_ULong table_size = 0;
1978
    FT_WinFNT_HeaderRec winfnt_header;
1979 1980 1981

    if (ft_face->style_flags & FT_STYLE_FLAG_ITALIC) flags |= NTM_ITALIC;
    if (ft_face->style_flags & FT_STYLE_FLAG_BOLD)   flags |= NTM_BOLD;
1982 1983 1984 1985 1986 1987 1988

    /* fixup the flag for our fake-bold implementation. */
    if (!FT_IS_SCALABLE( ft_face ) &&
        !pFT_Get_WinFNT_Header( ft_face, &winfnt_header ) &&
        winfnt_header.weight > FW_NORMAL )
        flags |= NTM_BOLD;

1989 1990 1991 1992 1993 1994 1995 1996
    if (flags == 0) flags = NTM_REGULAR;

    if (!pFT_Load_Sfnt_Table( ft_face, FT_MAKE_TAG( 'C','F','F',' ' ), 0, NULL, &table_size ))
        flags |= NTM_PS_OPENTYPE;

    return flags;
}

1997
static inline void get_bitmap_size( FT_Face ft_face, Bitmap_Size *face_size )
1998
{
1999
    My_FT_Bitmap_Size *size;
2000 2001
    FT_WinFNT_HeaderRec winfnt_header;

2002 2003 2004 2005 2006 2007 2008 2009 2010
    size = (My_FT_Bitmap_Size *)ft_face->available_sizes;
    TRACE("Adding bitmap size h %d w %d size %ld x_ppem %ld y_ppem %ld\n",
          size->height, size->width, size->size >> 6,
          size->x_ppem >> 6, size->y_ppem >> 6);
    face_size->height = size->height;
    face_size->width = size->width;
    face_size->size = size->size;
    face_size->x_ppem = size->x_ppem;
    face_size->y_ppem = size->y_ppem;
2011

2012
    if (!pFT_Get_WinFNT_Header( ft_face, &winfnt_header )) {
2013
        face_size->internal_leading = winfnt_header.internal_leading;
2014 2015 2016 2017 2018
        if (winfnt_header.external_leading > 0 &&
            (face_size->height ==
             winfnt_header.pixel_height + winfnt_header.external_leading))
            face_size->height = winfnt_header.pixel_height;
    }
2019 2020
}

2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
static inline void get_fontsig( FT_Face ft_face, FONTSIGNATURE *fs )
{
    TT_OS2 *os2;
    CHARSETINFO csi;
    FT_WinFNT_HeaderRec winfnt_header;
    int i;

    memset( fs, 0, sizeof(*fs) );

    os2 = pFT_Get_Sfnt_Table( ft_face, ft_sfnt_os2 );
    if (os2)
    {
        fs->fsUsb[0] = os2->ulUnicodeRange1;
        fs->fsUsb[1] = os2->ulUnicodeRange2;
        fs->fsUsb[2] = os2->ulUnicodeRange3;
        fs->fsUsb[3] = os2->ulUnicodeRange4;

        if (os2->version == 0)
        {
2040
            if (os2->usFirstCharIndex >= 0xf000 && os2->usFirstCharIndex < 0xf100)
2041
                fs->fsCsb[0] = FS_SYMBOL;
2042 2043
            else
                fs->fsCsb[0] = FS_LATIN1;
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
        }
        else
        {
            fs->fsCsb[0] = os2->ulCodePageRange1;
            fs->fsCsb[1] = os2->ulCodePageRange2;
        }
    }
    else
    {
        if (!pFT_Get_WinFNT_Header( ft_face, &winfnt_header ))
        {
            TRACE("pix_h %d charset %d dpi %dx%d pt %d\n", winfnt_header.pixel_height, winfnt_header.charset,
                  winfnt_header.vertical_resolution,winfnt_header.horizontal_resolution, winfnt_header.nominal_point_size);
            if (TranslateCharsetInfo( (DWORD*)(UINT_PTR)winfnt_header.charset, &csi, TCI_SRCCHARSET ))
                *fs = csi.fs;
        }
    }

    if (fs->fsCsb[0] == 0)
    {
        /* let's see if we can find any interesting cmaps */
        for (i = 0; i < ft_face->num_charmaps; i++)
        {
            switch (ft_face->charmaps[i]->encoding)
            {
            case FT_ENCODING_UNICODE:
            case FT_ENCODING_APPLE_ROMAN:
                fs->fsCsb[0] |= FS_LATIN1;
                break;
            case FT_ENCODING_MS_SYMBOL:
                fs->fsCsb[0] |= FS_SYMBOL;
                break;
            default:
                break;
            }
        }
    }
}

2083
static Face *create_face( FT_Face ft_face, FT_Long face_index, const char *file, void *font_data_ptr, DWORD font_data_size,
2084
                          DWORD flags )
2085
{
2086
    struct stat st;
2087
    Face *face = HeapAlloc( GetProcessHeap(), 0, sizeof(*face) );
2088

2089
    face->refcount = 1;
2090
    face->StyleName = get_face_name( ft_face, TT_NAME_ID_FONT_SUBFAMILY, GetSystemDefaultLangID() );
2091
    if (!face->StyleName) face->StyleName = towstr( CP_ACP, ft_face->style_name );
2092

2093
    face->FullName = get_face_name( ft_face, TT_NAME_ID_FULL_NAME, GetSystemDefaultLangID() );
2094
    if (flags & ADDFONT_VERTICAL_FONT)
2095 2096
        face->FullName = prepend_at( face->FullName );

2097 2098
    face->dev = 0;
    face->ino = 0;
2099 2100
    if (file)
    {
2101
        face->file = towstr( CP_UNIXCP, file );
2102 2103
        face->font_data_ptr = NULL;
        face->font_data_size = 0;
2104 2105 2106 2107 2108
        if (!stat( file, &st ))
        {
            face->dev = st.st_dev;
            face->ino = st.st_ino;
        }
2109 2110 2111 2112 2113 2114 2115
    }
    else
    {
        face->file = NULL;
        face->font_data_ptr = font_data_ptr;
        face->font_data_size = font_data_size;
    }
2116

2117
    face->face_index = face_index;
2118
    get_fontsig( ft_face, &face->fs );
2119
    face->ntmFlags = get_ntm_flags( ft_face );
2120
    face->font_version = get_font_version( ft_face );
2121

2122
    if (FT_IS_SCALABLE( ft_face ))
2123
    {
2124
        memset( &face->size, 0, sizeof(face->size) );
2125 2126 2127 2128
        face->scalable = TRUE;
    }
    else
    {
2129
        get_bitmap_size( ft_face, &face->size );
2130 2131
        face->scalable = FALSE;
    }
2132

2133 2134
    if (!HIWORD( flags )) flags |= ADDFONT_AA_FLAGS( default_aa_flags );
    face->flags  = flags;
2135 2136 2137
    face->family = NULL;
    face->cached_enum_data = NULL;

2138 2139 2140 2141
    TRACE("fsCsb = %08x %08x/%08x %08x %08x %08x\n",
          face->fs.fsCsb[0], face->fs.fsCsb[1],
          face->fs.fsUsb[0], face->fs.fsUsb[1],
          face->fs.fsUsb[2], face->fs.fsUsb[3]);
2142

2143 2144 2145 2146
    return face;
}

static void AddFaceToList(FT_Face ft_face, const char *file, void *font_data_ptr, DWORD font_data_size,
2147
                          FT_Long face_index, DWORD flags )
2148 2149 2150 2151
{
    Face *face;
    Family *family;

2152 2153
    face = create_face( ft_face, face_index, file, font_data_ptr, font_data_size, flags );
    family = get_family( ft_face, flags & ADDFONT_VERTICAL_FONT );
2154

2155
    if (insert_face_in_family_list( face, family ))
2156
    {
2157 2158
        if (flags & ADDFONT_ADD_TO_CACHE)
            add_face_to_cache( face );
2159

2160 2161 2162 2163 2164
        TRACE("Added font %s %s\n", debugstr_w(family->FamilyName),
              debugstr_w(face->StyleName));
    }
    release_face( face );
    release_family( family );
2165 2166
}

2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
static FT_Face new_ft_face( const char *file, void *font_data_ptr, DWORD font_data_size,
                            FT_Long face_index, BOOL allow_bitmap )
{
    FT_Error err;
    TT_OS2 *pOS2;
    FT_Face ft_face;

    if (file)
    {
        TRACE("Loading font file %s index %ld\n", debugstr_a(file), face_index);
        err = pFT_New_Face(library, file, face_index, &ft_face);
    }
    else
    {
        TRACE("Loading font from ptr %p size %d, index %ld\n", font_data_ptr, font_data_size, face_index);
        err = pFT_New_Memory_Face(library, font_data_ptr, font_data_size, face_index, &ft_face);
    }

    if (err != 0)
    {
        WARN("Unable to load font %s/%p err = %x\n", debugstr_a(file), font_data_ptr, err);
        return NULL;
    }

    /* There are too many bugs in FreeType < 2.1.9 for bitmap font support */
2192
    if (!FT_IS_SCALABLE( ft_face ) && FT_SimpleVersion < FT_VERSION_VALUE(2, 1, 9))
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
    {
        WARN("FreeType version < 2.1.9, skipping bitmap font %s/%p\n", debugstr_a(file), font_data_ptr);
        goto fail;
    }

    if (!FT_IS_SFNT( ft_face ))
    {
        if (FT_IS_SCALABLE( ft_face ) || !allow_bitmap )
        {
            WARN("Ignoring font %s/%p\n", debugstr_a(file), font_data_ptr);
            goto fail;
        }
    }
    else
    {
        if (!(pOS2 = pFT_Get_Sfnt_Table( ft_face, ft_sfnt_os2 )) ||
            !pFT_Get_Sfnt_Table( ft_face, ft_sfnt_hhea ) ||
            !pFT_Get_Sfnt_Table( ft_face, ft_sfnt_head ))
        {
            TRACE("Font %s/%p lacks either an OS2, HHEA or HEAD table.\n"
                  "Skipping this font.\n", debugstr_a(file), font_data_ptr);
            goto fail;
        }

        /* Wine uses ttfs as an intermediate step in building its bitmap fonts;
           we don't want to load these. */
        if (!memcmp( pOS2->achVendID, "Wine", sizeof(pOS2->achVendID) ))
        {
            FT_ULong len = 0;

            if (!pFT_Load_Sfnt_Table( ft_face, FT_MAKE_TAG('E','B','S','C'), 0, NULL, &len ))
            {
                TRACE("Skipping Wine bitmap-only TrueType font %s\n", debugstr_a(file));
                goto fail;
            }
        }
    }

    if (!ft_face->family_name || !ft_face->style_name)
    {
        TRACE("Font %s/%p lacks either a family or style name\n", debugstr_a(file), font_data_ptr);
        goto fail;
    }

    return ft_face;
fail:
    pFT_Done_Face( ft_face );
    return NULL;
}

2243
static INT AddFontToList(const char *file, void *font_data_ptr, DWORD font_data_size, DWORD flags)
2244 2245
{
    FT_Face ft_face;
2246
    FT_Long face_index = 0, num_faces;
2247
    INT ret = 0;
2248

2249 2250 2251
    /* we always load external fonts from files - otherwise we would get a crash in update_reg_entries */
    assert(file || !(flags & ADDFONT_EXTERNAL_FONT));

2252
#ifdef HAVE_CARBON_CARBON_H
2253
    if(file)
2254 2255 2256 2257 2258 2259 2260 2261 2262
    {
        char **mac_list = expand_mac_font(file);
        if(mac_list)
        {
            BOOL had_one = FALSE;
            char **cursor;
            for(cursor = mac_list; *cursor; cursor++)
            {
                had_one = TRUE;
2263
                AddFontToList(*cursor, NULL, 0, flags);
2264 2265 2266 2267
                HeapFree(GetProcessHeap(), 0, *cursor);
            }
            HeapFree(GetProcessHeap(), 0, mac_list);
            if(had_one)
2268
                return 1;
2269 2270 2271 2272
        }
    }
#endif /* HAVE_CARBON_CARBON_H */

2273
    do {
2274 2275 2276
        const DWORD FS_DBCS_MASK = FS_JISJAPAN|FS_CHINESESIMP|FS_WANSUNG|FS_CHINESETRAD|FS_JOHAB;
        FONTSIGNATURE fs;

2277
        ft_face = new_ft_face( file, font_data_ptr, font_data_size, face_index, flags & ADDFONT_ALLOW_BITMAP );
2278
        if (!ft_face) return 0;
2279

2280 2281 2282 2283 2284 2285 2286
        if(ft_face->family_name[0] == '.') /* Ignore fonts with names beginning with a dot */
        {
            TRACE("Ignoring %s since its family name begins with a dot\n", debugstr_a(file));
            pFT_Done_Face(ft_face);
            return 0;
        }

2287
        AddFaceToList(ft_face, file, font_data_ptr, font_data_size, face_index, flags);
2288 2289
        ++ret;

2290 2291
        get_fontsig(ft_face, &fs);
        if (fs.fsCsb[0] & FS_DBCS_MASK)
2292
        {
2293 2294
            AddFaceToList(ft_face, file, font_data_ptr, font_data_size, face_index,
                          flags | ADDFONT_VERTICAL_FONT);
2295 2296
            ++ret;
        }
2297

2298 2299 2300
	num_faces = ft_face->num_faces;
	pFT_Done_Face(ft_face);
    } while(num_faces > ++face_index);
2301
    return ret;
2302 2303
}

2304 2305 2306 2307
static int remove_font_resource( const char *file, DWORD flags )
{
    Family *family, *family_next;
    Face *face, *face_next;
2308
    struct stat st;
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
    int count = 0;

    if (stat( file, &st ) == -1) return 0;
    LIST_FOR_EACH_ENTRY_SAFE( family, family_next, &font_list, Family, entry )
    {
        family->refcount++;
        LIST_FOR_EACH_ENTRY_SAFE( face, face_next, &family->faces, Face, entry )
        {
            if (!face->file) continue;
            if (LOWORD(face->flags) != LOWORD(flags)) continue;
2319
            if (st.st_dev == face->dev && st.st_ino == face->ino)
2320
            {
2321
                TRACE( "removing matching face %s refcount %d\n", debugstr_w(face->file), face->refcount );
2322 2323 2324 2325 2326 2327 2328 2329 2330
                release_face( face );
                count++;
            }
	}
        release_family( family );
    }
    return count;
}

2331 2332 2333 2334 2335
static void DumpFontList(void)
{
    Family *family;
    Face *face;

2336
    LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
2337
        TRACE("Family: %s\n", debugstr_w(family->FamilyName));
2338
        LIST_FOR_EACH_ENTRY( face, &family->faces, Face, entry ) {
2339
            TRACE("\t%s\t%08x", debugstr_w(face->StyleName), face->fs.fsCsb[0]);
2340
            if(!face->scalable)
2341
                TRACE(" %d", face->size.height);
2342
            TRACE("\n");
2343 2344 2345 2346
	}
    }
}

2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
static BOOL map_font_family(const WCHAR *orig, const WCHAR *repl)
{
    Family *family = find_family_from_any_name(repl);
    if (family != NULL)
    {
        Family *new_family = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_family));
        if (new_family != NULL)
        {
            TRACE("mapping %s to %s\n", debugstr_w(repl), debugstr_w(orig));
            new_family->FamilyName = strdupW(orig);
            new_family->EnglishName = NULL;
            list_init(&new_family->faces);
            new_family->replacement = &family->faces;
            list_add_tail(&font_list, &new_family->entry);
            return TRUE;
        }
    }
    TRACE("%s is not available. Skip this replacement.\n", debugstr_w(repl));
    return FALSE;
}

2368 2369 2370 2371
/***********************************************************
 * The replacement list is a way to map an entire font
 * family onto another family.  For example adding
 *
2372
 * [HKCU\Software\Wine\Fonts\Replacements]
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
 * "Wingdings"="Winedings"
 *
 * would enumerate the Winedings font both as Winedings and
 * Wingdings.  However if a real Wingdings font is present the
 * replacement does not take place.
 * 
 */
static void LoadReplaceList(void)
{
    HKEY hkey;
    DWORD valuelen, datalen, i = 0, type, dlen, vlen;
2384
    LPWSTR value;
2385 2386
    LPVOID data;

2387 2388 2389
    /* @@ Wine registry key: HKCU\Software\Wine\Fonts\Replacements */
    if(RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Wine\\Fonts\\Replacements", &hkey) == ERROR_SUCCESS)
    {
2390
        RegQueryInfoKeyW(hkey, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2391 2392 2393
			 &valuelen, &datalen, NULL, NULL);

	valuelen++; /* returned value doesn't include room for '\0' */
2394
	value = HeapAlloc(GetProcessHeap(), 0, valuelen * sizeof(WCHAR));
2395 2396 2397 2398
	data = HeapAlloc(GetProcessHeap(), 0, datalen);

	dlen = datalen;
	vlen = valuelen;
2399 2400
        while(RegEnumValueW(hkey, i++, value, &vlen, NULL, &type, data, &dlen) == ERROR_SUCCESS)
        {
2401
            /* "NewName"="Oldname" */
2402
            if(!find_family_from_any_name(value))
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413
            {
                if (type == REG_MULTI_SZ)
                {
                    WCHAR *replace = data;
                    while(*replace)
                    {
                        if (map_font_family(value, replace))
                            break;
                        replace += strlenW(replace) + 1;
                    }
                }
2414
                else if (type == REG_SZ)
2415 2416
                    map_font_family(value, data);
            }
2417 2418
            else
	        TRACE("%s is available. Skip this replacement.\n", debugstr_w(value));
2419

2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
	    /* reset dlen and vlen */
	    dlen = datalen;
	    vlen = valuelen;
	}
	HeapFree(GetProcessHeap(), 0, data);
	HeapFree(GetProcessHeap(), 0, value);
	RegCloseKey(hkey);
    }
}

2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
static const WCHAR *font_links_list[] =
{
    Lucida_Sans_Unicode,
    Microsoft_Sans_Serif,
    Tahoma
};

static const struct font_links_defaults_list
{
    /* Keyed off substitution for "MS Shell Dlg" */
    const WCHAR *shelldlg;
    /* Maximum of four substitutes, plus terminating NULL pointer */
    const WCHAR *substitutes[5];
} font_links_defaults_list[] =
{
    /* Non East-Asian */
    { Tahoma, /* FIXME unverified ordering */
      { MS_UI_Gothic, SimSun, Gulim, PMingLiU, NULL }
    },
    /* Below lists are courtesy of
     * http://blogs.msdn.com/michkap/archive/2005/06/18/430507.aspx
     */
    /* Japanese */
    { MS_UI_Gothic,
      { MS_UI_Gothic, PMingLiU, SimSun, Gulim, NULL }
    },
    /* Chinese Simplified */
    { SimSun,
      { SimSun, PMingLiU, MS_UI_Gothic, Batang, NULL }
    },
    /* Korean */
    { Gulim,
      { Gulim, PMingLiU, MS_UI_Gothic, SimSun, NULL }
    },
    /* Chinese Traditional */
    { PMingLiU,
      { PMingLiU, SimSun, MS_UI_Gothic, Batang, NULL }
    }
};


2471 2472 2473 2474 2475 2476
static SYSTEM_LINKS *find_font_link(const WCHAR *name)
{
    SYSTEM_LINKS *font_link;

    LIST_FOR_EACH_ENTRY(font_link, &system_links, SYSTEM_LINKS, entry)
    {
2477
        if(!strncmpiW(font_link->font_name, name, LF_FACESIZE - 1))
2478 2479 2480 2481 2482 2483
            return font_link;
    }

    return NULL;
}

2484 2485 2486 2487 2488 2489 2490
static void populate_system_links(const WCHAR *name, const WCHAR *const *values)
{
    const WCHAR *value;
    int i;
    FontSubst *psub;
    Family *family;
    Face *face;
2491
    const WCHAR *file;
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504

    if (values)
    {
        SYSTEM_LINKS *font_link;

        psub = get_font_subst(&font_subst_list, name, -1);
        /* Don't store fonts that are only substitutes for other fonts */
        if(psub)
        {
            TRACE("%s: Internal SystemLink entry for substituted font, ignoring\n", debugstr_w(name));
            return;
        }

2505 2506
        font_link = find_font_link(name);
        if (font_link == NULL)
2507 2508 2509 2510
        {
            font_link = HeapAlloc(GetProcessHeap(), 0, sizeof(*font_link));
            font_link->font_name = strdupW(name);
            list_init(&font_link->links);
2511
            list_add_tail(&system_links, &font_link->entry);
2512 2513
        }

2514
        memset(&font_link->fs, 0, sizeof font_link->fs);
2515 2516
        for (i = 0; values[i] != NULL; i++)
        {
2517
            const struct list *face_list;
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
            CHILD_FONT *child_font;

            value = values[i];
            if (!strcmpiW(name,value))
                continue;
            psub = get_font_subst(&font_subst_list, value, -1);
            if(psub)
                value = psub->to.name;
            family = find_family_from_name(value);
            if (!family)
                continue;
            file = NULL;
            /* Use first extant filename for this Family */
2531 2532
            face_list = get_face_list_from_family(family);
            LIST_FOR_EACH_ENTRY(face, face_list, Face, entry)
2533 2534 2535
            {
                if (!face->file)
                    continue;
2536
                file = strrchrW(face->file, '/');
2537 2538 2539 2540 2541 2542 2543 2544
                if (!file)
                    file = face->file;
                else
                    file++;
                break;
            }
            if (!file)
                continue;
2545
            face = find_face_from_filename(file, value);
2546 2547
            if(!face)
            {
2548
                TRACE("Unable to find file %s face name %s\n", debugstr_w(file), debugstr_w(value));
2549 2550 2551 2552 2553 2554
                continue;
            }

            child_font = HeapAlloc(GetProcessHeap(), 0, sizeof(*child_font));
            child_font->face = face;
            child_font->font = NULL;
2555 2556
            font_link->fs.fsCsb[0] |= face->fs.fsCsb[0];
            font_link->fs.fsCsb[1] |= face->fs.fsCsb[1];
2557 2558
            TRACE("Adding file %s index %ld\n", debugstr_w(child_font->face->file),
                  child_font->face->face_index);
2559 2560
            list_add_tail(&font_link->links, &child_font->entry);

2561
            TRACE("added internal SystemLink for %s to %s in %s\n", debugstr_w(name), debugstr_w(value),debugstr_w(file));
2562 2563 2564 2565 2566
        }
    }
}


2567 2568 2569
/*************************************************************
 * init_system_links
 */
2570
static void init_system_links(void)
2571 2572 2573 2574 2575 2576 2577
{
    HKEY hkey;
    DWORD type, max_val, max_data, val_len, data_len, index;
    WCHAR *value, *data;
    WCHAR *entry, *next;
    SYSTEM_LINKS *font_link, *system_font_link;
    CHILD_FONT *child_font;
2578
    static const WCHAR tahoma_ttf[] = {'t','a','h','o','m','a','.','t','t','f',0};
2579
    static const WCHAR System[] = {'S','y','s','t','e','m',0};
2580
    static const WCHAR MS_Shell_Dlg[] = {'M','S',' ','S','h','e','l','l',' ','D','l','g',0};
2581
    Face *face;
2582
    FontSubst *psub;
2583
    UINT i, j;
2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594

    if(RegOpenKeyW(HKEY_LOCAL_MACHINE, system_link, &hkey) == ERROR_SUCCESS)
    {
        RegQueryInfoKeyW(hkey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &max_val, &max_data, NULL, NULL);
        value = HeapAlloc(GetProcessHeap(), 0, (max_val + 1) * sizeof(WCHAR));
        data = HeapAlloc(GetProcessHeap(), 0, max_data);
        val_len = max_val + 1;
        data_len = max_data;
        index = 0;
        while(RegEnumValueW(hkey, index++, value, &val_len, NULL, &type, (LPBYTE)data, &data_len) == ERROR_SUCCESS)
        {
2595
            psub = get_font_subst(&font_subst_list, value, -1);
2596 2597 2598 2599
            /* Don't store fonts that are only substitutes for other fonts */
            if(psub)
            {
                TRACE("%s: SystemLink entry for substituted font, ignoring\n", debugstr_w(value));
2600
                goto next;
2601 2602 2603
            }
            font_link = HeapAlloc(GetProcessHeap(), 0, sizeof(*font_link));
            font_link->font_name = strdupW(value);
2604
            memset(&font_link->fs, 0, sizeof font_link->fs);
2605 2606 2607 2608 2609 2610
            list_init(&font_link->links);
            for(entry = data; (char*)entry < (char*)data + data_len && *entry != 0; entry = next)
            {
                WCHAR *face_name;
                CHILD_FONT *child_font;

2611
                TRACE("%s: %s\n", debugstr_w(value), debugstr_w(entry));
2612 2613 2614 2615

                next = entry + strlenW(entry) + 1;
                
                face_name = strchrW(entry, ',');
2616
                if(face_name)
2617 2618 2619 2620
                {
                    *face_name++ = 0;
                    while(isspaceW(*face_name))
                        face_name++;
2621 2622 2623 2624

                    psub = get_font_subst(&font_subst_list, face_name, -1);
                    if(psub)
                        face_name = psub->to.name;
2625
                }
2626
                face = find_face_from_filename(entry, face_name);
2627 2628
                if(!face)
                {
2629
                    TRACE("Unable to find file %s face name %s\n", debugstr_w(entry), debugstr_w(face_name));
2630 2631 2632 2633
                    continue;
                }

                child_font = HeapAlloc(GetProcessHeap(), 0, sizeof(*child_font));
2634
                child_font->face = face;
2635
                child_font->font = NULL;
2636 2637
                font_link->fs.fsCsb[0] |= face->fs.fsCsb[0];
                font_link->fs.fsCsb[1] |= face->fs.fsCsb[1];
2638 2639
                TRACE("Adding file %s index %ld\n",
                      debugstr_w(child_font->face->file), child_font->face->face_index);
2640 2641 2642
                list_add_tail(&font_link->links, &child_font->entry);
            }
            list_add_tail(&system_links, &font_link->entry);
2643
        next:
2644 2645 2646 2647 2648 2649 2650 2651 2652
            val_len = max_val + 1;
            data_len = max_data;
        }

        HeapFree(GetProcessHeap(), 0, value);
        HeapFree(GetProcessHeap(), 0, data);
        RegCloseKey(hkey);
    }

2653

2654 2655 2656 2657 2658
    psub = get_font_subst(&font_subst_list, MS_Shell_Dlg, -1);
    if (!psub) {
        WARN("could not find FontSubstitute for MS Shell Dlg\n");
        goto skip_internal;
    }
2659

2660
    for (i = 0; i < ARRAY_SIZE(font_links_defaults_list); i++)
2661 2662 2663
    {
        const FontSubst *psub2;
        psub2 = get_font_subst(&font_subst_list, font_links_defaults_list[i].shelldlg, -1);
2664

2665 2666
        if ((!strcmpiW(font_links_defaults_list[i].shelldlg, psub->to.name) || (psub2 && !strcmpiW(psub2->to.name,psub->to.name))))
        {
2667
            for (j = 0; j < ARRAY_SIZE(font_links_list); j++)
2668
                populate_system_links(font_links_list[j], font_links_defaults_list[i].substitutes);
2669

2670 2671 2672 2673 2674 2675
            if (!strcmpiW(psub->to.name, font_links_defaults_list[i].substitutes[0]))
                populate_system_links(psub->to.name, font_links_defaults_list[i].substitutes);
        }
        else if (strcmpiW(psub->to.name, font_links_defaults_list[i].substitutes[0]))
        {
            populate_system_links(font_links_defaults_list[i].substitutes[0], NULL);
2676 2677 2678
        }
    }

2679 2680
skip_internal:

2681 2682
    /* Explicitly add an entry for the system font, this links to Tahoma and any links
       that Tahoma has */
2683

2684 2685
    system_font_link = HeapAlloc(GetProcessHeap(), 0, sizeof(*system_font_link));
    system_font_link->font_name = strdupW(System);
2686
    memset(&system_font_link->fs, 0, sizeof system_font_link->fs);
2687
    list_init(&system_font_link->links);    
2688

2689
    face = find_face_from_filename(tahoma_ttf, Tahoma);
2690 2691 2692
    if(face)
    {
        child_font = HeapAlloc(GetProcessHeap(), 0, sizeof(*child_font));
2693
        child_font->face = face;
2694
        child_font->font = NULL;
2695 2696
        system_font_link->fs.fsCsb[0] |= face->fs.fsCsb[0];
        system_font_link->fs.fsCsb[1] |= face->fs.fsCsb[1];
2697 2698
        TRACE("Found Tahoma in %s index %ld\n",
              debugstr_w(child_font->face->file), child_font->face->face_index);
2699 2700
        list_add_tail(&system_font_link->links, &child_font->entry);
    }
2701 2702
    font_link = find_font_link(Tahoma);
    if (font_link != NULL)
2703
    {
2704 2705
        CHILD_FONT *font_link_entry;
        LIST_FOR_EACH_ENTRY(font_link_entry, &font_link->links, CHILD_FONT, entry)
2706
        {
2707 2708 2709 2710
            CHILD_FONT *new_child;
            new_child = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_child));
            new_child->face = font_link_entry->face;
            new_child->font = NULL;
2711
            new_child->face->refcount++;
2712 2713
            system_font_link->fs.fsCsb[0] |= font_link_entry->face->fs.fsCsb[0];
            system_font_link->fs.fsCsb[1] |= font_link_entry->face->fs.fsCsb[1];
2714
            list_add_tail(&system_font_link->links, &new_child->entry);
2715 2716 2717 2718
        }
    }
    list_add_tail(&system_links, &system_font_link->entry);
}
2719

2720
static BOOL ReadFontDir(const char *dirname, BOOL external_fonts)
2721 2722 2723 2724 2725
{
    DIR *dir;
    struct dirent *dent;
    char path[MAX_PATH];

2726 2727
    TRACE("Loading fonts from %s\n", debugstr_a(dirname));

2728 2729
    dir = opendir(dirname);
    if(!dir) {
2730
        WARN("Can't open directory %s\n", debugstr_a(dirname));
2731 2732 2733
	return FALSE;
    }
    while((dent = readdir(dir)) != NULL) {
2734 2735
	struct stat statbuf;

2736 2737
        if(!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
	    continue;
2738 2739 2740

	TRACE("Found %s in %s\n", debugstr_a(dent->d_name), debugstr_a(dirname));

2741
	sprintf(path, "%s/%s", dirname, dent->d_name);
2742 2743 2744 2745 2746 2747 2748

	if(stat(path, &statbuf) == -1)
	{
	    WARN("Can't stat %s\n", debugstr_a(path));
	    continue;
	}
	if(S_ISDIR(statbuf.st_mode))
2749
	    ReadFontDir(path, external_fonts);
2750
	else
2751 2752 2753
        {
            DWORD addfont_flags = ADDFONT_ADD_TO_CACHE;
            if(external_fonts) addfont_flags |= ADDFONT_EXTERNAL_FONT;
2754
            AddFontToList(path, NULL, 0, addfont_flags);
2755
        }
2756
    }
2757
    closedir(dir);
2758 2759 2760
    return TRUE;
}

2761
#ifdef SONAME_LIBFONTCONFIG
2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781

static BOOL fontconfig_enabled;

static UINT parse_aa_pattern( FcPattern *pattern )
{
    FcBool antialias;
    int rgba;
    UINT aa_flags = 0;

    if (pFcPatternGetBool( pattern, FC_ANTIALIAS, 0, &antialias ) == FcResultMatch)
        aa_flags = antialias ? GGO_GRAY4_BITMAP : GGO_BITMAP;

    if (pFcPatternGetInteger( pattern, FC_RGBA, 0, &rgba ) == FcResultMatch)
    {
        switch (rgba)
        {
        case FC_RGBA_RGB:  aa_flags = WINE_GGO_HRGB_BITMAP; break;
        case FC_RGBA_BGR:  aa_flags = WINE_GGO_HBGR_BITMAP; break;
        case FC_RGBA_VRGB: aa_flags = WINE_GGO_VRGB_BITMAP; break;
        case FC_RGBA_VBGR: aa_flags = WINE_GGO_VBGR_BITMAP; break;
2782
        case FC_RGBA_NONE: aa_flags = aa_flags ? aa_flags : GGO_GRAY4_BITMAP; break;
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
        }
    }
    return aa_flags;
}

static void init_fontconfig(void)
{
    void *fc_handle = wine_dlopen(SONAME_LIBFONTCONFIG, RTLD_NOW, NULL, 0);

    if (!fc_handle)
    {
        TRACE("Wine cannot find the fontconfig library (%s).\n", SONAME_LIBFONTCONFIG);
        return;
    }

#define LOAD_FUNCPTR(f) if((p##f = wine_dlsym(fc_handle, #f, NULL, 0)) == NULL){WARN("Can't find symbol %s\n", #f); return;}
    LOAD_FUNCPTR(FcConfigSubstitute);
2800
    LOAD_FUNCPTR(FcDefaultSubstitute);
2801
    LOAD_FUNCPTR(FcFontList);
2802
    LOAD_FUNCPTR(FcFontMatch);
2803 2804
    LOAD_FUNCPTR(FcFontSetDestroy);
    LOAD_FUNCPTR(FcInit);
2805
    LOAD_FUNCPTR(FcPatternAddString);
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818
    LOAD_FUNCPTR(FcPatternCreate);
    LOAD_FUNCPTR(FcPatternDestroy);
    LOAD_FUNCPTR(FcPatternGetBool);
    LOAD_FUNCPTR(FcPatternGetInteger);
    LOAD_FUNCPTR(FcPatternGetString);
#undef LOAD_FUNCPTR

    if (pFcInit())
    {
        FcPattern *pattern = pFcPatternCreate();
        pFcConfigSubstitute( NULL, pattern, FcMatchFont );
        default_aa_flags = parse_aa_pattern( pattern );
        pFcPatternDestroy( pattern );
2819 2820 2821 2822 2823 2824 2825 2826 2827

        if (!default_aa_flags)
        {
            FcPattern *pattern = pFcPatternCreate();
            pFcConfigSubstitute( NULL, pattern, FcMatchPattern );
            default_aa_flags = parse_aa_pattern( pattern );
            pFcPatternDestroy( pattern );
        }

2828 2829 2830 2831 2832
        TRACE( "enabled, default flags = %x\n", default_aa_flags );
        fontconfig_enabled = TRUE;
    }
}

2833 2834 2835 2836 2837
static void load_fontconfig_fonts(void)
{
    FcPattern *pat;
    FcFontSet *fontset;
    int i, len;
2838 2839
    char *file;
    const char *ext;
2840

2841
    if (!fontconfig_enabled) return;
2842

2843
    pat = pFcPatternCreate();
2844 2845 2846 2847 2848 2849 2850 2851 2852
    if (!pat) return;

    fontset = pFcFontList(NULL, pat, NULL);
    if (!fontset)
    {
        pFcPatternDestroy(pat);
        return;
    }

2853
    for(i = 0; i < fontset->nfont; i++) {
2854
        FcBool scalable;
2855
        DWORD aa_flags;
2856

2857
        if(pFcPatternGetString(fontset->fonts[i], FC_FILE, 0, (FcChar8**)&file) != FcResultMatch)
2858 2859
            continue;

2860 2861
        pFcConfigSubstitute( NULL, fontset->fonts[i], FcMatchFont );

2862
        /* We're just interested in OT/TT fonts for now, so this hack just
2863 2864 2865 2866 2867 2868 2869 2870 2871
           picks up the scalable fonts without extensions .pf[ab] to save time
           loading every other font */

        if(pFcPatternGetBool(fontset->fonts[i], FC_SCALABLE, 0, &scalable) == FcResultMatch && !scalable)
        {
            TRACE("not scalable\n");
            continue;
        }

2872 2873
        aa_flags = parse_aa_pattern( fontset->fonts[i] );
        TRACE("fontconfig: %s aa %x\n", file, aa_flags);
2874

2875
        len = strlen( file );
2876
        if(len < 4) continue;
2877
        ext = &file[ len - 3 ];
2878
        if(_strnicmp(ext, "pfa", -1) && _strnicmp(ext, "pfb", -1))
2879 2880
            AddFontToList(file, NULL, 0,
                          ADDFONT_EXTERNAL_FONT | ADDFONT_ADD_TO_CACHE | ADDFONT_AA_FLAGS(aa_flags) );
2881 2882 2883 2884
    }
    pFcFontSetDestroy(fontset);
    pFcPatternDestroy(pat);
}
2885

2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
#elif defined(HAVE_CARBON_CARBON_H)

static void load_mac_font_callback(const void *value, void *context)
{
    CFStringRef pathStr = value;
    CFIndex len;
    char* path;

    len = CFStringGetMaximumSizeOfFileSystemRepresentation(pathStr);
    path = HeapAlloc(GetProcessHeap(), 0, len);
    if (path && CFStringGetFileSystemRepresentation(pathStr, path, len))
    {
        TRACE("font file %s\n", path);
        AddFontToList(path, NULL, 0, ADDFONT_EXTERNAL_FONT | ADDFONT_ADD_TO_CACHE);
    }
    HeapFree(GetProcessHeap(), 0, path);
}

static void load_mac_fonts(void)
{
    CFStringRef removeDupesKey;
    CFBooleanRef removeDupesValue;
    CFDictionaryRef options;
    CTFontCollectionRef col;
    CFArrayRef descs;
    CFMutableSetRef paths;
    CFIndex i;

    removeDupesKey = kCTFontCollectionRemoveDuplicatesOption;
    removeDupesValue = kCFBooleanTrue;
    options = CFDictionaryCreate(NULL, (const void**)&removeDupesKey, (const void**)&removeDupesValue, 1,
                                 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    col = CTFontCollectionCreateFromAvailableFonts(options);
    if (options) CFRelease(options);
    if (!col)
    {
        WARN("CTFontCollectionCreateFromAvailableFonts failed\n");
        return;
    }

    descs = CTFontCollectionCreateMatchingFontDescriptors(col);
    CFRelease(col);
    if (!descs)
    {
        WARN("CTFontCollectionCreateMatchingFontDescriptors failed\n");
        return;
    }

    paths = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
    if (!paths)
    {
        WARN("CFSetCreateMutable failed\n");
        CFRelease(descs);
        return;
    }

    for (i = 0; i < CFArrayGetCount(descs); i++)
    {
        CTFontDescriptorRef desc;
        CFURLRef url;
        CFStringRef ext;
        CFStringRef path;

        desc = CFArrayGetValueAtIndex(descs, i);

2951 2952 2953 2954
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
        url = CTFontDescriptorCopyAttribute(desc, kCTFontURLAttribute);
#else
        /* CTFontDescriptor doesn't support kCTFontURLAttribute prior to 10.6, so
2955 2956
           we have to go CFFontDescriptor -> CTFont -> ATSFont -> FSRef -> CFURL. */
        {
2957 2958 2959 2960
            CTFontRef font;
            ATSFontRef atsFont;
            OSStatus status;
            FSRef fsref;
2961

2962 2963
            font = CTFontCreateWithFontDescriptor(desc, 0, NULL);
            if (!font) continue;
2964

2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
            atsFont = CTFontGetPlatformFont(font, NULL);
            if (!atsFont)
            {
                CFRelease(font);
                continue;
            }

            status = ATSFontGetFileReference(atsFont, &fsref);
            CFRelease(font);
            if (status != noErr) continue;

            url = CFURLCreateFromFSRef(NULL, &fsref);
        }
#endif
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
        if (!url) continue;

        ext = CFURLCopyPathExtension(url);
        if (ext)
        {
            BOOL skip = (CFStringCompare(ext, CFSTR("pfa"), kCFCompareCaseInsensitive) == kCFCompareEqualTo ||
                         CFStringCompare(ext, CFSTR("pfb"), kCFCompareCaseInsensitive) == kCFCompareEqualTo);
            CFRelease(ext);
            if (skip)
            {
                CFRelease(url);
                continue;
            }
        }

        path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
        CFRelease(url);
        if (!path) continue;

        CFSetAddValue(paths, path);
        CFRelease(path);
    }

    CFRelease(descs);

    CFSetApplyFunction(paths, load_mac_font_callback, NULL);
    CFRelease(paths);
}

#endif

3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032
static char *get_font_dir(void)
{
    const char *build_dir, *data_dir;
    char *name = NULL;

    if ((data_dir = wine_get_data_dir()))
    {
        if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(data_dir) + 1 + sizeof(WINE_FONT_DIR) )))
            return NULL;
        strcpy( name, data_dir );
        strcat( name, "/" );
        strcat( name, WINE_FONT_DIR );
    }
    else if ((build_dir = wine_get_build_dir()))
    {
        if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(build_dir) + sizeof("/fonts") )))
            return NULL;
        strcpy( name, build_dir );
        strcat( name, "/fonts" );
    }
    return name;
}

3033
static char *get_data_dir_path( LPCWSTR file )
3034
{
3035
    char *unix_name = NULL;
3036
    char *font_dir = get_font_dir();
3037

3038
    if (font_dir)
3039
    {
3040
        INT len = WideCharToMultiByte(CP_UNIXCP, 0, file, -1, NULL, 0, NULL, NULL);
3041

3042 3043 3044
        unix_name = HeapAlloc(GetProcessHeap(), 0, strlen(font_dir) + len + 1 );
        strcpy(unix_name, font_dir);
        strcat(unix_name, "/");
3045 3046

        WideCharToMultiByte(CP_UNIXCP, 0, file, -1, unix_name + strlen(unix_name), len, NULL, NULL);
3047
        HeapFree( GetProcessHeap(), 0, font_dir );
3048 3049 3050
    }
    return unix_name;
}
3051

3052 3053 3054 3055 3056 3057 3058
static BOOL load_font_from_data_dir(LPCWSTR file)
{
    BOOL ret = FALSE;
    char *unix_name = get_data_dir_path( file );

    if (unix_name)
    {
3059
        EnterCriticalSection( &freetype_cs );
3060
        ret = AddFontToList(unix_name, NULL, 0, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_TO_CACHE);
3061
        LeaveCriticalSection( &freetype_cs );
3062 3063 3064 3065
        HeapFree(GetProcessHeap(), 0, unix_name);
    }
    return ret;
}
3066

3067
static char *get_winfonts_dir_path(LPCWSTR file)
3068 3069 3070 3071
{
    static const WCHAR slashW[] = {'\\','\0'};
    WCHAR windowsdir[MAX_PATH];

3072
    GetWindowsDirectoryW(windowsdir, ARRAY_SIZE(windowsdir));
3073 3074 3075
    strcatW(windowsdir, fontsW);
    strcatW(windowsdir, slashW);
    strcatW(windowsdir, file);
3076
    return wine_get_unix_file_name( windowsdir );
3077 3078
}

3079
static void load_system_fonts(void)
3080 3081 3082
{
    HKEY hkey;
    WCHAR data[MAX_PATH], windowsdir[MAX_PATH], pathW[MAX_PATH];
3083
    const WCHAR * const *value;
3084 3085 3086 3087 3088
    DWORD dlen, type;
    static const WCHAR fmtW[] = {'%','s','\\','%','s','\0'};
    char *unixname;

    if(RegOpenKeyW(HKEY_CURRENT_CONFIG, system_fonts_reg_key, &hkey) == ERROR_SUCCESS) {
3089
        GetWindowsDirectoryW(windowsdir, ARRAY_SIZE(windowsdir));
3090 3091 3092 3093 3094
        strcatW(windowsdir, fontsW);
        for(value = SystemFontValues; *value; value++) { 
            dlen = sizeof(data);
            if(RegQueryValueExW(hkey, *value, 0, &type, (void*)data, &dlen) == ERROR_SUCCESS &&
               type == REG_SZ) {
3095 3096
                BOOL added = FALSE;

3097 3098
                sprintfW(pathW, fmtW, windowsdir, data);
                if((unixname = wine_get_unix_file_name(pathW))) {
3099
                    added = AddFontToList(unixname, NULL, 0, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_TO_CACHE);
3100 3101
                    HeapFree(GetProcessHeap(), 0, unixname);
                }
3102 3103
                if (!added)
                    load_font_from_data_dir(data);
3104 3105 3106 3107 3108 3109
            }
        }
        RegCloseKey(hkey);
    }
}

3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136
static WCHAR *get_full_path_name(const WCHAR *name)
{
    WCHAR *full_path;
    DWORD len;

    if (!(len = GetFullPathNameW(name, 0, NULL, NULL)))
    {
        ERR("GetFullPathNameW() failed, name %s.\n", debugstr_w(name));
        return NULL;
    }

    if (!(full_path = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*full_path))))
    {
        ERR("Could not get memory.\n");
        return NULL;
    }

    if (GetFullPathNameW(name, len, full_path, NULL) != len - 1)
    {
        ERR("Unexpected GetFullPathNameW() result, name %s.\n", debugstr_w(name));
        HeapFree(GetProcessHeap(), 0, full_path);
        return NULL;
    }

    return full_path;
}

3137 3138 3139 3140 3141 3142 3143
/*************************************************************
 *
 * This adds registry entries for any externally loaded fonts
 * (fonts from fontconfig or FontDirs).  It also deletes entries
 * of no longer existing fonts.
 *
 */
3144
static void update_reg_entries(void)
3145
{
3146
    HKEY winnt_key = 0, win9x_key = 0, external_key = 0;
3147
    LPWSTR valueW;
3148
    DWORD len;
3149 3150
    Family *family;
    Face *face;
3151
    WCHAR *file, *path, *full_path;
3152
    static const WCHAR TrueType[] = {' ','(','T','r','u','e','T','y','p','e',')','\0'};
3153

3154 3155
    if(RegCreateKeyExW(HKEY_LOCAL_MACHINE, winnt_font_reg_key,
                       0, NULL, 0, KEY_ALL_ACCESS, NULL, &winnt_key, NULL) != ERROR_SUCCESS) {
3156 3157 3158 3159
        ERR("Can't create Windows font reg key\n");
        goto end;
    }

3160 3161 3162 3163
    if(RegCreateKeyExW(HKEY_LOCAL_MACHINE, win9x_font_reg_key,
                       0, NULL, 0, KEY_ALL_ACCESS, NULL, &win9x_key, NULL) != ERROR_SUCCESS) {
        ERR("Can't create Windows font reg key\n");
        goto end;
3164 3165
    }

3166
    if(RegCreateKeyExW(HKEY_CURRENT_USER, external_fonts_reg_key,
3167
                       0, NULL, 0, KEY_ALL_ACCESS, NULL, &external_key, NULL) != ERROR_SUCCESS) {
3168 3169 3170 3171 3172 3173
        ERR("Can't create external font reg key\n");
        goto end;
    }

    /* enumerate the fonts and add external ones to the two keys */

3174 3175
    LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
        LIST_FOR_EACH_ENTRY( face, &family->faces, Face, entry ) {
3176
            char *buffer;
3177 3178
            WCHAR *name;

3179
            if (!(face->flags & ADDFONT_EXTERNAL_FONT)) continue;
3180

3181 3182 3183 3184
            name = face->FullName ? face->FullName : family->FamilyName;

            len = strlenW(name) + 1;
            if (face->scalable)
3185
                len += ARRAY_SIZE(TrueType);
3186 3187 3188 3189 3190 3191

            valueW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
            strcpyW(valueW, name);

            if (face->scalable)
                strcatW(valueW, TrueType);
3192

3193 3194 3195 3196 3197
            buffer = strWtoA( CP_UNIXCP, face->file );
            path = wine_get_dos_file_name( buffer );
            HeapFree( GetProcessHeap(), 0, buffer );

            if (path)
3198 3199 3200 3201 3202 3203
            {
                if ((full_path = get_full_path_name(path)))
                {
                    HeapFree(GetProcessHeap(), 0, path);
                    path = full_path;
                }
3204
                file = path;
3205
            }
3206
            else if ((file = strrchrW(face->file, '/')))
3207
            {
3208
                file++;
3209
            }
3210
            else
3211
            {
3212
                file = face->file;
3213
            }
3214

3215
            len = strlenW(file) + 1;
3216 3217 3218
            RegSetValueExW(winnt_key, valueW, 0, REG_SZ, (BYTE*)file, len * sizeof(WCHAR));
            RegSetValueExW(win9x_key, valueW, 0, REG_SZ, (BYTE*)file, len * sizeof(WCHAR));
            RegSetValueExW(external_key, valueW, 0, REG_SZ, (BYTE*)file, len * sizeof(WCHAR));
3219

3220
            HeapFree(GetProcessHeap(), 0, path);
3221 3222 3223 3224
            HeapFree(GetProcessHeap(), 0, valueW);
        }
    }
 end:
3225 3226 3227
    if(external_key) RegCloseKey(external_key);
    if(win9x_key) RegCloseKey(win9x_key);
    if(winnt_key) RegCloseKey(winnt_key);
3228 3229
}

3230 3231 3232
static void delete_external_font_keys(void)
{
    HKEY winnt_key = 0, win9x_key = 0, external_key = 0;
3233
    DWORD dlen, plen, vlen, datalen, valuelen, i, type, path_type;
3234 3235
    LPWSTR valueW;
    LPVOID data;
3236
    BYTE *path;
3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260

    if(RegCreateKeyExW(HKEY_LOCAL_MACHINE, winnt_font_reg_key,
                       0, NULL, 0, KEY_ALL_ACCESS, NULL, &winnt_key, NULL) != ERROR_SUCCESS) {
        ERR("Can't create Windows font reg key\n");
        goto end;
    }

    if(RegCreateKeyExW(HKEY_LOCAL_MACHINE, win9x_font_reg_key,
                       0, NULL, 0, KEY_ALL_ACCESS, NULL, &win9x_key, NULL) != ERROR_SUCCESS) {
        ERR("Can't create Windows font reg key\n");
        goto end;
    }

    if(RegCreateKeyW(HKEY_CURRENT_USER, external_fonts_reg_key, &external_key) != ERROR_SUCCESS) {
        ERR("Can't create external font reg key\n");
        goto end;
    }

    /* Delete all external fonts added last time */

    RegQueryInfoKeyW(external_key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                     &valuelen, &datalen, NULL, NULL);
    valuelen++; /* returned value doesn't include room for '\0' */
    valueW = HeapAlloc(GetProcessHeap(), 0, valuelen * sizeof(WCHAR));
3261
    data = HeapAlloc(GetProcessHeap(), 0, datalen);
3262
    path = HeapAlloc(GetProcessHeap(), 0, datalen);
3263

3264
    dlen = datalen;
3265 3266 3267 3268
    vlen = valuelen;
    i = 0;
    while(RegEnumValueW(external_key, i++, valueW, &vlen, NULL, &type, data,
                        &dlen) == ERROR_SUCCESS) {
3269 3270 3271 3272 3273 3274 3275 3276 3277
        plen = dlen;
        if (RegQueryValueExW(winnt_key, valueW, 0, &path_type, path, &plen) == ERROR_SUCCESS &&
            type == path_type && dlen == plen && !memcmp(data, path, plen))
            RegDeleteValueW(winnt_key, valueW);

        plen = dlen;
        if (RegQueryValueExW(win9x_key, valueW, 0, &path_type, path, &plen) == ERROR_SUCCESS &&
            type == path_type && dlen == plen && !memcmp(data, path, plen))
            RegDeleteValueW(win9x_key, valueW);
3278 3279 3280 3281 3282

        /* reset dlen and vlen */
        dlen = datalen;
        vlen = valuelen;
    }
3283
    HeapFree(GetProcessHeap(), 0, path);
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
    HeapFree(GetProcessHeap(), 0, data);
    HeapFree(GetProcessHeap(), 0, valueW);

    /* Delete the old external fonts key */
    RegCloseKey(external_key);
    RegDeleteKeyW(HKEY_CURRENT_USER, external_fonts_reg_key);

 end:
    if(win9x_key) RegCloseKey(win9x_key);
    if(winnt_key) RegCloseKey(winnt_key);
}
3295

3296 3297 3298 3299 3300 3301
/*************************************************************
 *    WineEngAddFontResourceEx
 *
 */
INT WineEngAddFontResourceEx(LPCWSTR file, DWORD flags, PVOID pdv)
{
3302
    INT ret = 0;
3303 3304 3305

    GDI_CheckNotLock();

3306 3307
    if (ft_handle)  /* do it only if we have freetype up and running */
    {
3308
        char *unixname;
3309

3310
        EnterCriticalSection( &freetype_cs );
3311

3312 3313
        if((unixname = wine_get_unix_file_name(file)))
        {
3314
            DWORD addfont_flags = ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE;
3315 3316

            if(!(flags & FR_PRIVATE)) addfont_flags |= ADDFONT_ADD_TO_CACHE;
3317
            ret = AddFontToList(unixname, NULL, 0, addfont_flags);
3318
            HeapFree(GetProcessHeap(), 0, unixname);
3319 3320 3321
        }
        if (!ret && !strchrW(file, '\\')) {
            /* Try in %WINDIR%/fonts, needed for Fotobuch Designer */
3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
            if ((unixname = get_winfonts_dir_path( file )))
            {
                ret = AddFontToList(unixname, NULL, 0, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE);
                HeapFree(GetProcessHeap(), 0, unixname);
            }
            /* Try in datadir/fonts (or builddir/fonts), needed for Magic the Gathering Online */
            if (!ret && (unixname = get_data_dir_path( file )))
            {
                ret = AddFontToList(unixname, NULL, 0, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE);
                HeapFree(GetProcessHeap(), 0, unixname);
3332
            }
3333
        }
3334 3335

        LeaveCriticalSection( &freetype_cs );
3336
    }
3337
    return ret;
3338
}
3339

3340 3341 3342 3343 3344 3345
/*************************************************************
 *    WineEngAddFontMemResourceEx
 *
 */
HANDLE WineEngAddFontMemResourceEx(PVOID pbFont, DWORD cbFont, PVOID pdv, DWORD *pcFonts)
{
3346 3347
    GDI_CheckNotLock();

3348 3349 3350 3351 3352 3353 3354
    if (ft_handle)  /* do it only if we have freetype up and running */
    {
        PVOID pFontCopy = HeapAlloc(GetProcessHeap(), 0, cbFont);

        TRACE("Copying %d bytes of data from %p to %p\n", cbFont, pbFont, pFontCopy);
        memcpy(pFontCopy, pbFont, cbFont);

3355
        EnterCriticalSection( &freetype_cs );
3356
        *pcFonts = AddFontToList(NULL, pFontCopy, cbFont, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE);
3357
        LeaveCriticalSection( &freetype_cs );
3358 3359 3360 3361 3362

        if (*pcFonts == 0)
        {
            TRACE("AddFontToList failed\n");
            HeapFree(GetProcessHeap(), 0, pFontCopy);
3363
            return 0;
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
        }
        /* FIXME: is the handle only for use in RemoveFontMemResourceEx or should it be a true handle?
         * For now return something unique but quite random
         */
        TRACE("Returning handle %lx\n", ((INT_PTR)pFontCopy)^0x87654321);
        return (HANDLE)(((INT_PTR)pFontCopy)^0x87654321);
    }

    *pcFonts = 0;
    return 0;
}

3376 3377 3378 3379 3380 3381
/*************************************************************
 *    WineEngRemoveFontResourceEx
 *
 */
BOOL WineEngRemoveFontResourceEx(LPCWSTR file, DWORD flags, PVOID pdv)
{
3382 3383
    INT ret = 0;

3384
    GDI_CheckNotLock();
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416

    if (ft_handle)  /* do it only if we have freetype up and running */
    {
        char *unixname;

        EnterCriticalSection( &freetype_cs );

        if ((unixname = wine_get_unix_file_name(file)))
        {
            DWORD addfont_flags = ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE;

            if(!(flags & FR_PRIVATE)) addfont_flags |= ADDFONT_ADD_TO_CACHE;
            ret = remove_font_resource( unixname, addfont_flags );
            HeapFree(GetProcessHeap(), 0, unixname);
        }
        if (!ret && !strchrW(file, '\\'))
        {
            if ((unixname = get_winfonts_dir_path( file )))
            {
                ret = remove_font_resource( unixname, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE );
                HeapFree(GetProcessHeap(), 0, unixname);
            }
            if (!ret && (unixname = get_data_dir_path( file )))
            {
                ret = remove_font_resource( unixname, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE );
                HeapFree(GetProcessHeap(), 0, unixname);
            }
        }

        LeaveCriticalSection( &freetype_cs );
    }
    return ret;
3417
}
3418

3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489
static char *get_ttf_file_name( LPCWSTR font_file, LPCWSTR font_path )
{
    WCHAR *fullname;
    char *unix_name;
    int file_len;

    if (!font_file) return NULL;

    file_len = strlenW( font_file );

    if (font_path && font_path[0])
    {
        int path_len = strlenW( font_path );
        fullname = HeapAlloc( GetProcessHeap(), 0, (file_len + path_len + 2) * sizeof(WCHAR) );
        if (!fullname) return NULL;
        memcpy( fullname, font_path, path_len * sizeof(WCHAR) );
        fullname[path_len] = '\\';
        memcpy( fullname + path_len + 1, font_file, (file_len + 1) * sizeof(WCHAR) );
    }
    else
    {
        int len = GetFullPathNameW( font_file, 0, NULL, NULL );
        if (!len) return NULL;
        fullname = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
        if (!fullname) return NULL;
        GetFullPathNameW( font_file, len, fullname, NULL );
    }

    unix_name = wine_get_unix_file_name( fullname );
    HeapFree( GetProcessHeap(), 0, fullname );
    return unix_name;
}

#include <pshpack1.h>
struct fontdir
{
    WORD   num_of_resources;
    WORD   res_id;
    WORD   dfVersion;
    DWORD  dfSize;
    CHAR   dfCopyright[60];
    WORD   dfType;
    WORD   dfPoints;
    WORD   dfVertRes;
    WORD   dfHorizRes;
    WORD   dfAscent;
    WORD   dfInternalLeading;
    WORD   dfExternalLeading;
    BYTE   dfItalic;
    BYTE   dfUnderline;
    BYTE   dfStrikeOut;
    WORD   dfWeight;
    BYTE   dfCharSet;
    WORD   dfPixWidth;
    WORD   dfPixHeight;
    BYTE   dfPitchAndFamily;
    WORD   dfAvgWidth;
    WORD   dfMaxWidth;
    BYTE   dfFirstChar;
    BYTE   dfLastChar;
    BYTE   dfDefaultChar;
    BYTE   dfBreakChar;
    WORD   dfWidthBytes;
    DWORD  dfDevice;
    DWORD  dfFace;
    DWORD  dfReserved;
    CHAR   szFaceName[LF_FACESIZE];
};

#include <poppack.h>

3490
static void GetEnumStructs(Face *face, const WCHAR *family_name, LPENUMLOGFONTEXW pelf,
3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502
                           NEWTEXTMETRICEXW *pntm, LPDWORD ptype);

static BOOL get_fontdir( const char *unix_name, struct fontdir *fd )
{
    FT_Face ft_face = new_ft_face( unix_name, NULL, 0, 0, FALSE );
    Face *face;
    WCHAR *name, *english_name;
    ENUMLOGFONTEXW elf;
    NEWTEXTMETRICEXW ntm;
    DWORD type;

    if (!ft_face) return FALSE;
3503
    face = create_face( ft_face, 0, unix_name, NULL, 0, 0 );
3504 3505 3506
    get_family_names( ft_face, &name, &english_name, FALSE );
    pFT_Done_Face( ft_face );

3507
    GetEnumStructs( face, name, &elf, &ntm, &type );
3508
    release_face( face );
3509 3510
    HeapFree( GetProcessHeap(), 0, name );
    HeapFree( GetProcessHeap(), 0, english_name );
3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720

    if ((type & TRUETYPE_FONTTYPE) == 0) return FALSE;

    memset( fd, 0, sizeof(*fd) );

    fd->num_of_resources  = 1;
    fd->res_id            = 0;
    fd->dfVersion         = 0x200;
    fd->dfSize            = sizeof(*fd);
    strcpy( fd->dfCopyright, "Wine fontdir" );
    fd->dfType            = 0x4003;  /* 0x0080 set if private */
    fd->dfPoints          = ntm.ntmTm.ntmSizeEM;
    fd->dfVertRes         = 72;
    fd->dfHorizRes        = 72;
    fd->dfAscent          = ntm.ntmTm.tmAscent;
    fd->dfInternalLeading = ntm.ntmTm.tmInternalLeading;
    fd->dfExternalLeading = ntm.ntmTm.tmExternalLeading;
    fd->dfItalic          = ntm.ntmTm.tmItalic;
    fd->dfUnderline       = ntm.ntmTm.tmUnderlined;
    fd->dfStrikeOut       = ntm.ntmTm.tmStruckOut;
    fd->dfWeight          = ntm.ntmTm.tmWeight;
    fd->dfCharSet         = ntm.ntmTm.tmCharSet;
    fd->dfPixWidth        = 0;
    fd->dfPixHeight       = ntm.ntmTm.tmHeight;
    fd->dfPitchAndFamily  = ntm.ntmTm.tmPitchAndFamily;
    fd->dfAvgWidth        = ntm.ntmTm.tmAveCharWidth;
    fd->dfMaxWidth        = ntm.ntmTm.tmMaxCharWidth;
    fd->dfFirstChar       = ntm.ntmTm.tmFirstChar;
    fd->dfLastChar        = ntm.ntmTm.tmLastChar;
    fd->dfDefaultChar     = ntm.ntmTm.tmDefaultChar;
    fd->dfBreakChar       = ntm.ntmTm.tmBreakChar;
    fd->dfWidthBytes      = 0;
    fd->dfDevice          = 0;
    fd->dfFace            = FIELD_OFFSET( struct fontdir, szFaceName );
    fd->dfReserved        = 0;
    WideCharToMultiByte( CP_ACP, 0, elf.elfLogFont.lfFaceName, -1, fd->szFaceName, LF_FACESIZE, NULL, NULL );

    return TRUE;
}

#define NE_FFLAGS_LIBMODULE     0x8000
#define NE_OSFLAGS_WINDOWS      0x02

static const char dos_string[0x40] = "This is a TrueType resource file";
static const char FONTRES[] = {'F','O','N','T','R','E','S',':'};

#include <pshpack2.h>

struct ne_typeinfo
{
    WORD type_id;
    WORD count;
    DWORD res;
};

struct ne_nameinfo
{
    WORD off;
    WORD len;
    WORD flags;
    WORD id;
    DWORD res;
};

struct rsrc_tab
{
    WORD align;
    struct ne_typeinfo fontdir_type;
    struct ne_nameinfo fontdir_name;
    struct ne_typeinfo scalable_type;
    struct ne_nameinfo scalable_name;
    WORD end_of_rsrc;
    BYTE fontdir_res_name[8];
};

#include <poppack.h>

static BOOL create_fot( const WCHAR *resource, const WCHAR *font_file, const struct fontdir *fontdir )
{
    BOOL ret = FALSE;
    HANDLE file;
    DWORD size, written;
    BYTE *ptr, *start;
    BYTE import_name_len, res_name_len, non_res_name_len, font_file_len;
    char *font_fileA, *last_part, *ext;
    IMAGE_DOS_HEADER dos;
    IMAGE_OS2_HEADER ne =
    {
        IMAGE_OS2_SIGNATURE, 5, 1, 0, 0, 0, NE_FFLAGS_LIBMODULE, 0,
        0, 0, 0, 0, 0, 0,
        0, sizeof(ne), sizeof(ne), 0, 0, 0, 0,
        0, 4, 2, NE_OSFLAGS_WINDOWS, 0, 0, 0, 0, 0x300
    };
    struct rsrc_tab rsrc_tab =
    {
        4,
        { 0x8007, 1, 0 },
        { 0, 0, 0x0c50, 0x2c, 0 },
        { 0x80cc, 1, 0 },
        { 0, 0, 0x0c50, 0x8001, 0 },
        0,
        { 7,'F','O','N','T','D','I','R'}
    };

    memset( &dos, 0, sizeof(dos) );
    dos.e_magic = IMAGE_DOS_SIGNATURE;
    dos.e_lfanew = sizeof(dos) + sizeof(dos_string);

    /* import name is last part\0, resident name is last part without extension
       non-resident name is "FONTRES:" + lfFaceName */

    font_file_len = WideCharToMultiByte( CP_ACP, 0, font_file, -1, NULL, 0, NULL, NULL );
    font_fileA = HeapAlloc( GetProcessHeap(), 0, font_file_len );
    WideCharToMultiByte( CP_ACP, 0, font_file, -1, font_fileA, font_file_len, NULL, NULL );

    last_part = strrchr( font_fileA, '\\' );
    if (last_part) last_part++;
    else last_part = font_fileA;
    import_name_len = strlen( last_part ) + 1;

    ext = strchr( last_part, '.' );
    if (ext) res_name_len = ext - last_part;
    else res_name_len = import_name_len - 1;

    non_res_name_len = sizeof( FONTRES ) + strlen( fontdir->szFaceName );

    ne.ne_cbnrestab = 1 + non_res_name_len + 2 + 1; /* len + string + (WORD) ord_num + 1 byte eod */
    ne.ne_restab = ne.ne_rsrctab + sizeof(rsrc_tab);
    ne.ne_modtab = ne.ne_imptab = ne.ne_restab + 1 + res_name_len + 2 + 3; /* len + string + (WORD) ord_num + 3 bytes eod */
    ne.ne_enttab = ne.ne_imptab + 1 + import_name_len; /* len + string */
    ne.ne_cbenttab = 2;
    ne.ne_nrestab = ne.ne_enttab + ne.ne_cbenttab + 2 + dos.e_lfanew; /* there are 2 bytes of 0 after entry tab */

    rsrc_tab.scalable_name.off = (ne.ne_nrestab + ne.ne_cbnrestab + 0xf) >> 4;
    rsrc_tab.scalable_name.len = (font_file_len + 0xf) >> 4;
    rsrc_tab.fontdir_name.off  = rsrc_tab.scalable_name.off + rsrc_tab.scalable_name.len;
    rsrc_tab.fontdir_name.len  = (fontdir->dfSize + 0xf) >> 4;

    size = (rsrc_tab.fontdir_name.off + rsrc_tab.fontdir_name.len) << 4;
    start = ptr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size );

    if (!ptr)
    {
        HeapFree( GetProcessHeap(), 0, font_fileA );
        return FALSE;
    }

    memcpy( ptr, &dos, sizeof(dos) );
    memcpy( ptr + sizeof(dos), dos_string, sizeof(dos_string) );
    memcpy( ptr + dos.e_lfanew, &ne, sizeof(ne) );

    ptr = start + dos.e_lfanew + ne.ne_rsrctab;
    memcpy( ptr, &rsrc_tab, sizeof(rsrc_tab) );

    ptr = start + dos.e_lfanew + ne.ne_restab;
    *ptr++ = res_name_len;
    memcpy( ptr, last_part, res_name_len );

    ptr = start + dos.e_lfanew + ne.ne_imptab;
    *ptr++ = import_name_len;
    memcpy( ptr, last_part, import_name_len );

    ptr = start + ne.ne_nrestab;
    *ptr++ = non_res_name_len;
    memcpy( ptr, FONTRES, sizeof(FONTRES) );
    memcpy( ptr + sizeof(FONTRES), fontdir->szFaceName, strlen( fontdir->szFaceName ) );

    ptr = start + (rsrc_tab.scalable_name.off << 4);
    memcpy( ptr, font_fileA, font_file_len );

    ptr = start + (rsrc_tab.fontdir_name.off << 4);
    memcpy( ptr, fontdir, fontdir->dfSize );

    file = CreateFileW( resource, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL );
    if (file != INVALID_HANDLE_VALUE)
    {
        if (WriteFile( file, start, size, &written, NULL ) && written == size)
            ret = TRUE;
        CloseHandle( file );
    }

    HeapFree( GetProcessHeap(), 0, start );
    HeapFree( GetProcessHeap(), 0, font_fileA );

    return ret;
}

/*************************************************************
 *    WineEngCreateScalableFontResource
 *
 */
BOOL WineEngCreateScalableFontResource( DWORD hidden, LPCWSTR resource,
                                        LPCWSTR font_file, LPCWSTR font_path )
{
    char *unix_name = get_ttf_file_name( font_file, font_path );
    struct fontdir fontdir;
    BOOL ret = FALSE;

    if (!unix_name || !get_fontdir( unix_name, &fontdir ))
        SetLastError( ERROR_INVALID_PARAMETER );
    else
    {
        if (hidden) fontdir.dfType |= 0x80;
        ret = create_fot( resource, font_file, &fontdir );
    }

    HeapFree( GetProcessHeap(), 0, unix_name );
    return ret;
}

3721 3722 3723 3724
static const struct nls_update_font_list
{
    UINT ansi_cp, oem_cp;
    const char *oem, *fixed, *system;
3725
    const char *courier, *serif, *small, *sserif_96, *sserif_120;
3726
    /* these are for font substitutes */
3727
    const char *shelldlg, *tmsrmn;
3728 3729 3730 3731 3732 3733
    const char *fixed_0, *system_0, *courier_0, *serif_0, *small_0, *sserif_0,
               *helv_0, *tmsrmn_0;
    const struct subst
    {
        const char *from, *to;
    } arial_0, courier_new_0, times_new_roman_0;
3734 3735
} nls_update_font_list[] =
{
3736 3737
    /* Latin 1 (United States) */
    { 1252, 437, "vgaoem.fon", "vgafix.fon", "vgasys.fon",
3738
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
3739
      "Tahoma","Times New Roman",
3740 3741
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      { 0 }, { 0 }, { 0 }
3742
    },
3743 3744
    /* Latin 1 (Multilingual) */
    { 1252, 850, "vga850.fon", "vgafix.fon", "vgasys.fon",
3745
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
3746
      "Tahoma","Times New Roman",  /* FIXME unverified */
3747 3748
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      { 0 }, { 0 }, { 0 }
3749
    },
3750
    /* Eastern Europe */
3751
    { 1250, 852, "vga852.fon", "vgafixe.fon", "vgasyse.fon",
3752
      "couree.fon", "serifee.fon", "smallee.fon", "sserifee.fon", "sseriffe.fon",
3753
      "Tahoma","Times New Roman", /* FIXME unverified */
3754 3755 3756 3757 3758 3759
      "Fixedsys,238", "System,238",
      "Courier New,238", "MS Serif,238", "Small Fonts,238",
      "MS Sans Serif,238", "MS Sans Serif,238", "MS Serif,238",
      { "Arial CE,0", "Arial,238" },
      { "Courier New CE,0", "Courier New,238" },
      { "Times New Roman CE,0", "Times New Roman,238" }
3760 3761 3762
    },
    /* Cyrillic */
    { 1251, 866, "vga866.fon", "vgafixr.fon", "vgasysr.fon",
3763
      "courer.fon", "serifer.fon", "smaller.fon", "sserifer.fon", "sseriffr.fon",
3764
      "Tahoma","Times New Roman", /* FIXME unverified */
3765 3766 3767 3768 3769 3770
      "Fixedsys,204", "System,204",
      "Courier New,204", "MS Serif,204", "Small Fonts,204",
      "MS Sans Serif,204", "MS Sans Serif,204", "MS Serif,204",
      { "Arial Cyr,0", "Arial,204" },
      { "Courier New Cyr,0", "Courier New,204" },
      { "Times New Roman Cyr,0", "Times New Roman,204" }
3771 3772 3773
    },
    /* Greek */
    { 1253, 737, "vga869.fon", "vgafixg.fon", "vgasysg.fon",
3774
      "coureg.fon", "serifeg.fon", "smalleg.fon", "sserifeg.fon", "sseriffg.fon",
3775
      "Tahoma","Times New Roman", /* FIXME unverified */
3776 3777 3778 3779 3780 3781
      "Fixedsys,161", "System,161",
      "Courier New,161", "MS Serif,161", "Small Fonts,161",
      "MS Sans Serif,161", "MS Sans Serif,161", "MS Serif,161",
      { "Arial Greek,0", "Arial,161" },
      { "Courier New Greek,0", "Courier New,161" },
      { "Times New Roman Greek,0", "Times New Roman,161" }
3782
    },
3783 3784
    /* Turkish */
    { 1254, 857, "vga857.fon", "vgafixt.fon", "vgasyst.fon",
3785
      "couret.fon", "serifet.fon", "smallet.fon", "sserifet.fon", "sserifft.fon",
3786
      "Tahoma","Times New Roman", /* FIXME unverified */
3787 3788 3789 3790 3791 3792
      "Fixedsys,162", "System,162",
      "Courier New,162", "MS Serif,162", "Small Fonts,162",
      "MS Sans Serif,162", "MS Sans Serif,162", "MS Serif,162",
      { "Arial Tur,0", "Arial,162" },
      { "Courier New Tur,0", "Courier New,162" },
      { "Times New Roman Tur,0", "Times New Roman,162" }
3793
    },
3794 3795
    /* Hebrew */
    { 1255, 862, "vgaoem.fon", "vgaf1255.fon", "vgas1255.fon",
3796
      "coue1255.fon", "sere1255.fon", "smae1255.fon", "ssee1255.fon", "ssef1255.fon",
3797
      "Tahoma","Times New Roman", /* FIXME unverified */
3798 3799 3800 3801
      "Fixedsys,177", "System,177",
      "Courier New,177", "MS Serif,177", "Small Fonts,177",
      "MS Sans Serif,177", "MS Sans Serif,177", "MS Serif,177",
      { 0 }, { 0 }, { 0 }
3802
    },
3803 3804
    /* Arabic */
    { 1256, 720, "vgaoem.fon", "vgaf1256.fon", "vgas1256.fon",
3805
      "coue1256.fon", "sere1256.fon", "smae1256.fon", "ssee1256.fon", "ssef1256.fon",
3806
      "Microsoft Sans Serif","Times New Roman",
3807 3808 3809 3810
      "Fixedsys,178", "System,178",
      "Courier New,178", "MS Serif,178", "Small Fonts,178",
      "MS Sans Serif,178", "MS Sans Serif,178", "MS Serif,178",
      { 0 }, { 0 }, { 0 }
3811
    },
3812 3813
    /* Baltic */
    { 1257, 775, "vga775.fon", "vgaf1257.fon", "vgas1257.fon",
3814
      "coue1257.fon", "sere1257.fon", "smae1257.fon", "ssee1257.fon", "ssef1257.fon",
3815
      "Tahoma","Times New Roman", /* FIXME unverified */
3816 3817 3818 3819 3820 3821
      "Fixedsys,186", "System,186",
      "Courier New,186", "MS Serif,186", "Small Fonts,186",
      "MS Sans Serif,186", "MS Sans Serif,186", "MS Serif,186",
      { "Arial Baltic,0", "Arial,186" },
      { "Courier New Baltic,0", "Courier New,186" },
      { "Times New Roman Baltic,0", "Times New Roman,186" }
3822 3823 3824
    },
    /* Vietnamese */
    { 1258, 1258, "vga850.fon", "vgafix.fon", "vgasys.fon",
3825
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
3826
      "Tahoma","Times New Roman", /* FIXME unverified */
3827 3828
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      { 0 }, { 0 }, { 0 }
3829 3830 3831
    },
    /* Thai */
    { 874, 874, "vga850.fon", "vgaf874.fon", "vgas874.fon",
3832
      "coure.fon", "serife.fon", "smalle.fon", "ssee874.fon", "ssef874.fon",
3833
      "Tahoma","Times New Roman", /* FIXME unverified */
3834 3835
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      { 0 }, { 0 }, { 0 }
3836
    },
3837 3838
    /* Japanese */
    { 932, 932, "vga932.fon", "jvgafix.fon", "jvgasys.fon",
3839
      "coure.fon", "serife.fon", "jsmalle.fon", "sserife.fon", "sseriff.fon",
3840
      "MS UI Gothic","MS Serif",
3841 3842
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      { 0 }, { 0 }, { 0 }
3843
    },
3844 3845
    /* Chinese Simplified */
    { 936, 936, "vga936.fon", "svgafix.fon", "svgasys.fon",
3846
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
3847
      "SimSun", "NSimSun",
3848 3849
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      { 0 }, { 0 }, { 0 }
3850
    },
3851 3852
    /* Korean */
    { 949, 949, "vga949.fon", "hvgafix.fon", "hvgasys.fon",
3853
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
3854
      "Gulim",  "Batang",
3855 3856
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      { 0 }, { 0 }, { 0 }
3857
    },
3858 3859
    /* Chinese Traditional */
    { 950, 950, "vga950.fon", "cvgafix.fon", "cvgasys.fon",
3860
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
3861
      "PMingLiU",  "MingLiU",
3862 3863
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      { 0 }, { 0 }, { 0 }
3864 3865 3866
    }
};

3867 3868 3869 3870 3871 3872 3873 3874
static inline BOOL is_dbcs_ansi_cp(UINT ansi_cp)
{
    return ( ansi_cp == 932       /* CP932 for Japanese */
            || ansi_cp == 936     /* CP936 for Chinese Simplified */
            || ansi_cp == 949     /* CP949 for Korean */
            || ansi_cp == 950 );  /* CP950 for Chinese Traditional */
}

3875
static inline HKEY create_fonts_NT_registry_key(void)
3876 3877 3878 3879 3880 3881 3882 3883
{
    HKEY hkey = 0;

    RegCreateKeyExW(HKEY_LOCAL_MACHINE, winnt_font_reg_key, 0, NULL,
                    0, KEY_ALL_ACCESS, NULL, &hkey, NULL);
    return hkey;
}

3884
static inline HKEY create_fonts_9x_registry_key(void)
3885 3886 3887 3888 3889 3890 3891 3892
{
    HKEY hkey = 0;

    RegCreateKeyExW(HKEY_LOCAL_MACHINE, win9x_font_reg_key, 0, NULL,
                    0, KEY_ALL_ACCESS, NULL, &hkey, NULL);
    return hkey;
}

3893
static inline HKEY create_config_fonts_registry_key(void)
3894 3895 3896 3897 3898 3899 3900 3901
{
    HKEY hkey = 0;

    RegCreateKeyExW(HKEY_CURRENT_CONFIG, system_fonts_reg_key, 0, NULL,
                    0, KEY_ALL_ACCESS, NULL, &hkey, NULL);
    return hkey;
}

3902
static void add_font_list(HKEY hkey, const struct nls_update_font_list *fl, int dpi)
3903
{
3904 3905
    const char *sserif = (dpi <= 108) ? fl->sserif_96 : fl->sserif_120;

3906 3907
    RegSetValueExA(hkey, "Courier", 0, REG_SZ, (const BYTE *)fl->courier, strlen(fl->courier)+1);
    RegSetValueExA(hkey, "MS Serif", 0, REG_SZ, (const BYTE *)fl->serif, strlen(fl->serif)+1);
3908
    RegSetValueExA(hkey, "MS Sans Serif", 0, REG_SZ, (const BYTE *)sserif, strlen(sserif)+1);
3909 3910 3911
    RegSetValueExA(hkey, "Small Fonts", 0, REG_SZ, (const BYTE *)fl->small, strlen(fl->small)+1);
}

3912 3913 3914 3915 3916 3917 3918 3919
static void set_value_key(HKEY hkey, const char *name, const char *value)
{
    if (value)
        RegSetValueExA(hkey, name, 0, REG_SZ, (const BYTE *)value, strlen(value) + 1);
    else if (name)
        RegDeleteValueA(hkey, name);
}

3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959
static void update_font_association_info(UINT current_ansi_codepage)
{
    static const char *font_assoc_reg_key = "System\\CurrentControlSet\\Control\\FontAssoc";
    static const char *assoc_charset_subkey = "Associated Charset";

    if (is_dbcs_ansi_cp(current_ansi_codepage))
    {
        HKEY hkey;
        if (RegCreateKeyA(HKEY_LOCAL_MACHINE, font_assoc_reg_key, &hkey) == ERROR_SUCCESS)
        {
            HKEY hsubkey;
            if (RegCreateKeyA(hkey, assoc_charset_subkey, &hsubkey) == ERROR_SUCCESS)
            {
                switch (current_ansi_codepage)
                {
                case 932:
                    set_value_key(hsubkey, "ANSI(00)", "NO");
                    set_value_key(hsubkey, "OEM(FF)", "NO");
                    set_value_key(hsubkey, "SYMBOL(02)", "NO");
                    break;
                case 936:
                case 949:
                case 950:
                    set_value_key(hsubkey, "ANSI(00)", "YES");
                    set_value_key(hsubkey, "OEM(FF)", "YES");
                    set_value_key(hsubkey, "SYMBOL(02)", "NO");
                    break;
                }
                RegCloseKey(hsubkey);
            }

            /* TODO: Associated DefaultFonts */

            RegCloseKey(hkey);
        }
    }
    else
        RegDeleteTreeA(HKEY_LOCAL_MACHINE, font_assoc_reg_key);
}

3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035
static void set_multi_value_key(HKEY hkey, const WCHAR *name, const WCHAR *value, DWORD len)
{
    if (value)
        RegSetValueExW(hkey, name, 0, REG_MULTI_SZ, (const BYTE *)value, len);
    else if (name)
        RegDeleteValueW(hkey, name);
}

static void update_font_system_link_info(UINT current_ansi_codepage)
{
    static const WCHAR system_link_simplified_chinese[] =
        {'S','I','M','S','U','N','.','T','T','C',',','S','i','m','S','u','n','\0',
         'M','I','N','G','L','I','U','.','T','T','C',',','P','M','i','n','g','L','i','u','\0',
         'M','S','G','O','T','H','I','C','.','T','T','C',',','M','S',' ','U','I',' ','G','o','t','h','i','c','\0',
         'B','A','T','A','N','G','.','T','T','C',',','B','a','t','a','n','g','\0',
         '\0'};
    static const WCHAR system_link_traditional_chinese[] =
        {'M','I','N','G','L','I','U','.','T','T','C',',','P','M','i','n','g','L','i','u','\0',
         'S','I','M','S','U','N','.','T','T','C',',','S','i','m','S','u','n','\0',
         'M','S','G','O','T','H','I','C','.','T','T','C',',','M','S',' ','U','I',' ','G','o','t','h','i','c','\0',
         'B','A','T','A','N','G','.','T','T','C',',','B','a','t','a','n','g','\0',
         '\0'};
    static const WCHAR system_link_japanese[] =
        {'M','S','G','O','T','H','I','C','.','T','T','C',',','M','S',' ','U','I',' ','G','o','t','h','i','c','\0',
         'M','I','N','G','L','I','U','.','T','T','C',',','P','M','i','n','g','L','i','U','\0',
         'S','I','M','S','U','N','.','T','T','C',',','S','i','m','S','u','n','\0',
         'G','U','L','I','M','.','T','T','C',',','G','u','l','i','m','\0',
         '\0'};
    static const WCHAR system_link_korean[] =
        {'G','U','L','I','M','.','T','T','C',',','G','u','l','i','m','\0',
         'M','S','G','O','T','H','I','C','.','T','T','C',',','M','S',' ','U','I',' ','G','o','t','h','i','c','\0',
         'M','I','N','G','L','I','U','.','T','T','C',',','P','M','i','n','g','L','i','U','\0',
         'S','I','M','S','U','N','.','T','T','C',',','S','i','m','S','u','n','\0',
         '\0'};
    static const WCHAR system_link_non_cjk[] =
        {'M','S','G','O','T','H','I','C','.','T','T','C',',','M','S',' ','U','I',' ','G','o','t','h','i','c','\0',
         'M','I','N','G','L','I','U','.','T','T','C',',','P','M','i','n','g','L','i','U','\0',
         'S','I','M','S','U','N','.','T','T','C',',','S','i','m','S','u','n','\0',
         'G','U','L','I','M','.','T','T','C',',','G','u','l','i','m','\0',
         '\0'};
    HKEY hkey;

    if (RegCreateKeyW(HKEY_LOCAL_MACHINE, system_link, &hkey) == ERROR_SUCCESS)
    {
        const WCHAR *link;
        DWORD len;

        switch (current_ansi_codepage)
        {
        case 932:
            link = system_link_japanese;
            len = sizeof(system_link_japanese);
            break;
        case 936:
            link = system_link_simplified_chinese;
            len = sizeof(system_link_simplified_chinese);
            break;
        case 949:
            link = system_link_korean;
            len = sizeof(system_link_korean);
            break;
        case 950:
            link = system_link_traditional_chinese;
            len = sizeof(system_link_traditional_chinese);
            break;
        default:
            link = system_link_non_cjk;
            len = sizeof(system_link_non_cjk);
        }
        set_multi_value_key(hkey, Lucida_Sans_Unicode, link, len);
        set_multi_value_key(hkey, Microsoft_Sans_Serif, link, len);
        set_multi_value_key(hkey, Tahoma, link, len);
        RegCloseKey(hkey);
    }
}

4036 4037
static void update_font_info(void)
{
4038
    static const WCHAR logpixels[] = { 'L','o','g','P','i','x','e','l','s',0 };
4039
    char buf[40], cpbuf[40];
4040 4041 4042
    DWORD len, type;
    HKEY hkey = 0;
    UINT i, ansi_cp = 0, oem_cp = 0;
4043
    DWORD screen_dpi, font_dpi = 0;
4044
    BOOL done = FALSE;
4045

4046 4047
    screen_dpi = get_dpi();
    if (!screen_dpi) screen_dpi = 96;
4048

4049
    if (RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\Wine\\Fonts", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hkey, NULL) != ERROR_SUCCESS)
4050 4051
        return;

4052 4053
    reg_load_dword(hkey, logpixels, &font_dpi);

4054 4055 4056 4057 4058 4059
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_IDEFAULTANSICODEPAGE|LOCALE_RETURN_NUMBER|LOCALE_NOUSEROVERRIDE,
                   (WCHAR *)&ansi_cp, sizeof(ansi_cp)/sizeof(WCHAR));
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_IDEFAULTCODEPAGE|LOCALE_RETURN_NUMBER|LOCALE_NOUSEROVERRIDE,
                   (WCHAR *)&oem_cp, sizeof(oem_cp)/sizeof(WCHAR));
    sprintf( cpbuf, "%u,%u", ansi_cp, oem_cp );

4060 4061
    /* Setup Default_Fallback usage for DBCS ANSI codepages */
    if (is_dbcs_ansi_cp(ansi_cp))
4062 4063
        use_default_fallback = TRUE;

4064
    buf[0] = 0;
4065
    len = sizeof(buf);
4066
    if (RegQueryValueExA(hkey, "Codepages", 0, &type, (BYTE *)buf, &len) == ERROR_SUCCESS && type == REG_SZ)
4067
    {
4068
        if (!strcmp( buf, cpbuf ) && screen_dpi == font_dpi)  /* already set correctly */
4069 4070 4071 4072
        {
            RegCloseKey(hkey);
            return;
        }
4073 4074
        TRACE("updating registry, codepages/logpixels changed %s/%u -> %u,%u/%u\n",
              buf, font_dpi, ansi_cp, oem_cp, screen_dpi);
4075
    }
4076 4077
    else TRACE("updating registry, codepages/logpixels changed none -> %u,%u/%u\n",
               ansi_cp, oem_cp, screen_dpi);
4078

4079
    RegSetValueExA(hkey, "Codepages", 0, REG_SZ, (const BYTE *)cpbuf, strlen(cpbuf)+1);
4080
    RegSetValueExW(hkey, logpixels, 0, REG_DWORD, (const BYTE *)&screen_dpi, sizeof(screen_dpi));
4081 4082
    RegCloseKey(hkey);

4083
    for (i = 0; i < ARRAY_SIZE(nls_update_font_list); i++)
4084
    {
4085 4086
        HKEY hkey;

4087 4088 4089 4090 4091
        if (nls_update_font_list[i].ansi_cp == ansi_cp &&
            nls_update_font_list[i].oem_cp == oem_cp)
        {
            hkey = create_config_fonts_registry_key();
            RegSetValueExA(hkey, "OEMFONT.FON", 0, REG_SZ, (const BYTE *)nls_update_font_list[i].oem, strlen(nls_update_font_list[i].oem)+1);
4092
            RegSetValueExA(hkey, "FIXEDFON.FON", 0, REG_SZ, (const BYTE *)nls_update_font_list[i].fixed, strlen(nls_update_font_list[i].fixed)+1);
4093 4094 4095 4096
            RegSetValueExA(hkey, "FONTS.FON", 0, REG_SZ, (const BYTE *)nls_update_font_list[i].system, strlen(nls_update_font_list[i].system)+1);
            RegCloseKey(hkey);

            hkey = create_fonts_NT_registry_key();
4097
            add_font_list(hkey, &nls_update_font_list[i], screen_dpi);
4098 4099 4100
            RegCloseKey(hkey);

            hkey = create_fonts_9x_registry_key();
4101
            add_font_list(hkey, &nls_update_font_list[i], screen_dpi);
4102 4103
            RegCloseKey(hkey);

4104 4105 4106 4107 4108 4109
            if (!RegCreateKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes", &hkey ))
            {
                RegSetValueExA(hkey, "MS Shell Dlg", 0, REG_SZ, (const BYTE *)nls_update_font_list[i].shelldlg,
                               strlen(nls_update_font_list[i].shelldlg)+1);
                RegSetValueExA(hkey, "Tms Rmn", 0, REG_SZ, (const BYTE *)nls_update_font_list[i].tmsrmn,
                               strlen(nls_update_font_list[i].tmsrmn)+1);
4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135

                set_value_key(hkey, "Fixedsys,0", nls_update_font_list[i].fixed_0);
                set_value_key(hkey, "System,0", nls_update_font_list[i].system_0);
                set_value_key(hkey, "Courier,0", nls_update_font_list[i].courier_0);
                set_value_key(hkey, "MS Serif,0", nls_update_font_list[i].serif_0);
                set_value_key(hkey, "Small Fonts,0", nls_update_font_list[i].small_0);
                set_value_key(hkey, "MS Sans Serif,0", nls_update_font_list[i].sserif_0);
                set_value_key(hkey, "Helv,0", nls_update_font_list[i].helv_0);
                set_value_key(hkey, "Tms Rmn,0", nls_update_font_list[i].tmsrmn_0);

                set_value_key(hkey, nls_update_font_list[i].arial_0.from, nls_update_font_list[i].arial_0.to);
                set_value_key(hkey, nls_update_font_list[i].courier_new_0.from, nls_update_font_list[i].courier_new_0.to);
                set_value_key(hkey, nls_update_font_list[i].times_new_roman_0.from, nls_update_font_list[i].times_new_roman_0.to);

                RegCloseKey(hkey);
            }
            done = TRUE;
        }
        else
        {
            /* Delete the FontSubstitutes from other locales */
            if (!RegCreateKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes", &hkey ))
            {
                set_value_key(hkey, nls_update_font_list[i].arial_0.from, NULL);
                set_value_key(hkey, nls_update_font_list[i].courier_new_0.from, NULL);
                set_value_key(hkey, nls_update_font_list[i].times_new_roman_0.from, NULL);
4136 4137
                RegCloseKey(hkey);
            }
4138 4139
        }
    }
4140 4141
    if (!done)
        FIXME("there is no font defaults for codepages %u,%u\n", ansi_cp, oem_cp);
4142

4143
    /* update locale dependent font association info and font system link info in registry.
4144 4145
       update only when codepages changed, not logpixels. */
    if (strcmp(buf, cpbuf) != 0)
4146
    {
4147
        update_font_association_info(ansi_cp);
4148 4149
        update_font_system_link_info(ansi_cp);
    }
4150 4151
}

4152 4153
static BOOL init_freetype(void)
{
4154
    ft_handle = wine_dlopen(SONAME_LIBFREETYPE, RTLD_NOW, NULL, 0);
4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
    if(!ft_handle) {
        WINE_MESSAGE(
      "Wine cannot find the FreeType font library.  To enable Wine to\n"
      "use TrueType fonts please install a version of FreeType greater than\n"
      "or equal to 2.0.5.\n"
      "http://www.freetype.org\n");
	return FALSE;
    }

#define LOAD_FUNCPTR(f) if((p##f = wine_dlsym(ft_handle, #f, NULL, 0)) == NULL){WARN("Can't find symbol %s\n", #f); goto sym_not_found;}

    LOAD_FUNCPTR(FT_Done_Face)
    LOAD_FUNCPTR(FT_Get_Char_Index)
4168 4169
    LOAD_FUNCPTR(FT_Get_First_Char)
    LOAD_FUNCPTR(FT_Get_Next_Char)
4170 4171
    LOAD_FUNCPTR(FT_Get_Sfnt_Name)
    LOAD_FUNCPTR(FT_Get_Sfnt_Name_Count)
4172
    LOAD_FUNCPTR(FT_Get_Sfnt_Table)
4173
    LOAD_FUNCPTR(FT_Get_WinFNT_Header)
4174
    LOAD_FUNCPTR(FT_Init_FreeType)
4175
    LOAD_FUNCPTR(FT_Library_Version)
4176
    LOAD_FUNCPTR(FT_Load_Glyph)
4177
    LOAD_FUNCPTR(FT_Load_Sfnt_Table)
4178
    LOAD_FUNCPTR(FT_Matrix_Multiply)
4179
#ifndef FT_MULFIX_INLINED
4180
    LOAD_FUNCPTR(FT_MulFix)
4181
#endif
4182
    LOAD_FUNCPTR(FT_New_Face)
4183
    LOAD_FUNCPTR(FT_New_Memory_Face)
4184
    LOAD_FUNCPTR(FT_Outline_Get_Bitmap)
4185
    LOAD_FUNCPTR(FT_Outline_Get_CBox)
4186 4187
    LOAD_FUNCPTR(FT_Outline_Transform)
    LOAD_FUNCPTR(FT_Outline_Translate)
4188
    LOAD_FUNCPTR(FT_Render_Glyph)
4189
    LOAD_FUNCPTR(FT_Set_Charmap)
4190
    LOAD_FUNCPTR(FT_Set_Pixel_Sizes)
4191
    LOAD_FUNCPTR(FT_Vector_Length)
4192
    LOAD_FUNCPTR(FT_Vector_Transform)
4193
    LOAD_FUNCPTR(FT_Vector_Unit)
4194
#undef LOAD_FUNCPTR
4195
    /* Don't warn if these ones are missing */
4196
    pFT_Outline_Embolden = wine_dlsym(ft_handle, "FT_Outline_Embolden", NULL, 0);
4197
    pFT_Get_TrueType_Engine_Type = wine_dlsym(ft_handle, "FT_Get_TrueType_Engine_Type", NULL, 0);
4198
#ifdef FT_LCD_FILTER_H
4199 4200
    pFT_Library_SetLcdFilter = wine_dlsym(ft_handle, "FT_Library_SetLcdFilter", NULL, 0);
#endif
4201
    pFT_Property_Set = wine_dlsym(ft_handle, "FT_Property_Set", NULL, 0);
4202

4203
    if(pFT_Init_FreeType(&library) != 0) {
4204
        ERR("Can't init FreeType library\n");
4205
	wine_dlclose(ft_handle, NULL, 0);
4206
        ft_handle = NULL;
4207 4208
	return FALSE;
    }
4209
    pFT_Library_Version(library,&FT_Version.major,&FT_Version.minor,&FT_Version.patch);
4210

4211
    TRACE("FreeType version is %d.%d.%d\n",FT_Version.major,FT_Version.minor,FT_Version.patch);
4212 4213 4214
    FT_SimpleVersion = ((FT_Version.major << 16) & 0xff0000) |
                       ((FT_Version.minor <<  8) & 0x00ff00) |
                       ((FT_Version.patch      ) & 0x0000ff);
4215

4216
    /* In FreeType < 2.8.1 v40's FT_LOAD_TARGET_MONO has broken advance widths. */
4217 4218 4219 4220 4221 4222
    if (pFT_Property_Set && FT_SimpleVersion < FT_VERSION_VALUE(2, 8, 1))
    {
        FT_UInt interpreter_version = 35;
        pFT_Property_Set( library, "truetype", "interpreter-version", &interpreter_version );
    }

4223
    font_driver = &freetype_funcs;
4224 4225 4226 4227 4228 4229
    return TRUE;

sym_not_found:
    WINE_MESSAGE(
      "Wine cannot find certain functions that it needs inside the FreeType\n"
      "font library.  To enable Wine to use TrueType fonts please upgrade\n"
4230
      "FreeType to at least version 2.1.4.\n"
4231 4232 4233 4234 4235 4236
      "http://www.freetype.org\n");
    wine_dlclose(ft_handle, NULL, 0);
    ft_handle = NULL;
    return FALSE;
}

4237
static void init_font_list(void)
4238 4239 4240 4241 4242 4243 4244 4245
{
    static const WCHAR dot_fonW[] = {'.','f','o','n','\0'};
    static const WCHAR pathW[] = {'P','a','t','h',0};
    HKEY hkey;
    DWORD valuelen, datalen, i = 0, type, dlen, vlen;
    WCHAR windowsdir[MAX_PATH];
    char *unixname;

4246 4247
    delete_external_font_keys();

4248
    /* load the system bitmap fonts */
4249 4250
    load_system_fonts();

4251
    /* load in the fonts from %WINDOWSDIR%\\Fonts first of all */
4252
    GetWindowsDirectoryW(windowsdir, ARRAY_SIZE(windowsdir));
4253
    strcatW(windowsdir, fontsW);
4254 4255
    if((unixname = wine_get_unix_file_name(windowsdir)))
    {
4256
        ReadFontDir(unixname, FALSE);
4257 4258
        HeapFree(GetProcessHeap(), 0, unixname);
    }
4259

4260 4261
    /* load the wine fonts */
    if ((unixname = get_font_dir()))
4262
    {
4263
        ReadFontDir(unixname, TRUE);
4264 4265 4266
        HeapFree(GetProcessHeap(), 0, unixname);
    }

4267
    /* now look under HKLM\Software\Microsoft\Windows[ NT]\CurrentVersion\Fonts
4268
       for any fonts not installed in %WINDOWSDIR%\Fonts.  They will have their
4269 4270
       full path as the entry.  Also look for any .fon fonts, since ReadFontDir
       will skip these. */
4271 4272
    if(RegOpenKeyW(HKEY_LOCAL_MACHINE,
                   is_win9x() ? win9x_font_reg_key : winnt_font_reg_key,
4273 4274
                   &hkey) == ERROR_SUCCESS)
    {
4275
        LPWSTR data, valueW;
4276
        RegQueryInfoKeyW(hkey, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
4277
                         &valuelen, &datalen, NULL, NULL);
4278

4279 4280 4281
        valuelen++; /* returned value doesn't include room for '\0' */
        valueW = HeapAlloc(GetProcessHeap(), 0, valuelen * sizeof(WCHAR));
        data = HeapAlloc(GetProcessHeap(), 0, datalen * sizeof(WCHAR));
4282 4283 4284 4285
        if (valueW && data)
        {
            dlen = datalen * sizeof(WCHAR);
            vlen = valuelen;
4286
            while(RegEnumValueW(hkey, i++, valueW, &vlen, NULL, &type, (LPBYTE)data,
4287 4288
                                &dlen) == ERROR_SUCCESS)
            {
4289
                if(data[0] && (data[1] == ':'))
4290
                {
4291
                    if((unixname = wine_get_unix_file_name(data)))
4292
                    {
4293
                        AddFontToList(unixname, NULL, 0, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_TO_CACHE);
4294 4295 4296
                        HeapFree(GetProcessHeap(), 0, unixname);
                    }
                }
4297
                else if(dlen / 2 >= 6 && !strcmpiW(data + dlen / 2 - 5, dot_fonW))
4298 4299 4300
                {
                    WCHAR pathW[MAX_PATH];
                    static const WCHAR fmtW[] = {'%','s','\\','%','s','\0'};
4301 4302
                    BOOL added = FALSE;

4303 4304 4305
                    sprintfW(pathW, fmtW, windowsdir, data);
                    if((unixname = wine_get_unix_file_name(pathW)))
                    {
4306
                        added = AddFontToList(unixname, NULL, 0, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_TO_CACHE);
4307 4308
                        HeapFree(GetProcessHeap(), 0, unixname);
                    }
4309 4310
                    if (!added)
                        load_font_from_data_dir(data);
4311
                }
4312 4313 4314 4315 4316
                /* reset dlen and vlen */
                dlen = datalen;
                vlen = valuelen;
            }
        }
4317 4318
        HeapFree(GetProcessHeap(), 0, data);
        HeapFree(GetProcessHeap(), 0, valueW);
4319
        RegCloseKey(hkey);
4320 4321
    }

4322
#ifdef SONAME_LIBFONTCONFIG
4323
    load_fontconfig_fonts();
4324 4325
#elif defined(HAVE_CARBON_CARBON_H)
    load_mac_fonts();
4326 4327
#elif defined(__ANDROID__)
    ReadFontDir("/system/fonts", TRUE);
4328
#endif
4329 4330

    /* then look in any directories that we've specified in the config file */
4331 4332 4333 4334 4335 4336
    /* @@ Wine registry key: HKCU\Software\Wine\Fonts */
    if(RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Wine\\Fonts", &hkey) == ERROR_SUCCESS)
    {
        DWORD len;
        LPWSTR valueW;
        LPSTR valueA, ptr;
4337

4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350
        if (RegQueryValueExW( hkey, pathW, NULL, NULL, NULL, &len ) == ERROR_SUCCESS)
        {
            len += sizeof(WCHAR);
            valueW = HeapAlloc( GetProcessHeap(), 0, len );
            if (RegQueryValueExW( hkey, pathW, NULL, NULL, (LPBYTE)valueW, &len ) == ERROR_SUCCESS)
            {
                len = WideCharToMultiByte( CP_UNIXCP, 0, valueW, -1, NULL, 0, NULL, NULL );
                valueA = HeapAlloc( GetProcessHeap(), 0, len );
                WideCharToMultiByte( CP_UNIXCP, 0, valueW, -1, valueA, len, NULL, NULL );
                TRACE( "got font path %s\n", debugstr_a(valueA) );
                ptr = valueA;
                while (ptr)
                {
4351
                    const char* home;
4352 4353
                    LPSTR next = strchr( ptr, ':' );
                    if (next) *next++ = 0;
4354 4355 4356 4357 4358 4359 4360 4361 4362 4363
                    if (ptr[0] == '~' && ptr[1] == '/' && (home = getenv( "HOME" )) &&
                        (unixname = HeapAlloc( GetProcessHeap(), 0, strlen(ptr) + strlen(home) )))
                    {
                        strcpy( unixname, home );
                        strcat( unixname, ptr + 1 );
                        ReadFontDir( unixname, TRUE );
                        HeapFree( GetProcessHeap(), 0, unixname );
                    }
                    else
                        ReadFontDir( ptr, TRUE );
4364 4365 4366 4367 4368 4369 4370
                    ptr = next;
                }
                HeapFree( GetProcessHeap(), 0, valueA );
            }
            HeapFree( GetProcessHeap(), 0, valueW );
        }
        RegCloseKey(hkey);
4371
    }
4372 4373
}

4374 4375 4376 4377 4378
static BOOL move_to_front(const WCHAR *name)
{
    Family *family, *cursor2;
    LIST_FOR_EACH_ENTRY_SAFE(family, cursor2, &font_list, Family, entry)
    {
4379
        if(!strncmpiW(family->FamilyName, name, LF_FACESIZE - 1))
4380 4381 4382 4383 4384 4385 4386 4387 4388
        {
            list_remove(&family->entry);
            list_add_head(&font_list, &family->entry);
            return TRUE;
        }
    }
    return FALSE;
}

4389
static const WCHAR *set_default(const WCHAR **name_list)
4390
{
4391 4392 4393
    const WCHAR **entry = name_list;

    while (*entry)
4394
    {
4395 4396
        if (move_to_front(*entry)) return *entry;
        entry++;
4397
    }
4398

4399
    return *name_list;
4400
}
4401

4402 4403
static void reorder_font_list(void)
{
4404 4405 4406
    default_serif = set_default( default_serif_list );
    default_fixed = set_default( default_fixed_list );
    default_sans = set_default( default_sans_list );
4407 4408
}

4409 4410 4411 4412 4413 4414 4415
/*************************************************************
 *    WineEngInit
 *
 * Initialize FreeType library and create a list of available faces
 */
BOOL WineEngInit(void)
{
4416
    HKEY hkey;
4417
    DWORD disposition;
4418 4419 4420 4421 4422 4423 4424
    HANDLE font_mutex;

    /* update locale dependent font info in registry */
    update_font_info();

    if(!init_freetype()) return FALSE;

4425 4426 4427 4428
#ifdef SONAME_LIBFONTCONFIG
    init_fontconfig();
#endif

4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445
    if (!RegOpenKeyExW(HKEY_CURRENT_USER, wine_fonts_key, 0, KEY_READ, &hkey))
    {
        static const WCHAR antialias_fake_bold_or_italic[] = { 'A','n','t','i','a','l','i','a','s','F','a','k','e',
                                                               'B','o','l','d','O','r','I','t','a','l','i','c',0 };
        static const WCHAR true_options[] = { 'y','Y','t','T','1',0 };
        DWORD type, size;
        WCHAR buffer[20];

        size = sizeof(buffer);
        if (!RegQueryValueExW(hkey, antialias_fake_bold_or_italic, NULL, &type, (BYTE*)buffer, &size) &&
            type == REG_SZ && size >= 1)
        {
            antialias_fakes = (strchrW(true_options, buffer[0]) != NULL);
        }
        RegCloseKey(hkey);
    }

4446 4447 4448 4449 4450 4451 4452
    if((font_mutex = CreateMutexW(NULL, FALSE, font_mutex_nameW)) == NULL)
    {
        ERR("Failed to create font mutex\n");
        return FALSE;
    }
    WaitForSingleObject(font_mutex, INFINITE);

4453 4454
    create_font_cache_key(&hkey_font_cache, &disposition);

4455 4456 4457 4458
    if(disposition == REG_CREATED_NEW_KEY)
        init_font_list();
    else
        load_font_list_from_cache(hkey_font_cache);
4459

4460 4461
    reorder_font_list();

4462
    DumpFontList();
4463 4464
    LoadSubstList();
    DumpSubstList();
4465
    LoadReplaceList();
4466 4467 4468

    if(disposition == REG_CREATED_NEW_KEY)
        update_reg_entries();
4469

4470 4471
    init_system_links();
    
4472
    ReleaseMutex(font_mutex);
4473 4474 4475
    return TRUE;
}

4476 4477 4478 4479 4480 4481 4482
/* Some fonts have large usWinDescent values, as a result of storing signed short
   in unsigned field. That's probably caused by sTypoDescent vs usWinDescent confusion in
   some font generation tools. */
static inline USHORT get_fixed_windescent(USHORT windescent)
{
    return abs((SHORT)windescent);
}
4483

4484
static LONG calc_ppem_for_height(FT_Face ft_face, LONG height)
4485 4486
{
    TT_OS2 *pOS2;
4487 4488
    TT_HoriHeader *pHori;

4489
    LONG ppem;
4490
    const LONG MAX_PPEM = (1 << 16) - 1;
4491

4492
    pOS2 = pFT_Get_Sfnt_Table(ft_face, ft_sfnt_os2);
4493
    pHori = pFT_Get_Sfnt_Table(ft_face, ft_sfnt_hhea);
4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510

    if(height == 0) height = 16;

    /* Calc. height of EM square:
     *
     * For +ve lfHeight we have
     * lfHeight = (winAscent + winDescent) * ppem / units_per_em
     * Re-arranging gives:
     * ppem = units_per_em * lfheight / (winAscent + winDescent)
     *
     * For -ve lfHeight we have
     * |lfHeight| = ppem
     * [i.e. |lfHeight| = (winAscent + winDescent - il) * ppem / units_per_em
     * with il = winAscent + winDescent - units_per_em]
     *
     */

4511
    if(height > 0) {
4512 4513
        USHORT windescent = get_fixed_windescent(pOS2->usWinDescent);
        if(pOS2->usWinAscent + windescent == 0)
4514 4515
            ppem = MulDiv(ft_face->units_per_EM, height,
                          pHori->Ascender - pHori->Descender);
4516
        else
4517
            ppem = MulDiv(ft_face->units_per_EM, height,
4518
                          pOS2->usWinAscent + windescent);
4519 4520 4521 4522
        if(ppem > MAX_PPEM) {
            WARN("Ignoring too large height %d, ppem %d\n", height, ppem);
            ppem = 1;
        }
4523
    }
4524
    else if(height >= -MAX_PPEM)
4525
        ppem = -height;
4526 4527 4528 4529
    else {
        WARN("Ignoring too large height %d\n", height);
        ppem = 1;
    }
4530

4531 4532 4533
    return ppem;
}

4534
static struct font_mapping *map_font_file( const char *name )
4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574
{
    struct font_mapping *mapping;
    struct stat st;
    int fd;

    if ((fd = open( name, O_RDONLY )) == -1) return NULL;
    if (fstat( fd, &st ) == -1) goto error;

    LIST_FOR_EACH_ENTRY( mapping, &mappings_list, struct font_mapping, entry )
    {
        if (mapping->dev == st.st_dev && mapping->ino == st.st_ino)
        {
            mapping->refcount++;
            close( fd );
            return mapping;
        }
    }
    if (!(mapping = HeapAlloc( GetProcessHeap(), 0, sizeof(*mapping) )))
        goto error;

    mapping->data = mmap( NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0 );
    close( fd );

    if (mapping->data == MAP_FAILED)
    {
        HeapFree( GetProcessHeap(), 0, mapping );
        return NULL;
    }
    mapping->refcount = 1;
    mapping->dev = st.st_dev;
    mapping->ino = st.st_ino;
    mapping->size = st.st_size;
    list_add_tail( &mappings_list, &mapping->entry );
    return mapping;

error:
    close( fd );
    return NULL;
}

4575
static void unmap_font_file( struct font_mapping *mapping )
4576 4577 4578 4579 4580 4581 4582 4583 4584
{
    if (!--mapping->refcount)
    {
        list_remove( &mapping->entry );
        munmap( mapping->data, mapping->size );
        HeapFree( GetProcessHeap(), 0, mapping );
    }
}

4585
static LONG load_VDMX(GdiFont*, LONG);
4586

4587
static FT_Face OpenFontFace(GdiFont *font, Face *face, LONG width, LONG height)
4588 4589 4590
{
    FT_Error err;
    FT_Face ft_face;
4591 4592
    void *data_ptr;
    DWORD data_size;
4593

4594
    TRACE("%s/%p, %ld, %d x %d\n", debugstr_w(face->file), face->font_data_ptr, face->face_index, width, height);
4595

4596
    if (face->file)
4597
    {
4598 4599 4600 4601
        char *filename = strWtoA( CP_UNIXCP, face->file );
        font->mapping = map_font_file( filename );
        HeapFree( GetProcessHeap(), 0, filename );
        if (!font->mapping)
4602
        {
4603
            WARN("failed to map %s\n", debugstr_w(face->file));
4604 4605 4606 4607 4608 4609 4610 4611 4612
            return 0;
        }
        data_ptr = font->mapping->data;
        data_size = font->mapping->size;
    }
    else
    {
        data_ptr = face->font_data_ptr;
        data_size = face->font_data_size;
4613
    }
4614

4615
    err = pFT_New_Memory_Face(library, data_ptr, data_size, face->face_index, &ft_face);
4616 4617 4618 4619 4620 4621 4622 4623
    if(err) {
        ERR("FT_New_Face rets %d\n", err);
	return 0;
    }

    /* set it here, as load_VDMX needs it */
    font->ft_face = ft_face;

4624
    if(FT_IS_SCALABLE(ft_face)) {
4625 4626 4627
        FT_ULong len;
        DWORD header;

4628
        /* load the VDMX table if we have one */
4629 4630 4631
        font->ppem = load_VDMX(font, height);
        if(font->ppem == 0)
            font->ppem = calc_ppem_for_height(ft_face, height);
4632
        TRACE("height %d => ppem %d\n", height, font->ppem);
4633

4634
        if((err = pFT_Set_Pixel_Sizes(ft_face, 0, font->ppem)) != 0)
4635
            WARN("FT_Set_Pixel_Sizes %d, %d rets %x\n", 0, font->ppem, err);
4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649

        /* see if it's a TTC */
        len = sizeof(header);
        if (!pFT_Load_Sfnt_Table(ft_face, 0, 0, (void*)&header, &len)) {
            if (header == MS_TTCF_TAG)
            {
                len = sizeof(font->ttc_item_offset);
                if (pFT_Load_Sfnt_Table(ft_face, 0, (3 + face->face_index) * sizeof(DWORD),
                        (void*)&font->ttc_item_offset, &len))
                    font->ttc_item_offset = 0;
                else
                    font->ttc_item_offset = GET_BE_DWORD(font->ttc_item_offset);
            }
        }
4650
    } else {
4651
        font->ppem = height;
4652
        if((err = pFT_Set_Pixel_Sizes(ft_face, width, height)) != 0)
4653
            WARN("FT_Set_Pixel_Sizes %d, %d rets %x\n", width, height, err);
4654
    }
4655 4656 4657
    return ft_face;
}

4658

4659
static int get_nearest_charset(const WCHAR *family_name, Face *face, int *cp)
4660 4661 4662 4663 4664
{
  /* Only get here if lfCharSet == DEFAULT_CHARSET or we couldn't find
     a single face with the requested charset.  The idea is to check if
     the selected font supports the current ANSI codepage, if it does
     return the corresponding charset, else return the first charset */
4665

4666 4667 4668 4669
    CHARSETINFO csi;
    int acp = GetACP(), i;
    DWORD fs0;

4670
    *cp = acp;
4671
    if(TranslateCharsetInfo((DWORD*)(INT_PTR)acp, &csi, TCI_SRCCODEPAGE))
4672 4673 4674 4675
    {
        const SYSTEM_LINKS *font_link;

        if (csi.fs.fsCsb[0] & face->fs.fsCsb[0])
4676 4677
	    return csi.ciCharset;

4678 4679 4680 4681 4682
        font_link = find_font_link(family_name);
        if (font_link != NULL && csi.fs.fsCsb[0] & font_link->fs.fsCsb[0])
	    return csi.ciCharset;
    }

4683 4684
    for(i = 0; i < 32; i++) {
        fs0 = 1L << i;
4685
        if(face->fs.fsCsb[0] & fs0) {
4686 4687
	    if(TranslateCharsetInfo(&fs0, &csi, TCI_SRCFONTSIG)) {
                *cp = csi.ciACP;
4688
	        return csi.ciCharset;
4689
            }
4690
	    else
4691
                FIXME("TCI failing on %x\n", fs0);
4692 4693
	}
    }
4694

4695
    FIXME("returning DEFAULT_CHARSET face->fs.fsCsb[0] = %08x file = %s\n",
4696
	  face->fs.fsCsb[0], debugstr_w(face->file));
4697
    *cp = acp;
4698 4699 4700
    return DEFAULT_CHARSET;
}

4701
static GdiFont *alloc_font(void)
4702
{
4703
    GdiFont *ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
4704
    ret->refcount = 1;
4705 4706 4707
    ret->gmsize = 1;
    ret->gm = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(GM*));
    ret->gm[0] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(GM) * GM_BLOCK_SIZE);
4708
    ret->potm = NULL;
4709
    ret->font_desc.matrix.eM11 = ret->font_desc.matrix.eM22 = 1.0;
4710 4711
    ret->total_kern_pairs = (DWORD)-1;
    ret->kern_pairs = NULL;
4712
    ret->instance_id = alloc_font_handle(ret);
4713
    list_init(&ret->child_fonts);
4714 4715 4716
    return ret;
}

4717
static void free_font(GdiFont *font)
4718
{
4719
    CHILD_FONT *child, *child_next;
4720
    DWORD i;
4721

4722
    LIST_FOR_EACH_ENTRY_SAFE( child, child_next, &font->child_fonts, CHILD_FONT, entry )
4723
    {
4724
        list_remove(&child->entry);
4725 4726
        if(child->font)
            free_font(child->font);
4727
        release_face( child->face );
4728 4729 4730
        HeapFree(GetProcessHeap(), 0, child);
    }

4731
    HeapFree(GetProcessHeap(), 0, font->fileinfo);
4732
    free_font_handle(font->instance_id);
4733
    if (font->ft_face) pFT_Done_Face(font->ft_face);
4734
    if (font->mapping) unmap_font_file( font->mapping );
4735
    HeapFree(GetProcessHeap(), 0, font->kern_pairs);
4736 4737
    HeapFree(GetProcessHeap(), 0, font->potm);
    HeapFree(GetProcessHeap(), 0, font->name);
4738 4739
    for (i = 0; i < font->gmsize; i++)
        HeapFree(GetProcessHeap(),0,font->gm[i]);
4740
    HeapFree(GetProcessHeap(), 0, font->gm);
4741
    HeapFree(GetProcessHeap(), 0, font->GSUB_Table);
4742 4743 4744
    HeapFree(GetProcessHeap(), 0, font);
}

4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790
/* TODO: GGO format support */
static BOOL get_cached_metrics( GdiFont *font, UINT index, GLYPHMETRICS *gm, ABC *abc )
{
    UINT block = index / GM_BLOCK_SIZE;
    UINT entry = index % GM_BLOCK_SIZE;

    if (block < font->gmsize && font->gm[block] && font->gm[block][entry].init)
    {
        *gm  = font->gm[block][entry].gm;
        *abc = font->gm[block][entry].abc;

        TRACE( "cached gm: %u, %u, %s, %d, %d abc: %d, %u, %d\n",
               gm->gmBlackBoxX, gm->gmBlackBoxY, wine_dbgstr_point( &gm->gmptGlyphOrigin ),
               gm->gmCellIncX, gm->gmCellIncY, abc->abcA, abc->abcB, abc->abcC );
        return TRUE;
    }

    return FALSE;
}

static void set_cached_metrics( GdiFont *font, UINT index, const GLYPHMETRICS *gm, const ABC *abc )
{
    UINT block = index / GM_BLOCK_SIZE;
    UINT entry = index % GM_BLOCK_SIZE;

    if (block >= font->gmsize)
    {
        GM **ptr = HeapReAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
                                font->gm, (block + 1) * sizeof(GM *) );
        if (!ptr) return;

        font->gmsize = block + 1;
        font->gm = ptr;
    }

    if (!font->gm[block])
    {
        font->gm[block] = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
                                     sizeof(GM) * GM_BLOCK_SIZE );
        if (!font->gm[block]) return;
    }

    font->gm[block][entry].gm   = *gm;
    font->gm[block][entry].abc  = *abc;
    font->gm[block][entry].init = TRUE;
}
4791

4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804
static DWORD get_font_data( GdiFont *font, DWORD table, DWORD offset, LPVOID buf, DWORD cbData)
{
    FT_Face ft_face = font->ft_face;
    FT_ULong len;
    FT_Error err;

    if (!FT_IS_SFNT(ft_face)) return GDI_ERROR;

    if(!buf)
        len = 0;
    else
        len = cbData;

4805 4806 4807 4808 4809 4810 4811 4812 4813 4814
    /* if font is a member of TTC, 'ttcf' tag allows reading from beginning of TTC file,
       0 tag means to read from start of collection member data. */
    if (font->ttc_item_offset)
    {
        if (table == MS_TTCF_TAG)
            table = 0;
        else if (table == 0)
            offset += font->ttc_item_offset;
    }

4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826
    table = RtlUlongByteSwap( table );  /* MS tags differ in endianness from FT ones */

    /* make sure value of len is the value freetype says it needs */
    if (buf && len)
    {
        FT_ULong needed = 0;
        err = pFT_Load_Sfnt_Table(ft_face, table, offset, NULL, &needed);
        if( !err && needed < len) len = needed;
    }
    err = pFT_Load_Sfnt_Table(ft_face, table, offset, buf, &len);
    if (err)
    {
4827 4828
        table = RtlUlongByteSwap( table );
        TRACE("Can't find table %s\n", debugstr_an((char*)&table, 4));
4829 4830 4831 4832 4833
	return GDI_ERROR;
    }
    return len;
}

4834 4835 4836 4837 4838 4839 4840 4841
/*************************************************************
 * load_VDMX
 *
 * load the vdmx entry for the specified height
 */



4842 4843 4844 4845 4846 4847
typedef struct {
    WORD version;
    WORD numRecs;
    WORD numRatios;
} VDMX_Header;

4848 4849 4850 4851 4852 4853 4854
typedef struct {
    BYTE bCharSet;
    BYTE xRatio;
    BYTE yStartRatio;
    BYTE yEndRatio;
} Ratios;

4855 4856 4857 4858 4859
typedef struct {
    WORD recs;
    BYTE startsz;
    BYTE endsz;
} VDMX_group;
4860

4861 4862 4863 4864 4865 4866
typedef struct {
    WORD yPelHeight;
    WORD yMax;
    WORD yMin;
} VDMX_vTable;

4867
static LONG load_VDMX(GdiFont *font, LONG height)
4868
{
4869
    VDMX_Header hdr;
4870
    VDMX_group group;
4871 4872
    BYTE devXRatio, devYRatio;
    USHORT numRecs, numRatios;
4873
    DWORD result, offset = -1;
4874
    LONG ppem = 0;
4875
    int i;
4876

4877
    result = get_font_data(font, MS_VDMX_TAG, 0, &hdr, sizeof(hdr));
4878 4879 4880 4881 4882 4883 4884 4885

    if(result == GDI_ERROR) /* no vdmx table present, use linear scaling */
	return ppem;

    /* FIXME: need the real device aspect ratio */
    devXRatio = 1;
    devYRatio = 1;

4886 4887
    numRecs = GET_BE_WORD(hdr.numRecs);
    numRatios = GET_BE_WORD(hdr.numRatios);
4888

4889
    TRACE("version = %d numRecs = %d numRatios = %d\n", GET_BE_WORD(hdr.version), numRecs, numRatios);
4890 4891
    for(i = 0; i < numRatios; i++) {
	Ratios ratio;
4892

4893
	offset = sizeof(hdr) + (i * sizeof(Ratios));
4894
	get_font_data(font, MS_VDMX_TAG, offset, &ratio, sizeof(Ratios));
4895 4896 4897 4898
	offset = -1;

	TRACE("Ratios[%d] %d  %d : %d -> %d\n", i, ratio.bCharSet, ratio.xRatio, ratio.yStartRatio, ratio.yEndRatio);

4899 4900
        if (!ratio.bCharSet) continue;

4901
	if((ratio.xRatio == 0 &&
4902 4903
	    ratio.yStartRatio == 0 &&
	    ratio.yEndRatio == 0) ||
4904
	   (devXRatio == ratio.xRatio &&
4905
	    devYRatio >= ratio.yStartRatio &&
4906
	    devYRatio <= ratio.yEndRatio))
4907
	    {
4908
		WORD group_offset;
4909

4910 4911 4912
		offset = sizeof(hdr) + numRatios * sizeof(ratio) + i * sizeof(group_offset);
		get_font_data(font, MS_VDMX_TAG, offset, &group_offset, sizeof(group_offset));
		offset = GET_BE_WORD(group_offset);
4913 4914 4915 4916
		break;
	    }
    }

4917
    if(offset == -1) return 0;
4918

4919
    if(get_font_data(font, MS_VDMX_TAG, offset, &group, sizeof(group)) != GDI_ERROR) {
4920 4921
	USHORT recs;
	BYTE startsz, endsz;
4922
	WORD *vTable;
4923

4924 4925 4926
	recs = GET_BE_WORD(group.recs);
	startsz = group.startsz;
	endsz = group.endsz;
4927 4928 4929

	TRACE("recs=%d  startsz=%d  endsz=%d\n", recs, startsz, endsz);

4930 4931
	vTable = HeapAlloc(GetProcessHeap(), 0, recs * sizeof(VDMX_vTable));
	result = get_font_data(font, MS_VDMX_TAG, offset + sizeof(group), vTable, recs * sizeof(VDMX_vTable));
4932 4933 4934 4935 4936 4937 4938
	if(result == GDI_ERROR) {
	    FIXME("Failed to retrieve vTable\n");
	    goto end;
	}

	if(height > 0) {
	    for(i = 0; i < recs; i++) {
4939 4940 4941
                SHORT yMax = GET_BE_WORD(vTable[(i * 3) + 1]);
                SHORT yMin = GET_BE_WORD(vTable[(i * 3) + 2]);
                ppem = GET_BE_WORD(vTable[i * 3]);
4942 4943 4944 4945

		if(yMax + -yMin == height) {
		    font->yMax = yMax;
		    font->yMin = yMin;
4946
                    TRACE("ppem %d found; height=%d  yMax=%d  yMin=%d\n", ppem, height, font->yMax, font->yMin);
4947 4948 4949 4950 4951 4952 4953
		    break;
		}
		if(yMax + -yMin > height) {
		    if(--i < 0) {
			ppem = 0;
			goto end; /* failed */
		    }
4954 4955
		    font->yMax = GET_BE_WORD(vTable[(i * 3) + 1]);
		    font->yMin = GET_BE_WORD(vTable[(i * 3) + 2]);
4956
                    ppem = GET_BE_WORD(vTable[i * 3]);
4957
                    TRACE("ppem %d found; height=%d  yMax=%d  yMin=%d\n", ppem, height, font->yMax, font->yMin);
4958 4959 4960 4961 4962
		    break;
		}
	    }
	    if(!font->yMax) {
		ppem = 0;
4963
		TRACE("ppem not found for height %d\n", height);
4964
	    }
4965 4966 4967
	} else {
	    ppem = -height;
	    if(ppem < startsz || ppem > endsz)
4968 4969 4970 4971
            {
                ppem = 0;
                goto end;
            }
4972 4973 4974 4975 4976 4977

	    for(i = 0; i < recs; i++) {
		USHORT yPelHeight;
		yPelHeight = GET_BE_WORD(vTable[i * 3]);

		if(yPelHeight > ppem)
4978 4979 4980 4981
                {
                    ppem = 0;
                    break; /* failed */
                }
4982 4983 4984 4985 4986 4987 4988 4989

		if(yPelHeight == ppem) {
		    font->yMax = GET_BE_WORD(vTable[(i * 3) + 1]);
		    font->yMin = GET_BE_WORD(vTable[(i * 3) + 2]);
                    TRACE("ppem %d found; yMax=%d  yMin=%d\n", ppem, font->yMax, font->yMin);
		    break;
		}
	    }
4990 4991 4992 4993 4994 4995 4996 4997
	}
	end:
	HeapFree(GetProcessHeap(), 0, vTable);
    }

    return ppem;
}

4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039
static void dump_gdi_font_list(void)
{
    GdiFont *font;

    TRACE("---------- Font Cache ----------\n");
    LIST_FOR_EACH_ENTRY( font, &gdi_font_list, struct tagGdiFont, entry )
        TRACE("font=%p ref=%u %s %d\n", font, font->refcount,
              debugstr_w(font->font_desc.lf.lfFaceName), font->font_desc.lf.lfHeight);
}

static void grab_font( GdiFont *font )
{
    if (!font->refcount++)
    {
        list_remove( &font->unused_entry );
        unused_font_count--;
    }
}

static void release_font( GdiFont *font )
{
    if (!font) return;
    if (!--font->refcount)
    {
        TRACE( "font %p\n", font );

        /* add it to the unused list */
        list_add_head( &unused_gdi_font_list, &font->unused_entry );
        if (unused_font_count > UNUSED_CACHE_SIZE)
        {
            font = LIST_ENTRY( list_tail( &unused_gdi_font_list ), struct tagGdiFont, unused_entry );
            TRACE( "freeing %p\n", font );
            list_remove( &font->entry );
            list_remove( &font->unused_entry );
            free_font( font );
        }
        else unused_font_count++;

        if (TRACE_ON(font)) dump_gdi_font_list();
    }
}

5040
static BOOL fontcmp(const GdiFont *font, FONT_DESC *fd)
5041 5042 5043 5044
{
    if(font->font_desc.hash != fd->hash) return TRUE;
    if(memcmp(&font->font_desc.matrix, &fd->matrix, sizeof(fd->matrix))) return TRUE;
    if(memcmp(&font->font_desc.lf, &fd->lf, offsetof(LOGFONTW, lfFaceName))) return TRUE;
5045
    if(!font->font_desc.can_use_bitmap != !fd->can_use_bitmap) return TRUE;
5046 5047 5048 5049 5050 5051 5052
    return strcmpiW(font->font_desc.lf.lfFaceName, fd->lf.lfFaceName);
}

static void calc_hash(FONT_DESC *pfd)
{
    DWORD hash = 0, *ptr, two_chars;
    WORD *pwc;
5053
    unsigned int i;
5054 5055 5056 5057 5058

    for(i = 0, ptr = (DWORD*)&pfd->matrix; i < sizeof(FMAT2)/sizeof(DWORD); i++, ptr++)
        hash ^= *ptr;
    for(i = 0, ptr = (DWORD*)&pfd->lf; i < 7; i++, ptr++)
        hash ^= *ptr;
5059
    for(i = 0, ptr = (DWORD*)pfd->lf.lfFaceName; i < LF_FACESIZE/2; i++, ptr++) {
5060 5061 5062 5063 5064 5065 5066 5067 5068
        two_chars = *ptr;
        pwc = (WCHAR *)&two_chars;
        if(!*pwc) break;
        *pwc = toupperW(*pwc);
        pwc++;
        *pwc = toupperW(*pwc);
        hash ^= two_chars;
        if(!*pwc) break;
    }
5069
    hash ^= !pfd->can_use_bitmap;
5070 5071 5072
    pfd->hash = hash;
}

5073
static GdiFont *find_in_cache(HFONT hfont, const LOGFONTW *plf, const FMAT2 *pmat, BOOL can_use_bitmap)
5074
{
5075
    GdiFont *ret;
5076 5077
    FONT_DESC fd;

5078
    fd.lf = *plf;
5079
    fd.matrix = *pmat;
5080
    fd.can_use_bitmap = can_use_bitmap;
5081 5082 5083
    calc_hash(&fd);

    /* try the in-use list */
5084 5085 5086 5087
    LIST_FOR_EACH_ENTRY( ret, &gdi_font_list, struct tagGdiFont, entry )
    {
        if(fontcmp(ret, &fd)) continue;
        if(!can_use_bitmap && !FT_IS_SCALABLE(ret->ft_face)) continue;
5088 5089 5090
        list_remove( &ret->entry );
        list_add_head( &gdi_font_list, &ret->entry );
        grab_font( ret );
5091
        return ret;
5092 5093 5094
    }
    return NULL;
}
5095

5096 5097 5098 5099 5100 5101
static void add_to_cache(GdiFont *font)
{
    static DWORD cache_num = 1;

    font->cache_num = cache_num++;
    list_add_head(&gdi_font_list, &font->entry);
5102
    TRACE( "font %p\n", font );
5103 5104
}

5105 5106 5107
/*************************************************************
 * create_child_font_list
 */
5108
static BOOL create_child_font_list(GdiFont *font)
5109 5110 5111 5112
{
    BOOL ret = FALSE;
    SYSTEM_LINKS *font_link;
    CHILD_FONT *font_link_entry, *new_child;
5113 5114
    FontSubst *psub;
    WCHAR* font_name;
5115

5116 5117
    psub = get_font_subst(&font_subst_list, font->name, -1);
    font_name = psub ? psub->to.name : font->name;
5118 5119
    font_link = find_font_link(font_name);
    if (font_link != NULL)
5120
    {
5121 5122
        TRACE("found entry in system list\n");
        LIST_FOR_EACH_ENTRY(font_link_entry, &font_link->links, CHILD_FONT, entry)
5123
        {
5124 5125 5126
            new_child = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_child));
            new_child->face = font_link_entry->face;
            new_child->font = NULL;
5127
            new_child->face->refcount++;
5128
            list_add_tail(&font->child_fonts, &new_child->entry);
5129
            TRACE("font %s %ld\n", debugstr_w(new_child->face->file), new_child->face->face_index);
5130
        }
5131
        ret = TRUE;
5132
    }
5133 5134 5135 5136 5137 5138
    /*
     * if not SYMBOL or OEM then we also get all the fonts for Microsoft
     * Sans Serif.  This is how asian windows get default fallbacks for fonts
     */
    if (use_default_fallback && font->charset != SYMBOL_CHARSET &&
        font->charset != OEM_CHARSET &&
5139
        strcmpiW(font_name,szDefaultFallbackLink) != 0)
5140 5141 5142
    {
        font_link = find_font_link(szDefaultFallbackLink);
        if (font_link != NULL)
5143
        {
5144 5145
            TRACE("found entry in default fallback list\n");
            LIST_FOR_EACH_ENTRY(font_link_entry, &font_link->links, CHILD_FONT, entry)
5146
            {
5147 5148 5149
                new_child = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_child));
                new_child->face = font_link_entry->face;
                new_child->font = NULL;
5150
                new_child->face->refcount++;
5151
                list_add_tail(&font->child_fonts, &new_child->entry);
5152
                TRACE("font %s %ld\n", debugstr_w(new_child->face->file), new_child->face->face_index);
5153
            }
5154
            ret = TRUE;
5155
        }
5156
    }
5157 5158 5159 5160

    return ret;
}

5161 5162 5163
static BOOL select_charmap(FT_Face ft_face, FT_Encoding encoding)
{
    FT_Error ft_err = FT_Err_Invalid_CharMap_Handle;
5164 5165
    FT_CharMap cmap0, cmap1, cmap2, cmap3, cmap_def;
    FT_Int i;
5166

5167
    cmap0 = cmap1 = cmap2 = cmap3 = cmap_def = NULL;
5168

5169 5170 5171
    for (i = 0; i < ft_face->num_charmaps; i++)
    {
        if (ft_face->charmaps[i]->encoding == encoding)
5172
        {
5173 5174
            TRACE("found cmap with platform_id %u, encoding_id %u\n",
                   ft_face->charmaps[i]->platform_id, ft_face->charmaps[i]->encoding_id);
5175

5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
            switch (ft_face->charmaps[i]->platform_id)
            {
                default:
                    cmap_def = ft_face->charmaps[i];
                    break;
                case 0: /* Apple Unicode */
                    cmap0 = ft_face->charmaps[i];
                    break;
                case 1: /* Macintosh */
                    cmap1 = ft_face->charmaps[i];
                    break;
                case 2: /* ISO */
                    cmap2 = ft_face->charmaps[i];
                    break;
                case 3: /* Microsoft */
                    cmap3 = ft_face->charmaps[i];
                    break;
5193 5194
            }
        }
5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205

        if (cmap3) /* prefer Microsoft cmap table */
            ft_err = pFT_Set_Charmap(ft_face, cmap3);
        else if (cmap1)
            ft_err = pFT_Set_Charmap(ft_face, cmap1);
        else if (cmap2)
            ft_err = pFT_Set_Charmap(ft_face, cmap2);
        else if (cmap0)
            ft_err = pFT_Set_Charmap(ft_face, cmap0);
        else if (cmap_def)
            ft_err = pFT_Set_Charmap(ft_face, cmap_def);
5206 5207
    }

5208
    return ft_err == FT_Err_Ok;
5209 5210
}

5211 5212 5213 5214

/*************************************************************
 * freetype_CreateDC
 */
5215 5216
static BOOL CDECL freetype_CreateDC( PHYSDEV *dev, LPCWSTR driver, LPCWSTR device,
                                     LPCWSTR output, const DEVMODEW *devmode )
5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228
{
    struct freetype_physdev *physdev = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*physdev) );

    if (!physdev) return FALSE;
    push_dc_driver( dev, &physdev->dev, &freetype_funcs );
    return TRUE;
}


/*************************************************************
 * freetype_DeleteDC
 */
5229
static BOOL CDECL freetype_DeleteDC( PHYSDEV dev )
5230 5231
{
    struct freetype_physdev *physdev = get_freetype_dev( dev );
5232
    release_font( physdev->font );
5233 5234 5235 5236
    HeapFree( GetProcessHeap(), 0, physdev );
    return TRUE;
}

5237 5238
static FT_Encoding pick_charmap( FT_Face face, int charset )
{
5239
    static const FT_Encoding regular_order[] = { FT_ENCODING_UNICODE, FT_ENCODING_APPLE_ROMAN, FT_ENCODING_MS_SYMBOL, 0 };
5240 5241 5242 5243 5244 5245 5246 5247 5248 5249
    static const FT_Encoding symbol_order[]  = { FT_ENCODING_MS_SYMBOL, FT_ENCODING_UNICODE, FT_ENCODING_APPLE_ROMAN, 0 };
    const FT_Encoding *encs = regular_order;

    if (charset == SYMBOL_CHARSET) encs = symbol_order;

    while (*encs != 0)
    {
        if (select_charmap( face, *encs )) break;
        encs++;
    }
5250 5251 5252 5253 5254 5255 5256

    if (!face->charmap && face->num_charmaps)
    {
        if (!pFT_Set_Charmap(face, face->charmaps[0]))
            return face->charmap->encoding;
    }

5257 5258
    return *encs;
}
5259

5260 5261 5262 5263 5264 5265 5266 5267 5268
static BOOL get_gasp_flags( GdiFont *font, WORD *flags )
{
    DWORD size;
    WORD buf[16]; /* Enough for seven ranges before we need to alloc */
    WORD *alloced = NULL, *ptr = buf;
    WORD num_recs, version;
    BOOL ret = FALSE;

    *flags = 0;
5269
    size = get_font_data( font, MS_GASP_TAG,  0, NULL, 0 );
5270 5271 5272 5273 5274 5275 5276 5277
    if (size == GDI_ERROR) return FALSE;
    if (size < 4 * sizeof(WORD)) return FALSE;
    if (size > sizeof(buf))
    {
        ptr = alloced = HeapAlloc( GetProcessHeap(), 0, size );
        if (!ptr) return FALSE;
    }

5278
    get_font_data( font, MS_GASP_TAG, 0, ptr, size );
5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302

    version  = GET_BE_WORD( *ptr++ );
    num_recs = GET_BE_WORD( *ptr++ );

    if (version > 1 || size < (num_recs * 2 + 2) * sizeof(WORD))
    {
        FIXME( "Unsupported gasp table: ver %d size %d recs %d\n", version, size, num_recs );
        goto done;
    }

    while (num_recs--)
    {
        *flags = GET_BE_WORD( *(ptr + 1) );
        if (font->ft_face->size->metrics.y_ppem <= GET_BE_WORD( *ptr )) break;
        ptr += 2;
    }
    TRACE( "got flags %04x for ppem %d\n", *flags, font->ft_face->size->metrics.y_ppem );
    ret = TRUE;

done:
    HeapFree( GetProcessHeap(), 0, alloced );
    return ret;
}

5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372
#ifdef SONAME_LIBFONTCONFIG
static Family* get_fontconfig_family(DWORD pitch_and_family, const CHARSETINFO *csi)
{
    const char *name;
    WCHAR nameW[LF_FACESIZE];
    FcChar8 *str;
    FcPattern *pat = NULL, *best = NULL;
    FcResult result;
    FcBool r;
    int ret, i;
    Family *family = NULL;

    if (!csi->fs.fsCsb[0]) return NULL;

    if((pitch_and_family & FIXED_PITCH) ||
       (pitch_and_family & 0xF0) == FF_MODERN)
        name = "monospace";
    else if((pitch_and_family & 0xF0) == FF_ROMAN)
        name = "serif";
    else
        name = "sans-serif";

    pat = pFcPatternCreate();
    if (!pat) return NULL;
    r = pFcPatternAddString(pat, FC_FAMILY, (const FcChar8 *)name);
    if (!r) goto end;
    r = pFcPatternAddString(pat, FC_NAMELANG, (const FcChar8 *)"en-us");
    if (!r) goto end;
    r = pFcPatternAddString(pat, FC_PRGNAME, (const FcChar8 *)"wine");
    if (!r) goto end;
    r = pFcConfigSubstitute(NULL, pat, FcMatchPattern);
    if (!r) goto end;
    pFcDefaultSubstitute(pat);

    best = pFcFontMatch(NULL, pat, &result);
    if (!best || result != FcResultMatch) goto end;

    for (i = 0;
         !family && pFcPatternGetString(best, FC_FAMILY, i, &str) == FcResultMatch;
         i++)
    {
        Face *face;
        const SYSTEM_LINKS *font_link;
        const struct list *face_list;

        ret = MultiByteToWideChar(CP_UTF8, 0, (const char*)str, -1,
                                  nameW, ARRAY_SIZE(nameW));
        if (!ret) continue;
        family = find_family_from_any_name(nameW);
        if (!family) continue;

        font_link = find_font_link(family->FamilyName);
        face_list = get_face_list_from_family(family);
        LIST_FOR_EACH_ENTRY( face, face_list, Face, entry ) {
            if (!face->scalable)
                continue;
            if (csi->fs.fsCsb[0] & face->fs.fsCsb[0])
                goto found;
            if (font_link != NULL &&
                csi->fs.fsCsb[0] & font_link->fs.fsCsb[0])
                goto found;
        }
        family = NULL;
    }

found:
    if (family)
        TRACE("got %s\n", wine_dbgstr_w(nameW));

end:
5373 5374
    pFcPatternDestroy(pat);
    pFcPatternDestroy(best);
5375 5376 5377 5378
    return family;
}
#endif

5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509
static const GSUB_Script* GSUB_get_script_table( const GSUB_Header* header, const char* tag)
{
    const GSUB_ScriptList *script;
    const GSUB_Script *deflt = NULL;
    int i;
    script = (const GSUB_ScriptList*)((const BYTE*)header + GET_BE_WORD(header->ScriptList));

    TRACE("%i scripts in this font\n",GET_BE_WORD(script->ScriptCount));
    for (i = 0; i < GET_BE_WORD(script->ScriptCount); i++)
    {
        const GSUB_Script *scr;
        int offset;

        offset = GET_BE_WORD(script->ScriptRecord[i].Script);
        scr = (const GSUB_Script*)((const BYTE*)script + offset);

        if (strncmp(script->ScriptRecord[i].ScriptTag, tag,4)==0)
            return scr;
        if (strncmp(script->ScriptRecord[i].ScriptTag, "dflt",4)==0)
            deflt = scr;
    }
    return deflt;
}

static const GSUB_LangSys* GSUB_get_lang_table( const GSUB_Script* script, const char* tag)
{
    int i;
    int offset;
    const GSUB_LangSys *Lang;

    TRACE("Deflang %x, LangCount %i\n",GET_BE_WORD(script->DefaultLangSys), GET_BE_WORD(script->LangSysCount));

    for (i = 0; i < GET_BE_WORD(script->LangSysCount) ; i++)
    {
        offset = GET_BE_WORD(script->LangSysRecord[i].LangSys);
        Lang = (const GSUB_LangSys*)((const BYTE*)script + offset);

        if ( strncmp(script->LangSysRecord[i].LangSysTag,tag,4)==0)
            return Lang;
    }
    offset = GET_BE_WORD(script->DefaultLangSys);
    if (offset)
    {
        Lang = (const GSUB_LangSys*)((const BYTE*)script + offset);
        return Lang;
    }
    return NULL;
}

static const GSUB_Feature * GSUB_get_feature(const GSUB_Header *header, const GSUB_LangSys *lang, const char* tag)
{
    int i;
    const GSUB_FeatureList *feature;
    feature = (const GSUB_FeatureList*)((const BYTE*)header + GET_BE_WORD(header->FeatureList));

    TRACE("%i features\n",GET_BE_WORD(lang->FeatureCount));
    for (i = 0; i < GET_BE_WORD(lang->FeatureCount); i++)
    {
        int index = GET_BE_WORD(lang->FeatureIndex[i]);
        if (strncmp(feature->FeatureRecord[index].FeatureTag,tag,4)==0)
        {
            const GSUB_Feature *feat;
            feat = (const GSUB_Feature*)((const BYTE*)feature + GET_BE_WORD(feature->FeatureRecord[index].Feature));
            return feat;
        }
    }
    return NULL;
}

static const char* get_opentype_script(const GdiFont *font)
{
    /*
     * I am not sure if this is the correct way to generate our script tag
     */

    switch (font->charset)
    {
        case ANSI_CHARSET: return "latn";
        case BALTIC_CHARSET: return "latn"; /* ?? */
        case CHINESEBIG5_CHARSET: return "hani";
        case EASTEUROPE_CHARSET: return "latn"; /* ?? */
        case GB2312_CHARSET: return "hani";
        case GREEK_CHARSET: return "grek";
        case HANGUL_CHARSET: return "hang";
        case RUSSIAN_CHARSET: return "cyrl";
        case SHIFTJIS_CHARSET: return "kana";
        case TURKISH_CHARSET: return "latn"; /* ?? */
        case VIETNAMESE_CHARSET: return "latn";
        case JOHAB_CHARSET: return "latn"; /* ?? */
        case ARABIC_CHARSET: return "arab";
        case HEBREW_CHARSET: return "hebr";
        case THAI_CHARSET: return "thai";
        default: return "latn";
    }
}

static const VOID * get_GSUB_vert_feature(const GdiFont *font)
{
    const GSUB_Header *header;
    const GSUB_Script *script;
    const GSUB_LangSys *language;
    const GSUB_Feature *feature;

    if (!font->GSUB_Table)
        return NULL;

    header = font->GSUB_Table;

    script = GSUB_get_script_table(header, get_opentype_script(font));
    if (!script)
    {
        TRACE("Script not found\n");
        return NULL;
    }
    language = GSUB_get_lang_table(script, "xxxx"); /* Need to get Lang tag */
    if (!language)
    {
        TRACE("Language not found\n");
        return NULL;
    }
    feature  =  GSUB_get_feature(header, language, "vrt2");
    if (!feature)
        feature  =  GSUB_get_feature(header, language, "vert");
    if (!feature)
    {
        TRACE("vrt2/vert feature not found\n");
        return NULL;
    }
    return feature;
}

5510 5511 5512 5513 5514 5515 5516 5517
static void fill_fileinfo_from_face( GdiFont *font, Face *face )
{
    WIN32_FILE_ATTRIBUTE_DATA info;
    int len;

    if (!face->file)
    {
        font->fileinfo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*font->fileinfo));
5518
        font->fileinfo->size.QuadPart = face->font_data_size;
5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530
        return;
    }

    len = strlenW(face->file);
    font->fileinfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*font->fileinfo) + len * sizeof(WCHAR));
    if (GetFileAttributesExW(face->file, GetFileExInfoStandard, &info))
    {
        font->fileinfo->writetime = info.ftLastWriteTime;
        font->fileinfo->size.QuadPart = (LONGLONG)info.nFileSizeHigh << 32 | info.nFileSizeLow;
        strcpyW(font->fileinfo->path, face->file);
    }
    else
5531
        memset(font->fileinfo, 0, sizeof(*font->fileinfo) + len * sizeof(WCHAR));
5532 5533
}

5534
/*************************************************************
5535
 * freetype_SelectFont
5536
 */
5537
static HFONT CDECL freetype_SelectFont( PHYSDEV dev, HFONT hfont, UINT *aa_flags )
5538
{
5539
    struct freetype_physdev *physdev = get_freetype_dev( dev );
5540
    GdiFont *ret;
5541
    Face *face, *best, *best_bitmap;
5542
    Family *family, *last_resort_family;
5543
    const struct list *face_list;
5544
    INT height, width = 0;
5545
    unsigned int score = 0, new_score;
5546
    signed int diff = 0, newdiff;
5547
    BOOL bd, it, can_use_bitmap, want_vertical;
5548
    LOGFONTW lf;
5549
    CHARSETINFO csi;
5550
    FMAT2 dcmat;
5551
    FontSubst *psub = NULL;
5552
    DC *dc = get_physdev_dc( dev );
5553
    const SYSTEM_LINKS *font_link;
5554 5555 5556

    if (!hfont)  /* notification that the font has been changed by another driver */
    {
5557
        release_font( physdev->font );
5558 5559 5560
        physdev->font = NULL;
        return 0;
    }
5561

5562
    GetObjectW( hfont, sizeof(lf), &lf );
5563 5564
    lf.lfWidth = abs(lf.lfWidth);

5565
    can_use_bitmap = GetDeviceCaps(dev->hdc, TEXTCAPS) & TC_RA_ABLE;
5566

5567
    TRACE("%s, h=%d, it=%d, weight=%d, PandF=%02x, charset=%d orient %d escapement %d\n",
5568 5569 5570
	  debugstr_w(lf.lfFaceName), lf.lfHeight, lf.lfItalic,
	  lf.lfWeight, lf.lfPitchAndFamily, lf.lfCharSet, lf.lfOrientation,
	  lf.lfEscapement);
5571

5572
    if(dc->GraphicsMode == GM_ADVANCED)
5573
    {
5574
        memcpy(&dcmat, &dc->xformWorld2Vport, sizeof(FMAT2));
5575 5576 5577 5578 5579
        /* Try to avoid not necessary glyph transformations */
        if (dcmat.eM21 == 0.0 && dcmat.eM12 == 0.0 && dcmat.eM11 == dcmat.eM22)
        {
            lf.lfHeight *= fabs(dcmat.eM11);
            lf.lfWidth *= fabs(dcmat.eM11);
5580
            dcmat.eM11 = dcmat.eM22 = dcmat.eM11 < 0 ? -1 : 1;
5581 5582
        }
    }
5583 5584 5585 5586
    else
    {
        /* Windows 3.1 compatibility mode GM_COMPATIBLE has only limited
           font scaling abilities. */
5587
        dcmat.eM11 = dcmat.eM22 = 1.0;
5588
        dcmat.eM21 = dcmat.eM12 = 0;
5589
        lf.lfOrientation = lf.lfEscapement;
5590 5591 5592 5593 5594 5595 5596
        if (dc->vport2WorldValid)
        {
            if (dc->xformWorld2Vport.eM11 * dc->xformWorld2Vport.eM22 < 0)
                lf.lfOrientation = -lf.lfOrientation;
            lf.lfHeight *= fabs(dc->xformWorld2Vport.eM22);
            lf.lfWidth *= fabs(dc->xformWorld2Vport.eM22);
        }
5597 5598
    }

5599 5600
    TRACE("DC transform %f %f %f %f\n", dcmat.eM11, dcmat.eM12,
                                        dcmat.eM21, dcmat.eM22);
5601

5602
    GDI_CheckNotLock();
5603 5604
    EnterCriticalSection( &freetype_cs );

5605
    /* check the cache first */
5606
    if((ret = find_in_cache(hfont, &lf, &dcmat, can_use_bitmap)) != NULL) {
5607
        TRACE("returning cached gdiFont(%p) for hFont %p\n", ret, hfont);
5608
        goto done;
5609 5610
    }

5611
    TRACE("not in cache\n");
5612
    ret = alloc_font();
5613

5614
    ret->font_desc.matrix = dcmat;
5615 5616 5617
    ret->font_desc.lf = lf;
    ret->font_desc.can_use_bitmap = can_use_bitmap;
    calc_hash(&ret->font_desc);
5618

5619 5620 5621 5622 5623 5624 5625 5626
    /* If lfFaceName is "Symbol" then Windows fixes up lfCharSet to
       SYMBOL_CHARSET so that Symbol gets picked irrespective of the
       original value lfCharSet.  Note this is a special case for
       Symbol and doesn't happen at least for "Wingdings*" */

    if(!strcmpiW(lf.lfFaceName, SymbolW))
        lf.lfCharSet = SYMBOL_CHARSET;

5627
    if(!TranslateCharsetInfo((DWORD*)(INT_PTR)lf.lfCharSet, &csi, TCI_SRCCHARSET)) {
5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638
        switch(lf.lfCharSet) {
	case DEFAULT_CHARSET:
	    csi.fs.fsCsb[0] = 0;
	    break;
	default:
	    FIXME("Untranslated charset %d\n", lf.lfCharSet);
	    csi.fs.fsCsb[0] = 0;
	    break;
	}
    }

5639
    family = NULL;
5640
    if(lf.lfFaceName[0] != '\0') {
5641
        CHILD_FONT *font_link_entry;
5642
        LPWSTR FaceName = lf.lfFaceName;
5643

5644
        psub = get_font_subst(&font_subst_list, FaceName, lf.lfCharSet);
5645

5646
	if(psub) {
5647 5648 5649 5650
	    TRACE("substituting %s,%d -> %s,%d\n", debugstr_w(FaceName), lf.lfCharSet,
		  debugstr_w(psub->to.name), (psub->to.charset != -1) ? psub->to.charset : lf.lfCharSet);
	    if (psub->to.charset != -1)
		lf.lfCharSet = psub->to.charset;
5651 5652
	}

5653 5654 5655 5656 5657 5658
	/* We want a match on name and charset or just name if
	   charset was DEFAULT_CHARSET.  If the latter then
	   we fixup the returned charset later in get_nearest_charset
	   where we'll either use the charset of the current ansi codepage
	   or if that's unavailable the first charset that the font supports.
	*/
5659
        LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
5660 5661
            if (!strncmpiW(family->FamilyName, FaceName, LF_FACESIZE - 1) ||
                (psub && !strncmpiW(family->FamilyName, psub->to.name, LF_FACESIZE - 1)))
5662
            {
5663
                font_link = find_font_link(family->FamilyName);
5664
                face_list = get_face_list_from_family(family);
5665
                LIST_FOR_EACH_ENTRY( face, face_list, Face, entry ) {
5666 5667 5668 5669 5670 5671 5672 5673 5674
                    if (!(face->scalable || can_use_bitmap))
                        continue;
                    if (csi.fs.fsCsb[0] & face->fs.fsCsb[0])
                        goto found;
                    if (font_link != NULL &&
                        csi.fs.fsCsb[0] & font_link->fs.fsCsb[0])
                        goto found;
                    if (!csi.fs.fsCsb[0])
                        goto found;
5675
                }
5676
            }
5677
	}
5678

5679
        /* Search by full face name. */
5680
        LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
5681
            face_list = get_face_list_from_family(family);
5682
            LIST_FOR_EACH_ENTRY( face, face_list, Face, entry ) {
5683
                if(face->FullName && !strncmpiW(face->FullName, FaceName, LF_FACESIZE - 1) &&
5684
                   (face->scalable || can_use_bitmap))
5685
                {
5686 5687 5688 5689 5690
                    if (csi.fs.fsCsb[0] & face->fs.fsCsb[0] || !csi.fs.fsCsb[0])
                        goto found_face;
                    font_link = find_font_link(family->FamilyName);
                    if (font_link != NULL &&
                        csi.fs.fsCsb[0] & font_link->fs.fsCsb[0])
5691 5692 5693 5694 5695
                        goto found_face;
                }
            }
        }

5696 5697 5698 5699 5700 5701
        /*
	 * Try check the SystemLink list first for a replacement font.
	 * We may find good replacements there.
         */
        LIST_FOR_EACH_ENTRY(font_link, &system_links, SYSTEM_LINKS, entry)
        {
5702 5703
            if(!strncmpiW(font_link->font_name, FaceName, LF_FACESIZE - 1) ||
               (psub && !strncmpiW(font_link->font_name,psub->to.name, LF_FACESIZE - 1)))
5704 5705 5706 5707
            {
                TRACE("found entry in system list\n");
                LIST_FOR_EACH_ENTRY(font_link_entry, &font_link->links, CHILD_FONT, entry)
                {
5708 5709
                    const SYSTEM_LINKS *links;

5710
                    face = font_link_entry->face;
5711 5712
                    if (!(face->scalable || can_use_bitmap))
                        continue;
5713
                    family = face->family;
5714 5715 5716 5717 5718
                    if (csi.fs.fsCsb[0] & face->fs.fsCsb[0] || !csi.fs.fsCsb[0])
                        goto found;
                    links = find_font_link(family->FamilyName);
                    if (links != NULL && csi.fs.fsCsb[0] & links->fs.fsCsb[0])
                        goto found;
5719 5720 5721
                }
            }
        }
5722 5723
    }

5724 5725
    psub = NULL; /* substitution is no more relevant */

5726 5727
    /* If requested charset was DEFAULT_CHARSET then try using charset
       corresponding to the current ansi codepage */
5728
    if (!csi.fs.fsCsb[0])
5729
    {
5730
        INT acp = GetACP();
5731
        if(!TranslateCharsetInfo((DWORD*)(INT_PTR)acp, &csi, TCI_SRCCODEPAGE)) {
5732 5733 5734 5735 5736
            FIXME("TCI failed on codepage %d\n", acp);
            csi.fs.fsCsb[0] = 0;
        } else
            lf.lfCharSet = csi.ciCharset;
    }
5737

5738 5739
    want_vertical = (lf.lfFaceName[0] == '@');

5740 5741
    /* Face families are in the top 4 bits of lfPitchAndFamily,
       so mask with 0xF0 before testing */
5742

5743 5744
    if((lf.lfPitchAndFamily & FIXED_PITCH) ||
       (lf.lfPitchAndFamily & 0xF0) == FF_MODERN)
5745
        strcpyW(lf.lfFaceName, default_fixed);
5746
    else if((lf.lfPitchAndFamily & 0xF0) == FF_ROMAN)
5747
        strcpyW(lf.lfFaceName, default_serif);
5748
    else if((lf.lfPitchAndFamily & 0xF0) == FF_SWISS)
5749
        strcpyW(lf.lfFaceName, default_sans);
5750
    else
5751
        strcpyW(lf.lfFaceName, default_sans);
5752
    LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
5753
        if(!strncmpiW(family->FamilyName, lf.lfFaceName, LF_FACESIZE - 1)) {
5754
            font_link = find_font_link(family->FamilyName);
5755
            face_list = get_face_list_from_family(family);
5756
            LIST_FOR_EACH_ENTRY( face, face_list, Face, entry ) {
5757 5758 5759 5760 5761 5762
                if (!(face->scalable || can_use_bitmap))
                    continue;
                if (csi.fs.fsCsb[0] & face->fs.fsCsb[0])
                    goto found;
                if (font_link != NULL && csi.fs.fsCsb[0] & font_link->fs.fsCsb[0])
                    goto found;
5763
            }
5764
        }
5765 5766
    }

5767 5768 5769 5770 5771 5772
#ifdef SONAME_LIBFONTCONFIG
    /* Try FontConfig substitutions if the face isn't found */
    family = get_fontconfig_family(lf.lfPitchAndFamily, &csi);
    if (family) goto found;
#endif

5773
    last_resort_family = NULL;
5774
    LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
5775
        font_link = find_font_link(family->FamilyName);
5776
        face_list = get_face_list_from_family(family);
5777
        LIST_FOR_EACH_ENTRY( face, face_list, Face, entry ) {
5778
            if(!(face->flags & ADDFONT_VERTICAL_FONT) == !want_vertical &&
5779 5780
               (csi.fs.fsCsb[0] & face->fs.fsCsb[0] ||
                (font_link != NULL && csi.fs.fsCsb[0] & font_link->fs.fsCsb[0]))) {
5781
                if(face->scalable)
5782
                    goto found;
5783 5784 5785
                if(can_use_bitmap && !last_resort_family)
                    last_resort_family = family;
            }            
5786
        }
5787 5788
    }

5789 5790 5791 5792 5793 5794
    if(last_resort_family) {
        family = last_resort_family;
        csi.fs.fsCsb[0] = 0;
        goto found;
    }

5795
    LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
5796
        face_list = get_face_list_from_family(family);
5797
        LIST_FOR_EACH_ENTRY( face, face_list, Face, entry ) {
5798
            if(face->scalable && !(face->flags & ADDFONT_VERTICAL_FONT) == !want_vertical) {
5799
                csi.fs.fsCsb[0] = 0;
5800
                WARN("just using first face for now\n");
5801
                goto found;
5802
            }
5803 5804
            if(can_use_bitmap && !last_resort_family)
                last_resort_family = family;
5805
        }
5806
    }
5807 5808 5809
    if(!last_resort_family) {
        FIXME("can't find a single appropriate font - bailing\n");
        free_font(ret);
5810 5811
        ret = NULL;
        goto done;
5812 5813 5814 5815 5816
    }

    WARN("could only find a bitmap font - this will probably look awful!\n");
    family = last_resort_family;
    csi.fs.fsCsb[0] = 0;
5817

5818
found:
5819 5820
    it = lf.lfItalic ? 1 : 0;
    bd = lf.lfWeight > 550 ? 1 : 0;
5821

5822
    height = lf.lfHeight;
5823

5824
    face = best = best_bitmap = NULL;
5825
    font_link = find_font_link(family->FamilyName);
5826 5827
    face_list = get_face_list_from_family(family);
    LIST_FOR_EACH_ENTRY(face, face_list, Face, entry)
5828
    {
5829 5830 5831
        if (csi.fs.fsCsb[0] & face->fs.fsCsb[0] ||
            (font_link != NULL && csi.fs.fsCsb[0] & font_link->fs.fsCsb[0]) ||
            !csi.fs.fsCsb[0])
5832
        {
5833 5834 5835 5836 5837
            BOOL italic, bold;

            italic = (face->ntmFlags & NTM_ITALIC) ? 1 : 0;
            bold = (face->ntmFlags & NTM_BOLD) ? 1 : 0;
            new_score = (italic ^ it) + (bold ^ bd);
5838 5839 5840
            if(!best || new_score <= score)
            {
                TRACE("(it=%d, bd=%d) is selected for (it=%d, bd=%d)\n",
5841
                      italic, bold, it, bd);
5842
                score = new_score;
5843
                best = face;
5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858
                if(best->scalable  && score == 0) break;
                if(!best->scalable)
                {
                    if(height > 0)
                        newdiff = height - (signed int)(best->size.height);
                    else
                        newdiff = -height - ((signed int)(best->size.height) - best->size.internal_leading);
                    if(!best_bitmap || new_score < score ||
                       (diff > 0 && newdiff < diff && newdiff >= 0) || (diff < 0 && newdiff > diff))
                    {
                        TRACE("%d is better for %d diff was %d\n", best->size.height, height, diff);
                        diff = newdiff;
                        best_bitmap = best;
                        if(score == 0 && diff == 0) break;
                    }
5859
                }
5860 5861
            }
        }
5862
    }
5863 5864
    if(best)
        face = best->scalable ? best : best_bitmap;
5865 5866
    ret->fake_italic = (it && !(face->ntmFlags & NTM_ITALIC));
    ret->fake_bold = (bd && !(face->ntmFlags & NTM_BOLD));
5867

5868 5869 5870
found_face:
    height = lf.lfHeight;

5871
    ret->fs = face->fs;
5872

5873
    if(csi.fs.fsCsb[0]) {
5874
        ret->charset = lf.lfCharSet;
5875 5876
        ret->codepage = csi.ciACP;
    }
5877
    else
5878
        ret->charset = get_nearest_charset(family->FamilyName, face, &ret->codepage);
5879

5880
    TRACE("Chosen: %s %s (%s/%p:%ld)\n", debugstr_w(family->FamilyName),
5881
	  debugstr_w(face->StyleName), debugstr_w(face->file), face->font_data_ptr, face->face_index);
5882

5883
    ret->aveWidth = height ? lf.lfWidth : 0;
5884

5885
    if(!face->scalable) {
5886 5887
        /* Windows uses integer scaling factors for bitmap fonts */
        INT scale, scaled_height;
5888
        GdiFont *cachedfont;
5889

5890 5891 5892 5893 5894
        /* FIXME: rotation of bitmap fonts is ignored */
        height = abs(GDI_ROUND( (double)height * ret->font_desc.matrix.eM22 ));
        if (ret->aveWidth)
            ret->aveWidth = (double)ret->aveWidth * ret->font_desc.matrix.eM11;
        ret->font_desc.matrix.eM11 = ret->font_desc.matrix.eM22 = 1.0;
5895 5896 5897 5898 5899 5900
        dcmat.eM11 = dcmat.eM22 = 1.0;
        /* As we changed the matrix, we need to search the cache for the font again,
         * otherwise we might explode the cache. */
        if((cachedfont = find_in_cache(hfont, &lf, &dcmat, can_use_bitmap)) != NULL) {
            TRACE("Found cached font after non-scalable matrix rescale!\n");
            free_font( ret );
5901 5902
            ret = cachedfont;
            goto done;
5903 5904
        }
        calc_hash(&ret->font_desc);
5905

5906 5907 5908 5909 5910
        if (height != 0) height = diff;
        height += face->size.height;

        scale = (height + face->size.height - 1) / face->size.height;
        scaled_height = scale * face->size.height;
5911 5912 5913 5914
        /* Only jump to the next height if the difference <= 25% original height */
        if (scale > 2 && scaled_height - height > face->size.height / 4) scale--;
        /* The jump between unscaled and doubled is delayed by 1 */
        else if (scale == 2 && scaled_height - height > (face->size.height / 4 - 1)) scale--;
5915
        ret->scale_y = scale;
5916

5917 5918 5919
        width = face->size.x_ppem >> 6;
        height = face->size.y_ppem >> 6;
    }
5920 5921 5922 5923
    else
        ret->scale_y = 1.0;
    TRACE("font scale y: %f\n", ret->scale_y);

5924
    ret->ft_face = OpenFontFace(ret, face, width, height);
5925

5926 5927 5928
    if (!ret->ft_face)
    {
        free_font( ret );
5929 5930
        ret = NULL;
        goto done;
5931
    }
5932

5933
    fill_fileinfo_from_face( ret, face );
5934 5935
    ret->ntmFlags = face->ntmFlags;

5936
    pick_charmap( ret->ft_face, ret->charset );
5937

5938
    ret->orientation = FT_IS_SCALABLE(ret->ft_face) ? lf.lfOrientation : 0;
5939
    ret->name = psub ? strdupW(psub->from.name) : strdupW(family->FamilyName);
5940 5941
    ret->underline = lf.lfUnderline ? 0xff : 0;
    ret->strikeout = lf.lfStrikeOut ? 0xff : 0;
5942
    create_child_font_list(ret);
5943

5944
    if (face->flags & ADDFONT_VERTICAL_FONT) /* We need to try to load the GSUB table */
5945
    {
5946
        int length = get_font_data(ret, MS_GSUB_TAG , 0, NULL, 0);
5947 5948 5949
        if (length != GDI_ERROR)
        {
            ret->GSUB_Table = HeapAlloc(GetProcessHeap(),0,length);
5950
            get_font_data(ret, MS_GSUB_TAG , 0, ret->GSUB_Table, length);
5951
            TRACE("Loaded GSUB table of %i bytes\n",length);
5952 5953 5954 5955 5956 5957 5958
            ret->vert_feature = get_GSUB_vert_feature(ret);
            if (!ret->vert_feature)
            {
                TRACE("Vertical feature not found\n");
                HeapFree(GetProcessHeap(), 0, ret->GSUB_Table);
                ret->GSUB_Table = NULL;
            }
5959 5960
        }
    }
5961
    ret->aa_flags = HIWORD( face->flags );
5962

5963
    TRACE("caching: gdiFont=%p  hfont=%p\n", ret, hfont);
5964

5965
    add_to_cache(ret);
5966 5967 5968
done:
    if (ret)
    {
5969
        PHYSDEV next = GET_NEXT_PHYSDEV( dev, pSelectFont );
5970

5971
        switch (lf.lfQuality)
5972
        {
5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984
        case NONANTIALIASED_QUALITY:
        case ANTIALIASED_QUALITY:
            next->funcs->pSelectFont( dev, hfont, aa_flags );
            break;
        case CLEARTYPE_QUALITY:
        case CLEARTYPE_NATURAL_QUALITY:
        default:
            if (!*aa_flags) *aa_flags = ret->aa_flags;
            next->funcs->pSelectFont( dev, hfont, aa_flags );

            /* fixup the antialiasing flags for that font */
            switch (*aa_flags)
5985
            {
5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996
            case WINE_GGO_HRGB_BITMAP:
            case WINE_GGO_HBGR_BITMAP:
            case WINE_GGO_VRGB_BITMAP:
            case WINE_GGO_VBGR_BITMAP:
                if (is_subpixel_rendering_enabled()) break;
                *aa_flags = GGO_GRAY4_BITMAP;
                /* fall through */
            case GGO_GRAY2_BITMAP:
            case GGO_GRAY4_BITMAP:
            case GGO_GRAY8_BITMAP:
            case WINE_GGO_GRAY16_BITMAP:
5997
                if ((!antialias_fakes || (!ret->fake_bold && !ret->fake_italic)) && is_hinting_enabled())
5998 5999 6000
                {
                    WORD gasp_flags;
                    if (get_gasp_flags( ret, &gasp_flags ) && !(gasp_flags & GASP_DOGRAY))
6001 6002 6003
                    {
                        TRACE( "font %s %d aa disabled by GASP\n",
                               debugstr_w(lf.lfFaceName), lf.lfHeight );
6004
                        *aa_flags = GGO_BITMAP;
6005
                    }
6006
                }
6007 6008
            }
        }
6009
        TRACE( "%p %s %d aa %x\n", hfont, debugstr_w(lf.lfFaceName), lf.lfHeight, *aa_flags );
6010
        release_font( physdev->font );
6011 6012
        physdev->font = ret;
    }
6013
    LeaveCriticalSection( &freetype_cs );
6014
    return ret ? hfont : 0;
6015 6016
}

6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039
static INT load_script_name( UINT id, WCHAR buffer[LF_FACESIZE] )
{
    HRSRC rsrc;
    HGLOBAL hMem;
    WCHAR *p;
    int i;

    id += IDS_FIRST_SCRIPT;
    rsrc = FindResourceW( gdi32_module, (LPCWSTR)(ULONG_PTR)((id >> 4) + 1), (LPCWSTR)6 /*RT_STRING*/ );
    if (!rsrc) return 0;
    hMem = LoadResource( gdi32_module, rsrc );
    if (!hMem) return 0;

    p = LockResource( hMem );
    id &= 0x000f;
    while (id--) p += *p + 1;

    i = min(LF_FACESIZE - 1, *p);
    memcpy(buffer, p + 1, i * sizeof(WCHAR));
    buffer[i] = 0;
    return i;
}

6040 6041 6042 6043 6044 6045 6046
static inline BOOL is_complex_script_ansi_cp(UINT ansi_cp)
{
    return (ansi_cp == 874 /* Thai */
            || ansi_cp == 1255 /* Hebrew */
            || ansi_cp == 1256 /* Arabic */
        );
}
6047

6048 6049 6050 6051 6052
/***************************************************
 * create_enum_charset_list
 *
 * This function creates charset enumeration list because in DEFAULT_CHARSET
 * case, the ANSI codepage's charset takes precedence over other charsets.
6053
 * Above rule doesn't apply if the ANSI codepage uses complex script (e.g. Thai).
6054 6055 6056 6057 6058 6059 6060
 * This function works as a filter other than DEFAULT_CHARSET case.
 */
static DWORD create_enum_charset_list(DWORD charset, struct enum_charset_list *list)
{
    CHARSETINFO csi;
    DWORD n = 0;

6061
    if (TranslateCharsetInfo(ULongToPtr(charset), &csi, TCI_SRCCHARSET) &&
6062 6063 6064
        csi.fs.fsCsb[0] != 0) {
        list->element[n].mask    = csi.fs.fsCsb[0];
        list->element[n].charset = csi.ciCharset;
6065
        load_script_name( ffs(csi.fs.fsCsb[0]) - 1, list->element[n].name );
6066 6067 6068 6069
        n++;
    }
    else { /* charset is DEFAULT_CHARSET or invalid. */
        INT acp, i;
6070
        DWORD mask = 0;
6071 6072 6073

        /* Set the current codepage's charset as the first element. */
        acp = GetACP();
6074 6075
        if (!is_complex_script_ansi_cp(acp) &&
            TranslateCharsetInfo((DWORD*)(INT_PTR)acp, &csi, TCI_SRCCODEPAGE) &&
6076 6077 6078
            csi.fs.fsCsb[0] != 0) {
            list->element[n].mask    = csi.fs.fsCsb[0];
            list->element[n].charset = csi.ciCharset;
6079
            load_script_name( ffs(csi.fs.fsCsb[0]) - 1, list->element[n].name );
6080
            mask |= csi.fs.fsCsb[0];
6081 6082 6083 6084 6085 6086 6087 6088
            n++;
        }

        /* Fill out left elements. */
        for (i = 0; i < 32; i++) {
            FONTSIGNATURE fs;
            fs.fsCsb[0] = 1L << i;
            fs.fsCsb[1] = 0;
6089
            if (fs.fsCsb[0] & mask)
6090 6091 6092 6093 6094 6095
                continue; /* skip, already added. */
            if (!TranslateCharsetInfo(fs.fsCsb, &csi, TCI_SRCFONTSIG))
                continue; /* skip, this is an invalid fsCsb bit. */

            list->element[n].mask    = fs.fsCsb[0];
            list->element[n].charset = csi.ciCharset;
6096
            load_script_name( i, list->element[n].name );
6097 6098 6099 6100 6101 6102 6103 6104 6105 6106
            mask |= fs.fsCsb[0];
            n++;
        }

        /* add catch all mask for remaining bits */
        if (~mask)
        {
            list->element[n].mask    = ~mask;
            list->element[n].charset = DEFAULT_CHARSET;
            load_script_name( IDS_OTHER - IDS_FIRST_SCRIPT, list->element[n].name );
6107 6108 6109 6110 6111 6112 6113 6114
            n++;
        }
    }
    list->total = n;

    return n;
}

6115
static void GetEnumStructs(Face *face, const WCHAR *family_name, LPENUMLOGFONTEXW pelf,
6116
			   NEWTEXTMETRICEXW *pntm, LPDWORD ptype)
6117
{
6118
    GdiFont *font;
6119
    LONG width, height;
6120

6121
    if (face->cached_enum_data)
6122 6123
    {
        TRACE("Cached\n");
6124 6125
        *pelf = face->cached_enum_data->elf;
        *pntm = face->cached_enum_data->ntm;
6126
        *ptype = face->cached_enum_data->type;
6127 6128 6129
        return;
    }

6130 6131
    font = alloc_font();

6132
    if(face->scalable) {
6133
        height = 100;
6134 6135 6136 6137 6138
        width = 0;
    } else {
        height = face->size.y_ppem >> 6;
        width = face->size.x_ppem >> 6;
    }
6139
    font->scale_y = 1.0;
6140
    
6141
    if (!(font->ft_face = OpenFontFace(font, face, width, height)))
6142 6143 6144 6145
    {
        free_font(font);
        return;
    }
6146

6147
    font->name = strdupW( family_name );
6148
    font->ntmFlags = face->ntmFlags;
6149

6150
    if (get_outline_text_metrics(font))
6151 6152
    {
        memcpy(&pntm->ntmTm, &font->potm->otmTextMetrics, sizeof(TEXTMETRICW));
6153

6154
        pntm->ntmTm.ntmSizeEM = font->potm->otmEMSquare;
6155 6156
        pntm->ntmTm.ntmCellHeight = font->ntmCellHeight;
        pntm->ntmTm.ntmAvgWidth = font->ntmAvgWidth;
6157

6158
        lstrcpynW(pelf->elfLogFont.lfFaceName,
6159
                 (WCHAR*)((char*)font->potm + (ULONG_PTR)font->potm->otmpFamilyName),
6160
                 LF_FACESIZE);
6161
        lstrcpynW(pelf->elfFullName,
6162
                 (WCHAR*)((char*)font->potm + (ULONG_PTR)font->potm->otmpFaceName),
6163
                 LF_FULLFACESIZE);
6164
        lstrcpynW(pelf->elfStyle,
6165
                 (WCHAR*)((char*)font->potm + (ULONG_PTR)font->potm->otmpStyleName),
6166
                 LF_FACESIZE);
6167 6168 6169
    }
    else
    {
6170
        get_text_metrics(font, (TEXTMETRICW *)&pntm->ntmTm);
6171

6172
        pntm->ntmTm.ntmSizeEM = pntm->ntmTm.tmHeight - pntm->ntmTm.tmInternalLeading;
6173 6174
        pntm->ntmTm.ntmCellHeight = pntm->ntmTm.tmHeight;
        pntm->ntmTm.ntmAvgWidth = pntm->ntmTm.tmAveCharWidth;
6175

6176
        lstrcpynW(pelf->elfLogFont.lfFaceName, family_name, LF_FACESIZE);
6177 6178 6179
        if (face->FullName)
            lstrcpynW(pelf->elfFullName, face->FullName, LF_FULLFACESIZE);
        else
6180
            lstrcpynW(pelf->elfFullName, family_name, LF_FULLFACESIZE);
6181
        lstrcpynW(pelf->elfStyle, face->StyleName, LF_FACESIZE);
6182
    }
6183

6184
    pntm->ntmTm.ntmFlags = face->ntmFlags;
6185
    pntm->ntmFontSig = face->fs;
6186

6187
    pelf->elfScript[0] = '\0'; /* This will get set in WineEngEnumFonts */
6188

6189 6190
    pelf->elfLogFont.lfEscapement = 0;
    pelf->elfLogFont.lfOrientation = 0;
6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210
    pelf->elfLogFont.lfHeight = pntm->ntmTm.tmHeight;
    pelf->elfLogFont.lfWidth = pntm->ntmTm.tmAveCharWidth;
    pelf->elfLogFont.lfWeight = pntm->ntmTm.tmWeight;
    pelf->elfLogFont.lfItalic = pntm->ntmTm.tmItalic;
    pelf->elfLogFont.lfUnderline = pntm->ntmTm.tmUnderlined;
    pelf->elfLogFont.lfStrikeOut = pntm->ntmTm.tmStruckOut;
    pelf->elfLogFont.lfCharSet = pntm->ntmTm.tmCharSet;
    pelf->elfLogFont.lfOutPrecision = OUT_STROKE_PRECIS;
    pelf->elfLogFont.lfClipPrecision = CLIP_STROKE_PRECIS;
    pelf->elfLogFont.lfQuality = DRAFT_QUALITY;
    pelf->elfLogFont.lfPitchAndFamily = (pntm->ntmTm.tmPitchAndFamily & 0xf1) + 1;

    *ptype = 0;
    if (pntm->ntmTm.tmPitchAndFamily & TMPF_TRUETYPE)
        *ptype |= TRUETYPE_FONTTYPE;
    if (pntm->ntmTm.tmPitchAndFamily & TMPF_DEVICE)
        *ptype |= DEVICE_FONTTYPE;
    if(!(pntm->ntmTm.tmPitchAndFamily & TMPF_VECTOR))
        *ptype |= RASTER_FONTTYPE;

6211 6212 6213
    face->cached_enum_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*face->cached_enum_data));
    if (face->cached_enum_data)
    {
6214 6215
        face->cached_enum_data->elf = *pelf;
        face->cached_enum_data->ntm = *pntm;
6216 6217
        face->cached_enum_data->type = *ptype;
    }
6218

6219
    free_font(font);
6220 6221
}

6222
static BOOL family_matches(Family *family, const WCHAR *face_name)
6223
{
6224 6225
    Face *face;
    const struct list *face_list;
6226

6227
    if (!strncmpiW(face_name, family->FamilyName, LF_FACESIZE - 1)) return TRUE;
6228

6229
    face_list = get_face_list_from_family(family);
6230
    LIST_FOR_EACH_ENTRY(face, face_list, Face, entry)
6231
        if (face->FullName && !strncmpiW(face_name, face->FullName, LF_FACESIZE - 1)) return TRUE;
6232 6233 6234 6235

    return FALSE;
}

6236
static BOOL face_matches(const WCHAR *family_name, Face *face, const WCHAR *face_name)
6237
{
6238
    if (!strncmpiW(face_name, family_name, LF_FACESIZE - 1)) return TRUE;
6239

6240
    return (face->FullName && !strncmpiW(face_name, face->FullName, LF_FACESIZE - 1));
6241 6242
}

6243
static BOOL enum_face_charsets(const Family *family, Face *face, struct enum_charset_list *list,
6244
                               FONTENUMPROCW proc, LPARAM lparam, const WCHAR *subst)
6245 6246 6247 6248
{
    ENUMLOGFONTEXW elf;
    NEWTEXTMETRICEXW ntm;
    DWORD type = 0;
6249
    DWORD i;
6250

6251
    GetEnumStructs(face, face->family->FamilyName, &elf, &ntm, &type);
6252
    for(i = 0; i < list->total; i++) {
6253 6254
        if(!face->scalable && face->fs.fsCsb[0] == 0) { /* OEM bitmap */
            elf.elfLogFont.lfCharSet = ntm.ntmTm.tmCharSet = OEM_CHARSET;
6255
            load_script_name( IDS_OEM_DOS - IDS_FIRST_SCRIPT, elf.elfScript );
6256
            i = list->total; /* break out of loop after enumeration */
6257 6258 6259 6260 6261 6262 6263
        }
        else
        {
            if(!(face->fs.fsCsb[0] & list->element[i].mask)) continue;
            /* use the DEFAULT_CHARSET case only if no other charset is present */
            if (list->element[i].charset == DEFAULT_CHARSET &&
                (face->fs.fsCsb[0] & ~list->element[i].mask)) continue;
6264
            elf.elfLogFont.lfCharSet = ntm.ntmTm.tmCharSet = list->element[i].charset;
6265 6266
            strcpyW(elf.elfScript, list->element[i].name);
            if (!elf.elfScript[0])
6267
                FIXME("Unknown elfscript for bit %d\n", ffs(list->element[i].mask) - 1);
6268
        }
6269 6270 6271
        /* Font Replacement */
        if (family != face->family)
        {
6272
            lstrcpynW(elf.elfLogFont.lfFaceName, family->FamilyName, LF_FACESIZE);
6273
            if (face->FullName)
6274
                lstrcpynW(elf.elfFullName, face->FullName, LF_FULLFACESIZE);
6275
            else
6276
                lstrcpynW(elf.elfFullName, family->FamilyName, LF_FULLFACESIZE);
6277
        }
6278 6279
        if (subst)
            strcpyW(elf.elfLogFont.lfFaceName, subst);
6280 6281 6282
        TRACE("enuming face %s full %s style %s charset = %d type %d script %s it %d weight %d ntmflags %08x\n",
              debugstr_w(elf.elfLogFont.lfFaceName),
              debugstr_w(elf.elfFullName), debugstr_w(elf.elfStyle),
6283
              elf.elfLogFont.lfCharSet, type, debugstr_w(elf.elfScript),
6284 6285 6286 6287 6288 6289 6290 6291 6292 6293
              elf.elfLogFont.lfItalic, elf.elfLogFont.lfWeight,
              ntm.ntmTm.ntmFlags);
        /* release section before callback (FIXME) */
        LeaveCriticalSection( &freetype_cs );
        if (!proc(&elf.elfLogFont, (TEXTMETRICW *)&ntm, type, lparam)) return FALSE;
        EnterCriticalSection( &freetype_cs );
    }
    return TRUE;
}

6294
/*************************************************************
6295
 * freetype_EnumFonts
6296
 */
6297
static BOOL CDECL freetype_EnumFonts( PHYSDEV dev, LPLOGFONTW plf, FONTENUMPROCW proc, LPARAM lparam )
6298 6299 6300
{
    Family *family;
    Face *face;
6301
    const struct list *face_list;
6302
    LOGFONTW lf;
6303
    struct enum_charset_list enum_charsets;
6304

6305 6306 6307 6308 6309 6310 6311 6312
    if (!plf)
    {
        lf.lfCharSet = DEFAULT_CHARSET;
        lf.lfPitchAndFamily = 0;
        lf.lfFaceName[0] = 0;
        plf = &lf;
    }

6313
    TRACE("facename = %s charset %d\n", debugstr_w(plf->lfFaceName), plf->lfCharSet);
6314

6315 6316
    create_enum_charset_list(plf->lfCharSet, &enum_charsets);

6317
    GDI_CheckNotLock();
6318
    EnterCriticalSection( &freetype_cs );
6319
    if(plf->lfFaceName[0]) {
6320 6321
        WCHAR *face_name = plf->lfFaceName;
        FontSubst *psub = get_font_subst(&font_subst_list, plf->lfFaceName, plf->lfCharSet);
6322

6323 6324 6325
        if(psub) {
            TRACE("substituting %s -> %s\n", debugstr_w(plf->lfFaceName),
                  debugstr_w(psub->to.name));
6326
            face_name = psub->to.name;
6327
        }
6328

6329
        LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
6330
            if (!family_matches(family, face_name)) continue;
6331 6332
            face_list = get_face_list_from_family(family);
            LIST_FOR_EACH_ENTRY( face, face_list, Face, entry ) {
6333
                if (!face_matches(family->FamilyName, face, face_name)) continue;
6334
                if (!enum_face_charsets(family, face, &enum_charsets, proc, lparam, psub ? psub->from.name : NULL)) return FALSE;
6335 6336 6337
	    }
	}
    } else {
6338
        LIST_FOR_EACH_ENTRY( family, &font_list, Family, entry ) {
6339
            face_list = get_face_list_from_family(family);
6340
            face = LIST_ENTRY(list_head(face_list), Face, entry);
6341
            if (!enum_face_charsets(family, face, &enum_charsets, proc, lparam, NULL)) return FALSE;
6342 6343
	}
    }
6344
    LeaveCriticalSection( &freetype_cs );
6345
    return TRUE;
6346 6347
}

6348 6349 6350 6351 6352 6353 6354 6355 6356 6357
static void FTVectorToPOINTFX(FT_Vector *vec, POINTFX *pt)
{
    pt->x.value = vec->x >> 6;
    pt->x.fract = (vec->x & 0x3f) << 10;
    pt->x.fract |= ((pt->x.fract >> 6) | (pt->x.fract >> 12));
    pt->y.value = vec->y >> 6;
    pt->y.fract = (vec->y & 0x3f) << 10;
    pt->y.fract |= ((pt->y.fract >> 6) | (pt->y.fract >> 12));
}

6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376
/***************************************************
 * According to the MSDN documentation on WideCharToMultiByte,
 * certain codepages cannot set the default_used parameter.
 * This returns TRUE if the codepage can set that parameter, false else
 * so that calls to WideCharToMultiByte don't fail with ERROR_INVALID_PARAMETER
 */
static BOOL codepage_sets_default_used(UINT codepage)
{
   switch (codepage)
   {
       case CP_UTF7:
       case CP_UTF8:
       case CP_SYMBOL:
           return FALSE;
       default:
           return TRUE;
   }
}

6377 6378 6379 6380 6381 6382 6383 6384
/*
 * GSUB Table handling functions
 */

static INT GSUB_is_glyph_covered(LPCVOID table , UINT glyph)
{
    const GSUB_CoverageFormat1* cf1;

6385
    cf1 = table;
6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401

    if (GET_BE_WORD(cf1->CoverageFormat) == 1)
    {
        int count = GET_BE_WORD(cf1->GlyphCount);
        int i;
        TRACE("Coverage Format 1, %i glyphs\n",count);
        for (i = 0; i < count; i++)
            if (glyph == GET_BE_WORD(cf1->GlyphArray[i]))
                return i;
        return -1;
    }
    else if (GET_BE_WORD(cf1->CoverageFormat) == 2)
    {
        const GSUB_CoverageFormat2* cf2;
        int i;
        int count;
6402
        cf2 = (const GSUB_CoverageFormat2*)cf1;
6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416

        count = GET_BE_WORD(cf2->RangeCount);
        TRACE("Coverage Format 2, %i ranges\n",count);
        for (i = 0; i < count; i++)
        {
            if (glyph < GET_BE_WORD(cf2->RangeRecord[i].Start))
                return -1;
            if ((glyph >= GET_BE_WORD(cf2->RangeRecord[i].Start)) &&
                (glyph <= GET_BE_WORD(cf2->RangeRecord[i].End)))
            {
                return (GET_BE_WORD(cf2->RangeRecord[i].StartCoverageIndex) +
                    glyph - GET_BE_WORD(cf2->RangeRecord[i].Start));
            }
        }
6417
        return -1;
6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429
    }
    else
        ERR("Unknown CoverageFormat %i\n",GET_BE_WORD(cf1->CoverageFormat));

    return -1;
}

static FT_UInt GSUB_apply_feature(const GSUB_Header * header, const GSUB_Feature* feature, UINT glyph)
{
    int i;
    int offset;
    const GSUB_LookupList *lookup;
6430
    lookup = (const GSUB_LookupList*)((const BYTE*)header + GET_BE_WORD(header->LookupList));
6431 6432 6433 6434 6435 6436

    TRACE("%i lookups\n", GET_BE_WORD(feature->LookupCount));
    for (i = 0; i < GET_BE_WORD(feature->LookupCount); i++)
    {
        const GSUB_LookupTable *look;
        offset = GET_BE_WORD(lookup->Lookup[GET_BE_WORD(feature->LookupListIndex[i])]);
6437
        look = (const GSUB_LookupTable*)((const BYTE*)lookup + offset);
6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448
        TRACE("type %i, flag %x, subtables %i\n",GET_BE_WORD(look->LookupType),GET_BE_WORD(look->LookupFlag),GET_BE_WORD(look->SubTableCount));
        if (GET_BE_WORD(look->LookupType) != 1)
            FIXME("We only handle SubType 1\n");
        else
        {
            int j;

            for (j = 0; j < GET_BE_WORD(look->SubTableCount); j++)
            {
                const GSUB_SingleSubstFormat1 *ssf1;
                offset = GET_BE_WORD(look->SubTable[j]);
6449
                ssf1 = (const GSUB_SingleSubstFormat1*)((const BYTE*)look+offset);
6450 6451 6452 6453
                if (GET_BE_WORD(ssf1->SubstFormat) == 1)
                {
                    int offset = GET_BE_WORD(ssf1->Coverage);
                    TRACE("  subtype 1, delta %i\n", GET_BE_WORD(ssf1->DeltaGlyphID));
6454
                    if (GSUB_is_glyph_covered((const BYTE*)ssf1+offset, glyph) != -1)
6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466
                    {
                        TRACE("  Glyph 0x%x ->",glyph);
                        glyph += GET_BE_WORD(ssf1->DeltaGlyphID);
                        TRACE(" 0x%x\n",glyph);
                    }
                }
                else
                {
                    const GSUB_SingleSubstFormat2 *ssf2;
                    INT index;
                    INT offset;

6467
                    ssf2 = (const GSUB_SingleSubstFormat2 *)ssf1;
6468 6469
                    offset = GET_BE_WORD(ssf1->Coverage);
                    TRACE("  subtype 2,  glyph count %i\n", GET_BE_WORD(ssf2->GlyphCount));
6470
                    index = GSUB_is_glyph_covered((const BYTE*)ssf2+offset, glyph);
6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494
                    TRACE("  Coverage index %i\n",index);
                    if (index != -1)
                    {
                        TRACE("    Glyph is 0x%x ->",glyph);
                        glyph = GET_BE_WORD(ssf2->Substitute[index]);
                        TRACE("0x%x\n",glyph);
                    }
                }
            }
        }
    }
    return glyph;
}


static FT_UInt get_GSUB_vert_glyph(const GdiFont *font, UINT glyph)
{
    const GSUB_Header *header;
    const GSUB_Feature *feature;

    if (!font->GSUB_Table)
        return glyph;

    header = font->GSUB_Table;
6495
    feature = font->vert_feature;
6496 6497 6498 6499

    return GSUB_apply_feature(header, feature, glyph);
}

6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512
static FT_UInt get_glyph_index_symbol(const GdiFont *font, UINT glyph)
{
    FT_UInt ret;

    if (glyph < 0x100) glyph += 0xf000;
    /* there are a number of old pre-Unicode "broken" TTFs, which
       do have symbols at U+00XX instead of U+f0XX */
    if (!(ret = pFT_Get_Char_Index(font->ft_face, glyph)))
        ret = pFT_Get_Char_Index(font->ft_face, glyph - 0xf000);

    return ret;
}

6513
static FT_UInt get_glyph_index(const GdiFont *font, UINT glyph)
6514
{
6515 6516 6517
    FT_UInt ret;
    WCHAR wc;
    char buf;
6518

6519 6520
    if (font->ft_face->charmap->encoding == FT_ENCODING_NONE)
    {
6521
        BOOL default_used;
6522
        BOOL *default_used_pointer;
6523

6524 6525 6526 6527
        default_used_pointer = NULL;
        default_used = FALSE;
        if (codepage_sets_default_used(font->codepage))
            default_used_pointer = &default_used;
6528 6529 6530
        wc = (WCHAR)glyph;
        if (!WideCharToMultiByte(font->codepage, 0, &wc, 1, &buf, sizeof(buf), NULL, default_used_pointer) ||
            default_used)
6531
        {
6532 6533 6534 6535 6536 6537 6538 6539 6540
            if (font->codepage == CP_SYMBOL)
            {
                ret = get_glyph_index_symbol(font, glyph);
                if (!ret)
                {
                    if (WideCharToMultiByte(CP_ACP, 0, &wc, 1, &buf, 1, NULL, NULL))
                        ret = get_glyph_index_symbol(font, buf);
                }
            }
6541 6542 6543
            else
                ret = 0;
        }
6544 6545
        else
            ret = pFT_Get_Char_Index(font->ft_face, (unsigned char)buf);
6546
        TRACE("%04x (%02x) -> ret %d def_used %d\n", glyph, (unsigned char)buf, ret, default_used);
6547
        return ret;
6548 6549
    }

6550
    if (font->ft_face->charmap->encoding == FT_ENCODING_MS_SYMBOL)
6551
    {
6552 6553 6554 6555 6556 6557 6558 6559
        ret = get_glyph_index_symbol(font, glyph);
        if (!ret)
        {
            wc = (WCHAR)glyph;
            if (WideCharToMultiByte(CP_ACP, 0, &wc, 1, &buf, 1, NULL, NULL))
                ret = get_glyph_index_symbol(font, (unsigned char)buf);
        }
        return ret;
6560 6561
    }

6562
    return pFT_Get_Char_Index(font->ft_face, glyph);
6563 6564
}

6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592
/* helper for freetype_GetGlyphIndices */
static FT_UInt get_gdi_glyph_index(const GdiFont *font, UINT glyph)
{
    WCHAR wc = (WCHAR)glyph;
    BOOL default_used = FALSE;
    BOOL *default_used_pointer = NULL;
    FT_UInt ret;
    char buf;

    if(font->ft_face->charmap->encoding != FT_ENCODING_NONE)
        return get_glyph_index(font, glyph);

    if (codepage_sets_default_used(font->codepage))
        default_used_pointer = &default_used;
    if(!WideCharToMultiByte(font->codepage, 0, &wc, 1, &buf, sizeof(buf), NULL, default_used_pointer)
       || default_used)
    {
        if (font->codepage == CP_SYMBOL && wc < 0x100)
            ret = (unsigned char)wc;
        else
            ret = 0;
    }
    else
        ret = (unsigned char)buf;
    TRACE("%04x (%02x) -> ret %d def_used %d\n", glyph, (unsigned char)buf, ret, default_used);
    return ret;
}

6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611
static FT_UInt get_default_char_index(GdiFont *font)
{
    FT_UInt default_char;

    if (FT_IS_SFNT(font->ft_face))
    {
        TT_OS2 *pOS2 = pFT_Get_Sfnt_Table(font->ft_face, ft_sfnt_os2);
        default_char = (pOS2->usDefaultChar ? get_glyph_index(font, pOS2->usDefaultChar) : 0);
    }
    else
    {
        TEXTMETRICW textm;
        get_text_metrics(font, &textm);
        default_char = textm.tmDefaultChar;
    }

    return default_char;
}

6612
/*************************************************************
6613
 * freetype_GetGlyphIndices
6614
 */
6615
static DWORD CDECL freetype_GetGlyphIndices( PHYSDEV dev, LPCWSTR lpstr, INT count, LPWORD pgi, DWORD flags )
6616
{
6617
    struct freetype_physdev *physdev = get_freetype_dev( dev );
6618
    int i;
6619 6620
    WORD default_char;
    BOOL got_default = FALSE;
6621

6622 6623 6624 6625 6626 6627
    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetGlyphIndices );
        return dev->funcs->pGetGlyphIndices( dev, lpstr, count, pgi, flags );
    }

6628 6629 6630 6631 6632
    if (flags & GGI_MARK_NONEXISTING_GLYPHS)
    {
        default_char = 0xffff;  /* XP would use 0x1f for bitmap fonts */
        got_default = TRUE;
    }
6633

6634 6635 6636
    GDI_CheckNotLock();
    EnterCriticalSection( &freetype_cs );

6637
    for(i = 0; i < count; i++)
6638
    {
6639
        pgi[i] = get_gdi_glyph_index(physdev->font, lpstr[i]);
6640 6641
        if  (pgi[i] == 0)
        {
6642
            if (!got_default)
6643
            {
6644
                default_char = get_default_char_index(physdev->font);
6645
                got_default = TRUE;
6646 6647 6648
            }
            pgi[i] = default_char;
        }
6649 6650
        else
            pgi[i] = get_GSUB_vert_glyph(physdev->font, pgi[i]);
6651
    }
6652
    LeaveCriticalSection( &freetype_cs );
6653 6654 6655
    return count;
}

6656 6657 6658 6659 6660 6661
static inline BOOL is_identity_FMAT2(const FMAT2 *matrix)
{
    static const FMAT2 identity = { 1.0, 0.0, 0.0, 1.0 };
    return !memcmp(matrix, &identity, sizeof(FMAT2));
}

6662 6663 6664 6665 6666 6667
static inline BOOL is_identity_MAT2(const MAT2 *matrix)
{
    static const MAT2 identity = { {0,1}, {0,0}, {0,0}, {0,1} };
    return !memcmp(matrix, &identity, sizeof(MAT2));
}

6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681
static inline FT_Vector normalize_vector(FT_Vector *vec)
{
    FT_Vector out;
    FT_Fixed len;
    len = pFT_Vector_Length(vec);
    if (len) {
        out.x = (vec->x << 6) / len;
        out.y = (vec->y << 6) / len;
    }
    else
        out.x = out.y = 0;
    return out;
}

6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794
/* get_glyph_outline() glyph transform matrices index */
enum matrices_index
{
    matrix_hori,
    matrix_vert,
    matrix_unrotated
};

static BOOL get_transform_matrices( GdiFont *font, BOOL vertical, const MAT2 *user_transform,
                                    FT_Matrix matrices[3] )
{
    static const FT_Matrix identity_mat = { (1 << 16), 0, 0, (1 << 16) };
    BOOL needs_transform = FALSE;
    double width_ratio;
    int i;

    matrices[matrix_unrotated] = identity_mat;

    /* Scaling factor */
    if (font->aveWidth)
    {
        TEXTMETRICW tm;
        get_text_metrics( font, &tm );

        width_ratio = (double)font->aveWidth;
        width_ratio /= (double)font->potm->otmTextMetrics.tmAveCharWidth;
    }
    else
        width_ratio = font->scale_y;

    /* Scaling transform */
    if (width_ratio != 1.0 || font->scale_y != 1.0)
    {
        FT_Matrix scale_mat;
        scale_mat.xx = FT_FixedFromFloat( width_ratio );
        scale_mat.xy = 0;
        scale_mat.yx = 0;
        scale_mat.yy = FT_FixedFromFloat( font->scale_y );

        pFT_Matrix_Multiply( &scale_mat, &matrices[matrix_unrotated] );
        needs_transform = TRUE;
    }

    /* Slant transform */
    if (font->fake_italic)
    {
        FT_Matrix slant_mat;
        slant_mat.xx = (1 << 16);
        slant_mat.xy = (1 << 16) >> 2;
        slant_mat.yx = 0;
        slant_mat.yy = (1 << 16);

        pFT_Matrix_Multiply( &slant_mat, &matrices[matrix_unrotated] );
        needs_transform = TRUE;
    }

    /* Rotation transform */
    matrices[matrix_hori] = matrices[matrix_unrotated];
    if (font->orientation % 3600)
    {
        FT_Matrix rotation_mat;
        FT_Vector angle;

        pFT_Vector_Unit( &angle, MulDiv( 1 << 16, font->orientation, 10 ) );
        rotation_mat.xx =  angle.x;
        rotation_mat.xy = -angle.y;
        rotation_mat.yx =  angle.y;
        rotation_mat.yy =  angle.x;
        pFT_Matrix_Multiply( &rotation_mat, &matrices[matrix_hori] );
        needs_transform = TRUE;
    }

    /* Vertical transform */
    matrices[matrix_vert] = matrices[matrix_hori];
    if (vertical)
    {
        FT_Matrix vertical_mat = { 0, -(1 << 16), 1 << 16, 0 }; /* 90 degrees rotation */

        pFT_Matrix_Multiply( &vertical_mat, &matrices[matrix_vert] );
        needs_transform = TRUE;
    }

    /* World transform */
    if (!is_identity_FMAT2( &font->font_desc.matrix ))
    {
        FT_Matrix world_mat;
        world_mat.xx =  FT_FixedFromFloat( font->font_desc.matrix.eM11 );
        world_mat.xy = -FT_FixedFromFloat( font->font_desc.matrix.eM21 );
        world_mat.yx = -FT_FixedFromFloat( font->font_desc.matrix.eM12 );
        world_mat.yy =  FT_FixedFromFloat( font->font_desc.matrix.eM22 );

        for (i = 0; i < 3; i++)
            pFT_Matrix_Multiply( &world_mat, &matrices[i] );
        needs_transform = TRUE;
    }

    /* Extra transformation specified by caller */
    if (!is_identity_MAT2( user_transform ))
    {
        FT_Matrix user_mat;
        user_mat.xx = FT_FixedFromFIXED( user_transform->eM11 );
        user_mat.xy = FT_FixedFromFIXED( user_transform->eM21 );
        user_mat.yx = FT_FixedFromFIXED( user_transform->eM12 );
        user_mat.yy = FT_FixedFromFIXED( user_transform->eM22 );

        for (i = 0; i < 3; i++)
            pFT_Matrix_Multiply( &user_mat, &matrices[i] );
        needs_transform = TRUE;
    }

    return needs_transform;
}

6795
static BOOL get_bold_glyph_outline(FT_GlyphSlot glyph, LONG ppem, FT_Glyph_Metrics *metrics)
6796 6797
{
    FT_Error err;
6798 6799
    FT_Pos strength;
    FT_BBox bbox;
6800

6801 6802 6803 6804
    if(glyph->format != FT_GLYPH_FORMAT_OUTLINE)
        return FALSE;
    if(!pFT_Outline_Embolden)
        return FALSE;
6805

6806 6807 6808 6809 6810
    strength = MulDiv(ppem, 1 << 6, 24);
    err = pFT_Outline_Embolden(&glyph->outline, strength);
    if(err) {
        TRACE("FT_Ouline_Embolden returns %d\n", err);
        return FALSE;
6811
    }
6812 6813 6814 6815 6816 6817 6818 6819 6820

    pFT_Outline_Get_CBox(&glyph->outline, &bbox);
    metrics->width = bbox.xMax - bbox.xMin;
    metrics->height = bbox.yMax - bbox.yMin;
    metrics->horiBearingX = bbox.xMin;
    metrics->horiBearingY = bbox.yMax;
    metrics->vertBearingX = metrics->horiBearingX - metrics->horiAdvance / 2;
    metrics->vertBearingY = (metrics->vertAdvance - metrics->height) / 2;
    return TRUE;
6821 6822
}

6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833
static inline BYTE get_max_level( UINT format )
{
    switch( format )
    {
    case GGO_GRAY2_BITMAP: return 4;
    case GGO_GRAY4_BITMAP: return 16;
    case GGO_GRAY8_BITMAP: return 64;
    }
    return 255;
}

6834
extern const unsigned short vertical_orientation_table[] DECLSPEC_HIDDEN;
6835 6836 6837

static BOOL check_unicode_tategaki(WCHAR uchar)
{
6838
    unsigned short orientation = vertical_orientation_table[vertical_orientation_table[vertical_orientation_table[uchar >> 8]+((uchar >> 4) & 0x0f)]+ (uchar & 0xf)];
6839

6840 6841 6842
    /* We only reach this code if typographical substitution did not occur */
    /* Type: U or Type: Tu */
    return (orientation ==  1 || orientation == 3);
6843 6844
}

6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889
static FT_Vector get_advance_metric(GdiFont *incoming_font, GdiFont *font,
                                    const FT_Glyph_Metrics *metrics,
                                    const FT_Matrix *transMat, BOOL vertical_metrics)
{
    FT_Vector adv;
    FT_Fixed base_advance, em_scale = 0;
    BOOL fixed_pitch_full = FALSE;

    if (vertical_metrics)
        base_advance = metrics->vertAdvance;
    else
        base_advance = metrics->horiAdvance;

    adv.x = base_advance;
    adv.y = 0;

    /* In fixed-pitch font, we adjust the fullwidth character advance so that
       they have double halfwidth character width. E.g. if the font is 19 ppem,
       we return 20 (not 19) for fullwidth characters as we return 10 for
       halfwidth characters. */
    if(FT_IS_SCALABLE(incoming_font->ft_face) &&
       (incoming_font->potm || get_outline_text_metrics(incoming_font)) &&
       !(incoming_font->potm->otmTextMetrics.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
        UINT avg_advance;
        em_scale = MulDiv(incoming_font->ppem, 1 << 16,
                          incoming_font->ft_face->units_per_EM);
        avg_advance = pFT_MulFix(incoming_font->ntmAvgWidth, em_scale);
        fixed_pitch_full = (avg_advance > 0 &&
                            (base_advance + 63) >> 6 ==
                            pFT_MulFix(incoming_font->ntmAvgWidth*2, em_scale));
        if (fixed_pitch_full && !transMat)
            adv.x = (avg_advance * 2) << 6;
    }

    if (transMat) {
        pFT_Vector_Transform(&adv, transMat);
        if (fixed_pitch_full && adv.y == 0) {
            FT_Vector vec;
            vec.x = incoming_font->ntmAvgWidth;
            vec.y = 0;
            pFT_Vector_Transform(&vec, transMat);
            adv.x = (pFT_MulFix(vec.x, em_scale) * 2) << 6;
        }
    }

6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901
    if (font->fake_bold) {
        if (!transMat)
            adv.x += 1 << 6;
        else {
            FT_Vector fake_bold_adv, vec = { 1 << 6, 0 };
            pFT_Vector_Transform(&vec, transMat);
            fake_bold_adv = normalize_vector(&vec);
            adv.x += fake_bold_adv.x;
            adv.y += fake_bold_adv.y;
        }
    }

6902 6903 6904 6905 6906
    adv.x = (adv.x + 63) & -64;
    adv.y = -((adv.y + 63) & -64);
    return adv;
}

6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035
static FT_BBox get_transformed_bbox( const FT_Glyph_Metrics *metrics,
                                     BOOL needs_transform, const FT_Matrix metrices[3] )
{
    FT_BBox bbox = { 0, 0, 0, 0 };

    if (!needs_transform)
    {
        bbox.xMin = (metrics->horiBearingX) & -64;
        bbox.xMax = (metrics->horiBearingX + metrics->width + 63) & -64;
        bbox.yMax = (metrics->horiBearingY + 63) & -64;
        bbox.yMin = (metrics->horiBearingY - metrics->height) & -64;
    }
    else
    {
        FT_Vector vec;
        INT xc, yc;

        for (xc = 0; xc < 2; xc++)
        {
            for (yc = 0; yc < 2; yc++)
            {
                vec.x = metrics->horiBearingX + xc * metrics->width;
                vec.y = metrics->horiBearingY - yc * metrics->height;
                TRACE( "Vec %ld,i %ld\n", vec.x, vec.y );
                pFT_Vector_Transform( &vec, &metrices[matrix_vert] );
                if (xc == 0 && yc == 0)
                {
                    bbox.xMin = bbox.xMax = vec.x;
                    bbox.yMin = bbox.yMax = vec.y;
                }
                else
                {
                    if      (vec.x < bbox.xMin) bbox.xMin = vec.x;
                    else if (vec.x > bbox.xMax) bbox.xMax = vec.x;
                    if      (vec.y < bbox.yMin) bbox.yMin = vec.y;
                    else if (vec.y > bbox.yMax) bbox.yMax = vec.y;
                }
            }
        }
        bbox.xMin = bbox.xMin & -64;
        bbox.xMax = (bbox.xMax + 63) & -64;
        bbox.yMin = bbox.yMin & -64;
        bbox.yMax = (bbox.yMax + 63) & -64;
        TRACE( "transformed box: (%ld, %ld - %ld, %ld)\n", bbox.xMin, bbox.yMax, bbox.xMax, bbox.yMin );
    }

    return bbox;
}

static void compute_metrics( GdiFont *incoming_font, GdiFont *font,
                             FT_BBox bbox, const FT_Glyph_Metrics *metrics,
                             BOOL vertical, BOOL vertical_metrics,
                             BOOL needs_transform, const FT_Matrix matrices[3],
                             GLYPHMETRICS *gm, ABC *abc )
{
    FT_Vector adv, vec, origin;

    if (!needs_transform)
    {
        adv = get_advance_metric( incoming_font, font, metrics, NULL, vertical_metrics );
        gm->gmCellIncX = adv.x >> 6;
        gm->gmCellIncY = 0;
        origin.x = bbox.xMin;
        origin.y = bbox.yMax;
        abc->abcA = origin.x >> 6;
        abc->abcB = (metrics->width + 63) >> 6;
    }
    else
    {
        FT_Pos lsb;

        if (vertical && (font->potm || get_outline_text_metrics( font )))
        {
            if (vertical_metrics)
                lsb = metrics->horiBearingY + metrics->vertBearingY;
            else
                lsb = metrics->vertAdvance + (font->potm->otmDescent << 6);
            vec.x = lsb;
            vec.y = font->potm->otmDescent << 6;
            TRACE( "Vec %ld,%ld\n", vec.x>>6, vec.y>>6 );
            pFT_Vector_Transform( &vec, &matrices[matrix_hori] );
            origin.x = (vec.x + bbox.xMin) & -64;
            origin.y = (vec.y + bbox.yMax + 63) & -64;
            lsb -= metrics->horiBearingY;
        }
        else
        {
            origin.x = bbox.xMin;
            origin.y = bbox.yMax;
            lsb = metrics->horiBearingX;
        }

        adv = get_advance_metric( incoming_font, font, metrics, &matrices[matrix_hori],
                                  vertical_metrics );
        gm->gmCellIncX = adv.x >> 6;
        gm->gmCellIncY = adv.y >> 6;

        adv = get_advance_metric( incoming_font, font, metrics, &matrices[matrix_unrotated],
                                  vertical_metrics );
        adv.x = pFT_Vector_Length( &adv );
        adv.y = 0;

        vec.x = lsb;
        vec.y = 0;
        pFT_Vector_Transform( &vec, &matrices[matrix_unrotated] );
        if (lsb > 0) abc->abcA = pFT_Vector_Length( &vec ) >> 6;
        else abc->abcA = -((pFT_Vector_Length( &vec ) + 63) >> 6);

        /* We use lsb again to avoid rounding errors */
        vec.x = lsb + (vertical ? metrics->height : metrics->width);
        vec.y = 0;
        pFT_Vector_Transform( &vec, &matrices[matrix_unrotated] );
        abc->abcB = ((pFT_Vector_Length( &vec ) + 63) >> 6) - abc->abcA;
    }
    if (!abc->abcB) abc->abcB = 1;
    abc->abcC = (adv.x >> 6) - abc->abcA - abc->abcB;

    gm->gmptGlyphOrigin.x = origin.x >> 6;
    gm->gmptGlyphOrigin.y = origin.y >> 6;
    gm->gmBlackBoxX = (bbox.xMax - bbox.xMin) >> 6;
    gm->gmBlackBoxY = (bbox.yMax - bbox.yMin) >> 6;
    if (!gm->gmBlackBoxX) gm->gmBlackBoxX = 1;
    if (!gm->gmBlackBoxY) gm->gmBlackBoxY = 1;

    TRACE( "gm: %u, %u, %s, %d, %d abc %d, %u, %d\n",
           gm->gmBlackBoxX, gm->gmBlackBoxY, wine_dbgstr_point(&gm->gmptGlyphOrigin),
           gm->gmCellIncX, gm->gmCellIncY, abc->abcA, abc->abcB, abc->abcC );
}

7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331

static const BYTE masks[8] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};

static DWORD get_mono_glyph_bitmap( FT_GlyphSlot glyph, FT_BBox bbox,
                                    BOOL fake_bold, BOOL needs_transform, FT_Matrix matrices[3],
                                    DWORD buflen, BYTE *buf )
{
    DWORD width  = (bbox.xMax - bbox.xMin ) >> 6;
    DWORD height = (bbox.yMax - bbox.yMin ) >> 6;
    DWORD pitch  = ((width + 31) >> 5) << 2;
    DWORD needed = pitch * height;
    FT_Bitmap ft_bitmap;
    BYTE *src, *dst;
    INT w, h, x;

    if (!buf || !buflen) return needed;
    if (!needed) return GDI_ERROR;  /* empty glyph */
    if (needed > buflen) return GDI_ERROR;

    switch (glyph->format)
    {
    case FT_GLYPH_FORMAT_BITMAP:
        src = glyph->bitmap.buffer;
        dst = buf;
        w = min( pitch, (glyph->bitmap.width + 7) >> 3 );
        h = min( height, glyph->bitmap.rows );
        while (h--)
        {
            if (!fake_bold)
                memcpy( dst, src, w );
            else
            {
                dst[0] = 0;
                for (x = 0; x < w; x++)
                {
                    dst[x] = (dst[x] & 0x80) | (src[x] >> 1) | src[x];
                    if (x + 1 < pitch)
                        dst[x + 1] = (src[x] & 0x01) << 7;
                }
            }
            src += glyph->bitmap.pitch;
            dst += pitch;
        }
        break;

    case FT_GLYPH_FORMAT_OUTLINE:
        ft_bitmap.width = width;
        ft_bitmap.rows = height;
        ft_bitmap.pitch = pitch;
        ft_bitmap.pixel_mode = FT_PIXEL_MODE_MONO;
        ft_bitmap.buffer = buf;

        if (needs_transform)
            pFT_Outline_Transform( &glyph->outline, &matrices[matrix_vert] );
        pFT_Outline_Translate( &glyph->outline, -bbox.xMin, -bbox.yMin );

        /* Note: FreeType will only set 'black' bits for us. */
        memset( buf, 0, buflen );
        pFT_Outline_Get_Bitmap( library, &glyph->outline, &ft_bitmap );
        break;

    default:
        FIXME( "loaded glyph format %x\n", glyph->format );
        return GDI_ERROR;
    }

    return needed;
}

static DWORD get_antialias_glyph_bitmap( FT_GlyphSlot glyph, FT_BBox bbox, UINT format,
                                         BOOL fake_bold, BOOL needs_transform, FT_Matrix matrices[3],
                                         DWORD buflen, BYTE *buf )
{
    DWORD width  = (bbox.xMax - bbox.xMin ) >> 6;
    DWORD height = (bbox.yMax - bbox.yMin ) >> 6;
    DWORD pitch  = (width + 3) / 4 * 4;
    DWORD needed = pitch * height;
    FT_Bitmap ft_bitmap;
    INT w, h, x, max_level;
    BYTE *src, *dst;

    if (!buf || !buflen) return needed;
    if (!needed) return GDI_ERROR;  /* empty glyph */
    if (needed > buflen) return GDI_ERROR;

    max_level = get_max_level( format );

    switch (glyph->format)
    {
    case FT_GLYPH_FORMAT_BITMAP:
        src = glyph->bitmap.buffer;
        dst = buf;
        memset( buf, 0, buflen );

        w = min( pitch, glyph->bitmap.width );
        h = min( height, glyph->bitmap.rows );
        while (h--)
        {
            for (x = 0; x < w; x++)
            {
                if (src[x / 8] & masks[x % 8])
                {
                    dst[x] = max_level;
                    if (fake_bold && x + 1 < pitch) dst[x + 1] = max_level;
                }
            }
            src += glyph->bitmap.pitch;
            dst += pitch;
        }
        break;

    case FT_GLYPH_FORMAT_OUTLINE:
        ft_bitmap.width = width;
        ft_bitmap.rows = height;
        ft_bitmap.pitch = pitch;
        ft_bitmap.pixel_mode = FT_PIXEL_MODE_GRAY;
        ft_bitmap.buffer = buf;

        if (needs_transform)
            pFT_Outline_Transform( &glyph->outline, &matrices[matrix_vert] );
        pFT_Outline_Translate( &glyph->outline, -bbox.xMin, -bbox.yMin );

        memset( buf, 0, buflen );
        pFT_Outline_Get_Bitmap( library, &glyph->outline, &ft_bitmap );

        if (max_level != 255)
        {
            INT row, col;
            BYTE *ptr, *start;

            for (row = 0, start = buf; row < height; row++)
            {
                for (col = 0, ptr = start; col < width; col++, ptr++)
                    *ptr = (((int)*ptr) * (max_level + 1)) / 256;
                start += pitch;
            }
        }
        break;

    default:
        FIXME("loaded glyph format %x\n", glyph->format);
        return GDI_ERROR;
    }

    return needed;
}

static DWORD get_subpixel_glyph_bitmap( FT_GlyphSlot glyph, FT_BBox bbox, UINT format,
                                        BOOL fake_bold, BOOL needs_transform, FT_Matrix matrices[3],
                                        GLYPHMETRICS *gm, DWORD buflen, BYTE *buf )
{
    DWORD width  = (bbox.xMax - bbox.xMin ) >> 6;
    DWORD height = (bbox.yMax - bbox.yMin ) >> 6;
    DWORD pitch, needed = 0;
    BYTE *src, *dst;
    INT  w, h, x;

    switch (glyph->format)
    {
    case FT_GLYPH_FORMAT_BITMAP:
        pitch  = width * 4;
        needed = pitch * height;

        if (!buf || !buflen) break;
        if (!needed) return GDI_ERROR;  /* empty glyph */
        if (needed > buflen) return GDI_ERROR;

        src = glyph->bitmap.buffer;
        dst = buf;
        memset( buf, 0, buflen );

        w = min( width, glyph->bitmap.width );
        h = min( height, glyph->bitmap.rows );
        while (h--)
        {
            for (x = 0; x < w; x++)
            {
                if ( src[x / 8] & masks[x % 8] )
                {
                    ((unsigned int *)dst)[x] = ~0u;
                    if (fake_bold && x + 1 < width) ((unsigned int *)dst)[x + 1] = ~0u;
                }
            }
            src += glyph->bitmap.pitch;
            dst += pitch;
        }
        break;

    case FT_GLYPH_FORMAT_OUTLINE:
      {
        INT src_pitch, src_width, src_height, x_shift, y_shift;
        INT sub_stride, hmul, vmul;
        const INT *sub_order;
        const INT rgb_order[3] = { 0, 1, 2 };
        const INT bgr_order[3] = { 2, 1, 0 };
        FT_Render_Mode render_mode =
            (format == WINE_GGO_HRGB_BITMAP ||
             format == WINE_GGO_HBGR_BITMAP) ? FT_RENDER_MODE_LCD : FT_RENDER_MODE_LCD_V;

        if (!width || !height) /* empty glyph */
        {
            if (!buf || !buflen) break;
            return GDI_ERROR;
        }

        if ( render_mode == FT_RENDER_MODE_LCD)
        {
            gm->gmBlackBoxX += 2;
            gm->gmptGlyphOrigin.x -= 1;
            bbox.xMin -= (1 << 6);
        }
        else
        {
            gm->gmBlackBoxY += 2;
            gm->gmptGlyphOrigin.y += 1;
            bbox.yMax += (1 << 6);
        }

        width  = gm->gmBlackBoxX;
        height = gm->gmBlackBoxY;
        pitch  = width * 4;
        needed = pitch * height;

        if (!buf || !buflen) return needed;
        if (needed > buflen) return GDI_ERROR;

        if (needs_transform)
            pFT_Outline_Transform( &glyph->outline, &matrices[matrix_vert] );

#ifdef FT_LCD_FILTER_H
        if (pFT_Library_SetLcdFilter)
            pFT_Library_SetLcdFilter( library, FT_LCD_FILTER_DEFAULT );
#endif
        pFT_Render_Glyph( glyph, render_mode );

        src_pitch = glyph->bitmap.pitch;
        src_width = glyph->bitmap.width;
        src_height = glyph->bitmap.rows;
        src = glyph->bitmap.buffer;
        dst = buf;
        memset( buf, 0, buflen );

        sub_order  = (format == WINE_GGO_HRGB_BITMAP ||
                      format == WINE_GGO_VRGB_BITMAP) ? rgb_order : bgr_order;
        sub_stride = render_mode == FT_RENDER_MODE_LCD ? 1 : src_pitch;
        hmul       = render_mode == FT_RENDER_MODE_LCD ? 3 : 1;
        vmul       = render_mode == FT_RENDER_MODE_LCD ? 1 : 3;

        x_shift = glyph->bitmap_left - (bbox.xMin >> 6);
        if ( x_shift < 0 )
        {
            src += hmul * -x_shift;
            src_width -= hmul * -x_shift;
        }
        else if ( x_shift > 0 )
        {
            dst += x_shift * sizeof(unsigned int);
            width -= x_shift;
        }

        y_shift = (bbox.yMax >> 6) - glyph->bitmap_top;
        if ( y_shift < 0 )
        {
            src += src_pitch * vmul * -y_shift;
            src_height -= vmul * -y_shift;
        }
        else if ( y_shift > 0 )
        {
            dst += y_shift * pitch;
            height -= y_shift;
        }

        w = min( width, src_width / hmul );
        h = min( height, src_height / vmul );
        while (h--)
        {
            for (x = 0; x < w; x++)
            {
                ((unsigned int *)dst)[x] =
                    ((unsigned int)src[hmul * x + sub_stride * sub_order[0]] << 16) |
                    ((unsigned int)src[hmul * x + sub_stride * sub_order[1]] << 8) |
                    ((unsigned int)src[hmul * x + sub_stride * sub_order[2]]);
            }
            src += src_pitch * vmul;
            dst += pitch;
        }
        break;
      }
    default:
        FIXME ( "loaded glyph format %x\n", glyph->format );
        return GDI_ERROR;
    }

    return needed;
}

7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528
static unsigned int get_native_glyph_outline(FT_Outline *outline, unsigned int buflen, char *buf)
{
    TTPOLYGONHEADER *pph;
    TTPOLYCURVE *ppc;
    unsigned int needed = 0, point = 0, contour, first_pt;
    unsigned int pph_start, cpfx;
    DWORD type;

    for (contour = 0; contour < outline->n_contours; contour++)
    {
        /* Ignore contours containing one point */
        if (point == outline->contours[contour])
        {
            point++;
            continue;
        }

        pph_start = needed;
        pph = (TTPOLYGONHEADER *)(buf + needed);
        first_pt = point;
        if (buf)
        {
            pph->dwType = TT_POLYGON_TYPE;
            FTVectorToPOINTFX(&outline->points[point], &pph->pfxStart);
        }
        needed += sizeof(*pph);
        point++;
        while (point <= outline->contours[contour])
        {
            ppc = (TTPOLYCURVE *)(buf + needed);
            type = outline->tags[point] & FT_Curve_Tag_On ?
                TT_PRIM_LINE : TT_PRIM_QSPLINE;
            cpfx = 0;
            do
            {
                if (buf)
                    FTVectorToPOINTFX(&outline->points[point], &ppc->apfx[cpfx]);
                cpfx++;
                point++;
            } while (point <= outline->contours[contour] &&
                    (outline->tags[point] & FT_Curve_Tag_On) ==
                    (outline->tags[point-1] & FT_Curve_Tag_On));
            /* At the end of a contour Windows adds the start point, but
               only for Beziers */
            if (point > outline->contours[contour] &&
               !(outline->tags[point-1] & FT_Curve_Tag_On))
            {
                if (buf)
                    FTVectorToPOINTFX(&outline->points[first_pt], &ppc->apfx[cpfx]);
                cpfx++;
            }
            else if (point <= outline->contours[contour] &&
                      outline->tags[point] & FT_Curve_Tag_On)
            {
                /* add closing pt for bezier */
                if (buf)
                    FTVectorToPOINTFX(&outline->points[point], &ppc->apfx[cpfx]);
                cpfx++;
                point++;
            }
            if (buf)
            {
                ppc->wType = type;
                ppc->cpfx = cpfx;
            }
            needed += sizeof(*ppc) + (cpfx - 1) * sizeof(POINTFX);
        }
        if (buf)
            pph->cb = needed - pph_start;
    }
    return needed;
}

static unsigned int get_bezier_glyph_outline(FT_Outline *outline, unsigned int buflen, char *buf)
{
    /* Convert the quadratic Beziers to cubic Beziers.
       The parametric eqn for a cubic Bezier is, from PLRM:
       r(t) = at^3 + bt^2 + ct + r0
       with the control points:
       r1 = r0 + c/3
       r2 = r1 + (c + b)/3
       r3 = r0 + c + b + a

       A quadratic Bezier has the form:
       p(t) = (1-t)^2 p0 + 2(1-t)t p1 + t^2 p2

       So equating powers of t leads to:
       r1 = 2/3 p1 + 1/3 p0
       r2 = 2/3 p1 + 1/3 p2
       and of course r0 = p0, r3 = p2
    */
    int contour, point = 0, first_pt;
    TTPOLYGONHEADER *pph;
    TTPOLYCURVE *ppc;
    DWORD pph_start, cpfx, type;
    FT_Vector cubic_control[4];
    unsigned int needed = 0;

    for (contour = 0; contour < outline->n_contours; contour++)
    {
        pph_start = needed;
        pph = (TTPOLYGONHEADER *)(buf + needed);
        first_pt = point;
        if (buf)
        {
            pph->dwType = TT_POLYGON_TYPE;
            FTVectorToPOINTFX(&outline->points[point], &pph->pfxStart);
        }
        needed += sizeof(*pph);
        point++;
        while (point <= outline->contours[contour])
        {
            ppc = (TTPOLYCURVE *)(buf + needed);
            type = outline->tags[point] & FT_Curve_Tag_On ?
                TT_PRIM_LINE : TT_PRIM_CSPLINE;
            cpfx = 0;
            do
            {
                if (type == TT_PRIM_LINE)
                {
                    if (buf)
                        FTVectorToPOINTFX(&outline->points[point], &ppc->apfx[cpfx]);
                    cpfx++;
                    point++;
                }
                else
                {
                    /* Unlike QSPLINEs, CSPLINEs always have their endpoint
                       so cpfx = 3n */

                    /* FIXME: Possible optimization in endpoint calculation
                       if there are two consecutive curves */
                    cubic_control[0] = outline->points[point-1];
                    if (!(outline->tags[point-1] & FT_Curve_Tag_On))
                    {
                        cubic_control[0].x += outline->points[point].x + 1;
                        cubic_control[0].y += outline->points[point].y + 1;
                        cubic_control[0].x >>= 1;
                        cubic_control[0].y >>= 1;
                    }
                    if (point+1 > outline->contours[contour])
                        cubic_control[3] = outline->points[first_pt];
                    else
                    {
                        cubic_control[3] = outline->points[point+1];
                        if (!(outline->tags[point+1] & FT_Curve_Tag_On))
                        {
                            cubic_control[3].x += outline->points[point].x + 1;
                            cubic_control[3].y += outline->points[point].y + 1;
                            cubic_control[3].x >>= 1;
                            cubic_control[3].y >>= 1;
                        }
                    }
                    /* r1 = 1/3 p0 + 2/3 p1
                       r2 = 1/3 p2 + 2/3 p1 */
                    cubic_control[1].x = (2 * outline->points[point].x + 1) / 3;
                    cubic_control[1].y = (2 * outline->points[point].y + 1) / 3;
                    cubic_control[2] = cubic_control[1];
                    cubic_control[1].x += (cubic_control[0].x + 1) / 3;
                    cubic_control[1].y += (cubic_control[0].y + 1) / 3;
                    cubic_control[2].x += (cubic_control[3].x + 1) / 3;
                    cubic_control[2].y += (cubic_control[3].y + 1) / 3;
                    if (buf)
                    {
                        FTVectorToPOINTFX(&cubic_control[1], &ppc->apfx[cpfx]);
                        FTVectorToPOINTFX(&cubic_control[2], &ppc->apfx[cpfx+1]);
                        FTVectorToPOINTFX(&cubic_control[3], &ppc->apfx[cpfx+2]);
                    }
                    cpfx += 3;
                    point++;
                }
            } while (point <= outline->contours[contour] &&
                    (outline->tags[point] & FT_Curve_Tag_On) ==
                    (outline->tags[point-1] & FT_Curve_Tag_On));
            /* At the end of a contour Windows adds the start point,
               but only for Beziers and we've already done that.
            */
            if (point <= outline->contours[contour] &&
               outline->tags[point] & FT_Curve_Tag_On)
            {
                /* This is the closing pt of a bezier, but we've already
                   added it, so just inc point and carry on */
                point++;
            }
            if (buf)
            {
                ppc->wType = type;
                ppc->cpfx = cpfx;
            }
            needed += sizeof(*ppc) + (cpfx - 1) * sizeof(POINTFX);
        }
        if (buf)
            pph->cb = needed - pph_start;
    }
    return needed;
}

7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559
static FT_Int get_load_flags( UINT format )
{
    FT_Int load_flags = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;

    if (format & GGO_UNHINTED)
        return load_flags | FT_LOAD_NO_HINTING;

    switch (format & ~GGO_GLYPH_INDEX)
    {
    case GGO_BITMAP:
        load_flags |= FT_LOAD_TARGET_MONO;
        break;
    case GGO_GRAY2_BITMAP:
    case GGO_GRAY4_BITMAP:
    case GGO_GRAY8_BITMAP:
    case WINE_GGO_GRAY16_BITMAP:
        load_flags |= FT_LOAD_TARGET_NORMAL;
        break;
    case WINE_GGO_HRGB_BITMAP:
    case WINE_GGO_HBGR_BITMAP:
        load_flags |= FT_LOAD_TARGET_LCD;
        break;
    case WINE_GGO_VRGB_BITMAP:
    case WINE_GGO_VBGR_BITMAP:
        load_flags |= FT_LOAD_TARGET_LCD_V;
        break;
    }

    return load_flags;
}

7560
static DWORD get_glyph_outline(GdiFont *incoming_font, UINT glyph, UINT format,
7561
                               LPGLYPHMETRICS lpgm, ABC *abc, DWORD buflen, LPVOID buf,
7562
                               const MAT2* lpmat)
7563
{
7564
    GLYPHMETRICS gm;
7565 7566
    FT_Face ft_face = incoming_font->ft_face;
    GdiFont *font = incoming_font;
7567
    FT_Glyph_Metrics metrics;
7568
    FT_UInt glyph_index;
7569
    DWORD needed = 0;
7570
    FT_Error err;
7571
    FT_BBox bbox;
7572
    FT_Int load_flags = get_load_flags(format);
7573
    FT_Matrix matrices[3];
7574
    BOOL needsTransform = FALSE;
7575
    BOOL tategaki = (font->name[0] == '@');
7576
    BOOL vertical_metrics;
7577

7578
    TRACE("%p, %04x, %08x, %p, %08x, %p, %p\n", font, glyph, format, lpgm,
7579 7580
	  buflen, buf, lpmat);

7581 7582 7583 7584
    TRACE("font transform %f %f %f %f\n",
          font->font_desc.matrix.eM11, font->font_desc.matrix.eM12,
          font->font_desc.matrix.eM21, font->font_desc.matrix.eM22);

7585
    if(format & GGO_GLYPH_INDEX) {
7586 7587
        if(font->ft_face->charmap->encoding == FT_ENCODING_NONE) {
            /* Windows bitmap font, e.g. Small Fonts, uses ANSI character code
7588
               as glyph index. "Treasure Adventure Game" depends on this. */
7589 7590 7591 7592
            glyph_index = pFT_Get_Char_Index(font->ft_face, glyph);
            TRACE("translate glyph index %04x -> %04x\n", glyph, glyph_index);
        } else
            glyph_index = glyph;
7593
	format &= ~GGO_GLYPH_INDEX;
7594 7595 7596
        /* TODO: Window also turns off tategaki for glyphs passed in by index
            if their unicode code points fall outside of the range that is
            rotated. */
7597
    } else {
7598 7599
        BOOL vert;
        get_glyph_index_linked(incoming_font, glyph, &font, &glyph_index, &vert);
7600
        ft_face = font->ft_face;
7601 7602
        if (!vert && tategaki)
            tategaki = check_unicode_tategaki(glyph);
7603
    }
7604

7605
    format &= ~GGO_UNHINTED;
7606

7607 7608 7609
    if (format == GGO_METRICS && is_identity_MAT2(lpmat) &&
        get_cached_metrics( font, glyph_index, lpgm, abc ))
        return 1; /* FIXME */
7610

7611
    needsTransform = get_transform_matrices( font, tategaki, lpmat, matrices );
7612

7613 7614 7615
    vertical_metrics = (tategaki && FT_HAS_VERTICAL(ft_face));
    /* there is a freetype bug where vertical metrics are only
       properly scaled and correct in 2.4.0 or greater */
7616
    if (vertical_metrics && FT_SimpleVersion < FT_VERSION_VALUE(2, 4, 0))
7617 7618
        vertical_metrics = FALSE;

7619
    if (needsTransform || format != GGO_BITMAP) load_flags |= FT_LOAD_NO_BITMAP;
7620
    if (vertical_metrics) load_flags |= FT_LOAD_VERTICAL_LAYOUT;
7621 7622 7623 7624 7625 7626 7627 7628

    err = pFT_Load_Glyph(ft_face, glyph_index, load_flags);

    if(err) {
        WARN("FT_Load_Glyph on index %x returns %d\n", glyph_index, err);
        return GDI_ERROR;
    }

7629
    metrics = ft_face->glyph->metrics;
7630 7631 7632 7633
    if(font->fake_bold) {
        if (!get_bold_glyph_outline(ft_face->glyph, font->ppem, &metrics) && metrics.width)
            metrics.width += 1 << 6;
    }
7634

7635 7636 7637 7638 7639 7640
    /* Some poorly-created fonts contain glyphs that exceed the boundaries set
     * by the text metrics. The proper behavior is to clip the glyph metrics to
     * fit within the maximums specified in the text metrics. */
    if(incoming_font->potm || get_outline_text_metrics(incoming_font) ||
        get_bitmap_text_metrics(incoming_font)) {
        TEXTMETRICW *ptm = &incoming_font->potm->otmTextMetrics;
7641 7642
        INT top = min( metrics.horiBearingY, ptm->tmAscent << 6 );
        INT bottom = max( metrics.horiBearingY - metrics.height, -(ptm->tmDescent << 6) );
7643 7644 7645 7646 7647 7648 7649
        metrics.horiBearingY = top;
        metrics.height = top - bottom;

        /* TODO: Are we supposed to clip the width as well...? */
        /* metrics.width = min( metrics.width, ptm->tmMaxCharWidth << 6 ); */
    }

7650 7651 7652 7653
    bbox = get_transformed_bbox( &metrics, needsTransform, matrices );
    compute_metrics( incoming_font, font, bbox, &metrics,
                     tategaki, vertical_metrics, needsTransform, matrices,
                     &gm, abc );
7654

7655
    if ((format == GGO_METRICS || format == GGO_BITMAP || format ==  WINE_GGO_GRAY16_BITMAP) &&
7656
        is_identity_MAT2(lpmat)) /* don't cache custom transforms */
7657
        set_cached_metrics( font, glyph_index, &gm, abc );
7658 7659

    if(format == GGO_METRICS)
7660
    {
7661
        *lpgm = gm;
7662
        return 1; /* FIXME */
7663
    }
7664

7665
    if(ft_face->glyph->format != ft_glyph_format_outline &&
7666
       (format == GGO_NATIVE || format == GGO_BEZIER))
7667
    {
7668
        TRACE("loaded a bitmap\n");
7669 7670 7671
	return GDI_ERROR;
    }

7672 7673
    switch (format)
    {
7674
    case GGO_BITMAP:
7675 7676 7677
        needed = get_mono_glyph_bitmap( ft_face->glyph, bbox, font->fake_bold,
                                        needsTransform, matrices, buflen, buf );
        break;
7678 7679 7680 7681 7682

    case GGO_GRAY2_BITMAP:
    case GGO_GRAY4_BITMAP:
    case GGO_GRAY8_BITMAP:
    case WINE_GGO_GRAY16_BITMAP:
7683 7684
        needed = get_antialias_glyph_bitmap( ft_face->glyph, bbox, format, font->fake_bold,
                                             needsTransform, matrices, buflen, buf );
7685 7686
	break;

7687 7688 7689 7690
    case WINE_GGO_HRGB_BITMAP:
    case WINE_GGO_HBGR_BITMAP:
    case WINE_GGO_VRGB_BITMAP:
    case WINE_GGO_VBGR_BITMAP:
7691 7692
        needed = get_subpixel_glyph_bitmap( ft_face->glyph, bbox, format, font->fake_bold,
                                            needsTransform, matrices, &gm, buflen, buf );
7693 7694
        break;

7695 7696
    case GGO_NATIVE:
      {
7697
        FT_Outline *outline = &ft_face->glyph->outline;
7698

7699
        if(buflen == 0) buf = NULL;
7700

7701
        if (needsTransform && buf)
7702
            pFT_Outline_Transform( outline, &matrices[matrix_vert] );
7703

7704
        needed = get_native_glyph_outline(outline, buflen, NULL);
7705

7706 7707 7708 7709 7710 7711 7712
        if (!buf || !buflen)
            break;
        if (needed > buflen)
            return GDI_ERROR;

        get_native_glyph_outline(outline, buflen, buf);
        break;
7713
      }
7714 7715
    case GGO_BEZIER:
      {
7716 7717
        FT_Outline *outline = &ft_face->glyph->outline;
        if(buflen == 0) buf = NULL;
7718

7719
        if (needsTransform && buf)
7720
            pFT_Outline_Transform( outline, &matrices[matrix_vert] );
7721

7722 7723 7724 7725 7726 7727 7728 7729 7730
        needed = get_bezier_glyph_outline(outline, buflen, NULL);

        if (!buf || !buflen)
            break;
        if (needed > buflen)
            return GDI_ERROR;

        get_bezier_glyph_outline(outline, buflen, buf);
        break;
7731 7732
      }

7733
    default:
7734 7735 7736
        FIXME("Unsupported format %d\n", format);
	return GDI_ERROR;
    }
7737 7738 7739
    if (needed != GDI_ERROR)
        *lpgm = gm;

7740
    return needed;
7741 7742
}

7743
static BOOL get_bitmap_text_metrics(GdiFont *font)
7744 7745 7746 7747 7748 7749 7750 7751
{
    FT_Face ft_face = font->ft_face;
    FT_WinFNT_HeaderRec winfnt_header;
    const DWORD size = offsetof(OUTLINETEXTMETRICW, otmFiller); 
    font->potm = HeapAlloc(GetProcessHeap(), 0, size);
    font->potm->otmSize = size;

#define TM font->potm->otmTextMetrics
7752
    if(!pFT_Get_WinFNT_Header(ft_face, &winfnt_header))
7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766
    {
        TM.tmHeight = winfnt_header.pixel_height;
        TM.tmAscent = winfnt_header.ascent;
        TM.tmDescent = TM.tmHeight - TM.tmAscent;
        TM.tmInternalLeading = winfnt_header.internal_leading;
        TM.tmExternalLeading = winfnt_header.external_leading;
        TM.tmAveCharWidth = winfnt_header.avg_width;
        TM.tmMaxCharWidth = winfnt_header.max_width;
        TM.tmWeight = winfnt_header.weight;
        TM.tmOverhang = 0;
        TM.tmDigitizedAspectX = winfnt_header.horizontal_resolution;
        TM.tmDigitizedAspectY = winfnt_header.vertical_resolution;
        TM.tmFirstChar = winfnt_header.first_char;
        TM.tmLastChar = winfnt_header.last_char;
7767 7768
        TM.tmDefaultChar = winfnt_header.default_char + winfnt_header.first_char;
        TM.tmBreakChar = winfnt_header.break_char + winfnt_header.first_char;
7769
        TM.tmItalic = winfnt_header.italic;
7770 7771
        TM.tmUnderlined = font->underline;
        TM.tmStruckOut = font->strikeout;
7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792
        TM.tmPitchAndFamily = winfnt_header.pitch_and_family;
        TM.tmCharSet = winfnt_header.charset;
    }
    else
    {
        TM.tmAscent = ft_face->size->metrics.ascender >> 6;
        TM.tmDescent = -ft_face->size->metrics.descender >> 6;
        TM.tmHeight = TM.tmAscent + TM.tmDescent;
        TM.tmInternalLeading = TM.tmHeight - ft_face->size->metrics.y_ppem;
        TM.tmExternalLeading = (ft_face->size->metrics.height >> 6) - TM.tmHeight;
        TM.tmMaxCharWidth = ft_face->size->metrics.max_advance >> 6;
        TM.tmAveCharWidth = TM.tmMaxCharWidth * 2 / 3; /* FIXME */
        TM.tmWeight = ft_face->style_flags & FT_STYLE_FLAG_BOLD ? FW_BOLD : FW_NORMAL;
        TM.tmOverhang = 0;
        TM.tmDigitizedAspectX = 96; /* FIXME */
        TM.tmDigitizedAspectY = 96; /* FIXME */
        TM.tmFirstChar = 1;
        TM.tmLastChar = 255;
        TM.tmDefaultChar = 32;
        TM.tmBreakChar = 32;
        TM.tmItalic = ft_face->style_flags & FT_STYLE_FLAG_ITALIC ? 1 : 0;
7793 7794
        TM.tmUnderlined = font->underline;
        TM.tmStruckOut = font->strikeout;
7795
        /* NB inverted meaning of TMPF_FIXED_PITCH */
7796
        TM.tmPitchAndFamily = FT_IS_FIXED_WIDTH(ft_face) ? 0 : TMPF_FIXED_PITCH;
7797 7798
        TM.tmCharSet = font->charset;
    }
7799 7800 7801

    if(font->fake_bold)
        TM.tmWeight = FW_BOLD;
7802 7803 7804 7805 7806
#undef TM

    return TRUE;
}

7807

7808
static void scale_font_metrics(const GdiFont *font, LPTEXTMETRICW ptm)
7809
{
7810
    double scale_x, scale_y;
7811

7812 7813
    if (font->aveWidth)
    {
7814
        scale_x = (double)font->aveWidth;
7815
        scale_x /= (double)font->potm->otmTextMetrics.tmAveCharWidth;
7816
    }
7817 7818 7819
    else
        scale_x = font->scale_y;

7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831
    scale_x *= fabs(font->font_desc.matrix.eM11);
    scale_y = font->scale_y * fabs(font->font_desc.matrix.eM22);

#define SCALE_X(x) (x) = GDI_ROUND((double)(x) * (scale_x))
#define SCALE_Y(y) (y) = GDI_ROUND((double)(y) * (scale_y))

    SCALE_Y(ptm->tmHeight);
    SCALE_Y(ptm->tmAscent);
    SCALE_Y(ptm->tmDescent);
    SCALE_Y(ptm->tmInternalLeading);
    SCALE_Y(ptm->tmExternalLeading);

7832 7833
    SCALE_X(ptm->tmOverhang);
    if(font->fake_bold)
7834
    {
7835 7836
        if(!FT_IS_SCALABLE(font->ft_face))
            ptm->tmOverhang++;
7837 7838 7839
        ptm->tmAveCharWidth++;
        ptm->tmMaxCharWidth++;
    }
7840 7841
    SCALE_X(ptm->tmAveCharWidth);
    SCALE_X(ptm->tmMaxCharWidth);
7842

7843 7844
#undef SCALE_X
#undef SCALE_Y
7845 7846
}

7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863
static void scale_outline_font_metrics(const GdiFont *font, OUTLINETEXTMETRICW *potm)
{
    double scale_x, scale_y;

    if (font->aveWidth)
    {
        scale_x = (double)font->aveWidth;
        scale_x /= (double)font->potm->otmTextMetrics.tmAveCharWidth;
    }
    else
        scale_x = font->scale_y;

    scale_x *= fabs(font->font_desc.matrix.eM11);
    scale_y = font->scale_y * fabs(font->font_desc.matrix.eM22);

    scale_font_metrics(font, &potm->otmTextMetrics);

7864 7865 7866
/* Windows scales these values as signed integers even if they are unsigned */
#define SCALE_X(x) (x) = GDI_ROUND((int)(x) * (scale_x))
#define SCALE_Y(y) (y) = GDI_ROUND((int)(y) * (scale_y))
7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896

    SCALE_Y(potm->otmAscent);
    SCALE_Y(potm->otmDescent);
    SCALE_Y(potm->otmLineGap);
    SCALE_Y(potm->otmsCapEmHeight);
    SCALE_Y(potm->otmsXHeight);
    SCALE_Y(potm->otmrcFontBox.top);
    SCALE_Y(potm->otmrcFontBox.bottom);
    SCALE_X(potm->otmrcFontBox.left);
    SCALE_X(potm->otmrcFontBox.right);
    SCALE_Y(potm->otmMacAscent);
    SCALE_Y(potm->otmMacDescent);
    SCALE_Y(potm->otmMacLineGap);
    SCALE_X(potm->otmptSubscriptSize.x);
    SCALE_Y(potm->otmptSubscriptSize.y);
    SCALE_X(potm->otmptSubscriptOffset.x);
    SCALE_Y(potm->otmptSubscriptOffset.y);
    SCALE_X(potm->otmptSuperscriptSize.x);
    SCALE_Y(potm->otmptSuperscriptSize.y);
    SCALE_X(potm->otmptSuperscriptOffset.x);
    SCALE_Y(potm->otmptSuperscriptOffset.y);
    SCALE_Y(potm->otmsStrikeoutSize);
    SCALE_Y(potm->otmsStrikeoutPosition);
    SCALE_Y(potm->otmsUnderscoreSize);
    SCALE_Y(potm->otmsUnderscorePosition);

#undef SCALE_X
#undef SCALE_Y
}

7897
static BOOL get_text_metrics(GdiFont *font, LPTEXTMETRICW ptm)
7898
{
7899 7900 7901
    if(!font->potm)
    {
        if (!get_outline_text_metrics(font) && !get_bitmap_text_metrics(font)) return FALSE;
7902 7903 7904 7905 7906 7907 7908 7909 7910 7911

        /* Make sure that the font has sane width/height ratio */
        if (font->aveWidth)
        {
            if ((font->aveWidth + font->potm->otmTextMetrics.tmHeight - 1) / font->potm->otmTextMetrics.tmHeight > 100)
            {
                WARN("Ignoring too large font->aveWidth %d\n", font->aveWidth);
                font->aveWidth = 0;
            }
        }
7912
    }
7913
    *ptm = font->potm->otmTextMetrics;
7914
    scale_font_metrics(font, ptm);
7915 7916
    return TRUE;
}
7917

7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928
static BOOL face_has_symbol_charmap(FT_Face ft_face)
{
    int i;

    for(i = 0; i < ft_face->num_charmaps; i++)
    {
        if(ft_face->charmaps[i]->encoding == FT_ENCODING_MS_SYMBOL)
            return TRUE;
    }
    return FALSE;
}
7929

7930
static BOOL get_outline_text_metrics(GdiFont *font)
7931
{
7932
    BOOL ret = FALSE;
7933
    FT_Face ft_face = font->ft_face;
7934
    UINT needed, lenfam, lensty, lenface, lenfull;
7935 7936
    TT_OS2 *pOS2;
    TT_HoriHeader *pHori;
7937
    TT_Postscript *pPost;
7938
    FT_Fixed em_scale;
7939
    WCHAR *family_nameW, *style_nameW, *face_nameW, *full_nameW;
7940
    char *cp;
7941
    INT ascent, descent;
7942
    USHORT windescent;
7943

7944 7945
    TRACE("font=%p\n", font);

7946
    if(!FT_IS_SCALABLE(ft_face))
7947
        return FALSE;
7948

7949
    needed = sizeof(*font->potm);
7950

7951 7952
    lenfam = (strlenW(font->name) + 1) * sizeof(WCHAR);
    family_nameW = strdupW(font->name);
7953

7954 7955 7956
    style_nameW = get_face_name( ft_face, TT_NAME_ID_FONT_SUBFAMILY, GetSystemDefaultLangID() );
    if (!style_nameW)
    {
7957
        FIXME("failed to read style_nameW for font %s!\n", wine_dbgstr_w(font->name));
7958
        style_nameW = towstr( CP_ACP, ft_face->style_name );
7959
    }
7960
    lensty = (strlenW(style_nameW) + 1) * sizeof(WCHAR);
7961

7962
    face_nameW = get_face_name( ft_face, TT_NAME_ID_FULL_NAME, GetSystemDefaultLangID() );
7963
    if (!face_nameW)
7964 7965
    {
        FIXME("failed to read face_nameW for font %s!\n", wine_dbgstr_w(font->name));
7966
        face_nameW = strdupW(font->name);
7967
    }
7968
    if (font->name[0] == '@') face_nameW = prepend_at( face_nameW );
7969 7970
    lenface = (strlenW(face_nameW) + 1) * sizeof(WCHAR);

7971
    full_nameW = get_face_name( ft_face, TT_NAME_ID_UNIQUE_ID, GetSystemDefaultLangID() );
7972 7973
    if (!full_nameW)
    {
7974
        static const WCHAR fake_nameW[] = {'f','a','k','e',' ','n','a','m','e', 0};
7975 7976 7977 7978 7979
        FIXME("failed to read full_nameW for font %s!\n", wine_dbgstr_w(font->name));
        full_nameW = strdupW(fake_nameW);
    }
    lenfull = (strlenW(full_nameW) + 1) * sizeof(WCHAR);

7980 7981 7982 7983 7984 7985
    /* These names should be read from the TT name table */

    /* length of otmpFamilyName */
    needed += lenfam;

    /* length of otmpFaceName */
7986
    needed += lenface;
7987 7988 7989 7990 7991

    /* length of otmpStyleName */
    needed += lensty;

    /* length of otmpFullName */
7992
    needed += lenfull;
7993 7994


7995
    em_scale = (FT_Fixed)MulDiv(font->ppem, 1 << 16, ft_face->units_per_EM);
7996

7997
    pOS2 = pFT_Get_Sfnt_Table(ft_face, ft_sfnt_os2);
7998 7999 8000 8001 8002
    if(!pOS2) {
        FIXME("Can't find OS/2 table - not TT font?\n");
	goto end;
    }

8003
    pHori = pFT_Get_Sfnt_Table(ft_face, ft_sfnt_hhea);
8004 8005 8006 8007 8008
    if(!pHori) {
        FIXME("Can't find HHEA table - not TT font?\n");
	goto end;
    }

8009 8010
    pPost = pFT_Get_Sfnt_Table(ft_face, ft_sfnt_post); /* we can live with this failing */

8011
    TRACE("OS/2 winA = %u winD = %u typoA = %d typoD = %d typoLG = %d avgW %d FT_Face a = %d, d = %d, h = %d: HORZ a = %d, d = %d lg = %d maxY = %ld minY = %ld\n",
8012 8013
	  pOS2->usWinAscent, pOS2->usWinDescent,
	  pOS2->sTypoAscender, pOS2->sTypoDescender, pOS2->sTypoLineGap,
8014
	  pOS2->xAvgCharWidth,
8015 8016 8017 8018 8019 8020 8021 8022 8023
	  ft_face->ascender, ft_face->descender, ft_face->height,
	  pHori->Ascender, pHori->Descender, pHori->Line_Gap,
	  ft_face->bbox.yMax, ft_face->bbox.yMin);

    font->potm = HeapAlloc(GetProcessHeap(), 0, needed);
    font->potm->otmSize = needed;

#define TM font->potm->otmTextMetrics

8024 8025
    windescent = get_fixed_windescent(pOS2->usWinDescent);
    if(pOS2->usWinAscent + windescent == 0) {
8026 8027 8028 8029
        ascent = pHori->Ascender;
        descent = -pHori->Descender;
    } else {
        ascent = pOS2->usWinAscent;
8030
        descent = windescent;
8031 8032
    }

8033 8034 8035
    font->ntmCellHeight = ascent + descent;
    font->ntmAvgWidth = pOS2->xAvgCharWidth;

8036 8037
#define SCALE_X(x) (pFT_MulFix(x, em_scale))
#define SCALE_Y(y) (pFT_MulFix(y, em_scale))
8038

8039 8040 8041 8042 8043
    if(font->yMax) {
	TM.tmAscent = font->yMax;
	TM.tmDescent = -font->yMin;
	TM.tmInternalLeading = (TM.tmAscent + TM.tmDescent) - ft_face->size->metrics.y_ppem;
    } else {
8044 8045 8046
	TM.tmAscent = SCALE_Y(ascent);
	TM.tmDescent = SCALE_Y(descent);
	TM.tmInternalLeading = SCALE_Y(ascent + descent - ft_face->units_per_EM);
8047 8048 8049 8050 8051 8052 8053
    }

    TM.tmHeight = TM.tmAscent + TM.tmDescent;

    /* MSDN says:
     el = MAX(0, LineGap - ((WinAscent + WinDescent) - (Ascender - Descender)))
    */
8054 8055 8056
    TM.tmExternalLeading = max(0, SCALE_Y(pHori->Line_Gap -
                                          ((ascent + descent) -
                                           (pHori->Ascender - pHori->Descender))));
8057

8058
    TM.tmAveCharWidth = SCALE_X(pOS2->xAvgCharWidth);
8059 8060 8061
    if (TM.tmAveCharWidth == 0) {
        TM.tmAveCharWidth = 1; 
    }
8062
    TM.tmMaxCharWidth = SCALE_X(ft_face->bbox.xMax - ft_face->bbox.xMin);
8063
    TM.tmWeight = FW_REGULAR;
8064
    if (font->fake_bold)
8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075
        TM.tmWeight = FW_BOLD;
    else
    {
        if (ft_face->style_flags & FT_STYLE_FLAG_BOLD)
        {
            if (pOS2->usWeightClass > FW_MEDIUM)
                TM.tmWeight = pOS2->usWeightClass;
        }
        else if (pOS2->usWeightClass <= FW_MEDIUM)
            TM.tmWeight = pOS2->usWeightClass;
    }
8076
    TM.tmOverhang = 0;
8077 8078
    TM.tmDigitizedAspectX = 96; /* FIXME */
    TM.tmDigitizedAspectY = 96; /* FIXME */
8079 8080 8081
    /* It appears that for fonts with SYMBOL_CHARSET Windows always sets
     * symbol range to 0 - f0ff
     */
8082 8083

    if (face_has_symbol_charmap(ft_face) || (pOS2->usFirstCharIndex >= 0xf000 && pOS2->usFirstCharIndex < 0xf100))
8084
    {
8085
        TM.tmFirstChar = 0;
8086 8087
        switch(GetACP())
        {
8088 8089 8090
        case 1255: /* Hebrew */
            TM.tmLastChar = 0xf896;
            break;
8091 8092 8093 8094 8095 8096
        case 1257: /* Baltic */
            TM.tmLastChar = 0xf8fd;
            break;
        default:
            TM.tmLastChar = 0xf0ff;
        }
8097 8098
        TM.tmBreakChar = 0x20;
        TM.tmDefaultChar = 0x1f;
8099
    }
8100
    else
8101
    {
8102 8103 8104 8105 8106 8107 8108 8109 8110 8111
        TM.tmFirstChar = pOS2->usFirstCharIndex; /* Should be the first char in the cmap */
        TM.tmLastChar = pOS2->usLastCharIndex;   /* Should be min(cmap_last, os2_last) */

        if(pOS2->usFirstCharIndex <= 1)
            TM.tmBreakChar = pOS2->usFirstCharIndex + 2;
        else if (pOS2->usFirstCharIndex > 0xff)
            TM.tmBreakChar = 0x20;
        else
            TM.tmBreakChar = pOS2->usFirstCharIndex;
        TM.tmDefaultChar = TM.tmBreakChar - 1;
8112
    }
8113
    TM.tmItalic = font->fake_italic ? 255 : ((ft_face->style_flags & FT_STYLE_FLAG_ITALIC) ? 255 : 0);
8114 8115
    TM.tmUnderlined = font->underline;
    TM.tmStruckOut = font->strikeout;
8116 8117

    /* Yes TPMF_FIXED_PITCH is correct; braindead api */
8118 8119 8120
    if(!FT_IS_FIXED_WIDTH(ft_face) &&
       (pOS2->version == 0xFFFFU || 
        pOS2->panose[PAN_PROPORTION_INDEX] != PAN_PROP_MONOSPACED))
8121 8122 8123 8124
        TM.tmPitchAndFamily = TMPF_FIXED_PITCH;
    else
        TM.tmPitchAndFamily = 0;

8125 8126
    switch(pOS2->panose[PAN_FAMILYTYPE_INDEX])
    {
8127 8128
    case PAN_FAMILY_SCRIPT:
        TM.tmPitchAndFamily |= FF_SCRIPT;
8129 8130
        break;

8131 8132
    case PAN_FAMILY_DECORATIVE:
        TM.tmPitchAndFamily |= FF_DECORATIVE;
8133 8134 8135 8136
        break;

    case PAN_ANY:
    case PAN_NO_FIT:
8137
    case PAN_FAMILY_TEXT_DISPLAY:
8138 8139 8140
    case PAN_FAMILY_PICTORIAL: /* symbol fonts get treated as if they were text */
                               /* which is clearly not what the panose spec says. */
    default:
8141 8142
        if(TM.tmPitchAndFamily == 0 || /* fixed */
           pOS2->panose[PAN_PROPORTION_INDEX] == PAN_PROP_MONOSPACED)
8143
	    TM.tmPitchAndFamily = FF_MODERN;
8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168
        else
        {
            switch(pOS2->panose[PAN_SERIFSTYLE_INDEX])
            {
            case PAN_ANY:
            case PAN_NO_FIT:
            default:
                TM.tmPitchAndFamily |= FF_DONTCARE;
                break;

            case PAN_SERIF_COVE:
            case PAN_SERIF_OBTUSE_COVE:
            case PAN_SERIF_SQUARE_COVE:
            case PAN_SERIF_OBTUSE_SQUARE_COVE:
            case PAN_SERIF_SQUARE:
            case PAN_SERIF_THIN:
            case PAN_SERIF_BONE:
            case PAN_SERIF_EXAGGERATED:
            case PAN_SERIF_TRIANGLE:
                TM.tmPitchAndFamily |= FF_ROMAN;
                break;

            case PAN_SERIF_NORMAL_SANS:
            case PAN_SERIF_OBTUSE_SANS:
            case PAN_SERIF_PERP_SANS:
8169 8170
            case PAN_SERIF_FLARED:
            case PAN_SERIF_ROUNDED:
8171 8172 8173
                TM.tmPitchAndFamily |= FF_SWISS;
                break;
            }
8174 8175 8176 8177 8178 8179
	}
	break;
    }

    if(FT_IS_SCALABLE(ft_face))
        TM.tmPitchAndFamily |= TMPF_VECTOR;
8180

8181
    if(FT_IS_SFNT(ft_face))
8182 8183 8184 8185 8186 8187
    {
        if (font->ntmFlags & NTM_PS_OPENTYPE)
            TM.tmPitchAndFamily |= TMPF_DEVICE;
        else
            TM.tmPitchAndFamily |= TMPF_TRUETYPE;
    }
8188 8189 8190 8191 8192 8193

    TM.tmCharSet = font->charset;

    font->potm->otmFiller = 0;
    memcpy(&font->potm->otmPanoseNumber, pOS2->panose, PANOSE_COUNT);
    font->potm->otmfsSelection = pOS2->fsSelection;
8194 8195
    if (font->fake_italic)
        font->potm->otmfsSelection |= 1;
8196 8197
    if (font->fake_bold)
        font->potm->otmfsSelection |= 1 << 5;
8198 8199
    /* Only return valid bits that define embedding and subsetting restrictions */
    font->potm->otmfsType = pOS2->fsType & 0x30e;
8200 8201 8202 8203
    font->potm->otmsCharSlopeRise = pHori->caret_Slope_Rise;
    font->potm->otmsCharSlopeRun = pHori->caret_Slope_Run;
    font->potm->otmItalicAngle = 0; /* POST table */
    font->potm->otmEMSquare = ft_face->units_per_EM;
8204 8205 8206 8207 8208 8209 8210 8211 8212
    font->potm->otmAscent = SCALE_Y(pOS2->sTypoAscender);
    font->potm->otmDescent = SCALE_Y(pOS2->sTypoDescender);
    font->potm->otmLineGap = SCALE_Y(pOS2->sTypoLineGap);
    font->potm->otmsCapEmHeight = SCALE_Y(pOS2->sCapHeight);
    font->potm->otmsXHeight = SCALE_Y(pOS2->sxHeight);
    font->potm->otmrcFontBox.left = SCALE_X(ft_face->bbox.xMin);
    font->potm->otmrcFontBox.right = SCALE_X(ft_face->bbox.xMax);
    font->potm->otmrcFontBox.top = SCALE_Y(ft_face->bbox.yMax);
    font->potm->otmrcFontBox.bottom = SCALE_Y(ft_face->bbox.yMin);
8213 8214
    font->potm->otmMacAscent = TM.tmAscent;
    font->potm->otmMacDescent = -TM.tmDescent;
8215
    font->potm->otmMacLineGap = SCALE_Y(pHori->Line_Gap);
8216
    font->potm->otmusMinimumPPEM = 0; /* TT Header */
8217 8218 8219 8220 8221 8222 8223 8224 8225 8226
    font->potm->otmptSubscriptSize.x = SCALE_X(pOS2->ySubscriptXSize);
    font->potm->otmptSubscriptSize.y = SCALE_Y(pOS2->ySubscriptYSize);
    font->potm->otmptSubscriptOffset.x = SCALE_X(pOS2->ySubscriptXOffset);
    font->potm->otmptSubscriptOffset.y = SCALE_Y(pOS2->ySubscriptYOffset);
    font->potm->otmptSuperscriptSize.x = SCALE_X(pOS2->ySuperscriptXSize);
    font->potm->otmptSuperscriptSize.y = SCALE_Y(pOS2->ySuperscriptYSize);
    font->potm->otmptSuperscriptOffset.x = SCALE_X(pOS2->ySuperscriptXOffset);
    font->potm->otmptSuperscriptOffset.y = SCALE_Y(pOS2->ySuperscriptYOffset);
    font->potm->otmsStrikeoutSize = SCALE_Y(pOS2->yStrikeoutSize);
    font->potm->otmsStrikeoutPosition = SCALE_Y(pOS2->yStrikeoutPosition);
8227 8228 8229 8230
    if(!pPost) {
        font->potm->otmsUnderscoreSize = 0;
	font->potm->otmsUnderscorePosition = 0;
    } else {
8231 8232
        font->potm->otmsUnderscoreSize = SCALE_Y(pPost->underlineThickness);
	font->potm->otmsUnderscorePosition = SCALE_Y(pPost->underlinePosition);
8233
    }
8234 8235
#undef SCALE_X
#undef SCALE_Y
8236
#undef TM
8237

8238
    /* otmp* members should clearly have type ptrdiff_t, but M$ knows best */
8239 8240
    cp = (char*)font->potm + sizeof(*font->potm);
    font->potm->otmpFamilyName = (LPSTR)(cp - (char*)font->potm);
8241 8242
    strcpyW((WCHAR*)cp, family_nameW);
    cp += lenfam;
8243
    font->potm->otmpStyleName = (LPSTR)(cp - (char*)font->potm);
8244 8245
    strcpyW((WCHAR*)cp, style_nameW);
    cp += lensty;
8246
    font->potm->otmpFaceName = (LPSTR)(cp - (char*)font->potm);
8247 8248
    strcpyW((WCHAR*)cp, face_nameW);
	cp += lenface;
8249
    font->potm->otmpFullName = (LPSTR)(cp - (char*)font->potm);
8250
    strcpyW((WCHAR*)cp, full_nameW);
8251
    ret = TRUE;
8252 8253

end:
8254 8255
    HeapFree(GetProcessHeap(), 0, style_nameW);
    HeapFree(GetProcessHeap(), 0, family_nameW);
8256
    HeapFree(GetProcessHeap(), 0, face_nameW);
8257
    HeapFree(GetProcessHeap(), 0, full_nameW);
8258 8259 8260 8261
    return ret;
}

/*************************************************************
8262
 * freetype_GetGlyphOutline
8263
 */
8264 8265
static DWORD CDECL freetype_GetGlyphOutline( PHYSDEV dev, UINT glyph, UINT format,
                                             LPGLYPHMETRICS lpgm, DWORD buflen, LPVOID buf, const MAT2 *lpmat )
8266
{
8267
    struct freetype_physdev *physdev = get_freetype_dev( dev );
8268
    DWORD ret;
8269
    ABC abc;
8270

8271 8272 8273 8274 8275 8276
    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetGlyphOutline );
        return dev->funcs->pGetGlyphOutline( dev, glyph, format, lpgm, buflen, buf, lpmat );
    }

8277 8278
    GDI_CheckNotLock();
    EnterCriticalSection( &freetype_cs );
8279
    ret = get_glyph_outline( physdev->font, glyph, format, lpgm, &abc, buflen, buf, lpmat );
8280 8281 8282 8283 8284
    LeaveCriticalSection( &freetype_cs );
    return ret;
}

/*************************************************************
8285
 * freetype_GetTextMetrics
8286
 */
8287
static BOOL CDECL freetype_GetTextMetrics( PHYSDEV dev, TEXTMETRICW *metrics )
8288
{
8289
    struct freetype_physdev *physdev = get_freetype_dev( dev );
8290 8291
    BOOL ret;

8292 8293 8294 8295 8296 8297
    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextMetrics );
        return dev->funcs->pGetTextMetrics( dev, metrics );
    }

8298 8299
    GDI_CheckNotLock();
    EnterCriticalSection( &freetype_cs );
8300
    ret = get_text_metrics( physdev->font, metrics );
8301 8302 8303 8304 8305
    LeaveCriticalSection( &freetype_cs );
    return ret;
}

/*************************************************************
8306
 * freetype_GetOutlineTextMetrics
8307
 */
8308
static UINT CDECL freetype_GetOutlineTextMetrics( PHYSDEV dev, UINT cbSize, OUTLINETEXTMETRICW *potm )
8309
{
8310
    struct freetype_physdev *physdev = get_freetype_dev( dev );
8311 8312
    UINT ret = 0;

8313 8314 8315 8316 8317
    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetOutlineTextMetrics );
        return dev->funcs->pGetOutlineTextMetrics( dev, cbSize, potm );
    }
8318

8319 8320 8321
    TRACE("font=%p\n", physdev->font);

    if (!FT_IS_SCALABLE( physdev->font->ft_face )) return 0;
8322

8323 8324
    GDI_CheckNotLock();
    EnterCriticalSection( &freetype_cs );
8325

8326
    if (physdev->font->potm || get_outline_text_metrics( physdev->font ))
8327
    {
8328
        if(potm && cbSize >= physdev->font->potm->otmSize)
8329
        {
8330 8331
	    memcpy(potm, physdev->font->potm, physdev->font->potm->otmSize);
            scale_outline_font_metrics(physdev->font, potm);
8332
        }
8333
	ret = physdev->font->potm->otmSize;
8334
    }
8335
    LeaveCriticalSection( &freetype_cs );
8336 8337 8338
    return ret;
}

8339
static BOOL load_child_font(GdiFont *font, CHILD_FONT *child)
8340
{
8341 8342 8343 8344 8345
    const struct list *face_list;
    Face *child_face = NULL, *best_face = NULL;
    UINT penalty = 0, new_penalty = 0;
    BOOL bold, italic, bd, it;

8346 8347
    italic = !!font->font_desc.lf.lfItalic;
    bold = font->font_desc.lf.lfWeight > FW_MEDIUM;
8348 8349 8350 8351

    face_list = get_face_list_from_family( child->face->family );
    LIST_FOR_EACH_ENTRY( child_face, face_list, Face, entry )
    {
8352 8353
        it = !!(child_face->ntmFlags & NTM_ITALIC);
        bd = !!(child_face->ntmFlags & NTM_BOLD);
8354 8355 8356 8357 8358 8359 8360 8361 8362
        new_penalty = ( it ^ italic ) + ( bd ^ bold );
        if (!best_face || new_penalty < penalty)
        {
            penalty = new_penalty;
            best_face = child_face;
        }
    }
    child_face = best_face ? best_face : child->face;

8363
    child->font = alloc_font();
8364
    child->font->ft_face = OpenFontFace( child->font, child_face, 0, -font->ppem );
8365
    if(!child->font->ft_face)
8366 8367 8368
    {
        free_font(child->font);
        child->font = NULL;
8369
        return FALSE;
8370
    }
8371

8372 8373
    child->font->fake_italic = italic && !( child_face->ntmFlags & NTM_ITALIC );
    child->font->fake_bold = bold && !( child_face->ntmFlags & NTM_BOLD );
8374
    child->font->font_desc = font->font_desc;
8375
    child->font->ntmFlags = child_face->ntmFlags;
8376
    child->font->orientation = font->orientation;
8377
    child->font->scale_y = font->scale_y;
8378
    child->font->name = strdupW( child_face->family->FamilyName );
8379
    child->font->base_font = font;
8380
    TRACE("created child font %p for base %p\n", child->font, font);
8381 8382 8383
    return TRUE;
}

8384
static BOOL get_glyph_index_linked(GdiFont *font, UINT c, GdiFont **linked_font, FT_UInt *glyph, BOOL* vert)
8385
{
8386
    FT_UInt g,o;
8387 8388 8389 8390 8391 8392 8393 8394
    CHILD_FONT *child_font;

    if(font->base_font)
        font = font->base_font;

    *linked_font = font;

    if((*glyph = get_glyph_index(font, c)))
8395
    {
8396
        o = *glyph;
8397
        *glyph = get_GSUB_vert_glyph(font, *glyph);
8398
        *vert = (o != *glyph);
8399
        return TRUE;
8400
    }
8401

8402 8403
    if (c < 32) goto done;  /* don't check linked fonts for control characters */

8404 8405 8406 8407 8408 8409 8410 8411 8412
    LIST_FOR_EACH_ENTRY(child_font, &font->child_fonts, CHILD_FONT, entry)
    {
        if(!child_font->font)
            if(!load_child_font(font, child_font))
                continue;

        if(!child_font->font->ft_face)
            continue;
        g = get_glyph_index(child_font->font, c);
8413
        o = g;
8414
        g = get_GSUB_vert_glyph(child_font->font, g);
8415 8416 8417 8418
        if(g)
        {
            *glyph = g;
            *linked_font = child_font->font;
8419
            *vert = (o != g);
8420 8421 8422
            return TRUE;
        }
    }
8423 8424

done:
8425
    *vert = FALSE;
8426 8427
    return FALSE;
}
8428 8429

/*************************************************************
8430
 * freetype_GetCharWidth
8431
 */
8432
static BOOL CDECL freetype_GetCharWidth( PHYSDEV dev, UINT firstChar, UINT lastChar, LPINT buffer )
8433
{
8434
    static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
8435 8436
    UINT c;
    GLYPHMETRICS gm;
8437
    ABC abc;
8438
    struct freetype_physdev *physdev = get_freetype_dev( dev );
8439

8440 8441 8442 8443 8444 8445 8446
    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetCharWidth );
        return dev->funcs->pGetCharWidth( dev, firstChar, lastChar, buffer );
    }

    TRACE("%p, %d, %d, %p\n", physdev->font, firstChar, lastChar, buffer);
8447

8448
    GDI_CheckNotLock();
8449
    EnterCriticalSection( &freetype_cs );
8450
    for(c = firstChar; c <= lastChar; c++) {
8451 8452
        get_glyph_outline( physdev->font, c, GGO_METRICS, &gm, &abc, 0, NULL, &identity );
        buffer[c - firstChar] = abc.abcA + abc.abcB + abc.abcC;
8453
    }
8454
    LeaveCriticalSection( &freetype_cs );
8455 8456 8457
    return TRUE;
}

8458 8459 8460
/*************************************************************
 * freetype_GetCharWidthInfo
 */
8461
static BOOL CDECL freetype_GetCharWidthInfo( PHYSDEV dev, void* ptr )
8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491
{
    struct freetype_physdev *physdev = get_freetype_dev( dev );
    struct char_width_info *info = ptr;
    TT_HoriHeader *pHori;

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetCharWidthInfo );
        return dev->funcs->pGetCharWidthInfo( dev, ptr );
    }

    TRACE("%p, %p\n", physdev->font, info);

    if (FT_IS_SCALABLE(physdev->font->ft_face) &&
        (pHori = pFT_Get_Sfnt_Table(physdev->font->ft_face, ft_sfnt_hhea)))
    {
        FT_Fixed em_scale;
        em_scale = MulDiv(physdev->font->ppem, 1 << 16,
                          physdev->font->ft_face->units_per_EM);
        info->lsb = (SHORT)pFT_MulFix(pHori->min_Left_Side_Bearing,  em_scale);
        info->rsb = (SHORT)pFT_MulFix(pHori->min_Right_Side_Bearing, em_scale);
    }
    else
        info->lsb = info->rsb = 0;

    info->unk = 0;

    return TRUE;
}

8492
/*************************************************************
8493
 * freetype_GetCharABCWidths
8494
 */
8495
static BOOL CDECL freetype_GetCharABCWidths( PHYSDEV dev, UINT firstChar, UINT lastChar, LPABC buffer )
8496
{
8497
    static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
8498 8499
    UINT c;
    GLYPHMETRICS gm;
8500
    struct freetype_physdev *physdev = get_freetype_dev( dev );
8501

8502 8503 8504 8505 8506 8507 8508
    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetCharABCWidths );
        return dev->funcs->pGetCharABCWidths( dev, firstChar, lastChar, buffer );
    }

    TRACE("%p, %d, %d, %p\n", physdev->font, firstChar, lastChar, buffer);
8509

8510
    GDI_CheckNotLock();
8511 8512
    EnterCriticalSection( &freetype_cs );

8513 8514 8515
    for(c = firstChar; c <= lastChar; c++, buffer++)
        get_glyph_outline( physdev->font, c, GGO_METRICS, &gm, buffer, 0, NULL, &identity );

8516
    LeaveCriticalSection( &freetype_cs );
8517 8518 8519
    return TRUE;
}

8520
/*************************************************************
8521
 * freetype_GetCharABCWidthsI
8522
 */
8523
static BOOL CDECL freetype_GetCharABCWidthsI( PHYSDEV dev, UINT firstChar, UINT count, LPWORD pgi, LPABC buffer )
8524
{
8525
    static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
8526 8527
    UINT c;
    GLYPHMETRICS gm;
8528 8529 8530 8531 8532 8533 8534
    struct freetype_physdev *physdev = get_freetype_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetCharABCWidthsI );
        return dev->funcs->pGetCharABCWidthsI( dev, firstChar, count, pgi, buffer );
    }
8535

8536
    if(!FT_HAS_HORIZONTAL(physdev->font->ft_face))
8537 8538
        return FALSE;

8539
    GDI_CheckNotLock();
8540 8541
    EnterCriticalSection( &freetype_cs );

8542 8543 8544
    for(c = 0; c < count; c++, buffer++)
        get_glyph_outline( physdev->font, pgi ? pgi[c] : firstChar + c, GGO_METRICS | GGO_GLYPH_INDEX,
                           &gm, buffer, 0, NULL, &identity );
8545

8546
    LeaveCriticalSection( &freetype_cs );
8547 8548 8549
    return TRUE;
}

8550
/*************************************************************
8551
 * freetype_GetTextExtentExPoint
8552
 */
8553
static BOOL CDECL freetype_GetTextExtentExPoint( PHYSDEV dev, LPCWSTR wstr, INT count, LPINT dxs )
8554
{
8555
    static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
8556
    INT idx, pos;
8557
    ABC abc;
8558
    GLYPHMETRICS gm;
8559 8560 8561 8562 8563
    struct freetype_physdev *physdev = get_freetype_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextExtentExPoint );
8564
        return dev->funcs->pGetTextExtentExPoint( dev, wstr, count, dxs );
8565
    }
8566

8567
    TRACE("%p, %s, %d\n", physdev->font, debugstr_wn(wstr, count), count);
8568

8569
    GDI_CheckNotLock();
8570 8571
    EnterCriticalSection( &freetype_cs );

8572 8573
    for (idx = pos = 0; idx < count; idx++)
    {
8574
        get_glyph_outline( physdev->font, wstr[idx], GGO_METRICS, &gm, &abc, 0, NULL, &identity );
8575 8576
        pos += abc.abcA + abc.abcB + abc.abcC;
        dxs[idx] = pos;
8577
    }
8578

8579
    LeaveCriticalSection( &freetype_cs );
8580 8581 8582
    return TRUE;
}

8583
/*************************************************************
8584
 * freetype_GetTextExtentExPointI
8585
 */
8586
static BOOL CDECL freetype_GetTextExtentExPointI( PHYSDEV dev, const WORD *indices, INT count, LPINT dxs )
8587
{
8588
    static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
8589
    INT idx, pos;
8590
    ABC abc;
8591
    GLYPHMETRICS gm;
8592 8593 8594 8595 8596
    struct freetype_physdev *physdev = get_freetype_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextExtentExPointI );
8597
        return dev->funcs->pGetTextExtentExPointI( dev, indices, count, dxs );
8598
    }
8599

8600
    TRACE("%p, %p, %d\n", physdev->font, indices, count);
8601

8602
    GDI_CheckNotLock();
8603 8604
    EnterCriticalSection( &freetype_cs );

8605 8606
    for (idx = pos = 0; idx < count; idx++)
    {
8607 8608
        get_glyph_outline( physdev->font, indices[idx], GGO_METRICS | GGO_GLYPH_INDEX,
                           &gm, &abc, 0, NULL, &identity );
8609 8610
        pos += abc.abcA + abc.abcB + abc.abcC;
        dxs[idx] = pos;
8611
    }
8612

8613
    LeaveCriticalSection( &freetype_cs );
8614 8615 8616
    return TRUE;
}

Huw D M Davies's avatar
Huw D M Davies committed
8617
/*************************************************************
8618
 * freetype_GetFontData
Huw D M Davies's avatar
Huw D M Davies committed
8619
 */
8620
static DWORD CDECL freetype_GetFontData( PHYSDEV dev, DWORD table, DWORD offset, LPVOID buf, DWORD cbData )
Huw D M Davies's avatar
Huw D M Davies committed
8621
{
8622
    struct freetype_physdev *physdev = get_freetype_dev( dev );
Huw D M Davies's avatar
Huw D M Davies committed
8623

8624
    if (!physdev->font)
8625
    {
8626 8627
        dev = GET_NEXT_PHYSDEV( dev, pGetFontData );
        return dev->funcs->pGetFontData( dev, table, offset, buf, cbData );
8628
    }
8629

8630 8631
    TRACE("font=%p, table=%s, offset=0x%x, buf=%p, cbData=0x%x\n",
          physdev->font, debugstr_an((char*)&table, 4), offset, buf, cbData);
8632 8633

    return get_font_data( physdev->font, table, offset, buf, cbData );
Huw D M Davies's avatar
Huw D M Davies committed
8634 8635
}

8636
/*************************************************************
8637
 * freetype_GetTextFace
8638
 */
8639
static INT CDECL freetype_GetTextFace( PHYSDEV dev, INT count, LPWSTR str )
8640
{
8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656
    INT n;
    struct freetype_physdev *physdev = get_freetype_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextFace );
        return dev->funcs->pGetTextFace( dev, count, str );
    }

    n = strlenW(physdev->font->name) + 1;
    if (str)
    {
        lstrcpynW(str, physdev->font->name, count);
        n = min(count, n);
    }
    return n;
8657 8658
}

8659 8660 8661
/*************************************************************
 * freetype_GetTextCharsetInfo
 */
8662
static UINT CDECL freetype_GetTextCharsetInfo( PHYSDEV dev, LPFONTSIGNATURE fs, DWORD flags )
8663
{
8664 8665 8666 8667 8668 8669 8670 8671 8672
    struct freetype_physdev *physdev = get_freetype_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextCharsetInfo );
        return dev->funcs->pGetTextCharsetInfo( dev, fs, flags );
    }
    if (fs) *fs = physdev->font->fs;
    return physdev->font->charset;
8673
}
8674

8675 8676 8677 8678 8679 8680 8681 8682
/* Retrieve a list of supported Unicode ranges for a given font.
 * Can be called with NULL gs to calculate the buffer size. Returns
 * the number of ranges found.
 */
static DWORD get_font_unicode_ranges(FT_Face face, GLYPHSET *gs)
{
    DWORD num_ranges = 0;

8683
    if (face->charmap->encoding == FT_ENCODING_UNICODE)
8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730
    {
        FT_UInt glyph_code;
        FT_ULong char_code, char_code_prev;

        glyph_code = 0;
        char_code_prev = char_code = pFT_Get_First_Char(face, &glyph_code);

        TRACE("face encoding FT_ENCODING_UNICODE, number of glyphs %ld, first glyph %u, first char %04lx\n",
               face->num_glyphs, glyph_code, char_code);

        if (!glyph_code) return 0;

        if (gs)
        {
            gs->ranges[0].wcLow = (USHORT)char_code;
            gs->ranges[0].cGlyphs = 0;
            gs->cGlyphsSupported = 0;
        }

        num_ranges = 1;
        while (glyph_code)
        {
            if (char_code < char_code_prev)
            {
                ERR("expected increasing char code from FT_Get_Next_Char\n");
                return 0;
            }
            if (char_code - char_code_prev > 1)
            {
                num_ranges++;
                if (gs)
                {
                    gs->ranges[num_ranges - 1].wcLow = (USHORT)char_code;
                    gs->ranges[num_ranges - 1].cGlyphs = 1;
                    gs->cGlyphsSupported++;
                }
            }
            else if (gs)
            {
                gs->ranges[num_ranges - 1].cGlyphs++;
                gs->cGlyphsSupported++;
            }
            char_code_prev = char_code;
            char_code = pFT_Get_Next_Char(face, char_code, &glyph_code);
        }
    }
    else
8731 8732 8733 8734
    {
        DWORD encoding = RtlUlongByteSwap(face->charmap->encoding);
        FIXME("encoding %s not supported\n", debugstr_an((char *)&encoding, 4));
    }
8735 8736 8737 8738

    return num_ranges;
}

8739 8740 8741
/*************************************************************
 * freetype_GetFontUnicodeRanges
 */
8742
static DWORD CDECL freetype_GetFontUnicodeRanges( PHYSDEV dev, LPGLYPHSET glyphset )
8743
{
8744 8745
    struct freetype_physdev *physdev = get_freetype_dev( dev );
    DWORD size, num_ranges;
8746

8747 8748 8749 8750 8751 8752 8753
    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetFontUnicodeRanges );
        return dev->funcs->pGetFontUnicodeRanges( dev, glyphset );
    }

    num_ranges = get_font_unicode_ranges(physdev->font->ft_face, glyphset);
8754 8755
    size = sizeof(GLYPHSET) + sizeof(WCRANGE) * (num_ranges - 1);
    if (glyphset)
8756
    {
8757 8758
        glyphset->cbThis = size;
        glyphset->cRanges = num_ranges;
8759
        glyphset->flAccel = 0;
8760 8761 8762
    }
    return size;
}
Huw Davies's avatar
Huw Davies committed
8763 8764

/*************************************************************
8765
 * freetype_FontIsLinked
Huw Davies's avatar
Huw Davies committed
8766
 */
8767
static BOOL CDECL freetype_FontIsLinked( PHYSDEV dev )
Huw Davies's avatar
Huw Davies committed
8768
{
8769
    struct freetype_physdev *physdev = get_freetype_dev( dev );
8770
    BOOL ret;
8771 8772 8773 8774 8775 8776 8777

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pFontIsLinked );
        return dev->funcs->pFontIsLinked( dev );
    }

8778
    GDI_CheckNotLock();
8779
    EnterCriticalSection( &freetype_cs );
8780
    ret = !list_empty(&physdev->font->child_fonts);
8781 8782
    LeaveCriticalSection( &freetype_cs );
    return ret;
Huw Davies's avatar
Huw Davies committed
8783
}
8784

8785 8786 8787 8788 8789 8790
/*************************************************************************
 *             GetRasterizerCaps   (GDI32.@)
 */
BOOL WINAPI GetRasterizerCaps( LPRASTERIZER_STATUS lprs, UINT cbNumBytes)
{
    lprs->nSize = sizeof(RASTERIZER_STATUS);
8791
    lprs->wFlags = TT_AVAILABLE | TT_ENABLED;
8792 8793 8794 8795
    lprs->nLanguageID = 0;
    return TRUE;
}

8796
/*************************************************************
8797
 * freetype_GetFontRealizationInfo
8798
 */
8799
static BOOL CDECL freetype_GetFontRealizationInfo( PHYSDEV dev, void *ptr )
8800
{
8801
    struct freetype_physdev *physdev = get_freetype_dev( dev );
8802
    struct font_realization_info *info = ptr;
8803 8804 8805

    if (!physdev->font)
    {
8806 8807
        dev = GET_NEXT_PHYSDEV( dev, pGetFontRealizationInfo );
        return dev->funcs->pGetFontRealizationInfo( dev, ptr );
8808 8809
    }

8810
    TRACE("(%p, %p)\n", physdev->font, info);
8811 8812

    info->flags = 1;
8813
    if(FT_IS_SCALABLE(physdev->font->ft_face))
8814 8815
        info->flags |= 2;

8816
    info->cache_num = physdev->font->cache_num;
8817
    info->instance_id = physdev->font->instance_id;
8818 8819 8820 8821
    if (info->size == sizeof(*info))
    {
        info->unk = 0;
        info->face_index = physdev->font->ft_face->face_index;
8822 8823 8824 8825 8826
        info->simulations = 0;
        if (physdev->font->fake_bold)
            info->simulations |= 0x1;
        if (physdev->font->fake_italic)
            info->simulations |= 0x2;
8827 8828
    }

8829 8830 8831
    return TRUE;
}

8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861
/*************************************************************************
 *             GetFontFileData   (GDI32.@)
 */
BOOL WINAPI GetFontFileData( DWORD instance_id, DWORD unknown, UINT64 offset, void *buff, DWORD buff_size )
{
    struct font_handle_entry *entry = handle_entry( instance_id );
    DWORD tag = 0, size;
    GdiFont *font;

    if (!entry)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    font = entry->obj;
    if (font->ttc_item_offset)
        tag = MS_TTCF_TAG;

    size = get_font_data( font, tag, 0, NULL, 0 );
    if (size < buff_size || offset > size - buff_size)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    /* For now this only works for SFNT case. */
    return get_font_data( font, tag, offset, buff, buff_size ) != 0;
}

8862 8863 8864
/*************************************************************************
 *             GetFontFileInfo   (GDI32.@)
 */
8865
BOOL WINAPI GetFontFileInfo( DWORD instance_id, DWORD unknown, struct font_fileinfo *info, SIZE_T size, SIZE_T *needed )
8866 8867
{
    struct font_handle_entry *entry = handle_entry( instance_id );
8868
    SIZE_T required_size;
8869 8870 8871 8872 8873 8874 8875 8876
    const GdiFont *font;

    if (!entry)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

8877 8878 8879
    if (!needed)
        needed = &required_size;

8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892
    font = entry->obj;
    *needed = sizeof(*info) + strlenW(font->fileinfo->path) * sizeof(WCHAR);
    if (*needed > size)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return FALSE;
    }

    /* path is included too */
    memcpy(info, font->fileinfo, *needed);
    return TRUE;
}

8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936
/*************************************************************************
 * Kerning support for TrueType fonts
 */

struct TT_kern_table
{
    USHORT version;
    USHORT nTables;
};

struct TT_kern_subtable
{
    USHORT version;
    USHORT length;
    union
    {
        USHORT word;
        struct
        {
            USHORT horizontal : 1;
            USHORT minimum : 1;
            USHORT cross_stream: 1;
            USHORT override : 1;
            USHORT reserved1 : 4;
            USHORT format : 8;
        } bits;
    } coverage;
};

struct TT_format0_kern_subtable
{
    USHORT nPairs;
    USHORT searchRange;
    USHORT entrySelector;
    USHORT rangeShift;
};

struct TT_kern_pair
{
    USHORT left;
    USHORT right;
    short  value;
};

8937
static DWORD parse_format0_kern_subtable(GdiFont *font,
8938 8939 8940 8941 8942 8943 8944
                                         const struct TT_format0_kern_subtable *tt_f0_ks,
                                         const USHORT *glyph_to_char,
                                         KERNINGPAIR *kern_pair, DWORD cPairs)
{
    USHORT i, nPairs;
    const struct TT_kern_pair *tt_kern_pair;

8945
    TRACE("font height %d, units_per_EM %d\n", font->ppem, font->ft_face->units_per_EM);
8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963

    nPairs = GET_BE_WORD(tt_f0_ks->nPairs);

    TRACE("nPairs %u, searchRange %u, entrySelector %u, rangeShift %u\n",
           nPairs, GET_BE_WORD(tt_f0_ks->searchRange),
           GET_BE_WORD(tt_f0_ks->entrySelector), GET_BE_WORD(tt_f0_ks->rangeShift));

    if (!kern_pair || !cPairs)
        return nPairs;

    tt_kern_pair = (const struct TT_kern_pair *)(tt_f0_ks + 1);

    nPairs = min(nPairs, cPairs);

    for (i = 0; i < nPairs; i++)
    {
        kern_pair->wFirst = glyph_to_char[GET_BE_WORD(tt_kern_pair[i].left)];
        kern_pair->wSecond = glyph_to_char[GET_BE_WORD(tt_kern_pair[i].right)];
8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976
        /* this algorithm appears to better match what Windows does */
        kern_pair->iKernAmount = (short)GET_BE_WORD(tt_kern_pair[i].value) * font->ppem;
        if (kern_pair->iKernAmount < 0)
        {
            kern_pair->iKernAmount -= font->ft_face->units_per_EM / 2;
            kern_pair->iKernAmount -= font->ppem;
        }
        else if (kern_pair->iKernAmount > 0)
        {
            kern_pair->iKernAmount += font->ft_face->units_per_EM / 2;
            kern_pair->iKernAmount += font->ppem;
        }
        kern_pair->iKernAmount /= font->ft_face->units_per_EM;
8977 8978 8979 8980 8981 8982 8983 8984 8985 8986

        TRACE("left %u right %u value %d\n",
               kern_pair->wFirst, kern_pair->wSecond, kern_pair->iKernAmount);

        kern_pair++;
    }
    TRACE("copied %u entries\n", nPairs);
    return nPairs;
}

8987 8988 8989
/*************************************************************
 * freetype_GetKerningPairs
 */
8990
static DWORD CDECL freetype_GetKerningPairs( PHYSDEV dev, DWORD cPairs, KERNINGPAIR *kern_pair )
8991 8992 8993 8994 8995 8996 8997
{
    DWORD length;
    void *buf;
    const struct TT_kern_table *tt_kern_table;
    const struct TT_kern_subtable *tt_kern_subtable;
    USHORT i, nTables;
    USHORT *glyph_to_char;
8998 8999 9000 9001 9002 9003 9004 9005
    GdiFont *font;
    struct freetype_physdev *physdev = get_freetype_dev( dev );

    if (!(font = physdev->font))
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetKerningPairs );
        return dev->funcs->pGetKerningPairs( dev, cPairs, kern_pair );
    }
9006

9007
    GDI_CheckNotLock();
9008
    EnterCriticalSection( &freetype_cs );
9009 9010 9011 9012 9013 9014 9015
    if (font->total_kern_pairs != (DWORD)-1)
    {
        if (cPairs && kern_pair)
        {
            cPairs = min(cPairs, font->total_kern_pairs);
            memcpy(kern_pair, font->kern_pairs, cPairs * sizeof(*kern_pair));
        }
9016 9017
        else cPairs = font->total_kern_pairs;

9018
        LeaveCriticalSection( &freetype_cs );
9019
        return cPairs;
9020 9021 9022 9023
    }

    font->total_kern_pairs = 0;

9024
    length = get_font_data(font, MS_KERN_TAG, 0, NULL, 0);
9025 9026 9027 9028

    if (length == GDI_ERROR)
    {
        TRACE("no kerning data in the font\n");
9029
        LeaveCriticalSection( &freetype_cs );
9030 9031 9032 9033 9034 9035 9036
        return 0;
    }

    buf = HeapAlloc(GetProcessHeap(), 0, length);
    if (!buf)
    {
        WARN("Out of memory\n");
9037
        LeaveCriticalSection( &freetype_cs );
9038 9039 9040
        return 0;
    }

9041
    get_font_data(font, MS_KERN_TAG, 0, buf, length);
9042 9043 9044 9045 9046 9047 9048

    /* build a glyph index to char code map */
    glyph_to_char = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(USHORT) * 65536);
    if (!glyph_to_char)
    {
        WARN("Out of memory allocating a glyph index to char code map\n");
        HeapFree(GetProcessHeap(), 0, buf);
9049
        LeaveCriticalSection( &freetype_cs );
9050 9051 9052
        return 0;
    }

9053
    if (font->ft_face->charmap->encoding == FT_ENCODING_UNICODE)
9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079
    {
        FT_UInt glyph_code;
        FT_ULong char_code;

        glyph_code = 0;
        char_code = pFT_Get_First_Char(font->ft_face, &glyph_code);

        TRACE("face encoding FT_ENCODING_UNICODE, number of glyphs %ld, first glyph %u, first char %lu\n",
               font->ft_face->num_glyphs, glyph_code, char_code);

        while (glyph_code)
        {
            /*TRACE("Char %04lX -> Index %u%s\n", char_code, glyph_code, glyph_to_char[glyph_code] ? "  !" : "" );*/

            /* FIXME: This doesn't match what Windows does: it does some fancy
             * things with duplicate glyph index to char code mappings, while
             * we just avoid overriding existing entries.
             */
            if (glyph_code <= 65535 && !glyph_to_char[glyph_code])
                glyph_to_char[glyph_code] = (USHORT)char_code;

            char_code = pFT_Get_Next_Char(font->ft_face, char_code, &glyph_code);
        }
    }
    else
    {
9080
        DWORD encoding = RtlUlongByteSwap(font->ft_face->charmap->encoding);
9081 9082
        ULONG n;

9083
        FIXME("encoding %s not supported\n", debugstr_an((char *)&encoding, 4));
9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141
        for (n = 0; n <= 65535; n++)
            glyph_to_char[n] = (USHORT)n;
    }

    tt_kern_table = buf;
    nTables = GET_BE_WORD(tt_kern_table->nTables);
    TRACE("version %u, nTables %u\n",
           GET_BE_WORD(tt_kern_table->version), nTables);

    tt_kern_subtable = (const struct TT_kern_subtable *)(tt_kern_table + 1);

    for (i = 0; i < nTables; i++)
    {
        struct TT_kern_subtable tt_kern_subtable_copy;

        tt_kern_subtable_copy.version = GET_BE_WORD(tt_kern_subtable->version);
        tt_kern_subtable_copy.length = GET_BE_WORD(tt_kern_subtable->length);
        tt_kern_subtable_copy.coverage.word = GET_BE_WORD(tt_kern_subtable->coverage.word);

        TRACE("version %u, length %u, coverage %u, subtable format %u\n",
               tt_kern_subtable_copy.version, tt_kern_subtable_copy.length,
               tt_kern_subtable_copy.coverage.word, tt_kern_subtable_copy.coverage.bits.format);

        /* According to the TrueType specification this is the only format
         * that will be properly interpreted by Windows and OS/2
         */
        if (tt_kern_subtable_copy.coverage.bits.format == 0)
        {
            DWORD new_chunk, old_total = font->total_kern_pairs;

            new_chunk = parse_format0_kern_subtable(font, (const struct TT_format0_kern_subtable *)(tt_kern_subtable + 1),
                                                    glyph_to_char, NULL, 0);
            font->total_kern_pairs += new_chunk;

            if (!font->kern_pairs)
                font->kern_pairs = HeapAlloc(GetProcessHeap(), 0,
                                             font->total_kern_pairs * sizeof(*font->kern_pairs));
            else
                font->kern_pairs = HeapReAlloc(GetProcessHeap(), 0, font->kern_pairs,
                                               font->total_kern_pairs * sizeof(*font->kern_pairs));

            parse_format0_kern_subtable(font, (const struct TT_format0_kern_subtable *)(tt_kern_subtable + 1),
                        glyph_to_char, font->kern_pairs + old_total, new_chunk);
        }
        else
            TRACE("skipping kerning table format %u\n", tt_kern_subtable_copy.coverage.bits.format);

        tt_kern_subtable = (const struct TT_kern_subtable *)((const char *)tt_kern_subtable + tt_kern_subtable_copy.length);
    }

    HeapFree(GetProcessHeap(), 0, glyph_to_char);
    HeapFree(GetProcessHeap(), 0, buf);

    if (cPairs && kern_pair)
    {
        cPairs = min(cPairs, font->total_kern_pairs);
        memcpy(kern_pair, font->kern_pairs, cPairs * sizeof(*kern_pair));
    }
9142 9143
    else cPairs = font->total_kern_pairs;

9144
    LeaveCriticalSection( &freetype_cs );
9145
    return cPairs;
9146
}
9147

9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168
static const struct gdi_dc_funcs freetype_funcs =
{
    NULL,                               /* pAbortDoc */
    NULL,                               /* pAbortPath */
    NULL,                               /* pAlphaBlend */
    NULL,                               /* pAngleArc */
    NULL,                               /* pArc */
    NULL,                               /* pArcTo */
    NULL,                               /* pBeginPath */
    NULL,                               /* pBlendImage */
    NULL,                               /* pChord */
    NULL,                               /* pCloseFigure */
    NULL,                               /* pCreateCompatibleDC */
    freetype_CreateDC,                  /* pCreateDC */
    freetype_DeleteDC,                  /* pDeleteDC */
    NULL,                               /* pDeleteObject */
    NULL,                               /* pDeviceCapabilities */
    NULL,                               /* pEllipse */
    NULL,                               /* pEndDoc */
    NULL,                               /* pEndPage */
    NULL,                               /* pEndPath */
9169
    freetype_EnumFonts,                 /* pEnumFonts */
9170 9171 9172 9173 9174 9175 9176 9177 9178 9179
    NULL,                               /* pEnumICMProfiles */
    NULL,                               /* pExcludeClipRect */
    NULL,                               /* pExtDeviceMode */
    NULL,                               /* pExtEscape */
    NULL,                               /* pExtFloodFill */
    NULL,                               /* pExtSelectClipRgn */
    NULL,                               /* pExtTextOut */
    NULL,                               /* pFillPath */
    NULL,                               /* pFillRgn */
    NULL,                               /* pFlattenPath */
9180
    freetype_FontIsLinked,              /* pFontIsLinked */
9181 9182
    NULL,                               /* pFrameRgn */
    NULL,                               /* pGdiComment */
9183
    NULL,                               /* pGetBoundsRect */
9184
    freetype_GetCharABCWidths,          /* pGetCharABCWidths */
9185
    freetype_GetCharABCWidthsI,         /* pGetCharABCWidthsI */
9186
    freetype_GetCharWidth,              /* pGetCharWidth */
9187
    freetype_GetCharWidthInfo,          /* pGetCharWidthInfo */
9188 9189
    NULL,                               /* pGetDeviceCaps */
    NULL,                               /* pGetDeviceGammaRamp */
9190
    freetype_GetFontData,               /* pGetFontData */
9191
    freetype_GetFontRealizationInfo,    /* pGetFontRealizationInfo */
9192
    freetype_GetFontUnicodeRanges,      /* pGetFontUnicodeRanges */
9193
    freetype_GetGlyphIndices,           /* pGetGlyphIndices */
9194
    freetype_GetGlyphOutline,           /* pGetGlyphOutline */
9195 9196
    NULL,                               /* pGetICMProfile */
    NULL,                               /* pGetImage */
9197
    freetype_GetKerningPairs,           /* pGetKerningPairs */
9198
    NULL,                               /* pGetNearestColor */
9199
    freetype_GetOutlineTextMetrics,     /* pGetOutlineTextMetrics */
9200 9201
    NULL,                               /* pGetPixel */
    NULL,                               /* pGetSystemPaletteEntries */
9202
    freetype_GetTextCharsetInfo,        /* pGetTextCharsetInfo */
9203
    freetype_GetTextExtentExPoint,      /* pGetTextExtentExPoint */
9204
    freetype_GetTextExtentExPointI,     /* pGetTextExtentExPointI */
9205
    freetype_GetTextFace,               /* pGetTextFace */
9206
    freetype_GetTextMetrics,            /* pGetTextMetrics */
9207
    NULL,                               /* pGradientFill */
9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239
    NULL,                               /* pIntersectClipRect */
    NULL,                               /* pInvertRgn */
    NULL,                               /* pLineTo */
    NULL,                               /* pModifyWorldTransform */
    NULL,                               /* pMoveTo */
    NULL,                               /* pOffsetClipRgn */
    NULL,                               /* pOffsetViewportOrg */
    NULL,                               /* pOffsetWindowOrg */
    NULL,                               /* pPaintRgn */
    NULL,                               /* pPatBlt */
    NULL,                               /* pPie */
    NULL,                               /* pPolyBezier */
    NULL,                               /* pPolyBezierTo */
    NULL,                               /* pPolyDraw */
    NULL,                               /* pPolyPolygon */
    NULL,                               /* pPolyPolyline */
    NULL,                               /* pPolygon */
    NULL,                               /* pPolyline */
    NULL,                               /* pPolylineTo */
    NULL,                               /* pPutImage */
    NULL,                               /* pRealizeDefaultPalette */
    NULL,                               /* pRealizePalette */
    NULL,                               /* pRectangle */
    NULL,                               /* pResetDC */
    NULL,                               /* pRestoreDC */
    NULL,                               /* pRoundRect */
    NULL,                               /* pSaveDC */
    NULL,                               /* pScaleViewportExt */
    NULL,                               /* pScaleWindowExt */
    NULL,                               /* pSelectBitmap */
    NULL,                               /* pSelectBrush */
    NULL,                               /* pSelectClipPath */
9240
    freetype_SelectFont,                /* pSelectFont */
9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276
    NULL,                               /* pSelectPalette */
    NULL,                               /* pSelectPen */
    NULL,                               /* pSetArcDirection */
    NULL,                               /* pSetBkColor */
    NULL,                               /* pSetBkMode */
    NULL,                               /* pSetDCBrushColor */
    NULL,                               /* pSetDCPenColor */
    NULL,                               /* pSetDIBColorTable */
    NULL,                               /* pSetDIBitsToDevice */
    NULL,                               /* pSetDeviceClipping */
    NULL,                               /* pSetDeviceGammaRamp */
    NULL,                               /* pSetLayout */
    NULL,                               /* pSetMapMode */
    NULL,                               /* pSetMapperFlags */
    NULL,                               /* pSetPixel */
    NULL,                               /* pSetPolyFillMode */
    NULL,                               /* pSetROP2 */
    NULL,                               /* pSetRelAbs */
    NULL,                               /* pSetStretchBltMode */
    NULL,                               /* pSetTextAlign */
    NULL,                               /* pSetTextCharacterExtra */
    NULL,                               /* pSetTextColor */
    NULL,                               /* pSetTextJustification */
    NULL,                               /* pSetViewportExt */
    NULL,                               /* pSetViewportOrg */
    NULL,                               /* pSetWindowExt */
    NULL,                               /* pSetWindowOrg */
    NULL,                               /* pSetWorldTransform */
    NULL,                               /* pStartDoc */
    NULL,                               /* pStartPage */
    NULL,                               /* pStretchBlt */
    NULL,                               /* pStretchDIBits */
    NULL,                               /* pStrokeAndFillPath */
    NULL,                               /* pStrokePath */
    NULL,                               /* pUnrealizePalette */
    NULL,                               /* pWidenPath */
9277 9278
    NULL,                               /* pD3DKMTCheckVidPnExclusiveOwnership */
    NULL,                               /* pD3DKMTSetVidPnSourceOwner */
9279
    NULL,                               /* wine_get_wgl_driver */
9280
    NULL,                               /* wine_get_vulkan_driver */
9281
    GDI_PRIORITY_FONT_DRV               /* priority */
9282 9283
};

9284 9285
#else /* HAVE_FREETYPE */

9286 9287
struct font_fileinfo;

9288 9289
/*************************************************************************/

9290 9291 9292 9293 9294
BOOL WineEngInit(void)
{
    return FALSE;
}

9295 9296
INT WineEngAddFontResourceEx(LPCWSTR file, DWORD flags, PVOID pdv)
{
9297
    FIXME("(%s, %x, %p): stub\n", debugstr_w(file), flags, pdv);
9298 9299 9300 9301 9302
    return 1;
}

INT WineEngRemoveFontResourceEx(LPCWSTR file, DWORD flags, PVOID pdv)
{
9303
    FIXME("(%s, %x, %p): stub\n", debugstr_w(file), flags, pdv);
9304 9305
    return TRUE;
}
9306

9307 9308
HANDLE WineEngAddFontMemResourceEx(PVOID pbFont, DWORD cbFont, PVOID pdv, DWORD *pcFonts)
{
9309
    FIXME("(%p, %u, %p, %p): stub\n", pbFont, cbFont, pdv, pcFonts);
9310 9311 9312
    return NULL;
}

9313 9314 9315 9316 9317 9318 9319
BOOL WineEngCreateScalableFontResource( DWORD hidden, LPCWSTR resource,
                                        LPCWSTR font_file, LPCWSTR font_path )
{
    FIXME("stub\n");
    return FALSE;
}

9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330
/*************************************************************************
 *             GetRasterizerCaps   (GDI32.@)
 */
BOOL WINAPI GetRasterizerCaps( LPRASTERIZER_STATUS lprs, UINT cbNumBytes)
{
    lprs->nSize = sizeof(RASTERIZER_STATUS);
    lprs->wFlags = 0;
    lprs->nLanguageID = 0;
    return TRUE;
}

9331 9332 9333 9334 9335 9336 9337 9338
/*************************************************************************
 *             GetFontFileData   (GDI32.@)
 */
BOOL WINAPI GetFontFileData( DWORD instance_id, DWORD unknown, UINT64 offset, void *buff, DWORD buff_size )
{
    return FALSE;
}

9339 9340 9341
/*************************************************************************
 *             GetFontFileInfo   (GDI32.@)
 */
9342
BOOL WINAPI GetFontFileInfo( DWORD instance_id, DWORD unknown, struct font_fileinfo *info, SIZE_T size, SIZE_T *needed)
9343 9344 9345 9346 9347
{
    *needed = 0;
    return FALSE;
}

9348
#endif /* HAVE_FREETYPE */