xserver: Branch 'mpx' - 101 commits

Peter Hutterer whot at kemper.freedesktop.org
Fri Mar 9 09:03:35 EET 2007


 GL/Makefile.am                                                                  |   12 
 GL/apple/Makefile.am                                                            |   15 
 GL/apple/indirect.c                                                             | 2136 +++++++---
 GL/glx/glxbyteorder.h                                                           |    5 
 GL/mesa/.gitignore                                                              |    4 
 GL/mesa/Makefile.am                                                             |    4 
 GL/mesa/X/Makefile.am                                                           |    1 
 GL/mesa/array_cache/Makefile.am                                                 |   21 
 GL/mesa/glapi/Makefile.am                                                       |    1 
 GL/mesa/main/Makefile.am                                                        |    1 
 GL/mesa/math/Makefile.am                                                        |    1 
 GL/mesa/shader/Makefile.am                                                      |    1 
 GL/mesa/shader/grammar/Makefile.am                                              |    1 
 GL/mesa/shader/slang/Makefile.am                                                |    1 
 GL/mesa/swrast/Makefile.am                                                      |    1 
 GL/mesa/swrast_setup/Makefile.am                                                |    1 
 GL/mesa/tnl/Makefile.am                                                         |   16 
 GL/mesa/vbo/Makefile.am                                                         |   35 
 GL/symlink-mesa.sh                                                              |   20 
 XTrap/xtrapddmi.c                                                               |    4 
 Xext/security.c                                                                 |    8 
 Xext/xtest.c                                                                    |   13 
 Xi/Makefile.am                                                                  |    2 
 Xi/allowev.c                                                                    |   12 
 Xi/chgdctl.c                                                                    |    2 
 Xi/closedev.c                                                                   |    4 
 Xi/exevents.c                                                                   |   49 
 Xi/extinit.c                                                                    |    5 
 Xi/grabdevb.c                                                                   |    2 
 Xi/grabdevk.c                                                                   |    2 
 Xi/setcptr.c                                                                    |  105 
 Xi/setcptr.h                                                                    |   39 
 Xi/setdval.c                                                                    |    2 
 Xi/setmode.c                                                                    |    2 
 Xi/ungrdev.c                                                                    |    6 
 Xi/ungrdevb.c                                                                   |    2 
 Xi/ungrdevk.c                                                                   |    2 
 autogen.sh                                                                      |    2 
 config/config.c                                                                 |    6 
 configure.ac                                                                    |  221 -
 damageext/damageext.c                                                           |   17 
 dix/cursor.c                                                                    |   32 
 dix/devices.c                                                                   |  196 
 dix/dispatch.c                                                                  |    2 
 dix/dixfonts.c                                                                  |    1 
 dix/events.c                                                                    |  640 +-
 dix/getevents.c                                                                 |    2 
 doc/Makefile.am                                                                 |   16 
 doc/SecurityPolicy.man.pre                                                      |  258 +
 doc/Xserver.man.pre                                                             |  221 -
 exa/exa_accel.c                                                                 |    8 
 exa/exa_render.c                                                                |   18 
 fb/fbmmx.c                                                                      |   98 
 fb/fbmmx.h                                                                      |   12 
 fb/fbpict.c                                                                     |   18 
 hw/Makefile.am                                                                  |   13 
 hw/darwin/Makefile.am                                                           |  429 +-
 hw/darwin/README.apple                                                          |   41 
 hw/darwin/apple/English.lproj/InfoPlist.strings                                 |binary
 hw/darwin/apple/English.lproj/main.nib/.svn/entries                             |   65 
 hw/darwin/apple/English.lproj/main.nib/.svn/format                              |    1 
 hw/darwin/apple/English.lproj/main.nib/.svn/prop-base/keyedobjects.nib.svn-base |    5 
 hw/darwin/apple/English.lproj/main.nib/.svn/text-base/classes.nib.svn-base      |  318 +
 hw/darwin/apple/English.lproj/main.nib/.svn/text-base/info.nib.svn-base         |   18 
 hw/darwin/apple/English.lproj/main.nib/.svn/text-base/keyedobjects.nib.svn-base |binary
 hw/darwin/apple/English.lproj/main.nib/classes.nib                              |  318 +
 hw/darwin/apple/English.lproj/main.nib/info.nib                                 |   18 
 hw/darwin/apple/English.lproj/main.nib/keyedobjects.nib                         |binary
 hw/darwin/apple/Info.plist                                                      |   71 
 hw/darwin/apple/X11.icns                                                        |binary
 hw/darwin/apple/X11.xcodeproj/project.pbxproj                                   |  329 +
 hw/darwin/apple/X11Application.h                                                |  104 
 hw/darwin/apple/X11Application.m                                                |  955 ++++
 hw/darwin/apple/X11Controller.h                                                 |   86 
 hw/darwin/apple/X11Controller.m                                                 |  752 +++
 hw/darwin/apple/Xquartz.man                                                     |  158 
 hw/darwin/apple/bundle-main.c                                                   |  911 ++++
 hw/darwin/bundle/Dutch.lproj/Makefile.am                                        |   35 
 hw/darwin/bundle/English.lproj/Makefile.am                                      |   35 
 hw/darwin/bundle/French.lproj/Makefile.am                                       |   38 
 hw/darwin/bundle/German.lproj/Makefile.am                                       |   36 
 hw/darwin/bundle/Info.plist                                                     |   66 
 hw/darwin/bundle/Japanese.lproj/Makefile.am                                     |   37 
 hw/darwin/bundle/Makefile.am                                                    |   38 
 hw/darwin/bundle/Portuguese.lproj/Makefile.am                                   |   36 
 hw/darwin/bundle/Spanish.lproj/Makefile.am                                      |   36 
 hw/darwin/bundle/Swedish.lproj/Makefile.am                                      |   36 
 hw/darwin/bundle/ko.lproj/Makefile.am                                           |   37 
 hw/darwin/darwin.c                                                              |   14 
 hw/darwin/darwin.h                                                              |    1 
 hw/darwin/darwinEvents.c                                                        |   67 
 hw/darwin/darwinKeyboard.c                                                      |    2 
 hw/darwin/darwinKeyboard.h                                                      |    2 
 hw/darwin/iokit/Makefile.am                                                     |   17 
 hw/darwin/iokit/xfIOKit.c                                                       |    5 
 hw/darwin/iokit/xfIOKitCursor.c                                                 |    5 
 hw/darwin/iokit/xfIOKitStartup.c                                                |   11 
 hw/darwin/quartz/Makefile.am                                                    |   54 
 hw/darwin/quartz/Preferences.m                                                  |    6 
 hw/darwin/quartz/XDarwin.pbproj/project.pbxproj                                 |    2 
 hw/darwin/quartz/XDarwinStartup.c                                               |    4 
 hw/darwin/quartz/XServer.m                                                      |   18 
 hw/darwin/quartz/applewm.c                                                      |   27 
 hw/darwin/quartz/cr/XView.m                                                     |    4 
 hw/darwin/quartz/cr/crAppleWM.m                                                 |   14 
 hw/darwin/quartz/cr/crFrame.m                                                   |   10 
 hw/darwin/quartz/cr/crScreen.m                                                  |   18 
 hw/darwin/quartz/fullscreen/fullscreen.c                                        |   10 
 hw/darwin/quartz/fullscreen/quartzCursor.c                                      |    8 
 hw/darwin/quartz/pseudoramiX.c                                                  |    4 
 hw/darwin/quartz/quartz.c                                                       |   12 
 hw/darwin/quartz/quartzAudio.c                                                  |    5 
 hw/darwin/quartz/quartzCocoa.m                                                  |    3 
 hw/darwin/quartz/quartzCursor.c                                                 |    5 
 hw/darwin/quartz/quartzCursor.h                                                 |    1 
 hw/darwin/quartz/quartzKeyboard.c                                               |    5 
 hw/darwin/quartz/quartzPasteboard.c                                             |    3 
 hw/darwin/quartz/quartzStartup.c                                                |   87 
 hw/darwin/quartz/xpr/appledri.c                                                 |    3 
 hw/darwin/quartz/xpr/appledri.h                                                 |  107 
 hw/darwin/quartz/xpr/appledristr.h                                              |  176 
 hw/darwin/quartz/xpr/dri.c                                                      |    3 
 hw/darwin/quartz/xpr/x-hash.c                                                   |    4 
 hw/darwin/quartz/xpr/x-hook.c                                                   |    4 
 hw/darwin/quartz/xpr/x-list.c                                                   |    4 
 hw/darwin/quartz/xpr/xprAppleWM.c                                               |    7 
 hw/darwin/quartz/xpr/xprCursor.c                                                |    6 
 hw/darwin/quartz/xpr/xprFrame.c                                                 |    6 
 hw/darwin/quartz/xpr/xprScreen.c                                                |   27 
 hw/darwin/utils/Makefile.am                                                     |   11 
 hw/dmx/Makefile.am                                                              |   24 
 hw/dmx/glxProxy/glxdrawable.h                                                   |   52 
 hw/dmx/glxProxy/glxserver.h                                                     |    3 
 hw/kdrive/ephyr/ephyr.c                                                         |   25 
 hw/kdrive/ephyr/hostx.c                                                         |    6 
 hw/kdrive/ephyr/hostx.h                                                         |    2 
 hw/kdrive/src/kinput.c                                                          |   25 
 hw/vfb/Makefile.am                                                              |   25 
 hw/vfb/Xvfb.man.pre                                                             |   13 
 hw/xfree86/Makefile.am                                                          |   17 
 hw/xfree86/common/xf86Config.c                                                  |    2 
 hw/xfree86/common/xf86DGA.c                                                     |   10 
 hw/xfree86/common/xf86Events.c                                                  |   22 
 hw/xfree86/common/xf86Init.c                                                    |    1 
 hw/xfree86/common/xf86Mode.c                                                    |   48 
 hw/xfree86/common/xf86Xinput.c                                                  |   10 
 hw/xfree86/ddc/Makefile.am                                                      |    8 
 hw/xfree86/ddc/ddcProperty.c                                                    |    1 
 hw/xfree86/ddc/xf86DDC.c                                                        |    4 
 hw/xfree86/dixmods/Makefile.am                                                  |   19 
 hw/xfree86/dri/dri.c                                                            |  135 
 hw/xfree86/dri/dri.h                                                            |    5 
 hw/xfree86/dri/dristruct.h                                                      |    3 
 hw/xfree86/i2c/Makefile.am                                                      |    5 
 hw/xfree86/loader/Makefile.am                                                   |    2 
 hw/xfree86/loader/loadmod.c                                                     |   24 
 hw/xfree86/loader/xf86sym.c                                                     |   88 
 hw/xfree86/modes/Makefile.am                                                    |   27 
 hw/xfree86/modes/xf86Crtc.c                                                     | 1740 ++++++++
 hw/xfree86/modes/xf86Crtc.h                                                     |  597 ++
 hw/xfree86/modes/xf86DiDGA.c                                                    |  286 +
 hw/xfree86/modes/xf86EdidModes.c                                                |  490 ++
 hw/xfree86/modes/xf86Modes.c                                                    |  664 +++
 hw/xfree86/modes/xf86Modes.h                                                    |   98 
 hw/xfree86/modes/xf86RandR12.c                                                  |  961 ++++
 hw/xfree86/modes/xf86RandR12.h                                                  |   37 
 hw/xfree86/modes/xf86Rename.h                                                   |   80 
 hw/xfree86/modes/xf86Rotate.c                                                   |  404 +
 hw/xfree86/modes/xf86cvt.c                                                      |  308 +
 hw/xfree86/os-support/bus/axpPci.c                                              |    5 
 hw/xfree86/os-support/linux/lnx_agp.c                                           |    1 
 hw/xfree86/os-support/solaris/Makefile.am                                       |    4 
 hw/xfree86/os-support/solaris/sun_apm.c                                         |  232 +
 hw/xfree86/os-support/xf86_OSlib.h                                              |    2 
 hw/xfree86/os-support/xf86_libc.h                                               |    2 
 hw/xfree86/parser/Makefile.am                                                   |    4 
 hw/xfree86/ramdac/xf86Cursor.c                                                  |    3 
 hw/xfree86/x86emu/ops2.c                                                        |   36 
 hw/xfree86/xf4bpp/Makefile.am                                                   |    2 
 hw/xnest/Makefile.am                                                            |   22 
 include/dix-config.h.in                                                         |   18 
 include/dix.h                                                                   |   19 
 include/dixstruct.h                                                             |    2 
 include/input.h                                                                 |    4 
 include/inputstr.h                                                              |   44 
 include/xorg-server.h.in                                                        |   12 
 mi/miinitext.c                                                                  |   27 
 mi/mipointer.c                                                                  |   55 
 mi/mispritest.h                                                                 |    1 
 miext/Makefile.am                                                               |    3 
 miext/rootless/Makefile.am                                                      |   29 
 miext/rootless/accel/Makefile.am                                                |   18 
 miext/rootless/accel/rlBlt.c                                                    |    1 
 miext/rootless/rootlessCommon.c                                                 |    3 
 miext/rootless/rootlessGC.c                                                     |    1 
 miext/rootless/rootlessValTree.c                                                |    1 
 miext/rootless/rootlessWindow.c                                                 |    6 
 miext/rootless/safeAlpha/Makefile.am                                            |   12 
 miext/rootless/safeAlpha/safeAlphaPicture.c                                     |    6 
 miext/rootless/safeAlpha/safeAlphaWindow.c                                      |    4 
 os/connection.c                                                                 |    2 
 os/utils.c                                                                      |    2 
 randr/rrcrtc.c                                                                  |   32 
 randr/rrproperty.c                                                              |    2 
 randr/rrscreen.c                                                                |   62 
 xfixes/cursor.c                                                                 |    3 
 xfixes/select.c                                                                 |    4 
 xkb/xkbEvents.c                                                                 |    5 
 xkb/xkbUtils.c                                                                  |    1 
 209 files changed, 15278 insertions(+), 1795 deletions(-)

New commits:
diff-tree 577464af4362e5a32cf7165b5128655dd86c6200 (from 07806f4081f8dcd3b5733b590eb6e5b4cae734ad)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Fri Mar 9 17:13:05 2007 +1030

    dix:    restore commit b3b2a6a0d43d1724e04d69588f8a55c3270e5523 that for some
            reason got wiped.
            fix ProcGrabKeyboard to use PickKeyboard
            fix PickKeyboard to actually work.

diff --git a/dix/events.c b/dix/events.c
index 4e77577..b4b929f 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1706,6 +1706,11 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 	if (filter != CantBeFiltered &&
 	    !((wOtherEventMasks(pWin)|pWin->eventMask) & filter))
 	    return 0;
+        
+        if (!(type & EXTENSION_EVENT_BASE) && 
+            IsInterferingGrab(wClient(pWin), pDev, pEvents))
+                return 0;
+
 	if ( (attempt = TryClientEvents(wClient(pWin), pEvents, count,
 				      pWin->eventMask, filter, grab)) )
 	{
@@ -1734,6 +1739,11 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 	    other = (InputClients *)wOtherClients(pWin);
 	for (; other; other = other->next)
 	{
+            /* core event? check for grab interference */
+            if (!(type & EXTENSION_EVENT_BASE) &&
+                    IsInterferingGrab(rClient(other), pDev, pEvents))
+                continue;
+
 	    if ( (attempt = TryClientEvents(rClient(other), pEvents, count,
 					  other->mask[mskidx], filter, grab)) )
 	    {
@@ -4144,11 +4154,12 @@ ProcGrabKeyboard(ClientPtr client)
     xGrabKeyboardReply rep;
     REQUEST(xGrabKeyboardReq);
     int result;
+    DeviceIntPtr keyboard = PickKeyboard(client);
 
     REQUEST_SIZE_MATCH(xGrabKeyboardReq);
 
-    if (XaceHook(XACE_DEVICE_ACCESS, client, inputInfo.keyboard, TRUE))
-	result = GrabDevice(client, inputInfo.keyboard, stuff->keyboardMode,
+    if (XaceHook(XACE_DEVICE_ACCESS, client, keyboard, TRUE))
+	result = GrabDevice(client, keyboard, stuff->keyboardMode,
 			    stuff->pointerMode, stuff->grabWindow,
 			    stuff->ownerEvents, stuff->time,
 			    KeyPressMask | KeyReleaseMask, &rep.status);
@@ -4169,7 +4180,7 @@ ProcGrabKeyboard(ClientPtr client)
 int
 ProcUngrabKeyboard(ClientPtr client)
 {
-    DeviceIntPtr device = inputInfo.keyboard;
+    DeviceIntPtr device = PickKeyboard(client);
     GrabPtr grab;
     TimeStamp time;
     REQUEST(xResourceReq);
@@ -4902,8 +4913,8 @@ PickPointer(ClientPtr client)
 _X_EXPORT DeviceIntPtr
 PickKeyboard(ClientPtr client)
 {
-    DeviceIntPtr dev;
-    DeviceIntPtr ptr = inputInfo.devices;
+    DeviceIntPtr ptr;
+    DeviceIntPtr dev = inputInfo.devices;
     ptr = PickPointer(client);
 
     while(dev)
@@ -4916,3 +4927,49 @@ PickKeyboard(ClientPtr client)
     return inputInfo.keyboard;
 }
 
+/* A client that has one or more core grabs does not get core events from
+ * devices it does not have a grab on. Legacy applications behave bad
+ * otherwise because they are not used to it and the events interfere.
+ * Only applies for core events.
+ *
+ * Return true if a core event from the device would interfere and should not
+ * be delivered.
+ */
+Bool 
+IsInterferingGrab(ClientPtr client, DeviceIntPtr dev, xEvent* event)
+{
+    DeviceIntPtr it = inputInfo.devices;
+
+    if (dev->coreGrab.grab && SameClient(dev->coreGrab.grab, client))
+        return FALSE;
+
+    switch(event->u.u.type)
+    {
+        case KeyPress:
+        case KeyRelease:
+        case ButtonPress:
+        case ButtonRelease:
+        case MotionNotify:
+        case EnterNotify:
+        case LeaveNotify:
+            break;
+        default:
+            return FALSE;
+    }
+
+    while(it)
+    {
+        if (it != dev)
+        {
+            if (it->coreGrab.grab && SameClient(it->coreGrab.grab, client))
+            {
+                return TRUE;
+
+            }
+        }
+        it = it->next;
+    }
+
+    return FALSE;
+}
+
diff --git a/include/dix.h b/include/dix.h
index 06dafbb..57cdce3 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -614,6 +614,11 @@ extern DeviceIntPtr PickPointer(
 extern DeviceIntPtr PickKeyboard(
     ClientPtr /* client */);
 
+extern Bool IsInterferingGrab(
+        ClientPtr /* client */,
+        DeviceIntPtr /* dev */,
+        xEvent* /* events */);
+
 #ifdef PANORAMIX
 extern void ReinitializeRootWindow(WindowPtr win, int xoff, int yoff);
 #endif
diff-tree 07806f4081f8dcd3b5733b590eb6e5b4cae734ad (from b3b2a6a0d43d1724e04d69588f8a55c3270e5523)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Fri Mar 9 15:45:25 2007 +1030

    Xi:     Add SetClientPointer request handling.

diff --git a/Xi/Makefile.am b/Xi/Makefile.am
index e77c8a3..16d0e8d 100644
--- a/Xi/Makefile.am
+++ b/Xi/Makefile.am
@@ -76,6 +76,8 @@ libXi_la_SOURCES =	\
 	sendexev.h \
 	setbmap.c \
 	setbmap.h \
+	setcptr.c \
+	setcptr.h \
 	setdval.c \
 	setdval.h \
 	setfocus.c \
diff --git a/Xi/extinit.c b/Xi/extinit.c
index 598348e..ff6e4ac 100644
--- a/Xi/extinit.c
+++ b/Xi/extinit.c
@@ -110,6 +110,7 @@ SOFTWARE.
 #include "sendexev.h"
 #include "chgkmap.h"
 #include "setbmap.h"
+#include "setcptr.h"
 #include "setdval.h"
 #include "setfocus.h"
 #include "setmmap.h"
@@ -367,6 +368,8 @@ ProcIDispatch(register ClientPtr client)
         return (ProcXChangeWindowAccess(client));
     else if (stuff->data == X_QueryWindowAccess)
         return ProcXQueryWindowAccess(client);
+    else if (stuff->data == X_SetClientPointer)
+        return ProcXSetClientPointer(client);
     else {
 	SendErrorToClient(client, IReqCode, stuff->data, 0, BadRequest);
     }
@@ -472,6 +475,8 @@ SProcIDispatch(register ClientPtr client
         return (SProcXChangeWindowAccess(client));
     else if (stuff->data == X_QueryWindowAccess)
         return SProcXQueryWindowAccess(client);
+    else if (stuff->data == X_SetClientPointer)
+        return SProcXSetClientPointer(client);
     else {
 	SendErrorToClient(client, IReqCode, stuff->data, 0, BadRequest);
     }
diff --git a/Xi/setcptr.c b/Xi/setcptr.c
new file mode 100644
index 0000000..25874f0
--- /dev/null
+++ b/Xi/setcptr.c
@@ -0,0 +1,105 @@
+/*
+
+Copyright 2007 Peter Hutterer <peter at cs.unisa.edu.au>
+
+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 AUTHOR 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 author 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 author.
+
+*/
+
+/***********************************************************************
+ *
+ * Request to set the client pointer for the owner of the given window.
+ * All subsequent calls that are ambiguous will choose the client pointer as
+ * default value.
+ */
+
+
+#define	 NEED_EVENTS
+#define	 NEED_REPLIES
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <X11/X.h>	/* for inputstr.h    */
+#include <X11/Xproto.h>	/* Request macro     */
+#include "inputstr.h"	/* DeviceIntPtr      */
+#include "windowstr.h"	/* window structure  */
+#include "scrnintstr.h"	/* screen structure  */
+#include <X11/extensions/XI.h>
+#include <X11/extensions/XIproto.h>
+#include "extnsionst.h"
+#include "extinit.h"	/* LookupDeviceIntRec */
+#include "exevents.h"
+#include "exglobals.h"
+
+#include "setcptr.h"
+
+int
+SProcXSetClientPointer(ClientPtr client)
+{
+    char n;
+
+    REQUEST(xSetClientPointerReq);
+    swaps(&stuff->length, n);
+    REQUEST_SIZE_MATCH(xSetClientPointerReq);
+    return (ProcXSetClientPointer(client));
+}
+
+int
+ProcXSetClientPointer(ClientPtr client)
+{
+    DeviceIntPtr pDev;
+    WindowPtr pWin;
+    int err;
+
+    REQUEST(xSetClientPointerReq);
+    REQUEST_SIZE_MATCH(xSetClientPointerReq);
+
+
+    pDev = LookupDeviceIntRec(stuff->deviceid);
+    if (pDev == NULL || !IsPointerDevice(pDev))
+    {
+        SendErrorToClient(client, IReqCode, X_SetClientPointer, 0,
+                BadDevice); 
+        return Success;
+    }
+
+    if (stuff->win != None)
+    {
+        err = dixLookupWindow(&pWin, stuff->win, client, DixReadWriteAccess);
+        if (err != Success)
+        {
+            SendErrorToClient(client, IReqCode, X_SetClientPointer, 
+                    stuff->win, err);
+            return Success;
+        }
+    }
+    
+    if (!SetClientPointer(wClient(pWin), client, pDev))
+    {
+        SendErrorToClient(client, IReqCode, X_SetClientPointer, 
+                stuff->win, BadAccess);
+        return Success;
+    }
+    return Success;
+}
diff --git a/Xi/setcptr.h b/Xi/setcptr.h
new file mode 100644
index 0000000..0c24fd4
--- /dev/null
+++ b/Xi/setcptr.h
@@ -0,0 +1,39 @@
+/*
+
+Copyright 2007 Peter Hutterer <peter at cs.unisa.edu.au>
+
+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 AUTHOR 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 author 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 author.
+
+*/
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#ifndef SETCPTR_H
+#define SETCPTR_H 1
+
+int SProcXSetClientPointer(ClientPtr /* client */);
+int ProcXSetClientPointer(ClientPtr /* client */);
+
+#endif /* SETCPTR_H */
diff --git a/dix/cursor.c b/dix/cursor.c
index 23a2cc9..e44a5ef 100644
--- a/dix/cursor.c
+++ b/dix/cursor.c
@@ -131,6 +131,7 @@ FreeCursor(pointer value, XID cid)
     }
     FreeCursorBits(pCurs->bits);
     xfree( pCurs);
+    MPXDBG("freeing memory for cursor\n");
     return(Success);
 }
 
diff --git a/dix/events.c b/dix/events.c
index f6d6438..4e77577 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1706,12 +1706,6 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 	if (filter != CantBeFiltered &&
 	    !((wOtherEventMasks(pWin)|pWin->eventMask) & filter))
 	    return 0;
-
-       /* core event? check for grab interference */
-        if (!(type & EXTENSION_EVENT_BASE) && 
-            IsInterferingGrab(wClient(pWin), pDev, pEvents))
-                return 0;
-
 	if ( (attempt = TryClientEvents(wClient(pWin), pEvents, count,
 				      pWin->eventMask, filter, grab)) )
 	{
@@ -1740,11 +1734,6 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 	    other = (InputClients *)wOtherClients(pWin);
 	for (; other; other = other->next)
 	{
-           /* core event? check for grab interference */
-            if (!(type & EXTENSION_EVENT_BASE) && 
-                IsInterferingGrab(rClient(other), pDev, pEvents))
-                    continue;
-
 	    if ( (attempt = TryClientEvents(rClient(other), pEvents, count,
 					  other->mask[mskidx], filter, grab)) )
 	    {
@@ -4861,11 +4850,22 @@ WriteEventsToClient(ClientPtr pClient, i
     }
 }
 
+/*
+ * Set the client pointer for the given client. Second parameter setter could
+ * be used in the future to determine access rights. Unused for now.
+ */
+_X_EXPORT Bool
+SetClientPointer(ClientPtr client, ClientPtr setter, DeviceIntPtr device)
+{
+    client->clientPtr = device;
+    return TRUE;
+}
+
 /* PickPointer will pick an appropriate pointer for the given client.
  *
  * If a client pointer is set, it will pick the client pointer, otherwise the
  * first available pointer in the list. If no physical device is attached, it
- * will pick the core pointer.
+ * will pick the core pointer, but will not store it on the client.
  */
 _X_EXPORT DeviceIntPtr
 PickPointer(ClientPtr client)
@@ -4887,7 +4887,7 @@ PickPointer(ClientPtr client)
         if (!it)
         {
             ErrorF("Picking VCP\n");
-            client->clientPtr = inputInfo.pointer;
+            return inputInfo.pointer;
         }
     }
     return client->clientPtr;
@@ -4916,49 +4916,3 @@ PickKeyboard(ClientPtr client)
     return inputInfo.keyboard;
 }
 
-/* A client that has one or more core grabs does not get core events from
- * devices it does not have a grab on. Legacy applications behave bad
- * otherwise because they are not used to it and the events interfere.
- * Only applies for core events.
- *
- * Return true if a core event from the device would interfere and should not
- * be delivered.
- */
-Bool 
-IsInterferingGrab(ClientPtr client, DeviceIntPtr dev, xEvent* event)
-{
-    DeviceIntPtr it = inputInfo.devices;
-
-    if (dev->coreGrab.grab && SameClient(dev->coreGrab.grab, client))
-        return FALSE;
-
-    switch(event->u.u.type)
-    {
-        case KeyPress:
-        case KeyRelease:
-        case ButtonPress:
-        case ButtonRelease:
-        case MotionNotify:
-        case EnterNotify:
-        case LeaveNotify:
-            break;
-        default:
-            return FALSE;
-    }
-
-    while(it)
-    {
-        if (it != dev)
-        {
-            if (it->coreGrab.grab && SameClient(it->coreGrab.grab, client))
-            {
-                return TRUE;
-
-            }
-        }
-        it = it->next;
-    }
-
-    return FALSE;
-}
-
diff --git a/include/dix.h b/include/dix.h
index 56d2f17..06dafbb 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -603,17 +603,17 @@ extern int TryClientEvents(
 
 extern void WindowsRestructured(void);
 
+extern Bool SetClientPointer(
+        ClientPtr /* client */, 
+        ClientPtr /* setter */, 
+        DeviceIntPtr /* device */);
+
 extern DeviceIntPtr PickPointer(
     ClientPtr /* client */);
 
 extern DeviceIntPtr PickKeyboard(
     ClientPtr /* client */);
 
-extern Bool IsInterferingGrab(
-    ClientPtr /* client */,
-    DeviceIntPtr /* dev */,
-    xEvent* /* events */);
-
 #ifdef PANORAMIX
 extern void ReinitializeRootWindow(WindowPtr win, int xoff, int yoff);
 #endif
diff-tree b3b2a6a0d43d1724e04d69588f8a55c3270e5523 (from ceca5670fee99b5feceaa2453f1ac32d1bfe7dcd)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Thu Mar 8 22:16:17 2007 +1030

    dix:    Check if client has a grab on any other device before mouse/kbd
            event is delivered to the client. Client's don't cope well with
            receiving core events from other devices when having a grab on a
            pointer or keyboard.

diff --git a/dix/cursor.c b/dix/cursor.c
index e44a5ef..23a2cc9 100644
--- a/dix/cursor.c
+++ b/dix/cursor.c
@@ -131,7 +131,6 @@ FreeCursor(pointer value, XID cid)
     }
     FreeCursorBits(pCurs->bits);
     xfree( pCurs);
-    MPXDBG("freeing memory for cursor\n");
     return(Success);
 }
 
diff --git a/dix/events.c b/dix/events.c
index 66d63cc..f6d6438 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1706,6 +1706,12 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 	if (filter != CantBeFiltered &&
 	    !((wOtherEventMasks(pWin)|pWin->eventMask) & filter))
 	    return 0;
+
+       /* core event? check for grab interference */
+        if (!(type & EXTENSION_EVENT_BASE) && 
+            IsInterferingGrab(wClient(pWin), pDev, pEvents))
+                return 0;
+
 	if ( (attempt = TryClientEvents(wClient(pWin), pEvents, count,
 				      pWin->eventMask, filter, grab)) )
 	{
@@ -1734,6 +1740,11 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 	    other = (InputClients *)wOtherClients(pWin);
 	for (; other; other = other->next)
 	{
+           /* core event? check for grab interference */
+            if (!(type & EXTENSION_EVENT_BASE) && 
+                IsInterferingGrab(rClient(other), pDev, pEvents))
+                    continue;
+
 	    if ( (attempt = TryClientEvents(rClient(other), pEvents, count,
 					  other->mask[mskidx], filter, grab)) )
 	    {
@@ -4905,3 +4916,49 @@ PickKeyboard(ClientPtr client)
     return inputInfo.keyboard;
 }
 
+/* A client that has one or more core grabs does not get core events from
+ * devices it does not have a grab on. Legacy applications behave bad
+ * otherwise because they are not used to it and the events interfere.
+ * Only applies for core events.
+ *
+ * Return true if a core event from the device would interfere and should not
+ * be delivered.
+ */
+Bool 
+IsInterferingGrab(ClientPtr client, DeviceIntPtr dev, xEvent* event)
+{
+    DeviceIntPtr it = inputInfo.devices;
+
+    if (dev->coreGrab.grab && SameClient(dev->coreGrab.grab, client))
+        return FALSE;
+
+    switch(event->u.u.type)
+    {
+        case KeyPress:
+        case KeyRelease:
+        case ButtonPress:
+        case ButtonRelease:
+        case MotionNotify:
+        case EnterNotify:
+        case LeaveNotify:
+            break;
+        default:
+            return FALSE;
+    }
+
+    while(it)
+    {
+        if (it != dev)
+        {
+            if (it->coreGrab.grab && SameClient(it->coreGrab.grab, client))
+            {
+                return TRUE;
+
+            }
+        }
+        it = it->next;
+    }
+
+    return FALSE;
+}
+
diff --git a/include/dix.h b/include/dix.h
index f22f489..56d2f17 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -609,6 +609,11 @@ extern DeviceIntPtr PickPointer(
 extern DeviceIntPtr PickKeyboard(
     ClientPtr /* client */);
 
+extern Bool IsInterferingGrab(
+    ClientPtr /* client */,
+    DeviceIntPtr /* dev */,
+    xEvent* /* events */);
+
 #ifdef PANORAMIX
 extern void ReinitializeRootWindow(WindowPtr win, int xoff, int yoff);
 #endif
diff-tree ceca5670fee99b5feceaa2453f1ac32d1bfe7dcd (from 537bc2ead4d154552cbdc3a19e335f82af63792c)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Thu Mar 8 17:17:23 2007 +1030

    dix:    Each device needs to differ between a core grab and an XI grab,
            otherwise a Xi grab may overwrite or release a core grab.
            Replace grab and associates with coreGrab and deviceGrab structures,
            adjust rest of dix/Xi/etc to compile.
    
    xfree86: Don't check for core devices, we'll have the virtual ones anyway.
             If we check, the first mouse device is duplicated and sends
             double events.

diff --git a/Xext/security.c b/Xext/security.c
index 6e58b09..e9d2875 100644
--- a/Xext/security.c
+++ b/Xext/security.c
@@ -822,10 +822,13 @@ CALLBACK(SecurityCheckDeviceAccess)
     untrusted_got_event = FALSE;
     found_event_window = FALSE;
 
-    if (dev->grab)
+    /* We can just use coreGrab as a comment a few lines above clearly states
+       "device security other than keyboard is not implemented yet". The core
+       kbd should never have a device grab set. */
+    if (dev->coreGrab.grab)
     {
 	untrusted_got_event =
-	    (TRUSTLEVEL(rClient(dev->grab)) != XSecurityClientTrusted);
+          (TRUSTLEVEL(rClient(dev->coreGrab.grab)) != XSecurityClientTrusted);
     }
     else
     {
diff --git a/Xi/allowev.c b/Xi/allowev.c
index ea9c5de..c9e4c87 100644
--- a/Xi/allowev.c
+++ b/Xi/allowev.c
@@ -111,22 +111,22 @@ ProcXAllowDeviceEvents(register ClientPt
 
     switch (stuff->mode) {
     case ReplayThisDevice:
-	AllowSome(client, time, thisdev, NOT_GRABBED);
+	AllowSome(client, time, thisdev, NOT_GRABBED, FALSE);
 	break;
     case SyncThisDevice:
-	AllowSome(client, time, thisdev, FREEZE_NEXT_EVENT);
+	AllowSome(client, time, thisdev, FREEZE_NEXT_EVENT, FALSE);
 	break;
     case AsyncThisDevice:
-	AllowSome(client, time, thisdev, THAWED);
+	AllowSome(client, time, thisdev, THAWED, FALSE);
 	break;
     case AsyncOtherDevices:
-	AllowSome(client, time, thisdev, THAW_OTHERS);
+	AllowSome(client, time, thisdev, THAW_OTHERS, FALSE);
 	break;
     case SyncAll:
-	AllowSome(client, time, thisdev, FREEZE_BOTH_NEXT_EVENT);
+	AllowSome(client, time, thisdev, FREEZE_BOTH_NEXT_EVENT, FALSE);
 	break;
     case AsyncAll:
-	AllowSome(client, time, thisdev, THAWED_BOTH);
+	AllowSome(client, time, thisdev, THAWED_BOTH, FALSE);
 	break;
     default:
 	SendErrorToClient(client, IReqCode, X_AllowDeviceEvents, 0, BadValue);
diff --git a/Xi/chgdctl.c b/Xi/chgdctl.c
index badd938..899015a 100644
--- a/Xi/chgdctl.c
+++ b/Xi/chgdctl.c
@@ -138,7 +138,7 @@ ProcXChangeDeviceControl(ClientPtr clien
             ret = BadMatch;
             goto out;
 	}
-	if ((dev->grab) && !SameClient(dev->grab, client)) {
+	if ((dev->deviceGrab.grab) && !SameClient(dev->deviceGrab.grab, client)) {
 	    rep.status = AlreadyGrabbed;
             ret = Success;
             goto out;
diff --git a/Xi/closedev.c b/Xi/closedev.c
index cc83e6a..7bdd373 100644
--- a/Xi/closedev.c
+++ b/Xi/closedev.c
@@ -109,8 +109,8 @@ ProcXCloseDevice(register ClientPtr clie
 	return Success;
     }
 
-    if (d->grab && SameClient(d->grab, client))
-	(*d->DeactivateGrab) (d);	/* release active grab */
+    if (d->deviceGrab.grab && SameClient(d->deviceGrab.grab, client))
+	(*d->deviceGrab.DeactivateGrab) (d);	/* release active grab */
 
     /* Remove event selections from all windows for events from this device 
      * and selected by this client.
diff --git a/Xi/exevents.c b/Xi/exevents.c
index 5dbb0e2..6cedafb 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -99,8 +99,17 @@ RegisterOtherDevice(DeviceIntPtr device)
 {
     device->public.processInputProc = ProcessOtherEvent;
     device->public.realInputProc = ProcessOtherEvent;
-    (device)->ActivateGrab = ActivateKeyboardGrab;
-    (device)->DeactivateGrab = DeactivateKeyboardGrab;
+    (device)->deviceGrab.ActivateGrab = ActivateKeyboardGrab;
+    (device)->deviceGrab.DeactivateGrab = DeactivateKeyboardGrab;
+    if (IsPointerDevice(device))
+    {
+        (device)->coreGrab.ActivateGrab = ActivatePointerGrab;
+        (device)->coreGrab.DeactivateGrab = DeactivatePointerGrab;
+    } else
+    {
+        (device)->coreGrab.ActivateGrab = ActivateKeyboardGrab;
+        (device)->coreGrab.DeactivateGrab = DeactivateKeyboardGrab;
+    }
 }
 
  /*ARGSUSED*/ void
@@ -110,7 +119,7 @@ ProcessOtherEvent(xEventPtr xE, DeviceIn
     int i;
     CARD16 modifiers;
     CARD16 mask;
-    GrabPtr grab = other->grab;
+    GrabPtr grab = other->deviceGrab.grab;
     Bool deactivateDeviceGrab = FALSE;
     int key = 0, bit = 0, rootX, rootY;
     ButtonClassPtr b = other->button;
@@ -203,7 +212,7 @@ ProcessOtherEvent(xEventPtr xE, DeviceIn
 	    }
 	}
 	if (!grab && CheckDeviceGrabs(other, xE, 0, count)) {
-	    other->activatingKey = key;
+	    other->deviceGrab.activatingKey = key;
 	    return;
 	}
     } else if (xE->u.u.type == DeviceKeyRelease) {
@@ -229,9 +238,9 @@ ProcessOtherEvent(xEventPtr xE, DeviceIn
 	    }
 	}
 
-	if (other->fromPassiveGrab && 
-            !other->grab->coreGrab &&
-            (key == other->activatingKey))
+	if (other->deviceGrab.fromPassiveGrab && 
+            !other->deviceGrab.grab->coreGrab &&
+            (key == other->deviceGrab.activatingKey))
 	    deactivateDeviceGrab = TRUE;
     } else if (xE->u.u.type == DeviceButtonPress) {
         if (!b)
@@ -270,8 +279,8 @@ ProcessOtherEvent(xEventPtr xE, DeviceIn
 	    b->state &= ~((Button1Mask >> 1) << xE->u.u.detail);
 	SetMaskForEvent(Motion_Filter(b), DeviceMotionNotify);
         if (!b->state 
-            && other->fromPassiveGrab
-            && !other->grab->coreGrab)
+            && other->deviceGrab.fromPassiveGrab
+            && !other->deviceGrab.grab->coreGrab)
             deactivateDeviceGrab = TRUE;
     } else if (xE->u.u.type == ProximityIn)
 	other->valuator->mode &= ~OutOfProximity;
@@ -287,7 +296,7 @@ ProcessOtherEvent(xEventPtr xE, DeviceIn
 			    other, count);
 
     if (deactivateDeviceGrab == TRUE)
-	(*other->DeactivateGrab) (other);
+	(*other->deviceGrab.DeactivateGrab) (other);
 }
 
 _X_EXPORT int
@@ -663,7 +672,7 @@ SelectForWindow(DeviceIntPtr dev, Window
     if (dev->valuator)
 	if ((dev->valuator->motionHintWindow == pWin) &&
 	    (mask & DevicePointerMotionHintMask) &&
-	    !(check & DevicePointerMotionHintMask) && !dev->grab)
+	    !(check & DevicePointerMotionHintMask) && !dev->deviceGrab.grab)
 	    dev->valuator->motionHintWindow = NullWindow;
     RecalculateDeviceDeliverableEvents(pWin);
     return Success;
@@ -1034,8 +1043,8 @@ DeleteDeviceFromAnyExtEvents(WindowPtr p
      * any input focus changes.
      * Deactivating a device grab should cause focus events. */
 
-    if (dev->grab && (dev->grab->window == pWin))
-	(*dev->DeactivateGrab) (dev);
+    if (dev->deviceGrab.grab && (dev->deviceGrab.grab->window == pWin))
+	(*dev->deviceGrab.DeactivateGrab) (dev);
 
     /* If the focus window is a root window (ie. has no parent) 
      * then don't delete the focus from it. */
@@ -1045,7 +1054,7 @@ DeleteDeviceFromAnyExtEvents(WindowPtr p
 
 	/* If a grab is in progress, then alter the mode of focus events. */
 
-	if (dev->grab)
+	if (dev->deviceGrab.grab)
 	    focusEventMode = NotifyWhileGrabbed;
 
 	switch (dev->focus->revert) {
@@ -1139,7 +1148,7 @@ CheckDeviceGrabAndHintWindow(WindowPtr p
 	tempGrab.pointerMode = GrabModeAsync;
 	tempGrab.confineTo = NullWindow;
 	tempGrab.cursor = NullCursor;
-	(*dev->ActivateGrab) (dev, &tempGrab, currentTime, TRUE);
+	(*dev->deviceGrab.ActivateGrab) (dev, &tempGrab, currentTime, TRUE);
     }
 }
 
@@ -1162,7 +1171,7 @@ void
 MaybeStopDeviceHint(register DeviceIntPtr dev, ClientPtr client)
 {
     WindowPtr pWin;
-    GrabPtr grab = dev->grab;
+    GrabPtr grab = dev->deviceGrab.grab;
 
     pWin = dev->valuator->motionHintWindow;
 
diff --git a/Xi/setdval.c b/Xi/setdval.c
index 958b2ac..ce9b02d 100644
--- a/Xi/setdval.c
+++ b/Xi/setdval.c
@@ -125,7 +125,7 @@ ProcXSetDeviceValuators(register ClientP
 	return Success;
     }
 
-    if ((dev->grab) && !SameClient(dev->grab, client))
+    if ((dev->deviceGrab.grab) && !SameClient(dev->deviceGrab.grab, client))
 	rep.status = AlreadyGrabbed;
     else
 	rep.status = SetDeviceValuators(client, dev, (int *)&stuff[1],
diff --git a/Xi/setmode.c b/Xi/setmode.c
index 11feb6d..ff5a3bc 100644
--- a/Xi/setmode.c
+++ b/Xi/setmode.c
@@ -113,7 +113,7 @@ ProcXSetDeviceMode(register ClientPtr cl
 	SendErrorToClient(client, IReqCode, X_SetDeviceMode, 0, BadMatch);
 	return Success;
     }
-    if ((dev->grab) && !SameClient(dev->grab, client))
+    if ((dev->deviceGrab.grab) && !SameClient(dev->deviceGrab.grab, client))
 	rep.status = AlreadyGrabbed;
     else
 	rep.status = SetDeviceMode(client, dev, stuff->mode);
diff --git a/Xi/ungrdev.c b/Xi/ungrdev.c
index 980fa93..a028a22 100644
--- a/Xi/ungrdev.c
+++ b/Xi/ungrdev.c
@@ -106,12 +106,12 @@ ProcXUngrabDevice(register ClientPtr cli
 	SendErrorToClient(client, IReqCode, X_UngrabDevice, 0, BadDevice);
 	return Success;
     }
-    grab = dev->grab;
+    grab = dev->deviceGrab.grab;
 
     time = ClientTimeToServerTime(stuff->time);
     if ((CompareTimeStamps(time, currentTime) != LATER) &&
-	(CompareTimeStamps(time, dev->grabTime) != EARLIER) &&
+	(CompareTimeStamps(time, dev->deviceGrab.grabTime) != EARLIER) &&
 	(grab) && SameClient(grab, client))
-	(*dev->DeactivateGrab) (dev);
+	(*dev->deviceGrab.DeactivateGrab) (dev);
     return Success;
 }
diff --git a/dix/devices.c b/dix/devices.c
index 9e08794..05a03b5 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -104,14 +104,27 @@ AddInputDevice(DeviceProc deviceProc, Bo
     dev->public.enqueueInputProc = EnqueueEvent;
     dev->deviceProc = deviceProc;
     dev->startup = autoStart;
-    dev->sync.frozen = FALSE;
-    dev->sync.other = NullGrab;
-    dev->sync.state = NOT_GRABBED;
-    dev->sync.event = (xEvent *) NULL;
-    dev->sync.evcount = 0;
-    dev->grab = NullGrab;
-    dev->grabTime = currentTime;
-    dev->fromPassiveGrab = FALSE;
+
+    /* core grab defaults */
+    dev->coreGrab.sync.frozen = FALSE;
+    dev->coreGrab.sync.other = NullGrab;
+    dev->coreGrab.sync.state = NOT_GRABBED;
+    dev->coreGrab.sync.event = (xEvent *) NULL;
+    dev->coreGrab.sync.evcount = 0;
+    dev->coreGrab.grab = NullGrab;
+    dev->coreGrab.grabTime = currentTime;
+    dev->coreGrab.fromPassiveGrab = FALSE;
+
+    /* device grab defaults */
+    dev->deviceGrab.sync.frozen = FALSE;
+    dev->deviceGrab.sync.other = NullGrab;
+    dev->deviceGrab.sync.state = NOT_GRABBED;
+    dev->deviceGrab.sync.event = (xEvent *) NULL;
+    dev->deviceGrab.sync.evcount = 0;
+    dev->deviceGrab.grab = NullGrab;
+    dev->deviceGrab.grabTime = currentTime;
+    dev->deviceGrab.fromPassiveGrab = FALSE;
+
     dev->key = (KeyClassPtr)NULL;
     dev->valuator = (ValuatorClassPtr)NULL;
     dev->button = (ButtonClassPtr)NULL;
@@ -339,8 +352,8 @@ InitCoreDevices()
         dev->public.processInputProc = ProcessKeyboardEvent;
         dev->public.realInputProc = ProcessKeyboardEvent;
 #endif
-        dev->ActivateGrab = ActivateKeyboardGrab;
-        dev->DeactivateGrab = DeactivateKeyboardGrab;
+        dev->coreGrab.ActivateGrab = ActivateKeyboardGrab;
+        dev->coreGrab.DeactivateGrab = DeactivateKeyboardGrab;
         dev->coreEvents = FALSE;
         dev->spriteOwner = FALSE;
         if (!AllocateDevicePrivate(dev, CoreDevicePrivatesIndex))
@@ -372,8 +385,8 @@ InitCoreDevices()
         dev->public.processInputProc = ProcessPointerEvent;
         dev->public.realInputProc = ProcessPointerEvent;
 #endif
-        dev->ActivateGrab = ActivatePointerGrab;
-        dev->DeactivateGrab = DeactivatePointerGrab;
+        dev->coreGrab.ActivateGrab = ActivatePointerGrab;
+        dev->coreGrab.DeactivateGrab = DeactivatePointerGrab;
         dev->coreEvents = FALSE;
         if (!AllocateDevicePrivate(dev, CoreDevicePrivatesIndex))
             FatalError("Couldn't allocate pointer devPrivates\n");
@@ -535,7 +548,8 @@ CloseDevice(register DeviceIntPtr dev)
             PickPointer(clients[j]);
     }
 
-    xfree(dev->sync.event);
+    xfree(dev->coreGrab.sync.event);
+    xfree(dev->deviceGrab.sync.event);
     xfree(dev);
 }
 
@@ -1872,7 +1886,7 @@ ProcGetPointerControl(ClientPtr client)
 void
 MaybeStopHint(register DeviceIntPtr dev, ClientPtr client)
 {
-    GrabPtr grab = dev->grab;
+    GrabPtr grab = dev->coreGrab.grab;
 
     if ((grab && SameClient(grab, client) &&
 	 ((grab->eventMask & PointerMotionHintMask) ||
diff --git a/dix/events.c b/dix/events.c
index 23d5f22..66d63cc 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -478,7 +478,7 @@ XineramaCheckVirtualMotion(
 	pSprite->hot.pScreen = qe->pScreen;  /* should always be Screen 0 */
 	pSprite->hot.x = qe->event->u.keyButtonPointer.rootX;
 	pSprite->hot.y = qe->event->u.keyButtonPointer.rootY;
-	pWin = pDev->grab ? pDev->grab->confineTo :
+	pWin = pDev->coreGrab.grab ? pDev->coreGrab.grab->confineTo :
 					 NullWindow;
     }
     if (pWin)
@@ -801,7 +801,7 @@ CheckVirtualMotion(
 	pSprite->hot.pScreen = qe->pScreen;
 	pSprite->hot.x = qe->event->u.keyButtonPointer.rootX;
 	pSprite->hot.y = qe->event->u.keyButtonPointer.rootY;
-	pWin = pDev->grab ? pDev->grab->confineTo : NullWindow;
+	pWin = pDev->coreGrab.grab ? pDev->coreGrab.grab->confineTo : NullWindow;
     }
     if (pWin)
     {
@@ -916,7 +916,7 @@ static void
 PostNewCursor(DeviceIntPtr pDev)
 {
     register    WindowPtr win;
-    register    GrabPtr grab = pDev->grab;
+    register    GrabPtr grab = pDev->coreGrab.grab;
     SpritePtr   pSprite = pDev->pSprite;
     CursorPtr   pCursor;
 
@@ -1108,7 +1108,7 @@ PlayReleasedEvents(void)
     prev = &syncEvents.pending;
     while ( (qe = *prev) )
     {
-	if (!qe->device->sync.frozen)
+	if (!qe->device->coreGrab.sync.frozen)
 	{
 	    *prev = qe->next;
             pDev = qe->device;
@@ -1134,7 +1134,7 @@ PlayReleasedEvents(void)
 	    (*qe->device->public.processInputProc)(qe->event, qe->device,
 						   qe->evcount);
 	    xfree(qe);
-	    for (dev = inputInfo.devices; dev && dev->sync.frozen; dev = dev->next)
+	    for (dev = inputInfo.devices; dev && dev->coreGrab.sync.frozen; dev = dev->next)
 		;
 	    if (!dev)
 		break;
@@ -1150,7 +1150,7 @@ PlayReleasedEvents(void)
 static void
 FreezeThaw(register DeviceIntPtr dev, Bool frozen)
 {
-    dev->sync.frozen = frozen;
+    dev->coreGrab.sync.frozen = frozen;
     if (frozen)
 	dev->public.processInputProc = dev->public.enqueueInputProc;
     else
@@ -1169,14 +1169,15 @@ ComputeFreezes()
     register DeviceIntPtr dev;
 
     for (dev = inputInfo.devices; dev; dev = dev->next)
-	FreezeThaw(dev, dev->sync.other || (dev->sync.state >= FROZEN));
+	FreezeThaw(dev, dev->coreGrab.sync.other || 
+                (dev->coreGrab.sync.state >= FROZEN));
     if (syncEvents.playingEvents || (!replayDev && !syncEvents.pending))
 	return;
     syncEvents.playingEvents = TRUE;
     if (replayDev)
     {
-	xE = replayDev->sync.event;
-	count = replayDev->sync.evcount;
+	xE = replayDev->coreGrab.sync.event;
+	count = replayDev->coreGrab.sync.evcount;
 	syncEvents.replayDev = (DeviceIntPtr)NULL;
 
         w = XYToWindow( XE_KBPTR.rootX, XE_KBPTR.rootY);
@@ -1203,7 +1204,7 @@ ComputeFreezes()
 playmore:
     for (dev = inputInfo.devices; dev; dev = dev->next)
     {
-	if (!dev->sync.frozen)
+	if (!dev->coreGrab.sync.frozen)
 	{
 	    PlayReleasedEvents();
 	    break;
@@ -1216,7 +1217,7 @@ playmore:
         {
             /* the following may have been skipped during replay, 
               so do it now */
-            if ((grab = dev->grab) && grab->confineTo)
+            if ((grab = dev->coreGrab.grab) && grab->confineTo)
             {
                 if (grab->confineTo->drawable.pScreen !=
                         dev->pSprite->hotPhys.pScreen) 
@@ -1243,7 +1244,9 @@ ScreenRestructured (ScreenPtr pScreen)
     for (pDev = inputInfo.devices; pDev; pDev = pDev->next)
     {
 
-        if ((grab = pDev->grab) && grab->confineTo)
+        /* GrabDevice doesn't have a confineTo field, so we don't need to
+         * worry about it. */
+        if ((grab = pDev->coreGrab.grab) && grab->confineTo)
         {
             if (grab->confineTo->drawable.pScreen 
                     != pDev->pSprite->hotPhys.pScreen)
@@ -1261,31 +1264,31 @@ ScreenRestructured (ScreenPtr pScreen)
 void
 CheckGrabForSyncs(register DeviceIntPtr thisDev, Bool thisMode, Bool otherMode)
 {
-    register GrabPtr grab = thisDev->grab;
+    register GrabPtr grab = thisDev->coreGrab.grab;
     register DeviceIntPtr dev;
 
     if (thisMode == GrabModeSync)
-	thisDev->sync.state = FROZEN_NO_EVENT;
+	thisDev->coreGrab.sync.state = FROZEN_NO_EVENT;
     else
     {	/* free both if same client owns both */
-	thisDev->sync.state = THAWED;
-	if (thisDev->sync.other &&
-	    (CLIENT_BITS(thisDev->sync.other->resource) ==
+	thisDev->coreGrab.sync.state = THAWED;
+	if (thisDev->coreGrab.sync.other &&
+	    (CLIENT_BITS(thisDev->coreGrab.sync.other->resource) ==
 	     CLIENT_BITS(grab->resource)))
-	    thisDev->sync.other = NullGrab;
+	    thisDev->coreGrab.sync.other = NullGrab;
     }
     for (dev = inputInfo.devices; dev; dev = dev->next)
     {
 	if (dev != thisDev)
 	{
 	    if (otherMode == GrabModeSync)
-		dev->sync.other = grab;
+		dev->coreGrab.sync.other = grab;
 	    else
 	    {	/* free both if same client owns both */
-		if (dev->sync.other &&
-		    (CLIENT_BITS(dev->sync.other->resource) ==
+		if (dev->coreGrab.sync.other &&
+		    (CLIENT_BITS(dev->coreGrab.sync.other->resource) ==
 		     CLIENT_BITS(grab->resource)))
-		    dev->sync.other = NullGrab;
+		    dev->coreGrab.sync.other = NullGrab;
 	    }
 	}
     }
@@ -1296,8 +1299,9 @@ void
 ActivatePointerGrab(register DeviceIntPtr mouse, register GrabPtr grab, 
                     TimeStamp time, Bool autoGrab)
 {
-    WindowPtr oldWin = (mouse->grab) ? mouse->grab->window
-				     : mouse->pSprite->win;
+    WindowPtr oldWin = (mouse->coreGrab.grab) ? 
+                        mouse->coreGrab.grab->window
+                        : mouse->pSprite->win;
 
     if (grab->confineTo)
     {
@@ -1309,14 +1313,14 @@ ActivatePointerGrab(register DeviceIntPt
     DoEnterLeaveEvents(mouse, oldWin, grab->window, NotifyGrab);
     mouse->valuator->motionHintWindow = NullWindow;
     if (syncEvents.playingEvents)
-	mouse->grabTime = syncEvents.time;
+        mouse->coreGrab.grabTime = syncEvents.time;
     else
-	mouse->grabTime = time;
+	mouse->coreGrab.grabTime = time;
     if (grab->cursor)
 	grab->cursor->refcnt++;
-    mouse->activeGrab = *grab;
-    mouse->grab = &mouse->activeGrab;
-    mouse->fromPassiveGrab = autoGrab;
+    mouse->coreGrab.activeGrab = *grab;
+    mouse->coreGrab.grab = &mouse->coreGrab.activeGrab;
+    mouse->coreGrab.fromPassiveGrab = autoGrab;
     PostNewCursor(mouse);
     CheckGrabForSyncs(mouse,(Bool)grab->pointerMode, (Bool)grab->keyboardMode);
 }
@@ -1324,17 +1328,17 @@ ActivatePointerGrab(register DeviceIntPt
 void
 DeactivatePointerGrab(register DeviceIntPtr mouse)
 {
-    register GrabPtr grab = mouse->grab;
+    register GrabPtr grab = mouse->coreGrab.grab;
     register DeviceIntPtr dev;
 
     mouse->valuator->motionHintWindow = NullWindow;
-    mouse->grab = NullGrab;
-    mouse->sync.state = NOT_GRABBED;
-    mouse->fromPassiveGrab = FALSE;
+    mouse->coreGrab.grab = NullGrab;
+    mouse->coreGrab.sync.state = NOT_GRABBED;
+    mouse->coreGrab.fromPassiveGrab = FALSE;
     for (dev = inputInfo.devices; dev; dev = dev->next)
     {
-	if (dev->sync.other == grab)
-	    dev->sync.other = NullGrab;
+	if (dev->coreGrab.sync.other == grab)
+	    dev->coreGrab.sync.other = NullGrab;
     }
     DoEnterLeaveEvents(mouse, grab->window, 
                        mouse->pSprite->win, NotifyUngrab);
@@ -1351,8 +1355,8 @@ ActivateKeyboardGrab(register DeviceIntP
 {
     WindowPtr oldWin;
 
-    if (keybd->grab)
-	oldWin = keybd->grab->window;
+    if (keybd->coreGrab.grab)
+	oldWin = keybd->coreGrab.grab->window;
     else if (keybd->focus)
 	oldWin = keybd->focus->win;
     else
@@ -1363,19 +1367,19 @@ ActivateKeyboardGrab(register DeviceIntP
 	keybd->valuator->motionHintWindow = NullWindow;
     DoFocusEvents(keybd, oldWin, grab->window, NotifyGrab);
     if (syncEvents.playingEvents)
-	keybd->grabTime = syncEvents.time;
+	keybd->coreGrab.grabTime = syncEvents.time;
     else
-	keybd->grabTime = time;
-    keybd->activeGrab = *grab;
-    keybd->grab = &keybd->activeGrab;
-    keybd->fromPassiveGrab = passive;
+	keybd->coreGrab.grabTime = time;
+    keybd->coreGrab.activeGrab = *grab;
+    keybd->coreGrab.grab = &keybd->coreGrab.activeGrab;
+    keybd->coreGrab.fromPassiveGrab = passive;
     CheckGrabForSyncs(keybd, (Bool)grab->keyboardMode, (Bool)grab->pointerMode);
 }
 
 void
 DeactivateKeyboardGrab(register DeviceIntPtr keybd)
 {
-    register GrabPtr grab = keybd->grab;
+    register GrabPtr grab = keybd->coreGrab.grab;
     register DeviceIntPtr dev;
     register WindowPtr focusWin = keybd->focus ? keybd->focus->win
 					       : keybd->pSprite->win;
@@ -1384,49 +1388,61 @@ DeactivateKeyboardGrab(register DeviceIn
 	focusWin = inputInfo.keyboard->focus->win;
     if (keybd->valuator)
 	keybd->valuator->motionHintWindow = NullWindow;
-    keybd->grab = NullGrab;
-    keybd->sync.state = NOT_GRABBED;
-    keybd->fromPassiveGrab = FALSE;
+    keybd->coreGrab.grab = NullGrab;
+    keybd->coreGrab.sync.state = NOT_GRABBED;
+    keybd->coreGrab.fromPassiveGrab = FALSE;
     for (dev = inputInfo.devices; dev; dev = dev->next)
     {
-	if (dev->sync.other == grab)
-	    dev->sync.other = NullGrab;
+	if (dev->coreGrab.sync.other == grab)
+	    dev->coreGrab.sync.other = NullGrab;
     }
     DoFocusEvents(keybd, grab->window, focusWin, NotifyUngrab);
     ComputeFreezes();
 }
 
+/* 
+ * Core flag decides whether to work on the coreGrab or deviceGrab sync
+ * fields.
+ */
 void
-AllowSome(ClientPtr client, TimeStamp time, DeviceIntPtr thisDev, int newState)
+AllowSome(ClientPtr client, 
+          TimeStamp time, 
+          DeviceIntPtr thisDev, 
+          int newState, 
+          Bool core)
 {
     Bool thisGrabbed, otherGrabbed, othersFrozen, thisSynced;
     TimeStamp grabTime;
     register DeviceIntPtr dev;
+    GrabInfoPtr devgrabinfo, 
+                grabinfo = (core) ? &thisDev->coreGrab : &thisDev->deviceGrab;
 
-    thisGrabbed = thisDev->grab && SameClient(thisDev->grab, client);
+    thisGrabbed = grabinfo->grab && SameClient(grabinfo->grab, client);
     thisSynced = FALSE;
     otherGrabbed = FALSE;
     othersFrozen = TRUE;
-    grabTime = thisDev->grabTime;
+    grabTime = grabinfo->grabTime;
     for (dev = inputInfo.devices; dev; dev = dev->next)
     {
+        devgrabinfo = (core) ? &dev->coreGrab : &dev->deviceGrab;
+
 	if (dev == thisDev)
 	    continue;
-	if (dev->grab && SameClient(dev->grab, client))
+	if (devgrabinfo->grab && SameClient(devgrabinfo->grab, client))
 	{
 	    if (!(thisGrabbed || otherGrabbed) ||
-		(CompareTimeStamps(dev->grabTime, grabTime) == LATER))
-		grabTime = dev->grabTime;
+		(CompareTimeStamps(devgrabinfo->grabTime, grabTime) == LATER))
+		grabTime = devgrabinfo->grabTime;
 	    otherGrabbed = TRUE;
-	    if (thisDev->sync.other == dev->grab)
+	    if (grabinfo->sync.other == devgrabinfo->grab)
 		thisSynced = TRUE;
-	    if (dev->sync.state < FROZEN)
+	    if (devgrabinfo->sync.state < FROZEN)
 		othersFrozen = FALSE;
 	}
-	else if (!dev->sync.other || !SameClient(dev->sync.other, client))
+	else if (!devgrabinfo->sync.other || !SameClient(devgrabinfo->sync.other, client))
 	    othersFrozen = FALSE;
     }
-    if (!((thisGrabbed && thisDev->sync.state >= FROZEN) || thisSynced))
+    if (!((thisGrabbed && grabinfo->sync.state >= FROZEN) || thisSynced))
 	return;
     if ((CompareTimeStamps(time, currentTime) == LATER) ||
 	(CompareTimeStamps(time, grabTime) == EARLIER))
@@ -1435,17 +1451,17 @@ AllowSome(ClientPtr client, TimeStamp ti
     {
 	case THAWED:	 	       /* Async */
 	    if (thisGrabbed)
-		thisDev->sync.state = THAWED;
+		grabinfo->sync.state = THAWED;
 	    if (thisSynced)
-		thisDev->sync.other = NullGrab;
+		grabinfo->sync.other = NullGrab;
 	    ComputeFreezes();
 	    break;
 	case FREEZE_NEXT_EVENT:		/* Sync */
 	    if (thisGrabbed)
 	    {
-		thisDev->sync.state = FREEZE_NEXT_EVENT;
+		grabinfo->sync.state = FREEZE_NEXT_EVENT;
 		if (thisSynced)
-		    thisDev->sync.other = NullGrab;
+		    grabinfo->sync.other = NullGrab;
 		ComputeFreezes();
 	    }
 	    break;
@@ -1454,10 +1470,13 @@ AllowSome(ClientPtr client, TimeStamp ti
 	    {
 		for (dev = inputInfo.devices; dev; dev = dev->next)
 		{
-		    if (dev->grab && SameClient(dev->grab, client))
-			dev->sync.state = THAWED;
-		    if (dev->sync.other && SameClient(dev->sync.other, client))
-			dev->sync.other = NullGrab;
+                    devgrabinfo = (core) ? &dev->coreGrab : &dev->deviceGrab;
+		    if (devgrabinfo->grab 
+                            && SameClient(devgrabinfo->grab, client))
+			devgrabinfo->sync.state = THAWED;
+		    if (devgrabinfo->sync.other && 
+                            SameClient(devgrabinfo->sync.other, client))
+			devgrabinfo->sync.other = NullGrab;
 		}
 		ComputeFreezes();
 	    }
@@ -1467,22 +1486,25 @@ AllowSome(ClientPtr client, TimeStamp ti
 	    {
 		for (dev = inputInfo.devices; dev; dev = dev->next)
 		{
-		    if (dev->grab && SameClient(dev->grab, client))
-			dev->sync.state = FREEZE_BOTH_NEXT_EVENT;
-		    if (dev->sync.other && SameClient(dev->sync.other, client))
-			dev->sync.other = NullGrab;
+                    devgrabinfo = (core) ? &dev->coreGrab : &dev->deviceGrab;
+		    if (devgrabinfo->grab 
+                            && SameClient(devgrabinfo->grab, client))
+			devgrabinfo->sync.state = FREEZE_BOTH_NEXT_EVENT;
+		    if (devgrabinfo->sync.other 
+                            && SameClient(devgrabinfo->sync.other, client))
+			devgrabinfo->sync.other = NullGrab;
 		}
 		ComputeFreezes();
 	    }
 	    break;
 	case NOT_GRABBED:		/* Replay */
-	    if (thisGrabbed && thisDev->sync.state == FROZEN_WITH_EVENT)
+	    if (thisGrabbed && grabinfo->sync.state == FROZEN_WITH_EVENT)
 	    {
 		if (thisSynced)
-		    thisDev->sync.other = NullGrab;
+		    grabinfo->sync.other = NullGrab;
 		syncEvents.replayDev = thisDev;
-		syncEvents.replayWin = thisDev->grab->window;
-		(*thisDev->DeactivateGrab)(thisDev);
+		syncEvents.replayWin = grabinfo->grab->window;
+		(*grabinfo->DeactivateGrab)(thisDev);
 		syncEvents.replayDev = (DeviceIntPtr)NULL;
 	    }
 	    break;
@@ -1493,10 +1515,13 @@ AllowSome(ClientPtr client, TimeStamp ti
 		{
 		    if (dev == thisDev)
 			continue;
-		    if (dev->grab && SameClient(dev->grab, client))
-			dev->sync.state = THAWED;
-		    if (dev->sync.other && SameClient(dev->sync.other, client))
-			dev->sync.other = NullGrab;
+                    devgrabinfo = (core) ? &dev->coreGrab : &dev->deviceGrab;
+		    if (devgrabinfo->grab 
+                            && SameClient(devgrabinfo->grab, client))
+			devgrabinfo->sync.state = THAWED;
+		    if (devgrabinfo->sync.other 
+                            && SameClient(devgrabinfo->sync.other, client))
+			devgrabinfo->sync.other = NullGrab;
 		}
 		ComputeFreezes();
 	    }
@@ -1517,28 +1542,28 @@ ProcAllowEvents(register ClientPtr clien
     switch (stuff->mode)
     {
 	case ReplayPointer:
-	    AllowSome(client, time, mouse, NOT_GRABBED);
+	    AllowSome(client, time, mouse, NOT_GRABBED, True);
 	    break;
 	case SyncPointer: 
-	    AllowSome(client, time, mouse, FREEZE_NEXT_EVENT);
+	    AllowSome(client, time, mouse, FREEZE_NEXT_EVENT, True);
 	    break;
 	case AsyncPointer: 
-	    AllowSome(client, time, mouse, THAWED);
+	    AllowSome(client, time, mouse, THAWED, True);
 	    break;
 	case ReplayKeyboard: 
-	    AllowSome(client, time, keybd, NOT_GRABBED);
+	    AllowSome(client, time, keybd, NOT_GRABBED, True);
 	    break;
 	case SyncKeyboard: 
-	    AllowSome(client, time, keybd, FREEZE_NEXT_EVENT);
+	    AllowSome(client, time, keybd, FREEZE_NEXT_EVENT, True);
 	    break;
 	case AsyncKeyboard: 
-	    AllowSome(client, time, keybd, THAWED);
+	    AllowSome(client, time, keybd, THAWED, True);
 	    break;
 	case SyncBoth:
-	    AllowSome(client, time, keybd, FREEZE_BOTH_NEXT_EVENT);
+	    AllowSome(client, time, keybd, FREEZE_BOTH_NEXT_EVENT, True);
 	    break;
 	case AsyncBoth:
-	    AllowSome(client, time, keybd, THAWED_BOTH);
+	    AllowSome(client, time, keybd, THAWED_BOTH, True);
 	    break;
 	default: 
 	    client->errorValue = stuff->mode;
@@ -1560,9 +1585,15 @@ ReleaseActiveGrabs(ClientPtr client)
     	done = TRUE;
     	for (dev = inputInfo.devices; dev; dev = dev->next)
     	{
-	    if (dev->grab && SameClient(dev->grab, client))
+	    if (dev->coreGrab.grab && SameClient(dev->coreGrab.grab, client))
 	    {
-	    	(*dev->DeactivateGrab)(dev);
+	    	(*dev->coreGrab.DeactivateGrab)(dev);
+	    	done = FALSE;
+	    }
+
+	    if (dev->deviceGrab.grab && SameClient(dev->deviceGrab.grab, client))
+	    {
+	    	(*dev->deviceGrab.DeactivateGrab)(dev);
 	    	done = FALSE;
 	    }
     	}
@@ -1730,7 +1761,7 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 	tempGrab.confineTo = NullWindow;
 	tempGrab.cursor = NullCursor;
         tempGrab.coreGrab = True;
-	(*inputInfo.pointer->ActivateGrab)(pDev, &tempGrab,
+	(*inputInfo.pointer->coreGrab.ActivateGrab)(pDev, &tempGrab,
 					   currentTime, TRUE);
     }
     else if ((type == MotionNotify) && deliveries)
@@ -2175,7 +2206,7 @@ void ReinitializeRootWindow(WindowPtr wi
                 REGION_TRANSLATE(pSprite->screen, &pSprite->Reg2,    xoff, yoff);
 
             /* FIXME: if we call ConfineCursorToWindow, must we do anything else? */
-            if ((grab = pDev->grab) && grab->confineTo) {
+            if ((grab = pDev->coreGrab.grab) && grab->confineTo) {
                 if (grab->confineTo->drawable.pScreen 
                         != pSprite->hotPhys.pScreen)
                     pSprite->hotPhys.x = pSprite->hotPhys.y = 0;
@@ -2576,6 +2607,7 @@ CheckPassiveGrabsOnWindow(
 {
     register GrabPtr grab = wPassiveGrabs(pWin);
     GrabRec tempGrab;
+    GrabInfoPtr grabinfo;
     register xEvent *dxE;
 
     if (!grab)
@@ -2629,7 +2661,9 @@ CheckPassiveGrabsOnWindow(
 				tempGrab.modifiersDetail.exact&(~0x1f00);
 	    }
 #endif
-	    (*device->ActivateGrab)(device, grab, currentTime, TRUE);
+            grabinfo = (xE->u.u.type & EXTENSION_EVENT_BASE) ? 
+                &device->deviceGrab : &device->coreGrab;
+	    (*grabinfo->ActivateGrab)(device, grab, currentTime, TRUE);
  
 	    FixUpEventFromWindow(device, xE, grab->window, None, TRUE);
 
@@ -2637,20 +2671,20 @@ CheckPassiveGrabsOnWindow(
 				   filters[xE->u.u.type],
 				   filters[xE->u.u.type],  grab);
 
-	    if (device->sync.state == FROZEN_NO_EVENT)
+	    if (grabinfo->sync.state == FROZEN_NO_EVENT)
 	    {
-		if (device->sync.evcount < count)
+		if (grabinfo->sync.evcount < count)
 		{
 		    Must_have_memory = TRUE; /* XXX */
-		    device->sync.event = (xEvent *)xrealloc(device->sync.event,
+		    grabinfo->sync.event = (xEvent *)xrealloc(grabinfo->sync.event,
 							    count*
 							    sizeof(xEvent));
 		    Must_have_memory = FALSE; /* XXX */
 		}
-		device->sync.evcount = count;
-		for (dxE = device->sync.event; --count >= 0; dxE++, xE++)
+		grabinfo->sync.evcount = count;
+		for (dxE = grabinfo->sync.event; --count >= 0; dxE++, xE++)
 		    *dxE = *xE;
-	    	device->sync.state = FROZEN_WITH_EVENT;
+	    	grabinfo->sync.state = FROZEN_WITH_EVENT;
             }	
 	    return TRUE;
 	}
@@ -2747,12 +2781,20 @@ void
 DeliverGrabbedEvent(register xEvent *xE, register DeviceIntPtr thisDev, 
                     Bool deactivateGrab, int count)
 {
-    register GrabPtr grab = thisDev->grab;
+    register GrabPtr grab;
+    GrabInfoPtr grabinfo;
     int deliveries = 0;
     register DeviceIntPtr dev;
     register xEvent *dxE;
     SpritePtr pSprite = thisDev->pSprite;
 
+    if (xE->u.u.type & EXTENSION_EVENT_BASE)
+        grabinfo = &thisDev->deviceGrab;
+    else
+        grabinfo = &thisDev->coreGrab;
+
+    grab = grabinfo->grab;
+
     if (grab->ownerEvents)
     {
 	WindowPtr focus;
@@ -2798,7 +2840,7 @@ DeliverGrabbedEvent(register xEvent *xE,
 					  && xE->u.u.type != DeviceMotionNotify
 #endif
 					  ))
-	switch (thisDev->sync.state)
+	switch (grabinfo->sync.state)
 	{
 	case FREEZE_BOTH_NEXT_EVENT:
 	    for (dev = inputInfo.devices; dev; dev = dev->next)
@@ -2806,26 +2848,26 @@ DeliverGrabbedEvent(register xEvent *xE,
 		if (dev == thisDev)
 		    continue;
 		FreezeThaw(dev, TRUE);
-		if ((dev->sync.state == FREEZE_BOTH_NEXT_EVENT) &&
-		    (CLIENT_BITS(dev->grab->resource) ==
-		     CLIENT_BITS(thisDev->grab->resource)))
-		    dev->sync.state = FROZEN_NO_EVENT;
+		if ((grabinfo->sync.state == FREEZE_BOTH_NEXT_EVENT) &&
+		    (CLIENT_BITS(grab->resource) ==
+		     CLIENT_BITS(grab->resource)))
+		    grabinfo->sync.state = FROZEN_NO_EVENT;
 		else
-		    dev->sync.other = thisDev->grab;
+		    grabinfo->sync.other = grab;
 	    }
 	    /* fall through */
 	case FREEZE_NEXT_EVENT:
-	    thisDev->sync.state = FROZEN_WITH_EVENT;
+	    grabinfo->sync.state = FROZEN_WITH_EVENT;
 	    FreezeThaw(thisDev, TRUE);
-	    if (thisDev->sync.evcount < count)
+	    if (grabinfo->sync.evcount < count)
 	    {
 		Must_have_memory = TRUE; /* XXX */
-		thisDev->sync.event = (xEvent *)xrealloc(thisDev->sync.event,
+		grabinfo->sync.event = (xEvent *)xrealloc(grabinfo->sync.event,
 							 count*sizeof(xEvent));
 		Must_have_memory = FALSE; /* XXX */
 	    }
-	    thisDev->sync.evcount = count;
-	    for (dxE = thisDev->sync.event; --count >= 0; dxE++, xE++)
+	    grabinfo->sync.evcount = count;
+	    for (dxE = grabinfo->sync.event; --count >= 0; dxE++, xE++)
 		*dxE = *xE;
 	    break;
 	}
@@ -2843,9 +2885,11 @@ ProcessKeyboardEvent (register xEvent *x
     register int    i;
     register CARD8  modifiers;
     register CARD16 mask;
-    GrabPtr         grab = keybd->grab;
+    register GrabPtr         grab;
+    GrabInfoPtr     grabinfo;
     Bool            deactivateGrab = FALSE;
     register KeyClassPtr keyc = keybd->key;
+
 #ifdef XEVIE
     static Window           rootWin = 0;
 
@@ -2886,6 +2930,13 @@ drawable.id:0;
     }
 #endif
 
+    if (xE->u.u.type & EXTENSION_EVENT_BASE)
+        grabinfo = &keybd->deviceGrab;
+    else
+        grabinfo = &keybd->coreGrab;
+
+    grab = grabinfo->grab;
+
     if (!syncEvents.playingEvents)
     {
 	NoticeTime(xE);
@@ -2954,7 +3005,7 @@ drawable.id:0;
 	    }
 	    if (!grab && CheckDeviceGrabs(keybd, xE, 0, count))
 	    {
-		keybd->activatingKey = key;
+		grabinfo->activatingKey = key;
 		return;
 	    }
 	    break;
@@ -2975,7 +3026,7 @@ drawable.id:0;
 		    modifiers &= ~mask;
 		}
 	    }
-	    if (keybd->fromPassiveGrab && (key == keybd->activatingKey))
+	    if (grabinfo->fromPassiveGrab && (key == grabinfo->activatingKey))
 		deactivateGrab = TRUE;
 	    break;
 	default: 
@@ -2986,7 +3037,7 @@ drawable.id:0;
     else
 	DeliverFocusedEvent(keybd, xE, keybd->pSprite->win, count);
     if (deactivateGrab)
-        (*keybd->DeactivateGrab)(keybd);
+        (*grabinfo->DeactivateGrab)(keybd);
 
     XaceHook(XACE_KEY_AVAIL, xE, keybd, count);
 }
@@ -3033,7 +3084,7 @@ CoreProcessPointerEvent (register xEvent
 ProcessPointerEvent (register xEvent *xE, register DeviceIntPtr mouse, int count)
 #endif
 {
-    register GrabPtr	grab = mouse->grab;
+    GrabPtr	        grab = mouse->coreGrab.grab;
     Bool                deactivateGrab = FALSE;
     register ButtonClassPtr butc = mouse->button;
     SpritePtr           pSprite = mouse->pSprite;
@@ -3120,7 +3171,7 @@ ProcessPointerEvent (register xEvent *xE
 	    if (xE->u.u.detail <= 5)
 		butc->state &= ~((Button1Mask >> 1) << xE->u.u.detail);
 	    filters[MotionNotify] = Motion_Filter(butc);
-	    if (!butc->state && mouse->fromPassiveGrab)
+	    if (!butc->state && mouse->coreGrab.fromPassiveGrab)
 		deactivateGrab = TRUE;
 	    break;
 	default: 
@@ -3135,7 +3186,7 @@ ProcessPointerEvent (register xEvent *xE
 	DeliverDeviceEvents(pSprite->win, xE, NullGrab, NullWindow,
 			    mouse, count);
     if (deactivateGrab)
-        (*mouse->DeactivateGrab)(mouse);
+        (*mouse->coreGrab.DeactivateGrab)(mouse);
 }
 
 #define AtMostOneClient \
@@ -3277,7 +3328,7 @@ maskSet: 
     if ((inputInfo.pointer->valuator->motionHintWindow == pWin) &&
 	(mask & PointerMotionHintMask) &&
 	!(check & PointerMotionHintMask) &&
-	!inputInfo.pointer->grab)
+	!inputInfo.pointer->coreGrab.grab) /* VCP shouldn't have deviceGrab */
 	inputInfo.pointer->valuator->motionHintWindow = NullWindow;
     RecalculateDeliverableEvents(pWin);
     return Success;
@@ -3362,7 +3413,8 @@ EnterLeaveEvent(
     register DeviceIntPtr keybd = inputInfo.keyboard;
     WindowPtr		focus;
     register DeviceIntPtr mouse = pDev;
-    register GrabPtr	grab = mouse->grab;
+    GrabPtr	        grab = mouse->coreGrab.grab;
+    GrabPtr	        devgrab = mouse->deviceGrab.grab;
     Mask		mask;
 
     deviceEnterNotify   *devEnterLeave;
@@ -3430,9 +3482,9 @@ EnterLeaveEvent(
     if (inputMasks && 
        (filters[devEnterLeave->type] & inputMasks->deliverableEvents[mskidx]))
     {
-        if (grab)
-            (void)TryClientEvents(rClient(grab), (xEvent*)devEnterLeave, 1,
-                                  mask, filters[devEnterLeave->type], grab);
+        if (devgrab)
+            (void)TryClientEvents(rClient(devgrab), (xEvent*)devEnterLeave, 1,
+                                mask, filters[devEnterLeave->type], devgrab);
 	else
 	    (void)DeliverEventsToWindow(pDev, pWin, (xEvent*)devEnterLeave, 
                                         1, filters[devEnterLeave->type], 
@@ -3776,7 +3828,7 @@ SetInputFocus(
     if ((CompareTimeStamps(time, currentTime) == LATER) ||
 	(CompareTimeStamps(time, focus->time) == EARLIER))
 	return Success;
-    mode = (dev->grab) ? NotifyWhileGrabbed : NotifyNormal;
+    mode = (dev->coreGrab.grab) ? NotifyWhileGrabbed : NotifyNormal;
     if (focus->win == FollowKeyboardWin)
 	DoFocusEvents(dev, inputInfo.keyboard->focus->win, focusWin, mode);
     else
@@ -3912,7 +3964,7 @@ ProcGrabPointer(ClientPtr client)
     rep.type = X_Reply;
     rep.sequenceNumber = client->sequence;
     rep.length = 0;
-    grab = device->grab;
+    grab = device->coreGrab.grab;
     if ((grab) && !SameClient(grab, client))
 	rep.status = AlreadyGrabbed;
     else if ((!pWin->realized) ||
@@ -3920,11 +3972,12 @@ ProcGrabPointer(ClientPtr client)
                 !(confineTo->realized 
                     && BorderSizeNotEmpty(device, confineTo))))
 	rep.status = GrabNotViewable;
-    else if (device->sync.frozen &&
-	     device->sync.other && !SameClient(device->sync.other, client))
+    else if (device->coreGrab.sync.frozen &&
+	     device->coreGrab.sync.other && 
+             !SameClient(device->coreGrab.sync.other, client))
 	rep.status = GrabFrozen;
     else if ((CompareTimeStamps(time, currentTime) == LATER) ||
-	     (CompareTimeStamps(time, device->grabTime) == EARLIER))
+	     (CompareTimeStamps(time, device->coreGrab.grabTime) == EARLIER))
 	rep.status = GrabInvalidTime;
     else
     {
@@ -3948,7 +4001,7 @@ ProcGrabPointer(ClientPtr client)
 	tempGrab.pointerMode = stuff->pointerMode;
 	tempGrab.device = device;
         tempGrab.coreGrab = True;
-	(*device->ActivateGrab)(device, &tempGrab, time, FALSE);
+	(*device->coreGrab.ActivateGrab)(device, &tempGrab, time, FALSE);
 	if (oldCursor)
 	    FreeCursor (oldCursor, (Cursor)0);
 	rep.status = GrabSuccess;
@@ -3961,7 +4014,7 @@ int
 ProcChangeActivePointerGrab(ClientPtr client)
 {
     DeviceIntPtr device = PickPointer(client);
-    register GrabPtr grab = device->grab;
+    register GrabPtr grab = device->coreGrab.grab;
     CursorPtr newCursor, oldCursor;
     REQUEST(xChangeActivePointerGrabReq);
     TimeStamp time;
@@ -3990,7 +4043,7 @@ ProcChangeActivePointerGrab(ClientPtr cl
 	return Success;
     time = ClientTimeToServerTime(stuff->time);
     if ((CompareTimeStamps(time, currentTime) == LATER) ||
-	     (CompareTimeStamps(time, device->grabTime) == EARLIER))
+	     (CompareTimeStamps(time, device->coreGrab.grabTime) == EARLIER))
 	return Success;
     oldCursor = grab->cursor;
     grab->cursor = newCursor;
@@ -4013,12 +4066,12 @@ ProcUngrabPointer(ClientPtr client)
 
     REQUEST_SIZE_MATCH(xResourceReq);
     UpdateCurrentTime();
-    grab = device->grab;
+    grab = device->coreGrab.grab;
     time = ClientTimeToServerTime(stuff->id);
     if ((CompareTimeStamps(time, currentTime) != LATER) &&
-	    (CompareTimeStamps(time, device->grabTime) != EARLIER) &&
+	    (CompareTimeStamps(time, device->coreGrab.grabTime) != EARLIER) &&
 	    (grab) && SameClient(grab, client))
-	(*device->DeactivateGrab)(device);
+	(*device->coreGrab.DeactivateGrab)(device);
     return Success;
 }
 
@@ -4052,16 +4105,16 @@ GrabDevice(register ClientPtr client, re
     if (rc != Success)
 	return rc;
     time = ClientTimeToServerTime(ctime);
-    grab = dev->grab;
+    grab = dev->coreGrab.grab;
     if (grab && !SameClient(grab, client))
 	*status = AlreadyGrabbed;
     else if (!pWin->realized)
 	*status = GrabNotViewable;
     else if ((CompareTimeStamps(time, currentTime) == LATER) ||
-	     (CompareTimeStamps(time, dev->grabTime) == EARLIER))
+	     (CompareTimeStamps(time, dev->coreGrab.grabTime) == EARLIER))
 	*status = GrabInvalidTime;
-    else if (dev->sync.frozen &&
-	     dev->sync.other && !SameClient(dev->sync.other, client))
+    else if (dev->coreGrab.sync.frozen &&
+	     dev->coreGrab.sync.other && !SameClient(dev->coreGrab.sync.other, client))
 	*status = GrabFrozen;
     else
     {
@@ -4079,7 +4132,7 @@ GrabDevice(register ClientPtr client, re
 	tempGrab.device = dev;
         tempGrab.cursor = NULL;
 
-	(*dev->ActivateGrab)(dev, &tempGrab, time, FALSE);
+	(*dev->coreGrab.ActivateGrab)(dev, &tempGrab, time, FALSE);
 	*status = GrabSuccess;
     }
     return Success;
@@ -4123,12 +4176,12 @@ ProcUngrabKeyboard(ClientPtr client)
 
     REQUEST_SIZE_MATCH(xResourceReq);
     UpdateCurrentTime();
-    grab = device->grab;
+    grab = device->coreGrab.grab;
     time = ClientTimeToServerTime(stuff->id);
     if ((CompareTimeStamps(time, currentTime) != LATER) &&
-	(CompareTimeStamps(time, device->grabTime) != EARLIER) &&
+	(CompareTimeStamps(time, device->coreGrab.grabTime) != EARLIER) &&
 	(grab) && SameClient(grab, client))
-	(*device->DeactivateGrab)(device);
+	(*device->coreGrab.DeactivateGrab)(device);
     return Success;
 }
 
@@ -4547,19 +4600,21 @@ DeleteWindowFromAnyEvents(WindowPtr pWin
     FocusClassPtr	focus = keybd->focus;
     OtherClientsPtr	oc;
     GrabPtr		passive;
+    GrabPtr             grab; 
 
 
     /* Deactivate any grabs performed on this window, before making any
 	input focus changes. */
-
-    if (mouse->grab &&
-	((mouse->grab->window == pWin) || (mouse->grab->confineTo == pWin)))
-	(*mouse->DeactivateGrab)(mouse);
+    grab = mouse->coreGrab.grab;
+    if (grab &&
+	((grab->window == pWin) || (grab->confineTo == pWin)))
+	(*mouse->coreGrab.DeactivateGrab)(mouse);
 
     /* Deactivating a keyboard grab should cause focus events. */
 
-    if (keybd->grab && (keybd->grab->window == pWin))
-	(*keybd->DeactivateGrab)(keybd);
+    grab = keybd->coreGrab.grab;
+    if (grab && (grab->window == pWin))
+	(*keybd->coreGrab.DeactivateGrab)(keybd);
 
     /* If the focus window is a root window (ie. has no parent) then don't 
 	delete the focus from it. */
@@ -4570,7 +4625,7 @@ DeleteWindowFromAnyEvents(WindowPtr pWin
 
  	/* If a grab is in progress, then alter the mode of focus events. */
 
-	if (keybd->grab)
+	if (keybd->coreGrab.grab)
 	    focusEventMode = NotifyWhileGrabbed;
 
 	switch (focus->revert)
@@ -4644,11 +4699,11 @@ CheckCursorConfinement(WindowPtr pWin)
     {
         if (DevHasCursor(pDev))
         {
-            grab = pDev->grab;
+            grab = pDev->coreGrab.grab;
             if (grab && (confineTo = grab->confineTo))
             {
                 if (!BorderSizeNotEmpty(pDev, confineTo))
-                    (*inputInfo.pointer->DeactivateGrab)(pDev);
+                    (*inputInfo.pointer->coreGrab.DeactivateGrab)(pDev);
                 else if ((pWin == confineTo) || IsParent(pWin, confineTo))
                     ConfineCursorToWindow(pDev, confineTo, TRUE, TRUE);
             }
diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index c0e21dd..2981e17 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -2478,8 +2478,6 @@ xf86HandleConfigFile(Bool autoconfig)
              return CONFIG_PARSE_ERROR;
     }
 
-    checkInput(&xf86ConfigLayout);
-
     /*
      * Handle some command line options that can override some of the
      * ServerFlags settings.
diff --git a/hw/xfree86/common/xf86DGA.c b/hw/xfree86/common/xf86DGA.c
index 204457f..9a24040 100644
--- a/hw/xfree86/common/xf86DGA.c
+++ b/hw/xfree86/common/xf86DGA.c
@@ -1030,9 +1030,11 @@ DGAProcessKeyboardEvent (ScreenPtr pScre
     else
     {
 	/* If the keyboard is actively grabbed, deliver a grabbed core event */
-	if (keybd->grab && !keybd->fromPassiveGrab)
+	if (keybd->coreGrab.grab && !keybd->coreGrab.fromPassiveGrab)
 	{
-	    core.u.u.type		    = coreEquiv;
+            /* I've got no clue if that is correct but only working on core
+             * grabs seems the right thing here. (whot) */
+            core.u.u.type		    = coreEquiv;
 	    core.u.u.detail		    = de->u.u.detail;
 	    core.u.keyButtonPointer.time    = de->u.event.time;
 	    core.u.keyButtonPointer.eventX  = de->u.event.dx;
@@ -1109,8 +1111,10 @@ DGAProcessPointerEvent (ScreenPtr pScree
     else
     {
 	/* If the pointer is actively grabbed, deliver a grabbed core event */
-	if (mouse->grab && !mouse->fromPassiveGrab)
+	if (mouse->coreGrab.grab && !mouse->coreGrab.fromPassiveGrab)
 	{
+            /* I've got no clue if that is correct but only working on core
+             * grabs seems the right thing here. (whot) */
 	    core.u.u.type		    = coreEquiv;
 	    core.u.u.detail		    = de->u.u.detail;
 	    core.u.keyButtonPointer.time    = de->u.event.time;
diff --git a/hw/xfree86/common/xf86Events.c b/hw/xfree86/common/xf86Events.c
index 5f43714..a91f6b3 100644
--- a/hw/xfree86/common/xf86Events.c
+++ b/hw/xfree86/common/xf86Events.c
@@ -290,12 +290,13 @@ xf86ProcessActionEvent(ActionEvent actio
 	break;
     case ACTION_DISABLEGRAB:
 	if (!xf86Info.grabInfo.disabled && xf86Info.grabInfo.allowDeactivate) {
-	  if (inputInfo.pointer && inputInfo.pointer->grab != NULL &&
-	      inputInfo.pointer->DeactivateGrab)
-	    inputInfo.pointer->DeactivateGrab(inputInfo.pointer);
-	  if (inputInfo.keyboard && inputInfo.keyboard->grab != NULL &&
-	      inputInfo.keyboard->DeactivateGrab)
-	    inputInfo.keyboard->DeactivateGrab(inputInfo.keyboard);
+	  if (inputInfo.pointer && inputInfo.pointer->coreGrab.grab != NULL &&
+	      inputInfo.pointer->coreGrab.DeactivateGrab)
+	    inputInfo.pointer->coreGrab.DeactivateGrab(inputInfo.pointer);
+	  if (inputInfo.keyboard && 
+                  inputInfo.keyboard->coreGrab.grab != NULL &&
+	      inputInfo.keyboard->coreGrab.DeactivateGrab)
+	    inputInfo.keyboard->coreGrab.DeactivateGrab(inputInfo.keyboard);
 	}
 	break;
     case ACTION_CLOSECLIENT:
@@ -303,10 +304,11 @@ xf86ProcessActionEvent(ActionEvent actio
 	  ClientPtr pointer, keyboard, server;
 
 	  pointer = keyboard = server = NULL;
-	  if (inputInfo.pointer && inputInfo.pointer->grab != NULL)
-	    pointer = clients[CLIENT_ID(inputInfo.pointer->grab->resource)];
-	  if (inputInfo.keyboard && inputInfo.keyboard->grab != NULL) {
-	    keyboard = clients[CLIENT_ID(inputInfo.keyboard->grab->resource)];
+	  if (inputInfo.pointer && inputInfo.pointer->coreGrab.grab != NULL)
+	    pointer = clients[CLIENT_ID(inputInfo.pointer->coreGrab.grab->resource)];
+	  if (inputInfo.keyboard && inputInfo.keyboard->coreGrab.grab != NULL)
+          {
+	    keyboard = clients[CLIENT_ID(inputInfo.keyboard->coreGrab.grab->resource)];
 	    if (keyboard == pointer)
 	      keyboard = NULL;
 	  }
diff --git a/include/dix.h b/include/dix.h
index 95c69f0..f22f489 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -469,7 +469,8 @@ extern void AllowSome(
     ClientPtr	/* client */,
     TimeStamp /* time */,
     DeviceIntPtr /* thisDev */,
-    int /* newState */);
+    int /* newState */,
+    Bool /* core */);
 
 extern void ReleaseActiveGrabs(
     ClientPtr client);
diff --git a/include/input.h b/include/input.h
index ca81b1a..2d72f83 100644
--- a/include/input.h
+++ b/include/input.h
@@ -455,7 +455,7 @@ extern DeviceIntPtr GetPairedPointer(Dev
 extern Bool RegisterPairingClient(ClientPtr client);
 extern Bool UnregisterPairingClient(ClientPtr client);
 
-extern DeviceIntPtr GuessFreePointerDevice();
+extern DeviceIntPtr GuessFreePointerDevice(void);
 
 /* Window/device based access control */
 extern Bool ACRegisterClient(ClientPtr client);
diff --git a/include/inputstr.h b/include/inputstr.h
index 90a985b..8c3e560 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -300,11 +300,31 @@ typedef struct {
 #define FROZEN_NO_EVENT		5
 #define FROZEN_WITH_EVENT	6
 #define THAW_OTHERS		7
+typedef struct _GrabInfoRec {
+    TimeStamp	    grabTime;
+    Bool            fromPassiveGrab;
+    GrabRec         activeGrab;
+    GrabPtr         grab;
+    CARD8           activatingKey;
+    void	    (*ActivateGrab) (
+                    DeviceIntPtr /*device*/,
+                    GrabPtr /*grab*/,
+                    TimeStamp /*time*/,
+                    Bool /*autoGrab*/);
+    void	    (*DeactivateGrab)(
+                    DeviceIntPtr /*device*/);
+    struct {
+	Bool		frozen;
+	int		state;
+	GrabPtr		other;		/* if other grab has this frozen */
+	xEvent		*event;		/* saved to be replayed */
+	int		evcount;
+    } sync;
+} GrabInfoRec, *GrabInfoPtr;
 
 typedef struct _DeviceIntRec {
     DeviceRec	public;
     DeviceIntPtr next;
-    TimeStamp	grabTime;
     Bool	startup;		/* true if needs to be turned on at
 				          server intialization time */
     DeviceProc	deviceProc;		/* proc(DevicePtr, DEVICE_xx). It is
@@ -313,27 +333,11 @@ typedef struct _DeviceIntRec {
     Bool	inited;			/* TRUE if INIT returns Success */
     Bool        enabled;                /* TRUE if ON returns Success */
     Bool        coreEvents;             /* TRUE if device also sends core */
-    GrabPtr	grab;			/* the grabber - used by DIX */
-    struct {
-	Bool		frozen;
-	int		state;
-	GrabPtr		other;		/* if other grab has this frozen */
-	xEvent		*event;		/* saved to be replayed */
-	int		evcount;
-    } sync;
+    GrabInfoRec coreGrab;               /* grab on core events */
+    GrabInfoRec deviceGrab;             /* grab on device events */
     Atom		type;
     char		*name;
     CARD8		id;
-    CARD8		activatingKey;
-    Bool		fromPassiveGrab;
-    GrabRec		activeGrab;
-    void		(*ActivateGrab) (
-			DeviceIntPtr /*device*/,
-			GrabPtr /*grab*/,
-			TimeStamp /*time*/,
-			Bool /*autoGrab*/);
-    void		(*DeactivateGrab)(
-			DeviceIntPtr /*device*/);
     KeyClassPtr		key;
     ValuatorClassPtr	valuator;
     ButtonClassPtr	button;
diff --git a/xkb/xkbEvents.c b/xkb/xkbEvents.c
index 139221f..eeb9dec 100644
--- a/xkb/xkbEvents.c
+++ b/xkb/xkbEvents.c
@@ -808,6 +808,7 @@ XkbFilterEvents(ClientPtr pClient,int nE
 int	i, button_mask;
 DeviceIntPtr pXDev = (DeviceIntPtr)LookupKeyboardDevice();
 XkbSrvInfoPtr	xkbi;
+GrabInfoPtr grabinfo;
 
     xkbi= pXDev->key->xkbInfo;
     if ( pClient->xkbClientFlags & _XkbClientInitialized ) {
@@ -831,7 +832,9 @@ XkbSrvInfoPtr	xkbi;
 	     	(_XkbIsReleaseEvent(xE[0].u.u.type)) ) {
 	    return False;
 	}
-	if ((pXDev->grab != NullGrab) && pXDev->fromPassiveGrab &&
+        /* just coreGrab is fine, pXDev is inputInfo.keyboard (see above) */
+	if ((pXDev->coreGrab.grab != NullGrab) 
+                && pXDev->coreGrab.fromPassiveGrab &&
 	    ((xE[0].u.u.type==KeyPress)||(xE[0].u.u.type==KeyRelease))) {
 	    register unsigned state,flags;
 
diff-tree 537bc2ead4d154552cbdc3a19e335f82af63792c (from 39aa79177196e21bcdbaf8e44adead9ef91e6ee5)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Wed Mar 7 18:19:20 2007 +1030

    Xi:    Don't deactivate core grabs from non-core button/key releases.
    
    dix:    set coreGrab flag for grabs caused by GrabPointer and button presses.
            remove virtual core devices from device list, only real devices are in
            the list now.
            Auto-pair each keyboard with a real pointer if one is available,
              provides multiple keyboards automatically after startup if devices
              are configured.
            fix GuessFreePointerDevice() to do what it's supposed to do.
    
    mi:     fix: call miPointerMove from miPointerWarpCursor.
            fix: remove unused id field from miCursorInfoRec
            don't update sprite for virtual core pointer.

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 7e80926..5dbb0e2 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -104,12 +104,12 @@ RegisterOtherDevice(DeviceIntPtr device)
 }
 
  /*ARGSUSED*/ void
-ProcessOtherEvent(xEventPtr xE, register DeviceIntPtr other, int count)
+ProcessOtherEvent(xEventPtr xE, DeviceIntPtr other, int count)
 {
-    register BYTE *kptr;
-    register int i;
-    register CARD16 modifiers;
-    register CARD16 mask;
+    BYTE *kptr;
+    int i;
+    CARD16 modifiers;
+    CARD16 mask;
     GrabPtr grab = other->grab;
     Bool deactivateDeviceGrab = FALSE;
     int key = 0, bit = 0, rootX, rootY;
@@ -229,7 +229,9 @@ ProcessOtherEvent(xEventPtr xE, register
 	    }
 	}
 
-	if (other->fromPassiveGrab && (key == other->activatingKey))
+	if (other->fromPassiveGrab && 
+            !other->grab->coreGrab &&
+            (key == other->activatingKey))
 	    deactivateDeviceGrab = TRUE;
     } else if (xE->u.u.type == DeviceButtonPress) {
         if (!b)
@@ -267,7 +269,9 @@ ProcessOtherEvent(xEventPtr xE, register
 	if (xE->u.u.detail <= 5)
 	    b->state &= ~((Button1Mask >> 1) << xE->u.u.detail);
 	SetMaskForEvent(Motion_Filter(b), DeviceMotionNotify);
-        if (!b->state && other->fromPassiveGrab)
+        if (!b->state 
+            && other->fromPassiveGrab
+            && !other->grab->coreGrab)
             deactivateDeviceGrab = TRUE;
     } else if (xE->u.u.type == ProximityIn)
 	other->valuator->mode &= ~OutOfProximity;
diff --git a/dix/cursor.c b/dix/cursor.c
index cf515c1..e44a5ef 100644
--- a/dix/cursor.c
+++ b/dix/cursor.c
@@ -440,6 +440,33 @@ AllocGlyphCursor(Font source, unsigned s
     for (nscr = 0; nscr < screenInfo.numScreens; nscr++)
     {
         pscr = screenInfo.screens[nscr];
+
+        if (!(*pscr->RealizeCursor)(inputInfo.pointer, pscr, pCurs))
+        {
+            DeviceIntPtr pDevIt = inputInfo.devices; /*dev iterator*/
+            /* Realize for core pointer failed. Unrealize everything from
+             * previous screens.
+             */ 
+            while (--nscr >= 0)
+            {
+                pscr = screenInfo.screens[nscr];
+                /* now unrealize all devices on previous screens */
+                ( *pscr->UnrealizeCursor)(inputInfo.pointer, pscr, pCurs);
+
+                pDevIt = inputInfo.devices;
+                while (pDevIt)
+                {
+                    if (DevHasCursor(pDevIt))
+                        ( *pscr->UnrealizeCursor)(pDevIt, pscr, pCurs);
+                    pDevIt = pDevIt->next;
+                }
+                ( *pscr->UnrealizeCursor)(pDev, pscr, pCurs);
+            }
+            FreeCursorBits(bits);
+            xfree(pCurs);
+            return BadAlloc;
+        }
+
         for (pDev = inputInfo.devices; pDev; pDev = pDev->next)
         {
             if (DevHasCursor(pDev))
@@ -459,10 +486,15 @@ AllocGlyphCursor(Font source, unsigned s
                             ( *pscr->UnrealizeCursor)(pDevIt, pscr, pCurs);
                         pDevIt = pDevIt->next;
                     }
+
+                    (*pscr->UnrealizeCursor)(inputInfo.pointer, pscr, pCurs);
+
                     while (--nscr >= 0)
                     {
                         pscr = screenInfo.screens[nscr];
                         /* now unrealize all devices on previous screens */
+                        ( *pscr->UnrealizeCursor)(inputInfo.pointer, pscr, pCurs);
+
                         pDevIt = inputInfo.devices;
                         while (pDevIt)
                         {
diff --git a/dix/devices.c b/dix/devices.c
index 9195586..9e08794 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -347,7 +347,15 @@ InitCoreDevices()
             FatalError("Couldn't allocate keyboard devPrivates\n");
         dev->devPrivates[CoreDevicePrivatesIndex].ptr = NULL;
         (void)ActivateDevice(dev);
+
+        /* Enable device, and then remove it from the device list. Virtual
+         * devices are kept separate, not in the standard device list. 
+         */
+        if (dev->inited && dev->startup)
+            EnableDevice(dev);
+        inputInfo.off_devices = inputInfo.devices = NULL;
         inputInfo.keyboard = dev;
+        inputInfo.keyboard->next = NULL;
     }
 
     if (!inputInfo.pointer) {
@@ -372,7 +380,17 @@ InitCoreDevices()
         dev->devPrivates[CoreDevicePrivatesIndex].ptr = NULL;
         InitializeSprite(dev, NullWindow);
         (void)ActivateDevice(dev);
+
+        /* Enable device, and then remove it from the device list. Virtual
+         * devices are kept separate, not in the standard device list. 
+         */
+        if (dev->inited && dev->startup)
+            EnableDevice(dev);
+        inputInfo.off_devices = inputInfo.devices = NULL;
         inputInfo.pointer = dev;
+        inputInfo.pointer->next = NULL;
+
+
         /* the core keyboard is initialised by now. set the keyboard's sprite
          * to the core pointer's sprite. */
         PairDevices(pairingClient, inputInfo.pointer, inputInfo.keyboard);
@@ -382,7 +400,7 @@ InitCoreDevices()
 int
 InitAndStartDevices()
 {
-    register DeviceIntPtr dev, next;
+    DeviceIntPtr dev, next;
 
     for (dev = inputInfo.off_devices; dev; dev = dev->next) {
         DebugF("(dix) initialising device %d\n", dev->id);
@@ -395,21 +413,25 @@ InitAndStartDevices()
 	if (dev->inited && dev->startup)
 	    (void)EnableDevice(dev);
     }
-    for (dev = inputInfo.devices;
-	 dev && (dev != inputInfo.keyboard);
-	 dev = dev->next)
-    if (!dev || (dev != inputInfo.keyboard)) {
+
+    if (!inputInfo.keyboard) {
 	ErrorF("No core keyboard\n");
 	return BadImplementation;
     }
-    for (dev = inputInfo.devices;
-	 dev && (dev != inputInfo.pointer);
-	 dev = dev->next)
-	;
-    if (!dev || (dev != inputInfo.pointer)) {
+    if (!inputInfo.pointer) {
 	ErrorF("No core pointer\n");
 	return BadImplementation;
     }
+
+    /* All of the devices are started up now. Try to pair each keyboard with a
+     * real pointer, if possible. */
+    for (dev = inputInfo.devices; dev; dev = dev->next)
+    {
+        if (!DevHasCursor(dev))
+            PairDevices(NULL, GuessFreePointerDevice(), dev);
+    }
+
+
     return Success;
 }
 
@@ -2043,7 +2065,7 @@ GuessFreePointerDevice()
     while(it)
     {
         /* found device with a sprite? */
-        if (it != inputInfo.pointer && it->spriteOwner)
+        if (it->spriteOwner)
         {
             lastRealPtr = it;
 
@@ -2057,11 +2079,9 @@ GuessFreePointerDevice()
                 it2 = it2->next;
             }
 
-            if (it2)
-                break;
-
             /* woohoo! no pairing set up for 'it' yet */
-            return it;
+            if (!it2)
+                return it;
         }
         it = it->next;
     }
diff --git a/dix/events.c b/dix/events.c
index 5be923a..23d5f22 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -247,7 +247,7 @@ static int spriteTraceGood;
 _X_EXPORT Bool
 DevHasCursor(DeviceIntPtr pDev) 
 {
-    return pDev->spriteOwner;
+    return (pDev != inputInfo.pointer && pDev->spriteOwner);
 }
 
 #ifdef XEVIE
@@ -1663,6 +1663,8 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 		              this mask is the mask of the grab. */
     int type = pEvents->u.u.type;
     
+    /* if a  is denied, we return 0. This could cause the caller to
+     * traverse the parent. May be bad! (whot) */
     if (!ACDeviceAllowed(pWin, pDev))
         return 0;
 
@@ -1727,6 +1729,7 @@ DeliverEventsToWindow(DeviceIntPtr pDev,
 	tempGrab.pointerMode = GrabModeAsync;
 	tempGrab.confineTo = NullWindow;
 	tempGrab.cursor = NullCursor;
+        tempGrab.coreGrab = True;
 	(*inputInfo.pointer->ActivateGrab)(pDev, &tempGrab,
 					   currentTime, TRUE);
     }
@@ -1868,8 +1871,8 @@ FixUpEventFromWindow(
 }
 
 int
-DeliverDeviceEvents(register WindowPtr pWin, register xEvent *xE, GrabPtr grab, 
-                    register WindowPtr stopAt, DeviceIntPtr dev, int count)
+DeliverDeviceEvents(WindowPtr pWin, xEvent *xE, GrabPtr grab, 
+                    WindowPtr stopAt, DeviceIntPtr dev, int count)
 {
     Window child = None;
     int type = xE->u.u.type;
@@ -1878,7 +1881,7 @@ DeliverDeviceEvents(register WindowPtr p
 
     if (type & EXTENSION_EVENT_BASE)
     {
-	register OtherInputMasks *inputMasks;
+	OtherInputMasks *inputMasks;
 	int mskidx = dev->id;
 
 	inputMasks = wOtherInputMasks(pWin);
@@ -2199,6 +2202,8 @@ DefineInitialRootWindow(register WindowP
 #endif
     ROOT = win;
 
+    InitializeSprite(inputInfo.pointer, win);
+
     while (pDev)
     {
         if (DevHasCursor(pDev))
@@ -2274,7 +2279,6 @@ InitializeSprite(DeviceIntPtr pDev, Wind
         REGION_NULL(pScreen, &pSprite->Reg2);
     }
 #endif
-
 }
 
 /*
@@ -3943,6 +3947,7 @@ ProcGrabPointer(ClientPtr client)
 	tempGrab.keyboardMode = stuff->keyboardMode;
 	tempGrab.pointerMode = stuff->pointerMode;
 	tempGrab.device = device;
+        tempGrab.coreGrab = True;
 	(*device->ActivateGrab)(device, &tempGrab, time, FALSE);
 	if (oldCursor)
 	    FreeCursor (oldCursor, (Cursor)0);
diff --git a/include/input.h b/include/input.h
index 433cc94..ca81b1a 100644
--- a/include/input.h
+++ b/include/input.h
@@ -455,6 +455,8 @@ extern DeviceIntPtr GetPairedPointer(Dev
 extern Bool RegisterPairingClient(ClientPtr client);
 extern Bool UnregisterPairingClient(ClientPtr client);
 
+extern DeviceIntPtr GuessFreePointerDevice();
+
 /* Window/device based access control */
 extern Bool ACRegisterClient(ClientPtr client);
 extern Bool ACUnregisterClient(ClientPtr client);
diff --git a/mi/mipointer.c b/mi/mipointer.c
index 5df7a0a..edb5c5f 100644
--- a/mi/mipointer.c
+++ b/mi/mipointer.c
@@ -302,7 +302,7 @@ miPointerWarpCursor (pDev, pScreen, x, y
 
     if (GenerateEvent)
     {
-	miPointerMoved (pDev, pScreen, x, y, GetTimeInMillis()); 
+	miPointerMove (pDev, pScreen, x, y, GetTimeInMillis()); 
     }
     else
     {
@@ -346,8 +346,8 @@ miPointerUpdateSprite (DeviceIntPtr pDev
     int			x, y, devx, devy;
     miPointerPtr        pPointer;
 
-    if (!pDev || 
-            !(pDev->coreEvents || pDev == inputInfo.pointer || pDev->isMPDev))
+    if (!pDev || pDev == inputInfo.pointer || 
+            !(pDev->coreEvents || pDev->isMPDev))
         return;
 
     pPointer = MIPOINTER(pDev);
@@ -540,7 +540,7 @@ miPointerMove (DeviceIntPtr pDev, Screen
     int i, nevents;
     int valuators[2];
 
-    miPointerMoved(inputInfo.pointer, pScreen, x, y, time);
+    miPointerMoved(pDev, pScreen, x, y, time);
 
     /* generate motion notify */
     valuators[0] = x;
diff --git a/mi/mispritest.h b/mi/mispritest.h
index 8c8cd53..8cc2064 100644
--- a/mi/mispritest.h
+++ b/mi/mispritest.h
@@ -44,7 +44,6 @@ in this Software without prior written a
 # include   "damage.h"
 
 typedef struct {
-    int             id;                 /* id, corresponds with device id */
     CursorPtr	    pCursor;
     int		    x;			/* cursor hotspot */
     int		    y;
diff-tree 39aa79177196e21bcdbaf8e44adead9ef91e6ee5 (from 1f0075786fedde538a95e2f39681052e25021d88)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Mon Mar 5 15:31:16 2007 +1030

    dix:    Add GuessFreePointerDevice(). Runs through device list and tries to
            find a pointer that hasn't been paired yet.
    
    xfree86:  Use GuessFreePointerDevice() for newly connected non-sprite devices.

diff --git a/dix/devices.c b/dix/devices.c
index 87b3927..9195586 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -2026,3 +2026,45 @@ UnregisterPairingClient(ClientPtr client
     }
     return True;
 }
+
+/* Guess a pointer that could be a good one for pairing. Any pointer that is
+ * not yet paired with keyboard is considered a good one. 
+ * If no pointer is found, the last real pointer is chosen. If that doesn't
+ * work either, we take the core pointer.
+ */
+DeviceIntPtr
+GuessFreePointerDevice()
+{
+    DeviceIntPtr it, it2;
+    DeviceIntPtr lastRealPtr = NULL;
+        
+    it = inputInfo.devices;
+
+    while(it)
+    {
+        /* found device with a sprite? */
+        if (it != inputInfo.pointer && it->spriteOwner)
+        {
+            lastRealPtr = it;
+
+            it2 = inputInfo.devices;
+            while(it2)
+            {
+                /* something paired with it? */
+                if (it != it2 && it2->pSprite == it->pSprite)
+                    break;
+
+                it2 = it2->next;
+            }
+
+            if (it2)
+                break;
+
+            /* woohoo! no pairing set up for 'it' yet */
+            return it;
+        }
+        it = it->next;
+    }
+
+    return (lastRealPtr) ? lastRealPtr : inputInfo.pointer;
+}
diff --git a/hw/xfree86/common/xf86Xinput.c b/hw/xfree86/common/xf86Xinput.c
index 31be1e3..c6d6b36 100644
--- a/hw/xfree86/common/xf86Xinput.c
+++ b/hw/xfree86/common/xf86Xinput.c
@@ -189,8 +189,10 @@ xf86ActivateDevice(LocalDevicePtr local)
         /* Only create a new sprite if it's a non-shared pointer */
         if (IsPointerDevice(dev) && dev->isMPDev)
             InitializeSprite(dev, GetCurrentRootWindow());
-        else 
-            PairDevices(NULL, inputInfo.pointer, dev);
+        else {
+            /* pair with a free device */
+            PairDevices(NULL, GuessFreePointerDevice(), dev);
+        }
 
         RegisterOtherDevice(dev);
 
diff-tree 1f0075786fedde538a95e2f39681052e25021d88 (from parents)
Merge: 57aa5e908dc11d5d8c27ed705c526f1416c1e8ad 12175b668a94e23994f724b366a691ec312cce69
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Mon Mar 5 12:37:17 2007 +1030

    Merge branch 'master' into mpx
    
    Conflicts:
    
    	configure.ac
    	dix/getevents.c
    	hw/xfree86/ramdac/xf86Cursor.c
    	mi/mipointer.c
    	xkb/xkbUtils.c

diff --cc hw/xfree86/modes/xf86RandR12.c
index 0000000,052d12a..020fbb1
mode 000000,100644..100644
@@@ -1,0 -1,960 +1,961 @@@
+ /* $XdotOrg: xc/programs/Xserver/hw/xfree86/common/xf86RandR.c,v 1.3 2004/07/30 21:53:09 eich Exp $ */
+ /*
+  * $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86RandR.c,v 1.7tsi Exp $
+  *
+  * Copyright © 2002 Keith Packard, member of The XFree86 Project, 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 the copyright holders not be used in advertising or
+  * publicity pertaining to distribution of the software without specific,
+  * written prior permission.  The copyright holders make no representations
+  * about the suitability of this software for any purpose.  It is provided "as
+  * is" without express or implied warranty.
+  *
+  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+  * EVENT SHALL THE COPYRIGHT HOLDERS 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_XORG_CONFIG_H
+ #include <xorg-config.h>
+ #else
+ #ifdef HAVE_CONFIG_H
+ #include <config.h>
+ #endif
+ #endif
+ 
+ #include "xf86.h"
+ #include "os.h"
+ #include "mibank.h"
+ #include "globals.h"
+ #include "xf86.h"
+ #include "xf86Priv.h"
+ #include "xf86DDC.h"
+ #include "mipointer.h"
+ #include "windowstr.h"
++#include "inputstr.h"
+ #include <randrstr.h>
+ #include <X11/extensions/render.h>
+ 
+ #include "xf86Crtc.h"
+ #include "xf86RandR12.h"
+ 
+ typedef struct _xf86RandR12Info {
+     int				    virtualX;
+     int				    virtualY;
+     int				    mmWidth;
+     int				    mmHeight;
+     int				    maxX;
+     int				    maxY;
+     Rotation			    rotation; /* current mode */
+     Rotation                        supported_rotations; /* driver supported */
+ } XF86RandRInfoRec, *XF86RandRInfoPtr;
+ 
+ #ifdef RANDR_12_INTERFACE
+ static Bool xf86RandR12Init12 (ScreenPtr pScreen);
+ static Bool xf86RandR12CreateScreenResources12 (ScreenPtr pScreen);
+ #endif
+ 
+ static int	    xf86RandR12Index;
+ static int	    xf86RandR12Generation;
+ 
+ #define XF86RANDRINFO(p) \
+ 	((XF86RandRInfoPtr)(p)->devPrivates[xf86RandR12Index].ptr)
+ 
+ static int
+ xf86RandR12ModeRefresh (DisplayModePtr mode)
+ {
+     if (mode->VRefresh)
+ 	return (int) (mode->VRefresh + 0.5);
+     else
+ 	return (int) (mode->Clock * 1000.0 / mode->HTotal / mode->VTotal + 0.5);
+ }
+ 
+ static Bool
+ xf86RandR12GetInfo (ScreenPtr pScreen, Rotation *rotations)
+ {
+     RRScreenSizePtr	    pSize;
+     ScrnInfoPtr		    scrp = XF86SCRNINFO(pScreen);
+     XF86RandRInfoPtr	    randrp = XF86RANDRINFO(pScreen);
+     DisplayModePtr	    mode;
+     int			    refresh0 = 60;
+     int			    maxX = 0, maxY = 0;
+ 
+     *rotations = randrp->supported_rotations;
+ 
+     if (randrp->virtualX == -1 || randrp->virtualY == -1)
+     {
+ 	randrp->virtualX = scrp->virtualX;
+ 	randrp->virtualY = scrp->virtualY;
+     }
+ 
+     /* Re-probe the outputs for new monitors or modes */
+     xf86ProbeOutputModes (scrp, 0, 0);
+     xf86SetScrnInfoModes (scrp);
+     xf86DiDGAReInit (pScreen);
+ 
+     for (mode = scrp->modes; ; mode = mode->next)
+     {
+ 	int refresh = xf86RandR12ModeRefresh (mode);
+ 	if (randrp->maxX == 0 || randrp->maxY == 0)
+ 	{
+ 		if (maxX < mode->HDisplay)
+ 			maxX = mode->HDisplay;
+ 		if (maxY < mode->VDisplay)
+ 			maxY = mode->VDisplay;
+ 	}
+ 	if (mode == scrp->modes)
+ 	    refresh0 = refresh;
+ 	pSize = RRRegisterSize (pScreen,
+ 				mode->HDisplay, mode->VDisplay,
+ 				randrp->mmWidth, randrp->mmHeight);
+ 	if (!pSize)
+ 	    return FALSE;
+ 	RRRegisterRate (pScreen, pSize, refresh);
+ 
+ 	if (xf86ModesEqual(mode, scrp->currentMode) &&
+ 	    mode->HDisplay == scrp->virtualX &&
+ 	    mode->VDisplay == scrp->virtualY)
+ 	{
+ 	    RRSetCurrentConfig (pScreen, randrp->rotation, refresh, pSize);
+ 	}
+ 	if (mode->next == scrp->modes)
+ 	    break;
+     }
+ 
+     if (randrp->maxX == 0 || randrp->maxY == 0)
+     {
+ 	randrp->maxX = maxX;
+ 	randrp->maxY = maxY;
+     }
+ 
+     if (scrp->currentMode->HDisplay != randrp->virtualX ||
+ 	scrp->currentMode->VDisplay != randrp->virtualY)
+     {
+ 	pSize = RRRegisterSize (pScreen,
+ 				randrp->virtualX, randrp->virtualY,
+ 				randrp->mmWidth,
+ 				randrp->mmHeight);
+ 	if (!pSize)
+ 	    return FALSE;
+ 	RRRegisterRate (pScreen, pSize, refresh0);
+ 	if (scrp->virtualX == randrp->virtualX &&
+ 	    scrp->virtualY == randrp->virtualY)
+ 	{
+ 	    RRSetCurrentConfig (pScreen, randrp->rotation, refresh0, pSize);
+ 	}
+     }
+ 
+     return TRUE;
+ }
+ 
+ static Bool
+ xf86RandR12SetMode (ScreenPtr	    pScreen,
+ 		  DisplayModePtr    mode,
+ 		  Bool		    useVirtual,
+ 		  int		    mmWidth,
+ 		  int		    mmHeight)
+ {
+     ScrnInfoPtr		scrp = XF86SCRNINFO(pScreen);
+     XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+     int			oldWidth = pScreen->width;
+     int			oldHeight = pScreen->height;
+     int			oldmmWidth = pScreen->mmWidth;
+     int			oldmmHeight = pScreen->mmHeight;
+     WindowPtr		pRoot = WindowTable[pScreen->myNum];
+     DisplayModePtr      currentMode = NULL;
+     Bool 		ret = TRUE;
+     PixmapPtr 		pspix = NULL;
+ 
+     if (pRoot)
+ 	(*scrp->EnableDisableFBAccess) (pScreen->myNum, FALSE);
+     if (useVirtual)
+     {
+ 	scrp->virtualX = randrp->virtualX;
+ 	scrp->virtualY = randrp->virtualY;
+     }
+     else
+     {
+ 	scrp->virtualX = mode->HDisplay;
+ 	scrp->virtualY = mode->VDisplay;
+     }
+ 
+     if(randrp->rotation & (RR_Rotate_90 | RR_Rotate_270))
+     {
+ 	/* If the screen is rotated 90 or 270 degrees, swap the sizes. */
+ 	pScreen->width = scrp->virtualY;
+ 	pScreen->height = scrp->virtualX;
+ 	pScreen->mmWidth = mmHeight;
+ 	pScreen->mmHeight = mmWidth;
+     }
+     else
+     {
+ 	pScreen->width = scrp->virtualX;
+ 	pScreen->height = scrp->virtualY;
+ 	pScreen->mmWidth = mmWidth;
+ 	pScreen->mmHeight = mmHeight;
+     }
+     if (scrp->currentMode == mode) {
+         /* Save current mode */
+         currentMode = scrp->currentMode;
+         /* Reset, just so we ensure the drivers SwitchMode is called */
+         scrp->currentMode = NULL;
+     }
+     /*
+      * We know that if the driver failed to SwitchMode to the rotated
+      * version, then it should revert back to it's prior mode.
+      */
+     if (!xf86SwitchMode (pScreen, mode))
+     {
+         ret = FALSE;
+ 	scrp->virtualX = pScreen->width = oldWidth;
+ 	scrp->virtualY = pScreen->height = oldHeight;
+ 	pScreen->mmWidth = oldmmWidth;
+ 	pScreen->mmHeight = oldmmHeight;
+         scrp->currentMode = currentMode;
+     }
+     /*
+      * Get the new Screen pixmap ptr as SwitchMode might have called
+      * ModifyPixmapHeader and xf86EnableDisableFBAccess will put it back...
+      * Unfortunately.
+      */
+     pspix = (*pScreen->GetScreenPixmap) (pScreen);
+     if (pspix->devPrivate.ptr)
+        scrp->pixmapPrivate = pspix->devPrivate;
+ 
+     /*
+      * Make sure the layout is correct
+      */
+     xf86ReconfigureLayout();
+ 
+     /*
+      * Make sure the whole screen is visible
+      */
+     xf86SetViewport (pScreen, pScreen->width, pScreen->height);
+     xf86SetViewport (pScreen, 0, 0);
+     if (pRoot)
+ 	(*scrp->EnableDisableFBAccess) (pScreen->myNum, TRUE);
+     return ret;
+ }
+ 
+ Bool
+ xf86RandR12SetConfig (ScreenPtr		pScreen,
+ 		    Rotation		rotation,
+ 		    int			rate,
+ 		    RRScreenSizePtr	pSize)
+ {
+     ScrnInfoPtr		scrp = XF86SCRNINFO(pScreen);
+     XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+     DisplayModePtr	mode;
+     int			px, py;
+     Bool		useVirtual = FALSE;
+     int			maxX = 0, maxY = 0;
+     Rotation		oldRotation = randrp->rotation;
+ 
+     randrp->rotation = rotation;
+ 
+     if (randrp->virtualX == -1 || randrp->virtualY == -1)
+     {
+ 	randrp->virtualX = scrp->virtualX;
+ 	randrp->virtualY = scrp->virtualY;
+     }
+ 
 -    miPointerPosition (&px, &py);
++    miPointerGetPosition (inputInfo.pointer, &px, &py);
+     for (mode = scrp->modes; ; mode = mode->next)
+     {
+ 	if (randrp->maxX == 0 || randrp->maxY == 0)
+ 	{
+ 		if (maxX < mode->HDisplay)
+ 			maxX = mode->HDisplay;
+ 		if (maxY < mode->VDisplay)
+ 			maxY = mode->VDisplay;
+ 	}
+ 	if (mode->HDisplay == pSize->width &&
+ 	    mode->VDisplay == pSize->height &&
+ 	    (rate == 0 || xf86RandR12ModeRefresh (mode) == rate))
+ 	    break;
+ 	if (mode->next == scrp->modes)
+ 	{
+ 	    if (pSize->width == randrp->virtualX &&
+ 		pSize->height == randrp->virtualY)
+ 	    {
+ 		mode = scrp->modes;
+ 		useVirtual = TRUE;
+ 		break;
+ 	    }
+     	    if (randrp->maxX == 0 || randrp->maxY == 0)
+     	    {
+ 		randrp->maxX = maxX;
+ 		randrp->maxY = maxY;
+     	    }
+ 	    return FALSE;
+ 	}
+     }
+ 
+     if (randrp->maxX == 0 || randrp->maxY == 0)
+     {
+ 	randrp->maxX = maxX;
+ 	randrp->maxY = maxY;
+     }
+ 
+     if (!xf86RandR12SetMode (pScreen, mode, useVirtual, pSize->mmWidth,
+ 			   pSize->mmHeight)) {
+         randrp->rotation = oldRotation;
+ 	return FALSE;
+     }
+ 
+     /*
+      * Move the cursor back where it belongs; SwitchMode repositions it
+      */
 -    if (pScreen == miPointerCurrentScreen ())
++    if (pScreen == miPointerGetScreen(inputInfo.pointer))
+     {
+         px = (px >= pScreen->width ? (pScreen->width - 1) : px);
+         py = (py >= pScreen->height ? (pScreen->height - 1) : py);
+ 
+ 	xf86SetViewport(pScreen, px, py);
+ 
 -	(*pScreen->SetCursorPosition) (pScreen, px, py, FALSE);
++	(*pScreen->SetCursorPosition) (inputInfo.pointer, pScreen, px, py, FALSE);
+     }
+ 
+     return TRUE;
+ }
+ 
+ static Bool
+ xf86RandR12ScreenSetSize (ScreenPtr	pScreen,
+ 			CARD16		width,
+ 			CARD16		height,
+ 			CARD32		mmWidth,
+ 			CARD32		mmHeight)
+ {
+     XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+     ScrnInfoPtr		pScrn = XF86SCRNINFO(pScreen);
+     xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(pScrn);
+     WindowPtr		pRoot = WindowTable[pScreen->myNum];
+     Bool		ret = FALSE;
+ 
+     if (randrp->virtualX == -1 || randrp->virtualY == -1)
+     {
+ 	randrp->virtualX = pScrn->virtualX;
+ 	randrp->virtualY = pScrn->virtualY;
+     }
+     if (pRoot)
+ 	(*pScrn->EnableDisableFBAccess) (pScreen->myNum, FALSE);
+ 
+     /* Let the driver update virtualX and virtualY */
+     if (!(*config->funcs->resize)(pScrn, width, height))
+ 	goto finish;
+ 
+     ret = TRUE;
+ 
+     pScreen->width = width;
+     pScreen->height = height;
+     pScreen->mmWidth = mmWidth;
+     pScreen->mmHeight = mmHeight;
+ 
+     xf86SetViewport (pScreen, pScreen->width-1, pScreen->height-1);
+     xf86SetViewport (pScreen, 0, 0);
+ 
+ finish:
+     if (pRoot)
+ 	(*pScrn->EnableDisableFBAccess) (pScreen->myNum, TRUE);
+ #if RANDR_12_INTERFACE
+     if (WindowTable[pScreen->myNum] && ret)
+ 	RRScreenSizeNotify (pScreen);
+ #endif
+     return ret;
+ }
+ 
+ Rotation
+ xf86RandR12GetRotation(ScreenPtr pScreen)
+ {
+     XF86RandRInfoPtr	    randrp = XF86RANDRINFO(pScreen);
+ 
+     return randrp->rotation;
+ }
+ 
+ Bool
+ xf86RandR12CreateScreenResources (ScreenPtr pScreen)
+ {
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+     xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+     XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+     int			c;
+     int			width, height;
+     int			mmWidth, mmHeight;
+ #ifdef PANORAMIX
+     /* XXX disable RandR when using Xinerama */
+     if (!noPanoramiXExtension)
+ 	return TRUE;
+ #endif
+ 
+     /*
+      * Compute size of screen
+      */
+     width = 0; height = 0;
+     for (c = 0; c < config->num_crtc; c++)
+     {
+ 	xf86CrtcPtr crtc = config->crtc[c];
+ 	int	    crtc_width = crtc->x + xf86ModeWidth (&crtc->mode, crtc->rotation);
+ 	int	    crtc_height = crtc->y + xf86ModeHeight (&crtc->mode, crtc->rotation);
+ 	
+ 	if (crtc->enabled && crtc_width > width)
+ 	    width = crtc_width;
+ 	if (crtc->enabled && crtc_height > height)
+ 	    height = crtc_height;
+     }
+     
+     if (width && height)
+     {
+ 	/*
+ 	 * Compute physical size of screen
+ 	 */
+ 	if (monitorResolution) 
+ 	{
+ 	    mmWidth = width * 25.4 / monitorResolution;
+ 	    mmHeight = height * 25.4 / monitorResolution;
+ 	}
+ 	else
+ 	{
+ 	    mmWidth = pScreen->mmWidth;
+ 	    mmHeight = pScreen->mmHeight;
+ 	}
+ 	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
+ 		   "Setting screen physical size to %d x %d\n",
+ 		   mmWidth, mmHeight);
+ 	xf86RandR12ScreenSetSize (pScreen,
+ 				  width,
+ 				  height,
+ 				  mmWidth,
+ 				  mmHeight);
+     }
+ 
+     if (randrp->virtualX == -1 || randrp->virtualY == -1)
+     {
+ 	randrp->virtualX = pScrn->virtualX;
+ 	randrp->virtualY = pScrn->virtualY;
+     }
+     xf86CrtcSetScreenSubpixelOrder (pScreen);
+ #if RANDR_12_INTERFACE
+     if (xf86RandR12CreateScreenResources12 (pScreen))
+ 	return TRUE;
+ #endif
+     return TRUE;
+ }
+ 
+ 
+ Bool
+ xf86RandR12Init (ScreenPtr pScreen)
+ {
+     rrScrPrivPtr	rp;
+     XF86RandRInfoPtr	randrp;
+ 
+ #ifdef PANORAMIX
+     /* XXX disable RandR when using Xinerama */
+     if (!noPanoramiXExtension)
+ 	return TRUE;
+ #endif
+     if (xf86RandR12Generation != serverGeneration)
+     {
+ 	xf86RandR12Index = AllocateScreenPrivateIndex();
+ 	xf86RandR12Generation = serverGeneration;
+     }
+ 
+     randrp = xalloc (sizeof (XF86RandRInfoRec));
+     if (!randrp)
+ 	return FALSE;
+ 
+     if (!RRScreenInit(pScreen))
+     {
+ 	xfree (randrp);
+ 	return FALSE;
+     }
+     rp = rrGetScrPriv(pScreen);
+     rp->rrGetInfo = xf86RandR12GetInfo;
+     rp->rrSetConfig = xf86RandR12SetConfig;
+ 
+     randrp->virtualX = -1;
+     randrp->virtualY = -1;
+     randrp->mmWidth = pScreen->mmWidth;
+     randrp->mmHeight = pScreen->mmHeight;
+ 
+     randrp->rotation = RR_Rotate_0; /* initial rotated mode */
+ 
+     randrp->supported_rotations = RR_Rotate_0;
+ 
+     randrp->maxX = randrp->maxY = 0;
+ 
+     pScreen->devPrivates[xf86RandR12Index].ptr = randrp;
+ 
+ #if RANDR_12_INTERFACE
+     if (!xf86RandR12Init12 (pScreen))
+ 	return FALSE;
+ #endif
+     return TRUE;
+ }
+ 
+ void
+ xf86RandR12SetRotations (ScreenPtr pScreen, Rotation rotations)
+ {
+     XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+ #if RANDR_12_INTERFACE
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+     int			c;
+     xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+ 
+     for (c = 0; c < config->num_crtc; c++) {
+ 	xf86CrtcPtr    crtc = config->crtc[c];
+ 
+ 	RRCrtcSetRotations (crtc->randr_crtc, rotations);
+     }
+ #endif
+     randrp->supported_rotations = rotations;
+ }
+ 
+ void
+ xf86RandR12GetOriginalVirtualSize(ScrnInfoPtr pScrn, int *x, int *y)
+ {
+     ScreenPtr pScreen = screenInfo.screens[pScrn->scrnIndex];
+ 
+     if (xf86RandR12Generation != serverGeneration ||
+ 	XF86RANDRINFO(pScreen)->virtualX == -1)
+     {
+ 	*x = pScrn->virtualX;
+ 	*y = pScrn->virtualY;
+     } else {
+ 	XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen);
+ 
+ 	*x = randrp->virtualX;
+ 	*y = randrp->virtualY;
+     }
+ }
+ 
+ #if RANDR_12_INTERFACE
+ static Bool
+ xf86RandR12CrtcNotify (RRCrtcPtr	randr_crtc)
+ {
+     ScreenPtr		pScreen = randr_crtc->pScreen;
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+     xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+     RRModePtr		randr_mode = NULL;
+     int			x;
+     int			y;
+     Rotation		rotation;
+     int			numOutputs;
+     RROutputPtr		*randr_outputs;
+     RROutputPtr		randr_output;
+     xf86CrtcPtr		crtc = randr_crtc->devPrivate;
+     xf86OutputPtr	output;
+     int			i, j;
+     DisplayModePtr	mode = &crtc->mode;
+     Bool		ret;
+ 
+     randr_outputs = ALLOCATE_LOCAL(config->num_output * sizeof (RROutputPtr));
+     if (!randr_outputs)
+ 	return FALSE;
+     x = crtc->x;
+     y = crtc->y;
+     rotation = crtc->rotation;
+     numOutputs = 0;
+     randr_mode = NULL;
+     for (i = 0; i < config->num_output; i++)
+     {
+ 	output = config->output[i];
+ 	if (output->crtc == crtc)
+ 	{
+ 	    randr_output = output->randr_output;
+ 	    randr_outputs[numOutputs++] = randr_output;
+ 	    /*
+ 	     * We make copies of modes, so pointer equality 
+ 	     * isn't sufficient
+ 	     */
+ 	    for (j = 0; j < randr_output->numModes; j++)
+ 	    {
+ 		DisplayModePtr	outMode = randr_output->modes[j]->devPrivate;
+ 		if (xf86ModesEqual(mode, outMode))
+ 		{
+ 		    randr_mode = randr_output->modes[j];
+ 		    break;
+ 		}
+ 	    }
+ 	}
+     }
+     ret = RRCrtcNotify (randr_crtc, randr_mode, x, y,
+ 			rotation, numOutputs, randr_outputs);
+     DEALLOCATE_LOCAL(randr_outputs);
+     return ret;
+ }
+ 
+ static Bool
+ xf86RandR12CrtcSet (ScreenPtr	pScreen,
+ 		  RRCrtcPtr	randr_crtc,
+ 		  RRModePtr	randr_mode,
+ 		  int		x,
+ 		  int		y,
+ 		  Rotation	rotation,
+ 		  int		num_randr_outputs,
+ 		  RROutputPtr	*randr_outputs)
+ {
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+     xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+     xf86CrtcPtr		crtc = randr_crtc->devPrivate;
+     DisplayModePtr	mode = randr_mode ? randr_mode->devPrivate : NULL;
+     Bool		changed = FALSE;
+     int			o, ro;
+     xf86CrtcPtr		*save_crtcs;
+     Bool		save_enabled = crtc->enabled;
+ 
+     save_crtcs = ALLOCATE_LOCAL(config->num_crtc * sizeof (xf86CrtcPtr));
+     if ((mode != NULL) != crtc->enabled)
+ 	changed = TRUE;
+     else if (mode && !xf86ModesEqual (&crtc->mode, mode))
+ 	changed = TRUE;
+     
+     if (rotation != crtc->rotation)
+ 	changed = TRUE;
+ 
+     if (x != crtc->x || y != crtc->y)
+ 	changed = TRUE;
+     for (o = 0; o < config->num_output; o++) 
+     {
+ 	xf86OutputPtr  output = config->output[o];
+ 	xf86CrtcPtr    new_crtc;
+ 
+ 	save_crtcs[o] = output->crtc;
+ 	
+ 	if (output->crtc == crtc)
+ 	    new_crtc = NULL;
+ 	else
+ 	    new_crtc = output->crtc;
+ 	for (ro = 0; ro < num_randr_outputs; ro++) 
+ 	    if (output->randr_output == randr_outputs[ro])
+ 	    {
+ 		new_crtc = crtc;
+ 		break;
+ 	    }
+ 	if (new_crtc != output->crtc)
+ 	{
+ 	    changed = TRUE;
+ 	    output->crtc = new_crtc;
+ 	}
+     }
+     /* XXX need device-independent mode setting code through an API */
+     if (changed)
+     {
+ 	crtc->enabled = mode != NULL;
+ 
+ 	if (mode)
+ 	{
+ 	    if (!xf86CrtcSetMode (crtc, mode, rotation, x, y))
+ 	    {
+ 		crtc->enabled = save_enabled;
+ 		for (o = 0; o < config->num_output; o++)
+ 		{
+ 		    xf86OutputPtr	output = config->output[o];
+ 		    output->crtc = save_crtcs[o];
+ 		}
+ 		DEALLOCATE_LOCAL(save_crtcs);
+ 		return FALSE;
+ 	    }
+ 	    /*
+ 	     * Save the last successful setting for EnterVT
+ 	     */
+ 	    crtc->desiredMode = *mode;
+ 	    crtc->desiredRotation = rotation;
+ 	    crtc->desiredX = x;
+ 	    crtc->desiredY = y;
+ 	}
+ 	xf86DisableUnusedFunctions (pScrn);
+     }
+     DEALLOCATE_LOCAL(save_crtcs);
+     return xf86RandR12CrtcNotify (randr_crtc);
+ }
+ 
+ static Bool
+ xf86RandR12CrtcSetGamma (ScreenPtr    pScreen,
+ 			 RRCrtcPtr    randr_crtc)
+ {
+     xf86CrtcPtr		crtc = randr_crtc->devPrivate;
+ 
+     if (crtc->funcs->gamma_set == NULL)
+ 	return FALSE;
+ 
+     crtc->funcs->gamma_set(crtc, randr_crtc->gammaRed, randr_crtc->gammaGreen,
+ 			   randr_crtc->gammaBlue, randr_crtc->gammaSize);
+ 
+     return TRUE;
+ }
+ 
+ static Bool
+ xf86RandR12OutputSetProperty (ScreenPtr pScreen,
+ 			      RROutputPtr randr_output,
+ 			      Atom property,
+ 			      RRPropertyValuePtr value)
+ {
+     xf86OutputPtr output = randr_output->devPrivate;
+ 
+     /* If we don't have any property handler, then we don't care what the
+      * user is setting properties to.
+      */
+     if (output->funcs->set_property == NULL)
+ 	return TRUE;
+ 
+     return output->funcs->set_property(output, property, value);
+ }
+ 
+ /**
+  * Given a list of xf86 modes and a RandR Output object, construct
+  * RandR modes and assign them to the output
+  */
+ static Bool
+ xf86RROutputSetModes (RROutputPtr randr_output, DisplayModePtr modes)
+ {
+     DisplayModePtr  mode;
+     RRModePtr	    *rrmodes = NULL;
+     int		    nmode = 0;
+     int		    npreferred = 0;
+     Bool	    ret = TRUE;
+     int		    pref;
+ 
+     for (mode = modes; mode; mode = mode->next)
+ 	nmode++;
+ 
+     if (nmode) {
+ 	rrmodes = xalloc (nmode * sizeof (RRModePtr));
+ 	
+ 	if (!rrmodes)
+ 	    return FALSE;
+ 	nmode = 0;
+ 
+ 	for (pref = 1; pref >= 0; pref--) {
+ 	    for (mode = modes; mode; mode = mode->next) {
+ 		if ((pref != 0) == ((mode->type & M_T_PREFERRED) != 0)) {
+ 		    xRRModeInfo		modeInfo;
+ 		    RRModePtr		rrmode;
+ 		    
+ 		    modeInfo.nameLength = strlen (mode->name);
+ 		    modeInfo.width = mode->HDisplay;
+ 		    modeInfo.dotClock = mode->Clock * 1000;
+ 		    modeInfo.hSyncStart = mode->HSyncStart;
+ 		    modeInfo.hSyncEnd = mode->HSyncEnd;
+ 		    modeInfo.hTotal = mode->HTotal;
+ 		    modeInfo.hSkew = mode->HSkew;
+ 
+ 		    modeInfo.height = mode->VDisplay;
+ 		    modeInfo.vSyncStart = mode->VSyncStart;
+ 		    modeInfo.vSyncEnd = mode->VSyncEnd;
+ 		    modeInfo.vTotal = mode->VTotal;
+ 		    modeInfo.modeFlags = mode->Flags;
+ 
+ 		    rrmode = RRModeGet (&modeInfo, mode->name);
+ 		    if (rrmode) {
+ 			rrmode->devPrivate = mode;
+ 			rrmodes[nmode++] = rrmode;
+ 			npreferred += pref;
+ 		    }
+ 		}
+ 	    }
+ 	}
+     }
+     
+     ret = RROutputSetModes (randr_output, rrmodes, nmode, npreferred);
+     xfree (rrmodes);
+     return ret;
+ }
+ 
+ /*
+  * Mirror the current mode configuration to RandR
+  */
+ static Bool
+ xf86RandR12SetInfo12 (ScreenPtr pScreen)
+ {
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+     xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+     RROutputPtr		*clones;
+     RRCrtcPtr		*crtcs;
+     int			ncrtc;
+     int			o, c, l;
+     RRCrtcPtr		randr_crtc;
+     int			nclone;
+     
+     clones = ALLOCATE_LOCAL(config->num_output * sizeof (RROutputPtr));
+     crtcs = ALLOCATE_LOCAL (config->num_crtc * sizeof (RRCrtcPtr));
+     for (o = 0; o < config->num_output; o++)
+     {
+ 	xf86OutputPtr	output = config->output[o];
+ 	
+ 	ncrtc = 0;
+ 	for (c = 0; c < config->num_crtc; c++)
+ 	    if (output->possible_crtcs & (1 << c))
+ 		crtcs[ncrtc++] = config->crtc[c]->randr_crtc;
+ 
+ 	if (output->crtc)
+ 	    randr_crtc = output->crtc->randr_crtc;
+ 	else
+ 	    randr_crtc = NULL;
+ 
+ 	if (!RROutputSetCrtcs (output->randr_output, crtcs, ncrtc))
+ 	{
+ 	    DEALLOCATE_LOCAL (crtcs);
+ 	    DEALLOCATE_LOCAL (clones);
+ 	    return FALSE;
+ 	}
+ 
+ 	RROutputSetCrtc (output->randr_output, randr_crtc);
+ 	RROutputSetPhysicalSize(output->randr_output, 
+ 				output->mm_width,
+ 				output->mm_height);
+ 	xf86RROutputSetModes (output->randr_output, output->probed_modes);
+ 
+ 	switch (output->status) {
+ 	case XF86OutputStatusConnected:
+ 	    RROutputSetConnection (output->randr_output, RR_Connected);
+ 	    break;
+ 	case XF86OutputStatusDisconnected:
+ 	    RROutputSetConnection (output->randr_output, RR_Disconnected);
+ 	    break;
+ 	case XF86OutputStatusUnknown:
+ 	    RROutputSetConnection (output->randr_output, RR_UnknownConnection);
+ 	    break;
+ 	}
+ 
+ 	RROutputSetSubpixelOrder (output->randr_output, output->subpixel_order);
+ 
+ 	/*
+ 	 * Valid clones
+ 	 */
+ 	nclone = 0;
+ 	for (l = 0; l < config->num_output; l++)
+ 	{
+ 	    xf86OutputPtr	    clone = config->output[l];
+ 	    
+ 	    if (l != o && (output->possible_clones & (1 << l)))
+ 		clones[nclone++] = clone->randr_output;
+ 	}
+ 	if (!RROutputSetClones (output->randr_output, clones, nclone))
+ 	{
+ 	    DEALLOCATE_LOCAL (crtcs);
+ 	    DEALLOCATE_LOCAL (clones);
+ 	    return FALSE;
+ 	}
+     }
+     DEALLOCATE_LOCAL (crtcs);
+     DEALLOCATE_LOCAL (clones);
+     return TRUE;
+ }
+ 
+ 
+ 
+ /*
+  * Query the hardware for the current state, then mirror
+  * that to RandR
+  */
+ static Bool
+ xf86RandR12GetInfo12 (ScreenPtr pScreen, Rotation *rotations)
+ {
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+ 
+     xf86ProbeOutputModes (pScrn, 0, 0);
+     xf86SetScrnInfoModes (pScrn);
+     xf86DiDGAReInit (pScreen);
+     return xf86RandR12SetInfo12 (pScreen);
+ }
+ 
+ static Bool
+ xf86RandR12CreateObjects12 (ScreenPtr pScreen)
+ {
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+     xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+     int			c;
+     int			o;
+     
+     if (!RRInit ())
+ 	return FALSE;
+ 
+     /*
+      * Configure crtcs
+      */
+     for (c = 0; c < config->num_crtc; c++)
+     {
+ 	xf86CrtcPtr    crtc = config->crtc[c];
+ 	
+ 	crtc->randr_crtc = RRCrtcCreate (crtc);
+ 	RRCrtcAttachScreen (crtc->randr_crtc, pScreen);
+ 	RRCrtcGammaSetSize (crtc->randr_crtc, 256);
+     }
+     /*
+      * Configure outputs
+      */
+     for (o = 0; o < config->num_output; o++)
+     {
+ 	xf86OutputPtr	output = config->output[o];
+ 
+ 	output->randr_output = RROutputCreate (output->name, 
+ 					       strlen (output->name),
+ 					       output);
+ 	RROutputAttachScreen (output->randr_output, pScreen);
+ 
+ 	if (output->funcs->create_resources != NULL)
+ 	    output->funcs->create_resources(output);
+     }
+     return TRUE;
+ }
+ 
+ static Bool
+ xf86RandR12CreateScreenResources12 (ScreenPtr pScreen)
+ {
+     int			c;
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+     xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+ 
+     for (c = 0; c < config->num_crtc; c++)
+ 	xf86RandR12CrtcNotify (config->crtc[c]->randr_crtc);
+     
+     
+     RRScreenSetSizeRange (pScreen, config->minWidth, config->minHeight,
+ 			  config->maxWidth, config->maxHeight);
+     return TRUE;
+ }
+ 
+ static void
+ xf86RandR12PointerMoved (int scrnIndex, int x, int y)
+ {
+ }
+ 
+ static Bool
+ xf86RandR12Init12 (ScreenPtr pScreen)
+ {
+     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+     rrScrPrivPtr	rp = rrGetScrPriv(pScreen);
+ 
+     rp->rrGetInfo = xf86RandR12GetInfo12;
+     rp->rrScreenSetSize = xf86RandR12ScreenSetSize;
+     rp->rrCrtcSet = xf86RandR12CrtcSet;
+     rp->rrCrtcSetGamma = xf86RandR12CrtcSetGamma;
+     rp->rrOutputSetProperty = xf86RandR12OutputSetProperty;
+     rp->rrSetConfig = NULL;
+     pScrn->PointerMoved = xf86RandR12PointerMoved;
+     if (!xf86RandR12CreateObjects12 (pScreen))
+ 	return FALSE;
+ 
+     /*
+      * Configure output modes
+      */
+     if (!xf86RandR12SetInfo12 (pScreen))
+ 	return FALSE;
+     return TRUE;
+ }
+ 
+ #endif
+ 
+ Bool
+ xf86RandR12PreInit (ScrnInfoPtr pScrn)
+ {
+     return TRUE;
+ }
diff --cc hw/xfree86/ramdac/xf86Cursor.c
index 5a8509b,4578076..c968f18
@@@ -212,11 -199,11 +212,12 @@@
  	pScreen->devPrivates[xf86CursorScreenIndex].ptr;
  
      if (!enable && ScreenPriv->CurrentCursor != NullCursor) {
- 	ScreenPriv->SavedCursor = ScreenPriv->CurrentCursor;
 -	CursorPtr   currentCursor = ScreenPriv->CurrentCursor;
 -	xf86CursorSetCursor(pScreen, NullCursor, ScreenPriv->x, ScreenPriv->y);
 -	ScreenPriv->isUp = FALSE;
++        CursorPtr currentCursor = ScreenPriv->CurrentCursor;
 +        xf86CursorSetCursor(pDev, pScreen, NullCursor, ScreenPriv->x,
 +                ScreenPriv->y); 
 +        ScreenPriv->isUp = FALSE;
  	ScreenPriv->SWCursor = TRUE;
+ 	ScreenPriv->SavedCursor = currentCursor;
      }
  
      if (ScreenPriv->EnableDisableFBAccess)
diff --cc mi/mipointer.c
index ed82fcd,b94feaa..5df7a0a
@@@ -63,36 -56,22 +63,38 @@@
   * until more than one pointer device exists.
   */
  
 -static miPointerRec miPointer;
 +static miPointerPtr miCorePointer;
  
 -static Bool miPointerRealizeCursor(ScreenPtr pScreen, CursorPtr pCursor);
 -static Bool miPointerUnrealizeCursor(ScreenPtr pScreen, CursorPtr pCursor);
 -static Bool miPointerDisplayCursor(ScreenPtr pScreen, CursorPtr pCursor);
 -static void miPointerConstrainCursor(ScreenPtr pScreen, BoxPtr pBox);
 -static void miPointerPointerNonInterestBox(ScreenPtr pScreen, BoxPtr pBox);
 -static void miPointerCursorLimits(ScreenPtr pScreen, CursorPtr pCursor,
 -				  BoxPtr pHotBox, BoxPtr pTopLeftBox);
 -static Bool miPointerSetCursorPosition(ScreenPtr pScreen, int x, int y,
 +/* Multipointers 
 + * ID of a device == index in this array.
 + */
 +static miPointerRec miPointers[MAX_DEVICES];
 +#define MIPOINTER(dev) \
 +    (DevHasCursor((dev))) ? &miPointers[(dev)->id] : miCorePointer
 +
 +static Bool miPointerRealizeCursor(DeviceIntPtr pDev, ScreenPtr pScreen, 
 +                                   CursorPtr pCursor);
 +static Bool miPointerUnrealizeCursor(DeviceIntPtr pDev, ScreenPtr pScreen, 
 +                                     CursorPtr pCursor);
 +static Bool miPointerDisplayCursor(DeviceIntPtr pDev, ScreenPtr pScreen, 
 +                                   CursorPtr pCursor);
 +static void miPointerConstrainCursor(DeviceIntPtr pDev, ScreenPtr pScreen,
 +                                     BoxPtr pBox); 
 +static void miPointerPointerNonInterestBox(DeviceIntPtr pDev, 
 +                                           ScreenPtr pScreen, BoxPtr pBox);
 +static void miPointerCursorLimits(DeviceIntPtr pDev, ScreenPtr pScreen,
 +                                  CursorPtr pCursor, BoxPtr pHotBox, 
 +                                  BoxPtr pTopLeftBox);
 +static Bool miPointerSetCursorPosition(DeviceIntPtr pDev, ScreenPtr pScreen, 
 +                                       int x, int y,
  				       Bool generateEvent);
  static Bool miPointerCloseScreen(int index, ScreenPtr pScreen);
 -static void miPointerMove(ScreenPtr pScreen, int x, int y, unsigned long time);
 +static void miPointerMove(DeviceIntPtr pDev, ScreenPtr pScreen, 
 +                          int x, int y,
 +                          unsigned long time);
  
+ static xEvent* events; /* for WarpPointer MotionNotifies */
+ 
  _X_EXPORT Bool
  miPointerInitialize (pScreen, spriteFuncs, screenFuncs, waitForUpdate)
      ScreenPtr		    pScreen;
@@@ -139,29 -116,23 +141,30 @@@
      pScreen->SetCursorPosition = miPointerSetCursorPosition;
      pScreen->RecolorCursor = miRecolorCursor;
      pScreen->PointerNonInterestBox = miPointerPointerNonInterestBox;
 +
      /*
       * set up the pointer object
 +     * virtual core pointer ID is always 1, so we let it point to the matching
 +     * index in the array.
       */
 -    miPointer.pScreen = NULL;
 -    miPointer.pSpriteScreen = NULL;
 -    miPointer.pCursor = NULL;
 -    miPointer.pSpriteCursor = NULL;
 -    miPointer.limits.x1 = 0;
 -    miPointer.limits.x2 = 32767;
 -    miPointer.limits.y1 = 0;
 -    miPointer.limits.y2 = 32767;
 -    miPointer.confined = FALSE;
 -    miPointer.x = 0;
 -    miPointer.y = 0;
 +    miCorePointer = &miPointers[1];
 +    for(ptrIdx = 0; ptrIdx < MAX_DEVICES; ptrIdx++)
 +    {
 +            pPointer = &miPointers[ptrIdx];
 +            pPointer->pScreen = NULL;
 +            pPointer->pSpriteScreen = NULL;
 +            pPointer->pCursor = NULL;
 +            pPointer->pSpriteCursor = NULL;
 +            pPointer->limits.x1 = 0;
 +            pPointer->limits.x2 = 32767;
 +            pPointer->limits.y1 = 0;
 +            pPointer->limits.y2 = 32767;
 +            pPointer->confined = FALSE;
 +            pPointer->x = 0;
 +            pPointer->y = 0;
 +    }
  
+     events = NULL;
 -
      return TRUE;
  }
  
@@@ -170,23 -141,16 +173,25 @@@
      int		index;
      ScreenPtr	pScreen;
  {
 +    miPointerPtr pPointer;
 +    int ptrIdx;
 +
      SetupScreen(pScreen);
  
 -    if (pScreen == miPointer.pScreen)
 -	miPointer.pScreen = 0;
 -    if (pScreen == miPointer.pSpriteScreen)
 -	miPointer.pSpriteScreen = 0;
 +    for(ptrIdx = 0; ptrIdx < MAX_DEVICES; ptrIdx++)
 +    {
 +        pPointer = &miPointers[ptrIdx];
 +
 +        if (pScreen == pPointer->pScreen)
 +            pPointer->pScreen = 0;
 +        if (pScreen == pPointer->pSpriteScreen)
 +            pPointer->pSpriteScreen = 0;
 +    }
 +
      pScreen->CloseScreen = pScreenPriv->CloseScreen;
      xfree ((pointer) pScreenPriv);
+     xfree ((pointer) events);
+     events = NULL;
      return (*pScreen->CloseScreen) (index, pScreen);
  }
  
@@@ -530,9 -471,33 +535,33 @@@
  }
  
  void
 -miPointerMove (ScreenPtr pScreen, int x, int y, unsigned long time)
 +miPointerMove (DeviceIntPtr pDev, ScreenPtr pScreen, int x, int y, unsigned long time)
  {
-     miPointerMoved(pDev, pScreen, x, y, time);
+     int i, nevents;
+     int valuators[2];
+ 
+     miPointerMoved(inputInfo.pointer, pScreen, x, y, time);
+ 
+     /* generate motion notify */
+     valuators[0] = x;
+     valuators[1] = y;
+ 
+     if (!events)
+     {
+         events = (xEvent*)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
+ 
+         if (!events)
+         {
+             FatalError("Could not allocate event store.\n");
+             return;
+         }
+     }
+ 
+     nevents = GetPointerEvents(events, inputInfo.pointer, MotionNotify, 0,
+                                POINTER_ABSOLUTE, 0, 2, valuators);
+ 
+     for (i = 0; i < nevents; i++)
+         mieqEnqueue(inputInfo.pointer, &events[i]);
  }
  
  /* Move the pointer on the current screen,  and update the sprite. */
@@@ -540,41 -505,18 +569,21 @@@
  miPointerMoved (DeviceIntPtr pDev, ScreenPtr pScreen, int x, int y,
                       unsigned long time)
  {
-     xEvent* events;
-     int i, nevents;
 +    int valuators[2];
 +    miPointerPtr pPointer = MIPOINTER(pDev);
      SetupScreen(pScreen);
  
 -    if (pDev && (pDev->coreEvents || pDev == inputInfo.pointer) &&
 -        !pScreenPriv->waitForUpdate && pScreen == miPointer.pSpriteScreen)
 +
 +    if (pDev && (pDev->coreEvents || pDev == inputInfo.pointer || pDev->isMPDev)
 +        && !pScreenPriv->waitForUpdate && pScreen == pPointer->pSpriteScreen)
      {
 -	miPointer.devx = x;
 -	miPointer.devy = y;
 -	if(!miPointer.pCursor->bits->emptyMask)
 -	    (*pScreenPriv->spriteFuncs->MoveCursor) (pScreen, x, y);
 +	pPointer->devx = x;
 +	pPointer->devy = y;
 +	if(!pPointer->pCursor->bits->emptyMask)
 +	    (*pScreenPriv->spriteFuncs->MoveCursor) (pDev, pScreen, x, y);
      }
  
 -    miPointer.x = x;
 -    miPointer.y = y;
 -    miPointer.pScreen = pScreen;
 +    pPointer->x = x;
 +    pPointer->y = y;
 +    pPointer->pScreen = pScreen;
- 
-     /* generate event here */
-     valuators[0] = x;
-     valuators[1] = y;
-     events = (xEvent*)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
-     if (!events)
-     {
-         FatalError("Could not allocate event store.\n");
- 	return;
-     }
- 
-     nevents = GetPointerEvents(events, pDev, MotionNotify, 0,
-                                POINTER_ABSOLUTE, 0, 2, valuators);
- 
-     for (i = 0; i < nevents; i++)
-         mieqEnqueue(pDev, &events[i]);
- 
-     xfree(events);
  }
diff-tree 12175b668a94e23994f724b366a691ec312cce69 (from ea1a72946d1aa4c256e6afb9d834c582ba4ac3a1)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Wed Nov 15 17:50:02 2006 +1030

    o fix minor error in comment for GetPointerEvents()

diff --git a/dix/getevents.c b/dix/getevents.c
index 935112d..77d1e21 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -470,7 +470,7 @@ GetKeyboardValuatorEvents(xEvent *events
 
 
 /**
- * Generate a series of xEvents (returned in xE) representing pointer
+ * Generate a series of xEvents (returned in events) representing pointer
  * motion, or button presses.  Xi and XKB-aware.
  *
  * events is not NULL-terminated; the return value is the number of events.
diff-tree ea1a72946d1aa4c256e6afb9d834c582ba4ac3a1 (from 04d15da95d608766c7832a7aa881be499c1395ba)
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Wed Feb 28 14:26:47 2007 -0800

    Add a canGrow argument to xf86InitialConfiguration.
    
    canGrow indicates to the DDX that the driver can enlarge the desktop via the
    xf86_config->funcs->resize hook.  If so, xf86InitialConfiguration will set
    virtual[XY] to match the configuration it chooses and will leave the crtc config
    size ranges alone.  If FALSE, it will bloat the screen to fit the largest probed
    mode and also set the crtc config max size to limit the desktop to the initial
    virtual[XY] size.

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index ebc0f8f..c53d2a8 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -734,12 +734,16 @@ xf86PickCrtcs (ScrnInfoPtr	scrn,
 
 /*
  * Compute the virtual size necessary to place all of the available
- * crtcs in the specified configuration and also large enough to
- * resize any crtc to the largest available mode
+ * crtcs in the specified configuration.
+ *
+ * canGrow indicates that the driver can make the screen larger than its initial
+ * configuration.  If FALSE, this function will enlarge the screen to include
+ * the largest available mode.
  */
 
 static void
-xf86DefaultScreenLimits (ScrnInfoPtr scrn, int *widthp, int *heightp)
+xf86DefaultScreenLimits (ScrnInfoPtr scrn, int *widthp, int *heightp,
+			 Bool canGrow)
 {
     xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
     int	    width = 0, height = 0;
@@ -757,26 +761,28 @@ xf86DefaultScreenLimits (ScrnInfoPtr scr
 	    crtc_width = crtc->x + xf86ModeWidth (&crtc->desiredMode, crtc->desiredRotation);
 	    crtc_height = crtc->y + xf86ModeHeight (&crtc->desiredMode, crtc->desiredRotation);
 	}
-	for (o = 0; o < config->num_output; o++) 
-	{
-	    xf86OutputPtr   output = config->output[o];
+	if (!canGrow) {
+	    for (o = 0; o < config->num_output; o++)
+	    {
+		xf86OutputPtr   output = config->output[o];
 
-	    for (s = 0; s < config->num_crtc; s++)
-		if (output->possible_crtcs & (1 << s))
-		{
-		    DisplayModePtr  mode;
-		    for (mode = output->probed_modes; mode; mode = mode->next)
+		for (s = 0; s < config->num_crtc; s++)
+		    if (output->possible_crtcs & (1 << s))
 		    {
-			if (mode->HDisplay > crtc_width)
-			    crtc_width = mode->HDisplay;
-			if (mode->VDisplay > crtc_width)
-			    crtc_width = mode->VDisplay;
-			if (mode->VDisplay > crtc_height)
-			    crtc_height = mode->VDisplay;
-			if (mode->HDisplay > crtc_height)
-			    crtc_height = mode->HDisplay;
+			DisplayModePtr  mode;
+			for (mode = output->probed_modes; mode; mode = mode->next)
+			{
+			    if (mode->HDisplay > crtc_width)
+				crtc_width = mode->HDisplay;
+			    if (mode->VDisplay > crtc_width)
+				crtc_width = mode->VDisplay;
+			    if (mode->VDisplay > crtc_height)
+				crtc_height = mode->VDisplay;
+			    if (mode->HDisplay > crtc_height)
+				crtc_height = mode->HDisplay;
+			}
 		    }
-		}
+	    }
 	}
 	if (crtc_width > width)
 	    width = crtc_width;
@@ -1350,10 +1356,17 @@ xf86SetScrnInfoModes (ScrnInfoPtr scrn)
  *
  * Given auto-detected (and, eventually, configured) values,
  * construct a usable configuration for the system
+ *
+ * canGrow indicates that the driver can resize the screen to larger than its
+ * initially configured size via the config->funcs->resize hook.  If TRUE, this
+ * function will set virtualX and virtualY to match the initial configuration
+ * and leave config->max{Width,Height} alone.  If FALSE, it will bloat
+ * virtual[XY] to include the largest modes and set config->max{Width,Height}
+ * accordingly.
  */
 
 Bool
-xf86InitialConfiguration (ScrnInfoPtr	    scrn)
+xf86InitialConfiguration (ScrnInfoPtr scrn, Bool canGrow)
 {
     xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
     int			o, c;
@@ -1491,9 +1504,10 @@ xf86InitialConfiguration (ScrnInfoPtr	  
     if (scrn->display->virtualX == 0)
     {
 	/*
-	 * Expand virtual size to cover potential mode switches
+	 * Expand virtual size to cover the current config and potential mode
+	 * switches, if the driver can't enlarge the screen later.
 	 */
-	xf86DefaultScreenLimits (scrn, &width, &height);
+	xf86DefaultScreenLimits (scrn, &width, &height, canGrow);
     
 	scrn->display->virtualX = width;
 	scrn->display->virtualY = height;
@@ -1503,7 +1517,23 @@ xf86InitialConfiguration (ScrnInfoPtr	  
 	scrn->virtualX = width;
     if (height > scrn->virtualY)
 	scrn->virtualY = height;
-    
+
+    /*
+     * Make sure the configuration isn't too small.
+     */
+    if (width < config->minWidth || height < config->minHeight)
+	return FALSE;
+
+    /*
+     * Limit the crtc config to virtual[XY] if the driver can't grow the
+     * desktop.
+     */
+    if (!canGrow)
+    {
+	xf86CrtcSetSizeRange (scrn, config->minWidth, config->minHeight,
+			      width, height);
+    }
+
     /* Mirror output modes to scrn mode list */
     xf86SetScrnInfoModes (scrn);
     
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
index 345332b..b04f7f3 100644
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -545,7 +545,7 @@ void
 xf86SetScrnInfoModes (ScrnInfoPtr pScrn);
 
 Bool
-xf86InitialConfiguration (ScrnInfoPtr pScrn);
+xf86InitialConfiguration (ScrnInfoPtr pScrn, Bool canGrow);
 
 void
 xf86DPMSSet(ScrnInfoPtr pScrn, int PowerManagementMode, int flags);
diff-tree 04d15da95d608766c7832a7aa881be499c1395ba (from b11dfac287d65de7b83f63749087cba4e8ddaf4a)
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Wed Feb 28 13:36:58 2007 -0800

    Add a screen resize hook to xf86CrtcConfigRec.
    
    This hook is called when the DDX needs to resize the screen.  The driver is
    responsible for changing virtualX and virtualY, along with any other related
    screen properties (devPrivate.ptr, devKind, displayWidth, etc.).
    
    Use the size range from the crtc config instead of randrp->virtual[XY] when
    reporting the min and max screen sizes to the DDX.

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index 29042a0..ebc0f8f 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -52,13 +52,17 @@
 int xf86CrtcConfigPrivateIndex = -1;
 
 void
-xf86CrtcConfigInit (ScrnInfoPtr scrn)
+xf86CrtcConfigInit (ScrnInfoPtr scrn,
+		    const xf86CrtcConfigFuncsRec *funcs)
 {
     xf86CrtcConfigPtr	config;
     
     if (xf86CrtcConfigPrivateIndex == -1)
 	xf86CrtcConfigPrivateIndex = xf86AllocateScrnInfoPrivateIndex();
     config = xnfcalloc (1, sizeof (xf86CrtcConfigRec));
+
+    config->funcs = funcs;
+
     scrn->privates[xf86CrtcConfigPrivateIndex].ptr = config;
 }
  
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
index 756730e..345332b 100644
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -407,6 +407,25 @@ struct _xf86Output {
 #endif
 };
 
+typedef struct _xf86CrtcConfigFuncs {
+    /**
+     * Requests that the driver resize the screen.
+     *
+     * The driver is responsible for updating scrn->virtualX and scrn->virtualY.
+     * If the requested size cannot be set, the driver should leave those values
+     * alone and return FALSE.
+     *
+     * A naive driver that cannot reallocate the screen may simply change
+     * virtual[XY].  A more advanced driver will want to also change the
+     * devPrivate.ptr and devKind of the screen pixmap, update any offscreen
+     * pixmaps it may have moved, and change pScrn->displayWidth.
+     */
+    Bool
+    (*resize)(ScrnInfoPtr	scrn,
+	      int		width,
+	      int		height);
+} xf86CrtcConfigFuncsRec, *xf86CrtcConfigFuncsPtr;
+
 typedef struct _xf86CrtcConfig {
     int			num_output;
     xf86OutputPtr	*output;
@@ -435,6 +454,8 @@ typedef struct _xf86CrtcConfig {
     int			dga_width, dga_height, dga_stride;
     DisplayModePtr	dga_save_mode;
 
+    const xf86CrtcConfigFuncsRec *funcs;
+
 } xf86CrtcConfigRec, *xf86CrtcConfigPtr;
 
 extern int xf86CrtcConfigPrivateIndex;
@@ -446,7 +467,8 @@ extern int xf86CrtcConfigPrivateIndex;
  */
 
 void
-xf86CrtcConfigInit (ScrnInfoPtr		scrn);
+xf86CrtcConfigInit (ScrnInfoPtr				scrn,
+		    const xf86CrtcConfigFuncsRec	*funcs);
 
 void
 xf86CrtcSetSizeRange (ScrnInfoPtr scrn,
diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index abdf92e..052d12a 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -335,8 +335,9 @@ xf86RandR12ScreenSetSize (ScreenPtr	pScr
 {
     XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
     ScrnInfoPtr		pScrn = XF86SCRNINFO(pScreen);
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(pScrn);
     WindowPtr		pRoot = WindowTable[pScreen->myNum];
-    Bool 		ret = TRUE;
+    Bool		ret = FALSE;
 
     if (randrp->virtualX == -1 || randrp->virtualY == -1)
     {
@@ -345,20 +346,26 @@ xf86RandR12ScreenSetSize (ScreenPtr	pScr
     }
     if (pRoot)
 	(*pScrn->EnableDisableFBAccess) (pScreen->myNum, FALSE);
-    pScrn->virtualX = width;
-    pScrn->virtualY = height;
 
-    pScreen->width = pScrn->virtualX;
-    pScreen->height = pScrn->virtualY;
+    /* Let the driver update virtualX and virtualY */
+    if (!(*config->funcs->resize)(pScrn, width, height))
+	goto finish;
+
+    ret = TRUE;
+
+    pScreen->width = width;
+    pScreen->height = height;
     pScreen->mmWidth = mmWidth;
     pScreen->mmHeight = mmHeight;
 
     xf86SetViewport (pScreen, pScreen->width-1, pScreen->height-1);
     xf86SetViewport (pScreen, 0, 0);
+
+finish:
     if (pRoot)
 	(*pScrn->EnableDisableFBAccess) (pScreen->myNum, TRUE);
 #if RANDR_12_INTERFACE
-    if (WindowTable[pScreen->myNum])
+    if (WindowTable[pScreen->myNum] && ret)
 	RRScreenSizeNotify (pScreen);
 #endif
     return ret;
@@ -904,15 +911,14 @@ xf86RandR12CreateScreenResources12 (Scre
 {
     int			c;
     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
-    XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
     xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
 
     for (c = 0; c < config->num_crtc; c++)
 	xf86RandR12CrtcNotify (config->crtc[c]->randr_crtc);
     
     
-    RRScreenSetSizeRange (pScreen, 320, 240,
-			  randrp->virtualX, randrp->virtualY);
+    RRScreenSetSizeRange (pScreen, config->minWidth, config->minHeight,
+			  config->maxWidth, config->maxHeight);
     return TRUE;
 }
 
diff-tree b11dfac287d65de7b83f63749087cba4e8ddaf4a (from 2dafc46e3d814e02b25e5a2fa2e931f0257402a8)
Author: Matthias Hopf <mhopf at suse.de>
Date:   Fri Mar 2 12:30:26 2007 +0100

    Legacy framebuffer support wasn't compiled if Xorg wasn't explicitly enabled.

diff --git a/configure.ac b/configure.ac
index 9cefc2a..9386d87 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1570,6 +1570,9 @@ AM_CONDITIONAL([XQUARTZ],[test "X$XQUART
 AM_CONDITIONAL(DGA, [test "x$DGA" = xyes])
 
 dnl legacy fb support
+test "x$MFB" = xauto && MFB="$XORG"
+test "x$CFB" = xauto && CFB="$XORG"
+test "x$AFB" = xauto && AFB="$XORG"
 AM_CONDITIONAL(MFB, [test "x$MFB" = xyes])
 AM_CONDITIONAL(CFB, [test "x$CFB" = xyes])
 AM_CONDITIONAL(AFB, [test "x$AFB" = xyes])
diff-tree 57aa5e908dc11d5d8c27ed705c526f1416c1e8ad (from e43b8a4e40991ca6e545bda4cf9b9bd7a2bf22e2)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Fri Mar 2 17:14:37 2007 +1030

    dix, Xext, Xtrap, Xi: replace inputInfo.pointer with PickPointer where
                          possible. More replacements to come.

diff --git a/XTrap/xtrapddmi.c b/XTrap/xtrapddmi.c
index c633b8d..ec094ec 100644
--- a/XTrap/xtrapddmi.c
+++ b/XTrap/xtrapddmi.c
@@ -97,8 +97,8 @@ int XETrapSimulateXEvent(register xXTrap
     xEvent xev;
     register int x = request->input.x;
     register int y = request->input.y;
-    DevicePtr keydev = LookupKeyboardDevice();
-    DevicePtr ptrdev = LookupPointerDevice();
+    DevicePtr keydev = (DevicePtr)PickKeyboard(client);
+    DevicePtr ptrdev = (DevicePtr)PickPointer(client);
 
     if (request->input.screen < screenInfo.numScreens)
     {
diff --git a/Xext/xtest.c b/Xext/xtest.c
index cb7b5b8..93e88c4 100644
--- a/Xext/xtest.c
+++ b/Xext/xtest.c
@@ -316,7 +316,7 @@ ProcXTestFakeInput(client)
 #ifdef XINPUT
 	if (!extension)
 #endif /* XINPUT */
-	    dev = (DeviceIntPtr)LookupKeyboardDevice();
+	    dev = PickKeyboard(client);
 	if (ev->u.u.detail < dev->key->curKeySyms.minKeyCode ||
 	    ev->u.u.detail > dev->key->curKeySyms.maxKeyCode)
 	{
@@ -361,7 +361,7 @@ ProcXTestFakeInput(client)
 	}
 #endif /* XINPUT */
         if (!dev)
-            dev = (DeviceIntPtr*)LookupPointerDevice();
+            dev = PickPointer(client);
 	if (ev->u.keyButtonPointer.root == None)
 	    root = GetCurrentRootWindow();
 	else
@@ -451,7 +451,7 @@ ProcXTestFakeInput(client)
 #ifdef XINPUT
 	if (!extension)
 #endif /* XINPUT */
-            dev = (DeviceIntPtr*)LookupPointerDevice();
+            dev = PickPointer(client);
 	if (!ev->u.u.detail || ev->u.u.detail > dev->button->numButtons)
 	{
 	    client->errorValue = ev->u.u.detail;
diff --git a/Xi/grabdevb.c b/Xi/grabdevb.c
index 4333550..d79a36c 100644
--- a/Xi/grabdevb.c
+++ b/Xi/grabdevb.c
@@ -140,7 +140,7 @@ ProcXGrabDeviceButton(ClientPtr client)
 	    return Success;
 	}
     } else
-	mdev = (DeviceIntPtr) LookupKeyboardDevice();
+	mdev = PickKeyboard(client);
 
     class = (XEventClass *) (&stuff[1]);	/* first word of values */
 
diff --git a/Xi/grabdevk.c b/Xi/grabdevk.c
index 71e72d5..1120149 100644
--- a/Xi/grabdevk.c
+++ b/Xi/grabdevk.c
@@ -137,7 +137,7 @@ ProcXGrabDeviceKey(ClientPtr client)
 	    return Success;
 	}
     } else
-	mdev = (DeviceIntPtr) LookupKeyboardDevice();
+	mdev = PickKeyboard(client);
 
     class = (XEventClass *) (&stuff[1]);	/* first word of values */
 
diff --git a/Xi/ungrdevb.c b/Xi/ungrdevb.c
index 8db9307..b75916f 100644
--- a/Xi/ungrdevb.c
+++ b/Xi/ungrdevb.c
@@ -133,7 +133,7 @@ ProcXUngrabDeviceButton(ClientPtr client
 	    return Success;
 	}
     } else
-	mdev = (DeviceIntPtr) LookupKeyboardDevice();
+	mdev = PickKeyboard(client);
 
     rc = dixLookupWindow(&pWin, stuff->grabWindow, client, DixUnknownAccess);
     if (rc != Success) {
diff --git a/Xi/ungrdevk.c b/Xi/ungrdevk.c
index ebb83bc..e8c006a 100644
--- a/Xi/ungrdevk.c
+++ b/Xi/ungrdevk.c
@@ -132,7 +132,7 @@ ProcXUngrabDeviceKey(ClientPtr client)
 	    return Success;
 	}
     } else
-	mdev = (DeviceIntPtr) LookupKeyboardDevice();
+	mdev = PickKeyboard(client);
 
     rc = dixLookupWindow(&pWin, stuff->grabWindow, client, DixUnknownAccess);
     if (rc != Success) {
diff --git a/dix/devices.c b/dix/devices.c
index f053e34..87b3927 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -597,6 +597,8 @@ RemoveDevice(DeviceIntPtr dev)
 int
 NumMotionEvents()
 {
+    /* only called to fill data in initial connection reply. 
+     * VCP is ok here, it is the only fixed device we have. */
     return inputInfo.pointer->valuator->numMotionEvents;
 }
 
@@ -1376,6 +1378,7 @@ ProcSetPointerMapping(ClientPtr client)
     REQUEST(xSetPointerMappingReq);
     BYTE *map;
     int ret;
+    DeviceIntPtr ptr = PickPointer(client);
     xSetPointerMappingReply rep;
 
     REQUEST_AT_LEAST_SIZE(xSetPointerMappingReq);
@@ -1389,14 +1392,18 @@ ProcSetPointerMapping(ClientPtr client)
     
     /* So we're bounded here by the number of core buttons.  This check
      * probably wants disabling through XFixes. */
-    if (stuff->nElts != inputInfo.pointer->button->numButtons) {
+    /* MPX: With ClientPointer, we can return the right number of buttons.
+     * Let's just hope nobody changed ClientPointer between GetPointerMapping
+     * and SetPointerMapping
+     */
+    if (stuff->nElts != ptr->button->numButtons) {
 	client->errorValue = stuff->nElts;
 	return BadValue;
     }
     if (BadDeviceMap(&map[0], (int)stuff->nElts, 1, 255, &client->errorValue))
 	return BadValue;
 
-    ret = DoSetPointerMapping(inputInfo.pointer, map, stuff->nElts);
+    ret = DoSetPointerMapping(ptr, map, stuff->nElts);
     if (ret != Success) {
         rep.success = ret;
         WriteReplyToClient(client, sizeof(xSetPointerMappingReply), &rep);
@@ -1404,7 +1411,7 @@ ProcSetPointerMapping(ClientPtr client)
     }
 
     /* FIXME: Send mapping notifies for all the extended devices as well. */
-    SendMappingNotify(inputInfo.pointer, MappingPointer, 0, 0, client);
+    SendMappingNotify(ptr, MappingPointer, 0, 0, client);
     WriteReplyToClient(client, sizeof(xSetPointerMappingReply), &rep);
     return Success;
 }
@@ -1414,7 +1421,8 @@ ProcGetKeyboardMapping(ClientPtr client)
 {
     xGetKeyboardMappingReply rep;
     REQUEST(xGetKeyboardMappingReq);
-    KeySymsPtr curKeySyms = &inputInfo.keyboard->key->curKeySyms;
+    DeviceIntPtr kbd = PickKeyboard(client);
+    KeySymsPtr curKeySyms = &kbd->key->curKeySyms;
 
     REQUEST_SIZE_MATCH(xGetKeyboardMappingReq);
 
@@ -1449,7 +1457,9 @@ int
 ProcGetPointerMapping(ClientPtr client)
 {
     xGetPointerMappingReply rep;
-    ButtonClassPtr butc = inputInfo.pointer->button;
+    /* Apps may get different values each time they call GetPointerMapping as
+     * the ClientPointer could change. */
+    ButtonClassPtr butc = PickPointer(client)->button;
 
     REQUEST_SIZE_MATCH(xReq);
     rep.type = X_Reply;
@@ -1753,7 +1763,7 @@ ProcBell(ClientPtr client)
 int
 ProcChangePointerControl(ClientPtr client)
 {
-    DeviceIntPtr mouse = inputInfo.pointer;
+    DeviceIntPtr mouse = PickPointer(client);
     PtrCtrl ctrl;		/* might get BadValue part way through */
     REQUEST(xChangePointerControlReq);
 
@@ -1809,7 +1819,7 @@ ProcChangePointerControl(ClientPtr clien
 
 
     for (mouse = inputInfo.devices; mouse; mouse = mouse->next) {
-        if ((mouse->coreEvents || mouse == inputInfo.pointer) &&
+        if ((mouse->coreEvents || mouse == PickPointer(client)) &&
             mouse->ptrfeed && mouse->ptrfeed->CtrlProc) {
             mouse->ptrfeed->ctrl = ctrl;
             (*mouse->ptrfeed->CtrlProc)(mouse, &mouse->ptrfeed->ctrl);
@@ -1822,7 +1832,8 @@ ProcChangePointerControl(ClientPtr clien
 int
 ProcGetPointerControl(ClientPtr client)
 {
-    register PtrCtrl *ctrl = &inputInfo.pointer->ptrfeed->ctrl;
+    DeviceIntPtr ptr = PickPointer(client);
+    PtrCtrl *ctrl = &ptr->ptrfeed->ctrl;
     xGetPointerControlReply rep;
 
     REQUEST_SIZE_MATCH(xReq);
@@ -1860,7 +1871,7 @@ ProcGetMotionEvents(ClientPtr client)
     xGetMotionEventsReply rep;
     int i, count, xmin, xmax, ymin, ymax, rc;
     unsigned long nEvents;
-    DeviceIntPtr mouse = inputInfo.pointer;
+    DeviceIntPtr mouse = PickPointer(client);
     TimeStamp start, stop;
     REQUEST(xGetMotionEventsReq);
 
diff-tree e43b8a4e40991ca6e545bda4cf9b9bd7a2bf22e2 (from 43bd35fcf85b51b7e5714844bade90184dbd746f)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Fri Mar 2 15:21:46 2007 +1030

    dix:    Add ClientPointer to client, used for picking which pointer to use in
            ambiguious request. PickPointer and PickKeyboard are used for getting
            the appropriate pointer when situation is unclear.
            Fix some issues with InitializeSprite.
    
    dix, xfree86: Remove last traces of InitSprite.

diff --git a/dix/devices.c b/dix/devices.c
index 747d782..f053e34 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -342,6 +342,7 @@ InitCoreDevices()
         dev->ActivateGrab = ActivateKeyboardGrab;
         dev->DeactivateGrab = DeactivateKeyboardGrab;
         dev->coreEvents = FALSE;
+        dev->spriteOwner = FALSE;
         if (!AllocateDevicePrivate(dev, CoreDevicePrivatesIndex))
             FatalError("Couldn't allocate keyboard devPrivates\n");
         dev->devPrivates[CoreDevicePrivatesIndex].ptr = NULL;
@@ -369,12 +370,12 @@ InitCoreDevices()
         if (!AllocateDevicePrivate(dev, CoreDevicePrivatesIndex))
             FatalError("Couldn't allocate pointer devPrivates\n");
         dev->devPrivates[CoreDevicePrivatesIndex].ptr = NULL;
-        InitSprite(dev, TRUE);
+        InitializeSprite(dev, NullWindow);
         (void)ActivateDevice(dev);
         inputInfo.pointer = dev;
         /* the core keyboard is initialised by now. set the keyboard's sprite
          * to the core pointer's sprite. */
-        InitSprite(inputInfo.keyboard, FALSE);
+        PairDevices(pairingClient, inputInfo.pointer, inputInfo.keyboard);
     }
 }
 
@@ -421,6 +422,7 @@ CloseDevice(register DeviceIntPtr dev)
     StringFeedbackPtr s, snext;
     BellFeedbackPtr b, bnext;
     LedFeedbackPtr l, lnext;
+    int j;
 
     if (dev->inited)
 	(void)(*dev->deviceProc)(dev, DEVICE_CLOSE);
@@ -504,6 +506,13 @@ CloseDevice(register DeviceIntPtr dev)
     if (DevHasCursor(dev))
         xfree((pointer)dev->pSprite);
 
+    /* a client may have the device set as client pointer */
+    for (j = 0; j < currentMaxClients; j++)
+    {
+        if (clients[j]->clientPtr == dev)
+            PickPointer(clients[j]);
+    }
+
     xfree(dev->sync.event);
     xfree(dev);
 }
@@ -1955,6 +1964,25 @@ PairDevices(ClientPtr client, DeviceIntP
     return Success;
 }
 
+/* Return the pointer that is paired with the given keyboard. If no pointer is
+ * paired, return the virtual core pointer 
+ */ 
+DeviceIntPtr
+GetPairedPointer(DeviceIntPtr kbd)
+{
+    DeviceIntPtr ptr = inputInfo.devices;
+    while(ptr)
+    {
+        if (ptr->pSprite == kbd->pSprite && ptr->spriteOwner)
+        {
+            return ptr;
+        }
+        ptr = ptr->next;
+    }
+
+    return inputInfo.pointer;
+}
+
 /*
  * Register a client to be able to pair devices. 
  */
diff --git a/dix/dispatch.c b/dix/dispatch.c
index 98183cc..54931a1 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -3730,6 +3730,8 @@ void InitClient(ClientPtr client, int i,
     client->smart_stop_tick = SmartScheduleTime;
     client->smart_check_tick = SmartScheduleTime;
 #endif
+
+    client->clientPtr = NULL;
 }
 
 int
diff --git a/dix/events.c b/dix/events.c
index a1e72f1..5be923a 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1508,8 +1508,8 @@ int
 ProcAllowEvents(register ClientPtr client)
 {
     TimeStamp		time;
-    DeviceIntPtr	mouse = inputInfo.pointer;
-    DeviceIntPtr	keybd = inputInfo.keyboard;
+    DeviceIntPtr	mouse = PickPointer(client);
+    DeviceIntPtr	keybd = PickKeyboard(client);
     REQUEST(xAllowEventsReq);
 
     REQUEST_SIZE_MATCH(xAllowEventsReq);
@@ -2103,7 +2103,7 @@ CheckMotion(xEvent *xE, DeviceIntPtr pDe
     pSprite->win = XYToWindow(pSprite->hot.x, pSprite->hot.y);
 #ifdef notyet
     if (!(pSprite->win->deliverableEvents &
-	  Motion_Filter(inputInfo.pointer->button))
+	  Motion_Filter(pDev->button))
 	!syncEvents.playingEvents)
     {
 	/* XXX Do PointerNonInterestBox here */
@@ -2220,15 +2220,23 @@ InitializeSprite(DeviceIntPtr pDev, Wind
             FatalError("InitializeSprite: failed to allocate sprite struct");
     }
 
-    pScreen = (pWin) ? pWin->drawable.pScreen : (ScreenPtr)NULL;
     pSprite = pDev->pSprite;
+    pDev->spriteOwner = TRUE;
+
+    pScreen = (pWin) ? pWin->drawable.pScreen : (ScreenPtr)NULL;
+    pSprite->hot.pScreen = pScreen;
     pSprite->hotPhys.pScreen = pScreen;
-    pSprite->hotPhys.x = pScreen->width / 2;
-    pSprite->hotPhys.y = pScreen->height / 2;
+    if (pScreen)
+    {
+        pSprite->hotPhys.x = pScreen->width / 2;
+        pSprite->hotPhys.y = pScreen->height / 2;
+        pSprite->hotLimits.x2 = pScreen->width;
+        pSprite->hotLimits.y2 = pScreen->height;
+    }
+
     pSprite->hot = pSprite->hotPhys;
-    pSprite->hotLimits.x2 = pScreen->width;
-    pSprite->hotLimits.y2 = pScreen->height;
     pSprite->win = pWin;
+
     if (pWin)
     {
         pSprite->current = wCursor(pWin);
@@ -2236,16 +2244,19 @@ InitializeSprite(DeviceIntPtr pDev, Wind
     } else
         pSprite->current = NullCursor;
 
-    (*pScreen->CursorLimits) ( pDev, pScreen, pSprite->current,
-                               &pSprite->hotLimits, &pSprite->physLimits);
-    pSprite->confined = FALSE;
-
-    (*pScreen->ConstrainCursor) (pDev, pScreen,
-                                 &pSprite->physLimits);
-    (*pScreen->SetCursorPosition) (pDev, pScreen, pSprite->hot.x,
-                                   pSprite->hot.y,
-                                   FALSE); 
-    (*pScreen->DisplayCursor) (pDev, pScreen, pSprite->current);
+    if (pScreen)
+    {
+        (*pScreen->CursorLimits) ( pDev, pScreen, pSprite->current,
+                                   &pSprite->hotLimits, &pSprite->physLimits);
+        pSprite->confined = FALSE;
+
+        (*pScreen->ConstrainCursor) (pDev, pScreen,
+                                     &pSprite->physLimits);
+        (*pScreen->SetCursorPosition) (pDev, pScreen, pSprite->hot.x,
+                                       pSprite->hot.y,
+                                       FALSE); 
+        (*pScreen->DisplayCursor) (pDev, pScreen, pSprite->current);
+    }
 #ifdef PANORAMIX
     if(!noPanoramiXExtension) {
         pSprite->hotLimits.x1 = -panoramiXdataPtr[0].x;
@@ -2264,7 +2275,6 @@ InitializeSprite(DeviceIntPtr pDev, Wind
     }
 #endif
 
-    pDev->spriteOwner = TRUE;
 }
 
 /*
@@ -2370,7 +2380,7 @@ XineramaWarpPointer(ClientPtr client)
 {
     WindowPtr	dest = NULL;
     int		x, y, rc;
-    SpritePtr   pSprite = inputInfo.pointer->pSprite;
+    SpritePtr   pSprite = PickPointer(client)->pSprite;
 
     REQUEST(xWarpPointerReq);
 
@@ -2429,9 +2439,9 @@ XineramaWarpPointer(ClientPtr client)
     else if (y >= pSprite->physLimits.y2)
 	y = pSprite->physLimits.y2 - 1;
     if (pSprite->hotShape)
-	ConfineToShape(inputInfo.pointer, pSprite->hotShape, &x, &y);
+	ConfineToShape(PickPointer(client), pSprite->hotShape, &x, &y);
 
-    XineramaSetCursorPosition(inputInfo.pointer, x, y, TRUE);
+    XineramaSetCursorPosition(PickPointer(client), x, y, TRUE);
 
     return Success;
 }
@@ -2445,7 +2455,7 @@ ProcWarpPointer(ClientPtr client)
     WindowPtr	dest = NULL;
     int		x, y, rc;
     ScreenPtr	newScreen;
-    SpritePtr   pSprite = inputInfo.pointer->pSprite;
+    SpritePtr   pSprite = PickPointer(client)->pSprite;
 
     REQUEST(xWarpPointerReq);
 
@@ -2518,14 +2528,14 @@ ProcWarpPointer(ClientPtr client)
 	    y = pSprite->physLimits.y2 - 1;
 #if defined(SHAPE)
 	if (pSprite->hotShape)
-	    ConfineToShape(inputInfo.pointer, pSprite->hotShape, &x, &y);
+	    ConfineToShape(PickPointer(client), pSprite->hotShape, &x, &y);
 #endif
-        (*newScreen->SetCursorPosition)(inputInfo.pointer, newScreen, x, y,
+        (*newScreen->SetCursorPosition)(PickPointer(client), newScreen, x, y,
                                         TRUE); 
     }
-    else if (!PointerConfinedToScreen(inputInfo.pointer))
+    else if (!PointerConfinedToScreen(PickPointer(client)))
     {
-	NewCurrentScreen(inputInfo.pointer, newScreen, x, y);
+	NewCurrentScreen(PickPointer(client), newScreen, x, y);
     }
     return Success;
 }
@@ -2892,7 +2902,7 @@ drawable.id:0;
 #endif
     )))
 #endif
-    XE_KBPTR.state = (keyc->state | inputInfo.pointer->button->state);
+    XE_KBPTR.state = (keyc->state | GetPairedPointer(keybd)->button->state);
     XE_KBPTR.rootX = keybd->pSprite->hot.x;
     XE_KBPTR.rootY = keybd->pSprite->hot.y;
     key = xE->u.u.detail;
@@ -2925,7 +2935,7 @@ drawable.id:0;
 		}
 		return;
 	    }
-	    inputInfo.pointer->valuator->motionHintWindow = NullWindow;
+	    GetPairedPointer(keybd)->valuator->motionHintWindow = NullWindow;
 	    *kptr |= bit;
 	    keyc->prev_state = keyc->state;
 	    for (i = 0, mask = 1; modifiers; i++, mask <<= 1)
@@ -2947,7 +2957,7 @@ drawable.id:0;
 	case KeyRelease: 
 	    if (!(*kptr & bit)) /* guard against duplicates */
 		return;
-	    inputInfo.pointer->valuator->motionHintWindow = NullWindow;
+	    GetPairedPointer(keybd)->valuator->motionHintWindow = NullWindow;
 	    *kptr &= ~bit;
 	    keyc->prev_state = keyc->state;
 	    for (i = 0, mask = 1; modifiers; i++, mask <<= 1)
@@ -3837,7 +3847,7 @@ int
 ProcGrabPointer(ClientPtr client)
 {
     xGrabPointerReply rep;
-    DeviceIntPtr device = inputInfo.pointer;
+    DeviceIntPtr device = PickPointer(client);
     GrabPtr grab;
     WindowPtr pWin, confineTo;
     CursorPtr cursor, oldCursor;
@@ -3945,7 +3955,7 @@ ProcGrabPointer(ClientPtr client)
 int
 ProcChangeActivePointerGrab(ClientPtr client)
 {
-    DeviceIntPtr device = inputInfo.pointer;
+    DeviceIntPtr device = PickPointer(client);
     register GrabPtr grab = device->grab;
     CursorPtr newCursor, oldCursor;
     REQUEST(xChangeActivePointerGrabReq);
@@ -3991,7 +4001,7 @@ ProcChangeActivePointerGrab(ClientPtr cl
 int
 ProcUngrabPointer(ClientPtr client)
 {
-    DeviceIntPtr device = inputInfo.pointer;
+    DeviceIntPtr device = PickPointer(client);
     GrabPtr grab;
     TimeStamp time;
     REQUEST(xResourceReq);
@@ -4122,7 +4132,7 @@ ProcQueryPointer(ClientPtr client)
 {
     xQueryPointerReply rep;
     WindowPtr pWin, t;
-    DeviceIntPtr mouse = inputInfo.pointer;
+    DeviceIntPtr mouse = PickPointer(client);
     SpritePtr pSprite = mouse->pSprite;
     int rc;
 
@@ -4224,37 +4234,6 @@ InitEvents()
 }
 
 
-/**
- * Initialize a sprite structure for the given device. If hasCursor is False,
- * let the device use the core pointer's sprite structure.
- */
-void 
-InitSprite(DeviceIntPtr pDev, Bool hasCursor)
-{
-    if (hasCursor)
-    {
-        SpritePtr pSprite = (SpritePtr)xalloc(sizeof(SpriteRec));
-        if (!pSprite)
-            FatalError("failed to allocate sprite struct");
-        memset(pSprite, 0, sizeof(SpriteRec));
-        pSprite->hot.pScreen = pSprite->hotPhys.pScreen = (ScreenPtr)NULL;
-        pSprite->win = NullWindow;
-        pSprite->current = NullCursor;
-        pSprite->hotLimits.x1 = 0;
-        pSprite->hotLimits.y1 = 0;
-        pSprite->hotLimits.x2 = 0;
-        pSprite->hotLimits.y2 = 0;
-        pSprite->confined = FALSE;
-
-        pDev->pSprite = pSprite;
-        pDev->spriteOwner = TRUE;
-    } else
-    {
-        pDev->pSprite = inputInfo.pointer->pSprite;
-        pDev->spriteOwner = FALSE;
-    }
-}
-
 void
 CloseDownEvents(void)
 {
@@ -4268,7 +4247,7 @@ ProcSendEvent(ClientPtr client)
 {
     WindowPtr pWin;
     WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */
-    SpritePtr pSprite = inputInfo.pointer->pSprite;
+    SpritePtr pSprite = PickPointer(client)->pSprite;
     REQUEST(xSendEventReq);
 
     REQUEST_SIZE_MATCH(xSendEventReq);
@@ -4335,8 +4314,8 @@ ProcSendEvent(ClientPtr client)
     {
 	for (;pWin; pWin = pWin->parent)
 	{
-            if (DeliverEventsToWindow(inputInfo.pointer, pWin, &stuff->event,
-                                    1, stuff->eventMask, NullGrab, 0))
+            if (DeliverEventsToWindow(PickPointer(client), pWin,
+                        &stuff->event, 1, stuff->eventMask, NullGrab, 0))
 		return Success;
 	    if (pWin == effectiveFocus)
 		return Success;
@@ -4346,8 +4325,8 @@ ProcSendEvent(ClientPtr client)
 	}
     }
     else
-        (void)DeliverEventsToWindow(inputInfo.pointer, pWin, &stuff->event, 1,
-                                    stuff->eventMask, NullGrab, 0);
+        (void)DeliverEventsToWindow(PickPointer(client), pWin, &stuff->event,
+                                    1, stuff->eventMask, NullGrab, 0);
     return Success;
 }
 
@@ -4511,7 +4490,7 @@ ProcGrabButton(ClientPtr client)
     }
 
 
-    grab = CreateGrab(client->index, inputInfo.pointer, pWin, 
+    grab = CreateGrab(client->index, PickPointer(client), pWin, 
         (Mask)stuff->eventMask, (Bool)stuff->ownerEvents,
         (Bool) stuff->keyboardMode, (Bool)stuff->pointerMode,
         inputInfo.keyboard, stuff->modifiers, ButtonPress,
@@ -4540,7 +4519,7 @@ ProcUngrabButton(ClientPtr client)
     if (rc != Success)
 	return rc;
     tempGrab.resource = client->clientAsMask;
-    tempGrab.device = inputInfo.pointer;
+    tempGrab.device = PickPointer(client);
     tempGrab.window = pWin;
     tempGrab.modifiersDetail.exact = stuff->modifiers;
     tempGrab.modifiersDetail.pMask = NULL;
@@ -4694,7 +4673,7 @@ ProcRecolorCursor(ClientPtr client)
     int		nscr;
     ScreenPtr	pscr;
     Bool 	displayed;
-    SpritePtr   pSprite = inputInfo.pointer->pSprite;
+    SpritePtr   pSprite = PickPointer(client)->pSprite;
     REQUEST(xRecolorCursorReq);
 
     REQUEST_SIZE_MATCH(xRecolorCursorReq);
@@ -4723,7 +4702,7 @@ ProcRecolorCursor(ClientPtr client)
 	else
 #endif
 	    displayed = (pscr == pSprite->hotPhys.pScreen);
-	( *pscr->RecolorCursor)(inputInfo.pointer, pscr, pCursor,
+	( *pscr->RecolorCursor)(PickPointer(client), pscr, pCursor,
 				(pCursor == pSprite->current) && displayed);
     }
     return (Success);
@@ -4810,3 +4789,59 @@ WriteEventsToClient(ClientPtr pClient, i
 	(void)WriteToClient(pClient, count * sizeof(xEvent), (char *) events);
     }
 }
+
+/* PickPointer will pick an appropriate pointer for the given client.
+ *
+ * If a client pointer is set, it will pick the client pointer, otherwise the
+ * first available pointer in the list. If no physical device is attached, it
+ * will pick the core pointer.
+ */
+_X_EXPORT DeviceIntPtr
+PickPointer(ClientPtr client)
+{
+    if (!client->clientPtr)
+    {
+        /* look if there is a real device attached */
+        DeviceIntPtr it = inputInfo.devices;
+        while (it)
+        {
+            if (it != inputInfo.pointer && it->spriteOwner)
+            {
+                client->clientPtr = it;
+                break;
+            }
+            it = it->next;
+        }
+
+        if (!it)
+        {
+            ErrorF("Picking VCP\n");
+            client->clientPtr = inputInfo.pointer;
+        }
+    }
+    return client->clientPtr;
+}
+
+/* PickKeyboard will pick an appropriate keyboard for the given client by
+ * searching the list of devices for the keyboard device that is paired with
+ * the client's pointer.
+ * If no pointer is paired with the keyboard, the virtual core keyboard is
+ * returned.
+ */
+_X_EXPORT DeviceIntPtr
+PickKeyboard(ClientPtr client)
+{
+    DeviceIntPtr dev;
+    DeviceIntPtr ptr = inputInfo.devices;
+    ptr = PickPointer(client);
+
+    while(dev)
+    {
+        if (ptr->pSprite == dev->pSprite)
+            return dev;
+        dev = dev->next;
+    }
+
+    return inputInfo.keyboard;
+}
+
diff --git a/hw/xfree86/common/xf86Xinput.c b/hw/xfree86/common/xf86Xinput.c
index 41118c0..31be1e3 100644
--- a/hw/xfree86/common/xf86Xinput.c
+++ b/hw/xfree86/common/xf86Xinput.c
@@ -188,9 +188,9 @@ xf86ActivateDevice(LocalDevicePtr local)
 
         /* Only create a new sprite if it's a non-shared pointer */
         if (IsPointerDevice(dev) && dev->isMPDev)
-            InitializeSprite(pDev, NullWindow);
+            InitializeSprite(dev, GetCurrentRootWindow());
         else 
-            PairDevices(pairingClient, inputInfo.pointer, pDev);
+            PairDevices(NULL, inputInfo.pointer, dev);
 
         RegisterOtherDevice(dev);
 
@@ -425,8 +425,6 @@ NewInputDeviceRequest (InputOption *opti
         EnableDevice(dev);
 
     /* send enter/leave event, update sprite window */
-    if (dev->spriteOwner)
-        InitializeSprite(dev, GetCurrentRootWindow());
     CheckMotion(NULL, dev);
 
     return Success;
diff --git a/include/dix.h b/include/dix.h
index 1c6b163..95c69f0 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -602,6 +602,12 @@ extern int TryClientEvents(
 
 extern void WindowsRestructured(void);
 
+extern DeviceIntPtr PickPointer(
+    ClientPtr /* client */);
+
+extern DeviceIntPtr PickKeyboard(
+    ClientPtr /* client */);
+
 #ifdef PANORAMIX
 extern void ReinitializeRootWindow(WindowPtr win, int xoff, int yoff);
 #endif
diff --git a/include/dixstruct.h b/include/dixstruct.h
index b5ffcca..530009a 100644
--- a/include/dixstruct.h
+++ b/include/dixstruct.h
@@ -140,6 +140,8 @@ typedef struct _Client {
     long    smart_stop_tick;
     long    smart_check_tick;
 #endif
+    
+    DeviceIntPtr clientPtr;
 }           ClientRec;
 
 #ifdef SMART_SCHEDULE
diff --git a/include/input.h b/include/input.h
index a7b1e84..433cc94 100644
--- a/include/input.h
+++ b/include/input.h
@@ -450,6 +450,8 @@ extern int PairDevices(ClientPtr client,
                        DeviceIntPtr pointer, 
                        DeviceIntPtr keyboard);
 
+extern DeviceIntPtr GetPairedPointer(DeviceIntPtr kbd);
+
 extern Bool RegisterPairingClient(ClientPtr client);
 extern Bool UnregisterPairingClient(ClientPtr client);
 
diff-tree 2dafc46e3d814e02b25e5a2fa2e931f0257402a8 (from 39ecd6fff4f946deebe310b4b26b171c842db223)
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Thu Mar 1 17:44:39 2007 -0800

    Fixed pointer events in Xquartz -- Keyboard events work, but
    the keycodes are incorrect.

diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 3982d97..0be1e40 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -867,7 +867,8 @@ static void send_nsevent (NSEventType ty
     int valuators[2];
     float count;
     xEvent xe;
-    
+    char nullbyte=0;
+
     bzero(&xe, sizeof(xe));
     input_check_flag++;
 	
@@ -886,10 +887,10 @@ static void send_nsevent (NSEventType ty
       pointer_y = (screen.origin.y + screen.size.height) - location.y;
     }
     
-    ErrorF("send_nsevent: type=%d pointer=(%d,%d)\n", type, pointer_x, pointer_y);
+//    ErrorF("send_nsevent: type=%d pointer=(%d,%d)\n", type, pointer_x, pointer_y);
     
     valuators[0] = pointer_x;
-    valuators[1] = pointer_y;
+    valuators[1] = pointer_y - aquaMenuBarHeight;
     state = convert_flags ([e modifierFlags]);
     
     switch (type) {
@@ -916,12 +917,8 @@ static void send_nsevent (NSEventType ty
       num_events = GetPointerEvents(quartzEvents, darwinPointer, ev_type, ev_button, 
 				    POINTER_ABSOLUTE, 0, 2, valuators);
       
-      ErrorF("GetPointerEvents returned %d events\n", num_events);
-      for(i=0; i<num_events; i++) {
-	ErrorF("qe[%d].u.u.type=%d\n", i, quartzEvents[i].u.u.type);
-//				quartzEvents[i].u.keyButtonPointer.state = state;
+      for(i=0; i<num_events; i++)
 	mieqEnqueue (darwinPointer,&quartzEvents[i]);
-      }
       break;
     case NSScrollWheel: 
       count = [e deltaY];
@@ -929,28 +926,23 @@ static void send_nsevent (NSEventType ty
       for (count = fabs(count); count > 0.0; count = count - 1.0f) {
 	num_events = GetPointerEvents(quartzEvents, darwinPointer, ButtonPress, ev_button, 
 				      POINTER_ABSOLUTE, 0, 2, valuators);
-	for(i=0; i<num_events; i++) {
-//						quartzEvents[i].u.keyButtonPointer.state = state;
+	for(i=0; i<num_events; i++) 
 	  mieqEnqueue(darwinPointer,&quartzEvents[i]);
-	}
 	num_events = GetPointerEvents(quartzEvents, darwinPointer, ButtonRelease, ev_button, 
 				      POINTER_ABSOLUTE, 0, 2, valuators);
-	for(i=0; i<num_events; i++) {
-//						quartzEvents[i].u.keyButtonPointer.state = state;
+	for(i=0; i<num_events; i++)
 	  mieqEnqueue(darwinPointer,&quartzEvents[i]);
-	}
       }
       break;
       
-    case NSKeyDown:
+    case NSKeyDown:  // do we need to translate these keyCodes?
     case NSKeyUp:
       num_events = GetKeyboardEvents(quartzEvents, darwinKeyboard, 
 				     (type == NSKeyDown)?KeyPress:KeyRelease, [e keyCode]);
-      for(i=0; i<num_events; i++) {
-//				quartzEvents[i].u.keyButtonPointer.state = state;
+      for(i=0; i<num_events; i++) 
 	mieqEnqueue(darwinKeyboard,&quartzEvents[i]);
-      }
       break;
+
     case NSFlagsChanged:
       xe.u.u.type = kXDarwinUpdateModifiers;
       xe.u.clientMessage.u.l.longs0 = [e modifierFlags];
@@ -958,5 +950,6 @@ static void send_nsevent (NSEventType ty
       break;
     default: break; /* for gcc */
     }	
-    //	UpdateCurrentTime();
+    //  <daniels> bushing: oh, i ... er ... christ.
+    write(darwinEventWriteFD, &nullbyte, 1);
 }
diff --git a/hw/darwin/quartz/applewm.c b/hw/darwin/quartz/applewm.c
index 869f7a9..cc11cfa 100644
--- a/hw/darwin/quartz/applewm.c
+++ b/hw/darwin/quartz/applewm.c
@@ -446,7 +446,11 @@ ProcAppleWMSetWindowMenu(
         }
     }
 
+#ifdef INXQUARTZ
+    X11ApplicationSetWindowMenu (nitems, items, shortcuts);
+#else
     QuartzSetWindowMenu (nitems, items, shortcuts);
+#endif
 
     free(items);
     free(shortcuts);
@@ -462,10 +466,12 @@ ProcAppleWMSetWindowMenuCheck(
     REQUEST(xAppleWMSetWindowMenuCheckReq);
 
     REQUEST_SIZE_MATCH(xAppleWMSetWindowMenuCheckReq);
-
+#ifdef INXQUARTZ
+    X11ApplicationSetWindowMenuCheck(stuff->index);
+#else
     QuartzMessageMainThread(kQuartzSetWindowMenuCheck, &stuff->index,
                             sizeof(stuff->index));
-
+#endif
     return (client->noClientException);
 }
 
@@ -475,9 +481,11 @@ ProcAppleWMSetFrontProcess(
 )
 {
     REQUEST_SIZE_MATCH(xAppleWMSetFrontProcessReq);
-
+#ifdef INXQUARTZ
+    X11ApplicationSetFrontProcess();
+#else
     QuartzMessageMainThread(kQuartzSetFrontProcess, NULL, 0);
-
+#endif
     return (client->noClientException);
 }
 
@@ -516,9 +524,12 @@ ProcAppleWMSetCanQuit(
     REQUEST(xAppleWMSetCanQuitReq);
 
     REQUEST_SIZE_MATCH(xAppleWMSetCanQuitReq);
-
+#ifdef INXQUARTZ
+    X11ApplicationSetCanQuit(stuff->state);
+#else
     QuartzMessageMainThread(kQuartzSetCanQuit, &stuff->state,
                             sizeof(stuff->state));
+#endif
 
     return (client->noClientException);
 }
diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 913ea72..038b21e 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -160,7 +160,11 @@ void DarwinModeInitInput(
     int argc,
     char **argv )
 {
+#ifdef INXQUARTZ
+  X11ApplicationServerReady();
+#else
     QuartzMessageMainThread(kQuartzServerStarted, NULL, 0);
+#endif
 
     // Do final display mode specific initialization before handling events
     if (quartzProcs->InitInput)
@@ -274,7 +278,9 @@ static void QuartzHide(void)
         }
     }
     quartzServerVisible = FALSE;
+#ifndef INXQUARTZ
     QuartzMessageMainThread(kQuartzServerHidden, NULL, 0);
+#endif
 }
 
 
diff --git a/hw/darwin/quartz/quartzCursor.c b/hw/darwin/quartz/quartzCursor.c
index 1e618e3..6ed6a76 100644
--- a/hw/darwin/quartz/quartzCursor.c
+++ b/hw/darwin/quartz/quartzCursor.c
@@ -93,7 +93,9 @@ static pthread_cond_t cursorCondition;
         /* Acquire lock and tell the main thread to change cursor */    \
         pthread_mutex_lock(&cursorMutex);                               \
         currentCursor = (CCrsrHandle) (cursorH);                        \
+#ifndef INXQUARTZ
         QuartzMessageMainThread(kQuartzCursorUpdate, NULL, 0);          \
+#endif
                                                                         \
         /* Wait for the main thread to change the cursor */             \
         pthread_cond_wait(&cursorCondition, &cursorMutex);              \
diff-tree 39ecd6fff4f946deebe310b4b26b171c842db223 (from ed7ccc481ad1caaa518cafe944c2327a5d0b6c65)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Thu Mar 1 01:45:19 2007 -0800

    Rewrote parts of the Xquartz event-handling code (thanks daniels and whot!)
    It should still be considered a work in progress, but mouse events almost work.

diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 5da0574..3982d97 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -1,7 +1,6 @@
 /* X11Application.m -- subclass of NSApplication to multiplex events
- $Id: X11Application.m,v 1.59 2006/09/06 21:19:32 jharper Exp $
  
- Copyright (c) 2002-2007 Apple Inc. All rights reserved.
+ Copyright (c) 2002-2007 Apple Inc.
  
  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
@@ -35,12 +34,10 @@
 
 /* ouch! */
 #define BOOL X_BOOL
-//# include "Xproto.h"
 # include "darwin.h"
 # include "../quartz/quartz.h"
 # define _APPLEWM_SERVER_
 # include "X11/extensions/applewm.h"
-//# include "X.h"
 # include "micmap.h"
 #undef BOOL
 
@@ -55,15 +52,15 @@
 int X11EnableKeyEquivalents = TRUE;
 int quartzHasRoot = FALSE, quartzEnableRootless = TRUE;
 
-extern int darwinFakeButtons;
+extern int darwinFakeButtons, input_check_flag;
 // extern Bool enable_stereo; 
 Bool enable_stereo;  //<-- this needs to go back to being an extern once glxCGL is fixed
 
+static xEvent *quartzEvents;
 
 X11Application *X11App;
 
-#define ALL_KEY_MASKS (NSShiftKeyMask | NSControlKeyMask \
-| NSAlternateKeyMask | NSCommandKeyMask)
+#define ALL_KEY_MASKS (NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask)
 
 @implementation X11Application
 
@@ -82,27 +79,21 @@ static void send_nsevent (NSEventType ty
  but is statically linked into this X server. */
 extern Bool QuartzModeBundleInit(void);
 
-static void
-init_ports (void)
-{
+static void init_ports (void) {
     kern_return_t r;
     NSPort *p;
 	
-    if (_port != MACH_PORT_NULL)
-		return;
+    if (_port != MACH_PORT_NULL) return;
 	
     r = mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE, &_port);
-    if (r != KERN_SUCCESS)
-		return;
+    if (r != KERN_SUCCESS) return;
 	
     p = [NSMachPort portWithMachPort:_port];
     [p setDelegate:NSApp];
     [p scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
 }
 
-static void
-message_kit_thread (SEL selector, NSObject *arg)
-{
+static void message_kit_thread (SEL selector, NSObject *arg) {
     message msg;
     kern_return_t r;
 	
@@ -117,29 +108,24 @@ message_kit_thread (SEL selector, NSObje
     msg.arg = [arg retain];
 	
     r = mach_msg (&msg.hdr, MACH_SEND_MSG, msg.hdr.msgh_size,
-				  0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
+		  0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
     if (r != KERN_SUCCESS)
-		fprintf (stderr, "%s: mach_msg failed: %x\n", __FUNCTION__, r);
+		ErrorF("%s: mach_msg failed: %x\n", __FUNCTION__, r);
 }
 
-- (void) handleMachMessage:(void *)_msg
-{
+- (void) handleMachMessage:(void *)_msg {
     message *msg = _msg;
 	
     [self performSelector:msg->selector withObject:msg->arg];
     [msg->arg release];
 }
 
-- (void) set_controller:obj
-{
-    if (_controller == nil)
-		_controller = [obj retain];
+- (void) set_controller:obj {
+    if (_controller == nil) _controller = [obj retain];
 }
 
-- (void) dealloc
-{
-    if (_controller != nil)
-		[_controller release];
+- (void) dealloc {
+    if (_controller != nil) [_controller release];
 	
     if (_port != MACH_PORT_NULL)
 		mach_port_deallocate (mach_task_self (), _port);
@@ -147,8 +133,7 @@ message_kit_thread (SEL selector, NSObje
     [super dealloc];
 }
 
-- (void) orderFrontStandardAboutPanel: (id) sender
-{
+- (void) orderFrontStandardAboutPanel: (id) sender {
     NSMutableDictionary *dict;
     NSDictionary *infoDict;
     NSString *tem;
@@ -161,57 +146,45 @@ message_kit_thread (SEL selector, NSObje
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.1",
-					 tem] forKey:@"ApplicationVersion"];
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.3", tem] 
+	  forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
 }
 
-- (void) activateX:(BOOL)state
-{
+- (void) activateX:(BOOL)state {
     /* Create a TSM document that supports full Unicode input, and
 	 have it activated while X is active (unless using the old
 	 keymapping files) */
     static TSMDocumentID x11_document;
 	
-    if (state)
-    {
-		QuartzMessageServerThread (kXDarwinActivate, 0);
-		
-		if (!_x_active)
-		{
-			if (x11_document == 0 && darwinKeymapFile == NULL)
-			{
-				OSType types[1];
-				types[0] = kUnicodeDocument;
-				NewTSMDocument (1, types, &x11_document, 0);
-			}
-			
-			if (x11_document != 0)
-				ActivateTSMDocument (x11_document);
-		}
-    }
-    else
-    {
-		QuartzMessageServerThread (kXDarwinDeactivate, 0);
-		
-		if (_x_active)
-		{
-			if (x11_document != 0)
-				DeactivateTSMDocument (x11_document);
-		}
-    }
+    if (state) {
+      QuartzMessageServerThread (kXDarwinActivate, 0);
+      
+      if (!_x_active) {
+	if (x11_document == 0 && darwinKeymapFile == NULL) {
+	  OSType types[1];
+	  types[0] = kUnicodeDocument;
+	  NewTSMDocument (1, types, &x11_document, 0);
+	}
 	
+	if (x11_document != 0)	ActivateTSMDocument (x11_document);
+      }
+    } else {
+      QuartzMessageServerThread (kXDarwinDeactivate, 0);
+      
+      if (_x_active && x11_document != 0)
+	DeactivateTSMDocument (x11_document);
+    }
+    
     _x_active = state;
 }
 
-- (void) became_key:(NSWindow *)win
-{
+- (void) became_key:(NSWindow *)win {
     [self activateX:NO];
 }
 
-- (void) sendEvent:(NSEvent *)e
-{
+- (void) sendEvent:(NSEvent *)e {
     NSEventType type;
     BOOL for_appkit, for_x;
 	
@@ -221,178 +194,140 @@ message_kit_thread (SEL selector, NSObje
     for_appkit = YES;
     for_x = YES;
 	
-    switch (type)
-    {
+    switch (type) {
     case NSLeftMouseDown: case NSRightMouseDown: case NSOtherMouseDown:
     case NSLeftMouseUp: case NSRightMouseUp: case NSOtherMouseUp:
-		if ([e window] != nil)
-		{
-			/* Pointer event has a window. Probably something for the kit. */
-			
-			for_x = NO;
-			
-			if (_x_active)
-				[self activateX:NO];
-		}
-		else if ([self modalWindow] == nil)
-		{
-			/* Must be an X window. Tell appkit it doesn't have focus. */
-			
-			for_appkit = NO;
-			
-			if ([self isActive])
-			{
-				[self deactivate];
-				
-				if (!_x_active && quartzProcs->IsX11Window([e window],
-														   [e windowNumber]))
-				[self activateX:YES];
-			}
-		}
-		break;
-		
+      if ([e window] != nil) {
+	/* Pointer event has a window. Probably something for the kit. */
+	
+	for_x = NO;
+	
+	if (_x_active) [self activateX:NO];
+      } else if ([self modalWindow] == nil) {
+	/* Must be an X window. Tell appkit it doesn't have focus. */
+			
+	for_appkit = NO;
+	
+	if ([self isActive]) {
+	  [self deactivate];
+	  
+	  if (!_x_active && quartzProcs->IsX11Window([e window], [e windowNumber]))
+	    [self activateX:YES];
+	}
+      }
+      break;
+      
     case NSKeyDown: case NSKeyUp:
-		if (_x_active)
-		{
-			static int swallow_up;
-			
-			/* No kit window is focused, so send it to X. */
-			
-			for_appkit = NO;
-			
-			if (type == NSKeyDown)
-			{
-				/* Before that though, see if there are any global
-				 shortcuts bound to it. */
-				
-				if (X11EnableKeyEquivalents
-					&& [[self mainMenu] performKeyEquivalent:e])
-				{
-					swallow_up = [e keyCode];
-					for_x = NO;
-				}
-				else if (!quartzEnableRootless
-						 && ([e modifierFlags] & ALL_KEY_MASKS)
-						 == (NSCommandKeyMask | NSAlternateKeyMask)
-						 && ([e keyCode] == 0 /*a*/
-							 || [e keyCode] == 53 /*Esc*/))
-				{
-					swallow_up = 0;
-					for_x = NO;
+      if (_x_active) {
+	static int swallow_up;
+	
+	/* No kit window is focused, so send it to X. */
+	
+	for_appkit = NO;
+	
+	if (type == NSKeyDown) {
+	  /* Before that though, see if there are any global
+	     shortcuts bound to it. */
+	  
+	  if (X11EnableKeyEquivalents
+	      && [[self mainMenu] performKeyEquivalent:e]) {
+	    swallow_up = [e keyCode];
+	    for_x = NO;
+	  } else if (!quartzEnableRootless
+		   && ([e modifierFlags] & ALL_KEY_MASKS)
+		   == (NSCommandKeyMask | NSAlternateKeyMask)
+		   && ([e keyCode] == 0 /*a*/
+		       || [e keyCode] == 53 /*Esc*/)) {
+	    swallow_up = 0;
+	    for_x = NO;
 #ifdef DARWIN_DDX_MISSING
-					QuartzMessageServerThread (kXDarwinToggleFullscreen, 0);
+	    QuartzMessageServerThread (kXDarwinToggleFullscreen, 0);
 #endif
-				}
-			}
-			else
-			{
-				/* If we saw a key equivalent on the down, don't pass
-				 the up through to X. */
-				
-				if (swallow_up != 0 && [e keyCode] == swallow_up)
-				{
-					swallow_up = 0;
-					for_x = NO;
-				}
-			}
-		}
-		else
-		{
-			for_x = NO;
-		}
-		break;
+	  }
+	} else {
+	  /* If we saw a key equivalent on the down, don't pass
+	     the up through to X. */
+	  
+	  if (swallow_up != 0 && [e keyCode] == swallow_up) {
+	    swallow_up = 0;
+	    for_x = NO;
+	  }
+	}
+      }
+      else for_x = NO;
+      break;
 		
     case NSFlagsChanged:
-		/* For the l33t X users who remap modifier keys to normal keysyms. */
-		if (!_x_active)
-			for_x = NO;
-		break;
+      /* For the l33t X users who remap modifier keys to normal keysyms. */
+      if (!_x_active)
+	for_x = NO;
+      break;
 		
     case NSAppKitDefined:
-		switch ([e subtype])
-		{
-		case NSApplicationActivatedEventType:
-			for_x = NO;
-			if ([self modalWindow] == nil)
-			{
-				for_appkit = NO;
-				
-				/* FIXME: hack to avoid having to pass the event to appkit,
-				 which would cause it to raise one of its windows. */
-				_appFlags._active = YES;
-				
-				[self activateX:YES];
+      switch ([e subtype]) {
+      case NSApplicationActivatedEventType:
+	for_x = NO;
+	if ([self modalWindow] == nil) {
+	  for_appkit = NO;
+	  
+	  /* FIXME: hack to avoid having to pass the event to appkit,
+	     which would cause it to raise one of its windows. */
+	  _appFlags._active = YES;
+	  
+	  [self activateX:YES];
 #ifdef DARWIN_DDX_MISSING
-				if ([e data2] & 0x10) QuartzMessageServerThread (kXDarwinBringAllToFront, 0);
+	  if ([e data2] & 0x10) QuartzMessageServerThread (kXDarwinBringAllToFront, 0);
 #endif
-			}
-			break;
-			
-		case 18: /* ApplicationDidReactivate */
-			if (quartzHasRoot)
-				for_appkit = NO;
-			break;
+	}
+	break;
 			
-		case NSApplicationDeactivatedEventType:
-			for_x = NO;
-			[self activateX:NO];
-			break;
-		}
-		break;
-		
+      case 18: /* ApplicationDidReactivate */
+	if (quartzHasRoot) for_appkit = NO;
+	break;
+			
+      case NSApplicationDeactivatedEventType:
+	for_x = NO;
+	[self activateX:NO];
+	break;
+      }
+      break;
+      
     default: break; /* for gcc */
     }
 	
-    if (for_appkit)
-    {
-		[super sendEvent:e];
-    }
-	
-    if (for_x)
-    {
-		send_nsevent (type, e);
-    }
+    if (for_appkit) [super sendEvent:e];
+    if (for_x) send_nsevent (type, e);
 }
 
-- (void) set_window_menu:(NSArray *)list
-{
+- (void) set_window_menu:(NSArray *)list {
     [_controller set_window_menu:list];
 }
 
-- (void) set_window_menu_check:(NSNumber *)n
-{
+- (void) set_window_menu_check:(NSNumber *)n {
     [_controller set_window_menu_check:n];
 }
 
-- (void) set_apps_menu:(NSArray *)list
-{
+- (void) set_apps_menu:(NSArray *)list {
     [_controller set_apps_menu:list];
 }
 
-- (void) set_front_process:unused
-{
+- (void) set_front_process:unused {
     [NSApp activateIgnoringOtherApps:YES];
 	
-    if ([self modalWindow] == nil)
-		[self activateX:YES];
+    if ([self modalWindow] == nil) [self activateX:YES];
 }
 
-- (void) set_can_quit:(NSNumber *)state
-{
+- (void) set_can_quit:(NSNumber *)state {
     [_controller set_can_quit:[state boolValue]];
 }
 
-- (void) server_ready:unused
-{
+- (void) server_ready:unused {
     [_controller server_ready];
 }
 
-- (void) show_hide_menubar:(NSNumber *)state
-{
-    if ([state boolValue])
-		ShowMenuBar ();
-    else
-		HideMenuBar ();
+- (void) show_hide_menubar:(NSNumber *)state {
+    if ([state boolValue]) ShowMenuBar ();
+    else HideMenuBar ();
 }
 
 
@@ -404,12 +339,12 @@ message_kit_thread (SEL selector, NSObje
 static const void *cfretain (CFAllocatorRef a, const void *b) {
     return CFRetain (b);
 }
+
 static void cfrelease (CFAllocatorRef a, const void *b) {
     CFRelease (b);
 }
-static CFMutableArrayRef
-nsarray_to_cfarray (NSArray *in)
-{
+
+static CFMutableArrayRef nsarray_to_cfarray (NSArray *in) {
     CFMutableArrayRef out;
     CFArrayCallBacks cb;
     NSObject *ns;
@@ -424,24 +359,22 @@ nsarray_to_cfarray (NSArray *in)
     count = [in count];
     out = CFArrayCreateMutable (NULL, count, &cb);
 	
-    for (i = 0; i < count; i++)
-    {
-		ns = [in objectAtIndex:i];
-		
-		if ([ns isKindOfClass:[NSArray class]])
-			cf = (CFTypeRef) nsarray_to_cfarray ((NSArray *) ns);
-		else
-			cf = CFRetain ((CFTypeRef) ns);
-		
-		CFArrayAppendValue (out, cf);
-		CFRelease (cf);
+    for (i = 0; i < count; i++) {
+      ns = [in objectAtIndex:i];
+      
+      if ([ns isKindOfClass:[NSArray class]])
+	cf = (CFTypeRef) nsarray_to_cfarray ((NSArray *) ns);
+      else
+	cf = CFRetain ((CFTypeRef) ns);
+      
+      CFArrayAppendValue (out, cf);
+      CFRelease (cf);
     }
-	
+    
     return out;
 }
-static NSMutableArray *
-cfarray_to_nsarray (CFArrayRef in)
-{
+
+static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
     NSMutableArray *out;
     const CFTypeRef *cf;
     NSObject *ns;
@@ -450,320 +383,277 @@ cfarray_to_nsarray (CFArrayRef in)
     count = CFArrayGetCount (in);
     out = [[NSMutableArray alloc] initWithCapacity:count];
 	
-    for (i = 0; i < count; i++)
-    {
-		cf = CFArrayGetValueAtIndex (in, i);
-		
-		if (CFGetTypeID (cf) == CFArrayGetTypeID ())
-			ns = cfarray_to_nsarray ((CFArrayRef) cf);
-		else
-			ns = [(id)cf retain];
+    for (i = 0; i < count; i++) {
+      cf = CFArrayGetValueAtIndex (in, i);
 		
-		[out addObject:ns];
-		[ns release];
+      if (CFGetTypeID (cf) == CFArrayGetTypeID ())
+	ns = cfarray_to_nsarray ((CFArrayRef) cf);
+      else
+	ns = [(id)cf retain];
+      
+      [out addObject:ns];
+      [ns release];
     }
-	
+    
     return out;
 }
 
-- (CFPropertyListRef) prefs_get:(NSString *)key
-{
+- (CFPropertyListRef) prefs_get:(NSString *)key {
     CFPropertyListRef value;
 	
     value = CFPreferencesCopyAppValue ((CFStringRef) key, CFSTR (APP_PREFS));
 	
-    if (value == NULL)
-    {
-		static CFDictionaryRef defaults;
-		
-		if (defaults == NULL)
-		{
-			CFStringRef error = NULL;
-			CFDataRef data;
-			CFURLRef url;
-			SInt32 error_code;
-			
-			url = (CFURLCreateFromFileSystemRepresentation
-				   (NULL, (unsigned char *)DEFAULTS_FILE, strlen (DEFAULTS_FILE), false));
-			if (CFURLCreateDataAndPropertiesFromResource (NULL, url, &data,
-														  NULL, NULL,
-														  &error_code))
-			{
-				defaults = (CFPropertyListCreateFromXMLData
-							(NULL, data, kCFPropertyListMutableContainersAndLeaves, &error));
-				if (error != NULL)
-					CFRelease (error);
-				CFRelease (data);
-			}
-			CFRelease (url);
+    if (value == NULL) {
+      static CFDictionaryRef defaults;
+      
+      if (defaults == NULL) {
+	CFStringRef error = NULL;
+	CFDataRef data;
+	CFURLRef url;
+	SInt32 error_code;
+	
+	url = (CFURLCreateFromFileSystemRepresentation
+	       (NULL, (unsigned char *)DEFAULTS_FILE, strlen (DEFAULTS_FILE), false));
+	if (CFURLCreateDataAndPropertiesFromResource (NULL, url, &data,
+						      NULL, NULL, &error_code)) {
+	  defaults = (CFPropertyListCreateFromXMLData
+		      (NULL, data, kCFPropertyListMutableContainersAndLeaves, &error));
+	  if (error != NULL) CFRelease (error);
+	  CFRelease (data);
+	}
+	CFRelease (url);
 			
-			if (defaults != NULL)
-			{
-				NSMutableArray *apps, *elt;
-				int count, i;
-				NSString *name, *nname;
-				
-				/* Localize the names in the default apps menu. */
-				
-				apps = [(NSDictionary *)defaults objectForKey:@PREFS_APPSMENU];
-				if (apps != nil)
-				{
-					count = [apps count];
-					for (i = 0; i < count; i++)
-					{
-						elt = [apps objectAtIndex:i];
-						if (elt != nil && [elt isKindOfClass:[NSArray class]])
-						{
-							name = [elt objectAtIndex:0];
-							if (name != nil)
-							{
-								nname = NSLocalizedString (name, nil);
-								if (nname != nil && nname != name)
-									[elt replaceObjectAtIndex:0 withObject:nname];
-							}
-						}
-					}
-				}
-			}
-		}
-		
-		if (defaults != NULL)
-			value = CFDictionaryGetValue (defaults, key);
+	if (defaults != NULL) {
+	  NSMutableArray *apps, *elt;
+	  int count, i;
+	  NSString *name, *nname;
+	  
+	  /* Localize the names in the default apps menu. */
+	  
+	  apps = [(NSDictionary *)defaults objectForKey:@PREFS_APPSMENU];
+	  if (apps != nil) {
+	    count = [apps count];
+	    for (i = 0; i < count; i++)	{
+	      elt = [apps objectAtIndex:i];
+	      if (elt != nil && [elt isKindOfClass:[NSArray class]]) {
+		name = [elt objectAtIndex:0];
+		if (name != nil) {
+		  nname = NSLocalizedString (name, nil);
+		  if (nname != nil && nname != name)
+		    [elt replaceObjectAtIndex:0 withObject:nname];
+		}
+	      }
+	    }
+	  }
+	}
+      }
 		
-		if (value != NULL)
-			CFRetain (value);
+      if (defaults != NULL) value = CFDictionaryGetValue (defaults, key);
+      if (value != NULL) CFRetain (value);
     }
 	
     return value;
 }
 
-- (int) prefs_get_integer:(NSString *)key default:(int)def
-{
-    CFPropertyListRef value;
-    int ret;
-	
-    value = [self prefs_get:key];
-	
-    if (value != NULL && CFGetTypeID (value) == CFNumberGetTypeID ())
-		CFNumberGetValue (value, kCFNumberIntType, &ret);
-    else if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
-		ret = CFStringGetIntValue (value);
-    else
-		ret = def;
-	
-    if (value != NULL)
-		CFRelease (value);
-	
-    return ret;
-}
-
-- (const char *) prefs_get_string:(NSString *)key default:(const char *)def
-{
-    CFPropertyListRef value;
-    const char *ret = NULL;
-	
-    value = [self prefs_get:key];
-	
-    if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
-    {
-		NSString *s = (NSString *) value;
-		
-		ret = [s UTF8String];
-    }
-	
-    if (value != NULL)
-		CFRelease (value);
-	
-    return ret != NULL ? ret : def;
-}
-
-- (float) prefs_get_float:(NSString *)key default:(float)def
-{
-    CFPropertyListRef value;
-    float ret = def;
-	
-    value = [self prefs_get:key];
-	
-    if (value != NULL
-		&& CFGetTypeID (value) == CFNumberGetTypeID ()
-		&& CFNumberIsFloatType (value))
-    {
-		CFNumberGetValue (value, kCFNumberFloatType, &ret);
-    }
-    else if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
-    {
-		ret = CFStringGetDoubleValue (value);
-    }
-	
-    if (value != NULL)
-		CFRelease (value);
-	
-    return ret;
-}
-
-- (int) prefs_get_boolean:(NSString *)key default:(int)def
-{
-    CFPropertyListRef value;
-    int ret = def;
-	
-    value = [self prefs_get:key];
-	
-    if (value != NULL)
-    {
-		if (CFGetTypeID (value) == CFNumberGetTypeID ())
-			CFNumberGetValue (value, kCFNumberIntType, &ret);
-		else if (CFGetTypeID (value) == CFBooleanGetTypeID ())
-			ret = CFBooleanGetValue (value);
-		else if (CFGetTypeID (value) == CFStringGetTypeID ())
-		{
-			const char *tem = [(NSString *) value lossyCString];
-			if (strcasecmp (tem, "true") == 0 || strcasecmp (tem, "yes") == 0)
-				ret = YES;
-			else
-				ret = NO;
-		}
-		
-		CFRelease (value);
+- (int) prefs_get_integer:(NSString *)key default:(int)def {
+  CFPropertyListRef value;
+  int ret;
+  
+  value = [self prefs_get:key];
+  
+  if (value != NULL && CFGetTypeID (value) == CFNumberGetTypeID ())
+    CFNumberGetValue (value, kCFNumberIntType, &ret);
+  else if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
+    ret = CFStringGetIntValue (value);
+  else
+    ret = def;
+  
+  if (value != NULL) CFRelease (value);
+  
+  return ret;
+}
+
+- (const char *) prefs_get_string:(NSString *)key default:(const char *)def {
+  CFPropertyListRef value;
+  const char *ret = NULL;
+  
+  value = [self prefs_get:key];
+  
+  if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ()) {
+    NSString *s = (NSString *) value;
+    
+    ret = [s UTF8String];
+  }
+  
+  if (value != NULL) CFRelease (value);
+  
+  return ret != NULL ? ret : def;
+}
+
+- (float) prefs_get_float:(NSString *)key default:(float)def {
+  CFPropertyListRef value;
+  float ret = def;
+  
+  value = [self prefs_get:key];
+  
+  if (value != NULL
+      && CFGetTypeID (value) == CFNumberGetTypeID ()
+      && CFNumberIsFloatType (value)) 
+    CFNumberGetValue (value, kCFNumberFloatType, &ret);
+  else if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
+    ret = CFStringGetDoubleValue (value);
+	
+  if (value != NULL) CFRelease (value);
+  
+  return ret;
+}
+
+- (int) prefs_get_boolean:(NSString *)key default:(int)def {
+  CFPropertyListRef value;
+  int ret = def;
+  
+  value = [self prefs_get:key];
+  
+  if (value != NULL) {
+    if (CFGetTypeID (value) == CFNumberGetTypeID ())
+      CFNumberGetValue (value, kCFNumberIntType, &ret);
+    else if (CFGetTypeID (value) == CFBooleanGetTypeID ())
+      ret = CFBooleanGetValue (value);
+    else if (CFGetTypeID (value) == CFStringGetTypeID ()) {
+      const char *tem = [(NSString *) value lossyCString];
+      if (strcasecmp (tem, "true") == 0 || strcasecmp (tem, "yes") == 0)
+	ret = YES;
+      else
+	ret = NO;
     }
-	
-    return ret;
+    
+    CFRelease (value);
+  }
+  return ret;
 }
 
-- (NSArray *) prefs_get_array:(NSString *)key
-{
-    NSArray *ret = nil;
-    CFPropertyListRef value;
-	
-    value = [self prefs_get:key];
-	
-    if (value != NULL)
-    {
-		if (CFGetTypeID (value) == CFArrayGetTypeID ())
-			ret = [cfarray_to_nsarray (value) autorelease];
-		
-		CFRelease (value);
-    }
-	
-    return ret;
+- (NSArray *) prefs_get_array:(NSString *)key {
+  NSArray *ret = nil;
+  CFPropertyListRef value;
+  
+  value = [self prefs_get:key];
+  
+  if (value != NULL) {
+    if (CFGetTypeID (value) == CFArrayGetTypeID ())
+      ret = [cfarray_to_nsarray (value) autorelease];
+    
+    CFRelease (value);
+  }
+  
+  return ret;
 }
 
-- (void) prefs_set_integer:(NSString *)key value:(int)value
-{
+- (void) prefs_set_integer:(NSString *)key value:(int)value {
     CFNumberRef x;
 	
     x = CFNumberCreate (NULL, kCFNumberIntType, &value);
 	
     CFPreferencesSetValue ((CFStringRef) key, (CFTypeRef) x, CFSTR (APP_PREFS),
-						   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+			   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
 	
     CFRelease (x);
 }
 
-- (void) prefs_set_float:(NSString *)key value:(float)value
-{
+- (void) prefs_set_float:(NSString *)key value:(float)value {
     CFNumberRef x;
 	
     x = CFNumberCreate (NULL, kCFNumberFloatType, &value);
 	
     CFPreferencesSetValue ((CFStringRef) key, (CFTypeRef) x, CFSTR (APP_PREFS),
-						   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+			   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
 	
     CFRelease (x);
 }
 
-- (void) prefs_set_boolean:(NSString *)key value:(int)value
-{
-    CFPreferencesSetValue ((CFStringRef) key,
-						   (CFTypeRef) value ? kCFBooleanTrue
-						   : kCFBooleanFalse, CFSTR (APP_PREFS),
-						   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
-	
-}
-
-- (void) prefs_set_array:(NSString *)key value:(NSArray *)value
-{
-    CFArrayRef cfarray;
-	
-    cfarray = nsarray_to_cfarray (value);
-    CFPreferencesSetValue ((CFStringRef) key,
-						   (CFTypeRef) cfarray,
-						   CFSTR (APP_PREFS),
-						   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
-    CFRelease (cfarray);
-}
-
-- (void) prefs_set_string:(NSString *)key value:(NSString *)value
-{
-    CFPreferencesSetValue ((CFStringRef) key, (CFTypeRef) value,
-						   CFSTR (APP_PREFS), kCFPreferencesCurrentUser,
-						   kCFPreferencesAnyHost);
+- (void) prefs_set_boolean:(NSString *)key value:(int)value {
+  CFPreferencesSetValue ((CFStringRef) key,
+			 (CFTypeRef) value ? kCFBooleanTrue
+			 : kCFBooleanFalse, CFSTR (APP_PREFS),
+			 kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+  
+}
+
+- (void) prefs_set_array:(NSString *)key value:(NSArray *)value {
+  CFArrayRef cfarray;
+  
+  cfarray = nsarray_to_cfarray (value);
+  CFPreferencesSetValue ((CFStringRef) key,
+			 (CFTypeRef) cfarray,
+			 CFSTR (APP_PREFS),
+			 kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+  CFRelease (cfarray);
+}
+
+- (void) prefs_set_string:(NSString *)key value:(NSString *)value {
+  CFPreferencesSetValue ((CFStringRef) key, (CFTypeRef) value,
+			 CFSTR (APP_PREFS), kCFPreferencesCurrentUser,
+			 kCFPreferencesAnyHost);
 }
 
-- (void) prefs_synchronize
-{
+- (void) prefs_synchronize {
     CFPreferencesAppSynchronize (kCFPreferencesCurrentApplication);
 }
 
-- (void) read_defaults
-{
-    const char *tem;
-	
-    quartzUseSysBeep = [self prefs_get_boolean:@PREFS_SYSBEEP
-									   default:quartzUseSysBeep];
-    quartzEnableRootless = [self prefs_get_boolean:@PREFS_ROOTLESS
-										   default:quartzEnableRootless];
+- (void) read_defaults {
+  const char *tem;
+  
+  quartzUseSysBeep = [self prefs_get_boolean:@PREFS_SYSBEEP
+			   default:quartzUseSysBeep];
+  quartzEnableRootless = [self prefs_get_boolean:@PREFS_ROOTLESS
+			       default:quartzEnableRootless];
 #ifdef DARWIN_DDX_MISSING
-    quartzFullscreenDisableHotkeys = ![self prefs_get_boolean:
-									   @PREFS_FULLSCREEN_HOTKEYS default:
-									   !quartzFullscreenDisableHotkeys];
-    quartzXpluginOptions = [self prefs_get_integer:@PREFS_XP_OPTIONS
-										   default:quartzXpluginOptions];
+  quartzFullscreenDisableHotkeys = ![self prefs_get_boolean:
+					    @PREFS_FULLSCREEN_HOTKEYS default:
+					    !quartzFullscreenDisableHotkeys];
+  quartzXpluginOptions = [self prefs_get_integer:@PREFS_XP_OPTIONS
+			       default:quartzXpluginOptions];
 #endif
-	
-    darwinSwapAltMeta = [self prefs_get_boolean:@PREFS_SWAP_ALT_META
-										default:darwinSwapAltMeta];
-    darwinFakeButtons = [self prefs_get_boolean:@PREFS_FAKEBUTTONS
-										default:darwinFakeButtons];
-    if (darwinFakeButtons)
-    {
-        const char *fake2, *fake3;
-		
-        fake2 = [self prefs_get_string:@PREFS_FAKE_BUTTON2 default:NULL];
-        fake3 = [self prefs_get_string:@PREFS_FAKE_BUTTON3 default:NULL];
-		
-		if (fake2 != NULL) darwinFakeMouse2Mask = DarwinParseModifierList(fake2);
-		if (fake3 != NULL) darwinFakeMouse3Mask = DarwinParseModifierList(fake3);
+  
+  darwinSwapAltMeta = [self prefs_get_boolean:@PREFS_SWAP_ALT_META
+			    default:darwinSwapAltMeta];
+  darwinFakeButtons = [self prefs_get_boolean:@PREFS_FAKEBUTTONS
+			    default:darwinFakeButtons];
+  if (darwinFakeButtons) {
+    const char *fake2, *fake3;
+    
+    fake2 = [self prefs_get_string:@PREFS_FAKE_BUTTON2 default:NULL];
+    fake3 = [self prefs_get_string:@PREFS_FAKE_BUTTON3 default:NULL];
+													      
+     if (fake2 != NULL) darwinFakeMouse2Mask = DarwinParseModifierList(fake2);
+     if (fake3 != NULL) darwinFakeMouse3Mask = DarwinParseModifierList(fake3);
 		
-    }
+  }
 	
-    X11EnableKeyEquivalents = [self prefs_get_boolean:@PREFS_KEYEQUIVS
-											  default:X11EnableKeyEquivalents];
+  X11EnableKeyEquivalents = [self prefs_get_boolean:@PREFS_KEYEQUIVS
+				  default:X11EnableKeyEquivalents];
 	
-    darwinSyncKeymap = [self prefs_get_boolean:@PREFS_SYNC_KEYMAP
-									   default:darwinSyncKeymap];
+  darwinSyncKeymap = [self prefs_get_boolean:@PREFS_SYNC_KEYMAP
+			   default:darwinSyncKeymap];
 	
-    tem = [self prefs_get_string:@PREFS_KEYMAP_FILE default:NULL];
-    if (tem != NULL)
-		darwinKeymapFile = strdup (tem);
-    else
-        darwinKeymapFile = NULL;
+  tem = [self prefs_get_string:@PREFS_KEYMAP_FILE default:NULL];
+
+  if (tem != NULL) darwinKeymapFile = strdup (tem);
+  else darwinKeymapFile = NULL;
 	
-    darwinDesiredDepth = [self prefs_get_integer:@PREFS_DEPTH
-										 default:darwinDesiredDepth];
+  darwinDesiredDepth = [self prefs_get_integer:@PREFS_DEPTH
+			     default:darwinDesiredDepth];
 	
-    enable_stereo = [self prefs_get_boolean:@PREFS_ENABLE_STEREO
-									default:false];
+  enable_stereo = [self prefs_get_boolean:@PREFS_ENABLE_STEREO
+			default:false];
 }
 
 /* This will end up at the end of the responder chain. */
-- (void) copy:sender
-{
-    QuartzMessageServerThread (kXDarwinPasteboardNotify, 1,
-							   AppleWMCopyToPasteboard);
+- (void) copy:sender {
+  QuartzMessageServerThread (kXDarwinPasteboardNotify, 1,
+			     AppleWMCopyToPasteboard);
 }
 
-- (BOOL) x_active
-{
+- (BOOL) x_active {
     return _x_active;
 }
 
@@ -771,75 +661,62 @@ cfarray_to_nsarray (CFArrayRef in)
 
 static NSArray *
 array_with_strings_and_numbers (int nitems, const char **items,
-								const char *numbers)
-{
-    NSMutableArray *array, *subarray;
-    NSString *string;
-    NSString *number;
-    int i;
-	
-    /* (Can't autorelease on the X server thread) */
-	
-    array = [[NSMutableArray alloc] initWithCapacity:nitems];
-	
-    for (i = 0; i < nitems; i++)
-    {
-		subarray = [[NSMutableArray alloc] initWithCapacity:2];
-		
-		string = [[NSString alloc] initWithUTF8String:items[i]];
-		[subarray addObject:string];
-		[string release];
-		
-		if (numbers[i] != 0)
-		{
-			number = [[NSString alloc] initWithFormat:@"%d", numbers[i]];
-			[subarray addObject:number];
-			[number release];
-		}
-		else
-			[subarray addObject:@""];
-		
-		[array addObject:subarray];
-		[subarray release];
-    }
-	
-    return array;
-}
-
-void
-X11ApplicationSetWindowMenu (int nitems, const char **items,
-							 const char *shortcuts)
-{
-    NSArray *array;
-    array = array_with_strings_and_numbers (nitems, items, shortcuts);
-	
-    /* Send the array of strings over to the appkit thread */
-	
-    message_kit_thread (@selector (set_window_menu:), array);
-    [array release];
-}
-
-void
-X11ApplicationSetWindowMenuCheck (int idx)
-{
-    NSNumber *n;
-	
-    n = [[NSNumber alloc] initWithInt:idx];
-	
-    message_kit_thread (@selector (set_window_menu_check:), n);
-	
-    [n release];
+				const char *numbers) {
+  NSMutableArray *array, *subarray;
+  NSString *string, *number;
+  int i;
+	
+  /* (Can't autorelease on the X server thread) */
+  
+  array = [[NSMutableArray alloc] initWithCapacity:nitems];
+  
+  for (i = 0; i < nitems; i++) {
+    subarray = [[NSMutableArray alloc] initWithCapacity:2];
+    
+    string = [[NSString alloc] initWithUTF8String:items[i]];
+    [subarray addObject:string];
+    [string release];
+    
+    if (numbers[i] != 0) {
+      number = [[NSString alloc] initWithFormat:@"%d", numbers[i]];
+      [subarray addObject:number];
+      [number release];
+    } else
+      [subarray addObject:@""];
+    
+    [array addObject:subarray];
+    [subarray release];
+  }
+  
+  return array;
+}
+
+void X11ApplicationSetWindowMenu (int nitems, const char **items,
+				  const char *shortcuts) {
+  NSArray *array;
+  array = array_with_strings_and_numbers (nitems, items, shortcuts);
+  
+  /* Send the array of strings over to the appkit thread */
+  
+  message_kit_thread (@selector (set_window_menu:), array);
+  [array release];
+}
+
+void X11ApplicationSetWindowMenuCheck (int idx) {
+  NSNumber *n;
+  
+  n = [[NSNumber alloc] initWithInt:idx];
+  
+  message_kit_thread (@selector (set_window_menu_check:), n);
+  
+  [n release];
 }
 
-void
-X11ApplicationSetFrontProcess (void)
-{
+void X11ApplicationSetFrontProcess (void) {
     message_kit_thread (@selector (set_front_process:), nil);
 }
 
-void
-X11ApplicationSetCanQuit (int state)
-{
+void X11ApplicationSetCanQuit (int state) {
     NSNumber *n;
 	
     n = [[NSNumber alloc] initWithBool:state];
@@ -849,15 +726,11 @@ X11ApplicationSetCanQuit (int state)
     [n release];
 }
 
-void
-X11ApplicationServerReady (void)
-{
+void X11ApplicationServerReady (void) {
     message_kit_thread (@selector (server_ready:), nil);
 }
 
-void
-X11ApplicationShowHideMenubar (int state)
-{
+void X11ApplicationShowHideMenubar (int state) {
     NSNumber *n;
 	
     n = [[NSNumber alloc] initWithBool:state];
@@ -867,27 +740,20 @@ X11ApplicationShowHideMenubar (int state
     [n release];
 }
 
-static void *
-create_thread (void *func, void *arg)
-{
+static void * 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 (void *) tid;
 }
 
-static void
-check_xinitrc (void)
-{
+static void check_xinitrc (void) {
     char *tem, buf[1024];
     NSString *msg;
 	
@@ -895,8 +761,7 @@ check_xinitrc (void)
 		return;
 	
     tem = getenv ("HOME");
-    if (tem == NULL)
-		goto done;
+    if (tem == NULL) goto done;
 	
     snprintf (buf, sizeof (buf), "%s/.xinitrc", tem);
     if (access (buf, F_OK) != 0)
@@ -904,48 +769,44 @@ check_xinitrc (void)
 	
     /* FIXME: put localized strings into Resources/English.lproj */
 	
-    msg = NSLocalizedString (
-							 @"You have an existing ~/.xinitrc file.\n\n\
-							 Windows displayed by X11 applications may not have titlebars, or may look \
-							 different to windows displayed by native applications.\n\n\
-							 Would you like to move aside the existing file and use the standard X11 \
-							 environment?", @"Startup xinitrc dialog");
+    msg = NSLocalizedString (@"You have an existing ~/.xinitrc file.\n\n\
+Windows displayed by X11 applications may not have titlebars, or may look \
+different to windows displayed by native applications.\n\n\
+Would you like to move aside the existing file and use the standard X11 \
+environment?", @"Startup xinitrc dialog");
 	
     if (NSRunAlertPanel (nil, msg, NSLocalizedString (@"Yes", @""),
-						 NSLocalizedString (@"No", @""), nil)
-		== NSAlertDefaultReturn)
-    {
-		char buf2[1024];
-		int i = -1;
-		
-		snprintf (buf2, sizeof (buf2), "%s.old", buf);
-		
-		for (i = 1; access (buf2, F_OK) == 0; i++)
-			snprintf (buf2, sizeof (buf2), "%s.old.%d", buf, i);
-		
-		rename (buf, buf2);
+			 NSLocalizedString (@"No", @""), nil)
+	== NSAlertDefaultReturn) {
+      char buf2[1024];
+      int i = -1;
+      
+      snprintf (buf2, sizeof (buf2), "%s.old", buf);
+      
+      for (i = 1; access (buf2, F_OK) == 0; i++)
+	snprintf (buf2, sizeof (buf2), "%s.old.%d", buf, i);
+      
+      rename (buf, buf2);
     }
     
-	done:
+ done:
     [X11App prefs_set_boolean:@PREFS_DONE_XINIT_CHECK value:YES];
     [X11App prefs_synchronize];
 }
 
-void
-X11ApplicationMain (int argc, const char *argv[],
-					void (*server_thread) (void *), void *server_arg)
-{
+void X11ApplicationMain (int argc, const char *argv[],
+			 void (*server_thread) (void *), void *server_arg) {
     NSAutoreleasePool *pool;
 	
 #ifdef DEBUG
-    while (access ("/tmp/x11-block", F_OK) == 0)
-		sleep (1);
+    while (access ("/tmp/x11-block", F_OK) == 0) sleep (1);
 #endif
 	
     pool = [[NSAutoreleasePool alloc] init];
 	
     X11App = (X11Application *) [X11Application sharedApplication];
-	
+    quartzEvents = (xEvent *)malloc(sizeof(xEvent) * GetMaximumEventsNum());
+
     init_ports ();
 	
     [NSApp read_defaults];
@@ -953,8 +814,8 @@ X11ApplicationMain (int argc, const char
     [NSBundle loadNibNamed:@"main" owner:NSApp];
 	
     [[NSNotificationCenter defaultCenter] addObserver:NSApp
-											 selector:@selector (became_key:)
-												 name:NSWindowDidBecomeKeyNotification object:nil];
+					  selector:@selector (became_key:)
+					  name:NSWindowDidBecomeKeyNotification object:nil];
 	
     check_xinitrc ();
 	
@@ -966,173 +827,136 @@ X11ApplicationMain (int argc, const char
 	
     /* Calculate the height of the menubar so we can avoid it. */
     aquaMenuBarHeight = NSHeight([[NSScreen mainScreen] frame]) -
-	NSMaxY([[NSScreen mainScreen] visibleFrame]) - 1;
+      NSMaxY([[NSScreen mainScreen] visibleFrame]) - 1;
 	
-    if (!create_thread (server_thread, server_arg))
-    {
-		fprintf (stderr, "can't create secondary thread\n");
-		exit (1);
+    if (!create_thread (server_thread, server_arg)) {
+      ErrorF("can't create secondary thread\n");
+      exit(1);
     }
 	
     [NSApp run];
-	
-    /* not reached */
 }
 
 
 /* event conversion */
 
 static inline unsigned short
-convert_flags (unsigned int nsflags)
-{
-    unsigned int xflags;
+convert_flags (unsigned int nsflags) {
+    unsigned int xflags = 0;
 	
     if (nsflags == ~0) return 0xffff;
 	
-    xflags = 0;
-	
     if (nsflags & NSAlphaShiftKeyMask)	xflags |= LockMask;
-    if (nsflags & NSShiftKeyMask)		xflags |= ShiftMask;
-    if (nsflags & NSControlKeyMask)		xflags |= ControlMask;
+    if (nsflags & NSShiftKeyMask)	xflags |= ShiftMask;
+    if (nsflags & NSControlKeyMask)	xflags |= ControlMask;
     if (nsflags & NSAlternateKeyMask)	xflags |= Mod1Mask;
-    if (nsflags & NSCommandKeyMask)		xflags |= Mod2Mask;
+    if (nsflags & NSCommandKeyMask)	xflags |= Mod2Mask;
     /* FIXME: secondaryfn? */
 	
     return xflags;
 }
 
-static void
-send_nsevent (NSEventType type, NSEvent *e)
-{
+// This code should probably be merged with that in XDarwin's XServer.m - BB
+static void send_nsevent (NSEventType type, NSEvent *e) {
     static unsigned int button_state = 0;
     NSRect screen;
     NSPoint location;
     NSWindow *window;
-    int pointer_x, pointer_y;
+    int pointer_x, pointer_y, ev_button, ev_type; 
+    int num_events=0, i=0, state;
+    int valuators[2];
+    float count;
     xEvent xe;
+    
+    bzero(&xe, sizeof(xe));
+    input_check_flag++;
 	
-    memset (&xe, 0, sizeof (xe));
-	
-    /* This field should be filled in for every event */
-    xe.u.keyButtonPointer.time = GetTimeInMillis();
-
-	/* convert location to global top-left coordinates */
-	location = [e locationInWindow];
-	window = [e window];
-	screen = [[[NSScreen screens] objectAtIndex:0] frame];
-		
-	if (window != nil)	{
-		NSRect frame = [window frame];
-		pointer_x = location.x + frame.origin.x;
-		pointer_y = (((screen.origin.y + screen.size.height)
-					  - location.y) - frame.origin.y);
-	} else {
-		pointer_x = location.x;
-		pointer_y = (screen.origin.y + screen.size.height) - location.y;
+    /* convert location to global top-left coordinates */
+    location = [e locationInWindow];
+    window = [e window];
+    screen = [[[NSScreen screens] objectAtIndex:0] frame];
+		
+    if (window != nil)	{
+      NSRect frame = [window frame];
+      pointer_x = location.x + frame.origin.x;
+      pointer_y = (((screen.origin.y + screen.size.height)
+		    - location.y) - frame.origin.y);
+    } else {
+      pointer_x = location.x;
+      pointer_y = (screen.origin.y + screen.size.height) - location.y;
+    }
+    
+    ErrorF("send_nsevent: type=%d pointer=(%d,%d)\n", type, pointer_x, pointer_y);
+    
+    valuators[0] = pointer_x;
+    valuators[1] = pointer_y;
+    state = convert_flags ([e modifierFlags]);
+    
+    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 NSMouseMoved: ev_button=0; ev_type=MotionNotify; goto handle_mouse;
+    handle_mouse:
+      
+      if(ev_type==ButtonPress) {
+	if (!quartzProcs->IsX11Window([e window], [e windowNumber])) {
+	  fprintf(stderr, "Dropping event because it's not a window\n");
+	  break;
 	}
-		
-	xe.u.keyButtonPointer.rootX = pointer_x;
-	xe.u.keyButtonPointer.rootY = pointer_y;
-	
-	switch (type) {
-		float count;
-		
-    case NSLeftMouseDown:
-		xe.u.u.type = ButtonPress;
-		xe.u.u.detail = 1;
-		goto do_press_event;
-		
-    case NSRightMouseDown:
-		xe.u.u.type = ButtonPress;
-		xe.u.u.detail = 3;
-		goto do_press_event;
-		
-    case NSOtherMouseDown:
-		xe.u.u.type = ButtonPress;
-		xe.u.u.detail = 2; /* FIXME? */
-		goto do_press_event;
-		
-do_press_event:
-		if (!quartzProcs->IsX11Window([e window], [e windowNumber])) {
-			/* X server doesn't grok this window, drop the event.
-			 
-			 Note: theoretically this isn't necessary, but if I click
-			 on the menubar, we get sent a LeftMouseDown when the
-			 release happens, but no LeftMouseUp is ever seen! */
-			
-			break;
-		}
-		goto do_event;
-		
-    case NSLeftMouseUp:
-		xe.u.u.type = ButtonRelease;
-		xe.u.u.detail = 1;
-		goto do_release_event;
-		
-    case NSRightMouseUp:
-		xe.u.u.type = ButtonRelease;
-		xe.u.u.detail = 3;
-		goto do_release_event;
-		
-    case NSOtherMouseUp:
-		xe.u.u.type = ButtonRelease;
-		xe.u.u.detail = 2; /* FIXME? */
-		goto do_release_event;
-		
-do_release_event:
-		if ((button_state & (1 << xe.u.u.detail)) == 0)
-		{
-			/* X didn't see the button press for this release, so skip it */
-			break;
-		}
-		goto do_event;
-		
-    case NSMouseMoved:
-    case NSLeftMouseDragged:
-    case NSRightMouseDragged:
-    case NSOtherMouseDragged:
-		xe.u.u.type = MotionNotify;
-		goto do_event;
-		
+	button_state |= (1 << ev_button);
+      } else if (ev_type==ButtonRelease && (button_state & (1 << ev_button)) == 0) break;
+      
+      num_events = GetPointerEvents(quartzEvents, darwinPointer, ev_type, ev_button, 
+				    POINTER_ABSOLUTE, 0, 2, valuators);
+      
+      ErrorF("GetPointerEvents returned %d events\n", num_events);
+      for(i=0; i<num_events; i++) {
+	ErrorF("qe[%d].u.u.type=%d\n", i, quartzEvents[i].u.u.type);
+//				quartzEvents[i].u.keyButtonPointer.state = state;
+	mieqEnqueue (darwinPointer,&quartzEvents[i]);
+      }
+      break;
+    case NSScrollWheel: 
+      count = [e deltaY];
+      ev_button = count > 0.0f ? 4 : 5;
+      for (count = fabs(count); count > 0.0; count = count - 1.0f) {
+	num_events = GetPointerEvents(quartzEvents, darwinPointer, ButtonPress, ev_button, 
+				      POINTER_ABSOLUTE, 0, 2, valuators);
+	for(i=0; i<num_events; i++) {
+//						quartzEvents[i].u.keyButtonPointer.state = state;
+	  mieqEnqueue(darwinPointer,&quartzEvents[i]);
+	}
+	num_events = GetPointerEvents(quartzEvents, darwinPointer, ButtonRelease, ev_button, 
+				      POINTER_ABSOLUTE, 0, 2, valuators);
+	for(i=0; i<num_events; i++) {
+//						quartzEvents[i].u.keyButtonPointer.state = state;
+	  mieqEnqueue(darwinPointer,&quartzEvents[i]);
+	}
+      }
+      break;
+      
     case NSKeyDown:
-		xe.u.u.type = KeyPress;
-		xe.u.u.detail = [e keyCode];
-		goto do_event;
-		
     case NSKeyUp:
-		xe.u.u.type = KeyRelease;
-		xe.u.u.detail = [e keyCode];
-		goto do_event;
-		
-    case NSScrollWheel:
-		xe.u.keyButtonPointer.state = convert_flags ([e modifierFlags]);
-		count = [e deltaY];
-		xe.u.u.detail = count > 0.0f ? 4 : 5;
-		for (count = fabs(count); count > 0.0; count = count - 1.0f) {
-			xe.u.u.type = ButtonPress;
-			DarwinEQEnqueue(&xe);
-			xe.u.u.type = ButtonRelease;
-			DarwinEQEnqueue(&xe);
-		}
-		xe.u.u.type = 0;
-		break;
-		
+      num_events = GetKeyboardEvents(quartzEvents, darwinKeyboard, 
+				     (type == NSKeyDown)?KeyPress:KeyRelease, [e keyCode]);
+      for(i=0; i<num_events; i++) {
+//				quartzEvents[i].u.keyButtonPointer.state = state;
+	mieqEnqueue(darwinKeyboard,&quartzEvents[i]);
+      }
+      break;
     case NSFlagsChanged:
-        xe.u.u.type = kXDarwinUpdateModifiers;
-        xe.u.clientMessage.u.l.longs0 = [e modifierFlags];
-        DarwinEQEnqueue (&xe);
-        break;
-		
-do_event:
-		//	xe.u.keyButtonPointer.state = convert_flags ([e modifierFlags]);
-		DarwinEQEnqueue (&xe);
-		break;
-		
+      xe.u.u.type = kXDarwinUpdateModifiers;
+      xe.u.clientMessage.u.l.longs0 = [e modifierFlags];
+      DarwinEQEnqueue (&xe);
+      break;
     default: break; /* for gcc */
-    }
-	
-    if (xe.u.u.type == ButtonPress)
-		button_state |= (1 << xe.u.u.detail);
-    else if (xe.u.u.type == ButtonRelease)
-		button_state &= ~(1 << xe.u.u.detail);
+    }	
+    //	UpdateCurrentTime();
 }
diff --git a/hw/darwin/darwinEvents.c b/hw/darwin/darwinEvents.c
index 6b902df..2a27ac4 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -1,9 +1,9 @@
 /*
- * Darwin event queue and event handling
- */
-/*
-Copyright (c) 2002-2004 Torrey T. Lyons. All Rights Reserved.
+Darwin event queue and event handling
+
+Copyright 2007 Apple Inc.
 Copyright 2004 Kaleb S. KEITHLEY. All Rights Reserved.
+Copyright (c) 2002-2004 Torrey T. Lyons. All Rights Reserved.
 
 This file is based on mieq.c by Keith Packard,
 which contains the following copyright:
@@ -61,6 +61,8 @@ typedef struct _Event {
     ScreenPtr   pScreen;
 } EventRec, *EventPtr;
 
+int input_check_zero, input_check_flag;
+
 typedef struct _EventQueue {
     HWEventQueueType    head, tail; /* long for SetInputCheck */
     CARD32      lastEventTime;      /* to avoid time running backwards */
@@ -73,7 +75,6 @@ typedef struct _EventQueue {
 
 static EventQueueRec darwinEventQueue;
 
-
 /*
  * DarwinPressModifierMask
  *  Press or release the given modifier key, specified by its mask.
@@ -177,18 +178,15 @@ static void DarwinSimulateMouseClick(
 }
 
 
-Bool
-DarwinEQInit(
-    DevicePtr pKbd,
-    DevicePtr pPtr)
-{
+Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
+    mieqInit();
     darwinEventQueue.head = darwinEventQueue.tail = 0;
     darwinEventQueue.lastEventTime = GetTimeInMillis ();
     darwinEventQueue.pKbd = pKbd;
     darwinEventQueue.pPtr = pPtr;
     darwinEventQueue.pEnqueueScreen = screenInfo.screens[0];
     darwinEventQueue.pDequeueScreen = darwinEventQueue.pEnqueueScreen;
-    SetInputCheck (&darwinEventQueue.head, &darwinEventQueue.tail);
+    SetInputCheck(&input_check_zero, &input_check_flag);
     return TRUE;
 }
 
@@ -199,11 +197,10 @@ DarwinEQInit(
  *    DarwinEQEnqueue    - called from event gathering thread
  *    ProcessInputEvents - called from X server thread
  *  DarwinEQEnqueue should never be called from more than one thread.
+ * 
+ * This should be deprecated in favor of miEQEnqueue -- BB
  */
-void
-DarwinEQEnqueue(
-    const xEvent *e)
-{
+void DarwinEQEnqueue(const xEvent *e) {
     HWEventQueueType oldtail, newtail;
     char byte = 0;
 
@@ -213,13 +210,12 @@ DarwinEQEnqueue(
     // This is difficult to do in a thread-safe way and rarely useful.
 
     newtail = oldtail + 1;
-    if (newtail == QUEUE_SIZE)
-        newtail = 0;
+    if (newtail == QUEUE_SIZE) newtail = 0;
     /* Toss events which come in late */
-    if (newtail == darwinEventQueue.head)
-        return;
+    if (newtail == darwinEventQueue.head) return;
 
     darwinEventQueue.events[oldtail].event = *e;
+
     /*
      * Make sure that event times don't go backwards - this
      * is "unnecessary", but very useful
@@ -244,20 +240,13 @@ DarwinEQEnqueue(
  * DarwinEQPointerPost
  *  Post a pointer event. Used by the mipointer.c routines.
  */
-void
-DarwinEQPointerPost(
-    xEvent *e)
-{
+void DarwinEQPointerPost(xEvent *e) {
     (*darwinEventQueue.pPtr->processInputProc)
             (e, (DeviceIntPtr)darwinEventQueue.pPtr, 1);
 }
 
 
-void
-DarwinEQSwitchScreen(
-    ScreenPtr   pScreen,
-    Bool        fromDIX)
-{
+void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX) {
     darwinEventQueue.pEnqueueScreen = pScreen;
     if (fromDIX)
         darwinEventQueue.pDequeueScreen = pScreen;
@@ -268,8 +257,7 @@ DarwinEQSwitchScreen(
  * ProcessInputEvents
  *  Read and process events from the event queue until it is empty.
  */
-void ProcessInputEvents(void)
-{
+void ProcessInputEvents(void) {
     EventRec *e;
     int     x, y;
     xEvent  xe;
@@ -277,12 +265,15 @@ void ProcessInputEvents(void)
     // button number and modifier mask of currently pressed fake button
     static int darwinFakeMouseButtonDown = 0;
     static int darwinFakeMouseButtonMask = 0;
+    input_check_flag=0;
+
+    ErrorF("calling mieqProcessInputEvents\n");
+    mieqProcessInputEvents();
 
     // Empty the signaling pipe
     x = sizeof(xe);
-    while (x == sizeof(xe)) {
+    while (x == sizeof(xe)) 
         x = read(darwinEventReadFD, &xe, sizeof(xe));
-    }
 
     while (darwinEventQueue.head != darwinEventQueue.tail)
     {
@@ -298,10 +289,16 @@ void ProcessInputEvents(void)
                 dixScreenOrigins[miPointerCurrentScreen()->myNum].x;
         xe.u.keyButtonPointer.rootY -= darwinMainScreenY +
                 dixScreenOrigins[miPointerCurrentScreen()->myNum].y;
+	
+	ErrorF("old rootX = (%d,%d) darwinMainScreen = (%d,%d) dixScreenOrigins[%d]=(%d,%d)\n",
+	       xe.u.keyButtonPointer.rootX, xe.u.keyButtonPointer.rootY,
+	       darwinMainScreenX, darwinMainScreenY,
+	       miPointerCurrentScreen()->myNum,
+	       dixScreenOrigins[miPointerCurrentScreen()->myNum].x,
+	       dixScreenOrigins[miPointerCurrentScreen()->myNum].y);
+
+	//Assumption - screen switching can only occur on motion events
 
-        /*
-         * Assumption - screen switching can only occur on motion events
-         */
         if (e->pScreen != darwinEventQueue.pDequeueScreen)
         {
             darwinEventQueue.pDequeueScreen = e->pScreen;
diff-tree ed7ccc481ad1caaa518cafe944c2327a5d0b6c65 (from 90ca76ba28fcd8bed945e33cf9674784fa2eb533)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Thu Mar 1 00:51:10 2007 -0800

    AIGLX support for Darwin -- works well enough to run
    glxgears and glxinfo, but still needs more testing.

diff --git a/GL/apple/indirect.c b/GL/apple/indirect.c
index 8cba1c6..ba54186 100644
--- a/GL/apple/indirect.c
+++ b/GL/apple/indirect.c
@@ -1,11 +1,10 @@
 /*
  * GLX implementation that uses Apple's OpenGL.framework
  * (Indirect rendering path)
- */
-/*
- * Copyright (c) 2002 Greg Parker. All Rights Reserved.
- * Copyright (c) 2002 Apple Computer, Inc.
+ *
+ * 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:
@@ -39,11 +38,12 @@
 #include "dri.h"
 #include "quartz.h"
 
-#include <CoreGraphics/CoreGraphics.h>
+//#include <CoreGraphics/CoreGraphics.h>
 #include <OpenGL/OpenGL.h>
 #include <OpenGL/CGLContext.h>
 
 // X11 and X11's glx
+#include <GL/gl.h>
 #include <miscstruct.h>
 #include <windowstr.h>
 #include <resource.h>
@@ -61,11 +61,16 @@
 #include "x-hash.h"
 #include "x-list.h"
 
+#include <dispatch.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);
 
+#define GLAQUA_DEBUG 1
 
 // Write debugging output, or not
 #ifdef GLAQUA_DEBUG
@@ -74,182 +79,163 @@ extern void GlxSetVisualConfigs(int ncon
 #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);
-}
+static void setup_dispatch_table(void);
 
 // some prototypes
-static Bool glAquaScreenProbe(int screen);
+static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen);
 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
+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 __GLXdrawable * __glXAquaContextCreateDrawable(__GLXcontext *context, DrawablePtr pDraw, XID drawId);
+
+static CGLPixelFormatObj makeFormat(__GLcontextModes *mode);
+
+__GLXprovider __glXMesaProvider = {
+  __glXAquaScreenProbe,
+  "Core OpenGL",
+    NULL
 };
 
-void *__glXglDDXExtensionInfo(void) {
-    return &__glDDXExtensionInfo;
+__GLXprovider *
+GlxGetMesaProvider (void)
+{
+  ErrorF("GlxGetMesaProvider\n");
+  return &__glXMesaProvider;
 }
 
-// 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 __GLXAquaScreen   __GLXAquaScreen;
+typedef struct __GLXAquaContext  __GLXAquaContext;
+typedef struct __GLXAquaDrawable __GLXAquaDrawable;
 
-typedef struct {
+struct __GLXAquaScreen {
+  __GLXscreen   base;
+  int           index;
     int num_vis;
     __GLcontextModes *modes;
-    void **priv;
+};
 
-    // wrapped screen functions
-    RealizeWindowProcPtr RealizeWindow;
-    UnrealizeWindowProcPtr UnrealizeWindow;
-} glAquaScreenRec;
+static __GLXAquaScreen glAquaScreens[MAXSCREENS];
 
-static glAquaScreenRec glAquaScreens[MAXSCREENS];
+struct __GLXAquaContext {
+  __GLXcontext base;
+  CGLContextObj ctx;
+  CGLPixelFormatObj pixelFormat;
+  xp_surface_id sid;
+  unsigned isAttached :1;
+};
 
-// __GLdrawablePrivate->private
-typedef struct {
+struct __GLXAquaDrawable {
+  __GLXdrawable base;
     DrawablePtr pDraw;
     xp_surface_id sid;
-} GLAquaDrawableRec;
-
-struct __GLcontextRec {
-    struct __GLinterfaceRec interface; // required to be first
+};
 
-    CGLContextObj ctx;
-    CGLPixelFormatObj pixelFormat;
+static __GLXcontext *
+__glXAquaScreenCreateContext(__GLXscreen *screen,
+			     __GLcontextModes *modes,
+			     __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.modes      = modes;
+
+  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(modes);
+  if (!context->pixelFormat) {
+        free(context);
+        return NULL;
+  }
 
-    /* set when attached */
-    xp_surface_id sid;
+  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;
+}
 
-    unsigned isAttached :1;
+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;
 
-
-// Context manipulation; return GL_FALSE on failure
-static GLboolean glAquaDestroyContext(__GLcontext *gc)
-{
+static void __glXAquaContextDestroy(__GLXcontext *baseContext) {
     x_list *lst;
 
-    GLAQUA_DEBUG_MSG("glAquaDestroyContext (ctx 0x%x)\n",
-                     (unsigned int) gc->ctx);
-
-    if (gc != NULL)
-    {
-        if (gc->sid != 0 && surface_hash != NULL)
-        {
-            lst = x_hash_table_lookup(surface_hash, (void *) gc->sid, NULL);
-            lst = x_list_remove(lst, gc);
-            x_hash_table_insert(surface_hash, (void *) gc->sid, lst);
-        }
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
 
-        if (gc->ctx != NULL)
-            CGLDestroyContext(gc->ctx);
+    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 (gc->pixelFormat != NULL)
-            CGLDestroyPixelFormat(gc->pixelFormat);
+      if (context->ctx != NULL) CGLDestroyContext(context->ctx);
 
-        free(gc);
+      if (context->pixelFormat != NULL)	CGLDestroyPixelFormat(context->pixelFormat);
+      
+      free(context);
     }
-
-    return GL_TRUE;
 }
 
-static GLboolean glAquaLoseCurrent(__GLcontext *gc)
-{
+static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext) {
     CGLError gl_err;
 
-    GLAQUA_DEBUG_MSG("glAquaLoseCurrent (ctx 0x%x)\n", (unsigned int) gc->ctx);
+    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));
+      ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
 
     __glXLastContext = NULL; // Mesa does this; why?
 
@@ -258,141 +244,139 @@ static GLboolean glAquaLoseCurrent(__GLc
 
 /* 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 = _arg;
-    GLAquaDrawableRec *aquaPriv = data;
-    __GLcontext *gc;
+static void surface_notify(void *_arg, void *data) {
+    DRISurfaceNotifyArg *arg = (DRISurfaceNotifyArg *)_arg;
+    __GLXAquaDrawable *draw = (__GLXAquaDrawable *)data;
+    __GLXAquaContext *context;
     x_list *lst;
-
-    switch (arg->kind)
-    {
+	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);
-
-        aquaPriv->pDraw = NULL;
-        aquaPriv->sid = 0;
+	        draw->base->pDraw = NULL;
+			draw->sid = 0;
         break;
 
     case AppleDRISurfaceNotifyChanged:
-        if (surface_hash != NULL)
-        {
+        if (surface_hash != NULL) {
             lst = x_hash_table_lookup(surface_hash, (void *) arg->id, NULL);
             for (; lst != NULL; lst = lst->next)
             {
-                gc = lst->data;
-                xp_update_gl_context(gc->ctx);
+                context = lst->data;
+                xp_update_gl_context(context->ctx);
             }
         }
         break;
+	default:
+		ErrorF("surface_notify: unknown kind %d\n", arg->kind);
+		break;
     }
 }
 
-static void unattach(__GLcontext *gc)
-{
-    x_list *lst;
-
-    if (gc->isAttached)
-    {
-        GLAQUA_DEBUG_MSG("unattaching\n");
-
-        if (surface_hash != NULL)
-        {
-            lst = x_hash_table_lookup(surface_hash, (void *) gc->sid, NULL);
-            lst = x_list_remove(lst, gc);
-            x_hash_table_insert(surface_hash, (void *) gc->sid, lst);
-        }
-
-        CGLClearDrawable(gc->ctx);
-        gc->isAttached = FALSE;
-        gc->sid = 0;
-    }
-}
-
-static void attach(__GLcontext *gc, __GLdrawablePrivate *glPriv)
-{
-    __GLXdrawablePrivate *glxPriv;
-    GLAquaDrawableRec *aquaPriv;
+static void attach(__GLXAquaContext *context, __GLXAquaDrawable *draw) {
     DrawablePtr pDraw;
+	GLAQUA_DEBUG_MSG("attach(%p, %p)\n", context, draw);
+    pDraw = draw->base.pDraw;
 
-    glxPriv = (__GLXdrawablePrivate *)glPriv->other;
-    aquaPriv = (GLAquaDrawableRec *)glPriv->private;
-    pDraw = glxPriv->pDraw;
-
-    if (aquaPriv->sid == 0)
-    {
-        if (!quartzProcs->CreateSurface(pDraw->pScreen, pDraw->id, pDraw,
-                                        0, &aquaPriv->sid, NULL,
-                                        surface_notify, aquaPriv))
-        {
+    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;
-        }
-        aquaPriv->pDraw = pDraw;
-    }
+        draw->pDraw = pDraw;
+	} 
 
-    if (!gc->isAttached || gc->sid != aquaPriv->sid)
-    {
+    if (!context->isAttached || context->sid != draw->sid) {
         x_list *lst;
 
-        if (xp_attach_gl_context(gc->ctx, aquaPriv->sid) != Success)
-        {
-            quartzProcs->DestroySurface(pDraw->pScreen, pDraw->id, pDraw,
-                                        surface_notify, aquaPriv);
+        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 *) aquaPriv->sid);
+                x_hash_table_remove(surface_hash, (void *) draw->sid);
 
-            aquaPriv->sid = 0;
+            draw->sid = 0;
             return;
         }
 
-        gc->isAttached = TRUE;
-        gc->sid = aquaPriv->sid;
+        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 *) gc->sid, NULL);
-        if (x_list_find(lst, gc) == NULL)
-        {
-            lst = x_list_prepend(lst, gc);
-            x_hash_table_insert(surface_hash, (void *) gc->sid, lst);
+        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) aquaPriv->sid);
+                         (unsigned int) draw->sid);
+    } 
+}
+
+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;
     }
 }
 
-static GLboolean glAquaMakeCurrent(__GLcontext *gc)
-{
-    __GLdrawablePrivate *glPriv = gc->interface.imports.getDrawablePrivate(gc);
+static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext) {
     CGLError gl_err;
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
+	__GLXAquaDrawable *drawPriv = (__GLXAquaDrawable *) context->base.drawPriv;
+    __GLXAquaDrawable *readPriv = (__GLXAquaDrawable *) context->base.readPriv;
 
-    GLAQUA_DEBUG_MSG("glAquaMakeCurrent (ctx 0x%x)\n", (unsigned int) gc->ctx);
-
-    attach(gc, glPriv);
+    GLAQUA_DEBUG_MSG("glAquaMakeCurrent (ctx 0x%p)\n", baseContext);
+    
+    attach(context, drawPriv);
 
-    gl_err = CGLSetCurrentContext(gc->ctx);
+    gl_err = CGLSetCurrentContext(context->ctx);
     if (gl_err != 0)
         ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
-
+    
     return gl_err == 0;
 }
 
 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)
+static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask)
 {
     CGLError gl_err;
 
-    GLAQUA_DEBUG_MSG("glAquaCopyContext\n");
+    __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)
@@ -401,14 +385,13 @@ static GLboolean glAquaCopyContext(__GLc
     return gl_err == 0;
 }
 
-static GLboolean glAquaForceCurrent(__GLcontext *gc)
+static int __glXAquaContextForceCurrent(__GLXcontext *baseContext)
 {
     CGLError gl_err;
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
+    GLAQUA_DEBUG_MSG("glAquaForceCurrent (ctx %p)\n", context->ctx);
 
-    GLAQUA_DEBUG_MSG("glAquaForceCurrent (ctx 0x%x)\n",
-                     (unsigned int) gc->ctx);
-
-    gl_err = CGLSetCurrentContext(gc->ctx);
+    gl_err = CGLSetCurrentContext(context->ctx);
     if (gl_err != 0)
         ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
 
@@ -417,45 +400,41 @@ static GLboolean glAquaForceCurrent(__GL
 
 /* Drawing surface notification callbacks */
 
-static GLboolean glAquaNotifyResize(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifyResize");
+static GLboolean __glXAquaDrawableResize(__GLXdrawable *base)  {
+    GLAQUA_DEBUG_MSG("unimplemented glAquaDrawableResize\n");
     return GL_TRUE;
 }
 
-static void glAquaNotifyDestroy(__GLcontext *gc)
-{
+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 GLboolean __glXAquaDrawableSwapBuffers(__GLXdrawable *base) {
+    __GLXAquaDrawable *glxPriv = (__GLXAquaDrawable *) base;
+    CGLError gl_err;
+	__GLXAquaContext * drawableCtx;
+//    GLAQUA_DEBUG_MSG("glAquaDrawableSwapBuffers(%p)\n",base);
+	
+	if(!base) {
+		ErrorF("glXAquaDrawbleSwapBuffers passed NULL\n");
+	    return GL_FALSE;
+	}
 
-static void glAquaBeginDispatchOverride(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaBeginDispatchOverride");
-}
+    drawableCtx = (__GLXAquaContext *)base->drawGlxc;
 
-static void glAquaEndDispatchOverride(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaEndDispatchOverride");
+    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(__GLcontextModes *mode)
-{
+static CGLPixelFormatObj makeFormat(__GLcontextModes *mode) {
     int i;
     CGLPixelFormatAttribute attr[64]; // currently uses max of 30
     CGLPixelFormatObj result;
-    long n_formats;
+    GLint n_formats;
     CGLError gl_err;
     
     GLAQUA_DEBUG_MSG("makeFormat\n");
@@ -491,10 +470,12 @@ static CGLPixelFormatObj makeFormat(__GL
         attr[i++] = mode->accumRedBits + mode->accumGreenBits
                     + mode->accumBlueBits + mode->accumAlphaBits;
     }
+	
     if (mode->haveDepthBuffer) {
         attr[i++] = kCGLPFADepthSize;
         attr[i++] = mode->depthBits;
     }
+	
     if (mode->haveStencilBuffer) {
         attr[i++] = kCGLPFAStencilSize;
         attr[i++] = mode->stencilBits;
@@ -521,129 +502,6 @@ static CGLPixelFormatObj makeFormat(__GL
     return result;
 }
 
-static __GLinterface *glAquaCreateContext(__GLimports *imports,
-                                          __GLcontextModes *mode,
-                                          __GLinterface *shareGC)
-{
-    __GLcontext *result;
-    __GLcontext *sharectx = (__GLcontext *)shareGC;
-    CGLError gl_err;
-
-    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 = NULL;
-    gl_err = CGLCreateContext(result->pixelFormat,
-                              sharectx ? sharectx->ctx : NULL,
-                              &result->ctx);
-
-    if (gl_err != 0) {
-        ErrorF("CGLCreateContext error: %s\n", CGLErrorString(gl_err));
-        CGLDestroyPixelFormat(result->pixelFormat);
-        free(result);
-        return NULL;
-    }
-
-    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->next) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, glPriv);
-        }
-
-        // GL contexts bound to this window for reading
-        for (gx = glxPriv->readGlxc; gx != NULL; gx = gx->next) {
-            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->next) {
-            gc = (__GLcontext *)gx->gc;
-            unattach(gc);
-        }
-
-        // GL contexts bound to this window for reading
-        for (gx = glxPriv->readGlxc; gx != NULL; gx = gx->next) {
-            gc = (__GLcontext *)gx->gc;
-            unattach(gc);
-        }
-    }
-
-    pScreen->UnrealizeWindow = screenPriv->UnrealizeWindow;
-    result = pScreen->UnrealizeWindow(pWin);
-    pScreen->UnrealizeWindow = glAquaUnrealizeWindow;
-
-    return result;
-}
-
-
 // Originally copied from Mesa
 
 static int                 numConfigs     = 0;
@@ -821,15 +679,15 @@ static Bool init_visuals(int *nvisualp, 
 
     /* Alloc space for the list of new GLX visuals */
     pNewVisualConfigs = (__GLXvisualConfig *)
-                     __glXMalloc(numNewConfigs * sizeof(__GLXvisualConfig));
+                     malloc(numNewConfigs * sizeof(__GLXvisualConfig));
     if (!pNewVisualConfigs) {
         return FALSE;
     }
 
     /* Alloc space for the list of new GLX visual privates */
-    pNewVisualPriv = (void **) __glXMalloc(numNewConfigs * sizeof(void *));
+    pNewVisualPriv = (void **) malloc(numNewConfigs * sizeof(void *));
     if (!pNewVisualPriv) {
-        __glXFree(pNewVisualConfigs);
+        free(pNewVisualConfigs);
         return FALSE;
     }
 
@@ -879,40 +737,40 @@ static Bool init_visuals(int *nvisualp, 
     numConfigs = 0;
 
     /* Alloc temp space for the list of orig VisualIDs for each new visual */
-    orig_vid = (VisualID *)__glXMalloc(numNewVisuals * sizeof(VisualID));
+    orig_vid = (VisualID *)malloc(numNewVisuals * sizeof(VisualID));
     if (!orig_vid) {
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
+        free(pNewVisualPriv);
+        free(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);
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
         return FALSE;
     }
 
     /* Alloc space for the list of glXVisualPrivates */
-    glXVisualPriv = (void **)__glXMalloc(numNewVisuals * sizeof(void *));
+    glXVisualPriv = (void **)malloc(numNewVisuals * sizeof(void *));
     if (!glXVisualPriv) {
         _gl_context_modes_destroy( modes );
-        __glXFree(orig_vid);
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
         return FALSE;
     }
 
     /* Alloc space for the new list of the X server's visuals */
-    pVisualNew = (VisualPtr)__glXMalloc(numNewVisuals * sizeof(VisualRec));
+    pVisualNew = (VisualPtr)malloc(numNewVisuals * sizeof(VisualRec));
     if (!pVisualNew) {
-        __glXFree(glXVisualPriv);
+        free(glXVisualPriv);
         _gl_context_modes_destroy( modes );
-        __glXFree(orig_vid);
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
         return FALSE;
     }
 
@@ -1007,7 +865,7 @@ static Bool init_visuals(int *nvisualp, 
 
     /* Save the GLX visuals in the screen structure */
     glAquaScreens[screenInfo.numScreens-1].num_vis = numNewVisuals;
-    glAquaScreens[screenInfo.numScreens-1].priv = glXVisualPriv;
+    //    glAquaScreens[screenInfo.numScreens-1].priv = glXVisualPriv;
 
     /* Set up depth's VisualIDs */
     for (i = 0; i < ndepth; i++) {
@@ -1022,7 +880,7 @@ static Bool init_visuals(int *nvisualp, 
                 numVids++;
 
         /* Allocate a new list of VisualIDs for this depth */
-        pVids = (VisualID *)__glXMalloc(numVids * sizeof(VisualID));
+        pVids = (VisualID *)malloc(numVids * sizeof(VisualID));
 
         /* Initialize the new list of VisualIDs for this depth */
         for (j = 0; j < pdepth[i].numVids; j++)
@@ -1031,7 +889,7 @@ static Bool init_visuals(int *nvisualp, 
                 pVids[n++] = pVisualNew[k].vid;
 
         /* Update this depth's list of VisualIDs */
-        __glXFree(pdepth[i].vids);
+        free(pdepth[i].vids);
         pdepth[i].vids = pVids;
         pdepth[i].numVids = numVids;
     }
@@ -1041,21 +899,22 @@ static Bool init_visuals(int *nvisualp, 
     *visualp = pVisualNew;
 
     /* Free the old list of the X server's visuals */
-    __glXFree(pVisual);
+    free(pVisual);
 
     /* Clean up temporary allocations */
-    __glXFree(orig_vid);
-    __glXFree(pNewVisualPriv);
-    __glXFree(pNewVisualConfigs);
+    free(orig_vid);
+    free(pNewVisualPriv);
+    free(pNewVisualConfigs);
 
     /* Free the private list created by DDX HW driver */
     if (visualPrivates)
-        xfree(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. */
@@ -1066,20 +925,22 @@ glAquaInitVisualConfigs(void)
     __GLXvisualConfig  *lclVisualConfigs  = NULL;
     void              **lclVisualPrivates = NULL;
 
-    int depth, aux, buffers, stencil, accum;
+    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)
-        = 32 configs */
+        = 64 configs with stereo, or 32 without */
 
-    lclNumConfigs = 2 * 2 * 2 * 2 * 2; /* 32 */
+    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);
@@ -1088,54 +949,55 @@ glAquaInitVisualConfigs(void)
     /* fill in configs */
     if (NULL != lclVisualConfigs) {
         i = 0; /* current buffer */
-        for (depth = 0; depth < 2; depth++) {
+        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 = 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++;
-                        }
-                    }
-                }
+	      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");
@@ -1171,7 +1033,7 @@ static Bool glAquaInitVisuals(VisualPtr 
                         *ndepthp, *depthp, *rootDepthp);
 }
 
-
+#if 0
 static void fixup_visuals(int screen)
 {
     ScreenPtr pScreen = screenInfo.screens[screen];
@@ -1204,27 +1066,35 @@ static void fixup_visuals(int screen)
         }
     }
 }
+#endif
+static void __glXAquaScreenDestroy(__GLXscreen *screen) {
 
-static void init_screen_visuals(int screen)
-{
-    ScreenPtr pScreen = screenInfo.screens[screen];
-    __GLcontextModes *modes;
-    int *used;
-    int i, j;
+	GLAQUA_DEBUG_MSG("glXAquaScreenDestroy(%p)\n", screen);
+  __glXScreenDestroy(screen);
+
+  free(screen);
+}
 
+static void init_screen_visuals(__GLXAquaScreen *screen) {
+  ScreenPtr pScreen = screen->base.pScreen;
+  
+  __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: malloc / free.  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));
+    used = (int *)malloc(pScreen->numVisuals * sizeof(int));
+    memset(used, 0, pScreen->numVisuals * sizeof(int));
 
     i = 0;
-    for ( modes = glAquaScreens[screen].modes 
+    for ( modes = screen -> base.modes
           ; modes != NULL
           ; modes = modes->next ) {
         const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
@@ -1261,102 +1131,70 @@ static void init_screen_visuals(int scre
         i++;
     }
 
-    __glXFree(used);
+    free(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;
+static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen) {
+  __GLXAquaScreen *screen;
+  GLAQUA_DEBUG_MSG("glXAquaScreenProbe\n");
+  if (screen == NULL) return NULL;
 
-    return TRUE;
-}
+  screen = malloc(sizeof *screen);
 
-static GLboolean glAquaSwapBuffers(__GLXdrawablePrivate *glxPriv)
-{
-    // swap buffers on only *one* of the contexts
-    // (e.g. the last one for drawing)
-    __GLcontext *gc = (__GLcontext *)glxPriv->drawGlxc->gc;
-    CGLError gl_err;
+  __glXScreenInit(&screen->base, pScreen);
 
-    GLAQUA_DEBUG_MSG("glAquaSwapBuffers\n");
+  screen->base.destroy       = __glXAquaScreenDestroy;
+  screen->base.createContext = __glXAquaScreenCreateContext;
+  screen->base.pScreen       = pScreen;
 
-    if (gc != NULL && gc->ctx != NULL)
-    {
-        gl_err = CGLFlushDrawable(gc->ctx);
-        if (gl_err != 0)
-            ErrorF("CGLFlushDrawable error: %s\n", CGLErrorString(gl_err));
-    }
+  init_screen_visuals(screen);
 
-    return GL_TRUE;
+  return &screen->base;
 }
 
-static void glAquaDestroyDrawablePrivate(__GLdrawablePrivate *glPriv)
-{
+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(glPriv->private);
-    glPriv->private = NULL;
+    free(base);
 }
 
-static void glAquaCreateBuffer(__GLXdrawablePrivate *glxPriv)
+static __GLXdrawable *
+__glXAquaContextCreateDrawable(__GLXcontext *context,
+			       DrawablePtr pDraw,
+			       XID drawId)
 {
-    GLAquaDrawableRec *aquaPriv = malloc(sizeof(GLAquaDrawableRec));
-    __GLdrawablePrivate *glPriv = &glxPriv->glPriv;
+  __GLXAquaDrawable *glxPriv;
+  __GLXscreen *pGlxScreen;
+
+  GLAQUA_DEBUG_MSG("glAquaContextCreateDrawable(%p,%p,%d)\n", context, pDraw, drawId);
+  if (glxPriv == NULL) return NULL;
+  glxPriv = xalloc(sizeof *glxPriv);
+
+  memset(glxPriv, 0, sizeof *glxPriv);
+
+  if (!__glXDrawableInit(&glxPriv->base, context, pDraw, drawId)) {
+    xfree(glxPriv);
+    return NULL;
+  }
+
+  glxPriv->base.destroy       = __glXAquaDrawableDestroy;
+  glxPriv->base.resize        = __glXAquaDrawableResize;
+  glxPriv->base.swapBuffers   = __glXAquaDrawableSwapBuffers;
 
-    aquaPriv->sid = 0;
-    aquaPriv->pDraw = NULL;
+  pGlxScreen = __glXActiveScreens[pDraw->pScreen->myNum];
 
-    GLAQUA_DEBUG_MSG("glAquaCreateBuffer\n");
+  if (glxPriv->base.type == DRAWABLE_WINDOW) {
+    VisualID vid = wVisual((WindowPtr)pDraw);
 
-    // replace swapBuffers (original is never called)
-    glxPriv->swapBuffers = glAquaSwapBuffers;
+    glxPriv->base.modes = _gl_context_modes_find_visual(pGlxScreen->modes, vid);
+  } else 
+    glxPriv->base.modes = glxPriv->base.pGlxPixmap->modes;
 
-    // stash private data
-    glPriv->private = aquaPriv;
-    glPriv->freePrivate = glAquaDestroyDrawablePrivate;
+    return &glxPriv->base;
 }
 
 static void glAquaResetExtension(void)
@@ -1377,3 +1215,1239 @@ GLuint __glFloorLog2(GLuint val)
     }
     return c;
 }
+
+static void setup_dispatch_table(void) {
+	struct _glapi_table *disp=_glapi_get_dispatch();
+
+ SET_NewList(disp, glNewList);
+ SET_EndList(disp, glEndList);
+ SET_CallList(disp, glCallList);
+ SET_CallLists(disp, glCallLists);
+ SET_DeleteLists(disp, glDeleteLists);
+ SET_GenLists(disp, glGenLists);
+ SET_ListBase(disp, glListBase);
+ SET_Begin(disp, glBegin);
+ SET_Bitmap(disp, glBitmap);
+ 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_EdgeFlag(disp, glEdgeFlag);
+ SET_EdgeFlagv(disp, glEdgeFlagv);
+ SET_End(disp, glEnd);
+ 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_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_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_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_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_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_ClipPlane(disp, glClipPlane);
+ SET_ColorMaterial(disp, glColorMaterial);
+ SET_CullFace(disp, glCullFace);
+ SET_Fogf(disp, glFogf);
+ SET_Fogfv(disp, glFogfv);
+ SET_Fogi(disp, glFogi);
+ SET_Fogiv(disp, glFogiv);
+ SET_FrontFace(disp, glFrontFace);
+ SET_Hint(disp, glHint);
+ SET_Lightf(disp, glLightf);
+ SET_Lightfv(disp, glLightfv);
+ SET_Lighti(disp, glLighti);
+ SET_Lightiv(disp, glLightiv);
+ SET_LightModelf(disp, glLightModelf);
+ SET_LightModelfv(disp, glLightModelfv);
+ SET_LightModeli(disp, glLightModeli);
+ SET_LightModeliv(disp, glLightModeliv);
+ SET_LineStipple(disp, glLineStipple);
+ SET_LineWidth(disp, glLineWidth);
+ SET_Materialf(disp, glMaterialf);
+ SET_Materialfv(disp, glMaterialfv);
+ SET_Materiali(disp, glMateriali);
+ SET_Materialiv(disp, glMaterialiv);
+ SET_PointSize(disp, glPointSize);
+ SET_PolygonMode(disp, glPolygonMode);
+ SET_PolygonStipple(disp, glPolygonStipple);
+ SET_Scissor(disp, glScissor);
+ SET_ShadeModel(disp, glShadeModel);
+ SET_TexParameterf(disp, glTexParameterf);
+ SET_TexParameterfv(disp, glTexParameterfv);
+ SET_TexParameteri(disp, glTexParameteri);
+ SET_TexParameteriv(disp, glTexParameteriv);
+ SET_TexImage1D(disp, glTexImage1D);
+ SET_TexImage2D(disp, glTexImage2D);
+ 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_FeedbackBuffer(disp, glFeedbackBuffer);
+ SET_SelectBuffer(disp, glSelectBuffer);
+ SET_RenderMode(disp, glRenderMode);
+ SET_InitNames(disp, glInitNames);
+ SET_LoadName(disp, glLoadName);
+ SET_PassThrough(disp, glPassThrough);
+ SET_PopName(disp, glPopName);
+ SET_PushName(disp, glPushName);
+ SET_DrawBuffer(disp, glDrawBuffer);
+ SET_Clear(disp, glClear);
+ SET_ClearAccum(disp, glClearAccum);
+ SET_ClearIndex(disp, glClearIndex);
+ SET_ClearColor(disp, glClearColor);
+ SET_ClearStencil(disp, glClearStencil);
+ SET_ClearDepth(disp, glClearDepth);
+ SET_StencilMask(disp, glStencilMask);
+ SET_ColorMask(disp, glColorMask);
+ SET_DepthMask(disp, glDepthMask);
+ SET_IndexMask(disp, glIndexMask);
+ SET_Accum(disp, glAccum);
+ SET_Disable(disp, glDisable);
+ SET_Enable(disp, glEnable);
+ SET_Finish(disp, glFinish);
+ SET_Flush(disp, glFlush);
+ SET_PopAttrib(disp, glPopAttrib);
+ SET_PushAttrib(disp, glPushAttrib);
+ SET_Map1d(disp, glMap1d);
+ SET_Map1f(disp, glMap1f);
+ SET_Map2d(disp, glMap2d);
+ SET_Map2f(disp, glMap2f);
+ SET_MapGrid1d(disp, glMapGrid1d);
+ SET_MapGrid1f(disp, glMapGrid1f);
+ SET_MapGrid2d(disp, glMapGrid2d);
+ SET_MapGrid2f(disp, glMapGrid2f);
+ 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_EvalPoint1(disp, glEvalPoint1);
+ SET_EvalMesh2(disp, glEvalMesh2);
+ SET_EvalPoint2(disp, glEvalPoint2);
+ SET_AlphaFunc(disp, glAlphaFunc);
+ SET_BlendFunc(disp, glBlendFunc);
+ SET_LogicOp(disp, glLogicOp);
+ SET_StencilFunc(disp, glStencilFunc);
+ SET_StencilOp(disp, glStencilOp);
+ SET_DepthFunc(disp, glDepthFunc);
+ SET_PixelZoom(disp, glPixelZoom);
+ SET_PixelTransferf(disp, glPixelTransferf);
+ SET_PixelTransferi(disp, glPixelTransferi);
+ SET_PixelStoref(disp, glPixelStoref);
+ SET_PixelStorei(disp, glPixelStorei);
+ SET_PixelMapfv(disp, glPixelMapfv);
+ SET_PixelMapuiv(disp, glPixelMapuiv);
+ SET_PixelMapusv(disp, glPixelMapusv);
+ SET_ReadBuffer(disp, glReadBuffer);
+ SET_CopyPixels(disp, glCopyPixels);
+ SET_ReadPixels(disp, glReadPixels);
+ SET_DrawPixels(disp, glDrawPixels);
+ SET_GetBooleanv(disp, glGetBooleanv);
+ SET_GetClipPlane(disp, glGetClipPlane);
+ SET_GetDoublev(disp, glGetDoublev);
+ SET_GetError(disp, glGetError);
+ SET_GetFloatv(disp, glGetFloatv);
+ 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_GetPixelMapfv(disp, glGetPixelMapfv);
+ SET_GetPixelMapuiv(disp, glGetPixelMapuiv);
+ SET_GetPixelMapusv(disp, glGetPixelMapusv);
+ SET_GetPolygonStipple(disp, glGetPolygonStipple);
+ 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_GetTexParameterfv(disp, glGetTexParameterfv);
+ SET_GetTexParameteriv(disp, glGetTexParameteriv);
+ SET_GetTexLevelParameterfv(disp, glGetTexLevelParameterfv);
+ SET_GetTexLevelParameteriv(disp, glGetTexLevelParameteriv);
+ SET_IsEnabled(disp, glIsEnabled);
+ SET_IsList(disp, glIsList);
+ SET_DepthRange(disp, glDepthRange);
+ SET_Frustum(disp, glFrustum);
+ SET_LoadIdentity(disp, glLoadIdentity);
+ SET_LoadMatrixf(disp, glLoadMatrixf);
+ SET_LoadMatrixd(disp, glLoadMatrixd);
+ SET_MatrixMode(disp, glMatrixMode);
+ SET_MultMatrixf(disp, glMultMatrixf);
+ SET_MultMatrixd(disp, glMultMatrixd);
+ SET_Ortho(disp, glOrtho);
+ SET_PopMatrix(disp, glPopMatrix);
+ SET_PushMatrix(disp, glPushMatrix);
+ SET_Rotated(disp, glRotated);
+ SET_Rotatef(disp, glRotatef);
+ SET_Scaled(disp, glScaled);
+ SET_Scalef(disp, glScalef);
+ SET_Translated(disp, glTranslated);
+ SET_Translatef(disp, glTranslatef);
+ SET_Viewport(disp, glViewport);
+ SET_ArrayElement(disp, glArrayElement);
+ SET_BindTexture(disp, glBindTexture);
+ SET_ColorPointer(disp, glColorPointer);
+ SET_DisableClientState(disp, glDisableClientState);
+ SET_DrawArrays(disp, glDrawArrays);
+ SET_DrawElements(disp, glDrawElements);
+ SET_EdgeFlagPointer(disp, glEdgeFlagPointer);
+ SET_EnableClientState(disp, glEnableClientState);
+ SET_IndexPointer(disp, glIndexPointer);
+ SET_Indexub(disp, glIndexub);
+ SET_Indexubv(disp, glIndexubv);
+ SET_InterleavedArrays(disp, glInterleavedArrays);
+ SET_NormalPointer(disp, glNormalPointer);
+ SET_PolygonOffset(disp, glPolygonOffset);
+ SET_TexCoordPointer(disp, glTexCoordPointer);
+ SET_VertexPointer(disp, glVertexPointer);
+ SET_AreTexturesResident(disp, glAreTexturesResident); 
+ SET_CopyTexImage1D(disp, glCopyTexImage1D);
+ SET_CopyTexImage2D(disp, glCopyTexImage2D);
+ SET_CopyTexSubImage1D(disp, glCopyTexSubImage1D);
+ SET_CopyTexSubImage2D(disp, glCopyTexSubImage2D);
+ SET_DeleteTextures(disp, glDeleteTextures);
+ SET_GenTextures(disp, glGenTextures);
+ SET_GetPointerv(disp, glGetPointerv);
+ SET_IsTexture(disp, glIsTexture);
+ SET_PrioritizeTextures(disp, glPrioritizeTextures);
+ SET_TexSubImage1D(disp, glTexSubImage1D);
+ SET_TexSubImage2D(disp, glTexSubImage2D);
+ SET_PopClientAttrib(disp, glPopClientAttrib);
+ SET_PushClientAttrib(disp, glPushClientAttrib);
+ SET_BlendColor(disp, glBlendColor);
+ SET_BlendEquation(disp, glBlendEquation);
+ SET_DrawRangeElements(disp, glDrawRangeElements);
+ SET_ColorTable(disp, glColorTable);
+ SET_ColorTableParameterfv(disp, glColorTableParameterfv);
+ SET_ColorTableParameteriv(disp, glColorTableParameteriv);
+ SET_CopyColorTable(disp, glCopyColorTable);
+ SET_GetColorTable(disp, glGetColorTable);
+ SET_GetColorTableParameterfv(disp, glGetColorTableParameterfv);
+ SET_GetColorTableParameteriv(disp, glGetColorTableParameteriv);
+ SET_ColorSubTable(disp, glColorSubTable);
+ SET_CopyColorSubTable(disp, glCopyColorSubTable);
+ 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_CopyConvolutionFilter1D(disp, glCopyConvolutionFilter1D);
+ SET_CopyConvolutionFilter2D(disp, glCopyConvolutionFilter2D);
+ SET_GetConvolutionFilter(disp, glGetConvolutionFilter);
+ SET_GetConvolutionParameterfv(disp, glGetConvolutionParameterfv);
+ SET_GetConvolutionParameteriv(disp, glGetConvolutionParameteriv);
+ SET_GetSeparableFilter(disp, glGetSeparableFilter);
+ SET_SeparableFilter2D(disp, glSeparableFilter2D);
+ SET_GetHistogram(disp, glGetHistogram);
+ SET_GetHistogramParameterfv(disp, glGetHistogramParameterfv);
+ SET_GetHistogramParameteriv(disp, glGetHistogramParameteriv);
+ SET_GetMinmax(disp, glGetMinmax);
+ SET_GetMinmaxParameterfv(disp, glGetMinmaxParameterfv);
+ SET_GetMinmaxParameteriv(disp, glGetMinmaxParameteriv);
+ SET_Histogram(disp, glHistogram);
+ SET_Minmax(disp, glMinmax);
+ SET_ResetHistogram(disp, glResetHistogram);
+ SET_ResetMinmax(disp, glResetMinmax);
+ SET_TexImage3D(disp, glTexImage3D);
+ SET_TexSubImage3D(disp, glTexSubImage3D);
+ SET_CopyTexSubImage3D(disp, glCopyTexSubImage3D);
+ SET_ActiveTextureARB(disp, glActiveTextureARB);
+ SET_ClientActiveTextureARB(disp, glClientActiveTextureARB);
+ 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_LoadTransposeMatrixfARB(disp, glLoadTransposeMatrixfARB);
+ SET_LoadTransposeMatrixdARB(disp, glLoadTransposeMatrixdARB);
+ SET_MultTransposeMatrixfARB(disp, glMultTransposeMatrixfARB);
+ SET_MultTransposeMatrixdARB(disp, glMultTransposeMatrixdARB);
+ SET_SampleCoverageARB(disp, glSampleCoverageARB);
+ SET_DrawBuffersARB(disp, glDrawBuffersARB);
+/* SET_PolygonOffsetEXT(disp, glPolygonOffsetEXT);
+ SET_GetTexFilterFuncSGIS(disp, glGetTexFilterFuncSGIS);
+ SET_TexFilterFuncSGIS(disp, glTexFilterFuncSGIS);
+ SET_GetHistogramEXT(disp, glGetHistogramEXT);
+ SET_GetHistogramParameterfvEXT(disp, glGetHistogramParameterfvEXT);
+ SET_GetHistogramParameterivEXT(disp, glGetHistogramParameterivEXT);
+ SET_GetMinmaxEXT(disp, glGetMinmaxEXT);
+ SET_GetMinmaxParameterfvEXT(disp, glGetMinmaxParameterfvEXT);
+ SET_GetMinmaxParameterivEXT(disp, glGetMinmaxParameterivEXT);
+ SET_GetConvolutionFilterEXT(disp, glGetConvolutionFilterEXT);
+ SET_GetConvolutionParameterfvEXT(disp, glGetConvolutionParameterfvEXT);
+ SET_GetConvolutionParameterivEXT(disp, glGetConvolutionParameterivEXT);
+ SET_GetSeparableFilterEXT(disp, glGetSeparableFilterEXT);
+ SET_GetColorTableSGI(disp, glGetColorTableSGI);
+ SET_GetColorTableParameterfvSGI(disp, glGetColorTableParameterfvSGI);
+ SET_GetColorTableParameterivSGI(disp, glGetColorTableParameterivSGI);
+ SET_PixelTexGenSGIX(disp, glPixelTexGenSGIX);
+ SET_PixelTexGenParameteriSGIS(disp, glPixelTexGenParameteriSGIS);
+ SET_PixelTexGenParameterivSGIS(disp, glPixelTexGenParameterivSGIS);
+ SET_PixelTexGenParameterfSGIS(disp, glPixelTexGenParameterfSGIS);
+ SET_PixelTexGenParameterfvSGIS(disp, glPixelTexGenParameterfvSGIS);
+ SET_GetPixelTexGenParameterivSGIS(disp, glGetPixelTexGenParameterivSGIS);
+ SET_GetPixelTexGenParameterfvSGIS(disp, glGetPixelTexGenParameterfvSGIS);
+ SET_TexImage4DSGIS(disp, glTexImage4DSGIS);
+ SET_TexSubImage4DSGIS(disp, glTexSubImage4DSGIS); */
+ SET_AreTexturesResidentEXT(disp, glAreTexturesResident);
+ SET_GenTexturesEXT(disp, glGenTextures);
+ SET_IsTextureEXT(disp, glIsTexture);
+/* SET_DetailTexFuncSGIS(disp, glDetailTexFuncSGIS);
+ SET_GetDetailTexFuncSGIS(disp, glGetDetailTexFuncSGIS);
+ SET_SharpenTexFuncSGIS(disp, glSharpenTexFuncSGIS);
+ SET_GetSharpenTexFuncSGIS(disp, glGetSharpenTexFuncSGIS);
+ SET_SampleMaskSGIS(disp, glSampleMaskSGIS);
+ SET_SamplePatternSGIS(disp, glSamplePatternSGIS);
+ SET_ColorPointerEXT(disp, glColorPointerEXT);
+ SET_EdgeFlagPointerEXT(disp, glEdgeFlagPointerEXT);
+ SET_IndexPointerEXT(disp, glIndexPointerEXT);
+ SET_NormalPointerEXT(disp, glNormalPointerEXT);
+ SET_TexCoordPointerEXT(disp, glTexCoordPointerEXT);
+ SET_VertexPointerEXT(disp, glVertexPointerEXT);
+ SET_SpriteParameterfSGIX(disp, glSpriteParameterfSGIX);
+ SET_SpriteParameterfvSGIX(disp, glSpriteParameterfvSGIX);
+ SET_SpriteParameteriSGIX(disp, glSpriteParameteriSGIX);
+ SET_SpriteParameterivSGIX(disp, glSpriteParameterivSGIX);
+ SET_PointParameterfEXT(disp, glPointParameterfEXT);
+ SET_PointParameterfvEXT(disp, glPointParameterfvEXT);
+ SET_GetInstrumentsSGIX(disp, glGetInstrumentsSGIX);
+ SET_InstrumentsBufferSGIX(disp, glInstrumentsBufferSGIX);
+ SET_PollInstrumentsSGIX(disp, glPollInstrumentsSGIX);
+ SET_ReadInstrumentsSGIX(disp, glReadInstrumentsSGIX);
+ SET_StartInstrumentsSGIX(disp, glStartInstrumentsSGIX);
+ SET_StopInstrumentsSGIX(disp, glStopInstrumentsSGIX);
+ SET_FrameZoomSGIX(disp, glFrameZoomSGIX);
+ SET_TagSampleBufferSGIX(disp, glTagSampleBufferSGIX);
+ SET_ReferencePlaneSGIX(disp, glReferencePlaneSGIX);
+ SET_FlushRasterSGIX(disp, glFlushRasterSGIX);
+ SET_GetListParameterfvSGIX(disp, glGetListParameterfvSGIX);
+ SET_GetListParameterivSGIX(disp, glGetListParameterivSGIX);
+ SET_ListParameterfSGIX(disp, glListParameterfSGIX);
+ SET_ListParameterfvSGIX(disp, glListParameterfvSGIX);
+ SET_ListParameteriSGIX(disp, glListParameteriSGIX);
+ SET_ListParameterivSGIX(disp, glListParameterivSGIX);
+ SET_FragmentColorMaterialSGIX(disp, glFragmentColorMaterialSGIX);
+ SET_FragmentLightfSGIX(disp, glFragmentLightfSGIX);
+ SET_FragmentLightfvSGIX(disp, glFragmentLightfvSGIX);
+ SET_FragmentLightiSGIX(disp, glFragmentLightiSGIX);
+ SET_FragmentLightivSGIX(disp, glFragmentLightivSGIX);
+ SET_FragmentLightModelfSGIX(disp, glFragmentLightModelfSGIX);
+ SET_FragmentLightModelfvSGIX(disp, glFragmentLightModelfvSGIX);
+ SET_FragmentLightModeliSGIX(disp, glFragmentLightModeliSGIX);
+ SET_FragmentLightModelivSGIX(disp, glFragmentLightModelivSGIX);
+ SET_FragmentMaterialfSGIX(disp, glFragmentMaterialfSGIX);
+ SET_FragmentMaterialfvSGIX(disp, glFragmentMaterialfvSGIX);
+ SET_FragmentMaterialiSGIX(disp, glFragmentMaterialiSGIX);
+ SET_FragmentMaterialivSGIX(disp, glFragmentMaterialivSGIX);
+ SET_GetFragmentLightfvSGIX(disp, glGetFragmentLightfvSGIX);
+ SET_GetFragmentLightivSGIX(disp, glGetFragmentLightivSGIX);
+ SET_GetFragmentMaterialfvSGIX(disp, glGetFragmentMaterialfvSGIX);
+ SET_GetFragmentMaterialivSGIX(disp, glGetFragmentMaterialivSGIX);
+ SET_LightEnviSGIX(disp, glLightEnviSGIX); 
+ SET_VertexWeightfEXT(disp, glVertexWeightfEXT);
+ SET_VertexWeightfvEXT(disp, glVertexWeightfvEXT);
+ SET_VertexWeightPointerEXT(disp, glVertexWeightPointerEXT);
+ SET_FlushVertexArrayRangeNV(disp, glFlushVertexArrayRangeNV);
+ SET_VertexArrayRangeNV(disp, glVertexArrayRangeNV);
+ SET_CombinerParameterfvNV(disp, glCombinerParameterfvNV);
+ SET_CombinerParameterfNV(disp, glCombinerParameterfNV);
+ SET_CombinerParameterivNV(disp, glCombinerParameterivNV);
+ SET_CombinerParameteriNV(disp, glCombinerParameteriNV);
+ SET_CombinerInputNV(disp, glCombinerInputNV);
+ SET_CombinerOutputNV(disp, glCombinerOutputNV);
+ SET_FinalCombinerInputNV(disp, glFinalCombinerInputNV);
+ SET_GetCombinerInputParameterfvNV(disp, glGetCombinerInputParameterfvNV);
+ SET_GetCombinerInputParameterivNV(disp, glGetCombinerInputParameterivNV);
+ SET_GetCombinerOutputParameterfvNV(disp, glGetCombinerOutputParameterfvNV);
+ SET_GetCombinerOutputParameterivNV(disp, glGetCombinerOutputParameterivNV);
+ SET_GetFinalCombinerInputParameterfvNV(disp, glGetFinalCombinerInputParameterfvNV);
+ SET_GetFinalCombinerInputParameterivNV(disp, glGetFinalCombinerInputParameterivNV);
+ SET_ResizeBuffersMESA(disp, glResizeBuffersMESA);
+ SET_WindowPos2dMESA(disp, glWindowPos2dMESA);
+ SET_WindowPos2dvMESA(disp, glWindowPos2dvMESA);
+ SET_WindowPos2fMESA(disp, glWindowPos2fMESA);
+ SET_WindowPos2fvMESA(disp, glWindowPos2fvMESA);
+ SET_WindowPos2iMESA(disp, glWindowPos2iMESA);
+ SET_WindowPos2ivMESA(disp, glWindowPos2ivMESA);
+ SET_WindowPos2sMESA(disp, glWindowPos2sMESA);
+ SET_WindowPos2svMESA(disp, glWindowPos2svMESA);
+ SET_WindowPos3dMESA(disp, glWindowPos3dMESA);
+ SET_WindowPos3dvMESA(disp, glWindowPos3dvMESA);
+ SET_WindowPos3fMESA(disp, glWindowPos3fMESA);
+ SET_WindowPos3fvMESA(disp, glWindowPos3fvMESA);
+ SET_WindowPos3iMESA(disp, glWindowPos3iMESA);
+ SET_WindowPos3ivMESA(disp, glWindowPos3ivMESA);
+ SET_WindowPos3sMESA(disp, glWindowPos3sMESA);
+ SET_WindowPos3svMESA(disp, glWindowPos3svMESA);
+ 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);
+ SET_BlendFuncSeparateEXT(disp, glBlendFuncSeparateEXT);
+ SET_IndexMaterialEXT(disp, glIndexMaterialEXT);
+ SET_IndexFuncEXT(disp, glIndexFuncEXT);
+ SET_LockArraysEXT(disp, glLockArraysEXT);
+ SET_UnlockArraysEXT(disp, glUnlockArraysEXT);
+ SET_CullParameterdvEXT(disp, glCullParameterdvEXT);
+ SET_CullParameterfvEXT(disp, glCullParameterfvEXT);
+ SET_HintPGI(disp, glHintPGI);
+ SET_FogCoordfEXT(disp, glFogCoordfEXT);
+ SET_FogCoordfvEXT(disp, glFogCoordfvEXT);
+ SET_FogCoorddEXT(disp, glFogCoorddEXT);
+ SET_FogCoorddvEXT(disp, glFogCoorddvEXT);
+ SET_FogCoordPointerEXT(disp, glFogCoordPointerEXT);
+ SET_GetColorTableEXT(disp, glGetColorTableEXT);
+ SET_GetColorTableParameterivEXT(disp, glGetColorTableParameterivEXT);
+ SET_GetColorTableParameterfvEXT(disp, glGetColorTableParameterfvEXT);
+ SET_TbufferMask3DFX(disp, glTbufferMask3DFX);
+ SET_CompressedTexImage3DARB(disp, glCompressedTexImage3DARB);
+ SET_CompressedTexImage2DARB(disp, glCompressedTexImage2DARB);
+ SET_CompressedTexImage1DARB(disp, glCompressedTexImage1DARB);
+ SET_CompressedTexSubImage3DARB(disp, glCompressedTexSubImage3DARB);
+ SET_CompressedTexSubImage2DARB(disp, glCompressedTexSubImage2DARB);
+ SET_CompressedTexSubImage1DARB(disp, glCompressedTexSubImage1DARB);
+ SET_GetCompressedTexImageARB(disp, glGetCompressedTexImageARB);
+ 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_AreProgramsResidentNV(disp, glAreProgramsResidentNV);
+ SET_BindProgramNV(disp, glBindProgramNV);
+ SET_DeleteProgramsNV(disp, glDeleteProgramsNV);
+ SET_ExecuteProgramNV(disp, glExecuteProgramNV);
+ SET_GenProgramsNV(disp, glGenProgramsNV);
+ SET_GetProgramParameterdvNV(disp, glGetProgramParameterdvNV);
+ SET_GetProgramParameterfvNV(disp, glGetProgramParameterfvNV);
+ SET_GetProgramivNV(disp, glGetProgramivNV);
+ SET_GetProgramStringNV(disp, glGetProgramStringNV);
+ SET_GetTrackMatrixivNV(disp, glGetTrackMatrixivNV);
+ SET_GetVertexAttribdvARB(disp, glGetVertexAttribdvARB);
+ SET_GetVertexAttribfvARB(disp, glGetVertexAttribfvARB);
+ SET_GetVertexAttribivARB(disp, glGetVertexAttribivARB);
+ SET_GetVertexAttribPointervNV(disp, glGetVertexAttribPointervNV);
+ SET_IsProgramNV(disp, glIsProgramNV);
+ SET_LoadProgramNV(disp, glLoadProgramNV);
+ 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_RequestResidentProgramsNV(disp, glRequestResidentProgramsNV);
+ SET_TrackMatrixNV(disp, glTrackMatrixNV);
+ SET_VertexAttribPointerNV(disp, glVertexAttribPointerNV);
+ 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_VertexAttrib4dARB(disp, glVertexAttrib4dARB);
+ SET_VertexAttrib4dvARB(disp, glVertexAttrib4dvARB);
+ SET_VertexAttrib4fARB(disp, glVertexAttrib4fARB);
+ SET_VertexAttrib4fvARB(disp, glVertexAttrib4fvARB);
+ SET_VertexAttrib4sARB(disp, glVertexAttrib4sARB);
+ SET_VertexAttrib4svARB(disp, glVertexAttrib4svARB);
+ SET_VertexAttrib4NubARB(disp, glVertexAttrib4NubARB);
+ SET_VertexAttrib4NubvARB(disp, glVertexAttrib4NubvARB);
+ SET_VertexAttribs1dvNV(disp, glVertexAttribs1dvNV);
+ SET_VertexAttribs1fvNV(disp, glVertexAttribs1fvNV);
+ SET_VertexAttribs1svNV(disp, glVertexAttribs1svNV);
+ SET_VertexAttribs2dvNV(disp, glVertexAttribs2dvNV);
+ SET_VertexAttribs2fvNV(disp, glVertexAttribs2fvNV);
+ SET_VertexAttribs2svNV(disp, glVertexAttribs2svNV);
+ SET_VertexAttribs3dvNV(disp, glVertexAttribs3dvNV);
+ SET_VertexAttribs3fvNV(disp, glVertexAttribs3fvNV);
+ SET_VertexAttribs3svNV(disp, glVertexAttribs3svNV);
+ SET_VertexAttribs4dvNV(disp, glVertexAttribs4dvNV);
+ SET_VertexAttribs4fvNV(disp, glVertexAttribs4fvNV);
+ SET_VertexAttribs4svNV(disp, glVertexAttribs4svNV);
+ SET_VertexAttribs4ubvNV(disp, glVertexAttribs4ubvNV);
+ SET_PointParameteriNV(disp, glPointParameteriNV);
+ SET_PointParameterivNV(disp, glPointParameterivNV);
+ SET_MultiDrawArraysEXT(disp, glMultiDrawArraysEXT);
+ SET_MultiDrawElementsEXT(disp, glMultiDrawElementsEXT);
+ SET_ActiveStencilFaceEXT(disp, glActiveStencilFaceEXT);
+ SET_DeleteFencesNV(disp, glDeleteFencesNV);
+ SET_GenFencesNV(disp, glGenFencesNV);
+ SET_IsFenceNV(disp, glIsFenceNV);
+ SET_TestFenceNV(disp, glTestFenceNV);
+ SET_GetFenceivNV(disp, glGetFenceivNV);
+ SET_FinishFenceNV(disp, glFinishFenceNV);
+ SET_SetFenceNV(disp, glSetFenceNV);
+ SET_VertexAttrib4bvARB(disp, glVertexAttrib4bvARB);
+ SET_VertexAttrib4ivARB(disp, glVertexAttrib4ivARB);
+ SET_VertexAttrib4ubvARB(disp, glVertexAttrib4ubvARB);
+ SET_VertexAttrib4usvARB(disp, glVertexAttrib4usvARB);
+ SET_VertexAttrib4uivARB(disp, glVertexAttrib4uivARB);
+ SET_VertexAttrib4NbvARB(disp, glVertexAttrib4NbvARB);
+ SET_VertexAttrib4NsvARB(disp, glVertexAttrib4NsvARB);
+ SET_VertexAttrib4NivARB(disp, glVertexAttrib4NivARB);
+ SET_VertexAttrib4NusvARB(disp, glVertexAttrib4NusvARB);
+ SET_VertexAttrib4NuivARB(disp, glVertexAttrib4NuivARB);
+ SET_VertexAttribPointerARB(disp, glVertexAttribPointerARB);
+ SET_EnableVertexAttribArrayARB(disp, glEnableVertexAttribArrayARB);
+ SET_DisableVertexAttribArrayARB(disp, glDisableVertexAttribArrayARB);
+ SET_ProgramStringARB(disp, glProgramStringARB);
+ 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_GetProgramEnvParameterdvARB(disp, glGetProgramEnvParameterdvARB);
+ SET_GetProgramEnvParameterfvARB(disp, glGetProgramEnvParameterfvARB);
+ SET_GetProgramLocalParameterdvARB(disp, glGetProgramLocalParameterdvARB);
+ SET_GetProgramLocalParameterfvARB(disp, glGetProgramLocalParameterfvARB);
+ SET_GetProgramivARB(disp, glGetProgramivARB);
+ SET_GetProgramStringARB(disp, glGetProgramStringARB);
+ SET_ProgramNamedParameter4fNV(disp, glProgramNamedParameter4fNV);
+ SET_ProgramNamedParameter4dNV(disp, glProgramNamedParameter4dNV);
+ SET_ProgramNamedParameter4fvNV(disp, glProgramNamedParameter4fvNV);
+ SET_ProgramNamedParameter4dvNV(disp, glProgramNamedParameter4dvNV);
+ SET_GetProgramNamedParameterfvNV(disp, glGetProgramNamedParameterfvNV);
+ SET_GetProgramNamedParameterdvNV(disp, glGetProgramNamedParameterdvNV);
+ SET_BindBufferARB(disp, glBindBufferARB);
+ SET_BufferDataARB(disp, glBufferDataARB);
+ SET_BufferSubDataARB(disp, glBufferSubDataARB);
+ SET_DeleteBuffersARB(disp, glDeleteBuffersARB);
+ SET_GenBuffersARB(disp, glGenBuffersARB);
+ SET_GetBufferParameterivARB(disp, glGetBufferParameterivARB);
+ SET_GetBufferPointervARB(disp, glGetBufferPointervARB);
+ SET_GetBufferSubDataARB(disp, glGetBufferSubDataARB);
+ SET_IsBufferARB(disp, glIsBufferARB);
+ SET_MapBufferARB(disp, glMapBufferARB);
+ SET_UnmapBufferARB(disp, glUnmapBufferARB);
+ SET_DepthBoundsEXT(disp, glDepthBoundsEXT);
+ SET_GenQueriesARB(disp, glGenQueriesARB);
+ SET_DeleteQueriesARB(disp, glDeleteQueriesARB);
+ SET_IsQueryARB(disp, glIsQueryARB);
+ SET_BeginQueryARB(disp, glBeginQueryARB);
+ SET_EndQueryARB(disp, glEndQueryARB);
+ SET_GetQueryivARB(disp, glGetQueryivARB);
+ SET_GetQueryObjectivARB(disp, glGetQueryObjectivARB);
+ SET_GetQueryObjectuivARB(disp, glGetQueryObjectuivARB);
+ SET_MultiModeDrawArraysIBM(disp, glMultiModeDrawArraysIBM);
+ SET_MultiModeDrawElementsIBM(disp, glMultiModeDrawElementsIBM);
+ SET_BlendEquationSeparateEXT(disp, glBlendEquationSeparateEXT);
+ SET_DeleteObjectARB(disp, glDeleteObjectARB);
+ SET_GetHandleARB(disp, glGetHandleARB);
+ SET_DetachObjectARB(disp, glDetachObjectARB);
+ SET_CreateShaderObjectARB(disp, glCreateShaderObjectARB);
+ SET_ShaderSourceARB(disp, glShaderSourceARB);
+ SET_CompileShaderARB(disp, glCompileShaderARB);
+ SET_CreateProgramObjectARB(disp, glCreateProgramObjectARB);
+ SET_AttachObjectARB(disp, glAttachObjectARB);
+ SET_LinkProgramARB(disp, glLinkProgramARB);
+ SET_UseProgramObjectARB(disp, glUseProgramObjectARB);
+ SET_ValidateProgramARB(disp, glValidateProgramARB);
+ SET_Uniform1fARB(disp, glUniform1fARB);
+ SET_Uniform2fARB(disp, glUniform2fARB);
+ SET_Uniform3fARB(disp, glUniform3fARB);
+ SET_Uniform4fARB(disp, glUniform4fARB);
+ SET_Uniform1iARB(disp, glUniform1iARB);
+ SET_Uniform2iARB(disp, glUniform2iARB);
+ SET_Uniform3iARB(disp, glUniform3iARB);
+ SET_Uniform4iARB(disp, glUniform4iARB);
+ SET_Uniform1fvARB(disp, glUniform1fvARB);
+ SET_Uniform2fvARB(disp, glUniform2fvARB);
+ SET_Uniform3fvARB(disp, glUniform3fvARB);
+ SET_Uniform4fvARB(disp, glUniform4fvARB);
+ SET_Uniform1ivARB(disp, glUniform1ivARB);
+ SET_Uniform2ivARB(disp, glUniform2ivARB);
+ SET_Uniform3ivARB(disp, glUniform3ivARB);
+ SET_Uniform4ivARB(disp, glUniform4ivARB);
+ SET_UniformMatrix2fvARB(disp, glUniformMatrix2fvARB);
+ SET_UniformMatrix3fvARB(disp, glUniformMatrix3fvARB);
+ SET_UniformMatrix4fvARB(disp, glUniformMatrix4fvARB);
+ SET_GetObjectParameterfvARB(disp, glGetObjectParameterfvARB);
+ SET_GetObjectParameterivARB(disp, glGetObjectParameterivARB);
+ SET_GetInfoLogARB(disp, glGetInfoLogARB);
+ SET_GetAttachedObjectsARB(disp, glGetAttachedObjectsARB);
+ SET_GetUniformLocationARB(disp, glGetUniformLocationARB);
+ SET_GetActiveUniformARB(disp, glGetActiveUniformARB);
+ SET_GetUniformfvARB(disp, glGetUniformfvARB);
+ SET_GetUniformivARB(disp, glGetUniformivARB);
+ SET_GetShaderSourceARB(disp, glGetShaderSourceARB);
+ SET_BindAttribLocationARB(disp, glBindAttribLocationARB);
+ SET_GetActiveAttribARB(disp, glGetActiveAttribARB);
+ SET_GetAttribLocationARB(disp, glGetAttribLocationARB);
+ SET_GetVertexAttribdvNV(disp, glGetVertexAttribdvNV);
+ SET_GetVertexAttribfvNV(disp, glGetVertexAttribfvNV);
+ SET_GetVertexAttribivNV(disp, glGetVertexAttribivNV);
+ SET_VertexAttrib1dNV(disp, glVertexAttrib1dNV);
+ SET_VertexAttrib1dvNV(disp, glVertexAttrib1dvNV);
+ SET_VertexAttrib1fNV(disp, glVertexAttrib1fNV);
+ SET_VertexAttrib1fvNV(disp, glVertexAttrib1fvNV);
+ SET_VertexAttrib1sNV(disp, glVertexAttrib1sNV);
+ SET_VertexAttrib1svNV(disp, glVertexAttrib1svNV);
+ SET_VertexAttrib2dNV(disp, glVertexAttrib2dNV);
+ SET_VertexAttrib2dvNV(disp, glVertexAttrib2dvNV);
+ SET_VertexAttrib2fNV(disp, glVertexAttrib2fNV);
+ SET_VertexAttrib2fvNV(disp, glVertexAttrib2fvNV);
+ SET_VertexAttrib2sNV(disp, glVertexAttrib2sNV);
+ SET_VertexAttrib2svNV(disp, glVertexAttrib2svNV);
+ SET_VertexAttrib3dNV(disp, glVertexAttrib3dNV);
+ SET_VertexAttrib3dvNV(disp, glVertexAttrib3dvNV);
+ SET_VertexAttrib3fNV(disp, glVertexAttrib3fNV);
+ SET_VertexAttrib3fvNV(disp, glVertexAttrib3fvNV);
+ SET_VertexAttrib3sNV(disp, glVertexAttrib3sNV);
+ SET_VertexAttrib3svNV(disp, glVertexAttrib3svNV);
+ SET_VertexAttrib4dNV(disp, glVertexAttrib4dNV);
+ SET_VertexAttrib4dvNV(disp, glVertexAttrib4dvNV);
+ SET_VertexAttrib4fNV(disp, glVertexAttrib4fNV);
+ SET_VertexAttrib4fvNV(disp, glVertexAttrib4fvNV);
+ SET_VertexAttrib4sNV(disp, glVertexAttrib4sNV);
+ SET_VertexAttrib4svNV(disp, glVertexAttrib4svNV);
+ SET_VertexAttrib4ubNV(disp, glVertexAttrib4ubNV);
+ SET_VertexAttrib4ubvNV(disp, glVertexAttrib4ubvNV);
+ SET_GenFragmentShadersATI(disp, glGenFragmentShadersATI);
+ SET_BindFragmentShaderATI(disp, glBindFragmentShaderATI);
+ SET_DeleteFragmentShaderATI(disp, glDeleteFragmentShaderATI);
+ SET_BeginFragmentShaderATI(disp, glBeginFragmentShaderATI);
+ SET_EndFragmentShaderATI(disp, glEndFragmentShaderATI);
+ SET_PassTexCoordATI(disp, glPassTexCoordATI);
+ SET_SampleMapATI(disp, glSampleMapATI);
+ SET_ColorFragmentOp1ATI(disp, glColorFragmentOp1ATI);
+ SET_ColorFragmentOp2ATI(disp, glColorFragmentOp2ATI);
+ SET_ColorFragmentOp3ATI(disp, glColorFragmentOp3ATI);
+ SET_AlphaFragmentOp1ATI(disp, glAlphaFragmentOp1ATI);
+ SET_AlphaFragmentOp2ATI(disp, glAlphaFragmentOp2ATI);
+ SET_AlphaFragmentOp3ATI(disp, glAlphaFragmentOp3ATI);
+ SET_SetFragmentShaderConstantATI(disp, glSetFragmentShaderConstantATI);
+ SET_IsRenderbufferEXT(disp, glIsRenderbufferEXT);
+ SET_BindRenderbufferEXT(disp, glBindRenderbufferEXT);
+ SET_DeleteRenderbuffersEXT(disp, glDeleteRenderbuffersEXT);
+ SET_GenRenderbuffersEXT(disp, glGenRenderbuffersEXT);
+ SET_RenderbufferStorageEXT(disp, glRenderbufferStorageEXT);
+ SET_GetRenderbufferParameterivEXT(disp, glGetRenderbufferParameterivEXT);
+ SET_IsFramebufferEXT(disp, glIsFramebufferEXT);
+ SET_BindFramebufferEXT(disp, glBindFramebufferEXT);
+ SET_DeleteFramebuffersEXT(disp, glDeleteFramebuffersEXT);
+ SET_GenFramebuffersEXT(disp, glGenFramebuffersEXT);
+ SET_CheckFramebufferStatusEXT(disp, glCheckFramebufferStatusEXT);
+ SET_FramebufferTexture1DEXT(disp, glFramebufferTexture1DEXT);
+ SET_FramebufferTexture2DEXT(disp, glFramebufferTexture2DEXT);
+ SET_FramebufferTexture3DEXT(disp, glFramebufferTexture3DEXT);
+ SET_FramebufferRenderbufferEXT(disp, glFramebufferRenderbufferEXT);
+ SET_GetFramebufferAttachmentParameterivEXT(disp, glGetFramebufferAttachmentParameterivEXT);
+ SET_GenerateMipmapEXT(disp, glGenerateMipmapEXT);
+ SET_StencilFuncSeparate(disp, glStencilFuncSeparate);
+ SET_StencilOpSeparate(disp, glStencilOpSeparate);
+ SET_StencilMaskSeparate(disp, glStencilMaskSeparate);
+ SET_GetQueryObjecti64vEXT(disp, glGetQueryObjecti64vEXT);
+ SET_GetQueryObjectui64vEXT(disp, glGetQueryObjectui64vEXT);
+ SET_BlitFramebufferEXT(disp, glBlitFramebufferEXT);
+ SET_LoadTransposeMatrixfARB(disp, glLoadTransposeMatrixfARB);
+ SET_LoadTransposeMatrixdARB(disp, glLoadTransposeMatrixdARB);
+ SET_MultTransposeMatrixfARB(disp, glMultTransposeMatrixfARB);
+ SET_MultTransposeMatrixdARB(disp, glMultTransposeMatrixdARB);
+ SET_SampleCoverageARB(disp, glSampleCoverageARB);
+ SET_DrawBuffersARB(disp, glDrawBuffersARB);
+ SET_PolygonOffsetEXT(disp, glPolygonOffsetEXT);
+ SET_GetTexFilterFuncSGIS(disp, glGetTexFilterFuncSGIS);
+ SET_TexFilterFuncSGIS(disp, glTexFilterFuncSGIS);
+ SET_GetHistogramEXT(disp, glGetHistogramEXT);
+ SET_GetHistogramParameterfvEXT(disp, glGetHistogramParameterfvEXT);
+ SET_GetHistogramParameterivEXT(disp, glGetHistogramParameterivEXT);
+ SET_GetMinmaxEXT(disp, glGetMinmaxEXT);
+ SET_GetMinmaxParameterfvEXT(disp, glGetMinmaxParameterfvEXT);
+ SET_GetMinmaxParameterivEXT(disp, glGetMinmaxParameterivEXT);
+ SET_GetConvolutionFilterEXT(disp, glGetConvolutionFilterEXT);
+ SET_GetConvolutionParameterfvEXT(disp, glGetConvolutionParameterfvEXT);
+ SET_GetConvolutionParameterivEXT(disp, glGetConvolutionParameterivEXT);
+ SET_GetSeparableFilterEXT(disp, glGetSeparableFilterEXT);
+ SET_GetColorTableSGI(disp, glGetColorTableSGI);
+ SET_GetColorTableParameterfvSGI(disp, glGetColorTableParameterfvSGI);
+ SET_GetColorTableParameterivSGI(disp, glGetColorTableParameterivSGI);
+ SET_PixelTexGenSGIX(disp, glPixelTexGenSGIX);
+ SET_PixelTexGenParameteriSGIS(disp, glPixelTexGenParameteriSGIS);
+ SET_PixelTexGenParameterivSGIS(disp, glPixelTexGenParameterivSGIS);
+ SET_PixelTexGenParameterfSGIS(disp, glPixelTexGenParameterfSGIS);
+ SET_PixelTexGenParameterfvSGIS(disp, glPixelTexGenParameterfvSGIS);
+ SET_GetPixelTexGenParameterivSGIS(disp, glGetPixelTexGenParameterivSGIS);
+ SET_GetPixelTexGenParameterfvSGIS(disp, glGetPixelTexGenParameterfvSGIS);
+ SET_TexImage4DSGIS(disp, glTexImage4DSGIS);
+ SET_TexSubImage4DSGIS(disp, glTexSubImage4DSGIS);
+ SET_AreTexturesResidentEXT(disp, glAreTexturesResidentEXT);
+ SET_GenTexturesEXT(disp, glGenTexturesEXT);
+ SET_IsTextureEXT(disp, glIsTextureEXT);
+ SET_DetailTexFuncSGIS(disp, glDetailTexFuncSGIS);
+ SET_GetDetailTexFuncSGIS(disp, glGetDetailTexFuncSGIS);
+ SET_SharpenTexFuncSGIS(disp, glSharpenTexFuncSGIS);
+ SET_GetSharpenTexFuncSGIS(disp, glGetSharpenTexFuncSGIS);
+ SET_SampleMaskSGIS(disp, glSampleMaskSGIS);
+ SET_SamplePatternSGIS(disp, glSamplePatternSGIS);
+ SET_ColorPointerEXT(disp, glColorPointerEXT);
+ SET_EdgeFlagPointerEXT(disp, glEdgeFlagPointerEXT);
+ SET_IndexPointerEXT(disp, glIndexPointerEXT);
+ SET_NormalPointerEXT(disp, glNormalPointerEXT);
+ SET_TexCoordPointerEXT(disp, glTexCoordPointerEXT);
+ SET_VertexPointerEXT(disp, glVertexPointerEXT);
+ SET_SpriteParameterfSGIX(disp, glSpriteParameterfSGIX);
+ SET_SpriteParameterfvSGIX(disp, glSpriteParameterfvSGIX);
+ SET_SpriteParameteriSGIX(disp, glSpriteParameteriSGIX);
+ SET_SpriteParameterivSGIX(disp, glSpriteParameterivSGIX);
+ SET_PointParameterfEXT(disp, glPointParameterfEXT);
+ SET_PointParameterfvEXT(disp, glPointParameterfvEXT);
+ SET_GetInstrumentsSGIX(disp, glGetInstrumentsSGIX);
+ SET_InstrumentsBufferSGIX(disp, glInstrumentsBufferSGIX);
+ SET_PollInstrumentsSGIX(disp, glPollInstrumentsSGIX);
+ SET_ReadInstrumentsSGIX(disp, glReadInstrumentsSGIX);
+ SET_StartInstrumentsSGIX(disp, glStartInstrumentsSGIX);
+ SET_StopInstrumentsSGIX(disp, glStopInstrumentsSGIX);
+ SET_FrameZoomSGIX(disp, glFrameZoomSGIX);
+ SET_TagSampleBufferSGIX(disp, glTagSampleBufferSGIX);
+ SET_ReferencePlaneSGIX(disp, glReferencePlaneSGIX);
+ SET_FlushRasterSGIX(disp, glFlushRasterSGIX);
+ SET_GetListParameterfvSGIX(disp, glGetListParameterfvSGIX);
+ SET_GetListParameterivSGIX(disp, glGetListParameterivSGIX);
+ SET_ListParameterfSGIX(disp, glListParameterfSGIX);
+ SET_ListParameterfvSGIX(disp, glListParameterfvSGIX);
+ SET_ListParameteriSGIX(disp, glListParameteriSGIX);
+ SET_ListParameterivSGIX(disp, glListParameterivSGIX);
+ SET_FragmentColorMaterialSGIX(disp, glFragmentColorMaterialSGIX);
+ SET_FragmentLightfSGIX(disp, glFragmentLightfSGIX);
+ SET_FragmentLightfvSGIX(disp, glFragmentLightfvSGIX);
+ SET_FragmentLightiSGIX(disp, glFragmentLightiSGIX);
+ SET_FragmentLightivSGIX(disp, glFragmentLightivSGIX);
+ SET_FragmentLightModelfSGIX(disp, glFragmentLightModelfSGIX);
+ SET_FragmentLightModelfvSGIX(disp, glFragmentLightModelfvSGIX);
+ SET_FragmentLightModeliSGIX(disp, glFragmentLightModeliSGIX);
+ SET_FragmentLightModelivSGIX(disp, glFragmentLightModelivSGIX);
+ SET_FragmentMaterialfSGIX(disp, glFragmentMaterialfSGIX);
+ SET_FragmentMaterialfvSGIX(disp, glFragmentMaterialfvSGIX);
+ SET_FragmentMaterialiSGIX(disp, glFragmentMaterialiSGIX);
+ SET_FragmentMaterialivSGIX(disp, glFragmentMaterialivSGIX);
+ SET_GetFragmentLightfvSGIX(disp, glGetFragmentLightfvSGIX);
+ SET_GetFragmentLightivSGIX(disp, glGetFragmentLightivSGIX);
+ SET_GetFragmentMaterialfvSGIX(disp, glGetFragmentMaterialfvSGIX);
+ SET_GetFragmentMaterialivSGIX(disp, glGetFragmentMaterialivSGIX);
+ SET_LightEnviSGIX(disp, glLightEnviSGIX);
+ SET_VertexWeightfEXT(disp, glVertexWeightfEXT);
+ SET_VertexWeightfvEXT(disp, glVertexWeightfvEXT);
+ SET_VertexWeightPointerEXT(disp, glVertexWeightPointerEXT);
+ SET_FlushVertexArrayRangeNV(disp, glFlushVertexArrayRangeNV);
+ SET_VertexArrayRangeNV(disp, glVertexArrayRangeNV);
+ SET_CombinerParameterfvNV(disp, glCombinerParameterfvNV);
+ SET_CombinerParameterfNV(disp, glCombinerParameterfNV);
+ SET_CombinerParameterivNV(disp, glCombinerParameterivNV);
+ SET_CombinerParameteriNV(disp, glCombinerParameteriNV);
+ SET_CombinerInputNV(disp, glCombinerInputNV);
+ SET_CombinerOutputNV(disp, glCombinerOutputNV);
+ SET_FinalCombinerInputNV(disp, glFinalCombinerInputNV);
+ SET_GetCombinerInputParameterfvNV(disp, glGetCombinerInputParameterfvNV);
+ SET_GetCombinerInputParameterivNV(disp, glGetCombinerInputParameterivNV);
+ SET_GetCombinerOutputParameterfvNV(disp, glGetCombinerOutputParameterfvNV);
+ SET_GetCombinerOutputParameterivNV(disp, glGetCombinerOutputParameterivNV);
+ SET_GetFinalCombinerInputParameterfvNV(disp, glGetFinalCombinerInputParameterfvNV);
+ SET_GetFinalCombinerInputParameterivNV(disp, glGetFinalCombinerInputParameterivNV);
+ SET_ResizeBuffersMESA(disp, glResizeBuffersMESA);
+ SET_WindowPos2dMESA(disp, glWindowPos2dMESA);
+ SET_WindowPos2dvMESA(disp, glWindowPos2dvMESA);
+ SET_WindowPos2fMESA(disp, glWindowPos2fMESA);
+ SET_WindowPos2fvMESA(disp, glWindowPos2fvMESA);
+ SET_WindowPos2iMESA(disp, glWindowPos2iMESA);
+ SET_WindowPos2ivMESA(disp, glWindowPos2ivMESA);
+ SET_WindowPos2sMESA(disp, glWindowPos2sMESA);
+ SET_WindowPos2svMESA(disp, glWindowPos2svMESA);
+ SET_WindowPos3dMESA(disp, glWindowPos3dMESA);
+ SET_WindowPos3dvMESA(disp, glWindowPos3dvMESA);
+ SET_WindowPos3fMESA(disp, glWindowPos3fMESA);
+ SET_WindowPos3fvMESA(disp, glWindowPos3fvMESA);
+ SET_WindowPos3iMESA(disp, glWindowPos3iMESA);
+ SET_WindowPos3ivMESA(disp, glWindowPos3ivMESA);
+ SET_WindowPos3sMESA(disp, glWindowPos3sMESA);
+ SET_WindowPos3svMESA(disp, glWindowPos3svMESA);
+ 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);
+ SET_BlendFuncSeparateEXT(disp, glBlendFuncSeparateEXT);
+ SET_IndexMaterialEXT(disp, glIndexMaterialEXT);
+ SET_IndexFuncEXT(disp, glIndexFuncEXT);
+ SET_LockArraysEXT(disp, glLockArraysEXT);
+ SET_UnlockArraysEXT(disp, glUnlockArraysEXT);
+ SET_CullParameterdvEXT(disp, glCullParameterdvEXT);
+ SET_CullParameterfvEXT(disp, glCullParameterfvEXT);
+ SET_HintPGI(disp, glHintPGI);
+ SET_FogCoordfEXT(disp, glFogCoordfEXT);
+ SET_FogCoordfvEXT(disp, glFogCoordfvEXT);
+ SET_FogCoorddEXT(disp, glFogCoorddEXT);
+ SET_FogCoorddvEXT(disp, glFogCoorddvEXT);
+ SET_FogCoordPointerEXT(disp, glFogCoordPointerEXT);
+ SET_GetColorTableEXT(disp, glGetColorTableEXT);
+ SET_GetColorTableParameterivEXT(disp, glGetColorTableParameterivEXT);
+ SET_GetColorTableParameterfvEXT(disp, glGetColorTableParameterfvEXT);
+ SET_TbufferMask3DFX(disp, glTbufferMask3DFX);
+ SET_CompressedTexImage3DARB(disp, glCompressedTexImage3DARB);
+ SET_CompressedTexImage2DARB(disp, glCompressedTexImage2DARB);
+ SET_CompressedTexImage1DARB(disp, glCompressedTexImage1DARB);
+ SET_CompressedTexSubImage3DARB(disp, glCompressedTexSubImage3DARB);
+ SET_CompressedTexSubImage2DARB(disp, glCompressedTexSubImage2DARB);
+ SET_CompressedTexSubImage1DARB(disp, glCompressedTexSubImage1DARB);
+ SET_GetCompressedTexImageARB(disp, glGetCompressedTexImageARB);
+ 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_AreProgramsResidentNV(disp, glAreProgramsResidentNV);
+ SET_BindProgramNV(disp, glBindProgramNV);
+ SET_DeleteProgramsNV(disp, glDeleteProgramsNV);
+ SET_ExecuteProgramNV(disp, glExecuteProgramNV);
+ SET_GenProgramsNV(disp, glGenProgramsNV);
+ SET_GetProgramParameterdvNV(disp, glGetProgramParameterdvNV);
+ SET_GetProgramParameterfvNV(disp, glGetProgramParameterfvNV);
+ SET_GetProgramivNV(disp, glGetProgramivNV);
+ SET_GetProgramStringNV(disp, glGetProgramStringNV);
+ SET_GetTrackMatrixivNV(disp, glGetTrackMatrixivNV);
+ SET_GetVertexAttribdvARB(disp, glGetVertexAttribdvARB);
+ SET_GetVertexAttribfvARB(disp, glGetVertexAttribfvARB);
+ SET_GetVertexAttribivARB(disp, glGetVertexAttribivARB);
+ SET_GetVertexAttribPointervNV(disp, glGetVertexAttribPointervNV);
+ SET_IsProgramNV(disp, glIsProgramNV);
+ SET_LoadProgramNV(disp, glLoadProgramNV);
+ 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_RequestResidentProgramsNV(disp, glRequestResidentProgramsNV);
+ SET_TrackMatrixNV(disp, glTrackMatrixNV);
+ SET_VertexAttribPointerNV(disp, glVertexAttribPointerNV);
+ 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_VertexAttrib4dARB(disp, glVertexAttrib4dARB);
+ SET_VertexAttrib4dvARB(disp, glVertexAttrib4dvARB);
+ SET_VertexAttrib4fARB(disp, glVertexAttrib4fARB);
+ SET_VertexAttrib4fvARB(disp, glVertexAttrib4fvARB);
+ SET_VertexAttrib4sARB(disp, glVertexAttrib4sARB);
+ SET_VertexAttrib4svARB(disp, glVertexAttrib4svARB);
+ SET_VertexAttrib4NubARB(disp, glVertexAttrib4NubARB);
+ SET_VertexAttrib4NubvARB(disp, glVertexAttrib4NubvARB);
+ SET_VertexAttribs1dvNV(disp, glVertexAttribs1dvNV);
+ SET_VertexAttribs1fvNV(disp, glVertexAttribs1fvNV);
+ SET_VertexAttribs1svNV(disp, glVertexAttribs1svNV);
+ SET_VertexAttribs2dvNV(disp, glVertexAttribs2dvNV);
+ SET_VertexAttribs2fvNV(disp, glVertexAttribs2fvNV);
+ SET_VertexAttribs2svNV(disp, glVertexAttribs2svNV);
+ SET_VertexAttribs3dvNV(disp, glVertexAttribs3dvNV);
+ SET_VertexAttribs3fvNV(disp, glVertexAttribs3fvNV);
+ SET_VertexAttribs3svNV(disp, glVertexAttribs3svNV);
+ SET_VertexAttribs4dvNV(disp, glVertexAttribs4dvNV);
+ SET_VertexAttribs4fvNV(disp, glVertexAttribs4fvNV);
+ SET_VertexAttribs4svNV(disp, glVertexAttribs4svNV);
+ SET_VertexAttribs4ubvNV(disp, glVertexAttribs4ubvNV);
+ SET_PointParameteriNV(disp, glPointParameteriNV);
+ SET_PointParameterivNV(disp, glPointParameterivNV);
+ SET_MultiDrawArraysEXT(disp, glMultiDrawArraysEXT);
+ SET_MultiDrawElementsEXT(disp, glMultiDrawElementsEXT);
+ SET_ActiveStencilFaceEXT(disp, glActiveStencilFaceEXT);
+ SET_DeleteFencesNV(disp, glDeleteFencesNV);
+ SET_GenFencesNV(disp, glGenFencesNV);
+ SET_IsFenceNV(disp, glIsFenceNV);
+ SET_TestFenceNV(disp, glTestFenceNV);
+ SET_GetFenceivNV(disp, glGetFenceivNV);
+ SET_FinishFenceNV(disp, glFinishFenceNV);
+ SET_SetFenceNV(disp, glSetFenceNV);
+ SET_VertexAttrib4bvARB(disp, glVertexAttrib4bvARB);
+ SET_VertexAttrib4ivARB(disp, glVertexAttrib4ivARB);
+ SET_VertexAttrib4ubvARB(disp, glVertexAttrib4ubvARB);
+ SET_VertexAttrib4usvARB(disp, glVertexAttrib4usvARB);
+ SET_VertexAttrib4uivARB(disp, glVertexAttrib4uivARB);
+ SET_VertexAttrib4NbvARB(disp, glVertexAttrib4NbvARB);
+ SET_VertexAttrib4NsvARB(disp, glVertexAttrib4NsvARB);
+ SET_VertexAttrib4NivARB(disp, glVertexAttrib4NivARB);
+ SET_VertexAttrib4NusvARB(disp, glVertexAttrib4NusvARB);
+ SET_VertexAttrib4NuivARB(disp, glVertexAttrib4NuivARB);
+ SET_VertexAttribPointerARB(disp, glVertexAttribPointerARB);
+ SET_EnableVertexAttribArrayARB(disp, glEnableVertexAttribArrayARB);
+ SET_DisableVertexAttribArrayARB(disp, glDisableVertexAttribArrayARB);
+ SET_ProgramStringARB(disp, glProgramStringARB);
+ 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_GetProgramEnvParameterdvARB(disp, glGetProgramEnvParameterdvARB);
+ SET_GetProgramEnvParameterfvARB(disp, glGetProgramEnvParameterfvARB);
+ SET_GetProgramLocalParameterdvARB(disp, glGetProgramLocalParameterdvARB);
+ SET_GetProgramLocalParameterfvARB(disp, glGetProgramLocalParameterfvARB);
+ SET_GetProgramivARB(disp, glGetProgramivARB);
+ SET_GetProgramStringARB(disp, glGetProgramStringARB);
+ SET_ProgramNamedParameter4fNV(disp, glProgramNamedParameter4fNV);
+ SET_ProgramNamedParameter4dNV(disp, glProgramNamedParameter4dNV);
+ SET_ProgramNamedParameter4fvNV(disp, glProgramNamedParameter4fvNV);
+ SET_ProgramNamedParameter4dvNV(disp, glProgramNamedParameter4dvNV);
+ SET_GetProgramNamedParameterfvNV(disp, glGetProgramNamedParameterfvNV);
+ SET_GetProgramNamedParameterdvNV(disp, glGetProgramNamedParameterdvNV);
+ SET_BindBufferARB(disp, glBindBufferARB);
+ SET_BufferDataARB(disp, glBufferDataARB);
+ SET_BufferSubDataARB(disp, glBufferSubDataARB);
+ SET_DeleteBuffersARB(disp, glDeleteBuffersARB);
+ SET_GenBuffersARB(disp, glGenBuffersARB);
+ SET_GetBufferParameterivARB(disp, glGetBufferParameterivARB);
+ SET_GetBufferPointervARB(disp, glGetBufferPointervARB);
+ SET_GetBufferSubDataARB(disp, glGetBufferSubDataARB);
+ SET_IsBufferARB(disp, glIsBufferARB);
+ SET_MapBufferARB(disp, glMapBufferARB);
+ SET_UnmapBufferARB(disp, glUnmapBufferARB);
+ SET_DepthBoundsEXT(disp, glDepthBoundsEXT);
+ SET_GenQueriesARB(disp, glGenQueriesARB);
+ SET_DeleteQueriesARB(disp, glDeleteQueriesARB);
+ SET_IsQueryARB(disp, glIsQueryARB);
+ SET_BeginQueryARB(disp, glBeginQueryARB);
+ SET_EndQueryARB(disp, glEndQueryARB);
+ SET_GetQueryivARB(disp, glGetQueryivARB);
+ SET_GetQueryObjectivARB(disp, glGetQueryObjectivARB);
+ SET_GetQueryObjectuivARB(disp, glGetQueryObjectuivARB);
+ SET_MultiModeDrawArraysIBM(disp, glMultiModeDrawArraysIBM);
+ SET_MultiModeDrawElementsIBM(disp, glMultiModeDrawElementsIBM);
+ SET_BlendEquationSeparateEXT(disp, glBlendEquationSeparateEXT);
+ SET_DeleteObjectARB(disp, glDeleteObjectARB);
+ SET_GetHandleARB(disp, glGetHandleARB);
+ SET_DetachObjectARB(disp, glDetachObjectARB);
+ SET_CreateShaderObjectARB(disp, glCreateShaderObjectARB);
+ SET_ShaderSourceARB(disp, glShaderSourceARB);
+ SET_CompileShaderARB(disp, glCompileShaderARB);
+ SET_CreateProgramObjectARB(disp, glCreateProgramObjectARB);
+ SET_AttachObjectARB(disp, glAttachObjectARB);
+ SET_LinkProgramARB(disp, glLinkProgramARB);
+ SET_UseProgramObjectARB(disp, glUseProgramObjectARB);
+ SET_ValidateProgramARB(disp, glValidateProgramARB);
+ SET_Uniform1fARB(disp, glUniform1fARB);
+ SET_Uniform2fARB(disp, glUniform2fARB);
+ SET_Uniform3fARB(disp, glUniform3fARB);
+ SET_Uniform4fARB(disp, glUniform4fARB);
+ SET_Uniform1iARB(disp, glUniform1iARB);
+ SET_Uniform2iARB(disp, glUniform2iARB);
+ SET_Uniform3iARB(disp, glUniform3iARB);
+ SET_Uniform4iARB(disp, glUniform4iARB);
+ SET_Uniform1fvARB(disp, glUniform1fvARB);
+ SET_Uniform2fvARB(disp, glUniform2fvARB);
+ SET_Uniform3fvARB(disp, glUniform3fvARB);
+ SET_Uniform4fvARB(disp, glUniform4fvARB);
+ SET_Uniform1ivARB(disp, glUniform1ivARB);
+ SET_Uniform2ivARB(disp, glUniform2ivARB);
+ SET_Uniform3ivARB(disp, glUniform3ivARB);
+ SET_Uniform4ivARB(disp, glUniform4ivARB);
+ SET_UniformMatrix2fvARB(disp, glUniformMatrix2fvARB);
+ SET_UniformMatrix3fvARB(disp, glUniformMatrix3fvARB);
+ SET_UniformMatrix4fvARB(disp, glUniformMatrix4fvARB);
+ SET_GetObjectParameterfvARB(disp, glGetObjectParameterfvARB);
+ SET_GetObjectParameterivARB(disp, glGetObjectParameterivARB);
+ SET_GetInfoLogARB(disp, glGetInfoLogARB);
+ SET_GetAttachedObjectsARB(disp, glGetAttachedObjectsARB);
+ SET_GetUniformLocationARB(disp, glGetUniformLocationARB);
+ SET_GetActiveUniformARB(disp, glGetActiveUniformARB);
+ SET_GetUniformfvARB(disp, glGetUniformfvARB);
+ SET_GetUniformivARB(disp, glGetUniformivARB);
+ SET_GetShaderSourceARB(disp, glGetShaderSourceARB);
+ SET_BindAttribLocationARB(disp, glBindAttribLocationARB);
+ SET_GetActiveAttribARB(disp, glGetActiveAttribARB);
+ SET_GetAttribLocationARB(disp, glGetAttribLocationARB);
+ SET_GetVertexAttribdvNV(disp, glGetVertexAttribdvNV);
+ SET_GetVertexAttribfvNV(disp, glGetVertexAttribfvNV);
+ SET_GetVertexAttribivNV(disp, glGetVertexAttribivNV);
+ SET_VertexAttrib1dNV(disp, glVertexAttrib1dNV);
+ SET_VertexAttrib1dvNV(disp, glVertexAttrib1dvNV);
+ SET_VertexAttrib1fNV(disp, glVertexAttrib1fNV);
+ SET_VertexAttrib1fvNV(disp, glVertexAttrib1fvNV);
+ SET_VertexAttrib1sNV(disp, glVertexAttrib1sNV);
+ SET_VertexAttrib1svNV(disp, glVertexAttrib1svNV);
+ SET_VertexAttrib2dNV(disp, glVertexAttrib2dNV);
+ SET_VertexAttrib2dvNV(disp, glVertexAttrib2dvNV);
+ SET_VertexAttrib2fNV(disp, glVertexAttrib2fNV);
+ SET_VertexAttrib2fvNV(disp, glVertexAttrib2fvNV);
+ SET_VertexAttrib2sNV(disp, glVertexAttrib2sNV);
+ SET_VertexAttrib2svNV(disp, glVertexAttrib2svNV);
+ SET_VertexAttrib3dNV(disp, glVertexAttrib3dNV);
+ SET_VertexAttrib3dvNV(disp, glVertexAttrib3dvNV);
+ SET_VertexAttrib3fNV(disp, glVertexAttrib3fNV);
+ SET_VertexAttrib3fvNV(disp, glVertexAttrib3fvNV);
+ SET_VertexAttrib3sNV(disp, glVertexAttrib3sNV);
+ SET_VertexAttrib3svNV(disp, glVertexAttrib3svNV);
+ SET_VertexAttrib4dNV(disp, glVertexAttrib4dNV);
+ SET_VertexAttrib4dvNV(disp, glVertexAttrib4dvNV);
+ SET_VertexAttrib4fNV(disp, glVertexAttrib4fNV);
+ SET_VertexAttrib4fvNV(disp, glVertexAttrib4fvNV);
+ SET_VertexAttrib4sNV(disp, glVertexAttrib4sNV);
+ SET_VertexAttrib4svNV(disp, glVertexAttrib4svNV);
+ SET_VertexAttrib4ubNV(disp, glVertexAttrib4ubNV);
+ SET_VertexAttrib4ubvNV(disp, glVertexAttrib4ubvNV);
+ SET_GenFragmentShadersATI(disp, glGenFragmentShadersATI);
+ SET_BindFragmentShaderATI(disp, glBindFragmentShaderATI);
+ SET_DeleteFragmentShaderATI(disp, glDeleteFragmentShaderATI);
+ SET_BeginFragmentShaderATI(disp, glBeginFragmentShaderATI);
+ SET_EndFragmentShaderATI(disp, glEndFragmentShaderATI);
+ SET_PassTexCoordATI(disp, glPassTexCoordATI);
+ SET_SampleMapATI(disp, glSampleMapATI);
+ SET_ColorFragmentOp1ATI(disp, glColorFragmentOp1ATI);
+ SET_ColorFragmentOp2ATI(disp, glColorFragmentOp2ATI);
+ SET_ColorFragmentOp3ATI(disp, glColorFragmentOp3ATI);
+ SET_AlphaFragmentOp1ATI(disp, glAlphaFragmentOp1ATI);
+ SET_AlphaFragmentOp2ATI(disp, glAlphaFragmentOp2ATI);
+ SET_AlphaFragmentOp3ATI(disp, glAlphaFragmentOp3ATI);
+ SET_SetFragmentShaderConstantATI(disp, glSetFragmentShaderConstantATI);
+ SET_IsRenderbufferEXT(disp, glIsRenderbufferEXT);
+ SET_BindRenderbufferEXT(disp, glBindRenderbufferEXT);
+ SET_DeleteRenderbuffersEXT(disp, glDeleteRenderbuffersEXT);
+ SET_GenRenderbuffersEXT(disp, glGenRenderbuffersEXT);
+ SET_RenderbufferStorageEXT(disp, glRenderbufferStorageEXT);
+ SET_GetRenderbufferParameterivEXT(disp, glGetRenderbufferParameterivEXT);
+ SET_IsFramebufferEXT(disp, glIsFramebufferEXT);
+ SET_BindFramebufferEXT(disp, glBindFramebufferEXT);
+ SET_DeleteFramebuffersEXT(disp, glDeleteFramebuffersEXT);
+ SET_GenFramebuffersEXT(disp, glGenFramebuffersEXT);
+ SET_CheckFramebufferStatusEXT(disp, glCheckFramebufferStatusEXT);
+ SET_FramebufferTexture1DEXT(disp, glFramebufferTexture1DEXT);
+ SET_FramebufferTexture2DEXT(disp, glFramebufferTexture2DEXT);
+ SET_FramebufferTexture3DEXT(disp, glFramebufferTexture3DEXT);
+ SET_FramebufferRenderbufferEXT(disp, glFramebufferRenderbufferEXT);
+ SET_GetFramebufferAttachmentParameterivEXT(disp, glGetFramebufferAttachmentParameterivEXT);
+ SET_GenerateMipmapEXT(disp, glGenerateMipmapEXT);
+ SET_StencilFuncSeparate(disp, glStencilFuncSeparate);
+ SET_StencilOpSeparate(disp, glStencilOpSeparate);
+ SET_StencilMaskSeparate(disp, glStencilMaskSeparate);
+ SET_GetQueryObjecti64vEXT(disp, glGetQueryObjecti64vEXT);
+ SET_GetQueryObjectui64vEXT(disp, glGetQueryObjectui64vEXT);
+ SET_BlitFramebufferEXT(disp, glBlitFramebufferEXT); */
+
+}
diff-tree 43bd35fcf85b51b7e5714844bade90184dbd746f (from 2a35d44b6d87f96a7ce90dc8f0142f48cc176e95)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Thu Mar 1 17:19:37 2007 +1030

    dix:    Remove InitSprite, work can be done by InitializeSprite.
            Free sprite struct if a spriteOwner is paired.
    
    xfree86: Use PairDevices instead of passing booleans around when creating a
             sprite.
    
    Xext:    Switch back to using LookupPointer/KeyboardDevice instead of
             inputInfo.xyz.

diff --git a/Xext/xtest.c b/Xext/xtest.c
index d46d6e7..cb7b5b8 100644
--- a/Xext/xtest.c
+++ b/Xext/xtest.c
@@ -316,7 +316,7 @@ ProcXTestFakeInput(client)
 #ifdef XINPUT
 	if (!extension)
 #endif /* XINPUT */
-	    dev = inputInfo.keyboard;
+	    dev = (DeviceIntPtr)LookupKeyboardDevice();
 	if (ev->u.u.detail < dev->key->curKeySyms.minKeyCode ||
 	    ev->u.u.detail > dev->key->curKeySyms.maxKeyCode)
 	{
@@ -361,7 +361,7 @@ ProcXTestFakeInput(client)
 	}
 #endif /* XINPUT */
         if (!dev)
-            dev = inputInfo.pointer;
+            dev = (DeviceIntPtr*)LookupPointerDevice();
 	if (ev->u.keyButtonPointer.root == None)
 	    root = GetCurrentRootWindow();
 	else
@@ -427,7 +427,7 @@ ProcXTestFakeInput(client)
 #ifdef PANORAMIX
 	if ((!noPanoramiXExtension
 	     && root->drawable.pScreen->myNum 
-                != XineramaGetCursorScreen(inputInfo.pointer))
+                != XineramaGetCursorScreen(dev))
 	    || (noPanoramiXExtension && root != GetCurrentRootWindow()))
 
 #else
@@ -451,7 +451,7 @@ ProcXTestFakeInput(client)
 #ifdef XINPUT
 	if (!extension)
 #endif /* XINPUT */
-	    dev = inputInfo.pointer;
+            dev = (DeviceIntPtr*)LookupPointerDevice();
 	if (!ev->u.u.detail || ev->u.u.detail > dev->button->numButtons)
 	{
 	    client->errorValue = ev->u.u.detail;
diff --git a/autogen.sh b/autogen.sh
index 904cd67..1176abd 100755
--- a/autogen.sh
+++ b/autogen.sh
@@ -9,4 +9,4 @@ cd $srcdir
 autoreconf -v --install || exit 1
 cd $ORIGDIR || exit $?
 
-$srcdir/configure --enable-maintainer-mode "$@"
+$srcdir/configure --enable-maintainer-mode --disable-dmx "$@"
diff --git a/dix/devices.c b/dix/devices.c
index ad5cd50..747d782 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -1937,14 +1937,21 @@ ProcQueryKeymap(ClientPtr client)
  * pointer sprite. 
  */
 int 
-PairDevices(ClientPtr client, DeviceIntPtr pointer, DeviceIntPtr keyboard)
+PairDevices(ClientPtr client, DeviceIntPtr ptr, DeviceIntPtr kbd)
 {
     if (!pairingClient)
         RegisterPairingClient(client);
     else if (pairingClient != client)
         return BadAccess;
 
-    keyboard->pSprite = pointer->pSprite;
+    if (kbd->spriteOwner)
+    {
+        xfree(kbd->pSprite);
+        kbd->pSprite = NULL;
+        kbd->spriteOwner = FALSE;
+    }
+
+    kbd->pSprite = ptr->pSprite;
     return Success;
 }
 
diff --git a/dix/events.c b/dix/events.c
index 5ea9a65..a1e72f1 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -240,7 +240,6 @@ static WindowPtr *spriteTrace = (WindowP
 static int spriteTraceSize = 0;
 static int spriteTraceGood;
 
-
 /** 
  * True if device owns a cursor, false if device shares a cursor sprite with
  * another device.
@@ -2212,8 +2211,16 @@ void 
 InitializeSprite(DeviceIntPtr pDev, WindowPtr pWin)
 {
     SpritePtr pSprite;
-    ScreenPtr pScreen = pWin->drawable.pScreen;
+    ScreenPtr pScreen; 
+
+    if (!pDev->pSprite)
+    {
+        pDev->pSprite = (SpritePtr)xcalloc(1, sizeof(SpriteRec));
+        if (!pDev->pSprite)
+            FatalError("InitializeSprite: failed to allocate sprite struct");
+    }
 
+    pScreen = (pWin) ? pWin->drawable.pScreen : (ScreenPtr)NULL;
     pSprite = pDev->pSprite;
     pSprite->hotPhys.pScreen = pScreen;
     pSprite->hotPhys.x = pScreen->width / 2;
@@ -2222,8 +2229,12 @@ InitializeSprite(DeviceIntPtr pDev, Wind
     pSprite->hotLimits.x2 = pScreen->width;
     pSprite->hotLimits.y2 = pScreen->height;
     pSprite->win = pWin;
-    pSprite->current = wCursor (pWin);
-    pSprite->current->refcnt++;
+    if (pWin)
+    {
+        pSprite->current = wCursor(pWin);
+        pSprite->current->refcnt++;
+    } else
+        pSprite->current = NullCursor;
 
     (*pScreen->CursorLimits) ( pDev, pScreen, pSprite->current,
                                &pSprite->hotLimits, &pSprite->physLimits);
@@ -2252,6 +2263,8 @@ InitializeSprite(DeviceIntPtr pDev, Wind
         REGION_NULL(pScreen, &pSprite->Reg2);
     }
 #endif
+
+    pDev->spriteOwner = TRUE;
 }
 
 /*
diff --git a/hw/xfree86/common/xf86Xinput.c b/hw/xfree86/common/xf86Xinput.c
index 608fa9b..41118c0 100644
--- a/hw/xfree86/common/xf86Xinput.c
+++ b/hw/xfree86/common/xf86Xinput.c
@@ -187,7 +187,11 @@ xf86ActivateDevice(LocalDevicePtr local)
 #endif
 
         /* Only create a new sprite if it's a non-shared pointer */
-        InitSprite(dev, IsPointerDevice(dev) && dev->isMPDev);
+        if (IsPointerDevice(dev) && dev->isMPDev)
+            InitializeSprite(pDev, NullWindow);
+        else 
+            PairDevices(pairingClient, inputInfo.pointer, pDev);
+
         RegisterOtherDevice(dev);
 
         if (serverGeneration == 1) 
diff --git a/hw/xfree86/os-support/linux/lnx_agp.c b/hw/xfree86/os-support/linux/lnx_agp.c
index ded9e0f..300b08d 100644
--- a/hw/xfree86/os-support/linux/lnx_agp.c
+++ b/hw/xfree86/os-support/linux/lnx_agp.c
@@ -10,6 +10,7 @@
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
+#include <linux/types.h>
 #endif
 
 #include <X11/X.h>
diff --git a/include/inputstr.h b/include/inputstr.h
index c4a2d18..90a985b 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -355,7 +355,7 @@ typedef struct _DeviceIntRec {
     int			nPrivates;
     DeviceUnwrapProc    unwrapProc;
     Bool                isMPDev;           /* TRUE if multipointer device */
-    /* Each devices has a sprite. However, keyboards and shared pointers do
+    /* Each device has a sprite. However, keyboards and shared pointers do
        not in fact own a sprite but rather have their pointer set to the
        sprite of another device. pSprite always has to point to a valid
        sprite. spriteOwner indicates whether it is the device's sprite. */
diff-tree 90ca76ba28fcd8bed945e33cf9674784fa2eb533 (from 06c3021aec720837bef432656e88ae9b4e35101d)
Author: Jay Cotton <jay.cotton at sun.com>
Date:   Wed Feb 28 17:40:58 2007 -0800

    Add sun_apm.c for Suspend-and-Resume support on Solaris
    
    <http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=6205248>

diff --git a/hw/xfree86/os-support/solaris/Makefile.am b/hw/xfree86/os-support/solaris/Makefile.am
index 57ec89e..d01e2e6 100644
--- a/hw/xfree86/os-support/solaris/Makefile.am
+++ b/hw/xfree86/os-support/solaris/Makefile.am
@@ -19,9 +19,9 @@ solaris-$(SOLARIS_INOUT_ARCH).il: solari
 
 noinst_LTLIBRARIES = libsolaris.la
 libsolaris_la_SOURCES = sun_bios.c sun_init.c \
-	sun_mouse.c sun_vid.c sun_bell.c $(AGP_SRC) \
+	sun_mouse.c sun_vid.c sun_bell.c $(AGP_SRC) sun_apm.c \
 	$(srcdir)/../shared/libc_wrapper.c \
-	$(srcdir)/../shared/kmod_noop.c $(srcdir)/../shared/pm_noop.c \
+	$(srcdir)/../shared/kmod_noop.c \
 	$(srcdir)/../shared/posix_tty.c $(srcdir)/../shared/sigiostubs.c \
 	$(srcdir)/../shared/stdPci.c $(srcdir)/../shared/stdResource.c \
 	$(VTSW_SRC)
diff --git a/hw/xfree86/os-support/solaris/sun_apm.c b/hw/xfree86/os-support/solaris/sun_apm.c
new file mode 100644
index 0000000..a9657fd
--- /dev/null
+++ b/hw/xfree86/os-support/solaris/sun_apm.c
@@ -0,0 +1,232 @@
+/* Based on hw/xfree86/os-support/bsd/bsd_apm.c which bore no explicit
+ * copyright notice, so is covered by the following notice:
+ *
+ * Copyright (C) 1994-2003 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.
+ */
+
+/* Copyright 2005 Sun Microsystems, 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, and/or sell copies of the Software, and to permit persons
+ * to whom the Software is furnished to do so, provided that the above
+ * copyright notice(s) and this permission notice appear in all copies of
+ * the Software and that both the above copyright notice(s) and this
+ * permission notice appear in supporting documentation.
+ *
+ * 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
+ * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+ * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR 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.
+ *
+ * Except as contained in this notice, the name of a copyright holder
+ * shall not be used in advertising or otherwise to promote the sale, use
+ * or other dealings in this Software without prior written authorization
+ * of the copyright holder.
+ */
+
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#include <X11/X.h>
+#include "os.h"
+#include "xf86.h"
+#include "xf86Priv.h"
+#define XF86_OS_PRIVS
+#include "xf86_OSproc.h"
+#include "xf86_OSlib.h"
+
+#ifndef PLEASE_FIX_THIS
+#define APM_STANDBY_REQ 0xa01
+#define APM_SUSPEND_REQ 0xa02
+#define APM_NORMAL_RESUME 0xa03
+#define APM_CRIT_RESUME 0xa04
+#define APM_BATTERY_LOW 0xa05
+#define APM_POWER_CHANGE 0xa06
+#define APM_UPDATE_TIME 0xa07
+#define APM_CRIT_SUSPEND_REQ 0xa08
+#define APM_USER_STANDBY_REQ 0xa09
+#define APM_USER_SUSPEND_REQ 0xa0a
+#define APM_SYS_STANDBY_RESUME 0xa0b
+#define APM_IOC_NEXTEVENT 0xa0c
+#define APM_IOC_RESUME 0xa0d
+#define APM_IOC_SUSPEND 0xa0e
+#define APM_IOC_STANDBY 0xa0f
+#endif
+
+typedef struct apm_event_info 
+{
+	int	type;
+} apm_event_info;
+
+/*
+ This may be replaced with a better device name
+ very soon...
+*/
+#define APM_DEVICE "/dev/srn"
+#define APM_DEVICE1 "/dev/apm"
+
+static pointer APMihPtr = NULL;
+static void sunCloseAPM(void);
+
+static struct {
+    u_int apmBsd;
+    pmEvent xf86;
+} sunToXF86Array [] = {
+    { APM_STANDBY_REQ, XF86_APM_SYS_STANDBY },
+    { APM_SUSPEND_REQ, XF86_APM_SYS_SUSPEND },
+    { APM_NORMAL_RESUME, XF86_APM_NORMAL_RESUME },
+    { APM_CRIT_RESUME, XF86_APM_CRITICAL_RESUME },
+    { APM_BATTERY_LOW, XF86_APM_LOW_BATTERY },
+    { APM_POWER_CHANGE, XF86_APM_POWER_STATUS_CHANGE },
+    { APM_UPDATE_TIME, XF86_APM_UPDATE_TIME },
+    { APM_CRIT_SUSPEND_REQ, XF86_APM_CRITICAL_SUSPEND },
+    { APM_USER_STANDBY_REQ, XF86_APM_USER_STANDBY },
+    { APM_USER_SUSPEND_REQ, XF86_APM_USER_SUSPEND },
+    { APM_SYS_STANDBY_RESUME, XF86_APM_STANDBY_RESUME },
+#ifdef APM_CAPABILITY_CHANGE
+    { APM_CAPABILITY_CHANGE, XF86_APM_CAPABILITY_CHANGED },
+#endif
+};
+
+#define numApmEvents (sizeof(sunToXF86Array) / sizeof(sunToXF86Array[0]))
+
+static pmEvent
+sunToXF86(int type)
+{
+    int i;
+
+    for (i = 0; i < numApmEvents; i++) {
+	if (type == sunToXF86Array[i].apmBsd) {
+	    return sunToXF86Array[i].xf86;
+	}
+    }
+    return XF86_APM_UNKNOWN;
+}
+
+/*
+ * APM events can be requested direclty from /dev/apm 
+ */
+static int 
+sunPMGetEventFromOS(int fd, pmEvent *events, int num)
+{
+    struct apm_event_info sunEvent;
+    int i;
+
+    for (i = 0; i < num; i++) {
+	
+	if (ioctl(fd, APM_IOC_NEXTEVENT, &sunEvent) < 0) {
+	    if (errno != EAGAIN) {
+		xf86Msg(X_WARNING, "sunPMGetEventFromOS: APM_IOC_NEXTEVENT"
+			" errno = %d\n", errno);
+	    }
+	    break;
+	}
+	events[i] = sunToXF86(sunEvent.type);
+    }
+    xf86Msg(X_WARNING, "Got some events\n");
+    return i;
+}
+
+static pmWait
+sunPMConfirmEventToOs(int fd, pmEvent event)
+{
+    switch (event) {
+/* XXX: NOT CURRENTLY RETURNED FROM OS */
+      case XF86_APM_SYS_STANDBY:
+      case XF86_APM_USER_STANDBY:
+        if (ioctl( fd, APM_IOC_STANDBY, NULL ) == 0)
+            return PM_WAIT;  /* should we stop the Xserver in standby, too? */
+        else
+            return PM_NONE;
+      case XF86_APM_SYS_SUSPEND:
+      case XF86_APM_CRITICAL_SUSPEND:
+      case XF86_APM_USER_SUSPEND:
+	    xf86Msg(X_WARNING, "Got SUSPENDED\n");
+        if (ioctl( fd, APM_IOC_SUSPEND, NULL ) == 0)
+            return PM_CONTINUE;
+        else {
+	    xf86Msg(X_WARNING, "sunPMConfirmEventToOs: APM_IOC_SUSPEND"
+		" errno = %d\n", errno);
+            return PM_FAILED;
+	}
+      case XF86_APM_STANDBY_RESUME:
+      case XF86_APM_NORMAL_RESUME:
+      case XF86_APM_CRITICAL_RESUME:
+      case XF86_APM_STANDBY_FAILED:
+      case XF86_APM_SUSPEND_FAILED:
+	    xf86Msg(X_WARNING, "Got RESUME\n");
+        if (ioctl( fd, APM_IOC_RESUME, NULL ) == 0)
+            return PM_CONTINUE;
+        else {
+	    xf86Msg(X_WARNING, "sunPMConfirmEventToOs: APM_IOC_RESUME"
+		" errno = %d\n", errno);
+            return PM_FAILED;
+	}
+      default:
+	return PM_NONE;
+    }
+}
+
+PMClose
+xf86OSPMOpen(void)
+{
+    int fd;
+
+    if (APMihPtr || !xf86Info.pmFlag) {
+	return NULL;
+    }
+
+    if ((fd = open(APM_DEVICE, O_RDWR)) == -1) {
+    	if ((fd = open(APM_DEVICE1, O_RDWR)) == -1) {
+		return NULL;
+	}
+    }
+    xf86PMGetEventFromOs = sunPMGetEventFromOS;
+    xf86PMConfirmEventToOs = sunPMConfirmEventToOs;
+    APMihPtr = xf86AddInputHandler(fd, xf86HandlePMEvents, NULL);
+    return sunCloseAPM;
+}
+
+static void
+sunCloseAPM(void)
+{
+    int fd;
+
+    if (APMihPtr) {
+	fd = xf86RemoveInputHandler(APMihPtr);
+	close(fd);
+	APMihPtr = NULL;
+    }
+}
diff-tree 06c3021aec720837bef432656e88ae9b4e35101d (from 68c64ad7b1eea79c786b5a7f3459076780163a47)
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Wed Feb 28 16:09:11 2007 -0800

    Don't crash setting a NULL mode with a randr classic DDX. Also remember to update the screen size during modesets.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 474c946..1f7462f 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -290,6 +290,12 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	    RRScreenRate	    rate;
 	    Bool		    ret;
 
+	    if (!mode)
+	    {
+		RRCrtcNotify (crtc, NULL, x, y, rotation, 0, NULL);
+		return TRUE;
+	    }
+
 	    size.width = mode->mode.width;
 	    size.height = mode->mode.height;
 	    if (outputs[0]->mmWidth && outputs[0]->mmHeight)
@@ -310,7 +316,10 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	     * Old 1.0 interface tied screen size to mode size
 	     */
 	    if (ret)
+	    {
 		RRCrtcNotify (crtc, mode, x, y, rotation, 1, outputs);
+		RRScreenSizeNotify (pScreen);
+	    }
 	    return ret;
 	}
 #endif
diff-tree 68c64ad7b1eea79c786b5a7f3459076780163a47 (from 8b245758845523d5f8f017bb9d0e9aa57b616c28)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Thu Mar 1 09:51:20 2007 +1030

    Xext: Update device's lastx/lasty when sending a motion event with XTest.

diff --git a/Xext/xtest.c b/Xext/xtest.c
index c9b511e..94d8974 100644
--- a/Xext/xtest.c
+++ b/Xext/xtest.c
@@ -441,6 +441,8 @@ ProcXTestFakeInput(client)
 	    (root->drawable.pScreen,
 	     ev->u.keyButtonPointer.rootX,
 	     ev->u.keyButtonPointer.rootY, FALSE);
+        dev->valuator->lastx = ev->u.keyButtonPointer.rootX;
+        dev->valuator->lasty = ev->u.keyButtonPointer.rootY;
 	break;
     case ButtonPress:
     case ButtonRelease:
diff-tree 8b245758845523d5f8f017bb9d0e9aa57b616c28 (from d9bcb22d199e8444b9762a35754e04d327dd5915)
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Mon Feb 26 17:45:40 2007 -0800

    Return BadMatch if a client tries to clone non-cloneable outputs.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index fdd1d42..474c946 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -667,6 +667,27 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	    return BadMatch;
 	}
     }
+    /* validate clones */
+    for (i = 0; i < numOutputs; i++)
+    {
+	for (j = 0; j < numOutputs; j++)
+	{
+	    int k;
+	    if (i == j)
+		continue;
+	    for (k = 0; k < outputs[i]->numClones; k++)
+	    {
+		if (outputs[i]->clones[k] == outputs[j])
+		    break;
+	    }
+	    if (k == outputs[i]->numClones)
+	    {
+		if (outputs)
+		    xfree (outputs);
+		return BadMatch;
+	    }
+	}
+    }
 
     pScreen = crtc->pScreen;
     pScrPriv = rrGetScrPriv(pScreen);
diff-tree 2a35d44b6d87f96a7ce90dc8f0142f48cc176e95 (from bc4ae25433e38a25a2012f9f233d500665172a4b)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Wed Feb 28 15:43:06 2007 +1030

    Update device valuators on XTest motion event, otherwise the cursor jumps
    between coordinates stored in device and coordinates sent by the event.

diff --git a/Xext/xtest.c b/Xext/xtest.c
index c59adea..d46d6e7 100644
--- a/Xext/xtest.c
+++ b/Xext/xtest.c
@@ -316,7 +316,7 @@ ProcXTestFakeInput(client)
 #ifdef XINPUT
 	if (!extension)
 #endif /* XINPUT */
-	    dev = (DeviceIntPtr)LookupKeyboardDevice();
+	    dev = inputInfo.keyboard;
 	if (ev->u.u.detail < dev->key->curKeySyms.minKeyCode ||
 	    ev->u.u.detail > dev->key->curKeySyms.maxKeyCode)
 	{
@@ -360,7 +360,8 @@ ProcXTestFakeInput(client)
 	    break;
 	}
 #endif /* XINPUT */
-	dev = (DeviceIntPtr)LookupPointerDevice();
+        if (!dev)
+            dev = inputInfo.pointer;
 	if (ev->u.keyButtonPointer.root == None)
 	    root = GetCurrentRootWindow();
 	else
@@ -378,7 +379,7 @@ ProcXTestFakeInput(client)
 	if (ev->u.u.detail == xTrue)
 	{
 	    int x, y;
-	    GetSpritePosition(inputInfo.pointer, &x, &y);
+	    GetSpritePosition(dev, &x, &y);
 	    ev->u.keyButtonPointer.rootX += x;
 	    ev->u.keyButtonPointer.rootY += y;
 	}
@@ -442,13 +443,15 @@ ProcXTestFakeInput(client)
 	    (dev, root->drawable.pScreen,
 	     ev->u.keyButtonPointer.rootX,
 	     ev->u.keyButtonPointer.rootY, FALSE);
+        dev->valuator->lastx = ev->u.keyButtonPointer.rootX;
+        dev->valuator->lasty = ev->u.keyButtonPointer.rootY;
 	break;
     case ButtonPress:
     case ButtonRelease:
 #ifdef XINPUT
 	if (!extension)
 #endif /* XINPUT */
-	    dev = (DeviceIntPtr)LookupPointerDevice();
+	    dev = inputInfo.pointer;
 	if (!ev->u.u.detail || ev->u.u.detail > dev->button->numButtons)
 	{
 	    client->errorValue = ev->u.u.detail;
diff-tree d9bcb22d199e8444b9762a35754e04d327dd5915 (from parents)
Merge: 272d9341d0f7c3e9e0c9b9a8c0d4d8779cdcc5cf c16343ac2ca18391b21022b2edd02ad9f413d2b3
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Tue Feb 27 16:28:20 2007 -0800

    Merge branch 'master' of git+ssh://bbyer@git.freedesktop.org/git/xorg/xserver

diff-tree 272d9341d0f7c3e9e0c9b9a8c0d4d8779cdcc5cf (from ab0fc8c1ad7ea2dc3389a4a4bb1c45bbded5e7ad)
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Tue Feb 27 16:27:26 2007 -0800

    fix for hw/darwin/Makefile.am to properly use XSERVER_LIBS

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 22b396e..9b4628e 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -85,7 +85,7 @@ XDarwin_LDADD = \
 		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
 		$(top_builddir)/miext/rootless/accel/librlAccel.la \
 		@XORG_LIBS@ \
-		-lXau -lXdmcp -lXfont -lfreetype
+		$(XSERVER_LIBS)
 
 Xquartz_LDADD = \
 		$(top_builddir)/dix/dixfonts.lo \
@@ -112,7 +112,7 @@ Xquartz_LDADD = \
 		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
 		$(top_builddir)/miext/rootless/accel/librlAccel.la \
 		@XORG_LIBS@ \
-		-lXau -lXdmcp -lXfont -lfreetype -lXplugin
+		$(XSERVER_LIBS) -lXplugin
 
 XDarwin_LDFLAGS =  \
                  -XCClinker -Objc \
@@ -175,7 +175,7 @@ XDarwinApp_LDADD = \
 		 $(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
 		 $(top_builddir)/miext/rootless/accel/librlAccel.la \
 		 @XORG_LIBS@ \
-		 -lXau -lXdmcp -lXfont -lfreetype \
+		 $(XSERVER_LIBS) \
 		 $(top_builddir)/fb/libfb.la 
 
 XDarwinApp_LDFLAGS =  \
diff-tree c16343ac2ca18391b21022b2edd02ad9f413d2b3 (from 5680efc0d2baf0a9451e82e490e3690fc23dda0f)
Author: Eamon Walsh <ewalsh at tycho.nsa.gov>
Date:   Tue Feb 27 14:14:47 2007 -0500

    Make mfb, cfb, and afb support configurable at build-time.

diff --git a/configure.ac b/configure.ac
index 3260855..9cefc2a 100644
--- a/configure.ac
+++ b/configure.ac
@@ -540,6 +540,10 @@ AC_ARG_ENABLE(xprint,         AS_HELP_ST
 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])
 AC_ARG_ENABLE(xegl,           AS_HELP_STRING([--enable-xegl], [Build Xegl xgl module (default: no)]), [XEGL=$enableval], [XEGL=no])
+dnl legacy fb support
+AC_ARG_ENABLE(mfb,            AS_HELP_STRING([--enable-mfb], [Build legacy mono framebuffer support (default: enabled)]), [MFB=$enableval], [MFB=$XORG])
+AC_ARG_ENABLE(cfb,            AS_HELP_STRING([--enable-cfb], [Build legacy color framebuffer support (default: enabled)]), [CFB=$enableval], [CFB=$XORG])
+AC_ARG_ENABLE(afb,            AS_HELP_STRING([--enable-afb], [Build legacy advanced framebuffer support (default: enabled)]), [AFB=$enableval], [AFB=$XORG])
 dnl kdrive and its subsystems
 AC_ARG_ENABLE(kdrive,         AS_HELP_STRING([--enable-kdrive], [Build kdrive servers (default: no)]), [KDRIVE=$enableval], [KDRIVE=no])
 AC_ARG_ENABLE(xephyr,         AS_HELP_STRING([--enable-xephyr], [Build the kdrive Xephyr server (default: auto)]), [XEPHYR=$enableval], [XEPHYR=auto])
@@ -1561,13 +1565,20 @@ AM_CONDITIONAL([LINUX_ALPHA], [test "x$l
 AM_CONDITIONAL([LNXACPI], [test "x$linux_acpi" = xyes])
 AM_CONDITIONAL([SOLARIS_USL_CONSOLE], [test "x$solaris_usl_console" = xyes])
 AM_CONDITIONAL([SOLARIS_ASM_INLINE], [test "x$solaris_asm_inline" = xyes])
-AM_CONDITIONAL(MFB, [test "x$XORG" = xyes])
-AM_CONDITIONAL(CFB, [test "x$XORG" = xyes])
-AM_CONDITIONAL(AFB, [test "x$XORG" = xyes])
 AM_CONDITIONAL([BUILD_DARWIN],[test "X$build_darwin" = Xyes])
 AM_CONDITIONAL([XQUARTZ],[test "X$XQUARTZ" = Xyes])
 AM_CONDITIONAL(DGA, [test "x$DGA" = xyes])
 
+dnl legacy fb support
+AM_CONDITIONAL(MFB, [test "x$MFB" = xyes])
+AM_CONDITIONAL(CFB, [test "x$CFB" = xyes])
+AM_CONDITIONAL(AFB, [test "x$AFB" = xyes])
+if test "x$MFB" = xyes -o "x$CFB" = xyes -o "x$AFB" = xyes; then
+	if test "x$XORG" != xyes; then
+		AC_MSG_ERROR([legacy fb support requires the Xorg server])
+	fi
+fi
+
 dnl Xprint DDX
 
 AC_MSG_CHECKING([whether to build Xprint DDX])
diff --git a/hw/xfree86/Makefile.am b/hw/xfree86/Makefile.am
index 1a286d6..b669063 100644
--- a/hw/xfree86/Makefile.am
+++ b/hw/xfree86/Makefile.am
@@ -8,11 +8,19 @@ if XF86UTILS
 XF86UTILS_SUBDIR = utils
 endif
 
+if MFB
+MFB_SUBDIR = xf1bpp xf4bpp
+endif
+
+if CFB
+CFB_SUBDIR = xf8_16bpp xf8_32bpp
+endif
+
 DOC_SUBDIR = doc
 
 SUBDIRS = common ddc dummylib i2c x86emu int10 fbdevhw os-support parser rac \
-          ramdac shadowfb vbe vgahw xaa xf1bpp xf4bpp xf8_16bpp \
-	  xf8_32bpp loader scanpci dixmods exa modes \
+	  ramdac shadowfb vbe vgahw xaa $(MFB_SUBDIR) $(CFB_SUBDIR) \
+	  loader scanpci dixmods exa modes \
 	  $(DRI_SUBDIR) $(XF86UTILS_SUBDIR) $(DOC_SUBDIR)
 
 DIST_SUBDIRS = common ddc dummylib i2c x86emu int10 fbdevhw os-support \
diff --git a/hw/xfree86/dixmods/Makefile.am b/hw/xfree86/dixmods/Makefile.am
index c34ddd6..58099bc 100644
--- a/hw/xfree86/dixmods/Makefile.am
+++ b/hw/xfree86/dixmods/Makefile.am
@@ -14,12 +14,23 @@ if DBE
 DBEMOD = libdbe.la
 endif
 
-module_LTLIBRARIES = libafb.la \
-                     libcfb.la \
-                     libcfb32.la \
+if AFB
+AFBMOD = libafb.la
+endif
+
+if CFB
+CFBMOD = libcfb.la libcfb32.la
+endif
+
+if MFB
+MFBMOD = libmfb.la
+endif
+
+module_LTLIBRARIES = $(AFBMOD) \
+                     $(CFBMOD) \
                      libfb.la \
                      libwfb.la \
-                     libmfb.la \
+                     $(MFBMOD) \
                      libshadow.la
 
 extsmoduledir = $(moduledir)/extensions
diff-tree 5680efc0d2baf0a9451e82e490e3690fc23dda0f (from ab0fc8c1ad7ea2dc3389a4a4bb1c45bbded5e7ad)
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Tue Feb 27 09:55:48 2007 -0800

    Sun bug 6529003: Xorg should not be including <sys/immu.h> on Solaris
    
    <sys/immu.h> was removed from the latest Solaris Nevada build, but it's
    been useless to Xorg for a long time (it only declared a couple of kernel
    variables)
    <http://bugs.opensolaris.org/view_bug.do?bug_id=6529003>

diff --git a/hw/xfree86/os-support/xf86_OSlib.h b/hw/xfree86/os-support/xf86_OSlib.h
index 97f8723..27f766d 100644
--- a/hw/xfree86/os-support/xf86_OSlib.h
+++ b/hw/xfree86/os-support/xf86_OSlib.h
@@ -130,8 +130,8 @@ typedef signed long xf86ssize_t;
 # include <errno.h>
 
 # if defined(_NEED_SYSI86)
-#  include <sys/immu.h>
 #  if !(defined (sun) && defined (SVR4))
+#    include <sys/immu.h>
 #    include <sys/region.h>
 #  endif
 #  include <sys/proc.h>
diff-tree ab0fc8c1ad7ea2dc3389a4a4bb1c45bbded5e7ad (from cdd4c84572cc3bdd004f8dca6d8b64e710344ac0)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Tue Feb 27 00:14:35 2007 -0800

    verbiage corrected per daniels

diff --git a/hw/darwin/README.apple b/hw/darwin/README.apple
index 0977ce9..68bc692 100644
--- a/hw/darwin/README.apple
+++ b/hw/darwin/README.apple
@@ -1,5 +1,5 @@
-This repository contains patches to the modular X.org server code to allow
-it to be compiled on Darwin/OS X; this would not have been possible
+This directory contains a port of the XDarwin code to the modular X.org
+codebase to be compiled on Darwin/OS X; this would not have been possible
 without the help of Torrey Lyons and Peter O'Gorman, to whom I am
 grateful for their patches, time and moral support.
 
diff-tree cdd4c84572cc3bdd004f8dca6d8b64e710344ac0 (from 776d4d6587c57f94bca8732f915d07a0d4e137c8)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Mon Feb 26 23:57:02 2007 -0800

    added hw/darwin/README.apple file with some todo items and props.

diff --git a/hw/darwin/README.apple b/hw/darwin/README.apple
new file mode 100644
index 0000000..0977ce9
--- /dev/null
+++ b/hw/darwin/README.apple
@@ -0,0 +1,41 @@
+This repository contains patches to the modular X.org server code to allow
+it to be compiled on Darwin/OS X; this would not have been possible
+without the help of Torrey Lyons and Peter O'Gorman, to whom I am
+grateful for their patches, time and moral support.
+
+The server builds 4 targets:
+
+* XDarwin: this server runs on Darwin systems without Quartz
+  (i.e. non-OS X); it has not been well-tested.
+
+* XDarwinApp: this builds XDarwin.app, which is a full X server using
+  Quartz.  It has loadable module support for AGL and CGL, and well as
+  fullscreen and rootless support.
+
+* Xquartz: this server runs on Quartz-based systems, and is meant to
+  work with X11.app
+
+* x11app: this builds a version of Apple's X11.app using patches by
+  Torrey Lyons; most, but not all, functionality of Apple's original
+  X11.app is present in this release.
+
+Known issues:
+
+* AGL and CGL support for 3D indirect acceleration does not work;
+  indirect.c needs to be rewritten.
+
+* Fullscreen mode does not work; I don't know why.
+
+* The keyboard and mouse do not work at all; they worked in X11R7.1,
+  and I believe that they were broken by the events changes in dix/.
+
+* Some features in X11.app are not yet implemented; these are marked
+  with #ifdef DARWIN_DDX_MISSING in the code.
+
+* The build system code could probably be cleaned up slightly.
+
+* Most testing of this code has occurred under 10.5, but it should
+  also work under 10.4.
+
+Any patches or code contributions would be most welcome and may be
+sent to me at bbyer at apple.com.
diff-tree 776d4d6587c57f94bca8732f915d07a0d4e137c8 (from 154d2c13f4ec22b7e6332808bbcd049d63784891)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Mon Feb 26 23:40:00 2007 -0800

    X11.app now builds correctly

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 3133eaa..22b396e 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -37,7 +37,7 @@ Xquartz_SOURCES = \
                   $(top_srcdir)/Xi/stubs.c \
                   apple/X11Application.m \
                   apple/X11Controller.m \
-                  quartz/XServer.m \
+                  quartz/Xserver.m \
                   quartz/Preferences.m \
                   quartz/applewm.c \
                   quartz/keysym2ucs.c \
@@ -90,6 +90,7 @@ XDarwin_LDADD = \
 Xquartz_LDADD = \
 		$(top_builddir)/dix/dixfonts.lo \
 		$(top_builddir)/dix/libdix.la \
+		$(top_builddir)/config/libconfig.a \
 		$(top_builddir)/os/libos.la \
 		./libdarwinShared.a \
 		$(top_builddir)/dix/libxpstubs.la \
@@ -122,7 +123,7 @@ Xquartz_LDFLAGS =  \
                  -XCClinker -Objc \
                  -Wl,-u,_miDCInitialize \
                  -Wl,-framework,Carbon \
-                 -Wl,-framework,ApplicationServices \
+                 -Wl,-framework,OpenGL \
                  -Wl,-framework,Cocoa \
                  -Wl,-framework,CoreAudio \
                  -Wl,-framework,IOKit
diff --git a/hw/darwin/quartz/quartzStartup.c b/hw/darwin/quartz/quartzStartup.c
index ae156f8..76392e4 100644
--- a/hw/darwin/quartz/quartzStartup.c
+++ b/hw/darwin/quartz/quartzStartup.c
@@ -42,10 +42,12 @@
 char **envpGlobal;      // argcGlobal and argvGlobal
                         // are from dix/globals.c
 
-#ifdef INX11APP
+#ifdef INXQUARTZ
 void X11ControllerMain(int argc, char *argv[], void (*server_thread) (void *), void *server_arg);
+# ifdef GLXEXT
 void GlxExtensionInit(void);
 void GlxWrapInitVisuals(miInitVisualsProcPtr *);
+# endif
 
 static void server_thread (void *arg) {
   extern int main (int argc, char **argv, char **envp);
@@ -53,19 +55,18 @@ static void server_thread (void *arg) {
 }
 #else
 int NSApplicationMain(int argc, char *argv[]);
+typedef Bool (*QuartzModeBundleInitPtr)(void);
 
+# ifdef GLXEXT
 // GLX bundle function pointers
 typedef void (*GlxExtensionInitPtr)(void); 
 static GlxExtensionInitPtr GlxExtensionInit = NULL;
-
 typedef void (*GlxWrapInitVisualsPtr)(miInitVisualsProcPtr *);
 static GlxWrapInitVisualsPtr GlxWrapInitVisuals = NULL;
-
-typedef Bool (*QuartzModeBundleInitPtr)(void);
-
 void * __DarwinglXMesaProvider = NULL;
 typedef void (*GlxPushProviderPtr)(void *);
 GlxPushProviderPtr GlxPushProvider = NULL;
+# endif
 #endif
 
 /*
@@ -123,7 +124,7 @@ void DarwinHandleGUI(
         }
     }
 
-#ifdef INX11APP
+#ifdef INXQUARTZ
     /* 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
@@ -143,7 +144,7 @@ void DarwinHandleGUI(
     exit(main_exit);
 }
 
-#ifndef INX11APP
+#ifndef INXQUARTZ
 /*
  * QuartzLoadDisplayBundle
  *  Try to load the appropriate bundle containing the back end display code.
@@ -201,7 +202,7 @@ Bool QuartzLoadDisplayBundle(
     return TRUE;
 }
 
-
+#ifdef GLXEXT
 /*
  * LoadGlxBundle
  *  The Quartz mode X server needs to dynamically load the appropriate
@@ -268,7 +269,7 @@ static void LoadGlxBundle(void)
     CFRelease(bundleName);
     CFRelease(bundleURL);
 }
-
+# endif
 #else
 
 Bool QuartzLoadDisplayBundle(const char *dpyBundleName)
@@ -278,9 +279,10 @@ Bool QuartzLoadDisplayBundle(const char 
 
 #endif
 
+#ifdef GLXEXT
 void DarwinGlxPushProvider(void *impl)
 {
-#ifndef INX11APP
+#ifndef INXQUARTZ
     if (!GlxExtensionInit)
         LoadGlxBundle();
 #endif
@@ -294,7 +296,7 @@ void DarwinGlxPushProvider(void *impl)
  */
 void DarwinGlxExtensionInit(void)
 {
-#ifndef INX11APP
+#ifndef INXQUARTZ
     if (!GlxExtensionInit)
         LoadGlxBundle();
 #endif
@@ -308,13 +310,13 @@ void DarwinGlxExtensionInit(void)
 void DarwinGlxWrapInitVisuals(
     miInitVisualsProcPtr *procPtr)
 {
-#ifndef INX11APP
+#ifndef INXQUARTZ
     if (!GlxWrapInitVisuals)
         LoadGlxBundle();
 #endif
     GlxWrapInitVisuals(procPtr);
 }
-
+#endif
 
 int DarwinModeProcessArgument( int argc, char *argv[], int i )
 {
diff-tree 154d2c13f4ec22b7e6332808bbcd049d63784891 (from fa06e11f972e2a75c84b2f1586997ffc1239cbd9)
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Feb 26 19:39:26 2007 -0800

    more changes for X11.app

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index ebbfb61..3133eaa 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -25,11 +25,39 @@ libdarwinShared_a_SOURCES = darwin.c \
 			  darwinKeyboard.c \
 			  $(darwin_XINPUT_SRCS) 
 
-bin_PROGRAMS = XDarwin
+bin_PROGRAMS = XDarwin Xquartz
 XDarwin_SOURCES = \
                   $(top_srcdir)/fb/fbcmap.c \
                   $(top_srcdir)/mi/miinitext.c \
                   $(top_srcdir)/Xi/stubs.c
+
+Xquartz_SOURCES = \
+                  $(top_srcdir)/fb/fbcmap.c \
+                  $(top_srcdir)/mi/miinitext.c \
+                  $(top_srcdir)/Xi/stubs.c \
+                  apple/X11Application.m \
+                  apple/X11Controller.m \
+                  quartz/XServer.m \
+                  quartz/Preferences.m \
+                  quartz/applewm.c \
+                  quartz/keysym2ucs.c \
+                  quartz/pseudoramiX.c \
+                  quartz/quartz.c \
+                  quartz/quartzAudio.c \
+                  quartz/quartzCocoa.m \
+                  quartz/quartzKeyboard.c \
+                  quartz/quartzPasteboard.c \
+                  quartz/quartzStartup.c \
+                  quartz/xpr/appledri.c \
+                  quartz/xpr/dri.c \
+                  quartz/xpr/xprAppleWM.c \
+                  quartz/xpr/xprCursor.c \
+                  quartz/xpr/xprFrame.c \
+                  quartz/xpr/xprScreen.c \
+                  quartz/xpr/x-hash.c \
+                  quartz/xpr/x-hook.c \
+                  quartz/xpr/x-list.c
+
 XDarwin_LDADD = \
 		$(top_builddir)/dix/dixfonts.lo \
 		$(top_builddir)/dix/libdix.la \
@@ -59,12 +87,48 @@ XDarwin_LDADD = \
 		@XORG_LIBS@ \
 		-lXau -lXdmcp -lXfont -lfreetype
 
+Xquartz_LDADD = \
+		$(top_builddir)/dix/dixfonts.lo \
+		$(top_builddir)/dix/libdix.la \
+		$(top_builddir)/os/libos.la \
+		./libdarwinShared.a \
+		$(top_builddir)/dix/libxpstubs.la \
+		$(top_builddir)/miext/shadow/libshadow.la \
+		$(top_builddir)/fb/libfb.la \
+		$(top_builddir)/composite/libcomposite.la \
+		$(top_builddir)/damageext/libdamageext.la \
+		$(top_builddir)/miext/damage/libdamage.la \
+		$(top_builddir)/xfixes/libxfixes.la \
+		$(top_builddir)/miext/cw/libcw.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 \
+		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
+		$(top_builddir)/miext/rootless/accel/librlAccel.la \
+		@XORG_LIBS@ \
+		-lXau -lXdmcp -lXfont -lfreetype -lXplugin
+
 XDarwin_LDFLAGS =  \
-		 -XCClinker -Objc \
-		 -Wl,-u,_miDCInitialize \
-		 -Wl,-framework,IOKit
+                 -XCClinker -Objc \
+                 -Wl,-u,_miDCInitialize \
+                 -Wl,-framework,IOKit
+
+Xquartz_LDFLAGS =  \
+                 -XCClinker -Objc \
+                 -Wl,-u,_miDCInitialize \
+                 -Wl,-framework,Carbon \
+                 -Wl,-framework,ApplicationServices \
+                 -Wl,-framework,Cocoa \
+                 -Wl,-framework,CoreAudio \
+                 -Wl,-framework,IOKit
 
 XDarwin_CFLAGS = -DINXDARWIN
+Xquartz_CFLAGS = -DINXQUARTZ -DHAS_CG_MACH_PORT -DHAS_KL_API  -DHAVE_XORG_CONFIG_H
 
 if XQUARTZ
 macosdir = $(darwinappdir)/Contents/MacOS
@@ -72,6 +136,10 @@ macosdir = $(darwinappdir)/Contents/MacO
 DEFS += -DDARWIN_WITH_QUARTZ -DXFree86Server
 
 macos_PROGRAMS = XDarwinApp
+macos_SCRIPTS = x11app
+
+x11app:
+	cd apple && xcodebuild
 
 XDarwinApp_SOURCES = \
                 $(top_srcdir)/fb/fbcmap.c \
@@ -248,6 +316,7 @@ install-data-hook: $(HOOK_TARGETS)
 
 xquartz-install-hook:
 	mv $(DESTDIR)$(macosdir)/XDarwinApp $(DESTDIR)$(macosdir)/XDarwin
+	cd apple && xcodebuild install
 
 EXTRA_DIST = \
 	darwin.c \
diff --git a/hw/darwin/quartz/quartzStartup.c b/hw/darwin/quartz/quartzStartup.c
index 38fde3c..ae156f8 100644
--- a/hw/darwin/quartz/quartzStartup.c
+++ b/hw/darwin/quartz/quartzStartup.c
@@ -38,11 +38,22 @@
 #include "opaque.h"
 #include "micmap.h"
 #include <assert.h>
-int NSApplicationMain(int argc, char *argv[]);
 
 char **envpGlobal;      // argcGlobal and argvGlobal
                         // are from dix/globals.c
 
+#ifdef INX11APP
+void X11ControllerMain(int argc, char *argv[], void (*server_thread) (void *), void *server_arg);
+void GlxExtensionInit(void);
+void GlxWrapInitVisuals(miInitVisualsProcPtr *);
+
+static void server_thread (void *arg) {
+  extern int main (int argc, char **argv, char **envp);
+  exit (main (argcGlobal, argvGlobal, envpGlobal));
+}
+#else
+int NSApplicationMain(int argc, char *argv[]);
+
 // GLX bundle function pointers
 typedef void (*GlxExtensionInitPtr)(void); 
 static GlxExtensionInitPtr GlxExtensionInit = NULL;
@@ -55,6 +66,7 @@ typedef Bool (*QuartzModeBundleInitPtr)(
 void * __DarwinglXMesaProvider = NULL;
 typedef void (*GlxPushProviderPtr)(void *);
 GlxPushProviderPtr GlxPushProvider = NULL;
+#endif
 
 /*
  * DarwinHandleGUI
@@ -74,7 +86,9 @@ void DarwinHandleGUI(
     int         fd[2];
 
     if (been_here) {
+#ifdef INXDARWINAPP
         QuartzReadPreferences();
+#endif
         return;
     }
     been_here = TRUE;
@@ -109,11 +123,27 @@ void DarwinHandleGUI(
         }
     }
 
+#ifdef INX11APP
+    /* 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. */
+    extern void _InitHLTB(void);
+    
+    _InitHLTB();
+    
+    X11ControllerMain(argc, argv, server_thread, NULL);
+#else
     main_exit = NSApplicationMain(argc, argv);
+#endif
     exit(main_exit);
 }
 
-
+#ifndef INX11APP
 /*
  * QuartzLoadDisplayBundle
  *  Try to load the appropriate bundle containing the back end display code.
@@ -239,15 +269,21 @@ static void LoadGlxBundle(void)
     CFRelease(bundleURL);
 }
 
+#else
+
+Bool QuartzLoadDisplayBundle(const char *dpyBundleName)
+{
+      return TRUE;
+  }
+
+#endif
 
-/*
- * DarwinGlxExtensionInit
- *  Initialize the GLX extension.
- */
 void DarwinGlxPushProvider(void *impl)
 {
+#ifndef INX11APP
     if (!GlxExtensionInit)
         LoadGlxBundle();
+#endif
 	
     GlxPushProvider(impl);
 }
@@ -258,9 +294,10 @@ void DarwinGlxPushProvider(void *impl)
  */
 void DarwinGlxExtensionInit(void)
 {
+#ifndef INX11APP
     if (!GlxExtensionInit)
         LoadGlxBundle();
-
+#endif
     GlxExtensionInit();
 }
 
@@ -271,9 +308,10 @@ void DarwinGlxExtensionInit(void)
 void DarwinGlxWrapInitVisuals(
     miInitVisualsProcPtr *procPtr)
 {
+#ifndef INX11APP
     if (!GlxWrapInitVisuals)
         LoadGlxBundle();
-
+#endif
     GlxWrapInitVisuals(procPtr);
 }
 
diff-tree fa06e11f972e2a75c84b2f1586997ffc1239cbd9 (from a16360733ea393ec1fc267e88fc604d9d7534484)
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Feb 26 17:06:53 2007 -0800

    added hw/darwin/apple directory, which contains source and data files to build
    a version of the X11.app shipped with Mac OS X, using the X.org server.

diff --git a/hw/darwin/apple/English.lproj/InfoPlist.strings b/hw/darwin/apple/English.lproj/InfoPlist.strings
new file mode 100644
index 0000000..88e1f04
Binary files /dev/null and b/hw/darwin/apple/English.lproj/InfoPlist.strings differ
diff --git a/hw/darwin/apple/English.lproj/main.nib/.svn/entries b/hw/darwin/apple/English.lproj/main.nib/.svn/entries
new file mode 100644
index 0000000..95a15f2
--- /dev/null
+++ b/hw/darwin/apple/English.lproj/main.nib/.svn/entries
@@ -0,0 +1,65 @@
+8
+
+dir
+29110
+svn+ssh://src.apple.com/svn/BSD/X11server/trunk/darwin/apple/English.lproj/main.nib
+svn+ssh://src.apple.com/svn/BSD
+
+
+
+2007-02-03T03:06:20.842932Z
+28761
+bbyer
+
+
+svn:special svn:externals svn:needs-lock
+
+
+
+
+
+
+
+
+
+
+
+e92bca22-270c-0410-9cea-e3f1106b6a1c
+
+info.nib
+file
+
+
+
+
+2007-02-27T01:00:07.000000Z
+456347804c516786b1d1339ce2ef50a2
+2007-02-03T03:06:20.842932Z
+28761
+bbyer
+
+keyedobjects.nib
+file
+
+
+
+
+2007-02-27T01:00:07.000000Z
+eb3010372b09768c846df0d996cfdd8d
+2007-02-03T03:06:20.842932Z
+28761
+bbyer
+has-props
+
+classes.nib
+file
+
+
+
+
+2007-02-27T01:00:07.000000Z
+0ae2660c3afabbd5aa02fc34712c96e6
+2007-02-03T03:06:20.842932Z
+28761
+bbyer
+
diff --git a/hw/darwin/apple/English.lproj/main.nib/.svn/format b/hw/darwin/apple/English.lproj/main.nib/.svn/format
new file mode 100644
index 0000000..45a4fb7
--- /dev/null
+++ b/hw/darwin/apple/English.lproj/main.nib/.svn/format
@@ -0,0 +1 @@
+8
diff --git a/hw/darwin/apple/English.lproj/main.nib/.svn/prop-base/keyedobjects.nib.svn-base b/hw/darwin/apple/English.lproj/main.nib/.svn/prop-base/keyedobjects.nib.svn-base
new file mode 100644
index 0000000..5e9587e
--- /dev/null
+++ b/hw/darwin/apple/English.lproj/main.nib/.svn/prop-base/keyedobjects.nib.svn-base
@@ -0,0 +1,5 @@
+K 13
+svn:mime-type
+V 24
+application/octet-stream
+END
diff --git a/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/classes.nib.svn-base b/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/classes.nib.svn-base
new file mode 100644
index 0000000..a82159b
--- /dev/null
+++ b/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/classes.nib.svn-base
@@ -0,0 +1,318 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>IBClasses</key>
+	<array>
+		<dict>
+			<key>CLASS</key>
+			<string>IBLibraryObjectTemplate</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>OUTLETS</key>
+			<dict>
+				<key>draggedView</key>
+				<string>NSView</string>
+				<key>representedObject</key>
+				<string>NSObject</string>
+			</dict>
+			<key>SUPERCLASS</key>
+			<string>NSView</string>
+		</dict>
+		<dict>
+			<key>CLASS</key>
+			<string>IBInspector</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>OUTLETS</key>
+			<dict>
+				<key>inspectorView</key>
+				<string>NSView</string>
+			</dict>
+			<key>SUPERCLASS</key>
+			<string>NSObject</string>
+		</dict>
+		<dict>
+			<key>CLASS</key>
+			<string>NSDateFormatter</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>SUPERCLASS</key>
+			<string>NSFormatter</string>
+		</dict>
+		<dict>
+			<key>ACTIONS</key>
+			<dict>
+				<key>apps_table_cancel</key>
+				<string>id</string>
+				<key>apps_table_delete</key>
+				<string>id</string>
+				<key>apps_table_done</key>
+				<string>id</string>
+				<key>apps_table_duplicate</key>
+				<string>id</string>
+				<key>apps_table_new</key>
+				<string>id</string>
+				<key>apps_table_show</key>
+				<string>id</string>
+				<key>bring_to_front</key>
+				<string>id</string>
+				<key>close_window</key>
+				<string>id</string>
+				<key>enable_fullscreen_changed</key>
+				<string>id</string>
+				<key>minimize_window</key>
+				<string>id</string>
+				<key>next_window</key>
+				<string>id</string>
+				<key>prefs_changed</key>
+				<string>id</string>
+				<key>prefs_show</key>
+				<string>id</string>
+				<key>previous_window</key>
+				<string>id</string>
+				<key>toggle_fullscreen</key>
+				<string>id</string>
+				<key>x11_help</key>
+				<string>id</string>
+				<key>zoom_window</key>
+				<string>id</string>
+			</dict>
+			<key>CLASS</key>
+			<string>X11Controller</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>OUTLETS</key>
+			<dict>
+				<key>apps_separator</key>
+				<string>id</string>
+				<key>apps_table</key>
+				<string>id</string>
+				<key>depth</key>
+				<string>id</string>
+				<key>dock_apps_menu</key>
+				<string>id</string>
+				<key>dock_menu</key>
+				<string>id</string>
+				<key>dock_window_separator</key>
+				<string>id</string>
+				<key>enable_auth</key>
+				<string>id</string>
+				<key>enable_fullscreen</key>
+				<string>id</string>
+				<key>enable_keyequivs</key>
+				<string>id</string>
+				<key>enable_tcp</key>
+				<string>id</string>
+				<key>fake_buttons</key>
+				<string>id</string>
+				<key>prefs_panel</key>
+				<string>id</string>
+				<key>sync_keymap</key>
+				<string>id</string>
+				<key>toggle_fullscreen_item</key>
+				<string>id</string>
+				<key>use_sysbeep</key>
+				<string>id</string>
+				<key>window_separator</key>
+				<string>id</string>
+				<key>x11_about_item</key>
+				<string>id</string>
+			</dict>
+			<key>SUPERCLASS</key>
+			<string>NSObject</string>
+		</dict>
+		<dict>
+			<key>CLASS</key>
+			<string>NSNumberFormatter</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>SUPERCLASS</key>
+			<string>NSFormatter</string>
+		</dict>
+		<dict>
+			<key>CLASS</key>
+			<string>NSFormatter</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>SUPERCLASS</key>
+			<string>NSObject</string>
+		</dict>
+		<dict>
+			<key>ACTIONS</key>
+			<dict>
+				<key>alignCenter:</key>
+				<string>id</string>
+				<key>alignJustified:</key>
+				<string>id</string>
+				<key>alignLeft:</key>
+				<string>id</string>
+				<key>alignRight:</key>
+				<string>id</string>
+				<key>arrangeInFront:</key>
+				<string>id</string>
+				<key>centerSelectionInVisibleArea:</key>
+				<string>id</string>
+				<key>changeFont:</key>
+				<string>id</string>
+				<key>checkSpelling:</key>
+				<string>id</string>
+				<key>clear:</key>
+				<string>id</string>
+				<key>clearRecentDocuments:</key>
+				<string>id</string>
+				<key>complete:</key>
+				<string>id</string>
+				<key>copy:</key>
+				<string>id</string>
+				<key>copyFont:</key>
+				<string>id</string>
+				<key>copyRuler:</key>
+				<string>id</string>
+				<key>cut:</key>
+				<string>id</string>
+				<key>delete:</key>
+				<string>id</string>
+				<key>deminiaturize:</key>
+				<string>id</string>
+				<key>fax:</key>
+				<string>id</string>
+				<key>hide:</key>
+				<string>id</string>
+				<key>hideOtherApplications:</key>
+				<string>id</string>
+				<key>loosenKerning:</key>
+				<string>id</string>
+				<key>lowerBaseline:</key>
+				<string>id</string>
+				<key>makeKeyAndOrderFront:</key>
+				<string>id</string>
+				<key>miniaturize:</key>
+				<string>id</string>
+				<key>newDocument:</key>
+				<string>id</string>
+				<key>openDocument:</key>
+				<string>id</string>
+				<key>orderBack:</key>
+				<string>id</string>
+				<key>orderFront:</key>
+				<string>id</string>
+				<key>orderFrontColorPanel:</key>
+				<string>id</string>
+				<key>orderFrontHelpPanel:</key>
+				<string>id</string>
+				<key>orderOut:</key>
+				<string>id</string>
+				<key>outline:</key>
+				<string>id</string>
+				<key>paste:</key>
+				<string>id</string>
+				<key>pasteAsPlainText:</key>
+				<string>id</string>
+				<key>pasteAsRichText:</key>
+				<string>id</string>
+				<key>pasteFont:</key>
+				<string>id</string>
+				<key>pasteRuler:</key>
+				<string>id</string>
+				<key>pause:</key>
+				<string>id</string>
+				<key>performClose:</key>
+				<string>id</string>
+				<key>performFindPanelAction:</key>
+				<string>id</string>
+				<key>performMiniaturize:</key>
+				<string>id</string>
+				<key>performZoom:</key>
+				<string>id</string>
+				<key>play:</key>
+				<string>id</string>
+				<key>print:</key>
+				<string>id</string>
+				<key>printDocument:</key>
+				<string>id</string>
+				<key>raiseBaseline:</key>
+				<string>id</string>
+				<key>record:</key>
+				<string>id</string>
+				<key>redo:</key>
+				<string>id</string>
+				<key>resume:</key>
+				<string>id</string>
+				<key>revertDocumentToSaved:</key>
+				<string>id</string>
+				<key>run:</key>
+				<string>id</string>
+				<key>runPageLayout:</key>
+				<string>id</string>
+				<key>runToolbarCustomizationPalette:</key>
+				<string>id</string>
+				<key>saveAllDocuments:</key>
+				<string>id</string>
+				<key>saveDocument:</key>
+				<string>id</string>
+				<key>saveDocumentAs:</key>
+				<string>id</string>
+				<key>saveDocumentTo:</key>
+				<string>id</string>
+				<key>selectAll:</key>
+				<string>id</string>
+				<key>selectText:</key>
+				<string>id</string>
+				<key>showGuessPanel:</key>
+				<string>id</string>
+				<key>showHelp:</key>
+				<string>id</string>
+				<key>start:</key>
+				<string>id</string>
+				<key>startSpeaking:</key>
+				<string>id</string>
+				<key>stop:</key>
+				<string>id</string>
+				<key>stopSpeaking:</key>
+				<string>id</string>
+				<key>subscript:</key>
+				<string>id</string>
+				<key>superscript:</key>
+				<string>id</string>
+				<key>terminate:</key>
+				<string>id</string>
+				<key>tightenKerning:</key>
+				<string>id</string>
+				<key>toggleContinuousSpellChecking:</key>
+				<string>id</string>
+				<key>toggleRuler:</key>
+				<string>id</string>
+				<key>toggleToolbarShown:</key>
+				<string>id</string>
+				<key>turnOffKerning:</key>
+				<string>id</string>
+				<key>turnOffLigatures:</key>
+				<string>id</string>
+				<key>underline:</key>
+				<string>id</string>
+				<key>undo:</key>
+				<string>id</string>
+				<key>unhideAllApplications:</key>
+				<string>id</string>
+				<key>unscript:</key>
+				<string>id</string>
+				<key>useAllLigatures:</key>
+				<string>id</string>
+				<key>useStandardKerning:</key>
+				<string>id</string>
+				<key>useStandardLigatures:</key>
+				<string>id</string>
+			</dict>
+			<key>CLASS</key>
+			<string>FirstResponder</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>SUPERCLASS</key>
+			<string>NSObject</string>
+		</dict>
+	</array>
+	<key>IBVersion</key>
+	<integer>1</integer>
+</dict>
+</plist>
diff --git a/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/info.nib.svn-base b/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/info.nib.svn-base
new file mode 100644
index 0000000..88bc626
--- /dev/null
+++ b/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/info.nib.svn-base
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>IBFramework Version</key>
+	<string>588</string>
+	<key>IBOpenObjects</key>
+	<array>
+		<integer>244</integer>
+		<integer>29</integer>
+		<integer>423</integer>
+	</array>
+	<key>IBSystem Version</key>
+	<string>9A356</string>
+	<key>targetFramework</key>
+	<string>IBCocoaFramework</string>
+</dict>
+</plist>
diff --git a/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/keyedobjects.nib.svn-base b/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/keyedobjects.nib.svn-base
new file mode 100644
index 0000000..8b31450
Binary files /dev/null and b/hw/darwin/apple/English.lproj/main.nib/.svn/text-base/keyedobjects.nib.svn-base differ
diff --git a/hw/darwin/apple/English.lproj/main.nib/classes.nib b/hw/darwin/apple/English.lproj/main.nib/classes.nib
new file mode 100644
index 0000000..a82159b
--- /dev/null
+++ b/hw/darwin/apple/English.lproj/main.nib/classes.nib
@@ -0,0 +1,318 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>IBClasses</key>
+	<array>
+		<dict>
+			<key>CLASS</key>
+			<string>IBLibraryObjectTemplate</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>OUTLETS</key>
+			<dict>
+				<key>draggedView</key>
+				<string>NSView</string>
+				<key>representedObject</key>
+				<string>NSObject</string>
+			</dict>
+			<key>SUPERCLASS</key>
+			<string>NSView</string>
+		</dict>
+		<dict>
+			<key>CLASS</key>
+			<string>IBInspector</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>OUTLETS</key>
+			<dict>
+				<key>inspectorView</key>
+				<string>NSView</string>
+			</dict>
+			<key>SUPERCLASS</key>
+			<string>NSObject</string>
+		</dict>
+		<dict>
+			<key>CLASS</key>
+			<string>NSDateFormatter</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>SUPERCLASS</key>
+			<string>NSFormatter</string>
+		</dict>
+		<dict>
+			<key>ACTIONS</key>
+			<dict>
+				<key>apps_table_cancel</key>
+				<string>id</string>
+				<key>apps_table_delete</key>
+				<string>id</string>
+				<key>apps_table_done</key>
+				<string>id</string>
+				<key>apps_table_duplicate</key>
+				<string>id</string>
+				<key>apps_table_new</key>
+				<string>id</string>
+				<key>apps_table_show</key>
+				<string>id</string>
+				<key>bring_to_front</key>
+				<string>id</string>
+				<key>close_window</key>
+				<string>id</string>
+				<key>enable_fullscreen_changed</key>
+				<string>id</string>
+				<key>minimize_window</key>
+				<string>id</string>
+				<key>next_window</key>
+				<string>id</string>
+				<key>prefs_changed</key>
+				<string>id</string>
+				<key>prefs_show</key>
+				<string>id</string>
+				<key>previous_window</key>
+				<string>id</string>
+				<key>toggle_fullscreen</key>
+				<string>id</string>
+				<key>x11_help</key>
+				<string>id</string>
+				<key>zoom_window</key>
+				<string>id</string>
+			</dict>
+			<key>CLASS</key>
+			<string>X11Controller</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>OUTLETS</key>
+			<dict>
+				<key>apps_separator</key>
+				<string>id</string>
+				<key>apps_table</key>
+				<string>id</string>
+				<key>depth</key>
+				<string>id</string>
+				<key>dock_apps_menu</key>
+				<string>id</string>
+				<key>dock_menu</key>
+				<string>id</string>
+				<key>dock_window_separator</key>
+				<string>id</string>
+				<key>enable_auth</key>
+				<string>id</string>
+				<key>enable_fullscreen</key>
+				<string>id</string>
+				<key>enable_keyequivs</key>
+				<string>id</string>
+				<key>enable_tcp</key>
+				<string>id</string>
+				<key>fake_buttons</key>
+				<string>id</string>
+				<key>prefs_panel</key>
+				<string>id</string>
+				<key>sync_keymap</key>
+				<string>id</string>
+				<key>toggle_fullscreen_item</key>
+				<string>id</string>
+				<key>use_sysbeep</key>
+				<string>id</string>
+				<key>window_separator</key>
+				<string>id</string>
+				<key>x11_about_item</key>
+				<string>id</string>
+			</dict>
+			<key>SUPERCLASS</key>
+			<string>NSObject</string>
+		</dict>
+		<dict>
+			<key>CLASS</key>
+			<string>NSNumberFormatter</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>SUPERCLASS</key>
+			<string>NSFormatter</string>
+		</dict>
+		<dict>
+			<key>CLASS</key>
+			<string>NSFormatter</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>SUPERCLASS</key>
+			<string>NSObject</string>
+		</dict>
+		<dict>
+			<key>ACTIONS</key>
+			<dict>
+				<key>alignCenter:</key>
+				<string>id</string>
+				<key>alignJustified:</key>
+				<string>id</string>
+				<key>alignLeft:</key>
+				<string>id</string>
+				<key>alignRight:</key>
+				<string>id</string>
+				<key>arrangeInFront:</key>
+				<string>id</string>
+				<key>centerSelectionInVisibleArea:</key>
+				<string>id</string>
+				<key>changeFont:</key>
+				<string>id</string>
+				<key>checkSpelling:</key>
+				<string>id</string>
+				<key>clear:</key>
+				<string>id</string>
+				<key>clearRecentDocuments:</key>
+				<string>id</string>
+				<key>complete:</key>
+				<string>id</string>
+				<key>copy:</key>
+				<string>id</string>
+				<key>copyFont:</key>
+				<string>id</string>
+				<key>copyRuler:</key>
+				<string>id</string>
+				<key>cut:</key>
+				<string>id</string>
+				<key>delete:</key>
+				<string>id</string>
+				<key>deminiaturize:</key>
+				<string>id</string>
+				<key>fax:</key>
+				<string>id</string>
+				<key>hide:</key>
+				<string>id</string>
+				<key>hideOtherApplications:</key>
+				<string>id</string>
+				<key>loosenKerning:</key>
+				<string>id</string>
+				<key>lowerBaseline:</key>
+				<string>id</string>
+				<key>makeKeyAndOrderFront:</key>
+				<string>id</string>
+				<key>miniaturize:</key>
+				<string>id</string>
+				<key>newDocument:</key>
+				<string>id</string>
+				<key>openDocument:</key>
+				<string>id</string>
+				<key>orderBack:</key>
+				<string>id</string>
+				<key>orderFront:</key>
+				<string>id</string>
+				<key>orderFrontColorPanel:</key>
+				<string>id</string>
+				<key>orderFrontHelpPanel:</key>
+				<string>id</string>
+				<key>orderOut:</key>
+				<string>id</string>
+				<key>outline:</key>
+				<string>id</string>
+				<key>paste:</key>
+				<string>id</string>
+				<key>pasteAsPlainText:</key>
+				<string>id</string>
+				<key>pasteAsRichText:</key>
+				<string>id</string>
+				<key>pasteFont:</key>
+				<string>id</string>
+				<key>pasteRuler:</key>
+				<string>id</string>
+				<key>pause:</key>
+				<string>id</string>
+				<key>performClose:</key>
+				<string>id</string>
+				<key>performFindPanelAction:</key>
+				<string>id</string>
+				<key>performMiniaturize:</key>
+				<string>id</string>
+				<key>performZoom:</key>
+				<string>id</string>
+				<key>play:</key>
+				<string>id</string>
+				<key>print:</key>
+				<string>id</string>
+				<key>printDocument:</key>
+				<string>id</string>
+				<key>raiseBaseline:</key>
+				<string>id</string>
+				<key>record:</key>
+				<string>id</string>
+				<key>redo:</key>
+				<string>id</string>
+				<key>resume:</key>
+				<string>id</string>
+				<key>revertDocumentToSaved:</key>
+				<string>id</string>
+				<key>run:</key>
+				<string>id</string>
+				<key>runPageLayout:</key>
+				<string>id</string>
+				<key>runToolbarCustomizationPalette:</key>
+				<string>id</string>
+				<key>saveAllDocuments:</key>
+				<string>id</string>
+				<key>saveDocument:</key>
+				<string>id</string>
+				<key>saveDocumentAs:</key>
+				<string>id</string>
+				<key>saveDocumentTo:</key>
+				<string>id</string>
+				<key>selectAll:</key>
+				<string>id</string>
+				<key>selectText:</key>
+				<string>id</string>
+				<key>showGuessPanel:</key>
+				<string>id</string>
+				<key>showHelp:</key>
+				<string>id</string>
+				<key>start:</key>
+				<string>id</string>
+				<key>startSpeaking:</key>
+				<string>id</string>
+				<key>stop:</key>
+				<string>id</string>
+				<key>stopSpeaking:</key>
+				<string>id</string>
+				<key>subscript:</key>
+				<string>id</string>
+				<key>superscript:</key>
+				<string>id</string>
+				<key>terminate:</key>
+				<string>id</string>
+				<key>tightenKerning:</key>
+				<string>id</string>
+				<key>toggleContinuousSpellChecking:</key>
+				<string>id</string>
+				<key>toggleRuler:</key>
+				<string>id</string>
+				<key>toggleToolbarShown:</key>
+				<string>id</string>
+				<key>turnOffKerning:</key>
+				<string>id</string>
+				<key>turnOffLigatures:</key>
+				<string>id</string>
+				<key>underline:</key>
+				<string>id</string>
+				<key>undo:</key>
+				<string>id</string>
+				<key>unhideAllApplications:</key>
+				<string>id</string>
+				<key>unscript:</key>
+				<string>id</string>
+				<key>useAllLigatures:</key>
+				<string>id</string>
+				<key>useStandardKerning:</key>
+				<string>id</string>
+				<key>useStandardLigatures:</key>
+				<string>id</string>
+			</dict>
+			<key>CLASS</key>
+			<string>FirstResponder</string>
+			<key>LANGUAGE</key>
+			<string>ObjC</string>
+			<key>SUPERCLASS</key>
+			<string>NSObject</string>
+		</dict>
+	</array>
+	<key>IBVersion</key>
+	<integer>1</integer>
+</dict>
+</plist>
diff --git a/hw/darwin/apple/English.lproj/main.nib/info.nib b/hw/darwin/apple/English.lproj/main.nib/info.nib
new file mode 100644
index 0000000..88bc626
--- /dev/null
+++ b/hw/darwin/apple/English.lproj/main.nib/info.nib
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>IBFramework Version</key>
+	<string>588</string>
+	<key>IBOpenObjects</key>
+	<array>
+		<integer>244</integer>
+		<integer>29</integer>
+		<integer>423</integer>
+	</array>
+	<key>IBSystem Version</key>
+	<string>9A356</string>
+	<key>targetFramework</key>
+	<string>IBCocoaFramework</string>
+</dict>
+</plist>
diff --git a/hw/darwin/apple/English.lproj/main.nib/keyedobjects.nib b/hw/darwin/apple/English.lproj/main.nib/keyedobjects.nib
new file mode 100644
index 0000000..8b31450
Binary files /dev/null and b/hw/darwin/apple/English.lproj/main.nib/keyedobjects.nib differ
diff --git a/hw/darwin/apple/Info.plist b/hw/darwin/apple/Info.plist
new file mode 100644
index 0000000..ae47e95
--- /dev/null
+++ b/hw/darwin/apple/Info.plist
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>English</string>
+	<key>CFBundleDocumentTypes</key>
+	<array>
+		<dict>
+			<key>CFBundleTypeExtensions</key>
+			<array>
+				<string>x11app</string>
+			</array>
+			<key>CFBundleTypeIconFile</key>
+			<string>X11.icns</string>
+			<key>CFBundleTypeName</key>
+			<string>X11 Application</string>
+			<key>CFBundleTypeOSTypes</key>
+			<array>
+				<string>****</string>
+			</array>
+			<key>CFBundleTypeRole</key>
+			<string>Viewer</string>
+			<key>LSIsAppleDefaultForType</key>
+			<true/>
+		</dict>
+		<dict>
+			<key>CFBundleTypeExtensions</key>
+			<array>
+				<string>tool</string>
+				<string>*</string>
+			</array>
+			<key>CFBundleTypeName</key>
+			<string>UNIX Application</string>
+			<key>CFBundleTypeOSTypes</key>
+			<array>
+				<string>****</string>
+			</array>
+			<key>CFBundleTypeRole</key>
+			<string>Viewer</string>
+		</dict>
+	</array>
+	<key>CFBundleExecutable</key>
+	<string>X11</string>
+	<key>CFBundleGetInfoString</key>
+	<string>X11</string>
+	<key>CFBundleIconFile</key>
+	<string>X11.icns</string>
+	<key>CFBundleIdentifier</key>
+	<string>org.x.X11</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleName</key>
+	<string>X11</string>
+	<key>CFBundlePackageType</key>
+	<string>APPL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>2.0</string>
+	<key>CFBundleSignature</key>
+	<string>????</string>
+	<key>CSResourcesFileMapped</key>
+	<true/>
+	<key>NSHumanReadableCopyright</key>
+	<string>Copyright © 2003-2007, Apple Inc.
+Copyright © 2003, XFree86 Project, Inc.</string>
+	<key>NSMainNibFile</key>
+	<string>main</string>
+	<key>NSPrincipalClass</key>
+	<string>X11Application</string>
+</dict>
+</plist>
diff --git a/hw/darwin/apple/X11.icns b/hw/darwin/apple/X11.icns
new file mode 100644
index 0000000..4c47177
Binary files /dev/null and b/hw/darwin/apple/X11.icns differ
diff --git a/hw/darwin/apple/X11.xcodeproj/project.pbxproj b/hw/darwin/apple/X11.xcodeproj/project.pbxproj
new file mode 100644
index 0000000..7ca75d4
--- /dev/null
+++ b/hw/darwin/apple/X11.xcodeproj/project.pbxproj
@@ -0,0 +1,329 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 42;
+	objects = {
+
+/* Begin PBXBuildFile section */
+		527F24190B5D938C007840A7 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 0867D6AAFE840B52C02AAC07 /* InfoPlist.strings */; };
+		527F241A0B5D938C007840A7 /* main.nib in Resources */ = {isa = PBXBuildFile; fileRef = 02345980000FD03B11CA0E72 /* main.nib */; };
+		527F241B0B5D938C007840A7 /* X11.icns in Resources */ = {isa = PBXBuildFile; fileRef = 50459C5F038587C60ECA21EC /* X11.icns */; };
+		527F241D0B5D938C007840A7 /* bundle-main.c in Sources */ = {isa = PBXBuildFile; fileRef = 50EE2AB703849F0B0ECA21EC /* bundle-main.c */; };
+		527F241F0B5D938C007840A7 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 50F4F0A7039D6ACA0E82C0CB /* CoreFoundation.framework */; };
+		527F24200B5D938C007840A7 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 570C5748047186C400ACF82F /* SystemConfiguration.framework */; };
+		527F24370B5D9D89007840A7 /* Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 527F24260B5D938C007840A7 /* Info.plist */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXFileReference section */
+		0867D6ABFE840B52C02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = "<group>"; };
+		1870340FFE93FCAF11CA0CD7 /* English */ = {isa = PBXFileReference; lastKnownFileType = wrapper.nib; name = English; path = English.lproj/main.nib; sourceTree = "<group>"; };
+		50459C5F038587C60ECA21EC /* X11.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = X11.icns; sourceTree = "<group>"; };
+		50EE2AB703849F0B0ECA21EC /* bundle-main.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = "bundle-main.c"; sourceTree = "<group>"; };
+		50F4F0A7039D6ACA0E82C0CB /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = /System/Library/Frameworks/CoreFoundation.framework; sourceTree = "<absolute>"; };
+		527F24260B5D938C007840A7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = Info.plist; sourceTree = "<group>"; };
+		527F24270B5D938C007840A7 /* X11.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = X11.app; sourceTree = BUILT_PRODUCTS_DIR; };
+		570C5748047186C400ACF82F /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = /System/Library/Frameworks/SystemConfiguration.framework; sourceTree = "<absolute>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		527F241E0B5D938C007840A7 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				527F241F0B5D938C007840A7 /* CoreFoundation.framework in Frameworks */,
+				527F24200B5D938C007840A7 /* SystemConfiguration.framework in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		195DF8CFFE9D517E11CA2CBB /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				527F24270B5D938C007840A7 /* X11.app */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+		20286C29FDCF999611CA2CEA /* X11 */ = {
+			isa = PBXGroup;
+			children = (
+				20286C2AFDCF999611CA2CEA /* Sources */,
+				20286C2CFDCF999611CA2CEA /* Resources */,
+				20286C32FDCF999611CA2CEA /* External Frameworks and Libraries */,
+				195DF8CFFE9D517E11CA2CBB /* Products */,
+				527F24260B5D938C007840A7 /* Info.plist */,
+			);
+			name = X11;
+			sourceTree = "<group>";
+		};
+		20286C2AFDCF999611CA2CEA /* Sources */ = {
+			isa = PBXGroup;
+			children = (
+				50EE2AB703849F0B0ECA21EC /* bundle-main.c */,
+			);
+			name = Sources;
+			sourceTree = "<group>";
+		};
+		20286C2CFDCF999611CA2CEA /* Resources */ = {
+			isa = PBXGroup;
+			children = (
+				50459C5F038587C60ECA21EC /* X11.icns */,
+				0867D6AAFE840B52C02AAC07 /* InfoPlist.strings */,
+				02345980000FD03B11CA0E72 /* main.nib */,
+			);
+			name = Resources;
+			sourceTree = "<group>";
+		};
+		20286C32FDCF999611CA2CEA /* External Frameworks and Libraries */ = {
+			isa = PBXGroup;
+			children = (
+				50F4F0A7039D6ACA0E82C0CB /* CoreFoundation.framework */,
+				570C5748047186C400ACF82F /* SystemConfiguration.framework */,
+			);
+			name = "External Frameworks and Libraries";
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXHeadersBuildPhase section */
+		527F24170B5D938C007840A7 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXHeadersBuildPhase section */
+
+/* Begin PBXNativeTarget section */
+		527F24160B5D938C007840A7 /* X11 */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 527F24220B5D938C007840A7 /* Build configuration list for PBXNativeTarget "X11" */;
+			buildPhases = (
+				527F24170B5D938C007840A7 /* Headers */,
+				527F24180B5D938C007840A7 /* Resources */,
+				527F241C0B5D938C007840A7 /* Sources */,
+				527F241E0B5D938C007840A7 /* Frameworks */,
+				527F24210B5D938C007840A7 /* Rez */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = X11;
+			productName = X11;
+			productReference = 527F24270B5D938C007840A7 /* X11.app */;
+			productType = "com.apple.product-type.application";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		20286C28FDCF999611CA2CEA /* Project object */ = {
+			isa = PBXProject;
+			buildConfigurationList = 527F24080B5D8FFC007840A7 /* Build configuration list for PBXProject "X11" */;
+			compatibilityVersion = "Xcode 2.4";
+			hasScannedForEncodings = 1;
+			mainGroup = 20286C29FDCF999611CA2CEA /* X11 */;
+			projectDirPath = "";
+			projectRoot = "";
+			shouldCheckCompatibility = 1;
+			targets = (
+				527F24160B5D938C007840A7 /* X11 */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+		527F24180B5D938C007840A7 /* Resources */ = {
+			isa = PBXResourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				527F24370B5D9D89007840A7 /* Info.plist in Resources */,
+				527F24190B5D938C007840A7 /* InfoPlist.strings in Resources */,
+				527F241A0B5D938C007840A7 /* main.nib in Resources */,
+				527F241B0B5D938C007840A7 /* X11.icns in Resources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXRezBuildPhase section */
+		527F24210B5D938C007840A7 /* Rez */ = {
+			isa = PBXRezBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXRezBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+		527F241C0B5D938C007840A7 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				527F241D0B5D938C007840A7 /* bundle-main.c in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXVariantGroup section */
+		02345980000FD03B11CA0E72 /* main.nib */ = {
+			isa = PBXVariantGroup;
+			children = (
+				1870340FFE93FCAF11CA0CD7 /* English */,
+			);
+			name = main.nib;
+			sourceTree = "<group>";
+		};
+		0867D6AAFE840B52C02AAC07 /* InfoPlist.strings */ = {
+			isa = PBXVariantGroup;
+			children = (
+				0867D6ABFE840B52C02AAC07 /* English */,
+			);
+			name = InfoPlist.strings;
+			sourceTree = "<group>";
+		};
+/* End PBXVariantGroup section */
+
+/* Begin XCBuildConfiguration section */
+		527F24090B5D8FFC007840A7 /* Development */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				DSTROOT = "$(DSTROOT)";
+				SKIP_INSTALL = YES;
+			};
+			name = Development;
+		};
+		527F240A0B5D8FFC007840A7 /* Deployment */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				DSTROOT = "$(DSTROOT)";
+				SKIP_INSTALL = YES;
+			};
+			name = Deployment;
+		};
+		527F240B0B5D8FFC007840A7 /* Default */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				DSTROOT = "$(DSTROOT)";
+				SKIP_INSTALL = YES;
+			};
+			name = Default;
+		};
+		527F24230B5D938C007840A7 /* Development */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(NATIVE_ARCH_32_BIT)";
+				COPY_PHASE_STRIP = NO;
+				DSTROOT = "$(DSTROOT)";
+				FRAMEWORK_SEARCH_PATHS = "";
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				HEADER_SEARCH_PATHS = /usr/X11/include;
+				INFOPLIST_FILE = Info.plist;
+				INSTALL_PATH = $DSTROOT/Applications/Utilties;
+				LIBRARY_SEARCH_PATHS = /usr/X11/lib;
+				OTHER_CFLAGS = "";
+				OTHER_LDFLAGS = (
+					"-lXau",
+					"-lX11",
+				);
+				OTHER_REZFLAGS = "";
+				PRODUCT_NAME = X11;
+				SECTORDER_FLAGS = "";
+				WARNING_CFLAGS = (
+					"-Wmost",
+					"-Wno-four-char-constants",
+					"-Wno-unknown-pragmas",
+				);
+				WRAPPER_EXTENSION = app;
+			};
+			name = Development;
+		};
+		527F24240B5D938C007840A7 /* Deployment */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				COPY_PHASE_STRIP = YES;
+				DSTROOT = "$(DSTROOT)";
+				FRAMEWORK_SEARCH_PATHS = "";
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				HEADER_SEARCH_PATHS = /usr/X11/include;
+				INFOPLIST_FILE = Info.plist;
+				INSTALL_PATH = $DSTROOT/Applications/Utilties;
+				LIBRARY_SEARCH_PATHS = /usr/X11/lib;
+				OTHER_CFLAGS = "";
+				OTHER_LDFLAGS = (
+					"-lXau",
+					"-lX11",
+				);
+				OTHER_REZFLAGS = "";
+				PRODUCT_NAME = X11;
+				SECTORDER_FLAGS = "";
+				WARNING_CFLAGS = (
+					"-Wmost",
+					"-Wno-four-char-constants",
+					"-Wno-unknown-pragmas",
+				);
+				WRAPPER_EXTENSION = app;
+			};
+			name = Deployment;
+		};
+		527F24250B5D938C007840A7 /* Default */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				DSTROOT = "$(DSTROOT)";
+				FRAMEWORK_SEARCH_PATHS = "";
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				HEADER_SEARCH_PATHS = /usr/X11/include;
+				INFOPLIST_FILE = Info.plist;
+				INSTALL_PATH = $DSTROOT/Applications/Utilties;
+				LIBRARY_SEARCH_PATHS = /usr/X11/lib;
+				OTHER_CFLAGS = "";
+				OTHER_LDFLAGS = (
+					"-lXau",
+					"-lX11",
+				);
+				OTHER_REZFLAGS = "";
+				PRODUCT_NAME = X11;
+				SECTORDER_FLAGS = "";
+				WARNING_CFLAGS = (
+					"-Wmost",
+					"-Wno-four-char-constants",
+					"-Wno-unknown-pragmas",
+				);
+				WRAPPER_EXTENSION = app;
+			};
+			name = Default;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		527F24080B5D8FFC007840A7 /* Build configuration list for PBXProject "X11" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				527F24090B5D8FFC007840A7 /* Development */,
+				527F240A0B5D8FFC007840A7 /* Deployment */,
+				527F240B0B5D8FFC007840A7 /* Default */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Default;
+		};
+		527F24220B5D938C007840A7 /* Build configuration list for PBXNativeTarget "X11" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				527F24230B5D938C007840A7 /* Development */,
+				527F24240B5D938C007840A7 /* Deployment */,
+				527F24250B5D938C007840A7 /* Default */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Default;
+		};
+/* End XCConfigurationList section */
+	};
+	rootObject = 20286C28FDCF999611CA2CEA /* Project object */;
+}
diff --git a/hw/darwin/apple/X11Application.h b/hw/darwin/apple/X11Application.h
new file mode 100644
index 0000000..b9d2af8
--- /dev/null
+++ b/hw/darwin/apple/X11Application.h
@@ -0,0 +1,104 @@
+/* X11Application.h -- subclass of NSApplication to multiplex events
+   $Id: X11Application.h,v 1.26 2003/08/08 19:16:13 jharper Exp $
+
+   Copyright (c) 2002-2007 Apple 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 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.
+
+   Except as contained in this notice, the name(s) of the above
+   copyright holders shall not be used in advertising or otherwise to
+   promote the sale, use or other dealings in this Software without
+   prior written authorization. */
+
+#ifndef X11APPLICATION_H
+#define X11APPLICATION_H 1
+
+#if __OBJC__
+
+#import <Cocoa/Cocoa.h>
+#import "X11Controller.h"
+
+ at interface X11Application : NSApplication {
+    X11Controller *_controller;
+
+    unsigned int _x_active :1;
+}
+
+- (void) set_controller:controller;
+- (void) set_window_menu:(NSArray *)list;
+
+- (int) prefs_get_integer:(NSString *)key default:(int)def;
+- (const char *) prefs_get_string:(NSString *)key default:(const char *)def;
+- (float) prefs_get_float:(NSString *)key default:(float)def;
+- (int) prefs_get_boolean:(NSString *)key default:(int)def;
+- (NSArray *) prefs_get_array:(NSString *)key;
+- (void) prefs_set_integer:(NSString *)key value:(int)value;
+- (void) prefs_set_float:(NSString *)key value:(float)value;
+- (void) prefs_set_boolean:(NSString *)key value:(int)value;
+- (void) prefs_set_array:(NSString *)key value:(NSArray *)value;
+- (void) prefs_set_string:(NSString *)key value:(NSString *)value;
+- (void) prefs_synchronize;
+
+- (BOOL) x_active;
+
+ at end
+
+extern X11Application *X11App;
+
+#endif /* __OBJC__ */
+
+extern void X11ApplicationSetWindowMenu (int nitems, const char **items,
+					 const char *shortcuts);
+extern void X11ApplicationSetWindowMenuCheck (int idx);
+extern void X11ApplicationSetFrontProcess (void);
+extern void X11ApplicationSetCanQuit (int state);
+extern void X11ApplicationServerReady (void);
+extern void X11ApplicationShowHideMenubar (int state);
+
+extern void X11ApplicationMain (int argc, const char *argv[],
+				void (*server_thread) (void *),
+				void *server_arg);
+
+extern int X11EnableKeyEquivalents;
+extern int quartzHasRoot, quartzEnableRootless;
+
+#define APP_PREFS "com.apple.x11"
+
+#define PREFS_APPSMENU		"apps_menu"
+#define PREFS_FAKEBUTTONS	"enable_fake_buttons"
+#define PREFS_SYSBEEP		"enable_system_beep"
+#define PREFS_KEYEQUIVS		"enable_key_equivalents"
+#define PREFS_KEYMAP_FILE	"keymap_file"
+#define PREFS_SYNC_KEYMAP	"sync_keymap"
+#define PREFS_DEPTH		"depth"
+#define PREFS_NO_AUTH		"no_auth"
+#define PREFS_NO_TCP		"nolisten_tcp"
+#define PREFS_DONE_XINIT_CHECK	"done_xinit_check"
+#define PREFS_NO_QUIT_ALERT	"no_quit_alert"
+#define PREFS_FAKE_BUTTON2	"fake_button2"
+#define PREFS_FAKE_BUTTON3	"fake_button3"
+#define PREFS_ROOTLESS		"rootless"
+#define PREFS_FULLSCREEN_HOTKEYS "fullscreen_hotkeys"
+#define PREFS_SWAP_ALT_META	"swap_alt_meta"
+#define PREFS_XP_OPTIONS	"xp_options"
+#define PREFS_ENABLE_STEREO	"enable_stereo"
+
+#endif /* X11APPLICATION_H */
diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
new file mode 100644
index 0000000..5da0574
--- /dev/null
+++ b/hw/darwin/apple/X11Application.m
@@ -0,0 +1,1138 @@
+/* X11Application.m -- subclass of NSApplication to multiplex events
+ $Id: X11Application.m,v 1.59 2006/09/06 21:19:32 jharper Exp $
+ 
+ Copyright (c) 2002-2007 Apple 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 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.
+ 
+ Except as contained in this notice, the name(s) of the above
+ copyright holders shall not be used in advertising or otherwise to
+ promote the sale, use or other dealings in this Software without
+ prior written authorization. */
+
+#include "../quartz/quartzCommon.h"
+
+#import "X11Application.h"
+#include <Carbon/Carbon.h>
+
+/* ouch! */
+#define BOOL X_BOOL
+//# include "Xproto.h"
+# include "darwin.h"
+# include "../quartz/quartz.h"
+# define _APPLEWM_SERVER_
+# include "X11/extensions/applewm.h"
+//# include "X.h"
+# include "micmap.h"
+#undef BOOL
+
+#include "xf86Version.h"
+
+#include <mach/mach.h>
+#include <unistd.h>
+#include <pthread.h>
+
+#define DEFAULTS_FILE "/etc/X11/xserver/Xquartz.plist"
+
+int X11EnableKeyEquivalents = TRUE;
+int quartzHasRoot = FALSE, quartzEnableRootless = TRUE;
+
+extern int darwinFakeButtons;
+// extern Bool enable_stereo; 
+Bool enable_stereo;  //<-- this needs to go back to being an extern once glxCGL is fixed
+
+
+X11Application *X11App;
+
+#define ALL_KEY_MASKS (NSShiftKeyMask | NSControlKeyMask \
+| NSAlternateKeyMask | NSCommandKeyMask)
+
+ at implementation X11Application
+
+typedef struct message_struct message;
+struct message_struct {
+    mach_msg_header_t hdr;
+    SEL selector;
+    NSObject *arg;
+};
+
+static mach_port_t _port;
+
+static void send_nsevent (NSEventType type, NSEvent *e);
+
+/* Quartz mode initialization routine. This is often dynamically loaded
+ but is statically linked into this X server. */
+extern Bool QuartzModeBundleInit(void);
+
+static void
+init_ports (void)
+{
+    kern_return_t r;
+    NSPort *p;
+	
+    if (_port != MACH_PORT_NULL)
+		return;
+	
+    r = mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE, &_port);
+    if (r != KERN_SUCCESS)
+		return;
+	
+    p = [NSMachPort portWithMachPort:_port];
+    [p setDelegate:NSApp];
+    [p scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+}
+
+static void
+message_kit_thread (SEL selector, NSObject *arg)
+{
+    message msg;
+    kern_return_t r;
+	
+    msg.hdr.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_MAKE_SEND, 0);
+    msg.hdr.msgh_size = sizeof (msg);
+    msg.hdr.msgh_remote_port = _port;
+    msg.hdr.msgh_local_port = MACH_PORT_NULL;
+    msg.hdr.msgh_reserved = 0;
+    msg.hdr.msgh_id = 0;
+	
+    msg.selector = selector;
+    msg.arg = [arg retain];
+	
+    r = mach_msg (&msg.hdr, MACH_SEND_MSG, msg.hdr.msgh_size,
+				  0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
+    if (r != KERN_SUCCESS)
+		fprintf (stderr, "%s: mach_msg failed: %x\n", __FUNCTION__, r);
+}
+
+- (void) handleMachMessage:(void *)_msg
+{
+    message *msg = _msg;
+	
+    [self performSelector:msg->selector withObject:msg->arg];
+    [msg->arg release];
+}
+
+- (void) set_controller:obj
+{
+    if (_controller == nil)
+		_controller = [obj retain];
+}
+
+- (void) dealloc
+{
+    if (_controller != nil)
+		[_controller release];
+	
+    if (_port != MACH_PORT_NULL)
+		mach_port_deallocate (mach_task_self (), _port);
+	
+    [super dealloc];
+}
+
+- (void) orderFrontStandardAboutPanel: (id) sender
+{
+    NSMutableDictionary *dict;
+    NSDictionary *infoDict;
+    NSString *tem;
+	
+    dict = [NSMutableDictionary dictionaryWithCapacity:2];
+    infoDict = [[NSBundle mainBundle] infoDictionary];
+	
+    [dict setObject: NSLocalizedString (@"The X Window System", @"About panel")
+			 forKey:@"ApplicationName"];
+	
+    tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
+	
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.1",
+					 tem] forKey:@"ApplicationVersion"];
+	
+    [self orderFrontStandardAboutPanelWithOptions: dict];
+}
+
+- (void) activateX:(BOOL)state
+{
+    /* Create a TSM document that supports full Unicode input, and
+	 have it activated while X is active (unless using the old
+	 keymapping files) */
+    static TSMDocumentID x11_document;
+	
+    if (state)
+    {
+		QuartzMessageServerThread (kXDarwinActivate, 0);
+		
+		if (!_x_active)
+		{
+			if (x11_document == 0 && darwinKeymapFile == NULL)
+			{
+				OSType types[1];
+				types[0] = kUnicodeDocument;
+				NewTSMDocument (1, types, &x11_document, 0);
+			}
+			
+			if (x11_document != 0)
+				ActivateTSMDocument (x11_document);
+		}
+    }
+    else
+    {
+		QuartzMessageServerThread (kXDarwinDeactivate, 0);
+		
+		if (_x_active)
+		{
+			if (x11_document != 0)
+				DeactivateTSMDocument (x11_document);
+		}
+    }
+	
+    _x_active = state;
+}
+
+- (void) became_key:(NSWindow *)win
+{
+    [self activateX:NO];
+}
+
+- (void) sendEvent:(NSEvent *)e
+{
+    NSEventType type;
+    BOOL for_appkit, for_x;
+	
+    type = [e type];
+	
+    /* By default pass down the responder chain and to X. */
+    for_appkit = YES;
+    for_x = YES;
+	
+    switch (type)
+    {
+    case NSLeftMouseDown: case NSRightMouseDown: case NSOtherMouseDown:
+    case NSLeftMouseUp: case NSRightMouseUp: case NSOtherMouseUp:
+		if ([e window] != nil)
+		{
+			/* Pointer event has a window. Probably something for the kit. */
+			
+			for_x = NO;
+			
+			if (_x_active)
+				[self activateX:NO];
+		}
+		else if ([self modalWindow] == nil)
+		{
+			/* Must be an X window. Tell appkit it doesn't have focus. */
+			
+			for_appkit = NO;
+			
+			if ([self isActive])
+			{
+				[self deactivate];
+				
+				if (!_x_active && quartzProcs->IsX11Window([e window],
+														   [e windowNumber]))
+				[self activateX:YES];
+			}
+		}
+		break;
+		
+    case NSKeyDown: case NSKeyUp:
+		if (_x_active)
+		{
+			static int swallow_up;
+			
+			/* No kit window is focused, so send it to X. */
+			
+			for_appkit = NO;
+			
+			if (type == NSKeyDown)
+			{
+				/* Before that though, see if there are any global
+				 shortcuts bound to it. */
+				
+				if (X11EnableKeyEquivalents
+					&& [[self mainMenu] performKeyEquivalent:e])
+				{
+					swallow_up = [e keyCode];
+					for_x = NO;
+				}
+				else if (!quartzEnableRootless
+						 && ([e modifierFlags] & ALL_KEY_MASKS)
+						 == (NSCommandKeyMask | NSAlternateKeyMask)
+						 && ([e keyCode] == 0 /*a*/
+							 || [e keyCode] == 53 /*Esc*/))
+				{
+					swallow_up = 0;
+					for_x = NO;
+#ifdef DARWIN_DDX_MISSING
+					QuartzMessageServerThread (kXDarwinToggleFullscreen, 0);
+#endif
+				}
+			}
+			else
+			{
+				/* If we saw a key equivalent on the down, don't pass
+				 the up through to X. */
+				
+				if (swallow_up != 0 && [e keyCode] == swallow_up)
+				{
+					swallow_up = 0;
+					for_x = NO;
+				}
+			}
+		}
+		else
+		{
+			for_x = NO;
+		}
+		break;
+		
+    case NSFlagsChanged:
+		/* For the l33t X users who remap modifier keys to normal keysyms. */
+		if (!_x_active)
+			for_x = NO;
+		break;
+		
+    case NSAppKitDefined:
+		switch ([e subtype])
+		{
+		case NSApplicationActivatedEventType:
+			for_x = NO;
+			if ([self modalWindow] == nil)
+			{
+				for_appkit = NO;
+				
+				/* FIXME: hack to avoid having to pass the event to appkit,
+				 which would cause it to raise one of its windows. */
+				_appFlags._active = YES;
+				
+				[self activateX:YES];
+#ifdef DARWIN_DDX_MISSING
+				if ([e data2] & 0x10) QuartzMessageServerThread (kXDarwinBringAllToFront, 0);
+#endif
+			}
+			break;
+			
+		case 18: /* ApplicationDidReactivate */
+			if (quartzHasRoot)
+				for_appkit = NO;
+			break;
+			
+		case NSApplicationDeactivatedEventType:
+			for_x = NO;
+			[self activateX:NO];
+			break;
+		}
+		break;
+		
+    default: break; /* for gcc */
+    }
+	
+    if (for_appkit)
+    {
+		[super sendEvent:e];
+    }
+	
+    if (for_x)
+    {
+		send_nsevent (type, e);
+    }
+}
+
+- (void) set_window_menu:(NSArray *)list
+{
+    [_controller set_window_menu:list];
+}
+
+- (void) set_window_menu_check:(NSNumber *)n
+{
+    [_controller set_window_menu_check:n];
+}
+
+- (void) set_apps_menu:(NSArray *)list
+{
+    [_controller set_apps_menu:list];
+}
+
+- (void) set_front_process:unused
+{
+    [NSApp activateIgnoringOtherApps:YES];
+	
+    if ([self modalWindow] == nil)
+		[self activateX:YES];
+}
+
+- (void) set_can_quit:(NSNumber *)state
+{
+    [_controller set_can_quit:[state boolValue]];
+}
+
+- (void) server_ready:unused
+{
+    [_controller server_ready];
+}
+
+- (void) show_hide_menubar:(NSNumber *)state
+{
+    if ([state boolValue])
+		ShowMenuBar ();
+    else
+		HideMenuBar ();
+}
+
+
+/* user preferences */
+
+/* Note that these functions only work for arrays whose elements
+ can be toll-free-bridged between NS and CF worlds. */
+
+static const void *cfretain (CFAllocatorRef a, const void *b) {
+    return CFRetain (b);
+}
+static void cfrelease (CFAllocatorRef a, const void *b) {
+    CFRelease (b);
+}
+static CFMutableArrayRef
+nsarray_to_cfarray (NSArray *in)
+{
+    CFMutableArrayRef out;
+    CFArrayCallBacks cb;
+    NSObject *ns;
+    const CFTypeRef *cf;
+    int i, count;
+	
+    memset (&cb, 0, sizeof (cb));
+    cb.version = 0;
+    cb.retain = cfretain;
+    cb.release = cfrelease;
+	
+    count = [in count];
+    out = CFArrayCreateMutable (NULL, count, &cb);
+	
+    for (i = 0; i < count; i++)
+    {
+		ns = [in objectAtIndex:i];
+		
+		if ([ns isKindOfClass:[NSArray class]])
+			cf = (CFTypeRef) nsarray_to_cfarray ((NSArray *) ns);
+		else
+			cf = CFRetain ((CFTypeRef) ns);
+		
+		CFArrayAppendValue (out, cf);
+		CFRelease (cf);
+    }
+	
+    return out;
+}
+static NSMutableArray *
+cfarray_to_nsarray (CFArrayRef in)
+{
+    NSMutableArray *out;
+    const CFTypeRef *cf;
+    NSObject *ns;
+    int i, count;
+	
+    count = CFArrayGetCount (in);
+    out = [[NSMutableArray alloc] initWithCapacity:count];
+	
+    for (i = 0; i < count; i++)
+    {
+		cf = CFArrayGetValueAtIndex (in, i);
+		
+		if (CFGetTypeID (cf) == CFArrayGetTypeID ())
+			ns = cfarray_to_nsarray ((CFArrayRef) cf);
+		else
+			ns = [(id)cf retain];
+		
+		[out addObject:ns];
+		[ns release];
+    }
+	
+    return out;
+}
+
+- (CFPropertyListRef) prefs_get:(NSString *)key
+{
+    CFPropertyListRef value;
+	
+    value = CFPreferencesCopyAppValue ((CFStringRef) key, CFSTR (APP_PREFS));
+	
+    if (value == NULL)
+    {
+		static CFDictionaryRef defaults;
+		
+		if (defaults == NULL)
+		{
+			CFStringRef error = NULL;
+			CFDataRef data;
+			CFURLRef url;
+			SInt32 error_code;
+			
+			url = (CFURLCreateFromFileSystemRepresentation
+				   (NULL, (unsigned char *)DEFAULTS_FILE, strlen (DEFAULTS_FILE), false));
+			if (CFURLCreateDataAndPropertiesFromResource (NULL, url, &data,
+														  NULL, NULL,
+														  &error_code))
+			{
+				defaults = (CFPropertyListCreateFromXMLData
+							(NULL, data, kCFPropertyListMutableContainersAndLeaves, &error));
+				if (error != NULL)
+					CFRelease (error);
+				CFRelease (data);
+			}
+			CFRelease (url);
+			
+			if (defaults != NULL)
+			{
+				NSMutableArray *apps, *elt;
+				int count, i;
+				NSString *name, *nname;
+				
+				/* Localize the names in the default apps menu. */
+				
+				apps = [(NSDictionary *)defaults objectForKey:@PREFS_APPSMENU];
+				if (apps != nil)
+				{
+					count = [apps count];
+					for (i = 0; i < count; i++)
+					{
+						elt = [apps objectAtIndex:i];
+						if (elt != nil && [elt isKindOfClass:[NSArray class]])
+						{
+							name = [elt objectAtIndex:0];
+							if (name != nil)
+							{
+								nname = NSLocalizedString (name, nil);
+								if (nname != nil && nname != name)
+									[elt replaceObjectAtIndex:0 withObject:nname];
+							}
+						}
+					}
+				}
+			}
+		}
+		
+		if (defaults != NULL)
+			value = CFDictionaryGetValue (defaults, key);
+		
+		if (value != NULL)
+			CFRetain (value);
+    }
+	
+    return value;
+}
+
+- (int) prefs_get_integer:(NSString *)key default:(int)def
+{
+    CFPropertyListRef value;
+    int ret;
+	
+    value = [self prefs_get:key];
+	
+    if (value != NULL && CFGetTypeID (value) == CFNumberGetTypeID ())
+		CFNumberGetValue (value, kCFNumberIntType, &ret);
+    else if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
+		ret = CFStringGetIntValue (value);
+    else
+		ret = def;
+	
+    if (value != NULL)
+		CFRelease (value);
+	
+    return ret;
+}
+
+- (const char *) prefs_get_string:(NSString *)key default:(const char *)def
+{
+    CFPropertyListRef value;
+    const char *ret = NULL;
+	
+    value = [self prefs_get:key];
+	
+    if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
+    {
+		NSString *s = (NSString *) value;
+		
+		ret = [s UTF8String];
+    }
+	
+    if (value != NULL)
+		CFRelease (value);
+	
+    return ret != NULL ? ret : def;
+}
+
+- (float) prefs_get_float:(NSString *)key default:(float)def
+{
+    CFPropertyListRef value;
+    float ret = def;
+	
+    value = [self prefs_get:key];
+	
+    if (value != NULL
+		&& CFGetTypeID (value) == CFNumberGetTypeID ()
+		&& CFNumberIsFloatType (value))
+    {
+		CFNumberGetValue (value, kCFNumberFloatType, &ret);
+    }
+    else if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
+    {
+		ret = CFStringGetDoubleValue (value);
+    }
+	
+    if (value != NULL)
+		CFRelease (value);
+	
+    return ret;
+}
+
+- (int) prefs_get_boolean:(NSString *)key default:(int)def
+{
+    CFPropertyListRef value;
+    int ret = def;
+	
+    value = [self prefs_get:key];
+	
+    if (value != NULL)
+    {
+		if (CFGetTypeID (value) == CFNumberGetTypeID ())
+			CFNumberGetValue (value, kCFNumberIntType, &ret);
+		else if (CFGetTypeID (value) == CFBooleanGetTypeID ())
+			ret = CFBooleanGetValue (value);
+		else if (CFGetTypeID (value) == CFStringGetTypeID ())
+		{
+			const char *tem = [(NSString *) value lossyCString];
+			if (strcasecmp (tem, "true") == 0 || strcasecmp (tem, "yes") == 0)
+				ret = YES;
+			else
+				ret = NO;
+		}
+		
+		CFRelease (value);
+    }
+	
+    return ret;
+}
+
+- (NSArray *) prefs_get_array:(NSString *)key
+{
+    NSArray *ret = nil;
+    CFPropertyListRef value;
+	
+    value = [self prefs_get:key];
+	
+    if (value != NULL)
+    {
+		if (CFGetTypeID (value) == CFArrayGetTypeID ())
+			ret = [cfarray_to_nsarray (value) autorelease];
+		
+		CFRelease (value);
+    }
+	
+    return ret;
+}
+
+- (void) prefs_set_integer:(NSString *)key value:(int)value
+{
+    CFNumberRef x;
+	
+    x = CFNumberCreate (NULL, kCFNumberIntType, &value);
+	
+    CFPreferencesSetValue ((CFStringRef) key, (CFTypeRef) x, CFSTR (APP_PREFS),
+						   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+	
+    CFRelease (x);
+}
+
+- (void) prefs_set_float:(NSString *)key value:(float)value
+{
+    CFNumberRef x;
+	
+    x = CFNumberCreate (NULL, kCFNumberFloatType, &value);
+	
+    CFPreferencesSetValue ((CFStringRef) key, (CFTypeRef) x, CFSTR (APP_PREFS),
+						   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+	
+    CFRelease (x);
+}
+
+- (void) prefs_set_boolean:(NSString *)key value:(int)value
+{
+    CFPreferencesSetValue ((CFStringRef) key,
+						   (CFTypeRef) value ? kCFBooleanTrue
+						   : kCFBooleanFalse, CFSTR (APP_PREFS),
+						   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+	
+}
+
+- (void) prefs_set_array:(NSString *)key value:(NSArray *)value
+{
+    CFArrayRef cfarray;
+	
+    cfarray = nsarray_to_cfarray (value);
+    CFPreferencesSetValue ((CFStringRef) key,
+						   (CFTypeRef) cfarray,
+						   CFSTR (APP_PREFS),
+						   kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+    CFRelease (cfarray);
+}
+
+- (void) prefs_set_string:(NSString *)key value:(NSString *)value
+{
+    CFPreferencesSetValue ((CFStringRef) key, (CFTypeRef) value,
+						   CFSTR (APP_PREFS), kCFPreferencesCurrentUser,
+						   kCFPreferencesAnyHost);
+}
+
+- (void) prefs_synchronize
+{
+    CFPreferencesAppSynchronize (kCFPreferencesCurrentApplication);
+}
+
+- (void) read_defaults
+{
+    const char *tem;
+	
+    quartzUseSysBeep = [self prefs_get_boolean:@PREFS_SYSBEEP
+									   default:quartzUseSysBeep];
+    quartzEnableRootless = [self prefs_get_boolean:@PREFS_ROOTLESS
+										   default:quartzEnableRootless];
+#ifdef DARWIN_DDX_MISSING
+    quartzFullscreenDisableHotkeys = ![self prefs_get_boolean:
+									   @PREFS_FULLSCREEN_HOTKEYS default:
+									   !quartzFullscreenDisableHotkeys];
+    quartzXpluginOptions = [self prefs_get_integer:@PREFS_XP_OPTIONS
+										   default:quartzXpluginOptions];
+#endif
+	
+    darwinSwapAltMeta = [self prefs_get_boolean:@PREFS_SWAP_ALT_META
+										default:darwinSwapAltMeta];
+    darwinFakeButtons = [self prefs_get_boolean:@PREFS_FAKEBUTTONS
+										default:darwinFakeButtons];
+    if (darwinFakeButtons)
+    {
+        const char *fake2, *fake3;
+		
+        fake2 = [self prefs_get_string:@PREFS_FAKE_BUTTON2 default:NULL];
+        fake3 = [self prefs_get_string:@PREFS_FAKE_BUTTON3 default:NULL];
+		
+		if (fake2 != NULL) darwinFakeMouse2Mask = DarwinParseModifierList(fake2);
+		if (fake3 != NULL) darwinFakeMouse3Mask = DarwinParseModifierList(fake3);
+		
+    }
+	
+    X11EnableKeyEquivalents = [self prefs_get_boolean:@PREFS_KEYEQUIVS
+											  default:X11EnableKeyEquivalents];
+	
+    darwinSyncKeymap = [self prefs_get_boolean:@PREFS_SYNC_KEYMAP
+									   default:darwinSyncKeymap];
+	
+    tem = [self prefs_get_string:@PREFS_KEYMAP_FILE default:NULL];
+    if (tem != NULL)
+		darwinKeymapFile = strdup (tem);
+    else
+        darwinKeymapFile = NULL;
+	
+    darwinDesiredDepth = [self prefs_get_integer:@PREFS_DEPTH
+										 default:darwinDesiredDepth];
+	
+    enable_stereo = [self prefs_get_boolean:@PREFS_ENABLE_STEREO
+									default:false];
+}
+
+/* This will end up at the end of the responder chain. */
+- (void) copy:sender
+{
+    QuartzMessageServerThread (kXDarwinPasteboardNotify, 1,
+							   AppleWMCopyToPasteboard);
+}
+
+- (BOOL) x_active
+{
+    return _x_active;
+}
+
+ at end
+
+static NSArray *
+array_with_strings_and_numbers (int nitems, const char **items,
+								const char *numbers)
+{
+    NSMutableArray *array, *subarray;
+    NSString *string;
+    NSString *number;
+    int i;
+	
+    /* (Can't autorelease on the X server thread) */
+	
+    array = [[NSMutableArray alloc] initWithCapacity:nitems];
+	
+    for (i = 0; i < nitems; i++)
+    {
+		subarray = [[NSMutableArray alloc] initWithCapacity:2];
+		
+		string = [[NSString alloc] initWithUTF8String:items[i]];
+		[subarray addObject:string];
+		[string release];
+		
+		if (numbers[i] != 0)
+		{
+			number = [[NSString alloc] initWithFormat:@"%d", numbers[i]];
+			[subarray addObject:number];
+			[number release];
+		}
+		else
+			[subarray addObject:@""];
+		
+		[array addObject:subarray];
+		[subarray release];
+    }
+	
+    return array;
+}
+
+void
+X11ApplicationSetWindowMenu (int nitems, const char **items,
+							 const char *shortcuts)
+{
+    NSArray *array;
+    array = array_with_strings_and_numbers (nitems, items, shortcuts);
+	
+    /* Send the array of strings over to the appkit thread */
+	
+    message_kit_thread (@selector (set_window_menu:), array);
+    [array release];
+}
+
+void
+X11ApplicationSetWindowMenuCheck (int idx)
+{
+    NSNumber *n;
+	
+    n = [[NSNumber alloc] initWithInt:idx];
+	
+    message_kit_thread (@selector (set_window_menu_check:), n);
+	
+    [n release];
+}
+
+void
+X11ApplicationSetFrontProcess (void)
+{
+    message_kit_thread (@selector (set_front_process:), nil);
+}
+
+void
+X11ApplicationSetCanQuit (int state)
+{
+    NSNumber *n;
+	
+    n = [[NSNumber alloc] initWithBool:state];
+	
+    message_kit_thread (@selector (set_can_quit:), n);
+	
+    [n release];
+}
+
+void
+X11ApplicationServerReady (void)
+{
+    message_kit_thread (@selector (server_ready:), nil);
+}
+
+void
+X11ApplicationShowHideMenubar (int state)
+{
+    NSNumber *n;
+	
+    n = [[NSNumber alloc] initWithBool:state];
+	
+    message_kit_thread (@selector (show_hide_menubar:), n);
+	
+    [n release];
+}
+
+static void *
+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 (void *) tid;
+}
+
+static void
+check_xinitrc (void)
+{
+    char *tem, buf[1024];
+    NSString *msg;
+	
+    if ([X11App prefs_get_boolean:@PREFS_DONE_XINIT_CHECK default:NO])
+		return;
+	
+    tem = getenv ("HOME");
+    if (tem == NULL)
+		goto done;
+	
+    snprintf (buf, sizeof (buf), "%s/.xinitrc", tem);
+    if (access (buf, F_OK) != 0)
+		goto done;
+	
+    /* FIXME: put localized strings into Resources/English.lproj */
+	
+    msg = NSLocalizedString (
+							 @"You have an existing ~/.xinitrc file.\n\n\
+							 Windows displayed by X11 applications may not have titlebars, or may look \
+							 different to windows displayed by native applications.\n\n\
+							 Would you like to move aside the existing file and use the standard X11 \
+							 environment?", @"Startup xinitrc dialog");
+	
+    if (NSRunAlertPanel (nil, msg, NSLocalizedString (@"Yes", @""),
+						 NSLocalizedString (@"No", @""), nil)
+		== NSAlertDefaultReturn)
+    {
+		char buf2[1024];
+		int i = -1;
+		
+		snprintf (buf2, sizeof (buf2), "%s.old", buf);
+		
+		for (i = 1; access (buf2, F_OK) == 0; i++)
+			snprintf (buf2, sizeof (buf2), "%s.old.%d", buf, i);
+		
+		rename (buf, buf2);
+    }
+    
+	done:
+    [X11App prefs_set_boolean:@PREFS_DONE_XINIT_CHECK value:YES];
+    [X11App prefs_synchronize];
+}
+
+void
+X11ApplicationMain (int argc, const char *argv[],
+					void (*server_thread) (void *), void *server_arg)
+{
+    NSAutoreleasePool *pool;
+	
+#ifdef DEBUG
+    while (access ("/tmp/x11-block", F_OK) == 0)
+		sleep (1);
+#endif
+	
+    pool = [[NSAutoreleasePool alloc] init];
+	
+    X11App = (X11Application *) [X11Application sharedApplication];
+	
+    init_ports ();
+	
+    [NSApp read_defaults];
+	
+    [NSBundle loadNibNamed:@"main" owner:NSApp];
+	
+    [[NSNotificationCenter defaultCenter] addObserver:NSApp
+											 selector:@selector (became_key:)
+												 name:NSWindowDidBecomeKeyNotification object:nil];
+	
+    check_xinitrc ();
+	
+    /*
+     * The xpr Quartz mode is statically linked into this server.
+     * Initialize all the Quartz functions.
+     */
+    QuartzModeBundleInit();
+	
+    /* Calculate the height of the menubar so we can avoid it. */
+    aquaMenuBarHeight = NSHeight([[NSScreen mainScreen] frame]) -
+	NSMaxY([[NSScreen mainScreen] visibleFrame]) - 1;
+	
+    if (!create_thread (server_thread, server_arg))
+    {
+		fprintf (stderr, "can't create secondary thread\n");
+		exit (1);
+    }
+	
+    [NSApp run];
+	
+    /* not reached */
+}
+
+
+/* event conversion */
+
+static inline unsigned short
+convert_flags (unsigned int nsflags)
+{
+    unsigned int xflags;
+	
+    if (nsflags == ~0) return 0xffff;
+	
+    xflags = 0;
+	
+    if (nsflags & NSAlphaShiftKeyMask)	xflags |= LockMask;
+    if (nsflags & NSShiftKeyMask)		xflags |= ShiftMask;
+    if (nsflags & NSControlKeyMask)		xflags |= ControlMask;
+    if (nsflags & NSAlternateKeyMask)	xflags |= Mod1Mask;
+    if (nsflags & NSCommandKeyMask)		xflags |= Mod2Mask;
+    /* FIXME: secondaryfn? */
+	
+    return xflags;
+}
+
+static void
+send_nsevent (NSEventType type, NSEvent *e)
+{
+    static unsigned int button_state = 0;
+    NSRect screen;
+    NSPoint location;
+    NSWindow *window;
+    int pointer_x, pointer_y;
+    xEvent xe;
+	
+    memset (&xe, 0, sizeof (xe));
+	
+    /* This field should be filled in for every event */
+    xe.u.keyButtonPointer.time = GetTimeInMillis();
+
+	/* convert location to global top-left coordinates */
+	location = [e locationInWindow];
+	window = [e window];
+	screen = [[[NSScreen screens] objectAtIndex:0] frame];
+		
+	if (window != nil)	{
+		NSRect frame = [window frame];
+		pointer_x = location.x + frame.origin.x;
+		pointer_y = (((screen.origin.y + screen.size.height)
+					  - location.y) - frame.origin.y);
+	} else {
+		pointer_x = location.x;
+		pointer_y = (screen.origin.y + screen.size.height) - location.y;
+	}
+		
+	xe.u.keyButtonPointer.rootX = pointer_x;
+	xe.u.keyButtonPointer.rootY = pointer_y;
+	
+	switch (type) {
+		float count;
+		
+    case NSLeftMouseDown:
+		xe.u.u.type = ButtonPress;
+		xe.u.u.detail = 1;
+		goto do_press_event;
+		
+    case NSRightMouseDown:
+		xe.u.u.type = ButtonPress;
+		xe.u.u.detail = 3;
+		goto do_press_event;
+		
+    case NSOtherMouseDown:
+		xe.u.u.type = ButtonPress;
+		xe.u.u.detail = 2; /* FIXME? */
+		goto do_press_event;
+		
+do_press_event:
+		if (!quartzProcs->IsX11Window([e window], [e windowNumber])) {
+			/* X server doesn't grok this window, drop the event.
+			 
+			 Note: theoretically this isn't necessary, but if I click
+			 on the menubar, we get sent a LeftMouseDown when the
+			 release happens, but no LeftMouseUp is ever seen! */
+			
+			break;
+		}
+		goto do_event;
+		
+    case NSLeftMouseUp:
+		xe.u.u.type = ButtonRelease;
+		xe.u.u.detail = 1;
+		goto do_release_event;
+		
+    case NSRightMouseUp:
+		xe.u.u.type = ButtonRelease;
+		xe.u.u.detail = 3;
+		goto do_release_event;
+		
+    case NSOtherMouseUp:
+		xe.u.u.type = ButtonRelease;
+		xe.u.u.detail = 2; /* FIXME? */
+		goto do_release_event;
+		
+do_release_event:
+		if ((button_state & (1 << xe.u.u.detail)) == 0)
+		{
+			/* X didn't see the button press for this release, so skip it */
+			break;
+		}
+		goto do_event;
+		
+    case NSMouseMoved:
+    case NSLeftMouseDragged:
+    case NSRightMouseDragged:
+    case NSOtherMouseDragged:
+		xe.u.u.type = MotionNotify;
+		goto do_event;
+		
+    case NSKeyDown:
+		xe.u.u.type = KeyPress;
+		xe.u.u.detail = [e keyCode];
+		goto do_event;
+		
+    case NSKeyUp:
+		xe.u.u.type = KeyRelease;
+		xe.u.u.detail = [e keyCode];
+		goto do_event;
+		
+    case NSScrollWheel:
+		xe.u.keyButtonPointer.state = convert_flags ([e modifierFlags]);
+		count = [e deltaY];
+		xe.u.u.detail = count > 0.0f ? 4 : 5;
+		for (count = fabs(count); count > 0.0; count = count - 1.0f) {
+			xe.u.u.type = ButtonPress;
+			DarwinEQEnqueue(&xe);
+			xe.u.u.type = ButtonRelease;
+			DarwinEQEnqueue(&xe);
+		}
+		xe.u.u.type = 0;
+		break;
+		
+    case NSFlagsChanged:
+        xe.u.u.type = kXDarwinUpdateModifiers;
+        xe.u.clientMessage.u.l.longs0 = [e modifierFlags];
+        DarwinEQEnqueue (&xe);
+        break;
+		
+do_event:
+		//	xe.u.keyButtonPointer.state = convert_flags ([e modifierFlags]);
+		DarwinEQEnqueue (&xe);
+		break;
+		
+    default: break; /* for gcc */
+    }
+	
+    if (xe.u.u.type == ButtonPress)
+		button_state |= (1 << xe.u.u.detail);
+    else if (xe.u.u.type == ButtonRelease)
+		button_state &= ~(1 << xe.u.u.detail);
+}
diff --git a/hw/darwin/apple/X11Controller.h b/hw/darwin/apple/X11Controller.h
new file mode 100644
index 0000000..954d0ab
--- /dev/null
+++ b/hw/darwin/apple/X11Controller.h
@@ -0,0 +1,86 @@
+/* X11Controller.h -- connect the IB ui
+   $Id: X11Controller.h,v 1.21 2003/07/24 17:52:29 jharper Exp $
+
+   Copyright (c) 2002 Apple Computer, 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 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.
+
+   Except as contained in this notice, the name(s) of the above
+   copyright holders shall not be used in advertising or otherwise to
+   promote the sale, use or other dealings in this Software without
+   prior written authorization. */
+
+#ifndef X11CONTROLLER_H
+#define X11CONTROLLER_H 1
+
+#if __OBJC__
+
+#import <Cocoa/Cocoa.h>
+#include "../quartz/xpr/x-list.h"
+
+ at interface X11Controller : NSObject
+{
+    NSPanel *prefs_panel;
+
+    NSButton *fake_buttons;
+    NSButton *enable_fullscreen;
+    NSButton *use_sysbeep;
+    NSButton *enable_keyequivs;
+    NSButton *sync_keymap;
+    NSButton *enable_auth;
+    NSButton *enable_tcp;
+    NSPopUpButton *depth;
+
+    NSMenuItem *x11_about_item;
+    NSMenuItem *window_separator;
+    NSMenuItem *dock_window_separator;
+    NSMenuItem *apps_separator;
+    NSMenuItem *toggle_fullscreen_item;
+    NSMenu *dock_apps_menu;
+    NSTableView *apps_table;
+
+    NSArray *apps;
+    NSMutableArray *table_apps;
+
+    NSMenu *dock_menu;
+
+    int checked_window_item;
+    x_list *pending_apps;
+
+    BOOL finished_launching;
+    BOOL can_quit;
+}
+
+- (void) set_window_menu:(NSArray *)list;
+- (void) set_window_menu_check:(NSNumber *)n;
+- (void) set_apps_menu:(NSArray *)list;
+- (void) set_can_quit:(BOOL)state;
+- (void) server_ready;
+
+ at end
+
+#endif /* __OBJC__ */
+
+extern void X11ControllerMain (int argc, const char *argv[],
+			       void (*server_thread) (void *),
+			       void *server_arg);
+
+#endif /* X11CONTROLLER_H */
diff --git a/hw/darwin/apple/X11Controller.m b/hw/darwin/apple/X11Controller.m
new file mode 100644
index 0000000..3dc965b
--- /dev/null
+++ b/hw/darwin/apple/X11Controller.m
@@ -0,0 +1,752 @@
+/* X11Controller.m -- connect the IB ui, also the NSApp delegate
+   $Id: X11Controller.m,v 1.40 2006/09/06 21:19:32 jharper Exp $
+ 
+   Copyright (c) 2002-2007 Apple 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 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.
+ 
+   Except as contained in this notice, the name(s) of the above
+   copyright holders shall not be used in advertising or otherwise to
+   promote the sale, use or other dealings in this Software without
+   prior written authorization. */
+
+#define DEFAULT_PATH "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/X11/bin"
+
+#include "../quartz/quartzCommon.h"
+
+#import "X11Controller.h"
+#import "X11Application.h"
+#import <Carbon/Carbon.h>
+
+/* ouch! */
+#define BOOL X_BOOL
+//# include "Xproto.h"
+#include "opaque.h"
+# include "darwin.h"
+# include "../quartz/quartz.h"
+# define _APPLEWM_SERVER_
+# include "X11/extensions/applewm.h"
+# include "../quartz/applewmExt.h"
+//# include "X.h"
+#undef BOOL
+
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#define TRACE() fprintf (stderr, "%s\n", __FUNCTION__)
+
+ at implementation X11Controller
+
+- (void) awakeFromNib
+{
+  X11Application *xapp = NSApp;
+  NSArray *array;
+	
+  /* Point X11Application at ourself. */
+  [xapp set_controller:self];
+	
+  array = [xapp prefs_get_array:@PREFS_APPSMENU];
+  if (array != nil)
+    {
+      int count;
+		
+      /* convert from [TITLE1 COMMAND1 TITLE2 COMMAND2 ...]
+	 to [[TITLE1 COMMAND1] [TITLE2 COMMAND2] ...] format. */
+		
+      count = [array count];
+      if (count > 0
+	  && ![[array objectAtIndex:0] isKindOfClass:[NSArray class]])
+	{
+	  int i;
+	  NSMutableArray *copy, *sub;
+			
+	  copy = [NSMutableArray arrayWithCapacity:(count / 2)];
+			
+	  for (i = 0; i < count / 2; i++)
+	    {
+	      sub = [[NSMutableArray alloc] initWithCapacity:3];
+	      [sub addObject:[array objectAtIndex:i*2]];
+	      [sub addObject:[array objectAtIndex:i*2+1]];
+	      [sub addObject:@""];
+	      [copy addObject:sub];
+	      [sub release];
+	    }
+			
+	  array = copy;
+	}
+		
+      [self set_apps_menu:array];
+    }
+}
+
+- (void) item_selected:sender
+{
+  [NSApp activateIgnoringOtherApps:YES];
+	
+  QuartzMessageServerThread (kXDarwinControllerNotify, 2,
+			     AppleWMWindowMenuItem, [sender tag]);
+}
+
+- (void) remove_window_menu
+{
+  NSMenu *menu;
+  int first, count, i;
+	
+  /* Work backwards so we don't mess up the indices */
+  menu = [window_separator menu];
+  first = [menu indexOfItem:window_separator] + 1;
+  count = [menu numberOfItems];
+  for (i = count - 1; i >= first; i--)
+    [menu removeItemAtIndex:i];
+	
+  menu = [dock_window_separator menu];
+  count = [menu indexOfItem:dock_window_separator];
+  for (i = 0; i < count; i++)
+    [dock_menu removeItemAtIndex:0];
+}
+
+- (void) install_window_menu:(NSArray *)list
+{
+  NSMenu *menu;
+  NSMenuItem *item;
+  int first, count, i;
+	
+  menu = [window_separator menu];
+  first = [menu indexOfItem:window_separator] + 1;
+  count = [list count];
+  for (i = 0; i < count; i++)
+    {
+      NSString *name, *shortcut;
+		
+      name = [[list objectAtIndex:i] objectAtIndex:0];
+      shortcut = [[list objectAtIndex:i] objectAtIndex:1];
+		
+      item = (NSMenuItem *) [menu addItemWithTitle:name action:@selector
+				  (item_selected:) keyEquivalent:shortcut];
+      [item setTarget:self];
+      [item setTag:i];
+      [item setEnabled:YES];
+		
+      item = (NSMenuItem *) [dock_menu insertItemWithTitle:name
+				       action:@selector
+				       (item_selected:) keyEquivalent:shortcut
+				       atIndex:i];
+      [item setTarget:self];
+      [item setTag:i];
+      [item setEnabled:YES];
+    }
+	
+  if (checked_window_item >= 0 && checked_window_item < count)
+    {
+      item = (NSMenuItem *) [menu itemAtIndex:first + checked_window_item];
+      [item setState:NSOnState];
+      item = (NSMenuItem *) [dock_menu itemAtIndex:checked_window_item];
+      [item setState:NSOnState];
+    }
+}
+
+- (void) remove_apps_menu
+{
+  NSMenu *menu;
+  NSMenuItem *item;
+  int i;
+	
+  if (apps == nil || apps_separator == nil) return;
+	
+  menu = [apps_separator menu];
+	
+  if (menu != nil)
+    {
+      for (i = [menu numberOfItems] - 1; i >= 0; i--)
+	{
+	  item = (NSMenuItem *) [menu itemAtIndex:i];
+	  if ([item tag] != 0)
+	    [menu removeItemAtIndex:i];
+	}
+    }
+    
+  if (dock_apps_menu != nil)
+    {
+      for (i = [dock_apps_menu numberOfItems] - 1; i >= 0; i--)
+	{
+	  item = (NSMenuItem *) [dock_apps_menu itemAtIndex:i];
+	  if ([item tag] != 0)
+	    [dock_apps_menu removeItemAtIndex:i];
+	}
+    }
+    
+  [apps release];
+  apps = nil;
+}
+
+- (void) prepend_apps_item:(NSArray *)list index:(int)i menu:(NSMenu *)menu
+{
+  NSString *title, *shortcut = @"";
+  NSArray *group;
+  NSMenuItem *item;
+	
+  group = [list objectAtIndex:i];
+  title = [group objectAtIndex:0];
+  if ([group count] >= 3)
+    shortcut = [group objectAtIndex:2];
+	
+  if ([title length] != 0)
+    {
+      item = (NSMenuItem *) [menu insertItemWithTitle:title
+				  action:@selector (app_selected:)
+				  keyEquivalent:shortcut atIndex:0];
+      [item setTarget:self];
+      [item setEnabled:YES];
+    }
+  else
+    {
+      item = (NSMenuItem *) [NSMenuItem separatorItem];
+      [menu insertItem:item atIndex:0];
+    }
+	
+  [item setTag:i+1];			/* can't be zero, so add one */
+}
+
+- (void) install_apps_menu:(NSArray *)list
+{
+  NSMenu *menu;
+  int i, count;
+	
+  count = [list count];
+	
+  if (count == 0 || apps_separator == nil) return;
+	
+  menu = [apps_separator menu];
+	
+  for (i = count - 1; i >= 0; i--)
+    {
+      if (menu != nil)
+	[self prepend_apps_item:list index:i menu:menu];
+      if (dock_apps_menu != nil)
+	[self prepend_apps_item:list index:i menu:dock_apps_menu];
+    }
+	
+  apps = [list retain];
+}
+
+- (void) set_window_menu:(NSArray *)list
+{
+  [self remove_window_menu];
+  [self install_window_menu:list];
+	
+  QuartzMessageServerThread (kXDarwinControllerNotify, 1,
+			     AppleWMWindowMenuNotify);
+}
+
+- (void) set_window_menu_check:(NSNumber *)nn
+{
+  NSMenu *menu;
+  NSMenuItem *item;
+  int first, count;
+  int n = [nn intValue];
+
+  menu = [window_separator menu];
+  first = [menu indexOfItem:window_separator] + 1;
+  count = [menu numberOfItems] - first;
+	
+  if (checked_window_item >= 0 && checked_window_item < count)
+    {
+      item = (NSMenuItem *) [menu itemAtIndex:first + checked_window_item];
+      [item setState:NSOffState];
+      item = (NSMenuItem *) [dock_menu itemAtIndex:checked_window_item];
+      [item setState:NSOffState];
+    }
+  if (n >= 0 && n < count)
+    {
+      item = (NSMenuItem *) [menu itemAtIndex:first + n];
+      [item setState:NSOnState];
+      item = (NSMenuItem *) [dock_menu itemAtIndex:n];
+      [item setState:NSOnState];
+    }
+  checked_window_item = n;
+}
+
+- (void) set_apps_menu:(NSArray *)list
+{
+  [self remove_apps_menu];
+  [self install_apps_menu:list];
+}
+
+- (void) launch_client:(NSString *)filename
+{
+  const char *command = [filename UTF8String];
+  const char *shell;
+  const char *argv[5];
+  int child1, child2 = 0;
+  int status;
+	
+  shell = getenv("SHELL");
+  if (shell == NULL) shell = "/bin/bash";
+    
+  argv[0] = shell;
+  argv[1] = "-l";
+  argv[2] = "-c";
+  argv[3] = command;
+  argv[4] = NULL;
+    
+  /* Do the fork-twice trick to avoid having to reap zombies */
+    
+  child1 = fork();
+    
+  switch (child1) {
+  case -1:                                /* error */
+    break;
+      
+  case 0:                                 /* child1 */
+    child2 = fork();
+      
+    switch (child2) {
+      int max_files, i;
+      char buf[1024], *temp;
+	
+    case -1:                            /* error */
+      _exit(1);
+	
+    case 0:                             /* child2 */
+      /* close all open files except for standard streams */
+      max_files = sysconf(_SC_OPEN_MAX);
+      for (i = 3; i < max_files; i++)	close(i);
+	
+      /* ensure stdin is on /dev/null */
+      close(0);
+      open("/dev/null", O_RDONLY);
+	
+      /* Setup environment */
+      temp = getenv("DISPLAY");
+      if (temp == NULL || temp[0] == 0) {
+	snprintf(buf, sizeof(buf), ":%s", display);
+	setenv("DISPLAY", buf, TRUE);
+      }
+	
+      temp = getenv("PATH");
+      if (temp == NULL || temp[0] == 0) 
+	setenv ("PATH", DEFAULT_PATH, TRUE);
+      else if (strnstr(temp, "/usr/X11/bin", sizeof(temp)) == NULL) {
+	snprintf(buf, sizeof(buf), "%s:/usr/X11/bin", temp);            
+	setenv("PATH", buf, TRUE);      
+      }
+      /* cd $HOME */
+      temp = getenv("HOME");
+      if (temp != NULL && temp[0]!=0) chdir(temp);
+	
+      execvp(argv[0], (char **const) argv);
+	
+      _exit(2);
+	
+    default:                            /* parent (child1) */
+      _exit(0);
+    }
+    break;
+      
+  default:                                /* parent */
+    waitpid(child1, &status, 0);
+  }
+}
+
+- (void) app_selected:sender
+{
+  int tag;
+  NSString *item;
+  
+  tag = [sender tag] - 1;
+  if (apps == nil || tag < 0 || tag >= [apps count])
+    return;
+  
+  item = [[apps objectAtIndex:tag] objectAtIndex:1];
+  
+  [self launch_client:item];
+}
+
+- (IBAction) apps_table_show:sender
+{
+  NSArray *columns;
+	
+  if (table_apps == nil) {
+    table_apps = [[NSMutableArray alloc] initWithCapacity:1];
+      
+    if (apps != nil)[table_apps addObjectsFromArray:apps];
+  }
+	
+  columns = [apps_table tableColumns];
+  [[columns objectAtIndex:0] setIdentifier:@"0"];
+  [[columns objectAtIndex:1] setIdentifier:@"1"];
+  [[columns objectAtIndex:2] setIdentifier:@"2"];
+	
+  [apps_table setDataSource:self];
+  [apps_table selectRow:0 byExtendingSelection:NO];
+	
+  [[apps_table window] makeKeyAndOrderFront:sender];
+}
+
+- (IBAction) apps_table_cancel:sender
+{
+  [[apps_table window] orderOut:sender];
+  [apps_table reloadData];
+	
+  [table_apps release];
+  table_apps = nil;
+}
+
+- (IBAction) apps_table_done:sender
+{
+  [apps_table deselectAll:sender];	/* flush edits? */
+	
+  [self remove_apps_menu];
+  [self install_apps_menu:table_apps];
+	
+  [NSApp prefs_set_array:@PREFS_APPSMENU value:table_apps];
+  [NSApp prefs_synchronize];
+	
+  [[apps_table window] orderOut:sender];
+	
+  [table_apps release];
+  table_apps = nil;
+}
+
+- (IBAction) apps_table_new:sender
+{
+  NSMutableArray *item;
+	
+  int row = [apps_table selectedRow], i;
+	
+  if (row < 0) row = 0;
+  else row = row + 1;
+	
+  i = row;
+  if (i > [table_apps count])
+    return;				/* avoid exceptions */
+	
+  [apps_table deselectAll:sender];
+	
+  item = [[NSMutableArray alloc] initWithCapacity:3];
+  [item addObject:@""];
+  [item addObject:@""];
+  [item addObject:@""];
+	
+  [table_apps insertObject:item atIndex:i];
+  [item release];
+	
+  [apps_table reloadData];
+  [apps_table selectRow:row byExtendingSelection:NO];
+}
+
+- (IBAction) apps_table_duplicate:sender
+{
+  int row = [apps_table selectedRow], i;
+  NSObject *item;
+	
+  if (row < 0) {
+    [self apps_table_new:sender];
+    return;
+  }
+	
+  i = row;
+  if (i > [table_apps count] - 1) return;				/* avoid exceptions */
+    
+  [apps_table deselectAll:sender];
+	
+  item = [[table_apps objectAtIndex:i] mutableCopy];
+  [table_apps insertObject:item atIndex:i];
+  [item release];
+	
+  [apps_table reloadData];
+  [apps_table selectRow:row+1 byExtendingSelection:NO];
+}
+
+- (IBAction) apps_table_delete:sender
+{
+  int row = [apps_table selectedRow];
+	
+  if (row >= 0)
+    {
+      int i = row;
+      
+      if (i > [table_apps count] - 1) return;			/* avoid exceptions */
+      
+      [apps_table deselectAll:sender];
+      
+      [table_apps removeObjectAtIndex:i];
+    }
+	
+  [apps_table reloadData];
+	
+  row = MIN (row, [table_apps count] - 1);
+  if (row >= 0)
+    [apps_table selectRow:row byExtendingSelection:NO];
+}
+
+- (int) numberOfRowsInTableView:(NSTableView *)tableView
+{
+  if (table_apps == nil) return 0;
+  
+  return [table_apps count];
+}
+
+- (id) tableView:(NSTableView *)tableView
+objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
+{
+  NSArray *item;
+  int col;
+	
+  if (table_apps == nil) return nil;
+	
+  col = [[tableColumn identifier] intValue];
+	
+  item = [table_apps objectAtIndex:row];
+  if ([item count] > col)
+    return [item objectAtIndex:col];
+  else
+    return @"";
+}
+
+- (void) tableView:(NSTableView *)tableView setObjectValue:(id)object
+    forTableColumn:(NSTableColumn *)tableColumn row:(int)row
+{
+  NSMutableArray *item;
+  int col;
+	
+  if (table_apps == nil) return;
+	
+  col = [[tableColumn identifier] intValue];
+	
+  item = [table_apps objectAtIndex:row];
+  [item replaceObjectAtIndex:col withObject:object];
+}
+
+- (void) hide_window:sender
+{
+  if ([X11App x_active])
+    QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMHideWindow);
+  else
+    NSBeep ();			/* FIXME: something here */
+}
+
+- (IBAction)bring_to_front:sender
+{
+  QuartzMessageServerThread(kXDarwinControllerNotify, 1, AppleWMBringAllToFront);
+}
+
+- (IBAction)close_window:sender
+{
+  if ([X11App x_active])
+    QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMCloseWindow);
+  else
+    [[NSApp keyWindow] performClose:sender];
+}
+
+- (IBAction)minimize_window:sender
+{
+  if ([X11App x_active])
+    QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMMinimizeWindow);
+  else
+    [[NSApp keyWindow] performMiniaturize:sender];
+}
+
+- (IBAction)zoom_window:sender
+{
+  if ([X11App x_active])
+    QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMZoomWindow);
+  else
+    [[NSApp keyWindow] performZoom:sender];
+}
+
+- (IBAction) next_window:sender
+{
+  QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMNextWindow);
+}
+
+- (IBAction) previous_window:sender
+{
+  QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMPreviousWindow);
+}
+
+- (IBAction) enable_fullscreen_changed:sender
+{
+  int value = ![enable_fullscreen intValue];
+	
+#ifdef DARWIN_DDX_MISSING
+  QuartzMessageServerThread (kXDarwinSetRootless, 1, value);
+#endif
+	
+  [NSApp prefs_set_boolean:@PREFS_ROOTLESS value:value];
+  [NSApp prefs_synchronize];
+}
+
+- (IBAction) toggle_fullscreen:sender
+{
+#ifdef DARWIN_DDX_MISSING
+  QuartzMessageServerThread (kXDarwinToggleFullscreen, 0);
+#endif
+}
+
+- (void) set_can_quit:(BOOL)state
+{
+  can_quit = state;
+}
+
+- (IBAction)prefs_changed:sender
+{
+  darwinFakeButtons = [fake_buttons intValue];
+  quartzUseSysBeep = [use_sysbeep intValue];
+  X11EnableKeyEquivalents = [enable_keyequivs intValue];
+  darwinSyncKeymap = [sync_keymap intValue];
+	
+  /* after adding prefs here, also add to [X11Application read_defaults]
+     and below */
+	
+  [NSApp prefs_set_boolean:@PREFS_FAKEBUTTONS value:darwinFakeButtons];
+  [NSApp prefs_set_boolean:@PREFS_SYSBEEP value:quartzUseSysBeep];
+  [NSApp prefs_set_boolean:@PREFS_KEYEQUIVS value:X11EnableKeyEquivalents];
+  [NSApp prefs_set_boolean:@PREFS_SYNC_KEYMAP value:darwinSyncKeymap];
+  [NSApp prefs_set_boolean:@PREFS_NO_AUTH value:![enable_auth intValue]];
+  [NSApp prefs_set_boolean:@PREFS_NO_TCP value:![enable_tcp intValue]];
+  [NSApp prefs_set_integer:@PREFS_DEPTH value:[depth selectedTag]];
+	
+  [NSApp prefs_synchronize];
+}
+
+- (IBAction) prefs_show:sender
+{
+  [fake_buttons setIntValue:darwinFakeButtons];
+  [use_sysbeep setIntValue:quartzUseSysBeep];
+  [enable_keyequivs setIntValue:X11EnableKeyEquivalents];
+  [sync_keymap setIntValue:darwinSyncKeymap];
+  [sync_keymap setEnabled:darwinKeymapFile == NULL];
+	
+  [enable_auth setIntValue:![NSApp prefs_get_boolean:@PREFS_NO_AUTH default:NO]];
+  [enable_tcp setIntValue:![NSApp prefs_get_boolean:@PREFS_NO_TCP default:NO]];
+  [depth selectItemAtIndex:[depth indexOfItemWithTag:[NSApp prefs_get_integer:@PREFS_DEPTH default:-1]]];
+	
+  [enable_fullscreen setIntValue:!quartzEnableRootless];
+	
+  [prefs_panel makeKeyAndOrderFront:sender];
+}
+
+- (IBAction) quit:sender
+{
+  QuartzMessageServerThread (kXDarwinQuit, 0);
+}
+
+- (IBAction) x11_help:sender
+{
+  AHLookupAnchor (CFSTR ("Mac Help"), CFSTR ("mchlp2276"));
+}
+
+- (BOOL) validateMenuItem:(NSMenuItem *)item
+{
+  NSMenu *menu = [item menu];
+	
+  if (item == toggle_fullscreen_item)
+    return !quartzEnableRootless;
+  else if (menu == [window_separator menu] || menu == dock_menu
+	   || (menu == [x11_about_item menu] && [item tag] == 42))
+    return (AppleWMSelectedEvents () & AppleWMControllerNotifyMask) != 0;
+  else
+    return TRUE;
+}
+
+- (void) applicationDidHide:(NSNotification *)notify
+{
+  QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMHideAll);
+}
+
+- (void) applicationDidUnhide:(NSNotification *)notify
+{
+  QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMShowAll);
+}
+
+- (NSApplicationTerminateReply) applicationShouldTerminate:sender
+{
+  NSString *msg;
+	
+  if (can_quit || [X11App prefs_get_boolean:@PREFS_NO_QUIT_ALERT default:NO])
+    return NSTerminateNow;
+	
+  /* Make sure we're frontmost. */
+  [NSApp activateIgnoringOtherApps:YES];
+	
+  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");
+	
+  /* 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;
+}
+
+- (void) applicationWillTerminate:(NSNotification *)aNotification
+{
+  [X11App prefs_synchronize];
+	
+  /* shutdown the X server, it will exit () for us. */
+  QuartzMessageServerThread (kXDarwinQuit, 0);
+	
+  /* In case it doesn't, exit anyway after a while. */
+  while (sleep (10) != 0) ;
+  exit (1);
+}
+
+- (void) server_ready
+{
+  x_list *node;
+	
+  finished_launching = YES;
+	
+  for (node = pending_apps; node != NULL; node = node->next)
+    {
+      NSString *filename = node->data;
+      [self launch_client:filename];
+      [filename release];
+    }
+	
+  x_list_free (pending_apps);
+  pending_apps = NULL;
+}
+
+- (BOOL) application:(NSApplication *)app openFile:(NSString *)filename
+{
+  const char *name = [filename UTF8String];
+	
+  if (finished_launching)
+    [self launch_client:filename];
+  else if (name[0] != ':')		/* ignore display names */
+    pending_apps = x_list_prepend (pending_apps, [filename retain]);
+	
+  /* FIXME: report failures. */
+  return YES;
+}
+
+ at end
+
+void X11ControllerMain (int argc, const char *argv[],
+			void (*server_thread) (void *), void *server_arg)
+{
+  X11ApplicationMain (argc, argv, server_thread, server_arg);
+}
diff --git a/hw/darwin/apple/Xquartz.man b/hw/darwin/apple/Xquartz.man
new file mode 100644
index 0000000..edac30e
--- /dev/null
+++ b/hw/darwin/apple/Xquartz.man
@@ -0,0 +1,158 @@
+.\" $XFree86: xc/programs/Xserver/hw/darwin/XDarwin.man,v 1.4 2002/01/09 18:01:58 torrey Exp $
+.\"
+.TH XQUARTZ 1 __vendorversion__
+.SH NAME
+Xquartz \- X window system server for Quartz operating system
+.SH SYNOPSIS
+.B Xquartz
+[ options ] ...
+.SH DESCRIPTION
+.I Xquartz
+is the X window server for Mac OS X provided by Apple.
+.I Xquartz
+runs in parallel with Aqua in rootless mode. In rootless mode, the X
+window system and Mac OS X share your display.  The root window of the
+X11 display is the size of the screen and contains all the other
+windows. The X11 root window is not displayed in rootless mode as Mac
+OS X handles the desktop background.
+.SH OPTIONS
+.PP
+In addition to the normal server options described in the \fIXserver(1)\fP
+manual page, \fIXquartz\fP accepts the following command line switches:
+.TP 8
+.B \-fakebuttons
+Emulates a 3 button mouse using modifier keys. By default, the Command modifier
+is used to emulate button 2 and Option is used for button 3. Thus, clicking the
+first mouse button while holding down Command will act like clicking
+button 2. Holding down Option will simulate button 3.
+.TP 8
+.B \-nofakebuttons
+Do not emulate a 3 button mouse. This is the default.
+.TP 8
+.B "\-fakemouse2 \fImodifiers\fP"
+Change the modifier keys used to emulate the second mouse button. By default,
+Command is used to emulate the second button. Any combination of the following
+modifier names may be used: Shift, Option, Control, Command, Fn. For example,
+.B \-fakemouse2 """Option,Shift""
+will set holding Option, Shift and clicking on button one as equivalent to
+clicking the second mouse button.
+.TP 8
+.B "\-fakemouse3 \fImodifiers\fP"
+Change the modifier keys used to emulate the third mouse button. By default,
+Option is used to emulate the third button. Any combination of the following
+modifier names may be used: Shift, Option, Control, Command, Fn. For example,
+.B \-fakemouse3 """Control,Shift""
+will set holding Control, Shift and clicking on button one as equivalent to
+clicking the third mouse button.
+.TP 8
+.B "\-swapAltMeta"
+Swaps the meaning of the Alt and Meta modifier keys.
+.TP 8
+.B "\-keymap \fIfile\fP"
+On startup \fIXquartz\fP translates a Darwin keymapping into an X keymap.
+The default is to read this keymapping from USA.keymapping. With this option
+the keymapping will be read from \fIfile\fP instead. If the file's path is
+not specified, it will be searched for in Library/Keyboards/ underneath the
+following directories (in order): ~, /, /Network, /System.
+.TP 8
+.B \-nokeymap
+On startup \fIXquartz\fP translates a Darwin keymapping into an X keymap.
+With this option \fIXquartz\fP queries the kernel for the current keymapping
+instead of reading it from a file. This will often fail on newer kernels.
+.TP 8
+.B "\-depth \fIdepth\fP"
+Specifies the color bit depth to use. Currently only 15, and 24 color
+bits per pixel are supported. If not specified, defaults to the depth
+of the main display.
+.SH CUSTOMIZATION
+\fIXquartz\fP can also be customized using the defaults(1) command. The available options are:
+.TP 8
+.B defaults write com.apple.x11 enable_fake_buttons -boolean true
+Equivalent to the \fB-fakebuttons\fP command line option.
+.TP 8
+.B defaults write com.apple.x11 fake_button2 \fImodifiers\fP
+Equivalent to the \fB-fakemouse2\fP option.
+.TP 8
+.B defaults write com.apple.x11 fake_button3 \fImodifiers\fP
+Equivalent to the \fB-fakemouse3\fP option.
+.TP 8
+.B defaults write com.apple.x11 swap_alt_meta -boolean true
+Equivalent to the \fB-swapAltMeta\fP option.
+.TP 8
+.B defaults write com.apple.x11 keymap_file \fIfilename\fP
+Equivalent to the \fB-keymap\fP option.
+.TP 8
+.B defaults write com.apple.x11 no_quit_alert -boolean true
+Disables the alert dialog displayed when attempting to quit X11.
+.TP 8
+.B defaults write com.apple.x11 no_auth -boolean true
+Stops the X server requiring that clients authenticate themselves when
+connecting. See Xsecurity(__miscmansuffix__).
+.TP 8
+.B defaults write com.apple.x11 nolisten_tcp -boolean true
+Prevents the X server accepting remote connections.
+.TP 8
+.B defaults write com.apple.x11 xinit_kills_server -boolean false
+Stops the X server exiting when the xinitrc script terminates.
+.TP 8
+.B defaults write com.apple.x11 fullscreen_hotkeys -boolean false
+Allows system hotkeys to be handled while in X11 fullscreen mode.
+.TP 8
+.B defaults write com.apple.x11 enable_system_beep -boolean false
+Don't use the standard system beep effect for X11 alerts.
+.TP 8
+.B defaults write com.apple.x11 enable_key_equivalents -boolean false
+Disable menu keyboard equivalents while X11 windows are focused.
+.TP 8
+.B defaults write com.apple.x11 depth \fIdepth\fP
+Equivalent to the \fB-depth\fP option.
+.SH "SEE ALSO"
+.PP
+X(__miscmansuffix__), XFree86(1), Xserver(1), xdm(1), xinit(1)
+.PP
+.SH AUTHORS
+XFree86 was originally ported to Mac OS X Server by John Carmack. Dave
+Zarzycki used this as the basis of his port of XFree86 4.0 to Darwin 1.0.
+Torrey T. Lyons improved and integrated this code into the XFree86
+Project's mainline for the 4.0.2 release.
+.PP
+The following members of the XonX Team contributed to the following
+releases (in alphabetical order):
+.TP 4
+XFree86 4.1.0:
+.br
+Rob Braun - Darwin x86 support
+.br
+Torrey T. Lyons - Project Lead
+.br
+Andreas Monitzer - Cocoa version of XDarwin front end
+.br
+Gregory Robert Parker - Original Quartz implementation
+.br
+Christoph Pfisterer - Dynamic shared X libraries
+.br
+Toshimitsu Tanaka - Japanese localization
+.TP 4
+XFree86 4.2.0:
+.br
+Rob Braun - Darwin x86 support
+.br
+Pablo Di Noto - Spanish localization
+.br
+Paul Edens - Dutch localization
+.br
+Kyunghwan Kim - Korean localization
+.br
+Mario Klebsch - Non-US keyboard support
+.br
+Torrey T. Lyons - Project Lead
+.br
+Andreas Monitzer - German localization
+.br
+Patrik Montgomery - Swedish localization
+.br
+Greg Parker - Rootless support
+.br
+Toshimitsu Tanaka - Japanese localization
+.br
+Olivier Verdier - French localization
diff --git a/hw/darwin/apple/bundle-main.c b/hw/darwin/apple/bundle-main.c
new file mode 100644
index 0000000..12fb1bf
--- /dev/null
+++ b/hw/darwin/apple/bundle-main.c
@@ -0,0 +1,911 @@
+/* bundle-main.c -- X server launcher
+ $Id: bundle-main.c,v 1.17 2003/09/11 00:17:10 jharper Exp $
+ 
+ Copyright (c) 2002-2007 Apple 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 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.
+ 
+ Except as contained in this notice, the name(s) of the above
+ copyright holders shall not be used in advertising or otherwise to
+ promote the sale, use or other dealings in this Software without
+ prior written authorization.
+ 
+ Parts of this file are derived from xdm, which has this copyright:
+ 
+ Copyright 1988, 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. */
+
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <sys/socket.h>
+#include <sys/utsname.h>
+#include <ifaddrs.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <time.h>
+#include <sys/wait.h>
+#include <setjmp.h>
+#include <sys/ioctl.h>
+
+#include <X11/Xlib.h>
+#include <X11/Xauth.h>
+
+#include <CoreFoundation/CoreFoundation.h>
+#include <SystemConfiguration/SystemConfiguration.h>
+
+#define X_SERVER "/usr/X11/bin/Xquartz"
+#define XTERM_PATH "/usr/X11/bin/xterm"
+#define WM_PATH "/usr/X11/bin/quartz-wm"
+#define DEFAULT_XINITRC "/etc/X11/xinit/xinitrc"
+#define DEFAULT_PATH "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/X11/bin"
+
+/* what xinit does */
+#ifndef SHELL
+# define SHELL "sh"
+#endif
+
+#undef FALSE
+#define FALSE 0
+#undef TRUE
+#define TRUE 1
+
+#define MAX_DISPLAYS 64
+
+static int server_pid = -1, client_pid = -1;
+static int xinit_kills_server = FALSE;
+static jmp_buf exit_continuation;
+static const char *server_name = NULL;
+static Display *server_dpy;
+
+static char *auth_file;
+
+typedef struct addr_list_struct addr_list;
+
+struct addr_list_struct {
+    addr_list *next;
+    Xauth auth;
+};
+
+static addr_list *addresses;
+
+
+/* Utility functions. */
+
+/* Return the current host name. Matches what Xlib does. */
+static char *
+host_name (void)
+{
+#ifdef NEED_UTSNAME
+    static struct utsname name;
+	
+    uname(&name);
+	
+    return name.nodename;
+#else
+    static char buf[100];
+	
+    gethostname(buf, sizeof(buf));
+	
+    return buf;
+#endif
+}
+
+static int
+read_boolean_pref (CFStringRef name, int default_)
+{
+    int value;
+    Boolean ok;
+	
+    value = CFPreferencesGetAppBooleanValue (name,
+											 CFSTR ("com.apple.x11"), &ok);
+    return ok ? value : default_;
+}
+
+static inline int
+binary_equal (const void *a, const void *b, int length)
+{
+    return memcmp (a, b, length) == 0;
+}
+
+static inline void *
+binary_dup (const void *a, int length)
+{
+    void *b = malloc (length);
+    if (b != NULL)
+		memcpy (b, a, length);
+    return b;
+}
+
+static inline void
+binary_free (void *data, int length)
+{
+    if (data != NULL)
+		free (data);
+}
+
+
+/* Functions for managing the authentication entries. */
+
+/* Returns true if something matching AUTH is in our list of auth items */
+static int
+check_auth_item (Xauth *auth)
+{
+    addr_list *a;
+	
+    for (a = addresses; a != NULL; a = a->next)
+    {
+		if (a->auth.family == auth->family
+			&& a->auth.address_length == auth->address_length
+			&& binary_equal (a->auth.address, auth->address, auth->address_length)
+			&& a->auth.number_length == auth->number_length
+			&& binary_equal (a->auth.number, auth->number, auth->number_length)
+			&& a->auth.name_length == auth->name_length
+			&& binary_equal (a->auth.name, auth->name, auth->name_length))
+		{
+			return TRUE;
+		}
+    }
+	
+    return FALSE;
+}
+
+/* Add one item to our list of auth items. */
+static void
+add_auth_item (Xauth *auth)
+{
+    addr_list *a = malloc (sizeof (addr_list));
+	
+    a->auth.family = auth->family;
+    a->auth.address_length = auth->address_length;
+    a->auth.address = binary_dup (auth->address, auth->address_length);
+    a->auth.number_length = auth->number_length;
+    a->auth.number = binary_dup (auth->number, auth->number_length);
+    a->auth.name_length = auth->name_length;
+    a->auth.name = binary_dup (auth->name, auth->name_length);
+    a->auth.data_length = auth->data_length;
+    a->auth.data = binary_dup (auth->data, auth->data_length);
+	
+    a->next = addresses;
+    addresses = a;
+}
+
+/* Free all allocated auth items. */
+static void
+free_auth_items (void)
+{
+    addr_list *a;
+	
+    while ((a = addresses) != NULL)
+    {
+		addresses = a->next;
+		
+		binary_free (a->auth.address, a->auth.address_length);
+		binary_free (a->auth.number, a->auth.number_length);
+		binary_free (a->auth.name, a->auth.name_length);
+		binary_free (a->auth.data, a->auth.data_length);
+		free (a);
+    }
+}
+
+/* Add the unix domain auth item. */
+static void
+define_local (Xauth *auth)
+{
+    char *host = host_name ();
+	
+#ifdef DEBUG
+    fprintf (stderr, "x11: hostname is %s\n", host);
+#endif
+	
+    auth->family = FamilyLocal;
+    auth->address_length = strlen (host);
+    auth->address = host;
+	
+    add_auth_item (auth);
+}
+
+/* Add the tcp auth item. */
+static void
+define_named (Xauth *auth, const char *name)
+{
+    struct ifaddrs *addrs, *ptr;
+	
+    if (getifaddrs (&addrs) != 0)
+		return;
+	
+    for (ptr = addrs; ptr != NULL; ptr = ptr->ifa_next)
+    {
+		if (ptr->ifa_addr->sa_family != AF_INET)
+			continue;
+		
+		auth->family = FamilyInternet;
+		auth->address_length = sizeof (struct in_addr);
+		auth->address = (char *) &(((struct sockaddr_in *) ptr->ifa_addr)->sin_addr);
+		
+#ifdef DEBUG
+		fprintf (stderr, "x11: ipaddr is %d.%d.%d.%d\n",
+				 (unsigned char) auth->address[0],
+				 (unsigned char) auth->address[1],
+				 (unsigned char) auth->address[2],
+				 (unsigned char) auth->address[3]);
+#endif
+		
+		add_auth_item (auth);
+    }
+	
+    freeifaddrs (addrs);
+}
+
+/* Parse the display number from NAME and add it to AUTH. */
+static void
+set_auth_number (Xauth *auth, const char *name)
+{
+    char *colon;
+    char *dot, *number;
+	
+    colon = strrchr(name, ':');
+    if (colon != NULL)
+    {
+		colon++;
+		dot = strchr(colon, '.');
+		
+		if (dot != NULL)
+			auth->number_length = dot - colon;
+		else
+			auth->number_length = strlen (colon);
+		
+		number = malloc (auth->number_length + 1);
+		if (number != NULL)
+		{
+			strncpy (number, colon, auth->number_length);
+			number[auth->number_length] = '\0';
+		}
+		else
+		{
+			auth->number_length = 0;
+		}
+		
+		auth->number = number;
+    }
+}
+
+/* Put 128 bits of random data into DATA. If possible, it will be "high
+ quality" */
+static int
+generate_mit_magic_cookie (char data[16])
+{
+    int fd, ret, i;
+    long *ldata = (long *) data;
+	
+    fd = open ("/dev/random", O_RDONLY);
+    if (fd > 0) {
+		ret = read (fd, data, 16);
+		close (fd);
+		if (ret == 16) return TRUE;
+    }
+	
+    /* fall back to the usual crappy rng */
+	
+    srand48 (getpid () ^ time (NULL));
+	
+    for (i = 0; i < 4; i++)
+		ldata[i] = lrand48 ();
+	
+    return TRUE;
+}
+
+/* Create the keys we'll be using for the display named NAME. */
+static int
+make_auth_keys (const char *name)
+{
+    Xauth auth;
+    char key[16];
+	
+    if (auth_file == NULL)
+		return FALSE;
+	
+    auth.name = "MIT-MAGIC-COOKIE-1";
+    auth.name_length = strlen (auth.name);
+	
+    if (!generate_mit_magic_cookie (key))
+    {
+		auth_file = NULL;
+		return FALSE;
+    }
+	
+    auth.data = key;
+    auth.data_length = 16;
+	
+    set_auth_number (&auth, name);
+	
+    define_named (&auth, host_name ());
+    define_local (&auth);
+	
+    free (auth.number);
+	
+    return TRUE;
+}
+
+/* If ADD-ENTRIES is true, merge our auth entries into the existing
+ Xauthority file. If ADD-ENTRIES is false, remove our entries. */
+static int
+write_auth_file (int add_entries)
+{
+    char *home, newname[1024];
+    int fd, ret;
+    FILE *new_fh, *old_fh;
+    addr_list *addr;
+    Xauth *auth;
+	
+    if (auth_file == NULL)
+		return FALSE;
+	
+    home = getenv ("HOME");
+    if (home == NULL)
+    {
+		auth_file = NULL;
+		return FALSE;
+    }
+	
+    snprintf (newname, sizeof (newname), "%s/.XauthorityXXXXXX", home);
+    mktemp (newname);
+	
+    if (XauLockAuth (auth_file, 1, 2, 10) != LOCK_SUCCESS)
+    {
+		/* FIXME: do something here? */
+		
+		auth_file = NULL;
+		return FALSE;
+    }
+	
+    fd = open (newname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
+    if (fd >= 0)
+    {
+		new_fh = fdopen (fd, "w");
+		if (new_fh != NULL)
+		{
+			if (add_entries)
+			{
+				for (addr = addresses; addr != NULL; addr = addr->next)
+				{
+					XauWriteAuth (new_fh, &addr->auth);
+				}
+			}
+			
+			old_fh = fopen (auth_file, "r");
+			if (old_fh != NULL)
+			{
+				while ((auth = XauReadAuth (old_fh)) != NULL)
+				{
+					if (!check_auth_item (auth))
+						XauWriteAuth (new_fh, auth);
+					XauDisposeAuth (auth);
+				}
+				fclose (old_fh);
+			}
+			
+			fclose (new_fh);
+			unlink (auth_file);
+			
+			ret = rename (newname, auth_file);
+			
+			if (ret != 0)
+				auth_file = NULL;
+			
+			XauUnlockAuth (auth_file);
+			return ret == 0;
+		}
+		
+		close (fd);
+    }
+	
+    XauUnlockAuth (auth_file);
+    auth_file = NULL;
+    return FALSE;
+}
+
+
+/* Subprocess management functions. */
+
+static int
+start_server (char **xargv)
+{
+    int child;
+	
+    child = fork ();
+	
+    switch (child)
+    {
+    case -1:				/* error */
+		perror ("fork");
+		return FALSE;
+		
+    case 0:				/* child */
+		execv (X_SERVER, xargv);
+		perror ("Couldn't exec " X_SERVER);
+		_exit (1);
+		
+    default:				/* parent */
+		server_pid = child;
+		return TRUE;
+    }
+}
+
+static int
+wait_for_server (void)
+{
+    int count = 100;
+	
+    while (count-- > 0)
+    {
+		int status;
+		
+		server_dpy = XOpenDisplay (server_name);
+		if (server_dpy != NULL)
+			return TRUE;
+		
+		if (waitpid (server_pid, &status, WNOHANG) == server_pid)
+			return FALSE;
+		
+		sleep (1);
+    }
+	
+    return FALSE;
+}
+
+static int
+start_client (void)
+{
+    int child;
+	
+    child = fork();
+	
+    switch (child) {
+		char *temp, buf[1024];		
+
+	case -1:				/* error */
+		perror("fork");
+		return FALSE;
+
+	case 0:					/* child */
+		/* Setup environment */
+		temp = getenv("DISPLAY");
+		if (temp != NULL && temp[0] != 0)
+			setenv("DISPLAY", server_name, TRUE);
+
+		temp = getenv("PATH");
+		if (temp == NULL || temp[0] == 0) 
+			setenv ("PATH", DEFAULT_PATH, TRUE);
+		else if (strnstr(temp, "/usr/X11/bin", sizeof(temp)) == NULL) {
+			snprintf(buf, sizeof(buf), "%s:/usr/X11/bin", temp);		
+			setenv("PATH", buf, TRUE);	
+		}
+		
+		/* First try value of $XINITRC, if set. */
+		temp = getenv("XINITRC");
+		if (temp != NULL && temp[0] != 0 && access(temp, R_OK) == 0)
+			execlp (SHELL, SHELL, temp, NULL);
+
+		/* Then look for .xinitrc in user's home directory. */
+		temp = getenv("HOME");
+		if (temp != NULL && temp[0] != 0) {
+			chdir(temp);
+			snprintf (buf, sizeof (buf), "%s/.xinitrc", temp);
+			if (access(buf, R_OK) == 0)
+				execlp(SHELL, SHELL, buf, NULL);
+		}
+		
+		/* Then try the default xinitrc in the lib directory. */
+		
+		if (access(DEFAULT_XINITRC, R_OK) == 0)
+			execlp(SHELL, SHELL, DEFAULT_XINITRC, NULL);
+		
+		/* Then fallback to hardcoding an xterm and the window manager. */
+		
+		//		system(XTERM_PATH " &");
+		execl(WM_PATH, WM_PATH, NULL);
+		
+		perror("exec");
+		_exit(1);
+		
+    default:				/* parent */
+		client_pid = child;
+		return TRUE;
+    }
+}
+
+static void
+sigchld_handler (int sig)
+{
+    int pid, status;
+	
+	again:
+    pid = waitpid (WAIT_ANY, &status, WNOHANG);
+	
+    if (pid > 0)
+    {
+		if (pid == server_pid)
+		{
+			server_pid = -1;
+			
+			if (client_pid >= 0)
+				kill (client_pid, SIGTERM);
+		}
+		else if (pid == client_pid)
+		{
+			client_pid = -1;
+			
+			if (server_pid >= 0 && xinit_kills_server)
+				kill (server_pid, SIGTERM);
+		}
+		goto again;
+    }
+	
+    if (server_pid == -1 && client_pid == -1)
+		longjmp (exit_continuation, 1);
+	
+    signal (SIGCHLD, sigchld_handler);
+}
+
+
+/* Server utilities. */
+
+static Boolean
+display_exists_p (int number)
+{
+    char buf[64];
+    void *conn;
+    char *fullname = NULL;
+    int idisplay, iscreen;
+    char *conn_auth_name, *conn_auth_data;
+    int conn_auth_namelen, conn_auth_datalen;
+	
+    extern void *_X11TransConnectDisplay ();
+    extern void _XDisconnectDisplay ();
+	
+    /* Since connecting to the display waits for a few seconds if the
+	 display doesn't exist, check for trivial non-existence - if the
+	 socket in /tmp exists or not.. (note: if the socket exists, the
+	 server may still not, so we need to try to connect in that case..) */
+	
+    sprintf (buf, "/tmp/.X11-unix/X%d", number);
+    if (access (buf, F_OK) != 0)
+		return FALSE;
+	
+    /* This is a private function that we shouldn't really be calling,
+	 but it's the best way to see if the server exists (without
+	 needing to hold the necessary authentication to use it) */
+	
+    sprintf (buf, ":%d", number);
+    conn = _X11TransConnectDisplay (buf, &fullname, &idisplay, &iscreen,
+									&conn_auth_name, &conn_auth_namelen,
+									&conn_auth_data, &conn_auth_datalen);
+    if (conn == NULL)
+		return FALSE;
+	
+    _XDisconnectDisplay (conn);
+    return TRUE;
+}
+
+
+/* Monitoring when the system's ip addresses change. */
+
+static Boolean pending_timer;
+
+static void
+timer_callback (CFRunLoopTimerRef timer, void *info)
+{
+    pending_timer = FALSE;
+	
+    /* Update authentication names. Need to write .Xauthority file first
+	 without the existing entries, then again with the new entries.. */
+	
+    write_auth_file (FALSE);
+	
+    free_auth_items ();
+    make_auth_keys (server_name);
+	
+    write_auth_file (TRUE);
+}
+
+/* This function is called when the system's ip addresses may have changed. */
+static void
+ipaddr_callback (SCDynamicStoreRef store, CFArrayRef changed_keys, void *info)
+{
+#if DEBUG
+    if (changed_keys != NULL) {
+		fprintf (stderr, "x11: changed sc keys: ");
+		CFShow (changed_keys);
+    }
+#endif
+
+    if (auth_file != NULL && !pending_timer)
+    {
+		CFRunLoopTimerRef timer;
+		
+		timer = CFRunLoopTimerCreate (NULL, CFAbsoluteTimeGetCurrent () + 1.0,
+									  0.0, 0, 0, timer_callback, NULL);
+		CFRunLoopAddTimer (CFRunLoopGetCurrent (), timer,
+						   kCFRunLoopDefaultMode);
+		CFRelease (timer);
+		
+		pending_timer = TRUE;
+    }
+}
+
+/* This code adapted from "Living in a Dynamic TCP/IP Environment" technote. */
+static Boolean
+install_ipaddr_source (void)
+{
+    CFRunLoopSourceRef source = NULL;
+	
+    SCDynamicStoreContext context = {0};
+    SCDynamicStoreRef ref;
+	
+    ref = SCDynamicStoreCreate (NULL,
+								CFSTR ("AddIPAddressListChangeCallbackSCF"),
+								ipaddr_callback, &context);
+	
+    if (ref != NULL)
+    {
+		const void *keys[4], *patterns[2];
+		int i;
+		
+		keys[0] = SCDynamicStoreKeyCreateNetworkGlobalEntity (NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4);
+		keys[1] = SCDynamicStoreKeyCreateNetworkGlobalEntity (NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6);
+		keys[2] = SCDynamicStoreKeyCreateComputerName (NULL);
+		keys[3] = SCDynamicStoreKeyCreateHostNames (NULL);
+		
+		patterns[0] = SCDynamicStoreKeyCreateNetworkInterfaceEntity (NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4);
+		patterns[1] = SCDynamicStoreKeyCreateNetworkInterfaceEntity (NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv6);
+		
+		if (keys[0] != NULL && keys[1] != NULL && keys[2] != NULL
+			&& keys[3] != NULL && patterns[0] != NULL && patterns[1] != NULL)
+		{
+			CFArrayRef key_array, pattern_array;
+			
+			key_array = CFArrayCreate (NULL, keys, 4, &kCFTypeArrayCallBacks);
+			pattern_array = CFArrayCreate (NULL, patterns, 2, &kCFTypeArrayCallBacks);
+			
+			if (key_array != NULL || pattern_array != NULL)
+			{
+				SCDynamicStoreSetNotificationKeys (ref, key_array, pattern_array);
+				source = SCDynamicStoreCreateRunLoopSource (NULL, ref, 0);
+			}
+			
+			if (key_array != NULL)
+				CFRelease (key_array);
+			if (pattern_array != NULL)
+				CFRelease (pattern_array);
+		}
+		
+		
+		for (i = 0; i < 4; i++)
+			if (keys[i] != NULL)
+			CFRelease (keys[i]);
+		for (i = 0; i < 2; i++)
+			if (patterns[i] != NULL)
+			CFRelease (patterns[i]);
+		
+		CFRelease (ref); 
+    }
+	
+    if (source != NULL)
+    {
+		CFRunLoopAddSource (CFRunLoopGetCurrent (),
+							source, kCFRunLoopDefaultMode);
+		CFRelease (source);
+    }
+	
+    return source != NULL;
+}
+
+
+/* Entrypoint. */
+
+void
+termination_signal_handler (int unused_sig)
+{
+    signal (SIGTERM, SIG_DFL);
+    signal (SIGHUP, SIG_DFL);
+    signal (SIGINT, SIG_DFL);
+    signal (SIGQUIT, SIG_DFL);
+
+    longjmp (exit_continuation, 1);
+}
+
+int
+main (int argc, char **argv)
+{
+    char **xargv;
+    int i, j;
+    int fd;
+	
+    xargv = alloca (sizeof (char *) * (argc + 32));
+	
+    if (!read_boolean_pref (CFSTR ("no_auth"), FALSE))
+		auth_file = XauFileName ();
+	
+    /* The standard X11 behaviour is for the server to quit when the first
+	 client exits. But it can be useful for debugging (and to mimic our
+	 behaviour in the beta releases) to not do that. */
+	
+    xinit_kills_server = read_boolean_pref (CFSTR ("xinit_kills_server"), TRUE);
+	
+    for (i = 1; i < argc; i++)
+    {
+		if (argv[i][0] == ':')
+			server_name = argv[i];
+    }
+	
+    if (server_name == NULL)
+    {
+		static char name[8];
+		
+		/* No display number specified, so search for the first unused.
+		 
+		 There's a big old race condition here if two servers start at
+		 the same time, but that's fairly unlikely. We could create
+		 lockfiles or something, but that's seems more likely to cause
+		 problems than the race condition itself.. */
+		
+		for (i = 0; i < MAX_DISPLAYS; i++)
+		{
+			if (!display_exists_p (i))
+				break;
+		}
+		
+		if (i == MAX_DISPLAYS)
+		{
+			fprintf (stderr, "%s: couldn't allocate a display number", argv[0]);
+			exit (1);
+		}
+		
+		sprintf (name, ":%d", i);
+		server_name = name;
+    }
+	
+    if (auth_file != NULL)
+    {
+		/* Create new Xauth keys and add them to the .Xauthority file */
+		
+		make_auth_keys (server_name);
+		write_auth_file (TRUE);
+    }
+	
+    /* Construct our new argv */
+	
+    i = j = 0;
+	
+    xargv[i++] = argv[j++];
+	
+    if (auth_file != NULL)
+    {
+		xargv[i++] = "-auth";
+		xargv[i++] = auth_file;
+    }
+	
+    /* By default, don't listen on tcp sockets if Xauth is disabled. */
+	
+    if (read_boolean_pref (CFSTR ("nolisten_tcp"), auth_file == NULL))
+    {
+		xargv[i++] = "-nolisten";
+		xargv[i++] = "tcp";
+    }
+	
+    while (j < argc)
+    {
+		if (argv[j++][0] != ':')
+			xargv[i++] = argv[j-1];
+    }
+	
+    xargv[i++] = (char *) server_name;
+    xargv[i++] = NULL;
+	
+    /* Detach from any controlling terminal and connect stdin to /dev/null */
+	
+#ifdef TIOCNOTTY
+    fd = open ("/dev/tty", O_RDONLY);
+    if (fd != -1)
+    {
+		ioctl (fd, TIOCNOTTY, 0);
+		close (fd);
+    }
+#endif
+	
+    fd = open ("/dev/null", O_RDWR, 0);
+    if (fd >= 0)
+    {
+		dup2 (fd, 0);
+		if (fd > 0)
+			close (fd);
+    }
+	
+    if (!start_server (xargv))
+		return 1;
+	
+    if (!wait_for_server ())
+    {
+		kill (server_pid, SIGTERM);
+		return 1;
+    }
+	
+    if (!start_client ())
+    {
+		kill (server_pid, SIGTERM);
+		return 1;
+    }
+	
+    signal (SIGCHLD, sigchld_handler);
+	
+    signal (SIGTERM, termination_signal_handler);
+    signal (SIGHUP, termination_signal_handler);
+    signal (SIGINT, termination_signal_handler);
+    signal (SIGQUIT, termination_signal_handler);
+
+    if (setjmp (exit_continuation) == 0)
+    {
+		if (install_ipaddr_source ())
+			CFRunLoopRun ();
+		else
+			while (1) pause ();
+    }
+	
+    signal (SIGCHLD, SIG_IGN);
+
+    if (client_pid >= 0) kill (client_pid, SIGTERM);
+    if (server_pid >= 0) kill (server_pid, SIGTERM);
+	
+    if (auth_file != NULL)
+    {
+		/* Remove our Xauth keys */
+		
+		write_auth_file (FALSE);
+    }
+	
+    free_auth_items ();
+	
+    return 0;
+}
diff-tree a16360733ea393ec1fc267e88fc604d9d7534484 (from 566610680c4e1cab3e7fc7146adbeaba52fdd0ad)
Author: Jay Estabrook <Jay.Estabrook at hp.com>
Date:   Sun Feb 25 19:58:26 2007 +0000

    Fix root bus/domain selection on alpha

diff --git a/hw/xfree86/os-support/bus/axpPci.c b/hw/xfree86/os-support/bus/axpPci.c
index 9acc4ab..fc16a51 100644
--- a/hw/xfree86/os-support/bus/axpPci.c
+++ b/hw/xfree86/os-support/bus/axpPci.c
@@ -217,7 +217,8 @@ axpPciInit()
 	 * only set up the root bus for each domain (hose) and the bridged 
 	 * buses will be set up as they are found.
 	 */
-	bus = PCI_MAKE_BUS(domain, 0);
+	/* make a bus with both the domain and the root bus in it */
+	bus = PCI_MAKE_BUS(domain, pDomain->root_bus);
 	pciBusInfo[bus] = xnfalloc(sizeof(pciBusInfo_t));
 	(void)memset(pciBusInfo[bus], 0, sizeof(pciBusInfo_t));
 
@@ -249,7 +250,7 @@ axpPciBusFromTag(PCITAG tag)
 	|| !(pDomain = pBusInfo->pciBusPriv)
 	|| (pDomain->domain != PCI_DOM_FROM_TAG(tag))) return -1;
 
-    bus = PCI_BUS_NO_DOMAIN(bus) + pDomain->root_bus;
+    bus = PCI_BUS_NO_DOMAIN(bus); /* should just be root_bus */
     dfn = PCI_DFN_FROM_TAG(tag);
     if (_iobase(IOBASE_HOSE, -1, bus, dfn) != pDomain->hose) return -1;
 
diff-tree 566610680c4e1cab3e7fc7146adbeaba52fdd0ad (from af550ea91c451cf4f831c2413266a19d1f211d0e)
Author: Adam Jackson <ajax at benzedrine.nwnk.net>
Date:   Fri Feb 23 15:20:35 2007 -0500

    Don't install libi2c.a

diff --git a/hw/xfree86/i2c/Makefile.am b/hw/xfree86/i2c/Makefile.am
index 70a9ace..a16d880 100644
--- a/hw/xfree86/i2c/Makefile.am
+++ b/hw/xfree86/i2c/Makefile.am
@@ -1,4 +1,4 @@
-module_LIBRARIES = libi2c.a
+noinst_LIBRARIES = libi2c.a
 
 multimediadir = $(moduledir)/multimedia
 multimedia_LTLIBRARIES =	\
diff-tree af550ea91c451cf4f831c2413266a19d1f211d0e (from b1142cdbce76fed8cb22ba6d7ac027751dd56a76)
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Thu Feb 22 14:38:40 2007 -0800

    Move SecurityPolicy file format from Xserver(1) to it's own man page
    
    Don't make users looking for Xserver information page through pages of
    details only interesting to the handful of people writing security policies.

diff --git a/doc/Makefile.am b/doc/Makefile.am
index 0ac533e..ce1979d 100644
--- a/doc/Makefile.am
+++ b/doc/Makefile.am
@@ -1,25 +1,35 @@
 appmandir = $(APP_MAN_DIR)
+filemandir = $(FILE_MAN_DIR)
 
 # Xserver.man covers options generic to all X servers built in this tree
+# (i.e. those handled in the os/utils.c options processing instead of in
+#  the DDX-level options processing)
 appman_PRE = Xserver.man.pre
+fileman_PRE = SecurityPolicy.man.pre
 
 appman_PROCESSED = $(appman_PRE:man.pre=man)
+fileman_PROCESSED = $(fileman_PRE:man.pre=man)
 
 appman_DATA = $(appman_PRE:man.pre=@APP_MAN_SUFFIX@)
+fileman_DATA = $(fileman_PRE:man.pre=@FILE_MAN_SUFFIX@)
 
-BUILT_SOURCES = $(appman_PROCESSED)
+BUILT_SOURCES = $(appman_PROCESSED) $(fileman_PROCESSED)
 
-CLEANFILES = $(appman_PROCESSED) $(appman_DATA)
+CLEANFILES = $(appman_PROCESSED) $(appman_DATA) \
+		$(fileman_PROCESSED) $(fileman_DATA)
 
 include $(top_srcdir)/cpprules.in
 
 .man.$(APP_MAN_SUFFIX):
 	cp $< $@
 
+.man.$(FILE_MAN_SUFFIX):
+	cp $< $@
+
 EXTRAMANDEFS = -D__default_font_path__="`echo $(COMPILEDDEFAULTFONTPATH) | sed -e 's/,/, /g'`"
 
 # Docs about X server internals that we ship with source but don't install
 DEVEL_DOCS = smartsched
 
 
-EXTRA_DIST = $(DEVEL_DOCS) $(appman_PRE)
+EXTRA_DIST = $(DEVEL_DOCS) $(appman_PRE) $(fileman_PRE)
diff --git a/doc/SecurityPolicy.man.pre b/doc/SecurityPolicy.man.pre
new file mode 100644
index 0000000..f5aff0c
--- /dev/null
+++ b/doc/SecurityPolicy.man.pre
@@ -0,0 +1,258 @@
+.\" Split out of Xserver.man, which was covered by this notice:
+.\" Copyright 1984 - 1991, 1993, 1994, 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.
+.\" $XFree86: xc/programs/Xserver/Xserver.man,v 3.31 2004/01/10 22:27:46 dawes Exp $
+.\" shorthand for double quote that works everywhere.
+.ds q \N'34'
+.TH SecurityPolicy __filemansuffix__ __xorgversion__
+.SH NAME
+SecurityPolicy \- X Window System SECURITY Extension Policy file format
+.SH DESCRIPTION
+The SECURITY extension to the X Window System uses a policy file to determine
+which operations should be allowed or denied.   The default location for this
+file is
+.IR __projectroot__/lib/xserver/SecurityPolicy .
+.PP
+The syntax of the security policy file is as follows.
+Notation: "*" means zero or more occurrences of the preceding element,
+and "+" means one or more occurrences.  To interpret <foo/bar>, ignore
+the text after the /; it is used to distinguish between instances of
+<foo> in the next section.
+.PP
+.nf
+<policy file> ::= <version line> <other line>*
+
+<version line> ::= <string/v> '\en'
+
+<other line > ::= <comment> | <access rule> | <site policy> | <blank line>
+
+<comment> ::= # <not newline>* '\en'
+
+<blank line> ::= <space> '\en'
+
+<site policy> ::= sitepolicy <string/sp> '\en'
+
+<access rule> ::= property <property/ar> <window> <perms> '\en'
+
+<property> ::= <string>
+
+<window> ::= any | root | <required property>
+
+<required property> ::= <property/rp> | <property with value>
+
+<property with value> ::= <property/rpv> = <string/rv>
+
+<perms> ::= [ <operation> | <action> | <space> ]*
+
+<operation> ::= r | w | d
+
+<action> ::= a | i | e
+
+<string> ::= <dbl quoted string> | <single quoted string> | <unquoted string>
+
+<dbl quoted string> ::= <space> " <not dquote>* " <space>
+
+<single quoted string> ::= <space> ' <not squote>* ' <space>
+
+<unquoted string> ::= <space> <not space>+ <space>
+
+<space> ::= [ ' ' | '\et' ]*
+
+Character sets:
+
+<not newline> ::= any character except '\en'
+<not dquote>  ::= any character except "
+<not squote>  ::= any character except '
+<not space>   ::= any character except those in <space>
+.fi
+.PP
+The semantics associated with the above syntax are as follows.
+.PP
+<version line>, the first line in the file, specifies the file format
+version.  If the server does not recognize the version <string/v>, it
+ignores the rest of the file.  The version string for the file format
+described here is "version-1" .
+.PP
+Once past the <version line>, lines that do not match the above syntax
+are ignored.
+.PP
+<comment> lines are ignored.
+.PP
+<sitepolicy> lines are currently ignored.  They are intended to
+specify the site policies used by the XC-QUERY-SECURITY-1
+authorization method.
+.PP
+<access rule> lines specify how the server should react to untrusted
+client requests that affect the X Window property named <property/ar>.
+The rest of this section describes the interpretation of an
+<access rule>.
+.PP
+For an <access rule> to apply to a given instance of <property/ar>,
+<property/ar> must be on a window that is in the set of windows
+specified by <window>.  If <window> is any, the rule applies to
+<property/ar> on any window.  If <window> is root, the rule applies to
+<property/ar> only on root windows.
+.PP
+If <window> is <required property>, the following apply.  If <required
+property> is a <property/rp>, the rule applies when the window also
+has that <property/rp>, regardless of its value.  If <required
+property> is a <property with value>, <property/rpv> must also have
+the value specified by <string/rv>.  In this case, the property must
+have type STRING and format 8, and should contain one or more
+null-terminated strings.  If any of the strings match <string/rv>, the
+rule applies.
+.PP
+The definition of string matching is simple case-sensitive string
+comparison with one elaboration: the occurrence of the character '*' in
+<string/rv> is a wildcard meaning "any string."  A <string/rv> can
+contain multiple wildcards anywhere in the string.  For example, "x*"
+matches strings that begin with x, "*x" matches strings that end with
+x, "*x*" matches strings containing x, and "x*y*" matches strings that
+start with x and subsequently contain y.
+.PP
+There may be multiple <access rule> lines for a given <property/ar>.
+The rules are tested in the order that they appear in the file.  The
+first rule that applies is used.
+.PP
+<perms> specify operations that untrusted clients may attempt, and
+the actions that the server should take in response to those operations.
+.PP
+<operation> can be r (read), w (write), or d (delete).  The following
+table shows how X Protocol property requests map to these operations
+in the X.Org server implementation.
+.PP
+.nf
+GetProperty	r, or r and d if delete = True
+ChangeProperty	w
+RotateProperties	r and w
+DeleteProperty	d
+ListProperties	none, untrusted clients can always list all properties
+.fi
+.PP
+<action> can be a (allow), i (ignore), or e (error).  Allow means
+execute the request as if it had been issued by a trusted client.
+Ignore means treat the request as a no-op.  In the case of
+GetProperty, ignore means return an empty property value if the
+property exists, regardless of its actual value.  Error means do not
+execute the request and return a BadAtom error with the atom set to
+the property name.  Error is the default action for all properties,
+including those not listed in the security policy file.
+.PP
+An <action> applies to all <operation>s that follow it, until the next
+<action> is encountered.  Thus, irwad  means ignore read and write,
+allow delete.
+.PP
+GetProperty and RotateProperties may do multiple operations (r and d,
+or r and w).  If different actions apply to the operations, the most
+severe action is applied to the whole request; there is no partial
+request execution.  The severity ordering is: allow < ignore < error.
+Thus, if the <perms> for a property are ired (ignore read, error
+delete), and an untrusted client attempts GetProperty on that property
+with delete = True, an error is returned, but the property value is
+not.  Similarly, if any of the properties in a RotateProperties do not
+allow both read and write, an error is returned without changing any
+property values.
+.PP
+Here is an example security policy file.
+.PP
+.ta 3i 4i
+.nf
+version-1
+
+XCOMM Allow reading of application resources, but not writing.
+property RESOURCE_MANAGER	root	ar iw
+property SCREEN_RESOURCES	root	ar iw
+
+XCOMM Ignore attempts to use cut buffers.  Giving errors causes apps to crash,
+XCOMM and allowing access may give away too much information.
+property CUT_BUFFER0	root	irw
+property CUT_BUFFER1	root	irw
+property CUT_BUFFER2	root	irw
+property CUT_BUFFER3	root	irw
+property CUT_BUFFER4	root	irw
+property CUT_BUFFER5	root	irw
+property CUT_BUFFER6	root	irw
+property CUT_BUFFER7	root	irw
+
+XCOMM If you are using Motif, you probably want these.
+property _MOTIF_DEFAULT_BINDINGS	root	ar iw
+property _MOTIF_DRAG_WINDOW	root	ar iw
+property _MOTIF_DRAG_TARGETS	any 	ar iw
+property _MOTIF_DRAG_ATOMS	any 	ar iw
+property _MOTIF_DRAG_ATOM_PAIRS	any 	ar iw
+
+XCOMM The next two rules let xwininfo -tree work when untrusted.
+property WM_NAME	any	ar
+
+XCOMM Allow read of WM_CLASS, but only for windows with WM_NAME.
+XCOMM This might be more restrictive than necessary, but demonstrates
+XCOMM the <required property> facility, and is also an attempt to
+XCOMM say "top level windows only."
+property WM_CLASS	WM_NAME	ar
+
+XCOMM These next three let xlsclients work untrusted.  Think carefully
+XCOMM before including these; giving away the client machine name and command
+XCOMM may be exposing too much.
+property WM_STATE	WM_NAME	ar
+property WM_CLIENT_MACHINE	WM_NAME	ar
+property WM_COMMAND	WM_NAME	ar
+
+XCOMM To let untrusted clients use the standard colormaps created by
+XCOMM xstdcmap, include these lines.
+property RGB_DEFAULT_MAP	root	ar
+property RGB_BEST_MAP	root	ar
+property RGB_RED_MAP	root	ar
+property RGB_GREEN_MAP	root	ar
+property RGB_BLUE_MAP	root	ar
+property RGB_GRAY_MAP	root	ar
+
+XCOMM To let untrusted clients use the color management database created
+XCOMM by xcmsdb, include these lines.
+property XDCCC_LINEAR_RGB_CORRECTION	root	ar
+property XDCCC_LINEAR_RGB_MATRICES	root	ar
+property XDCCC_GRAY_SCREENWHITEPOINT	root	ar
+property XDCCC_GRAY_CORRECTION	root	ar
+
+XCOMM To let untrusted clients use the overlay visuals that many vendors
+XCOMM support, include this line.
+property SERVER_OVERLAY_VISUALS	root	ar
+
+XCOMM Dumb examples to show other capabilities.
+
+XCOMM oddball property names and explicit specification of error conditions
+property "property with spaces"	'property with "'	aw er ed
+
+XCOMM Allow deletion of Woo-Hoo if window also has property OhBoy with value
+XCOMM ending in "son".  Reads and writes will cause an error.
+property Woo-Hoo	OhBoy = "*son"	ad
+
+.fi
+.SH FILES
+.TP 30
+.I __projectroot__/lib/xserver/SecurityPolicy
+Default X server security policy
+.SH "SEE ALSO"
+.PP
+\fIXserver\fp(__appmansuffix__),
+.I "Security Extension Specification"
diff --git a/doc/Xserver.man.pre b/doc/Xserver.man.pre
index cca58b1..aac3b51 100644
--- a/doc/Xserver.man.pre
+++ b/doc/Xserver.man.pre
@@ -414,221 +414,8 @@ X servers that support the SECURITY exte
 causes the server to attempt to read and interpret filename as a security
 policy file with the format described below.  The file is read at server
 startup and reread at each server reset.
-.PP
-The syntax of the security policy file is as follows.
-Notation: "*" means zero or more occurrences of the preceding element,
-and "+" means one or more occurrences.  To interpret <foo/bar>, ignore
-the text after the /; it is used to distinguish between instances of
-<foo> in the next section.
-.PP
-.nf
-<policy file> ::= <version line> <other line>*
-
-<version line> ::= <string/v> '\en'
-
-<other line > ::= <comment> | <access rule> | <site policy> | <blank line>
-
-<comment> ::= # <not newline>* '\en'
-
-<blank line> ::= <space> '\en'
-
-<site policy> ::= sitepolicy <string/sp> '\en'
-
-<access rule> ::= property <property/ar> <window> <perms> '\en'
-
-<property> ::= <string>
-
-<window> ::= any | root | <required property>
-
-<required property> ::= <property/rp> | <property with value>
-
-<property with value> ::= <property/rpv> = <string/rv>
-
-<perms> ::= [ <operation> | <action> | <space> ]*
-
-<operation> ::= r | w | d
-
-<action> ::= a | i | e
-
-<string> ::= <dbl quoted string> | <single quoted string> | <unquoted string>
-
-<dbl quoted string> ::= <space> " <not dquote>* " <space>
-
-<single quoted string> ::= <space> ' <not squote>* ' <space>
-
-<unquoted string> ::= <space> <not space>+ <space>
-
-<space> ::= [ ' ' | '\et' ]*
-
-Character sets:
-
-<not newline> ::= any character except '\en'
-<not dquote>  ::= any character except "
-<not squote>  ::= any character except '
-<not space>   ::= any character except those in <space>
-.fi
-.PP
-The semantics associated with the above syntax are as follows.
-.PP
-<version line>, the first line in the file, specifies the file format
-version.  If the server does not recognize the version <string/v>, it
-ignores the rest of the file.  The version string for the file format
-described here is "version-1" .
-.PP
-Once past the <version line>, lines that do not match the above syntax
-are ignored.
-.PP
-<comment> lines are ignored.
-.PP
-<sitepolicy> lines are currently ignored.  They are intended to
-specify the site policies used by the XC-QUERY-SECURITY-1
-authorization method.
-.PP
-<access rule> lines specify how the server should react to untrusted
-client requests that affect the X Window property named <property/ar>.
-The rest of this section describes the interpretation of an
-<access rule>.
-.PP
-For an <access rule> to apply to a given instance of <property/ar>,
-<property/ar> must be on a window that is in the set of windows
-specified by <window>.  If <window> is any, the rule applies to
-<property/ar> on any window.  If <window> is root, the rule applies to
-<property/ar> only on root windows.
-.PP
-If <window> is <required property>, the following apply.  If <required
-property> is a <property/rp>, the rule applies when the window also
-has that <property/rp>, regardless of its value.  If <required
-property> is a <property with value>, <property/rpv> must also have
-the value specified by <string/rv>.  In this case, the property must
-have type STRING and format 8, and should contain one or more
-null-terminated strings.  If any of the strings match <string/rv>, the
-rule applies.
-.PP
-The definition of string matching is simple case-sensitive string
-comparison with one elaboration: the occurrence of the character '*' in
-<string/rv> is a wildcard meaning "any string."  A <string/rv> can
-contain multiple wildcards anywhere in the string.  For example, "x*"
-matches strings that begin with x, "*x" matches strings that end with
-x, "*x*" matches strings containing x, and "x*y*" matches strings that
-start with x and subsequently contain y.
-.PP
-There may be multiple <access rule> lines for a given <property/ar>.
-The rules are tested in the order that they appear in the file.  The
-first rule that applies is used.
-.PP
-<perms> specify operations that untrusted clients may attempt, and
-the actions that the server should take in response to those operations.
-.PP
-<operation> can be r (read), w (write), or d (delete).  The following
-table shows how X Protocol property requests map to these operations
-in The Open Group server implementation.
-.PP
-.nf
-GetProperty	r, or r and d if delete = True
-ChangeProperty	w
-RotateProperties	r and w
-DeleteProperty	d
-ListProperties	none, untrusted clients can always list all properties
-.fi
-.PP
-<action> can be a (allow), i (ignore), or e (error).  Allow means
-execute the request as if it had been issued by a trusted client.
-Ignore means treat the request as a no-op.  In the case of
-GetProperty, ignore means return an empty property value if the
-property exists, regardless of its actual value.  Error means do not
-execute the request and return a BadAtom error with the atom set to
-the property name.  Error is the default action for all properties,
-including those not listed in the security policy file.
-.PP
-An <action> applies to all <operation>s that follow it, until the next
-<action> is encountered.  Thus, irwad  means ignore read and write,
-allow delete.
-.PP
-GetProperty and RotateProperties may do multiple operations (r and d,
-or r and w).  If different actions apply to the operations, the most
-severe action is applied to the whole request; there is no partial
-request execution.  The severity ordering is: allow < ignore < error.
-Thus, if the <perms> for a property are ired (ignore read, error
-delete), and an untrusted client attempts GetProperty on that property
-with delete = True, an error is returned, but the property value is
-not.  Similarly, if any of the properties in a RotateProperties do not
-allow both read and write, an error is returned without changing any
-property values.
-.PP
-Here is an example security policy file.
-.PP
-.ta 3i 4i
-.nf
-version-1
-
-XCOMM Allow reading of application resources, but not writing.
-property RESOURCE_MANAGER	root	ar iw
-property SCREEN_RESOURCES	root	ar iw
-
-XCOMM Ignore attempts to use cut buffers.  Giving errors causes apps to crash,
-XCOMM and allowing access may give away too much information.
-property CUT_BUFFER0	root	irw
-property CUT_BUFFER1	root	irw
-property CUT_BUFFER2	root	irw
-property CUT_BUFFER3	root	irw
-property CUT_BUFFER4	root	irw
-property CUT_BUFFER5	root	irw
-property CUT_BUFFER6	root	irw
-property CUT_BUFFER7	root	irw
-
-XCOMM If you are using Motif, you probably want these.
-property _MOTIF_DEFAULT_BINDINGS	root	ar iw
-property _MOTIF_DRAG_WINDOW	root	ar iw
-property _MOTIF_DRAG_TARGETS	any 	ar iw
-property _MOTIF_DRAG_ATOMS	any 	ar iw
-property _MOTIF_DRAG_ATOM_PAIRS	any 	ar iw
-
-XCOMM The next two rules let xwininfo -tree work when untrusted.
-property WM_NAME	any	ar
-
-XCOMM Allow read of WM_CLASS, but only for windows with WM_NAME.
-XCOMM This might be more restrictive than necessary, but demonstrates
-XCOMM the <required property> facility, and is also an attempt to
-XCOMM say "top level windows only."
-property WM_CLASS	WM_NAME	ar
-
-XCOMM These next three let xlsclients work untrusted.  Think carefully
-XCOMM before including these; giving away the client machine name and command
-XCOMM may be exposing too much.
-property WM_STATE	WM_NAME	ar
-property WM_CLIENT_MACHINE	WM_NAME	ar
-property WM_COMMAND	WM_NAME	ar
-
-XCOMM To let untrusted clients use the standard colormaps created by
-XCOMM xstdcmap, include these lines.
-property RGB_DEFAULT_MAP	root	ar
-property RGB_BEST_MAP	root	ar
-property RGB_RED_MAP	root	ar
-property RGB_GREEN_MAP	root	ar
-property RGB_BLUE_MAP	root	ar
-property RGB_GRAY_MAP	root	ar
-
-XCOMM To let untrusted clients use the color management database created
-XCOMM by xcmsdb, include these lines.
-property XDCCC_LINEAR_RGB_CORRECTION	root	ar
-property XDCCC_LINEAR_RGB_MATRICES	root	ar
-property XDCCC_GRAY_SCREENWHITEPOINT	root	ar
-property XDCCC_GRAY_CORRECTION	root	ar
-
-XCOMM To let untrusted clients use the overlay visuals that many vendors
-XCOMM support, include this line.
-property SERVER_OVERLAY_VISUALS	root	ar
-
-XCOMM Dumb examples to show other capabilities.
-
-XCOMM oddball property names and explicit specification of error conditions
-property "property with spaces"	'property with "'	aw er ed
-
-XCOMM Allow deletion of Woo-Hoo if window also has property OhBoy with value
-XCOMM ending in "son".  Reads and writes will cause an error.
-property Woo-Hoo	OhBoy = "*son"	ad
-
-.fi
+The syntax of the security policy file is described in 
+\fISecurityPolicy\fP(__filemansuffix__).
 .SH "NETWORK CONNECTIONS"
 The X server supports client connections via a platform-dependent subset of
 the following transport types: TCP\/IP, Unix Domain sockets, DECnet,
@@ -757,6 +544,9 @@ Error log file for display number \fBn\f
 .TP 30
 .I __projectroot__/lib/X11/xdm/xdm-errors
 Default error log file if the server is run from \fIxdm\fP(1)
+.TP 30
+.I __projectroot__/lib/xserver/SecurityPolicy
+Default X server security policy
 .SH "SEE ALSO"
 General information: \fIX\fP(__miscmansuffix__)
 .PP
@@ -771,6 +561,7 @@ Fonts: \fIbdftopcf\fP(1), \fImkfontdir\f
 .PP
 Security: \fIXsecurity\fP(__miscmansuffix__), \fIxauth\fP(1), \fIXau\fP(1), 
 \fIxdm\fP(1), \fIxhost\fP(1), \fIxfwp\fP(1),
+\fISecurityPolicy\fP(__filemansuffix__),
 .I "Security Extension Specification"
 .PP
 Starting the server: \fIxdm\fP(1), \fIxinit\fP(1)
diff-tree b1142cdbce76fed8cb22ba6d7ac027751dd56a76 (from 3344a4eda704edc7dc30037f095de277a60a70bb)
Author: Brice Goglin <brice.goglin at ens-lyon.org>
Date:   Thu Feb 22 12:26:04 2007 -0800

    Bug #10034: 'man Xserver' typos: s/dqoute/dquote/
    
    Bugzilla #10034: <http://bugs.freedesktop.org/show_bug.cgi?id=10034>
    Patch #8780: <http://bugs.freedesktop.org/attachment.cgi?id=8780>

diff --git a/doc/Xserver.man.pre b/doc/Xserver.man.pre
index aa931a8..cca58b1 100644
--- a/doc/Xserver.man.pre
+++ b/doc/Xserver.man.pre
@@ -452,7 +452,7 @@ the text after the /; it is used to dist
 
 <string> ::= <dbl quoted string> | <single quoted string> | <unquoted string>
 
-<dbl quoted string> ::= <space> " <not dqoute>* " <space>
+<dbl quoted string> ::= <space> " <not dquote>* " <space>
 
 <single quoted string> ::= <space> ' <not squote>* ' <space>
 
@@ -463,7 +463,7 @@ the text after the /; it is used to dist
 Character sets:
 
 <not newline> ::= any character except '\en'
-<not dqoute>  ::= any character except "
+<not dquote>  ::= any character except "
 <not squote>  ::= any character except '
 <not space>   ::= any character except those in <space>
 .fi
diff-tree 3344a4eda704edc7dc30037f095de277a60a70bb (from 3c7a27dc77595ad018bb7c4f7cef6bc178268cb6)
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Thu Feb 15 16:27:50 2007 +0100

    DRI: Make sure number of DRI windows is accurate in driver ClipNotify hook.
    
    Always call DRI{De,In}creaseNumberVisible (which in turn calls
    DRIDriverClipNotify) after updating pDRIPriv->nrWindows.

diff --git a/hw/xfree86/dri/dri.c b/hw/xfree86/dri/dri.c
index bdef75a..c183e2a 100644
--- a/hw/xfree86/dri/dri.c
+++ b/hw/xfree86/dri/dri.c
@@ -1134,11 +1134,11 @@ DRICreateDrawable(ScreenPtr pScreen, Dra
 	    pWin->devPrivates[DRIWindowPrivIndex].ptr =
 						(pointer)pDRIDrawablePriv;
 
+	    pDRIPriv->nrWindows++;
+
 	    if (pDRIDrawablePriv->nrects)
 		DRIIncreaseNumberVisible(pScreen);
 
-	    pDRIPriv->nrWindows++;
-
 	    /* track this in case this window is destroyed */
 	    AddResource(id, DRIDrawablePrivResType, (pointer)pWin);
 	}
@@ -1210,13 +1210,13 @@ DRIDrawablePrivDelete(pointer pResource,
 	    return FALSE;
 	}
 
-	if (pDRIDrawablePriv->nrects)
-	    DRIDecreaseNumberVisible(pDrawable->pScreen);
-
 	xfree(pDRIDrawablePriv);
 	pWin->devPrivates[DRIWindowPrivIndex].ptr = NULL;
 
 	pDRIPriv->nrWindows--;
+
+	if (REGION_NUM_RECTS(&pWin->clipList))
+	    DRIDecreaseNumberVisible(pDrawable->pScreen);
     }
     else { /* pixmap (or for GLX 1.3, a PBuffer) */
 	/* NOT_DONE */
diff-tree 3c7a27dc77595ad018bb7c4f7cef6bc178268cb6 (from eedf148e5a1273ebbf4dc8dcac9c435712fc00ea)
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Wed Feb 14 16:17:18 2007 +0100

    DRI: New ClipNotify driver hook.
    
    The hook is called whenever the clipList of any DRI window changes, be it via
    DRIClipNotify, DRICreateDrawable or DRIDrawablePrivDelete. This allows the
    driver to keep track of which DRI windows are visible where.

diff --git a/hw/xfree86/dri/dri.c b/hw/xfree86/dri/dri.c
index ebfe28b..bdef75a 100644
--- a/hw/xfree86/dri/dri.c
+++ b/hw/xfree86/dri/dri.c
@@ -1007,6 +1007,55 @@ DRITransitionTo2d(ScreenPtr pScreen)
 }
 
 
+static int
+DRIDCNTreeTraversal(WindowPtr pWin, pointer data)
+{
+    DRIDrawablePrivPtr pDRIDrawablePriv = DRI_DRAWABLE_PRIV_FROM_WINDOW(pWin);
+
+    if (pDRIDrawablePriv) {
+	ScreenPtr pScreen = pWin->drawable.pScreen;
+	DRIScreenPrivPtr pDRIPriv = DRI_SCREEN_PRIV(pScreen);
+
+	if (REGION_NUM_RECTS(&pWin->clipList) > 0) {
+	    WindowPtr *pDRIWindows = (WindowPtr*)data;
+	    int i = 0;
+
+	    while (pDRIWindows[i])
+		i++;
+
+	    pDRIWindows[i] = pWin;
+
+	    pDRIPriv->nrWalked++;
+	}
+
+	if (pDRIPriv->nrWindows == pDRIPriv->nrWalked)
+	    return WT_STOPWALKING;
+    }
+
+    return WT_WALKCHILDREN;
+}
+
+static void
+DRIDriverClipNotify(ScreenPtr pScreen)
+{
+    DRIScreenPrivPtr pDRIPriv = DRI_SCREEN_PRIV(pScreen);
+
+    if (pDRIPriv->pDriverInfo->ClipNotify) {
+	WindowPtr *pDRIWindows = xcalloc(sizeof(WindowPtr), pDRIPriv->nrWindows);
+	DRIInfoPtr pDRIInfo = pDRIPriv->pDriverInfo;
+
+	if (pDRIPriv->nrWindows > 0) {
+	    pDRIPriv->nrWalked = 0;
+	    TraverseTree(WindowTable[pScreen->myNum], DRIDCNTreeTraversal,
+			 (pointer)pDRIWindows);
+	}
+
+	pDRIInfo->ClipNotify(pScreen, pDRIWindows, pDRIPriv->nrWindows);
+
+	xfree(pDRIWindows);
+    }
+}
+
 static void
 DRIIncreaseNumberVisible(ScreenPtr pScreen)
 {
@@ -1022,6 +1071,8 @@ DRIIncreaseNumberVisible(ScreenPtr pScre
     default:
 	break;
     }
+
+    DRIDriverClipNotify(pScreen);
 }
 
 static void
@@ -1039,6 +1090,8 @@ DRIDecreaseNumberVisible(ScreenPtr pScre
     default:
 	break;
     }
+
+    DRIDriverClipNotify(pScreen);
 }
 
 Bool
@@ -1880,6 +1933,8 @@ DRIClipNotify(WindowPtr pWin, int dx, in
 	    DRIIncreaseNumberVisible(pScreen);
 	else if (!nrects && pDRIDrawablePriv->nrects)
 	    DRIDecreaseNumberVisible(pScreen);
+	else
+	    DRIDriverClipNotify(pScreen);
 
 	pDRIDrawablePriv->nrects = nrects;
 
diff --git a/hw/xfree86/dri/dri.h b/hw/xfree86/dri/dri.h
index dca0edd..f65c571 100644
--- a/hw/xfree86/dri/dri.h
+++ b/hw/xfree86/dri/dri.h
@@ -107,7 +107,7 @@ typedef struct {
  */
 
 #define DRIINFO_MAJOR_VERSION   5
-#define DRIINFO_MINOR_VERSION   0
+#define DRIINFO_MINOR_VERSION   1
 #define DRIINFO_PATCH_VERSION   0
 
 typedef struct {
@@ -173,6 +173,9 @@ typedef struct {
     /* New with DRI version 4.1.0 */
     void        (*TransitionSingleToMulti3D)(ScreenPtr pScreen);
     void        (*TransitionMultiToSingle3D)(ScreenPtr pScreen);
+
+    /* New with DRI version 5.1.0 */
+    void        (*ClipNotify)(ScreenPtr pScreen, WindowPtr *ppWin, int num);
 } DRIInfoRec, *DRIInfoPtr;
 
 
diff --git a/hw/xfree86/dri/dristruct.h b/hw/xfree86/dri/dristruct.h
index 7579806..9c42ff9 100644
--- a/hw/xfree86/dri/dristruct.h
+++ b/hw/xfree86/dri/dristruct.h
@@ -89,6 +89,7 @@ typedef struct _DRIScreenPrivRec
     DRIInfoPtr		pDriverInfo;
     int                 nrWindows;
     int                 nrWindowsVisible;
+    int                 nrWalked;
     drm_clip_rect_t  private_buffer_rect; /* management of private buffers */
     DrawablePtr         fullscreen; /* pointer to fullscreen drawable */
     drm_clip_rect_t  fullscreen_rect; /* fake rect for fullscreen mode */
diff-tree eedf148e5a1273ebbf4dc8dcac9c435712fc00ea (from 8a42af6a935b1cf0e15102e986bb527f4fab31a8)
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Fri Feb 2 18:27:40 2007 +0100

    Track number of visible DRI windows separately for transitions.
    
    This allows e.g. doing page flipping with multiple DRI windows as long as
    only one of them is visible.

diff --git a/hw/xfree86/dri/dri.c b/hw/xfree86/dri/dri.c
index 5337f9a..ebfe28b 100644
--- a/hw/xfree86/dri/dri.c
+++ b/hw/xfree86/dri/dri.c
@@ -204,6 +204,7 @@ DRIScreenInit(ScreenPtr pScreen, DRIInfo
     pDRIPriv->directRenderingSupport = TRUE;
     pDRIPriv->pDriverInfo = pDRIInfo;
     pDRIPriv->nrWindows = 0;
+    pDRIPriv->nrWindowsVisible = 0;
     pDRIPriv->fullscreen = NULL;
 
     pDRIPriv->createDummyCtx     = pDRIInfo->createDummyCtx;
@@ -1006,6 +1007,40 @@ DRITransitionTo2d(ScreenPtr pScreen)
 }
 
 
+static void
+DRIIncreaseNumberVisible(ScreenPtr pScreen)
+{
+    DRIScreenPrivPtr pDRIPriv = DRI_SCREEN_PRIV(pScreen);
+
+    switch (++pDRIPriv->nrWindowsVisible) {
+    case 1:
+	DRITransitionTo3d( pScreen );
+	break;
+    case 2:
+	DRITransitionToSharedBuffers( pScreen );
+	break;
+    default:
+	break;
+    }
+}
+
+static void
+DRIDecreaseNumberVisible(ScreenPtr pScreen)
+{
+    DRIScreenPrivPtr pDRIPriv = DRI_SCREEN_PRIV(pScreen);
+
+    switch (--pDRIPriv->nrWindowsVisible) {
+    case 0:
+	DRITransitionTo2d( pScreen );
+	break;
+    case 1:
+	DRITransitionToPrivateBuffers( pScreen );
+	break;
+    default:
+	break;
+    }
+}
+
 Bool
 DRICreateDrawable(ScreenPtr pScreen, Drawable id,
                   DrawablePtr pDrawable, drm_drawable_t * hHWDrawable)
@@ -1040,21 +1075,16 @@ DRICreateDrawable(ScreenPtr pScreen, Dra
 	    pDRIDrawablePriv->pScreen = pScreen;
 	    pDRIDrawablePriv->refCount = 1;
 	    pDRIDrawablePriv->drawableIndex = -1;
+	    pDRIDrawablePriv->nrects = REGION_NUM_RECTS(&pWin->clipList);
 
 	    /* save private off of preallocated index */
 	    pWin->devPrivates[DRIWindowPrivIndex].ptr =
 						(pointer)pDRIDrawablePriv;
 
-	    switch (++pDRIPriv->nrWindows) {
-	    case 1:
-	       DRITransitionTo3d( pScreen );
-	       break;
-	    case 2:
-	       DRITransitionToSharedBuffers( pScreen );
-	       break;
-	    default:
-	       break;
-	    }
+	    if (pDRIDrawablePriv->nrects)
+		DRIIncreaseNumberVisible(pScreen);
+
+	    pDRIPriv->nrWindows++;
 
 	    /* track this in case this window is destroyed */
 	    AddResource(id, DRIDrawablePrivResType, (pointer)pWin);
@@ -1126,19 +1156,14 @@ DRIDrawablePrivDelete(pointer pResource,
 			       pDRIDrawablePriv->hwDrawable)) {
 	    return FALSE;
 	}
+
+	if (pDRIDrawablePriv->nrects)
+	    DRIDecreaseNumberVisible(pDrawable->pScreen);
+
 	xfree(pDRIDrawablePriv);
 	pWin->devPrivates[DRIWindowPrivIndex].ptr = NULL;
 
-	switch (--pDRIPriv->nrWindows) {
-	case 0:
-	   DRITransitionTo2d( pDrawable->pScreen );
-	   break;
-	case 1:
-	   DRITransitionToPrivateBuffers( pDrawable->pScreen );
-	   break;
-	default:
-	   break;
-	}
+	pDRIPriv->nrWindows--;
     }
     else { /* pixmap (or for GLX 1.3, a PBuffer) */
 	/* NOT_DONE */
@@ -1276,7 +1301,7 @@ DRIGetDrawableInfo(ScreenPtr pScreen,
 	    *backX = *X;
 	    *backY = *Y;
 
-	    if (pDRIPriv->nrWindows == 1 && *numClipRects) {
+	    if (pDRIPriv->nrWindowsVisible == 1 && *numClipRects) {
 	       /* Use a single cliprect. */
 
 	       int x0 = *X;
@@ -1652,7 +1677,7 @@ DRICopyWindow(WindowPtr pWin, DDXPointRe
 
     if(!pDRIPriv) return;
 
-    if(pDRIPriv->nrWindows > 0) {
+    if(pDRIPriv->nrWindowsVisible > 0) {
        RegionRec reg;
 
        REGION_NULL(pScreen, &reg);
@@ -1844,19 +1869,26 @@ DRIClipNotify(WindowPtr pWin, int dx, in
     if(!pDRIPriv) return;
 
     if ((pDRIDrawablePriv = DRI_DRAWABLE_PRIV_FROM_WINDOW(pWin))) {
+        int nrects = REGION_NUM_RECTS(&pWin->clipList);
 
         if(!pDRIPriv->windowsTouched) {
             DRILockTree(pScreen);
             pDRIPriv->windowsTouched = TRUE;
         }
 
+	if (nrects && !pDRIDrawablePriv->nrects)
+	    DRIIncreaseNumberVisible(pScreen);
+	else if (!nrects && pDRIDrawablePriv->nrects)
+	    DRIDecreaseNumberVisible(pScreen);
+
+	pDRIDrawablePriv->nrects = nrects;
+
 	pDRIPriv->pSAREA->drawableTable[pDRIDrawablePriv->drawableIndex].stamp
 	    = DRIDrawableValidationStamp++;
 
 	drmUpdateDrawableInfo(pDRIPriv->drmFD, pDRIDrawablePriv->hwDrawable,
 			      DRM_DRAWABLE_CLIPRECTS,
-			      REGION_NUM_RECTS(&pWin->clipList),
-			      REGION_RECTS(&pWin->clipList));
+			      nrects, REGION_RECTS(&pWin->clipList));
     }
 
     /* call lower wrapped functions */
diff --git a/hw/xfree86/dri/dristruct.h b/hw/xfree86/dri/dristruct.h
index 340c59a..7579806 100644
--- a/hw/xfree86/dri/dristruct.h
+++ b/hw/xfree86/dri/dristruct.h
@@ -53,6 +53,7 @@ typedef struct _DRIDrawablePrivRec
     int			drawableIndex;
     ScreenPtr		pScreen;
     int 		refCount;
+    int 		nrects;
 } DRIDrawablePrivRec, *DRIDrawablePrivPtr;
 
 struct _DRIContextPrivRec
@@ -87,6 +88,7 @@ typedef struct _DRIScreenPrivRec
     void**		partial3DContextStore; /* parital 3D context        */
     DRIInfoPtr		pDriverInfo;
     int                 nrWindows;
+    int                 nrWindowsVisible;
     drm_clip_rect_t  private_buffer_rect; /* management of private buffers */
     DrawablePtr         fullscreen; /* pointer to fullscreen drawable */
     drm_clip_rect_t  fullscreen_rect; /* fake rect for fullscreen mode */
diff-tree 8a42af6a935b1cf0e15102e986bb527f4fab31a8 (from 4660eaaffb36f526f71d5847ae1309c10ee133c6)
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Mon Feb 19 15:28:37 2007 -0800

    Check for clientGone before sending events from XFixes (bug #1753).
    
    Freeing resources during client closedown can cause cursor changes which
    attempt to send cursor events through the XFixes extension; a client in the
    process of closing down has no file to send events to, causing a crash when
    this path is hit.

diff --git a/xfixes/cursor.c b/xfixes/cursor.c
index 86a512c..3cdacc0 100755
--- a/xfixes/cursor.c
+++ b/xfixes/cursor.c
@@ -143,7 +143,8 @@ CursorDisplayCursor (ScreenPtr pScreen,
 	CursorCurrent = pCursor;
 	for (e = cursorEvents; e; e = e->next)
 	{
-	    if (e->eventMask & XFixesDisplayCursorNotifyMask)
+	    if ((e->eventMask & XFixesDisplayCursorNotifyMask) &&
+		!e->pClient->clientGone)
 	    {
 		xXFixesCursorNotifyEvent	ev;
 		ev.type = XFixesEventBase + XFixesCursorNotify;
diff --git a/xfixes/select.c b/xfixes/select.c
index d1c22c5..f0a9f2f 100755
--- a/xfixes/select.c
+++ b/xfixes/select.c
@@ -78,7 +78,9 @@ XFixesSelectionCallback (CallbackListPtr
     }
     for (e = selectionEvents; e; e = e->next)
     {
-	if (e->selection == selection->selection && (e->eventMask & eventMask))
+	if (e->selection == selection->selection && 
+	    (e->eventMask & eventMask) &&
+	    !e->pClient->clientGone)
 	{
 	    xXFixesSelectionNotifyEvent	ev;
 
diff-tree 4660eaaffb36f526f71d5847ae1309c10ee133c6 (from 5631a67f648f5f151a849a918ee12871c71c32e9)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Sun Feb 18 14:09:51 2007 -0800

    configure fixes for darwin

diff --git a/configure.ac b/configure.ac
index 0a3fe45..3260855 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1253,37 +1253,6 @@ if test "x$XORG" = xyes -o "x$XGL" = xye
 	XORG_CFLAGS="$XORGSERVER_CFLAGS -DHAVE_XORG_CONFIG_H"
 	XORG_LIBS="$COMPOSITE_LIB $MI_LIB $FIXES_LIB $XEXTXORG_LIB $GLX_LIBS $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XPSTUBS_LIB $OS_LIB"
 
-	if test "x$DGA" = xauto; then
-		PKG_CHECK_MODULES(DGA, xf86dgaproto, [DGA=yes], [DGA=no])
-	fi
-	if test "x$DGA" = xyes; then
-		XORG_MODULES="$XORG_MODULES xf86dgaproto"
-		AC_DEFINE(DGA, 1, [Support DGA extension])
-		AC_DEFINE(XFreeXDGA, 1, [Build XDGA support])
-	fi
-
-	if test "x$XF86MISC" = xauto; then
-		PKG_CHECK_MODULES(XF86MISC, xf86miscproto, [XF86MISC=yes], [XF86MISC=no])
-	fi
-	if test "x$XF86MISC" = xyes; then
-		XORG_MODULES="$XORG_MODULES xf86miscproto"
-		AC_DEFINE(XF86MISC, 1, [Support XFree86 miscellaneous extensions])
-	fi
-
-	if test "x$XF86VIDMODE" = xauto; then
-		PKG_CHECK_MODULES(XF86VIDMODE, xf86vidmodeproto, [XF86VIDMODE=yes], [XF86VIDMODE=no])
-	fi
-	if test "x$XF86VIDMODE" = xyes; then
-		XORG_MODULES="$XORG_MODULES xf86vidmodeproto"
-		AC_DEFINE(XF86VIDMODE, 1, [Support XFree86 Video Mode extension])
-	fi
-
-	if test -n "$XORG_MODULES"; then
-	        PKG_CHECK_MODULES(XORG_MODULES, [$XORG_MODULES])
-	        XORG_CFLAGS="$XORG_CFLAGS $XORG_MODULES_CFLAGS"
-	        XORG_LIBS="$XORG_LIBS $XORG_MODULES_LIBS"
-	fi
-
 dnl Check to see if dlopen is in default libraries (like Solaris, which
 dnl has it in libc), or if libdl is needed to get it.
 	AC_CHECK_FUNC([dlopen], [], 
@@ -1312,17 +1281,19 @@ return 0;}
                    XQUARTZ=no
                  fi
                fi
-               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
-               ])
+#	       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
                AC_CHECK_LIB([Xplugin],[xp_init],[:])
                AC_SUBST([APPLE_APPLICATIONS_DIR])
                CFLAGS="${CFLAGS} -D__DARWIN__"
@@ -1331,15 +1302,15 @@ return 0;}
                PLIST_VENDOR_WEB=$VENDOR_WEB
                AC_SUBST([PLIST_VENDOR_WEB])
                # Not sure that we should be disabling all these...
-               if test "x$XF86MISC" = xyes; then
+               if test "x$XF86MISC" = xyes || test "x$XF86MISC" = xauto; then
                        AC_MSG_NOTICE([Disabling XF86Misc extension])
                        XF86MISC=no
                fi
-               if test "x$XF86VIDMODE" = xyes; then
+               if test "x$XF86VIDMODE" = xyes || test "x$XF86VIDMODE" = xauto; then
                        AC_MSG_NOTICE([Disabling XF86VidMode extension])
                        XF86VIDMODE=no
                fi
-               if test "x$DGA" = xyes; then
+               if test "x$DGA" = xyes || test "x$DGA" = xauto; then
                        AC_MSG_NOTICE([Disabling DGA extension])
                        DGA=no
                fi
@@ -1499,6 +1470,37 @@ return 0;}
 	if test "x$XORG_OS_PCI" = x ; then
 		XORG_OS_PCI=$XORG_OS
 	fi
+	if test "x$DGA" = xauto; then
+		PKG_CHECK_MODULES(DGA, xf86dgaproto, [DGA=yes], [DGA=no])
+	fi
+	if test "x$DGA" = xyes; then
+		XORG_MODULES="$XORG_MODULES xf86dgaproto"
+		AC_DEFINE(DGA, 1, [Support DGA extension])
+		AC_DEFINE(XFreeXDGA, 1, [Build XDGA support])
+	fi
+
+	if test "x$XF86MISC" = xauto; then
+		PKG_CHECK_MODULES(XF86MISC, xf86miscproto, [XF86MISC=yes], [XF86MISC=no])
+	fi
+	if test "x$XF86MISC" = xyes; then
+		XORG_MODULES="$XORG_MODULES xf86miscproto"
+		AC_DEFINE(XF86MISC, 1, [Support XFree86 miscellaneous extensions])
+	fi
+
+	if test "x$XF86VIDMODE" = xauto; then
+		PKG_CHECK_MODULES(XF86VIDMODE, xf86vidmodeproto, [XF86VIDMODE=yes], [XF86VIDMODE=no])
+	fi
+	if test "x$XF86VIDMODE" = xyes; then
+		XORG_MODULES="$XORG_MODULES xf86vidmodeproto"
+		AC_DEFINE(XF86VIDMODE, 1, [Support XFree86 Video Mode extension])
+	fi
+
+	if test -n "$XORG_MODULES"; then
+	        PKG_CHECK_MODULES(XORG_MODULES, [$XORG_MODULES])
+	        XORG_CFLAGS="$XORG_CFLAGS $XORG_MODULES_CFLAGS"
+	        XORG_LIBS="$XORG_LIBS $XORG_MODULES_LIBS"
+	fi
+
 	AC_SUBST([XORG_LIBS])
 	AC_SUBST([XORG_INCS])
 	AC_SUBST([XORG_OS])
diff-tree 5631a67f648f5f151a849a918ee12871c71c32e9 (from 096965ec9c7514f0c9fc0d17e5166f2d26781f87)
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Fri Feb 16 10:06:22 2007 -0800

    Don't set subpixel order during startup; the screen won't be ready.
    
    in xf86CrtcSetMode, scrn->pScreen will be NULL during server startup time,
    so don't try to set the subpixel order. subpixel order will be set in the
    randr initialization anyways.
    (cherry picked from commit 5f6f8616d862ce4a37f6d3df4bdbc44fd21cc82a)

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index 37a3025..29042a0 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -313,7 +313,8 @@ xf86CrtcSetMode (xf86CrtcPtr crtc, Displ
 
     /* XXX free adjustedmode */
     ret = TRUE;
-    xf86CrtcSetScreenSubpixelOrder (scrn->pScreen);
+    if (scrn->pScreen)
+	xf86CrtcSetScreenSubpixelOrder (scrn->pScreen);
 
 done:
     if (!ret) {
diff-tree 096965ec9c7514f0c9fc0d17e5166f2d26781f87 (from 55797dd252382d35ebab5d9e18a5e0e77872d775)
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Fri Feb 16 02:17:11 2007 -0800

    Ensure drivers can use new modes header files.
    
    New modes header files required a few minor changes to be used by external
    drivers, the most notable of which is the publication of the config file
    parser header files.

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index 74e4c76..37a3025 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -41,6 +41,9 @@
 #define DPMS_SERVER
 #include "X11/extensions/dpms.h"
 #include "X11/Xatom.h"
+#ifdef RENDER
+#include "picturestr.h"
+#endif
 
 /*
  * Initialize xf86CrtcConfig structure
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
index 9a70be4..756730e 100644
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -28,7 +28,6 @@
 #include "xf86Rename.h"
 #endif
 #include "xf86Modes.h"
-#include "xf86Parser.h"
 #include "damage.h"
 
 /* Compat definitions for older X Servers. */
diff --git a/hw/xfree86/modes/xf86DiDGA.c b/hw/xfree86/modes/xf86DiDGA.c
index 551f052..0964cef 100644
--- a/hw/xfree86/modes/xf86DiDGA.c
+++ b/hw/xfree86/modes/xf86DiDGA.c
@@ -35,6 +35,8 @@
 #include "xf86Crtc.h"
 #include "xf86Modes.h"
 #include "gcstruct.h"
+#include "scrnintstr.h"
+#include "windowstr.h"
 
 static Bool
 xf86_dga_get_modes (ScreenPtr pScreen)
diff --git a/hw/xfree86/modes/xf86Modes.c b/hw/xfree86/modes/xf86Modes.c
index 37d0eb6..5b52bd7 100644
--- a/hw/xfree86/modes/xf86Modes.c
+++ b/hw/xfree86/modes/xf86Modes.c
@@ -36,11 +36,6 @@
 #endif
 #endif
 
-#include <stddef.h>
-#include <string.h>
-#include <stdio.h>
-
-#include "xf86.h"
 #include "xf86Modes.h"
 #include "xf86Priv.h"
 
diff --git a/hw/xfree86/modes/xf86Modes.h b/hw/xfree86/modes/xf86Modes.h
index 9494333..2bd4ede 100644
--- a/hw/xfree86/modes/xf86Modes.h
+++ b/hw/xfree86/modes/xf86Modes.h
@@ -25,11 +25,17 @@
  *
  */
 
-#ifndef _I830_XF86MODES_H_
-#define _I830_XF86MODES_H_
+#ifndef _XF86MODES_H_
+#define _XF86MODES_H_
+
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "xf86.h"
 #include "xorgVersion.h"
-#include "xf86Parser.h"
 #include "edid.h"
+#include "xf86Parser.h"
 #if XF86_MODES_RENAME
 #include "xf86Rename.h"
 #endif
@@ -89,4 +95,4 @@ xf86GetMonitorModes (ScrnInfoPtr pScrn, 
 DisplayModePtr
 xf86GetDefaultModes (Bool interlaceAllowed, Bool doubleScanAllowed);
 
-#endif /* _I830_XF86MODES_H_ */
+#endif /* _XF86MODES_H_ */
diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index c8ea778..abdf92e 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -496,19 +496,18 @@ void
 xf86RandR12SetRotations (ScreenPtr pScreen, Rotation rotations)
 {
     XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+#if RANDR_12_INTERFACE
     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
-    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
     int			c;
+    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
 
-    randrp->supported_rotations = rotations;
-
-#if RANDR_12_INTERFACE
     for (c = 0; c < config->num_crtc; c++) {
 	xf86CrtcPtr    crtc = config->crtc[c];
 
 	RRCrtcSetRotations (crtc->randr_crtc, rotations);
     }
 #endif
+    randrp->supported_rotations = rotations;
 }
 
 void
diff --git a/hw/xfree86/parser/Makefile.am b/hw/xfree86/parser/Makefile.am
index 1c1ba3f..849ee8b 100644
--- a/hw/xfree86/parser/Makefile.am
+++ b/hw/xfree86/parser/Makefile.am
@@ -36,4 +36,6 @@ EXTRA_DIST = \
 	cpconfig.c
 
 sdk_HEADERS = \
-	$(LIBHEADERS)
+	$(LIBHEADERS) \
+	xf86Parser.h \
+	xf86Optrec.h
diff-tree 55797dd252382d35ebab5d9e18a5e0e77872d775 (from e4507825bf0328ea59673f2bbe652de3a9105c86)
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Fri Feb 16 00:56:00 2007 -0800

    Respect rotation in initial screen size computation.

diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index 1dacb6f..c8ea778 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -394,8 +394,8 @@ xf86RandR12CreateScreenResources (Screen
     for (c = 0; c < config->num_crtc; c++)
     {
 	xf86CrtcPtr crtc = config->crtc[c];
-	int	    crtc_width = crtc->x + crtc->mode.HDisplay;
-	int	    crtc_height = crtc->y + crtc->mode.VDisplay;
+	int	    crtc_width = crtc->x + xf86ModeWidth (&crtc->mode, crtc->rotation);
+	int	    crtc_height = crtc->y + xf86ModeHeight (&crtc->mode, crtc->rotation);
 	
 	if (crtc->enabled && crtc_width > width)
 	    width = crtc_width;
diff-tree e4507825bf0328ea59673f2bbe652de3a9105c86 (from 8606aeb9b2ab2dafc11e64436db4d3a7e67dbcc0)
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Fri Feb 16 00:41:29 2007 -0800

    Enable startup-time rotation; change rotation pixmap creation API.
    
    Add monitor "Rotate" option taking one of "normal", "left", "inverted" or
    "right". However, because initial mode selection is made before the screen
    is completely initialized, we cannot create the shadow pixmap object at this
    point. Pend the shadow pixmap creation until the block handler.
    
    Note that this code is not completely functional yet.

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index bda8055..74e4c76 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -344,6 +344,7 @@ typedef enum {
     OPTION_MIN_CLOCK,
     OPTION_MAX_CLOCK,
     OPTION_IGNORE,
+    OPTION_ROTATE,
 } OutputOpts;
 
 static OptionInfoRec xf86OutputOptions[] = {
@@ -358,6 +359,7 @@ static OptionInfoRec xf86OutputOptions[]
     {OPTION_MIN_CLOCK,	    "MinClock",		OPTV_FREQ,    {0}, FALSE },
     {OPTION_MAX_CLOCK,	    "MaxClock",		OPTV_FREQ,    {0}, FALSE },
     {OPTION_IGNORE,	    "Ignore",		OPTV_BOOLEAN, {0}, FALSE },
+    {OPTION_ROTATE,	    "Rotate",		OPTV_STRING,  {0}, FALSE },
     {-1,		    NULL,		OPTV_NONE,    {0}, FALSE },
 };
 
@@ -413,6 +415,29 @@ xf86OutputIgnored (xf86OutputPtr    outp
     return xf86ReturnOptValBool (output->options, OPTION_IGNORE, FALSE);
 }
 
+static char *direction[4] = {
+    "normal", 
+    "left", 
+    "inverted", 
+    "right"
+};
+
+static Rotation
+xf86OutputInitialRotation (xf86OutputPtr output)
+{
+    char    *rotate_name = xf86GetOptValString (output->options, 
+						OPTION_ROTATE);
+    int	    i;
+
+    if (!rotate_name)
+	return RR_Rotate_0;
+    
+    for (i = 0; i < 4; i++)
+	if (xf86nameCompare (direction[i], rotate_name) == 0)
+	    return (1 << i);
+    return RR_Rotate_0;
+}
+
 xf86OutputPtr
 xf86OutputCreate (ScrnInfoPtr		    scrn,
 		  const xf86OutputFuncsRec *funcs,
@@ -533,8 +558,12 @@ xf86DefaultMode (xf86OutputPtr output, i
 	int	    preferred = (mode->type & M_T_PREFERRED) != 0;
 	int	    diff;
 
-	if (mode->HDisplay > width || mode->VDisplay > height) continue;
-	dpi = (mode->HDisplay * 254) / (mm_height * 10);
+	if (xf86ModeWidth (mode, output->initial_rotation) > width ||
+	    xf86ModeHeight (mode, output->initial_rotation) > height)
+	    continue;
+	
+	/* yes, use VDisplay here, not xf86ModeHeight */
+	dpi = (mode->VDisplay * 254) / (mm_height * 10);
 	diff = dpi - 96;
 	diff = diff < 0 ? -diff : diff;
 	if (target_mode == NULL || (preferred > target_preferred) ||
@@ -549,7 +578,8 @@ xf86DefaultMode (xf86OutputPtr output, i
 }
 
 static DisplayModePtr
-xf86ClosestMode (xf86OutputPtr output, DisplayModePtr match,
+xf86ClosestMode (xf86OutputPtr output, 
+		 DisplayModePtr match, Rotation match_rotation,
 		 int width, int height)
 {
     DisplayModePtr  target_mode = NULL;
@@ -564,14 +594,17 @@ xf86ClosestMode (xf86OutputPtr output, D
 	int	    dx, dy;
 	int	    diff;
 
-	if (mode->HDisplay > width || mode->VDisplay > height) continue;
+	if (xf86ModeWidth (mode, output->initial_rotation) > width ||
+	    xf86ModeHeight (mode, output->initial_rotation) > height)
+	    continue;
 	
 	/* exact matches are preferred */
-	if (xf86ModesEqual (mode, match))
+	if (output->initial_rotation == match_rotation &&
+	    xf86ModesEqual (mode, match))
 	    return mode;
 	
-	dx = match->HDisplay - mode->HDisplay;
-	dy = match->VDisplay - mode->VDisplay;
+	dx = xf86ModeWidth (match, match_rotation) - xf86ModeWidth (mode, output->initial_rotation);
+	dy = xf86ModeHeight (match, match_rotation) - xf86ModeHeight (mode, output->initial_rotation);
 	diff = dx * dx + dy * dy;
 	if (target_mode == NULL || diff < target_diff)
 	{
@@ -589,7 +622,10 @@ xf86OutputHasPreferredMode (xf86OutputPt
 
     for (mode = output->probed_modes; mode; mode = mode->next)
     {
-	if (mode->HDisplay > width || mode->VDisplay > height) continue;
+	if (xf86ModeWidth (mode, output->initial_rotation) > width ||
+	    xf86ModeHeight (mode, output->initial_rotation) > height)
+	    continue;
+
 	if (mode->type & M_T_PREFERRED)
 	    return TRUE;
     }
@@ -605,7 +641,7 @@ xf86PickCrtcs (ScrnInfoPtr	scrn,
 	       int		height)
 {
     xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
-    int		    c, o, l;
+    int		    c, o;
     xf86OutputPtr   output;
     xf86CrtcPtr	    crtc;
     xf86CrtcPtr	    *crtcs;
@@ -663,13 +699,11 @@ xf86PickCrtcs (ScrnInfoPtr	scrn,
 	     * see if they can be cloned
 	     */
 	    if (xf86ModesEqual (modes[o], modes[n]) &&
+		config->output[0]->initial_rotation == config->output[n]->initial_rotation &&
 		config->output[o]->initial_x == config->output[n]->initial_x &&
 		config->output[o]->initial_y == config->output[n]->initial_y)
 	    {
-		for (l = 0; l < config->num_output; l++)
-		    if (output->possible_clones & (1 << l))
-			break;
-		if (l == config->num_output)
+		if ((output->possible_clones & (1 << o)) == 0)
 		    continue;		/* nope, try next CRTC */
 	    }
 	    else
@@ -712,8 +746,8 @@ xf86DefaultScreenLimits (ScrnInfoPtr scr
 
 	if (crtc->enabled)
 	{
-	    crtc_width = crtc->x + crtc->desiredMode.HDisplay;
-	    crtc_height = crtc->y + crtc->desiredMode.VDisplay;
+	    crtc_width = crtc->x + xf86ModeWidth (&crtc->desiredMode, crtc->desiredRotation);
+	    crtc_height = crtc->y + xf86ModeHeight (&crtc->desiredMode, crtc->desiredRotation);
 	}
 	for (o = 0; o < config->num_output; o++) 
 	{
@@ -727,8 +761,12 @@ xf86DefaultScreenLimits (ScrnInfoPtr scr
 		    {
 			if (mode->HDisplay > crtc_width)
 			    crtc_width = mode->HDisplay;
+			if (mode->VDisplay > crtc_width)
+			    crtc_width = mode->VDisplay;
 			if (mode->VDisplay > crtc_height)
 			    crtc_height = mode->VDisplay;
+			if (mode->HDisplay > crtc_height)
+			    crtc_height = mode->HDisplay;
 		    }
 		}
 	}
@@ -858,16 +896,16 @@ xf86InitialOutputPositions (ScrnInfoPtr 
 		output->initial_y = relative->initial_y;
 		switch (relation) {
 		case OPTION_BELOW:
-		    output->initial_y += modes[or]->VDisplay;
+		    output->initial_y += xf86ModeHeight (modes[or], relative->initial_rotation);
 		    break;
 		case OPTION_RIGHT_OF:
-		    output->initial_x += modes[or]->HDisplay;
+		    output->initial_x += xf86ModeWidth (modes[or], relative->initial_rotation);
 		    break;
 		case OPTION_ABOVE:
-		    output->initial_y -= modes[o]->VDisplay;
+		    output->initial_y -= xf86ModeHeight (modes[or], relative->initial_rotation);
 		    break;
 		case OPTION_LEFT_OF:
-		    output->initial_x -= modes[o]->HDisplay;
+		    output->initial_x -= xf86ModeWidth (modes[or], relative->initial_rotation);
 		    break;
 		default:
 		    break;
@@ -1208,6 +1246,8 @@ xf86ProbeOutputModes (ScrnInfoPtr scrn, 
 	    }
 	}
 	
+	output->initial_rotation = xf86OutputInitialRotation (output);
+
 #ifdef DEBUG_REPROBE
 	if (output->probed_modes != NULL) {
 	    xf86DrvMsg(scrn->scrnIndex, X_INFO,
@@ -1310,6 +1350,7 @@ xf86InitialConfiguration (ScrnInfoPtr	  
     xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
     int			o, c;
     DisplayModePtr	target_mode = NULL;
+    Rotation		target_rotation = RR_Rotate_0;
     xf86CrtcPtr		*crtcs;
     DisplayModePtr	*modes;
     Bool		*enabled;
@@ -1351,6 +1392,7 @@ xf86InitialConfiguration (ScrnInfoPtr	  
 	    xf86OutputHasPreferredMode (output, width, height))
 	{
 	    target_mode = xf86DefaultMode (output, width, height);
+	    target_rotation = output->initial_rotation;
 	    if (target_mode)
 	    {
 		modes[o] = target_mode;
@@ -1367,6 +1409,7 @@ xf86InitialConfiguration (ScrnInfoPtr	  
 	    if (enabled[o])
 	    {
 		target_mode = xf86DefaultMode (output, width, height);
+		target_rotation = output->initial_rotation;
 		if (target_mode)
 		{
 		    modes[o] = target_mode;
@@ -1381,7 +1424,7 @@ xf86InitialConfiguration (ScrnInfoPtr	  
 	xf86OutputPtr output = config->output[o];
 	
 	if (enabled[o] && !modes[o])
-	    modes[o] = xf86ClosestMode (output, target_mode, width, height);
+	    modes[o] = xf86ClosestMode (output, target_mode, target_rotation, width, height);
     }
 
     /*
@@ -1429,6 +1472,7 @@ xf86InitialConfiguration (ScrnInfoPtr	  
 	if (mode && crtc)
 	{
 	    crtc->desiredMode = *mode;
+	    crtc->desiredRotation = output->initial_rotation;
 	    crtc->enabled = TRUE;
 	    crtc->x = output->initial_x;
 	    crtc->y = output->initial_y;
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
index 07f7d49..9a70be4 100644
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -112,16 +112,22 @@ typedef struct _xf86CrtcFuncs {
 		 int size);
 
     /**
+     * Allocate the shadow area, delay the pixmap creation until needed
+     */
+    void *
+    (*shadow_allocate) (xf86CrtcPtr crtc, int width, int height);
+    
+    /**
      * Create shadow pixmap for rotation support
      */
     PixmapPtr
-    (*shadow_create) (xf86CrtcPtr crtc, int width, int height);
+    (*shadow_create) (xf86CrtcPtr crtc, void *data, int width, int height);
     
     /**
      * Destroy shadow pixmap
      */
     void
-    (*shadow_destroy) (xf86CrtcPtr crtc, PixmapPtr pPixmap);
+    (*shadow_destroy) (xf86CrtcPtr crtc, PixmapPtr pPixmap, void *data);
 
     /**
      * Clean up driver-specific bits of the crtc
@@ -159,6 +165,8 @@ struct _xf86Crtc {
     DisplayModeRec  mode;
     Rotation	    rotation;
     PixmapPtr	    rotatedPixmap;
+    void	    *rotatedData;
+    
     /**
      * Position on screen
      *
@@ -357,6 +365,11 @@ struct _xf86Output {
     int			initial_x, initial_y;
 
     /**
+     * Desired initial rotation
+     */
+    Rotation		initial_rotation;
+
+    /**
      * Current connection status
      *
      * This indicates whether a monitor is known to be connected
diff --git a/hw/xfree86/modes/xf86Modes.c b/hw/xfree86/modes/xf86Modes.c
index 0706783..37d0eb6 100644
--- a/hw/xfree86/modes/xf86Modes.c
+++ b/hw/xfree86/modes/xf86Modes.c
@@ -94,6 +94,36 @@ xf86ModeVRefresh(DisplayModePtr mode)
     return refresh;
 }
 
+int
+xf86ModeWidth (DisplayModePtr mode, Rotation rotation)
+{
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_180:
+	return mode->HDisplay;
+    case RR_Rotate_90:
+    case RR_Rotate_270:
+	return mode->VDisplay;
+    default:
+	return 0;
+    }
+}
+
+int
+xf86ModeHeight (DisplayModePtr mode, Rotation rotation)
+{
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_180:
+	return mode->VDisplay;
+    case RR_Rotate_90:
+    case RR_Rotate_270:
+	return mode->HDisplay;
+    default:
+	return 0;
+    }
+}
+
 /** Sets a default mode name of <width>x<height> on a mode. */
 void
 xf86SetModeDefaultName(DisplayModePtr mode)
diff --git a/hw/xfree86/modes/xf86Modes.h b/hw/xfree86/modes/xf86Modes.h
index 60e2790..9494333 100644
--- a/hw/xfree86/modes/xf86Modes.h
+++ b/hw/xfree86/modes/xf86Modes.h
@@ -36,6 +36,13 @@
 
 double xf86ModeHSync(DisplayModePtr mode);
 double xf86ModeVRefresh(DisplayModePtr mode);
+
+int
+xf86ModeWidth (DisplayModePtr mode, Rotation rotation);
+    
+int
+xf86ModeHeight (DisplayModePtr mode, Rotation rotation);
+
 DisplayModePtr xf86DuplicateMode(DisplayModePtr pMode);
 DisplayModePtr xf86DuplicateModes(ScrnInfoPtr pScrn,
 				       DisplayModePtr modeList);
diff --git a/hw/xfree86/modes/xf86Rename.h b/hw/xfree86/modes/xf86Rename.h
index ce4d217..6cfa5ca 100644
--- a/hw/xfree86/modes/xf86Rename.h
+++ b/hw/xfree86/modes/xf86Rename.h
@@ -74,5 +74,7 @@
 #define xf86RandR12SetRotations XF86NAME(xf86RandR12SetRotations)
 #define xf86SaveScreen XF86NAME(xf86SaveScreen)
 #define xf86CrtcSetScreenSubpixelOrder XF86NAME(xf86CrtcSetScreenSubpixelOrder)
+#define xf86ModeWidth XF86NAME(xf86ModeWidth)
+#define xf86ModeHeight XF86NAME(xf86ModeHeight)
 
 #endif /* _XF86RENAME_H_ */
diff --git a/hw/xfree86/modes/xf86Rotate.c b/hw/xfree86/modes/xf86Rotate.c
index 1d55a6e..7b20498 100644
--- a/hw/xfree86/modes/xf86Rotate.c
+++ b/hw/xfree86/modes/xf86Rotate.c
@@ -44,36 +44,6 @@
 #include "X11/extensions/dpms.h"
 #include "X11/Xatom.h"
 
-static int
-mode_height (DisplayModePtr mode, Rotation rotation)
-{
-    switch (rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_180:
-	return mode->VDisplay;
-    case RR_Rotate_90:
-    case RR_Rotate_270:
-	return mode->HDisplay;
-    default:
-	return 0;
-    }
-}
-
-static int
-mode_width (DisplayModePtr mode, Rotation rotation)
-{
-    switch (rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_180:
-	return mode->HDisplay;
-    case RR_Rotate_90:
-    case RR_Rotate_270:
-	return mode->VDisplay;
-    default:
-	return 0;
-    }
-}
-
 /* borrowed from composite extension, move to Render and publish? */
 
 static VisualPtr
@@ -238,6 +208,42 @@ xf86RotateCrtcRedisplay (xf86CrtcPtr crt
 }
 
 static void
+xf86RotatePrepare (ScreenPtr pScreen)
+{
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
+    int			c;
+
+    for (c = 0; c < xf86_config->num_crtc; c++)
+    {
+	xf86CrtcPtr crtc = xf86_config->crtc[c];
+	
+	if (crtc->rotatedData && !crtc->rotatedPixmap)
+	{
+	    BoxRec	    damage_box;
+	    RegionRec   damage_region;
+
+	    crtc->rotatedPixmap = crtc->funcs->shadow_create (crtc,
+							     crtc->rotatedData,
+							     crtc->mode.HDisplay,
+							     crtc->mode.VDisplay);
+	    /* Hook damage to screen pixmap */
+	    DamageRegister (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
+			    xf86_config->rotationDamage);
+	    
+	    damage_box.x1 = 0;
+	    damage_box.y1 = 0;
+	    damage_box.x2 = xf86ModeWidth (&crtc->mode, crtc->rotation);
+	    damage_box.y2 = xf86ModeHeight (&crtc->mode, crtc->rotation);
+	    REGION_INIT (pScreen, &damage_region, &damage_box, 1);
+	    DamageDamageRegion (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
+				&damage_region);
+	    REGION_UNINIT (pScreen, &damage_region);
+	}
+    }
+}
+
+static void
 xf86RotateRedisplay(ScreenPtr pScreen)
 {
     ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
@@ -247,6 +253,7 @@ xf86RotateRedisplay(ScreenPtr pScreen)
 
     if (!damage)
 	return;
+    xf86RotatePrepare (pScreen);
     region = DamageRegion(damage);
     if (REGION_NOTEMPTY(pScreen, region)) 
     {
@@ -263,9 +270,9 @@ xf86RotateRedisplay(ScreenPtr pScreen)
 
 		/* compute portion of damage that overlaps crtc */
 		box.x1 = crtc->x;
-		box.x2 = crtc->x + mode_width (&crtc->mode, crtc->rotation);
+		box.x2 = crtc->x + xf86ModeWidth (&crtc->mode, crtc->rotation);
 		box.y1 = crtc->y;
-		box.y2 = crtc->y + mode_height (&crtc->mode, crtc->rotation);
+		box.y2 = crtc->y + xf86ModeHeight (&crtc->mode, crtc->rotation);
 		REGION_INIT(pScreen, &crtc_damage, &box, 1);
 		REGION_INTERSECT (pScreen, &crtc_damage, &crtc_damage, region);
 		
@@ -303,10 +310,11 @@ xf86CrtcRotate (xf86CrtcPtr crtc, Displa
     if (rotation == RR_Rotate_0)
     {
 	/* Free memory from rotation */
-	if (crtc->rotatedPixmap)
+	if (crtc->rotatedPixmap || crtc->rotatedData)
 	{
-	    crtc->funcs->shadow_destroy (crtc, crtc->rotatedPixmap);
+	    crtc->funcs->shadow_destroy (crtc, crtc->rotatedPixmap, crtc->rotatedData);
 	    crtc->rotatedPixmap = NULL;
+	    crtc->rotatedData = NULL;
 	}
 
 	if (xf86_config->rotationDamage)
@@ -331,24 +339,24 @@ xf86CrtcRotate (xf86CrtcPtr crtc, Displa
 	 */
 	int	    width = mode->HDisplay;
 	int	    height = mode->VDisplay;
+	void	    *shadowData = crtc->rotatedData;
 	PixmapPtr   shadow = crtc->rotatedPixmap;
 	int	    old_width = shadow ? shadow->drawable.width : 0;
 	int	    old_height = shadow ? shadow->drawable.height : 0;
-	BoxRec	    damage_box;
-	RegionRec   damage_region;
 	
 	/* Allocate memory for rotation */
 	if (old_width != width || old_height != height)
 	{
-	    if (shadow)
+	    if (shadow || shadowData)
 	    {
-		crtc->funcs->shadow_destroy (crtc, shadow);
+		crtc->funcs->shadow_destroy (crtc, shadow, shadowData);
 		crtc->rotatedPixmap = NULL;
+		crtc->rotatedData = NULL;
 	    }
-	    shadow = crtc->funcs->shadow_create (crtc, width, height);
-	    if (!shadow)
+	    shadowData = crtc->funcs->shadow_allocate (crtc, width, height);
+	    if (!shadowData)
 		goto bail1;
-	    crtc->rotatedPixmap = shadow;
+	    crtc->rotatedData = shadowData;
 	}
 	
 	if (!xf86_config->rotationDamage)
@@ -360,10 +368,6 @@ xf86CrtcRotate (xf86CrtcPtr crtc, Displa
 	    if (!xf86_config->rotationDamage)
 		goto bail2;
 	    
-	    /* Hook damage to screen pixmap */
-	    DamageRegister (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
-			    xf86_config->rotationDamage);
-	    
 	    /* Assign block/wakeup handler */
 	    if (!RegisterBlockAndWakeupHandlers (xf86RotateBlockHandler,
 						 xf86RotateWakeupHandler,
@@ -371,14 +375,6 @@ xf86CrtcRotate (xf86CrtcPtr crtc, Displa
 	    {
 		goto bail3;
 	    }
-	    damage_box.x1 = 0;
-	    damage_box.y1 = 0;
-	    damage_box.x2 = mode_width (mode, rotation);
-	    damage_box.y2 = mode_height (mode, rotation);
-	    REGION_INIT (pScreen, &damage_region, &damage_box, 1);
-	    DamageDamageRegion (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
-				&damage_region);
-	    REGION_UNINIT (pScreen, &damage_region);
 	}
 	if (0)
 	{
@@ -387,14 +383,16 @@ bail3:
 	    xf86_config->rotationDamage = NULL;
 	    
 bail2:
-	    if (shadow)
+	    if (shadow || shadowData)
 	    {
-		crtc->funcs->shadow_destroy (crtc, shadow);
+		crtc->funcs->shadow_destroy (crtc, shadow, shadowData);
 		crtc->rotatedPixmap = NULL;
+		crtc->rotatedData = NULL;
 	    }
 bail1:
 	    if (old_width && old_height)
 		crtc->rotatedPixmap = crtc->funcs->shadow_create (crtc,
+								  NULL,
 								  old_width,
 								  old_height);
 	    return FALSE;
diff --git a/hw/xfree86/modes/xf86cvt.c b/hw/xfree86/modes/xf86cvt.c
index dd6febf..69ccc42 100644
--- a/hw/xfree86/modes/xf86cvt.c
+++ b/hw/xfree86/modes/xf86cvt.c
@@ -40,6 +40,7 @@
 #endif
 
 #include "xf86.h"
+#include "xf86Modes.h"
 
 #include <string.h>
 
diff-tree 8606aeb9b2ab2dafc11e64436db4d3a7e67dbcc0 (from a88844eccb0e423e71d4fcb286866a026308babd)
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Thu Feb 15 22:23:16 2007 -0800

    RRConfigureOutputProperty is a variable length request.
    
    Replace REQUEST_SIZE_MATCH with REQUEST_AT_LEAST_SIZE

diff --git a/randr/rrproperty.c b/randr/rrproperty.c
index 916caf0..edfed1f 100644
--- a/randr/rrproperty.c
+++ b/randr/rrproperty.c
@@ -410,7 +410,7 @@ ProcRRConfigureOutputProperty (ClientPtr
     RROutputPtr				output;
     int					num_valid;
     
-    REQUEST_SIZE_MATCH(xRRConfigureOutputPropertyReq);
+    REQUEST_AT_LEAST_SIZE(xRRConfigureOutputPropertyReq);
 
     output = LookupOutput (client, stuff->output, DixReadAccess);
     
diff-tree a88844eccb0e423e71d4fcb286866a026308babd (from e9a2cc7d9fcc73e16576be2522522cce675dc3f3)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Sat Feb 17 20:35:07 2007 +0200

    configure.ac: disable dmx per default
    
    Disable DMX until it gets ported to the new input API.

diff --git a/configure.ac b/configure.ac
index 6841ee4..0a3fe45 100644
--- a/configure.ac
+++ b/configure.ac
@@ -532,7 +532,7 @@ AC_ARG_ENABLE(xfree86-utils,     AS_HELP
 
 dnl DDXes.
 AC_ARG_ENABLE(xorg,    	      AS_HELP_STRING([--enable-xorg], [Build Xorg server (default: auto)]), [XORG=$enableval], [XORG=auto])
-AC_ARG_ENABLE(dmx,    	      AS_HELP_STRING([--enable-dmx], [Build DMX server (default: auto)]), [DMX=$enableval], [DMX=auto])
+AC_ARG_ENABLE(dmx,    	      AS_HELP_STRING([--enable-dmx], [Build DMX server (default: no)]), [DMX=$enableval], [DMX=no])
 AC_ARG_ENABLE(xvfb,    	      AS_HELP_STRING([--enable-xvfb], [Build Xvfb server (default: yes)]), [XVFB=$enableval], [XVFB=yes])
 AC_ARG_ENABLE(xnest,   	      AS_HELP_STRING([--enable-xnest], [Build Xnest server (default: auto)]), [XNEST=$enableval], [XNEST=auto])
 AC_ARG_ENABLE(xwin,    	      AS_HELP_STRING([--enable-xwin], [Build XWin server (default: auto)]), [XWIN=$enableval], [XWIN=auto])
diff-tree e9a2cc7d9fcc73e16576be2522522cce675dc3f3 (from 81876bc5ddc2f3eda5078fe4bd101917fb32e586)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Sat Feb 17 16:17:48 2007 +0200

    config: error message cleanup
    
    Demote failure to connect from ErrorF to DebugF.

diff --git a/config/config.c b/config/config.c
index 76191ab..6c40143 100644
--- a/config/config.c
+++ b/config/config.c
@@ -303,15 +303,15 @@ configSetup(void)
     if (!configData)
         configData = (struct config_data *) xcalloc(sizeof(struct config_data), 1);
     if (!configData) {
-        ErrorF("[dbus] failed to allocate data struct.\n");
+        ErrorF("[dbus] failed to allocate data struct\n");
         return FALSE;
     }
 
     dbus_error_init(&error);
     configData->connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
     if (!configData->connection || dbus_error_is_set(&error)) {
-        ErrorF("[dbus] some kind of error occurred: %s (%s)\n", error.name,
-                error.message);
+        DebugF("[dbus] some kind of error occurred while connecting: %s (%s)\n",
+               error.name, error.message);
         dbus_error_free(&error);
         xfree(configData);
         configData = NULL;
diff-tree 81876bc5ddc2f3eda5078fe4bd101917fb32e586 (from d287b76471f66c9aea54f969d050b35643cb2501)
Author: Ben Byer <bbyer at apple.com>
Date:   Sat Feb 17 04:07:11 2007 -0800

    oops, missed a spot

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 87076df..ebbfb61 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -128,7 +128,7 @@ cr_la_SOURCES = \
 		quartz/cr/crAppleWM.m \
 		quartz/cr/crFrame.m \
 		quartz/cr/crScreen.m \
-		quartz/fullscreen/quartzCursor.m \
+		quartz/fullscreen/quartzCursor.c \
 		quartz/cr/XView.m
 
 cr_la_LIBADD = \
diff-tree d287b76471f66c9aea54f969d050b35643cb2501 (from 81444486be4f182dde778bac6f7edcbfc4368482)
Author: Ben Byer <bbyer at apple.com>
Date:   Sat Feb 17 03:47:42 2007 -0800

    cleaned up some linking ugliness in hw/darwin/quartz

diff --git a/configure.ac b/configure.ac
index 3288c09..6841ee4 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2061,9 +2061,6 @@ hw/darwin/bundle/Swedish.lproj/Makefile
 hw/darwin/bundle/ko.lproj/Makefile
 hw/darwin/iokit/Makefile
 hw/darwin/quartz/Makefile
-hw/darwin/quartz/cr/Makefile
-hw/darwin/quartz/fullscreen/Makefile
-hw/darwin/quartz/xpr/Makefile
 hw/darwin/utils/Makefile
 hw/kdrive/Makefile
 hw/kdrive/ati/Makefile
diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 7efd056..87076df 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -3,7 +3,7 @@ libdarwin_XINPUT_SRCS = darwinXinput.c
 
 AM_CFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
 AM_CPPFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
-INCLUDES = @XORG_INCS@
+INCLUDES = @XORG_INCS@ -I../../miext/rootless
 
 DEFS = @DEFS@ -DUSE_NEW_CLUT
 
@@ -20,7 +20,6 @@ SUBDIRS = \
 
 darwinappdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app
 
-
 libdarwinShared_a_SOURCES = darwin.c \
 			  darwinEvents.c \
 			  darwinKeyboard.c \
@@ -66,6 +65,7 @@ XDarwin_LDFLAGS =  \
 		 -Wl,-framework,IOKit
 
 XDarwin_CFLAGS = -DINXDARWIN
+
 if XQUARTZ
 macosdir = $(darwinappdir)/Contents/MacOS
 
@@ -74,8 +74,8 @@ DEFS += -DDARWIN_WITH_QUARTZ -DXFree86Se
 macos_PROGRAMS = XDarwinApp
 
 XDarwinApp_SOURCES = \
-               	$(top_srcdir)/fb/fbcmap.c \
-               	$(top_srcdir)/mi/miinitext.c \
+                $(top_srcdir)/fb/fbcmap.c \
+                $(top_srcdir)/mi/miinitext.c \
 		$(top_srcdir)/Xi/stubs.c 
 
 XDarwinApp_LDADD = \
@@ -118,21 +118,24 @@ XDarwinApp_LDFLAGS =  \
 		 -Wl,-framework,CoreAudio \
 		 -Wl,-framework,IOKit
 
+XDarwinApp_CFLAGS = -DINXDARWINAPP
 HOOK_TARGETS = xquartz-install-hook
 
 
 crplugindir = $(darwinappdir)/Contents/Resources/cr.bundle/Contents/MacOS
 crplugin_LTLIBRARIES = cr.la
-cr_la_SOURCES =
+cr_la_SOURCES = \
+		quartz/cr/crAppleWM.m \
+		quartz/cr/crFrame.m \
+		quartz/cr/crScreen.m \
+		quartz/fullscreen/quartzCursor.m \
+		quartz/cr/XView.m
+
 cr_la_LIBADD = \
-		quartz/cr/crAppleWM.o \
-		quartz/cr/crFrame.o \
-		quartz/cr/crScreen.o \
-		quartz/fullscreen/quartzCursor.o \
-		quartz/cr/XView.o \
 		$(top_builddir)/miext/rootless/librootless.la \
 		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
 		$(top_builddir)/miext/rootless/accel/librlAccel.la
+
 cr_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
 		-Wl,-framework,Cocoa \
 		-Wl,-framework,Carbon \
@@ -143,10 +146,11 @@ cr_la_DEPENDENCIES = XDarwinApp	
 
 fullscreenplugindir = $(darwinappdir)/Contents/Resources/fullscreen.bundle/Contents/MacOS
 fullscreenplugin_LTLIBRARIES = fullscreen.la
-fullscreen_la_SOURCES =
+fullscreen_la_SOURCES = \
+		quartz/fullscreen/fullscreen.c \
+		quartz/fullscreen/quartzCursor.c
+
 fullscreen_la_LIBADD = \
-		quartz/fullscreen/fullscreen.o \
-		quartz/fullscreen/quartzCursor.o \
 		$(top_builddir)/miext/shadow/libshadow.la
 
 fullscreen_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
@@ -175,20 +179,22 @@ if HAVE_X_PLUGIN
 
 xprplugindir = $(darwinappdir)/Contents/Resources/xpr.bundle/Contents/MacOS
 xprplugin_LTLIBRARIES = xpr.la
-xpr_la_SOURCES =
+xpr_la_SOURCES = \
+		quartz/xpr/appledri.c \
+		quartz/xpr/dri.c \
+		quartz/xpr/xprAppleWM.c \
+		quartz/xpr/xprCursor.c \
+		quartz/xpr/xprFrame.c \
+		quartz/xpr/xprScreen.c \
+		quartz/xpr/x-hash.c \
+		quartz/xpr/x-hook.c \
+		quartz/xpr/x-list.c
+
 xpr_la_LIBADD = \
-		quartz/xpr/appledri.o \
-		quartz/xpr/dri.o \
-		quartz/xpr/xprAppleWM.o \
-		quartz/xpr/xprCursor.o \
-		quartz/xpr/xprFrame.o \
-		quartz/xpr/xprScreen.o \
-		quartz/xpr/x-hash.o \
-		quartz/xpr/x-hook.o \
-		quartz/xpr/x-list.o \
 		$(top_builddir)/miext/rootless/librootless.la \
 		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
 		$(top_builddir)/miext/rootless/accel/librlAccel.la
+
 xpr_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
 		-lXplugin \
 		-XCClinker -bundle_loader -XCClinker XDarwinApp \
diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
index 9789330..993cdb0 100644
--- a/hw/darwin/quartz/Makefile.am
+++ b/hw/darwin/quartz/Makefile.am
@@ -7,10 +7,8 @@ INCLUDES = -I$(srcdir) -I$(srcdir)/.. @X
 AM_DEFS = -DHAS_CG_MACH_PORT -DHAS_KL_API
 if HAVE_X_PLUGIN
 AM_DEFS += -DBUILD_XPR
-XPR = xpr
 endif
 DEFS = @DEFS@ $(AM_DEFS) -DXBINDIR=\"${bindir}\"
-SUBDIRS = cr fullscreen $(XPR)
 
 libXQuartz_a_SOURCES = \
 		  Preferences.m \
diff --git a/hw/darwin/quartz/cr/Makefile.am b/hw/darwin/quartz/cr/Makefile.am
deleted file mode 100644
index 52a4771..0000000
--- a/hw/darwin/quartz/cr/Makefile.am
+++ /dev/null
@@ -1,20 +0,0 @@
-noinst_LIBRARIES = libcr.a
-AM_CFLAGS =  @XORG_CFLAGS@ @DIX_CFLAGS@
-AM_OBJCFLAGS =  @XORG_CFLAGS@ @DIX_CFLAGS@
-DEFS = @DEFS@ -DDEFER_NSWINDOW
-INCLUDES = @XORG_INCS@ \
-	   -I../fullscreen \
-	   -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. \
-	   -I$(top_srcdir)/miext/rootless \
-	   -I$(top_srcdir)/miext/rootless/safeAlpha \
-	   -I$(top_srcdir)/mi
-
-libcr_a_SOURCES = crAppleWM.m \
-	           crFrame.m \
-	           crScreen.m \
-	           ../fullscreen/quartzCursor.c \
-	           XView.m
-
-EXTRA_DIST = \
-	cr.h \
-	XView.h 
diff --git a/hw/darwin/quartz/cr/crAppleWM.m b/hw/darwin/quartz/cr/crAppleWM.m
index 259c2d8..0741d4e 100644
--- a/hw/darwin/quartz/cr/crAppleWM.m
+++ b/hw/darwin/quartz/cr/crAppleWM.m
@@ -30,8 +30,8 @@
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
-#include "quartzCommon.h"
-#include "cr.h"
+#include "quartz/quartzCommon.h"
+#include "quartz/cr/cr.h"
 
 #undef BOOL
 #define BOOL xBOOL
@@ -39,7 +39,7 @@
 #include "X11/X.h"
 #define _APPLEWM_SERVER_
 #include "X11/extensions/applewm.h"
-#include "applewmExt.h"
+#include "quartz/applewmExt.h"
 #undef BOOL
 
 #define StdDocumentStyleMask (NSTitledWindowMask | \
diff --git a/hw/darwin/quartz/cr/crFrame.m b/hw/darwin/quartz/cr/crFrame.m
index 3c282ea..2b8e57d 100644
--- a/hw/darwin/quartz/cr/crFrame.m
+++ b/hw/darwin/quartz/cr/crFrame.m
@@ -32,13 +32,13 @@
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
-#include "quartzCommon.h"
-#include "cr.h"
+#include "quartz/quartzCommon.h"
+#include "quartz/cr/cr.h"
 
 #undef BOOL
 #define BOOL xBOOL
 #include "rootless.h"
-#include "applewmExt.h"
+#include "quartz/applewmExt.h"
 #include "windowstr.h"
 #undef BOOL
 
diff --git a/hw/darwin/quartz/cr/crScreen.m b/hw/darwin/quartz/cr/crScreen.m
index b78d1ea..9dd130e 100644
--- a/hw/darwin/quartz/cr/crScreen.m
+++ b/hw/darwin/quartz/cr/crScreen.m
@@ -32,18 +32,18 @@
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
-#include "quartzCommon.h"
-#include "cr.h"
+#include "quartz/quartzCommon.h"
+#include "quartz/cr/cr.h"
 
 #undef BOOL
 #define BOOL xBOOL
 #include "darwin.h"
-#include "quartz.h"
-#include "quartzCursor.h"
+#include "quartz/quartz.h"
+#include "quartz/quartzCursor.h"
 #include "rootless.h"
-#include "safeAlpha.h"
-#include "pseudoramiX.h"
-#include "applewmExt.h"
+#include "safeAlpha/safeAlpha.h"
+#include "quartz/pseudoramiX.h"
+#include "quartz/applewmExt.h"
 
 #include "regionstr.h"
 #include "scrnintstr.h"
diff --git a/hw/darwin/quartz/fullscreen/Makefile.am b/hw/darwin/quartz/fullscreen/Makefile.am
deleted file mode 100644
index f56ad42..0000000
--- a/hw/darwin/quartz/fullscreen/Makefile.am
+++ /dev/null
@@ -1,9 +0,0 @@
-noinst_LIBRARIES = libfullscreen.a
-AM_CFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
-INCLUDES = @XORG_INCS@ -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. 
-
-libfullscreen_a_SOURCES = fullscreen.c \
-			   quartzCursor.c
-
-EXTRA_DIST = \
-	quartzCursor.h
diff --git a/hw/darwin/quartz/fullscreen/fullscreen.c b/hw/darwin/quartz/fullscreen/fullscreen.c
index 456c364..02f6e89 100644
--- a/hw/darwin/quartz/fullscreen/fullscreen.c
+++ b/hw/darwin/quartz/fullscreen/fullscreen.c
@@ -25,13 +25,13 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
- #ifdef HAVE_XORG_CONFIG_H
- #include <xorg-config.h>
- #endif
-#include "quartzCommon.h"
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+#include "quartz/quartzCommon.h"
 #include "darwin.h"
-#include "quartz.h"
-#include "quartzCursor.h"
+#include "quartz/quartz.h"
+#include "quartz/quartzCursor.h"
 #include "colormapst.h"
 #include "scrnintstr.h"
 #include "micmap.h"
diff --git a/hw/darwin/quartz/fullscreen/quartzCursor.c b/hw/darwin/quartz/fullscreen/quartzCursor.c
index f3e753c..77fa008 100644
--- a/hw/darwin/quartz/fullscreen/quartzCursor.c
+++ b/hw/darwin/quartz/fullscreen/quartzCursor.c
@@ -32,8 +32,8 @@
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
-#include "quartzCommon.h"
-#include "quartzCursor.h"
+#include "quartz/quartzCommon.h"
+#include "quartz/quartzCursor.h"
 #include "darwin.h"
 
 #include <pthread.h>
diff --git a/hw/darwin/quartz/xpr/Makefile.am b/hw/darwin/quartz/xpr/Makefile.am
deleted file mode 100644
index 7f2b008..0000000
--- a/hw/darwin/quartz/xpr/Makefile.am
+++ /dev/null
@@ -1,29 +0,0 @@
-noinst_LIBRARIES = libxpr.a
-AM_CFLAGS =  @XORG_CFLAGS@ @DIX_CFLAGS@
-INCLUDES = @XORG_INCS@ \
-	   -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. \
-	   -I$(top_srcdir)/miext/rootless/safeAlpha \
-	   -I$(top_srcdir)/miext/rootless \
-	   -I$(top_srcdir)/miext
-
-libxpr_a_SOURCES = \
-	appledri.c \
-        dri.c \
-        xprAppleWM.c \
-        xprCursor.c \
-        xprFrame.c \
-        xprScreen.c \
-        x-hash.c \
-        x-hook.c \
-        x-list.c
-
-xprbundledir = @APPLE_APPLICATIONS_DIR@/Resources/xpr.bundle/Contents/MacOS
-
-EXTRA_DIST = \
-	dri.h \
-	dristruct.h \
-	x-hash.h \
-	x-hook.h \
-	x-list.h \
-	Xplugin.h \
-	xpr.h
diff --git a/hw/darwin/quartz/xpr/xprAppleWM.c b/hw/darwin/quartz/xpr/xprAppleWM.c
index 0c827e2..fdf404c 100644
--- a/hw/darwin/quartz/xpr/xprAppleWM.c
+++ b/hw/darwin/quartz/xpr/xprAppleWM.c
@@ -31,12 +31,11 @@
 #include <xorg-config.h>
 #endif
 #include "xpr.h"
-#include "applewmExt.h"
+#include "quartz/applewmExt.h"
 #include "rootless.h"
 #include "Xplugin.h"
 #include <X11/X.h>
 
-
 static int xprSetWindowLevel(
     WindowPtr pWin,
     int level)
diff --git a/hw/darwin/quartz/xpr/xprCursor.c b/hw/darwin/quartz/xpr/xprCursor.c
index 71a4277..e7f23b7 100644
--- a/hw/darwin/quartz/xpr/xprCursor.c
+++ b/hw/darwin/quartz/xpr/xprCursor.c
@@ -33,7 +33,7 @@
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
-#include "quartzCommon.h"
+#include "quartz/quartzCommon.h"
 #include "xpr.h"
 #include "darwin.h"
 #include "Xplugin.h"
diff --git a/hw/darwin/quartz/xpr/xprFrame.c b/hw/darwin/quartz/xpr/xprFrame.c
index 49f8714..b71b2a6 100644
--- a/hw/darwin/quartz/xpr/xprFrame.c
+++ b/hw/darwin/quartz/xpr/xprFrame.c
@@ -35,7 +35,7 @@
 #include "Xplugin.h"
 #include "x-hash.h"
 #include "x-list.h"
-#include "applewmExt.h"
+#include "quartz/applewmExt.h"
 
 #include "propertyst.h"
 #include "dix.h"
diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index a5bccbf..67a0737 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -30,17 +30,17 @@
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
-#include "quartzCommon.h"
-#include "quartz.h"
+#include "quartz/quartzCommon.h"
+#include "quartz/quartz.h"
 #include "xpr.h"
-#include "pseudoramiX.h"
+#include "quartz/pseudoramiX.h"
 #include "darwin.h"
 #include "rootless.h"
-#include "safeAlpha.h"
+#include "safeAlpha/safeAlpha.h"
 #include "dri.h"
 #include "globals.h"
 #include "Xplugin.h"
-#include "applewmExt.h"
+#include "quartz/applewmExt.h"
 
 #ifdef DAMAGE
 # include "damage.h"
@@ -49,7 +49,6 @@
 // Name of GLX bundle for native OpenGL
 static const char *xprOpenGLBundle = "glxCGL.bundle";
 
-
 /*
  * eventHandler
  *  Callback handler for Xplugin events.
@@ -100,7 +99,6 @@ eventHandler(unsigned int type, const vo
     }
 }
 
-
 /*
  * displayScreenBounds
  *  Return the display ID for a particular display index.
@@ -119,7 +117,6 @@ displayAtIndex(int index)
         return kCGNullDirectDisplay;
 }
 
-
 /*
  * displayScreenBounds
  *  Return the bounds of a particular display.
@@ -142,7 +139,6 @@ displayScreenBounds(CGDirectDisplayID id
     return frame;
 }
 
-
 /*
  * xprAddPseudoramiXScreens
  *  Add a single virtual screen encompassing all the physical screens
@@ -198,7 +194,6 @@ xprAddPseudoramiXScreens(int *x, int *y,
     xfree(displayList);
 }
 
-
 /*
  * xprDisplayInit
  *  Find number of CoreGraphics displays and initialize Xplugin.
@@ -221,9 +216,7 @@ xprDisplayInit(void)
         darwinScreensFound =  1;
 
     if (xp_init(XP_IN_BACKGROUND) != Success)
-    {
         FatalError("Could not initialize the Xplugin library.");
-    }
 
     xp_select_events(XP_EVENT_DISPLAY_CHANGED
                      | XP_EVENT_WINDOW_STATE_CHANGED
@@ -236,7 +229,6 @@ xprDisplayInit(void)
     xprAppleWMInit();
 }
 
-
 /*
  * xprAddScreen
  *  Init the framebuffer and record pixmap parameters for the screen.
@@ -306,7 +298,6 @@ xprAddScreen(int index, ScreenPtr pScree
     return TRUE;
 }
 
-
 /*
  * xprSetupScreen
  *  Setup the screen for rootless access.
@@ -343,7 +334,6 @@ xprSetupScreen(int index, ScreenPtr pScr
     return DRIFinishScreenInit(pScreen);
 }
 
-
 /*
  * xprUpdateScreen
  *  Update screen after configuation change.
@@ -360,7 +350,6 @@ xprUpdateScreen(ScreenPtr pScreen)
     RootlessUpdateScreenPixmap(pScreen);
 }
 
-
 /*
  * xprInitInput
  *  Finalize xpr specific setup.
@@ -377,7 +366,6 @@ xprInitInput(int argc, char **argv)
         AppleWMSetScreenOrigin(WindowTable[i]);
 }
 
-
 /*
  * Quartz display mode function list.
  */
@@ -403,7 +391,6 @@ static QuartzModeProcsRec xprModeProcs =
     DRIDestroySurface
 };
 
-
 /*
  * QuartzModeBundleInit
  *  Initialize the display mode bundle after loading.
diff --git a/mi/miinitext.c b/mi/miinitext.c
index 2c560d5..0fc6d15 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -338,18 +338,18 @@ extern void XFree86DGAExtensionInit(INIT
 #endif
 #ifdef GLXEXT
 typedef struct __GLXprovider __GLXprovider;
-#ifndef __DARWIN__
-extern __GLXprovider __glXMesaProvider;
-extern void GlxPushProvider(__GLXprovider *impl);
-extern void GlxExtensionInit(INITARGS);
-extern void GlxWrapInitVisuals(miInitVisualsProcPtr *);
-#else
+#ifdef INXDARWINAPP
 extern __GLXprovider* __DarwinglXMesaProvider;
 extern void DarwinGlxPushProvider(__GLXprovider *impl);
 extern void DarwinGlxExtensionInit(INITARGS);
 extern void DarwinGlxWrapInitVisuals(miInitVisualsProcPtr *);
-#endif
-#endif
+#else
+extern __GLXprovider __glXMesaProvider;
+extern void GlxPushProvider(__GLXprovider *impl);
+extern void GlxExtensionInit(INITARGS);
+extern void GlxWrapInitVisuals(miInitVisualsProcPtr *);
+#endif // INXDARWINAPP
+#endif // GLXEXT
 #ifdef XF86DRI
 extern void XFree86DRIExtensionInit(INITARGS);
 #endif
@@ -633,14 +633,14 @@ InitExtensions(argc, argv)
 #endif
 
 #ifdef GLXEXT
-#ifndef __DARWIN__
-    GlxPushProvider(&__glXMesaProvider);
-    if (!noGlxExtension) GlxExtensionInit();
-#else
+#ifdef INXDARWINAPP
+    DarwinGlxPushProvider(__DarwinglXMesaProvider);
     if (!noGlxExtension) DarwinGlxExtensionInit();
+#else
     GlxPushProvider(&__glXMesaProvider);
-#endif
-#endif
+    if (!noGlxExtension) GlxExtensionInit();
+#endif // INXDARWINAPP
+#endif // GLXEXT
 #ifdef XFIXES
     /* must be before Render to layer DisplayCursor correctly */
     if (!noXFixesExtension) XFixesExtensionInit();
diff-tree 81444486be4f182dde778bac6f7edcbfc4368482 (from cf4994b0db2fef4c10ce8804adef766bc5118daf)
Author: Ben Byer <bbyer at apple.com>
Date:   Sat Feb 17 02:23:11 2007 -0800

    autoconf goodness for XDarwin, courtesy of pogma

diff --git a/configure.ac b/configure.ac
index a9f85db..3288c09 100644
--- a/configure.ac
+++ b/configure.ac
@@ -280,6 +280,7 @@ case $host_cpu in
 	use_x86_asm="yes"
 	I386_VIDEO=yes
 	case $host_os in
+	        darwin*)	use_x86_asm="no" ;;
 		*linux*)	DEFAULT_INT10=vm86 ;;
 		*freebsd*)	AC_DEFINE(USE_DEV_IO) ;;
 		*netbsd*)	AC_DEFINE(USE_I386_IOPL)
@@ -305,6 +306,7 @@ case $host_cpu in
   	use_x86_asm="yes"
 	I386_VIDEO=yes
 	case $host_os in
+	        darwin*)	use_x86_asm="no" ;;
 		*freebsd*)	AC_DEFINE(USE_DEV_IO, 1, [BSD /dev/io]) ;;
 		*netbsd*)	AC_DEFINE(USE_I386_IOPL, 1, [BSD i386 iopl])
 				SYS_LIBS=-lx86_64
@@ -473,6 +475,10 @@ AC_ARG_WITH(rgb-path,         AS_HELP_ST
 AC_ARG_WITH(dri-driver-path,  AS_HELP_STRING([--with-dri-driver-path=PATH], [Path to DRI drivers (default: ${libdir}/dri)]),
 				[ DRI_DRIVER_PATH="$withval" ],
 				[ DRI_DRIVER_PATH="${libdir}/dri" ])
+APPLE_APPLICATIONS_DIR="${bindir}/Applications"
+AC_ARG_WITH(apple-applications-dir,AS_HELP_STRING([--with-apple-applications-dir=PATH], [Path to the Applications directory (default: ${bindir}/Applications)]),
+                               [ APPLE_APPLICATIONS_DIR="${withval}" ].
+                               [ APPLE_APPLICATIONS_DIR="${bindir}/Applications" ])
 AC_ARG_ENABLE(builddocs,      AS_HELP_STRING([--enable-builddocs], [Build docs (default: disabled)]),
                                 [BUILDDOCS=$enableval],
                                 [BUILDDOCS=no])
@@ -495,6 +501,7 @@ AC_ARG_ENABLE(xres,           AS_HELP_ST
 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: enabled)]), [RECORD=$enableval], [RECORD=yes])
 AC_ARG_ENABLE(xv,             AS_HELP_STRING([--disable-xv], [Build Xv extension (default: enabled)]), [XV=$enableval], [XV=yes])
+AC_ARG_ENABLE(quartz,         AS_HELP_STRING([--enable-quartz], [Build with darwin quartz support (default: auto)]), [XQUARTZ=$enableval], [XQUARTZ=auto])
 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])
 AC_ARG_ENABLE(screensaver,    AS_HELP_STRING([--disable-screensaver], [Build ScreenSaver extension (default: enabled)]), [SCREENSAVER=$enableval], [SCREENSAVER=yes])
@@ -1007,6 +1014,9 @@ if test "x$GCC" = "xyes"; then
        LD_EXPORT_SYMBOLS_FLAG="-rdynamic"
 fi
 case $host_os in
+       darwin*)
+       LD_EXPORT_SYMBOLS_FLAG=""
+       ;;
        openbsd*)
        LD_EXPORT_SYMBOLS_FLAG="-Wl,--export-dynamic"
        ;;
@@ -1064,7 +1074,19 @@ AC_DEFINE([SVR4],1,[Define to 1 on syste
 AC_MSG_RESULT([yes])], AC_MSG_RESULT([no]))
 
 XSERVER_CFLAGS="$XSERVER_CFLAGS $CORE_INCS $XEXT_INC $COMPOSITE_INC $DAMAGE_INC $FIXES_INC $XI_INC $MI_INC $MIEXT_SHADOW_INC $MIEXT_LAYER_INC $MIEXT_DAMAGE_INC $RENDER_INC $RANDR_INC $FB_INC"
-AC_DEFINE_UNQUOTED(X_BYTE_ORDER,[$ENDIAN],[Endian order])
+AC_DEFINE_UNQUOTED(_X_BYTE_ORDER,[$ENDIAN],[Endian order])
+AH_VERBATIM([X_BYTE_ORDER],[
+/* Deal with multiple architecture compiles on Mac OS X */
+#ifndef __APPLE_CC__
+#define X_BYTE_ORDER _X_BYTE_ORDER
+#else
+#ifdef __BIG_ENDIAN__
+#define X_BYTE_ORDER X_BIG_ENDIAN
+#else
+#define X_BYTE_ORDER X_LITTLE_ENDIAN
+#endif
+#endif
+])
 
 AC_SUBST([XSERVER_LIBS])
 
@@ -1155,7 +1177,6 @@ if test "x$XORG" = xauto; then
 	XORG="yes"
 	case $host_os in
 		cygwin*) XORG="no" ;;
-		darwin*) XORG="no" ;;
 	esac
 fi
 AC_MSG_RESULT([$XORG])
@@ -1269,6 +1290,60 @@ dnl has it in libc), or if libdl is need
 		AC_CHECK_LIB([dl], [dlopen], XORG_LIBS="$XORG_LIBS -ldl"))
 
 	case $host_os in
+         darwin*)
+               XORG_OS="Darwin"
+               build_darwin=yes
+               if test "X$XQUARTZ" = Xauto; then
+                 AC_CACHE_CHECK([for Carbon framework],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
+                   AC_DEFINE([DARWIN_WITH_QUARTZ],[1],
+                         [Have Quartz])
+                   XQUARTZ=yes
+                 else
+                   XQUARTZ=no
+                 fi
+               fi
+               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
+               ])
+               AC_CHECK_LIB([Xplugin],[xp_init],[:])
+               AC_SUBST([APPLE_APPLICATIONS_DIR])
+               CFLAGS="${CFLAGS} -D__DARWIN__"
+               PLIST_VERSION_STRING=$VENDOR_VERSION_STRING
+               AC_SUBST([PLIST_VERSION_STRING])
+               PLIST_VENDOR_WEB=$VENDOR_WEB
+               AC_SUBST([PLIST_VENDOR_WEB])
+               # Not sure that we should be disabling all these...
+               if test "x$XF86MISC" = xyes; then
+                       AC_MSG_NOTICE([Disabling XF86Misc extension])
+                       XF86MISC=no
+               fi
+               if test "x$XF86VIDMODE" = xyes; then
+                       AC_MSG_NOTICE([Disabling XF86VidMode extension])
+                       XF86VIDMODE=no
+               fi
+               if test "x$DGA" = xyes; then
+                       AC_MSG_NOTICE([Disabling DGA extension])
+                       DGA=no
+               fi
+               ;;
 	  linux*)
 		if test "x$LNXAPM" = xyes; then
 			XORG_CFLAGS="$XORG_CFLAGS -DXF86PM"
@@ -1391,11 +1466,14 @@ dnl has it in libc), or if libdl is need
 
 	case $host_cpu in
 	  i*86)
-		xorg_bus_ix86pci=yes
+               case $host_os in
+                 darwin*) ;;
+                 *) xorg_bus_ix86pci=yes ;;
+               esac
 		;;
 	  powerpc*)
 		case $host_os in
-		  linux*|freebsd*|netbsd*|openbsd*|kfreebsd*-gnu)
+		  darwin*|linux*|freebsd*|netbsd*|openbsd*|kfreebsd*-gnu)
 			;;
 		  *)
 			xorg_bus_ppcpci="yes"
@@ -1408,7 +1486,7 @@ dnl has it in libc), or if libdl is need
 		;;
 	  x86_64*|amd64*)
 		case $host_os in
-		  freebsd*|kfreebsd*-gnu)
+		  darwin*|freebsd*|kfreebsd*-gnu)
 			# FreeBSD uses the system pci interface
 			;;
 		  *)
@@ -1484,6 +1562,8 @@ AM_CONDITIONAL([SOLARIS_ASM_INLINE], [te
 AM_CONDITIONAL(MFB, [test "x$XORG" = xyes])
 AM_CONDITIONAL(CFB, [test "x$XORG" = xyes])
 AM_CONDITIONAL(AFB, [test "x$XORG" = xyes])
+AM_CONDITIONAL([BUILD_DARWIN],[test "X$build_darwin" = Xyes])
+AM_CONDITIONAL([XQUARTZ],[test "X$XQUARTZ" = Xyes])
 AM_CONDITIONAL(DGA, [test "x$DGA" = xyes])
 
 dnl Xprint DDX
@@ -1494,7 +1574,7 @@ AC_MSG_RESULT([$XPRINT])
 if test "x$XPRINT" = xyes; then
 	PKG_CHECK_MODULES([XPRINT], [printproto x11 xfont $XDMCP_MODULES xau])
 	XPRINT_EXTENSIONS="$XEXT_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $COMPOSITE_LIB $RANDR_LIB $XI_LIB $FIXES_LIB $DAMAGE_LIB $XI_LIB $GLX_LIBS"
-	XPRINT_LIBS="$XPRINT_LIBS $DIX_LIB $CONFIG_LIB $XKB_LIB $XKB_STUB_LIB $XPRINT_EXTENSIONS $MI_LIB $MIEXT_DAMAGE_LIB $CWRAP_LIB $OS_LIB $LIBS"
+	XPRINT_LIBS="$DIX_LIB $CONFIG_LIB $XKB_LIB $XKB_STUB_LIB $XPRINT_EXTENSIONS $MI_LIB $MIEXT_DAMAGE_LIB $CWRAP_LIB $OS_LIB $LIBS $XPRINT_LIBS"
 	AC_SUBST([XPRINT_CFLAGS])
 	AC_SUBST([XPRINT_LIBS])
 
@@ -1608,6 +1688,21 @@ AM_CONDITIONAL(XWIN_PRIMARYFB, [test "x$
 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
+AM_CONDITIONAL(HAVE_X_PLUGIN, [test "x$ac_cv_lib_Xplugin_xp_init" = xyes])
+AM_CONDITIONAL(HAVE_AGL_FRAMEWORK, [test "x$xorg_cv_AGL_framework" = xyes])
+# Support for objc in autotools is minimal and not
+# documented.
+OBJC='$(CC)'
+OBJCLD='$(CCLD)'
+OBJCLINK='$(LINK)'
+OBJCFLAGS='$(CFLAGS)'
+AC_SUBST([OBJC])
+AC_SUBST([OBJCCLD])
+AC_SUBST([OBJCLINK])
+AC_SUBST([OBJCFLAGS])
+# internal, undocumented automake func follows :(
+_AM_DEPENDENCIES([OBJC])
 
 dnl kdrive DDX
 
@@ -1737,12 +1832,6 @@ AM_CONDITIONAL(XFAKESERVER, [test "x$KDR
 AM_CONDITIONAL(KDRIVEVESA, [test x"$ac_cv_header_sys_vm86_h" = xyes])
 AM_CONDITIONAL(KDRIVEFBDEV, [test x"$ac_cv_header_linux_fb_h" = xyes])
 
-dnl XDarwin DDX (FIXME)
-AM_CONDITIONAL(XQUARTZ, false)
-AM_CONDITIONAL(HAVE_X_PLUGIN, false)
-AM_CONDITIONAL(HAVE_AGL_FRAMEWORK, false)
-AM_CONDITIONAL(BUILD_DARWIN, false)
-
 dnl these only go in xkb-config.h (which is shared by the Xorg and Xnest servers)
 AC_DEFINE(__XKBDEFRULES__, "xorg", [Default XKB rules])
 AC_DEFINE_DIR(XKB_BASE_DIRECTORY, XKBPATH, [Path to XKB data])
@@ -1847,6 +1936,7 @@ XORG_RELEASE_VERSION
 AC_OUTPUT([
 Makefile
 GL/Makefile
+GL/apple/Makefile
 GL/glx/Makefile
 GL/mesa/Makefile
 GL/mesa/glapi/Makefile
@@ -1880,6 +1970,8 @@ miext/damage/Makefile
 miext/shadow/Makefile
 miext/cw/Makefile
 miext/rootless/Makefile
+miext/rootless/safeAlpha/Makefile
+miext/rootless/accel/Makefile
 os/Makefile
 randr/Makefile
 render/Makefile
@@ -1957,6 +2049,22 @@ hw/xgl/glxext/module/Makefile
 hw/xnest/Makefile
 hw/xwin/Makefile
 hw/darwin/Makefile
+hw/darwin/bundle/Makefile
+hw/darwin/bundle/Dutch.lproj/Makefile
+hw/darwin/bundle/English.lproj/Makefile
+hw/darwin/bundle/French.lproj/Makefile
+hw/darwin/bundle/German.lproj/Makefile
+hw/darwin/bundle/Japanese.lproj/Makefile
+hw/darwin/bundle/Portuguese.lproj/Makefile
+hw/darwin/bundle/Spanish.lproj/Makefile
+hw/darwin/bundle/Swedish.lproj/Makefile
+hw/darwin/bundle/ko.lproj/Makefile
+hw/darwin/iokit/Makefile
+hw/darwin/quartz/Makefile
+hw/darwin/quartz/cr/Makefile
+hw/darwin/quartz/fullscreen/Makefile
+hw/darwin/quartz/xpr/Makefile
+hw/darwin/utils/Makefile
 hw/kdrive/Makefile
 hw/kdrive/ati/Makefile
 hw/kdrive/chips/Makefile
diff --git a/dix/devices.c b/dix/devices.c
index 0739de6..9f42184 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -213,11 +213,7 @@ CoreKeyboardBell(int volume, DeviceIntPt
 {
     KeybdCtrl *ctrl = arg;
 
-#ifdef __DARWIN__
-    // not yet implemented :(
-#else
     DDXRingBell(volume, ctrl->bell_pitch, ctrl->bell_duration);
-#endif
 }
 
 static void
diff --git a/hw/darwin/darwin.c b/hw/darwin/darwin.c
index e33c321..7da8626 100644
--- a/hw/darwin/darwin.c
+++ b/hw/darwin/darwin.c
@@ -204,6 +204,12 @@ DarwinPrintBanner()
 }
 
 
+void DDXRingBell(int volume, int pitch, int duration)
+{
+  // FIXME -- make some noise, yo
+}
+
+
 /*
  * DarwinSaveScreen
  *  X screensaver support. Not implemented.
diff --git a/hw/darwin/utils/Makefile.am b/hw/darwin/utils/Makefile.am
new file mode 100644
index 0000000..11a2611
--- /dev/null
+++ b/hw/darwin/utils/Makefile.am
@@ -0,0 +1,11 @@
+bin_PROGRAMS = dumpkeymap
+
+dumpkeymap_SOURCES = dumpkeymap.c
+
+dumpkeymap_LDFLAGS = -Wl,-framework,IOKit
+
+man1_MANS = dumpkeymap.man
+
+EXTRA_DIST = \
+            README.txt \
+            dumpkeymap.man
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 458e3a1..62e109b 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -35,6 +35,9 @@
 /* Support Damage extension */
 #undef DAMAGE
 
+/* Build for darwin with Quartz support */
+#undef DARWIN_WITH_QUARTZ
+
 /* Use OsVendorInit */
 #undef DDXOSINIT
 
@@ -420,7 +423,17 @@
 #undef XVENDORNAME
 
 /* Endian order */
-#undef X_BYTE_ORDER
+#undef _X_BYTE_ORDER
+/* Deal with multiple architecture compiles on Mac OS X */
+#ifndef __APPLE_CC__
+#define X_BYTE_ORDER _X_BYTE_ORDER
+#else
+#ifdef __BIG_ENDIAN__
+#define X_BYTE_ORDER X_BIG_ENDIAN
+#else
+#define X_BYTE_ORDER X_LITTLE_ENDIAN
+#endif
+#endif
 
 /* Enable GNU and other extensions to the C environment for GLIBC */
 #undef _GNU_SOURCE
diff --git a/include/xorg-server.h.in b/include/xorg-server.h.in
index 48196d8..7b2a4d1 100644
--- a/include/xorg-server.h.in
+++ b/include/xorg-server.h.in
@@ -191,7 +191,17 @@
 #undef XVENDORNAME
 
 /* Endian order */
-#undef X_BYTE_ORDER
+#undef _X_BYTE_ORDER
+/* Deal with multiple architecture compiles on Mac OS X */
+#ifndef __APPLE_CC__
+#define X_BYTE_ORDER _X_BYTE_ORDER
+#else
+#ifdef __BIG_ENDIAN__
+#define X_BYTE_ORDER X_BIG_ENDIAN
+#else
+#define X_BYTE_ORDER X_LITTLE_ENDIAN
+#endif
+#endif
 
 /* BSD-compliant source */
 #undef _BSD_SOURCE
diff-tree cf4994b0db2fef4c10ce8804adef766bc5118daf (from cece0601571f6304e392a3a40505664544b249f3)
Author: Ben Byer <bbyer at apple.com>
Date:   Sat Feb 17 01:21:43 2007 -0800

    dix mods for Darwin

diff --git a/dix/devices.c b/dix/devices.c
index 9f42184..0739de6 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -213,7 +213,11 @@ CoreKeyboardBell(int volume, DeviceIntPt
 {
     KeybdCtrl *ctrl = arg;
 
+#ifdef __DARWIN__
+    // not yet implemented :(
+#else
     DDXRingBell(volume, ctrl->bell_pitch, ctrl->bell_duration);
+#endif
 }
 
 static void
diff --git a/dix/dixfonts.c b/dix/dixfonts.c
index d5b42dc..5f087a3 100644
--- a/dix/dixfonts.c
+++ b/dix/dixfonts.c
@@ -64,6 +64,7 @@ Equipment Corporation.
 #include "opaque.h"
 #include "dixfontstr.h"
 #include "closestr.h"
+#include "dixfont.h"
 
 #ifdef DEBUG
 #include	<stdio.h>
diff --git a/hw/Makefile.am b/hw/Makefile.am
index d00d6fb..99df8e2 100644
--- a/hw/Makefile.am
+++ b/hw/Makefile.am
@@ -1,10 +1,18 @@
 if DMX
+if BUILD_DARWIN
+# Darwin does not need the dmx subdir
+else
 DMX_SUBDIRS = dmx
 endif
+endif
 
 if XORG
+if BUILD_DARWIN
+# Darwin does not need the xfree86 subdir
+else
 XORG_SUBDIRS = xfree86
 endif
+endif
 
 if XVFB
 XVFB_SUBDIRS = vfb
@@ -30,12 +38,15 @@ if XPRINT
 XPRINT_SUBDIRS = xprint
 endif
 
-# need to add darwin support here
+if BUILD_DARWIN
+DARWIN_SUBDIRS = darwin
+endif
 
 SUBDIRS =			\
 	$(XORG_SUBDIRS)		\
 	$(XGL_SUBDIRS)		\
 	$(XWIN_SUBDIRS)		\
+	$(DARWIN_SUBDIRS)	\
 	$(XVFB_SUBDIRS)		\
 	$(XNEST_SUBDIRS)	\
 	$(DMX_SUBDIRS)          \
diff --git a/hw/xfree86/common/xf86Init.c b/hw/xfree86/common/xf86Init.c
index ff878d5..221ab9a 100644
--- a/hw/xfree86/common/xf86Init.c
+++ b/hw/xfree86/common/xf86Init.c
@@ -36,6 +36,7 @@
 #endif
 
 #include <stdlib.h>
+#include <errno.h>
 
 #undef HAS_UTSNAME
 #if !defined(WIN32) && !defined(__UNIXOS2__)
diff --git a/mi/miinitext.c b/mi/miinitext.c
index cb34473..2c560d5 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -338,12 +338,14 @@ extern void XFree86DGAExtensionInit(INIT
 #endif
 #ifdef GLXEXT
 typedef struct __GLXprovider __GLXprovider;
+#ifndef __DARWIN__
 extern __GLXprovider __glXMesaProvider;
 extern void GlxPushProvider(__GLXprovider *impl);
-#ifndef __DARWIN__
 extern void GlxExtensionInit(INITARGS);
 extern void GlxWrapInitVisuals(miInitVisualsProcPtr *);
 #else
+extern __GLXprovider* __DarwinglXMesaProvider;
+extern void DarwinGlxPushProvider(__GLXprovider *impl);
 extern void DarwinGlxExtensionInit(INITARGS);
 extern void DarwinGlxWrapInitVisuals(miInitVisualsProcPtr *);
 #endif
@@ -629,13 +631,14 @@ InitExtensions(argc, argv)
     if (!noXFree86DRIExtension) XFree86DRIExtensionInit();
 #endif
 #endif
-#ifdef GLXEXT
 
-    GlxPushProvider(&__glXMesaProvider);
+#ifdef GLXEXT
 #ifndef __DARWIN__
+    GlxPushProvider(&__glXMesaProvider);
     if (!noGlxExtension) GlxExtensionInit();
 #else
     if (!noGlxExtension) DarwinGlxExtensionInit();
+    GlxPushProvider(&__glXMesaProvider);
 #endif
 #endif
 #ifdef XFIXES
diff-tree cece0601571f6304e392a3a40505664544b249f3 (from 00b0657b815b95964401c3e36eed54063afbd003)
Author: Ben Byer <bbyer at apple.com>
Date:   Sat Feb 17 01:00:13 2007 -0800

    build fix for configure.ac / BUILD_DARWIN, oops

diff --git a/configure.ac b/configure.ac
index d2d2c87..a9f85db 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1741,6 +1741,7 @@ dnl XDarwin DDX (FIXME)
 AM_CONDITIONAL(XQUARTZ, false)
 AM_CONDITIONAL(HAVE_X_PLUGIN, false)
 AM_CONDITIONAL(HAVE_AGL_FRAMEWORK, false)
+AM_CONDITIONAL(BUILD_DARWIN, false)
 
 dnl these only go in xkb-config.h (which is shared by the Xorg and Xnest servers)
 AC_DEFINE(__XKBDEFRULES__, "xorg", [Default XKB rules])
diff-tree 00b0657b815b95964401c3e36eed54063afbd003 (from 93777c7b96e560da087963040e372aecbfca7bbc)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Sat Feb 17 00:55:32 2007 -0800

    glx fixes for XDarwin

diff --git a/GL/Makefile.am b/GL/Makefile.am
index b9337ba..df9f533 100644
--- a/GL/Makefile.am
+++ b/GL/Makefile.am
@@ -1,16 +1,16 @@
-SUBDIRS = glx mesa
-
 # someone could get really crazy someday and add support for the SI...
 
 # xwin/darwin/xfree86 have their accel support under the DDX
 
-APPLE_EXTRAS = \
-	apple/aglGlx.c \
-	apple/indirect.c
+if BUILD_DARWIN
+DARWIN_SUBDIRS = apple
+endif
+SUBDIRS = glx mesa $(DARWIN_SUBDIRS)
+
 WINDOWS_EXTRAS = \
 	windows/ChangeLog \
 	windows/glwindows.h \
 	windows/glwrap.c \
 	windows/indirect.c
 
-EXTRA_DIST = symlink-mesa.sh $(APPLE_EXTRAS) $(WINDOWS_EXTRAS)
+EXTRA_DIST = symlink-mesa.sh $(WINDOWS_EXTRAS)
diff --git a/GL/apple/Makefile.am b/GL/apple/Makefile.am
new file mode 100644
index 0000000..2b2d10c
--- /dev/null
+++ b/GL/apple/Makefile.am
@@ -0,0 +1,15 @@
+AM_CFLAGS = -I$(top_srcdir) \
+	 -I$(top_srcdir)/hw/darwin/quartz \
+	 -I$(top_srcdir)/GL/glx \
+	 -I$(top_srcdir)/hw/darwin/quartz/cr \
+	 -I$(top_srcdir)/GL/include
+
+if HAVE_AGL_FRAMEWORK
+noinst_LIBRARIES = libAGLcore.a 
+libAGLcore_a_SOURCES = aglGlx.c \
+		       $(top_srcdir)/hw/darwin/quartz/xpr/x-list.c \
+		       $(top_srcdir)/hw/darwin/quartz/xpr/x-list.h \
+		       $(top_srcdir)/hw/darwin/quartz/xpr/x-hash.c \
+		       $(top_srcdir)/hw/darwin/quartz/xpr/x-hash.h \
+		       $(top_srcdir)/hw/dmx/glxProxy/compsize.c
+endif
diff --git a/GL/glx/glxbyteorder.h b/GL/glx/glxbyteorder.h
index b9d738d..cdf6b15 100644
--- a/GL/glx/glxbyteorder.h
+++ b/GL/glx/glxbyteorder.h
@@ -39,6 +39,11 @@
 #include <byteswap.h>
 #elif defined(USE_SYS_ENDIAN_H)
 #include <sys/endian.h>
+#elif defined(__APPLE__)
+#include <libkern/OSByteOrder.h>
+#define bswap_16 OSSwapInt16
+#define bswap_32 OSSwapInt32
+#define bswap_64 OSSwapInt64
 #else
 #define	bswap_16(value)  \
  	((((value) & 0xff) << 8) | ((value) >> 8))
diff-tree 93777c7b96e560da087963040e372aecbfca7bbc (from 612144c811fdf06b7c03cf48a321388fe411acd4)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Sat Feb 17 00:22:39 2007 -0800

    more patches to make the Quartz part of XDarwin work again
    (thanks Peter and Torrey!)

diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
new file mode 100644
index 0000000..9789330
--- /dev/null
+++ b/hw/darwin/quartz/Makefile.am
@@ -0,0 +1,56 @@
+noinst_LIBRARIES = libXQuartz.a
+
+AM_CFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
+AM_OBJCFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
+
+INCLUDES = -I$(srcdir) -I$(srcdir)/.. @XORG_INCS@
+AM_DEFS = -DHAS_CG_MACH_PORT -DHAS_KL_API
+if HAVE_X_PLUGIN
+AM_DEFS += -DBUILD_XPR
+XPR = xpr
+endif
+DEFS = @DEFS@ $(AM_DEFS) -DXBINDIR=\"${bindir}\"
+SUBDIRS = cr fullscreen $(XPR)
+
+libXQuartz_a_SOURCES = \
+		  Preferences.m \
+	          XApplication.m \
+	          XServer.m \
+	          applewm.c \
+	          keysym2ucs.c \
+	          quartz.c \
+	          quartzAudio.c \
+	          quartzCocoa.m \
+	          quartzPasteboard.c \
+	          quartzKeyboard.c \
+	          quartzStartup.c \
+	          pseudoramiX.c
+
+bin_PROGRAMS = XDarwinStartup
+
+XDarwinStartup_SOURCES = XDarwinStartup.c
+XDarwinStartup_LDFLAGS = -Wl,-framework,CoreFoundation \
+			 -Wl,-framework,ApplicationServices
+XDarwinStartupCFLAGS = -DXBINDIR="${bindir}"
+XDARWINROOT = @APPLE_APPLICATIONS_DIR@
+BINDIR = $(bindir)
+install-exec-local:
+	-(cd $(DESTDIR)$(BINDIR); rm X; $(LN_S) XDarwinStartup X)
+
+man1_MANS = XDarwinStartup.man
+
+EXTRA_DIST = \
+	applewmExt.h \
+	keysym2ucs.h \
+	Preferences.h \
+	pseudoramiX.h \
+	quartzAudio.h \
+	quartzCommon.h \
+	quartzCursor.c \
+	quartzCursor.h \
+	quartz.h \
+	quartzPasteboard.h \
+	XApplication.h \
+	XDarwin.pbproj/project.pbxproj \
+	XServer.h \
+	XDarwinStartup.man
diff --git a/hw/darwin/quartz/Preferences.m b/hw/darwin/quartz/Preferences.m
index 6c14f49..eb78fd3 100644
--- a/hw/darwin/quartz/Preferences.m
+++ b/hw/darwin/quartz/Preferences.m
@@ -31,7 +31,9 @@
  * authorization.
  */
 /* $XFree86: xc/programs/Xserver/hw/darwin/quartz/Preferences.m,v 1.5 2004/06/08 22:58:10 torrey Exp $ */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #import "quartzCommon.h"
 
 #define BOOL xBOOL
@@ -44,7 +46,7 @@
 
 // Macros to build the path name
 #ifndef XBINDIR
-#define XBINDIR /usr/X11R6/bin
+#define XBINDIR /usr/X11/bin
 #endif
 #define STR(s) #s
 #define XSTRPATH(s) STR(s)
diff --git a/hw/darwin/quartz/XDarwin.pbproj/project.pbxproj b/hw/darwin/quartz/XDarwin.pbproj/project.pbxproj
index 90002db..0ad8314 100644
--- a/hw/darwin/quartz/XDarwin.pbproj/project.pbxproj
+++ b/hw/darwin/quartz/XDarwin.pbproj/project.pbxproj
@@ -387,7 +387,7 @@
 	<key>CFBundleIconFile</key>
 	<string>XDarwin.icns</string>
 	<key>CFBundleIdentifier</key>
-	<string>org.xfree86.XDarwin</string>
+	<string>org.x.x11</string>
 	<key>CFBundleInfoDictionaryVersion</key>
 	<string>6.0</string>
 	<key>CFBundleName</key>
diff --git a/hw/darwin/quartz/XDarwinStartup.c b/hw/darwin/quartz/XDarwinStartup.c
index 8697776..8041e32 100644
--- a/hw/darwin/quartz/XDarwinStartup.c
+++ b/hw/darwin/quartz/XDarwinStartup.c
@@ -48,7 +48,7 @@
 
 // Macros to build the path name
 #ifndef XBINDIR
-#define XBINDIR /usr/X11R6/bin
+#define XBINDIR /usr/X11/bin
 #endif
 #define STR(s) #s
 #define XSTRPATH(s) STR(s) "/"
@@ -124,7 +124,7 @@ int main(
 
         // Otherwise query LaunchServices for the location of the XDarwin application
         theStatus = LSFindApplicationForInfo(kLSUnknownCreator,
-                                             CFSTR("org.xfree86.XDarwin"),
+                                             CFSTR("org.x.x11"),
                                              NULL, NULL, &appURL);
         if (theStatus) {
             fprintf(stderr, "Could not find the XDarwin application. (Error = 0x%lx)\n", theStatus);
diff --git a/hw/darwin/quartz/XServer.m b/hw/darwin/quartz/XServer.m
index a5a1011..32bfbf5 100644
--- a/hw/darwin/quartz/XServer.m
+++ b/hw/darwin/quartz/XServer.m
@@ -36,18 +36,20 @@
  */
 /* $XdotOrg: xc/programs/Xserver/hw/darwin/quartz/XServer.m,v 1.3 2004/07/30 19:12:17 torrey Exp $ */
 /* $XFree86: xc/programs/Xserver/hw/darwin/quartz/XServer.m,v 1.19 2003/11/24 05:39:01 torrey Exp $ */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 
 #define BOOL xBOOL
-#include "X.h"
-#include "Xproto.h"
+#include "X11/X.h"
+#include "X11/Xproto.h"
 #include "os.h"
 #include "opaque.h"
 #include "darwin.h"
 #include "quartz.h"
 #define _APPLEWM_SERVER_
-#include "applewm.h"
+#include "X11/extensions/applewm.h"
 #include "applewmExt.h"
 #undef BOOL
 
@@ -830,13 +832,13 @@ static io_connect_t root_port;
                     chdir(tem);
 
                 /* Setup environment */
-                snprintf(buf, sizeof(buf), ":%s", display);
-                setenv("DISPLAY", buf, TRUE);
+//              snprintf(buf, sizeof(buf), ":%s", display);
+//              setenv("DISPLAY", buf, TRUE);
                 tem = getenv("PATH");
                 if (tem != NULL && tem[0] != NULL)
-                    snprintf(buf, sizeof(buf), "%s:/usr/X11R6/bin", tem);
+                    snprintf(buf, sizeof(buf), "%s:/usr/X11/bin", tem);
                 else
-                    snprintf(buf, sizeof(buf), "/bin:/usr/bin:/usr/X11R6/bin");
+                    snprintf(buf, sizeof(buf), "/bin:/usr/bin:/usr/X11/bin");
                 setenv("PATH", buf, TRUE);
 
                 execvp(argv[0], (char **const) argv);
diff --git a/hw/darwin/quartz/applewm.c b/hw/darwin/quartz/applewm.c
index 224d6c5..869f7a9 100644
--- a/hw/darwin/quartz/applewm.c
+++ b/hw/darwin/quartz/applewm.c
@@ -24,7 +24,9 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF 
 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 **************************************************************************/
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 
 #define NEED_REPLIES
@@ -43,7 +45,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN
 #include <X11/Xatom.h>
 #include "darwin.h"
 #define _APPLEWM_SERVER_
-#include "applewmstr.h"
+#include "X11/extensions/applewmstr.h"
 #include "applewmExt.h"
 
 #define DEFINE_ATOM_HELPER(func,atom_name)                      \
diff --git a/hw/darwin/quartz/pseudoramiX.c b/hw/darwin/quartz/pseudoramiX.c
index a003daf..7ba6d5a 100644
--- a/hw/darwin/quartz/pseudoramiX.c
+++ b/hw/darwin/quartz/pseudoramiX.c
@@ -34,7 +34,9 @@ Equipment Corporation.
 ******************************************************************/
 
 #include "pseudoramiX.h"
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "extnsionst.h"
 #include "dixstruct.h"
 #include "window.h"
diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 36a8bea..913ea72 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -29,14 +29,16 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "quartz.h"
 #include "darwin.h"
 #include "quartzAudio.h"
 #include "pseudoramiX.h"
 #define _APPLEWM_SERVER_
-#include "applewm.h"
+#include "X11/extensions/applewm.h"
 #include "applewmExt.h"
 
 // X headers
diff --git a/hw/darwin/quartz/quartzAudio.c b/hw/darwin/quartz/quartzAudio.c
index b477b03..16b9c2b 100644
--- a/hw/darwin/quartz/quartzAudio.c
+++ b/hw/darwin/quartz/quartzAudio.c
@@ -35,7 +35,9 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "quartzAudio.h"
 
@@ -44,6 +46,7 @@
 
 #include "inputstr.h"
 #include <X11/extensions/XI.h>
+#include <assert.h>
 
 void NSBeep();
 
diff --git a/hw/darwin/quartz/quartzCocoa.m b/hw/darwin/quartz/quartzCocoa.m
index 3cb191f..c54c18a 100644
--- a/hw/darwin/quartz/quartzCocoa.m
+++ b/hw/darwin/quartz/quartzCocoa.m
@@ -35,6 +35,9 @@
  * use or other dealings in this Software without prior written authorization.
  */
 /* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCocoa.m,v 1.5 2004/06/08 22:58:10 torrey Exp $ */
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 
 #include "quartzCommon.h"
 
diff --git a/hw/darwin/quartz/quartzCursor.c b/hw/darwin/quartz/quartzCursor.c
index e2333e2..1e618e3 100644
--- a/hw/darwin/quartz/quartzCursor.c
+++ b/hw/darwin/quartz/quartzCursor.c
@@ -30,6 +30,9 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "quartzCursor.h"
 #include "darwin.h"
diff --git a/hw/darwin/quartz/quartzCursor.h b/hw/darwin/quartz/quartzCursor.h
index 56cc94d..57fac68 100644
--- a/hw/darwin/quartz/quartzCursor.h
+++ b/hw/darwin/quartz/quartzCursor.h
@@ -36,6 +36,7 @@
 #include "screenint.h"
 
 Bool QuartzInitCursor(ScreenPtr pScreen);
+void QuartzReallySetCursor(void);
 void QuartzSuspendXCursor(ScreenPtr pScreen);
 void QuartzResumeXCursor(ScreenPtr pScreen, int x, int y);
 
diff --git a/hw/darwin/quartz/quartzKeyboard.c b/hw/darwin/quartz/quartzKeyboard.c
index fc12522..bd2cc25 100644
--- a/hw/darwin/quartz/quartzKeyboard.c
+++ b/hw/darwin/quartz/quartzKeyboard.c
@@ -33,13 +33,16 @@
    prior written authorization.
 */
 
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 
 #include <CoreServices/CoreServices.h>
 #include <Carbon/Carbon.h>
 
 #include "darwinKeyboard.h"
-#include "keysym.h"
+#include "X11/keysym.h"
 #include "keysym2ucs.h"
 
 #ifdef HAS_KL_API
diff --git a/hw/darwin/quartz/quartzPasteboard.c b/hw/darwin/quartz/quartzPasteboard.c
index e92fe5c..a3536fc 100644
--- a/hw/darwin/quartz/quartzPasteboard.c
+++ b/hw/darwin/quartz/quartzPasteboard.c
@@ -30,6 +30,9 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzPasteboard.h"
 
 #include <X11/Xatom.h>
diff --git a/hw/darwin/quartz/quartzStartup.c b/hw/darwin/quartz/quartzStartup.c
index 277e593..38fde3c 100644
--- a/hw/darwin/quartz/quartzStartup.c
+++ b/hw/darwin/quartz/quartzStartup.c
@@ -37,7 +37,7 @@
 #include "quartz.h"
 #include "opaque.h"
 #include "micmap.h"
-
+#include <assert.h>
 int NSApplicationMain(int argc, char *argv[]);
 
 char **envpGlobal;      // argcGlobal and argvGlobal
@@ -52,6 +52,9 @@ static GlxWrapInitVisualsPtr GlxWrapInit
 
 typedef Bool (*QuartzModeBundleInitPtr)(void);
 
+void * __DarwinglXMesaProvider = NULL;
+typedef void (*GlxPushProviderPtr)(void *);
+GlxPushProviderPtr GlxPushProvider = NULL;
 
 /*
  * DarwinHandleGUI
@@ -186,7 +189,7 @@ static void LoadGlxBundle(void)
 
     // Choose the bundle to load
     ErrorF("Loading GLX bundle ");
-    if (quartzUseAGL) {
+    if (/*quartzUseAGL*/0) {
         bundleName = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault,
                                                      quartzOpenGLBundle,
                                                      kCFStringEncodingASCII,
@@ -213,6 +216,14 @@ static void LoadGlxBundle(void)
     }
 
     // Find the GLX init functions
+
+
+    __DarwinglXMesaProvider = (void *) CFBundleGetDataPointerForName(
+			       glxBundle, CFSTR("__glXMesaProvider"));
+
+    GlxPushProvider = (void *) CFBundleGetFunctionPointerForName(
+                                glxBundle, CFSTR("GlxPushProvider"));
+
     GlxExtensionInit = (void *) CFBundleGetFunctionPointerForName(
                                 glxBundle, CFSTR("GlxExtensionInit"));
 
@@ -233,6 +244,18 @@ static void LoadGlxBundle(void)
  * DarwinGlxExtensionInit
  *  Initialize the GLX extension.
  */
+void DarwinGlxPushProvider(void *impl)
+{
+    if (!GlxExtensionInit)
+        LoadGlxBundle();
+	
+    GlxPushProvider(impl);
+}
+
+/*
+ * DarwinGlxExtensionInit
+ *  Initialize the GLX extension.
+ */
 void DarwinGlxExtensionInit(void)
 {
     if (!GlxExtensionInit)
diff-tree 612144c811fdf06b7c03cf48a321388fe411acd4 (from 68d39d8571d8717d26cedc84015d537549520a14)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Sat Feb 17 00:09:58 2007 -0800

    More build fixes / updates for XDarwin:
       quartz/cr: "Cocoa Rootless" support (deprecated in favor of xpr?)
       quartz/fullscreen: Fullscreen support using Xplugin (not yet functional)

diff --git a/hw/darwin/quartz/cr/Makefile.am b/hw/darwin/quartz/cr/Makefile.am
new file mode 100644
index 0000000..52a4771
--- /dev/null
+++ b/hw/darwin/quartz/cr/Makefile.am
@@ -0,0 +1,20 @@
+noinst_LIBRARIES = libcr.a
+AM_CFLAGS =  @XORG_CFLAGS@ @DIX_CFLAGS@
+AM_OBJCFLAGS =  @XORG_CFLAGS@ @DIX_CFLAGS@
+DEFS = @DEFS@ -DDEFER_NSWINDOW
+INCLUDES = @XORG_INCS@ \
+	   -I../fullscreen \
+	   -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. \
+	   -I$(top_srcdir)/miext/rootless \
+	   -I$(top_srcdir)/miext/rootless/safeAlpha \
+	   -I$(top_srcdir)/mi
+
+libcr_a_SOURCES = crAppleWM.m \
+	           crFrame.m \
+	           crScreen.m \
+	           ../fullscreen/quartzCursor.c \
+	           XView.m
+
+EXTRA_DIST = \
+	cr.h \
+	XView.h 
diff --git a/hw/darwin/quartz/cr/XView.m b/hw/darwin/quartz/cr/XView.m
index 5feac6b..8bcd1a7 100644
--- a/hw/darwin/quartz/cr/XView.m
+++ b/hw/darwin/quartz/cr/XView.m
@@ -30,7 +30,9 @@
  * use or other dealings in this Software without prior written authorization.
  */
 /* $XFree86: xc/programs/Xserver/hw/darwin/quartz/cr/XView.m,v 1.1 2003/06/07 05:49:07 torrey Exp $ */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #import "XView.h"
 
 
diff --git a/hw/darwin/quartz/cr/crAppleWM.m b/hw/darwin/quartz/cr/crAppleWM.m
index a2e97ff..259c2d8 100644
--- a/hw/darwin/quartz/cr/crAppleWM.m
+++ b/hw/darwin/quartz/cr/crAppleWM.m
@@ -27,16 +27,18 @@
  * use or other dealings in this Software without prior written authorization.
  */
 /* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xprFrame.c,v 1.2 2003/06/30 01:45:13 torrey Exp $ */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "cr.h"
 
 #undef BOOL
 #define BOOL xBOOL
 #include "rootless.h"
-#include "X.h"
+#include "X11/X.h"
 #define _APPLEWM_SERVER_
-#include "applewm.h"
+#include "X11/extensions/applewm.h"
 #include "applewmExt.h"
 #undef BOOL
 
diff --git a/hw/darwin/quartz/cr/crFrame.m b/hw/darwin/quartz/cr/crFrame.m
index 79d55a4..3c282ea 100644
--- a/hw/darwin/quartz/cr/crFrame.m
+++ b/hw/darwin/quartz/cr/crFrame.m
@@ -29,7 +29,9 @@
  */
 /* $XdotOrg: xc/programs/Xserver/hw/darwin/quartz/cr/crFrame.m,v 1.2 2004/04/23 19:15:51 eich Exp $ */
 /* $XFree86: xc/programs/Xserver/hw/darwin/quartz/cr/crFrame.m,v 1.9 2004/03/19 02:05:29 torrey Exp $ */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "cr.h"
 
diff --git a/hw/darwin/quartz/cr/crScreen.m b/hw/darwin/quartz/cr/crScreen.m
index 21a79e0..b78d1ea 100644
--- a/hw/darwin/quartz/cr/crScreen.m
+++ b/hw/darwin/quartz/cr/crScreen.m
@@ -29,7 +29,9 @@
  * use or other dealings in this Software without prior written authorization.
  */
 /* $XFree86: xc/programs/Xserver/hw/darwin/quartz/cr/crScreen.m,v 1.5 2003/11/12 20:21:52 torrey Exp $ */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "cr.h"
 
diff --git a/hw/darwin/quartz/fullscreen/Makefile.am b/hw/darwin/quartz/fullscreen/Makefile.am
new file mode 100644
index 0000000..f56ad42
--- /dev/null
+++ b/hw/darwin/quartz/fullscreen/Makefile.am
@@ -0,0 +1,9 @@
+noinst_LIBRARIES = libfullscreen.a
+AM_CFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
+INCLUDES = @XORG_INCS@ -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. 
+
+libfullscreen_a_SOURCES = fullscreen.c \
+			   quartzCursor.c
+
+EXTRA_DIST = \
+	quartzCursor.h
diff --git a/hw/darwin/quartz/fullscreen/fullscreen.c b/hw/darwin/quartz/fullscreen/fullscreen.c
index a4881f9..456c364 100644
--- a/hw/darwin/quartz/fullscreen/fullscreen.c
+++ b/hw/darwin/quartz/fullscreen/fullscreen.c
@@ -25,7 +25,9 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+ #ifdef HAVE_XORG_CONFIG_H
+ #include <xorg-config.h>
+ #endif
 #include "quartzCommon.h"
 #include "darwin.h"
 #include "quartz.h"
diff --git a/hw/darwin/quartz/fullscreen/quartzCursor.c b/hw/darwin/quartz/fullscreen/quartzCursor.c
index e2333e2..f3e753c 100644
--- a/hw/darwin/quartz/fullscreen/quartzCursor.c
+++ b/hw/darwin/quartz/fullscreen/quartzCursor.c
@@ -29,7 +29,9 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "quartzCursor.h"
 #include "darwin.h"
diff-tree 68d39d8571d8717d26cedc84015d537549520a14 (from 5507cb885d861e974be240120ada2ace2a980a72)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Fri Feb 16 23:02:13 2007 +0200

    kdrive/ephyr: fix keysym type confusion once and for all
    
    Take keysyms in as an XID in hostx_load_keymap() and explicitly
    convert them to CARD32 for loading into the server.  Fixes Xephyr on
    AMD64, wa-hey.

diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index 573f774..36d3cbd 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -656,7 +656,7 @@ hostx_paint_debug_rect(int x,     int y,
 void
 hostx_load_keymap(void)
 {
-  KeySym          *keymap;
+  XID             *keymap;
   int              host_width, min_keycode, max_keycode, width;
   int              i,j;
 
@@ -677,7 +677,7 @@ hostx_load_keymap(void)
    */
   width = (host_width > 4) ? 4 : host_width;
 
-  ephyrKeySyms.map = (KeySym *)calloc(sizeof(KeySym),
+  ephyrKeySyms.map = (CARD32 *)calloc(sizeof(CARD32),
                                       (max_keycode - min_keycode + 1) *
                                       width);
   if (!ephyrKeySyms.map)
@@ -685,7 +685,7 @@ hostx_load_keymap(void)
 
   for (i=0; i<(max_keycode - min_keycode+1); i++)
     for (j=0; j<width; j++)
-      ephyrKeySyms.map[(i*width)+j] = keymap[(i*host_width) + j];
+      ephyrKeySyms.map[(i*width)+j] = (CARD32) keymap[(i*host_width) + j];
 
   EPHYR_DBG("keymap width, host:%d kdrive:%d", host_width, width);
   
diff --git a/hw/kdrive/ephyr/hostx.h b/hw/kdrive/ephyr/hostx.h
index 4e3c6af..4d5f37f 100644
--- a/hw/kdrive/ephyr/hostx.h
+++ b/hw/kdrive/ephyr/hostx.h
@@ -56,7 +56,7 @@ typedef struct {
   int             minKeyCode;
   int             maxKeyCode;
   int             mapWidth;
-  KeySym         *map;
+  CARD32         *map;
 } EphyrKeySyms;
 
 struct EphyrHostXEvent
diff-tree 5507cb885d861e974be240120ada2ace2a980a72 (from 84efe23ae834dd3a4d3f3e08832b69469c7382aa)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Fri Feb 16 23:01:27 2007 +0200

    kdrive: delete input debugging, yet again ...
    
    I have no idea how this keeps on coming back.

diff --git a/hw/kdrive/src/kinput.c b/hw/kdrive/src/kinput.c
index 83da67f..3bf6bad 100644
--- a/hw/kdrive/src/kinput.c
+++ b/hw/kdrive/src/kinput.c
@@ -1915,11 +1915,6 @@ KdEnqueueKeyboardEvent(KdKeyboardInfo   
     KeybdCtrl *ctrl = NULL;
     int type, nEvents, i;
 
-#ifdef DEBUG
-    ErrorF("enqueuing kb event (scancode %d, %s)\n", scan_code, is_up ? "up" : "down");
-    ErrorF("event is from %s\n", ki->name);
-#endif
-    
     if (!ki || !ki->dixdev || !ki->dixdev->kbdfeed || !ki->dixdev->key)
 	return;
 
@@ -1947,9 +1942,6 @@ KdEnqueueKeyboardEvent(KdKeyboardInfo   
 	}
 	
         nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, type, key_code);
-#ifdef DEBUG
-        ErrorF("KdEnqueueKeyboardEvent: got %d events from GKE\n", nEvents);
-#endif
         for (i = 0; i < nEvents; i++)
             KdQueueEvent(ki->dixdev, kdEvents + i);
     }
@@ -2009,12 +2001,6 @@ KdEnqueuePointerEvent(KdPointerInfo *pi,
     }
     z = rz;
 
-#ifdef DEBUG
-    ErrorF("sending motion notification for (%d, %d, %d)\n", x, y, z);
-    ErrorF("  comes from (%d, %d, %d)\n", rx, ry, rz);
-    ErrorF("  is %s\n", (flags & KD_MOUSE_DELTA) ? "relative" : "absolute");
-#endif
-
     if (flags & KD_MOUSE_DELTA)
         dixflags = POINTER_RELATIVE & POINTER_ACCELERATE;
     else
@@ -2028,9 +2014,6 @@ KdEnqueuePointerEvent(KdPointerInfo *pi,
          button <<= 1, n++) {
         if (((pi->buttonState & button) ^ (buttons & button)) &&
            !(buttons & button)) {
-#ifdef DEBUG
-            ErrorF("  posting button release %d\n", n);
-#endif
             _KdEnqueuePointerEvent(pi, ButtonRelease, x, y, z, n,
                                    dixflags, FALSE);
 	}
@@ -2039,9 +2022,6 @@ KdEnqueuePointerEvent(KdPointerInfo *pi,
          button <<= 1, n++) {
 	if (((pi->buttonState & button) ^ (buttons & button)) &&
 	    (buttons & button)) {
-#ifdef DEBUG
-            ErrorF("  posting button press %d\n", n);
-#endif
             _KdEnqueuePointerEvent(pi, ButtonPress, x, y, z, n,
                                    dixflags, FALSE);
         }
@@ -2057,11 +2037,6 @@ _KdEnqueuePointerEvent (KdPointerInfo *p
     int nEvents = 0, i = 0;
     int valuators[3] = { x, y, z };
 
-#ifdef DEBUG
-    ErrorF("mouse enqueuing event from device %s (%d, %d, %d; %d)\n",
-           pi->name, x, y, z, b);
-#endif
-
     /* TRUE from KdHandlePointerEvent, means 'we swallowed the event'. */
     if (!force && KdHandlePointerEvent(pi, type, x, y, z, b, absrel))
         return;
diff-tree 84efe23ae834dd3a4d3f3e08832b69469c7382aa (from 5e7f7436a755a33e48ab91831cc6af710a8344ef)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Fri Feb 16 04:37:38 2007 -0800

    updated darwin/quartz/xpr (libXplugin interface for Mac OS X) support

diff --git a/hw/darwin/quartz/xpr/Makefile.am b/hw/darwin/quartz/xpr/Makefile.am
new file mode 100644
index 0000000..7f2b008
--- /dev/null
+++ b/hw/darwin/quartz/xpr/Makefile.am
@@ -0,0 +1,29 @@
+noinst_LIBRARIES = libxpr.a
+AM_CFLAGS =  @XORG_CFLAGS@ @DIX_CFLAGS@
+INCLUDES = @XORG_INCS@ \
+	   -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. \
+	   -I$(top_srcdir)/miext/rootless/safeAlpha \
+	   -I$(top_srcdir)/miext/rootless \
+	   -I$(top_srcdir)/miext
+
+libxpr_a_SOURCES = \
+	appledri.c \
+        dri.c \
+        xprAppleWM.c \
+        xprCursor.c \
+        xprFrame.c \
+        xprScreen.c \
+        x-hash.c \
+        x-hook.c \
+        x-list.c
+
+xprbundledir = @APPLE_APPLICATIONS_DIR@/Resources/xpr.bundle/Contents/MacOS
+
+EXTRA_DIST = \
+	dri.h \
+	dristruct.h \
+	x-hash.h \
+	x-hook.h \
+	x-list.h \
+	Xplugin.h \
+	xpr.h
diff --git a/hw/darwin/quartz/xpr/appledri.c b/hw/darwin/quartz/xpr/appledri.c
index dd688ca..ef68c86 100644
--- a/hw/darwin/quartz/xpr/appledri.c
+++ b/hw/darwin/quartz/xpr/appledri.c
@@ -35,6 +35,9 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN
  *
  */
 
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #define NEED_REPLIES
 #define NEED_EVENTS
 #include <X11/X.h>
diff --git a/hw/darwin/quartz/xpr/appledri.h b/hw/darwin/quartz/xpr/appledri.h
new file mode 100644
index 0000000..9c63037
--- /dev/null
+++ b/hw/darwin/quartz/xpr/appledri.h
@@ -0,0 +1,107 @@
+/* $XFree86: xc/lib/GL/dri/xf86dri.h,v 1.7 2000/12/07 20:26:02 dawes Exp $ */
+/**************************************************************************
+
+Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
+Copyright 2000 VA Linux Systems, Inc.
+Copyright (c) 2002 Apple Computer, 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.
+
+**************************************************************************/
+
+/*
+ * Authors:
+ *   Kevin E. Martin <martin at valinux.com>
+ *   Jens Owen <jens at valinux.com>
+ *   Rickard E. (Rik) Faith <faith at valinux.com>
+ *
+ */
+
+#ifndef _APPLEDRI_H_
+#define _APPLEDRI_H_
+
+#include <X11/Xfuncproto.h>
+
+#define X_AppleDRIQueryVersion			0
+#define X_AppleDRIQueryDirectRenderingCapable	1
+#define X_AppleDRICreateSurface			2
+#define X_AppleDRIDestroySurface		3
+#define X_AppleDRIAuthConnection                4
+/* Requests up to and including 18 were used in a previous version */
+
+/* Events */
+#define AppleDRIObsoleteEvent1		0
+#define AppleDRIObsoleteEvent2		1
+#define AppleDRIObsoleteEvent3		2
+#define AppleDRISurfaceNotify		3
+#define AppleDRINumberEvents		4
+
+/* Errors */
+#define AppleDRIClientNotLocal		0
+#define AppleDRIOperationNotSupported	1
+#define AppleDRINumberErrors		(AppleDRIOperationNotSupported + 1)
+
+/* Kinds of SurfaceNotify events: */
+#define AppleDRISurfaceNotifyChanged	0
+#define AppleDRISurfaceNotifyDestroyed	1
+
+#ifndef _APPLEDRI_SERVER_
+
+typedef struct {
+    int	type;		    /* of event */
+    unsigned long serial;   /* # of last request processed by server */
+    Bool send_event;	    /* true if this came frome a SendEvent request */
+    Display *display;	    /* Display the event was read from */
+    Window window;	    /* window of event */
+    Time time;		    /* server timestamp when event happened */
+    int kind;		    /* subtype of event */
+    int arg;
+} XAppleDRINotifyEvent;
+
+_XFUNCPROTOBEGIN
+
+Bool XAppleDRIQueryExtension (Display *dpy, int *event_base, int *error_base);
+
+Bool XAppleDRIQueryVersion (Display *dpy, int *majorVersion,
+			    int *minorVersion, int *patchVersion);
+
+Bool XAppleDRIQueryDirectRenderingCapable (Display *dpy, int screen,
+					   Bool *isCapable);
+
+void *XAppleDRISetSurfaceNotifyHandler (void (*fun) (Display *dpy,
+						     unsigned uid, int kind));
+
+Bool XAppleDRIAuthConnection (Display *dpy, int screen, unsigned int magic);
+
+Bool XAppleDRICreateSurface (Display *dpy, int screen, Drawable drawable,
+			     unsigned int client_id, unsigned int key[2],
+			     unsigned int* uid);
+
+Bool XAppleDRIDestroySurface (Display *dpy, int screen, Drawable drawable);
+
+Bool XAppleDRISynchronizeSurfaces (Display *dpy);
+
+_XFUNCPROTOEND
+
+#endif /* _APPLEDRI_SERVER_ */
+#endif /* _APPLEDRI_H_ */
+
diff --git a/hw/darwin/quartz/xpr/appledristr.h b/hw/darwin/quartz/xpr/appledristr.h
new file mode 100644
index 0000000..36a2e89
--- /dev/null
+++ b/hw/darwin/quartz/xpr/appledristr.h
@@ -0,0 +1,176 @@
+/* $XFree86: xc/lib/GL/dri/xf86dristr.h,v 1.9 2001/03/21 16:01:08 dawes Exp $ */
+/**************************************************************************
+
+Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
+Copyright 2000 VA Linux Systems, Inc.
+Copyright (c) 2002 Apple Computer, 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.
+
+**************************************************************************/
+
+/*
+ * Authors:
+ *   Kevin E. Martin <martin at valinux.com>
+ *   Jens Owen <jens at valinux.com>
+ *   Rickard E. (Rik) Fiath <faith at valinux.com>
+ *
+ */
+
+#ifndef _APPLEDRISTR_H_
+#define _APPLEDRISTR_H_
+
+#include "appledri.h"
+
+#define APPLEDRINAME "Apple-DRI"
+
+#define APPLE_DRI_MAJOR_VERSION	1	/* current version numbers */
+#define APPLE_DRI_MINOR_VERSION	0
+#define APPLE_DRI_PATCH_VERSION	0
+
+typedef struct _AppleDRIQueryVersion {
+    CARD8	reqType;		/* always DRIReqCode */
+    CARD8	driReqType;		/* always X_DRIQueryVersion */
+    CARD16	length B16;
+} xAppleDRIQueryVersionReq;
+#define sz_xAppleDRIQueryVersionReq	4
+
+typedef struct {
+    BYTE	type;			/* X_Reply */
+    BOOL	pad1;
+    CARD16	sequenceNumber B16;
+    CARD32	length B32;
+    CARD16	majorVersion B16;	/* major version of DRI protocol */
+    CARD16	minorVersion B16;	/* minor version of DRI protocol */
+    CARD32	patchVersion B32;       /* patch version of DRI protocol */
+    CARD32	pad3 B32;
+    CARD32	pad4 B32;
+    CARD32	pad5 B32;
+    CARD32	pad6 B32;
+} xAppleDRIQueryVersionReply;
+#define sz_xAppleDRIQueryVersionReply	32
+
+typedef struct _AppleDRIQueryDirectRenderingCapable {
+    CARD8	reqType;		/* always DRIReqCode */
+    CARD8	driReqType;		/* X_DRIQueryDirectRenderingCapable */
+    CARD16	length B16;
+    CARD32	screen B32;
+} xAppleDRIQueryDirectRenderingCapableReq;
+#define sz_xAppleDRIQueryDirectRenderingCapableReq	8
+
+typedef struct {
+    BYTE	type;			/* X_Reply */
+    BOOL	pad1;
+    CARD16	sequenceNumber B16;
+    CARD32	length B32;
+    BOOL	isCapable;
+    BOOL	pad2;
+    BOOL	pad3;
+    BOOL	pad4;
+    CARD32	pad5 B32;
+    CARD32	pad6 B32;
+    CARD32	pad7 B32;
+    CARD32	pad8 B32;
+    CARD32	pad9 B32;
+} xAppleDRIQueryDirectRenderingCapableReply;
+#define sz_xAppleDRIQueryDirectRenderingCapableReply	32
+
+typedef struct _AppleDRIAuthConnection {
+    CARD8	reqType;		/* always DRIReqCode */
+    CARD8	driReqType;		/* always X_DRICloseConnection */
+    CARD16	length B16;
+    CARD32	screen B32;
+    CARD32      magic B32;
+} xAppleDRIAuthConnectionReq;
+#define sz_xAppleDRIAuthConnectionReq	12
+
+typedef struct {
+    BYTE        type;
+    BOOL        pad1;
+    CARD16      sequenceNumber B16;
+    CARD32      length B32;
+    CARD32      authenticated B32;
+    CARD32      pad2 B32;
+    CARD32      pad3 B32;
+    CARD32      pad4 B32;
+    CARD32      pad5 B32;
+    CARD32      pad6 B32;
+} xAppleDRIAuthConnectionReply;
+#define zx_xAppleDRIAuthConnectionReply  32
+
+typedef struct _AppleDRICreateSurface {
+    CARD8	reqType;		/* always DRIReqCode */
+    CARD8	driReqType;		/* always X_DRICreateSurface */
+    CARD16	length B16;
+    CARD32	screen B32;
+    CARD32	drawable B32;
+    CARD32	client_id B32;
+} xAppleDRICreateSurfaceReq;
+#define sz_xAppleDRICreateSurfaceReq	16
+
+typedef struct {
+    BYTE	type;			/* X_Reply */
+    BOOL	pad1;
+    CARD16	sequenceNumber B16;
+    CARD32	length B32;
+    CARD32	key_0 B32;
+    CARD32	key_1 B32;
+    CARD32	uid B32;
+    CARD32	pad4 B32;
+    CARD32	pad5 B32;
+    CARD32	pad6 B32;
+} xAppleDRICreateSurfaceReply;
+#define sz_xAppleDRICreateSurfaceReply	32
+
+typedef struct _AppleDRIDestroySurface {
+    CARD8	reqType;		/* always DRIReqCode */
+    CARD8	driReqType;		/* always X_DRIDestroySurface */
+    CARD16	length B16;
+    CARD32	screen B32;
+    CARD32	drawable B32;
+} xAppleDRIDestroySurfaceReq;
+#define sz_xAppleDRIDestroySurfaceReq	12
+
+typedef struct _AppleDRINotify {
+	BYTE	type;		/* always eventBase + event type */
+	BYTE	kind;
+	CARD16	sequenceNumber B16;
+	Time	time B32;	/* time of change */
+	CARD16	pad1 B16;
+	CARD32	arg B32;
+	CARD32	pad3 B32;
+} xAppleDRINotifyEvent;
+#define sz_xAppleDRINotifyEvent	20
+
+#ifdef _APPLEDRI_SERVER_
+
+void AppleDRISendEvent (
+#if NeedFunctionPrototypes
+    int			/* type */,
+    unsigned int	/* mask */,
+    int			/* which */,
+    int			/* arg */
+#endif
+);
+
+#endif /* _APPLEDRI_SERVER_ */
+#endif /* _APPLEDRISTR_H_ */
diff --git a/hw/darwin/quartz/xpr/dri.c b/hw/darwin/quartz/xpr/dri.c
index 9aeaaa5..08ee382 100644
--- a/hw/darwin/quartz/xpr/dri.c
+++ b/hw/darwin/quartz/xpr/dri.c
@@ -33,6 +33,9 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN
  *   Rickard E. (Rik) Faith <faith at valinux.com>
  *
  */
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 
 #include <sys/time.h>
 #include <unistd.h>
diff --git a/hw/darwin/quartz/xpr/x-hash.c b/hw/darwin/quartz/xpr/x-hash.c
index a7024b2..40e530f 100644
--- a/hw/darwin/quartz/xpr/x-hash.c
+++ b/hw/darwin/quartz/xpr/x-hash.c
@@ -27,7 +27,9 @@
    copyright holders shall not be used in advertising or otherwise to
    promote the sale, use or other dealings in this Software without
    prior written authorization. */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "x-hash.h"
 #include "x-list.h"
 #include <stdlib.h>
diff --git a/hw/darwin/quartz/xpr/x-hook.c b/hw/darwin/quartz/xpr/x-hook.c
index dcd34fd..7a04967 100644
--- a/hw/darwin/quartz/xpr/x-hook.c
+++ b/hw/darwin/quartz/xpr/x-hook.c
@@ -28,7 +28,9 @@
    promote the sale, use or other dealings in this Software without
    prior written authorization. */
 /* $XFree86: $ */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "x-hook.h"
 #include <stdlib.h>
 #include <assert.h>
diff --git a/hw/darwin/quartz/xpr/x-list.c b/hw/darwin/quartz/xpr/x-list.c
index b9f2392..a973e03 100644
--- a/hw/darwin/quartz/xpr/x-list.c
+++ b/hw/darwin/quartz/xpr/x-list.c
@@ -27,7 +27,9 @@
    copyright holders shall not be used in advertising or otherwise to
    promote the sale, use or other dealings in this Software without
    prior written authorization. */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "x-list.h"
 #include <stdlib.h>
 #include <assert.h>
diff --git a/hw/darwin/quartz/xpr/xprAppleWM.c b/hw/darwin/quartz/xpr/xprAppleWM.c
index 21746f6..0c827e2 100644
--- a/hw/darwin/quartz/xpr/xprAppleWM.c
+++ b/hw/darwin/quartz/xpr/xprAppleWM.c
@@ -27,7 +27,9 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "xpr.h"
 #include "applewmExt.h"
 #include "rootless.h"
diff --git a/hw/darwin/quartz/xpr/xprCursor.c b/hw/darwin/quartz/xpr/xprCursor.c
index cb949da..71a4277 100644
--- a/hw/darwin/quartz/xpr/xprCursor.c
+++ b/hw/darwin/quartz/xpr/xprCursor.c
@@ -30,7 +30,9 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "xpr.h"
 #include "darwin.h"
diff --git a/hw/darwin/quartz/xpr/xprFrame.c b/hw/darwin/quartz/xpr/xprFrame.c
index ed02d4b..49f8714 100644
--- a/hw/darwin/quartz/xpr/xprFrame.c
+++ b/hw/darwin/quartz/xpr/xprFrame.c
@@ -27,7 +27,9 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "xpr.h"
 #include "rootlessCommon.h"
 #include "Xplugin.h"
diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index 1755ca6..a5bccbf 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -27,7 +27,9 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "quartz.h"
 #include "xpr.h"
diff-tree 5e7f7436a755a33e48ab91831cc6af710a8344ef (from f350909d1696fcfda87e8f12c729254d762313c9)
Author: Ben Byer <bbyer at bbyer.(none)>
Date:   Fri Feb 16 04:12:26 2007 -0800

    merged in miext/rootless changes for XDarwin support

diff --git a/miext/Makefile.am b/miext/Makefile.am
index 4fa584b..f138963 100644
--- a/miext/Makefile.am
+++ b/miext/Makefile.am
@@ -2,4 +2,7 @@ SUBDIRS = damage shadow
 if COMPOSITE
 SUBDIRS += cw
 endif
+if XQUARTZ
+SUBDIRS += rootless
+endif
 DIST_SUBDIRS = damage shadow cw rootless
diff --git a/miext/rootless/Makefile.am b/miext/rootless/Makefile.am
index ecf762a..8dae6d2 100644
--- a/miext/rootless/Makefile.am
+++ b/miext/rootless/Makefile.am
@@ -1,14 +1,13 @@
-EXTRA_DIST = \
-	accel/rlAccel.c \
-	accel/rlAccel.h \
-	accel/rlBlt.c \
-	accel/rlCopy.c \
-	accel/rlFill.c \
-	accel/rlFillRect.c \
-	accel/rlFillSpans.c \
-	accel/rlGlyph.c \
-	accel/rlSolid.c \
-	README.txt \
+AM_CFLAGS =  \
+	    $(DIX_CFLAGS) \
+	    $(XORG_CFLAGS)
+
+INCLUDES = -I$(top_srcdir)/hw/xfree86/os-support
+
+SUBDIRS = safeAlpha accel
+
+noinst_LTLIBRARIES = librootless.la
+librootless_la_SOURCES = \
 	rootlessCommon.c \
 	rootlessCommon.h \
 	rootlessConfig.h \
@@ -17,7 +16,7 @@ EXTRA_DIST = \
 	rootlessScreen.c \
 	rootlessValTree.c \
 	rootlessWindow.c \
-	rootlessWindow.h \
-	safeAlpha/safeAlpha.h \
-	safeAlpha/safeAlphaPicture.c \
-	safeAlpha/safeAlphaWindow.c
+	rootlessWindow.h 
+
+EXTRA_DIST = \
+	README.txt
diff --git a/miext/rootless/accel/Makefile.am b/miext/rootless/accel/Makefile.am
new file mode 100644
index 0000000..c49d5fb
--- /dev/null
+++ b/miext/rootless/accel/Makefile.am
@@ -0,0 +1,18 @@
+AM_CFLAGS =  \
+	    $(DIX_CFLAGS) \
+	    $(XORG_CFLAGS)
+
+INCLUDES = -I$(srcdir)/.. -I$(top_srcdir)/hw/xfree86/os-support
+
+
+noinst_LTLIBRARIES = librlAccel.la
+librlAccel_la_SOURCES = rlAccel.c \
+	             rlBlt.c \
+	             rlCopy.c \
+	             rlFill.c \
+	             rlFillRect.c \
+	             rlFillSpans.c \
+	             rlGlyph.c \
+	             rlSolid.c
+
+EXTRA_DIST = rlAccel.h
diff --git a/miext/rootless/accel/rlBlt.c b/miext/rootless/accel/rlBlt.c
index d1e7658..2cf72eb 100644
--- a/miext/rootless/accel/rlBlt.c
+++ b/miext/rootless/accel/rlBlt.c
@@ -31,6 +31,7 @@
 #include <dix-config.h>
 #endif
 
+#include <stddef.h> /* For NULL */
 #include "fb.h"
 #include "rootlessCommon.h"
 #include "rlAccel.h"
diff --git a/miext/rootless/rootlessCommon.c b/miext/rootless/rootlessCommon.c
index 8fd922d..9cbb7fa 100644
--- a/miext/rootless/rootlessCommon.c
+++ b/miext/rootless/rootlessCommon.c
@@ -33,6 +33,9 @@
 #include <dix-config.h>
 #endif
 
+#include <stddef.h> /* For NULL */
+#include <limits.h> /* For CHAR_BIT */
+
 #include "rootlessCommon.h"
 
 unsigned int rootless_CopyBytes_threshold = 0;
diff --git a/miext/rootless/rootlessGC.c b/miext/rootless/rootlessGC.c
index 5341267..b26f52c 100644
--- a/miext/rootless/rootlessGC.c
+++ b/miext/rootless/rootlessGC.c
@@ -33,6 +33,7 @@
 #include <dix-config.h>
 #endif
 
+#include <stddef.h> /* For NULL */
 #include "mi.h"
 #include "scrnintstr.h"
 #include "gcstruct.h"
diff --git a/miext/rootless/rootlessValTree.c b/miext/rootless/rootlessValTree.c
index 97348f5..4f16530 100644
--- a/miext/rootless/rootlessValTree.c
+++ b/miext/rootless/rootlessValTree.c
@@ -93,6 +93,7 @@ Equipment Corporation.
 #include <dix-config.h>
 #endif
 
+#include <stddef.h> /* For NULL */
 #include    <X11/X.h>
 #include    "scrnintstr.h"
 #include    "validate.h"
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index e89ebf8..30b7daa 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -33,6 +33,10 @@
 #include <dix-config.h>
 #endif
 
+#include <stddef.h> /* For NULL */
+#include <limits.h> /* For CHAR_BIT */
+#include <assert.h>
+
 #include "rootlessCommon.h"
 #include "rootlessWindow.h"
 
@@ -325,8 +329,8 @@ RootlessEnsureFrame(WindowPtr pWin)
     RootlessWindowRec *winRec;
 #ifdef SHAPE
     RegionRec shape;
-    RegionPtr pShape = NULL;
 #endif
+    RegionPtr pShape = NULL;
 
     if (WINREC(pWin) != NULL)
         return WINREC(pWin);
diff --git a/miext/rootless/safeAlpha/Makefile.am b/miext/rootless/safeAlpha/Makefile.am
new file mode 100644
index 0000000..7592c18
--- /dev/null
+++ b/miext/rootless/safeAlpha/Makefile.am
@@ -0,0 +1,12 @@
+AM_CFLAGS = \
+	    $(DIX_CFLAGS) \
+            $(XORG_CFLAGS)
+
+INCLUDES = -I$(srcdir)/.. -I$(top_srcdir)/hw/xfree86/os-support
+
+
+noinst_LTLIBRARIES = libsafeAlpha.la
+libsafeAlpha_la_SOURCES = safeAlphaPicture.c \
+		       safeAlphaWindow.c
+
+EXTRA_DIST = safeAlpha.h
diff --git a/miext/rootless/safeAlpha/safeAlphaPicture.c b/miext/rootless/safeAlpha/safeAlphaPicture.c
index 8550cc0..6ccc05a 100644
--- a/miext/rootless/safeAlpha/safeAlphaPicture.c
+++ b/miext/rootless/safeAlpha/safeAlphaPicture.c
@@ -33,15 +33,19 @@
  * Copyright © 2000 Keith Packard, member of The XFree86 Project, Inc.
  */
 
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
 #ifdef RENDER
 
+#include <stddef.h> /* For NULL */
 #include "fb.h"
 #include "picturestr.h"
 #include "mipict.h"
 #include "fbpict.h"
 #include "safeAlpha.h"
 #include "rootlessCommon.h"
-
 # define mod(a,b)	((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b))
 
 
diff --git a/miext/rootless/safeAlpha/safeAlphaWindow.c b/miext/rootless/safeAlpha/safeAlphaWindow.c
index 8884c10..5226782 100644
--- a/miext/rootless/safeAlpha/safeAlphaWindow.c
+++ b/miext/rootless/safeAlpha/safeAlphaWindow.c
@@ -32,6 +32,10 @@
  * Copyright © 1998 Keith Packard
  */
 
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
 #include "fb.h"
 #include "safeAlpha.h"
 #include "rootlessCommon.h"
diff --git a/os/utils.c b/os/utils.c
index 7c725e3..612c264 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -1871,7 +1871,7 @@ Fopen(char *file, char *type)
     pidlist = cur;
 
 #ifdef DEBUG
-    ErrorF("Popen: `%s', fp = %p\n", command, iop);
+    ErrorF("Fopen(%s), fp = %p\n", file, iop);
 #endif
 
     return iop;
diff-tree f350909d1696fcfda87e8f12c729254d762313c9 (from 258beebc77510f84fbea66d6ebf29c5097bd11db)
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Thu Feb 15 21:50:48 2007 -0800

    Kludge around duplicate code added in hw/xfree86/modes.
    
    Code added in hw/xfree86/modes came from the server-1.3-branch.
    Portions of this code had previously been integrated into xf86Mode.c
    and edid_modes.c.
    
    To preserve hw/xfree86/modes as much as possible, the duplicate code from
    the other files has been disabled; a more careful review would figure out
    where that code actually belonged.

diff --git a/hw/xfree86/common/xf86Mode.c b/hw/xfree86/common/xf86Mode.c
index d5085b5..fc905df 100644
--- a/hw/xfree86/common/xf86Mode.c
+++ b/hw/xfree86/common/xf86Mode.c
@@ -368,6 +368,7 @@ xf86HandleBuiltinMode(ScrnInfoPtr scrp,
     return MODE_OK;
 }
 
+#if 0
 /** Calculates the horizontal sync rate of a mode */
 _X_EXPORT double
 xf86ModeHSync(DisplayModePtr mode)
@@ -411,6 +412,7 @@ xf86SetModeDefaultName(DisplayModePtr mo
 
     mode->name = XNFprintf("%dx%d", mode->HDisplay, mode->VDisplay);
 }
+#endif
 
 /*
  * xf86LookupMode
@@ -680,6 +682,7 @@ xf86LookupMode(ScrnInfoPtr scrp, Display
 }
 
 
+#if 0
 /*
  * xf86SetModeCrtc
  *
@@ -733,7 +736,9 @@ xf86SetModeCrtc(DisplayModePtr p, int ad
     p->CrtcHAdjusted = FALSE;
     p->CrtcVAdjusted = FALSE;
 }
+#endif
 
+#if 0
 /**
  * Allocates and returns a copy of pMode, including pointers within pMode.
  */
@@ -814,6 +819,7 @@ xf86ModesEqual(DisplayModePtr pMode1, Di
 	return FALSE;
      }
 }
+#endif
 
 /*
  * xf86CheckModeForMonitor
@@ -2040,6 +2046,7 @@ add(char **p, char *new)
     strcat(*p, new);
 }
 
+#if 0
 _X_EXPORT void
 xf86PrintModeline(int scrnIndex,DisplayModePtr mode)
 {
@@ -2075,6 +2082,7 @@ xf86PrintModeline(int scrnIndex,DisplayM
 		   mode->VTotal, flags);
     xfree(flags);
 }
+#endif
 
 _X_EXPORT void
 xf86PrintModes(ScrnInfoPtr scrp)
@@ -2145,6 +2153,7 @@ xf86PrintModes(ScrnInfoPtr scrp)
     } while (p != NULL && p != scrp->modes);
 }
 
+#if 0
 /**
  * Adds the new mode into the mode list, and returns the new list
  *
@@ -2168,3 +2177,4 @@ xf86ModesAdd(DisplayModePtr modes, Displ
 
     return modes;
 }
+#endif
diff --git a/hw/xfree86/ddc/Makefile.am b/hw/xfree86/ddc/Makefile.am
index f3ac803..04d3e44 100644
--- a/hw/xfree86/ddc/Makefile.am
+++ b/hw/xfree86/ddc/Makefile.am
@@ -3,8 +3,7 @@ sdk_HEADERS = edid.h vdif.h xf86DDC.h
 noinst_LIBRARIES = libddc.a
 
 libddc_a_SOURCES = xf86DDC.c edid.c interpret_edid.c print_edid.c \
-                   interpret_vdif.c print_vdif.c ddcProperty.c \
-		   edid_modes.c
+                   interpret_vdif.c print_vdif.c ddcProperty.c
 
 INCLUDES = $(XORG_INCS) -I$(srcdir)/../i2c
 
diff --git a/hw/xfree86/modes/Makefile.am b/hw/xfree86/modes/Makefile.am
index 60d2553..e0b6136 100644
--- a/hw/xfree86/modes/Makefile.am
+++ b/hw/xfree86/modes/Makefile.am
@@ -24,4 +24,4 @@ sdk_HEADERS = \
 	xf86RandR12.h \
 	xf86Rename.h
 
-AM_CFLAGS = $(XORG_CFLAGS)
+AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
diff --git a/hw/xfree86/modes/xf86EdidModes.c b/hw/xfree86/modes/xf86EdidModes.c
index 77c0c87..c4cf687 100644
--- a/hw/xfree86/modes/xf86EdidModes.c
+++ b/hw/xfree86/modes/xf86EdidModes.c
@@ -259,6 +259,50 @@ DDCModeFromDetailedTiming(int scrnIndex,
     return Mode;
 }
 
+/*
+ *
+ */
+static void
+DDCGuessRangesFromModes(int scrnIndex, MonPtr Monitor, DisplayModePtr Modes)
+{
+    DisplayModePtr Mode = Modes;
+
+    if (!Monitor || !Modes)
+        return;
+
+    /* set up the ranges for scanning through the modes */
+    Monitor->nHsync = 1;
+    Monitor->hsync[0].lo = 1024.0;
+    Monitor->hsync[0].hi = 0.0;
+
+    Monitor->nVrefresh = 1;
+    Monitor->vrefresh[0].lo = 1024.0;
+    Monitor->vrefresh[0].hi = 0.0;
+
+    while (Mode) {
+        if (!Mode->HSync)
+            Mode->HSync = ((float) Mode->Clock ) / ((float) Mode->HTotal);
+
+        if (!Mode->VRefresh)
+            Mode->VRefresh = (1000.0 * ((float) Mode->Clock)) / 
+                ((float) (Mode->HTotal * Mode->VTotal));
+
+        if (Mode->HSync < Monitor->hsync[0].lo)
+            Monitor->hsync[0].lo = Mode->HSync;
+
+        if (Mode->HSync > Monitor->hsync[0].hi)
+            Monitor->hsync[0].hi = Mode->HSync;
+
+        if (Mode->VRefresh < Monitor->vrefresh[0].lo)
+            Monitor->vrefresh[0].lo = Mode->VRefresh;
+
+        if (Mode->VRefresh > Monitor->vrefresh[0].hi)
+            Monitor->vrefresh[0].hi = Mode->VRefresh;
+
+        Mode = Mode->next;
+    }
+}
+
 DisplayModePtr
 xf86DDCGetModes(int scrnIndex, xf86MonPtr DDC)
 {
@@ -341,3 +385,106 @@ xf86DDCGetModes(int scrnIndex, xf86MonPt
     }
     return Modes;
 }
+
+/*
+ * Fill out MonPtr with xf86MonPtr information.
+ */
+void
+xf86DDCMonitorSet(int scrnIndex, MonPtr Monitor, xf86MonPtr DDC)
+{
+    DisplayModePtr Modes = NULL, Mode;
+    int i, clock;
+    Bool have_hsync = FALSE, have_vrefresh = FALSE;
+
+    if (!Monitor || !DDC)
+        return;
+
+    Monitor->DDC = DDC;
+
+    Monitor->widthmm = 10 * DDC->features.hsize;
+    Monitor->heightmm = 10 * DDC->features.vsize;
+
+    /* If this is a digital display, then we can use reduced blanking */
+    if (DDC->features.input_type)
+        Monitor->reducedblanking = TRUE;
+    /* Allow the user to also enable this through config */
+
+    Modes = xf86DDCGetModes(scrnIndex, DDC);
+
+    /* Skip EDID ranges if they were specified in the config file */
+    have_hsync = (Monitor->nHsync != 0);
+    have_vrefresh = (Monitor->nVrefresh != 0);
+
+    /* Go through the detailed monitor sections */
+    for (i = 0; i < DET_TIMINGS; i++) {
+        switch (DDC->det_mon[i].type) {
+        case DS_RANGES:
+	    if (!have_hsync) {
+		if (!Monitor->nHsync)
+		    xf86DrvMsg(scrnIndex, X_INFO,
+			    "Using EDID range info for horizontal sync\n");
+		Monitor->hsync[Monitor->nHsync].lo =
+		    DDC->det_mon[i].section.ranges.min_h;
+		Monitor->hsync[Monitor->nHsync].hi =
+		    DDC->det_mon[i].section.ranges.max_h;
+		Monitor->nHsync++;
+	    } else {
+		xf86DrvMsg(scrnIndex, X_INFO,
+			"Using hsync ranges from config file\n");
+	    }
+
+	    if (!have_vrefresh) {
+		if (!Monitor->nVrefresh)
+		    xf86DrvMsg(scrnIndex, X_INFO,
+			    "Using EDID range info for vertical refresh\n");
+		Monitor->vrefresh[Monitor->nVrefresh].lo =
+		    DDC->det_mon[i].section.ranges.min_v;
+		Monitor->vrefresh[Monitor->nVrefresh].hi =
+		    DDC->det_mon[i].section.ranges.max_v;
+		Monitor->nVrefresh++;
+	    } else {
+		xf86DrvMsg(scrnIndex, X_INFO,
+			"Using vrefresh ranges from config file\n");
+	    }
+
+	    clock = DDC->det_mon[i].section.ranges.max_clock * 1000;
+	    if (clock > Monitor->maxPixClock)
+		Monitor->maxPixClock = clock;
+
+            break;
+        default:
+            break;
+        }
+    }
+
+    if (Modes) {
+        /* Print Modes */
+        xf86DrvMsg(scrnIndex, X_INFO, "Printing DDC gathered Modelines:\n");
+
+        Mode = Modes;
+        while (Mode) {
+            xf86PrintModeline(scrnIndex, Mode);
+            Mode = Mode->next;
+        }
+
+        /* Do we still need ranges to be filled in? */
+        if (!Monitor->nHsync || !Monitor->nVrefresh)
+            DDCGuessRangesFromModes(scrnIndex, Monitor, Modes);
+
+        /* look for last Mode */
+        Mode = Modes;
+
+        while (Mode->next)
+            Mode = Mode->next;
+
+        /* add to MonPtr */
+        if (Monitor->Modes) {
+            Monitor->Last->next = Modes;
+            Modes->prev = Monitor->Last;
+            Monitor->Last = Mode;
+        } else {
+            Monitor->Modes = Modes;
+            Monitor->Last = Mode;
+        }
+    }
+}
diff-tree 258beebc77510f84fbea66d6ebf29c5097bd11db (from ef6b1235fd7d6dc422e8a150c089496a8e648067)
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Thu Feb 15 20:13:15 2007 -0800

    Report correct RandR 1.0 sizeID. Report correct subpixel order.
    
    RandR 1.0 sizeID must be computed the same way every time, so when reporting
    it in the ScreenChangeNotify event, just construct the usual 1.0 data block
    and use that.
    
    subpixel geometry information can be computed by looking at the connected
    outputs and finding any with subpixel geometry and using one of those for
    the global screen subpixel geometry. This might be improved by reporting
    None if more than one screen has information and they conflict.

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index 5e0a0c6..bda8055 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -144,6 +144,71 @@ xf86CrtcInUse (xf86CrtcPtr crtc)
     return FALSE;
 }
 
+void
+xf86CrtcSetScreenSubpixelOrder (ScreenPtr pScreen)
+{
+#ifdef RENDER
+    int			subpixel_order = SubPixelUnknown;
+    Bool		has_none = FALSE;
+    ScrnInfoPtr		scrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			c, o;
+
+    for (c = 0; c < xf86_config->num_crtc; c++)
+    {
+	xf86CrtcPtr crtc = xf86_config->crtc[c];
+	
+	for (o = 0; o < xf86_config->num_output; o++)
+	{
+	    xf86OutputPtr   output = xf86_config->output[o];
+
+	    if (output->crtc == crtc)
+	    {
+		switch (output->subpixel_order) {
+		case SubPixelNone:
+		    has_none = TRUE;
+		    break;
+		case SubPixelUnknown:
+		    break;
+		default:
+		    subpixel_order = output->subpixel_order;
+		    break;
+		}
+	    }
+	    if (subpixel_order != SubPixelUnknown)
+		break;
+	}
+	if (subpixel_order != SubPixelUnknown)
+	{
+	    static const int circle[4] = {
+		SubPixelHorizontalRGB,
+		SubPixelVerticalRGB,
+		SubPixelHorizontalBGR,
+		SubPixelVerticalBGR,
+	    };
+	    int	rotate;
+	    int c;
+	    for (rotate = 0; rotate < 4; rotate++)
+		if (crtc->rotation & (1 << rotate))
+		    break;
+	    for (c = 0; c < 4; c++)
+		if (circle[c] == subpixel_order)
+		    break;
+	    c = (c + rotate) & 0x3;
+	    if ((crtc->rotation & RR_Reflect_X) && !(c & 1))
+		c ^= 2;
+	    if ((crtc->rotation & RR_Reflect_Y) && (c & 1))
+		c ^= 2;
+	    subpixel_order = circle[c];
+	    break;
+	}
+    }
+    if (subpixel_order == SubPixelUnknown && has_none)
+	subpixel_order = SubPixelNone;
+    PictureSetSubpixelOrder (pScreen, subpixel_order);
+#endif
+}
+
 /**
  * Sets the given video mode on the given crtc
  */
@@ -245,6 +310,8 @@ xf86CrtcSetMode (xf86CrtcPtr crtc, Displ
 
     /* XXX free adjustedmode */
     ret = TRUE;
+    xf86CrtcSetScreenSubpixelOrder (scrn->pScreen);
+
 done:
     if (!ret) {
 	crtc->x = saved_x;
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
index 49f4965..07f7d49 100644
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -552,4 +552,12 @@ xf86DiDGAInit (ScreenPtr pScreen, unsign
 Bool
 xf86DiDGAReInit (ScreenPtr pScreen);
 
+/*
+ * Set the subpixel order reported for the screen using
+ * the information from the outputs
+ */
+
+void
+xf86CrtcSetScreenSubpixelOrder (ScreenPtr pScreen);
+
 #endif /* _XF86CRTC_H_ */
diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index 2a5d7ba..1dacb6f 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -433,6 +433,7 @@ xf86RandR12CreateScreenResources (Screen
 	randrp->virtualX = pScrn->virtualX;
 	randrp->virtualY = pScrn->virtualY;
     }
+    xf86CrtcSetScreenSubpixelOrder (pScreen);
 #if RANDR_12_INTERFACE
     if (xf86RandR12CreateScreenResources12 (pScreen))
 	return TRUE;
diff --git a/hw/xfree86/modes/xf86Rename.h b/hw/xfree86/modes/xf86Rename.h
index a00253d..ce4d217 100644
--- a/hw/xfree86/modes/xf86Rename.h
+++ b/hw/xfree86/modes/xf86Rename.h
@@ -73,5 +73,6 @@
 #define xf86RandR12SetConfig XF86NAME(xf86RandR12SetConfig)
 #define xf86RandR12SetRotations XF86NAME(xf86RandR12SetRotations)
 #define xf86SaveScreen XF86NAME(xf86SaveScreen)
+#define xf86CrtcSetScreenSubpixelOrder XF86NAME(xf86CrtcSetScreenSubpixelOrder)
 
 #endif /* _XF86RENAME_H_ */
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index e10aa03..1680003 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -26,6 +26,9 @@ extern char	*ConnectionInfo;
 
 static int padlength[4] = {0, 3, 2, 1};
 
+static CARD16
+RR10CurrentSizeID (ScreenPtr pScreen);
+
 /*
  * Edit connection information block so that new clients
  * see the current screen size on connect
@@ -96,10 +99,7 @@ RRDeliverScreenEvent (ClientPtr client, 
     rrScrPriv (pScreen);
     xRRScreenChangeNotifyEvent	se;
     RRCrtcPtr	crtc = pScrPriv->numCrtcs ? pScrPriv->crtcs[0] : NULL;
-    RROutputPtr	output = pScrPriv->numOutputs ? pScrPriv->outputs[0] : NULL;
-    RRModePtr	mode = crtc ? crtc->mode : NULL;
     WindowPtr	pRoot = WindowTable[pScreen->myNum];
-    int		i;
     
     se.type = RRScreenChangeNotify + RREventBase;
     se.rotation = (CARD8) (crtc ? crtc->rotation : RR_Rotate_0);
@@ -115,32 +115,12 @@ RRDeliverScreenEvent (ClientPtr client, 
 #endif
 
     se.sequenceNumber = client->sequence;
-    if (mode) 
-    {
-	se.sizeID = -1;
-	for (i = 0; i < output->numModes; i++)
-	    if (mode == output->modes[i])
-	    {
-		se.sizeID = i;
-		break;
-	    }
-	se.widthInPixels = mode->mode.width;
-	se.heightInPixels = mode->mode.height;
-	se.widthInMillimeters = pScreen->mmWidth;
-	se.heightInMillimeters = pScreen->mmHeight;
-    }
-    else
-    {
-	/*
-	 * This "shouldn't happen", but a broken DDX can
-	 * forget to set the current configuration on GetInfo
-	 */
-	se.sizeID = 0xffff;
-	se.widthInPixels = 0;
-	se.heightInPixels = 0;
-	se.widthInMillimeters = 0;
-	se.heightInMillimeters = 0;
-    }    
+    se.sizeID = RR10CurrentSizeID (pScreen);
+    
+    se.widthInPixels = pScreen->width;
+    se.heightInPixels = pScreen->height;
+    se.widthInMillimeters = pScreen->mmWidth;
+    se.heightInMillimeters = pScreen->mmHeight;
     WriteEventsToClient (client, 1, (xEvent *) &se);
 }
 
@@ -949,3 +929,27 @@ sendReply:
     return (client->noClientException);
 }
 
+static CARD16
+RR10CurrentSizeID (ScreenPtr pScreen)
+{
+    CARD16	sizeID = 0xffff;
+    RROutputPtr output = RRFirstOutput (pScreen);
+    
+    if (output)
+    {
+	RR10DataPtr data = RR10GetData (pScreen, output);
+	if (data)
+	{
+	    int i;
+	    for (i = 0; i < data->nsize; i++)
+		if (data->sizes[i].width == pScreen->width &&
+		    data->sizes[i].height == pScreen->height)
+		{
+		    sizeID = (CARD16) i;
+		    break;
+		}
+	    xfree (data);
+	}
+    }
+    return sizeID;
+}
diff-tree ef6b1235fd7d6dc422e8a150c089496a8e648067 (from 3dbe8f6b6ea32a9a137ad6e9235f74009b095bd8)
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Thu Feb 15 11:27:35 2007 -0800

    Allow new modes code to build inside drivers as well as server.
    
    Use config.h for driver builds where xorg-config.h isn't available.

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index ab7070b..5e0a0c6 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -22,6 +22,10 @@
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
+#else
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
 #endif
 
 #include <stddef.h>
diff --git a/hw/xfree86/modes/xf86DiDGA.c b/hw/xfree86/modes/xf86DiDGA.c
index f4ac4de..551f052 100644
--- a/hw/xfree86/modes/xf86DiDGA.c
+++ b/hw/xfree86/modes/xf86DiDGA.c
@@ -22,6 +22,10 @@
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
+#else
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
 #endif
 
 #include "xf86.h"
diff --git a/hw/xfree86/modes/xf86EdidModes.c b/hw/xfree86/modes/xf86EdidModes.c
index 0476a68..77c0c87 100644
--- a/hw/xfree86/modes/xf86EdidModes.c
+++ b/hw/xfree86/modes/xf86EdidModes.c
@@ -27,6 +27,10 @@
  */
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
+#else
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
 #endif
 
 #include "xf86.h"
diff --git a/hw/xfree86/modes/xf86Modes.c b/hw/xfree86/modes/xf86Modes.c
index d126e5e..0706783 100644
--- a/hw/xfree86/modes/xf86Modes.c
+++ b/hw/xfree86/modes/xf86Modes.c
@@ -30,6 +30,10 @@
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
+#else
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
 #endif
 
 #include <stddef.h>
diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index bafe71f..2a5d7ba 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -25,6 +25,10 @@
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
+#else
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
 #endif
 
 #include "xf86.h"
diff --git a/hw/xfree86/modes/xf86Rotate.c b/hw/xfree86/modes/xf86Rotate.c
index 1e79063..1d55a6e 100644
--- a/hw/xfree86/modes/xf86Rotate.c
+++ b/hw/xfree86/modes/xf86Rotate.c
@@ -22,6 +22,10 @@
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
+#else
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
 #endif
 
 #include <stddef.h>
diff --git a/hw/xfree86/modes/xf86cvt.c b/hw/xfree86/modes/xf86cvt.c
index 4256577..dd6febf 100644
--- a/hw/xfree86/modes/xf86cvt.c
+++ b/hw/xfree86/modes/xf86cvt.c
@@ -33,6 +33,10 @@
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
+#else
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
 #endif
 
 #include "xf86.h"
diff-tree 3dbe8f6b6ea32a9a137ad6e9235f74009b095bd8 (from d4eb4d065032112a38444e36f791cb468a5ca8f4)
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Thu Feb 15 17:51:01 2007 +0100

    Distribute hw/xfree86/modes.

diff --git a/hw/xfree86/Makefile.am b/hw/xfree86/Makefile.am
index 5bed7d9..1a286d6 100644
--- a/hw/xfree86/Makefile.am
+++ b/hw/xfree86/Makefile.am
@@ -17,7 +17,7 @@ SUBDIRS = common ddc dummylib i2c x86emu
 
 DIST_SUBDIRS = common ddc dummylib i2c x86emu int10 fbdevhw os-support \
                parser rac ramdac shadowfb vbe vgahw xaa xf1bpp xf4bpp \
-               xf8_16bpp xf8_32bpp loader scanpci dixmods dri exa \
+               xf8_16bpp xf8_32bpp loader scanpci dixmods dri exa modes \
 	       utils doc
 
 bin_PROGRAMS = Xorg
diff-tree d4eb4d065032112a38444e36f791cb468a5ca8f4 (from 37fe4c49dc3a5faf2d3d56112b6bd78453045f6a)
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Thu Feb 15 20:36:20 2007 -0800

    Merge crtc/output-based mode selection code.
    
    This code comes from the intel driver, so there's no history in this tree.
    
    As the crtc/output-based mode selection code uses ddc, the ddc and i2c
    modules have been merged into the server. Attempts to load them are safely
    ignored now.

diff --git a/configure.ac b/configure.ac
index afbf980..d2d2c87 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1905,6 +1905,7 @@ hw/xfree86/fbdevhw/Makefile
 hw/xfree86/i2c/Makefile
 hw/xfree86/int10/Makefile
 hw/xfree86/loader/Makefile
+hw/xfree86/modes/Makefile
 hw/xfree86/os-support/Makefile
 hw/xfree86/os-support/bsd/Makefile
 hw/xfree86/os-support/bus/Makefile
diff --git a/hw/xfree86/Makefile.am b/hw/xfree86/Makefile.am
index 0c1306f..5bed7d9 100644
--- a/hw/xfree86/Makefile.am
+++ b/hw/xfree86/Makefile.am
@@ -12,7 +12,7 @@ DOC_SUBDIR = doc
 
 SUBDIRS = common ddc dummylib i2c x86emu int10 fbdevhw os-support parser rac \
           ramdac shadowfb vbe vgahw xaa xf1bpp xf4bpp xf8_16bpp \
-	  xf8_32bpp loader scanpci dixmods exa \
+	  xf8_32bpp loader scanpci dixmods exa modes \
 	  $(DRI_SUBDIR) $(XF86UTILS_SUBDIR) $(DOC_SUBDIR)
 
 DIST_SUBDIRS = common ddc dummylib i2c x86emu int10 fbdevhw os-support \
@@ -47,6 +47,9 @@ XORG_LIBS = \
 	    rac/librac.a \
             parser/libxf86config.a \
 	    dixmods/libdixmods.la \
+	    modes/libxf86modes.a \
+	    ddc/libddc.a \
+	    i2c/libi2c.a \
             @XORG_LIBS@
 
 Xorg_DEPENDENCIES = \
diff --git a/hw/xfree86/ddc/Makefile.am b/hw/xfree86/ddc/Makefile.am
index a04b5e8..f3ac803 100644
--- a/hw/xfree86/ddc/Makefile.am
+++ b/hw/xfree86/ddc/Makefile.am
@@ -1,11 +1,10 @@
 sdk_HEADERS = edid.h vdif.h xf86DDC.h
 
-module_LTLIBRARIES = libddc.la
+noinst_LIBRARIES = libddc.a
 
-libddc_la_LDFLAGS = -avoid-version
-libddc_la_SOURCES = xf86DDC.c edid.c interpret_edid.c print_edid.c \
+libddc_a_SOURCES = xf86DDC.c edid.c interpret_edid.c print_edid.c \
                    interpret_vdif.c print_vdif.c ddcProperty.c \
-		    edid_modes.c
+		   edid_modes.c
 
 INCLUDES = $(XORG_INCS) -I$(srcdir)/../i2c
 
diff --git a/hw/xfree86/ddc/ddcProperty.c b/hw/xfree86/ddc/ddcProperty.c
index 13083dd..37efb5b 100644
--- a/hw/xfree86/ddc/ddcProperty.c
+++ b/hw/xfree86/ddc/ddcProperty.c
@@ -31,6 +31,7 @@
 #include "property.h"
 #include "propertyst.h"
 #include "xf86DDC.h"
+#include "xf86_ansic.h"
 
 #define EDID1_ATOM_NAME         "XFree86_DDC_EDID1_RAWDATA"
 #define EDID2_ATOM_NAME         "XFree86_DDC_EDID2_RAWDATA"
diff --git a/hw/xfree86/ddc/xf86DDC.c b/hw/xfree86/ddc/xf86DDC.c
index dd64bd5..4ce585c 100644
--- a/hw/xfree86/ddc/xf86DDC.c
+++ b/hw/xfree86/ddc/xf86DDC.c
@@ -15,6 +15,8 @@
 
 static const OptionInfoRec *DDCAvailableOptions(void *unused);
 
+#if DDC_MODULE
+
 static MODULESETUPPROTO(ddcSetup);
 
 static XF86ModuleVersionInfo ddcVersRec =
@@ -57,6 +59,8 @@ ddcSetup(pointer module, pointer opts, i
     return (pointer)1;
 }
 
+#endif
+
 #define RETRIES 4
 
 static unsigned char *EDIDRead_DDC1(
diff --git a/hw/xfree86/i2c/Makefile.am b/hw/xfree86/i2c/Makefile.am
index e73fcae..70a9ace 100644
--- a/hw/xfree86/i2c/Makefile.am
+++ b/hw/xfree86/i2c/Makefile.am
@@ -1,4 +1,4 @@
-module_LTLIBRARIES = libi2c.la
+module_LIBRARIES = libi2c.a
 
 multimediadir = $(moduledir)/multimedia
 multimedia_LTLIBRARIES =	\
@@ -10,8 +10,7 @@ multimedia_LTLIBRARIES =	\
 	tda9885_drv.la		\
 	uda1380_drv.la
 
-libi2c_la_LDFLAGS = -avoid-version
-libi2c_la_SOURCES = xf86i2c.c xf86i2cmodule.c
+libi2c_a_SOURCES = xf86i2c.c
 
 INCLUDES = $(XORG_INCS)
 
diff --git a/hw/xfree86/loader/Makefile.am b/hw/xfree86/loader/Makefile.am
index 2066002..ceb66a2 100644
--- a/hw/xfree86/loader/Makefile.am
+++ b/hw/xfree86/loader/Makefile.am
@@ -2,7 +2,7 @@ noinst_LIBRARIES = libloader.a
 
 INCLUDES = $(XORG_INCS) -I$(srcdir)/../parser -I$(srcdir)/../dixmods/extmod \
 	   -I$(srcdir)/../vbe -I$(top_srcdir)/miext/cw -I$(srcdir)/../int10 \
-	   -I$(srcdir)/../ddc -I$(srcdir)/../i2c
+	   -I$(srcdir)/../ddc -I$(srcdir)/../i2c -I$(srcdir)/../modes
 
 #AM_LDFLAGS = -r
 AM_CFLAGS = -DIN_LOADER $(DIX_CFLAGS) $(XORG_CFLAGS)
diff --git a/hw/xfree86/loader/loadmod.c b/hw/xfree86/loader/loadmod.c
index ec0f181..e489212 100644
--- a/hw/xfree86/loader/loadmod.c
+++ b/hw/xfree86/loader/loadmod.c
@@ -768,7 +768,7 @@ LoadSubModule(ModuleDescPtr parent, cons
 
     submod = doLoadModule(module, NULL, subdirlist, patternlist, options,
 			  modreq, errmaj, errmin, LD_FLAG_GLOBAL);
-    if (submod) {
+    if (submod && submod != (ModuleDescPtr) 1) {
 	parent->child = AddSibling(parent->child, submod);
 	submod->parent = parent;
     }
@@ -799,7 +799,7 @@ LoadSubModuleLocal(ModuleDescPtr parent,
 
     submod = doLoadModule(module, NULL, subdirlist, patternlist, options,
 			  modreq, errmaj, errmin, 0);
-    if (submod) {
+    if (submod && submod != (ModuleDescPtr) 1) {
 	parent->child = AddSibling(parent->child, submod);
 	submod->parent = parent;
     }
@@ -838,6 +838,11 @@ DuplicateModule(ModuleDescPtr mod, Modul
     return ret;
 }
 
+static const char *compiled_in_modules[] = {
+    "ddc",
+    "i2c",
+    NULL
+};
 
 static ModuleDescPtr
 doLoadModule(const char *module, const char *path, const char **subdirlist,
@@ -856,9 +861,17 @@ doLoadModule(const char *module, const c
     PatternPtr patterns = NULL;
     int noncanonical = 0;
     char *m = NULL;
+    char **cim;
 
     xf86MsgVerb(X_INFO, 3, "LoadModule: \"%s\"", module);
 
+    for (cim = compiled_in_modules; *cim; cim++)
+	if (!strcmp (module, *cim))
+	{
+	    xf86MsgVerb(X_INFO, 3, "Module alread ybuilt-in");
+	    return (ModuleDescPtr) 1;
+	}
+
     patterns = InitPatterns(patternlist);
     name = LoaderGetCanonicalName(module, patterns);
     noncanonical = (name && strcmp(module, name) != 0);
@@ -1108,6 +1121,9 @@ UnloadDriver(ModuleDescPtr mod)
 static void
 UnloadModuleOrDriver(ModuleDescPtr mod)
 {
+    if (mod == (ModuleDescPtr) 1)
+	return;
+
     if (mod == NULL || mod->name == NULL)
 	return;
 
@@ -1156,6 +1172,8 @@ FreeModuleDesc(ModuleDescPtr head)
 {
     ModuleDescPtr sibs, prev;
 
+    if (head == (ModuleDescPtr) 1)
+	return;
     /*
      * only free it if it's not marked as in use. In use means that it may
      * be unloaded someday, and UnloadModule or UnloadDriver will free it
@@ -1338,7 +1356,7 @@ LoaderGetCanonicalName(const char *modna
 unsigned long
 LoaderGetModuleVersion(ModuleDescPtr mod)
 {
-    if (!mod || !mod->VersionInfo)
+    if (!mod || mod == (ModuleDescPtr) 1 || !mod->VersionInfo)
 	return 0;
 
     return MODULE_VERSION_NUMERIC(mod->VersionInfo->majorversion,
diff --git a/hw/xfree86/loader/xf86sym.c b/hw/xfree86/loader/xf86sym.c
index 1cb7dae..6337265 100644
--- a/hw/xfree86/loader/xf86sym.c
+++ b/hw/xfree86/loader/xf86sym.c
@@ -89,6 +89,13 @@
 #include "xf86sbusBus.h"
 #endif
 #include "compiler.h"
+#include "xf86Crtc.h"
+#include "xf86Modes.h"
+#ifdef RANDR
+#include "xf86RandR12.h"
+#endif
+#include "xf86DDC.h"
+#include "edid.h"
 
 #ifndef HAS_GLIBC_SIGSETJMP
 #if defined(setjmp) && defined(__GNU_LIBRARY__) && \
@@ -1161,4 +1168,85 @@ _X_HIDDEN void *xfree86LookupTab[] = {
 
     /* Pci.c */
     SYMVAR(pciNumBuses)
+
+    /* modes */
+    SYMFUNC(xf86CrtcConfigInit)
+    SYMFUNC(xf86CrtcConfigPrivateIndex)
+    SYMFUNC(xf86CrtcCreate)
+    SYMFUNC(xf86CrtcDestroy)
+    SYMFUNC(xf86CrtcInUse)
+    SYMFUNC(xf86CrtcRotate)
+    SYMFUNC(xf86CrtcSetMode)
+    SYMFUNC(xf86CrtcSetSizeRange)
+    SYMFUNC(xf86CVTMode)
+    SYMFUNC(xf86DisableUnusedFunctions)
+    SYMFUNC(xf86DPMSSet)
+    SYMFUNC(xf86DuplicateMode)
+    SYMFUNC(xf86DuplicateModes)
+    SYMFUNC(xf86GetDefaultModes)
+    SYMFUNC(xf86GetMonitorModes)
+    SYMFUNC(xf86InitialConfiguration)
+    SYMFUNC(xf86ModeHSync)
+    SYMFUNC(xf86ModesAdd)
+    SYMFUNC(xf86ModesEqual)
+    SYMFUNC(xf86ModeVRefresh)
+    SYMFUNC(xf86OutputCreate)
+    SYMFUNC(xf86OutputDestroy)
+    SYMFUNC(xf86OutputGetEDID)
+    SYMFUNC(xf86OutputGetEDIDModes)
+    SYMFUNC(xf86OutputRename)
+    SYMFUNC(xf86OutputSetEDID)
+    SYMFUNC(xf86PrintModeline)
+    SYMFUNC(xf86ProbeOutputModes)
+    SYMFUNC(xf86PruneInvalidModes)
+    SYMFUNC(xf86SetModeCrtc)
+    SYMFUNC(xf86SetModeDefaultName)
+    SYMFUNC(xf86SetScrnInfoModes)
+    SYMFUNC(xf86ValidateModesClocks)
+    SYMFUNC(xf86ValidateModesFlags)
+    SYMFUNC(xf86ValidateModesSize)
+    SYMFUNC(xf86ValidateModesSync)
+    SYMFUNC(xf86ValidateModesUserConfig)
+    SYMFUNC(xf86DiDGAInit)
+    SYMFUNC(xf86DiDGAReInit)
+    SYMFUNC(xf86DDCGetModes)
+    SYMFUNC(xf86SaveScreen)
+#ifdef RANDR
+    SYMFUNC(xf86RandR12CreateScreenResources)
+    SYMFUNC(xf86RandR12GetOriginalVirtualSize)
+    SYMFUNC(xf86RandR12GetRotation)
+    SYMFUNC(xf86RandR12Init)
+    SYMFUNC(xf86RandR12PreInit)
+    SYMFUNC(xf86RandR12SetConfig)
+    SYMFUNC(xf86RandR12SetRotations)
+#endif
+
+    SYMFUNC(xf86DoEDID_DDC1)
+    SYMFUNC(xf86DoEDID_DDC2)
+    SYMFUNC(xf86InterpretEDID)
+    SYMFUNC(xf86PrintEDID)
+    SYMFUNC(xf86InterpretVdif)
+    SYMFUNC(xf86print_vdif)
+    SYMFUNC(xf86DDCMonitorSet)
+    SYMFUNC(xf86SetDDCproperties)
+
+    SYMFUNC(xf86CreateI2CBusRec)
+    SYMFUNC(xf86CreateI2CDevRec)
+    SYMFUNC(xf86DestroyI2CBusRec)
+    SYMFUNC(xf86DestroyI2CDevRec)
+    SYMFUNC(xf86I2CBusInit)
+    SYMFUNC(xf86I2CDevInit)
+    SYMFUNC(xf86I2CFindBus)
+    SYMFUNC(xf86I2CFindDev)
+    SYMFUNC(xf86I2CGetScreenBuses)
+    SYMFUNC(xf86I2CProbeAddress)
+    SYMFUNC(xf86I2CReadByte)
+    SYMFUNC(xf86I2CReadBytes)
+    SYMFUNC(xf86I2CReadStatus)
+    SYMFUNC(xf86I2CReadWord)
+    SYMFUNC(xf86I2CWriteByte)
+    SYMFUNC(xf86I2CWriteBytes)
+    SYMFUNC(xf86I2CWriteRead)
+    SYMFUNC(xf86I2CWriteVec)
+    SYMFUNC(xf86I2CWriteWord)
 };
diff --git a/hw/xfree86/modes/Makefile.am b/hw/xfree86/modes/Makefile.am
new file mode 100644
index 0000000..60d2553
--- /dev/null
+++ b/hw/xfree86/modes/Makefile.am
@@ -0,0 +1,27 @@
+noinst_LIBRARIES = libxf86modes.a
+
+libxf86modes_a_SOURCES = \
+	xf86Crtc.c \
+	xf86Crtc.h \
+	xf86cvt.c \
+	xf86DiDGA.c \
+	xf86EdidModes.c \
+	xf86Modes.c \
+	xf86Modes.h \
+	xf86RandR12.c \
+	xf86RandR12.h \
+	xf86Rename.h \
+	xf86Rotate.c
+
+INCLUDES = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
+	   -I$(srcdir)/../loader -I$(srcdir)/../rac -I$(srcdir)/../parser \
+           -I$(srcdir)/../scanpci -I$(srcdir)/../vbe -I$(srcdir)/../int10 \
+	   -I$(srcdir)/../vgahw -I$(srcdir)/../dixmods/extmod
+
+sdk_HEADERS = \
+	xf86Crtc.h \
+	xf86Modes.h \
+	xf86RandR12.h \
+	xf86Rename.h
+
+AM_CFLAGS = $(XORG_CFLAGS)
diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
new file mode 100644
index 0000000..ab7070b
--- /dev/null
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -0,0 +1,1587 @@
+/*
+ * Copyright © 2006 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 the copyright holders not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  The copyright holders make no representations
+ * about the suitability of this software for any purpose.  It is provided "as
+ * is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS 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_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "xf86.h"
+#include "xf86DDC.h"
+#include "xf86Crtc.h"
+#include "xf86Modes.h"
+#include "xf86RandR12.h"
+#include "X11/extensions/render.h"
+#define DPMS_SERVER
+#include "X11/extensions/dpms.h"
+#include "X11/Xatom.h"
+
+/*
+ * Initialize xf86CrtcConfig structure
+ */
+
+int xf86CrtcConfigPrivateIndex = -1;
+
+void
+xf86CrtcConfigInit (ScrnInfoPtr scrn)
+{
+    xf86CrtcConfigPtr	config;
+    
+    if (xf86CrtcConfigPrivateIndex == -1)
+	xf86CrtcConfigPrivateIndex = xf86AllocateScrnInfoPrivateIndex();
+    config = xnfcalloc (1, sizeof (xf86CrtcConfigRec));
+    scrn->privates[xf86CrtcConfigPrivateIndex].ptr = config;
+}
+ 
+void
+xf86CrtcSetSizeRange (ScrnInfoPtr scrn,
+		      int minWidth, int minHeight,
+		      int maxWidth, int maxHeight)
+{
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+
+    config->minWidth = minWidth;
+    config->minHeight = minHeight;
+    config->maxWidth = maxWidth;
+    config->maxHeight = maxHeight;
+}
+
+/*
+ * Crtc functions
+ */
+xf86CrtcPtr
+xf86CrtcCreate (ScrnInfoPtr		scrn,
+		const xf86CrtcFuncsRec	*funcs)
+{
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    xf86CrtcPtr		crtc, *crtcs;
+
+    crtc = xcalloc (sizeof (xf86CrtcRec), 1);
+    if (!crtc)
+	return NULL;
+    crtc->scrn = scrn;
+    crtc->funcs = funcs;
+#ifdef RANDR_12_INTERFACE
+    crtc->randr_crtc = NULL;
+#endif
+    crtc->rotation = RR_Rotate_0;
+    crtc->desiredRotation = RR_Rotate_0;
+    if (xf86_config->crtc)
+	crtcs = xrealloc (xf86_config->crtc,
+			  (xf86_config->num_crtc + 1) * sizeof (xf86CrtcPtr));
+    else
+	crtcs = xalloc ((xf86_config->num_crtc + 1) * sizeof (xf86CrtcPtr));
+    if (!crtcs)
+    {
+	xfree (crtc);
+	return NULL;
+    }
+    xf86_config->crtc = crtcs;
+    xf86_config->crtc[xf86_config->num_crtc++] = crtc;
+    return crtc;
+}
+
+void
+xf86CrtcDestroy (xf86CrtcPtr crtc)
+{
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(crtc->scrn);
+    int			c;
+    
+    (*crtc->funcs->destroy) (crtc);
+    for (c = 0; c < xf86_config->num_crtc; c++)
+	if (xf86_config->crtc[c] == crtc)
+	{
+	    memmove (&xf86_config->crtc[c],
+		     &xf86_config->crtc[c+1],
+		     xf86_config->num_crtc - (c + 1));
+	    xf86_config->num_crtc--;
+	    break;
+	}
+    xfree (crtc);
+}
+
+
+/**
+ * Return whether any outputs are connected to the specified pipe
+ */
+
+Bool
+xf86CrtcInUse (xf86CrtcPtr crtc)
+{
+    ScrnInfoPtr		pScrn = crtc->scrn;
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
+    int			o;
+    
+    for (o = 0; o < xf86_config->num_output; o++)
+	if (xf86_config->output[o]->crtc == crtc)
+	    return TRUE;
+    return FALSE;
+}
+
+/**
+ * Sets the given video mode on the given crtc
+ */
+Bool
+xf86CrtcSetMode (xf86CrtcPtr crtc, DisplayModePtr mode, Rotation rotation,
+		 int x, int y)
+{
+    ScrnInfoPtr		scrn = crtc->scrn;
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			i;
+    Bool		ret = FALSE;
+    Bool		didLock = FALSE;
+    DisplayModePtr	adjusted_mode;
+    DisplayModeRec	saved_mode;
+    int			saved_x, saved_y;
+    Rotation		saved_rotation;
+
+    adjusted_mode = xf86DuplicateMode(mode);
+
+    crtc->enabled = xf86CrtcInUse (crtc);
+    
+    if (!crtc->enabled)
+    {
+	/* XXX disable crtc? */
+	return TRUE;
+    }
+
+    didLock = crtc->funcs->lock (crtc);
+
+    saved_mode = crtc->mode;
+    saved_x = crtc->x;
+    saved_y = crtc->y;
+    saved_rotation = crtc->rotation;
+    /* Update crtc values up front so the driver can rely on them for mode
+     * setting.
+     */
+    crtc->mode = *mode;
+    crtc->x = x;
+    crtc->y = y;
+    crtc->rotation = rotation;
+
+    /* XXX short-circuit changes to base location only */
+    
+    /* Pass our mode to the outputs and the CRTC to give them a chance to
+     * adjust it according to limitations or output properties, and also
+     * a chance to reject the mode entirely.
+     */
+    for (i = 0; i < xf86_config->num_output; i++) {
+	xf86OutputPtr output = xf86_config->output[i];
+
+	if (output->crtc != crtc)
+	    continue;
+
+	if (!output->funcs->mode_fixup(output, mode, adjusted_mode)) {
+	    goto done;
+	}
+    }
+
+    if (!crtc->funcs->mode_fixup(crtc, mode, adjusted_mode)) {
+	goto done;
+    }
+
+    if (!xf86CrtcRotate (crtc, mode, rotation)) {
+	goto done;
+    }
+
+    /* Disable the outputs and CRTCs before setting the mode. */
+    for (i = 0; i < xf86_config->num_output; i++) {
+	xf86OutputPtr output = xf86_config->output[i];
+
+	if (output->crtc != crtc)
+	    continue;
+
+	/* Disable the output as the first thing we do. */
+	output->funcs->dpms(output, DPMSModeOff);
+    }
+
+    crtc->funcs->dpms(crtc, DPMSModeOff);
+
+    /* Set up the DPLL and any output state that needs to adjust or depend
+     * on the DPLL.
+     */
+    crtc->funcs->mode_set(crtc, mode, adjusted_mode, x, y);
+    for (i = 0; i < xf86_config->num_output; i++) 
+    {
+	xf86OutputPtr output = xf86_config->output[i];
+	if (output->crtc == crtc)
+	    output->funcs->mode_set(output, mode, adjusted_mode);
+    }
+
+    /* Now, enable the clocks, plane, pipe, and outputs that we set up. */
+    crtc->funcs->dpms(crtc, DPMSModeOn);
+    for (i = 0; i < xf86_config->num_output; i++) 
+    {
+	xf86OutputPtr output = xf86_config->output[i];
+	if (output->crtc == crtc)
+	    output->funcs->dpms(output, DPMSModeOn);
+    }
+
+    /* XXX free adjustedmode */
+    ret = TRUE;
+done:
+    if (!ret) {
+	crtc->x = saved_x;
+	crtc->y = saved_y;
+	crtc->rotation = saved_rotation;
+	crtc->mode = saved_mode;
+    }
+
+    if (didLock)
+	crtc->funcs->unlock (crtc);
+
+    return ret;
+}
+
+/*
+ * Output functions
+ */
+
+extern XF86ConfigPtr xf86configptr;
+
+typedef enum {
+    OPTION_PREFERRED_MODE,
+    OPTION_POSITION,
+    OPTION_BELOW,
+    OPTION_RIGHT_OF,
+    OPTION_ABOVE,
+    OPTION_LEFT_OF,
+    OPTION_ENABLE,
+    OPTION_DISABLE,
+    OPTION_MIN_CLOCK,
+    OPTION_MAX_CLOCK,
+    OPTION_IGNORE,
+} OutputOpts;
+
+static OptionInfoRec xf86OutputOptions[] = {
+    {OPTION_PREFERRED_MODE, "PreferredMode",	OPTV_STRING,  {0}, FALSE },
+    {OPTION_POSITION,	    "Position",		OPTV_STRING,  {0}, FALSE },
+    {OPTION_BELOW,	    "Below",		OPTV_STRING,  {0}, FALSE },
+    {OPTION_RIGHT_OF,	    "RightOf",		OPTV_STRING,  {0}, FALSE },
+    {OPTION_ABOVE,	    "Above",		OPTV_STRING,  {0}, FALSE },
+    {OPTION_LEFT_OF,	    "LeftOf",		OPTV_STRING,  {0}, FALSE },
+    {OPTION_ENABLE,	    "Enable",		OPTV_BOOLEAN, {0}, FALSE },
+    {OPTION_DISABLE,	    "Disable",		OPTV_BOOLEAN, {0}, FALSE },
+    {OPTION_MIN_CLOCK,	    "MinClock",		OPTV_FREQ,    {0}, FALSE },
+    {OPTION_MAX_CLOCK,	    "MaxClock",		OPTV_FREQ,    {0}, FALSE },
+    {OPTION_IGNORE,	    "Ignore",		OPTV_BOOLEAN, {0}, FALSE },
+    {-1,		    NULL,		OPTV_NONE,    {0}, FALSE },
+};
+
+static void
+xf86OutputSetMonitor (xf86OutputPtr output)
+{
+    char    *option_name;
+    static const char monitor_prefix[] = "monitor-";
+    char    *monitor;
+
+    if (!output->name)
+	return;
+
+    if (output->options)
+	xfree (output->options);
+
+    output->options = xnfalloc (sizeof (xf86OutputOptions));
+    memcpy (output->options, xf86OutputOptions, sizeof (xf86OutputOptions));
+    
+    option_name = xnfalloc (strlen (monitor_prefix) +
+			    strlen (output->name) + 1);
+    strcpy (option_name, monitor_prefix);
+    strcat (option_name, output->name);
+    monitor = xf86findOptionValue (output->scrn->options, option_name);
+    if (!monitor)
+	monitor = output->name;
+    else
+	xf86MarkOptionUsedByName (output->scrn->options, option_name);
+    xfree (option_name);
+    output->conf_monitor = xf86findMonitor (monitor,
+					    xf86configptr->conf_monitor_lst);
+    if (output->conf_monitor)
+	xf86ProcessOptions (output->scrn->scrnIndex,
+			    output->conf_monitor->mon_option_lst,
+			    output->options);
+}
+
+static Bool
+xf86OutputEnabled (xf86OutputPtr    output)
+{
+    /* Check to see if this output was disabled in the config file */
+    if (xf86ReturnOptValBool (output->options, OPTION_ENABLE, TRUE) == FALSE ||
+	xf86ReturnOptValBool (output->options, OPTION_DISABLE, FALSE) == TRUE)
+    {
+	return FALSE;
+    }
+    return TRUE;
+}
+
+static Bool
+xf86OutputIgnored (xf86OutputPtr    output)
+{
+    return xf86ReturnOptValBool (output->options, OPTION_IGNORE, FALSE);
+}
+
+xf86OutputPtr
+xf86OutputCreate (ScrnInfoPtr		    scrn,
+		  const xf86OutputFuncsRec *funcs,
+		  const char		    *name)
+{
+    xf86OutputPtr	output, *outputs;
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			len;
+
+    if (name)
+	len = strlen (name) + 1;
+    else
+	len = 0;
+
+    output = xcalloc (sizeof (xf86OutputRec) + len, 1);
+    if (!output)
+	return NULL;
+    output->scrn = scrn;
+    output->funcs = funcs;
+    if (name)
+    {
+	output->name = (char *) (output + 1);
+	strcpy (output->name, name);
+    }
+    output->subpixel_order = SubPixelUnknown;
+#ifdef RANDR_12_INTERFACE
+    output->randr_output = NULL;
+#endif
+    if (name)
+    {
+	xf86OutputSetMonitor (output);
+	if (xf86OutputIgnored (output))
+	{
+	    xfree (output);
+	    return FALSE;
+	}
+    }
+    
+    
+    if (xf86_config->output)
+	outputs = xrealloc (xf86_config->output,
+			  (xf86_config->num_output + 1) * sizeof (xf86OutputPtr));
+    else
+	outputs = xalloc ((xf86_config->num_output + 1) * sizeof (xf86OutputPtr));
+    if (!outputs)
+    {
+	xfree (output);
+	return NULL;
+    }
+    
+    xf86_config->output = outputs;
+    xf86_config->output[xf86_config->num_output++] = output;
+    
+    return output;
+}
+
+Bool
+xf86OutputRename (xf86OutputPtr output, const char *name)
+{
+    int	    len = strlen(name) + 1;
+    char    *newname = xalloc (len);
+    
+    if (!newname)
+	return FALSE;	/* so sorry... */
+    
+    strcpy (newname, name);
+    if (output->name && output->name != (char *) (output + 1))
+	xfree (output->name);
+    output->name = newname;
+    xf86OutputSetMonitor (output);
+    if (xf86OutputIgnored (output))
+	return FALSE;
+    return TRUE;
+}
+
+void
+xf86OutputDestroy (xf86OutputPtr output)
+{
+    ScrnInfoPtr		scrn = output->scrn;
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			o;
+    
+    (*output->funcs->destroy) (output);
+    while (output->probed_modes)
+	xf86DeleteMode (&output->probed_modes, output->probed_modes);
+    for (o = 0; o < xf86_config->num_output; o++)
+	if (xf86_config->output[o] == output)
+	{
+	    memmove (&xf86_config->output[o],
+		     &xf86_config->output[o+1],
+		     xf86_config->num_output - (o + 1));
+	    xf86_config->num_output--;
+	    break;
+	}
+    if (output->name && output->name != (char *) (output + 1))
+	xfree (output->name);
+    xfree (output);
+}
+
+static DisplayModePtr
+xf86DefaultMode (xf86OutputPtr output, int width, int height)
+{
+    DisplayModePtr  target_mode = NULL;
+    DisplayModePtr  mode;
+    int		    target_diff = 0;
+    int		    target_preferred = 0;
+    int		    mm_height;
+    
+    mm_height = output->mm_height;
+    if (!mm_height)
+	mm_height = 203;	/* 768 pixels at 96dpi */
+    /*
+     * Pick a mode closest to 96dpi 
+     */
+    for (mode = output->probed_modes; mode; mode = mode->next)
+    {
+	int	    dpi;
+	int	    preferred = (mode->type & M_T_PREFERRED) != 0;
+	int	    diff;
+
+	if (mode->HDisplay > width || mode->VDisplay > height) continue;
+	dpi = (mode->HDisplay * 254) / (mm_height * 10);
+	diff = dpi - 96;
+	diff = diff < 0 ? -diff : diff;
+	if (target_mode == NULL || (preferred > target_preferred) ||
+	    (preferred == target_preferred && diff < target_diff))
+	{
+	    target_mode = mode;
+	    target_diff = diff;
+	    target_preferred = preferred;
+	}
+    }
+    return target_mode;
+}
+
+static DisplayModePtr
+xf86ClosestMode (xf86OutputPtr output, DisplayModePtr match,
+		 int width, int height)
+{
+    DisplayModePtr  target_mode = NULL;
+    DisplayModePtr  mode;
+    int		    target_diff = 0;
+    
+    /*
+     * Pick a mode closest to the specified mode
+     */
+    for (mode = output->probed_modes; mode; mode = mode->next)
+    {
+	int	    dx, dy;
+	int	    diff;
+
+	if (mode->HDisplay > width || mode->VDisplay > height) continue;
+	
+	/* exact matches are preferred */
+	if (xf86ModesEqual (mode, match))
+	    return mode;
+	
+	dx = match->HDisplay - mode->HDisplay;
+	dy = match->VDisplay - mode->VDisplay;
+	diff = dx * dx + dy * dy;
+	if (target_mode == NULL || diff < target_diff)
+	{
+	    target_mode = mode;
+	    target_diff = diff;
+	}
+    }
+    return target_mode;
+}
+
+static Bool
+xf86OutputHasPreferredMode (xf86OutputPtr output, int width, int height)
+{
+    DisplayModePtr  mode;
+
+    for (mode = output->probed_modes; mode; mode = mode->next)
+    {
+	if (mode->HDisplay > width || mode->VDisplay > height) continue;
+	if (mode->type & M_T_PREFERRED)
+	    return TRUE;
+    }
+    return FALSE;
+}
+
+static int
+xf86PickCrtcs (ScrnInfoPtr	scrn,
+	       xf86CrtcPtr	*best_crtcs,
+	       DisplayModePtr	*modes,
+	       int		n,
+	       int		width,
+	       int		height)
+{
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+    int		    c, o, l;
+    xf86OutputPtr   output;
+    xf86CrtcPtr	    crtc;
+    xf86CrtcPtr	    *crtcs;
+    xf86CrtcPtr	    best_crtc;
+    int		    best_score;
+    int		    score;
+    int		    my_score;
+    
+    if (n == config->num_output)
+	return 0;
+    output = config->output[n];
+    
+    /*
+     * Compute score with this output disabled
+     */
+    best_crtcs[n] = NULL;
+    best_crtc = NULL;
+    best_score = xf86PickCrtcs (scrn, best_crtcs, modes, n+1, width, height);
+    if (modes[n] == NULL)
+	return best_score;
+    
+    crtcs = xalloc (config->num_output * sizeof (xf86CrtcPtr));
+    if (!crtcs)
+	return best_score;
+
+    my_score = 1;
+    /* Score outputs that are known to be connected higher */
+    if (output->status == XF86OutputStatusConnected)
+	my_score++;
+    /* Score outputs with preferred modes higher */
+    if (xf86OutputHasPreferredMode (output, width, height))
+	my_score++;
+    /*
+     * Select a crtc for this output and
+     * then attempt to configure the remaining
+     * outputs
+     */
+    for (c = 0; c < config->num_crtc; c++)
+    {
+	if ((output->possible_crtcs & (1 << c)) == 0)
+	    continue;
+	
+	crtc = config->crtc[c];
+	/*
+	 * Check to see if some other output is
+	 * using this crtc
+	 */
+	for (o = 0; o < n; o++)
+	    if (best_crtcs[o] == crtc)
+		break;
+	if (o < n)
+	{
+	    /*
+	     * If the two outputs desire the same mode,
+	     * see if they can be cloned
+	     */
+	    if (xf86ModesEqual (modes[o], modes[n]) &&
+		config->output[o]->initial_x == config->output[n]->initial_x &&
+		config->output[o]->initial_y == config->output[n]->initial_y)
+	    {
+		for (l = 0; l < config->num_output; l++)
+		    if (output->possible_clones & (1 << l))
+			break;
+		if (l == config->num_output)
+		    continue;		/* nope, try next CRTC */
+	    }
+	    else
+		continue;		/* different modes, can't clone */
+	}
+	crtcs[n] = crtc;
+	memcpy (crtcs, best_crtcs, n * sizeof (xf86CrtcPtr));
+	score = my_score + xf86PickCrtcs (scrn, crtcs, modes, n+1, width, height);
+	if (score > best_score)
+	{
+	    best_crtc = crtc;
+	    best_score = score;
+	    memcpy (best_crtcs, crtcs, config->num_output * sizeof (xf86CrtcPtr));
+	}
+    }
+    xfree (crtcs);
+    return best_score;
+}
+
+
+/*
+ * Compute the virtual size necessary to place all of the available
+ * crtcs in the specified configuration and also large enough to
+ * resize any crtc to the largest available mode
+ */
+
+static void
+xf86DefaultScreenLimits (ScrnInfoPtr scrn, int *widthp, int *heightp)
+{
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+    int	    width = 0, height = 0;
+    int	    o;
+    int	    c;
+    int	    s;
+
+    for (c = 0; c < config->num_crtc; c++)
+    {
+	int	    crtc_width = 0, crtc_height = 0;
+	xf86CrtcPtr crtc = config->crtc[c];
+
+	if (crtc->enabled)
+	{
+	    crtc_width = crtc->x + crtc->desiredMode.HDisplay;
+	    crtc_height = crtc->y + crtc->desiredMode.VDisplay;
+	}
+	for (o = 0; o < config->num_output; o++) 
+	{
+	    xf86OutputPtr   output = config->output[o];
+
+	    for (s = 0; s < config->num_crtc; s++)
+		if (output->possible_crtcs & (1 << s))
+		{
+		    DisplayModePtr  mode;
+		    for (mode = output->probed_modes; mode; mode = mode->next)
+		    {
+			if (mode->HDisplay > crtc_width)
+			    crtc_width = mode->HDisplay;
+			if (mode->VDisplay > crtc_height)
+			    crtc_height = mode->VDisplay;
+		    }
+		}
+	}
+	if (crtc_width > width)
+	    width = crtc_width;
+	if (crtc_height > height)
+	    height = crtc_height;
+    }
+    if (config->maxWidth && width > config->maxWidth) width = config->maxWidth;
+    if (config->maxHeight && height > config->maxHeight) height = config->maxHeight;
+    if (config->minWidth && width < config->minWidth) width = config->minWidth;
+    if (config->minHeight && height < config->minHeight) height = config->minHeight;
+    *widthp = width;
+    *heightp = height;
+}
+
+#define POSITION_UNSET	-100000
+
+static Bool
+xf86InitialOutputPositions (ScrnInfoPtr scrn, DisplayModePtr *modes)
+{
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			o;
+    int			min_x, min_y;
+    
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr	output = config->output[o];
+
+	output->initial_x = output->initial_y = POSITION_UNSET;
+    }
+    
+    /*
+     * Loop until all outputs are set
+     */
+    for (;;)
+    {
+	Bool	any_set = FALSE;
+	Bool	keep_going = FALSE;
+
+	for (o = 0; o < config->num_output; o++)	
+	{
+	    static const OutputOpts	relations[] = {
+		OPTION_BELOW, OPTION_RIGHT_OF, OPTION_ABOVE, OPTION_LEFT_OF
+	    };
+	    xf86OutputPtr   output = config->output[o];
+	    xf86OutputPtr   relative;
+	    char	    *relative_name;
+	    char	    *position;
+	    OutputOpts	    relation;
+	    int		    r;
+
+	    if (output->initial_x != POSITION_UNSET)
+		continue;
+	    position = xf86GetOptValString (output->options,
+					    OPTION_POSITION);
+	    /*
+	     * Absolute position wins
+	     */
+	    if (position)
+	    {
+		int		    x, y;
+		if (sscanf (position, "%d %d", &x, &y) == 2)
+		{
+		    output->initial_x = x;
+		    output->initial_y = y;
+		}
+		else
+		{
+		    xf86DrvMsg (scrn->scrnIndex, X_ERROR,
+				"Output %s position not of form \"x y\"\n",
+				output->name);
+		    output->initial_x = output->initial_y = 0;
+		}
+		any_set = TRUE;
+		continue;
+	    }
+	    /*
+	     * Next comes relative positions
+	     */
+	    relation = 0;
+	    relative_name = NULL;
+	    for (r = 0; r < 4; r++)
+	    {
+		relation = relations[r];
+		relative_name = xf86GetOptValString (output->options,
+						     relation);
+		if (relative_name)
+		    break;
+	    }
+	    if (relative_name)
+	    {
+		int or;
+		relative = NULL;
+		for (or = 0; or < config->num_output; or++)
+		{
+		    xf86OutputPtr	out_rel = config->output[or];
+		    XF86ConfMonitorPtr	rel_mon = out_rel->conf_monitor;
+		    char		*name;
+
+		    if (rel_mon)
+			name = rel_mon->mon_identifier;
+		    else
+			name = out_rel->name;
+		    if (!strcmp (relative_name, name))
+		    {
+			relative = config->output[or];
+			break;
+		    }
+		}
+		if (!relative)
+		{
+		    xf86DrvMsg (scrn->scrnIndex, X_ERROR,
+				"Cannot position output %s relative to unknown output %s\n",
+				output->name, relative_name);
+		    output->initial_x = 0;
+		    output->initial_y = 0;
+		    any_set = TRUE;
+		    continue;
+		}
+		if (relative->initial_x == POSITION_UNSET)
+		{
+		    keep_going = TRUE;
+		    continue;
+		}
+		output->initial_x = relative->initial_x;
+		output->initial_y = relative->initial_y;
+		switch (relation) {
+		case OPTION_BELOW:
+		    output->initial_y += modes[or]->VDisplay;
+		    break;
+		case OPTION_RIGHT_OF:
+		    output->initial_x += modes[or]->HDisplay;
+		    break;
+		case OPTION_ABOVE:
+		    output->initial_y -= modes[o]->VDisplay;
+		    break;
+		case OPTION_LEFT_OF:
+		    output->initial_x -= modes[o]->HDisplay;
+		    break;
+		default:
+		    break;
+		}
+		any_set = TRUE;
+		continue;
+	    }
+	    
+	    /* Nothing set, just stick them at 0,0 */
+	    output->initial_x = 0;
+	    output->initial_y = 0;
+	    any_set = TRUE;
+	}
+	if (!keep_going)
+	    break;
+	if (!any_set) 
+	{
+	    for (o = 0; o < config->num_output; o++)
+	    {
+		xf86OutputPtr   output = config->output[o];
+		if (output->initial_x == POSITION_UNSET)
+		{
+		    xf86DrvMsg (scrn->scrnIndex, X_ERROR,
+				"Output position loop. Moving %s to 0,0\n",
+				output->name);
+		    output->initial_x = output->initial_y = 0;
+		    break;
+		}
+	    }
+	}
+    }
+
+    /*
+     * normalize positions
+     */
+    min_x = 1000000;
+    min_y = 1000000;
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr	output = config->output[o];
+
+	if (output->initial_x < min_x)
+	    min_x = output->initial_x;
+	if (output->initial_y < min_y)
+	    min_y = output->initial_y;
+    }
+    
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr	output = config->output[o];
+
+	output->initial_x -= min_x;
+	output->initial_y -= min_y;
+    }
+    return TRUE;
+}
+
+/*
+ * XXX walk the monitor mode list and prune out duplicates that
+ * are inserted by xf86DDCMonitorSet. In an ideal world, that
+ * function would do this work by itself.
+ */
+
+static void
+xf86PruneDuplicateMonitorModes (MonPtr Monitor)
+{
+    DisplayModePtr  master, clone, next;
+
+    for (master = Monitor->Modes; 
+	 master && master != Monitor->Last; 
+	 master = master->next)
+    {
+	for (clone = master->next; clone && clone != Monitor->Modes; clone = next)
+	{
+	    next = clone->next;
+	    if (xf86ModesEqual (master, clone))
+	    {
+		if (Monitor->Last == clone)
+		    Monitor->Last = clone->prev;
+		xf86DeleteMode (&Monitor->Modes, clone);
+	    }
+	}
+    }
+}
+
+/** Return - 0 + if a should be earlier, same or later than b in list
+ */
+static int
+xf86ModeCompare (DisplayModePtr a, DisplayModePtr b)
+{
+    int	diff;
+
+    diff = ((b->type & M_T_PREFERRED) != 0) - ((a->type & M_T_PREFERRED) != 0);
+    if (diff)
+	return diff;
+    diff = b->HDisplay * b->VDisplay - a->HDisplay * a->VDisplay;
+    if (diff)
+	return diff;
+    diff = b->Clock - a->Clock;
+    return diff;
+}
+
+/**
+ * Insertion sort input in-place and return the resulting head
+ */
+static DisplayModePtr
+xf86SortModes (DisplayModePtr input)
+{
+    DisplayModePtr  output = NULL, i, o, n, *op, prev;
+
+    /* sort by preferred status and pixel area */
+    while (input)
+    {
+	i = input;
+	input = input->next;
+	for (op = &output; (o = *op); op = &o->next)
+	    if (xf86ModeCompare (o, i) > 0)
+		break;
+	i->next = *op;
+	*op = i;
+    }
+    /* prune identical modes */
+    for (o = output; o && (n = o->next); o = n)
+    {
+	if (!strcmp (o->name, n->name) && xf86ModesEqual (o, n))
+	{
+	    o->next = n->next;
+	    xfree (n->name);
+	    xfree (n);
+	    n = o;
+	}
+    }
+    /* hook up backward links */
+    prev = NULL;
+    for (o = output; o; o = o->next)
+    {
+	o->prev = prev;
+	prev = o;
+    }
+    return output;
+}
+
+#define DEBUG_REPROBE 1
+
+void
+xf86ProbeOutputModes (ScrnInfoPtr scrn, int maxX, int maxY)
+{
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			o;
+
+    if (maxX == 0 || maxY == 0)
+	xf86RandR12GetOriginalVirtualSize (scrn, &maxX, &maxY);
+
+    /* Elide duplicate modes before defaulting code uses them */
+    xf86PruneDuplicateMonitorModes (scrn->monitor);
+    
+    /* Probe the list of modes for each output. */
+    for (o = 0; o < config->num_output; o++) 
+    {
+	xf86OutputPtr	    output = config->output[o];
+	DisplayModePtr	    mode;
+	DisplayModePtr	    config_modes = NULL, output_modes, default_modes;
+	char		    *preferred_mode;
+	xf86MonPtr	    edid_monitor;
+	XF86ConfMonitorPtr  conf_monitor;
+	MonRec		    mon_rec;
+	int		    min_clock = 0;
+	int		    max_clock = 0;
+	double		    clock;
+	enum { sync_config, sync_edid, sync_default } sync_source = sync_default;
+	
+	while (output->probed_modes != NULL)
+	    xf86DeleteMode(&output->probed_modes, output->probed_modes);
+
+	/*
+	 * Check connection status
+	 */
+	output->status = (*output->funcs->detect)(output);
+
+	if (output->status == XF86OutputStatusDisconnected)
+	    continue;
+
+	memset (&mon_rec, '\0', sizeof (mon_rec));
+	
+	conf_monitor = output->conf_monitor;
+	
+	if (conf_monitor)
+	{
+	    int	i;
+	    
+	    for (i = 0; i < conf_monitor->mon_n_hsync; i++)
+	    {
+		mon_rec.hsync[mon_rec.nHsync].lo = conf_monitor->mon_hsync[i].lo;
+		mon_rec.hsync[mon_rec.nHsync].hi = conf_monitor->mon_hsync[i].hi;
+		mon_rec.nHsync++;
+		sync_source = sync_config;
+	    }
+	    for (i = 0; i < conf_monitor->mon_n_vrefresh; i++)
+	    {
+		mon_rec.vrefresh[mon_rec.nVrefresh].lo = conf_monitor->mon_vrefresh[i].lo;
+		mon_rec.vrefresh[mon_rec.nVrefresh].hi = conf_monitor->mon_vrefresh[i].hi;
+		mon_rec.nVrefresh++;
+		sync_source = sync_config;
+	    }
+	    config_modes = xf86GetMonitorModes (scrn, conf_monitor);
+	}
+	
+	output_modes = (*output->funcs->get_modes) (output);
+	
+	edid_monitor = output->MonInfo;
+	
+	if (edid_monitor)
+	{
+	    int			    i;
+	    Bool		    set_hsync = mon_rec.nHsync == 0;
+	    Bool		    set_vrefresh = mon_rec.nVrefresh == 0;
+
+	    for (i = 0; i < sizeof (edid_monitor->det_mon) / sizeof (edid_monitor->det_mon[0]); i++)
+	    {
+		if (edid_monitor->det_mon[i].type == DS_RANGES)
+		{
+		    struct monitor_ranges   *ranges = &edid_monitor->det_mon[i].section.ranges;
+		    if (set_hsync && ranges->max_h)
+		    {
+			mon_rec.hsync[mon_rec.nHsync].lo = ranges->min_h;
+			mon_rec.hsync[mon_rec.nHsync].hi = ranges->max_h;
+			mon_rec.nHsync++;
+			if (sync_source == sync_default)
+			    sync_source = sync_edid;
+		    }
+		    if (set_vrefresh && ranges->max_v)
+		    {
+			mon_rec.vrefresh[mon_rec.nVrefresh].lo = ranges->min_v;
+			mon_rec.vrefresh[mon_rec.nVrefresh].hi = ranges->max_v;
+			mon_rec.nVrefresh++;
+			if (sync_source == sync_default)
+			    sync_source = sync_edid;
+		    }
+		    if (ranges->max_clock > max_clock)
+			max_clock = ranges->max_clock;
+		}
+	    }
+	}
+
+	if (xf86GetOptValFreq (output->options, OPTION_MIN_CLOCK,
+			       OPTUNITS_KHZ, &clock))
+	    min_clock = (int) clock;
+	if (xf86GetOptValFreq (output->options, OPTION_MAX_CLOCK,
+			       OPTUNITS_KHZ, &clock))
+	    max_clock = (int) clock;
+
+	/*
+	 * These limits will end up setting a 1024x768 at 60Hz mode by default,
+	 * which seems like a fairly good mode to use when nothing else is
+	 * specified
+	 */
+	if (mon_rec.nHsync == 0)
+	{
+	    mon_rec.hsync[0].lo = 31.0;
+	    mon_rec.hsync[0].hi = 55.0;
+	    mon_rec.nHsync = 1;
+	}
+	if (mon_rec.nVrefresh == 0)
+	{
+	    mon_rec.vrefresh[0].lo = 58.0;
+	    mon_rec.vrefresh[0].hi = 62.0;
+	    mon_rec.nVrefresh = 1;
+	}
+	default_modes = xf86GetDefaultModes (output->interlaceAllowed,
+					     output->doubleScanAllowed);
+	
+	if (sync_source == sync_config)
+	{
+	    /* 
+	     * Check output and config modes against sync range from config file
+	     */
+	    xf86ValidateModesSync (scrn, output_modes, &mon_rec);
+	    xf86ValidateModesSync (scrn, config_modes, &mon_rec);
+	}
+	/*
+	 * Check default modes against sync range
+	 */
+        xf86ValidateModesSync (scrn, default_modes, &mon_rec);
+	/*
+	 * Check default modes against monitor max clock
+	 */
+	if (max_clock)
+	    xf86ValidateModesClocks(scrn, default_modes,
+				    &min_clock, &max_clock, 1);
+	
+	output->probed_modes = NULL;
+	output->probed_modes = xf86ModesAdd (output->probed_modes, config_modes);
+	output->probed_modes = xf86ModesAdd (output->probed_modes, output_modes);
+	output->probed_modes = xf86ModesAdd (output->probed_modes, default_modes);
+	
+	/*
+	 * Check all modes against max size
+	 */
+	if (maxX && maxY)
+	    xf86ValidateModesSize (scrn, output->probed_modes,
+				       maxX, maxY, 0);
+	 
+	/*
+	 * Check all modes against output
+	 */
+	for (mode = output->probed_modes; mode != NULL; mode = mode->next) 
+	    if (mode->status == MODE_OK)
+		mode->status = (*output->funcs->mode_valid)(output, mode);
+	
+	xf86PruneInvalidModes(scrn, &output->probed_modes, TRUE);
+	
+	output->probed_modes = xf86SortModes (output->probed_modes);
+	
+	/* Check for a configured preference for a particular mode */
+	preferred_mode = xf86GetOptValString (output->options,
+					      OPTION_PREFERRED_MODE);
+
+	if (preferred_mode)
+	{
+	    for (mode = output->probed_modes; mode; mode = mode->next)
+	    {
+		if (!strcmp (preferred_mode, mode->name))
+		{
+		    if (mode != output->probed_modes)
+		    {
+			if (mode->prev)
+			    mode->prev->next = mode->next;
+			if (mode->next)
+			    mode->next->prev = mode->prev;
+			mode->next = output->probed_modes;
+			output->probed_modes->prev = mode;
+			mode->prev = NULL;
+			output->probed_modes = mode;
+		    }
+		    mode->type |= M_T_PREFERRED;
+		    break;
+		}
+	    }
+	}
+	
+#ifdef DEBUG_REPROBE
+	if (output->probed_modes != NULL) {
+	    xf86DrvMsg(scrn->scrnIndex, X_INFO,
+		       "Printing probed modes for output %s\n",
+		       output->name);
+	} else {
+	    xf86DrvMsg(scrn->scrnIndex, X_INFO,
+		       "No remaining probed modes for output %s\n",
+		       output->name);
+	}
+#endif
+	for (mode = output->probed_modes; mode != NULL; mode = mode->next)
+	{
+	    /* The code to choose the best mode per pipe later on will require
+	     * VRefresh to be set.
+	     */
+	    mode->VRefresh = xf86ModeVRefresh(mode);
+	    xf86SetModeCrtc(mode, INTERLACE_HALVE_V);
+
+#ifdef DEBUG_REPROBE
+	    xf86PrintModeline(scrn->scrnIndex, mode);
+#endif
+	}
+    }
+}
+
+
+/**
+ * Copy one of the output mode lists to the ScrnInfo record
+ */
+
+/* XXX where does this function belong? Here? */
+void
+xf86RandR12GetOriginalVirtualSize(ScrnInfoPtr scrn, int *x, int *y);
+
+void
+xf86SetScrnInfoModes (ScrnInfoPtr scrn)
+{
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+    xf86OutputPtr	output;
+    xf86CrtcPtr		crtc;
+    DisplayModePtr	last, mode;
+
+    output = config->output[config->compat_output];
+    if (!output->crtc)
+    {
+	int o;
+
+	output = NULL;
+	for (o = 0; o < config->num_output; o++)
+	    if (config->output[o]->crtc)
+	    {
+		config->compat_output = o;
+		output = config->output[o];
+		break;
+	    }
+	/* no outputs are active, punt and leave things as they are */
+	if (!output)
+	    return;
+    }
+    crtc = output->crtc;
+
+    /* Clear any existing modes from scrn->modes */
+    while (scrn->modes != NULL)
+	xf86DeleteMode(&scrn->modes, scrn->modes);
+
+    /* Set scrn->modes to the mode list for the 'compat' output */
+    scrn->modes = xf86DuplicateModes(scrn, output->probed_modes);
+
+    for (mode = scrn->modes; mode; mode = mode->next)
+	if (xf86ModesEqual (mode, &crtc->desiredMode))
+	    break;
+
+    if (scrn->modes != NULL) {
+	/* For some reason, scrn->modes is circular, unlike the other mode
+	 * lists.  How great is that?
+	 */
+	for (last = scrn->modes; last && last->next; last = last->next)
+	    ;
+	last->next = scrn->modes;
+	scrn->modes->prev = last;
+	if (mode) {
+	    while (scrn->modes != mode)
+		scrn->modes = scrn->modes->next;
+	}
+    }
+    scrn->currentMode = scrn->modes;
+}
+
+/**
+ * Construct default screen configuration
+ *
+ * Given auto-detected (and, eventually, configured) values,
+ * construct a usable configuration for the system
+ */
+
+Bool
+xf86InitialConfiguration (ScrnInfoPtr	    scrn)
+{
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			o, c;
+    DisplayModePtr	target_mode = NULL;
+    xf86CrtcPtr		*crtcs;
+    DisplayModePtr	*modes;
+    Bool		*enabled;
+    int			width;
+    int			height;
+
+    if (scrn->display->virtualX)
+	width = scrn->display->virtualX;
+    else
+	width = config->maxWidth;
+    if (scrn->display->virtualY)
+	height = scrn->display->virtualY;
+    else
+	height = config->maxHeight;
+
+    xf86ProbeOutputModes (scrn, width, height);
+
+    crtcs = xnfcalloc (config->num_output, sizeof (xf86CrtcPtr));
+    modes = xnfcalloc (config->num_output, sizeof (DisplayModePtr));
+    enabled = xnfcalloc (config->num_output, sizeof (Bool));
+    
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr output = config->output[o];
+	
+	modes[o] = NULL;
+	enabled[o] = (xf86OutputEnabled (output) &&
+		      output->status != XF86OutputStatusDisconnected);
+    }
+    
+    /*
+     * Let outputs with preferred modes drive screen size
+     */
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr output = config->output[o];
+
+	if (enabled[o] &&
+	    xf86OutputHasPreferredMode (output, width, height))
+	{
+	    target_mode = xf86DefaultMode (output, width, height);
+	    if (target_mode)
+	    {
+		modes[o] = target_mode;
+		config->compat_output = o;
+		break;
+	    }
+	}
+    }
+    if (!target_mode)
+    {
+	for (o = 0; o < config->num_output; o++)
+	{
+	    xf86OutputPtr output = config->output[o];
+	    if (enabled[o])
+	    {
+		target_mode = xf86DefaultMode (output, width, height);
+		if (target_mode)
+		{
+		    modes[o] = target_mode;
+		    config->compat_output = o;
+		    break;
+		}
+	    }
+	}
+    }
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr output = config->output[o];
+	
+	if (enabled[o] && !modes[o])
+	    modes[o] = xf86ClosestMode (output, target_mode, width, height);
+    }
+
+    /*
+     * Set the position of each output
+     */
+    if (!xf86InitialOutputPositions (scrn, modes))
+    {
+	xfree (crtcs);
+	xfree (modes);
+	return FALSE;
+    }
+	
+    /*
+     * Assign CRTCs to fit output configuration
+     */
+    if (!xf86PickCrtcs (scrn, crtcs, modes, 0, width, height))
+    {
+	xfree (crtcs);
+	xfree (modes);
+	return FALSE;
+    }
+    
+    /* XXX override xf86 common frame computation code */
+    
+    scrn->display->frameX0 = 0;
+    scrn->display->frameY0 = 0;
+    
+    for (c = 0; c < config->num_crtc; c++)
+    {
+	xf86CrtcPtr	crtc = config->crtc[c];
+
+	crtc->enabled = FALSE;
+	memset (&crtc->desiredMode, '\0', sizeof (crtc->desiredMode));
+    }
+    
+    /*
+     * Set initial configuration
+     */
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr	output = config->output[o];
+	DisplayModePtr	mode = modes[o];
+        xf86CrtcPtr	crtc = crtcs[o];
+
+	if (mode && crtc)
+	{
+	    crtc->desiredMode = *mode;
+	    crtc->enabled = TRUE;
+	    crtc->x = output->initial_x;
+	    crtc->y = output->initial_y;
+	    output->crtc = crtc;
+	}
+    }
+    
+    if (scrn->display->virtualX == 0)
+    {
+	/*
+	 * Expand virtual size to cover potential mode switches
+	 */
+	xf86DefaultScreenLimits (scrn, &width, &height);
+    
+	scrn->display->virtualX = width;
+	scrn->display->virtualY = height;
+    }
+
+    if (width > scrn->virtualX)
+	scrn->virtualX = width;
+    if (height > scrn->virtualY)
+	scrn->virtualY = height;
+    
+    /* Mirror output modes to scrn mode list */
+    xf86SetScrnInfoModes (scrn);
+    
+    xfree (crtcs);
+    xfree (modes);
+    return TRUE;
+}
+
+/**
+ * Set the DPMS power mode of all outputs and CRTCs.
+ *
+ * If the new mode is off, it will turn off outputs and then CRTCs.
+ * Otherwise, it will affect CRTCs before outputs.
+ */
+void
+xf86DPMSSet(ScrnInfoPtr scrn, int mode, int flags)
+{
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			i;
+
+    if (!scrn->vtSema)
+	return;
+
+    if (mode == DPMSModeOff) {
+	for (i = 0; i < config->num_output; i++) {
+	    xf86OutputPtr output = config->output[i];
+	    if (output->crtc != NULL)
+		(*output->funcs->dpms) (output, mode);
+	}
+    }
+
+    for (i = 0; i < config->num_crtc; i++) {
+	xf86CrtcPtr crtc = config->crtc[i];
+	if (crtc->enabled)
+	    (*crtc->funcs->dpms) (crtc, mode);
+    }
+
+    if (mode != DPMSModeOff) {
+	for (i = 0; i < config->num_output; i++) {
+	    xf86OutputPtr output = config->output[i];
+	    if (output->crtc != NULL)
+		(*output->funcs->dpms) (output, mode);
+	}
+    }
+}
+
+/**
+ * Implement the screensaver by just calling down into the driver DPMS hooks.
+ *
+ * Even for monitors with no DPMS support, by the definition of our DPMS hooks,
+ * the outputs will still get disabled (blanked).
+ */
+Bool
+xf86SaveScreen(ScreenPtr pScreen, int mode)
+{
+    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
+
+    if (xf86IsUnblank(mode))
+	xf86DPMSSet(pScrn, DPMSModeOn, 0);
+    else
+	xf86DPMSSet(pScrn, DPMSModeOff, 0);
+
+    return TRUE;
+}
+
+/**
+ * Disable all inactive crtcs and outputs
+ */
+void
+xf86DisableUnusedFunctions(ScrnInfoPtr pScrn)
+{
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
+    int			o, c;
+
+    for (o = 0; o < xf86_config->num_output; o++) 
+    {
+	xf86OutputPtr  output = xf86_config->output[o];
+	if (!output->crtc) 
+	    (*output->funcs->dpms)(output, DPMSModeOff);
+    }
+
+    for (c = 0; c < xf86_config->num_crtc; c++) 
+    {
+	xf86CrtcPtr crtc = xf86_config->crtc[c];
+
+	if (!crtc->enabled) 
+	{
+	    crtc->funcs->dpms(crtc, DPMSModeOff);
+	    memset(&crtc->mode, 0, sizeof(crtc->mode));
+	}
+    }
+}
+
+#ifdef RANDR_12_INTERFACE
+
+#define EDID_ATOM_NAME		"EDID_DATA"
+
+/**
+ * Set the RandR EDID property
+ */
+static void
+xf86OutputSetEDIDProperty (xf86OutputPtr output, void *data, int data_len)
+{
+    Atom edid_atom = MakeAtom(EDID_ATOM_NAME, sizeof(EDID_ATOM_NAME), TRUE);
+
+    /* This may get called before the RandR resources have been created */
+    if (output->randr_output == NULL)
+	return;
+
+    if (data_len != 0) {
+	RRChangeOutputProperty(output->randr_output, edid_atom, XA_INTEGER, 8,
+			       PropModeReplace, data_len, data, FALSE);
+    } else {
+	RRDeleteOutputProperty(output->randr_output, edid_atom);
+    }
+}
+
+#endif
+
+/**
+ * Set the EDID information for the specified output
+ */
+void
+xf86OutputSetEDID (xf86OutputPtr output, xf86MonPtr edid_mon)
+{
+    ScrnInfoPtr		scrn = output->scrn;
+    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(scrn);
+    int			i;
+#ifdef RANDR_12_INTERFACE
+    int			size;
+#endif
+    
+    if (output->MonInfo != NULL)
+	xfree(output->MonInfo);
+    
+    output->MonInfo = edid_mon;
+
+    /* Debug info for now, at least */
+    xf86DrvMsg(scrn->scrnIndex, X_INFO, "EDID for output %s\n", output->name);
+    xf86PrintEDID(edid_mon);
+    
+    /* Set the DDC properties for the 'compat' output */
+    if (output == config->output[config->compat_output])
+        xf86SetDDCproperties(scrn, edid_mon);
+
+#ifdef RANDR_12_INTERFACE
+    /* Set the RandR output properties */
+    size = 0;
+    if (edid_mon)
+    {
+	if (edid_mon->ver.version == 1)
+	    size = 128;
+	else if (edid_mon->ver.version == 2)
+	    size = 256;
+    }
+    xf86OutputSetEDIDProperty (output, edid_mon ? edid_mon->rawData : NULL, size);
+#endif
+
+    if (edid_mon)
+    {
+	/* Pull out a phyiscal size from a detailed timing if available. */
+	for (i = 0; i < 4; i++) {
+	    if (edid_mon->det_mon[i].type == DT &&
+		edid_mon->det_mon[i].section.d_timings.h_size != 0 &&
+		edid_mon->det_mon[i].section.d_timings.v_size != 0)
+	    {
+		output->mm_width = edid_mon->det_mon[i].section.d_timings.h_size;
+		output->mm_height = edid_mon->det_mon[i].section.d_timings.v_size;
+		break;
+	    }
+	}
+    
+	/* if no mm size is available from a detailed timing, check the max size field */
+	if ((!output->mm_width || !output->mm_height) &&
+	    (edid_mon->features.hsize && edid_mon->features.vsize))
+	{
+	    output->mm_width = edid_mon->features.hsize * 10;
+	    output->mm_height = edid_mon->features.vsize * 10;
+	}
+    }
+}
+
+/**
+ * Return the list of modes supported by the EDID information
+ * stored in 'output'
+ */
+DisplayModePtr
+xf86OutputGetEDIDModes (xf86OutputPtr output)
+{
+    ScrnInfoPtr	scrn = output->scrn;
+    xf86MonPtr	edid_mon = output->MonInfo;
+
+    if (!edid_mon)
+	return NULL;
+    return xf86DDCGetModes(scrn->scrnIndex, edid_mon);
+}
+
+xf86MonPtr
+xf86OutputGetEDID (xf86OutputPtr output, I2CBusPtr pDDCBus)
+{
+    ScrnInfoPtr	scrn = output->scrn;
+
+    return xf86DoEDID_DDC2 (scrn->scrnIndex, pDDCBus);
+}
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
new file mode 100644
index 0000000..49f4965
--- /dev/null
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -0,0 +1,555 @@
+/*
+ * Copyright © 2006 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 the copyright holders not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  The copyright holders make no representations
+ * about the suitability of this software for any purpose.  It is provided "as
+ * is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS 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.
+ */
+#ifndef _XF86CRTC_H_
+#define _XF86CRTC_H_
+
+#include <edid.h>
+#include "randrstr.h"
+#if XF86_MODES_RENAME
+#include "xf86Rename.h"
+#endif
+#include "xf86Modes.h"
+#include "xf86Parser.h"
+#include "damage.h"
+
+/* Compat definitions for older X Servers. */
+#ifndef M_T_PREFERRED
+#define M_T_PREFERRED	0x08
+#endif
+#ifndef M_T_DRIVER
+#define M_T_DRIVER	0x40
+#endif
+
+typedef struct _xf86Crtc xf86CrtcRec, *xf86CrtcPtr;
+typedef struct _xf86Output xf86OutputRec, *xf86OutputPtr;
+
+typedef enum _xf86OutputStatus {
+   XF86OutputStatusConnected,
+   XF86OutputStatusDisconnected,
+   XF86OutputStatusUnknown,
+} xf86OutputStatus;
+
+typedef struct _xf86CrtcFuncs {
+   /**
+    * Turns the crtc on/off, or sets intermediate power levels if available.
+    *
+    * Unsupported intermediate modes drop to the lower power setting.  If the
+    * mode is DPMSModeOff, the crtc must be disabled sufficiently for it to
+    * be safe to call mode_set.
+    */
+   void
+    (*dpms)(xf86CrtcPtr		crtc,
+	    int		    	mode);
+
+   /**
+    * Saves the crtc's state for restoration on VT switch.
+    */
+   void
+    (*save)(xf86CrtcPtr		crtc);
+
+   /**
+    * Restore's the crtc's state at VT switch.
+    */
+   void
+    (*restore)(xf86CrtcPtr	crtc);
+
+    /**
+     * Lock CRTC prior to mode setting, mostly for DRI.
+     * Returns whether unlock is needed
+     */
+    Bool
+    (*lock) (xf86CrtcPtr crtc);
+    
+    /**
+     * Unlock CRTC after mode setting, mostly for DRI
+     */
+    void
+    (*unlock) (xf86CrtcPtr crtc);
+    
+    /**
+     * Callback to adjust the mode to be set in the CRTC.
+     *
+     * This allows a CRTC to adjust the clock or even the entire set of
+     * timings, which is used for panels with fixed timings or for
+     * buses with clock limitations.
+     */
+    Bool
+    (*mode_fixup)(xf86CrtcPtr crtc,
+		  DisplayModePtr mode,
+		  DisplayModePtr adjusted_mode);
+
+    /**
+     * Callback for setting up a video mode after fixups have been made.
+     */
+    void
+    (*mode_set)(xf86CrtcPtr crtc,
+		DisplayModePtr mode,
+		DisplayModePtr adjusted_mode,
+		int x, int y);
+
+    /* Set the color ramps for the CRTC to the given values. */
+    void
+    (*gamma_set)(xf86CrtcPtr crtc, CARD16 *red, CARD16 *green, CARD16 *blue,
+		 int size);
+
+    /**
+     * Create shadow pixmap for rotation support
+     */
+    PixmapPtr
+    (*shadow_create) (xf86CrtcPtr crtc, int width, int height);
+    
+    /**
+     * Destroy shadow pixmap
+     */
+    void
+    (*shadow_destroy) (xf86CrtcPtr crtc, PixmapPtr pPixmap);
+
+    /**
+     * Clean up driver-specific bits of the crtc
+     */
+    void
+    (*destroy) (xf86CrtcPtr	crtc);
+} xf86CrtcFuncsRec, *xf86CrtcFuncsPtr;
+
+struct _xf86Crtc {
+    /**
+     * Associated ScrnInfo
+     */
+    ScrnInfoPtr	    scrn;
+    
+    /**
+     * Active state of this CRTC
+     *
+     * Set when this CRTC is driving one or more outputs 
+     */
+    Bool	    enabled;
+    
+    /** Track whether cursor is within CRTC range  */
+    Bool	    cursorInRange;
+    
+    /** Track state of cursor associated with this CRTC */
+    Bool	    cursorShown;
+    
+    /**
+     * Active mode
+     *
+     * This reflects the mode as set in the CRTC currently
+     * It will be cleared when the VT is not active or
+     * during server startup
+     */
+    DisplayModeRec  mode;
+    Rotation	    rotation;
+    PixmapPtr	    rotatedPixmap;
+    /**
+     * Position on screen
+     *
+     * Locates this CRTC within the frame buffer
+     */
+    int		    x, y;
+    
+    /**
+     * Desired mode
+     *
+     * This is set to the requested mode, independent of
+     * whether the VT is active. In particular, it receives
+     * the startup configured mode and saves the active mode
+     * on VT switch.
+     */
+    DisplayModeRec  desiredMode;
+    Rotation	    desiredRotation;
+    int		    desiredX, desiredY;
+    
+    /** crtc-specific functions */
+    const xf86CrtcFuncsRec *funcs;
+
+    /**
+     * Driver private
+     *
+     * Holds driver-private information
+     */
+    void	    *driver_private;
+
+#ifdef RANDR_12_INTERFACE
+    /**
+     * RandR crtc
+     *
+     * When RandR 1.2 is available, this
+     * points at the associated crtc object
+     */
+    RRCrtcPtr	    randr_crtc;
+#else
+    void	    *randr_crtc;
+#endif
+};
+
+typedef struct _xf86OutputFuncs {
+    /**
+     * Called to allow the output a chance to create properties after the
+     * RandR objects have been created.
+     */
+    void
+    (*create_resources)(xf86OutputPtr output);
+
+    /**
+     * Turns the output on/off, or sets intermediate power levels if available.
+     *
+     * Unsupported intermediate modes drop to the lower power setting.  If the
+     * mode is DPMSModeOff, the output must be disabled, as the DPLL may be
+     * disabled afterwards.
+     */
+    void
+    (*dpms)(xf86OutputPtr	output,
+	    int			mode);
+
+    /**
+     * Saves the output's state for restoration on VT switch.
+     */
+    void
+    (*save)(xf86OutputPtr	output);
+
+    /**
+     * Restore's the output's state at VT switch.
+     */
+    void
+    (*restore)(xf86OutputPtr	output);
+
+    /**
+     * Callback for testing a video mode for a given output.
+     *
+     * This function should only check for cases where a mode can't be supported
+     * on the output specifically, and not represent generic CRTC limitations.
+     *
+     * \return MODE_OK if the mode is valid, or another MODE_* otherwise.
+     */
+    int
+    (*mode_valid)(xf86OutputPtr	    output,
+		  DisplayModePtr    pMode);
+
+    /**
+     * Callback to adjust the mode to be set in the CRTC.
+     *
+     * This allows an output to adjust the clock or even the entire set of
+     * timings, which is used for panels with fixed timings or for
+     * buses with clock limitations.
+     */
+    Bool
+    (*mode_fixup)(xf86OutputPtr output,
+		  DisplayModePtr mode,
+		  DisplayModePtr adjusted_mode);
+
+    /**
+     * Callback for setting up a video mode after fixups have been made.
+     *
+     * This is only called while the output is disabled.  The dpms callback
+     * must be all that's necessary for the output, to turn the output on
+     * after this function is called.
+     */
+    void
+    (*mode_set)(xf86OutputPtr  output,
+		DisplayModePtr mode,
+		DisplayModePtr adjusted_mode);
+
+    /**
+     * Probe for a connected output, and return detect_status.
+     */
+    xf86OutputStatus
+    (*detect)(xf86OutputPtr	    output);
+
+    /**
+     * Query the device for the modes it provides.
+     *
+     * This function may also update MonInfo, mm_width, and mm_height.
+     *
+     * \return singly-linked list of modes or NULL if no modes found.
+     */
+    DisplayModePtr
+    (*get_modes)(xf86OutputPtr	    output);
+
+#ifdef RANDR_12_INTERFACE
+    /**
+     * Callback when an output's property has changed.
+     */
+    Bool
+    (*set_property)(xf86OutputPtr output,
+		    Atom property,
+		    RRPropertyValuePtr value);
+#endif
+    /**
+     * Clean up driver-specific bits of the output
+     */
+    void
+    (*destroy) (xf86OutputPtr	    output);
+} xf86OutputFuncsRec, *xf86OutputFuncsPtr;
+
+struct _xf86Output {
+    /**
+     * Associated ScrnInfo
+     */
+    ScrnInfoPtr		scrn;
+
+    /**
+     * Currently connected crtc (if any)
+     *
+     * If this output is not in use, this field will be NULL.
+     */
+    xf86CrtcPtr		crtc;
+
+    /**
+     * Possible CRTCs for this output as a mask of crtc indices
+     */
+    CARD32		possible_crtcs;
+
+    /**
+     * Possible outputs to share the same CRTC as a mask of output indices
+     */
+    CARD32		possible_clones;
+    
+    /**
+     * Whether this output can support interlaced modes
+     */
+    Bool		interlaceAllowed;
+
+    /**
+     * Whether this output can support double scan modes
+     */
+    Bool		doubleScanAllowed;
+
+    /**
+     * List of available modes on this output.
+     *
+     * This should be the list from get_modes(), plus perhaps additional
+     * compatible modes added later.
+     */
+    DisplayModePtr	probed_modes;
+
+    /**
+     * Options parsed from the related monitor section
+     */
+    OptionInfoPtr	options;
+    
+    /**
+     * Configured monitor section
+     */
+    XF86ConfMonitorPtr  conf_monitor;
+    
+    /**
+     * Desired initial position
+     */
+    int			initial_x, initial_y;
+
+    /**
+     * Current connection status
+     *
+     * This indicates whether a monitor is known to be connected
+     * to this output or not, or whether there is no way to tell
+     */
+    xf86OutputStatus	status;
+
+    /** EDID monitor information */
+    xf86MonPtr		MonInfo;
+
+    /** subpixel order */
+    int			subpixel_order;
+
+    /** Physical size of the currently attached output device. */
+    int			mm_width, mm_height;
+
+    /** Output name */
+    char		*name;
+
+    /** output-specific functions */
+    const xf86OutputFuncsRec *funcs;
+
+    /** driver private information */
+    void		*driver_private;
+    
+#ifdef RANDR_12_INTERFACE
+    /**
+     * RandR 1.2 output structure.
+     *
+     * When RandR 1.2 is available, this points at the associated
+     * RandR output structure and is created when this output is created
+     */
+    RROutputPtr		randr_output;
+#else
+    void		*randr_output;
+#endif
+};
+
+typedef struct _xf86CrtcConfig {
+    int			num_output;
+    xf86OutputPtr	*output;
+    /**
+     * compat_output is used whenever we deal
+     * with legacy code that only understands a single
+     * output. pScrn->modes will be loaded from this output,
+     * adjust frame will whack this output, etc.
+     */
+    int			compat_output;
+
+    int			num_crtc;
+    xf86CrtcPtr		*crtc;
+
+    int			minWidth, minHeight;
+    int			maxWidth, maxHeight;
+    
+    /* For crtc-based rotation */
+    DamagePtr   rotationDamage;
+
+    /* DGA */
+    unsigned int	dga_flags;
+    unsigned long	dga_address;
+    DGAModePtr		dga_modes;
+    int			dga_nmode;
+    int			dga_width, dga_height, dga_stride;
+    DisplayModePtr	dga_save_mode;
+
+} xf86CrtcConfigRec, *xf86CrtcConfigPtr;
+
+extern int xf86CrtcConfigPrivateIndex;
+
+#define XF86_CRTC_CONFIG_PTR(p)	((xf86CrtcConfigPtr) ((p)->privates[xf86CrtcConfigPrivateIndex].ptr))
+
+/*
+ * Initialize xf86CrtcConfig structure
+ */
+
+void
+xf86CrtcConfigInit (ScrnInfoPtr		scrn);
+
+void
+xf86CrtcSetSizeRange (ScrnInfoPtr scrn,
+		      int minWidth, int minHeight,
+		      int maxWidth, int maxHeight);
+
+/*
+ * Crtc functions
+ */
+xf86CrtcPtr
+xf86CrtcCreate (ScrnInfoPtr		scrn,
+		const xf86CrtcFuncsRec	*funcs);
+
+void
+xf86CrtcDestroy (xf86CrtcPtr		crtc);
+
+
+/**
+ * Allocate a crtc for the specified output
+ *
+ * Find a currently unused CRTC which is suitable for
+ * the specified output
+ */
+
+xf86CrtcPtr 
+xf86AllocCrtc (xf86OutputPtr		output);
+
+/**
+ * Free a crtc
+ *
+ * Mark the crtc as unused by any outputs
+ */
+
+void
+xf86FreeCrtc (xf86CrtcPtr		crtc);
+
+/**
+ * Sets the given video mode on the given crtc
+ */
+Bool
+xf86CrtcSetMode (xf86CrtcPtr crtc, DisplayModePtr mode, Rotation rotation,
+		 int x, int y);
+
+/*
+ * Assign crtc rotation during mode set
+ */
+Bool
+xf86CrtcRotate (xf86CrtcPtr crtc, DisplayModePtr mode, Rotation rotation);
+
+/**
+ * Return whether any output is assigned to the crtc
+ */
+Bool
+xf86CrtcInUse (xf86CrtcPtr crtc);
+
+/*
+ * Output functions
+ */
+xf86OutputPtr
+xf86OutputCreate (ScrnInfoPtr		scrn,
+		      const xf86OutputFuncsRec *funcs,
+		      const char	*name);
+
+Bool
+xf86OutputRename (xf86OutputPtr output, const char *name);
+
+void
+xf86OutputDestroy (xf86OutputPtr	output);
+
+void
+xf86ProbeOutputModes (ScrnInfoPtr pScrn, int maxX, int maxY);
+
+void
+xf86SetScrnInfoModes (ScrnInfoPtr pScrn);
+
+Bool
+xf86InitialConfiguration (ScrnInfoPtr pScrn);
+
+void
+xf86DPMSSet(ScrnInfoPtr pScrn, int PowerManagementMode, int flags);
+    
+Bool
+xf86SaveScreen(ScreenPtr pScreen, int mode);
+
+void
+xf86DisableUnusedFunctions(ScrnInfoPtr pScrn);
+
+/**
+ * Set the EDID information for the specified output
+ */
+void
+xf86OutputSetEDID (xf86OutputPtr output, xf86MonPtr edid_mon);
+
+/**
+ * Return the list of modes supported by the EDID information
+ * stored in 'output'
+ */
+DisplayModePtr
+xf86OutputGetEDIDModes (xf86OutputPtr output);
+
+xf86MonPtr
+xf86OutputGetEDID (xf86OutputPtr output, I2CBusPtr pDDCBus);
+
+/**
+ * Initialize dga for this screen
+ */
+
+Bool
+xf86DiDGAInit (ScreenPtr pScreen, unsigned long dga_address);
+
+/**
+ * Re-initialize dga for this screen (as when the set of modes changes)
+ */
+
+Bool
+xf86DiDGAReInit (ScreenPtr pScreen);
+
+#endif /* _XF86CRTC_H_ */
diff --git a/hw/xfree86/modes/xf86DiDGA.c b/hw/xfree86/modes/xf86DiDGA.c
new file mode 100644
index 0000000..f4ac4de
--- /dev/null
+++ b/hw/xfree86/modes/xf86DiDGA.c
@@ -0,0 +1,280 @@
+/*
+ * Copyright © 2006 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 the copyright holders not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  The copyright holders make no representations
+ * about the suitability of this software for any purpose.  It is provided "as
+ * is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS 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_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#include "xf86.h"
+#include "xf86DDC.h"
+#include "xf86_OSproc.h"
+#include "dgaproc.h"
+#include "xf86Crtc.h"
+#include "xf86Modes.h"
+#include "gcstruct.h"
+
+static Bool
+xf86_dga_get_modes (ScreenPtr pScreen)
+{
+    ScrnInfoPtr		scrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    DGAModePtr		modes, mode;
+    DisplayModePtr	display_mode;
+    int			bpp = scrn->bitsPerPixel >> 3;
+    int			num;
+
+    num = 0;
+    display_mode = scrn->modes;
+    while (display_mode) 
+    {
+	num++;
+	display_mode = display_mode->next;
+	if (display_mode == scrn->modes)
+	    break;
+    }
+    
+    if (!num)
+	return FALSE;
+    
+    modes = xalloc(num * sizeof(DGAModeRec));
+    if (!modes)
+	return FALSE;
+    
+    num = 0;
+    display_mode = scrn->modes;
+    while (display_mode) 
+    {
+	mode = modes + num++;
+
+	mode->mode = display_mode;
+	mode->flags = DGA_CONCURRENT_ACCESS | DGA_PIXMAP_AVAILABLE;
+        mode->flags |= DGA_FILL_RECT | DGA_BLIT_RECT;
+	if (display_mode->Flags & V_DBLSCAN)
+	    mode->flags |= DGA_DOUBLESCAN;
+	if (display_mode->Flags & V_INTERLACE)
+	    mode->flags |= DGA_INTERLACED;
+	mode->byteOrder = scrn->imageByteOrder;
+	mode->depth = scrn->depth;
+	mode->bitsPerPixel = scrn->bitsPerPixel;
+	mode->red_mask = scrn->mask.red;
+	mode->green_mask = scrn->mask.green;
+	mode->blue_mask = scrn->mask.blue;
+	mode->visualClass = (bpp == 1) ? PseudoColor : TrueColor;
+	mode->viewportWidth = display_mode->HDisplay;
+	mode->viewportHeight = display_mode->VDisplay;
+	mode->xViewportStep = (bpp == 3) ? 2 : 1;
+	mode->yViewportStep = 1;
+	mode->viewportFlags = DGA_FLIP_RETRACE;
+	mode->offset = 0;
+	mode->address = (unsigned char *) xf86_config->dga_address;
+	mode->bytesPerScanline = xf86_config->dga_stride;
+	mode->imageWidth = xf86_config->dga_width;
+	mode->imageHeight = xf86_config->dga_height;
+	mode->pixmapWidth = mode->imageWidth;
+	mode->pixmapHeight = mode->imageHeight;
+	mode->maxViewportX = mode->imageWidth -	mode->viewportWidth;
+	mode->maxViewportY = mode->imageHeight - mode->viewportHeight;
+
+	display_mode = display_mode->next;
+	if (display_mode == scrn->modes)
+	    break;
+    }
+    if (xf86_config->dga_modes)
+	xfree (xf86_config->dga_modes);
+    xf86_config->dga_nmode = num;
+    xf86_config->dga_modes = modes;
+    return TRUE;
+}
+
+static Bool
+xf86_dga_set_mode(ScrnInfoPtr scrn, DGAModePtr display_mode)
+{
+    ScreenPtr		pScreen = scrn->pScreen;
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+
+    if (!display_mode) 
+    {
+	if (xf86_config->dga_save_mode)
+	{
+	    xf86SwitchMode(pScreen, xf86_config->dga_save_mode);
+	    xf86_config->dga_save_mode = NULL;
+	}
+    }
+    else
+    {
+	if (!xf86_config->dga_save_mode)
+	{
+	    xf86_config->dga_save_mode = scrn->currentMode;
+	    xf86SwitchMode(pScreen, display_mode->mode);
+	}
+    }
+    return TRUE;
+}
+
+static int
+xf86_dga_get_viewport(ScrnInfoPtr scrn)
+{
+    return 0;
+}
+
+static void
+xf86_dga_set_viewport(ScrnInfoPtr scrn, int x, int y, int flags)
+{
+   scrn->AdjustFrame(scrn->pScreen->myNum, x, y, flags);
+}
+
+static Bool
+xf86_dga_get_drawable_and_gc (ScrnInfoPtr scrn, DrawablePtr *ppDrawable, GCPtr *ppGC)
+{
+    ScreenPtr		pScreen = scrn->pScreen;
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    PixmapPtr		pPixmap;
+    GCPtr		pGC;
+    
+    pPixmap = GetScratchPixmapHeader (pScreen, xf86_config->dga_width, xf86_config->dga_height,
+				      scrn->depth, scrn->bitsPerPixel, xf86_config->dga_stride, 
+				      (char *) scrn->memPhysBase + scrn->fbOffset);
+    if (!pPixmap)
+	return FALSE;
+    pGC  = GetScratchGC (scrn->depth, pScreen);
+    if (!pGC)
+    {
+	FreeScratchPixmapHeader (pPixmap);
+	return FALSE;
+    }
+    *ppDrawable = &pPixmap->drawable;
+    *ppGC = pGC;
+    return TRUE;
+}
+
+static void
+xf86_dga_release_drawable_and_gc (ScrnInfoPtr scrn, DrawablePtr pDrawable, GCPtr pGC)
+{
+    FreeScratchGC (pGC);
+    FreeScratchPixmapHeader ((PixmapPtr) pDrawable);
+}
+
+static void
+xf86_dga_fill_rect(ScrnInfoPtr scrn, int x, int y, int w, int h, unsigned long color)
+{
+    GCPtr		pGC;
+    DrawablePtr		pDrawable;
+    XID			vals[1];
+    xRectangle		r;
+
+    if (!xf86_dga_get_drawable_and_gc (scrn, &pDrawable, &pGC))
+	return;
+    vals[0] = color;
+    ChangeGC (pGC, GCForeground, vals);
+    ValidateGC (pDrawable, pGC);
+    r.x = x;
+    r.y = y;
+    r.width = w;
+    r.height = h;
+    pGC->ops->PolyFillRect (pDrawable, pGC, 1, &r);
+    xf86_dga_release_drawable_and_gc (scrn, pDrawable, pGC);
+}
+
+static void
+xf86_dga_sync(ScrnInfoPtr scrn)
+{
+    ScreenPtr	pScreen = scrn->pScreen;
+    WindowPtr	pRoot = WindowTable [pScreen->myNum];
+    char	buffer[4];
+
+    pScreen->GetImage (&pRoot->drawable, 0, 0, 1, 1, ZPixmap, ~0L, buffer);
+}
+
+static void
+xf86_dga_blit_rect(ScrnInfoPtr scrn, int srcx, int srcy, int w, int h, int dstx, int dsty)
+{
+    DrawablePtr	pDrawable;
+    GCPtr	pGC;
+
+    if (!xf86_dga_get_drawable_and_gc (scrn, &pDrawable, &pGC))
+	return;
+    ValidateGC (pDrawable, pGC);
+    pGC->ops->CopyArea (pDrawable, pDrawable, pGC, srcx, srcy, w, h, dstx, dsty);
+    xf86_dga_release_drawable_and_gc (scrn, pDrawable, pGC);
+}
+
+static Bool
+xf86_dga_open_framebuffer(ScrnInfoPtr scrn,
+			  char **name,
+			  unsigned char **mem, int *size, int *offset, int *flags)
+{
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    
+    *size = xf86_config->dga_stride * xf86_config->dga_height;
+    *mem = (unsigned char *) (xf86_config->dga_address);
+    *offset = 0;
+    *flags = DGA_NEED_ROOT;
+
+    return TRUE;
+}
+
+static void
+xf86_dga_close_framebuffer(ScrnInfoPtr scrn)
+{
+}
+
+static DGAFunctionRec xf86_dga_funcs = {
+   xf86_dga_open_framebuffer,
+   xf86_dga_close_framebuffer,
+   xf86_dga_set_mode,
+   xf86_dga_set_viewport,
+   xf86_dga_get_viewport,
+   xf86_dga_sync,
+   xf86_dga_fill_rect,
+   xf86_dga_blit_rect,
+   NULL
+};
+
+Bool
+xf86DiDGAReInit (ScreenPtr pScreen)
+{
+    ScrnInfoPtr		scrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+    
+    if (!xf86_dga_get_modes (pScreen))
+	return FALSE;
+    
+    return DGAReInitModes (pScreen, xf86_config->dga_modes, xf86_config->dga_nmode);
+}
+
+Bool
+xf86DiDGAInit (ScreenPtr pScreen, unsigned long dga_address)
+{
+    ScrnInfoPtr		scrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
+
+    xf86_config->dga_flags = 0;
+    xf86_config->dga_address = dga_address;
+    xf86_config->dga_width = scrn->virtualX;
+    xf86_config->dga_height = scrn->virtualY;
+    xf86_config->dga_stride = scrn->displayWidth * scrn->bitsPerPixel >> 3;
+    
+    if (!xf86_dga_get_modes (pScreen))
+	return FALSE;
+    
+    return DGAInit(pScreen, &xf86_dga_funcs, xf86_config->dga_modes, xf86_config->dga_nmode);
+}
diff --git a/hw/xfree86/modes/xf86EdidModes.c b/hw/xfree86/modes/xf86EdidModes.c
new file mode 100644
index 0000000..0476a68
--- /dev/null
+++ b/hw/xfree86/modes/xf86EdidModes.c
@@ -0,0 +1,339 @@
+/*
+ * Copyright 2006 Luc Verhaegen.
+ *
+ * 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 This is a copy of edid_modes.c from the X Server, for compatibility
+ * with old X Servers.
+ */
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#include "xf86.h"
+#include "xf86DDC.h"
+#include <X11/Xatom.h>
+#include "property.h"
+#include "propertyst.h"
+#include "xf86DDC.h"
+#include "xf86Crtc.h"
+#include <string.h>
+#include <math.h>
+
+/*
+ * Quirks to work around broken EDID data from various monitors.
+ */
+
+typedef enum {
+    DDC_QUIRK_NONE = 0,
+    /* Force detailed sync polarity to -h +v */
+    DDC_QUIRK_DT_SYNC_HM_VP = 1 << 0,
+    /* First detailed mode is bogus, prefer largest mode at 60hz */
+    DDC_QUIRK_PREFER_LARGE_60 = 1 << 1,
+    /* 135MHz clock is too high, drop a bit */
+    DDC_QUIRK_135_CLOCK_TOO_HIGH = 1 << 2
+} ddc_quirk_t;
+
+static Bool quirk_dt_sync_hm_vp (int scrnIndex, xf86MonPtr DDC)
+{
+    /* Belinea 1924S1W */
+    if (memcmp (DDC->vendor.name, "MAX", 4) == 0 &&
+	DDC->vendor.prod_id == 1932)
+	return TRUE;
+    /* Belinea 10 20 30W */
+    if (memcmp (DDC->vendor.name, "MAX", 4) == 0 &&
+	DDC->vendor.prod_id == 2007)
+	return TRUE;
+    /* ViewSonic VX2025wm (bug #9941) */
+    if (memcmp (DDC->vendor.name, "VSC", 4) == 0 &&
+	DDC->vendor.prod_id == 58653)
+	return TRUE;
+
+    return FALSE;
+}
+
+static Bool quirk_prefer_large_60 (int scrnIndex, xf86MonPtr DDC)
+{
+    /* Belinea 10 15 55 */
+    if (memcmp (DDC->vendor.name, "MAX", 4) == 0 &&
+	DDC->vendor.prod_id == 1516)
+	return TRUE;
+    
+    return FALSE;
+}
+
+static Bool quirk_135_clock_too_high (int scrnIndex, xf86MonPtr DDC)
+{
+    /* Envision Peripherals, Inc. EN-7100e.  See bug #9550. */
+    if (memcmp (DDC->vendor.name, "EPI", 4) == 0 &&
+	DDC->vendor.prod_id == 59264)
+	return TRUE;
+    
+    return FALSE;
+}
+
+typedef struct {
+    Bool	(*detect) (int scrnIndex, xf86MonPtr DDC);
+    ddc_quirk_t	quirk;
+    char	*description;
+} ddc_quirk_map_t;
+
+static const ddc_quirk_map_t ddc_quirks[] = {
+    { 
+	quirk_dt_sync_hm_vp,	DDC_QUIRK_DT_SYNC_HM_VP,
+	"Set detailed timing sync polarity to -h +v"
+    },
+    {
+	quirk_prefer_large_60,   DDC_QUIRK_PREFER_LARGE_60,
+	"Detailed timing is not preferred, use largest mode at 60Hz"
+    },
+    {
+	quirk_135_clock_too_high,   DDC_QUIRK_135_CLOCK_TOO_HIGH,
+	"Recommended 135MHz pixel clock is too high"
+    },
+    { 
+	NULL,		DDC_QUIRK_NONE,
+	"No known quirks"
+    },
+};
+
+/*
+ * TODO:
+ *  - for those with access to the VESA DMT standard; review please.
+ */
+#define MODEPREFIX(name) NULL, NULL, name, 0,M_T_DRIVER
+#define MODESUFFIX   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,FALSE,FALSE,0,NULL,0,0.0,0.0
+
+static DisplayModeRec DDCEstablishedModes[17] = {
+    { MODEPREFIX("800x600"),    40000,  800,  840,  968, 1056, 0,  600,  601,  605,  628, 0, V_PHSYNC | V_PVSYNC, MODESUFFIX }, /* 800x600 at 60Hz */
+    { MODEPREFIX("800x600"),    36000,  800,  824,  896, 1024, 0,  600,  601,  603,  625, 0, V_PHSYNC | V_PVSYNC, MODESUFFIX }, /* 800x600 at 56Hz */
+    { MODEPREFIX("640x480"),    31500,  640,  656,  720,  840, 0,  480,  481,  484,  500, 0, V_NHSYNC | V_NVSYNC, MODESUFFIX }, /* 640x480 at 75Hz */
+    { MODEPREFIX("640x480"),    31500,  640,  664,  704,  832, 0,  480,  489,  491,  520, 0, V_NHSYNC | V_NVSYNC, MODESUFFIX }, /* 640x480 at 72Hz */
+    { MODEPREFIX("640x480"),    30240,  640,  704,  768,  864, 0,  480,  483,  486,  525, 0, V_NHSYNC | V_NVSYNC, MODESUFFIX }, /* 640x480 at 67Hz */
+    { MODEPREFIX("640x480"),    25200,  640,  656,  752,  800, 0,  480,  490,  492,  525, 0, V_NHSYNC | V_NVSYNC, MODESUFFIX }, /* 640x480 at 60Hz */
+    { MODEPREFIX("720x400"),    35500,  720,  738,  846,  900, 0,  400,  421,  423,  449, 0, V_NHSYNC | V_NVSYNC, MODESUFFIX }, /* 720x400 at 88Hz */
+    { MODEPREFIX("720x400"),    28320,  720,  738,  846,  900, 0,  400,  412,  414,  449, 0, V_NHSYNC | V_PVSYNC, MODESUFFIX }, /* 720x400 at 70Hz */
+    { MODEPREFIX("1280x1024"), 135000, 1280, 1296, 1440, 1688, 0, 1024, 1025, 1028, 1066, 0, V_PHSYNC | V_PVSYNC, MODESUFFIX }, /* 1280x1024 at 75Hz */
+    { MODEPREFIX("1024x768"),   78800, 1024, 1040, 1136, 1312, 0,  768,  769,  772,  800, 0, V_PHSYNC | V_PVSYNC, MODESUFFIX }, /* 1024x768 at 75Hz */
+    { MODEPREFIX("1024x768"),   75000, 1024, 1048, 1184, 1328, 0,  768,  771,  777,  806, 0, V_NHSYNC | V_NVSYNC, MODESUFFIX }, /* 1024x768 at 70Hz */
+    { MODEPREFIX("1024x768"),   65000, 1024, 1048, 1184, 1344, 0,  768,  771,  777,  806, 0, V_NHSYNC | V_NVSYNC, MODESUFFIX }, /* 1024x768 at 60Hz */
+    { MODEPREFIX("1024x768"),   44900, 1024, 1032, 1208, 1264, 0,  768,  768,  776,  817, 0, V_PHSYNC | V_PVSYNC | V_INTERLACE, MODESUFFIX }, /* 1024x768 at 43Hz */
+    { MODEPREFIX("832x624"),    57284,  832,  864,  928, 1152, 0,  624,  625,  628,  667, 0, V_NHSYNC | V_NVSYNC, MODESUFFIX }, /* 832x624 at 75Hz */
+    { MODEPREFIX("800x600"),    49500,  800,  816,  896, 1056, 0,  600,  601,  604,  625, 0, V_PHSYNC | V_PVSYNC, MODESUFFIX }, /* 800x600 at 75Hz */
+    { MODEPREFIX("800x600"),    50000,  800,  856,  976, 1040, 0,  600,  637,  643,  666, 0, V_PHSYNC | V_PVSYNC, MODESUFFIX }, /* 800x600 at 72Hz */
+    { MODEPREFIX("1152x864"),  108000, 1152, 1216, 1344, 1600, 0,  864,  865,  868,  900, 0, V_PHSYNC | V_PVSYNC, MODESUFFIX }, /* 1152x864 at 75Hz */
+};
+
+static DisplayModePtr
+DDCModesFromEstablished(int scrnIndex, struct established_timings *timing,
+			ddc_quirk_t quirks)
+{
+    DisplayModePtr Modes = NULL, Mode = NULL;
+    CARD32 bits = (timing->t1) | (timing->t2 << 8) |
+        ((timing->t_manu & 0x80) << 9);
+    int i;
+
+    for (i = 0; i < 17; i++) {
+        if (bits & (0x01 << i)) {
+            Mode = xf86DuplicateMode(&DDCEstablishedModes[i]);
+            Modes = xf86ModesAdd(Modes, Mode);
+        }
+    }
+
+    return Modes;
+}
+
+/*
+ *
+ */
+static DisplayModePtr
+DDCModesFromStandardTiming(int scrnIndex, struct std_timings *timing,
+			   ddc_quirk_t quirks)
+{
+    DisplayModePtr Modes = NULL, Mode = NULL;
+    int i;
+
+    for (i = 0; i < STD_TIMINGS; i++) {
+        if (timing[i].hsize && timing[i].vsize && timing[i].refresh) {
+            Mode =  xf86CVTMode(timing[i].hsize, timing[i].vsize,
+                                timing[i].refresh, FALSE, FALSE);
+	    Mode->type = M_T_DRIVER;
+            Modes = xf86ModesAdd(Modes, Mode);
+        }
+    }
+
+    return Modes;
+}
+
+/*
+ *
+ */
+static DisplayModePtr
+DDCModeFromDetailedTiming(int scrnIndex, struct detailed_timings *timing,
+			  int preferred, ddc_quirk_t quirks)
+{
+    DisplayModePtr Mode;
+
+    /* We don't do stereo */
+    if (timing->stereo) {
+        xf86DrvMsg(scrnIndex, X_INFO,
+		   "%s: Ignoring: We don't handle stereo.\n", __func__);
+        return NULL;
+    }
+
+    /* We only do seperate sync currently */
+    if (timing->sync != 0x03) {
+         xf86DrvMsg(scrnIndex, X_INFO,
+		    "%s: %dx%d Warning: We only handle seperate"
+                    " sync.\n", __func__, timing->h_active, timing->v_active);
+    }
+
+    Mode = xnfalloc(sizeof(DisplayModeRec));
+    memset(Mode, 0, sizeof(DisplayModeRec));
+
+    Mode->type = M_T_DRIVER;
+    if (preferred)
+	Mode->type |= M_T_PREFERRED;
+
+    if( ( quirks & DDC_QUIRK_135_CLOCK_TOO_HIGH ) &&
+	timing->clock == 135000000 )
+        Mode->Clock = 108880;
+    else
+        Mode->Clock = timing->clock / 1000.0;
+
+    Mode->HDisplay = timing->h_active;
+    Mode->HSyncStart = timing->h_active + timing->h_sync_off;
+    Mode->HSyncEnd = Mode->HSyncStart + timing->h_sync_width;
+    Mode->HTotal = timing->h_active + timing->h_blanking;
+
+    Mode->VDisplay = timing->v_active;
+    Mode->VSyncStart = timing->v_active + timing->v_sync_off;
+    Mode->VSyncEnd = Mode->VSyncStart + timing->v_sync_width;
+    Mode->VTotal = timing->v_active + timing->v_blanking;
+
+    xf86SetModeDefaultName(Mode);
+
+    /* We ignore h/v_size and h/v_border for now. */
+
+    if (timing->interlaced)
+        Mode->Flags |= V_INTERLACE;
+
+    if (quirks & DDC_QUIRK_DT_SYNC_HM_VP)
+	Mode->Flags |= V_NHSYNC | V_PVSYNC;
+    else
+    {
+	if (timing->misc & 0x02)
+	    Mode->Flags |= V_PHSYNC;
+	else
+	    Mode->Flags |= V_NHSYNC;
+    
+	if (timing->misc & 0x01)
+	    Mode->Flags |= V_PVSYNC;
+	else
+	    Mode->Flags |= V_NVSYNC;
+    }
+
+    return Mode;
+}
+
+DisplayModePtr
+xf86DDCGetModes(int scrnIndex, xf86MonPtr DDC)
+{
+    int preferred, i;
+    DisplayModePtr  Modes = NULL, Mode;
+    ddc_quirk_t	    quirks;
+
+    xf86DrvMsg (scrnIndex, X_INFO, "EDID vendor \"%s\", prod id %d\n",
+		DDC->vendor.name, DDC->vendor.prod_id);
+    quirks = DDC_QUIRK_NONE;
+    for (i = 0; ddc_quirks[i].detect; i++)
+	if (ddc_quirks[i].detect (scrnIndex, DDC))
+	{
+	    xf86DrvMsg (scrnIndex, X_INFO, "    EDID quirk: %s\n",
+			ddc_quirks[i].description);
+	    quirks |= ddc_quirks[i].quirk;
+	}
+    
+    preferred = PREFERRED_TIMING_MODE(DDC->features.msc);
+    if (quirks & DDC_QUIRK_PREFER_LARGE_60)
+	preferred = 0;
+
+    for (i = 0; i < DET_TIMINGS; i++) {
+	struct detailed_monitor_section *det_mon = &DDC->det_mon[i];
+
+        switch (det_mon->type) {
+        case DT:
+            Mode = DDCModeFromDetailedTiming(scrnIndex,
+                                             &det_mon->section.d_timings,
+					     preferred,
+					     quirks);
+	    preferred = 0;
+            Modes = xf86ModesAdd(Modes, Mode);
+            break;
+        case DS_STD_TIMINGS:
+            Mode = DDCModesFromStandardTiming(scrnIndex,
+					      det_mon->section.std_t,
+					      quirks);
+            Modes = xf86ModesAdd(Modes, Mode);
+            break;
+        default:
+            break;
+        }
+    }
+
+    /* Add established timings */
+    Mode = DDCModesFromEstablished(scrnIndex, &DDC->timings1, quirks);
+    Modes = xf86ModesAdd(Modes, Mode);
+
+    /* Add standard timings */
+    Mode = DDCModesFromStandardTiming(scrnIndex, DDC->timings2, quirks);
+    Modes = xf86ModesAdd(Modes, Mode);
+
+    if (quirks & DDC_QUIRK_PREFER_LARGE_60)
+    {
+	DisplayModePtr	best = Modes;
+	for (Mode = Modes; Mode; Mode = Mode->next)
+	{
+	    if (Mode == best) continue;
+	    if (Mode->HDisplay * Mode->VDisplay > best->HDisplay * best->VDisplay)
+	    {
+		best = Mode;
+		continue;
+	    }
+	    if (Mode->HDisplay * Mode->VDisplay == best->HDisplay * best->VDisplay)
+	    {
+		double	mode_refresh = xf86ModeVRefresh (Mode);
+		double	best_refresh = xf86ModeVRefresh (best);
+		double	mode_dist = fabs(mode_refresh - 60.0);
+		double	best_dist = fabs(best_refresh - 60.0);
+		if (mode_dist < best_dist)
+		{
+		    best = Mode;
+		    continue;
+		}
+	    }
+	}
+	if (best)
+	    best->type |= M_T_PREFERRED;
+    }
+    return Modes;
+}
diff --git a/hw/xfree86/modes/xf86Modes.c b/hw/xfree86/modes/xf86Modes.c
new file mode 100644
index 0000000..d126e5e
--- /dev/null
+++ b/hw/xfree86/modes/xf86Modes.c
@@ -0,0 +1,635 @@
+/* -*- c-basic-offset: 4 -*- */
+/* $XdotOrg: xserver/xorg/hw/xfree86/common/xf86Mode.c,v 1.10 2006/03/07 16:00:57 libv Exp $ */
+/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Mode.c,v 1.69 2003/10/08 14:58:28 dawes Exp $ */
+/*
+ * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
+ *
+ * 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 COPYRIGHT HOLDER(S) OR AUTHOR(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.
+ *
+ * Except as contained in this notice, the name of the copyright holder(s)
+ * and author(s) shall not be used in advertising or otherwise to promote
+ * the sale, use or other dealings in this Software without prior written
+ * authorization from the copyright holder(s) and author(s).
+ */
+
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "xf86.h"
+#include "xf86Modes.h"
+#include "xf86Priv.h"
+
+extern XF86ConfigPtr xf86configptr;
+
+/**
+ * @file this file contains symbols from xf86Mode.c and friends that are static
+ * there but we still want to use.  We need to come up with better API here.
+ */
+
+#if XORG_VERSION_CURRENT <= XORG_VERSION_NUMERIC(7,2,99,2,0)
+/**
+ * Calculates the horizontal sync rate of a mode.
+ *
+ * Exact copy of xf86Mode.c's.
+ */
+double
+xf86ModeHSync(DisplayModePtr mode)
+{
+    double hsync = 0.0;
+    
+    if (mode->HSync > 0.0)
+	    hsync = mode->HSync;
+    else if (mode->HTotal > 0)
+	    hsync = (float)mode->Clock / (float)mode->HTotal;
+
+    return hsync;
+}
+
+/**
+ * Calculates the vertical refresh rate of a mode.
+ *
+ * Exact copy of xf86Mode.c's.
+ */
+double
+xf86ModeVRefresh(DisplayModePtr mode)
+{
+    double refresh = 0.0;
+
+    if (mode->VRefresh > 0.0)
+	refresh = mode->VRefresh;
+    else if (mode->HTotal > 0 && mode->VTotal > 0) {
+	refresh = mode->Clock * 1000.0 / mode->HTotal / mode->VTotal;
+	if (mode->Flags & V_INTERLACE)
+	    refresh *= 2.0;
+	if (mode->Flags & V_DBLSCAN)
+	    refresh /= 2.0;
+	if (mode->VScan > 1)
+	    refresh /= (float)(mode->VScan);
+    }
+    return refresh;
+}
+
+/** Sets a default mode name of <width>x<height> on a mode. */
+void
+xf86SetModeDefaultName(DisplayModePtr mode)
+{
+    if (mode->name != NULL)
+	xfree(mode->name);
+
+    mode->name = XNFprintf("%dx%d", mode->HDisplay, mode->VDisplay);
+}
+
+/*
+ * xf86SetModeCrtc
+ *
+ * Initialises the Crtc parameters for a mode.  The initialisation includes
+ * adjustments for interlaced and double scan modes.
+ *
+ * Exact copy of xf86Mode.c's.
+ */
+void
+xf86SetModeCrtc(DisplayModePtr p, int adjustFlags)
+{
+    if ((p == NULL) || ((p->type & M_T_CRTC_C) == M_T_BUILTIN))
+	return;
+
+    p->CrtcHDisplay             = p->HDisplay;
+    p->CrtcHSyncStart           = p->HSyncStart;
+    p->CrtcHSyncEnd             = p->HSyncEnd;
+    p->CrtcHTotal               = p->HTotal;
+    p->CrtcHSkew                = p->HSkew;
+    p->CrtcVDisplay             = p->VDisplay;
+    p->CrtcVSyncStart           = p->VSyncStart;
+    p->CrtcVSyncEnd             = p->VSyncEnd;
+    p->CrtcVTotal               = p->VTotal;
+    if (p->Flags & V_INTERLACE) {
+	if (adjustFlags & INTERLACE_HALVE_V) {
+	    p->CrtcVDisplay         /= 2;
+	    p->CrtcVSyncStart       /= 2;
+	    p->CrtcVSyncEnd         /= 2;
+	    p->CrtcVTotal           /= 2;
+	}
+	/* Force interlaced modes to have an odd VTotal */
+	/* maybe we should only do this when INTERLACE_HALVE_V is set? */
+	p->CrtcVTotal |= 1;
+    }
+
+    if (p->Flags & V_DBLSCAN) {
+        p->CrtcVDisplay         *= 2;
+        p->CrtcVSyncStart       *= 2;
+        p->CrtcVSyncEnd         *= 2;
+        p->CrtcVTotal           *= 2;
+    }
+    if (p->VScan > 1) {
+        p->CrtcVDisplay         *= p->VScan;
+        p->CrtcVSyncStart       *= p->VScan;
+        p->CrtcVSyncEnd         *= p->VScan;
+        p->CrtcVTotal           *= p->VScan;
+    }
+    p->CrtcVBlankStart = min(p->CrtcVSyncStart, p->CrtcVDisplay);
+    p->CrtcVBlankEnd = max(p->CrtcVSyncEnd, p->CrtcVTotal);
+    p->CrtcHBlankStart = min(p->CrtcHSyncStart, p->CrtcHDisplay);
+    p->CrtcHBlankEnd = max(p->CrtcHSyncEnd, p->CrtcHTotal);
+
+    p->CrtcHAdjusted = FALSE;
+    p->CrtcVAdjusted = FALSE;
+}
+
+/**
+ * Allocates and returns a copy of pMode, including pointers within pMode.
+ */
+DisplayModePtr
+xf86DuplicateMode(DisplayModePtr pMode)
+{
+    DisplayModePtr pNew;
+
+    pNew = xnfalloc(sizeof(DisplayModeRec));
+    *pNew = *pMode;
+    pNew->next = NULL;
+    pNew->prev = NULL;
+    if (pNew->name == NULL) {
+	xf86SetModeDefaultName(pMode);
+    } else {
+	pNew->name = xnfstrdup(pMode->name);
+    }
+
+    return pNew;
+}
+
+/**
+ * Duplicates every mode in the given list and returns a pointer to the first
+ * mode.
+ *
+ * \param modeList doubly-linked mode list
+ */
+DisplayModePtr
+xf86DuplicateModes(ScrnInfoPtr pScrn, DisplayModePtr modeList)
+{
+    DisplayModePtr first = NULL, last = NULL;
+    DisplayModePtr mode;
+
+    for (mode = modeList; mode != NULL; mode = mode->next) {
+	DisplayModePtr new;
+
+	new = xf86DuplicateMode(mode);
+
+	/* Insert pNew into modeList */
+	if (last) {
+	    last->next = new;
+	    new->prev = last;
+	} else {
+	    first = new;
+	    new->prev = NULL;
+	}
+	new->next = NULL;
+	last = new;
+    }
+
+    return first;
+}
+
+/**
+ * Returns true if the given modes should program to the same timings.
+ *
+ * This doesn't use Crtc values, as it might be used on ModeRecs without the
+ * Crtc values set.  So, it's assumed that the other numbers are enough.
+ *
+ * This isn't in xf86Modes.c, but it might deserve to be there.
+ */
+Bool
+xf86ModesEqual(DisplayModePtr pMode1, DisplayModePtr pMode2)
+{
+     if (pMode1->Clock == pMode2->Clock &&
+	 pMode1->HDisplay == pMode2->HDisplay &&
+	 pMode1->HSyncStart == pMode2->HSyncStart &&
+	 pMode1->HSyncEnd == pMode2->HSyncEnd &&
+	 pMode1->HTotal == pMode2->HTotal &&
+	 pMode1->HSkew == pMode2->HSkew &&
+	 pMode1->VDisplay == pMode2->VDisplay &&
+	 pMode1->VSyncStart == pMode2->VSyncStart &&
+	 pMode1->VSyncEnd == pMode2->VSyncEnd &&
+	 pMode1->VTotal == pMode2->VTotal &&
+	 pMode1->VScan == pMode2->VScan &&
+	 pMode1->Flags == pMode2->Flags)
+     {
+	return TRUE;
+     } else {
+	return FALSE;
+     }
+}
+
+/* exact copy of xf86Mode.c */
+static void
+add(char **p, char *new)
+{
+    *p = xnfrealloc(*p, strlen(*p) + strlen(new) + 2);
+    strcat(*p, " ");
+    strcat(*p, new);
+}
+
+/**
+ * Print out a modeline.
+ *
+ * Convenient VRefresh printing was added, though, compared to xf86Mode.c
+ */
+void
+xf86PrintModeline(int scrnIndex,DisplayModePtr mode)
+{
+    char tmp[256];
+    char *flags = xnfcalloc(1, 1);
+
+    if (mode->HSkew) { 
+	snprintf(tmp, 256, "hskew %i", mode->HSkew); 
+	add(&flags, tmp);
+    }
+    if (mode->VScan) { 
+	snprintf(tmp, 256, "vscan %i", mode->VScan); 
+	add(&flags, tmp);
+    }
+    if (mode->Flags & V_INTERLACE) add(&flags, "interlace");
+    if (mode->Flags & V_CSYNC) add(&flags, "composite");
+    if (mode->Flags & V_DBLSCAN) add(&flags, "doublescan");
+    if (mode->Flags & V_BCAST) add(&flags, "bcast");
+    if (mode->Flags & V_PHSYNC) add(&flags, "+hsync");
+    if (mode->Flags & V_NHSYNC) add(&flags, "-hsync");
+    if (mode->Flags & V_PVSYNC) add(&flags, "+vsync");
+    if (mode->Flags & V_NVSYNC) add(&flags, "-vsync");
+    if (mode->Flags & V_PCSYNC) add(&flags, "+csync");
+    if (mode->Flags & V_NCSYNC) add(&flags, "-csync");
+#if 0
+    if (mode->Flags & V_CLKDIV2) add(&flags, "vclk/2");
+#endif
+    xf86DrvMsg(scrnIndex, X_INFO,
+		   "Modeline \"%s\"x%.01f  %6.2f  %i %i %i %i  %i %i %i %i%s "
+		   "(%.01f kHz)\n",
+		   mode->name, mode->VRefresh, mode->Clock/1000., mode->HDisplay,
+		   mode->HSyncStart, mode->HSyncEnd, mode->HTotal,
+		   mode->VDisplay, mode->VSyncStart, mode->VSyncEnd,
+		   mode->VTotal, flags, xf86ModeHSync(mode));
+    xfree(flags);
+}
+#endif /* XORG_VERSION_CURRENT <= 7.2.99.2 */
+
+/**
+ * Marks as bad any modes with unsupported flags.
+ *
+ * \param modeList doubly-linked or circular list of modes.
+ * \param flags flags supported by the driver.
+ *
+ * \bug only V_INTERLACE and V_DBLSCAN are supported.  Is that enough?
+ *
+ * This is not in xf86Modes.c, but would be part of the proposed new API.
+ */
+void
+xf86ValidateModesFlags(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+			    int flags)
+{
+    DisplayModePtr mode;
+
+    for (mode = modeList; mode != NULL; mode = mode->next) {
+	if (mode->Flags & V_INTERLACE && !(flags & V_INTERLACE))
+	    mode->status = MODE_NO_INTERLACE;
+	if (mode->Flags & V_DBLSCAN && !(flags & V_DBLSCAN))
+	    mode->status = MODE_NO_DBLESCAN;
+    }
+}
+
+/**
+ * Marks as bad any modes extending beyond the given max X, Y, or pitch.
+ *
+ * \param modeList doubly-linked or circular list of modes.
+ *
+ * This is not in xf86Modes.c, but would be part of the proposed new API.
+ */
+void
+xf86ValidateModesSize(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+			  int maxX, int maxY, int maxPitch)
+{
+    DisplayModePtr mode;
+
+    for (mode = modeList; mode != NULL; mode = mode->next) {
+	if (maxPitch > 0 && mode->HDisplay > maxPitch)
+	    mode->status = MODE_BAD_WIDTH;
+
+	if (maxX > 0 && mode->HDisplay > maxX)
+	    mode->status = MODE_VIRTUAL_X;
+
+	if (maxY > 0 && mode->VDisplay > maxY)
+	    mode->status = MODE_VIRTUAL_Y;
+
+	if (mode->next == modeList)
+	    break;
+    }
+}
+
+/**
+ * Marks as bad any modes that aren't supported by the given monitor's
+ * hsync and vrefresh ranges.
+ *
+ * \param modeList doubly-linked or circular list of modes.
+ *
+ * This is not in xf86Modes.c, but would be part of the proposed new API.
+ */
+void
+xf86ValidateModesSync(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+			  MonPtr mon)
+{
+    DisplayModePtr mode;
+
+    for (mode = modeList; mode != NULL; mode = mode->next) {
+	Bool bad;
+	int i;
+
+	bad = TRUE;
+	for (i = 0; i < mon->nHsync; i++) {
+	    if (xf86ModeHSync(mode) >= mon->hsync[i].lo &&
+		xf86ModeHSync(mode) <= mon->hsync[i].hi)
+	    {
+		bad = FALSE;
+	    }
+	}
+	if (bad)
+	    mode->status = MODE_HSYNC;
+
+	bad = TRUE;
+	for (i = 0; i < mon->nVrefresh; i++) {
+	    if (xf86ModeVRefresh(mode) >= mon->vrefresh[i].lo &&
+		xf86ModeVRefresh(mode) <= mon->vrefresh[i].hi)
+	    {
+		bad = FALSE;
+	    }
+	}
+	if (bad)
+	    mode->status = MODE_VSYNC;
+
+	if (mode->next == modeList)
+	    break;
+    }
+}
+
+/**
+ * Marks as bad any modes extending beyond outside of the given clock ranges.
+ *
+ * \param modeList doubly-linked or circular list of modes.
+ * \param min pointer to minimums of clock ranges
+ * \param max pointer to maximums of clock ranges
+ * \param n_ranges number of ranges.
+ *
+ * This is not in xf86Modes.c, but would be part of the proposed new API.
+ */
+void
+xf86ValidateModesClocks(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+			    int *min, int *max, int n_ranges)
+{
+    DisplayModePtr mode;
+    int i;
+
+    for (mode = modeList; mode != NULL; mode = mode->next) {
+	Bool good = FALSE;
+	for (i = 0; i < n_ranges; i++) {
+	    if (mode->Clock >= min[i] && mode->Clock <= max[i]) {
+		good = TRUE;
+		break;
+	    }
+	}
+	if (!good)
+	    mode->status = MODE_CLOCK_RANGE;
+    }
+}
+
+/**
+ * If the user has specified a set of mode names to use, mark as bad any modes
+ * not listed.
+ *
+ * The user mode names specified are prefixes to names of modes, so "1024x768"
+ * will match modes named "1024x768", "1024x768x75", "1024x768-good", but
+ * "1024x768x75" would only match "1024x768x75" from that list.
+ *
+ * MODE_BAD is used as the rejection flag, for lack of a better flag.
+ *
+ * \param modeList doubly-linked or circular list of modes.
+ *
+ * This is not in xf86Modes.c, but would be part of the proposed new API.
+ */
+void
+xf86ValidateModesUserConfig(ScrnInfoPtr pScrn, DisplayModePtr modeList)
+{
+    DisplayModePtr mode;
+
+    if (pScrn->display->modes[0] == NULL)
+	return;
+
+    for (mode = modeList; mode != NULL; mode = mode->next) {
+	int i;
+	Bool good = FALSE;
+
+	for (i = 0; pScrn->display->modes[i] != NULL; i++) {
+	    if (strncmp(pScrn->display->modes[i], mode->name,
+			strlen(pScrn->display->modes[i])) == 0) {
+		good = TRUE;
+		break;
+	    }
+	}
+	if (!good)
+	    mode->status = MODE_BAD;
+    }
+}
+
+
+/**
+ * Frees any modes from the list with a status other than MODE_OK.
+ *
+ * \param modeList pointer to a doubly-linked or circular list of modes.
+ * \param verbose determines whether the reason for mode invalidation is
+ *	  printed.
+ *
+ * This is not in xf86Modes.c, but would be part of the proposed new API.
+ */
+void
+xf86PruneInvalidModes(ScrnInfoPtr pScrn, DisplayModePtr *modeList,
+			  Bool verbose)
+{
+    DisplayModePtr mode;
+
+    for (mode = *modeList; mode != NULL;) {
+	DisplayModePtr next = mode->next, first = *modeList;
+
+	if (mode->status != MODE_OK) {
+	    if (verbose) {
+		char *type = "";
+		if (mode->type & M_T_BUILTIN)
+		    type = "built-in ";
+		else if (mode->type & M_T_DEFAULT)
+		    type = "default ";
+		xf86DrvMsg(pScrn->scrnIndex, X_INFO,
+			   "Not using %smode \"%s\" (%s)\n", type, mode->name,
+			   xf86ModeStatusToString(mode->status));
+	    }
+	    xf86DeleteMode(modeList, mode);
+	}
+
+	if (next == first)
+	    break;
+	mode = next;
+    }
+}
+
+/**
+ * Adds the new mode into the mode list, and returns the new list
+ *
+ * \param modes doubly-linked mode list.
+ */
+DisplayModePtr
+xf86ModesAdd(DisplayModePtr modes, DisplayModePtr new)
+{
+    if (modes == NULL)
+	return new;
+
+    if (new) {
+	DisplayModePtr mode = modes;
+
+	while (mode->next)
+	    mode = mode->next;
+
+	mode->next = new;
+	new->prev = mode;
+    }
+
+    return modes;
+}
+
+/**
+ * Build a mode list from a list of config file modes
+ */
+static DisplayModePtr
+xf86GetConfigModes (XF86ConfModeLinePtr conf_mode)
+{
+    DisplayModePtr  head = NULL, prev = NULL, mode;
+    
+    for (; conf_mode; conf_mode = (XF86ConfModeLinePtr) conf_mode->list.next)
+    {
+        mode = xcalloc(1, sizeof(DisplayModeRec));
+	if (!mode)
+	    continue;
+        mode->name       = xstrdup(conf_mode->ml_identifier);
+	if (!mode->name)
+	{
+	    xfree (mode);
+	    continue;
+	}
+	mode->type       = 0;
+        mode->Clock      = conf_mode->ml_clock;
+        mode->HDisplay   = conf_mode->ml_hdisplay;
+        mode->HSyncStart = conf_mode->ml_hsyncstart;
+        mode->HSyncEnd   = conf_mode->ml_hsyncend;
+        mode->HTotal     = conf_mode->ml_htotal;
+        mode->VDisplay   = conf_mode->ml_vdisplay;
+        mode->VSyncStart = conf_mode->ml_vsyncstart;
+        mode->VSyncEnd   = conf_mode->ml_vsyncend;
+        mode->VTotal     = conf_mode->ml_vtotal;
+        mode->Flags      = conf_mode->ml_flags;
+        mode->HSkew      = conf_mode->ml_hskew;
+        mode->VScan      = conf_mode->ml_vscan;
+
+        mode->prev = prev;
+	mode->next = NULL;
+	if (prev)
+	    prev->next = mode;
+	else
+	    head = mode;
+	prev = mode;
+    }
+    return head;
+}
+
+/**
+ * Build a mode list from a monitor configuration
+ */
+DisplayModePtr
+xf86GetMonitorModes (ScrnInfoPtr pScrn, XF86ConfMonitorPtr conf_monitor)
+{
+    DisplayModePtr	    modes = NULL;
+    XF86ConfModesLinkPtr    modes_link;
+    
+    if (!conf_monitor)
+	return NULL;
+
+    /*
+     * first we collect the mode lines from the UseModes directive
+     */
+    for (modes_link = conf_monitor->mon_modes_sect_lst; 
+	 modes_link; 
+	 modes_link = modes_link->list.next)
+    {
+	/* If this modes link hasn't been resolved, go look it up now */
+	if (!modes_link->ml_modes)
+	    modes_link->ml_modes = xf86findModes (modes_link->ml_modes_str, 
+						  xf86configptr->conf_modes_lst);
+	if (modes_link->ml_modes)
+	    modes = xf86ModesAdd (modes,
+				  xf86GetConfigModes (modes_link->ml_modes->mon_modeline_lst));
+    }
+
+    return xf86ModesAdd (modes,
+			 xf86GetConfigModes (conf_monitor->mon_modeline_lst));
+}
+
+/**
+ * Build a mode list containing all of the default modes
+ */
+DisplayModePtr
+xf86GetDefaultModes (Bool interlaceAllowed, Bool doubleScanAllowed)
+{
+    DisplayModePtr  head = NULL, prev = NULL, mode;
+    int		    i;
+
+    for (i = 0; xf86DefaultModes[i].name != NULL; i++)
+    {
+	DisplayModePtr	defMode = &xf86DefaultModes[i];
+	
+	if (!interlaceAllowed && (defMode->Flags & V_INTERLACE))
+	    continue;
+	if (!doubleScanAllowed && (defMode->Flags & V_DBLSCAN))
+	    continue;
+
+	mode = xalloc(sizeof(DisplayModeRec));
+	if (!mode)
+	    continue;
+        memcpy(mode,&xf86DefaultModes[i],sizeof(DisplayModeRec));
+        mode->name = xstrdup(xf86DefaultModes[i].name);
+        if (!mode->name)
+	{
+	    xfree (mode);
+	    continue;
+	}
+        mode->prev = prev;
+	mode->next = NULL;
+	if (prev)
+	    prev->next = mode;
+	else
+	    head = mode;
+	prev = mode;
+    }
+    return head;
+}
diff --git a/hw/xfree86/modes/xf86Modes.h b/hw/xfree86/modes/xf86Modes.h
new file mode 100644
index 0000000..60e2790
--- /dev/null
+++ b/hw/xfree86/modes/xf86Modes.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright © 2006 Intel Corporation
+ *
+ * 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 (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 NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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:
+ *    Eric Anholt <eric at anholt.net>
+ *
+ */
+
+#ifndef _I830_XF86MODES_H_
+#define _I830_XF86MODES_H_
+#include "xorgVersion.h"
+#include "xf86Parser.h"
+#include "edid.h"
+#if XF86_MODES_RENAME
+#include "xf86Rename.h"
+#endif
+
+double xf86ModeHSync(DisplayModePtr mode);
+double xf86ModeVRefresh(DisplayModePtr mode);
+DisplayModePtr xf86DuplicateMode(DisplayModePtr pMode);
+DisplayModePtr xf86DuplicateModes(ScrnInfoPtr pScrn,
+				       DisplayModePtr modeList);
+void xf86SetModeDefaultName(DisplayModePtr mode);
+void xf86SetModeCrtc(DisplayModePtr p, int adjustFlags);
+Bool xf86ModesEqual(DisplayModePtr pMode1, DisplayModePtr pMode2);
+void xf86PrintModeline(int scrnIndex,DisplayModePtr mode);
+DisplayModePtr xf86ModesAdd(DisplayModePtr modes, DisplayModePtr new);
+
+DisplayModePtr xf86DDCGetModes(int scrnIndex, xf86MonPtr DDC);
+DisplayModePtr xf86CVTMode(int HDisplay, int VDisplay, float VRefresh,
+			   Bool Reduced, Bool Interlaced);
+
+void
+xf86ValidateModesFlags(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+		       int flags);
+
+void
+xf86ValidateModesClocks(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+			int *min, int *max, int n_ranges);
+
+void
+xf86ValidateModesSize(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+		      int maxX, int maxY, int maxPitch);
+
+void
+xf86ValidateModesSync(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+		      MonPtr mon);
+
+void
+xf86PruneInvalidModes(ScrnInfoPtr pScrn, DisplayModePtr *modeList,
+		      Bool verbose);
+
+void
+xf86ValidateModesFlags(ScrnInfoPtr pScrn, DisplayModePtr modeList,
+		       int flags);
+
+void
+xf86ValidateModesUserConfig(ScrnInfoPtr pScrn, DisplayModePtr modeList);
+
+DisplayModePtr
+xf86GetMonitorModes (ScrnInfoPtr pScrn, XF86ConfMonitorPtr conf_monitor);
+
+DisplayModePtr
+xf86GetDefaultModes (Bool interlaceAllowed, Bool doubleScanAllowed);
+
+#endif /* _I830_XF86MODES_H_ */
diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
new file mode 100644
index 0000000..bafe71f
--- /dev/null
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -0,0 +1,950 @@
+/* $XdotOrg: xc/programs/Xserver/hw/xfree86/common/xf86RandR.c,v 1.3 2004/07/30 21:53:09 eich Exp $ */
+/*
+ * $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86RandR.c,v 1.7tsi Exp $
+ *
+ * Copyright © 2002 Keith Packard, member of The XFree86 Project, 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 the copyright holders not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  The copyright holders make no representations
+ * about the suitability of this software for any purpose.  It is provided "as
+ * is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS 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_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#include "xf86.h"
+#include "os.h"
+#include "mibank.h"
+#include "globals.h"
+#include "xf86.h"
+#include "xf86Priv.h"
+#include "xf86DDC.h"
+#include "mipointer.h"
+#include "windowstr.h"
+#include <randrstr.h>
+#include <X11/extensions/render.h>
+
+#include "xf86Crtc.h"
+#include "xf86RandR12.h"
+
+typedef struct _xf86RandR12Info {
+    int				    virtualX;
+    int				    virtualY;
+    int				    mmWidth;
+    int				    mmHeight;
+    int				    maxX;
+    int				    maxY;
+    Rotation			    rotation; /* current mode */
+    Rotation                        supported_rotations; /* driver supported */
+} XF86RandRInfoRec, *XF86RandRInfoPtr;
+
+#ifdef RANDR_12_INTERFACE
+static Bool xf86RandR12Init12 (ScreenPtr pScreen);
+static Bool xf86RandR12CreateScreenResources12 (ScreenPtr pScreen);
+#endif
+
+static int	    xf86RandR12Index;
+static int	    xf86RandR12Generation;
+
+#define XF86RANDRINFO(p) \
+	((XF86RandRInfoPtr)(p)->devPrivates[xf86RandR12Index].ptr)
+
+static int
+xf86RandR12ModeRefresh (DisplayModePtr mode)
+{
+    if (mode->VRefresh)
+	return (int) (mode->VRefresh + 0.5);
+    else
+	return (int) (mode->Clock * 1000.0 / mode->HTotal / mode->VTotal + 0.5);
+}
+
+static Bool
+xf86RandR12GetInfo (ScreenPtr pScreen, Rotation *rotations)
+{
+    RRScreenSizePtr	    pSize;
+    ScrnInfoPtr		    scrp = XF86SCRNINFO(pScreen);
+    XF86RandRInfoPtr	    randrp = XF86RANDRINFO(pScreen);
+    DisplayModePtr	    mode;
+    int			    refresh0 = 60;
+    int			    maxX = 0, maxY = 0;
+
+    *rotations = randrp->supported_rotations;
+
+    if (randrp->virtualX == -1 || randrp->virtualY == -1)
+    {
+	randrp->virtualX = scrp->virtualX;
+	randrp->virtualY = scrp->virtualY;
+    }
+
+    /* Re-probe the outputs for new monitors or modes */
+    xf86ProbeOutputModes (scrp, 0, 0);
+    xf86SetScrnInfoModes (scrp);
+    xf86DiDGAReInit (pScreen);
+
+    for (mode = scrp->modes; ; mode = mode->next)
+    {
+	int refresh = xf86RandR12ModeRefresh (mode);
+	if (randrp->maxX == 0 || randrp->maxY == 0)
+	{
+		if (maxX < mode->HDisplay)
+			maxX = mode->HDisplay;
+		if (maxY < mode->VDisplay)
+			maxY = mode->VDisplay;
+	}
+	if (mode == scrp->modes)
+	    refresh0 = refresh;
+	pSize = RRRegisterSize (pScreen,
+				mode->HDisplay, mode->VDisplay,
+				randrp->mmWidth, randrp->mmHeight);
+	if (!pSize)
+	    return FALSE;
+	RRRegisterRate (pScreen, pSize, refresh);
+
+	if (xf86ModesEqual(mode, scrp->currentMode) &&
+	    mode->HDisplay == scrp->virtualX &&
+	    mode->VDisplay == scrp->virtualY)
+	{
+	    RRSetCurrentConfig (pScreen, randrp->rotation, refresh, pSize);
+	}
+	if (mode->next == scrp->modes)
+	    break;
+    }
+
+    if (randrp->maxX == 0 || randrp->maxY == 0)
+    {
+	randrp->maxX = maxX;
+	randrp->maxY = maxY;
+    }
+
+    if (scrp->currentMode->HDisplay != randrp->virtualX ||
+	scrp->currentMode->VDisplay != randrp->virtualY)
+    {
+	pSize = RRRegisterSize (pScreen,
+				randrp->virtualX, randrp->virtualY,
+				randrp->mmWidth,
+				randrp->mmHeight);
+	if (!pSize)
+	    return FALSE;
+	RRRegisterRate (pScreen, pSize, refresh0);
+	if (scrp->virtualX == randrp->virtualX &&
+	    scrp->virtualY == randrp->virtualY)
+	{
+	    RRSetCurrentConfig (pScreen, randrp->rotation, refresh0, pSize);
+	}
+    }
+
+    return TRUE;
+}
+
+static Bool
+xf86RandR12SetMode (ScreenPtr	    pScreen,
+		  DisplayModePtr    mode,
+		  Bool		    useVirtual,
+		  int		    mmWidth,
+		  int		    mmHeight)
+{
+    ScrnInfoPtr		scrp = XF86SCRNINFO(pScreen);
+    XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+    int			oldWidth = pScreen->width;
+    int			oldHeight = pScreen->height;
+    int			oldmmWidth = pScreen->mmWidth;
+    int			oldmmHeight = pScreen->mmHeight;
+    WindowPtr		pRoot = WindowTable[pScreen->myNum];
+    DisplayModePtr      currentMode = NULL;
+    Bool 		ret = TRUE;
+    PixmapPtr 		pspix = NULL;
+
+    if (pRoot)
+	(*scrp->EnableDisableFBAccess) (pScreen->myNum, FALSE);
+    if (useVirtual)
+    {
+	scrp->virtualX = randrp->virtualX;
+	scrp->virtualY = randrp->virtualY;
+    }
+    else
+    {
+	scrp->virtualX = mode->HDisplay;
+	scrp->virtualY = mode->VDisplay;
+    }
+
+    if(randrp->rotation & (RR_Rotate_90 | RR_Rotate_270))
+    {
+	/* If the screen is rotated 90 or 270 degrees, swap the sizes. */
+	pScreen->width = scrp->virtualY;
+	pScreen->height = scrp->virtualX;
+	pScreen->mmWidth = mmHeight;
+	pScreen->mmHeight = mmWidth;
+    }
+    else
+    {
+	pScreen->width = scrp->virtualX;
+	pScreen->height = scrp->virtualY;
+	pScreen->mmWidth = mmWidth;
+	pScreen->mmHeight = mmHeight;
+    }
+    if (scrp->currentMode == mode) {
+        /* Save current mode */
+        currentMode = scrp->currentMode;
+        /* Reset, just so we ensure the drivers SwitchMode is called */
+        scrp->currentMode = NULL;
+    }
+    /*
+     * We know that if the driver failed to SwitchMode to the rotated
+     * version, then it should revert back to it's prior mode.
+     */
+    if (!xf86SwitchMode (pScreen, mode))
+    {
+        ret = FALSE;
+	scrp->virtualX = pScreen->width = oldWidth;
+	scrp->virtualY = pScreen->height = oldHeight;
+	pScreen->mmWidth = oldmmWidth;
+	pScreen->mmHeight = oldmmHeight;
+        scrp->currentMode = currentMode;
+    }
+    /*
+     * Get the new Screen pixmap ptr as SwitchMode might have called
+     * ModifyPixmapHeader and xf86EnableDisableFBAccess will put it back...
+     * Unfortunately.
+     */
+    pspix = (*pScreen->GetScreenPixmap) (pScreen);
+    if (pspix->devPrivate.ptr)
+       scrp->pixmapPrivate = pspix->devPrivate;
+
+    /*
+     * Make sure the layout is correct
+     */
+    xf86ReconfigureLayout();
+
+    /*
+     * Make sure the whole screen is visible
+     */
+    xf86SetViewport (pScreen, pScreen->width, pScreen->height);
+    xf86SetViewport (pScreen, 0, 0);
+    if (pRoot)
+	(*scrp->EnableDisableFBAccess) (pScreen->myNum, TRUE);
+    return ret;
+}
+
+Bool
+xf86RandR12SetConfig (ScreenPtr		pScreen,
+		    Rotation		rotation,
+		    int			rate,
+		    RRScreenSizePtr	pSize)
+{
+    ScrnInfoPtr		scrp = XF86SCRNINFO(pScreen);
+    XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+    DisplayModePtr	mode;
+    int			px, py;
+    Bool		useVirtual = FALSE;
+    int			maxX = 0, maxY = 0;
+    Rotation		oldRotation = randrp->rotation;
+
+    randrp->rotation = rotation;
+
+    if (randrp->virtualX == -1 || randrp->virtualY == -1)
+    {
+	randrp->virtualX = scrp->virtualX;
+	randrp->virtualY = scrp->virtualY;
+    }
+
+    miPointerPosition (&px, &py);
+    for (mode = scrp->modes; ; mode = mode->next)
+    {
+	if (randrp->maxX == 0 || randrp->maxY == 0)
+	{
+		if (maxX < mode->HDisplay)
+			maxX = mode->HDisplay;
+		if (maxY < mode->VDisplay)
+			maxY = mode->VDisplay;
+	}
+	if (mode->HDisplay == pSize->width &&
+	    mode->VDisplay == pSize->height &&
+	    (rate == 0 || xf86RandR12ModeRefresh (mode) == rate))
+	    break;
+	if (mode->next == scrp->modes)
+	{
+	    if (pSize->width == randrp->virtualX &&
+		pSize->height == randrp->virtualY)
+	    {
+		mode = scrp->modes;
+		useVirtual = TRUE;
+		break;
+	    }
+    	    if (randrp->maxX == 0 || randrp->maxY == 0)
+    	    {
+		randrp->maxX = maxX;
+		randrp->maxY = maxY;
+    	    }
+	    return FALSE;
+	}
+    }
+
+    if (randrp->maxX == 0 || randrp->maxY == 0)
+    {
+	randrp->maxX = maxX;
+	randrp->maxY = maxY;
+    }
+
+    if (!xf86RandR12SetMode (pScreen, mode, useVirtual, pSize->mmWidth,
+			   pSize->mmHeight)) {
+        randrp->rotation = oldRotation;
+	return FALSE;
+    }
+
+    /*
+     * Move the cursor back where it belongs; SwitchMode repositions it
+     */
+    if (pScreen == miPointerCurrentScreen ())
+    {
+        px = (px >= pScreen->width ? (pScreen->width - 1) : px);
+        py = (py >= pScreen->height ? (pScreen->height - 1) : py);
+
+	xf86SetViewport(pScreen, px, py);
+
+	(*pScreen->SetCursorPosition) (pScreen, px, py, FALSE);
+    }
+
+    return TRUE;
+}
+
+static Bool
+xf86RandR12ScreenSetSize (ScreenPtr	pScreen,
+			CARD16		width,
+			CARD16		height,
+			CARD32		mmWidth,
+			CARD32		mmHeight)
+{
+    XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+    ScrnInfoPtr		pScrn = XF86SCRNINFO(pScreen);
+    WindowPtr		pRoot = WindowTable[pScreen->myNum];
+    Bool 		ret = TRUE;
+
+    if (randrp->virtualX == -1 || randrp->virtualY == -1)
+    {
+	randrp->virtualX = pScrn->virtualX;
+	randrp->virtualY = pScrn->virtualY;
+    }
+    if (pRoot)
+	(*pScrn->EnableDisableFBAccess) (pScreen->myNum, FALSE);
+    pScrn->virtualX = width;
+    pScrn->virtualY = height;
+
+    pScreen->width = pScrn->virtualX;
+    pScreen->height = pScrn->virtualY;
+    pScreen->mmWidth = mmWidth;
+    pScreen->mmHeight = mmHeight;
+
+    xf86SetViewport (pScreen, pScreen->width-1, pScreen->height-1);
+    xf86SetViewport (pScreen, 0, 0);
+    if (pRoot)
+	(*pScrn->EnableDisableFBAccess) (pScreen->myNum, TRUE);
+#if RANDR_12_INTERFACE
+    if (WindowTable[pScreen->myNum])
+	RRScreenSizeNotify (pScreen);
+#endif
+    return ret;
+}
+
+Rotation
+xf86RandR12GetRotation(ScreenPtr pScreen)
+{
+    XF86RandRInfoPtr	    randrp = XF86RANDRINFO(pScreen);
+
+    return randrp->rotation;
+}
+
+Bool
+xf86RandR12CreateScreenResources (ScreenPtr pScreen)
+{
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+    XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+    int			c;
+    int			width, height;
+    int			mmWidth, mmHeight;
+#ifdef PANORAMIX
+    /* XXX disable RandR when using Xinerama */
+    if (!noPanoramiXExtension)
+	return TRUE;
+#endif
+
+    /*
+     * Compute size of screen
+     */
+    width = 0; height = 0;
+    for (c = 0; c < config->num_crtc; c++)
+    {
+	xf86CrtcPtr crtc = config->crtc[c];
+	int	    crtc_width = crtc->x + crtc->mode.HDisplay;
+	int	    crtc_height = crtc->y + crtc->mode.VDisplay;
+	
+	if (crtc->enabled && crtc_width > width)
+	    width = crtc_width;
+	if (crtc->enabled && crtc_height > height)
+	    height = crtc_height;
+    }
+    
+    if (width && height)
+    {
+	/*
+	 * Compute physical size of screen
+	 */
+	if (monitorResolution) 
+	{
+	    mmWidth = width * 25.4 / monitorResolution;
+	    mmHeight = height * 25.4 / monitorResolution;
+	}
+	else
+	{
+	    mmWidth = pScreen->mmWidth;
+	    mmHeight = pScreen->mmHeight;
+	}
+	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
+		   "Setting screen physical size to %d x %d\n",
+		   mmWidth, mmHeight);
+	xf86RandR12ScreenSetSize (pScreen,
+				  width,
+				  height,
+				  mmWidth,
+				  mmHeight);
+    }
+
+    if (randrp->virtualX == -1 || randrp->virtualY == -1)
+    {
+	randrp->virtualX = pScrn->virtualX;
+	randrp->virtualY = pScrn->virtualY;
+    }
+#if RANDR_12_INTERFACE
+    if (xf86RandR12CreateScreenResources12 (pScreen))
+	return TRUE;
+#endif
+    return TRUE;
+}
+
+
+Bool
+xf86RandR12Init (ScreenPtr pScreen)
+{
+    rrScrPrivPtr	rp;
+    XF86RandRInfoPtr	randrp;
+
+#ifdef PANORAMIX
+    /* XXX disable RandR when using Xinerama */
+    if (!noPanoramiXExtension)
+	return TRUE;
+#endif
+    if (xf86RandR12Generation != serverGeneration)
+    {
+	xf86RandR12Index = AllocateScreenPrivateIndex();
+	xf86RandR12Generation = serverGeneration;
+    }
+
+    randrp = xalloc (sizeof (XF86RandRInfoRec));
+    if (!randrp)
+	return FALSE;
+
+    if (!RRScreenInit(pScreen))
+    {
+	xfree (randrp);
+	return FALSE;
+    }
+    rp = rrGetScrPriv(pScreen);
+    rp->rrGetInfo = xf86RandR12GetInfo;
+    rp->rrSetConfig = xf86RandR12SetConfig;
+
+    randrp->virtualX = -1;
+    randrp->virtualY = -1;
+    randrp->mmWidth = pScreen->mmWidth;
+    randrp->mmHeight = pScreen->mmHeight;
+
+    randrp->rotation = RR_Rotate_0; /* initial rotated mode */
+
+    randrp->supported_rotations = RR_Rotate_0;
+
+    randrp->maxX = randrp->maxY = 0;
+
+    pScreen->devPrivates[xf86RandR12Index].ptr = randrp;
+
+#if RANDR_12_INTERFACE
+    if (!xf86RandR12Init12 (pScreen))
+	return FALSE;
+#endif
+    return TRUE;
+}
+
+void
+xf86RandR12SetRotations (ScreenPtr pScreen, Rotation rotations)
+{
+    XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+    int			c;
+
+    randrp->supported_rotations = rotations;
+
+#if RANDR_12_INTERFACE
+    for (c = 0; c < config->num_crtc; c++) {
+	xf86CrtcPtr    crtc = config->crtc[c];
+
+	RRCrtcSetRotations (crtc->randr_crtc, rotations);
+    }
+#endif
+}
+
+void
+xf86RandR12GetOriginalVirtualSize(ScrnInfoPtr pScrn, int *x, int *y)
+{
+    ScreenPtr pScreen = screenInfo.screens[pScrn->scrnIndex];
+
+    if (xf86RandR12Generation != serverGeneration ||
+	XF86RANDRINFO(pScreen)->virtualX == -1)
+    {
+	*x = pScrn->virtualX;
+	*y = pScrn->virtualY;
+    } else {
+	XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen);
+
+	*x = randrp->virtualX;
+	*y = randrp->virtualY;
+    }
+}
+
+#if RANDR_12_INTERFACE
+static Bool
+xf86RandR12CrtcNotify (RRCrtcPtr	randr_crtc)
+{
+    ScreenPtr		pScreen = randr_crtc->pScreen;
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+    RRModePtr		randr_mode = NULL;
+    int			x;
+    int			y;
+    Rotation		rotation;
+    int			numOutputs;
+    RROutputPtr		*randr_outputs;
+    RROutputPtr		randr_output;
+    xf86CrtcPtr		crtc = randr_crtc->devPrivate;
+    xf86OutputPtr	output;
+    int			i, j;
+    DisplayModePtr	mode = &crtc->mode;
+    Bool		ret;
+
+    randr_outputs = ALLOCATE_LOCAL(config->num_output * sizeof (RROutputPtr));
+    if (!randr_outputs)
+	return FALSE;
+    x = crtc->x;
+    y = crtc->y;
+    rotation = crtc->rotation;
+    numOutputs = 0;
+    randr_mode = NULL;
+    for (i = 0; i < config->num_output; i++)
+    {
+	output = config->output[i];
+	if (output->crtc == crtc)
+	{
+	    randr_output = output->randr_output;
+	    randr_outputs[numOutputs++] = randr_output;
+	    /*
+	     * We make copies of modes, so pointer equality 
+	     * isn't sufficient
+	     */
+	    for (j = 0; j < randr_output->numModes; j++)
+	    {
+		DisplayModePtr	outMode = randr_output->modes[j]->devPrivate;
+		if (xf86ModesEqual(mode, outMode))
+		{
+		    randr_mode = randr_output->modes[j];
+		    break;
+		}
+	    }
+	}
+    }
+    ret = RRCrtcNotify (randr_crtc, randr_mode, x, y,
+			rotation, numOutputs, randr_outputs);
+    DEALLOCATE_LOCAL(randr_outputs);
+    return ret;
+}
+
+static Bool
+xf86RandR12CrtcSet (ScreenPtr	pScreen,
+		  RRCrtcPtr	randr_crtc,
+		  RRModePtr	randr_mode,
+		  int		x,
+		  int		y,
+		  Rotation	rotation,
+		  int		num_randr_outputs,
+		  RROutputPtr	*randr_outputs)
+{
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+    xf86CrtcPtr		crtc = randr_crtc->devPrivate;
+    DisplayModePtr	mode = randr_mode ? randr_mode->devPrivate : NULL;
+    Bool		changed = FALSE;
+    int			o, ro;
+    xf86CrtcPtr		*save_crtcs;
+    Bool		save_enabled = crtc->enabled;
+
+    save_crtcs = ALLOCATE_LOCAL(config->num_crtc * sizeof (xf86CrtcPtr));
+    if ((mode != NULL) != crtc->enabled)
+	changed = TRUE;
+    else if (mode && !xf86ModesEqual (&crtc->mode, mode))
+	changed = TRUE;
+    
+    if (rotation != crtc->rotation)
+	changed = TRUE;
+
+    if (x != crtc->x || y != crtc->y)
+	changed = TRUE;
+    for (o = 0; o < config->num_output; o++) 
+    {
+	xf86OutputPtr  output = config->output[o];
+	xf86CrtcPtr    new_crtc;
+
+	save_crtcs[o] = output->crtc;
+	
+	if (output->crtc == crtc)
+	    new_crtc = NULL;
+	else
+	    new_crtc = output->crtc;
+	for (ro = 0; ro < num_randr_outputs; ro++) 
+	    if (output->randr_output == randr_outputs[ro])
+	    {
+		new_crtc = crtc;
+		break;
+	    }
+	if (new_crtc != output->crtc)
+	{
+	    changed = TRUE;
+	    output->crtc = new_crtc;
+	}
+    }
+    /* XXX need device-independent mode setting code through an API */
+    if (changed)
+    {
+	crtc->enabled = mode != NULL;
+
+	if (mode)
+	{
+	    if (!xf86CrtcSetMode (crtc, mode, rotation, x, y))
+	    {
+		crtc->enabled = save_enabled;
+		for (o = 0; o < config->num_output; o++)
+		{
+		    xf86OutputPtr	output = config->output[o];
+		    output->crtc = save_crtcs[o];
+		}
+		DEALLOCATE_LOCAL(save_crtcs);
+		return FALSE;
+	    }
+	    /*
+	     * Save the last successful setting for EnterVT
+	     */
+	    crtc->desiredMode = *mode;
+	    crtc->desiredRotation = rotation;
+	    crtc->desiredX = x;
+	    crtc->desiredY = y;
+	}
+	xf86DisableUnusedFunctions (pScrn);
+    }
+    DEALLOCATE_LOCAL(save_crtcs);
+    return xf86RandR12CrtcNotify (randr_crtc);
+}
+
+static Bool
+xf86RandR12CrtcSetGamma (ScreenPtr    pScreen,
+			 RRCrtcPtr    randr_crtc)
+{
+    xf86CrtcPtr		crtc = randr_crtc->devPrivate;
+
+    if (crtc->funcs->gamma_set == NULL)
+	return FALSE;
+
+    crtc->funcs->gamma_set(crtc, randr_crtc->gammaRed, randr_crtc->gammaGreen,
+			   randr_crtc->gammaBlue, randr_crtc->gammaSize);
+
+    return TRUE;
+}
+
+static Bool
+xf86RandR12OutputSetProperty (ScreenPtr pScreen,
+			      RROutputPtr randr_output,
+			      Atom property,
+			      RRPropertyValuePtr value)
+{
+    xf86OutputPtr output = randr_output->devPrivate;
+
+    /* If we don't have any property handler, then we don't care what the
+     * user is setting properties to.
+     */
+    if (output->funcs->set_property == NULL)
+	return TRUE;
+
+    return output->funcs->set_property(output, property, value);
+}
+
+/**
+ * Given a list of xf86 modes and a RandR Output object, construct
+ * RandR modes and assign them to the output
+ */
+static Bool
+xf86RROutputSetModes (RROutputPtr randr_output, DisplayModePtr modes)
+{
+    DisplayModePtr  mode;
+    RRModePtr	    *rrmodes = NULL;
+    int		    nmode = 0;
+    int		    npreferred = 0;
+    Bool	    ret = TRUE;
+    int		    pref;
+
+    for (mode = modes; mode; mode = mode->next)
+	nmode++;
+
+    if (nmode) {
+	rrmodes = xalloc (nmode * sizeof (RRModePtr));
+	
+	if (!rrmodes)
+	    return FALSE;
+	nmode = 0;
+
+	for (pref = 1; pref >= 0; pref--) {
+	    for (mode = modes; mode; mode = mode->next) {
+		if ((pref != 0) == ((mode->type & M_T_PREFERRED) != 0)) {
+		    xRRModeInfo		modeInfo;
+		    RRModePtr		rrmode;
+		    
+		    modeInfo.nameLength = strlen (mode->name);
+		    modeInfo.width = mode->HDisplay;
+		    modeInfo.dotClock = mode->Clock * 1000;
+		    modeInfo.hSyncStart = mode->HSyncStart;
+		    modeInfo.hSyncEnd = mode->HSyncEnd;
+		    modeInfo.hTotal = mode->HTotal;
+		    modeInfo.hSkew = mode->HSkew;
+
+		    modeInfo.height = mode->VDisplay;
+		    modeInfo.vSyncStart = mode->VSyncStart;
+		    modeInfo.vSyncEnd = mode->VSyncEnd;
+		    modeInfo.vTotal = mode->VTotal;
+		    modeInfo.modeFlags = mode->Flags;
+
+		    rrmode = RRModeGet (&modeInfo, mode->name);
+		    if (rrmode) {
+			rrmode->devPrivate = mode;
+			rrmodes[nmode++] = rrmode;
+			npreferred += pref;
+		    }
+		}
+	    }
+	}
+    }
+    
+    ret = RROutputSetModes (randr_output, rrmodes, nmode, npreferred);
+    xfree (rrmodes);
+    return ret;
+}
+
+/*
+ * Mirror the current mode configuration to RandR
+ */
+static Bool
+xf86RandR12SetInfo12 (ScreenPtr pScreen)
+{
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+    RROutputPtr		*clones;
+    RRCrtcPtr		*crtcs;
+    int			ncrtc;
+    int			o, c, l;
+    RRCrtcPtr		randr_crtc;
+    int			nclone;
+    
+    clones = ALLOCATE_LOCAL(config->num_output * sizeof (RROutputPtr));
+    crtcs = ALLOCATE_LOCAL (config->num_crtc * sizeof (RRCrtcPtr));
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr	output = config->output[o];
+	
+	ncrtc = 0;
+	for (c = 0; c < config->num_crtc; c++)
+	    if (output->possible_crtcs & (1 << c))
+		crtcs[ncrtc++] = config->crtc[c]->randr_crtc;
+
+	if (output->crtc)
+	    randr_crtc = output->crtc->randr_crtc;
+	else
+	    randr_crtc = NULL;
+
+	if (!RROutputSetCrtcs (output->randr_output, crtcs, ncrtc))
+	{
+	    DEALLOCATE_LOCAL (crtcs);
+	    DEALLOCATE_LOCAL (clones);
+	    return FALSE;
+	}
+
+	RROutputSetCrtc (output->randr_output, randr_crtc);
+	RROutputSetPhysicalSize(output->randr_output, 
+				output->mm_width,
+				output->mm_height);
+	xf86RROutputSetModes (output->randr_output, output->probed_modes);
+
+	switch (output->status) {
+	case XF86OutputStatusConnected:
+	    RROutputSetConnection (output->randr_output, RR_Connected);
+	    break;
+	case XF86OutputStatusDisconnected:
+	    RROutputSetConnection (output->randr_output, RR_Disconnected);
+	    break;
+	case XF86OutputStatusUnknown:
+	    RROutputSetConnection (output->randr_output, RR_UnknownConnection);
+	    break;
+	}
+
+	RROutputSetSubpixelOrder (output->randr_output, output->subpixel_order);
+
+	/*
+	 * Valid clones
+	 */
+	nclone = 0;
+	for (l = 0; l < config->num_output; l++)
+	{
+	    xf86OutputPtr	    clone = config->output[l];
+	    
+	    if (l != o && (output->possible_clones & (1 << l)))
+		clones[nclone++] = clone->randr_output;
+	}
+	if (!RROutputSetClones (output->randr_output, clones, nclone))
+	{
+	    DEALLOCATE_LOCAL (crtcs);
+	    DEALLOCATE_LOCAL (clones);
+	    return FALSE;
+	}
+    }
+    DEALLOCATE_LOCAL (crtcs);
+    DEALLOCATE_LOCAL (clones);
+    return TRUE;
+}
+
+
+
+/*
+ * Query the hardware for the current state, then mirror
+ * that to RandR
+ */
+static Bool
+xf86RandR12GetInfo12 (ScreenPtr pScreen, Rotation *rotations)
+{
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+
+    xf86ProbeOutputModes (pScrn, 0, 0);
+    xf86SetScrnInfoModes (pScrn);
+    xf86DiDGAReInit (pScreen);
+    return xf86RandR12SetInfo12 (pScreen);
+}
+
+static Bool
+xf86RandR12CreateObjects12 (ScreenPtr pScreen)
+{
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+    int			c;
+    int			o;
+    
+    if (!RRInit ())
+	return FALSE;
+
+    /*
+     * Configure crtcs
+     */
+    for (c = 0; c < config->num_crtc; c++)
+    {
+	xf86CrtcPtr    crtc = config->crtc[c];
+	
+	crtc->randr_crtc = RRCrtcCreate (crtc);
+	RRCrtcAttachScreen (crtc->randr_crtc, pScreen);
+	RRCrtcGammaSetSize (crtc->randr_crtc, 256);
+    }
+    /*
+     * Configure outputs
+     */
+    for (o = 0; o < config->num_output; o++)
+    {
+	xf86OutputPtr	output = config->output[o];
+
+	output->randr_output = RROutputCreate (output->name, 
+					       strlen (output->name),
+					       output);
+	RROutputAttachScreen (output->randr_output, pScreen);
+
+	if (output->funcs->create_resources != NULL)
+	    output->funcs->create_resources(output);
+    }
+    return TRUE;
+}
+
+static Bool
+xf86RandR12CreateScreenResources12 (ScreenPtr pScreen)
+{
+    int			c;
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    XF86RandRInfoPtr	randrp = XF86RANDRINFO(pScreen);
+    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
+
+    for (c = 0; c < config->num_crtc; c++)
+	xf86RandR12CrtcNotify (config->crtc[c]->randr_crtc);
+    
+    
+    RRScreenSetSizeRange (pScreen, 320, 240,
+			  randrp->virtualX, randrp->virtualY);
+    return TRUE;
+}
+
+static void
+xf86RandR12PointerMoved (int scrnIndex, int x, int y)
+{
+}
+
+static Bool
+xf86RandR12Init12 (ScreenPtr pScreen)
+{
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    rrScrPrivPtr	rp = rrGetScrPriv(pScreen);
+
+    rp->rrGetInfo = xf86RandR12GetInfo12;
+    rp->rrScreenSetSize = xf86RandR12ScreenSetSize;
+    rp->rrCrtcSet = xf86RandR12CrtcSet;
+    rp->rrCrtcSetGamma = xf86RandR12CrtcSetGamma;
+    rp->rrOutputSetProperty = xf86RandR12OutputSetProperty;
+    rp->rrSetConfig = NULL;
+    pScrn->PointerMoved = xf86RandR12PointerMoved;
+    if (!xf86RandR12CreateObjects12 (pScreen))
+	return FALSE;
+
+    /*
+     * Configure output modes
+     */
+    if (!xf86RandR12SetInfo12 (pScreen))
+	return FALSE;
+    return TRUE;
+}
+
+#endif
+
+Bool
+xf86RandR12PreInit (ScrnInfoPtr pScrn)
+{
+    return TRUE;
+}
diff --git a/hw/xfree86/modes/xf86RandR12.h b/hw/xfree86/modes/xf86RandR12.h
new file mode 100644
index 0000000..8a4668b
--- /dev/null
+++ b/hw/xfree86/modes/xf86RandR12.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright © 2006 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 the copyright holders not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  The copyright holders make no representations
+ * about the suitability of this software for any purpose.  It is provided "as
+ * is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS 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.
+ */
+
+#ifndef _XF86_RANDR_H_
+#define _XF86_RANDR_H_
+#include <randrstr.h>
+#include <X11/extensions/render.h>
+
+Bool xf86RandR12CreateScreenResources (ScreenPtr pScreen);
+Bool xf86RandR12Init(ScreenPtr pScreen);
+void xf86RandR12SetRotations (ScreenPtr pScreen, Rotation rotation);
+Bool xf86RandR12SetConfig(ScreenPtr pScreen, Rotation rotation, int rate,
+			RRScreenSizePtr pSize);
+Rotation xf86RandR12GetRotation(ScreenPtr pScreen);
+void xf86RandR12GetOriginalVirtualSize(ScrnInfoPtr pScrn, int *x, int *y);
+Bool xf86RandR12PreInit (ScrnInfoPtr pScrn);
+
+#endif /* _XF86_RANDR_H_ */
diff --git a/hw/xfree86/modes/xf86Rename.h b/hw/xfree86/modes/xf86Rename.h
new file mode 100644
index 0000000..a00253d
--- /dev/null
+++ b/hw/xfree86/modes/xf86Rename.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright © 2006 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 the copyright holders not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  The copyright holders make no representations
+ * about the suitability of this software for any purpose.  It is provided "as
+ * is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS 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.
+ */
+
+#ifndef _XF86RENAME_H_
+#define _XF86RENAME_H_
+
+#include "local_xf86Rename.h"
+
+#define xf86CrtcConfigInit XF86NAME(xf86CrtcConfigInit)
+#define xf86CrtcConfigPrivateIndex XF86NAME(xf86CrtcConfigPrivateIndex)
+#define xf86CrtcCreate XF86NAME(xf86CrtcCreate)
+#define xf86CrtcDestroy XF86NAME(xf86CrtcDestroy)
+#define xf86CrtcInUse XF86NAME(xf86CrtcInUse)
+#define xf86CrtcRotate XF86NAME(xf86CrtcRotate)
+#define xf86CrtcSetMode XF86NAME(xf86CrtcSetMode)
+#define xf86CrtcSetSizeRange XF86NAME(xf86CrtcSetSizeRange)
+#define xf86CVTMode XF86NAME(xf86CVTMode)
+#define xf86DisableUnusedFunctions XF86NAME(xf86DisableUnusedFunctions)
+#define xf86DPMSSet XF86NAME(xf86DPMSSet)
+#define xf86DuplicateMode XF86NAME(xf86DuplicateMode)
+#define xf86DuplicateModes XF86NAME(xf86DuplicateModes)
+#define xf86GetDefaultModes XF86NAME(xf86GetDefaultModes)
+#define xf86GetMonitorModes XF86NAME(xf86GetMonitorModes)
+#define xf86InitialConfiguration XF86NAME(xf86InitialConfiguration)
+#define xf86ModeHSync XF86NAME(xf86ModeHSync)
+#define xf86ModesAdd XF86NAME(xf86ModesAdd)
+#define xf86ModesEqual XF86NAME(xf86ModesEqual)
+#define xf86ModeVRefresh XF86NAME(xf86ModeVRefresh)
+#define xf86OutputCreate XF86NAME(xf86OutputCreate)
+#define xf86OutputDestroy XF86NAME(xf86OutputDestroy)
+#define xf86OutputGetEDID XF86NAME(xf86OutputGetEDID)
+#define xf86OutputGetEDIDModes XF86NAME(xf86OutputGetEDIDModes)
+#define xf86OutputRename XF86NAME(xf86OutputRename)
+#define xf86OutputSetEDID XF86NAME(xf86OutputSetEDID)
+#define xf86PrintModeline XF86NAME(xf86PrintModeline)
+#define xf86ProbeOutputModes XF86NAME(xf86ProbeOutputModes)
+#define xf86PruneInvalidModes XF86NAME(xf86PruneInvalidModes)
+#define xf86SetModeCrtc XF86NAME(xf86SetModeCrtc)
+#define xf86SetModeDefaultName XF86NAME(xf86SetModeDefaultName)
+#define xf86SetScrnInfoModes XF86NAME(xf86SetScrnInfoModes)
+#define xf86ValidateModesClocks XF86NAME(xf86ValidateModesClocks)
+#define xf86ValidateModesFlags XF86NAME(xf86ValidateModesFlags)
+#define xf86ValidateModesSize XF86NAME(xf86ValidateModesSize)
+#define xf86ValidateModesSync XF86NAME(xf86ValidateModesSync)
+#define xf86ValidateModesUserConfig XF86NAME(xf86ValidateModesUserConfig)
+#define xf86DiDGAInit XF86NAME(xf86DiDGAInit)
+#define xf86DiDGAReInit XF86NAME(xf86DiDGAReInit)
+#define xf86DDCGetModes XF86NAME(xf86DDCGetModes)
+#define xf86RandR12CreateScreenResources XF86NAME(xf86RandR12CreateScreenResources)
+#define xf86RandR12GetOriginalVirtualSize XF86NAME(xf86RandR12GetOriginalVirtualSize)
+#define xf86RandR12GetRotation XF86NAME(xf86RandR12GetRotation)
+#define xf86RandR12Init XF86NAME(xf86RandR12Init)
+#define xf86RandR12PreInit XF86NAME(xf86RandR12PreInit)
+#define xf86RandR12SetConfig XF86NAME(xf86RandR12SetConfig)
+#define xf86RandR12SetRotations XF86NAME(xf86RandR12SetRotations)
+#define xf86SaveScreen XF86NAME(xf86SaveScreen)
+
+#endif /* _XF86RENAME_H_ */
diff --git a/hw/xfree86/modes/xf86Rotate.c b/hw/xfree86/modes/xf86Rotate.c
new file mode 100644
index 0000000..1e79063
--- /dev/null
+++ b/hw/xfree86/modes/xf86Rotate.c
@@ -0,0 +1,402 @@
+/*
+ * Copyright © 2006 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 the copyright holders not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  The copyright holders make no representations
+ * about the suitability of this software for any purpose.  It is provided "as
+ * is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS 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_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "xf86.h"
+#include "xf86DDC.h"
+#include "fb.h"
+#include "windowstr.h"
+#include "xf86Crtc.h"
+#include "xf86Modes.h"
+#include "xf86RandR12.h"
+#include "X11/extensions/render.h"
+#define DPMS_SERVER
+#include "X11/extensions/dpms.h"
+#include "X11/Xatom.h"
+
+static int
+mode_height (DisplayModePtr mode, Rotation rotation)
+{
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_180:
+	return mode->VDisplay;
+    case RR_Rotate_90:
+    case RR_Rotate_270:
+	return mode->HDisplay;
+    default:
+	return 0;
+    }
+}
+
+static int
+mode_width (DisplayModePtr mode, Rotation rotation)
+{
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_180:
+	return mode->HDisplay;
+    case RR_Rotate_90:
+    case RR_Rotate_270:
+	return mode->VDisplay;
+    default:
+	return 0;
+    }
+}
+
+/* borrowed from composite extension, move to Render and publish? */
+
+static VisualPtr
+compGetWindowVisual (WindowPtr pWin)
+{
+    ScreenPtr	    pScreen = pWin->drawable.pScreen;
+    VisualID	    vid = wVisual (pWin);
+    int		    i;
+
+    for (i = 0; i < pScreen->numVisuals; i++)
+	if (pScreen->visuals[i].vid == vid)
+	    return &pScreen->visuals[i];
+    return 0;
+}
+
+static PictFormatPtr
+compWindowFormat (WindowPtr pWin)
+{
+    ScreenPtr	pScreen = pWin->drawable.pScreen;
+    
+    return PictureMatchVisual (pScreen, pWin->drawable.depth,
+			       compGetWindowVisual (pWin));
+}
+
+static void
+xf86RotateBox (BoxPtr dst, BoxPtr src, Rotation rotation,
+	       int dest_width, int dest_height)
+{
+    switch (rotation & 0xf) {
+    default:
+    case RR_Rotate_0:
+	*dst = *src;
+	break;
+    case RR_Rotate_90:
+	dst->x1 = src->y1;
+	dst->y1 = dest_height - src->x2;
+	dst->x2 = src->y2;
+	dst->y2 = dest_height - src->x1;
+	break;
+    case RR_Rotate_180:
+	dst->x1 = dest_width - src->x2;
+	dst->y1 = dest_height - src->y2;
+	dst->x2 = dest_width - src->x1;
+	dst->y2 = dest_height - src->y1;
+	break;
+    case RR_Rotate_270:
+	dst->x1 = dest_width - src->y2;
+	dst->y1 = src->x1;
+	dst->y2 = src->x2;
+	dst->x2 = dest_width - src->y1;
+	break;
+    }
+    if (rotation & RR_Reflect_X) {
+	int x1 = dst->x1;
+	dst->x1 = dest_width - dst->x2;
+	dst->x2 = dest_width - x1;
+    }
+    if (rotation & RR_Reflect_Y) {
+	int y1 = dst->y1;
+	dst->y1 = dest_height - dst->y2;
+	dst->y2 = dest_height - y1;
+    }
+}
+
+static void
+xf86RotateCrtcRedisplay (xf86CrtcPtr crtc, RegionPtr region)
+{
+    ScrnInfoPtr		scrn = crtc->scrn;
+    ScreenPtr		screen = scrn->pScreen;
+    WindowPtr		root = WindowTable[screen->myNum];
+    PixmapPtr		dst_pixmap = crtc->rotatedPixmap;
+    PictFormatPtr	format = compWindowFormat (WindowTable[screen->myNum]);
+    int			error;
+    PicturePtr		src, dst;
+    PictTransform	transform;
+    int			n = REGION_NUM_RECTS(region);
+    BoxPtr		b = REGION_RECTS(region);
+    XID			include_inferiors = IncludeInferiors;
+    
+    src = CreatePicture (None,
+			 &root->drawable,
+			 format,
+			 CPSubwindowMode,
+			 &include_inferiors,
+			 serverClient,
+			 &error);
+    if (!src) {
+	ErrorF("couldn't create src pict\n");
+	return;
+    }
+    dst = CreatePicture (None,
+			 &dst_pixmap->drawable,
+			 format,
+			 0L,
+			 NULL,
+			 serverClient,
+			 &error);
+    if (!dst) {
+	ErrorF("couldn't create src pict\n");
+	return;
+    }
+
+    memset (&transform, '\0', sizeof (transform));
+    transform.matrix[2][2] = IntToxFixed(1);
+    transform.matrix[0][2] = IntToxFixed(crtc->x);
+    transform.matrix[1][2] = IntToxFixed(crtc->y);
+    switch (crtc->rotation & 0xf) {
+    default:
+    case RR_Rotate_0:
+	transform.matrix[0][0] = IntToxFixed(1);
+	transform.matrix[1][1] = IntToxFixed(1);
+	break;
+    case RR_Rotate_90:
+	transform.matrix[0][1] = IntToxFixed(-1);
+	transform.matrix[1][0] = IntToxFixed(1);
+	transform.matrix[0][2] += IntToxFixed(crtc->mode.VDisplay);
+	break;
+    case RR_Rotate_180:
+	transform.matrix[0][0] = IntToxFixed(-1);
+	transform.matrix[1][1] = IntToxFixed(-1);
+	transform.matrix[0][2] += IntToxFixed(crtc->mode.HDisplay);
+	transform.matrix[1][2] += IntToxFixed(crtc->mode.VDisplay);
+	break;
+    case RR_Rotate_270:
+	transform.matrix[0][1] = IntToxFixed(1);
+	transform.matrix[1][0] = IntToxFixed(-1);
+	transform.matrix[1][2] += IntToxFixed(crtc->mode.HDisplay);
+	break;
+    }
+
+    /* handle reflection */
+    if (crtc->rotation & RR_Reflect_X)
+    {
+	/* XXX figure this out */
+    }
+    if (crtc->rotation & RR_Reflect_Y)
+    {
+	/* XXX figure this out too */
+    }
+
+    error = SetPictureTransform (src, &transform);
+    if (error) {
+	ErrorF("Couldn't set transform\n");
+	return;
+    }
+
+    while (n--)
+    {
+	BoxRec	dst_box;
+
+	xf86RotateBox (&dst_box, b, crtc->rotation,
+		       crtc->mode.HDisplay, crtc->mode.VDisplay);
+	CompositePicture (PictOpSrc,
+			  src, NULL, dst,
+			  dst_box.x1, dst_box.y1, 0, 0, dst_box.x1, dst_box.y1,
+			  dst_box.x2 - dst_box.x1,
+			  dst_box.y2 - dst_box.y1);
+	b++;
+    }
+    FreePicture (src, None);
+    FreePicture (dst, None);
+}
+
+static void
+xf86RotateRedisplay(ScreenPtr pScreen)
+{
+    ScrnInfoPtr		pScrn = xf86Screens[pScreen->myNum];
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
+    DamagePtr		damage = xf86_config->rotationDamage;
+    RegionPtr		region;
+
+    if (!damage)
+	return;
+    region = DamageRegion(damage);
+    if (REGION_NOTEMPTY(pScreen, region)) 
+    {
+	int		    c;
+	
+	for (c = 0; c < xf86_config->num_crtc; c++)
+	{
+	    xf86CrtcPtr	    crtc = xf86_config->crtc[c];
+
+	    if (crtc->rotation != RR_Rotate_0)
+	    {
+		BoxRec	    box;
+		RegionRec   crtc_damage;
+
+		/* compute portion of damage that overlaps crtc */
+		box.x1 = crtc->x;
+		box.x2 = crtc->x + mode_width (&crtc->mode, crtc->rotation);
+		box.y1 = crtc->y;
+		box.y2 = crtc->y + mode_height (&crtc->mode, crtc->rotation);
+		REGION_INIT(pScreen, &crtc_damage, &box, 1);
+		REGION_INTERSECT (pScreen, &crtc_damage, &crtc_damage, region);
+		
+		/* update damaged region */
+		if (REGION_NOTEMPTY(pScreen, &crtc_damage))
+    		    xf86RotateCrtcRedisplay (crtc, &crtc_damage);
+		
+		REGION_UNINIT (pScreen, &crtc_damage);
+	    }
+	}
+	DamageEmpty(damage);
+    }
+}
+
+static void
+xf86RotateBlockHandler(pointer data, OSTimePtr pTimeout, pointer pRead)
+{
+    ScreenPtr pScreen = (ScreenPtr) data;
+
+    xf86RotateRedisplay(pScreen);
+}
+
+static void
+xf86RotateWakeupHandler(pointer data, int i, pointer LastSelectMask)
+{
+}
+
+Bool
+xf86CrtcRotate (xf86CrtcPtr crtc, DisplayModePtr mode, Rotation rotation)
+{
+    ScrnInfoPtr		pScrn = crtc->scrn;
+    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
+    ScreenPtr		pScreen = pScrn->pScreen;
+    
+    if (rotation == RR_Rotate_0)
+    {
+	/* Free memory from rotation */
+	if (crtc->rotatedPixmap)
+	{
+	    crtc->funcs->shadow_destroy (crtc, crtc->rotatedPixmap);
+	    crtc->rotatedPixmap = NULL;
+	}
+
+	if (xf86_config->rotationDamage)
+	{
+	    /* Free damage structure */
+	    DamageUnregister (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
+			      xf86_config->rotationDamage);
+	    DamageDestroy (xf86_config->rotationDamage);
+	    xf86_config->rotationDamage = NULL;
+	    /* Free block/wakeup handler */
+	    RemoveBlockAndWakeupHandlers (xf86RotateBlockHandler,
+					  xf86RotateWakeupHandler,
+					  (pointer) pScreen);
+	}
+    }
+    else
+    {
+	/* 
+	 * these are the size of the shadow pixmap, which
+	 * matches the mode, not the pre-rotated copy in the
+	 * frame buffer
+	 */
+	int	    width = mode->HDisplay;
+	int	    height = mode->VDisplay;
+	PixmapPtr   shadow = crtc->rotatedPixmap;
+	int	    old_width = shadow ? shadow->drawable.width : 0;
+	int	    old_height = shadow ? shadow->drawable.height : 0;
+	BoxRec	    damage_box;
+	RegionRec   damage_region;
+	
+	/* Allocate memory for rotation */
+	if (old_width != width || old_height != height)
+	{
+	    if (shadow)
+	    {
+		crtc->funcs->shadow_destroy (crtc, shadow);
+		crtc->rotatedPixmap = NULL;
+	    }
+	    shadow = crtc->funcs->shadow_create (crtc, width, height);
+	    if (!shadow)
+		goto bail1;
+	    crtc->rotatedPixmap = shadow;
+	}
+	
+	if (!xf86_config->rotationDamage)
+	{
+	    /* Create damage structure */
+	    xf86_config->rotationDamage = DamageCreate (NULL, NULL,
+						DamageReportNone,
+						TRUE, pScreen, pScreen);
+	    if (!xf86_config->rotationDamage)
+		goto bail2;
+	    
+	    /* Hook damage to screen pixmap */
+	    DamageRegister (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
+			    xf86_config->rotationDamage);
+	    
+	    /* Assign block/wakeup handler */
+	    if (!RegisterBlockAndWakeupHandlers (xf86RotateBlockHandler,
+						 xf86RotateWakeupHandler,
+						 (pointer) pScreen))
+	    {
+		goto bail3;
+	    }
+	    damage_box.x1 = 0;
+	    damage_box.y1 = 0;
+	    damage_box.x2 = mode_width (mode, rotation);
+	    damage_box.y2 = mode_height (mode, rotation);
+	    REGION_INIT (pScreen, &damage_region, &damage_box, 1);
+	    DamageDamageRegion (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
+				&damage_region);
+	    REGION_UNINIT (pScreen, &damage_region);
+	}
+	if (0)
+	{
+bail3:
+	    DamageDestroy (xf86_config->rotationDamage);
+	    xf86_config->rotationDamage = NULL;
+	    
+bail2:
+	    if (shadow)
+	    {
+		crtc->funcs->shadow_destroy (crtc, shadow);
+		crtc->rotatedPixmap = NULL;
+	    }
+bail1:
+	    if (old_width && old_height)
+		crtc->rotatedPixmap = crtc->funcs->shadow_create (crtc,
+								  old_width,
+								  old_height);
+	    return FALSE;
+	}
+    }
+    
+    /* All done */
+    return TRUE;
+}
diff --git a/hw/xfree86/modes/xf86cvt.c b/hw/xfree86/modes/xf86cvt.c
new file mode 100644
index 0000000..4256577
--- /dev/null
+++ b/hw/xfree86/modes/xf86cvt.c
@@ -0,0 +1,303 @@
+/*
+ * Copyright 2005-2006 Luc Verhaegen.
+ *
+ * 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 COPYRIGHT HOLDER(S) OR AUTHOR(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.
+ */
+
+/**
+ * @file This is a copy of xf86cvt.c from the X Server, for compatibility with
+ * old servers (pre-1.2).
+ */
+
+/*
+ * The reason for having this function in a file of its own is
+ * so that ../utils/cvt/cvt can link to it, and that xf86CVTMode
+ * code is shared directly.
+ */
+
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#include "xf86.h"
+
+#include <string.h>
+
+/*
+ * Generate a CVT standard mode from HDisplay, VDisplay and VRefresh.
+ *
+ * These calculations are stolen from the CVT calculation spreadsheet written
+ * by Graham Loveridge. He seems to be claiming no copyright and there seems to
+ * be no license attached to this. He apparently just wants to see his name
+ * mentioned.
+ *
+ * This file can be found at http://www.vesa.org/Public/CVT/CVTd6r1.xls
+ *
+ * Comments and structure corresponds to the comments and structure of the xls.
+ * This should ease importing of future changes to the standard (not very
+ * likely though).
+ *
+ * About margins; i'm sure that they are to be the bit between HDisplay and
+ * HBlankStart, HBlankEnd and HTotal, VDisplay and VBlankStart, VBlankEnd and 
+ * VTotal, where the overscan colour is shown. FB seems to call _all_ blanking
+ * outside sync "margin" for some reason. Since we prefer seeing proper
+ * blanking instead of the overscan colour, and since the Crtc* values will
+ * probably get altered after us, we will disable margins altogether. With
+ * these calculations, Margins will plainly expand H/VDisplay, and we don't
+ * want that. -- libv
+ *
+ */
+_X_EXPORT DisplayModePtr
+xf86CVTMode(int HDisplay, int VDisplay, float VRefresh, Bool Reduced,
+	    Bool Interlaced)
+{
+    DisplayModeRec  *Mode = xnfalloc(sizeof(DisplayModeRec));
+
+    /* 1) top/bottom margin size (% of height) - default: 1.8 */
+#define CVT_MARGIN_PERCENTAGE 1.8    
+
+    /* 2) character cell horizontal granularity (pixels) - default 8 */
+#define CVT_H_GRANULARITY 8
+
+    /* 4) Minimum vertical porch (lines) - default 3 */
+#define CVT_MIN_V_PORCH 3
+
+    /* 4) Minimum number of vertical back porch lines - default 6 */
+#define CVT_MIN_V_BPORCH 6
+
+    /* Pixel Clock step (kHz) */
+#define CVT_CLOCK_STEP 250
+
+    Bool Margins = FALSE;
+    float  VFieldRate, HPeriod;
+    int  HDisplayRnd, HMargin;
+    int  VDisplayRnd, VMargin, VSync;
+    float  Interlace; /* Please rename this */
+
+    memset(Mode, 0, sizeof(DisplayModeRec));
+
+    /* CVT default is 60.0Hz */
+    if (!VRefresh)
+        VRefresh = 60.0;
+
+    /* 1. Required field rate */
+    if (Interlaced)
+        VFieldRate = VRefresh * 2;
+    else
+        VFieldRate = VRefresh;
+
+    /* 2. Horizontal pixels */
+    HDisplayRnd = HDisplay - (HDisplay % CVT_H_GRANULARITY);
+
+    /* 3. Determine left and right borders */
+    if (Margins) {
+        /* right margin is actually exactly the same as left */
+        HMargin = (((float) HDisplayRnd) * CVT_MARGIN_PERCENTAGE / 100.0);
+        HMargin -= HMargin % CVT_H_GRANULARITY;
+    } else
+        HMargin = 0;
+
+    /* 4. Find total active pixels */
+    Mode->HDisplay = HDisplayRnd + 2*HMargin;
+
+    /* 5. Find number of lines per field */
+    if (Interlaced)
+        VDisplayRnd = VDisplay / 2;
+    else
+        VDisplayRnd = VDisplay;
+
+    /* 6. Find top and bottom margins */
+    /* nope. */
+    if (Margins)
+        /* top and bottom margins are equal again. */
+        VMargin = (((float) VDisplayRnd) * CVT_MARGIN_PERCENTAGE / 100.0);
+    else
+        VMargin = 0;
+
+    Mode->VDisplay = VDisplay + 2*VMargin;
+
+    /* 7. Interlace */
+    if (Interlaced)
+        Interlace = 0.5;
+    else
+        Interlace = 0.0;
+
+    /* Determine VSync Width from aspect ratio */
+    if (!(VDisplay % 3) && ((VDisplay * 4 / 3) == HDisplay))
+        VSync = 4;
+    else if (!(VDisplay % 9) && ((VDisplay * 16 / 9) == HDisplay))
+        VSync = 5;
+    else if (!(VDisplay % 10) && ((VDisplay * 16 / 10) == HDisplay))
+        VSync = 6;
+    else if (!(VDisplay % 4) && ((VDisplay * 5 / 4) == HDisplay))
+        VSync = 7;
+    else if (!(VDisplay % 9) && ((VDisplay * 15 / 9) == HDisplay))
+        VSync = 7;
+    else /* Custom */
+        VSync = 10;
+
+    if (!Reduced) { /* simplified GTF calculation */
+
+        /* 4) Minimum time of vertical sync + back porch interval (µs) 
+         * default 550.0 */
+#define CVT_MIN_VSYNC_BP 550.0
+
+        /* 3) Nominal HSync width (% of line period) - default 8 */
+#define CVT_HSYNC_PERCENTAGE 8
+
+        float  HBlankPercentage;
+        int  VSyncAndBackPorch, VBackPorch;
+        int  HBlank;
+
+        /* 8. Estimated Horizontal period */
+        HPeriod = ((float) (1000000.0 / VFieldRate - CVT_MIN_VSYNC_BP)) / 
+            (VDisplayRnd + 2 * VMargin + CVT_MIN_V_PORCH + Interlace);
+
+        /* 9. Find number of lines in sync + backporch */
+        if (((int)(CVT_MIN_VSYNC_BP / HPeriod) + 1) < (VSync + CVT_MIN_V_PORCH))
+            VSyncAndBackPorch = VSync + CVT_MIN_V_PORCH;
+        else
+            VSyncAndBackPorch = (int)(CVT_MIN_VSYNC_BP / HPeriod) + 1;
+
+        /* 10. Find number of lines in back porch */
+        VBackPorch = VSyncAndBackPorch - VSync;
+
+        /* 11. Find total number of lines in vertical field */
+        Mode->VTotal = VDisplayRnd + 2 * VMargin + VSyncAndBackPorch + Interlace
+            + CVT_MIN_V_PORCH;
+
+        /* 5) Definition of Horizontal blanking time limitation */
+        /* Gradient (%/kHz) - default 600 */
+#define CVT_M_FACTOR 600
+
+        /* Offset (%) - default 40 */
+#define CVT_C_FACTOR 40
+
+        /* Blanking time scaling factor - default 128 */
+#define CVT_K_FACTOR 128
+
+        /* Scaling factor weighting - default 20 */
+#define CVT_J_FACTOR 20
+
+#define CVT_M_PRIME CVT_M_FACTOR * CVT_K_FACTOR / 256
+#define CVT_C_PRIME (CVT_C_FACTOR - CVT_J_FACTOR) * CVT_K_FACTOR / 256 + \
+        CVT_J_FACTOR
+
+        /* 12. Find ideal blanking duty cycle from formula */
+        HBlankPercentage = CVT_C_PRIME - CVT_M_PRIME * HPeriod/1000.0;
+
+        /* 13. Blanking time */
+        if (HBlankPercentage < 20)
+            HBlankPercentage = 20;
+
+        HBlank = Mode->HDisplay * HBlankPercentage/(100.0 - HBlankPercentage);
+        HBlank -= HBlank % (2*CVT_H_GRANULARITY);
+        
+        /* 14. Find total number of pixels in a line. */
+        Mode->HTotal = Mode->HDisplay + HBlank;
+
+        /* Fill in HSync values */
+        Mode->HSyncEnd = Mode->HDisplay + HBlank / 2;
+
+        Mode->HSyncStart = Mode->HSyncEnd - 
+            (Mode->HTotal * CVT_HSYNC_PERCENTAGE) / 100;
+        Mode->HSyncStart += CVT_H_GRANULARITY - 
+            Mode->HSyncStart % CVT_H_GRANULARITY;
+
+        /* Fill in VSync values */
+        Mode->VSyncStart = Mode->VDisplay + CVT_MIN_V_PORCH;
+        Mode->VSyncEnd = Mode->VSyncStart + VSync;
+
+    } else { /* Reduced blanking */
+        /* Minimum vertical blanking interval time (µs) - default 460 */
+#define CVT_RB_MIN_VBLANK 460.0
+
+        /* Fixed number of clocks for horizontal sync */
+#define CVT_RB_H_SYNC 32.0
+
+        /* Fixed number of clocks for horizontal blanking */
+#define CVT_RB_H_BLANK 160.0
+
+        /* Fixed number of lines for vertical front porch - default 3 */
+#define CVT_RB_VFPORCH 3
+
+        int  VBILines;
+
+        /* 8. Estimate Horizontal period. */
+        HPeriod = ((float) (1000000.0 / VFieldRate - CVT_RB_MIN_VBLANK)) / 
+            (VDisplayRnd + 2*VMargin);
+
+        /* 9. Find number of lines in vertical blanking */
+        VBILines = ((float) CVT_RB_MIN_VBLANK) / HPeriod + 1;
+
+        /* 10. Check if vertical blanking is sufficient */
+        if (VBILines < (CVT_RB_VFPORCH + VSync + CVT_MIN_V_BPORCH))
+            VBILines = CVT_RB_VFPORCH + VSync + CVT_MIN_V_BPORCH;
+        
+        /* 11. Find total number of lines in vertical field */
+        Mode->VTotal = VDisplayRnd + 2 * VMargin + Interlace + VBILines;
+
+        /* 12. Find total number of pixels in a line */
+        Mode->HTotal = Mode->HDisplay + CVT_RB_H_BLANK;
+
+        /* Fill in HSync values */
+        Mode->HSyncEnd = Mode->HDisplay + CVT_RB_H_BLANK / 2;
+        Mode->HSyncStart = Mode->HSyncEnd - CVT_RB_H_SYNC;
+
+        /* Fill in VSync values */
+        Mode->VSyncStart = Mode->VDisplay + CVT_RB_VFPORCH;
+        Mode->VSyncEnd = Mode->VSyncStart + VSync;
+    }
+
+    /* 15/13. Find pixel clock frequency (kHz for xf86) */
+    Mode->Clock = Mode->HTotal * 1000.0 / HPeriod;
+    Mode->Clock -= Mode->Clock % CVT_CLOCK_STEP;
+
+    /* 16/14. Find actual Horizontal Frequency (kHz) */
+    Mode->HSync = ((float) Mode->Clock) / ((float) Mode->HTotal);
+
+    /* 17/15. Find actual Field rate */
+    Mode->VRefresh = (1000.0 * ((float) Mode->Clock)) / 
+        ((float) (Mode->HTotal * Mode->VTotal));
+
+    /* 18/16. Find actual vertical frame frequency */
+    /* ignore - just set the mode flag for interlaced */
+    if (Interlaced)
+        Mode->VTotal *= 2;
+
+    {
+        char  Name[256];
+        Name[0] = 0;
+
+        snprintf(Name, 256, "%dx%d", HDisplay, VDisplay);
+
+        Mode->name = xnfalloc(strlen(Name) + 1);
+        memcpy(Mode->name, Name, strlen(Name) + 1);
+    }
+
+    if (Reduced)
+        Mode->Flags |= V_PHSYNC | V_NVSYNC;
+    else
+        Mode->Flags |= V_NHSYNC | V_PVSYNC;
+
+    if (Interlaced)
+        Mode->Flags |= V_INTERLACE;
+
+    return Mode;
+}
diff --git a/hw/xfree86/ramdac/xf86Cursor.c b/hw/xfree86/ramdac/xf86Cursor.c
index a903f7f..4578076 100644
--- a/hw/xfree86/ramdac/xf86Cursor.c
+++ b/hw/xfree86/ramdac/xf86Cursor.c
@@ -199,10 +199,11 @@ xf86CursorEnableDisableFBAccess(
 	pScreen->devPrivates[xf86CursorScreenIndex].ptr;
 
     if (!enable && ScreenPriv->CurrentCursor != NullCursor) {
-	ScreenPriv->SavedCursor = ScreenPriv->CurrentCursor;
+	CursorPtr   currentCursor = ScreenPriv->CurrentCursor;
 	xf86CursorSetCursor(pScreen, NullCursor, ScreenPriv->x, ScreenPriv->y);
 	ScreenPriv->isUp = FALSE;
 	ScreenPriv->SWCursor = TRUE;
+	ScreenPriv->SavedCursor = currentCursor;
     }
 
     if (ScreenPriv->EnableDisableFBAccess)
diff-tree 37fe4c49dc3a5faf2d3d56112b6bd78453045f6a (from c2f3f705f1db8ca78292912544a7e416116175f3)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Fri Feb 16 09:57:57 2007 +1030

    mi:     Move WarpPointer event generation to miPointerMove to avoid duplicate
            events, cache event array allocation.

diff --git a/mi/mipointer.c b/mi/mipointer.c
index c28911b..b94feaa 100644
--- a/mi/mipointer.c
+++ b/mi/mipointer.c
@@ -70,6 +70,8 @@ static Bool miPointerSetCursorPosition(S
 static Bool miPointerCloseScreen(int index, ScreenPtr pScreen);
 static void miPointerMove(ScreenPtr pScreen, int x, int y, unsigned long time);
 
+static xEvent* events; /* for WarpPointer MotionNotifies */
+
 _X_EXPORT Bool
 miPointerInitialize (pScreen, spriteFuncs, screenFuncs, waitForUpdate)
     ScreenPtr		    pScreen;
@@ -128,6 +130,9 @@ miPointerInitialize (pScreen, spriteFunc
     miPointer.confined = FALSE;
     miPointer.x = 0;
     miPointer.y = 0;
+
+    events = NULL;
+
     return TRUE;
 }
 
@@ -144,6 +149,8 @@ miPointerCloseScreen (index, pScreen)
 	miPointer.pSpriteScreen = 0;
     pScreen->CloseScreen = pScreenPriv->CloseScreen;
     xfree ((pointer) pScreenPriv);
+    xfree ((pointer) events);
+    events = NULL;
     return (*pScreen->CloseScreen) (index, pScreen);
 }
 
@@ -466,7 +473,31 @@ miPointerGetPosition(DeviceIntPtr pDev, 
 void
 miPointerMove (ScreenPtr pScreen, int x, int y, unsigned long time)
 {
+    int i, nevents;
+    int valuators[2];
+
     miPointerMoved(inputInfo.pointer, pScreen, x, y, time);
+
+    /* generate motion notify */
+    valuators[0] = x;
+    valuators[1] = y;
+
+    if (!events)
+    {
+        events = (xEvent*)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
+
+        if (!events)
+        {
+            FatalError("Could not allocate event store.\n");
+            return;
+        }
+    }
+
+    nevents = GetPointerEvents(events, inputInfo.pointer, MotionNotify, 0,
+                               POINTER_ABSOLUTE, 0, 2, valuators);
+
+    for (i = 0; i < nevents; i++)
+        mieqEnqueue(inputInfo.pointer, &events[i]);
 }
 
 /* Move the pointer on the current screen,  and update the sprite. */
@@ -474,10 +505,6 @@ void
 miPointerMoved (DeviceIntPtr pDev, ScreenPtr pScreen, int x, int y,
                      unsigned long time)
 {
-    xEvent* events;
-    int i, nevents;
-    int valuators[2];
-
     SetupScreen(pScreen);
 
     if (pDev && (pDev->coreEvents || pDev == inputInfo.pointer) &&
@@ -492,23 +519,4 @@ miPointerMoved (DeviceIntPtr pDev, Scree
     miPointer.x = x;
     miPointer.y = y;
     miPointer.pScreen = pScreen;
-
-    /* generate motion notify */
-    valuators[0] = x;
-    valuators[1] = y;
-
-    events = (xEvent*)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
-    if (!events)
-    {
-        FatalError("Could not allocate event store.\n");
-        return;
-    }
-
-    nevents = GetPointerEvents(events, pDev, MotionNotify, 0,
-                               POINTER_ABSOLUTE, 0, 2, valuators);
-
-    for (i = 0; i < nevents; i++)
-        mieqEnqueue(pDev, &events[i]);
-
-    xfree(events);
 }
diff-tree c2f3f705f1db8ca78292912544a7e416116175f3 (from 811675733e97416c990e6dc9c19271b43d96248d)
Author: Eamon Walsh <ewalsh at tycho.nsa.gov>
Date:   Thu Feb 15 14:38:24 2007 -0500

    Bug #6988: Change behavior of Security extension per user feature request.

diff --git a/Xext/security.c b/Xext/security.c
index bd397a9..7202d39 100644
--- a/Xext/security.c
+++ b/Xext/security.c
@@ -1187,6 +1187,7 @@ CALLBACK(SecurityCheckMapAccess)
     if (STATEPTR(rec->client) &&
 	(TRUSTLEVEL(rec->client) != XSecurityClientTrusted) &&
 	(pWin->drawable.class == InputOnly) &&
+	pWin->parent && pWin->parent->parent &&
 	(TRUSTLEVEL(wClient(pWin->parent)) == XSecurityClientTrusted))
 
 	rec->rval = FALSE;
diff-tree 811675733e97416c990e6dc9c19271b43d96248d (from 8f6961d385bda92703f18090cff551409d2710c9)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Thu Feb 15 19:09:00 2007 +0200

    os: fix client privates leak
    Minor leak here.  Oops.

diff --git a/os/connection.c b/os/connection.c
index ffe911e..d0ffb81 100644
--- a/os/connection.c
+++ b/os/connection.c
@@ -1066,6 +1066,8 @@ CloseDownConnection(ClientPtr client)
     XdmcpCloseDisplay(oc->fd);
 #endif
     CloseDownFileDescriptor(oc);
+    FreeOsBuffers(oc);
+    xfree(client->osPrivate);
     client->osPrivate = (pointer)NULL;
     if (auditTrailLevel > 1)
 	AuditF("client %d disconnected\n", client->index);
diff-tree 8f6961d385bda92703f18090cff551409d2710c9 (from a3b62623b8aac56b219633bdb2c2f6de19b0580b)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Thu Feb 15 19:08:46 2007 +0200

    configure.ac: add xdarwin stubs
    Add stub AM_CONDITIONALs to at least fix the build.

diff --git a/configure.ac b/configure.ac
index 9611065..afbf980 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1737,6 +1737,11 @@ AM_CONDITIONAL(XFAKESERVER, [test "x$KDR
 AM_CONDITIONAL(KDRIVEVESA, [test x"$ac_cv_header_sys_vm86_h" = xyes])
 AM_CONDITIONAL(KDRIVEFBDEV, [test x"$ac_cv_header_linux_fb_h" = xyes])
 
+dnl XDarwin DDX (FIXME)
+AM_CONDITIONAL(XQUARTZ, false)
+AM_CONDITIONAL(HAVE_X_PLUGIN, false)
+AM_CONDITIONAL(HAVE_AGL_FRAMEWORK, false)
+
 dnl these only go in xkb-config.h (which is shared by the Xorg and Xnest servers)
 AC_DEFINE(__XKBDEFRULES__, "xorg", [Default XKB rules])
 AC_DEFINE_DIR(XKB_BASE_DIRECTORY, XKBPATH, [Path to XKB data])
diff-tree a3b62623b8aac56b219633bdb2c2f6de19b0580b (from 0f6dd4aea6176507dbe1c90c950d332fecbcaacb)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Thu Feb 15 17:07:42 2007 +0200

    change versioning for new server version scheme
    See:
    http://xorg.freedesktop.org/wiki/XDC2007Notes#head-2719037a1905516c45cf74f0e155c8703221e446

diff --git a/configure.ac b/configure.ac
index 92dc5c9..9611065 100644
--- a/configure.ac
+++ b/configure.ac
@@ -25,7 +25,7 @@ dnl Process this file with autoconf to c
 AC_PREREQ(2.57)
 dnl This is the not the Xorg version number, it's the server version number.
 dnl Yes, that's weird.
-AC_INIT([xorg-server], 1.2.99.0, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.3.99.0, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
 AC_CONFIG_SRCDIR([Makefile.am])
 AM_INIT_AUTOMAKE([dist-bzip2 foreign])
 AM_MAINTAINER_MODE
diff-tree 0f6dd4aea6176507dbe1c90c950d332fecbcaacb (from 9ecf79ca0111dd899ca88dd54156f71013220fcc)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Thu Feb 15 16:14:57 2007 +0200

    kdrive/ephyr: free screen struct
    Free screen->driver on screenFini, instead of just leaking it.

diff --git a/hw/kdrive/ephyr/ephyr.c b/hw/kdrive/ephyr/ephyr.c
index 2ca51c3..e8001df 100644
--- a/hw/kdrive/ephyr/ephyr.c
+++ b/hw/kdrive/ephyr/ephyr.c
@@ -675,6 +675,8 @@ ephyrRestore (KdCardInfo *card)
 void
 ephyrScreenFini (KdScreenInfo *screen)
 {
+    xfree(screen->driver);
+    screen->driver = NULL;
 }
 
 /*  
diff-tree 9ecf79ca0111dd899ca88dd54156f71013220fcc (from 136bb4874aadf4a731d7eb8671e8bb641f9980a7)
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Feb 15 05:22:21 2007 -0800

    Beginnings of an update Darwin driver

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 542bfdb..7efd056 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -1,52 +1,249 @@
+noinst_LIBRARIES = libdarwinShared.a
+libdarwin_XINPUT_SRCS = darwinXinput.c
+
+AM_CFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
+AM_CPPFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
+INCLUDES = @XORG_INCS@
+
+DEFS = @DEFS@ -DUSE_NEW_CLUT
+
+if XQUARTZ
+XQUARTZ_SUBDIRS = bundle quartz
+endif
+
+SUBDIRS = \
+	  iokit \
+	  $(XQUARTZ_SUBDIRS) \
+	  utils \
+	  .
+
+
+darwinappdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app
+
+
+libdarwinShared_a_SOURCES = darwin.c \
+			  darwinEvents.c \
+			  darwinKeyboard.c \
+			  $(darwin_XINPUT_SRCS) 
+
+bin_PROGRAMS = XDarwin
+XDarwin_SOURCES = \
+                  $(top_srcdir)/fb/fbcmap.c \
+                  $(top_srcdir)/mi/miinitext.c \
+                  $(top_srcdir)/Xi/stubs.c
+XDarwin_LDADD = \
+		$(top_builddir)/dix/dixfonts.lo \
+		$(top_builddir)/dix/libdix.la \
+		$(top_builddir)/config/libconfig.a \
+		$(top_builddir)/os/libos.la \
+		./libdarwinShared.a \
+		./iokit/libiokit.a \
+		$(top_builddir)/dix/libxpstubs.la \
+		$(top_builddir)/miext/shadow/libshadow.la \
+		$(top_builddir)/fb/libfb.la \
+		$(top_builddir)/composite/libcomposite.la \
+		$(top_builddir)/damageext/libdamageext.la \
+		$(top_builddir)/miext/damage/libdamage.la \
+		$(top_builddir)/xfixes/libxfixes.la \
+		$(top_builddir)/miext/cw/libcw.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 \
+		$(XGLX_LIBS) \
+		$(top_builddir)/miext/rootless/librootless.la \
+		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
+		$(top_builddir)/miext/rootless/accel/librlAccel.la \
+		@XORG_LIBS@ \
+		-lXau -lXdmcp -lXfont -lfreetype
+
+XDarwin_LDFLAGS =  \
+		 -XCClinker -Objc \
+		 -Wl,-u,_miDCInitialize \
+		 -Wl,-framework,IOKit
+
+XDarwin_CFLAGS = -DINXDARWIN
+if XQUARTZ
+macosdir = $(darwinappdir)/Contents/MacOS
+
+DEFS += -DDARWIN_WITH_QUARTZ -DXFree86Server
+
+macos_PROGRAMS = XDarwinApp
+
+XDarwinApp_SOURCES = \
+               	$(top_srcdir)/fb/fbcmap.c \
+               	$(top_srcdir)/mi/miinitext.c \
+		$(top_srcdir)/Xi/stubs.c 
+
+XDarwinApp_LDADD = \
+		$(top_builddir)/dix/dixfonts.lo \
+		$(top_builddir)/dix/libdix.la \
+		$(top_builddir)/config/libconfig.a \
+		$(top_builddir)/os/libos.la \
+		./quartz/XApplication.o \
+		./libdarwinShared.a \
+		./quartz/libXQuartz.a \
+		$(top_builddir)/dix/libxpstubs.la \
+		 $(top_builddir)/miext/shadow/libshadow.la \
+		 $(top_builddir)/fb/libfb.la \
+		 $(top_builddir)/composite/libcomposite.la \
+		 $(top_builddir)/damageext/libdamageext.la \
+		 $(top_builddir)/miext/damage/libdamage.la \
+		 $(top_builddir)/xfixes/libxfixes.la \
+		 $(top_builddir)/miext/cw/libcw.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 \
+		 $(XGLX_LIBS) \
+		 $(top_builddir)/miext/rootless/librootless.la \
+		 $(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
+		 $(top_builddir)/miext/rootless/accel/librlAccel.la \
+		 @XORG_LIBS@ \
+		 -lXau -lXdmcp -lXfont -lfreetype \
+		 $(top_builddir)/fb/libfb.la 
+
+XDarwinApp_LDFLAGS =  \
+		 -XCClinker -Objc \
+		 -Wl,-u,_miDCInitialize \
+		 -Wl,-framework,Carbon \
+		 -Wl,-framework,ApplicationServices \
+		 -Wl,-framework,Cocoa \
+		 -Wl,-framework,CoreAudio \
+		 -Wl,-framework,IOKit
+
+HOOK_TARGETS = xquartz-install-hook
+
+
+crplugindir = $(darwinappdir)/Contents/Resources/cr.bundle/Contents/MacOS
+crplugin_LTLIBRARIES = cr.la
+cr_la_SOURCES =
+cr_la_LIBADD = \
+		quartz/cr/crAppleWM.o \
+		quartz/cr/crFrame.o \
+		quartz/cr/crScreen.o \
+		quartz/fullscreen/quartzCursor.o \
+		quartz/cr/XView.o \
+		$(top_builddir)/miext/rootless/librootless.la \
+		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
+		$(top_builddir)/miext/rootless/accel/librlAccel.la
+cr_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
+		-Wl,-framework,Cocoa \
+		-Wl,-framework,Carbon \
+		-XCClinker -ObjC \
+		-XCClinker -bundle_loader -XCClinker XDarwinApp \
+		-module -avoid-version -no-undefined
+cr_la_DEPENDENCIES = XDarwinApp	
+
+fullscreenplugindir = $(darwinappdir)/Contents/Resources/fullscreen.bundle/Contents/MacOS
+fullscreenplugin_LTLIBRARIES = fullscreen.la
+fullscreen_la_SOURCES =
+fullscreen_la_LIBADD = \
+		quartz/fullscreen/fullscreen.o \
+		quartz/fullscreen/quartzCursor.o \
+		$(top_builddir)/miext/shadow/libshadow.la
+
+fullscreen_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
+		-XCClinker -bundle_loader -XCClinker XDarwinApp \
+		-module -avoid-version -no-undefined
+fullscreen_la_DEPENDENCIES = XDarwinApp	
+
+if GLX
+glxMesaplugindir = $(darwinappdir)/Contents/Resources/glxMesa.bundle/Contents/MacOS
+glxMesaplugin_LTLIBRARIES = glxMesa.la
+glxMesa_la_SOURCES =
+glxMesa_la_LIBADD = \
+		$(top_builddir)/GL/glx/libglx.la \
+		$(top_builddir)/GL/mesa/libGLcore.la 
+glxMesa_la_LDFLAGS = -shrext '' \
+		-Wl,-framework,AGL \
+		-Wl,-framework,OpenGL \
+		-XCClinker -ObjC \
+		-XCClinker -bundle_loader -XCClinker XDarwinApp \
+		-module -avoid-version -no-undefined
+glxMesa_la_DEPENDENCIES = XDarwinApp	
+endif
+
+endif
+if HAVE_X_PLUGIN
+
+xprplugindir = $(darwinappdir)/Contents/Resources/xpr.bundle/Contents/MacOS
+xprplugin_LTLIBRARIES = xpr.la
+xpr_la_SOURCES =
+xpr_la_LIBADD = \
+		quartz/xpr/appledri.o \
+		quartz/xpr/dri.o \
+		quartz/xpr/xprAppleWM.o \
+		quartz/xpr/xprCursor.o \
+		quartz/xpr/xprFrame.o \
+		quartz/xpr/xprScreen.o \
+		quartz/xpr/x-hash.o \
+		quartz/xpr/x-hook.o \
+		quartz/xpr/x-list.o \
+		$(top_builddir)/miext/rootless/librootless.la \
+		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
+		$(top_builddir)/miext/rootless/accel/librlAccel.la
+xpr_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
+		-lXplugin \
+		-XCClinker -bundle_loader -XCClinker XDarwinApp \
+		-module -avoid-version -no-undefined
+xpr_la_DEPENDENCIES = XDarwinApp	
+
+endif
+
+if HAVE_AGL_FRAMEWORK
+glxCGLplugindir = $(darwinappdir)/Contents/Resources/glxCGL.bundle/Contents/MacOS
+glxCGLplugin_LTLIBRARIES = glxCGL.la
+glxCGL_la_SOURCES =
+glxCGL_la_LIBADD = \
+		$(top_builddir)/GL/glx/glxext.o \
+		$(top_builddir)/GL/glx/libglx.a \
+		$(top_builddir)/GL/apple/libAGLcore.a
+glxCGL_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
+		-Wl,-framework,AGL \
+		-Wl,-framework,OpenGL \
+		-XCClinker -ObjC \
+		-XCClinker -bundle_loader -XCClinker XDarwinApp \
+		-module -avoid-version -no-undefined
+glxCGL_la_DEPENDENCIES = XDarwinApp	
+
+
+glxAGLplugindir = $(darwinappdir)/Contents/Resources/glxAGL.bundle/Contents/MacOS
+glxAGLplugin_LTLIBRARIES = glxAGL.la
+glxAGL_la_SOURCES =
+glxAGL_la_LIBADD = \
+		$(top_builddir)/GL/glx/glxext.o \
+		$(top_builddir)/GL/glx/libglx.a \
+		$(top_builddir)/GL/apple/libAGLcore.a
+glxAGL_la_LDFLAGS = -shrext '' \
+		-Wl,-framework,AGL \
+		-Wl,-framework,OpenGL \
+		-XCClinker -ObjC \
+		-XCClinker -bundle_loader -XCClinker XDarwinApp \
+		-module -avoid-version -no-undefined
+glxAGL_la_DEPENDENCIES = XDarwinApp	
+
+
+
+endif
+
+man1_MANS = XDarwin.man
+
+uninstall-hook:
+	rm -rf $(DESTDIR)$(macosdir)/XDarwin
+
+install-data-hook: $(HOOK_TARGETS)
+
+xquartz-install-hook:
+	mv $(DESTDIR)$(macosdir)/XDarwinApp $(DESTDIR)$(macosdir)/XDarwin
+
 EXTRA_DIST = \
-	bundle/Dutch.lproj/Credits.rtf \
-	bundle/Dutch.lproj/Localizable.strings \
-	bundle/Dutch.lproj/MainMenu.nib/classes.nib \
-	bundle/Dutch.lproj/MainMenu.nib/objects.nib \
-	bundle/Dutch.lproj/XDarwinHelp.html.cpp \
-	bundle/English.lproj/Credits.rtf \
-	bundle/English.lproj/InfoPlist.strings.cpp \
-	bundle/English.lproj/Localizable.strings \
-	bundle/English.lproj/MainMenu.nib/classes.nib \
-	bundle/English.lproj/MainMenu.nib/objects.nib \
-	bundle/English.lproj/XDarwinHelp.html.cpp \
-	bundle/French.lproj/Credits.rtf \
-	bundle/French.lproj/Localizable.strings \
-	bundle/French.lproj/MainMenu.nib/classes.nib \
-	bundle/French.lproj/MainMenu.nib/objects.nib \
-	bundle/French.lproj/XDarwinHelp.html.cpp \
-	bundle/German.lproj/Credits.rtf \
-	bundle/German.lproj/Localizable.strings \
-	bundle/German.lproj/MainMenu.nib/classes.nib \
-	bundle/German.lproj/MainMenu.nib/objects.nib \
-	bundle/German.lproj/XDarwinHelp.html.cpp \
-	bundle/Japanese.lproj/Credits.rtf \
-	bundle/Japanese.lproj/Localizable.strings \
-	bundle/Japanese.lproj/MainMenu.nib/classes.nib \
-	bundle/Japanese.lproj/MainMenu.nib/objects.nib \
-	bundle/Japanese.lproj/XDarwinHelp.html.cpp \
-	bundle/ko.lproj/Credits.rtf \
-	bundle/ko.lproj/Localizable.strings \
-	bundle/ko.lproj/MainMenu.nib/classes.nib \
-	bundle/ko.lproj/MainMenu.nib/objects.nib \
-	bundle/ko.lproj/XDarwinHelp.html.cpp \
-	bundle/Portuguese.lproj/Credits.rtf \
-	bundle/Portuguese.lproj/Localizable.strings \
-	bundle/Portuguese.lproj/MainMenu.nib/classes.nib \
-	bundle/Portuguese.lproj/MainMenu.nib/objects.nib \
-	bundle/Portuguese.lproj/XDarwinHelp.html.cpp \
-	bundle/Spanish.lproj/Credits.rtf \
-	bundle/Spanish.lproj/Localizable.strings \
-	bundle/Spanish.lproj/MainMenu.nib/classes.nib \
-	bundle/Spanish.lproj/MainMenu.nib/objects.nib \
-	bundle/Spanish.lproj/XDarwinHelp.html.cpp \
-	bundle/startXClients.cpp \
-	bundle/Swedish.lproj/Credits.rtf \
-	bundle/Swedish.lproj/Localizable.strings \
-	bundle/Swedish.lproj/MainMenu.nib/classes.nib \
-	bundle/Swedish.lproj/MainMenu.nib/objects.nib \
-	bundle/Swedish.lproj/XDarwinHelp.html.cpp \
-	bundle/XDarwin.icns \
 	darwin.c \
 	darwinClut8.h \
 	darwinEvents.c \
@@ -54,64 +251,4 @@ EXTRA_DIST = \
 	darwinKeyboard.c \
 	darwinKeyboard.h \
 	darwinXinput.c \
-	iokit/xfIOKit.c \
-	iokit/xfIOKitCursor.c \
-	iokit/xfIOKit.h \
-	iokit/xfIOKitStartup.c \
-	Makefile.am \
-	quartz/applewm.c \
-	quartz/applewmExt.h \
-	quartz/cr/crAppleWM.m \
-	quartz/cr/crFrame.m \
-	quartz/cr/cr.h \
-	quartz/cr/crScreen.m \
-	quartz/cr/XView.h \
-	quartz/cr/XView.m \
-	quartz/fullscreen/fullscreen.c \
-	quartz/fullscreen/quartzCursor.c \
-	quartz/fullscreen/quartzCursor.h \
-	quartz/keysym2ucs.c \
-	quartz/keysym2ucs.h \
-	quartz/Preferences.h \
-	quartz/Preferences.m \
-	quartz/pseudoramiX.c \
-	quartz/pseudoramiX.h \
-	quartz/quartzAudio.c \
-	quartz/quartzAudio.h \
-	quartz/quartz.c \
-	quartz/quartzCocoa.m \
-	quartz/quartzCommon.h \
-	quartz/quartzCursor.c \
-	quartz/quartzCursor.h \
-	quartz/quartz.h \
-	quartz/quartzKeyboard.c \
-	quartz/quartzPasteboard.c \
-	quartz/quartzPasteboard.h \
-	quartz/quartzStartup.c \
-	quartz/XApplication.h \
-	quartz/XApplication.m \
-	quartz/XDarwin.pbproj/project.pbxproj \
-	quartz/XDarwinStartup.c \
-	quartz/XDarwinStartup.man \
-	quartz/xpr/appledri.c \
-	quartz/xpr/dri.c \
-	quartz/xpr/dri.h \
-	quartz/xpr/dristruct.h \
-	quartz/xpr/x-hash.c \
-	quartz/xpr/x-hash.h \
-	quartz/xpr/x-hook.c \
-	quartz/xpr/x-hook.h \
-	quartz/xpr/x-list.c \
-	quartz/xpr/x-list.h \
-	quartz/xpr/Xplugin.h \
-	quartz/xpr/xprAppleWM.c \
-	quartz/xpr/xprCursor.c \
-	quartz/xpr/xprFrame.c \
-	quartz/xpr/xpr.h \
-	quartz/xpr/xprScreen.c \
-	quartz/XServer.h \
-	quartz/XServer.m \
-	utils/dumpkeymap.c \
-	utils/dumpkeymap.man \
-	utils/README.txt \
 	XDarwin.man
diff --git a/hw/darwin/darwin.c b/hw/darwin/darwin.c
index bd99989..e33c321 100644
--- a/hw/darwin/darwin.c
+++ b/hw/darwin/darwin.c
@@ -30,6 +30,10 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
 #include <X11/X.h>
 #include <X11/Xproto.h>
 #include "os.h"
@@ -409,9 +413,9 @@ static int DarwinMouseProc(
             InitPointerDeviceStruct( (DevicePtr)pPointer,
                         map,
                         5,   // numbuttons (4 & 5 are scroll wheel)
-                        miPointerGetMotionEvents,
+                        GetMotionHistory,
                         DarwinChangePointerControl,
-                        0 );
+                        GetMotionHistorySize(), 2 );
 #ifdef XINPUT
             InitValuatorAxisStruct( pPointer,
                                     0,     // X axis
diff --git a/hw/darwin/darwin.h b/hw/darwin/darwin.h
index cd57225..48a2224 100644
--- a/hw/darwin/darwin.h
+++ b/hw/darwin/darwin.h
@@ -31,6 +31,7 @@
 #include "inputstr.h"
 #include "scrnintstr.h"
 #include <X11/extensions/XKB.h>
+#include <assert.h>
 
 typedef struct {
     void                *framebuffer;
diff --git a/hw/darwin/darwinKeyboard.c b/hw/darwin/darwinKeyboard.c
index 1cc49fe..4e7a136 100644
--- a/hw/darwin/darwinKeyboard.c
+++ b/hw/darwin/darwinKeyboard.c
@@ -72,7 +72,7 @@
 #include <architecture/byte_order.h>  // For the NXSwap*
 #include "darwin.h"
 #include "darwinKeyboard.h"
-
+#include <assert.h>
 #define AltMask         Mod1Mask
 #define MetaMask        Mod2Mask
 #define FunctionMask    Mod3Mask
diff --git a/hw/darwin/darwinKeyboard.h b/hw/darwin/darwinKeyboard.h
index f4a8611..368aee9 100644
--- a/hw/darwin/darwinKeyboard.h
+++ b/hw/darwin/darwinKeyboard.h
@@ -29,7 +29,7 @@
 
 #define XK_TECHNICAL		// needed to get XK_Escape
 #define XK_PUBLISHING
-#include "keysym.h"
+#include "X11/keysym.h"
 #include "inputstr.h"
 
 // Each key can generate 4 glyphs. They are, in order:
diff-tree 136bb4874aadf4a731d7eb8671e8bb641f9980a7 (from 3ead1afe78d2913f08c8144cb2d3813c6b159488)
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Feb 15 05:14:38 2007 -0800

    iokit support for XDarwin

diff --git a/hw/darwin/iokit/Makefile.am b/hw/darwin/iokit/Makefile.am
new file mode 100644
index 0000000..54464ae
--- /dev/null
+++ b/hw/darwin/iokit/Makefile.am
@@ -0,0 +1,17 @@
+noinst_LIBRARIES = libiokit.a
+
+AM_CFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
+INCLUDES = -I. -I.. -I$(srcdir) -I$(srcdir)/.. @XORG_INCS@
+AM_DEFS =
+if XQUARTZ
+AM_DEFS += -DDARWIN_WITH_QUARTZ -DXFree86Server
+XQUARTZ_SUBDIRS = bundle quartz
+endif
+DEFS = @DEFS@ $(AM_DEFS)
+
+libiokit_a_SOURCES = xfIOKit.c \
+	           xfIOKitCursor.c \
+	           xfIOKitStartup.c
+
+EXTRA_DIST = \
+	xfIOKit.h
diff --git a/hw/darwin/iokit/xfIOKit.c b/hw/darwin/iokit/xfIOKit.c
index 95a7fb3..c7ebd1c 100644
--- a/hw/darwin/iokit/xfIOKit.c
+++ b/hw/darwin/iokit/xfIOKit.c
@@ -34,6 +34,10 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#if HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
 #include <X11/X.h>
 #include <X11/Xproto.h>
 #include "os.h"
@@ -51,6 +55,7 @@
 #include <unistd.h>
 #include <fcntl.h>
 #include <pthread.h>
+#include <assert.h>
 
 #include <mach/mach_interface.h>
 
diff --git a/hw/darwin/iokit/xfIOKitCursor.c b/hw/darwin/iokit/xfIOKitCursor.c
index ef3e254..8388513 100644
--- a/hw/darwin/iokit/xfIOKitCursor.c
+++ b/hw/darwin/iokit/xfIOKitCursor.c
@@ -58,6 +58,9 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#if HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "scrnintstr.h"
 #include "cursorstr.h"
 #include "mipointrst.h"
@@ -67,7 +70,7 @@
 #include <IOKit/hidsystem/IOHIDLib.h>
 #include "darwin.h"
 #include "xfIOKit.h"
-
+#include <assert.h>
 #define DUMP_DARWIN_CURSOR FALSE
 
 #define CURSOR_PRIV(pScreen) \
diff --git a/hw/darwin/iokit/xfIOKitStartup.c b/hw/darwin/iokit/xfIOKitStartup.c
index 512793a..07e8c21 100644
--- a/hw/darwin/iokit/xfIOKitStartup.c
+++ b/hw/darwin/iokit/xfIOKitStartup.c
@@ -29,6 +29,11 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+
+#if HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
 #include "darwin.h"
 #include "darwinKeyboard.h"
 #include "micmap.h"
@@ -57,7 +62,9 @@ void DarwinHandleGUI(
  */
 void DarwinGlxExtensionInit(void)
 {
-    GlxExtensionInit();
+#ifdef GLXEXT
+    	GlxExtensionInit();
+#endif
 }
 
 
@@ -67,7 +74,9 @@ void DarwinGlxExtensionInit(void)
 void DarwinGlxWrapInitVisuals(
     miInitVisualsProcPtr *procPtr)
 {
+#ifdef GLXEXT
     GlxWrapInitVisuals(procPtr);
+#endif
 }
 
 
diff-tree 3ead1afe78d2913f08c8144cb2d3813c6b159488 (from d570ff7c81858a3174686b46a088f67563b4a2d5)
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Feb 15 05:09:29 2007 -0800

    Beginning of patches to add XDarwin support to the modular tree;
    special thanks to Torrey Lyons and Peter O'Gorman for making this possible.
    
    This is the automake framework for the XDarwin.app interface files.

diff --git a/hw/darwin/bundle/Dutch.lproj/Makefile.am b/hw/darwin/bundle/Dutch.lproj/Makefile.am
new file mode 100644
index 0000000..a480cee
--- /dev/null
+++ b/hw/darwin/bundle/Dutch.lproj/Makefile.am
@@ -0,0 +1,35 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+Dutchlprojdir = $(resourcesdir)/Dutch.lproj
+
+Dutchlproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+Dutchlprojnibdir = $(Dutchlprojdir)/MainMenu.nib
+Dutchlprojnib_DATA = MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: $(srcdir)/../English.lproj/InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp
diff --git a/hw/darwin/bundle/English.lproj/Makefile.am b/hw/darwin/bundle/English.lproj/Makefile.am
new file mode 100644
index 0000000..4558708
--- /dev/null
+++ b/hw/darwin/bundle/English.lproj/Makefile.am
@@ -0,0 +1,35 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+Englishlprojdir = $(resourcesdir)/English.lproj
+Englishlproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+Englishlprojnibdir = $(Englishlprojdir)/MainMenu.nib
+Englishlprojnib_DATA = MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp \
+	InfoPlist.strings.cpp
diff --git a/hw/darwin/bundle/French.lproj/Makefile.am b/hw/darwin/bundle/French.lproj/Makefile.am
new file mode 100644
index 0000000..656ba5c
--- /dev/null
+++ b/hw/darwin/bundle/French.lproj/Makefile.am
@@ -0,0 +1,38 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+Frenchlprojdir = $(resourcesdir)/French.lproj
+
+Frenchlproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+Frenchlprojnibdir = $(Frenchlprojdir)/MainMenu.nib
+Frenchlprojnib_DATA = MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: $(srcdir)/../English.lproj/InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp
diff --git a/hw/darwin/bundle/German.lproj/Makefile.am b/hw/darwin/bundle/German.lproj/Makefile.am
new file mode 100644
index 0000000..17af414
--- /dev/null
+++ b/hw/darwin/bundle/German.lproj/Makefile.am
@@ -0,0 +1,36 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+Germanlprojdir = $(resourcesdir)/German.lproj
+
+Germanlproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+Germanlprojnibdir = $(Germanlprojdir)/MainMenu.nib
+Germanlprojnib_DATA =  MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: $(srcdir)/../English.lproj/InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp
diff --git a/hw/darwin/bundle/Info.plist b/hw/darwin/bundle/Info.plist
new file mode 100644
index 0000000..bfef48d
--- /dev/null
+++ b/hw/darwin/bundle/Info.plist
@@ -0,0 +1,66 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>English</string>
+	<key>CFBundleDocumentTypes</key>
+	<array>
+		<dict>
+			<key>CFBundleTypeExtensions</key>
+			<array>
+				<string>x11app</string>
+			</array>
+			<key>CFBundleTypeName</key>
+			<string>X11 Application</string>
+			<key>CFBundleTypeOSTypes</key>
+			<array>
+				<string>****</string>
+			</array>
+			<key>CFBundleTypeRole</key>
+			<string>Viewer</string>
+		</dict>
+		<dict>
+			<key>CFBundleTypeExtensions</key>
+			<array>
+				<string>tool</string>
+				<string>*</string>
+			</array>
+			<key>CFBundleTypeName</key>
+			<string>UNIX Application</string>
+			<key>CFBundleTypeOSTypes</key>
+			<array>
+				<string>****</string>
+			</array>
+			<key>CFBundleTypeRole</key>
+			<string>Viewer</string>
+		</dict>
+	</array>
+	<key>CFBundleExecutable</key>
+	<string>XDarwin</string>
+	<key>CFBundleGetInfoString</key>
+	<string>XDarwin 1.4.0, X.Org Foundation</string>
+	<key>CFBundleIconFile</key>
+	<string>XDarwin.icns</string>
+	<key>CFBundleIdentifier</key>
+	<string>org.x.XDarwin</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleName</key>
+	<string>XDarwin</string>
+	<key>CFBundlePackageType</key>
+	<string>APPL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>XDarwin 1.4.0</string>
+	<key>CFBundleSignature</key>
+	<string>????</string>
+	<key>CFBundleVersion</key>
+	<string></string>
+	<key>NSHelpFile</key>
+	<string>XDarwinHelp.html</string>
+	<key>NSMainNibFile</key>
+	<string>MainMenu</string>
+	<key>NSPrincipalClass</key>
+	<string>XApplication</string>
+</dict>
+</plist>
diff --git a/hw/darwin/bundle/Japanese.lproj/Makefile.am b/hw/darwin/bundle/Japanese.lproj/Makefile.am
new file mode 100644
index 0000000..2cc5248
--- /dev/null
+++ b/hw/darwin/bundle/Japanese.lproj/Makefile.am
@@ -0,0 +1,37 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+Japaneselprojdir = $(resourcesdir)/Japanese.lproj
+
+Japaneselproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+Japaneselprojnibdir = $(Japaneselprojdir)/MainMenu.nib
+Japaneselprojnib_DATA = MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: $(srcdir)/../English.lproj/InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp
diff --git a/hw/darwin/bundle/Makefile.am b/hw/darwin/bundle/Makefile.am
new file mode 100644
index 0000000..dee34fd
--- /dev/null
+++ b/hw/darwin/bundle/Makefile.am
@@ -0,0 +1,38 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+SUBDIRS =  English.lproj Dutch.lproj French.lproj German.lproj Japanese.lproj \
+	ko.lproj Portuguese.lproj Spanish.lproj Swedish.lproj
+
+bin_SCRIPTS = startXClients
+
+startXClients: $(srcdir)/startXClients.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) -DXINITDIR=$(XINITDIR) -DXBINDIR=$(BINDIR)  $< | $(CPP_SED_MAGIC) > $@
+	-chmod 755 startXClients
+
+contentsdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents
+resourcesdir = $(contentsdir)/Resources
+
+contents_DATA = Info.plist
+resources_DATA = XDarwin.icns startXClients
+
+install-data-hook:
+	chmod 755 $(DESTDIR)$(resourcesdir)/startXClients
+	echo "APPL????" > $(DESTDIR)$(contentsdir)/PkgInfo
+	touch $(DESTDIR)@APPLE_APPLICATIONS_DIR@/XDarwin.app
+
+uninstall-hook:
+	rm -rf $(DESTDIR)$(contentsdir)/PkgInfo
+
+CLEANFILES = startXClients
+
+EXTRA_DIST = \
+	XDarwin.icns \
+	Info.plist
diff --git a/hw/darwin/bundle/Portuguese.lproj/Makefile.am b/hw/darwin/bundle/Portuguese.lproj/Makefile.am
new file mode 100644
index 0000000..81ba2be
--- /dev/null
+++ b/hw/darwin/bundle/Portuguese.lproj/Makefile.am
@@ -0,0 +1,36 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+Portugueselprojdir = $(resourcesdir)/Portuguese.lproj
+
+Portugueselproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+Portugueselprojnibdir = $(Portugueselprojdir)/MainMenu.nib
+Portugueselprojnib_DATA = MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: $(srcdir)/../English.lproj/InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp
diff --git a/hw/darwin/bundle/Spanish.lproj/Makefile.am b/hw/darwin/bundle/Spanish.lproj/Makefile.am
new file mode 100644
index 0000000..438d0c2
--- /dev/null
+++ b/hw/darwin/bundle/Spanish.lproj/Makefile.am
@@ -0,0 +1,36 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+Spanishlprojdir = $(resourcesdir)/Spanish.lproj
+
+Spanishlproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+Spanishlprojnibdir = $(Spanishlprojdir)/MainMenu.nib
+Spanishlprojnib_DATA = MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: $(srcdir)/../English.lproj/InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp
diff --git a/hw/darwin/bundle/Swedish.lproj/Makefile.am b/hw/darwin/bundle/Swedish.lproj/Makefile.am
new file mode 100644
index 0000000..19f35a6
--- /dev/null
+++ b/hw/darwin/bundle/Swedish.lproj/Makefile.am
@@ -0,0 +1,36 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+Swedishlprojdir = $(resourcesdir)/Swedish.lproj
+
+Swedishlproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+Swedishlprojnibdir = $(Swedishlprojdir)/MainMenu.nib
+Swedishlprojnib_DATA = MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: $(srcdir)/../English.lproj/InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp
diff --git a/hw/darwin/bundle/ko.lproj/Makefile.am b/hw/darwin/bundle/ko.lproj/Makefile.am
new file mode 100644
index 0000000..56dd6b3
--- /dev/null
+++ b/hw/darwin/bundle/ko.lproj/Makefile.am
@@ -0,0 +1,37 @@
+BINDIR = ${bindir}
+include $(top_srcdir)/cpprules.in
+XINITDIR = $(libdir)/X11/xinit
+XDEFS = \
+        -DX_VERSION="$(PLIST_VERSION_STRING)" \
+        -DX_PRE_RELEASE="$(PRE)" \
+        -DX_REL_DATE="$(XORG_DATE)" \
+        -DX_VENDOR_NAME="$(VENDOR_STRING)" \
+        -DX_VENDOR_LINK="$(PLIST_VENDOR_WEB)"
+
+
+resourcesdir = @APPLE_APPLICATIONS_DIR@/XDarwin.app/Contents/Resources
+
+kolprojdir = $(resourcesdir)/ko.lproj
+
+kolproj_DATA = \
+		    XDarwinHelp.html \
+		    InfoPlist.strings \
+		    Credits.rtf Localizable.strings
+
+kolprojnibdir = $(kolprojdir)/MainMenu.nib
+kolprojnib_DATA = MainMenu.nib/classes.nib MainMenu.nib/objects.nib
+
+InfoPlist.strings: $(srcdir)/../English.lproj/InfoPlist.strings.cpp
+	 $(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) | $(SED) -e's/__quote__/"/g' > $@
+
+XDarwinHelp.html: XDarwinHelp.html.cpp
+	$(RAWCPP) $(RAWCPPFLAGS) $(XDEFS) $(CPP_FILES_FLAGS) $< | $(CPP_SED_MAGIC) > $@
+
+CLEANFILES = XDarwinHelp.html InfoPlist.strings 
+
+EXTRA_DIST = \
+	Credits.rtf Localizable.strings \
+	Localizable.strings \
+	MainMenu.nib/classes.nib \
+	MainMenu.nib/objects.nib \
+	XDarwinHelp.html.cpp
diff-tree d570ff7c81858a3174686b46a088f67563b4a2d5 (from 81aa7f059d3cfd8d28420b7932b8ff7e06d67979)
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Wed Feb 14 17:09:33 2007 +1030

    fix: WarpCursor needs to send MotionNotify.

diff --git a/dix/getevents.c b/dix/getevents.c
index 8b2a44d..935112d 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -489,6 +489,7 @@ GetPointerEvents(xEvent *events, DeviceI
     Bool sendValuators = (type == MotionNotify || flags & POINTER_ABSOLUTE);
     DeviceIntPtr cp = inputInfo.pointer;
     int x = 0, y = 0;
+    Bool coreOnly = (pDev == inputInfo.pointer);
 
     /* Sanity checks. */
     if (type != MotionNotify && type != ButtonPress && type != ButtonRelease)
@@ -497,7 +498,7 @@ GetPointerEvents(xEvent *events, DeviceI
     if ((type == ButtonPress || type == ButtonRelease) && !pDev->button)
         return 0;
 
-    if (pDev->coreEvents)
+    if (!coreOnly && pDev->coreEvents)
         num_events = 2;
     else
         num_events = 1;
@@ -507,7 +508,7 @@ GetPointerEvents(xEvent *events, DeviceI
     }
 
     /* Do we need to send a DeviceValuator event? */
-    if (sendValuators) {
+    if (!coreOnly && sendValuators) {
         if ((((num_valuators - 1) / 6) + 1) > MAX_VALUATOR_EVENTS)
             num_valuators = MAX_VALUATOR_EVENTS * 6;
         num_events += ((num_valuators - 1) / 6) + 1;
@@ -521,10 +522,6 @@ GetPointerEvents(xEvent *events, DeviceI
 
     ms = GetTimeInMillis();
 
-    kbp = (deviceKeyButtonPointer *) events;
-    kbp->time = ms;
-    kbp->deviceid = pDev->id;
-
     /* Set x and y based on whether this is absolute or relative, and
      * accelerate if we need to. */
     if (flags & POINTER_ABSOLUTE) {
@@ -602,29 +599,37 @@ GetPointerEvents(xEvent *events, DeviceI
     pDev->valuator->lastx = x;
     pDev->valuator->lasty = y;
 
-    if (type == MotionNotify) {
-        kbp->type = DeviceMotionNotify;
-    }
-    else {
-        if (type == ButtonPress)
-            kbp->type = DeviceButtonPress;
-        else if (type == ButtonRelease)
-            kbp->type = DeviceButtonRelease;
-        kbp->detail = pDev->button->map[buttons];
-    }
+    if (!coreOnly)
+    {
+        kbp = (deviceKeyButtonPointer *) events;
+        kbp->time = ms;
+        kbp->deviceid = pDev->id;
+
+        if (type == MotionNotify) {
+            kbp->type = DeviceMotionNotify;
+        }
+        else {
+            if (type == ButtonPress)
+                kbp->type = DeviceButtonPress;
+            else if (type == ButtonRelease)
+                kbp->type = DeviceButtonRelease;
+            kbp->detail = pDev->button->map[buttons];
+        }
 
-    kbp->root_x = x;
-    kbp->root_y = y;
+        kbp->root_x = x;
+        kbp->root_y = y;
 
-    events++;
-    if (sendValuators) {
-        kbp->deviceid |= MORE_EVENTS;
-        clipValuators(pDev, first_valuator, num_valuators, valuators);
-        events = getValuatorEvents(events, pDev, first_valuator,
-                                   num_valuators, valuators);
+        events++;
+        if (sendValuators) {
+            kbp->deviceid |= MORE_EVENTS;
+            clipValuators(pDev, first_valuator, num_valuators, valuators);
+            events = getValuatorEvents(events, pDev, first_valuator,
+                                       num_valuators, valuators);
+        }
     }
 
-    if (pDev->coreEvents) {
+    /* for some reason inputInfo.pointer does not have coreEvents set */
+    if (coreOnly || pDev->coreEvents) {
         events->u.u.type = type;
         events->u.keyButtonPointer.time = ms;
         events->u.keyButtonPointer.rootX = x;
diff --git a/mi/mipointer.c b/mi/mipointer.c
index dbe2aae..c28911b 100644
--- a/mi/mipointer.c
+++ b/mi/mipointer.c
@@ -474,6 +474,10 @@ void
 miPointerMoved (DeviceIntPtr pDev, ScreenPtr pScreen, int x, int y,
                      unsigned long time)
 {
+    xEvent* events;
+    int i, nevents;
+    int valuators[2];
+
     SetupScreen(pScreen);
 
     if (pDev && (pDev->coreEvents || pDev == inputInfo.pointer) &&
@@ -488,4 +492,23 @@ miPointerMoved (DeviceIntPtr pDev, Scree
     miPointer.x = x;
     miPointer.y = y;
     miPointer.pScreen = pScreen;
+
+    /* generate motion notify */
+    valuators[0] = x;
+    valuators[1] = y;
+
+    events = (xEvent*)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
+    if (!events)
+    {
+        FatalError("Could not allocate event store.\n");
+        return;
+    }
+
+    nevents = GetPointerEvents(events, pDev, MotionNotify, 0,
+                               POINTER_ABSOLUTE, 0, 2, valuators);
+
+    for (i = 0; i < nevents; i++)
+        mieqEnqueue(pDev, &events[i]);
+
+    xfree(events);
 }
diff-tree 81aa7f059d3cfd8d28420b7932b8ff7e06d67979 (from a5f19c5150a7b3dc2ff3ad759ee1a6ab0ad8925c)
Author: Eric Anholt <eric at anholt.net>
Date:   Wed Feb 14 12:48:15 2007 -0800

    Add missing dirty marking in a couple of fallback cases in the exaGlyphs path.

diff --git a/exa/exa_accel.c b/exa/exa_accel.c
index 6fa481a..e633d80 100644
--- a/exa/exa_accel.c
+++ b/exa/exa_accel.c
@@ -648,6 +648,14 @@ exaPolyFillRect(DrawablePtr pDrawable,
     {
 	exaDoMigration (pixmaps, 1, FALSE);
 	ExaCheckPolyFillRect (pDrawable, pGC, nrect, prect);
+	while (nrect-- >= 0) {
+	    exaDrawableDirty(pDrawable,
+			     pDrawable->x + prect->x,
+			     pDrawable->y + prect->y,
+			     pDrawable->x + prect->x + prect->width,
+			     pDrawable->y + prect->y + prect->height);
+	    prect++;
+	}
 	return;
     } else {
 	exaDoMigration (pixmaps, 1, TRUE);
diff --git a/exa/exa_render.c b/exa/exa_render.c
index a442987..b78d728 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -572,9 +572,7 @@ exaComposite(CARD8	op,
     if (pExaScr->swappedOut ||
 	pSrc->pDrawable == NULL || (pMask != NULL && pMask->pDrawable == NULL))
     {
-	ExaCheckComposite (op, pSrc, pMask, pDst, xSrc, ySrc,
-			   xMask, yMask, xDst, yDst, width, height);
-        return;
+	goto fallback;
     }
 
     /* Remove repeat in source if useless */
@@ -683,12 +681,18 @@ exaComposite(CARD8	op,
 	}
     }
 
+fallback:
 #if DEBUG_TRACE_FALL
     exaPrintCompositeFallback (op, pSrc, pMask, pDst);
 #endif
 
     ExaCheckComposite (op, pSrc, pMask, pDst, xSrc, ySrc,
 		      xMask, yMask, xDst, yDst, width, height);
+    exaDrawableDirty(pDst->pDrawable,
+		     pDst->pDrawable->x + xDst,
+		     pDst->pDrawable->y + yDst,
+		     pDst->pDrawable->x + xDst + width,
+		     pDst->pDrawable->y + yDst + height);
 
 done:
     pSrc->repeat = saveSrcRepeat;
diff-tree a5f19c5150a7b3dc2ff3ad759ee1a6ab0ad8925c (from a492d494f51caf15a5cb979dc335387486c105d1)
Author: Eric Anholt <eric at anholt.net>
Date:   Wed Feb 14 10:39:46 2007 -0800

    Mark sync when UploadToScreen succeeds in exaGlyphs().

diff --git a/exa/exa_render.c b/exa/exa_render.c
index 75108a7..a442987 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -995,15 +995,17 @@ exaGlyphs (CARD8	op,
 	     * First we try to use UploadToScreen, if we can, then we fall back
 	     * to a plain exaCopyArea in case of failure.
 	     */
-	    if (!pExaScr->info->UploadToScreen ||
-		!exaPixmapIsOffscreen(pPixmap) ||
-		!(*pExaScr->info->UploadToScreen) (pPixmap, 0, 0,
+	    if (pExaScr->info->UploadToScreen &&
+		exaPixmapIsOffscreen(pPixmap) &&
+		(*pExaScr->info->UploadToScreen) (pPixmap, 0, 0,
 					glyph->info.width,
 					glyph->info.height,
 					glyphdata,
 					PixmapBytePad(glyph->info.width,
 						      list->format->depth)))
 	    {
+		exaMarkSync (pScreen);
+	    } else {
 		/* Set up the scratch pixmap/GC for doing a CopyArea. */
 		if (pScratchPixmap == NULL) {
 		    /* Get a scratch pixmap to wrap the original glyph data */
diff-tree a492d494f51caf15a5cb979dc335387486c105d1 (from a23b0b069cac8a48e2b306b2095515d75f647705)
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Tue Feb 13 18:32:59 2007 -0800

    Update Xvfb man page: remove monolith build instructions, use /var/tmp instead of /usr/tmp

diff --git a/hw/vfb/Xvfb.man.pre b/hw/vfb/Xvfb.man.pre
index f0f5da1..e78e296 100644
--- a/hw/vfb/Xvfb.man.pre
+++ b/hw/vfb/Xvfb.man.pre
@@ -47,13 +47,6 @@ configurations, doing batch processing w
 rendering engine, load testing, as an aid to porting the X server to a
 new platform, and providing an unobtrusive way to run applications
 that don't really need an X server but insist on having one anyway.
-.SH BUILDING
-To build \fIXvfb\fP, put the following in your host.def and remake.
-.PP
-\&#define BuildServer YES /\(** if you aren't already building other servers */
-.br
-\&#define XVirtualFramebufferServer YES
-
 .SH OPTIONS
 .PP
 In addition to the normal server options described in the \fIXserver(1)\fP
@@ -116,14 +109,14 @@ The server will listen for connections a
 default screen configuration (one screen, 1280x1024x12), and screen 1
 will be depth 16 1600x1200.
 .TP 8
-Xvfb -pixdepths 3 27 -fbdir /usr/tmp
+Xvfb -pixdepths 3 27 -fbdir /var/tmp
 The server will listen for connections as server number 0, will have the
 default screen configuration (one screen, 1280x1024x12),
 will also support pixmap
 depths of 3 and 27, 
-and will use memory mapped files in /usr/tmp for the framebuffer.
+and will use memory mapped files in /var/tmp for the framebuffer.
 .TP 8
-xwud -in /usr/tmp/Xvfb_screen0
+xwud -in /var/tmp/Xvfb_screen0
 Displays screen 0 of the server started by the preceding example.
 .SH "SEE ALSO"
 .PP
diff-tree a23b0b069cac8a48e2b306b2095515d75f647705 (from d21c95f80bdba2f29eedd57fb0b00e580391c08e)
Author: Adam Jackson <ajax at benzedrine.nwnk.net>
Date:   Mon Feb 12 17:50:00 2007 -0500

    Typo fix.

diff --git a/hw/xfree86/os-support/xf86_libc.h b/hw/xfree86/os-support/xf86_libc.h
index df78d53..199fcd6 100644
--- a/hw/xfree86/os-support/xf86_libc.h
+++ b/hw/xfree86/os-support/xf86_libc.h
@@ -428,7 +428,7 @@ typedef int xf86jmp_buf[1024];
 #define toupper(i)		xf86toupper(i)
 #undef ungetc
 #define ungetc(i,FP)		xf86ungetc(i,FP)
-#undef vfprinf
+#undef vfprintf
 #define vfprintf(p,f,a)		xf86vfprintf(p,f,a)
 #undef vsnprintf
 #define vsnprintf(s,n,f,a)	xf86vsnprintf(s,n,f,a)
diff-tree d21c95f80bdba2f29eedd57fb0b00e580391c08e (from 46784d24c11767455a4986449a8037295912dcee)
Author: Adam Jackson <ajax at benzedrine.nwnk.net>
Date:   Mon Feb 12 17:22:39 2007 -0500

    Hook up --with-builderstring for vendor build identification.

diff --git a/configure.ac b/configure.ac
index 4a33ac0..92dc5c9 100644
--- a/configure.ac
+++ b/configure.ac
@@ -448,6 +448,9 @@ AC_ARG_WITH(os-name,         AS_HELP_STR
 AC_ARG_WITH(os-vendor,       AS_HELP_STRING([--with-os-vendor=OSVENDOR], [Name of OS vendor]),
 				[ OSVENDOR="$withval" ],
 				[ OSVENDOR="" ])
+AC_ARG_WITH(builderstring,   AS_HELP_STRING([--with-builderstring=BUILDERSTRING], [Additional builder string]),
+				[ BUILDERSTRING="$withval" ]
+				[ ])
 AC_ARG_WITH(mesa-source,     AS_HELP_STRING([--with-mesa-source=MESA_SOURCE], [Path to Mesa source tree]),
                                 [ MESA_SOURCE="$withval" ],
                                 [ MESA_SOURCE="" ])
@@ -934,6 +937,8 @@ AC_DEFINE_UNQUOTED(XORG_MAN_VERSION, ["$
 AC_DEFINE_UNQUOTED(BUILDERADDR, ["$BUILDERADDR"], [Builder address])
 AC_DEFINE_UNQUOTED(OSNAME, ["$OSNAME"], [Operating System Name])
 AC_DEFINE_UNQUOTED(OSVENDOR, ["$OSVENDOR"], [Operating System Vendor])
+AC_DEFINE_UNQUOTED(BUILDERSTRING, ["$BUILDERSTRING"], [Builder string])
+
 AC_SUBST([VENDOR_STRING])
 AC_SUBST([VENDOR_STRING_SHORT])
 AC_SUBST([VENDOR_RELEASE])
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 1a9fdc5..458e3a1 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -15,6 +15,9 @@
 /* Operating System Vendor */
 #undef OSVENDOR
 
+/* Builder string */
+#undef BUILDERSTRING
+
 /* Default font path */
 #undef COMPILEDDEFAULTFONTPATH
 
diff-tree 46784d24c11767455a4986449a8037295912dcee (from c4b7e9d1c16797c3e4b1200b40aceab5696a7fb8)
Author: Adam Jackson <ajax at benzedrine.nwnk.net>
Date:   Mon Feb 12 17:18:29 2007 -0500

    Remove spurious LIBADD from xf4bpp

diff --git a/hw/xfree86/xf4bpp/Makefile.am b/hw/xfree86/xf4bpp/Makefile.am
index 9af3364..8fddb6b 100644
--- a/hw/xfree86/xf4bpp/Makefile.am
+++ b/hw/xfree86/xf4bpp/Makefile.am
@@ -46,8 +46,6 @@ libxf4bpp_la_SOURCES = \
         mfbzerarc.c \
         vgamodule.c
 
-libxf4bpp_la_LIBADD = ../xf1bpp/libxf1bpp.la
-
 EXTRA_DIST = OScompiler.h ibmTrace.h ppcGCstr.h ppcSpMcro.h vgaReg.h \
              vgaVideo.h wm3.h NOTES
 
diff-tree c4b7e9d1c16797c3e4b1200b40aceab5696a7fb8 (from 262b9b104a04e55969593ef96a16004e53ecd00a)
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Tue Feb 6 14:57:22 2007 -0800

    Add an RDTSC implementation to the x86 emulator.
    
    This instruction is being used in some debug VBIOSes.  This implementation
    doesn't even try to be accurate.  Instead, it just increments the counter by a
    fixed amount every time an rdtsc instruction in encountered, to avoid divides by
    zero.

diff --git a/hw/xfree86/x86emu/ops2.c b/hw/xfree86/x86emu/ops2.c
index 7b0156a..8c6c535 100644
--- a/hw/xfree86/x86emu/ops2.c
+++ b/hw/xfree86/x86emu/ops2.c
@@ -65,6 +65,40 @@ static void x86emuOp2_illegal_op(
 
 /****************************************************************************
 REMARKS:
+Handles opcode 0x0f,0x31
+****************************************************************************/
+static void x86emuOp2_rdtsc(u8 X86EMU_UNUSED(op2))
+{
+#ifdef __HAS_LONG_LONG__
+    static u64 counter = 0;
+#else
+    static u32 counter = 0;
+#endif
+
+    counter += 0x10000;
+
+    /* read timestamp counter */
+    /*
+     * Note that instead of actually trying to accurately measure this, we just
+     * increase the counter by a fixed amount every time we hit one of these
+     * instructions.  Feel free to come up with a better method.
+     */
+    START_OF_INSTR();
+    DECODE_PRINTF("RDTSC\n");
+    TRACE_AND_STEP();
+#ifdef __HAS_LONG_LONG__
+    M.x86.R_EAX = counter & 0xffffffff;
+    M.x86.R_EDX = counter >> 32;
+#else
+    M.x86.R_EAX = counter;
+    M.x86.R_EDX = 0;
+#endif
+    DECODE_CLEAR_SEGOVR();
+    END_OF_INSTR();
+}
+
+/****************************************************************************
+REMARKS:
 Handles opcode 0x0f,0x80-0x8F
 ****************************************************************************/
 static void x86emuOp2_long_jump(u8 op2)
@@ -2580,7 +2614,7 @@ void (*x86emu_optab2[256])(u8) =
 /*  0x2f */ x86emuOp2_illegal_op,
 
 /*  0x30 */ x86emuOp2_illegal_op,
-/*  0x31 */ x86emuOp2_illegal_op,
+/*  0x31 */ x86emuOp2_rdtsc,
 /*  0x32 */ x86emuOp2_illegal_op,
 /*  0x33 */ x86emuOp2_illegal_op,
 /*  0x34 */ x86emuOp2_illegal_op,
diff-tree 262b9b104a04e55969593ef96a16004e53ecd00a (from 876b806ec09d5ff0c6cd19df91006c4eefedfaa6)
Author: Soren Sandmann Pedersen <ssp at dhcp83-218.boston.redhat.com>
Date:   Tue Feb 6 17:30:22 2007 -0500

    Use the new 8888x0565mmx function in fbpict.c

diff --git a/fb/fbpict.c b/fb/fbpict.c
index 3ff609f..cd6cac2 100644
--- a/fb/fbpict.c
+++ b/fb/fbpict.c
@@ -1175,7 +1175,12 @@ fbComposite (CARD8      op,
 			func = fbCompositeSrc_8888x0888;
 			break;
 		    case PICT_r5g6b5:
-			func = fbCompositeSrc_8888x0565;
+#ifdef USE_MMX
+			if (fbHaveMMX())
+			    func = fbCompositeSrc_8888x0565mmx;
+			else
+#endif
+			    func = fbCompositeSrc_8888x0565;
 			break;
 		    default:
 			break;
@@ -1221,7 +1226,12 @@ fbComposite (CARD8      op,
 			func = fbCompositeSrc_8888x0888;
 			break;
 		    case PICT_b5g6r5:
-			func = fbCompositeSrc_8888x0565;
+#ifdef USE_MMX
+			if (fbHaveMMX())
+			    func = fbCompositeSrc_8888x0565mmx;
+			else
+#endif
+			    func = fbCompositeSrc_8888x0565;
 			break;
 		    default:
 			break;
diff-tree 876b806ec09d5ff0c6cd19df91006c4eefedfaa6 (from 13568d2aa43da4216bbcb46e1125ff28c323ac54)
Author: Soren Sandmann Pedersen <ssp at dhcp83-218.boston.redhat.com>
Date:   Tue Feb 6 17:16:23 2007 -0500

    Reapply patch to fix AMD CPU detection

diff --git a/fb/fbpict.c b/fb/fbpict.c
index 28503c0..3ff609f 100644
--- a/fb/fbpict.c
+++ b/fb/fbpict.c
@@ -1516,7 +1516,9 @@ static unsigned int detectCPUFeatures(vo
             features |= SSE;
         if (result & (1 << 26))
             features |= SSE2;
-        if ((result & MMX) && !(result & SSE) && (strcmp(vendor, "AuthenticAMD") == 0)) {
+        if ((features & MMX) && !(features & SSE) &&
+            (strcmp(vendor, "AuthenticAMD") == 0 ||
+             strcmp(vendor, "Geode by NSC") == 0)) {
             /* check for AMD MMX extensions */
 
             unsigned int result;            
diff-tree 13568d2aa43da4216bbcb46e1125ff28c323ac54 (from 5a3334410367a2186b2c667fa1eb6cf0baf93e95)
Author: Soren Sandmann Pedersen <ssp at dhcp83-218.boston.redhat.com>
Date:   Tue Feb 6 17:12:01 2007 -0500

    Revert "Fix for AMD cpu detection. Bug 9614, Dan Williams."
    
    This reverts commit b2cd3b133748cc5aa541905a703a6fdb1cbbb1e6 since
    unrelated changes in fbpict.c broke the build.

diff --git a/fb/fbpict.c b/fb/fbpict.c
index 39d8d9f..28503c0 100644
--- a/fb/fbpict.c
+++ b/fb/fbpict.c
@@ -189,23 +189,6 @@ fbCompositeSolidMask_nx8888x8888C (CARD8
     fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1);
     fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1);
 
-    {
-	comp_image_t src, msk, dst;
-	comp_pixel_t src_pixel;
-	comp_format_t msk_format = { 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff };
-	
-	src_pixel.red   = src & 0x000000ff;
-	src_pixel.green = src & 0x0000ff00;
-	src_pixel.blue  = src & 0x00ff0000;
-	src_pixel.alpha = src & 0xff000000;
-	
-	comp_image_init_solid (&src, &src_pixel);
-	comp_image_init_bits  (&msk, maskLine, maskStride, &msk_format);
-	comp_image_init_bits  (&dst, dstLine, dstStride, &dst_format);
-
-	comp_over_c (src, msk, dst, srcX, srcY, mskX, mskY, dstX, dstY);
-    }
-    
     while (height--)
     {
 	dst = dstLine;
@@ -1533,9 +1516,7 @@ static unsigned int detectCPUFeatures(vo
             features |= SSE;
         if (result & (1 << 26))
             features |= SSE2;
-        if ((features & MMX) && !(features & SSE) &&
-            (strcmp(vendor, "AuthenticAMD") == 0 ||
-             strcmp(vendor, "Geode by NSC") == 0)) {
+        if ((result & MMX) && !(result & SSE) && (strcmp(vendor, "AuthenticAMD") == 0)) {
             /* check for AMD MMX extensions */
 
             unsigned int result;            
diff-tree 5a3334410367a2186b2c667fa1eb6cf0baf93e95 (from b2cd3b133748cc5aa541905a703a6fdb1cbbb1e6)
Author: Soren Sandmann Pedersen <ssp at dhcp83-218.boston.redhat.com>
Date:   Tue Feb 6 17:11:01 2007 -0500

    Add new fbCompositeSrc_8888x0565mmx() function, based on patch by Dan
    Williams. Bug 9682.

diff --git a/fb/fbmmx.c b/fb/fbmmx.c
index f74930a..5bbede1 100644
--- a/fb/fbmmx.c
+++ b/fb/fbmmx.c
@@ -1339,6 +1339,104 @@ fbCompositeSrc_8888x8888mmx (CARD8	op,
 }
 
 void
+fbCompositeSrc_8888x0565mmx (CARD8      op,
+			     PicturePtr pSrc,
+			     PicturePtr pMask,
+			     PicturePtr pDst,
+			     INT16      xSrc,
+			     INT16      ySrc,
+			     INT16      xMask,
+			     INT16      yMask,
+			     INT16      xDst,
+			     INT16      yDst,
+			     CARD16     width,
+			     CARD16     height)
+{
+    CARD16	*dstLine, *dst;
+    CARD32	*srcLine, *src;
+    FbStride	dstStride, srcStride;
+    CARD16	w;
+    
+    CHECKPOINT();
+    
+    fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1);
+    fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1);
+    
+    assert (pSrc->pDrawable == pMask->pDrawable);
+    
+    while (height--)
+    {
+	dst = dstLine;
+	dstLine += dstStride;
+	src = srcLine;
+	srcLine += srcStride;
+	w = width;
+	
+	CHECKPOINT();
+	
+	while (w && (unsigned long)dst & 7)
+	{
+	    __m64 vsrc = load8888 (*src);
+	    ullong d = *dst;
+	    __m64 vdest = expand565 ((__m64)d, 0);
+	    
+	    vdest = pack565(over(vsrc, expand_alpha(vsrc), vdest), vdest, 0);
+	    
+	    *dst = (ullong)vdest;
+	    
+	    w--;
+	    dst++;
+	    src++;
+	}
+	
+	CHECKPOINT();
+	
+	while (w >= 4)
+	{
+	    __m64 vsrc0, vsrc1, vsrc2, vsrc3;
+	    __m64 vdest;
+
+	    vsrc0 = load8888(*(src + 0));
+	    vsrc1 = load8888(*(src + 1));
+	    vsrc2 = load8888(*(src + 2));
+	    vsrc3 = load8888(*(src + 3));
+
+	    vdest = *(__m64 *)dst;
+	    
+	    vdest = pack565(over(vsrc0, expand_alpha(vsrc0), expand565(vdest, 0)), vdest, 0);
+	    vdest = pack565(over(vsrc1, expand_alpha(vsrc1), expand565(vdest, 1)), vdest, 1);
+	    vdest = pack565(over(vsrc2, expand_alpha(vsrc2), expand565(vdest, 2)), vdest, 2);
+	    vdest = pack565(over(vsrc3, expand_alpha(vsrc3), expand565(vdest, 3)), vdest, 3);
+	    
+	    *(__m64 *)dst = vdest;
+
+	    w -= 4;
+	    dst += 4;
+	    src += 4;
+	}
+
+	CHECKPOINT();
+	
+	while (w)
+	{
+	    __m64 vsrc = load8888 (*src);
+	    ullong d = *dst;
+	    __m64 vdest = expand565 ((__m64)d, 0);
+	    
+	    vdest = pack565(over(vsrc, expand_alpha(vsrc), vdest), vdest, 0);
+	    
+	    *dst = (ullong)vdest;
+	    
+	    w--;
+	    dst++;
+	    src++;
+	}
+    }
+    
+    _mm_empty();
+}
+
+void
 fbCompositeSolidMask_nx8x8888mmx (CARD8      op,
 				  PicturePtr pSrc,
 				  PicturePtr pMask,
diff --git a/fb/fbmmx.h b/fb/fbmmx.h
index 34718e3..b3e4d71 100644
--- a/fb/fbmmx.h
+++ b/fb/fbmmx.h
@@ -130,6 +130,18 @@ void fbCompositeSrc_8888RevNPx8888mmx (C
 				       INT16      yDst,
 				       CARD16     width,
 				       CARD16     height);
+void fbCompositeSrc_8888x0565mmx (CARD8      op,
+				  PicturePtr pSrc,
+				  PicturePtr pMask,
+				  PicturePtr pDst,
+				  INT16      xSrc,
+				  INT16      ySrc,
+				  INT16      xMask,
+				  INT16      yMask,
+				  INT16      xDst,
+				  INT16      yDst,
+				  CARD16     width,
+				  CARD16     height);
 void fbCompositeSrc_8888RevNPx0565mmx (CARD8      op,
 				       PicturePtr pSrc,
 				       PicturePtr pMask,
diff-tree b2cd3b133748cc5aa541905a703a6fdb1cbbb1e6 (from 760a38c4c7ab66ae653d3acb92f5cda4bd44edd6)
Author: Soren Sandmann Pedersen <ssp at dhcp83-218.boston.redhat.com>
Date:   Tue Feb 6 16:43:37 2007 -0500

    Fix for AMD cpu detection. Bug 9614, Dan Williams.
    
    Credit for the fixes in this patch goes to:
    
    Marco Gritti <mpg at redhat dot com>
    Jordan Crouse <jordan dot crouse at amd dot com>

diff --git a/fb/fbpict.c b/fb/fbpict.c
index 28503c0..39d8d9f 100644
--- a/fb/fbpict.c
+++ b/fb/fbpict.c
@@ -189,6 +189,23 @@ fbCompositeSolidMask_nx8888x8888C (CARD8
     fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1);
     fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1);
 
+    {
+	comp_image_t src, msk, dst;
+	comp_pixel_t src_pixel;
+	comp_format_t msk_format = { 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff };
+	
+	src_pixel.red   = src & 0x000000ff;
+	src_pixel.green = src & 0x0000ff00;
+	src_pixel.blue  = src & 0x00ff0000;
+	src_pixel.alpha = src & 0xff000000;
+	
+	comp_image_init_solid (&src, &src_pixel);
+	comp_image_init_bits  (&msk, maskLine, maskStride, &msk_format);
+	comp_image_init_bits  (&dst, dstLine, dstStride, &dst_format);
+
+	comp_over_c (src, msk, dst, srcX, srcY, mskX, mskY, dstX, dstY);
+    }
+    
     while (height--)
     {
 	dst = dstLine;
@@ -1516,7 +1533,9 @@ static unsigned int detectCPUFeatures(vo
             features |= SSE;
         if (result & (1 << 26))
             features |= SSE2;
-        if ((result & MMX) && !(result & SSE) && (strcmp(vendor, "AuthenticAMD") == 0)) {
+        if ((features & MMX) && !(features & SSE) &&
+            (strcmp(vendor, "AuthenticAMD") == 0 ||
+             strcmp(vendor, "Geode by NSC") == 0)) {
             /* check for AMD MMX extensions */
 
             unsigned int result;            
diff-tree 760a38c4c7ab66ae653d3acb92f5cda4bd44edd6 (from 17d85387d1e6851d35474b65929e268ca64ef65b)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Mon Feb 5 03:39:36 2007 +0200

    XkbCopyKeymap: fix copy-and-waste accident
    
    When we reallocated modmap, we accidentally clobbered syms with the
    result, leaving syms definitely too small, and modmap also potentially too
    small (as well as not actually allocated anymore).

diff --git a/xkb/xkbUtils.c b/xkb/xkbUtils.c
index 400306a..062159e 100644
--- a/xkb/xkbUtils.c
+++ b/xkb/xkbUtils.c
@@ -1220,7 +1220,7 @@ XkbCopyKeymap(XkbDescPtr src, XkbDescPtr
                     tmp = xalloc(src->max_key_code + 1);
                 if (!tmp)
                     return FALSE;
-                dst->map->syms = tmp;
+                dst->map->modmap = tmp;
             }
             memcpy(dst->map->modmap, src->map->modmap, src->max_key_code + 1);
         }
diff-tree 17d85387d1e6851d35474b65929e268ca64ef65b (from 236f04b638e7d4d1656c6bedd8a6e8d7cec285ec)
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Thu Jan 18 15:23:57 2007 +1100

    dmx, vfb, xnest: fix fbcmap compilation
    
    Don't always define XFree86Server, but only for damn fbcmap.c.
    Split fbcmap.c into its own library to achieve this.

diff --git a/hw/dmx/Makefile.am b/hw/dmx/Makefile.am
index 89136b9..17d27ed 100644
--- a/hw/dmx/Makefile.am
+++ b/hw/dmx/Makefile.am
@@ -2,6 +2,7 @@ DIST_SUBDIRS = input config glxProxy exa
 
 SUBDIRS = input config examples
 bin_PROGRAMS = Xdmx
+noinst_LIBRARIES = libfbcmap.a
 
 if XINERAMA
 PANORAMIX_SRCS = $(top_srcdir)/Xext/panoramiX.c
@@ -16,13 +17,20 @@ GLX_INCS = -I$(top_srcdir)/hw/xfree86/di
 GLX_DEFS = @GL_CFLAGS@ 
 endif
 
-# It's essential that fbcmap.c be compiled with this flag for DMX to work!!
-DMX_CFLAGS = -DXFree86Server=1
-
 if BUILDDOCS
 SUBDIRS += doc
 endif
 
+AM_CFLAGS = \
+      -DHAVE_DMX_CONFIG_H \
+      $(DIX_CFLAGS) \
+      $(GLX_INCS) \
+      $(GLX_DEFS) \
+      @DMXMODULES_CFLAGS@
+
+libfbcmap_a_SOURCES = libfbcmap.a
+libfbcmap_a_CFLAGS = $(AM_CFLAGS) -DXFree86Server
+
 Xdmx_SOURCES = dmx.c \
                dmxcb.c \
                dmxcb.h \
@@ -67,7 +75,6 @@ Xdmx_SOURCES = dmx.c \
                dmxvisual.h \
                dmxwindow.c \
                dmxwindow.h \
-               $(top_srcdir)/fb/fbcmap.c \
                $(top_srcdir)/mi/miinitext.c \
                $(GLX_SRCS) 
 
@@ -82,16 +89,9 @@ Xdmx_LDADD = $(XORG_CORE_LIBS) \
              $(GLX_LIBS) \
              input/libdmxinput.a \
              config/libdmxconfig.a \
+	     libfbcmap.a \
              @DMXMODULES_LIBS@
 
-Xdmx_CFLAGS = \
-              -DHAVE_DMX_CONFIG_H \
-              $(DIX_CFLAGS) \
-              $(GLX_INCS) \
-              $(GLX_DEFS) \
-              $(DMX_CFLAGS) \
-              @DMXMODULES_CFLAGS@
-
 # Man page
 appmandir = $(APP_MAN_DIR)
 
diff --git a/hw/vfb/Makefile.am b/hw/vfb/Makefile.am
index 4f711fd..40c3854 100644
--- a/hw/vfb/Makefile.am
+++ b/hw/vfb/Makefile.am
@@ -1,12 +1,21 @@
 bin_PROGRAMS = Xvfb
+noinst_LIBRARIES = libfbcmap.a
+
+AM_CFLAGS = -DHAVE_DIX_CONFIG_H \
+            -DNO_HW_ONLY_EXTS \
+            -DNO_MODULE_EXTS \
+            $(XVFBMODULES_CFLAGS) \
+	    $(DIX_CFLAGS)
 
 SRCS =	InitInput.c \
 	InitOutput.c \
 	lk201kbd.h \
 	$(top_srcdir)/Xext/dpmsstubs.c \
 	$(top_srcdir)/Xi/stubs.c \
-	$(top_srcdir)/mi/miinitext.c \
-	$(top_srcdir)/fb/fbcmap.c
+	$(top_srcdir)/mi/miinitext.c
+
+libfbcmap_a_CFLAGS = $(AM_CFLAGS) -DXFree86Server
+libfbcmap_a_SOURCES = $(top_srcdir)/fb/fbcmap.c
 
 Xvfb_SOURCES = $(SRCS)
 
@@ -14,16 +23,8 @@ Xvfb_LDADD = $(XORG_CORE_LIBS) \
              $(XVFB_LIBS) \
              $(XSERVER_LIBS) \
              $(EXTENSION_LIBS) \
-             $(XVFBMODULES_LIBS)
-
-Xvfb_LDFLAGS =
-
-AM_CFLAGS = -DHAVE_DIX_CONFIG_H \
-            -DNO_HW_ONLY_EXTS \
-            -DNO_MODULE_EXTS \
-            -DXFree86Server \
-            $(XVFBMODULES_CFLAGS) \
-	    $(DIX_CFLAGS)
+             $(XVFBMODULES_LIBS) \
+	     libfbcmap.a
 
 # Man page
 include $(top_srcdir)/cpprules.in
diff --git a/hw/xnest/Makefile.am b/hw/xnest/Makefile.am
index cce1fef..b897616 100644
--- a/hw/xnest/Makefile.am
+++ b/hw/xnest/Makefile.am
@@ -1,4 +1,10 @@
 bin_PROGRAMS = Xnest
+noinst_LIBRARIES = libfbcmap.a
+
+AM_CFLAGS = -DHAVE_XNEST_CONFIG_H \
+            -DNO_HW_ONLY_EXTS \
+            $(DIX_CFLAGS) \
+            $(XNESTMODULES_CFLAGS)
 
 SRCS =	Args.c \
 	Args.h \
@@ -37,23 +43,17 @@ SRCS =	Args.c \
 	xnest-config.h \
 	$(top_srcdir)/Xext/dpmsstubs.c \
 	$(top_srcdir)/Xi/stubs.c \
-	$(top_srcdir)/mi/miinitext.c \
-	$(top_srcdir)/fb/fbcmap.c
+	$(top_srcdir)/mi/miinitext.c
 
+libfbcmap_a_SOURCES = $(top_srcdir)/fb/fbcmap.c
+libfbcmap_a_CFLAGS = $(AM_CFLAGS) -DXFree86Server
 
 Xnest_SOURCES = $(SRCS)
 
 Xnest_LDADD = $(XORG_CORE_LIBS) \
               $(XNEST_LIBS) \
-              $(XNESTMODULES_LIBS)
-
-Xnest_LDFLAGS =
-
-AM_CFLAGS = -DHAVE_XNEST_CONFIG_H \
-            -DNO_HW_ONLY_EXTS \
-            -DXFree86Server \
-            $(DIX_CFLAGS) \
-            $(XNESTMODULES_CFLAGS)
+              $(XNESTMODULES_LIBS) \
+	      libfbcmap.a
 
 EXTRA_DIST = os2Stub.c \
              icon \
diff-tree 236f04b638e7d4d1656c6bedd8a6e8d7cec285ec (from eb228e8d1eaa78911541b2fec5d04a74c1299718)
Author: Dave Airlie <airlied at linux.ie>
Date:   Mon Feb 5 09:09:12 2007 +1100

    remove array_cache from everywhere

diff --git a/GL/mesa/.gitignore b/GL/mesa/.gitignore
index 44e2733..a00885d 100644
--- a/GL/mesa/.gitignore
+++ b/GL/mesa/.gitignore
@@ -2,8 +2,6 @@ X/drivers
 X/glxheader.h
 X/xmesaP.h
 X/xm*.c
-array_cache/*.c
-array_cache/*.h
 mesa/drivers
 mesa/glxheader.h
 mesa/xm*.c
diff --git a/GL/mesa/X/Makefile.am b/GL/mesa/X/Makefile.am
index 2a9f422..45345a7 100644
--- a/GL/mesa/X/Makefile.am
+++ b/GL/mesa/X/Makefile.am
@@ -2,7 +2,6 @@ noinst_LTLIBRARIES = libX.la
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff --git a/GL/mesa/glapi/Makefile.am b/GL/mesa/glapi/Makefile.am
index de457b9..db79114 100644
--- a/GL/mesa/glapi/Makefile.am
+++ b/GL/mesa/glapi/Makefile.am
@@ -7,7 +7,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff --git a/GL/mesa/main/Makefile.am b/GL/mesa/main/Makefile.am
index 64b383d..20b7935 100644
--- a/GL/mesa/main/Makefile.am
+++ b/GL/mesa/main/Makefile.am
@@ -7,7 +7,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff --git a/GL/mesa/math/Makefile.am b/GL/mesa/math/Makefile.am
index 5e99d90..c7c5642 100644
--- a/GL/mesa/math/Makefile.am
+++ b/GL/mesa/math/Makefile.am
@@ -7,7 +7,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff --git a/GL/mesa/shader/Makefile.am b/GL/mesa/shader/Makefile.am
index 4bd5736..3519545 100644
--- a/GL/mesa/shader/Makefile.am
+++ b/GL/mesa/shader/Makefile.am
@@ -9,7 +9,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff --git a/GL/mesa/shader/grammar/Makefile.am b/GL/mesa/shader/grammar/Makefile.am
index 0974d5b..332c8e9 100644
--- a/GL/mesa/shader/grammar/Makefile.am
+++ b/GL/mesa/shader/grammar/Makefile.am
@@ -7,7 +7,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../../X \
-           -I../../array_cache \
            -I../../glapi \
            -I../../main \
            -I../../math \
diff --git a/GL/mesa/shader/slang/Makefile.am b/GL/mesa/shader/slang/Makefile.am
index 8f2636e..04001c4 100644
--- a/GL/mesa/shader/slang/Makefile.am
+++ b/GL/mesa/shader/slang/Makefile.am
@@ -8,7 +8,6 @@ AM_CFLAGS = \
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../grammar \
            -I../../X \
-           -I../../array_cache \
            -I../../glapi \
            -I../../main \
            -I../../math \
diff --git a/GL/mesa/swrast/Makefile.am b/GL/mesa/swrast/Makefile.am
index d972af6..5ed6576 100644
--- a/GL/mesa/swrast/Makefile.am
+++ b/GL/mesa/swrast/Makefile.am
@@ -7,7 +7,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff --git a/GL/mesa/swrast_setup/Makefile.am b/GL/mesa/swrast_setup/Makefile.am
index 8d70408..1f3c031 100644
--- a/GL/mesa/swrast_setup/Makefile.am
+++ b/GL/mesa/swrast_setup/Makefile.am
@@ -7,7 +7,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff --git a/GL/mesa/tnl/Makefile.am b/GL/mesa/tnl/Makefile.am
index b59a5fa..5d9bdb1 100644
--- a/GL/mesa/tnl/Makefile.am
+++ b/GL/mesa/tnl/Makefile.am
@@ -7,7 +7,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff --git a/GL/mesa/vbo/Makefile.am b/GL/mesa/vbo/Makefile.am
index 09046bb..9943f2a 100644
--- a/GL/mesa/vbo/Makefile.am
+++ b/GL/mesa/vbo/Makefile.am
@@ -7,7 +7,6 @@ AM_CFLAGS = \
 
 INCLUDES = -I at MESA_SOURCE@/include \
            -I../X \
-           -I../array_cache \
            -I../glapi \
            -I../main \
            -I../math \
diff-tree eb228e8d1eaa78911541b2fec5d04a74c1299718 (from fb1bc1c65b88527b42a0e4abed23e5ddaae711b7)
Author: Alan Hourihane <alanh at fairlite.demon.co.uk>
Date:   Sun Feb 4 22:06:59 2007 +0000

    clean up more of the vbo fallout

diff --git a/configure.ac b/configure.ac
index d23c3c9..4a33ac0 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1838,7 +1838,6 @@ Makefile
 GL/Makefile
 GL/glx/Makefile
 GL/mesa/Makefile
-GL/mesa/array_cache/Makefile
 GL/mesa/glapi/Makefile
 GL/mesa/main/Makefile
 GL/mesa/math/Makefile
diff-tree fb1bc1c65b88527b42a0e4abed23e5ddaae711b7 (from d8e148ec841d340327e6813127b0e0ffc4db712d)
Author: Dave Airlie <airlied at linux.ie>
Date:   Sun Feb 4 18:39:58 2007 +1100

    add vbo to .gitignore

diff --git a/GL/mesa/.gitignore b/GL/mesa/.gitignore
index 82ab827..44e2733 100644
--- a/GL/mesa/.gitignore
+++ b/GL/mesa/.gitignore
@@ -30,3 +30,5 @@ tnl/*.c
 tnl/*.h
 x86
 x86-64
+vbo/*.c
+vbo/*.h
diff-tree d8e148ec841d340327e6813127b0e0ffc4db712d (from 5dcad9e9d7d9993d65f989219bee94a060bbf476)
Author: Dave Airlie <airlied at linux.ie>
Date:   Sun Feb 4 18:39:04 2007 +1100

    update xserver for vbo code in mesa

diff --git a/GL/mesa/Makefile.am b/GL/mesa/Makefile.am
index 5393628..99d3834 100644
--- a/GL/mesa/Makefile.am
+++ b/GL/mesa/Makefile.am
@@ -1,4 +1,4 @@
-SUBDIRS = main math swrast swrast_setup tnl shader X glapi
+SUBDIRS = main math swrast swrast_setup tnl shader X glapi vbo
 
 noinst_LTLIBRARIES = libGLcore.la
 
@@ -11,4 +11,5 @@ libGLcore_la_LIBADD = main/libmain.la \
                       shader/libshader.la \
 		      shader/grammar/libgrammar.la \
 		      shader/slang/libslang.la \
+                      vbo/libvbo.la \
                       X/libX.la
diff --git a/GL/mesa/tnl/Makefile.am b/GL/mesa/tnl/Makefile.am
index 717e6fd..b59a5fa 100644
--- a/GL/mesa/tnl/Makefile.am
+++ b/GL/mesa/tnl/Makefile.am
@@ -19,13 +19,9 @@ INCLUDES = -I at MESA_SOURCE@/include \
            -I.. \
            -I$(top_srcdir)/hw/xfree86/os-support
 
-nodist_libtnl_la_SOURCES = t_array_api.c \
-                      t_array_import.c \
-                      t_context.c \
+nodist_libtnl_la_SOURCES = t_context.c \
+                      t_draw.c \
                       t_pipeline.c \
-                      t_save_api.c \
-                      t_save_loopback.c \
-                      t_save_playback.c \
                       t_vb_arbprogram.c \
                       t_vb_arbprogram_sse.c \
                       t_vb_arbshader.c \
@@ -42,9 +38,4 @@ nodist_libtnl_la_SOURCES = t_array_api.c
                       t_vertex.c \
                       t_vertex_generic.c \
                       t_vertex_sse.c \
-                      t_vp_build.c \
-                      t_vtx_api.c \
-                      t_vtx_eval.c \
-                      t_vtx_exec.c \
-                      t_vtx_generic.c \
-                      t_vtx_x86.c
+                      t_vp_build.c
diff --git a/GL/mesa/vbo/Makefile.am b/GL/mesa/vbo/Makefile.am
new file mode 100644
index 0000000..09046bb
--- /dev/null
+++ b/GL/mesa/vbo/Makefile.am
@@ -0,0 +1,36 @@
+noinst_LTLIBRARIES = libvbo.la
+
+AM_CFLAGS = \
+	$(DIX_CFLAGS) \
+	-DXFree86Server \
+	@GLX_DEFINES@
+
+INCLUDES = -I at MESA_SOURCE@/include \
+           -I../X \
+           -I../array_cache \
+           -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 4205606..7d1e06e 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -148,6 +148,15 @@ symlink_mesa_shader_slang_library() {
     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
@@ -205,6 +214,7 @@ symlink_mesa() {
     symlink_mesa_glapi
     symlink_mesa_ppc
     symlink_mesa_sparc
+    symlink_mesa_vbo
     symlink_mesa_x86
     symlink_mesa_x8664
 }
diff --git a/configure.ac b/configure.ac
index c0a2770..d23c3c9 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1848,6 +1848,7 @@ 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
diff-tree 5dcad9e9d7d9993d65f989219bee94a060bbf476 (from 170a55022ebc7b148bff93886eda152a0d5ce79a)
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Fri Feb 2 14:44:55 2007 -0800

    Fix bus error on startup in 64-bit Xephyr
    
    hostx_get_visual_masks takes unsigned long * arguments, but was being
    passed pointers to CARD32's.

diff --git a/hw/kdrive/ephyr/ephyr.c b/hw/kdrive/ephyr/ephyr.c
index 7db8675..2ca51c3 100644
--- a/hw/kdrive/ephyr/ephyr.c
+++ b/hw/kdrive/ephyr/ephyr.c
@@ -81,7 +81,8 @@ Bool
 ephyrScreenInitialize (KdScreenInfo *screen, EphyrScrPriv *scrpriv)
 {
   int width = 640, height = 480; 
-
+  unsigned long redMask, greenMask, blueMask;
+  
   if (hostx_want_screen_size(&width, &height) 
       || !screen->width || !screen->height)
     {
@@ -133,30 +134,24 @@ ephyrScreenInitialize (KdScreenInfo *scr
 	{
 	  screen->fb[0].depth = 15;
 	  screen->fb[0].bitsPerPixel = 16;
-	  
-	  hostx_get_visual_masks (&screen->fb[0].redMask,
-				  &screen->fb[0].greenMask,
-				  &screen->fb[0].blueMask);
-	  
 	}
       else if (screen->fb[0].depth <= 16)
 	{
 	  screen->fb[0].depth = 16;
 	  screen->fb[0].bitsPerPixel = 16;
-	  
-	  hostx_get_visual_masks (&screen->fb[0].redMask,
-				  &screen->fb[0].greenMask,
-				  &screen->fb[0].blueMask);
 	}
       else
 	{
 	  screen->fb[0].depth = 24;
 	  screen->fb[0].bitsPerPixel = 32;
-	  
-	  hostx_get_visual_masks (&screen->fb[0].redMask,
-				  &screen->fb[0].greenMask,
-				  &screen->fb[0].blueMask);
 	}
+
+      hostx_get_visual_masks (&redMask, &greenMask, &blueMask);
+
+      screen->fb[0].redMask = (Pixel) redMask;
+      screen->fb[0].greenMask = (Pixel) greenMask;
+      screen->fb[0].blueMask = (Pixel) blueMask;
+
     }
   
   scrpriv->randr = screen->randr;
diff-tree 170a55022ebc7b148bff93886eda152a0d5ce79a (from e6a505be84f5f72349d6860dc5a5058367516019)
Author: Alan Hourihane <alanh at fairlite.demon.co.uk>
Date:   Fri Feb 2 20:56:12 2007 +0000

    remove file

diff --git a/GL/mesa/array_cache/Makefile.am b/GL/mesa/array_cache/Makefile.am
deleted file mode 100644
index 5016b73..0000000
--- a/GL/mesa/array_cache/Makefile.am
+++ /dev/null
@@ -1,21 +0,0 @@
-noinst_LTLIBRARIES = libac.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../array_cache \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libac_la_SOURCES = ac_context.c ac_import.c
diff-tree e6a505be84f5f72349d6860dc5a5058367516019 (from af20485ec370801f2aabfaeae17bbd030a849bd1)
Author: Dan Nicholson <dan at conor.dwcab.com>
Date:   Fri Feb 2 20:53:01 2007 +0000

    The array_cache sources don't exist anymore in the Mesa tree,
    so we shouldn't try to build them.

diff --git a/GL/mesa/Makefile.am b/GL/mesa/Makefile.am
index 18eebfc..5393628 100644
--- a/GL/mesa/Makefile.am
+++ b/GL/mesa/Makefile.am
@@ -1,11 +1,10 @@
-SUBDIRS = main math array_cache swrast swrast_setup tnl shader X glapi
+SUBDIRS = main math swrast swrast_setup tnl shader X glapi
 
 noinst_LTLIBRARIES = libGLcore.la
 
 libGLcore_la_SOURCES = dummy.c
 libGLcore_la_LIBADD = main/libmain.la \
                       math/libmath.la \
-                      array_cache/libac.la \
                       swrast/libswrast.la \
                       swrast_setup/libss.la \
                       tnl/libtnl.la \
diff-tree af20485ec370801f2aabfaeae17bbd030a849bd1 (from cf5b29d75dad7c74543f49f010c817623a3df747)
Author: Alan Hourihane <alanh at fairlite.demon.co.uk>
Date:   Fri Feb 2 19:14:46 2007 +0000

    Remove array_cache for recent Mesa changes

diff --git a/GL/symlink-mesa.sh b/GL/symlink-mesa.sh
index 9687ce8..4205606 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -85,15 +85,6 @@ symlink_mesa_math() {
     done
 }
 
-symlink_mesa_ac() {
-    src_dir src/mesa/array_cache
-    dst_dir mesa/array_cache
-
-    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
@@ -203,7 +194,6 @@ symlink_mesa_x8664() {
 symlink_mesa() {
     symlink_mesa_main
     symlink_mesa_math
-    symlink_mesa_ac
     symlink_mesa_swrast
     symlink_mesa_ss
     symlink_mesa_tnl
diff-tree cf5b29d75dad7c74543f49f010c817623a3df747 (from 4f2f3233c808fd86bf9f6c09937feda9e0b367fd)
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Feb 2 12:57:38 2007 +0200

    dmx: drop leftover __GLXdrawablePrivateRec struct.

diff --git a/hw/dmx/glxProxy/glxdrawable.h b/hw/dmx/glxProxy/glxdrawable.h
index 59fffa7..baed683 100644
--- a/hw/dmx/glxProxy/glxdrawable.h
+++ b/hw/dmx/glxProxy/glxdrawable.h
@@ -49,58 +49,6 @@ typedef struct {
 
 } __GLXpixmap;
 
-struct __GLXdrawablePrivateRec {
-    /*
-    ** list of drawable private structs
-    */
-    struct __GLXdrawablePrivateRec *last;
-    struct __GLXdrawablePrivateRec *next;
-
-    DrawablePtr pDraw;
-    XID drawId;
-    __GLXpixmap *pGlxPixmap;
-
-    /*
-    ** Either DRAWABLE_PIXMAP or DRAWABLE_WINDOW, copied from pDraw above.
-    ** Needed by the resource freer because pDraw might already have been
-    ** freed.
-    */
-    int type;
-
-    /*
-    ** Configuration of the visual to which this drawable was created.
-    */
-    __GLXvisualConfig *pGlxVisual;
-
-    /*
-    ** cached drawable size and origin
-    */
-    GLint xorigin, yorigin;
-    GLint width, height;
-
-    /*
-    ** list of contexts bound to this drawable
-    */
-    struct __GLXcontextRec *glxc;
-
-    /*
-    ** "methods" that the drawble should be able to respond to.
-    */
-    void (*freeBuffers)(struct __GLXdrawablePrivateRec *);
-    void (*updatePalette)(struct __GLXdrawablePrivateRec *);
-    GLboolean (*swapBuffers)(struct __GLXdrawablePrivateRec *);
-
-    /*
-    ** The GL drawable (information shared between GLX and the GL core)
-    */
-    __GLdrawablePrivate glPriv;
-
-    /*
-    ** reference count
-    */
-    int refCount;
-};
-
 typedef struct {
     DrawablePtr pDraw;
     int type;
diff --git a/hw/dmx/glxProxy/glxserver.h b/hw/dmx/glxProxy/glxserver.h
index db5be43..021d4c1 100644
--- a/hw/dmx/glxProxy/glxserver.h
+++ b/hw/dmx/glxProxy/glxserver.h
@@ -58,9 +58,6 @@
 #include <GL/glxproto.h>
 #include <GL/glxint.h>
 
-/* For glxscreens.h */
-typedef struct __GLXdrawablePrivateRec __GLXdrawablePrivate;
-
 #include "glxscreens.h"
 #include "glxdrawable.h"
 #include "glxcontext.h"
diff-tree 4f2f3233c808fd86bf9f6c09937feda9e0b367fd (from 8274ea6aa97b06a56b7468c3908894c0ff72b687)
Author: Eric Anholt <eric at anholt.net>
Date:   Thu Feb 1 15:10:29 2007 -0800

    Fix the size expectations of xRRSetCrtcGamma.
    
    It was using REQUEST_SIZE_MATCH (client request length must equal request size)
    rather than REQUEST_AT_LEAST_SIZE (client request length must be at least
    big enough for request size), and this request has data following the request
    structure.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index c84ec61..fdd1d42 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -870,7 +870,7 @@ ProcRRSetCrtcGamma (ClientPtr client)
     unsigned long		len;
     CARD16			*red, *green, *blue;
     
-    REQUEST_SIZE_MATCH(xRRSetCrtcGammaReq);
+    REQUEST_AT_LEAST_SIZE(xRRSetCrtcGammaReq);
     crtc = LookupCrtc (client, stuff->crtc, DixWriteAccess);
     if (!crtc)
 	return RRErrorBase + BadRRCrtc;
diff-tree 8274ea6aa97b06a56b7468c3908894c0ff72b687 (from 8bce182568f14edfb03911d8c5d791fd83bb6222)
Author: Eric Anholt <eric at anholt.net>
Date:   Thu Feb 1 12:15:54 2007 -0800

    Set the Damage version supported in the server, instead of using damageproto.
    
    This was caught by distributions upgrading damageproto to 1.1, before the
    server they had supported it.  The server then advertised the new version
    without supporting the protocol.

diff --git a/damageext/damageext.c b/damageext/damageext.c
index ae1091e..739d20f 100755
--- a/damageext/damageext.c
+++ b/damageext/damageext.c
@@ -35,6 +35,13 @@ int		DamageClientPrivateIndex;
 RESTYPE		DamageExtType;
 RESTYPE		DamageExtWinType;
 
+/* Version of the damage extension supported by the server, as opposed to the
+ * DAMAGE_* defines from damageproto for what version the proto header
+ * supports.
+ */
+#define SERVER_DAMAGE_MAJOR	1
+#define SERVER_DAMAGE_MINOR	1
+
 #define prScreen	screenInfo.screens[0]
 
 static void
@@ -143,16 +150,16 @@ ProcDamageQueryVersion(ClientPtr client)
     rep.type = X_Reply;
     rep.length = 0;
     rep.sequenceNumber = client->sequence;
-    if (stuff->majorVersion < DAMAGE_MAJOR) {
+    if (stuff->majorVersion < SERVER_DAMAGE_MAJOR) {
 	rep.majorVersion = stuff->majorVersion;
 	rep.minorVersion = stuff->minorVersion;
     } else {
-	rep.majorVersion = DAMAGE_MAJOR;
-	if (stuff->majorVersion == DAMAGE_MAJOR && 
-	    stuff->minorVersion < DAMAGE_MINOR)
+	rep.majorVersion = SERVER_DAMAGE_MAJOR;
+	if (stuff->majorVersion == SERVER_DAMAGE_MAJOR && 
+	    stuff->minorVersion < SERVER_DAMAGE_MINOR)
 	    rep.minorVersion = stuff->minorVersion;
 	else
-	    rep.minorVersion = DAMAGE_MINOR;
+	    rep.minorVersion = SERVER_DAMAGE_MINOR;
     }
     pDamageClient->major_version = rep.majorVersion;
     pDamageClient->minor_version = rep.minorVersion;
diff-tree 8bce182568f14edfb03911d8c5d791fd83bb6222 (from 31f2d4a57e04f5ea635fbb50c508405c4fc37b65)
Author: Eric Anholt <eric at anholt.net>
Date:   Mon Jan 29 17:30:59 2007 -0800

    Restore a few important lines killed in the previous commit.
    
    Typical results were failure to sync, and a black screen.

diff --git a/hw/xfree86/common/xf86Mode.c b/hw/xfree86/common/xf86Mode.c
index 7f5ae36..d5085b5 100644
--- a/hw/xfree86/common/xf86Mode.c
+++ b/hw/xfree86/common/xf86Mode.c
@@ -725,6 +725,11 @@ xf86SetModeCrtc(DisplayModePtr p, int ad
         p->CrtcVSyncEnd         *= p->VScan;
         p->CrtcVTotal           *= p->VScan;
     }
+    p->CrtcVBlankStart = min(p->CrtcVSyncStart, p->CrtcVDisplay);
+    p->CrtcVBlankEnd = max(p->CrtcVSyncEnd, p->CrtcVTotal);
+    p->CrtcHBlankStart = min(p->CrtcHSyncStart, p->CrtcHDisplay);
+    p->CrtcHBlankEnd = max(p->CrtcHSyncEnd, p->CrtcHTotal);
+
     p->CrtcHAdjusted = FALSE;
     p->CrtcVAdjusted = FALSE;
 }
diff-tree 31f2d4a57e04f5ea635fbb50c508405c4fc37b65 (from 1627af54497bee659ea30f2850b39cbbf576e22d)
Author: Eric Anholt <eric at anholt.net>
Date:   Mon Jan 29 09:39:33 2007 -0800

    Bug #9680: Remove bogus blank length limiting in xf86SetModeCrtc().
    
    Our modes typically come from EDID or default modes, and when the monitor
    asks for a specific mode, deciding to tweak it usually results in incorrect
    display.  And if the user is specifying a mode by hand, tweaking it then is
    still pretty rude.
    
    Reviewed by: ajax

diff --git a/hw/xfree86/common/xf86Mode.c b/hw/xfree86/common/xf86Mode.c
index 3cebac7..7f5ae36 100644
--- a/hw/xfree86/common/xf86Mode.c
+++ b/hw/xfree86/common/xf86Mode.c
@@ -727,45 +727,6 @@ xf86SetModeCrtc(DisplayModePtr p, int ad
     }
     p->CrtcHAdjusted = FALSE;
     p->CrtcVAdjusted = FALSE;
-
-    /*
-     * XXX
-     *
-     * The following is taken from VGA, but applies to other cores as well.
-     */
-    p->CrtcVBlankStart = min(p->CrtcVSyncStart, p->CrtcVDisplay);
-    p->CrtcVBlankEnd = max(p->CrtcVSyncEnd, p->CrtcVTotal);
-    if ((p->CrtcVBlankEnd - p->CrtcVBlankStart) >= 127) {
-        /* 
-         * V Blanking size must be < 127.
-         * Moving blank start forward is safer than moving blank end
-         * back, since monitors clamp just AFTER the sync pulse (or in
-         * the sync pulse), but never before.
-         */
-        p->CrtcVBlankStart = p->CrtcVBlankEnd - 127;
-	/*
-	 * If VBlankStart is now > VSyncStart move VBlankStart
-	 * to VSyncStart using the maximum width that fits into
-	 * VTotal.
-	 */
-	if (p->CrtcVBlankStart > p->CrtcVSyncStart) {
-	    p->CrtcVBlankStart = p->CrtcVSyncStart;
-	    p->CrtcVBlankEnd = min(p->CrtcHBlankStart + 127, p->CrtcVTotal);
-	}
-    }
-    p->CrtcHBlankStart = min(p->CrtcHSyncStart, p->CrtcHDisplay);
-    p->CrtcHBlankEnd = max(p->CrtcHSyncEnd, p->CrtcHTotal);
-
-    if ((p->CrtcHBlankEnd - p->CrtcHBlankStart) >= 63 * 8) {
-        /*
-         * H Blanking size must be < 63*8. Same remark as above.
-         */
-        p->CrtcHBlankStart = p->CrtcHBlankEnd - 63 * 8;
-	if (p->CrtcHBlankStart > p->CrtcHSyncStart) {
-	    p->CrtcHBlankStart = p->CrtcHSyncStart;
-	    p->CrtcHBlankEnd = min(p->CrtcHBlankStart + 63 * 8, p->CrtcHTotal);
-	}
-    }
 }
 
 /**



More information about the xorg-commit mailing list