[WIN32SS][FONT] Fix font metrics (#713)
[reactos.git] / win32ss / gdi / ntgdi / freetype.c
index 6417012..31d68a1 100644 (file)
@@ -5,7 +5,7 @@
  * PURPOSE:         FreeType font engine interface
  * PROGRAMMERS:     Copyright 2001 Huw D M Davies for CodeWeavers.
  *                  Copyright 2006 Dmitry Timoshkov for CodeWeavers.
- *                  Copyright 2016-2017 Katayama Hirofumi MZ.
+ *                  Copyright 2016-2018 Katayama Hirofumi MZ.
  */
 
 /** Includes ******************************************************************/
@@ -47,51 +47,51 @@ extern const MATRIX gmxWorldToPageDefault;
 /* HACK!! Fix XFORMOBJ then use 1:16 / 16:1 */
 #define gmxWorldToDeviceDefault gmxWorldToPageDefault
 
-FT_Library  library;
+FT_Library  g_FreeTypeLibrary;
 
 /* special font names */
-static const UNICODE_STRING MarlettW = RTL_CONSTANT_STRING(L"Marlett");
+static const UNICODE_STRING g_MarlettW = RTL_CONSTANT_STRING(L"Marlett");
 
 /* registry */
-static UNICODE_STRING FontRegPath =
+static UNICODE_STRING g_FontRegPath =
     RTL_CONSTANT_STRING(L"\\REGISTRY\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts");
 
 
 /* The FreeType library is not thread safe, so we have
    to serialize access to it */
-static PFAST_MUTEX FreeTypeLock;
+static PFAST_MUTEX      g_FreeTypeLock;
 
-static LIST_ENTRY FontListHead;
-static PFAST_MUTEX FontListLock;
-static BOOL RenderingEnabled = TRUE;
+static LIST_ENTRY       g_FontListHead;
+static PFAST_MUTEX      g_FontListLock;
+static BOOL             g_RenderingEnabled = TRUE;
 
-#define IntLockGlobalFonts \
-  ExEnterCriticalRegionAndAcquireFastMutexUnsafe(FontListLock)
+#define IntLockGlobalFonts() \
+    ExEnterCriticalRegionAndAcquireFastMutexUnsafe(g_FontListLock)
 
-#define IntUnLockGlobalFonts \
-  ExReleaseFastMutexUnsafeAndLeaveCriticalRegion(FontListLock)
+#define IntUnLockGlobalFonts() \
+    ExReleaseFastMutexUnsafeAndLeaveCriticalRegion(g_FontListLock)
 
 #define ASSERT_GLOBALFONTS_LOCK_HELD() \
-  ASSERT(FontListLock->Owner == KeGetCurrentThread())
+    ASSERT(g_FontListLock->Owner == KeGetCurrentThread())
 
-#define IntLockFreeType \
-  ExEnterCriticalRegionAndAcquireFastMutexUnsafe(FreeTypeLock)
+#define IntLockFreeType() \
+    ExEnterCriticalRegionAndAcquireFastMutexUnsafe(g_FreeTypeLock)
 
-#define IntUnLockFreeType \
-  ExReleaseFastMutexUnsafeAndLeaveCriticalRegion(FreeTypeLock)
+#define IntUnLockFreeType() \
+    ExReleaseFastMutexUnsafeAndLeaveCriticalRegion(g_FreeTypeLock)
 
 #define ASSERT_FREETYPE_LOCK_HELD() \
-  ASSERT(FreeTypeLock->Owner == KeGetCurrentThread())
+    ASSERT(g_FreeTypeLock->Owner == KeGetCurrentThread())
 
 #define ASSERT_FREETYPE_LOCK_NOT_HELD() \
-  ASSERT(FreeTypeLock->Owner != KeGetCurrentThread())
+    ASSERT(g_FreeTypeLock->Owner != KeGetCurrentThread())
 
 #define MAX_FONT_CACHE 256
 
-static LIST_ENTRY FontCacheListHead;
-static UINT FontCacheNumEntries;
+static LIST_ENTRY g_FontCacheListHead;
+static UINT g_FontCacheNumEntries;
 
-static PWCHAR ElfScripts[32] =   /* These are in the order of the fsCsb[0] bits */
+static PWCHAR g_ElfScripts[32] =   /* These are in the order of the fsCsb[0] bits */
 {
     L"Western", /* 00 */
     L"Central_European",
@@ -119,7 +119,7 @@ static PWCHAR ElfScripts[32] =   /* These are in the order of the fsCsb[0] bits
  */
 #define CP_SYMBOL   42
 #define MAXTCIINDEX 32
-static const CHARSETINFO FontTci[MAXTCIINDEX] =
+static const CHARSETINFO g_FontTci[MAXTCIINDEX] =
 {
     /* ANSI */
     { ANSI_CHARSET, 1252, {{0,0,0,0},{FS_LATIN1,0}} },
@@ -160,8 +160,37 @@ static const CHARSETINFO FontTci[MAXTCIINDEX] =
     { SYMBOL_CHARSET, CP_SYMBOL, {{0,0,0,0},{FS_SYMBOL,0}} }
 };
 
+#ifndef CP_OEMCP
+    #define CP_OEMCP  1
+    #define CP_MACCP  2
+#endif
+
+/* Get charset from specified codepage.
+   g_FontTci is used also in TranslateCharsetInfo. */
+BYTE FASTCALL IntCharSetFromCodePage(UINT uCodePage)
+{
+    UINT i;
+
+    if (uCodePage == CP_OEMCP)
+        return OEM_CHARSET;
+
+    if (uCodePage == CP_MACCP)
+        return MAC_CHARSET;
+
+    for (i = 0; i < MAXTCIINDEX; ++i)
+    {
+        if (g_FontTci[i].ciACP == 0)
+            continue;
+
+        if (g_FontTci[i].ciACP == uCodePage)
+            return g_FontTci[i].ciCharset;
+    }
+
+    return DEFAULT_CHARSET;
+}
+
 /* list head */
-static RTL_STATIC_LIST_HEAD(FontSubstListHead);
+static RTL_STATIC_LIST_HEAD(g_FontSubstListHead);
 
 static void
 SharedMem_AddRef(PSHARED_MEM Ptr)
@@ -193,7 +222,7 @@ SharedFace_Create(FT_Face Face, PSHARED_MEM Memory)
         SharedFaceCache_Init(&Ptr->UserLanguage);
 
         SharedMem_AddRef(Memory);
-        DPRINT("Creating SharedFace for %s\n", Face->family_name);
+        DPRINT("Creating SharedFace for %s\n", Face->family_name ? Face->family_name : "<NULL>");
     }
     return Ptr;
 }
@@ -230,8 +259,8 @@ RemoveCachedEntry(PFONT_CACHE_ENTRY Entry)
     FT_Done_Glyph((FT_Glyph)Entry->BitmapGlyph);
     RemoveEntryList(&Entry->ListEntry);
     ExFreePoolWithTag(Entry, TAG_FONT);
-    FontCacheNumEntries--;
-    ASSERT(FontCacheNumEntries <= MAX_FONT_CACHE);
+    g_FontCacheNumEntries--;
+    ASSERT(g_FontCacheNumEntries <= MAX_FONT_CACHE);
 }
 
 static void
@@ -242,8 +271,8 @@ RemoveCacheEntries(FT_Face Face)
 
     ASSERT_FREETYPE_LOCK_HELD();
 
