Index: trunk/src/gdi32/blit.cpp
===================================================================
--- trunk/src/gdi32/blit.cpp	(revision 10372)
+++ trunk/src/gdi32/blit.cpp	(revision 10373)
@@ -1,3 +1,3 @@
-/* $Id: blit.cpp,v 1.45 2003-07-16 10:46:16 sandervl Exp $ */
+/* $Id: blit.cpp,v 1.46 2004-01-11 11:42:08 sandervl Exp $ */
 
 /*
@@ -17,4 +17,6 @@
 #include <winuser32.h>
 #include <dbglog.h>
+#include "oslibgpi.h"
+#include <dcdata.h>
 #include "dibsect.h"
 #include "rgbcvt.h"
@@ -48,14 +50,12 @@
             rc  = dsect->BitBlt(hdcDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest,
                                 nXOriginSrc, nYOriginSrc, nWidthSrc, nHeightSrc, dwRop);
-            return rc;
+            goto blitdone;
         }
     }
     rc = O32_StretchBlt(hdcDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, hdcSrc, nXOriginSrc, nYOriginSrc, nWidthSrc, nHeightSrc, dwRop);
-    if(DIBSection::getSection() != NULL) {
-        DIBSection *destdib = DIBSection::findHDC(hdcDest);
-        if(destdib) {
-            destdib->sync(hdcDest, nYOriginDest, nHeightDest);
-        }
-    }
+
+blitdone:
+    DIBSECTION_MARK_INVALID(hdcDest);
+
     if(rc == FALSE) {
         dprintf(("!WARNING!: GDI32: StretchBlt returned FALSE; last error %x", rc, GetLastError()));
@@ -78,5 +78,5 @@
 
 #ifdef DEBUG
-      POINT point1, point2;
+    POINT point1, point2;
     GetViewportOrgEx(hdcDest, &point1);
     GetViewportOrgEx(hdcSrc, &point2);
@@ -90,5 +90,6 @@
         if(dsect) 
         {
-            return dsect->BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight, nXSrc, nYSrc, nWidth, nHeight, dwRop);
+            rc = dsect->BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight, nXSrc, nYSrc, nWidth, nHeight, dwRop);
+            goto blitdone;
         }
     }
@@ -98,10 +99,6 @@
     rc = O32_BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight, hdcSrc, nXSrc, nYSrc, dwRop);
 
-    if(DIBSection::getSection() != NULL) {
-        DIBSection *destdib = DIBSection::findHDC(hdcDest);
-        if(destdib) {
-            destdib->sync(hdcDest, nYDest, nHeight);
-        }
-    }
+blitdone:
+    DIBSECTION_MARK_INVALID(hdcDest);
     return rc;
 }
@@ -193,5 +190,5 @@
     }
     if(startscan != 0 || lines != info->bmiHeader.biHeight) {
-	    dprintf(("WARNING: SetDIBitsToDevice startscan != 0 || lines != info->bmiHeader.biHeight"));
+        dprintf(("WARNING: SetDIBitsToDevice startscan != 0 || lines != info->bmiHeader.biHeight"));
         dprintf(("info bmp (%d,%d)", info->bmiHeader.biWidth, info->bmiHeader.biHeight));
     }
@@ -209,17 +206,8 @@
 	result = info->bmiHeader.biHeight;
 
-  	DIBSection *destdib = DIBSection::findHDC(hdc);
- 	if(destdib) {
-		if(cx == info->bmiHeader.biWidth && cy == info->bmiHeader.biHeight &&
-                   destdib->GetBitCount() == info->bmiHeader.biBitCount &&
-                   destdib->GetBitCount() == 8) 
-                {
-			destdib->sync(xDest, yDest, cx, cy, (PVOID)bits);
-		}
-		else	destdib->sync(hdc, yDest, cy);
-	}
+        DIBSECTION_MARK_INVALID(hdc);
     }
     dprintf(("GDI32: SetDIBitsToDevice hdc:%X xDest:%d yDest:%d, cx:%d, cy:%d, xSrc:%d, ySrc:%d, startscan:%d, lines:%d \nGDI32: bits 0x%X, info 0x%X, coloruse %d returned %d",
-                 hdc, xDest, yDest, cx, cy, xSrc, ySrc, startscan, lines, (LPVOID) bits, (PBITMAPINFO)info, coloruse, result));
+              hdc, xDest, yDest, cx, cy, xSrc, ySrc, startscan, lines, (LPVOID) bits, (PBITMAPINFO)info, coloruse, result));
     dprintf(("GDI32: SetDIBitsToDevice %d %d %d %d %x %d", info->bmiHeader.biWidth, info->bmiHeader.biHeight, info->bmiHeader.biPlanes, info->bmiHeader.biBitCount, info->bmiHeader.biCompression, info->bmiHeader.biSizeImage));
 
@@ -358,8 +346,5 @@
     rc = O32_PatBlt(hdc,nXLeft,nYLeft,nWidth,nHeight,dwRop);
     if(rc) {
-      	DIBSection *destdib = DIBSection::findHDC(hdc);
-      	if(destdib) {
-		    destdib->sync(hdc, nYLeft, nHeight);
-  	    }
+        DIBSECTION_MARK_INVALID(hdc);
     }
     return(rc);
@@ -367,7 +352,15 @@
 //******************************************************************************
 //******************************************************************************
-BOOL WIN32API MaskBlt( HDC arg1, int arg2, int arg3, int arg4, int arg5, HDC   arg6, int arg7, int arg8, HBITMAP arg9, int arg10, int arg11, DWORD  arg12)
-{
-    return O32_MaskBlt(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
+BOOL WIN32API MaskBlt( HDC hdcDest, int arg2, int arg3, int arg4, int arg5, HDC hdcSrc, int arg7, int arg8, HBITMAP arg9, int arg10, int arg11, DWORD  arg12)
+{
+    BOOL ret;
+
+    DIBSECTION_CHECK_IF_DIRTY(hdcSrc);
+
+    ret = O32_MaskBlt(hdcDest, arg2, arg3, arg4, arg5, hdcSrc, arg7, arg8, arg9, arg10, arg11, arg12);
+    if(ret) {
+        DIBSECTION_MARK_INVALID(hdcDest);
+    }
+    return ret;
 }
 //******************************************************************************
@@ -426,20 +419,11 @@
         //Open32 always returns height of bitmap (regardless of how many scanlines were copied)
       	if(rc != heightSrc && rc != infoLoc->bmiHeader.biHeight) {
-		    dprintf(("StretchDIBits failed with rc %x", rc));
+	    dprintf(("StretchDIBits failed with rc %x", rc));
       	}
-	    else {
-		    rc = heightSrc;
-
-  		    DIBSection *destdib = DIBSection::findHDC(hdc);
-  		    if(destdib) {
-    			if(widthDst == widthSrc && heightDst == heightSrc &&
-                            destdib->GetBitCount() == infoLoc->bmiHeader.biBitCount &&
-                            destdib->GetBitCount() == 8) 
-                {
-				    destdib->sync(xDst, yDst, widthDst, heightDst, (PVOID)bits);
- 			    }
-			    else	destdib->sync(hdc, yDst, heightDst);
-  		    }
-	    }
+        else {
+	    rc = heightSrc;
+
+            DIBSECTION_MARK_INVALID(hdc);
+        }
     
     	return rc;
@@ -489,6 +473,6 @@
 
     rc = O32_StretchDIBits(hdc, xDst, yDst, widthDst, heightDst, xSrc, ySrc,
-                             widthSrc, heightSrc, (void *)bits,
-                             (PBITMAPINFO)info, wUsage, dwRop);
+                           widthSrc, heightSrc, (void *)bits,
+                           (PBITMAPINFO)info, wUsage, dwRop);
 
     if(compression == BI_BITFIELDS) {
@@ -505,14 +489,5 @@
 	    rc = heightSrc;
 
-  	    DIBSection *destdib = DIBSection::findHDC(hdc);
- 	    if(destdib) {
-    		if(widthDst == widthSrc && heightDst == heightSrc &&
-                    destdib->GetBitCount() == info->bmiHeader.biBitCount &&
-                    destdib->GetBitCount() == 8) 
-            {
-			     destdib->sync(xDst, yDst, widthDst, heightDst, (PVOID)bits);
-		    }
-		    else destdib->sync(hdc, yDst, heightDst);
-	    }
+            DIBSECTION_MARK_INVALID(hdc);
     }
 
@@ -526,5 +501,4 @@
                            const BITMAPINFO *info, UINT wUsage, DWORD dwRop )
 {
-
     if(info->bmiHeader.biHeight < 0) {
         // upside down
@@ -563,4 +537,5 @@
 int WIN32API SetStretchBltMode( HDC arg1, int  arg2)
 {
+#ifdef DEBUG
     if(DIBSection::getSection() != NULL)
     {
@@ -571,4 +546,5 @@
         }
     }
+#endif
     return O32_SetStretchBltMode(arg1, arg2);
 }
Index: trunk/src/gdi32/dbglocal.cpp
===================================================================
--- trunk/src/gdi32/dbglocal.cpp	(revision 10372)
+++ trunk/src/gdi32/dbglocal.cpp	(revision 10373)
@@ -1,3 +1,3 @@
-/* $Id: dbglocal.cpp,v 1.9 2002-11-26 10:53:07 sandervl Exp $ */
+/* $Id: dbglocal.cpp,v 1.10 2004-01-11 11:42:08 sandervl Exp $ */
 
 /*
@@ -43,5 +43,7 @@
 "printer",
 "icm",
-"trace"
+"trace",
+"fontres",
+"devcontext"
 };
 //******************************************************************************
Index: trunk/src/gdi32/dbglocal.h
===================================================================
--- trunk/src/gdi32/dbglocal.h	(revision 10372)
+++ trunk/src/gdi32/dbglocal.h	(revision 10373)
@@ -1,3 +1,3 @@
-/* $Id: dbglocal.h,v 1.8 2002-11-26 10:53:07 sandervl Exp $ */
+/* $Id: dbglocal.h,v 1.9 2004-01-11 11:42:09 sandervl Exp $ */
 
 /*
@@ -42,5 +42,7 @@
 #define DBG_icm             20
 #define DBG_trace           21
-#define DBG_MAXFILES        22
+#define DBG_fontres         22
+#define DBG_devcontext      23
+#define DBG_MAXFILES        24
 
 extern USHORT DbgEnabledGDI32[DBG_MAXFILES];
Index: trunk/src/gdi32/dbgwrap.cpp
===================================================================
--- trunk/src/gdi32/dbgwrap.cpp	(revision 10372)
+++ trunk/src/gdi32/dbgwrap.cpp	(revision 10373)
@@ -90,9 +90,9 @@
 DEBUGWRAP20(IntersectClipRect)
 DEBUGWRAP8(GetRgnBox)
-DEBUGWRAP12(GetRandomRgn)
 NODEF_DEBUGWRAP8(GetMetaRgn)
 DEBUGWRAP8(GetClipRgn)
 DEBUGWRAP20(FrameRgn)
 DEBUGWRAP12(FillRgn)
+DEBUGWRAP12(GetRandomRgn)
 DEBUGWRAP12(ExtSelectClipRgn)
 DEBUGWRAP8(EqualRgn)
@@ -214,5 +214,5 @@
 DEBUGWRAP_LVL2_4(GetObjectType)
 DEBUGWRAP12(GetObjectW)
-DEBUGWRAP4(GetStockObject)
+DEBUGWRAP_LVL2_4(GetStockObject)
 DEBUGWRAP_LVL2_8(SelectObject)
 NODEF_DEBUGWRAP8(SetObjectOwner)
@@ -295,12 +295,7 @@
 DEBUGWRAP4(CreateColorSpaceA)
 DEBUGWRAP4(CreateColorSpaceW)
-DEBUGWRAP4(CreateCompatibleDC)
-DEBUGWRAP16(CreateDCA)
-DEBUGWRAP16(CreateDCW)
 DEBUGWRAP8(CreateDIBPatternBrush)
 DEBUGWRAP8(CreateDIBPatternBrushPt)
 DEBUGWRAP8(CreateHatchBrush)
-DEBUGWRAP16(CreateICA)
-DEBUGWRAP16(CreateICW)
 DEBUGWRAP4(CreatePatternBrush)
 DEBUGWRAP12(CreatePen)
@@ -309,5 +304,4 @@
 DEBUGWRAP12(DPtoLP)
 DEBUGWRAP4(DeleteColorSpace)
-DEBUGWRAP4(DeleteDC)
 DEBUGWRAP16(DescribePixelFormat)
 //;    DeviceCapabilitiesEx       = _DeviceCapabilitiesEx@??    @177
@@ -356,5 +350,4 @@
 NODEF_DEBUGWRAP8(GetDeviceGammaRamp)
 DEBUGWRAP12(GetKerningPairsA)
-DEBUGWRAP12(GetKerningPairsW)
 NODEF_DEBUGWRAP12(GetLogColorSpaceA)
 NODEF_DEBUGWRAP12(GetLogColorSpaceW)
@@ -423,2 +416,13 @@
 DEBUGWRAP4(UpdateColors)
 DEBUGWRAP4(WidenPath)
+
+
+#undef DBG_LOCALLOG
+#define DBG_LOCALLOG    DBG_devcontext
+
+DEBUGWRAP4(CreateCompatibleDC)
+DEBUGWRAP16(CreateDCA)
+DEBUGWRAP16(CreateDCW)
+DEBUGWRAP16(CreateICA)
+DEBUGWRAP16(CreateICW)
+DEBUGWRAP4(DeleteDC)
Index: trunk/src/gdi32/devcontext.cpp
===================================================================
--- trunk/src/gdi32/devcontext.cpp	(revision 10373)
+++ trunk/src/gdi32/devcontext.cpp	(revision 10373)
@@ -0,0 +1,463 @@
+/* $Id: devcontext.cpp,v 1.1 2004-01-11 11:42:09 sandervl Exp $ */
+
+/*
+ * GDI32 device context apis
+ *
+ * Copyright 1998 Sander van Leeuwen (sandervl@xs4all.nl)
+ * Copyright 1998 Patrick Haller
+ * Copyright 2003 Innotek Systemberatung GmbH (sandervl@innotek.de)
+ *
+ * Project Odin Software License can be found in LICENSE.TXT
+ *
+ */
+#include <os2win.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <odinwrap.h>
+#include <misc.h>
+#include "callback.h"
+#include "unicode.h"
+#include "dibsect.h"
+#include <codepage.h>
+#include "oslibgpi.h"
+#include "oslibgdi.h"
+#include <dcdata.h>
+#include <winuser32.h>
+#include "font.h"
+#include <stats.h>
+#include <objhandle.h>
+#include <winspool.h>
+#include "region.h"
+#include <wingdi32.h>
+
+#define DBG_LOCALLOG    DBG_devcontext
+#include "dbglocal.h"
+
+typedef BOOL (* WIN32API PFN_SPLQUERYPMQUEUENAME)(LPSTR pDeviceName, LPSTR lpszPMQueue, INT cbPMQueue);
+
+#ifdef DEBUG
+void dprintfDEVMODE(DEVMODEA *lpInitData);
+#else
+#define dprintfDEVMODE(a)
+#endif
+
+static const char *szDisplay = "DISPLAY";
+
+//******************************************************************************
+// GetPMQueueName
+//
+// Get the PM printer queue name associated with the printer name
+//
+// NOTE: We can't have a hardcoded dependency on WINSPOOL in GDI32, so get the
+//       function address dynamically
+//
+//******************************************************************************
+static BOOL GetPMQueueName(LPSTR pDeviceName, LPSTR lpszPMQueue, INT cbPMQueue)
+{
+    return FALSE;
+}
+//******************************************************************************
+//******************************************************************************
+HDC WIN32API CreateDCA(LPCSTR lpszDriver, LPCSTR lpszDevice, LPCSTR lpszOutput, const DEVMODEA *lpInitData)
+{
+    HDC  hdc;
+    char szDevice[256];
+
+    // 2001-05-28 PH
+    // Ziff Davis Benchmarks come in here with "display".
+    // Obviously, Windows does accept case-insensitive driver names,
+    // whereas Open32 doesn't.
+    if(lpszDriver && !stricmp(lpszDriver, szDisplay)) {
+        lpszDriver = szDisplay;
+    }
+    else
+    { //Check if it's a printer device
+        if(GetPMQueueName((LPSTR)lpszDevice, szDevice, sizeof(szDevice)) == TRUE) 
+        {
+            dprintf(("Rename printer %s to PM Queue %s", lpszDevice, szDevice));
+            lpszDevice = szDevice;
+            //Must ignore port name here or else the wrong queue might be used
+            lpszOutput = NULL;
+        }
+    }
+
+    //SvL: Open32 tests lpszDriver for NULL even though it's ignored
+    if(lpszDriver == NULL) {
+        lpszDriver = lpszDevice;
+    }
+
+    if(lpInitData) {
+        dprintfDEVMODE((DEVMODEA *)lpInitData);
+    }
+
+    hdc = O32_CreateDC(lpszDriver, lpszDevice, lpszOutput, lpInitData);
+    if(hdc) {
+        OSLibGpiSetCp(hdc, GetDisplayCodepage());
+        STATS_CreateDCA(hdc, lpszDriver, lpszDevice, lpszOutput, lpInitData);
+    }
+
+    dprintf(("GDI32: CreateDCA %s %s %s %x returned %x", lpszDriver, lpszDevice, lpszOutput, lpInitData, hdc));
+    return hdc;
+}
+//******************************************************************************
+//******************************************************************************
+HDC WIN32API CreateDCW( LPCWSTR arg1, LPCWSTR arg2, LPCWSTR arg3, const DEVMODEW * arg4)
+{
+    char *astring4, *astring5;
+
+    char *astring1 = UnicodeToAsciiString((LPWSTR)arg1);
+    char *astring2 = UnicodeToAsciiString((LPWSTR)arg2);
+    char *astring3 = UnicodeToAsciiString((LPWSTR)arg3);
+
+    if(arg4)
+    {
+      astring4 = UnicodeToAsciiString((LPWSTR)(arg4->dmDeviceName));
+      astring5 = UnicodeToAsciiString((LPWSTR)(arg4->dmFormName));
+    }
+
+    HDC   rc;
+    DEVMODEA devmode;
+
+    if(arg4)
+    {
+      strcpy((char*)devmode.dmDeviceName, astring4);
+      strcpy((char*)devmode.dmFormName, astring5);
+
+      devmode.dmSpecVersion      = arg4->dmSpecVersion;
+      devmode.dmDriverVersion    = arg4->dmDriverVersion;
+      devmode.dmSize             = arg4->dmSize;
+      devmode.dmDriverExtra      = arg4->dmDriverExtra;
+      devmode.dmFields           = arg4->dmFields;
+#if (__IBMCPP__ == 360)
+      devmode.dmOrientation   = arg4->dmOrientation;
+      devmode.dmPaperSize     = arg4->dmPaperSize;
+      devmode.dmPaperLength   = arg4->dmPaperLength;
+      devmode.dmPaperWidth    = arg4->dmPaperWidth; 
+#else
+      devmode.s1.dmOrientation   = arg4->s1.dmOrientation;
+      devmode.s1.dmPaperSize     = arg4->s1.dmPaperSize;
+      devmode.s1.dmPaperLength   = arg4->s1.dmPaperLength;
+      devmode.s1.dmPaperWidth    = arg4->s1.dmPaperWidth; 
+#endif
+      devmode.dmScale            = arg4->dmScale;
+      devmode.dmCopies           = arg4->dmCopies;
+      devmode.dmDefaultSource    = arg4->dmDefaultSource;
+      devmode.dmPrintQuality     = arg4->dmPrintQuality;
+      devmode.dmColor            = arg4->dmColor;
+      devmode.dmDuplex           = arg4->dmDuplex;
+      devmode.dmYResolution      = arg4->dmYResolution;
+      devmode.dmTTOption         = arg4->dmTTOption;
+      devmode.dmCollate          = arg4->dmCollate;
+      devmode.dmLogPixels        = arg4->dmLogPixels;
+      devmode.dmBitsPerPel       = arg4->dmBitsPerPel;
+      devmode.dmPelsWidth        = arg4->dmPelsWidth;
+      devmode.dmPelsHeight       = arg4->dmPelsHeight;
+      devmode.dmDisplayFlags     = arg4->dmDisplayFlags;
+      devmode.dmDisplayFrequency = arg4->dmDisplayFrequency;
+      devmode.dmICMMethod        = arg4->dmICMMethod;
+      devmode.dmICMIntent        = arg4->dmICMIntent;
+      devmode.dmMediaType        = arg4->dmMediaType;
+      devmode.dmDitherType       = arg4->dmDitherType;
+      devmode.dmReserved1        = arg4->dmReserved1;
+      devmode.dmReserved2        = arg4->dmReserved2;
+      rc = CreateDCA(astring1,astring2,astring3,&devmode);
+    }
+    else
+      rc = CreateDCA(astring1,astring2,astring3, NULL);
+
+    FreeAsciiString(astring1);
+    FreeAsciiString(astring2);
+    FreeAsciiString(astring3);
+
+    if(arg4)
+    {
+      FreeAsciiString(astring4);
+      FreeAsciiString(astring5);
+    }
+
+    return rc;
+}
+//******************************************************************************
+//******************************************************************************
+HDC WIN32API CreateICA(LPCSTR lpszDriver, LPCSTR lpszDevice, LPCSTR lpszOutput,
+                       const DEVMODEA *lpdvmInit)
+{
+    HDC  hdc;
+    char szDevice[256];
+
+    //SvL: Open32 tests for "DISPLAY"
+    if(lpszDriver && !stricmp(lpszDriver, szDisplay)) {
+        lpszDriver = szDisplay;
+    }
+    else
+    { //Check if it's a printer device
+        if(GetPMQueueName((LPSTR)lpszDevice, szDevice, sizeof(szDevice)) == TRUE) 
+        {
+            dprintf(("Rename printer %s to PM Queue %s", lpszDevice, szDevice));
+            lpszDevice = szDevice;
+            //Must ignore port name here or else the wrong queue might be used
+            lpszOutput = NULL;
+        }
+    }
+  
+    //SvL: Open32 tests lpszDriver for NULL even though it's ignored
+    if(lpszDriver == NULL) {
+        lpszDriver = lpszDevice;
+    }
+    hdc = O32_CreateIC(lpszDriver, lpszDevice, lpszOutput, lpdvmInit);
+
+    dprintf(("GDI32: CreateICA %s %s %s %x returned %x", lpszDriver, lpszDevice, lpszOutput, lpdvmInit, hdc));
+
+    if(hdc) STATS_CreateICA(hdc, lpszDriver, lpszDevice, lpszOutput, lpdvmInit);
+    return hdc;
+}
+//******************************************************************************
+//******************************************************************************
+HDC WIN32API CreateICW( LPCWSTR arg1, LPCWSTR arg2, LPCWSTR arg3, const DEVMODEW * arg4)
+{
+    char *astring4, *astring5;
+
+    char *astring1 = UnicodeToAsciiString((LPWSTR)arg1);
+    char *astring2 = UnicodeToAsciiString((LPWSTR)arg2);
+    char *astring3 = UnicodeToAsciiString((LPWSTR)arg3);
+    if(arg4)
+    {
+      astring4 = UnicodeToAsciiString((LPWSTR)(arg4->dmDeviceName));
+      astring5 = UnicodeToAsciiString((LPWSTR)(arg4->dmFormName));
+    }
+
+    HDC   rc;
+    DEVMODEA devmode;
+
+    if(arg4)
+    {
+      strcpy((char*)devmode.dmDeviceName, astring4);
+      strcpy((char*)devmode.dmFormName, astring5);
+
+      devmode.dmSpecVersion      = arg4->dmSpecVersion;
+      devmode.dmDriverVersion    = arg4->dmDriverVersion;
+      devmode.dmSize             = arg4->dmSize;
+      devmode.dmDriverExtra      = arg4->dmDriverExtra;
+      devmode.dmFields           = arg4->dmFields;
+#if (__IBMCPP__ == 360)
+      devmode.dmOrientation      = arg4->dmOrientation;
+      devmode.dmPaperSize        = arg4->dmPaperSize;
+      devmode.dmPaperLength      = arg4->dmPaperLength;
+      devmode.dmPaperWidth       = arg4->dmPaperWidth; 
+#else
+      devmode.s1.dmOrientation   = arg4->s1.dmOrientation;
+      devmode.s1.dmPaperSize     = arg4->s1.dmPaperSize;
+      devmode.s1.dmPaperLength   = arg4->s1.dmPaperLength;
+      devmode.s1.dmPaperWidth    = arg4->s1.dmPaperWidth;
+#endif
+      devmode.dmScale            = arg4->dmScale;
+      devmode.dmCopies           = arg4->dmCopies;
+      devmode.dmDefaultSource    = arg4->dmDefaultSource;
+      devmode.dmPrintQuality     = arg4->dmPrintQuality;
+      devmode.dmColor            = arg4->dmColor;
+      devmode.dmDuplex           = arg4->dmDuplex;
+      devmode.dmYResolution      = arg4->dmYResolution;
+      devmode.dmTTOption         = arg4->dmTTOption;
+      devmode.dmCollate          = arg4->dmCollate;
+      devmode.dmLogPixels        = arg4->dmLogPixels;
+      devmode.dmBitsPerPel       = arg4->dmBitsPerPel;
+      devmode.dmPelsWidth        = arg4->dmPelsWidth;
+      devmode.dmPelsHeight       = arg4->dmPelsHeight;
+      devmode.dmDisplayFlags     = arg4->dmDisplayFlags;
+      devmode.dmDisplayFrequency = arg4->dmDisplayFrequency;
+      devmode.dmICMMethod        = arg4->dmICMMethod;
+      devmode.dmICMIntent        = arg4->dmICMIntent;
+      devmode.dmMediaType        = arg4->dmMediaType;
+      devmode.dmDitherType       = arg4->dmDitherType;
+      devmode.dmReserved1        = arg4->dmReserved1;
+      devmode.dmReserved2        = arg4->dmReserved2;
+
+      rc = CreateICA(astring1,astring2,astring3,&devmode);
+    }
+    else
+      rc = CreateICA(astring1,astring2,astring3, NULL);
+
+    FreeAsciiString(astring1);
+    FreeAsciiString(astring2);
+    FreeAsciiString(astring3);
+    if(arg4)
+    {
+      FreeAsciiString(astring4);
+      FreeAsciiString(astring5);
+    }
+
+    return rc;
+}
+//******************************************************************************
+//******************************************************************************
+HDC WIN32API CreateCompatibleDC( HDC hdc)
+{
+ HDC newHdc;
+
+    newHdc = O32_CreateCompatibleDC(hdc);
+    ULONG oldcp = OSLibGpiQueryCp(hdc);
+    if (!oldcp) /* If new DC is to be created */
+        oldcp = GetDisplayCodepage();
+
+    if(newHdc) STATS_CreateCompatibleDC(hdc, newHdc);
+    OSLibGpiSetCp(newHdc, oldcp);
+    //PF Open32 seems not to move coordinates to 0,0 in newHdc
+    MoveToEx(newHdc, 0, 0 , NULL);
+
+    return newHdc;
+}
+//******************************************************************************
+//******************************************************************************
+BOOL WIN32API DeleteDC(HDC hdc)
+{
+    pDCData  pHps = (pDCData)OSLibGpiQueryDCData((HPS)hdc);
+    if(!pHps)
+    {
+        dprintf(("WARNING: DeleteDC %x; invalid hdc!", hdc));
+        SetLastError(ERROR_INVALID_HANDLE);
+        return 0;
+    }
+    SetLastError(ERROR_SUCCESS);
+
+    DIBSection *dsect = DIBSection::findHDC(hdc);
+    if(dsect)
+    {
+        //remove previously selected dibsection
+        dprintf(("DeleteDC %x, unselect DIB section %x", hdc, dsect->GetBitmapHandle()));
+        dsect->UnSelectDIBObject();
+    }
+
+    //Must call ReleaseDC for window dcs
+    if(pHps->hdcType == TYPE_1) {
+        return ReleaseDC(OS2ToWin32Handle(pHps->hwnd), hdc);
+    }
+
+    STATS_DeleteDC(hdc);
+    return O32_DeleteDC(hdc);
+}
+//******************************************************************************
+//******************************************************************************
+int WIN32API SaveDC( HDC hdc)
+{
+    int      id;
+    pDCData  pHps = (pDCData)OSLibGpiQueryDCData((HPS)hdc);
+    if(!pHps)
+    {
+        dprintf(("WARNING: SaveDC %x; invalid hdc!", hdc));
+        SetLastError(ERROR_INVALID_HANDLE);
+        return 0;
+    }
+
+    HRGN hClipRgn = 0;
+    if(pHps->hrgnWin32Clip) {
+        // Make a copy of our current clip region
+        // (the visible region remains untouched!)     
+        hClipRgn = GdiCopyClipRgn(pHps);
+    }
+
+    id = O32_SaveDC(hdc);
+    if(id == 0) {
+         dprintf(("ERROR: GDI32: SaveDC %x FAILED", hdc));
+         if(hClipRgn) GdiDestroyRgn(pHps, hClipRgn);
+         return 0;
+    }
+    //overwrite the current clip region with the copy
+    pHps->hrgnWin32Clip = hClipRgn;
+    return id;
+}
+//******************************************************************************
+//******************************************************************************
+BOOL WIN32API RestoreDC(HDC hdc, int id)
+{
+    BOOL ret;
+    HRGN hrgnOldClip = 0;
+
+    pDCData  pHps = (pDCData)OSLibGpiQueryDCData((HPS)hdc);
+    if(!pHps)
+    {
+        dprintf(("WARNING: RestoreDC %x; invalid hdc!", hdc));
+        SetLastError(ERROR_INVALID_HANDLE);
+        return 0;
+    }
+
+    hrgnOldClip = pHps->hrgnWin32Clip;
+    ret = O32_RestoreDC(hdc, id);
+    if(ret == FALSE) {
+        dprintf(("ERROR: GDI32: RestoreDC %x %d FAILED", hdc, id));
+    }
+    else {
+        //Destroy copy of the clip region that we made in SaveDC
+        if(hrgnOldClip) GdiDestroyRgn(pHps, hrgnOldClip);
+
+        // Activate previous clip region
+        GdiCombineVisRgnClipRgn(pHps, pHps->hrgnWin32Clip, RGN_AND);
+    }
+    return ret;
+}
+//******************************************************************************
+//******************************************************************************
+HDC WIN32API ResetDCA(HDC hdc, const DEVMODEA *lpInitData)
+{
+    if(lpInitData) 
+    {
+        dprintfDEVMODE((DEVMODEA *)lpInitData);
+   }
+   HDC ret =O32_ResetDC(hdc, lpInitData);
+   return ret;
+}
+//******************************************************************************
+//******************************************************************************
+HDC WIN32API ResetDCW( HDC arg1, const DEVMODEW *  arg2)
+{
+    dprintf(("GDI32: ResetDCW: not properly implemented"));
+    DebugInt3();
+    // NOTE: This will not work as is (needs UNICODE support)
+    return (HDC)O32_ResetDC(arg1, (const DEVMODEA *)arg2);
+}
+//******************************************************************************
+//******************************************************************************
+#ifdef DEBUG
+void dprintfDEVMODE(DEVMODEA *lpInitData)
+{
+        dprintf(("devmode.dmSpecVersion %x", lpInitData->dmSpecVersion));
+        dprintf(("devmode.dmDriverVersion %x",lpInitData->dmDriverVersion));
+        dprintf(("devmode.dmSize %x", lpInitData->dmSize));
+        dprintf(("devmode.dmDriverExtra %x", lpInitData->dmDriverExtra));
+        dprintf(("devmode.dmFields %x", lpInitData->dmFields));
+#if (__IBMCPP__ == 360)
+        dprintf(("devmode.dmOrientation %x", lpInitData->dmOrientation));
+        dprintf(("devmode.dmPaperSize %x", lpInitData->dmPaperSize));
+        dprintf(("devmode.dmPaperLength %x", lpInitData->dmPaperLength));
+        dprintf(("devmode.dmPaperWidth %x", lpInitData->dmPaperWidth));
+#else
+        dprintf(("devmode.dmOrientation %x", lpInitData->s1.dmOrientation));
+        dprintf(("devmode.dmPaperSize %x", lpInitData->s1.dmPaperSize));
+        dprintf(("devmode.dmPaperLength %x", lpInitData->s1.dmPaperLength));
+        dprintf(("devmode.dmPaperWidth %x", lpInitData->s1.dmPaperWidth));
+#endif
+        dprintf(("devmode.dmScale %x", lpInitData->dmScale));
+        dprintf(("devmode.dmCopies %x", lpInitData->dmCopies));
+        dprintf(("devmode.dmDefaultSource %x", lpInitData->dmDefaultSource));
+        dprintf(("devmode.dmPrintQuality %x", lpInitData->dmPrintQuality));
+        dprintf(("devmode.dmColor %x", lpInitData->dmColor));
+        dprintf(("devmode.dmDuplex %x", lpInitData->dmDuplex));
+        dprintf(("devmode.dmYResolution %x", lpInitData->dmYResolution));
+        dprintf(("devmode.dmTTOption %x", lpInitData->dmTTOption));
+        dprintf(("devmode.dmCollate %x", lpInitData->dmCollate));
+        dprintf(("devmode.dmLogPixels %x", lpInitData->dmLogPixels));
+        dprintf(("devmode.dmBitsPerPel %x", lpInitData->dmBitsPerPel));
+        dprintf(("devmode.dmPelsWidth %x", lpInitData->dmPelsWidth));
+        dprintf(("devmode.dmPelsHeight %x", lpInitData->dmPelsHeight));
+        dprintf(("devmode.dmDisplayFlags %x", lpInitData->dmDisplayFlags));
+        dprintf(("devmode.dmDisplayFrequency %x", lpInitData->dmDisplayFrequency));
+        dprintf(("devmode.dmICMMethod %x", lpInitData->dmICMMethod));
+        dprintf(("devmode.dmICMIntent %x", lpInitData->dmICMIntent));
+        dprintf(("devmode.dmMediaType %x", lpInitData->dmMediaType));
+        dprintf(("devmode.dmDitherType %x", lpInitData->dmDitherType));
+        dprintf(("devmode.dmReserved1 %x", lpInitData->dmReserved1));
+        dprintf(("devmode.dmReserved2 %x", lpInitData->dmReserved2));
+}
+#endif
+//******************************************************************************
+//******************************************************************************
Index: trunk/src/gdi32/dibitmap.cpp
===================================================================
--- trunk/src/gdi32/dibitmap.cpp	(revision 10372)
+++ trunk/src/gdi32/dibitmap.cpp	(revision 10373)
@@ -1,3 +1,3 @@
-/* $Id: dibitmap.cpp,v 1.41 2003-07-16 10:46:17 sandervl Exp $ */
+/* $Id: dibitmap.cpp,v 1.42 2004-01-11 11:42:10 sandervl Exp $ */
 
 /*
@@ -6,4 +6,5 @@
  * Copyright 1998 Sander van Leeuwen (sandervl@xs4all.nl)
  * Copyright 1998 Patrick Haller
+ * Copyright 2002-2003 Innotek Systemberatung GmbH (sandervl@innotek.de)
  *
  * Project Odin Software License can be found in LICENSE.TXT
@@ -320,5 +321,5 @@
     if(dsect)
     {
-        return(dsect->SetDIBColorTable(uStartIndex, cEntries, pColors));
+         return(dsect->SetDIBColorTable(uStartIndex, cEntries, pColors));
     }
     else return(0);
@@ -326,8 +327,13 @@
 //******************************************************************************
 //******************************************************************************
-LONG WIN32API GetBitmapBits( HBITMAP hBitmap, LONG arg2, PVOID  arg3)
+LONG WIN32API GetBitmapBits( HBITMAP hBitmap, LONG arg2, PVOID lpvBits)
 {
     dprintf(("GDI32: GetBitmapBits %x", hBitmap));
-    return O32_GetBitmapBits(hBitmap, arg2, arg3);
+
+    if(lpvBits)
+    {
+        DIBSECTION_CHECK_IF_DIRTY_BMP(hBitmap);
+    }
+    return O32_GetBitmapBits(hBitmap, arg2, lpvBits);
 }
 //******************************************************************************
@@ -335,6 +341,10 @@
 LONG WIN32API SetBitmapBits( HBITMAP hBitmap, LONG arg2, const VOID *  arg3)
 {
+    LONG ret;
+
     dprintf(("GDI32: SetBitmapBits %x", hBitmap));
-    return O32_SetBitmapBits(hBitmap, (DWORD)arg2, arg3);
+    ret = O32_SetBitmapBits(hBitmap, (DWORD)arg2, arg3);
+    DIBSECTION_MARK_INVALID_BMP(hBitmap);
+    return ret;
 }
 //******************************************************************************
@@ -364,27 +374,8 @@
     dprintf(("GDI32: GetDIBits %x %x %d %d %x %x (biBitCount %d) %d", hdc, hBitmap, uStartScan, cScanLines, lpvBits, lpbi, lpbi->bmiHeader.biBitCount, uUsage));
 
-#if 0
-    if(lpvBits && DIBSection::getSection() != NULL)
-    {
-        DIBSection *dsect;
-
-        dsect = DIBSection::findObj(hBitmap);
-        if(dsect) {
-             char *bmpBits = dsect->GetDIBObject();
-
-             if(lpbi->bmiHeader.biBitCount == dsect->GetBitCount() && 
-                lpbi->bmiHeader.biWidth > 0) 
-             {
-                 LONG lLineByte;
-
-                 dprintf(("Quick copy from DIB section memory"));
-                 lLineByte = DIB_GetDIBWidthBytes(lpbi->bmiHeader.biWidth, lpbi->bmiHeader.biBitCount);
-                 
-                 memcpy(lpvBits, bmpBits+(uStartScan*lLineByte), cScanLines*lLineByte);
-                 return cScanLines;
-             }
-        }
-    }
-#endif
+    if(lpvBits)
+    {
+        DIBSECTION_CHECK_IF_DIRTY_BMP(hBitmap);
+    }
 
     //SvL: WGSS screws up the DC if it's a memory DC
@@ -397,7 +388,7 @@
     }
     if(pHps->isMemoryPS) {
-          hdcMem = CreateCompatibleDC(0);
-    }
-    else  hdcMem = hdc;
+         hdcMem = CreateCompatibleDC(0);
+    }
+    else hdcMem = hdc;
 
     if(lpvBits) {
@@ -547,4 +538,6 @@
         ret = O32_SetBitmapBits(hBitmap, pBitmapInfo->bmiHeader.biSizeImage, newpix);
 
+        DIBSECTION_MARK_INVALID_BMP(hBitmap);
+
         free(newpix);
         return ret;
@@ -624,15 +617,5 @@
     if(newbits) free(newbits);
 
-    if(DIBSection::getSection() != NULL)
-    {
-        DIBSection *dsect;
-
-        dsect = DIBSection::findObj(hBitmap);
-        if(dsect) {
-             HBITMAP hBmpOld = SelectObject(hdc, hBitmap);
-             dsect->sync(hdc, 0, dsect->GetHeight());
-             SelectObject(hdc, hBmpOld);
-        }
-    }
+    DIBSECTION_MARK_INVALID_BMP(hBitmap);
 
     return ret;
Index: trunk/src/gdi32/dibsect.cpp
===================================================================
--- trunk/src/gdi32/dibsect.cpp	(revision 10372)
+++ trunk/src/gdi32/dibsect.cpp	(revision 10373)
@@ -1,3 +1,3 @@
-/* $Id: dibsect.cpp,v 1.67 2003-07-16 10:46:17 sandervl Exp $ */
+/* $Id: dibsect.cpp,v 1.68 2004-01-11 11:42:10 sandervl Exp $ */
 
 /*
@@ -6,9 +6,35 @@
  * Copyright 1998-2000 Sander van Leeuwen (sandervl@xs4all.nl)
  * Copyright 1998 Patrick Haller
+ * Copyright 2002-2003 Innotek Systemberatung GmbH (sandervl@innotek.de)
  *
  * Project Odin Software License can be found in LICENSE.TXT
  *
- * NOTE:
- * This is not a complete solution for CreateDIBSection, but enough for Quake 2!
+ * Basic GPI object and bitmap data synchronization:
+ *
+ * - CreateDIBSection:
+ *      register a memory range for exception notification
+ *      set to read/commit during creation
+ *
+ * - if(exception)
+ *      if(invalid)
+ *         sync and set to commit/read, clear invalid flag
+ *      if(write violation) 
+ *         make as dirty and set range to read/write
+ *
+ * - before GDI operation
+ *       if(dirty) 
+ *           flush (set bitmap bits), clear dirty flag, set range to readonly
+ *
+ * - after GDI operation
+ *       set invalid flag, set range to invalid
+ *
+ * - GdiFlush: 
+ *       NOP
+ *
+ * Should probably detect partial changes to avoid having to sync the entire
+ * DIB section each time something minor changes.
+ *
+ * Might get a little bit more complicated when the application gives us a memory
+ * mapped file handle. (although we can change the protection flags of aliased pages)
  *
  */
