[WIN32SS][NTGDI] Correctly get/update ptlCurrent about TA_UPDATECP
[reactos.git] / win32ss / gdi / ntgdi / freetype.c
index e24e79c..f73c1c0 100644 (file)
@@ -43,6 +43,7 @@
 
 extern const MATRIX gmxWorldToDeviceDefault;
 extern const MATRIX gmxWorldToPageDefault;
+static const FT_Matrix identityMat = {(1 << 16), 0, 0, (1 << 16)};
 
 /* HACK!! Fix XFORMOBJ then use 1:16 / 16:1 */
 #define gmxWorldToDeviceDefault gmxWorldToPageDefault
@@ -335,6 +336,39 @@ SharedFace_Release(PSHARED_FACE Ptr)
     IntUnLockFreeType();
 }
 
+
+static __inline void FTVectorToPOINTFX(FT_Vector *vec, POINTFX *pt)
+{
+    pt->x.value = vec->x >> 6;
+    pt->x.fract = (vec->x & 0x3f) << 10;
+    pt->x.fract |= ((pt->x.fract >> 6) | (pt->x.fract >> 12));
+    pt->y.value = vec->y >> 6;
+    pt->y.fract = (vec->y & 0x3f) << 10;
+    pt->y.fract |= ((pt->y.fract >> 6) | (pt->y.fract >> 12));
+}
+
+/*
+   This function builds an FT_Fixed from a float. It puts the integer part
+   in the highest 16 bits and the decimal part in the lowest 16 bits of the FT_Fixed.
+   It fails if the integer part of the float number is greater than SHORT_MAX.
+*/
+static __inline FT_Fixed FT_FixedFromFloat(FLOAT f)
+{
+    short value = f;
+    unsigned short fract = (f - value) * 0xFFFF;
+    return (FT_Fixed)((long)value << 16 | (unsigned long)fract);
+}
+
+/*
+   This function builds an FT_Fixed from a FIXED. It simply put f.value
+   in the highest 16 bits and f.fract in the lowest 16 bits of the FT_Fixed.
+*/
+static __inline FT_Fixed FT_FixedFromFIXED(FIXED f)
+{
+    return (FT_Fixed)((long)f.value << 16 | (unsigned long)f.fract);
+}
+
+
 #if DBG
 VOID DumpFontGDI(PFONTGDI FontGDI)
 {
@@ -650,33 +684,82 @@ InitFontSupport(VOID)
     return TRUE;
 }
 
-VOID
-FtSetCoordinateTransform(
-    FT_Face face,
-    PMATRIX pmx)
+VOID FASTCALL IntWidthMatrix(FT_Face face, FT_Matrix *pmat, LONG lfWidth)
 {
-    FT_Matrix ftmatrix;
-    FLOATOBJ efTemp;
+    LONG tmAveCharWidth;
+    TT_OS2 *pOS2;
+    FT_Fixed XScale;
+
+    *pmat = identityMat;
+
+    if (lfWidth == 0)
+        return;
+
+    ASSERT_FREETYPE_LOCK_HELD();
+    pOS2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, FT_SFNT_OS2);
+    if (!pOS2)
+        return;
+
+    XScale = face->size->metrics.x_scale;
+    tmAveCharWidth = (FT_MulFix(pOS2->xAvgCharWidth, XScale) + 32) >> 6;
+    if (tmAveCharWidth == 0)
+    {
+        tmAveCharWidth = 1;
+    }
+
+    if (lfWidth == tmAveCharWidth)
+        return;
+
+    pmat->xx = (FT_Fixed)((1 << 16) * lfWidth / tmAveCharWidth);
+    pmat->xy = 0;
+    pmat->yx = 0;
+    pmat->yy = (FT_Fixed)(1 << 16);
+}
+
+VOID FASTCALL IntEscapeMatrix(FT_Matrix *pmat, LONG lfEscapement)
+{
+    FT_Vector vecAngle;
+    FT_Angle angle = FT_FixedFromFloat((FLOAT)(lfEscapement * M_PI) / (FLOAT)(180 * 10));
+    FT_Vector_Unit(&vecAngle, angle);
+    pmat->xx = vecAngle.x;
+    pmat->xy = -vecAngle.y;
+    pmat->yx = -pmat->xy;
+    pmat->yy = pmat->xx;
+}
+
+VOID FASTCALL
+FtMatrixFromMx(FT_Matrix *pmat, PMATRIX pmx)
+{
+    FLOATOBJ ef;
 
     /* Create a freetype matrix, by converting to 16.16 fixpoint format */
-    efTemp = pmx->efM11;
-    FLOATOBJ_MulLong(&efTemp, 0x00010000);
-    ftmatrix.xx = FLOATOBJ_GetLong(&efTemp);
+    ef = pmx->efM11;
+    FLOATOBJ_MulLong(&ef, 0x00010000);
+    pmat->xx = FLOATOBJ_GetLong(&ef);
 
-    efTemp = pmx->efM12;
-    FLOATOBJ_MulLong(&efTemp, 0x00010000);
-    ftmatrix.xy = FLOATOBJ_GetLong(&efTemp);
+    ef = pmx->efM21;
+    FLOATOBJ_MulLong(&ef, 0x00010000);
+    pmat->xy = FLOATOBJ_GetLong(&ef);
 
-    efTemp = pmx->efM21;
-    FLOATOBJ_MulLong(&efTemp, 0x00010000);
-    ftmatrix.yx = FLOATOBJ_GetLong(&efTemp);
+    ef = pmx->efM12;
+    FLOATOBJ_MulLong(&ef, 0x00010000);
+    pmat->yx = FLOATOBJ_GetLong(&ef);
 
-    efTemp = pmx->efM22;
-    FLOATOBJ_MulLong(&efTemp, 0x00010000);
-    ftmatrix.yy = FLOATOBJ_GetLong(&efTemp);
+    ef = pmx->efM22;
+    FLOATOBJ_MulLong(&ef, 0x00010000);
+    pmat->yy = FLOATOBJ_GetLong(&ef);
+}
+
+FORCEINLINE VOID FASTCALL
+FtSetCoordinateTransform(
+    FT_Face face,
+    PMATRIX pmx)
+{
+    FT_Matrix mat;
+    FtMatrixFromMx(&mat, pmx);
 
     /* Set the transformation matrix */
-    FT_Set_Transform(face, &ftmatrix, 0);
+    FT_Set_Transform(face, &mat, 0);
 }
 
 static BOOL
@@ -1592,14 +1675,7 @@ IntGdiCleanupPrivateFontsForProcess(VOID)
 BOOL FASTCALL
 IntIsFontRenderingEnabled(VOID)
 {
-    BOOL Ret = g_RenderingEnabled;
-    HDC hDC;
-
-    hDC = IntGetScreenDC();
-    if (hDC)
-        Ret = (NtGdiGetDeviceCaps(hDC, BITSPIXEL) > 8) && g_RenderingEnabled;
-
-    return Ret;
+    return (gpsi->BitsPixel > 8) && g_RenderingEnabled;
 }
 
 VOID FASTCALL
@@ -1619,8 +1695,12 @@ IntGetFontRenderMode(LOGFONTW *logfont)
         return FT_RENDER_MODE_MONO;
     case DRAFT_QUALITY:
         return FT_RENDER_MODE_LIGHT;
-        /*    case CLEARTYPE_QUALITY:
-                return FT_RENDER_MODE_LCD; */
+    case CLEARTYPE_QUALITY:
+        if (!gspv.bFontSmoothing)
+            break;
+        if (!gspv.uiFontSmoothingType)
+            break;
+        return FT_RENDER_MODE_LCD;
     }
     return FT_RENDER_MODE_NORMAL;
 }
@@ -2202,73 +2282,6 @@ IntGetOutlineTextMetrics(PFONTGDI FontGDI,
     return Cache->OutlineRequiredSize;
 }
 