-    CurrentEntry = FontCacheListHead.Flink;
-    while (CurrentEntry != &FontCacheListHead)
+    CurrentEntry = g_FontCacheListHead.Flink;
+    while (CurrentEntry != &g_FontCacheListHead)
     {
         FontEntry = CONTAINING_RECORD(CurrentEntry, FONT_CACHE_ENTRY, ListEntry);
         CurrentEntry = CurrentEntry->Flink;
@@ -285,7 +314,7 @@ SharedFaceCache_Release(PSHARED_FACE_CACHE Cache)
 static void
 SharedFace_Release(PSHARED_FACE Ptr)
 {
-    IntLockFreeType;
+    IntLockFreeType();
     ASSERT(Ptr->RefCount > 0);
 
     if (Ptr->RefCount <= 0)
@@ -294,7 +323,7 @@ SharedFace_Release(PSHARED_FACE Ptr)
     --Ptr->RefCount;
     if (Ptr->RefCount == 0)
     {
-        DPRINT("Releasing SharedFace for %s\n", Ptr->Face->family_name);
+        DPRINT("Releasing SharedFace for %s\n", Ptr->Face->family_name ? Ptr->Face->family_name : "<NULL>");
         RemoveCacheEntries(Ptr->Face);
         FT_Done_Face(Ptr->Face);
         SharedMem_Release(Ptr->Memory);
@@ -302,7 +331,7 @@ SharedFace_Release(PSHARED_FACE Ptr)
         SharedFaceCache_Release(&Ptr->UserLanguage);
         ExFreePoolWithTag(Ptr, TAG_FONT);
     }
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 }
 
 
@@ -455,25 +484,25 @@ InitFontSupport(VOID)
 {
     ULONG ulError;
 
-    InitializeListHead(&FontListHead);
-    InitializeListHead(&FontCacheListHead);
-    FontCacheNumEntries = 0;
+    InitializeListHead(&g_FontListHead);
+    InitializeListHead(&g_FontCacheListHead);
+    g_FontCacheNumEntries = 0;
     /* Fast Mutexes must be allocated from non paged pool */
-    FontListLock = ExAllocatePoolWithTag(NonPagedPool, sizeof(FAST_MUTEX), TAG_INTERNAL_SYNC);
-    if (FontListLock == NULL)
+    g_FontListLock = ExAllocatePoolWithTag(NonPagedPool, sizeof(FAST_MUTEX), TAG_INTERNAL_SYNC);
+    if (g_FontListLock == NULL)
     {
         return FALSE;
     }
 
-    ExInitializeFastMutex(FontListLock);
-    FreeTypeLock = ExAllocatePoolWithTag(NonPagedPool, sizeof(FAST_MUTEX), TAG_INTERNAL_SYNC);
-    if (FreeTypeLock == NULL)
+    ExInitializeFastMutex(g_FontListLock);
+    g_FreeTypeLock = ExAllocatePoolWithTag(NonPagedPool, sizeof(FAST_MUTEX), TAG_INTERNAL_SYNC);
+    if (g_FreeTypeLock == NULL)
     {
         return FALSE;
     }
-    ExInitializeFastMutex(FreeTypeLock);
+    ExInitializeFastMutex(g_FreeTypeLock);
 
-    ulError = FT_Init_FreeType(&library);
+    ulError = FT_Init_FreeType(&g_FreeTypeLibrary);
     if (ulError)
     {
         DPRINT1("FT_Init_FreeType failed with error code 0x%x\n", ulError);
@@ -481,7 +510,7 @@ InitFontSupport(VOID)
     }
 
     IntLoadSystemFonts();
-    IntLoadFontSubstList(&FontSubstListHead);
+    IntLoadFontSubstList(&g_FontSubstListHead);
 
     return TRUE;
 }
@@ -593,7 +622,7 @@ SubstituteFontRecurse(LOGFONTW* pLogFont)
 
     while (RecurseCount-- > 0)
     {
-        Found = SubstituteFontByList(&FontSubstListHead,
+        Found = SubstituteFontByList(&g_FontSubstListHead,
                                      &OutputNameW, &InputNameW,
                                      pLogFont->lfCharSet, CharSetMap);
         if (!Found)
@@ -776,6 +805,9 @@ WeightFromStyle(const char *style_name)
     return FW_NORMAL;
 }
 
+static FT_Error
+IntRequestFontSize(PDC dc, PFONTGDI FontGDI, LONG lfWidth, LONG lfHeight);
+
 static INT FASTCALL
 IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
                           PSHARED_FACE SharedFace, FT_Long FontIndex, INT CharSetIndex)
@@ -801,9 +833,9 @@ IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
     if (SharedFace == NULL && CharSetIndex == -1)
     {
         /* load a face from memory */
-        IntLockFreeType;
+        IntLockFreeType();
         Error = FT_New_Memory_Face(
-                    library,
+                    g_FreeTypeLibrary,
                     pLoadFont->Memory->Buffer,
                     pLoadFont->Memory->BufferSize,
                     ((FontIndex != -1) ? FontIndex : 0),
@@ -812,7 +844,7 @@ IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
         if (!Error)
             SharedFace = SharedFace_Create(Face, pLoadFont->Memory);
 
-        IntUnLockFreeType;
+        IntUnLockFreeType();
 
         if (!Error && FT_IS_SFNT(Face))
             pLoadFont->IsTrueType = TRUE;
@@ -832,9 +864,9 @@ IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
     else
     {
         Face = SharedFace->Face;
-        IntLockFreeType;
+        IntLockFreeType();
         SharedFace_AddRef(SharedFace);
-        IntUnLockFreeType;
+        IntUnLockFreeType();
     }
 
     /* allocate a FONT_ENTRY */
@@ -933,7 +965,7 @@ IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
     }
 
     os2_version = 0;
-    IntLockFreeType;
+    IntLockFreeType();
     pOS2 = (TT_OS2 *)FT_Get_Sfnt_Table(Face, FT_SFNT_OS2);
     if (pOS2)
     {
@@ -941,7 +973,7 @@ IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
         os2_ulCodePageRange1 = pOS2->ulCodePageRange1;
         os2_usWeightClass = pOS2->usWeightClass;
     }
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     if (pOS2 && os2_version >= 1)
     {
@@ -954,13 +986,13 @@ IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
         {
             if (os2_ulCodePageRange1 & (1 << BitIndex))
             {
-                if (FontTci[BitIndex].ciCharset == DEFAULT_CHARSET)
+                if (g_FontTci[BitIndex].ciCharset == DEFAULT_CHARSET)
                     continue;
 
                 if ((CharSetIndex == -1 && CharSetCount == 0) ||
                     CharSetIndex == CharSetCount)
                 {
-                    FontGDI->CharSet = FontTci[BitIndex].ciCharset;
+                    FontGDI->CharSet = g_FontTci[BitIndex].ciCharset;
                 }
 
                 ++CharSetCount;
@@ -973,26 +1005,32 @@ IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
     else
     {
         /* get charset from WinFNT header */
-        IntLockFreeType;
+        IntLockFreeType();
         Error = FT_Get_WinFNT_Header(Face, &WinFNT);
         if (!Error)
         {
             FontGDI->CharSet = WinFNT.charset;
         }
-        IntUnLockFreeType;
+        IntUnLockFreeType();
     }
 
     /* FIXME: CharSet is invalid on Marlett */
-    if (RtlEqualUnicodeString(&Entry->FaceName, &MarlettW, TRUE))
+    if (RtlEqualUnicodeString(&Entry->FaceName, &g_MarlettW, TRUE))
     {
         FontGDI->CharSet = SYMBOL_CHARSET;
     }
 
     ++FaceCount;
-    DPRINT("Font loaded: %s (%s)\n", Face->family_name, Face->style_name);
+    DPRINT("Font loaded: %s (%s)\n",
+           Face->family_name ? Face->family_name : "<NULL>",
+           Face->style_name ? Face->style_name : "<NULL>");
     DPRINT("Num glyphs: %d\n", Face->num_glyphs);
     DPRINT("CharSet: %d\n", FontGDI->CharSet);
 
+    IntLockFreeType();
+    IntRequestFontSize(NULL, FontGDI, 0, 0);
+    IntUnLockFreeType();
+
     /* Add this font resource to the font table */
     Entry->Font = FontGDI;
     Entry->NotEnum = (Characteristics & FR_NOT_ENUM);
@@ -1008,9 +1046,9 @@ IntGdiLoadFontsFromMemory(PGDI_LOAD_FONT pLoadFont,
     else
     {
         /* global font */
-        IntLockGlobalFonts;
-        InsertTailList(&FontListHead, &Entry->ListEntry);
-        IntUnLockGlobalFonts;
+        IntLockGlobalFonts();
+        InsertTailList(&g_FontListHead, &Entry->ListEntry);
+        IntUnLockGlobalFonts();
     }
 
     if (FontIndex == -1)
@@ -1135,9 +1173,9 @@ IntGdiAddFontResource(PUNICODE_STRING FileName, DWORD Characteristics)
     ObDereferenceObject(SectionObject);
 
     /* Release our copy */
-    IntLockFreeType;
+    IntLockFreeType();
     SharedMem_Release(LoadFont.Memory);
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     if (FontCount > 0)
     {
@@ -1162,7 +1200,7 @@ IntGdiAddFontResource(PUNICODE_STRING FileName, DWORD Characteristics)
         }
 
         /* registry */
-        InitializeObjectAttributes(&ObjectAttributes, &FontRegPath,
+        InitializeObjectAttributes(&ObjectAttributes, &g_FontRegPath,
                                    OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                                    NULL, NULL);
         Status = ZwOpenKey(&KeyHandle, KEY_WRITE, &ObjectAttributes);
@@ -1213,9 +1251,9 @@ IntGdiAddFontMemResource(PVOID Buffer, DWORD dwSize, PDWORD pNumAdded)
     RtlFreeUnicodeString(&LoadFont.RegValueName);
 
     /* Release our copy */
-    IntLockFreeType;
+    IntLockFreeType();
     SharedMem_Release(LoadFont.Memory);
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     if (FaceCount > 0)
     {
@@ -1372,12 +1410,12 @@ IntGdiCleanupPrivateFontsForProcess(VOID)
 BOOL FASTCALL
 IntIsFontRenderingEnabled(VOID)
 {
-    BOOL Ret = RenderingEnabled;
+    BOOL Ret = g_RenderingEnabled;
     HDC hDC;
 
     hDC = IntGetScreenDC();
     if (hDC)
-        Ret = (NtGdiGetDeviceCaps(hDC, BITSPIXEL) > 8) && RenderingEnabled;
+        Ret = (NtGdiGetDeviceCaps(hDC, BITSPIXEL) > 8) && g_RenderingEnabled;
 
     return Ret;
 }
@@ -1385,7 +1423,7 @@ IntIsFontRenderingEnabled(VOID)
 VOID FASTCALL
 IntEnableFontRendering(BOOL Enable)
 {
-    RenderingEnabled = Enable;
+    g_RenderingEnabled = Enable;
 }
 
 FT_Render_Mode FASTCALL
@@ -1466,13 +1504,13 @@ IntTranslateCharsetInfo(PDWORD Src, /* [in]
         }
         break;
     case TCI_SRCCODEPAGE:
-        while (Index < MAXTCIINDEX && *Src != FontTci[Index].ciACP)
+        while (Index < MAXTCIINDEX && *Src != g_FontTci[Index].ciACP)
         {
             Index++;
         }
         break;
     case TCI_SRCCHARSET:
-        while (Index < MAXTCIINDEX && *Src != FontTci[Index].ciCharset)
+        while (Index < MAXTCIINDEX && *Src != g_FontTci[Index].ciCharset)
         {
             Index++;
         }
@@ -1481,12 +1519,12 @@ IntTranslateCharsetInfo(PDWORD Src, /* [in]
         return FALSE;
     }
 
-    if (Index >= MAXTCIINDEX || DEFAULT_CHARSET == FontTci[Index].ciCharset)
+    if (Index >= MAXTCIINDEX || DEFAULT_CHARSET == g_FontTci[Index].ciCharset)
     {
         return FALSE;
     }
 
-    RtlCopyMemory(Cs, &FontTci[Index], sizeof(CHARSETINFO));
+    RtlCopyMemory(Cs, &g_FontTci[Index], sizeof(CHARSETINFO));
 
     return TRUE;
 }
@@ -1504,7 +1542,6 @@ static BOOL face_has_symbol_charmap(FT_Face ft_face)
     return FALSE;
 }
 
-
 static void FASTCALL
 FillTMEx(TEXTMETRICW *TM, PFONTGDI FontGDI,
          TT_OS2 *pOS2, TT_HoriHeader *pHori,
@@ -1564,16 +1601,14 @@ FillTMEx(TEXTMETRICW *TM, PFONTGDI FontGDI,
         Descent = pOS2->usWinDescent;
     }
 
-#if 0 /* This (Wine) code doesn't seem to work correctly for us, cmd issue */
-    TM->tmAscent = (FT_MulFix(Ascent, YScale) + 32) >> 6;
-    TM->tmDescent = (FT_MulFix(Descent, YScale) + 32) >> 6;
-#else /* This (ros) code was previously affected by a FreeType bug, but it works now */
-    TM->tmAscent = (Face->size->metrics.ascender + 32) >> 6; /* Units above baseline */
-    TM->tmDescent = (32 - Face->size->metrics.descender) >> 6; /* Units below baseline */
-#endif
-    TM->tmInternalLeading = (FT_MulFix(Ascent + Descent - Face->units_per_EM, YScale) + 32) >> 6;
-
+    if (FontGDI->Magic != FONTGDI_MAGIC)
+    {
+        IntRequestFontSize(NULL, FontGDI, 0, 0);
+    }
+    TM->tmAscent = FontGDI->tmAscent;
+    TM->tmDescent = FontGDI->tmDescent;
     TM->tmHeight = TM->tmAscent + TM->tmDescent;
+    TM->tmInternalLeading = FontGDI->tmInternalLeading;
 
     /* MSDN says:
      *  el = MAX(0, LineGap - ((WinAscent + WinDescent) - (Ascender - Descender)))
@@ -1825,11 +1860,11 @@ IntGetOutlineTextMetrics(PFONTGDI FontGDI,
     XScale = Face->size->metrics.x_scale;
     YScale = Face->size->metrics.y_scale;
 
-    IntLockFreeType;
+    IntLockFreeType();
     pOS2 = FT_Get_Sfnt_Table(Face, ft_sfnt_os2);
     if (NULL == pOS2)
     {
-        IntUnLockFreeType;
+        IntUnLockFreeType();
         DPRINT1("Can't find OS/2 table - not TT font?\n");
         RtlFreeUnicodeString(&FamilyNameW);
         RtlFreeUnicodeString(&FaceNameW);
@@ -1841,7 +1876,7 @@ IntGetOutlineTextMetrics(PFONTGDI FontGDI,
     pHori = FT_Get_Sfnt_Table(Face, ft_sfnt_hhea);
     if (NULL == pHori)
     {
-        IntUnLockFreeType;
+        IntUnLockFreeType();
         DPRINT1("Can't find HHEA table - not TT font?\n");
         RtlFreeUnicodeString(&FamilyNameW);
         RtlFreeUnicodeString(&FaceNameW);
@@ -1900,7 +1935,7 @@ IntGetOutlineTextMetrics(PFONTGDI FontGDI,
         Otm->otmsUnderscorePosition = (FT_MulFix(pPost->underlinePosition, YScale) + 32) >> 6;
     }
 
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     Cp = (char*) Otm + sizeof(OUTLINETEXTMETRICW);
 
@@ -1996,9 +2031,9 @@ FindFaceNameInLists(PUNICODE_STRING FaceName)
     }
 
     /* Search the global list */
-    IntLockGlobalFonts;
-    Font = FindFaceNameInList(FaceName, &FontListHead);
-    IntUnLockGlobalFonts;
+    IntLockGlobalFonts();
+    Font = FindFaceNameInList(FaceName, &g_FontListHead);
+    IntUnLockGlobalFonts();
 
     return Font;
 }
@@ -2227,18 +2262,18 @@ IntGetFontLocalizedName(PUNICODE_STRING pNameW, PSHARED_FACE SharedFace,
         if (NameID == TT_NAME_ID_FONT_FAMILY)
         {
             ASSERT_FREETYPE_LOCK_NOT_HELD();
-            IntLockFreeType;
+            IntLockFreeType();
             if (!Cache->FontFamily.Buffer)
                 DuplicateUnicodeString(pNameW, &Cache->FontFamily);
-            IntUnLockFreeType;
+            IntUnLockFreeType();
         }
         else if (NameID == TT_NAME_ID_FULL_NAME)
         {
             ASSERT_FREETYPE_LOCK_NOT_HELD();
-            IntLockFreeType;
+            IntLockFreeType();
             if (!Cache->FullName.Buffer)
                 DuplicateUnicodeString(pNameW, &Cache->FullName);
-            IntUnLockFreeType;
+            IntUnLockFreeType();
         }
     }
 
@@ -2357,12 +2392,12 @@ FontFamilyFillInfo(PFONTFAMILYINFO Info, LPCWSTR FaceName,
     }
     Info->EnumLogFontEx.elfScript[0] = UNICODE_NULL;
 
-    IntLockFreeType;
+    IntLockFreeType();
     pOS2 = FT_Get_Sfnt_Table(Face, ft_sfnt_os2);
 
     if (!pOS2)
     {
-        IntUnLockFreeType;
+        IntUnLockFreeType();
         return;
     }
 
@@ -2382,7 +2417,7 @@ FontFamilyFillInfo(PFONTFAMILYINFO Info, LPCWSTR FaceName,
         else
             fs.fsCsb[0] |= FS_SYMBOL;
     }
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     if (fs.fsCsb[0] == 0)
     {
@@ -2415,8 +2450,8 @@ FontFamilyFillInfo(PFONTFAMILYINFO Info, LPCWSTR FaceName,
             }
             if (DEFAULT_CHARSET != CharSetInfo.ciCharset)
             {
-                if (ElfScripts[i])
-                    wcscpy(Info->EnumLogFontEx.elfScript, ElfScripts[i]);
+                if (g_ElfScripts[i])
+                    wcscpy(Info->EnumLogFontEx.elfScript, g_ElfScripts[i]);
                 else
                 {
                     DPRINT1("Unknown elfscript for bit %u\n", i);
@@ -2549,7 +2584,7 @@ GetFontFamilyInfoForSubstitutes(LPLOGFONTW LogFont,
                                 DWORD *pCount,
                                 DWORD MaxCount)
 {
-    PLIST_ENTRY pEntry, pHead = &FontSubstListHead;
+    PLIST_ENTRY pEntry, pHead = &g_FontSubstListHead;
     PFONTSUBST_ENTRY pCurrentEntry;
     PUNICODE_STRING pFromW;
     FONTGDI *FontGDI;
@@ -2627,8 +2662,8 @@ ftGdiGlyphCacheGet(
 
     ASSERT_FREETYPE_LOCK_HELD();
 
-    CurrentEntry = FontCacheListHead.Flink;
-    while (CurrentEntry != &FontCacheListHead)
+    CurrentEntry = g_FontCacheListHead.Flink;
+    while (CurrentEntry != &g_FontCacheListHead)
     {
         FontEntry = CONTAINING_RECORD(CurrentEntry, FONT_CACHE_ENTRY, ListEntry);
         if ((FontEntry->Face == Face) &&
@@ -2640,13 +2675,13 @@ ftGdiGlyphCacheGet(
         CurrentEntry = CurrentEntry->Flink;
     }
 
-    if (CurrentEntry == &FontCacheListHead)
+    if (CurrentEntry == &g_FontCacheListHead)
     {
         return NULL;
     }
 
     RemoveEntryList(CurrentEntry);
-    InsertHeadList(&FontCacheListHead, CurrentEntry);
+    InsertHeadList(&g_FontCacheListHead, CurrentEntry);
     return FontEntry->BitmapGlyph;
 }
 
@@ -2753,10 +2788,10 @@ ftGdiGlyphCacheSet(
     NewEntry->RenderMode = RenderMode;
     NewEntry->mxWorldToDevice = *pmx;
 
-    InsertHeadList(&FontCacheListHead, &NewEntry->ListEntry);
-    if (++FontCacheNumEntries > MAX_FONT_CACHE)
+    InsertHeadList(&g_FontCacheListHead, &NewEntry->ListEntry);
+    if (++g_FontCacheNumEntries > MAX_FONT_CACHE)
     {
-        NewEntry = CONTAINING_RECORD(FontCacheListHead.Blink, FONT_CACHE_ENTRY, ListEntry);
+        NewEntry = CONTAINING_RECORD(g_FontCacheListHead.Blink, FONT_CACHE_ENTRY, ListEntry);
         RemoveCachedEntry(NewEntry);
     }
 
@@ -2992,38 +3027,104 @@ static unsigned int get_bezier_glyph_outline(FT_Outline *outline, unsigned int b
     return needed;
 }
 
-static INT
-IntRequestFontSize(PDC dc, FT_Face face, LONG Width, LONG Height)
+static FT_Error
+IntRequestFontSize(PDC dc, PFONTGDI FontGDI, LONG lfWidth, LONG lfHeight)
 {
+    FT_Error error;
     FT_Size_RequestRec  req;
+    FT_Face face = FontGDI->SharedFace->Face;
+    TT_OS2 *pOS2;
+    TT_HoriHeader *pHori;
+    FT_WinFNT_HeaderRec WinFNT;
+    LONG Ascent, Descent, Sum, EmHeight64;
+
+    lfWidth = abs(lfWidth);
+    if (lfHeight == 0)
+    {
+        if (lfWidth == 0)
+        {
+            DPRINT("lfHeight and lfWidth are zero.\n");
+            lfHeight = -16;
+        }
+        else
+        {
+            lfHeight = lfWidth;
+        }
+    }
 
-    if (Width < 0)
-        Width = -Width;
+    if (lfHeight == -1)
+        lfHeight = -2;
 
-    if (Height < 0)
+    ASSERT_FREETYPE_LOCK_HELD();
+    pOS2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, FT_SFNT_OS2);
+    pHori = (TT_HoriHeader *)FT_Get_Sfnt_Table(face, FT_SFNT_HHEA);
+
+    if (!pOS2 || !pHori)
     {
-        Height = -Height;
+        error = FT_Get_WinFNT_Header(face, &WinFNT);
+        if (error)
+            return error;
+
+        FontGDI->tmHeight           = WinFNT.pixel_height;
+        FontGDI->tmAscent           = WinFNT.ascent;
+        FontGDI->tmDescent          = FontGDI->tmHeight - FontGDI->tmAscent;
+        FontGDI->tmInternalLeading  = WinFNT.internal_leading;
+        FontGDI->EmHeight           = FontGDI->tmHeight - FontGDI->tmInternalLeading;
+        FontGDI->EmHeight = max(FontGDI->EmHeight, 1);
+        FontGDI->EmHeight = min(FontGDI->EmHeight, USHORT_MAX);
+        FontGDI->Magic = FONTGDI_MAGIC;
+
+        req.type           = FT_SIZE_REQUEST_TYPE_NOMINAL;
+        req.width          = 0;
+        req.height         = (FT_Long)(FontGDI->EmHeight << 6);
+        req.horiResolution = 0;
+        req.vertResolution = 0;
+        return FT_Request_Size(face, &req);
     }
-    if (Height == 0)
+
+    if (lfHeight > 0)
     {
-        Height = dc->ppdev->devinfo.lfDefaultFont.lfHeight;
+        /* case (A): lfHeight is positive */
+        Sum = pOS2->usWinAscent + pOS2->usWinDescent;
+        if (Sum == 0)
+        {
+            Ascent = pHori->Ascender;
+            Descent = -pHori->Descender;
+            Sum = Ascent + Descent;
+        }
+        else
+        {
+            Ascent = pOS2->usWinAscent;
+            Descent = pOS2->usWinDescent;
+        }
+
+        FontGDI->tmAscent = FT_MulDiv(lfHeight, Ascent, Sum);
+        FontGDI->tmDescent = FT_MulDiv(lfHeight, Descent, Sum);
+        FontGDI->tmHeight = FontGDI->tmAscent + FontGDI->tmDescent;
+        FontGDI->tmInternalLeading = FontGDI->tmHeight - FT_MulDiv(lfHeight, face->units_per_EM, Sum);
     }
-    if (Height == 0)
+    else if (lfHeight < 0)
     {
-        Height = Width;
+        /* case (B): lfHeight is negative */
+        FontGDI->tmAscent = FT_MulDiv(-lfHeight, pOS2->usWinAscent, face->units_per_EM);
+        FontGDI->tmDescent = FT_MulDiv(-lfHeight, pOS2->usWinDescent, face->units_per_EM);
+        FontGDI->tmHeight = FontGDI->tmAscent + FontGDI->tmDescent;
+        FontGDI->tmInternalLeading = FontGDI->tmHeight + lfHeight;
     }
 
-    if (Height < 1)
-        Height = 1;
+    FontGDI->EmHeight = FontGDI->tmHeight - FontGDI->tmInternalLeading;
+    FontGDI->EmHeight = max(FontGDI->EmHeight, 1);
+    FontGDI->EmHeight = min(FontGDI->EmHeight, USHORT_MAX);
+    FontGDI->Magic = FONTGDI_MAGIC;
 
-    if (Width > 0xFFFFU)
-        Width = 0xFFFFU;
-    if (Height > 0xFFFFU)
-        Height = 0xFFFFU;
+    if (lfHeight > 0)
+        EmHeight64 = (FontGDI->EmHeight << 6) + 31;
+    else
+        EmHeight64 = (FontGDI->EmHeight << 6);
 
     req.type           = FT_SIZE_REQUEST_TYPE_NOMINAL;
-    req.width          = (FT_Long)(Width << 6);
-    req.height         = (FT_Long)(Height << 6);
+    req.width          = 0;
+    req.height         = EmHeight64;
     req.horiResolution = 0;
     req.vertResolution = 0;
     return FT_Request_Size(face, &req);
@@ -3042,7 +3143,7 @@ TextIntUpdateSize(PDC dc,
     LOGFONTW *plf;
 
     if (bDoLock)
-        IntLockFreeType;
+        IntLockFreeType();
 
     face = FontGDI->SharedFace->Face;
     if (face->charmap == NULL)
@@ -3077,10 +3178,10 @@ TextIntUpdateSize(PDC dc,
 
     plf = &TextObj->logfont.elfEnumLogfontEx.elfLogFont;
 
-    error = IntRequestFontSize(dc, face, plf->lfWidth, plf->lfHeight);
+    error = IntRequestFontSize(dc, FontGDI, plf->lfWidth, plf->lfHeight);
 
     if (bDoLock)
-        IntUnLockFreeType;
+        IntUnLockFreeType();
 
     if (error)
     {
@@ -3173,7 +3274,7 @@ ftGdiGetGlyphOutline(
         return GDI_ERROR;
     }
 
-    IntLockFreeType;
+    IntLockFreeType();
     TextIntUpdateSize(dc, TextObj, FontGDI, FALSE);
     FtSetCoordinateTransform(ft_face, DC_pmxWorldToDevice(dc));
 
@@ -3199,11 +3300,11 @@ ftGdiGetGlyphOutline(
     if (error)
     {
         DPRINT1("WARNING: Failed to load and render glyph! [index: %u]\n", glyph_index);
-        IntUnLockFreeType;
+        IntUnLockFreeType();
         if (potm) ExFreePoolWithTag(potm, GDITAG_TEXT);
         return GDI_ERROR;
     }
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     if (aveWidth && potm)
     {
@@ -3221,15 +3322,25 @@ ftGdiGetGlyphOutline(
 
     DPRINT("Advance = %d, lsb = %d, bbx = %d\n",adv, lsb, bbx);
 
-    IntLockFreeType;
+    IntLockFreeType();
 
-    /* Scaling transform */
-    /*if (aveWidth)*/
+    /* Width scaling transform */
+    if (widthRatio != 1.0)
     {
+        FT_Matrix scaleMat;
+        scaleMat.xx = FT_FixedFromFloat(widthRatio);
+        scaleMat.xy = 0;
+        scaleMat.yx = 0;
+        scaleMat.yy = FT_FixedFromFloat(1.0);
+
+        FT_Matrix_Multiply(&scaleMat, &transMat);
+        needsTransform = TRUE;
+    }
 
+    /* World transform */
+    {
         FT_Matrix ftmatrix;
         FLOATOBJ efTemp;
-
         PMATRIX pmx = DC_pmxWorldToDevice(dc);
 
         /* Create a freetype matrix, by converting to 16.16 fixpoint format */
@@ -3249,8 +3360,11 @@ ftGdiGetGlyphOutline(
         FLOATOBJ_MulLong(&efTemp, 0x00010000);
         ftmatrix.yy = FLOATOBJ_GetLong(&efTemp);
 
-        FT_Matrix_Multiply(&ftmatrix, &transMat);
-        needsTransform = TRUE;
+        if (memcmp(&ftmatrix, &identityMat, sizeof(identityMat)) != 0)
+        {
+            FT_Matrix_Multiply(&ftmatrix, &transMat);
+            needsTransform = TRUE;
+        }
     }
 
     /* Rotation transform */
@@ -3343,7 +3457,7 @@ ftGdiGetGlyphOutline(
            gm.gmBlackBoxX, gm.gmBlackBoxY,
            gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);
 
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
 
     if (iFormat == GGO_METRICS)
@@ -3395,7 +3509,7 @@ ftGdiGetGlyphOutline(
             ft_bitmap.pixel_mode = FT_PIXEL_MODE_MONO;
             ft_bitmap.buffer = pvBuf;
 
-            IntLockFreeType;
+            IntLockFreeType();
             if (needsTransform)
             {
                 FT_Outline_Transform(&ft_face->glyph->outline, &transMat);
@@ -3403,8 +3517,8 @@ ftGdiGetGlyphOutline(
             FT_Outline_Translate(&ft_face->glyph->outline, -left, -bottom );
             /* Note: FreeType will only set 'black' bits for us. */
             RtlZeroMemory(pvBuf, needed);
-            FT_Outline_Get_Bitmap(library, &ft_face->glyph->outline, &ft_bitmap);
-            IntUnLockFreeType;
+            FT_Outline_Get_Bitmap(g_FreeTypeLibrary, &ft_face->glyph->outline, &ft_bitmap);
+            IntUnLockFreeType();
             break;
 
         default:
@@ -3459,15 +3573,15 @@ ftGdiGetGlyphOutline(
             ft_bitmap.pixel_mode = FT_PIXEL_MODE_GRAY;
             ft_bitmap.buffer = pvBuf;
 
-            IntLockFreeType;
+            IntLockFreeType();
             if (needsTransform)
             {
                 FT_Outline_Transform(&ft_face->glyph->outline, &transMat);
             }
             FT_Outline_Translate(&ft_face->glyph->outline, -left, -bottom );
             RtlZeroMemory(ft_bitmap.buffer, cjBuf);
-            FT_Outline_Get_Bitmap(library, &ft_face->glyph->outline, &ft_bitmap);
-            IntUnLockFreeType;
+            FT_Outline_Get_Bitmap(g_FreeTypeLibrary, &ft_face->glyph->outline, &ft_bitmap);
+            IntUnLockFreeType();
 
             if (iFormat == GGO_GRAY2_BITMAP)
                 mult = 4;
@@ -3505,23 +3619,23 @@ ftGdiGetGlyphOutline(
 
         if (cjBuf == 0) pvBuf = NULL; /* This is okay, need cjBuf to allocate. */
 
-        IntLockFreeType;
+        IntLockFreeType();
         if (needsTransform && pvBuf) FT_Outline_Transform(outline, &transMat);
 
         needed = get_native_glyph_outline(outline, cjBuf, NULL);
 
         if (!pvBuf || !cjBuf)
         {
-            IntUnLockFreeType;
+            IntUnLockFreeType();
             break;
         }
         if (needed > cjBuf)
         {
-            IntUnLockFreeType;
+            IntUnLockFreeType();
             return GDI_ERROR;
         }
         get_native_glyph_outline(outline, cjBuf, pvBuf);
-        IntUnLockFreeType;
+        IntUnLockFreeType();
         break;
     }
     case GGO_BEZIER:
@@ -3531,9 +3645,9 @@ ftGdiGetGlyphOutline(
 
         if (needsTransform && pvBuf)
         {
-            IntLockFreeType;
+            IntLockFreeType();
             FT_Outline_Transform(outline, &transMat);
-            IntUnLockFreeType;
+            IntUnLockFreeType();
         }
         needed = get_bezier_glyph_outline(outline, cjBuf, NULL);
 
@@ -3590,7 +3704,7 @@ TextIntGetTextExtentPoint(PDC dc,
         *Fit = 0;
     }
 
-    IntLockFreeType;
+    IntLockFreeType();
 
     TextIntUpdateSize(dc, TextObj, FontGDI, FALSE);
 
@@ -3687,9 +3801,10 @@ TextIntGetTextExtentPoint(PDC dc,
         previous = glyph_index;
         String++;
     }
-    ascender = (face->size->metrics.ascender + 32) >> 6; /* Units above baseline */
-    descender = (32 - face->size->metrics.descender) >> 6; /* Units below baseline */
-    IntUnLockFreeType;
+    ASSERT(FontGDI->Magic == FONTGDI_MAGIC);
+    ascender = FontGDI->tmAscent; /* Units above baseline */
+    descender = FontGDI->tmDescent; /* Units below baseline */
+    IntUnLockFreeType();
 
     Size->cx = (TotalWidth + 32) >> 6;
     Size->cy = ascender + descender;
@@ -3731,9 +3846,9 @@ ftGdiGetTextCharsetInfo(
     Face = FontGdi->SharedFace->Face;
     TEXTOBJ_UnlockText(TextObj);
 
-    IntLockFreeType;
+    IntLockFreeType();
     pOS2 = FT_Get_Sfnt_Table(Face, ft_sfnt_os2);
-    IntUnLockFreeType;
+    IntUnLockFreeType();
     memset(&fs, 0, sizeof(FONTSIGNATURE));
     if (NULL != pOS2)
     {
@@ -3915,10 +4030,12 @@ ftGdiGetTextMetricsW(
         FontGDI = ObjToGDI(TextObj->Font, FONT);
 
         Face = FontGDI->SharedFace->Face;
-        IntLockFreeType;
-        Error = IntRequestFontSize(dc, Face, plf->lfWidth, plf->lfHeight);
+
+        IntLockFreeType();
+        Error = IntRequestFontSize(dc, FontGDI, plf->lfWidth, plf->lfHeight);
         FtSetCoordinateTransform(Face, DC_pmxWorldToDevice(dc));
-        IntUnLockFreeType;
+        IntUnLockFreeType();
+
         if (0 != Error)
         {
             DPRINT1("Error in setting pixel sizes: %u\n", Error);
@@ -3929,7 +4046,7 @@ ftGdiGetTextMetricsW(
             FT_Face Face = FontGDI->SharedFace->Face;
             Status = STATUS_SUCCESS;
 
-            IntLockFreeType;
+            IntLockFreeType();
             pOS2 = FT_Get_Sfnt_Table(Face, ft_sfnt_os2);
             if (NULL == pOS2)
             {
@@ -3946,7 +4063,7 @@ ftGdiGetTextMetricsW(
 
             Error = FT_Get_WinFNT_Header(Face, &Win);
 
-            IntUnLockFreeType;
+            IntUnLockFreeType();
 
             if (NT_SUCCESS(Status))
             {
@@ -3984,7 +4101,7 @@ ftGdiGetFontData(
     DWORD Result = GDI_ERROR;
     FT_Face Face = FontGdi->SharedFace->Face;
 
-    IntLockFreeType;
+    IntLockFreeType();
 
     if (FT_IS_SFNT(Face))
     {
@@ -4007,7 +4124,7 @@ ftGdiGetFontData(
             Result = Size;
     }
 
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     return Result;
 }
@@ -4028,9 +4145,7 @@ GetFontPenalty(const LOGFONTW *               LogFont,
 
     ASSERT(Otm);
     ASSERT(LogFont);
-    ASSERT(style_name);
 
-    /* FIXME: Aspect Penalty 30 */
     /* FIXME: IntSizeSynth Penalty 20 */
     /* FIXME: SmallPenalty Penalty 1 */
     /* FIXME: FaceNameSubst Penalty 500 */
@@ -4101,7 +4216,7 @@ GetFontPenalty(const LOGFONTW *               LogFont,
     Byte = (LogFont->lfPitchAndFamily & 0x0F);
     if (Byte == DEFAULT_PITCH)
         Byte = VARIABLE_PITCH;
-    if (Byte == FIXED_PITCH)
+    if ((Byte & FIXED_PITCH) || (Byte & MONO_FONT))
     {
         if (TM->tmPitchAndFamily & _TMPF_VARIABLE_PITCH)
         {
@@ -4111,7 +4226,7 @@ GetFontPenalty(const LOGFONTW *               LogFont,
             Penalty += 15000;
         }
     }
-    if (Byte == VARIABLE_PITCH)
+    if (Byte & VARIABLE_PITCH)
     {
         if (!(TM->tmPitchAndFamily & _TMPF_VARIABLE_PITCH))
         {
@@ -4162,12 +4277,37 @@ GetFontPenalty(const LOGFONTW *               LogFont,
     Byte = (LogFont->lfPitchAndFamily & 0xF0);
     if (Byte != FF_DONTCARE)
     {
-        if (Byte != (TM->tmPitchAndFamily & 0xF0))
+        if (Byte & FF_MODERN)
+        {
+            if (TM->tmPitchAndFamily & _TMPF_VARIABLE_PITCH)
+            {
+                /* FixedPitch Penalty 15000 */
+                /* Requested a fixed pitch font, but the candidate is a
+                   variable pitch font. */
+                Penalty += 15000;
+            }
+        }
+
+        if ((Byte & FF_ROMAN) || (Byte & FF_SWISS))
+        {
+            if (!(TM->tmPitchAndFamily & _TMPF_VARIABLE_PITCH))
+            {
+                /* PitchVariable Penalty 350 */
+                /* Requested a variable pitch font, but the candidate is not a
+                   variable pitch font. */
+                Penalty += 350;
+            }
+        }
+
+#define FF_MASK  (FF_DECORATIVE | FF_SCRIPT | FF_SWISS)
+        if ((Byte & FF_MASK) != (TM->tmPitchAndFamily & FF_MASK))
         {
             /* Family Penalty 9000 */
             /* Requested a family, but the candidate's family is different. */
             Penalty += 9000;
         }
+#undef FF_MASK
+
         if ((TM->tmPitchAndFamily & 0xF0) == FF_DONTCARE)
         {
             /* FamilyUnknown Penalty 8000 */
@@ -4342,6 +4482,22 @@ GetFontPenalty(const LOGFONTW *               LogFont,
         Penalty += 2;
     }
 
+    if (TM->tmAveCharWidth >= 5 && TM->tmHeight >= 5)
+    {
+        if (TM->tmAveCharWidth / TM->tmHeight >= 3)
+        {
+            /* Aspect Penalty 30 */
+            /* The aspect rate is >= 3. It seems like a bad font. */
+            Penalty += ((TM->tmAveCharWidth / TM->tmHeight) - 2) * 30;
+        }
+        else if (TM->tmHeight / TM->tmAveCharWidth >= 3)
+        {
+            /* Aspect Penalty 30 */
+            /* The aspect rate is >= 3. It seems like a bad font. */
+            Penalty += ((TM->tmHeight / TM->tmAveCharWidth) - 2) * 30;
+        }
+    }
+
     if (Penalty < 200)
     {
         DPRINT("WARNING: Penalty:%ld < 200: RequestedNameW:%ls, "
@@ -4400,6 +4556,10 @@ FindBestFontFromList(FONTOBJ **FontObj, ULONG *MatchPenalty,
         /* update FontObj if lowest penalty */
         if (Otm)
         {
+            IntLockFreeType();
+            IntRequestFontSize(NULL, FontGDI, LogFont->lfWidth, LogFont->lfHeight);
+            IntUnLockFreeType();
+
             OtmSize = IntGetOutlineTextMetrics(FontGDI, OtmSize, Otm);
             if (!OtmSize)
                 continue;
@@ -4502,10 +4662,10 @@ TextIntRealizeFont(HFONT FontHandle, PTEXTOBJ pTextObj)
     IntUnLockProcessPrivateFonts(Win32Process);
 
     /* Search system fonts */
-    IntLockGlobalFonts;
+    IntLockGlobalFonts();
     FindBestFontFromList(&TextObj->Font, &MatchPenalty, &SubstitutedLogFont,
-                         &FontListHead);
-    IntUnLockGlobalFonts;
+                         &g_FontListHead);
+    IntUnLockGlobalFonts();
 
     if (NULL == TextObj->Font)
     {
@@ -4515,7 +4675,23 @@ TextIntRealizeFont(HFONT FontHandle, PTEXTOBJ pTextObj)
     }
     else
     {
+        UNICODE_STRING FaceName;
         PFONTGDI FontGdi = ObjToGDI(TextObj->Font, FONT);
+
+        IntLockFreeType();
+        IntRequestFontSize(NULL, FontGdi, pLogFont->lfWidth, pLogFont->lfHeight);
+        IntUnLockFreeType();
+
+        RtlInitUnicodeString(&FaceName, NULL);
+        IntGetFontLocalizedName(&FaceName, FontGdi->SharedFace, TT_NAME_ID_FONT_FAMILY, gusLanguageID);
+
+        /* truncated copy */
+        FaceName.Length = (USHORT)min(FaceName.Length, (LF_FACESIZE - 1) * sizeof(WCHAR));
+        FaceName.MaximumLength = (USHORT)(FaceName.Length + sizeof(UNICODE_NULL));
+        RtlCopyMemory(TextObj->FaceName, FaceName.Buffer, FaceName.MaximumLength);
+
+        RtlFreeUnicodeString(&FaceName);
+
         // Need hdev, when freetype is loaded need to create DEVOBJ for
         // Consumer and Producer.
         TextObj->Font->iUniq = 1; // Now it can be cached.
@@ -4684,8 +4860,8 @@ IntGdiGetFontResourceInfo(
     }
     /* Try to find the pathname in the global font list */
     Count = 0;
-    IntLockGlobalFonts;
-    for (ListEntry = FontListHead.Flink; ListEntry != &FontListHead;
+    IntLockGlobalFonts();
+    for (ListEntry = g_FontListHead.Flink; ListEntry != &g_FontListHead;
          ListEntry = ListEntry->Flink)
     {
         FontEntry = CONTAINING_RECORD(ListEntry, FONT_ENTRY, ListEntry);
@@ -4718,7 +4894,7 @@ IntGdiGetFontResourceInfo(
                 break;
         }
     }
-    IntUnLockGlobalFonts;
+    IntUnLockGlobalFonts();
 
     /* Free the buffers */
     ExFreePoolWithTag(NameInfo1, TAG_FINF);
@@ -4937,7 +5113,7 @@ ftGdiGetKerningPairs( PFONTGDI Font,
 
         char_previous = char_code = FT_Get_First_Char(face, &glyph_index);
 
-        IntLockFreeType;
+        IntLockFreeType();
 
         while (glyph_index)
         {
@@ -4959,7 +5135,7 @@ ftGdiGetKerningPairs( PFONTGDI Font,
             char_previous = char_code;
             char_code = FT_Get_Next_Char(face, char_code, &glyph_index);
         }
-        IntUnLockFreeType;
+        IntUnLockFreeType();
     }
     return Count;
 }
@@ -4999,15 +5175,15 @@ NtGdiGetFontFamilyInfo(HDC Dc,
     }
 
     /* Enumerate font families in the global list */
-    IntLockGlobalFonts;
+    IntLockGlobalFonts();
     Count = 0;
-    if (! GetFontFamilyInfoForList(&LogFont, Info, &Count, Size, &FontListHead) )
+    if (! GetFontFamilyInfoForList(&LogFont, Info, &Count, Size, &g_FontListHead) )
     {
-        IntUnLockGlobalFonts;
+        IntUnLockGlobalFonts();
         ExFreePoolWithTag(Info, GDITAG_TEXT);
         return -1;
     }
-    IntUnLockGlobalFonts;
+    IntUnLockGlobalFonts();
 
     /* Enumerate font families in the process local list */
     Win32Process = PsGetCurrentProcessWin32Process();
@@ -5248,7 +5424,7 @@ GreExtTextOutW(
     FontGDI = ObjToGDI(FontObj, FONT);
     ASSERT(FontGDI);
 
-    IntLockFreeType;
+    IntLockFreeType();
     face = FontGDI->SharedFace->Face;
 
     plf = &TextObj->logfont.elfEnumLogfontEx.elfLogFont;
@@ -5262,38 +5438,40 @@ GreExtTextOutW(
 
     if (!TextIntUpdateSize(dc, TextObj, FontGDI, FALSE))
     {
-        IntUnLockFreeType;
+        IntUnLockFreeType();
         bResult = FALSE;
         goto Cleanup;
     }
 
+    /* NOTE: Don't trust face->size->metrics.ascender and descender values. */
     if (dc->pdcattr->iGraphicsMode == GM_ADVANCED)
     {
         pmxWorldToDevice = DC_pmxWorldToDevice(dc);
         FtSetCoordinateTransform(face, pmxWorldToDevice);
 
-        fixAscender = ScaleLong(face->size->metrics.ascender, &pmxWorldToDevice->efM22);
-        fixDescender = ScaleLong(face->size->metrics.descender, &pmxWorldToDevice->efM22);
+        fixAscender = ScaleLong(FontGDI->tmAscent, &pmxWorldToDevice->efM22) << 6;
+        fixDescender = ScaleLong(FontGDI->tmDescent, &pmxWorldToDevice->efM22) << 6;
     }
     else
     {
         pmxWorldToDevice = (PMATRIX)&gmxWorldToDeviceDefault;
         FtSetCoordinateTransform(face, pmxWorldToDevice);
 
-        fixAscender = face->size->metrics.ascender;
-        fixDescender = face->size->metrics.descender;
+        fixAscender = FontGDI->tmAscent << 6;
+        fixDescender = FontGDI->tmDescent << 6;
     }
 
     /*
      * Process the vertical alignment and determine the yoff.
      */
-
-    if (pdcattr->lTextAlign & TA_BASELINE)
+#define VALIGN_MASK  (TA_TOP | TA_BASELINE | TA_BOTTOM)
+    if ((pdcattr->lTextAlign & VALIGN_MASK) == TA_BASELINE)
         yoff = 0;
-    else if (pdcattr->lTextAlign & TA_BOTTOM)
-        yoff = -fixDescender >> 6;
+    else if ((pdcattr->lTextAlign & VALIGN_MASK) == TA_BOTTOM)
+        yoff = -(fixDescender >> 6);
     else /* TA_TOP */
         yoff = fixAscender >> 6;
+#undef VALIGN_MASK
 
     use_kerning = FT_HAS_KERNING(face);
     previous = 0;
@@ -5364,7 +5542,7 @@ GreExtTextOutW(
                 if (!realglyph)
                 {
                     DPRINT1("Failed to render glyph! [index: %d]\n", glyph_index);
-                    IntUnLockFreeType;
+                    IntUnLockFreeType();
                     goto Cleanup;
                 }
 
@@ -5439,7 +5617,7 @@ GreExtTextOutW(
             if (error)
             {
                 DPRINT1("Failed to load and render glyph! [index: %d]\n", glyph_index);
-                IntUnLockFreeType;
+                IntUnLockFreeType();
                 goto Cleanup;
             }
 
@@ -5452,7 +5630,7 @@ GreExtTextOutW(
             if (!realglyph)
             {
                 DPRINT1("Failed to render glyph! [index: %d]\n", glyph_index);
-                IntUnLockFreeType;
+                IntUnLockFreeType();
                 goto Cleanup;
             }
 
@@ -5470,7 +5648,7 @@ GreExtTextOutW(
             DestRect.left = BackgroundLeft;
             DestRect.right = (TextLeft + (realglyph->root.advance.x >> 10) + 32) >> 6;
             DestRect.top = TextTop + yoff - ((fixAscender + 32) >> 6);
-            DestRect.bottom = TextTop + yoff + ((32 - fixDescender) >> 6);
+            DestRect.bottom = DestRect.top + ((fixAscender + fixDescender) >> 6);
             MouseSafetyOnDrawStart(dc->ppdev, DestRect.left, DestRect.top, DestRect.right, DestRect.bottom);
             if (dc->fs & (DC_ACCUM_APP|DC_ACCUM_WMGR))
             {
@@ -5610,7 +5788,7 @@ GreExtTextOutW(
             DestRect.left = BackgroundLeft;
             DestRect.right = (TextLeft + (realglyph->root.advance.x >> 10) + 32) >> 6;
             DestRect.top = TextTop + yoff - ((fixAscender + 32) >> 6);
-            DestRect.bottom = TextTop + yoff + ((32 - fixDescender) >> 6);
+            DestRect.bottom = DestRect.top + ((fixAscender + fixDescender) >> 6);
 
             if (dc->dctype == DCTYPE_DIRECT)
                 MouseSafetyOnDrawStart(dc->ppdev, DestRect.left, DestRect.top, DestRect.right, DestRect.bottom);
@@ -5801,7 +5979,7 @@ GreExtTextOutW(
         pdcattr->ptlCurrent.x = DestRect.right - dc->ptlDCOrig.x;
     }
 
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     EXLATEOBJ_vCleanup(&exloRGB2Dst);
     EXLATEOBJ_vCleanup(&exloDst2RGB);
@@ -6077,14 +6255,14 @@ NtGdiGetCharABCWidthsW(
             return FALSE;
         }
 
-        IntLockFreeType;
+        IntLockFreeType();
         FT_Set_Charmap(face, found);
-        IntUnLockFreeType;
+        IntUnLockFreeType();
     }
 
     plf = &TextObj->logfont.elfEnumLogfontEx.elfLogFont;
-    IntLockFreeType;
-    IntRequestFontSize(dc, face, plf->lfWidth, plf->lfHeight);
+    IntLockFreeType();
+    IntRequestFontSize(dc, FontGDI, plf->lfWidth, plf->lfHeight);
     FtSetCoordinateTransform(face, pmxWorldToDevice);
 
     for (i = FirstChar; i < FirstChar+Count; i++)
@@ -6132,7 +6310,7 @@ NtGdiGetCharABCWidthsW(
             SafeBuff[i - FirstChar].abcC = adv - lsb - bbx;
         }
     }
-    IntUnLockFreeType;
+    IntUnLockFreeType();
     TEXTOBJ_UnlockText(TextObj);
     Status = MmCopyToCaller(Buffer, SafeBuff, BufferSize);
 
@@ -6273,14 +6451,14 @@ NtGdiGetCharWidthW(
             return FALSE;
         }
 
-        IntLockFreeType;
+        IntLockFreeType();
         FT_Set_Charmap(face, found);
-        IntUnLockFreeType;
+        IntUnLockFreeType();
     }
 
     plf = &TextObj->logfont.elfEnumLogfontEx.elfLogFont;
-    IntLockFreeType;
-    IntRequestFontSize(dc, face, plf->lfWidth, plf->lfHeight);
+    IntLockFreeType();
+    IntRequestFontSize(dc, FontGDI, plf->lfWidth, plf->lfHeight);
     FtSetCoordinateTransform(face, pmxWorldToDevice);
 
     for (i = FirstChar; i < FirstChar+Count; i++)
@@ -6305,7 +6483,7 @@ NtGdiGetCharWidthW(
         else
             SafeBuff[i - FirstChar] = (face->glyph->advance.x + 32) >> 6;
     }
-    IntUnLockFreeType;
+    IntUnLockFreeType();
     TEXTOBJ_UnlockText(TextObj);
     MmCopyToCaller(Buffer, SafeBuff, BufferSize);
 
@@ -6449,7 +6627,7 @@ NtGdiGetGlyphIndicesW(
 
     if (!NT_SUCCESS(Status)) goto ErrorRet;
 
-    IntLockFreeType;
+    IntLockFreeType();
 
     for (i = 0; i < cwc; i++)
     {
@@ -6460,7 +6638,7 @@ NtGdiGetGlyphIndicesW(
         }
     }
 
-    IntUnLockFreeType;
+    IntUnLockFreeType();
 
     _SEH2_TRY
     {