@@ -27,14 +53,18 @@
 #include "oslibgpi.h"
 #include "rgbcvt.h"
+#include <memmap.h>
 
 #define DBG_LOCALLOG  DBG_dibsect
 #include "dbglocal.h"
 
-
-//******************************************************************************
-//******************************************************************************
-DIBSection::DIBSection(BITMAPINFOHEADER_W *pbmi, char *pColors, DWORD iUsage, DWORD hSection, DWORD dwOffset, DWORD handle, int fFlip)
+static BOOL WIN32API DIBExceptionNotify(LPVOID lpBase, ULONG offset, BOOL fWriteAccess, 
+                                        DWORD dwSize, DWORD dwUserData);
+
+
+//******************************************************************************
+//******************************************************************************
+DIBSection::DIBSection(BITMAPINFOHEADER_W *pbmi, char *pColors, DWORD iUsage, DWORD hSection, DWORD dwOffset, HBITMAP hBitmap, int fFlip)
                 : bmpBits(NULL), pOS2bmp(NULL), next(NULL), bmpBitsDblBuffer(NULL),
-                  hdc(0), hwndParent(0)
+                  hdc(0), hwndParent(0), fDirty(FALSE), fInvalid(FALSE), dwSize(0)
 {
  int  palsize=0;
@@ -90,7 +120,17 @@
    }
    if(!bmpBits) {
-        DosAllocMem((PPVOID)&bmpBits, bmpsize*pbmi->biHeight, PAG_READ|PAG_WRITE|PAG_COMMIT);
-   }
-   memset(bmpBits, 0, bmpsize*pbmi->biHeight);
+        APIRET rc = DosAllocMem((PPVOID)&bmpBits, bmpsize*pbmi->biHeight, PAG_READ|PAG_COMMIT);
+        if(rc) {
+            dprintf(("DosAllocMem failed with %d", rc));
+            DebugInt3();
+        }
+        if(MMAP_RegisterMemoryRange(DIBExceptionNotify, bmpBits, bmpsize*pbmi->biHeight, hBitmap) == FALSE) 
+        {
+            dprintf(("MMAP_RegisterMemoryRange failed!!"));
+            DebugInt3();
+        }
+        dwSize = bmpsize*pbmi->biHeight;
+   }
+   else memset(bmpBits, 0, bmpsize*pbmi->biHeight);
 
    pOS2bmp = (BITMAPINFO2 *)malloc(os2bmphdrsize);
