xserver: Branch 'transform-proposal' - 243 commits

Keith Packard keithp at kemper.freedesktop.org
Sun May 4 22:26:21 PDT 2008


 .gitignore                                                |    6 
 GL/Makefile.am                                            |    7 
 GL/apple/Makefile.am                                      |   24 
 GL/apple/aglGlx.c                                         | 1354 --------
 GL/apple/indirect.c                                       | 1938 ------------
 GL/glx/Makefile.am                                        |    7 
 GL/glx/glxcmds.c                                          |   58 
 GL/glx/glxcontext.h                                       |    6 
 GL/glx/glxdrawable.h                                      |    2 
 GL/glx/glxdri.c                                           |  259 -
 GL/glx/glxdri2.c                                          |  423 +-
 GL/glx/glxext.c                                           |    2 
 GL/glx/glxglcore.c                                        |  138 
 GL/glx/glxscreens.c                                       |   66 
 GL/glx/glxscreens.h                                       |   88 
 GL/glx/glxutil.c                                          |   63 
 GL/glx/glxutil.h                                          |    2 
 GL/mesa/.gitignore                                        |   32 
 GL/mesa/Makefile.am                                       |   18 
 GL/mesa/X/Makefile.am                                     |   27 
 GL/mesa/glapi/Makefile.am                                 |   20 
 GL/mesa/main/Makefile.am                                  |   86 
 GL/mesa/math/Makefile.am                                  |   27 
 GL/mesa/shader/Makefile.am                                |   39 
 GL/mesa/shader/grammar/Makefile.am                        |   20 
 GL/mesa/shader/slang/Makefile.am                          |   41 
 GL/mesa/swrast/Makefile.am                                |   50 
 GL/mesa/swrast_setup/Makefile.am                          |   20 
 GL/mesa/tnl/Makefile.am                                   |   37 
 GL/mesa/vbo/Makefile.am                                   |   35 
 GL/symlink-mesa.sh                                        |  164 -
 Makefile.am                                               |   15 
 Xext/EVI.c                                                |  200 -
 Xext/EVIstruct.h                                          |   58 
 Xext/Makefile.am                                          |   23 
 Xext/appgroup.c                                           |  775 ----
 Xext/appgroup.h                                           |   67 
 Xext/cup.c                                                |  342 --
 Xext/dpms.c                                               |    7 
 Xext/mitmisc.c                                            |  155 
 Xext/sampleEVI.c                                          |  123 
 Xext/security.c                                           |    8 
 Xext/xevie.c                                              |  122 
 Xext/xres.c                                               |    2 
 Xext/xselinux.c                                           |   96 
 Xext/xselinux.h                                           |    1 
 Xi/exevents.c                                             |    2 
 acinclude.m4                                              |  172 -
 cfb/Makefile.am                                           |   21 
 cfb/Makefile.am.inc                                       |  153 
 cfb/cfb.h                                                 | 1268 -------
 cfb/cfb16.h                                               |   93 
 cfb/cfb24.h                                               |   97 
 cfb/cfb32.h                                               |   93 
 cfb/cfb8bit.c                                             |  469 --
 cfb/cfb8bit.h                                             | 1570 ---------
 cfb/cfb8line.c                                            | 1503 ---------
 cfb/cfballpriv.c                                          |   70 
 cfb/cfbbitblt.c                                           | 1455 ---------
 cfb/cfbblt.c                                              |  933 -----
 cfb/cfbbres.c                                             |  340 --
 cfb/cfbbresd.c                                            |  404 --
 cfb/cfbcmap.c                                             |  119 
 cfb/cfbcppl.c                                             |  486 ---
 cfb/cfbfillarc.c                                          |  374 --
 cfb/cfbfillrct.c                                          |  305 -
 cfb/cfbfillsp.c                                           | 1004 ------
 cfb/cfbgc.c                                               |  799 ----
 cfb/cfbgetsp.c                                            |  213 -
 cfb/cfbglblt8.c                                           |  477 --
 cfb/cfbhrzvert.c                                          |  554 ---
 cfb/cfbigblt8.c                                           |  106 
 cfb/cfbimage.c                                            |  206 -
 cfb/cfbline.c                                             |  756 ----
 cfb/cfbmap.h                                              |  210 -
 cfb/cfbmskbits.c                                          | 1400 --------
 cfb/cfbmskbits.h                                          |  854 -----
 cfb/cfbpixmap.c                                           |  375 --
 cfb/cfbply1rct.c                                          |  363 --
 cfb/cfbpolypnt.c                                          |  202 -
 cfb/cfbpush8.c                                            |  184 -
 cfb/cfbrctstp8.c                                          |  593 ---
 cfb/cfbrrop.c                                             |  227 -
 cfb/cfbrrop.h                                             |  343 --
 cfb/cfbscrinit.c                                          |  223 -
 cfb/cfbsetsp.c                                            |  316 -
 cfb/cfbsolid.c                                            | 1365 --------
 cfb/cfbteblt8.c                                           |  589 ---
 cfb/cfbtegblt.c                                           |  218 -
 cfb/cfbtile32.c                                           |  517 ---
 cfb/cfbtileodd.c                                          | 1245 -------
 cfb/cfbunmap.h                                            |  161 -
 cfb/cfbwindow.c                                           |  160 
 cfb/cfbzerarc.c                                           |  322 --
 cfb/stip68kgnu.h                                          |  121 
 cfb/stipmips.s                                            |  281 -
 cfb/stipsparc.s                                           |  290 -
 cfb/stipsprc32.s                                          |  291 -
 cfb32/Makefile.am                                         |    9 
 composite/Makefile.am                                     |    1 
 composite/compext.c                                       |  193 -
 composite/compinit.c                                      |   13 
 composite/compint.h                                       |   24 
 composite/compoverlay.c                                   |  159 
 config/hal.c                                              |  194 -
 config/x11-input.fdi                                      |   62 
 configure.ac                                              |  225 -
 dix/Makefile.am                                           |   14 
 dix/devices.c                                             |    6 
 dix/dispatch.c                                            |    9 
 dix/dixutils.c                                            |    3 
 dix/events.c                                              |    7 
 dix/getevents.c                                           |   14 
 dix/main.c                                                |   19 
 dix/window.c                                              |   70 
 exa/Makefile.am                                           |    1 
 exa/exa.c                                                 |  133 
 exa/exa.h                                                 |    4 
 exa/exa_accel.c                                           |   32 
 exa/exa_glyphs.c                                          |  897 +++++
 exa/exa_offscreen.c                                       |  161 -
 exa/exa_priv.h                                            |   60 
 exa/exa_render.c                                          |  238 +
 fb/Makefile.am                                            |    6 
 fb/fb.h                                                   |    2 
 fb/fbpseudocolor.c                                        | 2248 --------------
 fb/fbpseudocolor.h                                        |   20 
 fb/wfbrename.h                                            |    8 
 hw/dmx/dmx-config.h                                       |    2 
 hw/dmx/dmxextension.c                                     |    1 
 hw/kdrive/Makefile.am                                     |    4 
 hw/kdrive/ati/Makefile.am                                 |    4 
 hw/kdrive/chips/Makefile.am                               |    4 
 hw/kdrive/ephyr/GL/internal/dri_interface.h               |  517 ---
 hw/kdrive/ephyr/Makefile.am                               |  107 
 hw/kdrive/ephyr/XF86dri.c                                 |    7 
 hw/kdrive/ephyr/ephyr.c                                   |   31 
 hw/kdrive/ephyr/ephyr.h                                   |    1 
 hw/kdrive/ephyr/ephyr_draw.c                              |    1 
 hw/kdrive/ephyr/ephyrdri.c                                |    7 
 hw/kdrive/ephyr/ephyrdriext.c                             |    4 
 hw/kdrive/ephyr/ephyrglxext.c                             |    5 
 hw/kdrive/ephyr/ephyrhostglx.c                            |    4 
 hw/kdrive/ephyr/ephyrinit.c                               |   19 
 hw/kdrive/ephyr/ephyrlog.h                                |    4 
 hw/kdrive/ephyr/hostx.c                                   |   39 
 hw/kdrive/ephyr/hostx.h                                   |    7 
 hw/kdrive/ephyr/xf86dri.h                                 |  120 
 hw/kdrive/epson/Makefile.am                               |    4 
 hw/kdrive/fake/Makefile.am                                |    4 
 hw/kdrive/fbdev/Makefile.am                               |    4 
 hw/kdrive/fbdev/fbdev.c                                   |   26 
 hw/kdrive/i810/Makefile.am                                |    4 
 hw/kdrive/linux/keyboard.c                                |   26 
 hw/kdrive/linux/tslib.c                                   |    4 
 hw/kdrive/mach64/Makefile.am                              |    4 
 hw/kdrive/mga/Makefile.am                                 |    4 
 hw/kdrive/neomagic/Makefile.am                            |    4 
 hw/kdrive/nvidia/Makefile.am                              |    4 
 hw/kdrive/pm2/Makefile.am                                 |    4 
 hw/kdrive/r128/Makefile.am                                |    4 
 hw/kdrive/sdl/Makefile.am                                 |    4 
 hw/kdrive/sis300/Makefile.am                              |    4 
 hw/kdrive/smi/Makefile.am                                 |    4 
 hw/kdrive/src/kinput.c                                    |    4 
 hw/kdrive/vesa/Makefile.am                                |    4 
 hw/kdrive/via/Makefile.am                                 |    4 
 hw/xfree86/Makefile.am                                    |    8 
 hw/xfree86/common/compiler.h                              |    6 
 hw/xfree86/common/xf86.h                                  |    1 
 hw/xfree86/common/xf86AutoConfig.c                        |  154 
 hw/xfree86/common/xf86Bus.c                               |    4 
 hw/xfree86/common/xf86Config.c                            |   40 
 hw/xfree86/common/xf86Init.c                              |   60 
 hw/xfree86/common/xf86Privstr.h                           |    3 
 hw/xfree86/common/xf86Xinput.c                            |   30 
 hw/xfree86/ddc/xf86DDC.c                                  |  241 -
 hw/xfree86/ddc/xf86DDC.h                                  |    2 
 hw/xfree86/dixmods/GLcoremodule.c                         |   63 
 hw/xfree86/dixmods/Makefile.am                            |   25 
 hw/xfree86/dixmods/cfb32module.c                          |   57 
 hw/xfree86/dixmods/cfbmodule.c                            |   57 
 hw/xfree86/dixmods/extmod/Makefile.am                     |    1 
 hw/xfree86/dixmods/extmod/modinit.c                       |   50 
 hw/xfree86/dixmods/extmod/modinit.h                       |   26 
 hw/xfree86/dixmods/glxmodule.c                            |   37 
 hw/xfree86/doc/man/xorg.conf.man.pre                      |    8 
 hw/xfree86/dri/Makefile.am                                |    2 
 hw/xfree86/dri/dri.c                                      |    2 
 hw/xfree86/dri2/Makefile.am                               |    5 
 hw/xfree86/dri2/dri2.c                                    |  107 
 hw/xfree86/dri2/dri2.h                                    |   16 
 hw/xfree86/dri2/dri2ext.c                                 |  361 ++
 hw/xfree86/exa/examodule.c                                |   13 
 hw/xfree86/int10/helper_exec.c                            |    2 
 hw/xfree86/loader/dixsym.c                                |   15 
 hw/xfree86/loader/loader.c                                |    2 
 hw/xfree86/loader/xf86sym.c                               |    3 
 hw/xfree86/modes/xf86Crtc.h                               |    6 
 hw/xfree86/modes/xf86Cursors.c                            |    3 
 hw/xfree86/modes/xf86EdidModes.c                          |   25 
 hw/xfree86/modes/xf86Rotate.c                             |   33 
 hw/xfree86/os-support/bsd/Makefile.am                     |    1 
 hw/xfree86/os-support/bsd/bsdResource.c                   |    2 
 hw/xfree86/os-support/bsd/bsd_jstk.c                      |  183 -
 hw/xfree86/os-support/bsd/i386_video.c                    |    8 
 hw/xfree86/os-support/bus/Pci.h                           |    8 
 hw/xfree86/os-support/linux/Makefile.am                   |    1 
 hw/xfree86/os-support/linux/lnxResource.c                 |    1 
 hw/xfree86/os-support/linux/lnx_jstk.c                    |  180 -
 hw/xfree86/os-support/linux/lnx_video.c                   |    4 
 hw/xfree86/utils/xorgcfg/expert.c                         |   50 
 hw/xfree86/utils/xorgcfg/loadmod.c                        |    4 
 hw/xfree86/x86emu/prim_ops.c                              |    2 
 hw/xfree86/x86emu/x86emu/prim_x86_gcc.h                   |    2 
 hw/xfree86/x86emu/x86emu/types.h                          |    2 
 hw/xfree86/xaa/xaaInitAccel.c                             |   57 
 hw/xfree86/xf8_32bpp/Makefile.am                          |   37 
 hw/xfree86/xf8_32bpp/cfb8_32.h                            |  191 -
 hw/xfree86/xf8_32bpp/cfb8_32module.c                      |   39 
 hw/xfree86/xf8_32bpp/cfbcpyarea.c                         |  549 ---
 hw/xfree86/xf8_32bpp/cfbcpyplane.c                        |   41 
 hw/xfree86/xf8_32bpp/cfbgc.c                              |  646 ----
 hw/xfree86/xf8_32bpp/cfbgcmisc.c                          |  150 
 hw/xfree86/xf8_32bpp/cfbgcunder.c                         |  620 ---
 hw/xfree86/xf8_32bpp/cfbimage.c                           |  174 -
 hw/xfree86/xf8_32bpp/cfbpntwin.c                          |   51 
 hw/xfree86/xf8_32bpp/cfbscrinit.c                         |  311 -
 hw/xfree86/xf8_32bpp/cfbwindow.c                          |  116 
 hw/xfree86/xf8_32bpp/xf86overlay.c                        | 1179 -------
 hw/xgl/egl/kinput.c                                       |    4 
 hw/xnest/Args.c                                           |    5 
 hw/xprint/Makefile.am                                     |    3 
 hw/xprint/ps/psout.h                                      |    2 
 hw/xquartz/GL/Makefile.am                                 |   13 
 hw/xquartz/GL/indirect.c                                  | 1940 ++++++++++++
 hw/xquartz/Makefile.am                                    |   17 
 hw/xquartz/X11Application.h                               |    9 
 hw/xquartz/X11Application.m                               |  567 +--
 hw/xquartz/X11Controller.h                                |   12 
 hw/xquartz/X11Controller.m                                |  173 -
 hw/xquartz/applewm.c                                      |    2 
 hw/xquartz/bundle/English.lproj/Localizable.strings       |binary
 hw/xquartz/bundle/English.lproj/main.nib/designable.nib   |  502 ++-
 hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib |binary
 hw/xquartz/darwin.c                                       |  117 
 hw/xquartz/darwin.h                                       |   44 
 hw/xquartz/darwinEvents.c                                 |  619 ++-
 hw/xquartz/darwinEvents.h                                 |   43 
 hw/xquartz/darwinKeyboard.c                               | 1009 ------
 hw/xquartz/darwinKeyboard.h                               |   45 
 hw/xquartz/darwinXinput.c                                 |  200 -
 hw/xquartz/pseudoramiX.c                                  |   37 
 hw/xquartz/quartz.c                                       |  162 -
 hw/xquartz/quartz.h                                       |    6 
 hw/xquartz/quartzAudio.c                                  |    2 
 hw/xquartz/quartzCocoa.m                                  |    9 
 hw/xquartz/quartzCommon.h                                 |   25 
 hw/xquartz/quartzCursor.c                                 |  646 ----
 hw/xquartz/quartzCursor.h                                 |   42 
 hw/xquartz/quartzForeground.c                             |    2 
 hw/xquartz/quartzKeyboard.c                               | 1010 ++++++
 hw/xquartz/quartzKeyboard.h                               |   16 
 hw/xquartz/quartzPasteboard.c                             |   10 
 hw/xquartz/quartzPasteboard.h                             |    4 
 hw/xquartz/quartzStartup.c                                |   99 
 hw/xquartz/sanitizedCarbon.h                              |   32 
 hw/xquartz/sanitizedCocoa.h                               |   27 
 hw/xquartz/threadSafety.c                                 |   70 
 hw/xquartz/threadSafety.h                                 |   56 
 hw/xquartz/xpr/Makefile.am                                |   29 
 hw/xquartz/xpr/dri.h                                      |    2 
 hw/xquartz/xpr/xpr.h                                      |    3 
 hw/xquartz/xpr/xprAppleWM.c                               |    2 
 hw/xquartz/xpr/xprCursor.c                                |    8 
 hw/xquartz/xpr/xprEvent.c                                 |   91 
 hw/xquartz/xpr/xprEvent.h                                 |   34 
 hw/xquartz/xpr/xprFrame.c                                 |   43 
 hw/xquartz/xpr/xprScreen.c                                |   85 
 include/dix-config.h.in                                   |   20 
 include/dixstruct.h                                       |    4 
 include/globals.h                                         |   26 
 include/servermd.h                                        |   32 
 include/windowstr.h                                       |    3 
 include/xkbsrv.h                                          |   16 
 include/xorg-server.h.in                                  |    6 
 mi/micoord.h                                              |    2 
 mi/miinitext.c                                            |   63 
 mi/mivaltree.c                                            |    4 
 miext/rootless/Makefile.am                                |    2 
 miext/rootless/README.txt                                 |    4 
 miext/rootless/accel/Makefile.am                          |   15 
 miext/rootless/accel/rlAccel.c                            |  147 
 miext/rootless/accel/rlAccel.h                            |  140 
 miext/rootless/accel/rlBlt.c                              |  408 --
 miext/rootless/accel/rlCopy.c                             |  106 
 miext/rootless/accel/rlFill.c                             |  220 -
 miext/rootless/accel/rlFillRect.c                         |  117 
 miext/rootless/accel/rlFillSpans.c                        |  105 
 miext/rootless/accel/rlGlyph.c                            |  169 -
 miext/rootless/accel/rlSolid.c                            |  111 
 miext/rootless/rootlessConfig.h                           |    3 
 miext/rootless/rootlessGC.c                               |    8 
 miext/rootless/rootlessWindow.c                           |   72 
 miext/rootless/rootlessWindow.h                           |    4 
 miext/rootless/safeAlpha/Makefile.am                      |    7 
 miext/rootless/safeAlpha/safeAlpha.h                      |   42 
 miext/rootless/safeAlpha/safeAlphaPicture.c               |  211 -
 os/WaitFor.c                                              |    6 
 os/connection.c                                           |    3 
 os/utils.c                                                |   19 
 render/matrix.c                                           |    7 
 render/picturestr.h                                       |    2 
 xkb/ddxLoad.c                                             |    6 
 xkb/xkbActions.c                                          |   11 
 xorg-server.pc.in                                         |    2 
 316 files changed, 9288 insertions(+), 44575 deletions(-)

New commits:
commit 33e5a176e62a0114cb8cca9447798c6d6b6665ed
Merge: e48f6bc... efa65a0...
Author: Keith Packard <keithp at keithp.com>
Date:   Sun May 4 22:24:56 2008 -0700

    Merge commit 'origin/master' into transform-proposal-old
    
    Conflicts:
    
    	configure.ac
    	exa/exa.c

diff --cc configure.ac
index 07a334c,f695551..8abebfe
--- a/configure.ac
+++ b/configure.ac
@@@ -1971,13 -1938,10 +1938,10 @@@ if test "$KDRIVE" = yes; the
  	    ;;
      esac
      KDRIVE_STUB_LIB='$(top_builddir)/hw/kdrive/src/libkdrivestubs.a'
-     KDRIVE_LOCAL_LIBS="$TSLIB_LIBS $DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
+     KDRIVE_LOCAL_LIBS="$DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
      KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $FB_LIB $MI_LIB $KDRIVE_PURE_LIBS"
 -    KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
 +    KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB $XEXT_LIB"
-     KDRIVE_LIBS="$KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
- 
-     # check if we can build Xephyr
-     PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
+     KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS $GLX_SYS_LIBS"
  
      AC_SUBST([XEPHYR_LIBS])
      AC_SUBST([XEPHYR_INCS])
diff --cc exa/exa.c
index baa9e94,809fb4b..0852334
--- a/exa/exa.c
+++ b/exa/exa.c
@@@ -699,8 -754,9 +754,10 @@@ exaCloseScreen(int i, ScreenPtr pScreen
  #ifdef RENDER
      if (ps) {
  	ps->Composite = pExaScr->SavedComposite;
+ 	ps->Glyphs = pExaScr->SavedGlyphs;
  	ps->Trapezoids = pExaScr->SavedTrapezoids;
 +	ps->AddTraps = pExaScr->SavedAddTraps;
+ 	ps->Triangles = pExaScr->SavedTriangles;
      }
  #endif
  
diff --cc hw/xfree86/modes/xf86Crtc.h
index 6d7a9b1,83b1f13..4d4d967
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@@ -677,9 -662,15 +677,15 @@@ xf86CrtcSetMode (xf86CrtcPtr crtc, Disp
   * Assign crtc rotation during mode set
   */
  Bool
 -xf86CrtcRotate (xf86CrtcPtr crtc, DisplayModePtr mode, Rotation rotation);
 +xf86CrtcRotate (xf86CrtcPtr crtc);
  
  /*
+  * free shadow memory allocated for all crtcs
+  */
+ void
+ xf86RotateFreeShadow(ScrnInfoPtr pScrn);
+ 
+ /*
   * Clean up rotation during CloseScreen
   */
  void
commit efa65a0317e12c9ad34fa00fe90bf5eae9fa2670
Author: Keith Packard <keithp at keithp.com>
Date:   Sun May 4 21:52:58 2008 -0700

    Rework composite overlay window code to fix several resource management bugs.
    
    The composite overlay window code had several misunderstandings of the
    workings of the X server, in particular error handling paths would often
    double-free objects. Clean all of this up by using resource destruction as
    the sole mechanism for freeing resource-based objects.

diff --git a/composite/Makefile.am b/composite/Makefile.am
index 21504e6..d7bead1 100644
--- a/composite/Makefile.am
+++ b/composite/Makefile.am
@@ -7,4 +7,5 @@ libcomposite_la_SOURCES = 	\
 	compext.c		\
 	compint.h		\
 	compinit.c		\
+	compoverlay.c		\
 	compwindow.c		
diff --git a/composite/compext.c b/composite/compext.c
index b3433f7..e720f6c 100644
--- a/composite/compext.c
+++ b/composite/compext.c
@@ -54,10 +54,7 @@ static CARD8	CompositeReqCode;
 static DevPrivateKey CompositeClientPrivateKey = &CompositeClientPrivateKey;
 RESTYPE		CompositeClientWindowType;
 RESTYPE		CompositeClientSubwindowsType;
-static RESTYPE	CompositeClientOverlayType;
-
-static void deleteCompOverlayClient (CompOverlayClientPtr pOcToDel, 
-				     ScreenPtr pScreen);
+RESTYPE		CompositeClientOverlayType;
 
 typedef struct _CompositeClient {
     int	    major_version;
@@ -107,19 +104,8 @@ static int
 FreeCompositeClientOverlay (pointer value, XID ccwid)
 {
     CompOverlayClientPtr pOc = (CompOverlayClientPtr) value;
-    ScreenPtr pScreen = pOc->pScreen;
-    CompScreenPtr cs;
-
-    deleteCompOverlayClient(pOc, pScreen);
-
-    /* Unmap overlay window when there are no more clients using it */
-    cs = GetCompScreen(pScreen);
-    if (cs->pOverlayClients == NULL) {
-	if (cs->pOverlayWin != NULL) {
-	    UnmapWindow(cs->pOverlayWin, FALSE);
-	}
-    }
 
+    compFreeOverlayClient (pOc);
     return Success;
 }
 
@@ -304,137 +290,6 @@ ProcCompositeNameWindowPixmap (ClientPtr client)
 }
 
 
-/*
- * Routines for manipulating the per-screen overlay clients list.
- * This list indicates which clients have called GetOverlayWindow
- * for this screen.
- */
-
-/* Return the screen's overlay client list element for the given client */
-static CompOverlayClientPtr
-findCompOverlayClient (ClientPtr pClient, ScreenPtr pScreen) 
-{
-    CompScreenPtr    cs = GetCompScreen(pScreen);
-    CompOverlayClientPtr pOc;
-
-    for (pOc = cs->pOverlayClients; pOc != NULL; pOc = pOc->pNext) {
-	if (pOc->pClient == pClient) {
-	    return pOc;
-	}
-    }
-
-    return NULL;           
-}
-
-static int
-createCompOverlayClient (ClientPtr pClient, ScreenPtr pScreen)
-{
-    CompScreenPtr    cs = GetCompScreen(pScreen);
-    CompOverlayClientPtr pOc;
-
-    pOc = (CompOverlayClientPtr) xalloc(sizeof(CompOverlayClientRec));
-    if (pOc == NULL) {
-	return BadAlloc;
-    }
-    pOc->pClient = pClient;
-    pOc->pScreen = pScreen;
-    pOc->resource = FakeClientID(pClient->index);
-    pOc->pNext = cs->pOverlayClients;
-    cs->pOverlayClients = pOc;
-
-    /* 
-     * Create a resource for this element so it can be deleted
-     * when the client goes away.
-     */
-    if (!AddResource (pOc->resource, CompositeClientOverlayType, 
-		      (pointer) pOc)) {
-	xfree(pOc);
-	return BadAlloc;
-    }
-
-    return Success;
-}
-
-/* 
- * Delete the given overlay client list element from its screen list.
- */
-static void
-deleteCompOverlayClient (CompOverlayClientPtr pOcToDel, ScreenPtr pScreen)
-{
-    CompScreenPtr    cs = GetCompScreen(pScreen);
-    CompOverlayClientPtr pOc, pNext;
-    CompOverlayClientPtr pOcLast = NULL;
-
-    pOc = cs->pOverlayClients;
-    while (pOc != NULL) {
-	pNext = pOc->pNext;
-	if (pOc == pOcToDel) {
-	    xfree(pOc);
-	    if (pOcLast == NULL) {
-		cs->pOverlayClients = pNext;
-	    } else {
-		pOcLast->pNext = pNext;
-	    }
-	    break;
-	}
-	pOcLast = pOc;
-	pOc = pNext;
-    }
-}
-
-/* 
- * Delete all the hide-counts list elements for this screen.
- */
-void
-deleteCompOverlayClientsForScreen (ScreenPtr pScreen)
-{
-    CompScreenPtr    cs = GetCompScreen(pScreen);
-    CompOverlayClientPtr pOc, pTmp;
-
-    pOc = cs->pOverlayClients;
-    while (pOc != NULL) {
-	pTmp = pOc->pNext;
-	FreeResource(pOc->resource, 0);
-	pOc = pTmp;
-    }
-    cs->pOverlayClients = NULL;
-}
-
-/* 
-** If necessary, create the overlay window. And map it 
-** Note: I found it excessively difficult to destroy this window
-** during compCloseScreen; DeleteWindow can't be called because
-** the input devices are already shut down. So we are going to 
-** just allocate an overlay window once per screen per X server
-** invocation.
-*/
-
-static WindowPtr
-createOverlayWindow (ScreenPtr pScreen)
-{
-    int wid = FakeClientID(0);
-    WindowPtr pWin;
-    XID overrideRedirect = TRUE;
-    int result;
-
-    pWin = CreateWindow (
-	        wid, WindowTable[pScreen->myNum],
-    	        0, 0, pScreen->width, pScreen->height, 0, 
-	        InputOutput, CWOverrideRedirect, &overrideRedirect,
-	        WindowTable[pScreen->myNum]->drawable.depth, 
-	        serverClient, pScreen->rootVisual, &result);
-    if (pWin == NULL) {
-	return NULL;
-    }
-
-    if (!AddResource(wid, RT_WINDOW, (pointer)pWin)) {
-	DeleteWindow(pWin, None);
-	return NULL;
-    }
-
-    return pWin;
-}
-
 static int
 ProcCompositeGetOverlayWindow (ClientPtr client)
 {
@@ -456,28 +311,31 @@ ProcCompositeGetOverlayWindow (ClientPtr client)
     }
     pScreen = pWin->drawable.pScreen;
 
+    /* 
+     * Create an OverlayClient structure to mark this client's
+     * interest in the overlay window
+     */
+    pOc = compCreateOverlayClient(pScreen, client);
+    if (pOc == NULL)
+	return BadAlloc;
+
+    /*
+     * Make sure the overlay window exists
+     */
     cs = GetCompScreen(pScreen);
-    if (cs->pOverlayWin == NULL) {
-	cs->pOverlayWin = createOverlayWindow(pScreen);
-	if (cs->pOverlayWin == NULL) {
+    if (cs->pOverlayWin == NULL)
+	if (!compCreateOverlayWindow(pScreen))
+	{
+	    FreeResource (pOc->resource, RT_NONE);
 	    return BadAlloc;
 	}
-    }
 
     rc = XaceHook(XACE_RESOURCE_ACCESS, client, cs->pOverlayWin->drawable.id,
 		  RT_WINDOW, cs->pOverlayWin, RT_NONE, NULL, DixGetAttrAccess);
     if (rc != Success)
+    {
+	FreeResource (pOc->resource, RT_NONE);
 	return rc;
-
-    MapWindow(cs->pOverlayWin, serverClient);
-
-    /* Record that client is using this overlay window */
-    pOc = findCompOverlayClient(client, pScreen);
-    if (pOc == NULL) {
-	int ret = createCompOverlayClient(client, pScreen);
-	if (ret != Success) {
-	    return ret;
-	}
     }
 
     rep.type = X_Reply;
@@ -504,7 +362,6 @@ ProcCompositeReleaseOverlayWindow (ClientPtr client)
     WindowPtr pWin;
     ScreenPtr pScreen;
     CompOverlayClientPtr pOc;
-    CompScreenPtr cs;
 
     REQUEST_SIZE_MATCH(xCompositeReleaseOverlayWindowReq);
     pWin = (WindowPtr) LookupIDByType (stuff->window, RT_WINDOW);
@@ -519,18 +376,12 @@ ProcCompositeReleaseOverlayWindow (ClientPtr client)
      * Has client queried a reference to the overlay window
      * on this screen? If not, generate an error.
      */
-    pOc = findCompOverlayClient(client, pWin->drawable.pScreen);
-    if (pOc == NULL) {
+    pOc = compFindOverlayClient (pWin->drawable.pScreen, client);
+    if (pOc == NULL)
 	return BadMatch;
-    }
 
     /* The delete function will free the client structure */
-    FreeResource (pOc->resource, 0);
-
-    cs = GetCompScreen(pScreen);
-    if (cs->pOverlayClients == NULL) {
-	UnmapWindow(cs->pOverlayWin, FALSE);
-    }
+    FreeResource (pOc->resource, RT_NONE);
 
     return client->noClientException;
 }
diff --git a/composite/compinit.c b/composite/compinit.c
index 49b2044..7914a8d 100644
--- a/composite/compinit.c
+++ b/composite/compinit.c
@@ -76,14 +76,6 @@ compCloseScreen (int index, ScreenPtr pScreen)
     pScreen->CopyWindow = cs->CopyWindow;
     pScreen->PositionWindow = cs->PositionWindow;
 
-    deleteCompOverlayClientsForScreen(pScreen);
-
-    /* 
-    ** Note: no need to call DeleteWindow; the server has
-    ** already destroyed it.
-    */
-    cs->pOverlayWin = NULL;
-
     xfree (cs);
     dixSetPrivate(&pScreen->devPrivates, CompScreenPrivateKey, NULL);
     ret = (*pScreen->CloseScreen) (index, pScreen);
@@ -122,11 +114,11 @@ compChangeWindowAttributes(WindowPtr pWin, unsigned long mask)
     if (ret && (mask & CWBackingStore)) {
 	if (pWin->backingStore != NotUseful) {
 	    compRedirectWindow(serverClient, pWin, CompositeRedirectAutomatic);
-	    pWin->backStorage = TRUE;
+	    pWin->backStorage = (pointer) (intptr_t) 1;
 	} else {
 	    compUnredirectWindow(serverClient, pWin,
 				 CompositeRedirectAutomatic);
-	    pWin->backStorage = FALSE;
+	    pWin->backStorage = NULL;
 	}
     }
 
@@ -380,6 +372,7 @@ compScreenInit (ScreenPtr pScreen)
 	return FALSE;
 
     cs->damaged = FALSE;
+    cs->overlayWid = FakeClientID(0);
     cs->pOverlayWin = NULL;
     cs->pOverlayClients = NULL;
 
diff --git a/composite/compint.h b/composite/compint.h
index 4b0fe08..1c19ccd 100644
--- a/composite/compint.h
+++ b/composite/compint.h
@@ -155,6 +155,7 @@ typedef struct _CompScreen {
     VisualID			*alternateVisuals;
 
     WindowPtr                   pOverlayWin;
+    Window			overlayWid;
     CompOverlayClientPtr        pOverlayClients;
     
 } CompScreenRec, *CompScreenPtr;
@@ -172,6 +173,7 @@ extern DevPrivateKey CompSubwindowsPrivateKey;
 
 extern RESTYPE		CompositeClientWindowType;
 extern RESTYPE		CompositeClientSubwindowsType;
+extern RESTYPE		CompositeClientOverlayType;
 
 /*
  * compalloc.c
@@ -230,6 +232,25 @@ Bool
 compScreenInit (ScreenPtr pScreen);
 
 /*
+ * compoverlay.c
+ */
+
+void
+compFreeOverlayClient (CompOverlayClientPtr pOcToDel);
+
+CompOverlayClientPtr
+compFindOverlayClient (ScreenPtr pScreen, ClientPtr pClient);
+    
+CompOverlayClientPtr
+compCreateOverlayClient (ScreenPtr pScreen, ClientPtr pClient);
+
+Bool
+compCreateOverlayWindow (ScreenPtr pScreen);
+
+void
+compDestroyOverlayWindow (ScreenPtr pScreen);
+
+/*
  * compwindow.c
  */
 
@@ -292,9 +313,6 @@ compCopyWindow (WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc);
 void
 compWindowUpdate (WindowPtr pWin);
 
-void
-deleteCompOverlayClientsForScreen (ScreenPtr pScreen);
-
 WindowPtr
 CompositeRealChildHead (WindowPtr pWin);
 
diff --git a/composite/compoverlay.c b/composite/compoverlay.c
new file mode 100644
index 0000000..94e5b03
--- /dev/null
+++ b/composite/compoverlay.c
@@ -0,0 +1,159 @@
+/*
+ * Copyright © 2006 Sun Microsystems
+ *
+ * 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, and that the name of Sun Microsystems not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Sun Microsystems makes no
+ * representations about the suitability of this software for any purpose.  It
+ * is provided "as is" without express or implied warranty.
+ *
+ * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Copyright © 2003 Keith Packard
+ *
+ * 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, and that the name of Keith Packard not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Keith Packard makes no
+ * representations about the suitability of this software for any purpose.  It
+ * is provided "as is" without express or implied warranty.
+ *
+ * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include "compint.h"
+#include "xace.h"
+
+/* 
+ * Delete the given overlay client list element from its screen list.
+ */
+void
+compFreeOverlayClient (CompOverlayClientPtr pOcToDel)
+{
+    ScreenPtr		    pScreen = pOcToDel->pScreen;
+    CompScreenPtr	    cs = GetCompScreen (pScreen);
+    CompOverlayClientPtr    *pPrev, pOc;
+
+    for (pPrev = &cs->pOverlayClients; (pOc = *pPrev); pPrev = &pOc->pNext)
+    {
+	if (pOc == pOcToDel) {
+	    *pPrev = pOc->pNext;
+	    xfree (pOc);
+	    break;
+	}
+    }
+    
+    /* Destroy overlay window when there are no more clients using it */
+    if (cs->pOverlayClients == NULL)
+	compDestroyOverlayWindow (pScreen);
+}
+
+/*
+ * Return the client's first overlay client rec from the given screen
+ */
+CompOverlayClientPtr
+compFindOverlayClient (ScreenPtr pScreen, ClientPtr pClient)
+{
+    CompScreenPtr	    cs = GetCompScreen(pScreen);
+    CompOverlayClientPtr    pOc;
+
+    for (pOc = cs->pOverlayClients; pOc != NULL; pOc = pOc->pNext)
+	if (pOc->pClient == pClient)
+	    return pOc;
+
+    return NULL;           
+}
+
+/*
+ * Create an overlay client object for the given client
+ */
+CompOverlayClientPtr
+compCreateOverlayClient (ScreenPtr pScreen, ClientPtr pClient)
+{
+    CompScreenPtr    cs = GetCompScreen(pScreen);
+    CompOverlayClientPtr pOc;
+
+    pOc = (CompOverlayClientPtr) xalloc(sizeof(CompOverlayClientRec));
+    if (pOc == NULL)
+	return NULL;
+
+    pOc->pClient = pClient;
+    pOc->pScreen = pScreen;
+    pOc->resource = FakeClientID(pClient->index);
+    pOc->pNext = cs->pOverlayClients;
+    cs->pOverlayClients = pOc;
+
+    /* 
+     * Create a resource for this element so it can be deleted
+     * when the client goes away.
+     */
+    if (!AddResource (pOc->resource, CompositeClientOverlayType, (pointer) pOc))
+	return NULL;
+
+    return pOc;
+}
+
+/*
+ * Create the overlay window and map it
+ */
+Bool
+compCreateOverlayWindow (ScreenPtr pScreen)
+{
+    CompScreenPtr   cs = GetCompScreen(pScreen);
+    WindowPtr	    pRoot = WindowTable[pScreen->myNum];
+    WindowPtr	    pWin;
+    XID		    overrideRedirect = TRUE;
+    int		    result;
+
+    pWin = cs->pOverlayWin = 
+	CreateWindow (cs->overlayWid, pRoot,
+		      0, 0, pScreen->width, pScreen->height, 0, 
+		      InputOutput, CWOverrideRedirect, &overrideRedirect,
+		      pRoot->drawable.depth, 
+		      serverClient, pScreen->rootVisual, &result);
+    if (pWin == NULL)
+	return FALSE;
+
+    if (!AddResource(pWin->drawable.id, RT_WINDOW, (pointer)pWin))
+	return FALSE;
+
+    MapWindow(pWin, serverClient);
+
+    return TRUE;
+}
+
+/*
+ * Destroy the overlay window
+ */
+void
+compDestroyOverlayWindow (ScreenPtr pScreen)
+{
+    CompScreenPtr cs = GetCompScreen(pScreen);
+
+    cs->pOverlayWin = NullWindow;
+    FreeResource (cs->overlayWid, RT_NONE);
+}
+
commit 6c1accce87c9bd640c1b4bbc49bae7d44b1cc97b
Author: Keith Packard <keithp at keithp.com>
Date:   Sun May 4 21:51:08 2008 -0700

    Empty the borderClip of manual redirect windows. (bug 15823)
    
    Thanks to Owen Taylor for root-causing this one.
    
    If a TreatAsTransparent window has any area in the borderClip, that will be
    added to the totalClip region for use by other windows. That's wrong.
    Instead, simply empty the borderClip for TreatAsTransparent windows right up
    front.

diff --git a/mi/mivaltree.c b/mi/mivaltree.c
index 74483e3..d9d07ca 100644
--- a/mi/mivaltree.c
+++ b/mi/mivaltree.c
@@ -255,7 +255,11 @@ miComputeClips (
     if (pParent->redirectDraw != RedirectDrawNone)
     {
 	if (miSetRedirectBorderClipProc)
+	{
+	    if (TreatAsTransparent (pParent))
+		REGION_EMPTY (pScreen, universe);
 	    (*miSetRedirectBorderClipProc) (pParent, universe);
+	}
 	REGION_COPY(pScreen, universe, &pParent->borderSize);
     }
 #endif
commit d500eeb9458336780d77baf8b7db96e1f7ff4f0d
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Sun May 4 10:26:25 2008 -0700

    Xephyr: Handle depth 30 and reject higher depths rather than crashing.

diff --git a/hw/kdrive/ephyr/ephyr.c b/hw/kdrive/ephyr/ephyr.c
index d69e148..3989d0d 100644
--- a/hw/kdrive/ephyr/ephyr.c
+++ b/hw/kdrive/ephyr/ephyr.c
@@ -150,11 +150,22 @@ ephyrScreenInitialize (KdScreenInfo *screen, EphyrScrPriv *scrpriv)
 	  screen->fb[0].depth = 16;
 	  screen->fb[0].bitsPerPixel = 16;
 	}
-      else
+      else if (screen->fb[0].depth <= 24)
 	{
 	  screen->fb[0].depth = 24;
 	  screen->fb[0].bitsPerPixel = 32;
 	}
+      else if (screen->fb[0].depth <= 30)
+	{
+	  screen->fb[0].depth = 30;
+	  screen->fb[0].bitsPerPixel = 32;
+	}
+      else
+	{
+	  ErrorF("\nXephyr: Unsupported screen depth %d\n",
+	         screen->fb[0].depth);
+	  return FALSE;
+	}
 
       hostx_get_visual_masks (screen, &redMask, &greenMask, &blueMask);
 
commit f4a68f3701889950d3b98842d021f357f3913fea
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri May 2 17:35:57 2008 -0700

    XQuartz: Fix mouse input offsets earlier since GetPointerEvents does not like negative (x,y) values
    (cherry picked from commit 8d9eab3a2ec5955cc2698fdcb1fa6ed12b2aadb7)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 646b9ef..691725d 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -839,7 +839,7 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
 	int pointer_x, pointer_y, ev_button, ev_type;
 	float pressure, tilt_x, tilt_y;
 
-	/* convert location to global top-left coordinates */
+	/* convert location to be relative to top-left of primary display */
 	location = [e locationInWindow];
 	window = [e window];
 	screen = [[[NSScreen screens] objectAtIndex:0] frame];
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 2c95ed7..1547094 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -359,6 +359,28 @@ static void DarwinPokeEQ(void) {
 	write(darwinEventWriteFD, &nullbyte, 1);
 }
 
+/* Convert from Appkit pointer input values to X input values:
+ * Note: pointer_x and pointer_y are relative to the upper-left of primary
+ *       display.
+ */
+static void DarwinPrepareValuators(int *valuators, ScreenPtr screen,
+                                   int pointer_x, int pointer_y, 
+                                   float pressure, float tilt_x, float tilt_y) {
+    /* Fix offset between darwin and X screens */
+    pointer_x -= darwinMainScreenX + dixScreenOrigins[screen->myNum].x;
+    pointer_y -= darwinMainScreenY + dixScreenOrigins[screen->myNum].y;
+    
+    /* Setup our array of values */
+    valuators[0] = pointer_x;
+    valuators[1] = pointer_y;
+    valuators[2] = pressure * SCALEFACTOR_PRESSURE;
+    valuators[3] = tilt_x * SCALEFACTOR_TILT;
+    valuators[4] = tilt_y * SCALEFACTOR_TILT;
+    
+    DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
+              valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
+}
+
 void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y, 
 			     float pressure, float tilt_x, float tilt_y) {
 	static int darwinFakeMouseButtonDown = 0;
@@ -366,22 +388,26 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	int i, num_events;
 	DeviceIntPtr dev;
     ScreenPtr screen;
+    int valuators[5];
 	
-//    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     
 	if(!darwinEvents) {
-		ErrorF("DarwinSendPointerEvents called before darwinEvents was initialized\n");
+		DEBUG_LOG("DarwinSendPointerEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
-	int valuators[5] = {pointer_x, pointer_y, pressure * SCALEFACTOR_PRESSURE, 
-		      tilt_x * SCALEFACTOR_TILT, tilt_y * SCALEFACTOR_TILT};
-	
-	if (pressure == 0 && tilt_x == 0 && tilt_y == 0) dev = darwinPointer;
-	else dev = darwinTablet;
+	if (pressure == 0 && tilt_x == 0 && tilt_y == 0)
+        dev = darwinPointer;
+	else
+        dev = darwinTablet;
+
+    screen = miPointerGetScreen(dev);
+    if(!screen) {
+        DEBUG_LOG("DarwinSendPointerEvents called before screen was initialized\n");
+        return;
+    }
 
-	DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
-			valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
 	if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
 		// Mimic multi-button mouse with modifier-clicks
 		// If both sets of modifiers are pressed,
@@ -411,19 +437,13 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 		DarwinUpdateModifiers(KeyPress, darwinFakeMouseButtonMask & old_flags);
 		darwinFakeMouseButtonMask = 0;
 		return;
-	} 
+	}
 
+    DarwinPrepareValuators(valuators, screen, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     darwinEvents_lock(); {
         num_events = GetPointerEvents(darwinEvents, dev, ev_type, ev_button, 
                                       POINTER_ABSOLUTE, 0, dev==darwinTablet?5:2, valuators);
-        screen = miPointerGetScreen(dev);
-        for(i=0; i<num_events && screen; i++) {
-            darwinEvents[i].u.keyButtonPointer.rootX -= darwinMainScreenX +
-                dixScreenOrigins[screen->myNum].x;
-            darwinEvents[i].u.keyButtonPointer.rootY -= darwinMainScreenY +
-                dixScreenOrigins[screen->myNum].y;
-            mieqEnqueue (dev, &darwinEvents[i]);
-        }
+        for(i=0; i<num_events; i++) mieqEnqueue (dev, &darwinEvents[i]);
         DarwinPokeEQ();
 
     } darwinEvents_unlock();
@@ -433,7 +453,7 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 	int i, num_events;
 
 	if(!darwinEvents) {
-		ErrorF("DarwinSendKeyboardEvents called before darwinEvents was initialized\n");
+		DEBUG_LOG("DarwinSendKeyboardEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
@@ -459,21 +479,28 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 
 void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
 	int i, num_events;
-
-	// tilt and pressure have no meaning for a Prox event
-	int valuators[5] = {pointer_x, pointer_y, 0, 0, 0};  
+    ScreenPtr screen;
+    DeviceIntPtr dev = darwinTablet;
+    int valuators[5];
 
 	DEBUG_LOG("DarwinSendProximityEvents(%d, %d, %d)\n", ev_type, pointer_x, pointer_y);
-	
+
 	if(!darwinEvents) {
-		ErrorF("DarwinSendProximityEvents called before darwinEvents was initialized\n");
+		DEBUG_LOG("DarwinSendProximityEvents called before darwinEvents was initialized\n");
 		return;
 	}
+    
+    screen = miPointerGetScreen(dev);
+    if(!screen) {
+        DEBUG_LOG("DarwinSendPointerEvents called before screen was initialized\n");
+        return;
+    }    
 
+    DarwinPrepareValuators(valuators, screen, pointer_x, pointer_y, 0.0f, 0.0f, 0.0f);
     darwinEvents_lock(); {
-        num_events = GetProximityEvents(darwinEvents, darwinTablet, ev_type,
+        num_events = GetProximityEvents(darwinEvents, dev, ev_type,
                                         0, 5, valuators);
-        for(i=0; i<num_events; i++) mieqEnqueue (darwinTablet,&darwinEvents[i]);
+        for(i=0; i<num_events; i++) mieqEnqueue (dev,&darwinEvents[i]);
         DarwinPokeEQ();
     } darwinEvents_unlock();
 }
@@ -484,7 +511,7 @@ void DarwinSendScrollEvents(float count_x, float count_y,
 							int pointer_x, int pointer_y, 
 			    			float pressure, float tilt_x, float tilt_y) {
 	if(!darwinEvents) {
-		ErrorF("DarwinSendScrollEvents called before darwinEvents was initialized\n");
+		DEBUG_LOG("DarwinSendScrollEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
commit 96fa7da3b87e2f9187ec13dad259beefdc17cd94
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri May 2 16:53:45 2008 -0700

    XQuartz: Avoid a possible crash at startup due to unfavorable context switching.
    (cherry picked from commit ff10c37bdd09656cf2f7ee9577f5552caa1ffdb8)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 161fd9d..2c95ed7 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -365,6 +365,7 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	static int darwinFakeMouseButtonMask = 0;
 	int i, num_events;
 	DeviceIntPtr dev;
+    ScreenPtr screen;
 	
 //    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     
@@ -415,11 +416,12 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
     darwinEvents_lock(); {
         num_events = GetPointerEvents(darwinEvents, dev, ev_type, ev_button, 
                                       POINTER_ABSOLUTE, 0, dev==darwinTablet?5:2, valuators);
-        for(i=0; i<num_events; i++) {
+        screen = miPointerGetScreen(dev);
+        for(i=0; i<num_events && screen; i++) {
             darwinEvents[i].u.keyButtonPointer.rootX -= darwinMainScreenX +
-                dixScreenOrigins[miPointerCurrentScreen()->myNum].x;
+                dixScreenOrigins[screen->myNum].x;
             darwinEvents[i].u.keyButtonPointer.rootY -= darwinMainScreenY +
-                dixScreenOrigins[miPointerCurrentScreen()->myNum].y;
+                dixScreenOrigins[screen->myNum].y;
             mieqEnqueue (dev, &darwinEvents[i]);
         }
         DarwinPokeEQ();
commit a338007be6fd4302af012109d959f43ac7eab2b1
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu May 1 18:02:59 2008 -0700

    XQuartz: Adjust the screen origin offset properly for multimonitor setups
    (cherry picked from commit f2020b9836bacd0593ac0b4c8541e32714ab02a9)

diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index df328f3..107d8ee 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -42,6 +42,7 @@
 
 #include "opaque.h"
 #include "darwin.h"
+#include "darwinEvents.h"
 #include "quartz.h"
 #define _APPLEWM_SERVER_
 #include "X11/extensions/applewm.h"
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 7b3091d..161fd9d 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -81,22 +81,21 @@ int input_check_zero, input_check_flag;
 static int old_flags = 0;  // last known modifier state
 
 xEvent *darwinEvents = NULL;
+pthread_mutex_t darwinEvents_mutex = PTHREAD_MUTEX_INITIALIZER;
 
-pthread_mutex_t mieqEnqueue_mutex = PTHREAD_MUTEX_INITIALIZER;
-
-static inline void mieqEnqueue_lock(void) {
+static inline void darwinEvents_lock(void) {
     int err;
-    if((err = pthread_mutex_lock(&mieqEnqueue_mutex))) {
-        ErrorF("%s:%s:%d: Failed to lock mieqEnqueue_mutex: %d\n",
+    if((err = pthread_mutex_lock(&darwinEvents_mutex))) {
+        ErrorF("%s:%s:%d: Failed to lock darwinEvents_mutex: %d\n",
                __FILE__, __FUNCTION__, __LINE__, err);
         spewCallStack();
     }
 }
 
-static inline void mieqEnqueue_unlock(void) {
+static inline void darwinEvents_unlock(void) {
     int err;
-    if((err = pthread_mutex_unlock(&mieqEnqueue_mutex))) {
-        ErrorF("%s:%s:%d: Failed to unlock mieqEnqueue_mutex: %d\n",
+    if((err = pthread_mutex_unlock(&darwinEvents_mutex))) {
+        ErrorF("%s:%s:%d: Failed to unlock darwinEvents_mutex: %d\n",
                __FILE__, __FUNCTION__, __LINE__, err);
         spewCallStack();
     }
@@ -413,13 +412,19 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 		return;
 	} 
 
-    mieqEnqueue_lock(); {
+    darwinEvents_lock(); {
         num_events = GetPointerEvents(darwinEvents, dev, ev_type, ev_button, 
                                       POINTER_ABSOLUTE, 0, dev==darwinTablet?5:2, valuators);
-        for(i=0; i<num_events; i++) mieqEnqueue (dev,&darwinEvents[i]);
+        for(i=0; i<num_events; i++) {
+            darwinEvents[i].u.keyButtonPointer.rootX -= darwinMainScreenX +
+                dixScreenOrigins[miPointerCurrentScreen()->myNum].x;
+            darwinEvents[i].u.keyButtonPointer.rootY -= darwinMainScreenY +
+                dixScreenOrigins[miPointerCurrentScreen()->myNum].y;
+            mieqEnqueue (dev, &darwinEvents[i]);
+        }
         DarwinPokeEQ();
 
-    } mieqEnqueue_unlock();
+    } darwinEvents_unlock();
 }
 
 void DarwinSendKeyboardEvents(int ev_type, int keycode) {
@@ -443,11 +448,11 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 		}
 	}
 
-    mieqEnqueue_lock(); {
+    darwinEvents_lock(); {
         num_events = GetKeyboardEvents(darwinEvents, darwinKeyboard, ev_type, keycode + MIN_KEYCODE);
         for(i=0; i<num_events; i++) mieqEnqueue(darwinKeyboard,&darwinEvents[i]);
         DarwinPokeEQ();
-    } mieqEnqueue_unlock();
+    } darwinEvents_unlock();
 }
 
 void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
@@ -463,12 +468,12 @@ void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
 		return;
 	}
 
-    mieqEnqueue_lock(); {
+    darwinEvents_lock(); {
         num_events = GetProximityEvents(darwinEvents, darwinTablet, ev_type,
                                         0, 5, valuators);
         for(i=0; i<num_events; i++) mieqEnqueue (darwinTablet,&darwinEvents[i]);
         DarwinPokeEQ();
-    } mieqEnqueue_unlock();
+    } darwinEvents_unlock();
 }
 
 
@@ -533,8 +538,8 @@ void DarwinSendDDXEvent(int type, int argc, ...) {
         va_end (args);
     }
 
-    mieqEnqueue_lock();
+    darwinEvents_lock();
     mieqEnqueue(darwinPointer, &xe);
     DarwinPokeEQ();
-    mieqEnqueue_unlock();
+    darwinEvents_unlock();
 }
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 7312226..d8eb72a 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -40,6 +40,7 @@
 #include "xprEvent.h"
 #include "pseudoramiX.h"
 #include "darwin.h"
+#include "darwinEvents.h"
 #include "rootless.h"
 #include "dri.h"
 #include "globals.h"
commit 3b8d53452cd6c74d32d7759964a7cd9ee775f161
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Thu May 1 15:10:52 2008 +0200

    EXA: Fall back in CompositeRects if the driver can't accelerate Composite.
    
    Fixes http://bugs.freedesktop.org/show_bug.cgi?id=15780 .

diff --git a/exa/exa_render.c b/exa/exa_render.c
index 43b0029..b480c6d 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -345,6 +345,9 @@ exaTryDriverCompositeRects(CARD8	       op,
     struct _Pixmap scratch;
     ExaMigrationRec pixmaps[2];
 
+    if (!pExaScr->info->PrepareComposite)
+	return -1;
+
     pSrcPix = exaGetDrawablePixmap(pSrc->pDrawable);
     pSrcExaPix = ExaGetPixmapPriv(pSrcPix);
 
commit 01c61f3d972fc2f4e5bb536dd00d8b6bbeb0fb3d
Author: Paulo Cesar Pereira de Andrade <pcpa at mandriva.com.br>
Date:   Thu May 1 01:02:39 2008 -0300

    xorgcfg: Fix a crash if xorg.conf doesn't have a Files section.
    
    This patch only creates a Files section if required, so if no entries are
    added, an empty Files section will not be created.
    
    Signed-off-by: Peter Hutterer <peter at cs.unisa.edu.au>

diff --git a/hw/xfree86/utils/xorgcfg/expert.c b/hw/xfree86/utils/xorgcfg/expert.c
index bb6960c..484c2ec 100644
--- a/hw/xfree86/utils/xorgcfg/expert.c
+++ b/hw/xfree86/utils/xorgcfg/expert.c
@@ -465,7 +465,7 @@ CreateFiles(TreeNode *files)
     Widget w;
     char *value;
 
-    value = file->file_logfile ? file->file_logfile : "";
+    value = (file && file->file_logfile) ? file->file_logfile : "";
     node = NewNode(files, NULL, NULL, files->node, 
 		   (TreeData*)XtCalloc(1, sizeof(TreeData)));
     CreateFilesField(node, "LogFile", value);
@@ -509,10 +509,14 @@ UpdateFiles(TreeNode *files)
     /* LogFile */
     files = files->child;
     XtVaGetValues(files->data->files.text, XtNstring, &str, NULL);
-    XtFree(XF86Config->conf_files->file_logfile);
-    if (*str)
+    if (XF86Config->conf_files && XF86Config->conf_files->file_logfile)
+	XtFree(XF86Config->conf_files->file_logfile);
+    if (*str) {
+	if (XF86Config->conf_files == NULL)
+	    XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
 	XF86Config->conf_files->file_logfile = XtNewString(str);
-    else
+    }
+    else if (XF86Config->conf_files)
 	XF86Config->conf_files->file_logfile = NULL;
 }
 
@@ -527,10 +531,11 @@ CreateFontPath(TreeNode *fontpath, char *path)
     if (path == NULL) {
 	if (XF86Font_path) {
 	    path = XtNewString(XF86Font_path);
-	    if (XF86Config->conf_files && XF86Config->conf_files->file_fontpath) {
+	    if (XF86Config->conf_files && XF86Config->conf_files->file_fontpath)
 		XtFree(XF86Config->conf_files->file_fontpath);
-		XF86Config->conf_files->file_fontpath = XtNewString(path);
-	    }
+	    if (XF86Config->conf_files == NULL)
+		XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
+	    XF86Config->conf_files->file_fontpath = XtNewString(path);
 	}
 	else if (XF86Config->conf_files && XF86Config->conf_files->file_fontpath)
 	    path = XtNewString(XF86Config->conf_files->file_fontpath);
@@ -629,9 +634,14 @@ FontPathChanged(TreeNode *node)
 	pos += len - 2;
     }
 
-    if (XF86Config->conf_files->file_fontpath)
-	XtFree(XF86Config->conf_files->file_fontpath);
-    XF86Config->conf_files->file_fontpath = fontpath;
+    if (XF86Config->conf_files) {
+	if (XF86Config->conf_files->file_fontpath)
+	    XtFree(XF86Config->conf_files->file_fontpath);
+    }
+    else if (fontpath)
+	XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
+    if (XF86Config->conf_files)
+	XF86Config->conf_files->file_fontpath = fontpath;
 }
 
 static void
@@ -703,10 +713,11 @@ CreateModulePath(TreeNode *modulepath, char *path)
     if (path == NULL) {
 	if (XF86Module_path) {
 	    path = XtNewString(XF86Module_path);
-	    if (XF86Config->conf_files && XF86Config->conf_files->file_modulepath) {
+	    if (XF86Config->conf_files == NULL)
+		XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
+	    else if (XF86Config->conf_files->file_modulepath)
 		XtFree(XF86Config->conf_files->file_modulepath);
-		XF86Config->conf_files->file_modulepath = XtNewString(path);
-	    }
+	    XF86Config->conf_files->file_modulepath = XtNewString(path);
 	}
 	else if (XF86Config->conf_files && XF86Config->conf_files->file_modulepath)
 	    path = XtNewString(XF86Config->conf_files->file_modulepath);
@@ -799,9 +810,14 @@ ModulePathChanged(TreeNode *node)
 	pos += len - 2;
     }
 
-    if (XF86Config->conf_files->file_modulepath)
-	XtFree(XF86Config->conf_files->file_modulepath);
-    XF86Config->conf_files->file_modulepath = modulepath;
+    if (XF86Config->conf_files) {
+	if (XF86Config->conf_files->file_modulepath)
+	    XtFree(XF86Config->conf_files->file_modulepath);
+    }
+    else if (modulepath)
+	XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
+    if (XF86Config->conf_files)
+	XF86Config->conf_files->file_modulepath = modulepath;
 }
 
 static void
@@ -921,6 +937,8 @@ NewModuleCallback(Widget unused, XtPointer user_data, XtPointer call_data)
     DeleteNode(node);
     load = (XF86LoadPtr)XtCalloc(1, sizeof(XF86LoadRec));
     load->load_name = XtNewString(label);
+    if (XF86Config->conf_modules == NULL)
+	XF86Config->conf_modules = XtCalloc(1, sizeof(XF86ConfModuleRec));
     XF86Config->conf_modules->mod_load_lst =
 	xf86addModule(XF86Config->conf_modules->mod_load_lst, load);
 
commit 6899ff81e8f668382e3e2f9afdd9cdf51d0e0f7d
Author: Paulo Cesar Pereira de Andrade <pcpa at mandriva.com.br>
Date:   Wed Apr 30 16:38:42 2008 -0300

    Fix an off by one read error in drmSIGIOHandler().
    
    Signed-off-by: Peter Hutterer <peter at cs.unisa.edu.au>

diff --git a/hw/xfree86/dri/dri.c b/hw/xfree86/dri/dri.c
index b736c6a..ef1a6ea 100644
--- a/hw/xfree86/dri/dri.c
+++ b/hw/xfree86/dri/dri.c
@@ -2436,7 +2436,7 @@ static void drmSIGIOHandler(int interrupt, void *closure)
 #if 0
 	    fprintf(stderr, "Trying %d\n", entry->fd);
 #endif
-	    if ((count = read(entry->fd, buf, sizeof(buf))) > 0) {
+	    if ((count = read(entry->fd, buf, sizeof(buf) - 1)) > 0) {
 		buf[count] = '\0';
 #if 0
 		fprintf(stderr, "Got %s\n", buf);
commit ec0419b50534006a272278b79ee51538193661cb
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 30 17:30:57 2008 -0700

    XQuartz: Moved some relevant stuff from darwin.h to darwinEvents.h
    (cherry picked from commit 1fcf74a436f2e19cceb3f285b89859025d94c040)

diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 4300b9f..bdf0046 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -89,38 +89,6 @@ extern int              darwinDesiredRefresh;
 extern int              darwinMainScreenX;
 extern int              darwinMainScreenY;
 
-
-/*
- * Special ddx events understood by the X server
- */
-enum {
-    kXquartzReloadKeymap      // Reload system keymap
-            = LASTEvent+1,    // (from X.h list of event names)
-    kXquartzActivate,         // restore X drawing and cursor
-    kXquartzDeactivate,       // clip X drawing and switch to Aqua cursor
-    kXquartzSetRootClip,      // enable or disable drawing to the X screen
-    kXquartzQuit,             // kill the X server and release the display
-    kXquartzReadPasteboard,   // copy Mac OS X pasteboard into X cut buffer
-    kXquartzWritePasteboard,  // copy X cut buffer onto Mac OS X pasteboard
-    kXquartzBringAllToFront,  // bring all X windows to front
-    kXquartzToggleFullscreen, // Enable/Disable fullscreen mode
-    kXquartzSetRootless,      // Set rootless mode
-    kXquartzSpaceChanged,     // Spaces changed
-    /*
-     * AppleWM events
-     */
-    kXquartzControllerNotify, // send an AppleWMControllerNotify event
-    kXquartzPasteboardNotify, // notify the WM to copy or paste
-    /*
-     * Xplugin notification events
-     */
-    kXquartzDisplayChanged,   // display configuration has changed
-    kXquartzWindowState,      // window visibility state has changed
-    kXquartzWindowMoved,      // window has moved on screen
-};
-
-void DarwinSendDDXEvent(int type, int argc, ...);
-
 #define ENABLE_DEBUG_LOG 1
 
 #ifdef ENABLE_DEBUG_LOG
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index ef8bf39..a676aeb 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -40,4 +40,36 @@ void DarwinSendScrollEvents(float count_x, float count_y, int pointer_x, int poi
 			    float pressure, float tilt_x, float tilt_y);
 void DarwinUpdateModKeys(int flags);
 
+/*
+ * Special ddx events understood by the X server
+ */
+enum {
+    kXquartzReloadKeymap      // Reload system keymap
+    = LASTEvent+1,    // (from X.h list of event names)
+    kXquartzActivate,         // restore X drawing and cursor
+    kXquartzDeactivate,       // clip X drawing and switch to Aqua cursor
+    kXquartzSetRootClip,      // enable or disable drawing to the X screen
+    kXquartzQuit,             // kill the X server and release the display
+    kXquartzReadPasteboard,   // copy Mac OS X pasteboard into X cut buffer
+    kXquartzWritePasteboard,  // copy X cut buffer onto Mac OS X pasteboard
+    kXquartzBringAllToFront,  // bring all X windows to front
+    kXquartzToggleFullscreen, // Enable/Disable fullscreen mode
+    kXquartzSetRootless,      // Set rootless mode
+    kXquartzSpaceChanged,     // Spaces changed
+    /*
+     * AppleWM events
+     */
+    kXquartzControllerNotify, // send an AppleWMControllerNotify event
+    kXquartzPasteboardNotify, // notify the WM to copy or paste
+    /*
+     * Xplugin notification events
+     */
+    kXquartzDisplayChanged,   // display configuration has changed
+    kXquartzWindowState,      // window visibility state has changed
+    kXquartzWindowMoved,      // window has moved on screen
+};
+
+/* Send one of the above events to the server thread. */
+void DarwinSendDDXEvent(int type, int argc, ...);
+
 #endif  /* _DARWIN_EVENTS_H */
commit 28d1e21f1523d475cb757d3cfa33737ed62c534d
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 30 17:30:32 2008 -0700

    Dix: Cleaned up sanity checking in Get{Pointer,Keyboard}Events
    
    XQuartz was crashing because the Appkit thread was trying to GetXXXEvents while the Xserver thread was exiting.
    This adds some more sanity checks and avoids that crash
    (cherry picked from commit 34ec4bd6acb834c0e3f9a5042a0cc3f52c6f3a68)

diff --git a/dix/getevents.c b/dix/getevents.c
index bf9331e..0229c0a 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -407,8 +407,8 @@ GetKeyboardValuatorEvents(xEvent *events, DeviceIntPtr pDev, int type,
                           int num_valuators, int *valuators) {
     int numEvents = 0;
     CARD32 ms = 0;
-    KeySym *map = pDev->key->curKeySyms.map;
-    KeySym sym = map[key_code * pDev->key->curKeySyms.mapWidth];
+    KeySym *map;
+    KeySym sym;
     deviceKeyButtonPointer *kbp = NULL;
 
     if (!events)
@@ -419,11 +419,14 @@ GetKeyboardValuatorEvents(xEvent *events, DeviceIntPtr pDev, int type,
         return 0;
 
     if (!pDev->key || !pDev->focus || !pDev->kbdfeed ||
-        (pDev->coreEvents && !inputInfo.keyboard->key))
+        (pDev->coreEvents && !(inputInfo.keyboard && inputInfo.keyboard->key)))
         return 0;
 
     if (key_code < 8 || key_code > 255)
         return 0;
+    
+    map = pDev->key->curKeySyms.map;
+    sym = map[key_code * pDev->key->curKeySyms.mapWidth];
 
     if (pDev->coreEvents)
         numEvents = 2;
@@ -539,6 +542,9 @@ GetPointerEvents(xEvent *events, DeviceIntPtr pDev, int type, int buttons,
 
     if ((type == ButtonPress || type == ButtonRelease) && !pDev->button)
         return 0;
+    
+    if(pDev->coreEvents && !cp)
+        return 0;
 
     /* FIXME: I guess it should, in theory, be possible to post button events
      *        from devices without valuators. */
commit ce36ae526d88d20ff67cd6cb429fb06f48d231f6
Author: Kazuhiro Inaoka <inaoka.kazuhiro at renesas.com>
Date:   Wed Apr 30 11:58:32 2008 +0300

    Add M32R architecture support (bug #10020)
    
    Still needs autotools support, so this won't actually _build_: it's just
    a starting point.

diff --git a/hw/xfree86/common/compiler.h b/hw/xfree86/common/compiler.h
index 7b65da8..9e7f821 100644
--- a/hw/xfree86/common/compiler.h
+++ b/hw/xfree86/common/compiler.h
@@ -1363,7 +1363,7 @@ do {									\
 #    define write_mem_barrier()   /* NOP */
 
 #    if !defined(__SUNPRO_C)
-#    if !defined(FAKEIT) && !defined(__mc68000__) && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__)
+#    if !defined(FAKEIT) && !defined(__mc68000__) && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__) && !defined(__m32r__)
 #     ifdef GCCUSESGAS
 
 /*
@@ -1472,7 +1472,7 @@ inl(unsigned short port)
 
 #     endif /* GCCUSESGAS */
 
-#    else /* !defined(FAKEIT) && !defined(__mc68000__)  && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__)*/
+#    else /* !defined(FAKEIT) && !defined(__mc68000__)  && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__m32r__) */
 
 static __inline__ void
 outb(unsigned short port, unsigned char val)
diff --git a/hw/xfree86/common/xf86Bus.c b/hw/xfree86/common/xf86Bus.c
index f7ffac8..7e6b93a 100644
--- a/hw/xfree86/common/xf86Bus.c
+++ b/hw/xfree86/common/xf86Bus.c
@@ -2773,7 +2773,7 @@ xf86FindPrimaryDevice()
     }
 }
 
-#if !defined(__sparc) && !defined(__sparc__) && !defined(__powerpc__) && !defined(__mips__) && !defined(__arm__)
+#if !defined(__sparc) && !defined(__sparc__) && !defined(__powerpc__) && !defined(__mips__) && !defined(__arm__) && !defined(__m32r__)
 #include "vgaHW.h"
 #include "compiler.h"
 #endif
@@ -2785,7 +2785,7 @@ static void
 CheckGenericGA()
 {
 /* This needs to be changed for multiple domains */
-#if !defined(__sparc__) && !defined(__sparc) && !defined(__powerpc__) && !defined(__mips__) && !defined(__ia64__) && !defined(__arm__) && !defined(__s390__)
+#if !defined(__sparc__) && !defined(__sparc) && !defined(__powerpc__) && !defined(__mips__) && !defined(__ia64__) && !defined(__arm__) && !defined(__s390__) && !defined(__m32r__)
     IOADDRESS GenericIOBase = VGAHW_GET_IOBASE();
     CARD8 CurrentValue, TestValue;
 
diff --git a/hw/xfree86/os-support/bus/Pci.h b/hw/xfree86/os-support/bus/Pci.h
index b78d307..1385eee 100644
--- a/hw/xfree86/os-support/bus/Pci.h
+++ b/hw/xfree86/os-support/bus/Pci.h
@@ -237,6 +237,12 @@
 # if defined(linux)
 #  define ARCH_PCI_INIT linuxPciInit
 # endif
+#elif defined(__m32r__)
+# if defined(linux)
+#  define ARCH_PCI_INIT linuxPciInit
+#  define INCLUDE_XF86_MAP_PCI_MEM
+#  define INCLUDE_XF86_NO_DOMAIN
+# endif
 #elif defined(__sparc__) || defined(sparc)
 # if defined(linux)
 #  define ARCH_PCI_INIT linuxPciInit
diff --git a/hw/xfree86/os-support/linux/lnxResource.c b/hw/xfree86/os-support/linux/lnxResource.c
index 67af9db..734f4d6 100644
--- a/hw/xfree86/os-support/linux/lnxResource.c
+++ b/hw/xfree86/os-support/linux/lnxResource.c
@@ -65,6 +65,7 @@ xf86AccResFromOS(resPtr ret)
       defined(__sparc__) || \
       defined(__mips__) || \
       defined(__sh__) || \
+      defined(__m32r__) || \
       defined(__mc68000__) || \
       defined(__arm__) || \
       defined(__s390__) || \
diff --git a/hw/xfree86/os-support/linux/lnx_video.c b/hw/xfree86/os-support/linux/lnx_video.c
index 1bd2d57..4295937 100644
--- a/hw/xfree86/os-support/linux/lnx_video.c
+++ b/hw/xfree86/os-support/linux/lnx_video.c
@@ -558,7 +558,7 @@ xf86EnableIO(void)
 #endif
 	}
 	close(fd);
-#elif !defined(__mc68000__) && !defined(__sparc__) && !defined(__mips__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__) && !defined(__arm__)
+#elif !defined(__mc68000__) && !defined(__sparc__) && !defined(__mips__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__) && !defined(__arm__) && !defined(__m32r__)
         if (ioperm(0, 1024, 1) || iopl(3)) {
                 if (errno == ENODEV)
                         ErrorF("xf86EnableIOPorts: no I/O ports found\n");
@@ -585,7 +585,7 @@ xf86DisableIO(void)
 #if defined(__powerpc__)
 	munmap(ioBase, 0x20000);
 	ioBase = NULL;
-#elif !defined(__mc68000__) && !defined(__sparc__) && !defined(__mips__) && !defined(__sh__) && !defined(__hppa__) && !defined(__arm__) && !defined(__s390__)
+#elif !defined(__mc68000__) && !defined(__sparc__) && !defined(__mips__) && !defined(__sh__) && !defined(__hppa__) && !defined(__arm__) && !defined(__s390__) && !defined(__m32r__)
 	iopl(0);
 	ioperm(0, 1024, 0);
 #endif
diff --git a/include/servermd.h b/include/servermd.h
index 7b0a328..8e6de09 100644
--- a/include/servermd.h
+++ b/include/servermd.h
@@ -217,6 +217,26 @@ SOFTWARE.
 
 #endif /* SuperH */
 
+#if defined(__m32r__)
+
+#if defined(__BIG_ENDIAN__)
+# define IMAGE_BYTE_ORDER      MSBFirst
+# define BITMAP_BIT_ORDER      MSBFirst
+# define GLYPHPADBYTES         4
+# define GETLEFTBITS_ALIGNMENT 1
+#else
+# define IMAGE_BYTE_ORDER      LSBFirst
+# define BITMAP_BIT_ORDER      LSBFirst
+# define GLYPHPADBYTES         4
+# define GETLEFTBITS_ALIGNMENT 1
+#endif
+
+#define AVOID_MEMORY_READ
+#define FAST_CONSTANT_OFFSET_MODE
+#define LARGE_INSTRUCTION_CACHE
+#define PLENTIFUL_REGISTERS
+
+#endif /* __m32r__ */
 
 #if (defined(sun) && (defined(__sparc) || defined(sparc))) || \
     (defined(__uxp__) && (defined(sparc) || defined(mc68000))) || \
commit b71b51c982706501b6229532ce342752207426bb
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Tue Apr 29 23:37:58 2008 -0700

    xquartz: created darwinTablet, to represent tablet events
    (cherry picked from commit 50641bce730ee03738fa0c4beb8125b34fda556f)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 6f47194..f20cce1 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -1,10 +1,9 @@
 /**************************************************************
  *
- * Shared code for the Darwin X Server
- * running with Quartz or IOKit display mode
+ * Xquartz initialization code
  *
+ * Copyright (c) 2007-2008 Apple Inc.
  * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
- * Copyright (c) 2007 Apple Inc.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -112,6 +111,7 @@ int                     darwinFakeMouse3Mask = NX_COMMANDMASK;
 
 // devices
 DeviceIntPtr            darwinPointer = NULL;
+DeviceIntPtr            darwinTablet = NULL;
 DeviceIntPtr            darwinKeyboard = NULL;
 
 // Common pixmap formats
@@ -332,14 +332,13 @@ static void DarwinChangePointerControl(
 #endif
 
 /*
- * DarwinMouseProc
- *  Handle the initialization, etc. of a mouse
+ * DarwinMouseProc: Handle the initialization, etc. of a mouse
  */
 static int DarwinMouseProc(DeviceIntPtr pPointer, int what) {
+	// 7 buttons: left, right, middle, then four scroll wheel "buttons"
     CARD8 map[8] = {0, 1, 2, 3, 4, 5, 6, 7};
     
     switch (what) {
-            
         case DEVICE_INIT:
             pPointer->public.on = FALSE;
             
@@ -347,15 +346,13 @@ static int DarwinMouseProc(DeviceIntPtr pPointer, int what) {
             InitPointerDeviceStruct((DevicePtr)pPointer, map, 7,
                                     GetMotionHistory,
                                     (PtrCtrlProcPtr)NoopDDA,
-                                    GetMotionHistorySize(), 7);
-            InitProximityClassDeviceStruct(pPointer);
+                                    GetMotionHistorySize(), 2);
+								pPointer->name = strdup("Quartz Pointing Device");
             break;
-            
         case DEVICE_ON:
             pPointer->public.on = TRUE;
             AddEnabledDevice( darwinEventReadFD );
             return Success;
-            
         case DEVICE_CLOSE:
         case DEVICE_OFF:
             pPointer->public.on = FALSE;
@@ -366,6 +363,34 @@ static int DarwinMouseProc(DeviceIntPtr pPointer, int what) {
     return Success;
 }
 
+static int DarwinTabletProc(DeviceIntPtr pPointer, int what) {
+    CARD8 map[4] = {0, 1, 2, 3};
+    
+    switch (what) {
+        case DEVICE_INIT:
+            pPointer->public.on = FALSE;
+            
+            // Set button map.
+            InitPointerDeviceStruct((DevicePtr)pPointer, map, 3,
+                                    GetMotionHistory,
+                                    (PtrCtrlProcPtr)NoopDDA,
+                                    GetMotionHistorySize(), 7);
+            InitProximityClassDeviceStruct(pPointer);
+//			InitAbsoluteClassDeviceStruct(pPointer);
+			pPointer->name = strdup("pen");			
+            break;
+        case DEVICE_ON:
+            pPointer->public.on = TRUE;
+            AddEnabledDevice( darwinEventReadFD );
+            return Success;
+        case DEVICE_CLOSE:
+        case DEVICE_OFF:
+            pPointer->public.on = FALSE;
+            RemoveEnabledDevice(darwinEventReadFD);
+            return Success;
+    }
+    return Success;
+}
 
 /*
  * DarwinKeybdProc
@@ -376,6 +401,7 @@ static int DarwinKeybdProc( DeviceIntPtr pDev, int onoff )
     switch ( onoff ) {
         case DEVICE_INIT:
             DarwinKeyboardInit( pDev );
+			pDev->name = strdup("Quartz Keyboard");
             break;
         case DEVICE_ON:
             pDev->public.on = TRUE;
@@ -499,9 +525,11 @@ int DarwinParseModifierList(
 void InitInput( int argc, char **argv )
 {
     darwinPointer = AddInputDevice(DarwinMouseProc, TRUE);
-	darwinPointer->name = strdup("tablet");
     RegisterPointerDevice( darwinPointer );
 
+    darwinTablet = AddInputDevice(DarwinTabletProc, TRUE);
+    RegisterPointerDevice( darwinTablet );
+
     darwinKeyboard = AddInputDevice(DarwinKeybdProc, TRUE);
     RegisterKeyboardDevice( darwinKeyboard );
 
diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 6d2fbd0..4300b9f 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -71,6 +71,7 @@ extern io_connect_t     darwinParamConnect;
 extern int              darwinEventReadFD;
 extern int              darwinEventWriteFD;
 extern DeviceIntPtr     darwinPointer;
+extern DeviceIntPtr     darwinTablet;
 extern DeviceIntPtr     darwinKeyboard;
 
 // User preferences
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index e25ae84..7b3091d 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -365,7 +365,8 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	static int darwinFakeMouseButtonDown = 0;
 	static int darwinFakeMouseButtonMask = 0;
 	int i, num_events;
-
+	DeviceIntPtr dev;
+	
 //    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     
 	if(!darwinEvents) {
@@ -376,7 +377,10 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	int valuators[5] = {pointer_x, pointer_y, pressure * SCALEFACTOR_PRESSURE, 
 		      tilt_x * SCALEFACTOR_TILT, tilt_y * SCALEFACTOR_TILT};
 	
-		DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
+	if (pressure == 0 && tilt_x == 0 && tilt_y == 0) dev = darwinPointer;
+	else dev = darwinTablet;
+
+	DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
 			valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
 	if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
 		// Mimic multi-button mouse with modifier-clicks
@@ -410,9 +414,9 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	} 
 
     mieqEnqueue_lock(); {
-        num_events = GetPointerEvents(darwinEvents, darwinPointer, ev_type, ev_button, 
-                                      POINTER_ABSOLUTE, 0, 5, valuators);
-        for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+        num_events = GetPointerEvents(darwinEvents, dev, ev_type, ev_button, 
+                                      POINTER_ABSOLUTE, 0, dev==darwinTablet?5:2, valuators);
+        for(i=0; i<num_events; i++) mieqEnqueue (dev,&darwinEvents[i]);
         DarwinPokeEQ();
 
     } mieqEnqueue_unlock();
@@ -460,9 +464,9 @@ void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
 	}
 
     mieqEnqueue_lock(); {
-        num_events = GetProximityEvents(darwinEvents, darwinPointer, ev_type,
+        num_events = GetProximityEvents(darwinEvents, darwinTablet, ev_type,
                                         0, 5, valuators);
-        for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+        for(i=0; i<num_events; i++) mieqEnqueue (darwinTablet,&darwinEvents[i]);
         DarwinPokeEQ();
     } mieqEnqueue_unlock();
 }
commit 519581b0bab5cc6dac397877da485745f18c2120
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Tue Apr 29 23:00:09 2008 -0700

    xquartz: remove unused params from DarwinEQInit
    (cherry picked from commit 299a056737168ca1faefd675dce6d6ab13176be9)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index c18b575..6f47194 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -499,12 +499,13 @@ int DarwinParseModifierList(
 void InitInput( int argc, char **argv )
 {
     darwinPointer = AddInputDevice(DarwinMouseProc, TRUE);
+	darwinPointer->name = strdup("tablet");
     RegisterPointerDevice( darwinPointer );
 
     darwinKeyboard = AddInputDevice(DarwinKeybdProc, TRUE);
     RegisterKeyboardDevice( darwinKeyboard );
 
-    DarwinEQInit( (DevicePtr)darwinKeyboard, (DevicePtr)darwinPointer );
+    DarwinEQInit();
 
     QuartzInitInput(argc, argv);
 }
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index cd2b49a..e25ae84 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -307,7 +307,7 @@ static void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, in
     }
 }
 
-Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
+Bool DarwinEQInit(void) { 
     if (!darwinEvents)
         darwinEvents = (xEvent *)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
     if (!darwinEvents)
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index 4a619c9..ef8bf39 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -28,7 +28,7 @@
 #ifndef _DARWIN_EVENTS_H
 #define _DARWIN_EVENTS_H
 
-Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr);
+Bool DarwinEQInit(void);
 void DarwinEQEnqueue(const xEventPtr e);
 void DarwinEQPointerPost(DeviceIntPtr pDev, xEventPtr e);
 void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX);
commit d70487a4c09cfeb90d996ab40a23a74b2c15be6f
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Tue Apr 29 23:59:26 2008 -0700

    XQuartz: Fix to tablet-event handling code; we now scale
    more conservatively (to match Linux's Wacom driver) and
    we now receive all tablet-related events.
    (cherry picked from commit 588683cecca2cfc65a28de035cd6ee3d64ff59d2)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index e10e71e..646b9ef 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -49,6 +49,13 @@
 
 #define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
 
+#ifndef XSERVER_VERSION
+#define XSERVER_VERSION "?"
+#endif
+
+#define ProximityIn    0
+#define ProximityOut   1
+
 int X11EnableKeyEquivalents = TRUE;
 int quartzHasRoot = FALSE, quartzEnableRootless = TRUE;
 
@@ -852,27 +859,37 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
 	tilt_y = 0;
 
 	switch (type) {
-		case NSLeftMouseDown:    ev_button=1; ev_type=ButtonPress; goto handle_mouse;
-		case NSOtherMouseDown:   ev_button=2; ev_type=ButtonPress; goto handle_mouse;
-		case NSRightMouseDown:   ev_button=3; ev_type=ButtonPress; goto handle_mouse;
-		case NSLeftMouseUp:      ev_button=1; ev_type=ButtonRelease; goto handle_mouse;
-		case NSOtherMouseUp:     ev_button=2; ev_type=ButtonRelease; goto handle_mouse;
-		case NSRightMouseUp:     ev_button=3; ev_type=ButtonRelease; goto handle_mouse;
-		case NSLeftMouseDragged:  ev_button=1; ev_type=MotionNotify; goto handle_mouse;
-		case NSOtherMouseDragged: ev_button=2; ev_type=MotionNotify; goto handle_mouse;
-		case NSRightMouseDragged: ev_button=3; ev_type=MotionNotify; goto handle_mouse;
+		case NSLeftMouseDown:    ev_button=1; ev_type=ButtonPress; goto check_subtype;
+		case NSOtherMouseDown:   ev_button=2; ev_type=ButtonPress; goto check_subtype;
+		case NSRightMouseDown:   ev_button=3; ev_type=ButtonPress; goto check_subtype;
+		case NSLeftMouseUp:      ev_button=1; ev_type=ButtonRelease; goto check_subtype;
+		case NSOtherMouseUp:     ev_button=2; ev_type=ButtonRelease; goto check_subtype;
+		case NSRightMouseUp:     ev_button=3; ev_type=ButtonRelease; goto check_subtype;
+		case NSLeftMouseDragged:  ev_button=1; ev_type=MotionNotify; goto check_subtype;
+		case NSOtherMouseDragged: ev_button=2; ev_type=MotionNotify; goto check_subtype;
+		case NSRightMouseDragged: ev_button=3; ev_type=MotionNotify; goto check_subtype;
+		
+check_subtype:
+			if ([e subtype] != NSTabletPointEventSubtype) goto handle_mouse;
+			// fall through to get tablet data
 		case NSTabletPoint:
 			pressure = [e pressure];
 			tilt_x = [e tilt].x;
-			tilt_y = [e tilt].y; // fall through
+			tilt_y = [e tilt].y; 
+			// fall through to normal mouse handling
+
 		case NSMouseMoved: ev_button=0; ev_type=MotionNotify; goto handle_mouse;
-		handle_mouse:
 
-//      if ([e subtype] == NSTabletPointEventSubtype) pressure = [e pressure];
+handle_mouse:
 		DarwinSendPointerEvents(ev_type, ev_button, pointer_x, pointer_y,
 			pressure, tilt_x, tilt_y);
 		break;
 
+		case NSTabletProximity:
+			DarwinSendProximityEvents([e isEnteringProximity]?ProximityIn:ProximityOut,
+				pointer_x, pointer_y);
+		break;
+
 		case NSScrollWheel:
 			DarwinSendScrollEvents([e deltaX], [e deltaY], pointer_x, pointer_y,
 				pressure, tilt_x, tilt_y);
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 86e7704..cd2b49a 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -65,6 +65,10 @@ in this Software without prior written authorization from The Open Group.
 #define SCROLLWHEELLEFTFAKE  6
 #define SCROLLWHEELRIGHTFAKE 7
 
+/* These values were chosen to match the output of xinput under Linux */
+#define SCALEFACTOR_TILT        64.0
+#define SCALEFACTOR_PRESSURE    1000.0
+
 #define _APPLEWM_SERVER_
 #include "applewmExt.h"
 #include <X11/extensions/applewm.h>
@@ -362,26 +366,18 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	static int darwinFakeMouseButtonMask = 0;
 	int i, num_events;
 
-    //DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+//    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     
 	if(!darwinEvents) {
 		ErrorF("DarwinSendPointerEvents called before darwinEvents was initialized\n");
 		return;
 	}
-	/* I can't find a spec for this, but at least GTK expects that tablets are
-     just like mice, except they have either one or three extra valuators, in this
-     order:
-     
-     X coord, Y coord, pressure, X tilt, Y tilt
-     Pressure and tilt should be represented natively as floats; unfortunately,
-     we can't do that.  Again, GTK seems to record the min/max of each valuator,
-     and then perform scaling back to float itself using that info. Soo.... */
-
-	int valuators[5] = {pointer_x, pointer_y, 
-		      pressure * INT32_MAX * 1.0f, 
-		      tilt_x * INT32_MAX * 1.0f, 
-		      tilt_y * INT32_MAX * 1.0f};
 
+	int valuators[5] = {pointer_x, pointer_y, pressure * SCALEFACTOR_PRESSURE, 
+		      tilt_x * SCALEFACTOR_TILT, tilt_y * SCALEFACTOR_TILT};
+	
+		DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
+			valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
 	if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
 		// Mimic multi-button mouse with modifier-clicks
 		// If both sets of modifiers are pressed,
@@ -450,16 +446,16 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
     } mieqEnqueue_unlock();
 }
 
-void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
-			       float pressure, float tilt_x, float tilt_y) {
+void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
 	int i, num_events;
-	int valuators[5] = {pointer_x, pointer_y, 
-		      pressure * INT32_MAX * 1.0f, 
-		      tilt_x * INT32_MAX * 1.0f, 
-		      tilt_y * INT32_MAX * 1.0f};
 
+	// tilt and pressure have no meaning for a Prox event
+	int valuators[5] = {pointer_x, pointer_y, 0, 0, 0};  
+
+	DEBUG_LOG("DarwinSendProximityEvents(%d, %d, %d)\n", ev_type, pointer_x, pointer_y);
+	
 	if(!darwinEvents) {
-		ErrorF("DarwinSendProximityvents called before darwinEvents was initialized\n");
+		ErrorF("DarwinSendProximityEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index dd3f81c..4a619c9 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -34,8 +34,7 @@ void DarwinEQPointerPost(DeviceIntPtr pDev, xEventPtr e);
 void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX);
 void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y,
 			     float pressure, float tilt_x, float tilt_y);
-void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
-			       float pressure, float tilt_x, float tilt_y);
+void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y);
 void DarwinSendKeyboardEvents(int ev_type, int keycode);
 void DarwinSendScrollEvents(float count_x, float count_y, int pointer_x, int pointer_y,
 			    float pressure, float tilt_x, float tilt_y);
commit f65a1a62f9eac2f6620d5d469dbf6c79b2eadab7
Author: Hong Liu <hong.liu at intel.com>
Date:   Tue Apr 29 09:00:11 2008 -0700

    Keep rotation wrappers in place while transforms are in use
    
    LeaveVT/EnterVT cycles will free/realloc shadow frame buffers. Because of
    this, the presense/absence of that data is insufficient to know whether
    the screen function wrappers are necessary. Instead, the 'transform_in_use'
    flag should be used.
    
    This patch also adds 'xf86RotateFreeShadow' for drivers to use at LeaveVT
    time to free the rotation data; it will be reallocated on EnterVT.

diff --git a/hw/xfree86/loader/xf86sym.c b/hw/xfree86/loader/xf86sym.c
index 24fc44c..9833d34 100644
--- a/hw/xfree86/loader/xf86sym.c
+++ b/hw/xfree86/loader/xf86sym.c
@@ -942,6 +942,7 @@ _X_HIDDEN void *xfree86LookupTab[] = {
     SYMFUNC(xf86CrtcDestroy)
     SYMFUNC(xf86CrtcInUse)
     SYMFUNC(xf86CrtcSetScreenSubpixelOrder)
+    SYMFUNC(xf86RotateFreeShadow)
     SYMFUNC(xf86RotateCloseScreen)
     SYMFUNC(xf86CrtcRotate)
     SYMFUNC(xf86CrtcSetMode)
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
index 2d723a5..83b1f13 100644
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -665,6 +665,12 @@ Bool
 xf86CrtcRotate (xf86CrtcPtr crtc, DisplayModePtr mode, Rotation rotation);
 
 /*
+ * free shadow memory allocated for all crtcs
+ */
+void
+xf86RotateFreeShadow(ScrnInfoPtr pScrn);
+
+/*
  * Clean up rotation during CloseScreen
  */
 void
diff --git a/hw/xfree86/modes/xf86Rotate.c b/hw/xfree86/modes/xf86Rotate.c
index e2d6295..8f34032 100644
--- a/hw/xfree86/modes/xf86Rotate.c
+++ b/hw/xfree86/modes/xf86Rotate.c
@@ -457,8 +457,7 @@ xf86RotateDestroy (xf86CrtcPtr crtc)
     }
 
     for (c = 0; c < xf86_config->num_crtc; c++)
-	if (xf86_config->crtc[c]->rotatedPixmap ||
-	    xf86_config->crtc[c]->rotatedData)
+	if (xf86_config->crtc[c]->transform_in_use)
 	    return;
 
     /*
@@ -479,6 +478,24 @@ xf86RotateDestroy (xf86CrtcPtr crtc)
 }
 
 _X_EXPORT void
+xf86RotateFreeShadow(ScrnInfoPtr pScrn)
+{
+    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
+    int c;
+
+   for (c = 0; c < config->num_crtc; c++) {
+       xf86CrtcPtr crtc = config->crtc[c];
+
+       if (crtc->rotatedPixmap || crtc->rotatedData) {
+	   crtc->funcs->shadow_destroy(crtc, crtc->rotatedPixmap,
+				crtc->rotatedData);
+	   crtc->rotatedPixmap = NULL;
+	   crtc->rotatedData = NULL;
+       }
+   }
+}
+
+_X_EXPORT void
 xf86RotateCloseScreen (ScreenPtr screen)
 {
     ScrnInfoPtr		scrn = xf86Screens[screen->myNum];
commit e48f6bcd94b310e5c79939bdb1703f9555a3cdd1
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 29 08:30:51 2008 -0700

    Debug XKB bits

diff --git a/xkb/ddxLoad.c b/xkb/ddxLoad.c
index d80ce62..c95ef4d 100644
--- a/xkb/ddxLoad.c
+++ b/xkb/ddxLoad.c
@@ -75,6 +75,9 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
 #define PATHSEPARATOR "/"
 #endif
 
+#define DEBUG
+#define xkbDebugFlags	65535
+
 #ifdef WIN32
 
 #include <X11/Xwindows.h>
@@ -350,11 +353,12 @@ unsigned	missing;
     if ((names->keycodes==NULL)&&(names->types==NULL)&&
 	(names->compat==NULL)&&(names->symbols==NULL)&&
 	(names->geometry==NULL)) {
+	LogMessage (X_ERROR, "XKB: missing XKB definition\n");
         return 0;
     }
     else if (!XkbDDXCompileKeymapByNames(xkb,names,want,need,
                                          nameRtrn,nameRtrnLen)){
-	DebugF("Couldn't compile keymap file\n");
+	LogMessage (X_ERROR, "Couldn't compile keymap file\n");
 	return 0;
     }
     file= XkbDDXOpenConfigFile(nameRtrn,fileName,PATH_MAX);
commit 4c7ca04362ca74cd54d76f6a05978b64c7598ead
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 29 08:30:17 2008 -0700

    kludge around glx crashes during server exit

diff --git a/GL/glx/glxext.c b/GL/glx/glxext.c
index 85d8deb..4519555 100644
--- a/GL/glx/glxext.c
+++ b/GL/glx/glxext.c
@@ -378,7 +378,7 @@ void glxSuspendClients(void)
     int i;
 
     for (i = 1; i < currentMaxClients; i++) {
-	if (clients[i] && glxGetClient(clients[i])->inUse)
+	if (clients[i] && clients[i]->osPrivate && glxGetClient(clients[i])->inUse)
 	    IgnoreClient(clients[i]);
     }
 
commit 15cd90455813f67b8e98e5164c6ae85bf42739a7
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 29 08:29:42 2008 -0700

    Handle transform failure when computing shadow damage area.
    
    PictureTransformBounds can fail, when this happens, damage the entire screen
    so that the shadow gets repainted correctly.

diff --git a/hw/xfree86/modes/xf86Rotate.c b/hw/xfree86/modes/xf86Rotate.c
index 8925fad..0090658 100644
--- a/hw/xfree86/modes/xf86Rotate.c
+++ b/hw/xfree86/modes/xf86Rotate.c
@@ -177,7 +177,17 @@ xf86CrtcDamageShadow (xf86CrtcPtr crtc)
     damage_box.x2 = crtc->mode.HDisplay;
     damage_box.y1 = 0;
     damage_box.y2 = crtc->mode.VDisplay;
-    PictureTransformBounds (&damage_box, &crtc->crtc_to_framebuffer);
+    if (1 || !PictureTransformBounds (&damage_box, &crtc->crtc_to_framebuffer))
+    {
+	damage_box.x1 = 0;
+	damage_box.y1 = 0;
+	damage_box.x2 = pScreen->width;
+	damage_box.y2 = pScreen->height;
+    }
+    if (damage_box.x1 < 0) damage_box.x1 = 0;
+    if (damage_box.y1 < 0) damage_box.y1 = 0;
+    if (damage_box.x2 > pScreen->width) damage_box.x2 = pScreen->width;
+    if (damage_box.y2 > pScreen->height) damage_box.y2 = pScreen->height;
     REGION_INIT (pScreen, &damage_region, &damage_box, 1);
     DamageDamageRegion (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
 			&damage_region);
diff --git a/render/matrix.c b/render/matrix.c
index 603281e..560ee94 100644
--- a/render/matrix.c
+++ b/render/matrix.c
@@ -84,7 +84,6 @@ _X_EXPORT Bool
 PictureTransformPoint (PictTransformPtr transform,
 		       PictVectorPtr	vector)
 {
-    PictVector	    result;
     int		    i, j;
     xFixed_32_32    partial;
     xFixed_34_30    v[3];
@@ -227,7 +226,7 @@ PictureTransformTranslate (PictTransformPtr forward,
     return TRUE;
 }
 
-_X_EXPORT void
+_X_EXPORT Bool
 PictureTransformBounds (BoxPtr b, PictTransformPtr matrix)
 {
     PictVector	v[4];
@@ -240,7 +239,8 @@ PictureTransformBounds (BoxPtr b, PictTransformPtr matrix)
     v[3].vector[0] = F (b->x1);    v[3].vector[1] = F (b->y2);	v[3].vector[2] = F(1);
     for (i = 0; i < 4; i++)
     {
-	PictureTransformPoint (matrix, &v[i]);
+	if (!PictureTransformPoint (matrix, &v[i]))
+	    return FALSE;
 	x1 = xFixedToInt (v[i].vector[0]);
 	y1 = xFixedToInt (v[i].vector[1]);
 	x2 = xFixedToInt (xFixedCeil (v[i].vector[0]));
@@ -258,6 +258,7 @@ PictureTransformBounds (BoxPtr b, PictTransformPtr matrix)
 	    if (y2 > b->y2) b->y2 = y2;
 	}
     }
+    return TRUE;
 }
 
 _X_EXPORT Bool
diff --git a/render/picturestr.h b/render/picturestr.h
index c993e93..ed77fe3 100644
--- a/render/picturestr.h
+++ b/render/picturestr.h
@@ -727,7 +727,7 @@ PictureTransformTranslate (PictTransformPtr forward,
 			   PictTransformPtr reverse,
 			   xFixed tx, xFixed ty);
 
-void
+Bool
 PictureTransformBounds (BoxPtr b, PictTransformPtr matrix);
 
 Bool
commit b93c9a1553f981e6b38dd0a33db8f766847ce232
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 29 08:27:57 2008 -0700

    Fix up kdrive build (again)

diff --git a/configure.ac b/configure.ac
index 8e890f6..07a334c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1962,7 +1962,7 @@ if test "$KDRIVE" = yes; then
     
     KDRIVE_CFLAGS="$XSERVER_CFLAGS -DHAVE_KDRIVE_CONFIG_H $TSLIB_CFLAGS"
 
-    KDRIVE_PURE_LIBS="$FB_LIB $MI_LIB $FIXES_LIB $XEXT_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $GLX_LIBS $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $OS_LIB"
+    KDRIVE_PURE_LIBS="$FB_LIB $MI_LIB $FIXES_LIB $XEXT_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $GLX_LIBS $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_SHADOW_LIB $MIEXT_DAMAGE_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $OS_LIB"
     KDRIVE_LIB='$(top_builddir)/hw/kdrive/src/libkdrive.a'
     case $host_os in
 	*linux*)
@@ -1973,7 +1973,7 @@ if test "$KDRIVE" = yes; then
     KDRIVE_STUB_LIB='$(top_builddir)/hw/kdrive/src/libkdrivestubs.a'
     KDRIVE_LOCAL_LIBS="$TSLIB_LIBS $DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $FB_LIB $MI_LIB $KDRIVE_PURE_LIBS"
-    KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
+    KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB $XEXT_LIB"
     KDRIVE_LIBS="$KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
 
     # check if we can build Xephyr
commit d5ab89f4f1acbe2614036e8934122185ac0f81ee
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 15:52:24 2008 -0700

    XQuartz: Unset CFProcessPath... blech
    (cherry picked from commit ce4fbfbc75c62a092214d140c7550279aebe69ef)

diff --git a/hw/xquartz/quartzStartup.c b/hw/xquartz/quartzStartup.c
index 7b6a1a6..a4472e6 100644
--- a/hw/xquartz/quartzStartup.c
+++ b/hw/xquartz/quartzStartup.c
@@ -98,6 +98,12 @@ int main(int argc, char **argv, char **envp) {
     int         i;
     int         fd[2];
 
+    /* Unset CFProcessPath, so our children don't inherit this kludge we need
+     * to load our nib.  If an xterm gets this set, then it fails to
+     * 'open hi.txt' properly.
+     */
+    unsetenv("CFProcessPath");
+    
     // Make a pipe to pass events
     assert( pipe(fd) == 0 );
     darwinEventReadFD = fd[0];
commit 0c2312b21b6700c1425baccaf9c26150b4f0fd6a
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 15:28:21 2008 -0700

    XQuartz: xprIsX11Window can be called from the Appkit thread (see X11Application.m)
    (cherry picked from commit 22cf72437601c07b8a6c744b4f2f1f4cd6713e60)

diff --git a/hw/xquartz/xpr/xprFrame.c b/hw/xquartz/xpr/xprFrame.c
index edb4128..9fa9424 100644
--- a/hw/xquartz/xpr/xprFrame.c
+++ b/hw/xquartz/xpr/xprFrame.c
@@ -453,8 +453,6 @@ xprGetXWindow(xp_window_id wid)
 {
     RootlessWindowRec *winRec;
 
-    TA_SERVER();
-    
     if (window_hash == NULL)
         return NULL;
 
@@ -474,8 +472,6 @@ xprGetXWindowFromAppKit(int windowNumber)
     Bool ret;
     xp_window_id wid;
 
-    TA_SERVER();
-    
     if (window_hash == NULL)
         return FALSE;
 
@@ -507,8 +503,6 @@ xprIsX11Window(void *nsWindow, int windowNumber)
     Bool ret;
     xp_window_id wid;
 
-    TA_SERVER();
-    
     if (window_hash == NULL)
         return FALSE;
 
commit c3dc4bdbb018c0606d561e2dfb9a36e9297fa312
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 15:42:02 2008 -0700

    XQuartz: Disabled DPMS extension
    (cherry picked from commit 1448fed9b6d484f471b9b2982c76ca921a9273b9)

diff --git a/configure.ac b/configure.ac
index 67606c7..f695551 100644
--- a/configure.ac
+++ b/configure.ac
@@ -524,11 +524,11 @@ AC_ARG_ENABLE(glx-tls,        AS_HELP_STRING([--enable-glx-tls], [Build GLX with
 
 dnl Extensions.
 AC_ARG_ENABLE(registry,       AS_HELP_STRING([--disable-registry], [Build string registry module (default: enabled)]), [XREGISTRY=$enableval], [XREGISTRY=yes])
-AC_ARG_ENABLE(composite,      AS_HELP_STRING([--disable-composite], [Build Composite extension (default: enabled)]), [COMPOSITE=$enableval], [COMPOSITE=auto])
+AC_ARG_ENABLE(composite,      AS_HELP_STRING([--disable-composite], [Build Composite extension (default: enabled)]), [COMPOSITE=$enableval], [COMPOSITE=yes])
 AC_ARG_ENABLE(mitshm,         AS_HELP_STRING([--disable-shm], [Build SHM extension (default: enabled)]), [MITSHM=$enableval], [MITSHM=yes])
 AC_ARG_ENABLE(xres,           AS_HELP_STRING([--disable-xres], [Build XRes extension (default: enabled)]), [RES=$enableval], [RES=yes])
 AC_ARG_ENABLE(xtrap,          AS_HELP_STRING([--disable-xtrap], [Build XTrap extension (default: enabled)]), [XTRAP=$enableval], [XTRAP=yes])
-AC_ARG_ENABLE(record,         AS_HELP_STRING([--disable-record], [Build Record extension (default: disabled)]), [RECORD=$enableval], [RECORD=no])
+AC_ARG_ENABLE(record,         AS_HELP_STRING([--enable-record], [Build Record extension (default: disabled)]), [RECORD=$enableval], [RECORD=no])
 AC_ARG_ENABLE(xv,             AS_HELP_STRING([--disable-xv], [Build Xv extension (default: enabled)]), [XV=$enableval], [XV=yes])
 AC_ARG_ENABLE(xvmc,           AS_HELP_STRING([--disable-xvmc], [Build XvMC extension (default: enabled)]), [XVMC=$enableval], [XVMC=yes])
 AC_ARG_ENABLE(dga,            AS_HELP_STRING([--disable-dga], [Build DGA extension (default: auto)]), [DGA=$enableval], [DGA=auto])
@@ -644,6 +644,40 @@ XORG_CHECK_LINUXDOC
 dnl Handle installing libxf86config
 AM_CONDITIONAL(INSTALL_LIBXF86CONFIG, [test "x$INSTALL_LIBXF86CONFIG" = xyes])
 
+dnl XQuartz DDX Detection... Yes, it's ugly to have it here... but we need to handle this early on
+case $host_os in
+	darwin*)
+		if test x$XQUARTZ = xauto; then
+			AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
+		 		save_LDFLAGS=$LDFLAGS
+				LDFLAGS="$LDFLAGS -framework Carbon"
+				AC_LINK_IFELSE([char FSFindFolder(); int main() { FSFindFolder(); return 0;}],
+				[xorg_cv_Carbon_framework=yes],
+				[xorg_cv_Carbon_framework=no])
+			LDFLAGS=$save_LDFLAGS])
+                
+			if test "X$xorg_cv_Carbon_framework" = Xyes; then
+				XQUARTZ=yes
+			else
+				XQUARTZ=no
+			fi
+		fi
+
+		if test "x$XQUARTZ" = xyes ; then
+			XQUARTZ=yes
+			XVFB=no
+			XNEST=no
+
+			COMPOSITE=no
+			DGA=no
+			DPMSExtension=no
+			XF86BIGFONT=no
+			XF86MISC=no
+			XF86VIDMODE=no
+		fi
+		;;
+esac
+
 dnl ---------------------------------------------------------------------------
 dnl Extension section
 dnl ---------------------------------------------------------------------------
@@ -780,18 +814,6 @@ if test "x$XREGISTRY" = xyes; then
 	AC_DEFINE(XREGISTRY, 1, [Build registry module])
 fi
 
-dnl XQuartz DDX Detection... Yes, it's ugly to have it here... but we need to disable COMPOSITE for 
-if test "x$COMPOSITE" = xauto; then
-	case $host_os in
-		darwin*)
-			test "x$XQUARTZ" = xyes -o "x$XQUARTZ" = xauto && COMPOSITE=no
-			;;
-		*)
-			COMPOSITE=yes
-			;;
-	esac
-fi
-
 AM_CONDITIONAL(COMPOSITE, [test "x$COMPOSITE" = xyes])
 if test "x$COMPOSITE" = xyes; then
 	AC_DEFINE(COMPOSITE, 1, [Support Composite Extension])
@@ -1706,22 +1728,6 @@ AM_CONDITIONAL(XWIN_RANDR, [test "x$XWIN" = xyes])
 AM_CONDITIONAL(XWIN_XV, [test "x$XWIN" = xyes && test "x$XV" = xyes])
 
 dnl Darwin / OS X DDX
-if test "X$XQUARTZ" = Xauto; then
-	AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
-	 	save_LDFLAGS=$LDFLAGS
-		LDFLAGS="$LDFLAGS -framework Carbon"
-		AC_LINK_IFELSE([char FSFindFolder(); int main() { FSFindFolder(); return 0;}],
-			[xorg_cv_Carbon_framework=yes],
-			[xorg_cv_Carbon_framework=no])
-		LDFLAGS=$save_LDFLAGS])
-                
-	if test "X$xorg_cv_Carbon_framework" = Xyes; then
-		XQUARTZ=yes
-	else
-		XQUARTZ=no
-	fi
-fi
-
 if test "x$XQUARTZ" = xyes; then
 	AC_DEFINE(XQUARTZ,1,[Have Quartz])
 	AC_DEFINE(ROOTLESS,1,[Build Rootless code])
@@ -1733,23 +1739,6 @@ if test "x$XQUARTZ" = xyes; then
 	AC_CHECK_LIB([Xplugin],[xp_init],[:])
 
 	CFLAGS="${CFLAGS} -DROOTLESS_WORKAROUND -DNO_ALLOCA"
-
-	if test "x$XF86MISC" = xyes || test "x$XF86MISC" = xauto; then
-		AC_MSG_NOTICE([Disabling XF86Misc extension])
-		XF86MISC=no
-	fi
-	if test "x$XF86VIDMODE" = xyes || test "x$XF86VIDMODE" = xauto; then
-		AC_MSG_NOTICE([Disabling XF86VidMode extension])
-		XF86VIDMODE=no
-	fi
-	if test "x$XF86BIGFONT" = xyes || test "x$XF86BIGFONT" = xauto; then
-		AC_MSG_NOTICE([Disabling XF86BigFont extension])
-		XF86BIGFONT=no
-	fi
-	if test "x$DGA" = xyes || test "x$DGA" = xauto; then
-		AC_MSG_NOTICE([Disabling DGA extension])
-		DGA=no
-	fi
 fi
 
 # Support for objc in autotools is minimal and not documented.
diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index 1465a52..b2674be 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -19,7 +19,6 @@ DIST_SUBDIRS = GL xpr bundle
 libXquartz_la_SOURCES = \
 	$(top_srcdir)/fb/fbcmap_mi.c \
 	$(top_srcdir)/mi/miinitext.c \
-	$(top_srcdir)/Xext/dpmsstubs.c \
 	X11Application.m \
 	X11Controller.m \
 	applewm.c \
commit 07382a70c7ac9807dfb31821a4763bea2309bde6
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 12:36:54 2008 -0700

    XQuartz: Added thread debugging to xprFrame.c
    (cherry picked from commit 41542502b321c697271c1752525b600872b6df96)

diff --git a/hw/xquartz/xpr/xprFrame.c b/hw/xquartz/xpr/xprFrame.c
index 901efca..edb4128 100644
--- a/hw/xquartz/xpr/xprFrame.c
+++ b/hw/xquartz/xpr/xprFrame.c
@@ -43,6 +43,8 @@
 #include <X11/Xatom.h>
 #include "windowstr.h"
 
+#include "threadSafety.h"
+
 #include <pthread.h>
 
 #define DEFINE_ATOM_HELPER(func,atom_name)                      \
@@ -69,7 +71,8 @@ static inline xp_error
 xprConfigureWindow(xp_window_id id, unsigned int mask,
                    const xp_window_changes *values)
 {
-  //  ErrorF("xprConfigureWindow()\n");
+    TA_SERVER();
+
     if (!no_configure_window)
         return xp_configure_window(id, mask, values);
     else
@@ -84,6 +87,8 @@ xprSetNativeProperty(RootlessWindowPtr pFrame)
     unsigned int native_id;
     long data;
 
+    TA_SERVER();
+    
     err = xp_get_native_window((xp_window_id) pFrame->wid, &native_id);
     if (err == Success)
     {
@@ -108,6 +113,8 @@ xprCreateFrame(RootlessWindowPtr pFrame, ScreenPtr pScreen,
     unsigned int mask = 0;
     xp_error err;
 
+    TA_SERVER();
+    
     wc.x = newX;
     wc.y = newY;
     wc.width = pFrame->width;
@@ -169,6 +176,8 @@ xprCreateFrame(RootlessWindowPtr pFrame, ScreenPtr pScreen,
 void
 xprDestroyFrame(RootlessFrameID wid)
 {
+    TA_SERVER();
+    
     pthread_mutex_lock(&window_hash_mutex);
     x_hash_table_remove(window_hash, wid);
     pthread_mutex_unlock(&window_hash_mutex);
@@ -183,6 +192,8 @@ xprDestroyFrame(RootlessFrameID wid)
 void
 xprMoveFrame(RootlessFrameID wid, ScreenPtr pScreen, int newX, int newY)
 {
+    TA_SERVER();
+    
     xp_window_changes wc;
 
     wc.x = newX;
@@ -202,6 +213,8 @@ xprResizeFrame(RootlessFrameID wid, ScreenPtr pScreen,
 {
     xp_window_changes wc;
 
+    TA_SERVER();
+    
     wc.x = newX;
     wc.y = newY;
     wc.width = newW;
@@ -223,7 +236,9 @@ xprRestackFrame(RootlessFrameID wid, RootlessFrameID nextWid)
 {
     xp_window_changes wc;
 
-    /* Stack frame below nextWid it if it exists, or raise
+    TA_SERVER();
+    
+   /* Stack frame below nextWid it if it exists, or raise
        frame above everything otherwise. */
 
     if (nextWid == NULL)
@@ -249,6 +264,8 @@ xprReshapeFrame(RootlessFrameID wid, RegionPtr pShape)
 {
     xp_window_changes wc;
 
+    TA_SERVER();
+    
     if (pShape != NULL)
     {
         wc.shape_nrects = REGION_NUM_RECTS(pShape);
@@ -274,6 +291,8 @@ xprUnmapFrame(RootlessFrameID wid)
 {
     xp_window_changes wc;
 
+    TA_SERVER();
+    
     wc.stack_mode = XP_UNMAPPED;
     wc.sibling = 0;
 
@@ -292,6 +311,8 @@ xprStartDrawing(RootlessFrameID wid, char **pixelData, int *bytesPerRow)
     unsigned int rowbytes[2];
     xp_error err;
 
+    TA_SERVER();
+    
     err = xp_lock_window((xp_window_id) wid, NULL, NULL, data, rowbytes, NULL);
     if (err != Success)
         FatalError("Could not lock window %i for drawing.", (int) wid);
@@ -307,6 +328,8 @@ xprStartDrawing(RootlessFrameID wid, char **pixelData, int *bytesPerRow)
 void
 xprStopDrawing(RootlessFrameID wid, Bool flush)
 {
+    TA_SERVER();
+    
     xp_unlock_window((xp_window_id) wid, flush);
 }
 
@@ -317,6 +340,8 @@ xprStopDrawing(RootlessFrameID wid, Bool flush)
 void
 xprUpdateRegion(RootlessFrameID wid, RegionPtr pDamage)
 {
+    TA_SERVER();
+    
     xp_flush_window((xp_window_id) wid);
 }
 
@@ -328,6 +353,8 @@ void
 xprDamageRects(RootlessFrameID wid, int nrects, const BoxRec *rects,
                int shift_x, int shift_y)
 {
+    TA_SERVER();
+    
     xp_mark_window((xp_window_id) wid, nrects, rects, shift_x, shift_y);
 }
 
@@ -341,6 +368,8 @@ xprSwitchWindow(RootlessWindowPtr pFrame, WindowPtr oldWin)
 {
     DeleteProperty(serverClient, oldWin, xa_native_window_id());
 
+    TA_SERVER();
+    
     xprSetNativeProperty(pFrame);
 }
 
@@ -352,6 +381,8 @@ Bool xprDoReorderWindow(RootlessWindowPtr pFrame)
 {
     WindowPtr pWin = pFrame->win;
 
+    TA_SERVER();
+    
     return AppleWMDoReorderWindow(pWin);
 }
 
@@ -364,6 +395,8 @@ void
 xprCopyWindow(RootlessFrameID wid, int dstNrects, const BoxRec *dstRects,
               int dx, int dy)
 {
+    TA_SERVER();
+    
     xp_copy_window((xp_window_id) wid, (xp_window_id) wid,
                    dstNrects, dstRects, dx, dy);
 }
@@ -398,6 +431,8 @@ xprInit(ScreenPtr pScreen)
 {
     RootlessInit(pScreen, &xprRootlessProcs);
 
+    TA_SERVER();
+    
     rootless_CopyBytes_threshold = xp_copy_bytes_threshold;
     rootless_FillBytes_threshold = xp_fill_bytes_threshold;
     rootless_CompositePixels_threshold = xp_composite_area_threshold;
@@ -418,6 +453,8 @@ xprGetXWindow(xp_window_id wid)
 {
     RootlessWindowRec *winRec;
 
+    TA_SERVER();
+    
     if (window_hash == NULL)
         return NULL;
 
@@ -437,6 +474,8 @@ xprGetXWindowFromAppKit(int windowNumber)
     Bool ret;
     xp_window_id wid;
 
+    TA_SERVER();
+    
     if (window_hash == NULL)
         return FALSE;
 
@@ -468,6 +507,8 @@ xprIsX11Window(void *nsWindow, int windowNumber)
     Bool ret;
     xp_window_id wid;
 
+    TA_SERVER();
+    
     if (window_hash == NULL)
         return FALSE;
 
@@ -498,6 +539,8 @@ xprHideWindows(Bool hide)
     int screen;
     WindowPtr pRoot, pWin;
 
+    TA_SERVER();
+    
     for (screen = 0; screen < screenInfo.numScreens; screen++) {
         pRoot = WindowTable[screenInfo.screens[screen]->myNum];
         RootlessFrameID prevWid = NULL;
commit 8349732a6720652bfbad7874a952be73a0e8e77b
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Mon Apr 28 21:09:35 2008 +0200

    EXA: Try to accelerate non-antialiased text via the glyph cache as well.
    
    Treat 1 bit glyphs and masks as PICT_a8 in the glyph cache. We're not able to
    accelerate them otherwise.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 08ec097..ff665d5 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -374,6 +374,10 @@ exaGlyphCacheUploadGlyph(ScreenPtr         pScreen,
     if (exaPixmapIsOffscreen(pGlyphPixmap))
 	return FALSE;
 
+    /* UploadToScreen only works if bpp match */
+    if (pGlyphPixmap->drawable.bitsPerPixel != pCachePixmap->drawable.bitsPerPixel)
+	return FALSE;
+
     /* cache pixmap must be offscreen. */
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = FALSE;
@@ -524,6 +528,9 @@ exaBufferGlyph(ScreenPtr         pScreen,
 
     if (buffer->count == GLYPH_BUFFER_SIZE)
 	return ExaGlyphNeedFlush;
+
+    if (PICT_FORMAT_BPP(format) == 1)
+	format = PICT_a8;
     
     for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
 	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
@@ -796,6 +803,14 @@ exaGlyphs (CARD8 	 op,
 	    return;
 	width = extents.x2 - extents.x1;
 	height = extents.y2 - extents.y1;
+
+	if (maskFormat->depth == 1) {
+	    PictFormatPtr a8Format = PictureMatchFormat (pScreen, 8, PICT_a8);
+
+	    if (a8Format)
+		maskFormat = a8Format;
+	}
+
 	pMaskPixmap = (*pScreen->CreatePixmap) (pScreen, width, height,
 						maskFormat->depth,
 						CREATE_PIXMAP_USAGE_SCRATCH);
commit a65d530040bb561ba88c5d8c71633a7c0bf11e89
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Mon Apr 28 21:03:12 2008 +0200

    EXA: Accumulate glyphs whenever possible, for full benefits of the glyph cache.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index b618365..08ec097 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -662,6 +662,79 @@ GlyphExtents (int		nlist,
     }
 }
 
+/**
+ * Returns TRUE if the glyphs in the lists intersect.  Only checks based on
+ * bounding box, which appears to be good enough to catch most cases at least.
+ */
+static Bool
+exaGlyphsIntersect(int nlist, GlyphListPtr list, GlyphPtr *glyphs)
+{
+    int x1, x2, y1, y2;
+    int n;
+    GlyphPtr glyph;
+    int x, y;
+    BoxRec extents;
+    Bool first = TRUE;
+
+    x = 0;
+    y = 0;
+    while (nlist--) {
+       x += list->xOff;
+       y += list->yOff;
+       n = list->len;
+       list++;
+       while (n--) {
+           glyph = *glyphs++;
+
+           if (glyph->info.width == 0 || glyph->info.height == 0) {
+               x += glyph->info.xOff;
+               y += glyph->info.yOff;
+               continue;
+           }
+
+           x1 = x - glyph->info.x;
+           if (x1 < MINSHORT)
+               x1 = MINSHORT;
+           y1 = y - glyph->info.y;
+           if (y1 < MINSHORT)
+               y1 = MINSHORT;
+           x2 = x1 + glyph->info.width;
+           if (x2 > MAXSHORT)
+               x2 = MAXSHORT;
+           y2 = y1 + glyph->info.height;
+           if (y2 > MAXSHORT)
+               y2 = MAXSHORT;
+
+           if (first) {
+               extents.x1 = x1;
+               extents.y1 = y1;
+               extents.x2 = x2;
+               extents.y2 = y2;
+               first = FALSE;
+           } else {
+               if (x1 < extents.x2 && x2 > extents.x1 &&
+                   y1 < extents.y2 && y2 > extents.y1)
+               {
+                   return TRUE;
+               }
+
+               if (x1 < extents.x1)
+                  extents.x1 = x1;
+               if (x2 > extents.x2)
+                   extents.x2 = x2;
+               if (y1 < extents.y1)
+                   extents.y1 = y1;
+               if (y2 > extents.y2)
+                   extents.y2 = y2;
+           }
+           x += glyph->info.xOff;
+           y += glyph->info.yOff;
+       }
+    }
+
+    return FALSE;
+}
+
 #define NeedsComponent(f) (PICT_FORMAT_A(f) != 0 && PICT_FORMAT_RGB(f) != 0)
 
 void
@@ -689,6 +762,29 @@ exaGlyphs (CARD8 	 op,
     CARD32	component_alpha;
     ExaGlyphBuffer buffer;
 
+    /* If we don't have a mask format but all the glyphs have the same format
+     * and don't intersect, use the glyph format as mask format for the full
+     * benefits of the glyph cache.
+     */
+    if (!maskFormat) {
+       Bool sameFormat = TRUE;
+       int i;
+
+       maskFormat = list[0].format;
+
+       for (i = 0; i < nlist; i++) {
+           if (maskFormat->format != list[i].format->format) {
+               sameFormat = FALSE;
+               break;
+           }
+       }
+
+       if (!sameFormat || (maskFormat->depth != 1 &&
+			   exaGlyphsIntersect(nlist, list, glyphs))) {
+	   maskFormat = NULL;
+       }
+    }
+
     if (maskFormat)
     {
 	GCPtr	    pGC;
commit e7eaac59c424a205dd106fc7d70734ff4b390f28
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Mon Apr 28 21:00:55 2008 +0200

    EXA: Glyph cache upload tweaks.
    
    Track damage after using UploadToScreen directly.
    
    Don't waste any effort on empty glyphs.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 95ff4d8..b618365 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -394,6 +394,12 @@ exaGlyphCacheUploadGlyph(ScreenPtr         pScreen,
 				       pExaPixmap->sys_pitch))
 	return FALSE;
 
+    exaPixmapDirty (pCachePixmap,
+		    CACHE_X(pos) + cacheXoff,
+		    CACHE_Y(pos) + cacheYoff,
+		    CACHE_X(pos) + cacheXoff + pGlyph->info.width,
+		    CACHE_Y(pos) + cacheYoff + pGlyph->info.height);
+
     return TRUE;
 }
 
@@ -737,7 +743,8 @@ exaGlyphs (CARD8 	 op,
 	    glyph = *glyphs++;
 	    pPicture = GlyphPicture (glyph)[pScreen->myNum];
 
-	    if (exaBufferGlyph(pScreen, &buffer, glyph, x, y) == ExaGlyphNeedFlush)
+	    if (glyph->info.width > 0 && glyph->info.height > 0 &&
+		exaBufferGlyph(pScreen, &buffer, glyph, x, y) == ExaGlyphNeedFlush)
 	    {
 		if (maskFormat)
 		    exaGlyphsToMask(pMask, &buffer);
commit cc08c06665ffe29ad44d023d75d0f86e5338875d
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:55 2008 +0200

    EXA: Use UploadToScreen() for uploads to glyph cache
    
    When possible, use UploadToScreen() rather than CompositePicture()
    to upload glyphs onto the glyph cache pixmap. This avoids allocating
    offscreen memory for each glyph making management of offscreen
    areas much more efficient.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 27ecd4a..95ff4d8 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -347,6 +347,56 @@ exaGlyphCacheHashRemove(ExaGlyphCachePtr cache,
 #define CACHE_X(pos) (((pos) % cache->columns) * cache->glyphWidth)
 #define CACHE_Y(pos) (cache->yOffset + ((pos) / cache->columns) * cache->glyphHeight)
 
+/* The most efficient thing to way to upload the glyph to the screen
+ * is to use the UploadToScreen() driver hook; this allows us to
+ * pipeline glyph uploads and to avoid creating offscreen pixmaps for
+ * glyphs that we'll never use again.
+ */
+static Bool
+exaGlyphCacheUploadGlyph(ScreenPtr         pScreen,
+			 ExaGlyphCachePtr  cache,
+			 int               pos,
+			 GlyphPtr          pGlyph)
+{
+    ExaScreenPriv(pScreen);
+    PicturePtr pGlyphPicture = GlyphPicture(pGlyph)[pScreen->myNum];
+    PixmapPtr pGlyphPixmap = (PixmapPtr)pGlyphPicture->pDrawable;
+    ExaPixmapPriv(pGlyphPixmap);
+    PixmapPtr pCachePixmap = (PixmapPtr)cache->picture->pDrawable;
+    ExaMigrationRec pixmaps[1];
+    int cacheXoff, cacheYoff;
+
+    if (!pExaScr->info->UploadToScreen || pExaScr->swappedOut || pExaPixmap->accel_blocked)
+	return FALSE;
+
+    /* If the glyph pixmap is already uploaded, no point in doing
+     * things this way */
+    if (exaPixmapIsOffscreen(pGlyphPixmap))
+	return FALSE;
+
+    /* cache pixmap must be offscreen. */
+    pixmaps[0].as_dst = TRUE;
+    pixmaps[0].as_src = FALSE;
+    pixmaps[0].pPix = pCachePixmap;
+    pixmaps[0].pReg = NULL;
+    exaDoMigration (pixmaps, 1, TRUE);
+
+    pCachePixmap = exaGetOffscreenPixmap ((DrawablePtr)pCachePixmap, &cacheXoff, &cacheYoff);
+    if (!pCachePixmap)
+	return FALSE;
+
+    if (!pExaScr->info->UploadToScreen(pCachePixmap,
+				       CACHE_X(pos) + cacheXoff,
+				       CACHE_Y(pos) + cacheYoff,
+				       pGlyph->info.width,
+				       pGlyph->info.height,
+				       (char *)pExaPixmap->sys_ptr,
+				       pExaPixmap->sys_pitch))
+	return FALSE;
+
+    return TRUE;
+}
+
 static ExaGlyphCacheResult
 exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 			 ExaGlyphCachePtr  cache,
@@ -413,18 +463,23 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 	    cache->evictionPosition = rand() % cache->size;
 	}
 
-	/* Now actually upload the glyph into the cache picture */
+	/* Now actually upload the glyph into the cache picture; if
+	 * we can't do it with UploadToScreen (because the glyph is
+	 * offscreen, etc), we fall back to CompositePicture.
+	 */
+	if (!exaGlyphCacheUploadGlyph(pScreen, cache, pos, pGlyph)) {
+	    CompositePicture (PictOpSrc,
+			      GlyphPicture(pGlyph)[pScreen->myNum],
+			      None,
+			      cache->picture,
+			      0, 0,
+			      0, 0,
+			      CACHE_X(pos),
+			      CACHE_Y(pos),
+			      pGlyph->info.width,
+			      pGlyph->info.height);
+	}
 
-	CompositePicture (PictOpSrc,
-			  GlyphPicture(pGlyph)[pScreen->myNum],
-			  None,
-			  cache->picture,
-			  0, 0,
-			  0, 0,
-			  CACHE_X(pos),
-			  CACHE_Y(pos),
-			  pGlyph->info.width,
-			  pGlyph->info.height);
     }
     
 
commit 13fd2256300b61d88b840952d838f834523f5dd7
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:55 2008 +0200

    EXA: Clean up debug messages

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 851e439..27ecd4a 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -260,11 +260,9 @@ exaGlyphCacheHashLookup(ExaGlyphCachePtr cache,
 	    return -1;
 
 	if (memcmp(pGlyph->sha1, cache->glyphs[entryPos].sha1, sizeof(pGlyph->sha1)) == 0){
-	    DBG_GLYPH_CACHE((" found entry at %d\n", slot));
 	    return entryPos;
 	}
 	    
-	DBG_GLYPH_CACHE((" lookup linear probe bumpalong\n"));
 	slot--;
 	if (slot < 0)
 	    slot = cache->hashSize - 1;
@@ -284,7 +282,6 @@ exaGlyphCacheHashInsert(ExaGlyphCachePtr cache,
     
     while (TRUE) { /* hash table can never be full */
 	if (cache->hashEntries[slot] == -1) {
-	    DBG_GLYPH_CACHE((" inserting entry at %d\n", slot));
 	    cache->hashEntries[slot] = pos;
 	    return;
 	}
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index 8a17f65..f3b72ae 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -61,7 +61,7 @@
 #define DEBUG_MIGRATE		0
 #define DEBUG_PIXMAP		0
 #define DEBUG_OFFSCREEN		0
-#define DEBUG_GLYPH_CACHE	1
+#define DEBUG_GLYPH_CACHE	0
 
 #if DEBUG_TRACE_FALL
 #define EXA_FALLBACK(x)     					\
commit fcb5949928f1c27f67f40c094c3c673786574422
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:54 2008 +0200

    EXA: Fix overlapping glyphs in glyph cache
    
    Allocate each cache at a different vertical position in the
    per-format pixmap. Fix width/height confusion when choosing
    the cache for a glyph.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 55fdb01..851e439 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -173,12 +173,13 @@ exaRealizeGlyphCaches(ScreenPtr    pScreen,
     for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
 	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
 	int rows;
-	
+
 	if (cache->format != format)
 	    continue;
 
-	rows = (cache->size + cache->columns - 1) / cache->columns;
+	cache->yOffset = height;
 
+	rows = (cache->size + cache->columns - 1) / cache->columns;
 	height += rows * cache->glyphHeight;
     }
 
@@ -346,6 +347,9 @@ exaGlyphCacheHashRemove(ExaGlyphCachePtr cache,
     }
 }
 
+#define CACHE_X(pos) (((pos) % cache->columns) * cache->glyphWidth)
+#define CACHE_Y(pos) (cache->yOffset + ((pos) / cache->columns) * cache->glyphHeight)
+
 static ExaGlyphCacheResult
 exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 			 ExaGlyphCachePtr  cache,
@@ -393,8 +397,8 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 		int x, y;
 		int i;
 		
-		x = (pos % cache->columns) * cache->glyphWidth;
-		y = (pos / cache->columns) * cache->glyphHeight;
+		x = CACHE_X(pos);
+		y = CACHE_Y(pos);
 
 		for (i = 0; i < buffer->count; i++) {
 		    if (buffer->rects[i].xSrc == x && buffer->rects[i].ySrc == y) {
@@ -420,8 +424,8 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 			  cache->picture,
 			  0, 0,
 			  0, 0,
-			  (pos % cache->columns) * cache->glyphWidth,
-			  (pos / cache->columns) * cache->glyphHeight,
+			  CACHE_X(pos),
+			  CACHE_Y(pos),
 			  pGlyph->info.width,
 			  pGlyph->info.height);
     }
@@ -430,8 +434,8 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
     buffer->source = cache->picture;
 	    
     rect = &buffer->rects[buffer->count];
-    rect->xSrc = (pos % cache->columns) * cache->glyphWidth;
-    rect->ySrc = (pos / cache->columns) * cache->glyphHeight;
+    rect->xSrc = CACHE_X(pos);
+    rect->ySrc = CACHE_Y(pos);
     rect->xDst = xGlyph - pGlyph->info.x;
     rect->yDst = yGlyph - pGlyph->info.y;
     rect->width = pGlyph->info.width;
@@ -442,6 +446,9 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
     return ExaGlyphSuccess;
 }
 
+#undef CACHE_X
+#undef CACHE_Y
+
 static ExaGlyphCacheResult
 exaBufferGlyph(ScreenPtr         pScreen,
 	       ExaGlyphBufferPtr buffer,
@@ -452,7 +459,7 @@ exaBufferGlyph(ScreenPtr         pScreen,
     ExaScreenPriv(pScreen);
     unsigned int format = (GlyphPicture(pGlyph)[pScreen->myNum])->format;
     int width = pGlyph->info.width;
-    int height = pGlyph->info.width;
+    int height = pGlyph->info.height;
     ExaCompositeRectPtr rect;
     PicturePtr source;
     int i;
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index 0d5d0f5..8a17f65 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -61,7 +61,7 @@
 #define DEBUG_MIGRATE		0
 #define DEBUG_PIXMAP		0
 #define DEBUG_OFFSCREEN		0
-#define DEBUG_GLYPH_CACHE	0
+#define DEBUG_GLYPH_CACHE	1
 
 #if DEBUG_TRACE_FALL
 #define EXA_FALLBACK(x)     					\
@@ -121,6 +121,7 @@ typedef struct {
     int glyphCount; /* Current number of glyphs */
     
     PicturePtr picture;   /* Where the glyphs of the cache are stored */
+    int yOffset;          /* y location within the picture where the cache starts */
     int columns;          /* Number of columns the glyphs are layed out in */
     int evictionPosition; /* Next random position to evict a glyph */
 } ExaGlyphCacheRec, *ExaGlyphCachePtr;
commit 40eb14c9482457969e0bde97c49edad536285e02
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:54 2008 +0200

    EXA: Add exaCompositeRects()
    
    Add a function to composite multiple independent rectangles
    from the same source to the same destination in a single
    operation: this is useful for building a glyph mask.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 3fe433a..55fdb01 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -56,16 +56,6 @@
 #define DBG_GLYPH_CACHE(a)
 #endif
 
-/* Instructions for rendering a single glyph */
-typedef struct {
-    INT16 xSrc;
-    INT16 ySrc;
-    INT16 xDst;
-    INT16 yDst;
-    INT16 width;
-    INT16 height;
-} ExaGlyphRenderRec, *ExaGlyphRenderPtr;
-
 /* Width of the pixmaps we use for the caches; this should be less than
  * max texture size of the driver; this may need to actually come from
  * the driver.
@@ -79,7 +69,7 @@ typedef struct {
 
 typedef struct {
     PicturePtr source;
-    ExaGlyphRenderRec glyphs[GLYPH_BUFFER_SIZE];
+    ExaCompositeRectRec rects[GLYPH_BUFFER_SIZE];
     int count;
 } ExaGlyphBuffer, *ExaGlyphBufferPtr;
 
@@ -364,7 +354,7 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 			 int               xGlyph,
 			 int               yGlyph)
 {
-    ExaGlyphRenderPtr glyphRec;
+    ExaCompositeRectPtr rect;
     int pos;
     
     if (buffer->source && buffer->source != cache->picture)
@@ -407,7 +397,7 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 		y = (pos / cache->columns) * cache->glyphHeight;
 
 		for (i = 0; i < buffer->count; i++) {
-		    if (buffer->glyphs[i].xSrc == x && buffer->glyphs[i].ySrc == y) {
+		    if (buffer->rects[i].xSrc == x && buffer->rects[i].ySrc == y) {
 			DBG_GLYPH_CACHE(("  must flush buffer\n"));
 			return ExaGlyphNeedFlush;
 		    }
@@ -439,13 +429,13 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 
     buffer->source = cache->picture;
 	    
-    glyphRec = &buffer->glyphs[buffer->count];
-    glyphRec->xSrc = (pos % cache->columns) * cache->glyphWidth;
-    glyphRec->ySrc = (pos / cache->columns) * cache->glyphHeight;
-    glyphRec->xDst = xGlyph - pGlyph->info.x;
-    glyphRec->yDst = yGlyph - pGlyph->info.y;
-    glyphRec->width = pGlyph->info.width;
-    glyphRec->height = pGlyph->info.height;
+    rect = &buffer->rects[buffer->count];
+    rect->xSrc = (pos % cache->columns) * cache->glyphWidth;
+    rect->ySrc = (pos / cache->columns) * cache->glyphHeight;
+    rect->xDst = xGlyph - pGlyph->info.x;
+    rect->yDst = yGlyph - pGlyph->info.y;
+    rect->width = pGlyph->info.width;
+    rect->height = pGlyph->info.height;
 	    
     buffer->count++;
 
@@ -463,7 +453,7 @@ exaBufferGlyph(ScreenPtr         pScreen,
     unsigned int format = (GlyphPicture(pGlyph)[pScreen->myNum])->format;
     int width = pGlyph->info.width;
     int height = pGlyph->info.width;
-    ExaGlyphRenderPtr glyphRec;
+    ExaCompositeRectPtr rect;
     PicturePtr source;
     int i;
 
@@ -497,13 +487,13 @@ exaBufferGlyph(ScreenPtr         pScreen,
 
     buffer->source = source;
     
-    glyphRec = &buffer->glyphs[buffer->count];
-    glyphRec->xSrc = 0;
-    glyphRec->ySrc = 0;
-    glyphRec->xDst = xGlyph - pGlyph->info.x;
-    glyphRec->yDst = yGlyph - pGlyph->info.y;
-    glyphRec->width = pGlyph->info.width;
-    glyphRec->height = pGlyph->info.height;
+    rect = &buffer->rects[buffer->count];
+    rect->xSrc = 0;
+    rect->ySrc = 0;
+    rect->xDst = xGlyph - pGlyph->info.x;
+    rect->yDst = yGlyph - pGlyph->info.y;
+    rect->width = pGlyph->info.width;
+    rect->height = pGlyph->info.height;
 
     buffer->count++;
 
@@ -514,23 +504,8 @@ static void
 exaGlyphsToMask(PicturePtr        pMask,
 		ExaGlyphBufferPtr buffer)
 {
-    int i;
-
-    for (i = 0; i < buffer->count; i++) {
-	ExaGlyphRenderPtr glyphRec = &buffer->glyphs[i];
-	
-	CompositePicture (PictOpAdd,
-			  buffer->source,
-			  None,
-			  pMask,
-			  glyphRec->xSrc,
-			  glyphRec->ySrc,
-			  0, 0,
-			  glyphRec->xDst,
-			  glyphRec->yDst,
-			  glyphRec->width,
-			  glyphRec->height);
-    }
+    exaCompositeRects(PictOpAdd, buffer->source, pMask,
+		      buffer->count, buffer->rects);
     
     buffer->count = 0;
     buffer->source = NULL;
@@ -549,20 +524,20 @@ exaGlyphsToDst(CARD8		 op,
     int i;
 
     for (i = 0; i < buffer->count; i++) {
-	ExaGlyphRenderPtr glyphRec = &buffer->glyphs[i];
+	ExaCompositeRectPtr rect = &buffer->rects[i];
 	
 	CompositePicture (op,
 			  pSrc,
 			  buffer->source,
 			  pDst,
-			  xSrc + glyphRec->xDst - xDst,
-			  ySrc + glyphRec->yDst - yDst,
-			  glyphRec->xSrc,
-			  glyphRec->ySrc,
-			  glyphRec->xDst,
-			  glyphRec->yDst,
-			  glyphRec->width,
-			  glyphRec->height);
+			  xSrc + rect->xDst - xDst,
+			  ySrc + rect->yDst - yDst,
+			  rect->xSrc,
+			  rect->ySrc,
+			  rect->xDst,
+			  rect->yDst,
+			  rect->width,
+			  rect->height);
     }
     
     buffer->count = 0;
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index aaceeb8..0d5d0f5 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -243,6 +243,15 @@ typedef struct _ExaMigrationRec {
     RegionPtr pReg;
 } ExaMigrationRec, *ExaMigrationPtr;
 
+typedef struct {
+    INT16 xSrc;
+    INT16 ySrc;
+    INT16 xDst;
+    INT16 yDst;
+    INT16 width;
+    INT16 height;
+} ExaCompositeRectRec, *ExaCompositeRectPtr;
+
 /**
  * exaDDXDriverInit must be implemented by the DDX using EXA, and is the place
  * to set EXA options or hook in screen functions to handle using EXA as the AA.
@@ -457,6 +466,13 @@ exaComposite(CARD8	op,
 	     CARD16	height);
 
 void
+exaCompositeRects(CARD8	              op,
+		  PicturePtr	      Src,
+		  PicturePtr	      pDst,
+		  int                 nrect,
+		  ExaCompositeRectPtr rects);
+
+void
 exaTrapezoids (CARD8 op, PicturePtr pSrc, PicturePtr pDst,
                PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc,
                int ntrap, xTrapezoid *traps);
diff --git a/exa/exa_render.c b/exa/exa_render.c
index 1d7b897..43b0029 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -332,6 +332,228 @@ exaTryDriverSolidFill(PicturePtr	pSrc,
 }
 
 static int
+exaTryDriverCompositeRects(CARD8	       op,
+			   PicturePtr	       pSrc,
+			   PicturePtr	       pDst,
+			   int                 nrect,
+			   ExaCompositeRectPtr rects)
+{
+    ExaScreenPriv (pDst->pDrawable->pScreen);
+    int src_off_x, src_off_y, dst_off_x, dst_off_y;
+    PixmapPtr pSrcPix, pDstPix;
+    ExaPixmapPrivPtr pSrcExaPix, pDstExaPix;
+    struct _Pixmap scratch;
+    ExaMigrationRec pixmaps[2];
+
+    pSrcPix = exaGetDrawablePixmap(pSrc->pDrawable);
+    pSrcExaPix = ExaGetPixmapPriv(pSrcPix);
+
+    pDstPix = exaGetDrawablePixmap(pDst->pDrawable);
+    pDstExaPix = ExaGetPixmapPriv(pDstPix);
+
+    /* Check whether the accelerator can use these pixmaps.
+     * FIXME: If it cannot, use temporary pixmaps so that the drawing
+     * happens within limits.
+     */
+    if (pSrcExaPix->accel_blocked ||
+	pDstExaPix->accel_blocked)
+    {
+	return -1;
+    }
+
+    if (pExaScr->info->CheckComposite &&
+	!(*pExaScr->info->CheckComposite) (op, pSrc, NULL, pDst))
+    {
+	return -1;
+    }
+    
+    exaGetDrawableDeltas (pDst->pDrawable, pDstPix, &dst_off_x, &dst_off_y);
+	
+    pixmaps[0].as_dst = TRUE;
+    pixmaps[0].as_src = exaOpReadsDestination(op);
+    pixmaps[0].pPix = pDstPix;
+    pixmaps[0].pReg = NULL;
+    pixmaps[1].as_dst = FALSE;
+    pixmaps[1].as_src = TRUE;
+    pixmaps[1].pPix = pSrcPix;
+    pixmaps[1].pReg = NULL;
+    exaDoMigration(pixmaps, 2, TRUE);
+
+    pSrcPix = exaGetOffscreenPixmap (pSrc->pDrawable, &src_off_x, &src_off_y);
+    if (!exaPixmapIsOffscreen(pDstPix))
+	return 0;
+    
+    if (!pSrcPix && pExaScr->info->UploadToScratch)
+    {
+	pSrcPix = exaGetDrawablePixmap (pSrc->pDrawable);
+	if ((*pExaScr->info->UploadToScratch) (pSrcPix, &scratch))
+	    pSrcPix = &scratch;
+    }
+
+    if (!pSrcPix)
+	return 0;
+
+    if (!(*pExaScr->info->PrepareComposite) (op, pSrc, NULL, pDst, pSrcPix,
+					     NULL, pDstPix))
+	return -1;
+
+    while (nrect--)
+    {
+	INT16 xDst = rects->xDst + pDst->pDrawable->x;
+	INT16 yDst = rects->yDst + pDst->pDrawable->y;
+	INT16 xSrc = rects->xSrc + pSrc->pDrawable->x;
+	INT16 ySrc = rects->ySrc + pSrc->pDrawable->y;
+	
+	RegionRec region;
+	BoxPtr pbox;
+	int nbox;
+	
+	if (!miComputeCompositeRegion (&region, pSrc, NULL, pDst,
+				       xSrc, ySrc, 0, 0, xDst, yDst,
+				       rects->width, rects->height))
+	    goto next_rect;
+	
+	REGION_TRANSLATE(pScreen, &region, dst_off_x, dst_off_y);
+	
+	nbox = REGION_NUM_RECTS(&region);
+	pbox = REGION_RECTS(&region);
+
+	xSrc = xSrc + src_off_x - xDst - dst_off_x;
+	ySrc = ySrc + src_off_y - yDst - dst_off_y;
+	
+	while (nbox--)
+	{
+	    (*pExaScr->info->Composite) (pDstPix,
+					 pbox->x1 + xSrc,
+					 pbox->y1 + ySrc,
+					 0, 0,
+					 pbox->x1,
+					 pbox->y1,
+					 pbox->x2 - pbox->x1,
+					 pbox->y2 - pbox->y1);
+	    pbox++;
+	}
+
+    next_rect:
+	REGION_UNINIT(pDst->pDrawable->pScreen, &region);
+
+	rects++;
+    }
+    
+    (*pExaScr->info->DoneComposite) (pDstPix);
+    exaMarkSync(pDst->pDrawable->pScreen);
+	
+    return 1;
+}
+
+/**
+ * Copy a number of rectangles from source to destination in a single
+ * operation. This is specialized for building a glyph mask: we don'y
+ * have a mask argument because we don't need it for that, and we
+ * don't have he special-case fallbacks found in exaComposite() - if the
+ * driver can support it, we use the driver functionality, otherwise we
+ * fallback straight to software.
+ */
+void
+exaCompositeRects(CARD8	              op,
+		  PicturePtr	      pSrc,
+		  PicturePtr	      pDst,
+		  int                 nrect,
+		  ExaCompositeRectPtr rects)
+{
+    PixmapPtr pPixmap = exaGetDrawablePixmap(pDst->pDrawable);
+    ExaPixmapPriv(pPixmap);
+    
+    int xoff, yoff;
+    int x1 = MAXSHORT;
+    int y1 = MAXSHORT;
+    int x2 = MINSHORT;
+    int y2 = MINSHORT;
+    RegionRec region;
+    RegionPtr pending_damage;
+    BoxRec box;
+    int n;
+    ExaCompositeRectPtr r;
+    
+    /* We have to manage the damage ourselves, since CompositeRects isn't
+     * something in the screen that can be managed by the damage extension,
+     * and EXA depends on damage to track what needs to be migrated between
+     * offscreen and onscreen.
+     */
+
+    /* Compute the overall extents of the composited region - we're making
+     * the assumption here that we are compositing a bunch of glyphs that
+     * cluster closely together and damaging each glyph individually would
+     * be a loss compared to damaging the bounding box.
+     */
+    n = nrect;
+    r = rects;
+    while (n--) {
+	int rect_x2 = r->xDst + r->width;
+	int rect_y2 = r->yDst + r->width;
+
+	if (r->xDst < x1) x1 = r->xDst;
+	if (r->xDst < y1) y1 = r->xDst;
+	if (rect_x2 > x2) x2 = rect_x2;
+	if (rect_y2 > y2) y2 = rect_y2;
+	
+	r++;
+    }
+
+    if (x2 <= x1 && y2 <= y1)
+	return;
+
+    box.x1 = x1;
+    box.x2 = x2 < MAXSHORT ? x2 : MAXSHORT;
+    box.y1 = y1;
+    box.y2 = y2 < MAXSHORT ? y2 : MAXSHORT;
+    
+    /* The pixmap migration code relies on pendingDamage indicating
+     * the bounds of the current rendering, so we need to force 
+     * the actual damage into that region before we do anything, and
+     * (see use of DamagePendingRegion in exaCopyDirty)
+     */
+    
+    REGION_INIT(pScreen, &region, &box, 1);
+    
+    exaGetDrawableDeltas(pDst->pDrawable, pPixmap, &xoff, &yoff);
+
+    REGION_TRANSLATE(pScreen, &region, xoff, yoff);
+    pending_damage = DamagePendingRegion(pExaPixmap->pDamage);
+    REGION_UNION(pScreen, pending_damage, pending_damage, &region);
+    REGION_TRANSLATE(pScreen, &region, -xoff, -yoff);
+    
+    /************************************************************/
+    
+    ValidatePicture (pSrc);
+    ValidatePicture (pDst);
+    
+    if (exaTryDriverCompositeRects(op, pSrc, pDst, nrect, rects) != 1) {
+	n = nrect;
+	r = rects;
+	while (n--) {
+	    ExaCheckComposite (op, pSrc, NULL, pDst,
+			       r->xSrc, r->ySrc,
+			       0, 0,
+			       r->xDst, r->yDst,
+			       r->width, r->height);
+	    r++;
+	}
+    }
+    
+    /************************************************************/
+
+    /* Now we have to flush the damage out from pendingDamage => damage 
+     * Calling DamageDamageRegion has that effect. (We could pass
+     * in an empty region here, but we pass in the same region we
+     * use above; the effect is the same.)
+     */
+
+    DamageDamageRegion(pDst->pDrawable, &region);
+    REGION_UNINIT(pScreen, &region);
+}
+
+static int
 exaTryDriverComposite(CARD8		op,
 		      PicturePtr	pSrc,
 		      PicturePtr	pMask,
commit 54184110f6f3e5d7276d5431e739a4fcf0c3523e
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:54 2008 +0200

    EXA: Use a single large glyph cache pixmap
    
    Add back exaGlyphs(); the new version copies the glyph images
    onto a single large glyph pixmap and draws from their to the
    destination surface. This reduces the management of small
    offscreen areas and will allow us to avoid texture unit setup
    between each glyph.

diff --git a/exa/Makefile.am b/exa/Makefile.am
index e2f7ed3..2b3f1e4 100644
--- a/exa/Makefile.am
+++ b/exa/Makefile.am
@@ -18,6 +18,7 @@ libexa_la_SOURCES = \
 	exa.c \
 	exa.h \
 	exa_accel.c \
+	exa_glyphs.c \
 	exa_migration.c \
 	exa_offscreen.c \
 	exa_render.c \
diff --git a/exa/exa.c b/exa/exa.c
index 3a6ad98..809fb4b 100644
--- a/exa/exa.c
+++ b/exa/exa.c
@@ -739,6 +739,8 @@ exaCloseScreen(int i, ScreenPtr pScreen)
     PictureScreenPtr	ps = GetPictureScreenIfSet(pScreen);
 #endif
 
+    exaGlyphsFini(pScreen);
+
     pScreen->CreateGC = pExaScr->SavedCreateGC;
     pScreen->CloseScreen = pExaScr->SavedCloseScreen;
     pScreen->GetImage = pExaScr->SavedGetImage;
@@ -752,7 +754,9 @@ exaCloseScreen(int i, ScreenPtr pScreen)
 #ifdef RENDER
     if (ps) {
 	ps->Composite = pExaScr->SavedComposite;
+	ps->Glyphs = pExaScr->SavedGlyphs;
 	ps->Trapezoids = pExaScr->SavedTrapezoids;
+	ps->Triangles = pExaScr->SavedTriangles;
     }
 #endif
 
@@ -914,6 +918,9 @@ exaDriverInit (ScreenPtr		pScreen,
         pExaScr->SavedComposite = ps->Composite;
 	ps->Composite = exaComposite;
 
+	pExaScr->SavedGlyphs = ps->Glyphs;
+	ps->Glyphs = exaGlyphs;
+	
 	pExaScr->SavedTriangles = ps->Triangles;
 	ps->Triangles = exaTriangles;
 
@@ -973,6 +980,8 @@ exaDriverInit (ScreenPtr		pScreen,
 	}
     }
 
+    exaGlyphsInit(pScreen);
+
     LogMessage(X_INFO, "EXA(%d): Driver registered support for the following"
 	       " operations:\n", pScreen->myNum);
     assert(pScreenInfo->PrepareSolid != NULL);
diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
new file mode 100644
index 0000000..3fe433a
--- /dev/null
+++ b/exa/exa_glyphs.c
@@ -0,0 +1,745 @@
+/*
+ * Copyright © 2008 Red Hat, Inc.
+ * Partly based on code Copyright © 2000 SuSE, Inc.
+ *
+ * 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, and that the name of Red Hat not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  Red Hat makes no representations about the
+ * suitability of this software for any purpose.  It is provided "as is"
+ * without express or implied warranty.
+ *
+ * Red Hat DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL Red Hat
+ * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * 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, and that the name of SuSE not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  SuSE makes no representations about the
+ * suitability of this software for any purpose.  It is provided "as is"
+ * without express or implied warranty.
+ *
+ * SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE
+ * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Author: Owen Taylor <otaylor at fishsoup.net>
+ * Based on code by: Keith Packard
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdlib.h>
+
+#include "exa_priv.h"
+
+#include "mipict.h"
+
+#if DEBUG_GLYPH_CACHE
+#define DBG_GLYPH_CACHE(a) ErrorF a
+#else
+#define DBG_GLYPH_CACHE(a)
+#endif
+
+/* Instructions for rendering a single glyph */
+typedef struct {
+    INT16 xSrc;
+    INT16 ySrc;
+    INT16 xDst;
+    INT16 yDst;
+    INT16 width;
+    INT16 height;
+} ExaGlyphRenderRec, *ExaGlyphRenderPtr;
+
+/* Width of the pixmaps we use for the caches; this should be less than
+ * max texture size of the driver; this may need to actually come from
+ * the driver.
+ */
+#define CACHE_PICTURE_WIDTH 1024
+
+/* Maximum number of glyphs we buffer on the stack before flushing
+ * rendering to the mask or destination surface.
+ */
+#define GLYPH_BUFFER_SIZE 256
+
+typedef struct {
+    PicturePtr source;
+    ExaGlyphRenderRec glyphs[GLYPH_BUFFER_SIZE];
+    int count;
+} ExaGlyphBuffer, *ExaGlyphBufferPtr;
+
+typedef enum {
+    ExaGlyphSuccess,    /* Glyph added to render buffer */
+    ExaGlyphFail,       /* out of memory, etc */
+    ExaGlyphNeedFlush,  /* would evict a glyph already in the buffer */
+} ExaGlyphCacheResult;
+
+void
+exaGlyphsInit(ScreenPtr pScreen)
+{
+    ExaScreenPriv(pScreen);
+    int i = 0;
+
+    memset(pExaScr->glyphCaches, 0, sizeof(pExaScr->glyphCaches));
+
+    pExaScr->glyphCaches[i].format = PICT_a8;
+    pExaScr->glyphCaches[i].glyphWidth = pExaScr->glyphCaches[i].glyphHeight = 16;
+    i++;
+    pExaScr->glyphCaches[i].format = PICT_a8;
+    pExaScr->glyphCaches[i].glyphWidth = pExaScr->glyphCaches[i].glyphHeight = 32;
+    i++;
+    pExaScr->glyphCaches[i].format = PICT_a8r8g8b8;
+    pExaScr->glyphCaches[i].glyphWidth = pExaScr->glyphCaches[i].glyphHeight = 16;
+    i++;
+    pExaScr->glyphCaches[i].format = PICT_a8r8g8b8;
+    pExaScr->glyphCaches[i].glyphWidth = pExaScr->glyphCaches[i].glyphHeight = 32;
+    i++;
+
+    assert(i == EXA_NUM_GLYPH_CACHES);
+    
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	pExaScr->glyphCaches[i].columns = CACHE_PICTURE_WIDTH / pExaScr->glyphCaches[i].glyphWidth;
+	pExaScr->glyphCaches[i].size = 256;
+	pExaScr->glyphCaches[i].hashSize = 557;
+    }
+}
+
+static void
+exaUnrealizeGlyphCaches(ScreenPtr    pScreen,
+			unsigned int format)
+{
+    ExaScreenPriv(pScreen);
+    int i;
+
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+	
+	if (cache->format != format)
+	    continue;
+
+	if (cache->picture) {
+	    FreePicture ((pointer) cache->picture, (XID) 0);
+	    cache->picture = NULL;
+	}
+
+	if (cache->hashEntries) {
+	    xfree(cache->hashEntries);
+	    cache->hashEntries = NULL;
+	}
+	
+	if (cache->glyphs) {
+	    xfree(cache->glyphs);
+	    cache->glyphs = NULL;
+	}
+	cache->glyphCount = 0;
+    }
+}
+
+/* All caches for a single format share a single pixmap for glyph storage,
+ * allowing mixing glyphs of different sizes without paying a penalty
+ * for switching between source pixmaps. (Note that for a size of font
+ * right at the border between two sizes, we might be switching for almost
+ * every glyph.)
+ *
+ * This function allocates the storage pixmap, and then fills in the
+ * rest of the allocated structures for all caches with the given format.
+ */
+static Bool
+exaRealizeGlyphCaches(ScreenPtr    pScreen,
+		      unsigned int format)
+{
+    ExaScreenPriv(pScreen);
+
+    int depth = PIXMAN_FORMAT_DEPTH(format);
+    PictFormatPtr pPictFormat;
+    PixmapPtr pPixmap;
+    PicturePtr pPicture;
+    int height;
+    int i;
+    int	error;
+
+    pPictFormat = PictureMatchFormat(pScreen, depth, format);
+    if (!pPictFormat)
+	return FALSE;
+    
+    /* Compute the total vertical size needed for the format */
+
+    height = 0;
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+	int rows;
+	
+	if (cache->format != format)
+	    continue;
+
+	rows = (cache->size + cache->columns - 1) / cache->columns;
+
+	height += rows * cache->glyphHeight;
+    }
+
+    /* Now allocate the pixmap and picture */
+       
+    pPixmap = (*pScreen->CreatePixmap) (pScreen,
+					CACHE_PICTURE_WIDTH,
+					height, depth, 0);
+    if (!pPixmap)
+	return FALSE;
+
+    pPicture = CreatePicture(0, &pPixmap->drawable, pPictFormat,
+			     0, 0, serverClient, &error);
+
+    (*pScreen->DestroyPixmap) (pPixmap); /* picture holds a refcount */
+
+    if (!pPicture)
+	return FALSE;
+
+    /* And store the picture in all the caches for the format */
+    
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+	int j;
+
+	if (cache->format != format)
+	    continue;
+
+	cache->picture = pPicture;
+	cache->picture->refcnt++;
+	cache->hashEntries = xalloc(sizeof(int) * cache->hashSize);
+	cache->glyphs = xalloc(sizeof(ExaCachedGlyphRec) * cache->size);
+	cache->glyphCount = 0;
+
+	if (!cache->hashEntries || !cache->glyphs)
+	    goto bail;
+
+	for (j = 0; j < cache->hashSize; j++)
+	    cache->hashEntries[j] = -1;
+	
+	cache->evictionPosition = rand() % cache->size;
+    }
+
+    /* Each cache references the picture individually */
+    FreePicture ((pointer) pPicture, (XID) 0);
+    return TRUE;
+
+bail:
+    exaUnrealizeGlyphCaches(pScreen, format);
+    return FALSE;
+}
+
+void
+exaGlyphsFini (ScreenPtr pScreen)
+{
+    ExaScreenPriv(pScreen);
+    int i;
+
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+
+	if (cache->picture)
+	    exaUnrealizeGlyphCaches(pScreen, cache->format);
+    }
+}
+
+static int
+exaGlyphCacheHashLookup(ExaGlyphCachePtr cache,
+			GlyphPtr         pGlyph)
+{
+    int slot;
+
+    slot = (*(CARD32 *) pGlyph->sha1) % cache->hashSize;
+    
+    while (TRUE) { /* hash table can never be full */
+	int entryPos = cache->hashEntries[slot];
+	if (entryPos == -1)
+	    return -1;
+
+	if (memcmp(pGlyph->sha1, cache->glyphs[entryPos].sha1, sizeof(pGlyph->sha1)) == 0){
+	    DBG_GLYPH_CACHE((" found entry at %d\n", slot));
+	    return entryPos;
+	}
+	    
+	DBG_GLYPH_CACHE((" lookup linear probe bumpalong\n"));
+	slot--;
+	if (slot < 0)
+	    slot = cache->hashSize - 1;
+    }
+}
+
+static void
+exaGlyphCacheHashInsert(ExaGlyphCachePtr cache,
+			GlyphPtr         pGlyph,
+			int              pos)
+{
+    int slot;
+
+    memcpy(cache->glyphs[pos].sha1, pGlyph->sha1, sizeof(pGlyph->sha1));
+    
+    slot = (*(CARD32 *) pGlyph->sha1) % cache->hashSize;
+    
+    while (TRUE) { /* hash table can never be full */
+	if (cache->hashEntries[slot] == -1) {
+	    DBG_GLYPH_CACHE((" inserting entry at %d\n", slot));
+	    cache->hashEntries[slot] = pos;
+	    return;
+	}
+	    
+	slot--;
+	if (slot < 0)
+	    slot = cache->hashSize - 1;
+    }
+}
+
+static void
+exaGlyphCacheHashRemove(ExaGlyphCachePtr cache,
+			int              pos)
+{
+    int slot;
+    int emptiedSlot = -1;
+
+    slot = (*(CARD32 *) cache->glyphs[pos].sha1) % cache->hashSize;
+
+    while (TRUE) { /* hash table can never be full */
+	int entryPos = cache->hashEntries[slot];
+	
+	if (entryPos == -1)
+	    return;
+
+	if (entryPos == pos) {
+	    cache->hashEntries[slot] = -1;
+	    emptiedSlot = slot;
+	} else if (emptiedSlot != -1) {
+	    /* See if we can move this entry into the emptied slot, we can't
+	     * do that if if entry would have hashed between the current position
+	     * and the emptied slot. (taking wrapping into account). Bad positions
+	     * are:
+	     *
+	     * |   XXXXXXXXXX             |
+	     *     i         j            
+	     *                            
+	     * |XXX                   XXXX|
+	     *     j                  i
+	     *
+	     * i - slot, j - emptiedSlot
+	     *
+	     * (Knuth 6.4R)
+	     */
+	    
+	    int entrySlot = (*(CARD32 *) cache->glyphs[entryPos].sha1) % cache->hashSize;
+
+	    if (!((entrySlot >= slot && entrySlot < emptiedSlot) ||
+		  (emptiedSlot < slot && (entrySlot < emptiedSlot || entrySlot >= slot)))) 
+	    {
+		cache->hashEntries[emptiedSlot] = entryPos;
+		cache->hashEntries[slot] = -1;
+		emptiedSlot = slot;
+	    }
+	}
+	
+	slot--;
+	if (slot < 0)
+	    slot = cache->hashSize - 1;
+    }
+}
+
+static ExaGlyphCacheResult
+exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
+			 ExaGlyphCachePtr  cache,
+			 ExaGlyphBufferPtr buffer,
+			 GlyphPtr          pGlyph,
+			 int               xGlyph,
+			 int               yGlyph)
+{
+    ExaGlyphRenderPtr glyphRec;
+    int pos;
+    
+    if (buffer->source && buffer->source != cache->picture)
+	return ExaGlyphNeedFlush;
+
+    if (!cache->picture) {
+	if (!exaRealizeGlyphCaches(pScreen, cache->format))
+	    return ExaGlyphFail;
+    }
+
+    DBG_GLYPH_CACHE(("(%d,%d,%s): buffering glyph %lx\n",
+		     cache->glyphWidth, cache->glyphHeight, cache->format == PICT_a8 ? "A" : "ARGB",
+		     (long)*(CARD32 *) pGlyph->sha1));
+   
+    pos = exaGlyphCacheHashLookup(cache, pGlyph);
+    if (pos != -1) {
+	DBG_GLYPH_CACHE(("  found existing glyph at %d\n", pos));
+    } else {
+	if (cache->glyphCount < cache->size) {
+	    /* Space remaining; we fill from the start */
+	    pos = cache->glyphCount;
+	    cache->glyphCount++;
+	    DBG_GLYPH_CACHE(("  storing glyph in free space at %d\n", pos));
+
+	    exaGlyphCacheHashInsert(cache, pGlyph, pos);
+
+	} else {
+	    /* Need to evict an entry. We have to see if any glyphs
+	     * already in the output buffer were at this position in
+	     * the cache
+	     */
+	    
+	    pos = cache->evictionPosition;
+	    DBG_GLYPH_CACHE(("  evicting glyph at %d\n", pos));
+	    if (buffer->count) {
+		int x, y;
+		int i;
+		
+		x = (pos % cache->columns) * cache->glyphWidth;
+		y = (pos / cache->columns) * cache->glyphHeight;
+
+		for (i = 0; i < buffer->count; i++) {
+		    if (buffer->glyphs[i].xSrc == x && buffer->glyphs[i].ySrc == y) {
+			DBG_GLYPH_CACHE(("  must flush buffer\n"));
+			return ExaGlyphNeedFlush;
+		    }
+		}
+	    }
+
+	    /* OK, we're all set, swap in the new glyph */
+	    exaGlyphCacheHashRemove(cache, pos);
+	    exaGlyphCacheHashInsert(cache, pGlyph, pos);
+
+	    /* And pick a new eviction position */
+	    cache->evictionPosition = rand() % cache->size;
+	}
+
+	/* Now actually upload the glyph into the cache picture */
+
+	CompositePicture (PictOpSrc,
+			  GlyphPicture(pGlyph)[pScreen->myNum],
+			  None,
+			  cache->picture,
+			  0, 0,
+			  0, 0,
+			  (pos % cache->columns) * cache->glyphWidth,
+			  (pos / cache->columns) * cache->glyphHeight,
+			  pGlyph->info.width,
+			  pGlyph->info.height);
+    }
+    
+
+    buffer->source = cache->picture;
+	    
+    glyphRec = &buffer->glyphs[buffer->count];
+    glyphRec->xSrc = (pos % cache->columns) * cache->glyphWidth;
+    glyphRec->ySrc = (pos / cache->columns) * cache->glyphHeight;
+    glyphRec->xDst = xGlyph - pGlyph->info.x;
+    glyphRec->yDst = yGlyph - pGlyph->info.y;
+    glyphRec->width = pGlyph->info.width;
+    glyphRec->height = pGlyph->info.height;
+	    
+    buffer->count++;
+
+    return ExaGlyphSuccess;
+}
+
+static ExaGlyphCacheResult
+exaBufferGlyph(ScreenPtr         pScreen,
+	       ExaGlyphBufferPtr buffer,
+	       GlyphPtr          pGlyph,
+	       int               xGlyph,
+	       int               yGlyph)
+{
+    ExaScreenPriv(pScreen);
+    unsigned int format = (GlyphPicture(pGlyph)[pScreen->myNum])->format;
+    int width = pGlyph->info.width;
+    int height = pGlyph->info.width;
+    ExaGlyphRenderPtr glyphRec;
+    PicturePtr source;
+    int i;
+
+    if (buffer->count == GLYPH_BUFFER_SIZE)
+	return ExaGlyphNeedFlush;
+    
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+
+	if (format == cache->format &&
+	    width <= cache->glyphWidth &&
+	    height <= cache->glyphHeight) {
+	    ExaGlyphCacheResult result = exaGlyphCacheBufferGlyph(pScreen, &pExaScr->glyphCaches[i],
+								  buffer,
+								  pGlyph, xGlyph, yGlyph);
+	    switch (result) {
+	    case ExaGlyphFail:
+		break;
+	    case ExaGlyphSuccess:
+	    case ExaGlyphNeedFlush:
+		return result;
+	    }
+	}
+    }
+
+    /* Couldn't find the glyph in the cache, use the glyph picture directly */
+
+    source = GlyphPicture(pGlyph)[pScreen->myNum];
+    if (buffer->source && buffer->source != source)
+	return ExaGlyphNeedFlush;
+
+    buffer->source = source;
+    
+    glyphRec = &buffer->glyphs[buffer->count];
+    glyphRec->xSrc = 0;
+    glyphRec->ySrc = 0;
+    glyphRec->xDst = xGlyph - pGlyph->info.x;
+    glyphRec->yDst = yGlyph - pGlyph->info.y;
+    glyphRec->width = pGlyph->info.width;
+    glyphRec->height = pGlyph->info.height;
+
+    buffer->count++;
+
+    return ExaGlyphSuccess;
+}
+
+static void
+exaGlyphsToMask(PicturePtr        pMask,
+		ExaGlyphBufferPtr buffer)
+{
+    int i;
+
+    for (i = 0; i < buffer->count; i++) {
+	ExaGlyphRenderPtr glyphRec = &buffer->glyphs[i];
+	
+	CompositePicture (PictOpAdd,
+			  buffer->source,
+			  None,
+			  pMask,
+			  glyphRec->xSrc,
+			  glyphRec->ySrc,
+			  0, 0,
+			  glyphRec->xDst,
+			  glyphRec->yDst,
+			  glyphRec->width,
+			  glyphRec->height);
+    }
+    
+    buffer->count = 0;
+    buffer->source = NULL;
+}
+
+static void
+exaGlyphsToDst(CARD8		 op,
+	       PicturePtr	 pSrc,
+	       PicturePtr	 pDst,
+	       ExaGlyphBufferPtr buffer,
+	       INT16		 xSrc,
+	       INT16		 ySrc,
+	       INT16		 xDst,
+	       INT16		 yDst)
+{
+    int i;
+
+    for (i = 0; i < buffer->count; i++) {
+	ExaGlyphRenderPtr glyphRec = &buffer->glyphs[i];
+	
+	CompositePicture (op,
+			  pSrc,
+			  buffer->source,
+			  pDst,
+			  xSrc + glyphRec->xDst - xDst,
+			  ySrc + glyphRec->yDst - yDst,
+			  glyphRec->xSrc,
+			  glyphRec->ySrc,
+			  glyphRec->xDst,
+			  glyphRec->yDst,
+			  glyphRec->width,
+			  glyphRec->height);
+    }
+    
+    buffer->count = 0;
+    buffer->source = NULL;
+}
+
+/* Cut and paste from render/glyph.c - probably should export it instead */
+static void
+GlyphExtents (int		nlist,
+	      GlyphListPtr	list,
+	      GlyphPtr	       *glyphs,
+	      BoxPtr		extents)
+{
+    int		x1, x2, y1, y2;
+    int		n;
+    GlyphPtr	glyph;
+    int		x, y;
+    
+    x = 0;
+    y = 0;
+    extents->x1 = MAXSHORT;
+    extents->x2 = MINSHORT;
+    extents->y1 = MAXSHORT;
+    extents->y2 = MINSHORT;
+    while (nlist--)
+    {
+	x += list->xOff;
+	y += list->yOff;
+	n = list->len;
+	list++;
+	while (n--)
+	{
+	    glyph = *glyphs++;
+	    x1 = x - glyph->info.x;
+	    if (x1 < MINSHORT)
+		x1 = MINSHORT;
+	    y1 = y - glyph->info.y;
+	    if (y1 < MINSHORT)
+		y1 = MINSHORT;
+	    x2 = x1 + glyph->info.width;
+	    if (x2 > MAXSHORT)
+		x2 = MAXSHORT;
+	    y2 = y1 + glyph->info.height;
+	    if (y2 > MAXSHORT)
+		y2 = MAXSHORT;
+	    if (x1 < extents->x1)
+		extents->x1 = x1;
+	    if (x2 > extents->x2)
+		extents->x2 = x2;
+	    if (y1 < extents->y1)
+		extents->y1 = y1;
+	    if (y2 > extents->y2)
+		extents->y2 = y2;
+	    x += glyph->info.xOff;
+	    y += glyph->info.yOff;
+	}
+    }
+}
+
+#define NeedsComponent(f) (PICT_FORMAT_A(f) != 0 && PICT_FORMAT_RGB(f) != 0)
+
+void
+exaGlyphs (CARD8 	 op,
+	   PicturePtr	 pSrc,
+	   PicturePtr	 pDst,
+	   PictFormatPtr maskFormat,
+	   INT16	 xSrc,
+	   INT16	 ySrc,
+	   int		 nlist,
+	   GlyphListPtr	 list,
+	   GlyphPtr	*glyphs)
+{
+    PicturePtr	pPicture;
+    PixmapPtr   pMaskPixmap = 0;
+    PicturePtr  pMask;
+    ScreenPtr   pScreen = pDst->pDrawable->pScreen;
+    int		width = 0, height = 0;
+    int		x, y;
+    int		xDst = list->xOff, yDst = list->yOff;
+    int		n;
+    GlyphPtr	glyph;
+    int		error;
+    BoxRec	extents = {0, 0, 0, 0};
+    CARD32	component_alpha;
+    ExaGlyphBuffer buffer;
+
+    if (maskFormat)
+    {
+	GCPtr	    pGC;
+	xRectangle  rect;
+
+	GlyphExtents (nlist, list, glyphs, &extents);
+
+	if (extents.x2 <= extents.x1 || extents.y2 <= extents.y1)
+	    return;
+	width = extents.x2 - extents.x1;
+	height = extents.y2 - extents.y1;
+	pMaskPixmap = (*pScreen->CreatePixmap) (pScreen, width, height,
+						maskFormat->depth,
+						CREATE_PIXMAP_USAGE_SCRATCH);
+	if (!pMaskPixmap)
+	    return;
+	component_alpha = NeedsComponent(maskFormat->format);
+	pMask = CreatePicture (0, &pMaskPixmap->drawable,
+			       maskFormat, CPComponentAlpha, &component_alpha,
+			       serverClient, &error);
+	if (!pMask)
+	{
+	    (*pScreen->DestroyPixmap) (pMaskPixmap);
+	    return;
+	}
+	pGC = GetScratchGC (pMaskPixmap->drawable.depth, pScreen);
+	ValidateGC (&pMaskPixmap->drawable, pGC);
+	rect.x = 0;
+	rect.y = 0;
+	rect.width = width;
+	rect.height = height;
+	(*pGC->ops->PolyFillRect) (&pMaskPixmap->drawable, pGC, 1, &rect);
+	FreeScratchGC (pGC);
+	x = -extents.x1;
+	y = -extents.y1;
+    }
+    else
+    {
+	pMask = pDst;
+	x = 0;
+	y = 0;
+    }
+    buffer.count = 0;
+    buffer.source = NULL;
+    while (nlist--)
+    {
+	x += list->xOff;
+	y += list->yOff;
+	n = list->len;
+	while (n--)
+	{
+	    glyph = *glyphs++;
+	    pPicture = GlyphPicture (glyph)[pScreen->myNum];
+
+	    if (exaBufferGlyph(pScreen, &buffer, glyph, x, y) == ExaGlyphNeedFlush)
+	    {
+		if (maskFormat)
+		    exaGlyphsToMask(pMask, &buffer);
+		else
+		    exaGlyphsToDst(op, pSrc, pDst, &buffer,
+				   xSrc, ySrc, xDst, yDst);
+
+		exaBufferGlyph(pScreen, &buffer, glyph, x, y);
+	    }
+
+	    x += glyph->info.xOff;
+	    y += glyph->info.yOff;
+	}
+	list++;
+    }
+    
+    if (maskFormat)
+	exaGlyphsToMask(pMask, &buffer);
+    else
+	exaGlyphsToDst(op, pSrc, pDst, &buffer,
+		       xSrc, ySrc, xDst, yDst);
+    
+    if (maskFormat)
+    {
+	x = extents.x1;
+	y = extents.y1;
+	CompositePicture (op,
+			  pSrc,
+			  pMask,
+			  pDst,
+			  xSrc + x - xDst,
+			  ySrc + y - yDst,
+			  0, 0,
+			  x, y,
+			  width, height);
+	FreePicture ((pointer) pMask, (XID) 0);
+	(*pScreen->DestroyPixmap) (pMaskPixmap);
+    }
+}
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index 0138e4a..aaceeb8 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -61,6 +61,7 @@
 #define DEBUG_MIGRATE		0
 #define DEBUG_PIXMAP		0
 #define DEBUG_OFFSCREEN		0
+#define DEBUG_GLYPH_CACHE	0
 
 #if DEBUG_TRACE_FALL
 #define EXA_FALLBACK(x)     					\
@@ -95,6 +96,37 @@ enum ExaMigrationHeuristic {
     ExaMigrationSmart
 };
 
+typedef struct {
+    unsigned char sha1[20];
+} ExaCachedGlyphRec, *ExaCachedGlyphPtr;
+
+typedef struct {
+    /* The identity of the cache, statically configured at initialization */
+    unsigned int format;
+    int glyphWidth;
+    int glyphHeight;
+
+    int size; /* Size of cache; eventually this should be dynamically determined */
+
+    /* Hash table mapping from glyph sha1 to position in the glyph; we use
+     * open addressing with a hash table size determined based on size and large
+     * enough so that we always have a good amount of free space, so we can
+     * use linear probing. (Linear probing is preferrable to double hashing
+     * here because it allows us to easily remove entries.)
+     */
+    int *hashEntries;
+    int hashSize;
+    
+    ExaCachedGlyphPtr glyphs;
+    int glyphCount; /* Current number of glyphs */
+    
+    PicturePtr picture;   /* Where the glyphs of the cache are stored */
+    int columns;          /* Number of columns the glyphs are layed out in */
+    int evictionPosition; /* Next random position to evict a glyph */
+} ExaGlyphCacheRec, *ExaGlyphCachePtr;
+
+#define EXA_NUM_GLYPH_CACHES 4
+
 typedef void (*EnableDisableFBAccessProcPtr)(int, Bool);
 typedef struct {
     ExaDriverPtr info;
@@ -122,6 +154,8 @@ typedef struct {
     unsigned			 disableFbCount;
     Bool			 optimize_migration;
     unsigned			 offScreenCounter;
+
+    ExaGlyphCacheRec             glyphCaches[EXA_NUM_GLYPH_CACHES];
 } ExaScreenPrivRec, *ExaScreenPrivPtr;
 
 /*
@@ -432,6 +466,13 @@ exaTriangles (CARD8 op, PicturePtr pSrc, PicturePtr pDst,
 	      PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc,
 	      int ntri, xTriangle *tris);
 
+/* exa_glyph.c */
+void
+exaGlyphsInit(ScreenPtr pScreen);
+
+void
+exaGlyphsFini (ScreenPtr pScreen);
+
 void
 exaGlyphs (CARD8	op,
 	  PicturePtr	pSrc,
commit e9734306088e12f2cd68bf347ecf8415be4f0268
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 11:47:49 2008 -0700

    XQuartz: More startup / threading house cleaning.
    (cherry picked from commit 72653c24c00dfba64ce35a3d400598bcd77defc1)

diff --git a/hw/xquartz/X11Application.h b/hw/xquartz/X11Application.h
index 3869df9..8e7fed2 100644
--- a/hw/xquartz/X11Application.h
+++ b/hw/xquartz/X11Application.h
@@ -71,7 +71,7 @@ void X11ApplicationSetCanQuit (int state);
 void X11ApplicationServerReady (void);
 void X11ApplicationShowHideMenubar (int state);
 
-void X11ApplicationMain(int argc, const char **argv);
+void X11ApplicationMain(int argc, char **argv, char **envp);
 
 extern int X11EnableKeyEquivalents;
 extern int quartzHasRoot, quartzEnableRootless;
diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 7680437..e10e71e 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -47,9 +47,6 @@
 #include <mach/mach.h>
 #include <unistd.h>
 
-#include <pthread.h>
-extern pthread_cond_t server_can_start_cond;
-
 #define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
 
 int X11EnableKeyEquivalents = TRUE;
@@ -776,7 +773,7 @@ environment?", @"Startup xinitrc dialog");
     [X11App prefs_synchronize];
 }
 
-void X11ApplicationMain (int argc, const char **argv) {
+void X11ApplicationMain (int argc, char **argv, char **envp) {
     NSAutoreleasePool *pool;
 
 #ifdef DEBUG
@@ -804,7 +801,7 @@ void X11ApplicationMain (int argc, const char **argv) {
     NSMaxY([[NSScreen mainScreen] visibleFrame]);
 
     /* Tell the server thread that it can proceed */
-    pthread_cond_broadcast(&server_can_start_cond);
+    QuartzInitServer(argc, argv, envp);
 
     [NSApp run];
     /* not reached */
diff --git a/hw/xquartz/X11Controller.h b/hw/xquartz/X11Controller.h
index d33752e..7942bc4 100644
--- a/hw/xquartz/X11Controller.h
+++ b/hw/xquartz/X11Controller.h
@@ -100,6 +100,6 @@
 
 #endif /* __OBJC__ */
 
-void X11ControllerMain(int argc, const char **argv);
+void X11ControllerMain(int argc, char **argv, char **envp);
 
 #endif /* X11CONTROLLER_H */
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 01470e5..df328f3 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -756,6 +756,6 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 @end
 
-void X11ControllerMain(int argc, const char **argv) {
-    X11ApplicationMain (argc, argv);
+void X11ControllerMain(int argc, char **argv, char **envp) {
+    X11ApplicationMain (argc, argv, envp);
 }
diff --git a/hw/xquartz/quartz.h b/hw/xquartz/quartz.h
index e116023..1b6d71f 100644
--- a/hw/xquartz/quartz.h
+++ b/hw/xquartz/quartz.h
@@ -128,6 +128,7 @@ Bool QuartzAddScreen(int index, ScreenPtr pScreen);
 Bool QuartzSetupScreen(int index, ScreenPtr pScreen);
 void QuartzInitOutput(int argc,char **argv);
 void QuartzInitInput(int argc, char **argv);
+void QuartzInitServer(int argc, char **argv, char **envp);
 void QuartzGiveUp(void);
 void QuartzProcessEvent(xEvent *xe);
 void QuartzDisplayChangedHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents);
diff --git a/hw/xquartz/quartzStartup.c b/hw/xquartz/quartzStartup.c
index 34eaf8a..7b6a1a6 100644
--- a/hw/xquartz/quartzStartup.c
+++ b/hw/xquartz/quartzStartup.c
@@ -58,19 +58,10 @@ struct arg {
     char **envp;
 };
 
-pthread_cond_t server_can_start_cond = PTHREAD_COND_INITIALIZER;
-
 static void server_thread (void *arg) {
-    struct arg *args = (struct arg *)arg;
-
-    /* Wait to be told we can continue */
-    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
-    pthread_mutex_lock(&mutex);
-    pthread_cond_wait(&server_can_start_cond, &mutex);
-    pthread_mutex_unlock(&mutex);
-    pthread_mutex_destroy(&mutex);
-
-    exit (dix_main(args->argc, args->argv, args->envp));
+    struct arg args = *((struct arg *)arg);
+    free(arg);
+    exit (dix_main(args.argc, args.argv, args.envp));
 }
 
 static pthread_t create_thread (void *func, void *arg) {
@@ -86,16 +77,27 @@ static pthread_t create_thread (void *func, void *arg) {
     return tid;
 }
 
+void QuartzInitServer(int argc, char **argv, char **envp) {
+    struct arg *args = (struct arg*)malloc(sizeof(struct arg));
+    if(!args)
+        FatalError("Could not allocate memory.\n");
+    
+    args->argc = argc;
+    args->argv = argv;
+    args->envp = envp;
+    
+    APPKIT_THREAD_ID = pthread_self();
+    SERVER_THREAD_ID = create_thread(server_thread, args);
+
+    if (!SERVER_THREAD_ID) {
+        FatalError("can't create secondary thread\n");
+    }
+}
+
 int main(int argc, char **argv, char **envp) {
     int         i;
     int         fd[2];
 
-    /* Store the args to pass to dix_main() */
-    struct arg  args;
-    args.argc = argc;
-    args.argv = argv;
-    args.envp = envp;
-
     // Make a pipe to pass events
     assert( pipe(fd) == 0 );
     darwinEventReadFD = fd[0];
@@ -112,18 +114,8 @@ int main(int argc, char **argv, char **envp) {
 
     /* Create the audio mutex */
     QuartzAudioInit();
-    
-    pthread_cond_init(&server_can_start_cond, NULL); 
-    
-    APPKIT_THREAD_ID = pthread_self();
-    SERVER_THREAD_ID = create_thread(server_thread, &args);
-
-    if (!SERVER_THREAD_ID) {
-        ErrorF("can't create secondary thread\n");
-        exit (1);
-    }
 
     QuartzMoveToForeground();
-    X11ControllerMain(argc, (const char **)argv);
+    X11ControllerMain(argc, argv, envp);
     exit(0);
 }
commit 4b46fc931e61bec0abd6a86062e46dd7a408e745
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 10:50:51 2008 -0700

    XQuartz: Updated Localizable.strings
    (cherry picked from commit d8d9c866b90fb24c93bd6e25fa90f8f2bf58ad34)

diff --git a/hw/xquartz/bundle/English.lproj/Localizable.strings b/hw/xquartz/bundle/English.lproj/Localizable.strings
index c83b085..63a1352 100644
Binary files a/hw/xquartz/bundle/English.lproj/Localizable.strings and b/hw/xquartz/bundle/English.lproj/Localizable.strings differ
commit 4017ebe5bfa7a261cd1135801756c44e9fe93ca1
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sun Apr 27 00:01:14 2008 -0700

    XQuartz: Added missing Xquartz.man.pre to EXTRA_DIST
    (cherry picked from commit 03e707987f7f32e47dd0355c6d16bfb9169a379b)

diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index 12009fb..41f2b86 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -47,6 +47,7 @@ include $(top_srcdir)/cpprules.in
 	cp $< $@
 
 EXTRA_DIST = \
+	Xquartz.man.pre \
 	dri.h \
 	dristruct.h \
 	appledri.h \
commit 0bd28315afc3b7223f8ff9f17597db09500a9388
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 26 23:00:42 2008 -0700

    Xquartz: Added missing to EXTRA_DIST
    (cherry picked from commit f4b963256feb03e9e6b5521bdefeb390e9a49688)

diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index ccef5f6..1465a52 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -52,4 +52,6 @@ EXTRA_DIST = \
 	quartzForeground.h \
 	quartzKeyboard.h \
 	quartzPasteboard.h \
+	sanitizedCarbon.h \
+	sanitizedCocoa.h \
 	threadSafety.h
commit ef1c52053755fa14b4ca98b22c506f73f5f4a4b7
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 26 19:21:05 2008 -0700

    XQuartz: Cleaned up startup and thread creation a tad.
    (cherry picked from commit c861fe00e112b21ee0156d09a6cd5281642a1dcc)

diff --git a/dix/main.c b/dix/main.c
index 6d9dd33..fbd6413 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -237,12 +237,11 @@ static int indexForScanlinePad[ 65 ] = {
 #define MIN(a,b) (((a) < (b)) ? (a) : (b))
 #endif
 
-#ifdef __APPLE__
-void DarwinHandleGUI(int argc, char **argv, char **envp);
+#ifdef XQUARTZ
+int dix_main(int argc, char *argv[], char *envp[])
+#else
+int main(int argc, char *argv[], char *envp[])
 #endif
-
-int
-main(int argc, char *argv[], char *envp[])
 {
     int		i, j, k, error;
     char	*xauthfile;
@@ -256,13 +255,6 @@ main(int argc, char *argv[], char *envp[])
     PrinterInitGlobals();
 #endif
 
-#ifdef XQUARTZ
-    /* Quartz support on Mac OS X requires that the Cocoa event loop be in
-     * the main thread. This allows the X server main to be called again
-     * from another thread. */
-    DarwinHandleGUI(argc, argv, envp);
-#endif
-
     CheckUserParameters(argc, argv, envp);
 
     CheckUserAuthorization();
diff --git a/hw/xquartz/X11Application.h b/hw/xquartz/X11Application.h
index 47c605c..3869df9 100644
--- a/hw/xquartz/X11Application.h
+++ b/hw/xquartz/X11Application.h
@@ -71,7 +71,7 @@ void X11ApplicationSetCanQuit (int state);
 void X11ApplicationServerReady (void);
 void X11ApplicationShowHideMenubar (int state);
 
-void X11ApplicationMain(int argc, const char **argv, void (*server_thread) (void *), void *server_arg);
+void X11ApplicationMain(int argc, const char **argv);
 
 extern int X11EnableKeyEquivalents;
 extern int quartzHasRoot, quartzEnableRootless;
diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index eefa45f..7680437 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -35,6 +35,7 @@
 
 #include "quartzForeground.h"
 #include "quartzCommon.h"
+
 #import "X11Application.h"
 
 # include "darwin.h"
@@ -45,7 +46,9 @@
 # include "micmap.h"
 #include <mach/mach.h>
 #include <unistd.h>
+
 #include <pthread.h>
+extern pthread_cond_t server_can_start_cond;
 
 #define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
 
@@ -732,19 +735,6 @@ void X11ApplicationShowHideMenubar (int state) {
     [n release];
 }
 
-static pthread_t create_thread (void *func, void *arg) {
-    pthread_attr_t attr;
-    pthread_t tid;
-	
-    pthread_attr_init (&attr);
-    pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
-    pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
-    pthread_create (&tid, &attr, func, arg);
-    pthread_attr_destroy (&attr);
-	
-    return tid;
-}
-
 static void check_xinitrc (void) {
     char *tem, buf[1024];
     NSString *msg;
@@ -786,7 +776,7 @@ environment?", @"Startup xinitrc dialog");
     [X11App prefs_synchronize];
 }
 
-void X11ApplicationMain (int argc, const char **argv, void (*server_thread) (void *), void *server_arg) {
+void X11ApplicationMain (int argc, const char **argv) {
     NSAutoreleasePool *pool;
 
 #ifdef DEBUG
@@ -812,16 +802,9 @@ void X11ApplicationMain (int argc, const char **argv, void (*server_thread) (voi
     /* Calculate the height of the menubar so we can avoid it. */
     aquaMenuBarHeight = NSHeight([[NSScreen mainScreen] frame]) -
     NSMaxY([[NSScreen mainScreen] visibleFrame]);
-  
-    APPKIT_THREAD = pthread_self();
-    SERVER_THREAD = create_thread (server_thread, server_arg);
-
-    if (!SERVER_THREAD) {
-        ErrorF("can't create secondary thread\n");
-        exit (1);
-    }
 
-    QuartzMoveToForeground();
+    /* Tell the server thread that it can proceed */
+    pthread_cond_broadcast(&server_can_start_cond);
 
     [NSApp run];
     /* not reached */
diff --git a/hw/xquartz/X11Controller.h b/hw/xquartz/X11Controller.h
index c5994bd..d33752e 100644
--- a/hw/xquartz/X11Controller.h
+++ b/hw/xquartz/X11Controller.h
@@ -100,6 +100,6 @@
 
 #endif /* __OBJC__ */
 
-void X11ControllerMain(int argc, const char **argv, void (*server_thread) (void *), void *server_arg);
+void X11ControllerMain(int argc, const char **argv);
 
 #endif /* X11CONTROLLER_H */
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 8dfe4b3..01470e5 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -756,6 +756,6 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 @end
 
-void X11ControllerMain(int argc, const char **argv, void (*server_thread) (void *), void *server_arg) {
-    X11ApplicationMain (argc, argv, server_thread, server_arg);
+void X11ControllerMain(int argc, const char **argv) {
+    X11ApplicationMain (argc, argv);
 }
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 0643e53..86e7704 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -78,7 +78,8 @@ static int old_flags = 0;  // last known modifier state
 
 xEvent *darwinEvents = NULL;
 
-pthread_mutex_t mieqEnqueue_mutex;
+pthread_mutex_t mieqEnqueue_mutex = PTHREAD_MUTEX_INITIALIZER;
+
 static inline void mieqEnqueue_lock(void) {
     int err;
     if((err = pthread_mutex_lock(&mieqEnqueue_mutex))) {
@@ -303,17 +304,11 @@ static void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, in
 }
 
 Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
-    int err;
-
     if (!darwinEvents)
         darwinEvents = (xEvent *)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
     if (!darwinEvents)
         FatalError("Couldn't allocate event buffer\n");
 
-    if((err = pthread_mutex_init(&mieqEnqueue_mutex, NULL))) {
-        FatalError("Couldn't allocate mieqEnqueue mutex: %d.\n", err);
-    }
-    
     mieqInit();
     mieqSetHandler(kXquartzReloadKeymap, DarwinKeyboardReloadHandler);
     mieqSetHandler(kXquartzActivate, DarwinEventHandler);
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 2cba5df..0635b48 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -39,7 +39,6 @@
 #include "quartz.h"
 #include "darwin.h"
 #include "darwinEvents.h"
-#include "quartzAudio.h"
 #include "pseudoramiX.h"
 #define _APPLEWM_SERVER_
 #include "applewmExt.h"
@@ -156,10 +155,6 @@ void QuartzInitOutput(
     int argc,
     char **argv )
 {
-    if (serverGeneration == 1) {
-        QuartzAudioInit();
-    }
-
     if (!RegisterBlockAndWakeupHandlers(QuartzBlockHandler,
                                         QuartzWakeupHandler,
                                         NULL))
diff --git a/hw/xquartz/quartzStartup.c b/hw/xquartz/quartzStartup.c
index 233e6e6..34eaf8a 100644
--- a/hw/xquartz/quartzStartup.c
+++ b/hw/xquartz/quartzStartup.c
@@ -37,54 +37,71 @@
 #include <unistd.h>
 #include <CoreFoundation/CoreFoundation.h>
 #include "quartzCommon.h"
+#include "quartzForeground.h"
 #include "X11Controller.h"
 #include "darwin.h"
+#include "darwinEvents.h"
+#include "quartzAudio.h"
 #include "quartz.h"
 #include "opaque.h"
 #include "micmap.h"
 
 #include <assert.h>
 
-char **envpGlobal;      // argcGlobal and argvGlobal
-                        // are from dix/globals.c
+#include <pthread.h>
 
-int main(int argc, char **argv, char **envp);
-void _InitHLTB(void);
-void DarwinHandleGUI(int argc, char **argv, char **envp);
+int dix_main(int argc, char **argv, char **envp);
+
+struct arg {
+    int argc;
+    char **argv;
+    char **envp;
+};
+
+pthread_cond_t server_can_start_cond = PTHREAD_COND_INITIALIZER;
 
 static void server_thread (void *arg) {
-  exit (main (argcGlobal, argvGlobal, envpGlobal));
+    struct arg *args = (struct arg *)arg;
+
+    /* Wait to be told we can continue */
+    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+    pthread_mutex_lock(&mutex);
+    pthread_cond_wait(&server_can_start_cond, &mutex);
+    pthread_mutex_unlock(&mutex);
+    pthread_mutex_destroy(&mutex);
+
+    exit (dix_main(args->argc, args->argv, args->envp));
 }
 
-/*
- * DarwinHandleGUI
- *  This function is called first from main(). The first time
- *  it is called we start the Mac OS X front end. The front end
- *  will call main() again from another thread to run the X
- *  server. On the second call this function loads the user
- *  preferences set by the Mac OS X front end.
- */
-void DarwinHandleGUI(int argc, char **argv, char **envp) {
-    static Bool been_here = FALSE;
+static pthread_t create_thread (void *func, void *arg) {
+    pthread_attr_t attr;
+    pthread_t tid;
+	
+    pthread_attr_init (&attr);
+    pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
+    pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
+    pthread_create (&tid, &attr, func, arg);
+    pthread_attr_destroy (&attr);
+	
+    return tid;
+}
+
+int main(int argc, char **argv, char **envp) {
     int         i;
     int         fd[2];
 
-    if (been_here) {
-        return;
-    }
-    been_here = TRUE;
-    
+    /* Store the args to pass to dix_main() */
+    struct arg  args;
+    args.argc = argc;
+    args.argv = argv;
+    args.envp = envp;
+
     // Make a pipe to pass events
     assert( pipe(fd) == 0 );
     darwinEventReadFD = fd[0];
     darwinEventWriteFD = fd[1];
     fcntl(darwinEventReadFD, F_SETFL, O_NONBLOCK);
 
-    // Store command line arguments to pass back to main()
-    argcGlobal = argc;
-    argvGlobal = argv;
-    envpGlobal = envp;
-
     for (i = 1; i < argc; i++) {
         // Display version info without starting Mac OS X UI if requested
         if (!strcmp( argv[i], "-showconfig" ) || !strcmp( argv[i], "-version" )) {
@@ -93,16 +110,20 @@ void DarwinHandleGUI(int argc, char **argv, char **envp) {
         }
     }
 
-    /* Initially I ran the X server on the main thread, and received
-       events on the second thread. But now we may be using Carbon,
-       that needs to run on the main thread. (Otherwise, when it's
-       prebound, it will initialize itself on the wrong thread)
-       
-       grr.. but doing that means that if the X thread gets scheduled
-       before the main thread when we're _not_ prebound, things fail,
-       so initialize by hand. */
-
-    _InitHLTB();    
-    X11ControllerMain(argc, (const char **)argv, server_thread, NULL);
+    /* Create the audio mutex */
+    QuartzAudioInit();
+    
+    pthread_cond_init(&server_can_start_cond, NULL); 
+    
+    APPKIT_THREAD_ID = pthread_self();
+    SERVER_THREAD_ID = create_thread(server_thread, &args);
+
+    if (!SERVER_THREAD_ID) {
+        ErrorF("can't create secondary thread\n");
+        exit (1);
+    }
+
+    QuartzMoveToForeground();
+    X11ControllerMain(argc, (const char **)argv);
     exit(0);
 }
diff --git a/hw/xquartz/threadSafety.c b/hw/xquartz/threadSafety.c
index 7835de6..b5a4ecf 100644
--- a/hw/xquartz/threadSafety.c
+++ b/hw/xquartz/threadSafety.c
@@ -33,8 +33,8 @@
 
 #include <execinfo.h>
 
-pthread_t SERVER_THREAD;
-pthread_t APPKIT_THREAD;
+pthread_t APPKIT_THREAD_ID;
+pthread_t SERVER_THREAD_ID;
 
 void spewCallStack(void) {
     void* callstack[128];
@@ -48,7 +48,7 @@ void spewCallStack(void) {
     free(strs);
 }
 
-void _threadAssert(pthread_t tid, const char *file, const char *fun, int line) {
+void _threadSafetyAssert(pthread_t tid, const char *file, const char *fun, int line) {
     if(pthread_equal(pthread_self(), tid))
         return;
     
@@ -58,3 +58,13 @@ void _threadAssert(pthread_t tid, const char *file, const char *fun, int line) {
            file, fun, line);
     spewCallStack();
 }
+
+const char *threadSafetyID(pthread_t tid) {
+    if(pthread_equal(tid, APPKIT_THREAD_ID)) {
+        return "Appkit Thread";
+    } else if(pthread_equal(tid, SERVER_THREAD_ID)) {
+        return "Xserver Thread";
+    } else {        
+        return "Unknown Thread";
+    }
+}
diff --git a/hw/xquartz/threadSafety.h b/hw/xquartz/threadSafety.h
index ed2ad9f..7b00910 100644
--- a/hw/xquartz/threadSafety.h
+++ b/hw/xquartz/threadSafety.h
@@ -31,22 +31,23 @@
 
 #include <pthread.h>
 
-extern pthread_t SERVER_THREAD;
-extern pthread_t APPKIT_THREAD;
-
-#define threadSafetyID(tid) (pthread_equal((tid), SERVER_THREAD) ? "X Server Thread" : "Appkit Thread")
+extern pthread_t APPKIT_THREAD_ID;
+extern pthread_t SERVER_THREAD_ID;
 
 /* Dump the call stack */
 void spewCallStack(void);
 
 /* Print message to ErrorF if we're in the wrong thread */
-void _threadAssert(pthread_t tid, const char *file, const char *fun, int line);
+void _threadSafetyAssert(pthread_t tid, const char *file, const char *fun, int line);
+
+/* Get a string that identifies our thread nicely */
+const char *threadSafetyID(pthread_t tid);
 
-#define threadAssert(tid) _threadAssert(tid, __FILE__, __FUNCTION__, __LINE__)
+#define threadSafetyAssert(tid) _threadSafetyAssert(tid, __FILE__, __FUNCTION__, __LINE__)
 
 #ifdef DEBUG_THREADS
-#define TA_SERVER() threadAssert(SERVER_THREAD)
-#define TA_APPKIT() threadAssert(APPKIT_THREAD)
+#define TA_APPKIT() threadSafetyAssert(APPKIT_THREAD_ID)
+#define TA_SERVER() threadSafetyAssert(SERVER_THREAD_ID)
 #else
 #define TA_SERVER() 
 #define TA_APPKIT() 
commit b114d4e861885cc5b49cd81b33ad825461811b3e
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 26 17:04:49 2008 -0700

    XQuartz: Don't subtract the titlebar off of the pointer_y
    (cherry picked from commit 00a9567acce2b27a649cbebd4790e3043688a7d8)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 265819a..eefa45f 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -867,8 +867,6 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
 		pointer_y = (screen.origin.y + screen.size.height) - location.y;
 	}
 
-	pointer_y -= aquaMenuBarHeight;
-
 	pressure = 0;  // for tablets
 	tilt_x = 0;
 	tilt_y = 0;
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index afa292f..0643e53 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -367,6 +367,8 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	static int darwinFakeMouseButtonMask = 0;
 	int i, num_events;
 
+    //DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+    
 	if(!darwinEvents) {
 		ErrorF("DarwinSendPointerEvents called before darwinEvents was initialized\n");
 		return;
commit b9ca7896356f79ee27be5d5aa62052f6984282b0
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Apr 25 17:54:36 2008 -0700

    XQuartz: Added some pseudoramiX debug traces
    (cherry picked from commit 5bee1585a399eab0a7b6fc80ad476d81b5d227d3)

diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 3231077..6d2fbd0 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -130,4 +130,6 @@ extern FILE *debug_log_fp;
 #define DEBUG_LOG(msg, args...) 
 #endif
 
+#define TRACE() DEBUG_LOG("\n")
+
 #endif  /* _DARWIN_H */
diff --git a/hw/xquartz/pseudoramiX.c b/hw/xquartz/pseudoramiX.c
index 49d5eb6..aafaa26 100644
--- a/hw/xquartz/pseudoramiX.c
+++ b/hw/xquartz/pseudoramiX.c
@@ -37,6 +37,7 @@ Equipment Corporation.
 #include <dix-config.h>
 #endif
 
+#include "darwin.h"
 #include "pseudoramiX.h"
 #include "extnsionst.h"
 #include "dixstruct.h"
@@ -99,6 +100,8 @@ PseudoramiXAddScreen(int x, int y, int w, int h)
                                       sizeof(PseudoramiXScreenRec));
     }
 
+    DEBUG_LOG("x: %d, y: %d, w: %d, h: %d\n", x, y, w, h);
+
     s = &pseudoramiXScreens[pseudoramiXNumScreens++];
     s->x = x;
     s->y = y;
@@ -116,6 +119,8 @@ void PseudoramiXExtensionInit(int argc, char *argv[])
 
     if (noPseudoramiXExtension) return;
 
+    TRACE();
+
     /* Even with only one screen we need to enable PseudoramiX to allow
        dynamic screen configuration changes. */
 #if 0
@@ -153,12 +158,16 @@ void PseudoramiXExtensionInit(int argc, char *argv[])
 
 void PseudoramiXResetScreens(void)
 {
+    TRACE();
+
     pseudoramiXNumScreens = 0;
 }
 
 
 static void PseudoramiXResetProc(ExtensionEntry *extEntry)
 {
+    TRACE();
+
     PseudoramiXResetScreens();
 }
 
@@ -166,6 +175,8 @@ static void PseudoramiXResetProc(ExtensionEntry *extEntry)
 // was PanoramiX
 static int ProcPseudoramiXQueryVersion(ClientPtr client)
 {
+    TRACE();
+
     return ProcPanoramiXQueryVersion(client);
 }
 
@@ -178,6 +189,8 @@ static int ProcPseudoramiXGetState(ClientPtr client)
     xPanoramiXGetStateReply rep;
     register int n, rc;
 
+    TRACE();
+    
     REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
     rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
     if (rc != Success)
@@ -205,6 +218,8 @@ static int ProcPseudoramiXGetScreenCount(ClientPtr client)
     xPanoramiXGetScreenCountReply rep;
     register int n, rc;
 
+    TRACE();
+    
     REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
     rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
     if (rc != Success)
@@ -232,6 +247,8 @@ static int ProcPseudoramiXGetScreenSize(ClientPtr client)
     xPanoramiXGetScreenSizeReply	rep;
     register int			n, rc;
 
+    TRACE();
+    
     REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
     rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
     if (rc != Success)
@@ -262,6 +279,8 @@ static int ProcPseudoramiXIsActive(ClientPtr client)
     /* REQUEST(xXineramaIsActiveReq); */
     xXineramaIsActiveReply	rep;
 
+    TRACE();
+    
     REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
 
     rep.type = X_Reply;
@@ -285,6 +304,8 @@ static int ProcPseudoramiXQueryScreens(ClientPtr client)
     /* REQUEST(xXineramaQueryScreensReq); */
     xXineramaQueryScreensReply	rep;
 
+    DEBUG_LOG("noPseudoramiXExtension=%d, pseudoramiXNumScreens=%d\n", noPseudoramiXExtension, pseudoramiXNumScreens);
+    
     REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
 
     rep.type = X_Reply;
@@ -327,6 +348,7 @@ static int ProcPseudoramiXQueryScreens(ClientPtr client)
 // was PanoramiX
 static int ProcPseudoramiXDispatch (ClientPtr client)
 {   REQUEST(xReq);
+    TRACE();
     switch (stuff->data)
     {
 	case X_PanoramiXQueryVersion:
@@ -353,6 +375,8 @@ SProcPseudoramiXQueryVersion (ClientPtr client)
 	REQUEST(xPanoramiXQueryVersionReq);
 	register int n;
 
+    TRACE();
+
 	swaps(&stuff->length,n);
 	REQUEST_SIZE_MATCH (xPanoramiXQueryVersionReq);
 	return ProcPseudoramiXQueryVersion(client);
@@ -364,6 +388,8 @@ SProcPseudoramiXGetState(ClientPtr client)
 	REQUEST(xPanoramiXGetStateReq);
 	register int n;
 
+    TRACE();
+
  	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
 	return ProcPseudoramiXGetState(client);
@@ -375,6 +401,8 @@ SProcPseudoramiXGetScreenCount(ClientPtr client)
 	REQUEST(xPanoramiXGetScreenCountReq);
 	register int n;
 
+    TRACE();
+
 	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
 	return ProcPseudoramiXGetScreenCount(client);
@@ -386,6 +414,8 @@ SProcPseudoramiXGetScreenSize(ClientPtr client)
 	REQUEST(xPanoramiXGetScreenSizeReq);
 	register int n;
 
+    TRACE();
+
 	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
 	return ProcPseudoramiXGetScreenSize(client);
@@ -398,6 +428,8 @@ SProcPseudoramiXIsActive(ClientPtr client)
 	REQUEST(xXineramaIsActiveReq);
 	register int n;
 
+    TRACE();
+
 	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
 	return ProcPseudoramiXIsActive(client);
@@ -410,6 +442,8 @@ SProcPseudoramiXQueryScreens(ClientPtr client)
 	REQUEST(xXineramaQueryScreensReq);
 	register int n;
 
+    TRACE();
+
 	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
 	return ProcPseudoramiXQueryScreens(client);
@@ -419,6 +453,9 @@ SProcPseudoramiXQueryScreens(ClientPtr client)
 static int
 SProcPseudoramiXDispatch (ClientPtr client)
 {   REQUEST(xReq);
+
+    TRACE();
+
     switch (stuff->data)
     {
 	case X_PanoramiXQueryVersion:
diff --git a/hw/xquartz/quartzCocoa.m b/hw/xquartz/quartzCocoa.m
index aa4b9fb..2890d34 100644
--- a/hw/xquartz/quartzCocoa.m
+++ b/hw/xquartz/quartzCocoa.m
@@ -44,8 +44,6 @@
 
 #include "darwin.h"
 
-#include "pseudoramiX.h"
-
 extern void FatalError(const char *, ...);
 extern char *display;
 extern int noPanoramiXExtension;
commit 0209e46249b61974a6e3ed54a51cc36dfaf0064f
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 23:48:11 2008 -0700

    XQuartz: More multi-monitor work... reverted Ben's workaround (worked for side-by-side only) and added more debugging.
    (cherry picked from commit 515b8b855ac5d2d5aef881053f73b2ad07a6dd2e)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index aad55fc..c18b575 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -535,8 +535,7 @@ DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo)
     /* Find leftmost screen. If there's a tie, take the topmost of the two. */
     for (i = 1; i < pScreenInfo->numScreens; i++) {
         if (dixScreenOrigins[i].x < left  ||
-            (dixScreenOrigins[i].x == left &&
-             dixScreenOrigins[i].y < top))
+            (dixScreenOrigins[i].x == left && dixScreenOrigins[i].y < top))
         {
             left = dixScreenOrigins[i].x;
             top = dixScreenOrigins[i].y;
@@ -545,17 +544,20 @@ DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo)
 
     darwinMainScreenX = left;
     darwinMainScreenY = top;
+    
+    DEBUG_LOG("top = %d, left=%d\n", top, left);
 
     /* Shift all screens so that there is a screen whose top left
-       is at X11 (0,0) and at global screen coordinate
-       (darwinMainScreenX, darwinMainScreenY). */
+     * is at X11 (0,0) and at global screen coordinate
+     * (darwinMainScreenX, darwinMainScreenY).
+     */
 
     if (darwinMainScreenX != 0 || darwinMainScreenY != 0) {
         for (i = 0; i < pScreenInfo->numScreens; i++) {
             dixScreenOrigins[i].x -= darwinMainScreenX;
             dixScreenOrigins[i].y -= darwinMainScreenY;
-    /*            ErrorF("Screen %d placed at X11 coordinate (%d,%d).\n",
-		  i, dixScreenOrigins[i].x, dixScreenOrigins[i].y); */
+            DEBUG_LOG("Screen %d placed at X11 coordinate (%d,%d).\n",
+                      i, dixScreenOrigins[i].x, dixScreenOrigins[i].y);
         }
     }
 }
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 583d7ef..7312226 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -153,7 +153,8 @@ displayScreenBounds(CGDirectDisplayID id, Bool remove_menubar)
               (int)frame.origin.x, (int)frame.origin.y);
     
     /* Remove menubar to help standard X11 window managers. */
-    if (remove_menubar && !quartzHasRoot && id == 0) {
+    if (remove_menubar && !quartzHasRoot && 
+        frame.origin.x == 0 && frame.origin.y == 0) {
         frame.origin.y += aquaMenuBarHeight;
         frame.size.height -= aquaMenuBarHeight;
     }
@@ -201,6 +202,9 @@ xprAddPseudoramiXScreens(int *x, int *y, int *width, int *height)
     *width = unionRect.size.width;
     *height = unionRect.size.height;
 
+    DEBUG_LOG("  screen union origin: (%d,%d) size: (%d,%d).\n",
+              *x, *y, *width, *height);
+
     /* Tell PseudoramiX about the real screens. */
     for (i = 0; i < displayCount; i++)
     {
@@ -229,7 +233,7 @@ xprDisplayInit(void)
 {
     CGDisplayCount displayCount;
 
-    //    ErrorF("Display mode: Rootless Quartz -- Xplugin implementation\n");
+    DEBUG_LOG("");
 
     CGGetActiveDisplayList(0, NULL, &displayCount);
 
@@ -265,6 +269,8 @@ xprAddScreen(int index, ScreenPtr pScreen)
 {
     DarwinFramebufferPtr dfb = SCREEN_PRIV(pScreen);
     int depth = darwinDesiredDepth;
+
+    DEBUG_LOG("index=%d depth=%d\n", index, depth);
     
     if(depth == -1) {
         depth = CGDisplaySamplesPerPixel(kCGDirectMainDisplay) * CGDisplayBitsPerSample(kCGDirectMainDisplay);
commit b65dbd350b8518bb90bed9cdc64dd900bc75d20c
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 21:14:04 2008 -0700

    XQuartz: Cleaned up multi-monitor support.
    (cherry picked from commit c05abf0a19b0ef0fc4ace9400a095ce2521456bc)
    (cherry picked from commit 9112f290434c246d3e797551aaaf3a89d2006b23)

diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 6f7598f..583d7ef 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -142,20 +142,26 @@ displayAtIndex(int index)
  *  Return the bounds of a particular display.
  */
 static CGRect
-displayScreenBounds(CGDirectDisplayID id)
+displayScreenBounds(CGDirectDisplayID id, Bool remove_menubar)
 {
     CGRect frame;
 
     frame = CGDisplayBounds(id);
 
+    DEBUG_LOG("    %dx%d @ (%d,%d).\n",
+              (int)frame.size.width, (int)frame.size.height,
+              (int)frame.origin.x, (int)frame.origin.y);
+    
     /* Remove menubar to help standard X11 window managers. */
-
-    if (frame.origin.y == 0)
-    {
+    if (remove_menubar && !quartzHasRoot && id == 0) {
         frame.origin.y += aquaMenuBarHeight;
         frame.size.height -= aquaMenuBarHeight;
     }
 
+    DEBUG_LOG("    %dx%d @ (%d,%d).\n",
+              (int)frame.size.width, (int)frame.size.height,
+              (int)frame.origin.x, (int)frame.origin.y);
+
     return frame;
 }
 
@@ -179,8 +185,13 @@ xprAddPseudoramiXScreens(int *x, int *y, int *width, int *height)
     /* Get the union of all screens */
     for (i = 0; i < displayCount; i++)
     {
+
+        /* we can't remove the menubar from the screen - doing so
+         * would constrain the pointer to the screen, not allowing it
+         * to reach the menubar..
+         */
         CGDirectDisplayID dpy = displayList[i];
-        frame = displayScreenBounds(dpy);
+        frame = displayScreenBounds(dpy, FALSE);
         unionRect = CGRectUnion(unionRect, frame);
     }
 
@@ -195,17 +206,12 @@ xprAddPseudoramiXScreens(int *x, int *y, int *width, int *height)
     {
         CGDirectDisplayID dpy = displayList[i];
 
-        frame = displayScreenBounds(dpy);
-
-	/*        ErrorF("PseudoramiX screen %d added: %dx%d @ (%d,%d).\n", i,
-               (int)frame.size.width, (int)frame.size.height,
-               (int)frame.origin.x, (int)frame.origin.y); */
-
+        frame = displayScreenBounds(dpy, TRUE);
         frame.origin.x -= unionRect.origin.x;
         frame.origin.y -= unionRect.origin.y;
 
-	/*        ErrorF("PseudoramiX screen %d placed at X11 coordinate (%d,%d).\n",
-		  i, (int)frame.origin.x, (int)frame.origin.y); */
+        DEBUG_LOG("    placed at X11 coordinate (%d,%d).\n",
+                  (int)frame.origin.x, (int)frame.origin.y);
 
         PseudoramiXAddScreen(frame.origin.x, frame.origin.y,
                              frame.size.width, frame.size.height);
@@ -315,12 +321,14 @@ xprAddScreen(int index, ScreenPtr pScreen)
 
     if (noPseudoramiXExtension)
     {
+        ErrorF("Warning: noPseudoramiXExtension!\n");
+        
         CGDirectDisplayID dpy;
         CGRect frame;
 
         dpy = displayAtIndex(index);
 
-        frame = displayScreenBounds(dpy);
+        frame = displayScreenBounds(dpy, TRUE);
 
         dfb->x = frame.origin.x;
         dfb->y = frame.origin.y;
commit 5869e3f5551e7e2d18e06a2f220b77d8c4161db1
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 19:39:27 2008 -0700

    darwin gots /dev/urandom, too yo!
    (cherry picked from commit bf0144f38034bc59f108bb2c5270ff37fbe70e10)

diff --git a/configure.ac b/configure.ac
index b42b120..67606c7 100644
--- a/configure.ac
+++ b/configure.ac
@@ -177,7 +177,7 @@ AC_CHECK_FUNC([dlopen], [],
 	AC_CHECK_LIB([dl], [dlopen], DLOPEN_LIBS="-ldl"))
 
 case $host_os in
-    linux*)
+    linux*|darwin*)
 	AC_DEFINE(HAVE_URANDOM, 1, [Has /dev/urandom]) ;;
     solaris*)
 	# Solaris 8 with patches, or Solaris 9 or later have /dev/urandom
commit b1ae7c79db78cc3b789701f81328669f9f8ed80f
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Thu Apr 24 19:02:43 2008 -0700

    Bug 14247: If pkg-config can't find openssl.pc, just link with -lcrypto
    
    X.Org bugzilla #14247 <http://bugs.freedesktop.org/show_bug.cgi?id=14247>

diff --git a/configure.ac b/configure.ac
index b2a07a6..b42b120 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1118,7 +1118,9 @@ PKG_CHECK_MODULES([XSERVERLIBS], [$REQUIRED_LIBS])
 
 # OpenSSL used for SHA1 hashing in render/glyph.c, but we don't need all of
 # the OpenSSL libraries, just libcrypto
-PKG_CHECK_MODULES([OPENSSL], [openssl], [OPENSSL_LIB_FLAGS=`$PKG_CONFIG --libs-only-L --libs-only-other openssl`])
+PKG_CHECK_EXISTS([openssl],
+ [PKG_CHECK_MODULES([OPENSSL], [openssl],
+   [OPENSSL_LIB_FLAGS=`$PKG_CONFIG --libs-only-L --libs-only-other openssl`])])
 LIBCRYPTO="$OPENSSL_LIB_FLAGS -lcrypto"
 
 # Autotools has some unfortunate issues with library handling.  In order to
commit 1daae4574c19a122baf73b6f9457b0d383b1bc66
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 18:22:05 2008 -0700

    Added missing HAVE_LAUNCHD to dix-config.h.in
    (cherry picked from commit 1b4b73cefbc2f3e3f6d0cb84ea202f84fb60abb5)

diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 135d3d8..fc1caa3 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -148,6 +148,9 @@
 /* Define to 1 if you have version 2.2 (or newer) of the drm library */
 #undef HAVE_LIBDRM_2_2
 
+/* Define to 1 if launchd is available. */
+#undef HAVE_LAUNCHD
+
 /* Have Quartz */
 #undef XQUARTZ
 
commit 63853e4ad211945ed25541223207a78f83766ced
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 18:21:42 2008 -0700

    XQuartz: Compile in missing glx source that we still need
    (cherry picked from commit c611335dee267e41dcd1733a6bb5206b102f804e)

diff --git a/GL/glx/Makefile.am b/GL/glx/Makefile.am
index 1d4719c..9bf296c 100644
--- a/GL/glx/Makefile.am
+++ b/GL/glx/Makefile.am
@@ -47,7 +47,12 @@ libglxdri_la_SOURCES = \
         extension_string.c \
         extension_string.h
 
+#if XQUARTZ
+XQUARTZ_libglx_la_SOURCES = glcontextmodes.c
+#endif
+
 libglx_la_SOURCES = \
+	$(XQUARTZ_libglx_la_SOURCES) \
         g_disptab.h \
         glxbyteorder.h \
         glxcmds.c \
commit ae982a27e4059fecd4048d245e6aa02f8dcc97d0
Author: Dave Airlie <airlied at redhat.com>
Date:   Thu Apr 24 16:37:29 2008 +1000

    glx: test for valid read and draw privates before using them
    
    this should fix a bug where f-spot exiting blows up the X server

diff --git a/GL/glx/glxutil.c b/GL/glx/glxutil.c
index 11e9f89..aa23a95 100644
--- a/GL/glx/glxutil.c
+++ b/GL/glx/glxutil.c
@@ -81,38 +81,40 @@ __glXDeassociateContext(__GLXcontext *glxc)
     __GLXcontext *curr, *prev;
 
     prev = NULL;
-    for ( curr = glxc->drawPriv->drawGlxc
-	  ; curr != NULL
-	  ; prev = curr, curr = curr->nextDrawPriv ) {
-	if (curr == glxc) {
-	    /* found context.  Deassociate. */
-	    if (prev == NULL) {
-		glxc->drawPriv->drawGlxc = curr->nextDrawPriv;
-	    } else {
-		prev->nextDrawPriv = curr->nextDrawPriv;
+    if (glxc->drawPriv) {
+        for ( curr = glxc->drawPriv->drawGlxc; curr != NULL
+	      ; prev = curr, curr = curr->nextDrawPriv ) {
+	    if (curr == glxc) {
+	        /* found context.  Deassociate. */
+	        if (prev == NULL) {
+		    glxc->drawPriv->drawGlxc = curr->nextDrawPriv;
+	        } else {
+		    prev->nextDrawPriv = curr->nextDrawPriv;
+	        }
+	        curr->nextDrawPriv = NULL;
+	        __glXUnrefDrawable(glxc->drawPriv);
+	        break;
 	    }
-	    curr->nextDrawPriv = NULL;
-	    __glXUnrefDrawable(glxc->drawPriv);
-	    break;
-	}
+        }
     }
 
-
     prev = NULL;
-    for ( curr = glxc->readPriv->readGlxc
-	  ; curr != NULL 
-	  ; prev = curr, curr = curr->nextReadPriv ) {
-	if (curr == glxc) {
-	    /* found context.  Deassociate. */
-	    if (prev == NULL) {
-		glxc->readPriv->readGlxc = curr->nextReadPriv;
-	    } else {
-		prev->nextReadPriv = curr->nextReadPriv;
-	    }
-	    curr->nextReadPriv = NULL;
-	    __glXUnrefDrawable(glxc->readPriv);
-	    break;
-	}
+    if (glxc->readPriv) {
+        for ( curr = glxc->readPriv->readGlxc
+	      ; curr != NULL 
+	      ; prev = curr, curr = curr->nextReadPriv ) {
+	    if (curr == glxc) {
+	        /* found context.  Deassociate. */
+	        if (prev == NULL) {
+		    glxc->readPriv->readGlxc = curr->nextReadPriv;
+	        } else {
+		    prev->nextReadPriv = curr->nextReadPriv;
+	        }
+	        curr->nextReadPriv = NULL;
+	        __glXUnrefDrawable(glxc->readPriv);
+	       break;
+	   }
+       }
     }
 }
 
commit f377141912594f87144d6d7f7fdd279a101d8e6c
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Thu Apr 24 13:30:28 2008 +0930

    Xi: don't attempt to send to a NULL window.
    
    Only applicable when the server comes down/restarts. In this case,
    WindowTable[i] may be NULL. Let's not try to send an event then.

diff --git a/Xi/exevents.c b/Xi/exevents.c
index fb84bef..641bead 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1279,6 +1279,8 @@ SendEventToAllWindows(DeviceIntPtr dev, Mask mask, xEvent * ev, int count)
 
     for (i = 0; i < screenInfo.numScreens; i++) {
         pWin = WindowTable[i];
+        if (!pWin)
+            continue;
         (void)DeliverEventsToWindow(pWin, ev, count, mask, NullGrab, dev->id);
         p1 = pWin->firstChild;
         FindInterestedChildren(dev, p1, mask, ev, count);
commit aec485f2dcc87b340759d67b60e7dee7931aaec5
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Thu Apr 24 13:29:46 2008 +0930

    dix: NULL out WindowTable after freeing all the windows.
    
    CloseDownDevices() tries to send PresenceNotify events. If the windows are
    already freed, then we are accessing dangling pointers.

diff --git a/dix/main.c b/dix/main.c
index db43473..6d9dd33 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -458,7 +458,10 @@ main(int argc, char *argv[], char *envp[])
 #endif
 
         config_fini();
+
+        memset(WindowTable, 0, MAXSCREENS * sizeof(WindowPtr));
 	CloseDownDevices();
+
 	for (i = screenInfo.numScreens - 1; i >= 0; i--)
 	{
 	    FreeScratchPixmapsForScreen(i);
commit 9ab4e2fd8eaa87dbd16835affb1aa54dcb1a619e
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Wed Apr 23 11:38:08 2008 +0930

    xfree86: don't free the config-file related information in DIDR. #15645
    
    In DeleteInputDeviceRequest, leave the conf_idev (which is shared with
    xf86ConfigLayout.input) alone for devices that were specified in the
    ServerLayout section of the config file. This way, in the next server
    generation we are left with what was the original config and can thus re-init
    the devices.
    
    This is an addon to 6d22a9615a0e6ab3d00b0bcb22ff001b6ece02ae, an attempt to
    fix Bug 14418.
    
    X.Org Bug 15645 <https://bugs.freedesktop.org/show_bug.cgi?id=15645>
    X.Org Bug 14418 <https://bugs.freedesktop.org/show_bug.cgi?id=15645>

diff --git a/hw/xfree86/common/xf86Init.c b/hw/xfree86/common/xf86Init.c
index 6d5eaad..68dc387 100644
--- a/hw/xfree86/common/xf86Init.c
+++ b/hw/xfree86/common/xf86Init.c
@@ -1123,37 +1123,35 @@ InitInput(argc, argv)
     xf86Info.vtRequestsPending = FALSE;
     xf86Info.inputPending = FALSE;
 
-    if (serverGeneration == 1) {
-	/* Call the PreInit function for each input device instance. */
-	for (pDev = xf86ConfigLayout.inputs; pDev && *pDev; pDev++) {
-	    /* Replace obsolete keyboard driver with kbd */
-	    if (!xf86NameCmp((*pDev)->driver, "keyboard")) {
-		strcpy((*pDev)->driver, "kbd");
-            }
-
-	    if ((pDrv = xf86LookupInputDriver((*pDev)->driver)) == NULL) {
-		xf86Msg(X_ERROR, "No Input driver matching `%s'\n", (*pDev)->driver);
-		/* XXX For now, just continue. */
-		continue;
-	    }
-	    if (!pDrv->PreInit) {
-		xf86MsgVerb(X_WARNING, 0,
-		    "Input driver `%s' has no PreInit function (ignoring)\n",
-		    pDrv->driverName);
-		continue;
-	    }
-	    pInfo = pDrv->PreInit(pDrv, *pDev, 0);
-	    if (!pInfo) {
-		xf86Msg(X_ERROR, "PreInit returned NULL for \"%s\"\n",
-			(*pDev)->identifier);
-		continue;
-	    } else if (!(pInfo->flags & XI86_CONFIGURED)) {
-		xf86Msg(X_ERROR, "PreInit failed for input device \"%s\"\n",
-			(*pDev)->identifier);
-		xf86DeleteInput(pInfo, 0);
-		continue;
-	    }
-	}
+    /* Call the PreInit function for each input device instance. */
+    for (pDev = xf86ConfigLayout.inputs; pDev && *pDev; pDev++) {
+        /* Replace obsolete keyboard driver with kbd */
+        if (!xf86NameCmp((*pDev)->driver, "keyboard")) {
+            strcpy((*pDev)->driver, "kbd");
+        }
+
+        if ((pDrv = xf86LookupInputDriver((*pDev)->driver)) == NULL) {
+            xf86Msg(X_ERROR, "No Input driver matching `%s'\n", (*pDev)->driver);
+            /* XXX For now, just continue. */
+            continue;
+        }
+        if (!pDrv->PreInit) {
+            xf86MsgVerb(X_WARNING, 0,
+                    "Input driver `%s' has no PreInit function (ignoring)\n",
+                    pDrv->driverName);
+            continue;
+        }
+        pInfo = pDrv->PreInit(pDrv, *pDev, 0);
+        if (!pInfo) {
+            xf86Msg(X_ERROR, "PreInit returned NULL for \"%s\"\n",
+                    (*pDev)->identifier);
+            continue;
+        } else if (!(pInfo->flags & XI86_CONFIGURED)) {
+            xf86Msg(X_ERROR, "PreInit failed for input device \"%s\"\n",
+                    (*pDev)->identifier);
+            xf86DeleteInput(pInfo, 0);
+            continue;
+        }
     }
 
     /* Initialise all input devices. */
diff --git a/hw/xfree86/common/xf86Xinput.c b/hw/xfree86/common/xf86Xinput.c
index d34238e..710e787 100644
--- a/hw/xfree86/common/xf86Xinput.c
+++ b/hw/xfree86/common/xf86Xinput.c
@@ -448,6 +448,8 @@ DeleteInputDeviceRequest(DeviceIntPtr pDev)
     LocalDevicePtr pInfo = (LocalDevicePtr) pDev->public.devicePrivate;
     InputDriverPtr drv;
     IDevRec *idev;
+    BOOL found;
+    IDevPtr *it;
 
     if (pInfo) /* need to get these before RemoveDevice */
     {
@@ -464,10 +466,18 @@ DeleteInputDeviceRequest(DeviceIntPtr pDev)
     else
         xf86DeleteInput(pInfo, 0);
 
-    xfree(idev->driver);
-    xfree(idev->identifier);
-    xf86optionListFree(idev->commonOptions);
-    xfree(idev);
+    /* devices added through HAL aren't in the config layout */
+    it = xf86ConfigLayout.inputs;
+    while(*it && *it != idev)
+        it++;
+
+    if (!(*it)) /* end of list, not in the layout */
+    {
+        xfree(idev->driver);
+        xfree(idev->identifier);
+        xf86optionListFree(idev->commonOptions);
+        xfree(idev);
+    }
 }
 
 /* 
commit d09c520b322ba5c5f4d6b630a7c0c62e56732f82
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 23 10:22:34 2008 -0700

    Moved Apple GL bits into our DDX subtree
    (cherry picked from commit c9356f32892978faecb30f7b7af7488820ce37ff)

diff --git a/GL/Makefile.am b/GL/Makefile.am
index 44fca18..c3ac155 100644
--- a/GL/Makefile.am
+++ b/GL/Makefile.am
@@ -1,9 +1,4 @@
-if XQUARTZ
-XQUARTZ_SUBDIRS = apple
-endif
-
-SUBDIRS = glx $(XQUARTZ_SUBDIRS)
-DIST_SUBDIRS = glx apple
+SUBDIRS = glx
 
 WINDOWS_EXTRAS = \
 	windows/ChangeLog \
diff --git a/GL/apple/Makefile.am b/GL/apple/Makefile.am
deleted file mode 100644
index 7ad9140..0000000
--- a/GL/apple/Makefile.am
+++ /dev/null
@@ -1,14 +0,0 @@
-AM_CFLAGS = $(DIX_CFLAGS)
-AM_CPPFLAGS = \
-	-I$(top_srcdir) \
-	-I$(top_srcdir)/GL/glx \
-	-I$(top_srcdir)/GL/include \
-	-I$(top_srcdir)/GL/mesa/glapi \
-	-I$(top_srcdir)/hw/xquartz \
-	-I$(top_srcdir)/hw/xquartz/xpr \
-	-I$(top_srcdir)/miext/damage
-
-noinst_LIBRARIES = libCGLcore.a 
-libCGLcore_a_SOURCES = \
-	indirect.c \
-	$(top_srcdir)/hw/dmx/glxProxy/compsize.c
diff --git a/GL/apple/indirect.c b/GL/apple/indirect.c
deleted file mode 100644
index a0884d4..0000000
--- a/GL/apple/indirect.c
+++ /dev/null
@@ -1,1940 +0,0 @@
-/*
- * GLX implementation that uses Apple's OpenGL.framework
- * (Indirect rendering path)
- *
- * Copyright (c) 2007 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.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "dri.h"
-
-#define GL_EXT_histogram 1
-#define GL_EXT_polygon_offset 1
-#define GL_SGIS_pixel_texture 1
-#define GL_SGIX_pixel_texture 1
-#define GL_EXT_multisample 1
-#define GL_SGIS_multisample 1
-#define GL_EXT_vertex_array 1
-#define GL_ARB_point_parameters 1
-#define GL_NV_vertex_array_range 1
-#define GL_MESA_resize_buffers 1
-#define GL_ARB_window_pos 1
-#define GL_EXT_cull_vertex 1
-#define GL_NV_vertex_program 1
-#define GL_APPLE_fence 1
-#define GL_IBM_multimode_draw_arrays 1
-#define GL_EXT_fragment_shader 1
-
-#include <OpenGL/OpenGL.h>
-#include <OpenGL/CGLContext.h>
-
-// X11 and X11's glx
-#include <GL/gl.h>
-#include <GL/glxproto.h>
-#include <windowstr.h>
-#include <resource.h>
-#include <GL/glxint.h>
-#include <GL/glxtokens.h>
-#include <scrnintstr.h>
-#include <glxserver.h>
-#include <glxscreens.h>
-#include <glxdrawable.h>
-#include <glxcontext.h>
-#include <glxext.h>
-#include <glxutil.h>
-#include <glxscreens.h>
-#include <GL/internal/glcore.h>
-#include "x-hash.h"
-#include "x-list.h"
-
-#include <dispatch.h>
-#define GLAPIENTRYP *
-typedef unsigned long long GLuint64EXT;
-typedef long long GLint64EXT;
-#include <Xplugin.h>
-#include "glcontextmodes.h"
-#include <glapi.h>
-#include <glapitable.h>
-
-// ggs: needed to call back to glx with visual configs
-extern void GlxSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs, void **configprivs);
-__GLXprovider * GlxGetMesaProvider (void);
-
-// Write debugging output, or not
-#ifdef GLAQUA_DEBUG
-#define GLAQUA_DEBUG_MSG ErrorF
-#else
-#define GLAQUA_DEBUG_MSG(a, ...)
-#endif
-
-static void setup_dispatch_table(void);
-GLuint __glFloorLog2(GLuint val);
-void warn_func(void * p1, char *format, ...);
-
-// some prototypes
-static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen);
-static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLXconfig *modes);
-
-static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
-                              int *nvisualp, int *ndepthp,
-                              int *rootDepthp, VisualID *defaultVisp,
-                              unsigned long sizes, int bitsPerRGB);
-static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
-                                   void **privates);
-
-static void glAquaResetExtension(void);
-static void __glXAquaContextDestroy(__GLXcontext *baseContext);
-static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext);
-static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext);
-static int __glXAquaContextForceCurrent(__GLXcontext *baseContext);
-static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask);
-
-static CGLPixelFormatObj makeFormat(__GLXconfig *mode);
-
-__GLXprovider __glXMesaProvider = {
-  __glXAquaScreenProbe,
-  "Core OpenGL",
-    NULL
-};
-
-__GLXprovider *
-GlxGetMesaProvider (void)
-{
-  GLAQUA_DEBUG_MSG("GlxGetMesaProvider\n");
-  return &__glXMesaProvider;
-}
-
-typedef struct __GLXAquaScreen   __GLXAquaScreen;
-typedef struct __GLXAquaContext  __GLXAquaContext;
-typedef struct __GLXAquaDrawable __GLXAquaDrawable;
-
-struct __GLXAquaScreen {
-  __GLXscreen   base;
-  int           index;
-    int num_vis;
-    __GLXconfig *modes;
-};
-
-static __GLXAquaScreen glAquaScreens[MAXSCREENS];
-
-struct __GLXAquaContext {
-  __GLXcontext base;
-  CGLContextObj ctx;
-  CGLPixelFormatObj pixelFormat;
-  xp_surface_id sid;
-  unsigned isAttached :1;
-};
-
-struct __GLXAquaDrawable {
-  __GLXdrawable base;
-    DrawablePtr pDraw;
-    xp_surface_id sid;
-};
-
-static __GLXcontext *
-__glXAquaScreenCreateContext(__GLXscreen *screen,
-			     __GLXconfig *config,
-			     __GLXcontext *baseShareContext)
-{
-  __GLXAquaContext *context;
-  __GLXAquaContext *shareContext = (__GLXAquaContext *) baseShareContext;
-  CGLError gl_err;
-  
-  GLAQUA_DEBUG_MSG("glXAquaScreenCreateContext\n");
-
-  context = malloc (sizeof (__GLXAquaContext));
-  if (context == NULL) return NULL;
-
-  memset(context, 0, sizeof *context);
-
-  context->base.pGlxScreen = screen;
-  context->base.config      = config;
-
-  context->base.destroy        = __glXAquaContextDestroy;
-  context->base.makeCurrent    = __glXAquaContextMakeCurrent;
-  context->base.loseCurrent    = __glXAquaContextLoseCurrent;
-  context->base.copy           = __glXAquaContextCopy;
-  context->base.forceCurrent   = __glXAquaContextForceCurrent;
-  //  context->base.createDrawable = __glXAquaContextCreateDrawable;
-
-  context->pixelFormat = makeFormat(config);
-  if (!context->pixelFormat) {
-        free(context);
-        return NULL;
-  }
-
-  context->ctx = NULL;
-  gl_err = CGLCreateContext(context->pixelFormat,
-                            shareContext ? shareContext->ctx : NULL,
-                            &context->ctx);
-
-  if (gl_err != 0) {
-      ErrorF("CGLCreateContext error: %s\n", CGLErrorString(gl_err));
-      CGLDestroyPixelFormat(context->pixelFormat);
-      free(context);
-      return NULL;
-    }
-	setup_dispatch_table();
-    GLAQUA_DEBUG_MSG("glAquaCreateContext done\n");
-  return &context->base;
-}
-
-static __GLXextensionInfo __glDDXExtensionInfo = {
-    GL_CORE_APPLE,
-    glAquaResetExtension,
-    glAquaInitVisuals,
-    glAquaSetVisualConfigs
-};
-
-void *__glXglDDXExtensionInfo(void) {
-  GLAQUA_DEBUG_MSG("glXAglDDXExtensionInfo\n");
-    return &__glDDXExtensionInfo;
-}
-
-/* maps from surface id -> list of __GLcontext */
-static x_hash_table *surface_hash;
-
-static void __glXAquaContextDestroy(__GLXcontext *baseContext) {
-    x_list *lst;
-
-    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
-
-    GLAQUA_DEBUG_MSG("glAquaContextDestroy (ctx 0x%x)\n",
-                     (unsigned int) baseContext);
-    if (context != NULL) {
-      if (context->sid != 0 && surface_hash != NULL) {
-		lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
-		lst = x_list_remove(lst, context);
-		x_hash_table_insert(surface_hash, (void *) context->sid, lst);
-      }
-
-      if (context->ctx != NULL) CGLDestroyContext(context->ctx);
-
-      if (context->pixelFormat != NULL)	CGLDestroyPixelFormat(context->pixelFormat);
-      
-      free(context);
-    }
-}
-
-static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext) {
-    CGLError gl_err;
-
-    GLAQUA_DEBUG_MSG("glAquaLoseCurrent (ctx 0x%p)\n", baseContext);
-
-    gl_err = CGLSetCurrentContext(NULL);
-    if (gl_err != 0)
-      ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
-
-    __glXLastContext = NULL; // Mesa does this; why?
-
-    return GL_TRUE;
-}
-
-/* Called when a surface is destroyed as a side effect of destroying
-   the window it's attached to. */
-static void surface_notify(void *_arg, void *data) {
-    DRISurfaceNotifyArg *arg = (DRISurfaceNotifyArg *)_arg;
-    __GLXAquaDrawable *draw = (__GLXAquaDrawable *)data;
-    __GLXAquaContext *context;
-    x_list *lst;
-	if(_arg == NULL || data == NULL) {
-		ErrorF("surface_notify called with bad params");
-		return;
-	}
-	
-    GLAQUA_DEBUG_MSG("surface_notify(%p, %p)\n", _arg, data);
-    switch (arg->kind) {
-    case AppleDRISurfaceNotifyDestroyed:
-        if (surface_hash != NULL)
-            x_hash_table_remove(surface_hash, (void *) arg->id);
-	        draw->base.pDraw = NULL;
-			draw->sid = 0;
-        break;
-
-    case AppleDRISurfaceNotifyChanged:
-        if (surface_hash != NULL) {
-            lst = x_hash_table_lookup(surface_hash, (void *) arg->id, NULL);
-            for (; lst != NULL; lst = lst->next)
-            {
-                context = lst->data;
-                xp_update_gl_context(context->ctx);
-            }
-        }
-        break;
-	default:
-		ErrorF("surface_notify: unknown kind %d\n", arg->kind);
-		break;
-    }
-}
-
-static void attach(__GLXAquaContext *context, __GLXAquaDrawable *draw) {
-    DrawablePtr pDraw;
-	GLAQUA_DEBUG_MSG("attach(%p, %p)\n", context, draw);
-    pDraw = draw->base.pDraw;
-
-    if (draw->sid == 0) {
-//        if (!quartzProcs->CreateSurface(pDraw->pScreen, pDraw->id, pDraw,
-        if (!DRICreateSurface(pDraw->pScreen, pDraw->id, pDraw,
-                                        0, &draw->sid, NULL,
-                                        surface_notify, draw))
-            return;
-        draw->pDraw = pDraw;
-	} 
-
-    if (!context->isAttached || context->sid != draw->sid) {
-        x_list *lst;
-
-        if (xp_attach_gl_context(context->ctx, draw->sid) != Success) {
-//            quartzProcs->DestroySurface(pDraw->pScreen, pDraw->id, pDraw,
-            DRIDestroySurface(pDraw->pScreen, pDraw->id, pDraw,
-								surface_notify, draw);
-            if (surface_hash != NULL)
-                x_hash_table_remove(surface_hash, (void *) draw->sid);
-
-            draw->sid = 0;
-            return;
-        }
-
-        context->isAttached = TRUE;
-        context->sid = draw->sid;
-
-        if (surface_hash == NULL)
-            surface_hash = x_hash_table_new(NULL, NULL, NULL, NULL);
-
-        lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
-        if (x_list_find(lst, context) == NULL) {
-            lst = x_list_prepend(lst, context);
-            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
-        }
-
-        GLAQUA_DEBUG_MSG("attached 0x%x to 0x%x\n", (unsigned int) pDraw->id,
-                         (unsigned int) draw->sid);
-    } 
-}
-
-#if 0     // unused
-static void unattach(__GLXAquaContext *context) {
-	x_list *lst;
-	GLAQUA_DEBUG_MSG("unattach\n");
-	if (context == NULL) {
-		ErrorF("Tried to unattach a null context\n");
-		return;
-	}
-    if (context->isAttached) {
-        GLAQUA_DEBUG_MSG("unattaching\n");
-
-        if (surface_hash != NULL) {
-            lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
-            lst = x_list_remove(lst, context);
-            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
-        }
-
-        CGLClearDrawable(context->ctx);
-        context->isAttached = FALSE;
-        context->sid = 0;
-    }
-}
-#endif
-
-static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext) {
-    CGLError gl_err;
-    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
-	__GLXAquaDrawable *drawPriv = (__GLXAquaDrawable *) context->base.drawPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaMakeCurrent (ctx 0x%p)\n", baseContext);
-    
-    attach(context, drawPriv);
-
-    gl_err = CGLSetCurrentContext(context->ctx);
-    if (gl_err != 0)
-        ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
-    
-    return gl_err == 0;
-}
-
-static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask)
-{
-    CGLError gl_err;
-
-    __GLXAquaContext *dst = (__GLXAquaContext *) baseDst;
-    __GLXAquaContext *src = (__GLXAquaContext *) baseSrc;
-
-    GLAQUA_DEBUG_MSG("GLXAquaContextCopy\n");
-
-    gl_err = CGLCopyContext(src->ctx, dst->ctx, mask);
-    if (gl_err != 0)
-        ErrorF("CGLCopyContext error: %s\n", CGLErrorString(gl_err));
-
-    return gl_err == 0;
-}
-
-static int __glXAquaContextForceCurrent(__GLXcontext *baseContext)
-{
-    CGLError gl_err;
-    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
-    GLAQUA_DEBUG_MSG("glAquaForceCurrent (ctx %p)\n", context->ctx);
-
-    gl_err = CGLSetCurrentContext(context->ctx);
-    if (gl_err != 0)
-        ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
-
-    return gl_err == 0;
-}
-
-/* Drawing surface notification callbacks */
-
-static GLboolean __glXAquaDrawableResize(__GLXdrawable *base)  {
-    GLAQUA_DEBUG_MSG("unimplemented glAquaDrawableResize\n");
-    return GL_TRUE;
-}
-
-static GLboolean __glXAquaDrawableSwapBuffers(__GLXdrawable *base) {
-    CGLError gl_err;
-	__GLXAquaContext * drawableCtx;
-//    GLAQUA_DEBUG_MSG("glAquaDrawableSwapBuffers(%p)\n",base);
-	
-	if(!base) {
-		ErrorF("glXAquaDrawbleSwapBuffers passed NULL\n");
-	    return GL_FALSE;
-	}
-
-    drawableCtx = (__GLXAquaContext *)base->drawGlxc;
-
-    if (drawableCtx != NULL && drawableCtx->ctx != NULL) {
-        gl_err = CGLFlushDrawable(drawableCtx->ctx);
-        if (gl_err != 0)
-            ErrorF("CGLFlushDrawable error: %s\n", CGLErrorString(gl_err));
-    }
-    return GL_TRUE;
-}
-
-static CGLPixelFormatObj makeFormat(__GLXconfig *config) {
-    int i;
-    CGLPixelFormatAttribute attr[64]; // currently uses max of 30
-    CGLPixelFormatObj result;
-    GLint n_formats;
-    CGLError gl_err;
-    
-    GLAQUA_DEBUG_MSG("makeFormat\n");
-
-    if (!config->rgbMode)
-        return NULL;
-
-    i = 0;
-
-    // attr [i++] = kCGLPFAAcelerated; // require hwaccel - BAD for multiscreen
-    // attr [i++] = kCGLPFANoRecovery; // disable fallback renderers - BAD
-
-    if (config->stereoMode) {
-        attr[i++] = kCGLPFAStereo;
-    }
-
-    if (config->doubleBufferMode) {
-        attr[i++] = kCGLPFADoubleBuffer;
-    }
-
-    if (config->colorIndexMode) {
-        /* ignored */
-    }
-
-    if (config->rgbMode) {
-        attr[i++] = kCGLPFAColorSize;
-        attr[i++] = config->redBits + config->greenBits + config->blueBits;
-        attr[i++] = kCGLPFAAlphaSize;
-        attr[i++] = 1; /* FIXME: ignoring config->alphaBits which is always 0 */
-    }
-
-    if (config->haveAccumBuffer) {
-        attr[i++] = kCGLPFAAccumSize;
-        attr[i++] = config->accumRedBits + config->accumGreenBits
-                    + config->accumBlueBits + config->accumAlphaBits;
-    }
-	
-    if (config->haveDepthBuffer) {
-        attr[i++] = kCGLPFADepthSize;
-        attr[i++] = config->depthBits;
-    }
-	
-    if (config->haveStencilBuffer) {
-        attr[i++] = kCGLPFAStencilSize;
-        attr[i++] = config->stencilBits;
-    }
-
-    attr[i++] = kCGLPFAAuxBuffers;
-    attr[i++] = config->numAuxBuffers;
-
-    /* mode->level ignored */
-
-    /* mode->pixmapMode ? */
-
-    attr[i++] = 0;
-
-    GLAQUA_DEBUG_MSG("makeFormat almost done\n");
-
-    result = NULL;
-    gl_err = CGLChoosePixelFormat(attr, &result, &n_formats);
-    if (gl_err != 0)
-        ErrorF("CGLChoosePixelFormat error: %s\n", CGLErrorString(gl_err));
-
-    GLAQUA_DEBUG_MSG("makeFormat done (0x%x)\n", (unsigned int) result);
-
-    return result;
-}
-
-// Originally copied from Mesa
-
-static int                 numConfigs     = 0;
-static __GLXvisualConfig  *visualConfigs  = NULL;
-static void              **visualPrivates = NULL;
-
-/*
- * In the case the driver defines no GLX visuals we'll use these.
- * Note that for TrueColor and DirectColor visuals, bufferSize is the 
- * sum of redSize, greenSize, blueSize and alphaSize, which may be larger 
- * than the nplanes/rootDepth of the server's X11 visuals
- */
-#define NUM_FALLBACK_CONFIGS 5
-static __GLXvisualConfig FallbackConfigs[NUM_FALLBACK_CONFIGS] = {
-  /* [0] = RGB, double buffered, Z */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [1] = RGB, double buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-    16, 16, 16, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [2] = RGB+Alpha, double buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 8,      /* rgba sizes */
-    -1, -1, -1, -1,     /* rgba masks */
-    16, 16, 16, 16,     /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [3] = RGB+Alpha, single buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 8,      /* rgba sizes */
-    -1, -1, -1, -1,     /* rgba masks */
-    16, 16, 16, 16,     /* rgba accum sizes */
-    False,              /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [4] = CI, double buffered, Z */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    False,              /* rgba? (false = color index) */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-};
-
-static __GLXvisualConfig NullConfig = {
-    -1,                 /* vid */
-    -1,                 /* class */
-    False,              /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    False,              /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE_EXT,       /* visualRating */
-    0,                  /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-};
-
-
-static inline int count_bits(uint32_t x)
-{
-    x = x - ((x >> 1) & 0x55555555);
-    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
-    x = (x + (x >> 4)) & 0x0f0f0f0f;
-    x = x + (x >> 8);
-    x = x + (x >> 16);
-    return x & 63;
-}
-
-
-static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
-                         VisualID *defaultVisp,
-                         int ndepth, DepthPtr pdepth,
-                         int rootDepth)
-{
-    int numRGBconfigs;
-    int numCIconfigs;
-    int numVisuals = *nvisualp;
-    int numNewVisuals;
-    int numNewConfigs;
-    VisualPtr pVisual = *visualp;
-    VisualPtr pVisualNew = NULL;
-    VisualID *orig_vid = NULL;
-    __GLXconfig *modes;
-    __GLXvisualConfig *pNewVisualConfigs = NULL;
-    void **glXVisualPriv;
-    void **pNewVisualPriv;
-    int found_default;
-    int i, j, k;
-
-    GLAQUA_DEBUG_MSG("init_visuals\n");
-
-    if (numConfigs > 0)
-        numNewConfigs = numConfigs;
-    else
-        numNewConfigs = NUM_FALLBACK_CONFIGS;
-
-    /* Alloc space for the list of new GLX visuals */
-    pNewVisualConfigs = (__GLXvisualConfig *)
-                     malloc(numNewConfigs * sizeof(__GLXvisualConfig));
-    if (!pNewVisualConfigs) {
-        return FALSE;
-    }
-
-    /* Alloc space for the list of new GLX visual privates */
-    pNewVisualPriv = (void **) malloc(numNewConfigs * sizeof(void *));
-    if (!pNewVisualPriv) {
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /*
-    ** If SetVisualConfigs was not called, then use default GLX
-    ** visual configs.
-    */
-    if (numConfigs == 0) {
-        memcpy(pNewVisualConfigs, FallbackConfigs,
-               NUM_FALLBACK_CONFIGS * sizeof(__GLXvisualConfig));
-        memset(pNewVisualPriv, 0, NUM_FALLBACK_CONFIGS * sizeof(void *));
-    }
-    else {
-        /* copy driver's visual config info */
-        for (i = 0; i < numConfigs; i++) {
-            pNewVisualConfigs[i] = visualConfigs[i];
-            pNewVisualPriv[i] = visualPrivates[i];
-        }
-    }
-
-    /* Count the number of RGB and CI visual configs */
-    numRGBconfigs = 0;
-    numCIconfigs = 0;
-    for (i = 0; i < numNewConfigs; i++) {
-        if (pNewVisualConfigs[i].rgba)
-            numRGBconfigs++;
-        else
-            numCIconfigs++;
-    }
-
-    /* Count the total number of visuals to compute */
-    numNewVisuals = 0;
-    for (i = 0; i < numVisuals; i++) {
-        int count;
-
-        count = ((pVisual[i].class == TrueColor ||
-                  pVisual[i].class == DirectColor)
-                ? numRGBconfigs : numCIconfigs);
-        if (count == 0)
-            count = 1;          /* preserve the existing visual */
-
-        numNewVisuals += count;
-    }
-
-    /* Reset variables for use with the next screen/driver's visual configs */
-    visualConfigs = NULL;
-    numConfigs = 0;
-
-    /* Alloc temp space for the list of orig VisualIDs for each new visual */
-    orig_vid = (VisualID *)malloc(numNewVisuals * sizeof(VisualID));
-    if (!orig_vid) {
-        free(pNewVisualPriv);
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the list of glXVisuals */
-    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLXconfig));
-    if (modes == NULL) {
-        free(orig_vid);
-        free(pNewVisualPriv);
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the list of glXVisualPrivates */
-    glXVisualPriv = (void **)malloc(numNewVisuals * sizeof(void *));
-    if (!glXVisualPriv) {
-        _gl_context_modes_destroy( modes );
-        free(orig_vid);
-        free(pNewVisualPriv);
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the new list of the X server's visuals */
-    pVisualNew = (VisualPtr)malloc(numNewVisuals * sizeof(VisualRec));
-    if (!pVisualNew) {
-        free(glXVisualPriv);
-        _gl_context_modes_destroy( modes );
-        free(orig_vid);
-        free(pNewVisualPriv);
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Initialize the new visuals */
-    found_default = FALSE;
-    glAquaScreens[screenInfo.numScreens-1].modes = modes;
-    for (i = j = 0; i < numVisuals; i++) {
-        int is_rgb = (pVisual[i].class == TrueColor ||
-                      pVisual[i].class == DirectColor);
-
-        if (!is_rgb)
-        {
-            /* We don't support non-rgb visuals for GL. But we don't
-               want to remove them either, so just pass them through
-               with null glX configs */
-
-            pVisualNew[j] = pVisual[i];
-            pVisualNew[j].vid = FakeClientID(0);
-
-            /* Check for the default visual */
-            if (!found_default && pVisual[i].vid == *defaultVisp) {
-                *defaultVisp = pVisualNew[j].vid;
-                found_default = TRUE;
-            }
-
-            /* Save the old VisualID */
-            orig_vid[j] = pVisual[i].vid;
-
-            /* Initialize the glXVisual */
-            _gl_copy_visual_to_context_mode( modes, & NullConfig );
-            modes->visualID = pVisualNew[j].vid;
-
-            j++;
-
-            continue;
-        }
-
-        for (k = 0; k < numNewConfigs; k++) {
-            if (pNewVisualConfigs[k].rgba != is_rgb)
-                continue;
-
-            assert( modes != NULL );
-
-            /* Initialize the new visual */
-            pVisualNew[j] = pVisual[i];
-            pVisualNew[j].vid = FakeClientID(0);
-
-            /* Check for the default visual */
-            if (!found_default && pVisual[i].vid == *defaultVisp) {
-                *defaultVisp = pVisualNew[j].vid;
-                found_default = TRUE;
-            }
-
-            /* Save the old VisualID */
-            orig_vid[j] = pVisual[i].vid;
-
-            /* Initialize the glXVisual */
-            _gl_copy_visual_to_context_mode( modes, & pNewVisualConfigs[k] );
-            modes->visualID = pVisualNew[j].vid;
-
-            /*
-             * If the class is -1, then assume the X visual information
-             * is identical to what GLX needs, and take them from the X
-             * visual.  NOTE: if class != -1, then all other fields MUST
-             * be initialized.
-             */
-            if (modes->visualType == GLX_NONE) {
-                modes->visualType = _gl_convert_from_x_visual_type( pVisual[i].class );
-                modes->redBits    = count_bits(pVisual[i].redMask);
-                modes->greenBits  = count_bits(pVisual[i].greenMask);
-                modes->blueBits   = count_bits(pVisual[i].blueMask);
-                modes->alphaBits  = modes->alphaBits;
-                modes->redMask    = pVisual[i].redMask;
-                modes->greenMask  = pVisual[i].greenMask;
-                modes->blueMask   = pVisual[i].blueMask;
-                modes->alphaMask  = modes->alphaMask;
-                modes->rgbBits = (is_rgb)
-                    ? (modes->redBits + modes->greenBits +
-                       modes->blueBits + modes->alphaBits)
-                    : rootDepth;
-            }
-
-            /* Save the device-dependent private for this visual */
-            glXVisualPriv[j] = pNewVisualPriv[k];
-
-            j++;
-            modes = modes->next;
-        }
-    }
-
-    assert(j <= numNewVisuals);
-
-    /* Save the GLX visuals in the screen structure */
-    glAquaScreens[screenInfo.numScreens-1].num_vis = numNewVisuals;
-    //    glAquaScreens[screenInfo.numScreens-1].priv = glXVisualPriv;
-
-    /* set up depth's VisualIDs */
-    for (i = 0; i < ndepth; i++) {
-        int numVids = 0;
-        VisualID *pVids = NULL;
-        int k, n = 0;
-
-        /* Count the new number of VisualIDs at this depth */
-        for (j = 0; j < pdepth[i].numVids; j++)
-            for (k = 0; k < numNewVisuals; k++)
-            if (pdepth[i].vids[j] == orig_vid[k])
-                numVids++;
-
-        /* Allocate a new list of VisualIDs for this depth */
-        pVids = (VisualID *)malloc(numVids * sizeof(VisualID));
-
-        /* Initialize the new list of VisualIDs for this depth */
-        for (j = 0; j < pdepth[i].numVids; j++)
-            for (k = 0; k < numNewVisuals; k++)
-            if (pdepth[i].vids[j] == orig_vid[k])
-                pVids[n++] = pVisualNew[k].vid;
-
-        /* Update this depth's list of VisualIDs */
-        free(pdepth[i].vids);
-        pdepth[i].vids = pVids;
-        pdepth[i].numVids = numVids;
-    }
-
-    /* Update the X server's visuals */
-    *nvisualp = numNewVisuals;
-    *visualp = pVisualNew;
-
-    /* Free the old list of the X server's visuals */
-    free(pVisual);
-
-    /* Clean up temporary allocations */
-    free(orig_vid);
-    free(pNewVisualPriv);
-    free(pNewVisualConfigs);
-
-    /* Free the private list created by DDX HW driver */
-    if (visualPrivates)
-        free(visualPrivates);
-    visualPrivates = NULL;
-
-    return TRUE;
-}
-
-Bool enable_stereo = FALSE;
-/* based on code in i830_dri.c
-   This ends calling glAquaSetVisualConfigs to set the static
-   numconfigs, etc. */
-// see also glxglcore.c -- bhb
-static void
-glAquaInitVisualConfigs(void)
-{
-    int                 lclNumConfigs     = 0;
-    __GLXvisualConfig  *lclVisualConfigs  = NULL;
-    void              **lclVisualPrivates = NULL;
-
-    int stereo, depth, aux, buffers, stencil, accum;
-    int i = 0;
-
-    GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs ");
-        
-    /* count num configs:
-        2 stereo (on, off) (optional)
-        2 Z buffer (0, 24 bit)
-        2 AUX buffer (0, 2)
-        2 buffers (single, double)
-        2 stencil (0, 8 bit)
-        2 accum (0, 64 bit)
-        = 64 configs with stereo, or 32 without */
-
-    if (enable_stereo) lclNumConfigs = 2 * 2 * 2 * 2 * 2 * 2; /* 64 */
-    else               lclNumConfigs = 2 * 2 * 2 * 2 * 2; /* 32 */
-
-    /* alloc */
-    lclVisualConfigs = xcalloc(sizeof(__GLXvisualConfig), lclNumConfigs);
-    lclVisualPrivates = xcalloc(sizeof(void *), lclNumConfigs);
-
-    /* fill in configs */
-    if (NULL != lclVisualConfigs) {
-        i = 0; /* current buffer */
-        for (stereo = 0; stereo < (enable_stereo ? 2 : 1); stereo++) {
-	  for (depth = 0; depth < 2; depth++) {
-            for (aux = 0; aux < 2; aux++) {
-	      for (buffers = 0; buffers < 2; buffers++) {
-		for (stencil = 0; stencil < 2; stencil++) {
-		  for (accum = 0; accum < 2; accum++) {
-		    lclVisualConfigs[i].vid = -1;
-		    lclVisualConfigs[i].class = -1;
-		    lclVisualConfigs[i].rgba = TRUE;
-		    lclVisualConfigs[i].redSize = -1;
-		    lclVisualConfigs[i].greenSize = -1;
-		    lclVisualConfigs[i].blueSize = -1;
-		    lclVisualConfigs[i].redMask = -1;
-		    lclVisualConfigs[i].greenMask = -1;
-		    lclVisualConfigs[i].blueMask = -1;
-		    lclVisualConfigs[i].alphaMask = 0;
-		    if (accum) {
-		      lclVisualConfigs[i].accumRedSize = 16;
-		      lclVisualConfigs[i].accumGreenSize = 16;
-		      lclVisualConfigs[i].accumBlueSize = 16;
-		      lclVisualConfigs[i].accumAlphaSize = 16;
-		    } else {
-		      lclVisualConfigs[i].accumRedSize = 0;
-		      lclVisualConfigs[i].accumGreenSize = 0;
-		      lclVisualConfigs[i].accumBlueSize = 0;
-		      lclVisualConfigs[i].accumAlphaSize = 0;
-		    }
-		    lclVisualConfigs[i].doubleBuffer = buffers ? TRUE : FALSE;
-		    lclVisualConfigs[i].stereo = stereo ? TRUE : FALSE;
-		    lclVisualConfigs[i].bufferSize = -1;
-		    
-		    lclVisualConfigs[i].depthSize = depth? 24 : 0;
-		    lclVisualConfigs[i].stencilSize = stencil ? 8 : 0;
-		    lclVisualConfigs[i].auxBuffers = aux ? 2 : 0;
-		    lclVisualConfigs[i].level = 0;
-		    lclVisualConfigs[i].visualRating = GLX_NONE_EXT;
-		    lclVisualConfigs[i].transparentPixel = 0;
-		    lclVisualConfigs[i].transparentRed = 0;
-		    lclVisualConfigs[i].transparentGreen = 0;
-		    lclVisualConfigs[i].transparentBlue = 0;
-		    lclVisualConfigs[i].transparentAlpha = 0;
-		    lclVisualConfigs[i].transparentIndex = 0;
-		    i++;
-		  }
-		}
-	      }
-            }
-	  }
-	}
-    }
-    if (i != lclNumConfigs)
-        GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs failed to alloc visual configs");
-
-    GlxSetVisualConfigs(lclNumConfigs, lclVisualConfigs, lclVisualPrivates);
-}
-
-
-static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
-                                   void **privates)
-{
-    GLAQUA_DEBUG_MSG("glAquaSetVisualConfigs\n");
-
-    numConfigs = nconfigs;
-    visualConfigs = configs;
-    visualPrivates = privates;
-}
-
-static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
-                              int *nvisualp, int *ndepthp,
-                              int *rootDepthp, VisualID *defaultVisp,
-                              unsigned long sizes, int bitsPerRGB)
-{
-    GLAQUA_DEBUG_MSG("glAquaInitVisuals\n");
-    
-    if (numConfigs == 0) /* if no configs */
-        glAquaInitVisualConfigs(); /* ensure the visual configs are setup */
-
-    /*
-     * setup the visuals supported by this particular screen.
-     */
-    return init_visuals(nvisualp, visualp, defaultVisp,
-                        *ndepthp, *depthp, *rootDepthp);
-}
-
-#if 0
-static void fixup_visuals(int screen)
-{
-    ScreenPtr pScreen = screenInfo.screens[screen];
-    glAquaScreenRec *pScr = &glAquaScreens[screen];
-    int j;
-    __GLcontextModes *modes;
-
-    GLAQUA_DEBUG_MSG("fixup_visuals\n");
-
-    for ( modes = pScr->modes ; modes != NULL ; modes = modes->next ) {
-        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
-        const int nplanes = (modes->rgbBits - modes->alphaBits);
-        const VisualPtr pVis = pScreen->visuals;
-
-        /* Find a visual that matches the GLX visual's class and size */
-        for (j = 0; j < pScreen->numVisuals; j++) {
-            if (pVis[j].class == vis_class &&
-            pVis[j].nplanes == nplanes) {
-
-            /* Fixup the masks */
-            modes->redMask   = pVis[j].redMask;
-            modes->greenMask = pVis[j].greenMask;
-            modes->blueMask  = pVis[j].blueMask;
-
-            /* Recalc the sizes */
-            modes->redBits   = count_bits(modes->redMask);
-            modes->greenBits = count_bits(modes->greenMask);
-            modes->blueBits  = count_bits(modes->blueMask);
-            }
-        }
-    }
-}
-#endif
-static void __glXAquaScreenDestroy(__GLXscreen *screen) {
-
-	GLAQUA_DEBUG_MSG("glXAquaScreenDestroy(%p)\n", screen);
-  __glXScreenDestroy(screen);
-
-  free(screen);
-}
-
-static void init_screen_visuals(__GLXAquaScreen *screen) {
-  ScreenPtr pScreen = screen->base.pScreen;
-  
-  __GLXconfig *modes;
-  int *used;
-  int i, j;
-  
-    GLAQUA_DEBUG_MSG("init_screen_visuals\n");
-
-    /* FIXME: Change 'used' to be a array of bits (rather than of ints),
-     * FIXME: create a stack array of 8 or 16 bytes.  If 'numVisuals' is less
-     * FIXME: than 64 or 128 the stack array can be used instead of calling
-     * FIXME: malloc / free.  If nothing else, convert 'used' to
-     * FIXME: array of bytes instead of ints!
-     */
-    used = (int *)malloc(pScreen->numVisuals * sizeof(int));
-    memset(used, 0, pScreen->numVisuals * sizeof(int));
-
-    i = 0;
-    for ( modes = screen -> base.visuals
-          ; modes != NULL
-          ; modes = modes->next ) {
-        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
-        const int nplanes = (modes->rgbBits - modes->alphaBits);
-        const VisualPtr pVis = pScreen->visuals;
-
-        for (j = 0; j < pScreen->numVisuals; j++) {
-            if (pVis[j].class     == vis_class &&
-                pVis[j].nplanes   == nplanes &&
-                pVis[j].redMask   == modes->redMask &&
-                pVis[j].greenMask == modes->greenMask &&
-                pVis[j].blueMask  == modes->blueMask &&
-                !used[j]) {
-
-                    /* set the VisualID */
-                    modes->visualID = pVis[j].vid;
-
-                    /* Mark this visual used */
-                    used[j] = 1;
-                    break;
-            }
-        }
-        if ( j == pScreen->numVisuals ) {
-            ErrorF("No matching visual for __GLcontextMode with "
-                   "visual class = %d (%d), nplanes = %u\n",
-                   vis_class, 
-                   (int)modes->visualType,
-                   (unsigned int)(modes->rgbBits - modes->alphaBits) );
-        }
-        else if ( modes->visualID == -1 ) {
-            FatalError( "Matching visual found, but visualID still -1!\n" );
-        }
-
-        i++;
-    }
-
-    free(used);
-}
-
-static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen) {
-  __GLXAquaScreen *screen;
-  GLAQUA_DEBUG_MSG("glXAquaScreenProbe\n");
-  if (screen == NULL) return NULL;
-
-  screen = malloc(sizeof *screen);
-
-  __glXScreenInit(&screen->base, pScreen);
-
-  screen->base.destroy        = __glXAquaScreenDestroy;
-  screen->base.createContext  = __glXAquaScreenCreateContext;
-  screen->base.createDrawable = __glXAquaScreenCreateDrawable;
-  screen->base.pScreen       = pScreen;
-
-  init_screen_visuals(screen);
-
-  return &screen->base;
-}
-
-static void __glXAquaDrawableDestroy(__GLXdrawable *base) {
-    GLAQUA_DEBUG_MSG("glAquaDestroyDrawablePrivate\n");
-
-    /* It doesn't work to call DRIDestroySurface here, the drawable's
-       already gone.. But dri.c notices the window destruction and
-       frees the surface itself. */
-
-    free(base);
-}
-
-static __GLXdrawable *
-__glXAquaScreenCreateDrawable(__GLXscreen *screen,
-			      DrawablePtr pDraw,
-			      XID drawId,
-			      __GLXconfig *modes) {
-  __GLXAquaDrawable *glxPriv;
-
-  GLAQUA_DEBUG_MSG("glAquaScreenCreateDrawable(%p,%p,%d,%p)\n", context, pDraw, drawId, modes);
-
-  glxPriv = xalloc(sizeof *glxPriv);
-  if (glxPriv == NULL) return NULL;
-
-  memset(glxPriv, 0, sizeof *glxPriv);
-
-  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, GLX_DRAWABLE_PIXMAP /*?*/, drawId, modes)) {
-    xfree(glxPriv);
-    return NULL;
-  }
-
-  glxPriv->base.destroy       = __glXAquaDrawableDestroy;
-  glxPriv->base.resize        = __glXAquaDrawableResize;
-  glxPriv->base.swapBuffers   = __glXAquaDrawableSwapBuffers;
-  //  glxPriv->base.copySubBuffer = __glXAquaDrawableCopySubBuffer;
-
-  return &glxPriv->base;
-}
-
-static void glAquaResetExtension(void)
-{
-    GLAQUA_DEBUG_MSG("glAquaResetExtension\n");
-    CGLSetOption(kCGLGOResetLibrary, GL_TRUE);
-}
-
-// Extra goodies for glx
-
-GLuint __glFloorLog2(GLuint val)
-{
-    int c = 0;
-
-    while (val > 1) {
-        c++;
-        val >>= 1;
-    }
-    return c;
-}
-
-void warn_func(void * p1, char *format, ...) {
-  va_list v;
-  va_start(v, format);
-  vfprintf(stderr, format, v);
-  va_end(v);
-}
-
-static void setup_dispatch_table(void) {
-  struct _glapi_table *disp=_glapi_get_dispatch();
-  _glapi_set_warning_func((_glapi_warning_func)warn_func);
-  _glapi_noop_enable_warnings(TRUE);
-
-  SET_Accum(disp, glAccum);
-  SET_ActiveStencilFaceEXT(disp, glActiveStencilFaceEXT);
-  SET_ActiveTextureARB(disp, glActiveTextureARB);
-//SET_AlphaFragmentOp1ATI(disp, glAlphaFragmentOp1EXT);   // <-- EXT -> ATI
-//SET_AlphaFragmentOp2ATI(disp, glAlphaFragmentOp2EXT);
-//SET_AlphaFragmentOp3ATI(disp, glAlphaFragmentOp3EXT);
-  SET_AlphaFunc(disp, glAlphaFunc);
-//SET_AreProgramsResidentNV(disp, glAreProgramsResidentNV);
-  SET_AreTexturesResident(disp, glAreTexturesResident); 
-  SET_ArrayElement(disp, glArrayElement);
-  SET_AttachObjectARB(disp, glAttachObjectARB);
-  SET_Begin(disp, glBegin);
-//SET_BeginFragmentShaderATI(disp, glBeginFragmentShaderEXT);   // <-- EXT -> ATI
-  SET_BeginQueryARB(disp, glBeginQueryARB);
-  SET_BindAttribLocationARB(disp, glBindAttribLocationARB);
-  SET_BindBufferARB(disp, glBindBufferARB);
-//SET_BindFragmentShaderATI(disp, glBindFragmentShaderEXT);     // <-- EXT -> ATI
-  SET_BindFramebufferEXT(disp, glBindFramebufferEXT);
-//SET_BindProgramNV(disp, glBindProgramNV);
-  SET_BindRenderbufferEXT(disp, glBindRenderbufferEXT);
-  SET_BindTexture(disp, glBindTexture);
-  SET_Bitmap(disp, glBitmap);
-  SET_BlendColor(disp, glBlendColor);
-  SET_BlendEquation(disp, glBlendEquation);
-  SET_BlendEquationSeparateEXT(disp, glBlendEquationSeparateEXT);
-  SET_BlendFunc(disp, glBlendFunc);
-  SET_BlendFuncSeparateEXT(disp, glBlendFuncSeparateEXT);
-  SET_BlitFramebufferEXT(disp, glBlitFramebufferEXT);
-  SET_BufferDataARB(disp, glBufferDataARB);
-  SET_BufferSubDataARB(disp, glBufferSubDataARB);
-  SET_CallList(disp, glCallList);
-  SET_CallLists(disp, glCallLists);
-  SET_CheckFramebufferStatusEXT(disp, glCheckFramebufferStatusEXT);
-  SET_Clear(disp, glClear);
-  SET_ClearAccum(disp, glClearAccum);
-  SET_ClearColor(disp, glClearColor);
-  SET_ClearDepth(disp, glClearDepth);
-  SET_ClearIndex(disp, glClearIndex);
-  SET_ClearStencil(disp, glClearStencil);
-  SET_ClientActiveTextureARB(disp, glClientActiveTextureARB);
-  SET_ClipPlane(disp, glClipPlane);
-  SET_Color3b(disp, glColor3b);
-  SET_Color3bv(disp, glColor3bv);
-  SET_Color3d(disp, glColor3d);
-  SET_Color3dv(disp, glColor3dv);
-  SET_Color3f(disp, glColor3f);
-  SET_Color3fv(disp, glColor3fv);
-  SET_Color3i(disp, glColor3i);
-  SET_Color3iv(disp, glColor3iv);
-  SET_Color3s(disp, glColor3s);
-  SET_Color3sv(disp, glColor3sv);
-  SET_Color3ub(disp, glColor3ub);
-  SET_Color3ubv(disp, glColor3ubv);
-  SET_Color3ui(disp, glColor3ui);
-  SET_Color3uiv(disp, glColor3uiv);
-  SET_Color3us(disp, glColor3us);
-  SET_Color3usv(disp, glColor3usv);
-  SET_Color4b(disp, glColor4b);
-  SET_Color4bv(disp, glColor4bv);
-  SET_Color4d(disp, glColor4d);
-  SET_Color4dv(disp, glColor4dv);
-  SET_Color4f(disp, glColor4f);
-  SET_Color4fv(disp, glColor4fv);
-  SET_Color4i(disp, glColor4i);
-  SET_Color4iv(disp, glColor4iv);
-  SET_Color4s(disp, glColor4s);
-  SET_Color4sv(disp, glColor4sv);
-  SET_Color4ub(disp, glColor4ub);
-  SET_Color4ubv(disp, glColor4ubv);
-  SET_Color4ui(disp, glColor4ui);
-  SET_Color4uiv(disp, glColor4uiv);
-  SET_Color4us(disp, glColor4us);
-  SET_Color4usv(disp, glColor4usv);
-//SET_ColorFragmentOp1ATI(disp, glColorFragmentOp1EXT);    // <-- EXT -> ATI
-//SET_ColorFragmentOp2ATI(disp, glColorFragmentOp2EXT);
-//SET_ColorFragmentOp3ATI(disp, glColorFragmentOp3EXT);
-  SET_ColorMask(disp, glColorMask);
-  SET_ColorMaterial(disp, glColorMaterial);
-  SET_ColorPointer(disp, glColorPointer);
-//SET_ColorPointerEXT(disp, glColorPointerEXT);
-  SET_ColorSubTable(disp, glColorSubTable);
-  SET_ColorTable(disp, glColorTable);
-  SET_ColorTableParameterfv(disp, glColorTableParameterfv);
-  SET_ColorTableParameteriv(disp, glColorTableParameteriv);
-  SET_CombinerInputNV(disp, glCombinerInputNV);
-  SET_CombinerOutputNV(disp, glCombinerOutputNV);
-  SET_CombinerParameterfNV(disp, glCombinerParameterfNV);
-  SET_CombinerParameterfvNV(disp, glCombinerParameterfvNV);
-  SET_CombinerParameteriNV(disp, glCombinerParameteriNV);
-  SET_CombinerParameterivNV(disp, glCombinerParameterivNV);
-  SET_CompileShaderARB(disp, glCompileShaderARB);
-  SET_CompressedTexImage1DARB(disp, glCompressedTexImage1DARB);
-  SET_CompressedTexImage2DARB(disp, glCompressedTexImage2DARB);
-  SET_CompressedTexImage3DARB(disp, glCompressedTexImage3DARB);
-  SET_CompressedTexSubImage1DARB(disp, glCompressedTexSubImage1DARB);
-  SET_CompressedTexSubImage2DARB(disp, glCompressedTexSubImage2DARB);
-  SET_CompressedTexSubImage3DARB(disp, glCompressedTexSubImage3DARB);
-  SET_ConvolutionFilter1D(disp, glConvolutionFilter1D);
-  SET_ConvolutionFilter2D(disp, glConvolutionFilter2D);
-  SET_ConvolutionParameterf(disp, glConvolutionParameterf);
-  SET_ConvolutionParameterfv(disp, glConvolutionParameterfv);
-  SET_ConvolutionParameteri(disp, glConvolutionParameteri);
-  SET_ConvolutionParameteriv(disp, glConvolutionParameteriv);
-  SET_CopyColorSubTable(disp, glCopyColorSubTable);
-  SET_CopyColorTable(disp, glCopyColorTable);
-  SET_CopyConvolutionFilter1D(disp, glCopyConvolutionFilter1D);
-  SET_CopyConvolutionFilter2D(disp, glCopyConvolutionFilter2D);
-  SET_CopyPixels(disp, glCopyPixels);
-  SET_CopyTexImage1D(disp, glCopyTexImage1D);
-  SET_CopyTexImage2D(disp, glCopyTexImage2D);
-  SET_CopyTexSubImage1D(disp, glCopyTexSubImage1D);
-  SET_CopyTexSubImage2D(disp, glCopyTexSubImage2D);
-  SET_CopyTexSubImage3D(disp, glCopyTexSubImage3D);
-  SET_CreateProgramObjectARB(disp, glCreateProgramObjectARB);
-  SET_CreateShaderObjectARB(disp, glCreateShaderObjectARB);
-  SET_CullFace(disp, glCullFace);
-//SET_CullParameterdvEXT(disp, glCullParameterdvEXT);
-//SET_CullParameterfvEXT(disp, glCullParameterfvEXT);
-  SET_DeleteBuffersARB(disp, glDeleteBuffersARB);
-  SET_DeleteFencesNV(disp, glDeleteFencesAPPLE);
-//SET_DeleteFragmentShaderATI(disp, glDeleteFragmentShaderEXT);      // <-- EXT -> ATI
-  SET_DeleteFramebuffersEXT(disp, glDeleteFramebuffersEXT);
-  SET_DeleteLists(disp, glDeleteLists);
-  SET_DeleteObjectARB(disp, glDeleteObjectARB);
-//SET_DeleteProgramsNV(disp, glDeleteProgramsNV);
-  SET_DeleteQueriesARB(disp, glDeleteQueriesARB);
-  SET_DeleteRenderbuffersEXT(disp, glDeleteRenderbuffersEXT);
-  SET_DeleteTextures(disp, glDeleteTextures);
-  SET_DepthBoundsEXT(disp, glDepthBoundsEXT);
-  SET_DepthFunc(disp, glDepthFunc);
-  SET_DepthMask(disp, glDepthMask);
-  SET_DepthRange(disp, glDepthRange);
-  SET_DetachObjectARB(disp, glDetachObjectARB);
-  SET_Disable(disp, glDisable);
-  SET_DisableClientState(disp, glDisableClientState);
-  SET_DisableVertexAttribArrayARB(disp, glDisableVertexAttribArrayARB);
-  SET_DrawArrays(disp, glDrawArrays);
-  SET_DrawBuffer(disp, glDrawBuffer);
-  SET_DrawBuffersARB(disp, glDrawBuffersARB);
-  SET_DrawElements(disp, glDrawElements);
-  SET_DrawPixels(disp, glDrawPixels);
-  SET_DrawRangeElements(disp, glDrawRangeElements);
-  SET_EdgeFlag(disp, glEdgeFlag);
-  SET_EdgeFlagPointer(disp, glEdgeFlagPointer);
-//SET_EdgeFlagPointerEXT(disp, glEdgeFlagPointerEXT);
-  SET_EdgeFlagv(disp, glEdgeFlagv);
-  SET_Enable(disp, glEnable);
-  SET_EnableClientState(disp, glEnableClientState);
-  SET_EnableVertexAttribArrayARB(disp, glEnableVertexAttribArrayARB);
-  SET_End(disp, glEnd);
-//SET_EndFragmentShaderATI(disp, glEndFragmentShaderEXT);        // <-- EXT -> ATI
-  SET_EndList(disp, glEndList);
-  SET_EndQueryARB(disp, glEndQueryARB);
-  SET_EvalCoord1d(disp, glEvalCoord1d);
-  SET_EvalCoord1dv(disp, glEvalCoord1dv);
-  SET_EvalCoord1f(disp, glEvalCoord1f);
-  SET_EvalCoord1fv(disp, glEvalCoord1fv);
-  SET_EvalCoord2d(disp, glEvalCoord2d);
-  SET_EvalCoord2dv(disp, glEvalCoord2dv);
-  SET_EvalCoord2f(disp, glEvalCoord2f);
-  SET_EvalCoord2fv(disp, glEvalCoord2fv);
-  SET_EvalMesh1(disp, glEvalMesh1);
-  SET_EvalMesh2(disp, glEvalMesh2);
-  SET_EvalPoint1(disp, glEvalPoint1);
-  SET_EvalPoint2(disp, glEvalPoint2);
-//SET_ExecuteProgramNV(disp, glExecuteProgramNV);
-  SET_FeedbackBuffer(disp, glFeedbackBuffer);
-  SET_FinalCombinerInputNV(disp, glFinalCombinerInputNV);
-  SET_Finish(disp, glFinish);
-  SET_FinishFenceNV(disp, glFinishFenceAPPLE);       // <-- APPLE -> NV
-  SET_Flush(disp, glFlush);
-//SET_FlushVertexArrayRangeNV(disp, glFlushVertexArrayRangeNV);
-  SET_FogCoordPointerEXT(disp, glFogCoordPointerEXT);
-  SET_FogCoorddEXT(disp, glFogCoorddEXT);
-  SET_FogCoorddvEXT(disp, glFogCoorddvEXT);
-  SET_FogCoordfEXT(disp, glFogCoordfEXT);
-  SET_FogCoordfvEXT(disp, glFogCoordfvEXT);
-  SET_Fogf(disp, glFogf);
-  SET_Fogfv(disp, glFogfv);
-  SET_Fogi(disp, glFogi);
-  SET_Fogiv(disp, glFogiv);
-  SET_FramebufferRenderbufferEXT(disp, glFramebufferRenderbufferEXT);
-  SET_FramebufferTexture1DEXT(disp, glFramebufferTexture1DEXT);
-  SET_FramebufferTexture2DEXT(disp, glFramebufferTexture2DEXT);
-  SET_FramebufferTexture3DEXT(disp, glFramebufferTexture3DEXT);
-  SET_FrontFace(disp, glFrontFace);
-  SET_Frustum(disp, glFrustum);
-  SET_GenBuffersARB(disp, glGenBuffersARB);
-  SET_GenFencesNV(disp, glGenFencesAPPLE);            // <-- APPLE -> NV
-//SET_GenFragmentShadersATI(disp, glGenFragmentShadersEXT);         // <-- EXT -> ATI
-  SET_GenFramebuffersEXT(disp, glGenFramebuffersEXT);
-  SET_GenLists(disp, glGenLists);
-//SET_GenProgramsNV(disp, glGenProgramsNV);
-  SET_GenQueriesARB(disp, glGenQueriesARB);
-  SET_GenRenderbuffersEXT(disp, glGenRenderbuffersEXT);
-  SET_GenTextures(disp, glGenTextures);
-  SET_GenerateMipmapEXT(disp, glGenerateMipmapEXT);
-  SET_GetActiveAttribARB(disp, glGetActiveAttribARB);
-  SET_GetActiveUniformARB(disp, glGetActiveUniformARB);
-  SET_GetAttachedObjectsARB(disp, glGetAttachedObjectsARB);
-  SET_GetAttribLocationARB(disp, glGetAttribLocationARB);
-  SET_GetBooleanv(disp, glGetBooleanv);
-  SET_GetBufferParameterivARB(disp, glGetBufferParameterivARB);
-  SET_GetBufferPointervARB(disp, glGetBufferPointervARB);
-  SET_GetBufferSubDataARB(disp, glGetBufferSubDataARB);
-  SET_GetClipPlane(disp, glGetClipPlane);
-  SET_GetColorTable(disp, glGetColorTable);
-  SET_GetColorTableParameterfv(disp, glGetColorTableParameterfv);
-  SET_GetColorTableParameteriv(disp, glGetColorTableParameteriv);
-  SET_GetCombinerInputParameterfvNV(disp, glGetCombinerInputParameterfvNV);
-  SET_GetCombinerInputParameterivNV(disp, glGetCombinerInputParameterivNV);
-  SET_GetCombinerOutputParameterfvNV(disp, glGetCombinerOutputParameterfvNV);
-  SET_GetCombinerOutputParameterivNV(disp, glGetCombinerOutputParameterivNV);
-  SET_GetCompressedTexImageARB(disp, glGetCompressedTexImageARB);
-  SET_GetConvolutionFilter(disp, glGetConvolutionFilter);
-  SET_GetConvolutionParameterfv(disp, glGetConvolutionParameterfv);
-  SET_GetConvolutionParameteriv(disp, glGetConvolutionParameteriv);
-  SET_GetDoublev(disp, glGetDoublev);
-  SET_GetError(disp, glGetError);
-//SET_GetFenceivNV(disp, glGetFenceivNV);
-  SET_GetFinalCombinerInputParameterfvNV(disp, glGetFinalCombinerInputParameterfvNV);
-  SET_GetFinalCombinerInputParameterivNV(disp, glGetFinalCombinerInputParameterivNV);
-  SET_GetFloatv(disp, glGetFloatv);
-  SET_GetFramebufferAttachmentParameterivEXT(disp, glGetFramebufferAttachmentParameterivEXT);
-  SET_GetHandleARB(disp, glGetHandleARB);
-  SET_GetHistogram(disp, glGetHistogram);
-  SET_GetHistogramParameterfv(disp, glGetHistogramParameterfv);
-  SET_GetHistogramParameteriv(disp, glGetHistogramParameteriv);
-  SET_GetInfoLogARB(disp, glGetInfoLogARB);
-  SET_GetIntegerv(disp, glGetIntegerv);
-  SET_GetLightfv(disp, glGetLightfv);
-  SET_GetLightiv(disp, glGetLightiv);
-  SET_GetMapdv(disp, glGetMapdv);
-  SET_GetMapfv(disp, glGetMapfv);
-  SET_GetMapiv(disp, glGetMapiv);
-  SET_GetMaterialfv(disp, glGetMaterialfv);
-  SET_GetMaterialiv(disp, glGetMaterialiv);
-  SET_GetMinmax(disp, glGetMinmax);
-  SET_GetMinmaxParameterfv(disp, glGetMinmaxParameterfv);
-  SET_GetMinmaxParameteriv(disp, glGetMinmaxParameteriv);
-  SET_GetObjectParameterfvARB(disp, glGetObjectParameterfvARB);
-  SET_GetObjectParameterivARB(disp, glGetObjectParameterivARB);
-  SET_GetPixelMapfv(disp, glGetPixelMapfv);
-  SET_GetPixelMapuiv(disp, glGetPixelMapuiv);
-  SET_GetPixelMapusv(disp, glGetPixelMapusv);
-//SET_GetPixelTexGenParameterfvSGIS(disp, glGetPixelTexGenParameterfvSGIS);
-//SET_GetPixelTexGenParameterivSGIS(disp, glGetPixelTexGenParameterivSGIS);
-  SET_GetPointerv(disp, glGetPointerv);
-  SET_GetPolygonStipple(disp, glGetPolygonStipple);
-  SET_GetProgramEnvParameterdvARB(disp, glGetProgramEnvParameterdvARB);
-  SET_GetProgramEnvParameterfvARB(disp, glGetProgramEnvParameterfvARB);
-  SET_GetProgramLocalParameterdvARB(disp, glGetProgramLocalParameterdvARB);
-  SET_GetProgramLocalParameterfvARB(disp, glGetProgramLocalParameterfvARB);
-//SET_GetProgramNamedParameterdvNV(disp, glGetProgramNamedParameterdvNV);
-//SET_GetProgramNamedParameterfvNV(disp, glGetProgramNamedParameterfvNV);
-//SET_GetProgramParameterdvNV(disp, glGetProgramParameterdvNV);
-//SET_GetProgramParameterfvNV(disp, glGetProgramParameterfvNV);
-  SET_GetProgramStringARB(disp, glGetProgramStringARB);
-//SET_GetProgramStringNV(disp, glGetProgramStringNV);
-  SET_GetProgramivARB(disp, glGetProgramivARB);
-//SET_GetProgramivNV(disp, glGetProgramivNV);
-//SET_GetQueryObjecti64vEXT(disp, glGetQueryObjecti64vEXT);
-  SET_GetQueryObjectivARB(disp, glGetQueryObjectivARB);
-//SET_GetQueryObjectui64vEXT(disp, glGetQueryObjectui64vEXT);
-  SET_GetQueryObjectuivARB(disp, glGetQueryObjectuivARB);
-  SET_GetQueryivARB(disp, glGetQueryivARB);
-  SET_GetRenderbufferParameterivEXT(disp, glGetRenderbufferParameterivEXT);
-  SET_GetSeparableFilter(disp, glGetSeparableFilter);
-  SET_GetShaderSourceARB(disp, glGetShaderSourceARB);
-  SET_GetString(disp, glGetString);
-  SET_GetTexEnvfv(disp, glGetTexEnvfv);
-  SET_GetTexEnviv(disp, glGetTexEnviv);
-  SET_GetTexGendv(disp, glGetTexGendv);
-  SET_GetTexGenfv(disp, glGetTexGenfv);
-  SET_GetTexGeniv(disp, glGetTexGeniv);
-  SET_GetTexImage(disp, glGetTexImage);
-  SET_GetTexLevelParameterfv(disp, glGetTexLevelParameterfv);
-  SET_GetTexLevelParameteriv(disp, glGetTexLevelParameteriv);
-  SET_GetTexParameterfv(disp, glGetTexParameterfv);
-  SET_GetTexParameteriv(disp, glGetTexParameteriv);
-//SET_GetTrackMatrixivNV(disp, glGetTrackMatrixivNV);
-  SET_GetUniformLocationARB(disp, glGetUniformLocationARB);
-  SET_GetUniformfvARB(disp, glGetUniformfvARB);
-  SET_GetUniformivARB(disp, glGetUniformivARB);
-//SET_GetVertexAttribPointervNV(disp, glGetVertexAttribPointervNV);
-  SET_GetVertexAttribdvARB(disp, glGetVertexAttribdvARB);
-//SET_GetVertexAttribdvNV(disp, glGetVertexAttribdvNV);
-  SET_GetVertexAttribfvARB(disp, glGetVertexAttribfvARB);
-//SET_GetVertexAttribfvNV(disp, glGetVertexAttribfvNV);
-  SET_GetVertexAttribivARB(disp, glGetVertexAttribivARB);
-//SET_GetVertexAttribivNV(disp, glGetVertexAttribivNV);
-  SET_Hint(disp, glHint);
-  SET_Histogram(disp, glHistogram);
-  SET_IndexMask(disp, glIndexMask);
-  SET_IndexPointer(disp, glIndexPointer);
-//SET_IndexPointerEXT(disp, glIndexPointerEXT);
-  SET_Indexd(disp, glIndexd);
-  SET_Indexdv(disp, glIndexdv);
-  SET_Indexf(disp, glIndexf);
-  SET_Indexfv(disp, glIndexfv);
-  SET_Indexi(disp, glIndexi);
-  SET_Indexiv(disp, glIndexiv);
-  SET_Indexs(disp, glIndexs);
-  SET_Indexsv(disp, glIndexsv);
-  SET_Indexub(disp, glIndexub);
-  SET_Indexubv(disp, glIndexubv);
-  SET_InitNames(disp, glInitNames);
-  SET_InterleavedArrays(disp, glInterleavedArrays);
-  SET_IsBufferARB(disp, glIsBufferARB);
-  SET_IsEnabled(disp, glIsEnabled);
-  SET_IsFenceNV(disp, glIsFenceAPPLE);           // <-- APPLE -> NV
-  SET_IsFramebufferEXT(disp, glIsFramebufferEXT);
-  SET_IsList(disp, glIsList);
-//SET_IsProgramNV(disp, glIsProgramNV);
-  SET_IsQueryARB(disp, glIsQueryARB);
-  SET_IsRenderbufferEXT(disp, glIsRenderbufferEXT);
-  SET_IsTexture(disp, glIsTexture);
-  SET_LightModelf(disp, glLightModelf);
-  SET_LightModelfv(disp, glLightModelfv);
-  SET_LightModeli(disp, glLightModeli);
-  SET_LightModeliv(disp, glLightModeliv);
-  SET_Lightf(disp, glLightf);
-  SET_Lightfv(disp, glLightfv);
-  SET_Lighti(disp, glLighti);
-  SET_Lightiv(disp, glLightiv);
-  SET_LineStipple(disp, glLineStipple);
-  SET_LineWidth(disp, glLineWidth);
-  SET_LinkProgramARB(disp, glLinkProgramARB);
-  SET_ListBase(disp, glListBase);
-  SET_LoadIdentity(disp, glLoadIdentity);
-  SET_LoadMatrixd(disp, glLoadMatrixd);
-  SET_LoadMatrixf(disp, glLoadMatrixf);
-  SET_LoadName(disp, glLoadName);
-//SET_LoadProgramNV(disp, glLoadProgramNV);
-  SET_LoadTransposeMatrixdARB(disp, glLoadTransposeMatrixdARB);
-  SET_LoadTransposeMatrixfARB(disp, glLoadTransposeMatrixfARB);
-  SET_LockArraysEXT(disp, glLockArraysEXT);
-  SET_LogicOp(disp, glLogicOp);
-  SET_Map1d(disp, glMap1d);
-  SET_Map1f(disp, glMap1f);
-  SET_Map2d(disp, glMap2d);
-  SET_Map2f(disp, glMap2f);
-  SET_MapBufferARB(disp, glMapBufferARB);
-  SET_MapGrid1d(disp, glMapGrid1d);
-  SET_MapGrid1f(disp, glMapGrid1f);
-  SET_MapGrid2d(disp, glMapGrid2d);
-  SET_MapGrid2f(disp, glMapGrid2f);
-  SET_Materialf(disp, glMaterialf);
-  SET_Materialfv(disp, glMaterialfv);
-  SET_Materiali(disp, glMateriali);
-  SET_Materialiv(disp, glMaterialiv);
-  SET_MatrixMode(disp, glMatrixMode);
-  SET_Minmax(disp, glMinmax);
-  SET_MultMatrixd(disp, glMultMatrixd);
-  SET_MultMatrixf(disp, glMultMatrixf);
-  SET_MultTransposeMatrixdARB(disp, glMultTransposeMatrixdARB);
-  SET_MultTransposeMatrixfARB(disp, glMultTransposeMatrixfARB);
-  SET_MultiDrawArraysEXT(disp, glMultiDrawArraysEXT);
-  SET_MultiDrawElementsEXT(disp, glMultiDrawElementsEXT);
-//SET_MultiModeDrawArraysIBM(disp, glMultiModeDrawArraysIBM);
-//SET_MultiModeDrawElementsIBM(disp, glMultiModeDrawElementsIBM);
-  SET_MultiTexCoord1dARB(disp, glMultiTexCoord1dARB);
-  SET_MultiTexCoord1dvARB(disp, glMultiTexCoord1dvARB);
-  SET_MultiTexCoord1fARB(disp, glMultiTexCoord1fARB);
-  SET_MultiTexCoord1fvARB(disp, glMultiTexCoord1fvARB);
-  SET_MultiTexCoord1iARB(disp, glMultiTexCoord1iARB);
-  SET_MultiTexCoord1ivARB(disp, glMultiTexCoord1ivARB);
-  SET_MultiTexCoord1sARB(disp, glMultiTexCoord1sARB);
-  SET_MultiTexCoord1svARB(disp, glMultiTexCoord1svARB);
-  SET_MultiTexCoord2dARB(disp, glMultiTexCoord2dARB);
-  SET_MultiTexCoord2dvARB(disp, glMultiTexCoord2dvARB);
-  SET_MultiTexCoord2fARB(disp, glMultiTexCoord2fARB);
-  SET_MultiTexCoord2fvARB(disp, glMultiTexCoord2fvARB);
-  SET_MultiTexCoord2iARB(disp, glMultiTexCoord2iARB);
-  SET_MultiTexCoord2ivARB(disp, glMultiTexCoord2ivARB);
-  SET_MultiTexCoord2sARB(disp, glMultiTexCoord2sARB);
-  SET_MultiTexCoord2svARB(disp, glMultiTexCoord2svARB);
-  SET_MultiTexCoord3dARB(disp, glMultiTexCoord3dARB);
-  SET_MultiTexCoord3dvARB(disp, glMultiTexCoord3dvARB);
-  SET_MultiTexCoord3fARB(disp, glMultiTexCoord3fARB);
-  SET_MultiTexCoord3fvARB(disp, glMultiTexCoord3fvARB);
-  SET_MultiTexCoord3iARB(disp, glMultiTexCoord3iARB);
-  SET_MultiTexCoord3ivARB(disp, glMultiTexCoord3ivARB);
-  SET_MultiTexCoord3sARB(disp, glMultiTexCoord3sARB);
-  SET_MultiTexCoord3svARB(disp, glMultiTexCoord3svARB);
-  SET_MultiTexCoord4dARB(disp, glMultiTexCoord4dARB);
-  SET_MultiTexCoord4dvARB(disp, glMultiTexCoord4dvARB);
-  SET_MultiTexCoord4fARB(disp, glMultiTexCoord4fARB);
-  SET_MultiTexCoord4fvARB(disp, glMultiTexCoord4fvARB);
-  SET_MultiTexCoord4iARB(disp, glMultiTexCoord4iARB);
-  SET_MultiTexCoord4ivARB(disp, glMultiTexCoord4ivARB);
-  SET_MultiTexCoord4sARB(disp, glMultiTexCoord4sARB);
-  SET_MultiTexCoord4svARB(disp, glMultiTexCoord4svARB);
-  SET_NewList(disp, glNewList);
-  SET_Normal3b(disp, glNormal3b);
-  SET_Normal3bv(disp, glNormal3bv);
-  SET_Normal3d(disp, glNormal3d);
-  SET_Normal3dv(disp, glNormal3dv);
-  SET_Normal3f(disp, glNormal3f);
-  SET_Normal3fv(disp, glNormal3fv);
-  SET_Normal3i(disp, glNormal3i);
-  SET_Normal3iv(disp, glNormal3iv);
-  SET_Normal3s(disp, glNormal3s);
-  SET_Normal3sv(disp, glNormal3sv);
-  SET_NormalPointer(disp, glNormalPointer);
-//SET_NormalPointerEXT(disp, glNormalPointerEXT);
-  SET_Ortho(disp, glOrtho);
-//SET_PassTexCoordATI(disp, glPassTexCoordEXT);         // <-- EXT -> ATI
-  SET_PassThrough(disp, glPassThrough);
-  SET_PixelMapfv(disp, glPixelMapfv);
-  SET_PixelMapuiv(disp, glPixelMapuiv);
-  SET_PixelMapusv(disp, glPixelMapusv);
-  SET_PixelStoref(disp, glPixelStoref);
-  SET_PixelStorei(disp, glPixelStorei);
-//SET_PixelTexGenParameterfSGIS(disp, glPixelTexGenParameterfSGIS);
-//SET_PixelTexGenParameterfvSGIS(disp, glPixelTexGenParameterfvSGIS);
-//SET_PixelTexGenParameteriSGIS(disp, glPixelTexGenParameteriSGIS);
-//SET_PixelTexGenParameterivSGIS(disp, glPixelTexGenParameterivSGIS);
-//  SET_PixelTexGenSGIX(disp, glPixelTexGenSGIX);
-  SET_PixelTransferf(disp, glPixelTransferf);
-  SET_PixelTransferi(disp, glPixelTransferi);
-  SET_PixelZoom(disp, glPixelZoom);
-  SET_PointParameterfEXT(disp, glPointParameterfARB);      // <-- ARB -> EXT
-  SET_PointParameterfvEXT(disp, glPointParameterfvARB);    // <-- ARB -> EXT
-  SET_PointParameteriNV(disp, glPointParameteriNV);
-  SET_PointParameterivNV(disp, glPointParameterivNV);
-  SET_PointSize(disp, glPointSize);
-  SET_PolygonMode(disp, glPolygonMode);
-  SET_PolygonOffset(disp, glPolygonOffset);
-//SET_PolygonOffsetEXT(disp, glPolygonOffsetEXT);
-  SET_PolygonStipple(disp, glPolygonStipple);
-  SET_PopAttrib(disp, glPopAttrib);
-  SET_PopClientAttrib(disp, glPopClientAttrib);
-  SET_PopMatrix(disp, glPopMatrix);
-  SET_PopName(disp, glPopName);
-  SET_PrioritizeTextures(disp, glPrioritizeTextures);
-  SET_ProgramEnvParameter4dARB(disp, glProgramEnvParameter4dARB);
-  SET_ProgramEnvParameter4dvARB(disp, glProgramEnvParameter4dvARB);
-  SET_ProgramEnvParameter4fARB(disp, glProgramEnvParameter4fARB);
-  SET_ProgramEnvParameter4fvARB(disp, glProgramEnvParameter4fvARB);
-  SET_ProgramLocalParameter4dARB(disp, glProgramLocalParameter4dARB);
-  SET_ProgramLocalParameter4dvARB(disp, glProgramLocalParameter4dvARB);
-  SET_ProgramLocalParameter4fARB(disp, glProgramLocalParameter4fARB);
-  SET_ProgramLocalParameter4fvARB(disp, glProgramLocalParameter4fvARB);
-//SET_ProgramNamedParameter4dNV(disp, glProgramNamedParameter4dNV);
-//SET_ProgramNamedParameter4dvNV(disp, glProgramNamedParameter4dvNV);
-//SET_ProgramNamedParameter4fNV(disp, glProgramNamedParameter4fNV);
-//SET_ProgramNamedParameter4fvNV(disp, glProgramNamedParameter4fvNV);
-//SET_ProgramParameter4dNV(disp, glProgramParameter4dNV);
-//SET_ProgramParameter4dvNV(disp, glProgramParameter4dvNV);
-//SET_ProgramParameter4fNV(disp, glProgramParameter4fNV);
-//SET_ProgramParameter4fvNV(disp, glProgramParameter4fvNV);
-//SET_ProgramParameters4dvNV(disp, glProgramParameters4dvNV);
-//SET_ProgramParameters4fvNV(disp, glProgramParameters4fvNV);
-  SET_ProgramStringARB(disp, glProgramStringARB);
-  SET_PushAttrib(disp, glPushAttrib);
-  SET_PushClientAttrib(disp, glPushClientAttrib);
-  SET_PushMatrix(disp, glPushMatrix);
-  SET_PushName(disp, glPushName);
-  SET_RasterPos2d(disp, glRasterPos2d);
-  SET_RasterPos2dv(disp, glRasterPos2dv);
-  SET_RasterPos2f(disp, glRasterPos2f);
-  SET_RasterPos2fv(disp, glRasterPos2fv);
-  SET_RasterPos2i(disp, glRasterPos2i);
-  SET_RasterPos2iv(disp, glRasterPos2iv);
-  SET_RasterPos2s(disp, glRasterPos2s);
-  SET_RasterPos2sv(disp, glRasterPos2sv);
-  SET_RasterPos3d(disp, glRasterPos3d);
-  SET_RasterPos3dv(disp, glRasterPos3dv);
-  SET_RasterPos3f(disp, glRasterPos3f);
-  SET_RasterPos3fv(disp, glRasterPos3fv);
-  SET_RasterPos3i(disp, glRasterPos3i);
-  SET_RasterPos3iv(disp, glRasterPos3iv);
-  SET_RasterPos3s(disp, glRasterPos3s);
-  SET_RasterPos3sv(disp, glRasterPos3sv);
-  SET_RasterPos4d(disp, glRasterPos4d);
-  SET_RasterPos4dv(disp, glRasterPos4dv);
-  SET_RasterPos4f(disp, glRasterPos4f);
-  SET_RasterPos4fv(disp, glRasterPos4fv);
-  SET_RasterPos4i(disp, glRasterPos4i);
-  SET_RasterPos4iv(disp, glRasterPos4iv);
-  SET_RasterPos4s(disp, glRasterPos4s);
-  SET_RasterPos4sv(disp, glRasterPos4sv);
-  SET_ReadBuffer(disp, glReadBuffer);
-  SET_ReadPixels(disp, glReadPixels);
-  SET_Rectd(disp, glRectd);
-  SET_Rectdv(disp, glRectdv);
-  SET_Rectf(disp, glRectf);
-  SET_Rectfv(disp, glRectfv);
-  SET_Recti(disp, glRecti);
-  SET_Rectiv(disp, glRectiv);
-  SET_Rects(disp, glRects);
-  SET_Rectsv(disp, glRectsv);
-  SET_RenderMode(disp, glRenderMode);
-  SET_RenderbufferStorageEXT(disp, glRenderbufferStorageEXT);
-//SET_RequestResidentProgramsNV(disp, glRequestResidentProgramsNV);
-  SET_ResetHistogram(disp, glResetHistogram);
-  SET_ResetMinmax(disp, glResetMinmax);
-//SET_ResizeBuffersMESA(disp, glResizeBuffersMESA);
-  SET_Rotated(disp, glRotated);
-  SET_Rotatef(disp, glRotatef);
-  SET_SampleCoverageARB(disp, glSampleCoverageARB);
-//SET_SampleMapATI(disp, glSampleMapEXT);       // <-- EXT -> ATI
-//SET_SampleMaskSGIS(disp, glSampleMaskSGIS);
-//SET_SamplePatternSGIS(disp, glSamplePatternSGIS);
-  SET_Scaled(disp, glScaled);
-  SET_Scalef(disp, glScalef);
-  SET_Scissor(disp, glScissor);
-  SET_SecondaryColor3bEXT(disp, glSecondaryColor3bEXT);
-  SET_SecondaryColor3bvEXT(disp, glSecondaryColor3bvEXT);
-  SET_SecondaryColor3dEXT(disp, glSecondaryColor3dEXT);
-  SET_SecondaryColor3dvEXT(disp, glSecondaryColor3dvEXT);
-  SET_SecondaryColor3fEXT(disp, glSecondaryColor3fEXT);
-  SET_SecondaryColor3fvEXT(disp, glSecondaryColor3fvEXT);
-  SET_SecondaryColor3iEXT(disp, glSecondaryColor3iEXT);
-  SET_SecondaryColor3ivEXT(disp, glSecondaryColor3ivEXT);
-  SET_SecondaryColor3sEXT(disp, glSecondaryColor3sEXT);
-  SET_SecondaryColor3svEXT(disp, glSecondaryColor3svEXT);
-  SET_SecondaryColor3ubEXT(disp, glSecondaryColor3ubEXT);
-  SET_SecondaryColor3ubvEXT(disp, glSecondaryColor3ubvEXT);
-  SET_SecondaryColor3uiEXT(disp, glSecondaryColor3uiEXT);
-  SET_SecondaryColor3uivEXT(disp, glSecondaryColor3uivEXT);
-  SET_SecondaryColor3usEXT(disp, glSecondaryColor3usEXT);
-  SET_SecondaryColor3usvEXT(disp, glSecondaryColor3usvEXT);
-  SET_SecondaryColorPointerEXT(disp, glSecondaryColorPointerEXT);
-  SET_SelectBuffer(disp, glSelectBuffer);
-  SET_SeparableFilter2D(disp, glSeparableFilter2D);
-  SET_SetFenceNV(disp, glSetFenceAPPLE);  // <-- APPLE -> NV
-//SET_SetFragmentShaderConstantATI(disp, glSetFragmentShaderConstantEXT);   // <-- EXT -> ATI
-  SET_ShadeModel(disp, glShadeModel);
-  SET_ShaderSourceARB(disp, glShaderSourceARB);
-  SET_StencilFunc(disp, glStencilFunc);
-  SET_StencilFuncSeparate(disp, glStencilFuncSeparate);
-  SET_StencilMask(disp, glStencilMask);
-  SET_StencilMaskSeparate(disp, glStencilMaskSeparate);
-  SET_StencilOp(disp, glStencilOp);
-  SET_StencilOpSeparate(disp, glStencilOpSeparate);
-  SET_TestFenceNV(disp, glTestFenceAPPLE); // <-- APPLE -> NV
-  SET_TexCoord1d(disp, glTexCoord1d);
-  SET_TexCoord1dv(disp, glTexCoord1dv);
-  SET_TexCoord1f(disp, glTexCoord1f);
-  SET_TexCoord1fv(disp, glTexCoord1fv);
-  SET_TexCoord1i(disp, glTexCoord1i);
-  SET_TexCoord1iv(disp, glTexCoord1iv);
-  SET_TexCoord1s(disp, glTexCoord1s);
-  SET_TexCoord1sv(disp, glTexCoord1sv);
-  SET_TexCoord2d(disp, glTexCoord2d);
-  SET_TexCoord2dv(disp, glTexCoord2dv);
-  SET_TexCoord2f(disp, glTexCoord2f);
-  SET_TexCoord2fv(disp, glTexCoord2fv);
-  SET_TexCoord2i(disp, glTexCoord2i);
-  SET_TexCoord2iv(disp, glTexCoord2iv);
-  SET_TexCoord2s(disp, glTexCoord2s);
-  SET_TexCoord2sv(disp, glTexCoord2sv);
-  SET_TexCoord3d(disp, glTexCoord3d);
-  SET_TexCoord3dv(disp, glTexCoord3dv);
-  SET_TexCoord3f(disp, glTexCoord3f);
-  SET_TexCoord3fv(disp, glTexCoord3fv);
-  SET_TexCoord3i(disp, glTexCoord3i);
-  SET_TexCoord3iv(disp, glTexCoord3iv);
-  SET_TexCoord3s(disp, glTexCoord3s);
-  SET_TexCoord3sv(disp, glTexCoord3sv);
-  SET_TexCoord4d(disp, glTexCoord4d);
-  SET_TexCoord4dv(disp, glTexCoord4dv);
-  SET_TexCoord4f(disp, glTexCoord4f);
-  SET_TexCoord4fv(disp, glTexCoord4fv);
-  SET_TexCoord4i(disp, glTexCoord4i);
-  SET_TexCoord4iv(disp, glTexCoord4iv);
-  SET_TexCoord4s(disp, glTexCoord4s);
-  SET_TexCoord4sv(disp, glTexCoord4sv);
-  SET_TexCoordPointer(disp, glTexCoordPointer);
-//SET_TexCoordPointerEXT(disp, glTexCoordPointerEXT);
-  SET_TexEnvf(disp, glTexEnvf);
-  SET_TexEnvfv(disp, glTexEnvfv);
-  SET_TexEnvi(disp, glTexEnvi);
-  SET_TexEnviv(disp, glTexEnviv);
-  SET_TexGend(disp, glTexGend);
-  SET_TexGendv(disp, glTexGendv);
-  SET_TexGenf(disp, glTexGenf);
-  SET_TexGenfv(disp, glTexGenfv);
-  SET_TexGeni(disp, glTexGeni);
-  SET_TexGeniv(disp, glTexGeniv);
-  SET_TexImage1D(disp, glTexImage1D);
-  SET_TexImage2D(disp, glTexImage2D);
-  SET_TexImage3D(disp, glTexImage3D);
-  SET_TexParameterf(disp, glTexParameterf);
-  SET_TexParameterfv(disp, glTexParameterfv);
-  SET_TexParameteri(disp, glTexParameteri);
-  SET_TexParameteriv(disp, glTexParameteriv);
-  SET_TexSubImage1D(disp, glTexSubImage1D);
-  SET_TexSubImage2D(disp, glTexSubImage2D);
-  SET_TexSubImage3D(disp, glTexSubImage3D);
-//SET_TrackMatrixNV(disp, glTrackMatrixNV);
-  SET_Translated(disp, glTranslated);
-  SET_Translatef(disp, glTranslatef);
-  SET_Uniform1fARB(disp, glUniform1fARB);
-  SET_Uniform1fvARB(disp, glUniform1fvARB);
-  SET_Uniform1iARB(disp, glUniform1iARB);
-  SET_Uniform1ivARB(disp, glUniform1ivARB);
-  SET_Uniform2fARB(disp, glUniform2fARB);
-  SET_Uniform2fvARB(disp, glUniform2fvARB);
-  SET_Uniform2iARB(disp, glUniform2iARB);
-  SET_Uniform2ivARB(disp, glUniform2ivARB);
-  SET_Uniform3fARB(disp, glUniform3fARB);
-  SET_Uniform3fvARB(disp, glUniform3fvARB);
-  SET_Uniform3iARB(disp, glUniform3iARB);
-  SET_Uniform3ivARB(disp, glUniform3ivARB);
-  SET_Uniform4fARB(disp, glUniform4fARB);
-  SET_Uniform4fvARB(disp, glUniform4fvARB);
-  SET_Uniform4iARB(disp, glUniform4iARB);
-  SET_Uniform4ivARB(disp, glUniform4ivARB);
-  SET_UniformMatrix2fvARB(disp, glUniformMatrix2fvARB);
-  SET_UniformMatrix3fvARB(disp, glUniformMatrix3fvARB);
-  SET_UniformMatrix4fvARB(disp, glUniformMatrix4fvARB);
-  SET_UnlockArraysEXT(disp, glUnlockArraysEXT);
-  SET_UnmapBufferARB(disp, glUnmapBufferARB);
-  SET_UseProgramObjectARB(disp, glUseProgramObjectARB);
-  SET_ValidateProgramARB(disp, glValidateProgramARB);
-  SET_Vertex2d(disp, glVertex2d);
-  SET_Vertex2dv(disp, glVertex2dv);
-  SET_Vertex2f(disp, glVertex2f);
-  SET_Vertex2fv(disp, glVertex2fv);
-  SET_Vertex2i(disp, glVertex2i);
-  SET_Vertex2iv(disp, glVertex2iv);
-  SET_Vertex2s(disp, glVertex2s);
-  SET_Vertex2sv(disp, glVertex2sv);
-  SET_Vertex3d(disp, glVertex3d);
-  SET_Vertex3dv(disp, glVertex3dv);
-  SET_Vertex3f(disp, glVertex3f);
-  SET_Vertex3fv(disp, glVertex3fv);
-  SET_Vertex3i(disp, glVertex3i);
-  SET_Vertex3iv(disp, glVertex3iv);
-  SET_Vertex3s(disp, glVertex3s);
-  SET_Vertex3sv(disp, glVertex3sv);
-  SET_Vertex4d(disp, glVertex4d);
-  SET_Vertex4dv(disp, glVertex4dv);
-  SET_Vertex4f(disp, glVertex4f);
-  SET_Vertex4fv(disp, glVertex4fv);
-  SET_Vertex4i(disp, glVertex4i);
-  SET_Vertex4iv(disp, glVertex4iv);
-  SET_Vertex4s(disp, glVertex4s);
-  SET_Vertex4sv(disp, glVertex4sv);
-//SET_VertexArrayRangeNV(disp, glVertexArrayRangeNV);
-  SET_VertexAttrib1dARB(disp, glVertexAttrib1dARB);
-  SET_VertexAttrib1dvARB(disp, glVertexAttrib1dvARB);
-  SET_VertexAttrib1fARB(disp, glVertexAttrib1fARB);
-  SET_VertexAttrib1fvARB(disp, glVertexAttrib1fvARB);
-  SET_VertexAttrib1sARB(disp, glVertexAttrib1sARB);
-  SET_VertexAttrib1svARB(disp, glVertexAttrib1svARB);
-  SET_VertexAttrib2dARB(disp, glVertexAttrib2dARB);
-  SET_VertexAttrib2dvARB(disp, glVertexAttrib2dvARB);
-  SET_VertexAttrib2fARB(disp, glVertexAttrib2fARB);
-  SET_VertexAttrib2fvARB(disp, glVertexAttrib2fvARB);
-  SET_VertexAttrib2sARB(disp, glVertexAttrib2sARB);
-  SET_VertexAttrib2svARB(disp, glVertexAttrib2svARB);
-  SET_VertexAttrib3dARB(disp, glVertexAttrib3dARB);
-  SET_VertexAttrib3dvARB(disp, glVertexAttrib3dvARB);
-  SET_VertexAttrib3fARB(disp, glVertexAttrib3fARB);
-  SET_VertexAttrib3fvARB(disp, glVertexAttrib3fvARB);
-  SET_VertexAttrib3sARB(disp, glVertexAttrib3sARB);
-  SET_VertexAttrib3svARB(disp, glVertexAttrib3svARB);
-  SET_VertexAttrib4NbvARB(disp, glVertexAttrib4NbvARB);
-  SET_VertexAttrib4NivARB(disp, glVertexAttrib4NivARB);
-  SET_VertexAttrib4NsvARB(disp, glVertexAttrib4NsvARB);
-  SET_VertexAttrib4NubARB(disp, glVertexAttrib4NubARB);
-  SET_VertexAttrib4NubvARB(disp, glVertexAttrib4NubvARB);
-  SET_VertexAttrib4NuivARB(disp, glVertexAttrib4NuivARB);
-  SET_VertexAttrib4NusvARB(disp, glVertexAttrib4NusvARB);
-  SET_VertexAttrib4bvARB(disp, glVertexAttrib4bvARB);
-  SET_VertexAttrib4dARB(disp, glVertexAttrib4dARB);
-  SET_VertexAttrib4dvARB(disp, glVertexAttrib4dvARB);
-  SET_VertexAttrib4fARB(disp, glVertexAttrib4fARB);
-  SET_VertexAttrib4fvARB(disp, glVertexAttrib4fvARB);
-  SET_VertexAttrib4ivARB(disp, glVertexAttrib4ivARB);
-  SET_VertexAttrib4sARB(disp, glVertexAttrib4sARB);
-  SET_VertexAttrib4svARB(disp, glVertexAttrib4svARB);
-  SET_VertexAttrib4ubvARB(disp, glVertexAttrib4ubvARB);
-  SET_VertexAttrib4uivARB(disp, glVertexAttrib4uivARB);
-  SET_VertexAttrib4usvARB(disp, glVertexAttrib4usvARB);
-  SET_VertexAttribPointerARB(disp, glVertexAttribPointerARB);
-  SET_VertexPointer(disp, glVertexPointer);
-//  SET_VertexPointerEXT(disp, glVertexPointerEXT);
-  SET_Viewport(disp, glViewport);
-  SET_WindowPos2dMESA(disp, glWindowPos2dARB);
-  SET_WindowPos2dvMESA(disp, glWindowPos2dvARB);
-  SET_WindowPos2fMESA(disp, glWindowPos2fARB);
-  SET_WindowPos2fvMESA(disp, glWindowPos2fvARB);
-  SET_WindowPos2iMESA(disp, glWindowPos2iARB);
-  SET_WindowPos2ivMESA(disp, glWindowPos2ivARB);
-  SET_WindowPos2sMESA(disp, glWindowPos2sARB);
-  SET_WindowPos2svMESA(disp, glWindowPos2svARB);
-  SET_WindowPos3dMESA(disp, glWindowPos3dARB);
-  SET_WindowPos3dvMESA(disp, glWindowPos3dvARB);
-  SET_WindowPos3fMESA(disp, glWindowPos3fARB);
-  SET_WindowPos3fvMESA(disp, glWindowPos3fvARB);
-  SET_WindowPos3iMESA(disp, glWindowPos3iARB);
-  SET_WindowPos3ivMESA(disp, glWindowPos3ivARB);
-  SET_WindowPos3sMESA(disp, glWindowPos3sARB);
-  SET_WindowPos3svMESA(disp, glWindowPos3svARB);
-//SET_WindowPos4dMESA(disp, glWindowPos4dMESA);
-//SET_WindowPos4dvMESA(disp, glWindowPos4dvMESA);
-//SET_WindowPos4fMESA(disp, glWindowPos4fMESA);
-//SET_WindowPos4fvMESA(disp, glWindowPos4fvMESA);
-//SET_WindowPos4iMESA(disp, glWindowPos4iMESA);
-//SET_WindowPos4ivMESA(disp, glWindowPos4ivMESA);
-//SET_WindowPos4sMESA(disp, glWindowPos4sMESA);
-//SET_WindowPos4svMESA(disp, glWindowPos4svMESA);
-}
diff --git a/configure.ac b/configure.ac
index 51ab4c6..b2a07a6 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1724,22 +1724,14 @@ if test "x$XQUARTZ" = xyes; then
 	AC_DEFINE(XQUARTZ,1,[Have Quartz])
 	AC_DEFINE(ROOTLESS,1,[Build Rootless code])
 
-#glxAGL / glxCGL don't work yet
-#	AC_CACHE_CHECK([for AGL framework],xorg_cv_AGL_framework,[
-#		save_LDFLAGS=$LDFLAGS
-#		LDFLAGS="$LDFLAGS -framework AGL"
-#		AC_LINK_IFELSE(
-#			[char aglEnable(); int main() { aglEnable(); return 0;}],
-#			[xorg_cv_AGL_framework=yes],
-#			[xorg_cv_AGL_framework=no])
-#		LDFLAGS=$save_LDFLAGS
-#	])
-	xorg_cv_AGL_framework=no
-	DARWIN_GLX_LIBS='$(top_builddir)/GL/apple/indirect.o $(top_builddir)/GL/glx/libglx.la'
-	DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $DARWIN_GLX_LIBS"
+	DARWIN_GLX_LIBS='$(top_builddir)/hw/xquartz/GL/libCGLCore.la $(top_builddir)/GL/glx/libglx.la'
+	DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $XPSTUBS_LIB $DARWIN_GLX_LIBS"
 	AC_SUBST([DARWIN_LIBS])
+
 	AC_CHECK_LIB([Xplugin],[xp_init],[:])
+
 	CFLAGS="${CFLAGS} -DROOTLESS_WORKAROUND -DNO_ALLOCA"
+
 	if test "x$XF86MISC" = xyes || test "x$XF86MISC" = xauto; then
 		AC_MSG_NOTICE([Disabling XF86Misc extension])
 		XF86MISC=no
@@ -2087,7 +2079,6 @@ XORG_MANPAGE_SECTIONS
 AC_OUTPUT([
 Makefile
 GL/Makefile
-GL/apple/Makefile
 GL/glx/Makefile
 include/Makefile
 afb/Makefile
@@ -2181,6 +2172,7 @@ hw/xgl/glxext/module/Makefile
 hw/xnest/Makefile
 hw/xwin/Makefile
 hw/xquartz/Makefile
+hw/xquartz/GL/Makefile
 hw/xquartz/bundle/Makefile
 hw/xquartz/xpr/Makefile
 hw/kdrive/Makefile
diff --git a/hw/xquartz/GL/Makefile.am b/hw/xquartz/GL/Makefile.am
new file mode 100644
index 0000000..41d4566
--- /dev/null
+++ b/hw/xquartz/GL/Makefile.am
@@ -0,0 +1,13 @@
+noinst_LTLIBRARIES = libCGLCore.la
+AM_CFLAGS = $(XSERVER_CFLAGS) $(DIX_CFLAGS)
+AM_CPPFLAGS = \
+	-I$(top_srcdir) \
+	-I$(top_srcdir)/GL/glx \
+	-I$(top_srcdir)/GL/include \
+	-I$(top_srcdir)/GL/mesa/glapi \
+	-I$(top_srcdir)/hw/xquartz \
+	-I$(top_srcdir)/hw/xquartz/xpr \
+	-I$(top_srcdir)/miext/damage
+
+libCGLCore_la_SOURCES = \
+	indirect.c
diff --git a/hw/xquartz/GL/indirect.c b/hw/xquartz/GL/indirect.c
new file mode 100644
index 0000000..a0884d4
--- /dev/null
+++ b/hw/xquartz/GL/indirect.c
@@ -0,0 +1,1940 @@
+/*
+ * GLX implementation that uses Apple's OpenGL.framework
+ * (Indirect rendering path)
+ *
+ * Copyright (c) 2007 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.
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include "dri.h"
+
+#define GL_EXT_histogram 1
+#define GL_EXT_polygon_offset 1
+#define GL_SGIS_pixel_texture 1
+#define GL_SGIX_pixel_texture 1
+#define GL_EXT_multisample 1
+#define GL_SGIS_multisample 1
+#define GL_EXT_vertex_array 1
+#define GL_ARB_point_parameters 1
+#define GL_NV_vertex_array_range 1
+#define GL_MESA_resize_buffers 1
+#define GL_ARB_window_pos 1
+#define GL_EXT_cull_vertex 1
+#define GL_NV_vertex_program 1
+#define GL_APPLE_fence 1
+#define GL_IBM_multimode_draw_arrays 1
+#define GL_EXT_fragment_shader 1
+
+#include <OpenGL/OpenGL.h>
+#include <OpenGL/CGLContext.h>
+
+// X11 and X11's glx
+#include <GL/gl.h>
+#include <GL/glxproto.h>
+#include <windowstr.h>
+#include <resource.h>
+#include <GL/glxint.h>
+#include <GL/glxtokens.h>
+#include <scrnintstr.h>
+#include <glxserver.h>
+#include <glxscreens.h>
+#include <glxdrawable.h>
+#include <glxcontext.h>
+#include <glxext.h>
+#include <glxutil.h>
+#include <glxscreens.h>
+#include <GL/internal/glcore.h>
+#include "x-hash.h"
+#include "x-list.h"
+
+#include <dispatch.h>
+#define GLAPIENTRYP *
+typedef unsigned long long GLuint64EXT;
+typedef long long GLint64EXT;
+#include <Xplugin.h>
+#include "glcontextmodes.h"
+#include <glapi.h>
+#include <glapitable.h>
+
+// ggs: needed to call back to glx with visual configs
+extern void GlxSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs, void **configprivs);
+__GLXprovider * GlxGetMesaProvider (void);
+
+// Write debugging output, or not
+#ifdef GLAQUA_DEBUG
+#define GLAQUA_DEBUG_MSG ErrorF
+#else
+#define GLAQUA_DEBUG_MSG(a, ...)
+#endif
+
+static void setup_dispatch_table(void);
+GLuint __glFloorLog2(GLuint val);
+void warn_func(void * p1, char *format, ...);
+
+// some prototypes
+static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen);
+static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLXconfig *modes);
+
+static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
+                              int *nvisualp, int *ndepthp,
+                              int *rootDepthp, VisualID *defaultVisp,
+                              unsigned long sizes, int bitsPerRGB);
+static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
+                                   void **privates);
+
+static void glAquaResetExtension(void);
+static void __glXAquaContextDestroy(__GLXcontext *baseContext);
+static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextForceCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask);
+
+static CGLPixelFormatObj makeFormat(__GLXconfig *mode);
+
+__GLXprovider __glXMesaProvider = {
+  __glXAquaScreenProbe,
+  "Core OpenGL",
+    NULL
+};
+
+__GLXprovider *
+GlxGetMesaProvider (void)
+{
+  GLAQUA_DEBUG_MSG("GlxGetMesaProvider\n");
+  return &__glXMesaProvider;
+}
+
+typedef struct __GLXAquaScreen   __GLXAquaScreen;
+typedef struct __GLXAquaContext  __GLXAquaContext;
+typedef struct __GLXAquaDrawable __GLXAquaDrawable;
+
+struct __GLXAquaScreen {
+  __GLXscreen   base;
+  int           index;
+    int num_vis;
+    __GLXconfig *modes;
+};
+
+static __GLXAquaScreen glAquaScreens[MAXSCREENS];
+
+struct __GLXAquaContext {
+  __GLXcontext base;
+  CGLContextObj ctx;
+  CGLPixelFormatObj pixelFormat;
+  xp_surface_id sid;
+  unsigned isAttached :1;
+};
+
+struct __GLXAquaDrawable {
+  __GLXdrawable base;
+    DrawablePtr pDraw;
+    xp_surface_id sid;
+};
+
+static __GLXcontext *
+__glXAquaScreenCreateContext(__GLXscreen *screen,
+			     __GLXconfig *config,
+			     __GLXcontext *baseShareContext)
+{
+  __GLXAquaContext *context;
+  __GLXAquaContext *shareContext = (__GLXAquaContext *) baseShareContext;
+  CGLError gl_err;
+  
+  GLAQUA_DEBUG_MSG("glXAquaScreenCreateContext\n");
+
+  context = malloc (sizeof (__GLXAquaContext));
+  if (context == NULL) return NULL;
+
+  memset(context, 0, sizeof *context);
+
+  context->base.pGlxScreen = screen;
+  context->base.config      = config;
+
+  context->base.destroy        = __glXAquaContextDestroy;
+  context->base.makeCurrent    = __glXAquaContextMakeCurrent;
+  context->base.loseCurrent    = __glXAquaContextLoseCurrent;
+  context->base.copy           = __glXAquaContextCopy;
+  context->base.forceCurrent   = __glXAquaContextForceCurrent;
+  //  context->base.createDrawable = __glXAquaContextCreateDrawable;
+
+  context->pixelFormat = makeFormat(config);
+  if (!context->pixelFormat) {
+        free(context);
+        return NULL;
+  }
+
+  context->ctx = NULL;
+  gl_err = CGLCreateContext(context->pixelFormat,
+                            shareContext ? shareContext->ctx : NULL,
+                            &context->ctx);
+
+  if (gl_err != 0) {
+      ErrorF("CGLCreateContext error: %s\n", CGLErrorString(gl_err));
+      CGLDestroyPixelFormat(context->pixelFormat);
+      free(context);
+      return NULL;
+    }
+	setup_dispatch_table();
+    GLAQUA_DEBUG_MSG("glAquaCreateContext done\n");
+  return &context->base;
+}
+
+static __GLXextensionInfo __glDDXExtensionInfo = {
+    GL_CORE_APPLE,
+    glAquaResetExtension,
+    glAquaInitVisuals,
+    glAquaSetVisualConfigs
+};
+
+void *__glXglDDXExtensionInfo(void) {
+  GLAQUA_DEBUG_MSG("glXAglDDXExtensionInfo\n");
+    return &__glDDXExtensionInfo;
+}
+
+/* maps from surface id -> list of __GLcontext */
+static x_hash_table *surface_hash;
+
+static void __glXAquaContextDestroy(__GLXcontext *baseContext) {
+    x_list *lst;
+
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
+
+    GLAQUA_DEBUG_MSG("glAquaContextDestroy (ctx 0x%x)\n",
+                     (unsigned int) baseContext);
+    if (context != NULL) {
+      if (context->sid != 0 && surface_hash != NULL) {
+		lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
+		lst = x_list_remove(lst, context);
+		x_hash_table_insert(surface_hash, (void *) context->sid, lst);
+      }
+
+      if (context->ctx != NULL) CGLDestroyContext(context->ctx);
+
+      if (context->pixelFormat != NULL)	CGLDestroyPixelFormat(context->pixelFormat);
+      
+      free(context);
+    }
+}
+
+static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext) {
+    CGLError gl_err;
+
+    GLAQUA_DEBUG_MSG("glAquaLoseCurrent (ctx 0x%p)\n", baseContext);
+
+    gl_err = CGLSetCurrentContext(NULL);
+    if (gl_err != 0)
+      ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
+
+    __glXLastContext = NULL; // Mesa does this; why?
+
+    return GL_TRUE;
+}
+
+/* Called when a surface is destroyed as a side effect of destroying
+   the window it's attached to. */
+static void surface_notify(void *_arg, void *data) {
+    DRISurfaceNotifyArg *arg = (DRISurfaceNotifyArg *)_arg;
+    __GLXAquaDrawable *draw = (__GLXAquaDrawable *)data;
+    __GLXAquaContext *context;
+    x_list *lst;
+	if(_arg == NULL || data == NULL) {
+		ErrorF("surface_notify called with bad params");
+		return;
+	}
+	
+    GLAQUA_DEBUG_MSG("surface_notify(%p, %p)\n", _arg, data);
+    switch (arg->kind) {
+    case AppleDRISurfaceNotifyDestroyed:
+        if (surface_hash != NULL)
+            x_hash_table_remove(surface_hash, (void *) arg->id);
+	        draw->base.pDraw = NULL;
+			draw->sid = 0;
+        break;
+
+    case AppleDRISurfaceNotifyChanged:
+        if (surface_hash != NULL) {
+            lst = x_hash_table_lookup(surface_hash, (void *) arg->id, NULL);
+            for (; lst != NULL; lst = lst->next)
+            {
+                context = lst->data;
+                xp_update_gl_context(context->ctx);
+            }
+        }
+        break;
+	default:
+		ErrorF("surface_notify: unknown kind %d\n", arg->kind);
+		break;
+    }
+}
+
+static void attach(__GLXAquaContext *context, __GLXAquaDrawable *draw) {
+    DrawablePtr pDraw;
+	GLAQUA_DEBUG_MSG("attach(%p, %p)\n", context, draw);
+    pDraw = draw->base.pDraw;
+
+    if (draw->sid == 0) {
+//        if (!quartzProcs->CreateSurface(pDraw->pScreen, pDraw->id, pDraw,
+        if (!DRICreateSurface(pDraw->pScreen, pDraw->id, pDraw,
+                                        0, &draw->sid, NULL,
+                                        surface_notify, draw))
+            return;
+        draw->pDraw = pDraw;
+	} 
+
+    if (!context->isAttached || context->sid != draw->sid) {
+        x_list *lst;
+
+        if (xp_attach_gl_context(context->ctx, draw->sid) != Success) {
+//            quartzProcs->DestroySurface(pDraw->pScreen, pDraw->id, pDraw,
+            DRIDestroySurface(pDraw->pScreen, pDraw->id, pDraw,
+								surface_notify, draw);
+            if (surface_hash != NULL)
+                x_hash_table_remove(surface_hash, (void *) draw->sid);
+
+            draw->sid = 0;
+            return;
+        }
+
+        context->isAttached = TRUE;
+        context->sid = draw->sid;
+
+        if (surface_hash == NULL)
+            surface_hash = x_hash_table_new(NULL, NULL, NULL, NULL);
+
+        lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
+        if (x_list_find(lst, context) == NULL) {
+            lst = x_list_prepend(lst, context);
+            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
+        }
+
+        GLAQUA_DEBUG_MSG("attached 0x%x to 0x%x\n", (unsigned int) pDraw->id,
+                         (unsigned int) draw->sid);
+    } 
+}
+
+#if 0     // unused
+static void unattach(__GLXAquaContext *context) {
+	x_list *lst;
+	GLAQUA_DEBUG_MSG("unattach\n");
+	if (context == NULL) {
+		ErrorF("Tried to unattach a null context\n");
+		return;
+	}
+    if (context->isAttached) {
+        GLAQUA_DEBUG_MSG("unattaching\n");
+
+        if (surface_hash != NULL) {
+            lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
+            lst = x_list_remove(lst, context);
+            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
+        }
+
+        CGLClearDrawable(context->ctx);
+        context->isAttached = FALSE;
+        context->sid = 0;
+    }
+}
+#endif
+
+static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext) {
+    CGLError gl_err;
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
+	__GLXAquaDrawable *drawPriv = (__GLXAquaDrawable *) context->base.drawPriv;
+
+    GLAQUA_DEBUG_MSG("glAquaMakeCurrent (ctx 0x%p)\n", baseContext);
+    
+    attach(context, drawPriv);
+
+    gl_err = CGLSetCurrentContext(context->ctx);
+    if (gl_err != 0)
+        ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
+    
+    return gl_err == 0;
+}
+
+static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask)
+{
+    CGLError gl_err;
+
+    __GLXAquaContext *dst = (__GLXAquaContext *) baseDst;
+    __GLXAquaContext *src = (__GLXAquaContext *) baseSrc;
+
+    GLAQUA_DEBUG_MSG("GLXAquaContextCopy\n");
+
+    gl_err = CGLCopyContext(src->ctx, dst->ctx, mask);
+    if (gl_err != 0)
+        ErrorF("CGLCopyContext error: %s\n", CGLErrorString(gl_err));
+
+    return gl_err == 0;
+}
+
+static int __glXAquaContextForceCurrent(__GLXcontext *baseContext)
+{
+    CGLError gl_err;
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
+    GLAQUA_DEBUG_MSG("glAquaForceCurrent (ctx %p)\n", context->ctx);
+
+    gl_err = CGLSetCurrentContext(context->ctx);
+    if (gl_err != 0)
+        ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
+
+    return gl_err == 0;
+}
+
+/* Drawing surface notification callbacks */
+
+static GLboolean __glXAquaDrawableResize(__GLXdrawable *base)  {
+    GLAQUA_DEBUG_MSG("unimplemented glAquaDrawableResize\n");
+    return GL_TRUE;
+}
+
+static GLboolean __glXAquaDrawableSwapBuffers(__GLXdrawable *base) {
+    CGLError gl_err;
+	__GLXAquaContext * drawableCtx;
+//    GLAQUA_DEBUG_MSG("glAquaDrawableSwapBuffers(%p)\n",base);
+	
+	if(!base) {
+		ErrorF("glXAquaDrawbleSwapBuffers passed NULL\n");
+	    return GL_FALSE;
+	}
+
+    drawableCtx = (__GLXAquaContext *)base->drawGlxc;
+
+    if (drawableCtx != NULL && drawableCtx->ctx != NULL) {
+        gl_err = CGLFlushDrawable(drawableCtx->ctx);
+        if (gl_err != 0)
+            ErrorF("CGLFlushDrawable error: %s\n", CGLErrorString(gl_err));
+    }
+    return GL_TRUE;
+}
+
+static CGLPixelFormatObj makeFormat(__GLXconfig *config) {
+    int i;
+    CGLPixelFormatAttribute attr[64]; // currently uses max of 30
+    CGLPixelFormatObj result;
+    GLint n_formats;
+    CGLError gl_err;
+    
+    GLAQUA_DEBUG_MSG("makeFormat\n");
+
+    if (!config->rgbMode)
+        return NULL;
+
+    i = 0;
+
+    // attr [i++] = kCGLPFAAcelerated; // require hwaccel - BAD for multiscreen
+    // attr [i++] = kCGLPFANoRecovery; // disable fallback renderers - BAD
+
+    if (config->stereoMode) {
+        attr[i++] = kCGLPFAStereo;
+    }
+
+    if (config->doubleBufferMode) {
+        attr[i++] = kCGLPFADoubleBuffer;
+    }
+
+    if (config->colorIndexMode) {
+        /* ignored */
+    }
+
+    if (config->rgbMode) {
+        attr[i++] = kCGLPFAColorSize;
+        attr[i++] = config->redBits + config->greenBits + config->blueBits;
+        attr[i++] = kCGLPFAAlphaSize;
+        attr[i++] = 1; /* FIXME: ignoring config->alphaBits which is always 0 */
+    }
+
+    if (config->haveAccumBuffer) {
+        attr[i++] = kCGLPFAAccumSize;
+        attr[i++] = config->accumRedBits + config->accumGreenBits
+                    + config->accumBlueBits + config->accumAlphaBits;
+    }
+	
+    if (config->haveDepthBuffer) {
+        attr[i++] = kCGLPFADepthSize;
+        attr[i++] = config->depthBits;
+    }
+	
+    if (config->haveStencilBuffer) {
+        attr[i++] = kCGLPFAStencilSize;
+        attr[i++] = config->stencilBits;
+    }
+
+    attr[i++] = kCGLPFAAuxBuffers;
+    attr[i++] = config->numAuxBuffers;
+
+    /* mode->level ignored */
+
+    /* mode->pixmapMode ? */
+
+    attr[i++] = 0;
+
+    GLAQUA_DEBUG_MSG("makeFormat almost done\n");
+
+    result = NULL;
+    gl_err = CGLChoosePixelFormat(attr, &result, &n_formats);
+    if (gl_err != 0)
+        ErrorF("CGLChoosePixelFormat error: %s\n", CGLErrorString(gl_err));
+
+    GLAQUA_DEBUG_MSG("makeFormat done (0x%x)\n", (unsigned int) result);
+
+    return result;
+}
+
+// Originally copied from Mesa
+
+static int                 numConfigs     = 0;
+static __GLXvisualConfig  *visualConfigs  = NULL;
+static void              **visualPrivates = NULL;
+
+/*
+ * In the case the driver defines no GLX visuals we'll use these.
+ * Note that for TrueColor and DirectColor visuals, bufferSize is the 
+ * sum of redSize, greenSize, blueSize and alphaSize, which may be larger 
+ * than the nplanes/rootDepth of the server's X11 visuals
+ */
+#define NUM_FALLBACK_CONFIGS 5
+static __GLXvisualConfig FallbackConfigs[NUM_FALLBACK_CONFIGS] = {
+  /* [0] = RGB, double buffered, Z */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    True,               /* rgba */
+    -1, -1, -1, 0,      /* rgba sizes */
+    -1, -1, -1, 0,      /* rgba masks */
+     0,  0,  0, 0,      /* rgba accum sizes */
+    True,               /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    0,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+  /* [1] = RGB, double buffered, Z, stencil, accum */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    True,               /* rgba */
+    -1, -1, -1, 0,      /* rgba sizes */
+    -1, -1, -1, 0,      /* rgba masks */
+    16, 16, 16, 0,      /* rgba accum sizes */
+    True,               /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    8,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+  /* [2] = RGB+Alpha, double buffered, Z, stencil, accum */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    True,               /* rgba */
+    -1, -1, -1, 8,      /* rgba sizes */
+    -1, -1, -1, -1,     /* rgba masks */
+    16, 16, 16, 16,     /* rgba accum sizes */
+    True,               /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    8,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+  /* [3] = RGB+Alpha, single buffered, Z, stencil, accum */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    True,               /* rgba */
+    -1, -1, -1, 8,      /* rgba sizes */
+    -1, -1, -1, -1,     /* rgba masks */
+    16, 16, 16, 16,     /* rgba accum sizes */
+    False,              /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    8,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+  /* [4] = CI, double buffered, Z */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    False,              /* rgba? (false = color index) */
+    -1, -1, -1, 0,      /* rgba sizes */
+    -1, -1, -1, 0,      /* rgba masks */
+     0,  0,  0, 0,      /* rgba accum sizes */
+    True,               /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    0,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+};
+
+static __GLXvisualConfig NullConfig = {
+    -1,                 /* vid */
+    -1,                 /* class */
+    False,              /* rgba */
+    -1, -1, -1, 0,      /* rgba sizes */
+    -1, -1, -1, 0,      /* rgba masks */
+     0,  0,  0, 0,      /* rgba accum sizes */
+    False,              /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    0,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE_EXT,       /* visualRating */
+    0,                  /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+};
+
+
+static inline int count_bits(uint32_t x)
+{
+    x = x - ((x >> 1) & 0x55555555);
+    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
+    x = (x + (x >> 4)) & 0x0f0f0f0f;
+    x = x + (x >> 8);
+    x = x + (x >> 16);
+    return x & 63;
+}
+
+
+static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
+                         VisualID *defaultVisp,
+                         int ndepth, DepthPtr pdepth,
+                         int rootDepth)
+{
+    int numRGBconfigs;
+    int numCIconfigs;
+    int numVisuals = *nvisualp;
+    int numNewVisuals;
+    int numNewConfigs;
+    VisualPtr pVisual = *visualp;
+    VisualPtr pVisualNew = NULL;
+    VisualID *orig_vid = NULL;
+    __GLXconfig *modes;
+    __GLXvisualConfig *pNewVisualConfigs = NULL;
+    void **glXVisualPriv;
+    void **pNewVisualPriv;
+    int found_default;
+    int i, j, k;
+
+    GLAQUA_DEBUG_MSG("init_visuals\n");
+
+    if (numConfigs > 0)
+        numNewConfigs = numConfigs;
+    else
+        numNewConfigs = NUM_FALLBACK_CONFIGS;
+
+    /* Alloc space for the list of new GLX visuals */
+    pNewVisualConfigs = (__GLXvisualConfig *)
+                     malloc(numNewConfigs * sizeof(__GLXvisualConfig));
+    if (!pNewVisualConfigs) {
+        return FALSE;
+    }
+
+    /* Alloc space for the list of new GLX visual privates */
+    pNewVisualPriv = (void **) malloc(numNewConfigs * sizeof(void *));
+    if (!pNewVisualPriv) {
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /*
+    ** If SetVisualConfigs was not called, then use default GLX
+    ** visual configs.
+    */
+    if (numConfigs == 0) {
+        memcpy(pNewVisualConfigs, FallbackConfigs,
+               NUM_FALLBACK_CONFIGS * sizeof(__GLXvisualConfig));
+        memset(pNewVisualPriv, 0, NUM_FALLBACK_CONFIGS * sizeof(void *));
+    }
+    else {
+        /* copy driver's visual config info */
+        for (i = 0; i < numConfigs; i++) {
+            pNewVisualConfigs[i] = visualConfigs[i];
+            pNewVisualPriv[i] = visualPrivates[i];
+        }
+    }
+
+    /* Count the number of RGB and CI visual configs */
+    numRGBconfigs = 0;
+    numCIconfigs = 0;
+    for (i = 0; i < numNewConfigs; i++) {
+        if (pNewVisualConfigs[i].rgba)
+            numRGBconfigs++;
+        else
+            numCIconfigs++;
+    }
+
+    /* Count the total number of visuals to compute */
+    numNewVisuals = 0;
+    for (i = 0; i < numVisuals; i++) {
+        int count;
+
+        count = ((pVisual[i].class == TrueColor ||
+                  pVisual[i].class == DirectColor)
+                ? numRGBconfigs : numCIconfigs);
+        if (count == 0)
+            count = 1;          /* preserve the existing visual */
+
+        numNewVisuals += count;
+    }
+
+    /* Reset variables for use with the next screen/driver's visual configs */
+    visualConfigs = NULL;
+    numConfigs = 0;
+
+    /* Alloc temp space for the list of orig VisualIDs for each new visual */
+    orig_vid = (VisualID *)malloc(numNewVisuals * sizeof(VisualID));
+    if (!orig_vid) {
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /* Alloc space for the list of glXVisuals */
+    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLXconfig));
+    if (modes == NULL) {
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /* Alloc space for the list of glXVisualPrivates */
+    glXVisualPriv = (void **)malloc(numNewVisuals * sizeof(void *));
+    if (!glXVisualPriv) {
+        _gl_context_modes_destroy( modes );
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /* Alloc space for the new list of the X server's visuals */
+    pVisualNew = (VisualPtr)malloc(numNewVisuals * sizeof(VisualRec));
+    if (!pVisualNew) {
+        free(glXVisualPriv);
+        _gl_context_modes_destroy( modes );
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /* Initialize the new visuals */
+    found_default = FALSE;
+    glAquaScreens[screenInfo.numScreens-1].modes = modes;
+    for (i = j = 0; i < numVisuals; i++) {
+        int is_rgb = (pVisual[i].class == TrueColor ||
+                      pVisual[i].class == DirectColor);
+
+        if (!is_rgb)
+        {
+            /* We don't support non-rgb visuals for GL. But we don't
+               want to remove them either, so just pass them through
+               with null glX configs */
+
+            pVisualNew[j] = pVisual[i];
+            pVisualNew[j].vid = FakeClientID(0);
+
+            /* Check for the default visual */
+            if (!found_default && pVisual[i].vid == *defaultVisp) {
+                *defaultVisp = pVisualNew[j].vid;
+                found_default = TRUE;
+            }
+
+            /* Save the old VisualID */
+            orig_vid[j] = pVisual[i].vid;
+
+            /* Initialize the glXVisual */
+            _gl_copy_visual_to_context_mode( modes, & NullConfig );
+            modes->visualID = pVisualNew[j].vid;
+
+            j++;
+
+            continue;
+        }
+
+        for (k = 0; k < numNewConfigs; k++) {
+            if (pNewVisualConfigs[k].rgba != is_rgb)
+                continue;
+
+            assert( modes != NULL );
+
+            /* Initialize the new visual */
+            pVisualNew[j] = pVisual[i];
+            pVisualNew[j].vid = FakeClientID(0);
+
+            /* Check for the default visual */
+            if (!found_default && pVisual[i].vid == *defaultVisp) {
+                *defaultVisp = pVisualNew[j].vid;
+                found_default = TRUE;
+            }
+
+            /* Save the old VisualID */
+            orig_vid[j] = pVisual[i].vid;
+
+            /* Initialize the glXVisual */
+            _gl_copy_visual_to_context_mode( modes, & pNewVisualConfigs[k] );
+            modes->visualID = pVisualNew[j].vid;
+
+            /*
+             * If the class is -1, then assume the X visual information
+             * is identical to what GLX needs, and take them from the X
+             * visual.  NOTE: if class != -1, then all other fields MUST
+             * be initialized.
+             */
+            if (modes->visualType == GLX_NONE) {
+                modes->visualType = _gl_convert_from_x_visual_type( pVisual[i].class );
+                modes->redBits    = count_bits(pVisual[i].redMask);
+                modes->greenBits  = count_bits(pVisual[i].greenMask);
+                modes->blueBits   = count_bits(pVisual[i].blueMask);
+                modes->alphaBits  = modes->alphaBits;
+                modes->redMask    = pVisual[i].redMask;
+                modes->greenMask  = pVisual[i].greenMask;
+                modes->blueMask   = pVisual[i].blueMask;
+                modes->alphaMask  = modes->alphaMask;
+                modes->rgbBits = (is_rgb)
+                    ? (modes->redBits + modes->greenBits +
+                       modes->blueBits + modes->alphaBits)
+                    : rootDepth;
+            }
+
+            /* Save the device-dependent private for this visual */
+            glXVisualPriv[j] = pNewVisualPriv[k];
+
+            j++;
+            modes = modes->next;
+        }
+    }
+
+    assert(j <= numNewVisuals);
+
+    /* Save the GLX visuals in the screen structure */
+    glAquaScreens[screenInfo.numScreens-1].num_vis = numNewVisuals;
+    //    glAquaScreens[screenInfo.numScreens-1].priv = glXVisualPriv;
+
+    /* set up depth's VisualIDs */
+    for (i = 0; i < ndepth; i++) {
+        int numVids = 0;
+        VisualID *pVids = NULL;
+        int k, n = 0;
+
+        /* Count the new number of VisualIDs at this depth */
+        for (j = 0; j < pdepth[i].numVids; j++)
+            for (k = 0; k < numNewVisuals; k++)
+            if (pdepth[i].vids[j] == orig_vid[k])
+                numVids++;
+
+        /* Allocate a new list of VisualIDs for this depth */
+        pVids = (VisualID *)malloc(numVids * sizeof(VisualID));
+
+        /* Initialize the new list of VisualIDs for this depth */
+        for (j = 0; j < pdepth[i].numVids; j++)
+            for (k = 0; k < numNewVisuals; k++)
+            if (pdepth[i].vids[j] == orig_vid[k])
+                pVids[n++] = pVisualNew[k].vid;
+
+        /* Update this depth's list of VisualIDs */
+        free(pdepth[i].vids);
+        pdepth[i].vids = pVids;
+        pdepth[i].numVids = numVids;
+    }
+
+    /* Update the X server's visuals */
+    *nvisualp = numNewVisuals;
+    *visualp = pVisualNew;
+
+    /* Free the old list of the X server's visuals */
+    free(pVisual);
+
+    /* Clean up temporary allocations */
+    free(orig_vid);
+    free(pNewVisualPriv);
+    free(pNewVisualConfigs);
+
+    /* Free the private list created by DDX HW driver */
+    if (visualPrivates)
+        free(visualPrivates);
+    visualPrivates = NULL;
+
+    return TRUE;
+}
+
+Bool enable_stereo = FALSE;
+/* based on code in i830_dri.c
+   This ends calling glAquaSetVisualConfigs to set the static
+   numconfigs, etc. */
+// see also glxglcore.c -- bhb
+static void
+glAquaInitVisualConfigs(void)
+{
+    int                 lclNumConfigs     = 0;
+    __GLXvisualConfig  *lclVisualConfigs  = NULL;
+    void              **lclVisualPrivates = NULL;
+
+    int stereo, depth, aux, buffers, stencil, accum;
+    int i = 0;
+
+    GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs ");
+        
+    /* count num configs:
+        2 stereo (on, off) (optional)
+        2 Z buffer (0, 24 bit)
+        2 AUX buffer (0, 2)
+        2 buffers (single, double)
+        2 stencil (0, 8 bit)
+        2 accum (0, 64 bit)
+        = 64 configs with stereo, or 32 without */
+
+    if (enable_stereo) lclNumConfigs = 2 * 2 * 2 * 2 * 2 * 2; /* 64 */
+    else               lclNumConfigs = 2 * 2 * 2 * 2 * 2; /* 32 */
+
+    /* alloc */
+    lclVisualConfigs = xcalloc(sizeof(__GLXvisualConfig), lclNumConfigs);
+    lclVisualPrivates = xcalloc(sizeof(void *), lclNumConfigs);
+
+    /* fill in configs */
+    if (NULL != lclVisualConfigs) {
+        i = 0; /* current buffer */
+        for (stereo = 0; stereo < (enable_stereo ? 2 : 1); stereo++) {
+	  for (depth = 0; depth < 2; depth++) {
+            for (aux = 0; aux < 2; aux++) {
+	      for (buffers = 0; buffers < 2; buffers++) {
+		for (stencil = 0; stencil < 2; stencil++) {
+		  for (accum = 0; accum < 2; accum++) {
+		    lclVisualConfigs[i].vid = -1;
+		    lclVisualConfigs[i].class = -1;
+		    lclVisualConfigs[i].rgba = TRUE;
+		    lclVisualConfigs[i].redSize = -1;
+		    lclVisualConfigs[i].greenSize = -1;
+		    lclVisualConfigs[i].blueSize = -1;
+		    lclVisualConfigs[i].redMask = -1;
+		    lclVisualConfigs[i].greenMask = -1;
+		    lclVisualConfigs[i].blueMask = -1;
+		    lclVisualConfigs[i].alphaMask = 0;
+		    if (accum) {
+		      lclVisualConfigs[i].accumRedSize = 16;
+		      lclVisualConfigs[i].accumGreenSize = 16;
+		      lclVisualConfigs[i].accumBlueSize = 16;
+		      lclVisualConfigs[i].accumAlphaSize = 16;
+		    } else {
+		      lclVisualConfigs[i].accumRedSize = 0;
+		      lclVisualConfigs[i].accumGreenSize = 0;
+		      lclVisualConfigs[i].accumBlueSize = 0;
+		      lclVisualConfigs[i].accumAlphaSize = 0;
+		    }
+		    lclVisualConfigs[i].doubleBuffer = buffers ? TRUE : FALSE;
+		    lclVisualConfigs[i].stereo = stereo ? TRUE : FALSE;
+		    lclVisualConfigs[i].bufferSize = -1;
+		    
+		    lclVisualConfigs[i].depthSize = depth? 24 : 0;
+		    lclVisualConfigs[i].stencilSize = stencil ? 8 : 0;
+		    lclVisualConfigs[i].auxBuffers = aux ? 2 : 0;
+		    lclVisualConfigs[i].level = 0;
+		    lclVisualConfigs[i].visualRating = GLX_NONE_EXT;
+		    lclVisualConfigs[i].transparentPixel = 0;
+		    lclVisualConfigs[i].transparentRed = 0;
+		    lclVisualConfigs[i].transparentGreen = 0;
+		    lclVisualConfigs[i].transparentBlue = 0;
+		    lclVisualConfigs[i].transparentAlpha = 0;
+		    lclVisualConfigs[i].transparentIndex = 0;
+		    i++;
+		  }
+		}
+	      }
+            }
+	  }
+	}
+    }
+    if (i != lclNumConfigs)
+        GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs failed to alloc visual configs");
+
+    GlxSetVisualConfigs(lclNumConfigs, lclVisualConfigs, lclVisualPrivates);
+}
+
+
+static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
+                                   void **privates)
+{
+    GLAQUA_DEBUG_MSG("glAquaSetVisualConfigs\n");
+
+    numConfigs = nconfigs;
+    visualConfigs = configs;
+    visualPrivates = privates;
+}
+
+static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
+                              int *nvisualp, int *ndepthp,
+                              int *rootDepthp, VisualID *defaultVisp,
+                              unsigned long sizes, int bitsPerRGB)
+{
+    GLAQUA_DEBUG_MSG("glAquaInitVisuals\n");
+    
+    if (numConfigs == 0) /* if no configs */
+        glAquaInitVisualConfigs(); /* ensure the visual configs are setup */
+
+    /*
+     * setup the visuals supported by this particular screen.
+     */
+    return init_visuals(nvisualp, visualp, defaultVisp,
+                        *ndepthp, *depthp, *rootDepthp);
+}
+
+#if 0
+static void fixup_visuals(int screen)
+{
+    ScreenPtr pScreen = screenInfo.screens[screen];
+    glAquaScreenRec *pScr = &glAquaScreens[screen];
+    int j;
+    __GLcontextModes *modes;
+
+    GLAQUA_DEBUG_MSG("fixup_visuals\n");
+
+    for ( modes = pScr->modes ; modes != NULL ; modes = modes->next ) {
+        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
+        const int nplanes = (modes->rgbBits - modes->alphaBits);
+        const VisualPtr pVis = pScreen->visuals;
+
+        /* Find a visual that matches the GLX visual's class and size */
+        for (j = 0; j < pScreen->numVisuals; j++) {
+            if (pVis[j].class == vis_class &&
+            pVis[j].nplanes == nplanes) {
+
+            /* Fixup the masks */
+            modes->redMask   = pVis[j].redMask;
+            modes->greenMask = pVis[j].greenMask;
+            modes->blueMask  = pVis[j].blueMask;
+
+            /* Recalc the sizes */
+            modes->redBits   = count_bits(modes->redMask);
+            modes->greenBits = count_bits(modes->greenMask);
+            modes->blueBits  = count_bits(modes->blueMask);
+            }
+        }
+    }
+}
+#endif
+static void __glXAquaScreenDestroy(__GLXscreen *screen) {
+
+	GLAQUA_DEBUG_MSG("glXAquaScreenDestroy(%p)\n", screen);
+  __glXScreenDestroy(screen);
+
+  free(screen);
+}
+
+static void init_screen_visuals(__GLXAquaScreen *screen) {
+  ScreenPtr pScreen = screen->base.pScreen;
+  
+  __GLXconfig *modes;
+  int *used;
+  int i, j;
+  
+    GLAQUA_DEBUG_MSG("init_screen_visuals\n");
+
+    /* FIXME: Change 'used' to be a array of bits (rather than of ints),
+     * FIXME: create a stack array of 8 or 16 bytes.  If 'numVisuals' is less
+     * FIXME: than 64 or 128 the stack array can be used instead of calling
+     * FIXME: malloc / free.  If nothing else, convert 'used' to
+     * FIXME: array of bytes instead of ints!
+     */
+    used = (int *)malloc(pScreen->numVisuals * sizeof(int));
+    memset(used, 0, pScreen->numVisuals * sizeof(int));
+
+    i = 0;
+    for ( modes = screen -> base.visuals
+          ; modes != NULL
+          ; modes = modes->next ) {
+        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
+        const int nplanes = (modes->rgbBits - modes->alphaBits);
+        const VisualPtr pVis = pScreen->visuals;
+
+        for (j = 0; j < pScreen->numVisuals; j++) {
+            if (pVis[j].class     == vis_class &&
+                pVis[j].nplanes   == nplanes &&
+                pVis[j].redMask   == modes->redMask &&
+                pVis[j].greenMask == modes->greenMask &&
+                pVis[j].blueMask  == modes->blueMask &&
+                !used[j]) {
+
+                    /* set the VisualID */
+                    modes->visualID = pVis[j].vid;
+
+                    /* Mark this visual used */
+                    used[j] = 1;
+                    break;
+            }
+        }
+        if ( j == pScreen->numVisuals ) {
+            ErrorF("No matching visual for __GLcontextMode with "
+                   "visual class = %d (%d), nplanes = %u\n",
+                   vis_class, 
+                   (int)modes->visualType,
+                   (unsigned int)(modes->rgbBits - modes->alphaBits) );
+        }
+        else if ( modes->visualID == -1 ) {
+            FatalError( "Matching visual found, but visualID still -1!\n" );
+        }
+
+        i++;
+    }
+
+    free(used);
+}
+
+static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen) {
+  __GLXAquaScreen *screen;
+  GLAQUA_DEBUG_MSG("glXAquaScreenProbe\n");
+  if (screen == NULL) return NULL;
+
+  screen = malloc(sizeof *screen);
+
+  __glXScreenInit(&screen->base, pScreen);
+
+  screen->base.destroy        = __glXAquaScreenDestroy;
+  screen->base.createContext  = __glXAquaScreenCreateContext;
+  screen->base.createDrawable = __glXAquaScreenCreateDrawable;
+  screen->base.pScreen       = pScreen;
+
+  init_screen_visuals(screen);
+
+  return &screen->base;
+}
+
+static void __glXAquaDrawableDestroy(__GLXdrawable *base) {
+    GLAQUA_DEBUG_MSG("glAquaDestroyDrawablePrivate\n");
+
+    /* It doesn't work to call DRIDestroySurface here, the drawable's
+       already gone.. But dri.c notices the window destruction and
+       frees the surface itself. */
+
+    free(base);
+}
+
+static __GLXdrawable *
+__glXAquaScreenCreateDrawable(__GLXscreen *screen,
+			      DrawablePtr pDraw,
+			      XID drawId,
+			      __GLXconfig *modes) {
+  __GLXAquaDrawable *glxPriv;
+
+  GLAQUA_DEBUG_MSG("glAquaScreenCreateDrawable(%p,%p,%d,%p)\n", context, pDraw, drawId, modes);
+
+  glxPriv = xalloc(sizeof *glxPriv);
+  if (glxPriv == NULL) return NULL;
+
+  memset(glxPriv, 0, sizeof *glxPriv);
+
+  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, GLX_DRAWABLE_PIXMAP /*?*/, drawId, modes)) {
+    xfree(glxPriv);
+    return NULL;
+  }
+
+  glxPriv->base.destroy       = __glXAquaDrawableDestroy;
+  glxPriv->base.resize        = __glXAquaDrawableResize;
+  glxPriv->base.swapBuffers   = __glXAquaDrawableSwapBuffers;
+  //  glxPriv->base.copySubBuffer = __glXAquaDrawableCopySubBuffer;
+
+  return &glxPriv->base;
+}
+
+static void glAquaResetExtension(void)
+{
+    GLAQUA_DEBUG_MSG("glAquaResetExtension\n");
+    CGLSetOption(kCGLGOResetLibrary, GL_TRUE);
+}
+
+// Extra goodies for glx
+
+GLuint __glFloorLog2(GLuint val)
+{
+    int c = 0;
+
+    while (val > 1) {
+        c++;
+        val >>= 1;
+    }
+    return c;
+}
+
+void warn_func(void * p1, char *format, ...) {
+  va_list v;
+  va_start(v, format);
+  vfprintf(stderr, format, v);
+  va_end(v);
+}
+
+static void setup_dispatch_table(void) {
+  struct _glapi_table *disp=_glapi_get_dispatch();
+  _glapi_set_warning_func((_glapi_warning_func)warn_func);
+  _glapi_noop_enable_warnings(TRUE);
+
+  SET_Accum(disp, glAccum);
+  SET_ActiveStencilFaceEXT(disp, glActiveStencilFaceEXT);
+  SET_ActiveTextureARB(disp, glActiveTextureARB);
+//SET_AlphaFragmentOp1ATI(disp, glAlphaFragmentOp1EXT);   // <-- EXT -> ATI
+//SET_AlphaFragmentOp2ATI(disp, glAlphaFragmentOp2EXT);
+//SET_AlphaFragmentOp3ATI(disp, glAlphaFragmentOp3EXT);
+  SET_AlphaFunc(disp, glAlphaFunc);
+//SET_AreProgramsResidentNV(disp, glAreProgramsResidentNV);
+  SET_AreTexturesResident(disp, glAreTexturesResident); 
+  SET_ArrayElement(disp, glArrayElement);
+  SET_AttachObjectARB(disp, glAttachObjectARB);
+  SET_Begin(disp, glBegin);
+//SET_BeginFragmentShaderATI(disp, glBeginFragmentShaderEXT);   // <-- EXT -> ATI
+  SET_BeginQueryARB(disp, glBeginQueryARB);
+  SET_BindAttribLocationARB(disp, glBindAttribLocationARB);
+  SET_BindBufferARB(disp, glBindBufferARB);
+//SET_BindFragmentShaderATI(disp, glBindFragmentShaderEXT);     // <-- EXT -> ATI
+  SET_BindFramebufferEXT(disp, glBindFramebufferEXT);
+//SET_BindProgramNV(disp, glBindProgramNV);
+  SET_BindRenderbufferEXT(disp, glBindRenderbufferEXT);
+  SET_BindTexture(disp, glBindTexture);
+  SET_Bitmap(disp, glBitmap);
+  SET_BlendColor(disp, glBlendColor);
+  SET_BlendEquation(disp, glBlendEquation);
+  SET_BlendEquationSeparateEXT(disp, glBlendEquationSeparateEXT);
+  SET_BlendFunc(disp, glBlendFunc);
+  SET_BlendFuncSeparateEXT(disp, glBlendFuncSeparateEXT);
+  SET_BlitFramebufferEXT(disp, glBlitFramebufferEXT);
+  SET_BufferDataARB(disp, glBufferDataARB);
+  SET_BufferSubDataARB(disp, glBufferSubDataARB);
+  SET_CallList(disp, glCallList);
+  SET_CallLists(disp, glCallLists);
+  SET_CheckFramebufferStatusEXT(disp, glCheckFramebufferStatusEXT);
+  SET_Clear(disp, glClear);
+  SET_ClearAccum(disp, glClearAccum);
+  SET_ClearColor(disp, glClearColor);
+  SET_ClearDepth(disp, glClearDepth);
+  SET_ClearIndex(disp, glClearIndex);
+  SET_ClearStencil(disp, glClearStencil);
+  SET_ClientActiveTextureARB(disp, glClientActiveTextureARB);
+  SET_ClipPlane(disp, glClipPlane);
+  SET_Color3b(disp, glColor3b);
+  SET_Color3bv(disp, glColor3bv);
+  SET_Color3d(disp, glColor3d);
+  SET_Color3dv(disp, glColor3dv);
+  SET_Color3f(disp, glColor3f);
+  SET_Color3fv(disp, glColor3fv);
+  SET_Color3i(disp, glColor3i);
+  SET_Color3iv(disp, glColor3iv);
+  SET_Color3s(disp, glColor3s);
+  SET_Color3sv(disp, glColor3sv);
+  SET_Color3ub(disp, glColor3ub);
+  SET_Color3ubv(disp, glColor3ubv);
+  SET_Color3ui(disp, glColor3ui);
+  SET_Color3uiv(disp, glColor3uiv);
+  SET_Color3us(disp, glColor3us);
+  SET_Color3usv(disp, glColor3usv);
+  SET_Color4b(disp, glColor4b);
+  SET_Color4bv(disp, glColor4bv);
+  SET_Color4d(disp, glColor4d);
+  SET_Color4dv(disp, glColor4dv);
+  SET_Color4f(disp, glColor4f);
+  SET_Color4fv(disp, glColor4fv);
+  SET_Color4i(disp, glColor4i);
+  SET_Color4iv(disp, glColor4iv);
+  SET_Color4s(disp, glColor4s);
+  SET_Color4sv(disp, glColor4sv);
+  SET_Color4ub(disp, glColor4ub);
+  SET_Color4ubv(disp, glColor4ubv);
+  SET_Color4ui(disp, glColor4ui);
+  SET_Color4uiv(disp, glColor4uiv);
+  SET_Color4us(disp, glColor4us);
+  SET_Color4usv(disp, glColor4usv);
+//SET_ColorFragmentOp1ATI(disp, glColorFragmentOp1EXT);    // <-- EXT -> ATI
+//SET_ColorFragmentOp2ATI(disp, glColorFragmentOp2EXT);
+//SET_ColorFragmentOp3ATI(disp, glColorFragmentOp3EXT);
+  SET_ColorMask(disp, glColorMask);
+  SET_ColorMaterial(disp, glColorMaterial);
+  SET_ColorPointer(disp, glColorPointer);
+//SET_ColorPointerEXT(disp, glColorPointerEXT);
+  SET_ColorSubTable(disp, glColorSubTable);
+  SET_ColorTable(disp, glColorTable);
+  SET_ColorTableParameterfv(disp, glColorTableParameterfv);
+  SET_ColorTableParameteriv(disp, glColorTableParameteriv);
+  SET_CombinerInputNV(disp, glCombinerInputNV);
+  SET_CombinerOutputNV(disp, glCombinerOutputNV);
+  SET_CombinerParameterfNV(disp, glCombinerParameterfNV);
+  SET_CombinerParameterfvNV(disp, glCombinerParameterfvNV);
+  SET_CombinerParameteriNV(disp, glCombinerParameteriNV);
+  SET_CombinerParameterivNV(disp, glCombinerParameterivNV);
+  SET_CompileShaderARB(disp, glCompileShaderARB);
+  SET_CompressedTexImage1DARB(disp, glCompressedTexImage1DARB);
+  SET_CompressedTexImage2DARB(disp, glCompressedTexImage2DARB);
+  SET_CompressedTexImage3DARB(disp, glCompressedTexImage3DARB);
+  SET_CompressedTexSubImage1DARB(disp, glCompressedTexSubImage1DARB);
+  SET_CompressedTexSubImage2DARB(disp, glCompressedTexSubImage2DARB);
+  SET_CompressedTexSubImage3DARB(disp, glCompressedTexSubImage3DARB);
+  SET_ConvolutionFilter1D(disp, glConvolutionFilter1D);
+  SET_ConvolutionFilter2D(disp, glConvolutionFilter2D);
+  SET_ConvolutionParameterf(disp, glConvolutionParameterf);
+  SET_ConvolutionParameterfv(disp, glConvolutionParameterfv);
+  SET_ConvolutionParameteri(disp, glConvolutionParameteri);
+  SET_ConvolutionParameteriv(disp, glConvolutionParameteriv);
+  SET_CopyColorSubTable(disp, glCopyColorSubTable);
+  SET_CopyColorTable(disp, glCopyColorTable);
+  SET_CopyConvolutionFilter1D(disp, glCopyConvolutionFilter1D);
+  SET_CopyConvolutionFilter2D(disp, glCopyConvolutionFilter2D);
+  SET_CopyPixels(disp, glCopyPixels);
+  SET_CopyTexImage1D(disp, glCopyTexImage1D);
+  SET_CopyTexImage2D(disp, glCopyTexImage2D);
+  SET_CopyTexSubImage1D(disp, glCopyTexSubImage1D);
+  SET_CopyTexSubImage2D(disp, glCopyTexSubImage2D);
+  SET_CopyTexSubImage3D(disp, glCopyTexSubImage3D);
+  SET_CreateProgramObjectARB(disp, glCreateProgramObjectARB);
+  SET_CreateShaderObjectARB(disp, glCreateShaderObjectARB);
+  SET_CullFace(disp, glCullFace);
+//SET_CullParameterdvEXT(disp, glCullParameterdvEXT);
+//SET_CullParameterfvEXT(disp, glCullParameterfvEXT);
+  SET_DeleteBuffersARB(disp, glDeleteBuffersARB);
+  SET_DeleteFencesNV(disp, glDeleteFencesAPPLE);
+//SET_DeleteFragmentShaderATI(disp, glDeleteFragmentShaderEXT);      // <-- EXT -> ATI
+  SET_DeleteFramebuffersEXT(disp, glDeleteFramebuffersEXT);
+  SET_DeleteLists(disp, glDeleteLists);
+  SET_DeleteObjectARB(disp, glDeleteObjectARB);
+//SET_DeleteProgramsNV(disp, glDeleteProgramsNV);
+  SET_DeleteQueriesARB(disp, glDeleteQueriesARB);
+  SET_DeleteRenderbuffersEXT(disp, glDeleteRenderbuffersEXT);
+  SET_DeleteTextures(disp, glDeleteTextures);
+  SET_DepthBoundsEXT(disp, glDepthBoundsEXT);
+  SET_DepthFunc(disp, glDepthFunc);
+  SET_DepthMask(disp, glDepthMask);
+  SET_DepthRange(disp, glDepthRange);
+  SET_DetachObjectARB(disp, glDetachObjectARB);
+  SET_Disable(disp, glDisable);
+  SET_DisableClientState(disp, glDisableClientState);
+  SET_DisableVertexAttribArrayARB(disp, glDisableVertexAttribArrayARB);
+  SET_DrawArrays(disp, glDrawArrays);
+  SET_DrawBuffer(disp, glDrawBuffer);
+  SET_DrawBuffersARB(disp, glDrawBuffersARB);
+  SET_DrawElements(disp, glDrawElements);
+  SET_DrawPixels(disp, glDrawPixels);
+  SET_DrawRangeElements(disp, glDrawRangeElements);
+  SET_EdgeFlag(disp, glEdgeFlag);
+  SET_EdgeFlagPointer(disp, glEdgeFlagPointer);
+//SET_EdgeFlagPointerEXT(disp, glEdgeFlagPointerEXT);
+  SET_EdgeFlagv(disp, glEdgeFlagv);
+  SET_Enable(disp, glEnable);
+  SET_EnableClientState(disp, glEnableClientState);
+  SET_EnableVertexAttribArrayARB(disp, glEnableVertexAttribArrayARB);
+  SET_End(disp, glEnd);
+//SET_EndFragmentShaderATI(disp, glEndFragmentShaderEXT);        // <-- EXT -> ATI
+  SET_EndList(disp, glEndList);
+  SET_EndQueryARB(disp, glEndQueryARB);
+  SET_EvalCoord1d(disp, glEvalCoord1d);
+  SET_EvalCoord1dv(disp, glEvalCoord1dv);
+  SET_EvalCoord1f(disp, glEvalCoord1f);
+  SET_EvalCoord1fv(disp, glEvalCoord1fv);
+  SET_EvalCoord2d(disp, glEvalCoord2d);
+  SET_EvalCoord2dv(disp, glEvalCoord2dv);
+  SET_EvalCoord2f(disp, glEvalCoord2f);
+  SET_EvalCoord2fv(disp, glEvalCoord2fv);
+  SET_EvalMesh1(disp, glEvalMesh1);
+  SET_EvalMesh2(disp, glEvalMesh2);
+  SET_EvalPoint1(disp, glEvalPoint1);
+  SET_EvalPoint2(disp, glEvalPoint2);
+//SET_ExecuteProgramNV(disp, glExecuteProgramNV);
+  SET_FeedbackBuffer(disp, glFeedbackBuffer);
+  SET_FinalCombinerInputNV(disp, glFinalCombinerInputNV);
+  SET_Finish(disp, glFinish);
+  SET_FinishFenceNV(disp, glFinishFenceAPPLE);       // <-- APPLE -> NV
+  SET_Flush(disp, glFlush);
+//SET_FlushVertexArrayRangeNV(disp, glFlushVertexArrayRangeNV);
+  SET_FogCoordPointerEXT(disp, glFogCoordPointerEXT);
+  SET_FogCoorddEXT(disp, glFogCoorddEXT);
+  SET_FogCoorddvEXT(disp, glFogCoorddvEXT);
+  SET_FogCoordfEXT(disp, glFogCoordfEXT);
+  SET_FogCoordfvEXT(disp, glFogCoordfvEXT);
+  SET_Fogf(disp, glFogf);
+  SET_Fogfv(disp, glFogfv);
+  SET_Fogi(disp, glFogi);
+  SET_Fogiv(disp, glFogiv);
+  SET_FramebufferRenderbufferEXT(disp, glFramebufferRenderbufferEXT);
+  SET_FramebufferTexture1DEXT(disp, glFramebufferTexture1DEXT);
+  SET_FramebufferTexture2DEXT(disp, glFramebufferTexture2DEXT);
+  SET_FramebufferTexture3DEXT(disp, glFramebufferTexture3DEXT);
+  SET_FrontFace(disp, glFrontFace);
+  SET_Frustum(disp, glFrustum);
+  SET_GenBuffersARB(disp, glGenBuffersARB);
+  SET_GenFencesNV(disp, glGenFencesAPPLE);            // <-- APPLE -> NV
+//SET_GenFragmentShadersATI(disp, glGenFragmentShadersEXT);         // <-- EXT -> ATI
+  SET_GenFramebuffersEXT(disp, glGenFramebuffersEXT);
+  SET_GenLists(disp, glGenLists);
+//SET_GenProgramsNV(disp, glGenProgramsNV);
+  SET_GenQueriesARB(disp, glGenQueriesARB);
+  SET_GenRenderbuffersEXT(disp, glGenRenderbuffersEXT);
+  SET_GenTextures(disp, glGenTextures);
+  SET_GenerateMipmapEXT(disp, glGenerateMipmapEXT);
+  SET_GetActiveAttribARB(disp, glGetActiveAttribARB);
+  SET_GetActiveUniformARB(disp, glGetActiveUniformARB);
+  SET_GetAttachedObjectsARB(disp, glGetAttachedObjectsARB);
+  SET_GetAttribLocationARB(disp, glGetAttribLocationARB);
+  SET_GetBooleanv(disp, glGetBooleanv);
+  SET_GetBufferParameterivARB(disp, glGetBufferParameterivARB);
+  SET_GetBufferPointervARB(disp, glGetBufferPointervARB);
+  SET_GetBufferSubDataARB(disp, glGetBufferSubDataARB);
+  SET_GetClipPlane(disp, glGetClipPlane);
+  SET_GetColorTable(disp, glGetColorTable);
+  SET_GetColorTableParameterfv(disp, glGetColorTableParameterfv);
+  SET_GetColorTableParameteriv(disp, glGetColorTableParameteriv);
+  SET_GetCombinerInputParameterfvNV(disp, glGetCombinerInputParameterfvNV);
+  SET_GetCombinerInputParameterivNV(disp, glGetCombinerInputParameterivNV);
+  SET_GetCombinerOutputParameterfvNV(disp, glGetCombinerOutputParameterfvNV);
+  SET_GetCombinerOutputParameterivNV(disp, glGetCombinerOutputParameterivNV);
+  SET_GetCompressedTexImageARB(disp, glGetCompressedTexImageARB);
+  SET_GetConvolutionFilter(disp, glGetConvolutionFilter);
+  SET_GetConvolutionParameterfv(disp, glGetConvolutionParameterfv);
+  SET_GetConvolutionParameteriv(disp, glGetConvolutionParameteriv);
+  SET_GetDoublev(disp, glGetDoublev);
+  SET_GetError(disp, glGetError);
+//SET_GetFenceivNV(disp, glGetFenceivNV);
+  SET_GetFinalCombinerInputParameterfvNV(disp, glGetFinalCombinerInputParameterfvNV);
+  SET_GetFinalCombinerInputParameterivNV(disp, glGetFinalCombinerInputParameterivNV);
+  SET_GetFloatv(disp, glGetFloatv);
+  SET_GetFramebufferAttachmentParameterivEXT(disp, glGetFramebufferAttachmentParameterivEXT);
+  SET_GetHandleARB(disp, glGetHandleARB);
+  SET_GetHistogram(disp, glGetHistogram);
+  SET_GetHistogramParameterfv(disp, glGetHistogramParameterfv);
+  SET_GetHistogramParameteriv(disp, glGetHistogramParameteriv);
+  SET_GetInfoLogARB(disp, glGetInfoLogARB);
+  SET_GetIntegerv(disp, glGetIntegerv);
+  SET_GetLightfv(disp, glGetLightfv);
+  SET_GetLightiv(disp, glGetLightiv);
+  SET_GetMapdv(disp, glGetMapdv);
+  SET_GetMapfv(disp, glGetMapfv);
+  SET_GetMapiv(disp, glGetMapiv);
+  SET_GetMaterialfv(disp, glGetMaterialfv);
+  SET_GetMaterialiv(disp, glGetMaterialiv);
+  SET_GetMinmax(disp, glGetMinmax);
+  SET_GetMinmaxParameterfv(disp, glGetMinmaxParameterfv);
+  SET_GetMinmaxParameteriv(disp, glGetMinmaxParameteriv);
+  SET_GetObjectParameterfvARB(disp, glGetObjectParameterfvARB);
+  SET_GetObjectParameterivARB(disp, glGetObjectParameterivARB);
+  SET_GetPixelMapfv(disp, glGetPixelMapfv);
+  SET_GetPixelMapuiv(disp, glGetPixelMapuiv);
+  SET_GetPixelMapusv(disp, glGetPixelMapusv);
+//SET_GetPixelTexGenParameterfvSGIS(disp, glGetPixelTexGenParameterfvSGIS);
+//SET_GetPixelTexGenParameterivSGIS(disp, glGetPixelTexGenParameterivSGIS);
+  SET_GetPointerv(disp, glGetPointerv);
+  SET_GetPolygonStipple(disp, glGetPolygonStipple);
+  SET_GetProgramEnvParameterdvARB(disp, glGetProgramEnvParameterdvARB);
+  SET_GetProgramEnvParameterfvARB(disp, glGetProgramEnvParameterfvARB);
+  SET_GetProgramLocalParameterdvARB(disp, glGetProgramLocalParameterdvARB);
+  SET_GetProgramLocalParameterfvARB(disp, glGetProgramLocalParameterfvARB);
+//SET_GetProgramNamedParameterdvNV(disp, glGetProgramNamedParameterdvNV);
+//SET_GetProgramNamedParameterfvNV(disp, glGetProgramNamedParameterfvNV);
+//SET_GetProgramParameterdvNV(disp, glGetProgramParameterdvNV);
+//SET_GetProgramParameterfvNV(disp, glGetProgramParameterfvNV);
+  SET_GetProgramStringARB(disp, glGetProgramStringARB);
+//SET_GetProgramStringNV(disp, glGetProgramStringNV);
+  SET_GetProgramivARB(disp, glGetProgramivARB);
+//SET_GetProgramivNV(disp, glGetProgramivNV);
+//SET_GetQueryObjecti64vEXT(disp, glGetQueryObjecti64vEXT);
+  SET_GetQueryObjectivARB(disp, glGetQueryObjectivARB);
+//SET_GetQueryObjectui64vEXT(disp, glGetQueryObjectui64vEXT);
+  SET_GetQueryObjectuivARB(disp, glGetQueryObjectuivARB);
+  SET_GetQueryivARB(disp, glGetQueryivARB);
+  SET_GetRenderbufferParameterivEXT(disp, glGetRenderbufferParameterivEXT);
+  SET_GetSeparableFilter(disp, glGetSeparableFilter);
+  SET_GetShaderSourceARB(disp, glGetShaderSourceARB);
+  SET_GetString(disp, glGetString);
+  SET_GetTexEnvfv(disp, glGetTexEnvfv);
+  SET_GetTexEnviv(disp, glGetTexEnviv);
+  SET_GetTexGendv(disp, glGetTexGendv);
+  SET_GetTexGenfv(disp, glGetTexGenfv);
+  SET_GetTexGeniv(disp, glGetTexGeniv);
+  SET_GetTexImage(disp, glGetTexImage);
+  SET_GetTexLevelParameterfv(disp, glGetTexLevelParameterfv);
+  SET_GetTexLevelParameteriv(disp, glGetTexLevelParameteriv);
+  SET_GetTexParameterfv(disp, glGetTexParameterfv);
+  SET_GetTexParameteriv(disp, glGetTexParameteriv);
+//SET_GetTrackMatrixivNV(disp, glGetTrackMatrixivNV);
+  SET_GetUniformLocationARB(disp, glGetUniformLocationARB);
+  SET_GetUniformfvARB(disp, glGetUniformfvARB);
+  SET_GetUniformivARB(disp, glGetUniformivARB);
+//SET_GetVertexAttribPointervNV(disp, glGetVertexAttribPointervNV);
+  SET_GetVertexAttribdvARB(disp, glGetVertexAttribdvARB);
+//SET_GetVertexAttribdvNV(disp, glGetVertexAttribdvNV);
+  SET_GetVertexAttribfvARB(disp, glGetVertexAttribfvARB);
+//SET_GetVertexAttribfvNV(disp, glGetVertexAttribfvNV);
+  SET_GetVertexAttribivARB(disp, glGetVertexAttribivARB);
+//SET_GetVertexAttribivNV(disp, glGetVertexAttribivNV);
+  SET_Hint(disp, glHint);
+  SET_Histogram(disp, glHistogram);
+  SET_IndexMask(disp, glIndexMask);
+  SET_IndexPointer(disp, glIndexPointer);
+//SET_IndexPointerEXT(disp, glIndexPointerEXT);
+  SET_Indexd(disp, glIndexd);
+  SET_Indexdv(disp, glIndexdv);
+  SET_Indexf(disp, glIndexf);
+  SET_Indexfv(disp, glIndexfv);
+  SET_Indexi(disp, glIndexi);
+  SET_Indexiv(disp, glIndexiv);
+  SET_Indexs(disp, glIndexs);
+  SET_Indexsv(disp, glIndexsv);
+  SET_Indexub(disp, glIndexub);
+  SET_Indexubv(disp, glIndexubv);
+  SET_InitNames(disp, glInitNames);
+  SET_InterleavedArrays(disp, glInterleavedArrays);
+  SET_IsBufferARB(disp, glIsBufferARB);
+  SET_IsEnabled(disp, glIsEnabled);
+  SET_IsFenceNV(disp, glIsFenceAPPLE);           // <-- APPLE -> NV
+  SET_IsFramebufferEXT(disp, glIsFramebufferEXT);
+  SET_IsList(disp, glIsList);
+//SET_IsProgramNV(disp, glIsProgramNV);
+  SET_IsQueryARB(disp, glIsQueryARB);
+  SET_IsRenderbufferEXT(disp, glIsRenderbufferEXT);
+  SET_IsTexture(disp, glIsTexture);
+  SET_LightModelf(disp, glLightModelf);
+  SET_LightModelfv(disp, glLightModelfv);
+  SET_LightModeli(disp, glLightModeli);
+  SET_LightModeliv(disp, glLightModeliv);
+  SET_Lightf(disp, glLightf);
+  SET_Lightfv(disp, glLightfv);
+  SET_Lighti(disp, glLighti);
+  SET_Lightiv(disp, glLightiv);
+  SET_LineStipple(disp, glLineStipple);
+  SET_LineWidth(disp, glLineWidth);
+  SET_LinkProgramARB(disp, glLinkProgramARB);
+  SET_ListBase(disp, glListBase);
+  SET_LoadIdentity(disp, glLoadIdentity);
+  SET_LoadMatrixd(disp, glLoadMatrixd);
+  SET_LoadMatrixf(disp, glLoadMatrixf);
+  SET_LoadName(disp, glLoadName);
+//SET_LoadProgramNV(disp, glLoadProgramNV);
+  SET_LoadTransposeMatrixdARB(disp, glLoadTransposeMatrixdARB);
+  SET_LoadTransposeMatrixfARB(disp, glLoadTransposeMatrixfARB);
+  SET_LockArraysEXT(disp, glLockArraysEXT);
+  SET_LogicOp(disp, glLogicOp);
+  SET_Map1d(disp, glMap1d);
+  SET_Map1f(disp, glMap1f);
+  SET_Map2d(disp, glMap2d);
+  SET_Map2f(disp, glMap2f);
+  SET_MapBufferARB(disp, glMapBufferARB);
+  SET_MapGrid1d(disp, glMapGrid1d);
+  SET_MapGrid1f(disp, glMapGrid1f);
+  SET_MapGrid2d(disp, glMapGrid2d);
+  SET_MapGrid2f(disp, glMapGrid2f);
+  SET_Materialf(disp, glMaterialf);
+  SET_Materialfv(disp, glMaterialfv);
+  SET_Materiali(disp, glMateriali);
+  SET_Materialiv(disp, glMaterialiv);
+  SET_MatrixMode(disp, glMatrixMode);
+  SET_Minmax(disp, glMinmax);
+  SET_MultMatrixd(disp, glMultMatrixd);
+  SET_MultMatrixf(disp, glMultMatrixf);
+  SET_MultTransposeMatrixdARB(disp, glMultTransposeMatrixdARB);
+  SET_MultTransposeMatrixfARB(disp, glMultTransposeMatrixfARB);
+  SET_MultiDrawArraysEXT(disp, glMultiDrawArraysEXT);
+  SET_MultiDrawElementsEXT(disp, glMultiDrawElementsEXT);
+//SET_MultiModeDrawArraysIBM(disp, glMultiModeDrawArraysIBM);
+//SET_MultiModeDrawElementsIBM(disp, glMultiModeDrawElementsIBM);
+  SET_MultiTexCoord1dARB(disp, glMultiTexCoord1dARB);
+  SET_MultiTexCoord1dvARB(disp, glMultiTexCoord1dvARB);
+  SET_MultiTexCoord1fARB(disp, glMultiTexCoord1fARB);
+  SET_MultiTexCoord1fvARB(disp, glMultiTexCoord1fvARB);
+  SET_MultiTexCoord1iARB(disp, glMultiTexCoord1iARB);
+  SET_MultiTexCoord1ivARB(disp, glMultiTexCoord1ivARB);
+  SET_MultiTexCoord1sARB(disp, glMultiTexCoord1sARB);
+  SET_MultiTexCoord1svARB(disp, glMultiTexCoord1svARB);
+  SET_MultiTexCoord2dARB(disp, glMultiTexCoord2dARB);
+  SET_MultiTexCoord2dvARB(disp, glMultiTexCoord2dvARB);
+  SET_MultiTexCoord2fARB(disp, glMultiTexCoord2fARB);
+  SET_MultiTexCoord2fvARB(disp, glMultiTexCoord2fvARB);
+  SET_MultiTexCoord2iARB(disp, glMultiTexCoord2iARB);
+  SET_MultiTexCoord2ivARB(disp, glMultiTexCoord2ivARB);
+  SET_MultiTexCoord2sARB(disp, glMultiTexCoord2sARB);
+  SET_MultiTexCoord2svARB(disp, glMultiTexCoord2svARB);
+  SET_MultiTexCoord3dARB(disp, glMultiTexCoord3dARB);
+  SET_MultiTexCoord3dvARB(disp, glMultiTexCoord3dvARB);
+  SET_MultiTexCoord3fARB(disp, glMultiTexCoord3fARB);
+  SET_MultiTexCoord3fvARB(disp, glMultiTexCoord3fvARB);
+  SET_MultiTexCoord3iARB(disp, glMultiTexCoord3iARB);
+  SET_MultiTexCoord3ivARB(disp, glMultiTexCoord3ivARB);
+  SET_MultiTexCoord3sARB(disp, glMultiTexCoord3sARB);
+  SET_MultiTexCoord3svARB(disp, glMultiTexCoord3svARB);
+  SET_MultiTexCoord4dARB(disp, glMultiTexCoord4dARB);
+  SET_MultiTexCoord4dvARB(disp, glMultiTexCoord4dvARB);
+  SET_MultiTexCoord4fARB(disp, glMultiTexCoord4fARB);
+  SET_MultiTexCoord4fvARB(disp, glMultiTexCoord4fvARB);
+  SET_MultiTexCoord4iARB(disp, glMultiTexCoord4iARB);
+  SET_MultiTexCoord4ivARB(disp, glMultiTexCoord4ivARB);
+  SET_MultiTexCoord4sARB(disp, glMultiTexCoord4sARB);
+  SET_MultiTexCoord4svARB(disp, glMultiTexCoord4svARB);
+  SET_NewList(disp, glNewList);
+  SET_Normal3b(disp, glNormal3b);
+  SET_Normal3bv(disp, glNormal3bv);
+  SET_Normal3d(disp, glNormal3d);
+  SET_Normal3dv(disp, glNormal3dv);
+  SET_Normal3f(disp, glNormal3f);
+  SET_Normal3fv(disp, glNormal3fv);
+  SET_Normal3i(disp, glNormal3i);
+  SET_Normal3iv(disp, glNormal3iv);
+  SET_Normal3s(disp, glNormal3s);
+  SET_Normal3sv(disp, glNormal3sv);
+  SET_NormalPointer(disp, glNormalPointer);
+//SET_NormalPointerEXT(disp, glNormalPointerEXT);
+  SET_Ortho(disp, glOrtho);
+//SET_PassTexCoordATI(disp, glPassTexCoordEXT);         // <-- EXT -> ATI
+  SET_PassThrough(disp, glPassThrough);
+  SET_PixelMapfv(disp, glPixelMapfv);
+  SET_PixelMapuiv(disp, glPixelMapuiv);
+  SET_PixelMapusv(disp, glPixelMapusv);
+  SET_PixelStoref(disp, glPixelStoref);
+  SET_PixelStorei(disp, glPixelStorei);
+//SET_PixelTexGenParameterfSGIS(disp, glPixelTexGenParameterfSGIS);
+//SET_PixelTexGenParameterfvSGIS(disp, glPixelTexGenParameterfvSGIS);
+//SET_PixelTexGenParameteriSGIS(disp, glPixelTexGenParameteriSGIS);
+//SET_PixelTexGenParameterivSGIS(disp, glPixelTexGenParameterivSGIS);
+//  SET_PixelTexGenSGIX(disp, glPixelTexGenSGIX);
+  SET_PixelTransferf(disp, glPixelTransferf);
+  SET_PixelTransferi(disp, glPixelTransferi);
+  SET_PixelZoom(disp, glPixelZoom);
+  SET_PointParameterfEXT(disp, glPointParameterfARB);      // <-- ARB -> EXT
+  SET_PointParameterfvEXT(disp, glPointParameterfvARB);    // <-- ARB -> EXT
+  SET_PointParameteriNV(disp, glPointParameteriNV);
+  SET_PointParameterivNV(disp, glPointParameterivNV);
+  SET_PointSize(disp, glPointSize);
+  SET_PolygonMode(disp, glPolygonMode);
+  SET_PolygonOffset(disp, glPolygonOffset);
+//SET_PolygonOffsetEXT(disp, glPolygonOffsetEXT);
+  SET_PolygonStipple(disp, glPolygonStipple);
+  SET_PopAttrib(disp, glPopAttrib);
+  SET_PopClientAttrib(disp, glPopClientAttrib);
+  SET_PopMatrix(disp, glPopMatrix);
+  SET_PopName(disp, glPopName);
+  SET_PrioritizeTextures(disp, glPrioritizeTextures);
+  SET_ProgramEnvParameter4dARB(disp, glProgramEnvParameter4dARB);
+  SET_ProgramEnvParameter4dvARB(disp, glProgramEnvParameter4dvARB);
+  SET_ProgramEnvParameter4fARB(disp, glProgramEnvParameter4fARB);
+  SET_ProgramEnvParameter4fvARB(disp, glProgramEnvParameter4fvARB);
+  SET_ProgramLocalParameter4dARB(disp, glProgramLocalParameter4dARB);
+  SET_ProgramLocalParameter4dvARB(disp, glProgramLocalParameter4dvARB);
+  SET_ProgramLocalParameter4fARB(disp, glProgramLocalParameter4fARB);
+  SET_ProgramLocalParameter4fvARB(disp, glProgramLocalParameter4fvARB);
+//SET_ProgramNamedParameter4dNV(disp, glProgramNamedParameter4dNV);
+//SET_ProgramNamedParameter4dvNV(disp, glProgramNamedParameter4dvNV);
+//SET_ProgramNamedParameter4fNV(disp, glProgramNamedParameter4fNV);
+//SET_ProgramNamedParameter4fvNV(disp, glProgramNamedParameter4fvNV);
+//SET_ProgramParameter4dNV(disp, glProgramParameter4dNV);
+//SET_ProgramParameter4dvNV(disp, glProgramParameter4dvNV);
+//SET_ProgramParameter4fNV(disp, glProgramParameter4fNV);
+//SET_ProgramParameter4fvNV(disp, glProgramParameter4fvNV);
+//SET_ProgramParameters4dvNV(disp, glProgramParameters4dvNV);
+//SET_ProgramParameters4fvNV(disp, glProgramParameters4fvNV);
+  SET_ProgramStringARB(disp, glProgramStringARB);
+  SET_PushAttrib(disp, glPushAttrib);
+  SET_PushClientAttrib(disp, glPushClientAttrib);
+  SET_PushMatrix(disp, glPushMatrix);
+  SET_PushName(disp, glPushName);
+  SET_RasterPos2d(disp, glRasterPos2d);
+  SET_RasterPos2dv(disp, glRasterPos2dv);
+  SET_RasterPos2f(disp, glRasterPos2f);
+  SET_RasterPos2fv(disp, glRasterPos2fv);
+  SET_RasterPos2i(disp, glRasterPos2i);
+  SET_RasterPos2iv(disp, glRasterPos2iv);
+  SET_RasterPos2s(disp, glRasterPos2s);
+  SET_RasterPos2sv(disp, glRasterPos2sv);
+  SET_RasterPos3d(disp, glRasterPos3d);
+  SET_RasterPos3dv(disp, glRasterPos3dv);
+  SET_RasterPos3f(disp, glRasterPos3f);
+  SET_RasterPos3fv(disp, glRasterPos3fv);
+  SET_RasterPos3i(disp, glRasterPos3i);
+  SET_RasterPos3iv(disp, glRasterPos3iv);
+  SET_RasterPos3s(disp, glRasterPos3s);
+  SET_RasterPos3sv(disp, glRasterPos3sv);
+  SET_RasterPos4d(disp, glRasterPos4d);
+  SET_RasterPos4dv(disp, glRasterPos4dv);
+  SET_RasterPos4f(disp, glRasterPos4f);
+  SET_RasterPos4fv(disp, glRasterPos4fv);
+  SET_RasterPos4i(disp, glRasterPos4i);
+  SET_RasterPos4iv(disp, glRasterPos4iv);
+  SET_RasterPos4s(disp, glRasterPos4s);
+  SET_RasterPos4sv(disp, glRasterPos4sv);
+  SET_ReadBuffer(disp, glReadBuffer);
+  SET_ReadPixels(disp, glReadPixels);
+  SET_Rectd(disp, glRectd);
+  SET_Rectdv(disp, glRectdv);
+  SET_Rectf(disp, glRectf);
+  SET_Rectfv(disp, glRectfv);
+  SET_Recti(disp, glRecti);
+  SET_Rectiv(disp, glRectiv);
+  SET_Rects(disp, glRects);
+  SET_Rectsv(disp, glRectsv);
+  SET_RenderMode(disp, glRenderMode);
+  SET_RenderbufferStorageEXT(disp, glRenderbufferStorageEXT);
+//SET_RequestResidentProgramsNV(disp, glRequestResidentProgramsNV);
+  SET_ResetHistogram(disp, glResetHistogram);
+  SET_ResetMinmax(disp, glResetMinmax);
+//SET_ResizeBuffersMESA(disp, glResizeBuffersMESA);
+  SET_Rotated(disp, glRotated);
+  SET_Rotatef(disp, glRotatef);
+  SET_SampleCoverageARB(disp, glSampleCoverageARB);
+//SET_SampleMapATI(disp, glSampleMapEXT);       // <-- EXT -> ATI
+//SET_SampleMaskSGIS(disp, glSampleMaskSGIS);
+//SET_SamplePatternSGIS(disp, glSamplePatternSGIS);
+  SET_Scaled(disp, glScaled);
+  SET_Scalef(disp, glScalef);
+  SET_Scissor(disp, glScissor);
+  SET_SecondaryColor3bEXT(disp, glSecondaryColor3bEXT);
+  SET_SecondaryColor3bvEXT(disp, glSecondaryColor3bvEXT);
+  SET_SecondaryColor3dEXT(disp, glSecondaryColor3dEXT);
+  SET_SecondaryColor3dvEXT(disp, glSecondaryColor3dvEXT);
+  SET_SecondaryColor3fEXT(disp, glSecondaryColor3fEXT);
+  SET_SecondaryColor3fvEXT(disp, glSecondaryColor3fvEXT);
+  SET_SecondaryColor3iEXT(disp, glSecondaryColor3iEXT);
+  SET_SecondaryColor3ivEXT(disp, glSecondaryColor3ivEXT);
+  SET_SecondaryColor3sEXT(disp, glSecondaryColor3sEXT);
+  SET_SecondaryColor3svEXT(disp, glSecondaryColor3svEXT);
+  SET_SecondaryColor3ubEXT(disp, glSecondaryColor3ubEXT);
+  SET_SecondaryColor3ubvEXT(disp, glSecondaryColor3ubvEXT);
+  SET_SecondaryColor3uiEXT(disp, glSecondaryColor3uiEXT);
+  SET_SecondaryColor3uivEXT(disp, glSecondaryColor3uivEXT);
+  SET_SecondaryColor3usEXT(disp, glSecondaryColor3usEXT);
+  SET_SecondaryColor3usvEXT(disp, glSecondaryColor3usvEXT);
+  SET_SecondaryColorPointerEXT(disp, glSecondaryColorPointerEXT);
+  SET_SelectBuffer(disp, glSelectBuffer);
+  SET_SeparableFilter2D(disp, glSeparableFilter2D);
+  SET_SetFenceNV(disp, glSetFenceAPPLE);  // <-- APPLE -> NV
+//SET_SetFragmentShaderConstantATI(disp, glSetFragmentShaderConstantEXT);   // <-- EXT -> ATI
+  SET_ShadeModel(disp, glShadeModel);
+  SET_ShaderSourceARB(disp, glShaderSourceARB);
+  SET_StencilFunc(disp, glStencilFunc);
+  SET_StencilFuncSeparate(disp, glStencilFuncSeparate);
+  SET_StencilMask(disp, glStencilMask);
+  SET_StencilMaskSeparate(disp, glStencilMaskSeparate);
+  SET_StencilOp(disp, glStencilOp);
+  SET_StencilOpSeparate(disp, glStencilOpSeparate);
+  SET_TestFenceNV(disp, glTestFenceAPPLE); // <-- APPLE -> NV
+  SET_TexCoord1d(disp, glTexCoord1d);
+  SET_TexCoord1dv(disp, glTexCoord1dv);
+  SET_TexCoord1f(disp, glTexCoord1f);
+  SET_TexCoord1fv(disp, glTexCoord1fv);
+  SET_TexCoord1i(disp, glTexCoord1i);
+  SET_TexCoord1iv(disp, glTexCoord1iv);
+  SET_TexCoord1s(disp, glTexCoord1s);
+  SET_TexCoord1sv(disp, glTexCoord1sv);
+  SET_TexCoord2d(disp, glTexCoord2d);
+  SET_TexCoord2dv(disp, glTexCoord2dv);
+  SET_TexCoord2f(disp, glTexCoord2f);
+  SET_TexCoord2fv(disp, glTexCoord2fv);
+  SET_TexCoord2i(disp, glTexCoord2i);
+  SET_TexCoord2iv(disp, glTexCoord2iv);
+  SET_TexCoord2s(disp, glTexCoord2s);
+  SET_TexCoord2sv(disp, glTexCoord2sv);
+  SET_TexCoord3d(disp, glTexCoord3d);
+  SET_TexCoord3dv(disp, glTexCoord3dv);
+  SET_TexCoord3f(disp, glTexCoord3f);
+  SET_TexCoord3fv(disp, glTexCoord3fv);
+  SET_TexCoord3i(disp, glTexCoord3i);
+  SET_TexCoord3iv(disp, glTexCoord3iv);
+  SET_TexCoord3s(disp, glTexCoord3s);
+  SET_TexCoord3sv(disp, glTexCoord3sv);
+  SET_TexCoord4d(disp, glTexCoord4d);
+  SET_TexCoord4dv(disp, glTexCoord4dv);
+  SET_TexCoord4f(disp, glTexCoord4f);
+  SET_TexCoord4fv(disp, glTexCoord4fv);
+  SET_TexCoord4i(disp, glTexCoord4i);
+  SET_TexCoord4iv(disp, glTexCoord4iv);
+  SET_TexCoord4s(disp, glTexCoord4s);
+  SET_TexCoord4sv(disp, glTexCoord4sv);
+  SET_TexCoordPointer(disp, glTexCoordPointer);
+//SET_TexCoordPointerEXT(disp, glTexCoordPointerEXT);
+  SET_TexEnvf(disp, glTexEnvf);
+  SET_TexEnvfv(disp, glTexEnvfv);
+  SET_TexEnvi(disp, glTexEnvi);
+  SET_TexEnviv(disp, glTexEnviv);
+  SET_TexGend(disp, glTexGend);
+  SET_TexGendv(disp, glTexGendv);
+  SET_TexGenf(disp, glTexGenf);
+  SET_TexGenfv(disp, glTexGenfv);
+  SET_TexGeni(disp, glTexGeni);
+  SET_TexGeniv(disp, glTexGeniv);
+  SET_TexImage1D(disp, glTexImage1D);
+  SET_TexImage2D(disp, glTexImage2D);
+  SET_TexImage3D(disp, glTexImage3D);
+  SET_TexParameterf(disp, glTexParameterf);
+  SET_TexParameterfv(disp, glTexParameterfv);
+  SET_TexParameteri(disp, glTexParameteri);
+  SET_TexParameteriv(disp, glTexParameteriv);
+  SET_TexSubImage1D(disp, glTexSubImage1D);
+  SET_TexSubImage2D(disp, glTexSubImage2D);
+  SET_TexSubImage3D(disp, glTexSubImage3D);
+//SET_TrackMatrixNV(disp, glTrackMatrixNV);
+  SET_Translated(disp, glTranslated);
+  SET_Translatef(disp, glTranslatef);
+  SET_Uniform1fARB(disp, glUniform1fARB);
+  SET_Uniform1fvARB(disp, glUniform1fvARB);
+  SET_Uniform1iARB(disp, glUniform1iARB);
+  SET_Uniform1ivARB(disp, glUniform1ivARB);
+  SET_Uniform2fARB(disp, glUniform2fARB);
+  SET_Uniform2fvARB(disp, glUniform2fvARB);
+  SET_Uniform2iARB(disp, glUniform2iARB);
+  SET_Uniform2ivARB(disp, glUniform2ivARB);
+  SET_Uniform3fARB(disp, glUniform3fARB);
+  SET_Uniform3fvARB(disp, glUniform3fvARB);
+  SET_Uniform3iARB(disp, glUniform3iARB);
+  SET_Uniform3ivARB(disp, glUniform3ivARB);
+  SET_Uniform4fARB(disp, glUniform4fARB);
+  SET_Uniform4fvARB(disp, glUniform4fvARB);
+  SET_Uniform4iARB(disp, glUniform4iARB);
+  SET_Uniform4ivARB(disp, glUniform4ivARB);
+  SET_UniformMatrix2fvARB(disp, glUniformMatrix2fvARB);
+  SET_UniformMatrix3fvARB(disp, glUniformMatrix3fvARB);
+  SET_UniformMatrix4fvARB(disp, glUniformMatrix4fvARB);
+  SET_UnlockArraysEXT(disp, glUnlockArraysEXT);
+  SET_UnmapBufferARB(disp, glUnmapBufferARB);
+  SET_UseProgramObjectARB(disp, glUseProgramObjectARB);
+  SET_ValidateProgramARB(disp, glValidateProgramARB);
+  SET_Vertex2d(disp, glVertex2d);
+  SET_Vertex2dv(disp, glVertex2dv);
+  SET_Vertex2f(disp, glVertex2f);
+  SET_Vertex2fv(disp, glVertex2fv);
+  SET_Vertex2i(disp, glVertex2i);
+  SET_Vertex2iv(disp, glVertex2iv);
+  SET_Vertex2s(disp, glVertex2s);
+  SET_Vertex2sv(disp, glVertex2sv);
+  SET_Vertex3d(disp, glVertex3d);
+  SET_Vertex3dv(disp, glVertex3dv);
+  SET_Vertex3f(disp, glVertex3f);
+  SET_Vertex3fv(disp, glVertex3fv);
+  SET_Vertex3i(disp, glVertex3i);
+  SET_Vertex3iv(disp, glVertex3iv);
+  SET_Vertex3s(disp, glVertex3s);
+  SET_Vertex3sv(disp, glVertex3sv);
+  SET_Vertex4d(disp, glVertex4d);
+  SET_Vertex4dv(disp, glVertex4dv);
+  SET_Vertex4f(disp, glVertex4f);
+  SET_Vertex4fv(disp, glVertex4fv);
+  SET_Vertex4i(disp, glVertex4i);
+  SET_Vertex4iv(disp, glVertex4iv);
+  SET_Vertex4s(disp, glVertex4s);
+  SET_Vertex4sv(disp, glVertex4sv);
+//SET_VertexArrayRangeNV(disp, glVertexArrayRangeNV);
+  SET_VertexAttrib1dARB(disp, glVertexAttrib1dARB);
+  SET_VertexAttrib1dvARB(disp, glVertexAttrib1dvARB);
+  SET_VertexAttrib1fARB(disp, glVertexAttrib1fARB);
+  SET_VertexAttrib1fvARB(disp, glVertexAttrib1fvARB);
+  SET_VertexAttrib1sARB(disp, glVertexAttrib1sARB);
+  SET_VertexAttrib1svARB(disp, glVertexAttrib1svARB);
+  SET_VertexAttrib2dARB(disp, glVertexAttrib2dARB);
+  SET_VertexAttrib2dvARB(disp, glVertexAttrib2dvARB);
+  SET_VertexAttrib2fARB(disp, glVertexAttrib2fARB);
+  SET_VertexAttrib2fvARB(disp, glVertexAttrib2fvARB);
+  SET_VertexAttrib2sARB(disp, glVertexAttrib2sARB);
+  SET_VertexAttrib2svARB(disp, glVertexAttrib2svARB);
+  SET_VertexAttrib3dARB(disp, glVertexAttrib3dARB);
+  SET_VertexAttrib3dvARB(disp, glVertexAttrib3dvARB);
+  SET_VertexAttrib3fARB(disp, glVertexAttrib3fARB);
+  SET_VertexAttrib3fvARB(disp, glVertexAttrib3fvARB);
+  SET_VertexAttrib3sARB(disp, glVertexAttrib3sARB);
+  SET_VertexAttrib3svARB(disp, glVertexAttrib3svARB);
+  SET_VertexAttrib4NbvARB(disp, glVertexAttrib4NbvARB);
+  SET_VertexAttrib4NivARB(disp, glVertexAttrib4NivARB);
+  SET_VertexAttrib4NsvARB(disp, glVertexAttrib4NsvARB);
+  SET_VertexAttrib4NubARB(disp, glVertexAttrib4NubARB);
+  SET_VertexAttrib4NubvARB(disp, glVertexAttrib4NubvARB);
+  SET_VertexAttrib4NuivARB(disp, glVertexAttrib4NuivARB);
+  SET_VertexAttrib4NusvARB(disp, glVertexAttrib4NusvARB);
+  SET_VertexAttrib4bvARB(disp, glVertexAttrib4bvARB);
+  SET_VertexAttrib4dARB(disp, glVertexAttrib4dARB);
+  SET_VertexAttrib4dvARB(disp, glVertexAttrib4dvARB);
+  SET_VertexAttrib4fARB(disp, glVertexAttrib4fARB);
+  SET_VertexAttrib4fvARB(disp, glVertexAttrib4fvARB);
+  SET_VertexAttrib4ivARB(disp, glVertexAttrib4ivARB);
+  SET_VertexAttrib4sARB(disp, glVertexAttrib4sARB);
+  SET_VertexAttrib4svARB(disp, glVertexAttrib4svARB);
+  SET_VertexAttrib4ubvARB(disp, glVertexAttrib4ubvARB);
+  SET_VertexAttrib4uivARB(disp, glVertexAttrib4uivARB);
+  SET_VertexAttrib4usvARB(disp, glVertexAttrib4usvARB);
+  SET_VertexAttribPointerARB(disp, glVertexAttribPointerARB);
+  SET_VertexPointer(disp, glVertexPointer);
+//  SET_VertexPointerEXT(disp, glVertexPointerEXT);
+  SET_Viewport(disp, glViewport);
+  SET_WindowPos2dMESA(disp, glWindowPos2dARB);
+  SET_WindowPos2dvMESA(disp, glWindowPos2dvARB);
+  SET_WindowPos2fMESA(disp, glWindowPos2fARB);
+  SET_WindowPos2fvMESA(disp, glWindowPos2fvARB);
+  SET_WindowPos2iMESA(disp, glWindowPos2iARB);
+  SET_WindowPos2ivMESA(disp, glWindowPos2ivARB);
+  SET_WindowPos2sMESA(disp, glWindowPos2sARB);
+  SET_WindowPos2svMESA(disp, glWindowPos2svARB);
+  SET_WindowPos3dMESA(disp, glWindowPos3dARB);
+  SET_WindowPos3dvMESA(disp, glWindowPos3dvARB);
+  SET_WindowPos3fMESA(disp, glWindowPos3fARB);
+  SET_WindowPos3fvMESA(disp, glWindowPos3fvARB);
+  SET_WindowPos3iMESA(disp, glWindowPos3iARB);
+  SET_WindowPos3ivMESA(disp, glWindowPos3ivARB);
+  SET_WindowPos3sMESA(disp, glWindowPos3sARB);
+  SET_WindowPos3svMESA(disp, glWindowPos3svARB);
+//SET_WindowPos4dMESA(disp, glWindowPos4dMESA);
+//SET_WindowPos4dvMESA(disp, glWindowPos4dvMESA);
+//SET_WindowPos4fMESA(disp, glWindowPos4fMESA);
+//SET_WindowPos4fvMESA(disp, glWindowPos4fvMESA);
+//SET_WindowPos4iMESA(disp, glWindowPos4iMESA);
+//SET_WindowPos4ivMESA(disp, glWindowPos4ivMESA);
+//SET_WindowPos4sMESA(disp, glWindowPos4sMESA);
+//SET_WindowPos4svMESA(disp, glWindowPos4svMESA);
+}
diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index 1c97ac8..ccef5f6 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -13,8 +13,8 @@ if X11APP
 X11APP_SUBDIRS = bundle
 endif
 
-SUBDIRS = . xpr $(X11APP_SUBDIRS)
-DIST_SUBDIRS = xpr bundle
+SUBDIRS = . GL xpr $(X11APP_SUBDIRS)
+DIST_SUBDIRS = GL xpr bundle
 
 libXquartz_la_SOURCES = \
 	$(top_srcdir)/fb/fbcmap_mi.c \
commit b05b416c622063b84747702a54ffd9a802d6fc11
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 23 09:59:48 2008 -0700

    XQuartz: No need to include indirect.c a second time
    (cherry picked from commit 41ed532525da85d1bd2c20af5ffa28ac6d1f4996)

diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index d74cf7d..12009fb 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -14,7 +14,6 @@ Xquartz_SOURCES = \
 	xprEvent.c \
 	xprFrame.c \
 	xprScreen.c \
-	../../../GL/apple/indirect.c \
 	x-hash.c \
 	x-hook.c \
 	x-list.c
commit 565492c70a280d7e749500c5c0073bdcaf175c86
Author: Ben Byer <bbyer at apple.com>
Date:   Wed Apr 23 06:00:57 2008 -0700

    xquartz: build fixes for GLX/DRI2 fallout (note: not guaranteed)
    (cherry picked from commit 85a5796b667461bf1fafc68c07b3a704cd8efd5b)

diff --git a/GL/apple/indirect.c b/GL/apple/indirect.c
index 2729ab0..a0884d4 100644
--- a/GL/apple/indirect.c
+++ b/GL/apple/indirect.c
@@ -102,7 +102,7 @@ void warn_func(void * p1, char *format, ...);
 
 // some prototypes
 static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen);
-static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLcontextModes *modes);
+static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLXconfig *modes);
 
 static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
                               int *nvisualp, int *ndepthp,
@@ -118,7 +118,7 @@ static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext);
 static int __glXAquaContextForceCurrent(__GLXcontext *baseContext);
 static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask);
 
-static CGLPixelFormatObj makeFormat(__GLcontextModes *mode);
+static CGLPixelFormatObj makeFormat(__GLXconfig *mode);
 
 __GLXprovider __glXMesaProvider = {
   __glXAquaScreenProbe,
@@ -141,7 +141,7 @@ struct __GLXAquaScreen {
   __GLXscreen   base;
   int           index;
     int num_vis;
-    __GLcontextModes *modes;
+    __GLXconfig *modes;
 };
 
 static __GLXAquaScreen glAquaScreens[MAXSCREENS];
@@ -162,7 +162,7 @@ struct __GLXAquaDrawable {
 
 static __GLXcontext *
 __glXAquaScreenCreateContext(__GLXscreen *screen,
-			     __GLcontextModes *modes,
+			     __GLXconfig *config,
 			     __GLXcontext *baseShareContext)
 {
   __GLXAquaContext *context;
@@ -177,7 +177,7 @@ __glXAquaScreenCreateContext(__GLXscreen *screen,
   memset(context, 0, sizeof *context);
 
   context->base.pGlxScreen = screen;
-  context->base.modes      = modes;
+  context->base.config      = config;
 
   context->base.destroy        = __glXAquaContextDestroy;
   context->base.makeCurrent    = __glXAquaContextMakeCurrent;
@@ -186,7 +186,7 @@ __glXAquaScreenCreateContext(__GLXscreen *screen,
   context->base.forceCurrent   = __glXAquaContextForceCurrent;
   //  context->base.createDrawable = __glXAquaContextCreateDrawable;
 
-  context->pixelFormat = makeFormat(modes);
+  context->pixelFormat = makeFormat(config);
   if (!context->pixelFormat) {
         free(context);
         return NULL;
@@ -437,7 +437,7 @@ static GLboolean __glXAquaDrawableSwapBuffers(__GLXdrawable *base) {
     return GL_TRUE;
 }
 
-static CGLPixelFormatObj makeFormat(__GLcontextModes *mode) {
+static CGLPixelFormatObj makeFormat(__GLXconfig *config) {
     int i;
     CGLPixelFormatAttribute attr[64]; // currently uses max of 30
     CGLPixelFormatObj result;
@@ -446,7 +446,7 @@ static CGLPixelFormatObj makeFormat(__GLcontextModes *mode) {
     
     GLAQUA_DEBUG_MSG("makeFormat\n");
 
-    if (!mode->rgbMode)
+    if (!config->rgbMode)
         return NULL;
 
     i = 0;
@@ -454,42 +454,43 @@ static CGLPixelFormatObj makeFormat(__GLcontextModes *mode) {
     // attr [i++] = kCGLPFAAcelerated; // require hwaccel - BAD for multiscreen
     // attr [i++] = kCGLPFANoRecovery; // disable fallback renderers - BAD
 
-    if (mode->stereoMode) {
+    if (config->stereoMode) {
         attr[i++] = kCGLPFAStereo;
     }
-    if (mode->doubleBufferMode) {
+
+    if (config->doubleBufferMode) {
         attr[i++] = kCGLPFADoubleBuffer;
     }
 
-    if (mode->colorIndexMode) {
+    if (config->colorIndexMode) {
         /* ignored */
     }
 
-    if (mode->rgbMode) {
+    if (config->rgbMode) {
         attr[i++] = kCGLPFAColorSize;
-        attr[i++] = mode->redBits + mode->greenBits + mode->blueBits;
+        attr[i++] = config->redBits + config->greenBits + config->blueBits;
         attr[i++] = kCGLPFAAlphaSize;
-        attr[i++] = 1; /* FIXME: ignoring mode->alphaBits which is always 0 */
+        attr[i++] = 1; /* FIXME: ignoring config->alphaBits which is always 0 */
     }
 
-    if (mode->haveAccumBuffer) {
+    if (config->haveAccumBuffer) {
         attr[i++] = kCGLPFAAccumSize;
-        attr[i++] = mode->accumRedBits + mode->accumGreenBits
-                    + mode->accumBlueBits + mode->accumAlphaBits;
+        attr[i++] = config->accumRedBits + config->accumGreenBits
+                    + config->accumBlueBits + config->accumAlphaBits;
     }
 	
-    if (mode->haveDepthBuffer) {
+    if (config->haveDepthBuffer) {
         attr[i++] = kCGLPFADepthSize;
-        attr[i++] = mode->depthBits;
+        attr[i++] = config->depthBits;
     }
 	
-    if (mode->haveStencilBuffer) {
+    if (config->haveStencilBuffer) {
         attr[i++] = kCGLPFAStencilSize;
-        attr[i++] = mode->stencilBits;
+        attr[i++] = config->stencilBits;
     }
 
     attr[i++] = kCGLPFAAuxBuffers;
-    attr[i++] = mode->numAuxBuffers;
+    attr[i++] = config->numAuxBuffers;
 
     /* mode->level ignored */
 
@@ -670,7 +671,7 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
     VisualPtr pVisual = *visualp;
     VisualPtr pVisualNew = NULL;
     VisualID *orig_vid = NULL;
-    __GLcontextModes *modes;
+    __GLXconfig *modes;
     __GLXvisualConfig *pNewVisualConfigs = NULL;
     void **glXVisualPriv;
     void **pNewVisualPriv;
@@ -752,7 +753,7 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
     }
 
     /* Alloc space for the list of glXVisuals */
-    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLcontextModes));
+    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLXconfig));
     if (modes == NULL) {
         free(orig_vid);
         free(pNewVisualPriv);
@@ -925,6 +926,7 @@ Bool enable_stereo = FALSE;
 /* based on code in i830_dri.c
    This ends calling glAquaSetVisualConfigs to set the static
    numconfigs, etc. */
+// see also glxglcore.c -- bhb
 static void
 glAquaInitVisualConfigs(void)
 {
@@ -1085,7 +1087,7 @@ static void __glXAquaScreenDestroy(__GLXscreen *screen) {
 static void init_screen_visuals(__GLXAquaScreen *screen) {
   ScreenPtr pScreen = screen->base.pScreen;
   
-  __GLcontextModes *modes;
+  __GLXconfig *modes;
   int *used;
   int i, j;
   
@@ -1101,7 +1103,7 @@ static void init_screen_visuals(__GLXAquaScreen *screen) {
     memset(used, 0, pScreen->numVisuals * sizeof(int));
 
     i = 0;
-    for ( modes = screen -> base.modes
+    for ( modes = screen -> base.visuals
           ; modes != NULL
           ; modes = modes->next ) {
         const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
@@ -1174,7 +1176,7 @@ static __GLXdrawable *
 __glXAquaScreenCreateDrawable(__GLXscreen *screen,
 			      DrawablePtr pDraw,
 			      XID drawId,
-			      __GLcontextModes *modes) {
+			      __GLXconfig *modes) {
   __GLXAquaDrawable *glxPriv;
 
   GLAQUA_DEBUG_MSG("glAquaScreenCreateDrawable(%p,%p,%d,%p)\n", context, pDraw, drawId, modes);
@@ -1184,7 +1186,7 @@ __glXAquaScreenCreateDrawable(__GLXscreen *screen,
 
   memset(glxPriv, 0, sizeof *glxPriv);
 
-  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, drawId, modes)) {
+  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, GLX_DRAWABLE_PIXMAP /*?*/, drawId, modes)) {
     xfree(glxPriv);
     return NULL;
   }
commit 6f6505db51763d902142a8161e71cad44f52560c
Author: Ben Byer <bbyer at apple.com>
Date:   Wed Apr 23 03:43:51 2008 -0700

    glx / xquartz:  we still need glxcontentmodes.[ch] kthx
    (cherry picked from commit 27545fd37f8c703b72f7cfc329778abc1ceabfa0)

diff --git a/GL/symlink-mesa.sh b/GL/symlink-mesa.sh
index 8deaa43..def4f63 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -64,6 +64,8 @@ symlink_glx() {
     dst_dir glx
 
     action indirect_size.h
+    action glcontextmodes.c
+    action glcontextmodes.h
     action indirect_dispatch.c
     action indirect_dispatch.h
     action indirect_dispatch_swap.c
commit 4e3a8af5751ff88c0cadd612821b0ef349d250c5
Author: Ben Byer <bbyer at apple.com>
Date:   Wed Apr 23 03:39:41 2008 -0700

    xquartz: clean up linker line for main binary
    (cherry picked from commit 821d7400f2ff917497b2ee58ceef2b69c2d47ec7)

diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index 6007423..d74cf7d 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -14,6 +14,7 @@ Xquartz_SOURCES = \
 	xprEvent.c \
 	xprFrame.c \
 	xprScreen.c \
+	../../../GL/apple/indirect.c \
 	x-hash.c \
 	x-hook.c \
 	x-list.c
@@ -21,23 +22,6 @@ Xquartz_SOURCES = \
 Xquartz_LDADD = \
 	$(top_builddir)/hw/xquartz/libXquartz.la \
 	$(top_builddir)/dix/dixfonts.lo \
-	$(top_builddir)/config/libconfig.a \
-	$(top_builddir)/dix/libdix.la \
-	$(top_builddir)/os/libos.la \
-	$(top_builddir)/dix/libxpstubs.la \
-	$(top_builddir)/miext/shadow/libshadow.la \
-	$(top_builddir)/fb/libfb.la \
-	$(top_builddir)/mi/libmi.la \
-	$(top_builddir)/damageext/libdamageext.la \
-	$(top_builddir)/miext/damage/libdamage.la \
-	$(top_builddir)/xfixes/libxfixes.la \
-	$(top_builddir)/Xext/libXext.la \
-	$(top_builddir)/xkb/libxkb.la \
-	$(top_builddir)/xkb/libxkbstubs.la \
-	$(top_builddir)/Xi/libXi.la \
-	$(top_builddir)/dbe/libdbe.la \
-	$(top_builddir)/record/librecord.la \
-	$(top_builddir)/XTrap/libxtrap.la \
 	$(top_builddir)/miext/rootless/librootless.la \
 	$(DARWIN_LIBS) $(XSERVER_LIBS) $(XSERVER_SYS_LIBS) -lXplugin
 
commit 3685b171da51f853bfdb312d36622dfa03ee75be
Author: Ben Byer <bbyer at apple.com>
Date:   Tue Apr 22 23:53:23 2008 -0700

    xquartz: remove vestigial aglGlx.c
    (cherry picked from commit 40bd041e4255f26fcbdf0831e68619ae0f46ab39)

diff --git a/GL/apple/Makefile.am b/GL/apple/Makefile.am
index c064c03..7ad9140 100644
--- a/GL/apple/Makefile.am
+++ b/GL/apple/Makefile.am
@@ -8,17 +8,7 @@ AM_CPPFLAGS = \
 	-I$(top_srcdir)/hw/xquartz/xpr \
 	-I$(top_srcdir)/miext/damage
 
-if HAVE_AGL_FRAMEWORK
-noinst_LIBRARIES = libAGLcore.a 
-libAGLcore_a_SOURCES = aglGlx.c \
-		       $(top_srcdir)/hw/xquartz/xpr/x-list.c \
-		       $(top_srcdir)/hw/xquartz/xpr/x-list.h \
-		       $(top_srcdir)/hw/xquartz/xpr/x-hash.c \
-		       $(top_srcdir)/hw/xquartz/xpr/x-hash.h \
-		       $(top_srcdir)/hw/dmx/glxProxy/compsize.c
-endif
-
-#noinst_LIBRARIES = libCGLcore.a 
-#libCGLcore_a_SOURCES = \
-#	indirect.c \
-#	$(top_srcdir)/hw/dmx/glxProxy/compsize.c
+noinst_LIBRARIES = libCGLcore.a 
+libCGLcore_a_SOURCES = \
+	indirect.c \
+	$(top_srcdir)/hw/dmx/glxProxy/compsize.c
diff --git a/GL/apple/aglGlx.c b/GL/apple/aglGlx.c
deleted file mode 100644
index 900a9a9..0000000
--- a/GL/apple/aglGlx.c
+++ /dev/null
@@ -1,1354 +0,0 @@
-/*
- * GLX implementation that uses Apple's AGL.framework for OpenGL
- *
- * FIXME: This file and indirect.c are very similar. The two should be
- * merged by introducing suitable abstractions.
- */
-/*
- * Copyright (c) 2002 Greg Parker. All Rights Reserved.
- * Copyright (c) 2004 Torrey T. Lyons. All Rights Reserved.
- *
- * Large 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.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "quartzCommon.h"
-#include <AGL/agl.h>
-#include "cr.h"
-
-// X11 and X11's glx
-#undef BOOL
-#define BOOL xBOOL
-#include "quartz.h"
-#include <miscstruct.h>
-#include <windowstr.h>
-#include <resource.h>
-#include <GL/glxint.h>
-#include <GL/glxtokens.h>
-#include <scrnintstr.h>
-#include <glxserver.h>
-#include <glxscreens.h>
-#include <glxdrawable.h>
-#include <glxcontext.h>
-#include <glxext.h>
-#include <glxutil.h>
-#include <glxscreens.h>
-#include <GL/internal/glcore.h>
-#undef BOOL
-
-#include "glcontextmodes.h"
-
-// ggs: needed to call back to glx with visual configs
-extern void GlxSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs, void **configprivs);
-
-// Write debugging output, or not
-#ifdef GLAQUA_DEBUG
-#define GLAQUA_DEBUG_MSG ErrorF
-#else
-#define GLAQUA_DEBUG_MSG(a, ...)
-#endif
-
-
-// The following GL functions don't have an EXT suffix in OpenGL.framework.
-GLboolean glAreTexturesResidentEXT (GLsizei a, const GLuint *b, GLboolean *c) {
-    return glAreTexturesResident(a, b, c);
-}
-void glDeleteTexturesEXT (GLsizei d, const GLuint *e) {
-    glDeleteTextures(d, e);
-}
-void glGenTexturesEXT (GLsizei f, GLuint *g) {
-    glGenTextures(f, g);
-}
-GLboolean glIsTextureEXT (GLuint h) {
-    return glIsTexture(h);
-}
-
-
-// some prototypes
-static Bool glAquaScreenProbe(int screen);
-static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
-                              int *nvisualp, int *ndepthp,
-                              int *rootDepthp, VisualID *defaultVisp,
-                              unsigned long sizes, int bitsPerRGB);
-static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
-                                   void **privates);
-static __GLinterface *glAquaCreateContext(__GLimports *imports,
-                                          __GLcontextModes *mode,
-                                          __GLinterface *shareGC);
-static void glAquaCreateBuffer(__GLXdrawablePrivate *glxPriv);
-static void glAquaResetExtension(void);
-
-
-/*
- * This structure is statically allocated in the __glXScreens[]
- * structure.  This struct is not used anywhere other than in
- * __glXScreenInit to initialize each of the active screens
- * (__glXActiveScreens[]).  Several of the fields must be initialized by
- * the screenProbe routine before they are copied to the active screens
- * struct.  In particular, the contextCreate, modes, numVisuals,
- * and numUsableVisuals fields must be initialized.
- */
-static __GLXscreenInfo __glDDXScreenInfo = {
-    glAquaScreenProbe,   /* Must be generic and handle all screens */
-    glAquaCreateContext, /* Substitute screen's createContext routine */
-    glAquaCreateBuffer,  /* Substitute screen's createBuffer routine */
-    NULL,                 /* Set up modes in probe */
-    NULL,                 /* Set up pVisualPriv in probe */
-    0,                    /* Set up numVisuals in probe */
-    0,                    /* Set up numUsableVisuals in probe */
-    "Vendor String",      /* GLXvendor is overwritten by __glXScreenInit */
-    "Version String",     /* GLXversion is overwritten by __glXScreenInit */
-    "Extensions String",  /* GLXextensions is overwritten by __glXScreenInit */
-    NULL                  /* WrappedPositionWindow is overwritten */
-};
-
-void *__glXglDDXScreenInfo(void) {
-    return &__glDDXScreenInfo;
-}
-
-static __GLXextensionInfo __glDDXExtensionInfo = {
-    GL_CORE_APPLE,
-    glAquaResetExtension,
-    glAquaInitVisuals,
-    glAquaSetVisualConfigs
-};
-
-void *__glXglDDXExtensionInfo(void) {
-    return &__glDDXExtensionInfo;
-}
-
-// prototypes
-
-static GLboolean glAquaDestroyContext(__GLcontext *gc);
-static GLboolean glAquaLoseCurrent(__GLcontext *gc);
-static GLboolean glAquaMakeCurrent(__GLcontext *gc);
-static GLboolean glAquaShareContext(__GLcontext *gc, __GLcontext *gcShare);
-static GLboolean glAquaCopyContext(__GLcontext *dst, const __GLcontext *src,
-                                    GLuint mask);
-static GLboolean glAquaForceCurrent(__GLcontext *gc);
-
-/* Drawing surface notification callbacks */
-static GLboolean glAquaNotifyResize(__GLcontext *gc);
-static void glAquaNotifyDestroy(__GLcontext *gc);
-static void glAquaNotifySwapBuffers(__GLcontext *gc);
-
-/* Dispatch table override control for external agents like libGLS */
-static struct __GLdispatchStateRec* glAquaDispatchExec(__GLcontext *gc);
-static void glAquaBeginDispatchOverride(__GLcontext *gc);
-static void glAquaEndDispatchOverride(__GLcontext *gc);
-
-
-static __GLexports glAquaExports = {
-    glAquaDestroyContext,
-    glAquaLoseCurrent,
-    glAquaMakeCurrent,
-    glAquaShareContext,
-    glAquaCopyContext,
-    glAquaForceCurrent,
-
-    glAquaNotifyResize,
-    glAquaNotifyDestroy,
-    glAquaNotifySwapBuffers,
-
-    glAquaDispatchExec,
-    glAquaBeginDispatchOverride,
-    glAquaEndDispatchOverride
-};
-
-
-typedef struct {
-    int num_vis;
-    __GLcontextModes *modes;
-    void **priv;
-
-    // wrapped screen functions
-    RealizeWindowProcPtr RealizeWindow;
-    UnrealizeWindowProcPtr UnrealizeWindow;
-} glAquaScreenRec;
-
-static glAquaScreenRec glAquaScreens[MAXSCREENS];
-
-
-// __GLdrawablePrivate->private
-typedef struct {
-    GLboolean (*resize)(__GLdrawableBuffer *buf, GLint x, GLint y,
-                        GLuint width, GLuint height,
-                        __GLdrawablePrivate *glPriv,
-                        GLuint bufferMask);
-} GLAquaDrawableRec;
-
-struct __GLcontextRec {
-  struct __GLinterfaceRec interface; // required to be first
-
-  AGLContext ctx;
-  AGLPixelFormat pixelFormat;
-
-  Bool isAttached; // TRUE if ctx is really attached to a window
-};
-
-
-// Context manipulation; return GL_FALSE on failure
-static GLboolean glAquaDestroyContext(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("glAquaDestroyContext (ctx 0x%x)\n", gc->ctx);
-
-    if (gc) {
-        if (gc->ctx) aglDestroyContext(gc->ctx);
-        if (gc->pixelFormat) aglDestroyPixelFormat(gc->pixelFormat);
-        free(gc);
-    }
-
-    return GL_TRUE;
-}
-
-
-static GLboolean glAquaLoseCurrent(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("glAquaLoseCurrent (ctx 0x%x)\n", gc->ctx);
-
-    aglSetCurrentContext(NULL);
-    __glXLastContext = NULL; // Mesa does this; why?
-    gc->isAttached = FALSE;
-
-    return GL_TRUE;
-}
-
-
-/*
- * Attach a GL context to a GL drawable
- * If glPriv is NULL, the context is detached.
- */
-static void attach(__GLcontext *gc, __GLdrawablePrivate *glPriv)
-{
-    __GLXdrawablePrivate *glxPriv;
-
-    if (glPriv == NULL) {
-        // attaching to nothing
-        GLAQUA_DEBUG_MSG("unattaching\n");
-        aglSetDrawable(gc->ctx, NULL);
-        gc->isAttached = FALSE;
-        return;
-    }
-
-    // Note that when resizing, the X11 WindowPtr already has its
-    // new size and position, but the Aqua window does not.
-
-    glxPriv = (__GLXdrawablePrivate *)glPriv->other;
-
-    if (glxPriv->type == DRAWABLE_WINDOW) {
-        WindowPtr pWin = (WindowPtr) glxPriv->pDraw;
-        WindowPtr topWin = quartzProcs->TopLevelParent(pWin);
-        CRWindowPtr crWinPtr;
-        AGLDrawable newPort;
-
-        if (glPriv->width <= 0 || glPriv->height <= 0) {
-            // attach to zero size drawable - will really attach later
-            GLAQUA_DEBUG_MSG("couldn't attach to zero size drawable\n");
-            aglSetDrawable(gc->ctx, NULL);
-            gc->isAttached = FALSE;
-            return;
-        }
-
-        crWinPtr = (CRWindowPtr) quartzProcs->FrameForWindow(pWin, FALSE);
-
-        if (crWinPtr) {
-            newPort = (AGLDrawable) crWinPtr->port;
-        } else {
-            newPort = NULL;
-        }
-
-        if (newPort) {
-            // FIXME: won't be a CGrafPtr if currently offscreen or fullscreen
-            AGLDrawable oldPort = aglGetDrawable(gc->ctx);
-            // AGLDrawable newPort = GetWindowPort(window);
-
-            // Frame is GLdrawable in X11 global coordinates
-            // FIXME: Does this work for multiple screens?
-            GLint frame[4] = {glPriv->xOrigin, glPriv->yOrigin, glPriv->width, glPriv->height};
-            GLAQUA_DEBUG_MSG("global size %d %d %d %d\n",
-                             frame[0], frame[1], frame[2], frame[3]);
-
-            // Convert to window-local coordinates
-            frame[0] -= topWin->drawable.x - topWin->borderWidth;
-            frame[1] -= topWin->drawable.y - topWin->borderWidth;
-
-            // AGL uses flipped coordinates
-            frame[1] = topWin->drawable.height + 2*topWin->borderWidth -
-                       frame[1] - frame[3];
-
-            GLAQUA_DEBUG_MSG("local size %d %d %d %d\n",
-                             frame[0], frame[1], frame[2], frame[3]);
-
-            if (oldPort != newPort) {
-                // FIXME: retain/release windows
-                if (!aglSetDrawable(gc->ctx, newPort)) return;
-            }
-            if (!aglSetInteger(gc->ctx, AGL_BUFFER_RECT, frame)) return;
-            if (!aglEnable(gc->ctx, AGL_BUFFER_RECT)) return;
-            if (!aglSetInteger(gc->ctx, AGL_SWAP_RECT, frame)) return;
-            if (!aglEnable(gc->ctx, AGL_SWAP_RECT)) return;
-            if (!aglUpdateContext(gc->ctx)) return;
-
-            gc->isAttached = TRUE;
-            GLAQUA_DEBUG_MSG("attached context 0x%x to window 0x%x\n", gc->ctx,
-                             pWin->drawable.id);
-        } else {
-            // attach to not-yet-realized window - will really attach later
-            GLAQUA_DEBUG_MSG("couldn't attach to unrealized window\n");
-            aglSetDrawable(gc->ctx, NULL);
-            gc->isAttached = FALSE;
-        }
-    } else {
-        GLAQUA_DEBUG_MSG("attach: attach to non-window unimplemented\n");
-        aglSetDrawable(gc->ctx, NULL);
-        gc->isAttached = FALSE;
-    }
-}
-
-static GLboolean glAquaMakeCurrent(__GLcontext *gc)
-{
-    __GLdrawablePrivate *glPriv = gc->interface.imports.getDrawablePrivate(gc);
-
-    GLAQUA_DEBUG_MSG("glAquaMakeCurrent (ctx 0x%x)\n", gc->ctx);
-
-    if (!gc->isAttached) {
-        attach(gc, glPriv);
-    }
-
-    return aglSetCurrentContext(gc->ctx);
-}
-
-static GLboolean glAquaShareContext(__GLcontext *gc, __GLcontext *gcShare)
-{
-  GLAQUA_DEBUG_MSG("glAquaShareContext unimplemented\n");
-
-  return GL_TRUE;
-}
-
-
-static GLboolean glAquaCopyContext(__GLcontext *dst, const __GLcontext *src,
-                                   GLuint mask)
-{
-  GLAQUA_DEBUG_MSG("glAquaCopyContext\n");
-
-    return aglCopyContext(src->ctx, dst->ctx, mask);
-}
-
-static GLboolean glAquaForceCurrent(__GLcontext *gc)
-{
-    //     GLAQUA_DEBUG_MSG("glAquaForceCurrent (ctx 0x%x)\n", gc->ctx);
-    return aglSetCurrentContext(gc->ctx);
-}
-
-/* Drawing surface notification callbacks */
-
-static GLboolean glAquaNotifyResize(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifyResize");
-    return GL_TRUE;
-}
-
-static void glAquaNotifyDestroy(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifyDestroy");
-}
-
-static void glAquaNotifySwapBuffers(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifySwapBuffers");
-}
-
-/* Dispatch table override control for external agents like libGLS */
-static struct __GLdispatchStateRec* glAquaDispatchExec(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaDispatchExec");
-    return NULL;
-}
-
-static void glAquaBeginDispatchOverride(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaBeginDispatchOverride");
-}
-
-static void glAquaEndDispatchOverride(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaEndDispatchOverride");
-}
-
-
-static AGLPixelFormat makeFormat(__GLcontextModes *mode)
-{
-    int i;
-    GLint attr[64]; // currently uses max of 30
-    AGLPixelFormat result;
-
-    GLAQUA_DEBUG_MSG("makeFormat\n");
-
-    i = 0;
-
-    // attr [i++] = AGL_ACCELERATED; // require hwaccel - BAD for multiscreen
-    // attr [i++] = AGL_NO_RECOVERY; // disable fallback renderers - BAD
-
-    if (mode->stereoMode) {
-        attr[i++] = AGL_STEREO;
-    }
-    if (mode->doubleBufferMode) {
-        attr[i++] = AGL_DOUBLEBUFFER;
-    }
-
-    if (mode->colorIndexMode) {
-        attr[i++] = AGL_BUFFER_SIZE;
-        attr[i++] = mode->indexBits;
-    }
-
-    if (mode->rgbMode) {
-        attr[i++] = AGL_RGBA;
-        attr[i++] = AGL_RED_SIZE;
-        attr[i++] = mode->redBits;
-        attr[i++] = AGL_GREEN_SIZE;
-        attr[i++] = mode->greenBits;
-        attr[i++] = AGL_BLUE_SIZE;
-        attr[i++] = mode->blueBits;
-        attr[i++] = AGL_ALPHA_SIZE;
-        attr[i++] = mode->alphaBits;
-    }
-
-    if (mode->haveAccumBuffer) {
-        attr[i++] = AGL_ACCUM_RED_SIZE;
-        attr[i++] = mode->accumRedBits;
-        attr[i++] = AGL_ACCUM_GREEN_SIZE;
-        attr[i++] = mode->accumGreenBits;
-        attr[i++] = AGL_ACCUM_BLUE_SIZE;
-        attr[i++] = mode->accumBlueBits;
-        attr[i++] = AGL_ACCUM_ALPHA_SIZE;
-        attr[i++] = mode->accumAlphaBits;
-    }
-    if (mode->haveDepthBuffer) {
-        attr[i++] = AGL_DEPTH_SIZE;
-        attr[i++] = mode->depthBits;
-    }
-    if (mode->haveStencilBuffer) {
-        attr[i++] = AGL_STENCIL_SIZE;
-        attr[i++] = mode->stencilBits;
-    }
-
-    attr[i++] = AGL_AUX_BUFFERS;
-    attr[i++] = mode->numAuxBuffers;
-
-    attr[i++] = AGL_LEVEL;
-    attr[i++] = mode->level;
-
-    // mode->pixmapMode ?
-
-    attr[i++] = AGL_NONE; // end of option list
-
-    GLAQUA_DEBUG_MSG("makeFormat almost done\n");
-    result = aglChoosePixelFormat(NULL, 0, attr);
-    GLAQUA_DEBUG_MSG("makeFormat done (0x%x)\n", result);
-    return result;
-}
-
-static __GLinterface *glAquaCreateContext(__GLimports *imports,
-                                          __GLcontextModes *mode,
-                                          __GLinterface *shareGC)
-{
-    __GLcontext *result;
-    __GLcontext *sharectx = (__GLcontext *)shareGC;
-
-    GLAQUA_DEBUG_MSG("glAquaCreateContext\n");
-
-    result = (__GLcontext *)calloc(1, sizeof(__GLcontext));
-    if (!result) return NULL;
-
-    result->interface.imports = *imports;
-    result->interface.exports = glAquaExports;
-
-    result->pixelFormat = makeFormat(mode);
-    if (!result->pixelFormat) {
-        free(result);
-        return NULL;
-    }
-
-    result->ctx = aglCreateContext(result->pixelFormat,
-                        (sharectx && sharectx->ctx) ? sharectx->ctx : NULL);
-
-    if (!result->ctx) {
-        aglDestroyPixelFormat(result->pixelFormat);
-        free(result);
-        return NULL;
-    }
-
-    result->isAttached = FALSE;
-
-    GLAQUA_DEBUG_MSG("glAquaCreateContext done\n");
-    return (__GLinterface *)result;
-}
-
-
-Bool
-glAquaRealizeWindow(WindowPtr pWin)
-{
-    // If this window has GL contexts, tell them to reattach
-    Bool result;
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    glAquaScreenRec *screenPriv = &glAquaScreens[pScreen->myNum];
-    __GLXdrawablePrivate *glxPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaRealizeWindow\n");
-
-    // Allow the window to be created (RootlessRealizeWindow is inside our wrap)
-    pScreen->RealizeWindow = screenPriv->RealizeWindow;
-    result = pScreen->RealizeWindow(pWin);
-    pScreen->RealizeWindow = glAquaRealizeWindow;
-
-    // The Aqua window will already have been created (windows are
-    // realized from top down)
-
-    // Re-attach this window's GL contexts, if any.
-    glxPriv = __glXFindDrawablePrivate(pWin->drawable.id);
-    if (glxPriv) {
-        __GLXcontext *gx;
-        __GLcontext *gc;
-        __GLdrawablePrivate *glPriv = &glxPriv->glPriv;
-        GLAQUA_DEBUG_MSG("glAquaRealizeWindow is GL drawable!\n");
-
-        // GL contexts bound to this window for drawing
-        for (gx = glxPriv->drawGlxc; gx != NULL; gx = gx->nextDrawPriv) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, glPriv);
-        }
-
-        // GL contexts bound to this window for reading
-        for (gx = glxPriv->readGlxc; gx != NULL; gx = gx->nextReadPriv) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, glPriv);
-        }
-    }
-
-    return result;
-}
-
-Bool
-glAquaUnrealizeWindow(WindowPtr pWin)
-{
-    // If this window has GL contexts, tell them to unattach
-    Bool result;
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    glAquaScreenRec *screenPriv = &glAquaScreens[pScreen->myNum];
-    __GLXdrawablePrivate *glxPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaUnrealizeWindow\n");
-
-    // The Aqua window may have already been destroyed (windows
-    // are unrealized from top down)
-
-    // Unattach this window's GL contexts, if any.
-    glxPriv = __glXFindDrawablePrivate(pWin->drawable.id);
-    if (glxPriv) {
-        __GLXcontext *gx;
-        __GLcontext *gc;
-        GLAQUA_DEBUG_MSG("glAquaUnealizeWindow is GL drawable!\n");
-
-        // GL contexts bound to this window for drawing
-        for (gx = glxPriv->drawGlxc; gx != NULL; gx = gx->nextDrawPriv) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, NULL);
-        }
-
-        // GL contexts bound to this window for reading
-        for (gx = glxPriv->readGlxc; gx != NULL; gx = gx->nextReadPriv) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, NULL);
-        }
-    }
-
-    pScreen->UnrealizeWindow = screenPriv->UnrealizeWindow;
-    result = pScreen->UnrealizeWindow(pWin);
-    pScreen->UnrealizeWindow = glAquaUnrealizeWindow;
-
-    return result;
-}
-
-
-// Originally copied from Mesa
-
-static int                 numConfigs     = 0;
-static __GLXvisualConfig  *visualConfigs  = NULL;
-static void              **visualPrivates = NULL;
-
-/*
- * In the case the driver defines no GLX visuals we'll use these.
- * Note that for TrueColor and DirectColor visuals, bufferSize is the 
- * sum of redSize, greenSize, blueSize and alphaSize, which may be larger 
- * than the nplanes/rootDepth of the server's X11 visuals
- */
-#define NUM_FALLBACK_CONFIGS 5
-static __GLXvisualConfig FallbackConfigs[NUM_FALLBACK_CONFIGS] = {
-  /* [0] = RGB, double buffered, Z */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [1] = RGB, double buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-    16, 16, 16, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [2] = RGB+Alpha, double buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 8,      /* rgba sizes */
-    -1, -1, -1, -1,     /* rgba masks */
-    16, 16, 16, 16,     /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [3] = RGB+Alpha, single buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 8,      /* rgba sizes */
-    -1, -1, -1, -1,     /* rgba masks */
-    16, 16, 16, 16,     /* rgba accum sizes */
-    False,              /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [4] = CI, double buffered, Z */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    False,              /* rgba? (false = color index) */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-};
-
-static __GLXvisualConfig NullConfig = {
-    -1,                 /* vid */
-    -1,                 /* class */
-    False,              /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    False,              /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE_EXT,       /* visualRating */
-    0,                  /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-};
-
-
-static int count_bits(unsigned int n)
-{
-   int bits = 0;
-
-   while (n > 0) {
-      if (n & 1) bits++;
-      n >>= 1;
-   }
-   return bits;
-}
-
-
-static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
-                         VisualID *defaultVisp,
-                         int ndepth, DepthPtr pdepth,
-                         int rootDepth)
-{
-    int numRGBconfigs;
-    int numCIconfigs;
-    int numVisuals = *nvisualp;
-    int numNewVisuals;
-    int numNewConfigs;
-    VisualPtr pVisual = *visualp;
-    VisualPtr pVisualNew = NULL;
-    VisualID *orig_vid = NULL;
-    __GLcontextModes *modes;
-    __GLXvisualConfig *pNewVisualConfigs = NULL;
-    void **glXVisualPriv;
-    void **pNewVisualPriv;
-    int found_default;
-    int i, j, k;
-
-    GLAQUA_DEBUG_MSG("init_visuals\n");
-
-    if (numConfigs > 0)
-        numNewConfigs = numConfigs;
-    else
-        numNewConfigs = NUM_FALLBACK_CONFIGS;
-
-    /* Alloc space for the list of new GLX visuals */
-    pNewVisualConfigs = (__GLXvisualConfig *)
-                     __glXMalloc(numNewConfigs * sizeof(__GLXvisualConfig));
-    if (!pNewVisualConfigs) {
-        return FALSE;
-    }
-
-    /* Alloc space for the list of new GLX visual privates */
-    pNewVisualPriv = (void **) __glXMalloc(numNewConfigs * sizeof(void *));
-    if (!pNewVisualPriv) {
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /*
-    ** If SetVisualConfigs was not called, then use default GLX
-    ** visual configs.
-    */
-    if (numConfigs == 0) {
-        memcpy(pNewVisualConfigs, FallbackConfigs,
-               NUM_FALLBACK_CONFIGS * sizeof(__GLXvisualConfig));
-        memset(pNewVisualPriv, 0, NUM_FALLBACK_CONFIGS * sizeof(void *));
-    }
-    else {
-        /* copy driver's visual config info */
-        for (i = 0; i < numConfigs; i++) {
-            pNewVisualConfigs[i] = visualConfigs[i];
-            pNewVisualPriv[i] = visualPrivates[i];
-        }
-    }
-
-    /* Count the number of RGB and CI visual configs */
-    numRGBconfigs = 0;
-    numCIconfigs = 0;
-    for (i = 0; i < numNewConfigs; i++) {
-        if (pNewVisualConfigs[i].rgba)
-            numRGBconfigs++;
-        else
-            numCIconfigs++;
-    }
-
-    /* Count the total number of visuals to compute */
-    numNewVisuals = 0;
-    for (i = 0; i < numVisuals; i++) {
-        int count;
-
-        count = ((pVisual[i].class == TrueColor ||
-                  pVisual[i].class == DirectColor)
-                ? numRGBconfigs : numCIconfigs);
-        if (count == 0)
-            count = 1;          /* preserve the existing visual */
-
-        numNewVisuals += count;
-    }
-
-    /* Reset variables for use with the next screen/driver's visual configs */
-    visualConfigs = NULL;
-    numConfigs = 0;
-
-    /* Alloc temp space for the list of orig VisualIDs for each new visual */
-    orig_vid = (VisualID *)__glXMalloc(numNewVisuals * sizeof(VisualID));
-    if (!orig_vid) {
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the list of glXVisuals */
-    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLcontextModes));
-    if (modes == NULL) {
-        __glXFree(orig_vid);
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the list of glXVisualPrivates */
-    glXVisualPriv = (void **)__glXMalloc(numNewVisuals * sizeof(void *));
-    if (!glXVisualPriv) {
-        _gl_context_modes_destroy( modes );
-        __glXFree(orig_vid);
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the new list of the X server's visuals */
-    pVisualNew = (VisualPtr)__glXMalloc(numNewVisuals * sizeof(VisualRec));
-    if (!pVisualNew) {
-        __glXFree(glXVisualPriv);
-        _gl_context_modes_destroy( modes );
-        __glXFree(orig_vid);
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Initialize the new visuals */
-    found_default = FALSE;
-    glAquaScreens[screenInfo.numScreens-1].modes = modes;
-    for (i = j = 0; i < numVisuals; i++) {
-        int is_rgb = (pVisual[i].class == TrueColor ||
-                  pVisual[i].class == DirectColor);
-
-        if (!is_rgb)
-        {
-            /* We don't support non-rgb visuals for GL. But we don't
-               want to remove them either, so just pass them through
-               with null glX configs */
-
-            pVisualNew[j] = pVisual[i];
-            pVisualNew[j].vid = FakeClientID(0);
-
-            /* Check for the default visual */
-            if (!found_default && pVisual[i].vid == *defaultVisp) {
-                *defaultVisp = pVisualNew[j].vid;
-                found_default = TRUE;
-            }
-
-            /* Save the old VisualID */
-            orig_vid[j] = pVisual[i].vid;
-
-            /* Initialize the glXVisual */
-            _gl_copy_visual_to_context_mode( modes, & NullConfig );
-            modes->visualID = pVisualNew[j].vid;
-
-            j++;
-
-            continue;
-        }
-
-        for (k = 0; k < numNewConfigs; k++) {
-            if (pNewVisualConfigs[k].rgba != is_rgb)
-                continue;
-
-            assert( modes != NULL );
-
-            /* Initialize the new visual */
-            pVisualNew[j] = pVisual[i];
-            pVisualNew[j].vid = FakeClientID(0);
-
-            /* Check for the default visual */
-            if (!found_default && pVisual[i].vid == *defaultVisp) {
-                *defaultVisp = pVisualNew[j].vid;
-                found_default = TRUE;
-            }
-
-            /* Save the old VisualID */
-            orig_vid[j] = pVisual[i].vid;
-
-            /* Initialize the glXVisual */
-            _gl_copy_visual_to_context_mode( modes, & pNewVisualConfigs[k] );
-            modes->visualID = pVisualNew[j].vid;
-
-            /*
-             * If the class is -1, then assume the X visual information
-             * is identical to what GLX needs, and take them from the X
-             * visual.  NOTE: if class != -1, then all other fields MUST
-             * be initialized.
-             */
-            if (modes->visualType == GLX_NONE) {
-                modes->visualType = _gl_convert_from_x_visual_type( pVisual[i].class );
-                modes->redBits    = count_bits(pVisual[i].redMask);
-                modes->greenBits  = count_bits(pVisual[i].greenMask);
-                modes->blueBits   = count_bits(pVisual[i].blueMask);
-                modes->alphaBits  = modes->alphaBits;
-                modes->redMask    = pVisual[i].redMask;
-                modes->greenMask  = pVisual[i].greenMask;
-                modes->blueMask   = pVisual[i].blueMask;
-                modes->alphaMask  = modes->alphaMask;
-                modes->rgbBits = (is_rgb)
-                    ? (modes->redBits + modes->greenBits +
-                       modes->blueBits + modes->alphaBits)
-                    : rootDepth;
-            }
-
-            /* Save the device-dependent private for this visual */
-            glXVisualPriv[j] = pNewVisualPriv[k];
-
-            j++;
-            modes = modes->next;
-        }
-    }
-
-    assert(j <= numNewVisuals);
-
-    /* Save the GLX visuals in the screen structure */
-    glAquaScreens[screenInfo.numScreens-1].num_vis = numNewVisuals;
-    glAquaScreens[screenInfo.numScreens-1].priv = glXVisualPriv;
-
-    /* Set up depth's VisualIDs */
-    for (i = 0; i < ndepth; i++) {
-        int numVids = 0;
-        VisualID *pVids = NULL;
-        int k, n = 0;
-
-        /* Count the new number of VisualIDs at this depth */
-        for (j = 0; j < pdepth[i].numVids; j++)
-            for (k = 0; k < numNewVisuals; k++)
-            if (pdepth[i].vids[j] == orig_vid[k])
-                numVids++;
-
-        /* Allocate a new list of VisualIDs for this depth */
-        pVids = (VisualID *)__glXMalloc(numVids * sizeof(VisualID));
-
-        /* Initialize the new list of VisualIDs for this depth */
-        for (j = 0; j < pdepth[i].numVids; j++)
-            for (k = 0; k < numNewVisuals; k++)
-            if (pdepth[i].vids[j] == orig_vid[k])
-                pVids[n++] = pVisualNew[k].vid;
-
-        /* Update this depth's list of VisualIDs */
-        __glXFree(pdepth[i].vids);
-        pdepth[i].vids = pVids;
-        pdepth[i].numVids = numVids;
-    }
-
-    /* Update the X server's visuals */
-    *nvisualp = numNewVisuals;
-    *visualp = pVisualNew;
-
-    /* Free the old list of the X server's visuals */
-    __glXFree(pVisual);
-
-    /* Clean up temporary allocations */
-    __glXFree(orig_vid);
-    __glXFree(pNewVisualPriv);
-    __glXFree(pNewVisualConfigs);
-
-    /* Free the private list created by DDX HW driver */
-    if (visualPrivates)
-        xfree(visualPrivates);
-    visualPrivates = NULL;
-
-    return TRUE;
-}
-
-/* based on code in i830_dri.c
-   This ends calling glAquaSetVisualConfigs to set the static
-   numconfigs, etc. */
-static void
-glAquaInitVisualConfigs(void)
-{
-    int                 lclNumConfigs     = 0;
-    __GLXvisualConfig  *lclVisualConfigs  = NULL;
-    void              **lclVisualPrivates = NULL;
-
-    int depth, aux, buffers, stencil, accum;
-    int i = 0;
-
-    GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs ");
-
-    /* count num configs:
-        2 Z buffer (0, 24 bit)
-        2 AUX buffer (0, 2)
-        2 buffers (single, double)
-        2 stencil (0, 8 bit)
-        2 accum (0, 64 bit)
-        = 32 configs */
-
-    lclNumConfigs = 2 * 2 * 2 * 2 * 2; /* 32 */
-
-    /* alloc */
-    lclVisualConfigs = xcalloc(sizeof(__GLXvisualConfig), lclNumConfigs);
-    lclVisualPrivates = xcalloc(sizeof(void *), lclNumConfigs);
-
-    /* fill in configs */
-    if (NULL != lclVisualConfigs) {
-        i = 0; /* current buffer */
-        for (depth = 0; depth < 2; depth++) {
-            for (aux = 0; aux < 2; aux++) {
-                for (buffers = 0; buffers < 2; buffers++) {
-                    for (stencil = 0; stencil < 2; stencil++) {
-                        for (accum = 0; accum < 2; accum++) {
-                            lclVisualConfigs[i].vid = -1;
-                            lclVisualConfigs[i].class = -1;
-                            lclVisualConfigs[i].rgba = TRUE;
-                            lclVisualConfigs[i].redSize = -1;
-                            lclVisualConfigs[i].greenSize = -1;
-                            lclVisualConfigs[i].blueSize = -1;
-                            lclVisualConfigs[i].redMask = -1;
-                            lclVisualConfigs[i].greenMask = -1;
-                            lclVisualConfigs[i].blueMask = -1;
-                            lclVisualConfigs[i].alphaMask = 0;
-                            if (accum) {
-                                lclVisualConfigs[i].accumRedSize = 16;
-                                lclVisualConfigs[i].accumGreenSize = 16;
-                                lclVisualConfigs[i].accumBlueSize = 16;
-                                lclVisualConfigs[i].accumAlphaSize = 16;
-                            }
-                            else {
-                                lclVisualConfigs[i].accumRedSize = 0;
-                                lclVisualConfigs[i].accumGreenSize = 0;
-                                lclVisualConfigs[i].accumBlueSize = 0;
-                                lclVisualConfigs[i].accumAlphaSize = 0;
-                            }
-                            lclVisualConfigs[i].doubleBuffer = buffers ? TRUE : FALSE;
-                            lclVisualConfigs[i].stereo = FALSE;
-                            lclVisualConfigs[i].bufferSize = -1;
-
-                            lclVisualConfigs[i].depthSize = depth? 24 : 0;
-                            lclVisualConfigs[i].stencilSize = stencil ? 8 : 0;
-                            lclVisualConfigs[i].auxBuffers = aux ? 2 : 0;
-                            lclVisualConfigs[i].level = 0;
-                            lclVisualConfigs[i].visualRating = GLX_NONE_EXT;
-                            lclVisualConfigs[i].transparentPixel = 0;
-                            lclVisualConfigs[i].transparentRed = 0;
-                            lclVisualConfigs[i].transparentGreen = 0;
-                            lclVisualConfigs[i].transparentBlue = 0;
-                            lclVisualConfigs[i].transparentAlpha = 0;
-                            lclVisualConfigs[i].transparentIndex = 0;
-                            i++;
-                        }
-                    }
-                }
-            }
-        }
-    }
-    if (i != lclNumConfigs)
-        GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs failed to alloc visual configs");
-
-    GlxSetVisualConfigs(lclNumConfigs, lclVisualConfigs, lclVisualPrivates);
-}
-
-
-static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
-                                   void **privates)
-{
-    GLAQUA_DEBUG_MSG("glAquaSetVisualConfigs\n");
-
-    numConfigs = nconfigs;
-    visualConfigs = configs;
-    visualPrivates = privates;
-}
-
-static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
-                              int *nvisualp, int *ndepthp,
-                              int *rootDepthp, VisualID *defaultVisp,
-                              unsigned long sizes, int bitsPerRGB)
-{
-    GLAQUA_DEBUG_MSG("glAquaInitVisuals\n");
-
-    if (numConfigs == 0) /* if no configs */
-        glAquaInitVisualConfigs(); /* ensure the visual configs are setup */
-
-    /*
-     * Setup the visuals supported by this particular screen.
-     */
-    return init_visuals(nvisualp, visualp, defaultVisp,
-                        *ndepthp, *depthp, *rootDepthp);
-}
-
-
-static void fixup_visuals(int screen)
-{
-    ScreenPtr pScreen = screenInfo.screens[screen];
-    glAquaScreenRec *pScr = &glAquaScreens[screen];
-    int j;
-    __GLcontextModes *modes;
-
-    GLAQUA_DEBUG_MSG("fixup_visuals\n");
-
-    for ( modes = pScr->modes ; modes != NULL ; modes = modes->next ) {
-        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
-        const int nplanes = (modes->rgbBits - modes->alphaBits);
-        const VisualPtr pVis = pScreen->visuals;
-
-        /* Find a visual that matches the GLX visual's class and size */
-        for (j = 0; j < pScreen->numVisuals; j++) {
-            if (pVis[j].class == vis_class &&
-            pVis[j].nplanes == nplanes) {
-
-            /* Fixup the masks */
-            modes->redMask   = pVis[j].redMask;
-            modes->greenMask = pVis[j].greenMask;
-            modes->blueMask  = pVis[j].blueMask;
-
-            /* Recalc the sizes */
-            modes->redBits   = count_bits(modes->redMask);
-            modes->greenBits = count_bits(modes->greenMask);
-            modes->blueBits  = count_bits(modes->blueMask);
-            }
-        }
-    }
-}
-
-static void init_screen_visuals(int screen)
-{
-    ScreenPtr pScreen = screenInfo.screens[screen];
-    __GLcontextModes *modes;
-    int *used;
-    int i, j;
-
-    GLAQUA_DEBUG_MSG("init_screen_visuals\n");
-
-    /* FIXME: Change 'used' to be a array of bits (rather than of ints),
-     * FIXME: create a stack array of 8 or 16 bytes.  If 'numVisuals' is less
-     * FIXME: than 64 or 128 the stack array can be used instead of calling
-     * FIXME: __glXMalloc / __glXFree.  If nothing else, convert 'used' to
-     * FIXME: array of bytes instead of ints!
-     */
-    used = (int *)__glXMalloc(pScreen->numVisuals * sizeof(int));
-    __glXMemset(used, 0, pScreen->numVisuals * sizeof(int));
-
-    i = 0;
-    for ( modes = glAquaScreens[screen].modes 
-          ; modes != NULL
-          ; modes = modes->next ) {
-        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
-        const int nplanes = (modes->rgbBits - modes->alphaBits);
-        const VisualPtr pVis = pScreen->visuals;
-
-        for (j = 0; j < pScreen->numVisuals; j++) {
-            if (pVis[j].class     == vis_class &&
-                pVis[j].nplanes   == nplanes &&
-                pVis[j].redMask   == modes->redMask &&
-                pVis[j].greenMask == modes->greenMask &&
-                pVis[j].blueMask  == modes->blueMask &&
-                !used[j]) {
-
-                    /* Set the VisualID */
-                    modes->visualID = pVis[j].vid;
-
-                    /* Mark this visual used */
-                    used[j] = 1;
-                    break;
-            }
-        }
-        if ( j == pScreen->numVisuals ) {
-            ErrorF("No matching visual for __GLcontextMode with "
-                   "visual class = %d (%d), nplanes = %u\n",
-                   vis_class, 
-                   (int)modes->visualType,
-                   (unsigned int)(modes->rgbBits - modes->alphaBits) );
-        }
-        else if ( modes->visualID == -1 ) {
-            FatalError( "Matching visual found, but visualID still -1!\n" );
-        }
-
-        i++;
-    }
-
-    __glXFree(used);
-}
-
-static Bool glAquaScreenProbe(int screen)
-{
-    ScreenPtr pScreen;
-    glAquaScreenRec *screenPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaScreenProbe\n");
-
-    /*
-     * Set up the current screen's visuals.
-     */
-    __glDDXScreenInfo.modes = glAquaScreens[screen].modes;
-    __glDDXScreenInfo.pVisualPriv = glAquaScreens[screen].priv;
-    __glDDXScreenInfo.numVisuals =
-        __glDDXScreenInfo.numUsableVisuals = glAquaScreens[screen].num_vis;
-
-    /*
-     * Set the current screen's createContext routine.  This could be
-     * wrapped by a DDX GLX context creation routine.
-     */
-    __glDDXScreenInfo.createContext = glAquaCreateContext;
-
-    /*
-     * The ordering of the rgb compenents might have been changed by the
-     * driver after mi initialized them.
-     */
-    fixup_visuals(screen);
-
-    /*
-     * Find the GLX visuals that are supported by this screen and create
-     * XMesa's visuals.
-     */
-    init_screen_visuals(screen);
-
-    /*
-     * Wrap RealizeWindow and UnrealizeWindow on this screen
-     */
-    pScreen = screenInfo.screens[screen];
-    screenPriv = &glAquaScreens[screen];
-    screenPriv->RealizeWindow = pScreen->RealizeWindow;
-    pScreen->RealizeWindow = glAquaRealizeWindow;
-    screenPriv->UnrealizeWindow = pScreen->UnrealizeWindow;
-    pScreen->UnrealizeWindow = glAquaUnrealizeWindow;
-
-    return TRUE;
-}
-
-
-static GLboolean glAquaResizeBuffers(__GLdrawableBuffer *buffer,
-                                     GLint x, GLint y,
-                                     GLuint width, GLuint height,
-                                     __GLdrawablePrivate *glPriv,
-                                     GLuint bufferMask)
-{
-    GLAquaDrawableRec *aquaPriv = (GLAquaDrawableRec *)glPriv->private;
-    __GLXdrawablePrivate *glxPriv = (__GLXdrawablePrivate *)glPriv->other;
-    __GLXcontext *gx;
-    __GLcontext *gc;
-
-    GLAQUA_DEBUG_MSG("glAquaResizeBuffers to (%d %d %d %d)\n", x, y, width, height);
-
-    // update all contexts that point at this drawable for drawing (hack?)
-    for (gx = glxPriv->drawGlxc; gx != NULL; gx = gx->nextDrawPriv) {
-        gc = (__GLcontext *)gx->gc;
-        attach(gc, glPriv);
-    }
-
-    // update all contexts that point at this drawable for reading (hack?)
-    for (gx = glxPriv->readGlxc; gx != NULL; gx = gx->nextReadPriv) {
-        gc = (__GLcontext *)gx->gc;
-        attach(gc, glPriv);
-    }
-
-    return aquaPriv->resize(buffer, x, y, width, height, glPriv, bufferMask);
-}
-
-
-static GLboolean glAquaSwapBuffers(__GLXdrawablePrivate *glxPriv)
-{
-    // fixme AGL software renderer will use properties of current QD port (bad)
-
-    // swap buffers on only *one* of the contexts
-    // (e.g. the last one for drawing)
-    __GLcontext *gc = (__GLcontext *)glxPriv->drawGlxc->gc;
-    if (gc && gc->ctx) aglSwapBuffers(gc->ctx);
-
-    return GL_TRUE;
-}
-
-static void glAquaDestroyDrawablePrivate(__GLdrawablePrivate *glPriv)
-{
-    GLAQUA_DEBUG_MSG("glAquaDestroyDrawablePrivate\n");
-
-    free(glPriv->private);
-    glPriv->private = NULL;
-}
-
-static void glAquaCreateBuffer(__GLXdrawablePrivate *glxPriv)
-{
-    GLAquaDrawableRec *aquaPriv = malloc(sizeof(GLAquaDrawableRec));
-    __GLdrawablePrivate *glPriv = &glxPriv->glPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaCreateBuffer\n");
-
-    // replace swapBuffers (original is never called)
-    glxPriv->swapBuffers = glAquaSwapBuffers;
-
-    // wrap front buffer resize
-    aquaPriv->resize = glPriv->frontBuffer.resize;
-    glPriv->frontBuffer.resize = glAquaResizeBuffers;
-
-    // stash private data
-    glPriv->private = aquaPriv;
-    glPriv->freePrivate = glAquaDestroyDrawablePrivate;
-}
-
-
-static void glAquaResetExtension(void)
-{
-    GLAQUA_DEBUG_MSG("glAquaResetExtension\n");
-    aglResetLibrary();
-}
-
-
-
-// Extra goodies for glx
-
-GLuint __glFloorLog2(GLuint val)
-{
-    int c = 0;
-
-    while (val > 1) {
-        c++;
-        val >>= 1;
-    }
-    return c;
-}
commit f6e22d69af6bc8f63c3a46535a09e217696a679f
Author: Hans de Goede <j.w.r.degoede at hhs.nl>
Date:   Wed Apr 23 12:28:30 2008 -0400

    Prefer glxvisuals with stencil buffer for default visuals
    
    The first fbconfig which has a depthbuffer > 0  and doublebuf is choosen
    when associating fbconfigs with the visuals, indepenent of stencil bits.
    This happens to work ok on intel as there all fbconfigs with a
    depthbuffer > 0 also have stencil bits.
    
    This patch fixes this by first trying to get a fbconfig for default X visuals
    with both stencilbuf, depthbuf and doublebuffering, and if that fails fallback
    to trying to get one with only a depthbuf and doublebuffering.

diff --git a/GL/glx/glxscreens.c b/GL/glx/glxscreens.c
index 41ee029..5859de0 100644
--- a/GL/glx/glxscreens.c
+++ b/GL/glx/glxscreens.c
@@ -437,6 +437,7 @@ initGlxVisual(VisualPtr visual, __GLXconfig *config)
 typedef struct {
     GLboolean doubleBuffer;
     GLboolean depthBuffer;
+    GLboolean stencilBuffer;
 } FBConfigTemplateRec, *FBConfigTemplatePtr;
 
 static __GLXconfig *
@@ -453,6 +454,8 @@ pickFBConfig(__GLXscreen *pGlxScreen, FBConfigTemplatePtr template, int class)
 	    continue;
 	if ((config->depthBits > 0) != template->depthBuffer)
 	    continue;
+	if ((config->stencilBits > 0) != template->stencilBuffer)
+	    continue;
 
 	return config;
     }
@@ -466,8 +469,9 @@ addMinimalSet(__GLXscreen *pGlxScreen)
     __GLXconfig *config;
     VisualPtr visuals;
     int i, j;
-    FBConfigTemplateRec best = { GL_TRUE, GL_TRUE };
-    FBConfigTemplateRec minimal = { GL_FALSE, GL_FALSE };
+    FBConfigTemplateRec best = { GL_TRUE, GL_TRUE, GL_TRUE };
+    FBConfigTemplateRec good = { GL_TRUE, GL_TRUE, GL_FALSE };
+    FBConfigTemplateRec minimal = { GL_FALSE, GL_FALSE, GL_FALSE };
 
     pGlxScreen->visuals = xcalloc(pGlxScreen->pScreen->numVisuals,
 				  sizeof (__GLXconfig *));
@@ -480,8 +484,11 @@ addMinimalSet(__GLXscreen *pGlxScreen)
     for (i = 0, j = 0; i < pGlxScreen->pScreen->numVisuals; i++) {
 	if (visuals[i].nplanes == 32)
 	    config = pickFBConfig(pGlxScreen, &minimal, visuals[i].class);
-	else
+	else {
 	    config = pickFBConfig(pGlxScreen, &best, visuals[i].class);
+	    if (config == NULL)
+		config = pickFBConfig(pGlxScreen, &good, visuals[i].class);
+        }
 	if (config == NULL)
 	    config = pGlxScreen->fbconfigs;
 	if (config == NULL)
commit 00effad583713e882c3f2518bcd3da51bf4db716
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:46:30 2008 +0300

    xephyr: XEPHYR_DRI is identical to XF86DRI

diff --git a/configure.ac b/configure.ac
index 21c1d91..51ab4c6 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1925,11 +1925,6 @@ if test "$KDRIVE" = yes; then
     if test "x$XEPHYR" = xauto; then
         XEPHYR=$xephyr
     fi
-    XEPHYR_DRI=no
-    if test x$XEPHYR = xyes -a x$DRI = xyes && test "x$GLX" = xyes; then
-        XEPHYR_DRI=yes
-        AC_DEFINE(XEPHYR_DRI,1,[enable DRI extension in xephyr])
-    fi
 
     # Xephyr needs nanosleep() which is in librt on Solaris
     AC_CHECK_FUNC([nanosleep], [],
@@ -1984,7 +1979,6 @@ AM_CONDITIONAL(KDRIVEFBDEV, [test "x$XFBDEV" = xyes])
 AM_CONDITIONAL(XSDLSERVER, [test x"$XSDL" = xyes])
 AM_CONDITIONAL(XEPHYR, [test "x$KDRIVE" = xyes && test "x$XEPHYR" = xyes])
 AM_CONDITIONAL(BUILD_KDRIVEFBDEVLIB, [test "x$KDRIVE" = xyes && test "x$KDRIVEFBDEVLIB" = xyes])
-AM_CONDITIONAL(XEPHYR_HAS_DRI, [test x$XEPHYR_DRI = xyes])
 AM_CONDITIONAL(XFAKESERVER, [test "x$KDRIVE" = xyes && test "x$XFAKE" = xyes])
 
 dnl these only go in xkb-config.h (which is shared by the Xorg and Xnest servers)
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index 90fd4d8..5269876 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -11,7 +11,7 @@ if XV
 LIBXEPHYR_HOSTXV=libxephyr-hostxv.a
 endif
 
-if XEPHYR_HAS_DRI
+if DRI
 LIBXEPHYR_HOSTDRI=libxephyr-hostdri.a
 endif
 
@@ -53,7 +53,7 @@ if XV
 libxephyr_hostxv_a_SOURCES = $(HOSTVIDEO_SRCS)
 endif
 
-if XEPHYR_HAS_DRI
+if DRI
 libxephyr_hostdri_a_SOURCES = $(HOSTDRI_SRCS)
 endif
 
diff --git a/hw/kdrive/ephyr/XF86dri.c b/hw/kdrive/ephyr/XF86dri.c
index a5fc9bd..be65edf 100644
--- a/hw/kdrive/ephyr/XF86dri.c
+++ b/hw/kdrive/ephyr/XF86dri.c
@@ -46,8 +46,6 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #include <kdrive-config.h>
 #endif
 
-#ifdef XEPHYR_DRI
-
 /* THIS IS NOT AN X CONSORTIUM STANDARD */
 
 #define NEED_REPLIES
@@ -639,5 +637,3 @@ XF86DRICloseFullScreen(Display *dpy, int screen, Drawable drawable)
     (void) drawable;
     return True;
 }
-#endif /*EPHYR_DRI*/
-
diff --git a/hw/kdrive/ephyr/ephyr.c b/hw/kdrive/ephyr/ephyr.c
index b02f990..d69e148 100644
--- a/hw/kdrive/ephyr/ephyr.c
+++ b/hw/kdrive/ephyr/ephyr.c
@@ -32,11 +32,11 @@
 #include "scrnintstr.h"
 #include "ephyrlog.h"
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 #include "ephyrdri.h"
 #include "ephyrdriext.h"
 #include "ephyrglxext.h"
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 
 extern int KdTsPhyScreen;
 #ifdef GLXEXT
@@ -631,7 +631,7 @@ ephyrInitScreen (ScreenPtr pScreen)
   }
 #endif /*XV*/
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
   if (!ephyrNoDRI && !hostx_has_dri ()) {
       EPHYR_LOG ("host x does not support DRI. Disabling DRI forwarding\n") ;
       ephyrNoDRI = TRUE ;
@@ -841,7 +841,7 @@ miPointerScreenFuncRec ephyrPointerScreenFuncs =
   ephyrWarpCursor
 };
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 /**
  * find if the remote window denoted by a_remote
  * is paired with an internal Window within the Xephyr server.
@@ -873,7 +873,7 @@ ephyrExposePairedWindow (int a_remote)
     screen->WindowExposures (pair->local, &reg, NullRegion);
     REGION_UNINIT (screen, &reg);
 }
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 
 void
 ephyrPoll(void)
@@ -908,14 +908,14 @@ ephyrPoll(void)
             else
               {
                   int x=0, y=0;
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
                   EphyrWindowPair *pair = NULL;
 #endif
                   EPHYR_LOG ("enqueuing mouse motion:%d\n", ephyrCurScreen) ;
                   x = ev.data.mouse_motion.x;
                   y = ev.data.mouse_motion.y;
                   EPHYR_LOG ("initial (x,y):(%d,%d)\n", x, y) ;
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
                   EPHYR_LOG ("is this window peered by a gl drawable ?\n") ;
                   if (findWindowPairFromRemote (ev.data.mouse_motion.window,
                                                 &pair))
@@ -972,7 +972,7 @@ ephyrPoll(void)
 	  KdEnqueueKeyboardEvent (ephyrKbd, ev.data.key_up.scancode, TRUE);
 	  break;
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 	case EPHYR_EV_EXPOSE:
 	  /*
 	   * We only receive expose events when the expose event have
@@ -982,7 +982,7 @@ ephyrPoll(void)
 	   */
 	  ephyrExposePairedWindow (ev.data.expose.window);
 	  break;
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 
 	default:
 	  break;
diff --git a/hw/kdrive/ephyr/ephyrdri.c b/hw/kdrive/ephyr/ephyrdri.c
index bb4f6a1..9aa68b1 100644
--- a/hw/kdrive/ephyr/ephyrdri.c
+++ b/hw/kdrive/ephyr/ephyrdri.c
@@ -29,11 +29,8 @@
 #include <kdrive-config.h>
 #endif
 
-#ifdef XEPHYR_DRI
-
 #include <X11/Xutil.h>
 #include <X11/Xlibint.h>
-/*#define _XF86DRI_SERVER_*/
 #include <GL/glx.h>
 #include "xf86dri.h"
 #include "hostx.h"
@@ -287,5 +284,3 @@ ephyrDRIGetDeviceInfo (int a_screen,
     EPHYR_LOG ("leave:%d\n", is_ok) ;
     return is_ok ;
 }
-#endif /*EPHYR_DRI*/
-
diff --git a/hw/kdrive/ephyr/ephyrdriext.c b/hw/kdrive/ephyr/ephyrdriext.c
index fafe56d..883e330 100644
--- a/hw/kdrive/ephyr/ephyrdriext.c
+++ b/hw/kdrive/ephyr/ephyrdriext.c
@@ -32,8 +32,6 @@
 #include <kdrive-config.h>
 #endif
 
-#ifdef XEPHYR_DRI
-
 #include <string.h>
 
 #define NEED_REPLIES
@@ -1439,5 +1437,3 @@ SProcXF86DRIDispatch (register ClientPtr client)
         }
     }
 }
-
-#endif /*XEPHYR_DRI*/
diff --git a/hw/kdrive/ephyr/ephyrglxext.c b/hw/kdrive/ephyr/ephyrglxext.c
index 43a634d..2e08e39 100644
--- a/hw/kdrive/ephyr/ephyrglxext.c
+++ b/hw/kdrive/ephyr/ephyrglxext.c
@@ -42,8 +42,6 @@
 #include "hostx.h"
 
 
-#ifdef XEPHYR_DRI
-
 #ifndef TRUE
 #define TRUE 1
 #endif
@@ -727,6 +725,3 @@ ephyrGLXIsDirectSwap (__GLXclientState *a_cl, GLbyte *a_pc)
 {
     return ephyrGLXIsDirectReal (a_cl, a_pc, TRUE) ;
 }
-
-#endif /*XEPHYR_DRI*/
-
diff --git a/hw/kdrive/ephyr/ephyrhostglx.c b/hw/kdrive/ephyr/ephyrhostglx.c
index f5db5be..6d783d2 100644
--- a/hw/kdrive/ephyr/ephyrhostglx.c
+++ b/hw/kdrive/ephyr/ephyrhostglx.c
@@ -41,7 +41,6 @@
 #include "ephyrlog.h"
 #include "hostx.h"
 
-#ifdef XEPHYR_DRI
 enum VisualConfRequestType {
     EPHYR_GET_FB_CONFIG,
     EPHYR_VENDOR_PRIV_GET_FB_CONFIG_SGIX,
@@ -687,6 +686,3 @@ out:
     EPHYR_LOG ("leave\n") ;
     return is_ok ;
 }
-
-#endif /*XEPHYR_DRI*/
-
diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index 1a71d06..74f9f16 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -45,12 +45,12 @@
 #include <X11/keysym.h>
 #include <X11/extensions/XShm.h>
 #include <X11/extensions/shape.h>
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 #include <GL/glx.h>
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 #include "ephyrlog.h"
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 extern Bool XF86DRIQueryExtension (Display *dpy,
                                    int *event_basep,
                                    int *error_basep);
@@ -1315,7 +1315,7 @@ hostx_has_xshape (void)
     return TRUE;
 }
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 typedef struct {
     int is_valid ;
     int local_id ;
@@ -1418,5 +1418,4 @@ hostx_has_glx (void)
     return TRUE ;
 }
 
-#endif /*XEPHYR_DRI*/
-
+#endif /* XF86DRI */
diff --git a/hw/kdrive/ephyr/hostx.h b/hw/kdrive/ephyr/hostx.h
index 47ba61b..c1b1958 100644
--- a/hw/kdrive/ephyr/hostx.h
+++ b/hw/kdrive/ephyr/hostx.h
@@ -244,7 +244,7 @@ int hostx_set_window_clipping_rectangles (int a_window,
                                           int a_num_rects) ;
 int hostx_has_xshape (void) ;
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 int hostx_lookup_peer_window (void *a_local_window,
                               int *a_host_peer /*out parameter*/) ;
 int
@@ -256,6 +256,6 @@ hostx_get_resource_id_peer (int a_local_resource_id,
 int hostx_has_dri (void) ;
 
 int hostx_has_glx (void) ;
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 
 #endif /*_XLIBS_STUFF_H_*/
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 1779082..135d3d8 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -419,8 +419,6 @@
 /* Support DRI extension */
 #undef XF86DRI
 
-#undef XEPHYR_DRI
-
 /* Build DRI2 extension */
 #undef DRI2
 
commit 6a9f7f28ec455d2879ca1a315ce77c48af49e7f4
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:46:15 2008 +0300

    xephyr: sync with mesa

diff --git a/hw/kdrive/ephyr/GL/internal/dri_interface.h b/hw/kdrive/ephyr/GL/internal/dri_interface.h
deleted file mode 100644
index 8d24e31..0000000
--- a/hw/kdrive/ephyr/GL/internal/dri_interface.h
+++ /dev/null
@@ -1,517 +0,0 @@
-/*
- * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
- * (C) Copyright IBM Corporation 2004
- * 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
- * on 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
- * THE COPYRIGHT HOLDERS AND/OR THEIR 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.
- */
-
-/**
- * \file dri_interface.h
- *
- * This file contains all the types and functions that define the interface
- * between a DRI driver and driver loader.  Currently, the most common driver
- * loader is the XFree86 libGL.so.  However, other loaders do exist, and in
- * the future the server-side libglx.a will also be a loader.
- * 
- * \author Kevin E. Martin <kevin at precisioninsight.com>
- * \author Ian Romanick <idr at us.ibm.com>
- */
-
-#ifndef DRI_INTERFACE_H
-#define DRI_INTERFACE_H
-
-#include <GL/internal/glcore.h>
-#include <drm.h>
-
-/**
- * \name DRI interface structures
- *
- * The following structures define the interface between the GLX client
- * side library and the DRI (direct rendering infrastructure).
- */
-/*@{*/
-typedef struct __DRIdisplayRec  __DRIdisplay;
-typedef struct __DRIscreenRec   __DRIscreen;
-typedef struct __DRIcontextRec  __DRIcontext;
-typedef struct __DRIdrawableRec __DRIdrawable;
-typedef struct __DRIdriverRec   __DRIdriver;
-typedef struct __DRIframebufferRec __DRIframebuffer;
-typedef struct __DRIversionRec     __DRIversion;
-typedef struct __DRIinterfaceMethodsRec  __DRIinterfaceMethods;
-typedef unsigned long __DRIid;
-typedef void __DRInativeDisplay;
-/*@}*/
-
-
-/**
- * \name Functions provided by the driver loader.
- */
-/*@{*/
-/**
- * Type of a pointer to \c glXGetScreenDriver, as returned by
- * \c glXGetProcAddress.  This function is used to get the name of the DRI
- * driver for the specified screen of the specified display.  The driver
- * name is typically used with \c glXGetDriverConfig.
- *
- * \sa glXGetScreenDriver, glXGetProcAddress, glXGetDriverConfig
- */
-typedef const char * (* PFNGLXGETSCREENDRIVERPROC) (__DRInativeDisplay *dpy, int scrNum);
-
-/**
- * Type of a pointer to \c glXGetDriverConfig, as returned by
- * \c glXGetProcAddress.  This function is used to get the XML document
- * describing the configuration options available for the specified driver.
- *
- * \sa glXGetDriverConfig, glXGetProcAddress, glXGetScreenDriver
- */
-typedef const char * (* PFNGLXGETDRIVERCONFIGPROC) (const char *driverName);
-
-/**
- * Type of a pointer to \c glxEnableExtension, as returned by
- * \c __DRIinterfaceMethods::getProcAddress.  This function is used to enable
- * a GLX extension on the specified screen.
- */
-typedef void (* PFNGLXSCRENABLEEXTENSIONPROC) ( void *psc, const char * name );
-/*@}*/
-
-
-/**
- * \name Functions and data provided by the driver.
- */
-/*@{*/
-
-typedef void *(CREATENEWSCREENFUNC)(__DRInativeDisplay *dpy, int scrn,
-    __DRIscreen *psc, const __GLcontextModes * modes,
-    const __DRIversion * ddx_version, const __DRIversion * dri_version,
-    const __DRIversion * drm_version, const __DRIframebuffer * frame_buffer,
-    void * pSAREA, int fd, int internal_api_version,
-    const __DRIinterfaceMethods * interface,
-    __GLcontextModes ** driver_modes);
-typedef CREATENEWSCREENFUNC* PFNCREATENEWSCREENFUNC;
-extern CREATENEWSCREENFUNC __driCreateNewScreen_20050727;
-
-
-/**
- * XML document describing the configuration options supported by the
- * driver.
- */
-extern const char __driConfigOptions[];
-
-/*@}*/
-
-
-/**
- * Stored version of some component (i.e., server-side DRI module, kernel-side
- * DRM, etc.).
- * 
- * \todo
- * There are several data structures that explicitly store a major version,
- * minor version, and patch level.  These structures should be modified to
- * have a \c __DRIversionRec instead.
- */
-struct __DRIversionRec {
-    int    major;        /**< Major version number. */
-    int    minor;        /**< Minor version number. */
-    int    patch;        /**< Patch-level. */
-};
-
-
-typedef void (*__DRIfuncPtr)(void);
-
-struct __DRIinterfaceMethodsRec {
-    /**
-     * Get pointer to named function.
-     */
-    __DRIfuncPtr (*getProcAddress)( const char * proc_name );
-
-    /**
-     * Create a list of \c __GLcontextModes structures.
-     */
-    __GLcontextModes * (*createContextModes)(unsigned count,
-        size_t minimum_bytes_per_struct);
-
-    /**
-     * Destroy a list of \c __GLcontextModes structures.
-     *
-     * \todo
-     * Determine if the drivers actually need to call this.
-     */
-    void (*destroyContextModes)( __GLcontextModes * modes );
-
-    /**
-     * Get the \c __DRIscreen for a given display and screen number.
-     */
-    __DRIscreen *(*getScreen)(__DRInativeDisplay *dpy, int screenNum);
-
-
-    /**
-     * \name Client/server protocol functions.
-     *
-     * These functions implement the DRI client/server protocol for
-     * context and drawable operations.  Platforms that do not implement
-     * the wire protocol (e.g., EGL) will implement glorified no-op functions.
-     */
-    /*@{*/
-    /**
-     * Determine if the specified window ID still exists.
-     * 
-     * \note
-     * Implementations may assume that the driver will only pass an ID into
-     * this function that actually corresponds to a window.  On
-     * implementations where windows can only be destroyed by the DRI driver
-     * (e.g., EGL), this function is allowed to always return \c GL_TRUE.
-     */
-    GLboolean (*windowExists)(__DRInativeDisplay *dpy, __DRIid draw);
-
-    /**
-     * Create the server-side portion of the GL context.
-     */
-    GLboolean (* createContext)( __DRInativeDisplay *dpy, int screenNum,
-        int configID, void * contextID, drm_context_t * hw_context );
-
-    /**
-     * Destroy the server-side portion of the GL context.
-     */
-    GLboolean (* destroyContext)( __DRInativeDisplay *dpy, int screenNum,
-        __DRIid context );
-
-    /**
-     * Create the server-side portion of the drawable.
-     */
-    GLboolean (*createDrawable)( __DRInativeDisplay * ndpy, int screen,
-        __DRIid drawable, drm_drawable_t * hHWDrawable );
-
-    /**
-     * Destroy the server-side portion of the drawable.
-     */
-    GLboolean (*destroyDrawable)( __DRInativeDisplay * ndpy, int screen,
-        __DRIid drawable );
-
-    /**
-     * This function is used to get information about the position, size, and
-     * clip rects of a drawable.
-     */
-    GLboolean (* getDrawableInfo) ( __DRInativeDisplay *dpy, int scrn,
-        __DRIid draw, unsigned int * index, unsigned int * stamp,
-        int * x, int * y, int * width, int * height,
-        int * numClipRects, drm_clip_rect_t ** pClipRects,
-        int * backX, int * backY,
-        int * numBackClipRects, drm_clip_rect_t ** pBackClipRects );
-    /*@}*/
-
-
-    /**
-     * \name Timing related functions.
-     */
-    /*@{*/
-    /**
-     * Get the 64-bit unadjusted system time (UST).
-     */
-    int (*getUST)(int64_t * ust);
-
-    /**
-     * Get the media stream counter (MSC) rate.
-     * 
-     * Matching the definition in GLX_OML_sync_control, this function returns
-     * the rate of the "media stream counter".  In practical terms, this is
-     * the frame refresh rate of the display.
-     */
-    GLboolean (*getMSCRate)(__DRInativeDisplay * dpy, __DRIid drawable,
-        int32_t * numerator, int32_t * denominator);
-    /*@}*/
-
-    /**
-     * Reports areas of the given drawable which have been modified by the
-     * driver.
-     *
-     * \param drawable which the drawing was done to.
-     * \param rects rectangles affected, with the drawable origin as the
-     *	      origin.
-     * \param x X offset of the drawable within the screen (used in the
-     *	      front_buffer case)
-     * \param y Y offset of the drawable within the screen.
-     * \param front_buffer boolean flag for whether the drawing to the
-     * 	      drawable was actually done directly to the front buffer (instead
-     *	      of backing storage, for example)
-     */
-    void (*reportDamage)(__DRInativeDisplay * dpy, int screen,
-			 __DRIid drawable,
-			 int x, int y,
-			 drm_clip_rect_t *rects, int num_rects,
-			 int front_buffer);
-};
-
-   
-/**
- * Framebuffer information record.  Used by libGL to communicate information
- * about the framebuffer to the driver's \c __driCreateNewScreen function.
- * 
- * In XFree86, most of this information is derrived from data returned by
- * calling \c XF86DRIGetDeviceInfo.
- *
- * \sa XF86DRIGetDeviceInfo __DRIdisplayRec::createNewScreen
- *     __driUtilCreateNewScreen CallCreateNewScreen
- *
- * \bug This structure could be better named.
- */
-struct __DRIframebufferRec {
-    unsigned char *base;    /**< Framebuffer base address in the CPU's
-			     * address space.  This value is calculated by
-			     * calling \c drmMap on the framebuffer handle
-			     * returned by \c XF86DRIGetDeviceInfo (or a
-			     * similar function).
-			     */
-    int size;               /**< Framebuffer size, in bytes. */
-    int stride;             /**< Number of bytes from one line to the next. */
-    int width;              /**< Pixel width of the framebuffer. */
-    int height;             /**< Pixel height of the framebuffer. */
-    int dev_priv_size;      /**< Size of the driver's dev-priv structure. */
-    void *dev_priv;         /**< Pointer to the driver's dev-priv structure. */
-};
-
-
-/**
- * Screen dependent methods.  This structure is initialized during the
- * \c __DRIdisplayRec::createScreen call.
- */
-struct __DRIscreenRec {
-    /**
-     * Method to destroy the private DRI screen data.
-     */
-    void (*destroyScreen)(__DRInativeDisplay *dpy, int scrn, void *screenPrivate);
-
-    /**
-     * Method to create the private DRI drawable data and initialize the
-     * drawable dependent methods.
-     */
-    void *(*createNewDrawable)(__DRInativeDisplay *dpy, const __GLcontextModes *modes,
-			       __DRIid draw, __DRIdrawable *pdraw,
-			       int renderType, const int *attrs);
-
-    /**
-     * Method to return a pointer to the DRI drawable data.
-     */
-    __DRIdrawable *(*getDrawable)(__DRInativeDisplay *dpy, __DRIid draw,
-				  void *drawablePrivate);
-
-    /**
-     * Opaque pointer to private per screen direct rendering data.  \c NULL
-     * if direct rendering is not supported on this screen.  Never
-     * dereferenced in libGL.
-     */
-    void *private;
-
-    /**
-     * Get the number of vertical refreshes since some point in time before
-     * this function was first called (i.e., system start up).
-     * 
-     * \since Internal API version 20030317.
-     */
-    int (*getMSC)( void *screenPrivate, int64_t *msc );
-
-    /**
-     * Opaque pointer that points back to the containing 
-     * \c __GLXscreenConfigs.  This data structure is shared with DRI drivers
-     * but \c __GLXscreenConfigs is not. However, they are needed by some GLX
-     * functions called by DRI drivers.
-     *
-     * \since Internal API version 20030813.
-     */
-    void *screenConfigs;
-
-    /**
-     * Functions associated with MESA_allocate_memory.
-     *
-     * \since Internal API version 20030815.
-     */
-    /*@{*/
-    void *(*allocateMemory)(__DRInativeDisplay *dpy, int scrn, GLsizei size,
-			    GLfloat readfreq, GLfloat writefreq,
-			    GLfloat priority);
-   
-    void (*freeMemory)(__DRInativeDisplay *dpy, int scrn, GLvoid *pointer);
-   
-    GLuint (*memoryOffset)(__DRInativeDisplay *dpy, int scrn, const GLvoid *pointer);
-    /*@}*/
-
-    /**
-     * Method to create the private DRI context data and initialize the
-     * context dependent methods.
-     *
-     * \since Internal API version 20031201.
-     */
-    void * (*createNewContext)(__DRInativeDisplay *dpy, const __GLcontextModes *modes,
-			       int render_type,
-			       void *sharedPrivate, __DRIcontext *pctx);
-
-    /**
-     * Method to override base texture image with a driver specific 'offset'.
-     * The depth passed in allows e.g. to ignore the alpha channel of texture
-     * images where the non-alpha components don't occupy a whole texel.
-     *
-     * For GLX_EXT_texture_from_pixmap with AIGLX.
-     *
-     * \since Internal API version 20070121.
-     */
-    void (*setTexOffset)(__DRIcontext *pDRICtx, GLint texname,
-			 unsigned long long offset, GLint depth, GLuint pitch);
-};
-
-/**
- * Context dependent methods.  This structure is initialized during the
- * \c __DRIscreenRec::createContext call.
- */
-struct __DRIcontextRec {
-    /**
-     * Method to destroy the private DRI context data.
-     */
-    void (*destroyContext)(__DRInativeDisplay *dpy, int scrn, void *contextPrivate);
-
-    /**
-     * Opaque pointer to private per context direct rendering data.
-     * \c NULL if direct rendering is not supported on the display or
-     * screen used to create this context.  Never dereferenced in libGL.
-     */
-    void *private;
-
-    /**
-     * Pointer to the mode used to create this context.
-     *
-     * \since Internal API version 20040317.
-     */
-    const __GLcontextModes * mode;
-
-    /**
-     * Method to bind a DRI drawable to a DRI graphics context.
-     *
-     * \since Internal API version 20050727.
-     */
-    GLboolean (*bindContext)(__DRInativeDisplay *dpy, int scrn, __DRIid draw,
-			 __DRIid read, __DRIcontext *ctx);
-
-    /**
-     * Method to unbind a DRI drawable from a DRI graphics context.
-     *
-     * \since Internal API version 20050727.
-     */
-    GLboolean (*unbindContext)(__DRInativeDisplay *dpy, int scrn, __DRIid draw,
-			   __DRIid read, __DRIcontext *ctx);
-};
-
-/**
- * Drawable dependent methods.  This structure is initialized during the
- * \c __DRIscreenRec::createDrawable call.  \c createDrawable is not called
- * by libGL at this time.  It's currently used via the dri_util.c utility code
- * instead.
- */
-struct __DRIdrawableRec {
-    /**
-     * Method to destroy the private DRI drawable data.
-     */
-    void (*destroyDrawable)(__DRInativeDisplay *dpy, void *drawablePrivate);
-
-    /**
-     * Method to swap the front and back buffers.
-     */
-    void (*swapBuffers)(__DRInativeDisplay *dpy, void *drawablePrivate);
-
-    /**
-     * Opaque pointer to private per drawable direct rendering data.
-     * \c NULL if direct rendering is not supported on the display or
-     * screen used to create this drawable.  Never dereferenced in libGL.
-     */
-    void *private;
-
-    /**
-     * Get the number of completed swap buffers for this drawable.
-     *
-     * \since Internal API version 20030317.
-     */
-    int (*getSBC)(__DRInativeDisplay *dpy, void *drawablePrivate, int64_t *sbc );
-
-    /**
-     * Wait for the SBC to be greater than or equal target_sbc.
-     *
-     * \since Internal API version 20030317.
-     */
-    int (*waitForSBC)( __DRInativeDisplay * dpy, void *drawablePriv,
-		       int64_t target_sbc,
-		       int64_t * msc, int64_t * sbc );
-
-    /**
-     * Wait for the MSC to equal target_msc, or, if that has already passed,
-     * the next time (MSC % divisor) is equal to remainder.  If divisor is
-     * zero, the function will return as soon as MSC is greater than or equal
-     * to target_msc.
-     * 
-     * \since Internal API version 20030317.
-     */
-    int (*waitForMSC)( __DRInativeDisplay * dpy, void *drawablePriv,
-		       int64_t target_msc, int64_t divisor, int64_t remainder,
-		       int64_t * msc, int64_t * sbc );
-
-    /**
-     * Like \c swapBuffers, but does NOT have an implicit \c glFlush.  Once
-     * rendering is complete, waits until MSC is equal to target_msc, or
-     * if that has already passed, waits until (MSC % divisor) is equal
-     * to remainder.  If divisor is zero, the swap will happen as soon as
-     * MSC is greater than or equal to target_msc.
-     * 
-     * \since Internal API version 20030317.
-     */
-    int64_t (*swapBuffersMSC)(__DRInativeDisplay *dpy, void *drawablePrivate,
-			      int64_t target_msc,
-			      int64_t divisor, int64_t remainder);
-
-    /**
-     * Enable or disable frame usage tracking.
-     * 
-     * \since Internal API version 20030317.
-     */
-    int (*frameTracking)(__DRInativeDisplay *dpy, void *drawablePrivate, GLboolean enable);
-
-    /**
-     * Retrieve frame usage information.
-     * 
-     * \since Internal API version 20030317.
-     */
-    int (*queryFrameTracking)(__DRInativeDisplay *dpy, void *drawablePrivate,
-			      int64_t * sbc, int64_t * missedFrames,
-			      float * lastMissedUsage, float * usage );
-
-    /**
-     * Used by drivers that implement the GLX_SGI_swap_control or
-     * GLX_MESA_swap_control extension.
-     *
-     * \since Internal API version 20030317.
-     */
-    unsigned swap_interval;
-
-    /**
-     * Used by drivers that implement the GLX_MESA_copy_sub_buffer extension.
-     *
-     * \since Internal API version 20060314.
-     */
-    void (*copySubBuffer)(__DRInativeDisplay *dpy, void *drawablePrivate,
-			  int x, int y, int w, int h);
-};
-
-#endif
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index d13bbae..90fd4d8 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -34,6 +34,7 @@ HOSTDRI_SRCS =			\
 	ephyrdri.c		\
 	ephyrdri.h		\
 	XF86dri.c		\
+	xf86dri.h		\
 	ephyrglxext.c		\
 	ephyrglxext.h		\
 	ephyrhostglx.c		\
diff --git a/hw/kdrive/ephyr/XF86dri.c b/hw/kdrive/ephyr/XF86dri.c
index e656ff5..a5fc9bd 100644
--- a/hw/kdrive/ephyr/XF86dri.c
+++ b/hw/kdrive/ephyr/XF86dri.c
@@ -55,9 +55,8 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #include <X11/extensions/Xext.h>
 #include <X11/extensions/extutil.h>
 #include <GL/glx.h>
-#include <X11/dri/xf86dri.h>
+#include "xf86dri.h"
 #include <X11/dri/xf86dristr.h>
-#include "GL/internal/dri_interface.h"
 
 static XExtensionInfo _xf86dri_info_data;
 static XExtensionInfo *xf86dri_info = &_xf86dri_info_data;
diff --git a/hw/kdrive/ephyr/ephyrdri.c b/hw/kdrive/ephyr/ephyrdri.c
index 53a96ba..bb4f6a1 100644
--- a/hw/kdrive/ephyr/ephyrdri.c
+++ b/hw/kdrive/ephyr/ephyrdri.c
@@ -35,7 +35,7 @@
 #include <X11/Xlibint.h>
 /*#define _XF86DRI_SERVER_*/
 #include <GL/glx.h>
-#include <X11/dri/xf86dri.h>
+#include "xf86dri.h"
 #include "hostx.h"
 #include "ephyrdri.h"
 #define _HAVE_XALLOC_DECLS
diff --git a/hw/kdrive/ephyr/xf86dri.h b/hw/kdrive/ephyr/xf86dri.h
new file mode 100644
index 0000000..cd650b5
--- /dev/null
+++ b/hw/kdrive/ephyr/xf86dri.h
@@ -0,0 +1,120 @@
+/* $XFree86: xc/lib/GL/dri/xf86dri.h,v 1.8 2002/10/30 12:51:25 alanh Exp $ */
+/**************************************************************************
+
+Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
+Copyright 2000 VA Linux Systems, 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, 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.
+
+**************************************************************************/
+
+/**
+ * \file xf86dri.h
+ * Protocol numbers and function prototypes for DRI X protocol.
+ *
+ * \author Kevin E. Martin <martin at valinux.com>
+ * \author Jens Owen <jens at tungstengraphics.com>
+ * \author Rickard E. (Rik) Faith <faith at valinux.com>
+ */
+
+#ifndef _XF86DRI_H_
+#define _XF86DRI_H_
+
+#include <X11/Xfuncproto.h>
+#include <xf86drm.h>
+
+#define X_XF86DRIQueryVersion			0
+#define X_XF86DRIQueryDirectRenderingCapable	1
+#define X_XF86DRIOpenConnection			2
+#define X_XF86DRICloseConnection		3
+#define X_XF86DRIGetClientDriverName		4
+#define X_XF86DRICreateContext			5
+#define X_XF86DRIDestroyContext			6
+#define X_XF86DRICreateDrawable			7
+#define X_XF86DRIDestroyDrawable		8
+#define X_XF86DRIGetDrawableInfo		9
+#define X_XF86DRIGetDeviceInfo			10
+#define X_XF86DRIAuthConnection                 11
+#define X_XF86DRIOpenFullScreen                 12   /* Deprecated */
+#define X_XF86DRICloseFullScreen                13   /* Deprecated */
+
+#define XF86DRINumberEvents		0
+
+#define XF86DRIClientNotLocal		0
+#define XF86DRIOperationNotSupported	1
+#define XF86DRINumberErrors		(XF86DRIOperationNotSupported + 1)
+
+#ifndef _XF86DRI_SERVER_
+
+_XFUNCPROTOBEGIN
+
+Bool XF86DRIQueryExtension( Display *dpy, int *event_base, int *error_base );
+
+Bool XF86DRIQueryVersion( Display *dpy, int *majorVersion, int *minorVersion,
+    int *patchVersion );
+
+Bool XF86DRIQueryDirectRenderingCapable( Display *dpy, int screen,
+    Bool *isCapable );
+
+Bool XF86DRIOpenConnection( Display *dpy, int screen, drm_handle_t *hSAREA,
+    char **busIDString );
+
+Bool XF86DRIAuthConnection( Display *dpy, int screen, drm_magic_t magic );
+
+Bool XF86DRICloseConnection( Display *dpy, int screen );
+
+Bool XF86DRIGetClientDriverName( Display *dpy, int screen,
+    int *ddxDriverMajorVersion, int *ddxDriverMinorVersion,
+    int *ddxDriverPatchVersion, char **clientDriverName );
+
+Bool XF86DRICreateContext( Display *dpy, int screen, Visual *visual,
+    XID *ptr_to_returned_context_id, drm_context_t *hHWContext );
+
+Bool XF86DRICreateContextWithConfig( Display *dpy, int screen, int configID,
+    XID *ptr_to_returned_context_id, drm_context_t *hHWContext );
+
+extern GLboolean XF86DRIDestroyContext( Display *dpy, int screen,
+    XID context_id );
+
+extern GLboolean XF86DRICreateDrawable( Display *dpy, int screen,
+    XID drawable, drm_drawable_t *hHWDrawable );
+
+extern GLboolean XF86DRIDestroyDrawable( Display *dpy, int screen, 
+    XID drawable);
+
+Bool XF86DRIGetDrawableInfo( Display *dpy, int screen, Drawable drawable,
+    unsigned int *index, unsigned int *stamp, 
+    int *X, int *Y, int *W, int *H,
+    int *numClipRects, drm_clip_rect_t ** pClipRects,
+    int *backX, int *backY,
+    int *numBackClipRects, drm_clip_rect_t **pBackClipRects );
+
+Bool XF86DRIGetDeviceInfo( Display *dpy, int screen,
+    drm_handle_t *hFrameBuffer, int *fbOrigin, int *fbSize,
+    int *fbStride, int *devPrivateSize, void **pDevPrivate );
+
+_XFUNCPROTOEND
+
+#endif /* _XF86DRI_SERVER_ */
+
+#endif /* _XF86DRI_H_ */
+
commit 7ffc68c5cc7108c9e56af25f9f9b4398f5b027df
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:45:54 2008 +0300

    xephyr: libGL is client lib

diff --git a/configure.ac b/configure.ac
index c1c10f7..21c1d91 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1917,6 +1917,10 @@ if test "$KDRIVE" = yes; then
     if test "x$XV" = xyes; then
         XEPHYR_REQUIRED_LIBS="$XEPHYR_REQUIRED_LIBS xv"
     fi
+    if test "x$DRI" = xyes && test "x$GLX" = xyes; then
+        XEPHYR_REQUIRED_LIBS="$XEPHYR_REQUIRED_LIBS gl libdrm"
+    fi
+
     PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
     if test "x$XEPHYR" = xauto; then
         XEPHYR=$xephyr
@@ -1924,10 +1928,6 @@ if test "$KDRIVE" = yes; then
     XEPHYR_DRI=no
     if test x$XEPHYR = xyes -a x$DRI = xyes && test "x$GLX" = xyes; then
         XEPHYR_DRI=yes
-        XEPHYR_DRI_LIBS=-lGL
-        AC_SUBST(XEPHYR_DRI_LIBS)
-    fi
-    if test x$XEPHYR_DRI = xyes ; then
         AC_DEFINE(XEPHYR_DRI,1,[enable DRI extension in xephyr])
     fi
 
@@ -1965,9 +1965,6 @@ if test "$KDRIVE" = yes; then
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
     KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS $GLX_SYS_LIBS"
 
-    # check if we can build Xephyr
-    PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
-
     AC_SUBST([XEPHYR_LIBS])
     AC_SUBST([XEPHYR_INCS])
     AC_SUBST([XSDL_LIBS])
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index dc0144a..d13bbae 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -2,15 +2,11 @@ INCLUDES = 			\
 	@KDRIVE_INCS@		\
 	@KDRIVE_CFLAGS@		\
 	@XEPHYR_INCS@		\
+	@XEPHYR_CFLAGS@		\
+	@DRIPROTO_CFLAGS@	\
 	-I$(top_srcdir)		\
 	-I$(top_srcdir)/exa
 
-if XEPHYR_HAS_DRI
-INCLUDES +=			\
-	@LIBDRM_CFLAGS@		\
-	@DRIPROTO_CFLAGS@
-endif
-
 if XV
 LIBXEPHYR_HOSTXV=libxephyr-hostxv.a
 endif
@@ -76,9 +72,7 @@ Xephyr_LDADD = 						\
 	$(LIBXEPHYR_HOSTDRI)				\
 	$(top_builddir)/exa/libexa.la			\
 	@KDRIVE_LIBS@					\
-	@XEPHYR_LIBS@ 					\
-	@LIBDRM_LIBS@					\
-	@XEPHYR_DRI_LIBS@
+	@XEPHYR_LIBS@
 
 Xephyr_DEPENDENCIES =	\
 	libxephyr.a					\
commit a27c244d72603e27766ff3900ab28fe094f7397e
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:45:37 2008 +0300

    xephyr: Makefile cleanup 2

diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index f0182d5..dc0144a 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -23,19 +23,16 @@ noinst_LIBRARIES = libxephyr-hostx.a $(LIBXEPHYR_HOSTXV) $(LIBXEPHYR_HOSTDRI) li
 
 bin_PROGRAMS = Xephyr
 
-libxephyr_hostx_a_SOURCES =	\
+HOSTX_SRCS =			\
 	hostx.c			\
 	hostx.h
 
-if XV
-libxephyr_hostxv_a_SOURCES=	\
+HOSTVIDEO_SRCS =		\
 	ephyrvideo.c		\
 	ephyrhostvideo.c	\
 	ephyrhostvideo.h
-endif
 
-if XEPHYR_HAS_DRI
-libxephyr_hostdri_a_SOURCES=	\
+HOSTDRI_SRCS =			\
 	ephyrdriext.c		\
 	ephyrdriext.h		\
 	ephyrdri.c		\
@@ -45,15 +42,26 @@ libxephyr_hostdri_a_SOURCES=	\
 	ephyrglxext.h		\
 	ephyrhostglx.c		\
 	ephyrhostglx.h
-endif
 
-libxephyr_a_SOURCES =		\
+XEPHYR_SRCS =			\
 	ephyr.c			\
 	ephyr.h			\
 	ephyrlog.h		\
 	ephyr_draw.c		\
 	os.c
 
+libxephyr_hostx_a_SOURCES = $(HOSTX_SRCS)
+
+if XV
+libxephyr_hostxv_a_SOURCES = $(HOSTVIDEO_SRCS)
+endif
+
+if XEPHYR_HAS_DRI
+libxephyr_hostdri_a_SOURCES = $(HOSTDRI_SRCS)
+endif
+
+libxephyr_a_SOURCES = $(XEPHYR_SRCS)
+
 Xephyr_SOURCES = \
 	ephyrinit.c
 
@@ -81,3 +89,7 @@ Xephyr_DEPENDENCIES =	\
 
 relink:
 	rm -f $(bin_PROGRAMS) && make $(bin_PROGRAMS)
+
+EXTRA_DIST = \
+	$(HOSTVIDEO_SRCS) \
+	$(HOSTDRI_SRCS)
commit d4d19b2f22002b1579438cb9cf08dd580c7ec005
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:45:19 2008 +0300

    xephyr: Makefile cleanup 1

diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index 7ef22a3..f0182d5 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -1,68 +1,58 @@
-INCLUDES = 					\
-	@KDRIVE_INCS@				\
-	@KDRIVE_CFLAGS@				\
-	-I$(srcdir)/../../../exa
+INCLUDES = 			\
+	@KDRIVE_INCS@		\
+	@KDRIVE_CFLAGS@		\
+	@XEPHYR_INCS@		\
+	-I$(top_srcdir)		\
+	-I$(top_srcdir)/exa
+
+if XEPHYR_HAS_DRI
+INCLUDES +=			\
+	@LIBDRM_CFLAGS@		\
+	@DRIPROTO_CFLAGS@
+endif
 
 if XV
-    LIBXEPHYR_HOSTXV=libxephyr-hostxv.a
-else
-    LIBXEPHYR_HOSTXV=
+LIBXEPHYR_HOSTXV=libxephyr-hostxv.a
 endif
 
 if XEPHYR_HAS_DRI
-    LIBXEPHYR_HOSTDRI=libxephyr-hostdri.a
-else
-    LIBXEPHYR_HOSTDRI=
+LIBXEPHYR_HOSTDRI=libxephyr-hostdri.a
 endif
 
 noinst_LIBRARIES = libxephyr-hostx.a $(LIBXEPHYR_HOSTXV) $(LIBXEPHYR_HOSTDRI) libxephyr.a
 
 bin_PROGRAMS = Xephyr
 
-libxephyr_hostx_a_SOURCES =                             \
-	hostx.c                                         \
+libxephyr_hostx_a_SOURCES =	\
+	hostx.c			\
 	hostx.h
 
-libxephyr_hostxv_a_INCLUDES = @XEPHYR_INCS@
-
 if XV
-libxephyr_hostxv_a_SOURCES=				\
-	ephyrhostvideo.c \
+libxephyr_hostxv_a_SOURCES=	\
+	ephyrvideo.c		\
+	ephyrhostvideo.c	\
 	ephyrhostvideo.h
 endif
 
 if XEPHYR_HAS_DRI
-
-libxephyr_hostdri_a_SOURCES= \
-ephyrdriext.c	\
-ephyrdriext.h	\
-ephyrdri.c	\
-ephyrdri.h	\
-XF86dri.c	\
-ephyrglxext.c	\
-ephyrglxext.h	\
-ephyrhostglx.c	\
-ephyrhostglx.h	
-
-libxephyr_hostdri_a_CFLAGS= \
--I$(top_srcdir)		\
- at LIBDRM_CFLAGS@ 	\
- at DRIPROTO_CFLAGS@
-
+libxephyr_hostdri_a_SOURCES=	\
+	ephyrdriext.c		\
+	ephyrdriext.h		\
+	ephyrdri.c		\
+	ephyrdri.h		\
+	XF86dri.c		\
+	ephyrglxext.c		\
+	ephyrglxext.h		\
+	ephyrhostglx.c		\
+	ephyrhostglx.h
 endif
 
-libxephyr_a_SOURCES =	\
-	ephyr.c		\
-	ephyr_draw.c	\
-	ephyrvideo.c	\
-	os.c		\
-	hostx.h         \
-	ephyr.h		\
-	ephyrlog.h
-
-libxephyr_a_CFLAGS = \
--I$(top_srcdir) \
- at LIBDRM_CFLAGS@
+libxephyr_a_SOURCES =		\
+	ephyr.c			\
+	ephyr.h			\
+	ephyrlog.h		\
+	ephyr_draw.c		\
+	os.c
 
 Xephyr_SOURCES = \
 	ephyrinit.c
@@ -73,18 +63,18 @@ endif
 
 Xephyr_LDADD = 						\
 	libxephyr.a					\
-	libxephyr-hostx.a			        \
+	libxephyr-hostx.a				\
 	$(LIBXEPHYR_HOSTXV)				\
 	$(LIBXEPHYR_HOSTDRI)				\
-	../../../exa/libexa.la				\
+	$(top_builddir)/exa/libexa.la			\
 	@KDRIVE_LIBS@					\
-        @XEPHYR_LIBS@ 					\
+	@XEPHYR_LIBS@ 					\
 	@LIBDRM_LIBS@					\
 	@XEPHYR_DRI_LIBS@
 
 Xephyr_DEPENDENCIES =	\
 	libxephyr.a					\
-	libxephyr-hostx.a			        \
+	libxephyr-hostx.a				\
 	$(LIBXEPHYR_HOSTXV)				\
 	$(LIBXEPHYR_HOSTDRI)				\
 	@KDRIVE_LOCAL_LIBS@
commit cdc4571b580a8f4fd279404215bff0fb9a5b4816
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Sun Apr 20 17:06:26 2008 +0300

    drop TOGCUP remnants

diff --git a/configure.ac b/configure.ac
index aba4619..c1c10f7 100644
--- a/configure.ac
+++ b/configure.ac
@@ -547,7 +547,6 @@ AC_ARG_ENABLE(xcsecurity,     AS_HELP_STRING([--disable-xcsecurity], [Build Secu
 AC_ARG_ENABLE(xcalibrate,     AS_HELP_STRING([--enable-xcalibrate], [Build XCalibrate extension (default: disabled)]), [XCALIBRATE=$enableval], [XCALIBRATE=no])
 AC_ARG_ENABLE(tslib,          AS_HELP_STRING([--enable-tslib], [Build kdrive tslib touchscreen support (default: disabled)]), [TSLIB=$enableval], [TSLIB=no])
 AC_ARG_ENABLE(xevie,          AS_HELP_STRING([--disable-xevie], [Build XEvIE extension (default: enabled)]), [XEVIE=$enableval], [XEVIE=yes])
-AC_ARG_ENABLE(cup,            AS_HELP_STRING([--disable-cup], [Build TOG-CUP extension (default: enabled)]), [CUP=$enableval], [CUP=yes])
 AC_ARG_ENABLE(multibuffer,    AS_HELP_STRING([--enable-multibuffer], [Build Multibuffer extension (default: disabled)]), [MULTIBUFFER=$enableval], [MULTIBUFFER=no])
 AC_ARG_ENABLE(fontcache,      AS_HELP_STRING([--enable-fontcache], [Build FontCache extension (default: disabled)]), [FONTCACHE=$enableval], [FONTCACHE=no])
 AC_ARG_ENABLE(dbe,            AS_HELP_STRING([--disable-dbe], [Build DBE extension (default: enabled)]), [DBE=$enableval], [DBE=yes])
@@ -930,12 +929,6 @@ if test "x$XEVIE" = xyes; then
 	REQUIRED_MODULES="$REQUIRED_MODULES evieproto"
 fi
 
-AM_CONDITIONAL(CUP, [test "x$CUP" = xyes])
-if test "x$CUP" = xyes; then
-	AC_DEFINE(TOGCUP, 1, [Build TOG-CUP extension])
-	# Requires xextproto which is always required
-fi
-
 AM_CONDITIONAL(MULTIBUFFER, [test "x$MULTIBUFFER" = xyes])
 if test "x$MULTIBUFFER" = xyes; then
 	AC_DEFINE(MULTIBUFFER, 1, [Build Multibuffer extension])
commit 6cd9287aed3c128d9c10b9b042ba7b864143d522
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Sun Apr 20 16:58:51 2008 +0300

    drop EVI remnants

diff --git a/Xext/EVIstruct.h b/Xext/EVIstruct.h
deleted file mode 100644
index e658190..0000000
--- a/Xext/EVIstruct.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/************************************************************
-Copyright (c) 1997 by Silicon Graphics Computer Systems, Inc.
-Permission to use, copy, modify, and distribute this
-software and its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright
-notice appear in all copies and that both that copyright
-notice and this permission notice appear in supporting
-documentation, and that the name of Silicon Graphics not be
-used in advertising or publicity pertaining to distribution
-of the software without specific prior written permission.
-Silicon Graphics makes no representation about the suitability
-of this software for any purpose. It is provided "as is"
-without any express or implied warranty.
-SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
-DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
-DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-********************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifndef EVI_STRUCT_H
-#define EVI_STRUCT_H
-
-/*
- ******************************************************************************
- ** Per-ddx data
- ******************************************************************************
- */
-
-typedef int (*GetVisualInfoProc)(
-	VisualID32*,
-	int,
-	xExtendedVisualInfo**,
-	int*,
-	VisualID32**,
-	int*
-);
-
-typedef void (*FreeVisualInfoProc)(
-    xExtendedVisualInfo*,
-    VisualID32*
-);
-typedef struct _EviPrivRec {
-    GetVisualInfoProc getVisualInfo;
-    FreeVisualInfoProc freeVisualInfo;
-} EviPrivRec, *EviPrivPtr;
-
-extern EviPrivPtr eviDDXInit(void);
-extern void eviDDXReset(void);
-
-#endif /* EVI_STRUCT_H */
commit a88c6b66465c039bf92a54a496516fee4d900784
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Apr 18 17:47:16 2008 +0300

    glcore: drop GLcore (files)

diff --git a/GL/mesa/.gitignore b/GL/mesa/.gitignore
deleted file mode 100644
index 6b92b24..0000000
--- a/GL/mesa/.gitignore
+++ /dev/null
@@ -1,32 +0,0 @@
-X/drivers
-X/glxheader.h
-X/xm*.h
-X/xm*.c
-mesa/drivers
-mesa/glxheader.h
-mesa/xm*.c
-glapi/*.c
-glapi/*.h
-main/*.c
-main/*.h
-math/*.c
-math/*.h
-ppc
-shader/*.c
-shader/*.h
-shader/slang/*.c
-shader/slang/*.h
-shader/slang/library
-shader/grammar/*.c
-shader/grammar/*.h
-sparc
-swrast/*.c
-swrast/*.h
-swrast_setup/*.c
-swrast_setup/*.h
-tnl/*.c
-tnl/*.h
-x86
-x86-64
-vbo/*.c
-vbo/*.h
diff --git a/GL/mesa/Makefile.am b/GL/mesa/Makefile.am
deleted file mode 100644
index 7f27c58..0000000
--- a/GL/mesa/Makefile.am
+++ /dev/null
@@ -1,18 +0,0 @@
-SUBDIRS = X
-SUBDIRS += main math swrast swrast_setup tnl shader glapi vbo
-
-noinst_LTLIBRARIES = libGLcore.la
-
-libGLcore_la_SOURCES = dummy.c
-MESA_LIBS           = main/libmain.la \
-                      math/libmath.la \
-                      swrast/libswrast.la \
-                      swrast_setup/libss.la \
-                      tnl/libtnl.la \
-                      shader/libshader.la \
-		      shader/grammar/libgrammar.la \
-		      shader/slang/libslang.la \
-                      vbo/libvbo.la
-
-libGLcore_la_LIBADD = $(MESA_LIBS) \
-                      X/libX.la
diff --git a/GL/mesa/X/Makefile.am b/GL/mesa/X/Makefile.am
deleted file mode 100644
index d8abbc6..0000000
--- a/GL/mesa/X/Makefile.am
+++ /dev/null
@@ -1,27 +0,0 @@
-noinst_LTLIBRARIES = libX.la
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I. \
-           -I at MESA_SOURCE@/src/mesa/glapi \
-           -I at MESA_SOURCE@/src/mesa/main \
-           -I at MESA_SOURCE@/src/mesa
-
-# -DXFree86Server is required because the X11 driver in Mesa thinks that
-# symbol means "being built in the server"
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-XM_SOURCES = \
-	xm_api.c \
-	xm_buffer.c \
-	xm_dd.c \
-	xm_image.c \
-	xm_line.c \
-	xm_span.c \
-	xm_tri.c
-
-XM_SOURCES += drivers/common/driverfuncs.c
-
-nodist_libX_la_SOURCES = $(XM_SOURCES)
diff --git a/GL/mesa/dummy.c b/GL/mesa/dummy.c
deleted file mode 100644
index e69de29..0000000
diff --git a/GL/mesa/glapi/Makefile.am b/GL/mesa/glapi/Makefile.am
deleted file mode 100644
index db79114..0000000
--- a/GL/mesa/glapi/Makefile.am
+++ /dev/null
@@ -1,20 +0,0 @@
-noinst_LTLIBRARIES = libglapi.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libglapi_la_SOURCES = glapi.c glthread.c
diff --git a/GL/mesa/main/Makefile.am b/GL/mesa/main/Makefile.am
deleted file mode 100644
index f8ce137..0000000
--- a/GL/mesa/main/Makefile.am
+++ /dev/null
@@ -1,86 +0,0 @@
-noinst_LTLIBRARIES = libmain.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-if NEED_VSNPRINTF
-VSNPRINTF_SOURCES = vsnprintf.c
-endif
-
-nodist_libmain_la_SOURCES = accum.c \
-                    api_arrayelt.c \
-                    api_loopback.c \
-                    api_noop.c \
-                    api_validate.c \
-                    arrayobj.c \
-                    attrib.c \
-                    blend.c \
-                    bufferobj.c \
-                    buffers.c \
-                    clip.c \
-                    colortab.c \
-                    context.c \
-                    convolve.c \
-                    debug.c \
-                    depth.c \
-		    depthstencil.c \
-                    dlist.c \
-                    drawpix.c \
-                    enable.c \
-                    enums.c \
-                    eval.c \
-                    execmem.c \
-                    extensions.c \
-                    fbobject.c \
-                    feedback.c \
-                    fog.c \
-                    framebuffer.c \
-                    get.c \
-                    getstring.c \
-                    hash.c \
-                    hint.c \
-                    histogram.c \
-                    image.c \
-                    imports.c \
-                    light.c \
-                    lines.c \
-                    matrix.c \
-                    mipmap.c \
-                    mm.c \
-                    pixel.c \
-                    points.c \
-                    polygon.c \
-		    queryobj.c \
-                    rastpos.c \
-                    rbadaptors.c \
-                    renderbuffer.c \
-                    shaders.c \
-                    state.c \
-                    stencil.c \
-                    texcompress.c \
-                    texcompress_fxt1.c \
-                    texcompress_s3tc.c \
-                    texenvprogram.c \
-                    texformat.c \
-                    teximage.c \
-                    texobj.c \
-                    texrender.c \
-                    texstate.c \
-                    texstore.c \
-                    varray.c \
-                    $(VSNPRINTF_SOURCES) \
-                    vtxfmt.c
diff --git a/GL/mesa/math/Makefile.am b/GL/mesa/math/Makefile.am
deleted file mode 100644
index c7c5642..0000000
--- a/GL/mesa/math/Makefile.am
+++ /dev/null
@@ -1,27 +0,0 @@
-noinst_LTLIBRARIES = libmath.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libmath_la_SOURCES = m_debug_clip.c \
-                       m_debug_norm.c \
-                       m_debug_xform.c \
-                       m_eval.c \
-                       m_matrix.c \
-                       m_translate.c \
-                       m_vector.c \
-                       m_xform.c
diff --git a/GL/mesa/shader/Makefile.am b/GL/mesa/shader/Makefile.am
deleted file mode 100644
index abde275..0000000
--- a/GL/mesa/shader/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-SUBDIRS = grammar slang
-
-noinst_LTLIBRARIES = libshader.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-	   -I../shader/grammar \
-	   -I../shader/slang \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libshader_la_SOURCES = \
-                      arbprogparse.c \
-                      arbprogram.c \
-                      atifragshader.c \
-                      nvfragparse.c \
-                      nvprogram.c \
-                      nvvertparse.c \
-                      prog_debug.c \
-                      prog_execute.c \
-                      prog_instruction.c \
-                      prog_parameter.c \
-                      prog_print.c \
-                      program.c \
-                      programopt.c \
-                      prog_statevars.c \
-                      shader_api.c
diff --git a/GL/mesa/shader/grammar/Makefile.am b/GL/mesa/shader/grammar/Makefile.am
deleted file mode 100644
index 332c8e9..0000000
--- a/GL/mesa/shader/grammar/Makefile.am
+++ /dev/null
@@ -1,20 +0,0 @@
-noinst_LTLIBRARIES = libgrammar.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../../X \
-           -I../../glapi \
-           -I../../main \
-           -I../../math \
-           -I../../shader \
-           -I../../swrast \
-           -I../../swrast_setup \
-           -I../../tnl \
-           -I../.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libgrammar_la_SOURCES = grammar_mesa.c
diff --git a/GL/mesa/shader/slang/Makefile.am b/GL/mesa/shader/slang/Makefile.am
deleted file mode 100644
index 71498ee..0000000
--- a/GL/mesa/shader/slang/Makefile.am
+++ /dev/null
@@ -1,41 +0,0 @@
-noinst_LTLIBRARIES = libslang.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../grammar \
-           -I../../X \
-           -I../../glapi \
-           -I../../main \
-           -I../../math \
-           -I../../shader \
-           -I../../swrast \
-           -I../../swrast_setup \
-           -I../../tnl \
-           -I../.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libslang_la_SOURCES = slang_builtin.c \
-		      slang_codegen.c \
-		      slang_compile.c \
-		      slang_compile_function.c \
-		      slang_compile_operation.c \
-		      slang_compile_struct.c \
-		      slang_compile_variable.c \
-		      slang_emit.c \
-		      slang_ir.c \
-		      slang_label.c \
-		      slang_library_noise.c \
-		      slang_link.c \
-		      slang_log.c \
-		      slang_mem.c \
-		      slang_preprocess.c \
-		      slang_print.c \
-		      slang_simplify.c \
-		      slang_storage.c \
-		      slang_typeinfo.c \
-		      slang_utility.c \
-		      slang_vartable.c
diff --git a/GL/mesa/swrast/Makefile.am b/GL/mesa/swrast/Makefile.am
deleted file mode 100644
index bffb1e7..0000000
--- a/GL/mesa/swrast/Makefile.am
+++ /dev/null
@@ -1,50 +0,0 @@
-noinst_LTLIBRARIES = libswrast.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../shader/slang \
-	   -I../shader/slang \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libswrast_la_SOURCES = s_aaline.c \
-                      s_aatriangle.c \
-                      s_accum.c \
-                      s_alpha.c \
-                      s_atifragshader.c \
-                      s_bitmap.c \
-                      s_blend.c \
-                      s_blit.c \
-                      s_buffers.c \
-                      s_context.c \
-                      s_copypix.c \
-                      s_depth.c \
-                      s_drawpix.c \
-                      s_feedback.c \
-                      s_fog.c \
-		      s_fragprog.c \
-                      s_imaging.c \
-                      s_lines.c \
-                      s_logic.c \
-                      s_masking.c \
-                      s_points.c \
-                      s_readpix.c \
-                      s_span.c \
-                      s_stencil.c \
-		      s_texcombine.c \
-		      s_texfilter.c \
-                      s_texstore.c \
-                      s_triangle.c \
-                      s_zoom.c
diff --git a/GL/mesa/swrast_setup/Makefile.am b/GL/mesa/swrast_setup/Makefile.am
deleted file mode 100644
index 1f3c031..0000000
--- a/GL/mesa/swrast_setup/Makefile.am
+++ /dev/null
@@ -1,20 +0,0 @@
-noinst_LTLIBRARIES = libss.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libss_la_SOURCES = ss_context.c ss_triangle.c
diff --git a/GL/mesa/tnl/Makefile.am b/GL/mesa/tnl/Makefile.am
deleted file mode 100644
index b3c8206..0000000
--- a/GL/mesa/tnl/Makefile.am
+++ /dev/null
@@ -1,37 +0,0 @@
-noinst_LTLIBRARIES = libtnl.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../shader/slang \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libtnl_la_SOURCES = t_context.c \
-                      t_draw.c \
-                      t_pipeline.c \
-                      t_vb_cull.c \
-                      t_vb_fog.c \
-                      t_vb_light.c \
-                      t_vb_normals.c \
-                      t_vb_points.c \
-                      t_vb_program.c \
-                      t_vb_render.c \
-                      t_vb_texgen.c \
-                      t_vb_texmat.c \
-                      t_vb_vertex.c \
-                      t_vertex.c \
-                      t_vertex_generic.c \
-                      t_vertex_sse.c \
-                      t_vp_build.c
diff --git a/GL/mesa/vbo/Makefile.am b/GL/mesa/vbo/Makefile.am
deleted file mode 100644
index 9943f2a..0000000
--- a/GL/mesa/vbo/Makefile.am
+++ /dev/null
@@ -1,35 +0,0 @@
-noinst_LTLIBRARIES = libvbo.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../shader/slang \
-	   -I../shader/slang \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libvbo_la_SOURCES = vbo_context.c \
-			vbo_exec_api.c \
-			vbo_exec_array.c \
-			vbo_exec.c \
-			vbo_exec_draw.c \
-			vbo_exec_eval.c \
-			vbo_rebase.c \
-			vbo_save_api.c \
-			vbo_save.c \
-			vbo_save_draw.c \
-			vbo_save_loopback.c \
-			vbo_split.c \
-			vbo_split_copy.c \
-			vbo_split_inplace.c
diff --git a/GL/symlink-mesa.sh b/GL/symlink-mesa.sh
index d611fcf..8deaa43 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -58,169 +58,6 @@ main() {
 
 ## actual symlinking
 
-symlink_mesa_glapi() {
-    src_dir src/mesa/glapi
-    dst_dir mesa/glapi
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_main() {
-    src_dir src/mesa/main
-    dst_dir mesa/main
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_math() {
-    src_dir src/mesa/math
-    dst_dir mesa/math
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_swrast() {
-    src_dir src/mesa/swrast
-    dst_dir mesa/swrast
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_ss() {
-    src_dir src/mesa/swrast_setup
-    dst_dir mesa/swrast_setup
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_tnl() {
-    src_dir src/mesa/tnl
-    dst_dir mesa/tnl
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_shader() {
-    src_dir src/mesa/shader
-    dst_dir mesa/shader
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_shader_grammar() {
-    src_dir src/mesa/shader/grammar
-    dst_dir mesa/shader/grammar
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_shader_slang() {
-    src_dir src/mesa/shader/slang
-    dst_dir mesa/shader/slang
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_shader_slang_library() {
-    src_dir src/mesa/shader/slang/library
-    dst_dir mesa/shader/slang/library
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}        
-
-symlink_mesa_vbo() {
-    src_dir src/mesa/vbo
-    dst_dir mesa/vbo
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_x() {
-    src_dir src/mesa/drivers/x11
-    dst_dir mesa/X
-
-    # action glxapi.h
-    action glxheader.h
-    # action realglx.h
-    # action xfonts.h
-    action xm_api.c
-    action xm_buffer.c
-    action xm_dd.c
-    action xm_image.c
-    action xm_image.h
-    action xm_line.c
-    action xm_span.c
-    action xm_tri.c
-    action xmesaP.h
-
-    # another hack
-    src_dir src/mesa/drivers/common
-    dst_dir mesa/X/drivers/common
-    action driverfuncs.c
-    action driverfuncs.h
-}
-
-symlink_mesa_ppc() {
-    src_dir src/mesa/ppc
-    dst_dir mesa/ppc
-}
-
-symlink_mesa_sparc() {
-    src_dir src/mesa/sparc
-    dst_dir mesa/sparc
-}
-
-symlink_mesa_x86() {
-    src_dir src/mesa/x86
-    dst_dir mesa/x86
-}
-
-symlink_mesa_x8664() {
-    src_dir src/mesa/x86-64
-    dst_dir mesa/x86-64
-}
-
-symlink_mesa() {
-    symlink_mesa_main
-    symlink_mesa_math
-    symlink_mesa_swrast
-    symlink_mesa_ss
-    symlink_mesa_tnl
-    symlink_mesa_shader
-    symlink_mesa_shader_grammar
-    symlink_mesa_shader_slang
-    symlink_mesa_shader_slang_library
-    symlink_mesa_x
-    symlink_mesa_glapi
-    symlink_mesa_ppc
-    symlink_mesa_sparc
-    symlink_mesa_vbo
-    symlink_mesa_x86
-    symlink_mesa_x8664
-}
-
 symlink_glx() {
     # this is... unpleasant
     src_dir src/glx/x11
diff --git a/hw/xfree86/dixmods/GLcoremodule.c b/hw/xfree86/dixmods/GLcoremodule.c
deleted file mode 100644
index d55cb78..0000000
--- a/hw/xfree86/dixmods/GLcoremodule.c
+++ /dev/null
@@ -1,63 +0,0 @@
-/**************************************************************************
-
-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, 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.
-
-**************************************************************************/
-
-/*
- * Authors:
- *   Kevin E. Martin <kevin at precisioninsight.com>
- *
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "xf86Module.h"
-
-static MODULESETUPPROTO(GLcoreSetup);
-
-static XF86ModuleVersionInfo VersRec =
-{
-        "GLcore",
-        MODULEVENDORSTRING,
-        MODINFOSTRING1,
-        MODINFOSTRING2,
-        XORG_VERSION_CURRENT,
-        1, 0, 0,
-        ABI_CLASS_EXTENSION,
-        ABI_EXTENSION_VERSION,
-        MOD_CLASS_NONE,
-        {0,0,0,0}
-};
-
-_X_EXPORT XF86ModuleData GLcoreModuleData = { &VersRec, GLcoreSetup, NULL };
-
-static pointer
-GLcoreSetup(pointer module, pointer opts, int *errmaj, int *errmin)
-{
-    /* Need a non-NULL return value to indicate success */
-    return (pointer)1;
-}
commit dd7a53f8f21e41e1ab43f7e684ba586abc97ef7e
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Apr 18 17:47:01 2008 +0300

    glcore: drop GLcore (build system)

diff --git a/GL/Makefile.am b/GL/Makefile.am
index 29d03f2..44fca18 100644
--- a/GL/Makefile.am
+++ b/GL/Makefile.am
@@ -2,8 +2,8 @@ if XQUARTZ
 XQUARTZ_SUBDIRS = apple
 endif
 
-SUBDIRS = glx mesa $(XQUARTZ_SUBDIRS)
-DIST_SUBDIRS = glx mesa apple
+SUBDIRS = glx $(XQUARTZ_SUBDIRS)
+DIST_SUBDIRS = glx apple
 
 WINDOWS_EXTRAS = \
 	windows/ChangeLog \
diff --git a/GL/symlink-mesa.sh b/GL/symlink-mesa.sh
index 47afdcd..d611fcf 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -267,7 +267,6 @@ run() {
     # $1 what to do
     # $2 explanation
 
-    ACTION=$1 EXPLANATION=$2 run_module mesa
     ACTION=$1 EXPLANATION=$2 run_module glx
 }
 
diff --git a/configure.ac b/configure.ac
index 5da56b5..aba4619 100644
--- a/configure.ac
+++ b/configure.ac
@@ -837,7 +837,7 @@ if test "x$GLX" = xyes && ! test "x$MESA_SOURCE" = x; then
 	PKG_CHECK_MODULES([GL], [glproto >= 1.4.9])
 	AC_SUBST(XLIB_CFLAGS)
 	AC_DEFINE(GLXEXT, 1, [Build GLX extension])
-	GLX_LIBS='$(top_builddir)/GL/glx/libglx.la $(top_builddir)/GL/mesa/libGLcore.la'
+	GLX_LIBS='$(top_builddir)/GL/glx/libglx.la'
 	test -d GL || mkdir GL
 	case $host_os in
 	  solaris*) 	
@@ -2105,18 +2105,6 @@ Makefile
 GL/Makefile
 GL/apple/Makefile
 GL/glx/Makefile
-GL/mesa/Makefile
-GL/mesa/glapi/Makefile
-GL/mesa/main/Makefile
-GL/mesa/math/Makefile
-GL/mesa/shader/Makefile
-GL/mesa/shader/grammar/Makefile
-GL/mesa/shader/slang/Makefile
-GL/mesa/swrast/Makefile
-GL/mesa/swrast_setup/Makefile
-GL/mesa/tnl/Makefile
-GL/mesa/vbo/Makefile
-GL/mesa/X/Makefile
 include/Makefile
 afb/Makefile
 composite/Makefile
diff --git a/hw/xfree86/dixmods/Makefile.am b/hw/xfree86/dixmods/Makefile.am
index 67967c5..beff9b1 100644
--- a/hw/xfree86/dixmods/Makefile.am
+++ b/hw/xfree86/dixmods/Makefile.am
@@ -3,7 +3,7 @@ noinst_LTLIBRARIES = libdixmods.la libxorgxkb.la
 SUBDIRS = extmod
 
 if GLX
-GLXMODS = libglx.la libGLcore.la
+GLXMODS = libglx.la
 endif
 
 if XTRAP
@@ -48,10 +48,6 @@ INCLUDES = @XORG_INCS@ \
            -I$(top_srcdir)/miext/shadow \
            -I$(top_srcdir)/GL/glx
 
-libGLcore_la_LDFLAGS = -avoid-version
-libGLcore_la_LIBADD = $(top_builddir)/GL/mesa/libGLcore.la
-libGLcore_la_SOURCES = GLcoremodule.c
-
 libafb_la_LDFLAGS = -avoid-version
 libafb_la_LIBADD = $(top_builddir)/afb/libafb.la
 libafb_la_SOURCES = afbmodule.c
commit 567d389d47dee233a973b101e04ce41c47a68f34
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Apr 18 17:46:18 2008 +0300

    glcore: build from mesa, dlopen from xorg
    
    * The GLcore interface is disposable
    * GLcore is installed in DRI_DRIVER_INSTALL_DIR which is overloaded for
      GLX_PROVIDER_INSTALL_DIR

diff --git a/GL/glx/glxglcore.c b/GL/glx/glxglcore.c
index c8a2514..dafa9bc 100644
--- a/GL/glx/glxglcore.c
+++ b/GL/glx/glxglcore.c
@@ -37,7 +37,9 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #endif
 
 #include <string.h>
+#include <dlfcn.h>
 
+#define _NEED_GL_CORE_IF
 #include <GL/xmesa.h>
 #include <GL/internal/glcore.h>
 #include <glxserver.h>
@@ -48,6 +50,22 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 #include "os.h"
 
+#define XMesaCreateVisual       (*glcore->XMesaCreateVisual)
+#define XMesaDestroyVisual      (*glcore->XMesaDestroyVisual)
+
+#define XMesaCreateWindowBuffer (*glcore->XMesaCreateWindowBuffer)
+#define XMesaCreatePixmapBuffer (*glcore->XMesaCreatePixmapBuffer)
+#define XMesaDestroyBuffer      (*glcore->XMesaDestroyBuffer)
+#define XMesaSwapBuffers        (*glcore->XMesaSwapBuffers)
+#define XMesaResizeBuffers      (*glcore->XMesaResizeBuffers)
+
+#define XMesaCreateContext      (*glcore->XMesaCreateContext)
+#define XMesaDestroyContext     (*glcore->XMesaDestroyContext)
+#define XMesaCopyContext        (*glcore->XMesaCopyContext)
+#define XMesaMakeCurrent2       (*glcore->XMesaMakeCurrent2)
+#define XMesaForceCurrent       (*glcore->XMesaForceCurrent)
+#define XMesaLoseCurrent        (*glcore->XMesaLoseCurrent)
+
 typedef struct __GLXMESAscreen   __GLXMESAscreen;
 typedef struct __GLXMESAcontext  __GLXMESAcontext;
 typedef struct __GLXMESAdrawable __GLXMESAdrawable;
@@ -55,8 +73,11 @@ typedef struct __GLXMESAdrawable __GLXMESAdrawable;
 struct __GLXMESAscreen {
     __GLXscreen   base;
     int           index;
-    int		  num_vis;
+    int           num_vis;
     XMesaVisual  *xm_vis;
+    void         *driver;
+
+    const __GLcoreModule *glcore;
 };
 
 struct __GLXMESAcontext {
@@ -65,8 +86,9 @@ struct __GLXMESAcontext {
 };
 
 struct __GLXMESAdrawable {
-    __GLXdrawable base;
-    XMesaBuffer   xm_buf;
+    __GLXdrawable    base;
+    XMesaBuffer      xm_buf;
+    __GLXMESAscreen *screen;
 };
 
 static XMesaVisual find_mesa_visual(__GLXscreen *screen, XID fbconfigID);
@@ -76,6 +98,7 @@ static void
 __glXMesaDrawableDestroy(__GLXdrawable *base)
 {
     __GLXMESAdrawable *glxPriv = (__GLXMESAdrawable *) base;
+    const __GLcoreModule *glcore = glxPriv->screen->glcore;
 
     if (glxPriv->xm_buf != NULL)
       XMesaDestroyBuffer(glxPriv->xm_buf);
@@ -86,6 +109,7 @@ static GLboolean
 __glXMesaDrawableResize(__GLXdrawable *base)
 {
     __GLXMESAdrawable *glxPriv = (__GLXMESAdrawable *) base;
+    const __GLcoreModule *glcore = glxPriv->screen->glcore;
 
     XMesaResizeBuffers(glxPriv->xm_buf);
 
@@ -96,6 +120,7 @@ static GLboolean
 __glXMesaDrawableSwapBuffers(__GLXdrawable *base)
 {
     __GLXMESAdrawable *glxPriv = (__GLXMESAdrawable *) base;
+    const __GLcoreModule *glcore = glxPriv->screen->glcore;
 
     /* This is terrifying: XMesaSwapBuffers() ends up calling CopyArea
      * to do the buffer swap, but this assumes that the server holds
@@ -121,6 +146,8 @@ __glXMesaScreenCreateDrawable(__GLXscreen *screen,
 			      XID drawId,
 			      __GLXconfig *modes)
 {
+    __GLXMESAscreen *mesaScreen = (__GLXMESAscreen *) screen;
+    const __GLcoreModule *glcore = mesaScreen->glcore;
     __GLXMESAdrawable *glxPriv;
     XMesaVisual xm_vis;
 
@@ -130,6 +157,7 @@ __glXMesaScreenCreateDrawable(__GLXscreen *screen,
 
     memset(glxPriv, 0, sizeof *glxPriv);
 
+    glxPriv->screen = mesaScreen;
     if (!__glXDrawableInit(&glxPriv->base, screen,
 			   pDraw, type, drawId, modes)) {
         xfree(glxPriv);
@@ -166,6 +194,8 @@ static void
 __glXMesaContextDestroy(__GLXcontext *baseContext)
 {
     __GLXMESAcontext *context = (__GLXMESAcontext *) baseContext;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) context->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     XMesaDestroyContext(context->xmesa);
     __glXContextDestroy(&context->base);
@@ -179,6 +209,8 @@ __glXMesaContextMakeCurrent(__GLXcontext *baseContext)
     __GLXMESAcontext *context = (__GLXMESAcontext *) baseContext;
     __GLXMESAdrawable *drawPriv = (__GLXMESAdrawable *) context->base.drawPriv;
     __GLXMESAdrawable *readPriv = (__GLXMESAdrawable *) context->base.readPriv;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) context->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     return XMesaMakeCurrent2(context->xmesa,
 			     drawPriv->xm_buf,
@@ -189,6 +221,8 @@ static int
 __glXMesaContextLoseCurrent(__GLXcontext *baseContext)
 {
     __GLXMESAcontext *context = (__GLXMESAcontext *) baseContext;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) context->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     return XMesaLoseCurrent(context->xmesa);
 }
@@ -200,6 +234,8 @@ __glXMesaContextCopy(__GLXcontext *baseDst,
 {
     __GLXMESAcontext *dst = (__GLXMESAcontext *) baseDst;
     __GLXMESAcontext *src = (__GLXMESAcontext *) baseSrc;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) dst->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     return XMesaCopyContext(src->xmesa, dst->xmesa, mask);
 }
@@ -208,6 +244,8 @@ static int
 __glXMesaContextForceCurrent(__GLXcontext *baseContext)
 {
     __GLXMESAcontext *context = (__GLXMESAcontext *) baseContext;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) context->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     /* GlxSetRenderTables() call for XGL moved in XMesaForceCurrent() */
 
@@ -219,6 +257,8 @@ __glXMesaScreenCreateContext(__GLXscreen *screen,
 			     __GLXconfig *config,
 			     __GLXcontext *baseShareContext)
 {
+    __GLXMESAscreen *mesaScreen = (__GLXMESAscreen *) screen;
+    const __GLcoreModule *glcore = mesaScreen->glcore;
     __GLXMESAcontext *context;
     __GLXMESAcontext *shareContext = (__GLXMESAcontext *) baseShareContext;
     XMesaVisual xm_vis;
@@ -261,6 +301,7 @@ static void
 __glXMesaScreenDestroy(__GLXscreen *screen)
 {
     __GLXMESAscreen *mesaScreen = (__GLXMESAscreen *) screen;
+    const __GLcoreModule *glcore = mesaScreen->glcore;
     int i;
 
     if (mesaScreen->xm_vis) {
@@ -272,6 +313,8 @@ __glXMesaScreenDestroy(__GLXscreen *screen)
 	xfree(mesaScreen->xm_vis);
     }
 
+    dlclose(mesaScreen->driver);
+
     __glXScreenDestroy(screen);
 
     xfree(screen);
@@ -373,6 +416,7 @@ createFBConfigs(__GLXscreen *pGlxScreen, ScreenPtr pScreen)
 static void
 createMesaVisuals(__GLXMESAscreen *pMesaScreen)
 {
+    const __GLcoreModule *glcore = pMesaScreen->glcore;
     __GLXconfig *config;
     ScreenPtr pScreen;
     VisualPtr visual = NULL;
@@ -409,15 +453,35 @@ createMesaVisuals(__GLXMESAscreen *pMesaScreen)
     }
 }
 
+static const char dri_driver_path[] = DRI_DRIVER_PATH;
+
 static __GLXscreen *
 __glXMesaScreenProbe(ScreenPtr pScreen)
 {
     __GLXMESAscreen *screen;
+    char filename[128];
 
     screen = xalloc(sizeof *screen);
     if (screen == NULL)
 	return NULL;
 
+    snprintf(filename, sizeof filename, "%s/%s.so",
+             dri_driver_path, "libGLcore");
+
+    screen->driver = dlopen(filename, RTLD_LAZY | RTLD_LOCAL);
+    if (screen->driver == NULL) {
+        LogMessage(X_ERROR, "GLX error: dlopen of %s failed (%s)\n",
+                   filename, dlerror());
+        goto handle_error;
+    }
+
+    screen->glcore = dlsym(screen->driver, __GL_CORE);
+    if (screen->glcore == NULL) {
+        LogMessage(X_ERROR, "GLX error: dlsym for %s failed (%s)\n",
+                   __GL_CORE, dlerror());
+        goto handle_error;
+    }
+
     /*
      * Find the GLX visuals that are supported by this screen and create
      * XMesa's visuals.
@@ -435,7 +499,20 @@ __glXMesaScreenProbe(ScreenPtr pScreen)
     screen->base.swapInterval  = NULL;
     screen->base.pScreen       = pScreen;
 
+    LogMessage(X_INFO, "GLX: Loaded and initialized %s\n", filename);
+
     return &screen->base;
+
+handle_error:
+
+    if (screen->driver)
+        dlclose(screen->driver);
+
+    xfree(screen);
+
+    FatalError("GLX: could not load software renderer\n");
+
+    return NULL;
 }
 
 __GLXprovider __glXMesaProvider = {
diff --git a/hw/xfree86/dixmods/glxmodule.c b/hw/xfree86/dixmods/glxmodule.c
index a1a0886..88091cd 100644
--- a/hw/xfree86/dixmods/glxmodule.c
+++ b/hw/xfree86/dixmods/glxmodule.c
@@ -72,37 +72,6 @@ static XF86ModuleVersionInfo VersRec =
 
 _X_EXPORT XF86ModuleData glxModuleData = { &VersRec, glxSetup, NULL };
 
-/* We do a little proxy dance here, so we can avoid loading GLcore
- * unless we really need to.*/
-
-static pointer glxModule;
-
-static __GLXscreen *
-__glXMesaProxyScreenProbe(ScreenPtr pScreen)
-{
-  pointer GLcore;
-  static __GLXprovider *provider;
-
-  if (provider == NULL) {
-    GLcore = LoadSubModule(glxModule, "GLcore", NULL, NULL, NULL, NULL, 
-			   NULL, NULL);
-    if (GLcore == NULL)
-      return NULL;
-
-    provider = LoaderSymbol("__glXMesaProvider");
-    if (provider == NULL)
-      return NULL;
-  }
-
-  return provider->screenProbe(pScreen);
-}
-
-static __GLXprovider __glXMesaProxyProvider = {
-    __glXMesaProxyScreenProbe,
-    "MESA-PROXY",
-    NULL
-};
-
 static pointer
 glxSetup(pointer module, pointer opts, int *errmaj, int *errmin)
 {
@@ -116,8 +85,10 @@ glxSetup(pointer module, pointer opts, int *errmaj, int *errmin)
 
     setupDone = TRUE;
 
-    glxModule = module;
-    GlxPushProvider(&__glXMesaProxyProvider);
+    provider = LoaderSymbol("__glXMesaProvider");
+    if (provider == NULL)
+	return NULL;
+    GlxPushProvider(provider);
 
     xf86Msg(xf86Info.aiglxFrom, "AIGLX %s\n", 
 	    xf86Info.aiglx ? "enabled" : "disabled");
commit efb723e166e5fa89e90c7b400fb4c7979b1f50c0
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Apr 18 17:45:53 2008 +0300

    glcore: prepare for dynamic loading
    
    glcore gets linked with -ldl, -lpthread for s3tc and glapi
    xserver needs
            DLOPEN_LIBS - to dlopen the glcore dso
            LD_EXPORT_SYMBOLS_FLAG - to export symbols for glcore to use
    
    the ld flag is added to kdrive only when GLX is enabled, the net overhead for
    Xephyr is ~155KB, could be reduced with --dynamic-list.

diff --git a/configure.ac b/configure.ac
index 995a652..5da56b5 100644
--- a/configure.ac
+++ b/configure.ac
@@ -848,6 +848,7 @@ if test "x$GLX" = xyes && ! test "x$MESA_SOURCE" = x; then
 	if test $? -ne 0; then
 		AC_MSG_ERROR([Failed to link Mesa source tree.  Please specify a proper path to Mesa sources, or disable GLX.])
 	fi
+	GLX_SYS_LIBS="$GLX_SYS_LIBS $DLOPEN_LIBS"
 else
         GLX=no
 fi
@@ -1969,7 +1970,7 @@ if test "$KDRIVE" = yes; then
     KDRIVE_LOCAL_LIBS="$DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $FB_LIB $MI_LIB $KDRIVE_PURE_LIBS"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
-    KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
+    KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS $GLX_SYS_LIBS"
 
     # check if we can build Xephyr
     PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
diff --git a/hw/kdrive/ati/Makefile.am b/hw/kdrive/ati/Makefile.am
index 8429250..31462bb 100644
--- a/hw/kdrive/ati/Makefile.am
+++ b/hw/kdrive/ati/Makefile.am
@@ -58,6 +58,10 @@ ATI_LIBS =				\
 	$(DRI_LIBS)			\
 	@KDRIVE_LIBS@
 
+if GLX
+Xati_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xati_LDADD = \
 	$(ATI_LIBS)			\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/chips/Makefile.am b/hw/kdrive/chips/Makefile.am
index 51b0edf..46e1760 100644
--- a/hw/kdrive/chips/Makefile.am
+++ b/hw/kdrive/chips/Makefile.am
@@ -20,6 +20,10 @@ CHIPS_LIBS =					 \
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xchips_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xchips_LDADD = \
 	$(CHIPS_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index 81d3d69..7ef22a3 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -67,6 +67,10 @@ libxephyr_a_CFLAGS = \
 Xephyr_SOURCES = \
 	ephyrinit.c
 
+if GLX
+Xephyr_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xephyr_LDADD = 						\
 	libxephyr.a					\
 	libxephyr-hostx.a			        \
diff --git a/hw/kdrive/epson/Makefile.am b/hw/kdrive/epson/Makefile.am
index 2a44014..14bb049 100644
--- a/hw/kdrive/epson/Makefile.am
+++ b/hw/kdrive/epson/Makefile.am
@@ -20,6 +20,10 @@ EPSON_LIBS =					\
 	libepson.a 				\
 	@KDRIVE_LIBS@
 
+if GLX
+Xepson_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xepson_LDADD = \
 	$(EPSON_LIBS)			       \
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/fake/Makefile.am b/hw/kdrive/fake/Makefile.am
index 09d179e..0f88656 100644
--- a/hw/kdrive/fake/Makefile.am
+++ b/hw/kdrive/fake/Makefile.am
@@ -16,6 +16,10 @@ libfake_a_SOURCES =	\
 Xfake_SOURCES = \
 	fakeinit.c
 
+if GLX
+Xfake_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xfake_LDADD = 						\
 	libfake.a					\
 	@KDRIVE_LIBS@					\
diff --git a/hw/kdrive/fbdev/Makefile.am b/hw/kdrive/fbdev/Makefile.am
index 420855b..c77f146 100644
--- a/hw/kdrive/fbdev/Makefile.am
+++ b/hw/kdrive/fbdev/Makefile.am
@@ -14,6 +14,10 @@ bin_PROGRAMS = Xfbdev
 Xfbdev_SOURCES = \
 	fbinit.c
 
+if GLX
+Xfbdev_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xfbdev_LDADD = 						\
 	libfbdev.a					\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/i810/Makefile.am b/hw/kdrive/i810/Makefile.am
index ea02cb6..30919fa 100644
--- a/hw/kdrive/i810/Makefile.am
+++ b/hw/kdrive/i810/Makefile.am
@@ -23,6 +23,10 @@ I810_LIBS =						\
 	libi810.a 					\
 	@KDRIVE_LIBS@
 
+if GLX
+Xi810_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xi810_LDADD = \
 	$(I810_LIBS)					\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/mach64/Makefile.am b/hw/kdrive/mach64/Makefile.am
index 746ffff..6ca376a 100644
--- a/hw/kdrive/mach64/Makefile.am
+++ b/hw/kdrive/mach64/Makefile.am
@@ -27,6 +27,10 @@ MACH64_LIBS =						\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a        
 
 
+if GLX
+Xmach64_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xmach64_LDADD = 					\
 	$(MACH64_LIBS)					\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/mga/Makefile.am b/hw/kdrive/mga/Makefile.am
index 37bc50c..a7dd2cb 100644
--- a/hw/kdrive/mga/Makefile.am
+++ b/hw/kdrive/mga/Makefile.am
@@ -22,6 +22,10 @@ MGA_LIBS =						\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a	\
 	@KDRIVE_LIBS@
 
+if GLX
+Xmga_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xmga_LDADD = \
 	$(MGA_LIBS)					\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/neomagic/Makefile.am b/hw/kdrive/neomagic/Makefile.am
index 95f0e1e..b449c37 100644
--- a/hw/kdrive/neomagic/Makefile.am
+++ b/hw/kdrive/neomagic/Makefile.am
@@ -32,6 +32,10 @@ NEOMAGIC_LIBS =                 \
 	${VESA_LIBS}                \
 	@KDRIVE_LIBS@
 
+if GLX
+Xneomagic_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xneomagic_LDADD = \
 	$(NEOMAGIC_LIBS)            \
 	@KDRIVE_LIBS@               \
diff --git a/hw/kdrive/nvidia/Makefile.am b/hw/kdrive/nvidia/Makefile.am
index b380e44..81736c3 100644
--- a/hw/kdrive/nvidia/Makefile.am
+++ b/hw/kdrive/nvidia/Makefile.am
@@ -23,6 +23,10 @@ NVIDIA_LIBS =					\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xnvidia_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xnvidia_LDADD = \
 	$(NVIDIA_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/pm2/Makefile.am b/hw/kdrive/pm2/Makefile.am
index 208d031..cb28de6 100644
--- a/hw/kdrive/pm2/Makefile.am
+++ b/hw/kdrive/pm2/Makefile.am
@@ -21,6 +21,10 @@ PM2_LIBS =					\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xpm2_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xpm2_LDADD = \
 	$(PM2_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/r128/Makefile.am b/hw/kdrive/r128/Makefile.am
index 62c1fcf..344fbeb 100644
--- a/hw/kdrive/r128/Makefile.am
+++ b/hw/kdrive/r128/Makefile.am
@@ -20,6 +20,10 @@ R128_LIBS =					\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xr128_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xr128_LDADD = \
 	$(R128_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/sdl/Makefile.am b/hw/kdrive/sdl/Makefile.am
index fe9309e..a70d147 100644
--- a/hw/kdrive/sdl/Makefile.am
+++ b/hw/kdrive/sdl/Makefile.am
@@ -7,6 +7,10 @@ bin_PROGRAMS = Xsdl
 
 Xsdl_SOURCES = sdl.c
 
+if GLX
+Xsdl_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xsdl_LDADD = \
 	@KDRIVE_LIBS@                                  \
 	@XSDL_LIBS@
diff --git a/hw/kdrive/sis300/Makefile.am b/hw/kdrive/sis300/Makefile.am
index 3e8ce90..af2500a 100644
--- a/hw/kdrive/sis300/Makefile.am
+++ b/hw/kdrive/sis300/Makefile.am
@@ -34,6 +34,10 @@ SIS_LIBS =				\
 	$(VESA_LIBS)			\
 	@KDRIVE_LIBS@
 
+if GLX
+Xsis_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xsis_LDADD = \
 	$(SIS_LIBS)				\
 	@KDRIVE_LIBS@                          \
diff --git a/hw/kdrive/smi/Makefile.am b/hw/kdrive/smi/Makefile.am
index a4d6624..bd7077c 100644
--- a/hw/kdrive/smi/Makefile.am
+++ b/hw/kdrive/smi/Makefile.am
@@ -25,6 +25,10 @@ SMI_LIBS =					\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xsmi_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xsmi_LDADD = \
 	$(SMI_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/vesa/Makefile.am b/hw/kdrive/vesa/Makefile.am
index ac50d2b..ec35c1e 100644
--- a/hw/kdrive/vesa/Makefile.am
+++ b/hw/kdrive/vesa/Makefile.am
@@ -19,6 +19,10 @@ libvesa_a_SOURCES = \
 Xvesa_SOURCES = \
 	vesainit.c
 
+if GLX
+Xvesa_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xvesa_LDADD = \
 	libvesa.a 				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/via/Makefile.am b/hw/kdrive/via/Makefile.am
index 249b3f3..c659379 100644
--- a/hw/kdrive/via/Makefile.am
+++ b/hw/kdrive/via/Makefile.am
@@ -21,6 +21,10 @@ VIA_LIBS =	\
 	libvia.a	\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a
 
+if GLX
+Xvia_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xvia_LDADD =						\
 	$(VIA_LIBS)					\
 	@KDRIVE_LIBS@
commit fbad87f2ae9f97fcb43546b0fa35f1100415dfec
Author: Julien Cristau <jcristau at debian.org>
Date:   Tue Apr 22 23:50:11 2008 +0200

    autoconfig: don't call closedir() when opendir() failed
    
    If opendir() fails, return from matchDriverFromFiles() immediately.
    Ubuntu bug 217647.

diff --git a/hw/xfree86/common/xf86AutoConfig.c b/hw/xfree86/common/xf86AutoConfig.c
index 5ffd847..7e5fab4 100644
--- a/hw/xfree86/common/xf86AutoConfig.c
+++ b/hw/xfree86/common/xf86AutoConfig.c
@@ -330,86 +330,87 @@ matchDriverFromFiles (char** matches, uint16_t match_vendor, uint16_t match_chip
     int i, j;
 
     idsdir = opendir(PCI_TXT_IDS_PATH);
-    if (idsdir) {
-         xf86Msg(X_INFO, "Scanning %s directory for additional PCI ID's supported by the drivers\n", PCI_TXT_IDS_PATH);
-        direntry = readdir(idsdir);
-        /* Read the directory */
-        while (direntry) {
-            if (direntry->d_name[0] == '.') {
-                direntry = readdir(idsdir);
-                continue;
+    if (!idsdir)
+        return;
+
+    xf86Msg(X_INFO, "Scanning %s directory for additional PCI ID's supported by the drivers\n", PCI_TXT_IDS_PATH);
+    direntry = readdir(idsdir);
+    /* Read the directory */
+    while (direntry) {
+        if (direntry->d_name[0] == '.') {
+            direntry = readdir(idsdir);
+            continue;
+        }
+        len = strlen(direntry->d_name);
+        /* A tiny bit of sanity checking. We should probably do better */
+        if (strncmp(&(direntry->d_name[len-4]), ".ids", 4) == 0) {
+            /* We need the full path name to open the file */
+            strncpy(path_name, PCI_TXT_IDS_PATH, 256);
+            strncat(path_name, "/", 1);
+            strncat(path_name, direntry->d_name, (256 - strlen(path_name) - 1));
+            fp = fopen(path_name, "r");
+            if (fp == NULL) {
+                xf86Msg(X_ERROR, "Could not open %s for reading. Exiting.\n", path_name);
+                goto end;
             }
-            len = strlen(direntry->d_name);
-            /* A tiny bit of sanity checking. We should probably do better */
-            if (strncmp(&(direntry->d_name[len-4]), ".ids", 4) == 0) {
-                /* We need the full path name to open the file */
-                strncpy(path_name, PCI_TXT_IDS_PATH, 256);
-                strncat(path_name, "/", 1);
-                strncat(path_name, direntry->d_name, (256 - strlen(path_name) - 1));
-                fp = fopen(path_name, "r");
-                if (fp == NULL) {
-                    xf86Msg(X_ERROR, "Could not open %s for reading. Exiting.\n", path_name);
-                    goto end;
-                }
-                /* Read the file */
-                #ifdef __GLIBC__
-                while ((read = getline(&line, &len, fp)) != -1) {
-                #else
-                while ((line = fgetln(fp, &len)) != (char *)NULL) {
-                #endif /* __GLIBC __ */
-                    xchomp(line);
-                    if (isdigit(line[0])) {
-                        strncpy(vendor_str, line, 4);
-                        vendor_str[4] = '\0';
-                        vendor = (int)strtol(vendor_str, NULL, 16);
-                        if ((strlen(&line[4])) == 0) {
-                                chip_str[0] = '\0';
-                                chip = -1;
+            /* Read the file */
+#ifdef __GLIBC__
+            while ((read = getline(&line, &len, fp)) != -1) {
+#else
+            while ((line = fgetln(fp, &len)) != (char *)NULL) {
+#endif /* __GLIBC __ */
+                xchomp(line);
+                if (isdigit(line[0])) {
+                    strncpy(vendor_str, line, 4);
+                    vendor_str[4] = '\0';
+                    vendor = (int)strtol(vendor_str, NULL, 16);
+                    if ((strlen(&line[4])) == 0) {
+                        chip_str[0] = '\0';
+                        chip = -1;
+                    } else {
+                        /* Handle trailing whitespace */
+                        if (isspace(line[4])) {
+                            chip_str[0] = '\0';
+                            chip = -1;
                         } else {
-                                /* Handle trailing whitespace */
-                                if (isspace(line[4])) {
-                                    chip_str[0] = '\0';
-                                    chip = -1;
-                                } else {
-                                /* Ok, it's a real ID */
-                                    strncpy(chip_str, &line[4], 4);
-                                    chip_str[4] = '\0';
-                                    chip = (int)strtol(chip_str, NULL, 16);
-                                }
+                            /* Ok, it's a real ID */
+                            strncpy(chip_str, &line[4], 4);
+                            chip_str[4] = '\0';
+                            chip = (int)strtol(chip_str, NULL, 16);
                         }
-                        if (vendor == match_vendor && chip == match_chip ) {
-                            i = 0;
-                            while (matches[i]) {
-                                i++;
-                            }
-                            matches[i] = (char*)xalloc(sizeof(char) * strlen(direntry->d_name) -  3);
-                            if (!matches[i]) {
-                                xf86Msg(X_ERROR, "Could not allocate space for the module name. Exiting.\n");
-                                goto end;
-                            }
-                            /* hack off the .ids suffix. This should guard
-                             * against other problems, but it will end up
-                             * taking off anything after the first '.' */
-                            for (j = 0; j < (strlen(direntry->d_name) - 3) ; j++) {
-                                if (direntry->d_name[j] == '.') {
-                                    matches[i][j] = '\0';
-                                    break;
-                                } else {
-                                    matches[i][j] = direntry->d_name[j];
-                                }
+                    }
+                    if (vendor == match_vendor && chip == match_chip ) {
+                        i = 0;
+                        while (matches[i]) {
+                            i++;
+                        }
+                        matches[i] = (char*)xalloc(sizeof(char) * strlen(direntry->d_name) -  3);
+                        if (!matches[i]) {
+                            xf86Msg(X_ERROR, "Could not allocate space for the module name. Exiting.\n");
+                            goto end;
+                        }
+                        /* hack off the .ids suffix. This should guard
+                         * against other problems, but it will end up
+                         * taking off anything after the first '.' */
+                        for (j = 0; j < (strlen(direntry->d_name) - 3) ; j++) {
+                            if (direntry->d_name[j] == '.') {
+                                matches[i][j] = '\0';
+                                break;
+                            } else {
+                                matches[i][j] = direntry->d_name[j];
                             }
-                            xf86Msg(X_INFO, "Matched %s from file name %s\n", matches[i], direntry->d_name);
                         }
-                    } else {
-                        /* TODO Handle driver overrides here */
+                        xf86Msg(X_INFO, "Matched %s from file name %s\n", matches[i], direntry->d_name);
                     }
+                } else {
+                    /* TODO Handle driver overrides here */
                 }
-                fclose(fp);
             }
-            direntry = readdir(idsdir);
+            fclose(fp);
         }
+        direntry = readdir(idsdir);
     }
-    end:
+ end:
     xfree(line);
     closedir(idsdir);
 }
commit 76381092e8f650ec7d1f058fa4c8a7348893f775
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 23 02:22:14 2008 -0700

    XQuartz: Make sure QuartzAudioInit() gets run.
    (cherry picked from commit bb3d034675b70e22e78df5554cab0ec2a3d913d0)
    (cherry picked from commit 824b31c7f8144a67a320442abd3d854e99d2bfe2)

diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 4d03d02..2cba5df 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -156,7 +156,7 @@ void QuartzInitOutput(
     int argc,
     char **argv )
 {
-    if (serverGeneration == 0) {
+    if (serverGeneration == 1) {
         QuartzAudioInit();
     }
 
@@ -244,7 +244,7 @@ void QuartzDisplayChangedHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev,
     int x, y, width, height, sx, sy;
     xEvent e;
 
-    DEBUG_LOG("QuartzDisplayChangedHandler()\n");
+    DEBUG_LOG("QuartzDisplayChangedHandler(): noPseudoramiXExtension=%d, screenInfo.numScreens=%d\n", noPseudoramiXExtension, screenInfo.numScreens);
     if (noPseudoramiXExtension || screenInfo.numScreens != 1)
     {
         /* FIXME: if not using Xinerama, we have multiple screens, and
commit 00815b3e5223e822f306db45cd4884a22ac9f7ed
Author: Julien Cristau <jcristau at debian.org>
Date:   Mon Apr 21 14:34:39 2008 +0200

    Don't set DRI2=yes if we can't find dri2proto or libdrm

diff --git a/configure.ac b/configure.ac
index 04d976c..995a652 100644
--- a/configure.ac
+++ b/configure.ac
@@ -379,7 +379,7 @@ case $host_os in
 	AC_DEFINE(PCVT_SUPPORT, 1, [System has PCVT console])
 	AC_DEFINE(SYSCONS_SUPPORT, 1, [System has syscons console])
 	DRI=yes
-	DRI2=yes
+	PKG_CHECK_EXISTS([dri2proto >= 1.1 libdrm >= 2.3.1], DRI2=yes, DRI2=no)
 	;;
   *netbsd*)
 	AC_DEFINE(CSRG_BASED, 1, [System is BSD-like])
@@ -387,7 +387,7 @@ case $host_os in
 	AC_DEFINE(PCVT_SUPPORT, 1, [System has PCVT console])
 	AC_DEFINE(WSCONS_SUPPORT, 1, [System has wscons console])
 	DRI=yes
-	DRI2=yes
+	PKG_CHECK_EXISTS([dri2proto >= 1.1 libdrm >= 2.3.1], DRI2=yes, DRI2=no)
 	;;
   *openbsd*)
 	AC_DEFINE(CSRG_BASED, 1, [System is BSD-like])
@@ -396,7 +396,7 @@ case $host_os in
 	;;
   *linux*)
 	DRI=yes
-	DRI2=yes
+	PKG_CHECK_EXISTS([dri2proto >= 1.1 libdrm >= 2.3.1], DRI2=yes, DRI2=no)
 	KDRIVE_HW=yes
 	;;
   *solaris*)
commit e77f65768efbf05cdf363a2f41f036f74eaa45de
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 18:07:46 2008 +0100

    Reuse the existing framebuffer mode in kdrive/fbdev
    
    When starting up kdrive/fbdev, if the current framebuffer mode is sensible use
    that unless told otherwise.
    
    Signed-off-by: Daniel Stone <daniel at fooishbar.org>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index 177be0b..7721e60 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -179,16 +179,24 @@ fbdevScreenInitialize (KdScreenInfo *screen, FbdevScrPriv *scrpriv)
 	screen->rate = 103; /* FIXME: should get proper value from fb driver */
     }
     if (!screen->fb[0].depth)
-	screen->fb[0].depth = 16;
-
-    t = KdFindMode (screen, fbdevModeSupported);
-    screen->rate = t->rate;
-    screen->width = t->horizontal;
-    screen->height = t->vertical;
+    {
+	if (k >= 0) 
+	    screen->fb[0].depth = var.bits_per_pixel;
+	else
+	    screen->fb[0].depth = 16;
+    }
 
-    /* Now try setting the mode */
-    if (k < 0 || (t->horizontal != var.xres || t->vertical != var.yres))
-        fbdevConvertMonitorTiming (t, &var);
+    if ((screen->width != var.xres) || (screen->height != var.yres))
+    {
+      t = KdFindMode (screen, fbdevModeSupported);
+      screen->rate = t->rate;
+      screen->width = t->horizontal;
+      screen->height = t->vertical;
+
+      /* Now try setting the mode */
+      if (k < 0 || (t->horizontal != var.xres || t->vertical != var.yres))
+          fbdevConvertMonitorTiming (t, &var);
+    }
 
     var.activate = FB_ACTIVATE_NOW;
     var.bits_per_pixel = screen->fb[0].depth;
commit c4fd1121531b0cba1a3e90fa747871d784365c7e
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 18:05:53 2008 +0100

    Add mediumraw support to the linux kdrive driver
    
    Signed-off-by: Daniel Stone <daniel at fooishbar.org>

diff --git a/hw/kdrive/linux/keyboard.c b/hw/kdrive/linux/keyboard.c
index 3193ab7..ae981b7 100644
--- a/hw/kdrive/linux/keyboard.c
+++ b/hw/kdrive/linux/keyboard.c
@@ -42,6 +42,8 @@
 #include <sys/ioctl.h>
 
 extern int LinuxConsoleFd;
+static unsigned char mediumraw_data, mediumraw_up;
+static enum { DEFAULT, EXTBYTE1, EXTBYTE2 } mediumraw_state = DEFAULT;
 
 static const KeySym linux_to_x[256] = {
 	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
@@ -701,7 +703,29 @@ LinuxKeyboardRead (int fd, void *closure)
             else
 #endif
                 scancode = b[0] & 0x7f;
-	    KdEnqueueKeyboardEvent (closure, scancode, b[0] & 0x80);
+	    /* This is extended medium raw mode interpreter
+	       see linux/drivers/keyboard.c (kbd->kbdmode == VC_MEDIUMRAW) */
+	    switch (mediumraw_state)
+	    {
+	    case DEFAULT:
+		if (scancode == 0)
+		{
+		    mediumraw_state = EXTBYTE1;
+		    mediumraw_up = b[0] & 0x80;
+		}
+		else
+		    KdEnqueueKeyboardEvent (closure, scancode, b[0] & 0x80);
+		break;
+	    case EXTBYTE1:
+		mediumraw_data = scancode;
+		mediumraw_state = EXTBYTE2;
+		break;
+	    case EXTBYTE2:
+		/* Note: Only codes < 256 will pass correctly through KdEnqueueKeyboardEvent() */
+	      KdEnqueueKeyboardEvent (closure, (int)mediumraw_data << 7 | scancode, mediumraw_up);
+		mediumraw_state = DEFAULT;
+		break;
+	    }
 	    b++;
 	}
     }
commit 455383db95618a05ebdbeae78423e08065f0e14e
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 18:04:31 2008 +0100

    Enable the epson kdrive driver
    
    Signed-off-by: Daniel Stone <daniel at fooishbar.org>

diff --git a/hw/kdrive/Makefile.am b/hw/kdrive/Makefile.am
index 5803644..767e1c4 100644
--- a/hw/kdrive/Makefile.am
+++ b/hw/kdrive/Makefile.am
@@ -1,10 +1,10 @@
 if KDRIVEVESA
-VESA_SUBDIRS = vesa ati chips epson i810 mach64 mga nvidia pm2 r128 \
+VESA_SUBDIRS = vesa ati chips i810 mach64 mga nvidia pm2 r128 \
                smi via
 endif
 
 if BUILD_KDRIVEFBDEVLIB
-FBDEV_SUBDIRS = fbdev
+FBDEV_SUBDIRS = fbdev epson
 endif
 
 if XFAKESERVER
commit 82b37d35af13a9f402755e167493ab256b664b9c
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 16:38:14 2008 +0100

    Add support for AVR32

diff --git a/include/servermd.h b/include/servermd.h
index 6168410..7b0a328 100644
--- a/include/servermd.h
+++ b/include/servermd.h
@@ -130,6 +130,16 @@ SOFTWARE.
 
 #endif /* vax */
 
+#ifdef __avr32__
+
+#define IMAGE_BYTE_ORDER        MSBFirst
+#define BITMAP_BIT_ORDER        MSBFirst
+#define GLYPHPADBYTES           4
+#define GETLEFTBITS_ALIGNMENT   1
+#define AVOID_MEMORY_READ
+
+#endif /* __avr32__ */ 
+
 #ifdef __arm32__
 
 #define IMAGE_BYTE_ORDER        LSBFirst
commit 20a90bef8b4993f06cf76ad05e3d4c974e1614f6
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 16:37:02 2008 +0100

    Add a default touchscreen path
    
    When enabling the touchscreen, open /dev/input/touchscreen0 if no path was
    specified.

diff --git a/hw/kdrive/linux/tslib.c b/hw/kdrive/linux/tslib.c
index 371aece..50cd7cb 100644
--- a/hw/kdrive/linux/tslib.c
+++ b/hw/kdrive/linux/tslib.c
@@ -114,6 +114,10 @@ TslibEnable (KdPointerInfo *pi)
 
     private->raw_event_hook = NULL;
     private->raw_event_closure = NULL;
+    if (!pi->path) {
+        pi->path = "/dev/input/touchscreen0";
+        ErrorF("[tslib/TslibEnable] no device path given, trying %s\n", pi->path);
+    }
     private->tsDev = ts_open(pi->path, 0);
     private->fd = ts_fd(private->tsDev);
     if (!private->tsDev || ts_config(private->tsDev) || private->fd < 0) {
commit b44e89f4683ffcfd75eaf39f1f37d7461db44689
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 16:28:39 2008 +0100

    Update to tslib 1.0
    
    Update the pkgconfig checks to tslib 1.0, and fix the LIBS definitions.

diff --git a/configure.ac b/configure.ac
index efb6e66..04d976c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1942,7 +1942,7 @@ if test "$KDRIVE" = yes; then
         AC_CHECK_LIB([rt], [nanosleep], XEPHYR_LIBS="$XEPHYR_LIBS -lrt"))
     
     if test "x$TSLIB" = xyes; then
-        PKG_CHECK_MODULES([TSLIB], [tslib-0.0], [HAVE_TSLIB="yes"], [HAVE_TSLIB="no"])
+        PKG_CHECK_MODULES([TSLIB], [tslib-1.0], [HAVE_TSLIB="yes"], [HAVE_TSLIB="no"])
         if test "x$HAVE_TSLIB" = xno; then
             AC_MSG_ERROR([tslib must be installed to build the tslib driver. See http://tslib.berlios.de/])
         fi
@@ -1966,10 +1966,10 @@ if test "$KDRIVE" = yes; then
 	    ;;
     esac
     KDRIVE_STUB_LIB='$(top_builddir)/hw/kdrive/src/libkdrivestubs.a'
-    KDRIVE_LOCAL_LIBS="$TSLIB_LIBS $DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
+    KDRIVE_LOCAL_LIBS="$DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $FB_LIB $MI_LIB $KDRIVE_PURE_LIBS"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
-    KDRIVE_LIBS="$KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
+    KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
 
     # check if we can build Xephyr
     PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
commit 3848422d2354b7a5302fda92b05b0d728190e050
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 16:25:23 2008 +0100

    Fix build when XKB is disabled.

diff --git a/dix/devices.c b/dix/devices.c
index 5a726af..2c9a329 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -524,8 +524,8 @@ CloseDevice(DeviceIntPtr dev)
 #ifdef XKB
 	if (dev->key->xkbInfo)
 	    XkbFreeInfo(dev->key->xkbInfo);
-#endif
         dev->key->xkbInfo = NULL;
+#endif
 	xfree(dev->key->curKeySyms.map);
 	xfree(dev->key->modifierKeyMap);
 	xfree(dev->key);
commit 744d0cfda74f8283801cc2d6c5eda48402455bc3
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Apr 21 22:06:38 2008 -0700

    add missing DARWIN_GLX_LIBS in configure.ac
    (cherry picked from commit a033c0b3dbb3b963261faa39f0236457cb00ff44)

diff --git a/configure.ac b/configure.ac
index d3a2317..efb6e66 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1742,7 +1742,7 @@ if test "x$XQUARTZ" = xyes; then
 #	])
 	xorg_cv_AGL_framework=no
 	DARWIN_GLX_LIBS='$(top_builddir)/GL/apple/indirect.o $(top_builddir)/GL/glx/libglx.la'
-	DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB"
+	DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $DARWIN_GLX_LIBS"
 	AC_SUBST([DARWIN_LIBS])
 	AC_CHECK_LIB([Xplugin],[xp_init],[:])
 	CFLAGS="${CFLAGS} -DROOTLESS_WORKAROUND -DNO_ALLOCA"
commit 2ddbfd345786aa39b6ccaed82a1ca5c145284ee3
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Tue Apr 22 16:31:44 2008 +0930

    xnest: re-enable XKB support. #10015
    
    XKB was disabled in 08928afb0500d46b0caa0a1d1244dee2ed80e6a0, with the comment
    "Disable XKB, as we can't yet use it". Seems like "yet" is over, running GNOME
    and changing XKB settings seems to work in Xnest now.
    
    X.Org Bug 10015 <https://bugs.freedesktop.org/show_bug.cgi?id=10015>

diff --git a/hw/xnest/Args.c b/hw/xnest/Args.c
index f061f9e..209f175 100644
--- a/hw/xnest/Args.c
+++ b/hw/xnest/Args.c
@@ -57,11 +57,6 @@ void ddxInitGlobals(void)
     extern Bool noCompositeExtension;
     noCompositeExtension = TRUE;
 #endif
-
-#ifdef XKB
-    extern Bool noXkbExtension;
-    noXkbExtension = TRUE;
-#endif
 }
 
 int
commit a8b8700c7345b89953c8b63cb5c347a95e6ab988
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 21 23:44:37 2008 -0700

    XQuartz: Fixed cmd-tab to bring all windows forward.
    (cherry picked from commit e48e2ce931228f4dfa36c39b8ec8c72a58025b1b)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 3df19de..265819a 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -264,7 +264,8 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 				_appFlags._active = YES;
 
 				[self activateX:YES];
-				if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
+				if ([e data2] & 0x10) 
+                    DarwinSendDDXEvent(kXquartzBringAllToFront, 0);
 			}
 			break;
 
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 98cb395..8dfe4b3 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -754,12 +754,6 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
     return YES;
 }
 
-- (OSX_BOOL) applicationShouldHandleReopen:(NSApplication *)app
-                     hasVisibleWindows:(OSX_BOOL)hasVis {
-    DarwinSendDDXEvent(kXquartzBringAllToFront, 0);
-    return YES;
-}
-
 @end
 
 void X11ControllerMain(int argc, const char **argv, void (*server_thread) (void *), void *server_arg) {
commit a368ab757edf36ed7bbda023673d28883ce11231
Author: Dave Airlie <airlied at linux.ie>
Date:   Tue Apr 22 15:13:57 2008 +1000

    GLcore: make googleearth not crash the server on sw-rendering.
    
    I don't think this is the 100% correct answer as I get log spam saying
    (EE) DoSwapInterval: cx = 0x98b8998, GLX screen = 0x96dd780
    (EE) AIGLX: cx->pGlxScreen->swapInterval == NULL
    
    but thats better than X exiting in my book.

diff --git a/GL/glx/glxglcore.c b/GL/glx/glxglcore.c
index 1eac0eb..c8a2514 100644
--- a/GL/glx/glxglcore.c
+++ b/GL/glx/glxglcore.c
@@ -432,6 +432,7 @@ __glXMesaScreenProbe(ScreenPtr pScreen)
     screen->base.destroy        = __glXMesaScreenDestroy;
     screen->base.createContext  = __glXMesaScreenCreateContext;
     screen->base.createDrawable = __glXMesaScreenCreateDrawable;
+    screen->base.swapInterval  = NULL;
     screen->base.pScreen       = pScreen;
 
     return &screen->base;
commit 449723510a1f9d024e23d9eb33795cac27f9443e
Author: Egbert Eich <eich at pdx.freedesktop.org>
Date:   Tue Apr 22 13:30:03 2008 +0930

    xkb: use the correct device instead of an uninitialised "dev". #15614
    
    X.Org Bug 15614 <http://bugs.freedesktop.org/show_bug.cgi?id=15614>
    
    Signed-off-by: Peter Hutterer <peter at cs.unisa.edu.au>

diff --git a/xkb/xkbActions.c b/xkb/xkbActions.c
index 8c72874..f226b6b 100644
--- a/xkb/xkbActions.c
+++ b/xkb/xkbActions.c
@@ -1031,7 +1031,7 @@ _XkbFilterDeviceBtn(	XkbSrvInfoPtr	xkbi,
 DeviceIntPtr	dev;
 int		button;
 
-    if (dev == inputInfo.keyboard)
+    if (xkbi->device == inputInfo.keyboard)
         return 0;
 
     if (filter->keycode==0) {		/* initial press */
commit ba87c25321c3378fd1ad0c55dcb0af0a6e82a540
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 21 20:03:08 2008 -0700

    Make rootless use dixLookupClient rather than deprecated LookupClient.
    (cherry picked from commit 582b5b01f9697b66489ea906a2ecb8bfc5915571)

diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index fa395a8..df1d3a8 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -131,32 +131,38 @@ RootlessNativeWindowStateChanged (WindowPtr pWin, unsigned int state)
   pWin->rootlessUnhittable = winRec->is_offscreen;
 }
 
-void
-RootlessNativeWindowMoved (WindowPtr pWin)
-{
-  xp_box bounds;
-  int sx, sy;
-  XID vlist[2];
-  Mask mask;
-  RootlessWindowRec *winRec = WINREC(pWin);
-
-  if (xp_get_window_bounds ((xp_window_id)winRec->wid, &bounds) != Success) return;
-
-  sx = dixScreenOrigins[pWin->drawable.pScreen->myNum].x + darwinMainScreenX;
-  sy = dixScreenOrigins[pWin->drawable.pScreen->myNum].y + darwinMainScreenY;
-
-  /* Fake up a ConfigureWindow packet to resize the window to the current bounds. */
-
-  vlist[0] = (INT16) bounds.x1 - sx;
-  vlist[1] = (INT16) bounds.y1 - sy;
-  mask = CWX | CWY;
-
-  /* Don't want to do anything to the physical window (avoids 
+void RootlessNativeWindowMoved (WindowPtr pWin) {
+    xp_box bounds;
+    int sx, sy, err;
+    XID vlist[2];
+    Mask mask;
+    ClientPtr client, pClient;
+    RootlessWindowRec *winRec = WINREC(pWin);
+    
+    if (xp_get_window_bounds ((xp_window_id)winRec->wid, &bounds) != Success) return;
+    
+    sx = dixScreenOrigins[pWin->drawable.pScreen->myNum].x + darwinMainScreenX;
+    sy = dixScreenOrigins[pWin->drawable.pScreen->myNum].y + darwinMainScreenY;
+    
+    /* Fake up a ConfigureWindow packet to resize the window to the current bounds. */
+    
+    vlist[0] = (INT16) bounds.x1 - sx;
+    vlist[1] = (INT16) bounds.y1 - sy;
+    mask = CWX | CWY;
+    
+    /* pretend we're the owner of the window! */
+    err = dixLookupClient(&pClient, pWin->drawable.id, NullClient, DixUnknownAccess);
+    if(err != Success) {
+        ErrorF("RootlessNativeWindowMoved(): Failed to lookup window: 0x%x\n", pWin->drawable.id);
+        return;
+    }
+    
+    /* Don't want to do anything to the physical window (avoids 
      notification-response feedback loops) */
-
-  no_configure_window = TRUE;
-  ConfigureWindow (pWin, mask, vlist, serverClient);
-  no_configure_window = FALSE;
+    
+    no_configure_window = TRUE;
+    ConfigureWindow (pWin, mask, vlist, client);
+    no_configure_window = FALSE;
 }
 
 /* Updates the _NATIVE_SCREEN_ORIGIN property on the given root window. */
commit 8822110d7d6b684f373fc883aeb7cab9734e9ddb
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 21 20:08:05 2008 -0700

    Fixed dixLookupClient to work with client=NullClient as it did in the 1.3 branch
    (cherry picked from commit e41ccc64702f856e5e09dfa652fe73c14b8a0225)
    (cherry picked from commit ce5a5f93990647de85e535734ee6bb430ad591cb)

diff --git a/dix/dixutils.c b/dix/dixutils.c
index aaf5106..22935ce 100644
--- a/dix/dixutils.c
+++ b/dix/dixutils.c
@@ -270,7 +270,8 @@ dixLookupClient(ClientPtr *pClient, XID rid, ClientPtr client, Mask access)
     *pClient = clients[clientIndex];
     return Success;
 bad:
-    client->errorValue = rid;
+    if(client)
+        client->errorValue = rid;
     *pClient = NULL;
     return rc;
 }
commit 5ffb6a2fe8db5871eaf26b8535af1588c43f33d3
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Apr 21 19:55:54 2008 -0700

    Nuke a call to deprecated LookupClient, and hopefully prevent a
    null-pointer dereference, too!
    (cherry picked from commit 3d28e9f953709914e18807bc74c241333671cb30)

diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index a6002bb..fa395a8 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -138,7 +138,6 @@ RootlessNativeWindowMoved (WindowPtr pWin)
   int sx, sy;
   XID vlist[2];
   Mask mask;
-  ClientPtr client;
   RootlessWindowRec *winRec = WINREC(pWin);
 
   if (xp_get_window_bounds ((xp_window_id)winRec->wid, &bounds) != Success) return;
@@ -152,14 +151,11 @@ RootlessNativeWindowMoved (WindowPtr pWin)
   vlist[1] = (INT16) bounds.y1 - sy;
   mask = CWX | CWY;
 
-  /* pretend we're the owner of the window! */
-  client = LookupClient (pWin->drawable.id, NullClient);
-
   /* Don't want to do anything to the physical window (avoids 
      notification-response feedback loops) */
 
   no_configure_window = TRUE;
-  ConfigureWindow (pWin, mask, vlist, client);
+  ConfigureWindow (pWin, mask, vlist, serverClient);
   no_configure_window = FALSE;
 }
 
commit 590688131d89595bdc78ca562ee88df86c9012a6
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sun Apr 20 22:18:45 2008 -0700

    XQuartz: Fixed quit dialog to be more conforming with HIG.
    (cherry picked from commit 14c6b837bb03bd0956f90882f550847f13d0ca09)

diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index f2dee2c..98cb395 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -690,24 +690,26 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMShowAll);
 }
 
-- (NSApplicationTerminateReply) applicationShouldTerminate:sender
-{
-  NSString *msg;
-	
-  if (can_quit || [X11App prefs_get_boolean:@PREFS_NO_QUIT_ALERT default:NO])
-    return NSTerminateNow;
+- (NSApplicationTerminateReply) applicationShouldTerminate:sender {
+    NSString *msg;
+    NSString *title;
 	
-  /* Make sure we're frontmost. */
-  [NSApp activateIgnoringOtherApps:YES];
+    if (can_quit || [X11App prefs_get_boolean:@PREFS_NO_QUIT_ALERT default:NO])
+        return NSTerminateNow;
 	
-  msg = NSLocalizedString (@"Are you sure you want to quit X11?\n\nIf you quit X11, any X11 applications you are running will stop immediately and you will lose any changes you have not saved.", @"Dialog when quitting");
+    /* Make sure we're frontmost. */
+    [NSApp activateIgnoringOtherApps:YES];
 	
-  /* FIXME: safe to run the alert in here? Or should we return Later
-     and then run the alert on a timer? It seems to work here, so.. */
+    title = NSLocalizedString(@"Do you really want to quit X11?", @"Dialog title when quitting");
+    msg = NSLocalizedString(@"Any open X11 applications will stop immediately, and you will lose any unsaved changes.", @"Dialog when quitting");
+
+    /* FIXME: safe to run the alert in here? Or should we return Later
+     *        and then run the alert on a timer? It seems to work here, so..
+     */
 	
-  return (NSRunAlertPanel (nil, msg, NSLocalizedString (@"Quit", @""),
-			   NSLocalizedString (@"Cancel", @""), nil)
-	  == NSAlertDefaultReturn) ? NSTerminateNow : NSTerminateCancel;
+    return (NSRunAlertPanel (title, msg, NSLocalizedString (@"Quit", @""),
+                             NSLocalizedString (@"Cancel", @""), nil)
+            == NSAlertDefaultReturn) ? NSTerminateNow : NSTerminateCancel;
 }
 
 - (void) applicationWillTerminate:(NSNotification *)aNotification
commit d20b3ac22d960fa44632cc4a14be079daa2d5a33
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sun Apr 20 22:18:19 2008 -0700

    .gitignore: Added Xquartz stuff
    (cherry picked from commit 0a9a3bec2de8d1f442493e13cf9f039902a4928f)

diff --git a/.gitignore b/.gitignore
index 548e784..a6925d9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -278,6 +278,8 @@ hw/xprint/doc/Xprt.1x
 hw/xprint/doc/Xprt.man
 hw/xprint/dpmsstubs-wrapper.c
 hw/xprint/miinitext-wrapper.c
+hw/xquartz/xpr/Xquartz
+hw/xquartz/xpr/Xquartz.1
 include/dix-config.h
 include/kdrive-config.h
 include/xgl-config.h
commit 570b0dca261920c9b01b4eb11fe9b9987b1c636a
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Apr 21 17:52:10 2008 -0700

    Fix for pointer-offset issue when using a multi-display environment on X11.app.
    (cherry picked from commit 9a7e14286ced55c5e2a4512e2629e03836443009)

diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index f685d4a..6f7598f 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -150,7 +150,7 @@ displayScreenBounds(CGDirectDisplayID id)
 
     /* Remove menubar to help standard X11 window managers. */
 
-    if (frame.origin.x == 0 && frame.origin.y == 0)
+    if (frame.origin.y == 0)
     {
         frame.origin.y += aquaMenuBarHeight;
         frame.size.height -= aquaMenuBarHeight;
commit 3f081b4de55e1378728a24d069bf06575ffca2d8
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Mon Apr 21 11:22:07 2008 +0200

    EXA: Set pixmap->accel_blocked on the screen pixmap, too.

diff --git a/exa/exa.c b/exa/exa.c
index 0e3ea70..3a6ad98 100644
--- a/exa/exa.c
+++ b/exa/exa.c
@@ -699,6 +699,34 @@ exaBitmapToRegion(PixmapPtr pPix)
   return ret;
 }
 
+static Bool
+exaCreateScreenResources(ScreenPtr pScreen)
+{
+    ExaScreenPriv(pScreen);
+    PixmapPtr pScreenPixmap;
+    Bool b;
+
+    pScreen->CreateScreenResources = pExaScr->SavedCreateScreenResources;
+    b = pScreen->CreateScreenResources(pScreen);
+    pScreen->CreateScreenResources = exaCreateScreenResources;
+
+    if (!b)
+        return FALSE;
+
+    pScreenPixmap = pScreen->GetScreenPixmap(pScreen);
+
+    if (pScreenPixmap) {
+        ExaPixmapPriv(pScreenPixmap);
+
+        exaSetAccelBlock(pExaScr, pExaPixmap,
+                         pScreenPixmap->drawable.width,
+                         pScreenPixmap->drawable.height,
+                         pScreenPixmap->drawable.bitsPerPixel);
+    }
+
+    return TRUE;
+}
+
 /**
  * exaCloseScreen() unwraps its wrapped screen functions and tears down EXA's
  * screen private, before calling down to the next CloseSccreen.
@@ -720,6 +748,7 @@ exaCloseScreen(int i, ScreenPtr pScreen)
     pScreen->CopyWindow = pExaScr->SavedCopyWindow;
     pScreen->ChangeWindowAttributes = pExaScr->SavedChangeWindowAttributes;
     pScreen->BitmapToRegion = pExaScr->SavedBitmapToRegion;
+    pScreen->CreateScreenResources = pExaScr->SavedCreateScreenResources;
 #ifdef RENDER
     if (ps) {
 	ps->Composite = pExaScr->SavedComposite;
@@ -877,6 +906,9 @@ exaDriverInit (ScreenPtr		pScreen,
     pExaScr->SavedBitmapToRegion = pScreen->BitmapToRegion;
     pScreen->BitmapToRegion = exaBitmapToRegion;
 
+    pExaScr->SavedCreateScreenResources = pScreen->CreateScreenResources;
+    pScreen->CreateScreenResources = exaCreateScreenResources;
+
 #ifdef RENDER
     if (ps) {
         pExaScr->SavedComposite = ps->Composite;
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index e41f46a..0138e4a 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -107,6 +107,7 @@ typedef struct {
     CopyWindowProcPtr 		 SavedCopyWindow;
     ChangeWindowAttributesProcPtr SavedChangeWindowAttributes;
     BitmapToRegionProcPtr        SavedBitmapToRegion;
+    CreateScreenResourcesProcPtr SavedCreateScreenResources;
     ModifyPixmapHeaderProcPtr    SavedModifyPixmapHeader;
 #ifdef RENDER
     CompositeProcPtr             SavedComposite;
commit 26c1801a27b81fdd988d5bd210ba0e76ecc274ae
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Mon Apr 21 11:03:27 2008 +0200

    EXA: Update sys_pitch/fb_pitch in exaModifyPixmapHeader.
    
    exaModifyPixmapHeader now also only evaluates arguments that have a
    meaningful value.

diff --git a/exa/exa.c b/exa/exa.c
index 81dc3e2..0e3ea70 100644
--- a/exa/exa.c
+++ b/exa/exa.c
@@ -248,6 +248,19 @@ exaSetAccelBlock(ExaScreenPrivPtr pExaScr, ExaPixmapPrivPtr pExaPixmap,
         pExaPixmap->accel_blocked |= EXA_RANGE_HEIGHT;
 }
 
+static void
+exaSetFbPitch(ExaScreenPrivPtr pExaScr, ExaPixmapPrivPtr pExaPixmap,
+              int w, int h, int bpp)
+{
+    if (pExaScr->info->flags & EXA_OFFSCREEN_ALIGN_POT && w != 1)
+        pExaPixmap->fb_pitch = (1 << (exaLog2(w - 1) + 1)) * bpp / 8;
+    else
+        pExaPixmap->fb_pitch = w * bpp / 8;
+
+    pExaPixmap->fb_pitch = EXA_ALIGN(pExaPixmap->fb_pitch,
+                                     pExaScr->info->pixmapPitchAlign);
+}
+
 /**
  * exaCreatePixmap() creates a new pixmap.
  *
@@ -292,12 +305,8 @@ exaCreatePixmap(ScreenPtr pScreen, int w, int h, int depth,
         if (paddedWidth / 4 > 32767 || h > 32767)
             return NullPixmap;
 
-        if (pExaScr->info->flags & EXA_OFFSCREEN_ALIGN_POT && w != 1)
-            pExaPixmap->fb_pitch = (1 << (exaLog2(w - 1) + 1)) * bpp / 8;
-        else
-            pExaPixmap->fb_pitch = w * bpp / 8;
-        pExaPixmap->fb_pitch = EXA_ALIGN(pExaPixmap->fb_pitch,
-                                         pExaScr->info->pixmapPitchAlign);
+        exaSetFbPitch(pExaScr, pExaPixmap, w, h, bpp);
+
         if (paddedWidth < pExaPixmap->fb_pitch)
             paddedWidth = pExaPixmap->fb_pitch;
 
@@ -331,12 +340,7 @@ exaCreatePixmap(ScreenPtr pScreen, int w, int h, int depth,
         pExaPixmap->offscreen = FALSE;
 
         pExaPixmap->fb_ptr = NULL;
-        if (pExaScr->info->flags & EXA_OFFSCREEN_ALIGN_POT && w != 1)
-            pExaPixmap->fb_pitch = (1 << (exaLog2(w - 1) + 1)) * bpp / 8;
-        else
-            pExaPixmap->fb_pitch = w * bpp / 8;
-        pExaPixmap->fb_pitch = EXA_ALIGN(pExaPixmap->fb_pitch,
-				         pExaScr->info->pixmapPitchAlign);
+        exaSetFbPitch(pExaScr, pExaPixmap, w, h, bpp);
         pExaPixmap->fb_size = pExaPixmap->fb_pitch * h;
 
         if (pExaPixmap->fb_pitch > 131071) {
@@ -384,10 +388,19 @@ exaModifyPixmapHeader(PixmapPtr pPixmap, int width, int height, int depth,
     pExaPixmap = ExaGetPixmapPriv(pPixmap);
 
     if (pExaPixmap) {
-	pExaPixmap->sys_ptr = pPixData;
+        if (pPixData)
+            pExaPixmap->sys_ptr = pPixData;
 
-        exaSetAccelBlock(pExaScr, pExaPixmap,
-                         width, height, bitsPerPixel);
+        if (devKind > 0)
+            pExaPixmap->sys_pitch = devKind;
+
+        if (width > 0 && height > 0 && bitsPerPixel > 0) {
+            exaSetFbPitch(pExaScr, pExaPixmap,
+                          width, height, bitsPerPixel);
+
+            exaSetAccelBlock(pExaScr, pExaPixmap,
+                             width, height, bitsPerPixel);
+        }
     }
 
 
commit 4fa89fbe18c929e0d36305ab47e7e17841309ffd
Author: Jordan Crouse <jordan.crouse at amd.com>
Date:   Mon Apr 21 12:09:00 2008 -0600

    xf86: Change AutoConfig driver for PCI ID 022:2091 to 'geode'

diff --git a/hw/xfree86/common/xf86AutoConfig.c b/hw/xfree86/common/xf86AutoConfig.c
index 92b204b..5ffd847 100644
--- a/hw/xfree86/common/xf86AutoConfig.c
+++ b/hw/xfree86/common/xf86AutoConfig.c
@@ -146,7 +146,11 @@ videoPtrToDriverName(struct pci_device *dev)
 
     switch (dev->vendor_id)
     {
-	case 0x1022:		    return "amd";
+	case 0x1022:
+		if (dev->device_id == 0x2081)
+			return "geode";
+		else
+			return NULL;
 	case 0x1142:		    return "apm";
 	case 0xedd8:		    return "ark";
 	case 0x1a03:		    return "ast";
commit 6c95fae1e9d6b0eb64bc78eced05a6e9f5faf02e
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Mon Apr 21 10:45:11 2008 +0200

    EXA: Offscreen memory eviction improvements.
    
    * Make sure available areas are considered to have no eviction cost. This seems
      to help for https://bugs.freedesktop.org/show_bug.cgi?id=15513 but I'm afraid
      that may just be coincidence.
    * Only calculate eviction cost of each area once for each eviction pass.
      Safeguard against potential (though unlikely) division by zero.
    * Cosmetic enhancements: Name eviction cost related variables 'cost' instead of
      'score' to emphasize that smaller values are better, update Doxygen file
      comment to the way eviction works now.

diff --git a/exa/exa.h b/exa/exa.h
index 97ae6c0..2562094 100644
--- a/exa/exa.h
+++ b/exa/exa.h
@@ -64,6 +64,8 @@ struct _ExaOffscreenArea {
     ExaOffscreenState   state;
 
     ExaOffscreenArea    *next;
+
+    unsigned            eviction_cost;
 };
 
 /**
diff --git a/exa/exa_offscreen.c b/exa/exa_offscreen.c
index 85b5388..4aaa2c1 100644
--- a/exa/exa_offscreen.c
+++ b/exa/exa_offscreen.c
@@ -21,11 +21,9 @@
  */
 
 /** @file
- * This allocator allocates blocks of memory by maintaining a list of areas
- * and a score for each area.  As an area is marked used, its score is
- * incremented, and periodically all of the areas have their scores decayed by
- * a fraction.  When allocating, the contiguous block of areas with the minimum
- * score is found and evicted in order to make room for the new allocation.
+ * This allocator allocates blocks of memory by maintaining a list of areas.
+ * When allocating, the contiguous block of areas with the minimum eviction
+ * cost is found and evicted in order to make room for the new allocation.
  */
 
 #include "exa_priv.h"
@@ -71,19 +69,36 @@ ExaOffscreenKickOut (ScreenPtr pScreen, ExaOffscreenArea *area)
     return exaOffscreenFree (pScreen, area);
 }
 
-#define AREA_SCORE(area) (area->size / (double)(pExaScr->offScreenCounter - area->last_use))
+static void
+exaUpdateEvictionCost(ExaOffscreenArea *area, unsigned offScreenCounter)
+{
+    unsigned age;
+
+    if (area->state == ExaOffscreenAvail)
+	return;
+
+    age = offScreenCounter - area->last_use;
+
+    /* This is unlikely to happen, but could result in a division by zero... */
+    if (age > (UINT_MAX / 2)) {
+	age = UINT_MAX / 2;
+	area->last_use = offScreenCounter - age;
+    }
+
+    area->eviction_cost = area->size / age;
+}
 
 static ExaOffscreenArea *
 exaFindAreaToEvict(ExaScreenPrivPtr pExaScr, int size, int align)
 {
     ExaOffscreenArea *begin, *end, *best;
-    double score, best_score;
+    unsigned cost, best_cost;
     int avail, real_size, tmp;
 
-    best_score = UINT_MAX;
+    best_cost = UINT_MAX;
     begin = end = pExaScr->info->offScreenAreas;
     avail = 0;
-    score = 0;
+    cost = 0;
     best = 0;
 
     while (end != NULL)
@@ -106,23 +121,24 @@ exaFindAreaToEvict(ExaScreenPrivPtr pExaScr, int size, int align)
 	    if (end->state == ExaOffscreenLocked) {
 		/* Can't more room here, restart after this locked area */
 		avail = 0;
-		score = 0;
+		cost = 0;
 		begin = end;
 		goto restart;
 	    }
 	    avail += end->size;
-	    score += AREA_SCORE(end);
+	    exaUpdateEvictionCost(end, pExaScr->offScreenCounter);
+	    cost += end->eviction_cost;
 	    end = end->next;
 	}
 
-	/* Check the score, update best */
-	if (avail >= real_size && score < best_score) {
+	/* Check the cost, update best */
+	if (avail >= real_size && cost < best_cost) {
 	    best = begin;
-	    best_score = score;
+	    best_cost = cost;
 	}
 
 	avail -= begin->size;
-	score -= AREA_SCORE(begin);
+	cost -= begin->eviction_cost;
 	begin = begin->next;
     }
 
@@ -244,6 +260,7 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 	new_area->state = ExaOffscreenAvail;
 	new_area->save = NULL;
 	new_area->last_use = 0;
+	new_area->eviction_cost = 0;
 	new_area->next = area->next;
 	area->next = new_area;
 	area->size = real_size;
@@ -409,6 +426,7 @@ exaOffscreenFree (ScreenPtr pScreen, ExaOffscreenArea *area)
     area->state = ExaOffscreenAvail;
     area->save = NULL;
     area->last_use = 0;
+    area->eviction_cost = 0;
     /*
      * Find previous area
      */
@@ -474,6 +492,7 @@ exaOffscreenInit (ScreenPtr pScreen)
     area->save = NULL;
     area->next = NULL;
     area->last_use = 0;
+    area->eviction_cost = 0;
 
     /* Add it to the free areas */
     pExaScr->info->offScreenAreas = area;
commit 40c6be1408a1f0b236fdb28af27ae18aea0d578f
Author: Julien Cristau <jcristau at debian.org>
Date:   Sun Apr 20 20:36:44 2008 +0200

    Minor xorg.conf manpage fixups
    
    Use __libmansuffix__ instead of __oslibmansuffix__ which isn't getting
    replaced, and rewrap some text to get __xservername__ replaced in the
    description of Option "Accel" (cpp doesn't like the preceding quote).

diff --git a/hw/xfree86/doc/man/xorg.conf.man.pre b/hw/xfree86/doc/man/xorg.conf.man.pre
index 9f39808..8b66f89 100644
--- a/hw/xfree86/doc/man/xorg.conf.man.pre
+++ b/hw/xfree86/doc/man/xorg.conf.man.pre
@@ -54,7 +54,7 @@ is the relative path (with no \(lq..\(rq components) specified by that
 environment variable, and
 .I <hostname>
 is the machine's hostname as reported by
-.BR gethostname (__oslibmansuffix__).
+.BR gethostname (__libmansuffix__).
 .PP
 When the __xservername__ server is started by the \(lqroot\(rq user, the config file
 search locations are as follows:
@@ -93,7 +93,7 @@ is the path specified by that environment variable (usually the home
 directory), and
 .I <hostname>
 is the machine's hostname as reported by
-.BR gethostname (__oslibmansuffix__).
+.BR gethostname (__libmansuffix__).
 .PP
 The
 .I __xconfigfile__
@@ -1624,8 +1624,8 @@ Others are driver\-independent, and will eventually be described here.
 .\" XXX These should really be in an xaa man page.
 .TP 7
 .BI "Option \*qAccel\*q"
-Enables XAA (X Acceleration Architecture), a mechanism that makes video
-cards' 2D hardware acceleration available to the  __xservername__ server.
+Enables XAA (X Acceleration Architecture), a mechanism that makes video cards'
+2D hardware acceleration available to the  __xservername__ server.
 This option is on by default, but it may be necessary to turn it off if
 there are bugs in the driver.
 There are many options to disable specific accelerated operations, listed
commit 4bcfed2f9cf5dbf682d3bc98873ba97c4efdff44
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sun Apr 20 08:35:42 2008 -0700

    Revert "Removed XWin DDX"
    
    This reverts commit 6550078b0925f754e3eec3bbce94dbfe5de8c419.
    
    Doctor, I'm starting to get a pulse...

diff --git a/.gitignore b/.gitignore
index afd5415..548e784 100644
--- a/.gitignore
+++ b/.gitignore
@@ -284,6 +284,7 @@ include/xgl-config.h
 include/xkb-config.h
 include/xorg-config.h
 include/xorg-server.h
+include/xwin-config.h
 mfb/mfbbltC.c
 mfb/mfbbltCI.c
 mfb/mfbbltG.c
diff --git a/configure.ac b/configure.ac
index ca16c5a..d3a2317 100644
--- a/configure.ac
+++ b/configure.ac
@@ -46,6 +46,8 @@ dnl xorg-config.h covers the Xorg DDX.
 AC_CONFIG_HEADERS(include/xorg-config.h)
 dnl xkb-config.h covers XKB for the Xorg and Xnest DDXs.
 AC_CONFIG_HEADERS(include/xkb-config.h)
+dnl xwin-config.h covers the XWin DDX.
+AC_CONFIG_HEADERS(include/xwin-config.h)
 dnl kdrive-config.h covers the kdrive DDX
 AC_CONFIG_HEADERS(include/kdrive-config.h)
 
@@ -564,6 +566,7 @@ AC_ARG_ENABLE(xquartz,        AS_HELP_STRING([--enable-xquartz], [Build Xquartz
 AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app for Xquartz (default: auto)]), [X11APP=$enableval], [X11APP=auto])
 AC_ARG_WITH(x11app-archs,     AS_HELP_STRING([--with-x11app-archs=ARCHS], [Architectures to build X11.app for, space delimeted (default: "ppc i386")]), [X11APP_ARCHS=$enableval], [X11APP_ARCHS="ppc i386"])
 AC_SUBST([X11APP_ARCHS])
+AC_ARG_ENABLE(xwin,    	      AS_HELP_STRING([--enable-xwin], [Build XWin server (default: auto)]), [XWIN=$enableval], [XWIN=auto])
 AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
 AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (default: no)]), [XGL=$enableval], [XGL=no])
 AC_ARG_ENABLE(xglx,           AS_HELP_STRING([--enable-xglx], [Build Xglx xgl module (default: no)]), [XGLX=$enableval], [XGLX=no])
@@ -1636,6 +1639,76 @@ if test "x$XPRINT" = xyes; then
 fi
 AM_CONDITIONAL(XP_USE_FREETYPE, [test "x$XPRINT" = xyes && test "x$XP_USE_FREETYPE" = xyes])
 
+
+dnl XWin DDX
+
+AC_MSG_CHECKING([whether to build XWin DDX])
+if test "x$XWIN" = xauto; then
+	case $host_os in
+		cygwin*) XWIN="yes" ;;
+		mingw*) XWIN="yes" ;;
+		*) XWIN="no" ;;
+	esac
+	XWIN_LIBS="$FB_LIB $XEXT_LIB $CONFIG_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $DAMAGE_LIB $LAYER_LIB $XPSTUBS_LIB $SHADOW_LIB"
+	AC_SUBST([XWIN_LIBS])
+fi
+AC_MSG_RESULT([$XWIN])
+
+if test "x$XWIN" = xyes; then
+	case $host_os in
+		cygwin*)
+			XWIN_SERVER_NAME=XWin
+			PKG_CHECK_MODULES([XWINMODULES],[x11 xdmcp xau xfont])
+			AC_DEFINE(HAS_DEVWINDOWS,1,[Cygwin has /dev/windows for signaling new win32 messages])
+			AC_DEFINE(ROOTLESS,1,[Build Rootless code])
+			CFLAGS="$CFLAGS -DFD_SETSIZE=256"
+			;;
+		mingw*)
+			XWIN_SERVER_NAME=Xming
+			PKG_CHECK_MODULES([XWINMODULES],[x11 xdmcp xau xfont])
+			AC_DEFINE(RELOCATE_PROJECTROOT,1,[Make PROJECT_ROOT relative to the xserver location])
+			AC_DEFINE(HAS_WINSOCK,1,[Use Windows sockets])
+			XWIN_SYS_LIBS=-lwinsock2
+			;;
+	esac
+	XWIN_SYS_LIBS="$XWIN_SYS_LIBS $(XWINMODULES_LIBS)"
+	AC_SUBST(XWIN_SERVER_NAME)
+	AC_SUBST(XWIN_SYS_LIBS)
+
+	if test "x$DEBUGGING" = xyes; then
+		AC_DEFINE(CYGDEBUG, 1, [Simple debug messages])
+		AC_DEFINE(CYGWINDOWING_DEBUG, 1, [Debug messages for window handling])
+		AC_DEFINE(CYGMULTIWINDOW_DEBUG, 1, [Debug window manager])
+	fi
+
+	AC_DEFINE(DDXOSINIT, 1, [Use OsVendorInit])
+	AC_DEFINE(DDXTIME, 1, [Use GetTimeInMillis])
+	AC_DEFINE(DDXOSFATALERROR, 1, [Use OsVendorFatalError])
+	AC_DEFINE(DDXOSVERRORF, 1, [Use OsVendorVErrorF])
+	AC_DEFINE(DDXBEFORERESET, 1, [Use ddxBeforeReset ])
+	if test "x$XF86VIDMODE" = xyes; then
+		AC_MSG_NOTICE([Disabling XF86VidMode extension])
+		XF86VIDMODE=no
+	fi
+	if test "x$XF86MISC" = xyes; then
+		AC_MSG_NOTICE([Disabling XF86Misc extension])
+		XF86MISC=no
+	fi
+	if test "x$COMPOSITE" = xyes; then
+		AC_MSG_NOTICE([Disabling Composite extension])
+		COMPOSITE=no
+	fi
+fi
+AM_CONDITIONAL(XWIN, [test "x$XWIN" = xyes])
+AM_CONDITIONAL(XWIN_MULTIWINDOW, [test "x$XWIN" = xyes])
+AM_CONDITIONAL(XWIN_MULTIWINDOWEXTWM, [test "x$XWIN" = xyes && false])
+AM_CONDITIONAL(XWIN_CLIPBOARD, [test "x$XWIN" = xyes])
+AM_CONDITIONAL(XWIN_GLX_WINDOWS, [test "x$XWIN" = xyes && false])
+AM_CONDITIONAL(XWIN_NATIVEGDI, [test "x$XWIN" = xyes && false])
+AM_CONDITIONAL(XWIN_PRIMARYFB, [test "x$XWIN" = xyes && false])
+AM_CONDITIONAL(XWIN_RANDR, [test "x$XWIN" = xyes])
+AM_CONDITIONAL(XWIN_XV, [test "x$XWIN" = xyes && test "x$XV" = xyes])
+
 dnl Darwin / OS X DDX
 if test "X$XQUARTZ" = Xauto; then
 	AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
@@ -2133,6 +2206,7 @@ hw/xgl/glx/module/Makefile
 hw/xgl/glxext/Makefile
 hw/xgl/glxext/module/Makefile
 hw/xnest/Makefile
+hw/xwin/Makefile
 hw/xquartz/Makefile
 hw/xquartz/bundle/Makefile
 hw/xquartz/xpr/Makefile
diff --git a/hw/Makefile.am b/hw/Makefile.am
index 011a280..c2b9571 100644
--- a/hw/Makefile.am
+++ b/hw/Makefile.am
@@ -14,6 +14,10 @@ if XNEST
 XNEST_SUBDIRS = xnest
 endif
 
+if XWIN
+XWIN_SUBDIRS = xwin
+endif
+
 if XGL
 XGL_SUBDIRS = xgl
 endif
@@ -33,6 +37,7 @@ endif
 SUBDIRS =			\
 	$(XORG_SUBDIRS)		\
 	$(XGL_SUBDIRS)		\
+	$(XWIN_SUBDIRS)		\
 	$(XVFB_SUBDIRS)		\
 	$(XNEST_SUBDIRS)	\
 	$(DMX_SUBDIRS)		\
@@ -40,7 +45,7 @@ SUBDIRS =			\
 	$(XQUARTZ_SUBDIRS)	\
 	$(XPRINT_SUBDIRS)
 
-DIST_SUBDIRS = dmx xfree86 vfb xnest xquartz kdrive xgl xprint
+DIST_SUBDIRS = dmx xfree86 vfb xnest xwin xquartz kdrive xgl xprint
 
 relink:
 	for i in $(SUBDIRS) ; do $(MAKE) -C $$i relink ; done
diff --git a/hw/xwin/ChangeLog b/hw/xwin/ChangeLog
new file mode 100644
index 0000000..aca2ffc
--- /dev/null
+++ b/hw/xwin/ChangeLog
@@ -0,0 +1,683 @@
+2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
+
+	* winprefs.c: (HandleCustomWM_COMMAND):
+	https://bugs.freedesktop.org/show_bug.cgi?id=4341
+	Make Xming error messages more meaningful.
+
+2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
+
+	* winmultiwindowwndproc.c: (winTopLevelWindowProc):
+	* winwndproc.c: (winWindowProc):
+	https://bugs.freedesktop.org/show_bug.cgi?id=4538
+	Fix mouse button release on multiwindows scrolling.
+
+2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
+
+	* winmultiwindowicons.c: (winXIconToHICON), (winUpdateIcon):
+	* winwin32rootlesswindow.c: (winMWExtWMUpdateIcon):
+	https://bugs.freedesktop.org/show_bug.cgi?id=5138
+	Check for NULL pointer
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwm.c:
+	Fix crash on server shutdown
+	
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.c:
+	* winkeybd.h:
+	* winwndproc.c:
+	Fix simultanious presses of Left and Right Control and Shift keys.
+	https://bugs.freedesktop.org/show_bug.cgi?id=3677
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwm.c:
+	Fix typo which broke window titles
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	* winkeybd.c:
+	Fix problem with fake Control press on Alt-Gr
+	https://bugs.freedesktop.org/show_bug.cgi?id=3680
+	https://bugs.freedesktop.org/show_bug.cgi?id=3497
+
+	* InitOutput.c:
+	Fix static declaration of winGetBaseDir
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winwindow.h:
+	* winmultiwindowwm.c:
+	* winscrinit.c:
+	External windowmanagers could connect in multiwindow mode which lead
+	to strange results with the internal windowmanager.
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* *.c:
+	Include xwin-config.h if HAVE_XWIN_CONFIG is defined
+	Cleanup X11 includes handling
+	Warning fixes
+	
+2005-06-30  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	Pass serverClient instead of NULL to ConfigureWindow.
+	This should fix a crash reported by Øyvind Harboe
+
+2005-06-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winlayouts.h:
+	Merge from CYGWIN
+	Added layout "French (Canada)" as ca_enhanced 
+	Added Czech (QWERTY) layout
+	* winshaddnl.c:
+	Merge from CYGWIN
+	Print error code if winStoreColorsShadowDDNL fails
+
+2005-06-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwindow.c:
+	Fix crash reported by Øyvind Harboe
+
+2005-06-03  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	* winblock.c:
+	Backout last winRaiseWindow patch which caused stacking problems
+
+2005-05-25  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h:
+	* winmultiwindowwm.c:
+	Workaround bug in pthread.h
+
+2005-05-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	* winblock.c:
+	Only call ConfigureWindow from winRaiseWindow if the windows
+	message dispatch loop is running.
+
+2005-05-02  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winerror.c:
+	Print correct logfile in FatalError message
+
+2005-04-19  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	Prevent recursive calls to winRaiseWindow. 
+
+2005-03-10  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	Force rebuilding of window stack if a window changes it's state from 
+	minimized.
+
+2005-03-07  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	* winmultiwindowwindow.c:
+	Prevent winRaiseWindow from calling ConfigureWindow if the message
+	was sent from within winDestroyWindowsWindow
+
+	DestroyWindow send a WM_WINDOWPOSCHANGED to another window causing
+	a restacking of all windows, even of the window which is just about
+	to destroyed and whose structures may not be intact anymore.
+
+2005-02-24  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	on WM_WINDOWPOSCHANGED raise window directly and in sync without 
+	utilizing the async windowmanager thread. Fixes some restacking 
+	problems occuring which were timing dependent
+	Do not raise the window on WM_ACTIVATE
+	Removed unused code for WM_WINDOWPOSCHANGING
+	ESC is debug key. Print status but do not abort processing the message
+	
+2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwindow.c
+	* winmultiwindowwndproc.c
+	* winwin32rootlesswndproc.c:
+	Cleanup some message debugging
+	
+2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h
+	* winfont.c
+	* winmultiwindowshape.c
+	* winmultiwindowwindow.c
+	* winpfbdd.c
+	* winshaddd.c
+	* winshadddnl.c
+	* winshadgdi.c
+	* winwindow.c:
+	Fix incorrect wrapping of functions. Ensure the pointers from pScreen 
+	point to the called function even if wrapped functions changed it
+	
+	* winmultiwindowwindow.c:
+	Set the window properties to NULL to avoid referencing freed memory 
+	because of timing problems after deleting a window
+
+	* winscrinit.c:
+	Do not wrap ChangeWindowAttributes. All functions are noops currently
+	
+2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmsg.h:
+	* winmsg.c:
+	print window handle in message output
+	
+2005-02-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.c:
+	* winkeynames.h:
+	Updated fix for ABNT2 and HK_Toggle keys. 
+
+2005-02-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.h:
+	* winkeynames.h:
+	Backout ABNT2 and HK_Toggle fix since it broke keys F1 and F4. 
+
+2005-02-07  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winlayouts.h:
+	* winconfig.c:
+	Moved keyboard layout table to external file.
+
+2005-02-02  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* wincreatewnd.c:
+	Force ShowWindow if XWin was started via run.exe. Fixes mainwindow
+	not showing bug
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwindow.c
+	* winmultiwindowwndproc.c:
+	Create windows with SWP_NOACTIVATE flag (updated) (Kensuke Matsuzaki)
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	Fixes for window ordering problem (updated) (Kensuke Matsuzaki)
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig.c:
+	Added hungarian keyboard layout.
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmessages.h
+	* winmsg.h
+	* winmsg.c
+	* winmultiwindowwndproc.c
+	* winwin32rootlesswndproc.c
+	* winwndproc.c:
+	Make logging of messages configurable with environment variables
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c:
+	resolve SHGetFolderPath dynamicly since it is not available on all Windows 
+	systems.
+
+2005-01-12  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmsg.c
+	* winmsg.h:
+	Introduce function winTrace which prints log message with verbosity 10
+	* winmultiwindowwindow.c:
+	Use winTrace for 3 heavily called functions
+
+2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* XWin.man:
+	Document the -silent-dup-error switch
+
+2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeyhook.c:
+	Do not grab ALT-TAB when window is in multiwindow mode
+	
+2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winprefs.h:
+	Fix crash with not matching definitions of PATH_MAX
+	
+2005-01-10  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.h
+	* winkeynames.h:
+	Adjust keysyms for  Hiragana_Katakana toggle and backslash/underscore
+	on Japanese and ABNT2 keyboards
+
+2005-01-10  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.h
+	* winkeyhook.c
+	* winwndproc.c:
+	Make keyhook feature work in multiwindowmode too
+	Hook windows keys
+
+2005-01-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winblock.c:
+	Fix a possible null-pointer dereference	(Keishi Suenaga)
+
+2005-01-06  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* Imakefile 
+	* InitOutput.c 
+	* XWin.rc 
+	* winerror.c 
+	* wintrayicon.c 
+	* winvideo.c
+	* winshaddd.c       	
+	* winwindow.h:
+	Set PROJECT_NAME in Imakefile to create alternative window titles 
+	for Cygwin/X and Xming
+	
+2005-01-06  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowclass.c:
+	* winmultiwindowwm.c:
+	Fix crash with non-nullterminated strings (reported by Øyvind Harboe)
+
+2004-12-14  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c:
+	* winprocarg.c:
+	EnumDisplayMonitors is not available on Window NT4 and 95. Resolve
+	the function dynamicly
+
+2004-12-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c:
+	* winprocarg.c:
+	Added support for placing the main window with the @<monitor#>.
+	Patch by Mark Fisher, small changes by Alexander Gottwald
+	
+2004-12-06  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* XWin.rc:
+	include windows.h
+
+2004-12-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* ddraw.h:
+	redone ddraw.h to be able to mix it with w32api style COM header 
+	files. 
+	
+	* winmultiwindowwm.c:
+	* obj_base.h:
+	* ddraw.h:
+	obj_base.h is not needed anymore. Using <objbase.h> instead.
+
+	* winms.h:
+	Use Xwindows.h instead of windows.h
+
+	* winresource.h:
+	do not include win_ms.h
+	
+	* win.h:
+	remove extra definition of sleep()
+
+	* InitOutput.c:
+	Set HOME to Documents and Settings/username if not set
+	
+	* winprefs.c:
+	Use Xming basedir instead of ProjectRoot for system.XWinrc
+
+	* windialogs.c:
+	* winshadgdi.c:
+	* winprefs.c:
+	Fix callback functions to use wBOOL instead of BOOL
+
+	* winmultiwindowwindow.c:
+	* winwin32rootless.c:
+	* winwin32rootlesswindow.c:
+	* winerror.c:
+	Fix compiler warnings. Added debug output.
+
+	* winconfig.c:
+	Fix warning about undefined macro max
+	
+2004-12-04  Earle Philhower
+
+	* InitOutput.c:
+	* win.h:
+	* wincreatewnd.c:
+	* winprocarg.c:
+	Optional position -screen parameter (-screen n WxH+X+Y or 
+	-screen n W H X Y)
+
+2004-12-03  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* windialogs.c:
+	* win.h:
+	* Imakefile:
+	* winerror.c:
+	Removed scprintf, aprintf and snprintf stuff and use newXprintf
+
+2004-12-02  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winwin32rootless.c:
+	Adjust the width of the rootless backbuffer to match 32 bit alignment
+
+	* winprocarg.c:
+	Make multiplemonitors default for -internalwm
+
+2004-12-01  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c:
+	Set XERRORDB environment variable to relocate the XErrorDB file
+
+2004-11-29  Kensuke Matsuzaki  <zakki at peppermint.jp>
+
+	* winmultiwindowwm.c:
+	Fixed windows.h include for cygwin.
+	
+	* winmultiwindowwindow.c:
+	Bugzilla #1945: Stop unnecessary reordering.
+
+2004-11-24  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwm.c:
+	Finally the multiwindow mode defines a default cursor
+
+2004-11-22  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwm.c: 
+	Fixes for building multiwindow and internalwm on mingw
+	* winwin32rootless.c:
+	Changed some debugging output
+
+2004-11-22  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c, winglobals.c, winprocarg.c:
+	Xming: Place logfile in users tempdir
+	
+2004-11-15  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* Imakefile:
+	Remove override of HasSnprintf
+
+2004-11-15  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* Imakefile:
+	* InitInput.c: (InitInput):
+	* InitOutput.c: (winClipboardShutdown), (ddxGiveUp),
+	(winCheckMount), (winGetBaseDir), (winFixupPaths), (OsVendorInit),
+	(winCheckDisplayNumber):
+	* win.h:
+	* winblock.c: (winBlockHandler):
+	* winclipboard.h:
+	* winclipboardthread.c: (winClipboardProc):
+	* winclipboardwndproc.c: (winClipboardWindowProc):
+	* winconfig.c: (winConfigKeyboard), (winConfigFiles):
+	* wincreatewnd.c: (winCreateBoundingWindowWindowed):
+	* windialogs.c: (winDisplayExitDialog), (winExitDlgProc),
+	(winAboutDlgProc):
+	* winengine.c: (winSetEngine):
+	* winerror.c: (OsVendorVErrorF), (winMessageBoxF), (scprintf):
+	* winglobals.c: (winInitializeGlobals):
+	* winkeybd.c: (winKeybdReleaseKeys):
+	* winmultiwindowicons.c:
+	* winmultiwindowwindow.c: (winCreateWindowsWindow):
+	* winmultiwindowwm.c:
+	* winprefs.c: (ReloadPrefs), (HandleCustomWM_COMMAND):
+	* winprocarg.c: (ddxProcessArgument):
+	* winscrinit.c: (winFinishScreenInitFB):
+	* winshadddnl.c:
+	* wintrayicon.c: (winHandleIconMessage):
+	* winwakeup.c: (winWakeupHandler):
+	* winwin32rootless.c: (winMWExtWMCreateFrame):
+	* winwindow.c: (winReshapeRootless):
+	* winwindow.h:
+	* winwndproc.c: (winWindowProc):
+	Bufzilla #1802, http://freedesktop.org/bugzilla/show_bug.cgi?id=1802
+	Added mingw (Win32) port     
+
+2004-11-11  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig.c:
+	added keyboard layout "French (Switzerland)"
+
+2004-11-06  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winwndproc.c, wintrayicon.c, winscrinit.c:
+	* winmultiwindowwindow.c:
+	Wrap all mwextwm and internalwm code with XWIN_MULTIWINDOWEXTWM
+
+2004-11-04  Kensuke Matsuzaki  <zakki at peppermint.jp>
+
+	* InitOutput.c: (winUseMsg):
+	* win.h:
+	* winmultiwindowwindow.c: (winMinimizeWindow):
+	* winmultiwindowwm.c: (PushMessage), (UpdateName),
+	(PreserveWin32Stack), (winMultiWindowWMProc),
+	(winMultiWindowXMsgProc), (winInitWM), (winInitMultiWindowWM),
+	(CheckAnotherWindowManager):
+	* winprocarg.c: (winInitializeDefaultScreens),
+	(ddxProcessArgument):
+	* winscrinit.c: (winFinishScreenInitFB):
+	* wintrayicon.c: (winHandleIconMessage):
+	* winwin32rootless.c: (InitWin32RootlessEngine),
+	(winMWExtWMResizeFrame), (winMWExtWMRestackFrame),
+	(winMWExtWMStartDrawing), (winMWExtWMRootlessSwitchWindow),
+	(winMWExtWMSetNativeProperty):
+	* winwin32rootlesswindow.c: (winMWExtWMReorderWindows),
+	(winMWExtWMDecorateWindow), (winMWExtWMUpdateWindowDecoration),
+	(winIsInternalWMRunning), (winMWExtWMRestackWindows):
+	* winwin32rootlesswndproc.c: (winMWExtWMWindowProc):
+	* winwindow.h:
+	* winwndproc.c: (winWindowProc):
+	Add internalwm mode.
+
+2004-10-28  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h:
+	add fRetryCreateSurface
+	* winshaddnl.c (winBltExposedRegionsShadowDDNL):
+	try to recreate the primary surface if it was lost
+	* winshaddnl.c (winCreatePrimarySurfaceShadowDDNL):
+	mark screen to retry creating the primary surface if it failed
+
+2004-10-23  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig (winConfigFiles):
+	Simplify /etc/X11/font-dirs parsing
+
+2004-10-20  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* XWin.rc, winresource.h, winwndproc.c:
+	Add ShowCursor entry to tray menu 
+
+2004-10-20  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* Imakefile:
+	Add ETCX11DIR to DEFINES
+	* InitOutput.c (InitOutput):
+	* winconfig.c (winConfigFiles) :
+	Add entries from /etc/X11/font-dirs to default fontpath
+
+2004-10-16  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winprocarg.c (winInitializeDefaultScreens, ddxProcessArgument):
+	* win.h:
+	Make multiple monitors default for -multiwindow and -mwextwm.
+	Added a flag to indicate if the user has overridden the multimonitor
+	settings. (Øyvind Harboe, Alexander Gottwald)
+
+2004-10-07  Torrey Lyons  <torrey at freedesktop dot org>
+
+	* winscrinit.c:
+	Add compatibility with the generic rootless layer's new
+	DoReorderWindow function.
+
+2004-10-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* XWin.rc:
+	Set the dialogstyle to DS_CENTERMOUSE. Dialogs will now popup on the
+	monitor where the mouse is and not on the center of the whole desktop.
+
+2004-10-02  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmouse.c (winMouseProc):
+	Make sure buttons 1-3 are mouse buttons and wheel events are 4-5
+	Document code
+	Replace ErrorF with appropriate winMsg
+	use a symbolic name for the wheel event offset
+	
+2004-10-01  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* wincreatewnd.c (winCreateBoundingWindowWindowed):
+	Do not adjust workarea if native windowmanager is used
+
+2004-09-22  Kensuke Matsuzaki
+
+	* winclipboardthread.c (winClipboardErrorHandler):
+	* winclipboardwndproc.c (winClipboardWindowProc):
+	* winclipboardxevents.c (winClipboardFlushXEvents):
+	Fix clipboard bug with unicode applications.
+	
+2004-09-17  Torrey Lyons  <torrey at freedesktop dot org>
+
+	* winscrinit.c: (winFinishScreenInitFB):
+	Bugzilla #1032: Make rootless acceleration functions compatible with
+	Damage.
+
+2004-09-16  Alexander Gottwald <ago at freedesktop dot org>
+
+	* wincreatewnd.c (winCreateBoundingWindowWindowed):
+	Remove code which prevented the use from specifying the window
+	size in nodecoration mode. 	
+
+2004-08-26  Chris B  <news at sempermax dot com>
+
+	* win.h, winmessages.h:
+	Add defines for WM_XBUTTON
+	* winmouse.c (winMouseProc):
+	Query number of mouse buttons from windows. 
+	* winmultiwindowwndproc.c (winTopLevelWindowProc):
+	* winwin32rootlesswndproc.c (winMWExtWMWindowProc):
+	* winwndproc.c (winWindowProc):
+	Handle WM_XBUTTON messages.  
+
+2004-08-02  Kensuke Matsuzaki
+
+	* winclipboardthread.c winclipboardwndproc.c: 
+	* winclipboardxevents.c winwin32rootlesswndproc.c:
+	Fix the bug that we can't copy & paste multi-byte string to
+	Unicode-base Windows application.  Rename fUnicodeSupport to
+	fUseUnicode, because it don't mean wheather Windows support
+	Unicode or not.
+	
+2004-07-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h:
+	adjust prototype for winInitCmapPrivates to match Egberts change.	
+
+2004-07-30  Egbert Eich  <eich at freedesktop dot org>
+
+	* winallpriv.c: (winInitCmapPrivates):
+	test if colormap with index really exists in the list of
+	installed maps before using it.
+
+2004-07-09  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig.c: Add entry for irish layout (ie)
+	* InitOutput.c, winerror.c, winglobals.c: rename g_fUseMsg to 
+	g_fSilentFatalError
+	* InitOutput.c, winglobals.c, winprocarg.c: added commandline option 
+	-silent-dup-error to allow silent termination if another instance of
+	XWin was found running
+
+2004-06-27  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig.c: Add entry for us layout. This changes not much but 
+	removes a strange error message about the unknown us layout. 
+
+2004-06-24  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c: Check for textmode mounted /tmp and print a warning
+
+2004-06-15  Harold Hunt  <huntharo at msu dot edu>
+
+	* windialogs.c: Fix path to locally installed changelog for the About 
+	dialog box.
+
+2004-05-27  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winpriv.c: Create win32 window if not already created
+	* winmultiwindowwindow.c: Export winCreateWindowWindow
+
+2004-05-27  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h: Allow CYGDEBUG to defined in the Makefile
+	* winwindow.h: Allow CYGWINDOWING_DEBUG to defined in the Makefile
+
+2004-05-19  Alexander Gottwald  <ago at freedesktop dot org>
+	
+	* winmultiwindowicons.c (winInitGlobalIcons): Load the small default
+	icon too
+	* winprefs.h, winprefs.c (winOverrideDefaultIcon): Takes the iconsize
+	as parameter
+
+2004-05-19  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h, winmultiwindowicons.c (winXIconToHICON): Takes iconsize
+	as parameter 
+	* winglobals.c, winmultiwindowicons.c: Rename g_hiconX to g_hIconX.
+	Added new variable g_hSmallIconX for 16x16 icon.
+	* winwindow.h, winmultiwindowicons.c (winInitGlobalIcons): Inits the 
+	global g_hIconX handles.
+	* winwindow.h, winmultiwindowicons.c (winDestroyIcon): Free the icon
+	without messing with the global icon handle. 
+	* winmultiwindowicons.c (winSelectIcons): Generate a custom icon from
+	window settigns or set them to globals.
+	* winmultiwindowshape.c, winmultiwindowwindow.c, winwin32rootless.c,
+	  winwin32rootlesswindow.c, winwin32rootlesswndproc.c: Remove 
+	declaration of g_hiconX;
+	* winmultiwindowwindow.c (winCreateWindowsWindow),
+	  winwin32rootless.c (winMWExtWMCreateFrame): Use winSelectIcons 
+	to get the window icons. Set the small icon too.
+	* winmultiwindowwindow.c (winDestroyWindowsWindow),
+	  winmultiwindowicons.c (winUpdateIcon), 
+	  winprefs.c (ReloadEnumWindowsProc),
+	  winwin32rootlesswindow.c (winMWExtWMUpdateIcon),
+	  winwin32rootless.c (winMWExtWMDestroyFrame): Use winDestroyIcon
+	to free the icon without destroying the global icon.  
+	  
+2004-05-17  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* windialogs.c (winExitDlgProc, winAboutDlgProc),
+	  winmultiwindowwndproc.c (winTopLevelWindowProc),
+	  winwndproc.c (winWindowProc): Check if g_fSoftwareCursor is set 
+	before calling ShowCursor.  
+
+2004-05-09  Dan Wilks  <Dan_Wilks at intuit dot com>
+    
+	* winclipboard.h: Add extern prototypes for winDebug, winErrorFVerb
+	copied from winmsg.h.
+	* winclipboardinit.c (winFixClipboardChain): Post rather than send the
+	reinit message to the clipboard window.  Sending the message caused,
+	or possibly just exacerbated an existing, race condition that would
+	cause the X server to hang when coming back from a remote desktop
+	session.
+	* winclipboardwndproc.c (winProcessXEventsTimeout): switch to new
+	logging api's.
+	* winclipboardwindproc.c (winClipboardWindowProc): switch to new 
+	logging api's.  Add some additional debug logging.  Make best effort 
+	to prevent our window appearing twice in the clipboard chain.  Also 
+	detect loops when they occur and try to behave in a reasonable way.
+
+# vim:ts=8:noexpandtab:encoding=utf8        
diff --git a/hw/xwin/InitInput.c b/hw/xwin/InitInput.c
new file mode 100644
index 0000000..6a850cd
--- /dev/null
+++ b/hw/xwin/InitInput.c
@@ -0,0 +1,177 @@
+/*
+
+  Copyright 1993, 1998  The Open Group
+
+  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"
+#ifdef XWIN_CLIPBOARD
+# include "../../Xext/xf86miscproc.h"
+#endif
+#include "dixstruct.h"
+
+
+/*
+ * Local function prototypes
+ */
+
+#ifdef XWIN_CLIPBOARD
+DISPATCH_PROC(winProcEstablishConnection);
+DISPATCH_PROC(winProcQueryTree);
+DISPATCH_PROC(winProcSetSelectionOwner);
+#endif
+
+
+/*
+ * Local global declarations
+ */
+
+CARD32				g_c32LastInputEventTime = 0;
+
+
+/*
+ * References to external symbols
+ */
+
+#ifdef HAS_DEVWINDOWS
+extern int			g_fdMessageQueue;
+#endif
+extern Bool			g_fXdmcpEnabled;
+#ifdef XWIN_CLIPBOARD
+extern winDispatchProcPtr	winProcEstablishConnectionOrig;
+extern winDispatchProcPtr	winProcQueryTreeOrig;
+#endif
+
+
+/* Called from dix/devices.c */
+/*
+ * All of our keys generate up and down transition notifications,
+ * so all of our keys can be used as modifiers.
+ * 
+ * An example of a modifier is mapping the A key to the Control key.
+ * A has to be a legal modifier.  I think.
+ */
+
+Bool
+LegalModifier (unsigned int uiKey, DeviceIntPtr pDevice)
+{
+  return TRUE;
+}
+
+
+/* Called from dix/dispatch.c */
+/*
+ * Run through the Windows message queue(s) one more time.
+ * Tell mi to dequeue the events that we have sent it.
+ */
+void
+ProcessInputEvents (void)
+{
+#if 0
+  ErrorF ("ProcessInputEvents\n");
+#endif
+
+  mieqProcessInputEvents ();
+  miPointerUpdate ();
+
+#if 0
+  ErrorF ("ProcessInputEvents - returning\n");
+#endif
+}
+
+
+int
+TimeSinceLastInputEvent ()
+{
+  if (g_c32LastInputEventTime == 0)
+    g_c32LastInputEventTime = GetTickCount ();
+  return GetTickCount () - g_c32LastInputEventTime;
+}
+
+
+/* See Porting Layer Definition - p. 17 */
+void
+InitInput (int argc, char *argv[])
+{
+  DeviceIntPtr		pMouse, pKeyboard;
+
+#if CYGDEBUG
+  winDebug ("InitInput\n");
+#endif
+
+#ifdef XWIN_CLIPBOARD
+  /*
+   * Wrap some functions at every generation of the server.
+   */
+  if (InitialVector[2] != winProcEstablishConnection)
+    {
+      winProcEstablishConnectionOrig = InitialVector[2];
+      InitialVector[2] = winProcEstablishConnection;
+    }
+  if (g_fXdmcpEnabled
+      && ProcVector[X_QueryTree] != winProcQueryTree)
+    {
+      winProcQueryTreeOrig = ProcVector[X_QueryTree];
+      ProcVector[X_QueryTree] = winProcQueryTree;
+    }
+#endif
+
+  pMouse = AddInputDevice (winMouseProc, TRUE);
+  pKeyboard = AddInputDevice (winKeybdProc, TRUE);
+  
+  RegisterPointerDevice (pMouse);
+  RegisterKeyboardDevice (pKeyboard);
+
+  miRegisterPointerDevice (screenInfo.screens[0], pMouse);
+  mieqInit ((DevicePtr)pKeyboard, (DevicePtr)pMouse);
+
+  /* Initialize the mode key states */
+  winInitializeModeKeyStates ();
+
+#ifdef HAS_DEVWINDOWS
+  /* Only open the windows message queue device once */
+  if (g_fdMessageQueue == WIN_FD_INVALID)
+    {
+      /* Open a file descriptor for the Windows message queue */
+      g_fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, O_RDONLY);
+      
+      if (g_fdMessageQueue == -1)
+	{
+	  FatalError ("InitInput - Failed opening %s\n",
+		      WIN_MSG_QUEUE_FNAME);
+	}
+
+      /* Add the message queue as a device to wait for in WaitForSomething */
+      AddEnabledDevice (g_fdMessageQueue);
+    }
+#endif
+
+#if CYGDEBUG
+  winDebug ("InitInput - returning\n");
+#endif
+}
diff --git a/hw/xwin/InitOutput.c b/hw/xwin/InitOutput.c
new file mode 100644
index 0000000..d215981
--- /dev/null
+++ b/hw/xwin/InitOutput.c
@@ -0,0 +1,1144 @@
+/*
+
+Copyright 1993, 1998  The Open Group
+
+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(XKB) && 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;
+#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 = (strcmp(ent->mnt_type, "system") == 0);
+    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, "binmode") == NULL)
+      binary = 0;
+    else
+      binary = 1;
+  }
+    
+  if (endmntent(mnt) != 1)
+  {
+    ErrorF("endmntent failed");
+    return;
+  }
+  
+ if (!binary) 
+   winMsg(X_WARNING, "/tmp mounted int 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);
+        }
+    }
+#ifdef XKB
+    {
+        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 /* XKB */
+#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, 1);
+
+  /* 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 ("-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");
+
+  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 ("-refresh rate_in_Hz\n"
+	  "\tSpecify an optional refresh rate to use in fullscreen mode\n"
+	  "\twith a DirectDraw engine.\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 at 2 ; 2nd monitor offset 100,100 size 800x600\n"
+      "\t -screen 0 1024x768 at 3        ; 3rd monitor size 1024x768\n"
+      "\t -screen 0 @1 ; on 1st monitor using its full resolution (the default)\n");
+
+  ErrorF ("-lesspointer\n"
+	  "\tHide the windows mouse pointer when it is over an inactive\n"
+          "\t" PROJECT_NAME " window.  This prevents ghost cursors appearing where\n"
+	  "\tthe Windows cursor is drawn overtop of the X cursor\n");
+
+  ErrorF ("-nodecoration\n"
+          "\tDo not draw a window border, title bar, etc.  Windowed\n"
+	  "\tmode only.\n");
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  ErrorF ("-mwextwm\n"
+	  "\tRun the server in multi-window external window manager mode.\n");
+
+  ErrorF ("-internalwm\n"
+	  "\tRun the internal window manager.\n");
+#endif
+
+  ErrorF ("-rootless\n"
+	  "\tRun the server in rootless mode.\n");
+
+#ifdef XWIN_MULTIWINDOW
+  ErrorF ("-multiwindow\n"
+	  "\tRun the server in multi-window mode.\n");
+#endif
+
+  ErrorF ("-multiplemonitors\n"
+	  "\tEXPERIMENTAL: Use the entire virtual screen if multiple\n"
+	  "\tmonitors are present.\n");
+
+#ifdef XWIN_CLIPBOARD
+  ErrorF ("-clipboard\n"
+	  "\tRun the clipboard integration module.\n"
+	  "\tDo not use at the same time as 'xwinclip'.\n");
+
+  ErrorF ("-nounicodeclipboard\n"
+	  "\tDo not use Unicode clipboard even if NT-based platform.\n");
+#endif
+
+  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 ("-[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 ("-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.  Currently supported only by `-engine 1'.\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 ("-[no]unixkill\n"
+          "\tCtrl+Alt+Backspace exits the X Server.\n");
+
+  ErrorF ("-[no]winkill\n"
+          "\tAlt+F4 exits the X Server.\n");
+
+#ifdef XWIN_XF86CONFIG
+  ErrorF ("-config\n"
+          "\tSpecify a configuration file.\n");
+
+  ErrorF ("-keyboard\n"
+	  "\tSpecify a keyboard device from the configuration file.\n");
+#endif
+
+#ifdef XKB
+  ErrorF ("-xkbrules XKBRules\n"
+	  "\tEquivalent to XKBRules in XF86Config files.\n");
+
+  ErrorF ("-xkbmodel XKBModel\n"
+	  "\tEquivalent to XKBModel in XF86Config files.\n");
+
+  ErrorF ("-xkblayout XKBLayout\n"
+	  "\tEquivalent to XKBLayout in XF86Config files.\n"
+	  "\tFor example: -xkblayout de\n");
+
+  ErrorF ("-xkbvariant XKBVariant\n"
+	  "\tEquivalent to XKBVariant in XF86Config files.\n"
+	  "\tFor example: -xkbvariant nodeadkeys\n");
+
+  ErrorF ("-xkboptions XKBOptions\n"
+	  "\tEquivalent to XKBOptions in XF86Config files.\n");
+#endif
+
+  ErrorF ("-logfile filename\n"
+	  "\tWrite logmessages to <filename> instead of /tmp/Xwin.log.\n");
+
+  ErrorF ("-logverbose verbosity\n"
+	  "\tSet the verbosity of logmessages. [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]keyhook\n"
+	  "\tGrab special windows key combinations like Alt-Tab or the Menu "
+          "key.\n These keys are discarded by default.\n");
+
+  ErrorF ("-swcursor\n"
+	  "\tDisable the usage of the windows cursor and use the X11 software "
+	  "cursor instead\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);
+}
+
+/* ddxInitGlobals - called by |InitGlobals| from os/util.c */
+void ddxInitGlobals(void)
+{
+}
+
+/* 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, "XF86Config 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)
+
+#if defined(XCSECURITY)
+  /* Generate a cookie used by internal clients for authorization */
+  if (g_fXdmcpEnabled)
+    winGenerateAuthorization ();
+#endif
+
+  /* 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 ()
+{
+  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;
+}
+
+#ifdef DPMSExtension
+Bool DPMSSupported(void)
+{
+  return FALSE;
+}
+
+void DPMSSet(int level)
+{
+  return;
+}
+
+int DPMSGet(int *plevel)
+{
+  return 0;
+}
+#endif
diff --git a/hw/xwin/Makefile.am b/hw/xwin/Makefile.am
new file mode 100644
index 0000000..5ffba12
--- /dev/null
+++ b/hw/xwin/Makefile.am
@@ -0,0 +1,197 @@
+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
+endif
+
+if XWIN_NATIVEGDI
+SRCS_NATIVEGDI = \
+	winclip.c \
+	winfillsp.c \
+	winfont.c \
+	wingc.c \
+	wingetsp.c \
+	winnativegdi.c \
+	winpixmap.c \
+	winpolyline.c \
+	winpushpxl.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 \
+	$(top_srcdir)/mi/miinitext.c \
+	$(top_srcdir)/fb/fbcmap.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 \
+           -I$(top_srcdir)/miext/rootless/safeAlpha
+
+XWIN_LIBS = \
+	$(top_builddir)/fb/libfb.la \
+	$(XSERVER_LIBS)
+
+XWin_DEPENDENCIES = $(XWIN_LIBS)
+XWin_LDADD = $(XWIN_LIBS) $(XSERVER_SYS_LIBS) $(XWIN_SYS_LIBS)
+
+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)
+
+AM_YFLAGS = -d
+AM_LFLAGS = -i
+AM_CFLAGS = -DHAVE_XWIN_CONFIG_H $(DIX_CFLAGS) \
+            $(XWINMODULES_CFLAGS)
+
+dist_man1_MANS = XWin.man XWinrc.man
+
+EXTRA_DIST = \
+	_usr_X11R6_lib_X11_system.XWinrc \
+	X-boxed.ico \
+	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 && $(MAKE) XWin
diff --git a/hw/xwin/README b/hw/xwin/README
new file mode 100644
index 0000000..219fd13
--- /dev/null
+++ b/hw/xwin/README
@@ -0,0 +1,141 @@
+Cygwin/X Release Notes
+======================
+
+Release X11R6.7
+===============
+
+Cygwin/X has continued its rapid pace of development that it has sustained
+since Spring 2001 and this release shows it, we now have: a stable and fast
+multi-window mode, seamless clipboard integration, a configurable tray menu
+icon, popups on error messages pointing users to the log file and our mailing
+list, the beginnings of indirect 3D acceleration for OpenGL applications,
+improved non-US keyboard and clipboard support, and only a handful of bugs
+that continue to be reported.
+
+Between the XFree86 4.3.0 release and the X.Org X11R6.7 release the Cyg-
+win/XFree86 project broke away from The XFree86 Project, Inc. due to a lack
+of support from the XFree86 project.  As such, the Cygwin/XFree86 project was
+renamed to the Cygwin/X project and the upstream source code tree that Cyg-
+win/X pulls from and pushes to is now the tree managed by the X.Org Founda-
+tion.  The Cygwin/X project has seen a rush of development and interest in
+the project since the split; one metric showing this is that the number of
+CVS committers we have has gone from zero to six.
+
+The most outstanding features of this release are
+
+   o Major multi-window mode improvements. (Takuma Murakami, Earle F. 
+     Philhower III)
+
+   o Initial work of accelerated OpenGL using the windows OpenGL drivers. 
+     (Alexander Gottwald)
+
+   o Massive rework of clipboard integration with windows. (Harold L Hunt II,
+     Kensuke Matsuzaki)
+
+   o Improved Japanese clipboard and keyboard support. (Kensuke Matsuzaki,
+     Takuma Murakami, Alexander Gottwald)
+
+   o Customizable tray menu icon allowing shortcuts to start programs,
+     etc.(Earle F. Philhower III)
+
+   o New icons. (Jehan Bing, Michael Bax, Benjamin Rienfenstahl)
+
+   o Fix some multi-monitor problems.(Takuma Murakami)
+
+   o Fix repeated key strokes. (Ivan Pascal)
+
+   o Automatic keyboard layouts for the most frequently used keyboard lay-
+     outs. (Alexander Gottwald)
+
+   o Built in SHM support with detection of the SHM engine (cygserver).
+     (Ralf Habacker, Harold L Hunt II)
+
+   o Merged in work on the NativeGDI engine. (Alan Hourihane)
+
+OpenGL with Cygwin/X
+====================
+
+Cygwin/X has supported GLX only with software rendering provided by the Mesa
+library. Starting with X11R6.7 we add support for hardware accelerated OpenGL.
+
+This support is still under development and still has some bigger problems. 
+To provide both versions (the stable software rendering and the new hardware
+accelerated) we ship to binaries. XWin.exe contains the software rendering 
+and XWin_GL.exe uses the hardware acceleration provided by the windows drivers.
+
+The known problems with hardware accelerated OpenGL are:
+
+   o Only multiwindow mode is useful. In the other modes the OpenGL output 
+     does not align with the X11 windows.
+
+   o Using two programs which require different visuals will fail. For example
+     glxgears and glxinfo will not work without restarting XWin_GL.exe.
+
+   o OpenGL extensions and functions from OpenGL 1.2 and later should work 
+     but are not completely tested.
+
+   o The standard Windows OpenGL driver will produce no output. Use the one 
+     from your video adapter vendor.  
+
+If you notice problems with some programs please send a message with the 
+logfile /tmp/XWin.log and a short error description to <cygwin-xfree at cygwin.com>
+
+The hardware accelerated OpenGL was tested using: 
+
+   o glxgears
+   o glxinfo
+   o blender
+   o tuxkart
+   o GLUT demos (some did fail)
+   o tuxracer (currently not working)
+
+    
+Release X11R6.8
+===============
+
+Having reached a quite mature state in release X11R6.7 the development 
+has slowed down a little bit. Some of the former active developers have
+retired or cut their work for the Cygwin/X project due to conflicts with 
+job, study and family. 
+
+The X11R6.8 release now includes major improvements from the xserver project.
+This includes the XFixes, Damage, Composite and XEVIE extension which is a 
+major step towards allowing Cygwin/X to have real transparency. 
+
+But at the current state Composite is not working with Cygwin/X. Not all code
+in the Cygwin/X Server has been updated to support the Composite feature and
+using it will even crash the xserver. But as a second problem nearly all
+functions required for compositing are lacking acceleration in Cygwin/X so
+the feature would not be very useful if it would work. So it is disabled by
+default. 
+
+OpenGL with Cygwin/X
+====================
+
+The OpenGL support has lost some of it's limitations from the last release 
+and should be much more stable. But due to missing wide spread testing in 
+the community it is still available in a separate program. XWin still uses 
+the old software OpenGL which is known to be stable.
+
+The known problems with hardware accelerated OpenGL are:
+
+   o Only multiwindow mode is useful. In the other modes the OpenGL output 
+     does not align with the X11 windows.
+
+   o OpenGL extensions and functions from OpenGL 1.2 and later should work 
+     but are not completely tested.
+
+   o The standard Windows OpenGL driver will produce no output. Use the one 
+     from your video adapter vendor.  
+
+If you notice problems with some programs please send a message with the 
+logfile /tmp/XWin.log and a short error description to <cygwin-xfree at cygwin.com>
+
+The hardware accelerated OpenGL was tested using: 
+
+   o glxgears
+   o glxinfo
+   o blender
+   o tuxkart
+   o GLUT demos (some did fail)
+
diff --git a/hw/xwin/X-boxed.ico b/hw/xwin/X-boxed.ico
new file mode 100755
index 0000000..0727042
Binary files /dev/null and b/hw/xwin/X-boxed.ico differ
diff --git a/hw/xwin/X.ico b/hw/xwin/X.ico
new file mode 100644
index 0000000..d47168f
Binary files /dev/null and b/hw/xwin/X.ico differ
diff --git a/hw/xwin/XWin.man b/hw/xwin/XWin.man
new file mode 100644
index 0000000..4e70c19
--- /dev/null
+++ b/hw/xwin/XWin.man
@@ -0,0 +1,287 @@
+.TH XWIN 1 __vendorversion__
+.SH NAME
+XWin \- X Server for the Cygwin environment on Microsoft Windows
+
+
+.SH SYNOPSIS
+.B XWin
+[ options ] ...
+
+
+.SH DESCRIPTION
+.I XWin is an X Server for the X Window System on the Cygwin environment
+running on Microsoft Windows.
+
+
+.SH MODES
+\fIXWin\fP can operate in five different and incompatible modes:
+.br
+* \fISingle Window\fP: This is the default option.  The X server
+appears as a single Windows window and all X windows are contained
+within this window.  This mode requires an external window manager.
+.br
+* \fINo Decoration\fP: This mode is like single window mode except
+that the X server window does not have a title bar or border, thus
+maximizing the amount of space available for X windows within the X
+server window.  This mode requires an external window manager.
+.br
+* \fIFull Screen\fP: This mode is like single window mode except that
+the X server window takes the full screen, covering completely the
+Windows desktop.  This mode requires an external window manager.
+.br
+* \fIRootless\fP: The X server works on a window covering the whole
+screen but the root window (traditionally covered with an X hatch
+pattern) is hidden from view.  This mode requires an external window
+manager.
+.br
+* \fIMulti-Window\fP: In this mode \fIXWin\fP uses its own integrated
+window manager in order to handle the top-level X windows, in such a
+way that they appear as normal Windows windows.
+.PP
+NOTE: \fIMulti-Window\fP mode will crash if an external window manager
+such as \fItwm\fP or \fIfvwm\fP is launched since \fIMulti-Window\fP
+uses its own internal window manager; all other modes require an
+external window manager in order to move, resize, and perform other
+operations on the individual X windows.
+
+
+.SH LOG
+As it runs \fIXWin\fP writes messages indicating the most relevant events
+to  the console
+from which it was called and to a log file that by default is located at
+\fI/tmp/XWin.log\fP.  This file is mainly for debugging purposes.
+
+
+.SH PREFERENCES FILE
+On startup \fIXWin\fP looks for the file \fI$HOME/.XWinrc\fP or, if
+the previous file does not exist,
+\fI/usr/X11R6/lib/X11/system.XWinrc\fP.  \fI.XWinrc\fP allows setting
+preferences for the following:
+.br
+1- To include items into the menu associated with the \fIXWin\fP icon
+which is in the \fIWindows\fP system tray.  This functions in all
+modes that have a tray icon.
+.br
+2- To include items in the menu which is associated with the Windows
+window that \fIXWin -multiwindow\fP produces for each top-level X
+window.  That can be done both for the generic case and for particular
+programs.
+.br
+3- To change the icon that is associated to the Windows window that
+\fIXWin -multiwindow\fP produces for each top-level X-window.  Again,
+that can be done both for the generic case and for particular
+programs.
+.PP
+The format of the \fI.XWinrc\fP file is given in the man page XWinrc(5).
+
+
+.SH OPTIONS
+In addition to the normal server options described in the \fIXserver(1)\fP
+manual page, \fIXWin\fP accepts the following command line switches,
+\fIall\fP of which are optional:
+.TP 8
+.B \-clipboard
+Enables the integration
+between the Cygwin/X clipboard and Windows clipboard.  Do not use in
+conjunction with the \fIxwinclip\fP program.
+.TP 8
+.B "\-clipupdates \fInum_boxes\fP"
+Specify an optional threshold, above which the boxes in a shadow
+update operation will be collected into a GDI clipping region.  The
+clipping region is then used to do a single bit block transfer that is
+constrained to the updated area by the clipping region.  There is some
+overhead involved in creating, installing, destroying, and removing
+the clipping region, thus there may not be much benefit for a small
+number of boxes (less than 10).  It is even possible that this
+functionality does not provide a benefit at any number of boxes; we
+can only determine the usefulness of this feature through testing.
+This parameter works in conjunction with engines 1, 2, and 4 (Shadow
+GDI, Shadow DirectDraw, and Shadow DirectDraw Non-Locking,
+respectively).
+.TP 8
+.B "\-emulate3buttons \fItimeout\fP"
+Emulate a three button mouse; pressing both buttons within
+.I timeout
+milliseconds causes an emulated middle button press.  The default 
+.I timeout
+is 50 milliseconds.  Note that most mice with scroll wheel have middle
+button functionality, usually you will need this option only if you have
+a two button mouse without scroll wheel.
+.TP 8
+.B \-emulatepseudo
+Create a depth 8 PseudoColor visual when running in depths 15, 16, 24,
+or 32, collectively known as TrueColor depths.
+ At this date (April 2004) this option is not still operative.
+.TP 8
+.B "\-engine \fIengine_type_id\fP"
+This option, which is intended for Cygwin/X developers,
+overrides the server's automatically supported engine type.  This
+parameter will be ignored if the specified engine type is not
+supported on the current system.  The supported engine type ids are 1
+- Shadow GDI, 2 - Shadow DirectDraw, and 4 - Shadow DirectDraw4.
+Additionally, there is a barely functional experimental engine type id
+16 - Native GDI.
+.TP 8
+.B "\-fullscreen [-depth \fIdepth\fP] [-refresh \fIrate_in_Hz\fP]"
+Run the server in fullscreen mode, as opposed to the default windowed
+mode.
+.TP 8
+.B "\-depth \fIdepth\fP"
+Specify the color depth, in bits per pixel, to use when running in
+fullscreen with a DirectDraw engine.  This parameter is ignored if
+\fB\-fullscreen\fP is not specified.
+.TP 8
+.B "\-refresh \fIrate_in_Hz\fP"
+Specify an optional refresh rate to use when running in
+fullscreen with a DirectDraw engine.  This parameter is ignored if
+\fB\-fullscreen\fP is not specified.
+.TP 8
+.B \-help
+Write a help text to the console and to the log file.
+.TP 8
+.B \-ignoreinput
+Ignore keyboard and mouse input.  This is usually only used for testing
+and debugging purposes.
+.TP 8
+.B \-[no]keyhook
+Enable [disable] a low-level keyboard hook for catching
+special key combinations like Alt+Tab and passing them to the X
+Server instead of letting \fIWindows\fP handle them.
+.TP 8
+.B \-lesspointer
+Hide the Windows mouse cursor when the mouse is over any Cygwin/X
+window (regardless of whether that window is active or inactive).  This
+prevents the Windows mouse cursor from being placed overtop of the X
+cursor.
+.TP 8
+.B "\-logfile \fIFile_Name\fP"
+Change the log file from the default located at \fI/tmp/XWin.log\fP to
+the one indicated by \fIFile_Name\fP.
+.TP 8
+.B "\-logverbose \fIlevel\fP"
+Control the degree of verbosity of the log messages with the integer
+parameter \fIlevel\fP.  For \fIlevel\fP=0 only fatal errors are
+reported, for \fIlevel\fP=1 (default) simple information about
+configuration is also given, for \fIlevel\fP=2 a detailed log
+information (including trace and debug output) is produced.  Bigger
+values will yield a still more detailed debug output.  At this date
+(April 2004) the option is still not fully operative; the default
+value is 2 and the output is insensitive to the level value.
+.TP 8
+.B \-multimonitors
+Create a root window that covers all monitors on a system with
+multiple monitors.
+.TP 8
+.B \-multiwindow
+Start the integrated \fIWindowsi\fP-based window manager, which launches each
+top-level X window in its own \fIWindows\fP window.  Not to be used together
+with \fB\-rootless\fP nor \fB\-fullscreen\fP.
+.TP 8
+.B \-nodecoration
+Do not give the Cygwin/X window a Windows window border, title bar,
+etc.  This parameter only applies to windowed mode screens, i.e., this
+parameter is ignored when the \fB\-fullscreen\fP parameter is specified.
+.TP 8
+.B \-nounicodeclipboard
+Do not use Unicode clipboard even if NT-based platform.
+.TP 8
+.B \-rootless
+Run the server in rootless mode.  Not to be used with \fB\-multiwindow\fP
+nor with \fB\-fullscreen\fP.
+.TP 8
+.B "\-screen \fIscreen_number\fP \fIwidth\fP \fIheight\fP"
+This parameter may be used to specify the
+.I screen_number,
+.I height,
+and
+.I width
+of one or several Cygwin/X screens; each Cygwin/X screen will be
+opened in its own window.  When using multiple screens, be sure not to
+duplicate any screen numbers.
+.I XWin
+default behavior is to create a single screen that is roughly
+the size of the current Windows display area.
+Screen specific parameters, such as \fB\-fullscreen\fP, can be applied as a
+default to all screens by placing those screen specific parameters
+before any \fB\-screen\fP parameter.  Screen specific parameters placed after
+the first \fB\-screen\fP parameter will apply only to the immediately
+preceeding \fB\-screen\fP parameter.
+.TP 8
+.B \-scrollbars
+In windowed mode, allow screens bigger than the Windows desktop.
+Moreover, if the window has decorations, one can now resize it.
+.TP 8
+.B \-[no]trayicon
+Do not create a tray icon.  Default is to create one
+icon per screen.  You can globally disable tray icons with
+\fB\-notrayicon\fP, then enable it for specific screens with
+\fB\-trayicon\fP for those screens.
+.TP 8
+.B \-[no]unixkill
+Enable or disable the \fICtrl-Alt-Backspace\fP key combination as a
+signal to exit the X Server.  The \fICtrl-Alt-Backspace\fP key combination
+is disabled by default.
+.TP 8
+.B \-[no]winkill
+Enable or disable the \fIAlt-F4\fP key combination as a signal to exit the
+X Server.
+The \fIAlt-F4\fP key combination is enabled by default.
+.TP 8
+.B \-swcursor
+Disable the usage of the windows cursor and use the X11 software cursor instead.
+.B \-silent-dup-error
+If another instance of XWin is found running, exit silently and don't display 
+the error messge.
+.TP 8
+.B "\-xkblayout \fIlayout\fP"
+.TP 8
+.B "\-xkbmodel \fImodel\fP"
+.TP 8
+.B "\-xkboptions \fIoption\fP"
+.TP 8
+.B "\-xkbrules \fIrule\fP"
+.TP 8
+.B "\-xkbvariant \fIvariant\fp"
+These options implement the xkeyboard extension for loading
+a particular keyboard map as the X server starts.  The behavior is similar
+to the \fIsetxkbmap\fP program.  The layout data is located at
+\fI/usr/X11R6/lib/X11/xkb/\fP.  Additional information is found in the
+README files therein and in the man page of \fIsetxkbmap\fP.  For example
+in order to load a German layout for a pc105 keyboard one uses
+the options:
+.br
+.I " \-xkblayout de \-xkbmodel pc105"
+.PP
+Alternatively one may use the \fIsetxkbmap\fP program after XWin is
+running or even the \fIxmodmap\fP program for loading the old-style
+keyboard maps.
+
+
+.SH "SEE ALSO"
+X(__miscmansuffix__), Xserver(1), xdm(1), xinit(1), XWinrc(1), setxkbmap(1)
+
+
+.SH BUGS
+.I XWin
+and this man page still have many limitations.  Some of the more obvious
+ones are:
+.br
+- The display mode can not be changed once the X server has started.
+.br
+- The XWin software is developing rapidly; it is therefore likely that
+this man page is not up to date.  It is always prudent to 
+look also at the output of \fIXWin -help\fP and to the Cygwin/X User Guide
+at /usr/share/doc/cygwin-x-doc-x.x.x/ug/cygwin-x-ug.xxx in order to
+check the options that are operative.
+
+
+.SH AUTHORS
+This list is by no means complete, but direct contributors to the
+Cygwin/X project include (in alphabetical order by last name): Stuart
+Adamson, Michael Bax, Jehan Bing, Lev Bishop, Dr. Peter Busch, Biju G
+C, Robert Collins, Nick Crabtree, Early Ehlinger, Christopher Faylor,
+John Fortin, Brian Genisio, Fabrizio Gennari, Alexander Gottwald, Ralf
+Habacker, Colin Harrison, Matthieu Herrb, Alan Hourihane, Pierre A
+Humblet, Harold L Hunt II, Dakshinamurthy Karra, Kensuke Matsuzaki,
+Takuma Murakami, Earle F. Philhower III, Benjamin Riefenstahl, Suhaib
+Siddiqi, Jack Tanner, and Nicholas Wourms.
diff --git a/hw/xwin/XWin.rc b/hw/xwin/XWin.rc
new file mode 100644
index 0000000..749c0f5
--- /dev/null
+++ b/hw/xwin/XWin.rc
@@ -0,0 +1,109 @@
+/*
+ *Copyright (C) 2002-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
+ */
+
+#include "windows.h"
+#include "winresource.h"
+
+/*
+ * Dialogs
+ */
+
+/* About */
+ABOUT_BOX DIALOG DISCARDABLE  32, 32, 240, 105
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP  | DS_CENTERMOUSE
+CAPTION "About " PROJECT_NAME
+FONT 8, "MS Sans Serif"
+BEGIN
+  CONTROL               PROJECT_NAME " Website", ID_ABOUT_WEBSITE, "Button",
+                        BS_OWNERDRAW | WS_TABSTOP, 30, 45, 75, 15
+  CONTROL               "Change Log", ID_ABOUT_CHANGELOG, "Button",
+                        BS_OWNERDRAW | WS_TABSTOP, 135, 45, 75, 15
+  CONTROL               "User's Guide", ID_ABOUT_UG, "Button",
+                        BS_OWNERDRAW | WS_TABSTOP, 30, 65, 75, 15
+  CONTROL               "FAQ", ID_ABOUT_FAQ, "Button",
+                        BS_OWNERDRAW | WS_TABSTOP, 135, 65, 75, 15
+
+  DEFPUSHBUTTON		"Dismiss", IDOK, 95, 85, 50, 15
+
+  CTEXT			"Welcome to the preliminary About box for the " PROJECT_NAME " X Server.  This dialog was created on 2004/03/25 and will eventually be filled with more useful information.  For now, use the links below to learn more about the " PROJECT_NAME " project.", IDC_STATIC, 5, 5, 230, 35
+END
+
+
+/* Depth change */
+
+DEPTH_CHANGE_BOX DIALOG DISCARDABLE	32, 32, 180, 100
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | DS_CENTERMOUSE
+FONT 8, "MS Sans Serif"
+CAPTION PROJECT_NAME
+BEGIN
+  DEFPUSHBUTTON		"Dismiss", IDOK, 66, 80, 50, 14
+  CTEXT			PROJECT_NAME, IDC_STATIC, 40, 12, 100, 8
+  CTEXT			"Disruptive screen configuration change.", IDC_STATIC, 7, 40, 166, 8
+  CTEXT			"Restore previous resolution to use " PROJECT_NAME ".", IDC_STATIC, 7, 52, 166, 8
+END
+
+
+/* Exit */
+
+EXIT_DIALOG DIALOG DISCARDABLE	32, 32, 180, 78
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP | DS_CENTERMOUSE
+FONT 8, "MS Sans Serif"
+CAPTION PROJECT_NAME " - Exit?"
+BEGIN
+  PUSHBUTTON "E&xit", IDOK, 55, 56, 30, 14
+  DEFPUSHBUTTON "&Cancel", IDCANCEL, 95, 56, 30, 14
+  CTEXT "Exiting will close all screens running on this display.", IDC_STATIC, 7, 12, 166, 8
+  CTEXT "No information about connected clients available.", IDC_CLIENTS_CONNECTED, 7, 24, 166, 8
+  CTEXT "Proceed with shutdown of this display/server?", IDC_STATIC, 7, 36, 166, 8
+END
+
+
+/*
+ * Menus
+ */
+
+IDM_TRAYICON_MENU MENU DISCARDABLE
+BEGIN
+	POPUP "TRAYICON_MENU"
+	BEGIN
+		MENUITEM "&Hide Root Window", ID_APP_HIDE_ROOT
+		MENUITEM "&About...", ID_APP_ABOUT
+		MENUITEM SEPARATOR
+		MENUITEM "E&xit", ID_APP_EXIT
+	END
+END
+
+
+/*
+ * Icons
+ */
+
+IDI_XWIN		ICON	DISCARDABLE	"X.ico"
+IDI_XWIN_BOXED		ICON	DISCARDABLE	"X-boxed.ico"
diff --git a/hw/xwin/XWinrc.man b/hw/xwin/XWinrc.man
new file mode 100755
index 0000000..eba3fb6
--- /dev/null
+++ b/hw/xwin/XWinrc.man
@@ -0,0 +1,180 @@
+.TH XWIN 5 __vendorversion__
+
+
+.SH NAME
+XWinrc\- XWin Server Resource Configuration File.
+
+
+.SH DESCRIPTION
+The X Server for the X Window System on the Cygwin/X environment
+running on Microsoft Windows, \fIXWin\fP can be optionally configured
+with the \fIXWinrc\fP file.  A system-wide configuration file should
+be placed in \fI/usr/X11R6/lib/X11/system.XWinrc\fP, a per-user file
+should be put at \fI$HOME/.XWinrc\fP.  The \fIsystem.XWinrc\fP file is
+read only if no \fI$HOME/.XWinrc\fP exist.
+.PP
+With the \fI.XWinrc\fP configuration file it is possible to do the
+following:
+.PP
+1- To include items into the menu associated with the \fIXWin\fP icon
+which is in the \fIWindows\fP system tray.  This feature functions in
+all XWin modes that have such tray icon.
+.PP
+2- To include items into the menu which is associated with the
+\fIWindows\fP window that \fIXWin -multiwindow\fP produces for each
+top-level X-window.  That can be done both for the generic case and
+for particular programs.
+.PP
+3- To change the icon that is associated to the \fIWindows\fP window
+that \fIXWin -multiwindow\fP produces for each top-level X-window.
+Again, that can be done both for the generic case and for particular
+programs.  The new icons associated should be \fIWindows\fP format
+icons \fI.ico\fP.
+
+
+.SH FILE FORMAT
+.B Keywords
+are case insensitive, but in this document they will be written
+completely capitalized.
+.PP
+.B Comments
+are legal pretty much anywhere you can have an end-of-line; they
+begin with "#" or "//" and go to the end-of-line.
+.PP
+Quote marks in strings are optional unless the string has included spaces.
+.PP
+There are three kinds of instructions: miscellaneous, menu, and icon.
+
+
+.SH Miscellaneous instruction
+.TP 8
+.B DEBUG \fIString\fP
+The \fIString\fP is printed to the XWin.log file.
+
+.TP 8
+.B TRAYICON \fIicon-specifier\fB
+The \fBTRAYICON\fP keyword changes the icon \fIXWin\fP displays in the
+system tray area.
+
+.TP 8
+.B SILENTEXIT
+The \fBSILENTEXIT\fP keyword, which takes no parameters, disables the
+exit confirmation dialog.
+
+
+.SH Menu instructions
+.TP 8
+.B MENU \fIMenu_Name\fP {
+.br
+.B       \fIMenu_Item_Line\fP
+.br
+.B       \fIMenu_Item_Line\fP
+.br
+.B        \fI...\fP
+.br
+.B }
+.br
+This instruction defines a menu and asigns a \fIMenu_Name\fP to it.
+\fIMenu_Item_Line\fP are lines  of any of the following types:
+.TP 8
+.B \t SEPARATOR
+.TP 8
+.B  \t \fIItem_Label\fP  EXEC \fICommand\fP
+.TP 8
+.B \t \fIItem_Label\fP  MENU \fIpreviously-defined-menu-name\fP
+.TP 8
+.B \t \fIItem_Label\fP  ALWAYSONTOP
+.TP 8
+.B \t \fIItem_Label\fP  RELOAD
+.br
+The \fIItem_Label\fP is the string that is written in the menu item.
+.br
+\fICommand\fP is a string with the command that will be executed by /bin/sh.
+Here paths should be \fICYGWIN\fP style (e.g. /usr/local/bin/myprogram).
+A string "%display%" appearing in the \fICommand\fP will be replaced
+with the proper display variable (i.e. 127.0.0.1:<display>.0).
+.br
+\fBALWAYSONTOP\fP sets the window to which the menu is associated to
+display above all others.
+.br
+\fBRELOAD\fP causes the XWinrc file to be reloaded and icons and menus
+regenerated.
+.TP 8
+.B ROOTMENU \fIpreviously-defined-menu-name\fP
+Includes the items in the indicated menu into the menu associated with
+\fIXWin\fP that appears in the system tray.
+.TP 8
+.B DEFAULTSYSMENU \fIpreviously-defined-menu-name\fP ATSTART|ATEND
+Includes the items in the indicated menu into the menu associated with
+generic top-level X-Windows in the \fIXWin\fP \fImultiwindow\fP mode.  The
+keywords \fBATSTART\fP and \fBATEND\fP indicate if such items should be
+included at the start or at the end of the menu.
+.TP 8
+.B SYSMENU {
+  \fIclass-or-name-of-window\fP \fIdefined-menu-name\fP \fBATSTART|ATEND\fP
+.br
+  \fI...\fP
+.br
+  \fB}\fP
+.br
+Associates a specific menu to a specific WM_CLASS or WM_NAME.
+
+
+.SH Icon Instructions
+When specifying an \fIicon-file\fP in the following commands several different formats are allowed:
+.br
+\fB"NAME.ICO"\fP\fI of an .ico format file\fP
+.br
+\t \t ("cygwin.ico", "apple.ico")
+.br
+\fB"NAME.DLL,nn"\fP\fI of a .DLL and icon index\fP
+.br
+\t \t ("c:\\windows\\system32\\shell32.dll,4" is the default folder icon)
+.br
+\fB",nn"\fP\fI index into XWin.EXE internal ICON resources\fP
+.br
+\t \t (",101" is the 1st icon inside \fIXWin.EXE\fP)
+.TP 8
+.B ICONDIRECTORY \fIWindows-path-to-icon-directory\fP
+Defines the default directory to search for \ficon-file\fP files.
+It should be a \fIWindows\fP style path (e.g. C:\\cygwin\\usr\\local\\icons).
+.TP 8
+.B DEFAULTICON \fIicon-file\fP
+Defines a replacement for the standard X icon for applications without
+specified icons.
+.TP 8
+.B ICONS {
+.br
+ \fIclass-or-name-of-window\fP \fIicon-file\fP
+.br
+  \fI...\fP
+.br
+  \fB}\fP
+.br
+Defines icon replacements windows matching the specified window class or names.
+If multiple name or class matches occur for a window, only the first one
+will be used.
+
+
+.SH EXAMPLE
+.TP 8
+This example adds an Xterm menu item to the system tray icon
+\fBMENU systray {
+.br
+\t xterm  EXEC "xterm -display %display% -sb -sl 999"
+.br
+\t SEPARATOR
+.br
+}
+.br
+ROOTMENU systray
+\fP
+
+
+.SH "SEE ALSO"
+ XWin(1)
+
+
+.SH AUTHOR
+The XWinrc feature of XWin was written primarily by Earle F. Philhower
+III.
diff --git a/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc b/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc
new file mode 100644
index 0000000..d9c2d42
--- /dev/null
+++ b/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc
@@ -0,0 +1,125 @@
+# XWin Server Resource File - EXAMPLE
+# Earle F. Philhower, III
+
+# Place in ~/.XWinrc or in /usr/X11R6/lib/X11/system.XWinrc
+
+# Keywords are case insensitive, comments legal pretty much anywhere
+# you can have an end-of-line
+
+# Comments begin with "#" or "//" and go to the end-of-line
+
+# Paths to commands are **cygwin** based (i.e. /usr/local/bin/xcalc)
+
+# Paths to icons are **WINDOWS** based (i.e. c:\windows\icons)
+
+# Menus are defined as...
+# MENU <name> {
+#	<Menu Text>	EXEC	<command>
+#                               ^^ This command will have any "%display%"
+#                                  string replaced with the proper display
+#                                  variable (i.e. 127.0.0.1:<display>.0)
+#  or	<Menu Text>	MENU	<name-of-some-prior-defined-menu>
+#  or	<Menu Text>	ALWAYSONTOP
+#                         ^^ Sets the window to display above all others
+#  or   <Menu Text>	RELOAD
+#                         ^^ Causes ~/.XWinrc or the system.XWinrc file
+#                            to be reloaded and icons and menus regenerated
+#  or	SEPARATOR
+#       ...
+# }
+
+# Set the taskmar menu with
+# ROOTMENU <name-of-some-prior-defined-menu>
+
+# If you want a menu to be applied to all popup window's system menu
+# DEFAULTSYSMENU <name-of-some-prior-defined-menu> <atstart|atend>
+
+# To choose a specific menu for a specific WM_CLASS or WM_NAME use ...
+# SYSMENU {
+#	<class-or-name-of-window> <name-of-prior-defined-menu> <atstart|atend>
+#	...
+# }
+
+# When specifying an ICONFILE in the following commands several different
+# formats are allowed:
+# 1. Name of a regular Windows .ico format file
+#    (ex:  "cygwin.ico", "apple.ico")
+# 2. Name and index into a Windows .DLL
+#    (ex: "c:\windows\system32\shell32.dll,4" gives the default folder icon
+#         "c:\windows\system32\shell32.dll,5" gives the floppy drive icon)
+# 3. Index into XWin.EXE internal ICON resource
+#    (ex: ",101" is the 1st icon inside XWin.exe)
+
+# To define where ICO files live (** Windows path**)
+# ICONDIRECTORY	<windows-path i.e. c:\cygwin\usr\icons>
+# NOTE: If you specify a fully qualified path to an ICON below
+#             (i.e. "c:\xxx" or "d:\xxxx")
+#       this ICONDIRECTORY will not be prepended
+
+# To change the taskbar icon use...
+# TRAYICON       <name-of-windows-ico-file-in-icondirectory>
+
+# To define a replacement for the standard X icon for apps w/o specified icons
+# DEFAULTICON	<name-of-windows-ico-file-in-icondirectory>
+
+# To define substitute icons on a per-window basis use...
+# ICONS {
+#	<class-or-name-of-window> <icon-file-name.ico>
+#	...
+# }
+# In the case where multiple matches occur, the first listed in the ICONS
+# section will be chosen.
+
+# To disable exit confirmation dialog add the line containing SilentExit
+
+# DEBUG <string> prints out the string to the XWin.log file
+
+// Below are just some silly menus to demonstrate writing your
+// own configuration file.
+
+// Make some menus...
+menu apps {
+	xterm	exec	"xterm"
+	"Emacs"		exec	"emacs"
+	notepad	exec	notepad
+	xload	exec	"xload -display %display%"  # Comment
+}
+
+menu root {
+// Comments fit here, too...
+	"Reload .XWinrc"	RELOAD
+	"Applications"	menu	apps
+	SEParATOR
+}
+
+menu aot {
+	Separator
+	"Always on Top"	alwaysontop
+}
+
+menu xtermspecial {
+	"Emacs"		exec	"emacs"
+	"Always on Top"	alwaysontop
+	SepArAtor
+}
+
+RootMenu root
+
+DefaultSysMenu aot atend
+
+SysMenu {
+	"xterm"	xtermspecial atstart
+}
+
+# IconDirectory	"c:\winnt\"
+
+# DefaultIcon	"reinstall.ico"
+
+# Icons {
+# 	"xterm"	"uninstall.ico"
+# }
+
+# SilentExit
+
+DEBUG "Done parsing the configuration file..."
+
diff --git a/hw/xwin/ddraw.h b/hw/xwin/ddraw.h
new file mode 100644
index 0000000..2eb7c26
--- /dev/null
+++ b/hw/xwin/ddraw.h
@@ -0,0 +1,2106 @@
+#ifndef __XWIN_DDRAW_H
+#define __XWIN_DDRAW_H
+
+#include <winnt.h>
+#include <wingdi.h>
+#include <objbase.h>
+
+#if defined(NONAMELESSUNION) && !defined(DUMMYUNIONNAME1)
+#define DUMMYUNIONNAME1 u1
+#endif
+
+#define ICOM_CALL_( xfn, p, args) (p)->lpVtbl->xfn args
+
+# ifdef UNICODE
+#  define WINELIB_NAME_AW(func) func##W
+# else
+#  define WINELIB_NAME_AW(func) func##A
+# endif  /* UNICODE */
+#define DECL_WINELIB_TYPE_AW(type)  typedef WINELIB_NAME_AW(type) type;
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* defined(__cplusplus) */
+
+#ifndef	DIRECTDRAW_VERSION
+#define	DIRECTDRAW_VERSION	0x0700
+#endif /* DIRECTDRAW_VERSION */
+
+/*****************************************************************************
+ * Predeclare the interfaces
+ */
+DEFINE_GUID( CLSID_DirectDraw,		0xD7B70EE0,0x4340,0x11CF,0xB0,0x63,0x00,0x20,0xAF,0xC2,0xCD,0x35 );
+DEFINE_GUID( CLSID_DirectDraw7,         0x3C305196,0x50DB,0x11D3,0x9C,0xFE,0x00,0xC0,0x4F,0xD9,0x30,0xC5 );
+DEFINE_GUID( CLSID_DirectDrawClipper,	0x593817A0,0x7DB3,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xb9,0x33,0x56 );
+DEFINE_GUID( IID_IDirectDraw,		0x6C14DB80,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
+DEFINE_GUID( IID_IDirectDraw2,		0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
+DEFINE_GUID( IID_IDirectDraw4,          0x9c59509a,0x39bd,0x11d1,0x8c,0x4a,0x00,0xc0,0x4f,0xd9,0x30,0xc5 );
+DEFINE_GUID( IID_IDirectDraw7,          0x15e65ec0,0x3b9c,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b );
+DEFINE_GUID( IID_IDirectDrawSurface,	0x6C14DB81,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
+DEFINE_GUID( IID_IDirectDrawSurface2,	0x57805885,0x6eec,0x11cf,0x94,0x41,0xa8,0x23,0x03,0xc1,0x0e,0x27 );
+DEFINE_GUID( IID_IDirectDrawSurface3,	0xDA044E00,0x69B2,0x11D0,0xA1,0xD5,0x00,0xAA,0x00,0xB8,0xDF,0xBB );
+DEFINE_GUID( IID_IDirectDrawSurface4,   0x0B2B8630,0xAD35,0x11D0,0x8E,0xA6,0x00,0x60,0x97,0x97,0xEA,0x5B );
+DEFINE_GUID( IID_IDirectDrawSurface7,   0x06675a80,0x3b9b,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b );
+DEFINE_GUID( IID_IDirectDrawPalette,	0x6C14DB84,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
+DEFINE_GUID( IID_IDirectDrawClipper,	0x6C14DB85,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
+DEFINE_GUID( IID_IDirectDrawColorControl,0x4B9F0EE0,0x0D7E,0x11D0,0x9B,0x06,0x00,0xA0,0xC9,0x03,0xA3,0xB8 );
+DEFINE_GUID( IID_IDirectDrawGammaControl,0x69C11C3E,0xB46B,0x11D1,0xAD,0x7A,0x00,0xC0,0x4F,0xC2,0x9B,0x4E );
+
+typedef struct IDirectDraw *LPDIRECTDRAW;
+typedef struct IDirectDraw2 *LPDIRECTDRAW2;
+typedef struct IDirectDraw4 *LPDIRECTDRAW4;
+typedef struct IDirectDraw7 *LPDIRECTDRAW7;
+typedef struct IDirectDrawClipper *LPDIRECTDRAWCLIPPER;
+typedef struct IDirectDrawPalette *LPDIRECTDRAWPALETTE;
+typedef struct IDirectDrawSurface *LPDIRECTDRAWSURFACE;
+typedef struct IDirectDrawSurface2 *LPDIRECTDRAWSURFACE2;
+typedef struct IDirectDrawSurface3 *LPDIRECTDRAWSURFACE3;
+typedef struct IDirectDrawSurface4 *LPDIRECTDRAWSURFACE4;
+typedef struct IDirectDrawSurface7 *LPDIRECTDRAWSURFACE7;
+typedef struct IDirectDrawColorControl *LPDIRECTDRAWCOLORCONTROL;
+typedef struct IDirectDrawGammaControl *LPDIRECTDRAWGAMMACONTROL;
+
+
+#define DDENUMRET_CANCEL	0
+#define DDENUMRET_OK		1
+
+#define DD_OK			0
+
+
+#define _FACDD		0x876
+#define MAKE_DDHRESULT( code )  MAKE_HRESULT( 1, _FACDD, code )
+
+#define DDERR_ALREADYINITIALIZED		MAKE_DDHRESULT( 5 )
+#define DDERR_CANNOTATTACHSURFACE		MAKE_DDHRESULT( 10 )
+#define DDERR_CANNOTDETACHSURFACE		MAKE_DDHRESULT( 20 )
+#define DDERR_CURRENTLYNOTAVAIL			MAKE_DDHRESULT( 40 )
+#define DDERR_EXCEPTION				MAKE_DDHRESULT( 55 )
+#define DDERR_GENERIC				E_FAIL
+#define DDERR_HEIGHTALIGN			MAKE_DDHRESULT( 90 )
+#define DDERR_INCOMPATIBLEPRIMARY		MAKE_DDHRESULT( 95 )
+#define DDERR_INVALIDCAPS			MAKE_DDHRESULT( 100 )
+#define DDERR_INVALIDCLIPLIST			MAKE_DDHRESULT( 110 )
+#define DDERR_INVALIDMODE			MAKE_DDHRESULT( 120 )
+#define DDERR_INVALIDOBJECT			MAKE_DDHRESULT( 130 )
+#define DDERR_INVALIDPARAMS			E_INVALIDARG
+#define DDERR_INVALIDPIXELFORMAT		MAKE_DDHRESULT( 145 )
+#define DDERR_INVALIDRECT			MAKE_DDHRESULT( 150 )
+#define DDERR_LOCKEDSURFACES			MAKE_DDHRESULT( 160 )
+#define DDERR_NO3D				MAKE_DDHRESULT( 170 )
+#define DDERR_NOALPHAHW				MAKE_DDHRESULT( 180 )
+#define DDERR_NOSTEREOHARDWARE          	MAKE_DDHRESULT( 181 )
+#define DDERR_NOSURFACELEFT                     MAKE_DDHRESULT( 182 )
+#define DDERR_NOCLIPLIST			MAKE_DDHRESULT( 205 )
+#define DDERR_NOCOLORCONVHW			MAKE_DDHRESULT( 210 )
+#define DDERR_NOCOOPERATIVELEVELSET		MAKE_DDHRESULT( 212 )
+#define DDERR_NOCOLORKEY			MAKE_DDHRESULT( 215 )
+#define DDERR_NOCOLORKEYHW			MAKE_DDHRESULT( 220 )
+#define DDERR_NODIRECTDRAWSUPPORT		MAKE_DDHRESULT( 222 )
+#define DDERR_NOEXCLUSIVEMODE			MAKE_DDHRESULT( 225 )
+#define DDERR_NOFLIPHW				MAKE_DDHRESULT( 230 )
+#define DDERR_NOGDI				MAKE_DDHRESULT( 240 )
+#define DDERR_NOMIRRORHW			MAKE_DDHRESULT( 250 )
+#define DDERR_NOTFOUND				MAKE_DDHRESULT( 255 )
+#define DDERR_NOOVERLAYHW			MAKE_DDHRESULT( 260 )
+#define DDERR_OVERLAPPINGRECTS                  MAKE_DDHRESULT( 270 )
+#define DDERR_NORASTEROPHW			MAKE_DDHRESULT( 280 )
+#define DDERR_NOROTATIONHW			MAKE_DDHRESULT( 290 )
+#define DDERR_NOSTRETCHHW			MAKE_DDHRESULT( 310 )
+#define DDERR_NOT4BITCOLOR			MAKE_DDHRESULT( 316 )
+#define DDERR_NOT4BITCOLORINDEX			MAKE_DDHRESULT( 317 )
+#define DDERR_NOT8BITCOLOR			MAKE_DDHRESULT( 320 )
+#define DDERR_NOTEXTUREHW			MAKE_DDHRESULT( 330 )
+#define DDERR_NOVSYNCHW				MAKE_DDHRESULT( 335 )
+#define DDERR_NOZBUFFERHW			MAKE_DDHRESULT( 340 )
+#define DDERR_NOZOVERLAYHW			MAKE_DDHRESULT( 350 )
+#define DDERR_OUTOFCAPS				MAKE_DDHRESULT( 360 )
+#define DDERR_OUTOFMEMORY			E_OUTOFMEMORY
+#define DDERR_OUTOFVIDEOMEMORY			MAKE_DDHRESULT( 380 )
+#define DDERR_OVERLAYCANTCLIP			MAKE_DDHRESULT( 382 )
+#define DDERR_OVERLAYCOLORKEYONLYONEACTIVE	MAKE_DDHRESULT( 384 )
+#define DDERR_PALETTEBUSY			MAKE_DDHRESULT( 387 )
+#define DDERR_COLORKEYNOTSET			MAKE_DDHRESULT( 400 )
+#define DDERR_SURFACEALREADYATTACHED		MAKE_DDHRESULT( 410 )
+#define DDERR_SURFACEALREADYDEPENDENT		MAKE_DDHRESULT( 420 )
+#define DDERR_SURFACEBUSY			MAKE_DDHRESULT( 430 )
+#define DDERR_CANTLOCKSURFACE			MAKE_DDHRESULT( 435 )
+#define DDERR_SURFACEISOBSCURED			MAKE_DDHRESULT( 440 )
+#define DDERR_SURFACELOST			MAKE_DDHRESULT( 450 )
+#define DDERR_SURFACENOTATTACHED		MAKE_DDHRESULT( 460 )
+#define DDERR_TOOBIGHEIGHT			MAKE_DDHRESULT( 470 )
+#define DDERR_TOOBIGSIZE			MAKE_DDHRESULT( 480 )
+#define DDERR_TOOBIGWIDTH			MAKE_DDHRESULT( 490 )
+#define DDERR_UNSUPPORTED			E_NOTIMPL
+#define DDERR_UNSUPPORTEDFORMAT			MAKE_DDHRESULT( 510 )
+#define DDERR_UNSUPPORTEDMASK			MAKE_DDHRESULT( 520 )
+#define DDERR_INVALIDSTREAM                     MAKE_DDHRESULT( 521 )
+#define DDERR_VERTICALBLANKINPROGRESS		MAKE_DDHRESULT( 537 )
+#define DDERR_WASSTILLDRAWING			MAKE_DDHRESULT( 540 )
+#define DDERR_DDSCAPSCOMPLEXREQUIRED            MAKE_DDHRESULT( 542 )
+#define DDERR_XALIGN				MAKE_DDHRESULT( 560 )
+#define DDERR_INVALIDDIRECTDRAWGUID		MAKE_DDHRESULT( 561 )
+#define DDERR_DIRECTDRAWALREADYCREATED		MAKE_DDHRESULT( 562 )
+#define DDERR_NODIRECTDRAWHW			MAKE_DDHRESULT( 563 )
+#define DDERR_PRIMARYSURFACEALREADYEXISTS	MAKE_DDHRESULT( 564 )
+#define DDERR_NOEMULATION			MAKE_DDHRESULT( 565 )
+#define DDERR_REGIONTOOSMALL			MAKE_DDHRESULT( 566 )
+#define DDERR_CLIPPERISUSINGHWND		MAKE_DDHRESULT( 567 )
+#define DDERR_NOCLIPPERATTACHED			MAKE_DDHRESULT( 568 )
+#define DDERR_NOHWND				MAKE_DDHRESULT( 569 )
+#define DDERR_HWNDSUBCLASSED			MAKE_DDHRESULT( 570 )
+#define DDERR_HWNDALREADYSET			MAKE_DDHRESULT( 571 )
+#define DDERR_NOPALETTEATTACHED			MAKE_DDHRESULT( 572 )
+#define DDERR_NOPALETTEHW			MAKE_DDHRESULT( 573 )
+#define DDERR_BLTFASTCANTCLIP			MAKE_DDHRESULT( 574 )
+#define DDERR_NOBLTHW				MAKE_DDHRESULT( 575 )
+#define DDERR_NODDROPSHW			MAKE_DDHRESULT( 576 )
+#define DDERR_OVERLAYNOTVISIBLE			MAKE_DDHRESULT( 577 )
+#define DDERR_NOOVERLAYDEST			MAKE_DDHRESULT( 578 )
+#define DDERR_INVALIDPOSITION			MAKE_DDHRESULT( 579 )
+#define DDERR_NOTAOVERLAYSURFACE		MAKE_DDHRESULT( 580 )
+#define DDERR_EXCLUSIVEMODEALREADYSET		MAKE_DDHRESULT( 581 )
+#define DDERR_NOTFLIPPABLE			MAKE_DDHRESULT( 582 )
+#define DDERR_CANTDUPLICATE			MAKE_DDHRESULT( 583 )
+#define DDERR_NOTLOCKED				MAKE_DDHRESULT( 584 )
+#define DDERR_CANTCREATEDC			MAKE_DDHRESULT( 585 )
+#define DDERR_NODC				MAKE_DDHRESULT( 586 )
+#define DDERR_WRONGMODE				MAKE_DDHRESULT( 587 )
+#define DDERR_IMPLICITLYCREATED			MAKE_DDHRESULT( 588 )
+#define DDERR_NOTPALETTIZED			MAKE_DDHRESULT( 589 )
+#define DDERR_UNSUPPORTEDMODE			MAKE_DDHRESULT( 590 )
+#define DDERR_NOMIPMAPHW			MAKE_DDHRESULT( 591 )
+#define DDERR_INVALIDSURFACETYPE		MAKE_DDHRESULT( 592 )
+#define DDERR_NOOPTIMIZEHW			MAKE_DDHRESULT( 600 )
+#define DDERR_NOTLOADED				MAKE_DDHRESULT( 601 )
+#define DDERR_NOFOCUSWINDOW			MAKE_DDHRESULT( 602 )
+#define DDERR_NOTONMIPMAPSUBLEVEL               MAKE_DDHRESULT( 603 )
+#define DDERR_DCALREADYCREATED			MAKE_DDHRESULT( 620 )
+#define DDERR_NONONLOCALVIDMEM			MAKE_DDHRESULT( 630 )
+#define DDERR_CANTPAGELOCK			MAKE_DDHRESULT( 640 )
+#define DDERR_CANTPAGEUNLOCK			MAKE_DDHRESULT( 660 )
+#define DDERR_NOTPAGELOCKED			MAKE_DDHRESULT( 680 )
+#define DDERR_MOREDATA				MAKE_DDHRESULT( 690 )
+#define DDERR_EXPIRED                           MAKE_DDHRESULT( 691 )
+#define DDERR_TESTFINISHED                      MAKE_DDHRESULT( 692 )
+#define DDERR_NEWMODE                           MAKE_DDHRESULT( 693 )
+#define DDERR_D3DNOTINITIALIZED                 MAKE_DDHRESULT( 694 )
+#define DDERR_VIDEONOTACTIVE			MAKE_DDHRESULT( 695 )
+#define DDERR_NOMONITORINFORMATION              MAKE_DDHRESULT( 696 )
+#define DDERR_NODRIVERSUPPORT                   MAKE_DDHRESULT( 697 )
+#define DDERR_DEVICEDOESNTOWNSURFACE		MAKE_DDHRESULT( 699 )
+#define DDERR_NOTINITIALIZED			CO_E_NOTINITIALIZED
+
+/* dwFlags for Blt* */
+#define DDBLT_ALPHADEST				0x00000001
+#define DDBLT_ALPHADESTCONSTOVERRIDE		0x00000002
+#define DDBLT_ALPHADESTNEG			0x00000004
+#define DDBLT_ALPHADESTSURFACEOVERRIDE		0x00000008
+#define DDBLT_ALPHAEDGEBLEND			0x00000010
+#define DDBLT_ALPHASRC				0x00000020
+#define DDBLT_ALPHASRCCONSTOVERRIDE		0x00000040
+#define DDBLT_ALPHASRCNEG			0x00000080
+#define DDBLT_ALPHASRCSURFACEOVERRIDE		0x00000100
+#define DDBLT_ASYNC				0x00000200
+#define DDBLT_COLORFILL				0x00000400
+#define DDBLT_DDFX				0x00000800
+#define DDBLT_DDROPS				0x00001000
+#define DDBLT_KEYDEST				0x00002000
+#define DDBLT_KEYDESTOVERRIDE			0x00004000
+#define DDBLT_KEYSRC				0x00008000
+#define DDBLT_KEYSRCOVERRIDE			0x00010000
+#define DDBLT_ROP				0x00020000
+#define DDBLT_ROTATIONANGLE			0x00040000
+#define DDBLT_ZBUFFER				0x00080000
+#define DDBLT_ZBUFFERDESTCONSTOVERRIDE		0x00100000
+#define DDBLT_ZBUFFERDESTOVERRIDE		0x00200000
+#define DDBLT_ZBUFFERSRCCONSTOVERRIDE		0x00400000
+#define DDBLT_ZBUFFERSRCOVERRIDE		0x00800000
+#define DDBLT_WAIT				0x01000000
+#define DDBLT_DEPTHFILL				0x02000000
+#define DDBLT_DONOTWAIT                         0x08000000
+
+/* dwTrans for BltFast */
+#define DDBLTFAST_NOCOLORKEY			0x00000000
+#define DDBLTFAST_SRCCOLORKEY			0x00000001
+#define DDBLTFAST_DESTCOLORKEY			0x00000002
+#define DDBLTFAST_WAIT				0x00000010
+#define DDBLTFAST_DONOTWAIT                     0x00000020
+
+/* dwFlags for Flip */
+#define DDFLIP_WAIT		0x00000001
+#define DDFLIP_EVEN		0x00000002 /* only valid for overlay */
+#define DDFLIP_ODD		0x00000004 /* only valid for overlay */
+#define DDFLIP_NOVSYNC		0x00000008
+#define DDFLIP_STEREO		0x00000010
+#define DDFLIP_DONOTWAIT	0x00000020
+
+/* dwFlags for GetBltStatus */
+#define DDGBS_CANBLT				0x00000001
+#define DDGBS_ISBLTDONE				0x00000002
+
+/* dwFlags for IDirectDrawSurface7::GetFlipStatus */
+#define DDGFS_CANFLIP		1L
+#define DDGFS_ISFLIPDONE	2L
+
+/* dwFlags for IDirectDrawSurface7::SetPrivateData */
+#define DDSPD_IUNKNOWNPTR	1L
+#define DDSPD_VOLATILE		2L
+
+/* DDSCAPS.dwCaps */
+/* reserved1, was 3d capable */
+#define DDSCAPS_RESERVED1		0x00000001
+/* surface contains alpha information */
+#define DDSCAPS_ALPHA			0x00000002
+/* this surface is a backbuffer */
+#define DDSCAPS_BACKBUFFER		0x00000004
+/* complex surface structure */
+#define DDSCAPS_COMPLEX			0x00000008
+/* part of surface flipping structure */
+#define DDSCAPS_FLIP			0x00000010
+/* this surface is the frontbuffer surface */
+#define DDSCAPS_FRONTBUFFER		0x00000020
+/* this is a plain offscreen surface */
+#define DDSCAPS_OFFSCREENPLAIN		0x00000040
+/* overlay */
+#define DDSCAPS_OVERLAY			0x00000080
+/* palette objects can be created and attached to us */
+#define DDSCAPS_PALETTE			0x00000100
+/* primary surface (the one the user looks at currently)(right eye)*/
+#define DDSCAPS_PRIMARYSURFACE		0x00000200
+/* primary surface for left eye */
+#define DDSCAPS_PRIMARYSURFACELEFT	0x00000400
+/* surface exists in systemmemory */
+#define DDSCAPS_SYSTEMMEMORY		0x00000800
+/* surface can be used as a texture */
+#define DDSCAPS_TEXTURE		        0x00001000
+/* surface may be destination for 3d rendering */
+#define DDSCAPS_3DDEVICE		0x00002000
+/* surface exists in videomemory */
+#define DDSCAPS_VIDEOMEMORY		0x00004000
+/* surface changes immediately visible */
+#define DDSCAPS_VISIBLE			0x00008000
+/* write only surface */
+#define DDSCAPS_WRITEONLY		0x00010000
+/* zbuffer surface */
+#define DDSCAPS_ZBUFFER			0x00020000
+/* has its own DC */
+#define DDSCAPS_OWNDC			0x00040000
+/* surface should be able to receive live video */
+#define DDSCAPS_LIVEVIDEO		0x00080000
+/* should be able to have a hw codec decompress stuff into it */
+#define DDSCAPS_HWCODEC			0x00100000
+/* mode X (320x200 or 320x240) surface */
+#define DDSCAPS_MODEX			0x00200000
+/* one mipmap surface (1 level) */
+#define DDSCAPS_MIPMAP			0x00400000
+#define DDSCAPS_RESERVED2		0x00800000
+/* memory allocation delayed until Load() */
+#define DDSCAPS_ALLOCONLOAD		0x04000000
+/* Indicates that the surface will receive data from a video port */
+#define DDSCAPS_VIDEOPORT		0x08000000
+/* surface is in local videomemory */
+#define DDSCAPS_LOCALVIDMEM		0x10000000
+/* surface is in nonlocal videomemory */
+#define DDSCAPS_NONLOCALVIDMEM		0x20000000
+/* surface is a standard VGA mode surface (NOT ModeX) */
+#define DDSCAPS_STANDARDVGAMODE		0x40000000
+/* optimized? surface */
+#define DDSCAPS_OPTIMIZED		0x80000000
+
+typedef struct _DDSCAPS {
+	DWORD	dwCaps;	/* capabilities of surface wanted */
+} DDSCAPS,*LPDDSCAPS;
+
+/* DDSCAPS2.dwCaps2 */
+/* indicates the surface will receive data from a video port using
+   deinterlacing hardware. */
+#define DDSCAPS2_HARDWAREDEINTERLACE	0x00000002
+/* indicates the surface will be locked very frequently. */
+#define DDSCAPS2_HINTDYNAMIC		0x00000004
+/* indicates surface can be re-ordered or retiled on load() */
+#define DDSCAPS2_HINTSTATIC             0x00000008
+/* indicates surface to be managed by directdraw/direct3D */
+#define DDSCAPS2_TEXTUREMANAGE          0x00000010
+/* reserved bits */
+#define DDSCAPS2_RESERVED1              0x00000020
+#define DDSCAPS2_RESERVED2              0x00000040
+/* indicates surface will never be locked again */
+#define DDSCAPS2_OPAQUE                 0x00000080
+/* set at CreateSurface() time to indicate antialising will be used */
+#define DDSCAPS2_HINTANTIALIASING       0x00000100
+/* set at CreateSurface() time to indicate cubic environment map */
+#define DDSCAPS2_CUBEMAP                0x00000200
+/* face flags for cube maps */
+#define DDSCAPS2_CUBEMAP_POSITIVEX      0x00000400
+#define DDSCAPS2_CUBEMAP_NEGATIVEX      0x00000800
+#define DDSCAPS2_CUBEMAP_POSITIVEY      0x00001000
+#define DDSCAPS2_CUBEMAP_NEGATIVEY      0x00002000
+#define DDSCAPS2_CUBEMAP_POSITIVEZ      0x00004000
+#define DDSCAPS2_CUBEMAP_NEGATIVEZ      0x00008000
+/* specifies all faces of a cube for CreateSurface() */
+#define DDSCAPS2_CUBEMAP_ALLFACES ( DDSCAPS2_CUBEMAP_POSITIVEX |\
+                                    DDSCAPS2_CUBEMAP_NEGATIVEX |\
+                                    DDSCAPS2_CUBEMAP_POSITIVEY |\
+                                    DDSCAPS2_CUBEMAP_NEGATIVEY |\
+                                    DDSCAPS2_CUBEMAP_POSITIVEZ |\
+                                    DDSCAPS2_CUBEMAP_NEGATIVEZ )
+/* set for mipmap sublevels on DirectX7 and later.  ignored by CreateSurface() */
+#define DDSCAPS2_MIPMAPSUBLEVEL         0x00010000
+/* indicates texture surface to be managed by Direct3D *only* */
+#define DDSCAPS2_D3DTEXTUREMANAGE       0x00020000
+/* indicates managed surface that can safely be lost */
+#define DDSCAPS2_DONOTPERSIST           0x00040000
+/* indicates surface is part of a stereo flipping chain */
+#define DDSCAPS2_STEREOSURFACELEFT      0x00080000
+
+typedef struct _DDSCAPS2 {
+	DWORD	dwCaps;	/* capabilities of surface wanted */
+	DWORD   dwCaps2; /* additional capabilities */
+	DWORD   dwCaps3; /* reserved capabilities */
+	DWORD   dwCaps4; /* more reserved capabilities */
+} DDSCAPS2,*LPDDSCAPS2;
+
+#define	DD_ROP_SPACE	(256/32)	/* space required to store ROP array */
+
+typedef struct _DDCAPS_DX7		/* DirectX 7 version of caps struct */
+{
+    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
+    DWORD	dwCaps;                 /* driver specific capabilities */
+    DWORD	dwCaps2;                /* more driver specific capabilites */
+    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
+    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
+    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
+    DWORD	dwPalCaps;              /* palette capabilities */
+    DWORD	dwSVCaps;               /* stereo vision capabilities */
+    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
+    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
+    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
+    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
+    DWORD	dwVidMemTotal;          /* total amount of video memory */
+    DWORD	dwVidMemFree;           /* amount of free video memory */
+    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
+    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
+    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
+    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
+    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
+    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
+    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
+    DWORD	dwAlignStrideAlign;     /* stride alignment */
+    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
+    DDSCAPS	ddsOldCaps;             /* old DDSCAPS - superceded for DirectX6+ */
+    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwReserved1;
+    DWORD	dwReserved2;
+    DWORD	dwReserved3;
+    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
+    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
+    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
+    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
+    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
+    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
+    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
+    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
+    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
+    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
+    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
+    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
+    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
+    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
+    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
+    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
+    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
+    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
+    DDSCAPS2    ddsCaps;		/* surface capabilities */
+} DDCAPS_DX7,*LPDDCAPS_DX7;
+
+typedef struct _DDCAPS_DX6		/* DirectX 6 version of caps struct */
+{
+    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
+    DWORD	dwCaps;                 /* driver specific capabilities */
+    DWORD	dwCaps2;                /* more driver specific capabilites */
+    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
+    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
+    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
+    DWORD	dwPalCaps;              /* palette capabilities */
+    DWORD	dwSVCaps;               /* stereo vision capabilities */
+    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
+    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
+    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
+    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
+    DWORD	dwVidMemTotal;          /* total amount of video memory */
+    DWORD	dwVidMemFree;           /* amount of free video memory */
+    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
+    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
+    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
+    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
+    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
+    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
+    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
+    DWORD	dwAlignStrideAlign;     /* stride alignment */
+    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
+    DDSCAPS	ddsOldCaps;             /* old DDSCAPS - superceded for DirectX6+ */
+    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwReserved1;
+    DWORD	dwReserved2;
+    DWORD	dwReserved3;
+    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
+    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
+    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
+    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
+    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
+    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
+    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
+    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
+    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
+    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
+    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
+    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
+    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
+    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
+    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
+    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
+    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
+    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
+    /* and one new member for DirectX 6 */
+    DDSCAPS2    ddsCaps;		/* surface capabilities */
+} DDCAPS_DX6,*LPDDCAPS_DX6;
+
+typedef struct _DDCAPS_DX5		/* DirectX5 version of caps struct */
+{
+    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
+    DWORD	dwCaps;                 /* driver specific capabilities */
+    DWORD	dwCaps2;                /* more driver specific capabilites */
+    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
+    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
+    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
+    DWORD	dwPalCaps;              /* palette capabilities */
+    DWORD	dwSVCaps;               /* stereo vision capabilities */
+    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
+    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
+    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
+    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
+    DWORD	dwVidMemTotal;          /* total amount of video memory */
+    DWORD	dwVidMemFree;           /* amount of free video memory */
+    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
+    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
+    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
+    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
+    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
+    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
+    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
+    DWORD	dwAlignStrideAlign;     /* stride alignment */
+    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
+    DDSCAPS	ddsCaps;                /* DDSCAPS structure has all the general capabilities */
+    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwReserved1;
+    DWORD	dwReserved2;
+    DWORD	dwReserved3;
+    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
+    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
+    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
+    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
+    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
+    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
+    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
+    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
+    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
+    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
+    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
+    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
+    /* the following are the new DirectX 5 members */
+    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
+    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
+    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
+    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
+    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
+    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
+} DDCAPS_DX5,*LPDDCAPS_DX5;
+
+typedef struct _DDCAPS_DX3		/* DirectX3 version of caps struct */
+{
+    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
+    DWORD	dwCaps;                 /* driver specific capabilities */
+    DWORD	dwCaps2;                /* more driver specific capabilites */
+    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
+    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
+    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
+    DWORD	dwPalCaps;              /* palette capabilities */
+    DWORD	dwSVCaps;               /* stereo vision capabilities */
+    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
+    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
+    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
+    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
+    DWORD	dwVidMemTotal;          /* total amount of video memory */
+    DWORD	dwVidMemFree;           /* amount of free video memory */
+    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
+    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
+    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
+    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
+    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
+    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
+    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
+    DWORD	dwAlignStrideAlign;     /* stride alignment */
+    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
+    DDSCAPS	ddsCaps;                /* DDSCAPS structure has all the general capabilities */
+    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwReserved1;
+    DWORD	dwReserved2;
+    DWORD	dwReserved3;
+    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
+    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
+    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
+    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
+    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
+    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
+    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
+    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
+    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
+    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
+    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
+    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
+    DWORD	dwReserved4;
+    DWORD	dwReserved5;
+    DWORD	dwReserved6;
+} DDCAPS_DX3,*LPDDCAPS_DX3;
+
+/* set caps struct according to DIRECTDRAW_VERSION */
+
+#if DIRECTDRAW_VERSION <= 0x300
+typedef DDCAPS_DX3 DDCAPS;
+#elif DIRECTDRAW_VERSION <= 0x500
+typedef DDCAPS_DX5 DDCAPS;
+#elif DIRECTDRAW_VERSION <= 0x600
+typedef DDCAPS_DX6 DDCAPS;
+#else
+typedef DDCAPS_DX7 DDCAPS;
+#endif
+
+typedef DDCAPS *LPDDCAPS;
+
+/* DDCAPS.dwCaps */
+#define DDCAPS_3D			0x00000001
+#define DDCAPS_ALIGNBOUNDARYDEST	0x00000002
+#define DDCAPS_ALIGNSIZEDEST		0x00000004
+#define DDCAPS_ALIGNBOUNDARYSRC		0x00000008
+#define DDCAPS_ALIGNSIZESRC		0x00000010
+#define DDCAPS_ALIGNSTRIDE		0x00000020
+#define DDCAPS_BLT			0x00000040
+#define DDCAPS_BLTQUEUE			0x00000080
+#define DDCAPS_BLTFOURCC		0x00000100
+#define DDCAPS_BLTSTRETCH		0x00000200
+#define DDCAPS_GDI			0x00000400
+#define DDCAPS_OVERLAY			0x00000800
+#define DDCAPS_OVERLAYCANTCLIP		0x00001000
+#define DDCAPS_OVERLAYFOURCC		0x00002000
+#define DDCAPS_OVERLAYSTRETCH		0x00004000
+#define DDCAPS_PALETTE			0x00008000
+#define DDCAPS_PALETTEVSYNC		0x00010000
+#define DDCAPS_READSCANLINE		0x00020000
+#define DDCAPS_STEREOVIEW		0x00040000
+#define DDCAPS_VBI			0x00080000
+#define DDCAPS_ZBLTS			0x00100000
+#define DDCAPS_ZOVERLAYS		0x00200000
+#define DDCAPS_COLORKEY			0x00400000
+#define DDCAPS_ALPHA			0x00800000
+#define DDCAPS_COLORKEYHWASSIST		0x01000000
+#define DDCAPS_NOHARDWARE		0x02000000
+#define DDCAPS_BLTCOLORFILL		0x04000000
+#define DDCAPS_BANKSWITCHED		0x08000000
+#define DDCAPS_BLTDEPTHFILL		0x10000000
+#define DDCAPS_CANCLIP			0x20000000
+#define DDCAPS_CANCLIPSTRETCHED		0x40000000
+#define DDCAPS_CANBLTSYSMEM		0x80000000
+
+/* DDCAPS.dwCaps2 */
+#define DDCAPS2_CERTIFIED		0x00000001
+#define DDCAPS2_NO2DDURING3DSCENE       0x00000002
+#define DDCAPS2_VIDEOPORT		0x00000004
+#define DDCAPS2_AUTOFLIPOVERLAY		0x00000008
+#define DDCAPS2_CANBOBINTERLEAVED	0x00000010
+#define DDCAPS2_CANBOBNONINTERLEAVED	0x00000020
+#define DDCAPS2_COLORCONTROLOVERLAY	0x00000040
+#define DDCAPS2_COLORCONTROLPRIMARY	0x00000080
+#define DDCAPS2_CANDROPZ16BIT		0x00000100
+#define DDCAPS2_NONLOCALVIDMEM		0x00000200
+#define DDCAPS2_NONLOCALVIDMEMCAPS	0x00000400
+#define DDCAPS2_NOPAGELOCKREQUIRED	0x00000800
+#define DDCAPS2_WIDESURFACES		0x00001000
+#define DDCAPS2_CANFLIPODDEVEN		0x00002000
+#define DDCAPS2_CANBOBHARDWARE		0x00004000
+#define DDCAPS2_COPYFOURCC              0x00008000
+#define DDCAPS2_PRIMARYGAMMA            0x00020000
+#define DDCAPS2_CANRENDERWINDOWED       0x00080000
+#define DDCAPS2_CANCALIBRATEGAMMA       0x00100000
+#define DDCAPS2_FLIPINTERVAL            0x00200000
+#define DDCAPS2_FLIPNOVSYNC             0x00400000
+#define DDCAPS2_CANMANAGETEXTURE        0x00800000
+#define DDCAPS2_TEXMANINNONLOCALVIDMEM  0x01000000
+#define DDCAPS2_STEREO                  0x02000000
+#define DDCAPS2_SYSTONONLOCAL_AS_SYSTOLOCAL   0x04000000
+
+
+/* Set/Get Colour Key Flags */
+#define DDCKEY_COLORSPACE  0x00000001  /* Struct is single colour space */
+#define DDCKEY_DESTBLT     0x00000002  /* To be used as dest for blt */
+#define DDCKEY_DESTOVERLAY 0x00000004  /* To be used as dest for CK overlays */
+#define DDCKEY_SRCBLT      0x00000008  /* To be used as src for blt */
+#define DDCKEY_SRCOVERLAY  0x00000010  /* To be used as src for CK overlays */
+
+typedef struct _DDCOLORKEY
+{
+	DWORD	dwColorSpaceLowValue;/* low boundary of color space that is to
+                                      * be treated as Color Key, inclusive
+				      */
+	DWORD	dwColorSpaceHighValue;/* high boundary of color space that is
+                                       * to be treated as Color Key, inclusive
+				       */
+} DDCOLORKEY,*LPDDCOLORKEY;
+
+/* ddCKEYCAPS bits */
+#define DDCKEYCAPS_DESTBLT			0x00000001
+#define DDCKEYCAPS_DESTBLTCLRSPACE		0x00000002
+#define DDCKEYCAPS_DESTBLTCLRSPACEYUV		0x00000004
+#define DDCKEYCAPS_DESTBLTYUV			0x00000008
+#define DDCKEYCAPS_DESTOVERLAY			0x00000010
+#define DDCKEYCAPS_DESTOVERLAYCLRSPACE		0x00000020
+#define DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV	0x00000040
+#define DDCKEYCAPS_DESTOVERLAYONEACTIVE		0x00000080
+#define DDCKEYCAPS_DESTOVERLAYYUV		0x00000100
+#define DDCKEYCAPS_SRCBLT			0x00000200
+#define DDCKEYCAPS_SRCBLTCLRSPACE		0x00000400
+#define DDCKEYCAPS_SRCBLTCLRSPACEYUV		0x00000800
+#define DDCKEYCAPS_SRCBLTYUV			0x00001000
+#define DDCKEYCAPS_SRCOVERLAY			0x00002000
+#define DDCKEYCAPS_SRCOVERLAYCLRSPACE		0x00004000
+#define DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV	0x00008000
+#define DDCKEYCAPS_SRCOVERLAYONEACTIVE		0x00010000
+#define DDCKEYCAPS_SRCOVERLAYYUV		0x00020000
+#define DDCKEYCAPS_NOCOSTOVERLAY		0x00040000
+
+typedef struct _DDPIXELFORMAT {
+    DWORD	dwSize;                 /* 0: size of structure */
+    DWORD	dwFlags;                /* 4: pixel format flags */
+    DWORD	dwFourCC;               /* 8: (FOURCC code) */
+    union {
+	DWORD	dwRGBBitCount;          /* C: how many bits per pixel */
+	DWORD	dwYUVBitCount;          /* C: how many bits per pixel */
+	DWORD	dwZBufferBitDepth;      /* C: how many bits for z buffers */
+	DWORD	dwAlphaBitDepth;        /* C: how many bits for alpha channels*/
+	DWORD	dwLuminanceBitCount;
+	DWORD	dwBumpBitCount;
+    } DUMMYUNIONNAME1;
+    union {
+	DWORD	dwRBitMask;             /* 10: mask for red bit*/
+	DWORD	dwYBitMask;             /* 10: mask for Y bits*/
+	DWORD	dwStencilBitDepth;
+	DWORD	dwLuminanceBitMask;
+	DWORD	dwBumpDuBitMask;
+    } DUMMYUNIONNAME2;
+    union {
+	DWORD	dwGBitMask;             /* 14: mask for green bits*/
+	DWORD	dwUBitMask;             /* 14: mask for U bits*/
+	DWORD	dwZBitMask;
+	DWORD	dwBumpDvBitMask;
+    } DUMMYUNIONNAME3;
+    union {
+	DWORD   dwBBitMask;             /* 18: mask for blue bits*/
+	DWORD   dwVBitMask;             /* 18: mask for V bits*/
+	DWORD	dwStencilBitMask;
+	DWORD	dwBumpLuminanceBitMask;
+    } DUMMYUNIONNAME4;
+    union {
+    	DWORD	dwRGBAlphaBitMask;	/* 1C: mask for alpha channel */
+    	DWORD	dwYUVAlphaBitMask;	/* 1C: mask for alpha channel */
+	DWORD	dwLuminanceAlphaBitMask;
+	DWORD	dwRGBZBitMask;		/* 1C: mask for Z channel */
+	DWORD	dwYUVZBitMask;		/* 1C: mask for Z channel */
+    } DUMMYUNIONNAME5;
+    					/* 20: next structure */
+} DDPIXELFORMAT,*LPDDPIXELFORMAT;
+
+/* DDCAPS.dwFXCaps */
+#define DDFXCAPS_BLTALPHA               0x00000001
+#define DDFXCAPS_OVERLAYALPHA           0x00000004
+#define DDFXCAPS_BLTARITHSTRETCHYN	0x00000010
+#define DDFXCAPS_BLTARITHSTRETCHY	0x00000020
+#define DDFXCAPS_BLTMIRRORLEFTRIGHT	0x00000040
+#define DDFXCAPS_BLTMIRRORUPDOWN	0x00000080
+#define DDFXCAPS_BLTROTATION		0x00000100
+#define DDFXCAPS_BLTROTATION90		0x00000200
+#define DDFXCAPS_BLTSHRINKX		0x00000400
+#define DDFXCAPS_BLTSHRINKXN		0x00000800
+#define DDFXCAPS_BLTSHRINKY		0x00001000
+#define DDFXCAPS_BLTSHRINKYN		0x00002000
+#define DDFXCAPS_BLTSTRETCHX		0x00004000
+#define DDFXCAPS_BLTSTRETCHXN		0x00008000
+#define DDFXCAPS_BLTSTRETCHY		0x00010000
+#define DDFXCAPS_BLTSTRETCHYN		0x00020000
+#define DDFXCAPS_OVERLAYARITHSTRETCHY	0x00040000
+#define DDFXCAPS_OVERLAYARITHSTRETCHYN	0x00000008
+#define DDFXCAPS_OVERLAYSHRINKX		0x00080000
+#define DDFXCAPS_OVERLAYSHRINKXN	0x00100000
+#define DDFXCAPS_OVERLAYSHRINKY		0x00200000
+#define DDFXCAPS_OVERLAYSHRINKYN	0x00400000
+#define DDFXCAPS_OVERLAYSTRETCHX	0x00800000
+#define DDFXCAPS_OVERLAYSTRETCHXN	0x01000000
+#define DDFXCAPS_OVERLAYSTRETCHY	0x02000000
+#define DDFXCAPS_OVERLAYSTRETCHYN	0x04000000
+#define DDFXCAPS_OVERLAYMIRRORLEFTRIGHT	0x08000000
+#define DDFXCAPS_OVERLAYMIRRORUPDOWN	0x10000000
+
+#define DDFXCAPS_OVERLAYFILTER          DDFXCAPS_OVERLAYARITHSTRETCHY
+
+/* DDCAPS.dwFXAlphaCaps */
+#define DDFXALPHACAPS_BLTALPHAEDGEBLEND		0x00000001
+#define DDFXALPHACAPS_BLTALPHAPIXELS		0x00000002
+#define DDFXALPHACAPS_BLTALPHAPIXELSNEG		0x00000004
+#define DDFXALPHACAPS_BLTALPHASURFACES		0x00000008
+#define DDFXALPHACAPS_BLTALPHASURFACESNEG	0x00000010
+#define DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND	0x00000020
+#define DDFXALPHACAPS_OVERLAYALPHAPIXELS	0x00000040
+#define DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG	0x00000080
+#define DDFXALPHACAPS_OVERLAYALPHASURFACES	0x00000100
+#define DDFXALPHACAPS_OVERLAYALPHASURFACESNEG	0x00000200
+
+/* DDCAPS.dwPalCaps */
+#define DDPCAPS_4BIT			0x00000001
+#define DDPCAPS_8BITENTRIES		0x00000002
+#define DDPCAPS_8BIT			0x00000004
+#define DDPCAPS_INITIALIZE		0x00000008
+#define DDPCAPS_PRIMARYSURFACE		0x00000010
+#define DDPCAPS_PRIMARYSURFACELEFT	0x00000020
+#define DDPCAPS_ALLOW256		0x00000040
+#define DDPCAPS_VSYNC			0x00000080
+#define DDPCAPS_1BIT			0x00000100
+#define DDPCAPS_2BIT			0x00000200
+#define DDPCAPS_ALPHA                   0x00000400
+
+/* DDCAPS.dwSVCaps */
+/* the first 4 of these are now obsolete */
+#if DIRECTDRAW_VERSION >= 0x700	/* FIXME: I'm not sure when this switch occured */
+#define DDSVCAPS_RESERVED1		0x00000001
+#define DDSVCAPS_RESERVED2		0x00000002
+#define DDSVCAPS_RESERVED3		0x00000004
+#define DDSVCAPS_RESERVED4		0x00000008
+#else
+#define DDSVCAPS_ENIGMA			0x00000001
+#define DDSVCAPS_FLICKER		0x00000002
+#define DDSVCAPS_REDBLUE		0x00000004
+#define DDSVCAPS_SPLIT			0x00000008
+#endif
+#define DDSVCAPS_STEREOSEQUENTIAL       0x00000010
+
+/* BitDepths */
+#define DDBD_1				0x00004000
+#define DDBD_2				0x00002000
+#define DDBD_4				0x00001000
+#define DDBD_8				0x00000800
+#define DDBD_16				0x00000400
+#define DDBD_24				0x00000200
+#define DDBD_32				0x00000100
+
+/* DDOVERLAYFX.dwDDFX */
+#define DDOVERFX_ARITHSTRETCHY		0x00000001
+#define DDOVERFX_MIRRORLEFTRIGHT	0x00000002
+#define DDOVERFX_MIRRORUPDOWN		0x00000004
+
+/* UpdateOverlay flags */
+#define DDOVER_ALPHADEST                        0x00000001
+#define DDOVER_ALPHADESTCONSTOVERRIDE           0x00000002
+#define DDOVER_ALPHADESTNEG                     0x00000004
+#define DDOVER_ALPHADESTSURFACEOVERRIDE         0x00000008
+#define DDOVER_ALPHAEDGEBLEND                   0x00000010
+#define DDOVER_ALPHASRC                         0x00000020
+#define DDOVER_ALPHASRCCONSTOVERRIDE            0x00000040
+#define DDOVER_ALPHASRCNEG                      0x00000080
+#define DDOVER_ALPHASRCSURFACEOVERRIDE          0x00000100
+#define DDOVER_HIDE                             0x00000200
+#define DDOVER_KEYDEST                          0x00000400
+#define DDOVER_KEYDESTOVERRIDE                  0x00000800
+#define DDOVER_KEYSRC                           0x00001000
+#define DDOVER_KEYSRCOVERRIDE                   0x00002000
+#define DDOVER_SHOW                             0x00004000
+#define DDOVER_ADDDIRTYRECT                     0x00008000
+#define DDOVER_REFRESHDIRTYRECTS                0x00010000
+#define DDOVER_REFRESHALL                       0x00020000
+#define DDOVER_DDFX                             0x00080000
+#define DDOVER_AUTOFLIP                         0x00100000
+#define DDOVER_BOB                              0x00200000
+#define DDOVER_OVERRIDEBOBWEAVE                 0x00400000
+#define DDOVER_INTERLEAVED                      0x00800000
+
+/* DDCOLORKEY.dwFlags */
+#define DDPF_ALPHAPIXELS		0x00000001
+#define DDPF_ALPHA			0x00000002
+#define DDPF_FOURCC			0x00000004
+#define DDPF_PALETTEINDEXED4		0x00000008
+#define DDPF_PALETTEINDEXEDTO8		0x00000010
+#define DDPF_PALETTEINDEXED8		0x00000020
+#define DDPF_RGB			0x00000040
+#define DDPF_COMPRESSED			0x00000080
+#define DDPF_RGBTOYUV			0x00000100
+#define DDPF_YUV			0x00000200
+#define DDPF_ZBUFFER			0x00000400
+#define DDPF_PALETTEINDEXED1		0x00000800
+#define DDPF_PALETTEINDEXED2		0x00001000
+#define DDPF_ZPIXELS			0x00002000
+#define DDPF_STENCILBUFFER              0x00004000
+#define DDPF_ALPHAPREMULT               0x00008000
+#define DDPF_LUMINANCE                  0x00020000
+#define DDPF_BUMPLUMINANCE              0x00040000
+#define DDPF_BUMPDUDV                   0x00080000
+
+/* SetCooperativeLevel dwFlags */
+#define DDSCL_FULLSCREEN		0x00000001
+#define DDSCL_ALLOWREBOOT		0x00000002
+#define DDSCL_NOWINDOWCHANGES		0x00000004
+#define DDSCL_NORMAL			0x00000008
+#define DDSCL_EXCLUSIVE			0x00000010
+#define DDSCL_ALLOWMODEX		0x00000040
+#define DDSCL_SETFOCUSWINDOW		0x00000080
+#define DDSCL_SETDEVICEWINDOW		0x00000100
+#define DDSCL_CREATEDEVICEWINDOW	0x00000200
+#define DDSCL_MULTITHREADED             0x00000400
+#define DDSCL_FPUSETUP                  0x00000800
+#define DDSCL_FPUPRESERVE               0x00001000
+
+
+/* DDSURFACEDESC.dwFlags */
+#define	DDSD_CAPS		0x00000001
+#define	DDSD_HEIGHT		0x00000002
+#define	DDSD_WIDTH		0x00000004
+#define	DDSD_PITCH		0x00000008
+#define	DDSD_BACKBUFFERCOUNT	0x00000020
+#define	DDSD_ZBUFFERBITDEPTH	0x00000040
+#define	DDSD_ALPHABITDEPTH	0x00000080
+#define	DDSD_LPSURFACE		0x00000800
+#define	DDSD_PIXELFORMAT	0x00001000
+#define	DDSD_CKDESTOVERLAY	0x00002000
+#define	DDSD_CKDESTBLT		0x00004000
+#define	DDSD_CKSRCOVERLAY	0x00008000
+#define	DDSD_CKSRCBLT		0x00010000
+#define	DDSD_MIPMAPCOUNT	0x00020000
+#define	DDSD_REFRESHRATE	0x00040000
+#define	DDSD_LINEARSIZE		0x00080000
+#define DDSD_TEXTURESTAGE       0x00100000
+#define DDSD_FVF                0x00200000
+#define DDSD_SRCVBHANDLE        0x00400000
+#define	DDSD_ALL		0x007ff9ee
+
+/* EnumSurfaces flags */
+#define DDENUMSURFACES_ALL          0x00000001
+#define DDENUMSURFACES_MATCH        0x00000002
+#define DDENUMSURFACES_NOMATCH      0x00000004
+#define DDENUMSURFACES_CANBECREATED 0x00000008
+#define DDENUMSURFACES_DOESEXIST    0x00000010
+
+/* SetDisplayMode flags */
+#define DDSDM_STANDARDVGAMODE	0x00000001
+
+/* EnumDisplayModes flags */
+#define DDEDM_REFRESHRATES	0x00000001
+#define DDEDM_STANDARDVGAMODES	0x00000002
+
+/* WaitForVerticalDisplay flags */
+
+#define DDWAITVB_BLOCKBEGIN		0x00000001
+#define DDWAITVB_BLOCKBEGINEVENT	0x00000002
+#define DDWAITVB_BLOCKEND		0x00000004
+
+typedef struct _DDSURFACEDESC
+{
+	DWORD	dwSize;		/* 0: size of the DDSURFACEDESC structure*/
+	DWORD	dwFlags;	/* 4: determines what fields are valid*/
+	DWORD	dwHeight;	/* 8: height of surface to be created*/
+	DWORD	dwWidth;	/* C: width of input surface*/
+	union {
+		LONG	lPitch;	/* 10: distance to start of next line (return value only)*/
+		DWORD	dwLinearSize;
+	} DUMMYUNIONNAME1;
+	DWORD	dwBackBufferCount;/* 14: number of back buffers requested*/
+	union {
+		DWORD	dwMipMapCount;/* 18:number of mip-map levels requested*/
+		DWORD	dwZBufferBitDepth;/*18: depth of Z buffer requested*/
+		DWORD	dwRefreshRate;/* 18:refresh rate (used when display mode is described)*/
+	} DUMMYUNIONNAME2;		
+	DWORD	dwAlphaBitDepth;/* 1C:depth of alpha buffer requested*/
+	DWORD	dwReserved;	/* 20:reserved*/
+	LPVOID	lpSurface;	/* 24:pointer to the associated surface memory*/
+	DDCOLORKEY	ddckCKDestOverlay;/* 28: CK for dest overlay use*/
+	DDCOLORKEY	ddckCKDestBlt;	/* 30: CK for destination blt use*/
+	DDCOLORKEY	ddckCKSrcOverlay;/* 38: CK for source overlay use*/
+	DDCOLORKEY	ddckCKSrcBlt;	/* 40: CK for source blt use*/
+	DDPIXELFORMAT	ddpfPixelFormat;/* 48: pixel format description of the surface*/
+	DDSCAPS		ddsCaps;	/* 68: direct draw surface caps */
+} DDSURFACEDESC,*LPDDSURFACEDESC;
+
+typedef struct _DDSURFACEDESC2
+{
+	DWORD	dwSize;		/* 0: size of the DDSURFACEDESC structure*/
+	DWORD	dwFlags;	/* 4: determines what fields are valid*/
+	DWORD	dwHeight;	/* 8: height of surface to be created*/
+	DWORD	dwWidth;	/* C: width of input surface*/
+	union {
+		LONG	lPitch;	      /*10: distance to start of next line (return value only)*/
+		DWORD   dwLinearSize; /*10: formless late-allocated optimized surface size */
+	} DUMMYUNIONNAME1;
+	DWORD	dwBackBufferCount;/* 14: number of back buffers requested*/
+	union {
+		DWORD	dwMipMapCount;/* 18:number of mip-map levels requested*/
+		DWORD	dwRefreshRate;/* 18:refresh rate (used when display mode is described)*/
+		DWORD   dwSrcVBHandle;/* 18:source used in VB::Optimize */
+	} DUMMYUNIONNAME2;
+	DWORD	dwAlphaBitDepth;/* 1C:depth of alpha buffer requested*/
+	DWORD	dwReserved;	/* 20:reserved*/
+	LPVOID	lpSurface;	/* 24:pointer to the associated surface memory*/
+	union {
+		DDCOLORKEY	ddckCKDestOverlay; /* 28: CK for dest overlay use*/
+		DWORD 		dwEmptyFaceColor;  /* 28: color for empty cubemap faces */
+	} DUMMYUNIONNAME3;
+	DDCOLORKEY	ddckCKDestBlt;	/* 30: CK for destination blt use*/
+	DDCOLORKEY	ddckCKSrcOverlay;/* 38: CK for source overlay use*/
+	DDCOLORKEY	ddckCKSrcBlt;	/* 40: CK for source blt use*/
+
+	union {
+		DDPIXELFORMAT	ddpfPixelFormat;/* 48: pixel format description of the surface*/
+		DWORD 		dwFVF;	/* 48: vertex format description of vertex buffers */	
+	} DUMMYUNIONNAME4;
+	DDSCAPS2	ddsCaps;  /* 68: DDraw surface caps */
+	DWORD		dwTextureStage; /* 78: stage in multitexture cascade */
+} DDSURFACEDESC2,*LPDDSURFACEDESC2;
+
+/* DDCOLORCONTROL.dwFlags */
+#define DDCOLOR_BRIGHTNESS	0x00000001
+#define DDCOLOR_CONTRAST	0x00000002
+#define DDCOLOR_HUE		0x00000004
+#define DDCOLOR_SATURATION	0x00000008
+#define DDCOLOR_SHARPNESS	0x00000010
+#define DDCOLOR_GAMMA		0x00000020
+#define DDCOLOR_COLORENABLE	0x00000040
+
+typedef struct {
+	DWORD	dwSize;
+	DWORD	dwFlags;
+	LONG	lBrightness;
+	LONG	lContrast;
+	LONG	lHue;
+	LONG	lSaturation;
+	LONG	lSharpness;
+	LONG	lGamma;
+	LONG	lColorEnable;
+	DWORD	dwReserved1;
+} DDCOLORCONTROL,*LPDDCOLORCONTROL;
+
+typedef struct {
+	WORD	red[256];
+	WORD	green[256];
+	WORD	blue[256];
+} DDGAMMARAMP,*LPDDGAMMARAMP;
+
+typedef BOOL CALLBACK (*LPDDENUMCALLBACKA)(GUID *, LPSTR, LPSTR, LPVOID);
+typedef BOOL CALLBACK (*LPDDENUMCALLBACKW)(GUID *, LPWSTR, LPWSTR, LPVOID);
+DECL_WINELIB_TYPE_AW(LPDDENUMCALLBACK)
+
+typedef HRESULT CALLBACK (*LPDDENUMMODESCALLBACK)(LPDDSURFACEDESC, LPVOID);
+typedef HRESULT CALLBACK (*LPDDENUMMODESCALLBACK2)(LPDDSURFACEDESC2, LPVOID);
+typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK)(LPDIRECTDRAWSURFACE, LPDDSURFACEDESC, LPVOID);
+typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK2)(LPDIRECTDRAWSURFACE4, LPDDSURFACEDESC2, LPVOID);
+typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK7)(LPDIRECTDRAWSURFACE7, LPDDSURFACEDESC2, LPVOID);
+
+typedef BOOL CALLBACK (*LPDDENUMCALLBACKEXA)(GUID *, LPSTR, LPSTR, LPVOID, HMONITOR);
+typedef BOOL CALLBACK (*LPDDENUMCALLBACKEXW)(GUID *, LPWSTR, LPWSTR, LPVOID, HMONITOR);
+DECL_WINELIB_TYPE_AW(LPDDENUMCALLBACKEX)
+
+HRESULT WINAPI DirectDrawEnumerateExA( LPDDENUMCALLBACKEXA lpCallback, LPVOID lpContext, DWORD dwFlags);
+HRESULT WINAPI DirectDrawEnumerateExW( LPDDENUMCALLBACKEXW lpCallback, LPVOID lpContext, DWORD dwFlags);
+#define DirectDrawEnumerateEx WINELIB_NAME_AW(DirectDrawEnumerateEx)
+
+/* flags for DirectDrawEnumerateEx */
+#define DDENUM_ATTACHEDSECONDARYDEVICES	0x00000001
+#define DDENUM_DETACHEDSECONDARYDEVICES	0x00000002
+#define DDENUM_NONDISPLAYDEVICES	0x00000004
+
+/* flags for DirectDrawCreate or IDirectDraw::Initialize */
+#define DDCREATE_HARDWAREONLY	1L
+#define DDCREATE_EMULATIONONLY	2L
+
+typedef struct _DDBLTFX
+{
+    DWORD       dwSize;                         /* size of structure */
+    DWORD       dwDDFX;                         /* FX operations */
+    DWORD       dwROP;                          /* Win32 raster operations */
+    DWORD       dwDDROP;                        /* Raster operations new for DirectDraw */
+    DWORD       dwRotationAngle;                /* Rotation angle for blt */
+    DWORD       dwZBufferOpCode;                /* ZBuffer compares */
+    DWORD       dwZBufferLow;                   /* Low limit of Z buffer */
+    DWORD       dwZBufferHigh;                  /* High limit of Z buffer */
+    DWORD       dwZBufferBaseDest;              /* Destination base value */
+    DWORD       dwZDestConstBitDepth;           /* Bit depth used to specify Z constant for destination */
+    union
+    {
+        DWORD   dwZDestConst;                   /* Constant to use as Z buffer for dest */
+        LPDIRECTDRAWSURFACE lpDDSZBufferDest;   /* Surface to use as Z buffer for dest */
+    } DUMMYUNIONNAME1;
+    DWORD       dwZSrcConstBitDepth;            /* Bit depth used to specify Z constant for source */
+    union
+    {
+        DWORD   dwZSrcConst;                    /* Constant to use as Z buffer for src */
+        LPDIRECTDRAWSURFACE lpDDSZBufferSrc;    /* Surface to use as Z buffer for src */
+    } DUMMYUNIONNAME2;
+    DWORD       dwAlphaEdgeBlendBitDepth;       /* Bit depth used to specify constant for alpha edge blend */
+    DWORD       dwAlphaEdgeBlend;               /* Alpha for edge blending */
+    DWORD       dwReserved;
+    DWORD       dwAlphaDestConstBitDepth;       /* Bit depth used to specify alpha constant for destination */
+    union
+    {
+        DWORD   dwAlphaDestConst;               /* Constant to use as Alpha Channel */
+        LPDIRECTDRAWSURFACE lpDDSAlphaDest;     /* Surface to use as Alpha Channel */
+    } DUMMYUNIONNAME3;
+    DWORD       dwAlphaSrcConstBitDepth;        /* Bit depth used to specify alpha constant for source */
+    union
+    {
+        DWORD   dwAlphaSrcConst;                /* Constant to use as Alpha Channel */
+        LPDIRECTDRAWSURFACE lpDDSAlphaSrc;      /* Surface to use as Alpha Channel */
+    } DUMMYUNIONNAME4;
+    union
+    {
+        DWORD   dwFillColor;                    /* color in RGB or Palettized */
+        DWORD   dwFillDepth;                    /* depth value for z-buffer */
+	DWORD   dwFillPixel;			/* pixel val for RGBA or RGBZ */
+        LPDIRECTDRAWSURFACE lpDDSPattern;       /* Surface to use as pattern */
+    } DUMMYUNIONNAME5;
+    DDCOLORKEY  ddckDestColorkey;               /* DestColorkey override */
+    DDCOLORKEY  ddckSrcColorkey;                /* SrcColorkey override */
+} DDBLTFX,*LPDDBLTFX;
+
+/* dwDDFX */
+/* arithmetic stretching along y axis */
+#define DDBLTFX_ARITHSTRETCHY			0x00000001
+/* mirror on y axis */
+#define DDBLTFX_MIRRORLEFTRIGHT			0x00000002
+/* mirror on x axis */
+#define DDBLTFX_MIRRORUPDOWN			0x00000004
+/* do not tear */
+#define DDBLTFX_NOTEARING			0x00000008
+/* 180 degrees clockwise rotation */
+#define DDBLTFX_ROTATE180			0x00000010
+/* 270 degrees clockwise rotation */
+#define DDBLTFX_ROTATE270			0x00000020
+/* 90 degrees clockwise rotation */
+#define DDBLTFX_ROTATE90			0x00000040
+/* dwZBufferLow and dwZBufferHigh specify limits to the copied Z values */
+#define DDBLTFX_ZBUFFERRANGE			0x00000080
+/* add dwZBufferBaseDest to every source z value before compare */
+#define DDBLTFX_ZBUFFERBASEDEST			0x00000100
+
+typedef struct _DDOVERLAYFX
+{
+    DWORD       dwSize;                         /* size of structure */
+    DWORD       dwAlphaEdgeBlendBitDepth;       /* Bit depth used to specify constant for alpha edge blend */
+    DWORD       dwAlphaEdgeBlend;               /* Constant to use as alpha for edge blend */
+    DWORD       dwReserved;
+    DWORD       dwAlphaDestConstBitDepth;       /* Bit depth used to specify alpha constant for destination */
+    union
+    {
+        DWORD   dwAlphaDestConst;               /* Constant to use as alpha channel for dest */
+        LPDIRECTDRAWSURFACE lpDDSAlphaDest;     /* Surface to use as alpha channel for dest */
+    } DUMMYUNIONNAME1;
+    DWORD       dwAlphaSrcConstBitDepth;        /* Bit depth used to specify alpha constant for source */
+    union
+    {
+        DWORD   dwAlphaSrcConst;                /* Constant to use as alpha channel for src */
+        LPDIRECTDRAWSURFACE lpDDSAlphaSrc;      /* Surface to use as alpha channel for src */
+    } DUMMYUNIONNAME2;
+    DDCOLORKEY  dckDestColorkey;                /* DestColorkey override */
+    DDCOLORKEY  dckSrcColorkey;                 /* DestColorkey override */
+    DWORD       dwDDFX;                         /* Overlay FX */
+    DWORD       dwFlags;                        /* flags */
+} DDOVERLAYFX,*LPDDOVERLAYFX;
+
+typedef struct _DDBLTBATCH
+{
+    LPRECT		lprDest;
+    LPDIRECTDRAWSURFACE	lpDDSSrc;
+    LPRECT		lprSrc;
+    DWORD		dwFlags;
+    LPDDBLTFX		lpDDBltFx;
+} DDBLTBATCH,*LPDDBLTBATCH;
+
+#define MAX_DDDEVICEID_STRING          512
+
+typedef struct tagDDDEVICEIDENTIFIER {
+  char    szDriver[MAX_DDDEVICEID_STRING];
+  char    szDescription[MAX_DDDEVICEID_STRING];
+  LARGE_INTEGER  liDriverVersion;
+  DWORD   dwVendorId;
+  DWORD   dwDeviceId;
+  DWORD   dwSubSysId;
+  DWORD   dwRevision;
+  GUID    guidDeviceIdentifier;
+} DDDEVICEIDENTIFIER, * LPDDDEVICEIDENTIFIER;
+
+typedef struct tagDDDEVICEIDENTIFIER2 {
+  char    szDriver[MAX_DDDEVICEID_STRING];	/* user readable driver name */
+  char    szDescription[MAX_DDDEVICEID_STRING]; /* user readable description */
+  LARGE_INTEGER  liDriverVersion;		/* driver version */
+  DWORD   dwVendorId;				/* vendor ID, zero if unknown */
+  DWORD   dwDeviceId;				/* chipset ID, zero if unknown */
+  DWORD   dwSubSysId;				/* board ID, zero if unknown */
+  DWORD   dwRevision;				/* chipset version, zero if unknown */
+  GUID    guidDeviceIdentifier;			/* unique ID for this driver/chipset combination */
+  DWORD   dwWHQLLevel;				/* Windows Hardware Quality Lab certification level */
+} DDDEVICEIDENTIFIER2, * LPDDDEVICEIDENTIFIER2;
+
+/*****************************************************************************
+ * IDirectDrawPalette interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawPalette
+DECLARE_INTERFACE_(IDirectDrawPalette,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(GetCaps)(THIS_ LPDWORD lpdwCaps) PURE;
+    STDMETHOD(GetEntries)(THIS_ DWORD dwFlags, DWORD dwBase, DWORD dwNumEntries, LPPALETTEENTRY lpEntries) PURE;
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, DWORD dwFlags, LPPALETTEENTRY lpDDColorTable) PURE;
+    STDMETHOD(SetEntries)(THIS_ DWORD dwFlags, DWORD dwStartingEntry, DWORD dwCount, LPPALETTEENTRY lpEntries) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawPalette_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawPalette_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawPalette_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDrawPalette methods ***/
+#define IDirectDrawPalette_GetCaps(p,a)          ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawPalette_GetEntries(p,a,b,c,d) ICOM_CALL_(GetEntries,p,(p,a,b,c,d))
+#define IDirectDrawPalette_Initialize(p,a,b,c)   ICOM_CALL_(Initialize,p,(p,a,b,c))
+#define IDirectDrawPalette_SetEntries(p,a,b,c,d) ICOM_CALL_(SetEntries,p,(p,a,b,c,d))
+
+
+/*****************************************************************************
+ * IDirectDrawClipper interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawClipper
+DECLARE_INTERFACE_(IDirectDrawClipper,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(GetClipList)(THIS_ LPRECT lpRect, LPRGNDATA lpClipList, LPDWORD lpdwSize) PURE;
+    STDMETHOD(GetHWnd)(THIS_ HWND* lphWnd) PURE;
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, DWORD dwFlags) PURE;
+    STDMETHOD(IsClipListChanged)(THIS_ BOOL* lpbChanged) PURE;
+    STDMETHOD(SetClipList)(THIS_ LPRGNDATA lpClipList, DWORD dwFlags) PURE;
+    STDMETHOD(SetHWnd)(THIS_ DWORD dwFlags, HWND hWnd) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawClipper_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawClipper_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawClipper_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDrawClipper methods ***/
+#define IDirectDrawClipper_GetClipList(p,a,b,c)   ICOM_CALL_(GetClipList,p,(p,a,b,c))
+#define IDirectDrawClipper_GetHWnd(p,a)           ICOM_CALL_(GetHWnd,p,(p,a))
+#define IDirectDrawClipper_Initialize(p,a,b)      ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawClipper_IsClipListChanged(p,a) ICOM_CALL_(IsClipListChanged,p,(p,a))
+#define IDirectDrawClipper_SetClipList(p,a,b)     ICOM_CALL_(SetClipList,p,(p,a,b))
+#define IDirectDrawClipper_SetHWnd(p,a,b)         ICOM_CALL_(SetHWnd,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDraw interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDraw
+DECLARE_INTERFACE_(IDirectDraw,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(Compact)(THIS) PURE;
+    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE;
+    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE;
+    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc, LPDIRECTDRAWSURFACE* lplpDDSurface, IUnknown* pUnkOuter) PURE;
+    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE lpDDSurface, LPDIRECTDRAWSURFACE* lplpDupDDSurface) PURE;
+    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK lpEnumModesCallback) PURE;
+    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE;
+    STDMETHOD(FlipToGDISurface)(THIS) PURE;
+    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE;
+    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE;
+    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE;
+    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE* lplpGDIDDSurface) PURE;
+    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE;
+    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE;
+    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE;
+    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE;
+    STDMETHOD(RestoreDisplayMode)(THIS) PURE;
+    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE;
+    STDMETHOD(SetDisplayMode)(THIS_ DWORD, DWORD, DWORD) PURE;
+    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDraw_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDraw_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDraw_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDraw methods ***/
+#define IDirectDraw_Compact(p)                  ICOM_CALL_(Compact,p,(p))
+#define IDirectDraw_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
+#define IDirectDraw_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
+#define IDirectDraw_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
+#define IDirectDraw_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
+#define IDirectDraw_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
+#define IDirectDraw_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
+#define IDirectDraw_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
+#define IDirectDraw_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
+#define IDirectDraw_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
+#define IDirectDraw_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
+#define IDirectDraw_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
+#define IDirectDraw_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
+#define IDirectDraw_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
+#define IDirectDraw_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
+#define IDirectDraw_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
+#define IDirectDraw_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
+#define IDirectDraw_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
+#define IDirectDraw_SetDisplayMode(p,a,b,c)     ICOM_CALL_(SetDisplayMode,p,(p,a,b,c))
+#define IDirectDraw_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
+
+
+/* flags for Lock() */
+#define DDLOCK_SURFACEMEMORYPTR	0x00000000
+#define DDLOCK_WAIT		0x00000001
+#define DDLOCK_EVENT		0x00000002
+#define DDLOCK_READONLY		0x00000010
+#define DDLOCK_WRITEONLY	0x00000020
+#define DDLOCK_NOSYSLOCK	0x00000800
+
+
+/*****************************************************************************
+ * IDirectDraw2 interface
+ */
+/* Note: IDirectDraw2 cannot derive from IDirectDraw because the number of 
+ * arguments of SetDisplayMode has changed !
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDraw2
+DECLARE_INTERFACE_(IDirectDraw2,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(Compact)(THIS) PURE; 
+    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc, LPDIRECTDRAWSURFACE2* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSurface, LPDIRECTDRAWSURFACE2* lplpDupDDSurface) PURE; 
+    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK lpEnumModesCallback) PURE; 
+    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
+    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
+    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE2* lplpGDIDDSurface) PURE; 
+    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
+    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
+    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
+    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
+    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
+    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
+    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
+    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
+           
+    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDraw2_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDraw2_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDraw2_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDraw methods ***/
+#define IDirectDraw2_Compact(p)                  ICOM_CALL_(Compact,p,(p))
+#define IDirectDraw2_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
+#define IDirectDraw2_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
+#define IDirectDraw2_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
+#define IDirectDraw2_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
+#define IDirectDraw2_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
+#define IDirectDraw2_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
+#define IDirectDraw2_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
+#define IDirectDraw2_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
+#define IDirectDraw2_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
+#define IDirectDraw2_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
+#define IDirectDraw2_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
+#define IDirectDraw2_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
+#define IDirectDraw2_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
+#define IDirectDraw2_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
+#define IDirectDraw2_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
+#define IDirectDraw2_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
+#define IDirectDraw2_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
+#define IDirectDraw2_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
+#define IDirectDraw2_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
+/*** IDirectDraw2 methods ***/
+#define IDirectDraw2_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
+
+
+/*****************************************************************************
+ * IDirectDraw4 interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDraw4
+DECLARE_INTERFACE_(IDirectDraw4,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(Compact)(THIS) PURE; 
+    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc, LPDIRECTDRAWSURFACE4* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSurface, LPDIRECTDRAWSURFACE4* lplpDupDDSurface) PURE; 
+    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK2 lpEnumModesCallback) PURE; 
+    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK2 lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
+    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
+    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
+    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE4* lplpGDIDDSurface) PURE; 
+    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
+    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
+    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
+    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
+    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
+    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
+    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
+    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
+           
+    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS2 lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; 
+     
+    STDMETHOD(GetSurfaceFromDC)(THIS_ HDC , LPDIRECTDRAWSURFACE4* ) PURE; 
+    STDMETHOD(RestoreAllSurfaces)(THIS) PURE; 
+    STDMETHOD(TestCooperativeLevel)(THIS) PURE; 
+    STDMETHOD(GetDeviceIdentifier)(THIS_ LPDDDEVICEIDENTIFIER , DWORD ) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDraw4_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDraw4_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDraw4_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDraw methods ***/
+#define IDirectDraw4_Compact(p)                  ICOM_CALL_(Compact,p,(p))
+#define IDirectDraw4_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
+#define IDirectDraw4_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
+#define IDirectDraw4_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
+#define IDirectDraw4_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
+#define IDirectDraw4_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
+#define IDirectDraw4_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
+#define IDirectDraw4_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
+#define IDirectDraw4_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
+#define IDirectDraw4_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
+#define IDirectDraw4_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
+#define IDirectDraw4_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
+#define IDirectDraw4_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
+#define IDirectDraw4_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
+#define IDirectDraw4_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
+#define IDirectDraw4_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
+#define IDirectDraw4_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
+#define IDirectDraw4_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
+#define IDirectDraw4_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
+#define IDirectDraw4_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
+/*** IDirectDraw2 methods ***/
+#define IDirectDraw4_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
+/*** IDirectDraw4 methods ***/
+#define IDirectDraw4_GetSurfaceFromDC(p,a,b)    ICOM_CALL_(GetSurfaceFromDC,p,(p,a,b))
+#define IDirectDraw4_RestoreAllSurfaces(pc)     ICOM_CALL_(RestoreAllSurfaces,p,(p))
+#define IDirectDraw4_TestCooperativeLevel(p)    ICOM_CALL_(TestCooperativeLevel,p,(p))
+#define IDirectDraw4_GetDeviceIdentifier(p,a,b) ICOM_CALL_(GetDeviceIdentifier,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDraw7 interface
+ */
+/* Note: IDirectDraw7 cannot derive from IDirectDraw4; it is even documented
+ * as not interchangeable with earlier DirectDraw interfaces.
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDraw7
+DECLARE_INTERFACE_(IDirectDraw7,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(Compact)(THIS) PURE; 
+    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc, LPDIRECTDRAWSURFACE7* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSurface, LPDIRECTDRAWSURFACE7* lplpDupDDSurface) PURE; 
+    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK2 lpEnumModesCallback) PURE; 
+    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
+    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
+    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
+    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE7* lplpGDIDDSurface) PURE; 
+    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
+    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
+    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
+    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
+    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
+    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
+    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
+    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
+           
+    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS2 lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; 
+           
+    STDMETHOD(GetSurfaceFromDC)(THIS_ HDC , LPDIRECTDRAWSURFACE7* ) PURE; 
+    STDMETHOD(RestoreAllSurfaces)(THIS) PURE; 
+    STDMETHOD(TestCooperativeLevel)(THIS) PURE; 
+    STDMETHOD(GetDeviceIdentifier)(THIS_ LPDDDEVICEIDENTIFIER2 , DWORD ) PURE; 
+           
+    STDMETHOD(StartModeTest)(THIS_ LPSIZE , DWORD , DWORD ) PURE; 
+    STDMETHOD(EvaluateMode)(THIS_ DWORD , DWORD * ) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDraw7_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDraw7_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDraw7_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDraw methods ***/
+#define IDirectDraw7_Compact(p)                  ICOM_CALL_(Compact,p,(p))
+#define IDirectDraw7_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
+#define IDirectDraw7_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
+#define IDirectDraw7_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
+#define IDirectDraw7_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
+#define IDirectDraw7_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
+#define IDirectDraw7_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
+#define IDirectDraw7_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
+#define IDirectDraw7_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
+#define IDirectDraw7_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
+#define IDirectDraw7_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
+#define IDirectDraw7_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
+#define IDirectDraw7_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
+#define IDirectDraw7_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
+#define IDirectDraw7_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
+#define IDirectDraw7_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
+#define IDirectDraw7_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
+#define IDirectDraw7_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
+#define IDirectDraw7_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
+#define IDirectDraw7_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
+/*** added in IDirectDraw2 ***/
+#define IDirectDraw7_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
+/*** added in IDirectDraw4 ***/
+#define IDirectDraw7_GetSurfaceFromDC(p,a,b)    ICOM_CALL_(GetSurfaceFromDC,p,(p,a,b))
+#define IDirectDraw7_RestoreAllSurfaces(p)     ICOM_CALL_(RestoreAllSurfaces,p,(p))
+#define IDirectDraw7_TestCooperativeLevel(p)    ICOM_CALL_(TestCooperativeLevel,p,(p))
+#define IDirectDraw7_GetDeviceIdentifier(p,a,b) ICOM_CALL_(GetDeviceIdentifier,p,(p,a,b))
+/*** added in IDirectDraw 7 ***/
+#define IDirectDraw7_StartModeTest(p,a,b,c)     ICOM_CALL_(StartModeTest,p,(p,a,b,c))
+#define IDirectDraw7_EvaluateMode(p,a,b)        ICOM_CALL_(EvaluateMode,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface
+DECLARE_INTERFACE_(IDirectDrawSurface,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE lpDDSReference) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDrawSurface methods ***/
+#define IDirectDrawSurface_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface2 interface
+ */
+/* Cannot inherit from IDirectDrawSurface because the LPDIRECTDRAWSURFACE parameters 
+ * have been converted to LPDIRECTDRAWSURFACE2.
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface2
+DECLARE_INTERFACE_(IDirectDrawSurface2,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE2 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE2 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE2 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE2* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE2 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE2 lpDDSReference) PURE; 
+    /* added in v2 */ 
+    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
+    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface2_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface2_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface2_Release(p)            ICOM_CALL_(Release,p,(p))
+/*** IDirectDrawSurface methods (almost) ***/
+#define IDirectDrawSurface2_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface2_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface2_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface2_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface2_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface2_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface2_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface2_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface2_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface2_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface2_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface2_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface2_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface2_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface2_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface2_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface2_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface2_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface2_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface2_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface2_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface2_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface2_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface2_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface2_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface2_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface2_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface2_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface2_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface2_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface2_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface2_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface2_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+/*** IDirectDrawSurface2 methods ***/
+#define IDirectDrawSurface2_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
+#define IDirectDrawSurface2_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
+#define IDirectDrawSurface2_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface3 interface
+ */
+/* Cannot inherit from IDirectDrawSurface2 because the LPDIRECTDRAWSURFACE2 parameters 
+ * have been converted to LPDIRECTDRAWSURFACE3.
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface3
+DECLARE_INTERFACE_(IDirectDrawSurface3,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE3 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE3 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE3 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE3 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE3 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE3* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE3 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE3 lpDDSReference) PURE; 
+    /* added in v2 */ 
+    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
+    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
+    /* added in v3 */ 
+    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSD, DWORD dwFlags) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface3_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface3_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface3_Release(p)            ICOM_CALL_(Release,p,(p))
+/*** IDirectDrawSurface methods (almost) ***/
+#define IDirectDrawSurface3_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface3_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface3_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface3_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface3_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface3_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface3_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface3_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface3_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface3_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface3_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface3_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface3_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface3_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface3_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface3_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface3_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface3_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface3_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface3_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface3_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface3_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface3_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface3_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface3_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface3_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface3_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface3_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface3_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface3_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface3_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface3_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface3_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+/*** IDirectDrawSurface2 methods ***/
+#define IDirectDrawSurface3_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
+#define IDirectDrawSurface3_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
+#define IDirectDrawSurface3_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
+/*** IDirectDrawSurface3 methods ***/
+#define IDirectDrawSurface3_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface4 interface
+ */
+/* Cannot inherit from IDirectDrawSurface2 because DDSCAPS changed to DDSCAPS2.
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface4
+DECLARE_INTERFACE_(IDirectDrawSurface4,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE4 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE4 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE4 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS2 lpDDSCaps, LPDIRECTDRAWSURFACE4* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS2 lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPRECT lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE4 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE4 lpDDSReference) PURE; 
+    /* added in v2 */ 
+    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
+    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
+    /* added in v3 */ 
+    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSD, DWORD dwFlags) PURE; 
+    /* added in v4 */ 
+    STDMETHOD(SetPrivateData)(THIS_ REFGUID , LPVOID , DWORD , DWORD ) PURE; 
+    STDMETHOD(GetPrivateData)(THIS_ REFGUID , LPVOID , LPDWORD ) PURE; 
+    STDMETHOD(FreePrivateData)(THIS_ REFGUID ) PURE; 
+    STDMETHOD(GetUniquenessValue)(THIS_ LPDWORD ) PURE; 
+    STDMETHOD(ChangeUniquenessValue)(THIS) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface4_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface4_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface4_Release(p)            ICOM_CALL_(Release,p,(p))
+/*** IDirectDrawSurface (almost) methods ***/
+#define IDirectDrawSurface4_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface4_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface4_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface4_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface4_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface4_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface4_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface4_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface4_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface4_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface4_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface4_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface4_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface4_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface4_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface4_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface4_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface4_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface4_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface4_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface4_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface4_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface4_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface4_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface4_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface4_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface4_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface4_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface4_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface4_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface4_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface4_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface4_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+/*** IDirectDrawSurface2 methods ***/
+#define IDirectDrawSurface4_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
+#define IDirectDrawSurface4_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
+#define IDirectDrawSurface4_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
+/*** IDirectDrawSurface3 methods ***/
+#define IDirectDrawSurface4_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
+/*** IDirectDrawSurface4 methods ***/
+#define IDirectDrawSurface4_SetPrivateData(p,a,b,c,d) ICOM_CALL_(SetPrivateData,p,(p,a,b,c,d))
+#define IDirectDrawSurface4_GetPrivateData(p,a,b,c)   ICOM_CALL_(GetPrivateData,p,(p,a,b,c))
+#define IDirectDrawSurface4_FreePrivateData(p,a)      ICOM_CALL_(FreePrivateData,p,(p,a))
+#define IDirectDrawSurface4_GetUniquenessValue(p,a)   ICOM_CALL_(GetUniquenessValue,p,(p,a))
+#define IDirectDrawSurface4_ChangeUniquenessValue(p)  ICOM_CALL_(ChangeUniquenessValue,p,(p))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface7 interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface7
+DECLARE_INTERFACE_(IDirectDrawSurface7,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE7 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE7 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS2 lpDDSCaps, LPDIRECTDRAWSURFACE7* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS2 lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC2 lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPRECT lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE7 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE7 lpDDSReference) PURE; 
+    /* added in v2 */ 
+    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
+    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
+    /* added in v3 */ 
+    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC2 lpDDSD, DWORD dwFlags) PURE; 
+    /* added in v4 */ 
+    STDMETHOD(SetPrivateData)(THIS_ REFGUID , LPVOID , DWORD , DWORD ) PURE; 
+    STDMETHOD(GetPrivateData)(THIS_ REFGUID , LPVOID , LPDWORD ) PURE; 
+    STDMETHOD(FreePrivateData)(THIS_ REFGUID ) PURE; 
+    STDMETHOD(GetUniquenessValue)(THIS_ LPDWORD ) PURE; 
+    STDMETHOD(ChangeUniquenessValue)(THIS) PURE; 
+    /* added in v7 */ 
+    STDMETHOD(SetPriority)(THIS_ DWORD prio) PURE; 
+    STDMETHOD(GetPriority)(THIS_ LPDWORD prio) PURE; 
+    STDMETHOD(SetLOD)(THIS_ DWORD lod) PURE; 
+    STDMETHOD(GetLOD)(THIS_ LPDWORD lod) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface7_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface7_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface7_Release(p)            ICOM_CALL_(Release,p,(p))
+/*** IDirectDrawSurface (almost) methods ***/
+#define IDirectDrawSurface7_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface7_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface7_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface7_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface7_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface7_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface7_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface7_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface7_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface7_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface7_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface7_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface7_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface7_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface7_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface7_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface7_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface7_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface7_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface7_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface7_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface7_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface7_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface7_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface7_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface7_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface7_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface7_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface7_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface7_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface7_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface7_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface7_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+/*** IDirectDrawSurface2 methods ***/
+#define IDirectDrawSurface7_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
+#define IDirectDrawSurface7_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
+#define IDirectDrawSurface7_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
+/*** IDirectDrawSurface3 methods ***/
+#define IDirectDrawSurface7_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
+/*** IDirectDrawSurface4 methods ***/
+#define IDirectDrawSurface7_SetPrivateData(p,a,b,c,d) ICOM_CALL_(SetPrivateData,p,(p,a,b,c,d))
+#define IDirectDrawSurface7_GetPrivateData(p,a,b,c)   ICOM_CALL_(GetPrivateData,p,(p,a,b,c))
+#define IDirectDrawSurface7_FreePrivateData(p,a)      ICOM_CALL_(FreePrivateData,p,(p,a))
+#define IDirectDrawSurface7_GetUniquenessValue(p,a)   ICOM_CALL_(GetUniquenessValue,p,(p,a))
+#define IDirectDrawSurface7_ChangeUniquenessValue(p)  ICOM_CALL_(ChangeUniquenessValue,p,(p))
+/*** IDirectDrawSurface7 methods ***/
+#define IDirectDrawSurface7_SetPriority(p,a)          ICOM_CALL_(SetPriority,p,(p,a))
+#define IDirectDrawSurface7_GetPriority(p,a)          ICOM_CALL_(GetPriority,p,(p,a))
+#define IDirectDrawSurface7_SetLOD(p,a)               ICOM_CALL_(SetLOD,p,(p,a))
+#define IDirectDrawSurface7_GetLOD(p,a)               ICOM_CALL_(GetLOD,p,(p,a))
+
+/*****************************************************************************
+ * IDirectDrawColorControl interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawColorControl
+DECLARE_INTERFACE_(IDirectDrawColorControl,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(GetColorControls)(THIS_ LPDDCOLORCONTROL lpColorControl) PURE; 
+    STDMETHOD(SetColorControls)(THIS_ LPDDCOLORCONTROL lpColorControl) PURE;
+};
+
+	/*** IUnknown methods ***/
+#define IDirectDrawColorControl_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawColorControl_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawColorControl_Release(p)            ICOM_CALL_(Release,p,(p))
+	/*** IDirectDrawColorControl methods ***/
+#define IDirectDrawColorControl_GetColorControls(p,a) ICOM_CALL_(GetColorControls,p,(p,a))
+#define IDirectDrawColorControl_SetColorControls(p,a) ICOM_CALL_(SetColorControls,p,(p,a))
+
+/*****************************************************************************
+ * IDirectDrawGammaControl interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawGammaControl
+DECLARE_INTERFACE_(IDirectDrawGammaControl,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(GetGammaRamp)(THIS_ DWORD dwFlags, LPDDGAMMARAMP lpGammaRamp) PURE; 
+    STDMETHOD(SetGammaRamp)(THIS_ DWORD dwFlags, LPDDGAMMARAMP lpGammaRamp) PURE;
+};
+
+	/*** IUnknown methods ***/
+#define IDirectDrawGammaControl_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawGammaControl_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawGammaControl_Release(p)            ICOM_CALL_(Release,p,(p))
+	/*** IDirectDrawGammaControl methods ***/
+#define IDirectDrawGammaControl_GetGammaRamp(p,a,b)   ICOM_CALL_(GetGammaRamp,p,(p,a,b))
+#define IDirectDrawGammaControl_SetGammaRamp(p,a,b)   ICOM_CALL_(SetGammaRamp,p,(p,a,b))
+
+
+HRESULT WINAPI DirectDrawCreate(LPGUID,LPDIRECTDRAW*,LPUNKNOWN);
+HRESULT WINAPI DirectDrawCreateEx(LPGUID,LPVOID*,REFIID,LPUNKNOWN);
+HRESULT WINAPI DirectDrawEnumerateA(LPDDENUMCALLBACKA,LPVOID);
+HRESULT WINAPI DirectDrawEnumerateW(LPDDENUMCALLBACKW,LPVOID);
+#define DirectDrawEnumerate WINELIB_NAME_AW(DirectDrawEnumerate)
+HRESULT WINAPI DirectDrawCreateClipper(DWORD,LPDIRECTDRAWCLIPPER*,LPUNKNOWN);
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* defined(__cplusplus) */
+
+#endif /* __XWIN_DDRAW_H */
diff --git a/hw/xwin/win.h b/hw/xwin/win.h
new file mode 100644
index 0000000..3ab3249
--- /dev/null
+++ b/hw/xwin/win.h
@@ -0,0 +1,1453 @@
+/*
+ *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 NEED_EVENTS
+
+#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 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 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;
+
+#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;
+#ifdef SHAPE
+  SetShapeProcPtr			SetShape;
+#endif
+
+  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 CARD32			g_c32LastInputEventTime;
+extern DWORD			g_dwEnginesSupported;
+extern HINSTANCE		g_hInstance;
+extern int                      g_copyROP[];
+extern int                      g_patternROP[];
+extern const char *		g_pszQueryHost;
+
+
+/*
+ * 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)
+# if defined(XCSECURITY)  
+Bool
+winGenerateAuthorization (void);
+# endif
+#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);
+
+
+/*
+ * 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);
+
+#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);
+
+#ifdef SHAPE
+void
+winSetShapeRootless (WindowPtr pWindow);
+#endif
+
+
+/*
+ * winmultiwindowicons.c - Used by both multi-window and Win32Rootless
+ */
+
+HICON
+winXIconToHICON (WindowPtr pWin, int iconSize);
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * winmultiwindowshape.c
+ */
+
+# ifdef SHAPE
+void
+winReshapeMultiWindow (WindowPtr pWin);
+
+void
+winSetShapeMultiWindow (WindowPtr pWindow);
+
+void
+winUpdateRgnMultiWindow (WindowPtr pWindow);
+# endif
+#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/hw/xwin/winallpriv.c b/hw/xwin/winallpriv.c
new file mode 100644
index 0000000..21ccd9b
--- /dev/null
+++ b/hw/xwin/winallpriv.c
@@ -0,0 +1,172 @@
+/*
+ *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:	Keith Packard, MIT X Consortium
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/* See Porting Layer Definition - p. 58 */
+/*
+ * Allocate indexes for the privates that we use.
+ * Allocate memory directly for the screen privates.
+ * Reserve space in GCs and Pixmaps for our privates.
+ * Colormap privates are handled in winAllocateCmapPrivates ()
+ */
+
+Bool
+winAllocatePrivates (ScreenPtr pScreen)
+{
+  winPrivScreenPtr	pScreenPriv;
+
+#if CYGDEBUG
+  winDebug ("winAllocateScreenPrivates - g_ulServerGeneration: %d "
+	  "serverGeneration: %d\n",
+	  g_ulServerGeneration, serverGeneration);
+#endif
+
+  /* We need a new slot for our privates if the screen gen has changed */
+  if (g_ulServerGeneration != serverGeneration)
+    {
+      g_ulServerGeneration = serverGeneration;
+    }
+
+  /* Allocate memory for the screen private structure */
+  pScreenPriv = (winPrivScreenPtr) malloc (sizeof (winPrivScreenRec));
+  if (!pScreenPriv)
+    {
+      ErrorF ("winAllocateScreenPrivates - malloc () failed\n");
+      return FALSE;
+    }
+
+  /* Initialize the memory of the private structure */
+  ZeroMemory (pScreenPriv, sizeof (winPrivScreenRec));
+
+  /* Intialize private structure members */
+  pScreenPriv->fActive = TRUE;
+
+  /* Save the screen private pointer */
+  winSetScreenPriv (pScreen, pScreenPriv);
+
+  /* Reserve GC memory for our privates */
+  if (!dixRequestPrivate(g_iGCPrivateKey, sizeof (winPrivGCRec)))
+    {
+      ErrorF ("winAllocatePrivates - AllocateGCPrivate () failed\n");
+      return FALSE;
+    }
+
+  /* Reserve Pixmap memory for our privates */
+  if (!dixRequestPrivate(g_iPixmapPrivateKey, sizeof (winPrivPixmapRec)))
+    {
+      ErrorF ("winAllocatePrivates - AllocatePixmapPrivates () failed\n");
+      return FALSE;
+    }
+
+  /* Reserve Window memory for our privates */
+  if (!dixRequestPrivate(g_iWindowPrivateKey, sizeof (winPrivWinRec)))
+    {
+      ErrorF ("winAllocatePrivates () - AllocateWindowPrivates () failed\n");
+       return FALSE;
+     }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap privates may be allocated after the default colormap has
+ * already been created for some screens.  This initialization procedure
+ * is called for each default colormap that is found.
+ */
+
+Bool
+winInitCmapPrivates (ColormapPtr pcmap, int index)
+{
+#if CYGDEBUG
+  winDebug ("winInitCmapPrivates\n");
+#endif
+  
+  /*
+   * I see no way that this function can do anything useful
+   * with only a ColormapPtr.  We don't have the index for
+   * our dev privates yet, so we can't really initialize
+   * anything.  Perhaps I am misunderstanding the purpose
+   * of this function.
+   */
+  /*  That's definitely true.
+   *  I therefore changed the API and added the index as argument.
+   */
+  return TRUE;
+}
+
+
+/*
+ * Allocate memory for our colormap privates
+ */
+
+Bool
+winAllocateCmapPrivates (ColormapPtr pCmap)
+{
+  winPrivCmapPtr		pCmapPriv;
+  static unsigned long		s_ulPrivateGeneration = 0;
+
+#if CYGDEBUG
+  winDebug ("winAllocateCmapPrivates\n");
+#endif
+
+  /* Get a new privates index when the server generation changes */
+  if (s_ulPrivateGeneration != serverGeneration)
+    {
+      /* Save the new server generation */
+      s_ulPrivateGeneration = serverGeneration;
+    }
+
+  /* Allocate memory for our private structure */
+  pCmapPriv = (winPrivCmapPtr) malloc (sizeof (winPrivCmapRec));
+  if (!pCmapPriv)
+    {
+      ErrorF ("winAllocateCmapPrivates - malloc () failed\n");
+      return FALSE;
+    }
+
+  /* Initialize the memory of the private structure */
+  ZeroMemory (pCmapPriv, sizeof (winPrivCmapRec));
+
+  /* Save the cmap private pointer */
+  winSetCmapPriv (pCmap, pCmapPriv);
+
+#if CYGDEBUG
+  winDebug ("winAllocateCmapPrivates - Returning\n");
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/winauth.c b/hw/xwin/winauth.c
new file mode 100644
index 0000000..b57a35a
--- /dev/null
+++ b/hw/xwin/winauth.c
@@ -0,0 +1,131 @@
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#if defined(XCSECURITY)
+/*
+ *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
+ */
+
+#include "win.h"
+
+/* Includes for authorization */
+#include <X11/Xauth.h>
+#include "securitysrv.h"
+#include <X11/extensions/securstr.h>
+
+
+/*
+ * Constants
+ */
+
+#define AUTH_NAME	"MIT-MAGIC-COOKIE-1"
+
+
+/*
+ * Globals
+ */
+
+XID		g_authId = 0;
+unsigned int	g_uiAuthDataLen = 0;
+char		*g_pAuthData = NULL;
+
+
+/*
+ * 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;
+    }
+#if 0
+  else
+    {
+      ErrorF ("winGenerateAuthorization - GenerateAuthorization success!\n"
+	      "AuthDataLen: %d AuthData: %s\n",
+	      g_uiAuthDataLen, g_pAuthData);
+    }
+#endif
+  
+  /* 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;
+  
+  return TRUE;
+
+ auth_bailout:
+  if (fFreeAuth)
+    xfree (pAuth);
+  
+  return FALSE;
+}
+#endif
diff --git a/hw/xwin/winblock.c b/hw/xwin/winblock.c
new file mode 100644
index 0000000..abea60e
--- /dev/null
+++ b/hw/xwin/winblock.c
@@ -0,0 +1,106 @@
+/*
+ *Copyright (C) 2001-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"
+#include "winmsg.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern HWND			g_hDlgDepthChange;
+extern HWND			g_hDlgExit;
+extern HWND			g_hDlgAbout;
+
+
+/* See Porting Layer Definition - p. 6 */
+void
+winBlockHandler (int nScreen,
+		 pointer pBlockData,
+		 pointer pTimeout,
+		 pointer pReadMask)
+{
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  winScreenPriv((ScreenPtr)pBlockData);
+#endif
+  MSG			msg;
+#ifndef HAS_DEVWINDOWS
+  struct timeval **tvp = pTimeout;
+  if (*tvp != NULL) 
+  {
+    (*tvp)->tv_sec = 0;
+    (*tvp)->tv_usec = 100;
+  }
+#endif
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Signal threaded modules to begin */
+  if (pScreenPriv != NULL && !pScreenPriv->fServerStarted)
+    {
+      int		iReturn;
+      
+      winDebug ("winBlockHandler - Releasing pmServerStarted\n");
+
+      /* Flag that modules are to be started */
+      pScreenPriv->fServerStarted = TRUE;
+
+      /* Unlock the mutex for threaded modules */
+      iReturn = pthread_mutex_unlock (&pScreenPriv->pmServerStarted);
+      if (iReturn != 0)
+	{
+	  ErrorF ("winBlockHandler - pthread_mutex_unlock () failed: %d\n",
+		  iReturn);
+	  goto winBlockHandler_ProcessMessages; 
+	}
+
+      winDebug ("winBlockHandler - pthread_mutex_unlock () returned\n");
+    }
+
+winBlockHandler_ProcessMessages:
+#endif
+
+  /* Process all messages on our queue */
+  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+    {
+      if ((g_hDlgDepthChange == 0
+	   || !IsDialogMessage (g_hDlgDepthChange, &msg))
+	  && (g_hDlgExit == 0
+	      || !IsDialogMessage (g_hDlgExit, &msg))
+	  && (g_hDlgAbout == 0
+	      || !IsDialogMessage (g_hDlgAbout, &msg)))
+	{
+	  DispatchMessage (&msg);
+	}
+    }
+}
diff --git a/hw/xwin/winclip.c b/hw/xwin/winclip.c
new file mode 100644
index 0000000..aab7d63
--- /dev/null
+++ b/hw/xwin/winclip.c
@@ -0,0 +1,42 @@
+/*
+ *Copyright (C) 2001-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"
+
+/* Look at mfb/mfbclip.c for sample implementation */
+RegionPtr
+winPixmapToRegionNativeGDI (PixmapPtr pPix)
+{
+  ErrorF ("winPixmapToRegion()\n");
+  return NULL;
+}
diff --git a/hw/xwin/winclipboard.h b/hw/xwin/winclipboard.h
new file mode 100644
index 0000000..445c01b
--- /dev/null
+++ b/hw/xwin/winclipboard.h
@@ -0,0 +1,164 @@
+#ifndef _WINCLIPBOARD_H_
+#define _WINCLIPBOARD_H_
+/*
+ *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
+ */
+
+/* Standard library headers */
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#ifdef __CYGWIN__
+#include <sys/select.h>
+#else
+#include "Xwinsock.h"
+#define HAS_WINSOCK
+#endif
+#include <fcntl.h>
+#include <setjmp.h>
+#include <pthread.h>
+
+/* X headers */
+#include <X11/X.h>
+#include <X11/Xatom.h>
+/* NOTE: For some unknown reason, including Xproto.h solves
+ * tons of problems with including windows.h.  Unknowns reasons
+ * are usually bad, so someone should investigate this.
+ */
+#include <X11/Xproto.h>
+#include "X11/Xutil.h"
+#include "X11/Xlocale.h"
+
+/* Fixups to prevent collisions between Windows and X headers */
+#define ATOM			DWORD
+
+#ifndef __CYGWIN__
+#define sleep(x) Sleep (1000 * (x))
+#endif
+
+/* Windows headers */
+#ifndef XFree86Server
+#define XFree86Server
+#endif
+#include <windows.h>
+#undef XFree86Server
+
+
+/* Clipboard module constants */
+#define WIN_CLIPBOARD_WINDOW_CLASS		"xwinclip"
+#define WIN_CLIPBOARD_WINDOW_TITLE		"xwinclip"
+#ifdef HAS_DEVWINDOWS
+# define WIN_MSG_QUEUE_FNAME			"/dev/windows"
+#endif
+#define WIN_CONNECT_RETRIES			40
+#define WIN_CONNECT_DELAY			4
+#define WIN_JMP_OKAY				0
+#define WIN_JMP_ERROR_IO			2
+#define WIN_LOCAL_PROPERTY			"CYGX_CUT_BUFFER"
+#define WIN_XEVENTS_SUCCESS			0
+#define WIN_XEVENTS_SHUTDOWN			1
+#define WIN_XEVENTS_CONVERT			2
+#define WIN_XEVENTS_NOTIFY			3
+
+#define WM_WM_REINIT                           (WM_USER + 1)
+
+/*
+ * References to external symbols
+ */
+
+extern char *display;
+extern void ErrorF (const char* /*f*/, ...);
+extern void winDebug (const char *format, ...);
+extern void winErrorFVerb (int verb, const char *format, ...);
+
+
+/*
+ * winclipboardinit.c
+ */
+
+Bool
+winInitClipboard (void);
+
+HWND
+winClipboardCreateMessagingWindow (void);
+
+
+/*
+ * winclipboardtextconv.c
+ */
+
+void
+winClipboardDOStoUNIX (char *pszData, int iLength);
+
+void
+winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength);
+
+
+/*
+ * winclipboardthread.c
+ */
+
+void *
+winClipboardProc (void *);
+
+void
+winDeinitClipboard (void);
+
+
+/*
+ * winclipboardunicode.c
+ */
+
+Bool
+winClipboardDetectUnicodeSupport (void);
+
+
+/*
+ * winclipboardwndproc.c
+ */
+
+BOOL
+winClipboardFlushWindowsMessageQueue (HWND hwnd);
+
+LRESULT CALLBACK
+winClipboardWindowProc (HWND hwnd, UINT message, 
+			WPARAM wParam, LPARAM lParam);
+
+
+/*
+ * winclipboardxevents.c
+ */
+
+int
+winClipboardFlushXEvents (HWND hwnd,
+			  int iWindow,
+			  Display *pDisplay,
+			  Bool fUnicodeSupport);
+#endif
diff --git a/hw/xwin/winclipboardinit.c b/hw/xwin/winclipboardinit.c
new file mode 100644
index 0000000..6a0cbaf
--- /dev/null
+++ b/hw/xwin/winclipboardinit.c
@@ -0,0 +1,143 @@
+/*
+ *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 "dixstruct.h"
+#include "winclipboard.h"
+
+
+/*
+ * Local typedefs
+ */
+
+typedef int (*winDispatchProcPtr) (ClientPtr);
+
+DISPATCH_PROC(winProcSetSelectionOwner);
+
+
+/*
+ * References to external symbols
+ */
+
+extern pthread_t		g_ptClipboardProc;
+extern winDispatchProcPtr	winProcSetSelectionOwnerOrig;
+extern Bool			g_fClipboard;
+extern HWND			g_hwndClipboard;
+
+
+/*
+ * Intialize the Clipboard module
+ */
+
+Bool
+winInitClipboard ()
+{
+  ErrorF ("winInitClipboard ()\n");
+
+  /* Wrap some internal server functions */
+  if (ProcVector[X_SetSelectionOwner] != winProcSetSelectionOwner)
+    {
+      winProcSetSelectionOwnerOrig = ProcVector[X_SetSelectionOwner];
+      ProcVector[X_SetSelectionOwner] = winProcSetSelectionOwner;
+    }
+  
+  /* Spawn a thread for the Clipboard module */
+  if (pthread_create (&g_ptClipboardProc,
+		      NULL,
+		      winClipboardProc,
+		      NULL))
+    {
+      /* Bail if thread creation failed */
+      ErrorF ("winInitClipboard - pthread_create failed.\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Create the Windows window that we use to recieve Windows messages
+ */
+
+HWND
+winClipboardCreateMessagingWindow ()
+{
+  WNDCLASS			wc;
+  HWND				hwnd;
+
+  /* Setup our window class */
+  wc.style = CS_HREDRAW | CS_VREDRAW;
+  wc.lpfnWndProc = winClipboardWindowProc;
+  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_CLIPBOARD_WINDOW_CLASS;
+  RegisterClass (&wc);
+
+  /* Create the window */
+  hwnd = CreateWindowExA (0,			/* Extended styles */
+			  WIN_CLIPBOARD_WINDOW_CLASS,/* Class name */
+			  WIN_CLIPBOARD_WINDOW_TITLE,/* Window name */
+			  WS_OVERLAPPED,	/* Not visible anyway */
+			  CW_USEDEFAULT,	/* Horizontal position */
+			  CW_USEDEFAULT,	/* Vertical position */
+			  CW_USEDEFAULT,	/* Right edge */
+			  CW_USEDEFAULT,	/* Bottom edge */
+			  (HWND) NULL,		/* No parent or owner window */
+			  (HMENU) NULL,		/* No menu */
+			  GetModuleHandle (NULL),/* Instance handle */
+			  NULL);		/* Creation data */
+  assert (hwnd != NULL);
+
+  /* I'm not sure, but we may need to call this to start message processing */
+  ShowWindow (hwnd, SW_HIDE);
+
+  /* Similarly, we may need a call to this even though we don't paint */
+  UpdateWindow (hwnd);
+
+  return hwnd;
+}
+
+void
+winFixClipboardChain (void)
+{
+   if (g_fClipboard
+       && g_hwndClipboard)
+     {
+       PostMessage (g_hwndClipboard, WM_WM_REINIT, 0, 0);
+     }
+}
diff --git a/hw/xwin/winclipboardtextconv.c b/hw/xwin/winclipboardtextconv.c
new file mode 100644
index 0000000..fd2e696
--- /dev/null
+++ b/hw/xwin/winclipboardtextconv.c
@@ -0,0 +1,159 @@
+/*
+ *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"
+#include <stdio.h>
+#include <stdlib.h>
+
+void
+winClipboardDOStoUNIX (char *pszSrc, int iLength);
+void
+winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength);
+
+/*
+ * Convert \r\n to \n
+ *
+ * NOTE: This was heavily inspired by, Cygwin's
+ * winsup/cygwin/fhandler.cc/fhandler_base::read ()
+ */
+
+void
+winClipboardDOStoUNIX (char *pszSrc, int iLength)
+{
+  char			*pszDest = pszSrc;
+  char			*pszEnd = pszSrc + iLength;
+
+  /* Loop until the last character */
+  while (pszSrc < pszEnd)
+    {
+      /* Copy the current source character to current destination character */
+      *pszDest = *pszSrc;
+
+      /* Advance to the next source character */
+      pszSrc++;
+
+      /* Don't advance the destination character if we need to drop an \r */
+      if (*pszDest != '\r' || *pszSrc != '\n')
+	pszDest++;
+    }
+
+  /* Move the terminating null */
+  *pszDest = '\0';
+}
+
+
+/*
+ * Convert \n to \r\n
+ */
+
+void
+winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength)
+{
+  int			iNewlineCount = 0;
+  unsigned char		*pszSrc = *ppszData;
+  unsigned char		*pszEnd = pszSrc + iLength;
+  unsigned char		*pszDest = NULL, *pszDestBegin = NULL;
+
+#if 0
+  ErrorF ("UNIXtoDOS () - Original data:\n%s\n", *ppszData);
+#endif
+
+  /* Count \n characters without leading \r */
+  while (pszSrc < pszEnd)
+    {
+      /* Skip ahead two character if found set of \r\n */
+      if (*pszSrc == '\r' && pszSrc + 1 < pszEnd && *(pszSrc + 1) == '\n')
+	{
+	  pszSrc += 2;
+	  continue;
+	} 
+
+      /* Increment the count if found naked \n */
+      if (*pszSrc == '\n')
+	{
+	  iNewlineCount++;
+	}
+
+      pszSrc++;
+    }
+  
+  /* Return if no naked \n's */
+  if (iNewlineCount == 0)
+    return;
+
+  /* Allocate a new string */
+  pszDestBegin = pszDest = malloc (iLength + iNewlineCount + 1);
+
+  /* Set source pointer to beginning of data string */
+  pszSrc = *ppszData;
+
+  /* Loop through all characters in source string */
+  while (pszSrc < pszEnd)
+    {
+      /* Copy line endings that are already valid */
+      if (*pszSrc == '\r' && pszSrc + 1 < pszEnd && *(pszSrc + 1) == '\n')
+	{
+	  *pszDest = *pszSrc;
+	  *(pszDest + 1) = *(pszSrc + 1);
+	  pszDest += 2;
+	  pszSrc += 2;
+	  continue;
+	}
+
+      /* Add \r to naked \n's */
+      if (*pszSrc == '\n')
+	{
+	  *pszDest = '\r';
+	  *(pszDest + 1) = *pszSrc;
+	  pszDest += 2;
+	  pszSrc += 1;
+	  continue;
+	}
+
+      /* Copy normal characters */
+      *pszDest = *pszSrc;
+      pszSrc++;
+      pszDest++;
+    }
+
+  /* Put terminating null at end of new string */
+  *pszDest = '\0';
+
+  /* Swap string pointers */
+  free (*ppszData);
+  *ppszData = pszDestBegin;
+
+#if 0
+  ErrorF ("UNIXtoDOS () - Final string:\n%s\n", pszDestBegin);
+#endif
+}
diff --git a/hw/xwin/winclipboardthread.c b/hw/xwin/winclipboardthread.c
new file mode 100644
index 0000000..081abd5
--- /dev/null
+++ b/hw/xwin/winclipboardthread.c
@@ -0,0 +1,477 @@
+/*
+ *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 <sys/types.h>
+#include "winclipboard.h"
+#ifdef __CYGWIN__
+#include <errno.h>
+#endif
+#include "X11/Xauth.h"
+
+
+/*
+ * Constants
+ */
+
+#define AUTH_NAME	"MIT-MAGIC-COOKIE-1"
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUnicodeClipboard;
+extern unsigned long	serverGeneration;
+#if defined(XCSECURITY)
+extern unsigned int	g_uiAuthDataLen;
+extern char		*g_pAuthData;
+#endif
+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 - Locale not supported by X.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* 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);
+    }
+
+#if defined(XCSECURITY)
+  /* Use our generated cookie for authentication */
+  XSetAuthorization (AUTH_NAME,
+		     strlen (AUTH_NAME),
+		     g_pAuthData,
+		     g_uiAuthDataLen);
+#endif
+
+  /* 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
+
+  /* Select event types to watch */
+  if (XSelectInput (pDisplay,
+		    DefaultRootWindow (pDisplay),
+		    SubstructureNotifyMask |
+		    StructureNotifyMask |
+		    PropertyChangeMask) == BadWindow)
+    ErrorF ("winClipboardProc - XSelectInput generated BadWindow "
+	    "on RootWindow\n\n");
+
+  /* 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);
+    }
+
+  /* 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)
+	{
+	  ErrorF ("winClipboardProc - Could not set PRIMARY owner\n");
+	  pthread_exit (NULL);
+	}
+
+      /* CLIPBOARD */
+      iReturn = XSetSelectionOwner (pDisplay, atomClipboard,
+				    iWindow, CurrentTime);
+      if (iReturn == BadAtom || iReturn == BadWindow)
+	{
+	  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;
+}
diff --git a/hw/xwin/winclipboardunicode.c b/hw/xwin/winclipboardunicode.c
new file mode 100644
index 0000000..ba86915
--- /dev/null
+++ b/hw/xwin/winclipboardunicode.c
@@ -0,0 +1,69 @@
+/*
+ *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 "winclipboard.h"
+
+
+/*
+ * Determine whether we suport Unicode or not.
+ * NOTE: Currently, just check if we are on an NT-based platform or not.
+ */
+
+Bool
+winClipboardDetectUnicodeSupport (void)
+{
+  Bool			fReturn = FALSE;
+  OSVERSIONINFO		osvi = {0};
+  
+  /* Get operating system version information */
+  osvi.dwOSVersionInfoSize = sizeof (osvi);
+  GetVersionEx (&osvi);
+
+  /* Branch on platform ID */
+  switch (osvi.dwPlatformId)
+    {
+    case VER_PLATFORM_WIN32_NT:
+      /* Unicode supported on NT only */
+      ErrorF ("DetectUnicodeSupport - Windows NT/2000/XP\n");
+      fReturn = TRUE;
+      break;
+
+    case VER_PLATFORM_WIN32_WINDOWS:
+      /* Unicode is not supported on non-NT */
+      ErrorF ("DetectUnicodeSupport - Windows 95/98/Me\n");
+      fReturn = FALSE;
+      break;
+    }
+
+  return fReturn;
+}
diff --git a/hw/xwin/winclipboardwndproc.c b/hw/xwin/winclipboardwndproc.c
new file mode 100644
index 0000000..802a740
--- /dev/null
+++ b/hw/xwin/winclipboardwndproc.c
@@ -0,0 +1,622 @@
+/*
+ *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 <sys/types.h>
+#include <sys/time.h>
+#include "winclipboard.h"
+
+extern void		winFixClipboardChain();
+
+
+/*
+ * Constants
+ */
+
+#define WIN_CLIPBOARD_PROP	"cyg_clipboard_prop"
+#define WIN_POLL_TIMEOUT	1
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUseUnicode;
+extern Bool		g_fUnicodeSupport;
+extern void		*g_pClipboardDisplay;
+extern Window		g_iClipboardWindow;
+extern Atom		g_atomLastOwnedSelection;
+
+/* BPS - g_hwndClipboard needed for X app->Windows paste fix */
+extern HWND		g_hwndClipboard;
+
+/* 
+ * Local function prototypes
+ */
+
+static Bool
+winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay,
+			  Bool fUseUnicode, int iTimeoutSec);
+
+
+/*
+ * Process X events up to specified timeout
+ */
+
+static int
+winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay,
+			  Bool fUseUnicode, int iTimeoutSec)
+{
+  int			iConnNumber;
+  struct timeval	tv;
+  int			iReturn;
+  DWORD			dwStopTime = (GetTickCount () / 1000) + iTimeoutSec;
+
+  /* We need to ensure that all pending events are processed */
+  XSync (pDisplay, FALSE);
+
+  /* Get our connection number */
+  iConnNumber = ConnectionNumber (pDisplay);
+
+  /* Loop for X events */
+  while (1)
+    {
+      fd_set		fdsRead;
+
+      /* Setup the file descriptor set */
+      FD_ZERO (&fdsRead);
+      FD_SET (iConnNumber, &fdsRead);
+
+      /* Adjust timeout */
+      tv.tv_sec = dwStopTime - (GetTickCount () / 1000);
+      tv.tv_usec = 0;
+
+      /* Break out if no time left */
+      if (tv.tv_sec < 0)
+	return WIN_XEVENTS_SUCCESS;
+
+      /* Wait for a Windows event or an X event */
+      iReturn = select (iConnNumber + 1,/* Highest fds number */
+			&fdsRead,	/* Read mask */
+			NULL,		/* No write mask */
+			NULL,		/* No exception mask */
+			&tv);		/* No timeout */
+      if (iReturn <= 0)
+	{
+	  ErrorF ("winProcessXEventsTimeout - Call to select () failed: %d.  "
+		  "Bailing.\n", iReturn);
+	  break;
+	}
+
+      /* Branch on which descriptor became active */
+      if (FD_ISSET (iConnNumber, &fdsRead))
+	{
+	  /* Process X events */
+	  /* Exit when we see that server is shutting down */
+	  iReturn = winClipboardFlushXEvents (hwnd,
+					      iWindow,
+					      pDisplay,
+					      fUseUnicode);
+	  if (WIN_XEVENTS_NOTIFY == iReturn
+	      || WIN_XEVENTS_CONVERT == iReturn)
+	    {
+	      /* Bail out if convert or notify processed */
+	      return iReturn;
+	    }
+	}
+    }
+
+  return WIN_XEVENTS_SUCCESS;
+}
+
+
+/*
+ * Process a given Windows message
+ */
+
+/* BPS - Define our own message, which we'll post to ourselves to facilitate
+ * resetting the delayed rendering mechanism after each paste from X app to
+ * Windows app. TODO - Perhaps move to win.h with the other WM_USER messages.
+ */
+#define WM_USER_PASTE_COMPLETE		(WM_USER + 1003)
+
+LRESULT CALLBACK
+winClipboardWindowProc (HWND hwnd, UINT message, 
+			WPARAM wParam, LPARAM lParam)
+{
+  static HWND		s_hwndNextViewer;
+  static Bool		s_fCBCInitialized;
+
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_DESTROY:
+      {
+	winDebug ("winClipboardWindowProc - WM_DESTROY\n");
+
+	/* Remove ourselves from the clipboard chain */
+	ChangeClipboardChain (hwnd, s_hwndNextViewer);
+	
+	s_hwndNextViewer = NULL;
+
+	PostQuitMessage (0);
+      }
+      return 0;
+
+
+    case WM_CREATE:
+      {
+	HWND first, next;
+	DWORD error_code = 0;
+	winDebug ("winClipboardWindowProc - WM_CREATE\n");
+	
+	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
+	if (first == hwnd) return 0;			/* Make sure it's not us! */
+	/* Add ourselves to the clipboard viewer chain */
+	next = SetClipboardViewer (hwnd);
+	error_code = GetLastError();
+	if (SUCCEEDED(error_code) && (next == first))	/* SetClipboardViewer must have succeeded, and the handle */
+		s_hwndNextViewer = next;		/* it returned must have been the first window in the chain */
+	else
+		s_fCBCInitialized = FALSE;
+      }
+      return 0;
+
+
+    case WM_CHANGECBCHAIN:
+      {
+	winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: wParam(%x) "
+		  "lParam(%x) s_hwndNextViewer(%x)\n", 
+		  wParam, lParam, s_hwndNextViewer);
+
+	if ((HWND) wParam == s_hwndNextViewer)
+	  {
+	    s_hwndNextViewer = (HWND) lParam;
+	    if (s_hwndNextViewer == hwnd)
+	      {
+		s_hwndNextViewer = NULL;
+		winErrorFVerb (1, "winClipboardWindowProc - WM_CHANGECBCHAIN: "
+			       "attempted to set next window to ourselves.");
+	      }
+	  }
+	else if (s_hwndNextViewer)
+	  SendMessage (s_hwndNextViewer, message,
+		       wParam, lParam);
+
+      }
+      winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: Exit\n");
+      return 0;
+
+    case WM_WM_REINIT:
+      {
+        /* Ensure that we're in the clipboard chain.  Some apps,
+         * WinXP's remote desktop for one, don't play nice with the
+         * chain.  This message is called whenever we receive a
+         * WM_ACTIVATEAPP message to ensure that we continue to
+         * receive clipboard messages.
+	 *
+	 * It might be possible to detect if we're still in the chain
+	 * by calling SendMessage (GetClipboardViewer(),
+	 * WM_DRAWCLIPBOARD, 0, 0); and then seeing if we get the
+	 * WM_DRAWCLIPBOARD message.  That, however, might be more
+	 * expensive than just putting ourselves back into the chain.
+	 */
+
+	HWND first, next;
+	DWORD error_code = 0;
+	winDebug ("winClipboardWindowProc - WM_WM_REINIT: Enter\n");
+
+	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
+	if (first == hwnd) return 0;			/* Make sure it's not us! */
+	winDebug ("  WM_WM_REINIT: Replacing us(%x) with %x at head "
+		  "of chain\n", hwnd, s_hwndNextViewer);
+	s_fCBCInitialized = FALSE;
+	ChangeClipboardChain (hwnd, s_hwndNextViewer);
+	s_hwndNextViewer = NULL;
+	s_fCBCInitialized = FALSE;
+	winDebug ("  WM_WM_REINIT: Putting us back at head of chain.\n");
+	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
+	if (first == hwnd) return 0;			/* Make sure it's not us! */
+	next = SetClipboardViewer (hwnd);
+	error_code = GetLastError();
+	if (SUCCEEDED(error_code) && (next == first))	/* SetClipboardViewer must have succeeded, and the handle */
+		s_hwndNextViewer = next;		/* it returned must have been the first window in the chain */
+	else
+		s_fCBCInitialized = FALSE;
+      }
+      winDebug ("winClipboardWindowProc - WM_WM_REINIT: Exit\n");
+      return 0;
+
+
+    case WM_DRAWCLIPBOARD:
+      {
+	static Bool s_fProcessingDrawClipboard = FALSE;
+	Display	*pDisplay = g_pClipboardDisplay;
+	Window	iWindow = g_iClipboardWindow;
+	int	iReturn;
+
+	winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Enter\n");
+
+	/*
+	 * We've occasionally seen a loop in the clipboard chain.
+	 * Try and fix it on the first hint of recursion.
+	 */
+	if (! s_fProcessingDrawClipboard) 
+	  {
+	    s_fProcessingDrawClipboard = TRUE;
+	  }
+	else
+	  {
+	    /* Attempt to break the nesting by getting out of the chain, twice?, and then fix and bail */
+	    s_fCBCInitialized = FALSE;
+	    ChangeClipboardChain (hwnd, s_hwndNextViewer);
+	    winFixClipboardChain();
+	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+			   "Nested calls detected.  Re-initing.\n");
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+	    s_fProcessingDrawClipboard = FALSE;
+	    return 0;
+	  }
+
+	/* Bail on first message */
+	if (!s_fCBCInitialized)
+	  {
+	    s_fCBCInitialized = TRUE;
+	    s_fProcessingDrawClipboard = FALSE;
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+	    return 0;
+	  }
+
+	/*
+	 * NOTE: We cannot bail out when NULL == GetClipboardOwner ()
+	 * because some applications deal with the clipboard in a manner
+	 * that causes the clipboard owner to be NULL when they are in
+	 * fact taking ownership.  One example of this is the Win32
+	 * native compile of emacs.
+	 */
+	
+	/* Bail when we still own the clipboard */
+	if (hwnd == GetClipboardOwner ())
+	  {
+
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "We own the clipboard, returning.\n");
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+	    s_fProcessingDrawClipboard = FALSE;
+	    if (s_hwndNextViewer)
+		SendMessage (s_hwndNextViewer, message, wParam, lParam);
+	    return 0;
+	  }
+
+	/*
+	 * Do not take ownership of the X11 selections when something
+	 * other than CF_TEXT or CF_UNICODETEXT has been copied
+	 * into the Win32 clipboard.
+	 */
+	if (!IsClipboardFormatAvailable (CF_TEXT)
+	    && !IsClipboardFormatAvailable (CF_UNICODETEXT))
+	  {
+
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Clipboard does not contain CF_TEXT nor "
+		    "CF_UNICODETEXT.\n");
+
+	    /*
+	     * We need to make sure that the X Server has processed
+	     * previous XSetSelectionOwner messages.
+	     */
+	    XSync (pDisplay, FALSE);
+	    
+	    /* Release PRIMARY selection if owned */
+	    iReturn = XGetSelectionOwner (pDisplay, XA_PRIMARY);
+	    if (iReturn == g_iClipboardWindow)
+	      {
+		winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+			"PRIMARY selection is owned by us.\n");
+		XSetSelectionOwner (pDisplay,
+				    XA_PRIMARY,
+				    None,
+				    CurrentTime);
+	      }
+	    else if (BadWindow == iReturn || BadAtom == iReturn)
+	      winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		      "XGetSelection failed for PRIMARY: %d\n", iReturn);
+
+	    /* Release CLIPBOARD selection if owned */
+	    iReturn = XGetSelectionOwner (pDisplay,
+					  XInternAtom (pDisplay,
+						       "CLIPBOARD",
+						       False));
+	    if (iReturn == g_iClipboardWindow)
+	      {
+		winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+			"CLIPBOARD selection is owned by us.\n");
+		XSetSelectionOwner (pDisplay,
+				    XInternAtom (pDisplay,
+						 "CLIPBOARD",
+						 False),
+				    None,
+				    CurrentTime);
+	      }
+	    else if (BadWindow == iReturn || BadAtom == iReturn)
+	      winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		      "XGetSelection failed for CLIPBOARD: %d\n", iReturn);
+
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+	    s_fProcessingDrawClipboard = FALSE;
+	    if (s_hwndNextViewer)
+		SendMessage (s_hwndNextViewer, message, wParam, lParam);
+	    return 0;
+	  }
+
+	/* Reassert ownership of PRIMARY */	  
+	iReturn = XSetSelectionOwner (pDisplay,
+				      XA_PRIMARY,
+				      iWindow,
+				      CurrentTime);
+	if (iReturn == BadAtom || iReturn == BadWindow)
+	  {
+	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Could not reassert ownership of PRIMARY\n");
+	  }
+	else
+	  {
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Reasserted ownership of PRIMARY\n");
+	  }
+	
+	/* Reassert ownership of the CLIPBOARD */	  
+	iReturn = XSetSelectionOwner (pDisplay,
+				      XInternAtom (pDisplay,
+						   "CLIPBOARD",
+						   False),
+				      iWindow,
+				      CurrentTime);
+	if (iReturn == BadAtom || iReturn == BadWindow)
+	  {
+	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Could not reassert ownership of CLIPBOARD\n");
+	  }
+	else
+	  {
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Reasserted ownership of CLIPBOARD\n");
+	  }
+	
+	/* Flush the pending SetSelectionOwner event now */
+	XFlush (pDisplay);
+
+	s_fProcessingDrawClipboard = FALSE;
+      }
+      winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+      /* Pass the message on the next window in the clipboard viewer chain */
+      if (s_hwndNextViewer)
+	SendMessage (s_hwndNextViewer, message, wParam, lParam);
+      return 0;
+
+
+    case WM_DESTROYCLIPBOARD:
+      /*
+       * NOTE: Intentionally do nothing.
+       * Changes in the Win32 clipboard are handled by WM_DRAWCLIPBOARD
+       * above.  We only process this message to conform to the specs
+       * for delayed clipboard rendering in Win32.  You might think
+       * that we need to release ownership of the X11 selections, but
+       * we do not, because a WM_DRAWCLIPBOARD message will closely
+       * follow this message and reassert ownership of the X11
+       * selections, handling the issue for us.
+       */
+      return 0;
+
+
+    case WM_RENDERFORMAT:
+    case WM_RENDERALLFORMATS:
+      {
+	int	iReturn;
+	Display *pDisplay = g_pClipboardDisplay;
+	Window	iWindow = g_iClipboardWindow;
+	Bool	fConvertToUnicode;
+
+	winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Hello.\n");
+
+	/* Flag whether to convert to Unicode or not */
+	if (message == WM_RENDERALLFORMATS)
+	  fConvertToUnicode = FALSE;
+	else
+	  fConvertToUnicode = g_fUnicodeSupport && (CF_UNICODETEXT == wParam);
+
+	/* Request the selection contents */
+	iReturn = XConvertSelection (pDisplay,
+				     g_atomLastOwnedSelection,
+				     XInternAtom (pDisplay,
+						  "COMPOUND_TEXT", False),
+				     XInternAtom (pDisplay,
+						  "CYGX_CUT_BUFFER", False),
+				     iWindow,
+				     CurrentTime);
+	if (iReturn == BadAtom || iReturn == BadWindow)
+	  {
+	    winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMAT - "
+		    "XConvertSelection () failed\n");
+	    break;
+	  }
+
+	/* Special handling for WM_RENDERALLFORMATS */
+	if (message == WM_RENDERALLFORMATS)
+	  {
+	    /* We must open and empty the clipboard */
+
+	    /* Close clipboard if we have it open already */
+	    if (GetOpenClipboardWindow () == hwnd)
+	      {
+		CloseClipboard ();
+	      }	    
+
+	    if (!OpenClipboard (hwnd))
+	      {
+		winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
+			"OpenClipboard () failed: %08x\n",
+			GetLastError ());
+		break;
+	      }
+	    
+	    if (!EmptyClipboard ())
+	      {
+		winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
+			"EmptyClipboard () failed: %08x\n",
+		      GetLastError ());
+		break;
+	      }
+	  }
+
+	/* Process the SelectionNotify event */
+	iReturn = winProcessXEventsTimeout (hwnd,
+					    iWindow,
+					    pDisplay,
+					    fConvertToUnicode,
+					    WIN_POLL_TIMEOUT);
+	if (WIN_XEVENTS_CONVERT == iReturn)
+	  {
+	    /*
+	     * The selection was offered for conversion first, so we have
+	     * to process a second SelectionNotify event to get the actual
+	     * data in the selection.
+	     */
+	    iReturn = winProcessXEventsTimeout (hwnd,
+						iWindow,
+						pDisplay,
+						fConvertToUnicode,
+						WIN_POLL_TIMEOUT);
+	  }
+	
+	/*
+	 * The last of the up-to two calls to winProcessXEventsTimeout
+	 * from above had better have seen a notify event, or else we
+	 * are dealing with a buggy or old X11 app.  In these cases we
+	 * have to paste some fake data to the Win32 clipboard to
+	 * satisfy the requirement that we write something to it.
+	 */
+	if (WIN_XEVENTS_NOTIFY != iReturn)
+	  {
+	    /* Paste no data, to satisfy required call to SetClipboardData */
+	    if (g_fUnicodeSupport)
+	      SetClipboardData (CF_UNICODETEXT, NULL);
+	    SetClipboardData (CF_TEXT, NULL);
+	  }
+
+	/* BPS - Post ourselves a user message whose handler will reset the
+	 * delayed rendering mechanism after the paste is complete. This is
+	 * necessary because calling SetClipboardData() with a NULL argument
+	 * here will cause the data we just put on the clipboard to be lost!
+	 */
+	PostMessage(g_hwndClipboard, WM_USER_PASTE_COMPLETE, 0, 0);
+
+	/* Special handling for WM_RENDERALLFORMATS */
+	if (message == WM_RENDERALLFORMATS)
+	  {
+	    /* We must close the clipboard */
+	    
+	    if (!CloseClipboard ())
+	      {
+	      winErrorFVerb (1, "winClipboardWindowProc - WM_RENDERALLFORMATS - "
+		      "CloseClipboard () failed: %08x\n",
+		      GetLastError ());
+	      break;
+	      }
+	  }
+
+	winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Returning.\n");
+	return 0;
+      }
+    /* BPS - This WM_USER message is posted by us. It gives us the opportunity
+     * to reset the delayed rendering mechanism after each and every paste
+     * from an X app to a Windows app. Without such a mechanism, subsequent
+     * changes of selection in the X app owning the selection are not
+     * reflected in pastes into Windows apps, since Windows won't send us the
+     * WM_RENDERFORMAT message unless someone has set changed data (or NULL)
+     * on the clipboard. */
+    case WM_USER_PASTE_COMPLETE:
+      {
+	if (hwnd != GetClipboardOwner ())
+	  /* In case we've lost the selection since posting the message */
+	  return 0;
+	winDebug ("winClipboardWindowProc - WM_USER_PASTE_COMPLETE\n");
+
+	/* Set up for another delayed rendering callback */
+	OpenClipboard (g_hwndClipboard);
+
+	/* Take ownership of the Windows clipboard */
+	EmptyClipboard ();
+
+	/* Advertise Unicode if we support it */
+	if (g_fUnicodeSupport)
+	  SetClipboardData (CF_UNICODETEXT, NULL);
+
+	/* Always advertise regular text */
+	SetClipboardData (CF_TEXT, NULL);
+
+	/* Release the clipboard */
+	CloseClipboard ();
+      }
+      return 0;
+    }
+
+  /* Let Windows perform default processing for unhandled messages */
+  return DefWindowProc (hwnd, message, wParam, lParam);
+}
+
+
+/*
+ * Process any pending Windows messages
+ */
+
+BOOL
+winClipboardFlushWindowsMessageQueue (HWND hwnd)
+{
+  MSG			msg;
+
+  /* Flush the messaging window queue */
+  /* NOTE: Do not pass the hwnd of our messaging window to PeekMessage,
+   * as this will filter out many non-window-specific messages that
+   * are sent to our thread, such as WM_QUIT.
+   */
+  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+    {
+      /* Dispatch the message if not WM_QUIT */
+      if (msg.message == WM_QUIT)
+	return FALSE;
+      else
+	DispatchMessage (&msg);
+    }
+  
+  return TRUE;
+}
diff --git a/hw/xwin/winclipboardwrappers.c b/hw/xwin/winclipboardwrappers.c
new file mode 100755
index 0000000..2cfe0ff
--- /dev/null
+++ b/hw/xwin/winclipboardwrappers.c
@@ -0,0 +1,541 @@
+/*
+ *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"
+#include "dixstruct.h"
+#include <X11/Xatom.h>
+
+
+/*
+ * Constants
+ */
+
+#define CLIP_NUM_SELECTIONS		2
+#define CLIP_OWN_PRIMARY		0
+#define CLIP_OWN_CLIPBOARD		1
+
+
+/*
+ * Local function prototypes
+ */
+
+DISPATCH_PROC(winProcEstablishConnection);
+DISPATCH_PROC(winProcQueryTree);
+DISPATCH_PROC(winProcSetSelectionOwner);
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUnicodeSupport;
+extern int		g_iNumScreens;
+extern unsigned int	g_uiAuthDataLen;
+extern char		*g_pAuthData;
+extern Bool		g_fXdmcpEnabled;
+extern Bool		g_fClipboardLaunched;
+extern Bool		g_fClipboardStarted;
+extern Bool		g_fClipboard;
+extern Window		g_iClipboardWindow;
+extern Atom		g_atomLastOwnedSelection;
+extern HWND		g_hwndClipboard;
+
+extern winDispatchProcPtr	winProcEstablishConnectionOrig;
+extern winDispatchProcPtr	winProcQueryTreeOrig;
+extern winDispatchProcPtr	winProcSetSelectionOwnerOrig;
+
+
+/*
+ * Wrapper for internal QueryTree function.
+ * Hides the clipboard client when it is the only client remaining.
+ */
+
+int
+winProcQueryTree (ClientPtr client)
+{
+  int			iReturn;
+
+  /*
+   * This procedure is only used for initialization.
+   * We can unwrap the original procedure at this point
+   * so that this function is no longer called until the
+   * server resets and the function is wrapped again.
+   */
+  ProcVector[X_QueryTree] = winProcQueryTreeOrig;
+
+  /*
+   * Call original function and bail if it fails.
+   * NOTE: We must do this first, since we need XdmcpOpenDisplay
+   * to be called before we initialize our clipboard client.
+   */
+  iReturn = (*winProcQueryTreeOrig) (client);
+  if (iReturn != 0)
+    {
+      ErrorF ("winProcQueryTree - ProcQueryTree failed, bailing.\n");
+      return iReturn;
+    }
+
+  /* Make errors more obvious */
+  winProcQueryTreeOrig = NULL;
+
+  /* Do nothing if clipboard is not enabled */
+  if (!g_fClipboard)
+    {
+      ErrorF ("winProcQueryTree - Clipboard is not enabled, "
+	      "returning.\n");
+      return iReturn;
+    }
+
+  /* If the clipboard client has already been started, abort */
+  if (g_fClipboardLaunched)
+    {
+      ErrorF ("winProcQueryTree - Clipboard client already "
+	      "launched, returning.\n");
+      return iReturn;
+    }
+
+  /* Startup the clipboard client if clipboard mode is being used */
+  if (g_fXdmcpEnabled && g_fClipboard)
+    {
+      /*
+       * NOTE: The clipboard client is started here for a reason:
+       * 1) Assume you are using XDMCP (e.g. XWin -query %hostname%)
+       * 2) If the clipboard client attaches during X Server startup,
+       *    then it becomes the "magic client" that causes the X Server
+       *    to reset if it exits.
+       * 3) XDMCP calls KillAllClients when it starts up.
+       * 4) The clipboard client is a client, so it is killed.
+       * 5) The clipboard client is the "magic client", so the X Server
+       *    resets itself.
+       * 6) This repeats ad infinitum.
+       * 7) We avoid this by waiting until at least one client (could
+       *    be XDM, could be another client) connects, which makes it
+       *    almost certain that the clipboard client will not connect
+       *    until after XDM when using XDMCP.
+       * 8) Unfortunately, there is another problem.
+       * 9) XDM walks the list of windows with XQueryTree,
+       *    killing any client it finds with a window.
+       * 10)Thus, when using XDMCP we wait until the first call
+       *    to ProcQueryTree before we startup the clipboard client.
+       *    This should prevent XDM from finding the clipboard client,
+       *    since it has not yet created a window.
+       * 11)Startup when not using XDMCP is handled in
+       *    winProcEstablishConnection.
+       */
+      
+      /* Create the clipboard client thread */
+      if (!winInitClipboard ())
+	{
+	  ErrorF ("winProcQueryTree - winClipboardInit "
+		  "failed.\n");
+	  return iReturn;
+	}
+      
+      ErrorF ("winProcQueryTree - winInitClipboard returned.\n");
+    }
+  
+  /* Flag that clipboard client has been launched */
+  g_fClipboardLaunched = TRUE;
+
+  return iReturn;
+}
+
+
+/*
+ * Wrapper for internal EstablishConnection function.
+ * Initializes internal clients that must not be started until
+ * an external client has connected.
+ */
+
+int
+winProcEstablishConnection (ClientPtr client)
+{
+  int			iReturn;
+  static int		s_iCallCount = 0;
+  static unsigned long	s_ulServerGeneration = 0;
+
+  ErrorF ("winProcEstablishConnection - Hello\n");
+
+  /* Do nothing if clipboard is not enabled */
+  if (!g_fClipboard)
+    {
+      ErrorF ("winProcEstablishConnection - Clipboard is not enabled, "
+	      "returning.\n");
+      
+      /* Unwrap the original function, call it, and return */
+      InitialVector[2] = winProcEstablishConnectionOrig;
+      iReturn = (*winProcEstablishConnectionOrig) (client);
+      winProcEstablishConnectionOrig = NULL;
+      return iReturn;
+    }
+
+  /* Watch for server reset */
+  if (s_ulServerGeneration != serverGeneration)
+    {
+      /* Save new generation number */
+      s_ulServerGeneration = serverGeneration;
+
+      /* Reset call count */
+      s_iCallCount = 0;
+    }
+
+  /* Increment call count */
+  ++s_iCallCount;
+
+  /* Wait for second call when Xdmcp is enabled */
+  if (g_fXdmcpEnabled
+      && !g_fClipboardLaunched
+      && s_iCallCount < 4)
+    {
+      ErrorF ("winProcEstablishConnection - Xdmcp enabled, waiting to "
+	      "start clipboard client until fourth call.\n");
+      return (*winProcEstablishConnectionOrig) (client);
+    }
+
+  /*
+   * This procedure is only used for initialization.
+   * We can unwrap the original procedure at this point
+   * so that this function is no longer called until the
+   * server resets and the function is wrapped again.
+   */
+  InitialVector[2] = winProcEstablishConnectionOrig;
+
+  /*
+   * Call original function and bail if it fails.
+   * NOTE: We must do this first, since we need XdmcpOpenDisplay
+   * to be called before we initialize our clipboard client.
+   */
+  iReturn = (*winProcEstablishConnectionOrig) (client);
+  if (iReturn != 0)
+    {
+      ErrorF ("winProcEstablishConnection - ProcEstablishConnection "
+	      "failed, bailing.\n");
+      return iReturn;
+    }
+
+  /* Clear original function pointer */
+  winProcEstablishConnectionOrig = NULL;
+
+  /* If the clipboard client has already been started, abort */
+  if (g_fClipboardLaunched)
+    {
+      ErrorF ("winProcEstablishConnection - Clipboard client already "
+	      "launched, returning.\n");
+      return iReturn;
+    }
+
+  /* Startup the clipboard client if clipboard mode is being used */
+  if (g_fClipboard)
+    {
+      /*
+       * NOTE: The clipboard client is started here for a reason:
+       * 1) Assume you are using XDMCP (e.g. XWin -query %hostname%)
+       * 2) If the clipboard client attaches during X Server startup,
+       *    then it becomes the "magic client" that causes the X Server
+       *    to reset if it exits.
+       * 3) XDMCP calls KillAllClients when it starts up.
+       * 4) The clipboard client is a client, so it is killed.
+       * 5) The clipboard client is the "magic client", so the X Server
+       *    resets itself.
+       * 6) This repeats ad infinitum.
+       * 7) We avoid this by waiting until at least one client (could
+       *    be XDM, could be another client) connects, which makes it
+       *    almost certain that the clipboard client will not connect
+       *    until after XDM when using XDMCP.
+       * 8) Unfortunately, there is another problem.
+       * 9) XDM walks the list of windows with XQueryTree,
+       *    killing any client it finds with a window.
+       * 10)Thus, when using XDMCP we wait until the second call
+       *    to ProcEstablishCeonnection before we startup the clipboard
+       *    client.  This should prevent XDM from finding the clipboard
+       *    client, since it has not yet created a window.
+       */
+      
+      /* Create the clipboard client thread */
+      if (!winInitClipboard ())
+	{
+	  ErrorF ("winProcEstablishConnection - winClipboardInit "
+		  "failed.\n");
+	  return iReturn;
+	}
+      
+      ErrorF ("winProcEstablishConnection - winInitClipboard returned.\n");
+    }
+  
+  /* Flag that clipboard client has been launched */
+  g_fClipboardLaunched = TRUE;
+
+  return iReturn;
+}
+
+
+/*
+ * Wrapper for internal SetSelectionOwner function.
+ * Grabs ownership of Windows clipboard when X11 clipboard owner changes.
+ */
+
+int
+winProcSetSelectionOwner (ClientPtr client)
+{
+  int			i;
+  DrawablePtr		pDrawable;
+  WindowPtr		pWindow = None;
+  Bool			fOwnedToNotOwned = FALSE;
+  static Window		s_iOwners[CLIP_NUM_SELECTIONS] = {None};
+  static unsigned long	s_ulServerGeneration = 0;
+  REQUEST(xSetSelectionOwnerReq);
+  
+  REQUEST_SIZE_MATCH(xSetSelectionOwnerReq);
+
+#if 0
+  ErrorF ("winProcSetSelectionOwner - Hello.\n");
+#endif
+
+  /* Watch for server reset */
+  if (s_ulServerGeneration != serverGeneration)
+    {
+      /* Save new generation number */
+      s_ulServerGeneration = serverGeneration;
+
+      /* Initialize static variables */
+      for (i = 0; i < CLIP_NUM_SELECTIONS; ++i)
+	s_iOwners[i] = None;
+    }
+
+  /* Abort if clipboard not completely initialized yet */
+  if (!g_fClipboardStarted)
+    {
+      ErrorF ("winProcSetSelectionOwner - Clipboard not yet started, "
+	      "aborting.\n");
+      goto winProcSetSelectionOwner_Done;
+    }
+  
+  /* Grab window if we have one */
+  if (None != stuff->window)
+    {
+      /* Grab the Window from the request */
+      int rc = dixLookupWindow(&pWindow, stuff->window, client, DixReadAccess);
+      if (rc != Success) {
+	  ErrorF ("winProcSetSelectionOwner - Found BadWindow, aborting.\n");
+	  goto winProcSetSelectionOwner_Done;
+      }
+    }
+
+  /* Now we either have a valid window or None */
+
+  /* Save selection owners for monitored selections, ignore other selections */
+  if (XA_PRIMARY == stuff->selection)
+    {
+      /* Look for owned -> not owned transition */
+      if (None == stuff->window
+	  && None != s_iOwners[CLIP_OWN_PRIMARY])
+	{
+	  fOwnedToNotOwned = TRUE;
+
+#if 0
+	  ErrorF ("winProcSetSelectionOwner - PRIMARY - Going from "
+		  "owned to not owned.\n");
+#endif
+
+	  /* Adjust last owned selection */
+	  if (None != s_iOwners[CLIP_OWN_CLIPBOARD])
+	    g_atomLastOwnedSelection = MakeAtom ("CLIPBOARD", 9, TRUE);
+	  else
+	    g_atomLastOwnedSelection = None;
+	}
+      
+      /* Save new selection owner or None */
+      s_iOwners[CLIP_OWN_PRIMARY] = stuff->window;
+
+#if 0
+      ErrorF ("winProcSetSelectionOwner - PRIMARY - Now owned by: %d\n",
+	      stuff->window);
+#endif
+    }
+  else if (MakeAtom ("CLIPBOARD", 9, TRUE) == stuff->selection)
+    {
+      /* Look for owned -> not owned transition */
+      if (None == stuff->window
+	  && None != s_iOwners[CLIP_OWN_CLIPBOARD])
+	{
+	  fOwnedToNotOwned = TRUE;
+	  
+#if 0
+	  ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Going from "
+		  "owned to not owned.\n");
+#endif
+
+	  /* Adjust last owned selection */
+	  if (None != s_iOwners[CLIP_OWN_PRIMARY])
+	    g_atomLastOwnedSelection = XA_PRIMARY;
+	  else
+	    g_atomLastOwnedSelection = None;
+	}
+      
+      /* Save new selection owner or None */
+      s_iOwners[CLIP_OWN_CLIPBOARD] = stuff->window;
+
+#if 0
+      ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Now owned by: %d\n",
+	      stuff->window);
+#endif
+    }
+  else
+    goto winProcSetSelectionOwner_Done;
+
+  /*
+   * At this point, if one of the selections is still owned by the 
+   * clipboard manager then it should be marked as unowned since
+   * we will be taking ownership of the Win32 clipboard.
+   */
+  if (g_iClipboardWindow == s_iOwners[CLIP_OWN_PRIMARY])
+    s_iOwners[CLIP_OWN_PRIMARY] = None;
+  if (g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD])
+    s_iOwners[CLIP_OWN_CLIPBOARD] = None;
+
+  /*
+   * Handle case when selection is being disowned,
+   * WM_DRAWCLIPBOARD did not do the disowning,
+   * both monitored selections are no longer owned,
+   * an owned to not owned transition was detected,
+   * and we currently own the Win32 clipboard.
+   */
+  if (None == stuff->window
+      && (None == s_iOwners[CLIP_OWN_PRIMARY]
+	  || g_iClipboardWindow == s_iOwners[CLIP_OWN_PRIMARY])
+      && (None == s_iOwners[CLIP_OWN_CLIPBOARD]
+	  || g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD])
+      && fOwnedToNotOwned
+      && g_hwndClipboard != NULL
+      && g_hwndClipboard == GetClipboardOwner ())
+    {
+#if 0
+      ErrorF ("winProcSetSelectionOwner - We currently own the "
+	      "clipboard and neither the PRIMARY nor the CLIPBOARD "
+	      "selections are owned, releasing ownership of Win32 "
+	      "clipboard.\n");
+#endif
+      
+      /* Release ownership of the Windows clipboard */
+      OpenClipboard (NULL);
+      EmptyClipboard ();
+      CloseClipboard ();
+
+      /* Clear X selection ownership (might still be marked as us owning) */
+      s_iOwners[CLIP_OWN_PRIMARY] = None;
+      s_iOwners[CLIP_OWN_CLIPBOARD] = None;
+      
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Abort if no window at this point */
+  if (None == stuff->window)
+    {
+#if 0
+      ErrorF ("winProcSetSelectionOwner - No window, returning.\n");
+#endif
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Abort if invalid selection */
+  if (!ValidAtom (stuff->selection))
+    {
+      ErrorF ("winProcSetSelectionOwner - Found BadAtom, aborting.\n");
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Cast Window to Drawable */
+  pDrawable = (DrawablePtr) pWindow;
+  
+  /* Abort if clipboard manager is owning the selection */
+  if (pDrawable->id == g_iClipboardWindow)
+    {
+#if 0
+      ErrorF ("winProcSetSelectionOwner - We changed ownership, "
+	      "aborting.\n");
+#endif
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Abort if root window is taking ownership */
+  if (pDrawable->id == 0)
+    {
+      ErrorF ("winProcSetSelectionOwner - Root window taking ownership, "
+	      "aborting\n");
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Close clipboard if we have it open already */
+  if (GetOpenClipboardWindow () == g_hwndClipboard)
+    {
+      CloseClipboard ();
+    }
+
+  /* Access the Windows clipboard */
+  if (!OpenClipboard (g_hwndClipboard))
+    {
+      ErrorF ("winProcSetSelectionOwner - OpenClipboard () failed: %08x\n",
+	      (int) GetLastError ());
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Take ownership of the Windows clipboard */
+  if (!EmptyClipboard ())
+    {
+      ErrorF ("winProcSetSelectionOwner - EmptyClipboard () failed: %08x\n",
+	      (int) GetLastError ());
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Advertise Unicode if we support it */
+  if (g_fUnicodeSupport)
+    SetClipboardData (CF_UNICODETEXT, NULL);
+
+  /* Always advertise regular text */
+  SetClipboardData (CF_TEXT, NULL);
+
+  /* Save handle to last owned selection */
+  g_atomLastOwnedSelection = stuff->selection;
+
+  /* Release the clipboard */
+  if (!CloseClipboard ())
+    {
+      ErrorF ("winProcSetSelectionOwner - CloseClipboard () failed: "
+	      "%08x\n",
+	      (int) GetLastError ());
+      goto winProcSetSelectionOwner_Done;
+    }
+
+ winProcSetSelectionOwner_Done:
+  return (*winProcSetSelectionOwnerOrig) (client);
+}
diff --git a/hw/xwin/winclipboardxevents.c b/hw/xwin/winclipboardxevents.c
new file mode 100644
index 0000000..d4c617b
--- /dev/null
+++ b/hw/xwin/winclipboardxevents.c
@@ -0,0 +1,796 @@
+/*
+ *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 "winclipboard.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUnicodeSupport;
+
+
+/*
+ * Process any pending X events
+ */
+
+int
+winClipboardFlushXEvents (HWND hwnd,
+			  int iWindow,
+			  Display *pDisplay,
+			  Bool fUseUnicode)
+{
+  Atom			atomLocalProperty = XInternAtom (pDisplay,
+							 WIN_LOCAL_PROPERTY,
+							 False);
+  Atom			atomUTF8String = XInternAtom (pDisplay,
+						      "UTF8_STRING",
+						      False);
+  Atom			atomCompoundText = XInternAtom (pDisplay,
+							"COMPOUND_TEXT",
+							False);
+  Atom			atomTargets = XInternAtom (pDisplay,
+						   "TARGETS",
+						   False);
+
+  /* Process all pending events */
+  while (XPending (pDisplay))
+    {
+      XTextProperty		xtpText = {0};
+      XEvent			event;
+      XSelectionEvent		eventSelection;
+      unsigned long		ulReturnBytesLeft;
+      unsigned char		*pszReturnData = NULL;
+      char			*pszGlobalData = NULL;
+      int			iReturn;
+      HGLOBAL			hGlobal = NULL;
+      XICCEncodingStyle		xiccesStyle;
+      int			iConvertDataLen = 0;
+      char			*pszConvertData = NULL;
+      char			*pszTextList[2] = {NULL};
+      int			iCount;
+      char			**ppszTextList = NULL;
+      wchar_t			*pwszUnicodeStr = NULL;
+      int			iUnicodeLen = 0;
+      int			iReturnDataLen = 0;
+      int			i;
+      Bool			fAbort = FALSE;
+      Bool			fCloseClipboard = FALSE;
+      Bool			fSetClipboardData = TRUE;
+
+      /* Get the next event - will not block because one is ready */
+      XNextEvent (pDisplay, &event);
+
+      /* Branch on the event type */
+      switch (event.type)
+	{
+	  /*
+	   * SelectionRequest
+	   */
+
+	case SelectionRequest:
+#if 0
+	  {
+	    char			*pszAtomName = NULL;
+	    
+	    ErrorF ("SelectionRequest - target %d\n",
+		    event.xselectionrequest.target);
+	    
+	    pszAtomName = XGetAtomName (pDisplay,
+					event.xselectionrequest.target);
+	    ErrorF ("SelectionRequest - Target atom name %s\n", pszAtomName);
+	    XFree (pszAtomName);
+	    pszAtomName = NULL;
+	  }
+#endif
+
+	  /* Abort if invalid target type */
+	  if (event.xselectionrequest.target != XA_STRING
+	      && event.xselectionrequest.target != atomUTF8String
+	      && event.xselectionrequest.target != atomCompoundText
+	      && event.xselectionrequest.target != atomTargets)
+	    {
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+
+	  /* Handle targets type of request */
+	  if (event.xselectionrequest.target == atomTargets)
+	    {
+	      Atom atomTargetArr[] = {atomTargets,
+				      atomCompoundText,
+				      atomUTF8String,
+				      XA_STRING};
+
+	      /* Try to change the property */
+	      iReturn = XChangeProperty (pDisplay,
+					 event.xselectionrequest.requestor,
+					 event.xselectionrequest.property,
+					 XA_ATOM,
+					 32,
+					 PropModeReplace,
+					 (unsigned char *) atomTargetArr,
+					 (sizeof (atomTargetArr)
+					  / sizeof (atomTargetArr[0])));
+	      if (iReturn == BadAlloc
+		  || iReturn == BadAtom
+		  || iReturn == BadMatch
+		  || iReturn == BadValue
+		  || iReturn == BadWindow)
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+			  "XChangeProperty failed: %d\n",
+			  iReturn);
+		}
+
+	      /* Setup selection notify xevent */
+	      eventSelection.type	= SelectionNotify;
+	      eventSelection.send_event	= True;
+	      eventSelection.display	= pDisplay;
+	      eventSelection.requestor	= event.xselectionrequest.requestor;
+	      eventSelection.selection	= event.xselectionrequest.selection;
+	      eventSelection.target	= event.xselectionrequest.target;
+	      eventSelection.property	= event.xselectionrequest.property;
+	      eventSelection.time	= event.xselectionrequest.time;
+
+	      /*
+	       * Notify the requesting window that
+	       * the operation has completed
+	       */
+	      iReturn = XSendEvent (pDisplay,
+				    eventSelection.requestor,
+				    False,
+				    0L,
+				    (XEvent *) &eventSelection);
+	      if (iReturn == BadValue || iReturn == BadWindow)
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+			  "XSendEvent () failed\n");
+		}
+	      break;
+	    }
+
+	  /* Check that clipboard format is available */
+	  if (fUseUnicode
+	      && !IsClipboardFormatAvailable (CF_UNICODETEXT))
+	    {
+	      ErrorF ("winClipboardFlushXEvents - CF_UNICODETEXT is not "
+		      "available from Win32 clipboard.  Aborting.\n");
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+	  else if (!fUseUnicode
+		   && !IsClipboardFormatAvailable (CF_TEXT))
+	    {
+	      ErrorF ("winClipboardFlushXEvents - CF_TEXT is not "
+		      "available from Win32 clipboard.  Aborting.\n");
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+
+	  /* Close clipboard if we have it open already */
+	  if (GetOpenClipboardWindow () == hwnd)
+	    {
+	      CloseClipboard ();
+	    }
+
+	  /* Access the clipboard */
+	  if (!OpenClipboard (hwnd))
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "OpenClipboard () failed: %08x\n",
+		      GetLastError ());
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+	  
+	  /* Indicate that clipboard was opened */
+	  fCloseClipboard = TRUE;
+
+	  /* Setup the string style */
+	  if (event.xselectionrequest.target == XA_STRING)
+	    xiccesStyle = XStringStyle;
+#ifdef X_HAVE_UTF8_STRING
+	  else if (event.xselectionrequest.target == atomUTF8String)
+	    xiccesStyle = XUTF8StringStyle;
+#endif
+	  else if (event.xselectionrequest.target == atomCompoundText)
+	    xiccesStyle = XCompoundTextStyle;
+	  else
+	    xiccesStyle = XStringStyle;
+
+	  /*
+	   * FIXME: Can't pass CF_UNICODETEXT on Windows 95/98/Me
+	   */
+	  
+	  /* Get a pointer to the clipboard text, in desired format */
+	  if (fUseUnicode)
+	    {
+	      /* Retrieve clipboard data */
+	      hGlobal = GetClipboardData (CF_UNICODETEXT);
+	    }
+	  else
+	    {
+	      /* Retrieve clipboard data */
+	      hGlobal = GetClipboardData (CF_TEXT);
+	    }
+	  if (!hGlobal)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "GetClipboardData () failed: %08x\n",
+		      GetLastError ());
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+	  pszGlobalData = (char *) GlobalLock (hGlobal);
+
+	  /* Convert the Unicode string to UTF8 (MBCS) */
+	  if (fUseUnicode)
+	    {
+	      iConvertDataLen = WideCharToMultiByte (CP_UTF8,
+						     0,
+						     (LPCWSTR)pszGlobalData,
+						     -1,
+						     NULL,
+						     0,
+						     NULL,
+						     NULL);
+	      /* NOTE: iConvertDataLen includes space for null terminator */
+	      pszConvertData = (char *) malloc (iConvertDataLen);
+	      WideCharToMultiByte (CP_UTF8,
+				   0,
+				   (LPCWSTR)pszGlobalData,
+				   -1,
+				   pszConvertData,
+				   iConvertDataLen,
+				   NULL,
+				   NULL);
+	    }
+	  else
+	    {
+	      pszConvertData = strdup (pszGlobalData);
+	      iConvertDataLen = strlen (pszConvertData) + 1;
+	    }
+
+	  /* Convert DOS string to UNIX string */
+	  winClipboardDOStoUNIX (pszConvertData, strlen (pszConvertData));
+
+	  /* Setup our text list */
+	  pszTextList[0] = pszConvertData;
+	  pszTextList[1] = NULL;
+
+	  /* Initialize the text property */
+	  xtpText.value = NULL;
+
+	  /* Create the text property from the text list */
+	  if (fUseUnicode)
+	    {
+#ifdef X_HAVE_UTF8_STRING
+	      iReturn = Xutf8TextListToTextProperty (pDisplay,
+						     pszTextList,
+						     1,
+						     xiccesStyle,
+						     &xtpText);
+#endif
+	    }
+	  else
+	    {
+	      iReturn = XmbTextListToTextProperty (pDisplay,
+						   pszTextList,
+						   1,
+						   xiccesStyle,
+						   &xtpText);
+	    }
+	  if (iReturn == XNoMemory || iReturn == XLocaleNotSupported)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "X*TextListToTextProperty failed: %d\n",
+		      iReturn);
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+	  
+	  /* Free the converted string */
+	  free (pszConvertData);
+	  pszConvertData = NULL;
+
+	  /* Copy the clipboard text to the requesting window */
+	  iReturn = XChangeProperty (pDisplay,
+				     event.xselectionrequest.requestor,
+				     event.xselectionrequest.property,
+				     event.xselectionrequest.target,
+				     8,
+				     PropModeReplace,
+				     xtpText.value,
+				     xtpText.nitems);
+	  if (iReturn == BadAlloc || iReturn == BadAtom
+	      || iReturn == BadMatch || iReturn == BadValue
+	      || iReturn == BadWindow)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "XChangeProperty failed: %d\n",
+		      iReturn);
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+
+	  /* Release the clipboard data */
+	  GlobalUnlock (hGlobal);
+	  pszGlobalData = NULL;
+
+	  /* Clean up */
+	  XFree (xtpText.value);
+	  xtpText.value = NULL;
+
+	  /* Setup selection notify event */
+	  eventSelection.type = SelectionNotify;
+	  eventSelection.send_event = True;
+	  eventSelection.display = pDisplay;
+	  eventSelection.requestor = event.xselectionrequest.requestor;
+	  eventSelection.selection = event.xselectionrequest.selection;
+	  eventSelection.target = event.xselectionrequest.target;
+	  eventSelection.property = event.xselectionrequest.property;
+	  eventSelection.time = event.xselectionrequest.time;
+
+	  /* Notify the requesting window that the operation has completed */
+	  iReturn = XSendEvent (pDisplay,
+				eventSelection.requestor,
+				False,
+				0L,
+				(XEvent *) &eventSelection);
+	  if (iReturn == BadValue || iReturn == BadWindow)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "XSendEvent () failed\n");
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+
+	winClipboardFlushXEvents_SelectionRequest_Done:
+	  /* Free allocated resources */
+	  if (xtpText.value)
+	    XFree (xtpText.value);
+	  if (pszConvertData)
+	    free (pszConvertData);
+	  if (hGlobal && pszGlobalData)
+	    GlobalUnlock (hGlobal);
+	  
+	  /*
+	   * Send a SelectionNotify event to the requesting
+	   * client when we abort.
+	   */
+	  if (fAbort)
+	    {
+	      /* Setup selection notify event */
+	      eventSelection.type = SelectionNotify;
+	      eventSelection.send_event = True;
+	      eventSelection.display = pDisplay;
+	      eventSelection.requestor = event.xselectionrequest.requestor;
+	      eventSelection.selection = event.xselectionrequest.selection;
+	      eventSelection.target = event.xselectionrequest.target;
+	      eventSelection.property = None;
+	      eventSelection.time = event.xselectionrequest.time;
+
+	      /* Notify the requesting window that the operation is complete */
+	      iReturn = XSendEvent (pDisplay,
+				    eventSelection.requestor,
+				    False,
+				    0L,
+				    (XEvent *) &eventSelection);
+	      if (iReturn == BadValue || iReturn == BadWindow)
+		{
+		  /*
+		   * Should not be a problem if XSendEvent fails because
+		   * the client may simply have exited.
+		   */
+		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+			  "XSendEvent () failed for abort event.\n");
+		}
+	    }
+
+	  /* Close clipboard if it was opened */
+	  if (fCloseClipboard)
+	    CloseClipboard ();
+	  break;
+
+
+	  /*
+	   * SelectionNotify
+	   */ 
+
+	case SelectionNotify:
+#if 0
+	  ErrorF ("winClipboardFlushXEvents - SelectionNotify\n");
+	  {
+	    char		*pszAtomName;
+	    
+	    pszAtomName = XGetAtomName (pDisplay,
+					event.xselection.selection);
+
+	    ErrorF ("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n",
+		    pszAtomName);
+	    
+	    XFree (pszAtomName);
+	  }
+#endif
+
+
+	  /*
+	   * Request conversion of UTF8 and CompoundText targets.
+	   */
+	  if (event.xselection.property == None)
+	    {
+	      if (event.xselection.target == XA_STRING)
+		{
+#if 0
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "XA_STRING\n");
+#endif
+		  return WIN_XEVENTS_CONVERT;
+		}
+	      else if (event.xselection.target == atomUTF8String)
+		{
+#if 0
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "Requesting conversion of UTF8 target.\n");
+#endif
+		  iReturn = XConvertSelection (pDisplay,
+					       event.xselection.selection,
+					       XA_STRING,
+					       atomLocalProperty,
+					       iWindow,
+					       CurrentTime);
+		  if (iReturn != Success)
+		    {
+		      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			      "XConvertSelection () failed for UTF8String, "
+			      "aborting: %d\n",
+			      iReturn);
+		      break;
+		    }
+
+		  /* Process the ConvertSelection event */
+		  XFlush (pDisplay);
+		  return WIN_XEVENTS_CONVERT;
+		}
+#ifdef X_HAVE_UTF8_STRING
+	      else if (event.xselection.target == atomCompoundText)
+		{
+#if 0
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "Requesting conversion of CompoundText target.\n");
+#endif
+		  iReturn = XConvertSelection (pDisplay,
+					       event.xselection.selection,
+					       atomUTF8String,
+					       atomLocalProperty,
+					       iWindow,
+					       CurrentTime);
+		  if (iReturn != Success)
+		    {
+		      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			      "XConvertSelection () failed for CompoundText, "
+			      "aborting: %d\n",
+			      iReturn);
+		      break;
+		    }
+
+		  /* Process the ConvertSelection event */
+		  XFlush (pDisplay);
+		  return WIN_XEVENTS_CONVERT;
+		}
+#endif
+	      else
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "Unknown format.  Cannot request conversion, "
+			  "aborting.\n");
+		  break;
+		}
+	    }
+
+	  /* Retrieve the size of the stored data */
+	  iReturn = XGetWindowProperty (pDisplay,
+					iWindow,
+					atomLocalProperty,
+					0,
+					0, /* Don't get data, just size */
+					False,
+					AnyPropertyType,
+					&xtpText.encoding,
+					&xtpText.format,
+					&xtpText.nitems,
+					&ulReturnBytesLeft,
+					&xtpText.value);
+	  if (iReturn != Success)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+		      "XGetWindowProperty () failed, aborting: %d\n",
+		      iReturn);
+	      break;
+	    }
+
+#if 0
+	  ErrorF ("SelectionNotify - returned data %d left %d\n",
+		  xtpText.nitems, ulReturnBytesLeft);
+#endif
+
+	  /* Request the selection data */
+	  iReturn = XGetWindowProperty (pDisplay,
+					iWindow,
+					atomLocalProperty,
+					0,
+					ulReturnBytesLeft,
+					False,
+					AnyPropertyType,
+					&xtpText.encoding,
+					&xtpText.format,
+					&xtpText.nitems,
+					&ulReturnBytesLeft,
+					&xtpText.value);
+	  if (iReturn != Success)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+		      "XGetWindowProperty () failed, aborting: %d\n",
+		      iReturn);
+	      break;
+	    }
+
+#if 0
+	    {
+	      char		*pszAtomName = NULL;
+
+	      ErrorF ("SelectionNotify - returned data %d left %d\n",
+		      xtpText.nitems, ulReturnBytesLeft);
+	      
+	      pszAtomName = XGetAtomName(pDisplay, xtpText.encoding);
+	      ErrorF ("Notify atom name %s\n", pszAtomName);
+	      XFree (pszAtomName);
+	      pszAtomName = NULL;
+	    }
+#endif
+
+	  if (fUseUnicode)
+	    {
+#ifdef X_HAVE_UTF8_STRING
+	      /* Convert the text property to a text list */
+	      iReturn = Xutf8TextPropertyToTextList (pDisplay,
+						     &xtpText,
+						     &ppszTextList,
+						     &iCount);
+#endif
+	    }
+	  else
+	    {
+	      iReturn = XmbTextPropertyToTextList (pDisplay,
+						   &xtpText,
+						   &ppszTextList,
+						   &iCount);
+	    }
+	  if (iReturn == Success || iReturn > 0)
+	    {
+	      /* Conversion succeeded or some unconvertible characters */
+	      if (ppszTextList != NULL)
+		{
+		  for (i = 0; i < iCount; i++)
+		    {
+		      iReturnDataLen += strlen(ppszTextList[i]);
+		    }
+		  pszReturnData = malloc (iReturnDataLen + 1);
+		  pszReturnData[0] = '\0';
+		  for (i = 0; i < iCount; i++)
+		    {
+		      strcat (pszReturnData, ppszTextList[i]);
+		    }
+		}
+	      else
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "X*TextPropertyToTextList list_return is NULL.\n");
+		  pszReturnData = malloc (1);
+		  pszReturnData[0] = '\0';
+		}
+	    }
+	  else
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+		      "X*TextPropertyToTextList returned: ");
+	      switch (iReturn)
+		{
+		case XNoMemory:
+		  ErrorF ("XNoMemory\n");
+		  break;
+		case XConverterNotFound:
+		  ErrorF ("XConverterNotFound\n");
+		  break;
+		default:
+		  ErrorF ("%d", iReturn);
+		  break;
+		}
+	      pszReturnData = malloc (1);
+	      pszReturnData[0] = '\0';
+	    }
+
+	  /* Free the data returned from XGetWindowProperty */
+	  if (ppszTextList)
+	    XFreeStringList (ppszTextList);
+	  ppszTextList = NULL;
+	  XFree (xtpText.value);
+	  xtpText.value = NULL;
+
+	  /* Convert the X clipboard string to DOS format */
+	  winClipboardUNIXtoDOS (&pszReturnData, strlen (pszReturnData));
+
+	  if (fUseUnicode)
+	    {
+	      /* Find out how much space needed to convert MBCS to Unicode */
+	      iUnicodeLen = MultiByteToWideChar (CP_UTF8,
+						 0,
+						 pszReturnData,
+						 -1,
+						 NULL,
+						 0);
+
+	      /* Allocate memory for the Unicode string */
+	      pwszUnicodeStr
+		= (wchar_t*) malloc (sizeof (wchar_t) * (iUnicodeLen + 1));
+	      if (!pwszUnicodeStr)
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify "
+			  "malloc failed for pwszUnicodeStr, aborting.\n");
+
+		  /* Abort */
+		  fAbort = TRUE;
+		  goto winClipboardFlushXEvents_SelectionNotify_Done;
+		}
+
+	      /* Do the actual conversion */
+	      MultiByteToWideChar (CP_UTF8,
+				   0,
+				   pszReturnData,
+				   -1,
+				   pwszUnicodeStr,
+				   iUnicodeLen);
+	      
+	      /* Allocate global memory for the X clipboard data */
+	      hGlobal = GlobalAlloc (GMEM_MOVEABLE,
+				     sizeof (wchar_t) * (iUnicodeLen + 1));
+	    }
+	  else
+	    {
+	      pszConvertData = strdup (pszReturnData);
+	      iConvertDataLen = strlen (pszConvertData) + 1;
+
+	      /* Allocate global memory for the X clipboard data */
+	      hGlobal = GlobalAlloc (GMEM_MOVEABLE, iConvertDataLen);
+	    }
+
+	  /* Check that global memory was allocated */
+	  if (!hGlobal)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionNotify "
+		      "GlobalAlloc failed, aborting: %ld\n",
+		      GetLastError ());
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionNotify_Done;
+	    }
+
+	  /* Obtain a pointer to the global memory */
+	  pszGlobalData = GlobalLock (hGlobal);
+	  if (pszGlobalData == NULL)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - Could not lock global "
+		      "memory for clipboard transfer\n");
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionNotify_Done;
+	    }
+
+	  /* Copy the returned string into the global memory */
+	  if (fUseUnicode)
+	    {
+	      memcpy (pszGlobalData,
+		      pwszUnicodeStr,
+		      sizeof (wchar_t) * (iUnicodeLen + 1));
+	      free (pwszUnicodeStr);
+	      pwszUnicodeStr = NULL;
+	    }
+	  else
+	    {
+	      strcpy (pszGlobalData, pszConvertData);
+	      free (pszConvertData);
+	      pszConvertData = NULL;
+	    }
+
+	  /* Release the pointer to the global memory */
+	  GlobalUnlock (hGlobal);
+	  pszGlobalData = NULL;
+
+	  /* Push the selection data to the Windows clipboard */
+	  if (fUseUnicode)
+	    SetClipboardData (CF_UNICODETEXT, hGlobal);
+	  else
+	    SetClipboardData (CF_TEXT, hGlobal);
+
+	  /* Flag that SetClipboardData has been called */
+	  fSetClipboardData = FALSE;
+
+	  /*
+	   * NOTE: Do not try to free pszGlobalData, it is owned by
+	   * Windows after the call to SetClipboardData ().
+	   */
+
+	winClipboardFlushXEvents_SelectionNotify_Done:
+	  /* Free allocated resources */
+	  if (ppszTextList)
+	    XFreeStringList (ppszTextList);
+	  if (xtpText.value)
+	    XFree (xtpText.value);
+	  if (pszConvertData)
+	    free (pszConvertData);
+	  if (pwszUnicodeStr)
+	    free (pwszUnicodeStr);
+	  if (hGlobal && pszGlobalData)
+	    GlobalUnlock (hGlobal);
+	  if (fSetClipboardData && g_fUnicodeSupport)
+	    SetClipboardData (CF_UNICODETEXT, NULL);
+	  if (fSetClipboardData)
+	    SetClipboardData (CF_TEXT, NULL);
+	  return WIN_XEVENTS_NOTIFY;
+
+	default:
+	  break;
+	}
+    }
+
+  return WIN_XEVENTS_SUCCESS;
+}
diff --git a/hw/xwin/wincmap.c b/hw/xwin/wincmap.c
new file mode 100644
index 0000000..7ebe002
--- /dev/null
+++ b/hw/xwin/wincmap.c
@@ -0,0 +1,674 @@
+/*
+ *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"
+
+
+/*
+ * Local prototypes
+ */
+
+static int
+winListInstalledColormaps (ScreenPtr pScreen, Colormap *pmaps);
+
+static void
+winStoreColors (ColormapPtr pmap, int ndef, xColorItem *pdefs);
+
+static void
+winInstallColormap (ColormapPtr pmap);
+
+static void
+winUninstallColormap (ColormapPtr pmap);
+
+static void
+winResolveColor (unsigned short *pred,
+		 unsigned short *pgreen,
+		 unsigned short *pblue,
+		 VisualPtr	pVisual);
+
+static Bool
+winCreateColormap (ColormapPtr pmap);
+
+static void
+winDestroyColormap (ColormapPtr pmap);
+
+static Bool
+winGetPaletteDIB (ScreenPtr pScreen, ColormapPtr pcmap);
+
+static Bool
+winGetPaletteDD (ScreenPtr pScreen, ColormapPtr pcmap);
+
+
+/*
+ * Set screen functions for colormaps
+ */
+
+void
+winSetColormapFunctions (ScreenPtr pScreen)
+{
+  pScreen->CreateColormap = winCreateColormap;
+  pScreen->DestroyColormap = winDestroyColormap;
+  pScreen->InstallColormap = winInstallColormap;
+  pScreen->UninstallColormap = winUninstallColormap;
+  pScreen->ListInstalledColormaps = winListInstalledColormaps;
+  pScreen->StoreColors = winStoreColors;
+  pScreen->ResolveColor = winResolveColor;
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+/*
+ * Walk the list of installed colormaps, filling the pmaps list
+ * with the resource ids of the installed maps, and return
+ * a count of the total number of installed maps.
+ */
+static int
+winListInstalledColormaps (ScreenPtr pScreen, Colormap *pmaps)
+{
+  winScreenPriv(pScreen);
+
+  /*
+   * There will only be one installed colormap, so we only need
+   * to return one id, and the count of installed maps will always
+   * be one.
+   */
+  *pmaps = pScreenPriv->pcmapInstalled->mid;
+  return 1;
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+/* See Programming Windows - p. 663 */
+static void
+winInstallColormap (ColormapPtr pColormap)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  ColormapPtr		oldpmap = pScreenPriv->pcmapInstalled;
+
+#if CYGDEBUG
+  winDebug ("winInstallColormap\n");
+#endif
+ 
+  /* Did the colormap actually change? */
+  if (pColormap != oldpmap)
+    {
+#if CYGDEBUG
+      winDebug ("winInstallColormap - Colormap has changed, attempt "
+	      "to install.\n");
+#endif
+      
+      /* Was there a previous colormap? */
+      if (oldpmap != (ColormapPtr) None)
+	{
+	  /* There was a previous colormap; tell clients it is gone */
+	  WalkTree (pColormap->pScreen, TellLostMap, (char *)&oldpmap->mid);
+	}
+      
+      /* Install new colormap */
+      pScreenPriv->pcmapInstalled = pColormap;
+      WalkTree (pColormap->pScreen, TellGainedMap, (char *)&pColormap->mid);
+      
+      /* Call the engine specific colormap install procedure */
+      if (!((*pScreenPriv->pwinInstallColormap) (pColormap)))
+	{
+	  winErrorFVerb (2, "winInstallColormap - Screen specific colormap install "
+		  "procedure failed.  Continuing, but colors may be "
+		  "messed up from now on.\n");
+	}
+    }
+
+  /* Save a pointer to the newly installed colormap */
+  pScreenPriv->pcmapInstalled = pColormap;
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+static void
+winUninstallColormap (ColormapPtr pmap)
+{
+  winScreenPriv(pmap->pScreen);
+  ColormapPtr curpmap = pScreenPriv->pcmapInstalled;
+
+#if CYGDEBUG
+  winDebug ("winUninstallColormap\n");
+#endif
+
+  /* Is the colormap currently installed? */
+  if (pmap != curpmap)
+    {
+      /* Colormap not installed, nothing to do */
+      return;
+    }
+  
+  /* Clear the installed colormap flag */
+  pScreenPriv->pcmapInstalled = NULL;
+  
+  /*
+   * NOTE: The default colormap does not get "uninstalled" before
+   * it is destroyed.
+   */
+
+  /* Install the default cmap in place of the cmap to be uninstalled */
+  if (pmap->mid != pmap->pScreen->defColormap)
+    {
+      curpmap = (ColormapPtr) LookupIDByType(pmap->pScreen->defColormap,
+					     RT_COLORMAP);
+      (*pmap->pScreen->InstallColormap) (curpmap);
+    }
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+static void
+winStoreColors (ColormapPtr pmap,
+		int ndef,
+		xColorItem *pdefs)
+{
+  ScreenPtr		pScreen = pmap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pmap);
+  int			i;
+  unsigned short	nRed, nGreen, nBlue;
+
+#if CYGDEBUG
+  if (ndef != 1)
+    winDebug ("winStoreColors - ndef: %d\n",
+	    ndef);
+#endif
+
+  /* Save the new colors in the colormap privates */
+  for (i = 0; i < ndef; ++i)
+    {
+      /* Adjust the colors from the X color spec to the Windows color spec */
+      nRed = pdefs[i].red >> 8;
+      nGreen = pdefs[i].green >> 8;
+      nBlue = pdefs[i].blue >> 8;
+
+      /* Copy the colors to a palette entry table */
+      pCmapPriv->peColors[pdefs[0].pixel + i].peRed = nRed;
+      pCmapPriv->peColors[pdefs[0].pixel + i].peGreen = nGreen;
+      pCmapPriv->peColors[pdefs[0].pixel + i].peBlue = nBlue;
+      
+      /* Copy the colors to a RGBQUAD table */
+      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbRed = nRed;
+      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbGreen = nGreen;
+      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbBlue = nBlue;
+
+#if CYGDEBUG
+      winDebug ("winStoreColors - nRed %d nGreen %d nBlue %d\n",
+	      nRed, nGreen, nBlue);
+#endif
+    }
+
+  /* Call the engine specific store colors procedure */
+  if (!((pScreenPriv->pwinStoreColors) (pmap, ndef, pdefs)))
+    {
+      winErrorFVerb (2, "winStoreColors - Engine cpecific color storage procedure "
+	      "failed.  Continuing, but colors may be messed up from now "
+	      "on.\n");
+    }
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+static void
+winResolveColor (unsigned short *pred,
+		 unsigned short *pgreen,
+		 unsigned short *pblue,
+		 VisualPtr	pVisual)
+{
+#if CYGDEBUG
+  winDebug ("winResolveColor ()\n");
+#endif
+
+  miResolveColor (pred, pgreen, pblue, pVisual);
+}
+
+
+/* See Porting Layer Definition - p. 29 */
+static Bool
+winCreateColormap (ColormapPtr pmap)
+{
+  winPrivCmapPtr	pCmapPriv = NULL;
+  ScreenPtr		pScreen = pmap->pScreen;
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winDebug ("winCreateColormap\n");
+#endif
+
+  /* Allocate colormap privates */
+  if (!winAllocateCmapPrivates (pmap))
+    {
+      ErrorF ("winCreateColorma - Couldn't allocate cmap privates\n");
+      return FALSE;
+    }
+
+  /* Get a pointer to the newly allocated privates */
+  pCmapPriv = winGetCmapPriv (pmap);
+
+  /*
+   * FIXME: This is some evil hackery to help in handling some X clients
+   * that expect the top pixel to be white.  This "help" only lasts until
+   * some client overwrites the top colormap entry.
+   * 
+   * We don't want to actually allocate the top entry, as that causes
+   * problems with X clients that need 7 planes (128 colors) in the default
+   * colormap, such as Magic 7.1.
+   */
+  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbRed = 255;
+  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbGreen = 255;
+  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbBlue = 255;
+  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peRed = 255;
+  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peGreen = 255;
+  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peBlue = 255;
+
+  /* Call the engine specific colormap initialization procedure */
+  if (!((*pScreenPriv->pwinCreateColormap) (pmap)))
+    {
+      ErrorF ("winCreateColormap - Engine specific colormap creation "
+	      "procedure failed.  Aborting.\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/* See Porting Layer Definition - p. 29, 30 */
+static void
+winDestroyColormap (ColormapPtr pColormap)
+{
+  winScreenPriv(pColormap->pScreen);
+  winCmapPriv(pColormap);
+
+  /* Call the engine specific colormap destruction procedure */
+  if (!((*pScreenPriv->pwinDestroyColormap) (pColormap)))
+    {
+      winErrorFVerb (2, "winDestroyColormap - Engine specific colormap destruction "
+	      "procedure failed.  Continuing, but it is possible that memory "
+	      "was leaked, or that colors will be messed up from now on.\n");
+    }
+
+  /* Free the colormap privates */
+  free (pCmapPriv);
+  winSetCmapPriv (pColormap, NULL);
+
+#if CYGDEBUG
+  winDebug ("winDestroyColormap - Returning\n");
+#endif
+}
+
+
+/*
+ * Internal function to load the palette used by the Shadow DIB
+ */
+
+static Bool
+winGetPaletteDIB (ScreenPtr pScreen, ColormapPtr pcmap)
+{
+  winScreenPriv(pScreen);
+  int			i;
+  Pixel			pixel; /* Pixel == CARD32 */
+  CARD16		nRed, nGreen, nBlue; /* CARD16 == unsigned short */
+  UINT			uiColorsRetrieved = 0;
+  RGBQUAD		rgbColors[WIN_NUM_PALETTE_ENTRIES];
+      
+  /* Get the color table for the screen */
+  uiColorsRetrieved = GetDIBColorTable (pScreenPriv->hdcScreen,
+					0,
+					WIN_NUM_PALETTE_ENTRIES,
+					rgbColors);
+  if (uiColorsRetrieved == 0)
+    {
+      ErrorF ("winGetPaletteDIB - Could not retrieve screen color table\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winGetPaletteDIB - Retrieved %d colors from DIB\n",
+	  uiColorsRetrieved);
+#endif
+
+  /* Set the DIB color table to the default screen palette */
+  if (SetDIBColorTable (pScreenPriv->hdcShadow,
+			0,
+			uiColorsRetrieved,
+			rgbColors) == 0)
+    {
+      ErrorF ("winGetPaletteDIB - SetDIBColorTable () failed\n");
+      return FALSE;
+    }
+
+  /* Alloc each color in the DIB color table */
+  for (i = 0; i < uiColorsRetrieved; ++i)
+    {
+      pixel = i;
+
+      /* Extract the color values for current palette entry */
+      nRed = rgbColors[i].rgbRed << 8;
+      nGreen = rgbColors[i].rgbGreen << 8;
+      nBlue = rgbColors[i].rgbBlue << 8;
+
+#if CYGDEBUG
+      winDebug ("winGetPaletteDIB - Allocating a color: %d; "
+	      "%d %d %d\n",
+	      pixel, nRed, nGreen, nBlue);
+#endif
+
+      /* Allocate a entry in the X colormap */
+      if (AllocColor (pcmap,
+		      &nRed,
+		      &nGreen,
+		      &nBlue,
+		      &pixel,
+		      0) != Success)
+	{
+	  ErrorF ("winGetPaletteDIB - AllocColor () failed, pixel %d\n",
+		  i);
+	  return FALSE;
+	}
+
+      if (i != pixel
+	  || nRed != rgbColors[i].rgbRed 
+	  || nGreen != rgbColors[i].rgbGreen
+	  || nBlue != rgbColors[i].rgbBlue)
+	{
+	  winDebug ("winGetPaletteDIB - Got: %d; "
+		  "%d %d %d\n",
+		  (int) pixel, nRed, nGreen, nBlue);
+	}
+	  
+      /* FIXME: Not sure that this bit is needed at all */
+      pcmap->red[i].co.local.red = nRed;
+      pcmap->red[i].co.local.green = nGreen;
+      pcmap->red[i].co.local.blue = nBlue;
+    }
+
+  /* System is using a colormap */
+  /* Set the black and white pixel indices */
+  pScreen->whitePixel = uiColorsRetrieved - 1;
+  pScreen->blackPixel = 0;
+
+  return TRUE;
+}
+
+
+/*
+ * Internal function to load the standard system palette being used by DD
+ */
+
+static Bool
+winGetPaletteDD (ScreenPtr pScreen, ColormapPtr pcmap)
+{
+  int			i;
+  Pixel			pixel; /* Pixel == CARD32 */
+  CARD16		nRed, nGreen, nBlue; /* CARD16 == unsigned short */
+  UINT			uiSystemPaletteEntries;
+  LPPALETTEENTRY	ppeColors = NULL;
+  HDC			hdc = NULL;
+
+  /* Get a DC to obtain the default palette */
+  hdc = GetDC (NULL);
+  if (hdc == NULL)
+    {
+      ErrorF ("winGetPaletteDD - Couldn't get a DC\n");
+      return FALSE;
+    }
+
+  /* Get the number of entries in the system palette */
+  uiSystemPaletteEntries = GetSystemPaletteEntries (hdc,
+						    0, 0, NULL);
+  if (uiSystemPaletteEntries == 0)
+    {
+      ErrorF ("winGetPaletteDD - Unable to determine number of "
+	      "system palette entries\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winGetPaletteDD - uiSystemPaletteEntries %d\n",
+	  uiSystemPaletteEntries);
+#endif
+  
+  /* Allocate palette entries structure */
+  ppeColors = malloc (uiSystemPaletteEntries * sizeof (PALETTEENTRY));
+  if (ppeColors == NULL)
+    {
+      ErrorF ("winGetPaletteDD - malloc () for colormap failed\n");
+      return FALSE;
+    }
+
+  /* Get system palette entries */
+  GetSystemPaletteEntries (hdc,
+			   0, uiSystemPaletteEntries, ppeColors);
+
+  /* Allocate an X colormap entry for every system palette entry */
+  for (i = 0; i < uiSystemPaletteEntries; ++i)
+    {
+      pixel = i;
+
+      /* Extract the color values for current palette entry */
+      nRed = ppeColors[i].peRed << 8;
+      nGreen = ppeColors[i].peGreen << 8;
+      nBlue = ppeColors[i].peBlue << 8;
+#if CYGDEBUG
+      winDebug ("winGetPaletteDD - Allocating a color: %d; "
+	      "%d %d %d\n",
+	      pixel, nRed, nGreen, nBlue);
+#endif
+      if (AllocColor (pcmap,
+		      &nRed,
+		      &nGreen,
+		      &nBlue,
+		      &pixel,
+		      0) != Success)
+	{
+	  ErrorF ("winGetPaletteDD - AllocColor () failed, pixel %d\n",
+		  i);
+	  free (ppeColors);
+	  ppeColors = NULL;
+	  return FALSE;
+	}
+
+      pcmap->red[i].co.local.red = nRed;
+      pcmap->red[i].co.local.green = nGreen;
+      pcmap->red[i].co.local.blue = nBlue;
+    }
+
+  /* System is using a colormap */
+  /* Set the black and white pixel indices */
+  pScreen->whitePixel = uiSystemPaletteEntries - 1;
+  pScreen->blackPixel = 0;
+
+  /* Free colormap */
+  if (ppeColors != NULL)
+    {
+      free (ppeColors);
+      ppeColors = NULL;
+    }
+
+  /* Free the DC */
+  if (hdc != NULL)
+    {
+      ReleaseDC (NULL, hdc);
+      hdc = NULL;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Install the standard fb colormap, or the GDI colormap,
+ * depending on the current screen depth.
+ */
+
+Bool
+winCreateDefColormap (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  unsigned short	zero = 0, ones = 0xFFFF;
+  VisualPtr		pVisual = pScreenPriv->pRootVisual;
+  ColormapPtr		pcmap = NULL;
+  Pixel			wp, bp;
+
+#if CYGDEBUG
+  winDebug ("winCreateDefColormap\n");
+#endif
+
+  /* Use standard fb colormaps for non palettized color modes */
+  if (pScreenInfo->dwBPP > 8)
+    {
+      winDebug ("winCreateDefColormap - Deferring to " \
+	      "fbCreateDefColormap ()\n");
+      return fbCreateDefColormap (pScreen);
+    }
+
+  /*
+   *  AllocAll for non-Dynamic visual classes,
+   *  AllocNone for Dynamic visual classes.
+   */
+
+  /*
+   * Dynamic visual classes allow the colors of the color map
+   * to be changed by clients.
+   */
+
+#if CYGDEBUG
+  winDebug ("winCreateDefColormap - defColormap: %d\n",
+	  pScreen->defColormap);
+#endif
+
+  /* Allocate an X colormap, owned by client 0 */
+  if (CreateColormap (pScreen->defColormap, 
+		      pScreen,
+		      pVisual,
+		      &pcmap,
+		      (pVisual->class & DynamicClass) ? AllocNone : AllocAll,
+		      0) != Success)
+    {
+      ErrorF ("winCreateDefColormap - CreateColormap failed\n");
+      return FALSE;
+    }
+  if (pcmap == NULL)
+    {
+      ErrorF ("winCreateDefColormap - Colormap could not be created\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winCreateDefColormap - Created a colormap\n");
+#endif
+
+  /* Branch on the visual class */
+  if (!(pVisual->class & DynamicClass))
+    {
+      /* Branch on engine type */
+      if (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI)
+	{
+	  /* Load the colors being used by the Shadow DIB */
+	  if (!winGetPaletteDIB (pScreen, pcmap))
+	    {
+	      ErrorF ("winCreateDefColormap - Couldn't get DIB colors\n");
+	      return FALSE;
+	    }
+	}
+      else
+	{
+	  /* Load the colors from the default system palette */
+	  if (!winGetPaletteDD (pScreen, pcmap))
+	    {
+	      ErrorF ("winCreateDefColormap - Couldn't get colors "
+		      "for DD\n");
+	      return FALSE;
+	    }
+	}
+    }
+  else
+    {
+      wp = pScreen->whitePixel;
+      bp = pScreen->blackPixel;
+      
+      /* Allocate a black and white pixel */
+      if ((AllocColor (pcmap, &ones, &ones, &ones, &wp, 0) !=
+	   Success)
+	  ||
+	  (AllocColor (pcmap, &zero, &zero, &zero, &bp, 0) !=
+	   Success))
+	{
+	  ErrorF ("winCreateDefColormap - Couldn't allocate bp or wp\n");
+	  return FALSE;
+	}
+      
+      pScreen->whitePixel = wp;
+      pScreen->blackPixel = bp;
+
+#if 0
+      /* Have to reserve first 10 and last ten pixels in DirectDraw windowed */
+      if (pScreenInfo->dwEngine != WIN_SERVER_SHADOW_GDI)
+	{
+	  int		k;
+	  Pixel		p;
+
+	  for (k = 1; k < 10; ++k)
+	    {
+	      p = k;
+	      if (AllocColor (pcmap, &ones, &ones, &ones, &p, 0) != Success)
+		FatalError ("Foo!\n");
+	    }
+	  
+	  for (k = 245; k < 255; ++k)
+	    {
+	      p = k;
+	      if (AllocColor (pcmap, &zero, &zero, &zero, &p, 0) != Success)
+		FatalError ("Baz!\n");
+	    }
+	}
+#endif
+    }
+
+  /* Install the created colormap */
+  (*pScreen->InstallColormap)(pcmap);
+
+#if CYGDEBUG
+  winDebug ("winCreateDefColormap - Returning\n");
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/winconfig.c b/hw/xwin/winconfig.c
new file mode 100644
index 0000000..38966bf
--- /dev/null
+++ b/hw/xwin/winconfig.c
@@ -0,0 +1,1150 @@
+/*
+ *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"
+
+#ifdef XKB
+#ifndef XKB_IN_SERVER
+#define XKB_IN_SERVER
+#endif
+#include <xkbsrv.h>
+#endif
+
+#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
+
+XF86ConfigPtr g_xf86configptr = NULL;
+#endif
+
+WinCmdlineRec g_cmdline = {
+#ifdef XWIN_XF86CONFIG
+  NULL,				/* configFile */
+#endif
+  NULL,				/* fontPath */
+#ifdef XWIN_XF86CONFIG
+  NULL,				/* keyboard */
+#endif
+#ifdef XKB
+  FALSE,			/* noXkbExtension */
+  NULL,				/* xkbMap */
+  NULL,             /* xkbRules */
+  NULL,             /* xkbModel */
+  NULL,             /* xkbLayout */
+  NULL,             /* xkbVariant */
+  NULL,             /* xkbOptions */
+#endif
+  NULL,				/* screenname */
+  NULL,				/* mousename */
+  FALSE,			/* emulate3Buttons */
+  0				/* emulate3Timeout */
+};
+
+winInfoRec g_winInfo = {
+  {				/* keyboard */
+   0,				/* leds */
+   500,				/* delay */
+   30				/* rate */
+#ifdef XKB
+   }
+  ,
+  {				/* xkb */
+   FALSE,			/* disable */
+   NULL,			/* rules */
+   NULL,			/* model */
+   NULL,			/* layout */
+   NULL,			/* variant */
+   NULL,			/* options */
+   NULL,			/* initialMap */
+   NULL,			/* keymap */
+   NULL,			/* types */
+   NULL,			/* compat */
+   NULL,			/* keycodes */
+   NULL,			/* symbols */
+   NULL				/* geometry */
+#endif
+   }
+  ,
+  {
+   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;
+  MessageType	from = X_DEFAULT;
+  char		*xf86ConfigFile = NULL;
+
+  if (g_cmdline.configFile)
+    {
+      from = X_CMDLINE;
+      xf86ConfigFile = g_cmdline.configFile;
+    }
+
+  /* Parse config file into data structure */
+
+  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");
+      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)
+{
+#ifdef XKB
+  char                          layoutName[KL_NAMELENGTH];
+  static unsigned int           layoutNum = 0;
+  int                           keyboardType;
+#endif
+#ifdef XWIN_XF86CONFIG
+  XF86ConfInputPtr		kbd = NULL;
+  XF86ConfInputPtr		input_list = NULL;
+  MessageType			kbdfrom = X_CONFIG;
+#endif
+  MessageType			from = X_DEFAULT;
+  char				*s = NULL;
+
+  /* Setup defaults */
+#ifdef XKB
+  g_winInfo.xkb.disable = FALSE;
+# ifdef PC98 /* japanese */	/* not implemented */
+  g_winInfo.xkb.rules = "xfree98";
+  g_winInfo.xkb.model = "pc98";
+  g_winInfo.xkb.layout = "nex/jp";
+  g_winInfo.xkb.variant = NULL;
+  g_winInfo.xkb.options = NULL;
+# else
+  g_winInfo.xkb.rules = "xorg";
+  g_winInfo.xkb.model = "pc101";
+  g_winInfo.xkb.layout = "us";
+  g_winInfo.xkb.variant = NULL;
+  g_winInfo.xkb.options = NULL;
+# endif	/* PC98 */
+
+  /*
+   * Query the windows autorepeat settings and change the xserver defaults.   
+   * If XKB is disabled then windows handles the autorepeat and the special 
+   * treatment is not needed
+   */
+  {
+    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);
+      }
+  }  
+  
+  g_winInfo.xkb.initialMap = NULL;
+  g_winInfo.xkb.keymap = NULL;
+  g_winInfo.xkb.types = NULL;
+  g_winInfo.xkb.compat = NULL;
+  g_winInfo.xkb.keycodes = NULL;
+  g_winInfo.xkb.symbols = NULL;
+  g_winInfo.xkb.geometry = NULL;
+#endif /* XKB */
+
+  /* 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
+      
+#ifdef XKB
+      from = X_DEFAULT;
+      if (g_cmdline.noXkbExtension)
+	{
+	  from = X_CMDLINE;
+	  g_winInfo.xkb.disable = TRUE;
+	}
+#ifdef XWIN_XF86CONFIG
+      else if (kbd->inp_option_lst)
+	{
+	  int b = winSetBoolOption (kbd->inp_option_lst, "XkbDisable", FALSE);
+	  if (b)
+	    {
+	      from = X_CONFIG;
+	      g_winInfo.xkb.disable = TRUE;
+	    }
+	}
+#endif
+      if (g_winInfo.xkb.disable)
+	{
+	  winMsg (from, "XkbExtension disabled\n");
+	}
+      else
+	{
+          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
+	  from = X_CMDLINE;
+
+	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbKeymap", NULL)))
+	    {
+	      g_winInfo.xkb.keymap = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: keymap: \"%s\" "
+		      " (overrides other XKB settings)\n", s);
+	    }
+
+	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbCompat", NULL)))
+	    {
+	      g_winInfo.xkb.compat = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: compat: \"%s\"\n", s);
+	    }
+
+	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbTypes", NULL)))
+	    {
+	      g_winInfo.xkb.types = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: types: \"%s\"\n", s);
+	    }
+
+	  if ((s =
+	       winSetStrOption (kbd->inp_option_lst, "XkbKeycodes", NULL)))
+	    {
+	      g_winInfo.xkb.keycodes = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: keycodes: \"%s\"\n", s);
+	    }
+
+	  if ((s =
+	       winSetStrOption (kbd->inp_option_lst, "XkbGeometry", NULL)))
+	    {
+	      g_winInfo.xkb.geometry = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: geometry: \"%s\"\n", s);
+	    }
+
+	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbSymbols", NULL)))
+	    {
+	      g_winInfo.xkb.symbols = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: symbols: \"%s\"\n", s);
+	    }
+#endif
+#endif
+	}
+#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 ()
+{
+  MessageType from;
+
+  /* Fontpath */
+  if (g_cmdline.fontPath)
+    {
+      defaultFontPath = g_cmdline.fontPath;
+      winMsg (X_CMDLINE, "FontPath set to \"%s\"\n", defaultFontPath);
+    }
+
+  return TRUE;
+}
+#endif
+
+
+Bool
+winConfigOptions ()
+{
+  return TRUE;
+}
+
+
+Bool
+winConfigScreens ()
+{
+  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/hw/xwin/winconfig.h b/hw/xwin/winconfig.h
new file mode 100644
index 0000000..4b56d63
--- /dev/null
+++ b/hw/xwin/winconfig.h
@@ -0,0 +1,343 @@
+#ifndef __WIN_CONFIG_H__
+#define __WIN_CONFIG_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: Alexander Gottwald	
+ */
+
+#include "win.h"
+#ifdef XWIN_XF86CONFIG
+#include "../xfree86/parser/xf86Parser.h"
+#endif
+
+
+/* These are taken from hw/xfree86/common/xf86str.h */
+
+typedef struct
+{
+  CARD32 red, green, blue;
+}
+rgb;
+
+
+typedef struct
+{
+  float red, green, blue;
+}
+Gamma;
+
+
+typedef struct
+{
+  char *identifier;
+  char *vendor;
+  char *board;
+  char *chipset;
+  char *ramdac;
+  char *driver;
+  struct _confscreenrec *myScreenSection;
+  Bool claimed;
+  Bool active;
+  Bool inUse;
+  int videoRam;
+  int textClockFreq;
+  pointer options;
+  int screen;			/* For multi-CRTC cards */
+}
+GDevRec, *GDevPtr;
+
+
+typedef struct
+{
+  char *identifier;
+  char *driver;
+  pointer commonOptions;
+  pointer extraOptions;
+}
+IDevRec, *IDevPtr;
+
+
+typedef struct
+{
+  int frameX0;
+  int frameY0;
+  int virtualX;
+  int virtualY;
+  int depth;
+  int fbbpp;
+  rgb weight;
+  rgb blackColour;
+  rgb whiteColour;
+  int defaultVisual;
+  char **modes;
+  pointer options;
+}
+DispRec, *DispPtr;
+
+
+typedef struct _confxvportrec
+{
+  char *identifier;
+  pointer options;
+}
+confXvPortRec, *confXvPortPtr;
+
+
+typedef struct _confxvadaptrec
+{
+  char *identifier;
+  int numports;
+  confXvPortPtr ports;
+  pointer options;
+}
+confXvAdaptorRec, *confXvAdaptorPtr;
+
+
+typedef struct _confscreenrec
+{
+  char *id;
+  int screennum;
+  int defaultdepth;
+  int defaultbpp;
+  int defaultfbbpp;
+  GDevPtr device;
+  int numdisplays;
+  DispPtr displays;
+  int numxvadaptors;
+  confXvAdaptorPtr xvadaptors;
+  pointer options;
+}
+confScreenRec, *confScreenPtr;
+
+
+typedef enum
+{
+  PosObsolete = -1,
+  PosAbsolute = 0,
+  PosRightOf,
+  PosLeftOf,
+  PosAbove,
+  PosBelow,
+  PosRelative
+}
+PositionType;
+
+
+typedef struct _screenlayoutrec
+{
+  confScreenPtr screen;
+  char *topname;
+  confScreenPtr top;
+  char *bottomname;
+  confScreenPtr bottom;
+  char *leftname;
+  confScreenPtr left;
+  char *rightname;
+  confScreenPtr right;
+  PositionType where;
+  int x;
+  int y;
+  char *refname;
+  confScreenPtr refscreen;
+}
+screenLayoutRec, *screenLayoutPtr;
+
+
+typedef struct _serverlayoutrec
+{
+  char *id;
+  screenLayoutPtr screens;
+  GDevPtr inactives;
+  IDevPtr inputs;
+  pointer options;
+}
+serverLayoutRec, *serverLayoutPtr;
+
+
+/*
+ * winconfig.c
+ */
+
+typedef struct
+{
+  /* Files */
+#ifdef XWIN_XF86CONFIG
+  char *configFile;
+#endif
+  char *fontPath;
+  /* input devices - keyboard */
+#ifdef XWIN_XF86CONFIG
+  char *keyboard;
+#endif
+#ifdef XKB
+  Bool noXkbExtension;
+  char *xkbMap;
+  char *xkbRules; 
+  char *xkbModel;
+  char *xkbLayout;
+  char *xkbVariant;
+  char *xkbOptions;
+#endif
+  /* layout */
+  char *screenname;
+  /* mouse settings */
+  char *mouse;
+  Bool emulate3buttons;
+  long emulate3timeout;
+}
+WinCmdlineRec, *WinCmdlinePtr;
+
+
+extern WinCmdlineRec g_cmdline;
+#ifdef XWIN_XF86CONFIG
+extern XF86ConfigPtr g_xf86configptr;
+#endif
+extern serverLayoutRec g_winConfigLayout;
+
+
+/*
+ * Function prototypes
+ */
+
+Bool winReadConfigfile (void);
+Bool winConfigFiles (void);
+Bool winConfigOptions (void);
+Bool winConfigScreens (void);
+Bool winConfigKeyboard (DeviceIntPtr pDevice);
+Bool winConfigMouse (DeviceIntPtr pDevice);
+
+
+typedef struct
+{
+  double freq;
+  int units;
+}
+OptFrequency;
+
+
+typedef union
+{
+  unsigned long num;
+  char *str;
+  double realnum;
+  Bool bool;
+  OptFrequency freq;
+}
+ValueUnion;
+
+
+typedef enum
+{
+  OPTV_NONE = 0,
+  OPTV_INTEGER,
+  OPTV_STRING,			/* a non-empty string */
+  OPTV_ANYSTR,			/* Any string, including an empty one */
+  OPTV_REAL,
+  OPTV_BOOLEAN,
+  OPTV_FREQ
+}
+OptionValueType;
+
+
+typedef enum
+{
+  OPTUNITS_HZ = 1,
+  OPTUNITS_KHZ,
+  OPTUNITS_MHZ
+}
+OptFreqUnits;
+
+
+typedef struct
+{
+  int token;
+  const char *name;
+  OptionValueType type;
+  ValueUnion value;
+  Bool found;
+}
+OptionInfoRec, *OptionInfoPtr;
+
+
+/*
+ * Function prototypes
+ */
+
+char *winSetStrOption (pointer optlist, const char *name, char *deflt);
+int winSetBoolOption (pointer optlist, const char *name, int deflt);
+int winSetIntOption (pointer optlist, const char *name, int deflt);
+double winSetRealOption (pointer optlist, const char *name, double deflt);
+#ifdef XWIN_XF86CONFIG
+XF86OptionPtr winFindOption (XF86OptionPtr list, const char *name);
+char *winFindOptionValue (XF86OptionPtr list, const char *name);
+#endif
+int winNameCompare (const char *s1, const char *s2);
+char *winNormalizeName (const char *s);
+
+
+typedef struct
+{
+  struct
+  {
+    long leds;
+    long delay;
+    long rate;
+  }
+  keyboard;
+#ifdef XKB
+  struct
+  {
+    Bool disable;
+    char *rules;
+    char *model;
+    char *layout;
+    char *variant;
+    char *options;
+    char *initialMap;
+    char *keymap;
+    char *types;
+    char *compat;
+    char *keycodes;
+    char *symbols;
+    char *geometry;
+  }
+  xkb;
+#endif
+  struct
+  {
+    Bool emulate3Buttons;
+    long emulate3Timeout;
+  }
+  pointer;
+}
+winInfoRec, *winInfoPtr;
+
+
+extern winInfoRec g_winInfo;
+
+#endif
diff --git a/hw/xwin/wincreatewnd.c b/hw/xwin/wincreatewnd.c
new file mode 100644
index 0000000..796a085
--- /dev/null
+++ b/hw/xwin/wincreatewnd.c
@@ -0,0 +1,644 @@
+/*
+ *Copyright (C) 2001-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"
+#include "shellapi.h"
+
+#ifndef ABS_AUTOHIDE
+#define ABS_AUTOHIDE 1
+#endif
+
+/*
+ * Local function prototypes
+ */
+
+static Bool
+winGetWorkArea (RECT *prcWorkArea, winScreenInfo *pScreenInfo);
+
+static Bool
+winAdjustForAutoHide (RECT *prcWorkArea);
+
+
+/*
+ * Create a full screen window
+ */
+
+Bool
+winCreateBoundingWindowFullScreen (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  int			iX = pScreenInfo->dwInitialX;
+  int			iY = pScreenInfo->dwInitialY;
+  int			iWidth = pScreenInfo->dwWidth;
+  int			iHeight = pScreenInfo->dwHeight;
+  HWND			*phwnd = &pScreenPriv->hwndScreen;
+  WNDCLASS		wc;
+  char			szTitle[256];
+
+#if CYGDEBUG
+  winDebug ("winCreateBoundingWindowFullScreen\n");
+#endif
+
+  /* Setup our window class */
+  wc.style = CS_HREDRAW | CS_VREDRAW;
+  wc.lpfnWndProc = winWindowProc;
+  wc.cbClsExtra = 0;
+  wc.cbWndExtra = 0;
+  wc.hInstance = g_hInstance;
+  wc.hIcon = LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN));
+  wc.hCursor = 0;
+  wc.hbrBackground = 0;
+  wc.lpszMenuName = NULL;
+  wc.lpszClassName = WINDOW_CLASS;
+  RegisterClass (&wc);
+
+  /* Set display and screen-specific tooltip text */
+  if (g_pszQueryHost != NULL)
+    snprintf (szTitle,
+	    sizeof (szTitle),
+	    WINDOW_TITLE_XDMCP,
+	    g_pszQueryHost); 
+  else    
+    snprintf (szTitle,
+	    sizeof (szTitle),
+	    WINDOW_TITLE,
+	    display, 
+	    (int) pScreenInfo->dwScreen);
+
+  /* Create the window */
+  *phwnd = CreateWindowExA (0,			/* Extended styles */
+			    WINDOW_CLASS,	/* Class name */
+			    szTitle,		/* Window name */
+			    WS_POPUP,
+			    iX,			/* Horizontal position */
+			    iY,			/* Vertical position */
+			    iWidth,		/* Right edge */ 
+			    iHeight,		/* Bottom edge */
+			    (HWND) NULL,	/* No parent or owner window */
+			    (HMENU) NULL,	/* No menu */
+			    GetModuleHandle (NULL),/* Instance handle */
+			    pScreenPriv);	/* ScreenPrivates */
+
+  /* Branch on the server engine */
+  switch (pScreenInfo->dwEngine)
+    {
+#ifdef XWIN_NATIVEGDI
+    case WIN_SERVER_SHADOW_GDI:
+      /* Show the window */
+      ShowWindow (*phwnd, SW_SHOWMAXIMIZED);
+      break;
+#endif
+
+    default:
+      /* Hide the window */
+      ShowWindow (*phwnd, SW_SHOWNORMAL);
+      break;
+    }
+
+  /* Send first paint message */
+  UpdateWindow (*phwnd);
+
+  /* Attempt to bring our window to the top of the display */
+  BringWindowToTop (*phwnd);
+
+  return TRUE;
+}
+
+
+/*
+ * Create our primary Windows display window
+ */
+
+Bool
+winCreateBoundingWindowWindowed (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  int			iWidth = pScreenInfo->dwUserWidth;
+  int			iHeight = pScreenInfo->dwUserHeight;
+  int                   iPosX;
+  int                   iPosY;
+  HWND			*phwnd = &pScreenPriv->hwndScreen;
+  WNDCLASS		wc;
+  RECT			rcClient, rcWorkArea;
+  DWORD			dwWindowStyle;
+  BOOL			fForceShowWindow = FALSE;
+  char			szTitle[256];
+  
+  winDebug ("winCreateBoundingWindowWindowed - User w: %d h: %d\n",
+	  (int) pScreenInfo->dwUserWidth, (int) pScreenInfo->dwUserHeight);
+  winDebug ("winCreateBoundingWindowWindowed - Current w: %d h: %d\n",
+	  (int) pScreenInfo->dwWidth, (int) pScreenInfo->dwHeight);
+
+  /* Set the common window style flags */
+  dwWindowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX;
+  
+  /* Decorated or undecorated window */
+  if (pScreenInfo->fDecoration
+#ifdef XWIN_MULTIWINDOWEXTWM
+      && !pScreenInfo->fMWExtWM
+#endif
+      && !pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+      && !pScreenInfo->fMultiWindow
+#endif
+      )
+    {
+        /* Try to handle startup via run.exe. run.exe instructs Windows to 
+         * hide all created windows. Detect this case and make sure the 
+         * window is shown nevertheless */
+        STARTUPINFO   startupInfo;
+        GetStartupInfo(&startupInfo);
+        if (startupInfo.dwFlags & STARTF_USESHOWWINDOW && 
+                startupInfo.wShowWindow == SW_HIDE)
+        {
+          fForceShowWindow = TRUE;
+        } 
+        dwWindowStyle |= WS_CAPTION;
+        if (pScreenInfo->fScrollbars)
+            dwWindowStyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
+    }
+  else
+    dwWindowStyle |= WS_POPUP;
+
+  /* Setup our window class */
+  wc.style = CS_HREDRAW | CS_VREDRAW;
+  wc.lpfnWndProc = winWindowProc;
+  wc.cbClsExtra = 0;
+  wc.cbWndExtra = 0;
+  wc.hInstance = g_hInstance;
+  wc.hIcon = LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN));
+  wc.hCursor = 0;
+  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
+  wc.lpszMenuName = NULL;
+  wc.lpszClassName = WINDOW_CLASS;
+  RegisterClass (&wc);
+
+  /* Get size of work area */
+  winGetWorkArea (&rcWorkArea, pScreenInfo);
+
+  /* Adjust for auto-hide taskbars */
+  winAdjustForAutoHide (&rcWorkArea);
+
+  /* Did the user specify a position? */
+  if (pScreenInfo->fUserGavePosition)
+    {
+      iPosX = pScreenInfo->dwInitialX;
+      iPosY = pScreenInfo->dwInitialY;
+    }
+  else
+    {
+      iPosX = rcWorkArea.left;
+      iPosY = rcWorkArea.top;
+    }
+
+  /* Did the user specify a height and width? */
+  if (pScreenInfo->fUserGaveHeightAndWidth)
+    {
+      /* User gave a desired height and width, try to accomodate */
+#if CYGDEBUG
+      winDebug ("winCreateBoundingWindowWindowed - User gave height "
+	      "and width\n");
+#endif
+      
+      /* Adjust the window width and height for borders and title bar */
+      if (pScreenInfo->fDecoration
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  && !pScreenInfo->fMWExtWM
+#endif
+	  && !pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+	  && !pScreenInfo->fMultiWindow
+#endif
+	  )
+	{
+#if CYGDEBUG
+	  winDebug ("winCreateBoundingWindowWindowed - Window has decoration\n");
+#endif
+	  /* Are we using scrollbars? */
+	  if (pScreenInfo->fScrollbars)
+	    {
+#if CYGDEBUG
+	      winDebug ("winCreateBoundingWindowWindowed - Window has "
+		      "scrollbars\n");
+#endif
+
+	      iWidth += 2 * GetSystemMetrics (SM_CXSIZEFRAME);
+	      iHeight += 2 * GetSystemMetrics (SM_CYSIZEFRAME) 
+		+ GetSystemMetrics (SM_CYCAPTION);
+	    }
+	  else
+	    {
+#if CYGDEBUG
+	      winDebug ("winCreateBoundingWindowWindowed - Window does not have "
+		      "scrollbars\n");
+#endif
+
+	      iWidth += 2 * GetSystemMetrics (SM_CXFIXEDFRAME);
+	      iHeight += 2 * GetSystemMetrics (SM_CYFIXEDFRAME) 
+		+ GetSystemMetrics (SM_CYCAPTION);
+	    }
+	}
+    }
+  else
+    {
+      /* By default, we are creating a window that is as large as possible */
+#if CYGDEBUG
+      winDebug ("winCreateBoundingWindowWindowed - User did not give "
+	      "height and width\n");
+#endif
+      /* Defaults are wrong if we have multiple monitors */
+      if (pScreenInfo->fMultipleMonitors)
+	{
+	  iWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+	  iHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+	}
+    }
+
+  /* Clean up the scrollbars flag, if necessary */
+  if ((!pScreenInfo->fDecoration
+#ifdef XWIN_MULTIWINDOWEXTWM
+       || pScreenInfo->fMWExtWM
+#endif
+       || pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+       || pScreenInfo->fMultiWindow
+#endif
+       )
+      && pScreenInfo->fScrollbars)
+    {
+      /* We cannot have scrollbars if we do not have a window border */
+      pScreenInfo->fScrollbars = FALSE;
+    }
+ 
+  if (TRUE 
+#ifdef XWIN_MULTIWINDOWEXTWM
+       && !pScreenInfo->fMWExtWM
+#endif
+#ifdef XWIN_MULTIWINDOW
+       && !pScreenInfo->fMultiWindow
+#endif
+     )
+    {
+      /* Trim window width to fit work area */
+      if (iWidth > (rcWorkArea.right - rcWorkArea.left))
+        iWidth = rcWorkArea.right - rcWorkArea.left;
+  
+      /* Trim window height to fit work area */
+      if (iHeight >= (rcWorkArea.bottom - rcWorkArea.top))
+        iHeight = rcWorkArea.bottom - rcWorkArea.top;
+  
+#if CYGDEBUG
+      winDebug ("winCreateBoundingWindowWindowed - Adjusted width: %d "\
+	      "height: %d\n",
+    	  iWidth, iHeight);
+#endif
+    }
+
+  /* Set display and screen-specific tooltip text */
+  if (g_pszQueryHost != NULL)
+    snprintf (szTitle,
+	    sizeof (szTitle),
+	    WINDOW_TITLE_XDMCP,
+	    g_pszQueryHost); 
+  else    
+    snprintf (szTitle,
+	    sizeof (szTitle),
+	    WINDOW_TITLE,
+	    display, 
+	    (int) pScreenInfo->dwScreen);
+
+  /* Create the window */
+  *phwnd = CreateWindowExA (0,			/* Extended styles */
+			    WINDOW_CLASS,	/* Class name */
+			    szTitle,		/* Window name */
+			    dwWindowStyle,
+			    iPosX,	        /* Horizontal position */
+			    iPosY,	        /* Vertical position */
+			    iWidth,		/* Right edge */
+			    iHeight,		/* Bottom edge */
+			    (HWND) NULL,	/* No parent or owner window */
+			    (HMENU) NULL,	/* No menu */
+			    GetModuleHandle (NULL),/* Instance handle */
+			    pScreenPriv);	/* ScreenPrivates */
+  if (*phwnd == NULL)
+    {
+      ErrorF ("winCreateBoundingWindowWindowed - CreateWindowEx () failed\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winCreateBoundingWindowWindowed - CreateWindowEx () returned\n");
+#endif
+
+  if (fForceShowWindow)
+  {
+      ErrorF("winCreateBoundingWindowWindowed - Setting normal windowstyle\n");
+      ShowWindow(*phwnd, SW_SHOW);      
+  }
+
+  /* Get the client area coordinates */
+  if (!GetClientRect (*phwnd, &rcClient))
+    {
+      ErrorF ("winCreateBoundingWindowWindowed - GetClientRect () "
+	      "failed\n");
+      return FALSE;
+    }
+
+  winDebug ("winCreateBoundingWindowWindowed - WindowClient "
+	  "w %ld h %ld r %ld l %ld b %ld t %ld\n",
+	  rcClient.right - rcClient.left,
+	  rcClient.bottom - rcClient.top,
+	  rcClient.right, rcClient.left,
+	  rcClient.bottom, rcClient.top);
+  
+  /* We adjust the visual size if the user did not specify it */
+  if (!(pScreenInfo->fScrollbars && pScreenInfo->fUserGaveHeightAndWidth))
+    {
+      /*
+       * User did not give a height and width with scrollbars enabled,
+       * so we will resize the underlying visual to be as large as
+       * the initial view port (page size).  This way scrollbars will
+       * not appear until the user shrinks the window, if they ever do.
+       *
+       * NOTE: We have to store the viewport size here because
+       * the user may have an autohide taskbar, which would
+       * cause the viewport size to be one less in one dimension
+       * than the viewport size that we calculated by subtracting
+       * the size of the borders and caption.
+       */
+      pScreenInfo->dwWidth = rcClient.right - rcClient.left;
+      pScreenInfo->dwHeight = rcClient.bottom - rcClient.top;
+    }
+
+#if 0
+  /*
+   * NOTE: For the uninitiated, the page size is the number of pixels
+   * that we can display in the x or y direction at a time and the
+   * range is the total number of pixels in the x or y direction that we
+   * have available to display.  In other words, the page size is the
+   * size of the window area minus the space the caption, borders, and
+   * scrollbars (if any) occupy, and the range is the size of the
+   * underlying X visual.  Notice that, contrary to what some of the
+   * MSDN Library arcticles lead you to believe, the windows
+   * ``client area'' size does not include the scrollbars.  In other words,
+   * the whole client area size that is reported to you is drawable by
+   * you; you do not have to subtract the size of the scrollbars from
+   * the client area size, and if you did it would result in the size
+   * of the scrollbars being double counted.
+   */
+
+  /* Setup scrollbar page and range, if scrollbars are enabled */
+  if (pScreenInfo->fScrollbars)
+    {
+      SCROLLINFO		si;
+      
+      /* Initialize the scrollbar info structure */
+      si.cbSize = sizeof (si);
+      si.fMask = SIF_RANGE | SIF_PAGE;
+      si.nMin = 0;
+      
+      /* Setup the width range and page size */
+      si.nMax = pScreenInfo->dwWidth - 1;
+      si.nPage = rcClient.right - rcClient.left;
+      winDebug ("winCreateBoundingWindowWindowed - HORZ nMax: %d nPage :%d\n",
+	      si.nMax, si.nPage);
+      SetScrollInfo (*phwnd, SB_HORZ, &si, TRUE);
+      
+      /* Setup the height range and page size */
+      si.nMax = pScreenInfo->dwHeight - 1;
+      si.nPage = rcClient.bottom - rcClient.top;
+      winDebug ("winCreateBoundingWindowWindowed - VERT nMax: %d nPage :%d\n",
+	      si.nMax, si.nPage);
+      SetScrollInfo (*phwnd, SB_VERT, &si, TRUE);
+    }
+#endif
+
+  /* Show the window */
+  if (FALSE
+#ifdef XWIN_MULTIWINDOWEXTWM
+      || pScreenInfo->fMWExtWM
+#endif
+#ifdef XWIN_MULTIWINDOW
+      || pScreenInfo->fMultiWindow
+#endif
+      )
+    {
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+      pScreenPriv->fRootWindowShown = FALSE;
+#endif
+      ShowWindow (*phwnd, SW_HIDE);
+    }
+  else
+    ShowWindow (*phwnd, SW_SHOWNORMAL);
+  if (!UpdateWindow (*phwnd))
+    {
+      ErrorF ("winCreateBoundingWindowWindowed - UpdateWindow () failed\n");
+      return FALSE;
+    }
+  
+  /* Attempt to bring our window to the top of the display */
+  if (TRUE
+#ifdef XWIN_MULTIWINDOWEXTWM
+      && !pScreenInfo->fMWExtWM
+#endif
+      && !pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+      && !pScreenInfo->fMultiWindow
+#endif
+      )
+    {
+      if (!BringWindowToTop (*phwnd))
+	{
+	  ErrorF ("winCreateBoundingWindowWindowed - BringWindowToTop () "
+		  "failed\n");
+	  return FALSE;
+	}
+    }
+
+#ifdef XWIN_NATIVEGDI
+  /* Paint window background blue */
+  if (pScreenInfo->dwEngine == WIN_SERVER_NATIVE_GDI)
+    winPaintBackground (*phwnd, RGB (0x00, 0x00, 0xFF));
+#endif
+
+  winDebug ("winCreateBoundingWindowWindowed -  Returning\n");
+
+  return TRUE;
+}
+
+
+/*
+ * Find the work area of all attached monitors
+ */
+
+static Bool
+winGetWorkArea (RECT *prcWorkArea, winScreenInfo *pScreenInfo)
+{
+  int			iPrimaryWidth, iPrimaryHeight;
+  int			iWidth, iHeight;
+  int			iLeft, iTop;
+  int			iPrimaryNonWorkAreaWidth, iPrimaryNonWorkAreaHeight;
+
+  /* SPI_GETWORKAREA only gets the work area of the primary screen. */
+  SystemParametersInfo (SPI_GETWORKAREA, 0, prcWorkArea, 0);
+
+  /* Bail out here if we aren't using multiple monitors */
+  if (!pScreenInfo->fMultipleMonitors)
+    return TRUE;
+  
+  winDebug ("winGetWorkArea - Original WorkArea: %d %d %d %d\n",
+	  (int) prcWorkArea->top, (int) prcWorkArea->left,
+	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
+
+  /* Get size of full virtual screen */
+  iWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+  iHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+
+  winDebug ("winGetWorkArea - Virtual screen is %d x %d\n", iWidth, iHeight);
+
+  /* Get origin of full virtual screen */
+  iLeft = GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iTop = GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+  winDebug ("winGetWorkArea - Virtual screen origin is %d, %d\n", iLeft, iTop);
+  
+  /* Get size of primary screen */
+  iPrimaryWidth = GetSystemMetrics (SM_CXSCREEN);
+  iPrimaryHeight = GetSystemMetrics (SM_CYSCREEN);
+
+  winDebug ("winGetWorkArea - Primary screen is %d x %d\n",
+	 iPrimaryWidth, iPrimaryHeight);
+  
+  /* Work out how much of the primary screen we aren't using */
+  iPrimaryNonWorkAreaWidth = iPrimaryWidth - (prcWorkArea->right -
+					      prcWorkArea->left);
+  iPrimaryNonWorkAreaHeight = iPrimaryHeight - (prcWorkArea->bottom
+						- prcWorkArea->top);
+  
+  /* Update the rectangle to include all monitors */
+  if (iLeft < 0) 
+    {
+      prcWorkArea->left = iLeft;
+    }
+  if (iTop < 0) 
+    {
+      prcWorkArea->top = iTop;
+    }
+  prcWorkArea->right = prcWorkArea->left + iWidth -
+    iPrimaryNonWorkAreaWidth;
+  prcWorkArea->bottom = prcWorkArea->top + iHeight -
+    iPrimaryNonWorkAreaHeight;
+  
+  winDebug ("winGetWorkArea - Adjusted WorkArea for multiple "
+	  "monitors: %d %d %d %d\n",
+	  (int) prcWorkArea->top, (int) prcWorkArea->left,
+	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
+  
+  return TRUE;
+}
+
+
+/*
+ * Adjust the client area so that any auto-hide toolbars
+ * will work correctly.
+ */
+
+static Bool
+winAdjustForAutoHide (RECT *prcWorkArea)
+{
+  APPBARDATA		abd;
+  HWND			hwndAutoHide;
+
+  winDebug ("winAdjustForAutoHide - Original WorkArea: %d %d %d %d\n",
+	  (int) prcWorkArea->top, (int) prcWorkArea->left,
+	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
+
+  /* Find out if the Windows taskbar is set to auto-hide */
+  ZeroMemory (&abd, sizeof (abd));
+  abd.cbSize = sizeof (abd);
+  if (SHAppBarMessage (ABM_GETSTATE, &abd) & ABS_AUTOHIDE)
+    winDebug ("winAdjustForAutoHide - Taskbar is auto hide\n");
+
+  /* Look for a TOP auto-hide taskbar */
+  abd.uEdge = ABE_TOP;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
+  if (hwndAutoHide != NULL)
+    {
+      winDebug ("winAdjustForAutoHide - Found TOP auto-hide taskbar\n");
+      prcWorkArea->top += 1;
+    }
+
+  /* Look for a LEFT auto-hide taskbar */
+  abd.uEdge = ABE_LEFT;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
+  if (hwndAutoHide != NULL)
+    {
+      winDebug ("winAdjustForAutoHide - Found LEFT auto-hide taskbar\n");
+      prcWorkArea->left += 1;
+    }
+
+  /* Look for a BOTTOM auto-hide taskbar */
+  abd.uEdge = ABE_BOTTOM;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
+  if (hwndAutoHide != NULL)
+    {
+      winDebug ("winAdjustForAutoHide - Found BOTTOM auto-hide taskbar\n");
+      prcWorkArea->bottom -= 1;
+    }
+
+  /* Look for a RIGHT auto-hide taskbar */
+  abd.uEdge = ABE_RIGHT;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
+  if (hwndAutoHide != NULL)
+    {
+      winDebug ("winAdjustForAutoHide - Found RIGHT auto-hide taskbar\n");
+      prcWorkArea->right -= 1;
+    }
+
+  winDebug ("winAdjustForAutoHide - Adjusted WorkArea: %d %d %d %d\n",
+	  (int) prcWorkArea->top, (int) prcWorkArea->left,
+	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
+  
+#if 0
+  /* Obtain the task bar window dimensions */
+  abd.hWnd = hwndAutoHide;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETTASKBARPOS, &abd);
+  winDebug ("hwndAutoHide %08x abd.hWnd %08x %d %d %d %d\n",
+	  hwndAutoHide, abd.hWnd,
+	  abd.rc.top, abd.rc.left, abd.rc.bottom, abd.rc.right);
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/wincursor.c b/hw/xwin/wincursor.c
new file mode 100644
index 0000000..021b8b8
--- /dev/null
+++ b/hw/xwin/wincursor.c
@@ -0,0 +1,614 @@
+/*
+ *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 "winmsg.h"
+#include <cursorstr.h>
+#include <mipointrst.h>
+#include <servermd.h>
+
+extern Bool	g_fSoftwareCursor;
+
+
+#ifndef MIN
+#define MIN(x,y) ((x)<(y)?(x):(y))
+#endif
+
+#define BYTE_COUNT(x) (((x) + 7) / 8)
+
+#define BRIGHTNESS(x) (x##Red * 0.299 + x##Green * 0.587 + x##Blue * 0.114)
+
+#if 0
+# define WIN_DEBUG_MSG winDebug
+#else
+# define WIN_DEBUG_MSG(...)
+#endif
+
+/*
+ * Local function prototypes
+ */
+
+static void
+winPointerWarpCursor (ScreenPtr pScreen, int x, int y);
+
+static Bool
+winCursorOffScreen (ScreenPtr *ppScreen, int *x, int *y);
+
+static void
+winCrossScreen (ScreenPtr pScreen, Bool fEntering);
+
+miPointerScreenFuncRec g_winPointerCursorFuncs =
+{
+  winCursorOffScreen,
+  winCrossScreen,
+  winPointerWarpCursor
+};
+
+
+static void
+winPointerWarpCursor (ScreenPtr pScreen, int x, int y)
+{
+  winScreenPriv(pScreen);
+  RECT			rcClient;
+  static Bool		s_fInitialWarp = TRUE;
+
+  /* Discard first warp call */
+  if (s_fInitialWarp)
+    {
+      /* First warp moves mouse to center of window, just ignore it */
+
+      /* Don't ignore subsequent warps */
+      s_fInitialWarp = FALSE;
+
+      winErrorFVerb (2, "winPointerWarpCursor - Discarding first warp: %d %d\n",
+	      x, y);
+      
+      return;
+    }
+
+  /* Only update the Windows cursor position if we are active */
+  if (pScreenPriv->hwndScreen == GetForegroundWindow ())
+    {
+      /* Get the client area coordinates */
+      GetClientRect (pScreenPriv->hwndScreen, &rcClient);
+      
+      /* Translate the client area coords to screen coords */
+      MapWindowPoints (pScreenPriv->hwndScreen,
+		       HWND_DESKTOP,
+		       (LPPOINT)&rcClient,
+		       2);
+      
+      /* 
+       * Update the Windows cursor position so that we don't
+       * immediately warp back to the current position.
+       */
+      SetCursorPos (rcClient.left + x, rcClient.top + y);
+    }
+
+  /* Call the mi warp procedure to do the actual warping in X. */
+  miPointerWarpCursor (pScreen, x, y);
+}
+
+static Bool
+winCursorOffScreen (ScreenPtr *ppScreen, int *x, int *y)
+{
+  return FALSE;
+}
+
+static void
+winCrossScreen (ScreenPtr pScreen, Bool fEntering)
+{
+}
+
+static unsigned char
+reverse(unsigned char c)
+{
+  int i;
+  unsigned char ret = 0;
+  for (i = 0; i < 8; ++i)
+    {
+      ret |= ((c >> i)&1) << (7 - i);
+    }
+  return ret;
+}
+
+/*
+ * Convert X cursor to Windows cursor
+ * FIXME: Perhaps there are more smart code
+ */
+static HCURSOR
+winLoadCursor (ScreenPtr pScreen, CursorPtr pCursor, int screen)
+{
+  winScreenPriv(pScreen);
+  HCURSOR hCursor = NULL;
+  unsigned char *pAnd;
+  unsigned char *pXor;
+  int nCX, nCY;
+  int nBytes;
+  double dForeY, dBackY;
+  BOOL fReverse;
+  HBITMAP hAnd, hXor;
+  ICONINFO ii;
+  unsigned char *pCur;
+  int x, y;
+  unsigned char bit;
+  HDC hDC;
+  BITMAPV4HEADER bi;
+  BITMAPINFO *pbmi;
+  unsigned long *lpBits;
+
+  WIN_DEBUG_MSG("winLoadCursor: Win32: %dx%d X11: %dx%d hotspot: %d,%d\n", 
+          pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
+          pCursor->bits->width, pCursor->bits->height,
+          pCursor->bits->xhot, pCursor->bits->yhot
+          );
+
+  /* We can use only White and Black, so calc brightness of color 
+   * Also check if the cursor is inverted */  
+  dForeY = BRIGHTNESS(pCursor->fore);
+  dBackY = BRIGHTNESS(pCursor->back);
+  fReverse = dForeY < dBackY;
+ 
+  /* Check wether the X11 cursor is bigger than the win32 cursor */
+  if (pScreenPriv->cursor.sm_cx < pCursor->bits->width || 
+      pScreenPriv->cursor.sm_cy < pCursor->bits->height)
+    {
+      winErrorFVerb (2, "winLoadCursor - Windows requires %dx%d cursor\n"
+	      "\tbut X requires %dx%d\n",
+	      pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
+	      pCursor->bits->width, pCursor->bits->height);
+    }
+
+  /* Get the number of bytes required to store the whole cursor image 
+   * This is roughly (sm_cx * sm_cy) / 8 
+   * round up to 8 pixel boundary so we can convert whole bytes */
+  nBytes = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * pScreenPriv->cursor.sm_cy;
+
+  /* Get the effective width and height */
+  nCX = MIN(pScreenPriv->cursor.sm_cx, pCursor->bits->width);
+  nCY = MIN(pScreenPriv->cursor.sm_cy, pCursor->bits->height);
+
+  /* Allocate memory for the bitmaps */
+  pAnd = malloc (nBytes);
+  memset (pAnd, 0xFF, nBytes);
+  pXor = malloc (nBytes);
+  memset (pXor, 0x00, nBytes);
+
+  /* Convert the X11 bitmap to a win32 bitmap 
+   * The first is for an empty mask */
+  if (pCursor->bits->emptyMask)
+    {
+      int x, y, xmax = BYTE_COUNT(nCX);
+      for (y = 0; y < nCY; ++y)
+	for (x = 0; x < xmax; ++x)
+	  {
+	    int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + x;
+	    int nXPix = BitmapBytePad(pCursor->bits->width) * y + x;
+
+	    pAnd[nWinPix] = 0;
+	    if (fReverse)
+	      pXor[nWinPix] = reverse (~pCursor->bits->source[nXPix]);
+	    else
+	      pXor[nWinPix] = reverse (pCursor->bits->source[nXPix]);
+	  }
+    }
+  else
+    {
+      int x, y, xmax = BYTE_COUNT(nCX);
+      for (y = 0; y < nCY; ++y)
+	for (x = 0; x < xmax; ++x)
+	  {
+	    int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + x;
+	    int nXPix = BitmapBytePad(pCursor->bits->width) * y + x;
+
+	    unsigned char mask = pCursor->bits->mask[nXPix];
+	    pAnd[nWinPix] = reverse (~mask);
+	    if (fReverse)
+	      pXor[nWinPix] = reverse (~pCursor->bits->source[nXPix] & mask);
+	    else
+	      pXor[nWinPix] = reverse (pCursor->bits->source[nXPix] & mask);
+	  }
+    }
+
+  /* prepare the pointers */ 
+  hCursor = NULL;
+  lpBits = NULL;
+
+  /* We have a truecolor alpha-blended cursor and can use it! */
+  if (pCursor->bits->argb) 
+    {
+      WIN_DEBUG_MSG("winLoadCursor: Trying truecolor alphablended cursor\n"); 
+      memset (&bi, 0, sizeof (BITMAPV4HEADER));
+      bi.bV4Size = sizeof(BITMAPV4HEADER);
+      bi.bV4Width = pScreenPriv->cursor.sm_cx;
+      bi.bV4Height = -(pScreenPriv->cursor.sm_cy); /* right-side up */
+      bi.bV4Planes = 1;
+      bi.bV4BitCount = 32;
+      bi.bV4V4Compression = BI_BITFIELDS;
+      bi.bV4RedMask = 0x00FF0000;
+      bi.bV4GreenMask = 0x0000FF00;
+      bi.bV4BlueMask = 0x000000FF;
+      bi.bV4AlphaMask = 0xFF000000; 
+      
+      lpBits = (unsigned long *) calloc (pScreenPriv->cursor.sm_cx*pScreenPriv->cursor.sm_cy,
+					 sizeof (unsigned long));
+      
+      if (lpBits)
+	{
+	  for (y=0; y<nCY; y++)
+	    {
+	      unsigned long *src, *dst;
+	      src = &(pCursor->bits->argb[y * pCursor->bits->width]);
+	      dst = &(lpBits[y * pScreenPriv->cursor.sm_cx]);
+	      memcpy (dst, src, 4*nCX);
+	    }
+	}
+    } /* End if-truecolor-icon */
+  
+  if (!lpBits)
+    {
+      /* Bicolor, use a palettized DIB */
+      WIN_DEBUG_MSG("winLoadCursor: Trying two color cursor\n"); 
+      pbmi = (BITMAPINFO*)&bi;
+      memset (pbmi, 0, sizeof (BITMAPINFOHEADER));
+      pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+      pbmi->bmiHeader.biWidth = pScreenPriv->cursor.sm_cx;
+      pbmi->bmiHeader.biHeight = -abs(pScreenPriv->cursor.sm_cy); /* right-side up */
+      pbmi->bmiHeader.biPlanes = 1;
+      pbmi->bmiHeader.biBitCount = 8;
+      pbmi->bmiHeader.biCompression = BI_RGB;
+      pbmi->bmiHeader.biSizeImage = 0;
+      pbmi->bmiHeader.biClrUsed = 3;
+      pbmi->bmiHeader.biClrImportant = 3;
+      pbmi->bmiColors[0].rgbRed = 0; /* Empty */
+      pbmi->bmiColors[0].rgbGreen = 0;
+      pbmi->bmiColors[0].rgbBlue = 0;
+      pbmi->bmiColors[0].rgbReserved = 0;
+      pbmi->bmiColors[1].rgbRed = pCursor->backRed>>8; /* Background */
+      pbmi->bmiColors[1].rgbGreen = pCursor->backGreen>>8;
+      pbmi->bmiColors[1].rgbBlue = pCursor->backBlue>>8;
+      pbmi->bmiColors[1].rgbReserved = 0;
+      pbmi->bmiColors[2].rgbRed = pCursor->foreRed>>8; /* Foreground */
+      pbmi->bmiColors[2].rgbGreen = pCursor->foreGreen>>8;
+      pbmi->bmiColors[2].rgbBlue = pCursor->foreBlue>>8;
+      pbmi->bmiColors[2].rgbReserved = 0;
+      
+      lpBits = (unsigned long *) calloc (pScreenPriv->cursor.sm_cx*pScreenPriv->cursor.sm_cy,
+					 sizeof (char));
+      
+      pCur = (unsigned char *)lpBits;
+      if (lpBits)
+	{
+	  for (y=0; y<pScreenPriv->cursor.sm_cy; y++)
+	    {
+	      for (x=0; x<pScreenPriv->cursor.sm_cx; x++)
+		{
+		  if (x>=nCX || y>=nCY) /* Outside of X11 icon bounds */
+		    (*pCur++) = 0;
+		  else /* Within X11 icon bounds */
+		    {
+		      int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + (x/8);
+
+		      bit = pAnd[nWinPix];
+		      bit = bit & (1<<(7-(x&7)));
+		      if (!bit) /* Within the cursor mask? */
+			{
+			  int nXPix = BitmapBytePad(pCursor->bits->width) * y + (x/8);
+			  bit = ~reverse(~pCursor->bits->source[nXPix] & pCursor->bits->mask[nXPix]);
+			  bit = bit & (1<<(7-(x&7)));
+			  if (bit) /* Draw foreground */
+			    (*pCur++) = 2;
+			  else /* Draw background */
+			    (*pCur++) = 1;
+			}
+		      else /* Outside the cursor mask */
+			(*pCur++) = 0;
+		    }
+		} /* end for (x) */
+	    } /* end for (y) */
+	} /* end if (lpbits) */
+    }
+
+  /* If one of the previous two methods gave us the bitmap we need, make a cursor */
+  if (lpBits)
+    {
+      WIN_DEBUG_MSG("winLoadCursor: Creating bitmap cursor: hotspot %d,%d\n",
+              pCursor->bits->xhot, pCursor->bits->yhot);
+
+      hAnd = NULL;
+      hXor = NULL;
+
+      hAnd = CreateBitmap (pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy, 1, 1, pAnd);
+
+      hDC = GetDC (NULL);
+      if (hDC)
+	{
+	  hXor = CreateCompatibleBitmap (hDC, pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy);
+	  SetDIBits (hDC, hXor, 0, pScreenPriv->cursor.sm_cy, lpBits, (BITMAPINFO*)&bi, DIB_RGB_COLORS);
+	  ReleaseDC (NULL, hDC);
+	}
+      free (lpBits);
+      
+      
+      if (hAnd && hXor)
+	{
+	  ii.fIcon = FALSE;
+	  ii.xHotspot = pCursor->bits->xhot;
+	  ii.yHotspot = pCursor->bits->yhot;
+	  ii.hbmMask = hAnd;
+	  ii.hbmColor = hXor;
+	  hCursor = (HCURSOR) CreateIconIndirect( &ii );
+
+	  if (hCursor == NULL)
+	    winW32Error(2, "winLoadCursor - CreateIconIndirect failed:");
+	  else 
+	    {
+	      if (GetIconInfo(hCursor, &ii))
+		{
+		  if (ii.fIcon)
+		    {
+		      WIN_DEBUG_MSG("winLoadCursor: CreateIconIndirect returned  no cursor. Trying again.\n");
+		      
+		      DestroyCursor(hCursor);
+		      
+		      ii.fIcon = FALSE;
+		      ii.xHotspot = pCursor->bits->xhot;
+		      ii.yHotspot = pCursor->bits->yhot;
+		      hCursor = (HCURSOR) CreateIconIndirect( &ii );
+		      
+		      if (hCursor == NULL)
+			winW32Error(2, "winLoadCursor - CreateIconIndirect failed:");
+		    }
+		  /* GetIconInfo creates new bitmaps. Destroy them again */
+		  if (ii.hbmMask)
+     	            DeleteObject(ii.hbmMask);
+		  if (ii.hbmColor)
+		    DeleteObject(ii.hbmColor);
+		}
+	    }
+	}
+
+      if (hAnd)
+	DeleteObject (hAnd);
+      if (hXor)
+	DeleteObject (hXor);
+    }
+
+  if (!hCursor)
+    {
+      /* We couldn't make a color cursor for this screen, use
+	 black and white instead */
+      hCursor = CreateCursor (g_hInstance,
+			      pCursor->bits->xhot, pCursor->bits->yhot,
+			      pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
+			      pAnd, pXor);
+      if (hCursor == NULL)
+	winW32Error(2, "winLoadCursor - CreateCursor failed:");
+    }
+  free (pAnd);
+  free (pXor);
+
+  return hCursor;
+}
+
+/*
+===========================================================================
+
+ Pointer sprite functions
+
+===========================================================================
+*/
+
+/*
+ * winRealizeCursor
+ *  Convert the X cursor representation to native format if possible.
+ */
+static Bool
+winRealizeCursor (ScreenPtr pScreen, CursorPtr pCursor)
+{
+  if(pCursor == NULL || pCursor->bits == NULL)
+    return FALSE;
+  
+  /* FIXME: cache ARGB8888 representation? */
+
+  return TRUE;
+}
+
+
+/*
+ * winUnrealizeCursor
+ *  Free the storage space associated with a realized cursor.
+ */
+static Bool
+winUnrealizeCursor(ScreenPtr pScreen, CursorPtr pCursor)
+{
+  return TRUE;
+}
+
+
+/*
+ * winSetCursor
+ *  Set the cursor sprite and position.
+ */
+static void
+winSetCursor (ScreenPtr pScreen, CursorPtr pCursor, int x, int y)
+{
+  POINT ptCurPos, ptTemp;
+  HWND  hwnd;
+  RECT  rcClient;
+  BOOL  bInhibit;
+  winScreenPriv(pScreen);
+  WIN_DEBUG_MSG("winSetCursor: cursor=%p\n", pCursor); 
+  
+  /* Inhibit changing the cursor if the mouse is not in a client area */
+  bInhibit = FALSE;
+  if (GetCursorPos (&ptCurPos))
+    {
+      hwnd = WindowFromPoint (ptCurPos);
+      if (hwnd)
+	{
+	  if (GetClientRect (hwnd, &rcClient))
+	    {
+	      ptTemp.x = rcClient.left;
+	      ptTemp.y = rcClient.top;
+	      if (ClientToScreen (hwnd, &ptTemp))
+		{
+		  rcClient.left = ptTemp.x;
+		  rcClient.top = ptTemp.y;
+		  ptTemp.x = rcClient.right;
+		  ptTemp.y = rcClient.bottom;
+		  if (ClientToScreen (hwnd, &ptTemp))
+		    {
+		      rcClient.right = ptTemp.x;
+		      rcClient.bottom = ptTemp.y;
+		      if (!PtInRect (&rcClient, ptCurPos))
+			bInhibit = TRUE;
+		    }
+		}
+	    }
+	}
+    }
+
+  if (pCursor == NULL)
+    {
+      if (pScreenPriv->cursor.visible)
+	{
+	  if (!bInhibit && g_fSoftwareCursor)
+	    ShowCursor (FALSE);
+	  pScreenPriv->cursor.visible = FALSE;
+	}
+    }
+  else
+    {
+      if (pScreenPriv->cursor.handle)
+	{
+	  if (!bInhibit)
+	    SetCursor (NULL);
+	  DestroyCursor (pScreenPriv->cursor.handle);
+	  pScreenPriv->cursor.handle = NULL;
+	}
+      pScreenPriv->cursor.handle =
+	winLoadCursor (pScreen, pCursor, pScreen->myNum);
+      WIN_DEBUG_MSG("winSetCursor: handle=%p\n", pScreenPriv->cursor.handle); 
+
+      if (!bInhibit)
+	SetCursor (pScreenPriv->cursor.handle);
+
+      if (!pScreenPriv->cursor.visible)
+	{
+	  if (!bInhibit && g_fSoftwareCursor)
+	    ShowCursor (TRUE);
+	  pScreenPriv->cursor.visible = TRUE;
+	}
+    }
+}
+
+
+/*
+ * QuartzMoveCursor
+ *  Move the cursor. This is a noop for us.
+ */
+static void
+winMoveCursor (ScreenPtr pScreen, int x, int y)
+{
+}
+
+
+static miPointerSpriteFuncRec winSpriteFuncsRec = {
+  winRealizeCursor,
+  winUnrealizeCursor,
+  winSetCursor,
+  winMoveCursor
+};
+
+
+/*
+===========================================================================
+
+ Other screen functions
+
+===========================================================================
+*/
+
+/*
+ * winCursorQueryBestSize
+ *  Handle queries for best cursor size
+ */
+static void
+winCursorQueryBestSize (int class, unsigned short *width,
+				     unsigned short *height, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  
+  if (class == CursorShape)
+    {
+      *width = pScreenPriv->cursor.sm_cx;
+      *height = pScreenPriv->cursor.sm_cy;
+    }
+  else
+    {
+      if (pScreenPriv->cursor.QueryBestSize)
+        (*pScreenPriv->cursor.QueryBestSize)(class, width, height, pScreen);
+    }
+}
+
+/*
+ * winInitCursor
+ *  Initialize cursor support
+ */
+Bool
+winInitCursor (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  miPointerScreenPtr pPointPriv;
+  /* override some screen procedures */
+  pScreenPriv->cursor.QueryBestSize = pScreen->QueryBestSize;
+  pScreen->QueryBestSize = winCursorQueryBestSize;
+  
+  pPointPriv = (miPointerScreenPtr)
+      dixLookupPrivate(&pScreen->devPrivates, miPointerScreenKey);
+  
+  pScreenPriv->cursor.spriteFuncs = pPointPriv->spriteFuncs;
+  pPointPriv->spriteFuncs = &winSpriteFuncsRec;
+
+  pScreenPriv->cursor.handle = NULL;
+  pScreenPriv->cursor.visible = FALSE;
+  
+  pScreenPriv->cursor.sm_cx = GetSystemMetrics (SM_CXCURSOR);
+  pScreenPriv->cursor.sm_cy = GetSystemMetrics (SM_CYCURSOR);
+
+  return TRUE;
+}
diff --git a/hw/xwin/windialogs.c b/hw/xwin/windialogs.c
new file mode 100755
index 0000000..ab06b0d
--- /dev/null
+++ b/hw/xwin/windialogs.c
@@ -0,0 +1,788 @@
+/*
+ *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
+ *              Earle F. Philhower III
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#ifdef __CYGWIN__
+#include <sys/cygwin.h>
+#endif
+#include <shellapi.h>
+#include "winprefs.h"
+
+
+/*
+ * References to external globals
+ */
+
+extern Bool			g_fCursor;
+extern HWND			g_hDlgDepthChange;
+extern HWND			g_hDlgExit;
+extern HWND			g_hDlgAbout;
+extern WINPREFS			pref;
+#ifdef XWIN_CLIPBOARD
+extern Bool			g_fClipboardStarted;
+#endif
+extern Bool			g_fSoftwareCursor;
+
+
+/*
+ * Local function prototypes
+ */
+
+static wBOOL CALLBACK
+winExitDlgProc (HWND hDialog, UINT message,
+		WPARAM wParam, LPARAM lParam);
+
+static wBOOL CALLBACK
+winChangeDepthDlgProc (HWND hDialog, UINT message,
+		       WPARAM wParam, LPARAM lParam);
+
+static wBOOL CALLBACK
+winAboutDlgProc (HWND hDialog, UINT message,
+		 WPARAM wParam, LPARAM lParam);
+
+
+static void
+winDrawURLWindow (LPARAM lParam);
+
+static LRESULT CALLBACK
+winURLWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
+
+static void
+winOverrideURLButton (HWND hdlg, int id);
+
+static void
+winUnoverrideURLButton (HWND hdlg, int id);
+
+
+/*
+ * Owner-draw a button as a URL
+ */
+
+static void
+winDrawURLWindow (LPARAM lParam)
+{
+  DRAWITEMSTRUCT *draw;
+  char str[256];
+  RECT rect;
+  HFONT font;
+  COLORREF crText;
+  
+  draw = (DRAWITEMSTRUCT *) lParam;
+  GetWindowText (draw->hwndItem, str, sizeof(str));
+  str[255] = 0;
+  GetClientRect (draw->hwndItem, &rect);
+  
+  /* Color the button depending upon its state */
+  if (draw->itemState & ODS_SELECTED)
+    crText = RGB(128+64,0,0);
+  else if (draw->itemState & ODS_FOCUS)
+    crText = RGB(0,128+64,0);
+  else
+    crText = RGB(0,0,128+64);
+  SetTextColor (draw->hDC, crText);
+  
+  /* Create underlined font 14 high, standard dialog font */
+  font = CreateFont (-14, 0, 0, 0, FW_NORMAL, FALSE, TRUE, FALSE,
+		     0, 0, 0, 0, 0, "MS Sans Serif");
+  if (!font)
+    {
+      ErrorF ("winDrawURLWindow: Unable to create URL font, bailing.\n");
+      return;
+    }
+  /* Draw it */
+  SetBkMode (draw->hDC, OPAQUE);
+  SelectObject (draw->hDC, font);
+  DrawText (draw->hDC, str, strlen (str),&rect,DT_CENTER | DT_VCENTER);
+  /* Delete the created font, replace it with stock font */
+  DeleteObject (SelectObject (draw->hDC, GetStockObject (ANSI_VAR_FONT)));
+}
+
+
+/*
+ * WndProc for overridden buttons
+ */
+
+static LRESULT CALLBACK
+winURLWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+  WNDPROC origCB = NULL;
+  HCURSOR cursor;
+  
+  /* If it's a SetCursor message, tell it to the hand */
+  if (msg==WM_SETCURSOR) {
+    cursor = LoadCursor (NULL, IDC_HAND);
+    if (cursor)
+      SetCursor (cursor);
+    return TRUE;
+  }
+  origCB = (WNDPROC)GetWindowLong (hwnd, GWL_USERDATA);
+  /* Otherwise fall through to original WndProc */
+  if (origCB)
+    return CallWindowProc (origCB, hwnd, msg, wParam, lParam);
+  else
+    return FALSE;
+}
+
+
+/*
+ * Register and unregister the custom WndProc
+ */
+
+static void
+winOverrideURLButton (HWND hwnd, int id)
+{
+  WNDPROC origCB;
+  origCB = (WNDPROC)SetWindowLong (GetDlgItem (hwnd, id),
+				   GWL_WNDPROC, (LONG)winURLWndProc);
+  SetWindowLong (GetDlgItem (hwnd, id), GWL_USERDATA, (LONG)origCB);
+}
+
+static void
+winUnoverrideURLButton (HWND hwnd, int id)
+{
+  WNDPROC origCB;
+  origCB = (WNDPROC)SetWindowLong (GetDlgItem (hwnd, id),
+				   GWL_USERDATA, 0);
+  if (origCB)
+    SetWindowLong (GetDlgItem (hwnd, id), GWL_WNDPROC, (LONG)origCB);
+}
+
+
+/*
+ * Center a dialog window in the desktop window
+ */
+
+static void
+winCenterDialog (HWND hwndDlg)
+{
+  HWND hwndDesk; 
+  RECT rc, rcDlg, rcDesk; 
+ 
+  hwndDesk = GetParent (hwndDlg);
+  if (!hwndDesk || IsIconic (hwndDesk))
+    hwndDesk = GetDesktopWindow (); 
+  
+  GetWindowRect (hwndDesk, &rcDesk); 
+  GetWindowRect (hwndDlg, &rcDlg); 
+  CopyRect (&rc, &rcDesk); 
+  
+  OffsetRect (&rcDlg, -rcDlg.left, -rcDlg.top); 
+  OffsetRect (&rc, -rc.left, -rc.top); 
+  OffsetRect (&rc, -rcDlg.right, -rcDlg.bottom); 
+  
+  SetWindowPos (hwndDlg, 
+		HWND_TOP, 
+		rcDesk.left + (rc.right / 2), 
+		rcDesk.top + (rc.bottom / 2), 
+		0, 0,
+		SWP_NOSIZE | SWP_NOZORDER); 
+}
+
+
+/*
+ * Display the Exit dialog box
+ */
+
+void
+winDisplayExitDialog (winPrivScreenPtr pScreenPriv)
+{
+  int i;
+  int liveClients = 0;
+
+  /* Count up running clinets (clients[0] is serverClient) */
+  for (i = 1; i < currentMaxClients; i++)
+    if (clients[i] != NullClient)	
+      liveClients++;
+#if defined(XWIN_MULTIWINDOW)
+  /* Count down server internal clients */
+  if (pScreenPriv->pScreenInfo->fMultiWindow)
+    liveClients -= 2; /* multiwindow window manager & XMsgProc  */
+#endif
+#if defined(XWIN_CLIPBOARD)
+  if (g_fClipboardStarted)
+    liveClients--; /* clipboard manager */
+#endif
+
+  /* A user reported that this sometimes drops below zero. just eye-candy. */ 
+  if (liveClients < 0)
+    liveClients = 0;      
+
+  /* Don't show the exit confirmation dialog if SilentExit is enabled */
+  if (pref.fSilentExit && liveClients <= 0)
+    {
+      if (g_hDlgExit != NULL)
+	{
+	  DestroyWindow (g_hDlgExit);
+	  g_hDlgExit = NULL;
+	}
+      PostMessage (pScreenPriv->hwndScreen, WM_GIVEUP, 0, 0);
+      return;
+    }
+
+  pScreenPriv->iConnectedClients = liveClients;
+  
+  /* Check if dialog already exists */
+  if (g_hDlgExit != NULL)
+    {
+      /* Dialog box already exists, display it */
+      ShowWindow (g_hDlgExit, SW_SHOWDEFAULT);
+
+      /* User has lost the dialog.  Show them where it is. */
+      SetForegroundWindow (g_hDlgExit);
+
+      return;
+    }
+
+  /* Create dialog box */
+  g_hDlgExit = CreateDialogParam (g_hInstance,
+				  "EXIT_DIALOG",
+				  pScreenPriv->hwndScreen,
+				  winExitDlgProc,
+				  (int) pScreenPriv);
+
+  /* Drop minimize and maximize buttons */
+  SetWindowLong (g_hDlgExit, GWL_STYLE,
+		 GetWindowLong (g_hDlgExit, GWL_STYLE)
+		 & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
+  SetWindowLong (g_hDlgExit, GWL_EXSTYLE,
+		 GetWindowLong (g_hDlgExit, GWL_EXSTYLE) & ~WS_EX_APPWINDOW );
+  SetWindowPos (g_hDlgExit, HWND_TOPMOST, 0, 0, 0, 0,
+		SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); 
+ 
+  /* Show the dialog box */
+  ShowWindow (g_hDlgExit, SW_SHOW);
+  
+  /* Needed to get keyboard controls (tab, arrows, enter, esc) to work */
+  SetForegroundWindow (g_hDlgExit);
+  
+  /* Set focus to the Cancel button */
+  PostMessage (g_hDlgExit, WM_NEXTDLGCTL,
+	       (int) GetDlgItem (g_hDlgExit, IDCANCEL), TRUE);
+}
+
+#define CONNECTED_CLIENTS_FORMAT	"There are currently %d clients connected."
+
+
+/*
+ * Exit dialog window procedure
+ */
+
+static wBOOL CALLBACK
+winExitDlgProc (HWND hDialog, UINT message,
+		WPARAM wParam, LPARAM lParam)
+{
+  static winPrivScreenPtr	s_pScreenPriv = NULL;
+
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_INITDIALOG:
+      {
+	char			*pszConnectedClients;
+
+	/* Store pointers to private structures for future use */
+	s_pScreenPriv = (winPrivScreenPtr) lParam;
+	
+	winCenterDialog (hDialog);
+	
+	/* Set icon to standard app icon */
+	PostMessage (hDialog,
+		     WM_SETICON,
+		     ICON_SMALL,
+		     (LPARAM) LoadIcon (g_hInstance,
+					MAKEINTRESOURCE(IDI_XWIN)));
+
+	/* Format the connected clients string */
+	pszConnectedClients = Xprintf (CONNECTED_CLIENTS_FORMAT,
+            s_pScreenPriv->iConnectedClients);
+	if (!pszConnectedClients)
+	    return TRUE;
+     
+        
+	
+	/* Set the number of connected clients */
+	SetWindowText (GetDlgItem (hDialog, IDC_CLIENTS_CONNECTED),
+		       pszConnectedClients);
+	xfree (pszConnectedClients);
+      }
+      return TRUE;
+
+    case WM_COMMAND:
+      switch (LOWORD (wParam))
+	{
+	case IDOK:
+	  /* Send message to call the GiveUp function */
+	  PostMessage (s_pScreenPriv->hwndScreen, WM_GIVEUP, 0, 0);
+	  DestroyWindow (g_hDlgExit);
+	  g_hDlgExit = NULL;
+
+	  /* Fix to make sure keyboard focus isn't trapped */
+	  PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
+	  return TRUE;
+
+	case IDCANCEL:
+	  DestroyWindow (g_hDlgExit);
+	  g_hDlgExit = NULL;
+