From 1ad46cbf3a9963f3d6d8c687480a80d359ec15f8 Mon Sep 17 00:00:00 2001
From: marha <marha@users.sourceforge.net>
Date: Sun, 28 Feb 2010 19:11:59 +0000
Subject: Some synchronisations with the jturney branch

---
 xorg-server/hw/xwin/InitOutput.c         | 2279 +++++++--------
 xorg-server/hw/xwin/Makefile.am          |  449 ++-
 xorg-server/hw/xwin/glx/indirect.c       | 4533 +++++++++++++++---------------
 xorg-server/hw/xwin/glx/winpriv.h        |   33 +-
 xorg-server/hw/xwin/win.h                | 2920 +++++++++----------
 xorg-server/hw/xwin/winauth.c            |  404 +--
 xorg-server/hw/xwin/winclipboardthread.c |  924 +++---
 xorg-server/hw/xwin/winconfig.c          | 2128 +++++++-------
 xorg-server/hw/xwin/winkeybd.c           | 1148 ++++----
 xorg-server/hw/xwin/winkeybd.h           |  616 ++--
 xorg-server/hw/xwin/winmouse.c           |  776 ++---
 xorg-server/hw/xwin/winmultiwindowwm.c   | 3490 +++++++++++------------
 xorg-server/hw/xwin/winscrinit.c         | 1580 +++++------
 xorg-server/hw/xwin/winshaddd.c          | 2910 +++++++++----------
 xorg-server/hw/xwin/winshadddnl.c        | 2934 +++++++++----------
 xorg-server/hw/xwin/winwindowswm.c       | 1302 +++++----
 16 files changed, 14173 insertions(+), 14253 deletions(-)

(limited to 'xorg-server/hw/xwin')

diff --git a/xorg-server/hw/xwin/InitOutput.c b/xorg-server/hw/xwin/InitOutput.c
index acb7d4ab2..b1bc551c2 100644
--- a/xorg-server/hw/xwin/InitOutput.c
+++ b/xorg-server/hw/xwin/InitOutput.c
@@ -1,1139 +1,1140 @@
-/*
-
-Copyright 1993, 1998  The Open Group
-Copyright (C) Colin Harrison 2005-2008
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-
-*/
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-#include "winconfig.h"
-#include "winprefs.h"
-#ifdef XWIN_CLIPBOARD
-#include "X11/Xlocale.h"
-#endif
-#ifdef DPMSExtension
-#include "dpmsproc.h"
-#endif
-#ifdef __CYGWIN__
-#include <mntent.h>
-#endif
-#if defined(WIN32)
-#include "xkbsrv.h"
-#endif
-#ifdef RELOCATE_PROJECTROOT
-#include <shlobj.h>
-typedef HRESULT (*SHGETFOLDERPATHPROC)(
-    HWND hwndOwner,
-    int nFolder,
-    HANDLE hToken,
-    DWORD dwFlags,
-    LPTSTR pszPath
-);
-#endif
-
-
-/*
- * References to external symbols
- */
-
-extern int			g_iNumScreens;
-extern winScreenInfo		g_ScreenInfo[];
-extern int			g_iLastScreen;
-extern char *			g_pszCommandLine;
-extern Bool			g_fSilentFatalError;
-
-extern char *			g_pszLogFile;
-extern Bool			g_fLogFileChanged;
-extern int			g_iLogVerbose;
-Bool				g_fLogInited;
-
-extern Bool			g_fXdmcpEnabled;
-extern Bool			g_fAuthEnabled;
-#ifdef HAS_DEVWINDOWS
-extern int			g_fdMessageQueue;
-#endif
-extern const char *		g_pszQueryHost;
-extern HINSTANCE		g_hInstance;
-
-#ifdef XWIN_CLIPBOARD
-extern Bool			g_fUnicodeClipboard;
-extern Bool			g_fClipboardLaunched;
-extern Bool			g_fClipboardStarted;
-extern pthread_t		g_ptClipboardProc;
-extern HWND			g_hwndClipboard;
-extern Bool			g_fClipboard;
-#endif
-
-extern HMODULE			g_hmodDirectDraw;
-extern FARPROC			g_fpDirectDrawCreate;
-extern FARPROC			g_fpDirectDrawCreateClipper;
-  
-extern HMODULE			g_hmodCommonControls;
-extern FARPROC			g_fpTrackMouseEvent;
-extern Bool			g_fNoHelpMessageBox;                     
-extern Bool			g_fSilentDupError;                     
-  
-  
-/*
- * Function prototypes
- */
-
-#ifdef XWIN_CLIPBOARD
-static void
-winClipboardShutdown (void);
-#endif
-
-#if defined(DDXOSVERRORF)
-void
-OsVendorVErrorF (const char *pszFormat, va_list va_args);
-#endif
-
-void
-winInitializeDefaultScreens (void);
-
-static Bool
-winCheckDisplayNumber (void);
-
-void
-winLogCommandLine (int argc, char *argv[]);
-
-void
-winLogVersionInfo (void);
-
-Bool
-winValidateArgs (void);
-
-#ifdef RELOCATE_PROJECTROOT
-const char *
-winGetBaseDir(void);
-#endif
-
-/*
- * For the depth 24 pixmap we default to 32 bits per pixel, but
- * we change this pixmap format later if we detect that the display
- * is going to be running at 24 bits per pixel.
- *
- * FIXME: On second thought, don't DIBs only support 32 bits per pixel?
- * DIBs are the underlying bitmap used for DirectDraw surfaces, so it
- * seems that all pixmap formats with depth 24 would be 32 bits per pixel.
- * Confirm whether depth 24 DIBs can have 24 bits per pixel, then remove/keep
- * the bits per pixel adjustment and update this comment to reflect the
- * situation.  Harold Hunt - 2002/07/02
- */
-
-static PixmapFormatRec g_PixmapFormats[] = {
-  { 1,    1,      BITMAP_SCANLINE_PAD },
-  { 4,    8,      BITMAP_SCANLINE_PAD },
-  { 8,    8,      BITMAP_SCANLINE_PAD },
-  { 15,   16,     BITMAP_SCANLINE_PAD },
-  { 16,   16,     BITMAP_SCANLINE_PAD },
-  { 24,   32,     BITMAP_SCANLINE_PAD },
-#ifdef RENDER
-  { 32,   32,     BITMAP_SCANLINE_PAD }
-#endif
-};
-
-const int NUMFORMATS = sizeof (g_PixmapFormats) / sizeof (g_PixmapFormats[0]);
-
-#ifdef XWIN_CLIPBOARD
-static void
-winClipboardShutdown (void)
-{
-  /* Close down clipboard resources */
-  if (g_fClipboard && g_fClipboardLaunched && g_fClipboardStarted)
-    {
-      /* Synchronously destroy the clipboard window */
-      if (g_hwndClipboard != NULL)
-	{
-	  SendMessage (g_hwndClipboard, WM_DESTROY, 0, 0);
-	  /* NOTE: g_hwndClipboard is set to NULL in winclipboardthread.c */
-	}
-      else
-	return;
-      
-      /* Wait for the clipboard thread to exit */
-      pthread_join (g_ptClipboardProc, NULL);
-
-      g_fClipboardLaunched = FALSE;
-      g_fClipboardStarted = FALSE;
-
-      winDebug ("winClipboardShutdown - Clipboard thread has exited.\n");
-    }
-}
-#endif
-
-
-#if defined(DDXBEFORERESET)
-/*
- * Called right before KillAllClients when the server is going to reset,
- * allows us to shutdown our seperate threads cleanly.
- */
-
-void
-ddxBeforeReset (void)
-{
-  winDebug ("ddxBeforeReset - Hello\n");
-
-#ifdef XWIN_CLIPBOARD
-  winClipboardShutdown ();
-#endif
-}
-#endif
-
-
-/* See Porting Layer Definition - p. 57 */
-void
-ddxGiveUp (void)
-{
-  int		i;
-
-#if CYGDEBUG
-  winDebug ("ddxGiveUp\n");
-#endif
-
-  /* Perform per-screen deinitialization */
-  for (i = 0; i < g_iNumScreens; ++i)
-    {
-      /* Delete the tray icon */
-      if (!g_ScreenInfo[i].fNoTrayIcon && g_ScreenInfo[i].pScreen)
- 	winDeleteNotifyIcon (winGetScreenPriv (g_ScreenInfo[i].pScreen));
-    }
-
-#ifdef XWIN_MULTIWINDOW
-  /* Notify the worker threads we're exiting */
-  winDeinitMultiWindowWM ();
-#endif
-
-#ifdef HAS_DEVWINDOWS
-  /* Close our handle to our message queue */
-  if (g_fdMessageQueue != WIN_FD_INVALID)
-    {
-      /* Close /dev/windows */
-      close (g_fdMessageQueue);
-
-      /* Set the file handle to invalid */
-      g_fdMessageQueue = WIN_FD_INVALID;
-    }
-#endif
-
-  if (!g_fLogInited) {
-    LogInit (g_pszLogFile, NULL);
-    g_fLogInited = TRUE;
-  }  
-  LogClose ();
-
-  /*
-   * At this point we aren't creating any new screens, so
-   * we are guaranteed to not need the DirectDraw functions.
-   */
-  if (g_hmodDirectDraw != NULL)
-    {
-      FreeLibrary (g_hmodDirectDraw);
-      g_hmodDirectDraw = NULL;
-      g_fpDirectDrawCreate = NULL;
-      g_fpDirectDrawCreateClipper = NULL;
-    }
-
-  /* Unload our TrackMouseEvent funtion pointer */
-  if (g_hmodCommonControls != NULL)
-    {
-      FreeLibrary (g_hmodCommonControls);
-      g_hmodCommonControls = NULL;
-      g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
-    }
-  
-  /* Free concatenated command line */
-  if (g_pszCommandLine)
-    {
-      free (g_pszCommandLine);
-      g_pszCommandLine = NULL;
-    }
-
-  /* Remove our keyboard hook if it is installed */
-  winRemoveKeyboardHookLL ();
-
-  /* Tell Windows that we want to end the app */
-  PostQuitMessage (0);
-}
-
-
-/* See Porting Layer Definition - p. 57 */
-void
-AbortDDX (void)
-{
-#if CYGDEBUG
-  winDebug ("AbortDDX\n");
-#endif
-  ddxGiveUp ();
-}
-
-#ifdef __CYGWIN__
-/* hasmntopt is currently not implemented for cygwin */
-static const char *winCheckMntOpt(const struct mntent *mnt, const char *opt)
-{
-    const char *s;
-    size_t len;
-    if (mnt == NULL)
-        return NULL;
-    if (opt == NULL)
-        return NULL;
-    if (mnt->mnt_opts == NULL)
-        return NULL;
-
-    len = strlen(opt);
-    s = strstr(mnt->mnt_opts, opt);
-    if (s == NULL)
-        return NULL;
-    if ((s == mnt->mnt_opts || *(s-1) == ',') &&  (s[len] == 0 || s[len] == ','))
-        return (char *)opt;
-    return NULL;
-}
-
-static void
-winCheckMount(void)
-{
-  FILE *mnt;
-  struct mntent *ent;
-
-  enum { none = 0, sys_root, user_root, sys_tmp, user_tmp } 
-    level = none, curlevel;
-  BOOL binary = TRUE;
-
-  mnt = setmntent("/etc/mtab", "r");
-  if (mnt == NULL)
-  {
-    ErrorF("setmntent failed");
-    return;
-  }
-
-  while ((ent = getmntent(mnt)) != NULL)
-  {
-    BOOL system = (winCheckMntOpt(ent, "user") != NULL);
-    BOOL root = (strcmp(ent->mnt_dir, "/") == 0);
-    BOOL tmp = (strcmp(ent->mnt_dir, "/tmp") == 0);
-    
-    if (system)
-    {
-      if (root)
-        curlevel = sys_root;
-      else if (tmp)
-        curlevel = sys_tmp;
-      else
-        continue;
-    }
-    else
-    {
-      if (root)
-        curlevel = user_root;
-      else if (tmp) 
-        curlevel = user_tmp;
-      else
-        continue;
-    }
-
-    if (curlevel <= level)
-      continue;
-    level = curlevel;
-
-    if ((winCheckMntOpt(ent, "binary") == NULL) ||
-        (winCheckMntOpt(ent, "binmode") == NULL))
-      binary = 0;
-    else
-      binary = 1;
-  }
-    
-  if (endmntent(mnt) != 1)
-  {
-    ErrorF("endmntent failed");
-    return;
-  }
-  
- if (!binary) 
-   winMsg(X_WARNING, "/tmp mounted in textmode\n");
-}
-#else
-static void
-winCheckMount(void) 
-{
-}
-#endif
-
-#ifdef RELOCATE_PROJECTROOT
-const char * 
-winGetBaseDir(void)
-{
-    static BOOL inited = FALSE;
-    static char buffer[MAX_PATH];
-    if (!inited)
-    {
-        char *fendptr;
-        HMODULE module = GetModuleHandle(NULL);
-        DWORD size = GetModuleFileName(module, buffer, sizeof(buffer));
-        if (sizeof(buffer) > 0)
-            buffer[sizeof(buffer)-1] = 0;
-    
-        fendptr = buffer + size;
-        while (fendptr > buffer)
-        {
-            if (*fendptr == '\\' || *fendptr == '/')
-            {
-                *fendptr = 0;
-                break;
-            }
-            fendptr--;
-        }
-        inited = TRUE;
-    }
-    return buffer;
-}
-#endif
-
-static void
-winFixupPaths (void)
-{
-    BOOL changed_fontpath = FALSE;
-    MessageType font_from = X_DEFAULT;
-#ifdef RELOCATE_PROJECTROOT
-    const char *basedir = winGetBaseDir();
-    size_t basedirlen = strlen(basedir);
-#endif
-
-#ifdef READ_FONTDIRS
-    {
-        /* Open fontpath configuration file */
-        FILE *fontdirs = fopen(ETCX11DIR "/font-dirs", "rt");
-        if (fontdirs != NULL)
-        {
-            char buffer[256];
-            int needs_sep = TRUE; 
-            int comment_block = FALSE;
-
-            /* get defautl fontpath */
-            char *fontpath = xstrdup(defaultFontPath);
-            size_t size = strlen(fontpath);
-
-            /* read all lines */
-            while (!feof(fontdirs))
-            {
-                size_t blen;
-                char *hashchar;
-                char *str;
-                int has_eol = FALSE;
-
-                /* read one line */
-                str = fgets(buffer, sizeof(buffer), fontdirs);
-                if (str == NULL) /* stop on error or eof */
-                    break;
-
-                if (strchr(str, '\n') != NULL)
-                    has_eol = TRUE;
-
-                /* check if block is continued comment */
-                if (comment_block)
-                {
-                    /* ignore all input */
-                    *str = 0; 
-                    blen = 0; 
-                    if (has_eol) /* check if line ended in this block */
-                        comment_block = FALSE;
-                }
-                else 
-                {
-                    /* find comment character. ignore all trailing input */
-                    hashchar = strchr(str, '#');
-                    if (hashchar != NULL)
-                    {
-                        *hashchar = 0;
-                        if (!has_eol) /* mark next block as continued comment */
-                            comment_block = TRUE;
-                    }
-                }
-
-                /* strip whitespaces from beginning */
-                while (*str == ' ' || *str == '\t')
-                    str++;
-
-                /* get size, strip whitespaces from end */ 
-                blen = strlen(str);
-                while (blen > 0 && (str[blen-1] == ' ' || 
-                            str[blen-1] == '\t' || str[blen-1] == '\n'))
-                {
-                    str[--blen] = 0;
-                }
-
-                /* still something left to add? */ 
-                if (blen > 0)
-                {
-                    size_t newsize = size + blen;
-                    /* reserve one character more for ',' */
-                    if (needs_sep)
-                        newsize++;
-
-                    /* allocate memory */
-                    if (fontpath == NULL)
-                        fontpath = malloc(newsize+1);
-                    else
-                        fontpath = realloc(fontpath, newsize+1);
-
-                    /* add separator */
-                    if (needs_sep)
-                    {
-                        fontpath[size] = ',';
-                        size++;
-                        needs_sep = FALSE;
-                    }
-
-                    /* mark next line as new entry */
-                    if (has_eol)
-                        needs_sep = TRUE;
-
-                    /* add block */
-                    strncpy(fontpath + size, str, blen);
-                    fontpath[newsize] = 0;
-                    size = newsize;
-                }
-            }
-
-            /* cleanup */
-            fclose(fontdirs);  
-            defaultFontPath = xstrdup(fontpath);
-            free(fontpath);
-            changed_fontpath = TRUE;
-            font_from = X_CONFIG;
-        }
-    }
-#endif /* READ_FONTDIRS */
-#ifdef RELOCATE_PROJECTROOT
-    {
-        const char *libx11dir = PROJECTROOT "/lib/X11";
-        size_t libx11dir_len = strlen(libx11dir);
-        char *newfp = NULL;
-        size_t newfp_len = 0;
-        const char *endptr, *ptr, *oldptr = defaultFontPath;
-
-        endptr = oldptr + strlen(oldptr);
-        ptr = strchr(oldptr, ',');
-        if (ptr == NULL)
-            ptr = endptr;
-        while (ptr != NULL)
-        {
-            size_t oldfp_len = (ptr - oldptr);
-            size_t newsize = oldfp_len;
-            char *newpath = malloc(newsize + 1);
-            strncpy(newpath, oldptr, newsize);
-            newpath[newsize] = 0;
-
-
-            if (strncmp(libx11dir, newpath, libx11dir_len) == 0)
-            {
-                char *compose;
-                newsize = newsize - libx11dir_len + basedirlen;
-                compose = malloc(newsize + 1);  
-                strcpy(compose, basedir);
-                strncat(compose, newpath + libx11dir_len, newsize - basedirlen);
-                compose[newsize] = 0;
-                free(newpath);
-                newpath = compose;
-            }
-
-            oldfp_len = newfp_len;
-            if (oldfp_len > 0)
-                newfp_len ++; /* space for separator */
-            newfp_len += newsize;
-
-            if (newfp == NULL)
-                newfp = malloc(newfp_len + 1);
-            else
-                newfp = realloc(newfp, newfp_len + 1);
-
-            if (oldfp_len > 0)
-            {
-                strcpy(newfp + oldfp_len, ",");
-                oldfp_len++;
-            }
-            strcpy(newfp + oldfp_len, newpath);
-
-            free(newpath);
-
-            if (*ptr == 0)
-            {
-                oldptr = ptr;
-                ptr = NULL;
-            } else
-            {
-                oldptr = ptr + 1;
-                ptr = strchr(oldptr, ',');
-                if (ptr == NULL)
-                    ptr = endptr;
-            }
-        } 
-
-        defaultFontPath = xstrdup(newfp);
-        free(newfp);
-        changed_fontpath = TRUE;
-    }
-#endif /* RELOCATE_PROJECTROOT */
-    if (changed_fontpath)
-        winMsg (font_from, "FontPath set to \"%s\"\n", defaultFontPath);
-
-#ifdef RELOCATE_PROJECTROOT
-    if (getenv("XKEYSYMDB") == NULL)
-    {
-        char buffer[MAX_PATH];
-        snprintf(buffer, sizeof(buffer), "XKEYSYMDB=%s\\XKeysymDB",
-                basedir);
-        buffer[sizeof(buffer)-1] = 0;
-        putenv(buffer);
-    }
-    if (getenv("XERRORDB") == NULL)
-    {
-        char buffer[MAX_PATH];
-        snprintf(buffer, sizeof(buffer), "XERRORDB=%s\\XErrorDB",
-                basedir);
-        buffer[sizeof(buffer)-1] = 0;
-        putenv(buffer);
-    }
-    if (getenv("XLOCALEDIR") == NULL)
-    {
-        char buffer[MAX_PATH];
-        snprintf(buffer, sizeof(buffer), "XLOCALEDIR=%s\\locale",
-                basedir);
-        buffer[sizeof(buffer)-1] = 0;
-        putenv(buffer);
-    }
-    if (getenv("HOME") == NULL)
-    {
-        HMODULE shfolder;
-        SHGETFOLDERPATHPROC shgetfolderpath = NULL;
-        char buffer[MAX_PATH + 5];
-        strncpy(buffer, "HOME=", 5);
-
-        /* Try to load SHGetFolderPath from shfolder.dll and shell32.dll */
-        
-        shfolder = LoadLibrary("shfolder.dll");
-        /* fallback to shell32.dll */
-        if (shfolder == NULL)
-            shfolder = LoadLibrary("shell32.dll");
-
-        /* resolve SHGetFolderPath */
-        if (shfolder != NULL)
-            shgetfolderpath = (SHGETFOLDERPATHPROC)GetProcAddress(shfolder, "SHGetFolderPathA");
-
-        /* query appdata directory */
-        if (shgetfolderpath &&
-                shgetfolderpath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, 
-                    buffer + 5) == 0)
-        { 
-            putenv(buffer);
-        } else
-        {
-            winMsg (X_ERROR, "Can not determine HOME directory\n");
-        } 
-        if (shfolder != NULL)
-            FreeLibrary(shfolder);
-    }
-    if (!g_fLogFileChanged) {
-        static char buffer[MAX_PATH];
-        DWORD size = GetTempPath(sizeof(buffer), buffer);
-        if (size && size < sizeof(buffer))
-        {
-            snprintf(buffer + size, sizeof(buffer) - size, 
-                    "XWin.%s.log", display); 
-            buffer[sizeof(buffer)-1] = 0;
-            g_pszLogFile = buffer;
-            winMsg (X_DEFAULT, "Logfile set to \"%s\"\n", g_pszLogFile);
-        }
-    }
-    {
-        static char xkbbasedir[MAX_PATH];
-
-        snprintf(xkbbasedir, sizeof(xkbbasedir), "%s\\xkb", basedir);
-        if (sizeof(xkbbasedir) > 0)
-            xkbbasedir[sizeof(xkbbasedir)-1] = 0;
-        XkbBaseDirectory = xkbbasedir;
-	XkbBinDirectory = basedir;
-    }
-#endif /* RELOCATE_PROJECTROOT */
-}
-
-void
-OsVendorInit (void)
-{
-  /* Re-initialize global variables on server reset */
-  winInitializeGlobals ();
-
-  LogInit (NULL, NULL);
-  LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose);
-
-  winFixupPaths();
-
-#ifdef DDXOSVERRORF
-  if (!OsVendorVErrorFProc)
-    OsVendorVErrorFProc = OsVendorVErrorF;
-#endif
-
-  if (!g_fLogInited) {
-    /* keep this order. If LogInit fails it calls Abort which then calls
-     * ddxGiveUp where LogInit is called again and creates an infinite 
-     * recursion. If we set g_fLogInited to TRUE before the init we 
-     * avoid the second call 
-     */  
-    g_fLogInited = TRUE;
-    LogInit (g_pszLogFile, NULL);
-  } 
-  LogSetParameter (XLOG_FLUSH, 1);
-  LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose);
-  LogSetParameter (XLOG_FILE_VERBOSITY, g_iLogVerbose);
-
-  /* Log the version information */
-  if (serverGeneration == 1)
-    winLogVersionInfo ();
-
-  winCheckMount();  
-
-  /* Add a default screen if no screens were specified */
-  if (g_iNumScreens == 0)
-    {
-      winDebug ("OsVendorInit - Creating bogus screen 0\n");
-
-      /* 
-       * We need to initialize default screens if no arguments
-       * were processed.  Otherwise, the default screens would
-       * already have been initialized by ddxProcessArgument ().
-       */
-      winInitializeDefaultScreens ();
-
-      /*
-       * Add a screen 0 using the defaults set by 
-       * winInitializeDefaultScreens () and any additional parameters
-       * processed by ddxProcessArgument ().
-       */
-      g_iNumScreens = 1;
-      g_iLastScreen = 0;
-
-      /* We have to flag this as an explicit screen, even though it isn't */
-      g_ScreenInfo[0].fExplicitScreen = TRUE;
-    }
-}
-
-
-static void
-winUseMsg (void)
-{
-  ErrorF("\n");
-  ErrorF("\n");
-  ErrorF(EXECUTABLE_NAME " Device Dependent Usage:\n");
-  ErrorF("\n");
-
-#ifdef XWIN_CLIPBOARD
-  ErrorF ("-[no]clipboard\n"
-	  "\tEnable [disable] the clipboard integration. Default is enabled.\n");
-#endif
-
-  ErrorF ("-clipupdates num_boxes\n"
-	  "\tUse a clipping region to constrain shadow update blits to\n"
-	  "\tthe updated region when num_boxes, or more, are in the\n"
-	  "\tupdated region.\n");
-
-#ifdef XWIN_XF86CONFIG
-  ErrorF ("-config\n"
-          "\tSpecify a configuration file.\n");
-
-  ErrorF ("-configdir\n"
-          "\tSpecify a configuration directory.\n");
-#endif
-
-  ErrorF ("-depth bits_per_pixel\n"
-	  "\tSpecify an optional bitdepth to use in fullscreen mode\n"
-	  "\twith a DirectDraw engine.\n");
-
-  ErrorF ("-emulate3buttons [timeout]\n"
-	  "\tEmulate 3 button mouse with an optional timeout in\n"
-	  "\tmilliseconds.\n");
-
-#ifdef XWIN_EMULATEPSEUDO
-  ErrorF ("-emulatepseudo\n"
-	  "\tCreate a depth 8 PseudoColor visual when running in\n"
-	  "\tdepths 15, 16, 24, or 32, collectively known as TrueColor\n"
-	  "\tdepths.  The PseudoColor visual does not have correct colors,\n"
-	  "\tand it may crash, but it at least allows you to run your\n"
-	  "\tapplication in TrueColor modes.\n");
-#endif
-
-  ErrorF ("-engine engine_type_id\n"
-	  "\tOverride the server's automatically selected engine type:\n"
-	  "\t\t1 - Shadow GDI\n"
-	  "\t\t2 - Shadow DirectDraw\n"
-	  "\t\t4 - Shadow DirectDraw4 Non-Locking\n"
-#ifdef XWIN_NATIVEGDI
-	  "\t\t16 - Native GDI - experimental\n"
-#endif
-	  );
-
-  ErrorF ("-fullscreen\n"
-	  "\tRun the server in fullscreen mode.\n");
-
-  ErrorF ("-ignoreinput\n"
-	  "\tIgnore keyboard and mouse input.\n");
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  ErrorF ("-internalwm\n"
-	  "\tRun the internal window manager.\n");
-#endif
-
-#ifdef XWIN_XF86CONFIG
-  ErrorF ("-keyboard\n"
-	  "\tSpecify a keyboard device from the configuration file.\n");
-#endif
-
-  ErrorF ("-[no]keyhook\n"
-	  "\tGrab special Windows keypresses like Alt-Tab or the Menu "
-          "key.\n");
-
-  ErrorF ("-lesspointer\n"
-	  "\tHide the windows mouse pointer when it is over any\n"
-          "\t" EXECUTABLE_NAME " window.  This prevents ghost cursors appearing when\n"
-	  "\tthe Windows cursor is drawn on top of the X cursor\n");
-
-  ErrorF ("-logfile filename\n"
-	  "\tWrite log messages to <filename>.\n");
-
-  ErrorF ("-logverbose verbosity\n"
-	  "\tSet the verbosity of log messages. [NOTE: Only a few messages\n"
-	  "\trespect the settings yet]\n"
-	  "\t\t0 - only print fatal error.\n"
-	  "\t\t1 - print additional configuration information.\n"
-	  "\t\t2 - print additional runtime information [default].\n"
-	  "\t\t3 - print debugging and tracing information.\n");
-
-  ErrorF ("-[no]multimonitors or -[no]multiplemonitors\n"
-	  "\tUse the entire virtual screen if multiple\n"
-	  "\tmonitors are present.\n");
-
-#ifdef XWIN_MULTIWINDOW
-  ErrorF ("-multiwindow\n"
-	  "\tRun the server in multi-window mode.\n");
-#endif
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  ErrorF ("-mwextwm\n"
-	  "\tRun the server in multi-window external window manager mode.\n");
-#endif
-
-  ErrorF ("-nodecoration\n"
-          "\tDo not draw a window border, title bar, etc.  Windowed\n"
-	  "\tmode only.\n");
-
-#ifdef XWIN_CLIPBOARD
-  ErrorF ("-nounicodeclipboard\n"
-	  "\tDo not use Unicode clipboard even if on a NT-based platform.\n");
-#endif
-
-  ErrorF ("-refresh rate_in_Hz\n"
-	  "\tSpecify an optional refresh rate to use in fullscreen mode\n"
-	  "\twith a DirectDraw engine.\n");
-
-  ErrorF ("-rootless\n"
-	  "\tRun the server in rootless mode.\n");
-
-  ErrorF ("-screen scr_num [width height [x y] | [[WxH[+X+Y]][@m]] ]\n"
-	  "\tEnable screen scr_num and optionally specify a width and\n"
-	  "\theight and initial position for that screen. Additionally\n"
-	  "\ta monitor number can be specified to start the server on,\n"
-	  "\tat which point, all coordinates become relative to that\n"
-      "\tmonitor (Not for Windows NT4 and 95). Examples:\n"
-      "\t -screen 0 800x600+100+100@2 ; 2nd monitor offset 100,100 size 800x600\n"
-      "\t -screen 0 1024x768@3        ; 3rd monitor size 1024x768\n"
-      "\t -screen 0 @1 ; on 1st monitor using its full resolution (the default)\n");
-
-  ErrorF ("-scrollbars\n"
-	  "\tIn windowed mode, allow screens bigger than the Windows desktop.\n"
-	  "\tMoreover, if the window has decorations, one can now resize\n"
-	  "\tit.\n");
-
-  ErrorF ("-silent-dup-error\n"
-	  "\tIf another instance of " EXECUTABLE_NAME " with the same display number is running\n"
-     "\texit silently and don’t display any error message.\n");
-
-  ErrorF ("-swcursor\n"
-	  "\tDisable the usage of the Windows cursor and use the X11 software\n"
-	  "\tcursor instead.\n");
-
-  ErrorF ("-[no]trayicon\n"
-          "\tDo not create a tray icon.  Default is to create one\n"
-	  "\ticon per screen.  You can globally disable tray icons with\n"
-	  "\t-notrayicon, then enable it for specific screens with\n"
-	  "\t-trayicon for those screens.\n");
-
-  ErrorF ("-[no]unixkill\n"
-          "\tCtrl+Alt+Backspace exits the X Server.\n");
-
-  ErrorF ("-[no]winkill\n"
-          "\tAlt+F4 exits the X Server.\n");
-
-  ErrorF ("-xkblayout XKBLayout\n"
-	  "\tEquivalent to XKBLayout in XF86Config files.\n"
-	  "\tFor example: -xkblayout de\n");
-
-  ErrorF ("-xkbmodel XKBModel\n"
-	  "\tEquivalent to XKBModel in XF86Config files.\n");
-
-  ErrorF ("-xkboptions XKBOptions\n"
-	  "\tEquivalent to XKBOptions in XF86Config files.\n");
-
-  ErrorF ("-xkbrules XKBRules\n"
-	  "\tEquivalent to XKBRules in XF86Config files.\n");
-
-  ErrorF ("-xkbvariant XKBVariant\n"
-	  "\tEquivalent to XKBVariant in XF86Config files.\n"
-	  "\tFor example: -xkbvariant nodeadkeys\n");
-}
-
-/* See Porting Layer Definition - p. 57 */
-void
-ddxUseMsg(void)
-{
-  /* Set a flag so that FatalError won't give duplicate warning message */
-  g_fSilentFatalError = TRUE;
-  
-  winUseMsg();  
-
-  /* Log file will not be opened for UseMsg unless we open it now */
-  if (!g_fLogInited) {
-    LogInit (g_pszLogFile, NULL);
-    g_fLogInited = TRUE;
-  }  
-  LogClose ();
-
-  /* Notify user where UseMsg text can be found.*/
-  if (!g_fNoHelpMessageBox)
-    winMessageBoxF ("The " PROJECT_NAME " help text has been printed to "
-		  "/tmp/XWin.log.\n"
-		  "Please open /tmp/XWin.log to read the help text.\n",
-		  MB_ICONINFORMATION);
-}
-
-/* See Porting Layer Definition - p. 20 */
-/*
- * Do any global initialization, then initialize each screen.
- * 
- * NOTE: We use ddxProcessArgument, so we don't need to touch argc and argv
- */
-
-void
-InitOutput (ScreenInfo *screenInfo, int argc, char *argv[])
-{
-  int		i;
-
-  /* Log the command line */
-  winLogCommandLine (argc, argv);
-
-#if CYGDEBUG
-  winDebug ("InitOutput\n");
-#endif
-
-  /* Validate command-line arguments */
-  if (serverGeneration == 1 && !winValidateArgs ())
-    {
-      FatalError ("InitOutput - Invalid command-line arguments found.  "
-		  "Exiting.\n");
-    }
-
-  /* Check for duplicate invocation on same display number.*/
-  if (serverGeneration == 1 && !winCheckDisplayNumber ())
-    {
-      if (g_fSilentDupError)
-        g_fSilentFatalError = TRUE;  
-      FatalError ("InitOutput - Duplicate invocation on display "
-		  "number: %s.  Exiting.\n", display);
-    }
-
-#ifdef XWIN_XF86CONFIG
-  /* Try to read the xorg.conf-style configuration file */
-  if (!winReadConfigfile ())
-    winErrorFVerb (1, "InitOutput - Error reading config file\n");
-#else
-  winMsg(X_INFO, "xorg.conf is not supported\n");
-  winMsg(X_INFO, "See http://x.cygwin.com/docs/faq/cygwin-x-faq.html "
-         "for more information\n");
-  winConfigFiles ();
-#endif
-
-  /* Load preferences from XWinrc file */
-  LoadPreferences();
-
-  /* Setup global screen info parameters */
-  screenInfo->imageByteOrder = IMAGE_BYTE_ORDER;
-  screenInfo->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
-  screenInfo->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
-  screenInfo->bitmapBitOrder = BITMAP_BIT_ORDER;
-  screenInfo->numPixmapFormats = NUMFORMATS;
-  
-  /* Describe how we want common pixmap formats padded */
-  for (i = 0; i < NUMFORMATS; i++)
-    {
-      screenInfo->formats[i] = g_PixmapFormats[i];
-    }
-
-  /* Load pointers to DirectDraw functions */
-  winGetDDProcAddresses ();
-  
-  /* Detect supported engines */
-  winDetectSupportedEngines ();
-
-  /* Load common controls library */
-  g_hmodCommonControls = LoadLibraryEx ("comctl32.dll", NULL, 0);
-
-  /* Load TrackMouseEvent function pointer */  
-  g_fpTrackMouseEvent = GetProcAddress (g_hmodCommonControls,
-					 "_TrackMouseEvent");
-  if (g_fpTrackMouseEvent == NULL)
-    {
-      winErrorFVerb (1, "InitOutput - Could not get pointer to function\n"
-	      "\t_TrackMouseEvent in comctl32.dll.  Try installing\n"
-	      "\tInternet Explorer 3.0 or greater if you have not\n"
-	      "\talready.\n");
-
-      /* Free the library since we won't need it */
-      FreeLibrary (g_hmodCommonControls);
-      g_hmodCommonControls = NULL;
-
-      /* Set function pointer to point to no operation function */
-      g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
-    }
-
-  /* Store the instance handle */
-  g_hInstance = GetModuleHandle (NULL);
-
-  /* Initialize each screen */
-  for (i = 0; i < g_iNumScreens; ++i)
-    {
-      /* Initialize the screen */
-      if (-1 == AddScreen (winScreenInit, argc, argv))
-	{
-	  FatalError ("InitOutput - Couldn't add screen %d", i);
-	}
-    }
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-
-  /* Generate a cookie used by internal clients for authorization */
-  if (g_fXdmcpEnabled || g_fAuthEnabled)
-    winGenerateAuthorization ();
-
-  /* Perform some one time initialization */
-  if (1 == serverGeneration)
-    {
-      /*
-       * setlocale applies to all threads in the current process.
-       * Apply locale specified in LANG environment variable.
-       */
-      setlocale (LC_ALL, "");
-    }
-#endif
-
-#if CYGDEBUG || YES
-  winDebug ("InitOutput - Returning.\n");
-#endif
-}
-
-
-/*
- * winCheckDisplayNumber - Check if another instance of Cygwin/X is
- * already running on the same display number.  If no one exists,
- * make a mutex to prevent new instances from running on the same display.
- *
- * return FALSE if the display number is already used.
- */
-
-static Bool
-winCheckDisplayNumber (void)
-{
-  int			nDisp;
-  HANDLE		mutex;
-  char			name[MAX_PATH];
-  char *		pszPrefix = '\0';
-  OSVERSIONINFO		osvi = {0};
-
-  /* Check display range */
-  nDisp = atoi (display);
-  if (nDisp < 0 || nDisp > 65535)
-    {
-      ErrorF ("winCheckDisplayNumber - Bad display number: %d\n", nDisp);
-      return FALSE;
-    }
-
-  /* Set first character of mutex name to null */
-  name[0] = '\0';
-
-  /* Get operating system version information */
-  osvi.dwOSVersionInfoSize = sizeof (osvi);
-  GetVersionEx (&osvi);
-
-  /* Want a mutex shared among all terminals on NT > 4.0 */
-  if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT
-      && osvi.dwMajorVersion >= 5)
-    {
-      pszPrefix = "Global\\";
-    }
-
-  /* Setup Cygwin/X specific part of name */
-  snprintf (name, sizeof(name), "%sCYGWINX_DISPLAY:%d", pszPrefix, nDisp);
-
-  /* Windows automatically releases the mutex when this process exits */
-  mutex = CreateMutex (NULL, FALSE, name);
-  if (!mutex)
-    {
-      LPVOID lpMsgBuf;
-
-      /* Display a fancy error message */
-      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
-		     FORMAT_MESSAGE_FROM_SYSTEM | 
-		     FORMAT_MESSAGE_IGNORE_INSERTS,
-		     NULL,
-		     GetLastError (),
-		     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-		     (LPTSTR) &lpMsgBuf,
-		     0, NULL);
-      ErrorF ("winCheckDisplayNumber - CreateMutex failed: %s\n",
-	      (LPSTR)lpMsgBuf);
-      LocalFree (lpMsgBuf);
-
-      return FALSE;
-    }
-  if (GetLastError () == ERROR_ALREADY_EXISTS)
-    {
-      ErrorF ("winCheckDisplayNumber - "
-	      PROJECT_NAME " is already running on display %d\n",
-	      nDisp);
-      return FALSE;
-    }
-
-  return TRUE;
-}
+
+/*
+
+Copyright 1993, 1998  The Open Group
+Copyright (C) Colin Harrison 2005-2008
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall
+not be used in advertising or otherwise to promote the sale, use or
+other dealings in this Software without prior written authorization
+from The Open Group.
+
+*/
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+#include "winconfig.h"
+#include "winprefs.h"
+#ifdef XWIN_CLIPBOARD
+#include "X11/Xlocale.h"
+#endif
+#ifdef DPMSExtension
+#include "dpmsproc.h"
+#endif
+#ifdef __CYGWIN__
+#include <mntent.h>
+#endif
+#if defined(WIN32)
+#include "xkbsrv.h"
+#endif
+#ifdef RELOCATE_PROJECTROOT
+#include <shlobj.h>
+typedef HRESULT (*SHGETFOLDERPATHPROC)(
+    HWND hwndOwner,
+    int nFolder,
+    HANDLE hToken,
+    DWORD dwFlags,
+    LPTSTR pszPath
+);
+#endif
+
+
+/*
+ * References to external symbols
+ */
+
+extern int			g_iNumScreens;
+extern winScreenInfo		g_ScreenInfo[];
+extern int			g_iLastScreen;
+extern char *			g_pszCommandLine;
+extern Bool			g_fSilentFatalError;
+
+extern char *			g_pszLogFile;
+extern Bool			g_fLogFileChanged;
+extern int			g_iLogVerbose;
+Bool				g_fLogInited;
+
+extern Bool			g_fXdmcpEnabled;
+extern Bool			g_fAuthEnabled;
+#ifdef HAS_DEVWINDOWS
+extern int			g_fdMessageQueue;
+#endif
+extern const char *		g_pszQueryHost;
+extern HINSTANCE		g_hInstance;
+
+#ifdef XWIN_CLIPBOARD
+extern Bool			g_fUnicodeClipboard;
+extern Bool			g_fClipboardLaunched;
+extern Bool			g_fClipboardStarted;
+extern pthread_t		g_ptClipboardProc;
+extern HWND			g_hwndClipboard;
+extern Bool			g_fClipboard;
+#endif
+
+extern HMODULE			g_hmodDirectDraw;
+extern FARPROC			g_fpDirectDrawCreate;
+extern FARPROC			g_fpDirectDrawCreateClipper;
+  
+extern HMODULE			g_hmodCommonControls;
+extern FARPROC			g_fpTrackMouseEvent;
+extern Bool			g_fNoHelpMessageBox;                     
+extern Bool			g_fSilentDupError;                     
+  
+  
+/*
+ * Function prototypes
+ */
+
+#ifdef XWIN_CLIPBOARD
+static void
+winClipboardShutdown (void);
+#endif
+
+#if defined(DDXOSVERRORF)
+void
+OsVendorVErrorF (const char *pszFormat, va_list va_args);
+#endif
+
+void
+winInitializeDefaultScreens (void);
+
+static Bool
+winCheckDisplayNumber (void);
+
+void
+winLogCommandLine (int argc, char *argv[]);
+
+void
+winLogVersionInfo (void);
+
+Bool
+winValidateArgs (void);
+
+#ifdef RELOCATE_PROJECTROOT
+const char *
+winGetBaseDir(void);
+#endif
+
+/*
+ * For the depth 24 pixmap we default to 32 bits per pixel, but
+ * we change this pixmap format later if we detect that the display
+ * is going to be running at 24 bits per pixel.
+ *
+ * FIXME: On second thought, don't DIBs only support 32 bits per pixel?
+ * DIBs are the underlying bitmap used for DirectDraw surfaces, so it
+ * seems that all pixmap formats with depth 24 would be 32 bits per pixel.
+ * Confirm whether depth 24 DIBs can have 24 bits per pixel, then remove/keep
+ * the bits per pixel adjustment and update this comment to reflect the
+ * situation.  Harold Hunt - 2002/07/02
+ */
+
+static PixmapFormatRec g_PixmapFormats[] = {
+  { 1,    1,      BITMAP_SCANLINE_PAD },
+  { 4,    8,      BITMAP_SCANLINE_PAD },
+  { 8,    8,      BITMAP_SCANLINE_PAD },
+  { 15,   16,     BITMAP_SCANLINE_PAD },
+  { 16,   16,     BITMAP_SCANLINE_PAD },
+  { 24,   32,     BITMAP_SCANLINE_PAD },
+#ifdef RENDER
+  { 32,   32,     BITMAP_SCANLINE_PAD }
+#endif
+};
+
+const int NUMFORMATS = sizeof (g_PixmapFormats) / sizeof (g_PixmapFormats[0]);
+
+#ifdef XWIN_CLIPBOARD
+static void
+winClipboardShutdown (void)
+{
+  /* Close down clipboard resources */
+  if (g_fClipboard && g_fClipboardLaunched && g_fClipboardStarted)
+    {
+      /* Synchronously destroy the clipboard window */
+      if (g_hwndClipboard != NULL)
+	{
+	  SendMessage (g_hwndClipboard, WM_DESTROY, 0, 0);
+	  /* NOTE: g_hwndClipboard is set to NULL in winclipboardthread.c */
+	}
+      else
+	return;
+      
+      /* Wait for the clipboard thread to exit */
+      pthread_join (g_ptClipboardProc, NULL);
+
+      g_fClipboardLaunched = FALSE;
+      g_fClipboardStarted = FALSE;
+
+      winDebug ("winClipboardShutdown - Clipboard thread has exited.\n");
+    }
+}
+#endif
+
+
+#if defined(DDXBEFORERESET)
+/*
+ * Called right before KillAllClients when the server is going to reset,
+ * allows us to shutdown our seperate threads cleanly.
+ */
+
+void
+ddxBeforeReset (void)
+{
+  winDebug ("ddxBeforeReset - Hello\n");
+
+#ifdef XWIN_CLIPBOARD
+  winClipboardShutdown ();
+#endif
+}
+#endif
+
+
+/* See Porting Layer Definition - p. 57 */
+void
+ddxGiveUp (void)
+{
+  int		i;
+
+#if CYGDEBUG
+  winDebug ("ddxGiveUp\n");
+#endif
+
+  /* Perform per-screen deinitialization */
+  for (i = 0; i < g_iNumScreens; ++i)
+    {
+      /* Delete the tray icon */
+      if (!g_ScreenInfo[i].fNoTrayIcon && g_ScreenInfo[i].pScreen)
+ 	winDeleteNotifyIcon (winGetScreenPriv (g_ScreenInfo[i].pScreen));
+    }
+
+#ifdef XWIN_MULTIWINDOW
+  /* Notify the worker threads we're exiting */
+  winDeinitMultiWindowWM ();
+#endif
+
+#ifdef HAS_DEVWINDOWS
+  /* Close our handle to our message queue */
+  if (g_fdMessageQueue != WIN_FD_INVALID)
+    {
+      /* Close /dev/windows */
+      close (g_fdMessageQueue);
+
+      /* Set the file handle to invalid */
+      g_fdMessageQueue = WIN_FD_INVALID;
+    }
+#endif
+
+  if (!g_fLogInited) {
+    LogInit (g_pszLogFile, NULL);
+    g_fLogInited = TRUE;
+  }  
+  LogClose ();
+
+  /*
+   * At this point we aren't creating any new screens, so
+   * we are guaranteed to not need the DirectDraw functions.
+   */
+  if (g_hmodDirectDraw != NULL)
+    {
+      FreeLibrary (g_hmodDirectDraw);
+      g_hmodDirectDraw = NULL;
+      g_fpDirectDrawCreate = NULL;
+      g_fpDirectDrawCreateClipper = NULL;
+    }
+
+  /* Unload our TrackMouseEvent funtion pointer */
+  if (g_hmodCommonControls != NULL)
+    {
+      FreeLibrary (g_hmodCommonControls);
+      g_hmodCommonControls = NULL;
+      g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
+    }
+  
+  /* Free concatenated command line */
+  if (g_pszCommandLine)
+    {
+      free (g_pszCommandLine);
+      g_pszCommandLine = NULL;
+    }
+
+  /* Remove our keyboard hook if it is installed */
+  winRemoveKeyboardHookLL ();
+
+  /* Tell Windows that we want to end the app */
+  PostQuitMessage (0);
+}
+
+
+/* See Porting Layer Definition - p. 57 */
+void
+AbortDDX (void)
+{
+#if CYGDEBUG
+  winDebug ("AbortDDX\n");
+#endif
+  ddxGiveUp ();
+}
+
+#ifdef __CYGWIN__
+/* hasmntopt is currently not implemented for cygwin */
+static const char *winCheckMntOpt(const struct mntent *mnt, const char *opt)
+{
+    const char *s;
+    size_t len;
+    if (mnt == NULL)
+        return NULL;
+    if (opt == NULL)
+        return NULL;
+    if (mnt->mnt_opts == NULL)
+        return NULL;
+
+    len = strlen(opt);
+    s = strstr(mnt->mnt_opts, opt);
+    if (s == NULL)
+        return NULL;
+    if ((s == mnt->mnt_opts || *(s-1) == ',') &&  (s[len] == 0 || s[len] == ','))
+        return (char *)opt;
+    return NULL;
+}
+
+static void
+winCheckMount(void)
+{
+  FILE *mnt;
+  struct mntent *ent;
+
+  enum { none = 0, sys_root, user_root, sys_tmp, user_tmp } 
+    level = none, curlevel;
+  BOOL binary = TRUE;
+
+  mnt = setmntent("/etc/mtab", "r");
+  if (mnt == NULL)
+  {
+    ErrorF("setmntent failed");
+    return;
+  }
+
+  while ((ent = getmntent(mnt)) != NULL)
+  {
+    BOOL system = (winCheckMntOpt(ent, "user") != NULL);
+    BOOL root = (strcmp(ent->mnt_dir, "/") == 0);
+    BOOL tmp = (strcmp(ent->mnt_dir, "/tmp") == 0);
+    
+    if (system)
+    {
+      if (root)
+        curlevel = sys_root;
+      else if (tmp)
+        curlevel = sys_tmp;
+      else
+        continue;
+    }
+    else
+    {
+      if (root)
+        curlevel = user_root;
+      else if (tmp) 
+        curlevel = user_tmp;
+      else
+        continue;
+    }
+
+    if (curlevel <= level)
+      continue;
+    level = curlevel;
+
+    if ((winCheckMntOpt(ent, "binary") == NULL) &&
+        (winCheckMntOpt(ent, "binmode") == NULL))
+      binary = FALSE;
+    else
+      binary = TRUE;
+  }
+    
+  if (endmntent(mnt) != 1)
+  {
+    ErrorF("endmntent failed");
+    return;
+  }
+  
+ if (!binary) 
+   winMsg(X_WARNING, "/tmp mounted in textmode\n");
+}
+#else
+static void
+winCheckMount(void) 
+{
+}
+#endif
+
+#ifdef RELOCATE_PROJECTROOT
+const char * 
+winGetBaseDir(void)
+{
+    static BOOL inited = FALSE;
+    static char buffer[MAX_PATH];
+    if (!inited)
+    {
+        char *fendptr;
+        HMODULE module = GetModuleHandle(NULL);
+        DWORD size = GetModuleFileName(module, buffer, sizeof(buffer));
+        if (sizeof(buffer) > 0)
+            buffer[sizeof(buffer)-1] = 0;
+    
+        fendptr = buffer + size;
+        while (fendptr > buffer)
+        {
+            if (*fendptr == '\\' || *fendptr == '/')
+            {
+                *fendptr = 0;
+                break;
+            }
+            fendptr--;
+        }
+        inited = TRUE;
+    }
+    return buffer;
+}
+#endif
+
+static void
+winFixupPaths (void)
+{
+    BOOL changed_fontpath = FALSE;
+    MessageType font_from = X_DEFAULT;
+#ifdef RELOCATE_PROJECTROOT
+    const char *basedir = winGetBaseDir();
+    size_t basedirlen = strlen(basedir);
+#endif
+
+#ifdef READ_FONTDIRS
+    {
+        /* Open fontpath configuration file */
+        FILE *fontdirs = fopen(ETCX11DIR "/font-dirs", "rt");
+        if (fontdirs != NULL)
+        {
+            char buffer[256];
+            int needs_sep = TRUE; 
+            int comment_block = FALSE;
+
+            /* get defautl fontpath */
+            char *fontpath = xstrdup(defaultFontPath);
+            size_t size = strlen(fontpath);
+
+            /* read all lines */
+            while (!feof(fontdirs))
+            {
+                size_t blen;
+                char *hashchar;
+                char *str;
+                int has_eol = FALSE;
+
+                /* read one line */
+                str = fgets(buffer, sizeof(buffer), fontdirs);
+                if (str == NULL) /* stop on error or eof */
+                    break;
+
+                if (strchr(str, '\n') != NULL)
+                    has_eol = TRUE;
+
+                /* check if block is continued comment */
+                if (comment_block)
+                {
+                    /* ignore all input */
+                    *str = 0; 
+                    blen = 0; 
+                    if (has_eol) /* check if line ended in this block */
+                        comment_block = FALSE;
+                }
+                else 
+                {
+                    /* find comment character. ignore all trailing input */
+                    hashchar = strchr(str, '#');
+                    if (hashchar != NULL)
+                    {
+                        *hashchar = 0;
+                        if (!has_eol) /* mark next block as continued comment */
+                            comment_block = TRUE;
+                    }
+                }
+
+                /* strip whitespaces from beginning */
+                while (*str == ' ' || *str == '\t')
+                    str++;
+
+                /* get size, strip whitespaces from end */ 
+                blen = strlen(str);
+                while (blen > 0 && (str[blen-1] == ' ' || 
+                            str[blen-1] == '\t' || str[blen-1] == '\n'))
+                {
+                    str[--blen] = 0;
+                }
+
+                /* still something left to add? */ 
+                if (blen > 0)
+                {
+                    size_t newsize = size + blen;
+                    /* reserve one character more for ',' */
+                    if (needs_sep)
+                        newsize++;
+
+                    /* allocate memory */
+                    if (fontpath == NULL)
+                        fontpath = malloc(newsize+1);
+                    else
+                        fontpath = realloc(fontpath, newsize+1);
+
+                    /* add separator */
+                    if (needs_sep)
+                    {
+                        fontpath[size] = ',';
+                        size++;
+                        needs_sep = FALSE;
+                    }
+
+                    /* mark next line as new entry */
+                    if (has_eol)
+                        needs_sep = TRUE;
+
+                    /* add block */
+                    strncpy(fontpath + size, str, blen);
+                    fontpath[newsize] = 0;
+                    size = newsize;
+                }
+            }
+
+            /* cleanup */
+            fclose(fontdirs);  
+            defaultFontPath = xstrdup(fontpath);
+            free(fontpath);
+            changed_fontpath = TRUE;
+            font_from = X_CONFIG;
+        }
+    }
+#endif /* READ_FONTDIRS */
+#ifdef RELOCATE_PROJECTROOT
+    {
+        const char *libx11dir = PROJECTROOT "/lib/X11";
+        size_t libx11dir_len = strlen(libx11dir);
+        char *newfp = NULL;
+        size_t newfp_len = 0;
+        const char *endptr, *ptr, *oldptr = defaultFontPath;
+
+        endptr = oldptr + strlen(oldptr);
+        ptr = strchr(oldptr, ',');
+        if (ptr == NULL)
+            ptr = endptr;
+        while (ptr != NULL)
+        {
+            size_t oldfp_len = (ptr - oldptr);
+            size_t newsize = oldfp_len;
+            char *newpath = malloc(newsize + 1);
+            strncpy(newpath, oldptr, newsize);
+            newpath[newsize] = 0;
+
+
+            if (strncmp(libx11dir, newpath, libx11dir_len) == 0)
+            {
+                char *compose;
+                newsize = newsize - libx11dir_len + basedirlen;
+                compose = malloc(newsize + 1);  
+                strcpy(compose, basedir);
+                strncat(compose, newpath + libx11dir_len, newsize - basedirlen);
+                compose[newsize] = 0;
+                free(newpath);
+                newpath = compose;
+            }
+
+            oldfp_len = newfp_len;
+            if (oldfp_len > 0)
+                newfp_len ++; /* space for separator */
+            newfp_len += newsize;
+
+            if (newfp == NULL)
+                newfp = malloc(newfp_len + 1);
+            else
+                newfp = realloc(newfp, newfp_len + 1);
+
+            if (oldfp_len > 0)
+            {
+                strcpy(newfp + oldfp_len, ",");
+                oldfp_len++;
+            }
+            strcpy(newfp + oldfp_len, newpath);
+
+            free(newpath);
+
+            if (*ptr == 0)
+            {
+                oldptr = ptr;
+                ptr = NULL;
+            } else
+            {
+                oldptr = ptr + 1;
+                ptr = strchr(oldptr, ',');
+                if (ptr == NULL)
+                    ptr = endptr;
+            }
+        } 
+
+        defaultFontPath = xstrdup(newfp);
+        free(newfp);
+        changed_fontpath = TRUE;
+    }
+#endif /* RELOCATE_PROJECTROOT */
+    if (changed_fontpath)
+        winMsg (font_from, "FontPath set to \"%s\"\n", defaultFontPath);
+
+#ifdef RELOCATE_PROJECTROOT
+    if (getenv("XKEYSYMDB") == NULL)
+    {
+        char buffer[MAX_PATH];
+        snprintf(buffer, sizeof(buffer), "XKEYSYMDB=%s\\XKeysymDB",
+                basedir);
+        buffer[sizeof(buffer)-1] = 0;
+        putenv(buffer);
+    }
+    if (getenv("XERRORDB") == NULL)
+    {
+        char buffer[MAX_PATH];
+        snprintf(buffer, sizeof(buffer), "XERRORDB=%s\\XErrorDB",
+                basedir);
+        buffer[sizeof(buffer)-1] = 0;
+        putenv(buffer);
+    }
+    if (getenv("XLOCALEDIR") == NULL)
+    {
+        char buffer[MAX_PATH];
+        snprintf(buffer, sizeof(buffer), "XLOCALEDIR=%s\\locale",
+                basedir);
+        buffer[sizeof(buffer)-1] = 0;
+        putenv(buffer);
+    }
+    if (getenv("HOME") == NULL)
+    {
+        HMODULE shfolder;
+        SHGETFOLDERPATHPROC shgetfolderpath = NULL;
+        char buffer[MAX_PATH + 5];
+        strncpy(buffer, "HOME=", 5);
+
+        /* Try to load SHGetFolderPath from shfolder.dll and shell32.dll */
+        
+        shfolder = LoadLibrary("shfolder.dll");
+        /* fallback to shell32.dll */
+        if (shfolder == NULL)
+            shfolder = LoadLibrary("shell32.dll");
+
+        /* resolve SHGetFolderPath */
+        if (shfolder != NULL)
+            shgetfolderpath = (SHGETFOLDERPATHPROC)GetProcAddress(shfolder, "SHGetFolderPathA");
+
+        /* query appdata directory */
+        if (shgetfolderpath &&
+                shgetfolderpath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, 
+                    buffer + 5) == 0)
+        { 
+            putenv(buffer);
+        } else
+        {
+            winMsg (X_ERROR, "Can not determine HOME directory\n");
+        } 
+        if (shfolder != NULL)
+            FreeLibrary(shfolder);
+    }
+    if (!g_fLogFileChanged) {
+        static char buffer[MAX_PATH];
+        DWORD size = GetTempPath(sizeof(buffer), buffer);
+        if (size && size < sizeof(buffer))
+        {
+            snprintf(buffer + size, sizeof(buffer) - size, 
+                    "XWin.%s.log", display); 
+            buffer[sizeof(buffer)-1] = 0;
+            g_pszLogFile = buffer;
+            winMsg (X_DEFAULT, "Logfile set to \"%s\"\n", g_pszLogFile);
+        }
+    }
+    {
+        static char xkbbasedir[MAX_PATH];
+
+        snprintf(xkbbasedir, sizeof(xkbbasedir), "%s\\xkb", basedir);
+        if (sizeof(xkbbasedir) > 0)
+            xkbbasedir[sizeof(xkbbasedir)-1] = 0;
+        XkbBaseDirectory = xkbbasedir;
+	XkbBinDirectory = basedir;
+    }
+#endif /* RELOCATE_PROJECTROOT */
+}
+
+void
+OsVendorInit (void)
+{
+  /* Re-initialize global variables on server reset */
+  winInitializeGlobals ();
+
+  LogInit (NULL, NULL);
+  LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose);
+
+  winFixupPaths();
+
+#ifdef DDXOSVERRORF
+  if (!OsVendorVErrorFProc)
+    OsVendorVErrorFProc = OsVendorVErrorF;
+#endif
+
+  if (!g_fLogInited) {
+    /* keep this order. If LogInit fails it calls Abort which then calls
+     * ddxGiveUp where LogInit is called again and creates an infinite 
+     * recursion. If we set g_fLogInited to TRUE before the init we 
+     * avoid the second call 
+     */  
+    g_fLogInited = TRUE;
+    LogInit (g_pszLogFile, NULL);
+  } 
+  LogSetParameter (XLOG_FLUSH, 1);
+  LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose);
+  LogSetParameter (XLOG_FILE_VERBOSITY, g_iLogVerbose);
+
+  /* Log the version information */
+  if (serverGeneration == 1)
+    winLogVersionInfo ();
+
+  winCheckMount();  
+
+  /* Add a default screen if no screens were specified */
+  if (g_iNumScreens == 0)
+    {
+      winDebug ("OsVendorInit - Creating bogus screen 0\n");
+
+      /* 
+       * We need to initialize default screens if no arguments
+       * were processed.  Otherwise, the default screens would
+       * already have been initialized by ddxProcessArgument ().
+       */
+      winInitializeDefaultScreens ();
+
+      /*
+       * Add a screen 0 using the defaults set by 
+       * winInitializeDefaultScreens () and any additional parameters
+       * processed by ddxProcessArgument ().
+       */
+      g_iNumScreens = 1;
+      g_iLastScreen = 0;
+
+      /* We have to flag this as an explicit screen, even though it isn't */
+      g_ScreenInfo[0].fExplicitScreen = TRUE;
+    }
+}
+
+
+static void
+winUseMsg (void)
+{
+  ErrorF("\n");
+  ErrorF("\n");
+  ErrorF(EXECUTABLE_NAME " Device Dependent Usage:\n");
+  ErrorF("\n");
+
+#ifdef XWIN_CLIPBOARD
+  ErrorF ("-[no]clipboard\n"
+	  "\tEnable [disable] the clipboard integration. Default is enabled.\n");
+#endif
+
+  ErrorF ("-clipupdates num_boxes\n"
+	  "\tUse a clipping region to constrain shadow update blits to\n"
+	  "\tthe updated region when num_boxes, or more, are in the\n"
+	  "\tupdated region.\n");
+
+#ifdef XWIN_XF86CONFIG
+  ErrorF ("-config\n"
+          "\tSpecify a configuration file.\n");
+
+  ErrorF ("-configdir\n"
+          "\tSpecify a configuration directory.\n");
+#endif
+
+  ErrorF ("-depth bits_per_pixel\n"
+	  "\tSpecify an optional bitdepth to use in fullscreen mode\n"
+	  "\twith a DirectDraw engine.\n");
+
+  ErrorF ("-emulate3buttons [timeout]\n"
+	  "\tEmulate 3 button mouse with an optional timeout in\n"
+	  "\tmilliseconds.\n");
+
+#ifdef XWIN_EMULATEPSEUDO
+  ErrorF ("-emulatepseudo\n"
+	  "\tCreate a depth 8 PseudoColor visual when running in\n"
+	  "\tdepths 15, 16, 24, or 32, collectively known as TrueColor\n"
+	  "\tdepths.  The PseudoColor visual does not have correct colors,\n"
+	  "\tand it may crash, but it at least allows you to run your\n"
+	  "\tapplication in TrueColor modes.\n");
+#endif
+
+  ErrorF ("-engine engine_type_id\n"
+	  "\tOverride the server's automatically selected engine type:\n"
+	  "\t\t1 - Shadow GDI\n"
+	  "\t\t2 - Shadow DirectDraw\n"
+	  "\t\t4 - Shadow DirectDraw4 Non-Locking\n"
+#ifdef XWIN_NATIVEGDI
+	  "\t\t16 - Native GDI - experimental\n"
+#endif
+	  );
+
+  ErrorF ("-fullscreen\n"
+	  "\tRun the server in fullscreen mode.\n");
+
+  ErrorF ("-ignoreinput\n"
+	  "\tIgnore keyboard and mouse input.\n");
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  ErrorF ("-internalwm\n"
+	  "\tRun the internal window manager.\n");
+#endif
+
+#ifdef XWIN_XF86CONFIG
+  ErrorF ("-keyboard\n"
+	  "\tSpecify a keyboard device from the configuration file.\n");
+#endif
+
+  ErrorF ("-[no]keyhook\n"
+	  "\tGrab special Windows keypresses like Alt-Tab or the Menu "
+          "key.\n");
+
+  ErrorF ("-lesspointer\n"
+	  "\tHide the windows mouse pointer when it is over any\n"
+          "\t" EXECUTABLE_NAME " window.  This prevents ghost cursors appearing when\n"
+	  "\tthe Windows cursor is drawn on top of the X cursor\n");
+
+  ErrorF ("-logfile filename\n"
+	  "\tWrite log messages to <filename>.\n");
+
+  ErrorF ("-logverbose verbosity\n"
+	  "\tSet the verbosity of log messages. [NOTE: Only a few messages\n"
+	  "\trespect the settings yet]\n"
+	  "\t\t0 - only print fatal error.\n"
+	  "\t\t1 - print additional configuration information.\n"
+	  "\t\t2 - print additional runtime information [default].\n"
+	  "\t\t3 - print debugging and tracing information.\n");
+
+  ErrorF ("-[no]multimonitors or -[no]multiplemonitors\n"
+	  "\tUse the entire virtual screen if multiple\n"
+	  "\tmonitors are present.\n");
+
+#ifdef XWIN_MULTIWINDOW
+  ErrorF ("-multiwindow\n"
+	  "\tRun the server in multi-window mode.\n");
+#endif
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  ErrorF ("-mwextwm\n"
+	  "\tRun the server in multi-window external window manager mode.\n");
+#endif
+
+  ErrorF ("-nodecoration\n"
+          "\tDo not draw a window border, title bar, etc.  Windowed\n"
+	  "\tmode only.\n");
+
+#ifdef XWIN_CLIPBOARD
+  ErrorF ("-nounicodeclipboard\n"
+	  "\tDo not use Unicode clipboard even if on a NT-based platform.\n");
+#endif
+
+  ErrorF ("-refresh rate_in_Hz\n"
+	  "\tSpecify an optional refresh rate to use in fullscreen mode\n"
+	  "\twith a DirectDraw engine.\n");
+
+  ErrorF ("-rootless\n"
+	  "\tRun the server in rootless mode.\n");
+
+  ErrorF ("-screen scr_num [width height [x y] | [[WxH[+X+Y]][@m]] ]\n"
+	  "\tEnable screen scr_num and optionally specify a width and\n"
+	  "\theight and initial position for that screen. Additionally\n"
+	  "\ta monitor number can be specified to start the server on,\n"
+	  "\tat which point, all coordinates become relative to that\n"
+      "\tmonitor (Not for Windows NT4 and 95). Examples:\n"
+      "\t -screen 0 800x600+100+100@2 ; 2nd monitor offset 100,100 size 800x600\n"
+      "\t -screen 0 1024x768@3        ; 3rd monitor size 1024x768\n"
+      "\t -screen 0 @1 ; on 1st monitor using its full resolution (the default)\n");
+
+  ErrorF ("-scrollbars\n"
+	  "\tIn windowed mode, allow screens bigger than the Windows desktop.\n"
+	  "\tMoreover, if the window has decorations, one can now resize\n"
+	  "\tit.\n");
+
+  ErrorF ("-silent-dup-error\n"
+	  "\tIf another instance of " EXECUTABLE_NAME " with the same display number is running\n"
+     "\texit silently and don’t display any error message.\n");
+
+  ErrorF ("-swcursor\n"
+	  "\tDisable the usage of the Windows cursor and use the X11 software\n"
+	  "\tcursor instead.\n");
+
+  ErrorF ("-[no]trayicon\n"
+          "\tDo not create a tray icon.  Default is to create one\n"
+	  "\ticon per screen.  You can globally disable tray icons with\n"
+	  "\t-notrayicon, then enable it for specific screens with\n"
+	  "\t-trayicon for those screens.\n");
+
+  ErrorF ("-[no]unixkill\n"
+          "\tCtrl+Alt+Backspace exits the X Server.\n");
+
+  ErrorF ("-[no]winkill\n"
+          "\tAlt+F4 exits the X Server.\n");
+
+  ErrorF ("-xkblayout XKBLayout\n"
+	  "\tEquivalent to XKBLayout in XF86Config files.\n"
+	  "\tFor example: -xkblayout de\n");
+
+  ErrorF ("-xkbmodel XKBModel\n"
+	  "\tEquivalent to XKBModel in XF86Config files.\n");
+
+  ErrorF ("-xkboptions XKBOptions\n"
+	  "\tEquivalent to XKBOptions in XF86Config files.\n");
+
+  ErrorF ("-xkbrules XKBRules\n"
+	  "\tEquivalent to XKBRules in XF86Config files.\n");
+
+  ErrorF ("-xkbvariant XKBVariant\n"
+	  "\tEquivalent to XKBVariant in XF86Config files.\n"
+	  "\tFor example: -xkbvariant nodeadkeys\n");
+}
+
+/* See Porting Layer Definition - p. 57 */
+void
+ddxUseMsg(void)
+{
+  /* Set a flag so that FatalError won't give duplicate warning message */
+  g_fSilentFatalError = TRUE;
+  
+  winUseMsg();  
+
+  /* Log file will not be opened for UseMsg unless we open it now */
+  if (!g_fLogInited) {
+    LogInit (g_pszLogFile, NULL);
+    g_fLogInited = TRUE;
+  }  
+  LogClose ();
+
+  /* Notify user where UseMsg text can be found.*/
+  if (!g_fNoHelpMessageBox)
+    winMessageBoxF ("The " PROJECT_NAME " help text has been printed to "
+		  "/tmp/XWin.log.\n"
+		  "Please open /tmp/XWin.log to read the help text.\n",
+		  MB_ICONINFORMATION);
+}
+
+/* See Porting Layer Definition - p. 20 */
+/*
+ * Do any global initialization, then initialize each screen.
+ * 
+ * NOTE: We use ddxProcessArgument, so we don't need to touch argc and argv
+ */
+
+void
+InitOutput (ScreenInfo *screenInfo, int argc, char *argv[])
+{
+  int		i;
+
+  /* Log the command line */
+  winLogCommandLine (argc, argv);
+
+#if CYGDEBUG
+  winDebug ("InitOutput\n");
+#endif
+
+  /* Validate command-line arguments */
+  if (serverGeneration == 1 && !winValidateArgs ())
+    {
+      FatalError ("InitOutput - Invalid command-line arguments found.  "
+		  "Exiting.\n");
+    }
+
+  /* Check for duplicate invocation on same display number.*/
+  if (serverGeneration == 1 && !winCheckDisplayNumber ())
+    {
+      if (g_fSilentDupError)
+        g_fSilentFatalError = TRUE;  
+      FatalError ("InitOutput - Duplicate invocation on display "
+		  "number: %s.  Exiting.\n", display);
+    }
+
+#ifdef XWIN_XF86CONFIG
+  /* Try to read the xorg.conf-style configuration file */
+  if (!winReadConfigfile ())
+    winErrorFVerb (1, "InitOutput - Error reading config file\n");
+#else
+  winMsg(X_INFO, "xorg.conf is not supported\n");
+  winMsg(X_INFO, "See http://x.cygwin.com/docs/faq/cygwin-x-faq.html "
+         "for more information\n");
+  winConfigFiles ();
+#endif
+
+  /* Load preferences from XWinrc file */
+  LoadPreferences();
+
+  /* Setup global screen info parameters */
+  screenInfo->imageByteOrder = IMAGE_BYTE_ORDER;
+  screenInfo->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
+  screenInfo->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
+  screenInfo->bitmapBitOrder = BITMAP_BIT_ORDER;
+  screenInfo->numPixmapFormats = NUMFORMATS;
+  
+  /* Describe how we want common pixmap formats padded */
+  for (i = 0; i < NUMFORMATS; i++)
+    {
+      screenInfo->formats[i] = g_PixmapFormats[i];
+    }
+
+  /* Load pointers to DirectDraw functions */
+  winGetDDProcAddresses ();
+  
+  /* Detect supported engines */
+  winDetectSupportedEngines ();
+
+  /* Load common controls library */
+  g_hmodCommonControls = LoadLibraryEx ("comctl32.dll", NULL, 0);
+
+  /* Load TrackMouseEvent function pointer */  
+  g_fpTrackMouseEvent = GetProcAddress (g_hmodCommonControls,
+					 "_TrackMouseEvent");
+  if (g_fpTrackMouseEvent == NULL)
+    {
+      winErrorFVerb (1, "InitOutput - Could not get pointer to function\n"
+	      "\t_TrackMouseEvent in comctl32.dll.  Try installing\n"
+	      "\tInternet Explorer 3.0 or greater if you have not\n"
+	      "\talready.\n");
+
+      /* Free the library since we won't need it */
+      FreeLibrary (g_hmodCommonControls);
+      g_hmodCommonControls = NULL;
+
+      /* Set function pointer to point to no operation function */
+      g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
+    }
+
+  /* Store the instance handle */
+  g_hInstance = GetModuleHandle (NULL);
+
+  /* Initialize each screen */
+  for (i = 0; i < g_iNumScreens; ++i)
+    {
+      /* Initialize the screen */
+      if (-1 == AddScreen (winScreenInit, argc, argv))
+	{
+	  FatalError ("InitOutput - Couldn't add screen %d", i);
+	}
+    }
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+
+  /* Generate a cookie used by internal clients for authorization */
+  if (g_fXdmcpEnabled || g_fAuthEnabled)
+    winGenerateAuthorization ();
+
+  /* Perform some one time initialization */
+  if (1 == serverGeneration)
+    {
+      /*
+       * setlocale applies to all threads in the current process.
+       * Apply locale specified in LANG environment variable.
+       */
+      setlocale (LC_ALL, "");
+    }
+#endif
+
+#if CYGDEBUG || YES
+  winDebug ("InitOutput - Returning.\n");
+#endif
+}
+
+
+/*
+ * winCheckDisplayNumber - Check if another instance of Cygwin/X is
+ * already running on the same display number.  If no one exists,
+ * make a mutex to prevent new instances from running on the same display.
+ *
+ * return FALSE if the display number is already used.
+ */
+
+static Bool
+winCheckDisplayNumber (void)
+{
+  int			nDisp;
+  HANDLE		mutex;
+  char			name[MAX_PATH];
+  char *		pszPrefix = '\0';
+  OSVERSIONINFO		osvi = {0};
+
+  /* Check display range */
+  nDisp = atoi (display);
+  if (nDisp < 0 || nDisp > 65535)
+    {
+      ErrorF ("winCheckDisplayNumber - Bad display number: %d\n", nDisp);
+      return FALSE;
+    }
+
+  /* Set first character of mutex name to null */
+  name[0] = '\0';
+
+  /* Get operating system version information */
+  osvi.dwOSVersionInfoSize = sizeof (osvi);
+  GetVersionEx (&osvi);
+
+  /* Want a mutex shared among all terminals on NT > 4.0 */
+  if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT
+      && osvi.dwMajorVersion >= 5)
+    {
+      pszPrefix = "Global\\";
+    }
+
+  /* Setup Cygwin/X specific part of name */
+  snprintf (name, sizeof(name), "%sCYGWINX_DISPLAY:%d", pszPrefix, nDisp);
+
+  /* Windows automatically releases the mutex when this process exits */
+  mutex = CreateMutex (NULL, FALSE, name);
+  if (!mutex)
+    {
+      LPVOID lpMsgBuf;
+
+      /* Display a fancy error message */
+      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+		     FORMAT_MESSAGE_FROM_SYSTEM | 
+		     FORMAT_MESSAGE_IGNORE_INSERTS,
+		     NULL,
+		     GetLastError (),
+		     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+		     (LPTSTR) &lpMsgBuf,
+		     0, NULL);
+      ErrorF ("winCheckDisplayNumber - CreateMutex failed: %s\n",
+	      (LPSTR)lpMsgBuf);
+      LocalFree (lpMsgBuf);
+
+      return FALSE;
+    }
+  if (GetLastError () == ERROR_ALREADY_EXISTS)
+    {
+      ErrorF ("winCheckDisplayNumber - "
+	      PROJECT_NAME " is already running on display %d\n",
+	      nDisp);
+      return FALSE;
+    }
+
+  return TRUE;
+}
diff --git a/xorg-server/hw/xwin/Makefile.am b/xorg-server/hw/xwin/Makefile.am
index 8b1897235..f9aa7c507 100644
--- a/xorg-server/hw/xwin/Makefile.am
+++ b/xorg-server/hw/xwin/Makefile.am
@@ -1,225 +1,224 @@
-bin_PROGRAMS = XWin
-
-if XWIN_CLIPBOARD
-SRCS_CLIPBOARD = \
-	winclipboardinit.c \
-	winclipboardtextconv.c \
-	winclipboardthread.c \
-	winclipboardunicode.c \
-	winclipboardwndproc.c \
-	winclipboardwrappers.c \
-	winclipboardxevents.c
-DEFS_CLIPBOARD = -DXWIN_CLIPBOARD
-endif
-
-if XWIN_GLX_WINDOWS
-SRCS_GLX_WINDOWS = \
-	winpriv.c
-DEFS_GLX_WINDOWS = -DXWIN_GLX_WINDOWS
-endif
-
-if XWIN_MULTIWINDOW
-SRCS_MULTIWINDOW = \
-	winmultiwindowshape.c \
-	winmultiwindowwindow.c \
-	winmultiwindowwm.c \
-	winmultiwindowwndproc.c
-DEFS_MULTIWINDOW = -DXWIN_MULTIWINDOW
-endif
-
-if XWIN_MULTIWINDOWEXTWM
-SRCS_MULTIWINDOWEXTWM = \
-	winwin32rootless.c \
-	winwin32rootlesswindow.c \
-	winwin32rootlesswndproc.c \
-	winwindowswm.c
-DEFS_MULTIWINDOWEXTWM = -DXWIN_MULTIWINDOWEXTWM
-MULTIWINDOWEXTWM_LIBS = $(top_builddir)/miext/rootless/librootless.la
-endif
-
-if XWIN_NATIVEGDI
-SRCS_NATIVEGDI = \
-	winclip.c \
-	winfillsp.c \
-	winfont.c \
-	wingc.c \
-	wingetsp.c \
-	winnativegdi.c \
-	winpixmap.c \
-	winpolyline.c \
-	winrop.c \
-	winsetsp.c
-DEFS_NATIVEGDI = -DXWIN_NATIVEGDI
-endif
-
-if XWIN_PRIMARYFB
-SRCS_PRIMARYFB = \
-	winpfbdd.c
-DEFS_PRIMARYFB = -DXWIN_PRIMARYFB
-endif
-
-if XWIN_RANDR
-SRCS_RANDR = \
-	winrandr.c
-DEFS_RANDR = -DXWIN_RANDR
-endif
-
-if XWIN_XV
-SRCS_XV = \
-	winvideo.c
-DEFS_XV = -DXWIN_XV
-endif
-
-SRCS =	InitInput.c \
-	InitOutput.c \
-	winallpriv.c \
-	winauth.c \
-	winblock.c \
-	wincmap.c \
-	winconfig.c \
-	wincreatewnd.c \
-	wincursor.c \
-	windialogs.c \
-	winengine.c \
-	winerror.c \
-	winglobals.c \
-	winkeybd.c \
-	winkeyhook.c \
-	winmisc.c \
-	winmouse.c \
-	winmsg.c \
-	winmultiwindowclass.c \
-	winmultiwindowicons.c \
-	winprefs.c \
-	winprefsyacc.y \
-	winprefslex.l \
-	winprocarg.c \
-	winregistry.c \
-	winscrinit.c \
-	winshaddd.c \
-	winshadddnl.c \
-	winshadgdi.c \
-	wintrayicon.c \
-	winvalargs.c \
-	winwakeup.c \
-	winwindow.c \
-	winwndproc.c \
-	ddraw.h \
-	winclipboard.h \
-	winconfig.h \
-	win.h \
-	winkeybd.h \
-	winkeymap.h \
-	winkeynames.h \
-	winlayouts.h \
-	winmessages.h \
-	winmsg.h \
-	winms.h \
-	winmultiwindowclass.h \
-	winprefs.h \
-	winpriv.h \
-	winresource.h \
-	winwindow.h \
-	XWin.rc \
-	$(top_srcdir)/Xext/dpmsstubs.c \
-	$(top_srcdir)/Xi/stubs.c \
-	$(top_srcdir)/mi/miinitext.c \
-	$(top_srcdir)/fb/fbcmap_mi.c \
-	$(SRCS_CLIPBOARD) \
-	$(SRCS_GLX_WINDOWS) \
-	$(SRCS_MULTIWINDOW) \
-	$(SRCS_MULTIWINDOWEXTWM) \
-	$(SRCS_NATIVEGDI) \
-	$(SRCS_PRIMARYFB) \
-	$(SRCS_RANDR) \
-	$(SRCS_XV)
-
- DEFS = $(DEFS_CLIPBOARD) \
-	$(DEFS_GLX_WINDOWS) \
-	$(DEFS_MULTIWINDOW) \
-	$(DEFS_MULTIWINDOWEXTWM) \
-	$(DEFS_NATIVEGDI) \
-	$(DEFS_PRIMARYFB) \
-	$(DEFS_RANDR) \
-	$(DEFS_XV)
-
-XWin_SOURCES = $(SRCS)
-
-INCLUDES = -I$(top_srcdir)/miext/rootless
-
-XWin_DEPENDENCIES = $(XWIN_LIBS)
-XWin_LDADD = $(MULTIWINDOWEXTWM_LIBS) $(XWIN_LIBS) $(MAIN_LIB) $(XSERVER_LIBS) $(XSERVER_SYS_LIBS) $(XWIN_SYS_LIBS)
-
-.rc.o:
-	$(WINDRES) --use-temp-file -i $< --input-format=rc -o $@ -O coff -I $(top_builddir)/include
-
-XWin_LDFLAGS = -mwindows -static
-
-winprefsyacc.h: winprefsyacc.c
-winprefslex.c: winprefslex.l winprefsyacc.c winprefsyacc.h
-
-BUILT_SOURCES = winprefsyacc.h winprefsyacc.c winprefslex.c
-CLEANFILES = $(BUILT_SOURCES) $(appman_DATA) $(fileman_DATA) XWin.man XWinrc.man
-
-AM_YFLAGS = -d
-AM_LFLAGS = -i
-AM_CFLAGS = -DHAVE_XWIN_CONFIG_H $(DIX_CFLAGS) \
-            $(XWINMODULES_CFLAGS) \
-            -DXFree86Server
-
-GLX_EXTRAS = \
-	glx/glwindows.h \
-	glx/glwrap.c \
-	glx/indirect.c
-
-MAN_SRCS = XWin.man.pre XWinrc.man.pre
-
-appmandir = $(APP_MAN_DIR)
-appman_DATA = XWin.$(APP_MAN_SUFFIX)
-
-filemandir = $(FILE_MAN_DIR)
-fileman_DATA = XWinrc.$(FILE_MAN_SUFFIX)
-
-XWin.$(APP_MAN_SUFFIX): XWin.man
-	-rm -f XWin.$(APP_MAN_SUFFIX)
-	$(LN_S) XWin.man XWin.$(APP_MAN_SUFFIX)
-
-XWinrc.$(FILE_MAN_SUFFIX): XWinrc.man
-	-rm -f XWinrc.$(FILE_MAN_SUFFIX)
-	$(LN_S) XWinrc.man XWinrc.$(FILE_MAN_SUFFIX)
-
-EXTRAMANDEFS = -D__logdir__=$(logdir) -D__sysconfdir__=$(sysconfdir) -D__datadir__=$(datadir)
-
-xwinconfigdir = $(sysconfdir)/X11
-xwinconfig_DATA = system.XWinrc
-
-include $(top_srcdir)/cpprules.in
-
-EXTRA_DIST = \
-	$(GLX_EXTRAS) \
-	$(MAN_SRCS) \
-	X.ico \
-	XWin.rc \
-	xlaunch/config.cc \
-	xlaunch/COPYING \
-	xlaunch/main.cc \
-	xlaunch/resources/dialog.rc \
-	xlaunch/resources/fullscreen.bmp \
-	xlaunch/resources/images.rc \
-	xlaunch/resources/multiwindow.bmp \
-	xlaunch/resources/nodecoration.bmp \
-	xlaunch/resources/resources.h \
-	xlaunch/resources/resources.rc \
-	xlaunch/resources/strings.rc \
-	xlaunch/resources/windowed.bmp \
-	xlaunch/window/dialog.cc \
-	xlaunch/window/dialog.h \
-	xlaunch/window/util.cc \
-	xlaunch/window/util.h \
-	xlaunch/window/window.cc \
-	xlaunch/window/window.h \
-	xlaunch/window/wizard.cc \
-	xlaunch/window/wizard.h
-
-relink:
-	rm -f XWin$(EXEEXT) && $(MAKE) XWin$(EXEEXT)
+bin_PROGRAMS = XWin
+
+if XWIN_CLIPBOARD
+SRCS_CLIPBOARD = \
+	winclipboardinit.c \
+	winclipboardtextconv.c \
+	winclipboardthread.c \
+	winclipboardunicode.c \
+	winclipboardwndproc.c \
+	winclipboardwrappers.c \
+	winclipboardxevents.c
+DEFS_CLIPBOARD = -DXWIN_CLIPBOARD
+endif
+
+if XWIN_GLX_WINDOWS
+SRCS_GLX_WINDOWS = \
+	winpriv.c
+DEFS_GLX_WINDOWS = -DXWIN_GLX_WINDOWS
+endif
+
+if XWIN_MULTIWINDOW
+SRCS_MULTIWINDOW = \
+	winmultiwindowshape.c \
+	winmultiwindowwindow.c \
+	winmultiwindowwm.c \
+	winmultiwindowwndproc.c
+DEFS_MULTIWINDOW = -DXWIN_MULTIWINDOW
+endif
+
+if XWIN_MULTIWINDOWEXTWM
+SRCS_MULTIWINDOWEXTWM = \
+	winwin32rootless.c \
+	winwin32rootlesswindow.c \
+	winwin32rootlesswndproc.c \
+	winwindowswm.c
+DEFS_MULTIWINDOWEXTWM = -DXWIN_MULTIWINDOWEXTWM
+MULTIWINDOWEXTWM_LIBS = $(top_builddir)/miext/rootless/librootless.la
+endif
+
+if XWIN_NATIVEGDI
+SRCS_NATIVEGDI = \
+	winclip.c \
+	winfillsp.c \
+	winfont.c \
+	wingc.c \
+	wingetsp.c \
+	winnativegdi.c \
+	winpixmap.c \
+	winpolyline.c \
+	winrop.c \
+	winsetsp.c
+DEFS_NATIVEGDI = -DXWIN_NATIVEGDI
+endif
+
+if XWIN_PRIMARYFB
+SRCS_PRIMARYFB = \
+	winpfbdd.c
+DEFS_PRIMARYFB = -DXWIN_PRIMARYFB
+endif
+
+if XWIN_RANDR
+SRCS_RANDR = \
+	winrandr.c
+DEFS_RANDR = -DXWIN_RANDR
+endif
+
+if XWIN_XV
+SRCS_XV = \
+	winvideo.c
+DEFS_XV = -DXWIN_XV
+endif
+
+SRCS =	InitInput.c \
+	InitOutput.c \
+	winallpriv.c \
+	winauth.c \
+	winblock.c \
+	wincmap.c \
+	winconfig.c \
+	wincreatewnd.c \
+	wincursor.c \
+	windialogs.c \
+	winengine.c \
+	winerror.c \
+	winglobals.c \
+	winkeybd.c \
+	winkeyhook.c \
+	winmisc.c \
+	winmouse.c \
+	winmsg.c \
+	winmultiwindowclass.c \
+	winmultiwindowicons.c \
+	winprefs.c \
+	winprefsyacc.y \
+	winprefslex.l \
+	winprocarg.c \
+	winregistry.c \
+	winscrinit.c \
+	winshaddd.c \
+	winshadddnl.c \
+	winshadgdi.c \
+	wintrayicon.c \
+	winvalargs.c \
+	winwakeup.c \
+	winwindow.c \
+	winwndproc.c \
+	ddraw.h \
+	winclipboard.h \
+	winconfig.h \
+	win.h \
+	winkeybd.h \
+	winkeynames.h \
+	winlayouts.h \
+	winmessages.h \
+	winmsg.h \
+	winms.h \
+	winmultiwindowclass.h \
+	winprefs.h \
+	winpriv.h \
+	winresource.h \
+	winwindow.h \
+	XWin.rc \
+	$(top_srcdir)/Xext/dpmsstubs.c \
+	$(top_srcdir)/Xi/stubs.c \
+	$(top_srcdir)/mi/miinitext.c \
+	$(top_srcdir)/fb/fbcmap_mi.c \
+	$(SRCS_CLIPBOARD) \
+	$(SRCS_GLX_WINDOWS) \
+	$(SRCS_MULTIWINDOW) \
+	$(SRCS_MULTIWINDOWEXTWM) \
+	$(SRCS_NATIVEGDI) \
+	$(SRCS_PRIMARYFB) \
+	$(SRCS_RANDR) \
+	$(SRCS_XV)
+
+ DEFS = $(DEFS_CLIPBOARD) \
+	$(DEFS_GLX_WINDOWS) \
+	$(DEFS_MULTIWINDOW) \
+	$(DEFS_MULTIWINDOWEXTWM) \
+	$(DEFS_NATIVEGDI) \
+	$(DEFS_PRIMARYFB) \
+	$(DEFS_RANDR) \
+	$(DEFS_XV)
+
+XWin_SOURCES = $(SRCS)
+
+INCLUDES = -I$(top_srcdir)/miext/rootless
+
+XWin_DEPENDENCIES = $(XWIN_LIBS)
+XWin_LDADD = $(MULTIWINDOWEXTWM_LIBS) $(XWIN_LIBS) $(MAIN_LIB) $(XSERVER_LIBS) $(XSERVER_SYS_LIBS) $(XWIN_SYS_LIBS)
+
+.rc.o:
+	$(WINDRES) --use-temp-file -i $< --input-format=rc -o $@ -O coff -I $(top_builddir)/include
+
+XWin_LDFLAGS = -mwindows -static
+
+winprefsyacc.h: winprefsyacc.c
+winprefslex.c: winprefslex.l winprefsyacc.c winprefsyacc.h
+
+BUILT_SOURCES = winprefsyacc.h winprefsyacc.c winprefslex.c
+CLEANFILES = $(BUILT_SOURCES) $(appman_DATA) $(fileman_DATA) XWin.man XWinrc.man
+
+AM_YFLAGS = -d
+AM_LFLAGS = -i
+AM_CFLAGS = -DHAVE_XWIN_CONFIG_H $(DIX_CFLAGS) \
+            $(XWINMODULES_CFLAGS) \
+            -DXFree86Server
+
+GLX_EXTRAS = \
+	glx/glwindows.h \
+	glx/glwrap.c \
+	glx/indirect.c
+
+MAN_SRCS = XWin.man.pre XWinrc.man.pre
+
+appmandir = $(APP_MAN_DIR)
+appman_DATA = XWin.$(APP_MAN_SUFFIX)
+
+filemandir = $(FILE_MAN_DIR)
+fileman_DATA = XWinrc.$(FILE_MAN_SUFFIX)
+
+XWin.$(APP_MAN_SUFFIX): XWin.man
+	-rm -f XWin.$(APP_MAN_SUFFIX)
+	$(LN_S) XWin.man XWin.$(APP_MAN_SUFFIX)
+
+XWinrc.$(FILE_MAN_SUFFIX): XWinrc.man
+	-rm -f XWinrc.$(FILE_MAN_SUFFIX)
+	$(LN_S) XWinrc.man XWinrc.$(FILE_MAN_SUFFIX)
+
+EXTRAMANDEFS = -D__logdir__=$(logdir) -D__sysconfdir__=$(sysconfdir)
+
+xwinconfigdir = $(sysconfdir)/X11
+xwinconfig_DATA = system.XWinrc
+
+include $(top_srcdir)/cpprules.in
+
+EXTRA_DIST = \
+	$(GLX_EXTRAS) \
+	$(MAN_SRCS) \
+	X.ico \
+	XWin.rc \
+	xlaunch/config.cc \
+	xlaunch/COPYING \
+	xlaunch/main.cc \
+	xlaunch/resources/dialog.rc \
+	xlaunch/resources/fullscreen.bmp \
+	xlaunch/resources/images.rc \
+	xlaunch/resources/multiwindow.bmp \
+	xlaunch/resources/nodecoration.bmp \
+	xlaunch/resources/resources.h \
+	xlaunch/resources/resources.rc \
+	xlaunch/resources/strings.rc \
+	xlaunch/resources/windowed.bmp \
+	xlaunch/window/dialog.cc \
+	xlaunch/window/dialog.h \
+	xlaunch/window/util.cc \
+	xlaunch/window/util.h \
+	xlaunch/window/window.cc \
+	xlaunch/window/window.h \
+	xlaunch/window/wizard.cc \
+	xlaunch/window/wizard.h
+
+relink:
+	rm -f XWin$(EXEEXT) && $(MAKE) XWin$(EXEEXT)
diff --git a/xorg-server/hw/xwin/glx/indirect.c b/xorg-server/hw/xwin/glx/indirect.c
index c3589c640..a5ea854b3 100644
--- a/xorg-server/hw/xwin/glx/indirect.c
+++ b/xorg-server/hw/xwin/glx/indirect.c
@@ -1,2255 +1,2278 @@
-/*
- * File: indirect.c
- * Purpose: A GLX implementation that uses Windows OpenGL library
- *
- * Authors: Alexander Gottwald
- *          Jon TURNEY
- *
- * Copyright (c) Jon TURNEY 2009
- * Copyright (c) Alexander Gottwald 2004
- *
- * Portions of this file are copied from GL/apple/indirect.c,
- * which contains the following copyright:
- *
- * Copyright (c) 2007, 2008, 2009 Apple Inc.
- * Copyright (c) 2004 Torrey T. Lyons. All Rights Reserved.
- * Copyright (c) 2002 Greg Parker. All Rights Reserved.
- *
- * Portions of this file are copied from Mesa's xf86glx.c,
- * which contains the following copyright:
- *
- * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
- * All Rights Reserved.
- *
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-/*
-  TODO:
-  - hook up remaining unimplemented extensions
-  - research what guarantees glXWaitX, glXWaitGL are supposed to offer, and implement then
-    using GdiFlush and/or glFinish
-  - pbuffer clobbering: we don't get async notification, but can we arrange to emit the
-    event when we notice it's been clobbered? at the very least, check if it's been clobbered
-    before using it?
-  - are the __GLXConfig * we get handed back ones we are made (so we can extend the structure
-    with privates?) Or are they created inside the GLX core as well?
-  - snap winWindowInfoRec, it's just the same as a HWND now...
-*/
-
-/*
-  MSDN clarifications:
-
-  It says SetPixelFormat()'s PIXELFORMATDESCRIPTOR pointer argument has no effect
-  except on metafiles, this seems to mean that as it's ok to supply NULL if the DC
-  is not for a metafile
-
-  wglMakeCurrent ignores the hdc if hglrc is NULL, so wglMakeCurrent(NULL, NULL)
-  is used to make no context current
-
-*/
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-
-#include "glwindows.h"
-#include <glx/glxserver.h>
-#include <glx/glxutil.h>
-#include <glx/extension_string.h>
-#include <GL/internal/glcore.h>
-#include <GL/glxtokens.h>
-
-#include <winpriv.h>
-#include <wgl_ext_api.h>
-
-#define NUM_ELEMENTS(x) (sizeof(x)/ sizeof(x[1]))
-
-/* ---------------------------------------------------------------------- */
-/*
- *   structure definitions
- */
-
-typedef struct __GLXWinContext  __GLXWinContext;
-typedef struct __GLXWinDrawable __GLXWinDrawable;
-typedef struct __GLXWinScreen glxWinScreen;
-typedef struct __GLXWinConfig GLXWinConfig;
-
-struct __GLXWinContext {
-  __GLXcontext base;
-  HGLRC ctx;                         /* Windows GL Context */
-  __GLXWinContext *shareContext;     /* Context with which we will share display lists and textures */
-  HWND hwnd;                         /* For detecting when HWND has changed */
-};
-
-struct __GLXWinDrawable
-{
-  __GLXdrawable base;
-  __GLXWinContext *drawContext;
-  __GLXWinContext *readContext;
-
-  /* If this drawable is GLX_DRAWABLE_PBUFFER */
-  HPBUFFERARB hPbuffer;
-
-  /* If this drawable is GLX_DRAWABLE_PIXMAP */
-  HDC dibDC;
-  HBITMAP hDIB;
-  HBITMAP hOldDIB; /* original DIB for DC */
-  void *pOldBits; /* original pBits for this drawable's pixmap */
-};
-
-struct __GLXWinScreen
-{
-  __GLXscreen base;
-
-  /* Supported GLX extensions */
-  unsigned char glx_enable_bits[__GLX_EXT_BYTES];
-
-  Bool has_WGL_ARB_multisample;
-  Bool has_WGL_ARB_pixel_format;
-  Bool has_WGL_ARB_pbuffer;
-  Bool has_WGL_ARB_render_texture;
-
-  /* wrapped screen functions */
-  RealizeWindowProcPtr RealizeWindow;
-  UnrealizeWindowProcPtr UnrealizeWindow;
-  CopyWindowProcPtr CopyWindow;
-};
-
-struct __GLXWinConfig
-{
-  __GLXconfig base;
-  int pixelFormatIndex;
-};
-
-/* ---------------------------------------------------------------------- */
-/*
- * Various debug helpers
- */
-
-#define GLWIN_DEBUG_HWND(hwnd)  \
-    if (glxWinDebugSettings.dumpHWND) { \
-        char buffer[1024]; \
-        if (GetWindowText(hwnd, buffer, sizeof(buffer))==0) *buffer=0; \
-        GLWIN_DEBUG_MSG("Got HWND %p for window '%s'", hwnd, buffer); \
-    }
-
-glxWinDebugSettingsRec glxWinDebugSettings = { 0, 0, 0, 0, 0, 0};
-
-static void glxWinInitDebugSettings(void)
-{
-    char *envptr;
-
-    envptr = getenv("GLWIN_ENABLE_DEBUG");
-    if (envptr != NULL)
-        glxWinDebugSettings.enableDebug = (atoi(envptr) == 1);
-
-    envptr = getenv("GLWIN_ENABLE_TRACE");
-    if (envptr != NULL)
-        glxWinDebugSettings.enableTrace = (atoi(envptr) == 1);
-
-    envptr = getenv("GLWIN_DUMP_PFD");
-    if (envptr != NULL)
-        glxWinDebugSettings.dumpPFD = (atoi(envptr) == 1);
-
-    envptr = getenv("GLWIN_DUMP_HWND");
-    if (envptr != NULL)
-        glxWinDebugSettings.dumpHWND = (atoi(envptr) == 1);
-
-    envptr = getenv("GLWIN_DUMP_DC");
-    if (envptr != NULL)
-        glxWinDebugSettings.dumpDC = (atoi(envptr) == 1);
-
-    envptr = getenv("GLWIN_ENABLE_GLCALL_TRACE");
-    if (envptr != NULL)
-        glxWinDebugSettings.enableGLcallTrace = (atoi(envptr) == 1);
-
-    envptr = getenv("GLWIN_ENABLE_WGLCALL_TRACE");
-    if (envptr != NULL)
-        glxWinDebugSettings.enableWGLcallTrace = (atoi(envptr) == 1);
-
-    envptr = getenv("GLWIN_DEBUG_ALL");
-    if (envptr != NULL)
-      {
-        glxWinDebugSettings.enableDebug = 1;
-        glxWinDebugSettings.enableTrace = 1;
-        glxWinDebugSettings.dumpPFD = 1;
-        glxWinDebugSettings.dumpHWND = 1;
-        glxWinDebugSettings.dumpDC = 1;
-        glxWinDebugSettings.enableGLcallTrace = 1;
-        glxWinDebugSettings.enableWGLcallTrace = 1;
-      }
-}
-
-static
-const char *glxWinErrorMessage(void)
-{
-  static char errorbuffer[1024];
-
-  if (!FormatMessage(
-                     FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
-                     NULL,
-                     GetLastError(),
-                     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                     (LPTSTR) &errorbuffer,
-                     sizeof(errorbuffer),
-                     NULL ))
-    {
-      snprintf(errorbuffer, sizeof(errorbuffer), "Unknown error in FormatMessage: %08x!", (unsigned)GetLastError());
-    }
-
-  if (errorbuffer[strlen(errorbuffer)-1] == '\n')
-    errorbuffer[strlen(errorbuffer)-1] = 0;
-
-  return errorbuffer;
-}
-
-static void pfdOut(const PIXELFORMATDESCRIPTOR *pfd);
-
-#define DUMP_PFD_FLAG(flag) \
-    if (pfd->dwFlags & flag) { \
-        ErrorF("%s%s", pipesym, #flag); \
-        pipesym = " | "; \
-    }
-
-static void pfdOut(const PIXELFORMATDESCRIPTOR *pfd)
-{
-    const char *pipesym = ""; /* will be set after first flag dump */
-    ErrorF("PIXELFORMATDESCRIPTOR:\n");
-    ErrorF("nSize = %u\n", pfd->nSize);
-    ErrorF("nVersion = %u\n", pfd->nVersion);
-    ErrorF("dwFlags = %lu = {", pfd->dwFlags);
-        DUMP_PFD_FLAG(PFD_DOUBLEBUFFER);
-        DUMP_PFD_FLAG(PFD_STEREO);
-        DUMP_PFD_FLAG(PFD_DRAW_TO_WINDOW);
-        DUMP_PFD_FLAG(PFD_DRAW_TO_BITMAP);
-        DUMP_PFD_FLAG(PFD_SUPPORT_GDI);
-        DUMP_PFD_FLAG(PFD_SUPPORT_OPENGL);
-        DUMP_PFD_FLAG(PFD_GENERIC_FORMAT);
-        DUMP_PFD_FLAG(PFD_NEED_PALETTE);
-        DUMP_PFD_FLAG(PFD_NEED_SYSTEM_PALETTE);
-        DUMP_PFD_FLAG(PFD_SWAP_EXCHANGE);
-        DUMP_PFD_FLAG(PFD_SWAP_COPY);
-        DUMP_PFD_FLAG(PFD_SWAP_LAYER_BUFFERS);
-        DUMP_PFD_FLAG(PFD_GENERIC_ACCELERATED);
-        DUMP_PFD_FLAG(PFD_DEPTH_DONTCARE);
-        DUMP_PFD_FLAG(PFD_DOUBLEBUFFER_DONTCARE);
-        DUMP_PFD_FLAG(PFD_STEREO_DONTCARE);
-    ErrorF("}\n");
-
-    ErrorF("iPixelType = %hu = %s\n", pfd->iPixelType,
-            (pfd->iPixelType == PFD_TYPE_RGBA ? "PFD_TYPE_RGBA" : "PFD_TYPE_COLORINDEX"));
-    ErrorF("cColorBits = %hhu\n", pfd->cColorBits);
-    ErrorF("cRedBits = %hhu\n", pfd->cRedBits);
-    ErrorF("cRedShift = %hhu\n", pfd->cRedShift);
-    ErrorF("cGreenBits = %hhu\n", pfd->cGreenBits);
-    ErrorF("cGreenShift = %hhu\n", pfd->cGreenShift);
-    ErrorF("cBlueBits = %hhu\n", pfd->cBlueBits);
-    ErrorF("cBlueShift = %hhu\n", pfd->cBlueShift);
-    ErrorF("cAlphaBits = %hhu\n", pfd->cAlphaBits);
-    ErrorF("cAlphaShift = %hhu\n", pfd->cAlphaShift);
-    ErrorF("cAccumBits = %hhu\n", pfd->cAccumBits);
-    ErrorF("cAccumRedBits = %hhu\n", pfd->cAccumRedBits);
-    ErrorF("cAccumGreenBits = %hhu\n", pfd->cAccumGreenBits);
-    ErrorF("cAccumBlueBits = %hhu\n", pfd->cAccumBlueBits);
-    ErrorF("cAccumAlphaBits = %hhu\n", pfd->cAccumAlphaBits);
-    ErrorF("cDepthBits = %hhu\n", pfd->cDepthBits);
-    ErrorF("cStencilBits = %hhu\n", pfd->cStencilBits);
-    ErrorF("cAuxBuffers = %hhu\n", pfd->cAuxBuffers);
-    ErrorF("iLayerType = %hhu\n", pfd->iLayerType);
-    ErrorF("bReserved = %hhu\n", pfd->bReserved);
-    ErrorF("dwLayerMask = %lu\n", pfd->dwLayerMask);
-    ErrorF("dwVisibleMask = %lu\n", pfd->dwVisibleMask);
-    ErrorF("dwDamageMask = %lu\n", pfd->dwDamageMask);
-    ErrorF("\n");
-}
-
-static const char *
-visual_class_name(int cls)
-{
-  switch (cls) {
-  case GLX_STATIC_COLOR:
-    return "StaticColor";
-  case GLX_PSEUDO_COLOR:
-    return "PseudoColor";
-  case GLX_STATIC_GRAY:
-    return "StaticGray";
-  case GLX_GRAY_SCALE:
-    return "GrayScale";
-  case GLX_TRUE_COLOR:
-     return "TrueColor";
-  case GLX_DIRECT_COLOR:
-     return "DirectColor";
-  default:
-    return "-none-";
-  }
-}
-
-static const char *
-swap_method_name(int mthd)
-{
-  switch (mthd)
-    {
-    case GLX_SWAP_EXCHANGE_OML:
-      return "xchg";
-    case GLX_SWAP_COPY_OML:
-      return "copy";
-    case GLX_SWAP_UNDEFINED_OML:
-      return "    ";
-    default:
-      return "????";
-    }
-}
-
-static void
-fbConfigsDump(unsigned int n, __GLXconfig *c)
-{
-  ErrorF("%d fbConfigs\n", n);
-  ErrorF("pxf vis  fb                      render         Ste                     aux    accum        MS    drawable             Group/\n");
-  ErrorF("idx  ID  ID VisualType Depth Lvl RGB CI DB Swap reo  R  G  B  A   Z  S  buf AR AG AB AA  bufs num  W P Pb  Float Trans Caveat\n");
-  ErrorF("-----------------------------------------------------------------------------------------------------------------------------\n");
-
-  while (c != NULL)
-    {
-      unsigned int i = ((GLXWinConfig *)c)->pixelFormatIndex;
-
-      ErrorF("%3d  %2x  %2x "
-             "%-11s"
-             " %3d %3d   %s   %s  %s %s  %s  "
-             "%2d %2d %2d %2d  "
-             "%2d %2d  "
-             "%2d  "
-             "%2d %2d %2d %2d"
-             "   %2d   %2d"
-             "  %s %s %s "
-             "    %s   "
-             "  %s   "
-             "  %d %s"
-             "\n",
-             i, c->visualID, c->fbconfigID,
-             visual_class_name(c->visualType),
-             c->rgbBits ? c->rgbBits : c->indexBits,
-             c->level,
-	     (c->renderType & GLX_RGBA_BIT) ? "y" : ".",
-	     (c->renderType & GLX_COLOR_INDEX_BIT) ? "y" : ".",
-	     c->doubleBufferMode ? "y" : ".",
-             swap_method_name(c->swapMethod),
-	     c->stereoMode ? "y" : ".",
-             c->redBits, c->greenBits, c->blueBits, c->alphaBits,
-             c->depthBits, c->stencilBits,
-             c->numAuxBuffers,
-             c->accumRedBits, c->accumGreenBits, c->accumBlueBits, c->accumAlphaBits,
-             c->sampleBuffers, c->samples,
-             (c->drawableType & GLX_WINDOW_BIT) ? "y" : ".",
-             (c->drawableType & GLX_PIXMAP_BIT) ? "y" : ".",
-             (c->drawableType & GLX_PBUFFER_BIT) ? "y" : ".",
-             ".",
-             (c->transparentPixel != GLX_NONE_EXT) ? "y" : ".",
-             c->visualSelectGroup, (c->visualRating == GLX_SLOW_VISUAL_EXT) ? "*" : " ");
-
-      c = c->next;
-    }
-}
-
-/* ---------------------------------------------------------------------- */
-/*
- * Forward declarations
- */
-
-static __GLXscreen *glxWinScreenProbe(ScreenPtr pScreen);
-static __GLXcontext *glxWinCreateContext(__GLXscreen *screen,
-                                        __GLXconfig *modes,
-                                        __GLXcontext *baseShareContext);
-static __GLXdrawable *glxWinCreateDrawable(__GLXscreen *screen,
-                                          DrawablePtr pDraw,
-                                          int type,
-                                          XID drawId,
-                                          __GLXconfig *conf);
-
-static Bool glxWinRealizeWindow(WindowPtr pWin);
-static Bool glxWinUnrealizeWindow(WindowPtr pWin);
-static void glxWinCopyWindow(WindowPtr pWindow, DDXPointRec ptOldOrg, RegionPtr prgnSrc);
-
-static HDC glxWinMakeDC(__GLXWinContext *gc, __GLXWinDrawable *draw, HDC *hdc, HWND *hwnd);
-static void glxWinReleaseDC(HWND hwnd, HDC hdc, __GLXWinDrawable *draw);
-
-static void glxWinCreateConfigs(HDC dc, glxWinScreen *screen);
-static void glxWinCreateConfigsExt(HDC hdc, glxWinScreen *screen);
-static int fbConfigToPixelFormat(__GLXconfig *mode, PIXELFORMATDESCRIPTOR *pfdret, int drawableTypeOverride);
-static int fbConfigToPixelFormatIndex(HDC hdc, __GLXconfig *mode, int drawableTypeOverride, glxWinScreen *winScreen);
-
-/* ---------------------------------------------------------------------- */
-/*
- * The GLX provider
- */
-
-__GLXprovider __glXWGLProvider = {
-    glxWinScreenProbe,
-    "Win32 native WGL",
-    NULL
-};
-
-void
-glxWinPushNativeProvider(void)
-{
-  GlxPushProvider(&__glXWGLProvider);
-}
-
-/* ---------------------------------------------------------------------- */
-/*
- * Screen functions
- */
-
-static void
-glxWinScreenDestroy(__GLXscreen *screen)
-{
-    GLWIN_DEBUG_MSG("glxWinScreenDestroy(%p)", screen);
-    __glXScreenDestroy(screen);
-    xfree(screen);
-}
-
-static int
-glxWinScreenSwapInterval(__GLXdrawable *drawable, int interval)
-{
-  BOOL ret = wglSwapIntervalEXTWrapper(interval);
-  if (!ret)
-    {
-      ErrorF("wglSwapIntervalEXT interval %d failed:%s\n", interval, glxWinErrorMessage());
-    }
-  return ret;
-}
-
-static void
-glxLogExtensions (char *extensions)
-{
-    int i = 0;
-    char *strl;
-    char *str = xalloc(strlen(extensions) + 1);
-
-    if (str == NULL)
-    {
-	ErrorF("\nglxLogExtensions: xalloc error\n");
-	return;
-    }
-
-    str[strlen(extensions)] = '\0';
-    strncpy (str, extensions, strlen(extensions));
-    strl = strtok(str, " ");
-    ErrorF("%s", strl);
-    while (1)
-    {
-	strl = strtok(NULL, " ");
-	if (strl == NULL) break;
-	if (++i%5 == 0) ErrorF("\n\t\t");
-	ErrorF(" %s", strl);
-    }
-    ErrorF("\n");
-    xfree(str);
-}
-
-/* This is called by GlxExtensionInit() asking the GLX provider if it can handle the screen... */
-static __GLXscreen *
-glxWinScreenProbe(ScreenPtr pScreen)
-{
-    glxWinScreen *screen;
-    const char *gl_extensions;
-    const char *wgl_extensions;
-    HWND hwnd;
-    HDC hdc;
-    HGLRC hglrc;
-
-    GLWIN_DEBUG_MSG("glxWinScreenProbe");
-
-    glxWinInitDebugSettings();
-
-    if (pScreen == NULL)
-	return NULL;
-
-    if (!winCheckScreenAiglxIsSupported(pScreen))
-      {
-        LogMessage(X_ERROR,"AIGLX: No native OpenGL in modes with a root window\n");
-        return NULL;
-      }
-
-    screen = xcalloc(1, sizeof(glxWinScreen));
-
-    if (NULL == screen)
-	return NULL;
-
-    /* Wrap RealizeWindow, UnrealizeWindow and CopyWindow on this screen */
-    screen->RealizeWindow = pScreen->RealizeWindow;
-    pScreen->RealizeWindow = glxWinRealizeWindow;
-    screen->UnrealizeWindow = pScreen->UnrealizeWindow;
-    pScreen->UnrealizeWindow = glxWinUnrealizeWindow;
-    screen->CopyWindow = pScreen->CopyWindow;
-    pScreen->CopyWindow = glxWinCopyWindow;
-
-    /* Dump out some useful information about the native renderer */
-
-    // create window class
-#define WIN_GL_TEST_WINDOW_CLASS "XWinGLTest"
-    {
-      static wATOM glTestWndClass = 0;
-      if (glTestWndClass == 0)
-        {
-          WNDCLASSEX wc;
-          wc.cbSize = sizeof(WNDCLASSEX);
-          wc.style = CS_HREDRAW | CS_VREDRAW;
-          wc.lpfnWndProc = DefWindowProc;
-          wc.cbClsExtra = 0;
-          wc.cbWndExtra = 0;
-          wc.hInstance = GetModuleHandle(NULL);
-          wc.hIcon = 0;
-          wc.hCursor = 0;
-          wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
-          wc.lpszMenuName = NULL;
-          wc.lpszClassName = WIN_GL_TEST_WINDOW_CLASS;
-          wc.hIconSm = 0;
-          RegisterClassEx (&wc);
-      }
-    }
-
-    // create an invisible window for a scratch DC
-    hwnd = CreateWindowExA(0,
-                           WIN_GL_TEST_WINDOW_CLASS,
-                           "XWin GL Renderer Capabilities Test Window",
-                           0, 0, 0, 0, 0, NULL, NULL, GetModuleHandle(NULL), NULL);
-    if (hwnd == NULL)
-      LogMessage(X_ERROR,"AIGLX: Couldn't create a window for render capabilities testing\n");
-
-    hdc = GetDC(hwnd);
-
-    // we must set a pixel format before we can create a context, just use the first one...
-    SetPixelFormat(hdc, 1, NULL);
-    hglrc = wglCreateContext(hdc);
-    wglMakeCurrent(hdc, hglrc);
-
-    // initialize wgl extension proc pointers (don't call them before here...)
-    // (but we need to have a current context for them to be resolvable)
-    wglResolveExtensionProcs();
-
-    ErrorF("GL_VERSION:    %s\n", glGetStringWrapperNonstatic(GL_VERSION));
-    ErrorF("GL_VENDOR:     %s\n", glGetStringWrapperNonstatic(GL_VENDOR));
-    ErrorF("GL_RENDERER:   %s\n", glGetStringWrapperNonstatic(GL_RENDERER));
-    gl_extensions = (const char *)glGetStringWrapperNonstatic(GL_EXTENSIONS);
-    ErrorF("GL_EXTENSIONS: ");
-    glxLogExtensions(gl_extensions);
-    wgl_extensions = wglGetExtensionsStringARBWrapper(hdc);
-    if (!wgl_extensions) wgl_extensions = "";
-    ErrorF("WGL_EXTENSIONS:");
-    glxLogExtensions(wgl_extensions);
-
-    // Can you see the problem here?  The extensions string is DC specific
-    // Different DCs for windows on a multimonitor system driven by multiple cards
-    // might have completely different capabilities.  Of course, good luck getting
-    // those screens to be accelerated in XP and earlier...
-
-    {
-      // testing facility to not use any WGL extensions
-      char *envptr = getenv("GLWIN_NO_WGL_EXTENSIONS");
-      if ((envptr != NULL) && (atoi(envptr) != 0))
-        {
-          ErrorF("GLWIN_NO_WGL_EXTENSIONS is set, ignoring WGL_EXTENSIONS\n");
-          wgl_extensions = "";
-        }
-    }
-
-    {
-      Bool glx_sgi_make_current_read = FALSE;
-
-      //
-      // Based on the WGL extensions available, enable various GLX extensions
-      // XXX: make this table-driven ?
-      //
-      memset(screen->glx_enable_bits, 0, __GLX_EXT_BYTES);
-
-      __glXEnableExtension(screen->glx_enable_bits, "GLX_EXT_visual_info");
-      __glXEnableExtension(screen->glx_enable_bits, "GLX_EXT_visual_rating");
-      __glXEnableExtension(screen->glx_enable_bits, "GLX_EXT_import_context");
-      __glXEnableExtension(screen->glx_enable_bits, "GLX_OML_swap_method");
-      __glXEnableExtension(screen->glx_enable_bits, "GLX_SGIX_fbconfig");
-
-      if (strstr(wgl_extensions, "WGL_ARB_make_current_read"))
-        {
-          __glXEnableExtension(screen->glx_enable_bits, "GLX_SGI_make_current_read");
-          LogMessage(X_INFO, "AIGLX: enabled GLX_SGI_make_current_read\n");
-          glx_sgi_make_current_read = TRUE;
-        }
-
-      if (strstr(gl_extensions, "GL_WIN_swap_hint"))
-        {
-          __glXEnableExtension(screen->glx_enable_bits, "GLX_MESA_copy_sub_buffer");
-          LogMessage(X_INFO, "AIGLX: enabled GLX_MESA_copy_sub_buffer\n");
-        }
-
-      if (strstr(wgl_extensions, "WGL_EXT_swap_control"))
-        {
-          __glXEnableExtension(screen->glx_enable_bits, "GLX_SGI_swap_control");
-          __glXEnableExtension(screen->glx_enable_bits, "GLX_MESA_swap_control");
-          LogMessage(X_INFO, "AIGLX: enabled GLX_SGI_swap_control and GLX_MESA_swap_control\n");
-        }
-
-/*       // Hmm?  screen->texOffset */
-/*       if (strstr(wgl_extensions, "WGL_ARB_render_texture")) */
-/*         { */
-/*           __glXEnableExtension(screen->glx_enable_bits, "GLX_EXT_texture_from_pixmap"); */
-/*           LogMessage(X_INFO, "AIGLX: GLX_EXT_texture_from_pixmap backed by buffer objects\n"); */
-/*           screen->has_WGL_ARB_render_texture = TRUE; */
-/*         } */
-
-      if (strstr(wgl_extensions, "WGL_ARB_pbuffer"))
-        {
-          __glXEnableExtension(screen->glx_enable_bits, "GLX_SGIX_pbuffer");
-          LogMessage(X_INFO, "AIGLX: enabled GLX_SGIX_pbuffer\n");
-          screen->has_WGL_ARB_pbuffer = TRUE;
-        }
-
-      if (strstr(wgl_extensions, "WGL_ARB_multisample"))
-        {
-          __glXEnableExtension(screen->glx_enable_bits, "GLX_ARB_multisample");
-          __glXEnableExtension(screen->glx_enable_bits, "GLX_SGIS_multisample");
-          LogMessage(X_INFO, "AIGLX: enabled GLX_ARB_multisample and GLX_SGIS_multisample\n");
-          screen->has_WGL_ARB_multisample = TRUE;
-        }
-
-      screen->base.destroy = glxWinScreenDestroy;
-      screen->base.createContext = glxWinCreateContext;
-      screen->base.createDrawable = glxWinCreateDrawable;
-      screen->base.swapInterval = glxWinScreenSwapInterval;
-      screen->base.hyperpipeFuncs = NULL;
-      screen->base.swapBarrierFuncs = NULL;
-      screen->base.pScreen = pScreen;
-
-      if (strstr(wgl_extensions, "WGL_ARB_pixel_format"))
-        {
-          glxWinCreateConfigsExt(hdc, screen);
-          screen->has_WGL_ARB_pixel_format = TRUE;
-        }
-      else
-        {
-          glxWinCreateConfigs(hdc, screen);
-          screen->has_WGL_ARB_pixel_format = FALSE;
-        }
-      // Initializes screen->base.fbconfigs and screen->base.numFBConfigs
-
-      /* These will be set by __glXScreenInit */
-      screen->base.visuals = NULL;
-      screen->base.numVisuals = 0;
-
-      __glXScreenInit(&screen->base, pScreen);
-
-      // dump out fbConfigs now fbConfigIds and visualIDs have been assigned
-      fbConfigsDump(screen->base.numFBConfigs, screen->base.fbconfigs);
-
-      // Override the GL extensions string set by __glXScreenInit()
-      screen->base.GLextensions = xstrdup(gl_extensions);
-
-      // Generate the GLX extensions string (overrides that set by __glXScreenInit())
-      {
-        unsigned int buffer_size = __glXGetExtensionString(screen->glx_enable_bits, NULL);
-        if (buffer_size > 0)
-          {
-            if (screen->base.GLXextensions != NULL)
-              {
-                xfree(screen->base.GLXextensions);
-              }
-
-            screen->base.GLXextensions = xnfalloc(buffer_size);
-            __glXGetExtensionString(screen->glx_enable_bits, screen->base.GLXextensions);
-          }
-      }
-
-      //
-      // Override the GLX version (__glXScreenInit() sets it to "1.2")
-      // if we have all the needed extensionsto operate as a higher version
-      //
-      // SGIX_fbconfig && SGIX_pbuffer && SGI_make_current_read -> 1.3
-      // ARB_multisample -> 1.4
-      //
-      if (screen->has_WGL_ARB_pbuffer && glx_sgi_make_current_read)
-        {
-          xfree(screen->base.GLXversion);
-
-          if (screen->has_WGL_ARB_multisample)
-            {
-              screen->base.GLXversion = xstrdup("1.4");
-              screen->base.GLXminor = 4;
-            }
-          else
-            {
-              screen->base.GLXversion = xstrdup("1.3");
-              screen->base.GLXminor = 3;
-            }
-          LogMessage(X_INFO, "AIGLX: Set GLX version to %s\n", screen->base.GLXversion);
-        }
-    }
-
-    wglMakeCurrent(NULL, NULL);
-    wglDeleteContext(hglrc);
-    ReleaseDC(hwnd, hdc);
-    DestroyWindow(hwnd);
-
-    return &screen->base;
-}
-
-/* ---------------------------------------------------------------------- */
-/*
- * Window functions
- */
-
-static Bool
-glxWinRealizeWindow(WindowPtr pWin)
-{
-    Bool result;
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    glxWinScreen *screenPriv = (glxWinScreen *) glxGetScreen(pScreen);
-
-    GLWIN_DEBUG_MSG("glxWinRealizeWindow");
-
-    /* Allow the window to be created (RootlessRealizeWindow is inside our wrap) */
-    pScreen->RealizeWindow = screenPriv->RealizeWindow;
-    result = pScreen->RealizeWindow(pWin);
-    pScreen->RealizeWindow = glxWinRealizeWindow;
-
-    return result;
-}
-
-
-static void
-glxWinCopyWindow(WindowPtr pWindow, DDXPointRec ptOldOrg, RegionPtr prgnSrc)
-{
-    __GLXWinDrawable *pGlxDraw;
-    ScreenPtr pScreen = pWindow->drawable.pScreen;
-    glxWinScreen *screenPriv = (glxWinScreen *) glxGetScreen(pScreen);
-
-    GLWIN_TRACE_MSG("glxWinCopyWindow pWindow %p", pWindow);
-
-    dixLookupResourceByType((pointer) &pGlxDraw, pWindow->drawable.id, __glXDrawableRes,
-				NullClient, DixUnknownAccess);
-
-
-    /*
-       Discard any CopyWindow requests if a GL drawing context is pointing at the window
-
-       For regions which are being drawn by GL, the shadow framebuffer doesn't have the
-       correct bits, so we wish to avoid shadow framebuffer damage occuring, which will
-       cause those incorrect bits to be transferred to the display....
-    */
-    if (pGlxDraw && pGlxDraw->drawContext)
-      {
-        GLWIN_DEBUG_MSG("glxWinCopyWindow: discarding");
-        return;
-      }
-
-    GLWIN_DEBUG_MSG("glxWinCopyWindow - passing to hw layer");
-
-    pScreen->CopyWindow = screenPriv->CopyWindow;
-    pScreen->CopyWindow(pWindow, ptOldOrg, prgnSrc);
-    pScreen->CopyWindow = glxWinCopyWindow;
-}
-
-static Bool
-glxWinUnrealizeWindow(WindowPtr pWin)
-{
-    Bool result;
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    glxWinScreen *screenPriv = (glxWinScreen *)glxGetScreen(pScreen);
-
-    GLWIN_DEBUG_MSG("glxWinUnrealizeWindow");
-
-    pScreen->UnrealizeWindow = screenPriv->UnrealizeWindow;
-    result = pScreen->UnrealizeWindow(pWin);
-    pScreen->UnrealizeWindow = glxWinUnrealizeWindow;
-
-    return result;
-}
-
-/* ---------------------------------------------------------------------- */
-/*
- * Drawable functions
- */
-
-static GLboolean
-glxWinDrawableSwapBuffers(__GLXdrawable *base)
-{
-    HDC dc;
-    HWND hwnd;
-    BOOL ret;
-    __GLXWinDrawable *draw = (__GLXWinDrawable *)base;
-
-    /* Swap buffers on the last active context for drawing on the drawable */
-    if (draw->drawContext == NULL)
-      {
-        GLWIN_TRACE_MSG("glxWinSwapBuffers - no context for drawable");
-        return GL_FALSE;
-      }
-
-    GLWIN_TRACE_MSG("glxWinSwapBuffers on drawable %p, last context %p (native ctx %p)", base, draw->drawContext, draw->drawContext->ctx);
-
-    /*
-       draw->drawContext->base.drawPriv will not be set if the context is not current anymore,
-       but if it is, it should point to this drawable....
-    */
-    assert((draw->drawContext->base.drawPriv == NULL) || (draw->drawContext->base.drawPriv == base));
-
-    dc = glxWinMakeDC(draw->drawContext, draw, &dc, &hwnd);
-    if (dc == NULL)
-      return GL_FALSE;
-
-    ret = wglSwapLayerBuffers(dc, WGL_SWAP_MAIN_PLANE);
-
-    glxWinReleaseDC(hwnd, dc, draw);
-
-    if (!ret)
-      {
-        ErrorF("wglSwapBuffers failed: %s\n", glxWinErrorMessage());
-        return GL_FALSE;
-      }
-
-    return GL_TRUE;
-}
-
-static void
-glxWinDrawableCopySubBuffer(__GLXdrawable *drawable,
-                            int x, int y, int w, int h)
-{
-  glAddSwapHintRectWINWrapperNonstatic(x, y, w, h);
-  glxWinDrawableSwapBuffers(drawable);
-}
-
-static void
-glxWinDrawableDestroy(__GLXdrawable *base)
-{
-  __GLXWinDrawable *glxPriv = (__GLXWinDrawable *)base;
-
-  if (glxPriv->drawContext && (__glXLastContext == &((glxPriv->drawContext)->base)))
-    {
-      // if this context is current and has unflushed commands, say we have flushed them
-      // (don't actually flush them, the window is going away anyhow, and an implict flush occurs
-      // on the next context change)
-      // (GLX core considers it an error when we try to select a new current context if the old one
-      // has unflushed commands, but the window has disappeared..)
-      __GLX_NOTE_FLUSHED_CMDS(__glXLastContext);
-      __glXLastContext = NULL;
-    }
-
-  if (glxPriv->hPbuffer)
-    if (!wglDestroyPbufferARBWrapper(glxPriv->hPbuffer))
-      {
-        ErrorF("wglDestroyPbufferARB failed: %s\n", glxWinErrorMessage());
-      }
-
-  if (glxPriv->dibDC)
-    {
-      // restore the default DIB
-      SelectObject(glxPriv->dibDC, glxPriv->hOldDIB);
-
-      if (!DeleteDC(glxPriv->dibDC))
-        {
-          ErrorF("DeleteDC failed: %s\n", glxWinErrorMessage());
-        }
-    }
-
-  if (glxPriv->hDIB)
-    {
-      if (!DeleteObject(glxPriv->hDIB))
-        {
-          ErrorF("DeleteObject failed: %s\n", glxWinErrorMessage());
-        }
-
-      ((PixmapPtr)glxPriv->base.pDraw)->devPrivate.ptr = glxPriv->pOldBits;
-    }
-
-  GLWIN_DEBUG_MSG("glxWinDestroyDrawable");
-  xfree(glxPriv);
-}
-
-static __GLXdrawable *
-glxWinCreateDrawable(__GLXscreen *screen,
-                    DrawablePtr pDraw,
-                    int type,
-                    XID drawId,
-                    __GLXconfig *conf)
-{
-  __GLXWinDrawable *glxPriv;
-
-  glxPriv = xalloc(sizeof *glxPriv);
-
-  if (glxPriv == NULL)
-      return NULL;
-
-  memset(glxPriv, 0, sizeof *glxPriv);
-
-  if(!__glXDrawableInit(&glxPriv->base, screen, pDraw, type, drawId, conf)) {
-    xfree(glxPriv);
-    return NULL;
-  }
-
-  glxPriv->base.destroy       = glxWinDrawableDestroy;
-  glxPriv->base.swapBuffers   = glxWinDrawableSwapBuffers;
-  glxPriv->base.copySubBuffer = glxWinDrawableCopySubBuffer;
-  // glxPriv->base.waitX  what are these for?
-  // glxPriv->base.waitGL
-
-  GLWIN_DEBUG_MSG("glxWinCreateDrawable %p", glxPriv);
-
-  return &glxPriv->base;
-}
-
-/* ---------------------------------------------------------------------- */
-/*
- * Texture functions
- */
-
-static
-int glxWinBindTexImage(__GLXcontext  *baseContext,
-                      int            buffer,
-                      __GLXdrawable *pixmap)
-{
-  ErrorF("glxWinBindTexImage: not implemented\n");
-  return FALSE;
-}
-
-static
-int glxWinReleaseTexImage(__GLXcontext  *baseContext,
-                         int            buffer,
-                         __GLXdrawable *pixmap)
-{
-  ErrorF(" glxWinReleaseTexImage: not implemented\n");
-  return FALSE;
-}
-
-/* ---------------------------------------------------------------------- */
-/*
- * Lazy update context implementation
- *
- * WGL contexts are created for a specific HDC, so we cannot create the WGL
- * context in glxWinCreateContext(), we must defer creation until the context
- * is actually used on a specifc drawable which is connected to a native window,
- * pbuffer or DIB
- *
- * The WGL context may be used on other, compatible HDCs, so we don't need to
- * recreate it for every new native window
- *
- * XXX: I wonder why we can't create the WGL context on the screen HDC ?
- * Basically we assume all HDCs are compatible at the moment: if they are not
- * we are in a muddle, there was some code in the old implementation to attempt
- * to transparently migrate a context to a new DC by copying state and sharing
- * lists with the old one...
- */
-
-static void
-glxWinSetPixelFormat(__GLXWinContext *gc, HDC hdc, int bppOverride, int drawableTypeOverride)
-{
-  __GLXscreen *screen = gc->base.pGlxScreen;
-  glxWinScreen *winScreen = (glxWinScreen *)screen;
-
-  __GLXconfig *config = gc->base.config;
-  GLXWinConfig *winConfig = (GLXWinConfig *)config;
-
-  GLWIN_DEBUG_MSG("glxWinSetPixelFormat: pixelFormatIndex %d", winConfig->pixelFormatIndex);
-
-  /*
-    Normally, we can just use the the pixelFormatIndex corresponding
-    to the fbconfig which has been specified by the client
-  */
-
-  if (!((bppOverride && (bppOverride != (config->redBits + config->greenBits + config->blueBits) ))
-        || ((config->drawableType & drawableTypeOverride) == 0)))
-    {
-      if (!SetPixelFormat(hdc, winConfig->pixelFormatIndex, NULL))
-        {
-          ErrorF("SetPixelFormat error: %s\n", glxWinErrorMessage());
-          return;
-        }
-
-      return;
-    }
-
-  /*
-    However, in certain special cases this pixel format will be incompatible with the
-    use we are going to put it to, so we need to re-evaluate the pixel format to use:
-
-    1) When PFD_DRAW_TO_BITMAP is set, ChoosePixelFormat() always returns a format with
-       the cColorBits we asked for, so we need to ensure it matches the bpp of the bitmap
-
-    2) Applications may assume that visuals selected with glXChooseVisual() work with
-       pixmap drawables (there is no attribute to explicitly query for pixmap drawable
-       support as there is for glXChooseFBConfig())
-       (it's arguable this is an error in the application, but we try to make it work)
-
-       pixmap rendering is always slow for us, so we don't want to choose those visuals
-       by default, but if the actual drawable type we're trying to select the context
-       on (drawableTypeOverride) isn't supported by the selected fbConfig, reconsider
-       and see if we can find a suitable one...
-   */
-  ErrorF("glxWinSetPixelFormat: having second thoughts: cColorbits %d, bppOveride %d; config->drawableType %d, drawableTypeOverride %d\n",
-         (config->redBits + config->greenBits + config->blueBits), bppOverride, config->drawableType, drawableTypeOverride);
-
-  if (!winScreen->has_WGL_ARB_pixel_format)
-    {
-      PIXELFORMATDESCRIPTOR pfd;
-      int pixelFormat;
-
-      /* convert fbConfig to PFD */
-      if (fbConfigToPixelFormat(gc->base.config, &pfd, drawableTypeOverride))
-        {
-          ErrorF("glxWinSetPixelFormat: fbConfigToPixelFormat failed\n");
-          return;
-        }
-
-      if (glxWinDebugSettings.dumpPFD)
-        pfdOut(&pfd);
-
-      if (bppOverride)
-        {
-          GLWIN_DEBUG_MSG("glxWinSetPixelFormat: Forcing bpp from %d to %d\n", pfd.cColorBits, bppOverride);
-          pfd.cColorBits = bppOverride;
-        }
-
-      pixelFormat = ChoosePixelFormat(hdc, &pfd);
-      if (pixelFormat == 0)
-        {
-          ErrorF("ChoosePixelFormat error: %s\n", glxWinErrorMessage());
-          return;
-        }
-
-      GLWIN_DEBUG_MSG("ChoosePixelFormat: chose pixelFormatIndex %d", pixelFormat);
-      ErrorF("ChoosePixelFormat: chose pixelFormatIndex %d (rather than %d as originally planned)\n", pixelFormat, winConfig->pixelFormatIndex);
-
-      if (!SetPixelFormat(hdc, pixelFormat, &pfd))
-        {
-          ErrorF("SetPixelFormat error: %s\n", glxWinErrorMessage());
-          return;
-        }
-    }
-  else
-    {
-      int pixelFormat = fbConfigToPixelFormatIndex(hdc, gc->base.config, drawableTypeOverride, winScreen);
-      if (pixelFormat == 0)
-        {
-          ErrorF("wglChoosePixelFormat error: %s\n", glxWinErrorMessage());
-          return;
-        }
-
-      GLWIN_DEBUG_MSG("wglChoosePixelFormat: chose pixelFormatIndex %d", pixelFormat);
-      ErrorF("wglChoosePixelFormat: chose pixelFormatIndex %d (rather than %d as originally planned)\n", pixelFormat, winConfig->pixelFormatIndex);
-
-      if (!SetPixelFormat(hdc, pixelFormat, NULL))
-        {
-          ErrorF("SetPixelFormat error: %s\n", glxWinErrorMessage());
-          return;
-        }
-    }
-}
-
-static HDC
-glxWinMakeDC(__GLXWinContext *gc, __GLXWinDrawable *draw, HDC *hdc, HWND *hwnd)
-{
-  *hdc = NULL;
-  *hwnd = NULL;
-
-  if (draw == NULL)
-    {
-      GLWIN_TRACE_MSG("No drawable for context %p (native ctx %p)", gc, gc->ctx);
-      return NULL;
-    }
-
-  switch (draw->base.type)
-  {
-    case GLX_DRAWABLE_WINDOW:
-    {
-      winWindowInfoRec winInfo;
-      WindowPtr pWin;
-
-      pWin = (WindowPtr) draw->base.pDraw;
-      if (pWin == NULL)
-        {
-          GLWIN_TRACE_MSG("for drawable %p, no WindowPtr", pWin);
-          return NULL;
-        }
-
-      winGetWindowInfo(pWin, &winInfo);
-      *hwnd = winInfo.hwnd;
-
-      if (winInfo.hwnd == NULL)
-        {
-          ErrorF("No HWND error: %s\n", glxWinErrorMessage());
-          return NULL;
-        }
-
-      *hdc = GetDC(winInfo.hwnd);
-
-      if (*hdc == NULL)
-        ErrorF("GetDC error: %s\n", glxWinErrorMessage());
-
-      /* Check if the hwnd has changed... */
-      if (winInfo.hwnd != gc->hwnd)
-        {
-          if (glxWinDebugSettings.enableTrace)
-            GLWIN_DEBUG_HWND(winInfo.hwnd);
-
-          GLWIN_TRACE_MSG("for context %p (native ctx %p), hWnd changed from %p to %p", gc, gc->ctx, gc->hwnd, winInfo.hwnd);
-          gc->hwnd = winInfo.hwnd;
-
-          /* We must select a pixelformat, but SetPixelFormat can only be called once for a window... */
-          glxWinSetPixelFormat(gc, *hdc, 0, GLX_WINDOW_BIT);
-        }
-    }
-    break;
-
-  case GLX_DRAWABLE_PBUFFER:
-    {
-      *hdc = wglGetPbufferDCARBWrapper(draw->hPbuffer);
-
-      if (*hdc == NULL)
-        ErrorF("GetDC (pbuffer) error: %s\n", glxWinErrorMessage());
-    }
-    break;
-
-  case GLX_DRAWABLE_PIXMAP:
-    {
-      *hdc = draw->dibDC;
-    }
-    break;
-
-  default:
-    {
-      ErrorF("glxWinMakeDC: tried to makeDC for unhandled drawable type %d\n", draw->base.type);
-    }
-  }
-
-  if (glxWinDebugSettings.dumpDC)
-    GLWIN_DEBUG_MSG("Got HDC %p", *hdc);
-
-  return *hdc;
-}
-
-static void
-glxWinReleaseDC(HWND hwnd, HDC hdc,__GLXWinDrawable *draw)
-{
-  switch (draw->base.type)
-  {
-    case GLX_DRAWABLE_WINDOW:
-    {
-      ReleaseDC(hwnd, hdc);
-    }
-    break;
-
-  case GLX_DRAWABLE_PBUFFER:
-    {
-      if (!wglReleasePbufferDCARBWrapper(draw->hPbuffer, hdc))
-        {
-          ErrorF("wglReleasePbufferDCARB error: %s\n", glxWinErrorMessage());
-        }
-    }
-    break;
-
-  case GLX_DRAWABLE_PIXMAP:
-    {
-      // don't release DC, the memory DC lives as long as the bitmap
-
-      // We must ensure that all GDI drawing into the bitmap has completed
-      // in case we subsequently access the bits from it
-      GdiFlush();
-    }
-    break;
-
-  default:
-    {
-      ErrorF("glxWinReleaseDC: tried to releaseDC for unhandled drawable type %d\n", draw->base.type);
-    }
-  }
-}
-
-static void
-glxWinDeferredCreateContext(__GLXWinContext *gc, __GLXWinDrawable *draw)
-{
-  HDC dc;
-  HWND hwnd;
-  GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: attach context %p to drawable %p", gc, draw);
-
-  switch (draw->base.type)
-  {
-    case GLX_DRAWABLE_WINDOW:
-    {
-      winWindowInfoRec winInfo;
-      WindowPtr pWin = (WindowPtr) draw->base.pDraw;
-
-      if (!(gc->base.config->drawableType & GLX_WINDOW_BIT))
-        {
-          ErrorF("glxWinDeferredCreateContext: tried to attach a context whose fbConfig doesn't have drawableType GLX_WINDOW_BIT to a GLX_DRAWABLE_WINDOW drawable\n");
-        }
-
-      if (pWin == NULL)
-        {
-          GLWIN_DEBUG_MSG("Deferring until X window is created");
-          return;
-        }
-
-      GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: pWin %p", pWin);
-
-      winGetWindowInfo(pWin, &winInfo);
-      if (winInfo.hwnd == NULL)
-        {
-          GLWIN_DEBUG_MSG("Deferring until native window is created");
-          return;
-        }
-    }
-    break;
-
-    case GLX_DRAWABLE_PBUFFER:
-    {
-      if (draw->hPbuffer == NULL)
-        {
-          __GLXscreen *screen;
-          glxWinScreen *winScreen;
-          int pixelFormat;
-          // XXX: which DC are supposed to use???
-          HDC screenDC = GetDC(NULL);
-
-          if (!(gc->base.config->drawableType & GLX_PBUFFER_BIT))
-            {
-              ErrorF("glxWinDeferredCreateContext: tried to attach a context whose fbConfig doesn't have drawableType GLX_PBUFFER_BIT to a GLX_DRAWABLE_PBUFFER drawable\n");
-            }
-
-          screen = gc->base.pGlxScreen;
-          winScreen = (glxWinScreen *)screen;
-
-          pixelFormat = fbConfigToPixelFormatIndex(screenDC, gc->base.config, GLX_DRAWABLE_PBUFFER, winScreen);
-          if (pixelFormat == 0)
-            {
-              ErrorF("wglChoosePixelFormat error: %s\n", glxWinErrorMessage());
-              return;
-            }
-
-          draw->hPbuffer = wglCreatePbufferARBWrapper(screenDC, pixelFormat, draw->base.pDraw->width, draw->base.pDraw->height, NULL);
-          ReleaseDC(NULL, screenDC);
-
-          if (draw->hPbuffer == NULL)
-            {
-              ErrorF("wglCreatePbufferARBWrapper error: %s\n", glxWinErrorMessage());
-              return;
-            }
-
-          GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: pBuffer %p created for drawable %p", draw->hPbuffer, draw);
-        }
-    }
-    break;
-
-    case GLX_DRAWABLE_PIXMAP:
-    {
-      if (draw->dibDC == NULL)
-        {
-          BITMAPINFOHEADER bmpHeader;
-          void *pBits;
-
-          memset (&bmpHeader, 0, sizeof(BITMAPINFOHEADER));
-          bmpHeader.biSize = sizeof(BITMAPINFOHEADER);
-          bmpHeader.biWidth = draw->base.pDraw->width;
-          bmpHeader.biHeight = draw->base.pDraw->height;
-          bmpHeader.biPlanes = 1;
-          bmpHeader.biBitCount = draw->base.pDraw->bitsPerPixel;
-          bmpHeader.biCompression = BI_RGB;
-
-          if (!(gc->base.config->drawableType & GLX_PIXMAP_BIT))
-            {
-              ErrorF("glxWinDeferredCreateContext: tried to attach a context whose fbConfig doesn't have drawableType GLX_PIXMAP_BIT to a GLX_DRAWABLE_PIXMAP drawable\n");
-            }
-
-          draw->dibDC = CreateCompatibleDC(NULL);
-          if (draw->dibDC == NULL)
-            {
-              ErrorF("CreateCompatibleDC error: %s\n", glxWinErrorMessage());
-              return;
-            }
-
-          draw->hDIB = CreateDIBSection(draw->dibDC, (BITMAPINFO *)&bmpHeader, DIB_RGB_COLORS, &pBits, 0, 0);
-          if (draw->dibDC == NULL)
-            {
-              ErrorF("CreateDIBSection error: %s\n", glxWinErrorMessage());
-              return;
-            }
-
-          // XXX: CreateDIBSection insists on allocating the bitmap memory for us, so we're going to
-          // need some jiggery pokery to point the underlying X Drawable's bitmap at the same set of bits
-          // so that they can be read with XGetImage as well as glReadPixels, assuming the formats are
-          // even compatible ...
-          draw->pOldBits = ((PixmapPtr)draw->base.pDraw)->devPrivate.ptr;
-          ((PixmapPtr)draw->base.pDraw)->devPrivate.ptr = pBits;
-
-          // Select the DIB into the DC
-          draw->hOldDIB = SelectObject(draw->dibDC, draw->hDIB);
-          if (!draw->hOldDIB)
-            {
-              ErrorF("SelectObject error: %s\n", glxWinErrorMessage());
-            }
-
-          // Set the pixel format of the bitmap
-          glxWinSetPixelFormat(gc, draw->dibDC, draw->base.pDraw->bitsPerPixel, GLX_PIXMAP_BIT);
-
-          GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: DIB bitmap %p created for drawable %p", draw->hDIB, draw);
-        }
-    }
-    break;
-
-    default:
-    {
-      ErrorF("glxWinDeferredCreateContext: tried to attach unhandled drawable type %d\n", draw->base.type);
-      return;
-    }
-  }
-
-  dc = glxWinMakeDC(gc, draw, &dc, &hwnd);
-  gc->ctx = wglCreateContext(dc);
-  glxWinReleaseDC(hwnd, dc, draw);
-
-  if (gc->ctx == NULL)
-    {
-      ErrorF("wglCreateContext error: %s\n", glxWinErrorMessage());
-      return;
-    }
-
-  GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: attached context %p to native context %p drawable %p", gc, gc->ctx, draw);
-
-  // if the native context was created successfully, shareLists if needed
-  if (gc->ctx && gc->shareContext)
-    {
-      GLWIN_DEBUG_MSG("glxWinCreateContextReal shareLists with context %p (native ctx %p)", gc->shareContext, gc->shareContext->ctx);
-
-      if (!wglShareLists(gc->shareContext->ctx, gc->ctx))
-        {
-          ErrorF("wglShareLists error: %s\n", glxWinErrorMessage());
-        }
-    }
-}
-
-/* ---------------------------------------------------------------------- */
-/*
- * Context functions
- */
-
-
-/* Context manipulation routines should return TRUE on success, FALSE on failure */
-static int
-glxWinContextMakeCurrent(__GLXcontext *base)
-{
-  __GLXWinContext *gc = (__GLXWinContext *)base;
-  BOOL ret;
-  HDC drawDC;
-  HDC readDC = NULL;
-  __GLXdrawable *drawPriv;
-  __GLXdrawable *readPriv = NULL;
-  HWND hDrawWnd;
-  HWND hReadWnd;
-
-  GLWIN_TRACE_MSG("glxWinContextMakeCurrent context %p (native ctx %p)", gc, gc->ctx);
-  glWinCallDelta();
-
-  /* Keep a note of the last active context in the drawable */
-  drawPriv = gc->base.drawPriv;
-  ((__GLXWinDrawable *)drawPriv)->drawContext = gc;
-
-  if (gc->ctx == NULL)
-    {
-      glxWinDeferredCreateContext(gc, (__GLXWinDrawable *)drawPriv);
-    }
-
-  if (gc->ctx == NULL)
-    {
-      ErrorF("glxWinContextMakeCurrent: Native context is NULL\n");
-      return FALSE;
-    }
-
-  drawDC = glxWinMakeDC(gc, (__GLXWinDrawable *)drawPriv, &drawDC, &hDrawWnd);
-  if (drawDC == NULL)
-    {
-      ErrorF("glxWinMakeDC failed for drawDC\n");
-      return FALSE;
-    }
-
-  if ((gc->base.readPriv != NULL) && (gc->base.readPriv != gc->base.drawPriv))
-    {
-      // XXX: should only occur with WGL_ARB_make_current_read
-      /*
-        If there is a separate read drawable, create a separate read DC, and
-        use the wglMakeContextCurrent extension to make the context current drawing
-        to one DC and reading from the other
-      */
-      readPriv = gc->base.readPriv;
-      readDC = glxWinMakeDC(gc, (__GLXWinDrawable *)readPriv, &readDC, &hReadWnd);
-      if (readDC == NULL)
-        {
-          ErrorF("glxWinMakeDC failed for readDC\n");
-          glxWinReleaseDC(hDrawWnd, drawDC, (__GLXWinDrawable *)drawPriv);
-          return FALSE;
-        }
-
-      ret = wglMakeContextCurrentARBWrapper(drawDC, readDC, gc->ctx);
-      if (!ret)
-        {
-          ErrorF("wglMakeContextCurrentARBWrapper error: %s\n", glxWinErrorMessage());
-        }
-    }
-  else
-    {
-      /* Otherwise, just use wglMakeCurrent */
-      ret = wglMakeCurrent(drawDC, gc->ctx);
-      if (!ret)
-        {
-          ErrorF("wglMakeCurrent error: %s\n", glxWinErrorMessage());
-        }
-    }
-
-  // apparently make current could fail if the context is current in a different thread,
-  // but that shouldn't be able to happen in the current server...
-
-  glxWinReleaseDC(hDrawWnd, drawDC, (__GLXWinDrawable *)drawPriv);
-  if (readDC)
-    glxWinReleaseDC(hReadWnd, readDC, (__GLXWinDrawable *)readPriv);
-
-  return ret;
-}
-
-static int
-glxWinContextLoseCurrent(__GLXcontext *base)
-{
-  BOOL ret;
-  __GLXWinContext *gc = (__GLXWinContext *)base;
-
-  GLWIN_TRACE_MSG("glxWinContextLoseCurrent context %p (native ctx %p)", gc, gc->ctx);
-  glWinCallDelta();
-
-  ret = wglMakeCurrent(NULL, NULL); /* We don't need a DC when setting no current context */
-  if (!ret)
-    ErrorF("glxWinContextLoseCurrent error: %s\n", glxWinErrorMessage());
-
-  __glXLastContext = NULL; /* Mesa does this; why? */
-  // __glXFlushContextCache()
-
-  return TRUE;
-}
-
-static int
-glxWinContextCopy(__GLXcontext *dst_base, __GLXcontext *src_base, unsigned long mask)
-{
-  __GLXWinContext *dst = (__GLXWinContext *)dst_base;
-  __GLXWinContext *src = (__GLXWinContext *)src_base;
-  BOOL ret;
-
-  GLWIN_DEBUG_MSG("glxWinContextCopy");
-
-  ret = wglCopyContext(src->ctx, dst->ctx, mask);
-  if (!ret)
-    {
-      ErrorF("wglCopyContext error: %s\n", glxWinErrorMessage());
-    }
-
-  return ret;
-}
-
-static int
-glxWinContextForceCurrent(__GLXcontext *base)
-{
-  /* wglMakeCurrent always flushes the previous context, so this is equivalent to glxWinContextMakeCurrent */
-  return glxWinContextMakeCurrent(base);
-}
-
-static void
-glxWinContextDestroy(__GLXcontext *base)
-{
-  __GLXWinContext *gc = (__GLXWinContext *)base;
-
-  if (gc != NULL)
-    {
-      GLWIN_DEBUG_MSG("GLXcontext %p destroyed (native ctx %p)", base, gc->ctx);
-
-      if (gc->ctx)
-        {
-          /* It's bad style to delete the context while it's still current */
-          if (wglGetCurrentContext() == gc->ctx)
-            {
-              wglMakeCurrent(NULL, NULL);
-            }
-
-          BOOL ret = wglDeleteContext(gc->ctx);
-          if (!ret)
-            ErrorF("wglDeleteContext error: %s\n", glxWinErrorMessage());
-          gc->ctx = NULL;
-        }
-
-      xfree(gc);
-    }
-}
-
-static __GLXcontext *
-glxWinCreateContext(__GLXscreen *screen,
-                   __GLXconfig *modes,
-                   __GLXcontext *baseShareContext)
-{
-    __GLXWinContext *context;
-    __GLXWinContext *shareContext = (__GLXWinContext *)baseShareContext;
-
-    static __GLXtextureFromPixmap glxWinTextureFromPixmap =
-      {
-        glxWinBindTexImage,
-        glxWinReleaseTexImage
-      };
-
-    context = (__GLXWinContext *)xcalloc(1, sizeof(__GLXWinContext));
-
-    if (!context)
-        return NULL;
-
-    memset(context, 0, sizeof *context);
-    context->base.destroy        = glxWinContextDestroy;
-    context->base.makeCurrent    = glxWinContextMakeCurrent;
-    context->base.loseCurrent    = glxWinContextLoseCurrent;
-    context->base.copy           = glxWinContextCopy;
-    context->base.forceCurrent   = glxWinContextForceCurrent;
-    context->base.textureFromPixmap = &glxWinTextureFromPixmap;
-    context->base.config = modes;
-    context->base.pGlxScreen = screen;
-
-    // actual native GL context creation is deferred until attach()
-    context->ctx = NULL;
-    context->shareContext = shareContext;
-
-    glWinSetupDispatchTable();
-
-    GLWIN_DEBUG_MSG("GLXcontext %p created", context);
-
-    return &(context->base);
-}
-
-/* ---------------------------------------------------------------------- */
-/*
- * Utility functions
- */
-
-static int
-fbConfigToPixelFormat(__GLXconfig *mode, PIXELFORMATDESCRIPTOR *pfdret, int drawableTypeOverride)
-{
-    PIXELFORMATDESCRIPTOR pfd = {
-      sizeof(PIXELFORMATDESCRIPTOR),   /* size of this pfd */
-      1,                     /* version number */
-      PFD_SUPPORT_OPENGL,    /* support OpenGL */
-      PFD_TYPE_RGBA,         /* RGBA type */
-      24,                    /* 24-bit color depth */
-      0, 0, 0, 0, 0, 0,      /* color bits ignored */
-      0,                     /* no alpha buffer */
-      0,                     /* shift bit ignored */
-      0,                     /* no accumulation buffer */
-      0, 0, 0, 0,            /* accum bits ignored */
-      32,                    /* 32-bit z-buffer */
-      0,                     /* no stencil buffer */
-      0,                     /* no auxiliary buffer */
-      PFD_MAIN_PLANE,        /* main layer */
-      0,                     /* reserved */
-      0, 0, 0                /* layer masks ignored */
-    };
-
-    if ((mode->drawableType | drawableTypeOverride) & GLX_WINDOW_BIT)
-      pfd.dwFlags |= PFD_DRAW_TO_WINDOW; /* support window */
-
-    if ((mode->drawableType | drawableTypeOverride) & GLX_PIXMAP_BIT)
-      pfd.dwFlags |= (PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI); /* supports software rendering to bitmap */
-
-    if (mode->stereoMode) {
-        pfd.dwFlags |= PFD_STEREO;
-    }
-    if (mode->doubleBufferMode) {
-        pfd.dwFlags |= PFD_DOUBLEBUFFER;
-    }
-
-    pfd.iPixelType = PFD_TYPE_RGBA;
-    pfd.cColorBits = mode->redBits + mode->greenBits + mode->blueBits;
-    pfd.cRedBits = mode->redBits;
-    pfd.cRedShift = 0; /* FIXME */
-    pfd.cGreenBits = mode->greenBits;
-    pfd.cGreenShift = 0; /* FIXME  */
-    pfd.cBlueBits = mode->blueBits;
-    pfd.cBlueShift = 0; /* FIXME */
-    pfd.cAlphaBits = mode->alphaBits;
-    pfd.cAlphaShift = 0; /* FIXME */
-
-    pfd.cAccumBits = mode->accumRedBits + mode->accumGreenBits + mode->accumBlueBits + mode->accumAlphaBits;
-    pfd.cAccumRedBits = mode->accumRedBits;
-    pfd.cAccumGreenBits = mode->accumGreenBits;
-    pfd.cAccumBlueBits = mode->accumBlueBits;
-    pfd.cAccumAlphaBits = mode->accumAlphaBits;
-
-    pfd.cDepthBits = mode->depthBits;
-    pfd.cStencilBits = mode->stencilBits;
-    pfd.cAuxBuffers = mode->numAuxBuffers;
-
-    /* mode->level ? */
-    /* mode->pixmapMode ? */
-
-    *pfdret = pfd;
-
-    return 0;
-}
-
-#define SET_ATTR_VALUE(attr, value) { attribList[i++] = attr; attribList[i++] = value; assert(i < NUM_ELEMENTS(attribList)); }
-
-static int
-fbConfigToPixelFormatIndex(HDC hdc, __GLXconfig *mode, int drawableTypeOverride, glxWinScreen *winScreen)
-{
-  UINT numFormats;
-  unsigned int i = 0;
-
-  /* convert fbConfig to attr-value list  */
-  int attribList[60];
-
-  SET_ATTR_VALUE(WGL_SUPPORT_OPENGL_ARB, TRUE);
-  SET_ATTR_VALUE(WGL_PIXEL_TYPE_ARB, (mode->visualType == GLX_TRUE_COLOR) ? WGL_TYPE_RGBA_ARB : WGL_TYPE_COLORINDEX_ARB);
-  SET_ATTR_VALUE(WGL_COLOR_BITS_ARB, (mode->visualType == GLX_TRUE_COLOR) ? mode->rgbBits : mode->indexBits);
-  SET_ATTR_VALUE(WGL_RED_BITS_ARB, mode->redBits);
-  SET_ATTR_VALUE(WGL_GREEN_BITS_ARB, mode->greenBits);
-  SET_ATTR_VALUE(WGL_BLUE_BITS_ARB, mode->blueBits);
-  SET_ATTR_VALUE(WGL_ALPHA_BITS_ARB, mode->alphaBits);
-  SET_ATTR_VALUE(WGL_ACCUM_RED_BITS_ARB, mode->accumRedBits);
-  SET_ATTR_VALUE(WGL_ACCUM_GREEN_BITS_ARB, mode->accumGreenBits);
-  SET_ATTR_VALUE(WGL_ACCUM_BLUE_BITS_ARB, mode->accumBlueBits);
-  SET_ATTR_VALUE(WGL_ACCUM_ALPHA_BITS_ARB, mode->accumAlphaBits);
-  SET_ATTR_VALUE(WGL_DEPTH_BITS_ARB, mode->depthBits);
-  SET_ATTR_VALUE(WGL_STENCIL_BITS_ARB, mode->stencilBits);
-  SET_ATTR_VALUE(WGL_AUX_BUFFERS_ARB, mode->numAuxBuffers);
-
-  if (mode->doubleBufferMode)
-    SET_ATTR_VALUE(WGL_DOUBLE_BUFFER_ARB, TRUE);
-
-  if (mode->stereoMode)
-    SET_ATTR_VALUE(WGL_STEREO_ARB, TRUE);
-
-  // Some attributes are only added to the list if the value requested is not 'don't care', as exactly matching that is daft..
-  if (mode->swapMethod == GLX_SWAP_EXCHANGE_OML)
-    SET_ATTR_VALUE(WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB);
-
-  if (mode->swapMethod == GLX_SWAP_COPY_OML)
-    SET_ATTR_VALUE(WGL_SWAP_COPY_ARB, TRUE);
-
-  // XXX: this should probably be the other way around, but that messes up drawableTypeOverride
-  if (mode->visualRating == GLX_SLOW_VISUAL_EXT)
-    SET_ATTR_VALUE(WGL_ACCELERATION_ARB, WGL_NO_ACCELERATION_ARB);
-
-  // must support all the drawable types the mode supports
-  if ((mode->drawableType | drawableTypeOverride) & GLX_WINDOW_BIT)
-    SET_ATTR_VALUE(WGL_DRAW_TO_WINDOW_ARB,TRUE);
-
-  // XXX: this is a horrible hacky heuristic, in fact this whole drawableTypeOverride thing is a bad idea
-  // try to avoid asking for formats which don't exist (by not asking for all when adjusting the config to include the drawableTypeOverride)
-  if (drawableTypeOverride == GLX_WINDOW_BIT)
-    {
-      if (mode->drawableType & GLX_PIXMAP_BIT)
-        SET_ATTR_VALUE(WGL_DRAW_TO_BITMAP_ARB, TRUE);
-
-      if (mode->drawableType & GLX_PBUFFER_BIT)
-        if (winScreen->has_WGL_ARB_pbuffer)
-          SET_ATTR_VALUE(WGL_DRAW_TO_PBUFFER_ARB, TRUE);
-    }
-  else
-    {
-      if (drawableTypeOverride & GLX_PIXMAP_BIT)
-        SET_ATTR_VALUE(WGL_DRAW_TO_BITMAP_ARB, TRUE);
-
-      if (drawableTypeOverride & GLX_PBUFFER_BIT)
-        if (winScreen->has_WGL_ARB_pbuffer)
-          SET_ATTR_VALUE(WGL_DRAW_TO_PBUFFER_ARB, TRUE);
-    }
-
-  SET_ATTR_VALUE(0, 0); // terminator
-
-  /* choose the first match */
-  {
-    int pixelFormatIndex;
-
-    if (!wglChoosePixelFormatARBWrapper(hdc, attribList, NULL, 1, &pixelFormatIndex, &numFormats))
-      {
-        ErrorF("wglChoosePixelFormat error: %s\n", glxWinErrorMessage());
-      }
-    else
-      {
-        if (numFormats > 0)
-          {
-            GLWIN_DEBUG_MSG("wglChoosePixelFormat: chose pixelFormatIndex %d)", pixelFormatIndex);
-            return pixelFormatIndex;
-          }
-        else
-          ErrorF("wglChoosePixelFormat couldn't decide\n");
-      }
-  }
-
-  return 0;
-}
-
-/* ---------------------------------------------------------------------- */
-
-#define BITS_AND_SHIFT_TO_MASK(bits,mask) (((1<<(bits))-1) << (mask))
-
-//
-// Create the GLXconfigs using DescribePixelFormat()
-//
-static void
-glxWinCreateConfigs(HDC hdc, glxWinScreen *screen)
-{
-  GLXWinConfig *c, *result, *prev = NULL;
-  int numConfigs = 0;
-  int i = 0;
-  int n = 0;
-  PIXELFORMATDESCRIPTOR pfd;
-
-  GLWIN_DEBUG_MSG("glxWinCreateConfigs");
-
-  screen->base.numFBConfigs = 0;
-  screen->base.fbconfigs = NULL;
-
-  // get the number of pixelformats
-  numConfigs = DescribePixelFormat(hdc, 1, sizeof(PIXELFORMATDESCRIPTOR), NULL);
-  GLWIN_DEBUG_MSG("DescribePixelFormat says %d possible pixel formats", numConfigs);
-
-  /* alloc */
-  result = xalloc(sizeof(GLXWinConfig) * numConfigs);
-
-  if (NULL == result)
-    {
-      return;
-    }
-
-  memset(result, 0, sizeof(GLXWinConfig) * numConfigs);
-  n = 0;
-
-  /* fill in configs */
-  for (i = 0;  i < numConfigs; i++)
-    {
-      int rc;
-
-      c = &(result[i]);
-      c->base.next = NULL;
-      c->pixelFormatIndex = i+1;
-
-      rc = DescribePixelFormat(hdc, i+1, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
-
-      if (!rc)
-        {
-          ErrorF("DescribePixelFormat failed for index %d, error %s\n", i+1, glxWinErrorMessage());
-          break;
-        }
-
-      if (glxWinDebugSettings.dumpPFD)
-        pfdOut(&pfd);
-
-      if (!(pfd.dwFlags & (PFD_DRAW_TO_WINDOW | PFD_DRAW_TO_BITMAP)) || !(pfd.dwFlags & PFD_SUPPORT_OPENGL))
-        {
-          GLWIN_DEBUG_MSG("pixelFormat %d has unsuitable flags 0x%08lx, skipping", i+1, pfd.dwFlags);
-          continue;
-        }
-
-      c->base.doubleBufferMode = (pfd.dwFlags & PFD_DOUBLEBUFFER) ? GL_TRUE : GL_FALSE;
-      c->base.stereoMode = (pfd.dwFlags & PFD_STEREO) ? GL_TRUE : GL_FALSE;
-
-      c->base.redBits = pfd.cRedBits;
-      c->base.greenBits = pfd.cGreenBits;
-      c->base.blueBits = pfd.cBlueBits;
-      c->base.alphaBits = pfd.cAlphaBits;
-
-      c->base.redMask = BITS_AND_SHIFT_TO_MASK(pfd.cRedBits, pfd.cRedShift);
-      c->base.greenMask =  BITS_AND_SHIFT_TO_MASK(pfd.cGreenBits, pfd.cGreenShift);
-      c->base.blueMask = BITS_AND_SHIFT_TO_MASK(pfd.cBlueBits, pfd.cBlueShift);
-      c->base.alphaMask = BITS_AND_SHIFT_TO_MASK(pfd.cAlphaBits, pfd.cAlphaShift);
-
-      c->base.rgbBits = pfd.cColorBits;
-
-      if (pfd.iPixelType == PFD_TYPE_COLORINDEX)
-        {
-          c->base.indexBits = pfd.cColorBits;
-        }
-      else
-        {
-          c->base.indexBits = 0;
-        }
-
-      c->base.accumRedBits = pfd.cAccumRedBits;
-      c->base.accumGreenBits = pfd.cAccumGreenBits;
-      c->base.accumBlueBits = pfd.cAccumBlueBits;
-      c->base.accumAlphaBits = pfd.cAccumAlphaBits;
-      //  pfd.cAccumBits;
-
-      c->base.depthBits = pfd.cDepthBits;
-      c->base.stencilBits = pfd.cStencilBits;
-      c->base.numAuxBuffers = pfd.cAuxBuffers;
-
-      // pfd.iLayerType; // ignored
-      c->base.level = 0;
-      // pfd.dwLayerMask; // ignored
-      // pfd.dwDamageMask;  // ignored
-
-      c->base.pixmapMode = 0;
-      c->base.visualID = -1;  // will be set by __glXScreenInit()
-
-      /* EXT_visual_rating / GLX 1.2 */
-      if (pfd.dwFlags & PFD_GENERIC_FORMAT)
-        {
-          c->base.visualRating = GLX_SLOW_VISUAL_EXT;
-        }
-      else
-        {
-          // PFD_GENERIC_ACCELERATED is not considered, so this may be MCD or ICD acclerated...
-          c->base.visualRating = GLX_NONE_EXT;
-        }
-
-      /* EXT_visual_info / GLX 1.2 */
-      if (pfd.iPixelType == PFD_TYPE_COLORINDEX)
-        {
-          c->base.visualType = GLX_STATIC_COLOR;
-        }
-      else
-        {
-          c->base.visualType = GLX_TRUE_COLOR;
-        }
-
-      // pfd.dwVisibleMask; ???
-      c->base.transparentPixel = GLX_NONE;
-      c->base.transparentRed = GLX_NONE;
-      c->base.transparentGreen = GLX_NONE;
-      c->base.transparentBlue = GLX_NONE;
-      c->base.transparentAlpha = GLX_NONE;
-      c->base.transparentIndex = GLX_NONE;
-
-      /* ARB_multisample / SGIS_multisample */
-      c->base.sampleBuffers = 0;
-      c->base.samples = 0;
-
-      /* SGIX_fbconfig / GLX 1.3 */
-      c->base.drawableType = (((pfd.dwFlags & PFD_DRAW_TO_WINDOW) ? GLX_WINDOW_BIT : 0)
-                         | ((pfd.dwFlags & PFD_DRAW_TO_BITMAP) ? GLX_PIXMAP_BIT : 0));
-      c->base.renderType = GLX_RGBA_BIT;
-      c->base.xRenderable = GL_TRUE;
-      c->base.fbconfigID = -1; // will be set by __glXScreenInit()
-
-      /* SGIX_pbuffer / GLX 1.3 */
-      // XXX: How can we find these values out ???
-      c->base.maxPbufferWidth = -1;
-      c->base.maxPbufferHeight = -1;
-      c->base.maxPbufferPixels = -1;
-      c->base.optimalPbufferWidth = 0; // there is no optimal value
-      c->base.optimalPbufferHeight = 0;
-
-      /* SGIX_visual_select_group */
-      // arrange for visuals with the best acceleration to be preferred in selection
-      switch (pfd.dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED))
-        {
-        case 0:
-          c->base.visualSelectGroup = 2;
-          break;
-
-        case PFD_GENERIC_ACCELERATED:
-          c->base.visualSelectGroup = 1;
-          break;
-
-        case PFD_GENERIC_FORMAT:
-          c->base.visualSelectGroup = 0;
-          break;
-
-        default:
-          ;
-          // "can't happen"
-        }
-
-      /* OML_swap_method */
-      if (pfd.dwFlags & PFD_SWAP_EXCHANGE)
-        c->base.swapMethod = GLX_SWAP_EXCHANGE_OML;
-      else if (pfd.dwFlags & PFD_SWAP_COPY)
-        c->base.swapMethod = GLX_SWAP_COPY_OML;
-      else
-        c->base.swapMethod = GLX_SWAP_UNDEFINED_OML;
-
-      /* EXT_import_context */
-      c->base.screen = screen->base.pScreen->myNum;
-
-      /* EXT_texture_from_pixmap */
-      c->base.bindToTextureRgb = -1;
-      c->base.bindToTextureRgba = -1;
-      c->base.bindToMipmapTexture = -1;
-      c->base.bindToTextureTargets = -1;
-      c->base.yInverted = -1;
-
-      n++;
-
-      // update previous config to point to this config
-      if (prev)
-        prev->base.next = &(c->base);
-
-      prev = c;
-    }
-
-  GLWIN_DEBUG_MSG("found %d pixelFormats suitable for conversion to fbConfigs", n);
-
-  screen->base.numFBConfigs = n;
-  screen->base.fbconfigs = &(result->base);
-}
-
-// helper function to access an attribute value from an attribute value array by attribute
-static
-int getAttrValue(const int attrs[], int values[], unsigned int num, int attr, int fallback)
-{
-  unsigned int i;
-  for (i = 0; i < num; i++)
-    {
-      if (attrs[i] == attr)
-        {
-          GLWIN_TRACE_MSG("getAttrValue attr 0x%x, value %d", attr, values[i]);
-          return values[i];
-        }
-    }
-
-  ErrorF("getAttrValue failed to find attr 0x%x, using default value %d\n", attr, fallback);
-  return fallback;
-}
-
-//
-// Create the GLXconfigs using wglGetPixelFormatAttribfvARB() extension
-//
-static void
-glxWinCreateConfigsExt(HDC hdc, glxWinScreen *screen)
-{
-  GLXWinConfig *c, *result, *prev = NULL;
-  int i = 0;
-  int n = 0;
-
-  const int attr = WGL_NUMBER_PIXEL_FORMATS_ARB;
-  int numConfigs;
-
-  int attrs[50];
-  unsigned int num_attrs = 0;
-
-  GLWIN_DEBUG_MSG("glxWinCreateConfigsExt");
-
-  screen->base.numFBConfigs = 0;
-  screen->base.fbconfigs = NULL;
-
-  if (!wglGetPixelFormatAttribivARBWrapper(hdc, 0, 0, 1, &attr, &numConfigs))
-    {
-      ErrorF("wglGetPixelFormatAttribivARB failed for WGL_NUMBER_PIXEL_FORMATS_ARB: %s\n", glxWinErrorMessage());
-      return;
-    }
-
-  GLWIN_DEBUG_MSG("wglGetPixelFormatAttribivARB says %d possible pixel formats", numConfigs);
-
-  /* alloc */
-  result = xalloc(sizeof(GLXWinConfig) * numConfigs);
-
-  if (NULL == result)
-    {
-      return;
-    }
-
-  memset(result, 0, sizeof(GLXWinConfig) * numConfigs);
-  n = 0;
-
-#define ADD_ATTR(a) { attrs[num_attrs++] = a; assert(num_attrs < NUM_ELEMENTS(attrs)); }
-
-  ADD_ATTR(WGL_DRAW_TO_WINDOW_ARB);
-  ADD_ATTR(WGL_DRAW_TO_BITMAP_ARB);
-  ADD_ATTR(WGL_ACCELERATION_ARB);
-  ADD_ATTR(WGL_SWAP_LAYER_BUFFERS_ARB);
-  ADD_ATTR(WGL_NUMBER_OVERLAYS_ARB);
-  ADD_ATTR(WGL_NUMBER_UNDERLAYS_ARB);
-  ADD_ATTR(WGL_TRANSPARENT_ARB);
-  ADD_ATTR(WGL_TRANSPARENT_RED_VALUE_ARB);
-  ADD_ATTR(WGL_TRANSPARENT_GREEN_VALUE_ARB);
-  ADD_ATTR(WGL_TRANSPARENT_GREEN_VALUE_ARB);
-  ADD_ATTR(WGL_TRANSPARENT_ALPHA_VALUE_ARB);
-  ADD_ATTR(WGL_SUPPORT_OPENGL_ARB);
-  ADD_ATTR(WGL_DOUBLE_BUFFER_ARB);
-  ADD_ATTR(WGL_STEREO_ARB);
-  ADD_ATTR(WGL_PIXEL_TYPE_ARB);
-  ADD_ATTR(WGL_COLOR_BITS_ARB);
-  ADD_ATTR(WGL_RED_BITS_ARB);
-  ADD_ATTR(WGL_RED_SHIFT_ARB);
-  ADD_ATTR(WGL_GREEN_BITS_ARB);
-  ADD_ATTR(WGL_GREEN_SHIFT_ARB);
-  ADD_ATTR(WGL_BLUE_BITS_ARB);
-  ADD_ATTR(WGL_BLUE_SHIFT_ARB);
-  ADD_ATTR(WGL_ALPHA_BITS_ARB);
-  ADD_ATTR(WGL_ALPHA_SHIFT_ARB);
-  ADD_ATTR(WGL_ACCUM_RED_BITS_ARB);
-  ADD_ATTR(WGL_ACCUM_GREEN_BITS_ARB);
-  ADD_ATTR(WGL_ACCUM_BLUE_BITS_ARB);
-  ADD_ATTR(WGL_ACCUM_ALPHA_BITS_ARB);
-  ADD_ATTR(WGL_DEPTH_BITS_ARB);
-  ADD_ATTR(WGL_STENCIL_BITS_ARB);
-  ADD_ATTR(WGL_AUX_BUFFERS_ARB);
-  ADD_ATTR(WGL_SWAP_METHOD_ARB);
-
-  if (screen->has_WGL_ARB_multisample)
-    {
-      // we may not query these attrs if WGL_ARB_multisample is not offered
-      ADD_ATTR(WGL_SAMPLE_BUFFERS_ARB);
-      ADD_ATTR(WGL_SAMPLES_ARB);
-    }
-
-  if (screen->has_WGL_ARB_render_texture)
-    {
-      // we may not query these attrs if WGL_ARB_render_texture is not offered
-      ADD_ATTR(WGL_BIND_TO_TEXTURE_RGB_ARB);
-      ADD_ATTR(WGL_BIND_TO_TEXTURE_RGBA_ARB);
-    }
-
-  if (screen->has_WGL_ARB_pbuffer)
-    {
-      // we may not query these attrs if WGL_ARB_pbuffer is not offered
-      ADD_ATTR(WGL_DRAW_TO_PBUFFER_ARB);
-      ADD_ATTR(WGL_MAX_PBUFFER_PIXELS_ARB);
-      ADD_ATTR(WGL_MAX_PBUFFER_WIDTH_ARB);
-      ADD_ATTR(WGL_MAX_PBUFFER_HEIGHT_ARB);
-    }
-
-  /* fill in configs */
-  for (i = 0;  i < numConfigs; i++)
-    {
-      int values[num_attrs];
-
-      c = &(result[i]);
-      c->base.next = NULL;
-      c->pixelFormatIndex = i+1;
-
-      if (!wglGetPixelFormatAttribivARBWrapper(hdc, i+1, 0, num_attrs, attrs, values))
-        {
-          ErrorF("wglGetPixelFormatAttribivARB failed for index %d, error %s\n", i+1, glxWinErrorMessage());
-          break;
-        }
-
-#define ATTR_VALUE(a, d) getAttrValue(attrs, values, num_attrs, (a), (d))
-
-      if (!ATTR_VALUE(WGL_SUPPORT_OPENGL_ARB, 0))
-        {
-          GLWIN_DEBUG_MSG("pixelFormat %d isn't WGL_SUPPORT_OPENGL_ARB, skipping", i+1);
-          continue;
-        }
-
-      c->base.doubleBufferMode = ATTR_VALUE(WGL_DOUBLE_BUFFER_ARB, 0) ? GL_TRUE : GL_FALSE;
-      c->base.stereoMode = ATTR_VALUE(WGL_STEREO_ARB, 0) ? GL_TRUE : GL_FALSE;
-
-      c->base.redBits = ATTR_VALUE(WGL_RED_BITS_ARB, 0);
-      c->base.greenBits = ATTR_VALUE(WGL_GREEN_BITS_ARB, 0);
-      c->base.blueBits = ATTR_VALUE(WGL_BLUE_BITS_ARB, 0);
-      c->base.alphaBits = ATTR_VALUE(WGL_ALPHA_BITS_ARB, 0);
-
-      c->base.redMask = BITS_AND_SHIFT_TO_MASK(c->base.redBits, ATTR_VALUE(WGL_RED_SHIFT_ARB, 0));
-      c->base.greenMask = BITS_AND_SHIFT_TO_MASK(c->base.greenBits, ATTR_VALUE(WGL_GREEN_SHIFT_ARB, 0));
-      c->base.blueMask = BITS_AND_SHIFT_TO_MASK(c->base.blueBits, ATTR_VALUE(WGL_BLUE_SHIFT_ARB, 0));
-      c->base.alphaMask = BITS_AND_SHIFT_TO_MASK(c->base.alphaBits, ATTR_VALUE(WGL_ALPHA_SHIFT_ARB, 0));
-
-      switch (ATTR_VALUE(WGL_PIXEL_TYPE_ARB, 0))
-        {
-        case WGL_TYPE_COLORINDEX_ARB:
-          c->base.indexBits = ATTR_VALUE(WGL_COLOR_BITS_ARB, 0);
-          c->base.rgbBits = 0;
-          c->base.visualType = GLX_STATIC_COLOR;
-          break;
-
-        case WGL_TYPE_RGBA_FLOAT_ARB:
-          GLWIN_DEBUG_MSG("pixelFormat %d is WGL_TYPE_RGBA_FLOAT_ARB, skipping", i+1);
-          continue;
-
-        case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
-          GLWIN_DEBUG_MSG("pixelFormat %d is WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT, skipping", i+1);
-          continue;
-
-        case WGL_TYPE_RGBA_ARB:
-          c->base.indexBits = 0;
-          c->base.rgbBits = ATTR_VALUE(WGL_COLOR_BITS_ARB, 0);
-          c->base.visualType = GLX_TRUE_COLOR;
-          break;
-
-        default:
-          ErrorF("wglGetPixelFormatAttribivARB returned unknown value 0x%x for WGL_PIXEL_TYPE_ARB\n", ATTR_VALUE(WGL_PIXEL_TYPE_ARB, 0));
-          continue;
-        }
-
-      c->base.accumRedBits = ATTR_VALUE(WGL_ACCUM_RED_BITS_ARB, 0);
-      c->base.accumGreenBits = ATTR_VALUE(WGL_ACCUM_GREEN_BITS_ARB, 0);
-      c->base.accumBlueBits = ATTR_VALUE(WGL_ACCUM_BLUE_BITS_ARB, 0);
-      c->base.accumAlphaBits = ATTR_VALUE(WGL_ACCUM_ALPHA_BITS_ARB, 0);
-
-      c->base.depthBits = ATTR_VALUE(WGL_DEPTH_BITS_ARB, 0);
-      c->base.stencilBits = ATTR_VALUE(WGL_STENCIL_BITS_ARB, 0);
-      c->base.numAuxBuffers = ATTR_VALUE(WGL_AUX_BUFFERS_ARB, 0);
-
-      {
-        int layers = ATTR_VALUE(WGL_NUMBER_OVERLAYS_ARB,0) + ATTR_VALUE(WGL_NUMBER_UNDERLAYS_ARB, 0);
-
-        if (layers > 0)
-          {
-            ErrorF("pixelFormat %d: has %d overlay, %d underlays which aren't currently handled", i, ATTR_VALUE(WGL_NUMBER_OVERLAYS_ARB,0), ATTR_VALUE(WGL_NUMBER_UNDERLAYS_ARB, 0));
-            // XXX: need to iterate over layers?
-          }
-      }
-      c->base.level = 0;
-
-      c->base.pixmapMode = 0; // ???
-      c->base.visualID = -1;  // will be set by __glXScreenInit()
-
-      /* EXT_visual_rating / GLX 1.2 */
-      switch (ATTR_VALUE(WGL_ACCELERATION_ARB, 0))
-        {
-        default:
-          ErrorF("wglGetPixelFormatAttribivARB returned unknown value 0x%x for WGL_ACCELERATION_ARB\n", ATTR_VALUE(WGL_ACCELERATION_ARB, 0));
-
-        case WGL_NO_ACCELERATION_ARB:
-          c->base.visualRating = GLX_SLOW_VISUAL_EXT;
-          break;
-
-        case WGL_GENERIC_ACCELERATION_ARB:
-        case WGL_FULL_ACCELERATION_ARB:
-          c->base.visualRating = GLX_NONE_EXT;
-          break;
-        }
-
-      /* EXT_visual_info / GLX 1.2 */
-      // c->base.visualType is set above
-      if (ATTR_VALUE(WGL_TRANSPARENT_ARB, 0))
-        {
-          c->base.transparentPixel = (c->base.visualType == GLX_TRUE_COLOR) ? GLX_TRANSPARENT_RGB_EXT : GLX_TRANSPARENT_INDEX_EXT;
-          c->base.transparentRed = ATTR_VALUE(WGL_TRANSPARENT_RED_VALUE_ARB, 0);
-          c->base.transparentGreen = ATTR_VALUE(WGL_TRANSPARENT_GREEN_VALUE_ARB, 0);
-          c->base.transparentBlue = ATTR_VALUE(WGL_TRANSPARENT_BLUE_VALUE_ARB, 0);
-          c->base.transparentAlpha = ATTR_VALUE(WGL_TRANSPARENT_ALPHA_VALUE_ARB, 0);
-          c->base.transparentIndex = ATTR_VALUE(WGL_TRANSPARENT_INDEX_VALUE_ARB, 0);
-        }
-      else
-        {
-          c->base.transparentPixel = GLX_NONE_EXT;
-          c->base.transparentRed = GLX_NONE;
-          c->base.transparentGreen = GLX_NONE;
-          c->base.transparentBlue = GLX_NONE;
-          c->base.transparentAlpha = GLX_NONE;
-          c->base.transparentIndex = GLX_NONE;
-        }
-
-      /* ARB_multisample / SGIS_multisample */
-      if (screen->has_WGL_ARB_multisample)
-        {
-          c->base.sampleBuffers = ATTR_VALUE(WGL_SAMPLE_BUFFERS_ARB, 0);
-          c->base.samples = ATTR_VALUE(WGL_SAMPLES_ARB, 0);
-        }
-      else
-        {
-          c->base.sampleBuffers = 0;
-          c->base.samples = 0;
-        }
-
-      /* SGIX_fbconfig / GLX 1.3 */
-      c->base.drawableType = ((ATTR_VALUE(WGL_DRAW_TO_WINDOW_ARB, 0) ? GLX_WINDOW_BIT : 0)
-                         | (ATTR_VALUE(WGL_DRAW_TO_BITMAP_ARB, 0) ? GLX_PIXMAP_BIT : 0)
-                         | (ATTR_VALUE(WGL_DRAW_TO_PBUFFER_ARB, 0) ? GLX_PBUFFER_BIT : 0));
-      c->base.renderType = GLX_RGBA_BIT | GLX_COLOR_INDEX_BIT; // Hmmm ???
-      c->base.xRenderable = GL_TRUE;
-      c->base.fbconfigID = -1; // will be set by __glXScreenInit()
-
-      /* SGIX_pbuffer / GLX 1.3 */
-      if (screen->has_WGL_ARB_pbuffer)
-        {
-          c->base.maxPbufferWidth = ATTR_VALUE(WGL_MAX_PBUFFER_WIDTH_ARB, -1);
-          c->base.maxPbufferHeight = ATTR_VALUE(WGL_MAX_PBUFFER_HEIGHT_ARB, -1);
-          c->base.maxPbufferPixels =  ATTR_VALUE(WGL_MAX_PBUFFER_PIXELS_ARB, -1);
-        }
-      else
-        {
-          c->base.maxPbufferWidth = -1;
-          c->base.maxPbufferHeight = -1;
-          c->base.maxPbufferPixels =  -1;
-        }
-      c->base.optimalPbufferWidth = 0; // there is no optimal value
-      c->base.optimalPbufferHeight = 0;
-
-      /* SGIX_visual_select_group */
-      // arrange for visuals with the best acceleration to be preferred in selection
-      switch (ATTR_VALUE(WGL_ACCELERATION_ARB, 0))
-        {
-        case WGL_FULL_ACCELERATION_ARB:
-          c->base.visualSelectGroup = 2;
-          break;
-
-        case WGL_GENERIC_ACCELERATION_ARB:
-          c->base.visualSelectGroup = 1;
-          break;
-
-        default:
-        case WGL_NO_ACCELERATION_ARB:
-          c->base.visualSelectGroup = 0;
-          break;
-        }
-
-      /* OML_swap_method */
-      switch (ATTR_VALUE(WGL_SWAP_METHOD_ARB, 0))
-        {
-        case WGL_SWAP_EXCHANGE_ARB:
-          c->base.swapMethod = GLX_SWAP_EXCHANGE_OML;
-          break;
-
-        case WGL_SWAP_COPY_ARB:
-          c->base.swapMethod = GLX_SWAP_COPY_OML;
-          break;
-
-        default:
-          ErrorF("wglGetPixelFormatAttribivARB returned unknown value 0x%x for WGL_SWAP_METHOD_ARB\n", ATTR_VALUE(WGL_SWAP_METHOD_ARB, 0));
-
-        case WGL_SWAP_UNDEFINED_ARB:
-          c->base.swapMethod = GLX_SWAP_UNDEFINED_OML;
-        }
-
-      /* EXT_import_context */
-      c->base.screen = screen->base.pScreen->myNum;
-
-      /* EXT_texture_from_pixmap */
-      /*
-         Mesa's DRI configs always have bindToTextureRgb/Rgba TRUE (see driCreateConfigs(), so setting
-         bindToTextureRgb/bindToTextureRgba to FALSE means that swrast can't find any fbConfigs to use,
-         so setting these to 0, even if we know bindToTexture isn't available, isn't a good idea...
-       */
-      if (screen->has_WGL_ARB_render_texture)
-        {
-          c->base.bindToTextureRgb = ATTR_VALUE(WGL_BIND_TO_TEXTURE_RGB_ARB, -1);
-          c->base.bindToTextureRgba = ATTR_VALUE(WGL_BIND_TO_TEXTURE_RGBA_ARB, -1);
-        }
-      else
-        {
-          c->base.bindToTextureRgb = -1;
-          c->base.bindToTextureRgba = -1;
-        }
-      c->base.bindToMipmapTexture = -1;
-      c->base.bindToTextureTargets = GLX_TEXTURE_1D_BIT_EXT | GLX_TEXTURE_2D_BIT_EXT | GLX_TEXTURE_RECTANGLE_BIT_EXT;
-      c->base.yInverted = -1;
-
-      n++;
-
-      // update previous config to point to this config
-      if (prev)
-        prev->base.next = &(c->base);
-
-      prev = c;
-    }
-
-  screen->base.numFBConfigs = n;
-  screen->base.fbconfigs = &(result->base);
-}
+/*
+ * File: indirect.c
+ * Purpose: A GLX implementation that uses Windows OpenGL library
+ *
+ * Authors: Alexander Gottwald
+ *          Jon TURNEY
+ *
+ * Copyright (c) Jon TURNEY 2009
+ * Copyright (c) Alexander Gottwald 2004
+ *
+ * Portions of this file are copied from GL/apple/indirect.c,
+ * which contains the following copyright:
+ *
+ * Copyright (c) 2007, 2008, 2009 Apple Inc.
+ * Copyright (c) 2004 Torrey T. Lyons. All Rights Reserved.
+ * Copyright (c) 2002 Greg Parker. All Rights Reserved.
+ *
+ * Portions of this file are copied from Mesa's xf86glx.c,
+ * which contains the following copyright:
+ *
+ * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
+ * All Rights Reserved.
+ *
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+  TODO:
+  - hook up remaining unimplemented extensions
+  - research what guarantees glXWaitX, glXWaitGL are supposed to offer, and implement then
+    using GdiFlush and/or glFinish
+  - pbuffer clobbering: we don't get async notification, but can we arrange to emit the
+    event when we notice it's been clobbered? at the very least, check if it's been clobbered
+    before using it?
+  - are the __GLXConfig * we get handed back ones we are made (so we can extend the structure
+    with privates?) Or are they created inside the GLX core as well?
+  - snap winWindowInfoRec, it's just the same as a HWND now...
+*/
+
+/*
+  MSDN clarifications:
+
+  It says SetPixelFormat()'s PIXELFORMATDESCRIPTOR pointer argument has no effect
+  except on metafiles, this seems to mean that as it's ok to supply NULL if the DC
+  is not for a metafile
+
+  wglMakeCurrent ignores the hdc if hglrc is NULL, so wglMakeCurrent(NULL, NULL)
+  is used to make no context current
+
+*/
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+
+#include "glwindows.h"
+#include <glx/glxserver.h>
+#include <glx/glxutil.h>
+#include <glx/extension_string.h>
+#include <GL/internal/glcore.h>
+#include <GL/glxtokens.h>
+
+#include <winpriv.h>
+#include <wgl_ext_api.h>
+
+#define NUM_ELEMENTS(x) (sizeof(x)/ sizeof(x[1]))
+
+/* ---------------------------------------------------------------------- */
+/*
+ *   structure definitions
+ */
+
+typedef struct __GLXWinContext  __GLXWinContext;
+typedef struct __GLXWinDrawable __GLXWinDrawable;
+typedef struct __GLXWinScreen glxWinScreen;
+typedef struct __GLXWinConfig GLXWinConfig;
+
+struct __GLXWinContext {
+  __GLXcontext base;
+  HGLRC ctx;                         /* Windows GL Context */
+  __GLXWinContext *shareContext;     /* Context with which we will share display lists and textures */
+  HWND hwnd;                         /* For detecting when HWND has changed */
+};
+
+struct __GLXWinDrawable
+{
+  __GLXdrawable base;
+  __GLXWinContext *drawContext;
+  __GLXWinContext *readContext;
+
+  /* If this drawable is GLX_DRAWABLE_PBUFFER */
+  HPBUFFERARB hPbuffer;
+
+  /* If this drawable is GLX_DRAWABLE_PIXMAP */
+  HDC dibDC;
+  HBITMAP hDIB;
+  HBITMAP hOldDIB; /* original DIB for DC */
+  void *pOldBits; /* original pBits for this drawable's pixmap */
+};
+
+struct __GLXWinScreen
+{
+  __GLXscreen base;
+
+  /* Supported GLX extensions */
+  unsigned char glx_enable_bits[__GLX_EXT_BYTES];
+
+  Bool has_WGL_ARB_multisample;
+  Bool has_WGL_ARB_pixel_format;
+  Bool has_WGL_ARB_pbuffer;
+  Bool has_WGL_ARB_render_texture;
+
+  /* wrapped screen functions */
+  RealizeWindowProcPtr RealizeWindow;
+  UnrealizeWindowProcPtr UnrealizeWindow;
+  CopyWindowProcPtr CopyWindow;
+};
+
+struct __GLXWinConfig
+{
+  __GLXconfig base;
+  int pixelFormatIndex;
+};
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Various debug helpers
+ */
+
+#define GLWIN_DEBUG_HWND(hwnd)  \
+    if (glxWinDebugSettings.dumpHWND) { \
+        char buffer[1024]; \
+        if (GetWindowText(hwnd, buffer, sizeof(buffer))==0) *buffer=0; \
+        GLWIN_DEBUG_MSG("Got HWND %p for window '%s'", hwnd, buffer); \
+    }
+
+glxWinDebugSettingsRec glxWinDebugSettings = { 0, 0, 0, 0, 0, 0};
+
+static void glxWinInitDebugSettings(void)
+{
+    char *envptr;
+
+    envptr = getenv("GLWIN_ENABLE_DEBUG");
+    if (envptr != NULL)
+        glxWinDebugSettings.enableDebug = (atoi(envptr) == 1);
+
+    envptr = getenv("GLWIN_ENABLE_TRACE");
+    if (envptr != NULL)
+        glxWinDebugSettings.enableTrace = (atoi(envptr) == 1);
+
+    envptr = getenv("GLWIN_DUMP_PFD");
+    if (envptr != NULL)
+        glxWinDebugSettings.dumpPFD = (atoi(envptr) == 1);
+
+    envptr = getenv("GLWIN_DUMP_HWND");
+    if (envptr != NULL)
+        glxWinDebugSettings.dumpHWND = (atoi(envptr) == 1);
+
+    envptr = getenv("GLWIN_DUMP_DC");
+    if (envptr != NULL)
+        glxWinDebugSettings.dumpDC = (atoi(envptr) == 1);
+
+    envptr = getenv("GLWIN_ENABLE_GLCALL_TRACE");
+    if (envptr != NULL)
+        glxWinDebugSettings.enableGLcallTrace = (atoi(envptr) == 1);
+
+    envptr = getenv("GLWIN_ENABLE_WGLCALL_TRACE");
+    if (envptr != NULL)
+        glxWinDebugSettings.enableWGLcallTrace = (atoi(envptr) == 1);
+
+    envptr = getenv("GLWIN_DEBUG_ALL");
+    if (envptr != NULL)
+      {
+        glxWinDebugSettings.enableDebug = 1;
+        glxWinDebugSettings.enableTrace = 1;
+        glxWinDebugSettings.dumpPFD = 1;
+        glxWinDebugSettings.dumpHWND = 1;
+        glxWinDebugSettings.dumpDC = 1;
+        glxWinDebugSettings.enableGLcallTrace = 1;
+        glxWinDebugSettings.enableWGLcallTrace = 1;
+      }
+}
+
+static
+const char *glxWinErrorMessage(void)
+{
+  static char errorbuffer[1024];
+
+  if (!FormatMessage(
+                     FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+                     NULL,
+                     GetLastError(),
+                     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                     (LPTSTR) &errorbuffer,
+                     sizeof(errorbuffer),
+                     NULL ))
+    {
+      snprintf(errorbuffer, sizeof(errorbuffer), "Unknown error in FormatMessage: %08x!", (unsigned)GetLastError());
+    }
+
+  if (errorbuffer[strlen(errorbuffer)-1] == '\n')
+    errorbuffer[strlen(errorbuffer)-1] = 0;
+
+  return errorbuffer;
+}
+
+static void pfdOut(const PIXELFORMATDESCRIPTOR *pfd);
+
+#define DUMP_PFD_FLAG(flag) \
+    if (pfd->dwFlags & flag) { \
+        ErrorF("%s%s", pipesym, #flag); \
+        pipesym = " | "; \
+    }
+
+static void pfdOut(const PIXELFORMATDESCRIPTOR *pfd)
+{
+    const char *pipesym = ""; /* will be set after first flag dump */
+    ErrorF("PIXELFORMATDESCRIPTOR:\n");
+    ErrorF("nSize = %u\n", pfd->nSize);
+    ErrorF("nVersion = %u\n", pfd->nVersion);
+    ErrorF("dwFlags = %lu = {", pfd->dwFlags);
+        DUMP_PFD_FLAG(PFD_DOUBLEBUFFER);
+        DUMP_PFD_FLAG(PFD_STEREO);
+        DUMP_PFD_FLAG(PFD_DRAW_TO_WINDOW);
+        DUMP_PFD_FLAG(PFD_DRAW_TO_BITMAP);
+        DUMP_PFD_FLAG(PFD_SUPPORT_GDI);
+        DUMP_PFD_FLAG(PFD_SUPPORT_OPENGL);
+        DUMP_PFD_FLAG(PFD_GENERIC_FORMAT);
+        DUMP_PFD_FLAG(PFD_NEED_PALETTE);
+        DUMP_PFD_FLAG(PFD_NEED_SYSTEM_PALETTE);
+        DUMP_PFD_FLAG(PFD_SWAP_EXCHANGE);
+        DUMP_PFD_FLAG(PFD_SWAP_COPY);
+        DUMP_PFD_FLAG(PFD_SWAP_LAYER_BUFFERS);
+        DUMP_PFD_FLAG(PFD_GENERIC_ACCELERATED);
+        DUMP_PFD_FLAG(PFD_DEPTH_DONTCARE);
+        DUMP_PFD_FLAG(PFD_DOUBLEBUFFER_DONTCARE);
+        DUMP_PFD_FLAG(PFD_STEREO_DONTCARE);
+    ErrorF("}\n");
+
+    ErrorF("iPixelType = %hu = %s\n", pfd->iPixelType,
+            (pfd->iPixelType == PFD_TYPE_RGBA ? "PFD_TYPE_RGBA" : "PFD_TYPE_COLORINDEX"));
+    ErrorF("cColorBits = %hhu\n", pfd->cColorBits);
+    ErrorF("cRedBits = %hhu\n", pfd->cRedBits);
+    ErrorF("cRedShift = %hhu\n", pfd->cRedShift);
+    ErrorF("cGreenBits = %hhu\n", pfd->cGreenBits);
+    ErrorF("cGreenShift = %hhu\n", pfd->cGreenShift);
+    ErrorF("cBlueBits = %hhu\n", pfd->cBlueBits);
+    ErrorF("cBlueShift = %hhu\n", pfd->cBlueShift);
+    ErrorF("cAlphaBits = %hhu\n", pfd->cAlphaBits);
+    ErrorF("cAlphaShift = %hhu\n", pfd->cAlphaShift);
+    ErrorF("cAccumBits = %hhu\n", pfd->cAccumBits);
+    ErrorF("cAccumRedBits = %hhu\n", pfd->cAccumRedBits);
+    ErrorF("cAccumGreenBits = %hhu\n", pfd->cAccumGreenBits);
+    ErrorF("cAccumBlueBits = %hhu\n", pfd->cAccumBlueBits);
+    ErrorF("cAccumAlphaBits = %hhu\n", pfd->cAccumAlphaBits);
+    ErrorF("cDepthBits = %hhu\n", pfd->cDepthBits);
+    ErrorF("cStencilBits = %hhu\n", pfd->cStencilBits);
+    ErrorF("cAuxBuffers = %hhu\n", pfd->cAuxBuffers);
+    ErrorF("iLayerType = %hhu\n", pfd->iLayerType);
+    ErrorF("bReserved = %hhu\n", pfd->bReserved);
+    ErrorF("dwLayerMask = %lu\n", pfd->dwLayerMask);
+    ErrorF("dwVisibleMask = %lu\n", pfd->dwVisibleMask);
+    ErrorF("dwDamageMask = %lu\n", pfd->dwDamageMask);
+    ErrorF("\n");
+}
+
+static const char *
+visual_class_name(int cls)
+{
+  switch (cls) {
+  case GLX_STATIC_COLOR:
+    return "StaticColor";
+  case GLX_PSEUDO_COLOR:
+    return "PseudoColor";
+  case GLX_STATIC_GRAY:
+    return "StaticGray";
+  case GLX_GRAY_SCALE:
+    return "GrayScale";
+  case GLX_TRUE_COLOR:
+     return "TrueColor";
+  case GLX_DIRECT_COLOR:
+     return "DirectColor";
+  default:
+    return "-none-";
+  }
+}
+
+static const char *
+swap_method_name(int mthd)
+{
+  switch (mthd)
+    {
+    case GLX_SWAP_EXCHANGE_OML:
+      return "xchg";
+    case GLX_SWAP_COPY_OML:
+      return "copy";
+    case GLX_SWAP_UNDEFINED_OML:
+      return "    ";
+    default:
+      return "????";
+    }
+}
+
+static void
+fbConfigsDump(unsigned int n, __GLXconfig *c)
+{
+  ErrorF("%d fbConfigs\n", n);
+  ErrorF("pxf vis  fb                      render         Ste                     aux    accum        MS    drawable             Group/\n");
+  ErrorF("idx  ID  ID VisualType Depth Lvl RGB CI DB Swap reo  R  G  B  A   Z  S  buf AR AG AB AA  bufs num  W P Pb  Float Trans Caveat\n");
+  ErrorF("-----------------------------------------------------------------------------------------------------------------------------\n");
+
+  while (c != NULL)
+    {
+      unsigned int i = ((GLXWinConfig *)c)->pixelFormatIndex;
+
+      ErrorF("%3d  %2x  %2x "
+             "%-11s"
+             " %3d %3d   %s   %s  %s %s  %s  "
+             "%2d %2d %2d %2d  "
+             "%2d %2d  "
+             "%2d  "
+             "%2d %2d %2d %2d"
+             "   %2d   %2d"
+             "  %s %s %s "
+             "    %s   "
+             "  %s   "
+             "  %d %s"
+             "\n",
+             i, c->visualID, c->fbconfigID,
+             visual_class_name(c->visualType),
+             c->rgbBits ? c->rgbBits : c->indexBits,
+             c->level,
+	     (c->renderType & GLX_RGBA_BIT) ? "y" : ".",
+	     (c->renderType & GLX_COLOR_INDEX_BIT) ? "y" : ".",
+	     c->doubleBufferMode ? "y" : ".",
+             swap_method_name(c->swapMethod),
+	     c->stereoMode ? "y" : ".",
+             c->redBits, c->greenBits, c->blueBits, c->alphaBits,
+             c->depthBits, c->stencilBits,
+             c->numAuxBuffers,
+             c->accumRedBits, c->accumGreenBits, c->accumBlueBits, c->accumAlphaBits,
+             c->sampleBuffers, c->samples,
+             (c->drawableType & GLX_WINDOW_BIT) ? "y" : ".",
+             (c->drawableType & GLX_PIXMAP_BIT) ? "y" : ".",
+             (c->drawableType & GLX_PBUFFER_BIT) ? "y" : ".",
+             ".",
+             (c->transparentPixel != GLX_NONE_EXT) ? "y" : ".",
+             c->visualSelectGroup, (c->visualRating == GLX_SLOW_VISUAL_EXT) ? "*" : " ");
+
+      c = c->next;
+    }
+}
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Forward declarations
+ */
+
+static __GLXscreen *glxWinScreenProbe(ScreenPtr pScreen);
+static __GLXcontext *glxWinCreateContext(__GLXscreen *screen,
+                                        __GLXconfig *modes,
+                                        __GLXcontext *baseShareContext);
+static __GLXdrawable *glxWinCreateDrawable(__GLXscreen *screen,
+                                          DrawablePtr pDraw,
+                                          int type,
+                                          XID drawId,
+                                          __GLXconfig *conf);
+
+static Bool glxWinRealizeWindow(WindowPtr pWin);
+static Bool glxWinUnrealizeWindow(WindowPtr pWin);
+static void glxWinCopyWindow(WindowPtr pWindow, DDXPointRec ptOldOrg, RegionPtr prgnSrc);
+
+static HDC glxWinMakeDC(__GLXWinContext *gc, __GLXWinDrawable *draw, HDC *hdc, HWND *hwnd);
+static void glxWinReleaseDC(HWND hwnd, HDC hdc, __GLXWinDrawable *draw);
+
+static void glxWinCreateConfigs(HDC dc, glxWinScreen *screen);
+static void glxWinCreateConfigsExt(HDC hdc, glxWinScreen *screen);
+static int fbConfigToPixelFormat(__GLXconfig *mode, PIXELFORMATDESCRIPTOR *pfdret, int drawableTypeOverride);
+static int fbConfigToPixelFormatIndex(HDC hdc, __GLXconfig *mode, int drawableTypeOverride, glxWinScreen *winScreen);
+
+/* ---------------------------------------------------------------------- */
+/*
+ * The GLX provider
+ */
+
+__GLXprovider __glXWGLProvider = {
+    glxWinScreenProbe,
+    "Win32 native WGL",
+    NULL
+};
+
+void
+glxWinPushNativeProvider(void)
+{
+  GlxPushProvider(&__glXWGLProvider);
+}
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Screen functions
+ */
+
+static void
+glxWinScreenDestroy(__GLXscreen *screen)
+{
+    GLWIN_DEBUG_MSG("glxWinScreenDestroy(%p)", screen);
+    __glXScreenDestroy(screen);
+    xfree(screen);
+}
+
+static int
+glxWinScreenSwapInterval(__GLXdrawable *drawable, int interval)
+{
+  BOOL ret = wglSwapIntervalEXTWrapper(interval);
+  if (!ret)
+    {
+      ErrorF("wglSwapIntervalEXT interval %d failed:%s\n", interval, glxWinErrorMessage());
+    }
+  return ret;
+}
+
+/*
+  Report the extensions split and formatted to avoid overflowing a line
+ */
+static void
+glxLogExtensions(const char *prefix, const char *extensions)
+{
+  int length = 0;
+  char *strl;
+  char *str = xalloc(strlen(extensions) + 1);
+
+  if (str == NULL)
+    {
+      ErrorF("glxLogExtensions: xalloc error\n");
+      return;
+    }
+
+  str[strlen(extensions)] = '\0';
+  strncpy (str, extensions, strlen(extensions));
+
+  strl = strtok(str, " ");
+  ErrorF("%s%s", prefix, strl);
+  length = strlen(prefix) + strlen(strl);
+
+  while (1)
+    {
+      strl = strtok(NULL, " ");
+      if (strl == NULL) break;
+
+      if (length + strlen(strl) + 1 > 120)
+        {
+          ErrorF("\n%s",prefix);
+          length = strlen(prefix);
+        }
+      else
+        {
+          ErrorF(" ");
+          length++;
+        }
+
+      ErrorF("%s", strl);
+      length = length + strlen(strl);
+    }
+
+  ErrorF("\n");
+
+  xfree(str);
+}
+
+/* This is called by GlxExtensionInit() asking the GLX provider if it can handle the screen... */
+static __GLXscreen *
+glxWinScreenProbe(ScreenPtr pScreen)
+{
+    glxWinScreen *screen;
+    const char *gl_extensions;
+    const char *wgl_extensions;
+    HWND hwnd;
+    HDC hdc;
+    HGLRC hglrc;
+
+    GLWIN_DEBUG_MSG("glxWinScreenProbe");
+
+    glxWinInitDebugSettings();
+
+    if (pScreen == NULL)
+	return NULL;
+
+    if (!winCheckScreenAiglxIsSupported(pScreen))
+      {
+        LogMessage(X_ERROR,"AIGLX: No native OpenGL in modes with a root window\n");
+        return NULL;
+      }
+
+    screen = xcalloc(1, sizeof(glxWinScreen));
+
+    if (NULL == screen)
+	return NULL;
+
+    /* Wrap RealizeWindow, UnrealizeWindow and CopyWindow on this screen */
+    screen->RealizeWindow = pScreen->RealizeWindow;
+    pScreen->RealizeWindow = glxWinRealizeWindow;
+    screen->UnrealizeWindow = pScreen->UnrealizeWindow;
+    pScreen->UnrealizeWindow = glxWinUnrealizeWindow;
+    screen->CopyWindow = pScreen->CopyWindow;
+    pScreen->CopyWindow = glxWinCopyWindow;
+
+    /* Dump out some useful information about the native renderer */
+
+    // create window class
+#define WIN_GL_TEST_WINDOW_CLASS "XWinGLTest"
+    {
+      static wATOM glTestWndClass = 0;
+      if (glTestWndClass == 0)
+        {
+          WNDCLASSEX wc;
+          wc.cbSize = sizeof(WNDCLASSEX);
+          wc.style = CS_HREDRAW | CS_VREDRAW;
+          wc.lpfnWndProc = DefWindowProc;
+          wc.cbClsExtra = 0;
+          wc.cbWndExtra = 0;
+          wc.hInstance = GetModuleHandle(NULL);
+          wc.hIcon = 0;
+          wc.hCursor = 0;
+          wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
+          wc.lpszMenuName = NULL;
+          wc.lpszClassName = WIN_GL_TEST_WINDOW_CLASS;
+          wc.hIconSm = 0;
+          RegisterClassEx (&wc);
+      }
+    }
+
+    // create an invisible window for a scratch DC
+    hwnd = CreateWindowExA(0,
+                           WIN_GL_TEST_WINDOW_CLASS,
+                           "XWin GL Renderer Capabilities Test Window",
+                           0, 0, 0, 0, 0, NULL, NULL, GetModuleHandle(NULL), NULL);
+    if (hwnd == NULL)
+      LogMessage(X_ERROR,"AIGLX: Couldn't create a window for render capabilities testing\n");
+
+    hdc = GetDC(hwnd);
+
+    // we must set a pixel format before we can create a context, just use the first one...
+    SetPixelFormat(hdc, 1, NULL);
+    hglrc = wglCreateContext(hdc);
+    wglMakeCurrent(hdc, hglrc);
+
+    // initialize wgl extension proc pointers (don't call them before here...)
+    // (but we need to have a current context for them to be resolvable)
+    wglResolveExtensionProcs();
+
+    ErrorF("GL_VERSION:     %s\n", glGetStringWrapperNonstatic(GL_VERSION));
+    ErrorF("GL_VENDOR:      %s\n", glGetStringWrapperNonstatic(GL_VENDOR));
+    ErrorF("GL_RENDERER:    %s\n", glGetStringWrapperNonstatic(GL_RENDERER));
+    gl_extensions = (const char *)glGetStringWrapperNonstatic(GL_EXTENSIONS);
+    glxLogExtensions("GL_EXTENSIONS:  ", gl_extensions);
+    wgl_extensions = wglGetExtensionsStringARBWrapper(hdc);
+    if (!wgl_extensions) wgl_extensions = "";
+    glxLogExtensions("WGL_EXTENSIONS: ", wgl_extensions);
+
+    // Can you see the problem here?  The extensions string is DC specific
+    // Different DCs for windows on a multimonitor system driven by multiple cards
+    // might have completely different capabilities.  Of course, good luck getting
+    // those screens to be accelerated in XP and earlier...
+
+    {
+      // testing facility to not use any WGL extensions
+      char *envptr = getenv("GLWIN_NO_WGL_EXTENSIONS");
+      if ((envptr != NULL) && (atoi(envptr) != 0))
+        {
+          ErrorF("GLWIN_NO_WGL_EXTENSIONS is set, ignoring WGL_EXTENSIONS\n");
+          wgl_extensions = "";
+        }
+    }
+
+    {
+      Bool glx_sgi_make_current_read = FALSE;
+
+      //
+      // Based on the WGL extensions available, enable various GLX extensions
+      // XXX: make this table-driven ?
+      //
+      memset(screen->glx_enable_bits, 0, __GLX_EXT_BYTES);
+
+      __glXEnableExtension(screen->glx_enable_bits, "GLX_EXT_visual_info");
+      __glXEnableExtension(screen->glx_enable_bits, "GLX_EXT_visual_rating");
+      __glXEnableExtension(screen->glx_enable_bits, "GLX_EXT_import_context");
+      __glXEnableExtension(screen->glx_enable_bits, "GLX_OML_swap_method");
+      __glXEnableExtension(screen->glx_enable_bits, "GLX_SGIX_fbconfig");
+
+      if (strstr(wgl_extensions, "WGL_ARB_make_current_read"))
+        {
+          __glXEnableExtension(screen->glx_enable_bits, "GLX_SGI_make_current_read");
+          LogMessage(X_INFO, "AIGLX: enabled GLX_SGI_make_current_read\n");
+          glx_sgi_make_current_read = TRUE;
+        }
+
+      if (strstr(gl_extensions, "GL_WIN_swap_hint"))
+        {
+          __glXEnableExtension(screen->glx_enable_bits, "GLX_MESA_copy_sub_buffer");
+          LogMessage(X_INFO, "AIGLX: enabled GLX_MESA_copy_sub_buffer\n");
+        }
+
+      if (strstr(wgl_extensions, "WGL_EXT_swap_control"))
+        {
+          __glXEnableExtension(screen->glx_enable_bits, "GLX_SGI_swap_control");
+          __glXEnableExtension(screen->glx_enable_bits, "GLX_MESA_swap_control");
+          LogMessage(X_INFO, "AIGLX: enabled GLX_SGI_swap_control and GLX_MESA_swap_control\n");
+        }
+
+/*       // Hmm?  screen->texOffset */
+/*       if (strstr(wgl_extensions, "WGL_ARB_render_texture")) */
+/*         { */
+/*           __glXEnableExtension(screen->glx_enable_bits, "GLX_EXT_texture_from_pixmap"); */
+/*           LogMessage(X_INFO, "AIGLX: GLX_EXT_texture_from_pixmap backed by buffer objects\n"); */
+/*           screen->has_WGL_ARB_render_texture = TRUE; */
+/*         } */
+
+      if (strstr(wgl_extensions, "WGL_ARB_pbuffer"))
+        {
+          __glXEnableExtension(screen->glx_enable_bits, "GLX_SGIX_pbuffer");
+          LogMessage(X_INFO, "AIGLX: enabled GLX_SGIX_pbuffer\n");
+          screen->has_WGL_ARB_pbuffer = TRUE;
+        }
+
+      if (strstr(wgl_extensions, "WGL_ARB_multisample"))
+        {
+          __glXEnableExtension(screen->glx_enable_bits, "GLX_ARB_multisample");
+          __glXEnableExtension(screen->glx_enable_bits, "GLX_SGIS_multisample");
+          LogMessage(X_INFO, "AIGLX: enabled GLX_ARB_multisample and GLX_SGIS_multisample\n");
+          screen->has_WGL_ARB_multisample = TRUE;
+        }
+
+      screen->base.destroy = glxWinScreenDestroy;
+      screen->base.createContext = glxWinCreateContext;
+      screen->base.createDrawable = glxWinCreateDrawable;
+      screen->base.swapInterval = glxWinScreenSwapInterval;
+      screen->base.hyperpipeFuncs = NULL;
+      screen->base.swapBarrierFuncs = NULL;
+      screen->base.pScreen = pScreen;
+
+      if (strstr(wgl_extensions, "WGL_ARB_pixel_format"))
+        {
+          glxWinCreateConfigsExt(hdc, screen);
+          screen->has_WGL_ARB_pixel_format = TRUE;
+        }
+      else
+        {
+          glxWinCreateConfigs(hdc, screen);
+          screen->has_WGL_ARB_pixel_format = FALSE;
+        }
+      // Initializes screen->base.fbconfigs and screen->base.numFBConfigs
+
+      /* These will be set by __glXScreenInit */
+      screen->base.visuals = NULL;
+      screen->base.numVisuals = 0;
+
+      __glXScreenInit(&screen->base, pScreen);
+
+      // dump out fbConfigs now fbConfigIds and visualIDs have been assigned
+      fbConfigsDump(screen->base.numFBConfigs, screen->base.fbconfigs);
+
+      // Override the GL extensions string set by __glXScreenInit()
+      screen->base.GLextensions = xstrdup(gl_extensions);
+
+      // Generate the GLX extensions string (overrides that set by __glXScreenInit())
+      {
+        unsigned int buffer_size = __glXGetExtensionString(screen->glx_enable_bits, NULL);
+        if (buffer_size > 0)
+          {
+            if (screen->base.GLXextensions != NULL)
+              {
+                xfree(screen->base.GLXextensions);
+              }
+
+            screen->base.GLXextensions = xnfalloc(buffer_size);
+            __glXGetExtensionString(screen->glx_enable_bits, screen->base.GLXextensions);
+          }
+      }
+
+      //
+      // Override the GLX version (__glXScreenInit() sets it to "1.2")
+      // if we have all the needed extensionsto operate as a higher version
+      //
+      // SGIX_fbconfig && SGIX_pbuffer && SGI_make_current_read -> 1.3
+      // ARB_multisample -> 1.4
+      //
+      if (screen->has_WGL_ARB_pbuffer && glx_sgi_make_current_read)
+        {
+          xfree(screen->base.GLXversion);
+
+          if (screen->has_WGL_ARB_multisample)
+            {
+              screen->base.GLXversion = xstrdup("1.4");
+              screen->base.GLXmajor = 1;
+              screen->base.GLXminor = 4;
+            }
+          else
+            {
+              screen->base.GLXversion = xstrdup("1.3");
+              screen->base.GLXmajor = 1;
+              screen->base.GLXminor = 3;
+            }
+          LogMessage(X_INFO, "AIGLX: Set GLX version to %s\n", screen->base.GLXversion);
+        }
+    }
+
+    wglMakeCurrent(NULL, NULL);
+    wglDeleteContext(hglrc);
+    ReleaseDC(hwnd, hdc);
+    DestroyWindow(hwnd);
+
+    return &screen->base;
+}
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Window functions
+ */
+
+static Bool
+glxWinRealizeWindow(WindowPtr pWin)
+{
+    Bool result;
+    ScreenPtr pScreen = pWin->drawable.pScreen;
+    glxWinScreen *screenPriv = (glxWinScreen *) glxGetScreen(pScreen);
+
+    GLWIN_DEBUG_MSG("glxWinRealizeWindow");
+
+    /* Allow the window to be created (RootlessRealizeWindow is inside our wrap) */
+    pScreen->RealizeWindow = screenPriv->RealizeWindow;
+    result = pScreen->RealizeWindow(pWin);
+    pScreen->RealizeWindow = glxWinRealizeWindow;
+
+    return result;
+}
+
+
+static void
+glxWinCopyWindow(WindowPtr pWindow, DDXPointRec ptOldOrg, RegionPtr prgnSrc)
+{
+    __GLXWinDrawable *pGlxDraw;
+    ScreenPtr pScreen = pWindow->drawable.pScreen;
+    glxWinScreen *screenPriv = (glxWinScreen *) glxGetScreen(pScreen);
+
+    GLWIN_TRACE_MSG("glxWinCopyWindow pWindow %p", pWindow);
+
+    dixLookupResourceByType((pointer) &pGlxDraw, pWindow->drawable.id, __glXDrawableRes,
+				NullClient, DixUnknownAccess);
+
+
+    /*
+       Discard any CopyWindow requests if a GL drawing context is pointing at the window
+
+       For regions which are being drawn by GL, the shadow framebuffer doesn't have the
+       correct bits, so we wish to avoid shadow framebuffer damage occuring, which will
+       cause those incorrect bits to be transferred to the display....
+    */
+    if (pGlxDraw && pGlxDraw->drawContext)
+      {
+        GLWIN_DEBUG_MSG("glxWinCopyWindow: discarding");
+        return;
+      }
+
+    GLWIN_DEBUG_MSG("glxWinCopyWindow - passing to hw layer");
+
+    pScreen->CopyWindow = screenPriv->CopyWindow;
+    pScreen->CopyWindow(pWindow, ptOldOrg, prgnSrc);
+    pScreen->CopyWindow = glxWinCopyWindow;
+}
+
+static Bool
+glxWinUnrealizeWindow(WindowPtr pWin)
+{
+    Bool result;
+    ScreenPtr pScreen = pWin->drawable.pScreen;
+    glxWinScreen *screenPriv = (glxWinScreen *)glxGetScreen(pScreen);
+
+    GLWIN_DEBUG_MSG("glxWinUnrealizeWindow");
+
+    pScreen->UnrealizeWindow = screenPriv->UnrealizeWindow;
+    result = pScreen->UnrealizeWindow(pWin);
+    pScreen->UnrealizeWindow = glxWinUnrealizeWindow;
+
+    return result;
+}
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Drawable functions
+ */
+
+static GLboolean
+glxWinDrawableSwapBuffers(ClientPtr client, __GLXdrawable *base)
+{
+    HDC dc;
+    HWND hwnd;
+    BOOL ret;
+    __GLXWinDrawable *draw = (__GLXWinDrawable *)base;
+
+    /* Swap buffers on the last active context for drawing on the drawable */
+    if (draw->drawContext == NULL)
+      {
+        GLWIN_TRACE_MSG("glxWinSwapBuffers - no context for drawable");
+        return GL_FALSE;
+      }
+
+    GLWIN_TRACE_MSG("glxWinSwapBuffers on drawable %p, last context %p (native ctx %p)", base, draw->drawContext, draw->drawContext->ctx);
+
+    /*
+       draw->drawContext->base.drawPriv will not be set if the context is not current anymore,
+       but if it is, it should point to this drawable....
+    */
+    assert((draw->drawContext->base.drawPriv == NULL) || (draw->drawContext->base.drawPriv == base));
+
+    dc = glxWinMakeDC(draw->drawContext, draw, &dc, &hwnd);
+    if (dc == NULL)
+      return GL_FALSE;
+
+    ret = wglSwapLayerBuffers(dc, WGL_SWAP_MAIN_PLANE);
+
+    glxWinReleaseDC(hwnd, dc, draw);
+
+    if (!ret)
+      {
+        ErrorF("wglSwapBuffers failed: %s\n", glxWinErrorMessage());
+        return GL_FALSE;
+      }
+
+    return GL_TRUE;
+}
+
+static void
+glxWinDrawableCopySubBuffer(__GLXdrawable *drawable,
+                            int x, int y, int w, int h)
+{
+  glAddSwapHintRectWINWrapperNonstatic(x, y, w, h);
+  glxWinDrawableSwapBuffers(NULL, drawable);
+}
+
+static void
+glxWinDrawableDestroy(__GLXdrawable *base)
+{
+  __GLXWinDrawable *glxPriv = (__GLXWinDrawable *)base;
+
+  if (glxPriv->drawContext && (__glXLastContext == &((glxPriv->drawContext)->base)))
+    {
+      // if this context is current and has unflushed commands, say we have flushed them
+      // (don't actually flush them, the window is going away anyhow, and an implict flush occurs
+      // on the next context change)
+      // (GLX core considers it an error when we try to select a new current context if the old one
+      // has unflushed commands, but the window has disappeared..)
+      __GLX_NOTE_FLUSHED_CMDS(__glXLastContext);
+      __glXLastContext = NULL;
+    }
+
+  if (glxPriv->hPbuffer)
+    if (!wglDestroyPbufferARBWrapper(glxPriv->hPbuffer))
+      {
+        ErrorF("wglDestroyPbufferARB failed: %s\n", glxWinErrorMessage());
+      }
+
+  if (glxPriv->dibDC)
+    {
+      // restore the default DIB
+      SelectObject(glxPriv->dibDC, glxPriv->hOldDIB);
+
+      if (!DeleteDC(glxPriv->dibDC))
+        {
+          ErrorF("DeleteDC failed: %s\n", glxWinErrorMessage());
+        }
+    }
+
+  if (glxPriv->hDIB)
+    {
+      if (!DeleteObject(glxPriv->hDIB))
+        {
+          ErrorF("DeleteObject failed: %s\n", glxWinErrorMessage());
+        }
+
+      ((PixmapPtr)glxPriv->base.pDraw)->devPrivate.ptr = glxPriv->pOldBits;
+    }
+
+  GLWIN_DEBUG_MSG("glxWinDestroyDrawable");
+  xfree(glxPriv);
+}
+
+static __GLXdrawable *
+glxWinCreateDrawable(__GLXscreen *screen,
+                    DrawablePtr pDraw,
+                    int type,
+                    XID drawId,
+                    __GLXconfig *conf)
+{
+  __GLXWinDrawable *glxPriv;
+
+  glxPriv = xalloc(sizeof *glxPriv);
+
+  if (glxPriv == NULL)
+      return NULL;
+
+  memset(glxPriv, 0, sizeof *glxPriv);
+
+  if(!__glXDrawableInit(&glxPriv->base, screen, pDraw, type, drawId, conf)) {
+    xfree(glxPriv);
+    return NULL;
+  }
+
+  glxPriv->base.destroy       = glxWinDrawableDestroy;
+  glxPriv->base.swapBuffers   = glxWinDrawableSwapBuffers;
+  glxPriv->base.copySubBuffer = glxWinDrawableCopySubBuffer;
+  // glxPriv->base.waitX  what are these for?
+  // glxPriv->base.waitGL
+
+  GLWIN_DEBUG_MSG("glxWinCreateDrawable %p", glxPriv);
+
+  return &glxPriv->base;
+}
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Texture functions
+ */
+
+static
+int glxWinBindTexImage(__GLXcontext  *baseContext,
+                      int            buffer,
+                      __GLXdrawable *pixmap)
+{
+  ErrorF("glxWinBindTexImage: not implemented\n");
+  return FALSE;
+}
+
+static
+int glxWinReleaseTexImage(__GLXcontext  *baseContext,
+                         int            buffer,
+                         __GLXdrawable *pixmap)
+{
+  ErrorF(" glxWinReleaseTexImage: not implemented\n");
+  return FALSE;
+}
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Lazy update context implementation
+ *
+ * WGL contexts are created for a specific HDC, so we cannot create the WGL
+ * context in glxWinCreateContext(), we must defer creation until the context
+ * is actually used on a specifc drawable which is connected to a native window,
+ * pbuffer or DIB
+ *
+ * The WGL context may be used on other, compatible HDCs, so we don't need to
+ * recreate it for every new native window
+ *
+ * XXX: I wonder why we can't create the WGL context on the screen HDC ?
+ * Basically we assume all HDCs are compatible at the moment: if they are not
+ * we are in a muddle, there was some code in the old implementation to attempt
+ * to transparently migrate a context to a new DC by copying state and sharing
+ * lists with the old one...
+ */
+
+static void
+glxWinSetPixelFormat(__GLXWinContext *gc, HDC hdc, int bppOverride, int drawableTypeOverride)
+{
+  __GLXscreen *screen = gc->base.pGlxScreen;
+  glxWinScreen *winScreen = (glxWinScreen *)screen;
+
+  __GLXconfig *config = gc->base.config;
+  GLXWinConfig *winConfig = (GLXWinConfig *)config;
+
+  GLWIN_DEBUG_MSG("glxWinSetPixelFormat: pixelFormatIndex %d", winConfig->pixelFormatIndex);
+
+  /*
+    Normally, we can just use the the pixelFormatIndex corresponding
+    to the fbconfig which has been specified by the client
+  */
+
+  if (!((bppOverride && (bppOverride != (config->redBits + config->greenBits + config->blueBits) ))
+        || ((config->drawableType & drawableTypeOverride) == 0)))
+    {
+      if (!SetPixelFormat(hdc, winConfig->pixelFormatIndex, NULL))
+        {
+          ErrorF("SetPixelFormat error: %s\n", glxWinErrorMessage());
+          return;
+        }
+
+      return;
+    }
+
+  /*
+    However, in certain special cases this pixel format will be incompatible with the
+    use we are going to put it to, so we need to re-evaluate the pixel format to use:
+
+    1) When PFD_DRAW_TO_BITMAP is set, ChoosePixelFormat() always returns a format with
+       the cColorBits we asked for, so we need to ensure it matches the bpp of the bitmap
+
+    2) Applications may assume that visuals selected with glXChooseVisual() work with
+       pixmap drawables (there is no attribute to explicitly query for pixmap drawable
+       support as there is for glXChooseFBConfig())
+       (it's arguable this is an error in the application, but we try to make it work)
+
+       pixmap rendering is always slow for us, so we don't want to choose those visuals
+       by default, but if the actual drawable type we're trying to select the context
+       on (drawableTypeOverride) isn't supported by the selected fbConfig, reconsider
+       and see if we can find a suitable one...
+   */
+  ErrorF("glxWinSetPixelFormat: having second thoughts: cColorbits %d, bppOveride %d; config->drawableType %d, drawableTypeOverride %d\n",
+         (config->redBits + config->greenBits + config->blueBits), bppOverride, config->drawableType, drawableTypeOverride);
+
+  if (!winScreen->has_WGL_ARB_pixel_format)
+    {
+      PIXELFORMATDESCRIPTOR pfd;
+      int pixelFormat;
+
+      /* convert fbConfig to PFD */
+      if (fbConfigToPixelFormat(gc->base.config, &pfd, drawableTypeOverride))
+        {
+          ErrorF("glxWinSetPixelFormat: fbConfigToPixelFormat failed\n");
+          return;
+        }
+
+      if (glxWinDebugSettings.dumpPFD)
+        pfdOut(&pfd);
+
+      if (bppOverride)
+        {
+          GLWIN_DEBUG_MSG("glxWinSetPixelFormat: Forcing bpp from %d to %d\n", pfd.cColorBits, bppOverride);
+          pfd.cColorBits = bppOverride;
+        }
+
+      pixelFormat = ChoosePixelFormat(hdc, &pfd);
+      if (pixelFormat == 0)
+        {
+          ErrorF("ChoosePixelFormat error: %s\n", glxWinErrorMessage());
+          return;
+        }
+
+      GLWIN_DEBUG_MSG("ChoosePixelFormat: chose pixelFormatIndex %d", pixelFormat);
+      ErrorF("ChoosePixelFormat: chose pixelFormatIndex %d (rather than %d as originally planned)\n", pixelFormat, winConfig->pixelFormatIndex);
+
+      if (!SetPixelFormat(hdc, pixelFormat, &pfd))
+        {
+          ErrorF("SetPixelFormat error: %s\n", glxWinErrorMessage());
+          return;
+        }
+    }
+  else
+    {
+      int pixelFormat = fbConfigToPixelFormatIndex(hdc, gc->base.config, drawableTypeOverride, winScreen);
+      if (pixelFormat == 0)
+        {
+          ErrorF("wglChoosePixelFormat error: %s\n", glxWinErrorMessage());
+          return;
+        }
+
+      GLWIN_DEBUG_MSG("wglChoosePixelFormat: chose pixelFormatIndex %d", pixelFormat);
+      ErrorF("wglChoosePixelFormat: chose pixelFormatIndex %d (rather than %d as originally planned)\n", pixelFormat, winConfig->pixelFormatIndex);
+
+      if (!SetPixelFormat(hdc, pixelFormat, NULL))
+        {
+          ErrorF("SetPixelFormat error: %s\n", glxWinErrorMessage());
+          return;
+        }
+    }
+}
+
+static HDC
+glxWinMakeDC(__GLXWinContext *gc, __GLXWinDrawable *draw, HDC *hdc, HWND *hwnd)
+{
+  *hdc = NULL;
+  *hwnd = NULL;
+
+  if (draw == NULL)
+    {
+      GLWIN_TRACE_MSG("No drawable for context %p (native ctx %p)", gc, gc->ctx);
+      return NULL;
+    }
+
+  switch (draw->base.type)
+  {
+    case GLX_DRAWABLE_WINDOW:
+    {
+      winWindowInfoRec winInfo;
+      WindowPtr pWin;
+
+      pWin = (WindowPtr) draw->base.pDraw;
+      if (pWin == NULL)
+        {
+          GLWIN_TRACE_MSG("for drawable %p, no WindowPtr", pWin);
+          return NULL;
+        }
+
+      winGetWindowInfo(pWin, &winInfo);
+      *hwnd = winInfo.hwnd;
+
+      if (winInfo.hwnd == NULL)
+        {
+          ErrorF("No HWND error: %s\n", glxWinErrorMessage());
+          return NULL;
+        }
+
+      *hdc = GetDC(winInfo.hwnd);
+
+      if (*hdc == NULL)
+        ErrorF("GetDC error: %s\n", glxWinErrorMessage());
+
+      /* Check if the hwnd has changed... */
+      if (winInfo.hwnd != gc->hwnd)
+        {
+          if (glxWinDebugSettings.enableTrace)
+            GLWIN_DEBUG_HWND(winInfo.hwnd);
+
+          GLWIN_TRACE_MSG("for context %p (native ctx %p), hWnd changed from %p to %p", gc, gc->ctx, gc->hwnd, winInfo.hwnd);
+          gc->hwnd = winInfo.hwnd;
+
+          /* We must select a pixelformat, but SetPixelFormat can only be called once for a window... */
+          glxWinSetPixelFormat(gc, *hdc, 0, GLX_WINDOW_BIT);
+        }
+    }
+    break;
+
+  case GLX_DRAWABLE_PBUFFER:
+    {
+      *hdc = wglGetPbufferDCARBWrapper(draw->hPbuffer);
+
+      if (*hdc == NULL)
+        ErrorF("GetDC (pbuffer) error: %s\n", glxWinErrorMessage());
+    }
+    break;
+
+  case GLX_DRAWABLE_PIXMAP:
+    {
+      *hdc = draw->dibDC;
+    }
+    break;
+
+  default:
+    {
+      ErrorF("glxWinMakeDC: tried to makeDC for unhandled drawable type %d\n", draw->base.type);
+    }
+  }
+
+  if (glxWinDebugSettings.dumpDC)
+    GLWIN_DEBUG_MSG("Got HDC %p", *hdc);
+
+  return *hdc;
+}
+
+static void
+glxWinReleaseDC(HWND hwnd, HDC hdc,__GLXWinDrawable *draw)
+{
+  switch (draw->base.type)
+  {
+    case GLX_DRAWABLE_WINDOW:
+    {
+      ReleaseDC(hwnd, hdc);
+    }
+    break;
+
+  case GLX_DRAWABLE_PBUFFER:
+    {
+      if (!wglReleasePbufferDCARBWrapper(draw->hPbuffer, hdc))
+        {
+          ErrorF("wglReleasePbufferDCARB error: %s\n", glxWinErrorMessage());
+        }
+    }
+    break;
+
+  case GLX_DRAWABLE_PIXMAP:
+    {
+      // don't release DC, the memory DC lives as long as the bitmap
+
+      // We must ensure that all GDI drawing into the bitmap has completed
+      // in case we subsequently access the bits from it
+      GdiFlush();
+    }
+    break;
+
+  default:
+    {
+      ErrorF("glxWinReleaseDC: tried to releaseDC for unhandled drawable type %d\n", draw->base.type);
+    }
+  }
+}
+
+static void
+glxWinDeferredCreateContext(__GLXWinContext *gc, __GLXWinDrawable *draw)
+{
+  HDC dc;
+  HWND hwnd;
+  GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: attach context %p to drawable %p", gc, draw);
+
+  switch (draw->base.type)
+  {
+    case GLX_DRAWABLE_WINDOW:
+    {
+      winWindowInfoRec winInfo;
+      WindowPtr pWin = (WindowPtr) draw->base.pDraw;
+
+      if (!(gc->base.config->drawableType & GLX_WINDOW_BIT))
+        {
+          ErrorF("glxWinDeferredCreateContext: tried to attach a context whose fbConfig doesn't have drawableType GLX_WINDOW_BIT to a GLX_DRAWABLE_WINDOW drawable\n");
+        }
+
+      if (pWin == NULL)
+        {
+          GLWIN_DEBUG_MSG("Deferring until X window is created");
+          return;
+        }
+
+      GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: pWin %p", pWin);
+
+      winGetWindowInfo(pWin, &winInfo);
+      if (winInfo.hwnd == NULL)
+        {
+          GLWIN_DEBUG_MSG("Deferring until native window is created");
+          return;
+        }
+    }
+    break;
+
+    case GLX_DRAWABLE_PBUFFER:
+    {
+      if (draw->hPbuffer == NULL)
+        {
+          __GLXscreen *screen;
+          glxWinScreen *winScreen;
+          int pixelFormat;
+          // XXX: which DC are supposed to use???
+          HDC screenDC = GetDC(NULL);
+
+          if (!(gc->base.config->drawableType & GLX_PBUFFER_BIT))
+            {
+              ErrorF("glxWinDeferredCreateContext: tried to attach a context whose fbConfig doesn't have drawableType GLX_PBUFFER_BIT to a GLX_DRAWABLE_PBUFFER drawable\n");
+            }
+
+          screen = gc->base.pGlxScreen;
+          winScreen = (glxWinScreen *)screen;
+
+          pixelFormat = fbConfigToPixelFormatIndex(screenDC, gc->base.config, GLX_DRAWABLE_PBUFFER, winScreen);
+          if (pixelFormat == 0)
+            {
+              ErrorF("wglChoosePixelFormat error: %s\n", glxWinErrorMessage());
+              return;
+            }
+
+          draw->hPbuffer = wglCreatePbufferARBWrapper(screenDC, pixelFormat, draw->base.pDraw->width, draw->base.pDraw->height, NULL);
+          ReleaseDC(NULL, screenDC);
+
+          if (draw->hPbuffer == NULL)
+            {
+              ErrorF("wglCreatePbufferARBWrapper error: %s\n", glxWinErrorMessage());
+              return;
+            }
+
+          GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: pBuffer %p created for drawable %p", draw->hPbuffer, draw);
+        }
+    }
+    break;
+
+    case GLX_DRAWABLE_PIXMAP:
+    {
+      if (draw->dibDC == NULL)
+        {
+          BITMAPINFOHEADER bmpHeader;
+          void *pBits;
+
+          memset (&bmpHeader, 0, sizeof(BITMAPINFOHEADER));
+          bmpHeader.biSize = sizeof(BITMAPINFOHEADER);
+          bmpHeader.biWidth = draw->base.pDraw->width;
+          bmpHeader.biHeight = draw->base.pDraw->height;
+          bmpHeader.biPlanes = 1;
+          bmpHeader.biBitCount = draw->base.pDraw->bitsPerPixel;
+          bmpHeader.biCompression = BI_RGB;
+
+          if (!(gc->base.config->drawableType & GLX_PIXMAP_BIT))
+            {
+              ErrorF("glxWinDeferredCreateContext: tried to attach a context whose fbConfig doesn't have drawableType GLX_PIXMAP_BIT to a GLX_DRAWABLE_PIXMAP drawable\n");
+            }
+
+          draw->dibDC = CreateCompatibleDC(NULL);
+          if (draw->dibDC == NULL)
+            {
+              ErrorF("CreateCompatibleDC error: %s\n", glxWinErrorMessage());
+              return;
+            }
+
+          draw->hDIB = CreateDIBSection(draw->dibDC, (BITMAPINFO *)&bmpHeader, DIB_RGB_COLORS, &pBits, 0, 0);
+          if (draw->dibDC == NULL)
+            {
+              ErrorF("CreateDIBSection error: %s\n", glxWinErrorMessage());
+              return;
+            }
+
+          // XXX: CreateDIBSection insists on allocating the bitmap memory for us, so we're going to
+          // need some jiggery pokery to point the underlying X Drawable's bitmap at the same set of bits
+          // so that they can be read with XGetImage as well as glReadPixels, assuming the formats are
+          // even compatible ...
+          draw->pOldBits = ((PixmapPtr)draw->base.pDraw)->devPrivate.ptr;
+          ((PixmapPtr)draw->base.pDraw)->devPrivate.ptr = pBits;
+
+          // Select the DIB into the DC
+          draw->hOldDIB = SelectObject(draw->dibDC, draw->hDIB);
+          if (!draw->hOldDIB)
+            {
+              ErrorF("SelectObject error: %s\n", glxWinErrorMessage());
+            }
+
+          // Set the pixel format of the bitmap
+          glxWinSetPixelFormat(gc, draw->dibDC, draw->base.pDraw->bitsPerPixel, GLX_PIXMAP_BIT);
+
+          GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: DIB bitmap %p created for drawable %p", draw->hDIB, draw);
+        }
+    }
+    break;
+
+    default:
+    {
+      ErrorF("glxWinDeferredCreateContext: tried to attach unhandled drawable type %d\n", draw->base.type);
+      return;
+    }
+  }
+
+  dc = glxWinMakeDC(gc, draw, &dc, &hwnd);
+  gc->ctx = wglCreateContext(dc);
+  glxWinReleaseDC(hwnd, dc, draw);
+
+  if (gc->ctx == NULL)
+    {
+      ErrorF("wglCreateContext error: %s\n", glxWinErrorMessage());
+      return;
+    }
+
+  GLWIN_DEBUG_MSG("glxWinDeferredCreateContext: attached context %p to native context %p drawable %p", gc, gc->ctx, draw);
+
+  // if the native context was created successfully, shareLists if needed
+  if (gc->ctx && gc->shareContext)
+    {
+      GLWIN_DEBUG_MSG("glxWinCreateContextReal shareLists with context %p (native ctx %p)", gc->shareContext, gc->shareContext->ctx);
+
+      if (!wglShareLists(gc->shareContext->ctx, gc->ctx))
+        {
+          ErrorF("wglShareLists error: %s\n", glxWinErrorMessage());
+        }
+    }
+}
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Context functions
+ */
+
+
+/* Context manipulation routines should return TRUE on success, FALSE on failure */
+static int
+glxWinContextMakeCurrent(__GLXcontext *base)
+{
+  __GLXWinContext *gc = (__GLXWinContext *)base;
+  BOOL ret;
+  HDC drawDC;
+  HDC readDC = NULL;
+  __GLXdrawable *drawPriv;
+  __GLXdrawable *readPriv = NULL;
+  HWND hDrawWnd;
+  HWND hReadWnd;
+
+  GLWIN_TRACE_MSG("glxWinContextMakeCurrent context %p (native ctx %p)", gc, gc->ctx);
+  glWinCallDelta();
+
+  /* Keep a note of the last active context in the drawable */
+  drawPriv = gc->base.drawPriv;
+  ((__GLXWinDrawable *)drawPriv)->drawContext = gc;
+
+  if (gc->ctx == NULL)
+    {
+      glxWinDeferredCreateContext(gc, (__GLXWinDrawable *)drawPriv);
+    }
+
+  if (gc->ctx == NULL)
+    {
+      ErrorF("glxWinContextMakeCurrent: Native context is NULL\n");
+      return FALSE;
+    }
+
+  drawDC = glxWinMakeDC(gc, (__GLXWinDrawable *)drawPriv, &drawDC, &hDrawWnd);
+  if (drawDC == NULL)
+    {
+      ErrorF("glxWinMakeDC failed for drawDC\n");
+      return FALSE;
+    }
+
+  if ((gc->base.readPriv != NULL) && (gc->base.readPriv != gc->base.drawPriv))
+    {
+      // XXX: should only occur with WGL_ARB_make_current_read
+      /*
+        If there is a separate read drawable, create a separate read DC, and
+        use the wglMakeContextCurrent extension to make the context current drawing
+        to one DC and reading from the other
+      */
+      readPriv = gc->base.readPriv;
+      readDC = glxWinMakeDC(gc, (__GLXWinDrawable *)readPriv, &readDC, &hReadWnd);
+      if (readDC == NULL)
+        {
+          ErrorF("glxWinMakeDC failed for readDC\n");
+          glxWinReleaseDC(hDrawWnd, drawDC, (__GLXWinDrawable *)drawPriv);
+          return FALSE;
+        }
+
+      ret = wglMakeContextCurrentARBWrapper(drawDC, readDC, gc->ctx);
+      if (!ret)
+        {
+          ErrorF("wglMakeContextCurrentARBWrapper error: %s\n", glxWinErrorMessage());
+        }
+    }
+  else
+    {
+      /* Otherwise, just use wglMakeCurrent */
+      ret = wglMakeCurrent(drawDC, gc->ctx);
+      if (!ret)
+        {
+          ErrorF("wglMakeCurrent error: %s\n", glxWinErrorMessage());
+        }
+    }
+
+  // apparently make current could fail if the context is current in a different thread,
+  // but that shouldn't be able to happen in the current server...
+
+  glxWinReleaseDC(hDrawWnd, drawDC, (__GLXWinDrawable *)drawPriv);
+  if (readDC)
+    glxWinReleaseDC(hReadWnd, readDC, (__GLXWinDrawable *)readPriv);
+
+  return ret;
+}
+
+static int
+glxWinContextLoseCurrent(__GLXcontext *base)
+{
+  BOOL ret;
+  __GLXWinContext *gc = (__GLXWinContext *)base;
+
+  GLWIN_TRACE_MSG("glxWinContextLoseCurrent context %p (native ctx %p)", gc, gc->ctx);
+  glWinCallDelta();
+
+  ret = wglMakeCurrent(NULL, NULL); /* We don't need a DC when setting no current context */
+  if (!ret)
+    ErrorF("glxWinContextLoseCurrent error: %s\n", glxWinErrorMessage());
+
+  __glXLastContext = NULL; /* Mesa does this; why? */
+  // __glXFlushContextCache()
+
+  return TRUE;
+}
+
+static int
+glxWinContextCopy(__GLXcontext *dst_base, __GLXcontext *src_base, unsigned long mask)
+{
+  __GLXWinContext *dst = (__GLXWinContext *)dst_base;
+  __GLXWinContext *src = (__GLXWinContext *)src_base;
+  BOOL ret;
+
+  GLWIN_DEBUG_MSG("glxWinContextCopy");
+
+  ret = wglCopyContext(src->ctx, dst->ctx, mask);
+  if (!ret)
+    {
+      ErrorF("wglCopyContext error: %s\n", glxWinErrorMessage());
+    }
+
+  return ret;
+}
+
+static int
+glxWinContextForceCurrent(__GLXcontext *base)
+{
+  /* wglMakeCurrent always flushes the previous context, so this is equivalent to glxWinContextMakeCurrent */
+  return glxWinContextMakeCurrent(base);
+}
+
+static void
+glxWinContextDestroy(__GLXcontext *base)
+{
+  __GLXWinContext *gc = (__GLXWinContext *)base;
+
+  if (gc != NULL)
+    {
+      GLWIN_DEBUG_MSG("GLXcontext %p destroyed (native ctx %p)", base, gc->ctx);
+
+      if (gc->ctx)
+        {
+          /* It's bad style to delete the context while it's still current */
+          if (wglGetCurrentContext() == gc->ctx)
+            {
+              wglMakeCurrent(NULL, NULL);
+            }
+
+          {
+            BOOL ret = wglDeleteContext(gc->ctx);
+            if (!ret)
+              ErrorF("wglDeleteContext error: %s\n", glxWinErrorMessage());
+          }
+
+          gc->ctx = NULL;
+        }
+
+      xfree(gc);
+    }
+}
+
+static __GLXcontext *
+glxWinCreateContext(__GLXscreen *screen,
+                   __GLXconfig *modes,
+                   __GLXcontext *baseShareContext)
+{
+    __GLXWinContext *context;
+    __GLXWinContext *shareContext = (__GLXWinContext *)baseShareContext;
+
+    static __GLXtextureFromPixmap glxWinTextureFromPixmap =
+      {
+        glxWinBindTexImage,
+        glxWinReleaseTexImage
+      };
+
+    context = (__GLXWinContext *)xcalloc(1, sizeof(__GLXWinContext));
+
+    if (!context)
+        return NULL;
+
+    memset(context, 0, sizeof *context);
+    context->base.destroy        = glxWinContextDestroy;
+    context->base.makeCurrent    = glxWinContextMakeCurrent;
+    context->base.loseCurrent    = glxWinContextLoseCurrent;
+    context->base.copy           = glxWinContextCopy;
+    context->base.forceCurrent   = glxWinContextForceCurrent;
+    context->base.textureFromPixmap = &glxWinTextureFromPixmap;
+    context->base.config = modes;
+    context->base.pGlxScreen = screen;
+
+    // actual native GL context creation is deferred until attach()
+    context->ctx = NULL;
+    context->shareContext = shareContext;
+
+    glWinSetupDispatchTable();
+
+    GLWIN_DEBUG_MSG("GLXcontext %p created", context);
+
+    return &(context->base);
+}
+
+/* ---------------------------------------------------------------------- */
+/*
+ * Utility functions
+ */
+
+static int
+fbConfigToPixelFormat(__GLXconfig *mode, PIXELFORMATDESCRIPTOR *pfdret, int drawableTypeOverride)
+{
+    PIXELFORMATDESCRIPTOR pfd = {
+      sizeof(PIXELFORMATDESCRIPTOR),   /* size of this pfd */
+      1,                     /* version number */
+      PFD_SUPPORT_OPENGL,    /* support OpenGL */
+      PFD_TYPE_RGBA,         /* RGBA type */
+      24,                    /* 24-bit color depth */
+      0, 0, 0, 0, 0, 0,      /* color bits ignored */
+      0,                     /* no alpha buffer */
+      0,                     /* shift bit ignored */
+      0,                     /* no accumulation buffer */
+      0, 0, 0, 0,            /* accum bits ignored */
+      32,                    /* 32-bit z-buffer */
+      0,                     /* no stencil buffer */
+      0,                     /* no auxiliary buffer */
+      PFD_MAIN_PLANE,        /* main layer */
+      0,                     /* reserved */
+      0, 0, 0                /* layer masks ignored */
+    };
+
+    if ((mode->drawableType | drawableTypeOverride) & GLX_WINDOW_BIT)
+      pfd.dwFlags |= PFD_DRAW_TO_WINDOW; /* support window */
+
+    if ((mode->drawableType | drawableTypeOverride) & GLX_PIXMAP_BIT)
+      pfd.dwFlags |= (PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI); /* supports software rendering to bitmap */
+
+    if (mode->stereoMode) {
+        pfd.dwFlags |= PFD_STEREO;
+    }
+    if (mode->doubleBufferMode) {
+        pfd.dwFlags |= PFD_DOUBLEBUFFER;
+    }
+
+    pfd.iPixelType = PFD_TYPE_RGBA;
+    pfd.cColorBits = mode->redBits + mode->greenBits + mode->blueBits;
+    pfd.cRedBits = mode->redBits;
+    pfd.cRedShift = 0; /* FIXME */
+    pfd.cGreenBits = mode->greenBits;
+    pfd.cGreenShift = 0; /* FIXME  */
+    pfd.cBlueBits = mode->blueBits;
+    pfd.cBlueShift = 0; /* FIXME */
+    pfd.cAlphaBits = mode->alphaBits;
+    pfd.cAlphaShift = 0; /* FIXME */
+
+    pfd.cAccumBits = mode->accumRedBits + mode->accumGreenBits + mode->accumBlueBits + mode->accumAlphaBits;
+    pfd.cAccumRedBits = mode->accumRedBits;
+    pfd.cAccumGreenBits = mode->accumGreenBits;
+    pfd.cAccumBlueBits = mode->accumBlueBits;
+    pfd.cAccumAlphaBits = mode->accumAlphaBits;
+
+    pfd.cDepthBits = mode->depthBits;
+    pfd.cStencilBits = mode->stencilBits;
+    pfd.cAuxBuffers = mode->numAuxBuffers;
+
+    /* mode->level ? */
+    /* mode->pixmapMode ? */
+
+    *pfdret = pfd;
+
+    return 0;
+}
+
+#define SET_ATTR_VALUE(attr, value) { attribList[i++] = attr; attribList[i++] = value; assert(i < NUM_ELEMENTS(attribList)); }
+
+static int
+fbConfigToPixelFormatIndex(HDC hdc, __GLXconfig *mode, int drawableTypeOverride, glxWinScreen *winScreen)
+{
+  UINT numFormats;
+  unsigned int i = 0;
+
+  /* convert fbConfig to attr-value list  */
+  int attribList[60];
+
+  SET_ATTR_VALUE(WGL_SUPPORT_OPENGL_ARB, TRUE);
+  SET_ATTR_VALUE(WGL_PIXEL_TYPE_ARB, (mode->visualType == GLX_TRUE_COLOR) ? WGL_TYPE_RGBA_ARB : WGL_TYPE_COLORINDEX_ARB);
+  SET_ATTR_VALUE(WGL_COLOR_BITS_ARB, (mode->visualType == GLX_TRUE_COLOR) ? mode->rgbBits : mode->indexBits);
+  SET_ATTR_VALUE(WGL_RED_BITS_ARB, mode->redBits);
+  SET_ATTR_VALUE(WGL_GREEN_BITS_ARB, mode->greenBits);
+  SET_ATTR_VALUE(WGL_BLUE_BITS_ARB, mode->blueBits);
+  SET_ATTR_VALUE(WGL_ALPHA_BITS_ARB, mode->alphaBits);
+  SET_ATTR_VALUE(WGL_ACCUM_RED_BITS_ARB, mode->accumRedBits);
+  SET_ATTR_VALUE(WGL_ACCUM_GREEN_BITS_ARB, mode->accumGreenBits);
+  SET_ATTR_VALUE(WGL_ACCUM_BLUE_BITS_ARB, mode->accumBlueBits);
+  SET_ATTR_VALUE(WGL_ACCUM_ALPHA_BITS_ARB, mode->accumAlphaBits);
+  SET_ATTR_VALUE(WGL_DEPTH_BITS_ARB, mode->depthBits);
+  SET_ATTR_VALUE(WGL_STENCIL_BITS_ARB, mode->stencilBits);
+  SET_ATTR_VALUE(WGL_AUX_BUFFERS_ARB, mode->numAuxBuffers);
+
+  if (mode->doubleBufferMode)
+    SET_ATTR_VALUE(WGL_DOUBLE_BUFFER_ARB, TRUE);
+
+  if (mode->stereoMode)
+    SET_ATTR_VALUE(WGL_STEREO_ARB, TRUE);
+
+  // Some attributes are only added to the list if the value requested is not 'don't care', as exactly matching that is daft..
+  if (mode->swapMethod == GLX_SWAP_EXCHANGE_OML)
+    SET_ATTR_VALUE(WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB);
+
+  if (mode->swapMethod == GLX_SWAP_COPY_OML)
+    SET_ATTR_VALUE(WGL_SWAP_COPY_ARB, TRUE);
+
+  // XXX: this should probably be the other way around, but that messes up drawableTypeOverride
+  if (mode->visualRating == GLX_SLOW_VISUAL_EXT)
+    SET_ATTR_VALUE(WGL_ACCELERATION_ARB, WGL_NO_ACCELERATION_ARB);
+
+  // must support all the drawable types the mode supports
+  if ((mode->drawableType | drawableTypeOverride) & GLX_WINDOW_BIT)
+    SET_ATTR_VALUE(WGL_DRAW_TO_WINDOW_ARB,TRUE);
+
+  // XXX: this is a horrible hacky heuristic, in fact this whole drawableTypeOverride thing is a bad idea
+  // try to avoid asking for formats which don't exist (by not asking for all when adjusting the config to include the drawableTypeOverride)
+  if (drawableTypeOverride == GLX_WINDOW_BIT)
+    {
+      if (mode->drawableType & GLX_PIXMAP_BIT)
+        SET_ATTR_VALUE(WGL_DRAW_TO_BITMAP_ARB, TRUE);
+
+      if (mode->drawableType & GLX_PBUFFER_BIT)
+        if (winScreen->has_WGL_ARB_pbuffer)
+          SET_ATTR_VALUE(WGL_DRAW_TO_PBUFFER_ARB, TRUE);
+    }
+  else
+    {
+      if (drawableTypeOverride & GLX_PIXMAP_BIT)
+        SET_ATTR_VALUE(WGL_DRAW_TO_BITMAP_ARB, TRUE);
+
+      if (drawableTypeOverride & GLX_PBUFFER_BIT)
+        if (winScreen->has_WGL_ARB_pbuffer)
+          SET_ATTR_VALUE(WGL_DRAW_TO_PBUFFER_ARB, TRUE);
+    }
+
+  SET_ATTR_VALUE(0, 0); // terminator
+
+  /* choose the first match */
+  {
+    int pixelFormatIndex;
+
+    if (!wglChoosePixelFormatARBWrapper(hdc, attribList, NULL, 1, &pixelFormatIndex, &numFormats))
+      {
+        ErrorF("wglChoosePixelFormat error: %s\n", glxWinErrorMessage());
+      }
+    else
+      {
+        if (numFormats > 0)
+          {
+            GLWIN_DEBUG_MSG("wglChoosePixelFormat: chose pixelFormatIndex %d)", pixelFormatIndex);
+            return pixelFormatIndex;
+          }
+        else
+          ErrorF("wglChoosePixelFormat couldn't decide\n");
+      }
+  }
+
+  return 0;
+}
+
+/* ---------------------------------------------------------------------- */
+
+#define BITS_AND_SHIFT_TO_MASK(bits,mask) (((1<<(bits))-1) << (mask))
+
+//
+// Create the GLXconfigs using DescribePixelFormat()
+//
+static void
+glxWinCreateConfigs(HDC hdc, glxWinScreen *screen)
+{
+  GLXWinConfig *c, *result, *prev = NULL;
+  int numConfigs = 0;
+  int i = 0;
+  int n = 0;
+  PIXELFORMATDESCRIPTOR pfd;
+
+  GLWIN_DEBUG_MSG("glxWinCreateConfigs");
+
+  screen->base.numFBConfigs = 0;
+  screen->base.fbconfigs = NULL;
+
+  // get the number of pixelformats
+  numConfigs = DescribePixelFormat(hdc, 1, sizeof(PIXELFORMATDESCRIPTOR), NULL);
+  GLWIN_DEBUG_MSG("DescribePixelFormat says %d possible pixel formats", numConfigs);
+
+  /* alloc */
+  result = xalloc(sizeof(GLXWinConfig) * numConfigs);
+
+  if (NULL == result)
+    {
+      return;
+    }
+
+  memset(result, 0, sizeof(GLXWinConfig) * numConfigs);
+  n = 0;
+
+  /* fill in configs */
+  for (i = 0;  i < numConfigs; i++)
+    {
+      int rc;
+
+      c = &(result[i]);
+      c->base.next = NULL;
+      c->pixelFormatIndex = i+1;
+
+      rc = DescribePixelFormat(hdc, i+1, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
+
+      if (!rc)
+        {
+          ErrorF("DescribePixelFormat failed for index %d, error %s\n", i+1, glxWinErrorMessage());
+          break;
+        }
+
+      if (glxWinDebugSettings.dumpPFD)
+        pfdOut(&pfd);
+
+      if (!(pfd.dwFlags & (PFD_DRAW_TO_WINDOW | PFD_DRAW_TO_BITMAP)) || !(pfd.dwFlags & PFD_SUPPORT_OPENGL))
+        {
+          GLWIN_DEBUG_MSG("pixelFormat %d has unsuitable flags 0x%08lx, skipping", i+1, pfd.dwFlags);
+          continue;
+        }
+
+      c->base.doubleBufferMode = (pfd.dwFlags & PFD_DOUBLEBUFFER) ? GL_TRUE : GL_FALSE;
+      c->base.stereoMode = (pfd.dwFlags & PFD_STEREO) ? GL_TRUE : GL_FALSE;
+
+      c->base.redBits = pfd.cRedBits;
+      c->base.greenBits = pfd.cGreenBits;
+      c->base.blueBits = pfd.cBlueBits;
+      c->base.alphaBits = pfd.cAlphaBits;
+
+      c->base.redMask = BITS_AND_SHIFT_TO_MASK(pfd.cRedBits, pfd.cRedShift);
+      c->base.greenMask =  BITS_AND_SHIFT_TO_MASK(pfd.cGreenBits, pfd.cGreenShift);
+      c->base.blueMask = BITS_AND_SHIFT_TO_MASK(pfd.cBlueBits, pfd.cBlueShift);
+      c->base.alphaMask = BITS_AND_SHIFT_TO_MASK(pfd.cAlphaBits, pfd.cAlphaShift);
+
+      c->base.rgbBits = pfd.cColorBits;
+
+      if (pfd.iPixelType == PFD_TYPE_COLORINDEX)
+        {
+          c->base.indexBits = pfd.cColorBits;
+        }
+      else
+        {
+          c->base.indexBits = 0;
+        }
+
+      c->base.accumRedBits = pfd.cAccumRedBits;
+      c->base.accumGreenBits = pfd.cAccumGreenBits;
+      c->base.accumBlueBits = pfd.cAccumBlueBits;
+      c->base.accumAlphaBits = pfd.cAccumAlphaBits;
+      //  pfd.cAccumBits;
+
+      c->base.depthBits = pfd.cDepthBits;
+      c->base.stencilBits = pfd.cStencilBits;
+      c->base.numAuxBuffers = pfd.cAuxBuffers;
+
+      // pfd.iLayerType; // ignored
+      c->base.level = 0;
+      // pfd.dwLayerMask; // ignored
+      // pfd.dwDamageMask;  // ignored
+
+      c->base.pixmapMode = 0;
+      c->base.visualID = -1;  // will be set by __glXScreenInit()
+
+      /* EXT_visual_rating / GLX 1.2 */
+      if (pfd.dwFlags & PFD_GENERIC_FORMAT)
+        {
+          c->base.visualRating = GLX_SLOW_VISUAL_EXT;
+        }
+      else
+        {
+          // PFD_GENERIC_ACCELERATED is not considered, so this may be MCD or ICD acclerated...
+          c->base.visualRating = GLX_NONE_EXT;
+        }
+
+      /* EXT_visual_info / GLX 1.2 */
+      if (pfd.iPixelType == PFD_TYPE_COLORINDEX)
+        {
+          c->base.visualType = GLX_STATIC_COLOR;
+        }
+      else
+        {
+          c->base.visualType = GLX_TRUE_COLOR;
+        }
+
+      // pfd.dwVisibleMask; ???
+      c->base.transparentPixel = GLX_NONE;
+      c->base.transparentRed = GLX_NONE;
+      c->base.transparentGreen = GLX_NONE;
+      c->base.transparentBlue = GLX_NONE;
+      c->base.transparentAlpha = GLX_NONE;
+      c->base.transparentIndex = GLX_NONE;
+
+      /* ARB_multisample / SGIS_multisample */
+      c->base.sampleBuffers = 0;
+      c->base.samples = 0;
+
+      /* SGIX_fbconfig / GLX 1.3 */
+      c->base.drawableType = (((pfd.dwFlags & PFD_DRAW_TO_WINDOW) ? GLX_WINDOW_BIT : 0)
+                         | ((pfd.dwFlags & PFD_DRAW_TO_BITMAP) ? GLX_PIXMAP_BIT : 0));
+      c->base.renderType = GLX_RGBA_BIT;
+      c->base.xRenderable = GL_TRUE;
+      c->base.fbconfigID = -1; // will be set by __glXScreenInit()
+
+      /* SGIX_pbuffer / GLX 1.3 */
+      // XXX: How can we find these values out ???
+      c->base.maxPbufferWidth = -1;
+      c->base.maxPbufferHeight = -1;
+      c->base.maxPbufferPixels = -1;
+      c->base.optimalPbufferWidth = 0; // there is no optimal value
+      c->base.optimalPbufferHeight = 0;
+
+      /* SGIX_visual_select_group */
+      // arrange for visuals with the best acceleration to be preferred in selection
+      switch (pfd.dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED))
+        {
+        case 0:
+          c->base.visualSelectGroup = 2;
+          break;
+
+        case PFD_GENERIC_ACCELERATED:
+          c->base.visualSelectGroup = 1;
+          break;
+
+        case PFD_GENERIC_FORMAT:
+          c->base.visualSelectGroup = 0;
+          break;
+
+        default:
+          ;
+          // "can't happen"
+        }
+
+      /* OML_swap_method */
+      if (pfd.dwFlags & PFD_SWAP_EXCHANGE)
+        c->base.swapMethod = GLX_SWAP_EXCHANGE_OML;
+      else if (pfd.dwFlags & PFD_SWAP_COPY)
+        c->base.swapMethod = GLX_SWAP_COPY_OML;
+      else
+        c->base.swapMethod = GLX_SWAP_UNDEFINED_OML;
+
+      /* EXT_import_context */
+      c->base.screen = screen->base.pScreen->myNum;
+
+      /* EXT_texture_from_pixmap */
+      c->base.bindToTextureRgb = -1;
+      c->base.bindToTextureRgba = -1;
+      c->base.bindToMipmapTexture = -1;
+      c->base.bindToTextureTargets = -1;
+      c->base.yInverted = -1;
+
+      n++;
+
+      // update previous config to point to this config
+      if (prev)
+        prev->base.next = &(c->base);
+
+      prev = c;
+    }
+
+  GLWIN_DEBUG_MSG("found %d pixelFormats suitable for conversion to fbConfigs", n);
+
+  screen->base.numFBConfigs = n;
+  screen->base.fbconfigs = &(result->base);
+}
+
+// helper function to access an attribute value from an attribute value array by attribute
+static
+int getAttrValue(const int attrs[], int values[], unsigned int num, int attr, int fallback)
+{
+  unsigned int i;
+  for (i = 0; i < num; i++)
+    {
+      if (attrs[i] == attr)
+        {
+          GLWIN_TRACE_MSG("getAttrValue attr 0x%x, value %d", attr, values[i]);
+          return values[i];
+        }
+    }
+
+  ErrorF("getAttrValue failed to find attr 0x%x, using default value %d\n", attr, fallback);
+  return fallback;
+}
+
+//
+// Create the GLXconfigs using wglGetPixelFormatAttribfvARB() extension
+//
+static void
+glxWinCreateConfigsExt(HDC hdc, glxWinScreen *screen)
+{
+  GLXWinConfig *c, *result, *prev = NULL;
+  int i = 0;
+  int n = 0;
+
+  const int attr = WGL_NUMBER_PIXEL_FORMATS_ARB;
+  int numConfigs;
+
+  int attrs[50];
+  unsigned int num_attrs = 0;
+
+  GLWIN_DEBUG_MSG("glxWinCreateConfigsExt");
+
+  screen->base.numFBConfigs = 0;
+  screen->base.fbconfigs = NULL;
+
+  if (!wglGetPixelFormatAttribivARBWrapper(hdc, 0, 0, 1, &attr, &numConfigs))
+    {
+      ErrorF("wglGetPixelFormatAttribivARB failed for WGL_NUMBER_PIXEL_FORMATS_ARB: %s\n", glxWinErrorMessage());
+      return;
+    }
+
+  GLWIN_DEBUG_MSG("wglGetPixelFormatAttribivARB says %d possible pixel formats", numConfigs);
+
+  /* alloc */
+  result = xalloc(sizeof(GLXWinConfig) * numConfigs);
+
+  if (NULL == result)
+    {
+      return;
+    }
+
+  memset(result, 0, sizeof(GLXWinConfig) * numConfigs);
+  n = 0;
+
+#define ADD_ATTR(a) { attrs[num_attrs++] = a; assert(num_attrs < NUM_ELEMENTS(attrs)); }
+
+  ADD_ATTR(WGL_DRAW_TO_WINDOW_ARB);
+  ADD_ATTR(WGL_DRAW_TO_BITMAP_ARB);
+  ADD_ATTR(WGL_ACCELERATION_ARB);
+  ADD_ATTR(WGL_SWAP_LAYER_BUFFERS_ARB);
+  ADD_ATTR(WGL_NUMBER_OVERLAYS_ARB);
+  ADD_ATTR(WGL_NUMBER_UNDERLAYS_ARB);
+  ADD_ATTR(WGL_TRANSPARENT_ARB);
+  ADD_ATTR(WGL_TRANSPARENT_RED_VALUE_ARB);
+  ADD_ATTR(WGL_TRANSPARENT_GREEN_VALUE_ARB);
+  ADD_ATTR(WGL_TRANSPARENT_GREEN_VALUE_ARB);
+  ADD_ATTR(WGL_TRANSPARENT_ALPHA_VALUE_ARB);
+  ADD_ATTR(WGL_SUPPORT_OPENGL_ARB);
+  ADD_ATTR(WGL_DOUBLE_BUFFER_ARB);
+  ADD_ATTR(WGL_STEREO_ARB);
+  ADD_ATTR(WGL_PIXEL_TYPE_ARB);
+  ADD_ATTR(WGL_COLOR_BITS_ARB);
+  ADD_ATTR(WGL_RED_BITS_ARB);
+  ADD_ATTR(WGL_RED_SHIFT_ARB);
+  ADD_ATTR(WGL_GREEN_BITS_ARB);
+  ADD_ATTR(WGL_GREEN_SHIFT_ARB);
+  ADD_ATTR(WGL_BLUE_BITS_ARB);
+  ADD_ATTR(WGL_BLUE_SHIFT_ARB);
+  ADD_ATTR(WGL_ALPHA_BITS_ARB);
+  ADD_ATTR(WGL_ALPHA_SHIFT_ARB);
+  ADD_ATTR(WGL_ACCUM_RED_BITS_ARB);
+  ADD_ATTR(WGL_ACCUM_GREEN_BITS_ARB);
+  ADD_ATTR(WGL_ACCUM_BLUE_BITS_ARB);
+  ADD_ATTR(WGL_ACCUM_ALPHA_BITS_ARB);
+  ADD_ATTR(WGL_DEPTH_BITS_ARB);
+  ADD_ATTR(WGL_STENCIL_BITS_ARB);
+  ADD_ATTR(WGL_AUX_BUFFERS_ARB);
+  ADD_ATTR(WGL_SWAP_METHOD_ARB);
+
+  if (screen->has_WGL_ARB_multisample)
+    {
+      // we may not query these attrs if WGL_ARB_multisample is not offered
+      ADD_ATTR(WGL_SAMPLE_BUFFERS_ARB);
+      ADD_ATTR(WGL_SAMPLES_ARB);
+    }
+
+  if (screen->has_WGL_ARB_render_texture)
+    {
+      // we may not query these attrs if WGL_ARB_render_texture is not offered
+      ADD_ATTR(WGL_BIND_TO_TEXTURE_RGB_ARB);
+      ADD_ATTR(WGL_BIND_TO_TEXTURE_RGBA_ARB);
+    }
+
+  if (screen->has_WGL_ARB_pbuffer)
+    {
+      // we may not query these attrs if WGL_ARB_pbuffer is not offered
+      ADD_ATTR(WGL_DRAW_TO_PBUFFER_ARB);
+      ADD_ATTR(WGL_MAX_PBUFFER_PIXELS_ARB);
+      ADD_ATTR(WGL_MAX_PBUFFER_WIDTH_ARB);
+      ADD_ATTR(WGL_MAX_PBUFFER_HEIGHT_ARB);
+    }
+
+  /* fill in configs */
+  for (i = 0;  i < numConfigs; i++)
+    {
+      int values[num_attrs];
+
+      c = &(result[i]);
+      c->base.next = NULL;
+      c->pixelFormatIndex = i+1;
+
+      if (!wglGetPixelFormatAttribivARBWrapper(hdc, i+1, 0, num_attrs, attrs, values))
+        {
+          ErrorF("wglGetPixelFormatAttribivARB failed for index %d, error %s\n", i+1, glxWinErrorMessage());
+          break;
+        }
+
+#define ATTR_VALUE(a, d) getAttrValue(attrs, values, num_attrs, (a), (d))
+
+      if (!ATTR_VALUE(WGL_SUPPORT_OPENGL_ARB, 0))
+        {
+          GLWIN_DEBUG_MSG("pixelFormat %d isn't WGL_SUPPORT_OPENGL_ARB, skipping", i+1);
+          continue;
+        }
+
+      c->base.doubleBufferMode = ATTR_VALUE(WGL_DOUBLE_BUFFER_ARB, 0) ? GL_TRUE : GL_FALSE;
+      c->base.stereoMode = ATTR_VALUE(WGL_STEREO_ARB, 0) ? GL_TRUE : GL_FALSE;
+
+      c->base.redBits = ATTR_VALUE(WGL_RED_BITS_ARB, 0);
+      c->base.greenBits = ATTR_VALUE(WGL_GREEN_BITS_ARB, 0);
+      c->base.blueBits = ATTR_VALUE(WGL_BLUE_BITS_ARB, 0);
+      c->base.alphaBits = ATTR_VALUE(WGL_ALPHA_BITS_ARB, 0);
+
+      c->base.redMask = BITS_AND_SHIFT_TO_MASK(c->base.redBits, ATTR_VALUE(WGL_RED_SHIFT_ARB, 0));
+      c->base.greenMask = BITS_AND_SHIFT_TO_MASK(c->base.greenBits, ATTR_VALUE(WGL_GREEN_SHIFT_ARB, 0));
+      c->base.blueMask = BITS_AND_SHIFT_TO_MASK(c->base.blueBits, ATTR_VALUE(WGL_BLUE_SHIFT_ARB, 0));
+      c->base.alphaMask = BITS_AND_SHIFT_TO_MASK(c->base.alphaBits, ATTR_VALUE(WGL_ALPHA_SHIFT_ARB, 0));
+
+      switch (ATTR_VALUE(WGL_PIXEL_TYPE_ARB, 0))
+        {
+        case WGL_TYPE_COLORINDEX_ARB:
+          c->base.indexBits = ATTR_VALUE(WGL_COLOR_BITS_ARB, 0);
+          c->base.rgbBits = 0;
+          c->base.visualType = GLX_STATIC_COLOR;
+          break;
+
+        case WGL_TYPE_RGBA_FLOAT_ARB:
+          GLWIN_DEBUG_MSG("pixelFormat %d is WGL_TYPE_RGBA_FLOAT_ARB, skipping", i+1);
+          continue;
+
+        case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
+          GLWIN_DEBUG_MSG("pixelFormat %d is WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT, skipping", i+1);
+          continue;
+
+        case WGL_TYPE_RGBA_ARB:
+          c->base.indexBits = 0;
+          c->base.rgbBits = ATTR_VALUE(WGL_COLOR_BITS_ARB, 0);
+          c->base.visualType = GLX_TRUE_COLOR;
+          break;
+
+        default:
+          ErrorF("wglGetPixelFormatAttribivARB returned unknown value 0x%x for WGL_PIXEL_TYPE_ARB\n", ATTR_VALUE(WGL_PIXEL_TYPE_ARB, 0));
+          continue;
+        }
+
+      c->base.accumRedBits = ATTR_VALUE(WGL_ACCUM_RED_BITS_ARB, 0);
+      c->base.accumGreenBits = ATTR_VALUE(WGL_ACCUM_GREEN_BITS_ARB, 0);
+      c->base.accumBlueBits = ATTR_VALUE(WGL_ACCUM_BLUE_BITS_ARB, 0);
+      c->base.accumAlphaBits = ATTR_VALUE(WGL_ACCUM_ALPHA_BITS_ARB, 0);
+
+      c->base.depthBits = ATTR_VALUE(WGL_DEPTH_BITS_ARB, 0);
+      c->base.stencilBits = ATTR_VALUE(WGL_STENCIL_BITS_ARB, 0);
+      c->base.numAuxBuffers = ATTR_VALUE(WGL_AUX_BUFFERS_ARB, 0);
+
+      {
+        int layers = ATTR_VALUE(WGL_NUMBER_OVERLAYS_ARB,0) + ATTR_VALUE(WGL_NUMBER_UNDERLAYS_ARB, 0);
+
+        if (layers > 0)
+          {
+            ErrorF("pixelFormat %d: has %d overlay, %d underlays which aren't currently handled", i, ATTR_VALUE(WGL_NUMBER_OVERLAYS_ARB,0), ATTR_VALUE(WGL_NUMBER_UNDERLAYS_ARB, 0));
+            // XXX: need to iterate over layers?
+          }
+      }
+      c->base.level = 0;
+
+      c->base.pixmapMode = 0; // ???
+      c->base.visualID = -1;  // will be set by __glXScreenInit()
+
+      /* EXT_visual_rating / GLX 1.2 */
+      switch (ATTR_VALUE(WGL_ACCELERATION_ARB, 0))
+        {
+        default:
+          ErrorF("wglGetPixelFormatAttribivARB returned unknown value 0x%x for WGL_ACCELERATION_ARB\n", ATTR_VALUE(WGL_ACCELERATION_ARB, 0));
+
+        case WGL_NO_ACCELERATION_ARB:
+          c->base.visualRating = GLX_SLOW_VISUAL_EXT;
+          break;
+
+        case WGL_GENERIC_ACCELERATION_ARB:
+        case WGL_FULL_ACCELERATION_ARB:
+          c->base.visualRating = GLX_NONE_EXT;
+          break;
+        }
+
+      /* EXT_visual_info / GLX 1.2 */
+      // c->base.visualType is set above
+      if (ATTR_VALUE(WGL_TRANSPARENT_ARB, 0))
+        {
+          c->base.transparentPixel = (c->base.visualType == GLX_TRUE_COLOR) ? GLX_TRANSPARENT_RGB_EXT : GLX_TRANSPARENT_INDEX_EXT;
+          c->base.transparentRed = ATTR_VALUE(WGL_TRANSPARENT_RED_VALUE_ARB, 0);
+          c->base.transparentGreen = ATTR_VALUE(WGL_TRANSPARENT_GREEN_VALUE_ARB, 0);
+          c->base.transparentBlue = ATTR_VALUE(WGL_TRANSPARENT_BLUE_VALUE_ARB, 0);
+          c->base.transparentAlpha = ATTR_VALUE(WGL_TRANSPARENT_ALPHA_VALUE_ARB, 0);
+          c->base.transparentIndex = ATTR_VALUE(WGL_TRANSPARENT_INDEX_VALUE_ARB, 0);
+        }
+      else
+        {
+          c->base.transparentPixel = GLX_NONE_EXT;
+          c->base.transparentRed = GLX_NONE;
+          c->base.transparentGreen = GLX_NONE;
+          c->base.transparentBlue = GLX_NONE;
+          c->base.transparentAlpha = GLX_NONE;
+          c->base.transparentIndex = GLX_NONE;
+        }
+
+      /* ARB_multisample / SGIS_multisample */
+      if (screen->has_WGL_ARB_multisample)
+        {
+          c->base.sampleBuffers = ATTR_VALUE(WGL_SAMPLE_BUFFERS_ARB, 0);
+          c->base.samples = ATTR_VALUE(WGL_SAMPLES_ARB, 0);
+        }
+      else
+        {
+          c->base.sampleBuffers = 0;
+          c->base.samples = 0;
+        }
+
+      /* SGIX_fbconfig / GLX 1.3 */
+      c->base.drawableType = ((ATTR_VALUE(WGL_DRAW_TO_WINDOW_ARB, 0) ? GLX_WINDOW_BIT : 0)
+                         | (ATTR_VALUE(WGL_DRAW_TO_BITMAP_ARB, 0) ? GLX_PIXMAP_BIT : 0)
+                         | (ATTR_VALUE(WGL_DRAW_TO_PBUFFER_ARB, 0) ? GLX_PBUFFER_BIT : 0));
+      c->base.renderType = GLX_RGBA_BIT | GLX_COLOR_INDEX_BIT; // Hmmm ???
+      c->base.xRenderable = GL_TRUE;
+      c->base.fbconfigID = -1; // will be set by __glXScreenInit()
+
+      /* SGIX_pbuffer / GLX 1.3 */
+      if (screen->has_WGL_ARB_pbuffer)
+        {
+          c->base.maxPbufferWidth = ATTR_VALUE(WGL_MAX_PBUFFER_WIDTH_ARB, -1);
+          c->base.maxPbufferHeight = ATTR_VALUE(WGL_MAX_PBUFFER_HEIGHT_ARB, -1);
+          c->base.maxPbufferPixels =  ATTR_VALUE(WGL_MAX_PBUFFER_PIXELS_ARB, -1);
+        }
+      else
+        {
+          c->base.maxPbufferWidth = -1;
+          c->base.maxPbufferHeight = -1;
+          c->base.maxPbufferPixels =  -1;
+        }
+      c->base.optimalPbufferWidth = 0; // there is no optimal value
+      c->base.optimalPbufferHeight = 0;
+
+      /* SGIX_visual_select_group */
+      // arrange for visuals with the best acceleration to be preferred in selection
+      switch (ATTR_VALUE(WGL_ACCELERATION_ARB, 0))
+        {
+        case WGL_FULL_ACCELERATION_ARB:
+          c->base.visualSelectGroup = 2;
+          break;
+
+        case WGL_GENERIC_ACCELERATION_ARB:
+          c->base.visualSelectGroup = 1;
+          break;
+
+        default:
+        case WGL_NO_ACCELERATION_ARB:
+          c->base.visualSelectGroup = 0;
+          break;
+        }
+
+      /* OML_swap_method */
+      switch (ATTR_VALUE(WGL_SWAP_METHOD_ARB, 0))
+        {
+        case WGL_SWAP_EXCHANGE_ARB:
+          c->base.swapMethod = GLX_SWAP_EXCHANGE_OML;
+          break;
+
+        case WGL_SWAP_COPY_ARB:
+          c->base.swapMethod = GLX_SWAP_COPY_OML;
+          break;
+
+        default:
+          ErrorF("wglGetPixelFormatAttribivARB returned unknown value 0x%x for WGL_SWAP_METHOD_ARB\n", ATTR_VALUE(WGL_SWAP_METHOD_ARB, 0));
+
+        case WGL_SWAP_UNDEFINED_ARB:
+          c->base.swapMethod = GLX_SWAP_UNDEFINED_OML;
+        }
+
+      /* EXT_import_context */
+      c->base.screen = screen->base.pScreen->myNum;
+
+      /* EXT_texture_from_pixmap */
+      /*
+         Mesa's DRI configs always have bindToTextureRgb/Rgba TRUE (see driCreateConfigs(), so setting
+         bindToTextureRgb/bindToTextureRgba to FALSE means that swrast can't find any fbConfigs to use,
+         so setting these to 0, even if we know bindToTexture isn't available, isn't a good idea...
+       */
+      if (screen->has_WGL_ARB_render_texture)
+        {
+          c->base.bindToTextureRgb = ATTR_VALUE(WGL_BIND_TO_TEXTURE_RGB_ARB, -1);
+          c->base.bindToTextureRgba = ATTR_VALUE(WGL_BIND_TO_TEXTURE_RGBA_ARB, -1);
+        }
+      else
+        {
+          c->base.bindToTextureRgb = -1;
+          c->base.bindToTextureRgba = -1;
+        }
+      c->base.bindToMipmapTexture = -1;
+      c->base.bindToTextureTargets = GLX_TEXTURE_1D_BIT_EXT | GLX_TEXTURE_2D_BIT_EXT | GLX_TEXTURE_RECTANGLE_BIT_EXT;
+      c->base.yInverted = -1;
+
+      n++;
+
+      // update previous config to point to this config
+      if (prev)
+        prev->base.next = &(c->base);
+
+      prev = c;
+    }
+
+  screen->base.numFBConfigs = n;
+  screen->base.fbconfigs = &(result->base);
+}
diff --git a/xorg-server/hw/xwin/glx/winpriv.h b/xorg-server/hw/xwin/glx/winpriv.h
index 9cb2981ad..a2f3e5818 100644
--- a/xorg-server/hw/xwin/glx/winpriv.h
+++ b/xorg-server/hw/xwin/glx/winpriv.h
@@ -1,17 +1,16 @@
-/*
- * Export window information for the Windows-OpenGL GLX implementation.
- *
- * Authors: Alexander Gottwald
- */
-
-#include <X11/Xwindows.h>
-#include <windowstr.h>
-
-typedef struct
-{
-    HWND    hwnd;
-} winWindowInfoRec, *winWindowInfoPtr;
-
-void winGetWindowInfo(WindowPtr pWin, winWindowInfoPtr pWinInfo);
-Bool winCheckScreenAiglxIsSupported(ScreenPtr pScreen);
-
+/*
+ * Export window information for the Windows-OpenGL GLX implementation.
+ *
+ * Authors: Alexander Gottwald
+ */
+
+#include <X11/Xwindows.h>
+#include <windowstr.h>
+
+typedef struct
+{
+    HWND    hwnd;
+} winWindowInfoRec, *winWindowInfoPtr;
+
+void winGetWindowInfo(WindowPtr pWin, winWindowInfoPtr pWinInfo);
+Bool winCheckScreenAiglxIsSupported(ScreenPtr pScreen);
diff --git a/xorg-server/hw/xwin/win.h b/xorg-server/hw/xwin/win.h
index 9ab8ed976..2fef56a50 100644
--- a/xorg-server/hw/xwin/win.h
+++ b/xorg-server/hw/xwin/win.h
@@ -1,1460 +1,1460 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- *		Kensuke Matsuzaki
- */
-
-#ifndef _WIN_H_
-#define _WIN_H_
-
-#ifndef NO
-#define NO					0
-#endif
-#ifndef YES
-#define YES					1
-#endif
-
-/* Turn debug messages on or off */
-#ifndef CYGDEBUG
-#define CYGDEBUG				NO
-#endif
-
-/* WM_XBUTTON Messages. They should go into w32api. */
-#ifndef WM_XBUTTONDOWN
-# define WM_XBUTTONDOWN 523
-#endif
-#ifndef WM_XBUTTONUP
-# define WM_XBUTTONUP 524
-#endif
-#ifndef WM_XBUTTONDBLCLK
-# define WM_XBUTTONDBLCLK 525
-#endif
-
-
-#define WIN_DEFAULT_BPP				0
-#define WIN_DEFAULT_WHITEPIXEL			255
-#define WIN_DEFAULT_BLACKPIXEL			0
-#define WIN_DEFAULT_LINEBIAS			0
-#define WIN_DEFAULT_E3B_TIME			50 /* milliseconds */
-#define WIN_DEFAULT_DPI				75
-#define WIN_DEFAULT_REFRESH			0
-#define WIN_DEFAULT_WIN_KILL			TRUE
-#define WIN_DEFAULT_UNIX_KILL			FALSE
-#define WIN_DEFAULT_CLIP_UPDATES_NBOXES		0
-#ifdef XWIN_EMULATEPSEUDO
-#define WIN_DEFAULT_EMULATE_PSEUDO		FALSE
-#endif
-#define WIN_DEFAULT_USER_GAVE_HEIGHT_AND_WIDTH	FALSE
-
-#define WIN_DIB_MAXIMUM_SIZE	0x08000000 /* 16 MB on Windows 95, 98, Me */
-#define WIN_DIB_MAXIMUM_SIZE_MB (WIN_DIB_MAXIMUM_SIZE / 8 / 1024 / 1024)
-
-/*
- * Windows only supports 256 color palettes
- */
-#define WIN_NUM_PALETTE_ENTRIES			256
-
-/*
- * Number of times to call Restore in an attempt to restore the primary surface
- */
-#define WIN_REGAIN_SURFACE_RETRIES		1
-
-/*
- * Build a supported display depths mask by shifting one to the left
- * by the number of bits in the supported depth.
- */
-#define WIN_SUPPORTED_BPPS	( (1 << (32 - 1)) | (1 << (24 - 1)) \
-				| (1 << (16 - 1)) | (1 << (15 - 1)) \
-				| (1 << ( 8 - 1)))
-#define WIN_CHECK_DEPTH		YES
-
-/*
- * Timer IDs for WM_TIMER
- */
-#define WIN_E3B_TIMER_ID		1
-#define WIN_POLLING_MOUSE_TIMER_ID	2
-
-#define MOUSE_POLLING_INTERVAL		50
-
-#define WIN_E3B_OFF		-1
-#define WIN_FD_INVALID		-1
-
-#define WIN_SERVER_NONE		0x0L	/* 0 */
-#define WIN_SERVER_SHADOW_GDI	0x1L	/* 1 */
-#define WIN_SERVER_SHADOW_DD	0x2L	/* 2 */
-#define WIN_SERVER_SHADOW_DDNL	0x4L	/* 4 */
-#ifdef XWIN_PRIMARYFB
-#define WIN_SERVER_PRIMARY_DD	0x8L	/* 8 */
-#endif
-#ifdef XWIN_NATIVEGDI
-# define WIN_SERVER_NATIVE_GDI	0x10L	/* 16 */
-#endif
-
-#define AltMapIndex		Mod1MapIndex
-#define NumLockMapIndex		Mod2MapIndex
-#define AltLangMapIndex		Mod3MapIndex
-#define KanaMapIndex		Mod4MapIndex
-#define ScrollLockMapIndex	Mod5MapIndex
-
-#define WIN_MOD_LALT		0x00000001
-#define WIN_MOD_RALT		0x00000002
-#define WIN_MOD_LCONTROL	0x00000004
-#define WIN_MOD_RCONTROL	0x00000008
-
-#define WIN_24BPP_MASK_RED	0x00FF0000
-#define WIN_24BPP_MASK_GREEN	0x0000FF00
-#define WIN_24BPP_MASK_BLUE	0x000000FF
-
-#define WIN_MAX_KEYS_PER_KEY	4
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdio.h>
-
-#include <errno.h>
-#if defined(XWIN_MULTIWINDOWEXTWM) || defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-#define HANDLE void *
-#include <pthread.h>
-#undef HANDLE
-#endif
-
-#ifdef HAS_MMAP
-#include <sys/mman.h>
-#ifndef MAP_FILE
-#define MAP_FILE 0
-#endif /* MAP_FILE */
-#endif /* HAS_MMAP */
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include <X11/Xos.h>
-#include <X11/Xprotostr.h>
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "pixmap.h"
-#include "region.h"
-#include "gcstruct.h"
-#include "colormap.h"
-#include "colormapst.h"
-#include "miscstruct.h"
-#include "servermd.h"
-#include "windowstr.h"
-#include "mi.h"
-#include "micmap.h"
-#include "mifillarc.h"
-#include "mifpoly.h"
-#include "mibstore.h"
-#include "input.h"
-#include "mipointer.h"
-#include "X11/keysym.h"
-#include "mibstore.h"
-#include "micoord.h"
-#include "dix.h"
-#include "miline.h"
-#include "shadow.h"
-#include "fb.h"
-#include "rootless.h"
-
-#ifdef RENDER
-#include "mipict.h"
-#include "picturestr.h"
-#endif
-
-#ifdef RANDR
-#include "randrstr.h"
-#endif
-
-/*
- * Windows headers
- */
-#include "winms.h"
-#include "./winresource.h"
-
-
-/*
- * Define Windows constants
- */
-
-#define WM_TRAYICON		(WM_USER + 1000)
-#define WM_INIT_SYS_MENU	(WM_USER + 1001)
-#define WM_GIVEUP		(WM_USER + 1002)
-
-
-/* Local includes */
-#include "winwindow.h"
-#include "winmsg.h"
-
-
-/*
- * Debugging macros
- */
-
-#if CYGDEBUG
-#define DEBUG_MSG(str,...) \
-if (fDebugProcMsg) \
-{ \
-  char *pszTemp; \
-  int iLength; \
-  pszTemp = Xprintf (str, ##__VA_ARGS__); \
-  MessageBox (NULL, pszTemp, szFunctionName, MB_OK); \
-  xfree (pszTemp); \
-}
-#else
-#define DEBUG_MSG(str,...)
-#endif
-
-#if CYGDEBUG
-#define DEBUG_FN_NAME(str) PTSTR szFunctionName = str
-#else
-#define DEBUG_FN_NAME(str)
-#endif
-
-#if CYGDEBUG || YES
-#define DEBUGVARS BOOL fDebugProcMsg = FALSE
-#else
-#define DEBUGVARS
-#endif
-
-#if CYGDEBUG || YES
-#define DEBUGPROC_MSG fDebugProcMsg = TRUE
-#else
-#define DEBUGPROC_MSG
-#endif
-
-#define PROFILEPOINT(point,thresh)\
-{\
-static unsigned int PROFPT##point = 0;\
-if (++PROFPT##point % thresh == 0)\
-ErrorF (#point ": PROFILEPOINT hit %u times\n", PROFPT##point);\
-}
-
-
-/* We use xor this macro for detecting toggle key state changes */
-#define WIN_XOR(a,b) ((!(a) && (b)) || ((a) && !(b)))
-
-#define DEFINE_ATOM_HELPER(func,atom_name)			\
-static Atom func (void) {					\
-    static int generation;					\
-    static Atom atom;						\
-    if (generation != serverGeneration) {			\
-	generation = serverGeneration;				\
-	atom = MakeAtom (atom_name, strlen (atom_name), TRUE);	\
-    }								\
-    return atom;						\
-}
-
-/*
- * Typedefs for engine dependent function pointers
- */
-
-typedef Bool (*winAllocateFBProcPtr)(ScreenPtr);
-
-typedef void (*winShadowUpdateProcPtr)(ScreenPtr, shadowBufPtr);
-
-typedef Bool (*winCloseScreenProcPtr)(int, ScreenPtr);
-
-typedef Bool (*winInitVisualsProcPtr)(ScreenPtr);
-
-typedef Bool (*winAdjustVideoModeProcPtr)(ScreenPtr);
-
-typedef Bool (*winCreateBoundingWindowProcPtr)(ScreenPtr);
-
-typedef Bool (*winFinishScreenInitProcPtr)(int, ScreenPtr, int, char **);
-
-typedef Bool (*winBltExposedRegionsProcPtr)(ScreenPtr);
-
-typedef Bool (*winActivateAppProcPtr)(ScreenPtr);
-
-typedef Bool (*winRedrawScreenProcPtr)(ScreenPtr pScreen);
-
-typedef Bool (*winRealizeInstalledPaletteProcPtr)(ScreenPtr pScreen);
-
-typedef Bool (*winInstallColormapProcPtr)(ColormapPtr pColormap);
-
-typedef Bool (*winStoreColorsProcPtr)(ColormapPtr pmap, 
-				      int ndef, xColorItem *pdefs);
-
-typedef Bool (*winCreateColormapProcPtr)(ColormapPtr pColormap);
-
-typedef Bool (*winDestroyColormapProcPtr)(ColormapPtr pColormap);
-
-typedef Bool (*winHotKeyAltTabProcPtr)(ScreenPtr);
-
-typedef Bool (*winCreatePrimarySurfaceProcPtr)(ScreenPtr);
-
-typedef Bool (*winReleasePrimarySurfaceProcPtr)(ScreenPtr);
-
-typedef Bool (*winFinishCreateWindowsWindowProcPtr)(WindowPtr pWin);
-
-typedef Bool (*winCreateScreenResourcesProc)(ScreenPtr);
-
-/* Typedef for DIX wrapper functions */
-typedef int (*winDispatchProcPtr) (ClientPtr);
-
-
-/*
- * GC (graphics context) privates
- */
-
-typedef struct
-{
-  HDC			hdc;
-  HDC			hdcMem;
-} winPrivGCRec, *winPrivGCPtr;
-
-
-/*
- * Pixmap privates
- */
-
-typedef struct
-{
-  HDC			hdcSelected;
-  HBITMAP		hBitmap;
-  BYTE			*pbBits;
-  DWORD			dwScanlineBytes;
-  BITMAPINFOHEADER	*pbmih;
-} winPrivPixmapRec, *winPrivPixmapPtr;
-
-
-/*
- * Colormap privates
- */
-
-typedef struct
-{
-  HPALETTE		hPalette;
-  LPDIRECTDRAWPALETTE	lpDDPalette;
-  RGBQUAD		rgbColors[WIN_NUM_PALETTE_ENTRIES];
-  PALETTEENTRY		peColors[WIN_NUM_PALETTE_ENTRIES];
-} winPrivCmapRec, *winPrivCmapPtr;
-
-/*
- * Windows Cursor handling.
- */ 
-  
-typedef struct {
-  /* from GetSystemMetrics */
-  int sm_cx;
-  int sm_cy;
-
-  BOOL visible;
-  HCURSOR handle;
-  QueryBestSizeProcPtr QueryBestSize;
-  miPointerSpriteFuncPtr spriteFuncs;
-} winCursorRec;
-
-/*
- * Screen information structure that we need before privates are available
- * in the server startup sequence.
- */
-
-typedef struct
-{
-  ScreenPtr		pScreen;
-  
-  /* Did the user specify a height and width? */
-  Bool			fUserGaveHeightAndWidth;
-
-  DWORD			dwScreen;
-  DWORD			dwUserWidth;
-  DWORD			dwUserHeight;
-  DWORD			dwWidth;
-  DWORD			dwHeight;
-  DWORD			dwWidth_mm;
-  DWORD			dwHeight_mm;
-  DWORD			dwPaddedWidth;
-
-  /* Did the user specify a screen position? */
-  Bool			fUserGavePosition;
-  DWORD                 dwInitialX;
-  DWORD                 dwInitialY;
-
-  /*
-   * dwStride is the number of whole pixels that occupy a scanline,
-   * including those pixels that are not displayed.  This is basically
-   * a rounding up of the width.
-   */
-  DWORD			dwStride;
-
-  /* Offset of the screen in the window when using scrollbars */
-  DWORD			dwXOffset;
-  DWORD			dwYOffset;
-
-  DWORD			dwBPP;
-  DWORD			dwDepth;
-  DWORD			dwRefreshRate;
-  char			*pfb;
-  DWORD			dwEngine;
-  DWORD			dwEnginePreferred;
-  DWORD			dwClipUpdatesNBoxes;
-#ifdef XWIN_EMULATEPSEUDO
-  Bool			fEmulatePseudo;
-#endif
-  Bool			fFullScreen;
-  Bool			fDecoration;
-#ifdef XWIN_MULTIWINDOWEXTWM
-  Bool			fMWExtWM;
-  Bool			fInternalWM;
-  Bool			fAnotherWMRunning;
-#endif
-  Bool			fRootless;
-#ifdef XWIN_MULTIWINDOW
-  Bool			fMultiWindow;
-#endif
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-  Bool			fMultiMonitorOverride;
-#endif
-  Bool                  fMultipleMonitors;
-  Bool			fLessPointer;
-  Bool			fScrollbars;
-  Bool			fNoTrayIcon;
-  int			iE3BTimeout;
-  /* Windows (Alt+F4) and Unix (Ctrl+Alt+Backspace) Killkey */
-  Bool                  fUseWinKillKey;
-  Bool                  fUseUnixKillKey;
-  Bool			fIgnoreInput;
-
-  /* Did the user explicitly set this screen? */
-  Bool			fExplicitScreen;
-} winScreenInfo, *winScreenInfoPtr;
-
-
-/*
- * Screen privates
- */
-
-typedef struct _winPrivScreenRec
-{
-  winScreenInfoPtr	pScreenInfo;
-
-  Bool			fEnabled;
-  Bool			fClosed;
-  Bool			fActive;
-  Bool			fBadDepth;
-
-  int			iDeltaZ;
-
-  int			iConnectedClients;
-
-  CloseScreenProcPtr	CloseScreen;
-
-  DWORD			dwRedMask;
-  DWORD			dwGreenMask;
-  DWORD			dwBlueMask;
-  DWORD			dwBitsPerRGB;
-
-  DWORD			dwModeKeyStates;
-
-  /* Handle to icons that must be freed */
-  HICON			hiconNotifyIcon;
-
-  /* Last width, height, and depth of the Windows display */
-  DWORD			dwLastWindowsWidth;
-  DWORD			dwLastWindowsHeight;
-  DWORD			dwLastWindowsBitsPixel;
-
-  /* Palette management */
-  ColormapPtr		pcmapInstalled;
-
-  /* Pointer to the root visual so we only have to look it up once */
-  VisualPtr		pRootVisual;
-
-  /* 3 button emulation variables */
-  int			iE3BCachedPress;
-  Bool			fE3BFakeButton2Sent;
-
-  /* Privates used by shadow fb GDI server */
-  HBITMAP		hbmpShadow;
-  HDC			hdcScreen;
-  HDC			hdcShadow;
-  HWND			hwndScreen;
-  
-  /* Privates used by shadow fb and primary fb DirectDraw servers */
-  LPDIRECTDRAW		pdd;
-  LPDIRECTDRAWSURFACE2	pddsPrimary;
-  LPDIRECTDRAW2		pdd2;
-
-  /* Privates used by shadow fb DirectDraw server */
-  LPDIRECTDRAWSURFACE2	pddsShadow;
-  LPDDSURFACEDESC	pddsdShadow;
-
-  /* Privates used by primary fb DirectDraw server */
-  LPDIRECTDRAWSURFACE2	pddsOffscreen;
-  LPDDSURFACEDESC	pddsdOffscreen;
-  LPDDSURFACEDESC	pddsdPrimary;
-
-  /* Privates used by shadow fb DirectDraw Nonlocking server */
-  LPDIRECTDRAW4		pdd4;
-  LPDIRECTDRAWSURFACE4	pddsShadow4;
-  LPDIRECTDRAWSURFACE4	pddsPrimary4;
-  BOOL			fRetryCreateSurface;
-
-  /* Privates used by both shadow fb DirectDraw servers */
-  LPDIRECTDRAWCLIPPER	pddcPrimary;
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  /* Privates used by multi-window external window manager */
-  RootlessFrameID	widTop;
-  Bool			fRestacking;
-#endif
-
-#ifdef XWIN_MULTIWINDOW
-  /* Privates used by multi-window */
-  pthread_t		ptWMProc;
-  pthread_t		ptXMsgProc;
-  void			*pWMInfo;
-#endif
-
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-  /* Privates used by both multi-window and rootless */
-  Bool			fRootWindowShown;
-#endif
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Privates used for any module running in a seperate thread */
-  pthread_mutex_t	pmServerStarted;
-  Bool			fServerStarted;
-#endif
-  
-  /* Engine specific functions */
-  winAllocateFBProcPtr			pwinAllocateFB;
-  winShadowUpdateProcPtr		pwinShadowUpdate;
-  winCloseScreenProcPtr			pwinCloseScreen;
-  winInitVisualsProcPtr			pwinInitVisuals;
-  winAdjustVideoModeProcPtr		pwinAdjustVideoMode;
-  winCreateBoundingWindowProcPtr	pwinCreateBoundingWindow;
-  winFinishScreenInitProcPtr		pwinFinishScreenInit;
-  winBltExposedRegionsProcPtr		pwinBltExposedRegions;
-  winActivateAppProcPtr			pwinActivateApp;
-  winRedrawScreenProcPtr		pwinRedrawScreen;
-  winRealizeInstalledPaletteProcPtr	pwinRealizeInstalledPalette;
-  winInstallColormapProcPtr		pwinInstallColormap;
-  winStoreColorsProcPtr			pwinStoreColors;
-  winCreateColormapProcPtr		pwinCreateColormap;
-  winDestroyColormapProcPtr		pwinDestroyColormap;
-  winHotKeyAltTabProcPtr		pwinHotKeyAltTab;
-  winCreatePrimarySurfaceProcPtr	pwinCreatePrimarySurface;
-  winReleasePrimarySurfaceProcPtr	pwinReleasePrimarySurface;
-
-  winCreateScreenResourcesProc       pwinCreateScreenResources;
-
-#ifdef XWIN_MULTIWINDOW
-  /* Window Procedures for MultiWindow mode */
-  winFinishCreateWindowsWindowProcPtr	pwinFinishCreateWindowsWindow;
-#endif
-
-  /* Window Procedures for Rootless mode */
-  CreateWindowProcPtr			CreateWindow;
-  DestroyWindowProcPtr			DestroyWindow;
-  PositionWindowProcPtr			PositionWindow;
-  ChangeWindowAttributesProcPtr		ChangeWindowAttributes;
-  RealizeWindowProcPtr			RealizeWindow;
-  UnrealizeWindowProcPtr		UnrealizeWindow;
-  ValidateTreeProcPtr			ValidateTree;
-  PostValidateTreeProcPtr		PostValidateTree;
-  WindowExposuresProcPtr		WindowExposures;
-  CopyWindowProcPtr			CopyWindow;
-  ClearToBackgroundProcPtr		ClearToBackground;
-  ClipNotifyProcPtr			ClipNotify;
-  RestackWindowProcPtr			RestackWindow;
-  ReparentWindowProcPtr			ReparentWindow;
-  ResizeWindowProcPtr			ResizeWindow;
-  MoveWindowProcPtr			MoveWindow;
-  SetShapeProcPtr			SetShape;
-
-  winCursorRec                          cursor;
-} winPrivScreenRec;
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-typedef struct {
-  RootlessWindowPtr	pFrame;
-  HWND			hWnd;
-  int			dwWidthBytes;
-  BITMAPINFOHEADER	*pbmihShadow;
-  HBITMAP		hbmpShadow;
-  HDC			hdcShadow;
-  HDC			hdcScreen;
-  BOOL			fResized;
-  BOOL			fRestackingNow;
-  BOOL			fClose;
-  BOOL			fMovingOrSizing;
-  BOOL			fDestroyed;//for debug
-  char			*pfb;
-} win32RootlessWindowRec, *win32RootlessWindowPtr;
-#endif
-
-
-typedef struct {
-  pointer		value;
-  XID			id;
-} WindowIDPairRec, *WindowIDPairPtr;
-
-
-/*
- * Extern declares for general global variables
- */
-
-extern winScreenInfo		g_ScreenInfo[];
-extern miPointerScreenFuncRec	g_winPointerCursorFuncs;
-extern DWORD			g_dwEvents;
-#ifdef HAS_DEVWINDOWS
-extern int			g_fdMessageQueue;
-#endif
-extern DevPrivateKey		g_iScreenPrivateKey;
-extern DevPrivateKey		g_iCmapPrivateKey;
-extern DevPrivateKey		g_iGCPrivateKey;
-extern DevPrivateKey		g_iPixmapPrivateKey;
-extern DevPrivateKey		g_iWindowPrivateKey;
-extern unsigned long		g_ulServerGeneration;
-extern DWORD			g_dwEnginesSupported;
-extern HINSTANCE		g_hInstance;
-extern int                      g_copyROP[];
-extern int                      g_patternROP[];
-extern const char *		g_pszQueryHost;
-extern DeviceIntPtr             g_pwinPointer;
-extern DeviceIntPtr             g_pwinKeyboard;
-
-
-/*
- * Extern declares for dynamically loaded libraries and function pointers
- */
-
-extern HMODULE			g_hmodDirectDraw;
-extern FARPROC			g_fpDirectDrawCreate;
-extern FARPROC			g_fpDirectDrawCreateClipper;
-
-extern HMODULE			g_hmodCommonControls;
-extern FARPROC			g_fpTrackMouseEvent;
-
-
-/*
- * Screen privates macros
- */
-
-#define winGetScreenPriv(pScreen) ((winPrivScreenPtr) \
-    dixLookupPrivate(&(pScreen)->devPrivates, g_iScreenPrivateKey))
-
-#define winSetScreenPriv(pScreen,v) \
-    dixSetPrivate(&(pScreen)->devPrivates, g_iScreenPrivateKey, v)
-
-#define winScreenPriv(pScreen) \
-	winPrivScreenPtr pScreenPriv = winGetScreenPriv(pScreen)
-
-
-/*
- * Colormap privates macros
- */
-
-#define winGetCmapPriv(pCmap) ((winPrivCmapPtr) \
-    dixLookupPrivate(&(pCmap)->devPrivates, g_iCmapPrivateKey))
-
-#define winSetCmapPriv(pCmap,v) \
-    dixSetPrivate(&(pCmap)->devPrivates, g_iCmapPrivateKey, v)
-
-#define winCmapPriv(pCmap) \
-	winPrivCmapPtr pCmapPriv = winGetCmapPriv(pCmap)
-
-
-/*
- * GC privates macros
- */
-
-#define winGetGCPriv(pGC) ((winPrivGCPtr) \
-    dixLookupPrivate(&(pGC)->devPrivates, g_iGCPrivateKey))
-
-#define winSetGCPriv(pGC,v) \
-    dixSetPrivate(&(pGC)->devPrivates, g_iGCPrivateKey, v)
-
-#define winGCPriv(pGC) \
-	winPrivGCPtr pGCPriv = winGetGCPriv(pGC)
-
-
-/*
- * Pixmap privates macros
- */
-
-#define winGetPixmapPriv(pPixmap) ((winPrivPixmapPtr) \
-    dixLookupPrivate(&(pPixmap)->devPrivates, g_iPixmapPrivateKey))
-
-#define winSetPixmapPriv(pPixmap,v) \
-    dixLookupPrivate(&(pPixmap)->devPrivates, g_iPixmapPrivateKey, v)
-
-#define winPixmapPriv(pPixmap) \
-	winPrivPixmapPtr pPixmapPriv = winGetPixmapPriv(pPixmap)
-
-
-/*
- * Window privates macros
- */
-
-#define winGetWindowPriv(pWin) ((winPrivWinPtr) \
-    dixLookupPrivate(&(pWin)->devPrivates, g_iWindowPrivateKey))
-
-#define winSetWindowPriv(pWin,v) \
-    dixLookupPrivate(&(pWin)->devPrivates, g_iWindowPrivateKey, v)
-
-#define winWindowPriv(pWin) \
-	winPrivWinPtr pWinPriv = winGetWindowPriv(pWin)
-
-/*
- * wrapper macros 
- */
-#define _WIN_WRAP(priv, real, mem, func) {\
-    priv->mem = real->mem; \
-    real->mem = func; \
-}
-
-#define _WIN_UNWRAP(priv, real, mem) {\
-    real->mem = priv->mem; \
-}
-
-#define WIN_WRAP(mem, func) _WIN_WRAP(pScreenPriv, pScreen, mem, func) 
-
-#define WIN_UNWRAP(mem) _WIN_UNWRAP(pScreenPriv, pScreen, mem)
-
-/*
- * BEGIN DDX and DIX Function Prototypes
- */
-
-
-/*
- * winallpriv.c
- */
-
-Bool
-winAllocatePrivates (ScreenPtr pScreen);
-
-Bool
-winInitCmapPrivates (ColormapPtr pCmap, int index);
-
-Bool
-winAllocateCmapPrivates (ColormapPtr pCmap);
-
-
-/*
- * winauth.c
- */
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-Bool
-winGenerateAuthorization (void);
-void winSetAuthorization(void);
-#endif
-
-
-/*
- * winblock.c
- */
-
-void
-winBlockHandler (int nScreen,
-		 pointer pBlockData,
-		 pointer pTimeout,
-		 pointer pReadMask);
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winclip.c
- */
-
-RegionPtr
-winPixmapToRegionNativeGDI (PixmapPtr pPix);
-#endif
-
-
-#ifdef XWIN_CLIPBOARD
-/*
- * winclipboardinit.c
- */
-
-Bool
-winInitClipboard (void);
-
-void
-winFixClipboardChain (void);
-#endif
-
-
-/*
- * wincmap.c
- */
-
-void
-winSetColormapFunctions (ScreenPtr pScreen);
-
-Bool
-winCreateDefColormap (ScreenPtr pScreen);
-
-
-/*
- * wincreatewnd.c
- */
-
-Bool
-winCreateBoundingWindowFullScreen (ScreenPtr pScreen);
-
-Bool
-winCreateBoundingWindowWindowed (ScreenPtr pScreen);
-
-
-/*
- * windialogs.c
- */
-
-void
-winDisplayExitDialog (winPrivScreenPtr pScreenPriv);
-
-void
-winDisplayDepthChangeDialog (winPrivScreenPtr pScreenPriv);
-
-void
-winDisplayAboutDialog (winPrivScreenPtr pScreenPriv);
-
-
-/*
- * winengine.c
- */
-
-void
-winDetectSupportedEngines (void);
-
-Bool
-winSetEngine (ScreenPtr pScreen);
-
-Bool
-winGetDDProcAddresses (void);
-
-
-/*
- * winerror.c
- */
-
-#ifdef DDXOSVERRORF
-void
-OSVenderVErrorF (const char *pszFormat, va_list va_args);
-#endif
-
-void
-winMessageBoxF (const char *pszError, UINT uType, ...);
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winfillsp.c
- */
-
-void
-winFillSpansNativeGDI (DrawablePtr	pDrawable,
-		       GCPtr		pGC,
-		       int		nSpans,
-		       DDXPointPtr	pPoints,
-		       int		*pWidths,
-		       int		fSorted);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winfont.c
- */
-
-Bool
-winRealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont);
-
-Bool
-winUnrealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * wingc.c
- */
-
-Bool
-winCreateGCNativeGDI (GCPtr pGC);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * wingetsp.c
- */
-
-void
-winGetSpansNativeGDI (DrawablePtr	pDrawable, 
-		      int		wMax, 
-		      DDXPointPtr	pPoints, 
-		      int		*pWidths, 
-		      int		nSpans, 
-		      char		*pDst);
-#endif
-
-
-/*
- * winglobals.c
- */
-
-void
-winInitializeGlobals (void);
-
-
-/*
- * winkeybd.c
- */
-
-void
-winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode);
-
-int
-winKeybdProc (DeviceIntPtr pDeviceInt, int iState);
-
-void
-winInitializeModeKeyStates (void);
-
-void
-winRestoreModeKeyStates (void);
-
-Bool
-winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam);
-
-void
-winKeybdReleaseKeys (void);
-
-void
-winSendKeyEvent (DWORD dwKey, Bool fDown);
-
-BOOL
-winCheckKeyPressed(WPARAM wParam, LPARAM lParam);
-
-void
-winFixShiftKeys (int iScanCode);
-
-/*
- * winkeyhook.c
- */
-
-Bool
-winInstallKeyboardHookLL (void);
-
-void
-winRemoveKeyboardHookLL (void);
-
-
-/*
- * winmisc.c
- */
-
-#ifdef XWIN_NATIVEGDI
-void
-winQueryBestSizeNativeGDI (int class, unsigned short *pWidth,
-			   unsigned short *pHeight, ScreenPtr pScreen);
-#endif
-
-CARD8
-winCountBits (DWORD dw);
-
-Bool
-winUpdateFBPointer (ScreenPtr pScreen, void *pbits);
-
-#ifdef XWIN_NATIVEGDI
-BOOL
-winPaintBackground (HWND hwnd, COLORREF colorref);
-#endif
-
-
-/*
- * winmouse.c
- */
-
-int
-winMouseProc (DeviceIntPtr pDeviceInt, int iState);
-
-int
-winMouseWheel (ScreenPtr pScreen, int iDeltaZ);
-
-void
-winMouseButtonsSendEvent (int iEventType, int iButton);
-
-int
-winMouseButtonsHandle (ScreenPtr pScreen,
-		       int iEventType, int iButton,
-		       WPARAM wParam);
-
-void
-winEnqueueMotion(int x, int y);
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winnativegdi.c
- */
-
-HBITMAP
-winCreateDIBNativeGDI (int iWidth, int iHeight, int iDepth,
-		       BYTE **ppbBits, BITMAPINFO **ppbmi);
-
-Bool
-winSetEngineFunctionsNativeGDI (ScreenPtr pScreen);
-#endif
-
-
-#ifdef XWIN_PRIMARYFB
-/*
- * winpfbddd.c
- */
-
-Bool
-winSetEngineFunctionsPrimaryDD (ScreenPtr pScreen);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winpixmap.c
- */
-
-PixmapPtr
-winCreatePixmapNativeGDI (ScreenPtr pScreen, int width, int height, int depth,
-			  unsigned usage_hint);
-
-Bool
-winDestroyPixmapNativeGDI (PixmapPtr pPixmap);
-
-Bool
-winModifyPixmapHeaderNativeGDI (PixmapPtr pPixmap,
-				int iWidth, int iHeight,
-				int iDepth,
-				int iBitsPerPixel,
-				int devKind,
-				pointer pPixData);
-#endif
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winpolyline.c
- */
-
-void
-winPolyLineNativeGDI (DrawablePtr	pDrawable,
-		      GCPtr		pGC,
-		      int		mode,
-		      int		npt,
-		      DDXPointPtr	ppt);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winpushpxl.c
- */
-
-void
-winPushPixels (GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDrawable,
-	       int dx, int dy, int xOrg, int yOrg);
-#endif
-
-
-/*
- * winscrinit.c
- */
-
-Bool
-winScreenInit (int index,
-	       ScreenPtr pScreen,
-	       int argc, char **argv);
-
-Bool
-winFinishScreenInitFB (int index,
-		       ScreenPtr pScreen,
-		       int argc, char **argv);
-
-#if defined(XWIN_NATIVEGDI)
-Bool
-winFinishScreenInitNativeGDI (int index,
-			      ScreenPtr pScreen,
-			      int argc, char **argv);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winsetsp.c
- */
-
-void
-winSetSpansNativeGDI (DrawablePtr	pDrawable,
-		      GCPtr		pGC,
-		      char		*pSrc,
-		      DDXPointPtr	pPoints,
-		      int		*pWidth,
-		      int		nSpans,
-		      int		fSorted);
-#endif
-
-
-/*
- * winshaddd.c
- */
-
-Bool
-winSetEngineFunctionsShadowDD (ScreenPtr pScreen);
-
-
-/*
- * winshadddnl.c
- */
-
-Bool
-winSetEngineFunctionsShadowDDNL (ScreenPtr pScreen);
-
-
-/*
- * winshadgdi.c
- */
-
-Bool
-winSetEngineFunctionsShadowGDI (ScreenPtr pScreen);
-
-
-/*
- * winwakeup.c
- */
-
-void
-winWakeupHandler (int nScreen,
-		  pointer pWakeupData,
-		  unsigned long ulResult,
-		  pointer pReadmask);
-
-
-/*
- * winwindow.c
- */
-
-#ifdef XWIN_NATIVEGDI
-Bool
-winCreateWindowNativeGDI (WindowPtr pWin);
-
-Bool
-winDestroyWindowNativeGDI (WindowPtr pWin);
-
-Bool
-winPositionWindowNativeGDI (WindowPtr pWin, int x, int y);
-
-void 
-winCopyWindowNativeGDI (WindowPtr pWin,
-			DDXPointRec ptOldOrg,
-			RegionPtr prgnSrc);
-
-Bool
-winChangeWindowAttributesNativeGDI (WindowPtr pWin, unsigned long mask);
-
-Bool
-winUnmapWindowNativeGDI (WindowPtr pWindow);
-
-Bool
-winMapWindowNativeGDI (WindowPtr pWindow);
-#endif
-
-Bool
-winCreateWindowRootless (WindowPtr pWindow);
-
-Bool
-winDestroyWindowRootless (WindowPtr pWindow);
-
-Bool
-winPositionWindowRootless (WindowPtr pWindow, int x, int y);
-
-Bool
-winChangeWindowAttributesRootless (WindowPtr pWindow, unsigned long mask);
-
-Bool
-winUnmapWindowRootless (WindowPtr pWindow);
-
-Bool
-winMapWindowRootless (WindowPtr pWindow);
-
-void
-winSetShapeRootless (WindowPtr pWindow);
-
-
-/*
- * winmultiwindowicons.c - Used by both multi-window and Win32Rootless
- */
-
-HICON
-winXIconToHICON (WindowPtr pWin, int iconSize);
-
-void
-winSelectIcons(WindowPtr pWin, HICON *pIcon, HICON *pSmallIcon);
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * winmultiwindowshape.c
- */
-
-void
-winReshapeMultiWindow (WindowPtr pWin);
-
-void
-winSetShapeMultiWindow (WindowPtr pWindow);
-
-void
-winUpdateRgnMultiWindow (WindowPtr pWindow);
-#endif
-
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * winmultiwindowwindow.c
- */
-
-Bool
-winCreateWindowMultiWindow (WindowPtr pWindow);
-
-Bool
-winDestroyWindowMultiWindow (WindowPtr pWindow);
-
-Bool
-winPositionWindowMultiWindow (WindowPtr pWindow, int x, int y);
-
-Bool
-winChangeWindowAttributesMultiWindow (WindowPtr pWindow, unsigned long mask);
-
-Bool
-winUnmapWindowMultiWindow (WindowPtr pWindow);
-
-Bool
-winMapWindowMultiWindow (WindowPtr pWindow);
-
-void
-winReparentWindowMultiWindow (WindowPtr pWin, WindowPtr pPriorParent);
-
-void
-winRestackWindowMultiWindow (WindowPtr pWin, WindowPtr pOldNextSib);
-
-void
-winReorderWindowsMultiWindow (void);
-
-void
-winResizeWindowMultiWindow (WindowPtr pWin, int x, int y, unsigned int w,
-			    unsigned int h, WindowPtr pSib);
-void
-winMoveWindowMultiWindow (WindowPtr pWin, int x, int y,
-			  WindowPtr pSib, VTKind kind);
-
-void
-winCopyWindowMultiWindow (WindowPtr pWin, DDXPointRec oldpt,
-			  RegionPtr oldRegion);
-
-XID
-winGetWindowID (WindowPtr pWin);
-
-int
-winAdjustXWindow (WindowPtr pWin, HWND hwnd);
-#endif
-
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * winmultiwindowwndproc.c
- */
-
-LRESULT CALLBACK
-winTopLevelWindowProc (HWND hwnd, UINT message, 
-		       WPARAM wParam, LPARAM lParam);
-#endif
-
-
-/*
- * wintrayicon.c
- */
-
-void
-winInitNotifyIcon (winPrivScreenPtr pScreenPriv);
-
-void
-winDeleteNotifyIcon (winPrivScreenPtr pScreenPriv);
-
-LRESULT
-winHandleIconMessage (HWND hwnd, UINT message,
-		      WPARAM wParam, LPARAM lParam,
-		      winPrivScreenPtr pScreenPriv);
-
-
-/*
- * winwndproc.c
- */
-
-LRESULT CALLBACK
-winWindowProc (HWND hWnd, UINT message, 
-	       WPARAM wParam, LPARAM lParam);
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-/*
- * winwin32rootless.c
- */
-
-Bool
-winMWExtWMCreateFrame (RootlessWindowPtr pFrame, ScreenPtr pScreen,
-			     int newX, int newY, RegionPtr pShape);
-
-void
-winMWExtWMDestroyFrame (RootlessFrameID wid);
-
-void
-winMWExtWMMoveFrame (RootlessFrameID wid, ScreenPtr pScreen, int newX, int newY);
-
-void
-winMWExtWMResizeFrame (RootlessFrameID wid, ScreenPtr pScreen,
-			     int newX, int newY, unsigned int newW, unsigned int newH,
-			     unsigned int gravity);
-
-void
-winMWExtWMRestackFrame (RootlessFrameID wid, RootlessFrameID nextWid);
-
-void
-winMWExtWMReshapeFrame (RootlessFrameID wid, RegionPtr pShape);
-
-void
-winMWExtWMUnmapFrame (RootlessFrameID wid);
-
-void
-winMWExtWMStartDrawing (RootlessFrameID wid, char **pixelData, int *bytesPerRow);
-
-void
-winMWExtWMStopDrawing (RootlessFrameID wid, Bool flush);
-
-void
-winMWExtWMUpdateRegion (RootlessFrameID wid, RegionPtr pDamage);
-
-void
-winMWExtWMDamageRects (RootlessFrameID wid, int count, const BoxRec *rects,
-			     int shift_x, int shift_y);
-
-void
-winMWExtWMRootlessSwitchWindow (RootlessWindowPtr pFrame, WindowPtr oldWin);
-
-void
-winMWExtWMCopyBytes (unsigned int width, unsigned int height,
-			   const void *src, unsigned int srcRowBytes,
-			   void *dst, unsigned int dstRowBytes);
-
-void
-winMWExtWMFillBytes (unsigned int width, unsigned int height, unsigned int value,
-			   void *dst, unsigned int dstRowBytes);
-
-int
-winMWExtWMCompositePixels (unsigned int width, unsigned int height, unsigned int function,
-				 void *src[2], unsigned int srcRowBytes[2],
-				 void *mask, unsigned int maskRowBytes,
-				 void *dst[2], unsigned int dstRowBytes[2]);
-
-void
-winMWExtWMCopyWindow (RootlessFrameID wid, int dstNrects, const BoxRec *dstRects,
-			    int dx, int dy);
-#endif
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-/*
- * winwin32rootlesswindow.c
- */
-
-void
-winMWExtWMReorderWindows (ScreenPtr pScreen);
-
-void
-winMWExtWMMoveXWindow (WindowPtr pWin, int x, int y);
-
-void
-winMWExtWMResizeXWindow (WindowPtr pWin, int w, int h);
-
-void
-winMWExtWMMoveResizeXWindow (WindowPtr pWin, int x, int y, int w, int h);
-
-void
-winMWExtWMUpdateIcon (Window id);
-
-void
-winMWExtWMUpdateWindowDecoration (win32RootlessWindowPtr pRLWinPriv,
-				  winScreenInfoPtr pScreenInfo);
-
-wBOOL CALLBACK
-winMWExtWMDecorateWindow (HWND hwnd, LPARAM lParam);
-
-Bool
-winIsInternalWMRunning (winScreenInfoPtr pScreenInfo);
-
-void
-winMWExtWMRestackWindows (ScreenPtr pScreen);
-#endif
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-/*
- * winwin32rootlesswndproc.c
- */
-
-LRESULT CALLBACK
-winMWExtWMWindowProc (HWND hwnd, UINT message, 
-			    WPARAM wParam, LPARAM lParam);
-#endif
-
-
-/*
- * winwindowswm.c
- */
-
-void
-winWindowsWMSendEvent (int type, unsigned int mask, int which, int arg,
-		       Window window, int x, int y, int w, int h);
-
-void
-winWindowsWMExtensionInit (void);
-
-/*
- * wincursor.c
- */
-
-Bool
-winInitCursor (ScreenPtr pScreen);
-
-/*
- * END DDX and DIX Function Prototypes
- */
-
-#endif /* _WIN_H_ */
-
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ *		Kensuke Matsuzaki
+ */
+
+#ifndef _WIN_H_
+#define _WIN_H_
+
+#ifndef NO
+#define NO					0
+#endif
+#ifndef YES
+#define YES					1
+#endif
+
+/* Turn debug messages on or off */
+#ifndef CYGDEBUG
+#define CYGDEBUG				NO
+#endif
+
+/* WM_XBUTTON Messages. They should go into w32api. */
+#ifndef WM_XBUTTONDOWN
+# define WM_XBUTTONDOWN 523
+#endif
+#ifndef WM_XBUTTONUP
+# define WM_XBUTTONUP 524
+#endif
+#ifndef WM_XBUTTONDBLCLK
+# define WM_XBUTTONDBLCLK 525
+#endif
+
+
+#define WIN_DEFAULT_BPP				0
+#define WIN_DEFAULT_WHITEPIXEL			255
+#define WIN_DEFAULT_BLACKPIXEL			0
+#define WIN_DEFAULT_LINEBIAS			0
+#define WIN_DEFAULT_E3B_TIME			50 /* milliseconds */
+#define WIN_DEFAULT_DPI				75
+#define WIN_DEFAULT_REFRESH			0
+#define WIN_DEFAULT_WIN_KILL			TRUE
+#define WIN_DEFAULT_UNIX_KILL			FALSE
+#define WIN_DEFAULT_CLIP_UPDATES_NBOXES		0
+#ifdef XWIN_EMULATEPSEUDO
+#define WIN_DEFAULT_EMULATE_PSEUDO		FALSE
+#endif
+#define WIN_DEFAULT_USER_GAVE_HEIGHT_AND_WIDTH	FALSE
+
+#define WIN_DIB_MAXIMUM_SIZE	0x08000000 /* 16 MB on Windows 95, 98, Me */
+#define WIN_DIB_MAXIMUM_SIZE_MB (WIN_DIB_MAXIMUM_SIZE / 8 / 1024 / 1024)
+
+/*
+ * Windows only supports 256 color palettes
+ */
+#define WIN_NUM_PALETTE_ENTRIES			256
+
+/*
+ * Number of times to call Restore in an attempt to restore the primary surface
+ */
+#define WIN_REGAIN_SURFACE_RETRIES		1
+
+/*
+ * Build a supported display depths mask by shifting one to the left
+ * by the number of bits in the supported depth.
+ */
+#define WIN_SUPPORTED_BPPS	( (1 << (32 - 1)) | (1 << (24 - 1)) \
+				| (1 << (16 - 1)) | (1 << (15 - 1)) \
+				| (1 << ( 8 - 1)))
+#define WIN_CHECK_DEPTH		YES
+
+/*
+ * Timer IDs for WM_TIMER
+ */
+#define WIN_E3B_TIMER_ID		1
+#define WIN_POLLING_MOUSE_TIMER_ID	2
+
+#define MOUSE_POLLING_INTERVAL		50
+
+#define WIN_E3B_OFF		-1
+#define WIN_FD_INVALID		-1
+
+#define WIN_SERVER_NONE		0x0L	/* 0 */
+#define WIN_SERVER_SHADOW_GDI	0x1L	/* 1 */
+#define WIN_SERVER_SHADOW_DD	0x2L	/* 2 */
+#define WIN_SERVER_SHADOW_DDNL	0x4L	/* 4 */
+#ifdef XWIN_PRIMARYFB
+#define WIN_SERVER_PRIMARY_DD	0x8L	/* 8 */
+#endif
+#ifdef XWIN_NATIVEGDI
+# define WIN_SERVER_NATIVE_GDI	0x10L	/* 16 */
+#endif
+
+#define AltMapIndex		Mod1MapIndex
+#define NumLockMapIndex		Mod2MapIndex
+#define AltLangMapIndex		Mod3MapIndex
+#define KanaMapIndex		Mod4MapIndex
+#define ScrollLockMapIndex	Mod5MapIndex
+
+#define WIN_MOD_LALT		0x00000001
+#define WIN_MOD_RALT		0x00000002
+#define WIN_MOD_LCONTROL	0x00000004
+#define WIN_MOD_RCONTROL	0x00000008
+
+#define WIN_24BPP_MASK_RED	0x00FF0000
+#define WIN_24BPP_MASK_GREEN	0x0000FF00
+#define WIN_24BPP_MASK_BLUE	0x000000FF
+
+#define WIN_MAX_KEYS_PER_KEY	4
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h>
+
+#include <errno.h>
+#if defined(XWIN_MULTIWINDOWEXTWM) || defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+#define HANDLE void *
+#include <pthread.h>
+#undef HANDLE
+#endif
+
+#ifdef HAS_MMAP
+#include <sys/mman.h>
+#ifndef MAP_FILE
+#define MAP_FILE 0
+#endif /* MAP_FILE */
+#endif /* HAS_MMAP */
+
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include <X11/Xos.h>
+#include <X11/Xprotostr.h>
+#include "scrnintstr.h"
+#include "pixmapstr.h"
+#include "pixmap.h"
+#include "region.h"
+#include "gcstruct.h"
+#include "colormap.h"
+#include "colormapst.h"
+#include "miscstruct.h"
+#include "servermd.h"
+#include "windowstr.h"
+#include "mi.h"
+#include "micmap.h"
+#include "mifillarc.h"
+#include "mifpoly.h"
+#include "mibstore.h"
+#include "input.h"
+#include "mipointer.h"
+#include "X11/keysym.h"
+#include "mibstore.h"
+#include "micoord.h"
+#include "dix.h"
+#include "miline.h"
+#include "shadow.h"
+#include "fb.h"
+#include "rootless.h"
+
+#ifdef RENDER
+#include "mipict.h"
+#include "picturestr.h"
+#endif
+
+#ifdef RANDR
+#include "randrstr.h"
+#endif
+
+/*
+ * Windows headers
+ */
+#include "winms.h"
+#include "winresource.h"
+
+
+/*
+ * Define Windows constants
+ */
+
+#define WM_TRAYICON		(WM_USER + 1000)
+#define WM_INIT_SYS_MENU	(WM_USER + 1001)
+#define WM_GIVEUP		(WM_USER + 1002)
+
+
+/* Local includes */
+#include "winwindow.h"
+#include "winmsg.h"
+
+
+/*
+ * Debugging macros
+ */
+
+#if CYGDEBUG
+#define DEBUG_MSG(str,...) \
+if (fDebugProcMsg) \
+{ \
+  char *pszTemp; \
+  int iLength; \
+  pszTemp = Xprintf (str, ##__VA_ARGS__); \
+  MessageBox (NULL, pszTemp, szFunctionName, MB_OK); \
+  xfree (pszTemp); \
+}
+#else
+#define DEBUG_MSG(str,...)
+#endif
+
+#if CYGDEBUG
+#define DEBUG_FN_NAME(str) PTSTR szFunctionName = str
+#else
+#define DEBUG_FN_NAME(str)
+#endif
+
+#if CYGDEBUG || YES
+#define DEBUGVARS BOOL fDebugProcMsg = FALSE
+#else
+#define DEBUGVARS
+#endif
+
+#if CYGDEBUG || YES
+#define DEBUGPROC_MSG fDebugProcMsg = TRUE
+#else
+#define DEBUGPROC_MSG
+#endif
+
+#define PROFILEPOINT(point,thresh)\
+{\
+static unsigned int PROFPT##point = 0;\
+if (++PROFPT##point % thresh == 0)\
+ErrorF (#point ": PROFILEPOINT hit %u times\n", PROFPT##point);\
+}
+
+
+/* We use xor this macro for detecting toggle key state changes */
+#define WIN_XOR(a,b) ((!(a) && (b)) || ((a) && !(b)))
+
+#define DEFINE_ATOM_HELPER(func,atom_name)			\
+static Atom func (void) {					\
+    static int generation;					\
+    static Atom atom;						\
+    if (generation != serverGeneration) {			\
+	generation = serverGeneration;				\
+	atom = MakeAtom (atom_name, strlen (atom_name), TRUE);	\
+    }								\
+    return atom;						\
+}
+
+/*
+ * Typedefs for engine dependent function pointers
+ */
+
+typedef Bool (*winAllocateFBProcPtr)(ScreenPtr);
+
+typedef void (*winShadowUpdateProcPtr)(ScreenPtr, shadowBufPtr);
+
+typedef Bool (*winCloseScreenProcPtr)(int, ScreenPtr);
+
+typedef Bool (*winInitVisualsProcPtr)(ScreenPtr);
+
+typedef Bool (*winAdjustVideoModeProcPtr)(ScreenPtr);
+
+typedef Bool (*winCreateBoundingWindowProcPtr)(ScreenPtr);
+
+typedef Bool (*winFinishScreenInitProcPtr)(int, ScreenPtr, int, char **);
+
+typedef Bool (*winBltExposedRegionsProcPtr)(ScreenPtr);
+
+typedef Bool (*winActivateAppProcPtr)(ScreenPtr);
+
+typedef Bool (*winRedrawScreenProcPtr)(ScreenPtr pScreen);
+
+typedef Bool (*winRealizeInstalledPaletteProcPtr)(ScreenPtr pScreen);
+
+typedef Bool (*winInstallColormapProcPtr)(ColormapPtr pColormap);
+
+typedef Bool (*winStoreColorsProcPtr)(ColormapPtr pmap, 
+				      int ndef, xColorItem *pdefs);
+
+typedef Bool (*winCreateColormapProcPtr)(ColormapPtr pColormap);
+
+typedef Bool (*winDestroyColormapProcPtr)(ColormapPtr pColormap);
+
+typedef Bool (*winHotKeyAltTabProcPtr)(ScreenPtr);
+
+typedef Bool (*winCreatePrimarySurfaceProcPtr)(ScreenPtr);
+
+typedef Bool (*winReleasePrimarySurfaceProcPtr)(ScreenPtr);
+
+typedef Bool (*winFinishCreateWindowsWindowProcPtr)(WindowPtr pWin);
+
+typedef Bool (*winCreateScreenResourcesProc)(ScreenPtr);
+
+/* Typedef for DIX wrapper functions */
+typedef int (*winDispatchProcPtr) (ClientPtr);
+
+
+/*
+ * GC (graphics context) privates
+ */
+
+typedef struct
+{
+  HDC			hdc;
+  HDC			hdcMem;
+} winPrivGCRec, *winPrivGCPtr;
+
+
+/*
+ * Pixmap privates
+ */
+
+typedef struct
+{
+  HDC			hdcSelected;
+  HBITMAP		hBitmap;
+  BYTE			*pbBits;
+  DWORD			dwScanlineBytes;
+  BITMAPINFOHEADER	*pbmih;
+} winPrivPixmapRec, *winPrivPixmapPtr;
+
+
+/*
+ * Colormap privates
+ */
+
+typedef struct
+{
+  HPALETTE		hPalette;
+  LPDIRECTDRAWPALETTE	lpDDPalette;
+  RGBQUAD		rgbColors[WIN_NUM_PALETTE_ENTRIES];
+  PALETTEENTRY		peColors[WIN_NUM_PALETTE_ENTRIES];
+} winPrivCmapRec, *winPrivCmapPtr;
+
+/*
+ * Windows Cursor handling.
+ */ 
+  
+typedef struct {
+  /* from GetSystemMetrics */
+  int sm_cx;
+  int sm_cy;
+
+  BOOL visible;
+  HCURSOR handle;
+  QueryBestSizeProcPtr QueryBestSize;
+  miPointerSpriteFuncPtr spriteFuncs;
+} winCursorRec;
+
+/*
+ * Screen information structure that we need before privates are available
+ * in the server startup sequence.
+ */
+
+typedef struct
+{
+  ScreenPtr		pScreen;
+  
+  /* Did the user specify a height and width? */
+  Bool			fUserGaveHeightAndWidth;
+
+  DWORD			dwScreen;
+  DWORD			dwUserWidth;
+  DWORD			dwUserHeight;
+  DWORD			dwWidth;
+  DWORD			dwHeight;
+  DWORD			dwWidth_mm;
+  DWORD			dwHeight_mm;
+  DWORD			dwPaddedWidth;
+
+  /* Did the user specify a screen position? */
+  Bool			fUserGavePosition;
+  DWORD                 dwInitialX;
+  DWORD                 dwInitialY;
+
+  /*
+   * dwStride is the number of whole pixels that occupy a scanline,
+   * including those pixels that are not displayed.  This is basically
+   * a rounding up of the width.
+   */
+  DWORD			dwStride;
+
+  /* Offset of the screen in the window when using scrollbars */
+  DWORD			dwXOffset;
+  DWORD			dwYOffset;
+
+  DWORD			dwBPP;
+  DWORD			dwDepth;
+  DWORD			dwRefreshRate;
+  char			*pfb;
+  DWORD			dwEngine;
+  DWORD			dwEnginePreferred;
+  DWORD			dwClipUpdatesNBoxes;
+#ifdef XWIN_EMULATEPSEUDO
+  Bool			fEmulatePseudo;
+#endif
+  Bool			fFullScreen;
+  Bool			fDecoration;
+#ifdef XWIN_MULTIWINDOWEXTWM
+  Bool			fMWExtWM;
+  Bool			fInternalWM;
+  Bool			fAnotherWMRunning;
+#endif
+  Bool			fRootless;
+#ifdef XWIN_MULTIWINDOW
+  Bool			fMultiWindow;
+#endif
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+  Bool			fMultiMonitorOverride;
+#endif
+  Bool                  fMultipleMonitors;
+  Bool			fLessPointer;
+  Bool			fScrollbars;
+  Bool			fNoTrayIcon;
+  int			iE3BTimeout;
+  /* Windows (Alt+F4) and Unix (Ctrl+Alt+Backspace) Killkey */
+  Bool                  fUseWinKillKey;
+  Bool                  fUseUnixKillKey;
+  Bool			fIgnoreInput;
+
+  /* Did the user explicitly set this screen? */
+  Bool			fExplicitScreen;
+} winScreenInfo, *winScreenInfoPtr;
+
+
+/*
+ * Screen privates
+ */
+
+typedef struct _winPrivScreenRec
+{
+  winScreenInfoPtr	pScreenInfo;
+
+  Bool			fEnabled;
+  Bool			fClosed;
+  Bool			fActive;
+  Bool			fBadDepth;
+
+  int			iDeltaZ;
+
+  int			iConnectedClients;
+
+  CloseScreenProcPtr	CloseScreen;
+
+  DWORD			dwRedMask;
+  DWORD			dwGreenMask;
+  DWORD			dwBlueMask;
+  DWORD			dwBitsPerRGB;
+
+  DWORD			dwModeKeyStates;
+
+  /* Handle to icons that must be freed */
+  HICON			hiconNotifyIcon;
+
+  /* Last width, height, and depth of the Windows display */
+  DWORD			dwLastWindowsWidth;
+  DWORD			dwLastWindowsHeight;
+  DWORD			dwLastWindowsBitsPixel;
+
+  /* Palette management */
+  ColormapPtr		pcmapInstalled;
+
+  /* Pointer to the root visual so we only have to look it up once */
+  VisualPtr		pRootVisual;
+
+  /* 3 button emulation variables */
+  int			iE3BCachedPress;
+  Bool			fE3BFakeButton2Sent;
+
+  /* Privates used by shadow fb GDI server */
+  HBITMAP		hbmpShadow;
+  HDC			hdcScreen;
+  HDC			hdcShadow;
+  HWND			hwndScreen;
+  
+  /* Privates used by shadow fb and primary fb DirectDraw servers */
+  LPDIRECTDRAW		pdd;
+  LPDIRECTDRAWSURFACE2	pddsPrimary;
+  LPDIRECTDRAW2		pdd2;
+
+  /* Privates used by shadow fb DirectDraw server */
+  LPDIRECTDRAWSURFACE2	pddsShadow;
+  LPDDSURFACEDESC	pddsdShadow;
+
+  /* Privates used by primary fb DirectDraw server */
+  LPDIRECTDRAWSURFACE2	pddsOffscreen;
+  LPDDSURFACEDESC	pddsdOffscreen;
+  LPDDSURFACEDESC	pddsdPrimary;
+
+  /* Privates used by shadow fb DirectDraw Nonlocking server */
+  LPDIRECTDRAW4		pdd4;
+  LPDIRECTDRAWSURFACE4	pddsShadow4;
+  LPDIRECTDRAWSURFACE4	pddsPrimary4;
+  BOOL			fRetryCreateSurface;
+
+  /* Privates used by both shadow fb DirectDraw servers */
+  LPDIRECTDRAWCLIPPER	pddcPrimary;
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  /* Privates used by multi-window external window manager */
+  RootlessFrameID	widTop;
+  Bool			fRestacking;
+#endif
+
+#ifdef XWIN_MULTIWINDOW
+  /* Privates used by multi-window */
+  pthread_t		ptWMProc;
+  pthread_t		ptXMsgProc;
+  void			*pWMInfo;
+#endif
+
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+  /* Privates used by both multi-window and rootless */
+  Bool			fRootWindowShown;
+#endif
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Privates used for any module running in a seperate thread */
+  pthread_mutex_t	pmServerStarted;
+  Bool			fServerStarted;
+#endif
+  
+  /* Engine specific functions */
+  winAllocateFBProcPtr			pwinAllocateFB;
+  winShadowUpdateProcPtr		pwinShadowUpdate;
+  winCloseScreenProcPtr			pwinCloseScreen;
+  winInitVisualsProcPtr			pwinInitVisuals;
+  winAdjustVideoModeProcPtr		pwinAdjustVideoMode;
+  winCreateBoundingWindowProcPtr	pwinCreateBoundingWindow;
+  winFinishScreenInitProcPtr		pwinFinishScreenInit;
+  winBltExposedRegionsProcPtr		pwinBltExposedRegions;
+  winActivateAppProcPtr			pwinActivateApp;
+  winRedrawScreenProcPtr		pwinRedrawScreen;
+  winRealizeInstalledPaletteProcPtr	pwinRealizeInstalledPalette;
+  winInstallColormapProcPtr		pwinInstallColormap;
+  winStoreColorsProcPtr			pwinStoreColors;
+  winCreateColormapProcPtr		pwinCreateColormap;
+  winDestroyColormapProcPtr		pwinDestroyColormap;
+  winHotKeyAltTabProcPtr		pwinHotKeyAltTab;
+  winCreatePrimarySurfaceProcPtr	pwinCreatePrimarySurface;
+  winReleasePrimarySurfaceProcPtr	pwinReleasePrimarySurface;
+
+  winCreateScreenResourcesProc       pwinCreateScreenResources;
+
+#ifdef XWIN_MULTIWINDOW
+  /* Window Procedures for MultiWindow mode */
+  winFinishCreateWindowsWindowProcPtr	pwinFinishCreateWindowsWindow;
+#endif
+
+  /* Window Procedures for Rootless mode */
+  CreateWindowProcPtr			CreateWindow;
+  DestroyWindowProcPtr			DestroyWindow;
+  PositionWindowProcPtr			PositionWindow;
+  ChangeWindowAttributesProcPtr		ChangeWindowAttributes;
+  RealizeWindowProcPtr			RealizeWindow;
+  UnrealizeWindowProcPtr		UnrealizeWindow;
+  ValidateTreeProcPtr			ValidateTree;
+  PostValidateTreeProcPtr		PostValidateTree;
+  WindowExposuresProcPtr		WindowExposures;
+  CopyWindowProcPtr			CopyWindow;
+  ClearToBackgroundProcPtr		ClearToBackground;
+  ClipNotifyProcPtr			ClipNotify;
+  RestackWindowProcPtr			RestackWindow;
+  ReparentWindowProcPtr			ReparentWindow;
+  ResizeWindowProcPtr			ResizeWindow;
+  MoveWindowProcPtr			MoveWindow;
+  SetShapeProcPtr			SetShape;
+
+  winCursorRec                          cursor;
+} winPrivScreenRec;
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+typedef struct {
+  RootlessWindowPtr	pFrame;
+  HWND			hWnd;
+  int			dwWidthBytes;
+  BITMAPINFOHEADER	*pbmihShadow;
+  HBITMAP		hbmpShadow;
+  HDC			hdcShadow;
+  HDC			hdcScreen;
+  BOOL			fResized;
+  BOOL			fRestackingNow;
+  BOOL			fClose;
+  BOOL			fMovingOrSizing;
+  BOOL			fDestroyed;//for debug
+  char			*pfb;
+} win32RootlessWindowRec, *win32RootlessWindowPtr;
+#endif
+
+
+typedef struct {
+  pointer		value;
+  XID			id;
+} WindowIDPairRec, *WindowIDPairPtr;
+
+
+/*
+ * Extern declares for general global variables
+ */
+
+extern winScreenInfo		g_ScreenInfo[];
+extern miPointerScreenFuncRec	g_winPointerCursorFuncs;
+extern DWORD			g_dwEvents;
+#ifdef HAS_DEVWINDOWS
+extern int			g_fdMessageQueue;
+#endif
+extern DevPrivateKey		g_iScreenPrivateKey;
+extern DevPrivateKey		g_iCmapPrivateKey;
+extern DevPrivateKey		g_iGCPrivateKey;
+extern DevPrivateKey		g_iPixmapPrivateKey;
+extern DevPrivateKey		g_iWindowPrivateKey;
+extern unsigned long		g_ulServerGeneration;
+extern DWORD			g_dwEnginesSupported;
+extern HINSTANCE		g_hInstance;
+extern int                      g_copyROP[];
+extern int                      g_patternROP[];
+extern const char *		g_pszQueryHost;
+extern DeviceIntPtr             g_pwinPointer;
+extern DeviceIntPtr             g_pwinKeyboard;
+
+
+/*
+ * Extern declares for dynamically loaded libraries and function pointers
+ */
+
+extern HMODULE			g_hmodDirectDraw;
+extern FARPROC			g_fpDirectDrawCreate;
+extern FARPROC			g_fpDirectDrawCreateClipper;
+
+extern HMODULE			g_hmodCommonControls;
+extern FARPROC			g_fpTrackMouseEvent;
+
+
+/*
+ * Screen privates macros
+ */
+
+#define winGetScreenPriv(pScreen) ((winPrivScreenPtr) \
+    dixLookupPrivate(&(pScreen)->devPrivates, g_iScreenPrivateKey))
+
+#define winSetScreenPriv(pScreen,v) \
+    dixSetPrivate(&(pScreen)->devPrivates, g_iScreenPrivateKey, v)
+
+#define winScreenPriv(pScreen) \
+	winPrivScreenPtr pScreenPriv = winGetScreenPriv(pScreen)
+
+
+/*
+ * Colormap privates macros
+ */
+
+#define winGetCmapPriv(pCmap) ((winPrivCmapPtr) \
+    dixLookupPrivate(&(pCmap)->devPrivates, g_iCmapPrivateKey))
+
+#define winSetCmapPriv(pCmap,v) \
+    dixSetPrivate(&(pCmap)->devPrivates, g_iCmapPrivateKey, v)
+
+#define winCmapPriv(pCmap) \
+	winPrivCmapPtr pCmapPriv = winGetCmapPriv(pCmap)
+
+
+/*
+ * GC privates macros
+ */
+
+#define winGetGCPriv(pGC) ((winPrivGCPtr) \
+    dixLookupPrivate(&(pGC)->devPrivates, g_iGCPrivateKey))
+
+#define winSetGCPriv(pGC,v) \
+    dixSetPrivate(&(pGC)->devPrivates, g_iGCPrivateKey, v)
+
+#define winGCPriv(pGC) \
+	winPrivGCPtr pGCPriv = winGetGCPriv(pGC)
+
+
+/*
+ * Pixmap privates macros
+ */
+
+#define winGetPixmapPriv(pPixmap) ((winPrivPixmapPtr) \
+    dixLookupPrivate(&(pPixmap)->devPrivates, g_iPixmapPrivateKey))
+
+#define winSetPixmapPriv(pPixmap,v) \
+    dixLookupPrivate(&(pPixmap)->devPrivates, g_iPixmapPrivateKey, v)
+
+#define winPixmapPriv(pPixmap) \
+	winPrivPixmapPtr pPixmapPriv = winGetPixmapPriv(pPixmap)
+
+
+/*
+ * Window privates macros
+ */
+
+#define winGetWindowPriv(pWin) ((winPrivWinPtr) \
+    dixLookupPrivate(&(pWin)->devPrivates, g_iWindowPrivateKey))
+
+#define winSetWindowPriv(pWin,v) \
+    dixLookupPrivate(&(pWin)->devPrivates, g_iWindowPrivateKey, v)
+
+#define winWindowPriv(pWin) \
+	winPrivWinPtr pWinPriv = winGetWindowPriv(pWin)
+
+/*
+ * wrapper macros 
+ */
+#define _WIN_WRAP(priv, real, mem, func) {\
+    priv->mem = real->mem; \
+    real->mem = func; \
+}
+
+#define _WIN_UNWRAP(priv, real, mem) {\
+    real->mem = priv->mem; \
+}
+
+#define WIN_WRAP(mem, func) _WIN_WRAP(pScreenPriv, pScreen, mem, func) 
+
+#define WIN_UNWRAP(mem) _WIN_UNWRAP(pScreenPriv, pScreen, mem)
+
+/*
+ * BEGIN DDX and DIX Function Prototypes
+ */
+
+
+/*
+ * winallpriv.c
+ */
+
+Bool
+winAllocatePrivates (ScreenPtr pScreen);
+
+Bool
+winInitCmapPrivates (ColormapPtr pCmap, int index);
+
+Bool
+winAllocateCmapPrivates (ColormapPtr pCmap);
+
+
+/*
+ * winauth.c
+ */
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+Bool
+winGenerateAuthorization (void);
+void winSetAuthorization(void);
+#endif
+
+
+/*
+ * winblock.c
+ */
+
+void
+winBlockHandler (int nScreen,
+		 pointer pBlockData,
+		 pointer pTimeout,
+		 pointer pReadMask);
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winclip.c
+ */
+
+RegionPtr
+winPixmapToRegionNativeGDI (PixmapPtr pPix);
+#endif
+
+
+#ifdef XWIN_CLIPBOARD
+/*
+ * winclipboardinit.c
+ */
+
+Bool
+winInitClipboard (void);
+
+void
+winFixClipboardChain (void);
+#endif
+
+
+/*
+ * wincmap.c
+ */
+
+void
+winSetColormapFunctions (ScreenPtr pScreen);
+
+Bool
+winCreateDefColormap (ScreenPtr pScreen);
+
+
+/*
+ * wincreatewnd.c
+ */
+
+Bool
+winCreateBoundingWindowFullScreen (ScreenPtr pScreen);
+
+Bool
+winCreateBoundingWindowWindowed (ScreenPtr pScreen);
+
+
+/*
+ * windialogs.c
+ */
+
+void
+winDisplayExitDialog (winPrivScreenPtr pScreenPriv);
+
+void
+winDisplayDepthChangeDialog (winPrivScreenPtr pScreenPriv);
+
+void
+winDisplayAboutDialog (winPrivScreenPtr pScreenPriv);
+
+
+/*
+ * winengine.c
+ */
+
+void
+winDetectSupportedEngines (void);
+
+Bool
+winSetEngine (ScreenPtr pScreen);
+
+Bool
+winGetDDProcAddresses (void);
+
+
+/*
+ * winerror.c
+ */
+
+#ifdef DDXOSVERRORF
+void
+OSVenderVErrorF (const char *pszFormat, va_list va_args);
+#endif
+
+void
+winMessageBoxF (const char *pszError, UINT uType, ...);
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winfillsp.c
+ */
+
+void
+winFillSpansNativeGDI (DrawablePtr	pDrawable,
+		       GCPtr		pGC,
+		       int		nSpans,
+		       DDXPointPtr	pPoints,
+		       int		*pWidths,
+		       int		fSorted);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winfont.c
+ */
+
+Bool
+winRealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont);
+
+Bool
+winUnrealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * wingc.c
+ */
+
+Bool
+winCreateGCNativeGDI (GCPtr pGC);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * wingetsp.c
+ */
+
+void
+winGetSpansNativeGDI (DrawablePtr	pDrawable, 
+		      int		wMax, 
+		      DDXPointPtr	pPoints, 
+		      int		*pWidths, 
+		      int		nSpans, 
+		      char		*pDst);
+#endif
+
+
+/*
+ * winglobals.c
+ */
+
+void
+winInitializeGlobals (void);
+
+
+/*
+ * winkeybd.c
+ */
+
+void
+winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode);
+
+int
+winKeybdProc (DeviceIntPtr pDeviceInt, int iState);
+
+void
+winInitializeModeKeyStates (void);
+
+void
+winRestoreModeKeyStates (void);
+
+Bool
+winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam);
+
+void
+winKeybdReleaseKeys (void);
+
+void
+winSendKeyEvent (DWORD dwKey, Bool fDown);
+
+BOOL
+winCheckKeyPressed(WPARAM wParam, LPARAM lParam);
+
+void
+winFixShiftKeys (int iScanCode);
+
+/*
+ * winkeyhook.c
+ */
+
+Bool
+winInstallKeyboardHookLL (void);
+
+void
+winRemoveKeyboardHookLL (void);
+
+
+/*
+ * winmisc.c
+ */
+
+#ifdef XWIN_NATIVEGDI
+void
+winQueryBestSizeNativeGDI (int class, unsigned short *pWidth,
+			   unsigned short *pHeight, ScreenPtr pScreen);
+#endif
+
+CARD8
+winCountBits (DWORD dw);
+
+Bool
+winUpdateFBPointer (ScreenPtr pScreen, void *pbits);
+
+#ifdef XWIN_NATIVEGDI
+BOOL
+winPaintBackground (HWND hwnd, COLORREF colorref);
+#endif
+
+
+/*
+ * winmouse.c
+ */
+
+int
+winMouseProc (DeviceIntPtr pDeviceInt, int iState);
+
+int
+winMouseWheel (ScreenPtr pScreen, int iDeltaZ);
+
+void
+winMouseButtonsSendEvent (int iEventType, int iButton);
+
+int
+winMouseButtonsHandle (ScreenPtr pScreen,
+		       int iEventType, int iButton,
+		       WPARAM wParam);
+
+void
+winEnqueueMotion(int x, int y);
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winnativegdi.c
+ */
+
+HBITMAP
+winCreateDIBNativeGDI (int iWidth, int iHeight, int iDepth,
+		       BYTE **ppbBits, BITMAPINFO **ppbmi);
+
+Bool
+winSetEngineFunctionsNativeGDI (ScreenPtr pScreen);
+#endif
+
+
+#ifdef XWIN_PRIMARYFB
+/*
+ * winpfbddd.c
+ */
+
+Bool
+winSetEngineFunctionsPrimaryDD (ScreenPtr pScreen);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winpixmap.c
+ */
+
+PixmapPtr
+winCreatePixmapNativeGDI (ScreenPtr pScreen, int width, int height, int depth,
+			  unsigned usage_hint);
+
+Bool
+winDestroyPixmapNativeGDI (PixmapPtr pPixmap);
+
+Bool
+winModifyPixmapHeaderNativeGDI (PixmapPtr pPixmap,
+				int iWidth, int iHeight,
+				int iDepth,
+				int iBitsPerPixel,
+				int devKind,
+				pointer pPixData);
+#endif
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winpolyline.c
+ */
+
+void
+winPolyLineNativeGDI (DrawablePtr	pDrawable,
+		      GCPtr		pGC,
+		      int		mode,
+		      int		npt,
+		      DDXPointPtr	ppt);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winpushpxl.c
+ */
+
+void
+winPushPixels (GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDrawable,
+	       int dx, int dy, int xOrg, int yOrg);
+#endif
+
+
+/*
+ * winscrinit.c
+ */
+
+Bool
+winScreenInit (int index,
+	       ScreenPtr pScreen,
+	       int argc, char **argv);
+
+Bool
+winFinishScreenInitFB (int index,
+		       ScreenPtr pScreen,
+		       int argc, char **argv);
+
+#if defined(XWIN_NATIVEGDI)
+Bool
+winFinishScreenInitNativeGDI (int index,
+			      ScreenPtr pScreen,
+			      int argc, char **argv);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winsetsp.c
+ */
+
+void
+winSetSpansNativeGDI (DrawablePtr	pDrawable,
+		      GCPtr		pGC,
+		      char		*pSrc,
+		      DDXPointPtr	pPoints,
+		      int		*pWidth,
+		      int		nSpans,
+		      int		fSorted);
+#endif
+
+
+/*
+ * winshaddd.c
+ */
+
+Bool
+winSetEngineFunctionsShadowDD (ScreenPtr pScreen);
+
+
+/*
+ * winshadddnl.c
+ */
+
+Bool
+winSetEngineFunctionsShadowDDNL (ScreenPtr pScreen);
+
+
+/*
+ * winshadgdi.c
+ */
+
+Bool
+winSetEngineFunctionsShadowGDI (ScreenPtr pScreen);
+
+
+/*
+ * winwakeup.c
+ */
+
+void
+winWakeupHandler (int nScreen,
+		  pointer pWakeupData,
+		  unsigned long ulResult,
+		  pointer pReadmask);
+
+
+/*
+ * winwindow.c
+ */
+
+#ifdef XWIN_NATIVEGDI
+Bool
+winCreateWindowNativeGDI (WindowPtr pWin);
+
+Bool
+winDestroyWindowNativeGDI (WindowPtr pWin);
+
+Bool
+winPositionWindowNativeGDI (WindowPtr pWin, int x, int y);
+
+void 
+winCopyWindowNativeGDI (WindowPtr pWin,
+			DDXPointRec ptOldOrg,
+			RegionPtr prgnSrc);
+
+Bool
+winChangeWindowAttributesNativeGDI (WindowPtr pWin, unsigned long mask);
+
+Bool
+winUnmapWindowNativeGDI (WindowPtr pWindow);
+
+Bool
+winMapWindowNativeGDI (WindowPtr pWindow);
+#endif
+
+Bool
+winCreateWindowRootless (WindowPtr pWindow);
+
+Bool
+winDestroyWindowRootless (WindowPtr pWindow);
+
+Bool
+winPositionWindowRootless (WindowPtr pWindow, int x, int y);
+
+Bool
+winChangeWindowAttributesRootless (WindowPtr pWindow, unsigned long mask);
+
+Bool
+winUnmapWindowRootless (WindowPtr pWindow);
+
+Bool
+winMapWindowRootless (WindowPtr pWindow);
+
+void
+winSetShapeRootless (WindowPtr pWindow);
+
+
+/*
+ * winmultiwindowicons.c - Used by both multi-window and Win32Rootless
+ */
+
+HICON
+winXIconToHICON (WindowPtr pWin, int iconSize);
+
+void
+winSelectIcons(WindowPtr pWin, HICON *pIcon, HICON *pSmallIcon);
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * winmultiwindowshape.c
+ */
+
+void
+winReshapeMultiWindow (WindowPtr pWin);
+
+void
+winSetShapeMultiWindow (WindowPtr pWindow);
+
+void
+winUpdateRgnMultiWindow (WindowPtr pWindow);
+#endif
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * winmultiwindowwindow.c
+ */
+
+Bool
+winCreateWindowMultiWindow (WindowPtr pWindow);
+
+Bool
+winDestroyWindowMultiWindow (WindowPtr pWindow);
+
+Bool
+winPositionWindowMultiWindow (WindowPtr pWindow, int x, int y);
+
+Bool
+winChangeWindowAttributesMultiWindow (WindowPtr pWindow, unsigned long mask);
+
+Bool
+winUnmapWindowMultiWindow (WindowPtr pWindow);
+
+Bool
+winMapWindowMultiWindow (WindowPtr pWindow);
+
+void
+winReparentWindowMultiWindow (WindowPtr pWin, WindowPtr pPriorParent);
+
+void
+winRestackWindowMultiWindow (WindowPtr pWin, WindowPtr pOldNextSib);
+
+void
+winReorderWindowsMultiWindow (void);
+
+void
+winResizeWindowMultiWindow (WindowPtr pWin, int x, int y, unsigned int w,
+			    unsigned int h, WindowPtr pSib);
+void
+winMoveWindowMultiWindow (WindowPtr pWin, int x, int y,
+			  WindowPtr pSib, VTKind kind);
+
+void
+winCopyWindowMultiWindow (WindowPtr pWin, DDXPointRec oldpt,
+			  RegionPtr oldRegion);
+
+XID
+winGetWindowID (WindowPtr pWin);
+
+int
+winAdjustXWindow (WindowPtr pWin, HWND hwnd);
+#endif
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * winmultiwindowwndproc.c
+ */
+
+LRESULT CALLBACK
+winTopLevelWindowProc (HWND hwnd, UINT message, 
+		       WPARAM wParam, LPARAM lParam);
+#endif
+
+
+/*
+ * wintrayicon.c
+ */
+
+void
+winInitNotifyIcon (winPrivScreenPtr pScreenPriv);
+
+void
+winDeleteNotifyIcon (winPrivScreenPtr pScreenPriv);
+
+LRESULT
+winHandleIconMessage (HWND hwnd, UINT message,
+		      WPARAM wParam, LPARAM lParam,
+		      winPrivScreenPtr pScreenPriv);
+
+
+/*
+ * winwndproc.c
+ */
+
+LRESULT CALLBACK
+winWindowProc (HWND hWnd, UINT message, 
+	       WPARAM wParam, LPARAM lParam);
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+/*
+ * winwin32rootless.c
+ */
+
+Bool
+winMWExtWMCreateFrame (RootlessWindowPtr pFrame, ScreenPtr pScreen,
+			     int newX, int newY, RegionPtr pShape);
+
+void
+winMWExtWMDestroyFrame (RootlessFrameID wid);
+
+void
+winMWExtWMMoveFrame (RootlessFrameID wid, ScreenPtr pScreen, int newX, int newY);
+
+void
+winMWExtWMResizeFrame (RootlessFrameID wid, ScreenPtr pScreen,
+			     int newX, int newY, unsigned int newW, unsigned int newH,
+			     unsigned int gravity);
+
+void
+winMWExtWMRestackFrame (RootlessFrameID wid, RootlessFrameID nextWid);
+
+void
+winMWExtWMReshapeFrame (RootlessFrameID wid, RegionPtr pShape);
+
+void
+winMWExtWMUnmapFrame (RootlessFrameID wid);
+
+void
+winMWExtWMStartDrawing (RootlessFrameID wid, char **pixelData, int *bytesPerRow);
+
+void
+winMWExtWMStopDrawing (RootlessFrameID wid, Bool flush);
+
+void
+winMWExtWMUpdateRegion (RootlessFrameID wid, RegionPtr pDamage);
+
+void
+winMWExtWMDamageRects (RootlessFrameID wid, int count, const BoxRec *rects,
+			     int shift_x, int shift_y);
+
+void
+winMWExtWMRootlessSwitchWindow (RootlessWindowPtr pFrame, WindowPtr oldWin);
+
+void
+winMWExtWMCopyBytes (unsigned int width, unsigned int height,
+			   const void *src, unsigned int srcRowBytes,
+			   void *dst, unsigned int dstRowBytes);
+
+void
+winMWExtWMFillBytes (unsigned int width, unsigned int height, unsigned int value,
+			   void *dst, unsigned int dstRowBytes);
+
+int
+winMWExtWMCompositePixels (unsigned int width, unsigned int height, unsigned int function,
+				 void *src[2], unsigned int srcRowBytes[2],
+				 void *mask, unsigned int maskRowBytes,
+				 void *dst[2], unsigned int dstRowBytes[2]);
+
+void
+winMWExtWMCopyWindow (RootlessFrameID wid, int dstNrects, const BoxRec *dstRects,
+			    int dx, int dy);
+#endif
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+/*
+ * winwin32rootlesswindow.c
+ */
+
+void
+winMWExtWMReorderWindows (ScreenPtr pScreen);
+
+void
+winMWExtWMMoveXWindow (WindowPtr pWin, int x, int y);
+
+void
+winMWExtWMResizeXWindow (WindowPtr pWin, int w, int h);
+
+void
+winMWExtWMMoveResizeXWindow (WindowPtr pWin, int x, int y, int w, int h);
+
+void
+winMWExtWMUpdateIcon (Window id);
+
+void
+winMWExtWMUpdateWindowDecoration (win32RootlessWindowPtr pRLWinPriv,
+				  winScreenInfoPtr pScreenInfo);
+
+wBOOL CALLBACK
+winMWExtWMDecorateWindow (HWND hwnd, LPARAM lParam);
+
+Bool
+winIsInternalWMRunning (winScreenInfoPtr pScreenInfo);
+
+void
+winMWExtWMRestackWindows (ScreenPtr pScreen);
+#endif
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+/*
+ * winwin32rootlesswndproc.c
+ */
+
+LRESULT CALLBACK
+winMWExtWMWindowProc (HWND hwnd, UINT message, 
+			    WPARAM wParam, LPARAM lParam);
+#endif
+
+
+/*
+ * winwindowswm.c
+ */
+
+void
+winWindowsWMSendEvent (int type, unsigned int mask, int which, int arg,
+		       Window window, int x, int y, int w, int h);
+
+void
+winWindowsWMExtensionInit (void);
+
+/*
+ * wincursor.c
+ */
+
+Bool
+winInitCursor (ScreenPtr pScreen);
+
+/*
+ * END DDX and DIX Function Prototypes
+ */
+
+#endif /* _WIN_H_ */
+
diff --git a/xorg-server/hw/xwin/winauth.c b/xorg-server/hw/xwin/winauth.c
index fcd1872da..2780f6acd 100644
--- a/xorg-server/hw/xwin/winauth.c
+++ b/xorg-server/hw/xwin/winauth.c
@@ -1,202 +1,202 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-
-#include "win.h"
-
-/* Includes for authorization */
-#include "securitysrv.h"
-
-
-/*
- * Constants
- */
-
-#define AUTH_NAME	"MIT-MAGIC-COOKIE-1"
-
-
-/*
- * Locals
- */
-
-static XID g_authId = 0;
-static unsigned int g_uiAuthDataLen = 0;
-static char *g_pAuthData = NULL;
-
-/*
- * Code to generate a MIT-MAGIC-COOKIE-1, copied from under XCSECURITY
- */
-
-#ifndef XCSECURITY
-static
-void
-GenerateRandomData (int len, char *buf)
-{
-    int fd;
-
-    fd = open("/dev/urandom", O_RDONLY);
-    read(fd, buf, len);
-    close(fd);
-}
-
-
-static char cookie[16]; /* 128 bits */
-
-XID
-static MitGenerateCookie (
-    unsigned	data_length,
-    char	*data,
-    XID		id,
-    unsigned	*data_length_return,
-    char	**data_return)
-{
-    int i = 0;
-    int status;
-
-    while (data_length--)
-    {
-	cookie[i++] += *data++;
-	if (i >= sizeof (cookie)) i = 0;
-    }
-    GenerateRandomData(sizeof (cookie), cookie);
-    status = MitAddCookie(sizeof (cookie), cookie, id);
-    if (!status)
-    {
-	id = -1;
-    }
-    else
-    {
-	*data_return = cookie;
-	*data_length_return = sizeof (cookie);
-    }
-    return id;
-}
-
-static
-XID
-GenerateAuthorization(
-	unsigned name_length,
-	char	*name,
-	unsigned data_length,
-	char	*data,
-	unsigned *data_length_return,
-	char	**data_return)
-{
-    return MitGenerateCookie(data_length, data,
-                             FakeClientID(0), data_length_return, data_return);
-}
-#endif
-
-/*
- * Generate authorization cookie for internal server clients
- */
-
-Bool
-winGenerateAuthorization ()
-{
-  Bool				fFreeAuth = FALSE;
-  SecurityAuthorizationPtr	pAuth = NULL;
-
-  /* Call OS layer to generate authorization key */
-  g_authId = GenerateAuthorization (strlen (AUTH_NAME),
-				    AUTH_NAME,
-				    0,
-				    NULL,
-				    &g_uiAuthDataLen,
-				    &g_pAuthData);
-  if ((XID) ~0L == g_authId)
-    {
-      ErrorF ("winGenerateAuthorization - GenerateAuthorization failed\n");
-      goto auth_bailout;
-    }
-
-  else
-    {
-      winDebug("winGenerateAuthorization - GenerateAuthorization success!\n"
-	      "AuthDataLen: %d AuthData: %s\n",
-	      g_uiAuthDataLen, g_pAuthData);
-    }
-
-#ifdef XCSECURITY
-  /* Allocate structure for additional auth information */
-  pAuth = (SecurityAuthorizationPtr) 
-    xalloc (sizeof (SecurityAuthorizationRec));
-  if (!(pAuth))
-    {
-      ErrorF ("winGenerateAuthorization - Failed allocating "
-	      "SecurityAuthorizationPtr.\n");
-      goto auth_bailout;
-    }
-  
-  /* Fill in the auth fields */
-  pAuth->id = g_authId;
-  pAuth->timeout = 0; /* live for x seconds after refcnt == 0 */
-  pAuth->group = None;
-  pAuth->trustLevel = XSecurityClientTrusted;
-  pAuth->refcnt = 1; /* this auth must stick around */
-  pAuth->secondsRemaining = 0;
-  pAuth->timer = NULL;
-  pAuth->eventClients = NULL;
-  
-  /* Add the authorization to the server's auth list */
-  if (!AddResource (g_authId,
-		    SecurityAuthorizationResType,
-		    pAuth))
-    {
-      ErrorF ("winGenerateAuthorization - AddResource failed for auth.\n");
-      fFreeAuth = TRUE;
-      goto auth_bailout;
-    }
-  
-  /* Don't free the auth data, since it is still used internally */
-  pAuth = NULL;
-#endif
-
-  return TRUE;
-
- auth_bailout:
-  if (fFreeAuth)
-    xfree (pAuth);
-  
-  return FALSE;
-}
-
-/* Use our generated cookie for authentication */
-void
-winSetAuthorization(void)
-{
-  XSetAuthorization (AUTH_NAME,
-		     strlen (AUTH_NAME),
-		     g_pAuthData,
-		     g_uiAuthDataLen);
-}
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+
+#include "win.h"
+
+/* Includes for authorization */
+#include "securitysrv.h"
+
+
+/*
+ * Constants
+ */
+
+#define AUTH_NAME	"MIT-MAGIC-COOKIE-1"
+
+
+/*
+ * Locals
+ */
+
+static XID g_authId = 0;
+static unsigned int g_uiAuthDataLen = 0;
+static char *g_pAuthData = NULL;
+
+/*
+ * Code to generate a MIT-MAGIC-COOKIE-1, copied from under XCSECURITY
+ */
+
+#ifndef XCSECURITY
+static
+void
+GenerateRandomData (int len, char *buf)
+{
+    int fd;
+
+    fd = open("/dev/urandom", O_RDONLY);
+    read(fd, buf, len);
+    close(fd);
+}
+
+
+static char cookie[16]; /* 128 bits */
+
+XID
+static MitGenerateCookie (
+    unsigned	data_length,
+    char	*data,
+    XID		id,
+    unsigned	*data_length_return,
+    char	**data_return)
+{
+    int i = 0;
+    int status;
+
+    while (data_length--)
+    {
+	cookie[i++] += *data++;
+	if (i >= sizeof (cookie)) i = 0;
+    }
+    GenerateRandomData(sizeof (cookie), cookie);
+    status = MitAddCookie(sizeof (cookie), cookie, id);
+    if (!status)
+    {
+	id = -1;
+    }
+    else
+    {
+	*data_return = cookie;
+	*data_length_return = sizeof (cookie);
+    }
+    return id;
+}
+
+static
+XID
+GenerateAuthorization(
+	unsigned name_length,
+	char	*name,
+	unsigned data_length,
+	char	*data,
+	unsigned *data_length_return,
+	char	**data_return)
+{
+    return MitGenerateCookie(data_length, data,
+                             FakeClientID(0), data_length_return, data_return);
+}
+#endif
+
+/*
+ * Generate authorization cookie for internal server clients
+ */
+
+Bool
+winGenerateAuthorization (void)
+{
+  Bool				fFreeAuth = FALSE;
+  SecurityAuthorizationPtr	pAuth = NULL;
+
+  /* Call OS layer to generate authorization key */
+  g_authId = GenerateAuthorization (strlen (AUTH_NAME),
+				    AUTH_NAME,
+				    0,
+				    NULL,
+				    &g_uiAuthDataLen,
+				    &g_pAuthData);
+  if ((XID) ~0L == g_authId)
+    {
+      ErrorF ("winGenerateAuthorization - GenerateAuthorization failed\n");
+      goto auth_bailout;
+    }
+
+  else
+    {
+      winDebug("winGenerateAuthorization - GenerateAuthorization success!\n"
+	      "AuthDataLen: %d AuthData: %s\n",
+	      g_uiAuthDataLen, g_pAuthData);
+    }
+
+#ifdef XCSECURITY
+  /* Allocate structure for additional auth information */
+  pAuth = (SecurityAuthorizationPtr) 
+    xalloc (sizeof (SecurityAuthorizationRec));
+  if (!(pAuth))
+    {
+      ErrorF ("winGenerateAuthorization - Failed allocating "
+	      "SecurityAuthorizationPtr.\n");
+      goto auth_bailout;
+    }
+  
+  /* Fill in the auth fields */
+  pAuth->id = g_authId;
+  pAuth->timeout = 0; /* live for x seconds after refcnt == 0 */
+  pAuth->group = None;
+  pAuth->trustLevel = XSecurityClientTrusted;
+  pAuth->refcnt = 1; /* this auth must stick around */
+  pAuth->secondsRemaining = 0;
+  pAuth->timer = NULL;
+  pAuth->eventClients = NULL;
+  
+  /* Add the authorization to the server's auth list */
+  if (!AddResource (g_authId,
+		    SecurityAuthorizationResType,
+		    pAuth))
+    {
+      ErrorF ("winGenerateAuthorization - AddResource failed for auth.\n");
+      fFreeAuth = TRUE;
+      goto auth_bailout;
+    }
+  
+  /* Don't free the auth data, since it is still used internally */
+  pAuth = NULL;
+#endif
+
+  return TRUE;
+
+ auth_bailout:
+  if (fFreeAuth)
+    xfree (pAuth);
+  
+  return FALSE;
+}
+
+/* Use our generated cookie for authentication */
+void
+winSetAuthorization(void)
+{
+  XSetAuthorization (AUTH_NAME,
+		     strlen (AUTH_NAME),
+		     g_pAuthData,
+		     g_uiAuthDataLen);
+}
diff --git a/xorg-server/hw/xwin/winclipboardthread.c b/xorg-server/hw/xwin/winclipboardthread.c
index a3809034e..01f288047 100644
--- a/xorg-server/hw/xwin/winclipboardthread.c
+++ b/xorg-server/hw/xwin/winclipboardthread.c
@@ -1,462 +1,462 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *Copyright (C) Colin Harrison 2005-2008
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the copyright holder(s)
- *and author(s) shall not be used in advertising or otherwise to promote
- *the sale, use or other dealings in this Software without prior written
- *authorization from the copyright holder(s) and author(s).
- *
- * Authors:	Harold L Hunt II
- *              Colin Harrison
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <sys/types.h>
-#include "winclipboard.h"
-#ifdef __CYGWIN__
-#include <errno.h>
-#endif
-#include "misc.h"
-
-
-/*
- * References to external symbols
- */
-
-extern Bool		g_fUnicodeClipboard;
-extern unsigned long	serverGeneration;
-extern Bool		g_fClipboardStarted;
-extern HWND		g_hwndClipboard;
-extern void		*g_pClipboardDisplay;
-extern Window		g_iClipboardWindow;
-
-
-/*
- * Global variables
- */
-
-static jmp_buf			g_jmpEntry;
-Bool				g_fUnicodeSupport = FALSE;
-Bool				g_fUseUnicode = FALSE;
-
-
-/*
- * Local function prototypes
- */
-
-static int
-winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr);
-
-static int
-winClipboardIOErrorHandler (Display *pDisplay);
-
-
-/*
- * Main thread function
- */
-
-void *
-winClipboardProc (void *pvNotUsed)
-{
-  Atom			atomClipboard, atomClipboardManager;
-  int			iReturn;
-  HWND			hwnd = NULL;
-  int			iConnectionNumber = 0;
-#ifdef HAS_DEVWINDOWS
-  int			fdMessageQueue = 0;
-#else
-  struct timeval        tvTimeout;
-#endif
-  fd_set		fdsRead;
-  int			iMaxDescriptor;
-  Display		*pDisplay = NULL;
-  Window		iWindow = None;
-  int			iRetries;
-  Bool			fUseUnicode;
-  char			szDisplay[512];
-  int			iSelectError;
-
-  ErrorF ("winClipboardProc - Hello\n");
-
-  /* Do we have Unicode support? */
-  g_fUnicodeSupport = winClipboardDetectUnicodeSupport ();
-
-  /* Do we use Unicode clipboard? */
-  fUseUnicode = g_fUnicodeClipboard && g_fUnicodeSupport;
-
-  /* Save the Unicode support flag in a global */
-  g_fUseUnicode = fUseUnicode;
-
-  /* Allow multiple threads to access Xlib */
-  if (XInitThreads () == 0)
-    {
-      ErrorF ("winClipboardProc - XInitThreads failed.\n");
-      pthread_exit (NULL);
-    }
-
-  /* See if X supports the current locale */
-  if (XSupportsLocale () == False)
-    {
-      ErrorF ("winClipboardProc - Warning: Locale not supported by X.\n");
-    }
-
-  /* Set jump point for Error exits */
-  iReturn = setjmp (g_jmpEntry);
-  
-  /* Check if we should continue operations */
-  if (iReturn != WIN_JMP_ERROR_IO
-      && iReturn != WIN_JMP_OKAY)
-    {
-      /* setjmp returned an unknown value, exit */
-      ErrorF ("winClipboardProc - setjmp returned: %d exiting\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-  else if (iReturn == WIN_JMP_ERROR_IO)
-    {
-      /* TODO: Cleanup the Win32 window and free any allocated memory */
-      ErrorF ("winClipboardProc - setjmp returned for IO Error Handler.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Use our generated cookie for authentication */
-  winSetAuthorization();
-
-  /* Set error handler */
-  XSetErrorHandler (winClipboardErrorHandler);
-  XSetIOErrorHandler (winClipboardIOErrorHandler);
-
-  /* Initialize retry count */
-  iRetries = 0;
-
-  /* Setup the display connection string x */
-  /*
-   * NOTE: Always connect to screen 0 since we require that screen
-   * numbers start at 0 and increase without gaps.  We only need
-   * to connect to one screen on the display to get events
-   * for all screens on the display.  That is why there is only
-   * one clipboard client thread.
-   */
-  snprintf (szDisplay,
-	    512,
-	    "127.0.0.1:%s.0",
-	    display);
-
-  /* Print the display connection string */
-  ErrorF ("winClipboardProc - DISPLAY=%s\n", szDisplay);
-
-  /* Open the X display */
-  do
-    {
-      pDisplay = XOpenDisplay (szDisplay);
-      if (pDisplay == NULL)
-	{
-	  ErrorF ("winClipboardProc - Could not open display, "
-		  "try: %d, sleeping: %d\n",
-		  iRetries + 1, WIN_CONNECT_DELAY);
-	  ++iRetries;
-	  sleep (WIN_CONNECT_DELAY);
-	  continue;
-	}
-      else
-	break;
-    }
-  while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
-
-  /* Make sure that the display opened */
-  if (pDisplay == NULL)
-    {
-      ErrorF ("winClipboardProc - Failed opening the display, giving up\n");
-      pthread_exit (NULL);
-    }
-
-  /* Save the display in the screen privates */
-  g_pClipboardDisplay = pDisplay;
-
-  ErrorF ("winClipboardProc - XOpenDisplay () returned and "
-	  "successfully opened the display.\n");
-
-  /* Get our connection number */
-  iConnectionNumber = ConnectionNumber (pDisplay);
-
-#ifdef HAS_DEVWINDOWS
-  /* Open a file descriptor for the windows message queue */
-  fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, O_RDONLY);
-  if (fdMessageQueue == -1)
-    {
-      ErrorF ("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME);
-      pthread_exit (NULL);
-    }
-
-  /* Find max of our file descriptors */
-  iMaxDescriptor = max (fdMessageQueue, iConnectionNumber) + 1;
-#else
-  iMaxDescriptor = iConnectionNumber + 1;
-#endif
-
-  /* Create atoms */
-  atomClipboard = XInternAtom (pDisplay, "CLIPBOARD", False);
-  atomClipboardManager = XInternAtom (pDisplay, "CLIPBOARD_MANAGER", False);
-
-  /* Create a messaging window */
-  iWindow = XCreateSimpleWindow (pDisplay,
-				 DefaultRootWindow (pDisplay),
-				 1, 1,
-				 500, 500,
-				 0,
-				 BlackPixel (pDisplay, 0),
-				 BlackPixel (pDisplay, 0));
-  if (iWindow == 0)
-    {
-      ErrorF ("winClipboardProc - Could not create an X window.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Select event types to watch */
-  if (XSelectInput (pDisplay,
-		    iWindow,
-		    PropertyChangeMask) == BadWindow)
-    ErrorF ("winClipboardProc - XSelectInput generated BadWindow "
-	    "on messaging window\n");
-
-  /* Save the window in the screen privates */
-  g_iClipboardWindow = iWindow;
-
-  /* Create Windows messaging window */
-  hwnd = winClipboardCreateMessagingWindow ();
-  
-  /* Save copy of HWND in screen privates */
-  g_hwndClipboard = hwnd;
-
-  /* Assert ownership of selections if Win32 clipboard is owned */
-  if (NULL != GetClipboardOwner ())
-    {
-      /* PRIMARY */
-      iReturn = XSetSelectionOwner (pDisplay, XA_PRIMARY,
-				    iWindow, CurrentTime);
-      if (iReturn == BadAtom || iReturn == BadWindow ||
-	  XGetSelectionOwner (pDisplay, XA_PRIMARY) != iWindow)
-	{
-	  ErrorF ("winClipboardProc - Could not set PRIMARY owner\n");
-	  pthread_exit (NULL);
-	}
-
-      /* CLIPBOARD */
-      iReturn = XSetSelectionOwner (pDisplay, atomClipboard,
-				    iWindow, CurrentTime);
-      if (iReturn == BadAtom || iReturn == BadWindow ||
-	  XGetSelectionOwner (pDisplay, atomClipboard) != iWindow)
-	{
-	  ErrorF ("winClipboardProc - Could not set CLIPBOARD owner\n");
-	  pthread_exit (NULL);
-	}
-    }
-
-  /* Pre-flush X events */
-  /* 
-   * NOTE: Apparently you'll freeze if you don't do this,
-   *	   because there may be events in local data structures
-   *	   already.
-   */
-  winClipboardFlushXEvents (hwnd,
-			    iWindow,
-			    pDisplay,
-			    fUseUnicode);
-
-  /* Pre-flush Windows messages */
-  if (!winClipboardFlushWindowsMessageQueue (hwnd))
-    return 0;
-
-  /* Signal that the clipboard client has started */
-  g_fClipboardStarted = TRUE;
-
-  /* Loop for X events */
-  while (1)
-    {
-      /* Setup the file descriptor set */
-      /*
-       * NOTE: You have to do this before every call to select
-       *       because select modifies the mask to indicate
-       *       which descriptors are ready.
-       */
-      FD_ZERO (&fdsRead);
-      FD_SET (iConnectionNumber, &fdsRead);
-#ifdef HAS_DEVWINDOWS
-      FD_SET (fdMessageQueue, &fdsRead);
-#else
-      tvTimeout.tv_sec = 0;
-      tvTimeout.tv_usec = 100;
-#endif
-
-      /* Wait for a Windows event or an X event */
-      iReturn = select (iMaxDescriptor,	/* Highest fds number */
-			&fdsRead,	/* Read mask */
-			NULL,		/* No write mask */
-			NULL,		/* No exception mask */
-#ifdef HAS_DEVWINDOWS
-			NULL		/* No timeout */
-#else
-			&tvTimeout      /* Set timeout */
-#endif
-          );
-
-#ifndef HAS_WINSOCK
-      iSelectError = errno;
-#else
-      iSelectError = WSAGetLastError();
-#endif
-
-      if (iReturn < 0)
-	{
-#ifndef HAS_WINSOCK
-          if (iSelectError == EINTR)
-#else
-          if (iSelectError == WSAEINTR)
-#endif
-            continue;
-          
-	  ErrorF ("winClipboardProc - Call to select () failed: %d.  "
-		  "Bailing.\n", iReturn);
-	  break;
-	}
-
-      /* Branch on which descriptor became active */
-      if (FD_ISSET (iConnectionNumber, &fdsRead))
-	{
-	  /* Process X events */
-	  /* Exit when we see that server is shutting down */
-	  iReturn = winClipboardFlushXEvents (hwnd,
-					      iWindow,
-					      pDisplay,
-					      fUseUnicode);
-	  if (WIN_XEVENTS_SHUTDOWN == iReturn)
-	    {
-	      ErrorF ("winClipboardProc - winClipboardFlushXEvents "
-		      "trapped shutdown event, exiting main loop.\n");
-	      break;
-	    }
-	}
-
-#ifdef HAS_DEVWINDOWS
-      /* Check for Windows event ready */
-      if (FD_ISSET (fdMessageQueue, &fdsRead))
-#else
-      if (1)
-#endif
-	{
-	  /* Process Windows messages */
-	  if (!winClipboardFlushWindowsMessageQueue (hwnd))
-	    {
-	      ErrorF ("winClipboardProc - "
-		      "winClipboardFlushWindowsMessageQueue trapped "
-		      "WM_QUIT message, exiting main loop.\n");
-	      break;
-	    }
-	}
-    }
-
-  /* Close our X window */
-  if (pDisplay && iWindow)
-    {
-      iReturn = XDestroyWindow (pDisplay, iWindow);
-      if (iReturn == BadWindow)
-	ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n");
-      else
-	ErrorF ("winClipboardProc - XDestroyWindow succeeded.\n");
-    }
-
-
-#ifdef HAS_DEVWINDOWS
-  /* Close our Win32 message handle */
-  if (fdMessageQueue)
-    close (fdMessageQueue);
-#endif
-
-#if 0
-  /*
-   * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26.  The
-   * XSync and XSelectInput calls did not help.
-   */
-
-  /* Discard any remaining events */
-  XSync (pDisplay, TRUE);
-
-  /* Select event types to watch */
-  XSelectInput (pDisplay,
-		DefaultRootWindow (pDisplay),
-		None);
-
-  /* Close our X display */
-  if (pDisplay)
-    {
-      XCloseDisplay (pDisplay);
-    }
-#endif
-
-  g_iClipboardWindow = None;
-  g_pClipboardDisplay = NULL;
-  g_hwndClipboard = NULL;
-
-  return NULL;
-}
-
-
-/*
- * winClipboardErrorHandler - Our application specific error handler
- */
-
-static int
-winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr)
-{
-  char pszErrorMsg[100];
-  
-  XGetErrorText (pDisplay,
-		 pErr->error_code,
-		 pszErrorMsg,
-		 sizeof (pszErrorMsg));
-  ErrorF ("winClipboardErrorHandler - ERROR: \n\t%s\n"
-	  "\tSerial: %d, Request Code: %d, Minor Code: %d\n",
-	  pszErrorMsg,
-	  pErr->serial,
-	  pErr->request_code,
-	  pErr->minor_code);
-  return 0;
-}
-
-
-/*
- * winClipboardIOErrorHandler - Our application specific IO error handler
- */
-
-static int
-winClipboardIOErrorHandler (Display *pDisplay)
-{
-  ErrorF ("\nwinClipboardIOErrorHandler!\n\n");
-
-  /* Restart at the main entry point */
-  longjmp (g_jmpEntry, WIN_JMP_ERROR_IO);
-  
-  return 0;
-}
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *Copyright (C) Colin Harrison 2005-2008
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the copyright holder(s)
+ *and author(s) shall not be used in advertising or otherwise to promote
+ *the sale, use or other dealings in this Software without prior written
+ *authorization from the copyright holder(s) and author(s).
+ *
+ * Authors:	Harold L Hunt II
+ *              Colin Harrison
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <sys/types.h>
+#include "winclipboard.h"
+#ifdef __CYGWIN__
+#include <errno.h>
+#endif
+#include "misc.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUnicodeClipboard;
+extern unsigned long	serverGeneration;
+extern Bool		g_fClipboardStarted;
+extern HWND		g_hwndClipboard;
+extern void		*g_pClipboardDisplay;
+extern Window		g_iClipboardWindow;
+
+
+/*
+ * Global variables
+ */
+
+static jmp_buf			g_jmpEntry;
+Bool				g_fUnicodeSupport = FALSE;
+Bool				g_fUseUnicode = FALSE;
+
+
+/*
+ * Local function prototypes
+ */
+
+static int
+winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static int
+winClipboardIOErrorHandler (Display *pDisplay);
+
+
+/*
+ * Main thread function
+ */
+
+void *
+winClipboardProc (void *pvNotUsed)
+{
+  Atom			atomClipboard, atomClipboardManager;
+  int			iReturn;
+  HWND			hwnd = NULL;
+  int			iConnectionNumber = 0;
+#ifdef HAS_DEVWINDOWS
+  int			fdMessageQueue = 0;
+#else
+  struct timeval        tvTimeout;
+#endif
+  fd_set		fdsRead;
+  int			iMaxDescriptor;
+  Display		*pDisplay = NULL;
+  Window		iWindow = None;
+  int			iRetries;
+  Bool			fUseUnicode;
+  char			szDisplay[512];
+  int			iSelectError;
+
+  ErrorF ("winClipboardProc - Hello\n");
+
+  /* Do we have Unicode support? */
+  g_fUnicodeSupport = winClipboardDetectUnicodeSupport ();
+
+  /* Do we use Unicode clipboard? */
+  fUseUnicode = g_fUnicodeClipboard && g_fUnicodeSupport;
+
+  /* Save the Unicode support flag in a global */
+  g_fUseUnicode = fUseUnicode;
+
+  /* Allow multiple threads to access Xlib */
+  if (XInitThreads () == 0)
+    {
+      ErrorF ("winClipboardProc - XInitThreads failed.\n");
+      pthread_exit (NULL);
+    }
+
+  /* See if X supports the current locale */
+  if (XSupportsLocale () == False)
+    {
+      ErrorF ("winClipboardProc - Warning: Locale not supported by X.\n");
+    }
+
+  /* Set jump point for Error exits */
+  iReturn = setjmp (g_jmpEntry);
+  
+  /* Check if we should continue operations */
+  if (iReturn != WIN_JMP_ERROR_IO
+      && iReturn != WIN_JMP_OKAY)
+    {
+      /* setjmp returned an unknown value, exit */
+      ErrorF ("winClipboardProc - setjmp returned: %d exiting\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+  else if (iReturn == WIN_JMP_ERROR_IO)
+    {
+      /* TODO: Cleanup the Win32 window and free any allocated memory */
+      ErrorF ("winClipboardProc - setjmp returned for IO Error Handler.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Use our generated cookie for authentication */
+  winSetAuthorization();
+
+  /* Set error handler */
+  XSetErrorHandler (winClipboardErrorHandler);
+  XSetIOErrorHandler (winClipboardIOErrorHandler);
+
+  /* Initialize retry count */
+  iRetries = 0;
+
+  /* Setup the display connection string x */
+  /*
+   * NOTE: Always connect to screen 0 since we require that screen
+   * numbers start at 0 and increase without gaps.  We only need
+   * to connect to one screen on the display to get events
+   * for all screens on the display.  That is why there is only
+   * one clipboard client thread.
+   */
+  snprintf (szDisplay,
+	    512,
+	    "127.0.0.1:%s.0",
+	    display);
+
+  /* Print the display connection string */
+  ErrorF ("winClipboardProc - DISPLAY=%s\n", szDisplay);
+
+  /* Open the X display */
+  do
+    {
+      pDisplay = XOpenDisplay (szDisplay);
+      if (pDisplay == NULL)
+	{
+	  ErrorF ("winClipboardProc - Could not open display, "
+		  "try: %d, sleeping: %d\n",
+		  iRetries + 1, WIN_CONNECT_DELAY);
+	  ++iRetries;
+	  sleep (WIN_CONNECT_DELAY);
+	  continue;
+	}
+      else
+	break;
+    }
+  while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
+
+  /* Make sure that the display opened */
+  if (pDisplay == NULL)
+    {
+      ErrorF ("winClipboardProc - Failed opening the display, giving up\n");
+      pthread_exit (NULL);
+    }
+
+  /* Save the display in the screen privates */
+  g_pClipboardDisplay = pDisplay;
+
+  ErrorF ("winClipboardProc - XOpenDisplay () returned and "
+	  "successfully opened the display.\n");
+
+  /* Get our connection number */
+  iConnectionNumber = ConnectionNumber (pDisplay);
+
+#ifdef HAS_DEVWINDOWS
+  /* Open a file descriptor for the windows message queue */
+  fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, O_RDONLY);
+  if (fdMessageQueue == -1)
+    {
+      ErrorF ("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME);
+      pthread_exit (NULL);
+    }
+
+  /* Find max of our file descriptors */
+  iMaxDescriptor = max (fdMessageQueue, iConnectionNumber) + 1;
+#else
+  iMaxDescriptor = iConnectionNumber + 1;
+#endif
+
+  /* Create atoms */
+  atomClipboard = XInternAtom (pDisplay, "CLIPBOARD", False);
+  atomClipboardManager = XInternAtom (pDisplay, "CLIPBOARD_MANAGER", False);
+
+  /* Create a messaging window */
+  iWindow = XCreateSimpleWindow (pDisplay,
+				 DefaultRootWindow (pDisplay),
+				 1, 1,
+				 500, 500,
+				 0,
+				 BlackPixel (pDisplay, 0),
+				 BlackPixel (pDisplay, 0));
+  if (iWindow == 0)
+    {
+      ErrorF ("winClipboardProc - Could not create an X window.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Select event types to watch */
+  if (XSelectInput (pDisplay,
+		    iWindow,
+		    PropertyChangeMask) == BadWindow)
+    ErrorF ("winClipboardProc - XSelectInput generated BadWindow "
+	    "on messaging window\n");
+
+  /* Save the window in the screen privates */
+  g_iClipboardWindow = iWindow;
+
+  /* Create Windows messaging window */
+  hwnd = winClipboardCreateMessagingWindow ();
+  
+  /* Save copy of HWND in screen privates */
+  g_hwndClipboard = hwnd;
+
+  /* Assert ownership of selections if Win32 clipboard is owned */
+  if (NULL != GetClipboardOwner ())
+    {
+      /* PRIMARY */
+      iReturn = XSetSelectionOwner (pDisplay, XA_PRIMARY,
+				    iWindow, CurrentTime);
+      if (iReturn == BadAtom || iReturn == BadWindow ||
+	  XGetSelectionOwner (pDisplay, XA_PRIMARY) != iWindow)
+	{
+	  ErrorF ("winClipboardProc - Could not set PRIMARY owner\n");
+	  pthread_exit (NULL);
+	}
+
+      /* CLIPBOARD */
+      iReturn = XSetSelectionOwner (pDisplay, atomClipboard,
+				    iWindow, CurrentTime);
+      if (iReturn == BadAtom || iReturn == BadWindow ||
+	  XGetSelectionOwner (pDisplay, atomClipboard) != iWindow)
+	{
+	  ErrorF ("winClipboardProc - Could not set CLIPBOARD owner\n");
+	  pthread_exit (NULL);
+	}
+    }
+
+  /* Pre-flush X events */
+  /* 
+   * NOTE: Apparently you'll freeze if you don't do this,
+   *	   because there may be events in local data structures
+   *	   already.
+   */
+  winClipboardFlushXEvents (hwnd,
+			    iWindow,
+			    pDisplay,
+			    fUseUnicode);
+
+  /* Pre-flush Windows messages */
+  if (!winClipboardFlushWindowsMessageQueue (hwnd))
+    return 0;
+
+  /* Signal that the clipboard client has started */
+  g_fClipboardStarted = TRUE;
+
+  /* Loop for X events */
+  while (1)
+    {
+      /* Setup the file descriptor set */
+      /*
+       * NOTE: You have to do this before every call to select
+       *       because select modifies the mask to indicate
+       *       which descriptors are ready.
+       */
+      FD_ZERO (&fdsRead);
+      FD_SET (iConnectionNumber, &fdsRead);
+#ifdef HAS_DEVWINDOWS
+      FD_SET (fdMessageQueue, &fdsRead);
+#else
+      tvTimeout.tv_sec = 0;
+      tvTimeout.tv_usec = 100;
+#endif
+
+      /* Wait for a Windows event or an X event */
+      iReturn = select (iMaxDescriptor,	/* Highest fds number */
+			&fdsRead,	/* Read mask */
+			NULL,		/* No write mask */
+			NULL,		/* No exception mask */
+#ifdef HAS_DEVWINDOWS
+			NULL		/* No timeout */
+#else
+			&tvTimeout      /* Set timeout */
+#endif
+          );
+
+#ifndef HAS_WINSOCK
+      iSelectError = errno;
+#else
+      iSelectError = WSAGetLastError();
+#endif
+
+      if (iReturn < 0)
+	{
+#ifndef HAS_WINSOCK
+          if (iSelectError == EINTR)
+#else
+          if (iSelectError == WSAEINTR)
+#endif
+            continue;
+          
+	  ErrorF ("winClipboardProc - Call to select () failed: %d.  "
+		  "Bailing.\n", iReturn);
+	  break;
+	}
+
+      /* Branch on which descriptor became active */
+      if (FD_ISSET (iConnectionNumber, &fdsRead))
+	{
+	  /* Process X events */
+	  /* Exit when we see that server is shutting down */
+	  iReturn = winClipboardFlushXEvents (hwnd,
+					      iWindow,
+					      pDisplay,
+					      fUseUnicode);
+	  if (WIN_XEVENTS_SHUTDOWN == iReturn)
+	    {
+	      ErrorF ("winClipboardProc - winClipboardFlushXEvents "
+		      "trapped shutdown event, exiting main loop.\n");
+	      break;
+	    }
+	}
+
+#ifdef HAS_DEVWINDOWS
+      /* Check for Windows event ready */
+      if (FD_ISSET (fdMessageQueue, &fdsRead))
+#else
+      if (1)
+#endif
+	{
+	  /* Process Windows messages */
+	  if (!winClipboardFlushWindowsMessageQueue (hwnd))
+	    {
+	      ErrorF ("winClipboardProc - "
+		      "winClipboardFlushWindowsMessageQueue trapped "
+		      "WM_QUIT message, exiting main loop.\n");
+	      break;
+	    }
+	}
+    }
+
+  /* Close our X window */
+  if (pDisplay && iWindow)
+    {
+      iReturn = XDestroyWindow (pDisplay, iWindow);
+      if (iReturn == BadWindow)
+	ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n");
+      else
+	ErrorF ("winClipboardProc - XDestroyWindow succeeded.\n");
+    }
+
+
+#ifdef HAS_DEVWINDOWS
+  /* Close our Win32 message handle */
+  if (fdMessageQueue)
+    close (fdMessageQueue);
+#endif
+
+#if 0
+  /*
+   * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26.  The
+   * XSync and XSelectInput calls did not help.
+   */
+
+  /* Discard any remaining events */
+  XSync (pDisplay, TRUE);
+
+  /* Select event types to watch */
+  XSelectInput (pDisplay,
+		DefaultRootWindow (pDisplay),
+		None);
+
+  /* Close our X display */
+  if (pDisplay)
+    {
+      XCloseDisplay (pDisplay);
+    }
+#endif
+
+  g_iClipboardWindow = None;
+  g_pClipboardDisplay = NULL;
+  g_hwndClipboard = NULL;
+
+  return NULL;
+}
+
+
+/*
+ * winClipboardErrorHandler - Our application specific error handler
+ */
+
+static int
+winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+  char pszErrorMsg[100];
+  
+  XGetErrorText (pDisplay,
+		 pErr->error_code,
+		 pszErrorMsg,
+		 sizeof (pszErrorMsg));
+  ErrorF ("winClipboardErrorHandler - ERROR: \n\t%s\n"
+	  "\tSerial: %d, Request Code: %d, Minor Code: %d\n",
+	  pszErrorMsg,
+	  pErr->serial,
+	  pErr->request_code,
+	  pErr->minor_code);
+  return 0;
+}
+
+
+/*
+ * winClipboardIOErrorHandler - Our application specific IO error handler
+ */
+
+static int
+winClipboardIOErrorHandler (Display *pDisplay)
+{
+  ErrorF ("winClipboardIOErrorHandler!\n\n");
+
+  /* Restart at the main entry point */
+  longjmp (g_jmpEntry, WIN_JMP_ERROR_IO);
+  
+  return 0;
+}
diff --git a/xorg-server/hw/xwin/winconfig.c b/xorg-server/hw/xwin/winconfig.c
index 259b3d238..0f9126d77 100644
--- a/xorg-server/hw/xwin/winconfig.c
+++ b/xorg-server/hw/xwin/winconfig.c
@@ -1,1064 +1,1064 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors: Alexander Gottwald	
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winconfig.h"
-#include "winmsg.h"
-#include "globals.h"
-
-#include "xkbsrv.h"
-
-#ifdef XWIN_XF86CONFIG
-#ifndef CONFIGPATH
-#define CONFIGPATH  "%A," "%R," \
-                    "/etc/X11/%R," "%P/etc/X11/%R," \
-                    "%E," "%F," \
-                    "/etc/X11/%F," "%P/etc/X11/%F," \
-                    "/etc/X11/%X-%M," "/etc/X11/%X," "/etc/%X," \
-                    "%P/etc/X11/%X.%H," "%P/etc/X11/%X-%M," \
-                    "%P/etc/X11/%X," \
-                    "%P/lib/X11/%X.%H," "%P/lib/X11/%X-%M," \
-                    "%P/lib/X11/%X"
-#endif
-#ifndef CONFIGDIRPATH
-#define CONFIGDIRPATH  "/etc/X11/%X-%M," "/etc/X11/%X," "/etc/%X," \
-                       "%P/etc/X11/%X.%H," "%P/etc/X11/%X-%M," \
-                       "%P/etc/X11/%X," \
-                       "%P/lib/X11/%X.%H," "%P/lib/X11/%X-%M," \
-                       "%P/lib/X11/%X"
-#endif
-
-XF86ConfigPtr g_xf86configptr = NULL;
-#endif
-
-WinCmdlineRec g_cmdline = {
-#ifdef XWIN_XF86CONFIG
-  NULL,				/* configFile */
-  NULL,				/* configDir */
-#endif
-  NULL,				/* fontPath */
-#ifdef XWIN_XF86CONFIG
-  NULL,				/* keyboard */
-#endif
-  NULL,             /* xkbRules */
-  NULL,             /* xkbModel */
-  NULL,             /* xkbLayout */
-  NULL,             /* xkbVariant */
-  NULL,             /* xkbOptions */
-  NULL,				/* screenname */
-  NULL,				/* mousename */
-  FALSE,			/* emulate3Buttons */
-  0				/* emulate3Timeout */
-};
-
-winInfoRec g_winInfo = {
-  {				/* keyboard */
-   0,				/* leds */
-   500,				/* delay */
-   30				/* rate */
-   }
-  ,
-  {				/* xkb */
-   NULL,			/* rules */
-   NULL,			/* model */
-   NULL,			/* layout */
-   NULL,			/* variant */
-   NULL,			/* options */
-   }
-  ,
-  {
-   FALSE,
-   50}
-};
-
-#define NULL_IF_EMPTY(x) (winNameCompare(x,"")?x:NULL)
-
-#ifdef XWIN_XF86CONFIG
-serverLayoutRec g_winConfigLayout;
-
-static Bool ParseOptionValue (int scrnIndex, pointer options,
-			      OptionInfoPtr p);
-static Bool configLayout (serverLayoutPtr, XF86ConfLayoutPtr, char *);
-static Bool configImpliedLayout (serverLayoutPtr, XF86ConfScreenPtr);
-static Bool GetBoolValue (OptionInfoPtr p, const char *s);
-
-
-Bool
-winReadConfigfile ()
-{
-  Bool		retval = TRUE;
-  const char	*filename, *dirname;
-  MessageType	filefrom = X_DEFAULT;
-  MessageType	dirfrom = X_DEFAULT;
-  char		*xf86ConfigFile = NULL;
-  char		*xf86ConfigDir = NULL;
-
-  if (g_cmdline.configFile)
-    {
-      filefrom = X_CMDLINE;
-      xf86ConfigFile = g_cmdline.configFile;
-    }
-  if (g_cmdline.configDir)
-    {
-      dirfrom = X_CMDLINE;
-      xf86ConfigDir = g_cmdline.configDir;
-    }
-
-  /* Parse config file into data structure */
-  xf86initConfigFiles();
-  dirname = xf86openConfigDirFiles (CONFIGDIRPATH, xf86ConfigDir, PROJECTROOT);
-  filename = xf86openConfigFile (CONFIGPATH, xf86ConfigFile, PROJECTROOT);
-
-  /* Hack for backward compatibility */
-  if (!filename && from == X_DEFAULT)
-    filename = xf86openConfigFile (CONFIGPATH, "XF86Config", PROJECTROOT);
-
-  if (filename)
-    {
-      winMsg (from, "Using config file: \"%s\"\n", filename);
-    }
-  else
-    {
-      winMsg (X_ERROR, "Unable to locate/open config file");
-      if (xf86ConfigFile)
-	ErrorF (": \"%s\"", xf86ConfigFile);
-      ErrorF ("\n");
-    }
-  if (dirname)
-    {
-      winMsg (from, "Using config directory: \"%s\"\n", dirname);
-    }
-  else
-    {
-      winMsg (X_ERROR, "Unable to locate/open config directory");
-      if (xf86ConfigDir)
-	ErrorF (": \"%s\"", xf86ConfigDir);
-      ErrorF ("\n");
-    }
-  if (!filename && !dirname)
-    {
-      return FALSE;
-    }
-  if ((g_xf86configptr = xf86readConfigFile ()) == NULL)
-    {
-      winMsg (X_ERROR, "Problem parsing the config file\n");
-      return FALSE;
-    }
-  xf86closeConfigFile ();
-
-  LogPrintMarkers();
-
-  /* set options from data structure */
-
-  if (g_xf86configptr->conf_layout_lst == NULL || g_cmdline.screenname != NULL)
-    {
-      if (g_cmdline.screenname == NULL)
-	{
-	  winMsg (X_WARNING,
-		  "No Layout section. Using the first Screen section.\n");
-	}
-      if (!configImpliedLayout (&g_winConfigLayout,
-				g_xf86configptr->conf_screen_lst))
-	{
-	  winMsg (X_ERROR, "Unable to determine the screen layout\n");
-	  return FALSE;
-	}
-    }
-  else
-    {
-      /* Check if layout is given in the config file */
-      if (g_xf86configptr->conf_flags != NULL)
-	{
-	  char *dfltlayout = NULL;
-	  pointer optlist = g_xf86configptr->conf_flags->flg_option_lst;
-
-	  if (optlist && winFindOption (optlist, "defaultserverlayout"))
-	    dfltlayout =
-	      winSetStrOption (optlist, "defaultserverlayout", NULL);
-
-	  if (!configLayout (&g_winConfigLayout,
-			     g_xf86configptr->conf_layout_lst,
-			     dfltlayout))
-	    {
-	      winMsg (X_ERROR, "Unable to determine the screen layout\n");
-	      return FALSE;
-	    }
-	}
-      else
-	{
-	  if (!configLayout (&g_winConfigLayout,
-			     g_xf86configptr->conf_layout_lst,
-			     NULL))
-	    {
-	      winMsg (X_ERROR, "Unable to determine the screen layout\n");
-	      return FALSE;
-	    }
-	}
-    }
-
-  /* setup special config files */
-  winConfigFiles ();
-  return retval;
-}
-#endif
-
-/* load layout definitions */
-#include "winlayouts.h"
-
-/* Set the keyboard configuration */
-Bool
-winConfigKeyboard (DeviceIntPtr pDevice)
-{
-  char                          layoutName[KL_NAMELENGTH];
-  static unsigned int           layoutNum = 0;
-  int                           keyboardType;
-#ifdef XWIN_XF86CONFIG
-  XF86ConfInputPtr		kbd = NULL;
-  XF86ConfInputPtr		input_list = NULL;
-  MessageType			kbdfrom = X_CONFIG;
-#endif
-  MessageType			from = X_DEFAULT;
-  char				*s = NULL;
-
-  /* Setup defaults */
-  XkbGetRulesDflts(&g_winInfo.xkb);
-
-  /*
-   * Query the windows autorepeat settings and change the xserver defaults.   
-   */
-  {
-    int kbd_delay;
-    DWORD kbd_speed;
-    if (SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &kbd_delay, 0) &&
-        SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &kbd_speed, 0))
-      {
-        switch (kbd_delay) 
-          {
-            case 0:  g_winInfo.keyboard.delay = 250; break;
-            case 1:  g_winInfo.keyboard.delay = 500; break;
-            case 2:  g_winInfo.keyboard.delay = 750; break;
-            default:
-            case 3:  g_winInfo.keyboard.delay = 1000; break;
-          }
-        g_winInfo.keyboard.rate = (kbd_speed>0)?kbd_speed:1;
-        winMsgVerb(X_PROBED, 1, "Setting autorepeat to delay=%d, rate=%d\n",
-                g_winInfo.keyboard.delay, g_winInfo.keyboard.rate);
-      }
-  }
-  
-
-  keyboardType = GetKeyboardType (0);
-  if (keyboardType > 0 && GetKeyboardLayoutName (layoutName)) 
-  {
-    WinKBLayoutPtr	pLayout;
-    Bool                bfound = FALSE;
-
-    if (! layoutNum)
-      layoutNum = strtoul (layoutName, (char **)NULL, 16);
-    if ((layoutNum & 0xffff) == 0x411) {
-        /* The japanese layouts know a lot of different IMEs which all have
-	   different layout numbers set. Map them to a single entry. 
-	   Same might apply for chinese, korean and other symbol languages
-	   too */
-        layoutNum = (layoutNum & 0xffff);
-	if (keyboardType == 7)
-	  {
-	    /* Japanese layouts have problems with key event messages
-	       such as the lack of WM_KEYUP for Caps Lock key.
-	       Loading US layout fixes this problem. */
-	    if (LoadKeyboardLayout("00000409", KLF_ACTIVATE) != NULL)
-	      winMsg (X_INFO, "Loading US keyboard layout.\n");
-	    else
-	      winMsg (X_ERROR, "LoadKeyboardLaout failed.\n");
-	  }
-    }
-    winMsg (X_PROBED, "winConfigKeyboard - Layout: \"%s\" (%08x) \n", 
-            layoutName, layoutNum);
-
-    for (pLayout = winKBLayouts; pLayout->winlayout != -1; pLayout++)
-      {
-	if (pLayout->winlayout != layoutNum)
-	  continue;
-	if (pLayout->winkbtype > 0 && pLayout->winkbtype != keyboardType)
-	  continue;
-	
-        bfound = TRUE;
-	winMsg (X_PROBED,
-		"Using preset keyboard for \"%s\" (%x), type \"%d\"\n",
-		pLayout->layoutname, pLayout->winlayout, keyboardType);
-	
-	g_winInfo.xkb.model = pLayout->xkbmodel;
-	g_winInfo.xkb.layout = pLayout->xkblayout;
-	g_winInfo.xkb.variant = pLayout->xkbvariant;
-	g_winInfo.xkb.options = pLayout->xkboptions; 
-	break;
-      }
-    
-    if (!bfound)
-      {
-        HKEY                regkey = NULL;
-        const char          regtempl[] = 
-          "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\";
-        char                *regpath;
-        char                lname[256];
-        DWORD               namesize = sizeof(lname);
-
-        regpath = malloc(sizeof(regtempl) + KL_NAMELENGTH + 1);
-        strcpy(regpath, regtempl);
-        strcat(regpath, layoutName);
-
-        if (!RegOpenKey(HKEY_LOCAL_MACHINE, regpath, &regkey) &&
-          !RegQueryValueEx(regkey, "Layout Text", 0, NULL, lname, &namesize))
-          {
-	    winMsg (X_ERROR,
-		"Keyboardlayout \"%s\" (%s) is unknown\n", lname, layoutName);
-          }
-
-	/* Close registry key */
-	if (regkey)
-	  RegCloseKey (regkey);
-        free(regpath);
-      }
-  }  
-  
-  /* parse the configuration */
-#ifdef XWIN_XF86CONFIG
-  if (g_cmdline.keyboard)
-    kbdfrom = X_CMDLINE;
-
-  /*
-   * Until the layout code is finished, I search for the keyboard 
-   * device and configure the server with it.
-   */
-
-  if (g_xf86configptr != NULL)
-    input_list = g_xf86configptr->conf_input_lst;
-
-  while (input_list != NULL)
-    {
-      if (winNameCompare (input_list->inp_driver, "keyboard") == 0)
-	{
-	  /* Check if device name matches requested name */
-	  if (g_cmdline.keyboard && winNameCompare (input_list->inp_identifier,
-						    g_cmdline.keyboard))
-	    continue;
-	  kbd = input_list;
-	}
-      input_list = input_list->list.next;
-    }
-
-  if (kbd != NULL)
-    {
-
-      if (kbd->inp_identifier)
-	winMsg (kbdfrom, "Using keyboard \"%s\" as primary keyboard\n",
-		kbd->inp_identifier);
-
-      if ((s = winSetStrOption(kbd->inp_option_lst, "AutoRepeat", NULL)))
-        {
-          if ((sscanf(s, "%ld %ld", &g_winInfo.keyboard.delay, 
-                      &g_winInfo.keyboard.rate) != 2) ||
-                  (g_winInfo.keyboard.delay < 1) || 
-                  (g_winInfo.keyboard.rate == 0) || 
-                  (1000 / g_winInfo.keyboard.rate) < 1) 
-            {
-              winErrorFVerb (2, "\"%s\" is not a valid AutoRepeat value", s);
-              xfree(s);
-              return FALSE;
-            }
-          xfree(s);
-          winMsg (X_CONFIG, "AutoRepeat: %ld %ld\n", 
-                  g_winInfo.keyboard.delay, g_winInfo.keyboard.rate);
-        }
-#endif
-      
-        s = NULL;
-        if (g_cmdline.xkbRules)
-          {
-            s = g_cmdline.xkbRules;
-            from = X_CMDLINE;
-          }
-#ifdef XWIN_XF86CONFIG
-        else
-          {
-            s = winSetStrOption (kbd->inp_option_lst, "XkbRules", NULL);
-            from = X_CONFIG;
-          }
-#endif
-        if (s)
-          {
-            g_winInfo.xkb.rules = NULL_IF_EMPTY (s);
-            winMsg (from, "XKB: rules: \"%s\"\n", s);
-	  }
-          
-        s = NULL;
-        if (g_cmdline.xkbModel)
-          {
-            s = g_cmdline.xkbModel;
-            from = X_CMDLINE;
-          }
-#ifdef XWIN_XF86CONFIG
-        else
-          {
-            s = winSetStrOption (kbd->inp_option_lst, "XkbModel", NULL);
-            from = X_CONFIG;
-          }
-#endif
-        if (s)
-	  {
-	    g_winInfo.xkb.model = NULL_IF_EMPTY (s);
-	    winMsg (from, "XKB: model: \"%s\"\n", s);
-	  }
-
-        s = NULL;
-        if (g_cmdline.xkbLayout)
-          {
-            s = g_cmdline.xkbLayout;
-            from = X_CMDLINE;
-          }
-#ifdef XWIN_XF86CONFIG
-        else
-          {
-            s = winSetStrOption (kbd->inp_option_lst, "XkbLayout", NULL);
-            from = X_CONFIG;
-          }
-#endif
-        if (s)
-          {
-	    g_winInfo.xkb.layout = NULL_IF_EMPTY (s);
-	    winMsg (from, "XKB: layout: \"%s\"\n", s);
-	  }
-
-        s = NULL;
-        if (g_cmdline.xkbVariant)
-          {
-            s = g_cmdline.xkbVariant;
-            from = X_CMDLINE;
-          }
-#ifdef XWIN_XF86CONFIG
-        else
-          {
-            s = winSetStrOption (kbd->inp_option_lst, "XkbVariant", NULL);
-            from = X_CONFIG;
-          }
-#endif
-	if (s)
-	  {
-	    g_winInfo.xkb.variant = NULL_IF_EMPTY (s);
-	    winMsg (from, "XKB: variant: \"%s\"\n", s);
-	  }
-
-        s = NULL;
-        if (g_cmdline.xkbOptions)
-          {
-            s = g_cmdline.xkbOptions;
-            from = X_CMDLINE;
-          }
-#ifdef XWIN_XF86CONFIG
-        else
-          {
-            s = winSetStrOption (kbd->inp_option_lst, "XkbOptions", NULL);
-            from = X_CONFIG;
-          }
-#endif
-        if (s)
-	  {
-	    g_winInfo.xkb.options = NULL_IF_EMPTY (s);
-	    winMsg (from, "XKB: options: \"%s\"\n", s);
-	  }
-
-#ifdef XWIN_XF86CONFIG
-    }
-#endif
-
-  return TRUE;
-}
-
-
-#ifdef XWIN_XF86CONFIG
-Bool
-winConfigMouse (DeviceIntPtr pDevice)
-{
-  MessageType			mousefrom = X_CONFIG;
-
-  XF86ConfInputPtr		mouse = NULL;
-  XF86ConfInputPtr		input_list = NULL;
-
-  if (g_cmdline.mouse)
-    mousefrom = X_CMDLINE;
-
-  if (g_xf86configptr != NULL)
-    input_list = g_xf86configptr->conf_input_lst;
-
-  while (input_list != NULL)
-    {
-      if (winNameCompare (input_list->inp_driver, "mouse") == 0)
-	{
-	  /* Check if device name matches requested name */
-	  if (g_cmdline.mouse && winNameCompare (input_list->inp_identifier,
-						 g_cmdline.mouse))
-	    continue;
-	  mouse = input_list;
-	}
-      input_list = input_list->list.next;
-    }
-
-  if (mouse != NULL)
-    {
-      if (mouse->inp_identifier)
-	winMsg (mousefrom, "Using pointer \"%s\" as primary pointer\n",
-		mouse->inp_identifier);
-
-      g_winInfo.pointer.emulate3Buttons =
-	winSetBoolOption (mouse->inp_option_lst, "Emulate3Buttons", FALSE);
-      if (g_cmdline.emulate3buttons)
-	g_winInfo.pointer.emulate3Buttons = g_cmdline.emulate3buttons;
-
-      g_winInfo.pointer.emulate3Timeout =
-	winSetIntOption (mouse->inp_option_lst, "Emulate3Timeout", 50);
-      if (g_cmdline.emulate3timeout)
-	g_winInfo.pointer.emulate3Timeout = g_cmdline.emulate3timeout;
-    }
-  else
-    {
-      winMsg (X_ERROR, "No primary pointer configured\n");
-      winMsg (X_DEFAULT, "Using compiletime defaults for pointer\n");
-    }
-
-  return TRUE;
-}
-
-
-Bool
-winConfigFiles ()
-{
-  MessageType from;
-  XF86ConfFilesPtr filesptr = NULL;
-
-  /* set some shortcuts */
-  if (g_xf86configptr != NULL)
-    {
-      filesptr = g_xf86configptr->conf_files;
-    }
-
-
-  /* Fontpath */
-  from = X_DEFAULT;
-
-  if (g_cmdline.fontPath)
-    {
-      from = X_CMDLINE;
-      defaultFontPath = g_cmdline.fontPath;
-    }
-  else if (filesptr != NULL && filesptr->file_fontpath)
-    {
-      from = X_CONFIG;
-      defaultFontPath = xstrdup (filesptr->file_fontpath);
-    }
-  winMsg (from, "FontPath set to \"%s\"\n", defaultFontPath);
-
-  return TRUE;
-}
-#else
-Bool
-winConfigFiles (void)
-{
-  /* Fontpath */
-  if (g_cmdline.fontPath)
-    {
-      defaultFontPath = g_cmdline.fontPath;
-      winMsg (X_CMDLINE, "FontPath set to \"%s\"\n", defaultFontPath);
-    }
-
-  return TRUE;
-}
-#endif
-
-
-Bool
-winConfigOptions (void)
-{
-  return TRUE;
-}
-
-
-Bool
-winConfigScreens (void)
-{
-  return TRUE;
-}
-
-
-#ifdef XWIN_XF86CONFIG
-char *
-winSetStrOption (pointer optlist, const char *name, char *deflt)
-{
-  OptionInfoRec o;
-
-  o.name = name;
-  o.type = OPTV_STRING;
-  if (ParseOptionValue (-1, optlist, &o))
-    deflt = o.value.str;
-  if (deflt)
-    return xstrdup (deflt);
-  else
-    return NULL;
-}
-
-
-int
-winSetBoolOption (pointer optlist, const char *name, int deflt)
-{
-  OptionInfoRec o;
-
-  o.name = name;
-  o.type = OPTV_BOOLEAN;
-  if (ParseOptionValue (-1, optlist, &o))
-    deflt = o.value.bool;
-  return deflt;
-}
-
-
-int
-winSetIntOption (pointer optlist, const char *name, int deflt)
-{
-  OptionInfoRec o;
-
-  o.name = name;
-  o.type = OPTV_INTEGER;
-  if (ParseOptionValue (-1, optlist, &o))
-    deflt = o.value.num;
-  return deflt;
-}
-
-
-double
-winSetRealOption (pointer optlist, const char *name, double deflt)
-{
-  OptionInfoRec o;
-
-  o.name = name;
-  o.type = OPTV_REAL;
-  if (ParseOptionValue (-1, optlist, &o))
-    deflt = o.value.realnum;
-  return deflt;
-}
-#endif
-
-
-/*
- * Compare two strings for equality. This is caseinsensitive  and
- * The characters '_', ' ' (space) and '\t' (tab) are treated as 
- * not existing.
- */
-
-int
-winNameCompare (const char *s1, const char *s2)
-{
-  char c1, c2;
-
-  if (!s1 || *s1 == 0)
-    {
-      if (!s2 || *s2 == 0)
-	return 0;
-      else
-	return 1;
-    }
-
-  while (*s1 == '_' || *s1 == ' ' || *s1 == '\t')
-    s1++;
-  while (*s2 == '_' || *s2 == ' ' || *s2 == '\t')
-    s2++;
-
-  c1 = (isupper (*s1) ? tolower (*s1) : *s1);
-  c2 = (isupper (*s2) ? tolower (*s2) : *s2);
-
-  while (c1 == c2)
-    {
-      if (c1 == 0)
-	return 0;
-      s1++;
-      s2++;
-
-      while (*s1 == '_' || *s1 == ' ' || *s1 == '\t')
-	s1++;
-      while (*s2 == '_' || *s2 == ' ' || *s2 == '\t')
-	s2++;
-
-      c1 = (isupper (*s1) ? tolower (*s1) : *s1);
-      c2 = (isupper (*s2) ? tolower (*s2) : *s2);
-    }
-  return (c1 - c2);
-}
-
-
-#ifdef XWIN_XF86CONFIG
-/*
- * Find the named option in the list. 
- * @return the pointer to the option record, or NULL if not found.
- */
-
-XF86OptionPtr
-winFindOption (XF86OptionPtr list, const char *name)
-{
-  while (list)
-    {
-      if (winNameCompare (list->opt_name, name) == 0)
-	return list;
-      list = list->list.next;
-    }
-  return NULL;
-}
-
-
-/*
- * Find the Value of an named option.
- * @return The option value or NULL if not found.
- */
-
-char *
-winFindOptionValue (XF86OptionPtr list, const char *name)
-{
-  list = winFindOption (list, name);
-  if (list)
-    {
-      if (list->opt_val)
-	return (list->opt_val);
-      else
-	return "";
-    }
-  return (NULL);
-}
-
-
-/*
- * Parse the option.
- */
-
-static Bool
-ParseOptionValue (int scrnIndex, pointer options, OptionInfoPtr p)
-{
-  char *s, *end;
-
-  if ((s = winFindOptionValue (options, p->name)) != NULL)
-    {
-      switch (p->type)
-	{
-	case OPTV_INTEGER:
-	  if (*s == '\0')
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires an integer value\n",
-			 p->name);
-	      p->found = FALSE;
-	    }
-	  else
-	    {
-	      p->value.num = strtoul (s, &end, 0);
-	      if (*end == '\0')
-		{
-		  p->found = TRUE;
-		}
-	      else
-		{
-		  winDrvMsg (scrnIndex, X_WARNING,
-			     "Option \"%s\" requires an integer value\n",
-			     p->name);
-		  p->found = FALSE;
-		}
-	    }
-	  break;
-	case OPTV_STRING:
-	  if (*s == '\0')
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires an string value\n", p->name);
-	      p->found = FALSE;
-	    }
-	  else
-	    {
-	      p->value.str = s;
-	      p->found = TRUE;
-	    }
-	  break;
-	case OPTV_ANYSTR:
-	  p->value.str = s;
-	  p->found = TRUE;
-	  break;
-	case OPTV_REAL:
-	  if (*s == '\0')
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires a floating point value\n",
-			 p->name);
-	      p->found = FALSE;
-	    }
-	  else
-	    {
-	      p->value.realnum = strtod (s, &end);
-	      if (*end == '\0')
-		{
-		  p->found = TRUE;
-		}
-	      else
-		{
-		  winDrvMsg (scrnIndex, X_WARNING,
-			     "Option \"%s\" requires a floating point value\n",
-			     p->name);
-		  p->found = FALSE;
-		}
-	    }
-	  break;
-	case OPTV_BOOLEAN:
-	  if (GetBoolValue (p, s))
-	    {
-	      p->found = TRUE;
-	    }
-	  else
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires a boolean value\n", p->name);
-	      p->found = FALSE;
-	    }
-	  break;
-	case OPTV_FREQ:
-	  if (*s == '\0')
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires a frequency value\n",
-			 p->name);
-	      p->found = FALSE;
-	    }
-	  else
-	    {
-	      double freq = strtod (s, &end);
-	      int units = 0;
-
-	      if (end != s)
-		{
-		  p->found = TRUE;
-		  if (!winNameCompare (end, "Hz"))
-		    units = 1;
-		  else if (!winNameCompare (end, "kHz") ||
-			   !winNameCompare (end, "k"))
-		    units = 1000;
-		  else if (!winNameCompare (end, "MHz") ||
-			   !winNameCompare (end, "M"))
-		    units = 1000000;
-		  else
-		    {
-		      winDrvMsg (scrnIndex, X_WARNING,
-				 "Option \"%s\" requires a frequency value\n",
-				 p->name);
-		      p->found = FALSE;
-		    }
-		  if (p->found)
-		    freq *= (double) units;
-		}
-	      else
-		{
-		  winDrvMsg (scrnIndex, X_WARNING,
-			     "Option \"%s\" requires a frequency value\n",
-			     p->name);
-		  p->found = FALSE;
-		}
-	      if (p->found)
-		{
-		  p->value.freq.freq = freq;
-		  p->value.freq.units = units;
-		}
-	    }
-	  break;
-	case OPTV_NONE:
-	  /* Should never get here */
-	  p->found = FALSE;
-	  break;
-	}
-      if (p->found)
-	{
-	  winDrvMsgVerb (scrnIndex, X_CONFIG, 2, "Option \"%s\"", p->name);
-	  if (!(p->type == OPTV_BOOLEAN && *s == 0))
-	    {
-	      winErrorFVerb (2, " \"%s\"", s);
-	    }
-	  winErrorFVerb (2, "\n");
-	}
-    }
-  else if (p->type == OPTV_BOOLEAN)
-    {
-      /* Look for matches with options with or without a "No" prefix. */
-      char *n, *newn;
-      OptionInfoRec opt;
-
-      n = winNormalizeName (p->name);
-      if (!n)
-	{
-	  p->found = FALSE;
-	  return FALSE;
-	}
-      if (strncmp (n, "no", 2) == 0)
-	{
-	  newn = n + 2;
-	}
-      else
-	{
-	  free (n);
-	  n = malloc (strlen (p->name) + 2 + 1);
-	  if (!n)
-	    {
-	      p->found = FALSE;
-	      return FALSE;
-	    }
-	  strcpy (n, "No");
-	  strcat (n, p->name);
-	  newn = n;
-	}
-      if ((s = winFindOptionValue (options, newn)) != NULL)
-	{
-	  if (GetBoolValue (&opt, s))
-	    {
-	      p->value.bool = !opt.value.bool;
-	      p->found = TRUE;
-	    }
-	  else
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires a boolean value\n", newn);
-	      p->found = FALSE;
-	    }
-	}
-      else
-	{
-	  p->found = FALSE;
-	}
-      if (p->found)
-	{
-	  winDrvMsgVerb (scrnIndex, X_CONFIG, 2, "Option \"%s\"", newn);
-	  if (*s != 0)
-	    {
-	      winErrorFVerb (2, " \"%s\"", s);
-	    }
-	  winErrorFVerb (2, "\n");
-	}
-      free (n);
-    }
-  else
-    {
-      p->found = FALSE;
-    }
-  return p->found;
-}
-
-
-static Bool
-configLayout (serverLayoutPtr servlayoutp, XF86ConfLayoutPtr conf_layout,
-	      char *default_layout)
-{
-#if 0
-#pragma warn UNIMPLEMENTED
-#endif
-  return TRUE;
-}
-
-
-static Bool
-configImpliedLayout (serverLayoutPtr servlayoutp,
-		     XF86ConfScreenPtr conf_screen)
-{
-#if 0
-#pragma warn UNIMPLEMENTED
-#endif
-  return TRUE;
-}
-
-
-static Bool
-GetBoolValue (OptionInfoPtr p, const char *s)
-{
-  if (*s == 0)
-    {
-      p->value.bool = TRUE;
-    }
-  else
-    {
-      if (winNameCompare (s, "1") == 0)
-	p->value.bool = TRUE;
-      else if (winNameCompare (s, "on") == 0)
-	p->value.bool = TRUE;
-      else if (winNameCompare (s, "true") == 0)
-	p->value.bool = TRUE;
-      else if (winNameCompare (s, "yes") == 0)
-	p->value.bool = TRUE;
-      else if (winNameCompare (s, "0") == 0)
-	p->value.bool = FALSE;
-      else if (winNameCompare (s, "off") == 0)
-	p->value.bool = FALSE;
-      else if (winNameCompare (s, "false") == 0)
-	p->value.bool = FALSE;
-      else if (winNameCompare (s, "no") == 0)
-	p->value.bool = FALSE;
-    }
-  return TRUE;
-}
-#endif
-
-
-char *
-winNormalizeName (const char *s)
-{
-  char *ret, *q;
-  const char *p;
-
-  if (s == NULL)
-    return NULL;
-
-  ret = malloc (strlen (s) + 1);
-  for (p = s, q = ret; *p != 0; p++)
-    {
-      switch (*p)
-	{
-	case '_':
-	case ' ':
-	case '\t':
-	  continue;
-	default:
-	  if (isupper (*p))
-	    *q++ = tolower (*p);
-	  else
-	    *q++ = *p;
-	}
-    }
-  *q = '\0';
-  return ret;
-}
-
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors: Alexander Gottwald	
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winconfig.h"
+#include "winmsg.h"
+#include "globals.h"
+
+#include "xkbsrv.h"
+
+#ifdef XWIN_XF86CONFIG
+#ifndef CONFIGPATH
+#define CONFIGPATH  "%A," "%R," \
+                    "/etc/X11/%R," "%P/etc/X11/%R," \
+                    "%E," "%F," \
+                    "/etc/X11/%F," "%P/etc/X11/%F," \
+                    "/etc/X11/%X-%M," "/etc/X11/%X," "/etc/%X," \
+                    "%P/etc/X11/%X.%H," "%P/etc/X11/%X-%M," \
+                    "%P/etc/X11/%X," \
+                    "%P/lib/X11/%X.%H," "%P/lib/X11/%X-%M," \
+                    "%P/lib/X11/%X"
+#endif
+#ifndef CONFIGDIRPATH
+#define CONFIGDIRPATH  "/etc/X11/%X-%M," "/etc/X11/%X," "/etc/%X," \
+                       "%P/etc/X11/%X.%H," "%P/etc/X11/%X-%M," \
+                       "%P/etc/X11/%X," \
+                       "%P/lib/X11/%X.%H," "%P/lib/X11/%X-%M," \
+                       "%P/lib/X11/%X"
+#endif
+
+XF86ConfigPtr g_xf86configptr = NULL;
+#endif
+
+WinCmdlineRec g_cmdline = {
+#ifdef XWIN_XF86CONFIG
+  NULL,				/* configFile */
+  NULL,				/* configDir */
+#endif
+  NULL,				/* fontPath */
+#ifdef XWIN_XF86CONFIG
+  NULL,				/* keyboard */
+#endif
+  NULL,             /* xkbRules */
+  NULL,             /* xkbModel */
+  NULL,             /* xkbLayout */
+  NULL,             /* xkbVariant */
+  NULL,             /* xkbOptions */
+  NULL,				/* screenname */
+  NULL,				/* mousename */
+  FALSE,			/* emulate3Buttons */
+  0				/* emulate3Timeout */
+};
+
+winInfoRec g_winInfo = {
+  {				/* keyboard */
+   0,				/* leds */
+   500,				/* delay */
+   30				/* rate */
+   }
+  ,
+  {				/* xkb */
+   NULL,			/* rules */
+   NULL,			/* model */
+   NULL,			/* layout */
+   NULL,			/* variant */
+   NULL,			/* options */
+   }
+  ,
+  {
+   FALSE,
+   50}
+};
+
+#define NULL_IF_EMPTY(x) (winNameCompare(x,"")?x:NULL)
+
+#ifdef XWIN_XF86CONFIG
+serverLayoutRec g_winConfigLayout;
+
+static Bool ParseOptionValue (int scrnIndex, pointer options,
+			      OptionInfoPtr p);
+static Bool configLayout (serverLayoutPtr, XF86ConfLayoutPtr, char *);
+static Bool configImpliedLayout (serverLayoutPtr, XF86ConfScreenPtr);
+static Bool GetBoolValue (OptionInfoPtr p, const char *s);
+
+
+Bool
+winReadConfigfile ()
+{
+  Bool		retval = TRUE;
+  const char	*filename, *dirname;
+  MessageType	filefrom = X_DEFAULT;
+  MessageType	dirfrom = X_DEFAULT;
+  char		*xf86ConfigFile = NULL;
+  char		*xf86ConfigDir = NULL;
+
+  if (g_cmdline.configFile)
+    {
+      filefrom = X_CMDLINE;
+      xf86ConfigFile = g_cmdline.configFile;
+    }
+  if (g_cmdline.configDir)
+    {
+      dirfrom = X_CMDLINE;
+      xf86ConfigDir = g_cmdline.configDir;
+    }
+
+  /* Parse config file into data structure */
+  xf86initConfigFiles();
+  dirname = xf86openConfigDirFiles (CONFIGDIRPATH, xf86ConfigDir, PROJECTROOT);
+  filename = xf86openConfigFile (CONFIGPATH, xf86ConfigFile, PROJECTROOT);
+
+  /* Hack for backward compatibility */
+  if (!filename && from == X_DEFAULT)
+    filename = xf86openConfigFile (CONFIGPATH, "XF86Config", PROJECTROOT);
+
+  if (filename)
+    {
+      winMsg (from, "Using config file: \"%s\"\n", filename);
+    }
+  else
+    {
+      winMsg (X_ERROR, "Unable to locate/open config file");
+      if (xf86ConfigFile)
+	ErrorF (": \"%s\"", xf86ConfigFile);
+      ErrorF ("\n");
+    }
+  if (dirname)
+    {
+      winMsg (from, "Using config directory: \"%s\"\n", dirname);
+    }
+  else
+    {
+      winMsg (X_ERROR, "Unable to locate/open config directory");
+      if (xf86ConfigDir)
+	ErrorF (": \"%s\"", xf86ConfigDir);
+      ErrorF ("\n");
+    }
+  if (!filename && !dirname)
+    {
+      return FALSE;
+    }
+  if ((g_xf86configptr = xf86readConfigFile ()) == NULL)
+    {
+      winMsg (X_ERROR, "Problem parsing the config file\n");
+      return FALSE;
+    }
+  xf86closeConfigFile ();
+
+  LogPrintMarkers();
+
+  /* set options from data structure */
+
+  if (g_xf86configptr->conf_layout_lst == NULL || g_cmdline.screenname != NULL)
+    {
+      if (g_cmdline.screenname == NULL)
+	{
+	  winMsg (X_WARNING,
+		  "No Layout section. Using the first Screen section.\n");
+	}
+      if (!configImpliedLayout (&g_winConfigLayout,
+				g_xf86configptr->conf_screen_lst))
+	{
+	  winMsg (X_ERROR, "Unable to determine the screen layout\n");
+	  return FALSE;
+	}
+    }
+  else
+    {
+      /* Check if layout is given in the config file */
+      if (g_xf86configptr->conf_flags != NULL)
+	{
+	  char *dfltlayout = NULL;
+	  pointer optlist = g_xf86configptr->conf_flags->flg_option_lst;
+
+	  if (optlist && winFindOption (optlist, "defaultserverlayout"))
+	    dfltlayout =
+	      winSetStrOption (optlist, "defaultserverlayout", NULL);
+
+	  if (!configLayout (&g_winConfigLayout,
+			     g_xf86configptr->conf_layout_lst,
+			     dfltlayout))
+	    {
+	      winMsg (X_ERROR, "Unable to determine the screen layout\n");
+	      return FALSE;
+	    }
+	}
+      else
+	{
+	  if (!configLayout (&g_winConfigLayout,
+			     g_xf86configptr->conf_layout_lst,
+			     NULL))
+	    {
+	      winMsg (X_ERROR, "Unable to determine the screen layout\n");
+	      return FALSE;
+	    }
+	}
+    }
+
+  /* setup special config files */
+  winConfigFiles ();
+  return retval;
+}
+#endif
+
+/* load layout definitions */
+#include "winlayouts.h"
+
+/* Set the keyboard configuration */
+Bool
+winConfigKeyboard (DeviceIntPtr pDevice)
+{
+  char                          layoutName[KL_NAMELENGTH];
+  static unsigned int           layoutNum = 0;
+  int                           keyboardType;
+#ifdef XWIN_XF86CONFIG
+  XF86ConfInputPtr		kbd = NULL;
+  XF86ConfInputPtr		input_list = NULL;
+  MessageType			kbdfrom = X_CONFIG;
+#endif
+  MessageType			from = X_DEFAULT;
+  char				*s = NULL;
+
+  /* Setup defaults */
+  XkbGetRulesDflts(&g_winInfo.xkb);
+
+  /*
+   * Query the windows autorepeat settings and change the xserver defaults.   
+   */
+  {
+    int kbd_delay;
+    DWORD kbd_speed;
+    if (SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &kbd_delay, 0) &&
+        SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &kbd_speed, 0))
+      {
+        switch (kbd_delay) 
+          {
+            case 0:  g_winInfo.keyboard.delay = 250; break;
+            case 1:  g_winInfo.keyboard.delay = 500; break;
+            case 2:  g_winInfo.keyboard.delay = 750; break;
+            default:
+            case 3:  g_winInfo.keyboard.delay = 1000; break;
+          }
+        g_winInfo.keyboard.rate = (kbd_speed>0)?kbd_speed:1;
+        winMsgVerb(X_PROBED, 1, "Setting autorepeat to delay=%d, rate=%d\n",
+                g_winInfo.keyboard.delay, g_winInfo.keyboard.rate);
+      }
+  }
+  
+
+  keyboardType = GetKeyboardType (0);
+  if (keyboardType > 0 && GetKeyboardLayoutName (layoutName)) 
+  {
+    WinKBLayoutPtr	pLayout;
+    Bool                bfound = FALSE;
+
+    if (! layoutNum)
+      layoutNum = strtoul (layoutName, (char **)NULL, 16);
+    if ((layoutNum & 0xffff) == 0x411) {
+        /* The japanese layouts know a lot of different IMEs which all have
+	   different layout numbers set. Map them to a single entry. 
+	   Same might apply for chinese, korean and other symbol languages
+	   too */
+        layoutNum = (layoutNum & 0xffff);
+	if (keyboardType == 7)
+	  {
+	    /* Japanese layouts have problems with key event messages
+	       such as the lack of WM_KEYUP for Caps Lock key.
+	       Loading US layout fixes this problem. */
+	    if (LoadKeyboardLayout("00000409", KLF_ACTIVATE) != NULL)
+	      winMsg (X_INFO, "Loading US keyboard layout.\n");
+	    else
+	      winMsg (X_ERROR, "LoadKeyboardLaout failed.\n");
+	  }
+    }
+    winMsg (X_PROBED, "winConfigKeyboard - Layout: \"%s\" (%08x) \n", 
+            layoutName, layoutNum);
+
+    for (pLayout = winKBLayouts; pLayout->winlayout != -1; pLayout++)
+      {
+	if (pLayout->winlayout != layoutNum)
+	  continue;
+	if (pLayout->winkbtype > 0 && pLayout->winkbtype != keyboardType)
+	  continue;
+	
+        bfound = TRUE;
+	winMsg (X_PROBED,
+		"Using preset keyboard for \"%s\" (%x), type \"%d\"\n",
+		pLayout->layoutname, pLayout->winlayout, keyboardType);
+	
+	g_winInfo.xkb.model = pLayout->xkbmodel;
+	g_winInfo.xkb.layout = pLayout->xkblayout;
+	g_winInfo.xkb.variant = pLayout->xkbvariant;
+	g_winInfo.xkb.options = pLayout->xkboptions; 
+	break;
+      }
+    
+    if (!bfound)
+      {
+        HKEY                regkey = NULL;
+        const char          regtempl[] = 
+          "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\";
+        char                *regpath;
+        unsigned char       lname[256];
+        DWORD               namesize = sizeof(lname);
+
+        regpath = malloc(sizeof(regtempl) + KL_NAMELENGTH + 1);
+        strcpy(regpath, regtempl);
+        strcat(regpath, layoutName);
+
+        if (!RegOpenKey(HKEY_LOCAL_MACHINE, regpath, &regkey) &&
+          !RegQueryValueEx(regkey, "Layout Text", 0, NULL, lname, &namesize))
+          {
+	    winMsg (X_ERROR,
+		"Keyboardlayout \"%s\" (%s) is unknown\n", lname, layoutName);
+          }
+
+	/* Close registry key */
+	if (regkey)
+	  RegCloseKey (regkey);
+        free(regpath);
+      }
+  }  
+  
+  /* parse the configuration */
+#ifdef XWIN_XF86CONFIG
+  if (g_cmdline.keyboard)
+    kbdfrom = X_CMDLINE;
+
+  /*
+   * Until the layout code is finished, I search for the keyboard 
+   * device and configure the server with it.
+   */
+
+  if (g_xf86configptr != NULL)
+    input_list = g_xf86configptr->conf_input_lst;
+
+  while (input_list != NULL)
+    {
+      if (winNameCompare (input_list->inp_driver, "keyboard") == 0)
+	{
+	  /* Check if device name matches requested name */
+	  if (g_cmdline.keyboard && winNameCompare (input_list->inp_identifier,
+						    g_cmdline.keyboard))
+	    continue;
+	  kbd = input_list;
+	}
+      input_list = input_list->list.next;
+    }
+
+  if (kbd != NULL)
+    {
+
+      if (kbd->inp_identifier)
+	winMsg (kbdfrom, "Using keyboard \"%s\" as primary keyboard\n",
+		kbd->inp_identifier);
+
+      if ((s = winSetStrOption(kbd->inp_option_lst, "AutoRepeat", NULL)))
+        {
+          if ((sscanf(s, "%ld %ld", &g_winInfo.keyboard.delay, 
+                      &g_winInfo.keyboard.rate) != 2) ||
+                  (g_winInfo.keyboard.delay < 1) || 
+                  (g_winInfo.keyboard.rate == 0) || 
+                  (1000 / g_winInfo.keyboard.rate) < 1) 
+            {
+              winErrorFVerb (2, "\"%s\" is not a valid AutoRepeat value", s);
+              xfree(s);
+              return FALSE;
+            }
+          xfree(s);
+          winMsg (X_CONFIG, "AutoRepeat: %ld %ld\n", 
+                  g_winInfo.keyboard.delay, g_winInfo.keyboard.rate);
+        }
+#endif
+      
+        s = NULL;
+        if (g_cmdline.xkbRules)
+          {
+            s = g_cmdline.xkbRules;
+            from = X_CMDLINE;
+          }
+#ifdef XWIN_XF86CONFIG
+        else
+          {
+            s = winSetStrOption (kbd->inp_option_lst, "XkbRules", NULL);
+            from = X_CONFIG;
+          }
+#endif
+        if (s)
+          {
+            g_winInfo.xkb.rules = NULL_IF_EMPTY (s);
+            winMsg (from, "XKB: rules: \"%s\"\n", s);
+	  }
+          
+        s = NULL;
+        if (g_cmdline.xkbModel)
+          {
+            s = g_cmdline.xkbModel;
+            from = X_CMDLINE;
+          }
+#ifdef XWIN_XF86CONFIG
+        else
+          {
+            s = winSetStrOption (kbd->inp_option_lst, "XkbModel", NULL);
+            from = X_CONFIG;
+          }
+#endif
+        if (s)
+	  {
+	    g_winInfo.xkb.model = NULL_IF_EMPTY (s);
+	    winMsg (from, "XKB: model: \"%s\"\n", s);
+	  }
+
+        s = NULL;
+        if (g_cmdline.xkbLayout)
+          {
+            s = g_cmdline.xkbLayout;
+            from = X_CMDLINE;
+          }
+#ifdef XWIN_XF86CONFIG
+        else
+          {
+            s = winSetStrOption (kbd->inp_option_lst, "XkbLayout", NULL);
+            from = X_CONFIG;
+          }
+#endif
+        if (s)
+          {
+	    g_winInfo.xkb.layout = NULL_IF_EMPTY (s);
+	    winMsg (from, "XKB: layout: \"%s\"\n", s);
+	  }
+
+        s = NULL;
+        if (g_cmdline.xkbVariant)
+          {
+            s = g_cmdline.xkbVariant;
+            from = X_CMDLINE;
+          }
+#ifdef XWIN_XF86CONFIG
+        else
+          {
+            s = winSetStrOption (kbd->inp_option_lst, "XkbVariant", NULL);
+            from = X_CONFIG;
+          }
+#endif
+	if (s)
+	  {
+	    g_winInfo.xkb.variant = NULL_IF_EMPTY (s);
+	    winMsg (from, "XKB: variant: \"%s\"\n", s);
+	  }
+
+        s = NULL;
+        if (g_cmdline.xkbOptions)
+          {
+            s = g_cmdline.xkbOptions;
+            from = X_CMDLINE;
+          }
+#ifdef XWIN_XF86CONFIG
+        else
+          {
+            s = winSetStrOption (kbd->inp_option_lst, "XkbOptions", NULL);
+            from = X_CONFIG;
+          }
+#endif
+        if (s)
+	  {
+	    g_winInfo.xkb.options = NULL_IF_EMPTY (s);
+	    winMsg (from, "XKB: options: \"%s\"\n", s);
+	  }
+
+#ifdef XWIN_XF86CONFIG
+    }
+#endif
+
+  return TRUE;
+}
+
+
+#ifdef XWIN_XF86CONFIG
+Bool
+winConfigMouse (DeviceIntPtr pDevice)
+{
+  MessageType			mousefrom = X_CONFIG;
+
+  XF86ConfInputPtr		mouse = NULL;
+  XF86ConfInputPtr		input_list = NULL;
+
+  if (g_cmdline.mouse)
+    mousefrom = X_CMDLINE;
+
+  if (g_xf86configptr != NULL)
+    input_list = g_xf86configptr->conf_input_lst;
+
+  while (input_list != NULL)
+    {
+      if (winNameCompare (input_list->inp_driver, "mouse") == 0)
+	{
+	  /* Check if device name matches requested name */
+	  if (g_cmdline.mouse && winNameCompare (input_list->inp_identifier,
+						 g_cmdline.mouse))
+	    continue;
+	  mouse = input_list;
+	}
+      input_list = input_list->list.next;
+    }
+
+  if (mouse != NULL)
+    {
+      if (mouse->inp_identifier)
+	winMsg (mousefrom, "Using pointer \"%s\" as primary pointer\n",
+		mouse->inp_identifier);
+
+      g_winInfo.pointer.emulate3Buttons =
+	winSetBoolOption (mouse->inp_option_lst, "Emulate3Buttons", FALSE);
+      if (g_cmdline.emulate3buttons)
+	g_winInfo.pointer.emulate3Buttons = g_cmdline.emulate3buttons;
+
+      g_winInfo.pointer.emulate3Timeout =
+	winSetIntOption (mouse->inp_option_lst, "Emulate3Timeout", 50);
+      if (g_cmdline.emulate3timeout)
+	g_winInfo.pointer.emulate3Timeout = g_cmdline.emulate3timeout;
+    }
+  else
+    {
+      winMsg (X_ERROR, "No primary pointer configured\n");
+      winMsg (X_DEFAULT, "Using compiletime defaults for pointer\n");
+    }
+
+  return TRUE;
+}
+
+
+Bool
+winConfigFiles ()
+{
+  MessageType from;
+  XF86ConfFilesPtr filesptr = NULL;
+
+  /* set some shortcuts */
+  if (g_xf86configptr != NULL)
+    {
+      filesptr = g_xf86configptr->conf_files;
+    }
+
+
+  /* Fontpath */
+  from = X_DEFAULT;
+
+  if (g_cmdline.fontPath)
+    {
+      from = X_CMDLINE;
+      defaultFontPath = g_cmdline.fontPath;
+    }
+  else if (filesptr != NULL && filesptr->file_fontpath)
+    {
+      from = X_CONFIG;
+      defaultFontPath = xstrdup (filesptr->file_fontpath);
+    }
+  winMsg (from, "FontPath set to \"%s\"\n", defaultFontPath);
+
+  return TRUE;
+}
+#else
+Bool
+winConfigFiles (void)
+{
+  /* Fontpath */
+  if (g_cmdline.fontPath)
+    {
+      defaultFontPath = g_cmdline.fontPath;
+      winMsg (X_CMDLINE, "FontPath set to \"%s\"\n", defaultFontPath);
+    }
+
+  return TRUE;
+}
+#endif
+
+
+Bool
+winConfigOptions (void)
+{
+  return TRUE;
+}
+
+
+Bool
+winConfigScreens (void)
+{
+  return TRUE;
+}
+
+
+#ifdef XWIN_XF86CONFIG
+char *
+winSetStrOption (pointer optlist, const char *name, char *deflt)
+{
+  OptionInfoRec o;
+
+  o.name = name;
+  o.type = OPTV_STRING;
+  if (ParseOptionValue (-1, optlist, &o))
+    deflt = o.value.str;
+  if (deflt)
+    return xstrdup (deflt);
+  else
+    return NULL;
+}
+
+
+int
+winSetBoolOption (pointer optlist, const char *name, int deflt)
+{
+  OptionInfoRec o;
+
+  o.name = name;
+  o.type = OPTV_BOOLEAN;
+  if (ParseOptionValue (-1, optlist, &o))
+    deflt = o.value.bool;
+  return deflt;
+}
+
+
+int
+winSetIntOption (pointer optlist, const char *name, int deflt)
+{
+  OptionInfoRec o;
+
+  o.name = name;
+  o.type = OPTV_INTEGER;
+  if (ParseOptionValue (-1, optlist, &o))
+    deflt = o.value.num;
+  return deflt;
+}
+
+
+double
+winSetRealOption (pointer optlist, const char *name, double deflt)
+{
+  OptionInfoRec o;
+
+  o.name = name;
+  o.type = OPTV_REAL;
+  if (ParseOptionValue (-1, optlist, &o))
+    deflt = o.value.realnum;
+  return deflt;
+}
+#endif
+
+
+/*
+ * Compare two strings for equality. This is caseinsensitive  and
+ * The characters '_', ' ' (space) and '\t' (tab) are treated as 
+ * not existing.
+ */
+
+int
+winNameCompare (const char *s1, const char *s2)
+{
+  char c1, c2;
+
+  if (!s1 || *s1 == 0)
+    {
+      if (!s2 || *s2 == 0)
+	return 0;
+      else
+	return 1;
+    }
+
+  while (*s1 == '_' || *s1 == ' ' || *s1 == '\t')
+    s1++;
+  while (*s2 == '_' || *s2 == ' ' || *s2 == '\t')
+    s2++;
+
+  c1 = (isupper (*s1) ? tolower (*s1) : *s1);
+  c2 = (isupper (*s2) ? tolower (*s2) : *s2);
+
+  while (c1 == c2)
+    {
+      if (c1 == 0)
+	return 0;
+      s1++;
+      s2++;
+
+      while (*s1 == '_' || *s1 == ' ' || *s1 == '\t')
+	s1++;
+      while (*s2 == '_' || *s2 == ' ' || *s2 == '\t')
+	s2++;
+
+      c1 = (isupper (*s1) ? tolower (*s1) : *s1);
+      c2 = (isupper (*s2) ? tolower (*s2) : *s2);
+    }
+  return (c1 - c2);
+}
+
+
+#ifdef XWIN_XF86CONFIG
+/*
+ * Find the named option in the list. 
+ * @return the pointer to the option record, or NULL if not found.
+ */
+
+XF86OptionPtr
+winFindOption (XF86OptionPtr list, const char *name)
+{
+  while (list)
+    {
+      if (winNameCompare (list->opt_name, name) == 0)
+	return list;
+      list = list->list.next;
+    }
+  return NULL;
+}
+
+
+/*
+ * Find the Value of an named option.
+ * @return The option value or NULL if not found.
+ */
+
+char *
+winFindOptionValue (XF86OptionPtr list, const char *name)
+{
+  list = winFindOption (list, name);
+  if (list)
+    {
+      if (list->opt_val)
+	return (list->opt_val);
+      else
+	return "";
+    }
+  return (NULL);
+}
+
+
+/*
+ * Parse the option.
+ */
+
+static Bool
+ParseOptionValue (int scrnIndex, pointer options, OptionInfoPtr p)
+{
+  char *s, *end;
+
+  if ((s = winFindOptionValue (options, p->name)) != NULL)
+    {
+      switch (p->type)
+	{
+	case OPTV_INTEGER:
+	  if (*s == '\0')
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires an integer value\n",
+			 p->name);
+	      p->found = FALSE;
+	    }
+	  else
+	    {
+	      p->value.num = strtoul (s, &end, 0);
+	      if (*end == '\0')
+		{
+		  p->found = TRUE;
+		}
+	      else
+		{
+		  winDrvMsg (scrnIndex, X_WARNING,
+			     "Option \"%s\" requires an integer value\n",
+			     p->name);
+		  p->found = FALSE;
+		}
+	    }
+	  break;
+	case OPTV_STRING:
+	  if (*s == '\0')
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires an string value\n", p->name);
+	      p->found = FALSE;
+	    }
+	  else
+	    {
+	      p->value.str = s;
+	      p->found = TRUE;
+	    }
+	  break;
+	case OPTV_ANYSTR:
+	  p->value.str = s;
+	  p->found = TRUE;
+	  break;
+	case OPTV_REAL:
+	  if (*s == '\0')
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires a floating point value\n",
+			 p->name);
+	      p->found = FALSE;
+	    }
+	  else
+	    {
+	      p->value.realnum = strtod (s, &end);
+	      if (*end == '\0')
+		{
+		  p->found = TRUE;
+		}
+	      else
+		{
+		  winDrvMsg (scrnIndex, X_WARNING,
+			     "Option \"%s\" requires a floating point value\n",
+			     p->name);
+		  p->found = FALSE;
+		}
+	    }
+	  break;
+	case OPTV_BOOLEAN:
+	  if (GetBoolValue (p, s))
+	    {
+	      p->found = TRUE;
+	    }
+	  else
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires a boolean value\n", p->name);
+	      p->found = FALSE;
+	    }
+	  break;
+	case OPTV_FREQ:
+	  if (*s == '\0')
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires a frequency value\n",
+			 p->name);
+	      p->found = FALSE;
+	    }
+	  else
+	    {
+	      double freq = strtod (s, &end);
+	      int units = 0;
+
+	      if (end != s)
+		{
+		  p->found = TRUE;
+		  if (!winNameCompare (end, "Hz"))
+		    units = 1;
+		  else if (!winNameCompare (end, "kHz") ||
+			   !winNameCompare (end, "k"))
+		    units = 1000;
+		  else if (!winNameCompare (end, "MHz") ||
+			   !winNameCompare (end, "M"))
+		    units = 1000000;
+		  else
+		    {
+		      winDrvMsg (scrnIndex, X_WARNING,
+				 "Option \"%s\" requires a frequency value\n",
+				 p->name);
+		      p->found = FALSE;
+		    }
+		  if (p->found)
+		    freq *= (double) units;
+		}
+	      else
+		{
+		  winDrvMsg (scrnIndex, X_WARNING,
+			     "Option \"%s\" requires a frequency value\n",
+			     p->name);
+		  p->found = FALSE;
+		}
+	      if (p->found)
+		{
+		  p->value.freq.freq = freq;
+		  p->value.freq.units = units;
+		}
+	    }
+	  break;
+	case OPTV_NONE:
+	  /* Should never get here */
+	  p->found = FALSE;
+	  break;
+	}
+      if (p->found)
+	{
+	  winDrvMsgVerb (scrnIndex, X_CONFIG, 2, "Option \"%s\"", p->name);
+	  if (!(p->type == OPTV_BOOLEAN && *s == 0))
+	    {
+	      winErrorFVerb (2, " \"%s\"", s);
+	    }
+	  winErrorFVerb (2, "\n");
+	}
+    }
+  else if (p->type == OPTV_BOOLEAN)
+    {
+      /* Look for matches with options with or without a "No" prefix. */
+      char *n, *newn;
+      OptionInfoRec opt;
+
+      n = winNormalizeName (p->name);
+      if (!n)
+	{
+	  p->found = FALSE;
+	  return FALSE;
+	}
+      if (strncmp (n, "no", 2) == 0)
+	{
+	  newn = n + 2;
+	}
+      else
+	{
+	  free (n);
+	  n = malloc (strlen (p->name) + 2 + 1);
+	  if (!n)
+	    {
+	      p->found = FALSE;
+	      return FALSE;
+	    }
+	  strcpy (n, "No");
+	  strcat (n, p->name);
+	  newn = n;
+	}
+      if ((s = winFindOptionValue (options, newn)) != NULL)
+	{
+	  if (GetBoolValue (&opt, s))
+	    {
+	      p->value.bool = !opt.value.bool;
+	      p->found = TRUE;
+	    }
+	  else
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires a boolean value\n", newn);
+	      p->found = FALSE;
+	    }
+	}
+      else
+	{
+	  p->found = FALSE;
+	}
+      if (p->found)
+	{
+	  winDrvMsgVerb (scrnIndex, X_CONFIG, 2, "Option \"%s\"", newn);
+	  if (*s != 0)
+	    {
+	      winErrorFVerb (2, " \"%s\"", s);
+	    }
+	  winErrorFVerb (2, "\n");
+	}
+      free (n);
+    }
+  else
+    {
+      p->found = FALSE;
+    }
+  return p->found;
+}
+
+
+static Bool
+configLayout (serverLayoutPtr servlayoutp, XF86ConfLayoutPtr conf_layout,
+	      char *default_layout)
+{
+#if 0
+#pragma warn UNIMPLEMENTED
+#endif
+  return TRUE;
+}
+
+
+static Bool
+configImpliedLayout (serverLayoutPtr servlayoutp,
+		     XF86ConfScreenPtr conf_screen)
+{
+#if 0
+#pragma warn UNIMPLEMENTED
+#endif
+  return TRUE;
+}
+
+
+static Bool
+GetBoolValue (OptionInfoPtr p, const char *s)
+{
+  if (*s == 0)
+    {
+      p->value.bool = TRUE;
+    }
+  else
+    {
+      if (winNameCompare (s, "1") == 0)
+	p->value.bool = TRUE;
+      else if (winNameCompare (s, "on") == 0)
+	p->value.bool = TRUE;
+      else if (winNameCompare (s, "true") == 0)
+	p->value.bool = TRUE;
+      else if (winNameCompare (s, "yes") == 0)
+	p->value.bool = TRUE;
+      else if (winNameCompare (s, "0") == 0)
+	p->value.bool = FALSE;
+      else if (winNameCompare (s, "off") == 0)
+	p->value.bool = FALSE;
+      else if (winNameCompare (s, "false") == 0)
+	p->value.bool = FALSE;
+      else if (winNameCompare (s, "no") == 0)
+	p->value.bool = FALSE;
+    }
+  return TRUE;
+}
+#endif
+
+
+char *
+winNormalizeName (const char *s)
+{
+  char *ret, *q;
+  const char *p;
+
+  if (s == NULL)
+    return NULL;
+
+  ret = malloc (strlen (s) + 1);
+  for (p = s, q = ret; *p != 0; p++)
+    {
+      switch (*p)
+	{
+	case '_':
+	case ' ':
+	case '\t':
+	  continue;
+	default:
+	  if (isupper (*p))
+	    *q++ = tolower (*p);
+	  else
+	    *q++ = *p;
+	}
+    }
+  *q = '\0';
+  return ret;
+}
+
diff --git a/xorg-server/hw/xwin/winkeybd.c b/xorg-server/hw/xwin/winkeybd.c
index a423b499a..c5795635f 100644
--- a/xorg-server/hw/xwin/winkeybd.c
+++ b/xorg-server/hw/xwin/winkeybd.c
@@ -1,617 +1,531 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winkeybd.h"
-#include "winconfig.h"
-#include "winmsg.h"
-
-#include "xkbsrv.h"
-
-static Bool g_winKeyState[NUM_KEYCODES];
-
-/*
- * Local prototypes
- */
-
-static void
-winGetKeyMappings (KeySymsPtr pKeySyms, CARD8 *pModMap);
-
-static void
-winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
-	      pointer pCtrl, int iClass);
-
-static void
-winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl);
-
-
-/* 
- * Translate a Windows WM_[SYS]KEY(UP/DOWN) message
- * into an ASCII scan code.
- *
- * We do this ourselves, rather than letting Windows handle it,
- * because Windows tends to munge the handling of special keys,
- * like AltGr on European keyboards.
- */
-
-void
-winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode)
-{
-  int		iKeyFixup = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 1];
-  int		iKeyFixupEx = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 2];
-  int		iParam = HIWORD (lParam);
-  int		iParamScanCode = LOBYTE (iParam);
-
-/* WM_ key messages faked by Vista speech recognition (WSR) don't have a
- * scan code.
- *
- * Vocola 3 (Rick Mohr's supplement to WSR) uses
- * System.Windows.Forms.SendKeys.SendWait(), which appears always to give a
- * scan code of 1
- */
-  if (iParamScanCode <= 1)
-    {
-      if (VK_PRIOR <= wParam && wParam <= VK_DOWN)
-        /* Trigger special case table to translate to extended
-         * keycode, otherwise if num_lock is on, we can get keypad
-         * numbers instead of navigation keys. */
-        iParam |= KF_EXTENDED;
-      else
-        iParamScanCode = MapVirtualKeyEx(wParam,
-                         /*MAPVK_VK_TO_VSC*/0,
-                         GetKeyboardLayout(0));
-    }
-
-  /* Branch on special extended, special non-extended, or normal key */
-  if ((iParam & KF_EXTENDED) && iKeyFixupEx)
-    *piScanCode = iKeyFixupEx;
-  else if (iKeyFixup)
-    *piScanCode = iKeyFixup;
-  else if (wParam == 0 && iParamScanCode == 0x70)
-    *piScanCode = KEY_HKTG;
-  else
-    switch (iParamScanCode)
-    {
-      case 0x70:
-        *piScanCode = KEY_HKTG;
-        break;
-      case 0x73:
-        *piScanCode = KEY_BSlash2;
-        break;
-      default: 
-        *piScanCode = iParamScanCode;
-        break;
-    }
-}
-
-
-/*
- * We call this function from winKeybdProc when we are
- * initializing the keyboard.
- */
-
-static void
-winGetKeyMappings (KeySymsPtr pKeySyms, CARD8 *pModMap)
-{
-  int			i;
-  KeySym		*pMap = map;
-  KeySym		*pKeySym;
-
-  /*
-   * Initialize all key states to up... which may not be true
-   * but it is close enough.
-   */
-  ZeroMemory (g_winKeyState, sizeof (g_winKeyState[0]) * NUM_KEYCODES);
-
-  /* MAP_LENGTH is defined in Xserver/include/input.h to be 256 */
-  for (i = 0; i < MAP_LENGTH; i++)
-    pModMap[i] = NoSymbol;  /* make sure it is restored */
-
-  /* Loop through all valid entries in the key symbol table */
-  for (pKeySym = pMap, i = MIN_KEYCODE;
-       i < (MIN_KEYCODE + NUM_KEYCODES);
-       i++, pKeySym += GLYPHS_PER_KEY)
-    {
-      switch (*pKeySym)
-	{
-	case XK_Shift_L:
-	case XK_Shift_R:
-	  pModMap[i] = ShiftMask;
-	  break;
-
-	case XK_Control_L:
-	case XK_Control_R:
-	  pModMap[i] = ControlMask;
-	  break;
-
-	case XK_Caps_Lock:
-	  pModMap[i] = LockMask;
-	  break;
-
-	case XK_Alt_L:
-	case XK_Alt_R:
-	  pModMap[i] = AltMask;
-	  break;
-
-	case XK_Num_Lock:
-	  pModMap[i] = NumLockMask;
-	  break;
-
-	case XK_Scroll_Lock:
-	  pModMap[i] = ScrollLockMask;
-	  break;
-
-#if 0
-	case XK_Super_L:
-	case XK_Super_R:
-	  pModMap[i] = Mod4Mask;
-	  break;
-#else
-	/* Hirigana/Katakana toggle */
-	case XK_Kana_Lock:
-	case XK_Kana_Shift:
-	  pModMap[i] = KanaMask;
-	  break;
-#endif
-
-	/* alternate toggle for multinational support */
-	case XK_Mode_switch:
-	  pModMap[i] = AltLangMask;
-	  break;
-	}
-    }
-
-  pKeySyms->map        = (KeySym *) pMap;
-  pKeySyms->mapWidth   = GLYPHS_PER_KEY;
-  pKeySyms->minKeyCode = MIN_KEYCODE;
-  pKeySyms->maxKeyCode = MAX_KEYCODE;
-}
-
-
-/* Ring the keyboard bell (system speaker on PCs) */
-static void
-winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
-	      pointer pCtrl, int iClass)
-{
-  /*
-   * We can't use Beep () here because it uses the PC speaker
-   * on NT/2000.  MessageBeep (MB_OK) will play the default system
-   * sound on systems with a sound card or it will beep the PC speaker
-   * on systems that do not have a sound card.
-   */
-  MessageBeep (MB_OK);
-}
-
-
-/* Change some keyboard configuration parameters */
-static void
-winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl)
-{
-}
-
-
-/* 
- * See Porting Layer Definition - p. 18
- * winKeybdProc is known as a DeviceProc.
- */
-
-int
-winKeybdProc (DeviceIntPtr pDeviceInt, int iState)
-{
-  DevicePtr		pDevice = (DevicePtr) pDeviceInt;
-  XkbSrvInfoPtr       xkbi;
-  XkbControlsPtr      ctrl;
-
-  switch (iState)
-    {
-    case DEVICE_INIT:
-      winConfigKeyboard (pDeviceInt);
-
-      /* FIXME: Maybe we should use winGetKbdLeds () here? */
-      defaultKeyboardControl.leds = g_winInfo.keyboard.leds;
-
-      winErrorFVerb(2, "Rules = \"%s\" Model = \"%s\" Layout = \"%s\""
-                    " Variant = \"%s\" Options = \"%s\"\n",
-                    g_winInfo.xkb.rules ? g_winInfo.xkb.rules : "none",
-                    g_winInfo.xkb.model ? g_winInfo.xkb.model : "none",
-                    g_winInfo.xkb.layout ? g_winInfo.xkb.layout : "none",
-                    g_winInfo.xkb.variant ? g_winInfo.xkb.variant : "none",
-                    g_winInfo.xkb.options ? g_winInfo.xkb.options : "none");
-
-      InitKeyboardDeviceStruct (pDeviceInt,
-                                &g_winInfo.xkb,
-                                winKeybdBell,
-                                winKeybdCtrl);
-
-      xkbi = pDeviceInt->key->xkbInfo;
-      if ((xkbi != NULL) && (xkbi->desc != NULL))
-        {
-          ctrl = xkbi->desc->ctrls;
-          ctrl->repeat_delay = g_winInfo.keyboard.delay;
-          ctrl->repeat_interval = 1000/g_winInfo.keyboard.rate;
-        }
-      else
-        {
-          winErrorFVerb (1, "winKeybdProc - Error initializing keyboard AutoRepeat\n");
-        }
-
-      break;
-      
-    case DEVICE_ON: 
-      pDevice->on = TRUE;
-
-      // immediately copy the state of this keyboard device to the VCK
-      // (which otherwise happens lazily after the first keypress)
-      CopyKeyClass(pDeviceInt, inputInfo.keyboard);
-      break;
-
-    case DEVICE_CLOSE:
-    case DEVICE_OFF: 
-      pDevice->on = FALSE;
-      break;
-    }
-
-  return Success;
-}
-
-
-/*
- * Detect current mode key states upon server startup.
- *
- * Simulate a press and release of any key that is currently
- * toggled.
- */
-
-void
-winInitializeModeKeyStates (void)
-{
-  /* Restore NumLock */
-  if (GetKeyState (VK_NUMLOCK) & 0x0001)
-    {
-      winSendKeyEvent (KEY_NumLock, TRUE);
-      winSendKeyEvent (KEY_NumLock, FALSE);
-    }
-
-  /* Restore CapsLock */
-  if (GetKeyState (VK_CAPITAL) & 0x0001)
-    {
-      winSendKeyEvent (KEY_CapsLock, TRUE);
-      winSendKeyEvent (KEY_CapsLock, FALSE);
-    }
-
-  /* Restore ScrollLock */
-  if (GetKeyState (VK_SCROLL) & 0x0001)
-    {
-      winSendKeyEvent (KEY_ScrollLock, TRUE);
-      winSendKeyEvent (KEY_ScrollLock, FALSE);
-    }
-
-  /* Restore KanaLock */
-  if (GetKeyState (VK_KANA) & 0x0001)
-    {
-      winSendKeyEvent (KEY_HKTG, TRUE);
-      winSendKeyEvent (KEY_HKTG, FALSE);
-    }
-}
-
-
-/*
- * Upon regaining the keyboard focus we must
- * resynchronize our internal mode key states
- * with the actual state of the keys.
- */
-
-void
-winRestoreModeKeyStates (void)
-{
-  DWORD			dwKeyState;
-  BOOL			processEvents = TRUE;
-  unsigned short	internalKeyStates;
-
-  /* X server is being initialized */
-  if (!inputInfo.keyboard)
-    return;
-
-  /* Only process events if the rootwindow is mapped. The keyboard events
-   * will cause segfaults otherwise */
-  if (WindowTable && WindowTable[0] && WindowTable[0]->mapped == FALSE)
-    processEvents = FALSE;    
-  
-  /* Force to process all pending events in the mi event queue */
-  if (processEvents)
-    mieqProcessInputEvents ();
-  
-  /* Read the mode key states of our X server */
-  /* (stored in the virtual core keyboard) */
-  internalKeyStates = XkbStateFieldFromRec(&inputInfo.keyboard->key->xkbInfo->state);
-  winDebug("winRestoreModeKeyStates: state %d\n", internalKeyStates);
-
-  /* 
-   * NOTE: The C XOR operator, ^, will not work here because it is
-   * a bitwise operator, not a logical operator.  C does not
-   * have a logical XOR operator, so we use a macro instead.
-   */
-
-  /* Has the key state changed? */
-  dwKeyState = GetKeyState (VK_NUMLOCK) & 0x0001;
-  if (WIN_XOR (internalKeyStates & NumLockMask, dwKeyState))
-    {
-      winSendKeyEvent (KEY_NumLock, TRUE);
-      winSendKeyEvent (KEY_NumLock, FALSE);
-    }
-
-  /* Has the key state changed? */
-  dwKeyState = GetKeyState (VK_CAPITAL) & 0x0001;
-  if (WIN_XOR (internalKeyStates & LockMask, dwKeyState))
-    {
-      winSendKeyEvent (KEY_CapsLock, TRUE);
-      winSendKeyEvent (KEY_CapsLock, FALSE);
-    }
-
-  /* Has the key state changed? */
-  dwKeyState = GetKeyState (VK_SCROLL) & 0x0001;
-  if (WIN_XOR (internalKeyStates & ScrollLockMask, dwKeyState))
-    {
-      winSendKeyEvent (KEY_ScrollLock, TRUE);
-      winSendKeyEvent (KEY_ScrollLock, FALSE);
-    }
-
-  /* Has the key state changed? */
-  dwKeyState = GetKeyState (VK_KANA) & 0x0001;
-  if (WIN_XOR (internalKeyStates & KanaMask, dwKeyState))
-    {
-      winSendKeyEvent (KEY_HKTG, TRUE);
-      winSendKeyEvent (KEY_HKTG, FALSE);
-    }
-}
-
-
-/*
- * Look for the lovely fake Control_L press/release generated by Windows
- * when AltGr is pressed/released on a non-U.S. keyboard.
- */
-
-Bool
-winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam)
-{
-  MSG		msgNext;
-  LONG		lTime;
-  Bool		fReturn;
-
-  /*
-   * Fake Ctrl_L presses will be followed by an Alt_R keypress
-   * with the same timestamp as the Ctrl_L press.
-   */
-  if ((message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
-      && wParam == VK_CONTROL
-      && (HIWORD (lParam) & KF_EXTENDED) == 0)
-    {
-      /* Got a Ctrl_L press */
-
-      /* Get time of current message */
-      lTime = GetMessageTime ();
-
-      /* Look for fake Ctrl_L preceeding an Alt_R press. */
-      fReturn = PeekMessage (&msgNext, NULL,
-			     WM_KEYDOWN, WM_SYSKEYDOWN,
-			     PM_NOREMOVE);
-
-      /*
-       * Try again if the first call fails.
-       * NOTE: This usually happens when TweakUI is enabled.
-       */
-      if (!fReturn)
-	{
-	  /* Voodoo to make sure that the Alt_R message has posted */
-	  Sleep (0);
-
-	  /* Look for fake Ctrl_L preceeding an Alt_R press. */
-	  fReturn = PeekMessage (&msgNext, NULL,
-				 WM_KEYDOWN, WM_SYSKEYDOWN,
-				 PM_NOREMOVE);
-	}
-      if (msgNext.message != WM_KEYDOWN && msgNext.message != WM_SYSKEYDOWN)
-          fReturn = 0;
-
-      /* Is next press an Alt_R with the same timestamp? */
-      if (fReturn && msgNext.wParam == VK_MENU
-	  && msgNext.time == lTime
-	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
-	{
-	  /* 
-	   * Next key press is Alt_R with same timestamp as current
-	   * Ctrl_L message.  Therefore, this Ctrl_L press is a fake
-	   * event, so discard it.
-	   */
-	  return TRUE;
-	}
-    }
-
-  /* 
-   * Fake Ctrl_L releases will be followed by an Alt_R release
-   * with the same timestamp as the Ctrl_L release.
-   */
-  if ((message == WM_KEYUP || message == WM_SYSKEYUP)
-      && wParam == VK_CONTROL
-      && (HIWORD (lParam) & KF_EXTENDED) == 0)
-    {
-      /* Got a Ctrl_L release */
-
-      /* Get time of current message */
-      lTime = GetMessageTime ();
-
-      /* Look for fake Ctrl_L release preceeding an Alt_R release. */
-      fReturn = PeekMessage (&msgNext, NULL,
-			     WM_KEYUP, WM_SYSKEYUP, 
-			     PM_NOREMOVE);
-
-      /*
-       * Try again if the first call fails.
-       * NOTE: This usually happens when TweakUI is enabled.
-       */
-      if (!fReturn)
-	{
-	  /* Voodoo to make sure that the Alt_R message has posted */
-	  Sleep (0);
-
-	  /* Look for fake Ctrl_L release preceeding an Alt_R release. */
-	  fReturn = PeekMessage (&msgNext, NULL,
-				 WM_KEYUP, WM_SYSKEYUP, 
-				 PM_NOREMOVE);
-	}
-
-      if (msgNext.message != WM_KEYUP && msgNext.message != WM_SYSKEYUP)
-          fReturn = 0;
-      
-      /* Is next press an Alt_R with the same timestamp? */
-      if (fReturn
-	  && (msgNext.message == WM_KEYUP
-	      || msgNext.message == WM_SYSKEYUP)
-	  && msgNext.wParam == VK_MENU
-	  && msgNext.time == lTime
-	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
-	{
-	  /*
-	   * Next key release is Alt_R with same timestamp as current
-	   * Ctrl_L message. Therefore, this Ctrl_L release is a fake
-	   * event, so discard it.
-	   */
-	  return TRUE;
-	}
-    }
-  
-  /* Not a fake control left press/release */
-  return FALSE;
-}
-
-
-/*
- * Lift any modifier keys that are pressed
- */
-
-void
-winKeybdReleaseKeys (void)
-{
-  int				i;
-
-#ifdef HAS_DEVWINDOWS
-  /* Verify that the mi input system has been initialized */
-  if (g_fdMessageQueue == WIN_FD_INVALID)
-    return;
-#endif
-
-  /* Loop through all keys */
-  for (i = 0; i < NUM_KEYCODES; ++i)
-    {
-      /* Pop key if pressed */
-      if (g_winKeyState[i])
-	winSendKeyEvent (i, FALSE);
-
-      /* Reset pressed flag for keys */
-      g_winKeyState[i] = FALSE;
-    }
-}
-
-
-/*
- * Take a raw X key code and send an up or down event for it.
- *
- * Thanks to VNC for inspiration, though it is a simple function.
- */
-
-void
-winSendKeyEvent (DWORD dwKey, Bool fDown)
-{
-  EventListPtr events;
-  int i, nevents;
-
-  /*
-   * When alt-tabing between screens we can get phantom key up messages
-   * Here we only pass them through it we think we should!
-   */
-  if (g_winKeyState[dwKey] == FALSE && fDown == FALSE) return;
-
-  /* Update the keyState map */
-  g_winKeyState[dwKey] = fDown;
-
-  GetEventList(&events);
-  nevents = GetKeyboardEvents(events, g_pwinKeyboard, fDown ? KeyPress : KeyRelease, dwKey + MIN_KEYCODE);
-
-  for (i = 0; i < nevents; i++)
-    mieqEnqueue(g_pwinKeyboard, events[i].event);
-
-#if CYGDEBUG
-  ErrorF("winSendKeyEvent: dwKey: %d, fDown: %d, nEvents %d\n",
-          dwKey, fDown, nevents);
-#endif
-}
-
-BOOL winCheckKeyPressed(WPARAM wParam, LPARAM lParam)
-{
-  switch (wParam)
-  {
-    case VK_CONTROL:
-      if ((lParam & 0x1ff0000) == 0x11d0000 && g_winKeyState[KEY_RCtrl])
-        return TRUE;
-      if ((lParam & 0x1ff0000) == 0x01d0000 && g_winKeyState[KEY_LCtrl])
-        return TRUE;
-      break;
-    case VK_SHIFT:
-      if ((lParam & 0x1ff0000) == 0x0360000 && g_winKeyState[KEY_ShiftR])
-        return TRUE;
-      if ((lParam & 0x1ff0000) == 0x02a0000 && g_winKeyState[KEY_ShiftL])
-        return TRUE;
-      break;
-    default:
-      return TRUE;
-  }
-  return FALSE;
-}
-
-/* Only on shift release message is sent even if both are pressed.
- * Fix this here 
- */
-void winFixShiftKeys (int iScanCode)
-{
-  if (GetKeyState (VK_SHIFT) & 0x8000)
-    return;
-
-  if (iScanCode == KEY_ShiftL && g_winKeyState[KEY_ShiftR])
-    winSendKeyEvent (KEY_ShiftR, FALSE);
-  if (iScanCode == KEY_ShiftR && g_winKeyState[KEY_ShiftL])
-    winSendKeyEvent (KEY_ShiftL, FALSE);
-}
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winkeybd.h"
+#include "winconfig.h"
+#include "winmsg.h"
+
+#include "xkbsrv.h"
+
+static Bool g_winKeyState[NUM_KEYCODES];
+
+/*
+ * Local prototypes
+ */
+
+static void
+winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
+	      pointer pCtrl, int iClass);
+
+static void
+winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl);
+
+
+/* 
+ * Translate a Windows WM_[SYS]KEY(UP/DOWN) message
+ * into an ASCII scan code.
+ *
+ * We do this ourselves, rather than letting Windows handle it,
+ * because Windows tends to munge the handling of special keys,
+ * like AltGr on European keyboards.
+ */
+
+void
+winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode)
+{
+  int		iKeyFixup = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 1];
+  int		iKeyFixupEx = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 2];
+  int		iParam = HIWORD (lParam);
+  int		iParamScanCode = LOBYTE (iParam);
+
+/* WM_ key messages faked by Vista speech recognition (WSR) don't have a
+ * scan code.
+ *
+ * Vocola 3 (Rick Mohr's supplement to WSR) uses
+ * System.Windows.Forms.SendKeys.SendWait(), which appears always to give a
+ * scan code of 1
+ */
+  if (iParamScanCode <= 1)
+    {
+      if (VK_PRIOR <= wParam && wParam <= VK_DOWN)
+        /* Trigger special case table to translate to extended
+         * keycode, otherwise if num_lock is on, we can get keypad
+         * numbers instead of navigation keys. */
+        iParam |= KF_EXTENDED;
+      else
+        iParamScanCode = MapVirtualKeyEx(wParam,
+                         /*MAPVK_VK_TO_VSC*/0,
+                         GetKeyboardLayout(0));
+    }
+
+  /* Branch on special extended, special non-extended, or normal key */
+  if ((iParam & KF_EXTENDED) && iKeyFixupEx)
+    *piScanCode = iKeyFixupEx;
+  else if (iKeyFixup)
+    *piScanCode = iKeyFixup;
+  else if (wParam == 0 && iParamScanCode == 0x70)
+    *piScanCode = KEY_HKTG;
+  else
+    switch (iParamScanCode)
+    {
+      case 0x70:
+        *piScanCode = KEY_HKTG;
+        break;
+      case 0x73:
+        *piScanCode = KEY_BSlash2;
+        break;
+      default: 
+        *piScanCode = iParamScanCode;
+        break;
+    }
+}
+
+
+/* Ring the keyboard bell (system speaker on PCs) */
+static void
+winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
+	      pointer pCtrl, int iClass)
+{
+  /*
+   * We can't use Beep () here because it uses the PC speaker
+   * on NT/2000.  MessageBeep (MB_OK) will play the default system
+   * sound on systems with a sound card or it will beep the PC speaker
+   * on systems that do not have a sound card.
+   */
+  MessageBeep (MB_OK);
+}
+
+
+/* Change some keyboard configuration parameters */
+static void
+winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl)
+{
+}
+
+
+/* 
+ * See Porting Layer Definition - p. 18
+ * winKeybdProc is known as a DeviceProc.
+ */
+
+int
+winKeybdProc (DeviceIntPtr pDeviceInt, int iState)
+{
+  DevicePtr		pDevice = (DevicePtr) pDeviceInt;
+  XkbSrvInfoPtr       xkbi;
+  XkbControlsPtr      ctrl;
+
+  switch (iState)
+    {
+    case DEVICE_INIT:
+      winConfigKeyboard (pDeviceInt);
+
+      /* FIXME: Maybe we should use winGetKbdLeds () here? */
+      defaultKeyboardControl.leds = g_winInfo.keyboard.leds;
+
+      winErrorFVerb(2, "Rules = \"%s\" Model = \"%s\" Layout = \"%s\""
+                    " Variant = \"%s\" Options = \"%s\"\n",
+                    g_winInfo.xkb.rules ? g_winInfo.xkb.rules : "none",
+                    g_winInfo.xkb.model ? g_winInfo.xkb.model : "none",
+                    g_winInfo.xkb.layout ? g_winInfo.xkb.layout : "none",
+                    g_winInfo.xkb.variant ? g_winInfo.xkb.variant : "none",
+                    g_winInfo.xkb.options ? g_winInfo.xkb.options : "none");
+
+      InitKeyboardDeviceStruct (pDeviceInt,
+                                &g_winInfo.xkb,
+                                winKeybdBell,
+                                winKeybdCtrl);
+
+      xkbi = pDeviceInt->key->xkbInfo;
+      if ((xkbi != NULL) && (xkbi->desc != NULL))
+        {
+          ctrl = xkbi->desc->ctrls;
+          ctrl->repeat_delay = g_winInfo.keyboard.delay;
+          ctrl->repeat_interval = 1000/g_winInfo.keyboard.rate;
+        }
+      else
+        {
+          winErrorFVerb (1, "winKeybdProc - Error initializing keyboard AutoRepeat\n");
+        }
+
+      break;
+      
+    case DEVICE_ON: 
+      pDevice->on = TRUE;
+
+      // immediately copy the state of this keyboard device to the VCK
+      // (which otherwise happens lazily after the first keypress)
+      CopyKeyClass(pDeviceInt, inputInfo.keyboard);
+      break;
+
+    case DEVICE_CLOSE:
+    case DEVICE_OFF: 
+      pDevice->on = FALSE;
+      break;
+    }
+
+  return Success;
+}
+
+
+/*
+ * Detect current mode key states upon server startup.
+ *
+ * Simulate a press and release of any key that is currently
+ * toggled.
+ */
+
+void
+winInitializeModeKeyStates (void)
+{
+  /* Restore NumLock */
+  if (GetKeyState (VK_NUMLOCK) & 0x0001)
+    {
+      winSendKeyEvent (KEY_NumLock, TRUE);
+      winSendKeyEvent (KEY_NumLock, FALSE);
+    }
+
+  /* Restore CapsLock */
+  if (GetKeyState (VK_CAPITAL) & 0x0001)
+    {
+      winSendKeyEvent (KEY_CapsLock, TRUE);
+      winSendKeyEvent (KEY_CapsLock, FALSE);
+    }
+
+  /* Restore ScrollLock */
+  if (GetKeyState (VK_SCROLL) & 0x0001)
+    {
+      winSendKeyEvent (KEY_ScrollLock, TRUE);
+      winSendKeyEvent (KEY_ScrollLock, FALSE);
+    }
+
+  /* Restore KanaLock */
+  if (GetKeyState (VK_KANA) & 0x0001)
+    {
+      winSendKeyEvent (KEY_HKTG, TRUE);
+      winSendKeyEvent (KEY_HKTG, FALSE);
+    }
+}
+
+
+/*
+ * Upon regaining the keyboard focus we must
+ * resynchronize our internal mode key states
+ * with the actual state of the keys.
+ */
+
+void
+winRestoreModeKeyStates (void)
+{
+  DWORD			dwKeyState;
+  BOOL			processEvents = TRUE;
+  unsigned short	internalKeyStates;
+
+  /* X server is being initialized */
+  if (!inputInfo.keyboard)
+    return;
+
+  /* Only process events if the rootwindow is mapped. The keyboard events
+   * will cause segfaults otherwise */
+  if (WindowTable && WindowTable[0] && WindowTable[0]->mapped == FALSE)
+    processEvents = FALSE;    
+  
+  /* Force to process all pending events in the mi event queue */
+  if (processEvents)
+    mieqProcessInputEvents ();
+  
+  /* Read the mode key states of our X server */
+  /* (stored in the virtual core keyboard) */
+  internalKeyStates = XkbStateFieldFromRec(&inputInfo.keyboard->key->xkbInfo->state);
+  winDebug("winRestoreModeKeyStates: state %d\n", internalKeyStates);
+
+  /* 
+   * NOTE: The C XOR operator, ^, will not work here because it is
+   * a bitwise operator, not a logical operator.  C does not
+   * have a logical XOR operator, so we use a macro instead.
+   */
+
+  /* Has the key state changed? */
+  dwKeyState = GetKeyState (VK_NUMLOCK) & 0x0001;
+  if (WIN_XOR (internalKeyStates & NumLockMask, dwKeyState))
+    {
+      winSendKeyEvent (KEY_NumLock, TRUE);
+      winSendKeyEvent (KEY_NumLock, FALSE);
+    }
+
+  /* Has the key state changed? */
+  dwKeyState = GetKeyState (VK_CAPITAL) & 0x0001;
+  if (WIN_XOR (internalKeyStates & LockMask, dwKeyState))
+    {
+      winSendKeyEvent (KEY_CapsLock, TRUE);
+      winSendKeyEvent (KEY_CapsLock, FALSE);
+    }
+
+  /* Has the key state changed? */
+  dwKeyState = GetKeyState (VK_SCROLL) & 0x0001;
+  if (WIN_XOR (internalKeyStates & ScrollLockMask, dwKeyState))
+    {
+      winSendKeyEvent (KEY_ScrollLock, TRUE);
+      winSendKeyEvent (KEY_ScrollLock, FALSE);
+    }
+
+  /* Has the key state changed? */
+  dwKeyState = GetKeyState (VK_KANA) & 0x0001;
+  if (WIN_XOR (internalKeyStates & KanaMask, dwKeyState))
+    {
+      winSendKeyEvent (KEY_HKTG, TRUE);
+      winSendKeyEvent (KEY_HKTG, FALSE);
+    }
+}
+
+
+/*
+ * Look for the lovely fake Control_L press/release generated by Windows
+ * when AltGr is pressed/released on a non-U.S. keyboard.
+ */
+
+Bool
+winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam)
+{
+  MSG		msgNext;
+  LONG		lTime;
+  Bool		fReturn;
+
+  /*
+   * Fake Ctrl_L presses will be followed by an Alt_R keypress
+   * with the same timestamp as the Ctrl_L press.
+   */
+  if ((message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
+      && wParam == VK_CONTROL
+      && (HIWORD (lParam) & KF_EXTENDED) == 0)
+    {
+      /* Got a Ctrl_L press */
+
+      /* Get time of current message */
+      lTime = GetMessageTime ();
+
+      /* Look for fake Ctrl_L preceeding an Alt_R press. */
+      fReturn = PeekMessage (&msgNext, NULL,
+			     WM_KEYDOWN, WM_SYSKEYDOWN,
+			     PM_NOREMOVE);
+
+      /*
+       * Try again if the first call fails.
+       * NOTE: This usually happens when TweakUI is enabled.
+       */
+      if (!fReturn)
+	{
+	  /* Voodoo to make sure that the Alt_R message has posted */
+	  Sleep (0);
+
+	  /* Look for fake Ctrl_L preceeding an Alt_R press. */
+	  fReturn = PeekMessage (&msgNext, NULL,
+				 WM_KEYDOWN, WM_SYSKEYDOWN,
+				 PM_NOREMOVE);
+	}
+      if (msgNext.message != WM_KEYDOWN && msgNext.message != WM_SYSKEYDOWN)
+          fReturn = 0;
+
+      /* Is next press an Alt_R with the same timestamp? */
+      if (fReturn && msgNext.wParam == VK_MENU
+	  && msgNext.time == lTime
+	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
+	{
+	  /* 
+	   * Next key press is Alt_R with same timestamp as current
+	   * Ctrl_L message.  Therefore, this Ctrl_L press is a fake
+	   * event, so discard it.
+	   */
+	  return TRUE;
+	}
+    }
+
+  /* 
+   * Fake Ctrl_L releases will be followed by an Alt_R release
+   * with the same timestamp as the Ctrl_L release.
+   */
+  if ((message == WM_KEYUP || message == WM_SYSKEYUP)
+      && wParam == VK_CONTROL
+      && (HIWORD (lParam) & KF_EXTENDED) == 0)
+    {
+      /* Got a Ctrl_L release */
+
+      /* Get time of current message */
+      lTime = GetMessageTime ();
+
+      /* Look for fake Ctrl_L release preceeding an Alt_R release. */
+      fReturn = PeekMessage (&msgNext, NULL,
+			     WM_KEYUP, WM_SYSKEYUP, 
+			     PM_NOREMOVE);
+
+      /*
+       * Try again if the first call fails.
+       * NOTE: This usually happens when TweakUI is enabled.
+       */
+      if (!fReturn)
+	{
+	  /* Voodoo to make sure that the Alt_R message has posted */
+	  Sleep (0);
+
+	  /* Look for fake Ctrl_L release preceeding an Alt_R release. */
+	  fReturn = PeekMessage (&msgNext, NULL,
+				 WM_KEYUP, WM_SYSKEYUP, 
+				 PM_NOREMOVE);
+	}
+
+      if (msgNext.message != WM_KEYUP && msgNext.message != WM_SYSKEYUP)
+          fReturn = 0;
+      
+      /* Is next press an Alt_R with the same timestamp? */
+      if (fReturn
+	  && (msgNext.message == WM_KEYUP
+	      || msgNext.message == WM_SYSKEYUP)
+	  && msgNext.wParam == VK_MENU
+	  && msgNext.time == lTime
+	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
+	{
+	  /*
+	   * Next key release is Alt_R with same timestamp as current
+	   * Ctrl_L message. Therefore, this Ctrl_L release is a fake
+	   * event, so discard it.
+	   */
+	  return TRUE;
+	}
+    }
+  
+  /* Not a fake control left press/release */
+  return FALSE;
+}
+
+
+/*
+ * Lift any modifier keys that are pressed
+ */
+
+void
+winKeybdReleaseKeys (void)
+{
+  int				i;
+
+#ifdef HAS_DEVWINDOWS
+  /* Verify that the mi input system has been initialized */
+  if (g_fdMessageQueue == WIN_FD_INVALID)
+    return;
+#endif
+
+  /* Loop through all keys */
+  for (i = 0; i < NUM_KEYCODES; ++i)
+    {
+      /* Pop key if pressed */
+      if (g_winKeyState[i])
+	winSendKeyEvent (i, FALSE);
+
+      /* Reset pressed flag for keys */
+      g_winKeyState[i] = FALSE;
+    }
+}
+
+
+/*
+ * Take a raw X key code and send an up or down event for it.
+ *
+ * Thanks to VNC for inspiration, though it is a simple function.
+ */
+
+void
+winSendKeyEvent (DWORD dwKey, Bool fDown)
+{
+  EventListPtr events;
+  int i, nevents;
+
+  /*
+   * When alt-tabing between screens we can get phantom key up messages
+   * Here we only pass them through it we think we should!
+   */
+  if (g_winKeyState[dwKey] == FALSE && fDown == FALSE) return;
+
+  /* Update the keyState map */
+  g_winKeyState[dwKey] = fDown;
+
+  GetEventList(&events);
+  nevents = GetKeyboardEvents(events, g_pwinKeyboard, fDown ? KeyPress : KeyRelease, dwKey + MIN_KEYCODE);
+
+  for (i = 0; i < nevents; i++)
+    mieqEnqueue(g_pwinKeyboard, (InternalEvent*)events[i].event);
+
+#if CYGDEBUG
+  ErrorF("winSendKeyEvent: dwKey: %d, fDown: %d, nEvents %d\n",
+          dwKey, fDown, nevents);
+#endif
+}
+
+BOOL winCheckKeyPressed(WPARAM wParam, LPARAM lParam)
+{
+  switch (wParam)
+  {
+    case VK_CONTROL:
+      if ((lParam & 0x1ff0000) == 0x11d0000 && g_winKeyState[KEY_RCtrl])
+        return TRUE;
+      if ((lParam & 0x1ff0000) == 0x01d0000 && g_winKeyState[KEY_LCtrl])
+        return TRUE;
+      break;
+    case VK_SHIFT:
+      if ((lParam & 0x1ff0000) == 0x0360000 && g_winKeyState[KEY_ShiftR])
+        return TRUE;
+      if ((lParam & 0x1ff0000) == 0x02a0000 && g_winKeyState[KEY_ShiftL])
+        return TRUE;
+      break;
+    default:
+      return TRUE;
+  }
+  return FALSE;
+}
+
+/* Only on shift release message is sent even if both are pressed.
+ * Fix this here 
+ */
+void winFixShiftKeys (int iScanCode)
+{
+  if (GetKeyState (VK_SHIFT) & 0x8000)
+    return;
+
+  if (iScanCode == KEY_ShiftL && g_winKeyState[KEY_ShiftR])
+    winSendKeyEvent (KEY_ShiftR, FALSE);
+  if (iScanCode == KEY_ShiftR && g_winKeyState[KEY_ShiftL])
+    winSendKeyEvent (KEY_ShiftL, FALSE);
+}
diff --git a/xorg-server/hw/xwin/winkeybd.h b/xorg-server/hw/xwin/winkeybd.h
index d0d6b9cad..fc5e6b53a 100644
--- a/xorg-server/hw/xwin/winkeybd.h
+++ b/xorg-server/hw/xwin/winkeybd.h
@@ -1,312 +1,304 @@
-#if !defined(WINKEYBD_H)
-#define WINKEYBD_H
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Harold L Hunt II
- */
-
-/*
- * We need symbols for the scan codes of keys.
- */
-#include "winkeynames.h"
-
-
-/*
- * Include the standard ASCII keymap.
- *
- * This header declares a static KeySym array called 'map'.
- */
-#include "winkeymap.h"
-
-#define		WIN_KEYMAP_COLS		3
-
-/* Rows 160 through 165 correspond to software-generated codes, which
- * may not be associated with the appropriate scan code.
- */
-const int
-g_iKeyMap [] = {
-  /* count	Windows VK,	ASCII,		ASCII when extended VK */
-  /* 0 */	0,		0,		0,
-  /* 1 */	0,		0,		0,
-  /* 2 */	0,		0,		0,
-  /* 3 */	VK_CANCEL,	0,		KEY_Break,
-  /* 4 */	0,		0,		0,
-  /* 5 */	0,		0,		0,
-  /* 6 */	0,		0,		0,
-  /* 7 */	0,		0,		0,
-  /* 8 */	0,		0,		0,
-  /* 9 */	0,		0,		0,
-  /* 10 */	0,		0,		0,
-  /* 11 */	0,		0,		0,
-  /* 12 */	0,		0,		0,
-  /* 13 */	VK_RETURN,	0,		KEY_KP_Enter,
-  /* 14 */	0,		0,		0,
-  /* 15 */	0,		0,		0,
-  /* 16 */	VK_SHIFT,	0,		0,
-  /* 17 */	VK_CONTROL,	0,		KEY_RCtrl,
-  /* 18 */	VK_MENU,	0,		KEY_AltLang,
-  /* 19 */	VK_PAUSE,	KEY_Pause,	0,
-  /* 20 */	0,		0,		0,
-  /* 21 */	0,		0,		0,
-  /* 22 */	0,		0,		0,
-  /* 23 */	0,		0,		0,
-  /* 24 */	0,		0,		0,
-  /* 25 */	0,		0,		0,
-  /* 26 */	0,		0,		0,
-  /* 27 */	0,		0,		0,
-  /* 28 */	0,		0,		0,
-  /* 29 */	0,		0,		0,
-  /* 30 */	0,		0,		0,
-  /* 31 */	0,		0,		0,
-  /* 32 */	0,		0,		0,
-  /* 33 */	VK_PRIOR,	0,		KEY_PgUp,
-  /* 34 */	VK_NEXT,	0,		KEY_PgDown,
-  /* 35 */	VK_END,		0,		KEY_End,
-  /* 36 */	VK_HOME,	0,		KEY_Home,
-  /* 37 */	VK_LEFT,	0,		KEY_Left,
-  /* 38 */	VK_UP,		0,		KEY_Up,
-  /* 39 */	VK_RIGHT,	0,		KEY_Right,
-  /* 40 */	VK_DOWN,	0,		KEY_Down,
-  /* 41 */	0,		0,		0,
-  /* 42 */	0,		0,		0,
-  /* 43 */	0,		0,		0,
-  /* 44 */	VK_SNAPSHOT,	0,		KEY_Print,  
-  /* 45 */	VK_INSERT,	0,		KEY_Insert,
-  /* 46 */	VK_DELETE,	0,		KEY_Delete,
-  /* 47 */	0,		0,		0,
-  /* 48 */	0,		0,		0,
-  /* 49 */	0,		0,		0,
-  /* 50 */	0,		0,		0,
-  /* 51 */	0,		0,		0,
-  /* 52 */	0,		0,		0,
-  /* 53 */	0,		0,		0,
-  /* 54 */	0,		0,		0,
-  /* 55 */	0,		0,		0,
-  /* 56 */	0,		0,		0,
-  /* 57 */	0,		0,		0,
-  /* 58 */	0,		0,		0,
-  /* 59 */	0,		0,		0,
-  /* 60 */	0,		0,		0,
-  /* 61 */	0,		0,		0,
-  /* 62 */	0,		0,		0,
-  /* 63 */	0,		0,		0,
-  /* 64 */	0,		0,		0,
-  /* 65 */	0,		0,		0,
-  /* 66 */	0,		0,		0,
-  /* 67 */	0,		0,		0,
-  /* 68 */	0,		0,		0,
-  /* 69 */	0,		0,		0,
-  /* 70 */	0,		0,		0,
-  /* 71 */	0,		0,		0,
-  /* 72 */	0,		0,		0,
-  /* 73 */	0,		0,		0,
-  /* 74 */	0,		0,		0,
-  /* 75 */	0,		0,		0,
-  /* 76 */	0,		0,		0,
-  /* 77 */	0,		0,		0,
-  /* 78 */	0,		0,		0,
-  /* 79 */	0,		0,		0,
-  /* 80 */	0,		0,		0,
-  /* 81 */	0,		0,		0,
-  /* 82 */	0,		0,		0,
-  /* 83 */	0,		0,		0,
-  /* 84 */	0,		0,		0,
-  /* 85 */	0,		0,		0,
-  /* 86 */	0,		0,		0,
-  /* 87 */	0,		0,		0,
-  /* 88 */	0,		0,		0,
-  /* 89 */	0,		0,		0,
-  /* 90 */	0,		0,		0,
-  /* 91 */	VK_LWIN,	KEY_LMeta,	0,
-  /* 92 */	VK_RWIN,	KEY_RMeta,	0,
-  /* 93 */	VK_APPS,	KEY_Menu,	0,
-  /* 94 */	0,		0,		0,
-  /* 95 */	0,		0,		0,
-  /* 96 */	0,		0,		0,
-  /* 97 */	0,		0,		0,
-  /* 98 */	0,		0,		0,
-  /* 99 */	0,		0,		0,
-  /* 100 */	0,		0,		0,
-  /* 101 */	0,		0,		0,
-  /* 102 */	0,		0,		0,
-  /* 103 */	0,		0,		0,
-  /* 104 */	0,		0,		0,
-  /* 105 */	0,		0,		0,
-  /* 106 */	0,		0,		0,
-  /* 107 */	0,		0,		0,
-  /* 108 */	0,		0,		0,
-  /* 109 */	0,		0,		0,
-  /* 110 */	0,		0,		0,
-  /* 111 */	VK_DIVIDE,	0,		KEY_KP_Divide,
-  /* 112 */	0,		0,		0,
-  /* 113 */	0,		0,		0,
-  /* 114 */	0,		0,		0,
-  /* 115 */	0,		0,		0,
-  /* 116 */	0,		0,		0,
-  /* 117 */	0,		0,		0,
-  /* 118 */	0,		0,		0,
-  /* 119 */	0,		0,		0,
-  /* 120 */	0,		0,		0,
-  /* 121 */	0,		0,		0,
-  /* 122 */	0,		0,		0,
-  /* 123 */	0,		0,		0,
-  /* 124 */	0,		0,		0,
-  /* 125 */	0,		0,		0,
-  /* 126 */	0,		0,		0,
-  /* 127 */	0,		0,		0,
-  /* 128 */	0,		0,		0,
-  /* 129 */	0,		0,		0,
-  /* 130 */	0,		0,		0,
-  /* 131 */	0,		0,		0,
-  /* 132 */	0,		0,		0,
-  /* 133 */	0,		0,		0,
-  /* 134 */	0,		0,		0,
-  /* 135 */	0,		0,		0,
-  /* 136 */	0,		0,		0,
-  /* 137 */	0,		0,		0,
-  /* 138 */	0,		0,		0,
-  /* 139 */	0,		0,		0,
-  /* 140 */	0,		0,		0,
-  /* 141 */	0,		0,		0,
-  /* 142 */	0,		0,		0,
-  /* 143 */	0,		0,		0,
-  /* 144 */	0,		0,		0,
-  /* 145 */	0,		0,		0,
-  /* 146 */	0,		0,		0,
-  /* 147 */	0,		0,		0,
-  /* 148 */	0,		0,		0,
-  /* 149 */	0,		0,		0,
-  /* 150 */	0,		0,		0,
-  /* 151 */	0,		0,		0,
-  /* 152 */	0,		0,		0,
-  /* 153 */	0,		0,		0,
-  /* 154 */	0,		0,		0,
-  /* 155 */	0,		0,		0,
-  /* 156 */	0,		0,		0,
-  /* 157 */	0,		0,		0,
-  /* 158 */	0,		0,		0,
-  /* 159 */	0,		0,		0,
-  /* 160 */	VK_LSHIFT,	KEY_ShiftL,	0,
-  /* 161 */	VK_RSHIFT,	KEY_ShiftR,	0,
-  /* 162 */	VK_LCONTROL,	KEY_LCtrl,	0,
-  /* 163 */	VK_RCONTROL,	KEY_RCtrl,	0,
-  /* 164 */	VK_LMENU,	KEY_Alt,	0,
-  /* 165 */	VK_RMENU,	KEY_AltLang,	0,
-  /* 166 */	0,		0,		0,
-  /* 167 */	0,		0,		0,
-  /* 168 */	0,		0,		0,
-  /* 169 */	0,		0,		0,
-  /* 170 */	0,		0,		0,
-  /* 171 */	0,		0,		0,
-  /* 172 */	0,		0,		0,
-  /* 173 */	0,		0,		0,
-  /* 174 */	0,		0,		0,
-  /* 175 */	0,		0,		0,
-  /* 176 */	0,		0,		0,
-  /* 177 */	0,		0,		0,
-  /* 178 */	0,		0,		0,
-  /* 179 */	0,		0,		0,
-  /* 180 */	0,		0,		0,
-  /* 181 */	0,		0,		0,
-  /* 182 */	0,		0,		0,
-  /* 183 */	0,		0,		0,
-  /* 184 */	0,		0,		0,
-  /* 185 */	0,		0,		0,
-  /* 186 */	0,		0,		0,
-  /* 187 */	0,		0,		0,
-  /* 188 */	0,		0,		0,
-  /* 189 */	0,		0,		0,
-  /* 190 */	0,		0,		0,
-  /* 191 */	0,		0,		0,
-  /* 192 */	0,		0,		0,
-  /* 193 */	0,		0,		0,
-  /* 194 */	0,		0,		0,
-  /* 195 */	0,		0,		0,
-  /* 196 */	0,		0,		0,
-  /* 197 */	0,		0,		0,
-  /* 198 */	0,		0,		0,
-  /* 199 */	0,		0,		0,
-  /* 200 */	0,		0,		0,
-  /* 201 */	0,		0,		0,
-  /* 202 */	0,		0,		0,
-  /* 203 */	0,		0,		0,
-  /* 204 */	0,		0,		0,
-  /* 205 */	0,		0,		0,
-  /* 206 */	0,		0,		0,
-  /* 207 */	0,		0,		0,
-  /* 208 */	0,		0,		0,
-  /* 209 */	0,		0,		0,
-  /* 210 */	0,		0,		0,
-  /* 211 */	0,		0,		0,
-  /* 212 */	0,		0,		0,
-  /* 213 */	0,		0,		0,
-  /* 214 */	0,		0,		0,
-  /* 215 */	0,		0,		0,
-  /* 216 */	0,		0,		0,
-  /* 217 */	0,		0,		0,
-  /* 218 */	0,		0,		0,
-  /* 219 */	0,		0,		0,
-  /* 220 */	0,		0,		0,
-  /* 221 */	0,		0,		0,
-  /* 222 */	0,		0,		0,
-  /* 223 */	0,		0,		0,
-  /* 224 */	0,		0,		0,
-  /* 225 */	0,		0,		0,
-  /* 226 */	0,		0,		0,
-  /* 227 */	0,		0,		0,
-  /* 228 */	0,		0,		0,
-  /* 229 */	0,		0,		0,
-  /* 230 */	0,		0,		0,
-  /* 231 */	0,		0,		0,
-  /* 232 */	0,		0,		0,
-  /* 233 */	0,		0,		0,
-  /* 234 */	0,		0,		0,
-  /* 235 */	0,		0,		0,
-  /* 236 */	0,		0,		0,
-  /* 237 */	0,		0,		0,
-  /* 238 */	0,		0,		0,
-  /* 239 */	0,		0,		0,
-  /* 240 */	0,		0,		0,
-  /* 241 */	0,		0,		0,
-  /* 242 */	0,		0,		0,
-  /* 243 */	0,		0,		0,
-  /* 244 */	0,		0,		0,
-  /* 245 */	0,		0,		0,
-  /* 246 */	0,		0,		0,
-  /* 247 */	0,		0,		0,
-  /* 248 */	0,		0,		0,
-  /* 249 */	0,		0,		0,
-  /* 250 */	0,		0,		0,
-  /* 251 */	0,		0,		0,
-  /* 252 */	0,		0,		0,
-  /* 253 */	0,		0,		0,
-  /* 254 */	0,		0,		0,
-  /* 255 */	0,		0,		0
-};
-
-#endif /* WINKEYBD_H */
+#if !defined(WINKEYBD_H)
+#define WINKEYBD_H
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+/*
+ * We need symbols for the scan codes of keys.
+ */
+#include "winkeynames.h"
+
+#define		WIN_KEYMAP_COLS		3
+
+/* Rows 160 through 165 correspond to software-generated codes, which
+ * may not be associated with the appropriate scan code.
+ */
+const int
+g_iKeyMap [] = {
+  /* count	Windows VK,	ASCII,		ASCII when extended VK */
+  /* 0 */	0,		0,		0,
+  /* 1 */	0,		0,		0,
+  /* 2 */	0,		0,		0,
+  /* 3 */	VK_CANCEL,	0,		KEY_Break,
+  /* 4 */	0,		0,		0,
+  /* 5 */	0,		0,		0,
+  /* 6 */	0,		0,		0,
+  /* 7 */	0,		0,		0,
+  /* 8 */	0,		0,		0,
+  /* 9 */	0,		0,		0,
+  /* 10 */	0,		0,		0,
+  /* 11 */	0,		0,		0,
+  /* 12 */	0,		0,		0,
+  /* 13 */	VK_RETURN,	0,		KEY_KP_Enter,
+  /* 14 */	0,		0,		0,
+  /* 15 */	0,		0,		0,
+  /* 16 */	VK_SHIFT,	0,		0,
+  /* 17 */	VK_CONTROL,	0,		KEY_RCtrl,
+  /* 18 */	VK_MENU,	0,		KEY_AltLang,
+  /* 19 */	VK_PAUSE,	KEY_Pause,	0,
+  /* 20 */	0,		0,		0,
+  /* 21 */	0,		0,		0,
+  /* 22 */	0,		0,		0,
+  /* 23 */	0,		0,		0,
+  /* 24 */	0,		0,		0,
+  /* 25 */	0,		0,		0,
+  /* 26 */	0,		0,		0,
+  /* 27 */	0,		0,		0,
+  /* 28 */	0,		0,		0,
+  /* 29 */	0,		0,		0,
+  /* 30 */	0,		0,		0,
+  /* 31 */	0,		0,		0,
+  /* 32 */	0,		0,		0,
+  /* 33 */	VK_PRIOR,	0,		KEY_PgUp,
+  /* 34 */	VK_NEXT,	0,		KEY_PgDown,
+  /* 35 */	VK_END,		0,		KEY_End,
+  /* 36 */	VK_HOME,	0,		KEY_Home,
+  /* 37 */	VK_LEFT,	0,		KEY_Left,
+  /* 38 */	VK_UP,		0,		KEY_Up,
+  /* 39 */	VK_RIGHT,	0,		KEY_Right,
+  /* 40 */	VK_DOWN,	0,		KEY_Down,
+  /* 41 */	0,		0,		0,
+  /* 42 */	0,		0,		0,
+  /* 43 */	0,		0,		0,
+  /* 44 */	VK_SNAPSHOT,	0,		KEY_Print,  
+  /* 45 */	VK_INSERT,	0,		KEY_Insert,
+  /* 46 */	VK_DELETE,	0,		KEY_Delete,
+  /* 47 */	0,		0,		0,
+  /* 48 */	0,		0,		0,
+  /* 49 */	0,		0,		0,
+  /* 50 */	0,		0,		0,
+  /* 51 */	0,		0,		0,
+  /* 52 */	0,		0,		0,
+  /* 53 */	0,		0,		0,
+  /* 54 */	0,		0,		0,
+  /* 55 */	0,		0,		0,
+  /* 56 */	0,		0,		0,
+  /* 57 */	0,		0,		0,
+  /* 58 */	0,		0,		0,
+  /* 59 */	0,		0,		0,
+  /* 60 */	0,		0,		0,
+  /* 61 */	0,		0,		0,
+  /* 62 */	0,		0,		0,
+  /* 63 */	0,		0,		0,
+  /* 64 */	0,		0,		0,
+  /* 65 */	0,		0,		0,
+  /* 66 */	0,		0,		0,
+  /* 67 */	0,		0,		0,
+  /* 68 */	0,		0,		0,
+  /* 69 */	0,		0,		0,
+  /* 70 */	0,		0,		0,
+  /* 71 */	0,		0,		0,
+  /* 72 */	0,		0,		0,
+  /* 73 */	0,		0,		0,
+  /* 74 */	0,		0,		0,
+  /* 75 */	0,		0,		0,
+  /* 76 */	0,		0,		0,
+  /* 77 */	0,		0,		0,
+  /* 78 */	0,		0,		0,
+  /* 79 */	0,		0,		0,
+  /* 80 */	0,		0,		0,
+  /* 81 */	0,		0,		0,
+  /* 82 */	0,		0,		0,
+  /* 83 */	0,		0,		0,
+  /* 84 */	0,		0,		0,
+  /* 85 */	0,		0,		0,
+  /* 86 */	0,		0,		0,
+  /* 87 */	0,		0,		0,
+  /* 88 */	0,		0,		0,
+  /* 89 */	0,		0,		0,
+  /* 90 */	0,		0,		0,
+  /* 91 */	VK_LWIN,	KEY_LMeta,	0,
+  /* 92 */	VK_RWIN,	KEY_RMeta,	0,
+  /* 93 */	VK_APPS,	KEY_Menu,	0,
+  /* 94 */	0,		0,		0,
+  /* 95 */	0,		0,		0,
+  /* 96 */	0,		0,		0,
+  /* 97 */	0,		0,		0,
+  /* 98 */	0,		0,		0,
+  /* 99 */	0,		0,		0,
+  /* 100 */	0,		0,		0,
+  /* 101 */	0,		0,		0,
+  /* 102 */	0,		0,		0,
+  /* 103 */	0,		0,		0,
+  /* 104 */	0,		0,		0,
+  /* 105 */	0,		0,		0,
+  /* 106 */	0,		0,		0,
+  /* 107 */	0,		0,		0,
+  /* 108 */	0,		0,		0,
+  /* 109 */	0,		0,		0,
+  /* 110 */	0,		0,		0,
+  /* 111 */	VK_DIVIDE,	0,		KEY_KP_Divide,
+  /* 112 */	0,		0,		0,
+  /* 113 */	0,		0,		0,
+  /* 114 */	0,		0,		0,
+  /* 115 */	0,		0,		0,
+  /* 116 */	0,		0,		0,
+  /* 117 */	0,		0,		0,
+  /* 118 */	0,		0,		0,
+  /* 119 */	0,		0,		0,
+  /* 120 */	0,		0,		0,
+  /* 121 */	0,		0,		0,
+  /* 122 */	0,		0,		0,
+  /* 123 */	0,		0,		0,
+  /* 124 */	0,		0,		0,
+  /* 125 */	0,		0,		0,
+  /* 126 */	0,		0,		0,
+  /* 127 */	0,		0,		0,
+  /* 128 */	0,		0,		0,
+  /* 129 */	0,		0,		0,
+  /* 130 */	0,		0,		0,
+  /* 131 */	0,		0,		0,
+  /* 132 */	0,		0,		0,
+  /* 133 */	0,		0,		0,
+  /* 134 */	0,		0,		0,
+  /* 135 */	0,		0,		0,
+  /* 136 */	0,		0,		0,
+  /* 137 */	0,		0,		0,
+  /* 138 */	0,		0,		0,
+  /* 139 */	0,		0,		0,
+  /* 140 */	0,		0,		0,
+  /* 141 */	0,		0,		0,
+  /* 142 */	0,		0,		0,
+  /* 143 */	0,		0,		0,
+  /* 144 */	0,		0,		0,
+  /* 145 */	0,		0,		0,
+  /* 146 */	0,		0,		0,
+  /* 147 */	0,		0,		0,
+  /* 148 */	0,		0,		0,
+  /* 149 */	0,		0,		0,
+  /* 150 */	0,		0,		0,
+  /* 151 */	0,		0,		0,
+  /* 152 */	0,		0,		0,
+  /* 153 */	0,		0,		0,
+  /* 154 */	0,		0,		0,
+  /* 155 */	0,		0,		0,
+  /* 156 */	0,		0,		0,
+  /* 157 */	0,		0,		0,
+  /* 158 */	0,		0,		0,
+  /* 159 */	0,		0,		0,
+  /* 160 */	VK_LSHIFT,	KEY_ShiftL,	0,
+  /* 161 */	VK_RSHIFT,	KEY_ShiftR,	0,
+  /* 162 */	VK_LCONTROL,	KEY_LCtrl,	0,
+  /* 163 */	VK_RCONTROL,	KEY_RCtrl,	0,
+  /* 164 */	VK_LMENU,	KEY_Alt,	0,
+  /* 165 */	VK_RMENU,	KEY_AltLang,	0,
+  /* 166 */	0,		0,		0,
+  /* 167 */	0,		0,		0,
+  /* 168 */	0,		0,		0,
+  /* 169 */	0,		0,		0,
+  /* 170 */	0,		0,		0,
+  /* 171 */	0,		0,		0,
+  /* 172 */	0,		0,		0,
+  /* 173 */	0,		0,		0,
+  /* 174 */	0,		0,		0,
+  /* 175 */	0,		0,		0,
+  /* 176 */	0,		0,		0,
+  /* 177 */	0,		0,		0,
+  /* 178 */	0,		0,		0,
+  /* 179 */	0,		0,		0,
+  /* 180 */	0,		0,		0,
+  /* 181 */	0,		0,		0,
+  /* 182 */	0,		0,		0,
+  /* 183 */	0,		0,		0,
+  /* 184 */	0,		0,		0,
+  /* 185 */	0,		0,		0,
+  /* 186 */	0,		0,		0,
+  /* 187 */	0,		0,		0,
+  /* 188 */	0,		0,		0,
+  /* 189 */	0,		0,		0,
+  /* 190 */	0,		0,		0,
+  /* 191 */	0,		0,		0,
+  /* 192 */	0,		0,		0,
+  /* 193 */	0,		0,		0,
+  /* 194 */	0,		0,		0,
+  /* 195 */	0,		0,		0,
+  /* 196 */	0,		0,		0,
+  /* 197 */	0,		0,		0,
+  /* 198 */	0,		0,		0,
+  /* 199 */	0,		0,		0,
+  /* 200 */	0,		0,		0,
+  /* 201 */	0,		0,		0,
+  /* 202 */	0,		0,		0,
+  /* 203 */	0,		0,		0,
+  /* 204 */	0,		0,		0,
+  /* 205 */	0,		0,		0,
+  /* 206 */	0,		0,		0,
+  /* 207 */	0,		0,		0,
+  /* 208 */	0,		0,		0,
+  /* 209 */	0,		0,		0,
+  /* 210 */	0,		0,		0,
+  /* 211 */	0,		0,		0,
+  /* 212 */	0,		0,		0,
+  /* 213 */	0,		0,		0,
+  /* 214 */	0,		0,		0,
+  /* 215 */	0,		0,		0,
+  /* 216 */	0,		0,		0,
+  /* 217 */	0,		0,		0,
+  /* 218 */	0,		0,		0,
+  /* 219 */	0,		0,		0,
+  /* 220 */	0,		0,		0,
+  /* 221 */	0,		0,		0,
+  /* 222 */	0,		0,		0,
+  /* 223 */	0,		0,		0,
+  /* 224 */	0,		0,		0,
+  /* 225 */	0,		0,		0,
+  /* 226 */	0,		0,		0,
+  /* 227 */	0,		0,		0,
+  /* 228 */	0,		0,		0,
+  /* 229 */	0,		0,		0,
+  /* 230 */	0,		0,		0,
+  /* 231 */	0,		0,		0,
+  /* 232 */	0,		0,		0,
+  /* 233 */	0,		0,		0,
+  /* 234 */	0,		0,		0,
+  /* 235 */	0,		0,		0,
+  /* 236 */	0,		0,		0,
+  /* 237 */	0,		0,		0,
+  /* 238 */	0,		0,		0,
+  /* 239 */	0,		0,		0,
+  /* 240 */	0,		0,		0,
+  /* 241 */	0,		0,		0,
+  /* 242 */	0,		0,		0,
+  /* 243 */	0,		0,		0,
+  /* 244 */	0,		0,		0,
+  /* 245 */	0,		0,		0,
+  /* 246 */	0,		0,		0,
+  /* 247 */	0,		0,		0,
+  /* 248 */	0,		0,		0,
+  /* 249 */	0,		0,		0,
+  /* 250 */	0,		0,		0,
+  /* 251 */	0,		0,		0,
+  /* 252 */	0,		0,		0,
+  /* 253 */	0,		0,		0,
+  /* 254 */	0,		0,		0,
+  /* 255 */	0,		0,		0
+};
+
+#endif /* WINKEYBD_H */
diff --git a/xorg-server/hw/xwin/winmouse.c b/xorg-server/hw/xwin/winmouse.c
index 342f20d56..b2ee73d90 100644
--- a/xorg-server/hw/xwin/winmouse.c
+++ b/xorg-server/hw/xwin/winmouse.c
@@ -1,388 +1,388 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-#if defined(XFree86Server)
-#include "inputstr.h"
-#include "exevents.h" /* for button/axes labels */
-#include "xserver-properties.h"
-
-/* Peek the internal button mapping */
-static CARD8 const *g_winMouseButtonMap = NULL;
-#endif
-
-
-/*
- * Local prototypes
- */
-
-static void
-winMouseCtrl (DeviceIntPtr pDevice, PtrCtrl *pCtrl);
-
-
-static void
-winMouseCtrl (DeviceIntPtr pDevice, PtrCtrl *pCtrl)
-{
-}
-
-
-/*
- * See Porting Layer Definition - p. 18
- * This is known as a DeviceProc
- */
-
-int
-winMouseProc (DeviceIntPtr pDeviceInt, int iState)
-{
-  int 			lngMouseButtons, i;
-  int			lngWheelEvents = 2;
-  CARD8			*map;
-  DevicePtr		pDevice = (DevicePtr) pDeviceInt;
-  Atom *btn_labels;
-  Atom axes_labels[2];
-
-  switch (iState)
-    {
-    case DEVICE_INIT:
-      /* Get number of mouse buttons */
-      lngMouseButtons = GetSystemMetrics(SM_CMOUSEBUTTONS);
-
-      /* Mapping of windows events to X events:
-       * LEFT:1 MIDDLE:2 RIGHT:3
-       * SCROLL_UP:4 SCROLL_DOWN:5
-       * XBUTTON 1:6 XBUTTON 2:7 ...
-       *
-       * To map scroll wheel correctly we need at least the 3 normal buttons
-       */
-      if (lngMouseButtons < 3)
-        lngMouseButtons = 3;
-      winMsg(X_PROBED, "%d mouse buttons found\n", lngMouseButtons);
-
-      /* allocate memory: 
-       * number of buttons + 2x mouse wheel event + 1 extra (offset for map) 
-       */
-      map = malloc(sizeof(CARD8) * (lngMouseButtons + lngWheelEvents + 1));
-    
-      /* initalize button map */ 
-      map[0] = 0;
-      for (i=1; i <= lngMouseButtons + lngWheelEvents; i++)
-      	map[i] = i;
-
-      btn_labels = calloc((lngMouseButtons + lngWheelEvents), sizeof(Atom));
-      btn_labels[0] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_LEFT);
-      btn_labels[1] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_MIDDLE);
-      btn_labels[2] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_RIGHT);
-      btn_labels[3] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_UP);
-      btn_labels[4] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_DOWN);
-
-      axes_labels[0] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_X);
-      axes_labels[1] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_Y);
-
-      InitPointerDeviceStruct (pDevice,
-			       map,
-			       lngMouseButtons + lngWheelEvents,
-			       btn_labels,
-			       winMouseCtrl,
-			       GetMotionHistorySize(),
-			       2,
-			       axes_labels);
-      free(map);
-      free(btn_labels);
-
-#if defined(XFree86Server)
-      g_winMouseButtonMap = pDeviceInt->button->map;
-#endif
-      break;
-
-    case DEVICE_ON:
-      pDevice->on = TRUE;
-      break;
-
-    case DEVICE_CLOSE:
-#if defined(XFree86Server)
-      g_winMouseButtonMap = NULL;
-#endif
-    case DEVICE_OFF:
-      pDevice->on = FALSE;
-      break;
-    }
-  return Success;
-}
-
-
-/* Handle the mouse wheel */
-int
-winMouseWheel (ScreenPtr pScreen, int iDeltaZ)
-{
-  winScreenPriv(pScreen);
-  int button; /* Button4 or Button5 */
-
-  /* Button4 = WheelUp */
-  /* Button5 = WheelDown */
-
-  /* Do we have any previous delta stored? */
-  if ((pScreenPriv->iDeltaZ > 0
-       && iDeltaZ > 0)
-      || (pScreenPriv->iDeltaZ < 0
-	  && iDeltaZ < 0))
-    {
-      /* Previous delta and of same sign as current delta */
-      iDeltaZ += pScreenPriv->iDeltaZ;
-      pScreenPriv->iDeltaZ = 0;
-    }
-  else
-    {
-      /*
-       * Previous delta of different sign, or zero.
-       * We will set it to zero for either case,
-       * as blindly setting takes just as much time
-       * as checking, then setting if necessary :)
-       */
-      pScreenPriv->iDeltaZ = 0;
-    }
-
-  /*
-   * Only process this message if the wheel has moved further than
-   * WHEEL_DELTA
-   */
-  if (iDeltaZ >= WHEEL_DELTA || (-1 * iDeltaZ) >= WHEEL_DELTA)
-    {
-      pScreenPriv->iDeltaZ = 0;
-	  
-      /* Figure out how many whole deltas of the wheel we have */
-      iDeltaZ /= WHEEL_DELTA;
-    }
-  else
-    {
-      /*
-       * Wheel has not moved past WHEEL_DELTA threshold;
-       * we will store the wheel delta until the threshold
-       * has been reached.
-       */
-      pScreenPriv->iDeltaZ = iDeltaZ;
-      return 0;
-    }
-
-  /* Set the button to indicate up or down wheel delta */
-  if (iDeltaZ > 0)
-    {
-      button = Button4;
-    }
-  else
-    {
-      button = Button5;
-    }
-
-  /*
-   * Flip iDeltaZ to positive, if negative,
-   * because always need to generate a *positive* number of
-   * button clicks for the Z axis.
-   */
-  if (iDeltaZ < 0)
-    {
-      iDeltaZ *= -1;
-    }
-
-  /* Generate X input messages for each wheel delta we have seen */
-  while (iDeltaZ--)
-    {
-      /* Push the wheel button */
-      winMouseButtonsSendEvent (ButtonPress, button);
-
-      /* Release the wheel button */
-      winMouseButtonsSendEvent (ButtonRelease, button);
-    }
-
-  return 0;
-}
-
-
-/*
- * Enqueue a mouse button event
- */
-
-void
-winMouseButtonsSendEvent (int iEventType, int iButton)
-{
-  EventListPtr events;
-  int i, nevents;
-
-#if defined(XFree86Server)
-  if (g_winMouseButtonMap)
-    iButton = g_winMouseButtonMap[iButton];
-#endif
-
-  GetEventList(&events);
-  nevents = GetPointerEvents(events, g_pwinPointer, iEventType, iButton,
-			     POINTER_RELATIVE, 0, 0, NULL);
-
-  for (i = 0; i < nevents; i++)
-    mieqEnqueue(g_pwinPointer, events[i].event);
-
-#if CYGDEBUG
-  ErrorF("winMouseButtonsSendEvent: iEventType: %d, iButton: %d, nEvents %d\n",
-          iEventType, iButton, nevents);
-#endif
-}
-
-
-/*
- * Decide what to do with a Windows mouse message
- */
-
-int
-winMouseButtonsHandle (ScreenPtr pScreen,
-		       int iEventType, int iButton,
-		       WPARAM wParam)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  /* Send button events right away if emulate 3 buttons is off */
-  if (pScreenInfo->iE3BTimeout == WIN_E3B_OFF)
-    {
-      /* Emulate 3 buttons is off, send the button event */
-      winMouseButtonsSendEvent (iEventType, iButton);
-      return 0;
-    }
-
-  /* Emulate 3 buttons is on, let the fun begin */
-  if (iEventType == ButtonPress
-      && pScreenPriv->iE3BCachedPress == 0
-      && !pScreenPriv->fE3BFakeButton2Sent)
-    {
-      /*
-       * Button was pressed, no press is cached,
-       * and there is no fake button 2 release pending.
-       */
-
-      /* Store button press type */
-      pScreenPriv->iE3BCachedPress = iButton;
-
-      /*
-       * Set a timer to send this button press if the other button
-       * is not pressed within the timeout time.
-       */
-      SetTimer (pScreenPriv->hwndScreen,
-		WIN_E3B_TIMER_ID,
-		pScreenInfo->iE3BTimeout,
-		NULL);
-    }
-  else if (iEventType == ButtonPress
-	   && pScreenPriv->iE3BCachedPress != 0
-	   && pScreenPriv->iE3BCachedPress != iButton
-	   && !pScreenPriv->fE3BFakeButton2Sent)
-    {
-      /*
-       * Button press is cached, other button was pressed,
-       * and there is no fake button 2 release pending.
-       */
-
-      /* Mouse button was cached and other button was pressed */
-      KillTimer (pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
-      pScreenPriv->iE3BCachedPress = 0;
-
-      /* Send fake middle button */
-      winMouseButtonsSendEvent (ButtonPress, Button2);
-
-      /* Indicate that a fake middle button event was sent */
-      pScreenPriv->fE3BFakeButton2Sent = TRUE;
-    }
-  else if (iEventType == ButtonRelease
-	   && pScreenPriv->iE3BCachedPress == iButton)
-    {
-      /*
-       * Cached button was released before timer ran out,
-       * and before the other mouse button was pressed.
-       */
-      KillTimer (pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
-      pScreenPriv->iE3BCachedPress = 0;
-
-      /* Send cached press, then send release */
-      winMouseButtonsSendEvent (ButtonPress, iButton);
-      winMouseButtonsSendEvent (ButtonRelease, iButton);
-    }
-  else if (iEventType == ButtonRelease
-	   && pScreenPriv->fE3BFakeButton2Sent
-	   && !(wParam & MK_LBUTTON)
-	   && !(wParam & MK_RBUTTON))
-    {
-      /*
-       * Fake button 2 was sent and both mouse buttons have now been released
-       */
-      pScreenPriv->fE3BFakeButton2Sent = FALSE;
-      
-      /* Send middle mouse button release */
-      winMouseButtonsSendEvent (ButtonRelease, Button2);
-    }
-  else if (iEventType == ButtonRelease
-	   && pScreenPriv->iE3BCachedPress == 0
-	   && !pScreenPriv->fE3BFakeButton2Sent)
-    {
-      /*
-       * Button was release, no button is cached,
-       * and there is no fake button 2 release is pending.
-       */
-      winMouseButtonsSendEvent (ButtonRelease, iButton);
-    }
-
-  return 0;
-}
-
-/**
- * Enqueue a motion event.
- *
- *  XXX: miPointerMove does exactly this, but is static :-( (and uses a static buffer)
- *
- */
-void winEnqueueMotion(int x, int y)
-{
-  int i, nevents;
-  int valuators[2];
-  EventListPtr events;
-
-  miPointerSetPosition(g_pwinPointer, &x, &y);
-  valuators[0] = x;
-  valuators[1] = y;
-
-  GetEventList(&events);
-  nevents = GetPointerEvents(events, g_pwinPointer, MotionNotify, 0,
-			     POINTER_ABSOLUTE | POINTER_SCREEN, 0, 2, valuators);
-
-  for (i = 0; i < nevents; i++)
-    mieqEnqueue(g_pwinPointer, events[i].event);
-}
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+#if defined(XFree86Server)
+#include "inputstr.h"
+#include "exevents.h" /* for button/axes labels */
+#include "xserver-properties.h"
+
+/* Peek the internal button mapping */
+static CARD8 const *g_winMouseButtonMap = NULL;
+#endif
+
+
+/*
+ * Local prototypes
+ */
+
+static void
+winMouseCtrl (DeviceIntPtr pDevice, PtrCtrl *pCtrl);
+
+
+static void
+winMouseCtrl (DeviceIntPtr pDevice, PtrCtrl *pCtrl)
+{
+}
+
+
+/*
+ * See Porting Layer Definition - p. 18
+ * This is known as a DeviceProc
+ */
+
+int
+winMouseProc (DeviceIntPtr pDeviceInt, int iState)
+{
+  int 			lngMouseButtons, i;
+  int			lngWheelEvents = 2;
+  CARD8			*map;
+  DevicePtr		pDevice = (DevicePtr) pDeviceInt;
+  Atom *btn_labels;
+  Atom axes_labels[2];
+
+  switch (iState)
+    {
+    case DEVICE_INIT:
+      /* Get number of mouse buttons */
+      lngMouseButtons = GetSystemMetrics(SM_CMOUSEBUTTONS);
+
+      /* Mapping of windows events to X events:
+       * LEFT:1 MIDDLE:2 RIGHT:3
+       * SCROLL_UP:4 SCROLL_DOWN:5
+       * XBUTTON 1:6 XBUTTON 2:7 ...
+       *
+       * To map scroll wheel correctly we need at least the 3 normal buttons
+       */
+      if (lngMouseButtons < 3)
+        lngMouseButtons = 3;
+      winMsg(X_PROBED, "%d mouse buttons found\n", lngMouseButtons);
+
+      /* allocate memory: 
+       * number of buttons + 2x mouse wheel event + 1 extra (offset for map) 
+       */
+      map = malloc(sizeof(CARD8) * (lngMouseButtons + lngWheelEvents + 1));
+    
+      /* initalize button map */ 
+      map[0] = 0;
+      for (i=1; i <= lngMouseButtons + lngWheelEvents; i++)
+      	map[i] = i;
+
+      btn_labels = calloc((lngMouseButtons + lngWheelEvents), sizeof(Atom));
+      btn_labels[0] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_LEFT);
+      btn_labels[1] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_MIDDLE);
+      btn_labels[2] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_RIGHT);
+      btn_labels[3] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_UP);
+      btn_labels[4] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_DOWN);
+
+      axes_labels[0] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_X);
+      axes_labels[1] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_Y);
+
+      InitPointerDeviceStruct (pDevice,
+			       map,
+			       lngMouseButtons + lngWheelEvents,
+			       btn_labels,
+			       winMouseCtrl,
+			       GetMotionHistorySize(),
+			       2,
+			       axes_labels);
+      free(map);
+      free(btn_labels);
+
+#if defined(XFree86Server)
+      g_winMouseButtonMap = pDeviceInt->button->map;
+#endif
+      break;
+
+    case DEVICE_ON:
+      pDevice->on = TRUE;
+      break;
+
+    case DEVICE_CLOSE:
+#if defined(XFree86Server)
+      g_winMouseButtonMap = NULL;
+#endif
+    case DEVICE_OFF:
+      pDevice->on = FALSE;
+      break;
+    }
+  return Success;
+}
+
+
+/* Handle the mouse wheel */
+int
+winMouseWheel (ScreenPtr pScreen, int iDeltaZ)
+{
+  winScreenPriv(pScreen);
+  int button; /* Button4 or Button5 */
+
+  /* Button4 = WheelUp */
+  /* Button5 = WheelDown */
+
+  /* Do we have any previous delta stored? */
+  if ((pScreenPriv->iDeltaZ > 0
+       && iDeltaZ > 0)
+      || (pScreenPriv->iDeltaZ < 0
+	  && iDeltaZ < 0))
+    {
+      /* Previous delta and of same sign as current delta */
+      iDeltaZ += pScreenPriv->iDeltaZ;
+      pScreenPriv->iDeltaZ = 0;
+    }
+  else
+    {
+      /*
+       * Previous delta of different sign, or zero.
+       * We will set it to zero for either case,
+       * as blindly setting takes just as much time
+       * as checking, then setting if necessary :)
+       */
+      pScreenPriv->iDeltaZ = 0;
+    }
+
+  /*
+   * Only process this message if the wheel has moved further than
+   * WHEEL_DELTA
+   */
+  if (iDeltaZ >= WHEEL_DELTA || (-1 * iDeltaZ) >= WHEEL_DELTA)
+    {
+      pScreenPriv->iDeltaZ = 0;
+	  
+      /* Figure out how many whole deltas of the wheel we have */
+      iDeltaZ /= WHEEL_DELTA;
+    }
+  else
+    {
+      /*
+       * Wheel has not moved past WHEEL_DELTA threshold;
+       * we will store the wheel delta until the threshold
+       * has been reached.
+       */
+      pScreenPriv->iDeltaZ = iDeltaZ;
+      return 0;
+    }
+
+  /* Set the button to indicate up or down wheel delta */
+  if (iDeltaZ > 0)
+    {
+      button = Button4;
+    }
+  else
+    {
+      button = Button5;
+    }
+
+  /*
+   * Flip iDeltaZ to positive, if negative,
+   * because always need to generate a *positive* number of
+   * button clicks for the Z axis.
+   */
+  if (iDeltaZ < 0)
+    {
+      iDeltaZ *= -1;
+    }
+
+  /* Generate X input messages for each wheel delta we have seen */
+  while (iDeltaZ--)
+    {
+      /* Push the wheel button */
+      winMouseButtonsSendEvent (ButtonPress, button);
+
+      /* Release the wheel button */
+      winMouseButtonsSendEvent (ButtonRelease, button);
+    }
+
+  return 0;
+}
+
+
+/*
+ * Enqueue a mouse button event
+ */
+
+void
+winMouseButtonsSendEvent (int iEventType, int iButton)
+{
+  EventListPtr events;
+  int i, nevents;
+
+#if defined(XFree86Server)
+  if (g_winMouseButtonMap)
+    iButton = g_winMouseButtonMap[iButton];
+#endif
+
+  GetEventList(&events);
+  nevents = GetPointerEvents(events, g_pwinPointer, iEventType, iButton,
+			     POINTER_RELATIVE, 0, 0, NULL);
+
+  for (i = 0; i < nevents; i++)
+    mieqEnqueue(g_pwinPointer, (InternalEvent*)events[i].event);
+
+#if CYGDEBUG
+  ErrorF("winMouseButtonsSendEvent: iEventType: %d, iButton: %d, nEvents %d\n",
+          iEventType, iButton, nevents);
+#endif
+}
+
+
+/*
+ * Decide what to do with a Windows mouse message
+ */
+
+int
+winMouseButtonsHandle (ScreenPtr pScreen,
+		       int iEventType, int iButton,
+		       WPARAM wParam)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  /* Send button events right away if emulate 3 buttons is off */
+  if (pScreenInfo->iE3BTimeout == WIN_E3B_OFF)
+    {
+      /* Emulate 3 buttons is off, send the button event */
+      winMouseButtonsSendEvent (iEventType, iButton);
+      return 0;
+    }
+
+  /* Emulate 3 buttons is on, let the fun begin */
+  if (iEventType == ButtonPress
+      && pScreenPriv->iE3BCachedPress == 0
+      && !pScreenPriv->fE3BFakeButton2Sent)
+    {
+      /*
+       * Button was pressed, no press is cached,
+       * and there is no fake button 2 release pending.
+       */
+
+      /* Store button press type */
+      pScreenPriv->iE3BCachedPress = iButton;
+
+      /*
+       * Set a timer to send this button press if the other button
+       * is not pressed within the timeout time.
+       */
+      SetTimer (pScreenPriv->hwndScreen,
+		WIN_E3B_TIMER_ID,
+		pScreenInfo->iE3BTimeout,
+		NULL);
+    }
+  else if (iEventType == ButtonPress
+	   && pScreenPriv->iE3BCachedPress != 0
+	   && pScreenPriv->iE3BCachedPress != iButton
+	   && !pScreenPriv->fE3BFakeButton2Sent)
+    {
+      /*
+       * Button press is cached, other button was pressed,
+       * and there is no fake button 2 release pending.
+       */
+
+      /* Mouse button was cached and other button was pressed */
+      KillTimer (pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
+      pScreenPriv->iE3BCachedPress = 0;
+
+      /* Send fake middle button */
+      winMouseButtonsSendEvent (ButtonPress, Button2);
+
+      /* Indicate that a fake middle button event was sent */
+      pScreenPriv->fE3BFakeButton2Sent = TRUE;
+    }
+  else if (iEventType == ButtonRelease
+	   && pScreenPriv->iE3BCachedPress == iButton)
+    {
+      /*
+       * Cached button was released before timer ran out,
+       * and before the other mouse button was pressed.
+       */
+      KillTimer (pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
+      pScreenPriv->iE3BCachedPress = 0;
+
+      /* Send cached press, then send release */
+      winMouseButtonsSendEvent (ButtonPress, iButton);
+      winMouseButtonsSendEvent (ButtonRelease, iButton);
+    }
+  else if (iEventType == ButtonRelease
+	   && pScreenPriv->fE3BFakeButton2Sent
+	   && !(wParam & MK_LBUTTON)
+	   && !(wParam & MK_RBUTTON))
+    {
+      /*
+       * Fake button 2 was sent and both mouse buttons have now been released
+       */
+      pScreenPriv->fE3BFakeButton2Sent = FALSE;
+      
+      /* Send middle mouse button release */
+      winMouseButtonsSendEvent (ButtonRelease, Button2);
+    }
+  else if (iEventType == ButtonRelease
+	   && pScreenPriv->iE3BCachedPress == 0
+	   && !pScreenPriv->fE3BFakeButton2Sent)
+    {
+      /*
+       * Button was release, no button is cached,
+       * and there is no fake button 2 release is pending.
+       */
+      winMouseButtonsSendEvent (ButtonRelease, iButton);
+    }
+
+  return 0;
+}
+
+/**
+ * Enqueue a motion event.
+ *
+ *  XXX: miPointerMove does exactly this, but is static :-( (and uses a static buffer)
+ *
+ */
+void winEnqueueMotion(int x, int y)
+{
+  int i, nevents;
+  int valuators[2];
+  EventListPtr events;
+
+  miPointerSetPosition(g_pwinPointer, &x, &y);
+  valuators[0] = x;
+  valuators[1] = y;
+
+  GetEventList(&events);
+  nevents = GetPointerEvents(events, g_pwinPointer, MotionNotify, 0,
+			     POINTER_ABSOLUTE | POINTER_SCREEN, 0, 2, valuators);
+
+  for (i = 0; i < nevents; i++)
+    mieqEnqueue(g_pwinPointer, (InternalEvent*)events[i].event);
+}
diff --git a/xorg-server/hw/xwin/winmultiwindowwm.c b/xorg-server/hw/xwin/winmultiwindowwm.c
index 21d913e5e..0749f5df6 100644
--- a/xorg-server/hw/xwin/winmultiwindowwm.c
+++ b/xorg-server/hw/xwin/winmultiwindowwm.c
@@ -1,1745 +1,1745 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *Copyright (C) Colin Harrison 2005-2009
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- *              Colin Harrison
- */
-
-/* X headers */
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#ifdef __CYGWIN__
-#include <sys/select.h>
-#endif
-#include <fcntl.h>
-#include <setjmp.h>
-#define HANDLE void *
-#include <pthread.h>
-#undef HANDLE
-#include <X11/X.h>
-#include <X11/Xatom.h>
-#include <X11/Xlib.h>
-#include <X11/Xlocale.h>
-#include <X11/Xproto.h>
-#include <X11/Xutil.h>
-#include <X11/cursorfont.h>
-#include <X11/Xwindows.h>
-
-/* Local headers */
-#include "objbase.h"
-#include "ddraw.h"
-#include "winwindow.h"
-#include "winprefs.h"
-#include "window.h"
-#include "pixmapstr.h"
-#include "windowstr.h"
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-#include <X11/extensions/windowswmstr.h>
-#else
-/* We need the native HWND atom for intWM, so for consistency use the
-   same name as extWM would if we were building with enabled... */
-#define WINDOWSWM_NATIVE_HWND "_WINDOWSWM_NATIVE_HWND"
-#endif
-
-extern void winDebug(const char *format, ...);
-extern void winReshapeMultiWindow(WindowPtr pWin);
-extern void winUpdateRgnMultiWindow(WindowPtr pWin);
-
-#ifndef CYGDEBUG
-#define CYGDEBUG NO
-#endif
-
-/*
- * Constant defines
- */
-
-#define WIN_CONNECT_RETRIES	5
-#define WIN_CONNECT_DELAY	5
-#ifdef HAS_DEVWINDOWS
-# define WIN_MSG_QUEUE_FNAME	"/dev/windows"
-#endif
-#define WIN_JMP_OKAY		0
-#define WIN_JMP_ERROR_IO	2
-
-/*
- * Local structures
- */
-
-typedef struct _WMMsgNodeRec {
-  winWMMessageRec	msg;
-  struct _WMMsgNodeRec	*pNext;
-} WMMsgNodeRec, *WMMsgNodePtr;
-
-typedef struct _WMMsgQueueRec {
-  struct _WMMsgNodeRec	*pHead;
-  struct _WMMsgNodeRec	*pTail;
-  pthread_mutex_t	pmMutex;
-  pthread_cond_t	pcNotEmpty;
-  int			nQueueSize;
-} WMMsgQueueRec, *WMMsgQueuePtr;
-
-typedef struct _WMInfo {
-  Display		*pDisplay;
-  WMMsgQueueRec		wmMsgQueue;
-  Atom			atmWmProtos;
-  Atom			atmWmDelete;
-  Atom			atmPrivMap;
-  Bool			fAllowOtherWM;
-} WMInfoRec, *WMInfoPtr;
-
-typedef struct _WMProcArgRec {
-  DWORD			dwScreen;
-  WMInfoPtr		pWMInfo;
-  pthread_mutex_t	*ppmServerStarted;
-} WMProcArgRec, *WMProcArgPtr;
-
-typedef struct _XMsgProcArgRec {
-  Display		*pDisplay;
-  DWORD			dwScreen;
-  WMInfoPtr		pWMInfo;
-  pthread_mutex_t	*ppmServerStarted;
-  HWND			hwndScreen;
-} XMsgProcArgRec, *XMsgProcArgPtr;
-
-
-/*
- * References to external symbols
- */
-
-extern char *display;
-extern void ErrorF (const char* /*f*/, ...);
-
-/*
- * Prototypes for local functions
- */
-
-static void
-PushMessage (WMMsgQueuePtr pQueue, WMMsgNodePtr pNode);
-
-static WMMsgNodePtr
-PopMessage (WMMsgQueuePtr pQueue, WMInfoPtr pWMInfo);
-
-static Bool
-InitQueue (WMMsgQueuePtr pQueue);
-
-static void
-GetWindowName (Display * pDpy, Window iWin, wchar_t **ppName);
-
-static int
-SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData);
-
-static void
-UpdateName (WMInfoPtr pWMInfo, Window iWindow);
-
-static void*
-winMultiWindowWMProc (void* pArg);
-
-static int
-winMultiWindowWMErrorHandler (Display *pDisplay, XErrorEvent *pErr);
-
-static int
-winMultiWindowWMIOErrorHandler (Display *pDisplay);
-
-static void *
-winMultiWindowXMsgProc (void *pArg);
-
-static int
-winMultiWindowXMsgProcErrorHandler (Display *pDisplay, XErrorEvent *pErr);
-
-static int
-winMultiWindowXMsgProcIOErrorHandler (Display *pDisplay);
-
-static int
-winRedirectErrorHandler (Display *pDisplay, XErrorEvent *pErr);
-
-static void
-winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg);
-
-#if 0
-static void
-PreserveWin32Stack(WMInfoPtr pWMInfo, Window iWindow, UINT direction);
-#endif
-
-static Bool
-CheckAnotherWindowManager (Display *pDisplay, DWORD dwScreen, Bool fAllowOtherWM);
-
-static void
-winApplyHints (Display *pDisplay, Window iWindow, HWND hWnd, HWND *zstyle);
-
-void
-winUpdateWindowPosition (HWND hWnd, Bool reshape, HWND *zstyle);
-
-/*
- * Local globals
- */
-
-static jmp_buf			g_jmpWMEntry;
-static jmp_buf			g_jmpXMsgProcEntry;
-static Bool			g_shutdown = FALSE;
-static Bool			redirectError = FALSE;
-static Bool			g_fAnotherWMRunning = FALSE;
-
-/*
- * PushMessage - Push a message onto the queue
- */
-
-static void
-PushMessage (WMMsgQueuePtr pQueue, WMMsgNodePtr pNode)
-{
-
-  /* Lock the queue mutex */
-  pthread_mutex_lock (&pQueue->pmMutex);
-
-  pNode->pNext = NULL;
-  
-  if (pQueue->pTail != NULL)
-    {
-      pQueue->pTail->pNext = pNode;
-    }
-  pQueue->pTail = pNode;
-  
-  if (pQueue->pHead == NULL)
-    {
-      pQueue->pHead = pNode;
-    }
-
-
-#if 0
-  switch (pNode->msg.msg)
-    {
-    case WM_WM_MOVE:
-      ErrorF ("\tWM_WM_MOVE\n");
-      break;
-    case WM_WM_SIZE:
-      ErrorF ("\tWM_WM_SIZE\n");
-      break;
-    case WM_WM_RAISE:
-      ErrorF ("\tWM_WM_RAISE\n");
-      break;
-    case WM_WM_LOWER:
-      ErrorF ("\tWM_WM_LOWER\n");
-      break;
-    case WM_WM_MAP:
-      ErrorF ("\tWM_WM_MAP\n");
-      break;
-    case WM_WM_MAP2:
-      ErrorF ("\tWM_WM_MAP2\n");
-      break;
-    case WM_WM_MAP3:
-      ErrorF ("\tWM_WM_MAP3\n");
-      break;
-    case WM_WM_UNMAP:
-      ErrorF ("\tWM_WM_UNMAP\n");
-      break;
-    case WM_WM_KILL:
-      ErrorF ("\tWM_WM_KILL\n");
-      break;
-    case WM_WM_ACTIVATE:
-      ErrorF ("\tWM_WM_ACTIVATE\n");
-      break;
-    default:
-      ErrorF ("\tUnknown Message.\n");
-      break;
-    }
-#endif
-
-  /* Increase the count of elements in the queue by one */
-  ++(pQueue->nQueueSize);
-
-  /* Release the queue mutex */
-  pthread_mutex_unlock (&pQueue->pmMutex);
-
-  /* Signal that the queue is not empty */
-  pthread_cond_signal (&pQueue->pcNotEmpty);
-}
-
-
-#if CYGMULTIWINDOW_DEBUG
-/*
- * QueueSize - Return the size of the queue
- */
-
-static int
-QueueSize (WMMsgQueuePtr pQueue)
-{
-  WMMsgNodePtr		pNode;
-  int			nSize = 0;
-  
-  /* Loop through all elements in the queue */
-  for (pNode = pQueue->pHead; pNode != NULL; pNode = pNode->pNext)
-    ++nSize;
-
-  return nSize;
-}
-#endif
-
-
-/*
- * PopMessage - Pop a message from the queue
- */
-
-static WMMsgNodePtr
-PopMessage (WMMsgQueuePtr pQueue, WMInfoPtr pWMInfo)
-{
-  WMMsgNodePtr		pNode;
-
-  /* Lock the queue mutex */
-  pthread_mutex_lock (&pQueue->pmMutex);
-
-  /* Wait for --- */
-  while (pQueue->pHead == NULL)
-    {
-      pthread_cond_wait (&pQueue->pcNotEmpty, &pQueue->pmMutex);
-    }
-  
-  pNode = pQueue->pHead;
-  if (pQueue->pHead != NULL)
-    {
-      pQueue->pHead = pQueue->pHead->pNext;
-    }
-
-  if (pQueue->pTail == pNode)
-    {
-      pQueue->pTail = NULL;
-    }
-
-  /* Drop the number of elements in the queue by one */
-  --(pQueue->nQueueSize);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("Queue Size %d %d\n", pQueue->nQueueSize, QueueSize(pQueue));
-#endif
-  
-  /* Release the queue mutex */
-  pthread_mutex_unlock (&pQueue->pmMutex);
-
-  return pNode;
-}
-
-
-#if 0
-/*
- * HaveMessage - 
- */
-
-static Bool
-HaveMessage (WMMsgQueuePtr pQueue, UINT msg, Window iWindow)
-{
-  WMMsgNodePtr pNode;
-  
-  for (pNode = pQueue->pHead; pNode != NULL; pNode = pNode->pNext)
-    {
-      if (pNode->msg.msg==msg && pNode->msg.iWindow==iWindow)
-	return True;
-    }
-  
-  return False;
-}
-#endif
-
-
-/*
- * InitQueue - Initialize the Window Manager message queue
- */
-
-static
-Bool
-InitQueue (WMMsgQueuePtr pQueue)
-{
-  /* Check if the pQueue pointer is NULL */
-  if (pQueue == NULL)
-    {
-      ErrorF ("InitQueue - pQueue is NULL.  Exiting.\n");
-      return FALSE;
-    }
-
-  /* Set the head and tail to NULL */
-  pQueue->pHead = NULL;
-  pQueue->pTail = NULL;
-
-  /* There are no elements initially */
-  pQueue->nQueueSize = 0;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("InitQueue - Queue Size %d %d\n", pQueue->nQueueSize,
-	  QueueSize(pQueue));
-#endif
-
-  ErrorF ("InitQueue - Calling pthread_mutex_init\n");
-
-  /* Create synchronization objects */
-  pthread_mutex_init (&pQueue->pmMutex, NULL);
-
-  ErrorF ("InitQueue - pthread_mutex_init returned\n");
-  ErrorF ("InitQueue - Calling pthread_cond_init\n");
-
-  pthread_cond_init (&pQueue->pcNotEmpty, NULL);
-
-  ErrorF ("InitQueue - pthread_cond_init returned\n");
-
-  return TRUE;
-}
-
-
-/*
- * GetWindowName - Retrieve the title of an X Window
- */
-
-static void
-GetWindowName (Display *pDisplay, Window iWin, wchar_t **ppName)
-{
-  int			nResult, nNum;
-  char			**ppList;
-  char			*pszReturnData;
-  int			iLen, i;
-  XTextProperty		xtpName;
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("GetWindowName\n");
-#endif
-
-  /* Intialize ppName to NULL */
-  *ppName = NULL;
-
-  /* Try to get --- */
-  nResult = XGetWMName (pDisplay, iWin, &xtpName);
-  if (!nResult || !xtpName.value || !xtpName.nitems)
-    {
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("GetWindowName - XGetWMName failed.  No name.\n");
-#endif
-      return;
-    }
-
-   if (Xutf8TextPropertyToTextList (pDisplay, &xtpName, &ppList, &nNum) >= Success && nNum > 0 && *ppList)
-   {
- 	iLen = 0;
- 	for (i = 0; i < nNum; i++) iLen += strlen(ppList[i]);
- 	pszReturnData = (char *) malloc (iLen + 1);
- 	pszReturnData[0] = '\0';
- 	for (i = 0; i < nNum; i++) strcat (pszReturnData, ppList[i]);
- 	if (ppList) XFreeStringList (ppList);
-   }
-   else
-   {
- 	pszReturnData = (char *) malloc (1);
- 	pszReturnData[0] = '\0';
-   }
-   iLen = MultiByteToWideChar (CP_UTF8, 0, pszReturnData, -1, NULL, 0);
-   *ppName = (wchar_t*)malloc(sizeof(wchar_t)*(iLen + 1));
-   MultiByteToWideChar (CP_UTF8, 0, pszReturnData, -1, *ppName, iLen);
-   XFree (xtpName.value);
-   free (pszReturnData);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("GetWindowName - Returning\n");
-#endif
-}
-
-
-/*
- * Send a message to the X server from the WM thread
- */
-
-static int
-SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData)
-{
-  XEvent		e;
-
-  /* Prepare the X event structure */
-  e.type = ClientMessage;
-  e.xclient.window = iWin;
-  e.xclient.message_type = atmType;
-  e.xclient.format = 32;
-  e.xclient.data.l[0] = nData;
-  e.xclient.data.l[1] = CurrentTime;
-
-  /* Send the event to X */
-  return XSendEvent (pDisplay, iWin, False, NoEventMask, &e);
-}
-
-
-/*
- * Updates the name of a HWND according to its X WM_NAME property
- */
-
-static void
-UpdateName (WMInfoPtr pWMInfo, Window iWindow)
-{
-  wchar_t		*pszName;
-  Atom			atmType;
-  int			fmtRet;
-  unsigned long		items, remain;
-  HWND			*retHwnd, hWnd;
-  XWindowAttributes	attr;
-
-  hWnd = 0;
-
-  /* See if we can get the cached HWND for this window... */
-  if (XGetWindowProperty (pWMInfo->pDisplay,
-			  iWindow,
-			  pWMInfo->atmPrivMap,
-			  0,
-			  1,
-			  False,
-			  XA_INTEGER,//pWMInfo->atmPrivMap,
-			  &atmType,
-			  &fmtRet,
-			  &items,
-			  &remain,
-			  (unsigned char **) &retHwnd) == Success)
-    {
-      if (retHwnd)
-	{
-	  hWnd = *retHwnd;
-	  XFree (retHwnd);
-	}
-    }
-  
-  /* Some sanity checks */
-  if (!hWnd) return;
-  if (!IsWindow (hWnd)) return;
-
-  /* Set the Windows window name */
-  GetWindowName (pWMInfo->pDisplay, iWindow, &pszName);
-  if (pszName)
-    {
-      /* Get the window attributes */
-      XGetWindowAttributes (pWMInfo->pDisplay,
-			    iWindow,
-			    &attr);
-      if (!attr.override_redirect)
-	{
-	  SetWindowTextW (hWnd, pszName);
-	  winUpdateIcon (iWindow);
-	}
-
-      free (pszName);
-    }
-}
-
-
-#if 0
-/*
- * Fix up any differences between the X11 and Win32 window stacks
- * starting at the window passed in
- */
-static void
-PreserveWin32Stack(WMInfoPtr pWMInfo, Window iWindow, UINT direction)
-{
-  Atom                  atmType;
-  int                   fmtRet;
-  unsigned long         items, remain;
-  HWND                  hWnd, *retHwnd;
-  DWORD                 myWinProcID, winProcID;
-  Window                xWindow;
-  WINDOWPLACEMENT       wndPlace;
-  
-  hWnd = NULL;
-  /* See if we can get the cached HWND for this window... */
-  if (XGetWindowProperty (pWMInfo->pDisplay,
-			  iWindow,
-			  pWMInfo->atmPrivMap,
-			  0,
-			  1,
-			  False,
-			  XA_INTEGER,//pWMInfo->atmPrivMap,
-			  &atmType,
-			  &fmtRet,
-			  &items,
-			  &remain,
-			  (unsigned char **) &retHwnd) == Success)
-    {
-      if (retHwnd)
-	{
-	  hWnd = *retHwnd;
-	  XFree (retHwnd);
-	}
-    }
-  
-  if (!hWnd) return;
-  
-  GetWindowThreadProcessId (hWnd, &myWinProcID);
-  hWnd = GetNextWindow (hWnd, direction);
-  
-  while (hWnd) {
-    GetWindowThreadProcessId (hWnd, &winProcID);
-    if (winProcID == myWinProcID)
-      {
-	wndPlace.length = sizeof(WINDOWPLACEMENT);
-	GetWindowPlacement (hWnd, &wndPlace);
-	if ( !(wndPlace.showCmd==SW_HIDE ||
-	       wndPlace.showCmd==SW_MINIMIZE) )
-	  {
-	    xWindow = (Window)GetProp (hWnd, WIN_WID_PROP);
-	    if (xWindow)
-	      {
-		if (direction==GW_HWNDPREV)
-		  XRaiseWindow (pWMInfo->pDisplay, xWindow);
-		else
-		  XLowerWindow (pWMInfo->pDisplay, xWindow);
-	      }
-	  }
-      }
-    hWnd = GetNextWindow(hWnd, direction);
-  }
-}
-#endif /* PreserveWin32Stack */
-
-
-/*
- * winMultiWindowWMProc
- */
-
-static void *
-winMultiWindowWMProc (void *pArg)
-{
-  WMProcArgPtr		pProcArg = (WMProcArgPtr)pArg;
-  WMInfoPtr		pWMInfo = pProcArg->pWMInfo;
-  
-  /* Initialize the Window Manager */
-  winInitMultiWindowWM (pWMInfo, pProcArg);
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winMultiWindowWMProc ()\n");
-#endif
-
-  /* Loop until we explicity break out */
-  for (;;)
-    {
-      WMMsgNodePtr	pNode;
-
-      if(g_fAnotherWMRunning)/* Another Window manager exists. */
-	{
-	  Sleep (1000);
-	  continue;
-	}
-
-      /* Pop a message off of our queue */
-      pNode = PopMessage (&pWMInfo->wmMsgQueue, pWMInfo);
-      if (pNode == NULL)
-	{
-	  /* Bail if PopMessage returns without a message */
-	  /* NOTE: Remember that PopMessage is a blocking function. */
-	  ErrorF ("winMultiWindowWMProc - Queue is Empty?  Exiting.\n");
-	  pthread_exit (NULL);
-	}
-
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("winMultiWindowWMProc - %d ms MSG: %d ID: %d\n",
-	      GetTickCount (), (int)pNode->msg.msg, (int)pNode->msg.dwID);
-#endif
-
-      /* Branch on the message type */
-      switch (pNode->msg.msg)
-	{
-#if 0
-	case WM_WM_MOVE:
-	  ErrorF ("\tWM_WM_MOVE\n");
-	  break;
-
-	case WM_WM_SIZE:
-	  ErrorF ("\tWM_WM_SIZE\n");
-	  break;
-#endif
-
-	case WM_WM_RAISE:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_RAISE\n");
-#endif
-	  /* Raise the window */
-	  XRaiseWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
-#if 0
-	  PreserveWin32Stack (pWMInfo, pNode->msg.iWindow, GW_HWNDPREV);
-#endif
-	  break;
-
-	case WM_WM_LOWER:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_LOWER\n");
-#endif
-
-	  /* Lower the window */
-	  XLowerWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_MAP:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_MAP\n");
-#endif
-	  /* Put a note as to the HWND associated with this Window */
-	  XChangeProperty (pWMInfo->pDisplay,
-			   pNode->msg.iWindow,
-			   pWMInfo->atmPrivMap,
-			   XA_INTEGER,//pWMInfo->atmPrivMap,
-			   32,
-			   PropModeReplace,
-			   (unsigned char *) &(pNode->msg.hwndWindow),
-			   1);
-	  UpdateName (pWMInfo, pNode->msg.iWindow);
-	  winUpdateIcon (pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_MAP2:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_MAP2\n");
-#endif
-	  XChangeProperty (pWMInfo->pDisplay,
-			   pNode->msg.iWindow,
-			   pWMInfo->atmPrivMap,
-			   XA_INTEGER,//pWMInfo->atmPrivMap,
-			   32,
-			   PropModeReplace,
-			   (unsigned char *) &(pNode->msg.hwndWindow),
-			   1);
-	  break;
-
-	case WM_WM_MAP3:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_MAP3\n");
-#endif
-	  /* Put a note as to the HWND associated with this Window */
-	  XChangeProperty (pWMInfo->pDisplay,
-			   pNode->msg.iWindow,
-			   pWMInfo->atmPrivMap,
-			   XA_INTEGER,//pWMInfo->atmPrivMap,
-			   32,
-			   PropModeReplace,
-			   (unsigned char *) &(pNode->msg.hwndWindow),
-			   1);
-	  UpdateName (pWMInfo, pNode->msg.iWindow);
-	  winUpdateIcon (pNode->msg.iWindow);
-	  {
-	    HWND zstyle = HWND_NOTOPMOST;
-	    winApplyHints (pWMInfo->pDisplay, pNode->msg.iWindow, pNode->msg.hwndWindow, &zstyle);
-	    winUpdateWindowPosition (pNode->msg.hwndWindow, TRUE, &zstyle);
-	  }
-	  break;
-
-	case WM_WM_UNMAP:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_UNMAP\n");
-#endif
-	  
-	  /* Unmap the window */
-	  XUnmapWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_KILL:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_KILL\n");
-#endif
-	  {
-	    int				i, n, found = 0;
-	    Atom			*protocols;
-	    
-	    /* --- */
-	    if (XGetWMProtocols (pWMInfo->pDisplay,
-				 pNode->msg.iWindow,
-				 &protocols,
-				 &n))
-	      {
-		for (i = 0; i < n; ++i)
-		  if (protocols[i] == pWMInfo->atmWmDelete)
-		    ++found;
-		
-		XFree (protocols);
-	      }
-
-	    /* --- */
-	    if (found)
-	      SendXMessage (pWMInfo->pDisplay,
-			    pNode->msg.iWindow,
-			    pWMInfo->atmWmProtos,
-			    pWMInfo->atmWmDelete);
-	    else
-	      XKillClient (pWMInfo->pDisplay,
-			   pNode->msg.iWindow);
-	  }
-	  break;
-
-	case WM_WM_ACTIVATE:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_ACTIVATE\n");
-#endif
-	  
-	  /* Set the input focus */
-	  XSetInputFocus (pWMInfo->pDisplay,
-			  pNode->msg.iWindow,
-			  RevertToPointerRoot,
-			  CurrentTime);
-	  break;
-
-	case WM_WM_NAME_EVENT:
-	  UpdateName (pWMInfo, pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_HINTS_EVENT:
-	  winUpdateIcon (pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_CHANGE_STATE:
-	  /* Minimize the window in Windows */
-	  winMinimizeWindow (pNode->msg.iWindow);
-	  break;
-
-	default:
-	  ErrorF ("winMultiWindowWMProc - Unknown Message.  Exiting.\n");
-	  pthread_exit (NULL);
-	  break;
-	}
-
-      /* Free the retrieved message */
-      free (pNode);
-
-      /* Flush any pending events on our display */
-      XFlush (pWMInfo->pDisplay);
-    }
-
-  /* Free the condition variable */
-  pthread_cond_destroy (&pWMInfo->wmMsgQueue.pcNotEmpty);
-  
-  /* Free the mutex variable */
-  pthread_mutex_destroy (&pWMInfo->wmMsgQueue.pmMutex);
-  
-  /* Free the passed-in argument */
-  free (pProcArg);
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF("-winMultiWindowWMProc ()\n");
-#endif
-  return NULL;
-}
-
-
-/*
- * X message procedure
- */
-
-static void *
-winMultiWindowXMsgProc (void *pArg)
-{
-  winWMMessageRec       msg;
-  XMsgProcArgPtr	pProcArg = (XMsgProcArgPtr) pArg;
-  char			pszDisplay[512];
-  int                   iRetries;
-  XEvent		event;
-  Atom                  atmWmName;
-  Atom                  atmWmHints;
-  Atom			atmWmChange;
-  int			iReturn;
-  XIconSize		*xis;
-
-  ErrorF ("winMultiWindowXMsgProc - Hello\n");
-
-  /* Check that argument pointer is not invalid */
-  if (pProcArg == NULL)
-    {
-      ErrorF ("winMultiWindowXMsgProc - pProcArg is NULL.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winMultiWindowXMsgProc - Calling pthread_mutex_lock ()\n");
-
-  /* Grab the server started mutex - pause until we get it */
-  iReturn = pthread_mutex_lock (pProcArg->ppmServerStarted);
-  if (iReturn != 0)
-    {
-      ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () failed: %d.  "
-	      "Exiting.\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () returned.\n");
-
-  /* Allow multiple threads to access Xlib */
-  if (XInitThreads () == 0)
-    {
-      ErrorF ("winMultiWindowXMsgProc - XInitThreads () failed.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* See if X supports the current locale */
-  if (XSupportsLocale () == False)
-    {
-      ErrorF ("winMultiWindowXMsgProc - Warning: locale not supported by X\n");
-    }
-
-  /* Release the server started mutex */
-  pthread_mutex_unlock (pProcArg->ppmServerStarted);
-
-  ErrorF ("winMultiWindowXMsgProc - pthread_mutex_unlock () returned.\n");
-
-  /* Set jump point for IO Error exits */
-  iReturn = setjmp (g_jmpXMsgProcEntry);
-  
-  /* Check if we should continue operations */
-  if (iReturn != WIN_JMP_ERROR_IO
-      && iReturn != WIN_JMP_OKAY)
-    {
-      /* setjmp returned an unknown value, exit */
-      ErrorF ("winInitMultiWindowXMsgProc - setjmp returned: %d.  Exiting.\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-  else if (iReturn == WIN_JMP_ERROR_IO)
-    {
-      ErrorF ("winInitMultiWindowXMsgProc - Caught IO Error.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Install our error handler */
-  XSetErrorHandler (winMultiWindowXMsgProcErrorHandler);
-  XSetIOErrorHandler (winMultiWindowXMsgProcIOErrorHandler);
-
-  /* Setup the display connection string x */
-  snprintf (pszDisplay,
-	    512, "127.0.0.1:%s.%d", display, (int)pProcArg->dwScreen);
-
-  /* Print the display connection string */
-  ErrorF ("winMultiWindowXMsgProc - DISPLAY=%s\n", pszDisplay);
-
-  /* Use our generated cookie for authentication */
-  winSetAuthorization();
-  
-  /* Initialize retry count */
-  iRetries = 0;
-
-  /* Open the X display */
-  do
-    {
-      /* Try to open the display */
-      pProcArg->pDisplay = XOpenDisplay (pszDisplay);
-      if (pProcArg->pDisplay == NULL)
-	{
-	  ErrorF ("winMultiWindowXMsgProc - Could not open display, try: %d, "
-		  "sleeping: %d\n\f",
-		  iRetries + 1, WIN_CONNECT_DELAY);
-	  ++iRetries;
-	  sleep (WIN_CONNECT_DELAY);
-	  continue;
-	}
-      else
-	break;
-    }
-  while (pProcArg->pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
-  
-  /* Make sure that the display opened */
-  if (pProcArg->pDisplay == NULL)
-    {
-      ErrorF ("winMultiWindowXMsgProc - Failed opening the display.  "
-	      "Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winMultiWindowXMsgProc - XOpenDisplay () returned and "
-	  "successfully opened the display.\n");
-
-  /* Check if another window manager is already running */
-  g_fAnotherWMRunning = CheckAnotherWindowManager (pProcArg->pDisplay, pProcArg->dwScreen, pProcArg->pWMInfo->fAllowOtherWM);
-
-  if (g_fAnotherWMRunning && !pProcArg->pWMInfo->fAllowOtherWM)
-    {
-      ErrorF ("winMultiWindowXMsgProc - "
-          "another window manager is running.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Set up the supported icon sizes */
-  xis = XAllocIconSize ();
-  if (xis)
-    {
-      xis->min_width = xis->min_height = 16;
-      xis->max_width = xis->max_height = 48;
-      xis->width_inc = xis->height_inc = 16;
-      XSetIconSizes (pProcArg->pDisplay,
-		     RootWindow (pProcArg->pDisplay, pProcArg->dwScreen),
-		     xis,
-		     1);
-      XFree (xis);
-    }
-
-  atmWmName   = XInternAtom (pProcArg->pDisplay,
-			     "WM_NAME",
-			     False);
-  atmWmHints   = XInternAtom (pProcArg->pDisplay,
-			      "WM_HINTS",
-			      False);
-  atmWmChange  = XInternAtom (pProcArg->pDisplay,
-			      "WM_CHANGE_STATE",
-			      False);
-
-  /*
-    iiimxcf had a bug until 2009-04-27, assuming that the
-    WM_STATE atom exists, causing clients to fail with
-    a BadAtom X error if it doesn't.
-
-    Since this is on in the default Solaris 10 install,
-    workaround this by making sure it does exist...
-   */
-  XInternAtom(pProcArg->pDisplay, "WM_STATE", 0);
-
-  /* Loop until we explicitly break out */
-  while (1)
-    {
-      if (g_shutdown)
-        break;
-
-      if (pProcArg->pWMInfo->fAllowOtherWM && !XPending (pProcArg->pDisplay))
-	{
-	  if (CheckAnotherWindowManager (pProcArg->pDisplay, pProcArg->dwScreen, TRUE))
-	    {
-	      if (!g_fAnotherWMRunning)
-		{
-		  g_fAnotherWMRunning = TRUE;
-		  SendMessage(*(HWND*)pProcArg->hwndScreen, WM_UNMANAGE, 0, 0);
-		}
-	    }
-	  else
-	    {
-	      if (g_fAnotherWMRunning)
-		{
-		  g_fAnotherWMRunning = FALSE;
-		  SendMessage(*(HWND*)pProcArg->hwndScreen, WM_MANAGE, 0, 0);
-		}
-	    }
-	  Sleep (500);
-	  continue;
-	}
-
-      /* Fetch next event */
-      XNextEvent (pProcArg->pDisplay, &event);
-
-      /* Branch on event type */
-      if (event.type == CreateNotify)
-	{
-	  XWindowAttributes	attr;
-
-	  XSelectInput (pProcArg->pDisplay,
-			event.xcreatewindow.window,
-			PropertyChangeMask);
-
-	  /* Get the window attributes */
-	  XGetWindowAttributes (pProcArg->pDisplay,
-				event.xcreatewindow.window,
-				&attr);
-
-	  if (!attr.override_redirect)
-	    XSetWindowBorderWidth(pProcArg->pDisplay,
-				  event.xcreatewindow.window,
-				  0);
-	}
-      else if (event.type == MapNotify)
-        {
-          /* Fake a reparentNotify event as SWT/Motif expects a
-             Window Manager to reparent a top-level window when
-             it is mapped and waits until they do.
-
-             We don't actually need to reparent, as the frame is
-             a native window, not an X window
-
-             We do this on MapNotify, not MapRequest like a real
-             Window Manager would, so we don't have do get involved
-             in actually mapping the window via it's (non-existent)
-             parent...
-
-             See sourceware bugzilla #9848
-          */
-
-          XWindowAttributes attr;
-          Window root;
-          Window parent;
-          Window *children;
-          unsigned int nchildren;
-
-          if (XGetWindowAttributes(event.xmap.display,
-                                   event.xmap.window,
-                                   &attr) &&
-              XQueryTree(event.xmap.display,
-                         event.xmap.window,
-                         &root, &parent, &children, &nchildren))
-            {
-              if (children) XFree(children);
-
-              /*
-                It's a top-level window if the parent window is a root window
-                Only non-override_redirect windows can get reparented
-              */
-              if ((attr.root == parent) && !event.xmap.override_redirect)
-                {
-                  XEvent event_send;
-
-                  event_send.type = ReparentNotify;
-                  event_send.xreparent.event = event.xmap.window;
-                  event_send.xreparent.window = event.xmap.window;
-                  event_send.xreparent.parent = parent;
-                  event_send.xreparent.x = attr.x;
-                  event_send.xreparent.y = attr.y;
-
-                  XSendEvent(event.xmap.display,
-                             event.xmap.window,
-                             True, StructureNotifyMask,
-                             &event_send);
-                }
-            }
-        }
-      else if (event.type == PropertyNotify
-	       && event.xproperty.atom == atmWmName)
-	{
-	  memset (&msg, 0, sizeof (msg));
-
-	  msg.msg = WM_WM_NAME_EVENT;
-	  msg.iWindow = event.xproperty.window;
-
-	  /* Other fields ignored */
-	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
-	}
-      else if (event.type == PropertyNotify
-	       && event.xproperty.atom == atmWmHints)
-	{
-	  memset (&msg, 0, sizeof (msg));
-
-	  msg.msg = WM_WM_HINTS_EVENT;
-	  msg.iWindow = event.xproperty.window;
-
-	  /* Other fields ignored */
-	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
-	}
-      else if (event.type == ClientMessage
-	       && event.xclient.message_type == atmWmChange
-	       && event.xclient.data.l[0] == IconicState)
-	{
-	  ErrorF ("winMultiWindowXMsgProc - WM_CHANGE_STATE - IconicState\n");
-
-	  memset (&msg, 0, sizeof (msg));
-
-	  msg.msg = WM_WM_CHANGE_STATE;
-	  msg.iWindow = event.xclient.window;
-
-	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
-	}
-    }
-
-  XCloseDisplay (pProcArg->pDisplay);
-  pthread_exit (NULL);
-  return NULL;
-}
-
-
-/*
- * winInitWM - Entry point for the X server to spawn
- * the Window Manager thread.  Called from
- * winscrinit.c/winFinishScreenInitFB ().
- */
-
-Bool
-winInitWM (void **ppWMInfo,
-	   pthread_t *ptWMProc,
-	   pthread_t *ptXMsgProc,
-	   pthread_mutex_t *ppmServerStarted,
-	   int dwScreen,
-	   HWND hwndScreen,
-	   BOOL allowOtherWM)
-{
-  WMProcArgPtr		pArg = (WMProcArgPtr) malloc (sizeof(WMProcArgRec));
-  WMInfoPtr		pWMInfo = (WMInfoPtr) malloc (sizeof(WMInfoRec));
-  XMsgProcArgPtr	pXMsgArg = (XMsgProcArgPtr) malloc (sizeof(XMsgProcArgRec));
-
-  /* Bail if the input parameters are bad */
-  if (pArg == NULL || pWMInfo == NULL)
-    {
-      ErrorF ("winInitWM - malloc failed.\n");
-      return FALSE;
-    }
-  
-  /* Zero the allocated memory */
-  ZeroMemory (pArg, sizeof (WMProcArgRec));
-  ZeroMemory (pWMInfo, sizeof (WMInfoRec));
-  ZeroMemory (pXMsgArg, sizeof (XMsgProcArgRec));
-
-  /* Set a return pointer to the Window Manager info structure */
-  *ppWMInfo = pWMInfo;
-  pWMInfo->fAllowOtherWM = allowOtherWM;
-
-  /* Setup the argument structure for the thread function */
-  pArg->dwScreen = dwScreen;
-  pArg->pWMInfo = pWMInfo;
-  pArg->ppmServerStarted = ppmServerStarted;
-  
-  /* Intialize the message queue */
-  if (!InitQueue (&pWMInfo->wmMsgQueue))
-    {
-      ErrorF ("winInitWM - InitQueue () failed.\n");
-      return FALSE;
-    }
-  
-  /* Spawn a thread for the Window Manager */
-  if (pthread_create (ptWMProc, NULL, winMultiWindowWMProc, pArg))
-    {
-      /* Bail if thread creation failed */
-      ErrorF ("winInitWM - pthread_create failed for Window Manager.\n");
-      return FALSE;
-    }
-
-  /* Spawn the XNextEvent thread, will send messages to WM */
-  pXMsgArg->dwScreen = dwScreen;
-  pXMsgArg->pWMInfo = pWMInfo;
-  pXMsgArg->ppmServerStarted = ppmServerStarted;
-  pXMsgArg->hwndScreen = hwndScreen;
-  if (pthread_create (ptXMsgProc, NULL, winMultiWindowXMsgProc, pXMsgArg))
-    {
-      /* Bail if thread creation failed */
-      ErrorF ("winInitWM - pthread_create failed on XMSG.\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG || YES
-  winDebug ("winInitWM - Returning.\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Window manager thread - setup
- */
-
-static void
-winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg)
-{
-  int                   iRetries = 0;
-  char			pszDisplay[512];
-  int			iReturn;
-
-  ErrorF ("winInitMultiWindowWM - Hello\n");
-
-  /* Check that argument pointer is not invalid */
-  if (pProcArg == NULL)
-    {
-      ErrorF ("winInitMultiWindowWM - pProcArg is NULL.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winInitMultiWindowWM - Calling pthread_mutex_lock ()\n");
-
-  /* Grab our garbage mutex to satisfy pthread_cond_wait */
-  iReturn = pthread_mutex_lock (pProcArg->ppmServerStarted);
-  if (iReturn != 0)
-    {
-      ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () failed: %d.  "
-	      "Exiting.\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () returned.\n");
-
-  /* Allow multiple threads to access Xlib */
-  if (XInitThreads () == 0)
-    {
-      ErrorF ("winInitMultiWindowWM - XInitThreads () failed.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* See if X supports the current locale */
-  if (XSupportsLocale () == False)
-    {
-      ErrorF ("winInitMultiWindowWM - Warning: Locale not supported by X.\n");
-    }
-
-  /* Release the server started mutex */
-  pthread_mutex_unlock (pProcArg->ppmServerStarted);
-
-  ErrorF ("winInitMultiWindowWM - pthread_mutex_unlock () returned.\n");
-
-  /* Set jump point for IO Error exits */
-  iReturn = setjmp (g_jmpWMEntry);
-  
-  /* Check if we should continue operations */
-  if (iReturn != WIN_JMP_ERROR_IO
-      && iReturn != WIN_JMP_OKAY)
-    {
-      /* setjmp returned an unknown value, exit */
-      ErrorF ("winInitMultiWindowWM - setjmp returned: %d.  Exiting.\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-  else if (iReturn == WIN_JMP_ERROR_IO)
-    {
-      ErrorF ("winInitMultiWindowWM - Caught IO Error.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Install our error handler */
-  XSetErrorHandler (winMultiWindowWMErrorHandler);
-  XSetIOErrorHandler (winMultiWindowWMIOErrorHandler);
-
-  /* Setup the display connection string x */
-  snprintf (pszDisplay,
-	    512,
-	    "127.0.0.1:%s.%d",
-	    display,
-	    (int) pProcArg->dwScreen);
-
-  /* Print the display connection string */
-  ErrorF ("winInitMultiWindowWM - DISPLAY=%s\n", pszDisplay);
-
-  /* Use our generated cookie for authentication */
-  winSetAuthorization();
-
-  /* Open the X display */
-  do
-    {
-      /* Try to open the display */
-      pWMInfo->pDisplay = XOpenDisplay (pszDisplay);
-      if (pWMInfo->pDisplay == NULL)
-	{
-	  ErrorF ("winInitMultiWindowWM - Could not open display, try: %d, "
-		  "sleeping: %d\n\f",
-		  iRetries + 1, WIN_CONNECT_DELAY);
-	  ++iRetries;
-	  sleep (WIN_CONNECT_DELAY);
-	  continue;
-	}
-      else
-	break;
-    }
-  while (pWMInfo->pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
-  
-  /* Make sure that the display opened */
-  if (pWMInfo->pDisplay == NULL)
-    {
-      ErrorF ("winInitMultiWindowWM - Failed opening the display.  "
-	      "Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winInitMultiWindowWM - XOpenDisplay () returned and "
-	  "successfully opened the display.\n");
-  
-
-  /* Create some atoms */
-  pWMInfo->atmWmProtos = XInternAtom (pWMInfo->pDisplay,
-				      "WM_PROTOCOLS",
-				      False);
-  pWMInfo->atmWmDelete = XInternAtom (pWMInfo->pDisplay,
-				      "WM_DELETE_WINDOW",
-				      False);
-
-  pWMInfo->atmPrivMap  = XInternAtom (pWMInfo->pDisplay,
-				      WINDOWSWM_NATIVE_HWND,
-				      False);
-
-
-  if (1) {
-    Cursor cursor = XCreateFontCursor (pWMInfo->pDisplay, XC_left_ptr);
-    if (cursor)
-    {
-      XDefineCursor (pWMInfo->pDisplay, DefaultRootWindow(pWMInfo->pDisplay), cursor);
-      XFreeCursor (pWMInfo->pDisplay, cursor);
-    }
-  }
-}
-
-
-/*
- * winSendMessageToWM - Send a message from the X thread to the WM thread
- */
-
-void
-winSendMessageToWM (void *pWMInfo, winWMMessagePtr pMsg)
-{
-  WMMsgNodePtr pNode;
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winSendMessageToWM ()\n");
-#endif
-  
-  pNode = (WMMsgNodePtr)malloc(sizeof(WMMsgNodeRec));
-  if (pNode != NULL)
-    {
-      memcpy (&pNode->msg, pMsg, sizeof(winWMMessageRec));
-      PushMessage (&((WMInfoPtr)pWMInfo)->wmMsgQueue, pNode);
-    }
-}
-
-
-/*
- * Window manager error handler
- */
-
-static int
-winMultiWindowWMErrorHandler (Display *pDisplay, XErrorEvent *pErr)
-{
-  char pszErrorMsg[100];
-
-  if (pErr->request_code == X_ChangeWindowAttributes
-      && pErr->error_code == BadAccess)
-    {
-      ErrorF ("winMultiWindowWMErrorHandler - ChangeWindowAttributes "
-	      "BadAccess.\n");
-      return 0;
-    }
-  
-  XGetErrorText (pDisplay,
-		 pErr->error_code,
-		 pszErrorMsg,
-		 sizeof (pszErrorMsg));
-  ErrorF ("winMultiWindowWMErrorHandler - ERROR: %s\n", pszErrorMsg);
-
-  return 0;
-}
-
-
-/*
- * Window manager IO error handler
- */
-
-static int
-winMultiWindowWMIOErrorHandler (Display *pDisplay)
-{
-  ErrorF ("\nwinMultiWindowWMIOErrorHandler!\n\n");
-
-  if (g_shutdown)
-    pthread_exit(NULL);
-
-  /* Restart at the main entry point */
-  longjmp (g_jmpWMEntry, WIN_JMP_ERROR_IO);
-  
-  return 0;
-}
-
-
-/*
- * X message procedure error handler
- */
-
-static int
-winMultiWindowXMsgProcErrorHandler (Display *pDisplay, XErrorEvent *pErr)
-{
-  char pszErrorMsg[100];
-  
-  XGetErrorText (pDisplay,
-		 pErr->error_code,
-		 pszErrorMsg,
-		 sizeof (pszErrorMsg));
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winMultiWindowXMsgProcErrorHandler - ERROR: %s\n", pszErrorMsg);
-#endif
-  
-  return 0;
-}
-
-
-/*
- * X message procedure IO error handler
- */
-
-static int
-winMultiWindowXMsgProcIOErrorHandler (Display *pDisplay)
-{
-  ErrorF ("\nwinMultiWindowXMsgProcIOErrorHandler!\n\n");
-
-  /* Restart at the main entry point */
-  longjmp (g_jmpXMsgProcEntry, WIN_JMP_ERROR_IO);
-  
-  return 0;
-}
-
-
-/*
- * Catch RedirectError to detect other window manager running
- */
-
-static int
-winRedirectErrorHandler (Display *pDisplay, XErrorEvent *pErr)
-{
-  redirectError = TRUE;
-  return 0;
-}
-
-
-/*
- * Check if another window manager is running
- */
-
-static Bool
-CheckAnotherWindowManager (Display *pDisplay, DWORD dwScreen, Bool fAllowOtherWM)
-{
-  /*
-    Try to select the events which only one client at a time is allowed to select.
-    If this causes an error, another window manager is already running...
-   */
-  redirectError = FALSE;
-  XSetErrorHandler (winRedirectErrorHandler);
-  XSelectInput(pDisplay, RootWindow (pDisplay, dwScreen),
-               ResizeRedirectMask | SubstructureRedirectMask | ButtonPressMask);
-  XSync (pDisplay, 0);
-  XSetErrorHandler (winMultiWindowXMsgProcErrorHandler);
-
-  /*
-    Side effect: select the events we are actually interested in...
-
-    If other WMs are not allowed, also select one of the events which only one client
-    at a time is allowed to select, so other window managers won't start...
-  */
-  XSelectInput(pDisplay, RootWindow (pDisplay, dwScreen),
-               SubstructureNotifyMask | ( !fAllowOtherWM ? ButtonPressMask : 0));
-  XSync (pDisplay, 0);
-  return redirectError;
-}
-
-/*
- * Notify the MWM thread we're exiting and not to reconnect
- */
-
-void
-winDeinitMultiWindowWM (void)
-{
-  ErrorF ("winDeinitMultiWindowWM - Noting shutdown in progress\n");
-  g_shutdown = TRUE;
-}
-
-/* Windows window styles */
-#define HINT_NOFRAME	(1l<<0)
-#define HINT_BORDER	(1L<<1)
-#define HINT_SIZEBOX	(1l<<2)
-#define HINT_CAPTION	(1l<<3)
-#define HINT_NOMAXIMIZE (1L<<4)
-/* These two are used on their own */
-#define HINT_MAX	(1L<<0)
-#define HINT_MIN	(1L<<1)
-
-static void
-winApplyHints (Display *pDisplay, Window iWindow, HWND hWnd, HWND *zstyle)
-{
-  static Atom		windowState, motif_wm_hints, windowType;
-  static Atom		hiddenState, fullscreenState, belowState, aboveState;
-  static Atom		dockWindow;
-  static int		generation;
-  Atom			type, *pAtom = NULL;
-  int			format;
-  unsigned long		hint = 0, maxmin = 0, style, nitems = 0 , left = 0;
-  WindowPtr		pWin = GetProp (hWnd, WIN_WINDOW_PROP);
-
-  if (!hWnd) return;
-  if (!IsWindow (hWnd)) return;
-
-  if (generation != serverGeneration) {
-      generation = serverGeneration;
-      windowState = XInternAtom(pDisplay, "_NET_WM_STATE", False);
-      motif_wm_hints = XInternAtom(pDisplay, "_MOTIF_WM_HINTS", False);
-      windowType = XInternAtom(pDisplay, "_NET_WM_WINDOW_TYPE", False);
-      hiddenState = XInternAtom(pDisplay, "_NET_WM_STATE_HIDDEN", False);
-      fullscreenState = XInternAtom(pDisplay, "_NET_WM_STATE_FULLSCREEN", False);
-      belowState = XInternAtom(pDisplay, "_NET_WM_STATE_BELOW", False);
-      aboveState = XInternAtom(pDisplay, "_NET_WM_STATE_ABOVE", False);
-      dockWindow = XInternAtom(pDisplay, "_NET_WM_WINDOW_TYPE_DOCK", False);
-  }
-
-  if (XGetWindowProperty(pDisplay, iWindow, windowState, 0L,
-			 1L, False, XA_ATOM, &type, &format,
-			 &nitems, &left, (unsigned char **)&pAtom) == Success)
-  {
-    if (pAtom && nitems == 1)
-    {
-      if (*pAtom == hiddenState) maxmin |= HINT_MIN;
-      else if (*pAtom == fullscreenState) maxmin |= HINT_MAX;
-      if (*pAtom == belowState) *zstyle = HWND_BOTTOM;
-      else if (*pAtom == aboveState) *zstyle = HWND_TOPMOST;
-    }
-    if (pAtom) XFree(pAtom);
-  }
-
-  nitems = left = 0;
-  MwmHints *mwm_hint = NULL;
-  if (XGetWindowProperty(pDisplay, iWindow, motif_wm_hints, 0L,
-			 PropMwmHintsElements, False, motif_wm_hints, &type, &format,
-			 &nitems, &left, (unsigned char **)&mwm_hint) == Success)
-  {
-    if (mwm_hint && nitems == PropMwmHintsElements && (mwm_hint->flags & MwmHintsDecorations))
-    {
-      if (!mwm_hint->decorations) hint |= HINT_NOFRAME;
-      else if (!(mwm_hint->decorations & MwmDecorAll))
-      {
-	if (mwm_hint->decorations & MwmDecorBorder) hint |= HINT_BORDER;
-	if (mwm_hint->decorations & MwmDecorHandle) hint |= HINT_SIZEBOX;
-	if (mwm_hint->decorations & MwmDecorTitle) hint |= HINT_CAPTION;
-      }
-    }
-    if (mwm_hint) XFree(mwm_hint);
-  }
-
-  nitems = left = 0;
-  pAtom = NULL;
-  if (XGetWindowProperty(pDisplay, iWindow, windowType, 0L,
-			 1L, False, XA_ATOM, &type, &format,
-			 &nitems, &left, (unsigned char **)&pAtom) == Success)
-  {
-    if (pAtom && nitems == 1)
-    {
-      if (*pAtom == dockWindow)
-      {
-	hint = (hint & ~HINT_NOFRAME) | HINT_SIZEBOX; /* Xming puts a sizebox on dock windows */
-	*zstyle = HWND_TOPMOST;
-      }
-    }
-    if (pAtom) XFree(pAtom);
-  }
-
-  {
-    XSizeHints *normal_hint = XAllocSizeHints();
-    long supplied;
-    if (normal_hint && (XGetWMNormalHints(pDisplay, iWindow, normal_hint, &supplied) == Success))
-      {
-        if (normal_hint->flags & PMaxSize)
-          {
-            /* Not maximizable if a maximum size is specified */
-            hint |= HINT_NOMAXIMIZE;
-
-            if (normal_hint->flags & PMinSize)
-              {
-                /*
-                  If both minimum size and maximum size are specified and are the same,
-                  don't bother with a resizing frame
-                */
-                if ((normal_hint->min_width == normal_hint->max_width)
-                    && (normal_hint->min_height == normal_hint->max_height))
-                  hint = (hint & ~HINT_SIZEBOX);
-              }
-          }
-      }
-    XFree(normal_hint);
-  }
-
-  /* Override hint settings from above with settings from config file */
-  style = winOverrideStyle((unsigned long)pWin);
-  if (style & STYLE_TOPMOST) *zstyle = HWND_TOPMOST;
-  else if (style & STYLE_MAXIMIZE) maxmin = (hint & ~HINT_MIN) | HINT_MAX;
-  else if (style & STYLE_MINIMIZE) maxmin = (hint & ~HINT_MAX) | HINT_MIN;
-  else if (style & STYLE_BOTTOM) *zstyle = HWND_BOTTOM;
-
-  if (maxmin & HINT_MAX) SendMessage(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
-  else if (maxmin & HINT_MIN) SendMessage(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
-
-  if (style & STYLE_NOTITLE)
-	hint = (hint & ~HINT_NOFRAME & ~HINT_BORDER & ~HINT_CAPTION) | HINT_SIZEBOX;
-  else if (style & STYLE_OUTLINE)
-	hint = (hint & ~HINT_NOFRAME & ~HINT_SIZEBOX & ~HINT_CAPTION) | HINT_BORDER;
-  else if (style & STYLE_NOFRAME)
-	hint = (hint & ~HINT_BORDER & ~HINT_CAPTION & ~HINT_SIZEBOX) | HINT_NOFRAME;
-
-  /* Now apply styles to window */
-  style = GetWindowLongPtr(hWnd, GWL_STYLE) & ~WS_CAPTION & ~WS_SIZEBOX; /* Just in case */
-  if (!style) return;
-
-  if (!hint) /* All on */
-    style = style | WS_CAPTION | WS_SIZEBOX;
-  else if (hint & HINT_NOFRAME) /* All off */
-    style = style & ~WS_CAPTION & ~WS_SIZEBOX;
-  else style = style | ((hint & HINT_BORDER) ? WS_BORDER : 0) |
-		((hint & HINT_SIZEBOX) ? WS_SIZEBOX : 0) |
-		((hint & HINT_CAPTION) ? WS_CAPTION : 0);
-
-  if (hint & HINT_NOMAXIMIZE)
-    style = style & ~WS_MAXIMIZEBOX;
-
-  SetWindowLongPtr (hWnd, GWL_STYLE, style);
-}
-
-void
-winUpdateWindowPosition (HWND hWnd, Bool reshape, HWND *zstyle)
-{
-  int iX, iY, iWidth, iHeight;
-  int	iDx, iDy;
-  RECT	rcNew;
-  WindowPtr	pWin = GetProp (hWnd, WIN_WINDOW_PROP);
-  DrawablePtr	pDraw = NULL;
-
-  if (!pWin) return;
-  pDraw = &pWin->drawable;
-  if (!pDraw) return;
-
-  /* Get the X and Y location of the X window */
-  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
-  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
-
-  /* Get the height and width of the X window */
-  iWidth = pWin->drawable.width;
-  iHeight = pWin->drawable.height;
-
-  /* Setup a rectangle with the X window position and size */
-  SetRect (&rcNew, iX, iY, iX + iWidth, iY + iHeight);
-
-#if 0
-  ErrorF ("winUpdateWindowPosition - (%d, %d)-(%d, %d)\n",
-	  rcNew.left, rcNew.top,
-	  rcNew.right, rcNew.bottom);
-#endif
-
-  AdjustWindowRectEx (&rcNew, GetWindowLongPtr (hWnd, GWL_STYLE), FALSE, WS_EX_APPWINDOW);
-
-  /* Don't allow window decoration to disappear off to top-left as a result of this adjustment */
-  if (rcNew.left < GetSystemMetrics(SM_XVIRTUALSCREEN))
-    {
-      iDx = GetSystemMetrics(SM_XVIRTUALSCREEN) - rcNew.left;
-      rcNew.left += iDx;
-      rcNew.right += iDx;
-    }
-
-  if (rcNew.top < GetSystemMetrics(SM_YVIRTUALSCREEN))
-    {
-      iDy = GetSystemMetrics(SM_YVIRTUALSCREEN) - rcNew.top;
-      rcNew.top += iDy;
-      rcNew.bottom += iDy;
-    }
-
-#if 0
-  ErrorF ("winUpdateWindowPosition - (%d, %d)-(%d, %d)\n",
-	  rcNew.left, rcNew.top,
-	  rcNew.right, rcNew.bottom);
-#endif
-
-  /* Position the Windows window */
-  SetWindowPos (hWnd, *zstyle, rcNew.left, rcNew.top,
-	rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
-	0);
-
-  if (reshape)
-  {
-    winReshapeMultiWindow(pWin);
-    winUpdateRgnMultiWindow(pWin);
-  }
-}
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *Copyright (C) Colin Harrison 2005-2009
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ *              Colin Harrison
+ */
+
+/* X headers */
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#ifdef __CYGWIN__
+#include <sys/select.h>
+#endif
+#include <fcntl.h>
+#include <setjmp.h>
+#define HANDLE void *
+#include <pthread.h>
+#undef HANDLE
+#include <X11/X.h>
+#include <X11/Xatom.h>
+#include <X11/Xlib.h>
+#include <X11/Xlocale.h>
+#include <X11/Xproto.h>
+#include <X11/Xutil.h>
+#include <X11/cursorfont.h>
+#include <X11/Xwindows.h>
+
+/* Local headers */
+#include "objbase.h"
+#include "ddraw.h"
+#include "winwindow.h"
+#include "winprefs.h"
+#include "window.h"
+#include "pixmapstr.h"
+#include "windowstr.h"
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+#include <X11/extensions/windowswmstr.h>
+#else
+/* We need the native HWND atom for intWM, so for consistency use the
+   same name as extWM would if we were building with enabled... */
+#define WINDOWSWM_NATIVE_HWND "_WINDOWSWM_NATIVE_HWND"
+#endif
+
+extern void winDebug(const char *format, ...);
+extern void winReshapeMultiWindow(WindowPtr pWin);
+extern void winUpdateRgnMultiWindow(WindowPtr pWin);
+
+#ifndef CYGDEBUG
+#define CYGDEBUG NO
+#endif
+
+/*
+ * Constant defines
+ */
+
+#define WIN_CONNECT_RETRIES	5
+#define WIN_CONNECT_DELAY	5
+#ifdef HAS_DEVWINDOWS
+# define WIN_MSG_QUEUE_FNAME	"/dev/windows"
+#endif
+#define WIN_JMP_OKAY		0
+#define WIN_JMP_ERROR_IO	2
+
+/*
+ * Local structures
+ */
+
+typedef struct _WMMsgNodeRec {
+  winWMMessageRec	msg;
+  struct _WMMsgNodeRec	*pNext;
+} WMMsgNodeRec, *WMMsgNodePtr;
+
+typedef struct _WMMsgQueueRec {
+  struct _WMMsgNodeRec	*pHead;
+  struct _WMMsgNodeRec	*pTail;
+  pthread_mutex_t	pmMutex;
+  pthread_cond_t	pcNotEmpty;
+  int			nQueueSize;
+} WMMsgQueueRec, *WMMsgQueuePtr;
+
+typedef struct _WMInfo {
+  Display		*pDisplay;
+  WMMsgQueueRec		wmMsgQueue;
+  Atom			atmWmProtos;
+  Atom			atmWmDelete;
+  Atom			atmPrivMap;
+  Bool			fAllowOtherWM;
+} WMInfoRec, *WMInfoPtr;
+
+typedef struct _WMProcArgRec {
+  DWORD			dwScreen;
+  WMInfoPtr		pWMInfo;
+  pthread_mutex_t	*ppmServerStarted;
+} WMProcArgRec, *WMProcArgPtr;
+
+typedef struct _XMsgProcArgRec {
+  Display		*pDisplay;
+  DWORD			dwScreen;
+  WMInfoPtr		pWMInfo;
+  pthread_mutex_t	*ppmServerStarted;
+  HWND			hwndScreen;
+} XMsgProcArgRec, *XMsgProcArgPtr;
+
+
+/*
+ * References to external symbols
+ */
+
+extern char *display;
+extern void ErrorF (const char* /*f*/, ...);
+
+/*
+ * Prototypes for local functions
+ */
+
+static void
+PushMessage (WMMsgQueuePtr pQueue, WMMsgNodePtr pNode);
+
+static WMMsgNodePtr
+PopMessage (WMMsgQueuePtr pQueue, WMInfoPtr pWMInfo);
+
+static Bool
+InitQueue (WMMsgQueuePtr pQueue);
+
+static void
+GetWindowName (Display * pDpy, Window iWin, wchar_t **ppName);
+
+static int
+SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData);
+
+static void
+UpdateName (WMInfoPtr pWMInfo, Window iWindow);
+
+static void*
+winMultiWindowWMProc (void* pArg);
+
+static int
+winMultiWindowWMErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static int
+winMultiWindowWMIOErrorHandler (Display *pDisplay);
+
+static void *
+winMultiWindowXMsgProc (void *pArg);
+
+static int
+winMultiWindowXMsgProcErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static int
+winMultiWindowXMsgProcIOErrorHandler (Display *pDisplay);
+
+static int
+winRedirectErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static void
+winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg);
+
+#if 0
+static void
+PreserveWin32Stack(WMInfoPtr pWMInfo, Window iWindow, UINT direction);
+#endif
+
+static Bool
+CheckAnotherWindowManager (Display *pDisplay, DWORD dwScreen, Bool fAllowOtherWM);
+
+static void
+winApplyHints (Display *pDisplay, Window iWindow, HWND hWnd, HWND *zstyle);
+
+void
+winUpdateWindowPosition (HWND hWnd, Bool reshape, HWND *zstyle);
+
+/*
+ * Local globals
+ */
+
+static jmp_buf			g_jmpWMEntry;
+static jmp_buf			g_jmpXMsgProcEntry;
+static Bool			g_shutdown = FALSE;
+static Bool			redirectError = FALSE;
+static Bool			g_fAnotherWMRunning = FALSE;
+
+/*
+ * PushMessage - Push a message onto the queue
+ */
+
+static void
+PushMessage (WMMsgQueuePtr pQueue, WMMsgNodePtr pNode)
+{
+
+  /* Lock the queue mutex */
+  pthread_mutex_lock (&pQueue->pmMutex);
+
+  pNode->pNext = NULL;
+  
+  if (pQueue->pTail != NULL)
+    {
+      pQueue->pTail->pNext = pNode;
+    }
+  pQueue->pTail = pNode;
+  
+  if (pQueue->pHead == NULL)
+    {
+      pQueue->pHead = pNode;
+    }
+
+
+#if 0
+  switch (pNode->msg.msg)
+    {
+    case WM_WM_MOVE:
+      ErrorF ("\tWM_WM_MOVE\n");
+      break;
+    case WM_WM_SIZE:
+      ErrorF ("\tWM_WM_SIZE\n");
+      break;
+    case WM_WM_RAISE:
+      ErrorF ("\tWM_WM_RAISE\n");
+      break;
+    case WM_WM_LOWER:
+      ErrorF ("\tWM_WM_LOWER\n");
+      break;
+    case WM_WM_MAP:
+      ErrorF ("\tWM_WM_MAP\n");
+      break;
+    case WM_WM_MAP2:
+      ErrorF ("\tWM_WM_MAP2\n");
+      break;
+    case WM_WM_MAP3:
+      ErrorF ("\tWM_WM_MAP3\n");
+      break;
+    case WM_WM_UNMAP:
+      ErrorF ("\tWM_WM_UNMAP\n");
+      break;
+    case WM_WM_KILL:
+      ErrorF ("\tWM_WM_KILL\n");
+      break;
+    case WM_WM_ACTIVATE:
+      ErrorF ("\tWM_WM_ACTIVATE\n");
+      break;
+    default:
+      ErrorF ("\tUnknown Message.\n");
+      break;
+    }
+#endif
+
+  /* Increase the count of elements in the queue by one */
+  ++(pQueue->nQueueSize);
+
+  /* Release the queue mutex */
+  pthread_mutex_unlock (&pQueue->pmMutex);
+
+  /* Signal that the queue is not empty */
+  pthread_cond_signal (&pQueue->pcNotEmpty);
+}
+
+
+#if CYGMULTIWINDOW_DEBUG
+/*
+ * QueueSize - Return the size of the queue
+ */
+
+static int
+QueueSize (WMMsgQueuePtr pQueue)
+{
+  WMMsgNodePtr		pNode;
+  int			nSize = 0;
+  
+  /* Loop through all elements in the queue */
+  for (pNode = pQueue->pHead; pNode != NULL; pNode = pNode->pNext)
+    ++nSize;
+
+  return nSize;
+}
+#endif
+
+
+/*
+ * PopMessage - Pop a message from the queue
+ */
+
+static WMMsgNodePtr
+PopMessage (WMMsgQueuePtr pQueue, WMInfoPtr pWMInfo)
+{
+  WMMsgNodePtr		pNode;
+
+  /* Lock the queue mutex */
+  pthread_mutex_lock (&pQueue->pmMutex);
+
+  /* Wait for --- */
+  while (pQueue->pHead == NULL)
+    {
+      pthread_cond_wait (&pQueue->pcNotEmpty, &pQueue->pmMutex);
+    }
+  
+  pNode = pQueue->pHead;
+  if (pQueue->pHead != NULL)
+    {
+      pQueue->pHead = pQueue->pHead->pNext;
+    }
+
+  if (pQueue->pTail == pNode)
+    {
+      pQueue->pTail = NULL;
+    }
+
+  /* Drop the number of elements in the queue by one */
+  --(pQueue->nQueueSize);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("Queue Size %d %d\n", pQueue->nQueueSize, QueueSize(pQueue));
+#endif
+  
+  /* Release the queue mutex */
+  pthread_mutex_unlock (&pQueue->pmMutex);
+
+  return pNode;
+}
+
+
+#if 0
+/*
+ * HaveMessage - 
+ */
+
+static Bool
+HaveMessage (WMMsgQueuePtr pQueue, UINT msg, Window iWindow)
+{
+  WMMsgNodePtr pNode;
+  
+  for (pNode = pQueue->pHead; pNode != NULL; pNode = pNode->pNext)
+    {
+      if (pNode->msg.msg==msg && pNode->msg.iWindow==iWindow)
+	return True;
+    }
+  
+  return False;
+}
+#endif
+
+
+/*
+ * InitQueue - Initialize the Window Manager message queue
+ */
+
+static
+Bool
+InitQueue (WMMsgQueuePtr pQueue)
+{
+  /* Check if the pQueue pointer is NULL */
+  if (pQueue == NULL)
+    {
+      ErrorF ("InitQueue - pQueue is NULL.  Exiting.\n");
+      return FALSE;
+    }
+
+  /* Set the head and tail to NULL */
+  pQueue->pHead = NULL;
+  pQueue->pTail = NULL;
+
+  /* There are no elements initially */
+  pQueue->nQueueSize = 0;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("InitQueue - Queue Size %d %d\n", pQueue->nQueueSize,
+	  QueueSize(pQueue));
+#endif
+
+  ErrorF ("InitQueue - Calling pthread_mutex_init\n");
+
+  /* Create synchronization objects */
+  pthread_mutex_init (&pQueue->pmMutex, NULL);
+
+  ErrorF ("InitQueue - pthread_mutex_init returned\n");
+  ErrorF ("InitQueue - Calling pthread_cond_init\n");
+
+  pthread_cond_init (&pQueue->pcNotEmpty, NULL);
+
+  ErrorF ("InitQueue - pthread_cond_init returned\n");
+
+  return TRUE;
+}
+
+
+/*
+ * GetWindowName - Retrieve the title of an X Window
+ */
+
+static void
+GetWindowName (Display *pDisplay, Window iWin, wchar_t **ppName)
+{
+  int			nResult, nNum;
+  char			**ppList;
+  char			*pszReturnData;
+  int			iLen, i;
+  XTextProperty		xtpName;
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("GetWindowName\n");
+#endif
+
+  /* Intialize ppName to NULL */
+  *ppName = NULL;
+
+  /* Try to get --- */
+  nResult = XGetWMName (pDisplay, iWin, &xtpName);
+  if (!nResult || !xtpName.value || !xtpName.nitems)
+    {
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("GetWindowName - XGetWMName failed.  No name.\n");
+#endif
+      return;
+    }
+
+   if (Xutf8TextPropertyToTextList (pDisplay, &xtpName, &ppList, &nNum) >= Success && nNum > 0 && *ppList)
+   {
+ 	iLen = 0;
+ 	for (i = 0; i < nNum; i++) iLen += strlen(ppList[i]);
+ 	pszReturnData = (char *) malloc (iLen + 1);
+ 	pszReturnData[0] = '\0';
+ 	for (i = 0; i < nNum; i++) strcat (pszReturnData, ppList[i]);
+ 	if (ppList) XFreeStringList (ppList);
+   }
+   else
+   {
+ 	pszReturnData = (char *) malloc (1);
+ 	pszReturnData[0] = '\0';
+   }
+   iLen = MultiByteToWideChar (CP_UTF8, 0, pszReturnData, -1, NULL, 0);
+   *ppName = (wchar_t*)malloc(sizeof(wchar_t)*(iLen + 1));
+   MultiByteToWideChar (CP_UTF8, 0, pszReturnData, -1, *ppName, iLen);
+   XFree (xtpName.value);
+   free (pszReturnData);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("GetWindowName - Returning\n");
+#endif
+}
+
+
+/*
+ * Send a message to the X server from the WM thread
+ */
+
+static int
+SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData)
+{
+  XEvent		e;
+
+  /* Prepare the X event structure */
+  e.type = ClientMessage;
+  e.xclient.window = iWin;
+  e.xclient.message_type = atmType;
+  e.xclient.format = 32;
+  e.xclient.data.l[0] = nData;
+  e.xclient.data.l[1] = CurrentTime;
+
+  /* Send the event to X */
+  return XSendEvent (pDisplay, iWin, False, NoEventMask, &e);
+}
+
+
+/*
+ * Updates the name of a HWND according to its X WM_NAME property
+ */
+
+static void
+UpdateName (WMInfoPtr pWMInfo, Window iWindow)
+{
+  wchar_t		*pszName;
+  Atom			atmType;
+  int			fmtRet;
+  unsigned long		items, remain;
+  HWND			*retHwnd, hWnd;
+  XWindowAttributes	attr;
+
+  hWnd = 0;
+
+  /* See if we can get the cached HWND for this window... */
+  if (XGetWindowProperty (pWMInfo->pDisplay,
+			  iWindow,
+			  pWMInfo->atmPrivMap,
+			  0,
+			  1,
+			  False,
+			  XA_INTEGER,//pWMInfo->atmPrivMap,
+			  &atmType,
+			  &fmtRet,
+			  &items,
+			  &remain,
+			  (unsigned char **) &retHwnd) == Success)
+    {
+      if (retHwnd)
+	{
+	  hWnd = *retHwnd;
+	  XFree (retHwnd);
+	}
+    }
+  
+  /* Some sanity checks */
+  if (!hWnd) return;
+  if (!IsWindow (hWnd)) return;
+
+  /* Set the Windows window name */
+  GetWindowName (pWMInfo->pDisplay, iWindow, &pszName);
+  if (pszName)
+    {
+      /* Get the window attributes */
+      XGetWindowAttributes (pWMInfo->pDisplay,
+			    iWindow,
+			    &attr);
+      if (!attr.override_redirect)
+	{
+	  SetWindowTextW (hWnd, pszName);
+	  winUpdateIcon (iWindow);
+	}
+
+      free (pszName);
+    }
+}
+
+
+#if 0
+/*
+ * Fix up any differences between the X11 and Win32 window stacks
+ * starting at the window passed in
+ */
+static void
+PreserveWin32Stack(WMInfoPtr pWMInfo, Window iWindow, UINT direction)
+{
+  Atom                  atmType;
+  int                   fmtRet;
+  unsigned long         items, remain;
+  HWND                  hWnd, *retHwnd;
+  DWORD                 myWinProcID, winProcID;
+  Window                xWindow;
+  WINDOWPLACEMENT       wndPlace;
+  
+  hWnd = NULL;
+  /* See if we can get the cached HWND for this window... */
+  if (XGetWindowProperty (pWMInfo->pDisplay,
+			  iWindow,
+			  pWMInfo->atmPrivMap,
+			  0,
+			  1,
+			  False,
+			  XA_INTEGER,//pWMInfo->atmPrivMap,
+			  &atmType,
+			  &fmtRet,
+			  &items,
+			  &remain,
+			  (unsigned char **) &retHwnd) == Success)
+    {
+      if (retHwnd)
+	{
+	  hWnd = *retHwnd;
+	  XFree (retHwnd);
+	}
+    }
+  
+  if (!hWnd) return;
+  
+  GetWindowThreadProcessId (hWnd, &myWinProcID);
+  hWnd = GetNextWindow (hWnd, direction);
+  
+  while (hWnd) {
+    GetWindowThreadProcessId (hWnd, &winProcID);
+    if (winProcID == myWinProcID)
+      {
+	wndPlace.length = sizeof(WINDOWPLACEMENT);
+	GetWindowPlacement (hWnd, &wndPlace);
+	if ( !(wndPlace.showCmd==SW_HIDE ||
+	       wndPlace.showCmd==SW_MINIMIZE) )
+	  {
+	    xWindow = (Window)GetProp (hWnd, WIN_WID_PROP);
+	    if (xWindow)
+	      {
+		if (direction==GW_HWNDPREV)
+		  XRaiseWindow (pWMInfo->pDisplay, xWindow);
+		else
+		  XLowerWindow (pWMInfo->pDisplay, xWindow);
+	      }
+	  }
+      }
+    hWnd = GetNextWindow(hWnd, direction);
+  }
+}
+#endif /* PreserveWin32Stack */
+
+
+/*
+ * winMultiWindowWMProc
+ */
+
+static void *
+winMultiWindowWMProc (void *pArg)
+{
+  WMProcArgPtr		pProcArg = (WMProcArgPtr)pArg;
+  WMInfoPtr		pWMInfo = pProcArg->pWMInfo;
+  
+  /* Initialize the Window Manager */
+  winInitMultiWindowWM (pWMInfo, pProcArg);
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winMultiWindowWMProc ()\n");
+#endif
+
+  /* Loop until we explicity break out */
+  for (;;)
+    {
+      WMMsgNodePtr	pNode;
+
+      if(g_fAnotherWMRunning)/* Another Window manager exists. */
+	{
+	  Sleep (1000);
+	  continue;
+	}
+
+      /* Pop a message off of our queue */
+      pNode = PopMessage (&pWMInfo->wmMsgQueue, pWMInfo);
+      if (pNode == NULL)
+	{
+	  /* Bail if PopMessage returns without a message */
+	  /* NOTE: Remember that PopMessage is a blocking function. */
+	  ErrorF ("winMultiWindowWMProc - Queue is Empty?  Exiting.\n");
+	  pthread_exit (NULL);
+	}
+
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("winMultiWindowWMProc - %d ms MSG: %d ID: %d\n",
+	      GetTickCount (), (int)pNode->msg.msg, (int)pNode->msg.dwID);
+#endif
+
+      /* Branch on the message type */
+      switch (pNode->msg.msg)
+	{
+#if 0
+	case WM_WM_MOVE:
+	  ErrorF ("\tWM_WM_MOVE\n");
+	  break;
+
+	case WM_WM_SIZE:
+	  ErrorF ("\tWM_WM_SIZE\n");
+	  break;
+#endif
+
+	case WM_WM_RAISE:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_RAISE\n");
+#endif
+	  /* Raise the window */
+	  XRaiseWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
+#if 0
+	  PreserveWin32Stack (pWMInfo, pNode->msg.iWindow, GW_HWNDPREV);
+#endif
+	  break;
+
+	case WM_WM_LOWER:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_LOWER\n");
+#endif
+
+	  /* Lower the window */
+	  XLowerWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_MAP:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_MAP\n");
+#endif
+	  /* Put a note as to the HWND associated with this Window */
+	  XChangeProperty (pWMInfo->pDisplay,
+			   pNode->msg.iWindow,
+			   pWMInfo->atmPrivMap,
+			   XA_INTEGER,//pWMInfo->atmPrivMap,
+			   32,
+			   PropModeReplace,
+			   (unsigned char *) &(pNode->msg.hwndWindow),
+			   1);
+	  UpdateName (pWMInfo, pNode->msg.iWindow);
+	  winUpdateIcon (pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_MAP2:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_MAP2\n");
+#endif
+	  XChangeProperty (pWMInfo->pDisplay,
+			   pNode->msg.iWindow,
+			   pWMInfo->atmPrivMap,
+			   XA_INTEGER,//pWMInfo->atmPrivMap,
+			   32,
+			   PropModeReplace,
+			   (unsigned char *) &(pNode->msg.hwndWindow),
+			   1);
+	  break;
+
+	case WM_WM_MAP3:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_MAP3\n");
+#endif
+	  /* Put a note as to the HWND associated with this Window */
+	  XChangeProperty (pWMInfo->pDisplay,
+			   pNode->msg.iWindow,
+			   pWMInfo->atmPrivMap,
+			   XA_INTEGER,//pWMInfo->atmPrivMap,
+			   32,
+			   PropModeReplace,
+			   (unsigned char *) &(pNode->msg.hwndWindow),
+			   1);
+	  UpdateName (pWMInfo, pNode->msg.iWindow);
+	  winUpdateIcon (pNode->msg.iWindow);
+	  {
+	    HWND zstyle = HWND_NOTOPMOST;
+	    winApplyHints (pWMInfo->pDisplay, pNode->msg.iWindow, pNode->msg.hwndWindow, &zstyle);
+	    winUpdateWindowPosition (pNode->msg.hwndWindow, TRUE, &zstyle);
+	  }
+	  break;
+
+	case WM_WM_UNMAP:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_UNMAP\n");
+#endif
+	  
+	  /* Unmap the window */
+	  XUnmapWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_KILL:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_KILL\n");
+#endif
+	  {
+	    int				i, n, found = 0;
+	    Atom			*protocols;
+	    
+	    /* --- */
+	    if (XGetWMProtocols (pWMInfo->pDisplay,
+				 pNode->msg.iWindow,
+				 &protocols,
+				 &n))
+	      {
+		for (i = 0; i < n; ++i)
+		  if (protocols[i] == pWMInfo->atmWmDelete)
+		    ++found;
+		
+		XFree (protocols);
+	      }
+
+	    /* --- */
+	    if (found)
+	      SendXMessage (pWMInfo->pDisplay,
+			    pNode->msg.iWindow,
+			    pWMInfo->atmWmProtos,
+			    pWMInfo->atmWmDelete);
+	    else
+	      XKillClient (pWMInfo->pDisplay,
+			   pNode->msg.iWindow);
+	  }
+	  break;
+
+	case WM_WM_ACTIVATE:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_ACTIVATE\n");
+#endif
+	  
+	  /* Set the input focus */
+	  XSetInputFocus (pWMInfo->pDisplay,
+			  pNode->msg.iWindow,
+			  RevertToPointerRoot,
+			  CurrentTime);
+	  break;
+
+	case WM_WM_NAME_EVENT:
+	  UpdateName (pWMInfo, pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_HINTS_EVENT:
+	  winUpdateIcon (pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_CHANGE_STATE:
+	  /* Minimize the window in Windows */
+	  winMinimizeWindow (pNode->msg.iWindow);
+	  break;
+
+	default:
+	  ErrorF ("winMultiWindowWMProc - Unknown Message.  Exiting.\n");
+	  pthread_exit (NULL);
+	  break;
+	}
+
+      /* Free the retrieved message */
+      free (pNode);
+
+      /* Flush any pending events on our display */
+      XFlush (pWMInfo->pDisplay);
+    }
+
+  /* Free the condition variable */
+  pthread_cond_destroy (&pWMInfo->wmMsgQueue.pcNotEmpty);
+  
+  /* Free the mutex variable */
+  pthread_mutex_destroy (&pWMInfo->wmMsgQueue.pmMutex);
+  
+  /* Free the passed-in argument */
+  free (pProcArg);
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF("-winMultiWindowWMProc ()\n");
+#endif
+  return NULL;
+}
+
+
+/*
+ * X message procedure
+ */
+
+static void *
+winMultiWindowXMsgProc (void *pArg)
+{
+  winWMMessageRec       msg;
+  XMsgProcArgPtr	pProcArg = (XMsgProcArgPtr) pArg;
+  char			pszDisplay[512];
+  int                   iRetries;
+  XEvent		event;
+  Atom                  atmWmName;
+  Atom                  atmWmHints;
+  Atom			atmWmChange;
+  int			iReturn;
+  XIconSize		*xis;
+
+  ErrorF ("winMultiWindowXMsgProc - Hello\n");
+
+  /* Check that argument pointer is not invalid */
+  if (pProcArg == NULL)
+    {
+      ErrorF ("winMultiWindowXMsgProc - pProcArg is NULL.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winMultiWindowXMsgProc - Calling pthread_mutex_lock ()\n");
+
+  /* Grab the server started mutex - pause until we get it */
+  iReturn = pthread_mutex_lock (pProcArg->ppmServerStarted);
+  if (iReturn != 0)
+    {
+      ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () failed: %d.  "
+	      "Exiting.\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () returned.\n");
+
+  /* Allow multiple threads to access Xlib */
+  if (XInitThreads () == 0)
+    {
+      ErrorF ("winMultiWindowXMsgProc - XInitThreads () failed.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* See if X supports the current locale */
+  if (XSupportsLocale () == False)
+    {
+      ErrorF ("winMultiWindowXMsgProc - Warning: locale not supported by X\n");
+    }
+
+  /* Release the server started mutex */
+  pthread_mutex_unlock (pProcArg->ppmServerStarted);
+
+  ErrorF ("winMultiWindowXMsgProc - pthread_mutex_unlock () returned.\n");
+
+  /* Set jump point for IO Error exits */
+  iReturn = setjmp (g_jmpXMsgProcEntry);
+  
+  /* Check if we should continue operations */
+  if (iReturn != WIN_JMP_ERROR_IO
+      && iReturn != WIN_JMP_OKAY)
+    {
+      /* setjmp returned an unknown value, exit */
+      ErrorF ("winInitMultiWindowXMsgProc - setjmp returned: %d.  Exiting.\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+  else if (iReturn == WIN_JMP_ERROR_IO)
+    {
+      ErrorF ("winInitMultiWindowXMsgProc - Caught IO Error.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Install our error handler */
+  XSetErrorHandler (winMultiWindowXMsgProcErrorHandler);
+  XSetIOErrorHandler (winMultiWindowXMsgProcIOErrorHandler);
+
+  /* Setup the display connection string x */
+  snprintf (pszDisplay,
+	    512, "127.0.0.1:%s.%d", display, (int)pProcArg->dwScreen);
+
+  /* Print the display connection string */
+  ErrorF ("winMultiWindowXMsgProc - DISPLAY=%s\n", pszDisplay);
+
+  /* Use our generated cookie for authentication */
+  winSetAuthorization();
+  
+  /* Initialize retry count */
+  iRetries = 0;
+
+  /* Open the X display */
+  do
+    {
+      /* Try to open the display */
+      pProcArg->pDisplay = XOpenDisplay (pszDisplay);
+      if (pProcArg->pDisplay == NULL)
+	{
+	  ErrorF ("winMultiWindowXMsgProc - Could not open display, try: %d, "
+		  "sleeping: %d\n",
+		  iRetries + 1, WIN_CONNECT_DELAY);
+	  ++iRetries;
+	  sleep (WIN_CONNECT_DELAY);
+	  continue;
+	}
+      else
+	break;
+    }
+  while (pProcArg->pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
+  
+  /* Make sure that the display opened */
+  if (pProcArg->pDisplay == NULL)
+    {
+      ErrorF ("winMultiWindowXMsgProc - Failed opening the display.  "
+	      "Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winMultiWindowXMsgProc - XOpenDisplay () returned and "
+	  "successfully opened the display.\n");
+
+  /* Check if another window manager is already running */
+  g_fAnotherWMRunning = CheckAnotherWindowManager (pProcArg->pDisplay, pProcArg->dwScreen, pProcArg->pWMInfo->fAllowOtherWM);
+
+  if (g_fAnotherWMRunning && !pProcArg->pWMInfo->fAllowOtherWM)
+    {
+      ErrorF ("winMultiWindowXMsgProc - "
+          "another window manager is running.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Set up the supported icon sizes */
+  xis = XAllocIconSize ();
+  if (xis)
+    {
+      xis->min_width = xis->min_height = 16;
+      xis->max_width = xis->max_height = 48;
+      xis->width_inc = xis->height_inc = 16;
+      XSetIconSizes (pProcArg->pDisplay,
+		     RootWindow (pProcArg->pDisplay, pProcArg->dwScreen),
+		     xis,
+		     1);
+      XFree (xis);
+    }
+
+  atmWmName   = XInternAtom (pProcArg->pDisplay,
+			     "WM_NAME",
+			     False);
+  atmWmHints   = XInternAtom (pProcArg->pDisplay,
+			      "WM_HINTS",
+			      False);
+  atmWmChange  = XInternAtom (pProcArg->pDisplay,
+			      "WM_CHANGE_STATE",
+			      False);
+
+  /*
+    iiimxcf had a bug until 2009-04-27, assuming that the
+    WM_STATE atom exists, causing clients to fail with
+    a BadAtom X error if it doesn't.
+
+    Since this is on in the default Solaris 10 install,
+    workaround this by making sure it does exist...
+   */
+  XInternAtom(pProcArg->pDisplay, "WM_STATE", 0);
+
+  /* Loop until we explicitly break out */
+  while (1)
+    {
+      if (g_shutdown)
+        break;
+
+      if (pProcArg->pWMInfo->fAllowOtherWM && !XPending (pProcArg->pDisplay))
+	{
+	  if (CheckAnotherWindowManager (pProcArg->pDisplay, pProcArg->dwScreen, TRUE))
+	    {
+	      if (!g_fAnotherWMRunning)
+		{
+		  g_fAnotherWMRunning = TRUE;
+		  SendMessage(*(HWND*)pProcArg->hwndScreen, WM_UNMANAGE, 0, 0);
+		}
+	    }
+	  else
+	    {
+	      if (g_fAnotherWMRunning)
+		{
+		  g_fAnotherWMRunning = FALSE;
+		  SendMessage(*(HWND*)pProcArg->hwndScreen, WM_MANAGE, 0, 0);
+		}
+	    }
+	  Sleep (500);
+	  continue;
+	}
+
+      /* Fetch next event */
+      XNextEvent (pProcArg->pDisplay, &event);
+
+      /* Branch on event type */
+      if (event.type == CreateNotify)
+	{
+	  XWindowAttributes	attr;
+
+	  XSelectInput (pProcArg->pDisplay,
+			event.xcreatewindow.window,
+			PropertyChangeMask);
+
+	  /* Get the window attributes */
+	  XGetWindowAttributes (pProcArg->pDisplay,
+				event.xcreatewindow.window,
+				&attr);
+
+	  if (!attr.override_redirect)
+	    XSetWindowBorderWidth(pProcArg->pDisplay,
+				  event.xcreatewindow.window,
+				  0);
+	}
+      else if (event.type == MapNotify)
+        {
+          /* Fake a reparentNotify event as SWT/Motif expects a
+             Window Manager to reparent a top-level window when
+             it is mapped and waits until they do.
+
+             We don't actually need to reparent, as the frame is
+             a native window, not an X window
+
+             We do this on MapNotify, not MapRequest like a real
+             Window Manager would, so we don't have do get involved
+             in actually mapping the window via it's (non-existent)
+             parent...
+
+             See sourceware bugzilla #9848
+          */
+
+          XWindowAttributes attr;
+          Window root;
+          Window parent;
+          Window *children;
+          unsigned int nchildren;
+
+          if (XGetWindowAttributes(event.xmap.display,
+                                   event.xmap.window,
+                                   &attr) &&
+              XQueryTree(event.xmap.display,
+                         event.xmap.window,
+                         &root, &parent, &children, &nchildren))
+            {
+              if (children) XFree(children);
+
+              /*
+                It's a top-level window if the parent window is a root window
+                Only non-override_redirect windows can get reparented
+              */
+              if ((attr.root == parent) && !event.xmap.override_redirect)
+                {
+                  XEvent event_send;
+
+                  event_send.type = ReparentNotify;
+                  event_send.xreparent.event = event.xmap.window;
+                  event_send.xreparent.window = event.xmap.window;
+                  event_send.xreparent.parent = parent;
+                  event_send.xreparent.x = attr.x;
+                  event_send.xreparent.y = attr.y;
+
+                  XSendEvent(event.xmap.display,
+                             event.xmap.window,
+                             True, StructureNotifyMask,
+                             &event_send);
+                }
+            }
+        }
+      else if (event.type == PropertyNotify
+	       && event.xproperty.atom == atmWmName)
+	{
+	  memset (&msg, 0, sizeof (msg));
+
+	  msg.msg = WM_WM_NAME_EVENT;
+	  msg.iWindow = event.xproperty.window;
+
+	  /* Other fields ignored */
+	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
+	}
+      else if (event.type == PropertyNotify
+	       && event.xproperty.atom == atmWmHints)
+	{
+	  memset (&msg, 0, sizeof (msg));
+
+	  msg.msg = WM_WM_HINTS_EVENT;
+	  msg.iWindow = event.xproperty.window;
+
+	  /* Other fields ignored */
+	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
+	}
+      else if (event.type == ClientMessage
+	       && event.xclient.message_type == atmWmChange
+	       && event.xclient.data.l[0] == IconicState)
+	{
+	  ErrorF ("winMultiWindowXMsgProc - WM_CHANGE_STATE - IconicState\n");
+
+	  memset (&msg, 0, sizeof (msg));
+
+	  msg.msg = WM_WM_CHANGE_STATE;
+	  msg.iWindow = event.xclient.window;
+
+	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
+	}
+    }
+
+  XCloseDisplay (pProcArg->pDisplay);
+  pthread_exit (NULL);
+  return NULL;
+}
+
+
+/*
+ * winInitWM - Entry point for the X server to spawn
+ * the Window Manager thread.  Called from
+ * winscrinit.c/winFinishScreenInitFB ().
+ */
+
+Bool
+winInitWM (void **ppWMInfo,
+	   pthread_t *ptWMProc,
+	   pthread_t *ptXMsgProc,
+	   pthread_mutex_t *ppmServerStarted,
+	   int dwScreen,
+	   HWND hwndScreen,
+	   BOOL allowOtherWM)
+{
+  WMProcArgPtr		pArg = (WMProcArgPtr) malloc (sizeof(WMProcArgRec));
+  WMInfoPtr		pWMInfo = (WMInfoPtr) malloc (sizeof(WMInfoRec));
+  XMsgProcArgPtr	pXMsgArg = (XMsgProcArgPtr) malloc (sizeof(XMsgProcArgRec));
+
+  /* Bail if the input parameters are bad */
+  if (pArg == NULL || pWMInfo == NULL)
+    {
+      ErrorF ("winInitWM - malloc failed.\n");
+      return FALSE;
+    }
+  
+  /* Zero the allocated memory */
+  ZeroMemory (pArg, sizeof (WMProcArgRec));
+  ZeroMemory (pWMInfo, sizeof (WMInfoRec));
+  ZeroMemory (pXMsgArg, sizeof (XMsgProcArgRec));
+
+  /* Set a return pointer to the Window Manager info structure */
+  *ppWMInfo = pWMInfo;
+  pWMInfo->fAllowOtherWM = allowOtherWM;
+
+  /* Setup the argument structure for the thread function */
+  pArg->dwScreen = dwScreen;
+  pArg->pWMInfo = pWMInfo;
+  pArg->ppmServerStarted = ppmServerStarted;
+  
+  /* Intialize the message queue */
+  if (!InitQueue (&pWMInfo->wmMsgQueue))
+    {
+      ErrorF ("winInitWM - InitQueue () failed.\n");
+      return FALSE;
+    }
+  
+  /* Spawn a thread for the Window Manager */
+  if (pthread_create (ptWMProc, NULL, winMultiWindowWMProc, pArg))
+    {
+      /* Bail if thread creation failed */
+      ErrorF ("winInitWM - pthread_create failed for Window Manager.\n");
+      return FALSE;
+    }
+
+  /* Spawn the XNextEvent thread, will send messages to WM */
+  pXMsgArg->dwScreen = dwScreen;
+  pXMsgArg->pWMInfo = pWMInfo;
+  pXMsgArg->ppmServerStarted = ppmServerStarted;
+  pXMsgArg->hwndScreen = hwndScreen;
+  if (pthread_create (ptXMsgProc, NULL, winMultiWindowXMsgProc, pXMsgArg))
+    {
+      /* Bail if thread creation failed */
+      ErrorF ("winInitWM - pthread_create failed on XMSG.\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG || YES
+  winDebug ("winInitWM - Returning.\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Window manager thread - setup
+ */
+
+static void
+winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg)
+{
+  int                   iRetries = 0;
+  char			pszDisplay[512];
+  int			iReturn;
+
+  ErrorF ("winInitMultiWindowWM - Hello\n");
+
+  /* Check that argument pointer is not invalid */
+  if (pProcArg == NULL)
+    {
+      ErrorF ("winInitMultiWindowWM - pProcArg is NULL.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winInitMultiWindowWM - Calling pthread_mutex_lock ()\n");
+
+  /* Grab our garbage mutex to satisfy pthread_cond_wait */
+  iReturn = pthread_mutex_lock (pProcArg->ppmServerStarted);
+  if (iReturn != 0)
+    {
+      ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () failed: %d.  "
+	      "Exiting.\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () returned.\n");
+
+  /* Allow multiple threads to access Xlib */
+  if (XInitThreads () == 0)
+    {
+      ErrorF ("winInitMultiWindowWM - XInitThreads () failed.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* See if X supports the current locale */
+  if (XSupportsLocale () == False)
+    {
+      ErrorF ("winInitMultiWindowWM - Warning: Locale not supported by X.\n");
+    }
+
+  /* Release the server started mutex */
+  pthread_mutex_unlock (pProcArg->ppmServerStarted);
+
+  ErrorF ("winInitMultiWindowWM - pthread_mutex_unlock () returned.\n");
+
+  /* Set jump point for IO Error exits */
+  iReturn = setjmp (g_jmpWMEntry);
+  
+  /* Check if we should continue operations */
+  if (iReturn != WIN_JMP_ERROR_IO
+      && iReturn != WIN_JMP_OKAY)
+    {
+      /* setjmp returned an unknown value, exit */
+      ErrorF ("winInitMultiWindowWM - setjmp returned: %d.  Exiting.\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+  else if (iReturn == WIN_JMP_ERROR_IO)
+    {
+      ErrorF ("winInitMultiWindowWM - Caught IO Error.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Install our error handler */
+  XSetErrorHandler (winMultiWindowWMErrorHandler);
+  XSetIOErrorHandler (winMultiWindowWMIOErrorHandler);
+
+  /* Setup the display connection string x */
+  snprintf (pszDisplay,
+	    512,
+	    "127.0.0.1:%s.%d",
+	    display,
+	    (int) pProcArg->dwScreen);
+
+  /* Print the display connection string */
+  ErrorF ("winInitMultiWindowWM - DISPLAY=%s\n", pszDisplay);
+
+  /* Use our generated cookie for authentication */
+  winSetAuthorization();
+
+  /* Open the X display */
+  do
+    {
+      /* Try to open the display */
+      pWMInfo->pDisplay = XOpenDisplay (pszDisplay);
+      if (pWMInfo->pDisplay == NULL)
+	{
+	  ErrorF ("winInitMultiWindowWM - Could not open display, try: %d, "
+		  "sleeping: %d\n",
+		  iRetries + 1, WIN_CONNECT_DELAY);
+	  ++iRetries;
+	  sleep (WIN_CONNECT_DELAY);
+	  continue;
+	}
+      else
+	break;
+    }
+  while (pWMInfo->pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
+  
+  /* Make sure that the display opened */
+  if (pWMInfo->pDisplay == NULL)
+    {
+      ErrorF ("winInitMultiWindowWM - Failed opening the display.  "
+	      "Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winInitMultiWindowWM - XOpenDisplay () returned and "
+	  "successfully opened the display.\n");
+  
+
+  /* Create some atoms */
+  pWMInfo->atmWmProtos = XInternAtom (pWMInfo->pDisplay,
+				      "WM_PROTOCOLS",
+				      False);
+  pWMInfo->atmWmDelete = XInternAtom (pWMInfo->pDisplay,
+				      "WM_DELETE_WINDOW",
+				      False);
+
+  pWMInfo->atmPrivMap  = XInternAtom (pWMInfo->pDisplay,
+				      WINDOWSWM_NATIVE_HWND,
+				      False);
+
+
+  if (1) {
+    Cursor cursor = XCreateFontCursor (pWMInfo->pDisplay, XC_left_ptr);
+    if (cursor)
+    {
+      XDefineCursor (pWMInfo->pDisplay, DefaultRootWindow(pWMInfo->pDisplay), cursor);
+      XFreeCursor (pWMInfo->pDisplay, cursor);
+    }
+  }
+}
+
+
+/*
+ * winSendMessageToWM - Send a message from the X thread to the WM thread
+ */
+
+void
+winSendMessageToWM (void *pWMInfo, winWMMessagePtr pMsg)
+{
+  WMMsgNodePtr pNode;
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winSendMessageToWM ()\n");
+#endif
+  
+  pNode = (WMMsgNodePtr)malloc(sizeof(WMMsgNodeRec));
+  if (pNode != NULL)
+    {
+      memcpy (&pNode->msg, pMsg, sizeof(winWMMessageRec));
+      PushMessage (&((WMInfoPtr)pWMInfo)->wmMsgQueue, pNode);
+    }
+}
+
+
+/*
+ * Window manager error handler
+ */
+
+static int
+winMultiWindowWMErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+  char pszErrorMsg[100];
+
+  if (pErr->request_code == X_ChangeWindowAttributes
+      && pErr->error_code == BadAccess)
+    {
+      ErrorF ("winMultiWindowWMErrorHandler - ChangeWindowAttributes "
+	      "BadAccess.\n");
+      return 0;
+    }
+  
+  XGetErrorText (pDisplay,
+		 pErr->error_code,
+		 pszErrorMsg,
+		 sizeof (pszErrorMsg));
+  ErrorF ("winMultiWindowWMErrorHandler - ERROR: %s\n", pszErrorMsg);
+
+  return 0;
+}
+
+
+/*
+ * Window manager IO error handler
+ */
+
+static int
+winMultiWindowWMIOErrorHandler (Display *pDisplay)
+{
+  ErrorF ("winMultiWindowWMIOErrorHandler!\n\n");
+
+  if (g_shutdown)
+    pthread_exit(NULL);
+
+  /* Restart at the main entry point */
+  longjmp (g_jmpWMEntry, WIN_JMP_ERROR_IO);
+  
+  return 0;
+}
+
+
+/*
+ * X message procedure error handler
+ */
+
+static int
+winMultiWindowXMsgProcErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+  char pszErrorMsg[100];
+  
+  XGetErrorText (pDisplay,
+		 pErr->error_code,
+		 pszErrorMsg,
+		 sizeof (pszErrorMsg));
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winMultiWindowXMsgProcErrorHandler - ERROR: %s\n", pszErrorMsg);
+#endif
+  
+  return 0;
+}
+
+
+/*
+ * X message procedure IO error handler
+ */
+
+static int
+winMultiWindowXMsgProcIOErrorHandler (Display *pDisplay)
+{
+  ErrorF ("winMultiWindowXMsgProcIOErrorHandler!\n\n");
+
+  /* Restart at the main entry point */
+  longjmp (g_jmpXMsgProcEntry, WIN_JMP_ERROR_IO);
+  
+  return 0;
+}
+
+
+/*
+ * Catch RedirectError to detect other window manager running
+ */
+
+static int
+winRedirectErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+  redirectError = TRUE;
+  return 0;
+}
+
+
+/*
+ * Check if another window manager is running
+ */
+
+static Bool
+CheckAnotherWindowManager (Display *pDisplay, DWORD dwScreen, Bool fAllowOtherWM)
+{
+  /*
+    Try to select the events which only one client at a time is allowed to select.
+    If this causes an error, another window manager is already running...
+   */
+  redirectError = FALSE;
+  XSetErrorHandler (winRedirectErrorHandler);
+  XSelectInput(pDisplay, RootWindow (pDisplay, dwScreen),
+               ResizeRedirectMask | SubstructureRedirectMask | ButtonPressMask);
+  XSync (pDisplay, 0);
+  XSetErrorHandler (winMultiWindowXMsgProcErrorHandler);
+
+  /*
+    Side effect: select the events we are actually interested in...
+
+    If other WMs are not allowed, also select one of the events which only one client
+    at a time is allowed to select, so other window managers won't start...
+  */
+  XSelectInput(pDisplay, RootWindow (pDisplay, dwScreen),
+               SubstructureNotifyMask | ( !fAllowOtherWM ? ButtonPressMask : 0));
+  XSync (pDisplay, 0);
+  return redirectError;
+}
+
+/*
+ * Notify the MWM thread we're exiting and not to reconnect
+ */
+
+void
+winDeinitMultiWindowWM (void)
+{
+  ErrorF ("winDeinitMultiWindowWM - Noting shutdown in progress\n");
+  g_shutdown = TRUE;
+}
+
+/* Windows window styles */
+#define HINT_NOFRAME	(1l<<0)
+#define HINT_BORDER	(1L<<1)
+#define HINT_SIZEBOX	(1l<<2)
+#define HINT_CAPTION	(1l<<3)
+#define HINT_NOMAXIMIZE (1L<<4)
+/* These two are used on their own */
+#define HINT_MAX	(1L<<0)
+#define HINT_MIN	(1L<<1)
+
+static void
+winApplyHints (Display *pDisplay, Window iWindow, HWND hWnd, HWND *zstyle)
+{
+  static Atom		windowState, motif_wm_hints, windowType;
+  static Atom		hiddenState, fullscreenState, belowState, aboveState;
+  static Atom		dockWindow;
+  static int		generation;
+  Atom			type, *pAtom = NULL;
+  int			format;
+  unsigned long		hint = 0, maxmin = 0, style, nitems = 0 , left = 0;
+  WindowPtr		pWin = GetProp (hWnd, WIN_WINDOW_PROP);
+
+  if (!hWnd) return;
+  if (!IsWindow (hWnd)) return;
+
+  if (generation != serverGeneration) {
+      generation = serverGeneration;
+      windowState = XInternAtom(pDisplay, "_NET_WM_STATE", False);
+      motif_wm_hints = XInternAtom(pDisplay, "_MOTIF_WM_HINTS", False);
+      windowType = XInternAtom(pDisplay, "_NET_WM_WINDOW_TYPE", False);
+      hiddenState = XInternAtom(pDisplay, "_NET_WM_STATE_HIDDEN", False);
+      fullscreenState = XInternAtom(pDisplay, "_NET_WM_STATE_FULLSCREEN", False);
+      belowState = XInternAtom(pDisplay, "_NET_WM_STATE_BELOW", False);
+      aboveState = XInternAtom(pDisplay, "_NET_WM_STATE_ABOVE", False);
+      dockWindow = XInternAtom(pDisplay, "_NET_WM_WINDOW_TYPE_DOCK", False);
+  }
+
+  if (XGetWindowProperty(pDisplay, iWindow, windowState, 0L,
+			 1L, False, XA_ATOM, &type, &format,
+			 &nitems, &left, (unsigned char **)&pAtom) == Success)
+  {
+    if (pAtom && nitems == 1)
+    {
+      if (*pAtom == hiddenState) maxmin |= HINT_MIN;
+      else if (*pAtom == fullscreenState) maxmin |= HINT_MAX;
+      if (*pAtom == belowState) *zstyle = HWND_BOTTOM;
+      else if (*pAtom == aboveState) *zstyle = HWND_TOPMOST;
+    }
+    if (pAtom) XFree(pAtom);
+  }
+
+  nitems = left = 0;
+  MwmHints *mwm_hint = NULL;
+  if (XGetWindowProperty(pDisplay, iWindow, motif_wm_hints, 0L,
+			 PropMwmHintsElements, False, motif_wm_hints, &type, &format,
+			 &nitems, &left, (unsigned char **)&mwm_hint) == Success)
+  {
+    if (mwm_hint && nitems == PropMwmHintsElements && (mwm_hint->flags & MwmHintsDecorations))
+    {
+      if (!mwm_hint->decorations) hint |= HINT_NOFRAME;
+      else if (!(mwm_hint->decorations & MwmDecorAll))
+      {
+	if (mwm_hint->decorations & MwmDecorBorder) hint |= HINT_BORDER;
+	if (mwm_hint->decorations & MwmDecorHandle) hint |= HINT_SIZEBOX;
+	if (mwm_hint->decorations & MwmDecorTitle) hint |= HINT_CAPTION;
+      }
+    }
+    if (mwm_hint) XFree(mwm_hint);
+  }
+
+  nitems = left = 0;
+  pAtom = NULL;
+  if (XGetWindowProperty(pDisplay, iWindow, windowType, 0L,
+			 1L, False, XA_ATOM, &type, &format,
+			 &nitems, &left, (unsigned char **)&pAtom) == Success)
+  {
+    if (pAtom && nitems == 1)
+    {
+      if (*pAtom == dockWindow)
+      {
+	hint = (hint & ~HINT_NOFRAME) | HINT_SIZEBOX; /* Xming puts a sizebox on dock windows */
+	*zstyle = HWND_TOPMOST;
+      }
+    }
+    if (pAtom) XFree(pAtom);
+  }
+
+  {
+    XSizeHints *normal_hint = XAllocSizeHints();
+    long supplied;
+    if (normal_hint && (XGetWMNormalHints(pDisplay, iWindow, normal_hint, &supplied) == Success))
+      {
+        if (normal_hint->flags & PMaxSize)
+          {
+            /* Not maximizable if a maximum size is specified */
+            hint |= HINT_NOMAXIMIZE;
+
+            if (normal_hint->flags & PMinSize)
+              {
+                /*
+                  If both minimum size and maximum size are specified and are the same,
+                  don't bother with a resizing frame
+                */
+                if ((normal_hint->min_width == normal_hint->max_width)
+                    && (normal_hint->min_height == normal_hint->max_height))
+                  hint = (hint & ~HINT_SIZEBOX);
+              }
+          }
+      }
+    XFree(normal_hint);
+  }
+
+  /* Override hint settings from above with settings from config file */
+  style = winOverrideStyle((unsigned long)pWin);
+  if (style & STYLE_TOPMOST) *zstyle = HWND_TOPMOST;
+  else if (style & STYLE_MAXIMIZE) maxmin = (hint & ~HINT_MIN) | HINT_MAX;
+  else if (style & STYLE_MINIMIZE) maxmin = (hint & ~HINT_MAX) | HINT_MIN;
+  else if (style & STYLE_BOTTOM) *zstyle = HWND_BOTTOM;
+
+  if (maxmin & HINT_MAX) SendMessage(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
+  else if (maxmin & HINT_MIN) SendMessage(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
+
+  if (style & STYLE_NOTITLE)
+	hint = (hint & ~HINT_NOFRAME & ~HINT_BORDER & ~HINT_CAPTION) | HINT_SIZEBOX;
+  else if (style & STYLE_OUTLINE)
+	hint = (hint & ~HINT_NOFRAME & ~HINT_SIZEBOX & ~HINT_CAPTION) | HINT_BORDER;
+  else if (style & STYLE_NOFRAME)
+	hint = (hint & ~HINT_BORDER & ~HINT_CAPTION & ~HINT_SIZEBOX) | HINT_NOFRAME;
+
+  /* Now apply styles to window */
+  style = GetWindowLongPtr(hWnd, GWL_STYLE) & ~WS_CAPTION & ~WS_SIZEBOX; /* Just in case */
+  if (!style) return;
+
+  if (!hint) /* All on */
+    style = style | WS_CAPTION | WS_SIZEBOX;
+  else if (hint & HINT_NOFRAME) /* All off */
+    style = style & ~WS_CAPTION & ~WS_SIZEBOX;
+  else style = style | ((hint & HINT_BORDER) ? WS_BORDER : 0) |
+		((hint & HINT_SIZEBOX) ? WS_SIZEBOX : 0) |
+		((hint & HINT_CAPTION) ? WS_CAPTION : 0);
+
+  if (hint & HINT_NOMAXIMIZE)
+    style = style & ~WS_MAXIMIZEBOX;
+
+  SetWindowLongPtr (hWnd, GWL_STYLE, style);
+}
+
+void
+winUpdateWindowPosition (HWND hWnd, Bool reshape, HWND *zstyle)
+{
+  int iX, iY, iWidth, iHeight;
+  int	iDx, iDy;
+  RECT	rcNew;
+  WindowPtr	pWin = GetProp (hWnd, WIN_WINDOW_PROP);
+  DrawablePtr	pDraw = NULL;
+
+  if (!pWin) return;
+  pDraw = &pWin->drawable;
+  if (!pDraw) return;
+
+  /* Get the X and Y location of the X window */
+  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+  /* Get the height and width of the X window */
+  iWidth = pWin->drawable.width;
+  iHeight = pWin->drawable.height;
+
+  /* Setup a rectangle with the X window position and size */
+  SetRect (&rcNew, iX, iY, iX + iWidth, iY + iHeight);
+
+#if 0
+  ErrorF ("winUpdateWindowPosition - (%d, %d)-(%d, %d)\n",
+	  rcNew.left, rcNew.top,
+	  rcNew.right, rcNew.bottom);
+#endif
+
+  AdjustWindowRectEx (&rcNew, GetWindowLongPtr (hWnd, GWL_STYLE), FALSE, WS_EX_APPWINDOW);
+
+  /* Don't allow window decoration to disappear off to top-left as a result of this adjustment */
+  if (rcNew.left < GetSystemMetrics(SM_XVIRTUALSCREEN))
+    {
+      iDx = GetSystemMetrics(SM_XVIRTUALSCREEN) - rcNew.left;
+      rcNew.left += iDx;
+      rcNew.right += iDx;
+    }
+
+  if (rcNew.top < GetSystemMetrics(SM_YVIRTUALSCREEN))
+    {
+      iDy = GetSystemMetrics(SM_YVIRTUALSCREEN) - rcNew.top;
+      rcNew.top += iDy;
+      rcNew.bottom += iDy;
+    }
+
+#if 0
+  ErrorF ("winUpdateWindowPosition - (%d, %d)-(%d, %d)\n",
+	  rcNew.left, rcNew.top,
+	  rcNew.right, rcNew.bottom);
+#endif
+
+  /* Position the Windows window */
+  SetWindowPos (hWnd, *zstyle, rcNew.left, rcNew.top,
+	rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
+	0);
+
+  if (reshape)
+  {
+    winReshapeMultiWindow(pWin);
+    winUpdateRgnMultiWindow(pWin);
+  }
+}
diff --git a/xorg-server/hw/xwin/winscrinit.c b/xorg-server/hw/xwin/winscrinit.c
index 37ec27e08..a9cc47df2 100644
--- a/xorg-server/hw/xwin/winscrinit.c
+++ b/xorg-server/hw/xwin/winscrinit.c
@@ -1,790 +1,790 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- *		Kensuke Matsuzaki
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-static RootlessFrameProcsRec
-winMWExtWMProcs = {	
-  winMWExtWMCreateFrame,
-  winMWExtWMDestroyFrame,
-  
-  winMWExtWMMoveFrame,
-  winMWExtWMResizeFrame,
-  winMWExtWMRestackFrame,
-  winMWExtWMReshapeFrame,
-  winMWExtWMUnmapFrame,
-  
-  winMWExtWMStartDrawing,
-  winMWExtWMStopDrawing,
-  winMWExtWMUpdateRegion,
-#ifndef ROOTLESS_TRACK_DAMAGE
-  winMWExtWMDamageRects,
-#endif
-  winMWExtWMRootlessSwitchWindow,
-  NULL,//winMWExtWMDoReorderWindow,
-  NULL,//winMWExtWMHideWindow,
-  NULL,//winMWExtWMUpdateColorMap,
-
-  NULL,//winMWExtWMCopyBytes,
-  NULL,//winMWExtWMFillBytes,
-  NULL,//winMWExtWMCompositePixels,
-  winMWExtWMCopyWindow
-};
-#endif
-
-
-/*
- * References to external symbols
- */
-
-extern Bool                     g_fSoftwareCursor;
-
-
-/*
- * Prototypes
- */
-
-Bool
-winRandRInit (ScreenPtr pScreen);
-
-
-/*
- * Local functions
- */
-
-static Bool
-winSaveScreen (ScreenPtr pScreen, int on);
-
-
-/*
- * Determine what type of screen we are initializing
- * and call the appropriate procedure to intiailize
- * that type of screen.
- */
-
-Bool
-winScreenInit (int index,
-	       ScreenPtr pScreen,
-	       int argc, char **argv)
-{
-  winScreenInfoPtr      pScreenInfo = &g_ScreenInfo[index];
-  winPrivScreenPtr	pScreenPriv;
-  HDC			hdc;
-
-#if CYGDEBUG || YES
-  winDebug ("winScreenInit - dwWidth: %ld dwHeight: %ld\n",
-	  pScreenInfo->dwWidth, pScreenInfo->dwHeight);
-#endif
-
-  /* Allocate privates for this screen */
-  if (!winAllocatePrivates (pScreen))
-    {
-      ErrorF ("winScreenInit - Couldn't allocate screen privates\n");
-      return FALSE;
-    }
-
-  /* Get a pointer to the privates structure that was allocated */
-  pScreenPriv = winGetScreenPriv (pScreen);
-
-  /* Save a pointer to this screen in the screen info structure */
-  pScreenInfo->pScreen = pScreen;
-
-  /* Save a pointer to the screen info in the screen privates structure */
-  /* This allows us to get back to the screen info from a screen pointer */
-  pScreenPriv->pScreenInfo = pScreenInfo;
-
-  /*
-   * Determine which engine to use.
-   *
-   * NOTE: This is done once per screen because each screen possibly has
-   * a preferred engine specified on the command line.
-   */
-  if (!winSetEngine (pScreen))
-    {
-      ErrorF ("winScreenInit - winSetEngine () failed\n");
-      return FALSE;
-    }
-
-  /* Adjust the video mode for our engine type */
-  if (!(*pScreenPriv->pwinAdjustVideoMode) (pScreen))
-    {
-      ErrorF ("winScreenInit - winAdjustVideoMode () failed\n");
-      return FALSE;
-    }
-
-  /* Check for supported display depth */
-  if (!(WIN_SUPPORTED_BPPS & (1 << (pScreenInfo->dwBPP - 1))))
-    {
-      ErrorF ("winScreenInit - Unsupported display depth: %d\n" \
-	      "Change your Windows display depth to 15, 16, 24, or 32 bits "
-	      "per pixel.\n",
-	      (int) pScreenInfo->dwBPP);
-      ErrorF ("winScreenInit - Supported depths: %08x\n",
-	      WIN_SUPPORTED_BPPS);
-#if WIN_CHECK_DEPTH
-      return FALSE;
-#endif
-    }
-
-  /*
-   * Check that all monitors have the same display depth if we are using
-   * multiple monitors
-   */
-  if (pScreenInfo->fMultipleMonitors 
-      && !GetSystemMetrics (SM_SAMEDISPLAYFORMAT))
-    {
-      ErrorF ("winScreenInit - Monitors do not all have same pixel format / "
-	      "display depth.\n"
-	      "Using primary display only.\n");
-      pScreenInfo->fMultipleMonitors = FALSE;
-    }
-
-  /* Create display window */
-  if (!(*pScreenPriv->pwinCreateBoundingWindow) (pScreen))
-    {
-      ErrorF ("winScreenInit - pwinCreateBoundingWindow () "
-	      "failed\n");
-      return FALSE;
-    }
-
-  /* Get a device context */
-  hdc = GetDC (pScreenPriv->hwndScreen);
-
-  /* Store the initial height, width, and depth of the display */
-  /* Are we using multiple monitors? */
-  if (pScreenInfo->fMultipleMonitors)
-    {
-      pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
-      pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
-
-      /* 
-       * In this case, some of the defaults set in
-       * winInitializeDefaultScreens () are not correct ...
-       */
-      if (!pScreenInfo->fUserGaveHeightAndWidth)
-	{
-	  pScreenInfo->dwWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
-	  pScreenInfo->dwHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
-	  pScreenInfo->dwWidth_mm = (pScreenInfo->dwWidth /
-				     WIN_DEFAULT_DPI) * 25.4;
-	  pScreenInfo->dwHeight_mm = (pScreenInfo->dwHeight /
-				      WIN_DEFAULT_DPI) * 25.4;
-	}
-    }
-  else
-    {
-      pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXSCREEN);
-      pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYSCREEN);
-    }
-
-  /* Save the original bits per pixel */
-  pScreenPriv->dwLastWindowsBitsPixel = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* Release the device context */
-  ReleaseDC (pScreenPriv->hwndScreen, hdc);
-    
-  /* Clear the visuals list */
-  miClearVisualTypes ();
-  
-  /* Set the padded screen width */
-  pScreenInfo->dwPaddedWidth = PixmapBytePad (pScreenInfo->dwWidth,
-					      pScreenInfo->dwBPP);
-
-  /* Call the engine dependent screen initialization procedure */
-  if (!((*pScreenPriv->pwinFinishScreenInit) (index, pScreen, argc, argv)))
-    {
-      ErrorF ("winScreenInit - winFinishScreenInit () failed\n");
-      return FALSE;
-    }
-
-  if (!g_fSoftwareCursor)
-    winInitCursor(pScreen);
-  else
-    winErrorFVerb(2, "winScreenInit - Using software cursor\n");  
-
-  /*
-     Note the screen origin in a normalized coordinate space where (0,0) is at the top left
-     of the native virtual desktop area
-  */
-  dixScreenOrigins[index].x = pScreenInfo->dwInitialX - GetSystemMetrics(SM_XVIRTUALSCREEN);
-  dixScreenOrigins[index].y = pScreenInfo->dwInitialY - GetSystemMetrics(SM_YVIRTUALSCREEN);
-
-  ErrorF("Screen %d added at XINERAMA coordinate (%d,%d).\n",
-         index, dixScreenOrigins[index].x, dixScreenOrigins[index].y);
-
-#if CYGDEBUG || YES
-  winDebug ("winScreenInit - returning\n");
-#endif
-
-  return TRUE;
-}
-
-static Bool
-winCreateScreenResources(ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  Bool result;
-
-  result = pScreenPriv->pwinCreateScreenResources(pScreen);
-
-  /* Now the screen bitmap has been wrapped in a pixmap,
-     add that to the Shadow framebuffer */
-  if (!shadowAdd(pScreen, pScreen->devPrivate,
-		 pScreenPriv->pwinShadowUpdate, NULL, 0, 0))
-    {
-      ErrorF ("winCreateScreenResources - shadowAdd () failed\n");
-      return FALSE;
-    }
-
-  return result;
-}
-
-/* See Porting Layer Definition - p. 20 */
-Bool
-winFinishScreenInitFB (int index,
-		       ScreenPtr pScreen,
-		       int argc, char **argv)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  VisualPtr		pVisual = NULL;
-  char			*pbits = NULL;
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  int			iReturn;
-#endif
-
-  /* Create framebuffer */
-  if (!(*pScreenPriv->pwinAllocateFB) (pScreen))
-    {
-      ErrorF ("winFinishScreenInitFB - Could not allocate framebuffer\n");
-      return FALSE;
-    }
-
-  /*
-   * Grab the number of bits that are used to represent color in each pixel.
-   */
-  if (pScreenInfo->dwBPP == 8)
-    pScreenInfo->dwDepth = 8;
-  else
-    pScreenInfo->dwDepth = winCountBits (pScreenPriv->dwRedMask)
-      + winCountBits (pScreenPriv->dwGreenMask)
-      + winCountBits (pScreenPriv->dwBlueMask);
-  
-  winErrorFVerb (2, "winFinishScreenInitFB - Masks: %08x %08x %08x\n",
-	  (unsigned int) pScreenPriv->dwRedMask,
-	  (unsigned int) pScreenPriv->dwGreenMask,
-	  (unsigned int) pScreenPriv->dwBlueMask);
-
-  /* Init visuals */
-  if (!(*pScreenPriv->pwinInitVisuals) (pScreen))
-    {
-      ErrorF ("winFinishScreenInitFB - winInitVisuals failed\n");
-      return FALSE;
-    }
-
-  /* Setup a local variable to point to the framebuffer */
-  pbits = pScreenInfo->pfb;
-  
-  /* Apparently we need this for the render extension */
-  miSetPixmapDepths ();
-
-  /* Start fb initialization */
-  if (!fbSetupScreen (pScreen,
-		      pScreenInfo->pfb,
-		      pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-		      monitorResolution, monitorResolution,
-		      pScreenInfo->dwStride,
-		      pScreenInfo->dwBPP))
-    {
-      ErrorF ("winFinishScreenInitFB - fbSetupScreen failed\n");
-      return FALSE;
-    }
-
-  /* Override default colormap routines if visual class is dynamic */
-  if (pScreenInfo->dwDepth == 8
-      && (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI
-	  || (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
-	      && pScreenInfo->fFullScreen)
-	  || (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
-	      && pScreenInfo->fFullScreen)))
-    {
-      winSetColormapFunctions (pScreen);
-
-      /*
-       * NOTE: Setting whitePixel to 255 causes Magic 7.1 to allocate its
-       * own colormap, as it cannot allocate 7 planes in the default
-       * colormap.  Setting whitePixel to 1 allows Magic to get 7
-       * planes in the default colormap, so it doesn't create its
-       * own colormap.  This latter situation is highly desireable,
-       * as it keeps the Magic window viewable when switching to
-       * other X clients that use the default colormap.
-       */
-      pScreen->blackPixel = 0;
-      pScreen->whitePixel = 1;
-    }
-
-  /* Place our save screen function */
-  pScreen->SaveScreen = winSaveScreen;
-
-  /* Finish fb initialization */
-  if (!fbFinishScreenInit (pScreen,
-			   pScreenInfo->pfb,
-			   pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-			   monitorResolution, monitorResolution,
-			   pScreenInfo->dwStride,
-			   pScreenInfo->dwBPP))
-    {
-      ErrorF ("winFinishScreenInitFB - fbFinishScreenInit failed\n");
-      return FALSE;
-    }
-
-  /* Save a pointer to the root visual */
-  for (pVisual = pScreen->visuals;
-       pVisual->vid != pScreen->rootVisual;
-       pVisual++);
-  pScreenPriv->pRootVisual = pVisual;
-
-  /* 
-   * Setup points to the block and wakeup handlers.  Pass a pointer
-   * to the current screen as pWakeupdata.
-   */
-  pScreen->BlockHandler = winBlockHandler;
-  pScreen->WakeupHandler = winWakeupHandler;
-  pScreen->blockData = pScreen;
-  pScreen->wakeupData = pScreen;
-
-#ifdef RENDER
-  /* Render extension initialization, calls miPictureInit */
-  if (!fbPictureInit (pScreen, NULL, 0))
-    {
-      ErrorF ("winFinishScreenInitFB - fbPictureInit () failed\n");
-      return FALSE;
-    }
-#endif
-
-#ifdef RANDR
-  /* Initialize resize and rotate support */
-  if (!winRandRInit (pScreen))
-    {
-      ErrorF ("winFinishScreenInitFB - winRandRInit () failed\n");
-      return FALSE;
-    }
-#endif
-
-  /*
-   * Backing store support should reduce network traffic and increase
-   * performance.
-   */
-  miInitializeBackingStore (pScreen);
-
-  /* KDrive does miDCInitialize right after miInitializeBackingStore */
-  /* Setup the cursor routines */
-#if CYGDEBUG
-  winDebug ("winFinishScreenInitFB - Calling miDCInitialize ()\n");
-#endif
-  miDCInitialize (pScreen, &g_winPointerCursorFuncs);
-
-  /* KDrive does winCreateDefColormap right after miDCInitialize */
-  /* Create a default colormap */
-#if CYGDEBUG
-  winDebug ("winFinishScreenInitFB - Calling winCreateDefColormap ()\n");
-#endif
-  if (!winCreateDefColormap (pScreen))
-    {
-      ErrorF ("winFinishScreenInitFB - Could not create colormap\n");
-      return FALSE;
-    }
-
-  /* Initialize the shadow framebuffer layer */
-  if ((pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI
-       || pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
-       || pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL)
-#ifdef XWIN_MULTIWINDOWEXTWM
-      && !pScreenInfo->fMWExtWM
-#endif
-      )
-    {
-#if CYGDEBUG
-      winDebug ("winFinishScreenInitFB - Calling shadowSetup ()\n");
-#endif
-      if (!shadowSetup(pScreen))
-	{
-	  ErrorF ("winFinishScreenInitFB - shadowSetup () failed\n");
-	  return FALSE;
-	}
-
-      /* Wrap CreateScreenResources so we can add the screen pixmap
-         to the Shadow framebuffer after it's been created */
-      pScreenPriv->pwinCreateScreenResources = pScreen->CreateScreenResources;
-      pScreen->CreateScreenResources = winCreateScreenResources;
-    }
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  /* Handle multi-window external window manager mode */
-  if (pScreenInfo->fMWExtWM)
-    {
-      winDebug ("winScreenInit - MultiWindowExtWM - Calling RootlessInit\n");
-      
-      RootlessInit(pScreen, &winMWExtWMProcs);
-      
-      winDebug ("winScreenInit - MultiWindowExtWM - RootlessInit returned\n");
-      
-      rootless_CopyBytes_threshold = 0;
-      rootless_FillBytes_threshold = 0;
-      rootless_CompositePixels_threshold = 0;
-      /* FIXME: How many? Profiling needed? */
-      rootless_CopyWindow_threshold = 1;
-
-      winWindowsWMExtensionInit ();
-    }
-#endif
-
-  /* Handle rootless mode */
-  if (pScreenInfo->fRootless)
-    {
-      /* Define the WRAP macro temporarily for local use */
-#define WRAP(a) \
-    if (pScreen->a) { \
-        pScreenPriv->a = pScreen->a; \
-    } else { \
-        ErrorF("null screen fn " #a "\n"); \
-        pScreenPriv->a = NULL; \
-    }
-
-      /* Save a pointer to each lower-level window procedure */
-      WRAP(CreateWindow);
-      WRAP(DestroyWindow);
-      WRAP(RealizeWindow);
-      WRAP(UnrealizeWindow);
-      WRAP(PositionWindow);
-      WRAP(ChangeWindowAttributes);
-      WRAP(SetShape);
-
-      /* Assign rootless window procedures to be top level procedures */
-      pScreen->CreateWindow = winCreateWindowRootless;
-      pScreen->DestroyWindow = winDestroyWindowRootless;
-      pScreen->PositionWindow = winPositionWindowRootless;
-      /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesRootless;*/
-      pScreen->RealizeWindow = winMapWindowRootless;
-      pScreen->UnrealizeWindow = winUnmapWindowRootless;
-      pScreen->SetShape = winSetShapeRootless;
-
-      /* Undefine the WRAP macro, as it is not needed elsewhere */
-#undef WRAP
-    }
-
-
-#ifdef XWIN_MULTIWINDOW
-  /* Handle multi window mode */
-  else if (pScreenInfo->fMultiWindow)
-    {
-      /* Define the WRAP macro temporarily for local use */
-#define WRAP(a) \
-    if (pScreen->a) { \
-        pScreenPriv->a = pScreen->a; \
-    } else { \
-        ErrorF("null screen fn " #a "\n"); \
-        pScreenPriv->a = NULL; \
-    }
-
-      /* Save a pointer to each lower-level window procedure */
-      WRAP(CreateWindow);
-      WRAP(DestroyWindow);
-      WRAP(RealizeWindow);
-      WRAP(UnrealizeWindow);
-      WRAP(PositionWindow);
-      WRAP(ChangeWindowAttributes);
-      WRAP(ReparentWindow);
-      WRAP(RestackWindow);
-      WRAP(ResizeWindow);
-      WRAP(MoveWindow);
-      WRAP(CopyWindow);
-      WRAP(SetShape);
-
-      /* Assign multi-window window procedures to be top level procedures */
-      pScreen->CreateWindow = winCreateWindowMultiWindow;
-      pScreen->DestroyWindow = winDestroyWindowMultiWindow;
-      pScreen->PositionWindow = winPositionWindowMultiWindow;
-      /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesMultiWindow;*/
-      pScreen->RealizeWindow = winMapWindowMultiWindow;
-      pScreen->UnrealizeWindow = winUnmapWindowMultiWindow;
-      pScreen->ReparentWindow = winReparentWindowMultiWindow;
-      pScreen->RestackWindow = winRestackWindowMultiWindow;
-      pScreen->ResizeWindow = winResizeWindowMultiWindow;
-      pScreen->MoveWindow = winMoveWindowMultiWindow;
-      pScreen->CopyWindow = winCopyWindowMultiWindow;
-      pScreen->SetShape = winSetShapeMultiWindow;
-
-      /* Undefine the WRAP macro, as it is not needed elsewhere */
-#undef WRAP
-    }
-#endif
-
-  /* Wrap either fb's or shadow's CloseScreen with our CloseScreen */
-  pScreenPriv->CloseScreen = pScreen->CloseScreen;
-  pScreen->CloseScreen = pScreenPriv->pwinCloseScreen;
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Create a mutex for modules in separate threads to wait for */
-  iReturn = pthread_mutex_init (&pScreenPriv->pmServerStarted, NULL);
-  if (iReturn != 0)
-    {
-      ErrorF ("winFinishScreenInitFB - pthread_mutex_init () failed: %d\n",
-	      iReturn);
-      return FALSE;
-    }
-
-  /* Own the mutex for modules in separate threads */
-  iReturn = pthread_mutex_lock (&pScreenPriv->pmServerStarted);
-  if (iReturn != 0)
-    {
-      ErrorF ("winFinishScreenInitFB - pthread_mutex_lock () failed: %d\n",
-	      iReturn);
-      return FALSE;
-    }
-
-  /* Set the ServerStarted flag to false */
-  pScreenPriv->fServerStarted = FALSE;
-#endif
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  pScreenPriv->fRestacking = FALSE;
-#endif
-
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-  if (FALSE
-#ifdef XWIN_MULTIWINDOW
-      || pScreenInfo->fMultiWindow
-#endif
-#ifdef XWIN_MULTIWINDOWEXTWM
-      || pScreenInfo->fInternalWM
-#endif
-      )
-    { 
-#if CYGDEBUG || YES
-      winDebug ("winFinishScreenInitFB - Calling winInitWM.\n");
-#endif
-
-      /* Initialize multi window mode */
-      if (!winInitWM (&pScreenPriv->pWMInfo,
-		      &pScreenPriv->ptWMProc,
-		      &pScreenPriv->ptXMsgProc,
-		      &pScreenPriv->pmServerStarted,
-		      pScreenInfo->dwScreen,
-		      (HWND)&pScreenPriv->hwndScreen,
-#ifdef XWIN_MULTIWINDOWEXTWM
-		      pScreenInfo->fInternalWM ||
-#endif
-		      FALSE))
-        {
-          ErrorF ("winFinishScreenInitFB - winInitWM () failed.\n");
-          return FALSE;
-        }
-    }      
-#endif
-
-  /* Tell the server that we are enabled */
-  pScreenPriv->fEnabled = TRUE;
-
-  /* Tell the server that we have a valid depth */
-  pScreenPriv->fBadDepth = FALSE;
-
-#if CYGDEBUG || YES
-  winDebug ("winFinishScreenInitFB - returning\n");
-#endif
-
-  return TRUE;
-}
-
-#ifdef XWIN_NATIVEGDI
-/* See Porting Layer Definition - p. 20 */
-
-Bool
-winFinishScreenInitNativeGDI (int index,
-			      ScreenPtr pScreen,
-			      int argc, char **argv)
-{
-  winScreenPriv(pScreen);
-  winScreenInfoPtr      pScreenInfo = &g_ScreenInfo[index];
-  VisualPtr		pVisuals = NULL;
-  DepthPtr		pDepths = NULL;
-  VisualID		rootVisual = 0;
-  int			nVisuals = 0, nDepths = 0, nRootDepth = 0;
-
-  /* Ignore user input (mouse, keyboard) */
-  pScreenInfo->fIgnoreInput = FALSE;
-
-  /* Get device contexts for the screen and shadow bitmap */
-  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
-  if (pScreenPriv->hdcScreen == NULL)
-    FatalError ("winFinishScreenInitNativeGDI - Couldn't get a DC\n");
-
-  /* Init visuals */
-  if (!(*pScreenPriv->pwinInitVisuals) (pScreen))
-    {
-      ErrorF ("winFinishScreenInitNativeGDI - pwinInitVisuals failed\n");
-      return FALSE;
-    }
-
-  /* Initialize the mi visuals */
-  if (!miInitVisuals (&pVisuals, &pDepths, &nVisuals, &nDepths, &nRootDepth,
-		      &rootVisual,
-		      ((unsigned long)1 << (pScreenInfo->dwDepth - 1)), 8,
-		      TrueColor))
-    {
-      ErrorF ("winFinishScreenInitNativeGDI - miInitVisuals () failed\n");
-      return FALSE;
-    }
-
-  /* Initialize the CloseScreen procedure pointer */
-  pScreen->CloseScreen = NULL;
-
-  /* Initialize the mi code */
-  if (!miScreenInit (pScreen,
-		     NULL, /* No framebuffer */
-		     pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-		     monitorResolution, monitorResolution,
-		     pScreenInfo->dwStride,
-		     nRootDepth, nDepths, pDepths, rootVisual,
-		     nVisuals, pVisuals))
-    {
-      ErrorF ("winFinishScreenInitNativeGDI - miScreenInit failed\n");
-      return FALSE;
-    }
-
-  pScreen->defColormap = FakeClientID(0);
-
-  /*
-   * Register our block and wakeup handlers; these procedures
-   * process messages in our Windows message queue; specifically,
-   * they process mouse and keyboard input.
-   */
-  pScreen->BlockHandler = winBlockHandler;
-  pScreen->WakeupHandler = winWakeupHandler;
-  pScreen->blockData = pScreen;
-  pScreen->wakeupData = pScreen;
-
-  /* Place our save screen function */
-  pScreen->SaveScreen = winSaveScreen;
-
-  /* Pixmaps */
-  pScreen->CreatePixmap = winCreatePixmapNativeGDI;
-  pScreen->DestroyPixmap = winDestroyPixmapNativeGDI;
-
-  /* Other Screen Routines */
-  pScreen->QueryBestSize = winQueryBestSizeNativeGDI;
-  pScreen->SaveScreen = winSaveScreen;  
-  pScreen->GetImage = miGetImage;
-  pScreen->GetSpans = winGetSpansNativeGDI;
-
-  /* Window Procedures */
-  pScreen->CreateWindow = winCreateWindowNativeGDI;
-  pScreen->DestroyWindow = winDestroyWindowNativeGDI;
-  pScreen->PositionWindow = winPositionWindowNativeGDI;
-  /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesNativeGDI;*/
-  pScreen->RealizeWindow = winMapWindowNativeGDI;
-  pScreen->UnrealizeWindow = winUnmapWindowNativeGDI;
-
-  /* Paint window */
-  pScreen->CopyWindow = winCopyWindowNativeGDI;
-
-  /* Fonts */
-  pScreen->RealizeFont = winRealizeFontNativeGDI;
-  pScreen->UnrealizeFont = winUnrealizeFontNativeGDI;
-
-  /* GC */
-  pScreen->CreateGC = winCreateGCNativeGDI;
-
-  /* Colormap Routines */
-  pScreen->CreateColormap = miInitializeColormap;
-  pScreen->DestroyColormap = (DestroyColormapProcPtr) (void (*)(void)) NoopDDA;
-  pScreen->InstallColormap = miInstallColormap;
-  pScreen->UninstallColormap = miUninstallColormap;
-  pScreen->ListInstalledColormaps = miListInstalledColormaps;
-  pScreen->StoreColors = (StoreColorsProcPtr) (void (*)(void)) NoopDDA;
-  pScreen->ResolveColor = miResolveColor;
-
-  /* Bitmap */
-  pScreen->BitmapToRegion = winPixmapToRegionNativeGDI;
-
-  ErrorF ("winFinishScreenInitNativeGDI - calling miDCInitialize\n");
-
-  /* Set the default white and black pixel positions */
-  pScreen->whitePixel = pScreen->blackPixel = (Pixel) 0;
-
-  /* Initialize the cursor */
-  if (!miDCInitialize (pScreen, &g_winPointerCursorFuncs))
-    {
-      ErrorF ("winFinishScreenInitNativeGDI - miDCInitialize failed\n");
-      return FALSE;
-    }
-  
-  /* Create a default colormap */
-  if (!miCreateDefColormap (pScreen))
-    {
-        ErrorF ("winFinishScreenInitNativeGDI - miCreateDefColormap () "
-		"failed\n");
-	return FALSE;
-    }
-
-  ErrorF ("winFinishScreenInitNativeGDI - miCreateDefColormap () "
-	  "returned\n");
-  
-  /* mi doesn't use a CloseScreen procedure, so no need to wrap */
-  pScreen->CloseScreen = pScreenPriv->pwinCloseScreen;
-
-  /* Tell the server that we are enabled */
-  pScreenPriv->fEnabled = TRUE;
-
-  ErrorF ("winFinishScreenInitNativeGDI - Successful addition of "
-	  "screen %08x\n",
-	  (unsigned int) pScreen);
-
-  return TRUE;
-}
-#endif
-
-
-/* See Porting Layer Definition - p. 33 */
-static Bool
-winSaveScreen (ScreenPtr pScreen, int on)
-{
-  return TRUE;
-}
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ *		Kensuke Matsuzaki
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+static RootlessFrameProcsRec
+winMWExtWMProcs = {	
+  winMWExtWMCreateFrame,
+  winMWExtWMDestroyFrame,
+  
+  winMWExtWMMoveFrame,
+  winMWExtWMResizeFrame,
+  winMWExtWMRestackFrame,
+  winMWExtWMReshapeFrame,
+  winMWExtWMUnmapFrame,
+  
+  winMWExtWMStartDrawing,
+  winMWExtWMStopDrawing,
+  winMWExtWMUpdateRegion,
+#ifndef ROOTLESS_TRACK_DAMAGE
+  winMWExtWMDamageRects,
+#endif
+  winMWExtWMRootlessSwitchWindow,
+  NULL,//winMWExtWMDoReorderWindow,
+  NULL,//winMWExtWMHideWindow,
+  NULL,//winMWExtWMUpdateColorMap,
+
+  NULL,//winMWExtWMCopyBytes,
+  NULL,//winMWExtWMFillBytes,
+  NULL,//winMWExtWMCompositePixels,
+  winMWExtWMCopyWindow
+};
+#endif
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool                     g_fSoftwareCursor;
+
+
+/*
+ * Prototypes
+ */
+
+Bool
+winRandRInit (ScreenPtr pScreen);
+
+
+/*
+ * Local functions
+ */
+
+static Bool
+winSaveScreen (ScreenPtr pScreen, int on);
+
+
+/*
+ * Determine what type of screen we are initializing
+ * and call the appropriate procedure to intiailize
+ * that type of screen.
+ */
+
+Bool
+winScreenInit (int index,
+	       ScreenPtr pScreen,
+	       int argc, char **argv)
+{
+  winScreenInfoPtr      pScreenInfo = &g_ScreenInfo[index];
+  winPrivScreenPtr	pScreenPriv;
+  HDC			hdc;
+
+#if CYGDEBUG || YES
+  winDebug ("winScreenInit - dwWidth: %ld dwHeight: %ld\n",
+	  pScreenInfo->dwWidth, pScreenInfo->dwHeight);
+#endif
+
+  /* Allocate privates for this screen */
+  if (!winAllocatePrivates (pScreen))
+    {
+      ErrorF ("winScreenInit - Couldn't allocate screen privates\n");
+      return FALSE;
+    }
+
+  /* Get a pointer to the privates structure that was allocated */
+  pScreenPriv = winGetScreenPriv (pScreen);
+
+  /* Save a pointer to this screen in the screen info structure */
+  pScreenInfo->pScreen = pScreen;
+
+  /* Save a pointer to the screen info in the screen privates structure */
+  /* This allows us to get back to the screen info from a screen pointer */
+  pScreenPriv->pScreenInfo = pScreenInfo;
+
+  /*
+   * Determine which engine to use.
+   *
+   * NOTE: This is done once per screen because each screen possibly has
+   * a preferred engine specified on the command line.
+   */
+  if (!winSetEngine (pScreen))
+    {
+      ErrorF ("winScreenInit - winSetEngine () failed\n");
+      return FALSE;
+    }
+
+  /* Adjust the video mode for our engine type */
+  if (!(*pScreenPriv->pwinAdjustVideoMode) (pScreen))
+    {
+      ErrorF ("winScreenInit - winAdjustVideoMode () failed\n");
+      return FALSE;
+    }
+
+  /* Check for supported display depth */
+  if (!(WIN_SUPPORTED_BPPS & (1 << (pScreenInfo->dwBPP - 1))))
+    {
+      ErrorF ("winScreenInit - Unsupported display depth: %d\n" \
+	      "Change your Windows display depth to 15, 16, 24, or 32 bits "
+	      "per pixel.\n",
+	      (int) pScreenInfo->dwBPP);
+      ErrorF ("winScreenInit - Supported depths: %08x\n",
+	      WIN_SUPPORTED_BPPS);
+#if WIN_CHECK_DEPTH
+      return FALSE;
+#endif
+    }
+
+  /*
+   * Check that all monitors have the same display depth if we are using
+   * multiple monitors
+   */
+  if (pScreenInfo->fMultipleMonitors 
+      && !GetSystemMetrics (SM_SAMEDISPLAYFORMAT))
+    {
+      ErrorF ("winScreenInit - Monitors do not all have same pixel format / "
+	      "display depth.\n"
+	      "Using primary display only.\n");
+      pScreenInfo->fMultipleMonitors = FALSE;
+    }
+
+  /* Create display window */
+  if (!(*pScreenPriv->pwinCreateBoundingWindow) (pScreen))
+    {
+      ErrorF ("winScreenInit - pwinCreateBoundingWindow () "
+	      "failed\n");
+      return FALSE;
+    }
+
+  /* Get a device context */
+  hdc = GetDC (pScreenPriv->hwndScreen);
+
+  /* Store the initial height, width, and depth of the display */
+  /* Are we using multiple monitors? */
+  if (pScreenInfo->fMultipleMonitors)
+    {
+      pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+      pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+
+      /* 
+       * In this case, some of the defaults set in
+       * winInitializeDefaultScreens () are not correct ...
+       */
+      if (!pScreenInfo->fUserGaveHeightAndWidth)
+	{
+	  pScreenInfo->dwWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+	  pScreenInfo->dwHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+	  pScreenInfo->dwWidth_mm = (pScreenInfo->dwWidth /
+				     WIN_DEFAULT_DPI) * 25.4;
+	  pScreenInfo->dwHeight_mm = (pScreenInfo->dwHeight /
+				      WIN_DEFAULT_DPI) * 25.4;
+	}
+    }
+  else
+    {
+      pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXSCREEN);
+      pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYSCREEN);
+    }
+
+  /* Save the original bits per pixel */
+  pScreenPriv->dwLastWindowsBitsPixel = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* Release the device context */
+  ReleaseDC (pScreenPriv->hwndScreen, hdc);
+    
+  /* Clear the visuals list */
+  miClearVisualTypes ();
+  
+  /* Set the padded screen width */
+  pScreenInfo->dwPaddedWidth = PixmapBytePad (pScreenInfo->dwWidth,
+					      pScreenInfo->dwBPP);
+
+  /* Call the engine dependent screen initialization procedure */
+  if (!((*pScreenPriv->pwinFinishScreenInit) (index, pScreen, argc, argv)))
+    {
+      ErrorF ("winScreenInit - winFinishScreenInit () failed\n");
+      return FALSE;
+    }
+
+  if (!g_fSoftwareCursor)
+    winInitCursor(pScreen);
+  else
+    winErrorFVerb(2, "winScreenInit - Using software cursor\n");  
+
+  /*
+     Note the screen origin in a normalized coordinate space where (0,0) is at the top left
+     of the native virtual desktop area
+  */
+  dixScreenOrigins[index].x = pScreenInfo->dwInitialX - GetSystemMetrics(SM_XVIRTUALSCREEN);
+  dixScreenOrigins[index].y = pScreenInfo->dwInitialY - GetSystemMetrics(SM_YVIRTUALSCREEN);
+
+  ErrorF("Screen %d added at virtual desktop coordinate (%d,%d).\n",
+         index, dixScreenOrigins[index].x, dixScreenOrigins[index].y);
+
+#if CYGDEBUG || YES
+  winDebug ("winScreenInit - returning\n");
+#endif
+
+  return TRUE;
+}
+
+static Bool
+winCreateScreenResources(ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  Bool result;
+
+  result = pScreenPriv->pwinCreateScreenResources(pScreen);
+
+  /* Now the screen bitmap has been wrapped in a pixmap,
+     add that to the Shadow framebuffer */
+  if (!shadowAdd(pScreen, pScreen->devPrivate,
+		 pScreenPriv->pwinShadowUpdate, NULL, 0, 0))
+    {
+      ErrorF ("winCreateScreenResources - shadowAdd () failed\n");
+      return FALSE;
+    }
+
+  return result;
+}
+
+/* See Porting Layer Definition - p. 20 */
+Bool
+winFinishScreenInitFB (int index,
+		       ScreenPtr pScreen,
+		       int argc, char **argv)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  VisualPtr		pVisual = NULL;
+  char			*pbits = NULL;
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  int			iReturn;
+#endif
+
+  /* Create framebuffer */
+  if (!(*pScreenPriv->pwinAllocateFB) (pScreen))
+    {
+      ErrorF ("winFinishScreenInitFB - Could not allocate framebuffer\n");
+      return FALSE;
+    }
+
+  /*
+   * Grab the number of bits that are used to represent color in each pixel.
+   */
+  if (pScreenInfo->dwBPP == 8)
+    pScreenInfo->dwDepth = 8;
+  else
+    pScreenInfo->dwDepth = winCountBits (pScreenPriv->dwRedMask)
+      + winCountBits (pScreenPriv->dwGreenMask)
+      + winCountBits (pScreenPriv->dwBlueMask);
+  
+  winErrorFVerb (2, "winFinishScreenInitFB - Masks: %08x %08x %08x\n",
+	  (unsigned int) pScreenPriv->dwRedMask,
+	  (unsigned int) pScreenPriv->dwGreenMask,
+	  (unsigned int) pScreenPriv->dwBlueMask);
+
+  /* Init visuals */
+  if (!(*pScreenPriv->pwinInitVisuals) (pScreen))
+    {
+      ErrorF ("winFinishScreenInitFB - winInitVisuals failed\n");
+      return FALSE;
+    }
+
+  /* Setup a local variable to point to the framebuffer */
+  pbits = pScreenInfo->pfb;
+  
+  /* Apparently we need this for the render extension */
+  miSetPixmapDepths ();
+
+  /* Start fb initialization */
+  if (!fbSetupScreen (pScreen,
+		      pScreenInfo->pfb,
+		      pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+		      monitorResolution, monitorResolution,
+		      pScreenInfo->dwStride,
+		      pScreenInfo->dwBPP))
+    {
+      ErrorF ("winFinishScreenInitFB - fbSetupScreen failed\n");
+      return FALSE;
+    }
+
+  /* Override default colormap routines if visual class is dynamic */
+  if (pScreenInfo->dwDepth == 8
+      && (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI
+	  || (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
+	      && pScreenInfo->fFullScreen)
+	  || (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
+	      && pScreenInfo->fFullScreen)))
+    {
+      winSetColormapFunctions (pScreen);
+
+      /*
+       * NOTE: Setting whitePixel to 255 causes Magic 7.1 to allocate its
+       * own colormap, as it cannot allocate 7 planes in the default
+       * colormap.  Setting whitePixel to 1 allows Magic to get 7
+       * planes in the default colormap, so it doesn't create its
+       * own colormap.  This latter situation is highly desireable,
+       * as it keeps the Magic window viewable when switching to
+       * other X clients that use the default colormap.
+       */
+      pScreen->blackPixel = 0;
+      pScreen->whitePixel = 1;
+    }
+
+  /* Place our save screen function */
+  pScreen->SaveScreen = winSaveScreen;
+
+  /* Finish fb initialization */
+  if (!fbFinishScreenInit (pScreen,
+			   pScreenInfo->pfb,
+			   pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+			   monitorResolution, monitorResolution,
+			   pScreenInfo->dwStride,
+			   pScreenInfo->dwBPP))
+    {
+      ErrorF ("winFinishScreenInitFB - fbFinishScreenInit failed\n");
+      return FALSE;
+    }
+
+  /* Save a pointer to the root visual */
+  for (pVisual = pScreen->visuals;
+       pVisual->vid != pScreen->rootVisual;
+       pVisual++);
+  pScreenPriv->pRootVisual = pVisual;
+
+  /* 
+   * Setup points to the block and wakeup handlers.  Pass a pointer
+   * to the current screen as pWakeupdata.
+   */
+  pScreen->BlockHandler = winBlockHandler;
+  pScreen->WakeupHandler = winWakeupHandler;
+  pScreen->blockData = pScreen;
+  pScreen->wakeupData = pScreen;
+
+#ifdef RENDER
+  /* Render extension initialization, calls miPictureInit */
+  if (!fbPictureInit (pScreen, NULL, 0))
+    {
+      ErrorF ("winFinishScreenInitFB - fbPictureInit () failed\n");
+      return FALSE;
+    }
+#endif
+
+#ifdef RANDR
+  /* Initialize resize and rotate support */
+  if (!winRandRInit (pScreen))
+    {
+      ErrorF ("winFinishScreenInitFB - winRandRInit () failed\n");
+      return FALSE;
+    }
+#endif
+
+  /*
+   * Backing store support should reduce network traffic and increase
+   * performance.
+   */
+  miInitializeBackingStore (pScreen);
+
+  /* KDrive does miDCInitialize right after miInitializeBackingStore */
+  /* Setup the cursor routines */
+#if CYGDEBUG
+  winDebug ("winFinishScreenInitFB - Calling miDCInitialize ()\n");
+#endif
+  miDCInitialize (pScreen, &g_winPointerCursorFuncs);
+
+  /* KDrive does winCreateDefColormap right after miDCInitialize */
+  /* Create a default colormap */
+#if CYGDEBUG
+  winDebug ("winFinishScreenInitFB - Calling winCreateDefColormap ()\n");
+#endif
+  if (!winCreateDefColormap (pScreen))
+    {
+      ErrorF ("winFinishScreenInitFB - Could not create colormap\n");
+      return FALSE;
+    }
+
+  /* Initialize the shadow framebuffer layer */
+  if ((pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI
+       || pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
+       || pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL)
+#ifdef XWIN_MULTIWINDOWEXTWM
+      && !pScreenInfo->fMWExtWM
+#endif
+      )
+    {
+#if CYGDEBUG
+      winDebug ("winFinishScreenInitFB - Calling shadowSetup ()\n");
+#endif
+      if (!shadowSetup(pScreen))
+	{
+	  ErrorF ("winFinishScreenInitFB - shadowSetup () failed\n");
+	  return FALSE;
+	}
+
+      /* Wrap CreateScreenResources so we can add the screen pixmap
+         to the Shadow framebuffer after it's been created */
+      pScreenPriv->pwinCreateScreenResources = pScreen->CreateScreenResources;
+      pScreen->CreateScreenResources = winCreateScreenResources;
+    }
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  /* Handle multi-window external window manager mode */
+  if (pScreenInfo->fMWExtWM)
+    {
+      winDebug ("winScreenInit - MultiWindowExtWM - Calling RootlessInit\n");
+      
+      RootlessInit(pScreen, &winMWExtWMProcs);
+      
+      winDebug ("winScreenInit - MultiWindowExtWM - RootlessInit returned\n");
+      
+      rootless_CopyBytes_threshold = 0;
+      rootless_FillBytes_threshold = 0;
+      rootless_CompositePixels_threshold = 0;
+      /* FIXME: How many? Profiling needed? */
+      rootless_CopyWindow_threshold = 1;
+
+      winWindowsWMExtensionInit ();
+    }
+#endif
+
+  /* Handle rootless mode */
+  if (pScreenInfo->fRootless)
+    {
+      /* Define the WRAP macro temporarily for local use */
+#define WRAP(a) \
+    if (pScreen->a) { \
+        pScreenPriv->a = pScreen->a; \
+    } else { \
+        ErrorF("null screen fn " #a "\n"); \
+        pScreenPriv->a = NULL; \
+    }
+
+      /* Save a pointer to each lower-level window procedure */
+      WRAP(CreateWindow);
+      WRAP(DestroyWindow);
+      WRAP(RealizeWindow);
+      WRAP(UnrealizeWindow);
+      WRAP(PositionWindow);
+      WRAP(ChangeWindowAttributes);
+      WRAP(SetShape);
+
+      /* Assign rootless window procedures to be top level procedures */
+      pScreen->CreateWindow = winCreateWindowRootless;
+      pScreen->DestroyWindow = winDestroyWindowRootless;
+      pScreen->PositionWindow = winPositionWindowRootless;
+      /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesRootless;*/
+      pScreen->RealizeWindow = winMapWindowRootless;
+      pScreen->UnrealizeWindow = winUnmapWindowRootless;
+      pScreen->SetShape = winSetShapeRootless;
+
+      /* Undefine the WRAP macro, as it is not needed elsewhere */
+#undef WRAP
+    }
+
+
+#ifdef XWIN_MULTIWINDOW
+  /* Handle multi window mode */
+  else if (pScreenInfo->fMultiWindow)
+    {
+      /* Define the WRAP macro temporarily for local use */
+#define WRAP(a) \
+    if (pScreen->a) { \
+        pScreenPriv->a = pScreen->a; \
+    } else { \
+        ErrorF("null screen fn " #a "\n"); \
+        pScreenPriv->a = NULL; \
+    }
+
+      /* Save a pointer to each lower-level window procedure */
+      WRAP(CreateWindow);
+      WRAP(DestroyWindow);
+      WRAP(RealizeWindow);
+      WRAP(UnrealizeWindow);
+      WRAP(PositionWindow);
+      WRAP(ChangeWindowAttributes);
+      WRAP(ReparentWindow);
+      WRAP(RestackWindow);
+      WRAP(ResizeWindow);
+      WRAP(MoveWindow);
+      WRAP(CopyWindow);
+      WRAP(SetShape);
+
+      /* Assign multi-window window procedures to be top level procedures */
+      pScreen->CreateWindow = winCreateWindowMultiWindow;
+      pScreen->DestroyWindow = winDestroyWindowMultiWindow;
+      pScreen->PositionWindow = winPositionWindowMultiWindow;
+      /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesMultiWindow;*/
+      pScreen->RealizeWindow = winMapWindowMultiWindow;
+      pScreen->UnrealizeWindow = winUnmapWindowMultiWindow;
+      pScreen->ReparentWindow = winReparentWindowMultiWindow;
+      pScreen->RestackWindow = winRestackWindowMultiWindow;
+      pScreen->ResizeWindow = winResizeWindowMultiWindow;
+      pScreen->MoveWindow = winMoveWindowMultiWindow;
+      pScreen->CopyWindow = winCopyWindowMultiWindow;
+      pScreen->SetShape = winSetShapeMultiWindow;
+
+      /* Undefine the WRAP macro, as it is not needed elsewhere */
+#undef WRAP
+    }
+#endif
+
+  /* Wrap either fb's or shadow's CloseScreen with our CloseScreen */
+  pScreenPriv->CloseScreen = pScreen->CloseScreen;
+  pScreen->CloseScreen = pScreenPriv->pwinCloseScreen;
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Create a mutex for modules in separate threads to wait for */
+  iReturn = pthread_mutex_init (&pScreenPriv->pmServerStarted, NULL);
+  if (iReturn != 0)
+    {
+      ErrorF ("winFinishScreenInitFB - pthread_mutex_init () failed: %d\n",
+	      iReturn);
+      return FALSE;
+    }
+
+  /* Own the mutex for modules in separate threads */
+  iReturn = pthread_mutex_lock (&pScreenPriv->pmServerStarted);
+  if (iReturn != 0)
+    {
+      ErrorF ("winFinishScreenInitFB - pthread_mutex_lock () failed: %d\n",
+	      iReturn);
+      return FALSE;
+    }
+
+  /* Set the ServerStarted flag to false */
+  pScreenPriv->fServerStarted = FALSE;
+#endif
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  pScreenPriv->fRestacking = FALSE;
+#endif
+
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+  if (FALSE
+#ifdef XWIN_MULTIWINDOW
+      || pScreenInfo->fMultiWindow
+#endif
+#ifdef XWIN_MULTIWINDOWEXTWM
+      || pScreenInfo->fInternalWM
+#endif
+      )
+    { 
+#if CYGDEBUG || YES
+      winDebug ("winFinishScreenInitFB - Calling winInitWM.\n");
+#endif
+
+      /* Initialize multi window mode */
+      if (!winInitWM (&pScreenPriv->pWMInfo,
+		      &pScreenPriv->ptWMProc,
+		      &pScreenPriv->ptXMsgProc,
+		      &pScreenPriv->pmServerStarted,
+		      pScreenInfo->dwScreen,
+		      (HWND)&pScreenPriv->hwndScreen,
+#ifdef XWIN_MULTIWINDOWEXTWM
+		      pScreenInfo->fInternalWM ||
+#endif
+		      FALSE))
+        {
+          ErrorF ("winFinishScreenInitFB - winInitWM () failed.\n");
+          return FALSE;
+        }
+    }      
+#endif
+
+  /* Tell the server that we are enabled */
+  pScreenPriv->fEnabled = TRUE;
+
+  /* Tell the server that we have a valid depth */
+  pScreenPriv->fBadDepth = FALSE;
+
+#if CYGDEBUG || YES
+  winDebug ("winFinishScreenInitFB - returning\n");
+#endif
+
+  return TRUE;
+}
+
+#ifdef XWIN_NATIVEGDI
+/* See Porting Layer Definition - p. 20 */
+
+Bool
+winFinishScreenInitNativeGDI (int index,
+			      ScreenPtr pScreen,
+			      int argc, char **argv)
+{
+  winScreenPriv(pScreen);
+  winScreenInfoPtr      pScreenInfo = &g_ScreenInfo[index];
+  VisualPtr		pVisuals = NULL;
+  DepthPtr		pDepths = NULL;
+  VisualID		rootVisual = 0;
+  int			nVisuals = 0, nDepths = 0, nRootDepth = 0;
+
+  /* Ignore user input (mouse, keyboard) */
+  pScreenInfo->fIgnoreInput = FALSE;
+
+  /* Get device contexts for the screen and shadow bitmap */
+  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
+  if (pScreenPriv->hdcScreen == NULL)
+    FatalError ("winFinishScreenInitNativeGDI - Couldn't get a DC\n");
+
+  /* Init visuals */
+  if (!(*pScreenPriv->pwinInitVisuals) (pScreen))
+    {
+      ErrorF ("winFinishScreenInitNativeGDI - pwinInitVisuals failed\n");
+      return FALSE;
+    }
+
+  /* Initialize the mi visuals */
+  if (!miInitVisuals (&pVisuals, &pDepths, &nVisuals, &nDepths, &nRootDepth,
+		      &rootVisual,
+		      ((unsigned long)1 << (pScreenInfo->dwDepth - 1)), 8,
+		      TrueColor))
+    {
+      ErrorF ("winFinishScreenInitNativeGDI - miInitVisuals () failed\n");
+      return FALSE;
+    }
+
+  /* Initialize the CloseScreen procedure pointer */
+  pScreen->CloseScreen = NULL;
+
+  /* Initialize the mi code */
+  if (!miScreenInit (pScreen,
+		     NULL, /* No framebuffer */
+		     pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+		     monitorResolution, monitorResolution,
+		     pScreenInfo->dwStride,
+		     nRootDepth, nDepths, pDepths, rootVisual,
+		     nVisuals, pVisuals))
+    {
+      ErrorF ("winFinishScreenInitNativeGDI - miScreenInit failed\n");
+      return FALSE;
+    }
+
+  pScreen->defColormap = FakeClientID(0);
+
+  /*
+   * Register our block and wakeup handlers; these procedures
+   * process messages in our Windows message queue; specifically,
+   * they process mouse and keyboard input.
+   */
+  pScreen->BlockHandler = winBlockHandler;
+  pScreen->WakeupHandler = winWakeupHandler;
+  pScreen->blockData = pScreen;
+  pScreen->wakeupData = pScreen;
+
+  /* Place our save screen function */
+  pScreen->SaveScreen = winSaveScreen;
+
+  /* Pixmaps */
+  pScreen->CreatePixmap = winCreatePixmapNativeGDI;
+  pScreen->DestroyPixmap = winDestroyPixmapNativeGDI;
+
+  /* Other Screen Routines */
+  pScreen->QueryBestSize = winQueryBestSizeNativeGDI;
+  pScreen->SaveScreen = winSaveScreen;  
+  pScreen->GetImage = miGetImage;
+  pScreen->GetSpans = winGetSpansNativeGDI;
+
+  /* Window Procedures */
+  pScreen->CreateWindow = winCreateWindowNativeGDI;
+  pScreen->DestroyWindow = winDestroyWindowNativeGDI;
+  pScreen->PositionWindow = winPositionWindowNativeGDI;
+  /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesNativeGDI;*/
+  pScreen->RealizeWindow = winMapWindowNativeGDI;
+  pScreen->UnrealizeWindow = winUnmapWindowNativeGDI;
+
+  /* Paint window */
+  pScreen->CopyWindow = winCopyWindowNativeGDI;
+
+  /* Fonts */
+  pScreen->RealizeFont = winRealizeFontNativeGDI;
+  pScreen->UnrealizeFont = winUnrealizeFontNativeGDI;
+
+  /* GC */
+  pScreen->CreateGC = winCreateGCNativeGDI;
+
+  /* Colormap Routines */
+  pScreen->CreateColormap = miInitializeColormap;
+  pScreen->DestroyColormap = (DestroyColormapProcPtr) (void (*)(void)) NoopDDA;
+  pScreen->InstallColormap = miInstallColormap;
+  pScreen->UninstallColormap = miUninstallColormap;
+  pScreen->ListInstalledColormaps = miListInstalledColormaps;
+  pScreen->StoreColors = (StoreColorsProcPtr) (void (*)(void)) NoopDDA;
+  pScreen->ResolveColor = miResolveColor;
+
+  /* Bitmap */
+  pScreen->BitmapToRegion = winPixmapToRegionNativeGDI;
+
+  ErrorF ("winFinishScreenInitNativeGDI - calling miDCInitialize\n");
+
+  /* Set the default white and black pixel positions */
+  pScreen->whitePixel = pScreen->blackPixel = (Pixel) 0;
+
+  /* Initialize the cursor */
+  if (!miDCInitialize (pScreen, &g_winPointerCursorFuncs))
+    {
+      ErrorF ("winFinishScreenInitNativeGDI - miDCInitialize failed\n");
+      return FALSE;
+    }
+  
+  /* Create a default colormap */
+  if (!miCreateDefColormap (pScreen))
+    {
+        ErrorF ("winFinishScreenInitNativeGDI - miCreateDefColormap () "
+		"failed\n");
+	return FALSE;
+    }
+
+  ErrorF ("winFinishScreenInitNativeGDI - miCreateDefColormap () "
+	  "returned\n");
+  
+  /* mi doesn't use a CloseScreen procedure, so no need to wrap */
+  pScreen->CloseScreen = pScreenPriv->pwinCloseScreen;
+
+  /* Tell the server that we are enabled */
+  pScreenPriv->fEnabled = TRUE;
+
+  ErrorF ("winFinishScreenInitNativeGDI - Successful addition of "
+	  "screen %08x\n",
+	  (unsigned int) pScreen);
+
+  return TRUE;
+}
+#endif
+
+
+/* See Porting Layer Definition - p. 33 */
+static Bool
+winSaveScreen (ScreenPtr pScreen, int on)
+{
+  return TRUE;
+}
diff --git a/xorg-server/hw/xwin/winshaddd.c b/xorg-server/hw/xwin/winshaddd.c
index 833444177..510c77c63 100644
--- a/xorg-server/hw/xwin/winshaddd.c
+++ b/xorg-server/hw/xwin/winshaddd.c
@@ -1,1455 +1,1455 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * External symbols
- */
-
-extern HWND			g_hDlgExit;
-extern char *g_pszLogFile;
-
-/*
- * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly,
- * so we have to redefine it here.
- */
-#ifdef DEFINE_GUID
-#undef DEFINE_GUID
-#define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
-#endif /* DEFINE_GUID */
-
-
-/*
- * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined
- * here manually.  Should be handled by ddraw.h
- */
-#ifndef IID_IDirectDraw2
-DEFINE_GUID( IID_IDirectDraw2,0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
-#endif /* IID_IDirectDraw2 */
-
-
-/*
- * Local prototypes
- */
-
-static Bool
-winAllocateFBShadowDD (ScreenPtr pScreen);
-
-static void
-winShadowUpdateDD (ScreenPtr pScreen, 
-		   shadowBufPtr pBuf);
-
-static Bool
-winCloseScreenShadowDD (int nIndex, ScreenPtr pScreen);
-
-static Bool
-winInitVisualsShadowDD (ScreenPtr pScreen);
-
-static Bool
-winAdjustVideoModeShadowDD (ScreenPtr pScreen);
-
-static Bool
-winBltExposedRegionsShadowDD (ScreenPtr pScreen);
-
-static Bool
-winActivateAppShadowDD (ScreenPtr pScreen);
-
-static Bool
-winRedrawScreenShadowDD (ScreenPtr pScreen);
-
-static Bool
-winRealizeInstalledPaletteShadowDD (ScreenPtr pScreen);
-
-static Bool
-winInstallColormapShadowDD (ColormapPtr pColormap);
-
-static Bool
-winStoreColorsShadowDD (ColormapPtr pmap, 
-			int ndef,
-			xColorItem *pdefs);
-
-static Bool
-winCreateColormapShadowDD (ColormapPtr pColormap);
-
-static Bool
-winDestroyColormapShadowDD (ColormapPtr pColormap);
-
-static Bool
-winCreatePrimarySurfaceShadowDD (ScreenPtr pScreen);
-
-static Bool
-winReleasePrimarySurfaceShadowDD (ScreenPtr pScreen);
-
-
-/*
- * Create the primary surface and attach the clipper.
- * Used for both the initial surface creation and during
- * WM_DISPLAYCHANGE messages.
- */
-
-static Bool
-winCreatePrimarySurfaceShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC		ddsd;
-
-  /* Describe the primary surface */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-  
-  /* Create the primary surface */
-  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
-				       &ddsd,
-				       &pScreenPriv->pddsPrimary,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreatePrimarySurfaceShadowDD - Could not create primary "
-	      "surface: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-  
-#if CYGDEBUG
-  winDebug ("winCreatePrimarySurfaceShadowDD - Created primary surface\n");
-#endif
-
-  /*
-   * Attach a clipper to the primary surface that will clip our blits to our
-   * display window.
-   */
-  ddrval = IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
-					   pScreenPriv->pddcPrimary);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreatePrimarySurfaceShadowDD - Primary attach clipper "
-	      "failed: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winCreatePrimarySurfaceShadowDD - Attached clipper to "
-	  "primary surface\n");
-#endif
-
-  /* Everything was correct */
-  return TRUE;
-}
-
-
-/*
- * Detach the clipper and release the primary surface.
- * Called from WM_DISPLAYCHANGE.
- */
-
-static Bool
-winReleasePrimarySurfaceShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-
-  ErrorF ("winReleasePrimarySurfaceShadowDD - Hello\n");
-
-  /* Release the primary surface and clipper, if they exist */
-  if (pScreenPriv->pddsPrimary)
-    {
-      /*
-       * Detach the clipper from the primary surface.
-       * NOTE: We do this explicity for clarity.  The Clipper is not released.
-       */
-      IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
-				      NULL);
-
-      ErrorF ("winReleasePrimarySurfaceShadowDD - Detached clipper\n");
-
-      /* Release the primary surface */
-      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
-      pScreenPriv->pddsPrimary = NULL;
-    }
-
-  ErrorF ("winReleasePrimarySurfaceShadowDD - Released primary surface\n");
-
-  return TRUE;
-}
-
-
-/*
- * Create a DirectDraw surface for the shadow framebuffer; also create
- * a primary surface object so we can blit to the display.
- * 
- * Install a DirectDraw clipper on our primary surface object
- * that clips our blits to the unobscured client area of our display window.
- */
-
-static Bool
-winAllocateFBShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC		ddsd;
-  DDSURFACEDESC		*pddsdShadow = NULL;
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD\n");
-#endif
-
-  /* Create a clipper */
-  ddrval = (*g_fpDirectDrawCreateClipper) (0,
-					   &pScreenPriv->pddcPrimary,
-					   NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not create clipper: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Created a clipper\n");
-#endif
-
-  /* Get a device context for the screen  */
-  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
-
-  /* Attach the clipper to our display window */
-  ddrval = IDirectDrawClipper_SetHWnd (pScreenPriv->pddcPrimary,
-				       0,
-				       pScreenPriv->hwndScreen);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Clipper not attached to "
-	      "window: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Attached clipper to window\n");
-#endif
-
-  /* Create a DirectDraw object, store the address at lpdd */
-  ddrval = (*g_fpDirectDrawCreate) (NULL, &pScreenPriv->pdd, NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not start DirectDraw: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD () - Created and initialized DD\n");
-#endif
-
-  /* Get a DirectDraw2 interface pointer */
-  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
-				       &IID_IDirectDraw2,
-				       (LPVOID*) &pScreenPriv->pdd2);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Failed DD2 query: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-  /* Are we full screen? */
-  if (pScreenInfo->fFullScreen)
-    {
-      DDSURFACEDESC	ddsdCurrent;
-      DWORD		dwRefreshRateCurrent = 0;
-      HDC		hdc = NULL;
-
-      /* Set the cooperative level to full screen */
-      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_EXCLUSIVE
-						 | DDSCL_FULLSCREEN);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winAllocateFBShadowDD - Could not set "
-		  "cooperative level: %08x\n",
-		  (unsigned int) ddrval);
-	  return FALSE;
-	}
-
-      /*
-       * We only need to get the current refresh rate for comparison
-       * if a refresh rate has been passed on the command line.
-       */
-      if (pScreenInfo->dwRefreshRate != 0)
-	{
-	  ZeroMemory (&ddsdCurrent, sizeof (ddsdCurrent));
-	  ddsdCurrent.dwSize = sizeof (ddsdCurrent);
-	  
-	  /* Get information about current display settings */
-	  ddrval = IDirectDraw2_GetDisplayMode (pScreenPriv->pdd2,
-						&ddsdCurrent);
-	  if (FAILED (ddrval))
-	    {
-	      ErrorF ("winAllocateFBShadowDD - Could not get current "
-		      "refresh rate: %08x.  Continuing.\n",
-		      (unsigned int) ddrval);
-	      dwRefreshRateCurrent = 0;
-	    }
-	  else
-	    {
-	      /* Grab the current refresh rate */
-	      dwRefreshRateCurrent = ddsdCurrent.u2.dwRefreshRate;
-	    }
-	}
-
-      /* Clean up the refresh rate */
-      if (dwRefreshRateCurrent == pScreenInfo->dwRefreshRate)
-	{
-	  /*
-	   * Refresh rate is non-specified or equal to current.
-	   */
-	  pScreenInfo->dwRefreshRate = 0;
-	}
-
-      /* Grab a device context for the screen */
-      hdc = GetDC (NULL);
-      if (hdc == NULL)
-	{
-	  ErrorF ("winAllocateFBShadowDD - GetDC () failed\n");
-	  return FALSE;
-	}
-
-      /* Only change the video mode when different than current mode */
-      if (!pScreenInfo->fMultipleMonitors
-	  && (pScreenInfo->dwWidth != GetSystemMetrics (SM_CXSCREEN)
-	      || pScreenInfo->dwHeight != GetSystemMetrics (SM_CYSCREEN)
-	      || pScreenInfo->dwBPP != GetDeviceCaps (hdc, BITSPIXEL)
-	      || pScreenInfo->dwRefreshRate != 0))
-	{
-	  ErrorF ("winAllocateFBShadowDD - Changing video mode\n");
-
-	  /* Change the video mode to the mode requested, and use the driver default refresh rate on failure */
-	  ddrval = IDirectDraw2_SetDisplayMode (pScreenPriv->pdd2,
-						pScreenInfo->dwWidth,
-						pScreenInfo->dwHeight,
-						pScreenInfo->dwBPP,
-						pScreenInfo->dwRefreshRate,
-						0);
-	  if (FAILED (ddrval))
-	    {
-	      ErrorF ("winAllocateFBShadowDD - Could not set "\
-		      "full screen display mode: %08x\n",
-		      (unsigned int) ddrval);
-	      ErrorF ("winAllocateFBShadowDD - Using default driver refresh rate\n");
-	      ddrval = IDirectDraw2_SetDisplayMode (pScreenPriv->pdd2,
-						    pScreenInfo->dwWidth,
-						    pScreenInfo->dwHeight,
-						    pScreenInfo->dwBPP,
-						    0,
-						    0);
-	      if (FAILED(ddrval))
-		{
-			ErrorF ("winAllocateFBShadowDD - Could not set default refresh rate "
-				"full screen display mode: %08x\n",
-				(unsigned int) ddrval);
-			return FALSE;
-		}
-	    }
-	}
-      else
-	{
-	  ErrorF ("winAllocateFBShadowDD - Not changing video mode\n");
-	}
-
-      /* Release our DC */
-      ReleaseDC (NULL, hdc);
-      hdc = NULL;
-    }
-  else
-    {
-      /* Set the cooperative level for windowed mode */
-      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_NORMAL);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winAllocateFBShadowDD - Could not set "\
-		  "cooperative level: %08x\n",
-		  (unsigned int) ddrval);
-	  return FALSE;
-	}
-    }
-
-  /* Create the primary surface */
-  if (!winCreatePrimarySurfaceShadowDD (pScreen))
-    {
-      ErrorF ("winAllocateFBShadowDD - winCreatePrimarySurfaceShadowDD "
-	      "failed\n");
-      return FALSE;
-    }
-
-  /* Describe the shadow surface to be created */
-  /* NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
-   * as drawing, locking, and unlocking take forever
-   * with video memory surfaces.  In addition,
-   * video memory is a somewhat scarce resource,
-   * so you shouldn't be allocating video memory when
-   * you have the option of using system memory instead.
-   */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
-  ddsd.dwHeight = pScreenInfo->dwHeight;
-  ddsd.dwWidth = pScreenInfo->dwWidth;
-
-  /* Create the shadow surface */
-  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
-				       &ddsd,
-				       &pScreenPriv->pddsShadow,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not create shadow "\
-	      "surface: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-  
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Created shadow\n");
-#endif
-
-  /* Allocate a DD surface description for our screen privates */
-  pddsdShadow = pScreenPriv->pddsdShadow = malloc (sizeof (DDSURFACEDESC));
-  if (pddsdShadow == NULL)
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not allocate surface "\
-	      "description memory\n");
-      return FALSE;
-    }
-  ZeroMemory (pddsdShadow, sizeof (*pddsdShadow));
-  pddsdShadow->dwSize = sizeof (*pddsdShadow);
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Locking shadow\n");
-#endif
-
-  /* Lock the shadow surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
-				     NULL,
-				     pddsdShadow,
-				     DDLOCK_WAIT,
-				     NULL);
-  if (FAILED (ddrval) || pddsdShadow->lpSurface == NULL)
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not lock shadow "\
-	      "surface: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Locked shadow\n");
-#endif
-
-  /* We don't know how to deal with anything other than RGB */
-  if (!(pddsdShadow->ddpfPixelFormat.dwFlags & DDPF_RGB))
-    {
-      ErrorF ("winAllocateFBShadowDD - Color format other than RGB\n");
-      return FALSE;
-    }
-
-  /* Grab the pitch from the surface desc */
-  pScreenInfo->dwStride = (pddsdShadow->u1.lPitch * 8)
-    / pScreenInfo->dwBPP;
-
-  /* Save the pointer to our surface memory */
-  pScreenInfo->pfb = pddsdShadow->lpSurface;
-  
-  /* Grab the color depth and masks from the surface description */
-  pScreenPriv->dwRedMask = pddsdShadow->ddpfPixelFormat.u2.dwRBitMask;
-  pScreenPriv->dwGreenMask = pddsdShadow->ddpfPixelFormat.u3.dwGBitMask;
-  pScreenPriv->dwBlueMask = pddsdShadow->ddpfPixelFormat.u4.dwBBitMask;
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Transfer the damaged regions of the shadow framebuffer to the display.
- */
-
-static void
-winShadowUpdateDD (ScreenPtr pScreen, 
-		   shadowBufPtr pBuf)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RegionPtr		damage = shadowDamage(pBuf);
-  HRESULT		ddrval = DD_OK;
-  RECT			rcDest, rcSrc;
-  POINT			ptOrigin;
-  DWORD			dwBox = REGION_NUM_RECTS (damage);
-  BoxPtr		pBox = REGION_RECTS (damage);
-  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
-
-  /*
-   * Return immediately if the app is not active
-   * and we are fullscreen, or if we have a bad display depth
-   */
-  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
-      || pScreenPriv->fBadDepth) return;
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-
-  /* Unlock the shadow surface, so we can blit */
-  ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winShadowUpdateDD - Unlock failed\n");
-      return;
-    }
-
-  /*
-   * Handle small regions with multiple blits,
-   * handle large regions by creating a clipping region and 
-   * doing a single blit constrained to that clipping region.
-   */
-  if (pScreenInfo->dwClipUpdatesNBoxes == 0
-      || dwBox < pScreenInfo->dwClipUpdatesNBoxes)
-    {
-      /* Loop through all boxes in the damaged region */
-      while (dwBox--)
-	{
-	  /* Assign damage box to source rectangle */
-	  rcSrc.left = pBox->x1;
-	  rcSrc.top = pBox->y1;
-	  rcSrc.right = pBox->x2;
-	  rcSrc.bottom = pBox->y2;
-	  
-	  /* Calculate destination rectange */
-	  rcDest.left = ptOrigin.x + rcSrc.left;
-	  rcDest.top = ptOrigin.y + rcSrc.top;
-	  rcDest.right = ptOrigin.x + rcSrc.right;
-	  rcDest.bottom = ptOrigin.y + rcSrc.bottom;
-	  
-	  /* Blit the damaged areas */
-	  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-					    &rcDest,
-					    pScreenPriv->pddsShadow,
-					    &rcSrc,
-					    DDBLT_WAIT,
-					    NULL);
-	  
-	  /* Get a pointer to the next box */
-	  ++pBox;
-	}
-    }
-  else
-    {
-      BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
-
-      /* Compute a GDI region from the damaged region */
-      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-      dwBox--;
-      pBox++;
-      while (dwBox--)
-	{
-	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
-	  DeleteObject (hrgnTemp);
-	  pBox++;
-	}  
-
-      /* Install the GDI region as a clipping region */
-      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
-      DeleteObject (hrgnCombined);
-      hrgnCombined = NULL;
-
-      /* Calculating a bounding box for the source is easy */
-      rcSrc.left = pBoxExtents->x1;
-      rcSrc.top = pBoxExtents->y1;
-      rcSrc.right = pBoxExtents->x2;
-      rcSrc.bottom = pBoxExtents->y2;
-
-      /* Calculating a bounding box for the destination is trickier */
-      rcDest.left = ptOrigin.x + rcSrc.left;
-      rcDest.top = ptOrigin.y + rcSrc.top;
-      rcDest.right = ptOrigin.x + rcSrc.right;
-      rcDest.bottom = ptOrigin.y + rcSrc.bottom;
-      
-      /* Our Blt should be clipped to the invalidated region */
-      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-					&rcDest,
-					pScreenPriv->pddsShadow,
-					&rcSrc,
-					DDBLT_WAIT,
-					NULL);
-
-      /* Reset the clip region */
-      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
-    }
-
-  /* Relock the shadow surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
-				     NULL,
-				     pScreenPriv->pddsdShadow,
-				     DDLOCK_WAIT,
-				     NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winShadowUpdateDD - Lock failed\n");
-      return;
-    }
-
-  /* Has our memory pointer changed? */
-  if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
-    {
-      ErrorF ("winShadowUpdateDD - Memory location of the shadow "
-	      "surface has changed, trying to update the root window "
-	      "pixmap header to point to the new address.  If you get "
-	      "this message and "PROJECT_NAME" freezes or crashes "
-	      "after this message then send a problem report and your "
-	      "%s file to " BUILDERADDR, g_pszLogFile);
-
-      /* Location of shadow framebuffer has changed */
-      pScreenInfo->pfb = pScreenPriv->pddsdShadow->lpSurface;
-      
-      /* Update the screen pixmap */
-      if (!(*pScreen->ModifyPixmapHeader)(pScreen->devPrivate,
-					  pScreen->width,
-					  pScreen->height,
-					  pScreen->rootDepth,
-					  BitsPerPixel (pScreen->rootDepth),
-					  PixmapBytePad (pScreenInfo->dwStride,
-							 pScreenInfo->dwBPP),
-					  pScreenInfo->pfb))
-	{
-	  ErrorF ("winShadowUpdateDD - Bits changed, could not "
-		  "notify fb.\n");
-	  return;
-	}
-    }
-}
-
-
-/*
- * Call the wrapped CloseScreen function.
- * 
- * Free our resources and private structures.
- */
-
-static Bool
-winCloseScreenShadowDD (int nIndex, ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  Bool			fReturn;
-  
-#if CYGDEBUG
-  winDebug ("winCloseScreenShadowDD - Freeing screen resources\n");
-#endif
-
-  /* Flag that the screen is closed */
-  pScreenPriv->fClosed = TRUE;
-  pScreenPriv->fActive = FALSE;
-
-  /* Call the wrapped CloseScreen procedure */
-  WIN_UNWRAP(CloseScreen);
-  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
-
-  /* Free the screen DC */
-  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
-
-  /* Delete the window property */
-  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
-
-  /* Free the shadow surface, if there is one */
-  if (pScreenPriv->pddsShadow)
-    {
-      IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
-      IDirectDrawSurface2_Release (pScreenPriv->pddsShadow);
-      pScreenPriv->pddsShadow = NULL;
-    }
-
-  /* Detach the clipper from the primary surface and release the clipper. */
-  if (pScreenPriv->pddcPrimary)
-    {
-      /* Detach the clipper */
-      IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
-				      NULL);
-
-      /* Release the clipper object */
-      IDirectDrawClipper_Release (pScreenPriv->pddcPrimary);
-      pScreenPriv->pddcPrimary = NULL;
-    }
-
-  /* Release the primary surface, if there is one */
-  if (pScreenPriv->pddsPrimary)
-    {
-      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
-      pScreenPriv->pddsPrimary = NULL;
-    }
-
-  /* Free the DirectDraw2 object, if there is one */
-  if (pScreenPriv->pdd2)
-    {
-      IDirectDraw2_RestoreDisplayMode (pScreenPriv->pdd2);
-      IDirectDraw2_Release (pScreenPriv->pdd2);
-      pScreenPriv->pdd2 = NULL;
-    }
-
-  /* Free the DirectDraw object, if there is one */
-  if (pScreenPriv->pdd)
-    {
-      IDirectDraw_Release (pScreenPriv->pdd);
-      pScreenPriv->pdd = NULL;
-    }
-
-  /* Delete tray icon, if we have one */
-  if (!pScreenInfo->fNoTrayIcon)
-    winDeleteNotifyIcon (pScreenPriv);
-  
-  /* Free the exit confirmation dialog box, if it exists */
-  if (g_hDlgExit != NULL)
-    {
-      DestroyWindow (g_hDlgExit);
-      g_hDlgExit = NULL;
-    }
-
-  /* Kill our window */
-  if (pScreenPriv->hwndScreen)
-    {
-      DestroyWindow (pScreenPriv->hwndScreen);
-      pScreenPriv->hwndScreen = NULL;
-    }
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Destroy the thread startup mutex */
-  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
-#endif
-
-  /* Kill our screeninfo's pointer to the screen */
-  pScreenInfo->pScreen = NULL;
-
-  /* Invalidate the ScreenInfo's fb pointer */
-  pScreenInfo->pfb = NULL;
-
-  /* Free the screen privates for this screen */
-  free ((pointer) pScreenPriv);
-
-  return fReturn;
-}
-
-
-/*
- * Tell mi what sort of visuals we need.
- * 
- * Generally we only need one visual, as our screen can only
- * handle one format at a time, I believe.  You may want
- * to verify that last sentence.
- */
-
-static Bool
-winInitVisualsShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
-
-  /* Count the number of ones in each color mask */
-  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
-  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
-  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
-  
-  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
-  if (dwRedBits == 0 || dwGreenBits == 0 || dwBlueBits == 0)
-    pScreenPriv->dwBitsPerRGB = 8;
-  else if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwRedBits;
-  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwGreenBits;
-  else
-    pScreenPriv->dwBitsPerRGB = dwBlueBits;
-  
-  ErrorF ("winInitVisualsShadowDD - Masks %08x %08x %08x BPRGB %d d %d "
-	  "bpp %d\n",
-	  (unsigned int) pScreenPriv->dwRedMask,
-	  (unsigned int) pScreenPriv->dwGreenMask,
-	  (unsigned int) pScreenPriv->dwBlueMask,
-	  (int) pScreenPriv->dwBitsPerRGB,
-	  (int) pScreenInfo->dwDepth,
-	  (int) pScreenInfo->dwBPP);
-
-  /* Create a single visual according to the Windows screen depth */
-  switch (pScreenInfo->dwDepth)
-    {
-    case 24:
-    case 16:
-    case 15:
-#if defined(XFree86Server)
-      /* Create the real visual */
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     TrueColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!miSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     -1,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#else /* XFree86Server */
-      /* Create the real visual */
-      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!fbSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#endif /* XFree86Server */
-      break;
-
-    case 8:
-#if defined(XFree86Server)
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColorMask : StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColor : StaticColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-#else /* XFree86Server */
-      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColorMask : StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-#endif /* XFree86Server */
-      break;
-
-    default:
-      ErrorF ("winInitVisualsShadowDD - Unknown screen depth\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winInitVisualsShadowDD - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Adjust the user proposed video mode
- */
-
-static Bool
-winAdjustVideoModeShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HDC			hdc = NULL;
-  DWORD			dwBPP;
-
-  /* We're in serious trouble if we can't get a DC */
-  hdc = GetDC (NULL);
-  if (hdc == NULL)
-    {
-      ErrorF ("winAdjustVideoModeShadowDD - GetDC () failed\n");
-      return FALSE;
-    }
-
-  /* Query GDI for current display depth */
-  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* DirectDraw can only change the depth in fullscreen mode */
-  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
-    {
-      /* No -depth parameter passed, let the user know the depth being used */
-      ErrorF ("winAdjustVideoModeShadowDD - Using Windows display "
-	      "depth of %d bits per pixel\n", (int) dwBPP);
-
-      /* Use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  else if (pScreenInfo->fFullScreen
-	   && pScreenInfo->dwBPP != dwBPP)
-    {
-      /* FullScreen, and GDI depth differs from -depth parameter */
-      ErrorF ("winAdjustVideoModeShadowDD - FullScreen, using command line "
-	      "bpp: %d\n", (int) pScreenInfo->dwBPP);
-    }
-  else if (dwBPP != pScreenInfo->dwBPP)
-    {
-      /* Windowed, and GDI depth differs from -depth parameter */
-      ErrorF ("winAdjustVideoModeShadowDD - Windowed, command line bpp: "
-	      "%d, using bpp: %d\n", (int) pScreenInfo->dwBPP, (int) dwBPP);
-
-      /* We'll use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  
-  /* See if the shadow bitmap will be larger than the DIB size limit */
-  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
-      >= WIN_DIB_MAXIMUM_SIZE)
-    {
-      ErrorF ("winAdjustVideoModeShadowDD - Requested DirectDraw surface "
-	      "will be larger than %d MB.  The surface may fail to be "
-	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
-	      "DIB size.  This limit does not apply to Windows NT/2000, and "
-	      "this message may be ignored on those platforms.\n",
-	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
-    }
-
-  /* Release our DC */
-  ReleaseDC (NULL, hdc);
-  return TRUE;
-}
-
-
-/*
- * Blt exposed regions to the screen
- */
-
-static Bool
-winBltExposedRegionsShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RECT			rcSrc, rcDest;
-  POINT			ptOrigin;
-  HDC			hdcUpdate = NULL;
-  PAINTSTRUCT		ps;
-  HRESULT		ddrval = DD_OK;
-  Bool			fReturn = TRUE;
-  Bool			fLocked = TRUE;
-  int			i;
-
-  /* BeginPaint gives us an hdc that clips to the invalidated region */
-  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
-  if (hdcUpdate == NULL)
-    {
-      ErrorF ("winBltExposedRegionsShadowDD - BeginPaint () returned "
-	      "a NULL device context handle.  Aborting blit attempt.\n");
-      return FALSE;
-    }
-  
-  /* Unlock the shadow surface, so we can blit */
-  ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
-  if (FAILED (ddrval))
-    {
-      fReturn = FALSE;
-      goto winBltExposedRegionsShadowDD_Exit;
-    }
-  else
-    {
-      /* Flag that we have unlocked the shadow surface */
-      fLocked = FALSE;
-    }
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-  rcDest.left = ptOrigin.x;
-  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
-  rcDest.top = ptOrigin.y;
-  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
-
-  /* Source can be enter shadow surface, as Blt should clip */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  /* Try to regain the primary surface and blit again if we've lost it */
-  for (i = 0; i <= WIN_REGAIN_SURFACE_RETRIES; ++i)
-    {
-      /* Our Blt should be clipped to the invalidated region */
-      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-					&rcDest,
-					pScreenPriv->pddsShadow,
-					&rcSrc,
-					DDBLT_WAIT,
-					NULL);
-      if (ddrval == DDERR_SURFACELOST)
-	{
-	  /* Surface was lost */
-	  ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Blt "
-		  "reported that the primary surface was lost, "
-		  "trying to restore, retry: %d\n", i + 1);
-
-	  /* Try to restore the surface, once */
-	  ddrval = IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
-	  ErrorF ("winBltExposedRegionsShadowDD - "
-		  "IDirectDrawSurface2_Restore returned: ");
-	  if (ddrval == DD_OK)
-	    ErrorF ("DD_OK\n");
-	  else if (ddrval == DDERR_WRONGMODE)
-	    ErrorF ("DDERR_WRONGMODE\n");
-	  else if (ddrval == DDERR_INCOMPATIBLEPRIMARY)
-	    ErrorF ("DDERR_INCOMPATIBLEPRIMARY\n");
-	  else if (ddrval == DDERR_UNSUPPORTED)
-	    ErrorF ("DDERR_UNSUPPORTED\n");
-	  else if (ddrval == DDERR_INVALIDPARAMS)
-	    ErrorF ("DDERR_INVALIDPARAMS\n");
-	  else if (ddrval == DDERR_INVALIDOBJECT)
-	    ErrorF ("DDERR_INVALIDOBJECT\n");
-	  else
-	    ErrorF ("unknown error: %08x\n", (unsigned int) ddrval);
-
-	  /* Loop around to try the blit one more time */
-	  continue;
-	}
-      else if (FAILED (ddrval))
-	{
-	  fReturn = FALSE;
-	  ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Blt "
-		  "failed, but surface not lost: %08x %d\n",
-		  (unsigned int) ddrval, (int) ddrval);
-	  goto winBltExposedRegionsShadowDD_Exit;
-	}
-      else
-	{
-	  /* Success, stop looping */
-	  break;
-	}
-    }
-
-  /* Relock the shadow surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
-				     NULL,
-				     pScreenPriv->pddsdShadow,
-				     DDLOCK_WAIT,
-				     NULL);
-  if (FAILED (ddrval))
-    {
-      fReturn = FALSE;
-      ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Lock "
-	      "failed\n");
-      goto winBltExposedRegionsShadowDD_Exit;
-    }
-  else
-    {
-      /* Indicate that we have relocked the shadow surface */
-      fLocked = TRUE;
-    }
-
-  /* Has our memory pointer changed? */
-  if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
-    winUpdateFBPointer (pScreen,
-			pScreenPriv->pddsdShadow->lpSurface);
-
- winBltExposedRegionsShadowDD_Exit:
-  /* EndPaint frees the DC */
-  if (hdcUpdate != NULL)
-    EndPaint (pScreenPriv->hwndScreen, &ps);
-
-  /*
-   * Relock the surface if it is not locked.  We don't care if locking fails,
-   * as it will cause the server to shutdown within a few more operations.
-   */
-  if (!fLocked)
-    {
-      IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
-				NULL,
-				pScreenPriv->pddsdShadow,
-				DDLOCK_WAIT,
-				NULL);
-
-      /* Has our memory pointer changed? */
-      if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
-	winUpdateFBPointer (pScreen,
-			    pScreenPriv->pddsdShadow->lpSurface);
-      
-      fLocked = TRUE;
-    }
-  return fReturn;
-}
-
-
-/*
- * Do any engine-specific appliation-activation processing
- */
-
-static Bool
-winActivateAppShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-
-  /*
-   * Do we have a surface?
-   * Are we active?
-   * Are we fullscreen?
-   */
-  if (pScreenPriv != NULL
-      && pScreenPriv->pddsPrimary != NULL
-      && pScreenPriv->fActive)
-    {
-      /* Primary surface was lost, restore it */
-      IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Reblit the shadow framebuffer to the screen.
- */
-
-static Bool
-winRedrawScreenShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HRESULT		ddrval = DD_OK;
-  RECT			rcSrc, rcDest;
-  POINT			ptOrigin;
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-  rcDest.left = ptOrigin.x;
-  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
-  rcDest.top = ptOrigin.y;
-  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
-
-  /* Source can be entire shadow surface, as Blt should clip for us */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  /* Redraw the whole window, to take account for the new colors */
-  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-				    &rcDest,
-				    pScreenPriv->pddsShadow,
-				    &rcSrc,
-				    DDBLT_WAIT,
-				    NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winRedrawScreenShadowDD - IDirectDrawSurface_Blt () "
-	      "failed: %08x\n",
-	      (unsigned int) ddrval);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Realize the currently installed colormap
- */
-
-static Bool
-winRealizeInstalledPaletteShadowDD (ScreenPtr pScreen)
-{
-  return TRUE;
-}
-
-
-/*
- * Install the specified colormap
- */
-
-static Bool
-winInstallColormapShadowDD (ColormapPtr pColormap)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  HRESULT		ddrval = DD_OK;
-
-  /* Install the DirectDraw palette on the primary surface */
-  ddrval = IDirectDrawSurface2_SetPalette (pScreenPriv->pddsPrimary,
-					   pCmapPriv->lpDDPalette);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winInstallColormapShadowDD - Failed installing the "
-	      "DirectDraw palette.\n");
-      return FALSE;
-    }
-
-  /* Save a pointer to the newly installed colormap */
-  pScreenPriv->pcmapInstalled = pColormap;
-
-  return TRUE;
-}
-
-
-/*
- * Store the specified colors in the specified colormap
- */
-
-static Bool
-winStoreColorsShadowDD (ColormapPtr pColormap, 
-			int ndef,
-			xColorItem *pdefs)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  ColormapPtr		curpmap = pScreenPriv->pcmapInstalled;
-  HRESULT		ddrval = DD_OK;
-  
-  /* Put the X colormap entries into the Windows logical palette */
-  ddrval = IDirectDrawPalette_SetEntries (pCmapPriv->lpDDPalette,
-					  0,
-					  pdefs[0].pixel,
-					  ndef,
-					  pCmapPriv->peColors 
-					  + pdefs[0].pixel);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winStoreColorsShadowDD - SetEntries () failed\n");
-      return FALSE;
-    }
-
-  /* Don't install the DirectDraw palette if the colormap is not installed */
-  if (pColormap != curpmap)
-    {
-      return TRUE;
-    }
-
-  if (!winInstallColormapShadowDD (pColormap))
-    {
-      ErrorF ("winStoreColorsShadowDD - Failed installing colormap\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap initialization procedure
- */
-
-static Bool
-winCreateColormapShadowDD (ColormapPtr pColormap)
-{
-  HRESULT		ddrval = DD_OK;
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  
-  /* Create a DirectDraw palette */
-  ddrval = IDirectDraw2_CreatePalette (pScreenPriv->pdd,
-				       DDPCAPS_8BIT | DDPCAPS_ALLOW256,
-				       pCmapPriv->peColors,
-				       &pCmapPriv->lpDDPalette,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreateColormapShadowDD - CreatePalette failed\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap destruction procedure
- */
-
-static Bool
-winDestroyColormapShadowDD (ColormapPtr pColormap)
-{
-  winScreenPriv(pColormap->pScreen);
-  winCmapPriv(pColormap);
-  HRESULT		ddrval = DD_OK;
-
-  /*
-   * Is colormap to be destroyed the default?
-   *
-   * Non-default colormaps should have had winUninstallColormap
-   * called on them before we get here.  The default colormap
-   * will not have had winUninstallColormap called on it.  Thus,
-   * we need to handle the default colormap in a special way.
-   */
-  if (pColormap->flags & IsDefault)
-    {
-#if CYGDEBUG
-      winDebug ("winDestroyColormapShadowDD - Destroying default "
-	      "colormap\n");
-#endif
-      
-      /*
-       * FIXME: Walk the list of all screens, popping the default
-       * palette out of each screen device context.
-       */
-      
-      /* Pop the palette out of the primary surface */
-      ddrval = IDirectDrawSurface2_SetPalette (pScreenPriv->pddsPrimary,
-					       NULL);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winDestroyColormapShadowDD - Failed freeing the "
-		  "default colormap DirectDraw palette.\n");
-	  return FALSE;
-	}
-
-      /* Clear our private installed colormap pointer */
-      pScreenPriv->pcmapInstalled = NULL;
-    }
-  
-  /* Release the palette */
-  IDirectDrawPalette_Release (pCmapPriv->lpDDPalette);
- 
-  /* Invalidate the colormap privates */
-  pCmapPriv->lpDDPalette = NULL;
-
-  return TRUE;
-}
-
-
-/*
- * Set engine specific functions
- */
-
-Bool
-winSetEngineFunctionsShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  
-  /* Set our pointers */
-  pScreenPriv->pwinAllocateFB = winAllocateFBShadowDD;
-  pScreenPriv->pwinShadowUpdate = winShadowUpdateDD;
-  pScreenPriv->pwinCloseScreen = winCloseScreenShadowDD;
-  pScreenPriv->pwinInitVisuals = winInitVisualsShadowDD;
-  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowDD;
-  if (pScreenInfo->fFullScreen)
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
-  else
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
-  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
-  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowDD;
-  pScreenPriv->pwinActivateApp = winActivateAppShadowDD;
-  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowDD;
-  pScreenPriv->pwinRealizeInstalledPalette
-    = winRealizeInstalledPaletteShadowDD;
-  pScreenPriv->pwinInstallColormap = winInstallColormapShadowDD;
-  pScreenPriv->pwinStoreColors = winStoreColorsShadowDD;
-  pScreenPriv->pwinCreateColormap = winCreateColormapShadowDD;
-  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowDD;
-  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
-  pScreenPriv->pwinCreatePrimarySurface = winCreatePrimarySurfaceShadowDD;
-  pScreenPriv->pwinReleasePrimarySurface = winReleasePrimarySurfaceShadowDD;
-#ifdef XWIN_MULTIWINDOW
-  pScreenPriv->pwinFinishCreateWindowsWindow =
-    (winFinishCreateWindowsWindowProcPtr) (void (*)(void))NoopDDA;
-#endif
-
-  return TRUE;
-}
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * External symbols
+ */
+
+extern HWND			g_hDlgExit;
+extern char *g_pszLogFile;
+
+/*
+ * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly,
+ * so we have to redefine it here.
+ */
+#ifdef DEFINE_GUID
+#undef DEFINE_GUID
+#define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#endif /* DEFINE_GUID */
+
+
+/*
+ * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined
+ * here manually.  Should be handled by ddraw.h
+ */
+#ifndef IID_IDirectDraw2
+DEFINE_GUID( IID_IDirectDraw2,0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
+#endif /* IID_IDirectDraw2 */
+
+
+/*
+ * Local prototypes
+ */
+
+static Bool
+winAllocateFBShadowDD (ScreenPtr pScreen);
+
+static void
+winShadowUpdateDD (ScreenPtr pScreen, 
+		   shadowBufPtr pBuf);
+
+static Bool
+winCloseScreenShadowDD (int nIndex, ScreenPtr pScreen);
+
+static Bool
+winInitVisualsShadowDD (ScreenPtr pScreen);
+
+static Bool
+winAdjustVideoModeShadowDD (ScreenPtr pScreen);
+
+static Bool
+winBltExposedRegionsShadowDD (ScreenPtr pScreen);
+
+static Bool
+winActivateAppShadowDD (ScreenPtr pScreen);
+
+static Bool
+winRedrawScreenShadowDD (ScreenPtr pScreen);
+
+static Bool
+winRealizeInstalledPaletteShadowDD (ScreenPtr pScreen);
+
+static Bool
+winInstallColormapShadowDD (ColormapPtr pColormap);
+
+static Bool
+winStoreColorsShadowDD (ColormapPtr pmap, 
+			int ndef,
+			xColorItem *pdefs);
+
+static Bool
+winCreateColormapShadowDD (ColormapPtr pColormap);
+
+static Bool
+winDestroyColormapShadowDD (ColormapPtr pColormap);
+
+static Bool
+winCreatePrimarySurfaceShadowDD (ScreenPtr pScreen);
+
+static Bool
+winReleasePrimarySurfaceShadowDD (ScreenPtr pScreen);
+
+
+/*
+ * Create the primary surface and attach the clipper.
+ * Used for both the initial surface creation and during
+ * WM_DISPLAYCHANGE messages.
+ */
+
+static Bool
+winCreatePrimarySurfaceShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC		ddsd;
+
+  /* Describe the primary surface */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
+  
+  /* Create the primary surface */
+  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
+				       &ddsd,
+				       &pScreenPriv->pddsPrimary,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreatePrimarySurfaceShadowDD - Could not create primary "
+	      "surface: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+  
+#if CYGDEBUG
+  winDebug ("winCreatePrimarySurfaceShadowDD - Created primary surface\n");
+#endif
+
+  /*
+   * Attach a clipper to the primary surface that will clip our blits to our
+   * display window.
+   */
+  ddrval = IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
+					   pScreenPriv->pddcPrimary);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreatePrimarySurfaceShadowDD - Primary attach clipper "
+	      "failed: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winCreatePrimarySurfaceShadowDD - Attached clipper to "
+	  "primary surface\n");
+#endif
+
+  /* Everything was correct */
+  return TRUE;
+}
+
+
+/*
+ * Detach the clipper and release the primary surface.
+ * Called from WM_DISPLAYCHANGE.
+ */
+
+static Bool
+winReleasePrimarySurfaceShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+
+  ErrorF ("winReleasePrimarySurfaceShadowDD - Hello\n");
+
+  /* Release the primary surface and clipper, if they exist */
+  if (pScreenPriv->pddsPrimary)
+    {
+      /*
+       * Detach the clipper from the primary surface.
+       * NOTE: We do this explicity for clarity.  The Clipper is not released.
+       */
+      IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
+				      NULL);
+
+      ErrorF ("winReleasePrimarySurfaceShadowDD - Detached clipper\n");
+
+      /* Release the primary surface */
+      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
+      pScreenPriv->pddsPrimary = NULL;
+    }
+
+  ErrorF ("winReleasePrimarySurfaceShadowDD - Released primary surface\n");
+
+  return TRUE;
+}
+
+
+/*
+ * Create a DirectDraw surface for the shadow framebuffer; also create
+ * a primary surface object so we can blit to the display.
+ * 
+ * Install a DirectDraw clipper on our primary surface object
+ * that clips our blits to the unobscured client area of our display window.
+ */
+
+static Bool
+winAllocateFBShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC		ddsd;
+  DDSURFACEDESC		*pddsdShadow = NULL;
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD\n");
+#endif
+
+  /* Create a clipper */
+  ddrval = (*g_fpDirectDrawCreateClipper) (0,
+					   &pScreenPriv->pddcPrimary,
+					   NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not create clipper: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Created a clipper\n");
+#endif
+
+  /* Get a device context for the screen  */
+  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
+
+  /* Attach the clipper to our display window */
+  ddrval = IDirectDrawClipper_SetHWnd (pScreenPriv->pddcPrimary,
+				       0,
+				       pScreenPriv->hwndScreen);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Clipper not attached to "
+	      "window: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Attached clipper to window\n");
+#endif
+
+  /* Create a DirectDraw object, store the address at lpdd */
+  ddrval = (*g_fpDirectDrawCreate) (NULL, &pScreenPriv->pdd, NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not start DirectDraw: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD () - Created and initialized DD\n");
+#endif
+
+  /* Get a DirectDraw2 interface pointer */
+  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
+				       &IID_IDirectDraw2,
+				       (LPVOID*) &pScreenPriv->pdd2);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Failed DD2 query: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+  /* Are we full screen? */
+  if (pScreenInfo->fFullScreen)
+    {
+      DDSURFACEDESC	ddsdCurrent;
+      DWORD		dwRefreshRateCurrent = 0;
+      HDC		hdc = NULL;
+
+      /* Set the cooperative level to full screen */
+      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_EXCLUSIVE
+						 | DDSCL_FULLSCREEN);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winAllocateFBShadowDD - Could not set "
+		  "cooperative level: %08x\n",
+		  (unsigned int) ddrval);
+	  return FALSE;
+	}
+
+      /*
+       * We only need to get the current refresh rate for comparison
+       * if a refresh rate has been passed on the command line.
+       */
+      if (pScreenInfo->dwRefreshRate != 0)
+	{
+	  ZeroMemory (&ddsdCurrent, sizeof (ddsdCurrent));
+	  ddsdCurrent.dwSize = sizeof (ddsdCurrent);
+	  
+	  /* Get information about current display settings */
+	  ddrval = IDirectDraw2_GetDisplayMode (pScreenPriv->pdd2,
+						&ddsdCurrent);
+	  if (FAILED (ddrval))
+	    {
+	      ErrorF ("winAllocateFBShadowDD - Could not get current "
+		      "refresh rate: %08x.  Continuing.\n",
+		      (unsigned int) ddrval);
+	      dwRefreshRateCurrent = 0;
+	    }
+	  else
+	    {
+	      /* Grab the current refresh rate */
+	      dwRefreshRateCurrent = ddsdCurrent.u2.dwRefreshRate;
+	    }
+	}
+
+      /* Clean up the refresh rate */
+      if (dwRefreshRateCurrent == pScreenInfo->dwRefreshRate)
+	{
+	  /*
+	   * Refresh rate is non-specified or equal to current.
+	   */
+	  pScreenInfo->dwRefreshRate = 0;
+	}
+
+      /* Grab a device context for the screen */
+      hdc = GetDC (NULL);
+      if (hdc == NULL)
+	{
+	  ErrorF ("winAllocateFBShadowDD - GetDC () failed\n");
+	  return FALSE;
+	}
+
+      /* Only change the video mode when different than current mode */
+      if (!pScreenInfo->fMultipleMonitors
+	  && (pScreenInfo->dwWidth != GetSystemMetrics (SM_CXSCREEN)
+	      || pScreenInfo->dwHeight != GetSystemMetrics (SM_CYSCREEN)
+	      || pScreenInfo->dwBPP != GetDeviceCaps (hdc, BITSPIXEL)
+	      || pScreenInfo->dwRefreshRate != 0))
+	{
+	  ErrorF ("winAllocateFBShadowDD - Changing video mode\n");
+
+	  /* Change the video mode to the mode requested, and use the driver default refresh rate on failure */
+	  ddrval = IDirectDraw2_SetDisplayMode (pScreenPriv->pdd2,
+						pScreenInfo->dwWidth,
+						pScreenInfo->dwHeight,
+						pScreenInfo->dwBPP,
+						pScreenInfo->dwRefreshRate,
+						0);
+	  if (FAILED (ddrval))
+	    {
+	      ErrorF ("winAllocateFBShadowDD - Could not set "\
+		      "full screen display mode: %08x\n",
+		      (unsigned int) ddrval);
+	      ErrorF ("winAllocateFBShadowDD - Using default driver refresh rate\n");
+	      ddrval = IDirectDraw2_SetDisplayMode (pScreenPriv->pdd2,
+						    pScreenInfo->dwWidth,
+						    pScreenInfo->dwHeight,
+						    pScreenInfo->dwBPP,
+						    0,
+						    0);
+	      if (FAILED(ddrval))
+		{
+			ErrorF ("winAllocateFBShadowDD - Could not set default refresh rate "
+				"full screen display mode: %08x\n",
+				(unsigned int) ddrval);
+			return FALSE;
+		}
+	    }
+	}
+      else
+	{
+	  ErrorF ("winAllocateFBShadowDD - Not changing video mode\n");
+	}
+
+      /* Release our DC */
+      ReleaseDC (NULL, hdc);
+      hdc = NULL;
+    }
+  else
+    {
+      /* Set the cooperative level for windowed mode */
+      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_NORMAL);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winAllocateFBShadowDD - Could not set "\
+		  "cooperative level: %08x\n",
+		  (unsigned int) ddrval);
+	  return FALSE;
+	}
+    }
+
+  /* Create the primary surface */
+  if (!winCreatePrimarySurfaceShadowDD (pScreen))
+    {
+      ErrorF ("winAllocateFBShadowDD - winCreatePrimarySurfaceShadowDD "
+	      "failed\n");
+      return FALSE;
+    }
+
+  /* Describe the shadow surface to be created */
+  /* NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
+   * as drawing, locking, and unlocking take forever
+   * with video memory surfaces.  In addition,
+   * video memory is a somewhat scarce resource,
+   * so you shouldn't be allocating video memory when
+   * you have the option of using system memory instead.
+   */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
+  ddsd.dwHeight = pScreenInfo->dwHeight;
+  ddsd.dwWidth = pScreenInfo->dwWidth;
+
+  /* Create the shadow surface */
+  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
+				       &ddsd,
+				       &pScreenPriv->pddsShadow,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not create shadow "\
+	      "surface: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+  
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Created shadow\n");
+#endif
+
+  /* Allocate a DD surface description for our screen privates */
+  pddsdShadow = pScreenPriv->pddsdShadow = malloc (sizeof (DDSURFACEDESC));
+  if (pddsdShadow == NULL)
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not allocate surface "\
+	      "description memory\n");
+      return FALSE;
+    }
+  ZeroMemory (pddsdShadow, sizeof (*pddsdShadow));
+  pddsdShadow->dwSize = sizeof (*pddsdShadow);
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Locking shadow\n");
+#endif
+
+  /* Lock the shadow surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
+				     NULL,
+				     pddsdShadow,
+				     DDLOCK_WAIT,
+				     NULL);
+  if (FAILED (ddrval) || pddsdShadow->lpSurface == NULL)
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not lock shadow "\
+	      "surface: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Locked shadow\n");
+#endif
+
+  /* We don't know how to deal with anything other than RGB */
+  if (!(pddsdShadow->ddpfPixelFormat.dwFlags & DDPF_RGB))
+    {
+      ErrorF ("winAllocateFBShadowDD - Color format other than RGB\n");
+      return FALSE;
+    }
+
+  /* Grab the pitch from the surface desc */
+  pScreenInfo->dwStride = (pddsdShadow->u1.lPitch * 8)
+    / pScreenInfo->dwBPP;
+
+  /* Save the pointer to our surface memory */
+  pScreenInfo->pfb = pddsdShadow->lpSurface;
+  
+  /* Grab the color depth and masks from the surface description */
+  pScreenPriv->dwRedMask = pddsdShadow->ddpfPixelFormat.u2.dwRBitMask;
+  pScreenPriv->dwGreenMask = pddsdShadow->ddpfPixelFormat.u3.dwGBitMask;
+  pScreenPriv->dwBlueMask = pddsdShadow->ddpfPixelFormat.u4.dwBBitMask;
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Transfer the damaged regions of the shadow framebuffer to the display.
+ */
+
+static void
+winShadowUpdateDD (ScreenPtr pScreen, 
+		   shadowBufPtr pBuf)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RegionPtr		damage = shadowDamage(pBuf);
+  HRESULT		ddrval = DD_OK;
+  RECT			rcDest, rcSrc;
+  POINT			ptOrigin;
+  DWORD			dwBox = REGION_NUM_RECTS (damage);
+  BoxPtr		pBox = REGION_RECTS (damage);
+  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
+
+  /*
+   * Return immediately if the app is not active
+   * and we are fullscreen, or if we have a bad display depth
+   */
+  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
+      || pScreenPriv->fBadDepth) return;
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+
+  /* Unlock the shadow surface, so we can blit */
+  ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winShadowUpdateDD - Unlock failed\n");
+      return;
+    }
+
+  /*
+   * Handle small regions with multiple blits,
+   * handle large regions by creating a clipping region and 
+   * doing a single blit constrained to that clipping region.
+   */
+  if (pScreenInfo->dwClipUpdatesNBoxes == 0
+      || dwBox < pScreenInfo->dwClipUpdatesNBoxes)
+    {
+      /* Loop through all boxes in the damaged region */
+      while (dwBox--)
+	{
+	  /* Assign damage box to source rectangle */
+	  rcSrc.left = pBox->x1;
+	  rcSrc.top = pBox->y1;
+	  rcSrc.right = pBox->x2;
+	  rcSrc.bottom = pBox->y2;
+	  
+	  /* Calculate destination rectange */
+	  rcDest.left = ptOrigin.x + rcSrc.left;
+	  rcDest.top = ptOrigin.y + rcSrc.top;
+	  rcDest.right = ptOrigin.x + rcSrc.right;
+	  rcDest.bottom = ptOrigin.y + rcSrc.bottom;
+	  
+	  /* Blit the damaged areas */
+	  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+					    &rcDest,
+					    pScreenPriv->pddsShadow,
+					    &rcSrc,
+					    DDBLT_WAIT,
+					    NULL);
+	  
+	  /* Get a pointer to the next box */
+	  ++pBox;
+	}
+    }
+  else
+    {
+      BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
+
+      /* Compute a GDI region from the damaged region */
+      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+      dwBox--;
+      pBox++;
+      while (dwBox--)
+	{
+	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
+	  DeleteObject (hrgnTemp);
+	  pBox++;
+	}  
+
+      /* Install the GDI region as a clipping region */
+      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
+      DeleteObject (hrgnCombined);
+      hrgnCombined = NULL;
+
+      /* Calculating a bounding box for the source is easy */
+      rcSrc.left = pBoxExtents->x1;
+      rcSrc.top = pBoxExtents->y1;
+      rcSrc.right = pBoxExtents->x2;
+      rcSrc.bottom = pBoxExtents->y2;
+
+      /* Calculating a bounding box for the destination is trickier */
+      rcDest.left = ptOrigin.x + rcSrc.left;
+      rcDest.top = ptOrigin.y + rcSrc.top;
+      rcDest.right = ptOrigin.x + rcSrc.right;
+      rcDest.bottom = ptOrigin.y + rcSrc.bottom;
+      
+      /* Our Blt should be clipped to the invalidated region */
+      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+					&rcDest,
+					pScreenPriv->pddsShadow,
+					&rcSrc,
+					DDBLT_WAIT,
+					NULL);
+
+      /* Reset the clip region */
+      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
+    }
+
+  /* Relock the shadow surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
+				     NULL,
+				     pScreenPriv->pddsdShadow,
+				     DDLOCK_WAIT,
+				     NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winShadowUpdateDD - Lock failed\n");
+      return;
+    }
+
+  /* Has our memory pointer changed? */
+  if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
+    {
+      ErrorF ("winShadowUpdateDD - Memory location of the shadow "
+	      "surface has changed, trying to update the root window "
+	      "pixmap header to point to the new address.  If you get "
+	      "this message and "PROJECT_NAME" freezes or crashes "
+	      "after this message then send a problem report and your "
+	      "%s file to " BUILDERADDR "\n", g_pszLogFile);
+
+      /* Location of shadow framebuffer has changed */
+      pScreenInfo->pfb = pScreenPriv->pddsdShadow->lpSurface;
+      
+      /* Update the screen pixmap */
+      if (!(*pScreen->ModifyPixmapHeader)(pScreen->devPrivate,
+					  pScreen->width,
+					  pScreen->height,
+					  pScreen->rootDepth,
+					  BitsPerPixel (pScreen->rootDepth),
+					  PixmapBytePad (pScreenInfo->dwStride,
+							 pScreenInfo->dwBPP),
+					  pScreenInfo->pfb))
+	{
+	  ErrorF ("winShadowUpdateDD - Bits changed, could not "
+		  "notify fb.\n");
+	  return;
+	}
+    }
+}
+
+
+/*
+ * Call the wrapped CloseScreen function.
+ * 
+ * Free our resources and private structures.
+ */
+
+static Bool
+winCloseScreenShadowDD (int nIndex, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  Bool			fReturn;
+  
+#if CYGDEBUG
+  winDebug ("winCloseScreenShadowDD - Freeing screen resources\n");
+#endif
+
+  /* Flag that the screen is closed */
+  pScreenPriv->fClosed = TRUE;
+  pScreenPriv->fActive = FALSE;
+
+  /* Call the wrapped CloseScreen procedure */
+  WIN_UNWRAP(CloseScreen);
+  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
+
+  /* Free the screen DC */
+  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
+
+  /* Delete the window property */
+  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
+
+  /* Free the shadow surface, if there is one */
+  if (pScreenPriv->pddsShadow)
+    {
+      IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
+      IDirectDrawSurface2_Release (pScreenPriv->pddsShadow);
+      pScreenPriv->pddsShadow = NULL;
+    }
+
+  /* Detach the clipper from the primary surface and release the clipper. */
+  if (pScreenPriv->pddcPrimary)
+    {
+      /* Detach the clipper */
+      IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
+				      NULL);
+
+      /* Release the clipper object */
+      IDirectDrawClipper_Release (pScreenPriv->pddcPrimary);
+      pScreenPriv->pddcPrimary = NULL;
+    }
+
+  /* Release the primary surface, if there is one */
+  if (pScreenPriv->pddsPrimary)
+    {
+      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
+      pScreenPriv->pddsPrimary = NULL;
+    }
+
+  /* Free the DirectDraw2 object, if there is one */
+  if (pScreenPriv->pdd2)
+    {
+      IDirectDraw2_RestoreDisplayMode (pScreenPriv->pdd2);
+      IDirectDraw2_Release (pScreenPriv->pdd2);
+      pScreenPriv->pdd2 = NULL;
+    }
+
+  /* Free the DirectDraw object, if there is one */
+  if (pScreenPriv->pdd)
+    {
+      IDirectDraw_Release (pScreenPriv->pdd);
+      pScreenPriv->pdd = NULL;
+    }
+
+  /* Delete tray icon, if we have one */
+  if (!pScreenInfo->fNoTrayIcon)
+    winDeleteNotifyIcon (pScreenPriv);
+  
+  /* Free the exit confirmation dialog box, if it exists */
+  if (g_hDlgExit != NULL)
+    {
+      DestroyWindow (g_hDlgExit);
+      g_hDlgExit = NULL;
+    }
+
+  /* Kill our window */
+  if (pScreenPriv->hwndScreen)
+    {
+      DestroyWindow (pScreenPriv->hwndScreen);
+      pScreenPriv->hwndScreen = NULL;
+    }
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Destroy the thread startup mutex */
+  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
+#endif
+
+  /* Kill our screeninfo's pointer to the screen */
+  pScreenInfo->pScreen = NULL;
+
+  /* Invalidate the ScreenInfo's fb pointer */
+  pScreenInfo->pfb = NULL;
+
+  /* Free the screen privates for this screen */
+  free ((pointer) pScreenPriv);
+
+  return fReturn;
+}
+
+
+/*
+ * Tell mi what sort of visuals we need.
+ * 
+ * Generally we only need one visual, as our screen can only
+ * handle one format at a time, I believe.  You may want
+ * to verify that last sentence.
+ */
+
+static Bool
+winInitVisualsShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
+
+  /* Count the number of ones in each color mask */
+  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
+  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
+  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
+  
+  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
+  if (dwRedBits == 0 || dwGreenBits == 0 || dwBlueBits == 0)
+    pScreenPriv->dwBitsPerRGB = 8;
+  else if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwRedBits;
+  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwGreenBits;
+  else
+    pScreenPriv->dwBitsPerRGB = dwBlueBits;
+  
+  ErrorF ("winInitVisualsShadowDD - Masks %08x %08x %08x BPRGB %d d %d "
+	  "bpp %d\n",
+	  (unsigned int) pScreenPriv->dwRedMask,
+	  (unsigned int) pScreenPriv->dwGreenMask,
+	  (unsigned int) pScreenPriv->dwBlueMask,
+	  (int) pScreenPriv->dwBitsPerRGB,
+	  (int) pScreenInfo->dwDepth,
+	  (int) pScreenInfo->dwBPP);
+
+  /* Create a single visual according to the Windows screen depth */
+  switch (pScreenInfo->dwDepth)
+    {
+    case 24:
+    case 16:
+    case 15:
+#if defined(XFree86Server)
+      /* Create the real visual */
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     TrueColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!miSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     -1,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#else /* XFree86Server */
+      /* Create the real visual */
+      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!fbSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#endif /* XFree86Server */
+      break;
+
+    case 8:
+#if defined(XFree86Server)
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColorMask : StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColor : StaticColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+#else /* XFree86Server */
+      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColorMask : StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+#endif /* XFree86Server */
+      break;
+
+    default:
+      ErrorF ("winInitVisualsShadowDD - Unknown screen depth\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winInitVisualsShadowDD - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Adjust the user proposed video mode
+ */
+
+static Bool
+winAdjustVideoModeShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HDC			hdc = NULL;
+  DWORD			dwBPP;
+
+  /* We're in serious trouble if we can't get a DC */
+  hdc = GetDC (NULL);
+  if (hdc == NULL)
+    {
+      ErrorF ("winAdjustVideoModeShadowDD - GetDC () failed\n");
+      return FALSE;
+    }
+
+  /* Query GDI for current display depth */
+  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* DirectDraw can only change the depth in fullscreen mode */
+  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
+    {
+      /* No -depth parameter passed, let the user know the depth being used */
+      ErrorF ("winAdjustVideoModeShadowDD - Using Windows display "
+	      "depth of %d bits per pixel\n", (int) dwBPP);
+
+      /* Use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  else if (pScreenInfo->fFullScreen
+	   && pScreenInfo->dwBPP != dwBPP)
+    {
+      /* FullScreen, and GDI depth differs from -depth parameter */
+      ErrorF ("winAdjustVideoModeShadowDD - FullScreen, using command line "
+	      "bpp: %d\n", (int) pScreenInfo->dwBPP);
+    }
+  else if (dwBPP != pScreenInfo->dwBPP)
+    {
+      /* Windowed, and GDI depth differs from -depth parameter */
+      ErrorF ("winAdjustVideoModeShadowDD - Windowed, command line bpp: "
+	      "%d, using bpp: %d\n", (int) pScreenInfo->dwBPP, (int) dwBPP);
+
+      /* We'll use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  
+  /* See if the shadow bitmap will be larger than the DIB size limit */
+  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
+      >= WIN_DIB_MAXIMUM_SIZE)
+    {
+      ErrorF ("winAdjustVideoModeShadowDD - Requested DirectDraw surface "
+	      "will be larger than %d MB.  The surface may fail to be "
+	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
+	      "DIB size.  This limit does not apply to Windows NT/2000, and "
+	      "this message may be ignored on those platforms.\n",
+	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
+    }
+
+  /* Release our DC */
+  ReleaseDC (NULL, hdc);
+  return TRUE;
+}
+
+
+/*
+ * Blt exposed regions to the screen
+ */
+
+static Bool
+winBltExposedRegionsShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RECT			rcSrc, rcDest;
+  POINT			ptOrigin;
+  HDC			hdcUpdate = NULL;
+  PAINTSTRUCT		ps;
+  HRESULT		ddrval = DD_OK;
+  Bool			fReturn = TRUE;
+  Bool			fLocked = TRUE;
+  int			i;
+
+  /* BeginPaint gives us an hdc that clips to the invalidated region */
+  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
+  if (hdcUpdate == NULL)
+    {
+      ErrorF ("winBltExposedRegionsShadowDD - BeginPaint () returned "
+	      "a NULL device context handle.  Aborting blit attempt.\n");
+      return FALSE;
+    }
+  
+  /* Unlock the shadow surface, so we can blit */
+  ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
+  if (FAILED (ddrval))
+    {
+      fReturn = FALSE;
+      goto winBltExposedRegionsShadowDD_Exit;
+    }
+  else
+    {
+      /* Flag that we have unlocked the shadow surface */
+      fLocked = FALSE;
+    }
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+  rcDest.left = ptOrigin.x;
+  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
+  rcDest.top = ptOrigin.y;
+  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
+
+  /* Source can be enter shadow surface, as Blt should clip */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  /* Try to regain the primary surface and blit again if we've lost it */
+  for (i = 0; i <= WIN_REGAIN_SURFACE_RETRIES; ++i)
+    {
+      /* Our Blt should be clipped to the invalidated region */
+      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+					&rcDest,
+					pScreenPriv->pddsShadow,
+					&rcSrc,
+					DDBLT_WAIT,
+					NULL);
+      if (ddrval == DDERR_SURFACELOST)
+	{
+	  /* Surface was lost */
+	  ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Blt "
+		  "reported that the primary surface was lost, "
+		  "trying to restore, retry: %d\n", i + 1);
+
+	  /* Try to restore the surface, once */
+	  ddrval = IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
+	  ErrorF ("winBltExposedRegionsShadowDD - "
+		  "IDirectDrawSurface2_Restore returned: ");
+	  if (ddrval == DD_OK)
+	    ErrorF ("DD_OK\n");
+	  else if (ddrval == DDERR_WRONGMODE)
+	    ErrorF ("DDERR_WRONGMODE\n");
+	  else if (ddrval == DDERR_INCOMPATIBLEPRIMARY)
+	    ErrorF ("DDERR_INCOMPATIBLEPRIMARY\n");
+	  else if (ddrval == DDERR_UNSUPPORTED)
+	    ErrorF ("DDERR_UNSUPPORTED\n");
+	  else if (ddrval == DDERR_INVALIDPARAMS)
+	    ErrorF ("DDERR_INVALIDPARAMS\n");
+	  else if (ddrval == DDERR_INVALIDOBJECT)
+	    ErrorF ("DDERR_INVALIDOBJECT\n");
+	  else
+	    ErrorF ("unknown error: %08x\n", (unsigned int) ddrval);
+
+	  /* Loop around to try the blit one more time */
+	  continue;
+	}
+      else if (FAILED (ddrval))
+	{
+	  fReturn = FALSE;
+	  ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Blt "
+		  "failed, but surface not lost: %08x %d\n",
+		  (unsigned int) ddrval, (int) ddrval);
+	  goto winBltExposedRegionsShadowDD_Exit;
+	}
+      else
+	{
+	  /* Success, stop looping */
+	  break;
+	}
+    }
+
+  /* Relock the shadow surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
+				     NULL,
+				     pScreenPriv->pddsdShadow,
+				     DDLOCK_WAIT,
+				     NULL);
+  if (FAILED (ddrval))
+    {
+      fReturn = FALSE;
+      ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Lock "
+	      "failed\n");
+      goto winBltExposedRegionsShadowDD_Exit;
+    }
+  else
+    {
+      /* Indicate that we have relocked the shadow surface */
+      fLocked = TRUE;
+    }
+
+  /* Has our memory pointer changed? */
+  if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
+    winUpdateFBPointer (pScreen,
+			pScreenPriv->pddsdShadow->lpSurface);
+
+ winBltExposedRegionsShadowDD_Exit:
+  /* EndPaint frees the DC */
+  if (hdcUpdate != NULL)
+    EndPaint (pScreenPriv->hwndScreen, &ps);
+
+  /*
+   * Relock the surface if it is not locked.  We don't care if locking fails,
+   * as it will cause the server to shutdown within a few more operations.
+   */
+  if (!fLocked)
+    {
+      IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
+				NULL,
+				pScreenPriv->pddsdShadow,
+				DDLOCK_WAIT,
+				NULL);
+
+      /* Has our memory pointer changed? */
+      if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
+	winUpdateFBPointer (pScreen,
+			    pScreenPriv->pddsdShadow->lpSurface);
+      
+      fLocked = TRUE;
+    }
+  return fReturn;
+}
+
+
+/*
+ * Do any engine-specific appliation-activation processing
+ */
+
+static Bool
+winActivateAppShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+
+  /*
+   * Do we have a surface?
+   * Are we active?
+   * Are we fullscreen?
+   */
+  if (pScreenPriv != NULL
+      && pScreenPriv->pddsPrimary != NULL
+      && pScreenPriv->fActive)
+    {
+      /* Primary surface was lost, restore it */
+      IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Reblit the shadow framebuffer to the screen.
+ */
+
+static Bool
+winRedrawScreenShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HRESULT		ddrval = DD_OK;
+  RECT			rcSrc, rcDest;
+  POINT			ptOrigin;
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+  rcDest.left = ptOrigin.x;
+  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
+  rcDest.top = ptOrigin.y;
+  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
+
+  /* Source can be entire shadow surface, as Blt should clip for us */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  /* Redraw the whole window, to take account for the new colors */
+  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+				    &rcDest,
+				    pScreenPriv->pddsShadow,
+				    &rcSrc,
+				    DDBLT_WAIT,
+				    NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winRedrawScreenShadowDD - IDirectDrawSurface_Blt () "
+	      "failed: %08x\n",
+	      (unsigned int) ddrval);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Realize the currently installed colormap
+ */
+
+static Bool
+winRealizeInstalledPaletteShadowDD (ScreenPtr pScreen)
+{
+  return TRUE;
+}
+
+
+/*
+ * Install the specified colormap
+ */
+
+static Bool
+winInstallColormapShadowDD (ColormapPtr pColormap)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  HRESULT		ddrval = DD_OK;
+
+  /* Install the DirectDraw palette on the primary surface */
+  ddrval = IDirectDrawSurface2_SetPalette (pScreenPriv->pddsPrimary,
+					   pCmapPriv->lpDDPalette);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winInstallColormapShadowDD - Failed installing the "
+	      "DirectDraw palette.\n");
+      return FALSE;
+    }
+
+  /* Save a pointer to the newly installed colormap */
+  pScreenPriv->pcmapInstalled = pColormap;
+
+  return TRUE;
+}
+
+
+/*
+ * Store the specified colors in the specified colormap
+ */
+
+static Bool
+winStoreColorsShadowDD (ColormapPtr pColormap, 
+			int ndef,
+			xColorItem *pdefs)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  ColormapPtr		curpmap = pScreenPriv->pcmapInstalled;
+  HRESULT		ddrval = DD_OK;
+  
+  /* Put the X colormap entries into the Windows logical palette */
+  ddrval = IDirectDrawPalette_SetEntries (pCmapPriv->lpDDPalette,
+					  0,
+					  pdefs[0].pixel,
+					  ndef,
+					  pCmapPriv->peColors 
+					  + pdefs[0].pixel);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winStoreColorsShadowDD - SetEntries () failed\n");
+      return FALSE;
+    }
+
+  /* Don't install the DirectDraw palette if the colormap is not installed */
+  if (pColormap != curpmap)
+    {
+      return TRUE;
+    }
+
+  if (!winInstallColormapShadowDD (pColormap))
+    {
+      ErrorF ("winStoreColorsShadowDD - Failed installing colormap\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap initialization procedure
+ */
+
+static Bool
+winCreateColormapShadowDD (ColormapPtr pColormap)
+{
+  HRESULT		ddrval = DD_OK;
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  
+  /* Create a DirectDraw palette */
+  ddrval = IDirectDraw2_CreatePalette (pScreenPriv->pdd,
+				       DDPCAPS_8BIT | DDPCAPS_ALLOW256,
+				       pCmapPriv->peColors,
+				       &pCmapPriv->lpDDPalette,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreateColormapShadowDD - CreatePalette failed\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap destruction procedure
+ */
+
+static Bool
+winDestroyColormapShadowDD (ColormapPtr pColormap)
+{
+  winScreenPriv(pColormap->pScreen);
+  winCmapPriv(pColormap);
+  HRESULT		ddrval = DD_OK;
+
+  /*
+   * Is colormap to be destroyed the default?
+   *
+   * Non-default colormaps should have had winUninstallColormap
+   * called on them before we get here.  The default colormap
+   * will not have had winUninstallColormap called on it.  Thus,
+   * we need to handle the default colormap in a special way.
+   */
+  if (pColormap->flags & IsDefault)
+    {
+#if CYGDEBUG
+      winDebug ("winDestroyColormapShadowDD - Destroying default "
+	      "colormap\n");
+#endif
+      
+      /*
+       * FIXME: Walk the list of all screens, popping the default
+       * palette out of each screen device context.
+       */
+      
+      /* Pop the palette out of the primary surface */
+      ddrval = IDirectDrawSurface2_SetPalette (pScreenPriv->pddsPrimary,
+					       NULL);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winDestroyColormapShadowDD - Failed freeing the "
+		  "default colormap DirectDraw palette.\n");
+	  return FALSE;
+	}
+
+      /* Clear our private installed colormap pointer */
+      pScreenPriv->pcmapInstalled = NULL;
+    }
+  
+  /* Release the palette */
+  IDirectDrawPalette_Release (pCmapPriv->lpDDPalette);
+ 
+  /* Invalidate the colormap privates */
+  pCmapPriv->lpDDPalette = NULL;
+
+  return TRUE;
+}
+
+
+/*
+ * Set engine specific functions
+ */
+
+Bool
+winSetEngineFunctionsShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  
+  /* Set our pointers */
+  pScreenPriv->pwinAllocateFB = winAllocateFBShadowDD;
+  pScreenPriv->pwinShadowUpdate = winShadowUpdateDD;
+  pScreenPriv->pwinCloseScreen = winCloseScreenShadowDD;
+  pScreenPriv->pwinInitVisuals = winInitVisualsShadowDD;
+  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowDD;
+  if (pScreenInfo->fFullScreen)
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
+  else
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
+  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
+  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowDD;
+  pScreenPriv->pwinActivateApp = winActivateAppShadowDD;
+  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowDD;
+  pScreenPriv->pwinRealizeInstalledPalette
+    = winRealizeInstalledPaletteShadowDD;
+  pScreenPriv->pwinInstallColormap = winInstallColormapShadowDD;
+  pScreenPriv->pwinStoreColors = winStoreColorsShadowDD;
+  pScreenPriv->pwinCreateColormap = winCreateColormapShadowDD;
+  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowDD;
+  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
+  pScreenPriv->pwinCreatePrimarySurface = winCreatePrimarySurfaceShadowDD;
+  pScreenPriv->pwinReleasePrimarySurface = winReleasePrimarySurfaceShadowDD;
+#ifdef XWIN_MULTIWINDOW
+  pScreenPriv->pwinFinishCreateWindowsWindow =
+    (winFinishCreateWindowsWindowProcPtr) (void (*)(void))NoopDDA;
+#endif
+
+  return TRUE;
+}
diff --git a/xorg-server/hw/xwin/winshadddnl.c b/xorg-server/hw/xwin/winshadddnl.c
index ef5c21469..3a6ea9d2c 100644
--- a/xorg-server/hw/xwin/winshadddnl.c
+++ b/xorg-server/hw/xwin/winshadddnl.c
@@ -1,1467 +1,1467 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * External symbols
- */
-
-extern HWND			g_hDlgExit;
-
-
-/*
- * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly,
- * so we have to redefine it here.
- */
-#ifdef DEFINE_GUID
-#undef DEFINE_GUID
-#define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
-#endif /* DEFINE_GUID */
-
-/*
- * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined
- * here manually.  Should be handled by ddraw.h
- */
-#ifndef IID_IDirectDraw4
-DEFINE_GUID( IID_IDirectDraw4, 0x9c59509a,0x39bd,0x11d1,0x8c,0x4a,0x00,0xc0,0x4f,0xd9,0x30,0xc5 );
-#endif /* IID_IDirectDraw4 */
-
-#define FAIL_MSG_MAX_BLT	10
-
-
-/*
- * Local prototypes
- */
-
-static Bool
-winAllocateFBShadowDDNL (ScreenPtr pScreen);
-
-static void
-winShadowUpdateDDNL (ScreenPtr pScreen, 
-		     shadowBufPtr pBuf);
-
-static Bool
-winCloseScreenShadowDDNL (int nIndex, ScreenPtr pScreen);
-
-static Bool
-winInitVisualsShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winAdjustVideoModeShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winBltExposedRegionsShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winActivateAppShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winRedrawScreenShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winRealizeInstalledPaletteShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winInstallColormapShadowDDNL (ColormapPtr pColormap);
-
-static Bool
-winStoreColorsShadowDDNL (ColormapPtr pmap, 
-			  int ndef,
-			  xColorItem *pdefs);
-
-static Bool
-winCreateColormapShadowDDNL (ColormapPtr pColormap);
-
-static Bool
-winDestroyColormapShadowDDNL (ColormapPtr pColormap);
-
-static Bool
-winCreatePrimarySurfaceShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winReleasePrimarySurfaceShadowDDNL (ScreenPtr pScreen);
-
-
-/*
- * Create the primary surface and attach the clipper.
- * Used for both the initial surface creation and during
- * WM_DISPLAYCHANGE messages.
- */
-
-static Bool
-winCreatePrimarySurfaceShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC2	ddsd;
-
-  winDebug ("winCreatePrimarySurfaceShadowDDNL - Creating primary surface\n");
-
-  /* Describe the primary surface */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-  
-  /* Create the primary surface */
-  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
-				       &ddsd,
-				       &pScreenPriv->pddsPrimary4,
-				       NULL);
-  pScreenPriv->fRetryCreateSurface = FALSE;
-  if (FAILED (ddrval))
-    {
-      if (ddrval == DDERR_NOEXCLUSIVEMODE)
-        {
-          /* Recreating the surface failed. Mark screen to retry later */ 
-          pScreenPriv->fRetryCreateSurface = TRUE;
-          winDebug ("winCreatePrimarySurfaceShadowDDNL - Could not create "
-	          "primary surface: DDERR_NOEXCLUSIVEMODE\n");
-        }
-      else
-        {
-          ErrorF ("winCreatePrimarySurfaceShadowDDNL - Could not create "
-	          "primary surface: %08x\n", (unsigned int) ddrval);
-        }
-      return FALSE;
-    }
-  
-#if 1
-  winDebug ("winCreatePrimarySurfaceShadowDDNL - Created primary surface\n");
-#endif
-
-  /* Attach our clipper to our primary surface handle */
-  ddrval = IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
-					   pScreenPriv->pddcPrimary);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreatePrimarySurfaceShadowDDNL - Primary attach clipper "
-	      "failed: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if 1
-  winDebug ("winCreatePrimarySurfaceShadowDDNL - Attached clipper to primary "
-	  "surface\n");
-#endif
-
-  /* Everything was correct */
-  return TRUE;
-}
-
-
-/*
- * Detach the clipper and release the primary surface.
- * Called from WM_DISPLAYCHANGE.
- */
-
-static Bool
-winReleasePrimarySurfaceShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-
-  winDebug ("winReleasePrimarySurfaceShadowDDNL - Hello\n");
-
-  /* Release the primary surface and clipper, if they exist */
-  if (pScreenPriv->pddsPrimary4)
-    {
-      /*
-       * Detach the clipper from the primary surface.
-       * NOTE: We do this explicity for clarity.  The Clipper is not released.
-       */
-      IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
-				      NULL);
-  
-      winDebug ("winReleasePrimarySurfaceShadowDDNL - Detached clipper\n");
-
-      /* Release the primary surface */
-      IDirectDrawSurface4_Release (pScreenPriv->pddsPrimary4);
-      pScreenPriv->pddsPrimary4 = NULL;
-    }
-
-  winDebug ("winReleasePrimarySurfaceShadowDDNL - Released primary surface\n");
-  
-  return TRUE;
-}
-
-
-/*
- * Create a DirectDraw surface for the shadow framebuffer; also create
- * a primary surface object so we can blit to the display.
- * 
- * Install a DirectDraw clipper on our primary surface object
- * that clips our blits to the unobscured client area of our display window.
- */
-
-Bool
-winAllocateFBShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC2	ddsdShadow;
-  char			*lpSurface = NULL;
-  DDPIXELFORMAT		ddpfPrimary;
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - w %d h %d d %d\n",
-	  pScreenInfo->dwWidth, pScreenInfo->dwHeight, pScreenInfo->dwDepth);
-#endif
-
-  /* Allocate memory for our shadow surface */
-  lpSurface = malloc (pScreenInfo->dwPaddedWidth * pScreenInfo->dwHeight);
-  if (lpSurface == NULL)
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not allocate bits\n");
-      return FALSE;
-    }
-
-  /*
-   * Initialize the framebuffer memory so we don't get a 
-   * strange display at startup
-   */
-  ZeroMemory (lpSurface, pScreenInfo->dwPaddedWidth * pScreenInfo->dwHeight);
-  
-  /* Create a clipper */
-  ddrval = (*g_fpDirectDrawCreateClipper) (0,
-					   &pScreenPriv->pddcPrimary,
-					   NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not attach clipper: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Created a clipper\n");
-#endif
-
-  /* Get a device context for the screen  */
-  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
-
-  /* Attach the clipper to our display window */
-  ddrval = IDirectDrawClipper_SetHWnd (pScreenPriv->pddcPrimary,
-				       0,
-				       pScreenPriv->hwndScreen);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Clipper not attached "
-	      "to window: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Attached clipper to window\n");
-#endif
-
-  /* Create a DirectDraw object, store the address at lpdd */
-  ddrval = (*g_fpDirectDrawCreate) (NULL,
-				    (LPDIRECTDRAW*) &pScreenPriv->pdd,
-				    NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not start "
-	      "DirectDraw: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Created and initialized DD\n");
-#endif
-
-  /* Get a DirectDraw4 interface pointer */
-  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
-				       &IID_IDirectDraw4,
-				       (LPVOID*) &pScreenPriv->pdd4);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Failed DD4 query: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-  /* Are we full screen? */
-  if (pScreenInfo->fFullScreen)
-    {
-      DDSURFACEDESC2	ddsdCurrent;
-      DWORD		dwRefreshRateCurrent = 0;
-      HDC		hdc = NULL;
-
-      /* Set the cooperative level to full screen */
-      ddrval = IDirectDraw4_SetCooperativeLevel (pScreenPriv->pdd4,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_EXCLUSIVE
-						 | DDSCL_FULLSCREEN);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winAllocateFBShadowDDNL - Could not set "
-		  "cooperative level: %08x\n",
-		  (unsigned int) ddrval);
-	  return FALSE;
-	}
-
-      /*
-       * We only need to get the current refresh rate for comparison
-       * if a refresh rate has been passed on the command line.
-       */
-      if (pScreenInfo->dwRefreshRate != 0)
-	{
-	  ZeroMemory (&ddsdCurrent, sizeof (ddsdCurrent));
-	  ddsdCurrent.dwSize = sizeof (ddsdCurrent);
-
-	  /* Get information about current display settings */
-	  ddrval = IDirectDraw4_GetDisplayMode (pScreenPriv->pdd4,
-						&ddsdCurrent);
-	  if (FAILED (ddrval))
-	    {
-	      ErrorF ("winAllocateFBShadowDDNL - Could not get current "
-		      "refresh rate: %08x.  Continuing.\n",
-		      (unsigned int) ddrval);
-	      dwRefreshRateCurrent = 0;
-	    }
-	  else
-	    {
-	      /* Grab the current refresh rate */
-	      dwRefreshRateCurrent = ddsdCurrent.u2.dwRefreshRate;
-	    }
-	}
-
-      /* Clean up the refresh rate */
-      if (dwRefreshRateCurrent == pScreenInfo->dwRefreshRate)
-	{
-	  /*
-	   * Refresh rate is non-specified or equal to current.
-	   */
-	  pScreenInfo->dwRefreshRate = 0;
-	}
-
-      /* Grab a device context for the screen */
-      hdc = GetDC (NULL);
-      if (hdc == NULL)
-	{
-	  ErrorF ("winAllocateFBShadowDDNL - GetDC () failed\n");
-	  return FALSE;
-	}
-
-      /* Only change the video mode when different than current mode */
-      if (!pScreenInfo->fMultipleMonitors
-	  && (pScreenInfo->dwWidth != GetSystemMetrics (SM_CXSCREEN)
-	      || pScreenInfo->dwHeight != GetSystemMetrics (SM_CYSCREEN)
-	      || pScreenInfo->dwBPP != GetDeviceCaps (hdc, BITSPIXEL)
-	      || pScreenInfo->dwRefreshRate != 0))
-	{
-	  winDebug ("winAllocateFBShadowDDNL - Changing video mode\n");
-
-	  /* Change the video mode to the mode requested, and use the driver default refresh rate on failure */
-	  ddrval = IDirectDraw4_SetDisplayMode (pScreenPriv->pdd4,
-						pScreenInfo->dwWidth,
-						pScreenInfo->dwHeight,
-						pScreenInfo->dwBPP,
-						pScreenInfo->dwRefreshRate,
-						0);	       
-	  if (FAILED (ddrval))
-	    {
-	      ErrorF ("winAllocateFBShadowDDNL - Could not set "
-		      "full screen display mode: %08x\n",
-		      (unsigned int) ddrval);
-	      ErrorF ("winAllocateFBShadowDDNL - Using default driver refresh rate\n");
-	      ddrval = IDirectDraw4_SetDisplayMode (pScreenPriv->pdd4,
-						    pScreenInfo->dwWidth,
-						    pScreenInfo->dwHeight,
-						    pScreenInfo->dwBPP,
-						    0,
-						    0);
-	      if (FAILED(ddrval))
-		{
-			ErrorF ("winAllocateFBShadowDDNL - Could not set default refresh rate "
-				"full screen display mode: %08x\n",
-				(unsigned int) ddrval);
-			return FALSE;
-		}
-	    }
-	}
-      else
-	{
-	  winDebug ("winAllocateFBShadowDDNL - Not changing video mode\n");
-	}
-
-      /* Release our DC */
-      ReleaseDC (NULL, hdc);
-      hdc = NULL;
-    }
-  else
-    {
-      /* Set the cooperative level for windowed mode */
-      ddrval = IDirectDraw4_SetCooperativeLevel (pScreenPriv->pdd4,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_NORMAL);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winAllocateFBShadowDDNL - Could not set "
-		  "cooperative level: %08x\n",
-		  (unsigned int) ddrval);
-	  return FALSE;
-	}
-    }
-
-  /* Create the primary surface */
-  if (!winCreatePrimarySurfaceShadowDDNL (pScreen))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - winCreatePrimarySurfaceShadowDDNL "
-	      "failed\n");
-      return FALSE;
-    }
-
-  /* Get primary surface's pixel format */
-  ZeroMemory (&ddpfPrimary, sizeof (ddpfPrimary));
-  ddpfPrimary.dwSize = sizeof (ddpfPrimary);
-  ddrval = IDirectDrawSurface4_GetPixelFormat (pScreenPriv->pddsPrimary4,
-					       &ddpfPrimary);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not get primary "
-	      "pixformat: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Primary masks: %08x %08x %08x "
-	  "dwRGBBitCount: %d\n",
-	  ddpfPrimary.u2.dwRBitMask,
-	  ddpfPrimary.u3.dwGBitMask,
-	  ddpfPrimary.u4.dwBBitMask,
-	  ddpfPrimary.u1.dwRGBBitCount);
-#endif
-
-  /* Describe the shadow surface to be created */
-  /*
-   * NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
-   * as drawing, locking, and unlocking take forever
-   * with video memory surfaces.  In addition,
-   * video memory is a somewhat scarce resource,
-   * so you shouldn't be allocating video memory when
-   * you have the option of using system memory instead.
-   */
-  ZeroMemory (&ddsdShadow, sizeof (ddsdShadow));
-  ddsdShadow.dwSize = sizeof (ddsdShadow);
-  ddsdShadow.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH
-    | DDSD_LPSURFACE | DDSD_PITCH | DDSD_PIXELFORMAT;
-  ddsdShadow.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
-  ddsdShadow.dwHeight = pScreenInfo->dwHeight;
-  ddsdShadow.dwWidth = pScreenInfo->dwWidth;
-  ddsdShadow.u1.lPitch = pScreenInfo->dwPaddedWidth;
-  ddsdShadow.lpSurface = lpSurface;
-  ddsdShadow.u4.ddpfPixelFormat = ddpfPrimary;
-  
-  winDebug ("winAllocateFBShadowDDNL - lPitch: %d\n",
-	  (int) pScreenInfo->dwPaddedWidth);
-
-  /* Create the shadow surface */
-  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
-				       &ddsdShadow,
-				       &pScreenPriv->pddsShadow4,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not create shadow "
-	      "surface: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-  
-#if CYGDEBUG || YES
-  winDebug ("winAllocateFBShadowDDNL - Created shadow pitch: %d\n",
-	  (int) ddsdShadow.u1.lPitch);
-#endif
-
-  /* Grab the pitch from the surface desc */
-  pScreenInfo->dwStride = (ddsdShadow.u1.lPitch * 8)
-    / pScreenInfo->dwBPP;
-
-#if CYGDEBUG || YES
-  winDebug ("winAllocateFBShadowDDNL - Created shadow stride: %d\n",
-	  (int) pScreenInfo->dwStride);
-#endif
-
-  /* Save the pointer to our surface memory */
-  pScreenInfo->pfb = lpSurface;
-  
-  /* Grab the masks from the surface description */
-  pScreenPriv->dwRedMask = ddsdShadow.u4.ddpfPixelFormat.u2.dwRBitMask;
-  pScreenPriv->dwGreenMask = ddsdShadow.u4.ddpfPixelFormat.u3.dwGBitMask;
-  pScreenPriv->dwBlueMask = ddsdShadow.u4.ddpfPixelFormat.u4.dwBBitMask;
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-/*
- * Create a DirectDraw surface for the new multi-window window
- */
-
-static
-Bool
-winFinishCreateWindowsWindowDDNL (WindowPtr pWin)
-{
-  winWindowPriv(pWin);
-  winPrivScreenPtr	pScreenPriv = pWinPriv->pScreenPriv;
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC2	ddsd;
-  int			iWidth, iHeight;
-  int			iX, iY;
-
-  winDebug ("\nwinFinishCreateWindowsWindowDDNL!\n\n");
-
-  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
-  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
-  
-  iWidth = pWin->drawable.width;
-  iHeight = pWin->drawable.height;
-
-  /* Describe the primary surface */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-  ddsd.dwHeight = iHeight;
-  ddsd.dwWidth = iWidth;
-
-  /* Create the primary surface */
-  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
-				       &ddsd,
-				       &pWinPriv->pddsPrimary4,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winFinishCreateWindowsWindowDDNL - Could not create primary "
-	      "surface: %08x\n",
-	      (unsigned int)ddrval);
-      return FALSE;
-    }
-  return TRUE;
-}
-#endif
-
-
-/*
- * Transfer the damaged regions of the shadow framebuffer to the display.
- */
-
-static void
-winShadowUpdateDDNL (ScreenPtr pScreen, 
-		     shadowBufPtr pBuf)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RegionPtr		damage = shadowDamage(pBuf);
-  HRESULT		ddrval = DD_OK;
-  RECT			rcDest, rcSrc;
-  POINT			ptOrigin;
-  DWORD			dwBox = REGION_NUM_RECTS (damage);
-  BoxPtr		pBox = REGION_RECTS (damage);
-  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
-
-  /*
-   * Return immediately if the app is not active
-   * and we are fullscreen, or if we have a bad display depth
-   */
-  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
-      || pScreenPriv->fBadDepth) return;
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-
-  /*
-   * Handle small regions with multiple blits,
-   * handle large regions by creating a clipping region and 
-   * doing a single blit constrained to that clipping region.
-   */
-  if (pScreenInfo->dwClipUpdatesNBoxes == 0
-      || dwBox < pScreenInfo->dwClipUpdatesNBoxes)
-    {
-      /* Loop through all boxes in the damaged region */
-      while (dwBox--)
-	{
-	  /* Assign damage box to source rectangle */
-	  rcSrc.left = pBox->x1;
-	  rcSrc.top = pBox->y1;
-	  rcSrc.right = pBox->x2;
-	  rcSrc.bottom = pBox->y2;
-	  -	  /* Calculate destination rectangle */
-	  rcDest.left = ptOrigin.x + rcSrc.left;
-	  rcDest.top = ptOrigin.y + rcSrc.top;
-	  rcDest.right = ptOrigin.x + rcSrc.right;
-	  rcDest.bottom = ptOrigin.y + rcSrc.bottom;
-	  
-	  /* Blit the damaged areas */
-	  ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
-					    &rcDest,
-					    pScreenPriv->pddsShadow4,
-					    &rcSrc,
-					    DDBLT_WAIT,
-					    NULL);
-	  if (FAILED (ddrval))
-	    {
-	      static int	s_iFailCount = 0;
-	      
-	      if (s_iFailCount < FAIL_MSG_MAX_BLT)
-		{
-		  ErrorF ("winShadowUpdateDDNL - IDirectDrawSurface4_Blt () "
-			  "failed: %08x\n",
-			  (unsigned int) ddrval);
-		  
-		  ++s_iFailCount;
-
-		  if (s_iFailCount == FAIL_MSG_MAX_BLT)
-		    {
-		      ErrorF ("winShadowUpdateDDNL - IDirectDrawSurface4_Blt "
-			      "failure message maximum (%d) reached.  No "
-			      "more failure messages will be printed.\n",
-			      FAIL_MSG_MAX_BLT);
-		    }
-		}
-	    }
-	  
-	  /* Get a pointer to the next box */
-	  ++pBox;
-	}
-    }
-  else
-    {
-      BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
-
-      /* Compute a GDI region from the damaged region */
-      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-      dwBox--;
-      pBox++;
-      while (dwBox--)
-	{
-	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
-	  DeleteObject (hrgnTemp);
-	  pBox++;
-	}
-
-      /* Install the GDI region as a clipping region */
-      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
-      DeleteObject (hrgnCombined);
-      hrgnCombined = NULL;
-
-#if CYGDEBUG
-      winDebug ("winShadowUpdateDDNL - be x1 %d y1 %d x2 %d y2 %d\n",
-	      pBoxExtents->x1, pBoxExtents->y1,
-	      pBoxExtents->x2, pBoxExtents->y2);
-#endif
-
-      /* Calculating a bounding box for the source is easy */
-      rcSrc.left = pBoxExtents->x1;
-      rcSrc.top = pBoxExtents->y1;
-      rcSrc.right = pBoxExtents->x2;
-      rcSrc.bottom = pBoxExtents->y2;
-
-      /* Calculating a bounding box for the destination is trickier */
-      rcDest.left = ptOrigin.x + rcSrc.left;
-      rcDest.top = ptOrigin.y + rcSrc.top;
-      rcDest.right = ptOrigin.x + rcSrc.right;
-      rcDest.bottom = ptOrigin.y + rcSrc.bottom;
-
-      /* Our Blt should be clipped to the invalidated region */
-      ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
-					&rcDest,
-					pScreenPriv->pddsShadow4,
-					&rcSrc,
-					DDBLT_WAIT,
-					NULL);
-
-      /* Reset the clip region */
-      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
-    }
-}
-
-
-/*
- * Call the wrapped CloseScreen function.
- *
- * Free our resources and private structures.
- */
-
-static Bool
-winCloseScreenShadowDDNL (int nIndex, ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  Bool			fReturn;
-
-#if CYGDEBUG
-  winDebug ("winCloseScreenShadowDDNL - Freeing screen resources\n");
-#endif
-
-  /* Flag that the screen is closed */
-  pScreenPriv->fClosed = TRUE;
-  pScreenPriv->fActive = FALSE;
-
-  /* Call the wrapped CloseScreen procedure */
-  WIN_UNWRAP(CloseScreen);
-  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
-
-  /* Free the screen DC */
-  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
-
-  /* Delete the window property */
-  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
-
-  /* Free the shadow surface, if there is one */
-  if (pScreenPriv->pddsShadow4)
-    {
-      IDirectDrawSurface4_Release (pScreenPriv->pddsShadow4);
-      free (pScreenInfo->pfb);
-      pScreenInfo->pfb = NULL;
-      pScreenPriv->pddsShadow4 = NULL;
-    }
-
-  /* Detach the clipper from the primary surface and release the clipper. */
-  if (pScreenPriv->pddcPrimary)
-    {
-      /* Detach the clipper */
-      IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
-				      NULL);
-
-      /* Release the clipper object */
-      IDirectDrawClipper_Release (pScreenPriv->pddcPrimary);
-      pScreenPriv->pddcPrimary = NULL;
-    }
-
-  /* Release the primary surface, if there is one */
-  if (pScreenPriv->pddsPrimary4)
-    {
-      IDirectDrawSurface4_Release (pScreenPriv->pddsPrimary4);
-      pScreenPriv->pddsPrimary4 = NULL;
-    }
-
-  /* Free the DirectDraw4 object, if there is one */
-  if (pScreenPriv->pdd4)
-    {
-      IDirectDraw4_RestoreDisplayMode (pScreenPriv->pdd4);
-      IDirectDraw4_Release (pScreenPriv->pdd4);
-      pScreenPriv->pdd4 = NULL;
-    }
-
-  /* Free the DirectDraw object, if there is one */
-  if (pScreenPriv->pdd)
-    {
-      IDirectDraw_Release (pScreenPriv->pdd);
-      pScreenPriv->pdd = NULL;
-    }
-
-  /* Delete tray icon, if we have one */
-  if (!pScreenInfo->fNoTrayIcon)
-    winDeleteNotifyIcon (pScreenPriv);
-
-  /* Free the exit confirmation dialog box, if it exists */
-  if (g_hDlgExit != NULL)
-    {
-      DestroyWindow (g_hDlgExit);
-      g_hDlgExit = NULL;
-    }
-
-  /* Kill our window */
-  if (pScreenPriv->hwndScreen)
-    {
-      DestroyWindow (pScreenPriv->hwndScreen);
-      pScreenPriv->hwndScreen = NULL;
-    }
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Destroy the thread startup mutex */
-  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
-#endif
-
-  /* Kill our screeninfo's pointer to the screen */
-  pScreenInfo->pScreen = NULL;
-
-  /* Invalidate the ScreenInfo's fb pointer */
-  pScreenInfo->pfb = NULL;
-
-  /* Free the screen privates for this screen */
-  free ((pointer) pScreenPriv);
-
-  return fReturn;
-}
-
-
-/*
- * Tell mi what sort of visuals we need.
- *
- * Generally we only need one visual, as our screen can only
- * handle one format at a time, I believe.  You may want
- * to verify that last sentence.
- */
-
-static Bool
-winInitVisualsShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
-
-  /* Count the number of ones in each color mask */
-  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
-  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
-  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
-  
-  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
-  if (dwRedBits == 0 || dwGreenBits == 0 || dwBlueBits == 0)
-    pScreenPriv->dwBitsPerRGB = 8;
-  else if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwRedBits;
-  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwGreenBits;
-  else
-    pScreenPriv->dwBitsPerRGB = dwBlueBits;
-
-  winDebug ("winInitVisualsShadowDDNL - Masks %08x %08x %08x BPRGB %d d %d "
-	  "bpp %d\n",
-	  (unsigned int) pScreenPriv->dwRedMask,
-	  (unsigned int) pScreenPriv->dwGreenMask,
-	  (unsigned int) pScreenPriv->dwBlueMask,
-	  (int) pScreenPriv->dwBitsPerRGB,
-	  (int) pScreenInfo->dwDepth,
-	  (int) pScreenInfo->dwBPP);
-
-  /* Create a single visual according to the Windows screen depth */
-  switch (pScreenInfo->dwDepth)
-    {
-    case 24:
-    case 16:
-    case 15:
-#if defined(XFree86Server)
-      /* Setup the real visual */
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     -1,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!miSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     -1,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#else /* XFree86Server */
-      /* Setup the real visual */
-      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!fbSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#endif /* XFree86Server */
-      break;
-
-    case 8:
-#if defined(XFree86Server)
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColorMask : StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColor : StaticColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-#else /* XFree86Server */
-        if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColorMask : StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}    
-#endif /* XFree86Server */
-      break;
-
-    default:
-      ErrorF ("winInitVisualsShadowDDNL - Unknown screen depth\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winInitVisualsShadowDDNL - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Adjust the user proposed video mode
- */
-
-static Bool
-winAdjustVideoModeShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HDC			hdc = NULL;
-  DWORD			dwBPP;
-
-  /* We're in serious trouble if we can't get a DC */
-  hdc = GetDC (NULL);
-  if (hdc == NULL)
-    {
-      ErrorF ("winAdjustVideoModeShadowDDNL - GetDC () failed\n");
-      return FALSE;
-    }
-
-  /* Query GDI for current display depth */
-  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* DirectDraw can only change the depth in fullscreen mode */
-  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
-    {
-      /* No -depth parameter passed, let the user know the depth being used */
-      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - Using Windows display "
-	      "depth of %d bits per pixel\n", (int) dwBPP);
-
-      /* Use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  else if (pScreenInfo->fFullScreen
-	   && pScreenInfo->dwBPP != dwBPP)
-    {
-      /* FullScreen, and GDI depth differs from -depth parameter */
-      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - FullScreen, using command "
-	      "line bpp: %d\n", (int) pScreenInfo->dwBPP);
-    }
-  else if (dwBPP != pScreenInfo->dwBPP)
-    {
-      /* Windowed, and GDI depth differs from -depth parameter */
-      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - Windowed, command line "
-	      "bpp: %d, using bpp: %d\n",
-	      (int) pScreenInfo->dwBPP, (int) dwBPP);
-
-      /* We'll use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-
-  /* See if the shadow bitmap will be larger than the DIB size limit */
-  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
-      >= WIN_DIB_MAXIMUM_SIZE)
-    {
-      winErrorFVerb (1, "winAdjustVideoModeShadowDDNL - Requested DirectDraw surface "
-	      "will be larger than %d MB.  The surface may fail to be "
-	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
-	      "DIB size.  This limit does not apply to Windows NT/2000, and "
-	      "this message may be ignored on those platforms.\n",
-	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
-    }
-  
-  /* Release our DC */
-  ReleaseDC (NULL, hdc);
-
-  return TRUE;
-}
-
-
-/*
- * Blt exposed regions to the screen
- */
-
-static Bool
-winBltExposedRegionsShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RECT			rcSrc, rcDest;
-  POINT			ptOrigin;
-  HDC			hdcUpdate;
-  PAINTSTRUCT		ps;
-  HRESULT		ddrval = DD_OK;
-  Bool			fReturn = TRUE;
-  int			i;
-
-  /* Quite common case. The primary surface was lost (maybe because of depth
-   * change). Try to create a new primary surface. Bail out if this fails */
-  if (pScreenPriv->pddsPrimary4 == NULL && pScreenPriv->fRetryCreateSurface &&
-      !winCreatePrimarySurfaceShadowDDNL(pScreen))
-    {
-      Sleep(100);
-      return FALSE;
-    }
-  if (pScreenPriv->pddsPrimary4 == NULL)
-    return FALSE;  
-  
-  /* BeginPaint gives us an hdc that clips to the invalidated region */
-  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
-  if (hdcUpdate == NULL)
-    {
-      fReturn = FALSE;
-      ErrorF ("winBltExposedRegionsShadowDDNL - BeginPaint () returned "
-	      "a NULL device context handle.  Aborting blit attempt.\n");
-      goto winBltExposedRegionsShadowDDNL_Exit;
-    }
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-  rcDest.left = ptOrigin.x;
-  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
-  rcDest.top = ptOrigin.y;
-  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
-
-  /* Source can be entire shadow surface, as Blt should clip for us */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  /* Try to regain the primary surface and blit again if we've lost it */
-  for (i = 0; i <= WIN_REGAIN_SURFACE_RETRIES; ++i)
-    {
-      /* Our Blt should be clipped to the invalidated region */
-      ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
-					&rcDest,
-					pScreenPriv->pddsShadow4,
-					&rcSrc,
-					DDBLT_WAIT,
-					NULL);
-      if (ddrval == DDERR_SURFACELOST)
-	{
-	  /* Surface was lost */
-	  winErrorFVerb (1, "winBltExposedRegionsShadowDDNL - "
-          "IDirectDrawSurface4_Blt reported that the primary "
-          "surface was lost, trying to restore, retry: %d\n", i + 1);
-
-	  /* Try to restore the surface, once */
-	  
-	  ddrval = IDirectDrawSurface4_Restore (pScreenPriv->pddsPrimary4);
-	  winDebug ("winBltExposedRegionsShadowDDNL - "
-		  "IDirectDrawSurface4_Restore returned: ");
-	  if (ddrval == DD_OK)
-	    winDebug ("DD_OK\n");
-	  else if (ddrval == DDERR_WRONGMODE)
-	    winDebug ("DDERR_WRONGMODE\n");
-	  else if (ddrval == DDERR_INCOMPATIBLEPRIMARY)
-	    winDebug ("DDERR_INCOMPATIBLEPRIMARY\n");
-	  else if (ddrval == DDERR_UNSUPPORTED)
-	    winDebug ("DDERR_UNSUPPORTED\n");
-	  else if (ddrval == DDERR_INVALIDPARAMS)
-	    winDebug ("DDERR_INVALIDPARAMS\n");
-	  else if (ddrval == DDERR_INVALIDOBJECT)
-	    winDebug ("DDERR_INVALIDOBJECT\n");
-	  else
-	    winDebug ("unknown error: %08x\n", (unsigned int) ddrval);
-	  
-	  /* Loop around to try the blit one more time */
-	  continue;
-	}  
-      else if (FAILED (ddrval))
-	{
-	  fReturn = FALSE;
-	  winErrorFVerb (1, "winBltExposedRegionsShadowDDNL - "
-		  "IDirectDrawSurface4_Blt failed, but surface not "
-		  "lost: %08x %d\n",
-		  (unsigned int) ddrval, (int) ddrval);
-	  goto winBltExposedRegionsShadowDDNL_Exit;
-	}
-      else
-	{
-	  /* Success, stop looping */
-	  break;
-	}
-    }
-
- winBltExposedRegionsShadowDDNL_Exit:
-  /* EndPaint frees the DC */
-  if (hdcUpdate != NULL)
-    EndPaint (pScreenPriv->hwndScreen, &ps);
-  return fReturn;
-}
-
-
-/*
- * Do any engine-specific application-activation processing
- */
-
-static Bool
-winActivateAppShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-
-  /*
-   * Do we have a surface?
-   * Are we active?
-   * Are we full screen?
-   */
-  if (pScreenPriv != NULL
-      && pScreenPriv->pddsPrimary4 != NULL
-      && pScreenPriv->fActive)
-    {
-      /* Primary surface was lost, restore it */
-      IDirectDrawSurface4_Restore (pScreenPriv->pddsPrimary4);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Reblit the shadow framebuffer to the screen.
- */
-
-static Bool
-winRedrawScreenShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HRESULT		ddrval = DD_OK;
-  RECT			rcSrc, rcDest;
-  POINT			ptOrigin;
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-  rcDest.left = ptOrigin.x;
-  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
-  rcDest.top = ptOrigin.y;
-  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
-
-  /* Source can be entire shadow surface, as Blt should clip for us */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  /* Redraw the whole window, to take account for the new colors */
-  ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
-				    &rcDest,
-				    pScreenPriv->pddsShadow4,
-				    &rcSrc,
-				    DDBLT_WAIT,
-				    NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winRedrawScreenShadowDDNL - IDirectDrawSurface4_Blt () "
-	      "failed: %08x\n",
-	      (unsigned int) ddrval);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Realize the currently installed colormap
- */
-
-static Bool
-winRealizeInstalledPaletteShadowDDNL (ScreenPtr pScreen)
-{
-  return TRUE;
-}
-
-
-/*
- * Install the specified colormap
- */
-
-static Bool
-winInstallColormapShadowDDNL (ColormapPtr pColormap)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  HRESULT		ddrval = DD_OK;
-
-  /* Install the DirectDraw palette on the primary surface */
-  ddrval = IDirectDrawSurface4_SetPalette (pScreenPriv->pddsPrimary4,
-					   pCmapPriv->lpDDPalette);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winInstallColormapShadowDDNL - Failed installing the "
-	      "DirectDraw palette.\n");
-      return FALSE;
-    }
-
-  /* Save a pointer to the newly installed colormap */
-  pScreenPriv->pcmapInstalled = pColormap;
-
-  return TRUE;
-}
-
-
-/*
- * Store the specified colors in the specified colormap
- */
-
-static Bool
-winStoreColorsShadowDDNL (ColormapPtr pColormap, 
-			  int ndef,
-			  xColorItem *pdefs)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  ColormapPtr		curpmap = pScreenPriv->pcmapInstalled;
-  HRESULT		ddrval = DD_OK;
-  
-  /* Put the X colormap entries into the Windows logical palette */
-  ddrval = IDirectDrawPalette_SetEntries (pCmapPriv->lpDDPalette,
-					  0,
-					  pdefs[0].pixel,
-					  ndef,
-					  pCmapPriv->peColors 
-					  + pdefs[0].pixel);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winStoreColorsShadowDDNL - SetEntries () failed: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-
-  /* Don't install the DirectDraw palette if the colormap is not installed */
-  if (pColormap != curpmap)
-    {
-      return TRUE;
-    }
-
-  if (!winInstallColormapShadowDDNL (pColormap))
-    {
-      ErrorF ("winStoreColorsShadowDDNL - Failed installing colormap\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap initialization procedure
- */
-
-static Bool
-winCreateColormapShadowDDNL (ColormapPtr pColormap)
-{
-  HRESULT		ddrval = DD_OK;
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  
-  /* Create a DirectDraw palette */
-  ddrval = IDirectDraw4_CreatePalette (pScreenPriv->pdd4,
-				       DDPCAPS_8BIT | DDPCAPS_ALLOW256,
-				       pCmapPriv->peColors,
-				       &pCmapPriv->lpDDPalette,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreateColormapShadowDDNL - CreatePalette failed\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap destruction procedure
- */
-
-static Bool
-winDestroyColormapShadowDDNL (ColormapPtr pColormap)
-{
-  winScreenPriv(pColormap->pScreen);
-  winCmapPriv(pColormap);
-  HRESULT		ddrval = DD_OK;
-
-  /*
-   * Is colormap to be destroyed the default?
-   *
-   * Non-default colormaps should have had winUninstallColormap
-   * called on them before we get here.  The default colormap
-   * will not have had winUninstallColormap called on it.  Thus,
-   * we need to handle the default colormap in a special way.
-   */
-  if (pColormap->flags & IsDefault)
-    {
-#if CYGDEBUG
-      winDebug ("winDestroyColormapShadowDDNL - Destroying default colormap\n");
-#endif
-      
-      /*
-       * FIXME: Walk the list of all screens, popping the default
-       * palette out of each screen device context.
-       */
-      
-      /* Pop the palette out of the primary surface */
-      ddrval = IDirectDrawSurface4_SetPalette (pScreenPriv->pddsPrimary4,
-					       NULL);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winDestroyColormapShadowDDNL - Failed freeing the "
-		  "default colormap DirectDraw palette.\n");
-	  return FALSE;
-	}
-
-      /* Clear our private installed colormap pointer */
-      pScreenPriv->pcmapInstalled = NULL;
-    }
-  
-  /* Release the palette */
-  IDirectDrawPalette_Release (pCmapPriv->lpDDPalette);
- 
-  /* Invalidate the colormap privates */
-  pCmapPriv->lpDDPalette = NULL;
-
-  return TRUE;
-}
-
-
-/*
- * Set pointers to our engine specific functions
- */
-
-Bool
-winSetEngineFunctionsShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  
-  /* Set our pointers */
-  pScreenPriv->pwinAllocateFB = winAllocateFBShadowDDNL;
-  pScreenPriv->pwinShadowUpdate = winShadowUpdateDDNL;
-  pScreenPriv->pwinCloseScreen = winCloseScreenShadowDDNL;
-  pScreenPriv->pwinInitVisuals = winInitVisualsShadowDDNL;
-  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowDDNL;
-  if (pScreenInfo->fFullScreen)
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
-  else
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
-  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
-  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowDDNL;
-  pScreenPriv->pwinActivateApp = winActivateAppShadowDDNL;
-  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowDDNL;
-  pScreenPriv->pwinRealizeInstalledPalette
-    = winRealizeInstalledPaletteShadowDDNL;
-  pScreenPriv->pwinInstallColormap = winInstallColormapShadowDDNL;
-  pScreenPriv->pwinStoreColors = winStoreColorsShadowDDNL;
-  pScreenPriv->pwinCreateColormap = winCreateColormapShadowDDNL;
-  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowDDNL;
-  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
-  pScreenPriv->pwinCreatePrimarySurface = winCreatePrimarySurfaceShadowDDNL;
-  pScreenPriv->pwinReleasePrimarySurface = winReleasePrimarySurfaceShadowDDNL;
-#ifdef XWIN_MULTIWINDOW
-  pScreenPriv->pwinFinishCreateWindowsWindow
-    = winFinishCreateWindowsWindowDDNL;
-#endif
-
-  return TRUE;
-}
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * External symbols
+ */
+
+extern HWND			g_hDlgExit;
+
+
+/*
+ * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly,
+ * so we have to redefine it here.
+ */
+#ifdef DEFINE_GUID
+#undef DEFINE_GUID
+#define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#endif /* DEFINE_GUID */
+
+/*
+ * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined
+ * here manually.  Should be handled by ddraw.h
+ */
+#ifndef IID_IDirectDraw4
+DEFINE_GUID( IID_IDirectDraw4, 0x9c59509a,0x39bd,0x11d1,0x8c,0x4a,0x00,0xc0,0x4f,0xd9,0x30,0xc5 );
+#endif /* IID_IDirectDraw4 */
+
+#define FAIL_MSG_MAX_BLT	10
+
+
+/*
+ * Local prototypes
+ */
+
+static Bool
+winAllocateFBShadowDDNL (ScreenPtr pScreen);
+
+static void
+winShadowUpdateDDNL (ScreenPtr pScreen, 
+		     shadowBufPtr pBuf);
+
+static Bool
+winCloseScreenShadowDDNL (int nIndex, ScreenPtr pScreen);
+
+static Bool
+winInitVisualsShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winAdjustVideoModeShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winBltExposedRegionsShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winActivateAppShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winRedrawScreenShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winRealizeInstalledPaletteShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winInstallColormapShadowDDNL (ColormapPtr pColormap);
+
+static Bool
+winStoreColorsShadowDDNL (ColormapPtr pmap, 
+			  int ndef,
+			  xColorItem *pdefs);
+
+static Bool
+winCreateColormapShadowDDNL (ColormapPtr pColormap);
+
+static Bool
+winDestroyColormapShadowDDNL (ColormapPtr pColormap);
+
+static Bool
+winCreatePrimarySurfaceShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winReleasePrimarySurfaceShadowDDNL (ScreenPtr pScreen);
+
+
+/*
+ * Create the primary surface and attach the clipper.
+ * Used for both the initial surface creation and during
+ * WM_DISPLAYCHANGE messages.
+ */
+
+static Bool
+winCreatePrimarySurfaceShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC2	ddsd;
+
+  winDebug ("winCreatePrimarySurfaceShadowDDNL - Creating primary surface\n");
+
+  /* Describe the primary surface */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
+  
+  /* Create the primary surface */
+  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
+				       &ddsd,
+				       &pScreenPriv->pddsPrimary4,
+				       NULL);
+  pScreenPriv->fRetryCreateSurface = FALSE;
+  if (FAILED (ddrval))
+    {
+      if (ddrval == DDERR_NOEXCLUSIVEMODE)
+        {
+          /* Recreating the surface failed. Mark screen to retry later */ 
+          pScreenPriv->fRetryCreateSurface = TRUE;
+          winDebug ("winCreatePrimarySurfaceShadowDDNL - Could not create "
+	          "primary surface: DDERR_NOEXCLUSIVEMODE\n");
+        }
+      else
+        {
+          ErrorF ("winCreatePrimarySurfaceShadowDDNL - Could not create "
+	          "primary surface: %08x\n", (unsigned int) ddrval);
+        }
+      return FALSE;
+    }
+  
+#if 1
+  winDebug ("winCreatePrimarySurfaceShadowDDNL - Created primary surface\n");
+#endif
+
+  /* Attach our clipper to our primary surface handle */
+  ddrval = IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
+					   pScreenPriv->pddcPrimary);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreatePrimarySurfaceShadowDDNL - Primary attach clipper "
+	      "failed: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if 1
+  winDebug ("winCreatePrimarySurfaceShadowDDNL - Attached clipper to primary "
+	  "surface\n");
+#endif
+
+  /* Everything was correct */
+  return TRUE;
+}
+
+
+/*
+ * Detach the clipper and release the primary surface.
+ * Called from WM_DISPLAYCHANGE.
+ */
+
+static Bool
+winReleasePrimarySurfaceShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+
+  winDebug ("winReleasePrimarySurfaceShadowDDNL - Hello\n");
+
+  /* Release the primary surface and clipper, if they exist */
+  if (pScreenPriv->pddsPrimary4)
+    {
+      /*
+       * Detach the clipper from the primary surface.
+       * NOTE: We do this explicity for clarity.  The Clipper is not released.
+       */
+      IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
+				      NULL);
+  
+      winDebug ("winReleasePrimarySurfaceShadowDDNL - Detached clipper\n");
+
+      /* Release the primary surface */
+      IDirectDrawSurface4_Release (pScreenPriv->pddsPrimary4);
+      pScreenPriv->pddsPrimary4 = NULL;
+    }
+
+  winDebug ("winReleasePrimarySurfaceShadowDDNL - Released primary surface\n");
+  
+  return TRUE;
+}
+
+
+/*
+ * Create a DirectDraw surface for the shadow framebuffer; also create
+ * a primary surface object so we can blit to the display.
+ * 
+ * Install a DirectDraw clipper on our primary surface object
+ * that clips our blits to the unobscured client area of our display window.
+ */
+
+Bool
+winAllocateFBShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC2	ddsdShadow;
+  char			*lpSurface = NULL;
+  DDPIXELFORMAT		ddpfPrimary;
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - w %d h %d d %d\n",
+	  pScreenInfo->dwWidth, pScreenInfo->dwHeight, pScreenInfo->dwDepth);
+#endif
+
+  /* Allocate memory for our shadow surface */
+  lpSurface = malloc (pScreenInfo->dwPaddedWidth * pScreenInfo->dwHeight);
+  if (lpSurface == NULL)
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not allocate bits\n");
+      return FALSE;
+    }
+
+  /*
+   * Initialize the framebuffer memory so we don't get a 
+   * strange display at startup
+   */
+  ZeroMemory (lpSurface, pScreenInfo->dwPaddedWidth * pScreenInfo->dwHeight);
+  
+  /* Create a clipper */
+  ddrval = (*g_fpDirectDrawCreateClipper) (0,
+					   &pScreenPriv->pddcPrimary,
+					   NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not attach clipper: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Created a clipper\n");
+#endif
+
+  /* Get a device context for the screen  */
+  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
+
+  /* Attach the clipper to our display window */
+  ddrval = IDirectDrawClipper_SetHWnd (pScreenPriv->pddcPrimary,
+				       0,
+				       pScreenPriv->hwndScreen);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Clipper not attached "
+	      "to window: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Attached clipper to window\n");
+#endif
+
+  /* Create a DirectDraw object, store the address at lpdd */
+  ddrval = (*g_fpDirectDrawCreate) (NULL,
+				    (LPDIRECTDRAW*) &pScreenPriv->pdd,
+				    NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not start "
+	      "DirectDraw: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Created and initialized DD\n");
+#endif
+
+  /* Get a DirectDraw4 interface pointer */
+  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
+				       &IID_IDirectDraw4,
+				       (LPVOID*) &pScreenPriv->pdd4);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Failed DD4 query: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+  /* Are we full screen? */
+  if (pScreenInfo->fFullScreen)
+    {
+      DDSURFACEDESC2	ddsdCurrent;
+      DWORD		dwRefreshRateCurrent = 0;
+      HDC		hdc = NULL;
+
+      /* Set the cooperative level to full screen */
+      ddrval = IDirectDraw4_SetCooperativeLevel (pScreenPriv->pdd4,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_EXCLUSIVE
+						 | DDSCL_FULLSCREEN);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winAllocateFBShadowDDNL - Could not set "
+		  "cooperative level: %08x\n",
+		  (unsigned int) ddrval);
+	  return FALSE;
+	}
+
+      /*
+       * We only need to get the current refresh rate for comparison
+       * if a refresh rate has been passed on the command line.
+       */
+      if (pScreenInfo->dwRefreshRate != 0)
+	{
+	  ZeroMemory (&ddsdCurrent, sizeof (ddsdCurrent));
+	  ddsdCurrent.dwSize = sizeof (ddsdCurrent);
+
+	  /* Get information about current display settings */
+	  ddrval = IDirectDraw4_GetDisplayMode (pScreenPriv->pdd4,
+						&ddsdCurrent);
+	  if (FAILED (ddrval))
+	    {
+	      ErrorF ("winAllocateFBShadowDDNL - Could not get current "
+		      "refresh rate: %08x.  Continuing.\n",
+		      (unsigned int) ddrval);
+	      dwRefreshRateCurrent = 0;
+	    }
+	  else
+	    {
+	      /* Grab the current refresh rate */
+	      dwRefreshRateCurrent = ddsdCurrent.u2.dwRefreshRate;
+	    }
+	}
+
+      /* Clean up the refresh rate */
+      if (dwRefreshRateCurrent == pScreenInfo->dwRefreshRate)
+	{
+	  /*
+	   * Refresh rate is non-specified or equal to current.
+	   */
+	  pScreenInfo->dwRefreshRate = 0;
+	}
+
+      /* Grab a device context for the screen */
+      hdc = GetDC (NULL);
+      if (hdc == NULL)
+	{
+	  ErrorF ("winAllocateFBShadowDDNL - GetDC () failed\n");
+	  return FALSE;
+	}
+
+      /* Only change the video mode when different than current mode */
+      if (!pScreenInfo->fMultipleMonitors
+	  && (pScreenInfo->dwWidth != GetSystemMetrics (SM_CXSCREEN)
+	      || pScreenInfo->dwHeight != GetSystemMetrics (SM_CYSCREEN)
+	      || pScreenInfo->dwBPP != GetDeviceCaps (hdc, BITSPIXEL)
+	      || pScreenInfo->dwRefreshRate != 0))
+	{
+	  winDebug ("winAllocateFBShadowDDNL - Changing video mode\n");
+
+	  /* Change the video mode to the mode requested, and use the driver default refresh rate on failure */
+	  ddrval = IDirectDraw4_SetDisplayMode (pScreenPriv->pdd4,
+						pScreenInfo->dwWidth,
+						pScreenInfo->dwHeight,
+						pScreenInfo->dwBPP,
+						pScreenInfo->dwRefreshRate,
+						0);	       
+	  if (FAILED (ddrval))
+	    {
+	      ErrorF ("winAllocateFBShadowDDNL - Could not set "
+		      "full screen display mode: %08x\n",
+		      (unsigned int) ddrval);
+	      ErrorF ("winAllocateFBShadowDDNL - Using default driver refresh rate\n");
+	      ddrval = IDirectDraw4_SetDisplayMode (pScreenPriv->pdd4,
+						    pScreenInfo->dwWidth,
+						    pScreenInfo->dwHeight,
+						    pScreenInfo->dwBPP,
+						    0,
+						    0);
+	      if (FAILED(ddrval))
+		{
+			ErrorF ("winAllocateFBShadowDDNL - Could not set default refresh rate "
+				"full screen display mode: %08x\n",
+				(unsigned int) ddrval);
+			return FALSE;
+		}
+	    }
+	}
+      else
+	{
+	  winDebug ("winAllocateFBShadowDDNL - Not changing video mode\n");
+	}
+
+      /* Release our DC */
+      ReleaseDC (NULL, hdc);
+      hdc = NULL;
+    }
+  else
+    {
+      /* Set the cooperative level for windowed mode */
+      ddrval = IDirectDraw4_SetCooperativeLevel (pScreenPriv->pdd4,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_NORMAL);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winAllocateFBShadowDDNL - Could not set "
+		  "cooperative level: %08x\n",
+		  (unsigned int) ddrval);
+	  return FALSE;
+	}
+    }
+
+  /* Create the primary surface */
+  if (!winCreatePrimarySurfaceShadowDDNL (pScreen))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - winCreatePrimarySurfaceShadowDDNL "
+	      "failed\n");
+      return FALSE;
+    }
+
+  /* Get primary surface's pixel format */
+  ZeroMemory (&ddpfPrimary, sizeof (ddpfPrimary));
+  ddpfPrimary.dwSize = sizeof (ddpfPrimary);
+  ddrval = IDirectDrawSurface4_GetPixelFormat (pScreenPriv->pddsPrimary4,
+					       &ddpfPrimary);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not get primary "
+	      "pixformat: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Primary masks: %08x %08x %08x "
+	  "dwRGBBitCount: %d\n",
+	  ddpfPrimary.u2.dwRBitMask,
+	  ddpfPrimary.u3.dwGBitMask,
+	  ddpfPrimary.u4.dwBBitMask,
+	  ddpfPrimary.u1.dwRGBBitCount);
+#endif
+
+  /* Describe the shadow surface to be created */
+  /*
+   * NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
+   * as drawing, locking, and unlocking take forever
+   * with video memory surfaces.  In addition,
+   * video memory is a somewhat scarce resource,
+   * so you shouldn't be allocating video memory when
+   * you have the option of using system memory instead.
+   */
+  ZeroMemory (&ddsdShadow, sizeof (ddsdShadow));
+  ddsdShadow.dwSize = sizeof (ddsdShadow);
+  ddsdShadow.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH
+    | DDSD_LPSURFACE | DDSD_PITCH | DDSD_PIXELFORMAT;
+  ddsdShadow.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
+  ddsdShadow.dwHeight = pScreenInfo->dwHeight;
+  ddsdShadow.dwWidth = pScreenInfo->dwWidth;
+  ddsdShadow.u1.lPitch = pScreenInfo->dwPaddedWidth;
+  ddsdShadow.lpSurface = lpSurface;
+  ddsdShadow.u4.ddpfPixelFormat = ddpfPrimary;
+  
+  winDebug ("winAllocateFBShadowDDNL - lPitch: %d\n",
+	  (int) pScreenInfo->dwPaddedWidth);
+
+  /* Create the shadow surface */
+  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
+				       &ddsdShadow,
+				       &pScreenPriv->pddsShadow4,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not create shadow "
+	      "surface: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+  
+#if CYGDEBUG || YES
+  winDebug ("winAllocateFBShadowDDNL - Created shadow pitch: %d\n",
+	  (int) ddsdShadow.u1.lPitch);
+#endif
+
+  /* Grab the pitch from the surface desc */
+  pScreenInfo->dwStride = (ddsdShadow.u1.lPitch * 8)
+    / pScreenInfo->dwBPP;
+
+#if CYGDEBUG || YES
+  winDebug ("winAllocateFBShadowDDNL - Created shadow stride: %d\n",
+	  (int) pScreenInfo->dwStride);
+#endif
+
+  /* Save the pointer to our surface memory */
+  pScreenInfo->pfb = lpSurface;
+  
+  /* Grab the masks from the surface description */
+  pScreenPriv->dwRedMask = ddsdShadow.u4.ddpfPixelFormat.u2.dwRBitMask;
+  pScreenPriv->dwGreenMask = ddsdShadow.u4.ddpfPixelFormat.u3.dwGBitMask;
+  pScreenPriv->dwBlueMask = ddsdShadow.u4.ddpfPixelFormat.u4.dwBBitMask;
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+/*
+ * Create a DirectDraw surface for the new multi-window window
+ */
+
+static
+Bool
+winFinishCreateWindowsWindowDDNL (WindowPtr pWin)
+{
+  winWindowPriv(pWin);
+  winPrivScreenPtr	pScreenPriv = pWinPriv->pScreenPriv;
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC2	ddsd;
+  int			iWidth, iHeight;
+  int			iX, iY;
+
+  winDebug ("winFinishCreateWindowsWindowDDNL!\n\n");
+
+  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
+  
+  iWidth = pWin->drawable.width;
+  iHeight = pWin->drawable.height;
+
+  /* Describe the primary surface */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
+  ddsd.dwHeight = iHeight;
+  ddsd.dwWidth = iWidth;
+
+  /* Create the primary surface */
+  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
+				       &ddsd,
+				       &pWinPriv->pddsPrimary4,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winFinishCreateWindowsWindowDDNL - Could not create primary "
+	      "surface: %08x\n",
+	      (unsigned int)ddrval);
+      return FALSE;
+    }
+  return TRUE;
+}
+#endif
+
+
+/*
+ * Transfer the damaged regions of the shadow framebuffer to the display.
+ */
+
+static void
+winShadowUpdateDDNL (ScreenPtr pScreen, 
+		     shadowBufPtr pBuf)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RegionPtr		damage = shadowDamage(pBuf);
+  HRESULT		ddrval = DD_OK;
+  RECT			rcDest, rcSrc;
+  POINT			ptOrigin;
+  DWORD			dwBox = REGION_NUM_RECTS (damage);
+  BoxPtr		pBox = REGION_RECTS (damage);
+  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
+
+  /*
+   * Return immediately if the app is not active
+   * and we are fullscreen, or if we have a bad display depth
+   */
+  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
+      || pScreenPriv->fBadDepth) return;
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+
+  /*
+   * Handle small regions with multiple blits,
+   * handle large regions by creating a clipping region and 
+   * doing a single blit constrained to that clipping region.
+   */
+  if (pScreenInfo->dwClipUpdatesNBoxes == 0
+      || dwBox < pScreenInfo->dwClipUpdatesNBoxes)
+    {
+      /* Loop through all boxes in the damaged region */
+      while (dwBox--)
+	{
+	  /* Assign damage box to source rectangle */
+	  rcSrc.left = pBox->x1;
+	  rcSrc.top = pBox->y1;
+	  rcSrc.right = pBox->x2;
+	  rcSrc.bottom = pBox->y2;
+	  
+	  /* Calculate destination rectangle */
+	  rcDest.left = ptOrigin.x + rcSrc.left;
+	  rcDest.top = ptOrigin.y + rcSrc.top;
+	  rcDest.right = ptOrigin.x + rcSrc.right;
+	  rcDest.bottom = ptOrigin.y + rcSrc.bottom;
+	  
+	  /* Blit the damaged areas */
+	  ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
+					    &rcDest,
+					    pScreenPriv->pddsShadow4,
+					    &rcSrc,
+					    DDBLT_WAIT,
+					    NULL);
+	  if (FAILED (ddrval))
+	    {
+	      static int	s_iFailCount = 0;
+	      
+	      if (s_iFailCount < FAIL_MSG_MAX_BLT)
+		{
+		  ErrorF ("winShadowUpdateDDNL - IDirectDrawSurface4_Blt () "
+			  "failed: %08x\n",
+			  (unsigned int) ddrval);
+		  
+		  ++s_iFailCount;
+
+		  if (s_iFailCount == FAIL_MSG_MAX_BLT)
+		    {
+		      ErrorF ("winShadowUpdateDDNL - IDirectDrawSurface4_Blt "
+			      "failure message maximum (%d) reached.  No "
+			      "more failure messages will be printed.\n",
+			      FAIL_MSG_MAX_BLT);
+		    }
+		}
+	    }
+	  
+	  /* Get a pointer to the next box */
+	  ++pBox;
+	}
+    }
+  else
+    {
+      BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
+
+      /* Compute a GDI region from the damaged region */
+      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+      dwBox--;
+      pBox++;
+      while (dwBox--)
+	{
+	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
+	  DeleteObject (hrgnTemp);
+	  pBox++;
+	}
+
+      /* Install the GDI region as a clipping region */
+      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
+      DeleteObject (hrgnCombined);
+      hrgnCombined = NULL;
+
+#if CYGDEBUG
+      winDebug ("winShadowUpdateDDNL - be x1 %d y1 %d x2 %d y2 %d\n",
+	      pBoxExtents->x1, pBoxExtents->y1,
+	      pBoxExtents->x2, pBoxExtents->y2);
+#endif
+
+      /* Calculating a bounding box for the source is easy */
+      rcSrc.left = pBoxExtents->x1;
+      rcSrc.top = pBoxExtents->y1;
+      rcSrc.right = pBoxExtents->x2;
+      rcSrc.bottom = pBoxExtents->y2;
+
+      /* Calculating a bounding box for the destination is trickier */
+      rcDest.left = ptOrigin.x + rcSrc.left;
+      rcDest.top = ptOrigin.y + rcSrc.top;
+      rcDest.right = ptOrigin.x + rcSrc.right;
+      rcDest.bottom = ptOrigin.y + rcSrc.bottom;
+
+      /* Our Blt should be clipped to the invalidated region */
+      ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
+					&rcDest,
+					pScreenPriv->pddsShadow4,
+					&rcSrc,
+					DDBLT_WAIT,
+					NULL);
+
+      /* Reset the clip region */
+      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
+    }
+}
+
+
+/*
+ * Call the wrapped CloseScreen function.
+ *
+ * Free our resources and private structures.
+ */
+
+static Bool
+winCloseScreenShadowDDNL (int nIndex, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  Bool			fReturn;
+
+#if CYGDEBUG
+  winDebug ("winCloseScreenShadowDDNL - Freeing screen resources\n");
+#endif
+
+  /* Flag that the screen is closed */
+  pScreenPriv->fClosed = TRUE;
+  pScreenPriv->fActive = FALSE;
+
+  /* Call the wrapped CloseScreen procedure */
+  WIN_UNWRAP(CloseScreen);
+  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
+
+  /* Free the screen DC */
+  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
+
+  /* Delete the window property */
+  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
+
+  /* Free the shadow surface, if there is one */
+  if (pScreenPriv->pddsShadow4)
+    {
+      IDirectDrawSurface4_Release (pScreenPriv->pddsShadow4);
+      free (pScreenInfo->pfb);
+      pScreenInfo->pfb = NULL;
+      pScreenPriv->pddsShadow4 = NULL;
+    }
+
+  /* Detach the clipper from the primary surface and release the clipper. */
+  if (pScreenPriv->pddcPrimary)
+    {
+      /* Detach the clipper */
+      IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
+				      NULL);
+
+      /* Release the clipper object */
+      IDirectDrawClipper_Release (pScreenPriv->pddcPrimary);
+      pScreenPriv->pddcPrimary = NULL;
+    }
+
+  /* Release the primary surface, if there is one */
+  if (pScreenPriv->pddsPrimary4)
+    {
+      IDirectDrawSurface4_Release (pScreenPriv->pddsPrimary4);
+      pScreenPriv->pddsPrimary4 = NULL;
+    }
+
+  /* Free the DirectDraw4 object, if there is one */
+  if (pScreenPriv->pdd4)
+    {
+      IDirectDraw4_RestoreDisplayMode (pScreenPriv->pdd4);
+      IDirectDraw4_Release (pScreenPriv->pdd4);
+      pScreenPriv->pdd4 = NULL;
+    }
+
+  /* Free the DirectDraw object, if there is one */
+  if (pScreenPriv->pdd)
+    {
+      IDirectDraw_Release (pScreenPriv->pdd);
+      pScreenPriv->pdd = NULL;
+    }
+
+  /* Delete tray icon, if we have one */
+  if (!pScreenInfo->fNoTrayIcon)
+    winDeleteNotifyIcon (pScreenPriv);
+
+  /* Free the exit confirmation dialog box, if it exists */
+  if (g_hDlgExit != NULL)
+    {
+      DestroyWindow (g_hDlgExit);
+      g_hDlgExit = NULL;
+    }
+
+  /* Kill our window */
+  if (pScreenPriv->hwndScreen)
+    {
+      DestroyWindow (pScreenPriv->hwndScreen);
+      pScreenPriv->hwndScreen = NULL;
+    }
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Destroy the thread startup mutex */
+  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
+#endif
+
+  /* Kill our screeninfo's pointer to the screen */
+  pScreenInfo->pScreen = NULL;
+
+  /* Invalidate the ScreenInfo's fb pointer */
+  pScreenInfo->pfb = NULL;
+
+  /* Free the screen privates for this screen */
+  free ((pointer) pScreenPriv);
+
+  return fReturn;
+}
+
+
+/*
+ * Tell mi what sort of visuals we need.
+ *
+ * Generally we only need one visual, as our screen can only
+ * handle one format at a time, I believe.  You may want
+ * to verify that last sentence.
+ */
+
+static Bool
+winInitVisualsShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
+
+  /* Count the number of ones in each color mask */
+  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
+  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
+  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
+  
+  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
+  if (dwRedBits == 0 || dwGreenBits == 0 || dwBlueBits == 0)
+    pScreenPriv->dwBitsPerRGB = 8;
+  else if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwRedBits;
+  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwGreenBits;
+  else
+    pScreenPriv->dwBitsPerRGB = dwBlueBits;
+
+  winDebug ("winInitVisualsShadowDDNL - Masks %08x %08x %08x BPRGB %d d %d "
+	  "bpp %d\n",
+	  (unsigned int) pScreenPriv->dwRedMask,
+	  (unsigned int) pScreenPriv->dwGreenMask,
+	  (unsigned int) pScreenPriv->dwBlueMask,
+	  (int) pScreenPriv->dwBitsPerRGB,
+	  (int) pScreenInfo->dwDepth,
+	  (int) pScreenInfo->dwBPP);
+
+  /* Create a single visual according to the Windows screen depth */
+  switch (pScreenInfo->dwDepth)
+    {
+    case 24:
+    case 16:
+    case 15:
+#if defined(XFree86Server)
+      /* Setup the real visual */
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     -1,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!miSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     -1,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#else /* XFree86Server */
+      /* Setup the real visual */
+      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!fbSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#endif /* XFree86Server */
+      break;
+
+    case 8:
+#if defined(XFree86Server)
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColorMask : StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColor : StaticColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+#else /* XFree86Server */
+        if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColorMask : StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}    
+#endif /* XFree86Server */
+      break;
+
+    default:
+      ErrorF ("winInitVisualsShadowDDNL - Unknown screen depth\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winInitVisualsShadowDDNL - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Adjust the user proposed video mode
+ */
+
+static Bool
+winAdjustVideoModeShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HDC			hdc = NULL;
+  DWORD			dwBPP;
+
+  /* We're in serious trouble if we can't get a DC */
+  hdc = GetDC (NULL);
+  if (hdc == NULL)
+    {
+      ErrorF ("winAdjustVideoModeShadowDDNL - GetDC () failed\n");
+      return FALSE;
+    }
+
+  /* Query GDI for current display depth */
+  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* DirectDraw can only change the depth in fullscreen mode */
+  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
+    {
+      /* No -depth parameter passed, let the user know the depth being used */
+      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - Using Windows display "
+	      "depth of %d bits per pixel\n", (int) dwBPP);
+
+      /* Use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  else if (pScreenInfo->fFullScreen
+	   && pScreenInfo->dwBPP != dwBPP)
+    {
+      /* FullScreen, and GDI depth differs from -depth parameter */
+      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - FullScreen, using command "
+	      "line bpp: %d\n", (int) pScreenInfo->dwBPP);
+    }
+  else if (dwBPP != pScreenInfo->dwBPP)
+    {
+      /* Windowed, and GDI depth differs from -depth parameter */
+      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - Windowed, command line "
+	      "bpp: %d, using bpp: %d\n",
+	      (int) pScreenInfo->dwBPP, (int) dwBPP);
+
+      /* We'll use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+
+  /* See if the shadow bitmap will be larger than the DIB size limit */
+  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
+      >= WIN_DIB_MAXIMUM_SIZE)
+    {
+      winErrorFVerb (1, "winAdjustVideoModeShadowDDNL - Requested DirectDraw surface "
+	      "will be larger than %d MB.  The surface may fail to be "
+	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
+	      "DIB size.  This limit does not apply to Windows NT/2000, and "
+	      "this message may be ignored on those platforms.\n",
+	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
+    }
+  
+  /* Release our DC */
+  ReleaseDC (NULL, hdc);
+
+  return TRUE;
+}
+
+
+/*
+ * Blt exposed regions to the screen
+ */
+
+static Bool
+winBltExposedRegionsShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RECT			rcSrc, rcDest;
+  POINT			ptOrigin;
+  HDC			hdcUpdate;
+  PAINTSTRUCT		ps;
+  HRESULT		ddrval = DD_OK;
+  Bool			fReturn = TRUE;
+  int			i;
+
+  /* Quite common case. The primary surface was lost (maybe because of depth
+   * change). Try to create a new primary surface. Bail out if this fails */
+  if (pScreenPriv->pddsPrimary4 == NULL && pScreenPriv->fRetryCreateSurface &&
+      !winCreatePrimarySurfaceShadowDDNL(pScreen))
+    {
+      Sleep(100);
+      return FALSE;
+    }
+  if (pScreenPriv->pddsPrimary4 == NULL)
+    return FALSE;  
+  
+  /* BeginPaint gives us an hdc that clips to the invalidated region */
+  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
+  if (hdcUpdate == NULL)
+    {
+      fReturn = FALSE;
+      ErrorF ("winBltExposedRegionsShadowDDNL - BeginPaint () returned "
+	      "a NULL device context handle.  Aborting blit attempt.\n");
+      goto winBltExposedRegionsShadowDDNL_Exit;
+    }
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+  rcDest.left = ptOrigin.x;
+  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
+  rcDest.top = ptOrigin.y;
+  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
+
+  /* Source can be entire shadow surface, as Blt should clip for us */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  /* Try to regain the primary surface and blit again if we've lost it */
+  for (i = 0; i <= WIN_REGAIN_SURFACE_RETRIES; ++i)
+    {
+      /* Our Blt should be clipped to the invalidated region */
+      ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
+					&rcDest,
+					pScreenPriv->pddsShadow4,
+					&rcSrc,
+					DDBLT_WAIT,
+					NULL);
+      if (ddrval == DDERR_SURFACELOST)
+	{
+	  /* Surface was lost */
+	  winErrorFVerb (1, "winBltExposedRegionsShadowDDNL - "
+          "IDirectDrawSurface4_Blt reported that the primary "
+          "surface was lost, trying to restore, retry: %d\n", i + 1);
+
+	  /* Try to restore the surface, once */
+	  
+	  ddrval = IDirectDrawSurface4_Restore (pScreenPriv->pddsPrimary4);
+	  winDebug ("winBltExposedRegionsShadowDDNL - "
+		  "IDirectDrawSurface4_Restore returned: ");
+	  if (ddrval == DD_OK)
+	    winDebug ("DD_OK\n");
+	  else if (ddrval == DDERR_WRONGMODE)
+	    winDebug ("DDERR_WRONGMODE\n");
+	  else if (ddrval == DDERR_INCOMPATIBLEPRIMARY)
+	    winDebug ("DDERR_INCOMPATIBLEPRIMARY\n");
+	  else if (ddrval == DDERR_UNSUPPORTED)
+	    winDebug ("DDERR_UNSUPPORTED\n");
+	  else if (ddrval == DDERR_INVALIDPARAMS)
+	    winDebug ("DDERR_INVALIDPARAMS\n");
+	  else if (ddrval == DDERR_INVALIDOBJECT)
+	    winDebug ("DDERR_INVALIDOBJECT\n");
+	  else
+	    winDebug ("unknown error: %08x\n", (unsigned int) ddrval);
+	  
+	  /* Loop around to try the blit one more time */
+	  continue;
+	}  
+      else if (FAILED (ddrval))
+	{
+	  fReturn = FALSE;
+	  winErrorFVerb (1, "winBltExposedRegionsShadowDDNL - "
+		  "IDirectDrawSurface4_Blt failed, but surface not "
+		  "lost: %08x %d\n",
+		  (unsigned int) ddrval, (int) ddrval);
+	  goto winBltExposedRegionsShadowDDNL_Exit;
+	}
+      else
+	{
+	  /* Success, stop looping */
+	  break;
+	}
+    }
+
+ winBltExposedRegionsShadowDDNL_Exit:
+  /* EndPaint frees the DC */
+  if (hdcUpdate != NULL)
+    EndPaint (pScreenPriv->hwndScreen, &ps);
+  return fReturn;
+}
+
+
+/*
+ * Do any engine-specific application-activation processing
+ */
+
+static Bool
+winActivateAppShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+
+  /*
+   * Do we have a surface?
+   * Are we active?
+   * Are we full screen?
+   */
+  if (pScreenPriv != NULL
+      && pScreenPriv->pddsPrimary4 != NULL
+      && pScreenPriv->fActive)
+    {
+      /* Primary surface was lost, restore it */
+      IDirectDrawSurface4_Restore (pScreenPriv->pddsPrimary4);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Reblit the shadow framebuffer to the screen.
+ */
+
+static Bool
+winRedrawScreenShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HRESULT		ddrval = DD_OK;
+  RECT			rcSrc, rcDest;
+  POINT			ptOrigin;
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+  rcDest.left = ptOrigin.x;
+  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
+  rcDest.top = ptOrigin.y;
+  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
+
+  /* Source can be entire shadow surface, as Blt should clip for us */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  /* Redraw the whole window, to take account for the new colors */
+  ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
+				    &rcDest,
+				    pScreenPriv->pddsShadow4,
+				    &rcSrc,
+				    DDBLT_WAIT,
+				    NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winRedrawScreenShadowDDNL - IDirectDrawSurface4_Blt () "
+	      "failed: %08x\n",
+	      (unsigned int) ddrval);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Realize the currently installed colormap
+ */
+
+static Bool
+winRealizeInstalledPaletteShadowDDNL (ScreenPtr pScreen)
+{
+  return TRUE;
+}
+
+
+/*
+ * Install the specified colormap
+ */
+
+static Bool
+winInstallColormapShadowDDNL (ColormapPtr pColormap)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  HRESULT		ddrval = DD_OK;
+
+  /* Install the DirectDraw palette on the primary surface */
+  ddrval = IDirectDrawSurface4_SetPalette (pScreenPriv->pddsPrimary4,
+					   pCmapPriv->lpDDPalette);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winInstallColormapShadowDDNL - Failed installing the "
+	      "DirectDraw palette.\n");
+      return FALSE;
+    }
+
+  /* Save a pointer to the newly installed colormap */
+  pScreenPriv->pcmapInstalled = pColormap;
+
+  return TRUE;
+}
+
+
+/*
+ * Store the specified colors in the specified colormap
+ */
+
+static Bool
+winStoreColorsShadowDDNL (ColormapPtr pColormap, 
+			  int ndef,
+			  xColorItem *pdefs)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  ColormapPtr		curpmap = pScreenPriv->pcmapInstalled;
+  HRESULT		ddrval = DD_OK;
+  
+  /* Put the X colormap entries into the Windows logical palette */
+  ddrval = IDirectDrawPalette_SetEntries (pCmapPriv->lpDDPalette,
+					  0,
+					  pdefs[0].pixel,
+					  ndef,
+					  pCmapPriv->peColors 
+					  + pdefs[0].pixel);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winStoreColorsShadowDDNL - SetEntries () failed: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+
+  /* Don't install the DirectDraw palette if the colormap is not installed */
+  if (pColormap != curpmap)
+    {
+      return TRUE;
+    }
+
+  if (!winInstallColormapShadowDDNL (pColormap))
+    {
+      ErrorF ("winStoreColorsShadowDDNL - Failed installing colormap\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap initialization procedure
+ */
+
+static Bool
+winCreateColormapShadowDDNL (ColormapPtr pColormap)
+{
+  HRESULT		ddrval = DD_OK;
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  
+  /* Create a DirectDraw palette */
+  ddrval = IDirectDraw4_CreatePalette (pScreenPriv->pdd4,
+				       DDPCAPS_8BIT | DDPCAPS_ALLOW256,
+				       pCmapPriv->peColors,
+				       &pCmapPriv->lpDDPalette,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreateColormapShadowDDNL - CreatePalette failed\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap destruction procedure
+ */
+
+static Bool
+winDestroyColormapShadowDDNL (ColormapPtr pColormap)
+{
+  winScreenPriv(pColormap->pScreen);
+  winCmapPriv(pColormap);
+  HRESULT		ddrval = DD_OK;
+
+  /*
+   * Is colormap to be destroyed the default?
+   *
+   * Non-default colormaps should have had winUninstallColormap
+   * called on them before we get here.  The default colormap
+   * will not have had winUninstallColormap called on it.  Thus,
+   * we need to handle the default colormap in a special way.
+   */
+  if (pColormap->flags & IsDefault)
+    {
+#if CYGDEBUG
+      winDebug ("winDestroyColormapShadowDDNL - Destroying default colormap\n");
+#endif
+      
+      /*
+       * FIXME: Walk the list of all screens, popping the default
+       * palette out of each screen device context.
+       */
+      
+      /* Pop the palette out of the primary surface */
+      ddrval = IDirectDrawSurface4_SetPalette (pScreenPriv->pddsPrimary4,
+					       NULL);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winDestroyColormapShadowDDNL - Failed freeing the "
+		  "default colormap DirectDraw palette.\n");
+	  return FALSE;
+	}
+
+      /* Clear our private installed colormap pointer */
+      pScreenPriv->pcmapInstalled = NULL;
+    }
+  
+  /* Release the palette */
+  IDirectDrawPalette_Release (pCmapPriv->lpDDPalette);
+ 
+  /* Invalidate the colormap privates */
+  pCmapPriv->lpDDPalette = NULL;
+
+  return TRUE;
+}
+
+
+/*
+ * Set pointers to our engine specific functions
+ */
+
+Bool
+winSetEngineFunctionsShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  
+  /* Set our pointers */
+  pScreenPriv->pwinAllocateFB = winAllocateFBShadowDDNL;
+  pScreenPriv->pwinShadowUpdate = winShadowUpdateDDNL;
+  pScreenPriv->pwinCloseScreen = winCloseScreenShadowDDNL;
+  pScreenPriv->pwinInitVisuals = winInitVisualsShadowDDNL;
+  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowDDNL;
+  if (pScreenInfo->fFullScreen)
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
+  else
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
+  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
+  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowDDNL;
+  pScreenPriv->pwinActivateApp = winActivateAppShadowDDNL;
+  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowDDNL;
+  pScreenPriv->pwinRealizeInstalledPalette
+    = winRealizeInstalledPaletteShadowDDNL;
+  pScreenPriv->pwinInstallColormap = winInstallColormapShadowDDNL;
+  pScreenPriv->pwinStoreColors = winStoreColorsShadowDDNL;
+  pScreenPriv->pwinCreateColormap = winCreateColormapShadowDDNL;
+  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowDDNL;
+  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
+  pScreenPriv->pwinCreatePrimarySurface = winCreatePrimarySurfaceShadowDDNL;
+  pScreenPriv->pwinReleasePrimarySurface = winReleasePrimarySurfaceShadowDDNL;
+#ifdef XWIN_MULTIWINDOW
+  pScreenPriv->pwinFinishCreateWindowsWindow
+    = winFinishCreateWindowsWindowDDNL;
+#endif
+
+  return TRUE;
+}
diff --git a/xorg-server/hw/xwin/winwindowswm.c b/xorg-server/hw/xwin/winwindowswm.c
index 34368246a..dffea425f 100644
--- a/xorg-server/hw/xwin/winwindowswm.c
+++ b/xorg-server/hw/xwin/winwindowswm.c
@@ -1,655 +1,647 @@
-/* WindowsWM extension is based on AppleWM extension */
-/**************************************************************************
-
-Copyright (c) 2002 Apple Computer, Inc. All Rights Reserved.
-Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
-
-Permission is hereby granted, free of charge, to any person obtaining a
-copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sub license, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice (including the
-next paragraph) shall be included in all copies or substantial portions
-of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
-IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
-ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-**************************************************************************/
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-#include "misc.h"
-#include "dixstruct.h"
-#include "extnsionst.h"
-#include "colormapst.h"
-#include "cursorstr.h"
-#include "scrnintstr.h"
-#include "servermd.h"
-#include "swaprep.h"
-#define _WINDOWSWM_SERVER_
-#include <X11/extensions/windowswmstr.h>
-#include "protocol-versions.h"
-
-static int WMErrorBase;
-
-static DISPATCH_PROC(ProcWindowsWMDispatch);
-static DISPATCH_PROC(SProcWindowsWMDispatch);
-
-static unsigned char WMReqCode = 0;
-static int WMEventBase = 0;
-
-static RESTYPE ClientType, eventResourceType; /* resource types for event masks */
-static XID eventResource;
-
-/* Currently selected events */
-static unsigned int eventMask = 0;
-
-static int WMFreeClient (pointer data, XID id);
-static int WMFreeEvents (pointer data, XID id);
-static void SNotifyEvent(xWindowsWMNotifyEvent *from, xWindowsWMNotifyEvent *to);
-
-typedef struct _WMEvent *WMEventPtr;
-typedef struct _WMEvent {
-  WMEventPtr      next;
-  ClientPtr	    client;
-  XID		    clientResource;
-  unsigned int    mask;
-} WMEventRec;
-
-static inline BoxRec
-make_box (int x, int y, int w, int h)
-{
-  BoxRec r;
-  r.x1 = x;
-  r.y1 = y;
-  r.x2 = x + w;
-  r.y2 = y + h;
-  return r;
-}
-
-void
-winWindowsWMExtensionInit ()
-{
-  ExtensionEntry* extEntry;
-
-  ClientType = CreateNewResourceType(WMFreeClient, "WMClient");
-  eventResourceType = CreateNewResourceType(WMFreeEvents, "WMEvent");
-  eventResource = FakeClientID(0);
-
-  if (ClientType && eventResourceType &&
-      (extEntry = AddExtension(WINDOWSWMNAME,
-			       WindowsWMNumberEvents,
-			       WindowsWMNumberErrors,
-			       ProcWindowsWMDispatch,
-			       SProcWindowsWMDispatch,
-			       NULL,
-			       StandardMinorOpcode)))
-    {
-      WMReqCode = (unsigned char)extEntry->base;
-      WMErrorBase = extEntry->errorBase;
-      WMEventBase = extEntry->eventBase;
-      EventSwapVector[WMEventBase] = (EventSwapPtr) SNotifyEvent;
-    }
-}
-
-static int
-ProcWindowsWMQueryVersion(register ClientPtr client)
-{
-  xWindowsWMQueryVersionReply rep;
-  register int n;
-
-  REQUEST_SIZE_MATCH(xWindowsWMQueryVersionReq);
-  rep.type = X_Reply;
-  rep.length = 0;
-  rep.sequenceNumber = client->sequence;
-  rep.majorVersion = SERVER_WINDOWSWM_MAJOR_VERSION;
-  rep.minorVersion = SERVER_WINDOWSWM_MINOR_VERSION;
-  rep.patchVersion = SERVER_WINDOWSWM_PATCH_VERSION;
-  if (client->swapped)
-    {
-      swaps(&rep.sequenceNumber, n);
-      swapl(&rep.length, n);
-    }
-  WriteToClient(client, sizeof(xWindowsWMQueryVersionReply), (char *)&rep);
-  return (client->noClientException);
-}
-
-
-/* events */
-
-static inline void
-updateEventMask (WMEventPtr *pHead)
-{
-  WMEventPtr pCur;
-
-  eventMask = 0;
-  for (pCur = *pHead; pCur != NULL; pCur = pCur->next)
-    eventMask |= pCur->mask;
-}
-
-/*ARGSUSED*/
-static int
-WMFreeClient (pointer data, XID id)
-{
-  WMEventPtr   pEvent;
-  WMEventPtr   *pHead, pCur, pPrev;
-
-  pEvent = (WMEventPtr) data;
-  dixLookupResourceByType((pointer) &pHead, eventResource, eventResourceType,
-				NullClient, DixUnknownAccess);
-  if (pHead)
-    {
-      pPrev = 0;
-      for (pCur = *pHead; pCur && pCur != pEvent; pCur=pCur->next)
-	pPrev = pCur;
-      if (pCur)
-	{
-	  if (pPrev)
-	    pPrev->next = pEvent->next;
-	  else
-	    *pHead = pEvent->next;
-	}
-      updateEventMask (pHead);
-    }
-  xfree ((pointer) pEvent);
-  return 1;
-}
-
-/*ARGSUSED*/
-static int
-WMFreeEvents (pointer data, XID id)
-{
-  WMEventPtr   *pHead, pCur, pNext;
-  
-  pHead = (WMEventPtr *) data;
-  for (pCur = *pHead; pCur; pCur = pNext)
-    {
-      pNext = pCur->next;
-      FreeResource (pCur->clientResource, ClientType);
-      xfree ((pointer) pCur);
-    }
-  xfree ((pointer) pHead);
-  eventMask = 0;
-  return 1;
-}
-
-static int
-ProcWindowsWMSelectInput (register ClientPtr client)
-{
-  REQUEST(xWindowsWMSelectInputReq);
-  WMEventPtr		pEvent, pNewEvent, *pHead;
-  XID			clientResource;
-
-  REQUEST_SIZE_MATCH (xWindowsWMSelectInputReq);
-  dixLookupResourceByType((pointer) &pHead, eventResource, eventResourceType, client, DixWriteAccess);
-  if (stuff->mask != 0)
-    {
-      if (pHead)
-	{
-	  /* check for existing entry. */
-	  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
-	    {
-	      if (pEvent->client == client)
-		{
-		  pEvent->mask = stuff->mask;
-		  updateEventMask (pHead);
-		  return Success;
-		}
-	    }
-	}
-      
-      /* build the entry */
-      pNewEvent = (WMEventPtr) xalloc (sizeof (WMEventRec));
-      if (!pNewEvent)
-	return BadAlloc;
-      pNewEvent->next = 0;
-      pNewEvent->client = client;
-      pNewEvent->mask = stuff->mask;
-      /*
-       * add a resource that will be deleted when
-       * the client goes away
-       */
-      clientResource = FakeClientID (client->index);
-      pNewEvent->clientResource = clientResource;
-      if (!AddResource (clientResource, ClientType, (pointer)pNewEvent))
-	return BadAlloc;
-      /*
-       * create a resource to contain a pointer to the list
-       * of clients selecting input.  This must be indirect as
-       * the list may be arbitrarily rearranged which cannot be
-       * done through the resource database.
-       */
-      if (!pHead)
-	{
-	  pHead = (WMEventPtr *) xalloc (sizeof (WMEventPtr));
-	  if (!pHead ||
-	      !AddResource (eventResource, eventResourceType, (pointer)pHead))
-	    {
-	      FreeResource (clientResource, RT_NONE);
-	      return BadAlloc;
-	    }
-	  *pHead = 0;
-	}
-      pNewEvent->next = *pHead;
-      *pHead = pNewEvent;
-      updateEventMask (pHead);
-    }
-  else if (stuff->mask == 0)
-    {
-      /* delete the interest */
-      if (pHead)
-	{
-	  pNewEvent = 0;
-	  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
-	    {
-	      if (pEvent->client == client)
-		break;
-	      pNewEvent = pEvent;
-	    }
-	  if (pEvent)
-	    {
-	      FreeResource (pEvent->clientResource, ClientType);
-	      if (pNewEvent)
-		pNewEvent->next = pEvent->next;
-	      else
-		*pHead = pEvent->next;
-	      xfree (pEvent);
-	      updateEventMask (pHead);
-	    }
-	}
-    }
-  else
-    {
-      client->errorValue = stuff->mask;
-      return BadValue;
-    }
-  return Success;
-}
-
-/*
- * deliver the event
- */
-
-void
-winWindowsWMSendEvent (int type, unsigned int mask, int which, int arg,
-		       Window window, int x, int y, int w, int h)
-{
-  WMEventPtr		*pHead, pEvent;
-  ClientPtr		client;
-  xWindowsWMNotifyEvent se;
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winWindowsWMSendEvent %d %d %d %d,  %d %d - %d %d\n",
-	  type, mask, which, arg, x, y, w, h);
-#endif
-  dixLookupResourceByType((pointer) &pHead, eventResource, eventResourceType,
-				NullClient, DixUnknownAccess);
-  if (!pHead)
-    return;
-  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
-    {
-      client = pEvent->client;
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("winWindowsWMSendEvent - x%08x\n", (int) client);
-#endif
-      if ((pEvent->mask & mask) == 0
-	  || client == serverClient || client->clientGone)
-	{
-	  continue;
-	}
-#if CYGMULTIWINDOW_DEBUG 
-      ErrorF ("winWindowsWMSendEvent - send\n");
-#endif
-      se.type = type + WMEventBase;
-      se.kind = which;
-      se.window = window;
-      se.arg = arg;
-      se.x = x;
-      se.y = y;
-      se.w = w;
-      se.h = h;
-      se.sequenceNumber = client->sequence;
-      se.time = currentTime.milliseconds;
-      WriteEventsToClient (client, 1, (xEvent *) &se);
-    }
-}
-
-/* Safe to call from any thread. */
-unsigned int
-WindowsWMSelectedEvents (void)
-{
-  return eventMask;
-}
-
-
-/* general utility functions */
-
-static int
-ProcWindowsWMDisableUpdate (register ClientPtr client)
-{
-  REQUEST_SIZE_MATCH(xWindowsWMDisableUpdateReq);
-
-  //winDisableUpdate();
-
-  return (client->noClientException);
-}
-
-static int
-ProcWindowsWMReenableUpdate (register ClientPtr client)
-{
-  REQUEST_SIZE_MATCH(xWindowsWMReenableUpdateReq);
-
-  //winEnableUpdate(); 
-
-  return (client->noClientException);
-}
-
-
-/* window functions */
-
-static int
-ProcWindowsWMSetFrontProcess (register ClientPtr client)
-{
-  REQUEST_SIZE_MATCH(xWindowsWMSetFrontProcessReq);
-  
-  //QuartzMessageMainThread(kWindowsSetFrontProcess, NULL, 0);
-  
-  return (client->noClientException);
-}
-
-
-/* frame functions */
-
-static int
-ProcWindowsWMFrameGetRect (register ClientPtr client)
-{
-  xWindowsWMFrameGetRectReply rep;
-  BoxRec ir;
-  RECT rcNew;
-  REQUEST(xWindowsWMFrameGetRectReq);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameGetRect %d %d\n",
-	  (sizeof(xWindowsWMFrameGetRectReq) >> 2), (int) client->req_len);
-#endif
-  
-  REQUEST_SIZE_MATCH(xWindowsWMFrameGetRectReq);
-  rep.type = X_Reply;
-  rep.length = 0;
-  rep.sequenceNumber = client->sequence;
-
-  ir = make_box (stuff->ix, stuff->iy, stuff->iw, stuff->ih);
-
-  if (stuff->frame_rect != 0)
-    {
-      ErrorF ("ProcWindowsWMFrameGetRect - stuff->frame_rect != 0\n");
-      return BadValue;
-    }
-
-  /* Store the origin, height, and width in a rectangle structure */
-  SetRect (&rcNew, stuff->ix, stuff->iy,
-	   stuff->ix + stuff->iw, stuff->iy + stuff->ih);
-    
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameGetRect - %d %d %d %d\n",
-	  stuff->ix, stuff->iy, stuff->ix + stuff->iw, stuff->iy + stuff->ih);
-#endif
-
-  /*
-   * Calculate the required size of the Windows window rectangle,
-   * given the size of the Windows window client area.
-   */
-  AdjustWindowRectEx (&rcNew, stuff->frame_style, FALSE, stuff->frame_style_ex);
-  rep.x = rcNew.left;
-  rep.y = rcNew.top;
-  rep.w = rcNew.right - rcNew.left;
-  rep.h = rcNew.bottom - rcNew.top;
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameGetRect - %d %d %d %d\n",
-	  rep.x, rep.y, rep.w, rep.h);
-#endif
-
-  WriteToClient(client, sizeof(xWindowsWMFrameGetRectReply), (char *)&rep);
-  return (client->noClientException);
-}
-
-
-static int
-ProcWindowsWMFrameDraw (register ClientPtr client)
-{
-  REQUEST(xWindowsWMFrameDrawReq);
-  WindowPtr pWin;
-  win32RootlessWindowPtr pRLWinPriv;
-  RECT rcNew;
-  int nCmdShow, rc;
-  RegionRec newShape;
-  ScreenPtr pScreen;
-
-  REQUEST_SIZE_MATCH (xWindowsWMFrameDrawReq);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameDraw\n");
-#endif
-  rc = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess);
-  if (rc != Success)
-      return rc;
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameDraw - Window found\n");
-#endif
-
-  pRLWinPriv = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, TRUE);
-  if (pRLWinPriv == 0) return BadWindow;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameDraw - HWND 0x%08x 0x%08x 0x%08x\n",
-	  (int) pRLWinPriv->hWnd, (int) stuff->frame_style,
-	  (int) stuff->frame_style_ex);
-  ErrorF ("ProcWindowsWMFrameDraw - %d %d %d %d\n",
-	  stuff->ix, stuff->iy, stuff->iw, stuff->ih);
-#endif
-
-  /* Store the origin, height, and width in a rectangle structure */
-  SetRect (&rcNew, stuff->ix, stuff->iy,
-	   stuff->ix + stuff->iw, stuff->iy + stuff->ih);
-
-  /*
-   * Calculate the required size of the Windows window rectangle,
-   * given the size of the Windows window client area.
-   */
-  AdjustWindowRectEx (&rcNew, stuff->frame_style, FALSE, stuff->frame_style_ex);
-  
-  /* Set the window extended style flags */
-  if (!SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, stuff->frame_style_ex))
-    {
-      return BadValue;
-    }
-
-  /* Set the window standard style flags */
-  if (!SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE, stuff->frame_style))
-    {
-      return BadValue;
-    }
-
-  /* Flush the window style */
-  if (!SetWindowPos (pRLWinPriv->hWnd, NULL,
-		     rcNew.left, rcNew.top,
-		     rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
-		     SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE))
-    {
-      return BadValue;
-    }
-  if (!IsWindowVisible(pRLWinPriv->hWnd))
-    nCmdShow = SW_HIDE;
-  else 
-    nCmdShow = SW_SHOWNA;
-
-  ShowWindow (pRLWinPriv->hWnd, nCmdShow);
-
-  winMWExtWMUpdateIcon (pWin->drawable.id);
-
-  if (wBoundingShape(pWin) != NULL)
-    {
-      pScreen = pWin->drawable.pScreen;
-      /* wBoundingShape is relative to *inner* origin of window.
-	 Translate by borderWidth to get the outside-relative position. */
-      
-      REGION_NULL(pScreen, &newShape);
-      REGION_COPY(pScreen, &newShape, wBoundingShape(pWin));
-      REGION_TRANSLATE(pScreen, &newShape, pWin->borderWidth, pWin->borderWidth);
-      winMWExtWMReshapeFrame (pRLWinPriv, &newShape);
-      REGION_UNINIT(pScreen, &newShape);
-    }
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameDraw - done\n");
-#endif
-
-  return (client->noClientException);
-}
-
-static int
-ProcWindowsWMFrameSetTitle(
-			   register ClientPtr client
-			   )
-{
-  unsigned int title_length, title_max;
-  unsigned char *title_bytes;
-  REQUEST(xWindowsWMFrameSetTitleReq);
-  WindowPtr pWin;
-  win32RootlessWindowPtr pRLWinPriv;
-  int rc;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameSetTitle\n");
-#endif
-
-  REQUEST_AT_LEAST_SIZE(xWindowsWMFrameSetTitleReq);
-
-  rc = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess);
-  if (rc != Success)
-      return rc;
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameSetTitle - Window found\n");
-#endif
-
-  title_length = stuff->title_length;
-  title_max = (stuff->length << 2) - sizeof(xWindowsWMFrameSetTitleReq);
-
-  if (title_max < title_length)
-    return BadValue;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameSetTitle - length is valid\n");
-#endif
-
-  title_bytes = malloc (title_length+1);
-  strncpy (title_bytes, (unsigned char *) &stuff[1], title_length);
-  title_bytes[title_length] = '\0';
-
-  pRLWinPriv = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
-
-  if (pRLWinPriv == 0)
-    {
-      free (title_bytes);
-      return BadWindow;
-    }
-    
-  /* Flush the window style */
-  SetWindowText (pRLWinPriv->hWnd, title_bytes);
-
-  free (title_bytes);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameSetTitle - done\n");
-#endif
-
-  return (client->noClientException);
-}
-
-
-/* dispatch */
-
-static int
-ProcWindowsWMDispatch (register ClientPtr client)
-{
-  REQUEST(xReq);
-
-  switch (stuff->data)
-    {
-    case X_WindowsWMQueryVersion:
-      return ProcWindowsWMQueryVersion(client);
-    }
-
-  if (!LocalClient(client))
-    return WMErrorBase + WindowsWMClientNotLocal;
-
-  switch (stuff->data)
-    {
-    case X_WindowsWMSelectInput:
-      return ProcWindowsWMSelectInput(client);
-    case X_WindowsWMDisableUpdate:
-      return ProcWindowsWMDisableUpdate(client);
-    case X_WindowsWMReenableUpdate:
-      return ProcWindowsWMReenableUpdate(client);
-    case X_WindowsWMSetFrontProcess:
-      return ProcWindowsWMSetFrontProcess(client);
-    case X_WindowsWMFrameGetRect:
-      return ProcWindowsWMFrameGetRect(client);
-    case X_WindowsWMFrameDraw:
-      return ProcWindowsWMFrameDraw(client);
-    case X_WindowsWMFrameSetTitle:
-      return ProcWindowsWMFrameSetTitle(client);
-    default:
-      return BadRequest;
-    }
-}
-
-static void
-SNotifyEvent (xWindowsWMNotifyEvent *from, xWindowsWMNotifyEvent *to)
-{
-  to->type = from->type;
-  to->kind = from->kind;
-  cpswaps (from->sequenceNumber, to->sequenceNumber);
-  cpswapl (from->window, to->window);
-  cpswapl (from->time, to->time);
-  cpswapl (from->arg, to->arg);
-}
-
-static int
-SProcWindowsWMQueryVersion (register ClientPtr client)
-{
-  register int n;
-  REQUEST(xWindowsWMQueryVersionReq);
-  swaps(&stuff->length, n);
-  return ProcWindowsWMQueryVersion(client);
-}
-
-static int
-SProcWindowsWMDispatch (register ClientPtr client)
-{
-  REQUEST(xReq);
-
-  /* It is bound to be non-local when there is byte swapping */
-  if (!LocalClient(client))
-    return WMErrorBase + WindowsWMClientNotLocal;
-
-  /* only local clients are allowed WM access */
-  switch (stuff->data)
-    {
-    case X_WindowsWMQueryVersion:
-      return SProcWindowsWMQueryVersion(client);
-    default:
-      return BadRequest;
-    }
-}
+/* WindowsWM extension is based on AppleWM extension */
+/**************************************************************************
+
+Copyright (c) 2002 Apple Computer, Inc. All Rights Reserved.
+Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sub license, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice (including the
+next paragraph) shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
+IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
+ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+**************************************************************************/
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+#include "misc.h"
+#include "dixstruct.h"
+#include "extnsionst.h"
+#include "colormapst.h"
+#include "cursorstr.h"
+#include "scrnintstr.h"
+#include "servermd.h"
+#include "swaprep.h"
+#define _WINDOWSWM_SERVER_
+#include <X11/extensions/windowswmstr.h>
+#include "protocol-versions.h"
+
+static int WMErrorBase;
+
+static DISPATCH_PROC(ProcWindowsWMDispatch);
+static DISPATCH_PROC(SProcWindowsWMDispatch);
+
+static unsigned char WMReqCode = 0;
+static int WMEventBase = 0;
+
+static RESTYPE ClientType, eventResourceType; /* resource types for event masks */
+static XID eventResource;
+
+/* Currently selected events */
+static unsigned int eventMask = 0;
+
+static int WMFreeClient (pointer data, XID id);
+static int WMFreeEvents (pointer data, XID id);
+static void SNotifyEvent(xWindowsWMNotifyEvent *from, xWindowsWMNotifyEvent *to);
+
+typedef struct _WMEvent *WMEventPtr;
+typedef struct _WMEvent {
+  WMEventPtr      next;
+  ClientPtr	    client;
+  XID		    clientResource;
+  unsigned int    mask;
+} WMEventRec;
+
+static inline BoxRec
+make_box (int x, int y, int w, int h)
+{
+  BoxRec r;
+  r.x1 = x;
+  r.y1 = y;
+  r.x2 = x + w;
+  r.y2 = y + h;
+  return r;
+}
+
+void
+winWindowsWMExtensionInit (void)
+{
+  ExtensionEntry* extEntry;
+
+  ClientType = CreateNewResourceType(WMFreeClient, "WMClient");
+  eventResourceType = CreateNewResourceType(WMFreeEvents, "WMEvent");
+  eventResource = FakeClientID(0);
+
+  if (ClientType && eventResourceType &&
+      (extEntry = AddExtension(WINDOWSWMNAME,
+			       WindowsWMNumberEvents,
+			       WindowsWMNumberErrors,
+			       ProcWindowsWMDispatch,
+			       SProcWindowsWMDispatch,
+			       NULL,
+			       StandardMinorOpcode)))
+    {
+      WMReqCode = (unsigned char)extEntry->base;
+      WMErrorBase = extEntry->errorBase;
+      WMEventBase = extEntry->eventBase;
+      EventSwapVector[WMEventBase] = (EventSwapPtr) SNotifyEvent;
+    }
+}
+
+static int
+ProcWindowsWMQueryVersion(register ClientPtr client)
+{
+  xWindowsWMQueryVersionReply rep;
+  register int n;
+
+  REQUEST_SIZE_MATCH(xWindowsWMQueryVersionReq);
+  rep.type = X_Reply;
+  rep.length = 0;
+  rep.sequenceNumber = client->sequence;
+  rep.majorVersion = SERVER_WINDOWSWM_MAJOR_VERSION;
+  rep.minorVersion = SERVER_WINDOWSWM_MINOR_VERSION;
+  rep.patchVersion = SERVER_WINDOWSWM_PATCH_VERSION;
+  if (client->swapped)
+    {
+      swaps(&rep.sequenceNumber, n);
+      swapl(&rep.length, n);
+    }
+  WriteToClient(client, sizeof(xWindowsWMQueryVersionReply), (char *)&rep);
+  return (client->noClientException);
+}
+
+
+/* events */
+
+static inline void
+updateEventMask (WMEventPtr *pHead)
+{
+  WMEventPtr pCur;
+
+  eventMask = 0;
+  for (pCur = *pHead; pCur != NULL; pCur = pCur->next)
+    eventMask |= pCur->mask;
+}
+
+/*ARGSUSED*/
+static int
+WMFreeClient (pointer data, XID id)
+{
+  WMEventPtr   pEvent;
+  WMEventPtr   *pHead, pCur, pPrev;
+
+  pEvent = (WMEventPtr) data;
+  dixLookupResourceByType((pointer) &pHead, eventResource, eventResourceType,
+				NullClient, DixUnknownAccess);
+  if (pHead)
+    {
+      pPrev = 0;
+      for (pCur = *pHead; pCur && pCur != pEvent; pCur=pCur->next)
+	pPrev = pCur;
+      if (pCur)
+	{
+	  if (pPrev)
+	    pPrev->next = pEvent->next;
+	  else
+	    *pHead = pEvent->next;
+	}
+      updateEventMask (pHead);
+    }
+  xfree ((pointer) pEvent);
+  return 1;
+}
+
+/*ARGSUSED*/
+static int
+WMFreeEvents (pointer data, XID id)
+{
+  WMEventPtr   *pHead, pCur, pNext;
+  
+  pHead = (WMEventPtr *) data;
+  for (pCur = *pHead; pCur; pCur = pNext)
+    {
+      pNext = pCur->next;
+      FreeResource (pCur->clientResource, ClientType);
+      xfree ((pointer) pCur);
+    }
+  xfree ((pointer) pHead);
+  eventMask = 0;
+  return 1;
+}
+
+static int
+ProcWindowsWMSelectInput (register ClientPtr client)
+{
+  REQUEST(xWindowsWMSelectInputReq);
+  WMEventPtr		pEvent, pNewEvent, *pHead;
+  XID			clientResource;
+
+  REQUEST_SIZE_MATCH (xWindowsWMSelectInputReq);
+  dixLookupResourceByType((pointer) &pHead, eventResource, eventResourceType, client, DixWriteAccess);
+  if (stuff->mask != 0)
+    {
+      if (pHead)
+	{
+	  /* check for existing entry. */
+	  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
+	    {
+	      if (pEvent->client == client)
+		{
+		  pEvent->mask = stuff->mask;
+		  updateEventMask (pHead);
+		  return Success;
+		}
+	    }
+	}
+      
+      /* build the entry */
+      pNewEvent = (WMEventPtr) xalloc (sizeof (WMEventRec));
+      if (!pNewEvent)
+	return BadAlloc;
+      pNewEvent->next = 0;
+      pNewEvent->client = client;
+      pNewEvent->mask = stuff->mask;
+      /*
+       * add a resource that will be deleted when
+       * the client goes away
+       */
+      clientResource = FakeClientID (client->index);
+      pNewEvent->clientResource = clientResource;
+      if (!AddResource (clientResource, ClientType, (pointer)pNewEvent))
+	return BadAlloc;
+      /*
+       * create a resource to contain a pointer to the list
+       * of clients selecting input.  This must be indirect as
+       * the list may be arbitrarily rearranged which cannot be
+       * done through the resource database.
+       */
+      if (!pHead)
+	{
+	  pHead = (WMEventPtr *) xalloc (sizeof (WMEventPtr));
+	  if (!pHead ||
+	      !AddResource (eventResource, eventResourceType, (pointer)pHead))
+	    {
+	      FreeResource (clientResource, RT_NONE);
+	      return BadAlloc;
+	    }
+	  *pHead = 0;
+	}
+      pNewEvent->next = *pHead;
+      *pHead = pNewEvent;
+      updateEventMask (pHead);
+    }
+  else if (stuff->mask == 0)
+    {
+      /* delete the interest */
+      if (pHead)
+	{
+	  pNewEvent = 0;
+	  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
+	    {
+	      if (pEvent->client == client)
+		break;
+	      pNewEvent = pEvent;
+	    }
+	  if (pEvent)
+	    {
+	      FreeResource (pEvent->clientResource, ClientType);
+	      if (pNewEvent)
+		pNewEvent->next = pEvent->next;
+	      else
+		*pHead = pEvent->next;
+	      xfree (pEvent);
+	      updateEventMask (pHead);
+	    }
+	}
+    }
+  else
+    {
+      client->errorValue = stuff->mask;
+      return BadValue;
+    }
+  return Success;
+}
+
+/*
+ * deliver the event
+ */
+
+void
+winWindowsWMSendEvent (int type, unsigned int mask, int which, int arg,
+		       Window window, int x, int y, int w, int h)
+{
+  WMEventPtr		*pHead, pEvent;
+  ClientPtr		client;
+  xWindowsWMNotifyEvent se;
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winWindowsWMSendEvent %d %d %d %d,  %d %d - %d %d\n",
+	  type, mask, which, arg, x, y, w, h);
+#endif
+  dixLookupResourceByType((pointer) &pHead, eventResource, eventResourceType,
+				NullClient, DixUnknownAccess);
+  if (!pHead)
+    return;
+  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
+    {
+      client = pEvent->client;
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("winWindowsWMSendEvent - x%08x\n", (int) client);
+#endif
+      if ((pEvent->mask & mask) == 0
+	  || client == serverClient || client->clientGone)
+	{
+	  continue;
+	}
+#if CYGMULTIWINDOW_DEBUG 
+      ErrorF ("winWindowsWMSendEvent - send\n");
+#endif
+      se.type = type + WMEventBase;
+      se.kind = which;
+      se.window = window;
+      se.arg = arg;
+      se.x = x;
+      se.y = y;
+      se.w = w;
+      se.h = h;
+      se.sequenceNumber = client->sequence;
+      se.time = currentTime.milliseconds;
+      WriteEventsToClient (client, 1, (xEvent *) &se);
+    }
+}
+
+/* general utility functions */
+
+static int
+ProcWindowsWMDisableUpdate (register ClientPtr client)
+{
+  REQUEST_SIZE_MATCH(xWindowsWMDisableUpdateReq);
+
+  //winDisableUpdate();
+
+  return (client->noClientException);
+}
+
+static int
+ProcWindowsWMReenableUpdate (register ClientPtr client)
+{
+  REQUEST_SIZE_MATCH(xWindowsWMReenableUpdateReq);
+
+  //winEnableUpdate(); 
+
+  return (client->noClientException);
+}
+
+
+/* window functions */
+
+static int
+ProcWindowsWMSetFrontProcess (register ClientPtr client)
+{
+  REQUEST_SIZE_MATCH(xWindowsWMSetFrontProcessReq);
+  
+  //QuartzMessageMainThread(kWindowsSetFrontProcess, NULL, 0);
+  
+  return (client->noClientException);
+}
+
+
+/* frame functions */
+
+static int
+ProcWindowsWMFrameGetRect (register ClientPtr client)
+{
+  xWindowsWMFrameGetRectReply rep;
+  BoxRec ir;
+  RECT rcNew;
+  REQUEST(xWindowsWMFrameGetRectReq);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameGetRect %d %d\n",
+	  (sizeof(xWindowsWMFrameGetRectReq) >> 2), (int) client->req_len);
+#endif
+  
+  REQUEST_SIZE_MATCH(xWindowsWMFrameGetRectReq);
+  rep.type = X_Reply;
+  rep.length = 0;
+  rep.sequenceNumber = client->sequence;
+
+  ir = make_box (stuff->ix, stuff->iy, stuff->iw, stuff->ih);
+
+  if (stuff->frame_rect != 0)
+    {
+      ErrorF ("ProcWindowsWMFrameGetRect - stuff->frame_rect != 0\n");
+      return BadValue;
+    }
+
+  /* Store the origin, height, and width in a rectangle structure */
+  SetRect (&rcNew, stuff->ix, stuff->iy,
+	   stuff->ix + stuff->iw, stuff->iy + stuff->ih);
+    
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameGetRect - %d %d %d %d\n",
+	  stuff->ix, stuff->iy, stuff->ix + stuff->iw, stuff->iy + stuff->ih);
+#endif
+
+  /*
+   * Calculate the required size of the Windows window rectangle,
+   * given the size of the Windows window client area.
+   */
+  AdjustWindowRectEx (&rcNew, stuff->frame_style, FALSE, stuff->frame_style_ex);
+  rep.x = rcNew.left;
+  rep.y = rcNew.top;
+  rep.w = rcNew.right - rcNew.left;
+  rep.h = rcNew.bottom - rcNew.top;
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameGetRect - %d %d %d %d\n",
+	  rep.x, rep.y, rep.w, rep.h);
+#endif
+
+  WriteToClient(client, sizeof(xWindowsWMFrameGetRectReply), (char *)&rep);
+  return (client->noClientException);
+}
+
+
+static int
+ProcWindowsWMFrameDraw (register ClientPtr client)
+{
+  REQUEST(xWindowsWMFrameDrawReq);
+  WindowPtr pWin;
+  win32RootlessWindowPtr pRLWinPriv;
+  RECT rcNew;
+  int nCmdShow, rc;
+  RegionRec newShape;
+  ScreenPtr pScreen;
+
+  REQUEST_SIZE_MATCH (xWindowsWMFrameDrawReq);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameDraw\n");
+#endif
+  rc = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess);
+  if (rc != Success)
+      return rc;
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameDraw - Window found\n");
+#endif
+
+  pRLWinPriv = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, TRUE);
+  if (pRLWinPriv == 0) return BadWindow;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameDraw - HWND 0x%08x 0x%08x 0x%08x\n",
+	  (int) pRLWinPriv->hWnd, (int) stuff->frame_style,
+	  (int) stuff->frame_style_ex);
+  ErrorF ("ProcWindowsWMFrameDraw - %d %d %d %d\n",
+	  stuff->ix, stuff->iy, stuff->iw, stuff->ih);
+#endif
+
+  /* Store the origin, height, and width in a rectangle structure */
+  SetRect (&rcNew, stuff->ix, stuff->iy,
+	   stuff->ix + stuff->iw, stuff->iy + stuff->ih);
+
+  /*
+   * Calculate the required size of the Windows window rectangle,
+   * given the size of the Windows window client area.
+   */
+  AdjustWindowRectEx (&rcNew, stuff->frame_style, FALSE, stuff->frame_style_ex);
+  
+  /* Set the window extended style flags */
+  if (!SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, stuff->frame_style_ex))
+    {
+      return BadValue;
+    }
+
+  /* Set the window standard style flags */
+  if (!SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE, stuff->frame_style))
+    {
+      return BadValue;
+    }
+
+  /* Flush the window style */
+  if (!SetWindowPos (pRLWinPriv->hWnd, NULL,
+		     rcNew.left, rcNew.top,
+		     rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
+		     SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE))
+    {
+      return BadValue;
+    }
+  if (!IsWindowVisible(pRLWinPriv->hWnd))
+    nCmdShow = SW_HIDE;
+  else 
+    nCmdShow = SW_SHOWNA;
+
+  ShowWindow (pRLWinPriv->hWnd, nCmdShow);
+
+  winMWExtWMUpdateIcon (pWin->drawable.id);
+
+  if (wBoundingShape(pWin) != NULL)
+    {
+      pScreen = pWin->drawable.pScreen;
+      /* wBoundingShape is relative to *inner* origin of window.
+	 Translate by borderWidth to get the outside-relative position. */
+      
+      REGION_NULL(pScreen, &newShape);
+      REGION_COPY(pScreen, &newShape, wBoundingShape(pWin));
+      REGION_TRANSLATE(pScreen, &newShape, pWin->borderWidth, pWin->borderWidth);
+      winMWExtWMReshapeFrame (pRLWinPriv, &newShape);
+      REGION_UNINIT(pScreen, &newShape);
+    }
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameDraw - done\n");
+#endif
+
+  return (client->noClientException);
+}
+
+static int
+ProcWindowsWMFrameSetTitle(
+			   register ClientPtr client
+			   )
+{
+  unsigned int title_length, title_max;
+  unsigned char *title_bytes;
+  REQUEST(xWindowsWMFrameSetTitleReq);
+  WindowPtr pWin;
+  win32RootlessWindowPtr pRLWinPriv;
+  int rc;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameSetTitle\n");
+#endif
+
+  REQUEST_AT_LEAST_SIZE(xWindowsWMFrameSetTitleReq);
+
+  rc = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess);
+  if (rc != Success)
+      return rc;
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameSetTitle - Window found\n");
+#endif
+
+  title_length = stuff->title_length;
+  title_max = (stuff->length << 2) - sizeof(xWindowsWMFrameSetTitleReq);
+
+  if (title_max < title_length)
+    return BadValue;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameSetTitle - length is valid\n");
+#endif
+
+  title_bytes = malloc (title_length+1);
+  strncpy (title_bytes, (unsigned char *) &stuff[1], title_length);
+  title_bytes[title_length] = '\0';
+
+  pRLWinPriv = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
+
+  if (pRLWinPriv == 0)
+    {
+      free (title_bytes);
+      return BadWindow;
+    }
+    
+  /* Flush the window style */
+  SetWindowText (pRLWinPriv->hWnd, title_bytes);
+
+  free (title_bytes);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameSetTitle - done\n");
+#endif
+
+  return (client->noClientException);
+}
+
+
+/* dispatch */
+
+static int
+ProcWindowsWMDispatch (register ClientPtr client)
+{
+  REQUEST(xReq);
+
+  switch (stuff->data)
+    {
+    case X_WindowsWMQueryVersion:
+      return ProcWindowsWMQueryVersion(client);
+    }
+
+  if (!LocalClient(client))
+    return WMErrorBase + WindowsWMClientNotLocal;
+
+  switch (stuff->data)
+    {
+    case X_WindowsWMSelectInput:
+      return ProcWindowsWMSelectInput(client);
+    case X_WindowsWMDisableUpdate:
+      return ProcWindowsWMDisableUpdate(client);
+    case X_WindowsWMReenableUpdate:
+      return ProcWindowsWMReenableUpdate(client);
+    case X_WindowsWMSetFrontProcess:
+      return ProcWindowsWMSetFrontProcess(client);
+    case X_WindowsWMFrameGetRect:
+      return ProcWindowsWMFrameGetRect(client);
+    case X_WindowsWMFrameDraw:
+      return ProcWindowsWMFrameDraw(client);
+    case X_WindowsWMFrameSetTitle:
+      return ProcWindowsWMFrameSetTitle(client);
+    default:
+      return BadRequest;
+    }
+}
+
+static void
+SNotifyEvent (xWindowsWMNotifyEvent *from, xWindowsWMNotifyEvent *to)
+{
+  to->type = from->type;
+  to->kind = from->kind;
+  cpswaps (from->sequenceNumber, to->sequenceNumber);
+  cpswapl (from->window, to->window);
+  cpswapl (from->time, to->time);
+  cpswapl (from->arg, to->arg);
+}
+
+static int
+SProcWindowsWMQueryVersion (register ClientPtr client)
+{
+  register int n;
+  REQUEST(xWindowsWMQueryVersionReq);
+  swaps(&stuff->length, n);
+  return ProcWindowsWMQueryVersion(client);
+}
+
+static int
+SProcWindowsWMDispatch (register ClientPtr client)
+{
+  REQUEST(xReq);
+
+  /* It is bound to be non-local when there is byte swapping */
+  if (!LocalClient(client))
+    return WMErrorBase + WindowsWMClientNotLocal;
+
+  /* only local clients are allowed WM access */
+  switch (stuff->data)
+    {
+    case X_WindowsWMQueryVersion:
+      return SProcWindowsWMQueryVersion(client);
+    default:
+      return BadRequest;
+    }
+}
-- 
cgit v1.2.3