@@ -111,5 +151,5 @@
    }
    pOS2bmp->cbImage       = pbmi->biSizeImage;
-   dprintf(("handle                 %x", handle));
+   dprintf(("hBitmap                %x", hBitmap));
    dprintf(("pOS2bmp->cx            %d\n", pOS2bmp->cx));
    dprintf(("pOS2bmp->cy            %d\n", pOS2bmp->cy));
@@ -169,5 +209,5 @@
    }
 
-   this->handle = handle;
+   this->hBitmap = hBitmap;
    this->iUsage = iUsage;
 
@@ -197,174 +237,42 @@
 DIBSection::~DIBSection()
 {
-   dprintf(("Delete DIBSection %x", handle));
+   dprintf(("Delete DIBSection %x", hBitmap));
 
    if(hSection) {
-        UnmapViewOfFile(bmpBits);
-   }
-   else
-   if(bmpBits)
-        DosFreeMem(bmpBits);
+       UnmapViewOfFile(bmpBits);
+   }
+   else 
+   {
+       if(MMAP_UnregisterMemoryRange(bmpBits) == FALSE) 
+       {
+           dprintf(("MMAP_UnregisterMemoryRange failed!!"));
+           DebugInt3();
+       }
+       if(bmpBits)
+           DosFreeMem(bmpBits);
+   }
 
    if(bmpBitsDblBuffer)
-        DosFreeMem(bmpBitsDblBuffer);
+       DosFreeMem(bmpBitsDblBuffer);
 
    if(pOS2bmp)
-        free(pOS2bmp);
+       free(pOS2bmp);
 
    lock();
    if(section == this)
    {
-     section = this->next;
+       section = this->next;
    }
    else
    {
-     DIBSection *dsect = section;
-
-     while(dsect->next != this)
-     {
-       dsect = dsect->next;
-     }
-     dsect->next = this->next;
+       DIBSection *dsect = section;
+
+       while(dsect->next != this)
+       {
+           dsect = dsect->next;
+       }
+       dsect->next = this->next;
    }
    unlock();
-}
-//******************************************************************************
-//******************************************************************************
-int DIBSection::SetDIBits(HDC hdc, HBITMAP hbitmap, UINT startscan, UINT
-                          lines, const VOID *bits, BITMAPINFOHEADER_W *pbmi,
-                          UINT coloruse)
-{
-  lines = (int)lines >= 0 ? (int)lines : (int)-lines;
-  int  palsize=0;
-
-  bmpsize = pbmi->biWidth;
-  os2bmphdrsize = sizeof(BITMAPINFO2);
-
-  switch(pbmi->biBitCount)
-  {
-    case 1:
-      bmpsize = ((bmpsize + 31) & ~31) / 8;
-      palsize = ((1 << pbmi->biBitCount))*sizeof(RGB2);
-      os2bmphdrsize += palsize;
-      break;
-    case 4:
-      bmpsize = ((bmpsize + 7) & ~7) / 2;
-      palsize = ((1 << pbmi->biBitCount))*sizeof(RGB2);
-      os2bmphdrsize += palsize;
-      break;
-    case 8:
-      palsize = ((1 << pbmi->biBitCount))*sizeof(RGB2);
-      os2bmphdrsize += palsize;
-      bmpsize = (bmpsize + 3) & ~3;
-      break;
-    case 16:
-      bmpsize *= 2;
-      bmpsize = (bmpsize + 3) & ~3;
-      break;
-    case 24:
-      bmpsize *= 3;
-      bmpsize = (bmpsize + 3) & ~3;
-      break;
-    case 32:
-      bmpsize *= 4;
-      break;
-   }
-
-   //SvL: TODO: Correct??
-   if(!hSection && pOS2bmp->cx != pbmi->biWidth && pOS2bmp->cy != pbmi->biHeight &&
-      pOS2bmp->cBitCount != pbmi->biBitCount)
-   {
-        char *oldbits = bmpBits;
-        int oldsize = dibinfo.dsBm.bmWidthBytes * dibinfo.dsBm.bmHeight;
-
-        DosAllocMem((PPVOID)&bmpBits, bmpsize*pbmi->biHeight, PAG_READ|PAG_WRITE|PAG_COMMIT);
-        memcpy(bmpBits, oldbits, min(oldsize, bmpsize*pbmi->biHeight));
-        DosFreeMem(oldbits);
-   }
-   pOS2bmp    = (BITMAPINFO2 *)realloc(pOS2bmp, os2bmphdrsize);
-   pOS2bmp->cbFix         = sizeof(BITMAPINFO2) - sizeof(RGB2);
-   pOS2bmp->cx            = pbmi->biWidth;
-   pOS2bmp->cy            = pbmi->biHeight;
-   pOS2bmp->cPlanes       = pbmi->biPlanes;
-   pOS2bmp->cBitCount     = pbmi->biBitCount;
-   pOS2bmp->ulCompression = pbmi->biCompression; //same as OS/2 (uncompressed, rle8, rle4)
-   //SvL: Ignore BI_BITFIELDS_W type (GpiDrawBits fails otherwise)
-   if(pOS2bmp->ulCompression == BI_BITFIELDS_W) {
-        pOS2bmp->ulCompression = 0;
-   }
-   pOS2bmp->cbImage       = pbmi->biSizeImage;
-
-   // clear DIBSECTION structure
-   memset(&dibinfo, 0, sizeof(dibinfo));
-
-   // copy BITMAPINFOHEADER data into DIBSECTION structure
-   memcpy(&dibinfo.dsBmih, pbmi, sizeof(*pbmi));
-   dibinfo.dsBm.bmType      = 0;
-   dibinfo.dsBm.bmWidth     = pbmi->biWidth;
-   dibinfo.dsBm.bmHeight    = pbmi->biHeight;
-   dibinfo.dsBm.bmWidthBytes= bmpsize;
-   dibinfo.dsBm.bmPlanes    = pbmi->biPlanes;
-   dibinfo.dsBm.bmBitsPixel = pbmi->biBitCount;
-   dibinfo.dsBm.bmBits      = bmpBits;
-
-   dibinfo.dshSection       = hSection;
-   dibinfo.dsOffset         = dwOffset;
-
-   if(coloruse == DIB_PAL_COLORS || pbmi->biBitCount <= 8)
-   {
-        dibinfo.dsBitfields[0] = dibinfo.dsBitfields[1] = dibinfo.dsBitfields[2] = 0;
-   }
-   else {
-        char *pColors = (char *)pbmi + 1;
-
-        switch(pbmi->biBitCount)
-        {
-           case 16:
-                dibinfo.dsBitfields[0] = (pbmi->biCompression == BI_BITFIELDS_W) ? *(DWORD *)pColors : 0x7c00;
-                dibinfo.dsBitfields[1] = (pbmi->biCompression == BI_BITFIELDS_W) ? *((DWORD *)pColors + 1) : 0x03e0;
-                dibinfo.dsBitfields[2] = (pbmi->biCompression == BI_BITFIELDS_W) ? *((DWORD *)pColors + 2) : 0x001f;
-                break;
-
-           case 24:
-           case 32:
-                dibinfo.dsBitfields[0] = (pbmi->biCompression == BI_BITFIELDS_W) ? *(DWORD *)pColors       : 0xff0000;
-                dibinfo.dsBitfields[1] = (pbmi->biCompression == BI_BITFIELDS_W) ? *((DWORD *)pColors + 1) : 0x00ff00;
-                dibinfo.dsBitfields[2] = (pbmi->biCompression == BI_BITFIELDS_W) ? *((DWORD *)pColors + 2) : 0x0000ff;
-                if(dibinfo.dsBitfields[0] != 0xff0000 && dibinfo.dsBitfields[1] != 0xff00 && dibinfo.dsBitfields[2] != 0xff) {
-                    dprintf(("DIBSection: unsupported bitfields for 32 bits bitmap!!"));
-                }
-                break;
-        }
-        dprintf(("BI_BITFIELDS_W %x %x %x", dibinfo.dsBitfields[0], dibinfo.dsBitfields[1], dibinfo.dsBitfields[2]));
-   }
-
-   //double buffer for rgb 555 dib sections (for conversion) or flipped sections
-   if(dibinfo.dsBitfields[1] == 0x03e0 || (fFlip & FLIP_VERT)) {
-        if(bmpBitsDblBuffer) {
-            DosFreeMem(bmpBitsDblBuffer);
-        }
-        DosAllocMem((PPVOID)&bmpBitsDblBuffer, dibinfo.dsBm.bmWidthBytes*pbmi->biHeight, PAG_READ|PAG_WRITE|PAG_COMMIT);
-   }
-
-   dprintf(("DIBSection::SetDIBits (%d,%d), %d %d", pbmi->biWidth, pbmi->biHeight, pbmi->biBitCount, pbmi->biCompression));
-   if(palsize) {
-        SetDIBColorTable(0, (pbmi->biClrUsed) ? pbmi->biClrUsed : (1 << pbmi->biBitCount), (RGBQUAD *)(pbmi+1));
-   }
-
-   if(bits)
-   {
-      if(pOS2bmp->ulCompression == BCA_UNCOMP) {
-          int size = bmpsize*lines;
-          memcpy(bmpBits+bmpsize*startscan, bits, size);
-      }
-      else {
-          dprintf(("Compressed image!!"));
-          if(startscan != 0) {
-               dprintf(("WARNING: Compressed image & startscan != 0!!!!"));
-          }
-          memcpy(bmpBits, bits, pbmi->biSizeImage);
-      }
-   }
-   return(lines);
 }
 //******************************************************************************
