font.c 271 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3 4
/*
 * GDI font objects
 *
 * Copyright 1993 Alexandre Julliard
Alexandre Julliard's avatar
Alexandre Julliard committed
5
 *           1997 Alex Korobka
6
 * Copyright 2002,2003 Shachar Shemesh
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * 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
20
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Alexandre Julliard's avatar
Alexandre Julliard committed
21
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
22

23
#include <limits.h>
24
#include <stdarg.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
25
#include <stdlib.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
26
#include <string.h>
27
#include <assert.h>
28
#include "winerror.h"
29
#include "windef.h"
30
#include "winbase.h"
31
#include "winnls.h"
32
#include "winternl.h"
33
#include "winreg.h"
34
#include "gdi_private.h"
35
#include "resource.h"
36
#include "wine/exception.h"
37
#include "wine/heap.h"
38
#include "wine/rbtree.h"
39
#include "wine/debug.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
40

41
WINE_DEFAULT_DEBUG_CHANNEL(font);
42

43
static HKEY wine_fonts_key;
44
static HKEY wine_fonts_cache_key;
45

46 47 48 49 50 51 52 53 54 55 56
struct font_physdev
{
    struct gdi_physdev dev;
    struct gdi_font   *font;
};

static inline struct font_physdev *get_font_dev( PHYSDEV dev )
{
    return (struct font_physdev *)dev;
}

57 58
struct gdi_font_family
{
59 60
    struct wine_rb_entry    name_entry;
    struct wine_rb_entry    second_name_entry;
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    unsigned int            refcount;
    WCHAR                   family_name[LF_FACESIZE];
    WCHAR                   second_name[LF_FACESIZE];
    struct list             faces;
    struct gdi_font_family *replacement;
};

struct gdi_font_face
{
    struct list   entry;
    unsigned int  refcount;
    WCHAR        *style_name;
    WCHAR        *full_name;
    WCHAR        *file;
    void         *data_ptr;
    SIZE_T        data_size;
    UINT          face_index;
    FONTSIGNATURE fs;
    DWORD         ntmFlags;
    DWORD         version;
    DWORD         flags;                 /* ADDFONT flags */
    BOOL          scalable;
    struct bitmap_font_size    size;     /* set if face is a bitmap */
    struct gdi_font_family    *family;
    struct gdi_font_enum_data *cached_enum_data;
86
    struct wine_rb_entry       full_name_entry;
87 88
};

89 90
static const struct font_backend_funcs *font_funcs;

91 92
static const MAT2 identity = { {0,1}, {0,0}, {0,0}, {0,1} };

93 94 95
static UINT font_smoothing = GGO_BITMAP;
static UINT subpixel_orientation = GGO_GRAY4_BITMAP;
static BOOL antialias_fakes = TRUE;
96
static struct font_gamma_ramp font_gamma_ramp;
97

98
static void add_face_to_cache( struct gdi_font_face *face );
99 100
static void remove_face_from_cache( struct gdi_font_face *face );

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
static inline WCHAR facename_tolower( WCHAR c )
{
    if (c >= 'A' && c <= 'Z') return c - 'A' + 'a';
    else if (c > 127) return RtlDowncaseUnicodeChar( c );
    else return c;
}

static inline int facename_compare( const WCHAR *str1, const WCHAR *str2, SIZE_T len )
{
    while (len--)
    {
        WCHAR c1 = facename_tolower( *str1++ ), c2 = facename_tolower( *str2++ );
        if (c1 != c2) return c1 - c2;
        else if (!c1) return 0;
    }
    return 0;
}

119 120 121 122 123 124 125
  /* Device -> World size conversion */

/* Performs a device to world transformation on the specified width (which
 * is in integer format).
 */
static inline INT INTERNAL_XDSTOWS(DC *dc, INT width)
{
126
    double floatWidth;
127 128

    /* Perform operation with floating point */
129
    floatWidth = (double)width * dc->xformVport2World.eM11;
130 131 132 133 134 135 136 137 138
    /* Round to integers */
    return GDI_ROUND(floatWidth);
}

/* Performs a device to world transformation on the specified size (which
 * is in integer format).
 */
static inline INT INTERNAL_YDSTOWS(DC *dc, INT height)
{
139
    double floatHeight;
140 141

    /* Perform operation with floating point */
142
    floatHeight = (double)height * dc->xformVport2World.eM22;
143 144 145 146
    /* Round to integers */
    return GDI_ROUND(floatHeight);
}

147 148 149 150 151 152 153 154 155 156 157 158
/* scale width and height but don't mirror them */

static inline INT width_to_LP( DC *dc, INT width )
{
    return GDI_ROUND( (double)width * fabs( dc->xformVport2World.eM11 ));
}

static inline INT height_to_LP( DC *dc, INT height )
{
    return GDI_ROUND( (double)height * fabs( dc->xformVport2World.eM22 ));
}

159 160 161 162 163 164
static inline INT INTERNAL_YWSTODS(DC *dc, INT height)
{
    POINT pt[2];
    pt[0].x = pt[0].y = 0;
    pt[1].x = 0;
    pt[1].y = height;
165
    lp_to_dp(dc, pt, 2);
166 167
    return pt[1].y - pt[0].y;
}
168

169 170 171 172 173
static inline BOOL is_win9x(void)
{
    return GetVersion() & 0x80000000;
}

174 175 176
static inline WCHAR *strdupW( const WCHAR *p )
{
    WCHAR *ret;
177
    DWORD len = (lstrlenW(p) + 1) * sizeof(WCHAR);
178 179 180 181 182
    ret = HeapAlloc(GetProcessHeap(), 0, len);
    memcpy(ret, p, len);
    return ret;
}

183
static HGDIOBJ FONT_SelectObject( HGDIOBJ handle, HDC hdc );
184 185
static INT FONT_GetObjectA( HGDIOBJ handle, INT count, LPVOID buffer );
static INT FONT_GetObjectW( HGDIOBJ handle, INT count, LPVOID buffer );
186
static BOOL FONT_DeleteObject( HGDIOBJ handle );
187

188
static const struct gdi_obj_funcs fontobj_funcs =
189 190 191 192 193 194 195 196
{
    FONT_SelectObject,  /* pSelectObject */
    FONT_GetObjectA,    /* pGetObjectA */
    FONT_GetObjectW,    /* pGetObjectW */
    NULL,               /* pUnrealizeObject */
    FONT_DeleteObject   /* pDeleteObject */
};

197 198 199 200 201
typedef struct
{
    LOGFONTW    logfont;
} FONTOBJ;

202
struct font_enum
Alexandre Julliard's avatar
Alexandre Julliard committed
203
{
204
  LPLOGFONTW          lpLogFontParam;
205
  FONTENUMPROCW       lpEnumFunc;
206
  LPARAM              lpData;
207
  BOOL                unicode;
208
  HDC                 hdc;
209
  INT                 retval;
210
};
211

212 213 214 215
/*
 *  For TranslateCharsetInfo
 */
#define MAXTCIINDEX 32
216
static const CHARSETINFO FONT_tci[MAXTCIINDEX] = {
217
  /* ANSI */
218 219 220 221 222 223 224 225 226
  { ANSI_CHARSET, 1252, {{0,0,0,0},{FS_LATIN1,0}} },
  { EASTEUROPE_CHARSET, 1250, {{0,0,0,0},{FS_LATIN2,0}} },
  { RUSSIAN_CHARSET, 1251, {{0,0,0,0},{FS_CYRILLIC,0}} },
  { GREEK_CHARSET, 1253, {{0,0,0,0},{FS_GREEK,0}} },
  { TURKISH_CHARSET, 1254, {{0,0,0,0},{FS_TURKISH,0}} },
  { HEBREW_CHARSET, 1255, {{0,0,0,0},{FS_HEBREW,0}} },
  { ARABIC_CHARSET, 1256, {{0,0,0,0},{FS_ARABIC,0}} },
  { BALTIC_CHARSET, 1257, {{0,0,0,0},{FS_BALTIC,0}} },
  { VIETNAMESE_CHARSET, 1258, {{0,0,0,0},{FS_VIETNAMESE,0}} },
227
  /* reserved by ANSI */
228 229 230 231 232 233 234
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
235
  /* ANSI and OEM */
236 237 238 239 240 241
  { THAI_CHARSET, 874, {{0,0,0,0},{FS_THAI,0}} },
  { SHIFTJIS_CHARSET, 932, {{0,0,0,0},{FS_JISJAPAN,0}} },
  { GB2312_CHARSET, 936, {{0,0,0,0},{FS_CHINESESIMP,0}} },
  { HANGEUL_CHARSET, 949, {{0,0,0,0},{FS_WANSUNG,0}} },
  { CHINESEBIG5_CHARSET, 950, {{0,0,0,0},{FS_CHINESETRAD,0}} },
  { JOHAB_CHARSET, 1361, {{0,0,0,0},{FS_JOHAB,0}} },
242
  /* reserved for alternate ANSI and OEM */
243 244 245 246 247 248 249 250
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
251
  /* reserved for system */
252 253
  { DEFAULT_CHARSET, 0, {{0,0,0,0},{FS_LATIN1,0}} },
  { SYMBOL_CHARSET, CP_SYMBOL, {{0,0,0,0},{FS_SYMBOL,0}} }
254 255
};

256
static const WCHAR * const default_serif_list[3] =
257
{
258 259 260
    L"Times New Roman",
    L"Liberation Serif",
    L"Bitstream Vera Serif"
261
};
262
static const WCHAR * const default_fixed_list[3] =
263
{
264 265 266
    L"Courier New",
    L"Liberation Mono",
    L"Bitstream Vera Sans Mono"
267
};
268
static const WCHAR * const default_sans_list[3] =
269
{
270 271 272
    L"Arial",
    L"Liberation Sans",
    L"Bitstream Vera Sans"
273
};
274 275 276
static WCHAR ff_roman_default[LF_FACESIZE];
static WCHAR ff_modern_default[LF_FACESIZE];
static WCHAR ff_swiss_default[LF_FACESIZE];
277

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
static const struct nls_update_font_list
{
    UINT ansi_cp, oem_cp;
    const char *oem, *fixed, *system;
    const char *courier, *serif, *small, *sserif_96, *sserif_120;
    /* these are for font substitutes */
    const char *shelldlg, *tmsrmn;
    const char *fixed_0, *system_0, *courier_0, *serif_0, *small_0, *sserif_0, *helv_0, *tmsrmn_0;
    struct subst { const char *from, *to; } arial_0, courier_new_0, times_new_roman_0;
} nls_update_font_list[] =
{
    /* Latin 1 (United States) */
    { 1252, 437, "vgaoem.fon", "vgafix.fon", "vgasys.fon",
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
      "Tahoma","Times New Roman"
    },
    /* Latin 1 (Multilingual) */
    { 1252, 850, "vga850.fon", "vgafix.fon", "vgasys.fon",
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
      "Tahoma","Times New Roman"  /* FIXME unverified */
    },
    /* Eastern Europe */
    { 1250, 852, "vga852.fon", "vgafixe.fon", "vgasyse.fon",
      "couree.fon", "serifee.fon", "smallee.fon", "sserifee.fon", "sseriffe.fon",
      "Tahoma","Times New Roman", /* FIXME unverified */
      "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" }
    },
    /* Cyrillic */
    { 1251, 866, "vga866.fon", "vgafixr.fon", "vgasysr.fon",
      "courer.fon", "serifer.fon", "smaller.fon", "sserifer.fon", "sseriffr.fon",
      "Tahoma","Times New Roman", /* FIXME unverified */
      "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" }
    },
    /* Greek */
    { 1253, 737, "vga869.fon", "vgafixg.fon", "vgasysg.fon",
      "coureg.fon", "serifeg.fon", "smalleg.fon", "sserifeg.fon", "sseriffg.fon",
      "Tahoma","Times New Roman", /* FIXME unverified */
      "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" }
    },
    /* Turkish */
    { 1254, 857, "vga857.fon", "vgafixt.fon", "vgasyst.fon",
      "couret.fon", "serifet.fon", "smallet.fon", "sserifet.fon", "sserifft.fon",
      "Tahoma","Times New Roman", /* FIXME unverified */
      "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" }
    },
    /* Hebrew */
    { 1255, 862, "vgaoem.fon", "vgaf1255.fon", "vgas1255.fon",
      "coue1255.fon", "sere1255.fon", "smae1255.fon", "ssee1255.fon", "ssef1255.fon",
      "Tahoma","Times New Roman", /* FIXME unverified */
      "Fixedsys,177", "System,177",
      "Courier New,177", "MS Serif,177", "Small Fonts,177",
      "MS Sans Serif,177", "MS Sans Serif,177", "MS Serif,177"
    },
    /* Arabic */
    { 1256, 720, "vgaoem.fon", "vgaf1256.fon", "vgas1256.fon",
      "coue1256.fon", "sere1256.fon", "smae1256.fon", "ssee1256.fon", "ssef1256.fon",
      "Microsoft Sans Serif","Times New Roman",
      "Fixedsys,178", "System,178",
      "Courier New,178", "MS Serif,178", "Small Fonts,178",
      "MS Sans Serif,178", "MS Sans Serif,178", "MS Serif,178"
    },
    /* Baltic */
    { 1257, 775, "vga775.fon", "vgaf1257.fon", "vgas1257.fon",
      "coue1257.fon", "sere1257.fon", "smae1257.fon", "ssee1257.fon", "ssef1257.fon",
      "Tahoma","Times New Roman", /* FIXME unverified */
      "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" }
    },
    /* Vietnamese */
    { 1258, 1258, "vga850.fon", "vgafix.fon", "vgasys.fon",
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
      "Tahoma","Times New Roman" /* FIXME unverified */
    },
    /* Thai */
    { 874, 874, "vga850.fon", "vgaf874.fon", "vgas874.fon",
      "coure.fon", "serife.fon", "smalle.fon", "ssee874.fon", "ssef874.fon",
      "Tahoma","Times New Roman" /* FIXME unverified */
    },
    /* Japanese */
    { 932, 932, "vga932.fon", "jvgafix.fon", "jvgasys.fon",
      "coure.fon", "serife.fon", "jsmalle.fon", "sserife.fon", "sseriff.fon",
      "MS UI Gothic","MS Serif"
    },
    /* Chinese Simplified */
    { 936, 936, "vga936.fon", "svgafix.fon", "svgasys.fon",
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
      "SimSun", "NSimSun"
    },
    /* Korean */
    { 949, 949, "vga949.fon", "hvgafix.fon", "hvgasys.fon",
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
      "Gulim",  "Batang"
    },
    /* Chinese Traditional */
    { 950, 950, "vga950.fon", "cvgafix.fon", "cvgasys.fon",
      "coure.fon", "serife.fon", "smalle.fon", "sserife.fon", "sseriff.fon",
      "PMingLiU",  "MingLiU"
    }
};

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 */
}

410
static CRITICAL_SECTION font_cs;
411 412 413 414 415 416
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &font_cs,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": font_cs") }
};
417
static CRITICAL_SECTION font_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
418

419 420 421 422
#ifndef WINE_FONT_DIR
#define WINE_FONT_DIR "fonts"
#endif

423 424 425 426 427 428 429 430
#ifdef WORDS_BIGENDIAN
#define GET_BE_WORD(x) (x)
#define GET_BE_DWORD(x) (x)
#else
#define GET_BE_WORD(x) RtlUshortByteSwap(x)
#define GET_BE_DWORD(x) RtlUlongByteSwap(x)
#endif

431
static void get_fonts_data_dir_path( const WCHAR *file, WCHAR *path )
432
{
433 434 435 436
    if (GetEnvironmentVariableW( L"WINEDATADIR", path, MAX_PATH ))
        lstrcatW( path, L"\\" WINE_FONT_DIR "\\" );
    else if (GetEnvironmentVariableW( L"WINEBUILDDIR", path, MAX_PATH ))
        lstrcatW( path, L"\\fonts\\" );
437

438 439
    lstrcatW( path, file );
    if (path[5] == ':') memmove( path, path + 4, (lstrlenW(path) - 3) * sizeof(WCHAR) );
440 441 442
    else path[1] = '\\';  /* change \??\ to \\?\ */
}

443
static void get_fonts_win_dir_path( const WCHAR *file, WCHAR *path )
444 445
{
    GetWindowsDirectoryW( path, MAX_PATH );
446
    lstrcatW( path, L"\\fonts\\" );
447
    lstrcatW( path, file );
448 449
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463
/* font substitutions */

struct gdi_font_subst
{
    struct list entry;
    int         from_charset;
    int         to_charset;
    WCHAR       names[1];
};

static struct list font_subst_list = LIST_INIT(font_subst_list);

static inline WCHAR *get_subst_to_name( struct gdi_font_subst *subst )
{
464
    return subst->names + lstrlenW( subst->names ) + 1;
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
}

static void dump_gdi_font_subst(void)
{
    struct gdi_font_subst *subst;

    LIST_FOR_EACH_ENTRY( subst, &font_subst_list, struct gdi_font_subst, entry )
    {
        if (subst->from_charset != -1 || subst->to_charset != -1)
	    TRACE("%s,%d -> %s,%d\n", debugstr_w(subst->names),
                  subst->from_charset, debugstr_w(get_subst_to_name(subst)), subst->to_charset);
	else
	    TRACE("%s -> %s\n", debugstr_w(subst->names), debugstr_w(get_subst_to_name(subst)));
    }
}

481
static const WCHAR *get_gdi_font_subst( const WCHAR *from_name, int from_charset, int *to_charset )
482 483 484 485 486
{
    struct gdi_font_subst *subst;

    LIST_FOR_EACH_ENTRY( subst, &font_subst_list, struct gdi_font_subst, entry )
    {
487
        if (!facename_compare( subst->names, from_name, -1 ) &&
488 489 490 491 492 493 494 495 496
           (subst->from_charset == from_charset || subst->from_charset == -1))
        {
            if (to_charset) *to_charset = subst->to_charset;
            return get_subst_to_name( subst );
        }
    }
    return NULL;
}

497
static BOOL add_gdi_font_subst( const WCHAR *from_name, int from_charset, const WCHAR *to_name, int to_charset )
498 499
{
    struct gdi_font_subst *subst;
500
    int len = lstrlenW( from_name ) + lstrlenW( to_name ) + 2;
501 502 503 504 505 506

    if (get_gdi_font_subst( from_name, from_charset, NULL )) return FALSE;  /* already exists */

    if (!(subst = HeapAlloc( GetProcessHeap(), 0,
                             offsetof( struct gdi_font_subst, names[len] ))))
        return FALSE;
507 508
    lstrcpyW( subst->names, from_name );
    lstrcpyW( get_subst_to_name(subst), to_name );
509 510 511 512 513 514
    subst->from_charset = from_charset;
    subst->to_charset = to_charset;
    list_add_tail( &font_subst_list, &subst->entry );
    return TRUE;
}

515
static void load_gdi_font_subst(void)
516 517 518 519 520
{
    HKEY hkey;
    DWORD i = 0, type, dlen, vlen;
    WCHAR value[64], data[64], *p;

521
    if (RegOpenKeyW( HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes",
522 523 524 525 526 527 528 529 530
                     &hkey)) return;

    dlen = sizeof(data);
    vlen = ARRAY_SIZE(value);
    while (!RegEnumValueW( hkey, i++, value, &vlen, NULL, &type, (BYTE *)data, &dlen ))
    {
        int from_charset = -1, to_charset = -1;

        TRACE("Got %s=%s\n", debugstr_w(value), debugstr_w(data));
531
        if ((p = wcsrchr( value, ',' )) && p[1])
532 533
        {
            *p++ = 0;
534
            from_charset = wcstol( p, NULL, 10 );
535
        }
536
        if ((p = wcsrchr( data, ',' )) && p[1])
537 538
        {
            *p++ = 0;
539
            to_charset = wcstol( p, NULL, 10 );
540 541 542 543 544 545 546 547 548 549 550 551 552 553
        }

        /* Win 2000 doesn't allow mapping between different charsets
           or mapping of DEFAULT_CHARSET */
        if ((!from_charset || to_charset == from_charset) && to_charset != DEFAULT_CHARSET)
            add_gdi_font_subst( value, from_charset, data, to_charset );

        /* reset dlen and vlen */
        dlen = sizeof(data);
        vlen = ARRAY_SIZE(value);
    }
    RegCloseKey( hkey );
}

554 555
/* font families */

556 557 558 559
static int family_namecmp( const WCHAR *str1, const WCHAR *str2 )
{
    int prio1, prio2, vert1 = (str1[0] == '@' ? 1 : 0), vert2 = (str2[0] == '@' ? 1 : 0);

560 561 562
    if (!facename_compare( str1, ff_swiss_default, LF_FACESIZE - 1 )) prio1 = 0;
    else if (!facename_compare( str1, ff_modern_default, LF_FACESIZE - 1 )) prio1 = 1;
    else if (!facename_compare( str1, ff_roman_default, LF_FACESIZE - 1 )) prio1 = 2;
563 564
    else prio1 = 3;

565 566 567
    if (!facename_compare( str2, ff_swiss_default, LF_FACESIZE - 1 )) prio2 = 0;
    else if (!facename_compare( str2, ff_modern_default, LF_FACESIZE - 1 )) prio2 = 1;
    else if (!facename_compare( str2, ff_roman_default, LF_FACESIZE - 1 )) prio2 = 2;
568 569 570 571
    else prio2 = 3;

    if (prio1 != prio2) return prio1 - prio2;
    if (vert1 != vert2) return vert1 - vert2;
572
    return facename_compare( str1 + vert1, str2 + vert2, LF_FACESIZE - 1 );
573 574 575 576 577 578 579 580 581 582 583 584 585 586
}

static int family_name_compare( const void *key, const struct wine_rb_entry *entry )
{
    const struct gdi_font_family *family = WINE_RB_ENTRY_VALUE( entry, const struct gdi_font_family, name_entry );
    return family_namecmp( (const WCHAR *)key, family->family_name );
}

static int family_second_name_compare( const void *key, const struct wine_rb_entry *entry )
{
    const struct gdi_font_family *family = WINE_RB_ENTRY_VALUE( entry, const struct gdi_font_family, second_name_entry );
    return family_namecmp( (const WCHAR *)key, family->second_name );
}

587 588 589 590 591 592
static int face_full_name_compare( const void *key, const struct wine_rb_entry *entry )
{
    const struct gdi_font_face *face = WINE_RB_ENTRY_VALUE( entry, const struct gdi_font_face, full_name_entry );
    return facename_compare( (const WCHAR *)key, face->full_name, LF_FULLFACESIZE - 1 );
}

593 594
static struct wine_rb_tree family_name_tree = { family_name_compare };
static struct wine_rb_tree family_second_name_tree = { family_second_name_compare };
595 596 597 598 599 600
static struct wine_rb_tree face_full_name_tree = { face_full_name_compare };

static int face_is_in_full_name_tree( const struct gdi_font_face *face )
{
    return face->full_name_entry.parent || face_full_name_tree.root == &face->full_name_entry;
}
601

602
static struct gdi_font_family *create_family( const WCHAR *name, const WCHAR *second_name )
603 604 605 606 607
{
    struct gdi_font_family *family = HeapAlloc( GetProcessHeap(), 0, sizeof(*family) );

    family->refcount = 1;
    lstrcpynW( family->family_name, name, LF_FACESIZE );
608
    if (second_name && second_name[0] && wcsicmp( name, second_name ))
609 610 611 612 613 614
    {
        lstrcpynW( family->second_name, second_name, LF_FACESIZE );
        add_gdi_font_subst( second_name, -1, name, -1 );
    }
    else family->second_name[0] = 0;
    list_init( &family->faces );
615
    family->replacement = NULL;
616 617
    wine_rb_put( &family_name_tree, family->family_name, &family->name_entry );
    if (family->second_name[0]) wine_rb_put( &family_second_name_tree, family->second_name, &family->second_name_entry );
618 619 620
    return family;
}

621
static void release_family( struct gdi_font_family *family )
622 623 624
{
    if (--family->refcount) return;
    assert( list_empty( &family->faces ));
625 626
    wine_rb_remove( &family_name_tree, &family->name_entry );
    if (family->second_name[0]) wine_rb_remove( &family_second_name_tree, &family->second_name_entry );
627
    if (family->replacement) release_family( family->replacement );
628 629 630
    HeapFree( GetProcessHeap(), 0, family );
}

631
static struct gdi_font_family *find_family_from_name( const WCHAR *name )
632
{
633 634 635
    struct wine_rb_entry *entry;
    if (!(entry = wine_rb_get( &family_name_tree, name ))) return NULL;
    return WINE_RB_ENTRY_VALUE( entry, struct gdi_font_family, name_entry );
636 637
}

638
static struct gdi_font_family *find_family_from_any_name( const WCHAR *name )
639
{
640
    struct wine_rb_entry *entry;
641
    struct gdi_font_family *family;
642 643 644
    if ((family = find_family_from_name( name ))) return family;
    if (!(entry = wine_rb_get( &family_second_name_tree, name ))) return NULL;
    return WINE_RB_ENTRY_VALUE( entry, struct gdi_font_family, second_name_entry );
645 646
}

647 648 649 650 651 652 653
static struct gdi_font_face *find_face_from_full_name( const WCHAR *full_name )
{
    struct wine_rb_entry *entry;
    if (!(entry = wine_rb_get( &face_full_name_tree, full_name ))) return NULL;
    return WINE_RB_ENTRY_VALUE( entry, struct gdi_font_face, full_name_entry );
}

654 655 656 657 658
static const struct list *get_family_face_list( const struct gdi_font_family *family )
{
    return family->replacement ? &family->replacement->faces : &family->faces;
}

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
static struct gdi_font_face *family_find_face_from_filename( struct gdi_font_family *family, const WCHAR *file_name )
{
    struct gdi_font_face *face;
    const WCHAR *file;
    LIST_FOR_EACH_ENTRY( face, get_family_face_list(family), struct gdi_font_face, entry )
    {
        if (!face->file) continue;
        file = wcsrchr(face->file, '\\');
        if (!file) file = face->file;
        else file++;
        if (wcsicmp( file, file_name )) continue;
        face->refcount++;
        return face;
    }
    return NULL;
}

676 677 678 679 680 681 682
static struct gdi_font_face *find_face_from_filename( const WCHAR *file_name, const WCHAR *family_name )
{
    struct gdi_font_family *family;
    struct gdi_font_face *face;

    TRACE( "looking for file %s name %s\n", debugstr_w(file_name), debugstr_w(family_name) );

683
    if (!family_name)
684
    {
685 686 687
        WINE_RB_FOR_EACH_ENTRY( family, &family_name_tree, struct gdi_font_family, name_entry )
            if ((face = family_find_face_from_filename( family, file_name ))) return face;
        return NULL;
688
    }
689 690 691

    if (!(family = find_family_from_name( family_name ))) return NULL;
    return family_find_face_from_filename( family, file_name );
692 693
}

694 695 696 697 698 699 700 701 702 703 704 705 706
static BOOL add_family_replacement( const WCHAR *new_name, const WCHAR *replace )
{
    struct gdi_font_family *new_family, *family;
    struct gdi_font_face *face;
    WCHAR new_name_vert[LF_FACESIZE], replace_vert[LF_FACESIZE];

    if (!(family = find_family_from_any_name( replace )))
    {
        TRACE( "%s is not available. Skip this replacement.\n", debugstr_w(replace) );
        return FALSE;
    }

    if (!(new_family = create_family( new_name, NULL ))) return FALSE;
707 708
    new_family->replacement = family;
    family->refcount++;
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
    TRACE( "mapping %s to %s\n", debugstr_w(replace), debugstr_w(new_name) );

    /* also add replacement for vertical font if necessary */
    if (replace[0] == '@') return TRUE;
    if (list_empty( &family->faces )) return TRUE;
    face = LIST_ENTRY( list_head(&family->faces), struct gdi_font_face, entry );
    if (!(face->fs.fsCsb[0] & FS_DBCS_MASK)) return TRUE;

    new_name_vert[0] = '@';
    lstrcpynW( new_name_vert + 1, new_name, LF_FACESIZE - 1 );
    if (find_family_from_any_name( new_name_vert )) return TRUE;  /* already exists */

    replace_vert[0] = '@';
    lstrcpynW( replace_vert + 1, replace, LF_FACESIZE - 1 );
    add_family_replacement( new_name_vert, replace_vert );
    return TRUE;
}

/*
 * The replacement list is a way to map an entire font
 * family onto another family.  For example adding
 *
 * [HKCU\Software\Wine\Fonts\Replacements]
 * "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.
 */
738
static void load_gdi_font_replacements(void)
739 740 741 742 743 744
{
    HKEY hkey;
    DWORD i = 0, type, dlen, vlen;
    WCHAR value[LF_FACESIZE], data[1024];

    /* @@ Wine registry key: HKCU\Software\Wine\Fonts\Replacements */
745
    if (RegOpenKeyW( wine_fonts_key, L"Replacements", &hkey )) return;
746 747 748 749 750 751 752 753 754 755 756 757 758 759

    dlen = sizeof(data);
    vlen = ARRAY_SIZE(value);
    while (!RegEnumValueW( hkey, i++, value, &vlen, NULL, &type, (BYTE *)data, &dlen ))
    {
        /* "NewName"="Oldname" */
        if (!find_family_from_any_name( value ))
        {
            if (type == REG_MULTI_SZ)
            {
                WCHAR *replace = data;
                while (*replace)
                {
                    if (add_family_replacement( value, replace )) break;
760
                    replace += lstrlenW(replace) + 1;
761 762 763 764 765 766 767 768 769 770 771 772 773
                }
            }
            else if (type == REG_SZ) add_family_replacement( value, data );
        }
        else TRACE("%s is available. Skip this replacement.\n", debugstr_w(value));

        /* reset dlen and vlen */
        dlen = sizeof(data);
        vlen = ARRAY_SIZE(value);
    }
    RegCloseKey( hkey );
}

774 775 776 777 778
static void dump_gdi_font_list(void)
{
    struct gdi_font_family *family;
    struct gdi_font_face *face;

779
    WINE_RB_FOR_EACH_ENTRY( family, &family_name_tree, struct gdi_font_family, name_entry )
780 781 782 783 784 785 786 787 788 789 790 791
    {
        TRACE( "Family: %s\n", debugstr_w(family->family_name) );
        LIST_FOR_EACH_ENTRY( face, &family->faces, struct gdi_font_face, entry )
        {
            TRACE( "\t%s\t%s\t%08x", debugstr_w(face->style_name), debugstr_w(face->full_name),
                   face->fs.fsCsb[0] );
            if (!face->scalable) TRACE(" %d", face->size.height );
            TRACE("\n");
	}
    }
}

792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
static BOOL enum_fallbacks( DWORD pitch_and_family, int index, WCHAR buffer[LF_FACESIZE] )
{
    if (index < 3)
    {
        const WCHAR * const *defaults;

        if ((pitch_and_family & FIXED_PITCH) || (pitch_and_family & 0xf0) == FF_MODERN)
            defaults = default_fixed_list;
        else if ((pitch_and_family & 0xf0) == FF_ROMAN)
            defaults = default_serif_list;
        else
            defaults = default_sans_list;
        lstrcpynW( buffer, defaults[index], LF_FACESIZE );
        return TRUE;
    }
    return font_funcs->enum_family_fallbacks( pitch_and_family, index - 3, buffer );
}

810
static void set_default_family( DWORD pitch_and_family, WCHAR *default_name )
811
{
812
    struct wine_rb_entry *entry;
813 814
    WCHAR name[LF_FACESIZE];
    int i = 0;
815

816
    while (enum_fallbacks( pitch_and_family, i++, name ))
817
    {
818 819 820 821
        if (!(entry = wine_rb_get( &family_name_tree, name ))) continue;
        wine_rb_remove( &family_name_tree, entry );
        lstrcpynW( default_name, name, LF_FACESIZE - 1 );
        wine_rb_put( &family_name_tree, name, entry );
822
        return;
823 824 825 826 827
    }
}

static void reorder_font_list(void)
{
828 829 830
    set_default_family( FF_ROMAN, ff_roman_default );
    set_default_family( FF_MODERN, ff_modern_default );
    set_default_family( FF_SWISS, ff_swiss_default );
831 832
}

833
static void release_face( struct gdi_font_face *face )
834 835 836 837 838 839 840 841
{
    if (--face->refcount) return;
    if (face->family)
    {
        if (face->flags & ADDFONT_ADD_TO_CACHE) remove_face_from_cache( face );
        list_remove( &face->entry );
        release_family( face->family );
    }
842
    if (face_is_in_full_name_tree( face )) wine_rb_remove( &face_full_name_tree, &face->full_name_entry );
843 844 845 846 847 848 849
    HeapFree( GetProcessHeap(), 0, face->file );
    HeapFree( GetProcessHeap(), 0, face->style_name );
    HeapFree( GetProcessHeap(), 0, face->full_name );
    HeapFree( GetProcessHeap(), 0, face->cached_enum_data );
    HeapFree( GetProcessHeap(), 0, face );
}

850 851 852 853 854 855 856
static int remove_font( const WCHAR *file, DWORD flags )
{
    struct gdi_font_family *family, *family_next;
    struct gdi_font_face *face, *face_next;
    int count = 0;

    EnterCriticalSection( &font_cs );
857
    WINE_RB_FOR_EACH_ENTRY_DESTRUCTOR( family, family_next, &family_name_tree, struct gdi_font_family, name_entry )
858 859 860 861 862 863
    {
        family->refcount++;
        LIST_FOR_EACH_ENTRY_SAFE( face, face_next, &family->faces, struct gdi_font_face, entry )
        {
            if (!face->file) continue;
            if (LOWORD(face->flags) != LOWORD(flags)) continue;
864
            if (!wcsicmp( face->file, file ))
865 866 867 868 869 870 871 872 873 874 875 876
            {
                TRACE( "removing matching face %s refcount %d\n", debugstr_w(face->file), face->refcount );
                release_face( face );
                count++;
            }
	}
        release_family( family );
    }
    LeaveCriticalSection( &font_cs );
    return count;
}

877 878
static inline BOOL faces_equal( const struct gdi_font_face *f1, const struct gdi_font_face *f2 )
{
879
    if (facename_compare( f1->full_name, f2->full_name, -1 )) return FALSE;
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    if (f1->scalable) return TRUE;
    if (f1->size.y_ppem != f2->size.y_ppem) return FALSE;
    return !memcmp( &f1->fs, &f2->fs, sizeof(f1->fs) );
}

static inline int style_order( const struct gdi_font_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 face %s with flags 0x%08x\n",
              debugstr_w(face->full_name), face->ntmFlags );
        return 9999;
    }
}

904
static BOOL insert_face_in_family_list( struct gdi_font_face *face, struct gdi_font_family *family )
905 906 907 908 909 910 911 912 913 914 915
{
    struct gdi_font_face *cursor;

    LIST_FOR_EACH_ENTRY( cursor, &family->faces, struct gdi_font_face, entry )
    {
        if (faces_equal( face, cursor ))
        {
            TRACE( "Already loaded face %s in family %s, original version %x, new version %x\n",
                   debugstr_w(face->full_name), debugstr_w(family->family_name),
                   cursor->version, face->version );

916
            if (face->file && cursor->file && !wcsicmp( face->file, cursor->file ))
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
            {
                cursor->refcount++;
                TRACE("Font %s already in list, refcount now %d\n",
                      debugstr_w(face->file), cursor->refcount);
                return FALSE;
            }
            if (face->version <= cursor->version)
            {
                TRACE("Original font %s is newer so skipping %s\n",
                      debugstr_w(cursor->file), debugstr_w(face->file));
                return FALSE;
            }
            else
            {
                TRACE("Replacing original %s with %s\n",
                      debugstr_w(cursor->file), debugstr_w(face->file));
                list_add_before( &cursor->entry, &face->entry );
                face->family = family;
                family->refcount++;
                face->refcount++;
937 938 939 940 941
                if (face_is_in_full_name_tree( cursor ))
                {
                    wine_rb_replace( &face_full_name_tree, &cursor->full_name_entry, &face->full_name_entry );
                    memset( &cursor->full_name_entry, 0, sizeof(cursor->full_name_entry) );
                }
942 943 944 945 946 947 948 949 950 951
                release_face( cursor );
                return TRUE;
            }
        }
        if (style_order( face ) < style_order( cursor )) break;
    }

    TRACE( "Adding face %s in family %s from %s\n", debugstr_w(face->full_name),
           debugstr_w(family->family_name), debugstr_w(face->file) );
    list_add_before( &cursor->entry, &face->entry );
952
    if (face->scalable) wine_rb_put( &face_full_name_tree, face->full_name, &face->full_name_entry );
953 954 955 956 957 958
    face->family = family;
    family->refcount++;
    face->refcount++;
    return TRUE;
}

959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
static struct gdi_font_face *create_face( struct gdi_font_family *family, const WCHAR *style,
                                          const WCHAR *fullname, const WCHAR *file,
                                          void *data_ptr, SIZE_T data_size, UINT index, FONTSIGNATURE fs,
                                          DWORD ntmflags, DWORD version, DWORD flags,
                                          const struct bitmap_font_size *size )
{
    struct gdi_font_face *face = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*face) );

    face->refcount   = 1;
    face->style_name = strdupW( style );
    face->full_name  = strdupW( fullname );
    face->face_index = index;
    face->fs         = fs;
    face->ntmFlags   = ntmflags;
    face->version    = version;
    face->flags      = flags;
    face->data_ptr   = data_ptr;
    face->data_size  = data_size;
    if (file) face->file = strdupW( file );
    if (size) face->size = *size;
    else face->scalable = TRUE;
    if (insert_face_in_family_list( face, family )) return face;
    release_face( face );
    return NULL;
}

985 986 987 988 989
static int CDECL add_gdi_face( const WCHAR *family_name, const WCHAR *second_name,
                               const WCHAR *style, const WCHAR *fullname, const WCHAR *file,
                               void *data_ptr, SIZE_T data_size, UINT index, FONTSIGNATURE fs,
                               DWORD ntmflags, DWORD version, DWORD flags,
                               const struct bitmap_font_size *size )
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
{
    struct gdi_font_face *face;
    struct gdi_font_family *family;
    int ret = 0;

    if ((family = find_family_from_name( family_name ))) family->refcount++;
    else if (!(family = create_family( family_name, second_name ))) return ret;

    if ((face = create_face( family, style, fullname, file, data_ptr, data_size,
                             index, fs, ntmflags, version, flags, size )))
    {
        if (flags & ADDFONT_ADD_TO_CACHE) add_face_to_cache( face );
        release_face( face );
    }
    release_family( family );
    ret++;

    if (fs.fsCsb[0] & FS_DBCS_MASK)
    {
        WCHAR vert_family[LF_FACESIZE], vert_second[LF_FACESIZE], vert_full[LF_FULLFACESIZE];

        vert_family[0] = '@';
        lstrcpynW( vert_family + 1, family_name, LF_FACESIZE - 1 );

        if (second_name && second_name[0])
        {
            vert_second[0] = '@';
            lstrcpynW( vert_second + 1, second_name, LF_FACESIZE - 1 );
        }
        else vert_second[0] = 0;

        if (fullname)
        {
            vert_full[0] = '@';
            lstrcpynW( vert_full + 1, fullname, LF_FULLFACESIZE - 1 );
            fullname = vert_full;
        }

        if ((family = find_family_from_name( vert_family ))) family->refcount++;
        else if (!(family = create_family( vert_family, vert_second ))) return ret;

        if ((face = create_face( family, style, fullname, file, data_ptr, data_size,
                                 index, fs, ntmflags, version, flags | ADDFONT_VERTICAL_FONT, size )))
        {
            if (flags & ADDFONT_ADD_TO_CACHE) add_face_to_cache( face );
            release_face( face );
        }
        release_family( family );
        ret++;
    }
    return ret;
}

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
/* font cache */

struct cached_face
{
    DWORD                   index;
    DWORD                   flags;
    DWORD                   ntmflags;
    DWORD                   version;
    struct bitmap_font_size size;
    FONTSIGNATURE           fs;
    WCHAR                   full_name[1];
    /* WCHAR                file_name[]; */
};

static void load_face_from_cache( HKEY hkey_family, struct gdi_font_family *family,
                                  void *buffer, DWORD buffer_size, BOOL scalable )
{
    DWORD type, size, needed, index = 0;
    struct gdi_font_face *face;
    HKEY hkey_strike;
    WCHAR name[256];
    struct cached_face *cached = (struct cached_face *)buffer;

    size = sizeof(name);
    needed = buffer_size - sizeof(DWORD);
    while (!RegEnumValueW( hkey_family, index++, name, &size, NULL, &type, buffer, &needed ))
    {
        if (type == REG_BINARY && needed > sizeof(*cached))
        {
            ((DWORD *)buffer)[needed / sizeof(DWORD)] = 0;
1073
            if ((face = create_face( family, name, cached->full_name,
1074
                                     cached->full_name + lstrlenW(cached->full_name) + 1,
1075 1076 1077 1078 1079 1080 1081
                                     NULL, 0, cached->index, cached->fs, cached->ntmflags, cached->version,
                                     cached->flags, scalable ? NULL : &cached->size )))
            {
                if (!scalable)
                    TRACE("Adding bitmap size h %d w %d size %d x_ppem %d y_ppem %d\n",
                          face->size.height, face->size.width, face->size.size >> 6,
                          face->size.x_ppem >> 6, face->size.y_ppem >> 6);
1082

1083 1084 1085 1086
                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]);
1087

1088 1089
                release_face( face );
            }
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
        }
        size = sizeof(name);
        needed = buffer_size - sizeof(DWORD);
    }

    /* load bitmap strikes */

    index = 0;
    needed = buffer_size;
    while (!RegEnumKeyExW( hkey_family, index++, buffer, &needed, NULL, NULL, NULL, NULL ))
    {
        if (!RegOpenKeyExW( hkey_family, buffer, 0, KEY_ALL_ACCESS, &hkey_strike ))
        {
            load_face_from_cache( hkey_strike, family, buffer, buffer_size, FALSE );
            RegCloseKey( hkey_strike );
        }
        needed = buffer_size;
    }
}

static void load_font_list_from_cache(void)
{
    DWORD size, family_index = 0;
    struct gdi_font_family *family;
    HKEY hkey_family;
    WCHAR buffer[4096], second_name[LF_FACESIZE];

    size = sizeof(buffer);
    while (!RegEnumKeyExW( wine_fonts_cache_key, family_index++, buffer, &size, NULL, NULL, NULL, NULL ))
    {
        RegOpenKeyExW( wine_fonts_cache_key, buffer, 0, KEY_ALL_ACCESS, &hkey_family );
        TRACE("opened family key %s\n", debugstr_w(buffer));
        size = sizeof(second_name);
        if (RegQueryValueExW( hkey_family, NULL, NULL, NULL, (BYTE *)second_name, &size ))
            second_name[0] = 0;

        family = create_family( buffer, second_name );

        load_face_from_cache( hkey_family, family, buffer, sizeof(buffer), TRUE );

        RegCloseKey( hkey_family );
        release_family( family );
        size = sizeof(buffer);
    }
}

1136
static void add_face_to_cache( struct gdi_font_face *face )
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
{
    HKEY hkey_family, hkey_face;
    DWORD len, buffer[1024];
    struct cached_face *cached = (struct cached_face *)buffer;

    if (RegCreateKeyExW( wine_fonts_cache_key, face->family->family_name, 0, NULL, REG_OPTION_VOLATILE,
                         KEY_ALL_ACCESS, NULL, &hkey_family, NULL ))
        return;

    if (face->family->second_name[0])
        RegSetValueExW( hkey_family, NULL, 0, REG_SZ, (BYTE *)face->family->second_name,
1148
                        (lstrlenW( face->family->second_name ) + 1) * sizeof(WCHAR) );
1149 1150 1151 1152 1153

    if (!face->scalable)
    {
        WCHAR name[10];

1154
        swprintf( name, ARRAY_SIZE(name), L"%d", face->size.y_ppem );
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
        RegCreateKeyExW( hkey_family, name, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS,
                         NULL, &hkey_face, NULL);
    }
    else hkey_face = hkey_family;

    memset( cached, 0, sizeof(*cached) );
    cached->index = face->face_index;
    cached->flags = face->flags;
    cached->ntmflags = face->ntmFlags;
    cached->version = face->version;
    cached->fs = face->fs;
    if (!face->scalable) cached->size = face->size;
1167 1168 1169 1170
    lstrcpyW( cached->full_name, face->full_name );
    len = lstrlenW( face->full_name ) + 1;
    lstrcpyW( cached->full_name + len, face->file );
    len += lstrlenW( face->file ) + 1;
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

    RegSetValueExW( hkey_face, face->style_name, 0, REG_BINARY, (BYTE *)cached,
                    offsetof( struct cached_face, full_name[len] ));

    if (hkey_face != hkey_family) RegCloseKey( hkey_face );
    RegCloseKey( hkey_family );
}

static void remove_face_from_cache( struct gdi_font_face *face )
{
    HKEY hkey_family;

    if (RegOpenKeyExW( wine_fonts_cache_key, face->family->family_name, 0, KEY_ALL_ACCESS, &hkey_family ))
        return;

    if (!face->scalable)
    {
        WCHAR name[10];
1189
        swprintf( name, ARRAY_SIZE(name), L"%d", face->size.y_ppem );
1190 1191 1192 1193 1194 1195 1196
        RegDeleteKeyW( hkey_family, name );
    }
    else RegDeleteValueW( hkey_family, face->style_name );

    RegCloseKey( hkey_family );
}

1197 1198
/* font links */

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
struct gdi_font_link
{
    struct list            entry;
    struct list            links;
    WCHAR                  name[LF_FACESIZE];
    FONTSIGNATURE          fs;
};

struct gdi_font_link_entry
{
    struct list            entry;
    FONTSIGNATURE          fs;
    WCHAR                  family_name[LF_FACESIZE];
};

1214 1215
static struct list font_links = LIST_INIT(font_links);

1216
static struct gdi_font_link *find_gdi_font_link( const WCHAR *name )
1217 1218 1219 1220
{
    struct gdi_font_link *link;

    LIST_FOR_EACH_ENTRY( link, &font_links, struct gdi_font_link, entry )
1221
        if (!facename_compare( link->name, name, LF_FACESIZE - 1 )) return link;
1222 1223 1224
    return NULL;
}

1225 1226
static struct gdi_font_family *find_family_from_font_links( const WCHAR *name, const WCHAR *subst,
                                                            FONTSIGNATURE fs )
1227 1228 1229 1230 1231 1232 1233
{
    struct gdi_font_link *link;
    struct gdi_font_link_entry *entry;
    struct gdi_font_family *family;

    LIST_FOR_EACH_ENTRY( link, &font_links, struct gdi_font_link, entry )
    {
1234 1235
        if (!facename_compare( link->name, name, LF_FACESIZE - 1 ) ||
            (subst && !facename_compare( link->name, subst, LF_FACESIZE - 1 )))
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 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
        {
            TRACE("found entry in system list\n");
            LIST_FOR_EACH_ENTRY( entry, &link->links, struct gdi_font_link_entry, entry )
            {
                const struct gdi_font_link *links;

                family = find_family_from_name( entry->family_name );
                if (!fs.fsCsb[0]) return family;
                if (fs.fsCsb[0] & entry->fs.fsCsb[0]) return family;
                if ((links = find_gdi_font_link( family->family_name )) && fs.fsCsb[0] & links->fs.fsCsb[0])
                    return family;
            }
        }
    }
    return NULL;
}

static struct gdi_font_link *add_gdi_font_link( const WCHAR *name )
{
    struct gdi_font_link *link = find_gdi_font_link( name );

    if (link) return link;
    if ((link = HeapAlloc( GetProcessHeap(), 0, sizeof(*link) )))
    {
        lstrcpynW( link->name, name, LF_FACESIZE );
        memset( &link->fs, 0, sizeof(link->fs) );
        list_init( &link->links );
        list_add_tail( &font_links, &link->entry );
    }
    return link;
}

static void add_gdi_font_link_entry( struct gdi_font_link *link, const WCHAR *family_name, FONTSIGNATURE fs )
{
    struct gdi_font_link_entry *entry;

    entry = HeapAlloc( GetProcessHeap(), 0, sizeof(*entry) );
    lstrcpynW( entry->family_name, family_name, LF_FACESIZE );
    entry->fs = fs;
    link->fs.fsCsb[0] |= fs.fsCsb[0];
    link->fs.fsCsb[1] |= fs.fsCsb[1];
    list_add_tail( &link->links, &entry->entry );
}

static const WCHAR * const font_links_list[] =
{
1282 1283 1284
    L"Lucida Sans Unicode",
    L"Microsoft Sans Serif",
    L"Tahoma"
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
};

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 */
1296 1297
    { L"Tahoma", /* FIXME unverified ordering */
      { L"MS UI Gothic", L"SimSun", L"Gulim", L"PMingLiU", NULL }
1298 1299 1300 1301 1302
    },
    /* Below lists are courtesy of
     * http://blogs.msdn.com/michkap/archive/2005/06/18/430507.aspx
     */
    /* Japanese */
1303 1304
    { L"MS UI Gothic",
      { L"MS UI Gothic", L"PMingLiU", L"SimSun", L"Gulim", NULL }
1305 1306
    },
    /* Chinese Simplified */
1307 1308
    { L"SimSun",
      { L"SimSun", L"PMingLiU", L"MS UI Gothic", L"Batang", NULL }
1309 1310
    },
    /* Korean */
1311 1312
    { L"Gulim",
      { L"Gulim", L"PMingLiU", L"MS UI Gothic", L"SimSun", NULL }
1313 1314
    },
    /* Chinese Traditional */
1315 1316
    { L"PMingLiU",
      { L"PMingLiU", L"SimSun", L"MS UI Gothic", L"Batang", NULL }
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
    }
};

static void populate_system_links( const WCHAR *name, const WCHAR * const *values )
{
    struct gdi_font_family *family;
    struct gdi_font_face *face;
    struct gdi_font_link *font_link;
    const WCHAR *file, *value;

    /* Don't store fonts that are only substitutes for other fonts */
    if (get_gdi_font_subst( name, -1, NULL ))
    {
        TRACE( "%s: Internal SystemLink entry for substituted font, ignoring\n", debugstr_w(name) );
        return;
    }
    font_link = add_gdi_font_link( name );
    for ( ; *values; values++)
    {
1336
        if  (!facename_compare( name, *values, -1 )) continue;
1337 1338 1339 1340 1341 1342
        if (!(value = get_gdi_font_subst( *values, -1, NULL ))) value = *values;
        if (!(family = find_family_from_name( value ))) continue;
        /* use first extant filename for this Family */
        LIST_FOR_EACH_ENTRY( face, get_family_face_list(family), struct gdi_font_face, entry )
        {
            if (!face->file) continue;
1343
            file = wcsrchr(face->file, '\\');
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
            if (!file) file = face->file;
            else file++;
            if ((face = find_face_from_filename( file, value )))
            {
                add_gdi_font_link_entry( font_link, face->family->family_name, face->fs );
                TRACE( "added internal SystemLink for %s to %s in %s\n",
                       debugstr_w(name), debugstr_w(value), debugstr_w(file) );
            }
            else TRACE( "Unable to find file %s face name %s\n", debugstr_w(file), debugstr_w(value) );
            break;
        }
    }
}

static void load_system_links(void)
{
    HKEY hkey;
    DWORD i, j;
    const WCHAR *shelldlg_name;
    struct gdi_font_link *font_link, *system_font_link;
    struct gdi_font_face *face;

1366 1367
    if (!RegOpenKeyW( HKEY_LOCAL_MACHINE,
                      L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontLink\\SystemLink", &hkey ))
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
    {
        WCHAR value[MAX_PATH], data[1024];
        DWORD type, val_len, data_len;
        WCHAR *entry, *next;

        val_len = ARRAY_SIZE(value);
        data_len = sizeof(data);
        i = 0;
        while (!RegEnumValueW( hkey, i++, value, &val_len, NULL, &type, (LPBYTE)data, &data_len))
        {
            /* Don't store fonts that are only substitutes for other fonts */
            if (!get_gdi_font_subst( value, -1, NULL ))
            {
                font_link = add_gdi_font_link( value );
                for (entry = data; (char *)entry < (char *)data + data_len && *entry; entry = next)
                {
                    const WCHAR *family_name = NULL;
                    WCHAR *p;

                    TRACE("%s: %s\n", debugstr_w(value), debugstr_w(entry));

1389 1390
                    next = entry + lstrlenW(entry) + 1;
                    if ((p = wcschr( entry, ',' )))
1391 1392
                    {
                        *p++ = 0;
1393
                        while (iswspace(*p)) p++;
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
                        if (!(family_name = get_gdi_font_subst( p, -1, NULL ))) family_name = p;
                    }
                    if ((face = find_face_from_filename( entry, family_name )))
                    {
                        add_gdi_font_link_entry( font_link, face->family->family_name, face->fs );
                        TRACE("Adding file %s index %u\n", debugstr_w(face->file), face->face_index);
                    }
                    else TRACE( "Unable to find file %s family %s\n",
                                debugstr_w(entry), debugstr_w(family_name) );
                }
            }
            else TRACE("%s: SystemLink entry for substituted font, ignoring\n", debugstr_w(value));

            val_len = ARRAY_SIZE(value);
            data_len = sizeof(data);
        }
        RegCloseKey( hkey );
    }

1413
    if ((shelldlg_name = get_gdi_font_subst( L"MS Shell Dlg", -1, NULL )))
1414 1415 1416 1417 1418
    {
        for (i = 0; i < ARRAY_SIZE(font_links_defaults_list); i++)
        {
            const WCHAR *subst = get_gdi_font_subst( font_links_defaults_list[i].shelldlg, -1, NULL );

1419 1420
            if ((!facename_compare( font_links_defaults_list[i].shelldlg, shelldlg_name, -1 ) ||
                 (subst && !facename_compare( subst, shelldlg_name, -1 ))))
1421 1422 1423
            {
                for (j = 0; j < ARRAY_SIZE(font_links_list); j++)
                    populate_system_links( font_links_list[j], font_links_defaults_list[i].substitutes );
1424
                if (!facename_compare(shelldlg_name, font_links_defaults_list[i].substitutes[0], -1))
1425 1426 1427 1428 1429 1430 1431 1432 1433
                    populate_system_links( shelldlg_name, font_links_defaults_list[i].substitutes );
            }
        }
    }
    else WARN( "could not find FontSubstitute for MS Shell Dlg\n" );

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

1434 1435
    system_font_link = add_gdi_font_link( L"System" );
    if ((face = find_face_from_filename( L"tahoma.ttf", L"Tahoma" )))
1436 1437 1438 1439
    {
        add_gdi_font_link_entry( system_font_link, face->family->family_name, face->fs );
        TRACE("Found Tahoma in %s index %u\n", debugstr_w(face->file), face->face_index);
    }
1440
    if ((font_link = find_gdi_font_link( L"Tahoma" )))
1441 1442 1443 1444 1445 1446 1447
    {
        struct gdi_font_link_entry *entry;
        LIST_FOR_EACH_ENTRY( entry, &font_link->links, struct gdi_font_link_entry, entry )
            add_gdi_font_link_entry( system_font_link, entry->family_name, entry->fs );
    }
}

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
/* font matching */

static BOOL can_select_face( const struct gdi_font_face *face, FONTSIGNATURE fs, BOOL can_use_bitmap )
{
    struct gdi_font_link *font_link;

    if (!face->scalable && !can_use_bitmap) return FALSE;
    if (!fs.fsCsb[0]) return TRUE;
    if (fs.fsCsb[0] & face->fs.fsCsb[0]) return TRUE;
    if (!(font_link = find_gdi_font_link( face->family->family_name ))) return FALSE;
    if (fs.fsCsb[0] & font_link->fs.fsCsb[0]) return TRUE;
    return FALSE;
}

static struct gdi_font_face *find_best_matching_face( const struct gdi_font_family *family,
                                                      const LOGFONTW *lf, FONTSIGNATURE fs,
                                                      BOOL can_use_bitmap )
{
    struct gdi_font_face *face = NULL, *best = NULL, *best_bitmap = NULL;
    unsigned int best_score = 4;
    int best_diff = 0;
    int it = !!lf->lfItalic;
    int bd = lf->lfWeight > 550;
    int height = lf->lfHeight;

    LIST_FOR_EACH_ENTRY( face, get_family_face_list(family), struct gdi_font_face, entry )
    {
        int italic = !!(face->ntmFlags & NTM_ITALIC);
        int bold = !!(face->ntmFlags & NTM_BOLD);
        int score = (italic ^ it) + (bold ^ bd);

        if (!can_select_face( face, fs, can_use_bitmap )) continue;
        if (score > best_score) continue;
        TRACE( "(it=%d, bd=%d) is selected for (it=%d, bd=%d)\n", italic, bold, it, bd );
        best_score = score;
        best = face;
        if (best->scalable && best_score == 0) break;
        if (!best->scalable)
        {
            int diff;
            if (height > 0)
                diff = height - (signed int)best->size.height;
            else
                diff = -height - ((signed int)best->size.height - best->size.internal_leading);
            if (!best_bitmap ||
                (best_diff > 0 && diff >= 0 && diff < best_diff) ||
                (best_diff < 0 && diff > best_diff))
            {
                TRACE( "%d is better for %d diff was %d\n", best->size.height, height, best_diff );
                best_diff = diff;
                best_bitmap = best;
                if (best_score == 0 && best_diff == 0) break;
            }
        }
    }
    if (!best) return NULL;
    return best->scalable ? best : best_bitmap;
}

1507 1508 1509
static struct gdi_font_face *find_matching_face_by_name( const WCHAR *name, const WCHAR *subst,
                                                         const LOGFONTW *lf, FONTSIGNATURE fs,
                                                         BOOL can_use_bitmap )
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
{
    struct gdi_font_family *family;
    struct gdi_font_face *face;

    family = find_family_from_any_name( name );
    if (family && (face = find_best_matching_face( family, lf, fs, can_use_bitmap ))) return face;
    if (subst)
    {
        family = find_family_from_any_name( subst );
        if (family && (face = find_best_matching_face( family, lf, fs, can_use_bitmap ))) return face;
    }

    /* search by full face name */
1523
    WINE_RB_FOR_EACH_ENTRY( family, &family_name_tree, struct gdi_font_family, name_entry )
1524
        LIST_FOR_EACH_ENTRY( face, get_family_face_list(family), struct gdi_font_face, entry )
1525
            if (!facename_compare( face->full_name, name, LF_FACESIZE - 1 ) &&
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
                can_select_face( face, fs, can_use_bitmap ))
                return face;

    if ((family = find_family_from_font_links( name, subst, fs )))
    {
        if ((face = find_best_matching_face( family, lf, fs, can_use_bitmap ))) return face;
    }
    return NULL;
}

1536 1537
static struct gdi_font_face *find_any_face( const LOGFONTW *lf, FONTSIGNATURE fs,
                                            BOOL can_use_bitmap, BOOL want_vertical )
1538 1539 1540
{
    struct gdi_font_family *family;
    struct gdi_font_face *face;
1541
    WCHAR name[LF_FACESIZE + 1];
1542
    int i = 0;
1543

1544 1545 1546
    /* first try the family fallbacks */
    while (enum_fallbacks( lf->lfPitchAndFamily, i++, name ))
    {
1547
        if (want_vertical)
1548
        {
1549 1550
            memmove(name + 1, name, min(lstrlenW(name), LF_FACESIZE));
            name[0] = '@';
1551
        }
1552 1553 1554

        if (!(family = find_family_from_any_name(name))) continue;
        if ((face = find_best_matching_face( family, lf, fs, FALSE ))) return face;
1555 1556
    }
    /* otherwise try only scalable */
1557
    WINE_RB_FOR_EACH_ENTRY( family, &family_name_tree, struct gdi_font_family, name_entry )
1558 1559 1560 1561 1562
    {
        if ((family->family_name[0] == '@') == !want_vertical) continue;
        if ((face = find_best_matching_face( family, lf, fs, FALSE ))) return face;
    }
    if (!can_use_bitmap) return NULL;
1563
    /* then also bitmap fonts */
1564
    WINE_RB_FOR_EACH_ENTRY( family, &family_name_tree, struct gdi_font_family, name_entry )
1565 1566 1567 1568 1569 1570 1571
    {
        if ((family->family_name[0] == '@') == !want_vertical) continue;
        if ((face = find_best_matching_face( family, lf, fs, can_use_bitmap ))) return face;
    }
    return NULL;
}

1572 1573
static struct gdi_font_face *find_matching_face( const LOGFONTW *lf, CHARSETINFO *csi, BOOL can_use_bitmap,
                                                 const WCHAR **orig_name )
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
{
    BOOL want_vertical = (lf->lfFaceName[0] == '@');
    struct gdi_font_face *face;

    if (!TranslateCharsetInfo( (DWORD *)(INT_PTR)lf->lfCharSet, csi, TCI_SRCCHARSET ))
    {
        if (lf->lfCharSet != DEFAULT_CHARSET) FIXME( "Untranslated charset %d\n", lf->lfCharSet );
        csi->fs.fsCsb[0] = 0;
    }

    if (lf->lfFaceName[0])
    {
        int subst_charset;
        const WCHAR *subst = get_gdi_font_subst( lf->lfFaceName, lf->lfCharSet, &subst_charset );

	if (subst)
        {
	    TRACE( "substituting %s,%d -> %s,%d\n", debugstr_w(lf->lfFaceName), lf->lfCharSet,
                   debugstr_w(subst), (subst_charset != -1) ? subst_charset : lf->lfCharSet );
1593 1594
	    if (subst_charset != -1)
                TranslateCharsetInfo( (DWORD *)(INT_PTR)subst_charset, csi, TCI_SRCCHARSET );
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
            *orig_name = lf->lfFaceName;
	}

        if ((face = find_matching_face_by_name( lf->lfFaceName, subst, lf, csi->fs, can_use_bitmap )))
            return face;
    }
    *orig_name = NULL; /* substitution is no longer relevant */

    /* If requested charset was DEFAULT_CHARSET then try using charset
       corresponding to the current ansi codepage */
    if (!csi->fs.fsCsb[0])
    {
        INT acp = GetACP();
        if (!TranslateCharsetInfo( (DWORD *)(INT_PTR)acp, csi, TCI_SRCCODEPAGE ))
        {
            FIXME( "TCI failed on codepage %d\n", acp );
            csi->fs.fsCsb[0] = 0;
        }
    }

    if ((face = find_any_face( lf, csi->fs, can_use_bitmap, want_vertical ))) return face;
    if (csi->fs.fsCsb[0])
    {
        csi->fs.fsCsb[0] = 0;
        if ((face = find_any_face( lf, csi->fs, can_use_bitmap, want_vertical ))) return face;
    }
    if (want_vertical && (face = find_any_face( lf, csi->fs, can_use_bitmap, FALSE ))) return face;
    return NULL;
}

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
/* realized font objects */

#define FIRST_FONT_HANDLE 1
#define MAX_FONT_HANDLES  256

struct font_handle_entry
{
    struct gdi_font *font;
    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 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 struct gdi_font *get_font_from_handle( DWORD handle )
{
    struct font_handle_entry *entry = handle_entry( handle );

    if (entry) return entry->font;
    SetLastError( ERROR_INVALID_PARAMETER );
    return NULL;
}

static DWORD alloc_font_handle( struct gdi_font *font )
{
    struct font_handle_entry *entry;

    entry = next_free;
    if (entry)
        next_free = (struct font_handle_entry *)entry->font;
    else if (next_unused < font_handles + MAX_FONT_HANDLES)
        entry = next_unused++;
    else
    {
        ERR( "out of realized font handles\n" );
        return 0;
    }
    entry->font = font;
    if (++entry->generation == 0xffff) entry->generation = 1;
    return MAKELONG( entry - font_handles + FIRST_FONT_HANDLE, entry->generation );
}

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

    if ((entry = handle_entry( handle )))
    {
        entry->font = (struct gdi_font *)next_free;
        next_free = entry;
    }
}

1692
static struct gdi_font *alloc_gdi_font( const WCHAR *file, void *data_ptr, SIZE_T data_size )
1693
{
1694
    UINT len = file ? lstrlenW(file) : 0;
1695 1696
    struct gdi_font *font = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
                                       offsetof( struct gdi_font, file[len + 1] ));
1697

1698 1699
    font->refcount = 1;
    font->matrix.eM11 = font->matrix.eM22 = 1.0;
1700
    font->scale_y = 1;
1701
    font->kern_count = -1;
1702
    list_init( &font->child_fonts );
1703

1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    if (file)
    {
        WIN32_FILE_ATTRIBUTE_DATA info;
        if (GetFileAttributesExW( file, GetFileExInfoStandard, &info ))
        {
            font->writetime = info.ftLastWriteTime;
            font->data_size = (LONGLONG)info.nFileSizeHigh << 32 | info.nFileSizeLow;
            memcpy( font->file, file, len * sizeof(WCHAR) );
        }
    }
    else
    {
        font->data_ptr = data_ptr;
        font->data_size = data_size;
    }

1720
    font->handle = alloc_font_handle( font );
1721 1722 1723
    return font;
}

1724
static void free_gdi_font( struct gdi_font *font )
1725
{
1726
    DWORD i;
1727
    struct gdi_font *child, *child_next;
1728

1729
    if (font->private) font_funcs->destroy_font( font );
1730
    free_font_handle( font->handle );
1731 1732 1733 1734 1735
    LIST_FOR_EACH_ENTRY_SAFE( child, child_next, &font->child_fonts, struct gdi_font, entry )
    {
        list_remove( &child->entry );
        free_gdi_font( child );
    }
1736
    for (i = 0; i < font->gm_size; i++) HeapFree( GetProcessHeap(), 0, font->gm[i] );
1737 1738 1739 1740
    HeapFree( GetProcessHeap(), 0, font->otm.otmpFamilyName );
    HeapFree( GetProcessHeap(), 0, font->otm.otmpStyleName );
    HeapFree( GetProcessHeap(), 0, font->otm.otmpFaceName );
    HeapFree( GetProcessHeap(), 0, font->otm.otmpFullName );
1741
    HeapFree( GetProcessHeap(), 0, font->gm );
1742
    HeapFree( GetProcessHeap(), 0, font->kern_pairs );
1743
    HeapFree( GetProcessHeap(), 0, font->gsub_table );
1744 1745 1746
    HeapFree( GetProcessHeap(), 0, font );
}

1747
static inline const WCHAR *get_gdi_font_name( struct gdi_font *font )
1748
{
1749
    return (WCHAR *)font->otm.otmpFamilyName;
1750 1751
}

1752 1753
static struct gdi_font *create_gdi_font( const struct gdi_font_face *face, const WCHAR *family_name,
                                         const LOGFONTW *lf )
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
{
    struct gdi_font *font;

    if (!(font = alloc_gdi_font( face->file, face->data_ptr, face->data_size ))) return NULL;
    font->fs = face->fs;
    font->lf = *lf;
    font->fake_italic = (lf->lfItalic && !(face->ntmFlags & NTM_ITALIC));
    font->fake_bold = (lf->lfWeight > 550 && !(face->ntmFlags & NTM_BOLD));
    font->scalable = face->scalable;
    font->face_index = face->face_index;
    font->ntmFlags = face->ntmFlags;
    font->aa_flags = HIWORD( face->flags );
    if (!family_name) family_name = face->family->family_name;
1767 1768 1769
    font->otm.otmpFamilyName = (char *)strdupW( family_name );
    font->otm.otmpStyleName = (char *)strdupW( face->style_name );
    font->otm.otmpFaceName = (char *)strdupW( face->full_name );
1770 1771 1772
    return font;
}

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
struct glyph_metrics
{
    GLYPHMETRICS gm;
    ABC          abc;  /* metrics of the unrotated char */
    BOOL         init;
};

#define GM_BLOCK_SIZE 128

/* TODO: GGO format support */
1783
static BOOL get_gdi_font_glyph_metrics( struct gdi_font *font, UINT index, GLYPHMETRICS *gm, ABC *abc )
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
{
    UINT block = index / GM_BLOCK_SIZE;
    UINT entry = index % GM_BLOCK_SIZE;

    if (block < font->gm_size && 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;
}

1802 1803
static void set_gdi_font_glyph_metrics( struct gdi_font *font, UINT index,
                                        const GLYPHMETRICS *gm, const ABC *abc )
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
{
    UINT block = index / GM_BLOCK_SIZE;
    UINT entry = index % GM_BLOCK_SIZE;

    if (block >= font->gm_size)
    {
        struct glyph_metrics **ptr;

        if (font->gm)
            ptr = HeapReAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, font->gm, (block + 1) * sizeof(*ptr) );
        else
            ptr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, (block + 1) * sizeof(*ptr) );
        if (!ptr) return;
        font->gm_size = block + 1;
        font->gm = ptr;
    }
    if (!font->gm[block])
    {
        font->gm[block] = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**font->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;
}

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020

/* GSUB table support */

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;

static GSUB_Script *GSUB_get_script_table( GSUB_Header *header, const char *tag )
{
    GSUB_ScriptList *script;
    GSUB_Script *deflt = NULL;
    int i;

    script = (GSUB_ScriptList *)((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++)
    {
        int offset = GET_BE_WORD(script->ScriptRecord[i].Script);
        GSUB_Script *scr = (GSUB_Script *)((BYTE *)script + offset);
        if (!memcmp( script->ScriptRecord[i].ScriptTag, tag, 4 )) return scr;
        if (!memcmp( script->ScriptRecord[i].ScriptTag, "dflt", 4 )) deflt = scr;
    }
    return deflt;
}

static GSUB_LangSys *GSUB_get_lang_table( GSUB_Script *script, const char *tag )
{
    int i, offset;
    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 = (GSUB_LangSys *)((BYTE *)script + offset);
        if (!memcmp( script->LangSysRecord[i].LangSysTag, tag, 4 )) return lang;
    }
    offset = GET_BE_WORD(script->DefaultLangSys);
    if (offset) return (GSUB_LangSys *)((BYTE *)script + offset);
    return NULL;
}

static GSUB_Feature *GSUB_get_feature( GSUB_Header *header, GSUB_LangSys *lang, const char *tag )
{
    int i;
    const GSUB_FeatureList *feature;

    feature = (GSUB_FeatureList *)((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 (!memcmp( feature->FeatureRecord[index].FeatureTag, tag, 4 ))
            return (GSUB_Feature *)((BYTE *)feature + GET_BE_WORD(feature->FeatureRecord[index].Feature));
    }
    return NULL;
}

static const char *get_opentype_script( const struct gdi_font *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";
    }
}

2021
static void *get_GSUB_vert_feature( struct gdi_font *font )
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 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 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
{
    GSUB_Header *header;
    GSUB_Script *script;
    GSUB_LangSys *language;
    GSUB_Feature *feature;
    DWORD length = font_funcs->get_font_data( font, MS_GSUB_TAG, 0, NULL, 0 );

    if (length == GDI_ERROR) return NULL;

    header = HeapAlloc( GetProcessHeap(), 0, length );
    font_funcs->get_font_data( font, MS_GSUB_TAG, 0, header, length );
    TRACE( "Loaded GSUB table of %i bytes\n", length );

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

    HeapFree( GetProcessHeap(), 0, header );
    return NULL;
}

static int GSUB_is_glyph_covered( void *table, UINT glyph )
{
    GSUB_CoverageFormat1 *cf1 = table;

    if (GET_BE_WORD(cf1->CoverageFormat) == 1)
    {
        int i, count = GET_BE_WORD(cf1->GlyphCount);

        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)
    {
        int i, count;
        GSUB_CoverageFormat2 *cf2 = table;

        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));
            }
        }
        return -1;
    }
    else ERR("Unknown CoverageFormat %i\n",GET_BE_WORD(cf1->CoverageFormat));

    return -1;
}

static UINT GSUB_apply_feature( GSUB_Header *header, GSUB_Feature *feature, UINT glyph )
{
    GSUB_LookupList *lookup = (GSUB_LookupList *)((BYTE *)header + GET_BE_WORD(header->LookupList));
    int i, j, offset;

    TRACE("%i lookups\n", GET_BE_WORD(feature->LookupCount));
    for (i = 0; i < GET_BE_WORD(feature->LookupCount); i++)
    {
        GSUB_LookupTable *look;
        offset = GET_BE_WORD(lookup->Lookup[GET_BE_WORD(feature->LookupListIndex[i])]);
        look = (GSUB_LookupTable *)((BYTE *)lookup + offset);
        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)
        {
            for (j = 0; j < GET_BE_WORD(look->SubTableCount); j++)
            {
                GSUB_SingleSubstFormat1 *ssf1;
                offset = GET_BE_WORD(look->SubTable[j]);
                ssf1 = (GSUB_SingleSubstFormat1 *)((BYTE *)look + offset);
                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));
                    if (GSUB_is_glyph_covered( (BYTE *) ssf1 + offset, glyph ) != -1)
                    {
                        TRACE("  Glyph 0x%x ->",glyph);
                        glyph += GET_BE_WORD(ssf1->DeltaGlyphID);
                        TRACE(" 0x%x\n",glyph);
                    }
                }
                else
                {
                    GSUB_SingleSubstFormat2 *ssf2;
                    int index, offset;

                    ssf2 = (GSUB_SingleSubstFormat2 *)ssf1;
                    offset = GET_BE_WORD(ssf1->Coverage);
                    TRACE("  subtype 2,  glyph count %i\n", GET_BE_WORD(ssf2->GlyphCount));
                    index = GSUB_is_glyph_covered( (BYTE *)ssf2 + offset, glyph );
                    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);
                    }
                }
            }
        }
        else FIXME("We only handle SubType 1\n");
    }
    return glyph;
}

2147
static UINT get_GSUB_vert_glyph( struct gdi_font *font, UINT glyph )
2148
{
2149
    if (!glyph) return glyph;
2150 2151 2152 2153
    if (!font->gsub_table) return glyph;
    return GSUB_apply_feature( font->gsub_table, font->vert_feature, glyph );
}

2154 2155
static void add_child_font( struct gdi_font *font, const WCHAR *family_name )
{
2156
    FONTSIGNATURE fs = {{0}};
2157
    struct gdi_font *child;
2158
    struct gdi_font_face *face;
2159

2160
    if (!(face = find_matching_face_by_name( family_name, NULL, &font->lf, fs, FALSE ))) return;
2161

2162
    if (!(child = create_gdi_font( face, family_name, &font->lf ))) return;
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
    child->matrix = font->matrix;
    child->can_use_bitmap = font->can_use_bitmap;
    child->scale_y = font->scale_y;
    child->aveWidth = font->aveWidth;
    child->charset = font->charset;
    child->codepage = font->codepage;
    child->base_font = font;
    list_add_tail( &font->child_fonts, &child->entry );
    TRACE( "created child font %p for base %p\n", child, font );
}

2174
static void create_child_font_list( struct gdi_font *font )
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
{
    struct gdi_font_link *font_link;
    struct gdi_font_link_entry *entry;
    const WCHAR* font_name;

    if (!(font_name = get_gdi_font_subst( get_gdi_font_name(font), -1, NULL )))
        font_name = get_gdi_font_name( font );

    if ((font_link = find_gdi_font_link( font_name )))
    {
        TRACE("found entry in system list\n");
        LIST_FOR_EACH_ENTRY( entry, &font_link->links, struct gdi_font_link_entry, entry )
            add_child_font( font, entry->family_name );
    }
    /*
     * 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 (is_dbcs_ansi_cp(GetACP()) && font->charset != SYMBOL_CHARSET && font->charset != OEM_CHARSET &&
2194
        facename_compare( font_name, L"Microsoft Sans Serif", -1 ) != 0)
2195
    {
2196
        if ((font_link = find_gdi_font_link( L"Microsoft Sans Serif" )))
2197 2198 2199 2200 2201 2202 2203 2204
        {
            TRACE("found entry in default fallback list\n");
            LIST_FOR_EACH_ENTRY( entry, &font_link->links, struct gdi_font_link_entry, entry )
                add_child_font( font, entry->family_name );
        }
    }
}

2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
/* font cache */

static struct list gdi_font_list = LIST_INIT( gdi_font_list );
static struct list unused_gdi_font_list = LIST_INIT( unused_gdi_font_list );
static unsigned int unused_font_count;
#define UNUSED_CACHE_SIZE 10

static BOOL fontcmp( const struct gdi_font *font, DWORD hash, const LOGFONTW *lf,
                     const FMAT2 *matrix, BOOL can_use_bitmap )
{
    if (font->hash != hash) return TRUE;
    if (memcmp( &font->matrix, matrix, sizeof(*matrix))) return TRUE;
    if (memcmp( &font->lf, lf, offsetof(LOGFONTW, lfFaceName))) return TRUE;
    if (!font->can_use_bitmap != !can_use_bitmap) return TRUE;
2219
    return facename_compare( font->lf.lfFaceName, lf->lfFaceName, -1 );
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
}

static DWORD hash_font( const LOGFONTW *lf, const FMAT2 *matrix, BOOL can_use_bitmap )
{
    DWORD hash = 0, *ptr, two_chars;
    WORD *pwc;
    unsigned int i;

    for (i = 0, ptr = (DWORD *)matrix; i < sizeof(*matrix) / sizeof(DWORD); i++, ptr++)
        hash ^= *ptr;
    for(i = 0, ptr = (DWORD *)lf; i < 7; i++, ptr++)
        hash ^= *ptr;
    for(i = 0, ptr = (DWORD *)lf->lfFaceName; i < LF_FACESIZE/2; i++, ptr++)
    {
        two_chars = *ptr;
        pwc = (WCHAR *)&two_chars;
        if(!*pwc) break;
2237
        *pwc = towupper(*pwc);
2238
        pwc++;
2239
        *pwc = towupper(*pwc);
2240 2241 2242 2243 2244 2245 2246
        hash ^= two_chars;
        if(!*pwc) break;
    }
    hash ^= !can_use_bitmap;
    return hash;
}

2247
static void cache_gdi_font( struct gdi_font *font )
2248 2249 2250 2251 2252 2253 2254 2255 2256
{
    static DWORD cache_num = 1;

    font->cache_num = cache_num++;
    font->hash = hash_font( &font->lf, &font->matrix, font->can_use_bitmap );
    list_add_head( &gdi_font_list, &font->entry );
    TRACE( "font %p\n", font );
}

2257
static struct gdi_font *find_cached_gdi_font( const LOGFONTW *lf, const FMAT2 *matrix, BOOL can_use_bitmap )
2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
{
    struct gdi_font *font;
    DWORD hash = hash_font( lf, matrix, can_use_bitmap );

    /* try the in-use list */
    LIST_FOR_EACH_ENTRY( font, &gdi_font_list, struct gdi_font, entry )
    {
        if (fontcmp( font, hash, lf, matrix, can_use_bitmap )) continue;
        list_remove( &font->entry );
        list_add_head( &gdi_font_list, &font->entry );
        if (!font->refcount++)
        {
            list_remove( &font->unused_entry );
            unused_font_count--;
        }
        return font;
    }
    return NULL;
}

static void release_gdi_font( struct gdi_font *font )
{
    if (!font) return;
    if (--font->refcount) return;

    TRACE( "font %p\n", font );

    /* add it to the unused list */
2286
    EnterCriticalSection( &font_cs );
2287 2288 2289 2290 2291 2292 2293 2294 2295
    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 gdi_font, unused_entry );
        TRACE( "freeing %p\n", font );
        list_remove( &font->entry );
        list_remove( &font->unused_entry );
        free_gdi_font( font );
    }
2296 2297
    else unused_font_count++;
    LeaveCriticalSection( &font_cs );
2298 2299
}

2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
static void add_font_list(HKEY hkey, const struct nls_update_font_list *fl, int dpi)
{
    const char *sserif = (dpi <= 108) ? fl->sserif_96 : fl->sserif_120;

    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);
    RegSetValueExA(hkey, "MS Sans Serif", 0, REG_SZ, (const BYTE *)sserif, strlen(sserif)+1);
    RegSetValueExA(hkey, "Small Fonts", 0, REG_SZ, (const BYTE *)fl->small, strlen(fl->small)+1);
}

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);
}

static void update_font_association_info(UINT current_ansi_codepage)
{
    if (is_dbcs_ansi_cp(current_ansi_codepage))
    {
        HKEY hkey;
2323
        if (RegCreateKeyW(HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\FontAssoc", &hkey) == ERROR_SUCCESS)
2324 2325
        {
            HKEY hsubkey;
2326
            if (RegCreateKeyW(hkey, L"Associated Charset", &hsubkey) == ERROR_SUCCESS)
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
            {
                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
2352
        RegDeleteTreeW(HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\FontAssoc");
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
}

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[] =
2366 2367 2368 2369
        L"SIMSUN.TTC,SimSun\0"
        L"MINGLIU.TTC,PMingLiu\0"
        L"MSGOTHIC.TTC,MS UI Gothic\0"
        L"BATANG.TTC,Batang\0";
2370
    static const WCHAR system_link_traditional_chinese[] =
2371 2372 2373 2374
        L"MINGLIU.TTC,PMingLiu\0"
        L"SIMSUN.TTC,SimSun\0"
        L"MSGOTHIC.TTC,MS UI Gothic\0"
        L"BATANG.TTC,Batang\0";
2375
    static const WCHAR system_link_japanese[] =
2376 2377 2378 2379
        L"MSGOTHIC.TTC,MS UI Gothic\0"
        L"MINGLIU.TTC,PMingLiU\0"
        L"SIMSUN.TTC,SimSun\0"
        L"GULIM.TTC,Gulim\0";
2380
    static const WCHAR system_link_korean[] =
2381 2382 2383 2384
        L"GULIM.TTC,Gulim\0"
        L"MSGOTHIC.TTC,MS UI Gothic\0"
        L"MINGLIU.TTC,PMingLiU\0"
        L"SIMSUN.TTC,SimSun\0";
2385
    static const WCHAR system_link_non_cjk[] =
2386 2387 2388 2389
        L"MSGOTHIC.TTC,MS UI Gothic\0"
        L"MINGLIU.TTC,PMingLiU\0"
        L"SIMSUN.TTC,SimSun\0"
        L"GULIM.TTC,Gulim\0";
2390 2391
    HKEY hkey;

2392 2393
    if (!RegCreateKeyW(HKEY_LOCAL_MACHINE,
                       L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontLink\\SystemLink", &hkey))
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
    {
        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);
        }
2420 2421 2422
        set_multi_value_key(hkey, L"Lucida Sans Unicode", link, len);
        set_multi_value_key(hkey, L"Microsoft Sans Serif", link, len);
        set_multi_value_key(hkey, L"Tahoma", link, len);
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
        RegCloseKey(hkey);
    }
}

static void update_codepage(void)
{
    char buf[40], cpbuf[40];
    HKEY hkey;
    DWORD len, type, size;
    UINT i, ansi_cp, oem_cp;
    DWORD screen_dpi, font_dpi = 0;
    BOOL done = FALSE;

    screen_dpi = get_dpi();
    if (!screen_dpi) screen_dpi = 96;

    size = sizeof(DWORD);
2440
    if (RegQueryValueExW(wine_fonts_key, L"LogPixels", NULL, &type, (BYTE *)&font_dpi, &size) ||
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
        type != REG_DWORD || size != sizeof(DWORD))
        font_dpi = 0;

    ansi_cp = GetACP();
    oem_cp = GetOEMCP();
    sprintf( cpbuf, "%u,%u", ansi_cp, oem_cp );

    buf[0] = 0;
    len = sizeof(buf);
    if (!RegQueryValueExA(wine_fonts_key, "Codepages", 0, &type, (BYTE *)buf, &len) && type == REG_SZ)
    {
        if (!strcmp( buf, cpbuf ) && screen_dpi == font_dpi) return;  /* already set correctly */
        TRACE("updating registry, codepages/logpixels changed %s/%u -> %u,%u/%u\n",
              buf, font_dpi, ansi_cp, oem_cp, screen_dpi);
    }
    else TRACE("updating registry, codepages/logpixels changed none -> %u,%u/%u\n",
               ansi_cp, oem_cp, screen_dpi);

    RegSetValueExA(wine_fonts_key, "Codepages", 0, REG_SZ, (const BYTE *)cpbuf, strlen(cpbuf)+1);
2460
    RegSetValueExW(wine_fonts_key, L"LogPixels", 0, REG_DWORD, (const BYTE *)&screen_dpi, sizeof(screen_dpi));
2461 2462 2463 2464 2465

    for (i = 0; i < ARRAY_SIZE(nls_update_font_list); i++)
    {
        if (nls_update_font_list[i].ansi_cp == ansi_cp && nls_update_font_list[i].oem_cp == oem_cp)
        {
2466
            if (!RegCreateKeyW( HKEY_CURRENT_CONFIG, L"Software\\Fonts", &hkey ))
2467 2468 2469 2470 2471 2472 2473 2474 2475
            {
                RegSetValueExA(hkey, "OEMFONT.FON", 0, REG_SZ, (const BYTE *)nls_update_font_list[i].oem,
                               strlen(nls_update_font_list[i].oem)+1);
                RegSetValueExA(hkey, "FIXEDFON.FON", 0, REG_SZ, (const BYTE *)nls_update_font_list[i].fixed,
                               strlen(nls_update_font_list[i].fixed)+1);
                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);
            }
2476 2477
            if (!RegCreateKeyW( HKEY_LOCAL_MACHINE,
                                L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts", &hkey ))
2478 2479 2480 2481
            {
                add_font_list(hkey, &nls_update_font_list[i], screen_dpi);
                RegCloseKey(hkey);
            }
2482 2483
            if (!RegCreateKeyW( HKEY_LOCAL_MACHINE,
                                L"Software\\Microsoft\\Windows\\CurrentVersion\\Fonts", &hkey ))
2484 2485 2486 2487
            {
                add_font_list(hkey, &nls_update_font_list[i], screen_dpi);
                RegCloseKey(hkey);
            }
2488 2489
            if (!RegCreateKeyW( HKEY_LOCAL_MACHINE,
                                L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes", &hkey ))
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
            {
                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);

                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 */
2516
            if (!RegCreateKeyW( HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes", &hkey ))
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
            {
                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);
                RegCloseKey(hkey);
            }
        }
    }
    if (!done)
        FIXME("there is no font defaults for codepages %u,%u\n", ansi_cp, oem_cp);

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

2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559

/*************************************************************
 * font_CreateDC
 */
static BOOL CDECL font_CreateDC( PHYSDEV *dev, LPCWSTR driver, LPCWSTR device,
                                 LPCWSTR output, const DEVMODEW *devmode )
{
    struct font_physdev *physdev;

    if (!font_funcs) return TRUE;
    if (!(physdev = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*physdev) ))) return FALSE;
    push_dc_driver( dev, &physdev->dev, &font_driver );
    return TRUE;
}


/*************************************************************
 * font_DeleteDC
 */
static BOOL CDECL font_DeleteDC( PHYSDEV dev )
{
    struct font_physdev *physdev = get_font_dev( dev );

2560
    release_gdi_font( physdev->font );
2561 2562 2563 2564 2565
    HeapFree( GetProcessHeap(), 0, physdev );
    return TRUE;
}


2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
struct gdi_font_enum_data
{
    ENUMLOGFONTEXW elf;
    NEWTEXTMETRICEXW ntm;
};

struct enum_charset
{
    DWORD mask;
    DWORD charset;
    DWORD script;
};

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;
}

static BOOL is_complex_script_ansi_cp( UINT ansi_cp )
{
    return (ansi_cp == 874 /* Thai */
            || ansi_cp == 1255 /* Hebrew */
            || ansi_cp == 1256 /* Arabic */
        );
}

/***************************************************
 * 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.
 * Above rule doesn't apply if the ANSI codepage uses complex script (e.g. Thai).
 * This function works as a filter other than DEFAULT_CHARSET case.
 */
static DWORD create_enum_charset_list(DWORD charset, struct enum_charset *list)
{
    struct enum_charset *start = list;
    CHARSETINFO csi;
    int i;

    if (TranslateCharsetInfo( ULongToPtr(charset), &csi, TCI_SRCCHARSET ) && csi.fs.fsCsb[0] != 0)
    {
        list->mask    = csi.fs.fsCsb[0];
        list->charset = csi.ciCharset;
        for (i = 0; i < 32; i++) if (csi.fs.fsCsb[0] & (1u << i)) list->script = i;
        list++;
    }
    else /* charset is DEFAULT_CHARSET or invalid. */
    {
        int acp = GetACP();
        DWORD mask = 0;

        /* Set the current codepage's charset as the first element. */
        if (!is_complex_script_ansi_cp(acp) &&
            TranslateCharsetInfo( (DWORD *)(INT_PTR)acp, &csi, TCI_SRCCODEPAGE ) &&
            csi.fs.fsCsb[0] != 0)
        {
            list->mask    = csi.fs.fsCsb[0];
            list->charset = csi.ciCharset;
            for (i = 0; i < 32; i++) if (csi.fs.fsCsb[0] & (1u << i)) list->script = i;
            mask |= csi.fs.fsCsb[0];
            list++;
        }

        /* Fill out left elements. */
        for (i = 0; i < 32; i++)
        {
            FONTSIGNATURE fs;
            fs.fsCsb[0] = 1u << i;
            fs.fsCsb[1] = 0;
            if (fs.fsCsb[0] & mask) continue; /* skip, already added. */
            if (!TranslateCharsetInfo( fs.fsCsb, &csi, TCI_SRCFONTSIG ))
                continue; /* skip, this is an invalid fsCsb bit. */
            list->mask    = fs.fsCsb[0];
            list->charset = csi.ciCharset;
            list->script  = i;
            mask |= fs.fsCsb[0];
            list++;
        }
        /* add catch all mask for remaining bits */
        if (~mask)
        {
            list->mask    = ~mask;
            list->charset = DEFAULT_CHARSET;
            list->script  = IDS_OTHER - IDS_FIRST_SCRIPT;
            list++;
        }
    }
    return list - start;
}

static UINT get_font_type( const NEWTEXTMETRICEXW *ntm )
{
    UINT ret = 0;

    if (ntm->ntmTm.tmPitchAndFamily & TMPF_TRUETYPE)  ret |= TRUETYPE_FONTTYPE;
    if (ntm->ntmTm.tmPitchAndFamily & TMPF_DEVICE)    ret |= DEVICE_FONTTYPE;
    if (!(ntm->ntmTm.tmPitchAndFamily & TMPF_VECTOR)) ret |= RASTER_FONTTYPE;
    return ret;
}

static BOOL get_face_enum_data( struct gdi_font_face *face, ENUMLOGFONTEXW *elf, NEWTEXTMETRICEXW *ntm )
{
    struct gdi_font *font;
    LOGFONTW lf = { .lfHeight = 100 };

    if (!(font = create_gdi_font( face, NULL, &lf ))) return FALSE;

    if (!font_funcs->load_font( font ))
    {
        free_gdi_font( font );
        return FALSE;
    }

    if (font_funcs->set_outline_text_metrics( font ))
    {
        memcpy( &ntm->ntmTm, &font->otm.otmTextMetrics, sizeof(TEXTMETRICW) );
        ntm->ntmTm.ntmSizeEM = font->otm.otmEMSquare;
        ntm->ntmTm.ntmCellHeight = font->ntmCellHeight;
        ntm->ntmTm.ntmAvgWidth = font->ntmAvgWidth;
    }
    else if (font_funcs->set_bitmap_text_metrics( font ))
    {
        memcpy( &ntm->ntmTm, &font->otm.otmTextMetrics, sizeof(TEXTMETRICW) );
        ntm->ntmTm.ntmSizeEM = ntm->ntmTm.tmHeight - ntm->ntmTm.tmInternalLeading;
        ntm->ntmTm.ntmCellHeight = ntm->ntmTm.tmHeight;
        ntm->ntmTm.ntmAvgWidth = ntm->ntmTm.tmAveCharWidth;
    }
    ntm->ntmTm.ntmFlags = font->ntmFlags;
    ntm->ntmFontSig = font->fs;

    elf->elfLogFont.lfEscapement = 0;
    elf->elfLogFont.lfOrientation = 0;
    elf->elfLogFont.lfHeight = ntm->ntmTm.tmHeight;
    elf->elfLogFont.lfWidth = ntm->ntmTm.tmAveCharWidth;
    elf->elfLogFont.lfWeight = ntm->ntmTm.tmWeight;
    elf->elfLogFont.lfItalic = ntm->ntmTm.tmItalic;
    elf->elfLogFont.lfUnderline = ntm->ntmTm.tmUnderlined;
    elf->elfLogFont.lfStrikeOut = ntm->ntmTm.tmStruckOut;
    elf->elfLogFont.lfCharSet = ntm->ntmTm.tmCharSet;
    elf->elfLogFont.lfOutPrecision = OUT_STROKE_PRECIS;
    elf->elfLogFont.lfClipPrecision = CLIP_STROKE_PRECIS;
    elf->elfLogFont.lfQuality = DRAFT_QUALITY;
    elf->elfLogFont.lfPitchAndFamily = (ntm->ntmTm.tmPitchAndFamily & 0xf1) + 1;
    lstrcpynW( elf->elfLogFont.lfFaceName, (WCHAR *)font->otm.otmpFamilyName, LF_FACESIZE );
    lstrcpynW( elf->elfFullName, (WCHAR *)font->otm.otmpFaceName, LF_FULLFACESIZE );
    lstrcpynW( elf->elfStyle, (WCHAR *)font->otm.otmpStyleName, LF_FACESIZE );

    free_gdi_font( font );
    return TRUE;
}

static BOOL family_matches( struct gdi_font_family *family, const WCHAR *face_name )
{
    struct gdi_font_face *face;

2740
    if (!facename_compare( face_name, family->family_name, LF_FACESIZE - 1 )) return TRUE;
2741
    LIST_FOR_EACH_ENTRY( face, get_family_face_list(family), struct gdi_font_face, entry )
2742
        if (!facename_compare( face_name, face->full_name, LF_FACESIZE - 1 )) return TRUE;
2743 2744 2745 2746 2747
    return FALSE;
}

static BOOL face_matches( const WCHAR *family_name, struct gdi_font_face *face, const WCHAR *face_name )
{
2748 2749
    if (!facename_compare( face_name, family_name, LF_FACESIZE - 1)) return TRUE;
    return !facename_compare( face_name, face->full_name, LF_FACESIZE - 1 );
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
}

static BOOL enum_face_charsets( const struct gdi_font_family *family, struct gdi_font_face *face,
                                struct enum_charset *list, DWORD count, FONTENUMPROCW proc, LPARAM lparam,
                                const WCHAR *subst )
{
    ENUMLOGFONTEXW elf;
    NEWTEXTMETRICEXW ntm;
    DWORD type, i;

    if (!face->cached_enum_data)
    {
        struct gdi_font_enum_data *data;

2764 2765
        if (!(data = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data) )) ||
            !get_face_enum_data( face, &data->elf, &data->ntm ))
2766 2767
        {
            HeapFree( GetProcessHeap(), 0, data );
2768
            return TRUE;
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
        }
        face->cached_enum_data = data;
    }

    elf = face->cached_enum_data->elf;
    ntm = face->cached_enum_data->ntm;
    type = get_font_type( &ntm );

    /* font replacement */
    if (family != face->family)
    {
        lstrcpynW( elf.elfLogFont.lfFaceName, family->family_name, LF_FACESIZE );
        lstrcpynW( elf.elfFullName, face->full_name, LF_FULLFACESIZE );
    }
    if (subst) lstrcpynW( elf.elfLogFont.lfFaceName, subst, LF_FACESIZE );

    for (i = 0; i < count; i++)
    {
        if (!face->scalable && face->fs.fsCsb[0] == 0)  /* OEM bitmap */
        {
            elf.elfLogFont.lfCharSet = ntm.ntmTm.tmCharSet = OEM_CHARSET;
            load_script_name( IDS_OEM_DOS - IDS_FIRST_SCRIPT, elf.elfScript );
            i = count; /* break out of loop after enumeration */
        }
        else
        {
            if (!(face->fs.fsCsb[0] & list[i].mask)) continue;
            /* use the DEFAULT_CHARSET case only if no other charset is present */
            if (list[i].charset == DEFAULT_CHARSET && (face->fs.fsCsb[0] & ~list[i].mask)) continue;
            elf.elfLogFont.lfCharSet = ntm.ntmTm.tmCharSet = list[i].charset;
            load_script_name( list[i].script, elf.elfScript );
            if (!elf.elfScript[0]) FIXME("Unknown elfscript for id %u\n", list[i].script);
        }
        TRACE( "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),
               elf.elfLogFont.lfCharSet, type, debugstr_w(elf.elfScript),
               elf.elfLogFont.lfItalic, elf.elfLogFont.lfWeight, ntm.ntmTm.ntmFlags );
        /* release section before callback (FIXME) */
        LeaveCriticalSection( &font_cs );
        if (!proc( &elf.elfLogFont, (TEXTMETRICW *)&ntm, type, lparam )) return FALSE;
        EnterCriticalSection( &font_cs );
    }
    return TRUE;
}

2814 2815 2816 2817 2818
/*************************************************************
 * font_EnumFonts
 */
static BOOL CDECL font_EnumFonts( PHYSDEV dev, LOGFONTW *lf, FONTENUMPROCW proc, LPARAM lparam )
{
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
    struct gdi_font_family *family;
    struct gdi_font_face *face;
    struct enum_charset enum_charsets[32];
    DWORD count, charset;

    charset = lf ? lf->lfCharSet : DEFAULT_CHARSET;

    count = create_enum_charset_list( charset, enum_charsets );

    EnterCriticalSection( &font_cs );

    if (lf && lf->lfFaceName[0])
    {
        const WCHAR *face_name = get_gdi_font_subst( lf->lfFaceName, charset, NULL );
        const WCHAR *orig_name = NULL;

        TRACE( "facename = %s charset %d\n", debugstr_w(lf->lfFaceName), charset );
        if (face_name)
        {
            orig_name = lf->lfFaceName;
            TRACE( "substituting %s -> %s\n", debugstr_w(lf->lfFaceName), debugstr_w(face_name) );
        }
        else face_name = lf->lfFaceName;

2843
        WINE_RB_FOR_EACH_ENTRY( family, &family_name_tree, struct gdi_font_family, name_entry )
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
        {
            if (!family_matches(family, face_name)) continue;
            LIST_FOR_EACH_ENTRY( face, get_family_face_list(family), struct gdi_font_face, entry )
            {
                if (!face_matches( family->family_name, face, face_name )) continue;
                if (!enum_face_charsets( family, face, enum_charsets, count, proc, lparam, orig_name ))
                    return FALSE;
	    }
	}
    }
    else
    {
        TRACE( "charset %d\n", charset );
2857
        WINE_RB_FOR_EACH_ENTRY( family, &family_name_tree, struct gdi_font_family, name_entry )
2858 2859 2860 2861 2862 2863 2864 2865
        {
            face = LIST_ENTRY( list_head(get_family_face_list(family)), struct gdi_font_face, entry );
            if (!enum_face_charsets( family, face, enum_charsets, count, proc, lparam, NULL ))
                return FALSE;
	}
    }
    LeaveCriticalSection( &font_cs );
    return TRUE;
2866 2867 2868
}


2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 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
static BOOL check_unicode_tategaki( WCHAR ch )
{
    extern const unsigned short vertical_orientation_table[] DECLSPEC_HIDDEN;
    unsigned short orientation = vertical_orientation_table[vertical_orientation_table[vertical_orientation_table[ch >> 8]+((ch >> 4) & 0x0f)]+ (ch & 0xf)];

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

static UINT get_glyph_index_symbol( struct gdi_font *font, UINT glyph )
{
    UINT index;

    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 */
    index = glyph;
    font_funcs->get_glyph_index( font, &index, FALSE );
    if (!index)
    {
        index = glyph - 0xf000;
        font_funcs->get_glyph_index( font, &index, FALSE );
    }
    return index;
}

static UINT get_glyph_index( struct gdi_font *font, UINT glyph )
{
    WCHAR wc = glyph;
    char ch;
    BOOL used;

    if (font_funcs->get_glyph_index( font, &glyph, TRUE )) return glyph;

    if (font->codepage == CP_SYMBOL)
    {
        glyph = get_glyph_index_symbol( font, wc );
        if (!glyph)
        {
            if (WideCharToMultiByte( CP_ACP, 0, &wc, 1, &ch, 1, NULL, NULL ))
                glyph = get_glyph_index_symbol( font, (unsigned char)ch );
        }
    }
    else if (WideCharToMultiByte( font->codepage, 0, &wc, 1, &ch, 1, NULL, &used ) && !used)
    {
        glyph = (unsigned char)ch;
        font_funcs->get_glyph_index( font, &glyph, FALSE );
    }
2918 2919
    else return 0;

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 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
    return glyph;
}

static UINT get_glyph_index_linked( struct gdi_font **font, UINT glyph )
{
    struct gdi_font *child;
    UINT res;

    if ((res = get_glyph_index( *font, glyph ))) return res;
    if (glyph < 32) return 0;  /* don't check linked fonts for control characters */

    LIST_FOR_EACH_ENTRY( child, &(*font)->child_fonts, struct gdi_font, entry )
    {
        if (!child->private && !font_funcs->load_font( child )) continue;
        if ((res = get_glyph_index( child, glyph )))
        {
            *font = child;
            return res;
        }
    }
    return 0;
}

static DWORD get_glyph_outline( struct gdi_font *font, UINT glyph, UINT format,
                                GLYPHMETRICS *gm_ret, ABC *abc_ret, DWORD buflen, void *buf,
                                const MAT2 *mat )
{
    GLYPHMETRICS gm;
    ABC abc;
    DWORD ret = 1;
    UINT index = glyph;
    BOOL tategaki = (*get_gdi_font_name( font ) == '@');

    if (format & GGO_GLYPH_INDEX)
    {
        /* Windows bitmap font, e.g. Small Fonts, uses ANSI character code
           as glyph index. "Treasure Adventure Game" depends on this. */
        font_funcs->get_glyph_index( font, &index, FALSE );
        /* 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. */
    }
    else
    {
        index = get_glyph_index_linked( &font, glyph );
        if (tategaki)
        {
            UINT orig = index;
            index = get_GSUB_vert_glyph( font, index );
            if (index == orig) tategaki = check_unicode_tategaki( glyph );
        }
    }

    format &= ~(GGO_GLYPH_INDEX | GGO_UNHINTED);

    if (mat && !memcmp( mat, &identity, sizeof(*mat) )) mat = NULL;

    if (format == GGO_METRICS && !mat && get_gdi_font_glyph_metrics( font, index, &gm, &abc ))
        goto done;

    ret = font_funcs->get_glyph_outline( font, index, format, &gm, &abc, buflen, buf, mat, tategaki );
    if (ret == GDI_ERROR) return ret;

    if ((format == GGO_METRICS || format == GGO_BITMAP || format ==  WINE_GGO_GRAY16_BITMAP) && !mat)
        set_gdi_font_glyph_metrics( font, index, &gm, &abc );

done:
    if (gm_ret) *gm_ret = gm;
    if (abc_ret) *abc_ret = abc;
    return ret;
}


2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
/*************************************************************
 * font_FontIsLinked
 */
static BOOL CDECL font_FontIsLinked( PHYSDEV dev )
{
    struct font_physdev *physdev = get_font_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pFontIsLinked );
        return dev->funcs->pFontIsLinked( dev );
    }
3005
    return !list_empty( &physdev->font->child_fonts );
3006 3007 3008 3009 3010 3011 3012 3013 3014
}


/*************************************************************
 * font_GetCharABCWidths
 */
static BOOL CDECL font_GetCharABCWidths( PHYSDEV dev, UINT first, UINT last, ABC *buffer )
{
    struct font_physdev *physdev = get_font_dev( dev );
3015
    UINT c;
3016 3017 3018 3019 3020 3021

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetCharABCWidths );
        return dev->funcs->pGetCharABCWidths( dev, first, last, buffer );
    }
3022 3023 3024

    TRACE( "%p, %u, %u, %p\n", physdev->font, first, last, buffer );

3025
    EnterCriticalSection( &font_cs );
3026
    for (c = first; c <= last; c++, buffer++)
3027
        get_glyph_outline( physdev->font, c, GGO_METRICS, NULL, buffer, 0, NULL, NULL );
3028
    LeaveCriticalSection( &font_cs );
3029
    return TRUE;
3030 3031 3032 3033 3034 3035 3036 3037 3038
}


/*************************************************************
 * font_GetCharABCWidthsI
 */
static BOOL CDECL font_GetCharABCWidthsI( PHYSDEV dev, UINT first, UINT count, WORD *gi, ABC *buffer )
{
    struct font_physdev *physdev = get_font_dev( dev );
3039
    UINT c;
3040 3041 3042 3043 3044 3045

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetCharABCWidthsI );
        return dev->funcs->pGetCharABCWidthsI( dev, first, count, gi, buffer );
    }
3046 3047 3048

    TRACE( "%p, %u, %u, %p\n", physdev->font, first, count, buffer );

3049
    EnterCriticalSection( &font_cs );
3050
    for (c = 0; c < count; c++, buffer++)
3051 3052
        get_glyph_outline( physdev->font, gi ? gi[c] : first + c, GGO_METRICS | GGO_GLYPH_INDEX,
                           NULL, buffer, 0, NULL, NULL );
3053
    LeaveCriticalSection( &font_cs );
3054
    return TRUE;
3055 3056 3057 3058 3059 3060 3061 3062 3063
}


/*************************************************************
 * font_GetCharWidth
 */
static BOOL CDECL font_GetCharWidth( PHYSDEV dev, UINT first, UINT last, INT *buffer )
{
    struct font_physdev *physdev = get_font_dev( dev );
3064 3065
    ABC abc;
    UINT c;
3066 3067 3068 3069 3070 3071

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetCharWidth );
        return dev->funcs->pGetCharWidth( dev, first, last, buffer );
    }
3072 3073 3074

    TRACE( "%p, %d, %d, %p\n", physdev->font, first, last, buffer );

3075
    EnterCriticalSection( &font_cs );
3076 3077
    for (c = first; c <= last; c++)
    {
3078
        if (get_glyph_outline( physdev->font, c, GGO_METRICS, NULL, &abc, 0, NULL, NULL ) == GDI_ERROR)
3079 3080 3081 3082
            buffer[c - first] = 0;
        else
            buffer[c - first] = abc.abcA + abc.abcB + abc.abcC;
    }
3083
    LeaveCriticalSection( &font_cs );
3084
    return TRUE;
3085 3086 3087 3088 3089 3090 3091 3092 3093
}


/*************************************************************
 * font_GetCharWidthInfo
 */
static BOOL CDECL font_GetCharWidthInfo( PHYSDEV dev, void *ptr )
{
    struct font_physdev *physdev = get_font_dev( dev );
3094
    struct char_width_info *info = ptr;
3095 3096 3097 3098 3099 3100

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetCharWidthInfo );
        return dev->funcs->pGetCharWidthInfo( dev, ptr );
    }
3101 3102 3103 3104 3105 3106

    info->unk = 0;
    if (!physdev->font->scalable || !font_funcs->get_char_width_info( physdev->font, info ))
        info->lsb = info->rsb = 0;

    return TRUE;
3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121
}


/*************************************************************
 * font_GetFontData
 */
static DWORD CDECL font_GetFontData( PHYSDEV dev, DWORD table, DWORD offset, void *buf, DWORD size )
{
    struct font_physdev *physdev = get_font_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetFontData );
        return dev->funcs->pGetFontData( dev, table, offset, buf, size );
    }
3122
    return font_funcs->get_font_data( physdev->font, table, offset, buf, size );
3123 3124 3125 3126 3127 3128 3129 3130 3131
}


/*************************************************************
 * font_GetFontRealizationInfo
 */
static BOOL CDECL font_GetFontRealizationInfo( PHYSDEV dev, void *ptr )
{
    struct font_physdev *physdev = get_font_dev( dev );
3132
    struct font_realization_info *info = ptr;
3133 3134 3135 3136 3137 3138

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetFontRealizationInfo );
        return dev->funcs->pGetFontRealizationInfo( dev, ptr );
    }
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155

    TRACE( "(%p, %p)\n", physdev->font, info);

    info->flags = 1;
    if (physdev->font->scalable) info->flags |= 2;

    info->cache_num = physdev->font->cache_num;
    info->instance_id = physdev->font->handle;
    if (info->size == sizeof(*info))
    {
        info->unk = 0;
        info->face_index = physdev->font->face_index;
        info->simulations = 0;
        if (physdev->font->fake_bold) info->simulations |= 0x1;
        if (physdev->font->fake_italic) info->simulations |= 0x2;
    }
    return TRUE;
3156 3157 3158 3159 3160 3161 3162 3163 3164
}


/*************************************************************
 * font_GetFontUnicodeRanges
 */
static DWORD CDECL font_GetFontUnicodeRanges( PHYSDEV dev, GLYPHSET *glyphset )
{
    struct font_physdev *physdev = get_font_dev( dev );
3165
    DWORD size, num_ranges;
3166 3167 3168 3169 3170 3171

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetFontUnicodeRanges );
        return dev->funcs->pGetFontUnicodeRanges( dev, glyphset );
    }
3172 3173 3174 3175 3176 3177 3178 3179 3180 3181

    num_ranges = font_funcs->get_unicode_ranges( physdev->font, glyphset );
    size = offsetof( GLYPHSET, ranges[num_ranges] );
    if (glyphset)
    {
        glyphset->cbThis = size;
        glyphset->cRanges = num_ranges;
        glyphset->flAccel = 0;
    }
    return size;
3182 3183 3184 3185 3186 3187 3188 3189 3190
}


/*************************************************************
 * font_GetGlyphIndices
 */
static DWORD CDECL font_GetGlyphIndices( PHYSDEV dev, const WCHAR *str, INT count, WORD *gi, DWORD flags )
{
    struct font_physdev *physdev = get_font_dev( dev );
3191 3192 3193 3194
    UINT default_char;
    char ch;
    BOOL used, got_default = FALSE;
    int i;
3195 3196 3197 3198 3199 3200

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetGlyphIndices );
        return dev->funcs->pGetGlyphIndices( dev, str, count, gi, flags );
    }
3201 3202 3203 3204 3205 3206 3207

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

3208
    EnterCriticalSection( &font_cs );
3209 3210 3211 3212 3213

    for (i = 0; i < count; i++)
    {
        UINT glyph = str[i];

3214
        if (!font_funcs->get_glyph_index( physdev->font, &glyph, TRUE ))
3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
        {
            glyph = 0;
            if (physdev->font->codepage == CP_SYMBOL)
            {
                if (str[i] >= 0xf020 && str[i] <= 0xf100) glyph = str[i] - 0xf000;
                else if (str[i] < 0x100) glyph = str[i];
            }
            else if (WideCharToMultiByte( physdev->font->codepage, 0, &str[i], 1,
                                          &ch, 1, NULL, &used ) && !used)
                glyph = (unsigned char)ch;
        }
        if (!glyph)
        {
            if (!got_default)
            {
                default_char = font_funcs->get_default_glyph( physdev->font );
                got_default = TRUE;
            }
3233
            gi[i] = default_char;
3234
        }
3235
        else gi[i] = get_GSUB_vert_glyph( physdev->font, glyph );
3236 3237
    }

3238
    LeaveCriticalSection( &font_cs );
3239
    return count;
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
}


/*************************************************************
 * font_GetGlyphOutline
 */
static DWORD CDECL font_GetGlyphOutline( PHYSDEV dev, UINT glyph, UINT format,
                                         GLYPHMETRICS *gm, DWORD buflen, void *buf, const MAT2 *mat )
{
    struct font_physdev *physdev = get_font_dev( dev );
3250
    DWORD ret;
3251 3252 3253 3254 3255 3256

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetGlyphOutline );
        return dev->funcs->pGetGlyphOutline( dev, glyph, format, gm, buflen, buf, mat );
    }
3257
    EnterCriticalSection( &font_cs );
3258
    ret = get_glyph_outline( physdev->font, glyph, format, gm, NULL, buflen, buf, mat );
3259 3260
    LeaveCriticalSection( &font_cs );
    return ret;
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
}


/*************************************************************
 * font_GetKerningPairs
 */
static DWORD CDECL font_GetKerningPairs( PHYSDEV dev, DWORD count, KERNINGPAIR *pairs )
{
    struct font_physdev *physdev = get_font_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetKerningPairs );
        return dev->funcs->pGetKerningPairs( dev, count, pairs );
    }
3276

3277
    EnterCriticalSection( &font_cs );
3278 3279 3280
    if (physdev->font->kern_count == -1)
        physdev->font->kern_count = font_funcs->get_kerning_pairs( physdev->font,
                                                                   &physdev->font->kern_pairs );
3281
    LeaveCriticalSection( &font_cs );
3282 3283 3284 3285 3286 3287 3288 3289 3290

    if (count && pairs)
    {
        count = min( count, physdev->font->kern_count );
        memcpy( pairs, physdev->font->kern_pairs, count * sizeof(*pairs) );
    }
    else count = physdev->font->kern_count;

    return count;
3291 3292 3293
}


3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
static void scale_outline_font_metrics( const struct gdi_font *font, OUTLINETEXTMETRICW *otm )
{
    double scale_x, scale_y;

    if (font->aveWidth)
    {
        scale_x = (double)font->aveWidth;
        scale_x /= (double)font->otm.otmTextMetrics.tmAveCharWidth;
    }
    else
        scale_x = font->scale_y;

    scale_x *= fabs(font->matrix.eM11);
    scale_y = font->scale_y * fabs(font->matrix.eM22);

/* 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))

    SCALE_Y(otm->otmTextMetrics.tmHeight);
    SCALE_Y(otm->otmTextMetrics.tmAscent);
    SCALE_Y(otm->otmTextMetrics.tmDescent);
    SCALE_Y(otm->otmTextMetrics.tmInternalLeading);
    SCALE_Y(otm->otmTextMetrics.tmExternalLeading);

    SCALE_X(otm->otmTextMetrics.tmOverhang);
    if (font->fake_bold)
    {
        if (!font->scalable) otm->otmTextMetrics.tmOverhang++;
        otm->otmTextMetrics.tmAveCharWidth++;
        otm->otmTextMetrics.tmMaxCharWidth++;
    }
    SCALE_X(otm->otmTextMetrics.tmAveCharWidth);
    SCALE_X(otm->otmTextMetrics.tmMaxCharWidth);

    SCALE_Y(otm->otmAscent);
    SCALE_Y(otm->otmDescent);
    SCALE_Y(otm->otmLineGap);
    SCALE_Y(otm->otmsCapEmHeight);
    SCALE_Y(otm->otmsXHeight);
    SCALE_Y(otm->otmrcFontBox.top);
    SCALE_Y(otm->otmrcFontBox.bottom);
    SCALE_X(otm->otmrcFontBox.left);
    SCALE_X(otm->otmrcFontBox.right);
    SCALE_Y(otm->otmMacAscent);
    SCALE_Y(otm->otmMacDescent);
    SCALE_Y(otm->otmMacLineGap);
    SCALE_X(otm->otmptSubscriptSize.x);
    SCALE_Y(otm->otmptSubscriptSize.y);
    SCALE_X(otm->otmptSubscriptOffset.x);
    SCALE_Y(otm->otmptSubscriptOffset.y);
    SCALE_X(otm->otmptSuperscriptSize.x);
    SCALE_Y(otm->otmptSuperscriptSize.y);
    SCALE_X(otm->otmptSuperscriptOffset.x);
    SCALE_Y(otm->otmptSuperscriptOffset.y);
    SCALE_Y(otm->otmsStrikeoutSize);
    SCALE_Y(otm->otmsStrikeoutPosition);
    SCALE_Y(otm->otmsUnderscoreSize);
    SCALE_Y(otm->otmsUnderscorePosition);

#undef SCALE_X
#undef SCALE_Y
}

3358 3359 3360 3361 3362 3363
/*************************************************************
 * font_GetOutlineTextMetrics
 */
static UINT CDECL font_GetOutlineTextMetrics( PHYSDEV dev, UINT size, OUTLINETEXTMETRICW *metrics )
{
    struct font_physdev *physdev = get_font_dev( dev );
3364
    UINT ret = 0;
3365 3366 3367 3368 3369 3370

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetOutlineTextMetrics );
        return dev->funcs->pGetOutlineTextMetrics( dev, size, metrics );
    }
3371 3372 3373 3374

    if (!physdev->font->scalable) return 0;

    EnterCriticalSection( &font_cs );
3375 3376 3377 3378 3379 3380 3381 3382
    if (font_funcs->set_outline_text_metrics( physdev->font ))
    {
	ret = physdev->font->otm.otmSize;
        if (metrics && size >= physdev->font->otm.otmSize)
        {
            WCHAR *ptr = (WCHAR *)(metrics + 1);
            *metrics = physdev->font->otm;
            metrics->otmpFamilyName = (char *)ptr - (ULONG_PTR)metrics;
3383 3384
            lstrcpyW( ptr, (WCHAR *)physdev->font->otm.otmpFamilyName );
            ptr += lstrlenW(ptr) + 1;
3385
            metrics->otmpStyleName = (char *)ptr - (ULONG_PTR)metrics;
3386 3387
            lstrcpyW( ptr, (WCHAR *)physdev->font->otm.otmpStyleName );
            ptr += lstrlenW(ptr) + 1;
3388
            metrics->otmpFaceName = (char *)ptr - (ULONG_PTR)metrics;
3389 3390
            lstrcpyW( ptr, (WCHAR *)physdev->font->otm.otmpFaceName );
            ptr += lstrlenW(ptr) + 1;
3391
            metrics->otmpFullName = (char *)ptr - (ULONG_PTR)metrics;
3392
            lstrcpyW( ptr, (WCHAR *)physdev->font->otm.otmpFullName );
3393 3394 3395
            scale_outline_font_metrics( physdev->font, metrics );
        }
    }
3396 3397
    LeaveCriticalSection( &font_cs );
    return ret;
3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
}


/*************************************************************
 * font_GetTextCharsetInfo
 */
static UINT CDECL font_GetTextCharsetInfo( PHYSDEV dev, FONTSIGNATURE *fs, DWORD flags )
{
    struct font_physdev *physdev = get_font_dev( dev );

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextCharsetInfo );
        return dev->funcs->pGetTextCharsetInfo( dev, fs, flags );
    }
3413 3414
    if (fs) *fs = physdev->font->fs;
    return physdev->font->charset;
3415 3416 3417 3418 3419 3420 3421 3422 3423
}


/*************************************************************
 * font_GetTextExtentExPoint
 */
static BOOL CDECL font_GetTextExtentExPoint( PHYSDEV dev, const WCHAR *str, INT count, INT *dxs )
{
    struct font_physdev *physdev = get_font_dev( dev );
3424 3425
    INT i, pos;
    ABC abc;
3426 3427 3428 3429 3430 3431

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextExtentExPoint );
        return dev->funcs->pGetTextExtentExPoint( dev, str, count, dxs );
    }
3432 3433 3434

    TRACE( "%p, %s, %d\n", physdev->font, debugstr_wn(str, count), count );

3435
    EnterCriticalSection( &font_cs );
3436 3437
    for (i = pos = 0; i < count; i++)
    {
3438
        get_glyph_outline( physdev->font, str[i], GGO_METRICS, NULL, &abc, 0, NULL, NULL );
3439 3440 3441
        pos += abc.abcA + abc.abcB + abc.abcC;
        dxs[i] = pos;
    }
3442
    LeaveCriticalSection( &font_cs );
3443
    return TRUE;
3444 3445 3446 3447 3448 3449 3450 3451 3452
}


/*************************************************************
 * font_GetTextExtentExPointI
 */
static BOOL CDECL font_GetTextExtentExPointI( PHYSDEV dev, const WORD *indices, INT count, INT *dxs )
{
    struct font_physdev *physdev = get_font_dev( dev );
3453 3454
    INT i, pos;
    ABC abc;
3455 3456 3457 3458 3459 3460

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextExtentExPointI );
        return dev->funcs->pGetTextExtentExPointI( dev, indices, count, dxs );
    }
3461 3462 3463

    TRACE( "%p, %p, %d\n", physdev->font, indices, count );

3464
    EnterCriticalSection( &font_cs );
3465 3466
    for (i = pos = 0; i < count; i++)
    {
3467 3468
        get_glyph_outline( physdev->font, indices[i], GGO_METRICS | GGO_GLYPH_INDEX,
                           NULL, &abc, 0, NULL, NULL );
3469 3470 3471
        pos += abc.abcA + abc.abcB + abc.abcC;
        dxs[i] = pos;
    }
3472
    LeaveCriticalSection( &font_cs );
3473
    return TRUE;
3474 3475 3476 3477 3478 3479 3480 3481 3482
}


/*************************************************************
 * font_GetTextFace
 */
static INT CDECL font_GetTextFace( PHYSDEV dev, INT count, WCHAR *str )
{
    struct font_physdev *physdev = get_font_dev( dev );
3483
    INT len;
3484 3485 3486 3487 3488 3489

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextFace );
        return dev->funcs->pGetTextFace( dev, count, str );
    }
3490
    len = lstrlenW( get_gdi_font_name(physdev->font) ) + 1;
3491 3492
    if (str)
    {
3493
        lstrcpynW( str, get_gdi_font_name(physdev->font), count );
3494 3495 3496
        len = min( count, len );
    }
    return len;
3497 3498 3499
}


3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 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
static void scale_font_metrics( struct gdi_font *font, TEXTMETRICW *tm )
{
    double scale_x, scale_y;

    /* Make sure that the font has sane width/height ratio */
    if (font->aveWidth && (font->aveWidth + tm->tmHeight - 1) / tm->tmHeight > 100)
    {
        WARN( "Ignoring too large font->aveWidth %d\n", font->aveWidth );
        font->aveWidth = 0;
    }

    if (font->aveWidth)
    {
        scale_x = (double)font->aveWidth;
        scale_x /= (double)font->otm.otmTextMetrics.tmAveCharWidth;
    }
    else
        scale_x = font->scale_y;

    scale_x *= fabs(font->matrix.eM11);
    scale_y = font->scale_y * fabs(font->matrix.eM22);

#define SCALE_X(x) (x) = GDI_ROUND((x) * scale_x)
#define SCALE_Y(y) (y) = GDI_ROUND((y) * scale_y)

    SCALE_Y(tm->tmHeight);
    SCALE_Y(tm->tmAscent);
    SCALE_Y(tm->tmDescent);
    SCALE_Y(tm->tmInternalLeading);
    SCALE_Y(tm->tmExternalLeading);

    SCALE_X(tm->tmOverhang);
    if (font->fake_bold)
    {
        if (!font->scalable) tm->tmOverhang++;
        tm->tmAveCharWidth++;
        tm->tmMaxCharWidth++;
    }
    SCALE_X(tm->tmAveCharWidth);
    SCALE_X(tm->tmMaxCharWidth);

#undef SCALE_X
#undef SCALE_Y
}

3545 3546 3547 3548 3549 3550
/*************************************************************
 * font_GetTextMetrics
 */
static BOOL CDECL font_GetTextMetrics( PHYSDEV dev, TEXTMETRICW *metrics )
{
    struct font_physdev *physdev = get_font_dev( dev );
3551
    BOOL ret = FALSE;
3552 3553 3554 3555 3556 3557

    if (!physdev->font)
    {
        dev = GET_NEXT_PHYSDEV( dev, pGetTextMetrics );
        return dev->funcs->pGetTextMetrics( dev, metrics );
    }
3558 3559

    EnterCriticalSection( &font_cs );
3560 3561 3562 3563 3564 3565 3566
    if (font_funcs->set_outline_text_metrics( physdev->font ) ||
        font_funcs->set_bitmap_text_metrics( physdev->font ))
    {
        *metrics = physdev->font->otm.otmTextMetrics;
        scale_font_metrics( physdev->font, metrics );
        ret = TRUE;
    }
3567 3568
    LeaveCriticalSection( &font_cs );
    return ret;
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
static void get_nearest_charset( const WCHAR *family_name, struct gdi_font_face *face, CHARSETINFO *csi )
{
  /* 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 */

    int i;

    if (TranslateCharsetInfo( (DWORD*)(INT_PTR)GetACP(), csi, TCI_SRCCODEPAGE ))
    {
        const struct gdi_font_link *font_link;

        if (csi->fs.fsCsb[0] & face->fs.fsCsb[0]) return;
        font_link = find_gdi_font_link(family_name);
        if (font_link && (csi->fs.fsCsb[0] & font_link->fs.fsCsb[0])) return;
    }
    for (i = 0; i < 32; i++)
    {
        DWORD fs0 = 1u << i;
        if (face->fs.fsCsb[0] & fs0)
        {
	    if (TranslateCharsetInfo(&fs0, csi, TCI_SRCFONTSIG)) return;
            FIXME("TCI failing on %x\n", fs0);
	}
    }

    FIXME("returning DEFAULT_CHARSET face->fs.fsCsb[0] = %08x file = %s\n",
	  face->fs.fsCsb[0], debugstr_w(face->file));
    csi->ciACP = GetACP();
    csi->ciCharset = DEFAULT_CHARSET;
}

static struct gdi_font *select_font( LOGFONTW *lf, FMAT2 dcmat, BOOL can_use_bitmap )
{
    struct gdi_font *font;
    struct gdi_font_face *face;
    INT height;
    CHARSETINFO csi;
    const WCHAR *orig_name = NULL;

    /* 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*" */
3617
    if (!facename_compare( lf->lfFaceName, L"Symbol", -1 )) lf->lfCharSet = SYMBOL_CHARSET;
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

    /* check the cache first */
    if ((font = find_cached_gdi_font( lf, &dcmat, can_use_bitmap )))
    {
        TRACE( "returning cached gdiFont(%p)\n", font );
        return font;
    }
    if (!(face = find_matching_face( lf, &csi, can_use_bitmap, &orig_name )))
    {
        FIXME( "can't find a single appropriate font - bailing\n" );
        return NULL;
    }
    height = lf->lfHeight;

    font = create_gdi_font( face, orig_name, lf );
    font->matrix = dcmat;
    font->can_use_bitmap = can_use_bitmap;
    if (!csi.fs.fsCsb[0]) get_nearest_charset( face->family->family_name, face, &csi );
    font->charset = csi.ciCharset;
    font->codepage = csi.ciACP;

    TRACE( "Chosen: %s (%s/%p:%u)\n", debugstr_w(face->full_name), debugstr_w(face->file),
           face->data_ptr, face->face_index );

    font->aveWidth = height ? lf->lfWidth : 0;
    if (!face->scalable)
    {
        /* Windows uses integer scaling factors for bitmap fonts */
        INT scale, scaled_height, diff;
        struct gdi_font *cachedfont;

        if (height > 0)
            diff = height - (signed int)face->size.height;
        else
            diff = -height - ((signed int)face->size.height - face->size.internal_leading);

        /* FIXME: rotation of bitmap fonts is ignored */
        height = abs(GDI_ROUND( (double)height * font->matrix.eM22 ));
        if (font->aveWidth)
            font->aveWidth = (double)font->aveWidth * font->matrix.eM11;
        font->matrix.eM11 = font->matrix.eM22 = 1.0;
        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_cached_gdi_font( lf, &dcmat, can_use_bitmap )))
        {
            TRACE("Found cached font after non-scalable matrix rescale!\n");
            free_gdi_font( font );
            return cachedfont;
        }

        if (height != 0) height = diff;
        height += face->size.height;

        scale = (height + face->size.height - 1) / face->size.height;
        scaled_height = scale * face->size.height;
        /* 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--;
        font->scale_y = scale;
3679
        TRACE("font scale y: %d\n", font->scale_y);
3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697
    }

    if (!font_funcs->load_font( font ))
    {
        free_gdi_font( font );
        return NULL;
    }

    if (face->flags & ADDFONT_VERTICAL_FONT) /* We need to try to load the GSUB table */
        font->vert_feature = get_GSUB_vert_feature( font );

    create_child_font_list( font );

    TRACE( "caching: gdiFont=%p\n", font );
    cache_gdi_font( font );
    return font;
}

3698 3699 3700 3701 3702 3703
/*************************************************************
 * font_SelectFont
 */
static HFONT CDECL font_SelectFont( PHYSDEV dev, HFONT hfont, UINT *aa_flags )
{
    struct font_physdev *physdev = get_font_dev( dev );
3704
    struct gdi_font *font = NULL, *prev = physdev->font;
3705 3706
    DC *dc = get_physdev_dc( dev );

3707 3708
    if (hfont)
    {
3709
        LOGFONTW lf;
3710 3711
        FMAT2 dcmat;
        BOOL can_use_bitmap = !!(GetDeviceCaps( dc->hSelf, TEXTCAPS ) & TC_RA_ABLE);
3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723

        GetObjectW( hfont, sizeof(lf), &lf );
        switch (lf.lfQuality)
        {
        case NONANTIALIASED_QUALITY:
            if (!*aa_flags) *aa_flags = GGO_BITMAP;
            break;
        case ANTIALIASED_QUALITY:
            if (!*aa_flags) *aa_flags = GGO_GRAY4_BITMAP;
            break;
        }

3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757
        lf.lfWidth = abs(lf.lfWidth);

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

        if (dc->GraphicsMode == GM_ADVANCED)
        {
            memcpy( &dcmat, &dc->xformWorld2Vport, sizeof(FMAT2) );
            /* 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);
                dcmat.eM11 = dcmat.eM22 = dcmat.eM11 < 0 ? -1 : 1;
            }
        }
        else
        {
            /* Windows 3.1 compatibility mode GM_COMPATIBLE has only limited font scaling abilities */
            dcmat.eM11 = dcmat.eM22 = 1.0;
            dcmat.eM21 = dcmat.eM12 = 0;
            lf.lfOrientation = lf.lfEscapement;
            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);
            }
        }
        TRACE( "DC transform %f %f %f %f\n", dcmat.eM11, dcmat.eM12, dcmat.eM21, dcmat.eM22 );

3758
        EnterCriticalSection( &font_cs );
3759

3760 3761
        font = select_font( &lf, dcmat, can_use_bitmap );

3762
        if (font)
3763
        {
3764
            if (!*aa_flags) *aa_flags = font->aa_flags;
3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
            if (!*aa_flags)
            {
                if (lf.lfQuality == CLEARTYPE_QUALITY || lf.lfQuality == CLEARTYPE_NATURAL_QUALITY)
                    *aa_flags = subpixel_orientation;
                else
                    *aa_flags = font_smoothing;
            }
            *aa_flags = font_funcs->get_aa_flags( font, *aa_flags, antialias_fakes );
        }
        TRACE( "%p %s %d aa %x\n", hfont, debugstr_w(lf.lfFaceName), lf.lfHeight, *aa_flags );
3775 3776
        LeaveCriticalSection( &font_cs );
    }
3777
    physdev->font = font;
3778
    if (prev) release_gdi_font( prev );
3779
    return font ? hfont : 0;
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
}


const struct gdi_dc_funcs font_driver =
{
    NULL,                           /* pAbortDoc */
    NULL,                           /* pAbortPath */
    NULL,                           /* pAlphaBlend */
    NULL,                           /* pAngleArc */
    NULL,                           /* pArc */
    NULL,                           /* pArcTo */
    NULL,                           /* pBeginPath */
    NULL,                           /* pBlendImage */
    NULL,                           /* pChord */
    NULL,                           /* pCloseFigure */
    NULL,                           /* pCreateCompatibleDC */
    font_CreateDC,                  /* pCreateDC */
    font_DeleteDC,                  /* pDeleteDC */
    NULL,                           /* pDeleteObject */
    NULL,                           /* pDeviceCapabilities */
    NULL,                           /* pEllipse */
    NULL,                           /* pEndDoc */
    NULL,                           /* pEndPage */
    NULL,                           /* pEndPath */
    font_EnumFonts,                 /* pEnumFonts */
    NULL,                           /* pEnumICMProfiles */
    NULL,                           /* pExcludeClipRect */
    NULL,                           /* pExtDeviceMode */
    NULL,                           /* pExtEscape */
    NULL,                           /* pExtFloodFill */
    NULL,                           /* pExtSelectClipRgn */
    NULL,                           /* pExtTextOut */
    NULL,                           /* pFillPath */
    NULL,                           /* pFillRgn */
    NULL,                           /* pFlattenPath */
    font_FontIsLinked,              /* pFontIsLinked */
    NULL,                           /* pFrameRgn */
    NULL,                           /* pGdiComment */
    NULL,                           /* pGetBoundsRect */
    font_GetCharABCWidths,          /* pGetCharABCWidths */
    font_GetCharABCWidthsI,         /* pGetCharABCWidthsI */
    font_GetCharWidth,              /* pGetCharWidth */
    font_GetCharWidthInfo,          /* pGetCharWidthInfo */
    NULL,                           /* pGetDeviceCaps */
    NULL,                           /* pGetDeviceGammaRamp */
    font_GetFontData,               /* pGetFontData */
    font_GetFontRealizationInfo,    /* pGetFontRealizationInfo */
    font_GetFontUnicodeRanges,      /* pGetFontUnicodeRanges */
    font_GetGlyphIndices,           /* pGetGlyphIndices */
    font_GetGlyphOutline,           /* pGetGlyphOutline */
    NULL,                           /* pGetICMProfile */
    NULL,                           /* pGetImage */
    font_GetKerningPairs,           /* pGetKerningPairs */
    NULL,                           /* pGetNearestColor */
    font_GetOutlineTextMetrics,     /* pGetOutlineTextMetrics */
    NULL,                           /* pGetPixel */
    NULL,                           /* pGetSystemPaletteEntries */
    font_GetTextCharsetInfo,        /* pGetTextCharsetInfo */
    font_GetTextExtentExPoint,      /* pGetTextExtentExPoint */
    font_GetTextExtentExPointI,     /* pGetTextExtentExPointI */
    font_GetTextFace,               /* pGetTextFace */
    font_GetTextMetrics,            /* pGetTextMetrics */
    NULL,                           /* pGradientFill */
    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 */
    font_SelectFont,                /* pSelectFont */
    NULL,                           /* pSelectPalette */
    NULL,                           /* pSelectPen */
    NULL,                           /* pSetArcDirection */
    NULL,                           /* pSetBkColor */
    NULL,                           /* pSetBkMode */
    NULL,                           /* pSetBoundsRect */
    NULL,                           /* pSetDCBrushColor */
    NULL,                           /* pSetDCPenColor */
    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 */
    NULL,                           /* pD3DKMTCheckVidPnExclusiveOwnership */
    NULL,                           /* pD3DKMTSetVidPnSourceOwner */
    NULL,                           /* wine_get_wgl_driver */
    NULL,                           /* wine_get_vulkan_driver */
    GDI_PRIORITY_FONT_DRV           /* priority */
};

3919 3920 3921 3922 3923 3924 3925 3926 3927
static DWORD get_key_value( HKEY key, const WCHAR *name, DWORD *value )
{
    WCHAR buf[12];
    DWORD count = sizeof(buf), type, err;

    err = RegQueryValueExW( key, name, NULL, &type, (BYTE *)buf, &count );
    if (!err)
    {
        if (type == REG_DWORD) memcpy( value, buf, sizeof(*value) );
3928
        else *value = wcstol( buf, NULL, 10 );
3929 3930 3931 3932 3933 3934 3935
    }
    return err;
}

static void init_font_options(void)
{
    HKEY key;
3936
    DWORD i, type, size, val, gamma = 1400;
3937 3938 3939
    WCHAR buffer[20];

    size = sizeof(buffer);
3940
    if (!RegQueryValueExW( wine_fonts_key, L"AntialiasFakeBoldOrItalic", NULL,
3941 3942
                           &type, (BYTE *)buffer, &size) && type == REG_SZ && size >= 1)
    {
3943
        antialias_fakes = (wcschr(L"yYtT1", buffer[0]) != NULL);
3944 3945
    }

3946
    if (!RegOpenKeyW( HKEY_CURRENT_USER, L"Control Panel\\Desktop", &key ))
3947 3948
    {
        /* FIXME: handle vertical orientations even though Windows doesn't */
3949
        if (!get_key_value( key, L"FontSmoothingOrientation", &val ))
3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960
        {
            switch (val)
            {
            case 0: /* FE_FONTSMOOTHINGORIENTATIONBGR */
                subpixel_orientation = WINE_GGO_HBGR_BITMAP;
                break;
            case 1: /* FE_FONTSMOOTHINGORIENTATIONRGB */
                subpixel_orientation = WINE_GGO_HRGB_BITMAP;
                break;
            }
        }
3961
        if (!get_key_value( key, L"FontSmoothing", &val ) && val /* enabled */)
3962
        {
3963
            if (!get_key_value( key, L"FontSmoothingType", &val ) && val == 2 /* FE_FONTSMOOTHINGCLEARTYPE */)
3964 3965 3966 3967
                font_smoothing = subpixel_orientation;
            else
                font_smoothing = GGO_GRAY4_BITMAP;
        }
3968 3969 3970 3971
        if (!get_key_value( key, L"FontSmoothingGamma", &val ) && val)
        {
            gamma = min( max( val, 1000 ), 2200 );
        }
3972 3973
        RegCloseKey( key );
    }
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985

    /* Calibrating the difference between the registry value and the Wine gamma value.
       This looks roughly similar to Windows Native with the same registry value.
       MS GDI seems to be rasterizing the outline at a different rate than FreeType. */
    gamma = 1000 * gamma / 1400;
    for (i = 0; i < 256; i++)
    {
        font_gamma_ramp.encode[i] = pow( i / 255., 1000. / gamma ) * 255. + .5;
        font_gamma_ramp.decode[i] = pow( i / 255., gamma / 1000. ) * 255. + .5;
    }
    font_gamma_ramp.gamma = gamma;
    TRACE("gamma %d\n", font_gamma_ramp.gamma);
3986 3987
}

3988

3989
static void FONT_LogFontAToW( const LOGFONTA *fontA, LPLOGFONTW fontW )
3990
{
3991 3992 3993
    memcpy(fontW, fontA, sizeof(LOGFONTA) - LF_FACESIZE);
    MultiByteToWideChar(CP_ACP, 0, fontA->lfFaceName, -1, fontW->lfFaceName,
			LF_FACESIZE);
3994
    fontW->lfFaceName[LF_FACESIZE-1] = 0;
3995 3996
}

3997
static void FONT_LogFontWToA( const LOGFONTW *fontW, LPLOGFONTA fontA )
3998 3999 4000 4001
{
    memcpy(fontA, fontW, sizeof(LOGFONTA) - LF_FACESIZE);
    WideCharToMultiByte(CP_ACP, 0, fontW->lfFaceName, -1, fontA->lfFaceName,
			LF_FACESIZE, NULL, NULL);
4002
    fontA->lfFaceName[LF_FACESIZE-1] = 0;
4003 4004
}

4005
static void FONT_EnumLogFontExWToA( const ENUMLOGFONTEXW *fontW, LPENUMLOGFONTEXA fontA )
4006
{
4007
    FONT_LogFontWToA( &fontW->elfLogFont, &fontA->elfLogFont );
4008 4009

    WideCharToMultiByte( CP_ACP, 0, fontW->elfFullName, -1,
4010
			 (LPSTR) fontA->elfFullName, LF_FULLFACESIZE, NULL, NULL );
4011 4012
    fontA->elfFullName[LF_FULLFACESIZE-1] = '\0';
    WideCharToMultiByte( CP_ACP, 0, fontW->elfStyle, -1,
4013
			 (LPSTR) fontA->elfStyle, LF_FACESIZE, NULL, NULL );
4014 4015
    fontA->elfStyle[LF_FACESIZE-1] = '\0';
    WideCharToMultiByte( CP_ACP, 0, fontW->elfScript, -1,
4016
			 (LPSTR) fontA->elfScript, LF_FACESIZE, NULL, NULL );
4017 4018 4019
    fontA->elfScript[LF_FACESIZE-1] = '\0';
}

4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034
static void FONT_EnumLogFontExAToW( const ENUMLOGFONTEXA *fontA, LPENUMLOGFONTEXW fontW )
{
    FONT_LogFontAToW( &fontA->elfLogFont, &fontW->elfLogFont );

    MultiByteToWideChar( CP_ACP, 0, (LPCSTR)fontA->elfFullName, -1,
			 fontW->elfFullName, LF_FULLFACESIZE );
    fontW->elfFullName[LF_FULLFACESIZE-1] = '\0';
    MultiByteToWideChar( CP_ACP, 0, (LPCSTR)fontA->elfStyle, -1,
			 fontW->elfStyle, LF_FACESIZE );
    fontW->elfStyle[LF_FACESIZE-1] = '\0';
    MultiByteToWideChar( CP_ACP, 0, (LPCSTR)fontA->elfScript, -1,
			 fontW->elfScript, LF_FACESIZE );
    fontW->elfScript[LF_FACESIZE-1] = '\0';
}

Alexandre Julliard's avatar
Alexandre Julliard committed
4035
/***********************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
4036 4037
 *              TEXTMETRIC conversion functions.
 */
4038
static void FONT_TextMetricWToA(const TEXTMETRICW *ptmW, LPTEXTMETRICA ptmA )
4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
{
    ptmA->tmHeight = ptmW->tmHeight;
    ptmA->tmAscent = ptmW->tmAscent;
    ptmA->tmDescent = ptmW->tmDescent;
    ptmA->tmInternalLeading = ptmW->tmInternalLeading;
    ptmA->tmExternalLeading = ptmW->tmExternalLeading;
    ptmA->tmAveCharWidth = ptmW->tmAveCharWidth;
    ptmA->tmMaxCharWidth = ptmW->tmMaxCharWidth;
    ptmA->tmWeight = ptmW->tmWeight;
    ptmA->tmOverhang = ptmW->tmOverhang;
    ptmA->tmDigitizedAspectX = ptmW->tmDigitizedAspectX;
    ptmA->tmDigitizedAspectY = ptmW->tmDigitizedAspectY;
4051 4052 4053
    ptmA->tmFirstChar = min(ptmW->tmFirstChar, 255);
    if (ptmW->tmCharSet == SYMBOL_CHARSET)
    {
4054 4055
        ptmA->tmFirstChar = 0x1e;
        ptmA->tmLastChar = 0xff;  /* win9x behaviour - we need the OS2 table data to calculate correctly */
4056
    }
4057
    else if (ptmW->tmPitchAndFamily & TMPF_TRUETYPE)
4058 4059 4060 4061
    {
        ptmA->tmFirstChar = ptmW->tmDefaultChar - 1;
        ptmA->tmLastChar = min(ptmW->tmLastChar, 0xff);
    }
4062 4063 4064 4065 4066
    else
    {
        ptmA->tmFirstChar = min(ptmW->tmFirstChar, 0xff);
        ptmA->tmLastChar  = min(ptmW->tmLastChar,  0xff);
    }
4067 4068
    ptmA->tmDefaultChar = ptmW->tmDefaultChar;
    ptmA->tmBreakChar = ptmW->tmBreakChar;
4069 4070 4071 4072 4073 4074 4075 4076
    ptmA->tmItalic = ptmW->tmItalic;
    ptmA->tmUnderlined = ptmW->tmUnderlined;
    ptmA->tmStruckOut = ptmW->tmStruckOut;
    ptmA->tmPitchAndFamily = ptmW->tmPitchAndFamily;
    ptmA->tmCharSet = ptmW->tmCharSet;
}


4077
static void FONT_NewTextMetricExWToA(const NEWTEXTMETRICEXW *ptmW, NEWTEXTMETRICEXA *ptmA )
4078
{
4079
    FONT_TextMetricWToA((const TEXTMETRICW *)ptmW, (LPTEXTMETRICA)ptmA);
4080 4081 4082 4083 4084
    ptmA->ntmTm.ntmFlags = ptmW->ntmTm.ntmFlags;
    ptmA->ntmTm.ntmSizeEM = ptmW->ntmTm.ntmSizeEM;
    ptmA->ntmTm.ntmCellHeight = ptmW->ntmTm.ntmCellHeight;
    ptmA->ntmTm.ntmAvgWidth = ptmW->ntmTm.ntmAvgWidth;
    memcpy(&ptmA->ntmFontSig, &ptmW->ntmFontSig, sizeof(FONTSIGNATURE));
4085 4086
}

4087 4088 4089 4090
/* compute positions for text rendering, in device coords */
static BOOL get_char_positions( DC *dc, const WCHAR *str, INT count, INT *dx, SIZE *size )
{
    TEXTMETRICW tm;
4091
    PHYSDEV dev;
4092 4093 4094 4095 4096 4097 4098

    size->cx = size->cy = 0;
    if (!count) return TRUE;

    dev = GET_DC_PHYSDEV( dc, pGetTextMetrics );
    dev->funcs->pGetTextMetrics( dev, &tm );

4099
    dev = GET_DC_PHYSDEV( dc, pGetTextExtentExPoint );
4100
    if (!dev->funcs->pGetTextExtentExPoint( dev, str, count, dx )) return FALSE;
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128

    if (dc->breakExtra || dc->breakRem)
    {
        int i, space = 0, rem = dc->breakRem;

        for (i = 0; i < count; i++)
        {
            if (str[i] == tm.tmBreakChar)
            {
                space += dc->breakExtra;
                if (rem > 0)
                {
                    space++;
                    rem--;
                }
            }
            dx[i] += space;
        }
    }
    size->cx = dx[count - 1];
    size->cy = tm.tmHeight;
    return TRUE;
}

/* compute positions for text rendering, in device coords */
static BOOL get_char_positions_indices( DC *dc, const WORD *indices, INT count, INT *dx, SIZE *size )
{
    TEXTMETRICW tm;
4129
    PHYSDEV dev;
4130 4131 4132 4133 4134 4135 4136

    size->cx = size->cy = 0;
    if (!count) return TRUE;

    dev = GET_DC_PHYSDEV( dc, pGetTextMetrics );
    dev->funcs->pGetTextMetrics( dev, &tm );

4137
    dev = GET_DC_PHYSDEV( dc, pGetTextExtentExPointI );
4138
    if (!dev->funcs->pGetTextExtentExPointI( dev, indices, count, dx )) return FALSE;
4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165

    if (dc->breakExtra || dc->breakRem)
    {
        WORD space_index;
        int i, space = 0, rem = dc->breakRem;

        dev = GET_DC_PHYSDEV( dc, pGetGlyphIndices );
        dev->funcs->pGetGlyphIndices( dev, &tm.tmBreakChar, 1, &space_index, 0 );

        for (i = 0; i < count; i++)
        {
            if (indices[i] == space_index)
            {
                space += dc->breakExtra;
                if (rem > 0)
                {
                    space++;
                    rem--;
                }
            }
            dx[i] += space;
        }
    }
    size->cx = dx[count - 1];
    size->cy = tm.tmHeight;
    return TRUE;
}
4166

4167
/***********************************************************************
4168
 *           GdiGetCodePage   (GDI32.@)
4169
 */
4170
DWORD WINAPI GdiGetCodePage( HDC hdc )
4171 4172
{
    UINT cp = CP_ACP;
4173
    DC *dc = get_dc_ptr( hdc );
4174

4175 4176 4177 4178
    if (dc)
    {
        cp = dc->font_code_page;
        release_dc_ptr( dc );
4179
    }
4180 4181 4182
    return cp;
}

4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216
/***********************************************************************
 *           get_text_charset_info
 *
 * Internal version of GetTextCharsetInfo() that takes a DC pointer.
 */
static UINT get_text_charset_info(DC *dc, FONTSIGNATURE *fs, DWORD flags)
{
    UINT ret = DEFAULT_CHARSET;
    PHYSDEV dev;

    dev = GET_DC_PHYSDEV( dc, pGetTextCharsetInfo );
    ret = dev->funcs->pGetTextCharsetInfo( dev, fs, flags );

    if (ret == DEFAULT_CHARSET && fs)
        memset(fs, 0, sizeof(FONTSIGNATURE));
    return ret;
}

/***********************************************************************
 *           GetTextCharsetInfo    (GDI32.@)
 */
UINT WINAPI GetTextCharsetInfo(HDC hdc, FONTSIGNATURE *fs, DWORD flags)
{
    UINT ret = DEFAULT_CHARSET;
    DC *dc = get_dc_ptr(hdc);

    if (dc)
    {
        ret = get_text_charset_info( dc, fs, flags );
        release_dc_ptr( dc );
    }
    return ret;
}

4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235
/***********************************************************************
 *           FONT_mbtowc
 *
 * Returns a Unicode translation of str using the charset of the
 * currently selected font in hdc.  If count is -1 then str is assumed
 * to be '\0' terminated, otherwise it contains the number of bytes to
 * convert.  If plenW is non-NULL, on return it will point to the
 * number of WCHARs that have been written.  If pCP is non-NULL, on
 * return it will point to the codepage used in the conversion.  The
 * caller should free the returned LPWSTR from the process heap
 * itself.
 */
static LPWSTR FONT_mbtowc(HDC hdc, LPCSTR str, INT count, INT *plenW, UINT *pCP)
{
    UINT cp;
    INT lenW;
    LPWSTR strW;

    cp = GdiGetCodePage( hdc );
4236 4237 4238

    if(count == -1) count = strlen(str);
    lenW = MultiByteToWideChar(cp, 0, str, count, NULL, 0);
4239
    strW = HeapAlloc(GetProcessHeap(), 0, lenW*sizeof(WCHAR));
4240 4241 4242
    MultiByteToWideChar(cp, 0, str, count, strW, lenW);
    TRACE("mapped %s -> %s\n", debugstr_an(str, count), debugstr_wn(strW, lenW));
    if(plenW) *plenW = lenW;
4243
    if(pCP) *pCP = cp;
4244 4245 4246
    return strW;
}

4247
/***********************************************************************
4248
 *           CreateFontIndirectExA   (GDI32.@)
4249
 */
4250
HFONT WINAPI CreateFontIndirectExA( const ENUMLOGFONTEXDVA *penumexA )
4251
{
4252
    ENUMLOGFONTEXDVW enumexW;
4253

4254
    if (!penumexA) return 0;
4255

4256 4257 4258
    FONT_EnumLogFontExAToW( &penumexA->elfEnumLogfontEx, &enumexW.elfEnumLogfontEx );
    enumexW.elfDesignVector = penumexA->elfDesignVector;
    return CreateFontIndirectExW( &enumexW );
4259 4260 4261
}

/***********************************************************************
4262
 *           CreateFontIndirectExW   (GDI32.@)
4263
 */
4264
HFONT WINAPI CreateFontIndirectExW( const ENUMLOGFONTEXDVW *penumex )
Alexandre Julliard's avatar
Alexandre Julliard committed
4265
{
4266 4267
    HFONT hFont;
    FONTOBJ *fontPtr;
4268
    const LOGFONTW *plf;
4269

4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280
    if (!penumex) return 0;

    if (penumex->elfEnumLogfontEx.elfFullName[0] ||
        penumex->elfEnumLogfontEx.elfStyle[0] ||
        penumex->elfEnumLogfontEx.elfScript[0])
    {
        FIXME("some fields ignored. fullname=%s, style=%s, script=%s\n",
            debugstr_w(penumex->elfEnumLogfontEx.elfFullName),
            debugstr_w(penumex->elfEnumLogfontEx.elfStyle),
            debugstr_w(penumex->elfEnumLogfontEx.elfScript));
    }
4281

4282
    plf = &penumex->elfEnumLogfontEx.elfLogFont;
4283
    if (!(fontPtr = HeapAlloc( GetProcessHeap(), 0, sizeof(*fontPtr) ))) return 0;
4284

4285
    fontPtr->logfont = *plf;
4286

4287
    if (!(hFont = alloc_gdi_handle( fontPtr, OBJ_FONT, &fontobj_funcs )))
4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303
    {
        HeapFree( GetProcessHeap(), 0, fontPtr );
        return 0;
    }

    TRACE("(%d %d %d %d %x %d %x %d %d) %s %s %s %s => %p\n",
          plf->lfHeight, plf->lfWidth,
          plf->lfEscapement, plf->lfOrientation,
          plf->lfPitchAndFamily,
          plf->lfOutPrecision, plf->lfClipPrecision,
          plf->lfQuality, plf->lfCharSet,
          debugstr_w(plf->lfFaceName),
          plf->lfWeight > 400 ? "Bold" : "",
          plf->lfItalic ? "Italic" : "",
          plf->lfUnderline ? "Underline" : "", hFont);

Alexandre Julliard's avatar
Alexandre Julliard committed
4304 4305
    return hFont;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
4306

4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335
/***********************************************************************
 *           CreateFontIndirectA   (GDI32.@)
 */
HFONT WINAPI CreateFontIndirectA( const LOGFONTA *plfA )
{
    LOGFONTW lfW;

    if (!plfA) return 0;

    FONT_LogFontAToW( plfA, &lfW );
    return CreateFontIndirectW( &lfW );
}

/***********************************************************************
 *           CreateFontIndirectW   (GDI32.@)
 */
HFONT WINAPI CreateFontIndirectW( const LOGFONTW *plf )
{
    ENUMLOGFONTEXDVW exdv;

    if (!plf) return 0;

    exdv.elfEnumLogfontEx.elfLogFont = *plf;
    exdv.elfEnumLogfontEx.elfFullName[0] = 0;
    exdv.elfEnumLogfontEx.elfStyle[0] = 0;
    exdv.elfEnumLogfontEx.elfScript[0] = 0;
    return CreateFontIndirectExW( &exdv );
}

Alexandre Julliard's avatar
Alexandre Julliard committed
4336
/*************************************************************************
4337
 *           CreateFontA    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4338
 */
4339 4340
HFONT WINAPI CreateFontA( INT height, INT width, INT esc,
                              INT orient, INT weight, DWORD italic,
Alexandre Julliard's avatar
Alexandre Julliard committed
4341 4342 4343
                              DWORD underline, DWORD strikeout, DWORD charset,
                              DWORD outpres, DWORD clippres, DWORD quality,
                              DWORD pitch, LPCSTR name )
Alexandre Julliard's avatar
Alexandre Julliard committed
4344
{
4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359
    LOGFONTA logfont;

    logfont.lfHeight = height;
    logfont.lfWidth = width;
    logfont.lfEscapement = esc;
    logfont.lfOrientation = orient;
    logfont.lfWeight = weight;
    logfont.lfItalic = italic;
    logfont.lfUnderline = underline;
    logfont.lfStrikeOut = strikeout;
    logfont.lfCharSet = charset;
    logfont.lfOutPrecision = outpres;
    logfont.lfClipPrecision = clippres;
    logfont.lfQuality = quality;
    logfont.lfPitchAndFamily = pitch;
4360 4361

    if (name)
4362
	lstrcpynA(logfont.lfFaceName,name,sizeof(logfont.lfFaceName));
4363
    else
4364 4365 4366
	logfont.lfFaceName[0] = '\0';

    return CreateFontIndirectA( &logfont );
Alexandre Julliard's avatar
Alexandre Julliard committed
4367 4368 4369
}

/*************************************************************************
4370
 *           CreateFontW    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4371
 */
4372 4373
HFONT WINAPI CreateFontW( INT height, INT width, INT esc,
                              INT orient, INT weight, DWORD italic,
Alexandre Julliard's avatar
Alexandre Julliard committed
4374 4375 4376
                              DWORD underline, DWORD strikeout, DWORD charset,
                              DWORD outpres, DWORD clippres, DWORD quality,
                              DWORD pitch, LPCWSTR name )
Alexandre Julliard's avatar
Alexandre Julliard committed
4377
{
4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
    LOGFONTW logfont;

    logfont.lfHeight = height;
    logfont.lfWidth = width;
    logfont.lfEscapement = esc;
    logfont.lfOrientation = orient;
    logfont.lfWeight = weight;
    logfont.lfItalic = italic;
    logfont.lfUnderline = underline;
    logfont.lfStrikeOut = strikeout;
    logfont.lfCharSet = charset;
    logfont.lfOutPrecision = outpres;
    logfont.lfClipPrecision = clippres;
    logfont.lfQuality = quality;
    logfont.lfPitchAndFamily = pitch;
4393 4394

    if (name)
4395
        lstrcpynW(logfont.lfFaceName, name, ARRAY_SIZE(logfont.lfFaceName));
4396
    else
4397 4398 4399
	logfont.lfFaceName[0] = '\0';

    return CreateFontIndirectW( &logfont );
Alexandre Julliard's avatar
Alexandre Julliard committed
4400 4401
}

4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418
#define ASSOC_CHARSET_OEM    1
#define ASSOC_CHARSET_ANSI   2
#define ASSOC_CHARSET_SYMBOL 4

static DWORD get_associated_charset_info(void)
{
    static DWORD associated_charset = -1;

    if (associated_charset == -1)
    {
        HKEY hkey;
        WCHAR dataW[32];
        DWORD type, data_len;

        associated_charset = 0;

        if (RegOpenKeyW(HKEY_LOCAL_MACHINE,
4419
                        L"System\\CurrentControlSet\\Control\\FontAssoc\\Associated Charset", &hkey))
4420 4421 4422
            return 0;

        data_len = sizeof(dataW);
4423 4424
        if (!RegQueryValueExW(hkey, L"ANSI(00)", NULL, &type, (LPBYTE)dataW, &data_len) &&
            type == REG_SZ && !wcsicmp(dataW, L"yes"))
4425 4426 4427
            associated_charset |= ASSOC_CHARSET_ANSI;

        data_len = sizeof(dataW);
4428 4429
        if (!RegQueryValueExW(hkey, L"OEM(FF)", NULL, &type, (LPBYTE)dataW, &data_len) &&
            type == REG_SZ && !wcsicmp(dataW, L"yes"))
4430 4431 4432
            associated_charset |= ASSOC_CHARSET_OEM;

        data_len = sizeof(dataW);
4433 4434
        if (!RegQueryValueExW(hkey, L"SYMBOL(02)", NULL, &type, (LPBYTE)dataW, &data_len) &&
            type == REG_SZ && !wcsicmp(dataW, L"yes"))
4435 4436 4437 4438 4439 4440 4441 4442 4443 4444
            associated_charset |= ASSOC_CHARSET_SYMBOL;

        RegCloseKey(hkey);

        TRACE("associated_charset = %d\n", associated_charset);
    }

    return associated_charset;
}

4445
static void update_font_code_page( DC *dc, HANDLE font )
4446 4447
{
    CHARSETINFO csi;
4448
    int charset = get_text_charset_info( dc, NULL, 0 );
4449

4450 4451 4452
    if (charset == ANSI_CHARSET && get_associated_charset_info() & ASSOC_CHARSET_ANSI)
    {
        LOGFONTW lf;
4453

4454 4455 4456 4457
        GetObjectW( font, sizeof(lf), &lf );
        if (!(lf.lfClipPrecision & CLIP_DFA_DISABLE))
            charset = DEFAULT_CHARSET;
    }
4458

4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496
    /* Hmm, nicely designed api this one! */
    if (TranslateCharsetInfo( ULongToPtr(charset), &csi, TCI_SRCCHARSET) )
        dc->font_code_page = csi.ciACP;
    else {
        switch(charset) {
        case OEM_CHARSET:
            dc->font_code_page = GetOEMCP();
            break;
        case DEFAULT_CHARSET:
            dc->font_code_page = GetACP();
            break;

        case VISCII_CHARSET:
        case TCVN_CHARSET:
        case KOI8_CHARSET:
        case ISO3_CHARSET:
        case ISO4_CHARSET:
        case ISO10_CHARSET:
        case CELTIC_CHARSET:
            /* FIXME: These have no place here, but because x11drv
               enumerates fonts with these (made up) charsets some apps
               might use them and then the FIXME below would become
               annoying.  Now we could pick the intended codepage for
               each of these, but since it's broken anyway we'll just
               use CP_ACP and hope it'll go away...
            */
            dc->font_code_page = CP_ACP;
            break;

        default:
            FIXME("Can't find codepage for charset %d\n", charset);
            dc->font_code_page = CP_ACP;
            break;
        }
    }

    TRACE("charset %d => cp %d\n", charset, dc->font_code_page);
}
Alexandre Julliard's avatar
Alexandre Julliard committed
4497

4498 4499 4500
/***********************************************************************
 *           FONT_SelectObject
 */
4501
static HGDIOBJ FONT_SelectObject( HGDIOBJ handle, HDC hdc )
4502 4503
{
    HGDIOBJ ret = 0;
4504
    DC *dc = get_dc_ptr( hdc );
4505
    PHYSDEV physdev;
4506
    UINT aa_flags = 0;
4507 4508 4509

    if (!dc) return 0;

4510 4511 4512 4513 4514 4515
    if (!GDI_inc_ref_count( handle ))
    {
        release_dc_ptr( dc );
        return 0;
    }

4516
    physdev = GET_DC_PHYSDEV( dc, pSelectFont );
4517
    if (physdev->funcs->pSelectFont( physdev, handle, &aa_flags ))
4518 4519 4520
    {
        ret = dc->hFont;
        dc->hFont = handle;
4521
        dc->aa_flags = aa_flags ? aa_flags : GGO_BITMAP;
4522
        update_font_code_page( dc, handle );
4523
        if (dc->font_gamma_ramp == NULL)
4524
            dc->font_gamma_ramp = &font_gamma_ramp;
4525
        GDI_dec_ref_count( ret );
4526
    }
4527 4528
    else GDI_dec_ref_count( handle );

4529
    release_dc_ptr( dc );
4530 4531 4532 4533
    return ret;
}


Alexandre Julliard's avatar
Alexandre Julliard committed
4534
/***********************************************************************
4535
 *           FONT_GetObjectA
Alexandre Julliard's avatar
Alexandre Julliard committed
4536
 */
4537
static INT FONT_GetObjectA( HGDIOBJ handle, INT count, LPVOID buffer )
Alexandre Julliard's avatar
Alexandre Julliard committed
4538
{
4539
    FONTOBJ *font = GDI_GetObjPtr( handle, OBJ_FONT );
4540
    LOGFONTA lfA;
Alexandre Julliard's avatar
Alexandre Julliard committed
4541

4542 4543 4544 4545 4546 4547 4548 4549 4550
    if (!font) return 0;
    if (buffer)
    {
        FONT_LogFontWToA( &font->logfont, &lfA );
        if (count > sizeof(lfA)) count = sizeof(lfA);
        memcpy( buffer, &lfA, count );
    }
    else count = sizeof(lfA);
    GDI_ReleaseObj( handle );
Alexandre Julliard's avatar
Alexandre Julliard committed
4551 4552
    return count;
}
4553

4554
/***********************************************************************
4555
 *           FONT_GetObjectW
4556
 */
4557
static INT FONT_GetObjectW( HGDIOBJ handle, INT count, LPVOID buffer )
4558
{
4559
    FONTOBJ *font = GDI_GetObjPtr( handle, OBJ_FONT );
4560 4561 4562 4563 4564 4565 4566 4567 4568

    if (!font) return 0;
    if (buffer)
    {
        if (count > sizeof(LOGFONTW)) count = sizeof(LOGFONTW);
        memcpy( buffer, &font->logfont, count );
    }
    else count = sizeof(LOGFONTW);
    GDI_ReleaseObj( handle );
4569 4570
    return count;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
4571 4572


4573 4574 4575
/***********************************************************************
 *           FONT_DeleteObject
 */
4576
static BOOL FONT_DeleteObject( HGDIOBJ handle )
4577
{
4578 4579 4580
    FONTOBJ *obj;

    if (!(obj = free_gdi_handle( handle ))) return FALSE;
4581 4582
    HeapFree( GetProcessHeap(), 0, obj );
    return TRUE;
4583 4584 4585
}


Alexandre Julliard's avatar
Alexandre Julliard committed
4586
/***********************************************************************
4587
 *              FONT_EnumInstance
4588 4589 4590
 *
 * Note: plf is really an ENUMLOGFONTEXW, and ptm is a NEWTEXTMETRICEXW.
 *       We have to use other types because of the FONTENUMPROCW definition.
Alexandre Julliard's avatar
Alexandre Julliard committed
4591
 */
4592 4593
static INT CALLBACK FONT_EnumInstance( const LOGFONTW *plf, const TEXTMETRICW *ptm,
                                       DWORD fType, LPARAM lp )
Alexandre Julliard's avatar
Alexandre Julliard committed
4594
{
4595
    struct font_enum *pfe = (struct font_enum *)lp;
4596
    INT ret = 1;
Alexandre Julliard's avatar
Alexandre Julliard committed
4597

4598
    /* lfCharSet is at the same offset in both LOGFONTA and LOGFONTW */
4599 4600
    if ((!pfe->lpLogFontParam ||
        pfe->lpLogFontParam->lfCharSet == DEFAULT_CHARSET ||
4601 4602
        pfe->lpLogFontParam->lfCharSet == plf->lfCharSet) &&
       (!(fType & RASTER_FONTTYPE) || GetDeviceCaps(pfe->hdc, TEXTCAPS) & TC_RA_ABLE) )
Alexandre Julliard's avatar
Alexandre Julliard committed
4603 4604
    {
	/* convert font metrics */
4605 4606
        ENUMLOGFONTEXA logfont;
        NEWTEXTMETRICEXA tmA;
Alexandre Julliard's avatar
Alexandre Julliard committed
4607

4608
        if (!pfe->unicode)
4609
        {
4610 4611 4612 4613
            FONT_EnumLogFontExWToA( (const ENUMLOGFONTEXW *)plf, &logfont);
            FONT_NewTextMetricExWToA( (const NEWTEXTMETRICEXW *)ptm, &tmA );
            plf = (LOGFONTW *)&logfont.elfLogFont;
            ptm = (TEXTMETRICW *)&tmA;
4614
        }
4615
        ret = pfe->lpEnumFunc( plf, ptm, fType, pfe->lpData );
4616
        pfe->retval = ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
4617
    }
4618
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
4619 4620 4621
}

/***********************************************************************
4622
 *		FONT_EnumFontFamiliesEx
Alexandre Julliard's avatar
Alexandre Julliard committed
4623
 */
4624 4625
static INT FONT_EnumFontFamiliesEx( HDC hDC, LPLOGFONTW plf, FONTENUMPROCW efproc,
                                    LPARAM lParam, BOOL unicode )
Alexandre Julliard's avatar
Alexandre Julliard committed
4626
{
4627
    INT ret = 0;
4628
    DC *dc = get_dc_ptr( hDC );
4629
    struct font_enum fe;
4630

4631
    if (dc)
4632
    {
4633
        PHYSDEV physdev = GET_DC_PHYSDEV( dc, pEnumFonts );
4634 4635 4636 4637 4638 4639 4640

        if (plf) TRACE("lfFaceName = %s lfCharset = %d\n", debugstr_w(plf->lfFaceName), plf->lfCharSet);
        fe.lpLogFontParam = plf;
        fe.lpEnumFunc = efproc;
        fe.lpData = lParam;
        fe.unicode = unicode;
        fe.hdc = hDC;
4641 4642
        fe.retval = 1;
        ret = physdev->funcs->pEnumFonts( physdev, plf, FONT_EnumInstance, (LPARAM)&fe );
4643
        release_dc_ptr( dc );
Huw D M Davies's avatar
Huw D M Davies committed
4644
    }
4645
    return ret ? fe.retval : 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
4646 4647 4648
}

/***********************************************************************
4649
 *              EnumFontFamiliesExW	(GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4650
 */
4651
INT WINAPI EnumFontFamiliesExW( HDC hDC, LPLOGFONTW plf,
4652
                                    FONTENUMPROCW efproc,
Alexandre Julliard's avatar
Alexandre Julliard committed
4653
                                    LPARAM lParam, DWORD dwFlags )
Alexandre Julliard's avatar
Alexandre Julliard committed
4654
{
4655
    return FONT_EnumFontFamiliesEx( hDC, plf, efproc, lParam, TRUE );
Alexandre Julliard's avatar
Alexandre Julliard committed
4656 4657 4658
}

/***********************************************************************
4659
 *              EnumFontFamiliesExA	(GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4660
 */
4661
INT WINAPI EnumFontFamiliesExA( HDC hDC, LPLOGFONTA plf,
4662
                                    FONTENUMPROCA efproc,
Alexandre Julliard's avatar
Alexandre Julliard committed
4663
                                    LPARAM lParam, DWORD dwFlags)
Alexandre Julliard's avatar
Alexandre Julliard committed
4664
{
4665 4666 4667 4668 4669 4670 4671 4672
    LOGFONTW lfW, *plfW;

    if (plf)
    {
        FONT_LogFontAToW( plf, &lfW );
        plfW = &lfW;
    }
    else plfW = NULL;
4673

4674
    return FONT_EnumFontFamiliesEx( hDC, plfW, (FONTENUMPROCW)efproc, lParam, FALSE );
Alexandre Julliard's avatar
Alexandre Julliard committed
4675 4676 4677
}

/***********************************************************************
4678
 *              EnumFontFamiliesA	(GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4679
 */
4680 4681
INT WINAPI EnumFontFamiliesA( HDC hDC, LPCSTR lpFamily,
                                  FONTENUMPROCA efproc, LPARAM lpData )
Alexandre Julliard's avatar
Alexandre Julliard committed
4682
{
4683
    LOGFONTA lf, *plf;
Alexandre Julliard's avatar
Alexandre Julliard committed
4684

4685 4686 4687 4688
    if (lpFamily)
    {
        if (!*lpFamily) return 1;
        lstrcpynA( lf.lfFaceName, lpFamily, LF_FACESIZE );
4689 4690 4691
        lf.lfCharSet = DEFAULT_CHARSET;
        lf.lfPitchAndFamily = 0;
        plf = &lf;
4692
    }
4693
    else plf = NULL;
Alexandre Julliard's avatar
Alexandre Julliard committed
4694

4695
    return EnumFontFamiliesExA( hDC, plf, efproc, lpData, 0 );
Alexandre Julliard's avatar
Alexandre Julliard committed
4696 4697 4698
}

/***********************************************************************
4699
 *              EnumFontFamiliesW	(GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4700
 */
4701 4702
INT WINAPI EnumFontFamiliesW( HDC hDC, LPCWSTR lpFamily,
                                  FONTENUMPROCW efproc, LPARAM lpData )
Alexandre Julliard's avatar
Alexandre Julliard committed
4703
{
4704
    LOGFONTW lf, *plf;
Alexandre Julliard's avatar
Alexandre Julliard committed
4705

4706 4707 4708 4709
    if (lpFamily)
    {
        if (!*lpFamily) return 1;
        lstrcpynW( lf.lfFaceName, lpFamily, LF_FACESIZE );
4710 4711 4712
        lf.lfCharSet = DEFAULT_CHARSET;
        lf.lfPitchAndFamily = 0;
        plf = &lf;
4713
    }
4714
    else plf = NULL;
Alexandre Julliard's avatar
Alexandre Julliard committed
4715

4716
    return EnumFontFamiliesExW( hDC, plf, efproc, lpData, 0 );
Alexandre Julliard's avatar
Alexandre Julliard committed
4717 4718 4719
}

/***********************************************************************
4720
 *              EnumFontsA		(GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4721
 */
4722
INT WINAPI EnumFontsA( HDC hDC, LPCSTR lpName, FONTENUMPROCA efproc,
Alexandre Julliard's avatar
Alexandre Julliard committed
4723
                           LPARAM lpData )
Alexandre Julliard's avatar
Alexandre Julliard committed
4724
{
4725
    return EnumFontFamiliesA( hDC, lpName, efproc, lpData );
Alexandre Julliard's avatar
Alexandre Julliard committed
4726 4727 4728
}

/***********************************************************************
4729
 *              EnumFontsW		(GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4730
 */
4731
INT WINAPI EnumFontsW( HDC hDC, LPCWSTR lpName, FONTENUMPROCW efproc,
Alexandre Julliard's avatar
Alexandre Julliard committed
4732
                           LPARAM lpData )
Alexandre Julliard's avatar
Alexandre Julliard committed
4733
{
4734
    return EnumFontFamiliesW( hDC, lpName, efproc, lpData );
Alexandre Julliard's avatar
Alexandre Julliard committed
4735
}
Alexandre Julliard's avatar
Alexandre Julliard committed
4736 4737 4738


/***********************************************************************
4739
 *           GetTextCharacterExtra    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4740
 */
4741
INT WINAPI GetTextCharacterExtra( HDC hdc )
Alexandre Julliard's avatar
Alexandre Julliard committed
4742
{
4743
    INT ret;
4744
    DC *dc = get_dc_ptr( hdc );
4745 4746
    if (!dc) return 0x80000000;
    ret = dc->charExtra;
4747
    release_dc_ptr( dc );
4748
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
4749 4750 4751 4752
}


/***********************************************************************
4753
 *           SetTextCharacterExtra    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4754
 */
4755
INT WINAPI SetTextCharacterExtra( HDC hdc, INT extra )
Alexandre Julliard's avatar
Alexandre Julliard committed
4756
{
4757
    INT ret = 0x80000000;
4758
    DC * dc = get_dc_ptr( hdc );
4759 4760

    if (dc)
4761
    {
4762 4763 4764 4765 4766 4767 4768 4769
        PHYSDEV physdev = GET_DC_PHYSDEV( dc, pSetTextCharacterExtra );
        extra = physdev->funcs->pSetTextCharacterExtra( physdev, extra );
        if (extra != 0x80000000)
        {
            ret = dc->charExtra;
            dc->charExtra = extra;
        }
        release_dc_ptr( dc );
4770
    }
4771
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
4772 4773 4774
}


Alexandre Julliard's avatar
Alexandre Julliard committed
4775
/***********************************************************************
4776
 *           SetTextJustification    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4777
 */
4778
BOOL WINAPI SetTextJustification( HDC hdc, INT extra, INT breaks )
Alexandre Julliard's avatar
Alexandre Julliard committed
4779
{
4780 4781
    BOOL ret;
    PHYSDEV physdev;
4782
    DC * dc = get_dc_ptr( hdc );
4783

4784
    if (!dc) return FALSE;
4785 4786 4787 4788

    physdev = GET_DC_PHYSDEV( dc, pSetTextJustification );
    ret = physdev->funcs->pSetTextJustification( physdev, extra, breaks );
    if (ret)
Alexandre Julliard's avatar
Alexandre Julliard committed
4789
    {
4790
        extra = abs((extra * dc->vport_ext.cx + dc->wnd_ext.cx / 2) / dc->wnd_ext.cx);
4791 4792 4793
        if (!extra) breaks = 0;
        if (breaks)
        {
4794
            dc->breakExtra = extra / breaks;
4795
            dc->breakRem   = extra - (breaks * dc->breakExtra);
4796 4797 4798
        }
        else
        {
4799 4800
            dc->breakExtra = 0;
            dc->breakRem   = 0;
4801
        }
Alexandre Julliard's avatar
Alexandre Julliard committed
4802
    }
4803
    release_dc_ptr( dc );
4804
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
4805 4806
}

Alexandre Julliard's avatar
Alexandre Julliard committed
4807

Alexandre Julliard's avatar
Alexandre Julliard committed
4808
/***********************************************************************
4809
 *           GetTextFaceA    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4810
 */
4811
INT WINAPI GetTextFaceA( HDC hdc, INT count, LPSTR name )
4812 4813 4814 4815
{
    INT res = GetTextFaceW(hdc, 0, NULL);
    LPWSTR nameW = HeapAlloc( GetProcessHeap(), 0, res * 2 );
    GetTextFaceW( hdc, res, nameW );
4816

4817
    if (name)
4818
    {
4819 4820 4821 4822 4823
        if (count)
        {
            res = WideCharToMultiByte(CP_ACP, 0, nameW, -1, name, count, NULL, NULL);
            if (res == 0)
                res = count;
4824
            name[count-1] = 0;
4825 4826 4827 4828 4829
            /* GetTextFaceA does NOT include the nul byte in the return count.  */
            res--;
        }
        else
            res = 0;
4830
    }
4831 4832 4833 4834 4835 4836 4837 4838 4839 4840
    else
        res = WideCharToMultiByte( CP_ACP, 0, nameW, -1, NULL, 0, NULL, NULL);
    HeapFree( GetProcessHeap(), 0, nameW );
    return res;
}

/***********************************************************************
 *           GetTextFaceW    (GDI32.@)
 */
INT WINAPI GetTextFaceW( HDC hdc, INT count, LPWSTR name )
Alexandre Julliard's avatar
Alexandre Julliard committed
4841
{
4842 4843
    PHYSDEV dev;
    INT ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
4844

4845
    DC * dc = get_dc_ptr( hdc );
Alexandre Julliard's avatar
Alexandre Julliard committed
4846
    if (!dc) return 0;
4847

4848 4849
    dev = GET_DC_PHYSDEV( dc, pGetTextFace );
    ret = dev->funcs->pGetTextFace( dev, count, name );
4850
    release_dc_ptr( dc );
4851
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
4852 4853 4854
}


Alexandre Julliard's avatar
Alexandre Julliard committed
4855
/***********************************************************************
4856
 *           GetTextExtentPoint32A    (GDI32.@)
4857 4858
 *
 * See GetTextExtentPoint32W.
Alexandre Julliard's avatar
Alexandre Julliard committed
4859
 */
4860 4861
BOOL WINAPI GetTextExtentPoint32A( HDC hdc, LPCSTR str, INT count,
                                     LPSIZE size )
Alexandre Julliard's avatar
Alexandre Julliard committed
4862
{
4863
    BOOL ret = FALSE;
4864
    INT wlen;
4865
    LPWSTR p;
Hidenori Takeshima's avatar
Hidenori Takeshima committed
4866

4867 4868 4869 4870 4871 4872
    if (count < 0) return FALSE;

    p = FONT_mbtowc(hdc, str, count, &wlen, NULL);

    if (p)
    {
4873 4874
	ret = GetTextExtentPoint32W( hdc, p, wlen, size );
	HeapFree( GetProcessHeap(), 0, p );
4875
    }
4876

4877
    TRACE("(%p %s %d %p): returning %d x %d\n",
4878
          hdc, debugstr_an (str, count), count, size, size->cx, size->cy );
4879
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
4880 4881 4882
}


Alexandre Julliard's avatar
Alexandre Julliard committed
4883
/***********************************************************************
Jon Griffiths's avatar
Jon Griffiths committed
4884 4885 4886
 * GetTextExtentPoint32W [GDI32.@]
 *
 * Computes width/height for a string.
Alexandre Julliard's avatar
Alexandre Julliard committed
4887 4888 4889 4890 4891 4892
 *
 * Computes width and height of the specified string.
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
Alexandre Julliard's avatar
Alexandre Julliard committed
4893
 */
4894 4895
BOOL WINAPI GetTextExtentPoint32W(
    HDC hdc,     /* [in]  Handle of device context */
Alexandre Julliard's avatar
Alexandre Julliard committed
4896
    LPCWSTR str,   /* [in]  Address of text string */
4897 4898
    INT count,   /* [in]  Number of characters in string */
    LPSIZE size) /* [out] Address of structure for string size */
Alexandre Julliard's avatar
Alexandre Julliard committed
4899
{
4900
    return GetTextExtentExPointW(hdc, str, count, 0, NULL, NULL, size);
Alexandre Julliard's avatar
Alexandre Julliard committed
4901 4902
}

4903
/***********************************************************************
4904
 * GetTextExtentExPointI [GDI32.@]
4905 4906 4907
 *
 * Computes width and height of the array of glyph indices.
 *
4908 4909 4910 4911 4912 4913 4914 4915 4916
 * PARAMS
 *    hdc     [I] Handle of device context.
 *    indices [I] Glyph index array.
 *    count   [I] Number of glyphs in array.
 *    max_ext [I] Maximum width in glyphs.
 *    nfit    [O] Maximum number of characters.
 *    dxs     [O] Partial string widths.
 *    size    [O] Returned string size.
 *
4917 4918 4919 4920
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
 */
4921 4922
BOOL WINAPI GetTextExtentExPointI( HDC hdc, const WORD *indices, INT count, INT max_ext,
                                   LPINT nfit, LPINT dxs, LPSIZE size )
4923
{
4924
    DC *dc;
4925 4926 4927
    int i;
    BOOL ret;
    INT buffer[256], *pos = dxs;
4928 4929 4930 4931

    if (count < 0) return FALSE;

    dc = get_dc_ptr( hdc );
4932 4933
    if (!dc) return FALSE;

4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951
    if (!dxs)
    {
        pos = buffer;
        if (count > 256 && !(pos = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*pos) )))
        {
            release_dc_ptr( dc );
            return FALSE;
        }
    }

    ret = get_char_positions_indices( dc, indices, count, pos, size );
    if (ret)
    {
        if (dxs || nfit)
        {
            for (i = 0; i < count; i++)
            {
                unsigned int dx = abs( INTERNAL_XDSTOWS( dc, pos[i] )) + (i + 1) * dc->charExtra;
4952
                if (nfit && dx > (unsigned int)max_ext) break;
4953 4954 4955 4956 4957 4958 4959 4960 4961 4962
                if (dxs) dxs[i] = dx;
            }
            if (nfit) *nfit = i;
        }

        size->cx = abs( INTERNAL_XDSTOWS( dc, size->cx )) + count * dc->charExtra;
        size->cy = abs( INTERNAL_YDSTOWS( dc, size->cy ));
    }

    if (pos != buffer && pos != dxs) HeapFree( GetProcessHeap(), 0, pos );
4963
    release_dc_ptr( dc );
4964

4965
    TRACE("(%p %p %d %p): returning %d x %d\n",
4966 4967 4968 4969
          hdc, indices, count, size, size->cx, size->cy );
    return ret;
}

4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989
/***********************************************************************
 * GetTextExtentPointI [GDI32.@]
 *
 * Computes width and height of the array of glyph indices.
 *
 * PARAMS
 *    hdc     [I] Handle of device context.
 *    indices [I] Glyph index array.
 *    count   [I] Number of glyphs in array.
 *    size    [O] Returned string size.
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
 */
BOOL WINAPI GetTextExtentPointI( HDC hdc, const WORD *indices, INT count, LPSIZE size )
{
    return GetTextExtentExPointI( hdc, indices, count, 0, NULL, NULL, size );
}

Alexandre Julliard's avatar
Alexandre Julliard committed
4990

Alexandre Julliard's avatar
Alexandre Julliard committed
4991
/***********************************************************************
4992
 *           GetTextExtentPointA    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
4993
 */
4994 4995
BOOL WINAPI GetTextExtentPointA( HDC hdc, LPCSTR str, INT count,
                                          LPSIZE size )
Alexandre Julliard's avatar
Alexandre Julliard committed
4996
{
4997
    TRACE("not bug compatible.\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
4998 4999 5000 5001
    return GetTextExtentPoint32A( hdc, str, count, size );
}

/***********************************************************************
5002
 *           GetTextExtentPointW   (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
5003
 */
5004 5005
BOOL WINAPI GetTextExtentPointW( HDC hdc, LPCWSTR str, INT count,
                                          LPSIZE size )
Alexandre Julliard's avatar
Alexandre Julliard committed
5006
{
5007
    TRACE("not bug compatible.\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
5008 5009 5010
    return GetTextExtentPoint32W( hdc, str, count, size );
}

Alexandre Julliard's avatar
Alexandre Julliard committed
5011

Alexandre Julliard's avatar
Alexandre Julliard committed
5012
/***********************************************************************
5013
 *           GetTextExtentExPointA    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
5014
 */
5015
BOOL WINAPI GetTextExtentExPointA( HDC hdc, LPCSTR str, INT count,
5016 5017 5018 5019
				   INT maxExt, LPINT lpnFit,
				   LPINT alpDx, LPSIZE size )
{
    BOOL ret;
5020
    INT wlen;
5021 5022
    INT *walpDx = NULL;
    LPWSTR p = NULL;
5023 5024

    if (count < 0) return FALSE;
5025
    if (maxExt < -1) return FALSE;
5026 5027 5028 5029 5030 5031 5032

    if (alpDx)
    {
        walpDx = HeapAlloc( GetProcessHeap(), 0, count * sizeof(INT) );
        if (!walpDx) return FALSE;
    }

5033
    p = FONT_mbtowc(hdc, str, count, &wlen, NULL);
5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044
    ret = GetTextExtentExPointW( hdc, p, wlen, maxExt, lpnFit, walpDx, size);
    if (walpDx)
    {
        INT n = lpnFit ? *lpnFit : wlen;
        INT i, j;
        for(i = 0, j = 0; i < n; i++, j++)
        {
            alpDx[j] = walpDx[i];
            if (IsDBCSLeadByte(str[j])) alpDx[++j] = walpDx[i];
        }
    }
5045
    if (lpnFit) *lpnFit = WideCharToMultiByte(CP_ACP,0,p,*lpnFit,NULL,0,NULL,NULL);
5046
    HeapFree( GetProcessHeap(), 0, p );
5047
    HeapFree( GetProcessHeap(), 0, walpDx );
5048 5049 5050 5051 5052
    return ret;
}


/***********************************************************************
5053
 *           GetTextExtentExPointW    (GDI32.@)
5054 5055 5056
 *
 * Return the size of the string as it would be if it was output properly by
 * e.g. TextOut.
5057
 */
5058 5059
BOOL WINAPI GetTextExtentExPointW( HDC hdc, LPCWSTR str, INT count, INT max_ext,
                                   LPINT nfit, LPINT dxs, LPSIZE size )
Alexandre Julliard's avatar
Alexandre Julliard committed
5060
{
5061
    DC *dc;
5062 5063 5064
    int i;
    BOOL ret;
    INT buffer[256], *pos = dxs;
5065

5066 5067
    if (count < 0) return FALSE;

5068
    dc = get_dc_ptr(hdc);
5069
    if (!dc) return FALSE;
5070

5071
    if (!dxs)
Alexandre Julliard's avatar
Alexandre Julliard committed
5072
    {
5073 5074 5075 5076 5077 5078
        pos = buffer;
        if (count > 256 && !(pos = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*pos) )))
        {
            release_dc_ptr( dc );
            return FALSE;
        }
Alexandre Julliard's avatar
Alexandre Julliard committed
5079
    }
Gerald Pfeifer's avatar
Gerald Pfeifer committed
5080

5081
    ret = get_char_positions( dc, str, count, pos, size );
5082 5083
    if (ret)
    {
5084
        if (dxs || nfit)
5085 5086 5087
        {
            for (i = 0; i < count; i++)
            {
5088
                unsigned int dx = abs( INTERNAL_XDSTOWS( dc, pos[i] )) + (i + 1) * dc->charExtra;
5089
                if (nfit && dx > (unsigned int)max_ext) break;
5090
		if (dxs) dxs[i] = dx;
5091
            }
5092
            if (nfit) *nfit = i;
5093
        }
5094

5095 5096 5097
        size->cx = abs( INTERNAL_XDSTOWS( dc, size->cx )) + count * dc->charExtra;
        size->cy = abs( INTERNAL_YDSTOWS( dc, size->cy ));
    }
5098

5099
    if (pos != buffer && pos != dxs) HeapFree( GetProcessHeap(), 0, pos );
5100
    release_dc_ptr( dc );
5101

5102
    TRACE("(%p, %s, %d) returning %dx%d\n", hdc, debugstr_wn(str,count), max_ext, size->cx, size->cy );
5103
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
5104 5105
}

Alexandre Julliard's avatar
Alexandre Julliard committed
5106
/***********************************************************************
5107
 *           GetTextMetricsA    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
5108
 */
5109
BOOL WINAPI GetTextMetricsA( HDC hdc, TEXTMETRICA *metrics )
5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122
{
    TEXTMETRICW tm32;

    if (!GetTextMetricsW( hdc, &tm32 )) return FALSE;
    FONT_TextMetricWToA( &tm32, metrics );
    return TRUE;
}

/***********************************************************************
 *           GetTextMetricsW    (GDI32.@)
 */
BOOL WINAPI GetTextMetricsW( HDC hdc, TEXTMETRICW *metrics )
{
5123
    PHYSDEV physdev;
5124
    BOOL ret = FALSE;
5125
    DC * dc = get_dc_ptr( hdc );
5126
    if (!dc) return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
5127

5128 5129
    physdev = GET_DC_PHYSDEV( dc, pGetTextMetrics );
    ret = physdev->funcs->pGetTextMetrics( physdev, metrics );
5130 5131

    if (ret)
5132
    {
Alexandre Julliard's avatar
Alexandre Julliard committed
5133 5134 5135
    /* device layer returns values in device units
     * therefore we have to convert them to logical */

5136 5137
        metrics->tmDigitizedAspectX = GetDeviceCaps(hdc, LOGPIXELSX);
        metrics->tmDigitizedAspectY = GetDeviceCaps(hdc, LOGPIXELSY);
5138 5139 5140 5141 5142 5143 5144 5145
        metrics->tmHeight           = height_to_LP( dc, metrics->tmHeight );
        metrics->tmAscent           = height_to_LP( dc, metrics->tmAscent );
        metrics->tmDescent          = height_to_LP( dc, metrics->tmDescent );
        metrics->tmInternalLeading  = height_to_LP( dc, metrics->tmInternalLeading );
        metrics->tmExternalLeading  = height_to_LP( dc, metrics->tmExternalLeading );
        metrics->tmAveCharWidth     = width_to_LP( dc, metrics->tmAveCharWidth );
        metrics->tmMaxCharWidth     = width_to_LP( dc, metrics->tmMaxCharWidth );
        metrics->tmOverhang         = width_to_LP( dc, metrics->tmOverhang );
5146
        ret = TRUE;
5147 5148

        TRACE("text metrics:\n"
5149 5150 5151
          "    Weight = %03i\t FirstChar = %i\t AveCharWidth = %i\n"
          "    Italic = % 3i\t LastChar = %i\t\t MaxCharWidth = %i\n"
          "    UnderLined = %01i\t DefaultChar = %i\t Overhang = %i\n"
5152
          "    StruckOut = %01i\t BreakChar = %i\t CharSet = %i\n"
5153 5154
          "    PitchAndFamily = %02x\n"
          "    --------------------\n"
5155 5156 5157 5158
          "    InternalLeading = %i\n"
          "    Ascent = %i\n"
          "    Descent = %i\n"
          "    Height = %i\n",
5159 5160 5161 5162 5163 5164 5165 5166 5167
          metrics->tmWeight, metrics->tmFirstChar, metrics->tmAveCharWidth,
          metrics->tmItalic, metrics->tmLastChar, metrics->tmMaxCharWidth,
          metrics->tmUnderlined, metrics->tmDefaultChar, metrics->tmOverhang,
          metrics->tmStruckOut, metrics->tmBreakChar, metrics->tmCharSet,
          metrics->tmPitchAndFamily,
          metrics->tmInternalLeading,
          metrics->tmAscent,
          metrics->tmDescent,
          metrics->tmHeight );
5168
    }
5169
    release_dc_ptr( dc );
5170
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
5171 5172 5173
}


5174
/***********************************************************************
5175 5176
 *		GetOutlineTextMetricsA (GDI32.@)
 * Gets metrics for TrueType fonts.
5177
 *
5178 5179 5180
 * NOTES
 *    If the supplied buffer isn't big enough Windows partially fills it up to
 *    its given length and returns that length.
5181 5182 5183 5184 5185
 *
 * RETURNS
 *    Success: Non-zero or size of required buffer
 *    Failure: 0
 */
5186 5187 5188 5189
UINT WINAPI GetOutlineTextMetricsA(
    HDC hdc,    /* [in]  Handle of device context */
    UINT cbData, /* [in]  Size of metric data array */
    LPOUTLINETEXTMETRICA lpOTM)  /* [out] Address of metric data array */
5190
{
5191 5192 5193
    char buf[512], *ptr;
    UINT ret, needed;
    OUTLINETEXTMETRICW *lpOTMW = (OUTLINETEXTMETRICW *)buf;
5194
    OUTLINETEXTMETRICA *output = lpOTM;
5195
    INT left, len;
5196

5197 5198 5199
    if((ret = GetOutlineTextMetricsW(hdc, 0, NULL)) == 0)
        return 0;
    if(ret > sizeof(buf))
5200
	lpOTMW = HeapAlloc(GetProcessHeap(), 0, ret);
5201
    GetOutlineTextMetricsW(hdc, ret, lpOTMW);
5202

5203 5204 5205
    needed = sizeof(OUTLINETEXTMETRICA);
    if(lpOTMW->otmpFamilyName)
        needed += WideCharToMultiByte(CP_ACP, 0,
5206
	   (WCHAR*)((char*)lpOTMW + (ptrdiff_t)lpOTMW->otmpFamilyName), -1,
5207 5208 5209
				      NULL, 0, NULL, NULL);
    if(lpOTMW->otmpFaceName)
        needed += WideCharToMultiByte(CP_ACP, 0,
5210
	   (WCHAR*)((char*)lpOTMW + (ptrdiff_t)lpOTMW->otmpFaceName), -1,
5211 5212 5213
				      NULL, 0, NULL, NULL);
    if(lpOTMW->otmpStyleName)
        needed += WideCharToMultiByte(CP_ACP, 0,
5214
	   (WCHAR*)((char*)lpOTMW + (ptrdiff_t)lpOTMW->otmpStyleName), -1,
5215 5216 5217
				      NULL, 0, NULL, NULL);
    if(lpOTMW->otmpFullName)
        needed += WideCharToMultiByte(CP_ACP, 0,
5218
	   (WCHAR*)((char*)lpOTMW + (ptrdiff_t)lpOTMW->otmpFullName), -1,
5219 5220 5221 5222 5223 5224
				      NULL, 0, NULL, NULL);

    if(!lpOTM) {
        ret = needed;
	goto end;
    }
5225

5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264
    TRACE("needed = %d\n", needed);
    if(needed > cbData)
        /* Since the supplied buffer isn't big enough, we'll alloc one
           that is and memcpy the first cbData bytes into the lpOTM at
           the end. */
        output = HeapAlloc(GetProcessHeap(), 0, needed);

    ret = output->otmSize = min(needed, cbData);
    FONT_TextMetricWToA( &lpOTMW->otmTextMetrics, &output->otmTextMetrics );
    output->otmFiller = 0;
    output->otmPanoseNumber = lpOTMW->otmPanoseNumber;
    output->otmfsSelection = lpOTMW->otmfsSelection;
    output->otmfsType = lpOTMW->otmfsType;
    output->otmsCharSlopeRise = lpOTMW->otmsCharSlopeRise;
    output->otmsCharSlopeRun = lpOTMW->otmsCharSlopeRun;
    output->otmItalicAngle = lpOTMW->otmItalicAngle;
    output->otmEMSquare = lpOTMW->otmEMSquare;
    output->otmAscent = lpOTMW->otmAscent;
    output->otmDescent = lpOTMW->otmDescent;
    output->otmLineGap = lpOTMW->otmLineGap;
    output->otmsCapEmHeight = lpOTMW->otmsCapEmHeight;
    output->otmsXHeight = lpOTMW->otmsXHeight;
    output->otmrcFontBox = lpOTMW->otmrcFontBox;
    output->otmMacAscent = lpOTMW->otmMacAscent;
    output->otmMacDescent = lpOTMW->otmMacDescent;
    output->otmMacLineGap = lpOTMW->otmMacLineGap;
    output->otmusMinimumPPEM = lpOTMW->otmusMinimumPPEM;
    output->otmptSubscriptSize = lpOTMW->otmptSubscriptSize;
    output->otmptSubscriptOffset = lpOTMW->otmptSubscriptOffset;
    output->otmptSuperscriptSize = lpOTMW->otmptSuperscriptSize;
    output->otmptSuperscriptOffset = lpOTMW->otmptSuperscriptOffset;
    output->otmsStrikeoutSize = lpOTMW->otmsStrikeoutSize;
    output->otmsStrikeoutPosition = lpOTMW->otmsStrikeoutPosition;
    output->otmsUnderscoreSize = lpOTMW->otmsUnderscoreSize;
    output->otmsUnderscorePosition = lpOTMW->otmsUnderscorePosition;


    ptr = (char*)(output + 1);
    left = needed - sizeof(*output);
5265 5266

    if(lpOTMW->otmpFamilyName) {
5267
        output->otmpFamilyName = (LPSTR)(ptr - (char*)output);
5268
	len = WideCharToMultiByte(CP_ACP, 0,
5269
	     (WCHAR*)((char*)lpOTMW + (ptrdiff_t)lpOTMW->otmpFamilyName), -1,
5270 5271 5272
				  ptr, left, NULL, NULL);
	left -= len;
	ptr += len;
5273
    } else
5274
        output->otmpFamilyName = 0;
5275 5276

    if(lpOTMW->otmpFaceName) {
5277
        output->otmpFaceName = (LPSTR)(ptr - (char*)output);
5278
	len = WideCharToMultiByte(CP_ACP, 0,
5279
	     (WCHAR*)((char*)lpOTMW + (ptrdiff_t)lpOTMW->otmpFaceName), -1,
5280 5281 5282
				  ptr, left, NULL, NULL);
	left -= len;
	ptr += len;
5283
    } else
5284
        output->otmpFaceName = 0;
5285 5286

    if(lpOTMW->otmpStyleName) {
5287
        output->otmpStyleName = (LPSTR)(ptr - (char*)output);
5288
	len = WideCharToMultiByte(CP_ACP, 0,
5289
	     (WCHAR*)((char*)lpOTMW + (ptrdiff_t)lpOTMW->otmpStyleName), -1,
5290 5291 5292 5293
				  ptr, left, NULL, NULL);
	left -= len;
	ptr += len;
    } else
5294
        output->otmpStyleName = 0;
5295 5296

    if(lpOTMW->otmpFullName) {
5297
        output->otmpFullName = (LPSTR)(ptr - (char*)output);
5298
	len = WideCharToMultiByte(CP_ACP, 0,
5299
	     (WCHAR*)((char*)lpOTMW + (ptrdiff_t)lpOTMW->otmpFullName), -1,
5300 5301 5302
				  ptr, left, NULL, NULL);
	left -= len;
    } else
5303
        output->otmpFullName = 0;
5304

5305
    assert(left == 0);
5306

5307 5308 5309
    if(output != lpOTM) {
        memcpy(lpOTM, output, cbData);
        HeapFree(GetProcessHeap(), 0, output);
5310 5311 5312

        /* check if the string offsets really fit into the provided size */
        /* FIXME: should we check string length as well? */
5313 5314 5315 5316 5317 5318
        /* make sure that we don't read/write beyond the provided buffer */
        if (lpOTM->otmSize >= FIELD_OFFSET(OUTLINETEXTMETRICA, otmpFamilyName) + sizeof(LPSTR))
        {
            if ((UINT_PTR)lpOTM->otmpFamilyName >= lpOTM->otmSize)
                lpOTM->otmpFamilyName = 0; /* doesn't fit */
        }
5319

5320 5321 5322 5323 5324 5325
        /* make sure that we don't read/write beyond the provided buffer */
        if (lpOTM->otmSize >= FIELD_OFFSET(OUTLINETEXTMETRICA, otmpFaceName) + sizeof(LPSTR))
        {
            if ((UINT_PTR)lpOTM->otmpFaceName >= lpOTM->otmSize)
                lpOTM->otmpFaceName = 0; /* doesn't fit */
        }
5326

5327 5328 5329 5330 5331 5332
            /* make sure that we don't read/write beyond the provided buffer */
        if (lpOTM->otmSize >= FIELD_OFFSET(OUTLINETEXTMETRICA, otmpStyleName) + sizeof(LPSTR))
        {
            if ((UINT_PTR)lpOTM->otmpStyleName >= lpOTM->otmSize)
                lpOTM->otmpStyleName = 0; /* doesn't fit */
        }
5333

5334 5335 5336 5337 5338 5339
        /* make sure that we don't read/write beyond the provided buffer */
        if (lpOTM->otmSize >= FIELD_OFFSET(OUTLINETEXTMETRICA, otmpFullName) + sizeof(LPSTR))
        {
            if ((UINT_PTR)lpOTM->otmpFullName >= lpOTM->otmSize)
                lpOTM->otmpFullName = 0; /* doesn't fit */
        }
5340
    }
5341 5342 5343 5344 5345 5346

end:
    if(lpOTMW != (OUTLINETEXTMETRICW *)buf)
        HeapFree(GetProcessHeap(), 0, lpOTMW);

    return ret;
5347 5348
}

5349

5350
/***********************************************************************
5351
 *           GetOutlineTextMetricsW [GDI32.@]
5352
 */
5353 5354 5355 5356
UINT WINAPI GetOutlineTextMetricsW(
    HDC hdc,    /* [in]  Handle of device context */
    UINT cbData, /* [in]  Size of metric data array */
    LPOUTLINETEXTMETRICW lpOTM)  /* [out] Address of metric data array */
5357
{
5358
    DC *dc = get_dc_ptr( hdc );
5359
    OUTLINETEXTMETRICW *output = lpOTM;
5360
    PHYSDEV dev;
5361 5362
    UINT ret;

5363
    TRACE("(%p,%d,%p)\n", hdc, cbData, lpOTM);
5364 5365
    if(!dc) return 0;

5366 5367
    dev = GET_DC_PHYSDEV( dc, pGetOutlineTextMetrics );
    ret = dev->funcs->pGetOutlineTextMetrics( dev, cbData, output );
5368

5369 5370 5371 5372 5373 5374 5375 5376
    if (lpOTM && ret > cbData)
    {
        output = HeapAlloc(GetProcessHeap(), 0, ret);
        ret = dev->funcs->pGetOutlineTextMetrics( dev, ret, output );
    }

    if (lpOTM && ret)
    {
5377 5378
        output->otmTextMetrics.tmDigitizedAspectX = GetDeviceCaps(hdc, LOGPIXELSX);
        output->otmTextMetrics.tmDigitizedAspectY = GetDeviceCaps(hdc, LOGPIXELSY);
5379 5380 5381 5382 5383 5384 5385 5386 5387 5388
        output->otmTextMetrics.tmHeight           = height_to_LP( dc, output->otmTextMetrics.tmHeight );
        output->otmTextMetrics.tmAscent           = height_to_LP( dc, output->otmTextMetrics.tmAscent );
        output->otmTextMetrics.tmDescent          = height_to_LP( dc, output->otmTextMetrics.tmDescent );
        output->otmTextMetrics.tmInternalLeading  = height_to_LP( dc, output->otmTextMetrics.tmInternalLeading );
        output->otmTextMetrics.tmExternalLeading  = height_to_LP( dc, output->otmTextMetrics.tmExternalLeading );
        output->otmTextMetrics.tmAveCharWidth     = width_to_LP( dc, output->otmTextMetrics.tmAveCharWidth );
        output->otmTextMetrics.tmMaxCharWidth     = width_to_LP( dc, output->otmTextMetrics.tmMaxCharWidth );
        output->otmTextMetrics.tmOverhang         = width_to_LP( dc, output->otmTextMetrics.tmOverhang );
        output->otmAscent                = height_to_LP( dc, output->otmAscent);
        output->otmDescent               = height_to_LP( dc, output->otmDescent);
5389 5390 5391
        output->otmLineGap               = INTERNAL_YDSTOWS(dc, output->otmLineGap);
        output->otmsCapEmHeight          = INTERNAL_YDSTOWS(dc, output->otmsCapEmHeight);
        output->otmsXHeight              = INTERNAL_YDSTOWS(dc, output->otmsXHeight);
5392 5393 5394 5395 5396 5397
        output->otmrcFontBox.top         = height_to_LP( dc, output->otmrcFontBox.top);
        output->otmrcFontBox.bottom      = height_to_LP( dc, output->otmrcFontBox.bottom);
        output->otmrcFontBox.left        = width_to_LP( dc, output->otmrcFontBox.left);
        output->otmrcFontBox.right       = width_to_LP( dc, output->otmrcFontBox.right);
        output->otmMacAscent             = height_to_LP( dc, output->otmMacAscent);
        output->otmMacDescent            = height_to_LP( dc, output->otmMacDescent);
5398
        output->otmMacLineGap            = INTERNAL_YDSTOWS(dc, output->otmMacLineGap);
5399 5400 5401 5402 5403 5404 5405 5406
        output->otmptSubscriptSize.x     = width_to_LP( dc, output->otmptSubscriptSize.x);
        output->otmptSubscriptSize.y     = height_to_LP( dc, output->otmptSubscriptSize.y);
        output->otmptSubscriptOffset.x   = width_to_LP( dc, output->otmptSubscriptOffset.x);
        output->otmptSubscriptOffset.y   = height_to_LP( dc, output->otmptSubscriptOffset.y);
        output->otmptSuperscriptSize.x   = width_to_LP( dc, output->otmptSuperscriptSize.x);
        output->otmptSuperscriptSize.y   = height_to_LP( dc, output->otmptSuperscriptSize.y);
        output->otmptSuperscriptOffset.x = width_to_LP( dc, output->otmptSuperscriptOffset.x);
        output->otmptSuperscriptOffset.y = height_to_LP( dc, output->otmptSuperscriptOffset.y);
5407
        output->otmsStrikeoutSize        = INTERNAL_YDSTOWS(dc, output->otmsStrikeoutSize);
5408 5409 5410
        output->otmsStrikeoutPosition    = height_to_LP( dc, output->otmsStrikeoutPosition);
        output->otmsUnderscoreSize       = height_to_LP( dc, output->otmsUnderscoreSize);
        output->otmsUnderscorePosition   = height_to_LP( dc, output->otmsUnderscorePosition);
5411

5412 5413 5414 5415 5416 5417
        if(output != lpOTM)
        {
            memcpy(lpOTM, output, cbData);
            HeapFree(GetProcessHeap(), 0, output);
            ret = cbData;
        }
5418
    }
5419
    release_dc_ptr(dc);
5420
    return ret;
5421
}
5422

5423
static LPSTR FONT_GetCharsByRangeA(HDC hdc, UINT firstChar, UINT lastChar, PINT pByteLen)
5424 5425
{
    INT i, count = lastChar - firstChar + 1;
5426
    UINT mbcp;
5427 5428 5429 5430 5431 5432
    UINT c;
    LPSTR str;

    if (count <= 0)
        return NULL;

5433 5434
    mbcp = GdiGetCodePage(hdc);
    switch (mbcp)
5435 5436 5437 5438 5439 5440 5441 5442
    {
    case 932:
    case 936:
    case 949:
    case 950:
    case 1361:
        if (lastChar > 0xffff)
            return NULL;
5443 5444
        if ((firstChar ^ lastChar) > 0xff)
            return NULL;
5445 5446 5447 5448
        break;
    default:
        if (lastChar > 0xff)
            return NULL;
5449
        mbcp = 0;
5450 5451 5452
        break;
    }

5453 5454 5455 5456 5457 5458
    str = HeapAlloc(GetProcessHeap(), 0, count * 2 + 1);
    if (str == NULL)
        return NULL;

    for(i = 0, c = firstChar; c <= lastChar; i++, c++)
    {
5459 5460 5461 5462 5463 5464 5465 5466 5467 5468
        if (mbcp) {
            if (c > 0xff)
                str[i++] = (BYTE)(c >> 8);
            if (c <= 0xff && IsDBCSLeadByteEx(mbcp, c))
                str[i] = 0x1f; /* FIXME: use default character */
            else
                str[i] = (BYTE)c;
        }
        else
            str[i] = (BYTE)c;
5469 5470 5471 5472 5473 5474 5475
    }
    str[i] = '\0';

    *pByteLen = i;

    return str;
}
5476

Alexandre Julliard's avatar
Alexandre Julliard committed
5477
/***********************************************************************
5478 5479
 *           GetCharWidthW      (GDI32.@)
 *           GetCharWidth32W    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
5480
 */
5481
BOOL WINAPI GetCharWidth32W( HDC hdc, UINT firstChar, UINT lastChar,
5482
                               LPINT buffer )
Alexandre Julliard's avatar
Alexandre Julliard committed
5483
{
5484
    UINT i;
5485
    BOOL ret;
5486
    PHYSDEV dev;
5487
    DC * dc = get_dc_ptr( hdc );
5488

5489
    if (!dc) return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
5490

5491 5492
    dev = GET_DC_PHYSDEV( dc, pGetCharWidth );
    ret = dev->funcs->pGetCharWidth( dev, firstChar, lastChar, buffer );
5493 5494

    if (ret)
5495 5496 5497
    {
        /* convert device units to logical */
        for( i = firstChar; i <= lastChar; i++, buffer++ )
5498
            *buffer = width_to_LP( dc, *buffer );
5499
    }
5500
    release_dc_ptr( dc );
5501
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
5502
}
Alexandre Julliard's avatar
Alexandre Julliard committed
5503

Alexandre Julliard's avatar
Alexandre Julliard committed
5504

Alexandre Julliard's avatar
Alexandre Julliard committed
5505
/***********************************************************************
5506 5507
 *           GetCharWidthA      (GDI32.@)
 *           GetCharWidth32A    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
5508
 */
5509
BOOL WINAPI GetCharWidth32A( HDC hdc, UINT firstChar, UINT lastChar,
5510
                               LPINT buffer )
Alexandre Julliard's avatar
Alexandre Julliard committed
5511
{
5512
    INT i, wlen;
5513 5514 5515 5516
    LPSTR str;
    LPWSTR wstr;
    BOOL ret = TRUE;

5517
    str = FONT_GetCharsByRangeA(hdc, firstChar, lastChar, &i);
5518 5519
    if(str == NULL)
        return FALSE;
5520

5521
    wstr = FONT_mbtowc(hdc, str, i, &wlen, NULL);
5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536

    for(i = 0; i < wlen; i++)
    {
	if(!GetCharWidth32W(hdc, wstr[i], wstr[i], buffer))
	{
	    ret = FALSE;
	    break;
	}
	buffer++;
    }

    HeapFree(GetProcessHeap(), 0, str);
    HeapFree(GetProcessHeap(), 0, wstr);

    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
5537 5538 5539
}


5540
/* helper for nulldrv_ExtTextOut */
5541
static DWORD get_glyph_bitmap( HDC hdc, UINT index, UINT flags, UINT aa_flags,
5542 5543 5544
                               GLYPHMETRICS *metrics, struct gdi_image_bits *image )
{
    UINT indices[3] = {0, 0, 0x20};
5545
    unsigned int i;
5546 5547 5548 5549
    DWORD ret, size;
    int stride;

    indices[0] = index;
5550
    if (flags & ETO_GLYPH_INDEX) aa_flags |= GGO_GLYPH_INDEX;
5551

5552
    for (i = 0; i < ARRAY_SIZE( indices ); i++)
5553
    {
5554
        index = indices[i];
5555
        ret = GetGlyphOutlineW( hdc, index, aa_flags, metrics, 0, NULL, &identity );
5556 5557 5558 5559 5560 5561 5562 5563
        if (ret != GDI_ERROR) break;
    }

    if (ret == GDI_ERROR) return ERROR_NOT_FOUND;
    if (!image) return ERROR_SUCCESS;

    image->ptr = NULL;
    image->free = NULL;
5564 5565 5566 5567 5568
    if (!ret)  /* empty glyph */
    {
        metrics->gmBlackBoxX = metrics->gmBlackBoxY = 0;
        return ERROR_SUCCESS;
    }
5569 5570 5571 5572 5573 5574 5575 5576

    stride = get_dib_stride( metrics->gmBlackBoxX, 1 );
    size = metrics->gmBlackBoxY * stride;

    if (!(image->ptr = HeapAlloc( GetProcessHeap(), 0, size ))) return ERROR_OUTOFMEMORY;
    image->is_copy = TRUE;
    image->free = free_heap_bits;

5577
    ret = GetGlyphOutlineW( hdc, index, aa_flags, metrics, size, image->ptr, &identity );
5578 5579 5580 5581 5582 5583 5584 5585
    if (ret == GDI_ERROR)
    {
        HeapFree( GetProcessHeap(), 0, image->ptr );
        return ERROR_NOT_FOUND;
    }
    return ERROR_SUCCESS;
}

5586 5587 5588 5589
/* helper for nulldrv_ExtTextOut */
static RECT get_total_extents( HDC hdc, INT x, INT y, UINT flags, UINT aa_flags,
                               LPCWSTR str, UINT count, const INT *dx )
{
5590
    UINT i;
5591
    RECT rect, bounds;
5592

5593
    reset_bounds( &bounds );
5594 5595 5596 5597
    for (i = 0; i < count; i++)
    {
        GLYPHMETRICS metrics;

5598
        if (get_glyph_bitmap( hdc, str[i], flags, aa_flags, &metrics, NULL )) continue;
5599

5600 5601 5602 5603 5604
        rect.left   = x + metrics.gmptGlyphOrigin.x;
        rect.top    = y - metrics.gmptGlyphOrigin.y;
        rect.right  = rect.left + metrics.gmBlackBoxX;
        rect.bottom = rect.top  + metrics.gmBlackBoxY;
        add_bounds_rect( &bounds, &rect );
5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620

        if (dx)
        {
            if (flags & ETO_PDY)
            {
                x += dx[ i * 2 ];
                y += dx[ i * 2 + 1];
            }
            else x += dx[ i ];
        }
        else
        {
            x += metrics.gmCellIncX;
            y += metrics.gmCellIncY;
        }
    }
5621
    return bounds;
5622 5623
}

5624
/* helper for nulldrv_ExtTextOut */
5625
static void draw_glyph( DC *dc, INT origin_x, INT origin_y, const GLYPHMETRICS *metrics,
5626 5627 5628
                        const struct gdi_image_bits *image, const RECT *clip )
{
    static const BYTE masks[8] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
5629 5630
    UINT i, count, max_count;
    LONG x, y;
5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642
    BYTE *ptr = image->ptr;
    int stride = get_dib_stride( metrics->gmBlackBoxX, 1 );
    POINT *pts;
    RECT rect, clipped_rect;

    rect.left   = origin_x  + metrics->gmptGlyphOrigin.x;
    rect.top    = origin_y  - metrics->gmptGlyphOrigin.y;
    rect.right  = rect.left + metrics->gmBlackBoxX;
    rect.bottom = rect.top  + metrics->gmBlackBoxY;
    if (!clip) clipped_rect = rect;
    else if (!intersect_rect( &clipped_rect, &rect, clip )) return;

5643 5644
    max_count = (metrics->gmBlackBoxX + 1) * metrics->gmBlackBoxY;
    pts = HeapAlloc( GetProcessHeap(), 0, max_count * sizeof(*pts) );
5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663
    if (!pts) return;

    count = 0;
    ptr += (clipped_rect.top - rect.top) * stride;
    for (y = clipped_rect.top; y < clipped_rect.bottom; y++, ptr += stride)
    {
        for (x = clipped_rect.left - rect.left; x < clipped_rect.right - rect.left; x++)
        {
            while (x < clipped_rect.right - rect.left && !(ptr[x / 8] & masks[x % 8])) x++;
            pts[count].x = rect.left + x;
            while (x < clipped_rect.right - rect.left && (ptr[x / 8] & masks[x % 8])) x++;
            pts[count + 1].x = rect.left + x;
            if (pts[count + 1].x > pts[count].x)
            {
                pts[count].y = pts[count + 1].y = y;
                count += 2;
            }
        }
    }
5664
    assert( count <= max_count );
5665 5666
    dp_to_lp( dc, pts, count );
    for (i = 0; i < count; i += 2) Polyline( dc->hSelf, pts + i, 2 );
5667 5668 5669 5670 5671 5672
    HeapFree( GetProcessHeap(), 0, pts );
}

/***********************************************************************
 *           nulldrv_ExtTextOut
 */
5673 5674
BOOL CDECL nulldrv_ExtTextOut( PHYSDEV dev, INT x, INT y, UINT flags, const RECT *rect,
                               LPCWSTR str, UINT count, const INT *dx )
5675
{
5676
    DC *dc = get_nulldrv_dc( dev );
5677
    UINT i;
5678 5679 5680 5681 5682 5683 5684
    DWORD err;
    HGDIOBJ orig;
    HPEN pen;

    if (flags & ETO_OPAQUE)
    {
        RECT rc = *rect;
5685
        HBRUSH brush = CreateSolidBrush( GetNearestColor( dev->hdc, dc->backgroundColor ) );
5686 5687 5688 5689

        if (brush)
        {
            orig = SelectObject( dev->hdc, brush );
5690
            dp_to_lp( dc, (POINT *)&rc, 2 );
5691 5692 5693 5694 5695 5696 5697 5698
            PatBlt( dev->hdc, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, PATCOPY );
            SelectObject( dev->hdc, orig );
            DeleteObject( brush );
        }
    }

    if (!count) return TRUE;

5699
    if (dc->aa_flags != GGO_BITMAP)
5700 5701 5702 5703 5704 5705
    {
        char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
        BITMAPINFO *info = (BITMAPINFO *)buffer;
        struct gdi_image_bits bits;
        struct bitblt_coords src, dst;
        PHYSDEV dst_dev;
5706
        /* FIXME Subpixel modes */
5707
        UINT aa_flags = GGO_GRAY4_BITMAP;
5708

5709 5710 5711
        dst_dev = GET_DC_PHYSDEV( dc, pPutImage );
        src.visrect = get_total_extents( dev->hdc, x, y, flags, aa_flags, str, count, dx );
        if (flags & ETO_CLIPPED) intersect_rect( &src.visrect, &src.visrect, rect );
5712
        if (!clip_visrect( dc, &src.visrect, &src.visrect )) return TRUE;
5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727

        /* FIXME: check for ETO_OPAQUE and avoid GetImage */
        src.x = src.visrect.left;
        src.y = src.visrect.top;
        src.width = src.visrect.right - src.visrect.left;
        src.height = src.visrect.bottom - src.visrect.top;
        dst = src;
        if ((flags & ETO_OPAQUE) && (src.visrect.left >= rect->left) && (src.visrect.top >= rect->top) &&
            (src.visrect.right <= rect->right) && (src.visrect.bottom <= rect->bottom))
        {
            /* we can avoid the GetImage, just query the needed format */
            memset( &info->bmiHeader, 0, sizeof(info->bmiHeader) );
            info->bmiHeader.biSize   = sizeof(info->bmiHeader);
            info->bmiHeader.biWidth  = src.width;
            info->bmiHeader.biHeight = -src.height;
5728
            info->bmiHeader.biSizeImage = get_dib_image_size( info );
5729
            err = dst_dev->funcs->pPutImage( dst_dev, 0, info, NULL, NULL, NULL, 0 );
5730 5731 5732 5733 5734 5735 5736 5737
            if (!err || err == ERROR_BAD_FORMAT)
            {
                /* make the source rectangle relative to the source bits */
                src.x = src.y = 0;
                src.visrect.left = src.visrect.top = 0;
                src.visrect.right = src.width;
                src.visrect.bottom = src.height;

5738
                bits.ptr = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
5739 5740 5741 5742 5743 5744 5745 5746 5747
                if (!bits.ptr) return ERROR_OUTOFMEMORY;
                bits.is_copy = TRUE;
                bits.free = free_heap_bits;
                err = ERROR_SUCCESS;
            }
        }
        else
        {
            PHYSDEV src_dev = GET_DC_PHYSDEV( dc, pGetImage );
5748
            err = src_dev->funcs->pGetImage( src_dev, info, &bits, &src );
5749 5750
            if (!err && !bits.is_copy)
            {
5751
                void *ptr = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
5752 5753 5754 5755 5756
                if (!ptr)
                {
                    if (bits.free) bits.free( &bits );
                    return ERROR_OUTOFMEMORY;
                }
5757
                memcpy( ptr, bits.ptr, info->bmiHeader.biSizeImage );
5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768
                if (bits.free) bits.free( &bits );
                bits.ptr = ptr;
                bits.is_copy = TRUE;
                bits.free = free_heap_bits;
            }
        }
        if (!err)
        {
            /* make x,y relative to the image bits */
            x += src.visrect.left - dst.visrect.left;
            y += src.visrect.top - dst.visrect.top;
5769
            render_aa_text_bitmapinfo( dc, info, &bits, &src, x, y, flags,
5770
                                       aa_flags, str, count, dx );
5771
            err = dst_dev->funcs->pPutImage( dst_dev, 0, info, &bits, &src, &dst, SRCCOPY );
5772 5773 5774 5775 5776
            if (bits.free) bits.free( &bits );
            return !err;
        }
    }

5777
    pen = CreatePen( PS_SOLID, 1, dc->textColor );
5778 5779 5780 5781 5782 5783 5784
    orig = SelectObject( dev->hdc, pen );

    for (i = 0; i < count; i++)
    {
        GLYPHMETRICS metrics;
        struct gdi_image_bits image;

5785
        err = get_glyph_bitmap( dev->hdc, str[i], flags, GGO_BITMAP, &metrics, &image );
5786 5787
        if (err) continue;

5788
        if (image.ptr) draw_glyph( dc, x, y, &metrics, &image, (flags & ETO_CLIPPED) ? rect : NULL );
5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812
        if (image.free) image.free( &image );

        if (dx)
        {
            if (flags & ETO_PDY)
            {
                x += dx[ i * 2 ];
                y += dx[ i * 2 + 1];
            }
            else x += dx[ i ];
        }
        else
        {
            x += metrics.gmCellIncX;
            y += metrics.gmCellIncY;
        }
    }

    SelectObject( dev->hdc, orig );
    DeleteObject( pen );
    return TRUE;
}


5813 5814
/***********************************************************************
 *           ExtTextOutA    (GDI32.@)
5815 5816
 *
 * See ExtTextOutW.
5817 5818 5819 5820 5821
 */
BOOL WINAPI ExtTextOutA( HDC hdc, INT x, INT y, UINT flags,
                         const RECT *lprect, LPCSTR str, UINT count, const INT *lpDx )
{
    INT wlen;
5822
    UINT codepage;
5823
    LPWSTR p;
5824 5825 5826
    BOOL ret;
    LPINT lpDxW = NULL;

5827 5828 5829
    if (flags & ETO_GLYPH_INDEX)
        return ExtTextOutW( hdc, x, y, flags, lprect, (LPCWSTR)str, count, lpDx );

5830
    p = FONT_mbtowc(hdc, str, count, &wlen, &codepage);
5831

5832 5833 5834
    if (lpDx) {
        unsigned int i = 0, j = 0;

5835 5836
        /* allocate enough for a ETO_PDY */
        lpDxW = HeapAlloc( GetProcessHeap(), 0, 2*wlen*sizeof(INT));
5837
        while(i < count) {
5838 5839 5840 5841 5842 5843 5844 5845 5846
            if(IsDBCSLeadByteEx(codepage, str[i]))
            {
                if(flags & ETO_PDY)
                {
                    lpDxW[j++] = lpDx[i * 2]     + lpDx[(i + 1) * 2];
                    lpDxW[j++] = lpDx[i * 2 + 1] + lpDx[(i + 1) * 2 + 1];
                }
                else
                    lpDxW[j++] = lpDx[i] + lpDx[i + 1];
5847
                i = i + 2;
5848 5849 5850 5851 5852 5853 5854 5855 5856 5857
            }
            else
            {
                if(flags & ETO_PDY)
                {
                    lpDxW[j++] = lpDx[i * 2];
                    lpDxW[j++] = lpDx[i * 2 + 1];
                }
                else
                    lpDxW[j++] = lpDx[i];
5858 5859 5860 5861 5862 5863 5864 5865
                i = i + 1;
            }
        }
    }

    ret = ExtTextOutW( hdc, x, y, flags, lprect, p, wlen, lpDxW );

    HeapFree( GetProcessHeap(), 0, p );
5866
    HeapFree( GetProcessHeap(), 0, lpDxW );
5867 5868 5869
    return ret;
}

5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881
/***********************************************************************
 *           get_line_width
 *
 * Scale the underline / strikeout line width.
 */
static inline int get_line_width( DC *dc, int metric_size )
{
    int width = abs( INTERNAL_YWSTODS( dc, metric_size ));
    if (width == 0) width = 1;
    if (metric_size < 0) width = -width;
    return width;
}
5882 5883 5884

/***********************************************************************
 *           ExtTextOutW    (GDI32.@)
5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911
 *
 * Draws text using the currently selected font, background color, and text color.
 * 
 * 
 * PARAMS
 *    x,y    [I] coordinates of string
 *    flags  [I]
 *        ETO_GRAYED - undocumented on MSDN
 *        ETO_OPAQUE - use background color for fill the rectangle
 *        ETO_CLIPPED - clipping text to the rectangle
 *        ETO_GLYPH_INDEX - Buffer is of glyph locations in fonts rather
 *                          than encoded characters. Implies ETO_IGNORELANGUAGE
 *        ETO_RTLREADING - Paragraph is basically a right-to-left paragraph.
 *                         Affects BiDi ordering
 *        ETO_IGNORELANGUAGE - Undocumented in MSDN - instructs ExtTextOut not to do BiDi reordering
 *        ETO_PDY - unimplemented
 *        ETO_NUMERICSLATIN - unimplemented always assumed -
 *                            do not translate numbers into locale representations
 *        ETO_NUMERICSLOCAL - unimplemented - Numerals in Arabic/Farsi context should assume local form
 *    lprect [I] dimensions for clipping or/and opaquing
 *    str    [I] text string
 *    count  [I] number of symbols in string
 *    lpDx   [I] optional parameter with distance between drawing characters
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
5912 5913 5914 5915 5916
 */
BOOL WINAPI ExtTextOutW( HDC hdc, INT x, INT y, UINT flags,
                         const RECT *lprect, LPCWSTR str, UINT count, const INT *lpDx )
{
    BOOL ret = FALSE;
5917
    LPWSTR reordered_str = (LPWSTR)str;
5918
    WORD *glyphs = NULL;
5919 5920
    UINT align;
    DWORD layout;
5921 5922 5923 5924
    POINT pt;
    TEXTMETRICW tm;
    LOGFONTW lf;
    double cosEsc, sinEsc;
5925
    INT char_extra;
5926 5927
    SIZE sz;
    RECT rc;
5928
    POINT *deltas = NULL, width = {0, 0};
5929
    DWORD type;
5930
    DC * dc = get_dc_ptr( hdc );
5931
    PHYSDEV physdev;
5932
    INT breakRem;
5933
    static int quietfixme = 0;
5934 5935 5936

    if (!dc) return FALSE;

5937
    align = dc->textAlign;
5938
    breakRem = dc->breakRem;
5939
    layout = dc->layout;
5940

5941
    if (quietfixme == 0 && flags & (ETO_NUMERICSLOCAL | ETO_NUMERICSLATIN))
5942
    {
5943
        FIXME("flags ETO_NUMERICSLOCAL | ETO_NUMERICSLATIN unimplemented\n");
5944 5945
        quietfixme = 1;
    }
5946

5947
    update_dc( dc );
5948
    physdev = GET_DC_PHYSDEV( dc, pExtTextOut );
5949 5950 5951
    type = GetObjectType(hdc);
    if(type == OBJ_METADC || type == OBJ_ENHMETADC)
    {
5952
        ret = physdev->funcs->pExtTextOut( physdev, x, y, flags, lprect, str, count, lpDx );
5953
        release_dc_ptr( dc );
5954 5955
        return ret;
    }
5956

5957 5958 5959 5960 5961 5962 5963
    if (flags & ETO_RTLREADING) align |= TA_RTLREADING;
    if (layout & LAYOUT_RTL)
    {
        if ((align & TA_CENTER) != TA_CENTER) align ^= TA_RIGHT;
        align ^= TA_RTLREADING;
    }

5964
    if( !(flags & (ETO_GLYPH_INDEX | ETO_IGNORELANGUAGE)) && count > 0 )
5965
    {
5966
        INT cGlyphs;
5967 5968
        reordered_str = HeapAlloc(GetProcessHeap(), 0, count*sizeof(WCHAR));

5969
        BIDI_Reorder( hdc, str, count, GCP_REORDER,
5970
                      (align & TA_RTLREADING) ? WINE_GCPW_FORCE_RTL : WINE_GCPW_FORCE_LTR,
5971
                      reordered_str, count, NULL, &glyphs, &cGlyphs);
5972

5973
        flags |= ETO_IGNORELANGUAGE;
5974
        if (glyphs)
5975
        {
5976
            flags |= ETO_GLYPH_INDEX;
5977 5978 5979
            if (cGlyphs != count)
                count = cGlyphs;
        }
5980
    }
5981 5982
    else if(flags & ETO_GLYPH_INDEX)
        glyphs = reordered_str;
5983

5984 5985
    TRACE("%p, %d, %d, %08x, %s, %s, %d, %p)\n", hdc, x, y, flags,
          wine_dbgstr_rect(lprect), debugstr_wn(str, count), count, lpDx);
5986
    TRACE("align = %x bkmode = %x mapmode = %x\n", align, dc->backgroundMode, dc->MapMode);
5987 5988 5989

    if(align & TA_UPDATECP)
    {
5990
        pt = dc->cur_pos;
5991 5992 5993 5994 5995
        x = pt.x;
        y = pt.y;
    }

    GetTextMetricsW(hdc, &tm);
5996
    GetObjectW(dc->hFont, sizeof(lf), &lf);
5997 5998 5999 6000

    if(!(tm.tmPitchAndFamily & TMPF_VECTOR)) /* Non-scalable fonts shouldn't be rotated */
        lf.lfEscapement = 0;

6001 6002 6003 6004 6005 6006
    if ((dc->GraphicsMode == GM_COMPATIBLE) &&
        (dc->vport2WorldValid && dc->xformWorld2Vport.eM11 * dc->xformWorld2Vport.eM22 < 0))
    {
        lf.lfEscapement = -lf.lfEscapement;
    }

6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017
    if(lf.lfEscapement != 0)
    {
        cosEsc = cos(lf.lfEscapement * M_PI / 1800);
        sinEsc = sin(lf.lfEscapement * M_PI / 1800);
    }
    else
    {
        cosEsc = 1;
        sinEsc = 0;
    }

6018
    if (lprect && (flags & (ETO_OPAQUE | ETO_CLIPPED)))
6019
    {
6020
        rc = *lprect;
6021
        lp_to_dp(dc, (POINT*)&rc, 2);
6022
        order_rect( &rc );
6023 6024
        if (flags & ETO_OPAQUE)
            physdev->funcs->pExtTextOut( physdev, 0, 0, ETO_OPAQUE, &rc, NULL, 0, NULL );
6025
    }
6026
    else flags &= ~ETO_CLIPPED;
6027

6028
    if(count == 0)
6029 6030
    {
        ret = TRUE;
6031
        goto done;
6032
    }
6033 6034 6035

    pt.x = x;
    pt.y = y;
6036
    lp_to_dp(dc, &pt, 1);
6037 6038 6039 6040
    x = pt.x;
    y = pt.y;

    char_extra = GetTextCharacterExtra(hdc);
6041 6042 6043
    if (char_extra && lpDx && GetDeviceCaps( hdc, TECHNOLOGY ) == DT_RASPRINTER)
        char_extra = 0; /* Printer drivers don't add char_extra if lpDx is supplied */

6044
    if(char_extra || dc->breakExtra || breakRem || lpDx || lf.lfEscapement != 0)
6045 6046
    {
        UINT i;
6047 6048 6049
        POINT total = {0, 0}, desired[2];

        deltas = HeapAlloc(GetProcessHeap(), 0, count * sizeof(*deltas));
6050
        if (lpDx)
6051
        {
6052
            if (flags & ETO_PDY)
6053
            {
6054
                for (i = 0; i < count; i++)
6055 6056 6057 6058
                {
                    deltas[i].x = lpDx[i * 2] + char_extra;
                    deltas[i].y = -lpDx[i * 2 + 1];
                }
6059 6060 6061 6062
            }
            else
            {
                for (i = 0; i < count; i++)
6063 6064 6065 6066 6067
                {
                    deltas[i].x = lpDx[i] + char_extra;
                    deltas[i].y = 0;
                }
            }
6068 6069 6070 6071 6072 6073 6074
        }
        else
        {
            INT *dx = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*dx) );

            if (flags & ETO_GLYPH_INDEX)
                GetTextExtentExPointI( hdc, glyphs, count, -1, NULL, dx, &sz );
6075
            else
6076
                GetTextExtentExPointW( hdc, reordered_str, count, -1, NULL, dx, &sz );
6077

6078 6079 6080
            deltas[0].x = dx[0];
            deltas[0].y = 0;
            for (i = 1; i < count; i++)
6081
            {
6082 6083
                deltas[i].x = dx[i] - dx[i - 1];
                deltas[i].y = 0;
6084
            }
6085 6086 6087 6088 6089
            HeapFree( GetProcessHeap(), 0, dx );
        }

        for(i = 0; i < count; i++)
        {
6090 6091 6092 6093 6094 6095 6096 6097
            total.x += deltas[i].x;
            total.y += deltas[i].y;

            desired[0].x = desired[0].y = 0;

            desired[1].x =  cosEsc * total.x + sinEsc * total.y;
            desired[1].y = -sinEsc * total.x + cosEsc * total.y;

6098
            lp_to_dp(dc, desired, 2);
6099 6100
            desired[1].x -= desired[0].x;
            desired[1].y -= desired[0].y;
6101 6102 6103 6104 6105 6106 6107 6108

            if (dc->GraphicsMode == GM_COMPATIBLE)
            {
                if (dc->vport2WorldValid && dc->xformWorld2Vport.eM11 < 0)
                    desired[1].x = -desired[1].x;
                if (dc->vport2WorldValid && dc->xformWorld2Vport.eM22 < 0)
                    desired[1].y = -desired[1].y;
            }
6109 6110 6111 6112 6113

            deltas[i].x = desired[1].x - width.x;
            deltas[i].y = desired[1].y - width.y;

            width = desired[1];
6114
        }
6115
        flags |= ETO_PDY;
6116 6117 6118
    }
    else
    {
6119 6120
        POINT desired[2];

6121 6122 6123 6124
        if(flags & ETO_GLYPH_INDEX)
            GetTextExtentPointI(hdc, glyphs, count, &sz);
        else
            GetTextExtentPointW(hdc, reordered_str, count, &sz);
6125 6126 6127
        desired[0].x = desired[0].y = 0;
        desired[1].x = sz.cx;
        desired[1].y = 0;
6128
        lp_to_dp(dc, desired, 2);
6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139
        desired[1].x -= desired[0].x;
        desired[1].y -= desired[0].y;

        if (dc->GraphicsMode == GM_COMPATIBLE)
        {
            if (dc->vport2WorldValid && dc->xformWorld2Vport.eM11 < 0)
                desired[1].x = -desired[1].x;
            if (dc->vport2WorldValid && dc->xformWorld2Vport.eM22 < 0)
                desired[1].y = -desired[1].y;
        }
        width = desired[1];
6140 6141 6142 6143 6144 6145 6146 6147 6148
    }

    tm.tmAscent = abs(INTERNAL_YWSTODS(dc, tm.tmAscent));
    tm.tmDescent = abs(INTERNAL_YWSTODS(dc, tm.tmDescent));
    switch( align & (TA_LEFT | TA_RIGHT | TA_CENTER) )
    {
    case TA_LEFT:
        if (align & TA_UPDATECP)
        {
6149
            pt.x = x + width.x;
6150
            pt.y = y + width.y;
6151
            dp_to_lp(dc, &pt, 1);
6152 6153 6154 6155 6156
            MoveToEx(hdc, pt.x, pt.y, NULL);
        }
        break;

    case TA_CENTER:
6157
        x -= width.x / 2;
6158
        y -= width.y / 2;
6159
        break;
6160

6161
    case TA_RIGHT:
6162
        x -= width.x;
6163
        y -= width.y;
6164 6165 6166 6167
        if (align & TA_UPDATECP)
        {
            pt.x = x;
            pt.y = y;
6168
            dp_to_lp(dc, &pt, 1);
6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189
            MoveToEx(hdc, pt.x, pt.y, NULL);
        }
        break;
    }

    switch( align & (TA_TOP | TA_BOTTOM | TA_BASELINE) )
    {
    case TA_TOP:
        y += tm.tmAscent * cosEsc;
        x += tm.tmAscent * sinEsc;
        break;

    case TA_BOTTOM:
        y -= tm.tmDescent * cosEsc;
        x -= tm.tmDescent * sinEsc;
        break;

    case TA_BASELINE:
        break;
    }

6190
    if (dc->backgroundMode != TRANSPARENT)
6191 6192 6193
    {
        if(!((flags & ETO_CLIPPED) && (flags & ETO_OPAQUE)))
        {
6194 6195
            if(!(flags & ETO_OPAQUE) || !lprect ||
               x < rc.left || x + width.x >= rc.right ||
6196 6197
               y - tm.tmAscent < rc.top || y + tm.tmDescent >= rc.bottom)
            {
6198 6199 6200 6201 6202
                RECT text_box;
                text_box.left = x;
                text_box.right = x + width.x;
                text_box.top = y - tm.tmAscent;
                text_box.bottom = y + tm.tmDescent;
6203

6204 6205
                if (flags & ETO_CLIPPED) intersect_rect( &text_box, &text_box, &rc );
                if (!is_rect_empty( &text_box ))
6206
                    physdev->funcs->pExtTextOut( physdev, 0, 0, ETO_OPAQUE, &text_box, NULL, 0, NULL );
6207
            }
6208 6209
        }
    }
6210

6211 6212
    ret = physdev->funcs->pExtTextOut( physdev, x, y, (flags & ~ETO_OPAQUE), &rc,
                                       glyphs ? glyphs : reordered_str, count, (INT*)deltas );
6213

6214 6215 6216 6217 6218 6219 6220 6221
done:
    HeapFree(GetProcessHeap(), 0, deltas);
    if(glyphs != reordered_str)
        HeapFree(GetProcessHeap(), 0, glyphs);
    if(reordered_str != str)
        HeapFree(GetProcessHeap(), 0, reordered_str);

    if (ret && (lf.lfUnderline || lf.lfStrikeOut))
6222 6223 6224
    {
        int underlinePos, strikeoutPos;
        int underlineWidth, strikeoutWidth;
6225
        UINT size = GetOutlineTextMetricsW(hdc, 0, NULL);
6226
        OUTLINETEXTMETRICW* otm = NULL;
6227 6228
        POINT pts[5];
        HPEN hpen = SelectObject(hdc, GetStockObject(NULL_PEN));
6229
        HBRUSH hbrush = CreateSolidBrush(dc->textColor);
6230 6231

        hbrush = SelectObject(hdc, hbrush);
6232

6233
        if(!size)
6234 6235 6236 6237 6238 6239 6240 6241
        {
            underlinePos = 0;
            underlineWidth = tm.tmAscent / 20 + 1;
            strikeoutPos = tm.tmAscent / 2;
            strikeoutWidth = underlineWidth;
        }
        else
        {
6242 6243
            otm = HeapAlloc(GetProcessHeap(), 0, size);
            GetOutlineTextMetricsW(hdc, size, otm);
6244 6245
            underlinePos = abs( INTERNAL_YWSTODS( dc, otm->otmsUnderscorePosition ));
            if (otm->otmsUnderscorePosition < 0) underlinePos = -underlinePos;
6246
            underlineWidth = get_line_width( dc, otm->otmsUnderscoreSize );
6247 6248
            strikeoutPos = abs( INTERNAL_YWSTODS( dc, otm->otmsStrikeoutPosition ));
            if (otm->otmsStrikeoutPosition < 0) strikeoutPos = -strikeoutPos;
6249
            strikeoutWidth = get_line_width( dc, otm->otmsStrikeoutSize );
6250
            HeapFree(GetProcessHeap(), 0, otm);
6251 6252 6253
        }


6254
        if (lf.lfUnderline)
6255
        {
6256 6257 6258 6259
            pts[0].x = x - (underlinePos + underlineWidth / 2) * sinEsc;
            pts[0].y = y - (underlinePos + underlineWidth / 2) * cosEsc;
            pts[1].x = x + width.x - (underlinePos + underlineWidth / 2) * sinEsc;
            pts[1].y = y + width.y - (underlinePos + underlineWidth / 2) * cosEsc;
6260 6261 6262 6263 6264 6265
            pts[2].x = pts[1].x + underlineWidth * sinEsc;
            pts[2].y = pts[1].y + underlineWidth * cosEsc;
            pts[3].x = pts[0].x + underlineWidth * sinEsc;
            pts[3].y = pts[0].y + underlineWidth * cosEsc;
            pts[4].x = pts[0].x;
            pts[4].y = pts[0].y;
6266
            dp_to_lp(dc, pts, 5);
6267 6268
            Polygon(hdc, pts, 5);
        }
6269

6270 6271
        if (lf.lfStrikeOut)
        {
6272 6273 6274 6275
            pts[0].x = x - (strikeoutPos + strikeoutWidth / 2) * sinEsc;
            pts[0].y = y - (strikeoutPos + strikeoutWidth / 2) * cosEsc;
            pts[1].x = x + width.x - (strikeoutPos + strikeoutWidth / 2) * sinEsc;
            pts[1].y = y + width.y - (strikeoutPos + strikeoutWidth / 2) * cosEsc;
6276 6277 6278 6279 6280 6281
            pts[2].x = pts[1].x + strikeoutWidth * sinEsc;
            pts[2].y = pts[1].y + strikeoutWidth * cosEsc;
            pts[3].x = pts[0].x + strikeoutWidth * sinEsc;
            pts[3].y = pts[0].y + strikeoutWidth * cosEsc;
            pts[4].x = pts[0].x;
            pts[4].y = pts[0].y;
6282
            dp_to_lp(dc, pts, 5);
6283
            Polygon(hdc, pts, 5);
6284
        }
6285 6286 6287 6288

        SelectObject(hdc, hpen);
        hbrush = SelectObject(hdc, hbrush);
        DeleteObject(hbrush);
6289
    }
6290

6291 6292
    release_dc_ptr( dc );

6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317
    return ret;
}


/***********************************************************************
 *           TextOutA    (GDI32.@)
 */
BOOL WINAPI TextOutA( HDC hdc, INT x, INT y, LPCSTR str, INT count )
{
    return ExtTextOutA( hdc, x, y, 0, NULL, str, count, NULL );
}


/***********************************************************************
 *           TextOutW    (GDI32.@)
 */
BOOL WINAPI TextOutW(HDC hdc, INT x, INT y, LPCWSTR str, INT count)
{
    return ExtTextOutW( hdc, x, y, 0, NULL, str, count, NULL );
}


/***********************************************************************
 *		PolyTextOutA (GDI32.@)
 *
6318
 * See PolyTextOutW.
6319
 */
6320
BOOL WINAPI PolyTextOutA( HDC hdc, const POLYTEXTA *pptxt, INT cStrings )
6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333
{
    for (; cStrings>0; cStrings--, pptxt++)
        if (!ExtTextOutA( hdc, pptxt->x, pptxt->y, pptxt->uiFlags, &pptxt->rcl, pptxt->lpstr, pptxt->n, pptxt->pdx ))
            return FALSE;
    return TRUE;
}



/***********************************************************************
 *		PolyTextOutW (GDI32.@)
 *
 * Draw several Strings
6334 6335 6336 6337
 *
 * RETURNS
 *  TRUE:  Success.
 *  FALSE: Failure.
6338
 */
6339
BOOL WINAPI PolyTextOutW( HDC hdc, const POLYTEXTW *pptxt, INT cStrings )
6340 6341 6342 6343 6344 6345 6346 6347
{
    for (; cStrings>0; cStrings--, pptxt++)
        if (!ExtTextOutW( hdc, pptxt->x, pptxt->y, pptxt->uiFlags, &pptxt->rcl, pptxt->lpstr, pptxt->n, pptxt->pdx ))
            return FALSE;
    return TRUE;
}


Alexandre Julliard's avatar
Alexandre Julliard committed
6348
/***********************************************************************
6349
 *           SetMapperFlags    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
6350
 */
6351
DWORD WINAPI SetMapperFlags( HDC hdc, DWORD flags )
Alexandre Julliard's avatar
Alexandre Julliard committed
6352
{
6353 6354 6355 6356
    DC *dc = get_dc_ptr( hdc );
    DWORD ret = GDI_ERROR;

    if (dc)
6357
    {
6358 6359 6360 6361 6362 6363 6364 6365
        PHYSDEV physdev = GET_DC_PHYSDEV( dc, pSetMapperFlags );
        flags = physdev->funcs->pSetMapperFlags( physdev, flags );
        if (flags != GDI_ERROR)
        {
            ret = dc->mapperFlags;
            dc->mapperFlags = flags;
        }
        release_dc_ptr( dc );
6366
    }
6367
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
6368 6369
}

6370
/***********************************************************************
6371
 *          GetAspectRatioFilterEx  (GDI32.@)
6372
 */
6373
BOOL WINAPI GetAspectRatioFilterEx( HDC hdc, LPSIZE pAspectRatio )
6374
{
6375
  FIXME("(%p, %p): -- Empty Stub !\n", hdc, pAspectRatio);
6376 6377
  return FALSE;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
6378

Alexandre Julliard's avatar
Alexandre Julliard committed
6379 6380

/***********************************************************************
6381
 *           GetCharABCWidthsA   (GDI32.@)
6382 6383
 *
 * See GetCharABCWidthsW.
Alexandre Julliard's avatar
Alexandre Julliard committed
6384
 */
6385 6386
BOOL WINAPI GetCharABCWidthsA(HDC hdc, UINT firstChar, UINT lastChar,
                                  LPABC abc )
Alexandre Julliard's avatar
Alexandre Julliard committed
6387
{
6388
    INT i, wlen;
6389 6390 6391 6392
    LPSTR str;
    LPWSTR wstr;
    BOOL ret = TRUE;

6393
    str = FONT_GetCharsByRangeA(hdc, firstChar, lastChar, &i);
6394 6395
    if (str == NULL)
        return FALSE;
6396

6397
    wstr = FONT_mbtowc(hdc, str, i, &wlen, NULL);
6398 6399 6400 6401 6402
    if (wstr == NULL)
    {
        HeapFree(GetProcessHeap(), 0, str);
        return FALSE;
    }
6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417

    for(i = 0; i < wlen; i++)
    {
	if(!GetCharABCWidthsW(hdc, wstr[i], wstr[i], abc))
	{
	    ret = FALSE;
	    break;
	}
	abc++;
    }

    HeapFree(GetProcessHeap(), 0, str);
    HeapFree(GetProcessHeap(), 0, wstr);

    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
6418 6419 6420
}


Alexandre Julliard's avatar
Alexandre Julliard committed
6421
/******************************************************************************
Jon Griffiths's avatar
Jon Griffiths committed
6422 6423 6424
 * GetCharABCWidthsW [GDI32.@]
 *
 * Retrieves widths of characters in range.
Alexandre Julliard's avatar
Alexandre Julliard committed
6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437
 *
 * PARAMS
 *    hdc       [I] Handle of device context
 *    firstChar [I] First character in range to query
 *    lastChar  [I] Last character in range to query
 *    abc       [O] Address of character-width structure
 *
 * NOTES
 *    Only works with TrueType fonts
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
Alexandre Julliard's avatar
Alexandre Julliard committed
6438
 */
6439 6440
BOOL WINAPI GetCharABCWidthsW( HDC hdc, UINT firstChar, UINT lastChar,
                                   LPABC abc )
Alexandre Julliard's avatar
Alexandre Julliard committed
6441
{
6442
    DC *dc = get_dc_ptr(hdc);
6443
    PHYSDEV dev;
6444
    unsigned int i;
6445
    BOOL ret;
6446
    TEXTMETRICW tm;
6447

6448 6449
    if (!dc) return FALSE;

6450 6451
    if (!abc)
    {
6452
        release_dc_ptr( dc );
6453 6454 6455
        return FALSE;
    }

6456
    /* unlike GetCharABCWidthsFloatW, this one is supposed to fail on non-scalable fonts */
6457
    dev = GET_DC_PHYSDEV( dc, pGetTextMetrics );
6458
    if (!dev->funcs->pGetTextMetrics( dev, &tm ) || !(tm.tmPitchAndFamily & TMPF_VECTOR))
6459 6460 6461 6462 6463
    {
        release_dc_ptr( dc );
        return FALSE;
    }

6464 6465
    dev = GET_DC_PHYSDEV( dc, pGetCharABCWidths );
    ret = dev->funcs->pGetCharABCWidths( dev, firstChar, lastChar, abc );
6466 6467 6468 6469
    if (ret)
    {
        /* convert device units to logical */
        for( i = firstChar; i <= lastChar; i++, abc++ ) {
6470 6471 6472
            abc->abcA = width_to_LP(dc, abc->abcA);
            abc->abcB = width_to_LP(dc, abc->abcB);
            abc->abcC = width_to_LP(dc, abc->abcC);
6473 6474 6475
	}
    }

6476
    release_dc_ptr( dc );
6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502
    return ret;
}


/******************************************************************************
 * GetCharABCWidthsI [GDI32.@]
 *
 * Retrieves widths of characters in range.
 *
 * PARAMS
 *    hdc       [I] Handle of device context
 *    firstChar [I] First glyphs in range to query
 *    count     [I] Last glyphs in range to query
 *    pgi       [i] Array of glyphs to query
 *    abc       [O] Address of character-width structure
 *
 * NOTES
 *    Only works with TrueType fonts
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
 */
BOOL WINAPI GetCharABCWidthsI( HDC hdc, UINT firstChar, UINT count,
                               LPWORD pgi, LPABC abc)
{
6503
    DC *dc = get_dc_ptr(hdc);
6504
    PHYSDEV dev;
6505
    unsigned int i;
6506
    BOOL ret;
6507 6508 6509

    if (!dc) return FALSE;

6510 6511
    if (!abc)
    {
6512
        release_dc_ptr( dc );
6513 6514 6515
        return FALSE;
    }

6516 6517
    dev = GET_DC_PHYSDEV( dc, pGetCharABCWidthsI );
    ret = dev->funcs->pGetCharABCWidthsI( dev, firstChar, count, pgi, abc );
6518 6519 6520
    if (ret)
    {
        /* convert device units to logical */
6521
        for( i = 0; i < count; i++, abc++ ) {
6522 6523 6524
            abc->abcA = width_to_LP(dc, abc->abcA);
            abc->abcB = width_to_LP(dc, abc->abcB);
            abc->abcC = width_to_LP(dc, abc->abcC);
6525
	}
6526
    }
6527

6528
    release_dc_ptr( dc );
6529
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
6530 6531
}

Alexandre Julliard's avatar
Alexandre Julliard committed
6532

Alexandre Julliard's avatar
Alexandre Julliard committed
6533
/***********************************************************************
6534
 *           GetGlyphOutlineA    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
6535
 */
6536 6537
DWORD WINAPI GetGlyphOutlineA( HDC hdc, UINT uChar, UINT fuFormat,
                                 LPGLYPHMETRICS lpgm, DWORD cbBuffer,
Alexandre Julliard's avatar
Alexandre Julliard committed
6538
                                 LPVOID lpBuffer, const MAT2 *lpmat2 )
Alexandre Julliard's avatar
Alexandre Julliard committed
6539
{
6540 6541
    if (!lpmat2) return GDI_ERROR;

6542
    if(!(fuFormat & GGO_GLYPH_INDEX)) {
6543
        UINT cp;
6544 6545
        int len;
        char mbchs[2];
6546
        WCHAR wChar;
6547 6548 6549

        cp = GdiGetCodePage(hdc);
        if (IsDBCSLeadByteEx(cp, uChar >> 8)) {
6550 6551 6552 6553 6554 6555 6556
            len = 2;
            mbchs[0] = (uChar & 0xff00) >> 8;
            mbchs[1] = (uChar & 0xff);
        } else {
            len = 1;
            mbchs[0] = (uChar & 0xff);
        }
6557 6558 6559
        wChar = 0;
        MultiByteToWideChar(cp, 0, mbchs, len, &wChar, 1);
        uChar = wChar;
6560 6561 6562 6563
    }

    return GetGlyphOutlineW(hdc, uChar, fuFormat, lpgm, cbBuffer, lpBuffer,
                            lpmat2);
Alexandre Julliard's avatar
Alexandre Julliard committed
6564 6565
}

Alexandre Julliard's avatar
Alexandre Julliard committed
6566
/***********************************************************************
6567
 *           GetGlyphOutlineW    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
6568
 */
6569 6570
DWORD WINAPI GetGlyphOutlineW( HDC hdc, UINT uChar, UINT fuFormat,
                                 LPGLYPHMETRICS lpgm, DWORD cbBuffer,
Alexandre Julliard's avatar
Alexandre Julliard committed
6571
                                 LPVOID lpBuffer, const MAT2 *lpmat2 )
Alexandre Julliard's avatar
Alexandre Julliard committed
6572
{
6573
    DC *dc;
6574
    DWORD ret;
6575
    PHYSDEV dev;
6576

6577
    TRACE("(%p, %04x, %04x, %p, %d, %p, %p)\n",
Alexandre Julliard's avatar
Alexandre Julliard committed
6578
	  hdc, uChar, fuFormat, lpgm, cbBuffer, lpBuffer, lpmat2 );
6579

6580 6581 6582
    if (!lpmat2) return GDI_ERROR;

    dc = get_dc_ptr(hdc);
6583 6584
    if(!dc) return GDI_ERROR;

6585 6586
    uChar &= 0xffff;

6587 6588
    dev = GET_DC_PHYSDEV( dc, pGetGlyphOutline );
    ret = dev->funcs->pGetGlyphOutline( dev, uChar, fuFormat, lpgm, cbBuffer, lpBuffer, lpmat2 );
6589
    release_dc_ptr( dc );
6590
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
6591
}
Alexandre Julliard's avatar
Alexandre Julliard committed
6592

Alexandre Julliard's avatar
Alexandre Julliard committed
6593

Alexandre Julliard's avatar
Alexandre Julliard committed
6594
/***********************************************************************
6595
 *           CreateScalableFontResourceA   (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
6596
 */
6597
BOOL WINAPI CreateScalableFontResourceA( DWORD fHidden,
Alexandre Julliard's avatar
Alexandre Julliard committed
6598 6599 6600
                                             LPCSTR lpszResourceFile,
                                             LPCSTR lpszFontFile,
                                             LPCSTR lpszCurrentPath )
Alexandre Julliard's avatar
Alexandre Julliard committed
6601
{
6602 6603 6604 6605 6606
    LPWSTR lpszResourceFileW = NULL;
    LPWSTR lpszFontFileW = NULL;
    LPWSTR lpszCurrentPathW = NULL;
    int len;
    BOOL ret;
6607

6608 6609 6610 6611 6612 6613
    if (lpszResourceFile)
    {
        len = MultiByteToWideChar(CP_ACP, 0, lpszResourceFile, -1, NULL, 0);
        lpszResourceFileW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszResourceFile, -1, lpszResourceFileW, len);
    }
6614

6615 6616 6617 6618 6619
    if (lpszFontFile)
    {
        len = MultiByteToWideChar(CP_ACP, 0, lpszFontFile, -1, NULL, 0);
        lpszFontFileW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszFontFile, -1, lpszFontFileW, len);
6620
    }
6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636

    if (lpszCurrentPath)
    {
        len = MultiByteToWideChar(CP_ACP, 0, lpszCurrentPath, -1, NULL, 0);
        lpszCurrentPathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszCurrentPath, -1, lpszCurrentPathW, len);
    }

    ret = CreateScalableFontResourceW(fHidden, lpszResourceFileW,
            lpszFontFileW, lpszCurrentPathW);

    HeapFree(GetProcessHeap(), 0, lpszResourceFileW);
    HeapFree(GetProcessHeap(), 0, lpszFontFileW);
    HeapFree(GetProcessHeap(), 0, lpszCurrentPathW);

    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
6637 6638
}

6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 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 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822
#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 <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>

#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;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
6823
/***********************************************************************
6824
 *           CreateScalableFontResourceW   (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
6825
 */
6826 6827 6828
BOOL WINAPI CreateScalableFontResourceW( DWORD hidden, LPCWSTR resource_file,
                                         LPCWSTR font_file, LPCWSTR font_path )
{
6829 6830 6831 6832
    struct fontdir fontdir = { 0 };
    struct gdi_font *font = NULL;
    WCHAR path[MAX_PATH];

6833 6834 6835
    TRACE("(%d, %s, %s, %s)\n", hidden, debugstr_w(resource_file),
          debugstr_w(font_file), debugstr_w(font_path) );

6836
    if (!font_funcs) return FALSE;
6837 6838 6839 6840

    if (!font_file) goto done;
    if (font_path && font_path[0])
    {
6841
        int len = lstrlenW( font_path ) + lstrlenW( font_file ) + 2;
6842 6843
        if (len > MAX_PATH) goto done;
        lstrcpynW( path, font_path, MAX_PATH );
6844
        lstrcatW( path, L"\\" );
6845
        lstrcatW( path, font_file );
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
    }
    else if (!GetFullPathNameW( font_file, MAX_PATH, path, NULL )) goto done;

    if (!(font = alloc_gdi_font( path, NULL, 0 ))) goto done;
    font->lf.lfHeight = 100;
    if (!font_funcs->load_font( font )) goto done;
    if (!font_funcs->set_outline_text_metrics( font )) goto done;

    if (!(font->otm.otmTextMetrics.tmPitchAndFamily & TMPF_TRUETYPE)) goto done;

    fontdir.num_of_resources  = 1;
    fontdir.res_id            = 0;
    fontdir.dfVersion         = 0x200;
    fontdir.dfSize            = sizeof(fontdir);
    strcpy( fontdir.dfCopyright, "Wine fontdir" );
    fontdir.dfType            = 0x4003;  /* 0x0080 set if private */
    fontdir.dfPoints          = font->otm.otmEMSquare;
    fontdir.dfVertRes         = 72;
    fontdir.dfHorizRes        = 72;
    fontdir.dfAscent          = font->otm.otmTextMetrics.tmAscent;
    fontdir.dfInternalLeading = font->otm.otmTextMetrics.tmInternalLeading;
    fontdir.dfExternalLeading = font->otm.otmTextMetrics.tmExternalLeading;
    fontdir.dfItalic          = font->otm.otmTextMetrics.tmItalic;
    fontdir.dfUnderline       = font->otm.otmTextMetrics.tmUnderlined;
    fontdir.dfStrikeOut       = font->otm.otmTextMetrics.tmStruckOut;
    fontdir.dfWeight          = font->otm.otmTextMetrics.tmWeight;
    fontdir.dfCharSet         = font->otm.otmTextMetrics.tmCharSet;
    fontdir.dfPixWidth        = 0;
    fontdir.dfPixHeight       = font->otm.otmTextMetrics.tmHeight;
    fontdir.dfPitchAndFamily  = font->otm.otmTextMetrics.tmPitchAndFamily;
    fontdir.dfAvgWidth        = font->otm.otmTextMetrics.tmAveCharWidth;
    fontdir.dfMaxWidth        = font->otm.otmTextMetrics.tmMaxCharWidth;
    fontdir.dfFirstChar       = font->otm.otmTextMetrics.tmFirstChar;
    fontdir.dfLastChar        = font->otm.otmTextMetrics.tmLastChar;
    fontdir.dfDefaultChar     = font->otm.otmTextMetrics.tmDefaultChar;
    fontdir.dfBreakChar       = font->otm.otmTextMetrics.tmBreakChar;
    fontdir.dfWidthBytes      = 0;
    fontdir.dfDevice          = 0;
    fontdir.dfFace            = FIELD_OFFSET( struct fontdir, szFaceName );
    fontdir.dfReserved        = 0;
    WideCharToMultiByte( CP_ACP, 0, (WCHAR *)font->otm.otmpFamilyName, -1,
                         fontdir.szFaceName, LF_FACESIZE, NULL, NULL );
6888
    free_gdi_font( font );
6889 6890 6891 6892 6893 6894 6895 6896

    if (hidden) fontdir.dfType |= 0x80;
    return create_fot( resource_file, font_file, &fontdir );

done:
    if (font) free_gdi_font( font );
    SetLastError( ERROR_INVALID_PARAMETER );
    return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
6897 6898
}

Alexandre Julliard's avatar
Alexandre Julliard committed
6899
/*************************************************************************
6900
 *             GetKerningPairsA   (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
6901
 */
6902
DWORD WINAPI GetKerningPairsA( HDC hDC, DWORD cPairs,
6903
                               LPKERNINGPAIR kern_pairA )
Alexandre Julliard's avatar
Alexandre Julliard committed
6904
{
6905
    UINT cp;
6906 6907 6908 6909 6910 6911 6912 6913 6914 6915
    CPINFO cpi;
    DWORD i, total_kern_pairs, kern_pairs_copied = 0;
    KERNINGPAIR *kern_pairW;

    if (!cPairs && kern_pairA)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

6916 6917
    cp = GdiGetCodePage(hDC);

6918 6919 6920 6921
    /* GetCPInfo() will fail on CP_SYMBOL, and WideCharToMultiByte is supposed
     * to fail on an invalid character for CP_SYMBOL.
     */
    cpi.DefaultChar[0] = 0;
6922
    if (cp != CP_SYMBOL && !GetCPInfo(cp, &cpi))
6923
    {
6924
        FIXME("Can't find codepage %u info\n", cp);
6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937
        return 0;
    }

    total_kern_pairs = GetKerningPairsW(hDC, 0, NULL);
    if (!total_kern_pairs) return 0;

    kern_pairW = HeapAlloc(GetProcessHeap(), 0, total_kern_pairs * sizeof(*kern_pairW));
    GetKerningPairsW(hDC, total_kern_pairs, kern_pairW);

    for (i = 0; i < total_kern_pairs; i++)
    {
        char first, second;

6938
        if (!WideCharToMultiByte(cp, 0, &kern_pairW[i].wFirst, 1, &first, 1, NULL, NULL))
6939 6940
            continue;

6941
        if (!WideCharToMultiByte(cp, 0, &kern_pairW[i].wSecond, 1, &second, 1, NULL, NULL))
6942
            continue;
Alexandre Julliard's avatar
Alexandre Julliard committed
6943

6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962
        if (first == cpi.DefaultChar[0] || second == cpi.DefaultChar[0])
            continue;

        if (kern_pairA)
        {
            if (kern_pairs_copied >= cPairs) break;

            kern_pairA->wFirst = (BYTE)first;
            kern_pairA->wSecond = (BYTE)second;
            kern_pairA->iKernAmount = kern_pairW[i].iKernAmount;
            kern_pairA++;
        }
        kern_pairs_copied++;
    }

    HeapFree(GetProcessHeap(), 0, kern_pairW);

    return kern_pairs_copied;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
6963 6964

/*************************************************************************
6965
 *             GetKerningPairsW   (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
6966
 */
6967 6968
DWORD WINAPI GetKerningPairsW( HDC hDC, DWORD cPairs,
                                 LPKERNINGPAIR lpKerningPairs )
Alexandre Julliard's avatar
Alexandre Julliard committed
6969
{
6970
    DC *dc;
6971 6972
    DWORD ret;
    PHYSDEV dev;
6973

6974
    TRACE("(%p,%d,%p)\n", hDC, cPairs, lpKerningPairs);
6975

6976 6977 6978 6979 6980 6981
    if (!cPairs && lpKerningPairs)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

6982
    dc = get_dc_ptr(hDC);
6983 6984
    if (!dc) return 0;

6985 6986
    dev = GET_DC_PHYSDEV( dc, pGetKerningPairs );
    ret = dev->funcs->pGetKerningPairs( dev, cPairs, lpKerningPairs );
6987
    release_dc_ptr( dc );
6988
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
6989
}
Alexandre Julliard's avatar
Alexandre Julliard committed
6990

Alexandre Julliard's avatar
Alexandre Julliard committed
6991
/*************************************************************************
6992
 * TranslateCharsetInfo [GDI32.@]
6993 6994
 *
 * Fills a CHARSETINFO structure for a character set, code page, or
6995
 * font. This allows making the correspondence between different labels
6996
 * (character set, Windows, ANSI, and OEM codepages, and Unicode ranges)
6997 6998 6999 7000 7001 7002 7003 7004 7005
 * of the same encoding.
 *
 * Only one codepage will be set in lpCs->fs. If TCI_SRCFONTSIG is used,
 * only one codepage should be set in *lpSrc.
 *
 * RETURNS
 *   TRUE on success, FALSE on failure.
 *
 */
7006
BOOL WINAPI TranslateCharsetInfo(
7007
  LPDWORD lpSrc, /* [in]
7008 7009 7010 7011
       if flags == TCI_SRCFONTSIG: pointer to fsCsb of a FONTSIGNATURE
       if flags == TCI_SRCCHARSET: a character set value
       if flags == TCI_SRCCODEPAGE: a code page value
		 */
7012
  LPCHARSETINFO lpCs, /* [out] structure to receive charset information */
Jon Griffiths's avatar
Jon Griffiths committed
7013 7014
  DWORD flags /* [in] determines interpretation of lpSrc */)
{
7015 7016 7017
    int index = 0;
    switch (flags) {
    case TCI_SRCFONTSIG:
7018
      while (index < MAXTCIINDEX && !(*lpSrc>>index & 0x0001)) index++;
7019 7020
      break;
    case TCI_SRCCODEPAGE:
7021
      while (index < MAXTCIINDEX && PtrToUlong(lpSrc) != FONT_tci[index].ciACP) index++;
7022 7023
      break;
    case TCI_SRCCHARSET:
7024
      while (index < MAXTCIINDEX && PtrToUlong(lpSrc) != FONT_tci[index].ciCharset) index++;
7025 7026 7027 7028 7029
      break;
    default:
      return FALSE;
    }
    if (index >= MAXTCIINDEX || FONT_tci[index].ciCharset == DEFAULT_CHARSET) return FALSE;
7030
    *lpCs = FONT_tci[index];
Alexandre Julliard's avatar
Alexandre Julliard committed
7031 7032 7033
    return TRUE;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
7034
/*************************************************************************
7035
 *             GetFontLanguageInfo   (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
7036
 */
7037 7038 7039
DWORD WINAPI GetFontLanguageInfo(HDC hdc)
{
	FONTSIGNATURE fontsig;
7040
	static const DWORD GCP_DBCS_MASK=FS_JISJAPAN|FS_CHINESESIMP|FS_WANSUNG|FS_CHINESETRAD|FS_JOHAB,
7041 7042
		GCP_DIACRITIC_MASK=0x00000000,
		FLI_GLYPHS_MASK=0x00000000,
7043
		GCP_GLYPHSHAPE_MASK=FS_ARABIC,
7044 7045
		GCP_KASHIDA_MASK=0x00000000,
		GCP_LIGATE_MASK=0x00000000,
7046
		GCP_REORDER_MASK=FS_HEBREW|FS_ARABIC;
7047

7048
	DWORD result=0;
7049

7050 7051 7052 7053 7054
	GetTextCharsetInfo( hdc, &fontsig, 0 );
	/* We detect each flag we return using a bitmask on the Codepage Bitfields */

	if( (fontsig.fsCsb[0]&GCP_DBCS_MASK)!=0 )
		result|=GCP_DBCS;
7055

7056 7057
	if( (fontsig.fsCsb[0]&GCP_DIACRITIC_MASK)!=0 )
		result|=GCP_DIACRITIC;
7058

7059 7060
	if( (fontsig.fsCsb[0]&FLI_GLYPHS_MASK)!=0 )
		result|=FLI_GLYPHS;
7061

7062 7063
	if( (fontsig.fsCsb[0]&GCP_GLYPHSHAPE_MASK)!=0 )
		result|=GCP_GLYPHSHAPE;
7064

7065 7066
	if( (fontsig.fsCsb[0]&GCP_KASHIDA_MASK)!=0 )
		result|=GCP_KASHIDA;
7067

7068 7069 7070
	if( (fontsig.fsCsb[0]&GCP_LIGATE_MASK)!=0 )
		result|=GCP_LIGATE;

7071
	if( GetKerningPairsW( hdc, 0, NULL ) )
7072
		result|=GCP_USEKERNING;
7073

7074 7075 7076 7077
        /* this might need a test for a HEBREW- or ARABIC_CHARSET as well */
        if( GetTextAlign( hdc) & TA_RTLREADING )
            if( (fontsig.fsCsb[0]&GCP_REORDER_MASK)!=0 )
                    result|=GCP_REORDER;
7078

7079
	return result;
Alexandre Julliard's avatar
Alexandre Julliard committed
7080 7081
}

Alexandre Julliard's avatar
Alexandre Julliard committed
7082

Alexandre Julliard's avatar
Alexandre Julliard committed
7083
/*************************************************************************
Jon Griffiths's avatar
Jon Griffiths committed
7084 7085 7086
 * GetFontData [GDI32.@]
 *
 * Retrieve data for TrueType font.
Alexandre Julliard's avatar
Alexandre Julliard committed
7087 7088 7089
 *
 * RETURNS
 *
7090
 * success: Number of bytes returned
Alexandre Julliard's avatar
Alexandre Julliard committed
7091 7092 7093 7094
 * failure: GDI_ERROR
 *
 * NOTES
 *
7095
 * Calls SetLastError()
Alexandre Julliard's avatar
Alexandre Julliard committed
7096 7097
 *
 */
7098
DWORD WINAPI GetFontData(HDC hdc, DWORD table, DWORD offset,
Alexandre Julliard's avatar
Alexandre Julliard committed
7099 7100
    LPVOID buffer, DWORD length)
{
7101
    DC *dc = get_dc_ptr(hdc);
7102 7103
    PHYSDEV dev;
    DWORD ret;
Huw D M Davies's avatar
Huw D M Davies committed
7104 7105 7106

    if(!dc) return GDI_ERROR;

7107 7108
    dev = GET_DC_PHYSDEV( dc, pGetFontData );
    ret = dev->funcs->pGetFontData( dev, table, offset, buffer, length );
7109
    release_dc_ptr( dc );
Huw D M Davies's avatar
Huw D M Davies committed
7110
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
7111
}
Alexandre Julliard's avatar
Alexandre Julliard committed
7112

7113 7114 7115 7116 7117 7118 7119 7120 7121 7122
/*************************************************************************
 * GetGlyphIndicesA [GDI32.@]
 */
DWORD WINAPI GetGlyphIndicesA(HDC hdc, LPCSTR lpstr, INT count,
			      LPWORD pgi, DWORD flags)
{
    DWORD ret;
    WCHAR *lpstrW;
    INT countW;

7123
    TRACE("(%p, %s, %d, %p, 0x%x)\n",
7124
          hdc, debugstr_an(lpstr, count), count, pgi, flags);
7125

7126
    lpstrW = FONT_mbtowc(hdc, lpstr, count, &countW, NULL);
7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138
    ret = GetGlyphIndicesW(hdc, lpstrW, countW, pgi, flags);
    HeapFree(GetProcessHeap(), 0, lpstrW);

    return ret;
}

/*************************************************************************
 * GetGlyphIndicesW [GDI32.@]
 */
DWORD WINAPI GetGlyphIndicesW(HDC hdc, LPCWSTR lpstr, INT count,
			      LPWORD pgi, DWORD flags)
{
7139
    DC *dc = get_dc_ptr(hdc);
7140 7141
    PHYSDEV dev;
    DWORD ret;
7142

7143
    TRACE("(%p, %s, %d, %p, 0x%x)\n",
7144
          hdc, debugstr_wn(lpstr, count), count, pgi, flags);
7145 7146 7147

    if(!dc) return GDI_ERROR;

7148 7149
    dev = GET_DC_PHYSDEV( dc, pGetGlyphIndices );
    ret = dev->funcs->pGetGlyphIndices( dev, lpstr, count, pgi, flags );
7150
    release_dc_ptr( dc );
7151 7152 7153
    return ret;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
7154
/*************************************************************************
7155
 * GetCharacterPlacementA [GDI32.@]
7156
 *
7157 7158
 * See GetCharacterPlacementW.
 *
7159 7160
 * NOTES:
 *  the web browser control of ie4 calls this with dwFlags=0
Alexandre Julliard's avatar
Alexandre Julliard committed
7161 7162
 */
DWORD WINAPI
7163 7164
GetCharacterPlacementA(HDC hdc, LPCSTR lpString, INT uCount,
			 INT nMaxExtent, GCP_RESULTSA *lpResults,
Alexandre Julliard's avatar
Alexandre Julliard committed
7165 7166
			 DWORD dwFlags)
{
7167
    WCHAR *lpStringW;
7168
    INT uCountW;
7169 7170
    GCP_RESULTSW resultsW;
    DWORD ret;
7171
    UINT font_cp;
7172

7173
    TRACE("%s, %d, %d, 0x%08x\n",
7174
          debugstr_an(lpString, uCount), uCount, nMaxExtent, dwFlags);
7175

7176 7177 7178 7179 7180 7181 7182 7183 7184
    lpStringW = FONT_mbtowc(hdc, lpString, uCount, &uCountW, &font_cp);

    if (!lpResults)
    {
        ret = GetCharacterPlacementW(hdc, lpStringW, uCountW, nMaxExtent, NULL, dwFlags);
        HeapFree(GetProcessHeap(), 0, lpStringW);
        return ret;
    }

7185 7186
    /* both structs are equal in size */
    memcpy(&resultsW, lpResults, sizeof(resultsW));
7187

7188 7189
    if(lpResults->lpOutString)
        resultsW.lpOutString = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR)*uCountW);
7190

7191 7192
    ret = GetCharacterPlacementW(hdc, lpStringW, uCountW, nMaxExtent, &resultsW, dwFlags);

7193 7194 7195
    lpResults->nGlyphs = resultsW.nGlyphs;
    lpResults->nMaxFit = resultsW.nMaxFit;

7196
    if(lpResults->lpOutString) {
7197
        WideCharToMultiByte(font_cp, 0, resultsW.lpOutString, uCountW,
7198
                            lpResults->lpOutString, uCount, NULL, NULL );
7199
    }
7200

7201 7202
    HeapFree(GetProcessHeap(), 0, lpStringW);
    HeapFree(GetProcessHeap(), 0, resultsW.lpOutString);
7203 7204

    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
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
static int kern_pair(const KERNINGPAIR *kern, int count, WCHAR c1, WCHAR c2)
{
    int i;

    for (i = 0; i < count; i++)
    {
        if (kern[i].wFirst == c1 && kern[i].wSecond == c2)
            return kern[i].iKernAmount;
    }

    return 0;
}

static int *kern_string(HDC hdc, const WCHAR *str, int len, int *kern_total)
{
    int i, count;
    KERNINGPAIR *kern = NULL;
    int *ret;

    *kern_total = 0;

    ret = heap_alloc(len * sizeof(*ret));
    if (!ret) return NULL;

    count = GetKerningPairsW(hdc, 0, NULL);
    if (count)
    {
        kern = heap_alloc(count * sizeof(*kern));
        if (!kern)
        {
            heap_free(ret);
            return NULL;
        }

        GetKerningPairsW(hdc, count, kern);
    }

    for (i = 0; i < len - 1; i++)
    {
        ret[i] = kern_pair(kern, count, str[i], str[i + 1]);
        *kern_total += ret[i];
    }

    ret[len - 1] = 0; /* no kerning for last element */

    heap_free(kern);
    return ret;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
7256
/*************************************************************************
7257
 * GetCharacterPlacementW [GDI32.@]
7258 7259 7260 7261 7262 7263
 *
 *   Retrieve information about a string. This includes the width, reordering,
 *   Glyphing and so on.
 *
 * RETURNS
 *
Francois Gouget's avatar
Francois Gouget committed
7264
 *   The width and height of the string if successful, 0 if failed.
7265 7266 7267 7268
 *
 * BUGS
 *
 *   All flags except GCP_REORDER are not yet implemented.
Austin English's avatar
Austin English committed
7269
 *   Reordering is not 100% compliant to the Windows BiDi method.
7270
 *   Caret positioning is not yet implemented for BiDi.
7271 7272
 *   Classes are not yet implemented.
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
7273 7274
 */
DWORD WINAPI
7275
GetCharacterPlacementW(
Andrew Talbot's avatar
Andrew Talbot committed
7276 7277 7278 7279 7280 7281 7282
        HDC hdc,                    /* [in] Device context for which the rendering is to be done */
        LPCWSTR lpString,           /* [in] The string for which information is to be returned */
        INT uCount,                 /* [in] Number of WORDS in string. */
        INT nMaxExtent,             /* [in] Maximum extent the string is to take (in HDC logical units) */
        GCP_RESULTSW *lpResults,    /* [in/out] A pointer to a GCP_RESULTSW struct */
        DWORD dwFlags               /* [in] Flags specifying how to process the string */
        )
Alexandre Julliard's avatar
Alexandre Julliard committed
7283
{
7284 7285
    DWORD ret=0;
    SIZE size;
7286
    UINT i, nSet;
7287
    int *kern = NULL, kern_total = 0;
7288

7289
    TRACE("%s, %d, %d, 0x%08x\n",
7290
          debugstr_wn(lpString, uCount), uCount, nMaxExtent, dwFlags);
7291

7292 7293 7294
    if (!uCount)
        return 0;

7295 7296 7297
    if (!lpResults)
        return GetTextExtentPoint32W(hdc, lpString, uCount, &size) ? MAKELONG(size.cx, size.cy) : 0;

7298 7299
    TRACE("lStructSize=%d, lpOutString=%p, lpOrder=%p, lpDx=%p, lpCaretPos=%p\n"
          "lpClass=%p, lpGlyphs=%p, nGlyphs=%u, nMaxFit=%d\n",
Andrew Talbot's avatar
Andrew Talbot committed
7300 7301 7302 7303
          lpResults->lStructSize, lpResults->lpOutString, lpResults->lpOrder,
          lpResults->lpDx, lpResults->lpCaretPos, lpResults->lpClass,
          lpResults->lpGlyphs, lpResults->nGlyphs, lpResults->nMaxFit);

7304
    if (dwFlags & ~(GCP_REORDER | GCP_USEKERNING))
Andrew Talbot's avatar
Andrew Talbot committed
7305
        FIXME("flags 0x%08x ignored\n", dwFlags);
7306
    if (lpResults->lpClass)
Andrew Talbot's avatar
Andrew Talbot committed
7307
        FIXME("classes not implemented\n");
7308 7309
    if (lpResults->lpCaretPos && (dwFlags & GCP_REORDER))
        FIXME("Caret positions for complex scripts not implemented\n");
7310

Andrew Talbot's avatar
Andrew Talbot committed
7311
    nSet = (UINT)uCount;
7312
    if (nSet > lpResults->nGlyphs)
Andrew Talbot's avatar
Andrew Talbot committed
7313
        nSet = lpResults->nGlyphs;
7314

Andrew Talbot's avatar
Andrew Talbot committed
7315 7316
    /* return number of initialized fields */
    lpResults->nGlyphs = nSet;
7317

7318
    if (!(dwFlags & GCP_REORDER))
Andrew Talbot's avatar
Andrew Talbot committed
7319 7320 7321
    {
        /* Treat the case where no special handling was requested in a fastpath way */
        /* copy will do if the GCP_REORDER flag is not set */
7322
        if (lpResults->lpOutString)
Andrew Talbot's avatar
Andrew Talbot committed
7323
            memcpy( lpResults->lpOutString, lpString, nSet * sizeof(WCHAR));
7324

7325
        if (lpResults->lpOrder)
Andrew Talbot's avatar
Andrew Talbot committed
7326
        {
7327
            for (i = 0; i < nSet; i++)
Andrew Talbot's avatar
Andrew Talbot committed
7328 7329 7330 7331 7332 7333 7334 7335 7336
                lpResults->lpOrder[i] = i;
        }
    }
    else
    {
        BIDI_Reorder(NULL, lpString, uCount, dwFlags, WINE_GCPW_FORCE_LTR, lpResults->lpOutString,
                     nSet, lpResults->lpOrder, NULL, NULL );
    }

7337 7338 7339 7340 7341 7342 7343 7344 7345 7346
    if (dwFlags & GCP_USEKERNING)
    {
        kern = kern_string(hdc, lpString, nSet, &kern_total);
        if (!kern)
        {
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            return 0;
        }
    }

Andrew Talbot's avatar
Andrew Talbot committed
7347 7348 7349 7350 7351 7352 7353
    /* FIXME: Will use the placement chars */
    if (lpResults->lpDx)
    {
        int c;
        for (i = 0; i < nSet; i++)
        {
            if (GetCharWidth32W(hdc, lpString[i], lpString[i], &c))
7354 7355 7356 7357 7358
            {
                lpResults->lpDx[i] = c;
                if (dwFlags & GCP_USEKERNING)
                    lpResults->lpDx[i] += kern[i];
            }
Andrew Talbot's avatar
Andrew Talbot committed
7359 7360
        }
    }
7361

7362 7363 7364
    if (lpResults->lpCaretPos && !(dwFlags & GCP_REORDER))
    {
        int pos = 0;
Andrew Talbot's avatar
Andrew Talbot committed
7365

7366
        lpResults->lpCaretPos[0] = 0;
7367 7368 7369 7370 7371 7372 7373 7374
        for (i = 0; i < nSet - 1; i++)
        {
            if (dwFlags & GCP_USEKERNING)
                pos += kern[i];

            if (GetTextExtentPoint32W(hdc, &lpString[i], 1, &size))
                lpResults->lpCaretPos[i + 1] = (pos += size.cx);
        }
7375
    }
Andrew Talbot's avatar
Andrew Talbot committed
7376

7377
    if (lpResults->lpGlyphs)
Andrew Talbot's avatar
Andrew Talbot committed
7378
        GetGlyphIndicesW(hdc, lpString, nSet, lpResults->lpGlyphs, 0);
7379

7380
    if (GetTextExtentPoint32W(hdc, lpString, uCount, &size))
7381 7382 7383
        ret = MAKELONG(size.cx + kern_total, size.cy);

    heap_free(kern);
7384 7385

    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
7386
}
7387 7388

/*************************************************************************
7389
 *      GetCharABCWidthsFloatA [GDI32.@]
7390 7391
 *
 * See GetCharABCWidthsFloatW.
7392
 */
7393
BOOL WINAPI GetCharABCWidthsFloatA( HDC hdc, UINT first, UINT last, LPABCFLOAT abcf )
7394
{
7395
    INT i, wlen;
7396 7397 7398 7399
    LPSTR str;
    LPWSTR wstr;
    BOOL ret = TRUE;

7400
    str = FONT_GetCharsByRangeA(hdc, first, last, &i);
7401 7402
    if (str == NULL)
        return FALSE;
7403

7404
    wstr = FONT_mbtowc( hdc, str, i, &wlen, NULL );
7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419

    for (i = 0; i < wlen; i++)
    {
        if (!GetCharABCWidthsFloatW( hdc, wstr[i], wstr[i], abcf ))
        {
            ret = FALSE;
            break;
        }
        abcf++;
    }

    HeapFree( GetProcessHeap(), 0, str );
    HeapFree( GetProcessHeap(), 0, wstr );

    return ret;
7420 7421 7422
}

/*************************************************************************
7423
 *      GetCharABCWidthsFloatW [GDI32.@]
7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435
 *
 * Retrieves widths of a range of characters.
 *
 * PARAMS
 *    hdc   [I] Handle to device context.
 *    first [I] First character in range to query.
 *    last  [I] Last character in range to query.
 *    abcf  [O] Array of LPABCFLOAT structures.
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
7436
 */
7437
BOOL WINAPI GetCharABCWidthsFloatW( HDC hdc, UINT first, UINT last, LPABCFLOAT abcf )
7438
{
7439
    UINT i;
7440 7441
    ABC *abc;
    PHYSDEV dev;
7442 7443 7444 7445 7446 7447
    BOOL ret = FALSE;
    DC *dc = get_dc_ptr( hdc );

    TRACE("%p, %d, %d, %p\n", hdc, first, last, abcf);

    if (!dc) return FALSE;
7448

7449 7450
    if (!abcf) goto done;
    if (!(abc = HeapAlloc( GetProcessHeap(), 0, (last - first + 1) * sizeof(*abc) ))) goto done;
7451

7452 7453
    dev = GET_DC_PHYSDEV( dc, pGetCharABCWidths );
    ret = dev->funcs->pGetCharABCWidths( dev, first, last, abc );
7454
    if (ret)
7455
    {
7456
        /* convert device units to logical */
7457
        FLOAT scale = fabs( dc->xformVport2World.eM11 );
7458
        for (i = first; i <= last; i++, abcf++)
7459
        {
7460 7461 7462
            abcf->abcfA = abc[i - first].abcA * scale;
            abcf->abcfB = abc[i - first].abcB * scale;
            abcf->abcfC = abc[i - first].abcC * scale;
7463 7464
        }
    }
7465
    HeapFree( GetProcessHeap(), 0, abc );
7466

7467
done:
7468
    release_dc_ptr( dc );
7469
    return ret;
7470 7471 7472
}

/*************************************************************************
7473
 *      GetCharWidthFloatA [GDI32.@]
7474
 */
7475
BOOL WINAPI GetCharWidthFloatA( HDC hdc, UINT first, UINT last, float *buffer )
7476
{
7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495
    WCHAR *wstr;
    int i, wlen;
    char *str;

    if (!(str = FONT_GetCharsByRangeA( hdc, first, last, &i )))
        return FALSE;
    wstr = FONT_mbtowc( hdc, str, i, &wlen, NULL );
    heap_free(str);

    for (i = 0; i < wlen; ++i)
    {
        if (!GetCharWidthFloatW( hdc, wstr[i], wstr[i], &buffer[i] ))
        {
            heap_free(wstr);
            return FALSE;
        }
    }
    heap_free(wstr);
    return TRUE;
7496 7497 7498
}

/*************************************************************************
7499
 *      GetCharWidthFloatW [GDI32.@]
7500
 */
7501
BOOL WINAPI GetCharWidthFloatW( HDC hdc, UINT first, UINT last, float *buffer )
7502
{
7503 7504 7505 7506 7507
    DC *dc = get_dc_ptr( hdc );
    int *ibuffer;
    PHYSDEV dev;
    BOOL ret;
    UINT i;
7508

7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529
    TRACE("dc %p, first %#x, last %#x, buffer %p\n", dc, first, last, buffer);

    if (!dc) return FALSE;

    if (!(ibuffer = heap_alloc( (last - first + 1) * sizeof(int) )))
    {
        release_dc_ptr( dc );
        return FALSE;
    }

    dev = GET_DC_PHYSDEV( dc, pGetCharWidth );
    if ((ret = dev->funcs->pGetCharWidth( dev, first, last, ibuffer )))
    {
        float scale = fabs( dc->xformVport2World.eM11 ) / 16.0f;
        for (i = first; i <= last; ++i)
            buffer[i - first] = ibuffer[i - first] * scale;
    }

    heap_free(ibuffer);
    return ret;
}
7530 7531 7532 7533 7534 7535 7536 7537

/***********************************************************************
 *								       *
 *           Font Resource API					       *
 *								       *
 ***********************************************************************/

/***********************************************************************
7538
 *           AddFontResourceA    (GDI32.@)
7539 7540 7541
 */
INT WINAPI AddFontResourceA( LPCSTR str )
{
7542
    return AddFontResourceExA( str, 0, NULL);
7543 7544 7545
}

/***********************************************************************
7546
 *           AddFontResourceW    (GDI32.@)
7547 7548 7549
 */
INT WINAPI AddFontResourceW( LPCWSTR str )
{
7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568
    return AddFontResourceExW(str, 0, NULL);
}


/***********************************************************************
 *           AddFontResourceExA    (GDI32.@)
 */
INT WINAPI AddFontResourceExA( LPCSTR str, DWORD fl, PVOID pdv )
{
    DWORD len = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
    LPWSTR strW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
    INT ret;

    MultiByteToWideChar(CP_ACP, 0, str, -1, strW, len);
    ret = AddFontResourceExW(strW, fl, pdv);
    HeapFree(GetProcessHeap(), 0, strW);
    return ret;
}

7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587
static BOOL CALLBACK load_enumed_resource(HMODULE hModule, LPCWSTR type, LPWSTR name, LONG_PTR lParam)
{
    HRSRC rsrc = FindResourceW(hModule, name, type);
    HGLOBAL hMem = LoadResource(hModule, rsrc);
    LPVOID *pMem = LockResource(hMem);
    int *num_total = (int *)lParam;
    DWORD num_in_res;

    TRACE("Found resource %s - trying to load\n", wine_dbgstr_w(type));
    if (!AddFontMemResourceEx(pMem, SizeofResource(hModule, rsrc), NULL, &num_in_res))
    {
        ERR("Failed to load PE font resource mod=%p ptr=%p\n", hModule, hMem);
        return FALSE;
    }

    *num_total += num_in_res;
    return TRUE;
}

7588 7589 7590 7591 7592 7593 7594 7595
static void *map_file( const WCHAR *filename, LARGE_INTEGER *size )
{
    HANDLE file, mapping;
    void *ptr;

    file = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
    if (file == INVALID_HANDLE_VALUE) return NULL;

7596 7597 7598 7599 7600 7601
    if (!GetFileSizeEx( file, size ) || size->u.HighPart)
    {
        CloseHandle( file );
        return NULL;
    }

7602 7603
    mapping = CreateFileMappingW( file, NULL, PAGE_READONLY, 0, 0, NULL );
    CloseHandle( file );
7604
    if (!mapping) return NULL;
7605 7606 7607 7608 7609 7610 7611

    ptr = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
    CloseHandle( mapping );

    return ptr;
}

7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637
static void *find_resource( BYTE *ptr, WORD type, DWORD rsrc_off, DWORD size, DWORD *len )
{
    WORD align, type_id, count;
    DWORD res_off;

    if (size < rsrc_off + 10) return NULL;
    align = *(WORD *)(ptr + rsrc_off);
    rsrc_off += 2;
    type_id = *(WORD *)(ptr + rsrc_off);
    while (type_id && type_id != type)
    {
        count = *(WORD *)(ptr + rsrc_off + 2);
        rsrc_off += 8 + count * 12;
        if (size < rsrc_off + 8) return NULL;
        type_id = *(WORD *)(ptr + rsrc_off);
    }
    if (!type_id) return NULL;
    count = *(WORD *)(ptr + rsrc_off + 2);
    if (size < rsrc_off + 8 + count * 12) return NULL;
    res_off = *(WORD *)(ptr + rsrc_off + 8) << align;
    *len = *(WORD *)(ptr + rsrc_off + 10) << align;
    if (size < res_off + *len) return NULL;
    return ptr + res_off;
}

static WCHAR *get_scalable_filename( const WCHAR *res, BOOL *hidden )
7638 7639 7640 7641 7642
{
    LARGE_INTEGER size;
    BYTE *ptr = map_file( res, &size );
    const IMAGE_DOS_HEADER *dos;
    const IMAGE_OS2_HEADER *ne;
7643 7644
    WORD *fontdir;
    char *data;
7645
    WCHAR *name = NULL;
7646
    DWORD len;
7647 7648 7649 7650 7651 7652 7653 7654 7655

    if (!ptr) return NULL;

    if (size.u.LowPart < sizeof( *dos )) goto fail;
    dos = (const IMAGE_DOS_HEADER *)ptr;
    if (dos->e_magic != IMAGE_DOS_SIGNATURE) goto fail;
    if (size.u.LowPart < dos->e_lfanew + sizeof( *ne )) goto fail;
    ne = (const IMAGE_OS2_HEADER *)(ptr + dos->e_lfanew);

7656 7657 7658
    fontdir = find_resource( ptr, 0x8007, dos->e_lfanew + ne->ne_rsrctab, size.u.LowPart, &len );
    if (!fontdir) goto fail;
    *hidden = (fontdir[35] & 0x80) != 0;  /* fontdir->dfType */
7659

7660 7661 7662
    data = find_resource( ptr, 0x80cc, dos->e_lfanew + ne->ne_rsrctab, size.u.LowPart, &len );
    if (!data) goto fail;
    if (!memchr( data, 0, len )) goto fail;
7663

7664
    len = MultiByteToWideChar( CP_ACP, 0, data, -1, NULL, 0 );
7665
    name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
7666
    if (name) MultiByteToWideChar( CP_ACP, 0, data, -1, name, len );
7667 7668 7669 7670 7671 7672

fail:
    UnmapViewOfFile( ptr );
    return name;
}

7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699
static int add_system_font_resource( const WCHAR *file, DWORD flags )
{
    WCHAR path[MAX_PATH];
    int ret;

    /* try in %WINDIR%/fonts, needed for Fotobuch Designer */
    get_fonts_win_dir_path( file, path );
    EnterCriticalSection( &font_cs );
    ret = font_funcs->add_font( path, flags );
    LeaveCriticalSection( &font_cs );
    /* try in datadir/fonts (or builddir/fonts), needed for Magic the Gathering Online */
    if (!ret)
    {
        get_fonts_data_dir_path( file, path );
        EnterCriticalSection( &font_cs );
        ret = font_funcs->add_font( path, flags );
        LeaveCriticalSection( &font_cs );
    }
    return ret;
}

static BOOL remove_system_font_resource( LPCWSTR file, DWORD flags )
{
    WCHAR path[MAX_PATH];
    int ret;

    get_fonts_win_dir_path( file, path );
7700
    if (!(ret = remove_font( path, flags )))
7701 7702
    {
        get_fonts_data_dir_path( file, path );
7703
        ret = remove_font( path, flags );
7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722
    }
    return ret;
}

static int add_font_resource( LPCWSTR file, DWORD flags )
{
    WCHAR path[MAX_PATH];
    int ret = 0;

    if (GetFullPathNameW( file, MAX_PATH, path, NULL ))
    {
        DWORD addfont_flags = ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE;

        if (!(flags & FR_PRIVATE)) addfont_flags |= ADDFONT_ADD_TO_CACHE;
        EnterCriticalSection( &font_cs );
        ret = font_funcs->add_font( path, addfont_flags );
        LeaveCriticalSection( &font_cs );
    }

7723
    if (!ret && !wcschr( file, '\\' ))
7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738
        ret = add_system_font_resource( file, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE );

    return ret;
}

static BOOL remove_font_resource( LPCWSTR file, DWORD flags )
{
    WCHAR path[MAX_PATH];
    BOOL ret = FALSE;

    if (GetFullPathNameW( file, MAX_PATH, path, NULL ))
    {
        DWORD addfont_flags = ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE;

        if (!(flags & FR_PRIVATE)) addfont_flags |= ADDFONT_ADD_TO_CACHE;
7739
        ret = remove_font( path, addfont_flags );
7740 7741
    }

7742
    if (!ret && !wcschr( file, '\\' ))
7743 7744 7745 7746 7747
        ret = remove_system_font_resource( file, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE );

    return ret;
}

7748
static void load_system_bitmap_fonts(void)
7749
{
7750
    static const WCHAR * const fonts[] = { L"FONTS.FON", L"OEMFONT.FON", L"FIXEDFON.FON" };
7751 7752 7753 7754
    HKEY hkey;
    WCHAR data[MAX_PATH];
    DWORD i, dlen, type;

7755
    if (RegOpenKeyW( HKEY_CURRENT_CONFIG, L"Software\\Fonts", &hkey )) return;
7756 7757 7758 7759
    for (i = 0; i < ARRAY_SIZE(fonts); i++)
    {
        dlen = sizeof(data);
        if (!RegQueryValueExW( hkey, fonts[i], 0, &type, (BYTE *)data, &dlen ) && type == REG_SZ)
7760
            add_system_font_resource( data, ADDFONT_ALLOW_BITMAP );
7761 7762 7763 7764
    }
    RegCloseKey( hkey );
}

7765 7766 7767 7768 7769 7770
static void load_directory_fonts( WCHAR *path, UINT flags )
{
    HANDLE handle;
    WIN32_FIND_DATAW data;
    WCHAR *p;

7771
    p = path + lstrlenW(path) - 1;
7772 7773 7774 7775 7776 7777
    TRACE( "loading fonts from %s\n", debugstr_w(path) );
    handle = FindFirstFileW( path, &data );
    if (handle == INVALID_HANDLE_VALUE) return;
    do
    {
        if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
7778
        lstrcpyW( p, data.cFileName );
7779 7780 7781 7782 7783
        font_funcs->add_font( path, flags );
    } while (FindNextFileW( handle, &data ));
    FindClose( handle );
}

7784
static void load_file_system_fonts(void)
7785 7786 7787 7788 7789
{
    WCHAR *ptr, *next, path[MAX_PATH], value[1024];
    DWORD len = ARRAY_SIZE(value);

    /* Windows directory */
7790
    get_fonts_win_dir_path( L"*", path );
7791
    load_directory_fonts( path, 0 );
7792 7793

    /* Wine data directory */
7794
    get_fonts_data_dir_path( L"*", path );
7795
    load_directory_fonts( path, ADDFONT_EXTERNAL_FONT );
7796 7797 7798

    /* custom paths */
    /* @@ Wine registry key: HKCU\Software\Wine\Fonts */
7799
    if (!RegQueryValueExW( wine_fonts_key, L"Path", NULL, NULL, (BYTE *)value, &len ))
7800 7801 7802
    {
        for (ptr = value; ptr; ptr = next)
        {
7803
            if ((next = wcschr( ptr, ';' ))) *next++ = 0;
7804 7805
            if (next && next - ptr < 2) continue;
            lstrcpynW( path, ptr, MAX_PATH - 2 );
7806
            lstrcatW( path, L"\\*" );
7807
            load_directory_fonts( path, ADDFONT_EXTERNAL_FONT );
7808 7809 7810 7811
        }
    }
}

7812 7813
struct external_key
{
7814 7815
    struct list entry;
    WCHAR       value[LF_FULLFACESIZE + 12];
7816 7817
};

7818
static void update_external_font_keys(void)
7819
{
7820 7821 7822 7823 7824 7825 7826 7827 7828
    struct list external_keys = LIST_INIT(external_keys);
    HKEY winnt_key = 0, win9x_key = 0;
    struct gdi_font_family *family;
    struct external_key *key, *next;
    struct gdi_font_face *face;
    DWORD len, i = 0, type, dlen, vlen;
    WCHAR value[LF_FULLFACESIZE + 12], path[MAX_PATH], *tmp;
    WCHAR *file;
    HKEY hkey;
7829

7830 7831 7832 7833
    RegCreateKeyExW( HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts",
                     0, NULL, 0, KEY_ALL_ACCESS, NULL, &winnt_key, NULL );
    RegCreateKeyExW( HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Fonts",
                     0, NULL, 0, KEY_ALL_ACCESS, NULL, &win9x_key, NULL );
7834

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

7837
    if (RegCreateKeyW( wine_fonts_key, L"External Fonts", &hkey )) return;
7838 7839 7840 7841 7842 7843

    vlen = ARRAY_SIZE(value);
    dlen = sizeof(path);
    while (!RegEnumValueW( hkey, i++, value, &vlen, NULL, &type, (BYTE *)path, &dlen ))
    {
        if (type != REG_SZ) goto next;
7844 7845 7846 7847 7848 7849 7850 7851
        if ((tmp = wcsrchr( value, ' ' )) && !facename_compare( tmp, L" (TrueType)", -1 )) *tmp = 0;
        if ((face = find_face_from_full_name( value )))
        {
            if (!wcsicmp( face->file, path )) face->flags |= ADDFONT_EXTERNAL_FOUND;
            goto next;
        }
        if (tmp && !*tmp) *tmp = ' ';
        if (!(key = HeapAlloc( GetProcessHeap(), 0, sizeof(*key) ))) break;
7852
        lstrcpyW( key->value, value );
7853
        list_add_tail( &external_keys, &key->entry );
7854 7855 7856 7857 7858
    next:
        vlen = ARRAY_SIZE(value);
        dlen = sizeof(path);
    }

7859
    WINE_RB_FOR_EACH_ENTRY( family, &family_name_tree, struct gdi_font_family, name_entry )
7860 7861 7862 7863
    {
        LIST_FOR_EACH_ENTRY( face, &family->faces, struct gdi_font_face, entry )
        {
            if (!(face->flags & ADDFONT_EXTERNAL_FONT)) continue;
7864
            if ((face->flags & ADDFONT_EXTERNAL_FOUND)) continue;
7865

7866
            lstrcpyW( value, face->full_name );
7867
            if (face->scalable) lstrcatW( value, L" (TrueType)" );
7868 7869 7870

            if (GetFullPathNameW( face->file, MAX_PATH, path, NULL ))
                file = path;
7871
            else if ((file = wcsrchr( face->file, '\\' )))
7872 7873 7874 7875
                file++;
            else
                file = face->file;

7876
            len = (lstrlenW(file) + 1) * sizeof(WCHAR);
7877 7878 7879 7880 7881
            RegSetValueExW( winnt_key, value, 0, REG_SZ, (BYTE *)file, len );
            RegSetValueExW( win9x_key, value, 0, REG_SZ, (BYTE *)file, len );
            RegSetValueExW( hkey, value, 0, REG_SZ, (BYTE *)file, len );
        }
    }
7882
    LIST_FOR_EACH_ENTRY_SAFE( key, next, &external_keys, struct external_key, entry )
7883 7884 7885 7886
    {
        RegDeleteValueW( win9x_key, key->value );
        RegDeleteValueW( winnt_key, key->value );
        RegDeleteValueW( hkey, key->value );
7887
        list_remove( &key->entry );
7888 7889 7890 7891
        HeapFree( GetProcessHeap(), 0, key );
    }
    RegCloseKey( win9x_key );
    RegCloseKey( winnt_key );
7892
    RegCloseKey( hkey );
7893 7894 7895
}

static void load_registry_fonts(void)
7896
{
7897
    WCHAR value[LF_FULLFACESIZE + 12], data[MAX_PATH], *tmp;
7898 7899 7900 7901 7902 7903 7904
    DWORD i = 0, type, dlen, vlen;
    HKEY hkey;

    /* Look under HKLM\Software\Microsoft\Windows[ NT]\CurrentVersion\Fonts
       for any fonts not installed in %WINDOWSDIR%\Fonts.  They will have their
       full path as the entry.  Also look for any .fon fonts, since ReadFontDir
       will skip these. */
7905 7906 7907
    if (RegOpenKeyW( HKEY_LOCAL_MACHINE,
                     is_win9x() ? L"Software\\Microsoft\\Windows\\CurrentVersion\\Fonts" :
                     L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts", &hkey ))
7908 7909 7910 7911
        return;

    vlen = ARRAY_SIZE(value);
    dlen = sizeof(data);
7912
    while (!RegEnumValueW( hkey, i++, value, &vlen, NULL, &type, NULL, NULL ))
7913
    {
7914
        if (type != REG_SZ) goto next;
7915
        dlen /= sizeof(WCHAR);
7916 7917 7918 7919
        if ((tmp = wcsrchr( value, ' ' )) && !facename_compare( tmp, L" (TrueType)", -1 )) *tmp = 0;
        if (find_face_from_full_name( value )) goto next;
        if (tmp && !*tmp) *tmp = ' ';

7920 7921 7922 7923 7924 7925 7926
        if (RegQueryValueExW( hkey, value, NULL, NULL, (LPBYTE)data, &dlen ))
        {
            WARN( "Unable to get face path %s\n", debugstr_w(value) );
            goto next;
        }

        dlen /= sizeof(WCHAR);
7927
        if (data[0] && data[1] == ':')
7928
            add_font_resource( data, ADDFONT_ALLOW_BITMAP );
7929
        else if (dlen >= 6 && !wcsicmp( data + dlen - 5, L".fon" ))
7930
            add_system_font_resource( data, ADDFONT_ALLOW_BITMAP );
7931
    next:
7932 7933 7934 7935 7936 7937
        vlen = ARRAY_SIZE(value);
        dlen = sizeof(data);
    }
    RegCloseKey( hkey );
}

7938 7939
static const struct font_callback_funcs callback_funcs = { add_gdi_face };

7940 7941 7942 7943 7944 7945 7946 7947
/***********************************************************************
 *              font_init
 */
void font_init(void)
{
    HANDLE mutex;
    DWORD disposition;

7948
    if (RegCreateKeyExW( HKEY_CURRENT_USER, L"Software\\Wine\\Fonts", 0, NULL, 0,
7949 7950 7951 7952 7953
                         KEY_ALL_ACCESS, NULL, &wine_fonts_key, NULL ))
        return;

    init_font_options();
    update_codepage();
7954
    if (__wine_init_unix_lib( gdi32_module, DLL_PROCESS_ATTACH, &callback_funcs, &font_funcs )) return;
7955

7956 7957 7958 7959
    load_system_bitmap_fonts();
    load_file_system_fonts();
    font_funcs->load_fonts();

7960
    if (!(mutex = CreateMutexW( NULL, FALSE, L"__WINE_FONT_MUTEX__" ))) return;
7961 7962
    WaitForSingleObject( mutex, INFINITE );

7963
    RegCreateKeyExW( wine_fonts_key, L"Cache", 0, NULL, REG_OPTION_VOLATILE,
7964 7965 7966 7967
                     KEY_ALL_ACCESS, NULL, &wine_fonts_cache_key, &disposition );

    if (disposition == REG_CREATED_NEW_KEY)
    {
7968
        load_registry_fonts();
7969
        update_external_font_keys();
7970 7971 7972 7973
    }

    ReleaseMutex( mutex );

7974 7975 7976 7977 7978 7979
    if (disposition != REG_CREATED_NEW_KEY)
    {
        load_registry_fonts();
        load_font_list_from_cache();
    }

7980 7981 7982 7983 7984 7985 7986 7987
    reorder_font_list();
    load_gdi_font_subst();
    load_gdi_font_replacements();
    load_system_links();
    dump_gdi_font_list();
    dump_gdi_font_subst();
}

7988 7989 7990
/***********************************************************************
 *           AddFontResourceExW    (GDI32.@)
 */
7991
INT WINAPI AddFontResourceExW( LPCWSTR str, DWORD flags, PVOID pdv )
7992
{
7993
    int ret;
7994
    WCHAR *filename;
7995
    BOOL hidden;
7996

7997
    if (!font_funcs) return 1;
7998
    if (!(ret = add_font_resource( str, flags )))
7999
    {
8000
        /* FreeType <2.3.5 has problems reading resources wrapped in PE files. */
8001 8002 8003 8004 8005 8006
        HMODULE hModule = LoadLibraryExW(str, NULL, LOAD_LIBRARY_AS_DATAFILE);
        if (hModule != NULL)
        {
            int num_resources = 0;
            LPWSTR rt_font = (LPWSTR)((ULONG_PTR)8);  /* we don't want to include winuser.h */

Stefan Leichter's avatar
Stefan Leichter committed
8007
            TRACE("WineEngAddFontResourceEx failed on PE file %s - trying to load resources manually\n",
8008 8009 8010 8011 8012
                wine_dbgstr_w(str));
            if (EnumResourceNamesW(hModule, rt_font, load_enumed_resource, (LONG_PTR)&num_resources))
                ret = num_resources;
            FreeLibrary(hModule);
        }
8013
        else if ((filename = get_scalable_filename( str, &hidden )) != NULL)
8014
        {
8015 8016
            if (hidden) flags |= FR_PRIVATE | FR_NOT_ENUM;
            ret = add_font_resource( filename, flags );
8017 8018
            HeapFree( GetProcessHeap(), 0, filename );
        }
8019 8020
    }
    return ret;
8021 8022 8023
}

/***********************************************************************
8024
 *           RemoveFontResourceA    (GDI32.@)
8025 8026 8027
 */
BOOL WINAPI RemoveFontResourceA( LPCSTR str )
{
8028
    return RemoveFontResourceExA(str, 0, 0);
8029 8030 8031
}

/***********************************************************************
8032
 *           RemoveFontResourceW    (GDI32.@)
8033 8034 8035
 */
BOOL WINAPI RemoveFontResourceW( LPCWSTR str )
{
8036 8037 8038
    return RemoveFontResourceExW(str, 0, 0);
}

8039 8040 8041
/***********************************************************************
 *           AddFontMemResourceEx    (GDI32.@)
 */
8042
HANDLE WINAPI AddFontMemResourceEx( PVOID ptr, DWORD size, PVOID pdv, DWORD *pcFonts )
8043
{
8044 8045
    HANDLE ret;
    DWORD num_fonts;
8046
    void *copy;
8047

8048
    if (!ptr || !size || !pcFonts)
8049 8050 8051 8052
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
    }
8053
    if (!font_funcs) return NULL;
8054 8055 8056
    if (!(copy = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
    memcpy( copy, ptr, size );

8057
    EnterCriticalSection( &font_cs );
8058
    num_fonts = font_funcs->add_mem_font( copy, size, ADDFONT_ALLOW_BITMAP | ADDFONT_ADD_RESOURCE );
8059
    LeaveCriticalSection( &font_cs );
8060 8061

    if (!num_fonts)
8062
    {
8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080
        HeapFree( GetProcessHeap(), 0, copy );
        return NULL;
    }

    /* FIXME: is the handle only for use in RemoveFontMemResourceEx or should it be a true handle?
     * For now return something unique but quite random
     */
    ret = (HANDLE)((INT_PTR)copy ^ 0x87654321);

    __TRY
    {
        *pcFonts = num_fonts;
    }
    __EXCEPT_PAGE_FAULT
    {
        WARN("page fault while writing to *pcFonts (%p)\n", pcFonts);
        RemoveFontMemResourceEx( ret );
        ret = 0;
8081
    }
8082 8083
    __ENDTRY
    TRACE( "Returning handle %p\n", ret );
8084
    return ret;
8085 8086
}

8087 8088 8089 8090 8091 8092 8093 8094 8095
/***********************************************************************
 *           RemoveFontMemResourceEx    (GDI32.@)
 */
BOOL WINAPI RemoveFontMemResourceEx( HANDLE fh )
{
    FIXME("(%p) stub\n", fh);
    return TRUE;
}

8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113
/***********************************************************************
 *           RemoveFontResourceExA    (GDI32.@)
 */
BOOL WINAPI RemoveFontResourceExA( LPCSTR str, DWORD fl, PVOID pdv )
{
    DWORD len = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
    LPWSTR strW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
    INT ret;

    MultiByteToWideChar(CP_ACP, 0, str, -1, strW, len);
    ret = RemoveFontResourceExW(strW, fl, pdv);
    HeapFree(GetProcessHeap(), 0, strW);
    return ret;
}

/***********************************************************************
 *           RemoveFontResourceExW    (GDI32.@)
 */
8114
BOOL WINAPI RemoveFontResourceExW( LPCWSTR str, DWORD flags, PVOID pdv )
8115
{
8116
    int ret;
8117
    WCHAR *filename;
8118
    BOOL hidden;
8119

8120 8121
    if (!font_funcs) return TRUE;

8122
    if (!(ret = remove_font_resource( str, flags )))
8123 8124 8125 8126 8127 8128 8129 8130
    {
        /* FreeType <2.3.5 has problems reading resources wrapped in PE files. */
        HMODULE hModule = LoadLibraryExW(str, NULL, LOAD_LIBRARY_AS_DATAFILE);
        if (hModule != NULL)
        {
            WARN("Can't unload resources from PE file %s\n", wine_dbgstr_w(str));
            FreeLibrary(hModule);
        }
8131
        else if ((filename = get_scalable_filename( str, &hidden )) != NULL)
8132
        {
8133 8134
            if (hidden) flags |= FR_PRIVATE | FR_NOT_ENUM;
            ret = remove_font_resource( filename, flags );
8135 8136 8137 8138
            HeapFree( GetProcessHeap(), 0, filename );
        }
    }
    return ret;
8139
}
8140

8141 8142 8143 8144 8145 8146 8147 8148 8149
/***********************************************************************
 *           GetFontResourceInfoW    (GDI32.@)
 */
BOOL WINAPI GetFontResourceInfoW( LPCWSTR str, LPDWORD size, PVOID buffer, DWORD type )
{
    FIXME("%s %p(%d) %p %d\n", debugstr_w(str), size, size ? *size : 0, buffer, type);
    return FALSE;
}

8150 8151 8152 8153 8154 8155 8156 8157 8158
/***********************************************************************
 *           GetTextCharset    (GDI32.@)
 */
UINT WINAPI GetTextCharset(HDC hdc)
{
    /* MSDN docs say this is equivalent */
    return GetTextCharsetInfo(hdc, NULL, 0);
}

8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188
/***********************************************************************
 *           GdiGetCharDimensions    (GDI32.@)
 *
 * Gets the average width of the characters in the English alphabet.
 *
 * PARAMS
 *  hdc    [I] Handle to the device context to measure on.
 *  lptm   [O] Pointer to memory to store the text metrics into.
 *  height [O] On exit, the maximum height of characters in the English alphabet.
 *
 * RETURNS
 *  The average width of characters in the English alphabet.
 *
 * NOTES
 *  This function is used by the dialog manager to get the size of a dialog
 *  unit. It should also be used by other pieces of code that need to know
 *  the size of a dialog unit in logical units without having access to the
 *  window handle of the dialog.
 *  Windows caches the font metrics from this function, but we don't and
 *  there doesn't appear to be an immediate advantage to do so.
 *
 * SEE ALSO
 *  GetTextExtentPointW, GetTextMetricsW, MapDialogRect.
 */
LONG WINAPI GdiGetCharDimensions(HDC hdc, LPTEXTMETRICW lptm, LONG *height)
{
    SIZE sz;

    if(lptm && !GetTextMetricsW(hdc, lptm)) return 0;

8189 8190
    if(!GetTextExtentPointW(hdc, L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 52, &sz))
        return 0;
8191 8192 8193 8194

    if (height) *height = sz.cy;
    return (sz.cx / 26 + 1) / 2;
}
8195 8196 8197 8198 8199 8200

BOOL WINAPI EnableEUDC(BOOL fEnableEUDC)
{
    FIXME("(%d): stub\n", fEnableEUDC);
    return FALSE;
}
8201 8202 8203

/***********************************************************************
 *           GetCharWidthI    (GDI32.@)
8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219
 *
 * Retrieve widths of characters.
 *
 * PARAMS
 *  hdc    [I] Handle to a device context.
 *  first  [I] First glyph in range to query.
 *  count  [I] Number of glyph indices to query.
 *  glyphs [I] Array of glyphs to query.
 *  buffer [O] Buffer to receive character widths.
 *
 * NOTES
 *  Only works with TrueType fonts.
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
8220
 */
8221
BOOL WINAPI GetCharWidthI(HDC hdc, UINT first, UINT count, LPWORD glyphs, LPINT buffer)
8222
{
8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237
    ABC *abc;
    unsigned int i;

    TRACE("(%p, %d, %d, %p, %p)\n", hdc, first, count, glyphs, buffer);

    if (!(abc = HeapAlloc(GetProcessHeap(), 0, count * sizeof(ABC))))
        return FALSE;

    if (!GetCharABCWidthsI(hdc, first, count, glyphs, abc))
    {
        HeapFree(GetProcessHeap(), 0, abc);
        return FALSE;
    }

    for (i = 0; i < count; i++)
8238
        buffer[i] = abc[i].abcA + abc[i].abcB + abc[i].abcC;
8239 8240 8241

    HeapFree(GetProcessHeap(), 0, abc);
    return TRUE;
8242 8243 8244 8245
}

/***********************************************************************
 *           GetFontUnicodeRanges    (GDI32.@)
8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256
 *
 *  Retrieve a list of supported Unicode characters in a font.
 *
 *  PARAMS
 *   hdc  [I] Handle to a device context.
 *   lpgs [O] GLYPHSET structure specifying supported character ranges.
 *
 *  RETURNS
 *   Success: Number of bytes written to the buffer pointed to by lpgs.
 *   Failure: 0
 *
8257 8258 8259
 */
DWORD WINAPI GetFontUnicodeRanges(HDC hdc, LPGLYPHSET lpgs)
{
8260 8261
    DWORD ret;
    PHYSDEV dev;
8262
    DC *dc = get_dc_ptr(hdc);
8263 8264 8265 8266 8267

    TRACE("(%p, %p)\n", hdc, lpgs);

    if (!dc) return 0;

8268 8269
    dev = GET_DC_PHYSDEV( dc, pGetFontUnicodeRanges );
    ret = dev->funcs->pGetFontUnicodeRanges( dev, lpgs );
8270
    release_dc_ptr(dc);
8271
    return ret;
8272
}
8273 8274 8275 8276 8277 8278 8279


/*************************************************************
 *           FontIsLinked    (GDI32.@)
 */
BOOL WINAPI FontIsLinked(HDC hdc)
{
8280
    DC *dc = get_dc_ptr(hdc);
8281 8282
    PHYSDEV dev;
    BOOL ret;
8283 8284

    if (!dc) return FALSE;
8285 8286
    dev = GET_DC_PHYSDEV( dc, pFontIsLinked );
    ret = dev->funcs->pFontIsLinked( dev );
8287
    release_dc_ptr(dc);
8288 8289 8290
    TRACE("returning %d\n", ret);
    return ret;
}
8291

8292
/*************************************************************
8293
 *           GetFontRealizationInfo    (GDI32.@)
8294
 */
8295
BOOL WINAPI GetFontRealizationInfo(HDC hdc, struct font_realization_info *info)
8296
{
8297
    BOOL is_v0 = info->size == FIELD_OFFSET(struct font_realization_info, unk);
8298 8299
    PHYSDEV dev;
    BOOL ret;
8300 8301 8302 8303
    DC *dc;

    if (info->size != sizeof(*info) && !is_v0)
        return FALSE;
8304

8305
    dc = get_dc_ptr(hdc);
8306
    if (!dc) return FALSE;
8307 8308
    dev = GET_DC_PHYSDEV( dc, pGetFontRealizationInfo );
    ret = dev->funcs->pGetFontRealizationInfo( dev, info );
8309 8310
    release_dc_ptr(dc);
    return ret;
8311
}
8312

8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328
/*************************************************************************
 *             GetRasterizerCaps   (GDI32.@)
 */
BOOL WINAPI GetRasterizerCaps( LPRASTERIZER_STATUS lprs, UINT cbNumBytes)
{
    lprs->nSize = sizeof(RASTERIZER_STATUS);
    lprs->wFlags = font_funcs ? (TT_AVAILABLE | TT_ENABLED) : 0;
    lprs->nLanguageID = 0;
    return TRUE;
}

/*************************************************************************
 *             GetFontFileData   (GDI32.@)
 */
BOOL WINAPI GetFontFileData( DWORD instance_id, DWORD unknown, UINT64 offset, void *buff, DWORD buff_size )
{
8329
    struct gdi_font *font;
8330
    DWORD tag = 0, size;
8331
    BOOL ret = FALSE;
8332

8333 8334 8335
    if (!font_funcs) return FALSE;
    EnterCriticalSection( &font_cs );
    if ((font = get_font_from_handle( instance_id )))
8336 8337 8338 8339 8340 8341 8342 8343
    {
        if (font->ttc_item_offset) tag = MS_TTCF_TAG;
        size = font_funcs->get_font_data( font, tag, 0, NULL, 0 );
        if (size != GDI_ERROR && size >= buff_size && offset <= size - buff_size)
            ret = font_funcs->get_font_data( font, tag, offset, buff, buff_size ) != GDI_ERROR;
        else
            SetLastError( ERROR_INVALID_PARAMETER );
    }
8344 8345
    LeaveCriticalSection( &font_cs );
    return ret;
8346 8347
}

8348 8349 8350 8351 8352 8353 8354 8355
/* Undocumented structure filled in by GetFontFileInfo */
struct font_fileinfo
{
    FILETIME writetime;
    LARGE_INTEGER size;
    WCHAR path[1];
};

8356 8357 8358 8359 8360 8361
/*************************************************************************
 *             GetFontFileInfo   (GDI32.@)
 */
BOOL WINAPI GetFontFileInfo( DWORD instance_id, DWORD unknown, struct font_fileinfo *info,
                             SIZE_T size, SIZE_T *needed )
{
8362 8363 8364
    SIZE_T required_size = 0;
    struct gdi_font *font;
    BOOL ret = FALSE;
8365

8366
    EnterCriticalSection( &font_cs );
8367

8368
    if ((font = get_font_from_handle( instance_id )))
8369
    {
8370
        required_size = sizeof(*info) + lstrlenW( font->file ) * sizeof(WCHAR);
8371 8372
        if (required_size <= size)
        {
8373 8374
            info->writetime = font->writetime;
            info->size.QuadPart = font->data_size;
8375
            lstrcpyW( info->path, font->file );
8376 8377 8378
            ret = TRUE;
        }
        else SetLastError( ERROR_INSUFFICIENT_BUFFER );
8379
    }
8380 8381 8382 8383

    LeaveCriticalSection( &font_cs );
    if (needed) *needed = required_size;
    return ret;
8384 8385
}

8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413
struct realization_info
{
    DWORD flags;       /* 1 for bitmap fonts, 3 for scalable fonts */
    DWORD cache_num;   /* keeps incrementing - num of fonts that have been created allowing for caching?? */
    DWORD instance_id; /* identifies a realized font instance */
};

/*************************************************************
 *           GdiRealizationInfo    (GDI32.@)
 *
 * Returns a structure that contains some font information.
 */
BOOL WINAPI GdiRealizationInfo(HDC hdc, struct realization_info *info)
{
    struct font_realization_info ri;
    BOOL ret;

    ri.size = sizeof(ri);
    ret = GetFontRealizationInfo( hdc, &ri );
    if (ret)
    {
        info->flags = ri.flags;
        info->cache_num = ri.cache_num;
        info->instance_id = ri.instance_id;
    }

    return ret;
}
8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437

/*************************************************************
 *           GetCharWidthInfo    (GDI32.@)
 *
 */
BOOL WINAPI GetCharWidthInfo(HDC hdc, struct char_width_info *info)
{
    PHYSDEV dev;
    BOOL ret;
    DC *dc;

    dc = get_dc_ptr(hdc);
    if (!dc) return FALSE;
    dev = GET_DC_PHYSDEV( dc, pGetCharWidthInfo );
    ret = dev->funcs->pGetCharWidthInfo( dev, info );

    if (ret)
    {
        info->lsb = width_to_LP( dc, info->lsb );
        info->rsb = width_to_LP( dc, info->rsb );
    }
    release_dc_ptr(dc);
    return ret;
}