-static PFONTGDI FASTCALL
-FindFaceNameInList(PUNICODE_STRING FaceName, PLIST_ENTRY Head)
-{
-    PLIST_ENTRY Entry;
-    PFONT_ENTRY CurrentEntry;
-    ANSI_STRING EntryFaceNameA;
-    UNICODE_STRING EntryFaceNameW;
-    FONTGDI *FontGDI;
-    NTSTATUS status;
-
-    for (Entry = Head->Flink; Entry != Head; Entry = Entry->Flink)
-    {
-        CurrentEntry = CONTAINING_RECORD(Entry, FONT_ENTRY, ListEntry);
-
-        FontGDI = CurrentEntry->Font;
-        ASSERT(FontGDI);
-
-        RtlInitAnsiString(&EntryFaceNameA, FontGDI->SharedFace->Face->family_name);
-        status = RtlAnsiStringToUnicodeString(&EntryFaceNameW, &EntryFaceNameA, TRUE);
-        if (!NT_SUCCESS(status))
-        {
-            break;
-        }
-
-        if ((LF_FACESIZE - 1) * sizeof(WCHAR) < EntryFaceNameW.Length)
-        {
-            EntryFaceNameW.Length = (LF_FACESIZE - 1) * sizeof(WCHAR);
-            EntryFaceNameW.Buffer[LF_FACESIZE - 1] = L'\0';
-        }
-
-        if (RtlEqualUnicodeString(FaceName, &EntryFaceNameW, TRUE))
-        {
-            RtlFreeUnicodeString(&EntryFaceNameW);
-            return FontGDI;
-        }
-
-        RtlFreeUnicodeString(&EntryFaceNameW);
-    }
-
-    return NULL;
-}
-
-static PFONTGDI FASTCALL
-FindFaceNameInLists(PUNICODE_STRING FaceName)
-{
-    PPROCESSINFO Win32Process;
-    PFONTGDI Font;
-
-    /* Search the process local list.
-       We do not have to search the 'Mem' list, since those fonts are linked in the PrivateFontListHead */
-    Win32Process = PsGetCurrentProcessWin32Process();
-    IntLockProcessPrivateFonts(Win32Process);
-    Font = FindFaceNameInList(FaceName, &Win32Process->PrivateFontListHead);
-    IntUnLockProcessPrivateFonts(Win32Process);
-    if (NULL != Font)
-    {
-        return Font;
-    }
-
-    /* Search the global list */
-    IntLockGlobalFonts();
-    Font = FindFaceNameInList(FaceName, &g_FontListHead);
-    IntUnLockGlobalFonts();
-
-    return Font;
-}
-
 /* See https://msdn.microsoft.com/en-us/library/bb165625(v=vs.90).aspx */
 static BYTE
 CharSetFromLangID(LANGID LangID)
@@ -2695,76 +2708,19 @@ FontFamilyFillInfo(PFONTFAMILYINFO Info, LPCWSTR FaceName,
     Info->NewTextMetricEx.ntmFontSig = fs;
 }
 
-static int FASTCALL
-FindFaceNameInInfo(PUNICODE_STRING FaceName, PFONTFAMILYINFO Info, DWORD InfoEntries)
-{
-    DWORD i;
-    UNICODE_STRING InfoFaceName;
-
-    for (i = 0; i < InfoEntries; i++)
-    {
-        RtlInitUnicodeString(&InfoFaceName, Info[i].EnumLogFontEx.elfLogFont.lfFaceName);
-        if (RtlEqualUnicodeString(&InfoFaceName, FaceName, TRUE))
-        {
-            return i;
-        }
-    }
-
-    return -1;
-}
-
-static BOOLEAN FASTCALL
-FontFamilyInclude(LPLOGFONTW LogFont, PUNICODE_STRING FaceName,
-                  PFONTFAMILYINFO Info, DWORD InfoEntries)
-{
-    UNICODE_STRING LogFontFaceName;
-
-    RtlInitUnicodeString(&LogFontFaceName, LogFont->lfFaceName);
-    if (0 != LogFontFaceName.Length &&
-        !RtlEqualUnicodeString(&LogFontFaceName, FaceName, TRUE))
-    {
-        return FALSE;
-    }
-
-    return FindFaceNameInInfo(FaceName, Info, InfoEntries) < 0;
-}
-
-static BOOL FASTCALL
-FontFamilyFound(PFONTFAMILYINFO InfoEntry,
-                PFONTFAMILYINFO Info, DWORD InfoCount)
-{
-    LPLOGFONTW plf1 = &InfoEntry->EnumLogFontEx.elfLogFont;
-    LPWSTR pFullName1 = InfoEntry->EnumLogFontEx.elfFullName;
-    LPWSTR pFullName2;
-    DWORD i;
-
-    for (i = 0; i < InfoCount; ++i)
-    {
-        LPLOGFONTW plf2 = &Info[i].EnumLogFontEx.elfLogFont;
-        if (plf1->lfCharSet != plf2->lfCharSet)
-            continue;
-
-        pFullName2 = Info[i].EnumLogFontEx.elfFullName;
-        if (_wcsicmp(pFullName1, pFullName2) != 0)
-            continue;
-
-        return TRUE;
-    }
-    return FALSE;
-}
-
 static BOOLEAN FASTCALL