@@ -472,6 +380,12 @@
 
   dprintf(("DIBSection::BitBlt %x %X (hps %x) %x to(%d,%d)(%d,%d) from (%d,%d)(%d,%d) rop %x flip %x",
-          handle, hdcDest, hps, hwndDest, nXdest, nYdest, nDestWidth, nDestHeight,
+          hBitmap, hdcDest, hps, hwndDest, nXdest, nYdest, nDestWidth, nDestHeight,
           nXsrc, nYsrc, nSrcWidth, nSrcHeight, Rop, fFlip));
+
+  //shortcut; better to sync it here instead of in the exception handler
+  //(pages touched inside PMGPI)
+  if(isInvalid()) {
+      sync();
+  }
 
   if(hwndDest) {
@@ -637,8 +551,4 @@
   }
   if(rc == GPI_OK) {
-        DIBSection *destdib = DIBSection::findHDC(hdcDest);
-        if(destdib) {
-            destdib->sync(hps, nYdest, nDestHeight, FALSE);
-        }
 #ifdef INVERT
         //restore old y inversion height
@@ -664,5 +574,5 @@
  char  *destBuf;
 
-  dprintf(("Sync destination dibsection %x (%x) (%d,%d) flip %d", handle, hdc, nYdest, nDestHeight, fFlip));
+  dprintf(("Sync destination dibsection %x (%x) (%d,%d) flip %d", hBitmap, hdc, nYdest, nDestHeight, fFlip));
 
   BITMAPINFO2 *tmphdr = (BITMAPINFO2 *)malloc(os2bmphdrsize);
@@ -692,4 +602,5 @@
   if(fFlip & FLIP_VERT) {
 #endif
+        //origin is top left, so no y conversion is necessary
         destBuf = bmpBitsDblBuffer + nYdest*dibinfo.dsBm.bmWidthBytes;
 
@@ -729,6 +640,5 @@
         tmphdr->cbImage = dibinfo.dsBm.bmHeight*dibinfo.dsBm.bmWidthBytes;
 
-        destBuf = GetDIBObject() + nYdest*dibinfo.dsBm.bmWidthBytes;
-
+        //origin is bottom left, nYdest is based on top left coordinate system
 #ifdef INVERT
         int dest = dibinfo.dsBm.bmHeight - nYdest - nDestHeight;
@@ -736,5 +646,8 @@
         int dest = nYdest;
 #endif
-        rc = GpiQueryBitmapBits(hdc, nYdest, nDestHeight, destBuf,
+
+        destBuf = GetDIBObject() + dest*dibinfo.dsBm.bmWidthBytes;
+
+        rc = GpiQueryBitmapBits(hdc, dest, nDestHeight, destBuf,
                                 tmphdr);
         if(rc == GPI_ALTERROR) {
@@ -769,4 +682,228 @@
 #endif
 
+}
+//******************************************************************************
+//******************************************************************************
+void DIBSection::flush(HDC hdc, DWORD nYdest, DWORD nDestHeight, BOOL orgYInversion)
+{
+ APIRET rc;
+ char  *destBuf;
+
+  dprintf(("flush destination dibsection %x (%x) (%d,%d) flip %d", hBitmap, hdc, nYdest, nDestHeight, fFlip));
+
+#ifdef INVERT
+  int oldyinversion = 0;
+  if(orgYInversion == TRUE) {
+      oldyinversion = GpiQueryYInversion(hdc);
+      dprintf(("Flush destination dibsection: hdc y inversion = %d", oldyinversion));
+      if(oldyinversion != 0) {
+#ifdef DEBUG
+          POINT point;
+          GetViewportOrgEx(hdc, &point);
+          dprintf(("Viewport origin (%d,%d)", point.x, point.y));
+#endif
+          GpiEnableYInversion(hdc, 0);
+      }
+  }
+#else
+  dprintf(("flush destination dibsection: hdc y inversion = %d", GpiQueryYInversion(hdc)));
+#endif
+
+#ifndef INVERT
+  if(!(fFlip & FLIP_VERT)) {
+#else
+  if(fFlip & FLIP_VERT) {
+#endif
+        //origin is top left, so no y conversion is necessary
+        destBuf = bmpBitsDblBuffer + nYdest*dibinfo.dsBm.bmWidthBytes;
+
+        //SvL: cbImage can be too small for compressed images; GpiQueryBitmapBits
+        //     will fail in that case (CoolEdit 2000). Perhaps because the returned
+        //     compressed image is larger than the original.
+        //     Use uncompressed size instead
+        //     NOTE: The correct size will be returned by GpiQueryBitmapBits
+        pOS2bmp->cbImage = dibinfo.dsBm.bmHeight*dibinfo.dsBm.bmWidthBytes;
+
+        //manually reverse bitmap data
+        char *src = GetDIBObject() + (nYdest+nDestHeight-1)*dibinfo.dsBm.bmWidthBytes;
+        char *dst = destBuf;
+        for(int i=0;i<nDestHeight;i++) {
+            memcpy(dst, src, dibinfo.dsBm.bmWidthBytes);
+            dst += dibinfo.dsBm.bmWidthBytes;
+            src -= dibinfo.dsBm.bmWidthBytes;
+        }
+
+        if(dibinfo.dsBitfields[1] == 0x3E0) {//RGB 555?
+            dprintf(("DIBSection::flush: convert RGB 565 to RGB 555"));
+
+            pRGB565to555((WORD *)destBuf, (WORD *)destBuf, (nDestHeight*dibinfo.dsBm.bmWidthBytes)/sizeof(WORD));
+        }
+
+#ifdef INVERT
+        int dest = dibinfo.dsBm.bmHeight - nYdest - nDestHeight;
+#else
+        int dest = nYdest;
+#endif
+        rc = GpiSetBitmapBits(hdc, dest, nDestHeight, destBuf,
+                              pOS2bmp);
+        if(rc == GPI_ALTERROR) {
+            dprintf(("ERROR: GpiQueryBitmapBits failed with %x", WinGetLastError(0)));
+        }
+
+  }
+  else {
+        //SvL: cbImage can be too small for compressed images; GpiQueryBitmapBits
+        //     will fail in that case (CoolEdit 2000). Perhaps because the returned
+        //     compressed image is larger than the original.
+        //     Use uncompressed size instead
+        //     NOTE: The correct size will be returned by GpiQueryBitmapBits
+        pOS2bmp->cbImage = dibinfo.dsBm.bmHeight*dibinfo.dsBm.bmWidthBytes;
+
+        //origin is bottom left, nYdest is based on top left coordinate system
+#ifdef INVERT
+        int dest = dibinfo.dsBm.bmHeight - nYdest - nDestHeight;
+#else
+        int dest = nYdest;
+#endif
+
+        destBuf = GetDIBObject() + dest*dibinfo.dsBm.bmWidthBytes;
+
+        if(dibinfo.dsBitfields[1] == 0x3E0) {//RGB 555?
+            dprintf(("DIBSection::flush: convert RGB 565 to RGB 555"));
+
+            pRGB565to555((WORD *)bmpBitsDblBuffer, (WORD *)destBuf, (nDestHeight*dibinfo.dsBm.bmWidthBytes)/sizeof(WORD));
+            destBuf = bmpBitsDblBuffer;
+        }
+
+        rc = GpiSetBitmapBits(hdc, dest, nDestHeight, destBuf,
+                              pOS2bmp);
+        if(rc == GPI_ALTERROR) {
+            dprintf(("ERROR: GpiQueryBitmapBits failed with %x", WinGetLastError(0)));
+        }
+#ifdef DEBUG_PALETTE
+        if(rc != GPI_ALTERROR && pOS2bmp->cBitCount <= 8) {
+            for(int i=0;i<(1<<pOS2bmp->cBitCount);i++)
+            {
+                dprintf2(("Index %d : 0x%08X\n",i, *((ULONG*)(&pOS2bmp->argbColor[i])) ));
+            }
+        }
+#endif
+  }
+  if(rc != nDestHeight) {
+      dprintf(("!WARNING!: GpiQueryBitmapBits returned %d instead of %d scanlines", rc, nDestHeight));
+  }
+
+#ifdef INVERT
+  if(oldyinversion) GpiEnableYInversion(hdc, oldyinversion);
+#endif
+
+}
+//******************************************************************************
+//Mark the DIB section as invalid; a subsequent read or write access must
+//cause a pagefault
+//******************************************************************************
+void DIBSection::setInvalid()
+{
+    if(!fInvalid) {
+        dprintf(("DIBSection::setInvalid %x (%x)", GetBitmapHandle(), GetDIBObject()));
+        APIRET rc = DosSetMem(bmpBits, dwSize, PAG_DECOMMIT);
+        if(rc) {
+            dprintf(("DIBSection::setInvalid: DosSetMem failed with %d!!", rc));
+            DebugInt3();
+        }
+        fInvalid = TRUE;
+    }
+}
+//******************************************************************************
+//******************************************************************************
+void DIBSection::flush()
+{ 
+    if(pOS2bmp == NULL) {
+        DebugInt3();
+        return;
+    }
+    if(hdc == 0) {
+         HBITMAP hOldBmp;
+         HDC hdcFlush = CreateCompatibleDC(0);
+
+         hOldBmp = SelectObject(hdcFlush, hBitmap);
+         flush(hdcFlush, 0, pOS2bmp->cy); 
+
+         SelectObject(hdcFlush, hOldBmp);
+         DeleteDC(hdcFlush);
+    }
+    else flush(hdc, 0, pOS2bmp->cy); 
+
+    APIRET rc = DosSetMem(bmpBits, dwSize, PAG_READ);
+    if(rc) {
+        dprintf(("DIBSection::flush: DosSetMem failed with %d!!", rc));
+        DebugInt3();
+    }
+    fDirty = FALSE;
+}
+//******************************************************************************
+//******************************************************************************
+void DIBSection::sync() 
+{ 
+    if(pOS2bmp == NULL) {
+        DebugInt3();
+        return;
+    }
+    APIRET rc = DosSetMem(bmpBits, dwSize, PAG_COMMIT|PAG_READ|PAG_WRITE);
+    if(rc) {
+        //might already be committed
+        rc = DosSetMem(bmpBits, dwSize, PAG_READ|PAG_WRITE);
+        if(rc) {
+            dprintf(("DIBSection::sync: DosSetMem failed with %d!!", rc));
+            DebugInt3();
+        }
+    }
+    if(hdc == 0) {
+         HBITMAP hOldBmp;
+         HDC hdcFlush = CreateCompatibleDC(0);
+
+         hOldBmp = SelectObject(hdcFlush, hBitmap);
+         sync(hdcFlush, 0, pOS2bmp->cy); 
+
+         SelectObject(hdcFlush, hOldBmp);
+         DeleteDC(hdcFlush);
+    }
+    else sync(hdc, 0, pOS2bmp->cy); 
+   
+    fInvalid = FALSE;
+
+    //Set bitmap memory to readonly again to detect updates
+    rc = DosSetMem(bmpBits, dwSize, PAG_READ);
+    if(rc) {
+        dprintf(("DosSetMem failed with %d!!", rc));
+        DebugInt3();
+    }
+}
+//******************************************************************************
+//******************************************************************************
+void DIBSection::syncAll()
+{
+  if (!section)
+      return;
+
+  lock();
+  DIBSection *dsect = section;
+
+  do
+  {
+      if(dsect->isDirty() && dsect->isInvalid()) {
+          DebugInt3();
+      }
+      if(dsect->isInvalid())
+      {
+          dsect->sync();
+      }
+      dsect = dsect->next;
+  }
+  while(dsect);
+
+  unlock();
+
+  return;
 }
 //******************************************************************************
@@ -796,9 +933,9 @@
   this->hdc  = hdc;
   hwndParent = WindowFromDC(hdc);
-  dprintf(("SelectDIBObject %x into %x hwndParent = %x", handle, hdc, hwndParent));
-}
-//******************************************************************************
-//******************************************************************************
-DIBSection *DIBSection::findObj(HANDLE handle)
+  dprintf(("SelectDIBObject %x into %x hwndParent = %x", hBitmap, hdc, hwndParent));
+}
+//******************************************************************************
+//******************************************************************************
+DIBSection *DIBSection::findObj(HBITMAP hBitmap)
 {
   // PH 2001-08-18 shortcut for performance optimization
@@ -806,10 +943,10 @@
       return NULL;
 
+  lock();
   DIBSection *dsect = section;
-  lock();
 
   do
   {
-    if(dsect->handle == handle)
+    if(dsect->hBitmap == hBitmap)
     {
         unlock();
@@ -832,7 +969,7 @@
       return NULL;
   
+  lock();
   DIBSection *dsect = section;
   
-  lock();
   do
   {
@@ -851,7 +988,7 @@
 //******************************************************************************
 //******************************************************************************
-void DIBSection::deleteSection(HANDLE handle)
-{
- DIBSection *dsect = findObj(handle);
+void DIBSection::deleteSection(HBITMAP hBitmap)
+{
+ DIBSection *dsect = findObj(hBitmap);
 
   if(dsect)
@@ -865,5 +1002,5 @@
  LPBITMAP_W  dsBm        = (LPBITMAP_W)lpBuffer;
 
-  dprintf2(("GetDIBSection %x %d %x", handle, iSize, lpBuffer));
+  dprintf2(("GetDIBSection %x %d %x", hBitmap, iSize, lpBuffer));
   if(iSize == sizeof(DIBSECTION))
   {
@@ -917,2 +1054,50 @@
 DIBSection      *DIBSection::section = NULL;
 CRITICAL_SECTION DIBSection::dibcritsect;
+
+
+//******************************************************************************
+//******************************************************************************
+static BOOL WIN32API DIBExceptionNotify(LPVOID lpBase, ULONG offset, BOOL fWriteAccess, 
+                                        DWORD dwSize, DWORD dwUserData)
+{
+    DIBSection *dsect;
+    HBITMAP hBitmap = (HBITMAP)dwUserData;
+
+    dprintf(("DIBExceptionNotify %x %x %d %d %x", lpBase, offset, fWriteAccess, dwSize, dwUserData));
+
+    dsect = DIBSection::findObj(hBitmap);
+    if(dsect == NULL) {
+        dprintf(("dib section not found!!"));
+        DebugInt3();
+        return FALSE;
+    }
+    if(dsect->isInvalid()) 
+    {//implies read or write to reserved pages
+        //synchronize bitmap memory and bitmap object
+        dsect->sync();
+    }
+    else
+    if(!fWriteAccess) {
+        APIRET rc = DosSetMem(lpBase, dwSize, PAG_READ|PAG_COMMIT);
+        if(rc) {
+            dprintf(("DosSetMem failed with %d!!", rc));
+            DebugInt3();
+            return FALSE;
+        }
+    }
+
+    if(fWriteAccess) {
+        APIRET rc = DosSetMem(lpBase, dwSize, PAG_READ|PAG_WRITE);
+        if(rc) {
+            dprintf(("DosSetMem failed with %d!!", rc));
+            DebugInt3();
+            return FALSE;
+        }
+        dsect->setDirty();
+    }
+
+
+    return TRUE;
+}
+//******************************************************************************
+//******************************************************************************
Index: trunk/src/gdi32/dibsect.h
===================================================================
--- trunk/src/gdi32/dibsect.h	(revision 10372)
+++ trunk/src/gdi32/dibsect.h	(revision 10373)
@@ -1,3 +1,3 @@
-/* $Id: dibsect.h,v 1.27 2003-11-14 17:31:47 sandervl Exp $ */
+/* $Id: dibsect.h,v 1.28 2004-01-11 11:42:11 sandervl Exp $ */
 
 /*
@@ -75,8 +75,53 @@
 #endif
 
+//
+//Mark DIB section as invalid (dib section memory is out of sync with
+//GDI bitmap).
+//
+//This must be done for any GDI function that modifies the bitmap
+//
+#define DIBSECTION_MARK_INVALID(hdc)                              \
+    if(DIBSection::getSection() != NULL) {                        \
+        DIBSection *dib = DIBSection::findHDC(hdc);               \
+        if(dib) {                                                 \
+            dib->setInvalid();                                    \
+        }                                                         \
+    }
+
+#define DIBSECTION_MARK_INVALID_BMP(hBitmap)                      \
+    if(DIBSection::getSection() != NULL) {                        \
+        DIBSection *dib = DIBSection::findObj(hBitmap);           \
+        if(dib) {                                                 \
+            dib->setInvalid();                                    \
+        }                                                         \
+    }
+
+//
+//Check if DIB section is marked dirty (bitmap data modified by application)
+//If true, then update the GDI bitmap
+//
+//This must be done for any GDI function that accesses the bitmap
+//
+#define DIBSECTION_CHECK_IF_DIRTY(hdc)                            \
+    if(DIBSection::getSection() != NULL) {                        \
+        DIBSection *dib = DIBSection::findHDC(hdc);               \
+        if(dib && dib->isDirty()) {                               \
+            dib->flush();                                         \
+        }                                                         \
+    }
+
+#define DIBSECTION_CHECK_IF_DIRTY_BMP(hBitmap)                    \
+    if(DIBSection::getSection() != NULL) {                        \
+        DIBSection *dib = DIBSection::findObj(hBitmap);           \
+        if(dib && dib->isDirty()) {                               \
+            dib->flush();                                         \
+        }                                                         \
+    }
+
+
 class DIBSection
 {
 public:
-              DIBSection(BITMAPINFOHEADER_W *pbmi, char *pColors, DWORD iUsage, DWORD hSection, DWORD dwOffset, DWORD handle, int fFlip);
+              DIBSection(BITMAPINFOHEADER_W *pbmi, char *pColors, DWORD iUsage, DWORD hSection, DWORD dwOffset, HBITMAP hBitmap, int fFlip);
              ~DIBSection();
 
@@ -88,6 +133,11 @@
               void  UnSelectDIBObject()      { this->hdc = 0;   };
 
-        DWORD GetBitmapHandle()      { return handle; };
-              void  SetBitmapHandle(DWORD bmphandle) { handle = bmphandle; };
+              void  setDirty()               { fDirty = TRUE;   };
+              BOOL  isDirty()                { return fDirty;   }
+              void  setInvalid();
+              BOOL  isInvalid()              { return fInvalid; };
+
+        DWORD GetBitmapHandle()              { return hBitmap; };
+              void  SetBitmapHandle(DWORD bmphandle) { hBitmap = bmphandle; };
         DWORD GetRGBUsage()            { return iUsage; };
 
@@ -97,20 +147,22 @@
                            int nSrcWidth, int nSrcHeight,
                            DWORD Rop);
+
+              void  flush();
+              void  sync();
+
               void  sync(HDC hdc, DWORD nYdest, DWORD nDestHeight, BOOL orgYInversion = TRUE);
+              void  flush(HDC hdc, DWORD nYdest, DWORD nDestHeight, BOOL orgYInversion = TRUE);
               void  sync(DWORD xDst, DWORD yDst, DWORD widthDst, DWORD heightDst, PVOID bits);
+
                int  SetDIBColorTable(int startIdx, int cEntries, RGBQUAD *rgb);
                int  GetDIBColorTable(int startIdx, int cEntries, RGBQUAD *rgb);
                int  SetDIBColorTable(int startIdx, int cEntries, PALETTEENTRY *rgb);
 
-               int  SetDIBits(HDC hdc, HBITMAP hbitmap, UINT startscan, UINT
-                              lines, const VOID *bits, BITMAPINFOHEADER_W *pbmi,
-                              UINT coloruse);
-
                int  GetDIBSection(int iSize , void *lpBuffer);
 
  static DIBSection *getSection() { return section; } ;
- static DIBSection *findObj(HANDLE handle);
+ static DIBSection *findObj(HBITMAP hBitmap);
  static DIBSection *findHDC(HDC hdc);
- static       void  deleteSection(HANDLE handle);
+ static       void  deleteSection(HBITMAP hBitmap);
 
  static       void  initDIBSection();
@@ -119,9 +171,12 @@
  static       void  unlock() { LeaveCriticalSection(&dibcritsect); };
 
+ static       void  syncAll();
+
 protected:
 
 private:
-          DWORD handle, iUsage;
-          DWORD hSection, dwOffset;
+          HBITMAP hBitmap;
+ 
+          DWORD hSection, dwOffset, iUsage, dwSize;
           HWND  hwndParent;
           HDC   hdc;
@@ -131,4 +186,7 @@
     DIBSECTION  dibinfo;
 
+          BOOL  fDirty;		//bitmap is out of sync with dib memory
+          BOOL  fInvalid;	//dib memory is out of sync with bitmap
+
     BITMAPINFO2 *pOS2bmp;
                              // Linked list management
@@ -139,7 +197,4 @@
 };
 
-#define DIBSECTION_MARK_INVALID(a)
-#define DIBSECTION_CHECK_IF_DIRTY(a)
-
 #endif
 
Index: trunk/src/gdi32/font.cpp
===================================================================
--- trunk/src/gdi32/font.cpp	(revision 10372)
+++ trunk/src/gdi32/font.cpp	(revision 10373)
@@ -1,3 +1,3 @@
-/* $Id: font.cpp,v 1.34 2004-01-08 11:11:55 sandervl Exp $ */
+/* $Id: font.cpp,v 1.35 2004-01-11 11:42:11 sandervl Exp $ */
 
 /*
@@ -7,4 +7,5 @@
  * Copyright 1999 Sander van Leeuwen (sandervl@xs4all.nl)
  * Copyright 1998 Patrick Haller
+ * Copyright 2003 Innotek Systemberatung GmbH (stauff@innotek.de)
  *
  * TODO: EnumFontsA/W, EnumFontFamiliesExA/W not complete
@@ -32,5 +33,5 @@
 #include <ctype.h>
 #include <string.h>
-#include "misc.h"
+#include <dbglog.h>
 #include "unicode.h"
 #include <heapstring.h>
@@ -40,4 +41,6 @@
 #include <stats.h>
 #include "oslibgpi.h"
+#include "font.h"
+#include "ft2supp.h"
 
 #define DBG_LOCALLOG    DBG_font
@@ -45,5 +48,4 @@
 
 ODINDEBUGCHANNEL(GDI32-FONT)
-
 
 typedef struct {
@@ -95,5 +97,5 @@
   /* reserved for system */
   { DEFAULT_CHARSET, 0, FS(0)},
-  { DEFAULT_CHARSET, 0, FS(0)},
+  { SYMBOL_CHARSET, CP_SYMBOL, FS(31)},
 };
 
@@ -146,80 +148,53 @@
                                   LF_FACESIZE);
 }
-/***********************************************************************
- *           FONT_mbtowc
- *
- * Returns a '\0' terminated Unicode translation of str using the
- * charset of the currently selected font in hdc.  If count is -1 then
- * str is assumed to be '\0' terminated, otherwise it contains the
- * number of bytes to convert.  If plenW is non-NULL, on return it
- * will point to the number of WCHARs (excluding the '\0') that have
- * been written.  If pCP is non-NULL, on return it will point to the
- * codepage used in the conversion (NB, this may be CP_SYMBOL so watch
- * out).  The caller should free the returned LPWSTR from the process
- * heap itself.
- */
-LPWSTR FONT_mbtowc(HDC hdc, LPCSTR str, INT count, INT *plenW, UINT *pCP)
-{
-    UINT cp = CP_ACP;
-    INT lenW, i;
-    LPWSTR strW;
-    CHARSETINFO csi;
-    int charset = GetTextCharset(hdc);
-
-    if( IsDBCSEnv() && ( charset == 0 ))
-        cp = CP_ACP;
-    else
-    /* Hmm, nicely designed api this one! */
-    if(TranslateCharsetInfo((DWORD*)charset, &csi, TCI_SRCCHARSET))
-        cp = csi.ciACP;
-    else {
-        switch(charset) {
-    case OEM_CHARSET:
-        cp = GetOEMCP();
-        break;
-    case DEFAULT_CHARSET:
-        cp = GetACP();
-        break;
-
-    case VISCII_CHARSET:
-    case TCVN_CHARSET:
-    case KOI8_CHARSET:
-    case ISO3_CHARSET:
-    case ISO4_CHARSET:
-      /* FIXME: These have no place here, but because x11drv
-         enumerates fonts with these (made up) charsets some apps
-         might use them and then the FIXME below would become
-         annoying.  Now we could pick the intended codepage for
-         each of these, but since it's broken anyway we'll just
-         use CP_ACP and hope it'll go away...
-      */
-        cp = CP_ACP;
-        break;
-
-
-    default:
-        dprintf(("Can't find codepage for charset %d\n", charset));
-        break;
-    }
-    }
-
-    dprintf(("cp == %d\n", cp));
-
-    if(count == -1) count = strlen(str);
-    if(cp != CP_SYMBOL) {
-        lenW = MultiByteToWideChar(cp, 0, str, count, NULL, 0);
-    strW = (WCHAR*)HeapAlloc(GetProcessHeap(), 0, (lenW + 1) * sizeof(WCHAR));
-    MultiByteToWideChar(cp, 0, str, count, strW, lenW);
-    } else {
-        lenW = count;
-    strW = (WCHAR*)HeapAlloc(GetProcessHeap(), 0, (lenW + 1) * sizeof(WCHAR));
-    for(i = 0; i < count; i++) strW[i] = (BYTE)str[i];
-    }
-    strW[lenW] = '\0';
-    dprintf(("mapped %s -> %ls\n", str, strW));
-    if(plenW) *plenW = lenW;
-    if(pCP) *pCP = cp;
-    return strW;
-}
+#ifdef DEBUG
+//******************************************************************************
+//******************************************************************************
+void dprintfLogFont(LOGFONTA *lplf)
+{
+  dprintf(("GDI32: lfHeight        = %d\n", lplf->lfHeight));
+  dprintf(("GDI32: lfWidth          = %d\n", lplf->lfWidth));
+  dprintf(("GDI32: lfEscapement    = %d\n", lplf->lfEscapement));
+  dprintf(("GDI32: lfOrientation   = %d\n", lplf->lfOrientation));
+  dprintf(("GDI32: lfWeight        = %d\n", lplf->lfWeight));
+  dprintf(("GDI32: lfItalic        = %d\n", lplf->lfItalic));
+  dprintf(("GDI32: lfUnderline     = %d\n", lplf->lfUnderline));
+  dprintf(("GDI32: lfStrikeOut     = %d\n", lplf->lfStrikeOut));
+  dprintf(("GDI32: lfCharSet       = %X\n", lplf->lfCharSet));
+  dprintf(("GDI32: lfOutPrecision  = %X\n", lplf->lfOutPrecision));
+  dprintf(("GDI32: lfClipPrecision = %X\n", lplf->lfClipPrecision));
+  dprintf(("GDI32: lfQuality       = %X\n", lplf->lfQuality));
+  dprintf(("GDI32: lfPitchAndFamily= %X\n", lplf->lfPitchAndFamily));
+  dprintf(("GDI32: lfFaceName      = %s\n", lplf->lfFaceName));
+}
+//******************************************************************************
+//******************************************************************************
+void dprintfTextMetrics(TEXTMETRICA *pwtm)
+{
+    dprintf(("pwtm->tmHeight %d", pwtm->tmHeight));
+    dprintf(("pwtm->tmAscent %d", pwtm->tmAscent));
+    dprintf(("pwtm->tmDescent %d", pwtm->tmDescent));
+    dprintf(("pwtm->tmInternalLeading %d", pwtm->tmInternalLeading));
+    dprintf(("pwtm->tmExternalLeading %d", pwtm->tmExternalLeading));
+    dprintf(("pwtm->tmAveCharWidth %d", pwtm->tmAveCharWidth));
+    dprintf(("pwtm->tmMaxCharWidth %d", pwtm->tmMaxCharWidth));
+    dprintf(("pwtm->tmWeight %d", pwtm->tmWeight));
+    dprintf(("pwtm->tmOverhang %d", pwtm->tmOverhang));
+    dprintf(("pwtm->tmDigitizedAspectX %d", pwtm->tmDigitizedAspectX));
+    dprintf(("pwtm->tmDigitizedAspectY %d", pwtm->tmDigitizedAspectY));
+    dprintf(("pwtm->tmFirstChar %d", pwtm->tmFirstChar));
+    dprintf(("pwtm->tmLastChar %d", pwtm->tmLastChar));
+    dprintf(("pwtm->tmDefaultChar %d", pwtm->tmDefaultChar));
+    dprintf(("pwtm->tmBreakChar %d", pwtm->tmBreakChar));
+    dprintf(("pwtm->tmItalic %x", pwtm->tmItalic));
+    dprintf(("pwtm->tmUnderlined %x", pwtm->tmUnderlined));
+    dprintf(("pwtm->tmStruckOut %x", pwtm->tmStruckOut));
+    dprintf(("pwtm->tmPitchAndFamily %x", pwtm->tmPitchAndFamily));
+    dprintf(("pwtm->tmCharSet %x", pwtm->tmCharSet));
+}
+#else
+#define dprintfLogFont(a)
+#define dprintfTextMetrics(a)
+#endif
 //******************************************************************************
 //******************************************************************************
@@ -336,20 +311,4 @@
   dprintf(("lpszFace = (%x) %s -> %s\n", lplf->lfFaceName, lplf->lfFaceName, afont.lfFaceName));
 
-  dprintf(("GDI32: CreateFontIndirectA\n"));
-  dprintf(("GDI32: lfHeight        = %d\n", lplf->lfHeight));
-  dprintf(("GDI32: lfWidth          = %d\n", lplf->lfWidth));
-  dprintf(("GDI32: lfEscapement    = %d\n", lplf->lfEscapement));
-  dprintf(("GDI32: lfOrientation   = %d\n", lplf->lfOrientation));
-  dprintf(("GDI32: lfWeight        = %d\n", lplf->lfWeight));
-  dprintf(("GDI32: lfItalic        = %d\n", lplf->lfItalic));
-  dprintf(("GDI32: lfUnderline     = %d\n", lplf->lfUnderline));
-  dprintf(("GDI32: lfStrikeOut     = %d\n", lplf->lfStrikeOut));
-  dprintf(("GDI32: lfCharSet       = %X\n", lplf->lfCharSet));
-  dprintf(("GDI32: lfOutPrecision  = %X\n", lplf->lfOutPrecision));
-  dprintf(("GDI32: lfClipPrecision = %X\n", lplf->lfClipPrecision));
-  dprintf(("GDI32: lfQuality       = %X\n", lplf->lfQuality));
-  dprintf(("GDI32: lfPitchAndFamily= %X\n", lplf->lfPitchAndFamily));
-  dprintf(("GDI32: lfFaceName      = %s\n", lplf->lfFaceName));
-
   if( IsDBCSEnv())
   {
@@ -362,7 +321,11 @@
   }
 
+  dprintf(("GDI32: CreateFontIndirectA\n"));
+  dprintfLogFont((LOGFONTA *)lplf);
+
   hFont = O32_CreateFontIndirect(&afont);
   if(hFont) {
       STATS_CreateFontIndirect(hFont, &afont);
+      RegisterFont(hFont, (LPSTR)lplf->lfFaceName);
   }
   return(hFont);
@@ -387,9 +350,16 @@
 //******************************************************************************
 int  EXPENTRY_O32 EnumFontProcA(LPENUMLOGFONTA lpLogFont, LPNEWTEXTMETRICA
-                                   lpTextM, DWORD arg3, LPARAM arg4)
-{
- ENUMUSERDATA *lpEnumData = (ENUMUSERDATA *)arg4;
- FONTENUMPROCA proc = (FONTENUMPROCA)lpEnumData->userProc;
- USHORT selTIB = SetWin32TIB(); // save current FS selector and set win32 sel
+                                lpTextM, DWORD arg3, LPARAM arg4)
+{
+  ENUMUSERDATA *lpEnumData = (ENUMUSERDATA *)arg4;
+  FONTENUMPROCA proc = (FONTENUMPROCA)lpEnumData->userProc;
+  USHORT selTIB = SetWin32TIB(); // save current FS selector and set win32 sel
+
+  if(FT2Module.Ft2QueryFontType(0, lpLogFont->elfLogFont.lfFaceName) == FT2_FONTTYPE_TRUETYPE) {
+      lpTextM->tmPitchAndFamily |= TMPF_TRUETYPE;
+  }
+
+  dprintfLogFont(&lpLogFont->elfLogFont);
+  dprintfTextMetrics((TEXTMETRICA *)lpTextM);
 
   int rc = proc(lpLogFont, lpTextM, arg3, lpEnumData->userData);
@@ -408,4 +378,11 @@
  USHORT selTIB = SetWin32TIB(); // save current FS selector and set win32 sel
  int rc;
+
+  if(FT2Module.Ft2QueryFontType(0, lpLogFont->elfLogFont.lfFaceName) == FT2_FONTTYPE_TRUETYPE) {
+      lpTextM->tmPitchAndFamily |= TMPF_TRUETYPE;
+  }
+
+  dprintfLogFont(&lpLogFont->elfLogFont);
+  dprintfTextMetrics((TEXTMETRICA *)lpTextM);
 
   memcpy(&LogFont, lpLogFont, ((ULONG)&LogFont.elfLogFont.lfFaceName -
@@ -448,5 +425,5 @@
 //******************************************************************************
 int  EXPENTRY_O32 EnumFontProcExA(LPENUMLOGFONTA lpLogFont, LPNEWTEXTMETRICA
-                                     lpTextM, DWORD arg3, LPARAM arg4)
+                                     lpTextM, DWORD FontType, LPARAM arg4)
 {
  ENUMUSERDATA *lpEnumData = (ENUMUSERDATA *)arg4;
@@ -456,4 +433,11 @@
  USHORT selTIB = SetWin32TIB(); // save current FS selector and set win32 sel
 
+  if(FT2Module.Ft2QueryFontType(0, lpLogFont->elfLogFont.lfFaceName) == FT2_FONTTYPE_TRUETYPE) {
+      lpTextM->tmPitchAndFamily |= TMPF_TRUETYPE;
+  }
+
+  dprintfLogFont(&lpLogFont->elfLogFont);
+  dprintfTextMetrics((TEXTMETRICA *)lpTextM);
+
   memcpy(&logFont, lpLogFont, sizeof(ENUMLOGFONTA));
   memset(logFont.elfScript, 0, sizeof(logFont.elfScript));
@@ -461,7 +445,7 @@
   memset(&textM.ntmFontSig, 0, sizeof(textM.ntmFontSig));
 
-  dprintf(("EnumFontProcExA %s height %d", logFont.elfLogFont.lfFaceName, textM.ntmTm.tmHeight));
-
-  int rc = proc(&logFont, &textM, arg3, lpEnumData->userData);
+  dprintf(("EnumFontProcExA %s type %x height %d", logFont.elfLogFont.lfFaceName, FontType, textM.ntmTm.tmHeight));
+
+  int rc = proc(&logFont, &textM, FontType, lpEnumData->userData);
   SetFS(selTIB);           // switch back to the saved FS selector
   return rc;
@@ -471,5 +455,5 @@
 //******************************************************************************
 int EXPENTRY_O32 EnumFontProcExW(LPENUMLOGFONTA lpLogFont, LPNEWTEXTMETRICA lpTextM,
-                                    DWORD arg3, LPARAM arg4)
+                                    DWORD FontType, LPARAM arg4)
 {
  ENUMUSERDATA *lpEnumData = (ENUMUSERDATA *)arg4;
@@ -479,4 +463,11 @@
  USHORT selTIB = SetWin32TIB(); // save current FS selector and set win32 sel
  int rc;
+
+  if(FT2Module.Ft2QueryFontType(0, lpLogFont->elfLogFont.lfFaceName) == FT2_FONTTYPE_TRUETYPE) {
+      lpTextM->tmPitchAndFamily |= TMPF_TRUETYPE;
+  }
+
+  dprintfLogFont(&lpLogFont->elfLogFont);
+  dprintfTextMetrics((TEXTMETRICA *)lpTextM);
 
   memcpy(&LogFont, lpLogFont, ((ULONG)&LogFont.elfLogFont.lfFaceName - (ULONG)&LogFont));
@@ -512,6 +503,6 @@
   memset(&textM.ntmFontSig, 0, sizeof(textM.ntmFontSig));
 
-  dprintf(("EnumFontProcExW %s height %d", lpLogFont->elfLogFont.lfFaceName, textM.ntmTm.tmHeight));
-  rc = proc(&LogFont, &textM, arg3, lpEnumData->userData);
+  dprintf(("EnumFontProcExW %s type %x height %d charset %d/%d", lpLogFont->elfLogFont.lfFaceName, FontType, textM.ntmTm.tmHeight, lpTextM->tmCharSet, lpLogFont->elfLogFont.lfCharSet));
+  rc = proc(&LogFont, &textM, FontType, lpEnumData->userData);
   SetFS(selTIB);           // switch back to the saved FS selector
   return rc;
@@ -586,5 +577,5 @@
 //******************************************************************************
 INT WIN32API EnumFontFamiliesExA(HDC hdc,
-                                 LPLOGFONTA arg2,
+                                 LPLOGFONTA lpLogFont,
                                  FONTENUMPROCEXA arg3,
                                  LPARAM arg4,
@@ -594,5 +585,6 @@
   int rc;
 
-  dprintf(("GDI32: EnumFontFamiliesExA not complete %s", arg2->lfFaceName));
+  dprintf(("GDI32: EnumFontFamiliesExA not complete %s", lpLogFont->lfFaceName));
+  dprintf(("GDI32: EnumFontFamiliesExA font name %s character set %x", lpLogFont->lfFaceName, lpLogFont->lfCharSet));
 
   enumData.userProc = (DWORD)arg3;
@@ -600,5 +592,5 @@
   enumData.dwFlags  = dwFlags;
 
-  rc = O32_EnumFontFamilies(hdc, arg2->lfFaceName, &EnumFontProcExA, (LPARAM)&enumData);
+  rc = O32_EnumFontFamilies(hdc, lpLogFont->lfFaceName, &EnumFontProcExA, (LPARAM)&enumData);
 
   return rc;
@@ -607,5 +599,5 @@
 //******************************************************************************
 INT WIN32API EnumFontFamiliesExW(HDC hdc,
-                                 LPLOGFONTW arg2,
+                                 LPLOGFONTW lpLogFont,
                                  FONTENUMPROCEXW arg3,
                                  LPARAM arg4,
@@ -614,7 +606,8 @@
   ENUMUSERDATA enumData;
   int rc;
-  char *astring = UnicodeToAsciiString((LPWSTR)arg2->lfFaceName);
+  char *astring = UnicodeToAsciiString((LPWSTR)lpLogFont->lfFaceName);
 
   dprintf(("GDI32: EnumFontFamiliesExW not complete %s", astring));
+  dprintf(("GDI32: EnumFontFamiliesExW font name %s character set %x", astring, lpLogFont->lfCharSet));
 
   enumData.userProc = (DWORD)arg3;
@@ -627,122 +620,4 @@
   return rc;
 }
-//******************************************************************************
-//******************************************************************************
-DWORD WIN32API GetFontData(HDC hdc, DWORD dwTable,
-                           DWORD dwOffset,
-                           LPVOID lpvBuffer,
-                           DWORD dbData)
-{
-  dprintf(("GDI32: GetFontData, not implemented (GDI_ERROR)\n"));
-  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
-
-  return(GDI_ERROR);
-}
-//******************************************************************************
-//******************************************************************************
-int WIN32API AddFontResourceA(LPCSTR szFont)
-{
-    HINSTANCE hInstance;
-
-    dprintf(("GDI32: AddFontResourceA %s", szFont));
-    hInstance = LoadLibraryA(szFont);
-    if(hInstance) {
-        dprintf(("AddFontResourceA: executable file; NOT IMPLEMENTED"));
-        FreeLibrary(hInstance);
-        return 1;
-    }
-    return 1;
-}
-//******************************************************************************
-//******************************************************************************
-int WIN32API AddFontResourceW(LPCWSTR szFont)
-{
- char *astring = UnicodeToAsciiString((LPWSTR)szFont);
- BOOL  rc;
-
-    dprintf(("GDI32: AddFontResourceW"));
-    // NOTE: This will not work as is (needs UNICODE support)
-    rc = AddFontResourceA(astring);
-    FreeAsciiString(astring);
-    return rc;
-}
-//******************************************************************************
-//******************************************************************************
-BOOL WIN32API RemoveFontResourceA(LPCSTR lpszFont)
-{
-    dprintf(("GDI32: RemoveFontResourceA %s", lpszFont));
-    return FALSE;
-}
-//******************************************************************************
-//******************************************************************************
-BOOL WIN32API RemoveFontResourceW(LPCWSTR szFont)
-{
- char *astring = UnicodeToAsciiString((LPWSTR)szFont);
- BOOL  rc;
-
-    dprintf(("GDI32: RemoveFontResourceW"));
-    rc = RemoveFontResourceA(astring);
-    FreeAsciiString(astring);
-    return(rc);
-}
-/*****************************************************************************
- * Name      : BOOL CreateScalableFontResourceA
- * Purpose   : The CreateScalableFontResourceA function creates a font resource
- *             file for a scalable font.
- * Parameters: DWORD   fdwHidden       flag for read-only embedded font
- *             LPCSTR lpszFontRes     address of filename for font resource
- *             LPCSTR lpszFontFile    address of filename for scalable font
- *             LPCSTR lpszCurrentPath address of path to font file
- * Variables :
- * Result    : TRUE / FALSE
- * Remark    :
- * Status    : UNTESTED STUB
- *
- * Author    : Patrick Haller [Mon, 1998/06/15 08:00]
- *****************************************************************************/
-
-BOOL WIN32API CreateScalableFontResourceA(DWORD fdwHidden,
-                                          LPCSTR lpszFontRes,
-                                          LPCSTR lpszFontFile,
-                                          LPCSTR lpszCurrentPath)
-{
-  dprintf(("GDI32: CreateScalableFontResourceA %x %s %s %s not implemented", fdwHidden, lpszFontRes, lpszFontFile, lpszCurrentPath));
-
-//  return OSLibGpiLoadFonts((LPSTR)lpszFontFile);
-  return FALSE;
-}
-
-
-/*****************************************************************************
- * Name      : BOOL CreateScalableFontResourceW
- * Purpose   : The CreateScalableFontResourceW function creates a font resource
- *             file for a scalable font.
- * Parameters: DWORD   fdwHidden       flag for read-only embedded font
- *             LPCSTR lpszFontRes     address of filename for font resource
- *             LPCSTR lpszFontFile    address of filename for scalable font
- *             LPCSTR lpszCurrentPath address of path to font file
- * Variables :
- * Result    : TRUE / FALSE
- * Remark    :
- * Status    : UNTESTED STUB
- *
- * Author    : Patrick Haller [Mon, 1998/06/15 08:00]
- *****************************************************************************/
-
-BOOL WIN32API CreateScalableFontResourceW(DWORD fdwHidden,
-                                          LPCWSTR lpszFontRes,
-                                          LPCWSTR lpszFontFile,
-                                          LPCWSTR lpszCurrentPath)
-{
-  LPSTR lpszFontFileA = NULL, lpszFontResA = NULL, lpszCurrentPathA = NULL;
-
-  dprintf(("GDI32: CreateScalableFontResourceW %x %ls %ls %ls not implemented", fdwHidden, lpszFontRes, lpszFontFile, lpszCurrentPath));
-
-  STACK_strdupWtoA(lpszFontFile, lpszFontFileA);
-  STACK_strdupWtoA(lpszFontRes, lpszFontResA);
-  STACK_strdupWtoA(lpszCurrentPath, lpszCurrentPathA);
-  return CreateScalableFontResourceA(fdwHidden, lpszFontResA, lpszFontFileA, lpszCurrentPathA);
-}
-
 
 /*****************************************************************************
@@ -819,5 +694,11 @@
 
     rc = O32_GetTextMetrics(hdc, pwtm);
-    dprintf(("GDI32: GetTextMetricsA %x %x returned %d", hdc, pwtm, rc));
+
+    if(rc == TRUE) {
+       if(FT2Module.Ft2QueryFontType(hdc, NULL) == FT2_FONTTYPE_TRUETYPE) {
+           pwtm->tmPitchAndFamily |= TMPF_TRUETYPE;
+       }
+    }
+    dprintfTextMetrics(pwtm);
     return(rc);
 }
@@ -826,10 +707,8 @@
 BOOL WIN32API GetTextMetricsW( HDC hdc, LPTEXTMETRICW pwtm)
 {
- BOOL rc;
- TEXTMETRICA atm;
-
-    dprintf(("GDI32: GetTextMetricsW"));
-
-    rc = O32_GetTextMetrics(hdc, &atm);
+    BOOL rc;
+    TEXTMETRICA atm;
+
+    rc = GetTextMetricsA(hdc, &atm);
     pwtm->tmHeight = atm.tmHeight;
     pwtm->tmAscent = atm.tmAscent;
@@ -853,25 +732,32 @@
     pwtm->tmCharSet = atm.tmCharSet;
 
-    dprintf(("GDI32: GetTextMetricsW %x %x returned %d", hdc, pwtm, rc));
     return(rc);
 }
 //******************************************************************************
 //******************************************************************************
-int WIN32API GetTextFaceA( HDC hdc, int arg2, LPSTR  arg3)
-{
-    dprintf(("GDI32: GetTextFaceA %x %d %x", hdc, arg2, arg3));
-    return O32_GetTextFace(hdc, arg2, arg3);
-}
-//******************************************************************************
-//******************************************************************************
-int WIN32API GetTextFaceW( HDC hdc, int arg2, LPWSTR  arg3)
-{
- char *astring = NULL;
- int   lenA = GetTextFaceA( hdc, 0, NULL );
- int   rc;
-
-    dprintf(("GDI32: GetTextFaceW"));
+int WIN32API GetTextFaceA( HDC hdc, int nCount, LPSTR lpFaceName)
+{
+    int ret;
+
+    dprintf(("GDI32: GetTextFaceA %x %d %x", hdc, nCount, lpFaceName));
+    ret = O32_GetTextFace(hdc, nCount, lpFaceName);
+    if(ret > 0 && lpFaceName) {
+        dprintf(("GDI32: GetTextFaceA returned %s", lpFaceName));
+    }
+    //We should return the length including null terminator (WGSS doesn't)
+    if(!lpFaceName) ret++;
+
+    return ret;
+}
+//******************************************************************************
+//******************************************************************************
+int WIN32API GetTextFaceW( HDC hdc, int nCount, LPWSTR  lpFaceName)
+{
+    char *astring = NULL;
+    int   lenA = GetTextFaceA( hdc, 0, NULL );
+    int   rc;
+
     astring = ( char * )malloc( lenA );
-    if( astring )
+    if( astring == NULL ) //@@VP:2003-11-05 was 'if ( astring )'
         return 0;
 
@@ -880,8 +766,8 @@
     if( rc )
     {
-        if( arg3 )
+        if( lpFaceName )
         {
-            AsciiToUnicodeN(astring, arg3, arg2);
-            rc = lstrlenW( arg3 );
+            AsciiToUnicodeN(astring, lpFaceName, nCount);
+            rc = lstrlenW( lpFaceName );
         }
         else
@@ -911,4 +797,263 @@
     return 0;
 }
-//******************************************************************************
-//******************************************************************************
+/*****************************************************************************
+ * Name      : DWORD GetCharacterPlacementA
+ * Purpose   : The GetCharacterPlacementA function retrieves information about
+ *             a character string, such as character widths, caret positioning,
+ *             ordering within the string, and glyph rendering. The type of
+ *             information returned depends on the dwFlags parameter and is
+ *             based on the currently selected font in the given display context.
+ *             The function copies the information to the specified GCP_RESULTSA
+ *             structure or to one or more arrays specified by the structure.
+ * Parameters: HDC     hdc        handle to device context
+ *             LPCSTR lpString   pointer to string
+ *             int     nCount     number of characters in string
+ *             int     nMaxExtent maximum extent for displayed string
+ *             LPGCP_RESULTSA *lpResults  pointer to buffer for placement result
+ *             DWORD   dwFlags    placement flags
+ * Variables :
+ * Result    :
+ * Remark    :
+ * Status    : UNTESTED STUB
+ *
+ * Author    : Patrick Haller [Mon, 1998/06/15 08:00]
+ *****************************************************************************/
+
+DWORD WIN32API GetCharacterPlacementA(HDC           hdc,
+                                         LPCSTR       lpString,
+                                         int           nCount,
+                                         int           nMaxExtent,
+                                         GCP_RESULTSA * lpResults,
+                                         DWORD         dwFlags)
+{
+  dprintf(("GDI32: GetCharacterPlacementA(%08xh,%s,%08xh,%08xh,%08xh,%08xh) not implemented.\n",
+           hdc,
+           lpString,
+           nCount,
+           nMaxExtent,
+           lpResults,
+           dwFlags));
+
+  return (0);
+}
+
+/*****************************************************************************
+ * Name      : DWORD GetCharacterPlacementW
+ * Purpose   : The GetCharacterPlacementW function retrieves information about
+ *             a character string, such as character widths, caret positioning,
+ *             ordering within the string, and glyph rendering. The type of
+ *             information returned depends on the dwFlags parameter and is
+ *             based on the currently selected font in the given display context.
+ *             The function copies the information to the specified GCP_RESULTSW
+ *             structure or to one or more arrays specified by the structure.
+ * Parameters: HDC     hdc        handle to device context
+ *             LPCSTR lpString   pointer to string
+ *             int     nCount     number of characters in string
+ *             int     nMaxExtent maximum extent for displayed string
+ *             GCP_RESULTSW *lpResults  pointer to buffer for placement result
+ *             DWORD   dwFlags    placement flags
+ * Variables :
+ * Result    :
+ * Remark    :
+ * Status    : Partly working
+ *
+ * Author    : Borrowed Rewind Code
+ *****************************************************************************/
+
+DWORD WIN32API GetCharacterPlacementW(HDC           hdc,
+                                         LPCWSTR       lpString,
+                                         int           uCount,
+                                         int           nMaxExtent,
+                                         GCP_RESULTSW *lpResults,
+                                         DWORD         dwFlags)
+{
+    return FT2Module.Ft2GetCharacterPlacementW(hdc, lpString, uCount, nMaxExtent, lpResults, dwFlags);
+}
+
+
+/***********************************************************************
+ *           FONT_mbtowc
+ *
+ * Returns a '\0' terminated Unicode translation of str using the
+ * charset of the currently selected font in hdc.  If count is -1 then
+ * str is assumed to be '\0' terminated, otherwise it contains the
+ * number of bytes to convert.  If plenW is non-NULL, on return it
+ * will point to the number of WCHARs (excluding the '\0') that have
+ * been written.  If pCP is non-NULL, on return it will point to the
+ * codepage used in the conversion (NB, this may be CP_SYMBOL so watch
+ * out).  The caller should free the returned LPWSTR from the process
+ * heap itself.
+ */
+LPWSTR FONT_mbtowc(HDC hdc, LPCSTR str, INT count, INT *plenW, UINT *pCP)
+{
+    UINT cp = CP_ACP;
+    INT lenW, i;
+    LPWSTR strW;
+    CHARSETINFO csi;
+    int charset = GetTextCharset(hdc);
+
+    if( IsDBCSEnv() && ( charset == 0 ))
+        cp = CP_ACP;
+    else
+    /* Hmm, nicely designed api this one! */
+    if(TranslateCharsetInfo((DWORD*)charset, &csi, TCI_SRCCHARSET))
+        cp = csi.ciACP;
+    else {
+        switch(charset) {
+	case OEM_CHARSET:
+	    cp = GetOEMCP();
+	    break;
+	case DEFAULT_CHARSET:
+	    cp = GetACP();
+	    break;
+
+	case VISCII_CHARSET:
+	case TCVN_CHARSET:
+	case KOI8_CHARSET:
+	case ISO3_CHARSET:
+	case ISO4_CHARSET:
+	  /* FIXME: These have no place here, but because x11drv
+	     enumerates fonts with these (made up) charsets some apps
+	     might use them and then the FIXME below would become
+	     annoying.  Now we could pick the intended codepage for
+	     each of these, but since it's broken anyway we'll just
+	     use CP_ACP and hope it'll go away...
+	  */
+	    cp = CP_ACP;
+	    break;
+
+
+	default:
+	    dprintf(("Can't find codepage for charset %d\n", charset));
+	    break;
+	}
+    }
+
+    dprintf(("cp == %d\n", cp));
+
+    if(count == -1) count = strlen(str);
+    if(cp != CP_SYMBOL) {
+        lenW = MultiByteToWideChar(cp, 0, str, count, NULL, 0);
+	strW = (WCHAR*)HeapAlloc(GetProcessHeap(), 0, (lenW + 1) * sizeof(WCHAR));
+	MultiByteToWideChar(cp, 0, str, count, strW, lenW);
+    } else {
+        lenW = count;
+	strW = (WCHAR*)HeapAlloc(GetProcessHeap(), 0, (lenW + 1) * sizeof(WCHAR));
+	for(i = 0; i < count; i++) strW[i] = (BYTE)str[i];
+    }
+    strW[lenW] = '\0';
+    dprintf(("mapped %s -> %ls\n", str, strW));
+    if(plenW) *plenW = lenW;
+    if(pCP) *pCP = cp;
+    return strW;
+}
+
+/*************************************************************************
+ * GetGlyphIndicesA [GDI32.@]
+ */
+DWORD WINAPI GetGlyphIndicesA(HDC hdc, LPCSTR lpstr, INT count,
+			      LPWORD pgi, DWORD flags)
+{
+    DWORD ret;
+    WCHAR *lpstrW;
+    INT countW;
+
+    dprintf(("GDI32: GetGlyphIndicesA (%p, %s, %d, %p, 0x%lx)\n",
+          hdc, lpstr, count, pgi, flags));
+
+    lpstrW = FONT_mbtowc(hdc, lpstr, count, &countW, NULL);
+    ret = GetGlyphIndicesW(hdc, lpstrW, countW, pgi, flags);
+    HeapFree(GetProcessHeap(), 0, lpstrW);
+
+    return ret;
+}
+
+/*************************************************************************
+ * GetGlyphIndicesW [GDI32.@]
+ */
+DWORD WINAPI GetGlyphIndicesW(HDC hdc, LPCWSTR lpstr, INT count,
+			      LPWORD pgi, DWORD flags)
+{
+    DWORD ret;
+
+    dprintf(("GDI32: GetGlyphIndicesW (%ls, %d, %p, 0x%lx)",
+             lpstr, count, pgi, flags));
+
+    if(!hdc) return GDI_ERROR;
+
+    ret = FT2Module.Ft2GetGlyphIndices(hdc, lpstr, count , pgi, flags); 
+    if(ret != GDI_ERROR) {
+        for(int i=0;i<ret;i++) {
+            dprintf(("GetGlyphIndices: %c (%x)-> %d", lpstr[i], lpstr[i], pgi[i]));
+        }
+    }
+    return ret;
+}
+
+/***********************************************************************
+ *           GetGlyphOutlineA    (GDI32.@)
+ */
+DWORD WINAPI GetGlyphOutlineA( HDC hdc, UINT uChar, UINT fuFormat,
+                                 LPGLYPHMETRICS lpgm, DWORD cbBuffer,
+                                 LPVOID lpBuffer, const MAT2 *lpmat2 )
+{
+    LPWSTR p = NULL;
+    DWORD ret;
+    UINT c;
+
+    if ((fuFormat & GGO_GLYPH_INDEX) == 0)
+    {
+        p = FONT_mbtowc(hdc, (char*)&uChar, 1, NULL, NULL);
+        if (p)
+        {
+	    c = p[0];
+	}
+	else
+	{
+            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
+	    return GDI_ERROR;
+	}
+    }
+    else
+    {
+        c = uChar;
+    }
+    
+    ret = GetGlyphOutlineW (hdc, c, fuFormat, lpgm, cbBuffer, lpBuffer, lpmat2);
+    
+    if (p != NULL)
+    {
+        HeapFree (GetProcessHeap(), 0, p);
+    }
+    
+    return ret;
+}
+
+/***********************************************************************
+ *           GetGlyphOutlineW    (GDI32.@)
+ */
+DWORD WINAPI GetGlyphOutlineW( HDC hdc, UINT uChar, UINT fuFormat,
+                               LPGLYPHMETRICS lpgm, DWORD cbBuffer,
+                               LPVOID lpBuffer, const MAT2 *lpmat2 )
+{
+    pDCData pHps = (pDCData)OSLibGpiQueryDCData(hdc);
+
+    dprintf(("GDI32: GetGlyphOutlineW(%p, %04x, %04x, %p, %ld, %p, %p)\n",
+              pHps, uChar, fuFormat, lpgm, cbBuffer, lpBuffer, lpmat2 ));
+
+    if (!hdc || !pHps)
+    {
+        SetLastError(ERROR_INVALID_PARAMETER);
+        return GDI_ERROR;
+    }
+
+    return FT2Module.Ft2GetGlyphOutline(pHps->hps, uChar, fuFormat, lpgm, cbBuffer, lpBuffer, lpmat2);
+}
+//******************************************************************************
+//******************************************************************************
+DWORD WIN32API GetKerningPairsA( HDC hdc, DWORD nNumPairs, LPKERNINGPAIR lpkrnpair)
+{
+    return O32_GetKerningPairs(hdc, nNumPairs, lpkrnpair);
+}
+//******************************************************************************
+//******************************************************************************
Index: trunk/src/gdi32/font.h
===================================================================
--- trunk/src/gdi32/font.h	(revision 10372)
+++ trunk/src/gdi32/font.h	(revision 10373)
@@ -7,5 +7,10 @@
 BOOL WIN32API IsSystemFont(HFONT hFont);
 
+BOOL RegisterFont(HFONT hFont, LPSTR lfFaceName);
+
 LPWSTR FONT_mbtowc(HDC hdc, LPCSTR str, INT count, INT *plenW, UINT *pCP);
 
+//text.cpp
+BOOL WIN32API GetStringWidthW(HDC hdc, LPWSTR lpszString, UINT cbString, PINT pWidthArray);
+
 #endif //__FONT_H__
Index: trunk/src/gdi32/fontres.cpp
===================================================================
--- trunk/src/gdi32/fontres.cpp	(revision 10373)
+++ trunk/src/gdi32/fontres.cpp	(revision 10373)
@@ -0,0 +1,203 @@
+/* $Id: fontres.cpp,v 1.1 2004-01-11 11:42:13 sandervl Exp $ */
+
+
+/*
+ * GDI32 font apis
+ *
+ * Copyright 2003 Sander van Leeuwen (sandervl@innotek.de)
+ *
+ * Project Odin Software License can be found in LICENSE.TXT
+ *
+ */
+
+/*****************************************************************************
+ * Includes                                                                  *
+ *****************************************************************************/
+
+#include <odin.h>
+#include <odinwrap.h>
+#include <os2sel.h>
+
+#include <os2win.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <string.h>
+#include <dbglog.h>
+#include <unicode.h>
+#include <stats.h>
+#include <objhandle.h>
+#include "oslibgpi.h"
+
+#define DBG_LOCALLOG    DBG_fontres
+#include "dbglocal.h"
+
+#define TESTFONT_RESNAME    	"TESTFONT"
+
+//just picking a reasonable maximum; don't want to mess with linked lists
+#define MAX_PUBLICFONTS		32
+
+typedef struct {
+  char  szFaceName[32];
+  char  szFontResName[260];
+  char  szFileName[260];
+  char *pFontData;
+  DWORD dwFontSize;
+} SCALABLEFONTS;
+
+
+static SCALABLEFONTS    *publicfonts = NULL;
+static CRITICAL_SECTION  fntcritsect = {0};
+
+#define FntLock()	EnterCriticalSection(&fntcritsect)
+#define FntUnlock()     LeaveCriticalSection(&fntcritsect)
+
+
+//******************************************************************************
+// Remember the font filename for GetFontData if this is a font previously
+// registered with AddFontResource
+//******************************************************************************
+BOOL RegisterFont(HFONT hFont, LPSTR lfFaceName)
+{
+    if(!publicfonts) {
+        return FALSE;
+    }
+
+    FntLock();
+    for(int i=0;i<MAX_PUBLICFONTS;i++) {
+        if(strcmp(publicfonts[i].szFaceName, lfFaceName) == 0) {
+#ifdef DEBUG
+            dprintf(("Remember font file %s for font %x", publicfonts[i].szFileName, hFont));
+            if(GetFileAttributesA(publicfonts[i].szFileName) == -1) {
+                dprintf(("ERROR: font file does not exist anymore!!!!!!"));
+            }
+#endif
+            ObjSetHandleGDI32Data(hFont, HNDL_FONT, (DWORD)&publicfonts[i]);
+            break;
+        }
+    }
+    FntUnlock();
+    if(i == MAX_PUBLICFONTS) {
+        return FALSE;
+    }
+    return TRUE;
+}
+//******************************************************************************
+//******************************************************************************
+DWORD WIN32API GetFontData(HDC hdc, DWORD dwTable,
+                           DWORD dwOffset,
+                           LPVOID lpvBuffer,
+                           DWORD dbData)
+{
+  dprintf(("GDI32: GetFontData, not implemented (GDI_ERROR)\n"));
+  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
+
+  return(GDI_ERROR);
+}
+//******************************************************************************
+//******************************************************************************
+int WIN32API AddFontResourceA(LPCSTR szFont)
+{
+    HINSTANCE hInstance;
+
+    dprintf(("GDI32: AddFontResourceA %s", szFont));
+    hInstance = LoadLibraryA(szFont);
+    if(hInstance) {
+        dprintf(("AddFontResourceA: executable file; NOT IMPLEMENTED"));
+        FreeLibrary(hInstance);
+        return 1;
+    }
+    return 1;
+}
+//******************************************************************************
+//******************************************************************************
+int WIN32API AddFontResourceW(LPCWSTR szFont)
+{
+ char *astring = UnicodeToAsciiString((LPWSTR)szFont);
+ BOOL  rc;
+
+    dprintf(("GDI32: AddFontResourceW"));
+    // NOTE: This will not work as is (needs UNICODE support)
+    rc = AddFontResourceA(astring);
+    FreeAsciiString(astring);
+    return rc;
+}
+//******************************************************************************
+//******************************************************************************
+BOOL WIN32API RemoveFontResourceA(LPCSTR lpszFont)
+{
+    dprintf(("GDI32: RemoveFontResourceA %s", lpszFont));
+    return FALSE;
+}
+//******************************************************************************
+//******************************************************************************
+BOOL WIN32API RemoveFontResourceW(LPCWSTR szFont)
+{
+ char *astring = UnicodeToAsciiString((LPWSTR)szFont);
+ BOOL  rc;
+
+    dprintf(("GDI32: RemoveFontResourceW"));
+    rc = RemoveFontResourceA(astring);
+    FreeAsciiString(astring);
+    return(rc);
+}
+/*****************************************************************************
+ * Name      : BOOL CreateScalableFontResourceA
+ * Purpose   : The CreateScalableFontResourceA function creates a font resource
+ *             file for a scalable font.
+ * Parameters: DWORD   fdwHidden       flag for read-only embedded font
+ *             LPCSTR lpszFontRes     address of filename for font resource
+ *             LPCSTR lpszFontFile    address of filename for scalable font
+ *             LPCSTR lpszCurrentPath address of path to font file
+ * Variables :
+ * Result    : TRUE / FALSE
+ * Remark    :
+ * Status    : UNTESTED STUB
+ *
+ * Author    : Patrick Haller [Mon, 1998/06/15 08:00]
+ *****************************************************************************/
+
+BOOL WIN32API CreateScalableFontResourceA(DWORD fdwHidden,
+                                          LPCSTR lpszFontRes,
+                                          LPCSTR lpszFontFile,
+                                          LPCSTR lpszCurrentPath)
+{
+  dprintf(("GDI32: CreateScalableFontResourceA %x %s %s %s not implemented", fdwHidden, lpszFontRes, lpszFontFile, lpszCurrentPath));
+
+//  return OSLibGpiLoadFonts((LPSTR)lpszFontFile);
+  return FALSE;
+}
+
+
+/*****************************************************************************
+ * Name      : BOOL CreateScalableFontResourceW
+ * Purpose   : The CreateScalableFontResourceW function creates a font resource
+ *             file for a scalable font.
+ * Parameters: DWORD   fdwHidden       flag for read-only embedded font
+ *             LPCSTR lpszFontRes     address of filename for font resource
+ *             LPCSTR lpszFontFile    address of filename for scalable font
+ *             LPCSTR lpszCurrentPath address of path to font file
+ * Variables :
+ * Result    : TRUE / FALSE
+ * Remark    :
+ * Status    : UNTESTED STUB
+ *
+ * Author    : Patrick Haller [Mon, 1998/06/15 08:00]
+ *****************************************************************************/
+
+BOOL WIN32API CreateScalableFontResourceW(DWORD fdwHidden,
+                                          LPCWSTR lpszFontRes,
+                                          LPCWSTR lpszFontFile,
+                                          LPCWSTR lpszCurrentPath)
+{
+  LPSTR lpszFontFileA = NULL, lpszFontResA = NULL, lpszCurrentPathA = NULL;
+
+  dprintf(("GDI32: CreateScalableFontResourceW %x %ls %ls %ls not implemented", fdwHidden, lpszFontRes, lpszFontFile, lpszCurrentPath));
+
+  STACK_strdupWtoA(lpszFontFile, lpszFontFileA);
+  STACK_strdupWtoA(lpszFontRes, lpszFontResA);
+  STACK_strdupWtoA(lpszCurrentPath, lpszCurrentPathA);
+  return CreateScalableFontResourceA(fdwHidden, lpszFontResA, lpszFontFileA, lpszCurrentPathA);
+}
+
+
Index: trunk/src/gdi32/ft2supp.cpp
===================================================================
--- trunk/src/gdi32/ft2supp.cpp	(revision 10373)
+++ trunk/src/gdi32/ft2supp.cpp	(revision 10373)
@@ -0,0 +1,472 @@
+/*
+ * GDI32 FreeType2 Support Class
+ *
+ * Copyright 2003 Innotek Systemberatung GmbH (sandervl@innotek.de)
+ *                                            (stauff@innotek.de)
+ *
+ * Project Odin Software License can be found in LICENSE.TXT
+ *
+ */
+
+/*****************************************************************************
+ * Includes                                                                  *
+ *****************************************************************************/
+
+#define  INCL_DOS
+#define  INCL_GPI
+#define  INCL_WIN
+#define  INCL_SHLERRORS
+#define  INCL_WINERRORS
+#include <os2wrap.h>  //Odin32 OS/2 api wrappers
+#include <stdlib.h>
+#include <string.h>
+#include <win32type.h>
+#include <dbglog.h>
+#include <win32api.h>
+#include <winconst.h>
+#include <winnls.h>
+#include <heapstring.h>
+#include <winuser32.h>
+#include <odinlx.h>
+#include "oslibgpi.h"
+
+#include "ft2supp.h"
+
+CFT2Module FT2Module;
+
+static BOOL fFT2LIBIntegration = FALSE;
+
+//******************************************************************************
+//******************************************************************************
+void WIN32API SetFreeTypeIntegration(BOOL fEnabled)
+{
+    fFT2LIBIntegration = fEnabled;   
+
+    FT2Module.init();
+}
+//******************************************************************************
+// Constructor
+//******************************************************************************
+CFT2Module::CFT2Module(char* sModuleName): bEnabled(FALSE), hftModule(0), pfnGetGlyphIndices(NULL), 
+                pfnFt2GetTextExtentW(NULL), pfnFt2EnableFontEngine(NULL),
+                pfnFt2GetGlyphOutline(NULL), pfnFt2CharStringPosAtA(NULL),  
+                pfnFt2CharStringPosAtW(NULL), pfnFt2GetFontData(NULL),
+                pfnFt2RegisterUconv(NULL), pfnFt2QueryStringWidthW(NULL),
+                pfnFt2GetVersion(NULL)
+{
+    pszModuleName = sModuleName; //must be static
+}
+//******************************************************************************
+//******************************************************************************
+void CFT2Module::init()
+{
+    APIRET rc;
+    UCHAR Loaderror[ 256 ];
+    LONG major = 0, minor = 0, buildnr = 0;
+
+    if(!fFT2LIBIntegration) {
+        dprintf(("No FT2LIB integration!!"));
+        goto failure;
+    }
+
+    rc = DosLoadModule((PSZ)Loaderror, sizeof(Loaderror), pszModuleName, &hftModule);
+    if (rc != 0) 
+        dprintf(("Freetype2 library load error: return code = %u\n", rc));
+    else
+       bEnabled = TRUE;   
+
+    if(bEnabled) {
+       pfnFt2GetVersion = (PFN_FT2GETVERSION)QueryProcAddress("Ft2GetVersion");
+       if(!pfnFt2GetVersion) {
+           dprintf(("Ft2GetVersion not found!!"));
+           goto failure;
+       }
+       pfnFt2GetVersion(&major, &minor, &buildnr);
+       if(major != FT2LIB_MAJOR_VERSION) {
+           dprintf(("Incorrect major version %d; expected %d!!", major, FT2LIB_MAJOR_VERSION));
+           goto failure;
+       }
+       if(minor < FT2LIB_MINOR_VERSION) {
+           dprintf(("Incorrect minor version %d; expected >= %d!!", minor, FT2LIB_MINOR_VERSION));
+           goto failure;
+       }
+
+       pfnFt2EnableFontEngine = (PFN_FT2ENABLEFONTENGINE)QueryProcAddress("Ft2EnableFontEngine");
+       if(!pfnFt2EnableFontEngine) dprintf(("Ft2EnableFontEngine not found!!"));
+       else pfnFt2EnableFontEngine(bEnabled);
+
+       pfnGetGlyphIndices = (PFN_FT2GETGLYPHINDICES)QueryProcAddress("Ft2GetGlyphIndices");
+       if(!pfnGetGlyphIndices) dprintf(("Ft2GetGlyphIndices not found!!"));
+
+       pfnFt2GetTextExtentW  = (PFN_FT2GETTEXTEXTENTW)QueryProcAddress("Ft2GetTextExtentW");
+       if(!pfnFt2GetTextExtentW) dprintf(("Ft2GetTextExtentW not found!!"));
+
+       pfnFt2CharStringPosAtA = (PFN_FT2CHARSTRINGPOSATA)QueryProcAddress("Ft2CharStringPosAtA");
+       if(!pfnFt2CharStringPosAtA) dprintf(("Ft2CharStringPosAtA not found!!"));
+       pfnFt2CharStringPosAtW = (PFN_FT2CHARSTRINGPOSATW)QueryProcAddress("Ft2CharStringPosAtW");
+       if(!pfnFt2CharStringPosAtW) dprintf(("Ft2CharStringPosAtW not found!!"));
+
+       pfnFt2GetGlyphOutline = (PFN_FT2GETGLYPHOUTLINE)QueryProcAddress("Ft2GetGlyphOutline");
+       if(!pfnFt2GetGlyphOutline) dprintf(("Ft2GetGlyphOutline not found!!"));
+
+       pfnFt2GetFontData = (PFN_FT2GETFONTDATA)QueryProcAddress("Ft2GetFontData");
+       if(!pfnFt2GetFontData) dprintf(("Ft2GetFontData not found!!"));
+
+       pfnFt2QueryFontType = (PFN_FT2QUERYFONTTYPE)QueryProcAddress("Ft2QueryFontType");
+       if(!pfnFt2QueryFontType) dprintf(("Ft2QueryFontType not found!!"));
+
+       pfnFt2QueryStringWidthW = (PFN_FT2QUERYSTRINGWIDTHW)QueryProcAddress("Ft2QueryStringWidthW");
+       if(!pfnFt2QueryStringWidthW) dprintf(("Ft2QueryStringWidthW not found!!"));
+
+       pfnFt2GetCharacterPlacementW = (PFN_FT2GETCHARACTERPLACEMENTW)QueryProcAddress("Ft2GetCharacterPlacementW");
+       if(!pfnFt2GetCharacterPlacementW) dprintf(("pfnFt2GetCharacterPlacementW not found!!"));
+
+       // Do not register functions for Mozilla plugins
+       if(IsDummyExeLoaded() == FALSE) 
+       {
+           pfnFt2RegisterUconv = (PFN_FT2REGISTERUCONV)QueryProcAddress("Ft2RegisterUconv");
+           if(pfnFt2RegisterUconv) 
+                pfnFt2RegisterUconv(WideCharToMultiByte, MultiByteToWideChar);
+           else dprintf(("Ft2QueryFontType not found!!"));
+       }
+       dprintf(("Freetype2 library enabled state %d",bEnabled));
+    }
+    return;
+
+failure:
+    if(pfnFt2RegisterUconv) 
+        pfnFt2RegisterUconv(NULL, NULL);
+    if(pfnFt2EnableFontEngine)
+        pfnFt2EnableFontEngine(FALSE);
+
+    pfnGetGlyphIndices     = NULL;
+    pfnFt2GetTextExtentW   = NULL;
+    pfnFt2EnableFontEngine = NULL;
+    pfnFt2GetGlyphOutline  = NULL; 
+    pfnFt2CharStringPosAtA = NULL;  
+    pfnFt2CharStringPosAtW = NULL; 
+    pfnFt2GetFontData      = NULL;
+    pfnFt2RegisterUconv    = NULL; 
+    pfnFt2QueryStringWidthW= NULL;
+    pfnFt2GetVersion       = NULL;
+    bEnabled = FALSE;
+    if (hftModule) {
+        DosFreeModule(hftModule);
+        hftModule = 0;
+    }
+    return;
+}
+//******************************************************************************
+// Destructor
+//******************************************************************************
+CFT2Module::~CFT2Module()
+{
+    if (hftModule)
+        DosFreeModule(hftModule);
+
+    bEnabled = FALSE;
+}
+//******************************************************************************
+//******************************************************************************
+PFN CFT2Module::QueryProcAddress(int ordinal)
+{
+    APIRET rc;
+    PFN ModuleAddr;
+
+    rc = DosQueryProcAddr(hftModule, ordinal, NULL, &ModuleAddr); 
+    if (rc != 0) {
+        dprintf(("FreeType2 QueryProcAddr error: return code = %u\n", rc));
+        return 0;
+    }
+    return ModuleAddr;
+}
+//******************************************************************************
+//******************************************************************************
+PFN CFT2Module::QueryProcAddress(char * procname)
+{
+    APIRET rc;
+    PFN ModuleAddr;
+
+    rc = DosQueryProcAddr(hftModule, 0, procname, &ModuleAddr); 
+    if (rc != 0) {
+        dprintf(("FreeType2 QueryProcAddr error: return code = %u\n", rc));
+        return 0;
+    }
+    return ModuleAddr;
+}
+//******************************************************************************
+//******************************************************************************
+DWORD CFT2Module::Ft2GetGlyphIndices(HPS hps, LPCWSTR str, int c, LPWORD pgi, DWORD fl)
+{
+    //no fallback
+    return GDI_ERROR;
+}
+//******************************************************************************
+//******************************************************************************
+DWORD CFT2Module::Ft2GetGlyphOutline(HPS hps, UINT glyph, UINT format, LPGLYPHMETRICS lpgm, DWORD buflen, LPVOID buf, const MAT2* lpmat)
+{
+    //no fallback
+    SetLastError(ERROR_INVALID_FUNCTION_W);
+    return GDI_ERROR;
+}
+//******************************************************************************
+//
+// This is basically the same as Ft2QueryTextBoxW, but it behaves as the Win32
+// API GetTextExtent (which ignores character attributes and underhang/overhang)
+// 
+// The fallback case is not accurate!! (but the same as our old code)
+//
+//******************************************************************************
+BOOL CFT2Module::Ft2GetTextExtentW(HPS hps, LONG lCount1,LPCWSTR pchString,LONG lCount2,PPOINTLOS2 aptlPoints)
+{
+    DWORD  ret; 
+    USHORT sel;
+
+    // All FreeType calls should be wrapped for saving FS 
+    if(pfnFt2GetTextExtentW) 
+    {
+        sel  = RestoreOS2FS();
+        ret  = pfnFt2GetTextExtentW(hps, lCount1, pchString, lCount2, aptlPoints);
+        SetFS(sel);
+        if(ret || (ret == FALSE && ERRORIDERROR(WinGetLastError(0)) != PMERR_FUNCTION_NOT_SUPPORTED))
+        {
+            //No need for scaling for printer DCs here
+            return ret; 
+        } 
+    }
+    //else fall back to GPI
+    int   len;
+    LPSTR astring;
+
+    pDCData pHps = (pDCData)OSLibGpiQueryDCData(hps);
+
+    len = WideCharToMultiByte( CP_ACP, 0, pchString, lCount1, 0, 0, NULL, NULL );
+    astring = (char *)malloc( len + 1 );
+    lstrcpynWtoA(astring, pchString, len + 1 );
+
+    ret = OSLibGpiQueryTextBox(pHps, lCount1, astring, lCount2, aptlPoints);
+    free(astring);
+    return ret;
+}
+//******************************************************************************
+//******************************************************************************
+BOOL CFT2Module::Ft2CharStringPosAtA(HPS hps,PPOINTLOS2 ptl,PRECTLOS2 rct,ULONG flOptions,LONG lCount,LPCSTR pchString,CONST INT *alAdx, DWORD fuWin32Options)
+{
+    DWORD  ret; 
+    USHORT sel;
+
+    // All FreeType calls should be wrapped for saving FS 
+    if(pfnFt2CharStringPosAtA) {
+        sel  = RestoreOS2FS();
+        ret  = pfnFt2CharStringPosAtA(hps, ptl,rct,flOptions,lCount,pchString,alAdx, fuWin32Options);
+        SetFS(sel);
+        if(ret || (ret == FALSE && ERRORIDERROR(WinGetLastError(0)) != PMERR_FUNCTION_NOT_SUPPORTED))
+            return ret; 
+    }
+    //else fall back to GPI
+    //NOTE: We don't support fuWin32Options in the fallback case
+    pDCData pHps = (pDCData)OSLibGpiQueryDCData(hps);
+    return OSLibGpiCharStringPosAt(pHps,ptl,rct,flOptions,lCount,pchString,alAdx);
+}
+//******************************************************************************
+//******************************************************************************
+BOOL CFT2Module::Ft2CharStringPosAtW(HPS hps, PPOINTLOS2 ptl,PRECTLOS2 rct,ULONG flOptions,LONG lCount,LPCWSTR pchString,CONST INT *alAdx, DWORD fuWin32Options)
+{
+    DWORD  ret; 
+    USHORT sel;
+
+    // All FreeType calls should be wrapped for saving FS 
+    if(pfnFt2CharStringPosAtW) {
+        sel  = RestoreOS2FS();
+        ret  = pfnFt2CharStringPosAtW(hps, ptl,rct,flOptions,lCount,pchString,alAdx, fuWin32Options);
+        SetFS(sel);
+        if(ret || (ret == FALSE && ERRORIDERROR(WinGetLastError(0)) != PMERR_FUNCTION_NOT_SUPPORTED))
+            return ret; 
+    }
+    //else fall back to GPI
+    //NOTE: We don't support fuWin32Options in the fallback case
+    int   len;
+    LPSTR astring;
+
+    pDCData pHps = (pDCData)OSLibGpiQueryDCData(hps);
+
+    len = WideCharToMultiByte( CP_ACP, 0, pchString, lCount, 0, 0, NULL, NULL );
+    astring = (char *)malloc( len + 1 );
+    lstrcpynWtoA(astring, pchString, len + 1 );
+
+    ret = OSLibGpiCharStringPosAt(pHps,ptl,rct,flOptions,lCount,astring,alAdx);
+    free(astring);
+    return ret;
+}
+//******************************************************************************
+//******************************************************************************
+DWORD CFT2Module::Ft2GetFontData(HPS hps, DWORD dwTable, DWORD dwOffset,
+                                 LPVOID lpvBuffer, DWORD cbData)
+{
+    //no fallback
+    SetLastError(ERROR_CALL_NOT_IMPLEMENTED_W);
+    return(GDI_ERROR);
+}
+//******************************************************************************
+// Query the font type current selected into the presentation space, or, 
+// when hps == NULL, query the type of the font with the specified name
+//******************************************************************************
+DWORD CFT2Module::Ft2QueryFontType(HPS hps, LPCSTR lpszFontName)
+{
+    DWORD  ret; 
+    USHORT sel;
+
+    // All FreeType calls should be wrapped for saving FS 
+    if(pfnFt2QueryFontType) {
+        sel  = RestoreOS2FS();
+        ret  = pfnFt2QueryFontType(hps, lpszFontName);
+        SetFS(sel);
+        if(ret || (ret == GDI_ERROR && ERRORIDERROR(WinGetLastError(0)) != PMERR_FUNCTION_NOT_SUPPORTED))
+            return ret; 
+    }
+    //no fallback
+    return FT2_FONTTYPE_UNKNOWN;
+}
+//******************************************************************************
+//******************************************************************************
+BOOL CFT2Module::Ft2GetStringWidthW(HDC hdc, LPWSTR lpszString, UINT cbString, PINT pWidthArray)
+{
+    DWORD  ret; 
+    USHORT sel;
+    pDCData pHps;
+
+    pHps = (pDCData)OSLibGpiQueryDCData(hdc);
+    if(pHps == NULL) {
+        DebugInt3();
+        SetLastError(ERROR_INVALID_HANDLE_W);
+        return 0;
+    }
+
+    // All FreeType calls should be wrapped for saving FS 
+    if(pfnFt2QueryStringWidthW) {
+        sel  = RestoreOS2FS();
+        ret  = pfnFt2QueryStringWidthW((HPS)hdc, lpszString, cbString, (LONG *)pWidthArray);
+        SetFS(sel);
+        if(ret || (ret == GDI_ERROR && ERRORIDERROR(WinGetLastError(0)) != PMERR_FUNCTION_NOT_SUPPORTED))
+        {
+           if(pHps && pHps->isPrinter && pHps->hdc)
+           {//scale for printer dcs
+               LONG alArray[2];
+
+               if(OSLibDevQueryCaps(pHps, OSLIB_CAPS_HORIZONTAL_RESOLUTION, 2, &alArray[0]) &&
+                  alArray[0] != alArray[1]) 
+               {
+                   dprintf(("Different hor/vert resolutions (%d,%d)", alArray[0], alArray[1]));
+                   for (int i = 0; i < cbString; i++)
+                   {
+                       pWidthArray[i] = pWidthArray[i] * alArray[0] / alArray[1];
+                   }
+                }
+            }
+            return ret; 
+        }
+    }
+    //fallback method
+    int c, i;
+    for (i = 0; i < cbString; i++)
+    {
+        if (GetCharWidth32W(hdc, lpszString[i], lpszString[i], (LPINT)&c)) {
+            dprintf(("%c pWidthArray[%d] = %d", lpszString[i], i, c));
+            pWidthArray[i]= c;
+        }
+        else {
+            dprintf(("WARNING: GetCharWidth32W failed for %c!!!", lpszString[i]));
+            pWidthArray[i] = 0;
+        }
+    }
+    return TRUE;
+}
+/*****************************************************************************
+ * Name      : DWORD GetCharacterPlacementW
+ * Purpose   : The GetCharacterPlacementW function retrieves information about
+ *             a character string, such as character widths, caret positioning,
+ *             ordering within the string, and glyph rendering. The type of
+ *             information returned depends on the dwFlags parameter and is
+ *             based on the currently selected font in the given display context.
+ *             The function copies the information to the specified GCP_RESULTSW
+ *             structure or to one or more arrays specified by the structure.
+ * Parameters: HDC     hdc        handle to device context
+ *             LPCSTR lpString   pointer to string
+ *             int     nCount     number of characters in string
+ *             int     nMaxExtent maximum extent for displayed string
+ *             GCP_RESULTSW *lpResults  pointer to buffer for placement result
+ *             DWORD   dwFlags    placement flags
+ * Variables :
+ * Result    :
+ * Remark    :
+ * Status    : Partly working
+ *
+ * Author    : Borrowed Rewind Code
+ *****************************************************************************/
+DWORD CFT2Module::Ft2GetCharacterPlacementW(HDC           hdc,
+                                            LPCWSTR       lpString,
+                                            int           uCount,
+                                            int           nMaxExtent,
+                                            GCP_RESULTSW *lpResults,
+                                            DWORD         dwFlags)
+{
+    DWORD  ret; 
+    USHORT sel;
+    SIZE   size;
+    UINT   i, nSet;
+    pDCData pHps;
+
+    pHps = (pDCData)OSLibGpiQueryDCData(hdc);
+    if(pHps == NULL) {
+        DebugInt3();
+        SetLastError(ERROR_INVALID_HANDLE_W);
+        return 0;
+    }
+
+    dprintf(("%ls, %d, %d, 0x%08lx\n", lpString, uCount, nMaxExtent, dwFlags));
+
+    dprintf(("lStructSize=%ld, lpOutString=%p, lpOrder=%p, lpDx=%p, lpCaretPos=%p, lpClass=%p, lpGlyphs=%p, nGlyphs=%u, nMaxFit=%d\n",
+	    lpResults->lStructSize, lpResults->lpOutString, lpResults->lpOrder,
+	    lpResults->lpDx, lpResults->lpCaretPos, lpResults->lpClass,
+	    lpResults->lpGlyphs, lpResults->nGlyphs, lpResults->nMaxFit));
+
+    if(dwFlags&(~0))            dprintf(("unsupported flags 0x%08lx\n", dwFlags));
+    if(lpResults->lpCaretPos)	dprintf(("caret positions not implemented\n"));
+    if(lpResults->lpClass)	dprintf(("classes not implemented\n"));
+
+    nSet = (UINT)uCount;
+    if(nSet > lpResults->nGlyphs)
+	nSet = lpResults->nGlyphs;
+
+    /* return number of initialized fields */
+    lpResults->nGlyphs = nSet;
+    lpResults->nMaxFit = nSet;
+
+    /* Treat the case where no special handling was requested in a fastpath way */
+    /* copy will do if the GCP_REORDER flag is not set */
+    if(lpResults->lpOutString)
+        strncpyW( lpResults->lpOutString, lpString, nSet );
+
+    if(lpResults->lpOrder)
+        for(i = 0; i < nSet; i++)
+            lpResults->lpOrder[i] = i;
+
+    //fallback method
+
+    /* FIXME: Will use the placement chars */
+    if (lpResults->lpDx)
+    {
+        Ft2GetStringWidthW(hdc, (LPWSTR)lpString, nSet, lpResults->lpDx);
+    }
+
+    if(lpResults->lpGlyphs)
+  	GetGlyphIndicesW(hdc, lpString, nSet, lpResults->lpGlyphs, 0);
+
+    if (GetTextExtentPoint32W(hdc, lpString, uCount, &size))
+         ret = MAKELONG(size.cx, size.cy);
+    else ret = 0;
+
+    return ret;
+}
+//******************************************************************************
+//******************************************************************************