-GetFontFamilyInfoForList(LPLOGFONTW LogFont,
+GetFontFamilyInfoForList(const LOGFONTW *LogFont,
                          PFONTFAMILYINFO Info,
-                         DWORD *pCount,
-                         DWORD MaxCount,
+                         LPCWSTR NominalName,
+                         LONG *pCount,
+                         LONG MaxCount,
                          PLIST_ENTRY Head)
 {
     PLIST_ENTRY Entry;
     PFONT_ENTRY CurrentEntry;
     FONTGDI *FontGDI;
     FONTFAMILYINFO InfoEntry;
-    DWORD Count = *pCount;
+    LONG Count = *pCount;
 
     for (Entry = Head->Flink; Entry != Head; Entry = Entry->Flink)
     {
@@ -2775,35 +2731,40 @@ GetFontFamilyInfoForList(LPLOGFONTW LogFont,
         if (LogFont->lfCharSet != DEFAULT_CHARSET &&
             LogFont->lfCharSet != FontGDI->CharSet)
         {
-            continue;
+            continue;   /* charset mismatch */
         }
 
-        if (LogFont->lfFaceName[0] == UNICODE_NULL)
+        /* get one info entry */
+        FontFamilyFillInfo(&InfoEntry, NULL, NULL, FontGDI);
+
+        if (LogFont->lfFaceName[0] != UNICODE_NULL)
         {
-            if (Count < MaxCount)
+            /* check name */
+            if (_wcsnicmp(LogFont->lfFaceName,
+                          InfoEntry.EnumLogFontEx.elfLogFont.lfFaceName,
+                          RTL_NUMBER_OF(LogFont->lfFaceName) - 1) != 0 &&
+                _wcsnicmp(LogFont->lfFaceName,
+                          InfoEntry.EnumLogFontEx.elfFullName,
+                          RTL_NUMBER_OF(LogFont->lfFaceName) - 1) != 0)
             {
-                FontFamilyFillInfo(&Info[Count], NULL, NULL, FontGDI);
+                continue;
             }
-            Count++;
-            continue;
         }
 
-        FontFamilyFillInfo(&InfoEntry, NULL, NULL, FontGDI);
-
-        if (_wcsnicmp(LogFont->lfFaceName, InfoEntry.EnumLogFontEx.elfLogFont.lfFaceName, RTL_NUMBER_OF(LogFont->lfFaceName)-1) != 0 &&
-            _wcsnicmp(LogFont->lfFaceName, InfoEntry.EnumLogFontEx.elfFullName, RTL_NUMBER_OF(LogFont->lfFaceName)-1) != 0)
+        if (NominalName)
         {
-            continue;
+            /* store the nominal name */
+            RtlStringCbCopyW(InfoEntry.EnumLogFontEx.elfLogFont.lfFaceName,
+                             sizeof(InfoEntry.EnumLogFontEx.elfLogFont.lfFaceName),
+                             NominalName);
         }
 
-        if (!FontFamilyFound(&InfoEntry, Info, min(Count, MaxCount)))
+        /* store one entry to Info */
+        if (0 <= Count && Count < MaxCount)
         {
-            if (Count < MaxCount)
-            {
-                RtlCopyMemory(&Info[Count], &InfoEntry, sizeof(InfoEntry));
-            }
-            Count++;
+            RtlCopyMemory(&Info[Count], &InfoEntry, sizeof(InfoEntry));
         }
+        Count++;
     }
 
     *pCount = Count;
@@ -2812,17 +2773,16 @@ GetFontFamilyInfoForList(LPLOGFONTW LogFont,
 }
 
 static BOOLEAN FASTCALL
-GetFontFamilyInfoForSubstitutes(LPLOGFONTW LogFont,
+GetFontFamilyInfoForSubstitutes(const LOGFONTW *LogFont,
                                 PFONTFAMILYINFO Info,
-                                DWORD *pCount,
-                                DWORD MaxCount)
+                                LONG *pCount,
+                                LONG MaxCount)
 {
     PLIST_ENTRY pEntry, pHead = &g_FontSubstListHead;
     PFONTSUBST_ENTRY pCurrentEntry;
-    PUNICODE_STRING pFromW;
-    FONTGDI *FontGDI;
+    PUNICODE_STRING pFromW, pToW;
     LOGFONTW lf = *LogFont;
-    UNICODE_STRING NameW;
+    PPROCESSINFO Win32Process = PsGetCurrentProcessWin32Process();
 
     for (pEntry = pHead->Flink; pEntry != pHead; pEntry = pEntry->Flink)
     {
@@ -2831,25 +2791,43 @@ GetFontFamilyInfoForSubstitutes(LPLOGFONTW LogFont,
         pFromW = &pCurrentEntry->FontNames[FONTSUBST_FROM];
         if (LogFont->lfFaceName[0] != UNICODE_NULL)
         {
-            if (!FontFamilyInclude(LogFont, pFromW, Info, min(*pCount, MaxCount)))
+            /* check name */
+            if (_wcsicmp(LogFont->lfFaceName, pFromW->Buffer) != 0)
                 continue;   /* mismatch */
         }
 
+        pToW = &pCurrentEntry->FontNames[FONTSUBST_TO];
+        if (RtlEqualUnicodeString(pFromW, pToW, TRUE) &&
+            pCurrentEntry->CharSets[FONTSUBST_FROM] ==
+            pCurrentEntry->CharSets[FONTSUBST_TO])
+        {
+            /* identical mapping */
+            continue;
+        }
+
+        /* substitute and get the real name */
         IntUnicodeStringToBuffer(lf.lfFaceName, sizeof(lf.lfFaceName), pFromW);
         SubstituteFontRecurse(&lf);
+        if (LogFont->lfCharSet != DEFAULT_CHARSET && LogFont->lfCharSet != lf.lfCharSet)
+            continue;
 
-        RtlInitUnicodeString(&NameW, lf.lfFaceName);
-        FontGDI = FindFaceNameInLists(&NameW);
-        if (FontGDI == NULL)
-        {
-            continue;   /* no real font */
-        }
+        /* search in global fonts */
+        IntLockGlobalFonts();
+        GetFontFamilyInfoForList(&lf, Info, pFromW->Buffer, pCount, MaxCount, &g_FontListHead);
+        IntUnLockGlobalFonts();
 
-        if (*pCount < MaxCount)
+        /* search in private fonts */
+        IntLockProcessPrivateFonts(Win32Process);
+        GetFontFamilyInfoForList(&lf, Info, pFromW->Buffer, pCount, MaxCount,
+                                 &Win32Process->PrivateFontListHead);
+        IntUnLockProcessPrivateFonts(Win32Process);
+
+        if (LogFont->lfFaceName[0] != UNICODE_NULL)
         {
-            FontFamilyFillInfo(&Info[*pCount], pFromW->Buffer, NULL, FontGDI);
+            /* it's already matched to the exact name and charset if the name
+               was specified at here, then so don't scan more for another name */
+            break;
         }
-        (*pCount)++;
     }
 
     return TRUE;
@@ -3032,37 +3010,6 @@ ftGdiGlyphCacheSet(
 }
 
 
-static void FTVectorToPOINTFX(FT_Vector *vec, POINTFX *pt)
-{
-    pt->x.value = vec->x >> 6;
-    pt->x.fract = (vec->x & 0x3f) << 10;
-    pt->x.fract |= ((pt->x.fract >> 6) | (pt->x.fract >> 12));
-    pt->y.value = vec->y >> 6;
-    pt->y.fract = (vec->y & 0x3f) << 10;
-    pt->y.fract |= ((pt->y.fract >> 6) | (pt->y.fract >> 12));
-}
-
-/*
-   This function builds an FT_Fixed from a float. It puts the integer part
-   in the highest 16 bits and the decimal part in the lowest 16 bits of the FT_Fixed.
-   It fails if the integer part of the float number is greater than SHORT_MAX.
-*/
-static __inline FT_Fixed FT_FixedFromFloat(float f)
-{
-    short value = f;
-    unsigned short fract = (f - value) * 0xFFFF;
-    return (FT_Fixed)((long)value << 16 | (unsigned long)fract);
-}
-
-/*
-   This function builds an FT_Fixed from a FIXED. It simply put f.value
-   in the highest 16 bits and f.fract in the lowest 16 bits of the FT_Fixed.
-*/
-static __inline FT_Fixed FT_FixedFromFIXED(FIXED f)
-{
-    return (FT_Fixed)((long)f.value << 16 | (unsigned long)f.fract);
-}
-
 static unsigned int get_native_glyph_outline(FT_Outline *outline, unsigned int buflen, char *buf)
 {
     TTPOLYGONHEADER *pph;
@@ -3365,10 +3312,7 @@ IntRequestFontSize(PDC dc, PFONTGDI FontGDI, LONG lfWidth, LONG lfHeight)
     FontGDI->EmHeight = min(FontGDI->EmHeight, USHORT_MAX);
     FontGDI->Magic = FONTGDI_MAGIC;
 
-    if (lfHeight > 0)
-        EmHeight64 = (FontGDI->EmHeight << 6) + 31;
-    else
-        EmHeight64 = (FontGDI->EmHeight << 6);
+    EmHeight64 = (FontGDI->EmHeight << 6);
 
     req.type           = FT_SIZE_REQUEST_TYPE_NOMINAL;
     req.width          = 0;
@@ -3512,7 +3456,6 @@ ftGdiGetGlyphOutline(
     LPMAT2 pmat2,
     BOOL bIgnoreRotation)
 {
-    static const FT_Matrix identityMat = {(1 << 16), 0, 0, (1 << 16)};
     PDC_ATTR pdcattr;
     PTEXTOBJ TextObj;
     PFONTGDI FontGDI;
@@ -3608,7 +3551,7 @@ ftGdiGetGlyphOutline(
     if (aveWidth && potm)
     {
         widthRatio = (FLOAT)aveWidth * eM11 /
-                     (FLOAT) potm->otmTextMetrics.tmAveCharWidth;
+                     (FLOAT)potm->otmTextMetrics.tmAveCharWidth;
     }
 
     left = (INT)(ft_face->glyph->metrics.horiBearingX * widthRatio) & -64;
@@ -3639,25 +3582,10 @@ ftGdiGetGlyphOutline(
     /* World transform */
     {
         FT_Matrix ftmatrix;
-        FLOATOBJ efTemp;
         PMATRIX pmx = DC_pmxWorldToDevice(dc);
 
         /* Create a freetype matrix, by converting to 16.16 fixpoint format */
-        efTemp = pmx->efM11;
-        FLOATOBJ_MulLong(&efTemp, 0x00010000);
-        ftmatrix.xx = FLOATOBJ_GetLong(&efTemp);
-
-        efTemp = pmx->efM12;
-        FLOATOBJ_MulLong(&efTemp, 0x00010000);
-        ftmatrix.xy = FLOATOBJ_GetLong(&efTemp);
-
-        efTemp = pmx->efM21;
-        FLOATOBJ_MulLong(&efTemp, 0x00010000);
-        ftmatrix.yx = FLOATOBJ_GetLong(&efTemp);
-
-        efTemp = pmx->efM22;
-        FLOATOBJ_MulLong(&efTemp, 0x00010000);
-        ftmatrix.yy = FLOATOBJ_GetLong(&efTemp);
+        FtMatrixFromMx(&ftmatrix, pmx);
 
         if (memcmp(&ftmatrix, &identityMat, sizeof(identityMat)) != 0)
         {
@@ -3672,7 +3600,7 @@ ftGdiGetGlyphOutline(
         FT_Matrix rotationMat;
         FT_Vector vecAngle;
         DPRINT("Rotation Trans!\n");
-        angle = FT_FixedFromFloat((float)orientation / 10.0);
+        angle = FT_FixedFromFloat((FLOAT)orientation / 10.0);
         FT_Vector_Unit(&vecAngle, angle);
         rotationMat.xx = vecAngle.x;
         rotationMat.xy = -vecAngle.y;
@@ -3775,6 +3703,7 @@ ftGdiGetGlyphOutline(
     switch (iFormat)
     {
     case GGO_BITMAP:
+    {
         width = gm.gmBlackBoxX;
         height = gm.gmBlackBoxY;
         pitch = ((width + 31) >> 5) << 2;
@@ -3802,6 +3731,7 @@ ftGdiGetGlyphOutline(
         }
 
         case ft_glyph_format_outline:
+        {
             ft_bitmap.width = width;
             ft_bitmap.rows = height;
             ft_bitmap.pitch = pitch;
@@ -3819,12 +3749,15 @@ ftGdiGetGlyphOutline(
             FT_Outline_Get_Bitmap(g_FreeTypeLibrary, &ft_face->glyph->outline, &ft_bitmap);
             IntUnLockFreeType();
             break;
+        }
 
         default:
             DPRINT1("Loaded glyph format %x\n", ft_face->glyph->format);
             return GDI_ERROR;
         }
+
         break;
+    }
 
     case GGO_GRAY2_BITMAP:
     case GGO_GRAY4_BITMAP:
@@ -3910,6 +3843,8 @@ ftGdiGetGlyphOutline(
             DPRINT1("Loaded glyph format %x\n", ft_face->glyph->format);
             return GDI_ERROR;
         }
+
+        break;
     }
 
     case GGO_NATIVE:
@@ -3937,6 +3872,7 @@ ftGdiGetGlyphOutline(
         IntUnLockFreeType();
         break;
     }
+
     case GGO_BEZIER:
     {
         FT_Outline *outline = &ft_face->glyph->outline;
@@ -3986,7 +3922,7 @@ TextIntGetTextExtentPoint(PDC dc,
     FT_GlyphSlot glyph;
     FT_BitmapGlyph realglyph;
     INT error, glyph_index, i, previous;
-    ULONGLONG TotalWidth = 0;
+    ULONGLONG TotalWidth64 = 0;
     BOOL use_kerning;
     FT_Render_Mode RenderMode;
     BOOLEAN Render;
@@ -4074,24 +4010,24 @@ TextIntGetTextExtentPoint(PDC dc,
         {
             FT_Vector delta;
             FT_Get_Kerning(face, previous, glyph_index, 0, &delta);
-            TotalWidth += delta.x;
+            TotalWidth64 += delta.x;
         }
 
-        TotalWidth += realglyph->root.advance.x >> 10;
+        TotalWidth64 += realglyph->root.advance.x >> 10;
 
-        if (((TotalWidth + 32) >> 6) <= MaxExtent && NULL != Fit)
+        if (((TotalWidth64 + 32) >> 6) <= MaxExtent && NULL != Fit)
         {
             *Fit = i + 1;
         }
         if (NULL != Dx)
         {
-            Dx[i] = (TotalWidth + 32) >> 6;
+            Dx[i] = (TotalWidth64 + 32) >> 6;
         }
 
+        /* Bold and italic do not use the cache */
         if (EmuBold || EmuItalic)
         {
             FT_Done_Glyph((FT_Glyph)realglyph);
-            realglyph = NULL;
         }
 
         previous = glyph_index;
@@ -4102,7 +4038,7 @@ TextIntGetTextExtentPoint(PDC dc,
     descender = FontGDI->tmDescent; /* Units below baseline */
     IntUnLockFreeType();
 
-    Size->cx = (TotalWidth + 32) >> 6;
+    Size->cx = (TotalWidth64 + 32) >> 6;
     Size->cy = ascender + descender;
 
     return TRUE;
@@ -4551,7 +4487,7 @@ GetFontPenalty(const LOGFONTW *               LogFont,
 
     ActualNameW = (WCHAR*)((ULONG_PTR)Otm + (ULONG_PTR)Otm->otmpFamilyName);
 
-    if (LogFont->lfFaceName[0])
+    if (LogFont->lfFaceName[0] != UNICODE_NULL)
     {
         BOOL Found = FALSE;
 
@@ -5477,70 +5413,129 @@ ftGdiGetKerningPairs( PFONTGDI Font,
 // Functions needing sorting.
 //
 ///////////////////////////////////////////////////////////////////////////
-int APIENTRY
+
+LONG FASTCALL
+IntGetFontFamilyInfo(HDC Dc,
+                     const LOGFONTW *SafeLogFont,
+                     PFONTFAMILYINFO SafeInfo,
+                     LONG InfoCount)
+{
+    LONG AvailCount = 0;
+    PPROCESSINFO Win32Process;
+
+    /* Enumerate font families in the global list */
+    IntLockGlobalFonts();
+    if (!GetFontFamilyInfoForList(SafeLogFont, SafeInfo, NULL, &AvailCount,
+                                  InfoCount, &g_FontListHead))
+    {
+        IntUnLockGlobalFonts();
+        return -1;
+    }
+    IntUnLockGlobalFonts();
+
+    /* Enumerate font families in the process local list */
+    Win32Process = PsGetCurrentProcessWin32Process();
+    IntLockProcessPrivateFonts(Win32Process);
+    if (!GetFontFamilyInfoForList(SafeLogFont, SafeInfo, NULL, &AvailCount, InfoCount,
+                                  &Win32Process->PrivateFontListHead))
+    {
+        IntUnLockProcessPrivateFonts(Win32Process);
+        return -1;
+    }
+    IntUnLockProcessPrivateFonts(Win32Process);
+
+    /* Enumerate font families in the registry */
+    if (!GetFontFamilyInfoForSubstitutes(SafeLogFont, SafeInfo, &AvailCount, InfoCount))
+    {
+        return -1;
+    }
+
+    return AvailCount;
+}
+
+LONG NTAPI
 NtGdiGetFontFamilyInfo(HDC Dc,
-                       LPLOGFONTW UnsafeLogFont,
+                       const LOGFONTW *UnsafeLogFont,
                        PFONTFAMILYINFO UnsafeInfo,
-                       DWORD Size)
+                       LPLONG UnsafeInfoCount)
 {
     NTSTATUS Status;
     LOGFONTW LogFont;
     PFONTFAMILYINFO Info;
-    DWORD Count;
-    PPROCESSINFO Win32Process;
+    LONG GotCount, AvailCount, SafeInfoCount;
+    ULONG DataSize;
 
-    /* Make a safe copy */
-    Status = MmCopyFromCaller(&LogFont, UnsafeLogFont, sizeof(LOGFONTW));
-    if (! NT_SUCCESS(Status))
+    if (UnsafeLogFont == NULL || UnsafeInfo == NULL || UnsafeInfoCount == NULL)
     {
         EngSetLastError(ERROR_INVALID_PARAMETER);
         return -1;
     }
 
-    /* Allocate space for a safe copy */
-    Info = ExAllocatePoolWithTag(PagedPool, Size * sizeof(FONTFAMILYINFO), GDITAG_TEXT);
-    if (NULL == Info)
+    Status = MmCopyFromCaller(&SafeInfoCount, UnsafeInfoCount, sizeof(SafeInfoCount));
+    if (!NT_SUCCESS(Status))
     {
-        EngSetLastError(ERROR_NOT_ENOUGH_MEMORY);
+        EngSetLastError(ERROR_INVALID_PARAMETER);
         return -1;
     }
-
-    /* Enumerate font families in the global list */
-    IntLockGlobalFonts();
-    Count = 0;
-    if (! GetFontFamilyInfoForList(&LogFont, Info, &Count, Size, &g_FontListHead) )
+    GotCount = 0;
+    Status = MmCopyToCaller(UnsafeInfoCount, &GotCount, sizeof(*UnsafeInfoCount));
+    if (!NT_SUCCESS(Status))
     {
-        IntUnLockGlobalFonts();
-        ExFreePoolWithTag(Info, GDITAG_TEXT);
+        EngSetLastError(ERROR_INVALID_PARAMETER);
         return -1;
     }
-    IntUnLockGlobalFonts();
-
-    /* Enumerate font families in the process local list */
-    Win32Process = PsGetCurrentProcessWin32Process();
-    IntLockProcessPrivateFonts(Win32Process);
-    if (! GetFontFamilyInfoForList(&LogFont, Info, &Count, Size,
-                                   &Win32Process->PrivateFontListHead))
+    Status = MmCopyFromCaller(&LogFont, UnsafeLogFont, sizeof(LOGFONTW));
+    if (!NT_SUCCESS(Status))
     {
-        IntUnLockProcessPrivateFonts(Win32Process);
-        ExFreePoolWithTag(Info, GDITAG_TEXT);
+        EngSetLastError(ERROR_INVALID_PARAMETER);
+        return -1;
+    }
+    if (SafeInfoCount <= 0)
+    {
+        EngSetLastError(ERROR_INVALID_PARAMETER);
         return -1;
     }
-    IntUnLockProcessPrivateFonts(Win32Process);
 
-    /* Enumerate font families in the registry */
-    if (! GetFontFamilyInfoForSubstitutes(&LogFont, Info, &Count, Size))
+    /* Allocate space for a safe copy */
+    Status = RtlULongMult(SafeInfoCount, sizeof(FONTFAMILYINFO), &DataSize);
+    if (!NT_SUCCESS(Status) || DataSize > LONG_MAX)
     {
-        ExFreePoolWithTag(Info, GDITAG_TEXT);
+        DPRINT1("Overflowed.\n");
+        EngSetLastError(ERROR_INVALID_PARAMETER);
         return -1;
     }
+    Info = ExAllocatePoolWithTag(PagedPool, DataSize, GDITAG_TEXT);
+    if (Info == NULL)
+    {
+        EngSetLastError(ERROR_NOT_ENOUGH_MEMORY);
+        return -1;
+    }
+
+    /* Retrieve the information */
+    AvailCount = IntGetFontFamilyInfo(Dc, &LogFont, Info, SafeInfoCount);
+    GotCount = min(AvailCount, SafeInfoCount);
+    SafeInfoCount = AvailCount;
 
     /* Return data to caller */
-    if (0 != Count)
+    if (GotCount > 0)
     {
-        Status = MmCopyToCaller(UnsafeInfo, Info,
-                                (Count < Size ? Count : Size) * sizeof(FONTFAMILYINFO));
-        if (! NT_SUCCESS(Status))
+        Status = RtlULongMult(GotCount, sizeof(FONTFAMILYINFO), &DataSize);
+        if (!NT_SUCCESS(Status) || DataSize > LONG_MAX)
+        {
+            DPRINT1("Overflowed.\n");
+            ExFreePoolWithTag(Info, GDITAG_TEXT);
+            EngSetLastError(ERROR_INVALID_PARAMETER);
+            return -1;
+        }
+        Status = MmCopyToCaller(UnsafeInfo, Info, DataSize);
+        if (!NT_SUCCESS(Status))
+        {
+            ExFreePoolWithTag(Info, GDITAG_TEXT);
+            EngSetLastError(ERROR_INVALID_PARAMETER);
+            return -1;
+        }
+        Status = MmCopyToCaller(UnsafeInfoCount, &SafeInfoCount, sizeof(*UnsafeInfoCount));
+        if (!NT_SUCCESS(Status))
         {
             ExFreePoolWithTag(Info, GDITAG_TEXT);
             EngSetLastError(ERROR_INVALID_PARAMETER);
@@ -5550,7 +5545,7 @@ NtGdiGetFontFamilyInfo(HDC Dc,
 
     ExFreePoolWithTag(Info, GDITAG_TEXT);
 
-    return Count;
+    return GotCount;
 }
 
 FORCEINLINE
@@ -5571,10 +5566,18 @@ ScaleLong(LONG lValue, PFLOATOBJ pef)
     return lValue;
 }
 
+FORCEINLINE LONG FASTCALL
+IntNormalizeAngle(LONG nTenthAngle)
+{
+    const LONG nFullAngle = 360 * 10;
+    nTenthAngle %= nFullAngle;
+    return (nTenthAngle + nFullAngle) % nFullAngle;
+}
+
 BOOL
 APIENTRY
-GreExtTextOutW(
-    IN HDC hDC,
+IntExtTextOutW(
+    IN PDC dc,
     IN INT XStart,
     IN INT YStart,
     IN UINT fuOptions,
@@ -5590,7 +5593,6 @@ GreExtTextOutW(
      * appropriate)
      */
 
-    DC *dc;
     PDC_ATTR pdcattr;
     SURFOBJ *SurfObj;
     SURFACE *psurf = NULL;
@@ -5598,15 +5600,14 @@ GreExtTextOutW(
     FT_Face face;
     FT_GlyphSlot glyph;
     FT_BitmapGlyph realglyph;
-    LONGLONG TextLeft, RealXStart;
-    ULONG TextTop, previous;
+    LONGLONG TextLeft64, TextTop64, DeltaX64, DeltaY64, XStart64, YStart64;
+    ULONG previous;
     FT_Bool use_kerning;
     RECTL DestRect, MaskRect;
     POINTL SourcePoint, BrushOrigin;
     HBITMAP HSourceGlyph;
     SURFOBJ *SourceGlyphSurf;
     SIZEL bitSize;
-    INT yoff;
     FONTOBJ *FontObj;
     PFONTGDI FontGDI;
     PTEXTOBJ TextObj = NULL;
@@ -5617,13 +5618,14 @@ GreExtTextOutW(
     BOOL DoBreak = FALSE;
     USHORT DxShift;
     PMATRIX pmxWorldToDevice;
-    LONG fixAscender, fixDescender;
+    LONG lfEscapement, lfWidth;
     FLOATOBJ Scale;
     LOGFONTW *plf;
     BOOL EmuBold, EmuItalic;
     int thickness;
     BOOL bResult;
-    ULONGLONG TextWidth;
+    FT_Matrix mat = identityMat, matWidth, matEscape, matWorld;
+    FT_Vector vecs[9];
 
     /* Check if String is valid */
     if ((Count > 0xFFFF) || (Count > 0 && String == NULL))
@@ -5632,19 +5634,8 @@ GreExtTextOutW(
         return FALSE;
     }
 
-    /* NOTE: This function locks the screen DC, so it must never be called
-       with a DC already locked */
     Render = IntIsFontRenderingEnabled();
 
-    // TODO: Write test-cases to exactly match real Windows in different
-    // bad parameters (e.g. does Windows check the DC or the RECT first?).
-    dc = DC_LockDc(hDC);
-    if (!dc)
-    {
-        EngSetLastError(ERROR_INVALID_HANDLE);
-        return FALSE;
-    }
-
     if (PATH_IsPathOpen(dc->dclevel))
     {
         bResult = PATH_ExtTextOut(dc,
@@ -5655,7 +5646,6 @@ GreExtTextOutW(
                               String,
                               Count,
                               (const INT *)Dx);
-        DC_UnlockDc(dc);
         return bResult;
     }
 
@@ -5675,19 +5665,16 @@ GreExtTextOutW(
         IntLPtoDP(dc, (POINT *)lprc, 2);
     }
 
-    if (pdcattr->lTextAlign & TA_UPDATECP)
+    if (pdcattr->flTextAlign & TA_UPDATECP)
+    {
+        IntGetCurrentPositionEx(dc, &Start);
+    }
+    else
     {
-        Start.x = pdcattr->ptlCurrent.x;
-        Start.y = pdcattr->ptlCurrent.y;
-    } else {
         Start.x = XStart;
         Start.y = YStart;
     }
 
-    IntLPtoDP(dc, &Start, 1);
-    RealXStart = ((LONGLONG)Start.x + dc->ptlDCOrig.x) << 6;
-    YStart = Start.y + dc->ptlDCOrig.y;
-
     SourcePoint.x = 0;
     SourcePoint.y = 0;
     MaskRect.left = 0;
@@ -5762,6 +5749,15 @@ GreExtTextOutW(
     plf = &TextObj->logfont.elfEnumLogfontEx.elfLogFont;
     EmuBold = (plf->lfWeight >= FW_BOLD && FontGDI->OriginalWeight <= FW_NORMAL);
     EmuItalic = (plf->lfItalic && !FontGDI->OriginalItalic);
+    if (FT_IS_SCALABLE(face))
+    {
+        lfEscapement = IntNormalizeAngle(plf->lfEscapement);
+        lfWidth = labs(plf->lfWidth);
+    }
+    else
+    {
+        lfEscapement = lfWidth = 0;
+    }
 
     if (Render)
         RenderMode = IntGetFontRenderMode(plf);
@@ -5776,47 +5772,39 @@ GreExtTextOutW(
     }
 
     /* NOTE: Don't trust face->size->metrics.ascender and descender values. */
+    DC_vUpdateWorldToDevice(dc);
     if (dc->pdcattr->iGraphicsMode == GM_ADVANCED)
     {
         pmxWorldToDevice = DC_pmxWorldToDevice(dc);
-        FtSetCoordinateTransform(face, pmxWorldToDevice);
-
-        fixAscender = ScaleLong(FontGDI->tmAscent, &pmxWorldToDevice->efM22) << 6;
-        fixDescender = ScaleLong(FontGDI->tmDescent, &pmxWorldToDevice->efM22) << 6;
     }
     else
     {
         pmxWorldToDevice = (PMATRIX)&gmxWorldToDeviceDefault;
-        FtSetCoordinateTransform(face, pmxWorldToDevice);
-
-        fixAscender = FontGDI->tmAscent << 6;
-        fixDescender = FontGDI->tmDescent << 6;
     }
 
-    /*
-     * Process the vertical alignment and determine the yoff.
-     */
-#define VALIGN_MASK  (TA_TOP | TA_BASELINE | TA_BOTTOM)
-    if ((pdcattr->lTextAlign & VALIGN_MASK) == TA_BASELINE)
-        yoff = 0;
-    else if ((pdcattr->lTextAlign & VALIGN_MASK) == TA_BOTTOM)
-        yoff = -(fixDescender >> 6);
-    else /* TA_TOP */
-        yoff = fixAscender >> 6;
-#undef VALIGN_MASK
+    IntWidthMatrix(face, &matWidth, lfWidth);
+    FT_Matrix_Multiply(&matWidth, &mat);
 
-    /*
-     * Calculate width of the text.
-     */
-    TextWidth = 0;
+    IntEscapeMatrix(&matEscape, lfEscapement);
+    FT_Matrix_Multiply(&matEscape, &mat);
+
+    FtMatrixFromMx(&matWorld, pmxWorldToDevice);
+    matWorld.yx = -matWorld.yx;
+    matWorld.xy = -matWorld.xy;
+    FT_Matrix_Multiply(&matWorld, &mat);
+
+    FT_Set_Transform(face, &mat, NULL);
+
+    // Calculate displacement of the text.
+    DeltaX64 = DeltaY64 = 0;
     DxShift = fuOptions & ETO_PDY ? 1 : 0;
     use_kerning = FT_HAS_KERNING(face);
     previous = 0;
     if ((fuOptions & ETO_OPAQUE) ||
-        (pdcattr->lTextAlign & (TA_CENTER | TA_RIGHT)))
+        (pdcattr->flTextAlign & (TA_CENTER | TA_RIGHT)) ||
+        memcmp(&mat, &identityMat, sizeof(mat)) != 0 ||
+        plf->lfUnderline || plf->lfStrikeOut)
     {
-        TextLeft = RealXStart;
-        TextTop = YStart;
         for (i = 0; i < Count; ++i)
         {
             glyph_index = get_glyph_index_flagged(face, String[i], ETO_GLYPH_INDEX, fuOptions);
@@ -5850,50 +5838,52 @@ GreExtTextOutW(
             {
                 FT_Vector delta;
                 FT_Get_Kerning(face, previous, glyph_index, 0, &delta);
-                TextLeft += delta.x;
+                DeltaX64 += delta.x;
+                DeltaY64 -= delta.y;
             }
 
             if (Dx == NULL)
             {
-                TextLeft += realglyph->root.advance.x >> 10;
+                DeltaX64 += realglyph->root.advance.x >> 10;
+                DeltaY64 -= realglyph->root.advance.y >> 10;
             }
             else
             {
-                // FIXME this should probably be a matrix transform with TextTop as well.
+                // FIXME this should probably be a matrix transform with DeltaY64 as well.
                 Scale = pdcattr->mxWorldToDevice.efM11;
                 if (FLOATOBJ_Equal0(&Scale))
                     FLOATOBJ_Set1(&Scale);
 
                 /* do the shift before multiplying to preserve precision */
                 FLOATOBJ_MulLong(&Scale, Dx[i << DxShift] << 6);
-                TextLeft += FLOATOBJ_GetLong(&Scale);
+                DeltaX64 += FLOATOBJ_GetLong(&Scale);
             }
 
             if (DxShift)
             {
-                TextTop -= Dx[2 * i + 1] << 6;
+                DeltaY64 -= Dx[2 * i + 1] << 6;
             }
 
             previous = glyph_index;
 
-            FT_Done_Glyph(realglyph);
+            FT_Done_Glyph((FT_Glyph)realglyph);
         }
-
-        TextWidth = TextLeft - RealXStart;
     }
 
-    /*
-     * Process the horizontal alignment and modify XStart accordingly.
-     */
-    if ((pdcattr->lTextAlign & TA_CENTER) == TA_CENTER)
+    // Process the X and Y alignments.
+    if ((pdcattr->flTextAlign & TA_CENTER) == TA_CENTER)
+    {
+        XStart64 = -DeltaX64 / 2;
+        YStart64 = -DeltaY64 / 2;
+    }
+    else if ((pdcattr->flTextAlign & TA_RIGHT) == TA_RIGHT)
     {
-        RealXStart -= TextWidth / 2;
+        XStart64 = -DeltaX64;
+        YStart64 = -DeltaY64;
     }
-    else if ((pdcattr->lTextAlign & TA_RIGHT) == TA_RIGHT)
+    else
     {
-        RealXStart -= TextWidth;
-        if (((RealXStart + TextWidth + 32) >> 6) <= Start.x + dc->ptlDCOrig.x)
-            RealXStart += 1 << 6;
+        XStart64 = YStart64 = 0;
     }
 
     psurf = dc->dclevel.pSurface;
@@ -5902,14 +5892,11 @@ GreExtTextOutW(
     if ((fuOptions & ETO_OPAQUE) && (dc->pdcattr->ulDirty_ & DIRTY_BACKGROUND))
         DC_vUpdateBackgroundBrush(dc) ;
 
-    if(dc->pdcattr->ulDirty_ & DIRTY_TEXT)
+    if (dc->pdcattr->ulDirty_ & DIRTY_TEXT)
         DC_vUpdateTextBrush(dc) ;
 
-    if (!face->units_per_EM)
-    {
-        thickness = 1;
-    }
-    else
+    thickness = 1;
+    if (face->units_per_EM)
     {
         thickness = face->underline_thickness *
             face->size->metrics.y_ppem / face->units_per_EM;
@@ -5917,15 +5904,110 @@ GreExtTextOutW(
             thickness = 1;
     }
 
+    /* Process the vertical alignment */
+#define VALIGN_MASK  (TA_TOP | TA_BASELINE | TA_BOTTOM)
+    RtlZeroMemory(vecs, sizeof(vecs));
+    if ((pdcattr->flTextAlign & VALIGN_MASK) == TA_BASELINE)
+    {
+        vecs[1].y = -FontGDI->tmAscent << 16;   // upper left
+        vecs[4].y = 0;                          // baseline
+        vecs[0].y = FontGDI->tmDescent << 16;   // lower left
+    }
+    else if ((pdcattr->flTextAlign & VALIGN_MASK) == TA_BOTTOM)
+    {
+        vecs[1].y = -FontGDI->tmHeight << 16;   // upper left
+        vecs[4].y = -FontGDI->tmDescent << 16;  // baseline
+        vecs[0].y = 0;                          // lower left
+    }
+    else /* TA_TOP */
+    {
+        vecs[1].y = 0;                          // upper left
+        vecs[4].y = FontGDI->tmAscent << 16;    // baseline
+        vecs[0].y = FontGDI->tmHeight << 16;    // lower left
+    }
+    vecs[2] = vecs[1];      // upper right
+    vecs[3] = vecs[0];      // lower right
+#undef VALIGN_MASK
+
+    // underline
+    if (plf->lfUnderline)
+    {
+        int position = 0;
+        if (face->units_per_EM)
+        {
+            position = face->underline_position *
+                face->size->metrics.y_ppem / face->units_per_EM;
+        }
+        vecs[5].y = vecs[6].y = vecs[4].y - (position << 16);
+    }
+
+    // strike through
+    if (plf->lfStrikeOut)
+    {
+        vecs[7].y = vecs[8].y = vecs[4].y - ((FontGDI->tmAscent / 3) << 16);
+    }
+
+    // invert y axis
+    IntEscapeMatrix(&matEscape, -lfEscapement);
+
+    matWorld.yx = -matWorld.yx;
+    matWorld.xy = -matWorld.xy;
+
+    // convert vecs
+    for (i = 0; i < 9; ++i)
+    {
+        FT_Vector_Transform(&vecs[i], &matWidth);
+        FT_Vector_Transform(&vecs[i], &matEscape);
+        FT_Vector_Transform(&vecs[i], &matWorld);
+    }
+    vecs[2].x += DeltaX64 << 10;
+    vecs[2].y += DeltaY64 << 10;     // upper right
+    vecs[3].x += DeltaX64 << 10;
+    vecs[3].y += DeltaY64 << 10;     // lower right
+    vecs[6].x += DeltaX64 << 10;
+    vecs[6].y += DeltaY64 << 10;     // underline right
+    vecs[8].x += DeltaX64 << 10;
+    vecs[8].y += DeltaY64 << 10;     // strike through right
+
+    {
+        POINT pt;
+        pt.x = Start.x + (XStart64 >> 6);
+        pt.y = Start.y + (YStart64 >> 6);
+        IntLPtoDP(dc, &pt, 1);
+
+        for (i = 0; i < 9; ++i)
+        {
+            vecs[i].x += pt.x << 16;
+            vecs[i].y += pt.y << 16;
+            vecs[i].x >>= 16;
+            vecs[i].y >>= 16;
+            vecs[i].x += dc->ptlDCOrig.x;
+            vecs[i].y += dc->ptlDCOrig.y;
+        }
+    }
+
     if (fuOptions & ETO_OPAQUE)
     {
         /* Draw background */
         RECTL Rect;
+        RtlZeroMemory(&Rect, sizeof(Rect));
 
-        Rect.left = (RealXStart + 32) >> 6;
-        Rect.top = TextTop + yoff - ((fixAscender + 32) >> 6);
-        Rect.right = (RealXStart + TextWidth + 32) >> 6;
-        Rect.bottom = Rect.top + ((fixAscender + fixDescender) >> 6);
+        if ((mat.xy == 0 && mat.yx == 0) || (mat.xx == 0 && mat.yy == 0))
+        {
+            Rect.left = Rect.top = MAXLONG;
+            Rect.right = Rect.bottom = MINLONG;
+            for (i = 0; i < 4; ++i)
+            {
+                Rect.left = min(Rect.left, vecs[i].x);
+                Rect.top = min(Rect.top, vecs[i].y);
+                Rect.right = max(Rect.right, vecs[i].x);
+                Rect.bottom = max(Rect.bottom, vecs[i].y);
+            }
+        }
+        else
+        {
+            // FIXME: Use vecs[0] ... vecs[3] and EngFillPath
+        }
 
         if (dc->fs & (DC_ACCUM_APP | DC_ACCUM_WMGR))
         {
@@ -5961,24 +6043,22 @@ GreExtTextOutW(
     EXLATEOBJ_vInitialize(&exloRGB2Dst, &gpalRGB, psurf->ppal, 0, 0, 0);
     EXLATEOBJ_vInitialize(&exloDst2RGB, psurf->ppal, &gpalRGB, 0, 0, 0);
 
-    /* Assume success */
+    // The main rendering loop.
     bResult = TRUE;
-
-    /*
-     * The main rendering loop.
-     */
-    TextLeft = RealXStart;
-    TextTop = YStart;
+    TextLeft64 = vecs[4].x << 6;
+    TextTop64 = vecs[4].y << 6;
     previous = 0;
     for (i = 0; i < Count; ++i)
     {
+        BOOL bNeedCache = (!EmuBold && !EmuItalic &&
+                           memcmp(&mat, &identityMat, sizeof(mat)) == 0);
         glyph_index = get_glyph_index_flagged(face, String[i], ETO_GLYPH_INDEX, fuOptions);
-
-        if (EmuBold || EmuItalic)
-            realglyph = NULL;
-        else
+        realglyph = NULL;
+        if (bNeedCache)
+        {
             realglyph = ftGdiGlyphCacheGet(face, glyph_index, plf->lfHeight,
                                            RenderMode, pmxWorldToDevice);
+        }
         if (!realglyph)
         {
             error = FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
@@ -5988,17 +6068,8 @@ GreExtTextOutW(
                 bResult = FALSE;
                 break;
             }
-
             glyph = face->glyph;
-            if (EmuBold || EmuItalic)
-            {
-                if (EmuBold)
-                    FT_GlyphSlot_Embolden(glyph);
-                if (EmuItalic)
-                    FT_GlyphSlot_Oblique(glyph);
-                realglyph = ftGdiGlyphSet(face, glyph, RenderMode);
-            }
-            else
+            if (bNeedCache)
             {
                 realglyph = ftGdiGlyphCacheSet(face,
                                                glyph_index,
@@ -6007,6 +6078,14 @@ GreExtTextOutW(
                                                glyph,
                                                RenderMode);
             }
+            else
+            {
+                if (EmuBold)
+                    FT_GlyphSlot_Embolden(glyph);
+                if (EmuItalic)
+                    FT_GlyphSlot_Oblique(glyph);
+                realglyph = ftGdiGlyphSet(face, glyph, RenderMode);
+            }
             if (!realglyph)
             {
                 DPRINT1("Failed to render glyph! [index: %d]\n", glyph_index);
@@ -6020,15 +6099,16 @@ GreExtTextOutW(
         {
             FT_Vector delta;
             FT_Get_Kerning(face, previous, glyph_index, 0, &delta);
-            TextLeft += delta.x;
+            TextLeft64 += delta.x;
+            TextTop64 -= delta.y;
         }
-        DPRINT("TextLeft: %I64d\n", TextLeft);
-        DPRINT("TextTop: %lu\n", TextTop);
+        DPRINT("TextLeft64: %I64d\n", TextLeft64);
+        DPRINT("TextTop64: %I64d\n", TextTop64);
         DPRINT("Advance: %d\n", realglyph->root.advance.x);
 
-        DestRect.left = ((TextLeft + 32) >> 6) + realglyph->left;
+        DestRect.left = ((TextLeft64 + 32) >> 6) + realglyph->left;
         DestRect.right = DestRect.left + realglyph->bitmap.width;
-        DestRect.top = TextTop + yoff - realglyph->top;
+        DestRect.top = ((TextTop64 + 32) >> 6) - realglyph->top;
         DestRect.bottom = DestRect.top + realglyph->bitmap.rows;
 
         bitSize.cx = realglyph->bitmap.width;
@@ -6050,8 +6130,12 @@ GreExtTextOutW(
             if ( !HSourceGlyph )
             {
                 DPRINT1("WARNING: EngCreateBitmap() failed!\n");
-                // FT_Done_Glyph(realglyph);
                 bResult = FALSE;
+                if (EmuBold || EmuItalic)
+                {
+                    FT_Done_Glyph((FT_Glyph)realglyph);
+                }
+
                 break;
             }
             SourceGlyphSurf = EngLockSurface((HSURF)HSourceGlyph);
@@ -6060,6 +6144,11 @@ GreExtTextOutW(
                 EngDeleteSurface((HSURF)HSourceGlyph);
                 DPRINT1("WARNING: EngLockSurface() failed!\n");
                 bResult = FALSE;
+                if (EmuBold || EmuItalic)
+                {
+                    FT_Done_Glyph((FT_Glyph)realglyph);
+                }
+
                 break;
             }
 
@@ -6108,85 +6197,123 @@ GreExtTextOutW(
 
         if (DoBreak)
         {
-            break;
-        }
-
-        if (plf->lfUnderline)
-        {
-            int i, position;
-            if (!face->units_per_EM)
-            {
-                position = 0;
-            }
-            else
-            {
-                position = face->underline_position *
-                    face->size->metrics.y_ppem / face->units_per_EM;
-            }
-            for (i = -thickness / 2; i < -thickness / 2 + thickness; ++i)
-            {
-                EngLineTo(SurfObj,
-                          (CLIPOBJ *)&dc->co,
-                          &dc->eboText.BrushObject,
-                          (TextLeft >> 6),
-                          TextTop + yoff - position + i,
-                          ((TextLeft + (realglyph->root.advance.x >> 10)) >> 6),
-                          TextTop + yoff - position + i,
-                          NULL,
-                          ROP2_TO_MIX(R2_COPYPEN));
-            }
-        }
-        if (plf->lfStrikeOut)
-        {
-            int i;
-            for (i = -thickness / 2; i < -thickness / 2 + thickness; ++i)
+            if (EmuBold || EmuItalic)
             {
-                EngLineTo(SurfObj,
-                          (CLIPOBJ *)&dc->co,
-                          &dc->eboText.BrushObject,
-                          (TextLeft >> 6),
-                          TextTop + yoff - (fixAscender >> 6) / 3 + i,
-                          ((TextLeft + (realglyph->root.advance.x >> 10)) >> 6),
-                          TextTop + yoff - (fixAscender >> 6) / 3 + i,
-                          NULL,
-                          ROP2_TO_MIX(R2_COPYPEN));
+                FT_Done_Glyph((FT_Glyph)realglyph);
             }
+
+            break;
         }
 
         if (NULL == Dx)
         {
-            TextLeft += realglyph->root.advance.x >> 10;
-            DPRINT("New TextLeft: %I64d\n", TextLeft);
+            TextLeft64 += realglyph->root.advance.x >> 10;
+            TextTop64 -= realglyph->root.advance.y >> 10;
+            DPRINT("New TextLeft64: %I64d\n", TextLeft64);
+            DPRINT("New TextTop64: %I64d\n", TextTop64);
         }
         else
         {
-            // FIXME this should probably be a matrix transform with TextTop as well.
+            // FIXME this should probably be a matrix transform with TextTop64 as well.
             Scale = pdcattr->mxWorldToDevice.efM11;
             if (FLOATOBJ_Equal0(&Scale))
                 FLOATOBJ_Set1(&Scale);
 
             /* do the shift before multiplying to preserve precision */
             FLOATOBJ_MulLong(&Scale, Dx[i<<DxShift] << 6); 
-            TextLeft += FLOATOBJ_GetLong(&Scale);
-            DPRINT("New TextLeft2: %I64d\n", TextLeft);
+            TextLeft64 += FLOATOBJ_GetLong(&Scale);
+            DPRINT("New TextLeft64 2: %I64d\n", TextLeft64);
         }
 
         if (DxShift)
         {
-            TextTop -= Dx[2 * i + 1] << 6;
+            TextTop64 -= Dx[2 * i + 1] << 6;
         }
 
         previous = glyph_index;
 
-        if (EmuBold || EmuItalic)
+        /* No cache, so clean up */
+        if (!bNeedCache)
         {
             FT_Done_Glyph((FT_Glyph)realglyph);
-            realglyph = NULL;
         }
     }
 
-    if (pdcattr->lTextAlign & TA_UPDATECP) {
-        pdcattr->ptlCurrent.x = DestRect.right - dc->ptlDCOrig.x;
+    if (plf->lfUnderline || plf->lfStrikeOut)
+    {
+        INT x0 = min(vecs[0].x, vecs[2].x);
+        INT y0 = min(vecs[0].y, vecs[2].y);
+        INT x1 = max(vecs[0].x, vecs[2].x);
+        INT y1 = max(vecs[0].y, vecs[2].y);
+        if (dc->dctype == DCTYPE_DIRECT)
+            MouseSafetyOnDrawStart(dc->ppdev, x0, y0, x1, y1);
+    }
+
+    if (plf->lfUnderline)
+    {
+        for (i = -thickness / 2; i < -thickness / 2 + thickness; ++i)
+        {
+            LONG dx = (LONG)(DeltaX64 >> 6), dy = (LONG)(DeltaY64 >> 6);
+            if (labs(dx) > labs(dy))
+            {
+                // move vertical
+                EngLineTo(SurfObj, (CLIPOBJ *)&dc->co,
+                          &dc->eboText.BrushObject,
+                          vecs[5].x, vecs[5].y + i,
+                          vecs[6].x, vecs[6].y + i,
+                          NULL, ROP2_TO_MIX(R2_COPYPEN));
+            }
+            else
+            {
+                // move horizontal
+                EngLineTo(SurfObj, (CLIPOBJ *)&dc->co,
+                          &dc->eboText.BrushObject,
+                          vecs[5].x + i, vecs[5].y,
+                          vecs[6].x + i, vecs[6].y,
+                          NULL, ROP2_TO_MIX(R2_COPYPEN));
+            }
+        }
+    }
+
+    if (plf->lfStrikeOut)
+    {
+        for (i = -thickness / 2; i < -thickness / 2 + thickness; ++i)
+        {
+            LONG dx = (LONG)(DeltaX64 >> 6), dy = (LONG)(DeltaY64 >> 6);
+            if (labs(dx) > labs(dy))
+            {
+                // move vertical
+                EngLineTo(SurfObj, (CLIPOBJ *)&dc->co,
+                          &dc->eboText.BrushObject,
+                          vecs[7].x, vecs[7].y + i,
+                          vecs[8].x, vecs[8].y + i,
+                          NULL, ROP2_TO_MIX(R2_COPYPEN));
+            }
+            else
+            {
+                // move horizontal
+                EngLineTo(SurfObj, (CLIPOBJ *)&dc->co,
+                          &dc->eboText.BrushObject,
+                          vecs[7].x + i, vecs[7].y,
+                          vecs[8].x + i, vecs[8].y,
+                          NULL, ROP2_TO_MIX(R2_COPYPEN));
+            }
+        }
+    }
+
+    if (plf->lfUnderline || plf->lfStrikeOut)
+    {
+        if (dc->dctype == DCTYPE_DIRECT)
+            MouseSafetyOnDrawEnd(dc->ppdev);
+    }
+
+    if (pdcattr->flTextAlign & TA_UPDATECP)
+    {
+        pdcattr->ptlCurrent.x = vecs[2].x - dc->ptlDCOrig.x;
+        pdcattr->ptlCurrent.y = vecs[2].y - dc->ptlDCOrig.y;
+        IntDPtoLP(dc, &pdcattr->ptlCurrent, 1);
+        pdcattr->ulDirty_ &= ~DIRTY_PTLCURRENT;
+        pdcattr->ulDirty_ |= (DIRTY_PTFXCURRENT | DIRTY_STYLESTATE);
     }
 
     IntUnLockFreeType();
@@ -6201,6 +6328,45 @@ Cleanup:
     if (TextObj != NULL)
         TEXTOBJ_UnlockText(TextObj);
 
+    return bResult;
+}
+
+
+BOOL
+APIENTRY
+GreExtTextOutW(
+    IN HDC hDC,
+    IN INT XStart,
+    IN INT YStart,
+    IN UINT fuOptions,
+    IN OPTIONAL PRECTL lprc,
+    IN LPCWSTR String,
+    IN INT Count,
+    IN OPTIONAL LPINT Dx,
+    IN DWORD dwCodePage)
+{
+    BOOL bResult;
+    DC *dc;
+
+    // TODO: Write test-cases to exactly match real Windows in different
+    // bad parameters (e.g. does Windows check the DC or the RECT first?).
+    dc = DC_LockDc(hDC);
+    if (!dc)
+    {
+        EngSetLastError(ERROR_INVALID_HANDLE);
+        return FALSE;
+    }
+
+    bResult = IntExtTextOutW( dc,
+                              XStart,
+                              YStart,
+                              fuOptions,
+                              lprc,
+                              String,
+                              Count,
+                              Dx,
+                              dwCodePage );
+
     DC_UnlockDc(dc);
 
     return bResult;
@@ -6523,7 +6689,7 @@ NtGdiGetCharABCWidthsW(
     if(Safepwch)
         ExFreePoolWithTag(Safepwch , GDITAG_TEXT);
 
-    if (! NT_SUCCESS(Status))
+    if (!NT_SUCCESS(Status))
     {
         SetLastNtError(Status);
         return FALSE;
@@ -6784,8 +6950,12 @@ NtGdiGetGlyphIndicesW(
         FT_Face Face = FontGDI->SharedFace->Face;
         if (FT_IS_SFNT(Face))
         {
-            TT_OS2 *pOS2 = FT_Get_Sfnt_Table(Face, ft_sfnt_os2);
+            TT_OS2 *pOS2;
+            
+            IntLockFreeType();
+            pOS2 = FT_Get_Sfnt_Table(Face, ft_sfnt_os2);
             DefChar = (pOS2->usDefaultChar ? get_glyph_index(Face, pOS2->usDefaultChar) : 0);
+            IntUnLockFreeType();
         }
         else
         {