xserver: Branch 'xorg-server-1.2-apple' - 140 commits

Jeremy Huddleston jeremyhu at kemper.freedesktop.org
Mon Nov 19 17:49:35 PST 2007


 GL/mesa/X/xf86glx.c              |    4 
 configure.ac                     |    3 
 damageext/damageext.c            |   57 +
 exa/exa.c                        |  141 ++-
 exa/exa.h                        |   12 
 exa/exa_accel.c                  |  167 ++--
 exa/exa_migration.c              |  223 +++--
 exa/exa_offscreen.c              |   71 +
 exa/exa_priv.h                   |   31 
 exa/exa_render.c                 |   66 +
 exa/exa_unaccel.c                |   32 
 fb/fbpict.h                      |    3 
 hw/dmx/glxProxy/glxdrawable.h    |   52 -
 hw/dmx/glxProxy/glxserver.h      |    3 
 hw/xfree86/Makefile.am           |    7 
 hw/xfree86/common/Makefile.am    |    2 
 hw/xfree86/ddc/Makefile.am       |    5 
 hw/xfree86/ddc/ddcProperty.c     |    1 
 hw/xfree86/ddc/xf86DDC.c         |    4 
 hw/xfree86/exa/Makefile.am       |    2 
 hw/xfree86/exa/exa.man.pre       |    2 
 hw/xfree86/i2c/Makefile.am       |    5 
 hw/xfree86/loader/Makefile.am    |    2 
 hw/xfree86/loader/loadmod.c      |   26 
 hw/xfree86/loader/xf86sym.c      |   88 ++
 hw/xfree86/modes/Makefile.am     |   27 
 hw/xfree86/modes/xf86Crtc.c      | 1587 +++++++++++++++++++++++++++++++++++++++
 hw/xfree86/modes/xf86Crtc.h      |  555 +++++++++++++
 hw/xfree86/modes/xf86DiDGA.c     |  280 ++++++
 hw/xfree86/modes/xf86EdidModes.c |  339 ++++++++
 hw/xfree86/modes/xf86Modes.c     |  635 +++++++++++++++
 hw/xfree86/modes/xf86Modes.h     |   85 ++
 hw/xfree86/modes/xf86RandR12.c   |  950 +++++++++++++++++++++++
 hw/xfree86/modes/xf86RandR12.h   |   37 
 hw/xfree86/modes/xf86Rename.h    |   77 +
 hw/xfree86/modes/xf86Rotate.c    |  402 +++++++++
 hw/xfree86/modes/xf86cvt.c       |  303 +++++++
 hw/xfree86/ramdac/xf86Cursor.c   |    3 
 hw/xfree86/xf1bpp/Makefile.am    |   90 +-
 miext/damage/damage.c            |  150 ++-
 miext/damage/damage.h            |    3 
 miext/damage/damagestr.h         |    3 
 randr/Makefile.am                |   12 
 randr/mirandr.c                  |  165 ++--
 randr/randr.c                    | 1300 +++++--------------------------
 randr/randrstr.h                 |  764 +++++++++++++++++-
 randr/rrcrtc.c                   |  891 +++++++++++++++++++++
 randr/rrdispatch.c               |  210 +++++
 randr/rrinfo.c                   |  339 ++++++++
 randr/rrmode.c                   |  242 +++++
 randr/rroutput.c                 |  465 +++++++++++
 randr/rrpointer.c                |  145 +++
 randr/rrproperty.c               |  638 +++++++++++++++
 randr/rrscreen.c                 |  958 +++++++++++++++++++++++
 randr/rrsdispatch.c              |  305 +++++++
 randr/rrxinerama.c               |  433 ++++++++++
 56 files changed, 11869 insertions(+), 1533 deletions(-)

New commits:
commit 71d937879636a60d1e924480ca8ae804515e7806
Merge: 9304a3f... 848c19a...
Author: Jeremy Huddleston <jeremy at tifa.local>
Date:   Mon Nov 19 03:17:42 2007 -0800

    Fast-forward xorg-server-1.2-apple branch point to server-1.2-branch
    Conflicts:
    	configure.ac

commit 9304a3f9848cc4349062e9555cbe88370798f546
Author: Jeremy Huddleston <jeremy at tifa.local>
Date:   Mon Nov 19 02:17:44 2007 -0800

    XDarwin dead code removal
    Removed unused code from the tree
    Moved some files to more appropriate locations

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index f82ed02..a77c006 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -4,7 +4,7 @@ AM_CPPFLAGS = @XORG_INCS@ -I$(top_srcdir)/Xext -I$(top_srcdir)/miext/rootless -D
 SUBDIRS = quartz utils
 
 bin_PROGRAMS = Xquartz
-man1_MANS = apple/Xquartz.man
+man1_MANS = Xquartz.man
 
 Xquartz_SOURCES = darwin.c \
 		  darwinEvents.c \
diff --git a/hw/darwin/XDarwin.man b/hw/darwin/XDarwin.man
deleted file mode 100644
index 143fb7c..0000000
--- a/hw/darwin/XDarwin.man
+++ /dev/null
@@ -1,204 +0,0 @@
-.\"
-.TH XDARWIN 1 __vendorversion__
-.SH NAME
-XDarwin \- X window system server for Darwin operating system
-.SH SYNOPSIS
-.B XDarwin
-[ options ] ...
-.SH DESCRIPTION
-#ifdef DARWIN_WITH_QUARTZ
-.I XDarwin
-is the X window server for Mac OS X and the Darwin operating system
-provided by the X.Org Foundation.
-.I XDarwin
-can run in three different modes. On Mac OS X,
-.I XDarwin
-runs in parallel with Aqua in full screen or rootless modes. These modes
-are called Quartz modes, named after the Quartz 2D compositing engine used
-by Aqua. XDarwin can also be run from the Darwin text console in IOKit mode.
-.PP
-When running from the console,
-.I XDarwin
-acts as the window server and uses IOKit services to access the display
-framebuffer, mouse and keyboard and to provide a layer of hardware
-abstraction. In console mode,
-.I XDarwin
-will normally be started by the \fIxdm(1)\fP display manager or by a script
-that runs the program \fIxinit(1)\fP.
-.PP
-When running with the Mac OS X Aqua GUI,
-.I XDarwin
-will normally be started by launching from the Finder, but it may also be
-started from the command line with the \fB\-quartz\fP, \fB\-fullscreen\fP, or
-\fB\-rootless\fP options. Note that the defaults for various command line
-options are set by the
-.I XDarwin
-application preferences in the Quartz modes.
-.PP
-In full screen Quartz mode, when the X Window System is active, it takes over
-the entire screen. CoreGraphics is used to capture and draw to the screen. The
-.I XDarwin
-application allows easy switching between the Mac OS X and X window
-desktops. More information is available in the Help menu of the
-.I XDarwin
-application.
-.PP
-In rootless mode, the X window system and Aqua 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 Aqua
-handles the desktop background.
-#else
-.I XDarwin
-is the X window server for Mac OS X and the Darwin operating system
-provided by the X.Org Foundation. This version of
-.I XDarwin
-can only be started from the Darwin text console. The Mac OS X Aqua GUI, if
-present, must be shut down.
-.I XDarwin
-uses IOKit services to access the display
-framebuffer, mouse and keyboard and to provide a layer of hardware
-abstraction.
-.I XDarwin
-will normally be started by the \fIxdm(1)\fP display manager or by a script
-that runs the program \fIxinit(1)\fP.
-#endif
-.SH OPTIONS
-.PP
-In addition to the normal server options described in the \fIXserver(1)\fP
-manual page, \fIXDarwin\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 "\-keymap \fIfile\fP"
-On startup \fIXDarwin\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 \fIXDarwin\fP translates a Darwin keymapping into an X keymap.
-With this option XDarwin queries the kernel for the current keymapping
-instead of reading it from a file. This will often fail on newer kernels.
-#ifdef DARWIN_WITH_QUARTZ
-.TP 8
-.B "\-size \fIwidth\fP \fIheight\fP"
-Sets the screen resolution for the X server to use.
-Ignored in rootless mode.
-.TP 8
-.B "\-depth \fIdepth\fP"
-Specifies the color bit depth to use. Currently only 8, 15, and 24 color bits
-per pixel are supported.
-Ignored in rootless mode.
-.TP 8
-.B "\-refresh \fIrate\fP"
-Gives the refresh rate to use in Hz. For LCD displays this should be 0.
-Ignored in rootless mode.
-.TP 8
-.B \-fullscreen
-Run full screen in parallel with Mac OS X Aqua GUI.
-.TP 8
-.B \-rootless
-Run rootless inside Mac OS X Aqua GUI.
-.TP 8
-.B \-quartz
-Run in parallel with the Mac OS X Aqua GUI using the default mode.
-#else
-.TP 8
-.B "\-size \fIwidth\fP \fIheight\fP"
-Sets the screen resolution for the X server to use.
-.TP 8
-.B "\-depth \fIdepth\fP"
-Specifies the color bit depth to use. Currently only 8, 15, and 24 color bits
-per pixel are supported.
-.TP 8
-.B "\-refresh \fIrate\fP"
-Gives the refresh rate to use in Hz. For LCD displays this should be 0.
-#endif
-.TP 8
-.B \-showconfig
-Print out the server version and patchlevel.
-.TP 8
-.B \-version
-Same as \fB\-showconfig\fP.
-.SH "SEE ALSO"
-.PP
-X(__miscmansuffix__), Xorg(1), Xserver(1), xdm(1), xinit(1)
-.SH BUGS
-.I XDarwin
-and this man page still have many limitations. Some of the more obvious
-ones are:
-.br
-- The display mode cannot be changed once the X server has started.
-.br
-- A screen saver is not supported.
-.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/Xquartz.man b/hw/darwin/Xquartz.man
new file mode 100644
index 0000000..37a7f1a
--- /dev/null
+++ b/hw/darwin/Xquartz.man
@@ -0,0 +1,156 @@
+.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/X11Application.h b/hw/darwin/apple/X11Application.h
deleted file mode 100644
index fb153e7..0000000
--- a/hw/darwin/apple/X11Application.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/* 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 "org.x.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
deleted file mode 100644
index 38359e6..0000000
--- a/hw/darwin/apple/X11Application.m
+++ /dev/null
@@ -1,1088 +0,0 @@
-/* X11Application.m -- subclass of NSApplication to multiplex events
- 
- 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 <mach/mach.h>
-#include <unistd.h>
-#include <pthread.h>
-
-#include "rootlessCommon.h"
-
-WindowPtr xprGetXWindowFromAppKit(int windowNumber); // xpr/xprFrame.c
-
-#define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
-
-int X11EnableKeyEquivalents = TRUE;
-int quartzHasRoot = FALSE, quartzEnableRootless = TRUE;
-
-extern int darwinFakeButtons;
-extern Bool enable_stereo; 
-
-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.2 (xorg-server-1.2a11)",
-					 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 an (AppKit) 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. */
-      WindowPtr pWin = xprGetXWindowFromAppKit([e windowNumber]);
-      if (pWin) RootlessReorderWindow(pWin);
-      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];
-	if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
-      }
-      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
-{
-    QuartzMessageServerThread(kXDarwinBringAllToFront, 0);
-}
-
-- (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 UTF8String];
-			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]);
-  
-  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;
-	
-    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
deleted file mode 100644
index 954d0ab..0000000
--- a/hw/darwin/apple/X11Controller.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/* 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
deleted file mode 100644
index df90049..0000000
--- a/hw/darwin/apple/X11Controller.m
+++ /dev/null
@@ -1,748 +0,0 @@
-/* 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>
-
- 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 *argv[7];
-  int child1, child2 = 0;
-  int status;
-	
-  argv[0] = "/usr/bin/login";
-  argv[1] = "-fp";
-  argv[2] = getlogin();
-  argv[3] = "/bin/sh";
-  argv[4] = "-c";
-  argv[5] = command;
-  argv[6] = 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 ((CFStringRef)NSLocalizedString(@"Mac Help", no comment), 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
deleted file mode 100644
index 37a7f1a..0000000
--- a/hw/darwin/apple/Xquartz.man
+++ /dev/null
@@ -1,156 +0,0 @@
-.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/bundle/Dutch.lproj/Credits.rtf b/hw/darwin/bundle/Dutch.lproj/Credits.rtf
deleted file mode 100644
index 5858e59..0000000
--- a/hw/darwin/bundle/Dutch.lproj/Credits.rtf
+++ /dev/null
@@ -1,168 +0,0 @@
-{\rtf1\mac\ansicpg10000\cocoartf102
-{\fonttbl\f0\fswiss\fcharset77 Helvetica;\f1\fswiss\fcharset77 Helvetica-Bold;\f2\fswiss\fcharset77 Helvetica-Oblique;
-}
-{\colortbl;\red255\green255\blue255;}
-\vieww9000\viewh9000\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 This product includes software developed by The XFree86 Project, Inc  (http://www.xfree86.org/) and its contributors. The following people contributed to Darwin/Mac OS X support.\
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Contributors to Xorg Foundation Release:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f2\i Working left and right Ctrl, Alt (Option), Meta (Command) and Shift keys.
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\f1\b \cf0 Contributors to XFree86 4.4:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper\
-     
-\f2\i Rootless acceleration and Apple-WM extension
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Additional XonX Contributors to XFree86 4.3:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro\
-     
-\f2\i Portuguese localization
-\f0\i0 \
-Michael Oland\
-     
-\f2\i New XDarwin icon
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Contributors to XFree86 4.2:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Pablo Di Noto\
-
-\f2\i      Spanish localization
-\f0\i0 \
-Paul Edens\
-
-\f2\i      Dutch localization
-\f0\i0 \
-Kyunghwan Kim\
-
-\f2\i      Korean localization
-\f0\i0 \
-Mario Klebsch\
-     
-\f2\i Non-US keyboard support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i German localization
-\f0\i0 \
-Patrik Montgomery\
-
-\f2\i      Swedish localization
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Rootless support
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-Olivier Verdier\
-
-\f2\i      French localization
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman and Zero G Software, Inc.\
-
-\f2\i      Installer
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Team Members\
-Contributing to XFree86 4.1:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Cocoa version of XDarwin front end
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Original Quartz implementation
-\f0\i0 \
-Christoph Pfisterer\
-     
-\f2\i Dynamic shared libraries
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     
-\f2\i XDarwin icon
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 History:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-     
-\f2\i Original XFree86 port to Mac OS X Server
-\f0\i0 \
-Dave Zarzycki\
-     
-\f2\i XFree86 4.0 port to Darwin 1.0
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Integration into XFree86 Project for 4.0.2}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Dutch.lproj/Localizable.strings b/hw/darwin/bundle/Dutch.lproj/Localizable.strings
deleted file mode 100644
index 4fe16b3..0000000
Binary files a/hw/darwin/bundle/Dutch.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/Dutch.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/Dutch.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/Dutch.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Dutch.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/Dutch.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index 8e9224c..0000000
Binary files a/hw/darwin/bundle/Dutch.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/Dutch.lproj/Makefile.am b/hw/darwin/bundle/Dutch.lproj/Makefile.am
deleted file mode 100644
index 49a3ec5..0000000
--- a/hw/darwin/bundle/Dutch.lproj/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-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 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' | iconv -t UTF-16 > $@
-
-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/Dutch.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/Dutch.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index 4b8e6f5..0000000
--- a/hw/darwin/bundle/Dutch.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-<html>
-<head>
-<title>XDarwin Help</title>
-</head>
-<body>
-<center>
-    <h1>XDarwin X Server for Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    Release Date: X_REL_DATE
-</center>
-<h2>Inhoud</h2>
-<ol>
-    <li><A HREF="#notice">Belangrijke Informatie</A></li>
-    <li><A HREF="#usage">Gebruik</A></li>
-    <li><A HREF="#path">Instellen van het Path</A></li>
-    <li><A HREF="#prefs">Voorkeursinstellingen</A></li>
-    <li><A HREF="#license">Licentie</A></li>
-</ol>
-<center>
-    <h2><a NAME="notice">Belangrijke Informatie</a></h2>
-</center>
-<blockquote>
-#if X_PRE_RELEASE
-Dit is een pre-release van XDarwin, waarvoor geen ondersteuning beschikbaar is.  Rapporteren van bugs en aanleveren van patches kan op de <A HREF="http://sourceforge.net/projects/xonx/">XonX project pagina</A> bij SourceForge.  Kijk alvorens een bug te rapporteren in een pre-release eerst of een nieuwe versie beschikbaar is bij <A HREF="http://sourceforge.net/projects/xonx/">XonX</A> of de X_VENDOR_LINK.
-#else
-Als de server ouder is dan 6-12 maanden, of als uw hardware nieuwer is dan de bovenstaande datum, kijk dan of een nieuwe versie beschikbaar is voor u een probleem aanmeldt.  Rapporteren van bugs en aanleveren van patches kan op de <A HREF="http://sourceforge.net/projects/xonx/">XonX project pagina</A> bij SourceForge.
-#endif
-</blockquote>
-<blockquote>
-Deze software is beschikbaar gesteld onder de voorwaarden van de <A HREF="#license">MIT X11 / X Consortium Licentie</A> en is beschikbaar 'AS IS',zonder enige garantie. Lees s.v.p. de <A HREF="#license">Licentie</A> voor gebruik.</blockquote>
-
-<h2><a NAME="usage">Gebruik</a></h2>
-<p>XDarwin is een open-source X server van het <a HREF="http://www.x.org/">X Window Systeem</a>. This version of XDarwin was produced by the X_VENDOR_LINK.  XDarwin werkt op Mac OS X in schermvullende of rootless modus.</p>
-<p>Het X window systeem in schermvullende modus neemt het hele beeldscherm in beslag. U schakelt terug naar de Mac OS X desktop door de toesten Command-Option-A in te drukken. Deze toetsencombinatie kunt u veranderen in de Voorkeuren. Op de Mac OS X desktop klikt u op de XDarwin icoon in de Dock om weer naar het X window systeem te schakelen.  (In de Voorkeuren kunt er voor kiezen om een apart XDarwin schakelpaneel te gebruiken op de Mac OS X desktop.)</p>
-<p>In rootless modus verschijnen het X window systeem en Aqua (de Mac OS X desktop) tegelijk op het scherm. Het achtergrondscherm van X11, waarbinnen alle X11 vensters vallen, is net zo groot als het gehele scherm, maar het achtergrondscherm zelf is onzichtbaar.</p>
-
-<h3>Meerknopsmuis emulatie</h3>
-<p>Voor veel X11 programma's hebt u een 3-knops muis nodig.  Met een 1-knops muis kunt u een 3-knops muis nabootsen door een toets in te drukken terwijl u klikt met de muis.  Het instellen hiervan kan bij Voorkeuren, "Meerknopsmuis emulatie" in "Algemeen".  Emulatie is standaard ingeschakeld: ingedrukt houden van de "command" toets terwijl u klikt emuleert knop 2, ingedrukt houden van "option" emuleert knop 3.  Deze toetsen kunt u dus wijzigen in de Voorkeuren.  Let op: als u xmodmap gebruikt om de indeling van het toetsenbord te wijzigen, moet u toch de oorspronkelijke toetsen op het toetsenbord gebruiken voor deze functie.</p>
-
-<h2><a NAME="path">Instellen van het Path</a></h2>
-<p>Het path is de lijst van directories waarin gezocht wordt naar commando's.  De X11 commando's staan in de directory <code>/usr/X11R6/bin</code>, die dus aan uw path moet worden toegevoegd.  XDarwin doet dit automatisch voor u en kan extra directories toevoegen waarin u commando's hebt ge&iuml;nstalleerd.</p>
-
-<p>Ervaren gebruikers zullen het path al correct hebben ingesteld in de configuratiebestanden voor hun shell.  In dat geval kunt u XDarwin via de Voorkeuren vertellen het path niet te wijzigen.  XDarwin start de eerste X11 clients binnen de standaard login shell van de gebruiker (bij de Voorkeuren kunt u een afwijkende shell opgeven).  Het instellen van het path is afhankelijk van de shell.  Zie hiervoor de man pages voor de shell.</p>
-
-<p>Het kan handig zijn de manualpages voor X11 toe te voegen aan de lijst waarin gezocht wordt als u documentatie opvraagt.  De manualpages voor X11 staan in <code>/usr/X11R6/man</code> en de <code>MANPATH</code> environment variable bevat de lijst van directories waarin naar documentatie wordt gezocht.</p>
-
-<h2><a NAME="prefs">Voorkeursinstellingen</a></h2>
-<p>Een aantal instellingen kan worden gewijzigd door "Voorkeuren..." te kiezen in het "XDarwin" menu.  Wijzigingen van de instellingen genoemd onder "Start" gaan pas in als u XDarwin opnieuw hebt gestart.  Een wijziging van de overige instellingen is direct effectief.  Hier onder vindt u de verschillende mogelijkheden beschreven:</p>
-
-<h3>Algemeen</h3>
-<ul>
-    <li><b>Gebruik systeempiep voor X11:</b> Als u dit inschakelt wordt het Mac OS X  waarschuwingssignaal ook gebruikt door X11, anders gebruikt X11 een simpele pieptoon (dit is de standaardinstelling).</li>
-    <li><b>Wijzigen muis-versnelling door X11 mogelijk:</b> In een standaard X window systeem kan de window manager de muis-versnelling aanpassen.  Dit kan verwarrend zijn omdat de snelheid onder X11 dan verschillend kan zijn van de snelheid die u in Mac OS X bij Systeemvoorkeuren hebt ingesteld.  Om verwarring te voorkomen is de standaardinstelling dat X11 de versnelling niet kan wijzigen.</li>
-    <li><b>Meerknopsmuis emulatie:</b> Dit is hierboven beschreven bij <a HREF="#usage">Gebruik</a>.  Als emulatie is ingeschakeld moet u de gekozen toetsen ingedrukt houden terwijl u met de muis klikt om de tweede en derde muisknop na te bootsen.</li>
-</ul>
-
-<h3>Start</h3>
-<ul>
-    <li><b>Standaard modus:</b> Hier kiest u de standaard scherm-modus: schermvullend of rootless (hierboven beschreven bij <a HREF="#usage">Gebruik</a>).  U kunt ook kiezen tijdens het starten van XDarwin, zie de optie hieronder.</li>
-    <li><b>Kies scherm-modus tijdens start:</b> Dit is standaard ingeschakeld zodat u tijdens het starten van XDarwin kunt kiezen tussen schermvullend en rootless scherm-modus.  Als u dit uitschakelt start XDarwin in de standaard modus zonder u iets te vragen.</li>
-    <li><b>X11 scherm nummer:</b> Met X11 kunnen meerdere schermen worden aangestuurd door verschillende X servers op dezelfde computer.  Als u meerdere X servers tegelijk wilt gebruiken stelt u hier het scherm nummer in dat door XDarwin wordt gebruikt.</li>
-    <li><b>Xinerama multi-monitor ondersteuning mogelijk:</b> XDarwin ondersteunt het gebruik van meerdere monitoren met Xinerama, waarbij elke monitor wordt gezien als deel van &eacute;&eacute;n groot rechthoekig scherm.  U kunt Xinerama hier uitschakelen, maar XDarwin werkt op dit moment zonder Xinerama niet goed met meerdere monitoren.  Als u maar 1 monitor gebruikt is deze instelling automatisch uitgeschakeld.</li>
-    <li><b>Toetsenbordindeling-bestand:</b> Een toetsenbordindeling-bestand wordt bij het starten geladen en omgezet naar een X11 toetsenbordindeling.  Voor verschillende talen vindt u toetsenbordindelingen in de directory <code>/System/Library/Keyboards</code>.</li>
-    <li><b>Bij starten eerste X11 clients:</b> Als XDarwin start, wordt  <code>xinit</code> uitgevoerd om de X window manager en andere X clients te starten (zie "<code>man xinit</code>").  Voordat XDarwin <code>xinit</code> uitvoert voegt het de opgegeven directories toe aan het path.  Standaard wordt alleen <code>/usr/X11R6/bin</code> toegevoegd.  U kunt meerdere directories opgeven, gescheiden door een dubbelepunt.  X clients worden gestart met de standaard login shell van de gebruiker met gebruik van de configuratiebestanden voor die shell.  U kunt een afwijkende shell opgeven.</li>
-</ul>
-
-<h3>Schermvullend</h3>
-<ul>
-    <li><b>Toetscombinatie knop:</b> Klik op deze knop om de toetscombinatie te wijzigen waarmee u tussen de Mac OS X desktop en X11 schakelt.  Als toetscombinatie kunt u elke combinatie gebruiken van de shift, control, command en option toetsen samen met &eacute;&eacute;n normale toets.</li>
-    <li><b>Klikken op icoon in Dock schakelt naar X11:</b> Hiermee is een klik op de XDarwin icoon in de Dock voldoende om naar X11 te schakelen.  In sommige versies van Mac OS X verdwijnt soms de cursor als u deze mogelijkheid gebruikt en daarna terugkeert naar de Mac OS X desktop.</li>
-    <li><b>Toon help bij schermvullend starten:</b> Hiermee wordt een inleidend scherm getoond als XDarwin schermvullend start.</li>
-    <li><b>Kleurdiepte:</b> In de schermvullende modus kan X11 een andere kleurdiepte gebruiken dan Aqua (en de Mac OS X desktop).  Als u "Huidig" kiest, neemt XDarwin bij het starten de kleurdiepte over van Aqua.  U kunt ook kiezen voor 8, 15 of 24 bits.</li>
-</ul>
-
-<h2><a NAME="license">Licentie</a></h2>
-The main license for XDarwin is one based on the traditional MIT X11 / X Consortium License, which does not impose any conditions on modification or redistribution of source code or binaries other than requiring that copyright/license notices are left intact. For more information and additional copyright/licensing notices covering some sections of the code, please refer to the source code.
-<H3><A NAME="3"></A>X Consortium License</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>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:</p>
-<p>The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Except as contained in this notice, the name of the X Consortium 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 X Consortium.</p>
-<p>X Window System is a trademark of X Consortium, Inc.</p>
-</body>
-</html>
-
diff --git a/hw/darwin/bundle/English.lproj/Credits.rtf b/hw/darwin/bundle/English.lproj/Credits.rtf
deleted file mode 100644
index 34408e7..0000000
--- a/hw/darwin/bundle/English.lproj/Credits.rtf
+++ /dev/null
@@ -1,168 +0,0 @@
-{\rtf1\mac\ansicpg10000\cocoartf102
-{\fonttbl\f0\fswiss\fcharset77 Helvetica;\f1\fswiss\fcharset77 Helvetica-Bold;\f2\fswiss\fcharset77 Helvetica-Oblique;
-}
-{\colortbl;\red255\green255\blue255;}
-\vieww5160\viewh6300\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 This product includes software developed by The XFree86 Project, Inc  (http://www.xfree86.org/) and its contributors. The following people contributed to Darwin/Mac OS X support.\
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Contributors to Xorg Foundation Release:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f2\i Working left and right Ctrl, Alt (Option), Meta (Command) and Shift keys.
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\f1\b \cf0 Contributors to XFree86 4.4:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper\
-     
-\f2\i Rootless acceleration and Apple-WM extension
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Additional XonX Contributors to XFree86 4.3:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro\
-     
-\f2\i Portuguese localization
-\f0\i0 \
-Michael Oland\
-     
-\f2\i New XDarwin icon
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Contributors to XFree86 4.2:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Pablo Di Noto\
-
-\f2\i      Spanish localization
-\f0\i0 \
-Paul Edens\
-
-\f2\i      Dutch localization
-\f0\i0 \
-Kyunghwan Kim\
-
-\f2\i      Korean localization
-\f0\i0 \
-Mario Klebsch\
-     
-\f2\i Non-US keyboard support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i German localization
-\f0\i0 \
-Patrik Montgomery\
-
-\f2\i      Swedish localization
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Rootless support
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-Olivier Verdier\
-
-\f2\i      French localization
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman and Zero G Software, Inc.\
-
-\f2\i      Installer
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Team Members\
-Contributing to XFree86 4.1:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Cocoa version of XDarwin front end
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Original Quartz implementation
-\f0\i0 \
-Christoph Pfisterer\
-     
-\f2\i Dynamic shared libraries
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     
-\f2\i XDarwin icon
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 History:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-     
-\f2\i Original XFree86 port to Mac OS X Server
-\f0\i0 \
-Dave Zarzycki\
-     
-\f2\i XFree86 4.0 port to Darwin 1.0
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Integration into XFree86 Project for 4.0.2}
\ No newline at end of file
diff --git a/hw/darwin/bundle/English.lproj/InfoPlist.strings.cpp b/hw/darwin/bundle/English.lproj/InfoPlist.strings.cpp
deleted file mode 100644
index 268b800..0000000
--- a/hw/darwin/bundle/English.lproj/InfoPlist.strings.cpp
+++ /dev/null
@@ -1,4 +0,0 @@
-/* English versions of the Info.plist keys; used by most localizations. */
-/* Most of these are set in the target application settings. */
-
-NSHumanReadableCopyright = __quote__ X_VENDOR_NAME X_VERSION __quote__;
diff --git a/hw/darwin/bundle/English.lproj/Localizable.strings b/hw/darwin/bundle/English.lproj/Localizable.strings
deleted file mode 100644
index f2e8e3c..0000000
Binary files a/hw/darwin/bundle/English.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/English.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/English.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/English.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/English.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/English.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index ebbfd83..0000000
Binary files a/hw/darwin/bundle/English.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/English.lproj/Makefile.am b/hw/darwin/bundle/English.lproj/Makefile.am
deleted file mode 100644
index 8d6f7e5..0000000
--- a/hw/darwin/bundle/English.lproj/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-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' | iconv -t UTF-16 > $@
-
-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 \
-	InfoPlist.strings.cpp
-
diff --git a/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index db33670..0000000
--- a/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-<html>
-<head>
-<title>XDarwin Help</title>
-</head>
-<body>
-<center>
-    <h1>XDarwin X Server for Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    Release Date: X_REL_DATE
-</center>
-<h2>Contents</h2>
-<ol>
-    <li><A HREF="#notice">Important Notice</A></li>
-    <li><A HREF="#usage">Usage</A></li>
-    <li><A HREF="#path">Setting Your Path</A></li>
-    <li><A HREF="#prefs">User Preferences</A></li>
-    <li><A HREF="#license">License</A></li>
-</ol>
-<center>
-    <h2><a NAME="notice">Important Notice</a></h2>
-</center>
-<blockquote>
-#if X_PRE_RELEASE
-This is a pre-release version of XDarwin, and is not supported in any way. Bugs may be reported and patches may be submitted to the <A HREF="http://sourceforge.net/projects/xonx/">XonX project page</A> at SourceForge.  Before reporting bugs in pre-release versions, please check the latest version from <A HREF="http://sourceforge.net/projects/xonx/">XonX</A> or the X_VENDOR_LINK.
-#else
-If the server is older than 6-12 months, or if your hardware is newer than the above date, look for a newer version before reporting problems. Bugs may be reported and patches may be submitted to the <A HREF="http://sourceforge.net/projects/xonx/">XonX project page</A> at SourceForge.
-#endif
-</blockquote>
-<blockquote>
-This software is distributed under the terms of the <A HREF="#license">MIT X11 / X Consortium License</A> and is provided AS IS, with no warranty. Please read the <A HREF="#license">License</A> before using.</blockquote>
-
-<h2><a NAME="usage">Usage</a></h2>
-<p>XDarwin is a freely redistributable open-source X server for the <a HREF="http://www.x.org/">X Window System</a>. This version of XDarwin was produced by the X_VENDOR_LINK. XDarwin runs on Mac OS X in full screen or rootless modes.</p>
-<p>In full screen mode, when the X window system is active, it takes over the entire screen. You can switch back to the Mac OS X desktop by holding down Command-Option-A. This key combination can be changed in the user preferences. From the Mac OS X desktop, click on the XDarwin icon in the Dock to switch back to the X window system.  (You can change this behavior in the user preferences so that you must click the XDarwin icon in the floating switch window instead.)</p>
-<p>In rootless mode, the X window system and Aqua 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 Aqua handles the desktop background.</p>
-<h3>Multi-Button Mouse Emulation</h3>
-<p>Many X11 applications rely on the use of a 3-button mouse. You can emulate a 3-button mouse with a single button by holding down various modifier keys while you click the mouse button. This is controlled by settings in the "Multi-Button Mouse Emulation" section of the "General" preferences. By default, emulation is on and holding down the command key and clicking the mouse button will simulate clicking the second mouse button. Holding down the option key and clicking will simulate the third button. You can change to any combination of modifiers to emulate buttons two and three in the preferences. Note, even if the modifiers keys are mapped to some other key with xmodmap, you still must use the actual keys specified in the preferences for multi-button mouse emulation.</p>
-
-<h2><a NAME="path">Setting Your Path</a></h2>
-<p>Your path is the list of directories to be searched for executable commands. The X11 commands are located in <code>/usr/X11R6/bin</code>, which needs to be added to your path. XDarwin does this for you by default and can also add additional directories where you have installed command line applications.</p>
-<p>More experienced users will have already set their path correctly using the initialization files for their shell. In this case, you can inform XDarwin not to modify your path in the preferences. XDarwin launches the initial X11 clients in the user's default login shell. (An alternate shell can also be specified in the preferences.) The way to set the path depends on the shell you are using. This is described in the man page documentation for the shell.</p>
-<p>In addition you may also want to add the X11 man pages to the list of pages to be searched when you are looking for documentation. The X11 man pages are located in <code>/usr/X11R6/man</code> and the <code>MANPATH</code> environment variable contains the list of directories to search.</p>
-
-<h2><a NAME="prefs">User Preferences</a></h2>
-<p>A number of options may be set from the user preferences, accessible from the "Preferences..." menu item in the "XDarwin" menu. The options listed as start up options will not take effect until you have restarted XDarwin. All other options take effect immediately. The various options are described below:</p>
-<h3>General</h3>
-<ul>
-    <li><b>Use System beep for X11:</b> When enabled the standard Mac OS X alert sound is used as the X11 bell. When disabled (default) a simple tone is used.</li>
-    <li><b>Allow X11 to change mouse acceleration:</b> In a standard X window system implementation, the window manager can change the mouse acceleration. This can lead to confusion as the mouse acceleration may be set to different values by the Mac OS X System Preferences and the X window manager. By default, X11 is not allowed to change the mouse acceleration to avoid this problem.</li>
-    <li><b>Multi-Button Mouse Emulation:</b> This is described above under <a HREF="#usage">Usage</a>. When emulation is enabled the selected modifiers must be held down when the mouse button is pushed to emulate the second or third mouse buttons.</li>
-</ul>
-<h3>Start Up</h3>
-<ul>
-    <li><b>Default Mode:</b> If the user does not indicate whether to run in full screen or rootless mode, the mode specified here will be used.</li>
-    <li><b>Show mode pick panel on startup:</b> By default, a panel is displayed when XDarwin is started to allow the user to choose between full screen or rootless mode. If this option is turned off, the default mode will be started automatically.</li>
-    <li><b>X11 Display number:</b> X11 allows there to be multiple displays managed by separate X servers on a single computer. The user may specify an integer display number for XDarwin to use if more than one X server is going to be run simultaneously.</li>
-    <li><b>Allow Xinerama multiple monitor support:</b> XDarwin supports multiple monitors with Xinerama, which treats all monitors as being part of one large rectangular screen. You can disable Xinerama with this option, but currently XDarwin does not handle multiple monitors correctly without it. If you only have a single monitor, Xinerama is automatically disabled.</li>
-    <li><b>Keymapping File:</b> A keymapping file is read at startup and translated to an X11 keymap. Keymapping files, available for a wide variety of languages, are found in <code>/System/Library/Keyboards</code>.</li>
-    <li><b>Starting First X11 Clients:</b> When XDarwin is started from the Finder, it will run <code>xinit</code> to launch the X window manager and other X clients. (See "<code>man xinit</code>" for more information.) Before XDarwin runs <code>xinit</code> it will add the specified directories to the user's path. By default only <code>/usr/X11R6/bin</code> is added. Additional directories may added, separated by a colon. The X clients are started in the user's default login shell so that the user's shell initialization files are read. If desired, an alternate shell may be specified.</li>
-</ul>
-<h3>Full Screen</h3>
-<ul>
-    <li><b>Key combination button:</b> Click this button and then press any number of modifiers followed by a standard key to change the key combination to switch between Aqua and X11.</li>
-    <li><b>Click on icon in Dock switches to X11:</b> Enable this to activate switching to X11 by clicking on the XDarwin icon in the Dock. On some versions of Mac OS X, switching by clicking in the Dock can cause the cursor to disappear on returning to Aqua.</li>
-    <li><b>Show help on startup:</b> This will show an introductory splash screen when XDarwin is started in full screen mode.</li>
-    <li><b>Color bit depth:</b> In full screen mode, the X11 display can use a different color bit depth than is used by Aqua. If "Current" is specified, the depth used by Aqua when XDarwin starts will be used. Otherwise 8, 15, or 24 bits may be specified.</li>
-</ul>
-
-<h2><a NAME="license">License</a></h2>
-The main license for XDarwin is based on the traditional MIT X11 / X Consortium License, which does not impose any conditions on modification or redistribution of source code or binaries other than requiring that copyright/license notices are left intact. For more information and additional copyright/licensing notices covering some sections of the code, please refer to the source code.
-<H3><A NAME="3"></A>X Consortium License</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>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:</p>
-<p>The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Except as contained in this notice, the name of the X Consortium 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 X Consortium.</p>
-<p>X Window System is a trademark of X Consortium, Inc.</p>
-</body>
-</html>
diff --git a/hw/darwin/bundle/French.lproj/Credits.rtf b/hw/darwin/bundle/French.lproj/Credits.rtf
deleted file mode 100644
index 17e0a0d..0000000
--- a/hw/darwin/bundle/French.lproj/Credits.rtf
+++ /dev/null
@@ -1,166 +0,0 @@
-{\rtf1\mac\ansicpg10000\cocoartf102
-{\fonttbl\f0\fswiss\fcharset77 Helvetica;\f1\fswiss\fcharset77 Helvetica-Bold;\f2\fswiss\fcharset77 Helvetica-Oblique;
-}
-{\colortbl;\red255\green255\blue255;}
-\vieww5160\viewh4480\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 This product includes software developed by The XFree86 Project, Inc  (http://www.xfree86.org/) and its contributors. The following people contributed to Darwin/Mac OS X support.\
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Contributors to Xorg Foundation Release:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f2\i Working left and right Ctrl, Alt (Option), Meta (Command) and Shift keys.
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\f1\b \cf0 Contributors to XFree86 4.4:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper\
-     
-\f2\i Rootless acceleration and Apple-WM extension
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Additional XonX Contributors to XFree86 4.3:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro\
-     
-\f2\i Portuguese localization
-\f0\i0 \
-Michael Oland\
-     
-\f2\i New XDarwin icon
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 \
-Participants \'88 XonX pour XFree86 4.2 :
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Version pour Darwin x86 
-\f0\i0 \
-Pablo Di Noto\
-
-\f2\i      Traduction en espagnol
-\f0\i0 \
-Paul Edens\
-
-\f2\i      Traduction en allemand
-\f0\i0 \
-Kyunghwan Kim\
-
-\f2\i      Traduction en cor\'8een
-\f0\i0 \
-Mario Klebsch\
-     
-\f2\i Claviers non-US
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Direction du projet
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Traduction en allemand
-\f0\i0 \
-Patrik Montgomery\
-
-\f2\i      Traduction en su\'8edois
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Version \'c7 rootless \'c8
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Traduction en japonais
-\f0\i0 \
-Olivier Verdier\
-
-\f2\i      Traduction en fran\'8dais
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Remerciements :
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman et Zero G Software, Inc.\
-
-\f2\i      Installeur
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Participants \'88 XonX pour XFree86 4.2 :
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Version pour Darwin x86 
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Direction du projet
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Version Cocoa de l'interface de XDarwin
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Impl\'8ementation initiale sur Quartz
-\f0\i0 \
-Christoph Pfisterer\
-     
-\f2\i Librairies partag\'8ees dynamiquement
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Traduction en japonais
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Remerciements :
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     Ic\'99ne 
-\f2\i XDarwin
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Historique :
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-     
-\f2\i Premi\'8fre adaptation de XFree86 sur Mac OS X Server
-\f0\i0 \
-Dave Zarzycki\
-     
-\f2\i Adaptation de Free86 4.0 pour Darwin 1.0
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Int\'8egration dans le projet XFree86 pour la version 4.0.2}
\ No newline at end of file
diff --git a/hw/darwin/bundle/French.lproj/Localizable.strings b/hw/darwin/bundle/French.lproj/Localizable.strings
deleted file mode 100644
index 21c4a99..0000000
Binary files a/hw/darwin/bundle/French.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/French.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/French.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/French.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/French.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/French.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index 109d5cc..0000000
Binary files a/hw/darwin/bundle/French.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/French.lproj/Makefile.am b/hw/darwin/bundle/French.lproj/Makefile.am
deleted file mode 100644
index 4dca934..0000000
--- a/hw/darwin/bundle/French.lproj/Makefile.am
+++ /dev/null
@@ -1,41 +0,0 @@
-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' | iconv -t UTF-16 > $@
-
-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/French.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/French.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index 512416b..0000000
--- a/hw/darwin/bundle/French.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-<html>
-<head><META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
-<title>XDarwin Help</title>
-</head>
-<body>
-<center>
-    <h1>XDarwin X Server pour Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    Date : X_REL_DATE
-</center>
-<h2>Sommaire</h2>
-<ol>
-    <li><A HREF="#notice">Avertissement</A></li>
-    <li><A HREF="#usage">Utilisation</A></li>
-    <li><A HREF="#path">Chemins d'accès</A></li>
-    <li><A HREF="#prefs">Préférences</A></li>
-    <li><A HREF="#license">Licence</A></li>
-</ol>
-<center>
-    <h2><a NAME="notice">Avertissement</a></h2>
-</center>
-<blockquote>
-#if PRE_RELEASE
-Ceci est une pré-version de XDarwin et ne fait par conséquent l'objet d'aucun support client. Les bogues peuvent être signalés et des patches peuvent être soumis sur la 
-<A HREF="http://sourceforge.net/projects/xonx/">page du projet XonX</A> chez SourceForge. Veuillez prendre connaissance de la dernière version sur <A HREF="http://sourceforge.net/projects/xonx/">XonX</A> ou le X_VENDOR_LINK avant de signaler un bogue d'une pré-version.
-#else
-Si le serveur date de plus de 6-12 mois ou si votre matériel est plus récent que la date indiquée ci-dessus, veuillez vous procurer une version plus récente avant de signaler toute anomalie. Les bogues peuvent être signalés et des patches peuvent être soumis sur la <A HREF="http://sourceforge.net/projects/xonx/">page du projet XonX</A> chez SourceForge.
-#endif
-</blockquote>
-<blockquote>
-Ce logiciel est distribué sous la 
-<A HREF="#license">Licence du Consortium X/X11 du MIT</A> et est fourni TEL QUEL, sans garanties. Veuillez prendre connaissance de la <A HREF="#license">Licence</A> avant toute utilisation.</blockquote>
-
-<h2><a NAME="usage">Utilisation</a></h2>
-<p>XDarwin est une X server libre et distribuable sans contrainte du <a HREF
-="http://www.x.org/">X Window System</a>. This version of XDarwin was produced by the X_VENDOR_LINK. XDarwin fonctionne sous Mac OS X en mode « rootless » ou plein écran.</p>
-<p>Lorsque le système X window est actif en mode plein écran, il prend en charge la totalité de l'écran. Il est possible de revenir sur le bureau de Mac OS X en appuyant sur Commande-Option-A. Cette combinaison de touches peut être modifiée dans les préférences. Pour revenir dans X window, cliquer sur l'icône de XDarwin dans le Dock de Mac OS X.  (Un réglage des préférences permet d'effectuer cette opération en cliquant dans une fenêtre flottante au lieu de l'icône du Dock)</p>
-<p>En mode « rootless », X window system et Aqua utilisent le même affichage. La fenêtre-mère de l'affichage X11 est de la taille de l'écran et contient toutes les autre fenêtres. En mode « rootless » cette fenêtre-mère n'est pas affichée car Aqua gère le fond d'écran.</p>
-<h3>Émulation de souris à plusieurs boutons</h3>
-<p>Le fonctionnement de la plupart des applications X11 repose sur l'utilisation d'une souris à 3 boutons. Il est possible d'émuler une souris à 3 boutons avec un seul bouton en appuyant sur des touches de modification. Ceci est réglé dans la section "Émulation de souris à plusieurs boutons" de l'onglet "Général" des préférences. L'émulation est activée par défaut. Dans ce cas, cliquer en appuyant simultanément sur la touche "commande" simulera le bouton du milieu. Cliquer en appuyant simultanément sur la touche "option" simulera le bouton de droite. Les préférences permettent de régler n'importe quelle combinaison de touches de modification pour émuler les boutons du milieu et de droite. Notez que même si les touches de modifications sont mises en correspondance avec d'autres touches par xmodmap, ce sont les touches originelles spécifiées dans les préférences qui assureront l'émulation d'une souris à plusieurs boutons.
-
-<h2><a NAME="path">Réglage du chemin d'accès</a></h2>
-<p>Le chemin d'accès est une liste de répertoires utilisés pour la recherche d'exécutables. Les commandes X11 sont situées dans <code>/usr/X11R6/bin</code>, qui doit être ajouté à votre chemin d'accès. XDarwin fait cela par défaut, et peut également ajouter d'autres répertoires dans lesquels vous auriez installé d'autre commandes unix.</p>
-<p>Les utilisateurs plus expérimentés auront déjà réglé leur chemin d'accès correctement par le biais des fichiers d'initialisation de leur shell. Dans ce cas, il est possible de demander à XDarwin de ne pas modifier le chemin d'accès initial. XDarwin lance les premiers clients X11 dans le shell d'ouverture de session par défaut. (Un shell de remplacement peut être spécifié dans les préférences.) La façon de régler le chemin d'accès dépend du shell utilisé. Ceci est documenté dans les pages "man" du shell.</p>
-<p>De plus, il est possible d'ajouter les pages "man" de X11 à la liste des pages recherchées pour la documentation "man". Les pages "man" X11 se trouvent dans <code>/usr/X11R6/man</code>  et la variable d'environnement <code>MANPATH</code> contient la liste des répertoires dans lesquels chercher.</p>
-
-
-<h2><a NAME="prefs">Préférences</a></h2>
-<p>Un certain nombre d'options peuvent être réglées dans les préférences. On accède aux préférences en choisissant "Préférences..." dans le menu "XDarwin". Les options décrites comme options de démarrage ne prendront pas effet avant le redémarrage de XDarwin. Les autres options prennent immédiatement effet. Les différentes options sont détaillées ci-après :</p>
-<h3>Général</h3>
-<ul>
-    <li><b>Utiliser le bip d'alerte Système dans X11 :</b> Cocher cette option pour que le son d'alerte standard de Mac OS X soit utilisé à la place du son d'alerte de X11. L'option n'est pas cochée ar défaut. Dans ce cas, un simple signal sonore est utilisé.</li>
-    <li><b>Autoriser X11 à changer la vitesse de la souris :</b> Dans une implémentation classique du sytème X window, le gestionnaire de fenêtres peut modifier la vitesse de la souris. Cela peut s'avérer déroutant puisque le réglage de la vitesse de la souris peut être différent dans les préférences de Mac OS X et dans le gestionnaire X window. Par défaut, X11 n'est pas autorisé à changer la vitesse de la souris.</li>
-    <li><b>Émulation de souris à plusieurs boutons :</b> Ceci est décrit ci-dessus à la rubrique <a HREF="#usage">Usage</a>. Lorsque l'émulation est activée, il suffit d'appuyer simultanément sur les touches modificatrices sélectionnées et sur le bouton de la souris afin d'émuler les boutons du milieu et de droite.</li>
-</ul>
-<h3>Démarrage</h3>
-<ul>
-    <li><b>Mode par défaut :</b> Le mode spécifié à cet endroit sera utilisé si l'utilisateur ne l'indique pas au démarrage.</li>
-    <li><b>Choix du mode d'affichage au démarrage</b> Par défaut, une fenêtre de dialogue est affichée au démarrage de XDarwin pour permettre à l'utilisateur de choisir entre le mode plein écran et le mode « rootless ». Si cette option est désactivée, le mode par défaut sera automatiquement utilisé.</li>
-    <li><b>Numéro d'affichage (Display)</b> X11 offre la possibilité de plusieurs serveurs X sur un ordinateur. L'utilisateur doit spécifier ici le numéro d'affichage utilisé par XDarwin dans le cas où plusieurs serveurs X seraient en service simultanément.</li>
-    <li><b>Autoriser la prise en charge Xinerama de plusieurs moniteurs :</b> XDarwin peut être utilisé avec plusieurs moniteur avec Xinerama, qui considère les différents moniteurs comme des parties d'un écran rectugulaire plus grand. Cette option permet de désactiver Xinerama mais XDarwin ne prend alors pour l'instant pas correctement en charge l'affichage sur plusieurs écrans. Si il n'y a qu'un seul moniteur, Xinerama est automatiquement désactivé.</li>
-    <li><b>Fichier clavier :</b> Un fichier de correspondance de clavier est lu au démarrage puis transformé en un fihcier de correspondance clavier pour X11. Les fichiers de correspondance clavier, disponibles pour de nombreuses langues, se trouvent dans <code>/System/Library/Keyboards</code>.</li>
-    <li><b>Démarrage des premiers clients X11 :</b> Lorsque XDarwin est démarré à partir du Finder, il lance <code>xinit</code> qui lance à son tour le gestionnaire X window ainsi que d'autres clients X. (Voir "<code>man xinit</code>" pour plus d'informations.) Avant de lancer <code>xinit</code>, XDarwin ajoute les répertoires ainsi spécifiés au chemin d'accès de l'utilisateur. Par défaut, seul <code>/usr/X11R6/bin</code> est ajouté. Il est possible d'ajouter d'autres répertoires en les séparants à l'aide de deux points (<code>:</code>). Les clients X sont démarrés à partir du shell par défaut de l'utilisateur. Ainsi, le fichier d'initialisation de shell de l'utilisateur est lu. Un autre shell peut éventuellement être spécifié.</li>
-</ul>
-<h3>Plein écran</h3>
-<ul>
-    <li><b>Combinaison de touches :</b> Appuyer sur ce bouton, puis appuyer sur une ou plusieurs touches modificatrices suivies d'une touche ordinaire. Cette combinaison de touche servira à commuter entre Aqua et X11.</li>
-    <li><b>Basculer dans X11 en cliquant sur l'icône du Dock :</b> Cette option permet de passer dans X11 en cliquant dans l'icône de XDarwin dans le Dock. Sur certaines versions de Mac OS X, la commutation en utilisant le Dock peut faire disparaître le curseur lors du retour dans Aqua.</li>
-    <li><b>Afficher l'aide du mode plein écran au démarrage :</b> Permet l'affichage d'une fenêtre d'introduction lorsque XDarwin est démarré en mode plein écran.</li>
-    <li><b>Profondeur de couleur :</b> En mode plein écran, l'affichage X11 peut utiliser une autre profondeur de couleur que celle employée par Aqua. Si "Actuelle" est choisi, XDarwin utilisera la même profondeur de couleur qu'Aqua. Les autres choix sont 8 (256 couleurs), 15 (milliers de couleurs) et 24 bits (millions de couleurs). </li>
-</ul>
-
-<h2><a NAME="license">Licence</a></h2>
-The main license for XDarwin is one based on the traditional MIT X11 / X Consortium License, which does not impose any conditions on modification or redistribution of source code or binaries other than requiring that copyright/license notices are left intact. For more information and additional copyright/licensing notices covering some sections of the code, please refer to the source code.
-<H3><A NAME="3"></A>X Consortium License</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>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:</p>
-<p>The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Except as contained in this notice, the name of the X Consortium 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 X Consortium.</p>
-<p>X Window System is a trademark of X Consortium, Inc.</p>
-</body>
-</html>
-
diff --git a/hw/darwin/bundle/German.lproj/Credits.rtf b/hw/darwin/bundle/German.lproj/Credits.rtf
deleted file mode 100644
index 34408e7..0000000
--- a/hw/darwin/bundle/German.lproj/Credits.rtf
+++ /dev/null
@@ -1,168 +0,0 @@
-{\rtf1\mac\ansicpg10000\cocoartf102
-{\fonttbl\f0\fswiss\fcharset77 Helvetica;\f1\fswiss\fcharset77 Helvetica-Bold;\f2\fswiss\fcharset77 Helvetica-Oblique;
-}
-{\colortbl;\red255\green255\blue255;}
-\vieww5160\viewh6300\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 This product includes software developed by The XFree86 Project, Inc  (http://www.xfree86.org/) and its contributors. The following people contributed to Darwin/Mac OS X support.\
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Contributors to Xorg Foundation Release:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f2\i Working left and right Ctrl, Alt (Option), Meta (Command) and Shift keys.
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\f1\b \cf0 Contributors to XFree86 4.4:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper\
-     
-\f2\i Rootless acceleration and Apple-WM extension
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Additional XonX Contributors to XFree86 4.3:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro\
-     
-\f2\i Portuguese localization
-\f0\i0 \
-Michael Oland\
-     
-\f2\i New XDarwin icon
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Contributors to XFree86 4.2:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Pablo Di Noto\
-
-\f2\i      Spanish localization
-\f0\i0 \
-Paul Edens\
-
-\f2\i      Dutch localization
-\f0\i0 \
-Kyunghwan Kim\
-
-\f2\i      Korean localization
-\f0\i0 \
-Mario Klebsch\
-     
-\f2\i Non-US keyboard support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i German localization
-\f0\i0 \
-Patrik Montgomery\
-
-\f2\i      Swedish localization
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Rootless support
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-Olivier Verdier\
-
-\f2\i      French localization
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman and Zero G Software, Inc.\
-
-\f2\i      Installer
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Team Members\
-Contributing to XFree86 4.1:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Cocoa version of XDarwin front end
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Original Quartz implementation
-\f0\i0 \
-Christoph Pfisterer\
-     
-\f2\i Dynamic shared libraries
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     
-\f2\i XDarwin icon
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 History:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-     
-\f2\i Original XFree86 port to Mac OS X Server
-\f0\i0 \
-Dave Zarzycki\
-     
-\f2\i XFree86 4.0 port to Darwin 1.0
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Integration into XFree86 Project for 4.0.2}
\ No newline at end of file
diff --git a/hw/darwin/bundle/German.lproj/Localizable.strings b/hw/darwin/bundle/German.lproj/Localizable.strings
deleted file mode 100644
index 5db6306..0000000
Binary files a/hw/darwin/bundle/German.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/German.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/German.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/German.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/German.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/German.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index 28fff89..0000000
Binary files a/hw/darwin/bundle/German.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/German.lproj/Makefile.am b/hw/darwin/bundle/German.lproj/Makefile.am
deleted file mode 100644
index fcb5dd2..0000000
--- a/hw/darwin/bundle/German.lproj/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-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 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' | iconv -t UTF-16 > $@
-
-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/German.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/German.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index db33670..0000000
--- a/hw/darwin/bundle/German.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-<html>
-<head>
-<title>XDarwin Help</title>
-</head>
-<body>
-<center>
-    <h1>XDarwin X Server for Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    Release Date: X_REL_DATE
-</center>
-<h2>Contents</h2>
-<ol>
-    <li><A HREF="#notice">Important Notice</A></li>
-    <li><A HREF="#usage">Usage</A></li>
-    <li><A HREF="#path">Setting Your Path</A></li>
-    <li><A HREF="#prefs">User Preferences</A></li>
-    <li><A HREF="#license">License</A></li>
-</ol>
-<center>
-    <h2><a NAME="notice">Important Notice</a></h2>
-</center>
-<blockquote>
-#if X_PRE_RELEASE
-This is a pre-release version of XDarwin, and is not supported in any way. Bugs may be reported and patches may be submitted to the <A HREF="http://sourceforge.net/projects/xonx/">XonX project page</A> at SourceForge.  Before reporting bugs in pre-release versions, please check the latest version from <A HREF="http://sourceforge.net/projects/xonx/">XonX</A> or the X_VENDOR_LINK.
-#else
-If the server is older than 6-12 months, or if your hardware is newer than the above date, look for a newer version before reporting problems. Bugs may be reported and patches may be submitted to the <A HREF="http://sourceforge.net/projects/xonx/">XonX project page</A> at SourceForge.
-#endif
-</blockquote>
-<blockquote>
-This software is distributed under the terms of the <A HREF="#license">MIT X11 / X Consortium License</A> and is provided AS IS, with no warranty. Please read the <A HREF="#license">License</A> before using.</blockquote>
-
-<h2><a NAME="usage">Usage</a></h2>
-<p>XDarwin is a freely redistributable open-source X server for the <a HREF="http://www.x.org/">X Window System</a>. This version of XDarwin was produced by the X_VENDOR_LINK. XDarwin runs on Mac OS X in full screen or rootless modes.</p>
-<p>In full screen mode, when the X window system is active, it takes over the entire screen. You can switch back to the Mac OS X desktop by holding down Command-Option-A. This key combination can be changed in the user preferences. From the Mac OS X desktop, click on the XDarwin icon in the Dock to switch back to the X window system.  (You can change this behavior in the user preferences so that you must click the XDarwin icon in the floating switch window instead.)</p>
-<p>In rootless mode, the X window system and Aqua 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 Aqua handles the desktop background.</p>
-<h3>Multi-Button Mouse Emulation</h3>
-<p>Many X11 applications rely on the use of a 3-button mouse. You can emulate a 3-button mouse with a single button by holding down various modifier keys while you click the mouse button. This is controlled by settings in the "Multi-Button Mouse Emulation" section of the "General" preferences. By default, emulation is on and holding down the command key and clicking the mouse button will simulate clicking the second mouse button. Holding down the option key and clicking will simulate the third button. You can change to any combination of modifiers to emulate buttons two and three in the preferences. Note, even if the modifiers keys are mapped to some other key with xmodmap, you still must use the actual keys specified in the preferences for multi-button mouse emulation.</p>
-
-<h2><a NAME="path">Setting Your Path</a></h2>
-<p>Your path is the list of directories to be searched for executable commands. The X11 commands are located in <code>/usr/X11R6/bin</code>, which needs to be added to your path. XDarwin does this for you by default and can also add additional directories where you have installed command line applications.</p>
-<p>More experienced users will have already set their path correctly using the initialization files for their shell. In this case, you can inform XDarwin not to modify your path in the preferences. XDarwin launches the initial X11 clients in the user's default login shell. (An alternate shell can also be specified in the preferences.) The way to set the path depends on the shell you are using. This is described in the man page documentation for the shell.</p>
-<p>In addition you may also want to add the X11 man pages to the list of pages to be searched when you are looking for documentation. The X11 man pages are located in <code>/usr/X11R6/man</code> and the <code>MANPATH</code> environment variable contains the list of directories to search.</p>
-
-<h2><a NAME="prefs">User Preferences</a></h2>
-<p>A number of options may be set from the user preferences, accessible from the "Preferences..." menu item in the "XDarwin" menu. The options listed as start up options will not take effect until you have restarted XDarwin. All other options take effect immediately. The various options are described below:</p>
-<h3>General</h3>
-<ul>
-    <li><b>Use System beep for X11:</b> When enabled the standard Mac OS X alert sound is used as the X11 bell. When disabled (default) a simple tone is used.</li>
-    <li><b>Allow X11 to change mouse acceleration:</b> In a standard X window system implementation, the window manager can change the mouse acceleration. This can lead to confusion as the mouse acceleration may be set to different values by the Mac OS X System Preferences and the X window manager. By default, X11 is not allowed to change the mouse acceleration to avoid this problem.</li>
-    <li><b>Multi-Button Mouse Emulation:</b> This is described above under <a HREF="#usage">Usage</a>. When emulation is enabled the selected modifiers must be held down when the mouse button is pushed to emulate the second or third mouse buttons.</li>
-</ul>
-<h3>Start Up</h3>
-<ul>
-    <li><b>Default Mode:</b> If the user does not indicate whether to run in full screen or rootless mode, the mode specified here will be used.</li>
-    <li><b>Show mode pick panel on startup:</b> By default, a panel is displayed when XDarwin is started to allow the user to choose between full screen or rootless mode. If this option is turned off, the default mode will be started automatically.</li>
-    <li><b>X11 Display number:</b> X11 allows there to be multiple displays managed by separate X servers on a single computer. The user may specify an integer display number for XDarwin to use if more than one X server is going to be run simultaneously.</li>
-    <li><b>Allow Xinerama multiple monitor support:</b> XDarwin supports multiple monitors with Xinerama, which treats all monitors as being part of one large rectangular screen. You can disable Xinerama with this option, but currently XDarwin does not handle multiple monitors correctly without it. If you only have a single monitor, Xinerama is automatically disabled.</li>
-    <li><b>Keymapping File:</b> A keymapping file is read at startup and translated to an X11 keymap. Keymapping files, available for a wide variety of languages, are found in <code>/System/Library/Keyboards</code>.</li>
-    <li><b>Starting First X11 Clients:</b> When XDarwin is started from the Finder, it will run <code>xinit</code> to launch the X window manager and other X clients. (See "<code>man xinit</code>" for more information.) Before XDarwin runs <code>xinit</code> it will add the specified directories to the user's path. By default only <code>/usr/X11R6/bin</code> is added. Additional directories may added, separated by a colon. The X clients are started in the user's default login shell so that the user's shell initialization files are read. If desired, an alternate shell may be specified.</li>
-</ul>
-<h3>Full Screen</h3>
-<ul>
-    <li><b>Key combination button:</b> Click this button and then press any number of modifiers followed by a standard key to change the key combination to switch between Aqua and X11.</li>
-    <li><b>Click on icon in Dock switches to X11:</b> Enable this to activate switching to X11 by clicking on the XDarwin icon in the Dock. On some versions of Mac OS X, switching by clicking in the Dock can cause the cursor to disappear on returning to Aqua.</li>
-    <li><b>Show help on startup:</b> This will show an introductory splash screen when XDarwin is started in full screen mode.</li>
-    <li><b>Color bit depth:</b> In full screen mode, the X11 display can use a different color bit depth than is used by Aqua. If "Current" is specified, the depth used by Aqua when XDarwin starts will be used. Otherwise 8, 15, or 24 bits may be specified.</li>
-</ul>
-
-<h2><a NAME="license">License</a></h2>
-The main license for XDarwin is based on the traditional MIT X11 / X Consortium License, which does not impose any conditions on modification or redistribution of source code or binaries other than requiring that copyright/license notices are left intact. For more information and additional copyright/licensing notices covering some sections of the code, please refer to the source code.
-<H3><A NAME="3"></A>X Consortium License</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>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:</p>
-<p>The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Except as contained in this notice, the name of the X Consortium 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 X Consortium.</p>
-<p>X Window System is a trademark of X Consortium, Inc.</p>
-</body>
-</html>
diff --git a/hw/darwin/bundle/Info.plist b/hw/darwin/bundle/Info.plist
deleted file mode 100644
index 7e17708..0000000
--- a/hw/darwin/bundle/Info.plist
+++ /dev/null
@@ -1,66 +0,0 @@
-<?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.X11</string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundleName</key>
-	<string>XDarwin</string>
-	<key>CFBundlePackageType</key>
-	<string>APPL</string>
-	<key>CFBundleShortVersionString</key>
-	<string>2.0.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/Credits.rtf b/hw/darwin/bundle/Japanese.lproj/Credits.rtf
deleted file mode 100644
index cf9eae2..0000000
--- a/hw/darwin/bundle/Japanese.lproj/Credits.rtf
+++ /dev/null
@@ -1,193 +0,0 @@
-{\rtf1\mac\ansicpg10001\cocoartf102
-{\fonttbl\f0\fnil\fcharset78 HiraKakuPro-W3;\f1\fswiss\fcharset77 Helvetica;\f2\fswiss\fcharset77 Helvetica-Bold;
-\f3\fswiss\fcharset77 Helvetica-Oblique;}
-{\colortbl;\red255\green255\blue255;}
-\vieww13980\viewh11160\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 \'82\'b1\'82\'cc\'90\'bb\'95\'69\'82\'cd 
-\f1 XFree86 
-\f0 \'83\'76\'83\'8d\'83\'57\'83\'46\'83\'4e\'83\'67
-\f1 (http://www.xfree86.org/)
-\f0 \'82\'a8\'82\'e6\'82\'d1\'82\'bb\'82\'cc\'8d\'76\'8c\'a3\'8e\'d2\'82\'c9\'82\'e6\'82\'c1\'82\'c4\'8a\'4a\'94\'ad\'82\'b3\'82\'ea\'82\'bd\'83\'5c\'83\'74\'83\'67\'83\'45\'83\'46\'83\'41\'82\'f0\'8a\'dc\'82\'f1\'82\'c5\'82\'a2\'82\'dc\'82\'b7\'81\'42\'8e\'9f\'82\'cc\'90\'6c\'81\'58\'82\'cd Darwin
-\f1 /Mac OS X 
-\f0 \'82\'cc\'83\'54\'83\'7c\'81\'5b\'83\'67\'82\'c9\'8d\'76\'8c\'a3\'82\'b5\'82\'dc\'82\'b5\'82\'bd\'81\'42
-\f1 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f2\b \cf0 Contributors to Xorg Foundation Release:
-\f1\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f0 \'8d\'b6\'89\'45\'82\'cc Ctrl,Alt(Option),Meta(Command) \'82\'a8\'82\'e6\'82\'d1 Shift \'83\'4c\'81\'5b\'82\'cc\'93\'ae\'8d\'ec
-\f1 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f2\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Contributors to XFree86 4.4:
-\f1\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper
-\f3\i \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f0\i0 \cf0    \'83\'8b\'81\'5b\'83\'67\'83\'8c\'83\'58 \'83\'41\'83\'4e\'83\'5a\'83\'89\'83\'8c\'81\'5b\'83\'56\'83\'87\'83\'93 \'82\'a8\'82\'e6\'82\'d1 Apple-WM \'8a\'67\'92\'a3
-\f1 \
-Torrey T. Lyons\
-     
-\f0 \'83\'76\'83\'8d\'83\'57\'83\'46\'83\'4e\'83\'67 \'83\'8a\'81\'5b\'83\'5f\'81\'5b\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f2\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Additional XonX Contributors to XFree86 4.3:
-\f1\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro\
-     
-\f0 \'83\'7c\'83\'8b\'83\'67\'83\'4b\'83\'8b\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-Michael Oland\
-     
-\f0 \'90\'56\'82\'b5\'82\'a2 
-\f1 XDarwin 
-\f0 \'83\'41\'83\'43\'83\'52\'83\'93
-\f1 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f2\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Contributors to XFree86 4.2:
-\f1\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     Darwin x86
-\f3\i  
-\f0\i0 \'83\'54\'83\'7c\'81\'5b\'83\'67
-\f1 \
-Pablo Di Noto\
-
-\f3\i      
-\f0\i0 \'83\'58\'83\'79\'83\'43\'83\'93\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-Paul Edens\
-
-\f3\i      
-\f0\i0 \'83\'49\'83\'89\'83\'93\'83\'5f\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-Kyunghwan Kim\
-
-\f3\i      
-\f0\i0 \'8a\'d8\'8d\'91\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-Mario Klebsch\
-     
-\f0 \'94\'f1US\'83\'4c\'81\'5b\'83\'7b\'81\'5b\'83\'68 \'83\'54\'83\'7c\'81\'5b\'83\'67
-\f1 \
-Torrey T. Lyons\
-     
-\f0 \'83\'76\'83\'8d\'83\'57\'83\'46\'83\'4e\'83\'67 \'83\'8a\'81\'5b\'83\'5f\'81\'5b
-\f1 \
-Andreas Monitzer\
-     
-\f0 \'83\'68\'83\'43\'83\'63\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-Patrik Montgomery\
-
-\f3\i      
-\f0\i0 \'83\'58\'83\'45\'83\'46\'81\'5b\'83\'66\'83\'93\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-Greg Parker\
-     
-\f0 \'83\'8b\'81\'5b\'83\'67\'83\'8c\'83\'58 \'83\'54\'83\'7c\'81\'5b\'83\'67
-\f1 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f0 \cf0 \'93\'63\'92\'86 \'8f\'72\'8c\'f5
-\f1 \
-     
-\f0 \'93\'fa\'96\'7b\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-Olivier Verdier\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f3\i \cf0      
-\f0\i0 \'83\'74\'83\'89\'83\'93\'83\'58\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f2\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Special Thanks:
-\f1\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman and Zero G Software, Inc.\
-
-\f3\i      
-\f0\i0 \'83\'43\'83\'93\'83\'58\'83\'67\'81\'5b\'83\'89
-\f1 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f2\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Team Members\
-Contributing to XFree86 4.1:
-\f1\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     Darwin x86 
-\f0 \'83\'54\'83\'7c\'81\'5b\'83\'67
-\f1 \
-Torrey T. Lyons\
-     
-\f0 \'83\'76\'83\'8d\'83\'57\'83\'46\'83\'4e\'83\'67 \'83\'8a\'81\'5b\'83\'5f\'81\'5b
-\f1 \
-Andreas Monitzer\
-     Cocoa 
-\f0 \'94\'c5 XDarwin \'83\'74\'83\'8d\'83\'93\'83\'67\'83\'47\'83\'93\'83\'68
-\f1 \
-Greg Parker\
-     
-\f0 \'8d\'c5\'8f\'89\'82\'cc Quartz \'83\'43\'83\'93\'83\'76\'83\'8a\'83\'81\'83\'93\'83\'67
-\f1 \
-Christoph Pfisterer\
-     
-\f0 \'8b\'a4\'97\'4c\'83\'89\'83\'43\'83\'75\'83\'89\'83\'8a
-\f1 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f0 \cf0 \'93\'63\'92\'86 \'8f\'72\'8c\'f5
-\f1 \
-     
-\f0 \'93\'fa\'96\'7b\'8c\'ea\'83\'8d\'81\'5b\'83\'4a\'83\'89\'83\'43\'83\'59
-\f1 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f2\b \cf0 Special Thanks:
-\f1\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     XDarwin 
-\f0 \'83\'41\'83\'43\'83\'52\'83\'93
-\f1 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f2\b \cf0 History:
-\f1\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-     
-\f0 XFree86 \'82\'cc Mac OS X Server \'82\'d6\'82\'cc\'8d\'c5\'8f\'89\'82\'cc\'88\'da\'90\'41
-\f1 \
-Dave Zarzycki\
-     XFree86 4.0 
-\f0 \'82\'f0 Darwin 1.0 \'82\'c9\'88\'da\'90\'41
-\f1 \
-Torrey T. Lyons\
-     XFree86 4.0.2 
-\f0 \'83\'76\'83\'8d\'83\'57\'83\'46\'83\'4e\'83\'67\'82\'d6\'82\'cc\'93\'9d\'8d\'87}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Japanese.lproj/Localizable.strings b/hw/darwin/bundle/Japanese.lproj/Localizable.strings
deleted file mode 100644
index c5c26d6..0000000
Binary files a/hw/darwin/bundle/Japanese.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/Japanese.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/Japanese.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/Japanese.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Japanese.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/Japanese.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index 3570027..0000000
Binary files a/hw/darwin/bundle/Japanese.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/Japanese.lproj/Makefile.am b/hw/darwin/bundle/Japanese.lproj/Makefile.am
deleted file mode 100644
index 8d891ed..0000000
--- a/hw/darwin/bundle/Japanese.lproj/Makefile.am
+++ /dev/null
@@ -1,40 +0,0 @@
-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' | iconv -t UTF-16 > $@
-
-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/Japanese.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/Japanese.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index 6653f5b..0000000
--- a/hw/darwin/bundle/Japanese.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,141 +0,0 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/Japanese.lproj/XDarwinHelp.html.cpp,v 1.4 2001/11/27 07:27:46 torrey Exp $ -->
-
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=EUC-JP">
-<title>
-XDarwin Help</title></head>
-<body>
-<center>
-    <h1>XDarwin X Server for Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    Release Date: X_REL_DATE
-</center>
-<h2>Ìܼ¡</h2>
-<ol>
-    <li><A HREF="#notice">Ãí°Õ»ö¹à</A></li>
-    <li><A HREF="#usage">»ÈÍÑË¡</A></li>
-    <li><A HREF="#path">¥Ñ¥¹¤ÎÀßÄê</A></li>
-    <li><A HREF="#prefs">´Ä¶­ÀßÄê</A></li>
-    <li><A HREF="#license">¥é¥¤¥»¥ó¥¹</A></li>
-</ol>
-<center>
-        <h2><a NAME="notice">Ãí°Õ»ö¹à</a></h2>
-</center>
-<blockquote>
-#if X_PRE_RELEASE
-¤³¤ì¤Ï¡¤XDarwin ¤Î¥×¥ì¥ê¥ê¡¼¥¹¥Ð¡¼¥¸¥ç¥ó¤Ç¤¢¤ê¡¤¤¤¤«¤Ê¤ë¾ì¹ç¤Ë¤ª¤¤¤Æ¤â¥µ¥Ý¡¼¥È¤µ¤ì¤Þ¤»¤ó¡£ 
-¥Ð¥°¤ÎÊó¹ð¤ä¥Ñ¥Ã¥Á¤¬ SourceForge ¤Î <A HREF="http://sourceforge.net/projects/xonx/">XonX ¥×¥í¥¸¥§¥¯¥È¥Ú¡¼¥¸</A>¤ËÄó½Ð¤µ¤ì¤Æ¤¤¤ë¤«¤â¤·¤ì¤Þ¤»¤ó¡£
-¥×¥ì¥ê¥ê¡¼¥¹¥Ð¡¼¥¸¥ç¥ó¤Î¥Ð¥°¤òÊó¹ð¤¹¤ëÁ°¤Ë¡¤<A HREF="http://sourceforge.net/projects/xonx/">XonX</A> ¥×¥í¥¸¥§¥¯¥È¥Ú¡¼¥¸¤Þ¤¿¤Ï X_VENDOR_LINK¤ÇºÇ¿·ÈǤΥÁ¥§¥Ã¥¯¤ò¤·¤Æ²¼¤µ¤¤¡£
-#else
-¤â¤·¡¤¥µ¡¼¥Ð¡¼¤¬ 6 -12 ¥ö·î°Ê¾åÁ°¤Î¤â¤Î¤«¡¤¤Þ¤¿¤Ï¤¢¤Ê¤¿¤Î¥Ï¡¼¥É¥¦¥§¥¢¤¬¾åµ­¤ÎÆüÉÕ¤è¤ê¤â¿·¤·¤¤¤â¤Î¤Ê¤é¤Ð¡¤ÌäÂê¤òÊó¹ð¤¹¤ëÁ°¤Ë¤è¤ê¿·¤·¤¤¥Ð¡¼¥¸¥ç¥ó¤òõ¤·¤Æ¤ß¤Æ¤¯¤À¤µ¤¤¡£
-¥Ð¥°¤ÎÊó¹ð¤ä¥Ñ¥Ã¥Á¤¬ SourceForge ¤Î <A HREF="http://sourceforge.net/projects/xonx/">XonX ¥×¥í¥¸¥§¥¯¥È¥Ú¡¼¥¸</A>¤ËÄó½Ð¤µ¤ì¤Æ¤¤¤ë¤«¤â¤·¤ì¤Þ¤»¤ó¡£
-#endif
-</blockquote>
-<blockquote>
-ËÜ¥½¥Õ¥È¥¦¥§¥¢¤Ï¡¤<A HREF="#license">MIT X11/X Consortium License</A> ¤Î¾ò·ï¤Ë´ð¤Å¤­¡¤ÌµÊݾڤǡ¤¡Ö¤½¤Î¤Þ¤Þ¡×¤Î·Á¤Ç¶¡µë¤µ¤ì¤Þ¤¹¡£
-¤´»ÈÍѤˤʤëÁ°¤Ë¡¤<A HREF="#license">¥é¥¤¥»¥ó¥¹¾ò·ï</A>¤ò¤ªÆɤ߲¼¤µ¤¤¡£
-</blockquote>
-
-<h2><a NAME="usage">»ÈÍÑË¡</a></h2>
-<p>XDarwin ¤Ï¡¤ºÆÇÛÉÛ²Äǽ¤Ê¥ª¡¼¥×¥ó¥½¡¼¥¹¤Î <a HREF="http://www.x.org/">X Window System</a> ¤Î¤¿¤á¤Î X ¥µ¡¼¥Ð¡¼¤Î¼ÂÁõ¤Ç¤¹¡£¤³¤Î¥Ð¡¼¥¸¥ç¥ó¤Î XDarwin ¤Ï X_VENDOR_LINK ¤Ë¤è¤Ã¤ÆºîÀ®¤µ¤ì¤Þ¤·¤¿¡£XDarwin ¤Ï¡¤Mac OS X ¾å¤Ç¥Õ¥ë¥¹¥¯¥ê¡¼¥ó¥â¡¼¥É¤Þ¤¿¤Ï¥ë¡¼¥È¥ì¥¹¥â¡¼¥É¤ÇÆ°ºî¤·¤Þ¤¹¡£</p>
-
-<p>¥Õ¥ë¥¹¥¯¥ê¡¼¥ó¥â¡¼¥É¤Ç¤Ï¡¤X Window System ¤¬¥¢¥¯¥Æ¥£¥Ö¤Ê»þ¡¤¤½¤ì¤ÏÁ´²èÌ̤òÀêÍ­¤·¤Þ¤¹¡£
-¤¢¤Ê¤¿¤Ï¡¤Command-Option-A ¥­¡¼¤ò²¡¤¹¤³¤È¤Ë¤è¤Ã¤Æ Mac OS X ¥Ç¥¹¥¯¥È¥Ã¥×¤ØÀÚ¤êÂؤ¨¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£¤³¤Î¥­¡¼¤ÎÁȤ߹ç¤ï¤»¤Ï¡¤´Ä¶­ÀßÄê¤ÇÊѹ¹²Äǽ¤Ç¤¹¡£
-Mac OS X ¥Ç¥¹¥¯¥È¥Ã¥×¤«¤é X Window System ¤ØÀÚ¤êÂؤ¨¤ë¾ì¹ç¤Ï¡¤¥É¥Ã¥¯¤Ëɽ¼¨¤µ¤ì¤¿ XDarwin ¥¢¥¤¥³¥ó¤ò¥¯¥ê¥Ã¥¯¤·¤Æ²¼¤µ¤¤¡£
-¡Ê´Ä¶­ÀßÄê¤Ç¡¤¥Õ¥í¡¼¥Æ¥£¥ó¥°¡¦¥¦¥£¥ó¥É¥¦¤Ëɽ¼¨¤µ¤ì¤¿ XDarwin ¥¢¥¤¥³¥ó¤ò¥¯¥ê¥Ã¥¯¤¹¤ë¤è¤¦¤ËÊѹ¹¤¹¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£¡Ë</p>
-
-<p>¥ë¡¼¥È¥ì¥¹¥â¡¼¥É¤Ç¤Ï¡¤X Window System ¤È Aqua ¤Ï²èÌ̤ò¶¦Í­¤·¤Þ¤¹¡£
-X11 ¤¬É½¼¨¤¹¤ë¥ë¡¼¥È¥¦¥£¥ó¥É¥¦¤Ï²èÌ̤Υµ¥¤¥º¤Ç¤¢¤ê¡¤Â¾¤ÎÁ´¤Æ¤Î¥¦¥£¥ó¥É¥¦¤ò´Þ¤ó¤Ç¤¤¤Þ¤¹¡£
-Aqua ¤¬¥Ç¥¹¥¯¥È¥Ã¥×¤ÎÇطʤòÀ©¸æ¤¹¤ë¤Î¤Ç¡¤X11 ¤Î¥ë¡¼¥È¥¦¥£¥ó¥É¥¦¤Ï¥ë¡¼¥È¥ì¥¹¥â¡¼¥É¤Ç¤Ïɽ¼¨¤µ¤ì¤Þ¤»¤ó¡£</p>
-
-<h3>Ê£¿ô¥Ü¥¿¥ó¥Þ¥¦¥¹¤Î¥¨¥ß¥å¥ì¡¼¥·¥ç¥ó</h3>
-<p>¿¤¯¤Î X11 ¥¢¥×¥ê¥±¡¼¥·¥ç¥ó¤Ï¡¤3 ¥Ü¥¿¥ó¥Þ¥¦¥¹¤òɬÍפȤ·¤Þ¤¹¡£
-¤¢¤Ê¤¿¤Ï¥Þ¥¦¥¹¥Ü¥¿¥ó¤Î¥¯¥ê¥Ã¥¯¤ÈƱ»þ¤Ë¤¤¤¯¤Ä¤«¤Î½¤¾þ¥­¡¼¤ò²¡¤¹¤³¤È¤Ë¤è¤Ã¤Æ¡¤°ì¤Ä¤Î¥Ü¥¿¥ó¤Ç 3 ¥Ü¥¿¥ó¥Þ¥¦¥¹¤ò¥¨¥ß¥å¥ì¡¼¥·¥ç¥ó¤¹¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£
-¤³¤ì¤Ï¡¤´Ä¶­ÀßÄê¤Î¡Ö°ìÈÌÀßÄê¡×¤Î¡ÖÊ£¿ô¥Ü¥¿¥ó¥Þ¥¦¥¹¤Î¥¨¥ß¥å¥ì¡¼¥·¥ç¥ó¡×¥»¥¯¥·¥ç¥ó¤ÇÀßÄꤷ¤Þ¤¹¡£
-¥Ç¥Õ¥©¥ë¥È¤Ç¤Ï¡¤¥¨¥ß¥å¥ì¡¼¥·¥ç¥ó¤ÏÍ­¸ú¤Ç¡¤¥³¥Þ¥ó¥É¥­¡¼¤ò²¡¤·¤Ê¤¬¤é¥Þ¥¦¥¹¥Ü¥¿¥ó¤ò¥¯¥ê¥Ã¥¯¤¹¤ë¤³¤È¤ÏÂè 2 ¥Þ¥¦¥¹¥Ü¥¿¥ó¤Î¥¯¥ê¥Ã¥¯¤ËÁêÅö¤·¤Þ¤¹¡£
-¥ª¥×¥·¥ç¥ó¥­¡¼¤ò²¡¤·¤Ê¤¬¤é¥¯¥ê¥Ã¥¯¤¹¤ë¤³¤È¤ÏÂè 3 ¥Þ¥¦¥¹¥Ü¥¿¥ó¤Î¥¯¥ê¥Ã¥¯¤ËÁêÅö¤·¤Þ¤¹¡£
-¤¢¤Ê¤¿¤Ï¡¤´Ä¶­ÀßÄê¤Ç¥Ü¥¿¥ó 2 ¤È 3 ¤ò¥¨¥ß¥å¥ì¡¼¥È¤¹¤ë¤¿¤á¤Ë»ÈÍѤ¹¤ë½¤¾þ¥­¡¼¤ÎÁȹ礻¤òÊѹ¹¤¹¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£
-Ãí¡§½¤¾þ¥­¡¼¤ò xmodmap ¤Ç¾¤Î¥­¡¼¤Ë³ä¤êÅö¤Æ¤Æ¤¤¤ë¾ì¹ç¤Ç¤â¡¤Ê£¿ô¥Ü¥¿¥ó¥Þ¥¦¥¹¤Î¥¨¥ß¥å¥ì¡¼¥·¥ç¥ó¤Ç¤ÏËÜÍè¤Î¥³¥Þ¥ó¥É¥­¡¼¤ä¥ª¥×¥·¥ç¥ó¥­¡¼¤ò»È¤ï¤Ê¤±¤ì¤Ð¤Ê¤ê¤Þ¤»¤ó¡£</p>
-
-<h2><a NAME="path">¥Ñ¥¹¤ÎÀßÄê</a></h2>
-<p>¥Ñ¥¹¤Ï¡¤ ¼Â¹Ô²Äǽ¤Ê¥³¥Þ¥ó¥É¤ò¸¡º÷¤¹¤ë¥Ç¥£¥ì¥¯¥È¥ê¤Î¥ê¥¹¥È¤Ç¤¹¡£
-X11 ¥Ð¥¤¥Ê¥ê¤Ï¡¤<code>/usr/X11R6/bin</code> ¤ËÃÖ¤«¤ì¤Þ¤¹¡£¤¢¤Ê¤¿¤Ï¤½¤ì¤ò¥Ñ¥¹¤Ë²Ã¤¨¤ëɬÍפ¬¤¢¤ê¤Þ¤¹¡£
-XDarwin ¤Ï¡¤¤³¤ì¤ò¥Ç¥Õ¥©¥ë¥È¤Ç¹Ô¤¤¤Þ¤¹¡£¤Þ¤¿¡¤¤¢¤Ê¤¿¤¬¥³¥Þ¥ó¥É¥é¥¤¥ó¡¦¥¢¥×¥ê¥±¡¼¥·¥ç¥ó¤ò¥¤¥ó¥¹¥È¡¼¥ë¤·¤¿ÄɲäΥǥ£¥ì¥¯¥È¥ê¤ò²Ã¤¨¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£</p>
-
-<p>·Ð¸³Ë­¤«¤Ê¥æ¡¼¥¶¡¼¤Ï¡¤¤¹¤Ç¤Ë¼«¤é¤Î¥·¥§¥ë¤Î¤¿¤á¤Ë½é´ü²½¥Õ¥¡¥¤¥ë¤ò»ÈÍѤ·¤Æ¥Ñ¥¹¤òÀßÄꤷ¤Æ¤¤¤ë¤Ç¤·¤ç¤¦¡£
-¤³¤Î¾ì¹ç¡¤¤¢¤Ê¤¿¤Ï´Ä¶­ÀßÄê¤Ç XDarwin ¤¬¤¢¤Ê¤¿¤Î¥Ñ¥¹¤òÊѹ¹¤·¤Ê¤¤¤è¤¦¤ËÀßÄꤹ¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£
-XDarwin ¤Ï¡¤¥æ¡¼¥¶¡¼¤Î¥Ç¥Õ¥©¥ë¥È¤Î¥í¥°¥¤¥ó¥·¥§¥ë¤ÇºÇ½é¤Î X11 ¥¯¥é¥¤¥¢¥ó¥È¤ò³«»Ï¤·¤Þ¤¹¡£
-¡Ê´Ä¶­ÀßÄê¤ÇÂå¤ï¤ê¤Î¥·¥§¥ë¤ò»ØÄꤹ¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£¡Ë
-¥Ñ¥¹¤òÀßÄꤹ¤ëÊýË¡¤Ï¡¤¤¢¤Ê¤¿¤¬»ÈÍѤ·¤Æ¤¤¤ë¥·¥§¥ë¤Ë°Í¸¤·¤Þ¤¹¡£
-¤³¤ì¤Ï¡¤¥·¥§¥ë¤Î¥Þ¥Ë¥å¥¢¥ë¥Ú¡¼¥¸¥É¥­¥å¥á¥ó¥È¤Ëµ­ºÜ¤µ¤ì¤Æ¤¤¤Þ¤¹¡£
-
-<p>¤Þ¤¿¡¤¤¢¤Ê¤¿¤Ï¥É¥­¥å¥á¥ó¥È¤òõ¤·¤Æ¤¤¤ë»þ¡¤X11 ¤Î¥Þ¥Ë¥å¥¢¥ë¥Ú¡¼¥¸¤ò¸¡º÷¤µ¤ì¤ë¥Ú¡¼¥¸¤Î¥ê¥¹¥È¤ËÄɲä·¤¿¤¤¤È»×¤¦¤«¤â¤·¤ì¤Þ¤»¤ó¡£
-X11 ¤Î¥Þ¥Ë¥å¥¢¥ë¥Ú¡¼¥¸¤Ï <code>/usr/X11R6/man</code> ¤ËÃÖ¤«¤ì¤Þ¤¹¡£¤½¤·¤Æ <code>MANPATH</code> ´Ä¶­ÊÑ¿ô¤Ï¸¡º÷¤¹¤ë¥Ç¥£¥ì¥¯¥È¥ê¤Î¥ê¥¹¥È¤ò´Þ¤ó¤Ç¤¤¤Þ¤¹¡£</p>
-
-<h2><a NAME="prefs">´Ä¶­ÀßÄê</a></h2>
-<p>¡ÖXDarwin¡×¥á¥Ë¥å¡¼¤Î¡Ö´Ä¶­ÀßÄê...¡×¥á¥Ë¥å¡¼¹àÌܤ«¤é¥¢¥¯¥»¥¹¤Ç¤­¤ë´Ä¶­ÀßÄê¥Ñ¥Í¥ë¤Ç¡¤¤¤¤¯¤Ä¤«¤Î¥ª¥×¥·¥ç¥ó¤òÀßÄꤹ¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£
-¡Öµ¯Æ°¥ª¥×¥·¥ç¥ó¡×¤ÎÆâÍƤϡ¤XDarwin ¤òºÆµ¯Æ°¤¹¤ë¤Þ¤ÇÍ­¸ú¤È¤Ê¤ê¤Þ¤»¤ó¡£
-¾¤ÎÁ´¤Æ¤Î¥ª¥×¥·¥ç¥ó¤ÎÆâÍƤϡ¤Ä¾¤Á¤ËÍ­¸ú¤È¤Ê¤ê¤Þ¤¹¡£
-°Ê²¼¡¤¤½¤ì¤¾¤ì¤Î¥ª¥×¥·¥ç¥ó¤Ë¤Ä¤¤¤ÆÀâÌÀ¤·¤Þ¤¹:</p>
-
-<h3>°ìÈÌÀßÄê</h3>
-<ul>
-    <li><b>X11 ¤Ç¥·¥¹¥Æ¥à¤Î¥Ó¡¼¥×²»¤ò»ÈÍѤ¹¤ë:</b> ¥ª¥ó¤Î¾ì¹ç¡¤Mac OS X ¤Î¥Ó¡¼¥×²»¤¬ X11 ¤Î¥Ù¥ë¤È¤·¤Æ»ÈÍѤµ¤ì¤Þ¤¹¡£¥ª¥Õ¤Î¾ì¹ç¡Ê¥Ç¥Õ¥©¥ë¥È¡Ë¡¤¥·¥ó¥×¥ë ¥È¡¼¥ó¤¬»È¤ï¤ì¤Þ¤¹¡£</li>
-    <li><b>X11 ¤Î¥Þ¥¦¥¹¥¢¥¯¥»¥é¥ì¡¼¥·¥ç¥ó¤òÍ­¸ú¤Ë¤¹¤ë:</b> ɸ½àŪ¤Ê X Window System ¤Î¼ÂÁõ¤Ç¤Ï¡¤¥¦¥£¥ó¥É¥¦¥Þ¥Í¡¼¥¸¥ã¡¼¤Ï¥Þ¥¦¥¹¤Î²Ã®ÅÙ¤òÊѹ¹¤¹¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£
-    ¥Þ¥¦¥¹¤Î²Ã®ÅÙ¤Ë Mac OS X ¤Î¥·¥¹¥Æ¥à´Ä¶­ÀßÄê¤È X ¥¦¥£¥ó¥É¥¦¥Þ¥Í¡¼¥¸¥ã¡¼¤¬°Û¤Ê¤ëÃͤòÀßÄꤷ¤¿¾ì¹ç¡¤¤³¤ì¤Ïº®Íð¤ò¾·¤­¤Þ¤¹¡£
-    ¤³¤ÎÌäÂê¤òÈò¤±¤ë¤¿¤á¡¤¥Ç¥Õ¥©¥ë¥È¤Ç¤Ï X11 ¤Î¥Þ¥¦¥¹¥¢¥¯¥»¥é¥ì¡¼¥·¥ç¥ó¤òÍ­¸ú¤È¤·¤Þ¤»¤ó¡£</li>
-    <li><b>Ê£¿ô¥Ü¥¿¥ó¥Þ¥¦¥¹¤Î¥¨¥ß¥å¥ì¡¼¥·¥ç¥ó:</b> <a HREF="#usage">»ÈÍÑË¡</a>¤ò»²¾È¤·¤Æ²¼¤µ¤¤¡£¥ª¥ó¤Î¾ì¹ç¡¤¥Þ¥¦¥¹¥Ü¥¿¥ó¤¬Âè 2 ¤Þ¤¿¤ÏÂè 3 ¤Î¥Þ¥¦¥¹¥Ü¥¿¥ó¤ò¥¨¥ß¥å¥ì¡¼¥È¤¹¤ë»þ¤Ë¡¤ÁªÂò¤·¤¿½¤¾þ¥­¡¼¤òƱ»þ¤Ë²¡¤·¤Þ¤¹¡£</li>
-</ul>
-
-<h3>µ¯Æ°¥ª¥×¥·¥ç¥ó</h3>
-<ul>
-    <li><b>²èÌ̥⡼¥É:</b> ¥æ¡¼¥¶¡¼¤¬¥Õ¥ë¥¹¥¯¥ê¡¼¥ó¥â¡¼¥É¤Þ¤¿¤Ï¥ë¡¼¥È¥ì¥¹¥â¡¼¥É¤Î¤É¤Á¤é¤ò»ÈÍѤ¹¤ë¤«¤ò»ØÄꤷ¤Ê¤¤¾ì¹ç¡¤¤³¤³¤Ç»ØÄꤵ¤ì¤¿¥â¡¼¥É¤¬»È¤ï¤ì¤Þ¤¹¡£</li>
-    <li><b>µ¯Æ°»þ¤Ë¥â¡¼¥ÉÁªÂò¥Ñ¥Í¥ë¤òɽ¼¨¤¹¤ë:</b> ¥Ç¥Õ¥©¥ë¥È¤Ç¤Ï¡¤XDarwin ¤Îµ¯Æ°»þ¤Ë¥æ¡¼¥¶¡¼¤¬¥Õ¥ë¥¹¥¯¥ê¡¼¥ó¥â¡¼¥É¤Þ¤¿¤Ï¥ë¡¼¥È¥ì¥¹¥â¡¼¥É¤Î¤É¤Á¤é¤ò»ÈÍѤ¹¤ë¤«¤òÁªÂò¤¹¤ë¥Ñ¥Í¥ë¤òɽ¼¨¤·¤Þ¤¹¡£¤³¤Î¥ª¥×¥·¥ç¥ó¤¬¥ª¥Õ¤Î¾ì¹ç¡¤²èÌ̥⡼¥É¤Ç»ØÄꤷ¤¿¥â¡¼¥É¤Çµ¯Æ°¤·¤Þ¤¹¡£</li>
-    <li><b>X11 ¥Ç¥£¥¹¥×¥ì¥¤ÈÖ¹æ:</b> X11¤Ï¡¤°ì¤Ä¤Î¥³¥ó¥Ô¥å¡¼¥¿¾å¤ÇÊÌ¡¹¤Î X ¥µ¡¼¥Ð¡¼¤¬´ÉÍý¤¹¤ëÊ£¿ô¤Î¥Ç¥£¥¹¥×¥ì¥¤¤¬Â¸ºß¤¹¤ë¤³¤È¤òµö¤·¤Þ¤¹¡£Ê£¿ô¤Î X ¥µ¡¼¥Ð¡¼¤¬Æ±»þ¤Ë¼Â¹Ô¤·¤Æ¤¤¤ë»þ¡¤XDarwin ¤¬»ÈÍѤ¹¤ë¥Ç¥£¥¹¥×¥ì¥¤¤ÎÈÖ¹æ¤ò»ØÄꤹ¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£</li>
-    <li><b>Xinerama ¥Þ¥ë¥Á¥â¥Ë¥¿¥µ¥Ý¡¼¥È¤òÍ­¸ú¤Ë¤¹¤ë:</b> XDarwin ¤Ï¡¤Xinerama ¥Þ¥ë¥Á¥â¥Ë¥¿¤ò¥µ¥Ý¡¼¥È¤·¤Þ¤¹¡£¤½¤ì¤ÏÁ´¤Æ¤Î¥â¥Ë¥¿¤ò°ì¤Ä¤ÎÂ礭¤Ê²èÌ̤ΰìÉô¤È¤ß¤Ê¤·¤Þ¤¹¡£¤¢¤Ê¤¿¤Ï¤³¤Î¥ª¥×¥·¥ç¥ó¤Ç Xinerama ¤ò̵¸ú¤Ë¤¹¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£¤¿¤À¤·¡¤¸½ºß XDarwin ¤Ï¤½¤ì̵¤·¤ÇÀµ¤·¤¯Ê£¿ô¤Î¥â¥Ë¥¿¤ò°·¤¦¤³¤È¤¬¤Ç¤­¤Þ¤»¤ó¡£¤â¤·¡¤¤¢¤Ê¤¿¤¬°ì¤Ä¤Î¥â¥Ë¥¿¤ò»È¤¦¤À¤±¤Ê¤é¤Ð¡¤Xinerama ¤Ï¼«Æ°Åª¤Ë̵¸ú¤È¤Ê¤ê¤Þ¤¹¡£</li>
-    <li><b>¥­¡¼¥Þ¥Ã¥Ô¥ó¥°¥Õ¥¡¥¤¥ë:</b> ¥­¡¼¥Þ¥Ã¥Ô¥ó¥°¥Õ¥¡¥¤¥ë¤Ïµ¯Æ°»þ¤ËÆɤ߹þ¤Þ¤ì¡¤X11 ¥­¡¼¥Þ¥Ã¥×¤ËÊÑ´¹¤µ¤ì¤Þ¤¹¡£Â¾¸À¸ì¤ËÂбþ¤·¤¿¥­¡¼¥Þ¥Ã¥Ô¥ó¥°¥Õ¥¡¥¤¥ë¤Ï <code>/System/Library/Keyboards</code> ¤Ë¤¢¤ê¤Þ¤¹¡£¡ÊÌõÃí¡§¥­¡¼¥Þ¥Ã¥Ô¥ó¥°¤Ç Japanese ¤òÁªÂò¤¹¤ë¤È¡¤°ìÉô¤Î¥­¡¼¤¬¸ú¤«¤Ê¤¤Åù¤ÎÉÔ¶ñ¹ç¤¬È¯À¸¤¹¤ë¤³¤È¤¬¤¢¤ê¤Þ¤¹¡£¤³¤Î¾ì¹ç¤Ï USA ¤òÁªÂò¤·¤¿¾å¤Ç ~/.Xmodmap ¤òŬÍѤ·¤Æ²¼¤µ¤¤¡£¡Ë</li>
-    <li><b>ºÇ½é¤Î X11 ¥¯¥é¥¤¥¢¥ó¥È¤Îµ¯Æ°:</b> XDarwin ¤¬ Finder¤«¤éµ¯Æ°¤¹¤ë»þ¡¤X ¥¦¥£¥ó¥É¥¦¥Þ¥Í¡¼¥¸¥ã¡¼¤È X ¥¯¥é¥¤¥¢¥ó¥È¤Îµ¯Æ°¤Ï <code>xinit</code> ¤ò¼Â¹Ô¤·¤Þ¤¹¡£¡Ê¾ÜºÙ¤Ï "<code>man xinit</code>" ¤ò»²¾È¤·¤Æ²¼¤µ¤¤¡£¡ËXDarwin ¤Ï <code>xinit</code> ¤ò¼Â¹Ô¤¹¤ëÁ°¤Ë¡¤»ØÄꤵ¤ì¤¿¥Ç¥£¥ì¥¯¥È¥ê¤ò¥æ¡¼¥¶¡¼¤Î¥Ñ¥¹¤ËÄɲä·¤Þ¤¹¡£¥Ç¥Õ¥©¥ë¥È¤Ç¤Ï <code>/usr/X11R6/bin</code> ¤À¤±¤òÄɲä·¤Þ¤¹¡£Â¾¤Î¥Ç¥£¥ì¥¯¥È¥ê¤òÄɲä·¤¿¤¤¾ì¹ç¤Ï¡¤¥³¥í¥ó¤Ç¶èÀڤäƻØÄꤷ¤Þ¤¹¡£¥æ¡¼¥¶¡¼¤Î¥·¥§¥ë½é´ü²½¥Õ¥¡¥¤¥ë¤òÆɤ߹þ¤à¤¿¤á¤Ë¡¤X ¥¯¥é¥¤¥¢¥ó¥È¤Ï¥æ¡¼¥¶¡¼¤Î¥Ç¥Õ¥©¥ë¥È¥í¥°¥¤¥ó¥·¥§¥ë¤Çµ¯Æ°¤µ¤ì¤Þ¤¹¡£É¬ÍפǤ¢¤ì¤Ð¡¤Âå¤ï¤ê¤Î¥·¥§¥ë¤ò»ØÄꤹ¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£</li>
-</ul>
-
-<h3>¥Õ¥ë¥¹¥¯¥ê¡¼¥ó</h3>
-<ul>
-    <li><b>¥­¡¼ÀßÄê¥Ü¥¿¥ó:</b> X11 ¤È Aqua ¤òÀÚ¤êÂؤ¨¤ë¤¿¤á¤Ë»ÈÍѤ¹¤ë¥Ü¥¿¥ó¤ÎÁȤ߹ç¤ï¤»¤ò»ØÄꤷ¤Þ¤¹¡£
-    ¥Ü¥¿¥ó¤ò¥¯¥ê¥Ã¥¯¤·¤Æ¡¤Ç¤°Õ¤Î¿ô¤Î½¤¾þ¥­¡¼¤Ë³¤¤¤ÆÄ̾ï¤Î¥­¡¼¤ò²¡¤·¤Þ¤¹¡£</li>
-    <li><b>¥É¥Ã¥¯¤Î¥¢¥¤¥³¥ó¤Î¥¯¥ê¥Ã¥¯¤Ç X11 ¤ËÌá¤ë:</b> ¥ª¥ó¤Î¾ì¹ç¡¤¥É¥Ã¥¯¤Ëɽ¼¨¤µ¤ì¤¿ XDarwin ¥¢¥¤¥³¥ó¤Î¥¯¥ê¥Ã¥¯¤Ç X11 ¤Ø¤ÎÀڤ괹¤¨¤¬²Äǽ¤È¤Ê¤ê¤Þ¤¹¡£Mac OS X ¤Î¤¤¤¯¤Ä¤«¤Î¥Ð¡¼¥¸¥ç¥ó¤Ç¤Ï¡¤¥É¥Ã¥¯¤Î¥¢¥¤¥³¥ó¤Î¥¯¥ê¥Ã¥¯¤Ç Aqua ¤ËÌá¤Ã¤¿»þ¡¤¥«¡¼¥½¥ë¤¬¾Ã¼º¤¹¤ë¤³¤È¤¬¤¢¤ê¤Þ¤¹¡£</li>
-    <li><b>µ¯Æ°»þ¤Ë¥Ø¥ë¥×¤òɽ¼¨¤¹¤ë:</b> XDarwin ¤¬¥Õ¥ë¥¹¥¯¥ê¡¼¥ó¥â¡¼¥É¤Çµ¯Æ°¤¹¤ë»þ¡¤¥¹¥×¥é¥Ã¥·¥å¥¹¥¯¥ê¡¼¥ó¤òɽ¼¨¤·¤Þ¤¹¡£</li>
-    <li><b>¿§¿¼ÅÙ:</b> ¥Õ¥ë¥¹¥¯¥ê¡¼¥ó¥â¡¼¥É¤Ç¤Ï¡¤X11 ¥Ç¥£¥¹¥×¥ì¥¤¤¬ Aqua ¤È°Û¤Ê¤ë¿§¿¼ÅÙ¤ò»È¤¦¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£¡ÖÊѹ¹¤Ê¤·¡×¤¬»ØÄꤵ¤ì¤¿¾ì¹ç¡¤XDarwin ¤Ï Aqua ¤Ë¤è¤Ã¤Æ»ÈÍѤµ¤ì¤ë¿§¿¼ÅÙ¤ò»È¤¤¤Þ¤¹¡£¤³¤ì°Ê³°¤Ë 8¡¤15 ¤Þ¤¿¤Ï24 ¥Ó¥Ã¥È¤ò»ØÄꤹ¤ë¤³¤È¤¬¤Ç¤­¤Þ¤¹¡£</li>
-</ul>
-
-<h2>
-<a NAME="license">¥é¥¤¥»¥ó¥¹</a>
-</h2>
-XDarwin ¤Î¼çÍפʥ饤¥»¥ó¥¹¤ÏÅÁÅýŪ¤Ê MIT X11/X Consortium License ¤Ë´ð¤Å¤­¤Þ¤¹¡£
-¤½¤ì¤Ï½¤Àµ¤Þ¤¿¤ÏºÆÇÛÉÛ¤µ¤ì¤ë¥½¡¼¥¹¥³¡¼¥É¤Þ¤¿¤Ï¥Ð¥¤¥Ê¥ê¤Ë¡¤¤½¤ÎÃøºî¸¢/¥é¥¤¥»¥ó¥¹É½¼¨¤¬¤½¤Î¤Þ¤Þ»Ä¤µ¤ì¤ë¤³¤È¤òÍ׵᤹¤ë°Ê³°¤Î¾ò·ï¤ò¶¯À©¤·¤Þ¤»¤ó¡£
-¤è¤ê¿¤¯¤Î¾ðÊó¤È¡¤¥³¡¼¥É¤Î°ìÉô¤ò¥«¥Ð¡¼¤¹¤ëÄɲäÎÃøºî¸¢/¥é¥¤¥»¥ó¥¹É½¼¨¤Î¤¿¤á¤Ë¡¤¥½¡¼¥¹¥³¡¼¥É¤ò»²¾È¤·¤Æ²¼¤µ¤¤¡£
-<H3>
-<A NAME="3"></A>
-X  Consortium License</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>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:</p>
-<p>The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Except as contained in this notice, the name of the X Consortium 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 X Consortium.</p>
-<p>X Window System is a trademark of X Consortium, Inc.</p>
-</body>
-</html>
diff --git a/hw/darwin/bundle/Makefile.am b/hw/darwin/bundle/Makefile.am
deleted file mode 100644
index f02be74..0000000
--- a/hw/darwin/bundle/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-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 \
-	startXClients.cpp \
-	Info.plist
diff --git a/hw/darwin/bundle/Portuguese.lproj/Credits.rtf b/hw/darwin/bundle/Portuguese.lproj/Credits.rtf
deleted file mode 100644
index 8dcddc2..0000000
--- a/hw/darwin/bundle/Portuguese.lproj/Credits.rtf
+++ /dev/null
@@ -1,171 +0,0 @@
-{\rtf1\mac\ansicpg10000\cocoartf102
-{\fonttbl\f0\fswiss\fcharset77 Helvetica;\f1\fswiss\fcharset77 Helvetica-Bold;\f2\fswiss\fcharset77 Helvetica-Oblique;
-}
-{\colortbl;\red255\green255\blue255;}
-\vieww5140\viewh4980\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 This product includes software developed by The XFree86 Project, Inc  (http://www.xfree86.org/) and its contributors. The following people contributed to Darwin/Mac OS X support.\
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Contributors to Xorg Foundation Release:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f2\i Working left and right Ctrl, Alt (Option), Meta (Command) and Shift keys.
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\f1\b \cf0 Contributors to XFree86 4.4:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper\
-     
-\f2\i Rootless acceleration and Apple-WM extension
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Contribuidores do XonX ao XFree86 4.3:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro
-\f1\b \
-     
-\f2\i\b0 Localiza\'8d\'8bo para o Portugu\'90s\
-
-\f0\i0 Michael Oland\
-     
-\f2\i New XDarwin icon
-\f1\i0\b \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Contribuidores do XonX ao XFree86 4.2:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Suporte para o Darwin x86\
-
-\f0\i0 Pablo Di Noto\
-
-\f2\i      Localiza\'8d\'8bo para o Espanhol
-\f0\i0 \
-Paul Edens\
-
-\f2\i      Localiza\'8d\'8bo para o Holand\'90s
-\f0\i0 \
-Kyunghwan Kim\
-
-\f2\i      Localiza\'8d\'8bo para o Coreano
-\f0\i0 \
-Mario Klebsch\
-     
-\f2\i Suporte para teclados Non-US
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i L\'92der de Projeto
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Localiza\'8d\'8bo para o Alem\'8bo
-\f0\i0 \
-Patrik Montgomery\
-
-\f2\i      Localiza\'8d\'8bo para o Sueco
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Suporte ao modo Compartilhado (Rootless)
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Localiza\'8d\'8bo para o Japon\'90s
-\f0\i0 \
-Olivier Verdier\
-
-\f2\i      Localiza\'8d\'8bo para o Fran\'8d\'90s
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Agradecimentos Especiais:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman and Zero G Software, Inc.\
-
-\f2\i      Instalador
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Membros do Time XonX\
-Contribuindo com o XFree86 4.1:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Suporte ao Darwin x86\
-
-\f0\i0 Torrey T. Lyons\
-    
-\f2\i  L\'92der de Projeto
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Vers\'8bo Cocoa da interface XDarwin
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Implementa\'8d\'8bo Original
-\f0\i0  
-\f2\i ao Quartz \
-
-\f0\i0 Christoph Pfisterer\
-     
-\f2\i Bibliotecas Din\'89micas Compartilhadas
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Localiza\'8d\'8bo para o Japon\'90s
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Agradecimento Especial:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     
-\f2\i \'eacone do XDarwin
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Hist\'97rico:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-    
-\f2\i  Suporte Original do XFree86 no Mac OS X Server
-\f0\i0 \
-Dave Zarzycki\
-     
-\f2\i Suporte ao
-\f0\i0  
-\f2\i XFree86 4.0 no Darwin 1.0
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Integra\'8d\'8bo dentro do Projeto XFree86 na vers\'8bo 4.0.2}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Portuguese.lproj/Localizable.strings b/hw/darwin/bundle/Portuguese.lproj/Localizable.strings
deleted file mode 100644
index c79b282..0000000
Binary files a/hw/darwin/bundle/Portuguese.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/Portuguese.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/Portuguese.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/Portuguese.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Portuguese.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/Portuguese.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index 9cb67cf..0000000
Binary files a/hw/darwin/bundle/Portuguese.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/Portuguese.lproj/Makefile.am b/hw/darwin/bundle/Portuguese.lproj/Makefile.am
deleted file mode 100644
index 540649c..0000000
--- a/hw/darwin/bundle/Portuguese.lproj/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-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' | iconv -t UTF-16 > $@
-
-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/Portuguese.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/Portuguese.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index 6800171..0000000
--- a/hw/darwin/bundle/Portuguese.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,209 +0,0 @@
-<head>
-<title>XDarwin Help</title>
-</head>
-
-<center>
-    
-  <h1>XDarwin X Server para Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    Release Date: X_REL_DATE
-</center>
-<h2>&Iacute;ndice</h2>
-<ol>
-    <li><A HREF="#notice">Notas importantes</A></li>
-    <li><A HREF="#usage">Uso</A></li>
-    <li><A HREF="#path">Ajustando seu Path</A></li>
-    
-  <li><A HREF="#prefs">Prefer&ecirc;ncias do usu&aacute;rio</A></li>
-  <li><A HREF="#license">Licen&ccedil;a</A></li>
-</ol>
-<center>
-    <h2><a NAME="notice">Notas importantes</a></h2>
-</center>
-<blockquote>
-#if PRE_RELEASE
-  Essa &eacute; uma vers&atilde;o pr&eacute;-lancamento 
-  do XDarwin, e ela n&atilde;o &eacute; suportada de nenhuma forma. Bugs podem 
-  ser reportados e corre&ccedil;&otilde;es podem ser enviadas para <A HREF="http://sourceforge.net/projects/xonx/">P&aacute;gina 
-  do projeto XonX</A> no SourceForge. Antes de informar bugs em vers&otilde;es 
-  pr&eacute;-lancamento, por favor verifique a þltima vers&atilde;o em <A HREF="http://sourceforge.net/projects/xonx/">XonX</A> 
-  or X_VENDOR_LINK. 
-#else
-Se o servidor &eacute; mais velho que 6-12 semanas, ou seu hardware &eacute; 
-  mais novo que a data acima, procure por uma nova vers&atilde;o antes de informar 
-  problemas. Bugs podem ser reportados e corre&ccedil;&otilde;es podem ser enviadas 
-  para a <A HREF="http://sourceforge.net/projects/xonx/">P&aacute;gina do projeto 
-  XonX</A> na SourceForge.
-#endif
-</blockquote>
-<blockquote> Este software &eacute; distribu&iacute;do sob os termos da <a href="#license">licen&ccedil;a 
-  MIT X11 / X Consortium</a> e &eacute; provido, sem nenhuma garantia. Por favor 
-  leia a <a href="#license">Licen&ccedil;a</a> antes de come&ccedil;ar a usar 
-  o programa.</blockquote>
-
-<h2><a NAME="usage">Uso</a></h2>
-<p>O XDarwin &eacute; uma X server &quot;open-source&quot; livremente 
-  redistribu&iacute;da do <a HREF
-="http://www.x.org/">Sistema X Window</a>. This version of XDarwin was produced by the X_VENDOR_LINK.
-  XDarwin roda sobre Mac OS X no modo Tela Cheia ou no modo Compartilhado.</p>
-<p>No modo Tela Cheia, quando o sistema X window est&aacute; ativo, ele ocupa 
-  a tela toda. Voc&ecirc; pode voltar ao desktop do Mac OS X clicando Command-Option-A. 
-  Essa combina&ccedil;&atilde;o de teclas pode ser mudada nas prefer&ecirc;ncias. 
-  Pelo desktop Mac OS X, clique no &iacute;cone XDarwin no Dock para voltar ao 
-  sistema X window. (Voc&ecirc; pode mudar esse comportamento nas prefer&ecirc;ncias 
-  da&iacute; voc&ecirc; dever&aacute; clicar no &iacute;cone XDarwin na janela 
-  flutuante que aparecer&aacute;.)</p>
-<p>No modo Compartilhado, o sistema X window e Aqua dividem a mesma tela. A janela 
-  raiz da tela X11 est&aacute; do tamanho da tela (monitor) e cont&eacute;m todas 
-  as outras janelas. A janela raiz do X11 no modo compartilhado n&atilde;o &eacute; 
-  mostrada pois o Aqua controla o fundo de tela.</p>
-<h3>Emula&ccedil;&atilde;o de Mouse Multi-Bot&otilde;es</h3>
-<p>Muitas aplica&ccedil;&otilde;es X11 insistem em usar um mouse de 3 bot&otilde;es. 
-  Voc&ecirc; pode emular um mouse de 3 bot&otilde;es com um simples bot&atilde;o, 
-  mantendo pressionando teclas modificadoras enquanto voc&ecirc; clica no bot&atilde;o 
-  do mouse. Isto &eacute; controlado pela configura&ccedil;&atilde;o da &quot;Emula&ccedil;&atilde;o 
-  de Mouse Multi-Bot&otilde;es&quot; da prefer&ecirc;ncia &quot;Geral&quot;. Por 
-  padr&atilde;o, a emula&ccedil;&atilde;o est&aacute; habilitada e mantendo pressionada 
-  a tecla Command e clicando no bot&atilde;o do mouse ele simular&aacute; o clique 
-  no segundo bot&atilde;o do mouse. Mantendo pressionada a tecla Option e clicando 
-  no bot&atilde;o do mouse ele simular&aacute; o terceiro bot&atilde;o. Voc&ecirc; 
-  pode mudar a combina&ccedil;&atilde;o de teclas modificadoras para emular os 
-  bot&otilde;es dois e tr&ecirc;s nas prefer&ecirc;ncias. Nota, se a tecla modificadora 
-  foi mapeada para alguma outra tecla no xmodmap, voc&ecirc; ainda ter&aacute; 
-  que usar a tecla atual especificada nas prefer&ecirc;ncias para a emula&ccedil;&atilde;o 
-  do mouse multi-bot&otilde;es.</p>
-<h2><a NAME="path">Ajustando seu Path</a></h2>
-<p>Seu path &eacute; a lista de diret&oacute;rios a serem procurados por arquivos 
-  execut&aacute;veis. O comando X11 est&aacute; localizado em <code>/usr/X11R6/bin</code>, 
-  que precisa ser adicionado ao seu path. XDarwin faz isso para voc&ecirc; por 
-  padr&atilde;o e pode-se tamb&eacute;m adicionar diret&oacute;rios onde voc&ecirc; 
-  instalou aplica&ccedil;&otilde;es de linha de comando.</p>
-<p>Usu&aacute;rios experientes j&aacute; ter&atilde;o configurado corretamente 
-  seu path usando arquivos de inicializa&ccedil;&atilde;o de seu shell. Neste 
-  caso, voc&ecirc; pode informar o XDarwin para n&atilde;o modificar seu path 
-  nas prefer&ecirc;ncias. O XDarwin inicia o cliente inicial X11 no shell padr&atilde;o 
-  do usu&aacute;rio corrente. (Um shell alternativo pode ser tamb&eacute;m expecificado 
-  nas prefer&ecirc;ncias.) O modo para ajustar o path depende do shell que voc&ecirc; 
-  est&aacute; usando. Isto &eacute; descrito na man page do seu shell.</p>
-<p>Voc&ecirc; pode tamb&eacute;m querer adicionar as man pages do X11 para 
-  a lista de p&aacute;ginas a serem procuradas quando voc&ecirc; est&aacute; procurando 
-  por documenta&ccedil;&atilde;o. As man pages do X11 est&atilde;o localizadas 
-  em <code>/usr/X11R6/man</code> e a vari&aacute;vel de ambiente <code>MANPATH</code> 
-  cont&eacute;m a lista de diret&oacute;rios a buscar.</p>
-<h2><a NAME="prefs">Prefer&ecirc;ncias do Usu&aacute;rio</a></h2>
-<p>V&aacute;rias op&ccedil;&otilde;es podem ser ajustadas nas prefer&ecirc;ncias 
-  do usu&aacute;rio, acess&iacute;vel pelo item &quot;Prefer&ecirc;ncias...&quot; 
-  no menu &quot;XDarwin&quot;. As op&ccedil;&otilde;es listadas como op&ccedil;&otilde;es 
-  de inicializa&ccedil;&atilde;o, n&atilde;o ter&atilde;o efeito at&eacute; voc&ecirc; 
-  reiniciar o XDarwin. Todas as outras op&ccedil;&otilde;es ter&atilde;o efeito 
-  imediatamente. V&aacute;rias das op&ccedil;&otilde;es est&atilde;o descritas 
-  abaixo:</p>
-<h3>Geral</h3>
-<ul>
-  <li><b>Usar o Beep do Sistema para o X11: </b>Quando habilitado som de alerta 
-    padr&atilde;o do Mac OS X ser&aacute; usado como alerta no X11. Quando desabilitado 
-    (padr&atilde;o) um tom simples ser&aacute; usado.</li>
-  <li><b>Permitir o X11 mudar a acelera&ccedil;&atilde;o do mouse: </b>Por implementa&ccedil;&atilde;o 
-    padr&atilde;o no sistema X window, o gerenciador de janelas pode mudar a acelera&ccedil;&atilde;o 
-    do mouse. Isso pode gerar uma confus&atilde;o pois a acelera&ccedil;&atilde;o 
-    do mouse pode ser ajustada diferentemente nas prefer&ecirc;ncias do Mac OS 
-    X e nas prefer&ecirc;ncias do X window. Por padr&atilde;o, o X11 n&atilde;o 
-    est&aacute; habilitado a mudar a acelera&ccedil;&atilde;o do mouse para evitar 
-    este problema.</li>
-  <li><b>Emula&ccedil;&atilde;o de Mouse de Multi-Bot&otilde;es: </b>Esta op&ccedil;&atilde;o 
-    est&aacute; escrita acima em <a href="#usage">Uso</a>. Quando a emula&ccedil;&atilde;o 
-    est&aacute; habilitada as teclas modificadoras selecionadas tem que estar 
-    pressionadas quando o bot&atilde;o do mouse for pressionado, para emular o 
-    segundo e terceiro bot&otilde;es.</li>
-</ul>
-<h3>Inicial</h3>
-<ul>
-  <li><b>Modo Padr&atilde;o: </b>Se o usu&aacute;rio n&atilde;o indicar qual modo 
-    de exibi&ccedil;&atilde;o quer usar (Tela Cheia ou Compartilhado) o modo especificado 
-    aqui ser&aacute; usado .</li>
-  <li><b>Mostrar o painel de escolha na inicializa&ccedil;&atilde;o: </b> Por 
-    padr&atilde;o, uma painel &eacute; mostrado quando o XDarwin &eacute; 
-    iniciado para permitir que o usu&aacute;rio escolha ente o modo tela cheia 
-    ou modo compartilhado. Se esta op&ccedil;&atilde;o estiver desligada, o modo 
-    padr&atilde;o ser&aacute; inicializado automaticamente.</li>
-  <li><b>N&uacute;mero do Monitor X11: </b>O X11 permite ser administrado em multiplos 
-    monitores por servidores X separados num mesmo computador. O usu&aacute;rio 
-    pode indicar o n&uacute;mero do monitor para o XDarwin usar se mais de um 
-    servidor X se estiver rodando simultaneamente.</li>
-  <li><b>Habilitar suporte a m&uacute;ltiplos monitores pelo Xinerama: </b>o XDarwin 
-    suporta m&uacute;ltiplos monitores com o Xinerama, que trata todos os monitores 
-    como parte de uma grande e retangular tela. Voc&ecirc; pode desabilitar o 
-    Xinerama com est&aacute; op&ccedil;&atilde;o, mas normalmente o XDarwin n&atilde;o 
-    controla m&uacute;ltiplos monitores corretamente sem est&aacute; op&ccedil;&atilde;o. 
-    Se voc&ecirc; s&oacute; tiver um monotor, Xinerama &eacute; automaticamente 
-    desabilitado. </li>
-  <li><b>Arquivo de Mapa de Teclado: </b> O mapa de teclado &eacute; lido na inicializa&ccedil;&atilde;o 
-    e traduzido para um mapa de teclado X11. Arquivos de mapa de teclado, est&atilde;o 
-    dispon&iacute;veis numa grande variedade de l&iacute;nguas e s&atilde;o encontradas 
-    em <code>/System/Library/Keyboards</code>.</li>
-  <li><b>Iniciando Clientes X11 primeiro: </b>Quando o XDrawin &eacute; inicializado 
-    pelo Finder, ele ir&aacute; rodar o <code>xinit</code> para abrir o controlador 
-    X window e outros clientes X. (Veja o manual "<code>man xinit</code>" para 
-    mais informa&ccedil;&otilde;es.) Antes do XDarwin rodar o <code>xinit</code> 
-    ele ir&aacute; adicionar espec&iacute;ficos diret&oacute;rios a seu path. 
-    Por padr&atilde;o somente o <code>/usr/X11R6/bin</code> &eacute; adicionado. 
-    separado por um ponto-e-v&iacute;rgula. Os clientes X s&atilde;o inicializados 
-    no shell padr&atilde;o do usu&aacute;rio e os arquivos de inicializa&ccedil;&atilde;o 
-    do shell ser&atilde;o lidos. Se desejado, um shell alternativo pode ser especificado.</li>
-</ul>
-<h3>Tela Cheia</h3>
-<ul>
-  <li><b>Bot&atilde;o de Combina&ccedil;&atilde;o de Teclas: </b> Clique no bot&atilde;o 
-    e pressione qualquer quantidade de teclas modificadoras seguidas por uma tecla 
-    padr&atilde;o para modificar a combina&ccedil;&atilde;o quando se quer mudar 
-    entre o Aqua e X11.</li>
-  <li><b>Clique no &Iacute;cone no Dock para mudar para o X11: </b>Habilitando 
-    esta op&ccedil;&atilde;o voc&ecirc; ir&aacute; ativar a mudan&ccedil;a para 
-    o X11 clicando no &iacute;cone do XDarwin no Dock. Em algumas vers&otilde;es 
-    do Mac OS X, mudando pelo clique no Dock pode causar o desaparecimento do 
-    cursor quando retornar ao Aqua.</li>
-  <li><b>Mostrar a Ajuda na inicializa&ccedil;&atilde;o: </b>Isto ir&aacute; mostrar 
-    uma tela introdut&oacute;ria quando o XDarwin for inicializado no modo Tela 
-    Cheia. </li>
-  <li><b>Profundidade de Cores em bits: </b> No modo Tela Cheia, a tela do X11 
-    pode usar uma profundiadde de cor diferente da usada no Aqua. Se a op&ccedil;&atilde;o 
-    &quot;Atual&quot; est&aacute; especificada, a profundidade usada pelo Aqua 
-    quando o XDarwin iniciar ser&aacute; a mesma. Al&eacute;m das op&ccedil;&otilde;es 
-    8, 15 ou 24 bits que podem ser especificadas.</li>
-</ul>
-
-<h2><a NAME="license">Licen&ccedil;a</a></h2>
-<p>A licen&ccedil;a 
-  principal n&oacute;s por XDarwin baseada na licen&ccedil;a tradicional MIT X11 
-  / X Consortium, que n&atilde;o imp&otilde;e nenhuma condi&ccedil;&atilde;o sobre 
-  modifica&ccedil;&otilde;es ou redistribui&ccedil;&atilde;o do c&oacute;digo-fonte 
-  ou dos bin&aacute;rios desde que o copyright/licen&ccedil;a sejam mantidos intactos. 
-  Para mais informa&ccedil;&otilde;es e not&iacute;cias adicionais de copyright/licensing 
-  em algumas se&ccedil;&atilde;o do c&oacute;digo, por favor refer to the source code.</p>
-<H3><A NAME="3"></A>Licen&ccedil;a do X Consortium</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>Permiss&otilde;es s&atilde;o em virtude garantidas, livre de mudan&ccedil;as, 
-  para qualquer pessoa que possua uma c&oacute;pia deste software e aos arquivos 
-  de documenta&ccedil;&atilde;o associada (o &quot;Software&quot;), para lidar 
-  com o software sem restri&ccedil;&otilde;es, incluindo limita&ccedil;&otilde;es 
-  dos direitos de uso, c&oacute;pia, modifica&ccedil;&atilde;o, inclus&atilde;o, 
-  publica&ccedil;&atilde;o, distribui&ccedil;&atilde;o, sub licen&ccedil;a, e/ou 
-  venda de c&oacute;pias deste Software, e permitir pessoas to whom o Software 
-  &eacute; fornecido para ser desta forma, verifique as seguintes condi&ccedil;&otilde;es:</p>
-<p>O nota de copyright abaixo e a permiss&atilde;o dever&atilde;o ser inclu&iacute;das 
-  em todas as c&oacute;pias ou substanciais por&ccedil;&otilde;es do Software.</p>
-<p>O SOFTWARE 'E PROVIDO &quot;COMO TAL&quot;, SEM GARANTIAS DE NENHUM TIPO, EXPLICITA 
-  OU IMPLICITA, INCLUINDO MAS N&Atilde;O LIMITADO NOS AVISOS DE COM&Eacute;RCIO, 
-  TAMANHO OU PARA PROPOSTAS PARTICULARES E N&Atilde;O INFRA&Ccedil;&Atilde;O. 
-  EM NENHUM ACONTECIMENTO O X CONSORTIUM SER&Aacute; RESPONSAV&Eacute;L POR NENHUMA 
-  RECLAMA&Ccedil;&Atilde;O, DANOS OU OUTRAS RESPONSABILIDADES, SE NUMA A&Ccedil;&Atilde;O 
-  DE CONTRATO, OU OUTRA COISA, SURGINDO DE, FORA DE OU EM CONEX&Atilde;O COM O 
-  SOFTWARE OU O USO OU OUTRO MODO DE LIDAR COM O SOFTWARE.</p>
-<p>Exceto o contido nesta nota, o nome do X Consortium n&atilde;o pode ser usado 
-  em propagandas ou outra forma de promo&ccedil;&atilde;o de vendas, uso ou outro 
-  modo de lidar com este Software sem ter recebido uma autoriza&ccedil;&atilde;o 
-  escrita pelo X Consortium.</p>
-<p>O Sistema X Window &eacute; marca registrada do X Consortium, Inc.</p>
-</body>
-</html>
-
diff --git a/hw/darwin/bundle/Spanish.lproj/Credits.rtf b/hw/darwin/bundle/Spanish.lproj/Credits.rtf
deleted file mode 100644
index 34408e7..0000000
--- a/hw/darwin/bundle/Spanish.lproj/Credits.rtf
+++ /dev/null
@@ -1,168 +0,0 @@
-{\rtf1\mac\ansicpg10000\cocoartf102
-{\fonttbl\f0\fswiss\fcharset77 Helvetica;\f1\fswiss\fcharset77 Helvetica-Bold;\f2\fswiss\fcharset77 Helvetica-Oblique;
-}
-{\colortbl;\red255\green255\blue255;}
-\vieww5160\viewh6300\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 This product includes software developed by The XFree86 Project, Inc  (http://www.xfree86.org/) and its contributors. The following people contributed to Darwin/Mac OS X support.\
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Contributors to Xorg Foundation Release:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f2\i Working left and right Ctrl, Alt (Option), Meta (Command) and Shift keys.
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\f1\b \cf0 Contributors to XFree86 4.4:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper\
-     
-\f2\i Rootless acceleration and Apple-WM extension
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Additional XonX Contributors to XFree86 4.3:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro\
-     
-\f2\i Portuguese localization
-\f0\i0 \
-Michael Oland\
-     
-\f2\i New XDarwin icon
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Contributors to XFree86 4.2:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Pablo Di Noto\
-
-\f2\i      Spanish localization
-\f0\i0 \
-Paul Edens\
-
-\f2\i      Dutch localization
-\f0\i0 \
-Kyunghwan Kim\
-
-\f2\i      Korean localization
-\f0\i0 \
-Mario Klebsch\
-     
-\f2\i Non-US keyboard support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i German localization
-\f0\i0 \
-Patrik Montgomery\
-
-\f2\i      Swedish localization
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Rootless support
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-Olivier Verdier\
-
-\f2\i      French localization
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman and Zero G Software, Inc.\
-
-\f2\i      Installer
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Team Members\
-Contributing to XFree86 4.1:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Cocoa version of XDarwin front end
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Original Quartz implementation
-\f0\i0 \
-Christoph Pfisterer\
-     
-\f2\i Dynamic shared libraries
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     
-\f2\i XDarwin icon
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 History:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-     
-\f2\i Original XFree86 port to Mac OS X Server
-\f0\i0 \
-Dave Zarzycki\
-     
-\f2\i XFree86 4.0 port to Darwin 1.0
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Integration into XFree86 Project for 4.0.2}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Spanish.lproj/Localizable.strings b/hw/darwin/bundle/Spanish.lproj/Localizable.strings
deleted file mode 100644
index 5bf813f..0000000
Binary files a/hw/darwin/bundle/Spanish.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/Spanish.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/Spanish.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/Spanish.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Spanish.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/Spanish.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index 2df75ee..0000000
Binary files a/hw/darwin/bundle/Spanish.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/Spanish.lproj/Makefile.am b/hw/darwin/bundle/Spanish.lproj/Makefile.am
deleted file mode 100644
index 978ac35..0000000
--- a/hw/darwin/bundle/Spanish.lproj/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-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' | iconv -t UTF-16 > $@
-
-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/XDarwinHelp.html.cpp b/hw/darwin/bundle/Spanish.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index a79e6f9..0000000
--- a/hw/darwin/bundle/Spanish.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-<html>
-<head>
-<title>XDarwin Ayuda</title>
-</head>
-<body>
-<center>
-    <h1>XDarwin X Server for Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    Fecha de release: X_REL_DATE
-</center>
-<h2>Contenido</h2>
-<ol>
-    <li><A HREF="#notice">Aviso Importante</A></li>
-    <li><A HREF="#usage">Modo de uso</A></li>
-    <li><A HREF="#path">Configurando su Path</A></li>
-    <li><A HREF="#prefs">Preferencias del Usuario</A></li>
-    <li><A HREF="#license">Licencia</A></li>
-</ol>
-<center>
-    <h2><a NAME="notice">Aviso Importante</a></h2>
-</center>
-<blockquote>
-#if PRE_RELEASE
-Esta es una versi&oacuten pre-release de XDarwin, y no tiene ning&uacuten soporte. Patches y reportes de error pueden ser enviados a la <A HREF="http://sourceforge.net/projects/xonx/">p&aacutegina del proyecto XonX</A> en SourceForge.  Antes de reportar errores en versiones pre-release, por favor verifique la ultima versi&oacuten en <A HREF="http://sourceforge.net/projects/xonx/">XonX</A> o bien el X_VENDOR_LINK.
-#else
-Si el server el m&aacutes antiguo que 6 a 12 meses, o si su hardware es posterior a la fecha indicada m&aacutes arriba, por favor verifique la &uacuteltima versi&oacuten antes de reportar problemas. Patches y reportes de error pueden ser enviados a la <A HREF="http://sourceforge.net/projects/xonx/">p&aacutegina del proyecto XonX</A> en SourceForge.
-#endif
-</blockquote>
-<blockquote>
-Este software es distribuido bajo los t&eacuterminos de la <A HREF="#license">Licencia MIT X11 / X Consortium</A> y es provisto sin garant&iacutea alguna y en el estado en que se encuentra. Por favor lea la <A HREF="#license">Licencia</A> antes de utilizarlo.</blockquote>
-
-<h2><a NAME="usage">Modo de uso</a></h2>
-<p>XDarwin es una X server open-source de distribuci&oacuten libre del <a HREF
-="http://www.x.org/">X Window System</a>. This version of XDarwin was produced by the X_VENDOR_LINK. XDarwin funciona en Mac OS X en modo pantalla completa o en modo rootless (integrado al escritorio).</p>
-<p>En modo pantalla completa, el X window system toma control total de la pantalla mientras esta activo. Presionando Command-Option-A  puede regresar al Escritorio de Mac OS X. Esta combinaci&oacuten de teclas puede cambiarse en las Preferencias de Usuario. Desde el Escritorio de Mac OS X, haga click en &iacutecono de XDarwin en el Dock para volver al X window system.  (Puede cambiar esta comportamiento en las Preferencias de Usuario y configurar que XDarwin vuelva al X window system haciendo click en la ventana flotante con el logo X.)</p>
-<p>En modo rootless, el X window system comparte la pantalla con Aqua. La ventana root de X11 es del tama&ntildeo de la pantalla y contiene a todas las dem&aacutes ventanas. La ventana root de X11 no se muestra en este modo, ya que Aqua maneja el fondo de pantalla.</p>
-<h3>Emulaci&oacuten de mouse multi-bot&oacuten</h3>
-<p>Muchas aplicaciones X11 requieren del uso de un mouse de 3 botones. Es posible emular un mouse de 3 botones con un mouse de solo un bot&oacuten presionando teclas modificadoras mientras hace click. Esto es controlado en de la seccion "Emulaci&oacuten mouse" dentro de la secci&oacuten "General" de las Preferencias del Usuario. Por defecto, la emulaci&oacuten est&aacute activa y utiliza la tecla Command para simular el 2do bot&oacuten y la tecla Option para simlar el 3er bot&oacuten. La conbinaci&oacuten para simular el 2do y 3er bot&oacuten pueden ser modificada por cualquier combinaci&oacuten de teclas modificadoras dentro de las Preferencias del Usuario. Tenga en cuenta que aunque las teclas modificadoras hayan sido mapeadas a otras teclas con xmodmap, las teclas configuradas en las Preferencias del Usuario seguir&aacuten siendo las utilizadas por la emulaci&oacuten de mouse multi-bot&oacuten.</p>
-
-<h2><a NAME="path">Configurando su Path</a></h2>
-<p>El path es la lista de directorios donde se buscar&aacuten los comandos ejecutables. Los comandos de X11 se encuentran en  <code>/usr/X11R6/bin</code>, y &eacuteste necesita estar dentro de su path. XDarwin hace &eacutesto autom&aacuteticamente por defecto, y puede adem&aacutes agregar directorios adicionales donde tenga otros comandos de l&iacutenea.</p>
-<p>Usuarios experimentados pueden tener su path correctamente configurado mediante los archivos de inicio de su interprete de comandos.  En este caso, puede informarle a XDarwin en las Preferencias de Usuario para que no modifique su path. XDarwin arrancar&aacute los clientes X11 iniciales usando el int&eacuterprete de comandos del usuario, seg&uacuten su configuraci&oacuten de login. Un int&eacuterprete de comandos alternativo puede ser especificado en las Preferencias del Usuario. La manera de configurar el path de su int&eacuterprete de comandos depende de cual est&aacute usando, y es generalmente descripta en las p&aacuteginas man del mismo.</p>
-<p>Adem&aacutes, Ud. puede agregar las p&aacuteginas man de X11 a la lista de p&aacuteginas que son consultadas. Estas est&aacuten ubicadas en <code>/usr/X11R6/man</code> y <code>MANPATH</code> es la variable de entorno que contiene los directorios que son consultados.</p>
-
-<h2><a NAME="prefs">Preferencias del Usuario</a></h2>
-<p>Ciertas opciones pueden definirse dentro de "Preferencias...", en el men&uacute de XDarwin. Las opciones dentro de de "Inicio" no surtir&aacuten efecto hasta que la aplicaci&oacuten se reinicie. Las restantes opciones surten efecto inmediatamente. Las diferentes opciones se describen a continuaci&oacuten:</p>
-<h3>General</h3>
-<ul>
-    <li><b>Usar beep del sistema en X11:</b> Cuando esta opci&oacuten est&aacute activa, el sonido de alerta est&aacutendar de Mac OS X se usar&aacute como alerta de X11. Cuando est&aacute desactivada, un simple tono es utilizado (esta es la opci&oacuten por defecto).</li>
-    <li><b>Permitir que X11 cambie la aceleraci&oacuten del mouse:</b> En una implementaci&oacuten est&aacutendard de X11, el window manager puede cambiar la aceleraci&oacuten del mouse. Esto puede llevar a una gran confusi&oacuten si la aceleraci&oacuten es diferente en XDarwin y en Mac OS X. Por defecto, no se le permite a X11 alterar la aceleraci&oacuten para evitar este inconveniente.</li>
-    <li><b>Emulaci&oacuten de mouse multi-bot&oacuten:</b> Esta opci&oacuten es descripta m&aacutes arriba bajo <a HREF="#usage">Modo de Uso</a>. Cuando esta emulaci&oacuten est&aacute activa los modificadores seleccionados deben ser presionados cuando se hace click para emular el bot&oacuten 2 o el bot&oacuten 3.</li>
-</ul>
-<h3>Inicio</h3>
-<ul>
-    <li><b>Modo inicial:</b> Si el usuario no indica si desea utilizar la Pantalla Completa o el modo Rootless, el modo especificado aqu&iacute ser&aacute el usado.</li>
-    <li><b>Mostrar panel de selecci&oacuten al inicio:</b> Por defecto, un di&aacutelogo permite al usuario elegir entre Pantalla Completa o Rootless al inicio. Si esta opci&oacuten esta desactivada, XDarwin arrancar&aacute utilizando el modo por defecto sin consultar al usuario.</li>
-    <li><b>N&uacutemero de display X11:</b> X11 permite que existan m&uacuteltiples pantallas manejadas por servidores X11 separados funcionando en una misma computadora. El usuario puede especificar aqui un n&uacutemero entero para indicar el n&uacutemero de pantalla (display) que XDarwin utilizar&aacute si m&aacutes de un servidor X funciona en forma simult&aacutenea.</li>
-    <li><b>Habilitar soporte Xinerama para m&uacuteltipes monitores:</b> XDarwin suporta m&uacuteltiple monitores con Xinerama, que maneja todos los monitores como si fueran parte de una gran pantalla rectangular. Puede deshabilitar Xinerama con esta opci&oacuten, pero XDarwin no maneja m&uacuteltiples monitores en forma correcta sin esta opci&oacuten habilitada. Si tiene solo un monitor, Xinerama es autom&aacuteticamente deshabilitado.</li>
-    <li><b>Archivo de mapa de teclado:</b> Un archivo de mapa de teclas es le&iacutedo al inicio y es traducido a un keymap X11 (un archivo est&aacutendard de X11 para especificar la funci&oacuten de cada tecla). Estos archivos, disponibles para una amplia variedad de lenguajes, pueden encontrarse en  <code>/System/Library/Keyboards</code>.</li>
-    <li><b>Al iniciar clientes X11:</b> Cuando XDarwin arranca desde el Finder, &eacuteste ejecutar&aacute <code>xinit</code> para a su vez arrancar el window manager y otros clientes. (Vea en "<code>man xinit</code>" para mayor informaci&oacuten). Antes de ejecutar <code>xinit</code> XDarwin agregar&aacute los directorios especificados al path del usuario. Por defecto, solo <code>/usr/X11R6/bin</code> es agregado. Otros directorios adicionales puede agregarse separados por dos puntos (:). Los clientes X son ejecutados con el int&eacuterprete de comandos del usuario, por lo que los archivos de inicio de &eacuteste son le&iacutedos. Si se desea, un int&eacuterprete de comandos diferente puede ser especificado.</li>
-</ul>
-<h3>Pantalla Completa</h3>
-<ul>
-    <li><b>Bot&oacuten para definir combinaci&oacuten de teclas:</b> Haga click en este bot&oacuten y luego presione cualquier combinaci&oacuten de modificadores seguidos de una tecla convencional para definir que combinaci&oacuten usar&aacute para intercambiar entre X11 y Aqua.</li>
-    <li><b>Click en el &iacutecono del Dock cambia a X11:</b> Habilite esta opci&oacuten para volver a X11 al hacer click en &iacutecono de XDarwin en el Dock. En algunas versiones de Mac OS X, al volver haciendo click en el Dock puede causar al desaparci&oacuten del cursor al volver a Aqua.</li>
-    <li><b>Mostrar ayuda al inicio:</b> Esta opci&oacuten habilitada har&aacute que una pantalla inicial de introducci&oacuten aparezca cuando XDarwin es arrancado en modo Pantalla Completa.</li>
-    <li><b>Profundidad de color (bits):</b> En modo Pantalla Completa, el display X11 puede utilizar una profundidad de color diferente de la utilizada por Aqua. Si se especifica "Actual", la misma profundidad de color que Aqua utiliza ser&aacute adoptada por X11. Al contrario, puede especificar 8, 15, o 24 bits.</li>
-</ul>
-
-<h2><a NAME="license">Licencia</a></h2>
-La licencia principal de XDarwin es basada en la Licencia MIT X11 tradicional, que no impone condiciones a la modificaci&oacuten o redistribuci&oacuten del c&oacutedigo fuente o de archivos binarios m&aacutes all&aacute de requerir que los mensajes de Licencia y Copyright se mantengan intactos. Para mayor informaci&oacuten y para mensajes adicionales de Licencia y Copyright que cubren algunas secciones del c&oacutedigo fuente, por favor consulte the source code.
-<H3><A NAME="3"></A>Licencia del X Consortium</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>Se otorga aqui permiso, libre de costo, a toda persona que obtenga una copia de este Software y los archivos de documentaci&oacuten asociados (el "Software"),
-para utilizar el Software sin restricciones, incluyendo sin l&iacutemites los derechos de usar, copiar, modificar, integrar con otros productos, publicar, distribuir, sub-licenciar y/o comercializar copias del Software, y de permitir a las personas que lo reciben para hacer lo propio, sujeto a las siguientes condiciones:</p>
-<p>El mensaje de Copyright indicado m&aacutes arriba y este permiso ser&aacute inclu&iacutedo en todas las copias o porciones sustanciales del Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Excepto lo indicado en este mensaje, el nombre del X Consortium no ser&aacute utilizado en propaganda o como medio de promoci&oacuten para la venta, utilizaci&oacuten u otros manejos de este Software sin previa autorizaci&oacuten escrita del X Consortium.</p>
-<p>X Window System es una marca registrada de X Consortium, Inc.</p>
-<H3><A NAME="3"></A>X Consortium License (English)</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>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:</p>
-<p>The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Except as contained in this notice, the name of the X Consortium 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 X Consortium.</p>
-<p>X Window System is a trademark of X Consortium, Inc.</p>
-</body>
-</html>
diff --git a/hw/darwin/bundle/Swedish.lproj/Credits.rtf b/hw/darwin/bundle/Swedish.lproj/Credits.rtf
deleted file mode 100644
index 34408e7..0000000
--- a/hw/darwin/bundle/Swedish.lproj/Credits.rtf
+++ /dev/null
@@ -1,168 +0,0 @@
-{\rtf1\mac\ansicpg10000\cocoartf102
-{\fonttbl\f0\fswiss\fcharset77 Helvetica;\f1\fswiss\fcharset77 Helvetica-Bold;\f2\fswiss\fcharset77 Helvetica-Oblique;
-}
-{\colortbl;\red255\green255\blue255;}
-\vieww5160\viewh6300\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 This product includes software developed by The XFree86 Project, Inc  (http://www.xfree86.org/) and its contributors. The following people contributed to Darwin/Mac OS X support.\
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Contributors to Xorg Foundation Release:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f2\i Working left and right Ctrl, Alt (Option), Meta (Command) and Shift keys.
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\f1\b \cf0 Contributors to XFree86 4.4:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper\
-     
-\f2\i Rootless acceleration and Apple-WM extension
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Additional XonX Contributors to XFree86 4.3:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro\
-     
-\f2\i Portuguese localization
-\f0\i0 \
-Michael Oland\
-     
-\f2\i New XDarwin icon
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Contributors to XFree86 4.2:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Pablo Di Noto\
-
-\f2\i      Spanish localization
-\f0\i0 \
-Paul Edens\
-
-\f2\i      Dutch localization
-\f0\i0 \
-Kyunghwan Kim\
-
-\f2\i      Korean localization
-\f0\i0 \
-Mario Klebsch\
-     
-\f2\i Non-US keyboard support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i German localization
-\f0\i0 \
-Patrik Montgomery\
-
-\f2\i      Swedish localization
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Rootless support
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-Olivier Verdier\
-
-\f2\i      French localization
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman and Zero G Software, Inc.\
-
-\f2\i      Installer
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Team Members\
-Contributing to XFree86 4.1:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Cocoa version of XDarwin front end
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Original Quartz implementation
-\f0\i0 \
-Christoph Pfisterer\
-     
-\f2\i Dynamic shared libraries
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     
-\f2\i XDarwin icon
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 History:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-     
-\f2\i Original XFree86 port to Mac OS X Server
-\f0\i0 \
-Dave Zarzycki\
-     
-\f2\i XFree86 4.0 port to Darwin 1.0
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Integration into XFree86 Project for 4.0.2}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Swedish.lproj/Localizable.strings b/hw/darwin/bundle/Swedish.lproj/Localizable.strings
deleted file mode 100644
index 9709e54..0000000
Binary files a/hw/darwin/bundle/Swedish.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/Swedish.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/Swedish.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/Swedish.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/Swedish.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/Swedish.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index 3157d72..0000000
Binary files a/hw/darwin/bundle/Swedish.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/Swedish.lproj/Makefile.am b/hw/darwin/bundle/Swedish.lproj/Makefile.am
deleted file mode 100644
index 3cf542c..0000000
--- a/hw/darwin/bundle/Swedish.lproj/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-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' | iconv -t UTF-16 > $@
-
-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/XDarwinHelp.html.cpp b/hw/darwin/bundle/Swedish.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index ab940ec..0000000
--- a/hw/darwin/bundle/Swedish.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-<html>
-<head>
-<title>XDarwin Help</title>
-</head>
-<body>
-<center>
-    <h1>XDarwin X Server for Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    F&auml;rdigst&auml;llt: X_REL_DATE
-</center>
-<h2>Inneh&aring;ll</h2>
-<ol>
-    <li><A HREF="#notice">Viktigt!</A></li>
-    <li><A HREF="#usage">Anv&auml;ndande</A></li>
-    <li><A HREF="#path">Att st&auml;lla in sin s&ouml;kv&auml;g</A></li>
-    <li><A HREF="#prefs">Inst&auml;llningar</A></li>
-    <li><A HREF="#license">Licens</A></li>
-</ol>
-<center>
-    <h2><a NAME="notice">Viktigt!</a></h2>
-</center>
-<blockquote>
-#if PRE_RELEASE
-Detta &auml;r en testversion av XDarwin, och du kan inte garranteras n&aring;gon som helst support f&ouml;r den. Buggar och fel kan rapporteras och f&ouml;rslag till fixar kan skickas till <A HREF="http://sourceforge.net/projects/xonx/">XonX-projektets sida</A> p&aring; SourceForge.  Innan du rapporterar buggar i testversioner, var god pr&ouml;va den senaste versionen fr&aring;n <A HREF="http://sourceforge.net/projects/xonx/">XonX</A> eller i X_VENDOR_LINK.
-#else
-Om servern &auml;r &auml;ldre &auml;n 6-12 m&aring;nader, eller om din h&aring;rdvara &auml;r nyare &auml;n datumet ovan, leta efter en nyare version innan du rapporterar fel. Buggar och fel kan rapporteras och f&ouml;rslag till fixar kan skickas till <A HREF="http://sourceforge.net/projects/xonx/">XonX-projektets sida</A> p&aring; SourceForge.
-#endif
-</blockquote>
-<blockquote>
-Denna programvara distrubueras i enlighet med <A HREF="#license">MIT X11 / X Consortium License</A> och tilhandh&aring;lls som den &auml;r, helt utan garantier. Var god l&auml;s igenom <A HREF="#license">licensdokumentet (engelska)</A> innan du anv&auml;nder programmet.</blockquote>
-
-<h2><a NAME="usage">Anv&auml;ndande</a></h2>
-<p>XDarwin &auml;r en fritt spridd X server av <a HREF
-="http://www.x.org/">X Window-systemet</a>. This version of XDarwin was produced by the X_VENDOR_LINK. XDarwin kan k&ouml;ras p&aring; Mac OS X i fullsk&auml;rmsl&auml;ge eller rotl&ouml;st l&auml;ge.</p>
-<p>I fullsk&auml;rmsl&auml;ge kommer X window-systemet att ta &ouml;ver hela sk&auml;rmen n&auml;r det &auml;r aktivt. Du kan byta tillbaka till Mac OS Xs skrivbord genom att trycka Kommando-Alt-A. Denna tangentkombination kan &auml;ndra i inst&auml;llningarna. N&auml;r du &auml;r p&aring; Mac OS Xs skrivbord kan du klicka p&aring; XDarwin-ikonen i dockan f&ouml;r att byta tillbaka till X Window-systemet. (Du kan f&ouml;r&auml;ndra detta beteende i inst&auml;llningarna s&aring; att du ist&auml;llet m&aring;ste klicka i det fltande bytesf&ouml;nstret ist&auml;llet.)</p>
-<p>I rotl&ouml;stl&auml;ge delar X11 och Aqua p&aring; din sk&auml;rm. Rotf&ouml;nstret p&aring; X11-sk&auml;rmen &auml;r av samma storlek som hela sk&auml;rmen och inneh&aring;ller alla andra f&ouml;nster - det fungerar som bakgrund. I rotl&ouml;stl&auml;ge visas inte detta rotf&ouml;nster, eftersom Aqua hanterar skrvbordbakgrunden.</p>
-
-<h3>Emulering av flerknapparsmus</h3>
-<p>M&aring;nga X11-program utnyttjar en treknapparsmus. Du kan emulera en treknapparsmus med en knapp genom att h&aring;lla ner olika knappar p&aring; tangentbordet medan du klickar med musens enda knapp. Denna funktion styrs av inst&auml;llningarna i  "Emulera flerknapparsmus" under fliken "Diverse" i inst&auml;llningarna. Grundinst&auml;llningen &auml;r att emulationen &auml;r aktiv  och att ett kommando-klick (H&aring;ll ner kommando och klicka) simulerar den andra musknappen. Den tredje musknappen f&aring;s genom att h&aring;lla ner alt och klicka. Du kan &auml;ndra detta till n&aring;gon annan kombination av de fem tangenterna kommando, alt, kontrol, skift och fn (Powerbook/iBook). Notera att om dessa knappar har flyttats med hj&auml;lp av kommandot xmodmap kommer denna f&ouml;r&auml;ndring inte att p&aring;verka vilka knappar som anv&auml;nds vid flerknappsemulationen.</p>
-
-<h2><a NAME="path">Att st&auml;lla in sin s&ouml;kv&auml;g</a></h2>
-<p>Din s&ouml;kv&auml;g &auml;r en lista av kataloger som s&ouml;ks igenom n&auml;r terminalen letar efter kommandon att exekvera. Kommandon som h&ouml;r till X11 ligger i <code>/usr/X11R6/bin</code>, en katalog som inte ligger i din s&ouml;kv&auml;g fr&aring;n b&ouml;rjan. XDarwin l&auml;gger till denna katalog &aring;t dig, och du kan ocks&aring; l&auml;gga till ytterligare kataloger i vilka du lagt program som skall k&ouml;ras fr&aring;n kommandoraden.</p>
-<p>Mer erfarna anv&auml;ndare har antagligen redan st&auml;llt in sin s&ouml;kv&auml;g i skalets inst&auml;llningsfiler. Om detta g&auml;ller dig  kan st&auml;lla in XDarwin s&aring; att din s&ouml;kv&auml;g inte modifieras. XDarwin startar de f&ouml;rsta X11-klienterna i anv&auml;ndarens inloggningsskal (Vill du anv&auml;nda ett alternativt skall, kan du specificera detta i inst&auml;llningarna). Hur du st&auml;ller in din s&ouml;kv&auml;g beror p&aring; vilket skal du anv&auml;nder. Exakt hur beskrivs i skalets man-sidor.</p>
-
-<p>Ut&ouml;ver detta kan du ocks&aring; vilja l&auml;gga till X11s man-sidor (dokumentation) till listan &auml;ver sidor som som skall s&ouml;kas n&auml;r du vill l&auml;sa efter dokumentationen. X11s man-sidor ligger i <code>/usr/X11R6/man</code> och listan &auml;ver kataloger att s&ouml;ka best&auml;mms av variabeln<code>MANPATH</code>.</p>
-
-<h2><a NAME="prefs">Inst&auml;llningar</a></h2>
-<p>I inst&auml;llningarna finns ett antal alternativ d&auml;r du kan p&aring;verka hur XDarwin beter sig i vissa fall. Inst&auml;llningarna kommer du till genom att v&auml;lja "Inst&auml;llningar..." i menyn "XDarwin". De alternativ som finns under fliken "Starta" tr&auml;der inte i kraft f&ouml;rr&auml;n du startat om programmet. Alla andra alternativ tr&auml;der i kraft omedelbart. De olika alternativen beskrivs nedan:</p>
-<h3>Diverse</h3>
-<ul>
-    <li><b>Anv&auml;nd Mac OS varningsljud i X11:</b> N&auml;r detta alternativ &auml;r valt anv&auml;nds Mac OS vanliga varningsljud &auml;r X11s varningsljud (bell). N&auml;r detta alternativ inte &auml;r valt (f&ouml;rvalt) anv&auml;nds en vanlig ton.</li>
-    <li><b>Till&aring;t X11 att &auml;ndra musens acceleration:</b> I ett vanligt X11-system kan f&ouml;nsterhanteraren &auml;ndra musens acceleration. Detta kan vara f&ouml;rvirrande eftersom musens acceleration kan vara olika i Mac OS Xs System Preferences och i f&ouml;nsterhanteraren i X11. F&ouml;rvalet &auml;r att X11 inte kan &auml;ndra musens acceleration f&ouml;r att p&aring; detta s&auml;tt undvika detta problem.</li>
-    <li><b>Emulera flerknapparsmus:</b> Detta beskrivs ovan under <a HREF="#usage">Anv&auml;ndande</a>. N&auml;r emulationen &auml;r aktiv m&aring;ste du h&aring;lla ner de valda knapparna f&ouml;r att emulera en andra eller tredje musknapp.</li>
-</ul>
-<h3>Starta</h3>
-<ul>
-    <li><b>F&ouml;rvalt l&auml;ge:</b> Om anv&auml;ndaren inte p&aring; annat s&auml;tt v&auml;ljer vilket l&auml;ge som skall anv&auml;ndas kommer alternativet h&auml;r att anv&auml;ndas.</li>
-    <li><b>Visa val av sk&auml;rml&auml;ge vid start:</b> F&ouml;rvalet &auml;r att visa ett f&ouml;nster n&auml;r XDarwin startar som l&aring;ter anv&auml;ndaren v&auml;lja mellan fullsk&auml;rmsl&auml;ge och rotl&ouml;st l&auml;ge. Om detta alternativ inte &auml;r aktivt kommer XDarwin automatiskt att startas i det l&auml;ge som valts ovan.</li>
-    <li><b>Sk&auml;rmnummer i X11:</b> X11 till&aring;ter att det finns flera sk&auml;rmar styrda av varsin X-server p&aring; en och samma dator. Anv&auml;ndaren kan ange vilket nummer XDarwin skall anv&auml;nda om mer &auml;n en X-server skall anv&auml;ndas samtidigt.</li>
-    <li><b>Aktivera Xinerama (st&ouml;d f&ouml;r flera sk&auml;rmar):</b> XDarwin st&ouml;djer flera sk&auml;rmar genom Xinerama, vilket hanterar alla skr&auml;mar som delar av en enda stor rektangul&auml;r sk&auml;rm. Du kan anv&auml;nda detta alternativ f&ouml;r att st&auml;nga av Xinerama, men f&ouml;r n&auml;rvarande kan inte XDarwin hantera flera sk&auml;rmar utan det. Om du bara har en sk&auml;rm kommer Xinerama automatiskt att deaktiveras.</li>
-    <li><b>Fil med tangentbordsupps&auml;ttning:</b> En fil som anger tangentbordsupps&auml;ttning l&auml;ses vid start och &ouml;vers&auml;tts till en tangentborsupps&auml;ttningsfil f&ouml;r X11. Filer med tangentbordsupps&auml;ttningar f&ouml;r ett stort antal spr&aring;k finns i <code>/System/Library/Keyboards</code>.</li>
-    <li><b>Startar f&ouml;rsta X11-klienterna:</b> N&auml;r X11 startas fr&aring;n Finder kommer det att exekvera filen <code>xinit</code> f&ouml;r att starta f&ouml;nsterhanteraren i X11 och andra program. (Se "<code>man xinit</code>" f&ouml;r mer information.) Innan XDarwin k&ouml;r xinit kommer det att l&auml;gga till katalogern h&auml;r till anv&auml;ndarens s&ouml;kv&auml;g. F&ouml;rvalet &auml;r att endast l&auml;gga till katalogen <code>/usr/X11R6/bin</code>. Ytterligare kataloger kan l&auml;ggas till - separera dem med kolon. X11-klienterna startas i anv&auml;ndarens inloggningsskal s&aring; att anv&auml;ndarens inst&auml;llningsfiler i skalet l&auml;ses. Om s&aring; &ouml;nskas kan de startas i ett annat skal.</li>
-</ul>
-<h3>Fullsk&auml;rm</h3>
-<ul>
-    <li><b>Tangentkombinationsknappen:</b> Tryck p&aring; denna knapp och en tangentkombination f&ouml;r att &auml;ndra den tangentkombination som anv&auml;nds f&ouml;r att byta mellan X11 och Aqua.</li>
-    <li><b>Klick p&aring; ikonen i dockan byter till X11:</b> Aktivera detta alternativ f&ouml;r att byta till X11 genom att klicka p&aring; ikonen i dockan. I vissa versioner av Mac OS X kommer ett bte p&aring; detta s&auml;tt att g&ouml;mma pekaren n&auml;r du &aring;terv&auml;nder till Aqua.</li>
-    <li><b>Visa fullsk&auml;rmshj&auml;lp vid start:</b> Detta kommer att visa en informationsruta n&auml;r XDarwin startas i fullsk&auml;rmsl&auml;ge.</li>
-    <li><b>F&auml;rgdjup:</b> I fullsk&auml;rmsl&auml;ge kan X11 anv&auml;nda ett annat f&auml;rgdjup &auml;n Aquas. Om du v&auml;jer "Nuvarande" kommer X11 att anv&auml;nda det f&auml;rgdjup som Aqua har just d&aring;.  Annars kan du v&auml;lja 8, 15, eller 24 bitare f&auml;rg.</li>
-</ul>
-
-<h2><a NAME="license">Licens (svenska)</a></h2>
-<p>Den huvudsakliga licens vi anv&auml;nder oss av &auml;r baserad p&aring; den traditionella MIT X11 / XConsortium-licensen, vilken inte p&aring; n&aring;got s&auml;tt begr&auml;nsar f&ouml;r&auml;ndringar eller vidarespridning av vare sig k&auml;llkod eller kompilerad programvara annat &auml;n genom att kr&auml;va att delarna som r&ouml;r copyright och licensiering l&auml;mnas intakta. F&ouml;r mer information och ytterligare copyright/licensieringsinfromation r&ouml;rande vissa speciella delar av koden, se the source code.</p>
-
-<h3>Licence (english)</h3>
-<p>The main license for XDarwin is based on the traditional MIT X11 / X Consortium License, which does not impose any conditions on modification or redistribution of source code or binaries other than requiring that copyright/license notices are left intact. For more information and additional copyright/licensing notices covering some sections of the code, please refer to the source code.</p>
-
-<H3><A NAME="3"></A>X Consortium License</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>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:</p>
-<p>The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Except as contained in this notice, the name of the X Consortium 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 X Consortium.</p>
-<p>X Window System is a trademark of X Consortium, Inc.</p>
-</body>
-</html>
diff --git a/hw/darwin/bundle/XDarwin.icns b/hw/darwin/bundle/XDarwin.icns
deleted file mode 100644
index 9c56084..0000000
Binary files a/hw/darwin/bundle/XDarwin.icns and /dev/null differ
diff --git a/hw/darwin/bundle/ko.lproj/Credits.rtf b/hw/darwin/bundle/ko.lproj/Credits.rtf
deleted file mode 100644
index 34408e7..0000000
--- a/hw/darwin/bundle/ko.lproj/Credits.rtf
+++ /dev/null
@@ -1,168 +0,0 @@
-{\rtf1\mac\ansicpg10000\cocoartf102
-{\fonttbl\f0\fswiss\fcharset77 Helvetica;\f1\fswiss\fcharset77 Helvetica-Bold;\f2\fswiss\fcharset77 Helvetica-Oblique;
-}
-{\colortbl;\red255\green255\blue255;}
-\vieww5160\viewh6300\viewkind0
-\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
-
-\f0\fs24 \cf0 This product includes software developed by The XFree86 Project, Inc  (http://www.xfree86.org/) and its contributors. The following people contributed to Darwin/Mac OS X support.\
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Contributors to Xorg Foundation Release:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Kaleb KEITHLEY\
-     
-\f2\i Working left and right Ctrl, Alt (Option), Meta (Command) and Shift keys.
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\f1\b \cf0 Contributors to XFree86 4.4:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Harper\
-     
-\f2\i Rootless acceleration and Apple-WM extension
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Additional XonX Contributors to XFree86 4.3:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Fabr\'92cio Luis de Castro\
-     
-\f2\i Portuguese localization
-\f0\i0 \
-Michael Oland\
-     
-\f2\i New XDarwin icon
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Contributors to XFree86 4.2:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Pablo Di Noto\
-
-\f2\i      Spanish localization
-\f0\i0 \
-Paul Edens\
-
-\f2\i      Dutch localization
-\f0\i0 \
-Kyunghwan Kim\
-
-\f2\i      Korean localization
-\f0\i0 \
-Mario Klebsch\
-     
-\f2\i Non-US keyboard support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i German localization
-\f0\i0 \
-Patrik Montgomery\
-
-\f2\i      Swedish localization
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Rootless support
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-Olivier Verdier\
-
-\f2\i      French localization
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Devin Poolman and Zero G Software, Inc.\
-
-\f2\i      Installer
-\f0\i0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-
-\f1\b \cf0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-\cf0 XonX Team Members\
-Contributing to XFree86 4.1:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Rob Braun\
-     
-\f2\i Darwin x86 support
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Project Lead
-\f0\i0 \
-Andreas Monitzer\
-     
-\f2\i Cocoa version of XDarwin front end
-\f0\i0 \
-Greg Parker\
-     
-\f2\i Original Quartz implementation
-\f0\i0 \
-Christoph Pfisterer\
-     
-\f2\i Dynamic shared libraries
-\f0\i0 \
-Toshimitsu Tanaka\
-     
-\f2\i Japanese localization
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 Special Thanks:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 Tiago Ribeiro\
-     
-\f2\i XDarwin icon
-\f0\i0 \
-\
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\qc
-
-\f1\b \cf0 History:
-\f0\b0 \
-\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
-\cf0 John Carmack\
-     
-\f2\i Original XFree86 port to Mac OS X Server
-\f0\i0 \
-Dave Zarzycki\
-     
-\f2\i XFree86 4.0 port to Darwin 1.0
-\f0\i0 \
-Torrey T. Lyons\
-     
-\f2\i Integration into XFree86 Project for 4.0.2}
\ No newline at end of file
diff --git a/hw/darwin/bundle/ko.lproj/Localizable.strings b/hw/darwin/bundle/ko.lproj/Localizable.strings
deleted file mode 100644
index fb8c77e..0000000
Binary files a/hw/darwin/bundle/ko.lproj/Localizable.strings and /dev/null differ
diff --git a/hw/darwin/bundle/ko.lproj/MainMenu.nib/classes.nib b/hw/darwin/bundle/ko.lproj/MainMenu.nib/classes.nib
deleted file mode 100644
index 77f345a..0000000
--- a/hw/darwin/bundle/ko.lproj/MainMenu.nib/classes.nib
+++ /dev/null
@@ -1,72 +0,0 @@
-{
-    IBClasses = (
-        {
-            ACTIONS = {showHelp = id; }; 
-            CLASS = FirstResponder; 
-            LANGUAGE = ObjC; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            ACTIONS = {close = id; pickFile = id; saveChanges = id; setKey = id; }; 
-            CLASS = Preferences; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                addToPathButton = id; 
-                addToPathField = id; 
-                button2ModifiersMatrix = id; 
-                button3ModifiersMatrix = id; 
-                depthButton = id; 
-                displayField = id; 
-                dockSwitchButton = id; 
-                fakeButton = id; 
-                keymapFileField = id; 
-                modeMatrix = id; 
-                modeWindowButton = id; 
-                mouseAccelChangeButton = id; 
-                startupHelpButton = id; 
-                switchKeyButton = id; 
-                systemBeepButton = id; 
-                useDefaultShellMatrix = id; 
-                useOtherShellField = id; 
-                useXineramaButton = id; 
-                window = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }, 
-        {
-            CLASS = XApplication; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {preferences = id; xserver = id; }; 
-            SUPERCLASS = NSApplication; 
-        }, 
-        {
-            ACTIONS = {
-                bringAllToFront = id; 
-                closeHelpAndShow = id; 
-                itemSelected = id; 
-                nextWindow = id; 
-                previousWindow = id; 
-                showAction = id; 
-                showSwitchPanel = id; 
-                startFullScreen = id; 
-                startRootless = id; 
-            }; 
-            CLASS = XServer; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                dockMenu = NSMenu; 
-                helpWindow = NSWindow; 
-                modeWindow = NSWindow; 
-                startFullScreenButton = NSButton; 
-                startRootlessButton = NSButton; 
-                startupHelpButton = NSButton; 
-                startupModeButton = NSButton; 
-                switchWindow = NSPanel; 
-                windowMenu = NSMenu; 
-                windowSeparator = NSMenuItem; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
diff --git a/hw/darwin/bundle/ko.lproj/MainMenu.nib/objects.nib b/hw/darwin/bundle/ko.lproj/MainMenu.nib/objects.nib
deleted file mode 100644
index 8f9b5e0..0000000
Binary files a/hw/darwin/bundle/ko.lproj/MainMenu.nib/objects.nib and /dev/null differ
diff --git a/hw/darwin/bundle/ko.lproj/Makefile.am b/hw/darwin/bundle/ko.lproj/Makefile.am
deleted file mode 100644
index a5462ff..0000000
--- a/hw/darwin/bundle/ko.lproj/Makefile.am
+++ /dev/null
@@ -1,40 +0,0 @@
-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' | iconv -t UTF-16 > $@
-
-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/XDarwinHelp.html.cpp b/hw/darwin/bundle/ko.lproj/XDarwinHelp.html.cpp
deleted file mode 100644
index db33670..0000000
--- a/hw/darwin/bundle/ko.lproj/XDarwinHelp.html.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-<html>
-<head>
-<title>XDarwin Help</title>
-</head>
-<body>
-<center>
-    <h1>XDarwin X Server for Mac OS X</h1>
-    X_VENDOR_NAME X_VERSION<br>
-    Release Date: X_REL_DATE
-</center>
-<h2>Contents</h2>
-<ol>
-    <li><A HREF="#notice">Important Notice</A></li>
-    <li><A HREF="#usage">Usage</A></li>
-    <li><A HREF="#path">Setting Your Path</A></li>
-    <li><A HREF="#prefs">User Preferences</A></li>
-    <li><A HREF="#license">License</A></li>
-</ol>
-<center>
-    <h2><a NAME="notice">Important Notice</a></h2>
-</center>
-<blockquote>
-#if X_PRE_RELEASE
-This is a pre-release version of XDarwin, and is not supported in any way. Bugs may be reported and patches may be submitted to the <A HREF="http://sourceforge.net/projects/xonx/">XonX project page</A> at SourceForge.  Before reporting bugs in pre-release versions, please check the latest version from <A HREF="http://sourceforge.net/projects/xonx/">XonX</A> or the X_VENDOR_LINK.
-#else
-If the server is older than 6-12 months, or if your hardware is newer than the above date, look for a newer version before reporting problems. Bugs may be reported and patches may be submitted to the <A HREF="http://sourceforge.net/projects/xonx/">XonX project page</A> at SourceForge.
-#endif
-</blockquote>
-<blockquote>
-This software is distributed under the terms of the <A HREF="#license">MIT X11 / X Consortium License</A> and is provided AS IS, with no warranty. Please read the <A HREF="#license">License</A> before using.</blockquote>
-
-<h2><a NAME="usage">Usage</a></h2>
-<p>XDarwin is a freely redistributable open-source X server for the <a HREF="http://www.x.org/">X Window System</a>. This version of XDarwin was produced by the X_VENDOR_LINK. XDarwin runs on Mac OS X in full screen or rootless modes.</p>
-<p>In full screen mode, when the X window system is active, it takes over the entire screen. You can switch back to the Mac OS X desktop by holding down Command-Option-A. This key combination can be changed in the user preferences. From the Mac OS X desktop, click on the XDarwin icon in the Dock to switch back to the X window system.  (You can change this behavior in the user preferences so that you must click the XDarwin icon in the floating switch window instead.)</p>
-<p>In rootless mode, the X window system and Aqua 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 Aqua handles the desktop background.</p>
-<h3>Multi-Button Mouse Emulation</h3>
-<p>Many X11 applications rely on the use of a 3-button mouse. You can emulate a 3-button mouse with a single button by holding down various modifier keys while you click the mouse button. This is controlled by settings in the "Multi-Button Mouse Emulation" section of the "General" preferences. By default, emulation is on and holding down the command key and clicking the mouse button will simulate clicking the second mouse button. Holding down the option key and clicking will simulate the third button. You can change to any combination of modifiers to emulate buttons two and three in the preferences. Note, even if the modifiers keys are mapped to some other key with xmodmap, you still must use the actual keys specified in the preferences for multi-button mouse emulation.</p>
-
-<h2><a NAME="path">Setting Your Path</a></h2>
-<p>Your path is the list of directories to be searched for executable commands. The X11 commands are located in <code>/usr/X11R6/bin</code>, which needs to be added to your path. XDarwin does this for you by default and can also add additional directories where you have installed command line applications.</p>
-<p>More experienced users will have already set their path correctly using the initialization files for their shell. In this case, you can inform XDarwin not to modify your path in the preferences. XDarwin launches the initial X11 clients in the user's default login shell. (An alternate shell can also be specified in the preferences.) The way to set the path depends on the shell you are using. This is described in the man page documentation for the shell.</p>
-<p>In addition you may also want to add the X11 man pages to the list of pages to be searched when you are looking for documentation. The X11 man pages are located in <code>/usr/X11R6/man</code> and the <code>MANPATH</code> environment variable contains the list of directories to search.</p>
-
-<h2><a NAME="prefs">User Preferences</a></h2>
-<p>A number of options may be set from the user preferences, accessible from the "Preferences..." menu item in the "XDarwin" menu. The options listed as start up options will not take effect until you have restarted XDarwin. All other options take effect immediately. The various options are described below:</p>
-<h3>General</h3>
-<ul>
-    <li><b>Use System beep for X11:</b> When enabled the standard Mac OS X alert sound is used as the X11 bell. When disabled (default) a simple tone is used.</li>
-    <li><b>Allow X11 to change mouse acceleration:</b> In a standard X window system implementation, the window manager can change the mouse acceleration. This can lead to confusion as the mouse acceleration may be set to different values by the Mac OS X System Preferences and the X window manager. By default, X11 is not allowed to change the mouse acceleration to avoid this problem.</li>
-    <li><b>Multi-Button Mouse Emulation:</b> This is described above under <a HREF="#usage">Usage</a>. When emulation is enabled the selected modifiers must be held down when the mouse button is pushed to emulate the second or third mouse buttons.</li>
-</ul>
-<h3>Start Up</h3>
-<ul>
-    <li><b>Default Mode:</b> If the user does not indicate whether to run in full screen or rootless mode, the mode specified here will be used.</li>
-    <li><b>Show mode pick panel on startup:</b> By default, a panel is displayed when XDarwin is started to allow the user to choose between full screen or rootless mode. If this option is turned off, the default mode will be started automatically.</li>
-    <li><b>X11 Display number:</b> X11 allows there to be multiple displays managed by separate X servers on a single computer. The user may specify an integer display number for XDarwin to use if more than one X server is going to be run simultaneously.</li>
-    <li><b>Allow Xinerama multiple monitor support:</b> XDarwin supports multiple monitors with Xinerama, which treats all monitors as being part of one large rectangular screen. You can disable Xinerama with this option, but currently XDarwin does not handle multiple monitors correctly without it. If you only have a single monitor, Xinerama is automatically disabled.</li>
-    <li><b>Keymapping File:</b> A keymapping file is read at startup and translated to an X11 keymap. Keymapping files, available for a wide variety of languages, are found in <code>/System/Library/Keyboards</code>.</li>
-    <li><b>Starting First X11 Clients:</b> When XDarwin is started from the Finder, it will run <code>xinit</code> to launch the X window manager and other X clients. (See "<code>man xinit</code>" for more information.) Before XDarwin runs <code>xinit</code> it will add the specified directories to the user's path. By default only <code>/usr/X11R6/bin</code> is added. Additional directories may added, separated by a colon. The X clients are started in the user's default login shell so that the user's shell initialization files are read. If desired, an alternate shell may be specified.</li>
-</ul>
-<h3>Full Screen</h3>
-<ul>
-    <li><b>Key combination button:</b> Click this button and then press any number of modifiers followed by a standard key to change the key combination to switch between Aqua and X11.</li>
-    <li><b>Click on icon in Dock switches to X11:</b> Enable this to activate switching to X11 by clicking on the XDarwin icon in the Dock. On some versions of Mac OS X, switching by clicking in the Dock can cause the cursor to disappear on returning to Aqua.</li>
-    <li><b>Show help on startup:</b> This will show an introductory splash screen when XDarwin is started in full screen mode.</li>
-    <li><b>Color bit depth:</b> In full screen mode, the X11 display can use a different color bit depth than is used by Aqua. If "Current" is specified, the depth used by Aqua when XDarwin starts will be used. Otherwise 8, 15, or 24 bits may be specified.</li>
-</ul>
-
-<h2><a NAME="license">License</a></h2>
-The main license for XDarwin is based on the traditional MIT X11 / X Consortium License, which does not impose any conditions on modification or redistribution of source code or binaries other than requiring that copyright/license notices are left intact. For more information and additional copyright/licensing notices covering some sections of the code, please refer to the source code.
-<H3><A NAME="3"></A>X Consortium License</H3>
-<p>Copyright (C) 1996 X Consortium</p>
-<p>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:</p>
-<p>The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.</p>
-<p>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 X CONSORTIUM 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.</p>
-<p>Except as contained in this notice, the name of the X Consortium 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 X Consortium.</p>
-<p>X Window System is a trademark of X Consortium, Inc.</p>
-</body>
-</html>
diff --git a/hw/darwin/bundle/startXClients.cpp b/hw/darwin/bundle/startXClients.cpp
deleted file mode 100644
index f812dbf..0000000
--- a/hw/darwin/bundle/startXClients.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-XCOMM!/bin/sh
-
-XCOMM This script is used by XDarwin to start X clients when XDarwin is
-XCOMM launched from the Finder.
-
-userclientrc=$HOME/.xinitrc
-sysclientrc=XINITDIR/xinitrc
-clientargs=""
-
-if [ -f $userclientrc ]; then
-    clientargs=$userclientrc
-else if [ -f $sysclientrc ]; then
-    clientargs=$sysclientrc
-fi
-fi
-
-if [ "x$2" != "x" ]; then
-    PATH="$PATH:$2"
-    export PATH
-fi
-
-exec xinit $clientargs -- XBINDIR/XDarwinStartup "$1" -idle
diff --git a/hw/darwin/iokit/Makefile.am b/hw/darwin/iokit/Makefile.am
deleted file mode 100644
index 77227d7..0000000
--- a/hw/darwin/iokit/Makefile.am
+++ /dev/null
@@ -1,17 +0,0 @@
-noinst_LIBRARIES = libiokit.a
-
-AM_CFLAGS = @XORG_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
deleted file mode 100644
index 7f126c7..0000000
--- a/hw/darwin/iokit/xfIOKit.c
+++ /dev/null
@@ -1,774 +0,0 @@
-/**************************************************************
- *
- * IOKit support for the Darwin X Server
- *
- * HISTORY:
- * Original port to Mac OS X Server by John Carmack
- * Port to Darwin 1.0 by Dave Zarzycki
- * Significantly rewritten for XFree86 4.0.1 by Torrey Lyons
- *
- **************************************************************/
-/*
- * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, 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.
- */
-
-#if HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "os.h"
-#include "servermd.h"
-#include "inputstr.h"
-#include "scrnintstr.h"
-#include "mi.h"
-#include "mibstore.h"
-#include "mipointer.h"
-#include "micmap.h"
-#include "shadow.h"
-
-#include <sys/types.h>
-#include <sys/time.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <assert.h>
-
-#include <mach/mach_interface.h>
-
-#define NO_CFPLUGIN
-#include <IOKit/IOKitLib.h>
-#include <IOKit/hidsystem/IOHIDShared.h>
-#include <IOKit/graphics/IOGraphicsLib.h>
-
-// Define this to work around bugs in the display drivers for
-// older PowerBook G3's. If the X server starts without this
-// #define, you don't need it.
-#undef OLD_POWERBOOK_G3
-
-#include "darwin.h"
-#include "xfIOKit.h"
-
-// Globals
-int             xfIOKitScreenIndex = 0;
-io_connect_t    xfIOKitInputConnect = 0;
-
-static pthread_t                inputThread;
-static EvGlobals *              evg;
-static mach_port_t              masterPort;
-static mach_port_t              notificationPort;
-static IONotificationPortRef    NotificationPortRef;
-static mach_port_t              pmNotificationPort;
-static io_iterator_t            fbIter;
-
-
-/*
- * XFIOKitStoreColors
- * This is a callback from X to change the hardware colormap
- * when using PsuedoColor.
- */
-static void XFIOKitStoreColors(
-    ColormapPtr     pmap,
-    int             numEntries,
-    xColorItem      *pdefs)
-{
-    kern_return_t   kr;
-    int             i;
-    IOColorEntry    *newColors;
-    ScreenPtr       pScreen = pmap->pScreen;
-    XFIOKitScreenPtr iokitScreen = XFIOKIT_SCREEN_PRIV(pScreen);
-
-    assert( newColors = (IOColorEntry *)
-                xalloc( numEntries*sizeof(IOColorEntry) ));
-
-    // Convert xColorItem values to IOColorEntry
-    // assume the colormap is PsuedoColor
-    // as we do not support DirectColor
-    for (i = 0; i < numEntries; i++) {
-        newColors[i].index = pdefs[i].pixel;
-        newColors[i].red =   pdefs[i].red;
-        newColors[i].green = pdefs[i].green;
-        newColors[i].blue =  pdefs[i].blue;
-    }
-
-    kr = IOFBSetCLUT( iokitScreen->fbService, 0, numEntries,
-                      kSetCLUTByValue, newColors );
-    kern_assert( kr );
-
-    xfree( newColors );
-}
-
-
-/*
- * DarwinModeBell
- *  FIXME
- */
-void DarwinModeBell(
-    int             loud,
-    DeviceIntPtr    pDevice,
-    pointer         ctrl,
-    int             fbclass)
-{
-}
-
-
-/*
- * DarwinModeGiveUp
- *  Closes the connections to IOKit services
- */
-void DarwinModeGiveUp( void )
-{
-    int i;
-
-    // we must close the HID System first
-    // because it is a client of the framebuffer
-    NXCloseEventStatus( darwinParamConnect );
-    IOServiceClose( xfIOKitInputConnect );
-    for (i = 0; i < screenInfo.numScreens; i++) {
-        XFIOKitScreenPtr iokitScreen =
-                            XFIOKIT_SCREEN_PRIV(screenInfo.screens[i]);
-        IOServiceClose( iokitScreen->fbService );
-    }
-}
-
-
-/*
- * ClearEvent
- *  Clear an event from the HID System event queue
- */
-static void ClearEvent(NXEvent * ep)
-{
-    static NXEvent nullEvent = {NX_NULLEVENT, {0, 0 }, 0, -1, 0 };
-
-    *ep = nullEvent;
-    ep->data.compound.subType = ep->data.compound.misc.L[0] =
-                                ep->data.compound.misc.L[1] = 0;
-}
-
-
-/*
- * XFIOKitHIDThread
- *  Read the HID System event queue, translate it to an X event,
- *  and queue it for processing.
- */
-static void *XFIOKitHIDThread(void *unused)
-{
-    for (;;) {
-        NXEQElement             *oldHead;
-        mach_msg_return_t       kr;
-        mach_msg_empty_rcv_t    msg;
-
-        kr = mach_msg((mach_msg_header_t*) &msg, MACH_RCV_MSG, 0,
-                      sizeof(msg), notificationPort, 0, MACH_PORT_NULL);
-        kern_assert(kr);
-
-        while (evg->LLEHead != evg->LLETail) {
-            NXEvent ev;
-            xEvent xe;
-
-            // Extract the next event from the kernel queue
-            oldHead = (NXEQElement*)&evg->lleq[evg->LLEHead];
-            ev_lock(&oldHead->sema);
-            ev = oldHead->event;
-            ClearEvent(&oldHead->event);
-            evg->LLEHead = oldHead->next;
-            ev_unlock(&oldHead->sema);
-
-            memset(&xe, 0, sizeof(xe));
-
-            // These fields should be filled in for every event
-            xe.u.keyButtonPointer.rootX = ev.location.x;
-            xe.u.keyButtonPointer.rootY = ev.location.y;
-            xe.u.keyButtonPointer.time = GetTimeInMillis();
-
-            switch( ev.type ) {
-                case NX_MOUSEMOVED:
-                    xe.u.u.type = MotionNotify;
-                    break;
-
-                case NX_LMOUSEDOWN:
-                    xe.u.u.type = ButtonPress;
-                    xe.u.u.detail = 1;
-                    break;
-
-                case NX_LMOUSEUP:
-                    xe.u.u.type = ButtonRelease;
-                    xe.u.u.detail = 1;
-                    break;
-
-                // A newer kernel generates multi-button events with
-                // NX_SYSDEFINED. Button 2 isn't handled correctly by
-                // older kernels anyway. Just let NX_SYSDEFINED events
-                // handle these.
-#if 0
-                case NX_RMOUSEDOWN:
-                    xe.u.u.type = ButtonPress;
-                    xe.u.u.detail = 2;
-                    break;
-
-                case NX_RMOUSEUP:
-                    xe.u.u.type = ButtonRelease;
-                    xe.u.u.detail = 2;
-                    break;
-#endif
-
-                case NX_KEYDOWN:
-                    xe.u.u.type = KeyPress;
-                    xe.u.u.detail = ev.data.key.keyCode;
-                    break;
-
-                case NX_KEYUP:
-                    xe.u.u.type = KeyRelease;
-                    xe.u.u.detail = ev.data.key.keyCode;
-                    break;
-
-                case NX_FLAGSCHANGED:
-                    xe.u.u.type = kXDarwinUpdateModifiers;
-                    xe.u.clientMessage.u.l.longs0 = ev.flags;
-                    break;
-
-                case NX_SYSDEFINED:
-                    if (ev.data.compound.subType == 7) {
-                        xe.u.u.type = kXDarwinUpdateButtons;
-                        xe.u.clientMessage.u.l.longs0 =
-                                        ev.data.compound.misc.L[0];
-                        xe.u.clientMessage.u.l.longs1 =
-                                        ev.data.compound.misc.L[1];
-                    } else {
-                        continue;
-                    }
-                    break;
-
-                case NX_SCROLLWHEELMOVED:
-                    xe.u.u.type = kXDarwinScrollWheel;
-                    xe.u.clientMessage.u.s.shorts0 =
-                                    ev.data.scrollWheel.deltaAxis1;
-                    break;
-
-                default:
-                    continue;
-            }
-
-            DarwinEQEnqueue(&xe);
-        }
-    }
-
-    return NULL;
-}
-
-
-/*
- * XFIOKitPMThread
- *  Handle power state notifications
- */
-static void *XFIOKitPMThread(void *arg)
-{
-    ScreenPtr pScreen = (ScreenPtr)arg;
-    XFIOKitScreenPtr iokitScreen = XFIOKIT_SCREEN_PRIV(pScreen);
-
-    for (;;) {
-        mach_msg_return_t       kr;
-        mach_msg_empty_rcv_t    msg;
-
-        kr = mach_msg((mach_msg_header_t*) &msg, MACH_RCV_MSG, 0,
-                      sizeof(msg), pmNotificationPort, 0, MACH_PORT_NULL);
-        kern_assert(kr);
-
-        // display is powering down
-        if (msg.header.msgh_id == 0) {
-            IOFBAcknowledgePM( iokitScreen->fbService );
-            xf86SetRootClip(pScreen, FALSE);
-        }
-        // display just woke up
-        else if (msg.header.msgh_id == 1) {
-            xf86SetRootClip(pScreen, TRUE);
-        }
-    }
-    return NULL;
-}
-
-
-/*
- * SetupFBandHID
- *  Setup an IOFramebuffer service and connect the HID system to it.
- */
-static Bool SetupFBandHID(
-    int                    index,
-    DarwinFramebufferPtr   dfb,
-    XFIOKitScreenPtr       iokitScreen)
-{
-    kern_return_t           kr;
-    io_service_t            service;
-    io_connect_t            fbService;
-    vm_address_t            vram;
-    vm_size_t               shmemSize;
-    int                     i;
-    UInt32                  numModes;
-    IODisplayModeInformation modeInfo;
-    IODisplayModeID         displayMode, *allModes;
-    IOIndex                 displayDepth;
-    IOFramebufferInformation fbInfo;
-    IOPixelInformation      pixelInfo;
-    StdFBShmem_t            *cshmem;
-
-    // find and open the IOFrameBuffer service
-    service = IOIteratorNext(fbIter);
-    if (service == 0)
-        return FALSE;
-
-    kr = IOServiceOpen( service, mach_task_self(),
-                        kIOFBServerConnectType, &iokitScreen->fbService );
-    IOObjectRelease( service );
-    if (kr != KERN_SUCCESS) {
-        ErrorF("Failed to connect as window server to screen %i.\n", index);
-        return FALSE;
-    }
-    fbService = iokitScreen->fbService;
-
-    // create the slice of shared memory containing cursor state data
-    kr = IOFBCreateSharedCursor( fbService,
-                                 kIOFBCurrentShmemVersion,
-                                 32, 32 );
-    if (kr != KERN_SUCCESS)
-        return FALSE;
-
-    // Register for power management events for the framebuffer's device
-    kr = IOCreateReceivePort(kOSNotificationMessageID, &pmNotificationPort);
-    kern_assert(kr);
-    kr = IOConnectSetNotificationPort( fbService, 0,
-                                       pmNotificationPort, 0 );
-    if (kr != KERN_SUCCESS) {
-        ErrorF("Power management registration failed.\n");
-    }
-
-    // SET THE SCREEN PARAMETERS
-    // get the current screen resolution, refresh rate and depth
-    kr = IOFBGetCurrentDisplayModeAndDepth( fbService,
-                                            &displayMode,
-                                            &displayDepth );
-    if (kr != KERN_SUCCESS)
-        return FALSE;
-
-    // use the current screen resolution if the user
-    // only wants to change the refresh rate
-    if (darwinDesiredRefresh != -1 && darwinDesiredWidth == 0) {
-        kr = IOFBGetDisplayModeInformation( fbService,
-                                            displayMode,
-                                            &modeInfo );
-        if (kr != KERN_SUCCESS)
-            return FALSE;
-        darwinDesiredWidth = modeInfo.nominalWidth;
-        darwinDesiredHeight = modeInfo.nominalHeight;
-    }
-
-    // use the current resolution and refresh rate
-    // if the user doesn't have a preference
-    if (darwinDesiredWidth == 0) {
-
-        // change the pixel depth if desired
-        if (darwinDesiredDepth != -1) {
-            kr = IOFBGetDisplayModeInformation( fbService,
-                                                displayMode,
-                                                &modeInfo );
-            if (kr != KERN_SUCCESS)
-                return FALSE;
-            if (modeInfo.maxDepthIndex < darwinDesiredDepth) {
-                ErrorF("Discarding screen %i:\n", index);
-                ErrorF("Current screen resolution does not support desired pixel depth.\n");
-                return FALSE;
-            }
-
-            displayDepth = darwinDesiredDepth;
-            kr = IOFBSetDisplayModeAndDepth( fbService, displayMode,
-                                             displayDepth );
-            if (kr != KERN_SUCCESS)
-                return FALSE;
-        }
-
-    // look for display mode with correct resolution and refresh rate
-    } else {
-
-        // get an array of all supported display modes
-        kr = IOFBGetDisplayModeCount( fbService, &numModes );
-        if (kr != KERN_SUCCESS)
-            return FALSE;
-        assert(allModes = (IODisplayModeID *)
-                xalloc( numModes * sizeof(IODisplayModeID) ));
-        kr = IOFBGetDisplayModes( fbService, numModes, allModes );
-        if (kr != KERN_SUCCESS)
-            return FALSE;
-
-        for (i = 0; i < numModes; i++) {
-            kr = IOFBGetDisplayModeInformation( fbService, allModes[i],
-                                                &modeInfo );
-            if (kr != KERN_SUCCESS)
-                return FALSE;
-
-            if (modeInfo.flags & kDisplayModeValidFlag &&
-                modeInfo.nominalWidth == darwinDesiredWidth &&
-                modeInfo.nominalHeight == darwinDesiredHeight) {
-
-                if (darwinDesiredDepth == -1)
-                    darwinDesiredDepth = modeInfo.maxDepthIndex;
-                if (modeInfo.maxDepthIndex < darwinDesiredDepth) {
-                    ErrorF("Discarding screen %i:\n", index);
-                    ErrorF("Desired screen resolution does not support desired pixel depth.\n");
-                    return FALSE;
-                }
-
-                if ((darwinDesiredRefresh == -1 ||
-                    (darwinDesiredRefresh << 16) == modeInfo.refreshRate)) {
-                    displayMode = allModes[i];
-                    displayDepth = darwinDesiredDepth;
-                    kr = IOFBSetDisplayModeAndDepth(fbService,
-                                                    displayMode,
-                                                    displayDepth);
-                    if (kr != KERN_SUCCESS)
-                        return FALSE;
-                    break;
-                }
-            }
-        }
-
-        xfree( allModes );
-        if (i >= numModes) {
-            ErrorF("Discarding screen %i:\n", index);
-            ErrorF("Desired screen resolution or refresh rate is not supported.\n");
-            return FALSE;
-        }
-    }
-
-    kr = IOFBGetPixelInformation( fbService, displayMode, displayDepth,
-                                  kIOFBSystemAperture, &pixelInfo );
-    if (kr != KERN_SUCCESS)
-        return FALSE;
-
-#ifdef __i386__
-    /* x86 in 8bit mode currently needs fixed color map... */
-    if (pixelInfo.bitsPerComponent == 8 &&
-        pixelInfo.componentCount == 1)
-    {
-        pixelInfo.pixelType = kIOFixedCLUTPixels;
-    }
-#endif
-
-#ifdef OLD_POWERBOOK_G3
-    if (pixelInfo.pixelType == kIOCLUTPixels)
-        pixelInfo.pixelType = kIOFixedCLUTPixels;
-#endif
-
-    kr = IOFBGetFramebufferInformationForAperture( fbService,
-                                                   kIOFBSystemAperture,
-                                                   &fbInfo );
-    if (kr != KERN_SUCCESS)
-        return FALSE;
-
-    // FIXME: 1x1 IOFramebuffers are sometimes used to indicate video
-    // outputs without a monitor connected to them. Since IOKit Xinerama
-    // does not really work, this often causes problems on PowerBooks.
-    // For now we explicitly check and ignore these screens.
-    if (fbInfo.activeWidth <= 1 || fbInfo.activeHeight <= 1) {
-        ErrorF("Discarding screen %i:\n", index);
-        ErrorF("Invalid width or height.\n");
-        return FALSE;
-    }
-
-    kr = IOConnectMapMemory( fbService, kIOFBCursorMemory,
-                             mach_task_self(), (vm_address_t *) &cshmem,
-                             &shmemSize, kIOMapAnywhere );
-    if (kr != KERN_SUCCESS)
-        return FALSE;
-    iokitScreen->cursorShmem = cshmem;
-
-    kr = IOConnectMapMemory( fbService, kIOFBSystemAperture,
-                             mach_task_self(), &vram, &shmemSize,
-                             kIOMapAnywhere );
-    if (kr != KERN_SUCCESS)
-        return FALSE;
-
-    iokitScreen->framebuffer = (void*)vram;
-    dfb->x = cshmem->screenBounds.minx;
-    dfb->y = cshmem->screenBounds.miny;
-    dfb->width = fbInfo.activeWidth;
-    dfb->height = fbInfo.activeHeight;
-    dfb->pitch = fbInfo.bytesPerRow;
-    dfb->bitsPerPixel = fbInfo.bitsPerPixel;
-    dfb->colorBitsPerPixel = pixelInfo.componentCount *
-                             pixelInfo.bitsPerComponent;
-    dfb->bitsPerComponent = pixelInfo.bitsPerComponent;
-
-    // allocate shadow framebuffer
-    iokitScreen->shadowPtr = xalloc(dfb->pitch * dfb->height);
-    dfb->framebuffer = iokitScreen->shadowPtr;
-
-    // Note: Darwin kIORGBDirectPixels = X TrueColor, not DirectColor
-    if (pixelInfo.pixelType == kIORGBDirectPixels) {
-        dfb->colorType = TrueColor;
-    } else if (pixelInfo.pixelType == kIOCLUTPixels) {
-        dfb->colorType = PseudoColor;
-    } else if (pixelInfo.pixelType == kIOFixedCLUTPixels) {
-        dfb->colorType = StaticColor;
-    }
-
-    // Inform the HID system that the framebuffer is also connected to it.
-    kr = IOConnectAddClient( xfIOKitInputConnect, fbService );
-    kern_assert( kr );
-
-    // We have to have added at least one screen
-    // before we can enable the cursor.
-    kr = IOHIDSetCursorEnable(xfIOKitInputConnect, TRUE);
-    kern_assert( kr );
-
-    return TRUE;
-}
-
-
-/*
- * DarwinModeAddScreen
- *  IOKit specific initialization for each screen.
- */
-Bool DarwinModeAddScreen(
-    int index,
-    ScreenPtr pScreen)
-{
-    DarwinFramebufferPtr dfb = SCREEN_PRIV(pScreen);
-    XFIOKitScreenPtr iokitScreen;
-
-    // allocate space for private per screen storage
-    iokitScreen = xalloc(sizeof(XFIOKitScreenRec));
-    XFIOKIT_SCREEN_PRIV(pScreen) = iokitScreen;
-
-    // setup hardware framebuffer
-    iokitScreen->fbService = 0;
-    if (! SetupFBandHID(index, dfb, iokitScreen)) {
-        if (iokitScreen->fbService) {
-            IOServiceClose(iokitScreen->fbService);
-        }
-        return FALSE;
-    }
-
-    return TRUE;
-}
-
-
-/*
- * XFIOKitShadowUpdate
- *  Update the damaged regions of the shadow framebuffer on the screen.
- */
-static void XFIOKitShadowUpdate(ScreenPtr pScreen,
-                                shadowBufPtr pBuf)
-{
-    DarwinFramebufferPtr dfb = SCREEN_PRIV(pScreen);
-    XFIOKitScreenPtr iokitScreen = XFIOKIT_SCREEN_PRIV(pScreen);
-    RegionPtr damage = &pBuf->damage;
-    int numBox = REGION_NUM_RECTS(damage);
-    BoxPtr pBox = REGION_RECTS(damage);
-    int pitch = dfb->pitch;
-    int bpp = dfb->bitsPerPixel/8;
-
-    // Loop through all the damaged boxes
-    while (numBox--) {
-        int width, height, offset;
-        unsigned char *src, *dst;
-
-        width = (pBox->x2 - pBox->x1) * bpp;
-        height = pBox->y2 - pBox->y1;
-        offset = (pBox->y1 * pitch) + (pBox->x1 * bpp);
-        src = iokitScreen->shadowPtr + offset;
-        dst = iokitScreen->framebuffer + offset;
-
-        while (height--) {
-            memcpy(dst, src, width);
-            dst += pitch;
-            src += pitch;
-        }
-
-        // Get the next box
-        pBox++;
-    }
-}
-
-
-/*
- * DarwinModeSetupScreen
- *  Finalize IOKit specific initialization of each screen.
- */
-Bool DarwinModeSetupScreen(
-    int index,
-    ScreenPtr pScreen)
-{
-    DarwinFramebufferPtr dfb = SCREEN_PRIV(pScreen);
-    pthread_t pmThread;
-
-    // initalize cursor support
-    if (! XFIOKitInitCursor(pScreen)) {
-        return FALSE;
-    }
-
-    // initialize shadow framebuffer support
-    if (! shadowInit(pScreen, XFIOKitShadowUpdate, NULL)) {
-        ErrorF("Failed to initalize shadow framebuffer for screen %i.\n",
-               index);
-        return FALSE;
-    }
-
-    // initialize colormap handling as needed
-    if (dfb->colorType == PseudoColor) {
-        pScreen->StoreColors = XFIOKitStoreColors;
-    }
-
-    // initialize power manager handling
-    pthread_create( &pmThread, NULL, XFIOKitPMThread,
-                    (void *) pScreen );
-
-    return TRUE;
-}
-
-
-/*
- * DarwinModeInitOutput
- *  One-time initialization of IOKit output support.
- */
-void DarwinModeInitOutput(
-    int argc,
-    char **argv)
-{
-    static unsigned long    generation = 0;
-    kern_return_t           kr;
-    io_iterator_t           iter;
-    io_service_t            service;
-    vm_address_t            shmem;
-    vm_size_t               shmemSize;
-
-    ErrorF("Display mode: IOKit\n");
-
-    // Allocate private storage for each screen's IOKit specific info
-    if (generation != serverGeneration) {
-        xfIOKitScreenIndex = AllocateScreenPrivateIndex();
-        generation = serverGeneration;
-    }
-
-    kr = IOMasterPort(bootstrap_port, &masterPort);
-    kern_assert( kr );
-
-    // Find and open the HID System Service
-    // Do this now to be sure the Mac OS X window server is not running.
-    kr = IOServiceGetMatchingServices( masterPort,
-                                       IOServiceMatching( kIOHIDSystemClass ),
-                                       &iter );
-    kern_assert( kr );
-
-    assert( service = IOIteratorNext( iter ) );
-
-    kr = IOServiceOpen( service, mach_task_self(), kIOHIDServerConnectType,
-                        &xfIOKitInputConnect );
-    if (kr != KERN_SUCCESS) {
-        ErrorF("Failed to connect to the HID System as the window server!\n");
-#ifdef DARWIN_WITH_QUARTZ
-        FatalError("Quit the Mac OS X window server or use the -quartz option.\n");
-#else
-        FatalError("Make sure you have quit the Mac OS X window server.\n");
-#endif
-    }
-
-    IOObjectRelease( service );
-    IOObjectRelease( iter );
-
-    // Setup the event queue in memory shared by the kernel and X server
-    kr = IOHIDCreateSharedMemory( xfIOKitInputConnect,
-                                  kIOHIDCurrentShmemVersion );
-    kern_assert( kr );
-
-    kr = IOConnectMapMemory( xfIOKitInputConnect, kIOHIDGlobalMemory,
-                             mach_task_self(), &shmem, &shmemSize,
-                             kIOMapAnywhere );
-    kern_assert( kr );
-
-    evg = (EvGlobals *)(shmem + ((EvOffsets *)shmem)->evGlobalsOffset);
-
-    assert(sizeof(EvGlobals) == evg->structSize);
-
-    NotificationPortRef = IONotificationPortCreate( masterPort );
-
-    notificationPort = IONotificationPortGetMachPort(NotificationPortRef);
-
-    kr = IOConnectSetNotificationPort( xfIOKitInputConnect,
-                                       kIOHIDEventNotification,
-                                       notificationPort, 0 );
-    kern_assert( kr );
-
-    evg->movedMask |= NX_MOUSEMOVEDMASK;
-
-    // find number of framebuffers
-    kr = IOServiceGetMatchingServices( masterPort,
-                        IOServiceMatching( IOFRAMEBUFFER_CONFORMSTO ),
-                        &fbIter );
-    kern_assert( kr );
-
-    darwinScreensFound = 0;
-    while ((service = IOIteratorNext(fbIter))) {
-        IOObjectRelease( service );
-        darwinScreensFound++;
-    }
-    IOIteratorReset(fbIter);
-}
-
-
-/*
- * DarwinModeInitInput
- *  One-time initialization of IOKit input support.
- */
-void DarwinModeInitInput(
-    int argc,
-    char **argv)
-{
-    kern_return_t           kr;
-    int                     fd[2];
-
-    kr = IOHIDSetEventsEnable(xfIOKitInputConnect, TRUE);
-    kern_assert( kr );
-
-    // Start event passing thread
-    assert( pipe(fd) == 0 );
-    darwinEventReadFD = fd[0];
-    darwinEventWriteFD = fd[1];
-    fcntl(darwinEventReadFD, F_SETFL, O_NONBLOCK);
-    pthread_create(&inputThread, NULL,
-                   XFIOKitHIDThread, NULL);
-
-}
-
-
-/*
- * DarwinModeProcessEvent
- *  Process IOKit specific events.
- */
-void DarwinModeProcessEvent(
-    xEvent *xe)
-{
-    // No mode specific events
-    ErrorF("Unknown X event caught: %d\n", xe->u.u.type);
-}
diff --git a/hw/darwin/iokit/xfIOKit.h b/hw/darwin/iokit/xfIOKit.h
deleted file mode 100644
index 27d27bc..0000000
--- a/hw/darwin/iokit/xfIOKit.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
-  xfIOKit.h
-
-  IOKit specific functions and definitions
-*/
-/*
- * Copyright (c) 2001-2002 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, 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 _XFIOKIT_H
-#define _XFIOKIT_H
-
-#include <pthread.h>
-#include <IOKit/graphics/IOFramebufferShared.h>
-#include <X11/Xproto.h>
-#include "screenint.h"
-#include "darwin.h"
-
-typedef struct {
-    io_connect_t        fbService;
-    StdFBShmem_t       *cursorShmem;
-    unsigned char      *framebuffer;
-    unsigned char      *shadowPtr;
-} XFIOKitScreenRec, *XFIOKitScreenPtr;
-
-#define XFIOKIT_SCREEN_PRIV(pScreen) \
-    ((XFIOKitScreenPtr)pScreen->devPrivates[xfIOKitScreenIndex].ptr)
-
-extern int xfIOKitScreenIndex; // index into pScreen.devPrivates
-extern io_connect_t xfIOKitInputConnect;
-
-Bool XFIOKitInitCursor(ScreenPtr pScreen);
-
-#endif	/* _XFIOKIT_H */
diff --git a/hw/darwin/iokit/xfIOKitCursor.c b/hw/darwin/iokit/xfIOKitCursor.c
deleted file mode 100644
index 8388513..0000000
--- a/hw/darwin/iokit/xfIOKitCursor.c
+++ /dev/null
@@ -1,737 +0,0 @@
-/**************************************************************
- *
- * Cursor support for Darwin X Server
- *
- * Three different cursor modes are possible:
- *  X (0)         - tracking via Darwin kernel,
- *                  display via X machine independent
- *  Kernel (1)    - tracking and display via Darwin kernel
- *                  (not currently supported)
- *  Hardware (2)  - tracking and display via hardware
- *
- * The X software cursor uses the Darwin software cursor
- * routines in IOFramebuffer.cpp to track the cursor, but
- * displays the cursor image using the X machine
- * independent display cursor routines in midispcur.c.
- *
- * The kernel cursor uses IOFramebuffer.cpp routines to
- * track and display the cursor. This gives better
- * performance as the display calls don't have to cross
- * the kernel boundary. Unfortunately, this mode has
- * synchronization issues with the user land X server
- * and isn't currently used.
- *
- * Hardware cursor support lets the hardware handle these
- * details.
- *
- * Kernel and hardware cursor mode only work for cursors
- * up to a certain size, currently 16x16 pixels. If a
- * bigger cursor is set, we fallback to X cursor mode.
- *
- * HISTORY:
- * 1.0 by Torrey T. Lyons, October 30, 2000
- *
- **************************************************************/
-/*
- * Copyright (c) 2001-2002 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, 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.
- */
-
-#if HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-#include "scrnintstr.h"
-#include "cursorstr.h"
-#include "mipointrst.h"
-#include "micmap.h"
-#define NO_CFPLUGIN
-#include <IOKit/graphics/IOGraphicsLib.h>
-#include <IOKit/hidsystem/IOHIDLib.h>
-#include "darwin.h"
-#include "xfIOKit.h"
-#include <assert.h>
-#define DUMP_DARWIN_CURSOR FALSE
-
-#define CURSOR_PRIV(pScreen) \
-    ((XFIOKitCursorScreenPtr)pScreen->devPrivates[darwinCursorScreenIndex].ptr)
-
-// The cursors format are documented in IOFramebufferShared.h.
-#define RGBto34WithGamma(red, green, blue)  \
-    (  0x000F                               \
-     | (((red) & 0xF) << 12)                \
-     | (((green) & 0xF) << 8)               \
-     | (((blue) & 0xF) << 4) )
-#define RGBto38WithGamma(red, green, blue)  \
-    (  0xFF << 24                           \
-     | (((red) & 0xFF) << 16)               \
-     | (((green) & 0xFF) << 8)              \
-     | (((blue) & 0xFF)) )
-#define HighBitOf32 0x80000000
-
-typedef struct {
-    Bool                    canHWCursor;
-    short                   cursorMode;
-    RecolorCursorProcPtr    RecolorCursor;
-    InstallColormapProcPtr  InstallColormap;
-    QueryBestSizeProcPtr    QueryBestSize;
-    miPointerSpriteFuncPtr  spriteFuncs;
-    ColormapPtr             pInstalledMap;
-} XFIOKitCursorScreenRec, *XFIOKitCursorScreenPtr;
-
-static int darwinCursorScreenIndex = -1;
-static unsigned long darwinCursorGeneration = 0;
-
-/*
-===========================================================================
-
- Pointer sprite functions
-
-===========================================================================
-*/
-
-/*
-    Realizing the Darwin hardware cursor (ie. converting from the
-    X representation to the IOKit representation) is complicated
-    by the fact that we have three different potential cursor
-    formats to go to, one for each bit depth (8, 15, or 24).
-    The IOKit formats are documented in IOFramebufferShared.h.
-    X cursors are represented as two pieces, a source and a mask.
-    The mask is a bitmap indicating which parts of the cursor are 
-    transparent and which parts are drawn.  The source is a bitmap
-    indicating which parts of the non-transparent portion of the the
-    cursor should be painted in the foreground color and which should
-    be painted in the background color. The bitmaps are given in
-    32-bit format with least significant byte and bit first.
-    (This is opposite PowerPC Darwin.)
-*/
-
-typedef struct {
-    unsigned char image[CURSORWIDTH*CURSORHEIGHT];
-    unsigned char mask[CURSORWIDTH*CURSORHEIGHT];
-} cursorPrivRec, *cursorPrivPtr;
-
-/*
- * XFIOKitRealizeCursor8
- * Convert the X cursor representation to an 8-bit depth
- * format for Darwin. This function assumes the maximum cursor
- * width is a multiple of 8.
- */
-static Bool
-XFIOKitRealizeCursor8(
-    ScreenPtr pScreen,
-    CursorPtr pCursor)
-{
-    cursorPrivPtr   newCursor;
-    unsigned char   *newSourceP, *newMaskP;
-    CARD32          *oldSourceP, *oldMaskP;
-    xColorItem      fgColor, bgColor;
-    int             index, x, y, rowPad;
-    int             cursorWidth, cursorHeight;
-    ColormapPtr     pmap;
-
-    // check cursor size just to be sure
-    cursorWidth = pCursor->bits->width;
-    cursorHeight = pCursor->bits->height;
-    if (cursorHeight > CURSORHEIGHT || cursorWidth > CURSORWIDTH)
-        return FALSE;
-
-    // get cursor colors in colormap
-    index = pScreen->myNum;
-    pmap = miInstalledMaps[index];
-    if (!pmap) return FALSE;
-
-    fgColor.red = pCursor->foreRed;
-    fgColor.green = pCursor->foreGreen;
-    fgColor.blue = pCursor->foreBlue;
-    FakeAllocColor(pmap, &fgColor);
-    bgColor.red = pCursor->backRed;
-    bgColor.green = pCursor->backGreen;
-    bgColor.blue = pCursor->backBlue;
-    FakeAllocColor(pmap, &bgColor);
-    FakeFreeColor(pmap, fgColor.pixel);
-    FakeFreeColor(pmap, bgColor.pixel);
-
-    // allocate memory for new cursor image
-    newCursor = xalloc( sizeof(cursorPrivRec) );
-    if (!newCursor)
-        return FALSE;
-    memset( newCursor->image, pScreen->blackPixel, CURSORWIDTH*CURSORHEIGHT );
-    memset( newCursor->mask, 0, CURSORWIDTH*CURSORHEIGHT );
-
-    // convert to 8-bit Darwin cursor format
-    oldSourceP = (CARD32 *) pCursor->bits->source;
-    oldMaskP = (CARD32 *) pCursor->bits->mask;
-    newSourceP = newCursor->image;
-    newMaskP = newCursor->mask;
-    rowPad = CURSORWIDTH - cursorWidth;
-
-    for (y = 0; y < cursorHeight; y++) {
-        for (x = 0; x < cursorWidth; x++) {
-            if (*oldSourceP & (HighBitOf32 >> x))
-                *newSourceP = fgColor.pixel;
-            else
-                *newSourceP = bgColor.pixel;
-            if (*oldMaskP & (HighBitOf32 >> x))
-                *newMaskP = 255;
-            else
-                *newSourceP = pScreen->blackPixel;
-            newSourceP++; newMaskP++;
-        }
-        oldSourceP++; oldMaskP++;
-        newSourceP += rowPad; newMaskP += rowPad;
-    }
-
-    // save the result
-    pCursor->devPriv[pScreen->myNum] = (pointer) newCursor;
-    return TRUE;
-}
-
-
-/*
- * XFIOKitRealizeCursor15
- * Convert the X cursor representation to an 15-bit depth
- * format for Darwin.
- */
-static Bool
-XFIOKitRealizeCursor15(
-    ScreenPtr       pScreen,
-    CursorPtr       pCursor)
-{
-    unsigned short  *newCursor;
-    unsigned short  fgPixel, bgPixel;
-    unsigned short  *newSourceP;
-    CARD32          *oldSourceP, *oldMaskP;
-    int             x, y, rowPad;
-    int             cursorWidth, cursorHeight;
-
-    // check cursor size just to be sure
-    cursorWidth = pCursor->bits->width;
-    cursorHeight = pCursor->bits->height;
-    if (cursorHeight > CURSORHEIGHT || cursorWidth > CURSORWIDTH)
-       return FALSE;
-
-    // allocate memory for new cursor image
-    newCursor = xalloc( CURSORWIDTH*CURSORHEIGHT*sizeof(short) );
-    if (!newCursor)
-        return FALSE;
-    memset( newCursor, 0, CURSORWIDTH*CURSORHEIGHT*sizeof(short) );
-
-    // calculate pixel values
-    fgPixel = RGBto34WithGamma( pCursor->foreRed, pCursor->foreGreen,
-                                pCursor->foreBlue );
-    bgPixel = RGBto34WithGamma( pCursor->backRed, pCursor->backGreen,
-                                pCursor->backBlue );
-
-    // convert to 15-bit Darwin cursor format
-    oldSourceP = (CARD32 *) pCursor->bits->source;
-    oldMaskP = (CARD32 *) pCursor->bits->mask;
-    newSourceP = newCursor;
-    rowPad = CURSORWIDTH - cursorWidth;
-
-    for (y = 0; y < cursorHeight; y++) {
-        for (x = 0; x < cursorWidth; x++) {
-            if (*oldMaskP & (HighBitOf32 >> x)) {
-                if (*oldSourceP & (HighBitOf32 >> x))
-                    *newSourceP = fgPixel;
-                else
-                    *newSourceP = bgPixel;
-            } else {
-                *newSourceP = 0;
-            }
-            newSourceP++;
-        }
-        oldSourceP++; oldMaskP++;
-        newSourceP += rowPad;
-    }
-
-#if DUMP_DARWIN_CURSOR
-    // Write out the cursor
-    ErrorF("Cursor: 0x%x\n", pCursor);
-    ErrorF("Width = %i, Height = %i, RowPad = %i\n", cursorWidth,
-            cursorHeight, rowPad);
-    for (y = 0; y < cursorHeight; y++) {
-        newSourceP = newCursor + y*CURSORWIDTH;
-        for (x = 0; x < cursorWidth; x++) {
-            if (*newSourceP == fgPixel)
-                ErrorF("x");
-            else if (*newSourceP == bgPixel)
-                ErrorF("o");
-            else
-                ErrorF(" ");
-            newSourceP++;
-        }
-        ErrorF("\n");
-    }
-#endif
-
-    // save the result
-    pCursor->devPriv[pScreen->myNum] = (pointer) newCursor;
-    return TRUE;
-}
-
-
-/*
- * XFIOKitRealizeCursor24
- * Convert the X cursor representation to an 24-bit depth
- * format for Darwin. This function assumes the maximum cursor
- * width is a multiple of 8.
- */
-static Bool
-XFIOKitRealizeCursor24(
-    ScreenPtr       pScreen,
-    CursorPtr       pCursor)
-{
-    unsigned int    *newCursor;
-    unsigned int    fgPixel, bgPixel;
-    unsigned int    *newSourceP;
-    CARD32          *oldSourceP, *oldMaskP;
-    int             x, y, rowPad;
-    int             cursorWidth, cursorHeight;
-
-    // check cursor size just to be sure
-    cursorWidth = pCursor->bits->width;
-    cursorHeight = pCursor->bits->height;
-    if (cursorHeight > CURSORHEIGHT || cursorWidth > CURSORWIDTH)
-       return FALSE;
-
-    // allocate memory for new cursor image
-    newCursor = xalloc( CURSORWIDTH*CURSORHEIGHT*sizeof(int) );
-    if (!newCursor)
-        return FALSE;
-    memset( newCursor, 0, CURSORWIDTH*CURSORHEIGHT*sizeof(int) );
-
-    // calculate pixel values
-    fgPixel = RGBto38WithGamma( pCursor->foreRed, pCursor->foreGreen,
-                                pCursor->foreBlue );
-    bgPixel = RGBto38WithGamma( pCursor->backRed, pCursor->backGreen,
-                                pCursor->backBlue );
-
-    // convert to 24-bit Darwin cursor format
-    oldSourceP = (CARD32 *) pCursor->bits->source;
-    oldMaskP = (CARD32 *) pCursor->bits->mask;
-    newSourceP = newCursor;
-    rowPad = CURSORWIDTH - cursorWidth;
-
-    for (y = 0; y < cursorHeight; y++) {
-        for (x = 0; x < cursorWidth; x++) {
-            if (*oldMaskP & (HighBitOf32 >> x)) {
-                if (*oldSourceP & (HighBitOf32 >> x))
-                    *newSourceP = fgPixel;
-                else
-                    *newSourceP = bgPixel;
-            } else {
-                *newSourceP = 0;
-            }
-            newSourceP++;
-        }
-        oldSourceP++; oldMaskP++;
-        newSourceP += rowPad;
-    }
-
-#if DUMP_DARWIN_CURSOR
-    // Write out the cursor
-    ErrorF("Cursor: 0x%x\n", pCursor);
-    ErrorF("Width = %i, Height = %i, RowPad = %i\n", cursorWidth,
-            cursorHeight, rowPad);
-    for (y = 0; y < cursorHeight; y++) {
-        newSourceP = newCursor + y*CURSORWIDTH;
-        for (x = 0; x < cursorWidth; x++) {
-            if (*newSourceP == fgPixel)
-                ErrorF("x");
-            else if (*newSourceP == bgPixel)
-                ErrorF("o");
-            else
-                ErrorF(" ");
-            newSourceP++;
-        }
-        ErrorF("\n");
-    }
-#endif
-
-    // save the result
-    pCursor->devPriv[pScreen->myNum] = (pointer) newCursor;
-    return TRUE;
-}
-
-
-/*
- * XFIOKitRealizeCursor
- * 
- */
-static Bool
-XFIOKitRealizeCursor(
-    ScreenPtr       pScreen,
-    CursorPtr       pCursor)
-{
-    Bool                        result;
-    XFIOKitCursorScreenPtr      ScreenPriv = CURSOR_PRIV(pScreen);
-    DarwinFramebufferPtr        dfb = SCREEN_PRIV(pScreen);
-
-    if ((pCursor->bits->height > CURSORHEIGHT) ||
-        (pCursor->bits->width > CURSORWIDTH) ||
-        // FIXME: this condition is not needed after kernel cursor works
-        !ScreenPriv->canHWCursor) {
-        result = (*ScreenPriv->spriteFuncs->RealizeCursor)(pScreen, pCursor);
-    } else if (dfb->bitsPerPixel == 8) {
-        result = XFIOKitRealizeCursor8(pScreen, pCursor);
-    } else if (dfb->bitsPerPixel == 16) {
-        result = XFIOKitRealizeCursor15(pScreen, pCursor);
-    } else {
-        result = XFIOKitRealizeCursor24(pScreen, pCursor);
-    }
-
-    return result;
-}
-
-
-/*
- * XFIOKitUnrealizeCursor
- * 
- */
-static Bool
-XFIOKitUnrealizeCursor(
-    ScreenPtr pScreen,
-    CursorPtr pCursor)
-{
-    Bool                        result;
-    XFIOKitCursorScreenPtr      ScreenPriv = CURSOR_PRIV(pScreen);
-
-    if ((pCursor->bits->height > CURSORHEIGHT) ||
-        (pCursor->bits->width > CURSORWIDTH) ||
-        // FIXME: this condition is not needed after kernel cursor works
-        !ScreenPriv->canHWCursor) {
-        result = (*ScreenPriv->spriteFuncs->UnrealizeCursor)(pScreen, pCursor);
-    } else {
-        xfree( pCursor->devPriv[pScreen->myNum] );
-        result = TRUE;
-    }
-
-    return result;
-}
-
-
-/*
- * XFIOKitSetCursor
- * Set the cursor sprite and position
- * Use hardware cursor if possible
- */
-static void
-XFIOKitSetCursor(
-    ScreenPtr       pScreen,
-    CursorPtr       pCursor,
-    int             x,
-    int             y)
-{
-    kern_return_t               kr;
-    DarwinFramebufferPtr        dfb = SCREEN_PRIV(pScreen);
-    XFIOKitScreenPtr            iokitScreen = XFIOKIT_SCREEN_PRIV(pScreen);
-    StdFBShmem_t                *cshmem = iokitScreen->cursorShmem;
-    XFIOKitCursorScreenPtr      ScreenPriv = CURSOR_PRIV(pScreen);
-
-    // are we supposed to remove the cursor?
-    if (!pCursor) {
-        if (ScreenPriv->cursorMode == 0)
-            (*ScreenPriv->spriteFuncs->SetCursor)(pScreen, 0, x, y);
-        else {
-            if (!cshmem->cursorShow) {
-                cshmem->cursorShow++;
-                if (cshmem->hardwareCursorActive) {
-                    kr = IOFBSetCursorVisible(iokitScreen->fbService, FALSE);
-                    kern_assert( kr );
-                }
-            }
-        }
-        return;
-    } 
- 
-    // can we use the kernel or hardware cursor?
-    if ((pCursor->bits->height <= CURSORHEIGHT) &&
-        (pCursor->bits->width <= CURSORWIDTH) &&
-        // FIXME: condition not needed when kernel cursor works
-        ScreenPriv->canHWCursor) {
-
-        if (ScreenPriv->cursorMode == 0)    // remove the X cursor
-            (*ScreenPriv->spriteFuncs->SetCursor)(pScreen, 0, x, y);
-        ScreenPriv->cursorMode = 1;         // kernel cursor
-
-        // change the cursor image in shared memory
-        if (dfb->bitsPerPixel == 8) {
-            cursorPrivPtr newCursor =
-                    (cursorPrivPtr) pCursor->devPriv[pScreen->myNum];
-            memcpy(cshmem->cursor.bw8.image[0], newCursor->image,
-                        CURSORWIDTH*CURSORHEIGHT);
-            memcpy(cshmem->cursor.bw8.mask[0], newCursor->mask,
-                        CURSORWIDTH*CURSORHEIGHT);
-        } else if (dfb->bitsPerPixel == 16) {
-            unsigned short *newCursor =
-                    (unsigned short *) pCursor->devPriv[pScreen->myNum];
-            memcpy(cshmem->cursor.rgb.image[0], newCursor,
-                        2*CURSORWIDTH*CURSORHEIGHT);
-        } else {
-            unsigned int *newCursor =
-                    (unsigned int *) pCursor->devPriv[pScreen->myNum];
-            memcpy(cshmem->cursor.rgb24.image[0], newCursor,
-                        4*CURSORWIDTH*CURSORHEIGHT);
-        }
-
-        // FIXME: We always use a full size cursor, even if the image
-        // is smaller because I couldn't get the padding to come out
-        // right otherwise.
-        cshmem->cursorSize[0].width = CURSORWIDTH;
-        cshmem->cursorSize[0].height = CURSORHEIGHT;
-        cshmem->hotSpot[0].x = pCursor->bits->xhot;
-        cshmem->hotSpot[0].y = pCursor->bits->yhot;
-
-        // try to use a hardware cursor
-        if (ScreenPriv->canHWCursor) {
-            kr = IOFBSetNewCursor(iokitScreen->fbService, 0, 0, 0);
-            // FIXME: this is a fatal error without the kernel cursor
-            kern_assert( kr );
-#if 0
-            if (kr != KERN_SUCCESS) {
-                ErrorF("Could not set new cursor with kernel return 0x%x.\n", kr);
-                ScreenPriv->canHWCursor = FALSE;
-            }
-#endif
-        }
-
-        // make the new cursor visible
-        if (cshmem->cursorShow)
-            cshmem->cursorShow--;
-
-        if (!cshmem->cursorShow && ScreenPriv->canHWCursor) {
-            kr = IOFBSetCursorVisible(iokitScreen->fbService, TRUE);
-            // FIXME: this is a fatal error without the kernel cursor
-            kern_assert( kr );
-#if 0
-            if (kr != KERN_SUCCESS) {
-                ErrorF("Couldn't set hardware cursor visible with kernel return 0x%x.\n", kr);
-                ScreenPriv->canHWCursor = FALSE;
-            } else
-#endif
-                ScreenPriv->cursorMode = 2;     // hardware cursor
-        }
-
-	return; 
-    }
-
-    // otherwise we use a software cursor
-    if (ScreenPriv->cursorMode) {
-        /* remove the kernel or hardware cursor */
-        XFIOKitSetCursor(pScreen, 0, x, y);
-    }
-
-    ScreenPriv->cursorMode = 0;
-    (*ScreenPriv->spriteFuncs->SetCursor)(pScreen, pCursor, x, y);
-}
-
-
-/*
- * XFIOKitMoveCursor
- * Move the cursor. This is a noop for a kernel or hardware cursor.
- */
-static void
-XFIOKitMoveCursor(
-    ScreenPtr   pScreen,
-    int         x,
-    int         y)
-{
-    XFIOKitCursorScreenPtr ScreenPriv = CURSOR_PRIV(pScreen);
-
-    // only the X cursor needs to be explicitly moved
-    if (!ScreenPriv->cursorMode)
-        (*ScreenPriv->spriteFuncs->MoveCursor)(pScreen, x, y);
-}
-
-static miPointerSpriteFuncRec darwinSpriteFuncsRec = {
-    XFIOKitRealizeCursor,
-    XFIOKitUnrealizeCursor,
-    XFIOKitSetCursor,
-    XFIOKitMoveCursor
-};
-
-
-/*
-===========================================================================
-
- Pointer screen functions
-
-===========================================================================
-*/
-
-/*
- * XFIOKitCursorOffScreen
- */
-static Bool XFIOKitCursorOffScreen(ScreenPtr *pScreen, int *x, int *y)
-{	return FALSE;
-}
-
-
-/*
- * XFIOKitCrossScreen
- */
-static void XFIOKitCrossScreen(ScreenPtr pScreen, Bool entering)
-{	return;
-}
-
-
-/*
- * XFIOKitWarpCursor
- * Change the cursor position without generating an event or motion history
- */
-static void
-XFIOKitWarpCursor(
-    ScreenPtr               pScreen,
-    int                     x,
-    int                     y)
-{
-    kern_return_t           kr;
-
-    kr = IOHIDSetMouseLocation( xfIOKitInputConnect, x, y );
-    if (kr != KERN_SUCCESS) {
-        ErrorF("Could not set cursor position with kernel return 0x%x.\n", kr);
-    }
-    miPointerWarpCursor(pScreen, x, y);
-}
-
-static miPointerScreenFuncRec darwinScreenFuncsRec = {
-  XFIOKitCursorOffScreen,
-  XFIOKitCrossScreen,
-  XFIOKitWarpCursor,
-  DarwinEQPointerPost,
-  DarwinEQSwitchScreen
-};
-
-
-/*
-===========================================================================
-
- Other screen functions
-
-===========================================================================
-*/
-
-/*
- * XFIOKitCursorQueryBestSize
- * Handle queries for best cursor size
- */
-static void
-XFIOKitCursorQueryBestSize(
-   int              class, 
-   unsigned short   *width,
-   unsigned short   *height,
-   ScreenPtr        pScreen)
-{
-    XFIOKitCursorScreenPtr ScreenPriv = CURSOR_PRIV(pScreen);
-
-    if (class == CursorShape) {
-        *width = CURSORWIDTH;
-        *height = CURSORHEIGHT;
-    } else
-        (*ScreenPriv->QueryBestSize)(class, width, height, pScreen);
-}
-
-
-/*
- * XFIOKitInitCursor
- * Initialize cursor support
- */
-Bool 
-XFIOKitInitCursor(
-    ScreenPtr	pScreen)
-{
-    XFIOKitScreenPtr        iokitScreen = XFIOKIT_SCREEN_PRIV(pScreen);
-    XFIOKitCursorScreenPtr  ScreenPriv;
-    miPointerScreenPtr	    PointPriv;
-    kern_return_t           kr;
-
-    // start with no cursor displayed
-    if (!iokitScreen->cursorShmem->cursorShow++) {
-        if (iokitScreen->cursorShmem->hardwareCursorActive) {
-            kr = IOFBSetCursorVisible(iokitScreen->fbService, FALSE);
-            kern_assert( kr );
-        }
-    }
-
-    // initialize software cursor handling (always needed as backup)
-    if (!miDCInitialize(pScreen, &darwinScreenFuncsRec)) {
-        return FALSE;
-    }
-
-    // allocate private storage for this screen's hardware cursor info
-    if (darwinCursorGeneration != serverGeneration) {
-        if ((darwinCursorScreenIndex = AllocateScreenPrivateIndex()) < 0)
-            return FALSE;
-        darwinCursorGeneration = serverGeneration; 	
-    }
-
-    ScreenPriv = xcalloc( 1, sizeof(XFIOKitCursorScreenRec) );
-    if (!ScreenPriv) return FALSE;
-
-    pScreen->devPrivates[darwinCursorScreenIndex].ptr = (pointer) ScreenPriv;
-
-    // check if a hardware cursor is supported
-    if (!iokitScreen->cursorShmem->hardwareCursorCapable) {
-        ScreenPriv->canHWCursor = FALSE;
-        ErrorF("Hardware cursor not supported.\n");
-    } else {
-        // we need to make sure that the hardware cursor really works
-        ScreenPriv->canHWCursor = TRUE;
-        kr = IOFBSetNewCursor(iokitScreen->fbService, 0, 0, 0);
-        if (kr != KERN_SUCCESS) {
-            ErrorF("Could not set hardware cursor with kernel return 0x%x.\n", kr);
-            ScreenPriv->canHWCursor = FALSE;
-        }
-        kr = IOFBSetCursorVisible(iokitScreen->fbService, TRUE);
-        if (kr != KERN_SUCCESS) {
-            ErrorF("Couldn't set hardware cursor visible with kernel return 0x%x.\n", kr);
-            ScreenPriv->canHWCursor = FALSE;
-        }
-        IOFBSetCursorVisible(iokitScreen->fbService, FALSE);
-    }
-
-    ScreenPriv->cursorMode = 0;
-    ScreenPriv->pInstalledMap = NULL;
-
-    // override some screen procedures
-    ScreenPriv->QueryBestSize = pScreen->QueryBestSize;
-    pScreen->QueryBestSize = XFIOKitCursorQueryBestSize;
-//    ScreenPriv->ConstrainCursor = pScreen->ConstrainCursor;
-//    pScreen->ConstrainCursor = XFIOKitConstrainCursor;
-
-    // initialize hardware cursor handling
-    PointPriv = (miPointerScreenPtr)
-                    pScreen->devPrivates[miPointerScreenIndex].ptr;
-
-    ScreenPriv->spriteFuncs = PointPriv->spriteFuncs;
-    PointPriv->spriteFuncs = &darwinSpriteFuncsRec; 
-
-    /* Other routines that might be overridden */
-/*
-    CursorLimitsProcPtr		CursorLimits;
-    RecolorCursorProcPtr	RecolorCursor;
-*/
-
-    return TRUE;
-}
diff --git a/hw/darwin/iokit/xfIOKitStartup.c b/hw/darwin/iokit/xfIOKitStartup.c
deleted file mode 100644
index 413d062..0000000
--- a/hw/darwin/iokit/xfIOKitStartup.c
+++ /dev/null
@@ -1,133 +0,0 @@
-/**************************************************************
- *
- * Startup code for the IOKit Darwin X Server
- *
- **************************************************************/
-/*
- * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, 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.
- */
-
-#if HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "darwin.h"
-#include "darwinKeyboard.h"
-#include "micmap.h"
-
-void GlxExtensionInit(void);
-void GlxWrapInitVisuals(miInitVisualsProcPtr *procPtr);
-
-
-/*
- * DarwinHandleGUI
- *  This function is called first from main().
- *  It does nothing for the IOKit X server.
- */
-void DarwinHandleGUI(
-    int         argc,
-    char        *argv[],
-    char        *envp[] )
-{
-}
-
-
-/*
- * DarwinGlxExtensionInit
- *  Initialize the GLX extension.
- *  Mesa is linked into the IOKit mode X server so we just call directly.
- */
-void DarwinGlxExtensionInit(void)
-{
-#ifdef GLXEXT
-    	GlxExtensionInit();
-#endif
-}
-
-
-/*
- * DarwinGlxWrapInitVisuals
- */
-void DarwinGlxWrapInitVisuals(
-    miInitVisualsProcPtr *procPtr)
-{
-#ifdef GLXEXT
-    GlxWrapInitVisuals(procPtr);
-#endif
-}
-
-
-/*
- * DarwinModeProcessArgument
- *  Process IOKit specific command line arguments.
- */
-int DarwinModeProcessArgument(
-    int argc,
-    char *argv[],
-    int i)
-{
-#ifdef DARWIN_WITH_QUARTZ
-    // XDarwinStartup uses these arguments to indicate which X server
-    // should be started. Ignore them here.
-    if (!strcmp( argv[i], "-fullscreen" ) ||
-        !strcmp( argv[i], "-rootless" ) ||
-        !strcmp( argv[i], "-quartz" ))
-    {
-        return 1;
-    }
-#else
-    if (!strcmp( argv[i], "-fullscreen" ) ||
-        !strcmp( argv[i], "-rootless" ) ||
-        !strcmp( argv[i], "-quartz" ))
-    {
-        FatalError("Command line option %s is not available without Quartz "
-                   "support.\n", argv[i]);
-    }
-#endif
-
-    return 0;
-}
-
-
-/*
- * DarwinModeSystemKeymapSeed
- *  Changes to NXKeyMapping are not tracked.
- */
-unsigned int
-DarwinModeSystemKeymapSeed(void)
-{
-    return 0;
-}
-
-
-/*
- * DarwinModeReadSystemKeymap
- *  IOKit has no alternative to NXKeyMapping API.
- */
-Bool DarwinModeReadSystemKeymap(
-    darwinKeyboardInfo *info)
-{
-    return FALSE;
-}
diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
index 838af29..44b52e7 100644
--- a/hw/darwin/quartz/Makefile.am
+++ b/hw/darwin/quartz/Makefile.am
@@ -2,13 +2,13 @@ noinst_LIBRARIES = libXQuartz.a
 
 AM_CFLAGS = @XORG_CFLAGS@
 AM_OBJCFLAGS = @XORG_CFLAGS@
-AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../apple -I$(top_srcdir)/miext/rootless @XORG_INCS@ -DXBINDIR=\"${bindir}\" -DHAS_KL_API -DHAVE_XORG_CONFIG_H
+AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/.. -I$(top_srcdir)/miext/rootless @XORG_INCS@ -DXBINDIR=\"${bindir}\" -DHAS_KL_API -DHAVE_XORG_CONFIG_H
 
 SUBDIRS = cr fullscreen xpr
 
 libXQuartz_a_SOURCES = \
-		  ../apple/X11Application.m \
-		  ../apple/X11Controller.m \
+		  X11Application.m \
+		  X11Controller.m \
 	          applewm.c \
 	          keysym2ucs.c \
 	          pseudoramiX.c \
diff --git a/hw/darwin/quartz/Preferences.h b/hw/darwin/quartz/Preferences.h
deleted file mode 100644
index cf43758..0000000
--- a/hw/darwin/quartz/Preferences.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (c) 2002-2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, 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.
- */
-
-#import <Cocoa/Cocoa.h>
-
- at interface Preferences : NSObject
-{
-    IBOutlet NSPanel *window;
-    IBOutlet id displayField;
-    IBOutlet id dockSwitchButton;
-    IBOutlet id fakeButton;
-    IBOutlet id button2ModifiersMatrix;
-    IBOutlet id button3ModifiersMatrix;
-    IBOutlet id switchKeyButton;
-    IBOutlet id keymapFileField;
-    IBOutlet id modeMatrix;
-    IBOutlet id modeWindowButton;
-    IBOutlet id startupHelpButton;
-    IBOutlet id systemBeepButton;
-    IBOutlet id mouseAccelChangeButton;
-    IBOutlet id useXineramaButton;
-    IBOutlet id addToPathButton;
-    IBOutlet id addToPathField;
-    IBOutlet id useDefaultShellMatrix;
-    IBOutlet id useOtherShellField;
-    IBOutlet id depthButton;
-
-    BOOL isGettingKeyCode;
-    int keyCode;
-    int modifiers;
-    NSMutableString *switchString;
-}
-
-- (IBAction)close:(id)sender;
-- (IBAction)pickFile:(id)sender;
-- (IBAction)saveChanges:(id)sender;
-- (IBAction)setKey:(id)sender;
-
-- (BOOL)sendEvent:(NSEvent *)anEvent;
-
-- (void)awakeFromNib;
-- (void)windowWillClose:(NSNotification *)aNotification;
-
-+ (void)setUseKeymapFile:(BOOL)newUseKeymapFile;
-+ (void)setKeymapFile:(NSString *)newFile;
-+ (void)setSwitchString:(NSString *)newString;
-+ (void)setKeyCode:(int)newKeyCode;
-+ (void)setModifiers:(int)newModifiers;
-+ (void)setDisplay:(int)newDisplay;
-+ (void)setDockSwitch:(BOOL)newDockSwitch;
-+ (void)setFakeButtons:(BOOL)newFakeButtons;
-+ (void)setButton2Mask:(int)newFakeMask;
-+ (void)setButton3Mask:(int)newFakeMask;
-+ (void)setMouseAccelChange:(BOOL)newMouseAccelChange;
-+ (void)setUseQDCursor:(int)newUseQDCursor;
-+ (void)setRootless:(BOOL)newRootless;
-+ (void)setUseAGL:(BOOL)newUseAGL;
-+ (void)setModeWindow:(BOOL)newModeWindow;
-+ (void)setStartupHelp:(BOOL)newStartupHelp;
-+ (void)setSystemBeep:(BOOL)newSystemBeep;
-+ (void)setEnableKeyEquivalents:(BOOL)newKeyEquivs;
-+ (void)setXinerama:(BOOL)newXinerama;
-+ (void)setAddToPath:(BOOL)newAddToPath;
-+ (void)setAddToPathString:(NSString *)newAddToPathString;
-+ (void)setUseDefaultShell:(BOOL)newUseDefaultShell;
-+ (void)setShellString:(NSString *)newShellString;
-+ (void)setDepth:(int)newDepth;
-+ (void)setDisplayModeBundles:(NSArray *)newBundles;
-+ (void)saveToDisk;
-
-+ (BOOL)useKeymapFile;
-+ (NSString *)keymapFile;
-+ (NSString *)switchString;
-+ (unsigned int)keyCode;
-+ (unsigned int)modifiers;
-+ (int)display;
-+ (BOOL)dockSwitch;
-+ (BOOL)fakeButtons;
-+ (int)button2Mask;
-+ (int)button3Mask;
-+ (BOOL)mouseAccelChange;
-+ (int)useQDCursor;
-+ (BOOL)rootless;
-+ (BOOL)useAGL;
-+ (BOOL)modeWindow;
-+ (BOOL)startupHelp;
-+ (BOOL)systemBeep;
-+ (BOOL)enableKeyEquivalents;
-+ (BOOL)xinerama;
-+ (BOOL)addToPath;
-+ (NSString *)addToPathString;
-+ (BOOL)useDefaultShell;
-+ (NSString *)shellString;
-+ (int)depth;
-+ (NSArray *)displayModeBundles;
-
- at end
-
-// Possible settings for useQDCursor
-enum {
-    qdCursor_Never,	// never use QuickDraw cursor
-    qdCursor_Not8Bit,	// don't try to use QuickDraw with 8-bit depth
-    qdCursor_Always	// always try to use QuickDraw cursor
-};
-
-// Possible settings for depth
-enum {
-    depth_Current,
-    depth_8Bit,
-    depth_15Bit,
-    depth_24Bit
-};
diff --git a/hw/darwin/quartz/Preferences.m b/hw/darwin/quartz/Preferences.m
deleted file mode 100644
index b5eeedd..0000000
--- a/hw/darwin/quartz/Preferences.m
+++ /dev/null
@@ -1,599 +0,0 @@
-//
-//  Preferences.m
-//
-//  This class keeps track of the user preferences.
-//
-/*
- * Copyright (c) 2002-2004 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, 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.
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-#import "quartzCommon.h"
-
-#define BOOL xBOOL
-#include "darwin.h"
-#undef BOOL
-
-#import "Preferences.h"
-
-#include <IOKit/hidsystem/IOLLEvent.h>	// for modifier masks
-
-// Macros to build the path name
-#ifndef XBINDIR
-#define XBINDIR /usr/X11/bin
-#endif
-#define STR(s) #s
-#define XSTRPATH(s) STR(s)
-
-// Keys for user defaults dictionary
-static NSString *X11EnableKeyEquivalentsKey = @"EnableKeyEquivalents";
-
-
- at implementation Preferences
-
-+ (void)initialize
-{
-    // Provide user defaults if needed
-    NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
-        [NSNumber numberWithInt:0], @"Display",
-        @"YES", @"FakeButtons",
-        [NSNumber numberWithInt:NX_COMMANDMASK], @"Button2Mask",
-        [NSNumber numberWithInt:NX_ALTERNATEMASK], @"Button3Mask",
-        NSLocalizedString(@"USA.keymapping",@""), @"KeymappingFile",
-        @"YES", @"UseKeymappingFile",
-        NSLocalizedString(@"Cmd-Opt-a",@""), @"SwitchString",
-        @"YES", @"UseRootlessMode",
-        @"YES", @"UseAGLforGLX",
-        @"YES", @"ShowModePickWindow",
-        @"YES", @"ShowStartupHelp",
-        [NSNumber numberWithInt:0], @"SwitchKeyCode",
-        [NSNumber numberWithInt:(NSCommandKeyMask | NSAlternateKeyMask)],
-        @"SwitchModifiers", @"NO", @"UseSystemBeep",
-        @"YES", X11EnableKeyEquivalentsKey,
-        @"YES", @"DockSwitch",
-        @"NO", @"AllowMouseAccelChange",
-        [NSNumber numberWithInt:qdCursor_Not8Bit], @"UseQDCursor",
-        @"YES", @"Xinerama",
-        @"YES", @"AddToPath",
-        [NSString stringWithCString:XSTRPATH(XBINDIR)], @"AddToPathString",
-        @"YES", @"UseDefaultShell",
-        @"/bin/tcsh", @"Shell",
-        [NSNumber numberWithInt:depth_Current], @"Depth",
-#ifdef BUILD_XPR
-        [NSArray arrayWithObjects:@"xpr.bundle", @"cr.bundle", nil],
-#else
-        [NSArray arrayWithObjects:@"cr.bundle", nil],
-#endif
-        @"DisplayModeBundles", nil];
-
-    [super initialize];
-    [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
-}
-
-// Initialize internal state info of switch key button
-- (void)initSwitchKey
-{
-    keyCode = [Preferences keyCode];
-    modifiers = [Preferences modifiers];
-    [switchString setString:[Preferences switchString]];
-}
-
-- (id)init
-{
-    self = [super init];
-
-    isGettingKeyCode=NO;
-    switchString=[[NSMutableString alloc] init];
-    [self initSwitchKey];
-
-    return self;
-}
-
-// Set a modifiers checkbox matrix to match a modifier mask
-- (void)resetMatrix:(NSMatrix *)aMatrix withMask:(int)aMask
-{
-    [aMatrix setState:(aMask & NX_SHIFTMASK)       atRow:0 column:0];
-    [aMatrix setState:(aMask & NX_CONTROLMASK)     atRow:1 column:0];
-    [aMatrix setState:(aMask & NX_COMMANDMASK)     atRow:2 column:0];
-    [aMatrix setState:(aMask & NX_ALTERNATEMASK)   atRow:3 column:0];
-    [aMatrix setState:(aMask & NX_SECONDARYFNMASK) atRow:4 column:0];
-}
-
-// Generate a modifiers mask from a modifiers checkbox matrix
-- (int)getMaskFromMatrix:(NSMatrix *)aMatrix
-{
-    int theMask = 0;
-
-    if ([[aMatrix cellAtRow:0 column:0] state])
-        theMask |= NX_SHIFTMASK;
-    if ([[aMatrix cellAtRow:1 column:0] state])
-        theMask |= NX_CONTROLMASK;
-    if ([[aMatrix cellAtRow:2 column:0] state])
-        theMask |= NX_COMMANDMASK;
-    if ([[aMatrix cellAtRow:3 column:0] state])
-        theMask |= NX_ALTERNATEMASK;
-    if ([[aMatrix cellAtRow:4 column:0] state])
-        theMask |= NX_SECONDARYFNMASK;
-
-    return theMask;
-}
-
-// Set the window controls to the state in user defaults
-- (void)resetWindow
-{
-    if ([Preferences keymapFile] == nil)
-        [keymapFileField setStringValue:@" "];
-    else
-        [keymapFileField setStringValue:[Preferences keymapFile]];
-
-    if ([Preferences switchString] == nil)
-        [switchKeyButton setTitle:@"--"];
-    else
-        [switchKeyButton setTitle:[Preferences switchString]];
-
-    [displayField setIntValue:[Preferences display]];
-    [dockSwitchButton setIntValue:[Preferences dockSwitch]];
-    [fakeButton setIntValue:[Preferences fakeButtons]];
-    [self resetMatrix:button2ModifiersMatrix
-          withMask:[Preferences button2Mask]];
-    [self resetMatrix:button3ModifiersMatrix
-          withMask:[Preferences button3Mask]];
-    [modeMatrix setState:[Preferences rootless] atRow:0 column:1];
-    [startupHelpButton setIntValue:[Preferences startupHelp]];
-    [modeWindowButton setIntValue:[Preferences modeWindow]];
-    [systemBeepButton setIntValue:[Preferences systemBeep]];
-    [mouseAccelChangeButton setIntValue:[Preferences mouseAccelChange]];
-    [useXineramaButton setIntValue:[Preferences xinerama]];
-    [addToPathButton setIntValue:[Preferences addToPath]];
-    [addToPathField setStringValue:[Preferences addToPathString]];
-    [useDefaultShellMatrix setState:![Preferences useDefaultShell]
-                           atRow:1 column:0];
-    [useOtherShellField setStringValue:[Preferences shellString]];
-    [depthButton selectItemAtIndex:[Preferences depth]];
-}
-
-- (void)awakeFromNib
-{
-    [self resetWindow];
-}
-
-// Preference window delegate
-- (void)windowWillClose:(NSNotification *)aNotification
-{
-    [self resetWindow];
-    [self initSwitchKey];
-}
-
-// User cancelled the changes
-- (IBAction)close:(id)sender
-{
-    [window orderOut:nil];
-    [self resetWindow];  	// reset window controls
-    [self initSwitchKey];	// reset switch key state
-}
-
-// Pick keymapping file
-- (IBAction)pickFile:(id)sender
-{
-    int result;
-    NSArray *fileTypes = [NSArray arrayWithObject:@"keymapping"];
-    NSOpenPanel *oPanel = [NSOpenPanel openPanel];
-
-    [oPanel setAllowsMultipleSelection:NO];
-    result = [oPanel runModalForDirectory:@"/System/Library/Keyboards"
-                     file:nil types:fileTypes];
-    if (result == NSOKButton) {
-        [keymapFileField setStringValue:[oPanel filename]];
-    }
-}
-
-// User saved changes
-- (IBAction)saveChanges:(id)sender
-{
-    [Preferences setKeyCode:keyCode];
-    [Preferences setModifiers:modifiers];
-    [Preferences setSwitchString:switchString];
-    [Preferences setKeymapFile:[keymapFileField stringValue]];
-    [Preferences setUseKeymapFile:YES];
-    [Preferences setDisplay:[displayField intValue]];
-    [Preferences setDockSwitch:[dockSwitchButton intValue]];
-    [Preferences setFakeButtons:[fakeButton intValue]];
-    [Preferences setButton2Mask:
-                    [self getMaskFromMatrix:button2ModifiersMatrix]];
-    [Preferences setButton3Mask:
-                    [self getMaskFromMatrix:button3ModifiersMatrix]];
-    [Preferences setRootless:[[modeMatrix cellAtRow:0 column:1] state]];
-    [Preferences setModeWindow:[modeWindowButton intValue]];
-    [Preferences setStartupHelp:[startupHelpButton intValue]];
-    [Preferences setSystemBeep:[systemBeepButton intValue]];
-    [Preferences setMouseAccelChange:[mouseAccelChangeButton intValue]];
-    [Preferences setXinerama:[useXineramaButton intValue]];
-    [Preferences setAddToPath:[addToPathButton intValue]];
-    [Preferences setAddToPathString:[addToPathField stringValue]];
-    [Preferences setUseDefaultShell:
-                    [[useDefaultShellMatrix cellAtRow:0 column:0] state]];
-    [Preferences setShellString:[useOtherShellField stringValue]];
-    [Preferences setDepth:[depthButton indexOfSelectedItem]];
-    [Preferences saveToDisk];
-
-    [window orderOut:nil];
-}
-
-- (IBAction)setKey:(id)sender
-{
-    [switchKeyButton setTitle:NSLocalizedString(@"Press key",@"")];
-    isGettingKeyCode=YES;
-    [switchString setString:@""];
-}
-
-- (BOOL)sendEvent:(NSEvent *)anEvent
-{
-    if(isGettingKeyCode) {
-        if([anEvent type]==NSKeyDown) // wait for keyup
-            return YES;
-        if([anEvent type]!=NSKeyUp)
-            return NO;
-
-        if([anEvent modifierFlags] & NSCommandKeyMask)
-            [switchString appendString:@"Cmd-"];
-        if([anEvent modifierFlags] & NSControlKeyMask)
-            [switchString appendString:@"Ctrl-"];
-        if([anEvent modifierFlags] & NSAlternateKeyMask)
-            [switchString appendString:@"Opt-"];
-        if([anEvent modifierFlags] & NSNumericPadKeyMask) // doesn't work
-            [switchString appendString:@"Num-"];
-        if([anEvent modifierFlags] & NSHelpKeyMask)
-            [switchString appendString:@"Help-"];
-        if([anEvent modifierFlags] & NSFunctionKeyMask) // powerbooks only
-            [switchString appendString:@"Fn-"];
-        
-        [switchString appendString:[anEvent charactersIgnoringModifiers]];
-        [switchKeyButton setTitle:switchString];
-        
-        keyCode = [anEvent keyCode];
-        modifiers = [anEvent modifierFlags];
-        isGettingKeyCode=NO;
-        
-        return YES;
-    }
-    return NO;
-}
-
-+ (void)setKeymapFile:(NSString *)newFile
-{
-    [[NSUserDefaults standardUserDefaults] setObject:newFile
-            forKey:@"KeymappingFile"];
-}
-
-+ (void)setUseKeymapFile:(BOOL)newUseKeymapFile
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newUseKeymapFile
-            forKey:@"UseKeymappingFile"];
-}
-
-+ (void)setSwitchString:(NSString *)newString
-{
-    [[NSUserDefaults standardUserDefaults] setObject:newString
-            forKey:@"SwitchString"];
-}
-
-+ (void)setKeyCode:(int)newKeyCode
-{
-    [[NSUserDefaults standardUserDefaults] setInteger:newKeyCode
-            forKey:@"SwitchKeyCode"];
-}
-
-+ (void)setModifiers:(int)newModifiers
-{
-    [[NSUserDefaults standardUserDefaults] setInteger:newModifiers
-            forKey:@"SwitchModifiers"];
-}
-
-+ (void)setDisplay:(int)newDisplay
-{
-    [[NSUserDefaults standardUserDefaults] setInteger:newDisplay
-            forKey:@"Display"];
-}
-
-+ (void)setDockSwitch:(BOOL)newDockSwitch
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newDockSwitch
-            forKey:@"DockSwitch"];
-}
-
-+ (void)setFakeButtons:(BOOL)newFakeButtons
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newFakeButtons
-            forKey:@"FakeButtons"];
-    // Update the setting used by the X server thread
-    darwinFakeButtons = newFakeButtons;
-}
-
-+ (void)setButton2Mask:(int)newFakeMask
-{
-    [[NSUserDefaults standardUserDefaults] setInteger:newFakeMask
-            forKey:@"Button2Mask"];
-    // Update the setting used by the X server thread
-    darwinFakeMouse2Mask = newFakeMask;
-}
-
-+ (void)setButton3Mask:(int)newFakeMask
-{
-    [[NSUserDefaults standardUserDefaults] setInteger:newFakeMask
-            forKey:@"Button3Mask"];
-    // Update the setting used by the X server thread
-    darwinFakeMouse3Mask = newFakeMask;
-}
-
-+ (void)setMouseAccelChange:(BOOL)newMouseAccelChange
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newMouseAccelChange
-            forKey:@"AllowMouseAccelChange"];
-    // Update the setting used by the X server thread
-    darwinMouseAccelChange = newMouseAccelChange;
-}
-
-+ (void)setUseQDCursor:(int)newUseQDCursor
-{
-    [[NSUserDefaults standardUserDefaults] setInteger:newUseQDCursor
-            forKey:@"UseQDCursor"];
-}
-
-+ (void)setModeWindow:(BOOL)newModeWindow
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newModeWindow
-            forKey:@"ShowModePickWindow"];
-}
-
-+ (void)setRootless:(BOOL)newRootless
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newRootless
-            forKey:@"UseRootlessMode"];
-}
-
-+ (void)setUseAGL:(BOOL)newUseAGL
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newUseAGL
-            forKey:@"UseAGLforGLX"];
-}
-
-+ (void)setStartupHelp:(BOOL)newStartupHelp
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newStartupHelp
-            forKey:@"ShowStartupHelp"];
-}
-
-+ (void)setSystemBeep:(BOOL)newSystemBeep
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newSystemBeep
-            forKey:@"UseSystemBeep"];
-    // Update the setting used by the X server thread
-    quartzUseSysBeep = newSystemBeep;
-}
-
-+ (void)setEnableKeyEquivalents:(BOOL)newKeyEquivs
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newKeyEquivs
-            forKey:X11EnableKeyEquivalentsKey];
-    // Update the setting used by the X server thread
-    quartzEnableKeyEquivalents = newKeyEquivs;
-}
-
-+ (void)setXinerama:(BOOL)newXinerama
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newXinerama
-            forKey:@"Xinerama"];
-}
-
-+ (void)setAddToPath:(BOOL)newAddToPath
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newAddToPath
-            forKey:@"AddToPath"];
-}
-
-+ (void)setAddToPathString:(NSString *)newAddToPathString
-{
-    [[NSUserDefaults standardUserDefaults] setObject:newAddToPathString
-            forKey:@"AddToPathString"];
-}
-
-+ (void)setUseDefaultShell:(BOOL)newUseDefaultShell
-{
-    [[NSUserDefaults standardUserDefaults] setBool:newUseDefaultShell
-            forKey:@"UseDefaultShell"];
-}
-
-+ (void)setShellString:(NSString *)newShellString
-{
-    [[NSUserDefaults standardUserDefaults] setObject:newShellString
-            forKey:@"Shell"];
-}
-
-+ (void)setDepth:(int)newDepth
-{
-    [[NSUserDefaults standardUserDefaults] setInteger:newDepth
-            forKey:@"Depth"];
-}
-
-+ (void)setDisplayModeBundles:(NSArray *)newBundles
-{
-    [[NSUserDefaults standardUserDefaults] setObject:newBundles
-            forKey:@"DisplayModeBundles"];
-}
-
-+ (void)saveToDisk
-{
-    [[NSUserDefaults standardUserDefaults] synchronize];
-}
-
-+ (BOOL)useKeymapFile
-{
-    return [[NSUserDefaults standardUserDefaults]
-                boolForKey:@"UseKeymappingFile"];
-}
-
-+ (NSString *)keymapFile
-{
-    return [[NSUserDefaults standardUserDefaults]
-                stringForKey:@"KeymappingFile"];
-}
-
-+ (NSString *)switchString
-{
-    return [[NSUserDefaults standardUserDefaults]
-                stringForKey:@"SwitchString"];
-}
-
-+ (unsigned int)keyCode
-{
-    return [[NSUserDefaults standardUserDefaults]
-                integerForKey:@"SwitchKeyCode"];
-}
-
-+ (unsigned int)modifiers
-{
-    return [[NSUserDefaults standardUserDefaults]
-                integerForKey:@"SwitchModifiers"];
-}
-
-+ (int)display
-{
-    return [[NSUserDefaults standardUserDefaults]
-                integerForKey:@"Display"];
-}
-
-+ (BOOL)dockSwitch
-{
-    return [[NSUserDefaults standardUserDefaults] boolForKey:@"DockSwitch"];
-}
-
-+ (BOOL)fakeButtons
-{
-    return [[NSUserDefaults standardUserDefaults] boolForKey:@"FakeButtons"];
-}
-
-+ (int)button2Mask
-{
-    return [[NSUserDefaults standardUserDefaults]
-                integerForKey:@"Button2Mask"];
-}
-
-+ (int)button3Mask
-{
-    return [[NSUserDefaults standardUserDefaults]
-                integerForKey:@"Button3Mask"];
-}
-
-+ (BOOL)mouseAccelChange
-{
-    return [[NSUserDefaults standardUserDefaults]
-                boolForKey:@"AllowMouseAccelChange"];
-}
-
-+ (int)useQDCursor
-{
-    return [[NSUserDefaults standardUserDefaults]
-                integerForKey:@"UseQDCursor"];
-}
-
-+ (BOOL)rootless
-{
-    return [[NSUserDefaults standardUserDefaults]
-                boolForKey:@"UseRootlessMode"];
-}
-
-+ (BOOL)useAGL
-{
-    return [[NSUserDefaults standardUserDefaults]
-                boolForKey:@"UseAGLforGLX"];
-}
-
-+ (BOOL)modeWindow
-{
-    return [[NSUserDefaults standardUserDefaults]
-                boolForKey:@"ShowModePickWindow"];
-}
-
-+ (BOOL)startupHelp
-{
-    return [[NSUserDefaults standardUserDefaults]
-                boolForKey:@"ShowStartupHelp"];
-}
-
-+ (BOOL)systemBeep
-{
-    return [[NSUserDefaults standardUserDefaults] boolForKey:@"UseSystemBeep"];
-}
-
-+ (BOOL)enableKeyEquivalents
-{
-    return [[NSUserDefaults standardUserDefaults] boolForKey:X11EnableKeyEquivalentsKey];
-}
-
-+ (BOOL)xinerama
-{
-    return [[NSUserDefaults standardUserDefaults] boolForKey:@"Xinerama"];
-}
-
-+ (BOOL)addToPath
-{
-    return [[NSUserDefaults standardUserDefaults] boolForKey:@"AddToPath"];
-}
-
-+ (NSString *)addToPathString
-{
-    return [[NSUserDefaults standardUserDefaults]
-                stringForKey:@"AddToPathString"];
-}
-
-+ (BOOL)useDefaultShell
-{
-    return [[NSUserDefaults standardUserDefaults]
-                boolForKey:@"UseDefaultShell"];
-}
-
-+ (NSString *)shellString
-{
-    return [[NSUserDefaults standardUserDefaults]
-                stringForKey:@"Shell"];
-}
-
-+ (int)depth
-{
-    return [[NSUserDefaults standardUserDefaults]
-                integerForKey:@"Depth"];
-}
-
-+ (NSArray *)displayModeBundles
-{
-    return [[NSUserDefaults standardUserDefaults]
-                objectForKey:@"DisplayModeBundles"];
-}
-
- at end
diff --git a/hw/darwin/quartz/X11Application.h b/hw/darwin/quartz/X11Application.h
new file mode 100644
index 0000000..fb153e7
--- /dev/null
+++ b/hw/darwin/quartz/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 "org.x.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/quartz/X11Application.m b/hw/darwin/quartz/X11Application.m
new file mode 100644
index 0000000..38359e6
--- /dev/null
+++ b/hw/darwin/quartz/X11Application.m
@@ -0,0 +1,1088 @@
+/* X11Application.m -- subclass of NSApplication to multiplex events
+ 
+ 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 <mach/mach.h>
+#include <unistd.h>
+#include <pthread.h>
+
+#include "rootlessCommon.h"
+
+WindowPtr xprGetXWindowFromAppKit(int windowNumber); // xpr/xprFrame.c
+
+#define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
+
+int X11EnableKeyEquivalents = TRUE;
+int quartzHasRoot = FALSE, quartzEnableRootless = TRUE;
+
+extern int darwinFakeButtons;
+extern Bool enable_stereo; 
+
+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.2 (xorg-server-1.2a11)",
+					 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 an (AppKit) 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. */
+      WindowPtr pWin = xprGetXWindowFromAppKit([e windowNumber]);
+      if (pWin) RootlessReorderWindow(pWin);
+      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];
+	if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
+      }
+      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
+{
+    QuartzMessageServerThread(kXDarwinBringAllToFront, 0);
+}
+
+- (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 UTF8String];
+			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]);
+  
+  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;
+	
+    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/quartz/X11Controller.h b/hw/darwin/quartz/X11Controller.h
new file mode 100644
index 0000000..954d0ab
--- /dev/null
+++ b/hw/darwin/quartz/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/quartz/X11Controller.m b/hw/darwin/quartz/X11Controller.m
new file mode 100644
index 0000000..df90049
--- /dev/null
+++ b/hw/darwin/quartz/X11Controller.m
@@ -0,0 +1,748 @@
+/* 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>
+
+ 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 *argv[7];
+  int child1, child2 = 0;
+  int status;
+	
+  argv[0] = "/usr/bin/login";
+  argv[1] = "-fp";
+  argv[2] = getlogin();
+  argv[3] = "/bin/sh";
+  argv[4] = "-c";
+  argv[5] = command;
+  argv[6] = 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 ((CFStringRef)NSLocalizedString(@"Mac Help", no comment), 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/quartz/XApplication.h b/hw/darwin/quartz/XApplication.h
deleted file mode 100644
index 2f2b223..0000000
--- a/hw/darwin/quartz/XApplication.h
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-//  XApplication.h
-//
-//  Created by Andreas Monitzer on January 6, 2001.
-//
-/*
- * Copyright (c) 2001 Andreas Monitzer. 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.
- */
-
-#import <Cocoa/Cocoa.h>
-
-#import "XServer.h"
-#import "Preferences.h"
-
- at interface XApplication : NSApplication {
-    IBOutlet XServer *xserver;
-    IBOutlet Preferences *preferences;
-}
-
-- (void)sendEvent:(NSEvent *)anEvent;
-
- at end
diff --git a/hw/darwin/quartz/XApplication.m b/hw/darwin/quartz/XApplication.m
deleted file mode 100644
index de32d38..0000000
--- a/hw/darwin/quartz/XApplication.m
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-//  XApplication.m
-//
-//  Created by Andreas Monitzer on January 6, 2001.
-//
-/*
- * Copyright (c) 2001 Andreas Monitzer. 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.
- */
-
-#import "XApplication.h"
-
-
- at implementation XApplication
-
-- (void)sendEvent:(NSEvent *)anEvent {
-    if (![xserver translateEvent:anEvent]) {
-        if (![preferences sendEvent:anEvent])
-            [super sendEvent:anEvent];
-    }
-}
-
- at end
diff --git a/hw/darwin/quartz/XDarwin.pbproj/project.pbxproj b/hw/darwin/quartz/XDarwin.pbproj/project.pbxproj
deleted file mode 100644
index 0ad8314..0000000
--- a/hw/darwin/quartz/XDarwin.pbproj/project.pbxproj
+++ /dev/null
@@ -1,2519 +0,0 @@
-// !$*UTF8*$!
-{
-	archiveVersion = 1;
-	classes = {
-	};
-	objectVersion = 39;
-	objects = {
-		01279092000747AA0A000002 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.objc;
-			path = XServer.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		0127909600074AF60A000002 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.objc;
-			path = XApplication.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		0127909800074B1A0A000002 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = XApplication.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		015698ED003DF345CE6F79C2 = {
-			isa = PBXFileReference;
-			lastKnownFileType = image.icns;
-			path = XDarwin.icns;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		0157A37D002CF6D7CE6F79C2 = {
-			children = (
-				F533214601A4B45401000001,
-				0157A37E002CF6D7CE6F79C2,
-				F58D65DF018F79B101000001,
-				F533213D0193CBE001000001,
-				43B962E200617B93416877C2,
-				F5ACD263C5BE031F01000001,
-				F51BF62E02026E3501000001,
-				F5ACD25CC5B5E96601000001,
-				F587E16401924C6901000001,
-			);
-			isa = PBXVariantGroup;
-			name = Credits.rtf;
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		0157A37E002CF6D7CE6F79C2 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = English;
-			path = English.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		015EDCEA004203A8CE6F79C2 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.framework;
-			name = IOKit.framework;
-			path = /System/Library/Frameworks/IOKit.framework;
-			refType = 0;
-			sourceTree = "<absolute>";
-		};
-		018F40F2003E1902CE6F79C2 = {
-			children = (
-				018F40F3003E1916CE6F79C2,
-				021D6BA9003E1BACCE6F79C2,
-				3E74E03600863F047F000001,
-				F5A94EF10314BAC70100011B,
-				018F40F6003E1974CE6F79C2,
-				6E5F5F0005537A1A008FEAD7,
-			);
-			isa = PBXGroup;
-			name = "X Server";
-			path = ..;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		018F40F3003E1916CE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = darwin.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		018F40F6003E1974CE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = darwinKeyboard.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		018F40F8003E1979CE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = quartz.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		018F40FA003E197ECE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = quartz.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		018F40FC003E1983CE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = xfIOKit.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		018F40FE003E1988CE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = xfIOKit.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		018F4100003E19E4CE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = xfIOKitCursor.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//010
-//011
-//012
-//013
-//014
-//020
-//021
-//022
-//023
-//024
-		021D6BA9003E1BACCE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = darwin.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		02A1FEA6006D34BE416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = xfIOKitStartup.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		02A1FEA8006D38F0416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = quartzStartup.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		02E03CA000348209CE6F79C2 = {
-			children = (
-				F533214701A4B48301000001,
-				02E03CA100348209CE6F79C2,
-				F58D65E0018F79C001000001,
-				F533213E0193CBF401000001,
-				43B962E300617B93416877C2,
-				F5ACD268C5BE046401000001,
-				F51BF62F02026E5C01000001,
-				F5ACD261C5B5EA2001000001,
-				F587E16501924C7401000001,
-			);
-			isa = PBXVariantGroup;
-			name = XDarwinHelp.html;
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		02E03CA100348209CE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = English;
-			path = English.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//020
-//021
-//022
-//023
-//024
-//030
-//031
-//032
-//033
-//034
-		0338412F0083BFE57F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = quartzCursor.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//030
-//031
-//032
-//033
-//034
-//040
-//041
-//042
-//043
-//044
-		04329610000763920A000002 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.objc;
-			path = Preferences.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		04329611000763920A000002 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = Preferences.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//040
-//041
-//042
-//043
-//044
-//080
-//081
-//082
-//083
-//084
-		080E96DDFE201D6D7F000001 = {
-			children = (
-				04329610000763920A000002,
-				04329611000763920A000002,
-				0127909600074AF60A000002,
-				0127909800074B1A0A000002,
-				01279092000747AA0A000002,
-				1C4A3109004D8F24CE6F79C2,
-			);
-			isa = PBXGroup;
-			name = Classes;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		089C165CFE840E0CC02AAC07 = {
-			children = (
-				F533214301A4B3F001000001,
-				089C165DFE840E0CC02AAC07,
-				F58D65DD018F798F01000001,
-				F533213A0193CBA201000001,
-				43B962E100617B49416877C2,
-				F5ACD269C5BE049301000001,
-				F51BF62B02026DDA01000001,
-				F5ACD262C5B5EA4D01000001,
-				F587E16101924C2F01000001,
-			);
-			isa = PBXVariantGroup;
-			name = InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		089C165DFE840E0CC02AAC07 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = English;
-			path = English.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//080
-//081
-//082
-//083
-//084
-//0A0
-//0A1
-//0A2
-//0A3
-//0A4
-		0A79E19E004499A1CE6F79C2 = {
-			explicitFileType = wrapper.application;
-			isa = PBXFileReference;
-			path = XDarwin.app;
-			refType = 3;
-			sourceTree = BUILT_PRODUCTS_DIR;
-		};
-		0A79E19F004499A1CE6F79C2 = {
-			buildPhases = (
-				0A79E1A0004499A1CE6F79C2,
-				0A79E1A1004499A1CE6F79C2,
-				0A79E1A2004499A1CE6F79C2,
-				0A79E1A3004499A1CE6F79C2,
-				0A79E1A4004499A1CE6F79C2,
-			);
-			buildSettings = {
-				INSTALL_PATH = /;
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = XDarwin;
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
-				WRAPPER_EXTENSION = app;
-			};
-			dependencies = (
-				6EF065C903D4F0CA006877C2,
-				6EF065C703D4EE19006877C2,
-				6E11A986048BDFFB006877C2,
-				6E7904110500F33B00EEC080,
-			);
-			isa = PBXApplicationTarget;
-			name = XDarwin;
-			productInstallPath = /;
-			productName = XDarwin;
-			productReference = 0A79E19E004499A1CE6F79C2;
-			productSettingsXML = "<?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.x11</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>
-";
-		};
-		0A79E1A0004499A1CE6F79C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXHeadersBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0A79E1A1004499A1CE6F79C2 = {
-			buildActionMask = 2147483647;
-			files = (
-				0A79E1A600449EB2CE6F79C2,
-				0A79E1A700449EB2CE6F79C2,
-				0A79E1A800449EB2CE6F79C2,
-				0A79E1A900449EB2CE6F79C2,
-				0A79E1AA00449EB2CE6F79C2,
-				1220774500712D2D416877C2,
-				F54BF6ED017D506E01000001,
-			);
-			isa = PBXResourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0A79E1A2004499A1CE6F79C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXSourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0A79E1A3004499A1CE6F79C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXFrameworksBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0A79E1A4004499A1CE6F79C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXRezBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0A79E1A600449EB2CE6F79C2 = {
-			fileRef = 29B97318FDCFA39411CA2CEA;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		0A79E1A700449EB2CE6F79C2 = {
-			fileRef = 089C165CFE840E0CC02AAC07;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		0A79E1A800449EB2CE6F79C2 = {
-			fileRef = 0157A37D002CF6D7CE6F79C2;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		0A79E1A900449EB2CE6F79C2 = {
-			fileRef = 02E03CA000348209CE6F79C2;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		0A79E1AA00449EB2CE6F79C2 = {
-			fileRef = 015698ED003DF345CE6F79C2;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-//0A0
-//0A1
-//0A2
-//0A3
-//0A4
-//100
-//101
-//102
-//103
-//104
-		1058C7A0FEA54F0111CA2CBB = {
-			children = (
-				F53321400193CCF001000001,
-				1BE4F84D0006C9890A000002,
-				1058C7A1FEA54F0111CA2CBB,
-				F53321410193CCF001000001,
-				015EDCEA004203A8CE6F79C2,
-			);
-			isa = PBXGroup;
-			name = "Linked Frameworks";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1058C7A1FEA54F0111CA2CBB = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.framework;
-			name = Cocoa.framework;
-			path = /System/Library/Frameworks/Cocoa.framework;
-			refType = 0;
-			sourceTree = "<absolute>";
-		};
-		1058C7A2FEA54F0111CA2CBB = {
-			children = (
-				29B97325FDCFA39411CA2CEA,
-				29B97324FDCFA39411CA2CEA,
-			);
-			isa = PBXGroup;
-			name = "Other Frameworks";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//100
-//101
-//102
-//103
-//104
-//120
-//121
-//122
-//123
-//124
-		1220774300712D2D416877C2 = {
-			children = (
-				F533214501A4B42501000001,
-				1220774400712D2D416877C2,
-				F58D65DE018F79A001000001,
-				F533213C0193CBC901000001,
-				1220774600712D75416877C2,
-				F5ACD266C5BE03C501000001,
-				F51BF62D02026E1C01000001,
-				F5ACD25FC5B5E9AA01000001,
-				F587E16301924C5E01000001,
-			);
-			isa = PBXVariantGroup;
-			name = Localizable.strings;
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1220774400712D2D416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = English;
-			path = English.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1220774500712D2D416877C2 = {
-			fileRef = 1220774300712D2D416877C2;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		1220774600712D75416877C2 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Japanese;
-			path = Japanese.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//120
-//121
-//122
-//123
-//124
-//170
-//171
-//172
-//173
-//174
-		170DFAFF00729A35416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = XDarwinStartup.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		170DFB0000729C86416877C2 = {
-			children = (
-				018F40FC003E1983CE6F79C2,
-				018F40FE003E1988CE6F79C2,
-				018F4100003E19E4CE6F79C2,
-				02A1FEA6006D34BE416877C2,
-			);
-			isa = PBXGroup;
-			name = IOKit;
-			path = ../iokit;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//170
-//171
-//172
-//173
-//174
-//190
-//191
-//192
-//193
-//194
-		19C28FACFE9D520D11CA2CBB = {
-			children = (
-				0A79E19E004499A1CE6F79C2,
-				6EF7C58703D3BC6D00000104,
-				6EF065C603D4EE19006877C2,
-				6E11A985048BDFEE006877C2,
-				6E7904100500F05600EEC080,
-			);
-			isa = PBXGroup;
-			name = Products;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//190
-//191
-//192
-//193
-//194
-//1B0
-//1B1
-//1B2
-//1B3
-//1B4
-		1BD8DE4200B8A3567F000001 = {
-			children = (
-				F533214401A4B40F01000001,
-				1BD8DE4300B8A3567F000001,
-				F58D65DC018F794D01000001,
-				F533213B0193CBB401000001,
-				1BD8DE4700B8A3C77F000001,
-				F5ACD264C5BE035B01000001,
-				F51BF62C02026E0601000001,
-				F5ACD25DC5B5E97701000001,
-				F587E16201924C5301000001,
-			);
-			isa = PBXVariantGroup;
-			name = InfoPlist.strings.cpp;
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1BD8DE4300B8A3567F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = English;
-			path = English.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1BD8DE4400B8A38E7F000001 = {
-			children = (
-				F533214801A4B4D701000001,
-				1BD8DE4500B8A38E7F000001,
-				F58D65E1018F79E001000001,
-				F533213F0193CC2501000001,
-				1BD8DE4800B8A4167F000001,
-				F5ACD267C5BE03FC01000001,
-				F51BF63002026E8D01000001,
-				F5ACD260C5B5E9DF01000001,
-				F587E16601924C9D01000001,
-			);
-			isa = PBXVariantGroup;
-			name = XDarwinHelp.html.cpp;
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1BD8DE4500B8A38E7F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = English;
-			path = English.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1BD8DE4700B8A3C77F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Japanese;
-			path = Japanese.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1BD8DE4800B8A4167F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Japanese;
-			path = Japanese.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		1BE4F84D0006C9890A000002 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.framework;
-			name = Carbon.framework;
-			path = /System/Library/Frameworks/Carbon.framework;
-			refType = 0;
-			sourceTree = "<absolute>";
-		};
-//1B0
-//1B1
-//1B2
-//1B3
-//1B4
-//1C0
-//1C1
-//1C2
-//1C3
-//1C4
-		1C4A3109004D8F24CE6F79C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = XServer.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//1C0
-//1C1
-//1C2
-//1C3
-//1C4
-//230
-//231
-//232
-//233
-//234
-		237A34C10076E37E7F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = quartzAudio.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		237A34C20076E37E7F000001 = {
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				GCC_DYNAMIC_NO_PIC = NO;
-				GCC_ENABLE_FIX_AND_CONTINUE = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				GCC_OPTIMIZATION_LEVEL = 0;
-				OPTIMIZATION_CFLAGS = "-O0";
-				ZERO_LINK = YES;
-			};
-			isa = PBXBuildStyle;
-			name = Development;
-		};
-		237A34C30076E37E7F000001 = {
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				GCC_ENABLE_FIX_AND_CONTINUE = NO;
-				ZERO_LINK = NO;
-			};
-			isa = PBXBuildStyle;
-			name = Deployment;
-		};
-		237A34C40076F4F07F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = quartzAudio.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//230
-//231
-//232
-//233
-//234
-//290
-//291
-//292
-//293
-//294
-		29B97313FDCFA39411CA2CEA = {
-			buildSettings = {
-			};
-			buildStyles = (
-				237A34C20076E37E7F000001,
-				237A34C30076E37E7F000001,
-			);
-			hasScannedForEncodings = 1;
-			isa = PBXProject;
-			knownRegions = (
-				English,
-				Japanese,
-				French,
-				German,
-				Swedish,
-				Dutch,
-				Spanish,
-				ko,
-				Portuguese,
-			);
-			mainGroup = 29B97314FDCFA39411CA2CEA;
-			projectDirPath = "";
-			targets = (
-				0A79E19F004499A1CE6F79C2,
-				6EF7C58603D3BC6D00000104,
-				6E11A984048BDFEE006877C2,
-				6EF065C503D4EE19006877C2,
-				6E79040F0500F05600EEC080,
-			);
-		};
-		29B97314FDCFA39411CA2CEA = {
-			children = (
-				080E96DDFE201D6D7F000001,
-				018F40F2003E1902CE6F79C2,
-				170DFB0000729C86416877C2,
-				43B962CE00617089416877C2,
-				F5614B3D025112D901000114,
-				6EC4A64C042A9597006877C2,
-				32FEE13C00E07C3E7F000001,
-				6EE1214104968658006877C2,
-				6EC4A66D042A97FC006877C2,
-				29B97315FDCFA39411CA2CEA,
-				29B97317FDCFA39411CA2CEA,
-				29B97323FDCFA39411CA2CEA,
-				19C28FACFE9D520D11CA2CBB,
-			);
-			isa = PBXGroup;
-			name = "Xmaster-Cocoa";
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		29B97315FDCFA39411CA2CEA = {
-			children = (
-				170DFAFF00729A35416877C2,
-			);
-			isa = PBXGroup;
-			name = "Other Sources";
-			path = "";
-			refType = 2;
-			sourceTree = SOURCE_ROOT;
-		};
-		29B97317FDCFA39411CA2CEA = {
-			children = (
-				29B97318FDCFA39411CA2CEA,
-				089C165CFE840E0CC02AAC07,
-				1BD8DE4200B8A3567F000001,
-				1220774300712D2D416877C2,
-				0157A37D002CF6D7CE6F79C2,
-				02E03CA000348209CE6F79C2,
-				1BD8DE4400B8A38E7F000001,
-				015698ED003DF345CE6F79C2,
-				F54BF6EA017D500901000001,
-				F54BF6EC017D506E01000001,
-			);
-			isa = PBXGroup;
-			name = Resources;
-			path = ../bundle;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		29B97318FDCFA39411CA2CEA = {
-			children = (
-				F533214201A4B3CE01000001,
-				29B97319FDCFA39411CA2CEA,
-				F58D65DB018F793801000001,
-				F53321390193CB6A01000001,
-				43B962E000617B49416877C2,
-				F5ACD265C5BE038601000001,
-				F51BF62A02026DAF01000001,
-				F5ACD25EC5B5E98D01000001,
-				F587E16001924C1D01000001,
-			);
-			isa = PBXVariantGroup;
-			name = MainMenu.nib;
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		29B97319FDCFA39411CA2CEA = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = English;
-			path = English.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		29B97323FDCFA39411CA2CEA = {
-			children = (
-				1058C7A0FEA54F0111CA2CBB,
-				1058C7A2FEA54F0111CA2CBB,
-			);
-			isa = PBXGroup;
-			name = Frameworks;
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		29B97324FDCFA39411CA2CEA = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.framework;
-			name = AppKit.framework;
-			path = /System/Library/Frameworks/AppKit.framework;
-			refType = 0;
-			sourceTree = "<absolute>";
-		};
-		29B97325FDCFA39411CA2CEA = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.framework;
-			name = Foundation.framework;
-			path = /System/Library/Frameworks/Foundation.framework;
-			refType = 0;
-			sourceTree = "<absolute>";
-		};
-//290
-//291
-//292
-//293
-//294
-//320
-//321
-//322
-//323
-//324
-		32FEE13C00E07C3E7F000001 = {
-			children = (
-				F5269C2D01D5BC3501000001,
-				F5269C2E01D5BC3501000001,
-			);
-			isa = PBXGroup;
-			name = "Old Cocoa Imp";
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//320
-//321
-//322
-//323
-//324
-//350
-//351
-//352
-//353
-//354
-		3576829A0077B8F17F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = quartzCursor.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//350
-//351
-//352
-//353
-//354
-//3E0
-//3E1
-//3E2
-//3E3
-//3E4
-		3E74E03600863F047F000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = darwinClut8.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//3E0
-//3E1
-//3E2
-//3E3
-//3E4
-//430
-//431
-//432
-//433
-//434
-		43B962CE00617089416877C2 = {
-			children = (
-				6EE9B21604E859C200CA7FEA,
-				6E97A0F505079F9100B8294C,
-				6E5F5F030553815A008FEAD7,
-				6E5F5F040553815A008FEAD7,
-				018F40F8003E1979CE6F79C2,
-				018F40FA003E197ECE6F79C2,
-				237A34C10076E37E7F000001,
-				237A34C40076F4F07F000001,
-				43B962CF00617089416877C2,
-				F5582948015DAD3B01000001,
-				6E5F5F0105537A5F008FEAD7,
-				43B962D000617089416877C2,
-				43B962D100617089416877C2,
-				02A1FEA8006D38F0416877C2,
-			);
-			isa = PBXGroup;
-			name = Quartz;
-			path = "";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		43B962CF00617089416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.objc;
-			path = quartzCocoa.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		43B962D000617089416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = quartzPasteboard.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		43B962D100617089416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = quartzPasteboard.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		43B962E000617B49416877C2 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = Japanese;
-			path = Japanese.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		43B962E100617B49416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Japanese;
-			path = Japanese.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		43B962E200617B93416877C2 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = Japanese;
-			path = Japanese.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		43B962E300617B93416877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = Japanese;
-			path = Japanese.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-//430
-//431
-//432
-//433
-//434
-//6E0
-//6E1
-//6E2
-//6E3
-//6E4
-		6E11A97F048BDFEE006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXHeadersBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E11A980048BDFEE006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXResourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E11A981048BDFEE006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXSourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E11A982048BDFEE006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXFrameworksBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E11A983048BDFEE006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXRezBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E11A984048BDFEE006877C2 = {
-			buildPhases = (
-				6E11A97F048BDFEE006877C2,
-				6E11A980048BDFEE006877C2,
-				6E11A981048BDFEE006877C2,
-				6E11A982048BDFEE006877C2,
-				6E11A983048BDFEE006877C2,
-			);
-			buildSettings = {
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = glxCGL;
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
-				WRAPPER_EXTENSION = bundle;
-			};
-			dependencies = (
-			);
-			isa = PBXBundleTarget;
-			name = glxCGL;
-			productInstallPath = "$(USER_LIBRARY_DIR)/Bundles";
-			productName = glxCGL;
-			productReference = 6E11A985048BDFEE006877C2;
-			productSettingsXML = "<?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>CFBundleExecutable</key>
-	<string>glxCGL</string>
-	<key>CFBundleGetInfoString</key>
-	<string></string>
-	<key>CFBundleIconFile</key>
-	<string></string>
-	<key>CFBundleIdentifier</key>
-	<string></string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundleName</key>
-	<string>GLX bundle using Apple's OpenGL</string>
-	<key>CFBundlePackageType</key>
-	<string>BNDL</string>
-	<key>CFBundleShortVersionString</key>
-	<string>0.1</string>
-	<key>CFBundleSignature</key>
-	<string>????</string>
-	<key>CFBundleVersion</key>
-	<string>0.1</string>
-</dict>
-</plist>
-";
-		};
-		6E11A985048BDFEE006877C2 = {
-			explicitFileType = wrapper.cfbundle;
-			isa = PBXFileReference;
-			path = glxCGL.bundle;
-			refType = 3;
-			sourceTree = BUILT_PRODUCTS_DIR;
-		};
-		6E11A986048BDFFB006877C2 = {
-			isa = PBXTargetDependency;
-			target = 6E11A984048BDFEE006877C2;
-			targetProxy = 6E4CAF650702464F001A7398;
-		};
-		6E4CAF630702464F001A7398 = {
-			containerPortal = 29B97313FDCFA39411CA2CEA;
-			isa = PBXContainerItemProxy;
-			proxyType = 1;
-			remoteGlobalIDString = 6EF7C58603D3BC6D00000104;
-			remoteInfo = glxAGL;
-		};
-		6E4CAF640702464F001A7398 = {
-			containerPortal = 29B97313FDCFA39411CA2CEA;
-			isa = PBXContainerItemProxy;
-			proxyType = 1;
-			remoteGlobalIDString = 6E79040F0500F05600EEC080;
-			remoteInfo = xpr;
-		};
-		6E4CAF650702464F001A7398 = {
-			containerPortal = 29B97313FDCFA39411CA2CEA;
-			isa = PBXContainerItemProxy;
-			proxyType = 1;
-			remoteGlobalIDString = 6E11A984048BDFEE006877C2;
-			remoteInfo = glxCGL;
-		};
-		6E4CAF660702464F001A7398 = {
-			containerPortal = 29B97313FDCFA39411CA2CEA;
-			isa = PBXContainerItemProxy;
-			proxyType = 1;
-			remoteGlobalIDString = 6EF065C503D4EE19006877C2;
-			remoteInfo = glxMesa;
-		};
-		6E5F5F0005537A1A008FEAD7 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = darwinKeyboard.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E5F5F0105537A5F008FEAD7 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = quartzKeyboard.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E5F5F030553815A008FEAD7 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = keysym2ucs.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E5F5F040553815A008FEAD7 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = keysym2ucs.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E6656EC048832CF006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = "x-hook.c";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E6656ED048832CF006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = "x-hook.h";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E6656F0048832EC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = dri.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E6656F1048832EC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = dri.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E6656F2048832EC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = dristruct.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E6656F3048832F9006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = appledri.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E79040104FD5ED900EEC080 = {
-			children = (
-				6E79040204FD5EDA00EEC080,
-				6E79040304FD5EDA00EEC080,
-				6E79040404FD5EDA00EEC080,
-			);
-			isa = PBXGroup;
-			name = "Safe Alpha";
-			path = safeAlpha;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E79040204FD5EDA00EEC080 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = safeAlpha.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E79040304FD5EDA00EEC080 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = safeAlphaPicture.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E79040404FD5EDA00EEC080 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = safeAlphaWindow.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E79040A0500F05600EEC080 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXHeadersBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E79040B0500F05600EEC080 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXResourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E79040C0500F05600EEC080 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXSourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E79040D0500F05600EEC080 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXFrameworksBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E79040E0500F05600EEC080 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXRezBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6E79040F0500F05600EEC080 = {
-			buildPhases = (
-				6E79040A0500F05600EEC080,
-				6E79040B0500F05600EEC080,
-				6E79040C0500F05600EEC080,
-				6E79040D0500F05600EEC080,
-				6E79040E0500F05600EEC080,
-			);
-			buildSettings = {
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = xpr;
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
-				WRAPPER_EXTENSION = bundle;
-			};
-			dependencies = (
-			);
-			isa = PBXBundleTarget;
-			name = xpr;
-			productInstallPath = "$(USER_LIBRARY_DIR)/Bundles";
-			productName = xpr;
-			productReference = 6E7904100500F05600EEC080;
-			productSettingsXML = "<?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>CFBundleExecutable</key>
-	<string>xpr</string>
-	<key>CFBundleGetInfoString</key>
-	<string></string>
-	<key>CFBundleIconFile</key>
-	<string></string>
-	<key>CFBundleIdentifier</key>
-	<string></string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundleName</key>
-	<string>Xplugin rootless implementation</string>
-	<key>CFBundlePackageType</key>
-	<string>BNDL</string>
-	<key>CFBundleShortVersionString</key>
-	<string>0.1</string>
-	<key>CFBundleSignature</key>
-	<string>????</string>
-	<key>CFBundleVersion</key>
-	<string>0.1</string>
-</dict>
-</plist>
-";
-		};
-		6E7904100500F05600EEC080 = {
-			explicitFileType = wrapper.cfbundle;
-			isa = PBXFileReference;
-			path = xpr.bundle;
-			refType = 3;
-			sourceTree = BUILT_PRODUCTS_DIR;
-		};
-		6E7904110500F33B00EEC080 = {
-			isa = PBXTargetDependency;
-			target = 6E79040F0500F05600EEC080;
-			targetProxy = 6E4CAF640702464F001A7398;
-		};
-		6E97A0F2050798B100B8294C = {
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = xprAppleWM.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E97A0F305079B6500B8294C = {
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.objc;
-			path = crAppleWM.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6E97A0F505079F9100B8294C = {
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = applewmExt.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3AF0544A9CC006877C2 = {
-			children = (
-				6EA0B3B00544A9CC006877C2,
-				6EA0B3B10544A9CC006877C2,
-				6EA0B3B20544A9CC006877C2,
-				6EA0B3B30544A9CC006877C2,
-				6EA0B3B40544A9CC006877C2,
-				6EA0B3B50544A9CC006877C2,
-				6EA0B3B60544A9CC006877C2,
-				6EA0B3B70544A9CC006877C2,
-			);
-			isa = PBXGroup;
-			name = Acceleration;
-			path = accel;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3B00544A9CC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = rlAccel.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3B10544A9CC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rlBlt.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3B20544A9CC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rlCopy.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3B30544A9CC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rlFill.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3B40544A9CC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rlFillRect.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3B50544A9CC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rlFillSpans.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3B60544A9CC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rlGlyph.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA0B3B70544A9CC006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rlSolid.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EA8EEC80445E25C006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = rootlessConfig.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A64C042A9597006877C2 = {
-			children = (
-				6EC4A65D042A9654006877C2,
-				6EC4A65E042A9654006877C2,
-				6EC4A65F042A9654006877C2,
-				6EA8EEC80445E25C006877C2,
-				6EC4A661042A9654006877C2,
-				6EC4A662042A9654006877C2,
-				6EC4A660042A9654006877C2,
-				6EC4A663042A9654006877C2,
-				6EC4A664042A9654006877C2,
-				6EA0B3AF0544A9CC006877C2,
-				6E79040104FD5ED900EEC080,
-			);
-			isa = PBXGroup;
-			name = Rootless;
-			path = ../../../miext/rootless;
-			refType = 2;
-			sourceTree = SOURCE_ROOT;
-		};
-		6EC4A65D042A9654006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = rootless.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A65E042A9654006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rootlessCommon.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A65F042A9654006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = rootlessCommon.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A660042A9654006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = rootlessWindow.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A661042A9654006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rootlessScreen.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A662042A9654006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rootlessWindow.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A663042A9654006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rootlessGC.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A664042A9654006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = rootlessValTree.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EC4A66D042A97FC006877C2 = {
-			children = (
-				6EF471A004478DE0006877C2,
-				6E6656F3048832F9006877C2,
-				6E6656F0048832EC006877C2,
-				6E6656F1048832EC006877C2,
-				6E6656F2048832EC006877C2,
-				6ECF218404589E4D006877C2,
-				6E97A0F2050798B100B8294C,
-				6ECF218604589F40006877C2,
-				6EF4719E04478B08006877C2,
-				6EDDB2DF04508B2C006877C2,
-				6EF471A204479263006877C2,
-				6EF471A404479263006877C2,
-				6E6656EC048832CF006877C2,
-				6E6656ED048832CF006877C2,
-				6EF471A504479263006877C2,
-				6EF471A304479263006877C2,
-			);
-			isa = PBXGroup;
-			path = xpr;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6ECF218404589E4D006877C2 = {
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = xpr.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6ECF218604589F40006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = xprCursor.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EDDB2DF04508B2C006877C2 = {
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = xprScreen.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EE1214104968658006877C2 = {
-			children = (
-				6EE1214304968692006877C2,
-				6EE1214404968692006877C2,
-				6EE1214204968692006877C2,
-				6E97A0F305079B6500B8294C,
-				6EE1214504968692006877C2,
-				6EE1214604968692006877C2,
-			);
-			isa = PBXGroup;
-			path = cr;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EE1214204968692006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = cr.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EE1214304968692006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.objc;
-			path = XView.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EE1214404968692006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = XView.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EE1214504968692006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.objc;
-			path = crFrame.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EE1214604968692006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.objc;
-			path = crScreen.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EE9B21604E859C200CA7FEA = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = applewm.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EF065C003D4EE19006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXHeadersBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF065C103D4EE19006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXResourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF065C203D4EE19006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXSourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF065C303D4EE19006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXFrameworksBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF065C403D4EE19006877C2 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXRezBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF065C503D4EE19006877C2 = {
-			buildPhases = (
-				6EF065C003D4EE19006877C2,
-				6EF065C103D4EE19006877C2,
-				6EF065C203D4EE19006877C2,
-				6EF065C303D4EE19006877C2,
-				6EF065C403D4EE19006877C2,
-			);
-			buildSettings = {
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = glxMesa;
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
-				WRAPPER_EXTENSION = bundle;
-			};
-			dependencies = (
-			);
-			isa = PBXBundleTarget;
-			name = glxMesa;
-			productInstallPath = "$(USER_LIBRARY_DIR)/Bundles";
-			productName = glxMesa;
-			productReference = 6EF065C603D4EE19006877C2;
-			productSettingsXML = "<?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>CFBundleExecutable</key>
-	<string>glxMesa</string>
-	<key>CFBundleGetInfoString</key>
-	<string></string>
-	<key>CFBundleIconFile</key>
-	<string></string>
-	<key>CFBundleIdentifier</key>
-	<string></string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundleName</key>
-	<string>GLX bundle with Mesa</string>
-	<key>CFBundlePackageType</key>
-	<string>BNDL</string>
-	<key>CFBundleShortVersionString</key>
-	<string>0.1</string>
-	<key>CFBundleSignature</key>
-	<string>????</string>
-	<key>CFBundleVersion</key>
-	<string>0.1</string>
-</dict>
-</plist>
-";
-		};
-		6EF065C603D4EE19006877C2 = {
-			explicitFileType = wrapper.cfbundle;
-			isa = PBXFileReference;
-			path = glxMesa.bundle;
-			refType = 3;
-			sourceTree = BUILT_PRODUCTS_DIR;
-		};
-		6EF065C703D4EE19006877C2 = {
-			isa = PBXTargetDependency;
-			target = 6EF065C503D4EE19006877C2;
-			targetProxy = 6E4CAF660702464F001A7398;
-		};
-		6EF065C903D4F0CA006877C2 = {
-			isa = PBXTargetDependency;
-			target = 6EF7C58603D3BC6D00000104;
-			targetProxy = 6E4CAF630702464F001A7398;
-		};
-		6EF4719E04478B08006877C2 = {
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = xprFrame.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EF471A004478DE0006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = Xplugin.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EF471A204479263006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = "x-hash.c";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EF471A304479263006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = "x-list.h";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EF471A404479263006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = "x-hash.h";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EF471A504479263006877C2 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = "x-list.c";
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		6EF7C58103D3BC6D00000104 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXHeadersBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF7C58203D3BC6D00000104 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXResourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF7C58303D3BC6D00000104 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXSourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF7C58403D3BC6D00000104 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXFrameworksBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF7C58503D3BC6D00000104 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXRezBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		6EF7C58603D3BC6D00000104 = {
-			buildPhases = (
-				6EF7C58103D3BC6D00000104,
-				6EF7C58203D3BC6D00000104,
-				6EF7C58303D3BC6D00000104,
-				6EF7C58403D3BC6D00000104,
-				6EF7C58503D3BC6D00000104,
-			);
-			buildSettings = {
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = glxAGL;
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
-				WRAPPER_EXTENSION = bundle;
-			};
-			dependencies = (
-			);
-			isa = PBXBundleTarget;
-			name = glxAGL;
-			productName = glxAGL;
-			productReference = 6EF7C58703D3BC6D00000104;
-			productSettingsXML = "<?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>CFBundleExecutable</key>
-	<string>glxAGL</string>
-	<key>CFBundleGetInfoString</key>
-	<string></string>
-	<key>CFBundleIconFile</key>
-	<string></string>
-	<key>CFBundleIdentifier</key>
-	<string></string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundleName</key>
-	<string>GLX bundle using AGL framework</string>
-	<key>CFBundlePackageType</key>
-	<string>BNDL</string>
-	<key>CFBundleShortVersionString</key>
-	<string>0.1</string>
-	<key>CFBundleSignature</key>
-	<string>????</string>
-	<key>CFBundleVersion</key>
-	<string>0.1</string>
-</dict>
-</plist>
-";
-		};
-		6EF7C58703D3BC6D00000104 = {
-			explicitFileType = wrapper.cfbundle;
-			isa = PBXFileReference;
-			path = glxAGL.bundle;
-			refType = 3;
-			sourceTree = BUILT_PRODUCTS_DIR;
-		};
-//6E0
-//6E1
-//6E2
-//6E3
-//6E4
-//F50
-//F51
-//F52
-//F53
-//F54
-		F51BF62A02026DAF01000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = Portuguese;
-			path = Portuguese.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F51BF62B02026DDA01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Portuguese;
-			path = Portuguese.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F51BF62C02026E0601000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Portuguese;
-			path = Portuguese.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F51BF62D02026E1C01000001 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Portuguese;
-			path = Portuguese.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F51BF62E02026E3501000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = Portuguese;
-			path = Portuguese.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F51BF62F02026E5C01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = Portuguese;
-			path = Portuguese.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F51BF63002026E8D01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Portuguese;
-			path = Portuguese.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5269C2D01D5BC3501000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = pseudoramiX.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5269C2E01D5BC3501000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = pseudoramiX.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F53321390193CB6A01000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = German;
-			path = German.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533213A0193CBA201000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = German;
-			path = German.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533213B0193CBB401000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = German;
-			path = German.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533213C0193CBC901000001 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = German;
-			path = German.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533213D0193CBE001000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = German;
-			path = German.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533213E0193CBF401000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = German;
-			path = German.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533213F0193CC2501000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = German;
-			path = German.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F53321400193CCF001000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.framework;
-			name = ApplicationServices.framework;
-			path = /System/Library/Frameworks/ApplicationServices.framework;
-			refType = 0;
-			sourceTree = "<absolute>";
-		};
-		F53321410193CCF001000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.framework;
-			name = CoreAudio.framework;
-			path = /System/Library/Frameworks/CoreAudio.framework;
-			refType = 0;
-			sourceTree = "<absolute>";
-		};
-		F533214201A4B3CE01000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = Dutch;
-			path = Dutch.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533214301A4B3F001000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Dutch;
-			path = Dutch.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533214401A4B40F01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Dutch;
-			path = Dutch.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533214501A4B42501000001 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Dutch;
-			path = Dutch.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533214601A4B45401000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = Dutch;
-			path = Dutch.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533214701A4B48301000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = Dutch;
-			path = Dutch.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F533214801A4B4D701000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Dutch;
-			path = Dutch.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F54BF6EA017D500901000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			path = startXClients.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F54BF6EC017D506E01000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.script.sh;
-			path = startXClients;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F54BF6ED017D506E01000001 = {
-			fileRef = F54BF6EC017D506E01000001;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F5582948015DAD3B01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.h;
-			path = quartzCommon.h;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5614B3B0251124C01000114 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = fullscreen.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5614B3D025112D901000114 = {
-			children = (
-				F5614B3B0251124C01000114,
-				3576829A0077B8F17F000001,
-				0338412F0083BFE57F000001,
-			);
-			isa = PBXGroup;
-			path = fullscreen;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F587E16001924C1D01000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = Swedish;
-			path = Swedish.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F587E16101924C2F01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Swedish;
-			path = Swedish.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F587E16201924C5301000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Swedish;
-			path = Swedish.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F587E16301924C5E01000001 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Swedish;
-			path = Swedish.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F587E16401924C6901000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = Swedish;
-			path = Swedish.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F587E16501924C7401000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = Swedish;
-			path = Swedish.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F587E16601924C9D01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Swedish;
-			path = Swedish.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F58D65DB018F793801000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = French;
-			path = French.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F58D65DC018F794D01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = French;
-			path = French.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F58D65DD018F798F01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = French;
-			path = French.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F58D65DE018F79A001000001 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = French;
-			path = French.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F58D65DF018F79B101000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = French;
-			path = French.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F58D65E0018F79C001000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = French;
-			path = French.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F58D65E1018F79E001000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = French;
-			path = French.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5A94EF10314BAC70100011B = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.c.c;
-			path = darwinEvents.c;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD25CC5B5E96601000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = Spanish;
-			path = Spanish.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD25DC5B5E97701000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Spanish;
-			path = Spanish.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD25EC5B5E98D01000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = Spanish;
-			path = Spanish.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD25FC5B5E9AA01000001 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Spanish;
-			path = Spanish.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD260C5B5E9DF01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = Spanish;
-			path = Spanish.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD261C5B5EA2001000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = Spanish;
-			path = Spanish.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD262C5B5EA4D01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = Spanish;
-			path = Spanish.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD263C5BE031F01000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = text.rtf;
-			name = ko;
-			path = ko.lproj/Credits.rtf;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD264C5BE035B01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = ko;
-			path = ko.lproj/InfoPlist.strings.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD265C5BE038601000001 = {
-			isa = PBXFileReference;
-			lastKnownFileType = wrapper.nib;
-			name = ko;
-			path = ko.lproj/MainMenu.nib;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD266C5BE03C501000001 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = ko;
-			path = ko.lproj/Localizable.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD267C5BE03FC01000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = sourcecode.cpp.cpp;
-			name = ko;
-			path = ko.lproj/XDarwinHelp.html.cpp;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD268C5BE046401000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.html;
-			name = ko;
-			path = ko.lproj/XDarwinHelp.html;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-		F5ACD269C5BE049301000001 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			lastKnownFileType = text.plist.strings;
-			name = ko;
-			path = ko.lproj/InfoPlist.strings;
-			refType = 4;
-			sourceTree = "<group>";
-		};
-	};
-	rootObject = 29B97313FDCFA39411CA2CEA;
-}
diff --git a/hw/darwin/quartz/XDarwinStartup.c b/hw/darwin/quartz/XDarwinStartup.c
deleted file mode 100644
index 3ad4898..0000000
--- a/hw/darwin/quartz/XDarwinStartup.c
+++ /dev/null
@@ -1,166 +0,0 @@
-/**************************************************************
- *
- * Startup program for Darwin X servers
- *
- * This program selects the appropriate X server to launch:
- *  XDarwin         IOKit X server (default)
- *  XDarwinQuartz   A soft link to the Quartz X server
- *                  executable (-quartz etc. option)
- *
- * If told to idle, the program will simply pause and not
- * launch any X server. This is to support startx being
- * run by XDarwin.app.
- *
- **************************************************************/
-/*
- * Copyright (c) 2001-2002 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, 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
- * TORREY T. LYONS 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 Torrey T. Lyons shall not
- * be used in advertising or otherwise to promote the sale, use or other
- * dealings in this Software without prior written authorization from
- * Torrey T. Lyons.
- */
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <unistd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <sys/syslimits.h>
-#include <ApplicationServices/ApplicationServices.h>
-
-// Macros to build the path name
-#ifndef XBINDIR
-#define XBINDIR /usr/X11/bin
-#endif
-#define STR(s) #s
-#define XSTRPATH(s) STR(s) "/"
-#define XPATH(file) XSTRPATH(XBINDIR) STR(file)
-
-int main(
-    int         argc,
-    char        *argv[] )
-{
-    int         i, j, quartzMode = -1;
-    char        **newargv;
-
-    // Check if we are going to run in Quartz mode or idle
-    // to support startx from the Quartz server. The last
-    // parameter in the list is the one used.
-    for (i = argc-1; i; i--) {
-        if (!strcmp(argv[i], "-idle")) {
-            pause();
-            return 0;
-
-        } else if (!strcmp(argv[i], "-quartz") ||
-                   !strcmp(argv[i], "-rootless") ||
-                   !strcmp(argv[i], "-fullscreen"))
-        {
-            quartzMode = 1;
-            break;
-
-        } else if (!strcmp(argv[i], "-iokit")) {
-            quartzMode = 0;
-            break;
-        }
-    }
-
-    if (quartzMode == -1) {
-#ifdef HAS_CG_MACH_PORT
-        // Check if the CoreGraphics window server is running.
-        // Mike Paquette says this is the fastest way to determine if it is running.
-        CFMachPortRef cgMachPortRef = CGWindowServerCFMachPort();
-        if (cgMachPortRef == NULL)
-            quartzMode = 0;
-        else
-            quartzMode = 1;
-#else
-        // On older systems we assume IOKit mode.
-        quartzMode = 0;
-#endif
-    }
-
-    if (quartzMode) {
-        // Launch the X server for the quartz modes
-
-        char quartzPath[PATH_MAX+1];
-        int pathLength;
-        OSStatus theStatus;
-        CFURLRef appURL;
-        CFStringRef appPath;
-        Boolean success;
-
-        // Build the new argument list
-        newargv = (char **) malloc((argc+2) * sizeof(char *));
-        for (j = argc; j; j--)
-            newargv[j] = argv[j];
-        newargv[argc] = "-nostartx";
-        newargv[argc+1] = NULL;
-
-        // Use the XDarwinQuartz soft link if it is valid
-        pathLength = readlink(XPATH(XDarwinQuartz), quartzPath, PATH_MAX);
-        if (pathLength != -1) {
-            quartzPath[pathLength] = '\0';
-            newargv[0] = quartzPath;
-            execv(newargv[0], newargv);
-        }
-
-        // Otherwise query LaunchServices for the location of the XDarwin application
-        theStatus = LSFindApplicationForInfo(kLSUnknownCreator,
-                                             CFSTR("org.x.x11"),
-                                             NULL, NULL, &appURL);
-        if (theStatus) {
-            fprintf(stderr, "Could not find the XDarwin application. (Error = 0x%lx)\n", theStatus);
-            fprintf(stderr, "Launch XDarwin once from the Finder.\n");
-            return theStatus;
-        }
-
-        appPath = CFURLCopyFileSystemPath (appURL, kCFURLPOSIXPathStyle);
-        success = CFStringGetCString(appPath, quartzPath, PATH_MAX, CFStringGetSystemEncoding());
-        if (! success) {
-            fprintf(stderr, "Could not find path to XDarwin application.\n");
-            return success;
-        }
-
-        // Launch the XDarwin application
-        strncat(quartzPath, "/Contents/MacOS/XDarwin", PATH_MAX);
-        newargv[0] = quartzPath;
-        execv(newargv[0], newargv);
-        fprintf(stderr, "Could not start XDarwin application at %s.\n", newargv[0]);
-        return errno;
-
-    } else {
-
-        // Build the new argument list
-        newargv = (char **) malloc((argc+1) * sizeof(char *));
-        for (j = argc; j; j--)
-            newargv[j] = argv[j];
-        newargv[0] = "XDarwin";
-        newargv[argc] = NULL;
-    
-        // Launch the IOKit X server
-        execvp(newargv[0], newargv);
-        fprintf(stderr, "Could not start XDarwin IOKit X server.\n");
-        return errno;
-    }
-}
diff --git a/hw/darwin/quartz/XDarwinStartup.man b/hw/darwin/quartz/XDarwinStartup.man
deleted file mode 100644
index 1ad3bbc..0000000
--- a/hw/darwin/quartz/XDarwinStartup.man
+++ /dev/null
@@ -1,74 +0,0 @@
-.TH XDarwinStartup 1
-.SH NAME
-XDarwinStartup - Startup program for the XDarwin X window server
-.SH SYNOPSIS
-.B XDarwinStartup
-[\fI-iokit\fP]
-[\fI-fullscreen\fP]
-[\fI-rootless\fP]
-[\fI-quartz\fP]
-[\fI-idle\fP]
-[\fIoptions\fP]
-.SH DESCRIPTION
-The \fIXDarwin(1)\fP X window server can be run in a variety of different
-modes and is actually two different executables. The IOKit X server,
-XDarwin, is used when running from the console. It is most commonly
-located in __XBinDir__. The Quartz X server, for running in parallel with
-Aqua, is a full-fledged Mac OS X application that can be started from
-the Finder. Its application bundle is XDarwin.app, which is typically
-located in /Applications.
-.I XDarwinStartup
-allows easy switching between these X servers and auto-detection of the
-appropriate one to use when launching from the command line.
-When run without any arguments,
-.I XDarwinStartup
-will start the Quartz X server if the Core Graphics window server
-is currently running. Otherwise it will start the IOKit X server.
-.PP
-To locate the Quartz X server,
-.I XDarwinStartup
-will try to read the soft link at __XBinDir__/XDarwinQuartz.
-This is typically a soft link to the executable of the XDarwin.app
-application. If this fails,
-.I XDarwinStartup
-will call Launch Services to locate XDarwin.app.
-.PP
-To start the IOKit X server,
-.I XDarwinStartup
-will run the XDarwin executable, which should be present in the
-user's path.
-.SH OPTIONS
-.I XDarwinStartup
-accepts and passes on all options to the X server it
-launches. In addition the following options have specific effects:
-.TP 8
-.B \-iokit
-Launch the IOKit X server.
-.TP 8
-.B \-fullscreen
-Launch the Quartz X server to run in full screen mode.
-.TP 8
-.B \-rootless
-Launch the Quartz X server to run in rootless mode.
-.TP 8
-.B \-quartz
-Launch the Quartz X server.
-.TP 8
-.B \-idle
-Pause and do nothing. This option is used by XDarwin.app when it is
-started from the Finder.
-.SH FILES
-.TP 30
-__XBinDir__/XDarwin
-IOKit mode X server
-.TP 30
-/Applications/XDarwin.app
-Quartz mode X server
-.TP 30
-__XBinDir__/XDarwinQuartz
-Soft link to Quartz mode X server executable
-.SH SEE ALSO 
-XDarwin(1)
-.SH BUGS
-The path to XDarwinQuartz should not be hard coded. 
-
diff --git a/hw/darwin/quartz/XServer.h b/hw/darwin/quartz/XServer.h
deleted file mode 100644
index 030ccb5..0000000
--- a/hw/darwin/quartz/XServer.h
+++ /dev/null
@@ -1,136 +0,0 @@
-//
-//  XServer.h
-//
-/*
- * Copyright (c) 2001 Andreas Monitzer. All Rights Reserved.
- * Copyright (c) 2002-2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, 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 BOOL xBOOL
-#include <X11/Xproto.h>
-#undef BOOL
-
-#import <Cocoa/Cocoa.h>
-
- at interface XServer : NSObject {
-    // Server state
-    int serverState;
-    NSRecursiveLock *serverLock;
-    NSMutableArray *pendingClients;
-    BOOL serverVisible;
-    BOOL rootlessMenuBarVisible;
-    BOOL queueShowServer;
-    BOOL quitWithoutQuery;
-    BOOL pendingAppQuitReply;
-    UInt32 mouseState;
-    unsigned short swallowedKey;
-    BOOL sendServerEvents;
-    BOOL x11Active;
-
-    // Aqua interface
-    IBOutlet NSWindow *modeWindow;
-    IBOutlet NSButton *startupModeButton;
-    IBOutlet NSButton *startFullScreenButton;
-    IBOutlet NSButton *startRootlessButton;
-    IBOutlet NSWindow *helpWindow;
-    IBOutlet NSButton *startupHelpButton;
-    IBOutlet NSPanel *switchWindow;
-
-    // Menu elements setable by Apple-WM extension
-    IBOutlet NSMenu *windowMenu;
-    IBOutlet NSMenuItem *windowSeparator;
-    IBOutlet NSMenu *dockMenu;
-    int checkedWindowItem;
-}
-
-- (id)init;
-
-- (BOOL)translateEvent:(NSEvent *)anEvent;
-- (BOOL)getMousePosition:(xEvent *)xe fromEvent:(NSEvent *)anEvent;
-
-- (NSString *)makeSafePath:(NSString *)path;
-
-- (BOOL)loadDisplayBundle;
-- (void)startX;
-- (void)finishStartX;
-- (BOOL)startXClients;
-- (void)runClient:(NSString *)filename;
-- (void)run;
-- (void)toggle;
-- (void)showServer:(BOOL)show;
-- (void)forceShowServer:(BOOL)show;
-- (void)setRootClip:(BOOL)enable;
-- (void)readPasteboard;
-- (void)writePasteboard;
-- (void)quitServer;
-- (void)sendXEvent:(xEvent *)xe;
-- (void)sendShowHide:(BOOL)show;
-- (void)clientProcessDone:(int)clientStatus;
-- (void)activateX11:(BOOL)state;
-- (void)windowBecameKey:(NSNotification *)notification;
-- (void)setX11WindowList:(NSArray *)list;
-- (void)setX11WindowCheck:(NSNumber *)nn;
-
-// Aqua interface actions
-- (IBAction)startFullScreen:(id)sender;
-- (IBAction)startRootless:(id)sender;
-- (IBAction)closeHelpAndShow:(id)sender;
-- (IBAction)showSwitchPanel:(id)sender;
-- (IBAction)showAction:(id)sender;
-- (IBAction)itemSelected:(id)sender;
-- (IBAction)nextWindow:(id)sender;
-- (IBAction)previousWindow:(id)sender;
-- (IBAction)performClose:(id)sender;
-- (IBAction)performMiniaturize:(id)sender;
-- (IBAction)performZoom:(id)sender;
-- (IBAction)bringAllToFront:(id)sender;
-- (IBAction)copy:(id)sender;
-
-// NSApplication delegate
-- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
-- (void)applicationWillTerminate:(NSNotification *)aNotification;
-- (void)applicationDidFinishLaunching:(NSNotification *)aNotification;
-- (void)applicationDidHide:(NSNotification *)aNotification;
-- (void)applicationDidUnhide:(NSNotification *)aNotification;
-- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag;
-- (void)applicationWillResignActive:(NSNotification *)aNotification;
-- (void)applicationWillBecomeActive:(NSNotification *)aNotification;
-- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename;
-
-// NSPort delegate
-- (void)handlePortMessage:(NSPortMessage *)portMessage;
-
- at end
-
-// X server states
-enum {
-    server_NotStarted,
-    server_Starting,
-    server_Running,
-    server_Quitting,
-    server_Done
-};
diff --git a/hw/darwin/quartz/XServer.m b/hw/darwin/quartz/XServer.m
deleted file mode 100644
index 0587415..0000000
--- a/hw/darwin/quartz/XServer.m
+++ /dev/null
@@ -1,1539 +0,0 @@
-//
-//  XServer.m
-//
-//  This class handles the interaction between the Cocoa front-end
-//  and the Darwin X server thread.
-//
-//  Created by Andreas Monitzer on January 6, 2001.
-//
-/*
- * Copyright (c) 2001 Andreas Monitzer. All Rights Reserved.
- * Copyright (c) 2002-2005 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, 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.
- */
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-#include "quartzCommon.h"
-
-#define BOOL xBOOL
-#include "X11/X.h"
-#include "X11/Xproto.h"
-#include "os.h"
-#include "opaque.h"
-#include "darwin.h"
-#include "quartz.h"
-#define _APPLEWM_SERVER_
-#include "X11/extensions/applewm.h"
-#include "applewmExt.h"
-#undef BOOL
-
-#import "XServer.h"
-#import "Preferences.h"
-
-#include <unistd.h>
-#include <stdio.h>
-#include <sys/syslimits.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <pwd.h>
-#include <signal.h>
-#include <fcntl.h>
-
-// For power management notifications
-#import <mach/mach_port.h>
-#import <mach/mach_interface.h>
-#import <mach/mach_init.h>
-#import <IOKit/pwr_mgt/IOPMLib.h>
-#import <IOKit/IOMessage.h>
-
-// Types of shells
-enum {
-    shell_Unknown,
-    shell_Bourne,
-    shell_C
-};
-
-typedef struct {
-    char *name;
-    int type;
-} shellList_t;
-
-static shellList_t const shellList[] = {
-    { "csh",    shell_C },          // standard C shell
-    { "tcsh",   shell_C },          // ... needs no introduction
-    { "sh",     shell_Bourne },     // standard Bourne shell
-    { "zsh",    shell_Bourne },     // Z shell
-    { "bash",   shell_Bourne },     // GNU Bourne again shell
-    { NULL,     shell_Unknown }
-};
-
-extern int argcGlobal;
-extern char **argvGlobal;
-extern char **envpGlobal;
-extern int main(int argc, char *argv[], char *envp[]);
-extern void HideMenuBar(void);
-extern void ShowMenuBar(void);
-static void childDone(int sig);
-static void powerDidChange(void *x, io_service_t y, natural_t messageType,
-                           void *messageArgument);
-
-static NSPort *signalPort;
-static NSPort *returnPort;
-static NSPortMessage *signalMessage;
-static pid_t clientPID;
-static XServer *oneXServer;
-static NSRect aquaMenuBarBox;
-static io_connect_t root_port;
-
-
- at implementation XServer
-
-- (id)init
-{
-    self = [super init];
-    oneXServer = self;
-
-    serverState = server_NotStarted;
-    serverLock = [[NSRecursiveLock alloc] init];
-    pendingClients = nil;
-    clientPID = 0;
-    sendServerEvents = NO;
-    x11Active = YES;
-    serverVisible = NO;
-    rootlessMenuBarVisible = YES;
-    queueShowServer = YES;
-    quartzServerQuitting = NO;
-    pendingAppQuitReply = NO;
-    mouseState = 0;
-
-    // set up a port to safely send messages to main thread from server thread
-    signalPort = [[NSPort port] retain];
-    returnPort = [[NSPort port] retain];
-    signalMessage = [[NSPortMessage alloc] initWithSendPort:signalPort
-                    receivePort:returnPort components:nil];
-
-    // set up receiving end
-    [signalPort setDelegate:self];
-    [[NSRunLoop currentRunLoop] addPort:signalPort
-                                forMode:NSDefaultRunLoopMode];
-    [[NSRunLoop currentRunLoop] addPort:signalPort
-                                forMode:NSModalPanelRunLoopMode];
-
-    return self;
-}
-
-- (NSApplicationTerminateReply)
-        applicationShouldTerminate:(NSApplication *)sender
-{
-    // Quit if the X server is not running
-    if ([serverLock tryLock]) {
-        quartzServerQuitting = YES;
-        serverState = server_Done;
-        if (clientPID != 0)
-            kill(clientPID, SIGINT);
-        return NSTerminateNow;
-    }
-
-    // Hide the X server and stop sending it events
-    [self showServer:NO];
-    sendServerEvents = NO;
-
-    if (!quitWithoutQuery && (clientPID != 0 || !quartzStartClients)) {
-        int but;
-
-        but = NSRunAlertPanel(NSLocalizedString(@"Quit X server?",@""),
-                              NSLocalizedString(@"Quitting the X server will terminate any running X Window System programs.",@""),
-                              NSLocalizedString(@"Quit",@""),
-                              NSLocalizedString(@"Cancel",@""),
-                              nil);
-
-        switch (but) {
-            case NSAlertDefaultReturn:		// quit
-                break;
-            case NSAlertAlternateReturn:	// cancel
-                if (serverState == server_Running)
-                    sendServerEvents = YES;
-                return NSTerminateCancel;
-        }
-    }
-
-    quartzServerQuitting = YES;
-    if (clientPID != 0)
-        kill(clientPID, SIGINT);
-
-    // At this point the X server is either running or starting.
-    if (serverState == server_Starting) {
-        // Quit will be queued later when server is running
-        pendingAppQuitReply = YES;
-        return NSTerminateLater;
-    } else if (serverState == server_Running) {
-        [self quitServer];
-    }
-
-    return NSTerminateNow;
-}
-
-// Ensure that everything has quit cleanly
-- (void)applicationWillTerminate:(NSNotification *)aNotification
-{
-    // Make sure the client process has finished
-    if (clientPID != 0) {
-        NSLog(@"Waiting on client process...");
-        sleep(2);
-
-        // If the client process hasn't finished yet, kill it off
-        if (clientPID != 0) {
-            int clientStatus;
-            NSLog(@"Killing client process...");
-            killpg(clientPID, SIGKILL);
-            waitpid(clientPID, &clientStatus, 0);
-        }
-    }
-
-    // Wait until the X server thread quits
-    [serverLock lock];
-}
-
-// returns YES when event was handled
-- (BOOL)translateEvent:(NSEvent *)anEvent
-{
-    xEvent xe;
-    static BOOL mouse1Pressed = NO;
-    NSEventType type;
-    unsigned int flags;
-
-    if (!sendServerEvents) {
-        return NO;
-    }
-
-    type  = [anEvent type];
-    flags = [anEvent modifierFlags];
-
-    if (!quartzRootless) {
-        // Check for switch keypress
-        if ((type == NSKeyDown) && (![anEvent isARepeat]) &&
-            ([anEvent keyCode] == [Preferences keyCode]))
-        {
-            unsigned int switchFlags = [Preferences modifiers];
-
-            // Switch if all the switch modifiers are pressed, while none are
-            // pressed that should not be, except for caps lock.
-            if (((flags & switchFlags) == switchFlags) &&
-                ((flags & ~(switchFlags | NSAlphaShiftKeyMask)) == 0))
-            {
-                [self toggle];
-                return YES;
-            }
-        }
-
-        if (!serverVisible)
-            return NO;
-    }
-
-    memset(&xe, 0, sizeof(xe));
-
-    switch (type) {
-        case NSLeftMouseUp:
-            if (quartzRootless && !mouse1Pressed) {
-                // MouseUp after MouseDown in menu - ignore
-                return NO;
-            }
-            mouse1Pressed = NO;
-            [self getMousePosition:&xe fromEvent:anEvent];
-            xe.u.u.type = ButtonRelease;
-            xe.u.u.detail = 1;
-            break;
-
-        case NSLeftMouseDown:
-            if (quartzRootless) {
-                // Check that event is in X11 window
-                if (!quartzProcs->IsX11Window([anEvent window],
-                                              [anEvent windowNumber]))
-                {
-                    if (x11Active)
-                        [self activateX11:NO];
-                    return NO;
-                } else {
-                    if (!x11Active)
-                        [self activateX11:YES];
-                }
-            }
-            mouse1Pressed = YES;
-            [self getMousePosition:&xe fromEvent:anEvent];
-            xe.u.u.type = ButtonPress;
-            xe.u.u.detail = 1;
-            break;
-
-        case NSRightMouseUp:
-            [self getMousePosition:&xe fromEvent:anEvent];
-            xe.u.u.type = ButtonRelease;
-            xe.u.u.detail = 3;
-            break;
-
-        case NSRightMouseDown:
-            [self getMousePosition:&xe fromEvent:anEvent];
-            xe.u.u.type = ButtonPress;
-            xe.u.u.detail = 3;
-            break;
-
-        case NSOtherMouseUp:
-        {
-            int hwButton = [anEvent buttonNumber];
-
-            [self getMousePosition:&xe fromEvent:anEvent];
-            xe.u.u.type = ButtonRelease;
-            xe.u.u.detail = (hwButton == 2) ? hwButton : hwButton + 1;
-            break;
-        }
-
-        case NSOtherMouseDown:
-        {
-            int hwButton = [anEvent buttonNumber];
-
-            [self getMousePosition:&xe fromEvent:anEvent];
-            xe.u.u.type = ButtonPress;
-            xe.u.u.detail = (hwButton == 2) ? hwButton : hwButton + 1;
-            break;
-        }
-
-        case NSMouseMoved:
-        case NSLeftMouseDragged:
-        case NSRightMouseDragged:
-        case NSOtherMouseDragged:
-            [self getMousePosition:&xe fromEvent:anEvent];
-            xe.u.u.type = MotionNotify;
-            break;
-
-        case NSScrollWheel:
-            [self getMousePosition:&xe fromEvent:anEvent];
-            xe.u.u.type = kXDarwinScrollWheel;
-            xe.u.clientMessage.u.s.shorts0 = [anEvent deltaX] +
-                                             [anEvent deltaY];
-            break;
-
-        case NSKeyDown:
-        case NSKeyUp:
-            if (!x11Active) {
-                swallowedKey = 0;
-                return NO;
-            }
-
-            if (type == NSKeyDown) {
-                // If the mouse is not on the valid X display area,
-                // don't send the X server key events.
-                if (![self getMousePosition:&xe fromEvent:nil]) {
-                    swallowedKey = [anEvent keyCode];
-                    return NO;
-                }
-
-                // See if there are any global shortcuts for this key combo.
-                if (quartzEnableKeyEquivalents
-                    && [[NSApp mainMenu] performKeyEquivalent:anEvent])
-                {
-                    swallowedKey = [anEvent keyCode];
-                    return YES;
-                }
-            } else {
-                // If the down key event was a valid key combo,
-                // don't pass the up event to X11.
-                if (swallowedKey != 0 && [anEvent keyCode] == swallowedKey) {
-                    swallowedKey = 0;
-                    return NO;
-                }
-            }
-
-            xe.u.u.type = (type == NSKeyDown) ? KeyPress : KeyRelease;
-            xe.u.u.detail = [anEvent keyCode];
-            break;
-
-        case NSFlagsChanged:
-            if (!x11Active)
-                return NO;
-            xe.u.u.type = kXDarwinUpdateModifiers;
-            xe.u.clientMessage.u.l.longs0 = flags;
-            break;
-
-        default:
-            return NO;
-    }
-
-    [self sendXEvent:&xe];
-
-    // Rootless: Send first NSLeftMouseDown to Cocoa windows and views so
-    // window ordering can be suppressed.
-    // Don't pass further events - they (incorrectly?) bring the window
-    // forward no matter what.
-    if (quartzRootless  &&
-        (type == NSLeftMouseDown || type == NSLeftMouseUp) &&
-        [anEvent clickCount] == 1 && [anEvent window])
-    {
-        return NO;
-    }
-
-    return YES;
-}
-
-// Return mouse coordinates, inverting y coordinate.
-// The coordinates are extracted from an event or the current mouse position.
-// For rootless mode, the menu bar is treated as not part of the usable
-// X display area and the cursor position is adjusted accordingly.
-// Returns YES if the cursor is not in the menu bar.
-- (BOOL)getMousePosition:(xEvent *)xe fromEvent:(NSEvent *)anEvent
-{
-    NSPoint pt;
-
-    if (anEvent) {
-        NSWindow *eventWindow = [anEvent window];
-
-        if (eventWindow) {
-            pt = [anEvent locationInWindow];
-            pt.x += [eventWindow frame].origin.x;
-            pt.y += [eventWindow frame].origin.y;
-        } else {
-            pt = [NSEvent mouseLocation];
-        }
-    } else {
-        pt = [NSEvent mouseLocation];
-    }
-
-    xe->u.keyButtonPointer.rootX = (int)(pt.x);
-
-    if (quartzRootless && NSMouseInRect(pt, aquaMenuBarBox, NO)) {
-        // mouse in menu bar - tell X11 that it's just below instead
-        xe->u.keyButtonPointer.rootY = aquaMenuBarHeight;
-        return NO;
-    } else {
-        xe->u.keyButtonPointer.rootY =
-            NSHeight([[NSScreen mainScreen] frame]) - (int)(pt.y);
-        return YES;
-    }
-}
-
-
-// Make a safe path
-//
-// Return the path in single quotes in case there are problematic characters in it.
-// We still have to worry about there being single quotes in the path. So, replace
-// all instances of the ' character in the path with '\''.
-- (NSString *)makeSafePath:(NSString *)path
-{
-    NSMutableString *safePath = [NSMutableString stringWithString:path];
-    NSRange aRange = NSMakeRange(0, [safePath length]);
-
-    while (aRange.length) {
-        aRange = [safePath rangeOfString:@"'" options:0 range:aRange];
-        if (!aRange.length)
-            break;
-        [safePath replaceCharactersInRange:aRange
-                        withString:@"\'\\'\'"];
-        aRange.location += 4;
-        aRange.length = [safePath length] - aRange.location;
-    }
-
-    safePath = [NSMutableString stringWithFormat:@"'%@'", safePath];
-
-    return safePath;
-}
-
-
-- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
-{
-    // Block SIGPIPE
-    // SIGPIPE repeatably killed the (rootless) server when closing a
-    // dozen xterms in rapid succession. Those SIGPIPEs should have been
-    // sent to the X server thread, which ignores them, but somehow they
-    // ended up in this thread instead.
-    {
-        sigset_t set;
-        sigemptyset(&set);
-        sigaddset(&set, SIGPIPE);
-        // pthread_sigmask not implemented yet
-        // pthread_sigmask(SIG_BLOCK, &set, NULL);
-        sigprocmask(SIG_BLOCK, &set, NULL);
-    }
-
-    if (quartzRootless == -1) {
-        // The display mode was not set from the command line.
-        // Show mode pick panel?
-        if ([Preferences modeWindow]) {
-            if ([Preferences rootless])
-                [startRootlessButton setKeyEquivalent:@"\r"];
-            else
-                [startFullScreenButton setKeyEquivalent:@"\r"];
-            [modeWindow makeKeyAndOrderFront:nil];
-        } else {
-            // Otherwise use default mode
-            quartzRootless = [Preferences rootless];
-            [self startX];
-        }
-    } else {
-        [self startX];
-    }
-}
-
-
-// Load the appropriate display mode bundle
-- (BOOL)loadDisplayBundle
-{
-    if (quartzRootless) {
-        NSEnumerator *enumerator = [[Preferences displayModeBundles]
-                                            objectEnumerator];
-        NSString *bundleName;
-
-        while ((bundleName = [enumerator nextObject])) {
-            if (QuartzLoadDisplayBundle([bundleName cString]))
-                return YES;
-        }
-
-        return NO;
-    } else {
-        return QuartzLoadDisplayBundle("fullscreen.bundle");
-    }
-}
-
-
-// Start the X server thread and the client process
-- (void)startX
-{
-    NSDictionary *appDictionary;
-    NSString *appVersion;
-
-    [modeWindow close];
-
-    // Calculate the height of the menu bar so rootless mode can avoid it
-    if (quartzRootless) {
-        aquaMenuBarHeight = NSHeight([[NSScreen mainScreen] frame]) -
-                            NSMaxY([[NSScreen mainScreen] visibleFrame]) - 1;
-        aquaMenuBarBox =
-            NSMakeRect(0, NSMaxY([[NSScreen mainScreen] visibleFrame]) + 1,
-                       NSWidth([[NSScreen mainScreen] frame]),
-                       aquaMenuBarHeight);
-    }
-
-    // Write the XDarwin version to the console log
-    appDictionary = [[NSBundle mainBundle] infoDictionary];
-    appVersion = [appDictionary objectForKey:@"CFBundleShortVersionString"];
-    if (appVersion)
-        NSLog(@"\n%@", appVersion);
-    else
-        NSLog(@"No version");
-
-    if (![self loadDisplayBundle])
-        [NSApp terminate:nil];
-
-    if (quartzRootless) {
-        // We need to track whether the key window is an X11 window
-        [[NSNotificationCenter defaultCenter]
-                addObserver:self
-                selector:@selector(windowBecameKey:)
-                name:NSWindowDidBecomeKeyNotification
-                object:nil];
-
-        // Request notification of screen layout changes even when this
-        // is not the active application
-        [[NSDistributedNotificationCenter defaultCenter]
-                addObserver:self
-                selector:@selector(applicationDidChangeScreenParameters:)
-                name:NSApplicationDidChangeScreenParametersNotification
-                object:nil];
-    }
-
-    // Start the X server thread
-    serverState = server_Starting;
-    [NSThread detachNewThreadSelector:@selector(run) toTarget:self
-              withObject:nil];
-
-    // Start the X clients if started from GUI
-    if (quartzStartClients) {
-        [self startXClients];
-    }
-
-    if (quartzRootless) {
-        // There is no help window for rootless; just start
-        [helpWindow close];
-        helpWindow = nil;
-    } else {
-        IONotificationPortRef notify;
-        io_object_t anIterator;
-
-        // Register for system power notifications
-        root_port = IORegisterForSystemPower(0, &notify, powerDidChange,
-                                             &anIterator);
-        if (root_port) {
-            CFRunLoopAddSource([[NSRunLoop currentRunLoop] getCFRunLoop],
-                               IONotificationPortGetRunLoopSource(notify),
-                               kCFRunLoopDefaultMode);
-        } else {
-            NSLog(@"Failed to register for system power notifications.");
-        }
-        
-        // Show the X switch window if not using dock icon switching
-        if (![Preferences dockSwitch])
-            [switchWindow orderFront:nil];
-
-        if ([Preferences startupHelp]) {
-            // display the full screen mode help
-            [helpWindow makeKeyAndOrderFront:nil];
-            queueShowServer = NO;
-        } else {
-            // start running full screen and make sure X is visible
-            ShowMenuBar();
-            [self closeHelpAndShow:nil];
-        }
-    }
-}
-
-// Finish starting the X server thread
-// This includes anything that must be done after the X server is
-// ready to process events after the first or subsequent generations.
-- (void)finishStartX
-{
-    sendServerEvents = YES;
-    serverState = server_Running;
-
-    if (quartzRootless) {
-        [self forceShowServer:[NSApp isActive]];
-    } else {
-        [self forceShowServer:queueShowServer];
-    }
-
-    if (quartzServerQuitting) {
-        [self quitServer];
-        if (pendingAppQuitReply)
-            [NSApp replyToApplicationShouldTerminate:YES];
-        return;
-    }
-
-    if (pendingClients) {
-        NSEnumerator *enumerator = [pendingClients objectEnumerator];
-        NSString *filename;
-
-        while ((filename = [enumerator nextObject])) {
-            [self runClient:filename];
-        }
-
-        [pendingClients release];
-        pendingClients = nil;
-    }
-}
-
-// Start the first X clients in a separate process
-- (BOOL)startXClients
-{
-    struct passwd *passwdUser;
-    NSString *shellPath, *dashShellName, *commandStr, *startXPath;
-    NSString *safeStartXPath;
-    NSBundle *thisBundle;
-    const char *shellPathStr, *newargv[3], *shellNameStr;
-    int fd[2], outFD, length, shellType, i;
-
-    // Register to catch the signal when the client processs finishes
-    signal(SIGCHLD, childDone);
-
-    // Get user's password database entry
-    passwdUser = getpwuid(getuid());
-
-    // Find the shell to use
-    if ([Preferences useDefaultShell])
-        shellPath = [NSString stringWithCString:passwdUser->pw_shell];
-    else
-        shellPath = [Preferences shellString];
-
-    dashShellName = [NSString stringWithFormat:@"-%@",
-                            [shellPath lastPathComponent]];
-    shellPathStr = [shellPath cString];
-    shellNameStr = [[shellPath lastPathComponent] cString];
-
-    if (access(shellPathStr, X_OK)) {
-        NSLog(@"Shell %s is not valid!", shellPathStr);
-        return NO;
-    }
-
-    // Find the type of shell
-    for (i = 0; shellList[i].name; i++) {
-        if (!strcmp(shellNameStr, shellList[i].name))
-            break;
-    }
-    shellType = shellList[i].type;
-
-    newargv[0] = [dashShellName cString];
-    if (shellType == shell_Bourne) {
-        // Bourne shells need to be told they are interactive to make
-        // sure they read all their initialization files.
-        newargv[1] = "-i";
-        newargv[2] = NULL;
-    } else {
-        newargv[1] = NULL;
-    }
-
-    // Create a pipe to communicate with the X client process
-    NSAssert(pipe(fd) == 0, @"Could not create new pipe.");
-
-    // Open a file descriptor for writing to stdout and stderr
-    outFD = open("/dev/console", O_WRONLY, 0);
-    if (outFD == -1) {
-        outFD = open("/dev/null", O_WRONLY, 0);
-        NSAssert(outFD != -1, @"Could not open shell output.");
-    }
-
-    // Fork process to start X clients in user's default shell
-    // Sadly we can't use NSTask because we need to start a login shell.
-    // Login shells are started by passing "-" as the first character of
-    // argument 0. NSTask forces argument 0 to be the shell's name.
-    clientPID = vfork();
-    if (clientPID == 0) {
-
-        // Inside the new process:
-        if (fd[0] != STDIN_FILENO) {
-            dup2(fd[0], STDIN_FILENO);      // Take stdin from pipe
-            close(fd[0]);
-        }
-        close(fd[1]);                       // Close write end of pipe
-        if (outFD == STDOUT_FILENO) {       // Setup stdout and stderr
-            dup2(outFD, STDERR_FILENO);
-        } else if (outFD == STDERR_FILENO) {
-            dup2(outFD, STDOUT_FILENO);
-        } else {
-            dup2(outFD, STDERR_FILENO);
-            dup2(outFD, STDOUT_FILENO);
-            close(outFD);
-        }
-
-        // Setup environment
-        setenv("HOME", passwdUser->pw_dir, 1);
-        setenv("SHELL", shellPathStr, 1);
-        setenv("LOGNAME", passwdUser->pw_name, 1);
-        setenv("USER", passwdUser->pw_name, 1);
-        setenv("TERM", "unknown", 1);
-        if (chdir(passwdUser->pw_dir))	// Change to user's home dir
-            NSLog(@"Could not change to user's home directory.");
-
-        execv(shellPathStr, (char * const *)newargv);	// Start user's shell
-
-        NSLog(@"Could not start X client process with errno = %i.", errno);
-        _exit(127);
-    }
-
-    // In parent process:
-    close(fd[0]);	// Close read end of pipe
-    close(outFD);	// Close output file descriptor
-
-    thisBundle = [NSBundle bundleForClass:[self class]];
-    startXPath = [thisBundle pathForResource:@"startXClients" ofType:nil];
-    if (!startXPath) {
-        NSLog(@"Could not find startXClients in application bundle!");
-        return NO;
-    }
-
-    safeStartXPath = [self makeSafePath:startXPath];
-
-    if ([Preferences addToPath]) {
-        commandStr = [NSString stringWithFormat:@"%@ :%d %@\n",
-                        safeStartXPath, [Preferences display],
-                        [Preferences addToPathString]];
-    } else {
-        commandStr = [NSString stringWithFormat:@"%@ :%d\n",
-                        safeStartXPath, [Preferences display]];
-    }
-
-    length = [commandStr cStringLength];
-    if (write(fd[1], [commandStr cString], length) != length) {
-        NSLog(@"Write to X client process failed.");
-        return NO;
-    }
-
-    // Close the pipe so that shell will terminate when xinit quits
-    close(fd[1]);
-
-    return YES;
-}
-
-// Start the specified client in its own task
-// FIXME: This should be unified with startXClients
-- (void)runClient:(NSString *)filename
-{
-    const char *command = [[self makeSafePath:filename] UTF8String];
-    const char *shell;
-    const char *argv[5];
-    int child1, child2 = 0;
-    int status;
-
-    shell = getenv("SHELL");
-    if (shell == NULL)
-        shell = "/bin/bash";
-
-    /* At least [ba]sh, [t]csh and zsh all work with this syntax. We
-       need to use an interactive shell to force it to load the user's
-       environment. */
-
-    argv[0] = shell;
-    argv[1] = "-i";
-    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], *tem;
-
-            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);
-
-                /* cd $HOME */
-                tem = getenv("HOME");
-                if (tem != NULL)
-                    chdir(tem);
-
-                /* Setup environment */
-//              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/X11/bin", tem);
-                else
-                    snprintf(buf, sizeof(buf), "/bin:/usr/bin:/usr/X11/bin");
-                setenv("PATH", buf, TRUE);
-
-                execvp(argv[0], (char **const) argv);
-
-                _exit(2);
-
-            default:                            /* parent (child1) */
-                _exit(0);
-            }
-            break;
-
-        default:                                /* parent */
-            waitpid(child1, &status, 0);
-    }
-}
-
-// Run the X server thread
-- (void)run
-{
-    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
-    [serverLock lock];
-    main(argcGlobal, argvGlobal, envpGlobal);
-    serverVisible = NO;
-    [pool release];
-    [serverLock unlock];
-    QuartzMessageMainThread(kQuartzServerDied, nil, 0);
-}
-
-// Full screen mode was picked in the mode pick panel
-- (IBAction)startFullScreen:(id)sender
-{
-    [Preferences setModeWindow:[startupModeButton intValue]];
-    [Preferences saveToDisk];
-    quartzRootless = FALSE;
-    [self startX];
-}
-
-// Rootless mode was picked in the mode pick panel
-- (IBAction)startRootless:(id)sender
-{
-    [Preferences setModeWindow:[startupModeButton intValue]];
-    [Preferences saveToDisk];
-    quartzRootless = TRUE;
-    [self startX];
-}
-
-// Close the help splash screen and show the X server
-- (IBAction)closeHelpAndShow:(id)sender
-{
-    if (sender) {
-        int helpVal = [startupHelpButton intValue];
-        [Preferences setStartupHelp:helpVal];
-        [Preferences saveToDisk];
-    }
-    [helpWindow close];
-    helpWindow = nil;
-
-    [self forceShowServer:YES];
-    [NSApp activateIgnoringOtherApps:YES];
-}
-
-// Show the Aqua-X11 switch panel useful for fullscreen mode
-- (IBAction)showSwitchPanel:(id)sender
-{
-    [switchWindow orderFront:nil];
-}
-
-// Show the X server when sent message from GUI
-- (IBAction)showAction:(id)sender
-{
-    [self forceShowServer:YES];
-}
-
-// Show or hide the X server or menu bar in rootless mode
-- (void)toggle
-{
-    if (quartzRootless) {
-#if 0
-        // FIXME: Remove or add option to not dodge menubar
-        if (rootlessMenuBarVisible)
-            HideMenuBar();
-        else
-            ShowMenuBar();
-        rootlessMenuBarVisible = !rootlessMenuBarVisible;
-#endif
-    } else {
-        [self showServer:!serverVisible];
-    }
-}
-
-// Show or hide the X server on screen
-- (void)showServer:(BOOL)show
-{
-    // Do not show or hide multiple times in a row
-    if (serverVisible == show)
-        return;
-
-    if (sendServerEvents) {
-        [self sendShowHide:show];
-    } else if (serverState == server_Starting) {
-        queueShowServer = show;
-    }
-}
-
-// Show or hide the X server irregardless of the current state
-- (void)forceShowServer:(BOOL)show
-{
-    serverVisible = !show;
-    [self showServer:show];
-}
-
-// Tell the X server to show or hide itself.
-// This ignores the current X server visible state.
-//
-// In full screen mode, the order we do things is important and must be
-// preserved between the threads. X drawing operations have to be performed
-// in the X server thread. It appears that we have the additional
-// constraint that we must hide and show the menu bar in the main thread.
-//
-// To show the X server:
-//   1. Capture the displays. (Main thread)
-//   2. Hide the menu bar. (Must be in main thread)
-//   3. Send event to X server thread to redraw X screen.
-//   4. Redraw the X screen. (Must be in X server thread)
-//
-// To hide the X server:
-//   1. Send event to X server thread to stop drawing.
-//   2. Stop drawing to the X screen. (Must be in X server thread)
-//   3. Message main thread that drawing is stopped.
-//   4. If main thread still wants X server hidden:
-//     a. Release the displays. (Main thread)
-//     b. Unhide the menu bar. (Must be in main thread)
-//   Otherwise we have already queued an event to start drawing again.
-//
-- (void)sendShowHide:(BOOL)show
-{
-    xEvent xe;
-
-    [self getMousePosition:&xe fromEvent:nil];
-
-    if (show) {
-        if (!quartzRootless) {
-            quartzProcs->CaptureScreens();
-            HideMenuBar();
-        }
-        [self activateX11:YES];
-
-        // the mouse location will have moved; track it
-        xe.u.u.type = MotionNotify;
-        [self sendXEvent:&xe];
-
-        // inform the X server of the current modifier state
-        xe.u.u.type = kXDarwinUpdateModifiers;
-        xe.u.clientMessage.u.l.longs0 = [[NSApp currentEvent] modifierFlags];
-        [self sendXEvent:&xe];
-
-        // If there is no AppleWM-aware cut and paste manager, do what we can.
-        if ((AppleWMSelectedEvents() & AppleWMPasteboardNotifyMask) == 0) {
-            // put the pasteboard into the X cut buffer
-            [self readPasteboard];
-        }
-    } else {
-        // If there is no AppleWM-aware cut and paste manager, do what we can.
-        if ((AppleWMSelectedEvents() & AppleWMPasteboardNotifyMask) == 0) {
-            // put the X cut buffer on the pasteboard
-            [self writePasteboard];
-        }
-
-        [self activateX11:NO];
-    }
-
-    serverVisible = show;
-}
-
-// Enable or disable rendering to the X screen
-- (void)setRootClip:(BOOL)enable
-{
-    xEvent xe;
-
-    xe.u.u.type = kXDarwinSetRootClip;
-    xe.u.clientMessage.u.l.longs0 = enable;
-    [self sendXEvent:&xe];
-}
-
-// Tell the X server to read from the pasteboard into the X cut buffer
-- (void)readPasteboard
-{
-    xEvent xe;
-
-    xe.u.u.type = kXDarwinReadPasteboard;
-    [self sendXEvent:&xe];
-}
-
-// Tell the X server to write the X cut buffer into the pasteboard
-- (void)writePasteboard
-{
-    xEvent xe;
-
-    xe.u.u.type = kXDarwinWritePasteboard;
-    [self sendXEvent:&xe];
-}
-
-- (void)quitServer
-{
-    xEvent xe;
-
-    xe.u.u.type = kXDarwinQuit;
-    [self sendXEvent:&xe];
-
-    // Revert to the Mac OS X arrow cursor. The main thread sets the cursor
-    // and it won't be responding to future requests to change it.
-    [[NSCursor arrowCursor] set];
-
-    serverState = server_Quitting;
-}
-
-- (void)sendXEvent:(xEvent *)xe
-{
-    // This field should be filled in for every event
-    xe->u.keyButtonPointer.time = GetTimeInMillis();
-
-    DarwinEQEnqueue(xe);
-}
-
-// Handle messages from the X server thread
-- (void)handlePortMessage:(NSPortMessage *)portMessage
-{
-    unsigned msg = [portMessage msgid];
-
-    switch (msg) {
-        case kQuartzServerHidden:
-            // Make sure the X server wasn't queued to be shown again while
-            // the hide was pending.
-            if (!quartzRootless && !serverVisible) {
-                quartzProcs->ReleaseScreens();
-                ShowMenuBar();
-            }
-            break;
-
-        case kQuartzServerStarted:
-            [self finishStartX];
-            break;
-
-        case kQuartzServerDied:
-            sendServerEvents = NO;
-            serverState = server_Done;
-            if (!quartzServerQuitting) {
-                [NSApp terminate:nil];	// quit if we aren't already
-            }
-            break;
-
-        case kQuartzCursorUpdate:
-            if (quartzProcs->CursorUpdate)
-                quartzProcs->CursorUpdate();
-            break;
-
-        case kQuartzPostEvent:
-        {
-            const xEvent *xe = [[[portMessage components] lastObject] bytes];
-            DarwinEQEnqueue(xe);
-            break;
-        }
-
-        case kQuartzSetWindowMenu:
-        {
-            NSArray *list;
-            [[[portMessage components] lastObject] getBytes:&list];
-            [self setX11WindowList:list];
-            [list release];
-            break;
-        }
-
-        case kQuartzSetWindowMenuCheck:
-        {
-            int n;
-            [[[portMessage components] lastObject] getBytes:&n];
-            [self setX11WindowCheck:[NSNumber numberWithInt:n]];
-            break;
-        }
-
-        case kQuartzSetFrontProcess:
-            [NSApp activateIgnoringOtherApps:YES];
-            break;
-
-        case kQuartzSetCanQuit:
-        {
-            int n;
-            [[[portMessage components] lastObject] getBytes:&n];
-            quitWithoutQuery = (BOOL) n;
-            break;
-        }
-
-        default:
-            NSLog(@"Unknown message from server thread.");
-    }
-}
-
-// Quit the X server when the X client process finishes
-- (void)clientProcessDone:(int)clientStatus
-{
-    if (WIFEXITED(clientStatus)) {
-        int exitStatus = WEXITSTATUS(clientStatus);
-        if (exitStatus != 0)
-            NSLog(@"X client process terminated with status %i.", exitStatus);
-    } else {
-        NSLog(@"X client process terminated abnormally.");
-    }
-
-    if (!quartzServerQuitting) {
-        [NSApp terminate:nil];	// quit if we aren't already
-    }
-}
-
-// User selected an X11 window from a menu
-- (IBAction)itemSelected:(id)sender
-{
-    xEvent xe;
-
-    [NSApp activateIgnoringOtherApps:YES];
-
-    // Notify the client of the change through the X server thread
-    xe.u.u.type = kXDarwinControllerNotify;
-    xe.u.clientMessage.u.l.longs0 = AppleWMWindowMenuItem;
-    xe.u.clientMessage.u.l.longs1 = [sender tag];
-    [self sendXEvent:&xe];
-}
-
-// User selected Next from window menu
-- (IBAction)nextWindow:(id)sender
-{
-    QuartzMessageServerThread(kXDarwinControllerNotify, 1,
-                              AppleWMNextWindow);
-}
-
-// User selected Previous from window menu
-- (IBAction)previousWindow:(id)sender
-{
-    QuartzMessageServerThread(kXDarwinControllerNotify, 1,
-                              AppleWMPreviousWindow);
-}
-
-/*
- * The XPR implementation handles close, minimize, and zoom actions for X11
- * windows here, while CR handles these in the NSWindow class.
- */
-
-// Handle Close from window menu for X11 window in XPR implementation
-- (IBAction)performClose:(id)sender
-{
-    QuartzMessageServerThread(kXDarwinControllerNotify, 1,
-                              AppleWMCloseWindow);
-}
-
-// Handle Minimize from window menu for X11 window in XPR implementation
-- (IBAction)performMiniaturize:(id)sender
-{
-    QuartzMessageServerThread(kXDarwinControllerNotify, 1,
-                              AppleWMMinimizeWindow);
-}
-
-// Handle Zoom from window menu for X11 window in XPR implementation
-- (IBAction)performZoom:(id)sender
-{
-    QuartzMessageServerThread(kXDarwinControllerNotify, 1,
-                              AppleWMZoomWindow);
-}
-
-// Handle "Bring All to Front" from window menu
-- (IBAction)bringAllToFront:(id)sender
-{
-    if ((AppleWMSelectedEvents() & AppleWMControllerNotifyMask) != 0) {
-        QuartzMessageServerThread(kXDarwinControllerNotify, 1,
-                                  AppleWMBringAllToFront);
-    } else {
-        [NSApp arrangeInFront:nil];
-    }
-}
-
-// This ends up at the end of the responder chain.
-- (IBAction)copy:(id)sender
-{
-    QuartzMessageServerThread(kXDarwinPasteboardNotify, 1,
-                              AppleWMCopyToPasteboard);
-}
-
-// Set whether or not X11 is active and should receive all key events
-- (void)activateX11:(BOOL)state
-{
-    if (state) {
-        QuartzMessageServerThread(kXDarwinActivate, 0);
-    }
-    else {
-        QuartzMessageServerThread(kXDarwinDeactivate, 0);
-    }
-
-    x11Active = state;
-}
-
-// Some NSWindow became the key window
-- (void)windowBecameKey:(NSNotification *)notification
-{
-    NSWindow *window = [notification object];
-
-    if (quartzProcs->IsX11Window(window, [window windowNumber])) {
-        if (!x11Active)
-            [self activateX11:YES];
-    } else {
-        if (x11Active)
-            [self activateX11:NO];
-    }
-}
-
-// Set the Apple-WM specifiable part of the window menu
-- (void)setX11WindowList:(NSArray *)list
-{
-    NSMenuItem *item;
-    int first, count, i;
-    xEvent xe;
-
-    /* Work backwards so we don't mess up the indices */
-    first = [windowMenu indexOfItem:windowSeparator] + 1;
-    if (first > 0) {
-        count = [windowMenu numberOfItems];
-        for (i = count - 1; i >= first; i--)
-            [windowMenu removeItemAtIndex:i];
-    } else {
-        windowSeparator = (NSMenuItem *)[windowMenu addItemWithTitle:@""
-                                                    action:nil
-                                                    keyEquivalent:@""];
-    }
-
-    count = [dockMenu numberOfItems];
-    for (i = 0; i < count; i++)
-        [dockMenu removeItemAtIndex:0];
-
-    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 *)[windowMenu addItemWithTitle:name
-                                         action:@selector(itemSelected:)
-                                         keyEquivalent:shortcut];
-        [item setTarget:self];
-        [item setTag:i];
-        [item setEnabled:YES];
-
-        item = (NSMenuItem *)[dockMenu insertItemWithTitle:name
-                                       action:@selector(itemSelected:)
-                                       keyEquivalent:shortcut atIndex:i];
-        [item setTarget:self];
-        [item setTag:i];
-        [item setEnabled:YES];
-    }
-
-    if (checkedWindowItem >= 0 && checkedWindowItem < count)
-    {
-        item = (NSMenuItem *)[windowMenu itemAtIndex:first + checkedWindowItem];
-        [item setState:NSOnState];
-        item = (NSMenuItem *)[dockMenu itemAtIndex:checkedWindowItem];
-        [item setState:NSOnState];
-    }
-
-    // Notify the client of the change through the X server thread
-    xe.u.u.type = kXDarwinControllerNotify;
-    xe.u.clientMessage.u.l.longs0 = AppleWMWindowMenuNotify;
-    [self sendXEvent:&xe];
-}
-
-// Set the checked item on the Apple-WM specifiable window menu
-- (void)setX11WindowCheck:(NSNumber *)nn
-{
-    NSMenuItem *item;
-    int first, count;
-    int n = [nn intValue];
-
-    first = [windowMenu indexOfItem:windowSeparator] + 1;
-    count = [windowMenu numberOfItems] - first;
-
-    if (checkedWindowItem >= 0 && checkedWindowItem < count)
-    {
-        item = (NSMenuItem *)[windowMenu itemAtIndex:first + checkedWindowItem];
-        [item setState:NSOffState];
-        item = (NSMenuItem *)[dockMenu itemAtIndex:checkedWindowItem];
-        [item setState:NSOffState];
-    }
-    if (n >= 0 && n < count)
-    {
-        item = (NSMenuItem *)[windowMenu itemAtIndex:first + n];
-        [item setState:NSOnState];
-        item = (NSMenuItem *)[dockMenu itemAtIndex:n];
-        [item setState:NSOnState];
-    }
-    checkedWindowItem = n;
-}
-
-// Return whether or not a menu item should be enabled
-- (BOOL)validateMenuItem:(NSMenuItem *)item
-{
-    NSMenu *menu = [item menu];
-
-    if (menu == windowMenu && [item tag] == 30) {
-        // Mode switch panel is for fullscreen only
-        return !quartzRootless;
-    }
-    else if ((menu == windowMenu && [item tag] != 40) || menu == dockMenu) {
-        // The special window and dock menu items should not be active unless
-        // there is an AppleWM-aware window manager running.
-        return (AppleWMSelectedEvents() & AppleWMControllerNotifyMask) != 0;
-    }
-    else {
-        return TRUE;
-    }
-}
-
-/*
- * Application Delegate Methods
- */
-
-- (void)applicationDidChangeScreenParameters:(NSNotification *)aNotification
-{
-    if (quartzProcs->ScreenChanged)
-        quartzProcs->ScreenChanged();
-}
-
-- (void)applicationDidHide:(NSNotification *)aNotification
-{
-    if ((AppleWMSelectedEvents() & AppleWMControllerNotifyMask) != 0) {
-        QuartzMessageServerThread(kXDarwinControllerNotify, 1,
-                                  AppleWMHideAll);
-    } else {
-        if (quartzProcs->HideWindows)
-            quartzProcs->HideWindows(YES);
-    }
-}
-
-- (void)applicationDidUnhide:(NSNotification *)aNotification
-{
-    if ((AppleWMSelectedEvents() & AppleWMControllerNotifyMask) != 0) {
-        QuartzMessageServerThread(kXDarwinControllerNotify, 1,
-                                  AppleWMShowAll);
-    } else {
-        if (quartzProcs->HideWindows)
-            quartzProcs->HideWindows(NO);
-    }
-}
-
-// Called when the user clicks the application icon,
-// but not when Cmd-Tab is used.
-// Rootless: Don't switch until applicationWillBecomeActive.
-- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication
-            hasVisibleWindows:(BOOL)flag
-{
-    if ([Preferences dockSwitch] && !quartzRootless) {
-        [self showServer:YES];
-    }
-    return NO;
-}
-
-- (void)applicationWillResignActive:(NSNotification *)aNotification
-{
-    [self showServer:NO];
-}
-
-- (void)applicationWillBecomeActive:(NSNotification *)aNotification
-{
-    if (quartzRootless) {
-        [self showServer:YES];
-
-        // If there is no AppleWM-aware window manager, we can't allow
-        // interleaving of Aqua and X11 windows.
-        if ((AppleWMSelectedEvents() & AppleWMControllerNotifyMask) == 0) {
-            [NSApp arrangeInFront:nil];
-        }
-    }
-}
-
-// Called when the user opens a document type that we claim (ie. an X11 executable).
-- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
-{
-    if (serverState == server_Running) {
-        [self runClient:filename];
-        return YES;
-    }
-    else if (serverState == server_NotStarted || serverState == server_Starting) {
-        if ([filename UTF8String][0] != ':') {          // Ignore display names
-            if (!pendingClients) {
-                pendingClients = [[NSMutableArray alloc] initWithCapacity:1];
-            }
-            [pendingClients addObject:filename];
-            return YES;                 // Assume it will launch successfully
-        }
-        return NO;
-    }
-
-    // If the server is quitting or done,
-    // its too late to launch new clients this time.
-    return NO;
-}
-
- at end
-
-
-// Send a message to the main thread, which calls handlePortMessage in
-// response. Must only be called from the X server thread because
-// NSPort is not thread safe.
-void QuartzMessageMainThread(unsigned msg, void *data, unsigned length)
-{
-    if (length > 0) {
-        NSData *eventData = [NSData dataWithBytes:data length:length];
-        NSArray *eventArray = [NSArray arrayWithObject:eventData];
-        NSPortMessage *newMessage =
-                [[NSPortMessage alloc]
-                        initWithSendPort:signalPort
-                        receivePort:returnPort components:eventArray];
-        [newMessage setMsgid:msg];
-        [newMessage sendBeforeDate:[NSDate distantPast]];
-        [newMessage release];
-    } else {
-        [signalMessage setMsgid:msg];
-        [signalMessage sendBeforeDate:[NSDate distantPast]];
-    }
-}
-
-void
-QuartzSetWindowMenu(int nitems, const char **items,
-                    const char *shortcuts)
-{
-    NSMutableArray *array;
-    int i;
-
-    array = [[NSMutableArray alloc] initWithCapacity:nitems];
-
-    for (i = 0; i < nitems; i++) {
-        NSMutableArray *subarray = [NSMutableArray arrayWithCapacity:2];
-        NSString *string = [NSString stringWithUTF8String:items[i]];
-
-        [subarray addObject:string];
-
-        if (shortcuts[i] != 0) {
-            NSString *number = [NSString stringWithFormat:@"%d",
-                                         shortcuts[i]];
-            [subarray addObject:number];
-        } else
-            [subarray addObject:@""];
-
-        [array addObject:subarray];
-    }
-
-    /* Send the array of strings over to the main thread. */
-    /* Will be released in main thread. */
-    QuartzMessageMainThread(kQuartzSetWindowMenu, &array, sizeof(NSArray *));
-}
-
-// Handle SIGCHLD signals
-static void childDone(int sig)
-{
-    int clientStatus;
-
-    if (clientPID == 0)
-        return;
-
-    // Make sure it was the client task that finished
-    if (waitpid(clientPID, &clientStatus, WNOHANG) == clientPID) {
-        if (WIFSTOPPED(clientStatus))
-            return;
-        clientPID = 0;
-        [oneXServer clientProcessDone:clientStatus];
-    }
-}
-
-static void powerDidChange(
-    void *x,
-    io_service_t y,
-    natural_t messageType,
-    void *messageArgument)
-{
-    switch (messageType) {
-        case kIOMessageSystemWillSleep:
-            if (!quartzRootless) {
-                [oneXServer setRootClip:FALSE];
-            }
-            IOAllowPowerChange(root_port, (long)messageArgument);
-            break;
-        case kIOMessageCanSystemSleep:
-            IOAllowPowerChange(root_port, (long)messageArgument);
-            break;
-        case kIOMessageSystemHasPoweredOn:
-            if (!quartzRootless) {
-                [oneXServer setRootClip:TRUE];
-            }
-            break;
-    }
-
-}
commit ec84a4cef66a2b46ed71f9758c434ea629d2f270
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sun Nov 18 17:44:12 2007 -0800

    Added some DEBUG_LOG sauce to the XP_EVENT handling code

diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index 25f491a..739cefc 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -64,49 +64,49 @@ static void
 eventHandler(unsigned int type, const void *arg,
              unsigned int arg_size, void *data)
 {
-    switch (type)
-    {
+    switch (type) {
     case XP_EVENT_DISPLAY_CHANGED:
-      //      ErrorF("XP_EVENT_DISPLAY_MOVED\n");
-        QuartzMessageServerThread(kXDarwinDisplayChanged, 0);
-        break;
+      DEBUG_LOG("XP_EVENT_DISPLAY_CHANGED\n");
+      QuartzMessageServerThread(kXDarwinDisplayChanged, 0);
+      break;
 
     case XP_EVENT_WINDOW_STATE_CHANGED:
-      //      ErrorF("XP_EVENT_WINDOW_STATE_CHANGED\n");
-        if (arg_size >= sizeof(xp_window_state_event))
-        {
-            const xp_window_state_event *ws_arg = arg;
-
-            QuartzMessageServerThread(kXDarwinWindowState, 2,
-                                      ws_arg->id, ws_arg->state);
-        }
-        break;
+      DEBUG_LOG("XP_EVENT_WINDOW_STATE_CHANGED\n");
+      if (arg_size >= sizeof(xp_window_state_event)) {
+	const xp_window_state_event *ws_arg = arg;
+	
+	QuartzMessageServerThread(kXDarwinWindowState, 2,
+				  ws_arg->id, ws_arg->state);
+      }
+      break;
 
     case XP_EVENT_WINDOW_MOVED:
-      //      ErrorF("XP_EVENT_WINDOW_MOVED\n");
-        if (arg_size == sizeof(xp_window_id))
-        {
-            xp_window_id id = * (xp_window_id *) arg;
-	    WindowPtr pWin = xprGetXWindow(id);
-            QuartzMessageServerThread(kXDarwinWindowMoved, 1, pWin);
-        }
-        break;
-
+      DEBUG_LOG("XP_EVENT_WINDOW_MOVED\n");
+      if (arg_size == sizeof(xp_window_id))  {
+	xp_window_id id = * (xp_window_id *) arg;
+	WindowPtr pWin = xprGetXWindow(id);
+	QuartzMessageServerThread(kXDarwinWindowMoved, 1, pWin);
+      }
+      break;
+      
     case XP_EVENT_SURFACE_DESTROYED:
+      DEBUG_LOG("XP_EVENT_SURFACE_DESTROYED\n");
     case XP_EVENT_SURFACE_CHANGED:
-      //      ErrorF("XP_EVENT_SURFACE_MOVED\n");
-        if (arg_size == sizeof(xp_surface_id))
-        {
-            int kind;
-
-            if (type == XP_EVENT_SURFACE_DESTROYED)
-                kind = AppleDRISurfaceNotifyDestroyed;
-            else
-                kind = AppleDRISurfaceNotifyChanged;
-
-            DRISurfaceNotify(*(xp_surface_id *) arg, kind);
+      DEBUG_LOG("XP_EVENT_SURFACE_CHANGED\n");
+        if (arg_size == sizeof(xp_surface_id)) {
+	  int kind;
+	  
+	  if (type == XP_EVENT_SURFACE_DESTROYED)
+	    kind = AppleDRISurfaceNotifyDestroyed;
+	  else
+	    kind = AppleDRISurfaceNotifyChanged;
+	  
+	  DRISurfaceNotify(*(xp_surface_id *) arg, kind);
         }
         break;
+    default:
+      ErrorF("Unknown XP_EVENT type (%d) in xprScreen:eventHandler\n",
+	     type);
     }
 }
 
commit fd181254f85543558190140787dc7b41f6cf90db
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sun Nov 18 17:43:40 2007 -0800

    Disabled ALT_IS_MODE_SWITCH
    (just for joke, nothing more)

diff --git a/hw/darwin/darwinKeyboard.c b/hw/darwin/darwinKeyboard.c
index 111c98a..efa12b7 100644
--- a/hw/darwin/darwinKeyboard.c
+++ b/hw/darwin/darwinKeyboard.c
@@ -61,7 +61,7 @@
 #undef DUMP_DARWIN_KEYMAP
 
 /* Define this to use Alt for Mode_switch. */
-#define ALT_IS_MODE_SWITCH 1
+//#define ALT_IS_MODE_SWITCH 1
 
 #include <stdio.h>
 #include <stdlib.h>
commit 6ec763f52c661c033eb63f5cad95b90dde2120b3
Author: Jeremy Huddleston <jeremy at yuffie.local>
Date:   Sun Nov 18 03:03:39 2007 -0800

    Added --with-x11app-archs configure option
    This configure option's value is passed to xcodebuild in ARCHS, so we can easily choose architecture targets for X11.app

diff --git a/configure.ac b/configure.ac
index 1646e5b..492c870 100644
--- a/configure.ac
+++ b/configure.ac
@@ -512,6 +512,8 @@ AC_ARG_ENABLE(xvfb,    	      AS_HELP_STRING([--enable-xvfb], [Build Xvfb server
 AC_ARG_ENABLE(xnest,   	      AS_HELP_STRING([--enable-xnest], [Build Xnest server (default: no)]), [XNEST=$enableval], [XNEST=no])
 AC_ARG_ENABLE(xquartz,        AS_HELP_STRING([--enable-xquartz], [Build Xquartz server for OS-X (default: auto)]), [XQUARTZ=$enableval], [XQUARTZ=auto])
 AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app for Xquartz (default: auto)]), [X11APP=$enableval], [X11APP=auto])
+AC_ARG_WITH(x11app-archs,     AS_HELP_STRING([--with-x11app-archs=ARCHS], [Architectures to build X11.app for, space delimeted (default: "ppc i386")]), [X11APP_ARCHS=$enableval], [X11APP_ARCHS="ppc i386"])
+AC_SUBST([X11APP_ARCHS])
 AC_ARG_ENABLE(xwin,    	      AS_HELP_STRING([--enable-xwin], [Build XWin server (default: auto)]), [XWIN=$enableval], [XWIN=auto])
 AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
 AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (default: no)]), [XGL=$enableval], [XGL=no])
diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 0d3ee02..f82ed02 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -1,11 +1,11 @@
 AM_CFLAGS = @XORG_CFLAGS@
 AM_CPPFLAGS = @XORG_INCS@ -I$(top_srcdir)/Xext -I$(top_srcdir)/miext/rootless -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" -DHAVE_XORG_CONFIG_H -DXFree86Server -DINXQUARTZ
-  
+
 SUBDIRS = quartz utils
-  
+
 bin_PROGRAMS = Xquartz
 man1_MANS = apple/Xquartz.man
-  
+
 Xquartz_SOURCES = darwin.c \
 		  darwinEvents.c \
 		  darwinKeyboard.c \
@@ -43,7 +43,6 @@ Xquartz_LDADD = ./quartz/libXquartz.a \
 		$(top_builddir)/miext/rootless/accel/librlAccel.la \
 		$(DARWIN_LIBS) $(XSERVER_LIBS) -lXplugin
 
-
 Xquartz_LDFLAGS =  -XCClinker -Objc \
 		   -Wl,-u,_miDCInitialize \
 		   -Wl,-framework,Carbon \
@@ -57,16 +56,16 @@ if X11APP
 bin_SCRIPTS = x11app x11launcher
 
 x11app:
-	cd apple && xcodebuild CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)"
+	cd apple && xcodebuild CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)" ARCHS="$(X11APP_ARCHS)"
 
 x11launcher:
-	cd launcher && xcodebuild CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)"
+	cd launcher && xcodebuild CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)" ARCHS="$(X11APP_ARCHS)"
 
 x11app-install:
-	cd apple && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(prefix) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
+	cd apple && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(prefix) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO ARCHS="$(X11APP_ARCHS)"
 
 x11launcher-install:
-	cd launcher && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(APPLE_APPLICATIONS_DIR) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
+	cd launcher && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(APPLE_APPLICATIONS_DIR) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO ARCHS="$(X11APP_ARCHS)"
 
 x11app-clean:
 	rm -rf apple/build
commit 2ab1dd5e7456441f36dd3815804035d381e8cf75
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Fri Nov 16 16:07:17 2007 -0800

    From Jeremy: In my previous patch, I "overfixed" hook.c.  This patch
    removes the changes I made to the searching for loop since those are
    extraneous due to the remove function call in the delete for loop.

diff --git a/hw/darwin/quartz/xpr/x-hook.c b/hw/darwin/quartz/xpr/x-hook.c
index 2d9a564..84bf444 100644
--- a/hw/darwin/quartz/xpr/x-hook.c
+++ b/hw/darwin/quartz/xpr/x-hook.c
@@ -50,19 +50,12 @@ X_PFX (hook_remove) (x_list *lst, x_hook_function *fun, void *data)
 {
     x_list *node, *cell;
     x_list *to_delete = NULL;
-    x_list *prev = NULL;
 
-    for (node = lst; node != NULL; prev = node, node = node->next)
+    for (node = lst; node != NULL; node = node->next)
     {
 	cell = node->data;
 	if (CELL_FUN (cell) == fun && CELL_DATA (cell) == data)
-        {
 	    to_delete = X_PFX (list_prepend) (to_delete, cell);
-            if(lst == node)
-                lst = node->next;
-            else
-                prev->next = node->next;
-        }
     }
 
     for (node = to_delete; node != NULL; node = node->next)
commit 604e6afc8e63de887bebea767fdeb9e2b2aff8f8
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Nov 16 06:02:54 2007 -0800

    1.2a11

diff --git a/configure.ac b/configure.ac
index ab6b866..1646e5b 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.2a10, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a11, [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 --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index f36a5e2..38359e6 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -160,7 +160,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a10)",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a11)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
commit dc48ad4a45d37a7fc65a3a0455fccd4aca09962f
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Nov 16 05:36:51 2007 -0800

    More correctness fixes to fix compiler warnings.

diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 615ea8d..d1eb724 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -464,7 +464,7 @@ void DarwinModeProcessEvent(
 	  
         case kXDarwinWindowMoved:
 	  DEBUG_LOG("kXDarwinWindowMoved\n");
-            RootlessNativeWindowMoved (xe->u.clientMessage.u.l.longs0);
+	  RootlessNativeWindowMoved ((WindowPtr)xe->u.clientMessage.u.l.longs0);
 	    break;
 
         case kXDarwinToggleFullscreen:
diff --git a/hw/darwin/quartz/quartzCocoa.m b/hw/darwin/quartz/quartzCocoa.m
index c5e6e5c..46c61dc 100644
--- a/hw/darwin/quartz/quartzCocoa.m
+++ b/hw/darwin/quartz/quartzCocoa.m
@@ -123,9 +123,9 @@ int QuartzFSUseQDCursor(
  *  Clean out any autoreleased objects.
  */
 void QuartzBlockHandler(
-    void *blockData,
-    void *pTimeout,
-    void *pReadmask)
+    pointer blockData,
+    OSTimePtr pTimeout,
+    pointer pReadmask)
 {
     static NSAutoreleasePool *aPool = nil;
 
@@ -138,9 +138,9 @@ void QuartzBlockHandler(
  * QuartzWakeupHandler
  */
 void QuartzWakeupHandler(
-    void *blockData,
+    pointer blockData,
     int result,
-    void *pReadmask)
+    pointer pReadmask)
 {
     // nothing here
 }
diff --git a/hw/darwin/quartz/quartzCommon.h b/hw/darwin/quartz/quartzCommon.h
index f5dff66..f0d5a7a 100644
--- a/hw/darwin/quartz/quartzCommon.h
+++ b/hw/darwin/quartz/quartzCommon.h
@@ -46,6 +46,7 @@
 #undef Cursor
 #undef WindowPtr
 #undef Picture
+#include <X11/Xdefs.h>
 
 // Quartz specific per screen storage structure
 typedef struct {
@@ -87,8 +88,8 @@ void QuartzSetWindowMenu(int nitems, const char **items,
 void QuartzFSCapture(void);
 void QuartzFSRelease(void);
 int  QuartzFSUseQDCursor(int depth);
-void QuartzBlockHandler(void *blockData, void *pTimeout, void *pReadmask);
-void QuartzWakeupHandler(void *blockData, int result, void *pReadmask);
+void QuartzBlockHandler(pointer blockData, OSTimePtr pTimeout, pointer pReadmask);
+void QuartzWakeupHandler(pointer blockData, int result, pointer pReadmask);
 
 // Messages that can be sent to the main thread.
 enum {
diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index 49cd1c1..25f491a 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -88,13 +88,7 @@ eventHandler(unsigned int type, const void *arg,
         {
             xp_window_id id = * (xp_window_id *) arg;
 	    WindowPtr pWin = xprGetXWindow(id);
-	    BoxRec box;
-	    xp_error retval  = xp_get_window_bounds(id, &box);
-	    if (retval != Success) {
-	      ErrorF("Unable to find new bounds for window\n");
-	      break;
-	    }
-            QuartzMessageServerThread(kXDarwinWindowMoved, 3, pWin, box.x1, box.y1);
+            QuartzMessageServerThread(kXDarwinWindowMoved, 1, pWin);
         }
         break;
 
commit 213b51710c4a060ec5f04d1c96c82a5ba933cea9
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Nov 16 05:04:54 2007 -0800

    From Jeremy Huddleston:
    1) Fixed a bug where XQUARTZ was #defined when auto but not when --enable-xquartz
    2) Cleaned up missing #includes and function prototypes.
    3) Fixed some invalid C syntax problems
    4) Removed a bunch of dead code
    5) Cleaned up code to prevent some warnings
    6) Bugfix in xpr/x-hook.c - looks like someone just forgot to finish writing code for hook_remove()... I only noticed it because gcc -Wall complained about reaching the end of a non-void function... lucky for us gcc is smarter than we are.

diff --git a/configure.ac b/configure.ac
index 1eaf6ad..ab6b866 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1610,7 +1610,6 @@ if test "X$XQUARTZ" = Xauto; then
 		LDFLAGS=$save_LDFLAGS])
                 
 	if test "X$xorg_cv_Carbon_framework" = Xyes; then
-		AC_DEFINE([XQUARTZ],[1],[Have Quartz])
 		XQUARTZ=yes
 	else
 		XQUARTZ=no
@@ -1618,15 +1617,7 @@ if test "X$XQUARTZ" = Xauto; then
 fi
 
 if test "x$XQUARTZ" = xyes; then
-	if test "x$X11APP" = xauto; then
-		AC_MSG_CHECKING([whether to build X11.app])
-		if test "x$XQUARTZ" = xyes ; then
-			X11APP=yes
-		else
-			X11APP=no
-		fi
-		AC_MSG_RESULT([$X11APP])
-	fi
+	AC_DEFINE([XQUARTZ],[1],[Have Quartz])
 
 #	       glxAGL / glxCGL don't work yet
 #               AC_CACHE_CHECK([for AGL framework],xorg_cv_AGL_framework,[
@@ -1669,6 +1660,16 @@ if test "x$XQUARTZ" = xyes; then
                fi
 fi
 
+if test "x$X11APP" = xauto; then
+	AC_MSG_CHECKING([whether to build X11.app])
+	if test "x$XQUARTZ" = xyes ; then
+		X11APP=yes
+	else
+		X11APP=no
+	fi
+	AC_MSG_RESULT([$X11APP])
+fi
+
 if test "x$LAUNCHD" = xauto; then
 	# Do we want to have this default to on for Xquartz builds only or any time we have launchd (like Xnest or Xvfb on OS-X)
 	#AC_CHECK_PROG(LAUNCHD, [launchd], [yes], [no])
diff --git a/dix/main.c b/dix/main.c
index 50dbb67..7f7b094 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -260,11 +260,6 @@ main(int argc, char *argv[], char *envp[])
     /* Quartz support on Mac OS X requires that the Cocoa event loop be in
      * the main thread. This allows the X server main to be called again
      * from another thread. */
-
-    /* TODO: Put some runtime conditioning on this, so it doesn't get
-     * executed by Xvfb, Xnest, Xfake, Xephyr, etc when built at the same
-     * time as Xquartz
-     */
     DarwinHandleGUI(argc, argv, envp);
 #endif
 
diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index e23a3d1..0d3ee02 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -1,5 +1,5 @@
 AM_CFLAGS = @XORG_CFLAGS@
-AM_CPPFLAGS = @XORG_INCS@ -I../../miext/rootless -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" -DHAVE_XORG_CONFIG_H -DXFree86Server -DINXQUARTZ
+AM_CPPFLAGS = @XORG_INCS@ -I$(top_srcdir)/Xext -I$(top_srcdir)/miext/rootless -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" -DHAVE_XORG_CONFIG_H -DXFree86Server -DINXQUARTZ
   
 SUBDIRS = quartz utils
   
diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index df42c1b..f36a5e2 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -47,6 +47,10 @@
 #include <unistd.h>
 #include <pthread.h>
 
+#include "rootlessCommon.h"
+
+WindowPtr xprGetXWindowFromAppKit(int windowNumber); // xpr/xprFrame.c
+
 #define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
 
 int X11EnableKeyEquivalents = TRUE;
@@ -577,7 +581,7 @@ cfarray_to_nsarray (CFArrayRef in)
 			ret = CFBooleanGetValue (value);
 		else if (CFGetTypeID (value) == CFStringGetTypeID ())
 		{
-			const char *tem = [(NSString *) value lossyCString];
+			const char *tem = [(NSString *) value UTF8String];
 			if (strcasecmp (tem, "true") == 0 || strcasecmp (tem, "yes") == 0)
 				ret = YES;
 			else
diff --git a/hw/darwin/darwin.c b/hw/darwin/darwin.c
index 789b0e2..c721ca1 100644
--- a/hw/darwin/darwin.c
+++ b/hw/darwin/darwin.c
@@ -69,6 +69,11 @@
 #include <IOKit/hidsystem/IOHIDLib.h>
 #include <IOKit/hidsystem/ev_keymap.h>
 
+#ifdef MITSHM
+#define _XSHM_SERVER_
+#include <X11/extensions/XShm.h>
+#endif
+
 #include "darwin.h"
 #include "darwinClut8.h"
 
@@ -186,7 +191,9 @@ static Bool DarwinAddScreen(
 
     // allocate space for private per screen storage
     dfb = xalloc(sizeof(DarwinFramebufferRec));
-    SCREEN_PRIV(pScreen) = dfb;
+
+    // SCREEN_PRIV(pScreen) = dfb;
+    pScreen->devPrivates[darwinScreenIndex].ptr = dfb;
 
     // setup hardware/mode specific details
     ret = DarwinModeAddScreen(foundIndex, pScreen);
@@ -342,7 +349,7 @@ static int DarwinMouseProc(
     DeviceIntPtr    pPointer,
     int             what )
 {
-    char map[6];
+    CARD8 map[6];
 
     switch (what) {
 
@@ -699,10 +706,30 @@ void ddxInitGlobals(void)
  */
 int ddxProcessArgument( int argc, char *argv[], int i )
 {
-    int numDone;
+    if ( !strcmp( argv[i], "-fullscreen" ) ) {
+        ErrorF( "Running full screen in parallel with Mac OS X Quartz window server.\n" );
+        return 1;
+    }
+
+    if ( !strcmp( argv[i], "-rootless" ) ) {
+        ErrorF( "Running rootless inside Mac OS X window server.\n" );
+        return 1;
+    }
 
-    if ((numDone = DarwinModeProcessArgument( argc, argv, i )))
-        return numDone;
+    if ( !strcmp( argv[i], "-quartz" ) ) {
+        ErrorF( "Running in parallel with Mac OS X Quartz window server.\n" );
+        return 1;
+    }
+
+    // The Mac OS X front end uses this argument, which we just ignore here.
+    if ( !strcmp( argv[i], "-nostartx" ) ) {
+        return 1;
+    }
+
+    // This command line arg is passed when launched from the Aqua GUI.
+    if ( !strncmp( argv[i], "-psn_", 5 ) ) {
+        return 1;
+    }
 
     if ( !strcmp( argv[i], "-fakebuttons" ) ) {
         darwinFakeButtons = TRUE;
diff --git a/hw/darwin/darwin.h b/hw/darwin/darwin.h
index 25bba20..14443b9 100644
--- a/hw/darwin/darwin.h
+++ b/hw/darwin/darwin.h
@@ -72,7 +72,6 @@ Bool DarwinModeAddScreen(int index, ScreenPtr pScreen);
 Bool DarwinModeSetupScreen(int index, ScreenPtr pScreen);
 void DarwinModeInitOutput(int argc,char **argv);
 void DarwinModeInitInput(int argc, char **argv);
-int DarwinModeProcessArgument(int argc, char *argv[], int i);
 void DarwinModeProcessEvent(xEvent *xe);
 void DarwinModeGiveUp(void);
 void DarwinModeBell(int volume, DeviceIntPtr pDevice, pointer ctrl, int class);
diff --git a/hw/darwin/darwinEvents.c b/hw/darwin/darwinEvents.c
index 0fb5c9a..4201e0e 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -235,7 +235,7 @@ static void DarwinUpdateModifiers(
 void DarwinReleaseModifiers(void) {
   KeySym *map = NULL;
   xEvent ke;
-  int i = 0, j = 0, nevents = 0; 
+  int i = 0; 
  
   DEBUG_LOG("DarwinReleaseModifiers(%p)\n", &keyInfo.keyMap);
   
diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
index 26bc8eb..838af29 100644
--- a/hw/darwin/quartz/Makefile.am
+++ b/hw/darwin/quartz/Makefile.am
@@ -2,7 +2,7 @@ noinst_LIBRARIES = libXQuartz.a
 
 AM_CFLAGS = @XORG_CFLAGS@
 AM_OBJCFLAGS = @XORG_CFLAGS@
-AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/.. @XORG_INCS@ -DXBINDIR=\"${bindir}\" -DHAS_KL_API -DHAVE_XORG_CONFIG_H
+AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../apple -I$(top_srcdir)/miext/rootless @XORG_INCS@ -DXBINDIR=\"${bindir}\" -DHAS_KL_API -DHAVE_XORG_CONFIG_H
 
 SUBDIRS = cr fullscreen xpr
 
diff --git a/hw/darwin/quartz/applewm.c b/hw/darwin/quartz/applewm.c
index 2272a70..11cec4a 100644
--- a/hw/darwin/quartz/applewm.c
+++ b/hw/darwin/quartz/applewm.c
@@ -47,6 +47,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #define _APPLEWM_SERVER_
 #include "X11/extensions/applewmstr.h"
 #include "applewmExt.h"
+#include "X11Application.h"
 
 #define DEFINE_ATOM_HELPER(func,atom_name)                      \
 static Atom func (void) {                                       \
diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index fcd78ae..615ea8d 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -40,11 +40,14 @@
 #include "X11/extensions/applewm.h"
 #include "applewmExt.h"
 
+#include "X11Application.h"
+
 // X headers
 #include "scrnintstr.h"
 #include "windowstr.h"
 #include "colormapst.h"
 #include "globals.h"
+#include "rootlessWindow.h"
 
 // System headers
 #include <sys/types.h>
@@ -111,7 +114,9 @@ Bool DarwinModeAddScreen(
 {
     // allocate space for private per screen Quartz specific storage
     QuartzScreenPtr displayInfo = xcalloc(sizeof(QuartzScreenRec), 1);
-    QUARTZ_PRIV(pScreen) = displayInfo;
+
+    // QUARTZ_PRIV(pScreen) = displayInfo;
+    pScreen->devPrivates[quartzScreenIndex].ptr = displayInfo;
 
     // do Quartz mode specific initialization
     return quartzProcs->AddScreen(index, pScreen);
diff --git a/hw/darwin/quartz/quartz.h b/hw/darwin/quartz/quartz.h
index 172f323..e74a108 100644
--- a/hw/darwin/quartz/quartz.h
+++ b/hw/darwin/quartz/quartz.h
@@ -124,6 +124,4 @@ typedef struct _QuartzModeProcs {
 extern QuartzModeProcsPtr quartzProcs;
 extern int quartzHasRoot, quartzEnableRootless;
 
-Bool QuartzLoadDisplayBundle(const char *dpyBundleName);
-
 #endif
diff --git a/hw/darwin/quartz/quartzStartup.c b/hw/darwin/quartz/quartzStartup.c
index 583941d..3c8412f 100644
--- a/hw/darwin/quartz/quartzStartup.c
+++ b/hw/darwin/quartz/quartzStartup.c
@@ -40,14 +40,10 @@ char **envpGlobal;      // argcGlobal and argvGlobal
                         // are from dix/globals.c
 
 
-void X11ControllerMain(int argc, char *argv[],
-		       void (*server_thread) (void *), void *server_arg);
-void GlxExtensionInit(void);
-void GlxWrapInitVisuals(miInitVisualsProcPtr *procPtr);
+void X11ControllerMain(int argc, char *argv[], void (*server_thread) (void *), void *server_arg);
 
 static void server_thread (void *arg) {
   extern int main(int argc, char **argv, char **envp);
-  
   exit (main (argcGlobal, argvGlobal, envpGlobal));
 }
 
@@ -65,7 +61,7 @@ void DarwinHandleGUI(
     char        *envp[] )
 {
     static Bool been_here = FALSE;
-    int         main_exit, i;
+    int         i;
     int         fd[2];
 
     if (been_here) {
@@ -107,135 +103,5 @@ void DarwinHandleGUI(
     
     _InitHLTB();
     X11ControllerMain(argc, argv, server_thread, NULL);
-    exit(main_exit);
-}
-
-/*
- * QuartzLoadDisplayBundle
- *  Try to load the appropriate bundle containing the back end display code.
- */
-Bool QuartzLoadDisplayBundle(
-    const char *dpyBundleName)
-{
-    return TRUE;
-}
-
-
-/*
- * LoadGlxBundle
- *  The Quartz mode X server needs to dynamically load the appropriate
- *  bundle before initializing GLX.
- */
-static void LoadGlxBundle(void)
-{
-    CFBundleRef mainBundle;
-    CFStringRef bundleName;
-    CFURLRef    bundleURL;
-    CFBundleRef glxBundle;
-
-    // Get the main bundle for the application
-    mainBundle = CFBundleGetMainBundle();
-
-    // Choose the bundle to load
-    ErrorF("Loading GLX bundle ");
-    if (/*quartzUseAGL*/0) {
-        bundleName = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault,
-                                                     quartzOpenGLBundle,
-                                                     kCFStringEncodingASCII,
-                                                     kCFAllocatorNull);
-        ErrorF("%s (using Apple's OpenGL)\n", quartzOpenGLBundle);
-    } else {
-        bundleName = CFSTR("glxMesa.bundle");
-        CFRetain(bundleName);			// so we can release later
-        ErrorF("glxMesa.bundle (using Mesa)\n");
-    }
-
-    // Look for the appropriate GLX bundle in the main bundle by name
-    bundleURL = CFBundleCopyResourceURL(mainBundle, bundleName,
-                                        NULL, NULL);
-    if (!bundleURL) {
-        FatalError("Could not find GLX bundle.");
-    }
-
-    // Make a bundle instance using the URLRef
-    glxBundle = CFBundleCreate(kCFAllocatorDefault, bundleURL);
-
-    if (!CFBundleLoadExecutable(glxBundle)) {
-        FatalError("Could not load GLX bundle.");
-    }
-
-    // Find the GLX init functions
-    if (!GlxExtensionInit || !GlxWrapInitVisuals) {
-        FatalError("Could not initialize GLX bundle.");
-    }
-
-    // Release the CF objects
-    CFRelease(bundleName);
-    CFRelease(bundleURL);
-}
-
-
-/*
- * DarwinGlxExtensionInit
- *  Initialize the GLX extension.
- */
-void DarwinGlxPushProvider(void *impl)
-{
-    GlxPushProvider(impl);
-}
-
-/*
- * DarwinGlxExtensionInit
- *  Initialize the GLX extension.
- */
-void DarwinGlxExtensionInit(void)
-{
-    GlxExtensionInit();
-}
-
-
-/*
- * DarwinGlxWrapInitVisuals
- */
-void DarwinGlxWrapInitVisuals(
-    miInitVisualsProcPtr *procPtr)
-{
-    if (!GlxWrapInitVisuals)
-        LoadGlxBundle();
-    GlxWrapInitVisuals(procPtr);
-}
-
-
-int DarwinModeProcessArgument( int argc, char *argv[], int i )
-{
-    // fullscreen: CoreGraphics full-screen mode
-    // rootless: Cocoa rootless mode
-    // quartz: Default, either fullscreen or rootless
-
-    if ( !strcmp( argv[i], "-fullscreen" ) ) {
-        ErrorF( "Running full screen in parallel with Mac OS X Quartz window server.\n" );
-        return 1;
-    }
-
-    if ( !strcmp( argv[i], "-rootless" ) ) {
-        ErrorF( "Running rootless inside Mac OS X window server.\n" );
-        return 1;
-    }
-
-    if ( !strcmp( argv[i], "-quartz" ) ) {
-        ErrorF( "Running in parallel with Mac OS X Quartz window server.\n" );
-        return 1;
-    }
-
-    // The Mac OS X front end uses this argument, which we just ignore here.
-    if ( !strcmp( argv[i], "-nostartx" ) ) {
-        return 1;
-    }
-
-    // This command line arg is passed when launched from the Aqua GUI.
-    if ( !strncmp( argv[i], "-psn_", 5 ) ) {
-        return 1;
-    }
-
-    return 0;
+    exit(0);
 }
diff --git a/hw/darwin/quartz/xpr/appledri.c b/hw/darwin/quartz/xpr/appledri.c
index c38157d..7925239 100644
--- a/hw/darwin/quartz/xpr/appledri.c
+++ b/hw/darwin/quartz/xpr/appledri.c
@@ -175,7 +175,7 @@ ProcAppleDRIAuthConnection(
     rep.authenticated = 1;
 
     if (!DRIAuthConnection( screenInfo.screens[stuff->screen], stuff->magic)) {
-        ErrorF("Failed to authenticate %u\n", stuff->magic);
+        ErrorF("Failed to authenticate %u\n", (unsigned int)stuff->magic);
         rep.authenticated = 0;
     }
     WriteToClient(client, sizeof(xAppleDRIAuthConnectionReply), (char *)&rep);
diff --git a/hw/darwin/quartz/xpr/x-hook.c b/hw/darwin/quartz/xpr/x-hook.c
index 323e373..2d9a564 100644
--- a/hw/darwin/quartz/xpr/x-hook.c
+++ b/hw/darwin/quartz/xpr/x-hook.c
@@ -50,12 +50,19 @@ X_PFX (hook_remove) (x_list *lst, x_hook_function *fun, void *data)
 {
     x_list *node, *cell;
     x_list *to_delete = NULL;
+    x_list *prev = NULL;
 
-    for (node = lst; node != NULL; node = node->next)
+    for (node = lst; node != NULL; prev = node, node = node->next)
     {
 	cell = node->data;
 	if (CELL_FUN (cell) == fun && CELL_DATA (cell) == data)
+        {
 	    to_delete = X_PFX (list_prepend) (to_delete, cell);
+            if(lst == node)
+                lst = node->next;
+            else
+                prev->next = node->next;
+        }
     }
 
     for (node = to_delete; node != NULL; node = node->next)
@@ -66,6 +73,7 @@ X_PFX (hook_remove) (x_list *lst, x_hook_function *fun, void *data)
     }
 
     X_PFX (list_free) (to_delete);
+    return lst;
 }
 
 X_EXTERN void
diff --git a/hw/darwin/quartz/xpr/xprCursor.c b/hw/darwin/quartz/xpr/xprCursor.c
index 02260bd..e45bd1f 100644
--- a/hw/darwin/quartz/xpr/xprCursor.c
+++ b/hw/darwin/quartz/xpr/xprCursor.c
@@ -381,7 +381,8 @@ QuartzInitCursor(ScreenPtr pScreen)
     if (ScreenPriv == NULL)
         return FALSE;
 
-    CURSOR_PRIV(pScreen) = ScreenPriv;
+    /* CURSOR_PRIV(pScreen) = ScreenPriv; */
+    pScreen->devPrivates[darwinCursorScreenIndex].ptr = ScreenPriv;
 
     /* override some screen procedures */
     ScreenPriv->QueryBestSize = pScreen->QueryBestSize;
diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index 589b172..49cd1c1 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -42,6 +42,9 @@
 #include "Xplugin.h"
 #include "quartz/applewmExt.h"
 
+// From xprFrame.c
+WindowPtr xprGetXWindow(xp_window_id wid);
+
 #ifdef DAMAGE
 # include "damage.h"
 #endif
diff --git a/mi/miinitext.c b/mi/miinitext.c
index 3ccd456..f6aa9bd 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -660,12 +660,8 @@ InitVisualWrap()
 {
     miResetInitVisuals();
 #ifdef GLXEXT
-#ifdef INXQUARTZ
-    DarwinGlxWrapInitVisuals(&miInitVisualsProc);
-#else
     GlxWrapInitVisuals(&miInitVisualsProc);
 #endif
-#endif
 }
 
 #else /* XFree86LOADER */
diff --git a/miext/rootless/rootlessWindow.h b/miext/rootless/rootlessWindow.h
index 093a2b3..ad876e5 100644
--- a/miext/rootless/rootlessWindow.h
+++ b/miext/rootless/rootlessWindow.h
@@ -36,6 +36,7 @@
 
 #include "rootlessCommon.h"
 
+#include <Xplugin.h>
 
 Bool RootlessCreateWindow(WindowPtr pWin);
 Bool RootlessDestroyWindow(WindowPtr pWin);
@@ -59,5 +60,7 @@ void RootlessPaintWindowBackground(WindowPtr pWin, RegionPtr pRegion,
 void RootlessPaintWindowBorder(WindowPtr pWin, RegionPtr pRegion,
                                int what);
 void RootlessChangeBorderWidth(WindowPtr pWin, unsigned int width);
+void RootlessNativeWindowMoved (WindowPtr pWin);
+void RootlessNativeWindowStateChanged (xp_window_id id, unsigned int state); 
 
 #endif
commit 815bf67416f65f935fdadd4640e59b5443d33ef9
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Nov 16 04:37:58 2007 -0800

    added a bunch of debugging code to help troubleshoot the stuck
    modifier key issue; much of it may be taken out later.
    Also, hopefully fixed a race condition that may have
    prevented ReleaseModifiers from working in some cases.

diff --git a/hw/darwin/darwinEvents.c b/hw/darwin/darwinEvents.c
index 7984130..0fb5c9a 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -71,29 +71,8 @@ typedef struct _EventQueue {
 } EventQueueRec, *EventQueuePtr;
 
 static EventQueueRec darwinEventQueue;
-extern KeyClassPtr darwinKeyc;
-#define KeyPressed(k) (darwinKeyc->down[k >> 3] & (1 << (k & 7)))
-
-/*
- * DarwinPressModifierMask
- *  Press or release the given modifier key, specified by its mask.
- */
-static void DarwinPressModifierMask(
-    xEvent *xe,     // must already have type, time and mouse location
-    int mask)       // one of NX_*MASK constants
-{
-    int key = DarwinModifierNXMaskToNXKey(mask);
-
-    DEBUG_LOG("DarwinPressModifierMask(%p, %x, %d)\n", xe, mask, key);
-    if (key != -1) {
-        int keycode = DarwinModifierNXKeyToNXKeycode(key, 0);
-        if (keycode != 0) {
-            xe->u.u.detail = keycode + MIN_KEYCODE;
-            (*darwinEventQueue.pKbd->processInputProc)(xe,
-                            (DeviceIntPtr)darwinEventQueue.pKbd, 1);
-        }
-    }
-}
+extern darwinKeyboardInfo keyInfo;
+#define KeyPressed(k) (((DeviceIntPtr)darwinEventQueue.pKbd)->key->down[k >> 3] & (1 << (k & 7)))
 
 #ifdef NX_DEVICELCTLKEYMASK
 #define CONTROL_MASK(flags) (flags & (NX_DEVICELCTLKEYMASK|NX_DEVICERCTLKEYMASK))
@@ -119,6 +98,104 @@ static void DarwinPressModifierMask(
 #define ALTERNATE_MASK(flags) (NX_ALTERNATEMASK)
 #endif /* NX_DEVICELALTKEYMASK */
 
+#define KEYBOARD_MASK (NX_COMMANDMASK | NX_CONTROLMASK | NX_ALTERNATEMASK | NX_SHIFTMASK | \
+                       NX_SECONDARYFNMASK | NX_ALPHASHIFTMASK | NX_NUMERICPADMASK | \
+                       NX_HELPMASK | NX_DEVICELCTLKEYMASK | NX_DEVICELSHIFTKEYMASK | \
+		       NX_DEVICERSHIFTKEYMASK | NX_DEVICELCMDKEYMASK | NX_DEVICERCMDKEYMASK | \
+		       NX_DEVICELALTKEYMASK | NX_DEVICERALTKEYMASK | NX_DEVICERCTLKEYMASK)
+                      
+char * decode_event_flags(unsigned int modifiers) {
+  char buf[1024];
+  buf[0]='\0';
+  if (modifiers & NX_DEVICELCTLKEYMASK)   strcat(buf, "NX_DEVICELCTLKEYMASK | ");
+  if (modifiers & NX_DEVICELSHIFTKEYMASK) strcat(buf, "NX_DEVICELSHIFTKEYMASK | ");
+  if (modifiers & NX_DEVICERSHIFTKEYMASK) strcat(buf, "NX_DEVICERSHIFTKEYMASK | ");
+  if (modifiers & NX_DEVICELCMDKEYMASK)   strcat(buf, "NX_DEVICELCMDKEYMASK | ");
+  if (modifiers & NX_DEVICERCMDKEYMASK)   strcat(buf, "NX_DEVICERCMDKEYMASK | ");
+  if (modifiers & NX_DEVICELALTKEYMASK)   strcat(buf, "NX_DEVICELALTKEYMASK | ");
+  if (modifiers & NX_DEVICERALTKEYMASK)   strcat(buf, "NX_DEVICERALTKEYMASK | ");
+  if (modifiers & NX_DEVICERCTLKEYMASK)   strcat(buf, "NX_DEVICERCTLKEYMASK | ");
+
+  if (modifiers & NX_ALPHASHIFTMASK)      strcat(buf, "NX_ALPHASHIFTMASK | ");
+  if (modifiers & NX_SHIFTMASK)           strcat(buf, "NX_SHIFTMASK | ");
+  if (modifiers & NX_CONTROLMASK)         strcat(buf, "NX_CONTROLMASK | ");
+  if (modifiers & NX_ALTERNATEMASK)       strcat(buf, "NX_ALTERNATEMASK | ");
+  if (modifiers & NX_COMMANDMASK)         strcat(buf, "NX_COMMANDMASK | ");
+  if (modifiers & NX_NUMERICPADMASK)      strcat(buf, "NX_NUMERICPADMASK | ");
+  if (modifiers & NX_HELPMASK)            strcat(buf, "NX_HELPMASK | ");
+  if (modifiers & NX_SECONDARYFNMASK)     strcat(buf, "NX_SECONDARYFNMASK | ");
+
+  if (modifiers & NX_STYLUSPROXIMITYMASK) strcat(buf, "NX_STYLUSPROXIMITYMASK | ");
+  if (modifiers & NX_NONCOALSESCEDMASK)   strcat(buf, "NX_NONCOALSESCEDMASK | ");
+  if (modifiers & NX_NULLEVENTMASK)       strcat(buf, "NX_NULLEVENTMASK | ");
+  //  if (modifiers & NX_LMOUSEDOWNMASK)      strcat(buf, "NX_LMOUSEDOWNMASK | ");
+  //  if (modifiers & NX_LMOUSEUPMASK)        strcat(buf, "NX_LMOUSEUPMASK | ");
+  //  if (modifiers & NX_RMOUSEDOWNMASK)      strcat(buf, "NX_RMOUSEDOWNMASK | ");
+  //  if (modifiers & NX_RMOUSEUPMASK)        strcat(buf, "NX_RMOUSEUPMASK | ");
+  //  if (modifiers & NX_OMOUSEDOWNMASK)      strcat(buf, "NX_OMOUSEDOWNMASK | ");
+  //  if (modifiers & NX_OMOUSEUPMASK)        strcat(buf, "NX_OMOUSEUPMASK | ");
+  //  if (modifiers & NX_MOUSEMOVEDMASK)      strcat(buf, "NX_MOUSEMOVEDMASK | ");
+  // if (modifiers & NX_LMOUSEDRAGGEDMASK)   strcat(buf, "NX_LMOUSEDRAGGEDMASK | ");
+  //if (modifiers & NX_RMOUSEDRAGGEDMASK)   strcat(buf, "NX_RMOUSEDRAGGEDMASK | ");
+  //if (modifiers & NX_OMOUSEDRAGGEDMASK)   strcat(buf, "NX_OMOUSEDRAGGEDMASK | ");
+  //if (modifiers & NX_MOUSEENTEREDMASK)    strcat(buf, "NX_MOUSEENTEREDMASK | ");
+  //if (modifiers & NX_MOUSEEXITEDMASK)     strcat(buf, "NX_MOUSEEXITEDMASK | ");
+  if (modifiers & NX_KEYDOWNMASK)         strcat(buf, "NX_KEYDOWNMASK | ");
+  if (modifiers & NX_KEYUPMASK)           strcat(buf, "NX_KEYUPMASK | ");
+  if (modifiers & NX_FLAGSCHANGEDMASK)    strcat(buf, "NX_FLAGSCHANGEDMASK | ");
+  if (modifiers & NX_KITDEFINEDMASK)      strcat(buf, "NX_KITDEFINEDMASK | ");
+  if (modifiers & NX_SYSDEFINEDMASK)      strcat(buf, "NX_SYSDEFINEDMASK | ");
+  if (modifiers & NX_APPDEFINEDMASK)      strcat(buf, "NX_APPDEFINEDMASK | ");
+  
+  if (strlen(buf) < 5) strcpy(buf, "(empty)");
+  else buf[strlen(buf)-3]='\0';
+  return strdup(buf);
+}
+
+char * get_keysym_name(int ks) {
+  switch(ks) {
+  case XK_Alt_L: return "XK_Alt_L";
+  case XK_Alt_R: return "XK_Alt_R";
+  case XK_Meta_L: return "XK_Meta_L";
+  case XK_Meta_R: return "XK_Meta_R";
+  case XK_Control_L: return "XK_Control_L";
+  case XK_Control_R: return "XK_Control_R";
+  case XK_Shift_L: return "XK_Shift_L";
+  case XK_Shift_R: return "XK_Shift_R";
+  case XK_Mode_switch: return "XK_Mode_switch";
+  case XK_Caps_Lock: return "XK_Caps_Lock";
+  }
+  return "???";
+}
+
+/*
+ * DarwinPressModifierMask
+ *  Press or release the given modifier key, specified by its mask.
+ */
+static void DarwinPressModifierMask(
+    xEvent *xe,     // must already have type, time and mouse location
+    int mask)       // one of NX_*MASK constants
+{
+  int key, keycode;
+  key = DarwinModifierNXMaskToNXKey(mask);
+  if (key == -1) {
+    ErrorF("DarwinPressModifierMask: can't find key for mask %x\n", mask);
+    return;
+  }
+  keycode = DarwinModifierNXKeyToNXKeycode(key, 0);    
+  if (keycode == 0) {
+    ErrorF("DarwinPressModifierMask: can't find keycode for mask %x\n", mask);
+    return;
+  }
+  
+  DEBUG_LOG("%x: %s %s\n", mask, xe->u.u.type==KeyPress?"pressing":"releasing",
+	    decode_event_flags(mask));
+  
+  xe->u.u.detail = keycode + MIN_KEYCODE;
+  (*darwinEventQueue.pKbd->processInputProc)(xe,
+           (DeviceIntPtr)darwinEventQueue.pKbd, 1);
+}
+
 /*
  * DarwinUpdateModifiers
  *  Send events to update the modifier state.
@@ -126,23 +203,27 @@ static void DarwinPressModifierMask(
 static void DarwinUpdateModifiers(
     xEvent *xe,         // event template with time and mouse position set
     int pressed,        // KeyPress or KeyRelease
-    int flags )         // modifier flags that have changed
+    unsigned int flags )         // modifier flags that have changed
 {
-    DEBUG_LOG("DarwinUpdateModifiers(%p, %d, %x)\n", xe, pressed, flags);
-    xe->u.u.type = pressed;
-    if (flags & NX_COMMANDMASK) DarwinPressModifierMask(xe, COMMAND_MASK(flags));
-    if (flags & NX_CONTROLMASK) DarwinPressModifierMask(xe, CONTROL_MASK(flags));
-    if (flags & NX_ALTERNATEMASK) DarwinPressModifierMask(xe, ALTERNATE_MASK(flags));
-    if (flags & NX_SHIFTMASK)  DarwinPressModifierMask(xe, SHIFT_MASK(flags));
-    if (flags & NX_SECONDARYFNMASK) DarwinPressModifierMask(xe, NX_SECONDARYFNMASK);
-    if (flags & NX_ALPHASHIFTMASK) {
-		// Alpha shift only sees KeyDown when enabled and KeyUp when disabled,
-		// but X11 wants to see a up/down pair to enable, and again to disable
-		xe->u.u.type = KeyPress;
-        DarwinPressModifierMask(xe, NX_ALPHASHIFTMASK);
-		xe->u.u.type = KeyRelease;
-        DarwinPressModifierMask(xe, NX_ALPHASHIFTMASK);
-    }
+  int i;
+  DEBUG_LOG("DarwinUpdateModifiers(%p, %d, %x, %s)\n", xe, pressed, flags, decode_event_flags(flags));
+  xe->u.u.type = pressed;
+  /* If we have "device specific" flags -- meaning, left or right -- then strip out the generic flag */
+  if (flags & (NX_DEVICELCTLKEYMASK | NX_DEVICERCTLKEYMASK)) flags &= ~NX_CONTROLMASK;
+  if (flags & (NX_DEVICELALTKEYMASK | NX_DEVICERALTKEYMASK)) flags &= ~NX_ALTERNATEMASK;
+  if (flags & (NX_DEVICELCMDKEYMASK | NX_DEVICERCMDKEYMASK)) flags &= ~NX_COMMANDMASK;
+  if (flags & (NX_DEVICELSHIFTKEYMASK | NX_DEVICERSHIFTKEYMASK)) flags &= ~NX_SHIFTMASK;
+  if (flags == NX_ALPHASHIFTMASK) {
+    // Alpha shift only sees KeyDown when enabled and KeyUp when disabled,
+    // but X11 wants to see a up/down pair to enable, and again to disable
+    xe->u.u.type = KeyPress;
+    DarwinPressModifierMask(xe, NX_ALPHASHIFTMASK);
+    xe->u.u.type = KeyRelease;
+    DarwinPressModifierMask(xe, NX_ALPHASHIFTMASK);
+    flags &= ~NX_ALPHASHIFTMASK;
+  }
+  for(i=0; i < (sizeof(flags)*8); i++) 
+    if (flags & (1 << i)) DarwinPressModifierMask(xe, flags & (1 << i));
 }
 
 /*
@@ -151,18 +232,16 @@ static void DarwinUpdateModifiers(
  * is deactivated (kXDarwinDeactivate) to prevent modifiers from getting stuck if they
  * are held down during a "context" switch -- otherwise, we would miss the KeyUp.
  */
-static void DarwinReleaseModifiers(void) {
+void DarwinReleaseModifiers(void) {
   KeySym *map = NULL;
   xEvent ke;
   int i = 0, j = 0, nevents = 0; 
  
-  DEBUG_LOG("DarwinReleaseModifiers(%p)\n", darwinKeyc);
-  if (!darwinKeyc) return;
-  map = darwinKeyc->curKeySyms.map;
+  DEBUG_LOG("DarwinReleaseModifiers(%p)\n", &keyInfo.keyMap);
   
-  for (i = darwinKeyc->curKeySyms.minKeyCode, map = darwinKeyc->curKeySyms.map;
-       i < darwinKeyc->curKeySyms.maxKeyCode;
-       i++, map += darwinKeyc->curKeySyms.mapWidth) {
+  for (i = MIN_KEYCODE, map =keyInfo.keyMap;
+       i < MAX_KEYCODE;
+       i++, map += GLYPHS_PER_KEY) {
     if (KeyPressed(i)) {
       switch (*map) {
 	/* Don't release the lock keys */
@@ -173,7 +252,7 @@ static void DarwinReleaseModifiers(void) {
       case XK_Kana_Lock:
 	break;
       default:
-	DEBUG_LOG("DarwinReleaseModifiers: releasing key %d\n", i);
+	DEBUG_LOG("DarwinReleaseModifiers: releasing key %d (%s)\n", i, get_keysym_name(*map));
 	  ke.u.keyButtonPointer.time = GetTimeInMillis();
 	  ke.u.keyButtonPointer.rootX = 0;
 	  ke.u.keyButtonPointer.rootY = 0;
@@ -452,12 +531,14 @@ void ProcessInputEvents(void)
             {
                 // Update modifier state.
                 // Any amount of modifiers may have changed.
-                int flags = xe.u.clientMessage.u.l.longs0;
-		DEBUG_LOG("kxDarwinUpdateModifiers(%x, %x)\n", old_flags, flags);
-                DarwinUpdateModifiers(&xe, KeyRelease,
-                                      old_flags & ~flags);
-                DarwinUpdateModifiers(&xe, KeyPress,
-                                      ~old_flags & flags);
+	      unsigned int flags = xe.u.clientMessage.u.l.longs0 & ~NX_NONCOALSESCEDMASK; // ignore that one
+		DEBUG_LOG("kxDarwinUpdateModifiers(%x, %x, %s)\n", old_flags, flags, decode_event_flags(flags));
+		//		DEBUG_LOG("Ignoring these flags: %x %s\n", flags & ~KEYBOARD_MASK, decode_event_flags(flags & ~KEYBOARD_MASK));
+		flags &= KEYBOARD_MASK;
+                if (old_flags & ~flags) DarwinUpdateModifiers(&xe, KeyRelease,
+							      old_flags & ~flags);
+                if (~old_flags & flags) DarwinUpdateModifiers(&xe, KeyPress,
+							      ~old_flags & flags);
                 old_flags = flags;
                 break;
             }
diff --git a/hw/darwin/darwinKeyboard.c b/hw/darwin/darwinKeyboard.c
index 3685bff..111c98a 100644
--- a/hw/darwin/darwinKeyboard.c
+++ b/hw/darwin/darwinKeyboard.c
@@ -217,10 +217,9 @@ static void DarwinChangeKeyboardControl( DeviceIntPtr device, KeybdCtrl *ctrl )
     // keyclick, bell volume / pitch, autorepead, LED's
 }
 
-static darwinKeyboardInfo keyInfo;
+darwinKeyboardInfo keyInfo;
 static FILE *fref = NULL;
 static char *inBuffer = NULL;
-KeyClassPtr darwinKeyc = NULL;
 
 //-----------------------------------------------------------------------------
 // Data Stream Object
@@ -817,7 +816,7 @@ void DarwinKeyboardInit(
     assert( darwinParamConnect = NXOpenEventStatus() );
 
     DarwinLoadKeyboardMapping(&keySyms);
-
+    //    DarwinKeyboardReload(pDev);
     /* Initialize the seed, so we don't reload the keymap unnecessarily
        (and possibly overwrite xinitrc changes) */
     DarwinModeSystemKeymapSeed();
@@ -836,7 +835,7 @@ InitModMap(register KeyClassPtr keyc)
     CARD8 keysPerModifier[8];
     CARD8 mask;
 
-    darwinKeyc = keyc;
+    //    darwinKeyc = keyc;
     if (keyc->modifierKeyMap != NULL)
         xfree (keyc->modifierKeyMap);
 
@@ -888,7 +887,7 @@ DarwinKeyboardReload(DeviceIntPtr pDev)
 
         memmove(pDev->key->modifierMap, keyInfo.modMap, MAP_LENGTH);
         InitModMap(pDev->key);
-    }
+    } else DEBUG_LOG("SetKeySymsMap=0\n");
 
     SendMappingNotify(MappingKeyboard, MIN_KEYCODE, NUM_KEYCODES, 0);
     SendMappingNotify(MappingModifier, 0, 0, 0);
@@ -938,6 +937,32 @@ int DarwinModifierNXKeycodeToNXKey(unsigned char keycode, int *outSide)
 }
 
 /*
+ * DarwinModifierNXMaskToNXKeyCode
+ *      Returns 0 if mask is not a known modifier mask.
+ */
+int DarwinModifierNXMaskToNXKeyCode(int mask)
+{
+  switch (mask) {
+  case NX_ALPHASHIFTMASK:       return XK_Caps_Lock;
+  case NX_SHIFTMASK: ErrorF("Warning: Received NX_SHIFTMASK, treating as NX_DEVICELSHIFTKEYMASK\n");
+  case NX_DEVICELSHIFTKEYMASK:  return NX_MODIFIERKEY_SHIFT; //XK_Shift_L;
+  case NX_DEVICERSHIFTKEYMASK:  return NX_MODIFIERKEY_RSHIFT; //XK_Shift_R;
+  case NX_CONTROLMASK: ErrorF("Warning: Received NX_CONTROLMASK, treating as NX_DEVICELCTLKEYMASK\n");
+  case NX_DEVICELCTLKEYMASK:    return XK_Control_L;
+  case NX_DEVICERCTLKEYMASK:    return XK_Control_R;
+  case NX_ALTERNATEMASK: ErrorF("Warning: Received NX_ALTERNATEMASK, treating as NX_DEVICELALTKEYMASK\n");
+  case NX_DEVICELALTKEYMASK:    return XK_Alt_L;
+  case NX_DEVICERALTKEYMASK:    return XK_Alt_R;
+  case NX_COMMANDMASK: ErrorF("Warning: Received NX_COMMANDMASK, treating as NX_DEVICELCMDKEYMASK\n");
+  case NX_DEVICELCMDKEYMASK:    return XK_Meta_L;
+  case NX_DEVICERCMDKEYMASK:    return XK_Meta_R;
+  case NX_NUMERICPADMASK:       return XK_Num_Lock;
+  case NX_HELPMASK:             return XK_Help;
+  case NX_SECONDARYFNMASK:      return XK_Control_L; // this seems very wrong, but is what the old code did
+    }
+}
+
+/*
  * DarwinModifierNXMaskToNXKey
  *      Returns -1 if mask is not a known modifier mask.
  */
@@ -972,6 +997,29 @@ int DarwinModifierNXMaskToNXKey(int mask)
     return -1;
 }
 
+char * DarwinModifierNXMaskTostring(int mask)
+{
+    switch (mask) {
+    case NX_ALPHASHIFTMASK: return "NX_ALPHASHIFTMASK";
+    case NX_SHIFTMASK: return "NX_SHIFTMASK";
+    case NX_DEVICELSHIFTKEYMASK: return "NX_DEVICELSHIFTKEYMASK";
+    case NX_DEVICERSHIFTKEYMASK: return "NX_DEVICERSHIFTKEYMASK";
+    case NX_CONTROLMASK: return "NX_CONTROLMASK";
+    case NX_DEVICELCTLKEYMASK: return "NX_DEVICELCTLKEYMASK";
+    case NX_DEVICERCTLKEYMASK: return "NX_DEVICERCTLKEYMASK";
+    case NX_ALTERNATEMASK: return "NX_ALTERNATEMASK";
+    case NX_DEVICELALTKEYMASK: return "NX_DEVICELALTKEYMASK";
+    case NX_DEVICERALTKEYMASK: return "NX_DEVICERALTKEYMASK";
+    case NX_COMMANDMASK: return "NX_COMMANDMASK";
+    case NX_DEVICELCMDKEYMASK: return "NX_DEVICELCMDKEYMASK";
+    case NX_DEVICERCMDKEYMASK: return "NX_DEVICERCMDKEYMASK";
+    case NX_NUMERICPADMASK: return "NX_NUMERICPADMASK";
+    case NX_HELPMASK: return "NX_HELPMASK";
+    case NX_SECONDARYFNMASK: return "NX_SECONDARYFNMASK";
+    }
+    return "unknown mask";
+}
+
 /*
  * DarwinModifierNXKeyToNXMask
  *      Returns 0 if key is not a known modifier key.
commit 65a717fd7b5855558b3807ab94b70e8c1d47c855
Author: Ben Byer <bbyer at bbyer.local>
Date:   Thu Nov 15 02:41:07 2007 -0800

    a first stab at DEBUG_LOG

diff --git a/hw/darwin/apple/X11Controller.m b/hw/darwin/apple/X11Controller.m
index a6a75d0..df90049 100644
--- a/hw/darwin/apple/X11Controller.m
+++ b/hw/darwin/apple/X11Controller.m
@@ -54,8 +54,6 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 
-#define TRACE() fprintf (stderr, "%s\n", __FUNCTION__)
-
 @implementation X11Controller
 
 - (void) awakeFromNib
diff --git a/hw/darwin/darwin.c b/hw/darwin/darwin.c
index ada29c4..789b0e2 100644
--- a/hw/darwin/darwin.c
+++ b/hw/darwin/darwin.c
@@ -667,6 +667,7 @@ void OsVendorInit(void)
 	}
 #endif
     }
+    //    DEBUG_LOG("Xquartz started at %s\n", ctime(time(NULL)));
 
     // Find the full path to the keymapping file.
     if ( darwinKeymapFile ) {
diff --git a/hw/darwin/darwinEvents.c b/hw/darwin/darwinEvents.c
index 85ae305..7984130 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -84,6 +84,7 @@ static void DarwinPressModifierMask(
 {
     int key = DarwinModifierNXMaskToNXKey(mask);
 
+    DEBUG_LOG("DarwinPressModifierMask(%p, %x, %d)\n", xe, mask, key);
     if (key != -1) {
         int keycode = DarwinModifierNXKeyToNXKeycode(key, 0);
         if (keycode != 0) {
@@ -127,6 +128,7 @@ static void DarwinUpdateModifiers(
     int pressed,        // KeyPress or KeyRelease
     int flags )         // modifier flags that have changed
 {
+    DEBUG_LOG("DarwinUpdateModifiers(%p, %d, %x)\n", xe, pressed, flags);
     xe->u.u.type = pressed;
     if (flags & NX_COMMANDMASK) DarwinPressModifierMask(xe, COMMAND_MASK(flags));
     if (flags & NX_CONTROLMASK) DarwinPressModifierMask(xe, CONTROL_MASK(flags));
@@ -154,6 +156,7 @@ static void DarwinReleaseModifiers(void) {
   xEvent ke;
   int i = 0, j = 0, nevents = 0; 
  
+  DEBUG_LOG("DarwinReleaseModifiers(%p)\n", darwinKeyc);
   if (!darwinKeyc) return;
   map = darwinKeyc->curKeySyms.map;
   
@@ -170,6 +173,7 @@ static void DarwinReleaseModifiers(void) {
       case XK_Kana_Lock:
 	break;
       default:
+	DEBUG_LOG("DarwinReleaseModifiers: releasing key %d\n", i);
 	  ke.u.keyButtonPointer.time = GetTimeInMillis();
 	  ke.u.keyButtonPointer.rootX = 0;
 	  ke.u.keyButtonPointer.rootY = 0;
@@ -201,6 +205,7 @@ static void DarwinSimulateMouseClick(
     int whichButton,    // mouse button to be pressed
     int modifierMask)   // modifiers used for the fake click
 {
+  DEBUG_LOG("DarwinSimulateMouseClick(%p, %d, %x)\n", xe, whichButton, modifierMask);
     // first fool X into forgetting about the keys
 	// for some reason, it's not enough to tell X we released the Command key -- 
 	// it has to be the *left* Command key.
@@ -448,6 +453,7 @@ void ProcessInputEvents(void)
                 // Update modifier state.
                 // Any amount of modifiers may have changed.
                 int flags = xe.u.clientMessage.u.l.longs0;
+		DEBUG_LOG("kxDarwinUpdateModifiers(%x, %x)\n", old_flags, flags);
                 DarwinUpdateModifiers(&xe, KeyRelease,
                                       old_flags & ~flags);
                 DarwinUpdateModifiers(&xe, KeyPress,
@@ -508,6 +514,7 @@ void ProcessInputEvents(void)
             }
 
 	    case kXDarwinDeactivate:
+	      DEBUG_LOG("kxDarwinDeactivate\n");
 	      DarwinReleaseModifiers();
 	      old_flags=0;
 	      // fall through
diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 7ba452c..fcd78ae 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -249,7 +249,7 @@ static void QuartzUpdateScreens(void)
     int x, y, width, height, sx, sy;
     xEvent e;
 
-    TRACE("QuartzUpdateScreens()\n");
+    DEBUG_LOG("QuartzUpdateScreens()\n");
     if (noPseudoramiXExtension || screenInfo.numScreens != 1)
     {
         /* FIXME: if not using Xinerama, we have multiple screens, and
@@ -414,7 +414,7 @@ void DarwinModeProcessEvent(
 {
     switch (xe->u.u.type) {
         case kXDarwinControllerNotify:
-	  TRACE("kXDarwinControllerNotify\n");
+	  DEBUG_LOG("kXDarwinControllerNotify\n");
             AppleWMSendEvent(AppleWMControllerNotify,
                              AppleWMControllerNotifyMask,
                              xe->u.clientMessage.u.l.longs0,
@@ -422,7 +422,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinPasteboardNotify:
-	  TRACE("kXDarwinPasteboardNotify\n");
+	  DEBUG_LOG("kXDarwinPasteboardNotify\n");
             AppleWMSendEvent(AppleWMPasteboardNotify,
                              AppleWMPasteboardNotifyMask,
                              xe->u.clientMessage.u.l.longs0,
@@ -430,7 +430,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinActivate:
-	  TRACE("kXDarwinActivate\n");
+	  DEBUG_LOG("kXDarwinActivate\n");
             QuartzShow(xe->u.keyButtonPointer.rootX,
                        xe->u.keyButtonPointer.rootY);
             AppleWMSendEvent(AppleWMActivationNotify,
@@ -439,7 +439,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinDeactivate:
-  	  TRACE("kXDarwinDeactivate\n");
+  	  DEBUG_LOG("kXDarwinDeactivate\n");
             AppleWMSendEvent(AppleWMActivationNotify,
                              AppleWMActivationNotifyMask,
                              AppleWMIsInactive, 0);
@@ -447,23 +447,23 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinDisplayChanged:
-	    TRACE("kXDarwinDisplayChanged\n");
+	    DEBUG_LOG("kXDarwinDisplayChanged\n");
             QuartzUpdateScreens();
             break;
 
         case kXDarwinWindowState:
-	  TRACE("kXDarwinWindowState\n");
+	  DEBUG_LOG("kXDarwinWindowState\n");
             RootlessNativeWindowStateChanged(xe->u.clientMessage.u.l.longs0,
 		  			     xe->u.clientMessage.u.l.longs1);
 	    break;
 	  
         case kXDarwinWindowMoved:
-	  TRACE("kXDarwinWindowMoved\n");
+	  DEBUG_LOG("kXDarwinWindowMoved\n");
             RootlessNativeWindowMoved (xe->u.clientMessage.u.l.longs0);
 	    break;
 
         case kXDarwinToggleFullscreen:
-	  TRACE("kXDarwinToggleFullscreen\n");
+	  DEBUG_LOG("kXDarwinToggleFullscreen\n");
 #ifdef DARWIN_DDX_MISSING
             if (quartzEnableRootless) QuartzSetFullscreen(!quartzHasRoot);
             else if (quartzHasRoot) QuartzHide();
@@ -499,7 +499,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinBringAllToFront:
-  	  TRACE("kXDarwinBringAllToFront\n");
+  	  DEBUG_LOG("kXDarwinBringAllToFront\n");
 	    RootlessOrderAllWindows();
             break;
 
diff --git a/hw/darwin/quartz/quartz.h b/hw/darwin/quartz/quartz.h
index febc51a..172f323 100644
--- a/hw/darwin/quartz/quartz.h
+++ b/hw/darwin/quartz/quartz.h
@@ -38,14 +38,6 @@
 #include "screenint.h"
 #include "window.h"
 
-//#define DEBUG 1
-
-#ifdef DEBUG
-#define TRACE(msg, args...) ErrorF("%s:%d: " msg, __FUNCTION__, __LINE__, ##args )
-#else
-#define TRACE(msg, args...) 
-#endif
-
 /*------------------------------------------
    Quartz display mode function types
   ------------------------------------------*/
commit 0e0b452d10c0af55497c3299b5f3db45d5b381cb
Author: Ben Byer <bbyer at bbyer.local>
Date:   Thu Nov 15 02:25:50 2007 -0800

    Added a lightweight debugging facility to support troubleshooting
    (for example) the stuck modifier key issue

diff --git a/hw/darwin/darwin.c b/hw/darwin/darwin.c
index f0c35f8..ada29c4 100644
--- a/hw/darwin/darwin.c
+++ b/hw/darwin/darwin.c
@@ -72,6 +72,10 @@
 #include "darwin.h"
 #include "darwinClut8.h"
 
+#ifdef ENABLE_DEBUG_LOG
+FILE *debug_log_fp = NULL;
+#endif
+
 /*
  * X server shared global variables
  */
@@ -648,6 +652,20 @@ void OsVendorInit(void)
 {
     if (serverGeneration == 1) {
         DarwinPrintBanner();
+#ifdef ENABLE_DEBUG_LOG
+	{
+	  char *home_dir=NULL, *log_file_path=NULL;
+	  home_dir = getenv("HOME");
+	  if (home_dir) asprintf(&log_file_path, "%s/%s", home_dir, DEBUG_LOG_NAME);
+	  if (log_file_path) {
+	    if (!access(log_file_path, F_OK)) {
+	      debug_log_fp = fopen(log_file_path, "a");
+	      if (debug_log_fp) ErrorF("Debug logging enabled to %s\n", log_file_path);
+	    }
+	    free(log_file_path);
+	  }
+	}
+#endif
     }
 
     // Find the full path to the keymapping file.
diff --git a/hw/darwin/darwin.h b/hw/darwin/darwin.h
index bc96bb0..25bba20 100644
--- a/hw/darwin/darwin.h
+++ b/hw/darwin/darwin.h
@@ -152,4 +152,14 @@ enum {
     kXDarwinWindowMoved       // window has moved on screen
 };
 
+#define ENABLE_DEBUG_LOG 1
+
+#ifdef ENABLE_DEBUG_LOG
+extern FILE *debug_log_fp;
+#define DEBUG_LOG_NAME "x11-debug.txt"
+#define DEBUG_LOG(msg, args...) if (debug_log_fp) fprintf(debug_log_fp, "%s:%d: " msg, __FUNCTION__, __LINE__, ##args )
+#else
+#define DEBUG_LOG(msg, args...) 
+#endif
+
 #endif  /* _DARWIN_H */
commit 905d672c05bb060ba50bc5383843fc920e568a8e
Author: Ben Byer <bbyer at bbyer.local>
Date:   Thu Nov 15 01:49:33 2007 -0800

    More XDarwin cleanup / dead code removal from Jeremy

diff --git a/configure.ac b/configure.ac
index 3c9aa04..1eaf6ad 100644
--- a/configure.ac
+++ b/configure.ac
@@ -70,11 +70,6 @@ AC_HEADER_DIRENT
 AC_HEADER_STDC
 AC_CHECK_HEADERS([fcntl.h stdlib.h string.h unistd.h])
 
-AC_CHECK_PROG(HAVE_LAUNCHD, [launchd], [yes], [])
-if test "x$HAVE_LAUNCHD" = xyes; then
-	AC_DEFINE(HAS_LAUNCHD, 1, [launchd support available])
-fi
-
 dnl Checks for typedefs, structures, and compiler characteristics.
 AC_C_CONST
 AC_C_BIGENDIAN([ENDIAN="X_BIG_ENDIAN"], [ENDIAN="X_LITTLE_ENDIAN"])
@@ -464,6 +459,8 @@ AC_ARG_WITH(apple-applications-dir,AS_HELP_STRING([--with-apple-applications-dir
 				[ APPLE_APPLICATIONS_DIR="${withval}" ].
 				[ APPLE_APPLICATIONS_DIR="/Applications/Utilities" ])
 
+AC_ARG_WITH(launchd,          AS_HELP_STRING([--with-launchd], [Build with support for Apple's launchd (default: auto)]), [LAUNCHD=$withval], [LAUNCHD=auto])
+
 AC_ARG_ENABLE(builddocs,      AS_HELP_STRING([--enable-builddocs], [Build docs (default: disabled)]),
                                 [BUILDDOCS=$enableval],
                                 [BUILDDOCS=no])
@@ -1613,7 +1610,7 @@ if test "X$XQUARTZ" = Xauto; then
 		LDFLAGS=$save_LDFLAGS])
                 
 	if test "X$xorg_cv_Carbon_framework" = Xyes; then
-		AC_DEFINE([DARWIN_WITH_QUARTZ],[1],[Have Quartz])
+		AC_DEFINE([XQUARTZ],[1],[Have Quartz])
 		XQUARTZ=yes
 	else
 		XQUARTZ=no
@@ -1649,7 +1646,7 @@ if test "x$XQUARTZ" = xyes; then
 	       AC_SUBST([DARWIN_LIBS])
                AC_CHECK_LIB([Xplugin],[xp_init],[:])
                AC_SUBST([APPLE_APPLICATIONS_DIR])
-               CFLAGS="${CFLAGS} -DHAVE_LAUNCHD -D__DARWIN__ -DDARWIN_WITH_QUARTZ -DROOTLESS_WORKAROUND"
+               CFLAGS="${CFLAGS} -D__DARWIN__ -DROOTLESS_WORKAROUND"
                PLIST_VERSION_STRING=$PACKAGE_VERSION
                AC_SUBST([PLIST_VERSION_STRING])
                PLIST_VENDOR_WEB=$VENDOR_WEB
@@ -1671,6 +1668,23 @@ if test "x$XQUARTZ" = xyes; then
                        DGA=no
                fi
 fi
+
+if test "x$LAUNCHD" = xauto; then
+	# Do we want to have this default to on for Xquartz builds only or any time we have launchd (like Xnest or Xvfb on OS-X)
+	#AC_CHECK_PROG(LAUNCHD, [launchd], [yes], [no])
+	AC_MSG_CHECKING([whether to support launchd])
+	if test "x$XQUARTZ" = xyes ; then
+		LAUNCHD=yes
+	else
+		LAUNCHD=no
+	fi
+	AC_MSG_RESULT([$LAUNCHD])
+fi
+
+if test "x$LAUNCHD" = xyes ; then
+	AC_DEFINE(HAVE_LAUNCHD, 1, [launchd support available])
+fi
+
 # Support for objc in autotools is minimal and not documented.
 OBJC='$(CC)'
 OBJCLD='$(CCLD)'
@@ -2000,17 +2014,6 @@ 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
diff --git a/dix/main.c b/dix/main.c
index 586b800..50dbb67 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -256,10 +256,15 @@ main(int argc, char *argv[], char *envp[])
     PrinterInitGlobals();
 #endif
 
+#ifdef XQUARTZ
     /* Quartz support on Mac OS X requires that the Cocoa event loop be in
      * the main thread. This allows the X server main to be called again
      * from another thread. */
-#ifdef DARWIN_WITH_QUARTZ
+
+    /* TODO: Put some runtime conditioning on this, so it doesn't get
+     * executed by Xvfb, Xnest, Xfake, Xephyr, etc when built at the same
+     * time as Xquartz
+     */
     DarwinHandleGUI(argc, argv, envp);
 #endif
 
diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index e83f04d..e23a3d1 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -1,5 +1,5 @@
 AM_CFLAGS = @XORG_CFLAGS@
-AM_CPPFLAGS = @XORG_INCS@ -I../../miext/rootless -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" -DHAVE_XORG_CONFIG_H -DXFree86Server
+AM_CPPFLAGS = @XORG_INCS@ -I../../miext/rootless -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" -DHAVE_XORG_CONFIG_H -DXFree86Server -DINXQUARTZ
   
 SUBDIRS = quartz utils
   
diff --git a/hw/darwin/darwin.c b/hw/darwin/darwin.c
index 52fd170..f0c35f8 100644
--- a/hw/darwin/darwin.c
+++ b/hw/darwin/darwin.c
@@ -836,14 +836,11 @@ void ddxUseMsg( void )
     ErrorF("-keymap <file> : read the keymapping from a file instead of the kernel.\n");
     ErrorF("-version : show the server version.\n");
     ErrorF("\n");
-#ifdef DARWIN_WITH_QUARTZ
-    ErrorF("Quartz modes:\n");
+    ErrorF("Quartz modes (Experimental / In Development):\n");
     ErrorF("-fullscreen : run full screen in parallel with Mac OS X window server.\n");
     ErrorF("-rootless : run rootless inside Mac OS X window server.\n");
-    ErrorF("-quartz : use default Mac OS X window server mode\n");
     ErrorF("\n");
     ErrorF("Options ignored in rootless mode:\n");
-#endif
     ErrorF("-size <height> <width> : use a screen resolution of <height> x <width>.\n");
     ErrorF("-depth <8,15,24> : use this bit depth.\n");
     ErrorF("-refresh <rate> : use a monitor refresh rate of <rate> Hz.\n");
diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
index 5a78bfb..26bc8eb 100644
--- a/hw/darwin/quartz/Makefile.am
+++ b/hw/darwin/quartz/Makefile.am
@@ -2,7 +2,7 @@ noinst_LIBRARIES = libXQuartz.a
 
 AM_CFLAGS = @XORG_CFLAGS@
 AM_OBJCFLAGS = @XORG_CFLAGS@
-AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/.. @XORG_INCS@ -DXBINDIR=\"${bindir}\" -DINXQUARTZ -DHAS_KL_API -DHAVE_XORG_CONFIG_H
+AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/.. @XORG_INCS@ -DXBINDIR=\"${bindir}\" -DHAS_KL_API -DHAVE_XORG_CONFIG_H
 
 SUBDIRS = cr fullscreen xpr
 
diff --git a/hw/darwin/quartz/applewm.c b/hw/darwin/quartz/applewm.c
index 78cf9df..2272a70 100644
--- a/hw/darwin/quartz/applewm.c
+++ b/hw/darwin/quartz/applewm.c
@@ -445,11 +445,7 @@ ProcAppleWMSetWindowMenu(
                 break;
         }
     }
-#ifdef INXQUARTZ
     X11ApplicationSetWindowMenu (nitems, items, shortcuts);
-#else
-    QuartzSetWindowMenu (nitems, items, shortcuts);
-#endif
     free(items);
     free(shortcuts);
 
@@ -464,12 +460,7 @@ ProcAppleWMSetWindowMenuCheck(
     REQUEST(xAppleWMSetWindowMenuCheckReq);
 
     REQUEST_SIZE_MATCH(xAppleWMSetWindowMenuCheckReq);
-#ifdef INXQUARTZ
     X11ApplicationSetWindowMenuCheck (stuff->index);
-#else
-    QuartzMessageMainThread(kQuartzSetWindowMenuCheck, &stuff->index,
-                            sizeof(stuff->index));
-#endif
     return (client->noClientException);
 }
 
@@ -480,11 +471,7 @@ ProcAppleWMSetFrontProcess(
 {
     REQUEST_SIZE_MATCH(xAppleWMSetFrontProcessReq);
 
-#ifdef INXQUARTZ
     X11ApplicationSetFrontProcess();
-#else
-    QuartzMessageMainThread(kQuartzSetFrontProcess, NULL, 0);
-#endif
     return (client->noClientException);
 }
 
@@ -526,12 +513,7 @@ ProcAppleWMSetCanQuit(
 
     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 c0666e6..7ba452c 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -185,12 +185,8 @@ void DarwinModeInitInput(
     int argc,
     char **argv )
 {
-#ifdef INXQUARTZ
     X11ApplicationSetCanQuit(1);
     X11ApplicationServerReady();
-#else
-    QuartzMessageMainThread(kQuartzServerStarted, NULL, 0);
-#endif
     // Do final display mode specific initialization before handling events
     if (quartzProcs->InitInput)
         quartzProcs->InitInput(argc, argv);
@@ -354,9 +350,6 @@ static void QuartzHide(void)
         }
     }
     quartzServerVisible = FALSE;
-#ifndef INXQUARTZ
-    QuartzMessageMainThread(kQuartzServerHidden, NULL, 0);
-#endif
 }
 
 
diff --git a/hw/darwin/quartz/quartzCocoa.m b/hw/darwin/quartz/quartzCocoa.m
index 2e7b86b..c5e6e5c 100644
--- a/hw/darwin/quartz/quartzCocoa.m
+++ b/hw/darwin/quartz/quartzCocoa.m
@@ -45,63 +45,12 @@
 
 #include <Cocoa/Cocoa.h>
 
-#ifndef INXQUARTZ
-#import "Preferences.h"
-#endif
 #include "pseudoramiX.h"
 
 extern void FatalError(const char *, ...);
 extern char *display;
 extern int noPanoramiXExtension;
 
-#ifndef INXQUARTZ
-/*
- * QuartzReadPreferences
- *  Read the user preferences from the Cocoa front end.
- */
-void QuartzReadPreferences(void)
-{
-    char *fileString;
-
-    darwinFakeButtons = [Preferences fakeButtons];
-    darwinFakeMouse2Mask = [Preferences button2Mask];
-    darwinFakeMouse3Mask = [Preferences button3Mask];
-    darwinMouseAccelChange = [Preferences mouseAccelChange];
-    quartzUseSysBeep = [Preferences systemBeep];
-    quartzEnableKeyEquivalents = [Preferences enableKeyEquivalents];
-
-    // quartzRootless has already been set
-    if (quartzRootless) {
-        // Use PseudoramiX instead of Xinerama
-        noPanoramiXExtension = TRUE;
-        noPseudoramiXExtension = ![Preferences xinerama];
-
-        quartzUseAGL = [Preferences useAGL];
-    } else {
-        noPanoramiXExtension = ![Preferences xinerama];
-        noPseudoramiXExtension = TRUE;
-
-        // Full screen can't use AGL for GLX
-        quartzUseAGL = FALSE;
-    }
-
-    if ([Preferences useKeymapFile]) {
-        fileString = (char *) [[Preferences keymapFile] lossyCString];
-        darwinKeymapFile = (char *) malloc(strlen(fileString)+1);
-        if (! darwinKeymapFile)
-            FatalError("malloc failed in QuartzReadPreferences()!\n");
-        strcpy(darwinKeymapFile, fileString);
-    }
-
-    display = (char *) malloc(8);
-    if (! display)
-        FatalError("malloc failed in QuartzReadPreferences()!\n");
-    snprintf(display, 8, "%i", [Preferences display]);
-
-    darwinDesiredDepth = [Preferences depth] - 1;
-}
-#endif
-
 /*
  * QuartzWriteCocoaPasteboard
  *  Write text to the Mac OS X pasteboard.
@@ -165,19 +114,6 @@ char *QuartzReadCocoaPasteboard(void)
 int QuartzFSUseQDCursor(
     int depth)  // screen depth
 {
-#ifndef INXQUARTZ
-    switch ([Preferences useQDCursor]) {
-        case qdCursor_Always:
-            return TRUE;
-        case qdCursor_Never:
-            return FALSE;
-        case qdCursor_Not8Bit:
-            if (depth > 8)
-                return TRUE;
-            else
-                return FALSE;
-    }
-#endif
     return TRUE;
 }
 
diff --git a/hw/darwin/quartz/quartzStartup.c b/hw/darwin/quartz/quartzStartup.c
index f627790..583941d 100644
--- a/hw/darwin/quartz/quartzStartup.c
+++ b/hw/darwin/quartz/quartzStartup.c
@@ -40,19 +40,6 @@ char **envpGlobal;      // argcGlobal and argvGlobal
                         // are from dix/globals.c
 
 
-#ifndef INXQUARTZ
-int NSApplicationMain(int argc, char *argv[]);
-
-// GLX bundle function pointers
-void * __DarwinglXMesaProvider = NULL;
-typedef void (*GlxPushProviderPtr)(void *);
-GlxPushProviderPtr GlxPushProvider = NULL;
-typedef void (*GlxExtensionInitPtr)(void); 
-typedef void (*GlxWrapInitVisualsPtr)(miInitVisualsProcPtr *);
-typedef Bool (*QuartzModeBundleInitPtr)(void);
-static GlxExtensionInitPtr GlxExtensionInit = NULL;
-static GlxWrapInitVisualsPtr GlxWrapInitVisuals = NULL;
-#else
 void X11ControllerMain(int argc, char *argv[],
 		       void (*server_thread) (void *), void *server_arg);
 void GlxExtensionInit(void);
@@ -63,7 +50,6 @@ static void server_thread (void *arg) {
   
   exit (main (argcGlobal, argvGlobal, envpGlobal));
 }
-#endif
 
 /*
  * DarwinHandleGUI
@@ -83,9 +69,6 @@ void DarwinHandleGUI(
     int         fd[2];
 
     if (been_here) {
-#ifndef INXQUARTZ      
-        QuartzReadPreferences();
-#endif
         return;
     }
     been_here = TRUE;
@@ -120,14 +103,10 @@ void DarwinHandleGUI(
         }
     }
 
-#ifndef INXQUARTZ
-    main_exit = NSApplicationMain(argc, argv);
-#else
     extern void _InitHLTB(void);
     
     _InitHLTB();
     X11ControllerMain(argc, argv, server_thread, NULL);
-#endif
     exit(main_exit);
 }
 
@@ -138,54 +117,6 @@ void DarwinHandleGUI(
 Bool QuartzLoadDisplayBundle(
     const char *dpyBundleName)
 {
-#ifndef INXQUARTZ
-    CFBundleRef mainBundle;
-    CFStringRef bundleName;
-    CFURLRef    bundleURL;
-    CFBundleRef dpyBundle;
-    QuartzModeBundleInitPtr bundleInit;
-
-    // Get the main bundle for the application
-    mainBundle = CFBundleGetMainBundle();
-
-    // Make CFString from bundle name
-    bundleName = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault,
-                                                 dpyBundleName,
-                                                 kCFStringEncodingASCII,
-                                                 kCFAllocatorNull);
-
-    // Look for the appropriate bundle in the main bundle
-    bundleURL = CFBundleCopyResourceURL(mainBundle, bundleName,
-                                        NULL, NULL);
-    if (!bundleURL) {
-        ErrorF("Could not find display mode bundle %s.\n", dpyBundleName);
-        return FALSE;
-    }
-
-    // Make a bundle instance using the URLRef
-    dpyBundle = CFBundleCreate(kCFAllocatorDefault, bundleURL);
-
-    if (!CFBundleLoadExecutable(dpyBundle)) {
-        ErrorF("Could not load display mode bundle %s.\n", dpyBundleName);
-        return FALSE;
-    }
-
-    // Lookup the bundle initialization function
-    bundleInit = (void *)
-            CFBundleGetFunctionPointerForName(dpyBundle,
-                                              CFSTR("QuartzModeBundleInit"));
-    if (!bundleInit) {
-        ErrorF("Could not initialize display mode bundle %s.\n",
-               dpyBundleName);
-        return FALSE;
-    }
-    if (!bundleInit())
-        return FALSE;
-
-    // Release the CF objects
-    CFRelease(bundleName);
-    CFRelease(bundleURL);
-#endif
     return TRUE;
 }
 
@@ -234,20 +165,6 @@ static void LoadGlxBundle(void)
     }
 
     // Find the GLX init functions
-
-#ifndef INXQUARTZ
-    __DarwinglXMesaProvider = (void *) CFBundleGetDataPointerForName(
-			       glxBundle, CFSTR("__glXMesaProvider"));
-
-    GlxPushProvider = (void *) CFBundleGetFunctionPointerForName(
-                                glxBundle, CFSTR("GlxPushProvider"));
-
-    GlxExtensionInit = (void *) CFBundleGetFunctionPointerForName(
-                                glxBundle, CFSTR("GlxExtensionInit"));
-
-    GlxWrapInitVisuals = (void *) CFBundleGetFunctionPointerForName(
-                                glxBundle, CFSTR("GlxWrapInitVisuals"));
-#endif
     if (!GlxExtensionInit || !GlxWrapInitVisuals) {
         FatalError("Could not initialize GLX bundle.");
     }
@@ -264,10 +181,6 @@ static void LoadGlxBundle(void)
  */
 void DarwinGlxPushProvider(void *impl)
 {
-#ifndef INXQUARTZ
-    if (!GlxExtensionInit)
-        LoadGlxBundle();
-#endif
     GlxPushProvider(impl);
 }
 
@@ -277,10 +190,6 @@ void DarwinGlxPushProvider(void *impl)
  */
 void DarwinGlxExtensionInit(void)
 {
-#ifndef INXQUARTZ
-    if (!GlxExtensionInit)
-        LoadGlxBundle();
-#endif
     GlxExtensionInit();
 }
 
@@ -291,10 +200,8 @@ void DarwinGlxExtensionInit(void)
 void DarwinGlxWrapInitVisuals(
     miInitVisualsProcPtr *procPtr)
 {
-#ifdef INXQUARTZ
     if (!GlxWrapInitVisuals)
         LoadGlxBundle();
-#endif
     GlxWrapInitVisuals(procPtr);
 }
 
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 6badcca..29b917e 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -130,6 +130,9 @@
 /* Define to 1 if launchd is available. */
 #undef HAVE_LAUNCHD
 
+/* Have Quartz */
+#undef XQUARTZ
+
 /* Define to 1 if you have the `m' library (-lm). */
 #undef HAVE_LIBM
 
commit 148a87ff20aa5e7a6d839610aa14fa1a31505c4a
Author: Ben Byer <bbyer at bbyer.local>
Date:   Thu Nov 15 00:56:54 2007 -0800

    Patch to avert (some) damage / rootless crashes, courtesy of Ken Thomases

diff --git a/miext/rootless/rootless.h b/miext/rootless/rootless.h
index b4a5b2a..5224dca 100644
--- a/miext/rootless/rootless.h
+++ b/miext/rootless/rootless.h
@@ -66,7 +66,6 @@ typedef struct _RootlessWindowRec {
     int bytesPerRow;
 
     PixmapPtr pixmap;
-    PixmapPtr oldPixmap;
 
 #ifdef ROOTLESS_TRACK_DAMAGE
     RegionRec damage;
diff --git a/miext/rootless/rootlessCommon.c b/miext/rootless/rootlessCommon.c
index fc22b1b..9771ac9 100644
--- a/miext/rootless/rootlessCommon.c
+++ b/miext/rootless/rootlessCommon.c
@@ -169,8 +169,24 @@ void RootlessStartDrawing(WindowPtr pWindow)
         winRec->is_drawing = TRUE;
     }
 
-    winRec->oldPixmap = pScreen->GetWindowPixmap(pWindow);
-    pScreen->SetWindowPixmap(pWindow, winRec->pixmap);
+    PixmapPtr curPixmap = pScreen->GetWindowPixmap(pWindow);
+    if (curPixmap == winRec->pixmap)
+    {
+        RL_DEBUG_MSG("Window %p already has winRec->pixmap %p; not pushing\n", pWindow, winRec->pixmap);
+    }
+    else
+    {
+        PixmapPtr oldPixmap = pWindow->devPrivates[rootlessWindowOldPixmapPrivateIndex].ptr;
+        if (oldPixmap != NULL)
+        {
+            if (oldPixmap == curPixmap)
+                RL_DEBUG_MSG("Window %p's curPixmap %p is the same as its oldPixmap; strange\n", pWindow, curPixmap);
+            else
+                RL_DEBUG_MSG("Window %p's existing oldPixmap %p being lost!\n", pWindow, oldPixmap);
+        }
+        pWindow->devPrivates[rootlessWindowOldPixmapPrivateIndex].ptr = curPixmap;
+        pScreen->SetWindowPixmap(pWindow, winRec->pixmap);
+    }
 }
 
 
@@ -179,6 +195,29 @@ void RootlessStartDrawing(WindowPtr pWindow)
  *  Stop drawing to a window's backing buffer. If flush is true,
  *  damaged regions are flushed to the screen.
  */
+static int RestorePreDrawingPixmapVisitor(WindowPtr pWindow, pointer data)
+{
+    RootlessWindowRec *winRec = (RootlessWindowRec*)data;
+    ScreenPtr pScreen = pWindow->drawable.pScreen;
+    PixmapPtr exPixmap = pScreen->GetWindowPixmap(pWindow);
+    PixmapPtr oldPixmap = pWindow->devPrivates[rootlessWindowOldPixmapPrivateIndex].ptr;
+    if (oldPixmap == NULL)
+    {
+        if (exPixmap == winRec->pixmap)
+            RL_DEBUG_MSG("Window %p appears to be in drawing mode (ex-pixmap %p equals winRec->pixmap, which is being freed) but has no oldPixmap!\n", pWindow, exPixmap);
+    }
+    else
+    {
+        if (exPixmap != winRec->pixmap)
+            RL_DEBUG_MSG("Window %p appears to be in drawing mode (oldPixmap %p) but ex-pixmap %p not winRec->pixmap %p!\n", pWindow, oldPixmap, exPixmap, winRec->pixmap);
+        if (oldPixmap == winRec->pixmap)
+            RL_DEBUG_MSG("Window %p's oldPixmap %p is winRec->pixmap, which has just been freed!\n", pWindow, oldPixmap);
+        pScreen->SetWindowPixmap(pWindow, oldPixmap);
+        pWindow->devPrivates[rootlessWindowOldPixmapPrivateIndex].ptr = NULL;
+    }
+    return WT_WALKCHILDREN;
+}
+
 void RootlessStopDrawing(WindowPtr pWindow, Bool flush)
 {
     ScreenPtr pScreen = pWindow->drawable.pScreen;
@@ -195,7 +234,7 @@ void RootlessStopDrawing(WindowPtr pWindow, Bool flush)
         SCREENREC(pScreen)->imp->StopDrawing(winRec->wid, flush);
 
         FreeScratchPixmapHeader(winRec->pixmap);
-        pScreen->SetWindowPixmap(pWindow, winRec->oldPixmap);
+        TraverseTree(top, RestorePreDrawingPixmapVisitor, (pointer)winRec);
         winRec->pixmap = NULL;
 
         winRec->is_drawing = FALSE;
diff --git a/miext/rootless/rootlessCommon.h b/miext/rootless/rootlessCommon.h
index b002214..d3f242e 100644
--- a/miext/rootless/rootlessCommon.h
+++ b/miext/rootless/rootlessCommon.h
@@ -56,6 +56,7 @@
 extern int rootlessGCPrivateIndex;
 extern int rootlessScreenPrivateIndex;
 extern int rootlessWindowPrivateIndex;
+extern int rootlessWindowOldPixmapPrivateIndex;
 
 
 // RootlessGCRec: private per-gc data
diff --git a/miext/rootless/rootlessScreen.c b/miext/rootless/rootlessScreen.c
index b314581..4af395e 100644
--- a/miext/rootless/rootlessScreen.c
+++ b/miext/rootless/rootlessScreen.c
@@ -65,6 +65,7 @@ extern Bool RootlessCreateGC(GCPtr pGC);
 int rootlessGCPrivateIndex = -1;
 int rootlessScreenPrivateIndex = -1;
 int rootlessWindowPrivateIndex = -1;
+int rootlessWindowOldPixmapPrivateIndex = -1;
 
 
 /*
@@ -618,6 +619,8 @@ RootlessAllocatePrivates(ScreenPtr pScreen)
         if (rootlessGCPrivateIndex == -1) return FALSE;
         rootlessWindowPrivateIndex = AllocateWindowPrivateIndex();
         if (rootlessWindowPrivateIndex == -1) return FALSE;
+        rootlessWindowOldPixmapPrivateIndex = AllocateWindowPrivateIndex();
+        if (rootlessWindowOldPixmapPrivateIndex == -1) return FALSE;
         rootlessGeneration = serverGeneration;
     }
 
@@ -627,6 +630,8 @@ RootlessAllocatePrivates(ScreenPtr pScreen)
         return FALSE;
     if (!AllocateWindowPrivate(pScreen, rootlessWindowPrivateIndex, 0))
         return FALSE;
+    if (!AllocateWindowPrivate(pScreen, rootlessWindowOldPixmapPrivateIndex, 0))
+        return FALSE;
 
     s = xalloc(sizeof(RootlessScreenRec));
     if (! s) return FALSE;
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index cf32426..82f54d6 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -198,6 +198,7 @@ RootlessCreateWindow(WindowPtr pWin)
     RegionRec saveRoot;
 
     WINREC(pWin) = NULL;
+    pWin->devPrivates[rootlessWindowOldPixmapPrivateIndex].ptr = NULL;
 
     SCREEN_UNWRAP(pWin->drawable.pScreen, CreateWindow);
 
commit 0cf45239c21326de8bbd3d2b6f3d68685173ceb3
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 14 21:25:50 2007 -0800

    Build system patches to remove XDarwin from the build (since it doesn't
    work anyway), courtesy of Jeremy Huddleston

diff --git a/configure.ac b/configure.ac
index 386776d..3c9aa04 100644
--- a/configure.ac
+++ b/configure.ac
@@ -513,9 +513,8 @@ AC_ARG_ENABLE(xorg,    	      AS_HELP_STRING([--enable-xorg], [Build Xorg server
 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: no)]), [XVFB=$enableval], [XVFB=no])
 AC_ARG_ENABLE(xnest,   	      AS_HELP_STRING([--enable-xnest], [Build Xnest server (default: no)]), [XNEST=$enableval], [XNEST=no])
-AC_ARG_ENABLE(xdarwin, 	      AS_HELP_STRING([--enable-xdarwin], [Build XDarwin server (default: auto)]), [XDARWIN=$enableval], [XDARWIN=auto])
-AC_ARG_ENABLE(xquartz,        AS_HELP_STRING([--disable-xquartz], [Build Xquartz server on Darwin (default: auto)]), [XQUARTZ=$enableval], [XQUARTZ=auto])
-AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app wrapper for Xquartz (default: auto)]), [X11APP=$enableval], [X11APP=auto])
+AC_ARG_ENABLE(xquartz,        AS_HELP_STRING([--enable-xquartz], [Build Xquartz server for OS-X (default: auto)]), [XQUARTZ=$enableval], [XQUARTZ=auto])
+AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app for Xquartz (default: auto)]), [X11APP=$enableval], [X11APP=auto])
 AC_ARG_ENABLE(xwin,    	      AS_HELP_STRING([--enable-xwin], [Build XWin server (default: auto)]), [XWIN=$enableval], [XWIN=auto])
 AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
 AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (default: no)]), [XGL=$enableval], [XGL=no])
@@ -1604,33 +1603,24 @@ 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
-AC_MSG_CHECKING([whether to build XDarwin/Xquartz])
-if test "x$XDARWIN" = xauto; then
-	case $host_os in
-		darwin*) XDARWIN="yes" ;;
-		*) XDARWIN="no" ;;
-	esac
-fi
-AC_MSG_RESULT([$XDARWIN])
-
-if test "x$XDARWIN" = xyes; then
-	if test "X$XQUARTZ" = Xauto; then
-		AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
-		 	save_LDFLAGS=$LDFLAGS
-			LDFLAGS="$LDFLAGS -framework Carbon"
-			AC_LINK_IFELSE([char FSFindFolder(); int main() { FSFindFolder(); return 0;}],
-				[xorg_cv_Carbon_framework=yes],
-				[xorg_cv_Carbon_framework=no])
-			LDFLAGS=$save_LDFLAGS])
-                 
-		if test "X$xorg_cv_Carbon_framework" = Xyes; then
-			AC_DEFINE([DARWIN_WITH_QUARTZ],[1],[Have Quartz])
-			XQUARTZ=yes
-		else
-			XQUARTZ=no
-		fi
+if test "X$XQUARTZ" = Xauto; then
+	AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
+	 	save_LDFLAGS=$LDFLAGS
+		LDFLAGS="$LDFLAGS -framework Carbon"
+		AC_LINK_IFELSE([char FSFindFolder(); int main() { FSFindFolder(); return 0;}],
+			[xorg_cv_Carbon_framework=yes],
+			[xorg_cv_Carbon_framework=no])
+		LDFLAGS=$save_LDFLAGS])
+                
+	if test "X$xorg_cv_Carbon_framework" = Xyes; then
+		AC_DEFINE([DARWIN_WITH_QUARTZ],[1],[Have Quartz])
+		XQUARTZ=yes
+	else
+		XQUARTZ=no
 	fi
+fi
 
+if test "x$XQUARTZ" = xyes; then
 	if test "x$X11APP" = xauto; then
 		AC_MSG_CHECKING([whether to build X11.app])
 		if test "x$XQUARTZ" = xyes ; then
@@ -1694,7 +1684,6 @@ AC_SUBST([OBJCFLAGS])
 _AM_DEPENDENCIES([OBJC])
 AM_CONDITIONAL(HAVE_XPLUGIN, [test "x$ac_cv_lib_Xplugin_xp_init" = xyes])
 AM_CONDITIONAL(HAVE_AGL_FRAMEWORK, [test "x$xorg_cv_AGL_framework" = xyes])
-AM_CONDITIONAL(XDARWIN, [test "x$XDARWIN" = xyes])
 AM_CONDITIONAL(XQUARTZ, [test "x$XQUARTZ" = xyes])
 AM_CONDITIONAL(X11APP,[test "X$X11APP" = Xyes]) 
 
diff --git a/hw/Makefile.am b/hw/Makefile.am
index db76977..6a15820 100644
--- a/hw/Makefile.am
+++ b/hw/Makefile.am
@@ -22,7 +22,7 @@ if XPRINT
 XPRINT_SUBDIRS = xprint
 endif
 
-if XDARWIN
+if XQUARTZ
 DARWIN_SUBDIRS = darwin
 endif
 
diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 04d9965..e83f04d 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -1,98 +1,27 @@
-noinst_LIBRARIES = libdarwinShared.a
-libdarwin_XINPUT_SRCS = darwinXinput.c
-
 AM_CFLAGS = @XORG_CFLAGS@
-INCLUDES = @XORG_INCS@ -I../../miext/rootless
-
-DEFS = @DEFS@ -DUSE_NEW_CLUT -DXFree86Server -DBUILD_DATE=\"$(BUILD_DATE)\" 
-
-if XQUARTZ
-XQUARTZ_SUBDIRS = quartz
-endif
-
-SUBDIRS = \
-	  iokit \
-	  $(XQUARTZ_SUBDIRS) \
-	  utils
-
-DIST_SUBDIRS = \
-	  iokit \
-	  quartz \
-	  utils
-
-libdarwinShared_a_SOURCES = darwin.c \
-			  darwinEvents.c \
-			  darwinKeyboard.c \
-			  $(darwin_XINPUT_SRCS) 
-
-if XQUARTZ
+AM_CPPFLAGS = @XORG_INCS@ -I../../miext/rootless -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" -DHAVE_XORG_CONFIG_H -DXFree86Server
+  
+SUBDIRS = quartz utils
+  
 bin_PROGRAMS = Xquartz
-else
-bin_PROGRAMS = XDarwin
-endif
-
-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/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 = \
+man1_MANS = apple/Xquartz.man
+  
+Xquartz_SOURCES = darwin.c \
+		  darwinEvents.c \
+		  darwinKeyboard.c \
+		  darwinXinput.c \
+		  $(top_srcdir)/fb/fbcmap.c \
+		  $(top_srcdir)/mi/miinitext.c
+
+#		We should probably add these once they're working, or are these obsolete and to be removed?
+#		./quartz/cr/libcr.a
+#		./quartz/fullscreen/libfullscreen.a
+
+Xquartz_LDADD = ./quartz/libXquartz.a \
+		./quartz/xpr/libxpr.a \
 		$(top_builddir)/dix/dixfonts.lo \
 		$(top_builddir)/dix/libdix.la \
 		$(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 \
-		$(XSERVER_LIBS) -lXplugin
-
-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 \
@@ -114,33 +43,24 @@ Xquartz_LDADD = \
 		$(top_builddir)/miext/rootless/accel/librlAccel.la \
 		$(DARWIN_LIBS) $(XSERVER_LIBS) -lXplugin
 
-XDarwin_LDFLAGS =  \
-                 -XCClinker -Objc \
-                 -Wl,-u,_miDCInitialize \
-                 -Wl,-framework,IOKit
-
-Xquartz_LDFLAGS =  \
-                 -XCClinker -Objc \
-                 -Wl,-u,_miDCInitialize \
-                 -Wl,-framework,Carbon \
-	         -L/System/Library/Frameworks/OpenGL.framework/Libraries -lGL \
-                 -Wl,-framework,OpenGL \
-                 -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
-Xquartz_OBJCFLAGS = -DINXQUARTZ -DHAS_CG_MACH_PORT -DHAS_KL_API  -DHAVE_XORG_CONFIG_H
+Xquartz_LDFLAGS =  -XCClinker -Objc \
+		   -Wl,-u,_miDCInitialize \
+		   -Wl,-framework,Carbon \
+		   -L/System/Library/Frameworks/OpenGL.framework/Libraries -lGL \
+		   -Wl,-framework,OpenGL \
+		   -Wl,-framework,Cocoa \
+		   -Wl,-framework,CoreAudio \
+	  	   -Wl,-framework,IOKit
 
 if X11APP
 bin_SCRIPTS = x11app x11launcher
 
 x11app:
-	cd apple && xcodebuild CFLAGS="$(XSERVERCFLAGS_CFLAGS)" LDFLAGS="$(XSERVERCFLAGS_LIBS)"
+	cd apple && xcodebuild CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)"
 
 x11launcher:
-	cd launcher && xcodebuild CFLAGS="$(XSERVERCFLAGS_CFLAGS)" LDFLAGS="$(XSERVERCFLAGS_LIBS)"
+	cd launcher && xcodebuild CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)"
 
 x11app-install:
 	cd apple && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(prefix) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
@@ -156,19 +76,12 @@ x11launcher-clean:
 
 install-data-hook: x11app-install x11launcher-install
 clean-local: x11app-clean x11launcher-clean
-
 endif
 
-man1_MANS = XDarwin.man
-
 EXTRA_DIST = \
-	darwin.c \
 	darwinClut8.h \
-	darwinEvents.c \
 	darwin.h \
-	darwinKeyboard.c \
 	darwinKeyboard.h \
-	darwinXinput.c \
 	apple/X11Application.h \
 	apple/X11Controller.h \
 	apple/Info.plist \
@@ -184,5 +97,4 @@ EXTRA_DIST = \
 	launcher/bundle-main.c \
 	launcher/Info.plist \
 	launcher/X11.icns \
-	launcher/X11.xcodeproj/project.pbxproj \
-	XDarwin.man
+	launcher/X11.xcodeproj/project.pbxproj
diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
index baa7d44..5a78bfb 100644
--- a/hw/darwin/quartz/Makefile.am
+++ b/hw/darwin/quartz/Makefile.am
@@ -2,41 +2,30 @@ noinst_LIBRARIES = libXQuartz.a
 
 AM_CFLAGS = @XORG_CFLAGS@
 AM_OBJCFLAGS = @XORG_CFLAGS@
+AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/.. @XORG_INCS@ -DXBINDIR=\"${bindir}\" -DINXQUARTZ -DHAS_KL_API -DHAVE_XORG_CONFIG_H
 
-INCLUDES = -I$(srcdir) -I$(srcdir)/.. @XORG_INCS@
-AM_DEFS = -DHAS_CG_MACH_PORT -DHAS_KL_API
-AM_DEFS += -DBUILD_XPR
-XPR = xpr
-
-DEFS = @DEFS@ $(AM_DEFS) -DXBINDIR=\"${bindir}\"
-SUBDIRS = cr fullscreen $(XPR)
+SUBDIRS = cr fullscreen xpr
 
 libXQuartz_a_SOURCES = \
-		  Preferences.m \
-	          XApplication.m \
-	          XServer.m \
+		  ../apple/X11Application.m \
+		  ../apple/X11Controller.m \
 	          applewm.c \
 	          keysym2ucs.c \
+	          pseudoramiX.c \
 	          quartz.c \
 	          quartzAudio.c \
 	          quartzCocoa.m \
-	          quartzPasteboard.c \
 	          quartzKeyboard.c \
-	          quartzStartup.c \
-	          pseudoramiX.c
+	          quartzPasteboard.c \
+	          quartzStartup.c
 
 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
+	quartzPasteboard.h
diff --git a/hw/darwin/quartz/cr/Makefile.am b/hw/darwin/quartz/cr/Makefile.am
index abfac99..ff6043d 100644
--- a/hw/darwin/quartz/cr/Makefile.am
+++ b/hw/darwin/quartz/cr/Makefile.am
@@ -1,8 +1,8 @@
 noinst_LIBRARIES = libcr.a
 AM_CFLAGS =  @XORG_CFLAGS@
 AM_OBJCFLAGS =  @XORG_CFLAGS@
-DEFS = @DEFS@ -DDEFER_NSWINDOW
-INCLUDES = @XORG_INCS@ \
+AM_CPPFLAGS = -DDEFER_NSWINDOW \
+	   @XORG_INCS@ \
 	   -I../fullscreen \
 	   -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. \
 	   -I$(top_srcdir)/miext/rootless \
diff --git a/hw/darwin/quartz/fullscreen/Makefile.am b/hw/darwin/quartz/fullscreen/Makefile.am
index 37c767c..5e471ad 100644
--- a/hw/darwin/quartz/fullscreen/Makefile.am
+++ b/hw/darwin/quartz/fullscreen/Makefile.am
@@ -1,6 +1,6 @@
 noinst_LIBRARIES = libfullscreen.a
 AM_CFLAGS = @XORG_CFLAGS@
-INCLUDES = @XORG_INCS@ -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. 
+AM_CPPFLAGS = @XORG_INCS@ -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. 
 
 libfullscreen_a_SOURCES = fullscreen.c \
 			   quartzCursor.c
diff --git a/hw/darwin/quartz/xpr/Makefile.am b/hw/darwin/quartz/xpr/Makefile.am
index 7ebcba7..1f19fe9 100644
--- a/hw/darwin/quartz/xpr/Makefile.am
+++ b/hw/darwin/quartz/xpr/Makefile.am
@@ -1,6 +1,7 @@
 noinst_LIBRARIES = libxpr.a
 AM_CFLAGS =  @XORG_CFLAGS@
-INCLUDES = @XORG_INCS@ \
+AM_CPPFLAGS = @XORG_INCS@ \
+	   -DHAVE_XORG_CONFIG_H \
 	   -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. \
 	   -I$(top_srcdir)/miext/rootless \
 	   -I$(top_srcdir)/miext/rootless/safeAlpha \
@@ -17,8 +18,6 @@ libxpr_a_SOURCES = \
         x-hook.c \
         x-list.c
 
-xprbundledir = @APPLE_APPLICATIONS_DIR@/Resources/xpr.bundle/Contents/MacOS
-
 EXTRA_DIST = \
 	dri.h \
 	dristruct.h \
diff --git a/mi/miinitext.c b/mi/miinitext.c
index f15d0c9..3ccd456 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -338,18 +338,11 @@ extern void XFree86DGAExtensionInit(INITARGS);
 #endif
 #ifdef GLXEXT
 typedef struct __GLXprovider __GLXprovider;
-#if defined(__DARWIN__) && defined(INXDARWINAPP)
-extern __GLXprovider* __DarwinglXMesaProvider;
-extern void DarwinGlxPushProvider(__GLXprovider *impl);
-extern void DarwinGlxExtensionInit(INITARGS);
-extern void DarwinGlxWrapInitVisuals(miInitVisualsProcPtr *);
-#else
 extern __GLXprovider __glXMesaProvider;
 extern void GlxPushProvider(__GLXprovider *impl);
 extern void GlxExtensionInit(INITARGS);
 extern void GlxWrapInitVisuals(miInitVisualsProcPtr *);
 #endif
-#endif
 #ifdef XF86DRI
 extern void XFree86DRIExtensionInit(INITARGS);
 #endif
@@ -632,14 +625,9 @@ InitExtensions(argc, argv)
 #endif
 #endif
 #ifdef GLXEXT
-#if defined(__DARWIN__) && defined(INXDARWINAPP)
-    DarwinGlxPushProvider(__DarwinglXMesaProvider);
-    if (!noGlxExtension) DarwinGlxExtensionInit();
-#else
     GlxPushProvider(&__glXMesaProvider);
     if (!noGlxExtension) GlxExtensionInit();
 #endif
-#endif
 #ifdef XFIXES
     /* must be before Render to layer DisplayCursor correctly */
     if (!noXFixesExtension) XFixesExtensionInit();
commit 51e0071e3228fc9fbec2588a7abf4cb681311a4f
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 14 21:09:21 2007 -0800

    bump to 1.2a10

diff --git a/configure.ac b/configure.ac
index 4daccc0..386776d 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.2a9, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a10, [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 --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 7132186..df42c1b 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -156,7 +156,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a9)",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a10)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
commit ed6d0b75e6c3022114e704f3dc3f9e4782fdcffe
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 14 04:26:25 2007 -0800

    Trying to add launchd detection to tell Xtrans
    to enable launchd support; fix me later.

diff --git a/configure.ac b/configure.ac
index 6d0030c..4daccc0 100644
--- a/configure.ac
+++ b/configure.ac
@@ -71,6 +71,9 @@ AC_HEADER_STDC
 AC_CHECK_HEADERS([fcntl.h stdlib.h string.h unistd.h])
 
 AC_CHECK_PROG(HAVE_LAUNCHD, [launchd], [yes], [])
+if test "x$HAVE_LAUNCHD" = xyes; then
+	AC_DEFINE(HAS_LAUNCHD, 1, [launchd support available])
+fi
 
 dnl Checks for typedefs, structures, and compiler characteristics.
 AC_C_CONST
@@ -1656,7 +1659,7 @@ if test "x$XDARWIN" = xyes; then
 	       AC_SUBST([DARWIN_LIBS])
                AC_CHECK_LIB([Xplugin],[xp_init],[:])
                AC_SUBST([APPLE_APPLICATIONS_DIR])
-               CFLAGS="${CFLAGS} -D__DARWIN__ -DDARWIN_WITH_QUARTZ -DROOTLESS_WORKAROUND"
+               CFLAGS="${CFLAGS} -DHAVE_LAUNCHD -D__DARWIN__ -DDARWIN_WITH_QUARTZ -DROOTLESS_WORKAROUND"
                PLIST_VERSION_STRING=$PACKAGE_VERSION
                AC_SUBST([PLIST_VERSION_STRING])
                PLIST_VENDOR_WEB=$VENDOR_WEB
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 5efd356..6badcca 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -127,6 +127,9 @@
 /* Define to 1 if you have the <inttypes.h> header file. */
 #undef HAVE_INTTYPES_H
 
+/* Define to 1 if launchd is available. */
+#undef HAVE_LAUNCHD
+
 /* Define to 1 if you have the `m' library (-lm). */
 #undef HAVE_LIBM
 
commit 2450788d32ded73dc8cb6d8c89f0d235dc02310b
Author: Ben Byer <bbyer at bbyer.local>
Date:   Tue Nov 13 01:09:16 2007 -0800

    Revert "Revert "These changes are necessary, yet not sufficient, to get 8-bit indexed""
    
    This reverts commit 45f8601692cf31bc3acdab56fad6688064bbdcb6.
    bah, not needed

diff --git a/miext/rootless/rootlessCommon.c b/miext/rootless/rootlessCommon.c
index 8fd922d..fc22b1b 100644
--- a/miext/rootless/rootlessCommon.c
+++ b/miext/rootless/rootlessCommon.c
@@ -34,6 +34,7 @@
 #endif
 
 #include "rootlessCommon.h"
+#include "colormapst.h"
 
 unsigned int rootless_CopyBytes_threshold = 0;
 unsigned int rootless_FillBytes_threshold = 0;
@@ -95,6 +96,41 @@ IsFramedWindow(WindowPtr pWin)
     return (top && WINREC(top));
 }
 
+Bool
+RootlessResolveColormap (ScreenPtr pScreen, int first_color,
+                         int n_colors, uint32_t *colors)
+{
+  int last, i;
+  ColormapPtr map;
+
+  map = RootlessGetColormap (pScreen);
+  if (map == NULL || map->class != PseudoColor) return FALSE;
+
+  last = MIN (map->pVisual->ColormapEntries, first_color + n_colors);
+  for (i = MAX (0, first_color); i < last; i++) {
+    Entry *ent = map->red + i;
+    uint16_t red, green, blue;
+
+      if (!ent->refcnt)	continue;
+      if (ent->fShared) {
+	red = ent->co.shco.red->color;
+	green = ent->co.shco.green->color;
+	blue = ent->co.shco.blue->color;
+      } else {
+	red = ent->co.local.red;
+	green = ent->co.local.green;
+	blue = ent->co.local.blue;
+      }
+
+      colors[i - first_color] = (0xFF000000UL
+				 | ((uint32_t) red & 0xff00) << 8
+				 | (green & 0xff00)
+				 | (blue >> 8));
+    }
+
+  return TRUE;
+}
+
 
 /*
  * RootlessStartDrawing
diff --git a/miext/rootless/rootlessCommon.h b/miext/rootless/rootlessCommon.h
index 3bf6af0..b002214 100644
--- a/miext/rootless/rootlessCommon.h
+++ b/miext/rootless/rootlessCommon.h
@@ -32,6 +32,7 @@
 #include <dix-config.h>
 #endif
 
+#include <stdint.h>
 #ifndef _ROOTLESSCOMMON_H
 #define _ROOTLESSCOMMON_H
 
@@ -104,13 +105,20 @@ typedef struct _RootlessScreenRec {
     GlyphsProcPtr Glyphs;
 #endif
 
+    InstallColormapProcPtr InstallColormap;
+    UninstallColormapProcPtr UninstallColormap;
+    StoreColorsProcPtr StoreColors;
+
     void *pixmap_data;
     unsigned int pixmap_data_size;
 
+    ColormapPtr colormap;
+
     void *redisplay_timer;
     unsigned int redisplay_timer_set :1;
     unsigned int redisplay_queued :1;
     unsigned int redisplay_expired :1;
+    unsigned int colormap_changed :1;
 } RootlessScreenRec, *RootlessScreenPtr;
 
 
@@ -251,6 +259,16 @@ void RootlessRedisplayScreen(ScreenPtr pScreen);
 
 void RootlessQueueRedisplay(ScreenPtr pScreen);
 
+/* Return the colormap currently installed on the given screen. */
+ColormapPtr RootlessGetColormap (ScreenPtr pScreen);
+
+/* Convert colormap to ARGB. */
+Bool RootlessResolveColormap (ScreenPtr pScreen, int first_color,
+			      int n_colors, uint32_t *colors);
+
+void RootlessFlushWindowColormap (WindowPtr pWin);
+void RootlessFlushScreenColormaps (ScreenPtr pScreen);
+
 // Move a window to its proper location on the screen.
 void RootlessRepositionWindow(WindowPtr pWin);
 
diff --git a/miext/rootless/rootlessScreen.c b/miext/rootless/rootlessScreen.c
index 356fec7..b314581 100644
--- a/miext/rootless/rootlessScreen.c
+++ b/miext/rootless/rootlessScreen.c
@@ -42,6 +42,7 @@
 #include "propertyst.h"
 #include "mivalidate.h"
 #include "picturestr.h"
+#include "colormapst.h"
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -469,6 +470,67 @@ RootlessMarkOverlappedWindows(WindowPtr pWin, WindowPtr pFirst,
     return result;
 }
 
+ColormapPtr
+RootlessGetColormap (ScreenPtr pScreen)
+{
+  RootlessScreenRec *s = SCREENREC (pScreen);
+
+  return s->colormap;
+}
+
+static void
+RootlessInstallColormap (ColormapPtr pMap)
+{
+  ScreenPtr pScreen = pMap->pScreen;
+  RootlessScreenRec *s = SCREENREC (pScreen);
+
+  SCREEN_UNWRAP(pScreen, InstallColormap);
+
+  if (s->colormap != pMap) {
+    s->colormap = pMap;
+    s->colormap_changed = TRUE;
+    RootlessQueueRedisplay (pScreen);
+  }
+
+  pScreen->InstallColormap (pMap);
+
+  SCREEN_WRAP (pScreen, InstallColormap);
+}
+
+static void
+RootlessUninstallColormap (ColormapPtr pMap)
+{
+  ScreenPtr pScreen = pMap->pScreen;
+  RootlessScreenRec *s = SCREENREC (pScreen);
+
+  SCREEN_UNWRAP(pScreen, UninstallColormap);
+
+  if (s->colormap == pMap)
+    s->colormap = NULL;
+
+  pScreen->UninstallColormap (pMap);
+
+  SCREEN_WRAP(pScreen, UninstallColormap);
+}
+
+static void
+RootlessStoreColors (ColormapPtr pMap, int ndef, xColorItem *pdef)
+{
+  ScreenPtr pScreen = pMap->pScreen;
+  RootlessScreenRec *s = SCREENREC (pScreen);
+
+  SCREEN_UNWRAP(pScreen, StoreColors);
+
+  if (s->colormap == pMap && ndef > 0) {
+    s->colormap_changed = TRUE;
+    RootlessQueueRedisplay (pScreen);
+  }
+
+  pScreen->StoreColors (pMap, ndef, pdef);
+
+  SCREEN_WRAP(pScreen, StoreColors);
+}
+
 
 static CARD32
 RootlessRedisplayCallback(OsTimerPtr timer, CARD32 time, void *arg)
@@ -616,6 +678,9 @@ RootlessWrap(ScreenPtr pScreen)
     WRAP(MarkOverlappedWindows);
     WRAP(ValidateTree);
     WRAP(ChangeWindowAttributes);
+    WRAP(InstallColormap);
+    WRAP(UninstallColormap);
+    WRAP(StoreColors);
 
 #ifdef SHAPE
     WRAP(SetShape);
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index 84aa91d..cf32426 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -447,6 +447,12 @@ RootlessInitializeFrame(WindowPtr pWin, RootlessWindowRec *winRec)
 }
 
 
+Bool
+RootlessColormapCallback (void *data, int first_color, int n_colors, uint32_t *colors)
+{
+  return RootlessResolveColormap (data, first_color, n_colors, colors);
+}
+
 /*
  * RootlessEnsureFrame
  *  Make sure the given window is framed. If the window doesn't have a
@@ -505,6 +511,9 @@ RootlessEnsureFrame(WindowPtr pWin)
         return NULL;
     }
 
+    if (pWin->drawable.depth == 8)
+      RootlessFlushWindowColormap(pWin);
+
 #ifdef SHAPE
     if (pShape != NULL)
         REGION_UNINIT(pScreen, &shape);
@@ -1458,6 +1467,25 @@ out:
 }
 
 
+void
+RootlessFlushWindowColormap (WindowPtr pWin)
+{
+  RootlessWindowRec *winRec = WINREC (pWin);
+  xp_window_changes wc;
+
+  if (winRec == NULL)
+    return;
+
+  RootlessStopDrawing (pWin, FALSE);
+
+  /* This is how we tell xp that the colormap may have changed. */
+
+  wc.colormap = RootlessColormapCallback;
+  wc.colormap_data = pWin->drawable.pScreen;
+
+  configure_window (winRec->wid, XP_COLORMAP, &wc);
+}
+
 /*
  * SetPixmapOfAncestors
  *  Set the Pixmaps on all ParentRelative windows up the ancestor chain.
commit 9523ea00f603b941de32049f1fb8b0bf5d4c1afa
Author: Ben Byer <bbyer at bbyer.local>
Date:   Tue Nov 13 01:08:02 2007 -0800

    fix missing -DXFree86Server; this needs to be defined when building
    fb/fbcmap.c or else you get the "sunglasses effect"

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index d41e7cc..04d9965 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -4,7 +4,7 @@ libdarwin_XINPUT_SRCS = darwinXinput.c
 AM_CFLAGS = @XORG_CFLAGS@
 INCLUDES = @XORG_INCS@ -I../../miext/rootless
 
-DEFS = @DEFS@ -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" 
+DEFS = @DEFS@ -DUSE_NEW_CLUT -DXFree86Server -DBUILD_DATE=\"$(BUILD_DATE)\" 
 
 if XQUARTZ
 XQUARTZ_SUBDIRS = quartz
commit 983088ed28f258fdb75ed9754670caaac9650dd2
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Nov 12 21:33:04 2007 -0800

    Revert "These changes are necessary, yet not sufficient, to get 8-bit indexed"
    
    This reverts commit 7baba3f6b8db059ff984afbe23a43d89638ccb0e.
    This should hopefully prevent the "sunglasses" problem aka
    "why is my xterm black"?

diff --git a/miext/rootless/rootlessCommon.c b/miext/rootless/rootlessCommon.c
index fc22b1b..8fd922d 100644
--- a/miext/rootless/rootlessCommon.c
+++ b/miext/rootless/rootlessCommon.c
@@ -34,7 +34,6 @@
 #endif
 
 #include "rootlessCommon.h"
-#include "colormapst.h"
 
 unsigned int rootless_CopyBytes_threshold = 0;
 unsigned int rootless_FillBytes_threshold = 0;
@@ -96,41 +95,6 @@ IsFramedWindow(WindowPtr pWin)
     return (top && WINREC(top));
 }
 
-Bool
-RootlessResolveColormap (ScreenPtr pScreen, int first_color,
-                         int n_colors, uint32_t *colors)
-{
-  int last, i;
-  ColormapPtr map;
-
-  map = RootlessGetColormap (pScreen);
-  if (map == NULL || map->class != PseudoColor) return FALSE;
-
-  last = MIN (map->pVisual->ColormapEntries, first_color + n_colors);
-  for (i = MAX (0, first_color); i < last; i++) {
-    Entry *ent = map->red + i;
-    uint16_t red, green, blue;
-
-      if (!ent->refcnt)	continue;
-      if (ent->fShared) {
-	red = ent->co.shco.red->color;
-	green = ent->co.shco.green->color;
-	blue = ent->co.shco.blue->color;
-      } else {
-	red = ent->co.local.red;
-	green = ent->co.local.green;
-	blue = ent->co.local.blue;
-      }
-
-      colors[i - first_color] = (0xFF000000UL
-				 | ((uint32_t) red & 0xff00) << 8
-				 | (green & 0xff00)
-				 | (blue >> 8));
-    }
-
-  return TRUE;
-}
-
 
 /*
  * RootlessStartDrawing
diff --git a/miext/rootless/rootlessCommon.h b/miext/rootless/rootlessCommon.h
index b002214..3bf6af0 100644
--- a/miext/rootless/rootlessCommon.h
+++ b/miext/rootless/rootlessCommon.h
@@ -32,7 +32,6 @@
 #include <dix-config.h>
 #endif
 
-#include <stdint.h>
 #ifndef _ROOTLESSCOMMON_H
 #define _ROOTLESSCOMMON_H
 
@@ -105,20 +104,13 @@ typedef struct _RootlessScreenRec {
     GlyphsProcPtr Glyphs;
 #endif
 
-    InstallColormapProcPtr InstallColormap;
-    UninstallColormapProcPtr UninstallColormap;
-    StoreColorsProcPtr StoreColors;
-
     void *pixmap_data;
     unsigned int pixmap_data_size;
 
-    ColormapPtr colormap;
-
     void *redisplay_timer;
     unsigned int redisplay_timer_set :1;
     unsigned int redisplay_queued :1;
     unsigned int redisplay_expired :1;
-    unsigned int colormap_changed :1;
 } RootlessScreenRec, *RootlessScreenPtr;
 
 
@@ -259,16 +251,6 @@ void RootlessRedisplayScreen(ScreenPtr pScreen);
 
 void RootlessQueueRedisplay(ScreenPtr pScreen);
 
-/* Return the colormap currently installed on the given screen. */
-ColormapPtr RootlessGetColormap (ScreenPtr pScreen);
-
-/* Convert colormap to ARGB. */
-Bool RootlessResolveColormap (ScreenPtr pScreen, int first_color,
-			      int n_colors, uint32_t *colors);
-
-void RootlessFlushWindowColormap (WindowPtr pWin);
-void RootlessFlushScreenColormaps (ScreenPtr pScreen);
-
 // Move a window to its proper location on the screen.
 void RootlessRepositionWindow(WindowPtr pWin);
 
diff --git a/miext/rootless/rootlessScreen.c b/miext/rootless/rootlessScreen.c
index b314581..356fec7 100644
--- a/miext/rootless/rootlessScreen.c
+++ b/miext/rootless/rootlessScreen.c
@@ -42,7 +42,6 @@
 #include "propertyst.h"
 #include "mivalidate.h"
 #include "picturestr.h"
-#include "colormapst.h"
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -470,67 +469,6 @@ RootlessMarkOverlappedWindows(WindowPtr pWin, WindowPtr pFirst,
     return result;
 }
 
-ColormapPtr
-RootlessGetColormap (ScreenPtr pScreen)
-{
-  RootlessScreenRec *s = SCREENREC (pScreen);
-
-  return s->colormap;
-}
-
-static void
-RootlessInstallColormap (ColormapPtr pMap)
-{
-  ScreenPtr pScreen = pMap->pScreen;
-  RootlessScreenRec *s = SCREENREC (pScreen);
-
-  SCREEN_UNWRAP(pScreen, InstallColormap);
-
-  if (s->colormap != pMap) {
-    s->colormap = pMap;
-    s->colormap_changed = TRUE;
-    RootlessQueueRedisplay (pScreen);
-  }
-
-  pScreen->InstallColormap (pMap);
-
-  SCREEN_WRAP (pScreen, InstallColormap);
-}
-
-static void
-RootlessUninstallColormap (ColormapPtr pMap)
-{
-  ScreenPtr pScreen = pMap->pScreen;
-  RootlessScreenRec *s = SCREENREC (pScreen);
-
-  SCREEN_UNWRAP(pScreen, UninstallColormap);
-
-  if (s->colormap == pMap)
-    s->colormap = NULL;
-
-  pScreen->UninstallColormap (pMap);
-
-  SCREEN_WRAP(pScreen, UninstallColormap);
-}
-
-static void
-RootlessStoreColors (ColormapPtr pMap, int ndef, xColorItem *pdef)
-{
-  ScreenPtr pScreen = pMap->pScreen;
-  RootlessScreenRec *s = SCREENREC (pScreen);
-
-  SCREEN_UNWRAP(pScreen, StoreColors);
-
-  if (s->colormap == pMap && ndef > 0) {
-    s->colormap_changed = TRUE;
-    RootlessQueueRedisplay (pScreen);
-  }
-
-  pScreen->StoreColors (pMap, ndef, pdef);
-
-  SCREEN_WRAP(pScreen, StoreColors);
-}
-
 
 static CARD32
 RootlessRedisplayCallback(OsTimerPtr timer, CARD32 time, void *arg)
@@ -678,9 +616,6 @@ RootlessWrap(ScreenPtr pScreen)
     WRAP(MarkOverlappedWindows);
     WRAP(ValidateTree);
     WRAP(ChangeWindowAttributes);
-    WRAP(InstallColormap);
-    WRAP(UninstallColormap);
-    WRAP(StoreColors);
 
 #ifdef SHAPE
     WRAP(SetShape);
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index cf32426..84aa91d 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -447,12 +447,6 @@ RootlessInitializeFrame(WindowPtr pWin, RootlessWindowRec *winRec)
 }
 
 
-Bool
-RootlessColormapCallback (void *data, int first_color, int n_colors, uint32_t *colors)
-{
-  return RootlessResolveColormap (data, first_color, n_colors, colors);
-}
-
 /*
  * RootlessEnsureFrame
  *  Make sure the given window is framed. If the window doesn't have a
@@ -511,9 +505,6 @@ RootlessEnsureFrame(WindowPtr pWin)
         return NULL;
     }
 
-    if (pWin->drawable.depth == 8)
-      RootlessFlushWindowColormap(pWin);
-
 #ifdef SHAPE
     if (pShape != NULL)
         REGION_UNINIT(pScreen, &shape);
@@ -1467,25 +1458,6 @@ out:
 }
 
 
-void
-RootlessFlushWindowColormap (WindowPtr pWin)
-{
-  RootlessWindowRec *winRec = WINREC (pWin);
-  xp_window_changes wc;
-
-  if (winRec == NULL)
-    return;
-
-  RootlessStopDrawing (pWin, FALSE);
-
-  /* This is how we tell xp that the colormap may have changed. */
-
-  wc.colormap = RootlessColormapCallback;
-  wc.colormap_data = pWin->drawable.pScreen;
-
-  configure_window (winRec->wid, XP_COLORMAP, &wc);
-}
-
 /*
  * SetPixmapOfAncestors
  *  Set the Pixmaps on all ParentRelative windows up the ancestor chain.
commit 9f33e822627f9b1efbcabcc28e48102859f4ba4f
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Nov 12 21:32:21 2007 -0800

    bump to 1.2a9

diff --git a/configure.ac b/configure.ac
index 770c292..6d0030c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.2a8, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a9, [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 --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 92d369b..7132186 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -156,7 +156,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a8)",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a9)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
commit 40be575058a1d5a8c3e77d2f1bbf242f19dd1b65
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Nov 12 20:10:10 2007 -0800

    null pointer check

diff --git a/hw/darwin/darwinEvents.c b/hw/darwin/darwinEvents.c
index c9b30ee..85ae305 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -154,6 +154,7 @@ static void DarwinReleaseModifiers(void) {
   xEvent ke;
   int i = 0, j = 0, nevents = 0; 
  
+  if (!darwinKeyc) return;
   map = darwinKeyc->curKeySyms.map;
   
   for (i = darwinKeyc->curKeySyms.minKeyCode, map = darwinKeyc->curKeySyms.map;
commit 09019357629e85e42a63b9aa07b4e708424965cb
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Nov 12 19:08:40 2007 -0800

    More build system fixes from Jeremy

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index ccaacfd..d41e7cc 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -13,8 +13,12 @@ endif
 SUBDIRS = \
 	  iokit \
 	  $(XQUARTZ_SUBDIRS) \
-	  utils \
-	  .
+	  utils
+
+DIST_SUBDIRS = \
+	  iokit \
+	  quartz \
+	  utils
 
 libdarwinShared_a_SOURCES = darwin.c \
 			  darwinEvents.c \
@@ -138,18 +142,25 @@ x11app:
 x11launcher:
 	cd launcher && xcodebuild CFLAGS="$(XSERVERCFLAGS_CFLAGS)" LDFLAGS="$(XSERVERCFLAGS_LIBS)"
 
-x11app-install-hook:
-	cd apple && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(prefixdir) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
+x11app-install:
+	cd apple && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(prefix) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
+
+x11launcher-install:
 	cd launcher && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(APPLE_APPLICATIONS_DIR) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
 
-HOOK_TARGETS = x11app-install-hook
+x11app-clean:
+	rm -rf apple/build
+
+x11launcher-clean:
+	rm -rf launcher/build
+
+install-data-hook: x11app-install x11launcher-install
+clean-local: x11app-clean x11launcher-clean
 
 endif
 
 man1_MANS = XDarwin.man
 
-install-data-hook: $(HOOK_TARGETS)
-
 EXTRA_DIST = \
 	darwin.c \
 	darwinClut8.h \
@@ -170,4 +181,8 @@ EXTRA_DIST = \
 	apple/English.lproj/main.nib/info.nib \
 	apple/English.lproj/main.nib/keyedobjects.nib \
 	apple/X11.xcodeproj/project.pbxproj \
+	launcher/bundle-main.c \
+	launcher/Info.plist \
+	launcher/X11.icns \
+	launcher/X11.xcodeproj/project.pbxproj \
 	XDarwin.man
diff --git a/hw/darwin/apple/X11.xcodeproj/project.pbxproj b/hw/darwin/apple/X11.xcodeproj/project.pbxproj
index a47e4d1..217f07e 100644
--- a/hw/darwin/apple/X11.xcodeproj/project.pbxproj
+++ b/hw/darwin/apple/X11.xcodeproj/project.pbxproj
@@ -207,38 +207,33 @@
 		527F24090B5D8FFC007840A7 /* Development */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				DSTROOT = "$(DSTROOT)";
-				SKIP_INSTALL = YES;
+				INSTALL_MODE_FLAG = "a+rX";
 			};
 			name = Development;
 		};
 		527F240A0B5D8FFC007840A7 /* Deployment */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				DSTROOT = "$(DSTROOT)";
-				SKIP_INSTALL = YES;
+				INSTALL_MODE_FLAG = "a+rX";
 			};
 			name = Deployment;
 		};
 		527F240B0B5D8FFC007840A7 /* Default */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				DSTROOT = "$(DSTROOT)";
-				SKIP_INSTALL = YES;
+				INSTALL_MODE_FLAG = "a+rX";
 			};
 			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;
+				INSTALL_PATH = /usr/X11;
 				LIBRARY_SEARCH_PATHS = /usr/X11/lib;
 				OTHER_CFLAGS = "";
 				OTHER_LDFLAGS = (
@@ -262,12 +257,11 @@
 			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;
+				INSTALL_PATH = /usr/X11;
 				LIBRARY_SEARCH_PATHS = /usr/X11/lib;
 				OTHER_CFLAGS = "";
 				OTHER_LDFLAGS = (
@@ -290,12 +284,11 @@
 		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;
+				INSTALL_PATH = /usr/X11;
 				LIBRARY_SEARCH_PATHS = /usr/X11/lib;
 				OTHER_CFLAGS = "";
 				OTHER_LDFLAGS = (
diff --git a/hw/darwin/launcher/X11.xcodeproj/project.pbxproj b/hw/darwin/launcher/X11.xcodeproj/project.pbxproj
index f82552a..34b76da 100644
--- a/hw/darwin/launcher/X11.xcodeproj/project.pbxproj
+++ b/hw/darwin/launcher/X11.xcodeproj/project.pbxproj
@@ -164,33 +164,28 @@
 		527F24090B5D8FFC007840A7 /* Development */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				DSTROOT = "$(DSTROOT)";
-				SKIP_INSTALL = YES;
+				INSTALL_MODE_FLAG = "a+rX";
 			};
 			name = Development;
 		};
 		527F240A0B5D8FFC007840A7 /* Deployment */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				DSTROOT = "$(DSTROOT)";
-				SKIP_INSTALL = YES;
+				INSTALL_MODE_FLAG = "a+rX";
 			};
 			name = Deployment;
 		};
 		527F240B0B5D8FFC007840A7 /* Default */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				DSTROOT = "$(DSTROOT)";
-				SKIP_INSTALL = YES;
+				INSTALL_MODE_FLAG = "a+rX";
 			};
 			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;
@@ -219,12 +214,11 @@
 			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;
+				INSTALL_PATH = /Applications/Utilties;
 				LIBRARY_SEARCH_PATHS = /usr/X11/lib;
 				OTHER_CFLAGS = "";
 				OTHER_LDFLAGS = "";
@@ -243,12 +237,11 @@
 		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;
+				INSTALL_PATH = /Applications/Utilties;
 				LIBRARY_SEARCH_PATHS = /usr/X11/lib;
 				OTHER_CFLAGS = "";
 				OTHER_LDFLAGS = (
commit 97b113d5504add2d82e92336e80bf9c200c8a29d
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Nov 12 16:42:00 2007 -0800

    converted some debugging prints to TRACE() statements

diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 34f5e45..c0666e6 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -253,7 +253,7 @@ static void QuartzUpdateScreens(void)
     int x, y, width, height, sx, sy;
     xEvent e;
 
-    ErrorF("QuartzUpdateScreens()\n");
+    TRACE("QuartzUpdateScreens()\n");
     if (noPseudoramiXExtension || screenInfo.numScreens != 1)
     {
         /* FIXME: if not using Xinerama, we have multiple screens, and
@@ -421,6 +421,7 @@ void DarwinModeProcessEvent(
 {
     switch (xe->u.u.type) {
         case kXDarwinControllerNotify:
+	  TRACE("kXDarwinControllerNotify\n");
             AppleWMSendEvent(AppleWMControllerNotify,
                              AppleWMControllerNotifyMask,
                              xe->u.clientMessage.u.l.longs0,
@@ -428,6 +429,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinPasteboardNotify:
+	  TRACE("kXDarwinPasteboardNotify\n");
             AppleWMSendEvent(AppleWMPasteboardNotify,
                              AppleWMPasteboardNotifyMask,
                              xe->u.clientMessage.u.l.longs0,
@@ -435,7 +437,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinActivate:
-  //	  ErrorF("kXDarwinActivate\n");
+	  TRACE("kXDarwinActivate\n");
             QuartzShow(xe->u.keyButtonPointer.rootX,
                        xe->u.keyButtonPointer.rootY);
             AppleWMSendEvent(AppleWMActivationNotify,
@@ -444,7 +446,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinDeactivate:
-  //	  ErrorF("kXDarwinDeactivate\n");
+  	  TRACE("kXDarwinDeactivate\n");
             AppleWMSendEvent(AppleWMActivationNotify,
                              AppleWMActivationNotifyMask,
                              AppleWMIsInactive, 0);
@@ -452,22 +454,23 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinDisplayChanged:
-  //	  ErrorF("kXDarwinDisplayChanged\n");
+	    TRACE("kXDarwinDisplayChanged\n");
             QuartzUpdateScreens();
             break;
 
         case kXDarwinWindowState:
-  //	  ErrorF("kXDarwinWindowState\n");
+	  TRACE("kXDarwinWindowState\n");
             RootlessNativeWindowStateChanged(xe->u.clientMessage.u.l.longs0,
 		  			     xe->u.clientMessage.u.l.longs1);
 	    break;
 	  
         case kXDarwinWindowMoved:
-  //	  ErrorF("kXDarwinWindowMoved\n");
+	  TRACE("kXDarwinWindowMoved\n");
             RootlessNativeWindowMoved (xe->u.clientMessage.u.l.longs0);
 	    break;
 
         case kXDarwinToggleFullscreen:
+	  TRACE("kXDarwinToggleFullscreen\n");
 #ifdef DARWIN_DDX_MISSING
             if (quartzEnableRootless) QuartzSetFullscreen(!quartzHasRoot);
             else if (quartzHasRoot) QuartzHide();
@@ -503,7 +506,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinBringAllToFront:
-  //	  ErrorF("kXDarwinBringAllToFront\n");
+  	  TRACE("kXDarwinBringAllToFront\n");
 	    RootlessOrderAllWindows();
             break;
 
diff --git a/hw/darwin/quartz/quartz.h b/hw/darwin/quartz/quartz.h
index 172f323..febc51a 100644
--- a/hw/darwin/quartz/quartz.h
+++ b/hw/darwin/quartz/quartz.h
@@ -38,6 +38,14 @@
 #include "screenint.h"
 #include "window.h"
 
+//#define DEBUG 1
+
+#ifdef DEBUG
+#define TRACE(msg, args...) ErrorF("%s:%d: " msg, __FUNCTION__, __LINE__, ##args )
+#else
+#define TRACE(msg, args...) 
+#endif
+
 /*------------------------------------------
    Quartz display mode function types
   ------------------------------------------*/
commit ef290201d6d316ed2cebb9714e0f979ba7dbd816
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Nov 12 16:41:13 2007 -0800

    Fix for stuck modifier keys, attempt 2!

diff --git a/hw/darwin/darwinEvents.c b/hw/darwin/darwinEvents.c
index 6293d6b..c9b30ee 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -41,7 +41,6 @@ in this Software without prior written authorization from The Open Group.
 #include   "mi.h"
 #include   "scrnintstr.h"
 #include   "mipointer.h"
-
 #include "darwin.h"
 #include "darwinKeyboard.h"
 
@@ -72,7 +71,8 @@ typedef struct _EventQueue {
 } EventQueueRec, *EventQueuePtr;
 
 static EventQueueRec darwinEventQueue;
-
+extern KeyClassPtr darwinKeyc;
+#define KeyPressed(k) (darwinKeyc->down[k >> 3] & (1 << (k & 7)))
 
 /*
  * DarwinPressModifierMask
@@ -150,8 +150,37 @@ static void DarwinUpdateModifiers(
  * are held down during a "context" switch -- otherwise, we would miss the KeyUp.
  */
 static void DarwinReleaseModifiers(void) {
-	xEvent e;
-	DarwinUpdateModifiers(&e, KeyRelease, COMMAND_MASK(-1) | CONTROL_MASK(-1) | ALTERNATE_MASK(-1) | SHIFT_MASK(-1));
+  KeySym *map = NULL;
+  xEvent ke;
+  int i = 0, j = 0, nevents = 0; 
+ 
+  map = darwinKeyc->curKeySyms.map;
+  
+  for (i = darwinKeyc->curKeySyms.minKeyCode, map = darwinKeyc->curKeySyms.map;
+       i < darwinKeyc->curKeySyms.maxKeyCode;
+       i++, map += darwinKeyc->curKeySyms.mapWidth) {
+    if (KeyPressed(i)) {
+      switch (*map) {
+	/* Don't release the lock keys */
+      case XK_Caps_Lock:
+      case XK_Shift_Lock:
+      case XK_Num_Lock:
+      case XK_Scroll_Lock:
+      case XK_Kana_Lock:
+	break;
+      default:
+	  ke.u.keyButtonPointer.time = GetTimeInMillis();
+	  ke.u.keyButtonPointer.rootX = 0;
+	  ke.u.keyButtonPointer.rootY = 0;
+	  ke.u.u.type = KeyRelease;
+	  ke.u.u.detail = i;
+	  (*darwinEventQueue.pKbd->processInputProc)(&ke,
+		    (DeviceIntPtr)darwinEventQueue.pKbd, 1);
+	break;
+      }
+    }
+  }
+  ProcessInputEvents();
 }
 
 /*
@@ -477,9 +506,10 @@ void ProcessInputEvents(void)
                 break;
             }
 
-			case kXDarwinDeactivate:
-				DarwinReleaseModifiers();
-				// fall through
+	    case kXDarwinDeactivate:
+	      DarwinReleaseModifiers();
+	      old_flags=0;
+	      // fall through
             default:
                 // Check for mode specific event
                 DarwinModeProcessEvent(&xe);
diff --git a/hw/darwin/darwinKeyboard.c b/hw/darwin/darwinKeyboard.c
index 2a10496..3685bff 100644
--- a/hw/darwin/darwinKeyboard.c
+++ b/hw/darwin/darwinKeyboard.c
@@ -220,6 +220,7 @@ static void DarwinChangeKeyboardControl( DeviceIntPtr device, KeybdCtrl *ctrl )
 static darwinKeyboardInfo keyInfo;
 static FILE *fref = NULL;
 static char *inBuffer = NULL;
+KeyClassPtr darwinKeyc = NULL;
 
 //-----------------------------------------------------------------------------
 // Data Stream Object
@@ -835,6 +836,7 @@ InitModMap(register KeyClassPtr keyc)
     CARD8 keysPerModifier[8];
     CARD8 mask;
 
+    darwinKeyc = keyc;
     if (keyc->modifierKeyMap != NULL)
         xfree (keyc->modifierKeyMap);
 
commit 9e9633c6705a759769a533c2b12fcc87f3cb794e
Author: Ben Byer <bbyer at bbyer.local>
Date:   Mon Nov 12 00:44:11 2007 -0800

    And now we kill XDarwinApp -- credit, Jeremy Huddleston

diff --git a/configure.ac b/configure.ac
index 0be2755..770c292 100644
--- a/configure.ac
+++ b/configure.ac
@@ -456,10 +456,10 @@ AC_ARG_WITH(rgb-path,         AS_HELP_STRING([--with-rgb-path=PATH], [Path to RG
 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="/Applications/Utilities"
+AC_ARG_WITH(apple-applications-dir,AS_HELP_STRING([--with-apple-applications-dir=PATH], [Path to the Applications directory (default: /Applications/Utilities)]),
 				[ APPLE_APPLICATIONS_DIR="${withval}" ].
-				[ APPLE_APPLICATIONS_DIR="${bindir}/Applications" ])
+				[ APPLE_APPLICATIONS_DIR="/Applications/Utilities" ])
 
 AC_ARG_ENABLE(builddocs,      AS_HELP_STRING([--enable-builddocs], [Build docs (default: disabled)]),
                                 [BUILDDOCS=$enableval],
@@ -511,9 +511,8 @@ AC_ARG_ENABLE(dmx,    	      AS_HELP_STRING([--enable-dmx], [Build DMX server (d
 AC_ARG_ENABLE(xvfb,    	      AS_HELP_STRING([--enable-xvfb], [Build Xvfb server (default: no)]), [XVFB=$enableval], [XVFB=no])
 AC_ARG_ENABLE(xnest,   	      AS_HELP_STRING([--enable-xnest], [Build Xnest server (default: no)]), [XNEST=$enableval], [XNEST=no])
 AC_ARG_ENABLE(xdarwin, 	      AS_HELP_STRING([--enable-xdarwin], [Build XDarwin server (default: auto)]), [XDARWIN=$enableval], [XDARWIN=auto])
-AC_ARG_ENABLE(xdarwinapp,     AS_HELP_STRING([--enable-xdarwinapp], [Build XDarwin.app server (default: no)]), [XDARWINAPP=$enableval], [XDARWINAPP=no])
 AC_ARG_ENABLE(xquartz,        AS_HELP_STRING([--disable-xquartz], [Build Xquartz server on Darwin (default: auto)]), [XQUARTZ=$enableval], [XQUARTZ=auto])
-AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app wrapper for Xquartz (default: no)]), [X11APP=$enableval], [X11APP=no])
+AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app wrapper for Xquartz (default: auto)]), [X11APP=$enableval], [X11APP=auto])
 AC_ARG_ENABLE(xwin,    	      AS_HELP_STRING([--enable-xwin], [Build XWin server (default: auto)]), [XWIN=$enableval], [XWIN=auto])
 AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
 AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (default: no)]), [XGL=$enableval], [XGL=no])
@@ -1479,7 +1478,6 @@ 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]) 
 
 dnl Xprint DDX
 
@@ -1603,7 +1601,7 @@ 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
-AC_MSG_CHECKING([whether to build XDarwin (Mac OS X) DDX])
+AC_MSG_CHECKING([whether to build XDarwin/Xquartz])
 if test "x$XDARWIN" = xauto; then
 	case $host_os in
 		darwin*) XDARWIN="yes" ;;
@@ -1613,25 +1611,33 @@ fi
 AC_MSG_RESULT([$XDARWIN])
 
 if test "x$XDARWIN" = xyes; then
-        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
+	if test "X$XQUARTZ" = Xauto; then
+		AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
+		 	save_LDFLAGS=$LDFLAGS
+			LDFLAGS="$LDFLAGS -framework Carbon"
+			AC_LINK_IFELSE([char FSFindFolder(); int main() { FSFindFolder(); return 0;}],
+				[xorg_cv_Carbon_framework=yes],
+				[xorg_cv_Carbon_framework=no])
+			LDFLAGS=$save_LDFLAGS])
+                 
+		if test "X$xorg_cv_Carbon_framework" = Xyes; then
+			AC_DEFINE([DARWIN_WITH_QUARTZ],[1],[Have Quartz])
+			XQUARTZ=yes
+		else
+			XQUARTZ=no
+		fi
+	fi
+
+	if test "x$X11APP" = xauto; then
+		AC_MSG_CHECKING([whether to build X11.app])
+		if test "x$XQUARTZ" = xyes ; then
+			X11APP=yes
+		else
+			X11APP=no
+		fi
+		AC_MSG_RESULT([$X11APP])
+	fi
+
 #	       glxAGL / glxCGL don't work yet
 #               AC_CACHE_CHECK([for AGL framework],xorg_cv_AGL_framework,[
 #               save_LDFLAGS=$LDFLAGS
@@ -1686,8 +1692,8 @@ _AM_DEPENDENCIES([OBJC])
 AM_CONDITIONAL(HAVE_XPLUGIN, [test "x$ac_cv_lib_Xplugin_xp_init" = xyes])
 AM_CONDITIONAL(HAVE_AGL_FRAMEWORK, [test "x$xorg_cv_AGL_framework" = xyes])
 AM_CONDITIONAL(XDARWIN, [test "x$XDARWIN" = xyes])
-AM_CONDITIONAL(XDARWINAPP, [test "x$XDARWINAPP" = xyes])
 AM_CONDITIONAL(XQUARTZ, [test "x$XQUARTZ" = xyes])
+AM_CONDITIONAL(X11APP,[test "X$X11APP" = Xyes]) 
 
 dnl kdrive DDX
 
diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 545ff2f..ccaacfd 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = @XORG_INCS@ -I../../miext/rootless
 DEFS = @DEFS@ -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" 
 
 if XQUARTZ
-XQUARTZ_SUBDIRS = bundle quartz
+XQUARTZ_SUBDIRS = quartz
 endif
 
 SUBDIRS = \
@@ -16,14 +16,17 @@ SUBDIRS = \
 	  utils \
 	  .
 
-darwinappdir = /Applications/Utilities/XDarwin.app
-
 libdarwinShared_a_SOURCES = darwin.c \
 			  darwinEvents.c \
 			  darwinKeyboard.c \
 			  $(darwin_XINPUT_SRCS) 
 
+if XQUARTZ
 bin_PROGRAMS = Xquartz
+else
+bin_PROGRAMS = XDarwin
+endif
+
 XDarwin_SOURCES = \
                   $(top_srcdir)/fb/fbcmap.c \
                   $(top_srcdir)/mi/miinitext.c \
@@ -126,185 +129,27 @@ XDarwin_CFLAGS = -DINXDARWIN
 Xquartz_CFLAGS = -DINXQUARTZ -DHAS_CG_MACH_PORT -DHAS_KL_API  -DHAVE_XORG_CONFIG_H
 Xquartz_OBJCFLAGS = -DINXQUARTZ -DHAS_CG_MACH_PORT -DHAS_KL_API  -DHAVE_XORG_CONFIG_H
 
-if XQUARTZ
-macosdir = $(darwinappdir)/Contents/MacOS
-
-DEFS += -DDARWIN_WITH_QUARTZ -DXFree86Server
-
-macos_PROGRAMS = 
-macos_SCRIPTS = x11app
+if X11APP
+bin_SCRIPTS = x11app x11launcher
 
 x11app:
-	cd apple && xcodebuild
+	cd apple && xcodebuild CFLAGS="$(XSERVERCFLAGS_CFLAGS)" LDFLAGS="$(XSERVERCFLAGS_LIBS)"
 
-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)/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_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_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_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
-
-xprplugindir = $(darwinappdir)/Contents/Resources/xpr.bundle/Contents/MacOS
-xprplugin_LTLIBRARIES =
-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	
-
-
-if HAVE_AGL_FRAMEWORK
-glxCGLplugindir = $(darwinappdir)/Contents/Resources/glxCGL.bundle/Contents/MacOS
-glxCGLplugin_LTLIBRARIES =
-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_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	
+x11launcher:
+	cd launcher && xcodebuild CFLAGS="$(XSERVERCFLAGS_CFLAGS)" LDFLAGS="$(XSERVERCFLAGS_LIBS)"
 
+x11app-install-hook:
+	cd apple && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(prefixdir) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
+	cd launcher && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=$(APPLE_APPLICATIONS_DIR) DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
 
+HOOK_TARGETS = x11app-install-hook
 
 endif
 
 man1_MANS = XDarwin.man
 
-uninstall-hook:
-	rm -rf $(DESTDIR)$(macosdir)/XDarwin
-
 install-data-hook: $(HOOK_TARGETS)
 
-xquartz-install-hook:
-	cd apple && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=/usr/X11 DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
-	cd launcher && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=/Applications/Utilities DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
- 
 EXTRA_DIST = \
 	darwin.c \
 	darwinClut8.h \
diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
index 0d236be..baa7d44 100644
--- a/hw/darwin/quartz/Makefile.am
+++ b/hw/darwin/quartz/Makefile.am
@@ -25,20 +25,6 @@ libXQuartz_a_SOURCES = \
 	          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 \
commit b772f42723918ce19b0aa711651c5e5d2c8792e6
Author: Ben Byer <bbyer at bbyer.local>
Date:   Mon Nov 12 00:27:30 2007 -0800

    Patch to fix various issues with the launcher, courtesy of Jeremy Huddleston

diff --git a/hw/darwin/launcher/bundle-main.c b/hw/darwin/launcher/bundle-main.c
index 988c04f..ca62553 100644
--- a/hw/darwin/launcher/bundle-main.c
+++ b/hw/darwin/launcher/bundle-main.c
@@ -37,7 +37,7 @@
 
 int main (int argc, char **argv) {
   char *command = DEFAULT_APP;
-  const char *newargv[5];
+  const char *newargv[7];
   int child;
   
 
@@ -60,8 +60,10 @@ int main (int argc, char **argv) {
 	newargv[0] = "/usr/bin/login";
 	newargv[1] = "-fp";
 	newargv[2] = getlogin();
-	newargv[3] = command;
-	newargv[4] = NULL;
+	newargv[3] = "/bin/sh";
+	newargv[4] = "-c";
+	newargv[5] = command;
+	newargv[6] = NULL;
 
     child = fork();
 	
commit a415f62f5289fae99ea9b0038d21fad7695b1336
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sun Nov 11 04:30:34 2007 -0800

    These changes are necessary, yet not sufficient, to get 8-bit indexed
    color mode working in Xquartz.

diff --git a/miext/rootless/rootlessCommon.c b/miext/rootless/rootlessCommon.c
index 8fd922d..fc22b1b 100644
--- a/miext/rootless/rootlessCommon.c
+++ b/miext/rootless/rootlessCommon.c
@@ -34,6 +34,7 @@
 #endif
 
 #include "rootlessCommon.h"
+#include "colormapst.h"
 
 unsigned int rootless_CopyBytes_threshold = 0;
 unsigned int rootless_FillBytes_threshold = 0;
@@ -95,6 +96,41 @@ IsFramedWindow(WindowPtr pWin)
     return (top && WINREC(top));
 }
 
+Bool
+RootlessResolveColormap (ScreenPtr pScreen, int first_color,
+                         int n_colors, uint32_t *colors)
+{
+  int last, i;
+  ColormapPtr map;
+
+  map = RootlessGetColormap (pScreen);
+  if (map == NULL || map->class != PseudoColor) return FALSE;
+
+  last = MIN (map->pVisual->ColormapEntries, first_color + n_colors);
+  for (i = MAX (0, first_color); i < last; i++) {
+    Entry *ent = map->red + i;
+    uint16_t red, green, blue;
+
+      if (!ent->refcnt)	continue;
+      if (ent->fShared) {
+	red = ent->co.shco.red->color;
+	green = ent->co.shco.green->color;
+	blue = ent->co.shco.blue->color;
+      } else {
+	red = ent->co.local.red;
+	green = ent->co.local.green;
+	blue = ent->co.local.blue;
+      }
+
+      colors[i - first_color] = (0xFF000000UL
+				 | ((uint32_t) red & 0xff00) << 8
+				 | (green & 0xff00)
+				 | (blue >> 8));
+    }
+
+  return TRUE;
+}
+
 
 /*
  * RootlessStartDrawing
diff --git a/miext/rootless/rootlessCommon.h b/miext/rootless/rootlessCommon.h
index 3bf6af0..b002214 100644
--- a/miext/rootless/rootlessCommon.h
+++ b/miext/rootless/rootlessCommon.h
@@ -32,6 +32,7 @@
 #include <dix-config.h>
 #endif
 
+#include <stdint.h>
 #ifndef _ROOTLESSCOMMON_H
 #define _ROOTLESSCOMMON_H
 
@@ -104,13 +105,20 @@ typedef struct _RootlessScreenRec {
     GlyphsProcPtr Glyphs;
 #endif
 
+    InstallColormapProcPtr InstallColormap;
+    UninstallColormapProcPtr UninstallColormap;
+    StoreColorsProcPtr StoreColors;
+
     void *pixmap_data;
     unsigned int pixmap_data_size;
 
+    ColormapPtr colormap;
+
     void *redisplay_timer;
     unsigned int redisplay_timer_set :1;
     unsigned int redisplay_queued :1;
     unsigned int redisplay_expired :1;
+    unsigned int colormap_changed :1;
 } RootlessScreenRec, *RootlessScreenPtr;
 
 
@@ -251,6 +259,16 @@ void RootlessRedisplayScreen(ScreenPtr pScreen);
 
 void RootlessQueueRedisplay(ScreenPtr pScreen);
 
+/* Return the colormap currently installed on the given screen. */
+ColormapPtr RootlessGetColormap (ScreenPtr pScreen);
+
+/* Convert colormap to ARGB. */
+Bool RootlessResolveColormap (ScreenPtr pScreen, int first_color,
+			      int n_colors, uint32_t *colors);
+
+void RootlessFlushWindowColormap (WindowPtr pWin);
+void RootlessFlushScreenColormaps (ScreenPtr pScreen);
+
 // Move a window to its proper location on the screen.
 void RootlessRepositionWindow(WindowPtr pWin);
 
diff --git a/miext/rootless/rootlessScreen.c b/miext/rootless/rootlessScreen.c
index 356fec7..b314581 100644
--- a/miext/rootless/rootlessScreen.c
+++ b/miext/rootless/rootlessScreen.c
@@ -42,6 +42,7 @@
 #include "propertyst.h"
 #include "mivalidate.h"
 #include "picturestr.h"
+#include "colormapst.h"
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -469,6 +470,67 @@ RootlessMarkOverlappedWindows(WindowPtr pWin, WindowPtr pFirst,
     return result;
 }
 
+ColormapPtr
+RootlessGetColormap (ScreenPtr pScreen)
+{
+  RootlessScreenRec *s = SCREENREC (pScreen);
+
+  return s->colormap;
+}
+
+static void
+RootlessInstallColormap (ColormapPtr pMap)
+{
+  ScreenPtr pScreen = pMap->pScreen;
+  RootlessScreenRec *s = SCREENREC (pScreen);
+
+  SCREEN_UNWRAP(pScreen, InstallColormap);
+
+  if (s->colormap != pMap) {
+    s->colormap = pMap;
+    s->colormap_changed = TRUE;
+    RootlessQueueRedisplay (pScreen);
+  }
+
+  pScreen->InstallColormap (pMap);
+
+  SCREEN_WRAP (pScreen, InstallColormap);
+}
+
+static void
+RootlessUninstallColormap (ColormapPtr pMap)
+{
+  ScreenPtr pScreen = pMap->pScreen;
+  RootlessScreenRec *s = SCREENREC (pScreen);
+
+  SCREEN_UNWRAP(pScreen, UninstallColormap);
+
+  if (s->colormap == pMap)
+    s->colormap = NULL;
+
+  pScreen->UninstallColormap (pMap);
+
+  SCREEN_WRAP(pScreen, UninstallColormap);
+}
+
+static void
+RootlessStoreColors (ColormapPtr pMap, int ndef, xColorItem *pdef)
+{
+  ScreenPtr pScreen = pMap->pScreen;
+  RootlessScreenRec *s = SCREENREC (pScreen);
+
+  SCREEN_UNWRAP(pScreen, StoreColors);
+
+  if (s->colormap == pMap && ndef > 0) {
+    s->colormap_changed = TRUE;
+    RootlessQueueRedisplay (pScreen);
+  }
+
+  pScreen->StoreColors (pMap, ndef, pdef);
+
+  SCREEN_WRAP(pScreen, StoreColors);
+}
+
 
 static CARD32
 RootlessRedisplayCallback(OsTimerPtr timer, CARD32 time, void *arg)
@@ -616,6 +678,9 @@ RootlessWrap(ScreenPtr pScreen)
     WRAP(MarkOverlappedWindows);
     WRAP(ValidateTree);
     WRAP(ChangeWindowAttributes);
+    WRAP(InstallColormap);
+    WRAP(UninstallColormap);
+    WRAP(StoreColors);
 
 #ifdef SHAPE
     WRAP(SetShape);
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index 84aa91d..cf32426 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -447,6 +447,12 @@ RootlessInitializeFrame(WindowPtr pWin, RootlessWindowRec *winRec)
 }
 
 
+Bool
+RootlessColormapCallback (void *data, int first_color, int n_colors, uint32_t *colors)
+{
+  return RootlessResolveColormap (data, first_color, n_colors, colors);
+}
+
 /*
  * RootlessEnsureFrame
  *  Make sure the given window is framed. If the window doesn't have a
@@ -505,6 +511,9 @@ RootlessEnsureFrame(WindowPtr pWin)
         return NULL;
     }
 
+    if (pWin->drawable.depth == 8)
+      RootlessFlushWindowColormap(pWin);
+
 #ifdef SHAPE
     if (pShape != NULL)
         REGION_UNINIT(pScreen, &shape);
@@ -1458,6 +1467,25 @@ out:
 }
 
 
+void
+RootlessFlushWindowColormap (WindowPtr pWin)
+{
+  RootlessWindowRec *winRec = WINREC (pWin);
+  xp_window_changes wc;
+
+  if (winRec == NULL)
+    return;
+
+  RootlessStopDrawing (pWin, FALSE);
+
+  /* This is how we tell xp that the colormap may have changed. */
+
+  wc.colormap = RootlessColormapCallback;
+  wc.colormap_data = pWin->drawable.pScreen;
+
+  configure_window (winRec->wid, XP_COLORMAP, &wc);
+}
+
 /*
  * SetPixmapOfAncestors
  *  Set the Pixmaps on all ParentRelative windows up the ancestor chain.
commit c7573379a85a1480cc51650075078e41dafe56af
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sun Nov 11 04:30:00 2007 -0800

    Fixed the call to xp_init so that we now receive Motion notifications even
    if X is not the active application.
    fixes <rdar://problem/5167664> xeyes dead until window activation

diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index d84e646..589b172 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -233,7 +233,7 @@ xprDisplayInit(void)
     else
         darwinScreensFound =  1;
 
-    if (xp_init(XP_IN_BACKGROUND | XP_NO_DEFERRED_UPDATES) != Success)
+    if (xp_init(XP_BACKGROUND_EVENTS | XP_NO_DEFERRED_UPDATES) != Success)
     {
         FatalError("Could not initialize the Xplugin library.");
     }
commit 300e1bb458a8971c312dbeb2d67b10bd0f195caf
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Fri Nov 9 15:44:30 2007 -0800

    Fix {/usr/X11,/Applications/Utilities}/X11.app install targets to properly respect
    $DESTDIR.  Credit to Jeremy Huddleston

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 45eb08b..545ff2f 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -302,9 +302,9 @@ uninstall-hook:
 install-data-hook: $(HOOK_TARGETS)
 
 xquartz-install-hook:
-	cd apple && xcodebuild install
-	cd launcher && xcodebuild install
-
+	cd apple && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=/usr/X11 DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
+	cd launcher && xcodebuild install DSTROOT=$(DESTDIR) INSTALL_PATH=/Applications/Utilities DEPLOYMENT_LOCATION=YES SKIP_INSTALL=NO
+ 
 EXTRA_DIST = \
 	darwin.c \
 	darwinClut8.h \
commit c3a514ba45e9ffbdad0ccc7e936c33451fc5928a
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Nov 9 04:13:01 2007 -0800

    bump to 1.2a8

diff --git a/configure.ac b/configure.ac
index 6336b63..0be2755 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.2a7, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a8, [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 --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 1033e95..92d369b 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -156,7 +156,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a7)",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a8)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
commit fe794635bd497a01f9e1d755e5e4dd664ba23c75
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Nov 9 03:40:37 2007 -0800

    fixes to allow Xvfb and Xephyr to be built if you build with --disable-xdarwin

diff --git a/configure.ac b/configure.ac
index 125517d..6336b63 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1727,7 +1727,7 @@ if test "$KDRIVE" = yes; then
     KDRIVE_OS_INC='-I$(top_srcdir)/hw/kdrive/linux'
     KDRIVE_INCS="$KDRIVE_PURE_INCS $KDRIVE_OS_INC"
     
-    KDRIVE_CFLAGS="$XSERVER_CFLAGS -DHAVE_KDRIVE_CONFIG_H $TSLIB_CFLAGS"
+    KDRIVE_CFLAGS="$XSERVER_CFLAGS -DHAVE_KDRIVE_CONFIG_H $TSLIB_CFLAGS -fno-common"
 
     # dix os fb mi extension glx (NOTYET) damage shadow xpstubs
     #KDRIVE_PURE_LIBS="$DIX_LIB $OS_LIB $FB_LIB $XEXT_LIB $MIEXT_DAMAGE_LIB \
diff --git a/dix/main.c b/dix/main.c
index f3cde18..586b800 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -259,7 +259,7 @@ main(int argc, char *argv[], char *envp[])
     /* Quartz support on Mac OS X requires that the Cocoa event loop be in
      * the main thread. This allows the X server main to be called again
      * from another thread. */
-#if defined(__DARWIN__) && defined(DARWIN_WITH_QUARTZ)
+#ifdef DARWIN_WITH_QUARTZ
     DarwinHandleGUI(argc, argv, envp);
 #endif
 
diff --git a/hw/Makefile.am b/hw/Makefile.am
index a1918ab..db76977 100644
--- a/hw/Makefile.am
+++ b/hw/Makefile.am
@@ -22,7 +22,9 @@ if XPRINT
 XPRINT_SUBDIRS = xprint
 endif
 
+if XDARWIN
 DARWIN_SUBDIRS = darwin
+endif
 
 SUBDIRS =			\
 	$(XORG_SUBDIRS)		\
diff --git a/mi/miinitext.c b/mi/miinitext.c
index 8736745..f15d0c9 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -672,10 +672,10 @@ InitVisualWrap()
 {
     miResetInitVisuals();
 #ifdef GLXEXT
-#ifndef __DARWIN__
-    GlxWrapInitVisuals(&miInitVisualsProc);
-#else
+#ifdef INXQUARTZ
     DarwinGlxWrapInitVisuals(&miInitVisualsProc);
+#else
+    GlxWrapInitVisuals(&miInitVisualsProc);
 #endif
 #endif
 }
commit 30cbfc786e4fedda3fe070bacceabe1d9212d00b
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Thu Nov 8 22:17:38 2007 -0800

    fix for spurious "Are you sure you want to quit?" message

diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index a0eb4ed..34f5e45 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -186,6 +186,7 @@ void DarwinModeInitInput(
     char **argv )
 {
 #ifdef INXQUARTZ
+    X11ApplicationSetCanQuit(1);
     X11ApplicationServerReady();
 #else
     QuartzMessageMainThread(kQuartzServerStarted, NULL, 0);
commit 633490c4e8dab30af7ecbe1bef076c22ad5f5da9
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Thu Nov 8 22:12:41 2007 -0800

    Adding "fake RandR" support from old X11.app

diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index eccb4ef..a0eb4ed 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -52,6 +52,8 @@
 #include <fcntl.h>
 #include <IOKit/pwr_mgt/IOPMLib.h>
 
+#define FAKE_RANDR 1
+
 // Shared global variables for Quartz modes
 int                     quartzEventWriteFD = -1;
 int                     quartzStartClients = 1;
@@ -67,6 +69,30 @@ int                     noPseudoramiXExtension = FALSE;
 QuartzModeProcsPtr      quartzProcs = NULL;
 const char             *quartzOpenGLBundle = NULL;
 
+#if defined(RANDR) && !defined(FAKE_RANDR)
+Bool DarwinModeRandRGetInfo (ScreenPtr pScreen, Rotation *rotations) {
+  return FALSE;
+}
+
+Bool DarwinModeRandRSetConfig (ScreenPtr           pScreen,
+			       Rotation            randr,
+			       int                 rate,
+			       RRScreenSizePtr     pSize) {
+  return FALSE;
+}
+
+Bool DarwinModeRandRInit (ScreenPtr pScreen) {
+  rrScrPrivPtr    pScrPriv;
+    
+  if (!RRScreenInit (pScreen)) return FALSE;
+
+  pScrPriv = rrGetScrPriv(pScreen);
+  pScrPriv->rrGetInfo = DarwinModeRandRGetInfo;
+  pScrPriv->rrSetConfig = DarwinModeRandRSetConfig;
+  return TRUE;
+}
+#endif
+
 /*
 ===========================================================================
 
@@ -170,6 +196,51 @@ void DarwinModeInitInput(
 }
 
 
+#ifdef FAKE_RANDR
+extern char	*ConnectionInfo;
+
+static int padlength[4] = {0, 3, 2, 1};
+
+static void
+RREditConnectionInfo (ScreenPtr pScreen)
+{
+    xConnSetup	    *connSetup;
+    char	    *vendor;
+    xPixmapFormat   *formats;
+    xWindowRoot	    *root;
+    xDepth	    *depth;
+    xVisualType	    *visual;
+    int		    screen = 0;
+    int		    d;
+
+    connSetup = (xConnSetup *) ConnectionInfo;
+    vendor = (char *) connSetup + sizeof (xConnSetup);
+    formats = (xPixmapFormat *) ((char *) vendor +
+				 connSetup->nbytesVendor +
+				 padlength[connSetup->nbytesVendor & 3]);
+    root = (xWindowRoot *) ((char *) formats +
+			    sizeof (xPixmapFormat) * screenInfo.numPixmapFormats);
+    while (screen != pScreen->myNum)
+    {
+	depth = (xDepth *) ((char *) root + 
+			    sizeof (xWindowRoot));
+	for (d = 0; d < root->nDepths; d++)
+	{
+	    visual = (xVisualType *) ((char *) depth +
+				      sizeof (xDepth));
+	    depth = (xDepth *) ((char *) visual +
+				depth->nVisuals * sizeof (xVisualType));
+	}
+	root = (xWindowRoot *) ((char *) depth);
+	screen++;
+    }
+    root->pixWidth = pScreen->width;
+    root->pixHeight = pScreen->height;
+    root->mmWidth = pScreen->mmWidth;
+    root->mmHeight = pScreen->mmHeight;
+}
+#endif
+
 /*
  * QuartzUpdateScreens
  *  Adjust for screen arrangement changes.
@@ -181,6 +252,7 @@ static void QuartzUpdateScreens(void)
     int x, y, width, height, sx, sy;
     xEvent e;
 
+    ErrorF("QuartzUpdateScreens()\n");
     if (noPseudoramiXExtension || screenInfo.numScreens != 1)
     {
         /* FIXME: if not using Xinerama, we have multiple screens, and
@@ -202,8 +274,11 @@ static void QuartzUpdateScreens(void)
     pScreen->mmHeight = pScreen->mmHeight * ((double) height / pScreen->height);
     pScreen->width = width;
     pScreen->height = height;
-
-    /* FIXME: should probably do something with RandR here. */
+    
+#ifndef FAKE_RANDR
+    if(!DarwinModeRandRInit(pScreen))
+      FatalError("Failed to init RandR extension.\n");
+#endif
 
     DarwinAdjustScreenOrigins(&screenInfo);
     quartzProcs->UpdateScreen(pScreen);
@@ -231,7 +306,9 @@ static void QuartzUpdateScreens(void)
     e.u.configureNotify.override = pRoot->overrideRedirect;
     DeliverEvents(pRoot, &e, 1, NullWindow);
 
-    /* FIXME: Should we use RREditConnectionInfo(pScreen)? */
+#ifdef FAKE_RANDR
+    RREditConnectionInfo(pScreen);
+#endif
 }
 
 
commit 8606c76a904d55027173aa864d8914a1547fd8d6
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Thu Nov 8 18:49:05 2007 -0800

    Patch to rootless code that should fix many crashes.  Credit to Ken Thomases
    at CodeWeavers for the patch.  From his description:
    
    Fix a display bug with the X server.  The Generic Rootless extension
    installs overrides for certain GC (graphics context) operations.  Within
    these overrides, they temporarily uninstall themselves, perform their work,
    and then reinstall themselves.  Except sometimes they would return early
    and wouldn't reinstall themselves when they should.  Now they do in all cases.
    
    Fix a bug in RootlessCopyWindow where early returns could leave the screen's
    dispatch table entry for CopyWindow unwrapped.  We think that this is
    another case (hopefully the last) of the rootless drawing bug.

diff --git a/miext/rootless/rootlessGC.c b/miext/rootless/rootlessGC.c
index 5341267..6051367 100644
--- a/miext/rootless/rootlessGC.c
+++ b/miext/rootless/rootlessGC.c
@@ -412,10 +412,12 @@ static void RootlessCopyClip(GCPtr pgcDst, GCPtr pgcSrc)
 #define GC_IS_ROOT(pDst) ((pDst)->type == DRAWABLE_WINDOW \
                             && IsRoot ((WindowPtr) (pDst)))
 
-#define GC_SKIP_ROOT(pDst)			\
+#define GC_SKIP_ROOT(pDst, pGC)			\
     do {					\
-        if (GC_IS_ROOT (pDst))			\
+        if (GC_IS_ROOT (pDst)) {		\
+            GCOP_WRAP(pGC);			\
             return;				\
+        }					\
     } while (0)
 
 
@@ -425,7 +427,7 @@ RootlessFillSpans(DrawablePtr dst, GCPtr pGC, int nInit,
 {
     GC_SAVE(pGC);
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("fill spans start ");
 
     if (nInit <= 0) {
@@ -481,7 +483,7 @@ RootlessSetSpans(DrawablePtr dst, GCPtr pGC, char *pSrc,
                  int nspans, int sorted)
 {
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("set spans start ");
 
     if (nspans <= 0) {
@@ -532,7 +534,7 @@ RootlessPutImage(DrawablePtr dst, GCPtr pGC,
     BoxRec box;
 
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("put image start ");
 
     RootlessStartDrawing((WindowPtr) dst);
@@ -564,7 +566,10 @@ RootlessCopyArea(DrawablePtr pSrc, DrawablePtr dst, GCPtr pGC,
     GCOP_UNWRAP(pGC);
 
     if (GC_IS_ROOT(dst) || GC_IS_ROOT(pSrc))
+    {
+        GCOP_WRAP(pGC);
         return NULL;			/* nothing exposed */
+    }
 
     RL_DEBUG_MSG("copy area start (src 0x%x, dst 0x%x)", pSrc, dst);
 
@@ -614,7 +619,10 @@ static RegionPtr RootlessCopyPlane(DrawablePtr pSrc, DrawablePtr dst,
     GCOP_UNWRAP(pGC);
 
     if (GC_IS_ROOT(dst) || GC_IS_ROOT(pSrc))
+    {
+        GCOP_WRAP(pGC);
         return NULL;			/* nothing exposed */
+    }
 
     RL_DEBUG_MSG("copy plane start ");
 
@@ -651,7 +659,7 @@ static void RootlessPolyPoint(DrawablePtr dst, GCPtr pGC,
                               int mode, int npt, DDXPointPtr pptInit)
 {
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("polypoint start ");
 
     RootlessStartDrawing((WindowPtr) dst);
@@ -745,7 +753,7 @@ static void RootlessPolylines(DrawablePtr dst, GCPtr pGC,
                               int mode, int npt, DDXPointPtr pptInit)
 {
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("poly lines start ");
 
     RootlessStartDrawing((WindowPtr) dst);
@@ -820,7 +828,7 @@ static void RootlessPolySegment(DrawablePtr dst, GCPtr pGC,
                                 int nseg, xSegment *pSeg)
 {
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("poly segment start (win 0x%x)", dst);
 
     RootlessStartDrawing((WindowPtr) dst);
@@ -891,7 +899,7 @@ static void RootlessPolyRectangle(DrawablePtr dst, GCPtr pGC,
                                   int nRects, xRectangle *pRects)
 {
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("poly rectangle start ");
 
     RootlessStartDrawing((WindowPtr) dst);
@@ -952,7 +960,7 @@ static void RootlessPolyRectangle(DrawablePtr dst, GCPtr pGC,
 static void RootlessPolyArc(DrawablePtr dst, GCPtr pGC, int narcs, xArc *parcs)
 {
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("poly arc start ");
 
     RootlessStartDrawing((WindowPtr) dst);
@@ -1008,7 +1016,7 @@ static void RootlessFillPolygon(DrawablePtr dst, GCPtr pGC,
 {
     GC_SAVE(pGC);
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("fill poly start (win 0x%x, fillStyle 0x%x)", dst,
                  pGC->fillStyle);
 
@@ -1082,7 +1090,7 @@ static void RootlessPolyFillRect(DrawablePtr dst, GCPtr pGC,
 {
     GC_SAVE(pGC);
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("fill rect start (win 0x%x, fillStyle 0x%x)", dst,
                  pGC->fillStyle);
 
@@ -1137,7 +1145,7 @@ static void RootlessPolyFillArc(DrawablePtr dst, GCPtr pGC,
 {
     GC_SAVE(pGC);
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("fill arc start ");
 
     if (narcsInit > 0) {
@@ -1192,7 +1200,7 @@ static void RootlessImageText8(DrawablePtr dst, GCPtr pGC,
 {
     GC_SAVE(pGC);
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("imagetext8 start ");
 
     if (count > 0) {
@@ -1246,7 +1254,10 @@ static int RootlessPolyText8(DrawablePtr dst, GCPtr pGC,
     GCOP_UNWRAP(pGC);
 
     if (GC_IS_ROOT(dst))
+    {
+        GCOP_WRAP(pGC);
         return 0;
+    }
 
     RL_DEBUG_MSG("polytext8 start ");
 
@@ -1284,7 +1295,7 @@ static void RootlessImageText16(DrawablePtr dst, GCPtr pGC,
 {
     GC_SAVE(pGC);
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("imagetext16 start ");
 
     if (count > 0) {
@@ -1338,7 +1349,10 @@ static int RootlessPolyText16(DrawablePtr dst, GCPtr pGC,
     GCOP_UNWRAP(pGC);
 
     if (GC_IS_ROOT(dst))
+    {
+        GCOP_WRAP(pGC);
         return 0;
+    }
 
     RL_DEBUG_MSG("polytext16 start ");
 
@@ -1377,7 +1391,7 @@ static void RootlessImageGlyphBlt(DrawablePtr dst, GCPtr pGC,
 {
     GC_SAVE(pGC);
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("imageglyph start ");
 
     if (nglyphInit > 0) {
@@ -1438,7 +1452,7 @@ static void RootlessPolyGlyphBlt(DrawablePtr dst, GCPtr pGC,
                                  CharInfoPtr *ppci, pointer pglyphBase)
 {
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("polyglyph start ");
 
     RootlessStartDrawing((WindowPtr) dst);
@@ -1484,7 +1498,7 @@ RootlessPushPixels(GCPtr pGC, PixmapPtr pBitMap, DrawablePtr dst,
     BoxRec box;
 
     GCOP_UNWRAP(pGC);
-    GC_SKIP_ROOT(dst);
+    GC_SKIP_ROOT(dst, pGC);
     RL_DEBUG_MSG("push pixels start ");
 
     RootlessStartDrawing((WindowPtr) dst);
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index 1aa0b77..84aa91d 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -838,13 +838,13 @@ RootlessCopyWindow(WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc)
         top = TopLevelParent(pWin);
         if (top == NULL) {
             RL_DEBUG_MSG("no parent\n");
-            return;
+            goto out;
         }
 
         winRec = WINREC(top);
         if (winRec == NULL) {
             RL_DEBUG_MSG("not framed\n");
-            return;
+            goto out;
         }
 
         /* Move region to window local coords */
@@ -867,6 +867,7 @@ RootlessCopyWindow(WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc)
         RootlessDamageRegion(pWin, prgnSrc);
     }
 
+out:
     REGION_UNINIT(pScreen, &rgnDst);
     fbValidateDrawable(&pWin->drawable);
 
commit 9c30b6b9aaf56d900de51050da86353e5dd4af04
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 7 03:56:44 2007 -0800

    formatting fixes

diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 43cdbc6..1033e95 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -889,50 +889,42 @@ environment?", @"Startup xinitrc dialog");
 
 void
 X11ApplicationMain (int argc, const char *argv[],
-					void (*server_thread) (void *), void *server_arg)
+		    void (*server_thread) (void *), void *server_arg)
 {
-    NSAutoreleasePool *pool;
-	
+  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];
-	
-    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]);
-	
-    if (!create_thread (server_thread, server_arg))
-    {
-		fprintf (stderr, "can't create secondary thread\n");
-		exit (1);
-    }
-	
-    [NSApp run];
-	
-    /* not reached */
+  
+  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]);
+  
+  if (!create_thread (server_thread, server_arg)) {
+    ErrorF("can't create secondary thread\n");
+    exit (1);
+  }
+  
+  [NSApp run];
+  
+  /* not reached */
 }
 
 
commit 826610d21690b2e05f6be3f2d5f71c6dc683054b
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 7 03:55:08 2007 -0800

    Fix for off-by-one error in menu bar height calculation -- props to Nicholas Riley!

diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index d0c4936..43cdbc6 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -922,7 +922,7 @@ X11ApplicationMain (int argc, const char *argv[],
 	
     /* 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]);
 	
     if (!create_thread (server_thread, server_arg))
     {
commit e5652a59f1b56db1b196d3179932ab6801583072
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 7 03:10:52 2007 -0800

    Undo some last-minute breakage in xpr.h

diff --git a/hw/darwin/quartz/xpr/xpr.h b/hw/darwin/quartz/xpr/xpr.h
index 09e85f5..ddc6d0c 100644
--- a/hw/darwin/quartz/xpr/xpr.h
+++ b/hw/darwin/quartz/xpr/xpr.h
@@ -37,8 +37,6 @@ void AppleDRIExtensionInit(void);
 void xprAppleWMInit(void);
 Bool xprInit(ScreenPtr pScreen);
 Bool xprIsX11Window(void *nsWindow, int windowNumber);
-WindowPtr xprGetX11Window(xp_window_id wid);
-WindowPtr xprGetXWindowFromAppKit(int windowNumber);
 
 void xprHideWindows(Bool hide);
 
commit f86db8249bda9b10a2f8af9c88359395a63e5912
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 7 02:58:56 2007 -0800

    bump to version 1.2a7

diff --git a/configure.ac b/configure.ac
index e0aa894..125517d 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.2a6, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a7, [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 --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index bfde6f6..45eb08b 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -1,11 +1,10 @@
 noinst_LIBRARIES = libdarwinShared.a
 libdarwin_XINPUT_SRCS = darwinXinput.c
 
-# -O2 inexplicably causes quartzKeyboard.o to break?!
 AM_CFLAGS = @XORG_CFLAGS@
 INCLUDES = @XORG_INCS@ -I../../miext/rootless
 
-DEFS = @DEFS@ -DUSE_NEW_CLUT
+DEFS = @DEFS@ -DUSE_NEW_CLUT -DBUILD_DATE=\"$(BUILD_DATE)\" 
 
 if XQUARTZ
 XQUARTZ_SUBDIRS = bundle quartz
diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index c52dfd0..d0c4936 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -156,7 +156,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a6)",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a7)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
commit 6adb325e7a33ee7199a604d86de7a0ff67c03861
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 7 02:28:49 2007 -0800

    removed debugging output

diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 113a7d2..eccb4ef 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -357,7 +357,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinActivate:
-	  ErrorF("kXDarwinActivate\n");
+  //	  ErrorF("kXDarwinActivate\n");
             QuartzShow(xe->u.keyButtonPointer.rootX,
                        xe->u.keyButtonPointer.rootY);
             AppleWMSendEvent(AppleWMActivationNotify,
@@ -366,7 +366,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinDeactivate:
-	  ErrorF("kXDarwinDeactivate\n");
+  //	  ErrorF("kXDarwinDeactivate\n");
             AppleWMSendEvent(AppleWMActivationNotify,
                              AppleWMActivationNotifyMask,
                              AppleWMIsInactive, 0);
@@ -374,18 +374,18 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinDisplayChanged:
-	  ErrorF("kXDarwinDisplayChanged\n");
+  //	  ErrorF("kXDarwinDisplayChanged\n");
             QuartzUpdateScreens();
             break;
 
         case kXDarwinWindowState:
-	  ErrorF("kXDarwinWindowState\n");
+  //	  ErrorF("kXDarwinWindowState\n");
             RootlessNativeWindowStateChanged(xe->u.clientMessage.u.l.longs0,
 		  			     xe->u.clientMessage.u.l.longs1);
 	    break;
 	  
         case kXDarwinWindowMoved:
-	  ErrorF("kXDarwinWindowMoved\n");
+  //	  ErrorF("kXDarwinWindowMoved\n");
             RootlessNativeWindowMoved (xe->u.clientMessage.u.l.longs0);
 	    break;
 
@@ -395,7 +395,7 @@ void DarwinModeProcessEvent(
             else if (quartzHasRoot) QuartzHide();
             else QuartzShow();
 #else
-	    ErrorF("kXDarwinToggleFullscreen not implemented\n");
+    //	    ErrorF("kXDarwinToggleFullscreen not implemented\n");
 #endif
             break;
 
@@ -404,7 +404,7 @@ void DarwinModeProcessEvent(
             QuartzSetRootless(xe->u.clientMessage.u.l.longs0);
             if (!quartzEnableRootless && !quartzHasRoot) QuartzHide();
 #else
-	    ErrorF("kXDarwinSetRootless not implemented\n");
+    //	    ErrorF("kXDarwinSetRootless not implemented\n");
 #endif
             break;
 
@@ -425,7 +425,7 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinBringAllToFront:
-	  ErrorF("kXDarwinBringAllToFront\n");
+  //	  ErrorF("kXDarwinBringAllToFront\n");
 	    RootlessOrderAllWindows();
             break;
 
commit 1dc55c67d96279dfa38fcd39c7129d7b185ba683
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 7 02:22:39 2007 -0800

    Fixed focus problem (clicking on an X11 window that sits behind
    an Aqua window would not always bring it to the top of the stack.

diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 62bf1f9..c52dfd0 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -225,6 +225,8 @@ message_kit_thread (SEL selector, NSObject *arg)
       if (_x_active) [self activateX:NO];
     } else if ([self modalWindow] == nil) {
       /* Must be an X window. Tell appkit it doesn't have focus. */
+      WindowPtr pWin = xprGetXWindowFromAppKit([e windowNumber]);
+      if (pWin) RootlessReorderWindow(pWin);
       for_appkit = NO;
       
       if ([self isActive]) {
diff --git a/hw/darwin/quartz/xpr/xpr.h b/hw/darwin/quartz/xpr/xpr.h
index 81bb912..09e85f5 100644
--- a/hw/darwin/quartz/xpr/xpr.h
+++ b/hw/darwin/quartz/xpr/xpr.h
@@ -37,6 +37,9 @@ void AppleDRIExtensionInit(void);
 void xprAppleWMInit(void);
 Bool xprInit(ScreenPtr pScreen);
 Bool xprIsX11Window(void *nsWindow, int windowNumber);
+WindowPtr xprGetX11Window(xp_window_id wid);
+WindowPtr xprGetXWindowFromAppKit(int windowNumber);
+
 void xprHideWindows(Bool hide);
 
 Bool QuartzInitCursor(ScreenPtr pScreen);
diff --git a/hw/darwin/quartz/xpr/xprFrame.c b/hw/darwin/quartz/xpr/xprFrame.c
index 53fbb31..54b2035 100644
--- a/hw/darwin/quartz/xpr/xprFrame.c
+++ b/hw/darwin/quartz/xpr/xprFrame.c
@@ -425,6 +425,37 @@ xprGetXWindow(xp_window_id wid)
     return winRec != NULL ? winRec->win : NULL;
 }
 
+/*
+ * Given the id of a physical window, try to find the top-level (or root)
+ * X window that it represents.
+ */
+WindowPtr
+xprGetXWindowFromAppKit(int windowNumber)
+{
+    RootlessWindowRec *winRec;
+    Bool ret;
+    xp_window_id wid;
+
+    if (window_hash == NULL)
+        return FALSE;
+
+    /* need to lock, since this function can be called by any thread */
+
+    pthread_mutex_lock(&window_hash_mutex);
+
+    if (xp_lookup_native_window(windowNumber, &wid))
+        ret = xprGetXWindow(wid) != NULL;
+    else
+        ret = FALSE;
+
+    pthread_mutex_unlock(&window_hash_mutex);
+
+    if (!ret) return NULL;
+    winRec = x_hash_table_lookup(window_hash, (void *) wid, NULL);
+
+    return winRec != NULL ? winRec->win : NULL;
+}
+
 
 /*
  * The windowNumber is an AppKit window number. Returns TRUE if xpr is
commit e5ecee63646731b816167dcdd01a1da9293b902d
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 7 01:56:37 2007 -0800

    formatting changes.

diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index bd6b062..62bf1f9 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -207,140 +207,111 @@ message_kit_thread (SEL selector, NSObject *arg)
 
 - (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;
+  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 an (AppKit) 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;
-		
-    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];
-				if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
-			}
-			break;
-			
-		case 18: /* ApplicationDidReactivate */
-			if (quartzHasRoot)
-				for_appkit = NO;
-			break;
-			
-		case NSApplicationDeactivatedEventType:
-			for_x = NO;
-			[self activateX:NO];
-			break;
-		}
-		break;
-		
-    default: break; /* for gcc */
+	  }
+	} 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];
+	if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
+      }
+      break;
+	
+      case 18: /* ApplicationDidReactivate */
+	if (quartzHasRoot) for_appkit = NO;
+	break;
+	
+    case NSApplicationDeactivatedEventType:
+      for_x = NO;
+      [self activateX:NO];
+      break;
     }
-	
-    if (for_appkit)
-		[super sendEvent:e];
-	
-    if (for_x)
-		send_nsevent (type, e);
+    break;
+    
+  default: break; /* for gcc */
+  }
+  
+  if (for_appkit) [super sendEvent:e];
+  
+  if (for_x) send_nsevent (type, e);
 }
 
 - (void) set_window_menu:(NSArray *)list
@@ -697,57 +668,53 @@ cfarray_to_nsarray (CFArrayRef in)
     const char *tem;
 	
     quartzUseSysBeep = [self prefs_get_boolean:@PREFS_SYSBEEP
-									   default:quartzUseSysBeep];
+                        default:quartzUseSysBeep];
     quartzEnableRootless = [self prefs_get_boolean:@PREFS_ROOTLESS
-										   default:quartzEnableRootless];
+                        default:quartzEnableRootless];
 #ifdef DARWIN_DDX_MISSING
     quartzFullscreenDisableHotkeys = ![self prefs_get_boolean:
-									   @PREFS_FULLSCREEN_HOTKEYS default:
-									   !quartzFullscreenDisableHotkeys];
+					      @PREFS_FULLSCREEN_HOTKEYS default:
+					      !quartzFullscreenDisableHotkeys];
     quartzXpluginOptions = [self prefs_get_integer:@PREFS_XP_OPTIONS
-										   default:quartzXpluginOptions];
+                            default:quartzXpluginOptions];
 #endif
 	
     darwinSwapAltMeta = [self prefs_get_boolean:@PREFS_SWAP_ALT_META
-										default:darwinSwapAltMeta];
+                         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);
-		
+                         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];
+                               default:X11EnableKeyEquivalents];
 	
     darwinSyncKeymap = [self prefs_get_boolean:@PREFS_SYNC_KEYMAP
-									   default:darwinSyncKeymap];
+                        default:darwinSyncKeymap];
 	
     tem = [self prefs_get_string:@PREFS_KEYMAP_FILE default:NULL];
-    if (tem != NULL)
-		darwinKeymapFile = strdup (tem);
-    else
-        darwinKeymapFile = NULL;
+    if (tem != NULL) darwinKeymapFile = strdup (tem);
+    else             darwinKeymapFile = NULL;
 	
     darwinDesiredDepth = [self prefs_get_integer:@PREFS_DEPTH
-										 default:darwinDesiredDepth];
+                          default:darwinDesiredDepth];
 	
     enable_stereo = [self prefs_get_boolean:@PREFS_ENABLE_STEREO
-									default:false];
+                     default:false];
 }
 
 /* This will end up at the end of the responder chain. */
 - (void) copy:sender
 {
     QuartzMessageServerThread (kXDarwinPasteboardNotify, 1,
-							   AppleWMCopyToPasteboard);
+			       AppleWMCopyToPasteboard);
 }
 
 - (BOOL) x_active
@@ -991,135 +958,133 @@ convert_flags (unsigned int nsflags)
 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 */
+  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;
     }
-	
-    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);
+    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);
 }
commit 7f1780091bc0a3bae0cbfa93ec4dae95eca447f1
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Nov 7 01:35:48 2007 -0800

    Fixed Spaces issue, correctly -- dragging an X window from one
    Space to another in Expose mode now works.

diff --git a/hw/darwin/darwin.h b/hw/darwin/darwin.h
index 93ad3ab..bc96bb0 100644
--- a/hw/darwin/darwin.h
+++ b/hw/darwin/darwin.h
@@ -127,7 +127,6 @@ enum {
             = LASTEvent+1,    // (from X.h list of event names)
     kXDarwinUpdateButtons,    // update state of mouse buttons 2 and up
     kXDarwinScrollWheel,      // scroll wheel event
-
     /*
      * Quartz-specific events -- not used in IOKit mode
      */
@@ -138,6 +137,8 @@ enum {
     kXDarwinReadPasteboard,   // copy Mac OS X pasteboard into X cut buffer
     kXDarwinWritePasteboard,  // copy X cut buffer onto Mac OS X pasteboard
     kXDarwinBringAllToFront,  // bring all X windows to front
+    kXDarwinToggleFullscreen, // Enable/Disable fullscreen mode
+    kXDarwinSetRootless,      // Set rootless mode
     /*
      * AppleWM events
      */
diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index a24aeb1..113a7d2 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -342,8 +342,22 @@ void DarwinModeProcessEvent(
     xEvent *xe)
 {
     switch (xe->u.u.type) {
+        case kXDarwinControllerNotify:
+            AppleWMSendEvent(AppleWMControllerNotify,
+                             AppleWMControllerNotifyMask,
+                             xe->u.clientMessage.u.l.longs0,
+                             xe->u.clientMessage.u.l.longs1);
+            break;
+
+        case kXDarwinPasteboardNotify:
+            AppleWMSendEvent(AppleWMPasteboardNotify,
+                             AppleWMPasteboardNotifyMask,
+                             xe->u.clientMessage.u.l.longs0,
+                             xe->u.clientMessage.u.l.longs1);
+            break;
 
         case kXDarwinActivate:
+	  ErrorF("kXDarwinActivate\n");
             QuartzShow(xe->u.keyButtonPointer.rootX,
                        xe->u.keyButtonPointer.rootY);
             AppleWMSendEvent(AppleWMActivationNotify,
@@ -352,12 +366,48 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinDeactivate:
+	  ErrorF("kXDarwinDeactivate\n");
             AppleWMSendEvent(AppleWMActivationNotify,
                              AppleWMActivationNotifyMask,
                              AppleWMIsInactive, 0);
             QuartzHide();
             break;
 
+        case kXDarwinDisplayChanged:
+	  ErrorF("kXDarwinDisplayChanged\n");
+            QuartzUpdateScreens();
+            break;
+
+        case kXDarwinWindowState:
+	  ErrorF("kXDarwinWindowState\n");
+            RootlessNativeWindowStateChanged(xe->u.clientMessage.u.l.longs0,
+		  			     xe->u.clientMessage.u.l.longs1);
+	    break;
+	  
+        case kXDarwinWindowMoved:
+	  ErrorF("kXDarwinWindowMoved\n");
+            RootlessNativeWindowMoved (xe->u.clientMessage.u.l.longs0);
+	    break;
+
+        case kXDarwinToggleFullscreen:
+#ifdef DARWIN_DDX_MISSING
+            if (quartzEnableRootless) QuartzSetFullscreen(!quartzHasRoot);
+            else if (quartzHasRoot) QuartzHide();
+            else QuartzShow();
+#else
+	    ErrorF("kXDarwinToggleFullscreen not implemented\n");
+#endif
+            break;
+
+        case kXDarwinSetRootless:
+#ifdef DARWIN_DDX_MISSING
+            QuartzSetRootless(xe->u.clientMessage.u.l.longs0);
+            if (!quartzEnableRootless && !quartzHasRoot) QuartzHide();
+#else
+	    ErrorF("kXDarwinSetRootless not implemented\n");
+#endif
+            break;
+
         case kXDarwinSetRootClip:
             QuartzSetRootClip((BOOL)xe->u.clientMessage.u.l.longs0);
             break;
@@ -374,46 +424,13 @@ void DarwinModeProcessEvent(
             QuartzWritePasteboard();
             break;
 
-        /*
-         * AppleWM events
-         */
-        case kXDarwinControllerNotify:
-            AppleWMSendEvent(AppleWMControllerNotify,
-                             AppleWMControllerNotifyMask,
-                             xe->u.clientMessage.u.l.longs0,
-                             xe->u.clientMessage.u.l.longs1);
-            break;
-
-        case kXDarwinPasteboardNotify:
-            AppleWMSendEvent(AppleWMPasteboardNotify,
-                             AppleWMPasteboardNotifyMask,
-                             xe->u.clientMessage.u.l.longs0,
-                             xe->u.clientMessage.u.l.longs1);
-            break;
-
-        case kXDarwinDisplayChanged:
-            QuartzUpdateScreens();
-            break;
-
         case kXDarwinBringAllToFront:
+	  ErrorF("kXDarwinBringAllToFront\n");
 	    RootlessOrderAllWindows();
             break;
 
-        case kXDarwinWindowState:
-	  ErrorF("kXDarwinWindowState\n");
-	  break;
-    case kXDarwinWindowMoved: {
-	  WindowPtr pWin = (WindowPtr)xe->u.clientMessage.u.l.longs0;
-	  short x = xe->u.clientMessage.u.l.longs1,
-	        y = xe->u.clientMessage.u.l.longs2;
-	  ErrorF("kXDarwinWindowMoved(%p, %hd, %hd)\n", pWin, x, y);
-	  RootlessMoveWindow(pWin, x, y, pWin->nextSib, VTMove);
-    }
-	  break;
-
         default:
-            ErrorF("Unknown application defined event type %d.\n",
-                   xe->u.u.type);
+            ErrorF("Unknown application defined event type %d.\n", xe->u.u.type);
     }
 }
 
diff --git a/hw/darwin/quartz/quartz.h b/hw/darwin/quartz/quartz.h
index fa7499d..172f323 100644
--- a/hw/darwin/quartz/quartz.h
+++ b/hw/darwin/quartz/quartz.h
@@ -122,6 +122,7 @@ typedef struct _QuartzModeProcs {
 } QuartzModeProcsRec, *QuartzModeProcsPtr;
 
 extern QuartzModeProcsPtr quartzProcs;
+extern int quartzHasRoot, quartzEnableRootless;
 
 Bool QuartzLoadDisplayBundle(const char *dpyBundleName);
 
diff --git a/miext/rootless/rootless.h b/miext/rootless/rootless.h
index d9fdb6a..b4a5b2a 100644
--- a/miext/rootless/rootless.h
+++ b/miext/rootless/rootless.h
@@ -74,6 +74,8 @@ typedef struct _RootlessWindowRec {
 
     unsigned int is_drawing :1;	// Currently drawing?
     unsigned int is_reorder_pending :1;
+    unsigned int is_offscreen :1;
+    unsigned int is_obscured :1;
 } RootlessWindowRec, *RootlessWindowPtr;
 
 
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index 1e06d2c..1aa0b77 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -36,13 +36,23 @@
 #include <stddef.h> /* For NULL */
 #include <limits.h> /* For CHAR_BIT */
 #include <assert.h>
+#ifdef __APPLE__
+//#include <X11/Xlib.h>
+#include <X11/Xatom.h>
+#include "mi.h"
+#include "pixmapstr.h"
+#include "windowstr.h"
+#include <Xplugin.h>
+//#include <X11/extensions/applewm.h>
+extern int darwinMainScreenX, darwinMainScreenY;
+#endif
+#include "fb.h"
+
+#define AppleWMNumWindowLevels 5
 
 #include "rootlessCommon.h"
 #include "rootlessWindow.h"
 
-#include "fb.h"
-
-
 #ifdef ROOTLESS_GLOBAL_COORDS
 #define SCREEN_TO_GLOBAL_X \
     (dixScreenOrigins[pScreen->myNum].x + rootlessGlobalOffsetX)
@@ -53,6 +63,127 @@
 #define SCREEN_TO_GLOBAL_Y 0
 #endif
 
+#define DEFINE_ATOM_HELPER(func,atom_name)                      \
+  static Atom func (void) {                                       \
+    static unsigned int generation;                             \
+    static Atom atom;                                           \
+    if (generation != serverGeneration) {                       \
+      generation = serverGeneration;                          \
+      atom = MakeAtom (atom_name, strlen (atom_name), TRUE);  \
+    }                                                           \
+    return atom;                                                \
+  }
+
+DEFINE_ATOM_HELPER (xa_native_screen_origin, "_NATIVE_SCREEN_ORIGIN")
+DEFINE_ATOM_HELPER (xa_native_window_id, "_NATIVE_WINDOW_ID")
+DEFINE_ATOM_HELPER (xa_apple_no_order_in, "_APPLE_NO_ORDER_IN")
+
+static Bool no_configure_window;
+static Bool windows_hidden;
+// TODO - abstract xp functions
+
+static const int normal_window_levels[AppleWMNumWindowLevels+1] = {
+  0, 3, 4, 5, LONG_MIN + 30, LONG_MIN + 29,
+};
+static const int rooted_window_levels[AppleWMNumWindowLevels+1] = {
+  202, 203, 204, 205, 201, 200
+};
+
+static inline int
+configure_window (xp_window_id id, unsigned int mask,
+                  const xp_window_changes *values)
+{
+  if (!no_configure_window)
+    return xp_configure_window (id, mask, values);
+  else
+    return XP_Success;
+}
+
+/*static inline unsigned long
+current_time_in_seconds (void)
+{
+  unsigned long t = 0;
+
+  t += currentTime.milliseconds / 1000;
+  t += currentTime.months * 4294967;
+
+  return t;
+  } */
+
+static inline Bool
+rootlessHasRoot (ScreenPtr pScreen)
+{
+  return WINREC (WindowTable[pScreen->myNum]) != NULL;
+}
+
+void
+RootlessNativeWindowStateChanged (xp_window_id id, unsigned int state)
+{
+  WindowPtr pWin;
+  RootlessWindowRec *winRec;
+
+  pWin = xprGetXWindow (id);
+  if (pWin == NULL) return;
+
+  winRec = WINREC (pWin);
+  if (winRec == NULL) return;
+
+  winRec->is_offscreen = ((state & XP_WINDOW_STATE_OFFSCREEN) != 0);
+  winRec->is_obscured = ((state & XP_WINDOW_STATE_OBSCURED) != 0);
+  //  pWin->rootlessUnhittable = winRec->is_offscreen;
+}
+
+void
+RootlessNativeWindowMoved (WindowPtr pWin)
+{
+  xp_box bounds;
+  int sx, sy;
+  XID vlist[2];
+  Mask mask;
+  ClientPtr client;
+  RootlessWindowRec *winRec = WINREC(pWin);
+
+  if (xp_get_window_bounds (winRec->wid, &bounds) != Success) return;
+
+  sx = dixScreenOrigins[pWin->drawable.pScreen->myNum].x + darwinMainScreenX;
+  sy = dixScreenOrigins[pWin->drawable.pScreen->myNum].y + darwinMainScreenY;
+
+  /* Fake up a ConfigureWindow packet to resize the window to the current bounds. */
+
+  vlist[0] = (INT16) bounds.x1 - sx;
+  vlist[1] = (INT16) bounds.y1 - sy;
+  mask = CWX | CWY;
+
+  /* pretend we're the owner of the window! */
+  client = LookupClient (pWin->drawable.id, NullClient);
+
+  /* Don't want to do anything to the physical window (avoids 
+     notification-response feedback loops) */
+
+  no_configure_window = TRUE;
+  ConfigureWindow (pWin, mask, vlist, client);
+  no_configure_window = FALSE;
+}
+
+/* Updates the _NATIVE_SCREEN_ORIGIN property on the given root window. */
+static void
+set_screen_origin (WindowPtr pWin)
+{
+  long data[2];
+
+  if (!IsRoot (pWin))
+    return;
+
+  /* FIXME: move this to an extension? */
+
+  data[0] = (dixScreenOrigins[pWin->drawable.pScreen->myNum].x
+	     + darwinMainScreenX);
+  data[1] = (dixScreenOrigins[pWin->drawable.pScreen->myNum].y
+	     + darwinMainScreenY);
+
+  ChangeWindowProperty (pWin, xa_native_screen_origin (), XA_INTEGER,
+			32, PropModeReplace, 2, data, TRUE);
+}
 
 /*
  * RootlessCreateWindow
@@ -567,7 +698,6 @@ RootlessRestackWindow(WindowPtr pWin, WindowPtr pOldNextSib)
     RL_DEBUG_MSG("restackwindow end\n");
 }
 
-
 /*
  * Specialized window copy procedures
  */
commit df17777fe75481ac2587b831a448e802095c5783
Author: Ben Byer <bbyer at bbyer.local>
Date:   Tue Nov 6 23:19:03 2007 -0800

    Fixed glx/DarwinGlx symbol problems; other servers (such as xvfb and xnest)
    should now be buildable from this code if you pass e.g. --enable-xvfb
    to configure.

diff --git a/configure.ac b/configure.ac
index 1636ad5..e0aa894 100644
--- a/configure.ac
+++ b/configure.ac
@@ -656,7 +656,7 @@ if test "x$GLX" = xyes && ! test "x$MESA_SOURCE" = x; then
 	PKG_CHECK_MODULES([GL], [glproto >= 1.4.8])
 	AC_SUBST(XLIB_CFLAGS)
 	AC_DEFINE(GLXEXT, 1, [Build GLX extension])
-	GLX_LIBS='$(top_builddir)/GL/apple/indirect.o $(top_builddir)/GL/glx/libglx.la'
+	GLX_LIBS='$(top_builddir)/GL/glx/libglx.la $(top_builddir)/GL/mesa/libGLcore.la'
 	test -d GL || mkdir GL
 	case $host_os in
 	  solaris*) 	
@@ -1645,7 +1645,8 @@ return 0;}
 #               LDFLAGS=$save_LDFLAGS
 #               ])
                xorg_cv_AGL_framework=no
-	       DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $GLX_LIBS $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB"
+	       DARWIN_GLX_LIBS='$(top_builddir)/GL/apple/indirect.o $(top_builddir)/GL/glx/libglx.la'
+	       DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $DARWIN_GLX_LIBS"
 	       AC_SUBST([DARWIN_LIBS])
                AC_CHECK_LIB([Xplugin],[xp_init],[:])
                AC_SUBST([APPLE_APPLICATIONS_DIR])
diff --git a/mi/miinitext.c b/mi/miinitext.c
index fa00674..8736745 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -338,7 +338,7 @@ extern void XFree86DGAExtensionInit(INITARGS);
 #endif
 #ifdef GLXEXT
 typedef struct __GLXprovider __GLXprovider;
-#if defined(__DARWIN__) && !defined(INXQUARTZ)
+#if defined(__DARWIN__) && defined(INXDARWINAPP)
 extern __GLXprovider* __DarwinglXMesaProvider;
 extern void DarwinGlxPushProvider(__GLXprovider *impl);
 extern void DarwinGlxExtensionInit(INITARGS);
@@ -632,7 +632,7 @@ InitExtensions(argc, argv)
 #endif
 #endif
 #ifdef GLXEXT
-#if defined(__DARWIN__) && !defined(INXQUARTZ)
+#if defined(__DARWIN__) && defined(INXDARWINAPP)
     DarwinGlxPushProvider(__DarwinglXMesaProvider);
     if (!noGlxExtension) DarwinGlxExtensionInit();
 #else
commit 0504639d9f63a9982458e57dcc61b36f4ef67721
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Nov 5 20:25:10 2007 -0800

    formatting cleanup

diff --git a/hw/darwin/quartz/quartzKeyboard.c b/hw/darwin/quartz/quartzKeyboard.c
index 10fca0e..79028ef 100644
--- a/hw/darwin/quartz/quartzKeyboard.c
+++ b/hw/darwin/quartz/quartzKeyboard.c
@@ -1,10 +1,9 @@
 /*
    quartzKeyboard.c
 
-   Code to build a keymap using the Carbon Keyboard Layout API,
-   which is supported on Mac OS X 10.2 and newer.
+   Code to build a keymap using the Carbon Keyboard Layout API.
 
-   Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
+   Copyright (c) 2003-2007 Apple, Inc.
 
    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation files
@@ -152,22 +151,17 @@ unsigned int
 DarwinModeSystemKeymapSeed (void)
 {
     static unsigned int seed;
-
     static KeyboardLayoutRef last_key_layout;
     KeyboardLayoutRef key_layout;
 
     KLGetCurrentKeyboardLayout (&key_layout);
-
-    if (key_layout != last_key_layout)
-        seed++;
-
+    if (key_layout != last_key_layout) seed++;
     last_key_layout = key_layout;
 
     return seed;
 }
 
-//static inline UniChar
-UniChar
+static inline UniChar
 macroman2ucs (unsigned char c)
 {
     /* Precalculated table mapping MacRoman-128 to Unicode. Generated
@@ -193,10 +187,8 @@ macroman2ucs (unsigned char c)
         0xaf, 0x2d8, 0x2d9, 0x2da, 0xb8, 0x2dd, 0x2db, 0x2c7,
     };
 
-    if (c < 128)
-        return c;
-    else
-        return table[c - 128];
+    if (c < 128) return c;
+    else         return table[c - 128];
 }
 
 static KeySym
@@ -205,10 +197,7 @@ make_dead_key (KeySym in)
     int i;
 
     for (i = 0; i < sizeof (dead_keys) / sizeof (dead_keys[0]); i++)
-    {
-        if (dead_keys[i].normal == in)
-            return dead_keys[i].dead;
-    }
+        if (dead_keys[i].normal == in) return dead_keys[i].dead;
 
     return in;
 }
@@ -252,53 +241,39 @@ DarwinModeReadSystemKeymap (darwinKeyboardInfo *info)
        an X11 keysym (which may just the bit that says "this is
        Unicode" if it can't find the real symbol.) */
 
-    for (i = 0; i < num_keycodes; i++)
-    {
+    for (i = 0; i < num_keycodes; i++) {
         static const int mods[4] = {0, MOD_SHIFT, MOD_OPTION,
                                     MOD_OPTION | MOD_SHIFT};
 
         k = info->keyMap + i * GLYPHS_PER_KEY;
 
-        for (j = 0; j < 4; j++)
-        {
-            if (is_uchr)
-            {
+        for (j = 0; j < 4; j++) {
+            if (is_uchr)  {
                 UniChar s[8];
                 UniCharCount len;
-                UInt32 dead_key_state, extra_dead;
+                UInt32 dead_key_state = 0, extra_dead = 0;
 
-                dead_key_state = 0;
                 err = UCKeyTranslate (chr_data, i, kUCKeyActionDown,
                                       mods[j] >> 8, keyboard_type, 0,
                                       &dead_key_state, 8, &len, s);
-                if (err != noErr)
-                    continue;
+                if (err != noErr) continue;
 
-                if (len == 0 && dead_key_state != 0)
-                {
+                if (len == 0 && dead_key_state != 0) {
                     /* Found a dead key. Work out which one it is, but
                        remembering that it's dead. */
-
-                    extra_dead = 0;
                     err = UCKeyTranslate (chr_data, i, kUCKeyActionDown,
                                           mods[j] >> 8, keyboard_type,
                                           kUCKeyTranslateNoDeadKeysMask,
                                           &extra_dead, 8, &len, s);
-                    if (err != noErr)
-                        continue;
+                    if (err != noErr) continue;
                 }
 
-                if (len > 0 && s[0] != 0x0010)
-                {
+                if (len > 0 && s[0] != 0x0010) {
                     k[j] = ucs2keysym (s[0]);
-    
-                    if (dead_key_state != 0)
-                        k[j] = make_dead_key (k[j]);
+                    if (dead_key_state != 0) k[j] = make_dead_key (k[j]);
                 }
-            }
-            else
-            {
-                UInt32 c, state = 0;
+            } else { // kchr
+	      UInt32 c, state = 0, state2 = 0;
                 UInt16 code;
 
                 code = i | mods[j];
@@ -310,67 +285,50 @@ DarwinModeReadSystemKeymap (darwinKeyboardInfo *info)
                    us the actual dead character. */
 
                 if (state != 0)
-                {
-                    UInt32 state2 = 0;
                     c = KeyTranslate (chr_data, code | 128, &state2);
-                }
 
                 /* Characters seem to be in MacRoman encoding. */
 
-                if (c != 0 && c != 0x0010)
-                {
+                if (c != 0 && c != 0x0010) {
                     k[j] = ucs2keysym (macroman2ucs (c & 255));
 
-                    if (state != 0)
-                        k[j] = make_dead_key (k[j]);
+                    if (state != 0) k[j] = make_dead_key (k[j]);
                 }
             }
         }
-
-        if (k[3] == k[2])
-            k[3] = NoSymbol;
-        if (k[2] == k[1])
-            k[2] = NoSymbol;
-        if (k[1] == k[0])
-            k[1] = NoSymbol;
-        if (k[0] == k[2] && k[1] == k[3])
-            k[2] = k[3] = NoSymbol;
+	
+        if (k[3] == k[2]) k[3] = NoSymbol;
+        if (k[2] == k[1]) k[2] = NoSymbol;
+        if (k[1] == k[0]) k[1] = NoSymbol;
+        if (k[0] == k[2] && k[1] == k[3]) k[2] = k[3] = NoSymbol;
     }
 
     /* Fix up some things that are normally missing.. */
 
-    if (HACK_MISSING)
-    {
-        for (i = 0; i < sizeof (known_keys) / sizeof (known_keys[0]); i++)
-        {
+    if (HACK_MISSING) {
+        for (i = 0; i < sizeof (known_keys) / sizeof (known_keys[0]); i++) {
             k = info->keyMap + known_keys[i].keycode * GLYPHS_PER_KEY;
 
-            if (k[0] == NoSymbol && k[1] == NoSymbol
+            if    (k[0] == NoSymbol && k[1] == NoSymbol
                 && k[2] == NoSymbol && k[3] == NoSymbol)
-            {
-                k[0] = known_keys[i].keysym;
-            }
+	      k[0] = known_keys[i].keysym;
         }
     }
 
     /* And some more things. We find the right symbols for the numeric
        keypad, but not the KP_ keysyms. So try to convert known keycodes. */
 
-    if (HACK_KEYPAD)
-    {
+    if (HACK_KEYPAD) {
         for (i = 0; i < sizeof (known_numeric_keys)
-                        / sizeof (known_numeric_keys[0]); i++)
-        {
+                        / sizeof (known_numeric_keys[0]); i++) {
             k = info->keyMap + known_numeric_keys[i].keycode * GLYPHS_PER_KEY;
 
             if (k[0] == known_numeric_keys[i].normal)
-            {
                 k[0] = known_numeric_keys[i].keypad;
-            }
         }
     }
-	if(currentKeyLayoutRef)	CFRelease(currentKeyLayoutRef);
-
+    if(currentKeyLayoutRef)	CFRelease(currentKeyLayoutRef);
+    
     return TRUE;
 }
 
commit c3a9b7a664c92a3a7a1d9de894f632330b5c3109
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Nov 5 20:01:34 2007 -0800

    Fixed logic error that prevent JIS (Japanese) keyboard layouts from
    being detected.

diff --git a/hw/darwin/quartz/quartzKeyboard.c b/hw/darwin/quartz/quartzKeyboard.c
index 60f73e5..10fca0e 100644
--- a/hw/darwin/quartz/quartzKeyboard.c
+++ b/hw/darwin/quartz/quartzKeyboard.c
@@ -225,36 +225,27 @@ DarwinModeReadSystemKeymap (darwinKeyboardInfo *info)
     KeySym *k;
 
     TISInputSourceRef currentKeyLayoutRef = TISCopyCurrentKeyboardLayoutInputSource();
-	if (currentKeyLayoutRef)
-	{
-		CFDataRef currentKeyLayoutDataRef = (CFDataRef )TISGetInputSourceProperty(currentKeyLayoutRef, kTISPropertyUnicodeKeyLayoutData);
-		if (currentKeyLayoutDataRef)
-			chr_data = CFDataGetBytePtr(currentKeyLayoutDataRef);
-	}
-	
-	if(chr_data == NULL) {
-		KLGetCurrentKeyboardLayout (&key_layout);
-		KLGetKeyboardLayoutProperty (key_layout, kKLuchrData, &chr_data);
-
-		if (chr_data != NULL)
-		{
-			is_uchr = 1;
-			keyboard_type = LMGetKbdType ();
-		}
-		else
-		{
-			KLGetKeyboardLayoutProperty (key_layout, kKLKCHRData, &chr_data);
-
-			if (chr_data == NULL)
-			{
-				ErrorF ( "Couldn't get uchr or kchr resource\n");
-				return FALSE;
-			}
-
-			is_uchr = 0;
-			num_keycodes = 128;
-		}    
-	}
+    keyboard_type = LMGetKbdType ();
+    if (currentKeyLayoutRef) {
+      CFDataRef currentKeyLayoutDataRef = (CFDataRef )TISGetInputSourceProperty(currentKeyLayoutRef, kTISPropertyUnicodeKeyLayoutData);
+      if (currentKeyLayoutDataRef) chr_data = CFDataGetBytePtr(currentKeyLayoutDataRef);
+    }
+    
+    if (chr_data == NULL) {
+      KLGetCurrentKeyboardLayout (&key_layout);
+      KLGetKeyboardLayoutProperty (key_layout, kKLuchrData, &chr_data);
+    }
+    
+    if (chr_data == NULL) {
+      KLGetKeyboardLayoutProperty (key_layout, kKLKCHRData, &chr_data);
+      is_uchr = 0;
+      num_keycodes = 128;
+    }
+    
+    if (chr_data == NULL) {
+      ErrorF ( "Couldn't get uchr or kchr resource\n");
+      return FALSE;
+    }
 
     /* Scan the keycode range for the Unicode character that each
        key produces in the four shift states. Then convert that to
commit 707ae28034748405719226f330a1f26f7479b92b
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sun Nov 4 19:14:40 2007 -0800

    bump version to 1.2a6

diff --git a/configure.ac b/configure.ac
index 9fa40f6..1636ad5 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.2a5, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a6, [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 --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index a8ba95f..bd6b062 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -156,7 +156,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a5)",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a6)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
diff --git a/hw/xfree86/scanpci/pciid2c.pl b/hw/xfree86/scanpci/pciid2c.pl
old mode 100644
new mode 100755
commit 1a1be462ed82cfbe8ec8e0dea9efa9a44798accc
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sun Nov 4 19:14:10 2007 -0800

    Disable deferred updates in xp_init to fix performance problems
    -- thanks to Eric Gouriou for pointing out the issue

diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index 9284d5d..d84e646 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -46,10 +46,13 @@
 # include "damage.h"
 #endif
 
+/* 10.4's deferred update makes X slower.. have to live with the tearing
+   for now.. */
+#define XP_NO_DEFERRED_UPDATES 8
+
 // Name of GLX bundle for native OpenGL
 static const char *xprOpenGLBundle = "glxCGL.bundle";
 
-
 /*
  * eventHandler
  *  Callback handler for Xplugin events.
@@ -230,7 +233,7 @@ xprDisplayInit(void)
     else
         darwinScreensFound =  1;
 
-    if (xp_init(XP_IN_BACKGROUND) != Success)
+    if (xp_init(XP_IN_BACKGROUND | XP_NO_DEFERRED_UPDATES) != Success)
     {
         FatalError("Could not initialize the Xplugin library.");
     }
commit a36983602f3be15b6fa76e634df9e7c7438f4c65
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sat Nov 3 22:06:39 2007 -0700

    bump version to 1.2a5

diff --git a/configure.ac b/configure.ac
index 8eb4f49..9fa40f6 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.2a4, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a5, [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 --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 9dba46c..a8ba95f 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -156,7 +156,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a4)",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a5)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
commit 2d50ea8013e7c1639d570e227b53b037fb567565
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sat Nov 3 05:34:19 2007 -0700

    Initial support for Spaces -- if you use Expose to drag an X11
    window to another Space, it will work correctly (as opposed
    to just leaving a ghost window).  We accomplish this by listening
    for the notification from Xplugin that our window has been moved,
    and then we ask X11 to move the window to the new location.

diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 8670e57..a24aeb1 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -400,9 +400,16 @@ void DarwinModeProcessEvent(
             break;
 
         case kXDarwinWindowState:
-        case kXDarwinWindowMoved:
-            // FIXME: Not implemented yet
-            break;
+	  ErrorF("kXDarwinWindowState\n");
+	  break;
+    case kXDarwinWindowMoved: {
+	  WindowPtr pWin = (WindowPtr)xe->u.clientMessage.u.l.longs0;
+	  short x = xe->u.clientMessage.u.l.longs1,
+	        y = xe->u.clientMessage.u.l.longs2;
+	  ErrorF("kXDarwinWindowMoved(%p, %hd, %hd)\n", pWin, x, y);
+	  RootlessMoveWindow(pWin, x, y, pWin->nextSib, VTMove);
+    }
+	  break;
 
         default:
             ErrorF("Unknown application defined event type %d.\n",
diff --git a/hw/darwin/quartz/xpr/xprFrame.c b/hw/darwin/quartz/xpr/xprFrame.c
index 0e3b200..53fbb31 100644
--- a/hw/darwin/quartz/xpr/xprFrame.c
+++ b/hw/darwin/quartz/xpr/xprFrame.c
@@ -68,6 +68,7 @@ static inline xp_error
 xprConfigureWindow(xp_window_id id, unsigned int mask,
                    const xp_window_changes *values)
 {
+  //  ErrorF("xprConfigureWindow()\n");
     if (!no_configure_window)
         return xp_configure_window(id, mask, values);
     else
@@ -185,7 +186,7 @@ xprMoveFrame(RootlessFrameID wid, ScreenPtr pScreen, int newX, int newY)
 
     wc.x = newX;
     wc.y = newY;
-
+    //    ErrorF("xprMoveFrame(%d, %p, %d, %d)\n", wid, pScreen, newX, newY);
     xprConfigureWindow((xp_window_id) wid, XP_ORIGIN, &wc);
 }
 
@@ -411,7 +412,7 @@ xprInit(ScreenPtr pScreen)
  * Given the id of a physical window, try to find the top-level (or root)
  * X window that it represents.
  */
-static WindowPtr
+WindowPtr
 xprGetXWindow(xp_window_id wid)
 {
     RootlessWindowRec *winRec;
diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index 92886fc..9284d5d 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -61,10 +61,12 @@ eventHandler(unsigned int type, const void *arg,
     switch (type)
     {
     case XP_EVENT_DISPLAY_CHANGED:
+      //      ErrorF("XP_EVENT_DISPLAY_MOVED\n");
         QuartzMessageServerThread(kXDarwinDisplayChanged, 0);
         break;
 
     case XP_EVENT_WINDOW_STATE_CHANGED:
+      //      ErrorF("XP_EVENT_WINDOW_STATE_CHANGED\n");
         if (arg_size >= sizeof(xp_window_state_event))
         {
             const xp_window_state_event *ws_arg = arg;
@@ -75,16 +77,24 @@ eventHandler(unsigned int type, const void *arg,
         break;
 
     case XP_EVENT_WINDOW_MOVED:
+      //      ErrorF("XP_EVENT_WINDOW_MOVED\n");
         if (arg_size == sizeof(xp_window_id))
         {
             xp_window_id id = * (xp_window_id *) arg;
-
-            QuartzMessageServerThread(kXDarwinWindowMoved, 1, id);
+	    WindowPtr pWin = xprGetXWindow(id);
+	    BoxRec box;
+	    xp_error retval  = xp_get_window_bounds(id, &box);
+	    if (retval != Success) {
+	      ErrorF("Unable to find new bounds for window\n");
+	      break;
+	    }
+            QuartzMessageServerThread(kXDarwinWindowMoved, 3, pWin, box.x1, box.y1);
         }
         break;
 
     case XP_EVENT_SURFACE_DESTROYED:
     case XP_EVENT_SURFACE_CHANGED:
+      //      ErrorF("XP_EVENT_SURFACE_MOVED\n");
         if (arg_size == sizeof(xp_surface_id))
         {
             int kind;
commit b6681aff2ba23b1489283f2d1190415a85f807de
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sat Nov 3 02:05:34 2007 -0700

    bumped version to 1.2a4

diff --git a/configure.ac b/configure.ac
index ff756cb..8eb4f49 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.2a3, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a4, [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 --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index ccdc072..9dba46c 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -156,7 +156,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a3)",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a4)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
commit 1f945fcabe2c99e4637add34103de58c4b6d6477
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Nov 2 15:19:39 2007 -0700

    Imported a fix from xserver/master which was part of a larger refactoring of fbComposite
    code. This part fixes a logic error in SafeAlphaComposite where some return paths resulted
    in the server changing the color depth of a Drawable out from under the client.
    This caused random crashes in many cairo/pango/gtk apps. Props to Guy Harris for tracking
    this down in WireShark, but it will probably solve problems in other apps (Inkscape, Gimp?)

diff --git a/fb/fbpict.c b/fb/fbpict.c
index 613e652..5f7289a 100644
--- a/fb/fbpict.c
+++ b/fb/fbpict.c
@@ -37,19 +37,6 @@
 #include "fbpict.h"
 #include "fbmmx.h"
 
-typedef void	(*CompositeFunc) (CARD8      op,
-				  PicturePtr pSrc,
-				  PicturePtr pMask,
-				  PicturePtr pDst,
-				  INT16      xSrc,
-				  INT16      ySrc,
-				  INT16      xMask,
-                                  INT16      yMask,
-				  INT16      xDst,
-				  INT16      yDst,
-				  CARD16     width,
-				  CARD16     height);
-
 CARD32
 fbOver (CARD32 x, CARD32 y)
 {
@@ -826,6 +813,110 @@ fbCompositeSolidMask_nx1xn (CARD8      op,
 # define mod(a,b)	((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b))
 
 void
+fbWalkCompositeRegion (CARD8 op,
+                       PicturePtr pSrc,
+                       PicturePtr pMask,
+                       PicturePtr pDst,
+                       INT16 xSrc,
+                       INT16 ySrc,
+                       INT16 xMask,
+                       INT16 yMask,
+                       INT16 xDst,
+                       INT16 yDst,
+                       CARD16 width,
+                       CARD16 height,
+                       Bool srcRepeat,
+                       Bool maskRepeat,
+                       CompositeFunc compositeRect)
+{
+  RegionRec       region;
+  int             n;
+  BoxPtr          pbox;
+  int             w, h, w_this, h_this;
+  int             x_msk, y_msk, x_src, y_src, x_dst, y_dst;
+    
+  xDst += pDst->pDrawable->x;
+  yDst += pDst->pDrawable->y;
+  if (pSrc->pDrawable)
+    {
+      xSrc += pSrc->pDrawable->x;
+      ySrc += pSrc->pDrawable->y;
+    }
+  if (pMask && pMask->pDrawable)
+    {
+      xMask += pMask->pDrawable->x;
+      yMask += pMask->pDrawable->y;
+    }
+
+  if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc,
+				 xMask, yMask, xDst, yDst, width, height))
+    return;
+    
+  n = REGION_NUM_RECTS (&region);
+  pbox = REGION_RECTS (&region);
+  while (n--)
+    {
+      h = pbox->y2 - pbox->y1;
+      y_src = pbox->y1 - yDst + ySrc;
+      y_msk = pbox->y1 - yDst + yMask;
+      y_dst = pbox->y1;
+      while (h)
+        {
+	  h_this = h;
+	  w = pbox->x2 - pbox->x1;
+	  x_src = pbox->x1 - xDst + xSrc;
+	  x_msk = pbox->x1 - xDst + xMask;
+	  x_dst = pbox->x1;
+	  if (maskRepeat)
+            {
+	      y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height);
+	      if (h_this > pMask->pDrawable->height - y_msk)
+		h_this = pMask->pDrawable->height - y_msk;
+	      y_msk += pMask->pDrawable->y;
+            }
+	  if (srcRepeat)
+            {
+	      y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height);
+	      if (h_this > pSrc->pDrawable->height - y_src)
+		h_this = pSrc->pDrawable->height - y_src;
+	      y_src += pSrc->pDrawable->y;
+            }
+	  while (w)
+            {
+	      w_this = w;
+	      if (maskRepeat)
+                {
+		  x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width);
+		  if (w_this > pMask->pDrawable->width - x_msk)
+		    w_this = pMask->pDrawable->width - x_msk;
+		  x_msk += pMask->pDrawable->x;
+                }
+	      if (srcRepeat)
+                {
+		  x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width);
+		  if (w_this > pSrc->pDrawable->width - x_src)
+		    w_this = pSrc->pDrawable->width - x_src;
+		  x_src += pSrc->pDrawable->x;
+		}
+	      (*compositeRect) (op, pSrc, pMask, pDst,
+				x_src, y_src, x_msk, y_msk, x_dst, y_dst,
+				w_this, h_this);
+	      w -= w_this;
+	      x_src += w_this;
+	      x_msk += w_this;
+	      x_dst += w_this;
+            }
+	  h -= h_this;
+	  y_src += h_this;
+	  y_msk += h_this;
+	  y_dst += h_this;
+        }
+      pbox++;
+    }
+  REGION_UNINIT (pDst->pDrawable->pScreen, &region);
+}
+
+void
 fbComposite (CARD8      op,
 	     PicturePtr pSrc,
 	     PicturePtr pMask,
diff --git a/fb/fbpict.h b/fb/fbpict.h
index bfcb38e..b90863e 100644
--- a/fb/fbpict.h
+++ b/fb/fbpict.h
@@ -618,6 +618,37 @@ fbComposite (CARD8      op,
 	     CARD16     width,
 	     CARD16     height);
 
+
+typedef void    (*CompositeFunc) (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
+fbWalkCompositeRegion (CARD8 op,
+		       PicturePtr pSrc,
+		       PicturePtr pMask,
+		       PicturePtr pDst,
+		       INT16 xSrc,
+		       INT16 ySrc,
+		       INT16 xMask,
+		       INT16 yMask,
+		       INT16 xDst,
+		       INT16 yDst,
+		       CARD16 width,
+		       CARD16 height,
+		       Bool srcRepeat,
+		       Bool maskRepeat,
+		       CompositeFunc compositeRect);
+
 /* fbtrap.c */
 
 void
diff --git a/miext/rootless/safeAlpha/safeAlphaPicture.c b/miext/rootless/safeAlpha/safeAlphaPicture.c
index 6ccc05a..8f66315 100644
--- a/miext/rootless/safeAlpha/safeAlphaPicture.c
+++ b/miext/rootless/safeAlpha/safeAlphaPicture.c
@@ -48,21 +48,6 @@
 #include "rootlessCommon.h"
 # define mod(a,b)	((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b))
 
-
-typedef void	(*CompositeFunc) (CARD8      op,
-				  PicturePtr pSrc,
-				  PicturePtr pMask,
-				  PicturePtr pDst,
-				  INT16      xSrc,
-				  INT16      ySrc,
-				  INT16      xMask,
-                                  INT16      yMask,
-				  INT16      xDst,
-				  INT16      yDst,
-				  CARD16     width,
-				  CARD16     height);
-
-
 /* Optimized version of fbCompositeSolidMask_nx8x8888 */
 void
 SafeAlphaCompositeSolidMask_nx8x8888(
@@ -148,499 +133,79 @@ SafeAlphaCompositeSolidMask_nx8x8888(
 }
 
 void
-SafeAlphaComposite (CARD8      op,
-    PicturePtr      pSrc,
-    PicturePtr      pMask,
-    PicturePtr      pDst,
-    INT16           xSrc,
-    INT16           ySrc,
-    INT16           xMask,
-    INT16           yMask,
-    INT16           xDst,
-    INT16           yDst,
-    CARD16          width,
-    CARD16          height)
+SafeAlphaComposite (CARD8           op,
+                    PicturePtr      pSrc,
+                    PicturePtr      pMask,
+                    PicturePtr      pDst,
+                    INT16           xSrc,
+                    INT16           ySrc,
+                    INT16           xMask,
+                    INT16           yMask,
+                    INT16           xDst,
+                    INT16           yDst,
+                    CARD16          width,
+                    CARD16          height)
 {
-    RegionRec	    region;
-    int		    n;
-    BoxPtr	    pbox;
-    CompositeFunc   func = 0;
-    Bool	    srcRepeat = pSrc->repeat;
-    Bool	    maskRepeat = FALSE;
-    Bool            srcAlphaMap = pSrc->alphaMap != 0;
-    Bool	    maskAlphaMap = FALSE;
-    Bool            dstAlphaMap = pDst->alphaMap != 0;
-    int		    x_msk, y_msk, x_src, y_src, x_dst, y_dst;
-    int		    w, h, w_this, h_this;
-    int		    dstDepth = pDst->pDrawable->depth;
-    int		    oldFormat = pDst->format;
-
-    xDst += pDst->pDrawable->x;
-    yDst += pDst->pDrawable->y;
-    xSrc += pSrc->pDrawable->x;
-    ySrc += pSrc->pDrawable->y;
-    if (pMask)
+  if (!pSrc) {
+    ErrorF("SafeAlphaComposite: pSrc must not be null!\n");
+    return;
+  }
+
+  if (!pDst) {
+    ErrorF("SafeAlphaComposite: pDst must not be null!\n");
+    return;
+  }
+  
+  int oldDepth = pDst->pDrawable->depth;
+  int oldFormat = pDst->format;
+    
+  /*
+   * We can use the more optimized fbpict code, but it sets bits above
+   * the depth to zero. Temporarily adjust destination depth if needed.
+   */
+  if (pDst->pDrawable->type == DRAWABLE_WINDOW
+        && pDst->pDrawable->depth == 24
+      && pDst->pDrawable->bitsPerPixel == 32)
     {
-	xMask += pMask->pDrawable->x;
-	yMask += pMask->pDrawable->y;
-	maskRepeat = pMask->repeat;
-	maskAlphaMap = pMask->alphaMap != 0;
+      pDst->pDrawable->depth = 32;
     }
-
-
-    /*
-     * We can use the more optimized fbpict code, but it sets bits above
-     * the depth to zero. Temporarily adjust destination depth if needed.
-     */
-    if (pDst->pDrawable->type == DRAWABLE_WINDOW
-	&& pDst->pDrawable->depth == 24
-	&& pDst->pDrawable->bitsPerPixel == 32)
+    
+  /* For rootless preserve the alpha in x8r8g8b8 which really is
+   * a8r8g8b8
+   */
+  if (oldFormat == PICT_x8r8g8b8)
     {
-	pDst->pDrawable->depth = 32;
+      pDst->format = PICT_a8r8g8b8;
     }
-    /* For rootless preserve the alpha in x8r8g8b8 which really is
-     * a8r8g8b8
-     */
-    if (oldFormat == PICT_x8r8g8b8)
+    
+  if (pSrc->pDrawable && pMask && pMask->pDrawable &&
+        !pSrc->transform && !pMask->transform &&
+        !pSrc->alphaMap && !pMask->alphaMap &&
+        !pMask->repeat && !pMask->componentAlpha && !pDst->alphaMap &&
+        pMask->format == PICT_a8 &&
+       pSrc->repeatType == RepeatNormal && 
+        pSrc->pDrawable->width == 1 &&
+        pSrc->pDrawable->height == 1 &&
+      (pDst->format == PICT_a8r8g8b8 ||
+         pDst->format == PICT_x8r8g8b8 ||
+         pDst->format == PICT_a8b8g8r8 ||
+       pDst->format == PICT_x8b8g8r8))
     {
-        pDst->format = PICT_a8r8g8b8;
-    }
-
-
-
-    if (!pSrc->transform && !(pMask && pMask->transform))
-    if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap)
-    switch (op) {
-    case PictOpSrc:
-#ifdef USE_MMX
-	if (!pMask && pSrc->format == pDst->format &&
-	    pSrc->pDrawable != pDst->pDrawable)
-	{
-	    func = fbCompositeCopyAreammx;
-	}
-#endif
-	break;
-    case PictOpOver:
-	if (pMask)
-	{
-	    if (srcRepeat && 
-		pSrc->pDrawable->width == 1 &&
-		pSrc->pDrawable->height == 1)
-	    {
-		srcRepeat = FALSE;
-		if (PICT_FORMAT_COLOR(pSrc->format)) {
-		    switch (pMask->format) {
-		    case PICT_a8:
-			switch (pDst->format) {
-			case PICT_r5g6b5:
-			case PICT_b5g6r5:
-#ifdef USE_MMX
-			    if (fbHaveMMX())
-				func = fbCompositeSolidMask_nx8x0565mmx;
-			    else
-#endif
-			    func = fbCompositeSolidMask_nx8x0565;
-			    break;
-			case PICT_r8g8b8:
-			case PICT_b8g8r8:
-			    func = fbCompositeSolidMask_nx8x0888;
-			    break;
-			case PICT_a8r8g8b8:
-			case PICT_x8r8g8b8:
-			case PICT_a8b8g8r8:
-			case PICT_x8b8g8r8:
-			    func = SafeAlphaCompositeSolidMask_nx8x8888;
-			    break;
-			}
-			break;
-		    case PICT_a8r8g8b8:
-			if (pMask->componentAlpha) {
-			    switch (pDst->format) {
-			    case PICT_a8r8g8b8:
-			    case PICT_x8r8g8b8:
-#ifdef USE_MMX
-				if (fbHaveMMX())
-				    func = fbCompositeSolidMask_nx8888x8888Cmmx;
-				else
-#endif
-				func = fbCompositeSolidMask_nx8888x8888C;
-				break;
-			    case PICT_r5g6b5:
-#ifdef USE_MMX
-				if (fbHaveMMX())
-				    func = fbCompositeSolidMask_nx8888x0565Cmmx;
-				else
-#endif
-				func = fbCompositeSolidMask_nx8888x0565C;
-				break;
-			    }
-			}
-			break;
-		    case PICT_a8b8g8r8:
-			if (pMask->componentAlpha) {
-			    switch (pDst->format) {
-			    case PICT_a8b8g8r8:
-			    case PICT_x8b8g8r8:
-#ifdef USE_MMX
-				if (fbHaveMMX())
-				    func = fbCompositeSolidMask_nx8888x8888Cmmx;
-				else
-#endif
-				func = fbCompositeSolidMask_nx8888x8888C;
-				break;
-			    case PICT_b5g6r5:
-#ifdef USE_MMX
-				if (fbHaveMMX())
-				    func = fbCompositeSolidMask_nx8888x0565Cmmx;
-				else
-#endif
-				func = fbCompositeSolidMask_nx8888x0565C;
-				break;
-			    }
-			}
-			break;
-		    case PICT_a1:
-			switch (pDst->format) {
-			case PICT_r5g6b5:
-			case PICT_b5g6r5:
-			case PICT_r8g8b8:
-			case PICT_b8g8r8:
-			case PICT_a8r8g8b8:
-			case PICT_x8r8g8b8:
-			case PICT_a8b8g8r8:
-			case PICT_x8b8g8r8:
-			    func = fbCompositeSolidMask_nx1xn;
-			    break;
-			}
-			break;
-		    }
-		}
-	    }
-	    else /* has mask and non-repeating source */
-	    {
-		if (pSrc->pDrawable == pMask->pDrawable &&
-		    xSrc == xMask && ySrc == yMask &&
-		    !pMask->componentAlpha)
-		{
-		    /* source == mask: non-premultiplied data */
-		    switch (pSrc->format) {
-		    case PICT_x8b8g8r8:
-			switch (pMask->format) {
-			case PICT_a8r8g8b8:
-			case PICT_a8b8g8r8:
-			    switch (pDst->format) {
-			    case PICT_a8r8g8b8:
-			    case PICT_x8r8g8b8:
-#ifdef USE_MMX
-				if (fbHaveMMX())
-				    func = fbCompositeSrc_8888RevNPx8888mmx;
-#endif
-				break;
-			    case PICT_r5g6b5:
-#ifdef USE_MMX
-				if (fbHaveMMX())
-				    func = fbCompositeSrc_8888RevNPx0565mmx;
-#endif
-				break;
-			    }
-			    break;
-			}
-			break;
-		    case PICT_x8r8g8b8:
-			switch (pMask->format) {
-			case PICT_a8r8g8b8:
-			case PICT_a8b8g8r8:
-			    switch (pDst->format) {
-			    case PICT_a8b8g8r8:
-			    case PICT_x8b8g8r8:
-#ifdef USE_MMX
-				if (fbHaveMMX())
-				    func = fbCompositeSrc_8888RevNPx8888mmx;
-#endif
-				break;
-			    case PICT_r5g6b5:
-#ifdef USE_MMX
-				if (fbHaveMMX())
-				    func = fbCompositeSrc_8888RevNPx0565mmx;
-#endif
-				break;
-			    }
-			    break;
-			}
-			break;
-		    }
-		    break;
-	}
-	else
-	{
-		    /* non-repeating source, repeating mask => translucent window */
-		    if (maskRepeat &&
-			pMask->pDrawable->width == 1 &&
-			pMask->pDrawable->height == 1)
-		    {
-			if (pSrc->format == PICT_x8r8g8b8 &&
-			    pDst->format == PICT_x8r8g8b8 &&
-			    pMask->format == PICT_a8)
-			{
-#ifdef USE_MMX
-			    if (fbHaveMMX())
-				func = fbCompositeSrc_8888x8x8888mmx;
-#endif
-			}
-		    }
-		}
-	    }
-	}
-	else /* no mask */
-	{
-	    if (srcRepeat &&
-		pSrc->pDrawable->width == 1 &&
-		pSrc->pDrawable->height == 1)
-	    {
-		/* no mask and repeating source */
-	    switch (pSrc->format) {
-	    case PICT_a8r8g8b8:
-		    switch (pDst->format) {
-		    case PICT_a8r8g8b8:
-	    case PICT_x8r8g8b8:
-#ifdef USE_MMX
-			if (fbHaveMMX())
-			{
-			    srcRepeat = FALSE;
-			    func = fbCompositeSolid_nx8888mmx;
-			}
-#endif
-			break;
-		    case PICT_r5g6b5:
-#ifdef USE_MMX
-			if (fbHaveMMX())
-			{
-			    srcRepeat = FALSE;
-			    func = fbCompositeSolid_nx0565mmx;
-			}
-#endif
-			break;
-		    }
-		    break;
-		}
-	    }
-	    else
-	    {
-		switch (pSrc->format) {
-		case PICT_a8r8g8b8:
-		switch (pDst->format) {
-		case PICT_a8r8g8b8:
-		case PICT_x8r8g8b8:
-#ifdef USE_MMX
-			if (fbHaveMMX())
-			    func = fbCompositeSrc_8888x8888mmx;
-			else
-#endif
-		    func = fbCompositeSrc_8888x8888;
-		    break;
-		case PICT_r8g8b8:
-		    func = fbCompositeSrc_8888x0888;
-		    break;
-		case PICT_r5g6b5:
-		    func = fbCompositeSrc_8888x0565;
-		    break;
-		}
-		break;
-		case PICT_x8r8g8b8:
-		    switch (pDst->format) {
-		    case PICT_a8r8g8b8:
-		    case PICT_x8r8g8b8:
-#ifdef USE_MMX
-			if (fbHaveMMX())
-			    func = fbCompositeCopyAreammx;
-#endif
-			break;
-		    }
-		case PICT_x8b8g8r8:
-		    switch (pDst->format) {
-	    case PICT_a8b8g8r8:
-	    case PICT_x8b8g8r8:
-#ifdef USE_MMX
-			if (fbHaveMMX())
-			    func = fbCompositeCopyAreammx;
-#endif
-			break;
-		    }
-		    break;
-		case PICT_a8b8g8r8:
-		switch (pDst->format) {
-		case PICT_a8b8g8r8:
-		case PICT_x8b8g8r8:
-#ifdef USE_MMX
-			if (fbHaveMMX())
-			    func = fbCompositeSrc_8888x8888mmx;
-			else
-#endif
-		    func = fbCompositeSrc_8888x8888;
-		    break;
-		case PICT_b8g8r8:
-		    func = fbCompositeSrc_8888x0888;
-		    break;
-		case PICT_b5g6r5:
-		    func = fbCompositeSrc_8888x0565;
-		    break;
-		}
-		break;
-	    case PICT_r5g6b5:
-		switch (pDst->format) {
-		case PICT_r5g6b5:
-		    func = fbCompositeSrc_0565x0565;
-		    break;
-		}
-		break;
-	    case PICT_b5g6r5:
-		switch (pDst->format) {
-		case PICT_b5g6r5:
-		    func = fbCompositeSrc_0565x0565;
-		    break;
-		}
-		break;
-	    }
-	}
-	}
-	break;
-    case PictOpAdd:
-	if (pMask == 0)
-	{
-	    switch (pSrc->format) {
-	    case PICT_a8r8g8b8:
-		switch (pDst->format) {
-		case PICT_a8r8g8b8:
-#ifdef USE_MMX
-		    if (fbHaveMMX())
-			func = fbCompositeSrcAdd_8888x8888mmx;
-		    else
-#endif
-		    func = fbCompositeSrcAdd_8888x8888;
-		    break;
-		}
-		break;
-	    case PICT_a8b8g8r8:
-		switch (pDst->format) {
-		case PICT_a8b8g8r8:
-#ifdef USE_MMX
-		    if (fbHaveMMX())
-			func = fbCompositeSrcAdd_8888x8888mmx;
-		    else
-#endif
-		    func = fbCompositeSrcAdd_8888x8888;
-		    break;
-		}
-		break;
-	    case PICT_a8:
-		switch (pDst->format) {
-		case PICT_a8:
-#ifdef USE_MMX
-		    if (fbHaveMMX())
-			func = fbCompositeSrcAdd_8000x8000mmx;
-		    else
-#endif
-		    func = fbCompositeSrcAdd_8000x8000;
-		    break;
-		}
-		break;
-	    case PICT_a1:
-		switch (pDst->format) {
-		case PICT_a1:
-		    func = fbCompositeSrcAdd_1000x1000;
-		    break;
-		}
-		break;
-	    }
-	}
-	break;
-    }
-
-    if (!func) {
-        /* no fast path, use the general code */
-        fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height);
-        // Reset destination depth and format to their true value
-        pDst->pDrawable->depth = dstDepth;
-        pDst->format = oldFormat;
-        return;
+      fbWalkCompositeRegion (op, pSrc, pMask, pDst,
+			     xSrc, ySrc, xMask, yMask, xDst, yDst,
+			     width, height,
+			     TRUE /* srcRepeat */,
+			     FALSE /* maskRepeat */,
+			     SafeAlphaCompositeSolidMask_nx8x8888);
     }
-
-    if (!miComputeCompositeRegion (&region,
- 				   pSrc,
- 				   pMask,
- 				   pDst,
- 				   xSrc,
- 				   ySrc,
- 				   xMask,
- 				   yMask,
- 				   xDst,
- 				   yDst,
- 				   width,
-                                   height))
-        return;
-
-    n = REGION_NUM_RECTS (&region);
-    pbox = REGION_RECTS (&region);
-    while (n--)
+  else
     {
-	h = pbox->y2 - pbox->y1;
-	y_src = pbox->y1 - yDst + ySrc;
-	y_msk = pbox->y1 - yDst + yMask;
-	y_dst = pbox->y1;
-	while (h)
-	{
-	    h_this = h;
-	    w = pbox->x2 - pbox->x1;
-	    x_src = pbox->x1 - xDst + xSrc;
-	    x_msk = pbox->x1 - xDst + xMask;
-	    x_dst = pbox->x1;
-	    if (maskRepeat)
-	    {
-		y_msk = mod (y_msk, pMask->pDrawable->height);
-		if (h_this > pMask->pDrawable->height - y_msk)
-		    h_this = pMask->pDrawable->height - y_msk;
-	    }
-	    if (srcRepeat)
-	    {
-		y_src = mod (y_src, pSrc->pDrawable->height);
-		if (h_this > pSrc->pDrawable->height - y_src)
-		    h_this = pSrc->pDrawable->height - y_src;
-	    }
-	    while (w)
-	    {
-		w_this = w;
-		if (maskRepeat)
-		{
-		    x_msk = mod (x_msk, pMask->pDrawable->width);
-		    if (w_this > pMask->pDrawable->width - x_msk)
-			w_this = pMask->pDrawable->width - x_msk;
-		}
-		if (srcRepeat)
-		{
-		    x_src = mod (x_src, pSrc->pDrawable->width);
-		    if (w_this > pSrc->pDrawable->width - x_src)
-			w_this = pSrc->pDrawable->width - x_src;
-		}
-		(*func) (op, pSrc, pMask, pDst,
-			 x_src, y_src, x_msk, y_msk, x_dst, y_dst,
-			 w_this, h_this);
-		w -= w_this;
-		x_src += w_this;
-		x_msk += w_this;
-		x_dst += w_this;
-	    }
-	    h -= h_this;
-	    y_src += h_this;
-	    y_msk += h_this;
-	    y_dst += h_this;
-	}
-	pbox++;
+      fbComposite (op, pSrc, pMask, pDst,
+		   xSrc, ySrc, xMask, yMask, xDst, yDst, width, height);
     }
-    REGION_UNINIT (pDst->pDrawable->pScreen, &region);
 
-    // Reset destination depth/format to its true value
-    pDst->pDrawable->depth = dstDepth;
-    pDst->format = oldFormat;
+  pDst->pDrawable->depth = oldDepth;
+  pDst->format = oldFormat;
 }
 
 #endif /* RENDER */
commit fd6a04e530e89a085662ab91c60a232d02d6a8a3
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Nov 2 02:59:29 2007 -0700

    Fix for focus issue:
    <rdar://problem/5289578> X11 menu bar uncoupled from X11 application's windows
    Credit to William Mortensen for submitting the first community patch!

diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index fe18214..ccdc072 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -360,10 +360,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 
 - (void) set_front_process:unused
 {
-    [NSApp activateIgnoringOtherApps:YES];
-	
-    if ([self modalWindow] == nil)
-		[self activateX:YES];
+    QuartzMessageServerThread(kXDarwinBringAllToFront, 0);
 }
 
 - (void) set_can_quit:(NSNumber *)state
diff --git a/hw/darwin/darwin.h b/hw/darwin/darwin.h
index 48a2224..93ad3ab 100644
--- a/hw/darwin/darwin.h
+++ b/hw/darwin/darwin.h
@@ -137,6 +137,7 @@ enum {
     kXDarwinQuit,             // kill the X server and release the display
     kXDarwinReadPasteboard,   // copy Mac OS X pasteboard into X cut buffer
     kXDarwinWritePasteboard,  // copy X cut buffer onto Mac OS X pasteboard
+    kXDarwinBringAllToFront,  // bring all X windows to front
     /*
      * AppleWM events
      */
diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 422bd17..8670e57 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -395,6 +395,10 @@ void DarwinModeProcessEvent(
             QuartzUpdateScreens();
             break;
 
+        case kXDarwinBringAllToFront:
+	    RootlessOrderAllWindows();
+            break;
+
         case kXDarwinWindowState:
         case kXDarwinWindowMoved:
             // FIXME: Not implemented yet
diff --git a/miext/rootless/rootless.h b/miext/rootless/rootless.h
index f83defe..d9fdb6a 100644
--- a/miext/rootless/rootless.h
+++ b/miext/rootless/rootless.h
@@ -432,4 +432,8 @@ void RootlessUpdateScreenPixmap(ScreenPtr pScreen);
  */
 void RootlessRepositionWindows(ScreenPtr pScreen);
 
+/*
+ * Bring all windows to the front of the Aqua stack
+ */
+void RootlessOrderAllWindows (void);
 #endif /* _ROOTLESS_H */
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index 30b7daa..1e06d2c 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -1468,3 +1468,29 @@ RootlessChangeBorderWidth(WindowPtr pWin, unsigned int width)
 
     RL_DEBUG_MSG("change border width end\n");
 }
+
+/*
+ * RootlessOrderAllWindows
+ * Brings all X11 windows to the top of the window stack
+ * (i.e in front of Aqua windows) -- called when X11.app is given focus
+ */
+void
+RootlessOrderAllWindows (void)
+{
+    int i;
+    WindowPtr pWin;
+    
+    RL_DEBUG_MSG("RootlessOrderAllWindows() ");
+    for (i = 0; i < screenInfo.numScreens; i++) {
+      if (screenInfo.screens[i] == NULL) continue;
+      pWin = WindowTable[i];
+      if (pWin == NULL) continue;
+      
+      for (pWin = pWin->firstChild; pWin != NULL; pWin = pWin->nextSib) {
+	if (!pWin->realized) continue;
+	if (RootlessEnsureFrame(pWin) == NULL) continue;
+	RootlessReorderWindow (pWin);
+      }
+    }
+    RL_DEBUG_MSG("RootlessOrderAllWindows() done");
+}
commit 375d50620938686e2e46c94a86fe38283eff1807
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Oct 31 23:51:28 2007 -0700

    bump version to 1.2a3

diff --git a/configure.ac b/configure.ac
index 0ae785c..ff756cb 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ dnl Process this file with autoconf to create configure.
 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.0, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+AC_INIT([xorg-server], 1.2a3, [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 --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index afd495b..fe18214 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -156,7 +156,7 @@ message_kit_thread (SEL selector, NSObject *arg)
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2",
+    [dict setObject:[NSString stringWithFormat:@"X11.app %@ - X.org X11R7.2 (xorg-server-1.2a3)",
 					 tem] forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
commit 0aa61293b62aeb69a93b2035d0aef8644343eed3
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Oct 31 23:46:50 2007 -0700

    Swap modifier keys for buttons 2 and 3 -- now Option-click is the middle click

diff --git a/hw/darwin/darwin.c b/hw/darwin/darwin.c
index 5500a5f..52fd170 100644
--- a/hw/darwin/darwin.c
+++ b/hw/darwin/darwin.c
@@ -96,8 +96,8 @@ int                     darwinSyncKeymap = FALSE;
 int                     darwinSwapAltMeta = FALSE;
 
 // modifier masks for faking mouse buttons
-int                     darwinFakeMouse2Mask = NX_COMMANDMASK;
-int                     darwinFakeMouse3Mask = NX_ALTERNATEMASK;
+int                     darwinFakeMouse2Mask = NX_ALTERNATEMASK;
+int                     darwinFakeMouse3Mask = NX_COMMANDMASK;
 
 // devices
 DeviceIntPtr            darwinPointer = NULL;
commit 374eb38063a1b0653326cbdb2be9459229ad0263
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Oct 31 23:45:58 2007 -0700

    default for is_uchr should be 1, not 0

diff --git a/hw/darwin/quartz/quartzKeyboard.c b/hw/darwin/quartz/quartzKeyboard.c
index 3ecee3a..60f73e5 100644
--- a/hw/darwin/quartz/quartzKeyboard.c
+++ b/hw/darwin/quartz/quartzKeyboard.c
@@ -220,7 +220,7 @@ DarwinModeReadSystemKeymap (darwinKeyboardInfo *info)
     const void *chr_data = NULL;
     int num_keycodes = NUM_KEYCODES;
     UInt32 keyboard_type = 0;
-    int is_uchr = 0, i, j;
+    int is_uchr = 1, i, j;
     OSStatus err;
     KeySym *k;
 
commit 947fdd9fe8d51c4f3bb1eadf4357748ffa3946fc
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Wed Oct 31 16:19:46 2007 -0700

    fixed an uninitialized variable, which caused keyboard breakage on x86
    when building with optimization enabled.

diff --git a/hw/darwin/quartz/quartzKeyboard.c b/hw/darwin/quartz/quartzKeyboard.c
index f9c5963..3ecee3a 100644
--- a/hw/darwin/quartz/quartzKeyboard.c
+++ b/hw/darwin/quartz/quartzKeyboard.c
@@ -220,7 +220,7 @@ DarwinModeReadSystemKeymap (darwinKeyboardInfo *info)
     const void *chr_data = NULL;
     int num_keycodes = NUM_KEYCODES;
     UInt32 keyboard_type = 0;
-    int is_uchr, i, j;
+    int is_uchr = 0, i, j;
     OSStatus err;
     KeySym *k;
 
commit 966d329b144a36f1998f13351f5aa0daff028bd7
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Wed Oct 31 16:17:06 2007 -0700

    add -DROOTLESS_WORKAROUND to CFLAGS

diff --git a/configure.ac b/configure.ac
index af62b5e..0ae785c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1649,7 +1649,7 @@ return 0;}
 	       AC_SUBST([DARWIN_LIBS])
                AC_CHECK_LIB([Xplugin],[xp_init],[:])
                AC_SUBST([APPLE_APPLICATIONS_DIR])
-               CFLAGS="${CFLAGS} -D__DARWIN__ -DDARWIN_WITH_QUARTZ"
+               CFLAGS="${CFLAGS} -D__DARWIN__ -DDARWIN_WITH_QUARTZ -DROOTLESS_WORKAROUND"
                PLIST_VERSION_STRING=$PACKAGE_VERSION
                AC_SUBST([PLIST_VERSION_STRING])
                PLIST_VENDOR_WEB=$VENDOR_WEB
commit ab304446f7e42f59f670b3dd0d53a2f42ded44a0
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Oct 31 04:09:32 2007 -0700

    fixed bug that prevented customized Applications menu items
    with arguments from working

diff --git a/hw/darwin/apple/X11Controller.m b/hw/darwin/apple/X11Controller.m
index cc039b1..a6a75d0 100644
--- a/hw/darwin/apple/X11Controller.m
+++ b/hw/darwin/apple/X11Controller.m
@@ -296,15 +296,17 @@
 - (void) launch_client:(NSString *)filename
 {
   const char *command = [filename UTF8String];
-  const char *argv[5];
+  const char *argv[7];
   int child1, child2 = 0;
   int status;
 	
   argv[0] = "/usr/bin/login";
   argv[1] = "-fp";
   argv[2] = getlogin();
-  argv[3] = command;
-  argv[4] = NULL;
+  argv[3] = "/bin/sh";
+  argv[4] = "-c";
+  argv[5] = command;
+  argv[6] = NULL;
     
   /* Do the fork-twice trick to avoid having to reap zombies */
     
commit cf51502a81a56f418e2e086afb68192e619142ed
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Oct 31 04:08:06 2007 -0700

    fix incorrectly formatted .xinitrc warning

diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index a4adc05..afd495b 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -895,12 +895,11 @@ 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)
commit 2b189a99330eb465fa0d17020fb1db1e38829151
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Oct 31 03:39:47 2007 -0700

    Trap Deactivate messages and release modifiers to avoid "stuck shift lock" (etc) bugs

diff --git a/hw/darwin/darwinEvents.c b/hw/darwin/darwinEvents.c
index fc79da8..6293d6b 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -143,6 +143,16 @@ static void DarwinUpdateModifiers(
     }
 }
 
+/*
+ * DarwinReleaseModifiers
+ * This hacky function releases all modifier keys.  It should be called when X11.app
+ * is deactivated (kXDarwinDeactivate) to prevent modifiers from getting stuck if they
+ * are held down during a "context" switch -- otherwise, we would miss the KeyUp.
+ */
+static void DarwinReleaseModifiers(void) {
+	xEvent e;
+	DarwinUpdateModifiers(&e, KeyRelease, COMMAND_MASK(-1) | CONTROL_MASK(-1) | ALTERNATE_MASK(-1) | SHIFT_MASK(-1));
+}
 
 /*
  * DarwinSimulateMouseClick
@@ -467,6 +477,9 @@ void ProcessInputEvents(void)
                 break;
             }
 
+			case kXDarwinDeactivate:
+				DarwinReleaseModifiers();
+				// fall through
             default:
                 // Check for mode specific event
                 DarwinModeProcessEvent(&xe);
commit 0d5dd5dffa4c5ce3f54dfe53720a39d524dc8e37
Author: Ben Byer <bbyer at bbyer.local>
Date:   Wed Oct 31 03:22:18 2007 -0700

    Workaround for a bug where the holding down Command to make a "fake"
    button 2 click would actually result in a Command-2 chord.
    (I.e. it wasn't releasing Command before clicking the fake button.)

diff --git a/hw/darwin/darwinEvents.c b/hw/darwin/darwinEvents.c
index 6b4f727..fc79da8 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -162,6 +162,9 @@ static void DarwinSimulateMouseClick(
     int modifierMask)   // modifiers used for the fake click
 {
     // first fool X into forgetting about the keys
+	// for some reason, it's not enough to tell X we released the Command key -- 
+	// it has to be the *left* Command key.
+	if (modifierMask & NX_COMMANDMASK) modifierMask |=NX_DEVICELCMDKEYMASK ;
     DarwinUpdateModifiers(xe, KeyRelease, modifierMask);
 
     // push the mouse button
commit 13dd8544319b88e845672d566e552454ebe0c31c
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Tue Oct 30 20:00:21 2007 -0700

    DIX Fix:  QueryFontReply packets can be too big to be allocated on the stack

diff --git a/dix/dispatch.c b/dix/dispatch.c
index 0579540..bd9136f 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -1366,7 +1366,7 @@ ProcQueryFont(register ClientPtr client)
 	rlength = sizeof(xQueryFontReply) +
 	             FONTINFONPROPS(FONTCHARSET(pFont)) * sizeof(xFontProp)  +
 		     nprotoxcistructs * sizeof(xCharInfo);
-	reply = (xQueryFontReply *)ALLOCATE_LOCAL(rlength);
+	reply = (xQueryFontReply *)xalloc(rlength);
 	if(!reply)
 	{
 	    return(BadAlloc);
@@ -1378,7 +1378,7 @@ ProcQueryFont(register ClientPtr client)
 	QueryFont( pFont, reply, nprotoxcistructs);
 
         WriteReplyToClient(client, rlength, reply);
-	DEALLOCATE_LOCAL(reply);
+	xfree(reply);
 	return(client->noClientException);
     }
 }
@@ -2203,7 +2203,7 @@ DoGetImage(register ClientPtr client, int format, Drawable drawable,
 		length += widthBytesLine;
 	    }
 	}
-	if(!(pBuf = (char *) ALLOCATE_LOCAL(length)))
+	if(!(pBuf = (char *)xalloc(length)))
 	    return (BadAlloc);
 	WriteReplyToClient(client, sizeof (xGetImageReply), &xgi);
     }
@@ -2312,7 +2312,7 @@ DoGetImage(register ClientPtr client, int format, Drawable drawable,
 	REGION_DESTROY(pDraw->pScreen, pVisibleRegion);
 #endif
     if (!im_return)
-	DEALLOCATE_LOCAL(pBuf);
+	xfree(pBuf);
     return (client->noClientException);
 }
 
commit a221730d23626722e9f5a2a640e141169b97157c
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Tue Oct 30 19:05:02 2007 -0700

    Enable PseudoramiX extension by default, like on the old server

diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index ac555ec..422bd17 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -63,7 +63,7 @@ int                     quartzServerVisible = TRUE;
 int                     quartzServerQuitting = FALSE;
 int                     quartzScreenIndex = 0;
 int                     aquaMenuBarHeight = 0;
-int                     noPseudoramiXExtension = TRUE;
+int                     noPseudoramiXExtension = FALSE;
 QuartzModeProcsPtr      quartzProcs = NULL;
 const char             *quartzOpenGLBundle = NULL;
 
commit 0c7acd113e3c6c31ff1783f502f3bce1aa45c0ff
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Oct 29 18:11:10 2007 -0700

    make dist fixes

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 9222f57..bfde6f6 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -314,4 +314,16 @@ EXTRA_DIST = \
 	darwinKeyboard.c \
 	darwinKeyboard.h \
 	darwinXinput.c \
+	apple/X11Application.h \
+	apple/X11Controller.h \
+	apple/Info.plist \
+	apple/X11.icns \
+	apple/Xquartz.man \
+	apple/bundle-main.c \
+	apple/English.lproj/InfoPlist.strings \
+	apple/English.lproj/Localizable.strings \
+	apple/English.lproj/main.nib/classes.nib \
+	apple/English.lproj/main.nib/info.nib \
+	apple/English.lproj/main.nib/keyedobjects.nib \
+	apple/X11.xcodeproj/project.pbxproj \
 	XDarwin.man
diff --git a/hw/darwin/bundle/Makefile.am b/hw/darwin/bundle/Makefile.am
index dee34fd..f02be74 100644
--- a/hw/darwin/bundle/Makefile.am
+++ b/hw/darwin/bundle/Makefile.am
@@ -35,4 +35,5 @@ CLEANFILES = startXClients
 
 EXTRA_DIST = \
 	XDarwin.icns \
+	startXClients.cpp \
 	Info.plist
diff --git a/hw/darwin/quartz/xpr/Makefile.am b/hw/darwin/quartz/xpr/Makefile.am
index 980c7a4..7ebcba7 100644
--- a/hw/darwin/quartz/xpr/Makefile.am
+++ b/hw/darwin/quartz/xpr/Makefile.am
@@ -22,6 +22,8 @@ xprbundledir = @APPLE_APPLICATIONS_DIR@/Resources/xpr.bundle/Contents/MacOS
 EXTRA_DIST = \
 	dri.h \
 	dristruct.h \
+	appledri.h \
+	appledristr.h \
 	x-hash.h \
 	x-hook.h \
 	x-list.h \
diff --git a/hw/darwin/utils/Makefile.am b/hw/darwin/utils/Makefile.am
index 92bf151..76cb793 100644
--- a/hw/darwin/utils/Makefile.am
+++ b/hw/darwin/utils/Makefile.am
@@ -8,5 +8,6 @@ man1_MANS = dumpkeymap.man
 
 EXTRA_DIST = \
 	     README.txt \
+	     event_status_driver.h \
 	     dumpkeymap.man
 
commit 2db9600f6a4f3fa8504766e546cad6fab3bf05c9
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Oct 29 16:18:48 2007 -0700

    Added patch fix yellow-cursor problem which appears on some Intel Macs

diff --git a/hw/darwin/quartz/xpr/xprCursor.c b/hw/darwin/quartz/xpr/xprCursor.c
index 570ef0b..02260bd 100644
--- a/hw/darwin/quartz/xpr/xprCursor.c
+++ b/hw/darwin/quartz/xpr/xprCursor.c
@@ -83,8 +83,17 @@ load_cursor(CursorPtr src, int screen)
 #ifdef ARGB_CURSOR
     if (src->bits->argb != NULL)
     {
-        rowbytes = src->bits->width * sizeof(CARD32);
+#if BITMAP_BIT_ORDER == MSBFirst
+        rowbytes = src->bits->width * sizeof (CARD32);
         data = (uint32_t *) src->bits->argb;
+#else
+        const uint32_t *be_data=(uint32_t *) src->bits->argb;
+        unsigned i;
+        rowbytes = src->bits->width * sizeof (CARD32);
+        data=alloca (rowbytes * src->bits->height);
+        for(i=0;i<(src->bits->width*src->bits->height);i++)
+            data[i]=ntohl(be_data[i]);
+#endif
     }
     else
 #endif
commit fe7d2be313288ff2dc61ec53519da066eff1a0b6
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Mon Oct 29 16:15:22 2007 -0700

    Some autoconf hacks to make 'make dist' work correctly

diff --git a/configure.ac b/configure.ac
index 33f1bb2..af62b5e 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1960,7 +1960,6 @@ hw/xfree86/os-support/misc/Makefile
 hw/xfree86/os-support/linux/Makefile
 hw/xfree86/os-support/lynxos/Makefile
 hw/xfree86/os-support/sco/Makefile
-hw/xfree86/os-support/solaris/Makefile
 hw/xfree86/os-support/sysv/Makefile
 hw/xfree86/os-support/usl/Makefile
 hw/xfree86/parser/Makefile
diff --git a/hw/xfree86/os-support/Makefile.am b/hw/xfree86/os-support/Makefile.am
index 6cd9bb1..f40a662 100644
--- a/hw/xfree86/os-support/Makefile.am
+++ b/hw/xfree86/os-support/Makefile.am
@@ -1,5 +1,5 @@
 SUBDIRS = bus @XORG_OS_SUBDIR@ misc
-DIST_SUBDIRS = bsd bus misc linux lynxos solaris sysv sco usl hurd
+DIST_SUBDIRS = bsd bus misc linux lynxos sysv sco usl hurd
 
 sdk_HEADERS = xf86_OSproc.h xf86_OSlib.h xf86_ansic.h xf86_libc.h \
               assyntax.h xf86OSKbd.h xf86OSmouse.h
commit f86d2ef33fbd0aa23ac677128bd09ae1d743b97f
Author: Ben Byer <bbyer at bbyer.local>
Date:   Mon Oct 29 00:07:29 2007 -0700

    finished committing downstream changes

diff --git a/GL/Makefile.am b/GL/Makefile.am
index b9337ba..4e8337a 100644
--- a/GL/Makefile.am
+++ b/GL/Makefile.am
@@ -1,16 +1,9 @@
-SUBDIRS = glx mesa
+SUBDIRS = glx mesa apple
 
-# 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
 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/configure.ac b/configure.ac
index c7e099d..33f1bb2 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1649,7 +1649,7 @@ return 0;}
 	       AC_SUBST([DARWIN_LIBS])
                AC_CHECK_LIB([Xplugin],[xp_init],[:])
                AC_SUBST([APPLE_APPLICATIONS_DIR])
-               CFLAGS="${CFLAGS} -D__DARWIN__"
+               CFLAGS="${CFLAGS} -D__DARWIN__ -DDARWIN_WITH_QUARTZ"
                PLIST_VERSION_STRING=$PACKAGE_VERSION
                AC_SUBST([PLIST_VERSION_STRING])
                PLIST_VENDOR_WEB=$VENDOR_WEB
diff --git a/dix/dixfonts.c b/dix/dixfonts.c
index f10011e..e085bd0 100644
--- a/dix/dixfonts.c
+++ b/dix/dixfonts.c
@@ -1632,9 +1632,9 @@ FreeFontPath(FontPathElementPtr *list, int n, Bool force)
 		    found++;
 	    }
 	    if (list[i]->refcount != found) {
-		ErrorF("FreeFontPath: FPE \"%.*s\" refcount is %d, should be %d; fixing.\n",
+	      /*		ErrorF("FreeFontPath: FPE \"%.*s\" refcount is %d, should be %d; fixing.\n",
 		       list[i]->name_length, list[i]->name,
-		       list[i]->refcount, found);
+		       list[i]->refcount, found); */
 		list[i]->refcount = found; /* ensure it will get freed */
 	    }
 	}
diff --git a/hw/Makefile.am b/hw/Makefile.am
index d00d6fb..a1918ab 100644
--- a/hw/Makefile.am
+++ b/hw/Makefile.am
@@ -1,11 +1,3 @@
-if DMX
-DMX_SUBDIRS = dmx
-endif
-
-if XORG
-XORG_SUBDIRS = xfree86
-endif
-
 if XVFB
 XVFB_SUBDIRS = vfb
 endif
@@ -30,7 +22,7 @@ if XPRINT
 XPRINT_SUBDIRS = xprint
 endif
 
-# need to add darwin support here
+DARWIN_SUBDIRS = darwin
 
 SUBDIRS =			\
 	$(XORG_SUBDIRS)		\
@@ -40,6 +32,7 @@ SUBDIRS =			\
 	$(XNEST_SUBDIRS)	\
 	$(DMX_SUBDIRS)          \
         $(KDRIVE_SUBDIRS)	\
+        $(DARWIN_SUBDIRS)	\
 	$(XPRINT_SUBDIRS)
 
 DIST_SUBDIRS = dmx xfree86 vfb xnest xwin darwin kdrive xgl xprint
diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index aa4fbee..9222f57 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -1,6 +1,7 @@
 noinst_LIBRARIES = libdarwinShared.a
 libdarwin_XINPUT_SRCS = darwinXinput.c
 
+# -O2 inexplicably causes quartzKeyboard.o to break?!
 AM_CFLAGS = @XORG_CFLAGS@
 INCLUDES = @XORG_INCS@ -I../../miext/rootless
 
@@ -79,7 +80,7 @@ XDarwin_LDADD = \
 		$(top_builddir)/miext/rootless/librootless.la \
 		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
 		$(top_builddir)/miext/rootless/accel/librlAccel.la \
-		$(XSERVER_LIBS)
+		$(XSERVER_LIBS) -lXplugin
 
 Xquartz_LDADD = \
 		$(top_builddir)/dix/dixfonts.lo \
@@ -105,7 +106,7 @@ Xquartz_LDADD = \
 		$(top_builddir)/miext/rootless/librootless.la \
 		$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
 		$(top_builddir)/miext/rootless/accel/librlAccel.la \
-		$(XSERVER_LIBS)
+		$(DARWIN_LIBS) $(XSERVER_LIBS) -lXplugin
 
 XDarwin_LDFLAGS =  \
                  -XCClinker -Objc \
diff --git a/hw/darwin/quartz/quartzKeyboard.c b/hw/darwin/quartz/quartzKeyboard.c
index b330793..f9c5963 100644
--- a/hw/darwin/quartz/quartzKeyboard.c
+++ b/hw/darwin/quartz/quartzKeyboard.c
@@ -166,7 +166,8 @@ DarwinModeSystemKeymapSeed (void)
     return seed;
 }
 
-static inline UniChar
+//static inline UniChar
+UniChar
 macroman2ucs (unsigned char c)
 {
     /* Precalculated table mapping MacRoman-128 to Unicode. Generated
commit b3dc1483f7e52af9a88b8ac6fe16cd79bfa2726b
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sun Oct 28 17:22:16 2007 -0700

    more patches, autoconf fixes...

diff --git a/GL/glx/indirect_dispatch_swap.c b/GL/glx/indirect_dispatch_swap.c
index 9c58ef1..2adacb3 100644
--- a/GL/glx/indirect_dispatch_swap.c
+++ b/GL/glx/indirect_dispatch_swap.c
@@ -35,6 +35,11 @@
 #define bswap_16 __swap16
 #define bswap_32 __swap32
 #define bswap_64 __swap64
+#elif defined(__APPLE__)
+#include <libkern/OSByteOrder.h>
+#define bswap_16 OSSwapInt16
+#define bswap_32 OSSwapInt32
+#define bswap_64 OSSwapInt64
 #else
 #include <sys/endian.h>
 #define bswap_16 bswap16
diff --git a/GL/glx/indirect_program.c b/GL/glx/indirect_program.c
index d0fd3d1..94c207e 100644
--- a/GL/glx/indirect_program.c
+++ b/GL/glx/indirect_program.c
@@ -53,6 +53,12 @@
 #define bswap_16 __swap16
 #define bswap_32 __swap32
 #define bswap_64 __swap64
+ #define bswap_64 __swap64
+#elif defined(__APPLE__)
+#include <libkern/OSByteOrder.h>
+#define bswap_16 OSSwapInt16
+#define bswap_32 OSSwapInt32
+#define bswap_64 OSSwapInt64
 #else
 #include <sys/endian.h>
 #define bswap_16 bswap16
diff --git a/GL/glx/indirect_texture_compression.c b/GL/glx/indirect_texture_compression.c
index 0c42ea0..d1881e9 100644
--- a/GL/glx/indirect_texture_compression.c
+++ b/GL/glx/indirect_texture_compression.c
@@ -46,6 +46,11 @@
 #define bswap_16 __swap16
 #define bswap_32 __swap32
 #define bswap_64 __swap64
+#elif defined(__APPLE__)
+#include <libkern/OSByteOrder.h>
+#define bswap_16 OSSwapInt16
+#define bswap_32 OSSwapInt32
+#define bswap_64 OSSwapInt64
 #else
 #include <sys/endian.h>
 #define bswap_16 bswap16
diff --git a/GL/glx/indirect_util.c b/GL/glx/indirect_util.c
index 09b7ab8..efc84c7 100644
--- a/GL/glx/indirect_util.c
+++ b/GL/glx/indirect_util.c
@@ -35,6 +35,11 @@
 #define bswap_16 __swap16
 #define bswap_32 __swap32
 #define bswap_64 __swap64
+#elif defined(__APPLE__)
+#include <libkern/OSByteOrder.h>
+#define bswap_16 OSSwapInt16
+#define bswap_32 OSSwapInt32
+#define bswap_64 OSSwapInt64
 #else
 #include <sys/endian.h>
 #define bswap_16 bswap16
diff --git a/GL/glx/swap_interval.c b/GL/glx/swap_interval.c
index bcc1c47..55bb07b 100644
--- a/GL/glx/swap_interval.c
+++ b/GL/glx/swap_interval.c
@@ -47,6 +47,11 @@
 #define bswap_16 __swap16
 #define bswap_32 __swap32
 #define bswap_64 __swap64
+#elif defined(__APPLE__)
+#include <libkern/OSByteOrder.h>
+#define bswap_16 OSSwapInt16
+#define bswap_32 OSSwapInt32
+#define bswap_64 OSSwapInt64
 #else
 #include <sys/endian.h>
 #define bswap_16 bswap16
diff --git a/configure.ac b/configure.ac
index 61fdc4c..c7e099d 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,24 +1,27 @@
-dnl $Id$
+dnl Copyright © 2003-2007 Keith Packard, Daniel Stone
 dnl
-dnl Copyright © 2003-2005 Keith Packard, Daniel Stone
+dnl Permission is hereby granted, free of charge, to any person obtaining a
+dnl copy of this software and associated documentation files (the "Software"),
+dnl to deal in the Software without restriction, including without limitation
+dnl the rights to use, copy, modify, merge, publish, distribute, sublicense,
+dnl and/or sell copies of the Software, and to permit persons to whom the
+dnl Software is furnished to do so, subject to the following conditions:
 dnl
-dnl Permission to use, copy, modify, distribute, and sell this software and its
-dnl documentation for any purpose is hereby granted without fee, provided that
-dnl the above copyright notice appear in all copies and that both that
-dnl copyright notice and this permission notice appear in supporting
-dnl documentation, and that the names of Keith Packard and Daniel Stone not be
-dnl used in advertising or publicity pertaining to distribution of the software
-dnl without specific, written prior permission.  Keith Packard and Daniel Stone
-dnl make no representations about the suitability of this software for any
-dnl purpose.  It is provided "as is" without express or implied warranty.
+dnl The above copyright notice and this permission notice (including the next
+dnl paragraph) shall be included in all copies or substantial portions of the
+dnl Software.
 dnl
-dnl KEITH PACKARD AND DANIEL STONE DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
-dnl SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
-dnl IN NO EVENT SHALL KEITH PACKARD OR DANIEL STONE BE LIABLE FOR ANY SPECIAL,
-dnl INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-dnl LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-dnl OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-dnl PERFORMANCE OF THIS SOFTWARE.
+dnl THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+dnl IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+dnl FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+dnl THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+dnl LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+dnl FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+dnl DEALINGS IN THE SOFTWARE.
+dnl
+dnl Authors: Keith Packard <keithp at keithp.com>
+dnl          Daniel Stone <daniel at fooishbar.org>
+dnl          an unwitting cast of miscellaneous others
 dnl
 dnl Process this file with autoconf to create configure.
 
@@ -67,6 +70,8 @@ AC_HEADER_DIRENT
 AC_HEADER_STDC
 AC_CHECK_HEADERS([fcntl.h stdlib.h string.h unistd.h])
 
+AC_CHECK_PROG(HAVE_LAUNCHD, [launchd], [yes], [])
+
 dnl Checks for typedefs, structures, and compiler characteristics.
 AC_C_CONST
 AC_C_BIGENDIAN([ENDIAN="X_BIG_ENDIAN"], [ENDIAN="X_LITTLE_ENDIAN"])
@@ -78,6 +83,67 @@ fi
 
 AC_TYPE_PID_T
 
+# Checks for headers/macros for byte swapping
+# Known variants:
+#	<byteswap.h> bswap_16, bswap_32, bswap_64  (glibc)
+#	<sys/endian.h> __swap16, __swap32, __swap64 (OpenBSD)
+#	<sys/endian.h> bswap16, bswap32, bswap64 (other BSD's)
+#	and a fallback to local macros if none of the above are found
+
+# if <byteswap.h> is found, assume it's the correct version
+AC_CHECK_HEADERS([byteswap.h])
+
+# if <sys/endian.h> is found, have to check which version
+AC_CHECK_HEADER([sys/endian.h], [HAVE_SYS_ENDIAN_H="yes"], [HAVE_SYS_ENDIAN_H="no"])
+
+if test "x$HAVE_SYS_ENDIAN_H" = "xyes" ; then
+	AC_MSG_CHECKING([for __swap16 variant of <sys/endian.h> byteswapping macros])
+	AC_LINK_IFELSE([AC_LANG_PROGRAM([
+#include <sys/endian.h>
+ ], [
+int a = 1, b;
+b = __swap16(a);
+ ])
+], [SYS_ENDIAN__SWAP='yes'], [SYS_ENDIAN__SWAP='no'])
+	AC_MSG_RESULT([$SYS_ENDIAN__SWAP])
+
+	AC_MSG_CHECKING([for bswap16 variant of <sys/endian.h> byteswapping macros])
+	AC_LINK_IFELSE([AC_LANG_PROGRAM([
+#include <sys/endian.h>
+ ], [
+int a = 1, b;
+b = bswap16(a);
+ ])
+], [SYS_ENDIAN_BSWAP='yes'], [SYS_ENDIAN_BSWAP='no'])
+	AC_MSG_RESULT([$SYS_ENDIAN_BSWAP])
+
+    	if test "$SYS_ENDIAN_BSWAP" = "yes" ; then
+		USE_SYS_ENDIAN_H=yes
+		BSWAP=bswap
+	else	
+	    	if test "$SYS_ENDIAN__SWAP" = "yes" ; then
+			USE_SYS_ENDIAN_H=yes
+			BSWAP=__swap
+		else
+			USE_SYS_ENDIAN_H=no
+		fi
+	fi
+
+	if test "$USE_SYS_ENDIAN_H" = "yes" ; then
+	    AC_DEFINE([USE_SYS_ENDIAN_H], 1, 
+		[Define to use byteswap macros from <sys/endian.h>])
+	    AC_DEFINE_UNQUOTED([bswap_16], ${BSWAP}16, 
+			[Define to 16-bit byteswap macro])
+	    AC_DEFINE_UNQUOTED([bswap_32], ${BSWAP}32, 
+			[Define to 32-bit byteswap macro])
+	    AC_DEFINE_UNQUOTED([bswap_64], ${BSWAP}64, 
+			[Define to 64-bit byteswap macro])
+	fi
+fi
+
+AC_CHECK_FUNC([dlopen], [],
+	AC_CHECK_LIB([dl], [dlopen], DLOPEN_LIBS="-ldl"))
+
 dnl Checks for library functions.
 AC_FUNC_VPRINTF
 AC_CHECK_FUNCS([geteuid getuid link memmove memset mkstemp strchr strrchr \
@@ -86,23 +152,25 @@ AC_CHECK_FUNCS([geteuid getuid link memmove memset mkstemp strchr strrchr \
 AC_FUNC_ALLOCA
 dnl Old HAS_* names used in os/*.c.
 AC_CHECK_FUNC([getdtablesize],
-	AC_DEFINE(HAS_GETDTABLESIZE, 1, [Have the `getdtablesize' function.]))
+	AC_DEFINE(HAS_GETDTABLESIZE, 1, [Have the 'getdtablesize' function.]))
 AC_CHECK_FUNC([getifaddrs],
-	AC_DEFINE(HAS_GETIFADDRS, 1, [Have the `getifaddrs' function.]))
+	AC_DEFINE(HAS_GETIFADDRS, 1, [Have the 'getifaddrs' function.]))
 AC_CHECK_FUNC([getpeereid],
-	AC_DEFINE(HAS_GETPEEREID, 1, [Have the `getpeereid' function.]))
+	AC_DEFINE(HAS_GETPEEREID, 1, [Have the 'getpeereid' function.]))
 AC_CHECK_FUNC([getpeerucred],
-	AC_DEFINE(HAS_GETPEERUCRED, 1, [Have the `getpeerucred' function.]))
+	AC_DEFINE(HAS_GETPEERUCRED, 1, [Have the 'getpeerucred' function.]))
 AC_CHECK_FUNC([strlcat], HAVE_STRLCAT=yes, HAVE_STRLCAT=no)
 AM_CONDITIONAL(NEED_STRLCAT, [test x$HAVE_STRLCAT = xno])	
+AC_CHECK_FUNC([strlcpy], AC_DEFINE(HAS_STRLCPY, 1, [Have the 'strlcpy' function]))
 
 AM_CONDITIONAL(NEED_VSNPRINTF, [test x$HAVE_VSNPRINTF = xno])
 
 dnl Check for mmap support for Xvfb
-AC_CHECK_FUNC([mmap], AC_DEFINE(HAS_MMAP, 1, [Have the `mmap' function.]))
+AC_CHECK_FUNC([mmap], AC_DEFINE(HAS_MMAP, 1, [Have the 'mmap' function.]))
 
 dnl Find the math libary
 AC_CHECK_LIB(m, sqrt)
+AC_CHECK_LIB(m, cbrt, AC_DEFINE(HAVE_CBRT, 1, [Have the 'cbrt' function]))
 
 AC_CHECK_HEADERS([ndbm.h dbm.h rpcsvc/dbm.h])
 
@@ -198,9 +266,10 @@ case $host_cpu in
 	ARM_VIDEO=yes
 	;;
   i*86)
-	use_x86_asm="no"
+	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)
@@ -223,9 +292,10 @@ case $host_cpu in
 	BSD_ARCH_SOURCES="sparc64_video.c ioperm_noop.c"
 	;;
   x86_64*|amd64*)
-  	use_x86_asm="no"
+  	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
@@ -407,7 +477,6 @@ AC_ARG_ENABLE(xres,           AS_HELP_STRING([--disable-xres], [Build XRes exten
 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: enabled)]), [DGA=$enableval], [DGA=yes])
 AC_ARG_ENABLE(screensaver,    AS_HELP_STRING([--disable-screensaver], [Build ScreenSaver extension (default: enabled)]), [SCREENSAVER=$enableval], [SCREENSAVER=yes])
@@ -418,9 +487,9 @@ AC_ARG_ENABLE(aiglx,          AS_HELP_STRING([--enable-aiglx], [Build accelerate
 AC_ARG_ENABLE(glx-tls,        AS_HELP_STRING([--enable-glx-tls], [Build GLX with TLS support (default: disabled)]), [GLX_USE_TLS=$enableval], [GLX_USE_TLS=no])
 AC_ARG_ENABLE(dri,            AS_HELP_STRING([--enable-dri], [Build DRI extension (default: auto)]), [DRI=$enableval])
 AC_ARG_ENABLE(xinerama,	      AS_HELP_STRING([--disable-xinerama], [Build Xinerama extension (default: enabled)]), [XINERAMA=$enableval], [XINERAMA=yes])
-AC_ARG_ENABLE(xf86vidmode,    AS_HELP_STRING([--disable-xf86vidmode], [Build XF86VidMode extension (default: enabled)]), [XF86VIDMODE=$enableval], [XF86VIDMODE=yes])
-AC_ARG_ENABLE(xf86misc,       AS_HELP_STRING([--disable-xf86misc], [Build XF86Misc extension (default: enabled)]), [XF86MISC=$enableval], [XF86MISC=yes])
-AC_ARG_ENABLE(xace,     AS_HELP_STRING([--disable-xace], [Build X-ACE extension (default: enabled)]), [XACE=$enableval], [XACE=yes])
+AC_ARG_ENABLE(xf86vidmode,    AS_HELP_STRING([--disable-xf86vidmode], [Build XF86VidMode extension (default: auto)]), [XF86VIDMODE=$enableval], [XF86VIDMODE=auto])
+AC_ARG_ENABLE(xf86misc,       AS_HELP_STRING([--disable-xf86misc], [Build XF86Misc extension (default: auto)]), [XF86MISC=$enableval], [XF86MISC=auto])
+AC_ARG_ENABLE(xace,           AS_HELP_STRING([--disable-xace], [Build X-ACE extension (default: enabled)]), [XACE=$enableval], [XACE=yes])
 AC_ARG_ENABLE(xcsecurity,     AS_HELP_STRING([--disable-xcsecurity], [Build Security extension (default: enabled)]), [XCSECURITY=$enableval], [XCSECURITY=$XACE])
 AC_ARG_ENABLE(appgroup,       AS_HELP_STRING([--disable-appgroup], [Build XC-APPGROUP extension (default: enabled)]), [APPGROUP=$enableval], [APPGROUP=$XCSECURITY])
 AC_ARG_ENABLE(xcalibrate,     AS_HELP_STRING([--enable-xcalibrate], [Build XCalibrate extension (default: disabled)]), [XCALIBRATE=$enableval], [XCALIBRATE=no])
@@ -438,11 +507,15 @@ AC_ARG_ENABLE(xfree86-utils,     AS_HELP_STRING([--enable-xfree86-utils], [Build
 
 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(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(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: no)]), [XVFB=$enableval], [XVFB=no])
+AC_ARG_ENABLE(xnest,   	      AS_HELP_STRING([--enable-xnest], [Build Xnest server (default: no)]), [XNEST=$enableval], [XNEST=no])
+AC_ARG_ENABLE(xdarwin, 	      AS_HELP_STRING([--enable-xdarwin], [Build XDarwin server (default: auto)]), [XDARWIN=$enableval], [XDARWIN=auto])
+AC_ARG_ENABLE(xdarwinapp,     AS_HELP_STRING([--enable-xdarwinapp], [Build XDarwin.app server (default: no)]), [XDARWINAPP=$enableval], [XDARWINAPP=no])
+AC_ARG_ENABLE(xquartz,        AS_HELP_STRING([--disable-xquartz], [Build Xquartz server on Darwin (default: auto)]), [XQUARTZ=$enableval], [XQUARTZ=auto])
+AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app wrapper for Xquartz (default: no)]), [X11APP=$enableval], [X11APP=no])
 AC_ARG_ENABLE(xwin,    	      AS_HELP_STRING([--enable-xwin], [Build XWin server (default: auto)]), [XWIN=$enableval], [XWIN=auto])
-AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: auto)]), [XPRINT=$enableval], [XPRINT=auto])
+AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
 AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (default: no)]), [XGL=$enableval], [XGL=no])
 AC_ARG_ENABLE(xglx,           AS_HELP_STRING([--enable-xglx], [Build Xglx xgl module (default: no)]), [XGLX=$enableval], [XGLX=no])
 AC_ARG_ENABLE(xegl,           AS_HELP_STRING([--enable-xegl], [Build Xegl xgl module (default: no)]), [XEGL=$enableval], [XEGL=no])
@@ -1106,61 +1179,6 @@ dnl has it in libc), or if libdl is needed to get it.
 		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_DEFINE(ROOTLESS,1,[Build Rootless code])
-		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"
@@ -1335,6 +1353,40 @@ int main () {
 	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"
+		PKG_CHECK_MODULES(DGA, 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"
+		PKG_CHECK_MODULES(XF86MISC, 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"
+		PKG_CHECK_MODULES(XF86VIDMODE, 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_SYS_LIBS="$XORG_SYS_LIBS $XORG_MODULES_LIBS"
+	fi
+
 	AC_SUBST([XORG_LIBS])
 	AC_SUBST([XORG_INCS])
 	AC_SUBST([XORG_OS])
@@ -1409,26 +1461,6 @@ int main () {
 	AC_SUBST([extdir])
 	AC_SUBST([logdir])
 fi
-
-if test "x$XF86VIDMODE" = xyes; then
-	AC_DEFINE(XF86VIDMODE, 1, [Support XFree86 Video Mode extension])
-fi
-
-if test "x$XF86MISC" = xyes; then
-	AC_DEFINE(XF86MISC, 1, [Support XFree86 miscellaneous extensions])
-fi
-# 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])
-
 AM_CONDITIONAL([XORG], [test "x$XORG" = xyes])
 AM_CONDITIONAL([XORG_BUS_LINUXPCI], [test "x$xorg_bus_linuxpci" = xyes])
 AM_CONDITIONAL([XORG_BUS_FREEBSDPCI], [test "x$xorg_bus_freebsdpci" = xyes])
@@ -1570,10 +1602,95 @@ AM_CONDITIONAL(XWIN_PRIMARYFB, [test "x$XWIN" = xyes && false])
 AM_CONDITIONAL(XWIN_RANDR, [test "x$XWIN" = xyes])
 AM_CONDITIONAL(XWIN_XV, [test "x$XWIN" = xyes && test "x$XV" = xyes])
 
+dnl Darwin / OS X DDX
+AC_MSG_CHECKING([whether to build XDarwin (Mac OS X) DDX])
+if test "x$XDARWIN" = xauto; then
+	case $host_os in
+		darwin*) XDARWIN="yes" ;;
+		*) XDARWIN="no" ;;
+	esac
+fi
+AC_MSG_RESULT([$XDARWIN])
+
+if test "x$XDARWIN" = xyes; then
+        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
+#	       glxAGL / glxCGL don't work yet
+#               AC_CACHE_CHECK([for AGL framework],xorg_cv_AGL_framework,[
+#               save_LDFLAGS=$LDFLAGS
+#               LDFLAGS="$LDFLAGS -framework AGL"
+#               AC_LINK_IFELSE([char aglEnable();
+#int main() {
+#aglEnable();
+#return 0;}
+#               ],[xorg_cv_AGL_framework=yes],
+#               [xorg_cv_AGL_framework=no])
+#               LDFLAGS=$save_LDFLAGS
+#               ])
+               xorg_cv_AGL_framework=no
+	       DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $GLX_LIBS $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB"
+	       AC_SUBST([DARWIN_LIBS])
+               AC_CHECK_LIB([Xplugin],[xp_init],[:])
+               AC_SUBST([APPLE_APPLICATIONS_DIR])
+               CFLAGS="${CFLAGS} -D__DARWIN__"
+               PLIST_VERSION_STRING=$PACKAGE_VERSION
+               AC_SUBST([PLIST_VERSION_STRING])
+               PLIST_VENDOR_WEB=$VENDOR_WEB
+               AC_SUBST([PLIST_VENDOR_WEB])
+               if test "x$XF86MISC" = xyes || test "x$XF86MISC" = xauto; then
+                       AC_MSG_NOTICE([Disabling XF86Misc extension])
+                       XF86MISC=no
+               fi
+               if test "x$XF86VIDMODE" = xyes || test "x$XF86VIDMODE" = xauto; then
+                       AC_MSG_NOTICE([Disabling XF86VidMode extension])
+                       XF86VIDMODE=no
+               fi
+               if test "x$XF86BIGFONT" = xyes || test "x$XF86BIGFONT" = xauto; then
+                       AC_MSG_NOTICE([Disabling XF86BigFont extension])
+                       XF86BIGFONT=no
+               fi
+               if test "x$DGA" = xyes || test "x$DGA" = xauto; then
+                       AC_MSG_NOTICE([Disabling DGA extension])
+                       DGA=no
+               fi
+fi
+# Support for objc in autotools is minimal and not documented.
+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])
+AM_CONDITIONAL(HAVE_XPLUGIN, [test "x$ac_cv_lib_Xplugin_xp_init" = xyes])
+AM_CONDITIONAL(HAVE_AGL_FRAMEWORK, [test "x$xorg_cv_AGL_framework" = xyes])
+AM_CONDITIONAL(XDARWIN, [test "x$XDARWIN" = xyes])
+AM_CONDITIONAL(XDARWINAPP, [test "x$XDARWINAPP" = xyes])
+AM_CONDITIONAL(XQUARTZ, [test "x$XQUARTZ" = xyes])
 
 dnl kdrive DDX
 
-XEYPHR_LIBS=
+XEPHYR_LIBS=
 XEPHYR_INCS=
 XSDL_LIBS=
 XSDL_INCS=
diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 54f3f33..aa4fbee 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -79,8 +79,7 @@ XDarwin_LDADD = \
 		$(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
+		$(XSERVER_LIBS)
 
 Xquartz_LDADD = \
 		$(top_builddir)/dix/dixfonts.lo \
@@ -90,6 +89,7 @@ Xquartz_LDADD = \
 		$(top_builddir)/dix/libxpstubs.la \
 		$(top_builddir)/miext/shadow/libshadow.la \
 		$(top_builddir)/fb/libfb.la \
+		$(top_builddir)/mi/libmi.la \
 		$(top_builddir)/composite/libcomposite.la \
 		$(top_builddir)/damageext/libdamageext.la \
 		$(top_builddir)/miext/damage/libdamage.la \
@@ -105,8 +105,7 @@ Xquartz_LDADD = \
 		$(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
+		$(XSERVER_LIBS)
 
 XDarwin_LDFLAGS =  \
                  -XCClinker -Objc \
@@ -258,6 +257,8 @@ xpr_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
 		-module -avoid-version -no-undefined
 xpr_la_DEPENDENCIES = XDarwinApp	
 
+
+if HAVE_AGL_FRAMEWORK
 glxCGLplugindir = $(darwinappdir)/Contents/Resources/glxCGL.bundle/Contents/MacOS
 glxCGLplugin_LTLIBRARIES =
 glxCGL_la_SOURCES =
@@ -289,6 +290,10 @@ glxAGL_la_LDFLAGS = -shrext '' \
 		-module -avoid-version -no-undefined
 glxAGL_la_DEPENDENCIES = XDarwinApp	
 
+
+
+endif
+
 man1_MANS = XDarwin.man
 
 uninstall-hook:
diff --git a/hw/darwin/apple/X11Application.m b/hw/darwin/apple/X11Application.m
index 9ae470e..a4adc05 100644
--- a/hw/darwin/apple/X11Application.m
+++ b/hw/darwin/apple/X11Application.m
@@ -43,8 +43,6 @@
 # include "micmap.h"
 #undef BOOL
 
-#include "xf86Version.h"
-
 #include <mach/mach.h>
 #include <unistd.h>
 #include <pthread.h>
diff --git a/hw/darwin/darwin.c b/hw/darwin/darwin.c
index c3b21c1..5500a5f 100644
--- a/hw/darwin/darwin.c
+++ b/hw/darwin/darwin.c
@@ -6,6 +6,7 @@
  **************************************************************/
 /*
  * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
+ * Copyright (c) 2007 Apple Inc.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -30,9 +31,7 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
+#include <dix-config.h>
 
 #include <X11/X.h>
 #include <X11/Xproto.h>
@@ -46,8 +45,6 @@
 #include "fb.h"			// fb framebuffer code
 #include "site.h"
 #include "globals.h"
-#include "xorgVersion.h"
-#include "xf86Date.h"
 #include "dix.h"
 
 #ifdef XINPUT
@@ -83,6 +80,7 @@ int                     darwinScreenIndex = 0;
 io_connect_t            darwinParamConnect = 0;
 int                     darwinEventReadFD = -1;
 int                     darwinEventWriteFD = -1;
+// int                     darwinMouseAccelChange = 1;
 int                     darwinFakeButtons = 0;
 
 // location of X11's (0,0) point in global screen coordinates
@@ -129,13 +127,21 @@ const int NUMFORMATS = sizeof(formats)/sizeof(formats[0]);
 #ifndef BUILD_DATE
 #define BUILD_DATE ""
 #endif
+#ifndef XORG_RELEASE
+#define XORG_RELEASE "?"
+#endif
+
+void DDXRingBell(int volume, int pitch, int duration) {
+  // FIXME -- make some noise, yo
+}
 
 void
-DarwinPrintBanner()
-{
+DarwinPrintBanner(void)
+{ 
+  // this should change depending on which specific server we are building
   ErrorF("X11.app starting:\n");
   ErrorF("Xquartz server based on X.org %s, built on %s\n", XORG_RELEASE, BUILD_DATE );
- }
+}
 
 
 /*
@@ -301,6 +307,29 @@ static Bool DarwinAddScreen(
  =============================================================================
 */
 
+#if 0
+/*
+ * DarwinChangePointerControl
+ *  Set mouse acceleration and thresholding
+ *  FIXME: We currently ignore the threshold in ctrl->threshold.
+ */
+static void DarwinChangePointerControl(
+    DeviceIntPtr    device,
+    PtrCtrl         *ctrl )
+{
+    kern_return_t   kr;
+    double          acceleration;
+
+    if (!darwinMouseAccelChange)
+        return;
+
+    acceleration = ctrl->num / ctrl->den;
+    kr = IOHIDSetMouseAcceleration( darwinParamConnect, acceleration );
+    if (kr != KERN_SUCCESS)
+        ErrorF( "Could not set mouse acceleration with kernel return = 0x%x.\n", kr );
+}
+#endif
+
 /*
  * DarwinMouseProc
  *  Handle the initialization, etc. of a mouse
@@ -549,8 +578,8 @@ DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo)
         for (i = 0; i < pScreenInfo->numScreens; i++) {
             dixScreenOrigins[i].x -= darwinMainScreenX;
             dixScreenOrigins[i].y -= darwinMainScreenY;
-	    /*            ErrorF("Screen %d placed at X11 coordinate (%d,%d).\n",
-			  i, dixScreenOrigins[i].x, dixScreenOrigins[i].y); */
+    /*            ErrorF("Screen %d placed at X11 coordinate (%d,%d).\n",
+		  i, dixScreenOrigins[i].x, dixScreenOrigins[i].y); */
         }
     }
 }
@@ -627,14 +656,10 @@ void OsVendorInit(void)
         if ( !tempStr ) {
             ErrorF("Could not find keymapping file %s.\n", darwinKeymapFile);
         } else {
-	  ErrorF("Using keymapping provided in %s.\n", tempStr);
+            ErrorF("Using keymapping provided in %s.\n", tempStr);
         }
         darwinKeymapFile = tempStr;
     }
-
-    if ( !darwinKeymapFile ) {
-      //        ErrorF("Reading keymap from the system.\n");
-    }
 }
 
 
@@ -832,7 +857,7 @@ void ddxUseMsg( void )
  */
 void ddxGiveUp( void )
 {
-    ErrorF( "Quitting Xquartz...\n" );
+    ErrorF( "Quitting XQuartz...\n" );
 
     DarwinModeGiveUp();
 }
@@ -855,7 +880,6 @@ void AbortDDX( void )
 }
 
 
-#ifdef DPMSExtension
 /*
  * DPMS extension stubs
  */
@@ -872,8 +896,6 @@ int DPMSGet(int *level)
 {
     return -1;
 }
-#endif
-
 
 #include "mivalidate.h" // for union _Validate used by windowstr.h
 #include "windowstr.h"  // for struct _Window
commit 6ff9f43ae2924f5648be864f5dcc6c8865f33fa1
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sat Oct 27 23:33:51 2007 -0700

    More patches from downstream

diff --git a/GL/apple/Makefile.am b/GL/apple/Makefile.am
new file mode 100644
index 0000000..4220f7f
--- /dev/null
+++ b/GL/apple/Makefile.am
@@ -0,0 +1,10 @@
+AM_CFLAGS = -I$(top_srcdir) \
+	 -I$(top_srcdir)/GL/glx \
+	 -I$(top_srcdir)/GL/include \
+	 -I$(top_srcdir)/GL/mesa/glapi \
+	 -I$(top_srcdir)/hw/darwin/quartz \
+	 -I$(top_srcdir)/hw/darwin/quartz/xpr
+
+noinst_LIBRARIES = libCGLcore.a 
+libCGLcore_a_SOURCES = indirect.c \
+		       $(top_srcdir)/hw/dmx/glxProxy/compsize.c
diff --git a/GL/apple/aglGlx.c b/GL/apple/aglGlx.c
index 900a9a9..0bc9f61 100644
--- a/GL/apple/aglGlx.c
+++ b/GL/apple/aglGlx.c
@@ -1008,6 +1008,7 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
     return TRUE;
 }
 
+Bool enable_stereo = false;
 /* based on code in i830_dri.c
    This ends calling glAquaSetVisualConfigs to set the static
    numconfigs, etc. */
@@ -1022,16 +1023,18 @@ glAquaInitVisualConfigs(void)
     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);
@@ -1040,54 +1043,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");
@@ -1095,7 +1099,6 @@ glAquaInitVisualConfigs(void)
     GlxSetVisualConfigs(lclNumConfigs, lclVisualConfigs, lclVisualPrivates);
 }
 
-
 static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
                                    void **privates)
 {
diff --git a/GL/apple/indirect.c b/GL/apple/indirect.c
index 8cba1c6..2729ab0 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:
@@ -37,14 +36,30 @@
 #endif
 
 #include "dri.h"
-#include "quartz.h"
 
-#include <CoreGraphics/CoreGraphics.h>
+#define GL_EXT_histogram 1
+#define GL_EXT_polygon_offset 1
+#define GL_SGIS_pixel_texture 1
+#define GL_SGIX_pixel_texture 1
+#define GL_EXT_multisample 1
+#define GL_SGIS_multisample 1
+#define GL_EXT_vertex_array 1
+#define GL_ARB_point_parameters 1
+#define GL_NV_vertex_array_range 1
+#define GL_MESA_resize_buffers 1
+#define GL_ARB_window_pos 1
+#define GL_EXT_cull_vertex 1
+#define GL_NV_vertex_program 1
+#define GL_APPLE_fence 1
+#define GL_IBM_multimode_draw_arrays 1
+#define GL_EXT_fragment_shader 1
+
 #include <OpenGL/OpenGL.h>
 #include <OpenGL/CGLContext.h>
 
 // X11 and X11's glx
-#include <miscstruct.h>
+#include <GL/gl.h>
+#include <GL/glxproto.h>
 #include <windowstr.h>
 #include <resource.h>
 #include <GL/glxint.h>
@@ -61,11 +76,18 @@
 #include "x-hash.h"
 #include "x-list.h"
 
+#include <dispatch.h>
+#define GLAPIENTRYP *
+typedef unsigned long long GLuint64EXT;
+typedef long long GLint64EXT;
+#include <Xplugin.h>
 #include "glcontextmodes.h"
+#include <glapi.h>
+#include <glapitable.h>
 
 // ggs: needed to call back to glx with visual configs
 extern void GlxSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs, void **configprivs);
-
+__GLXprovider * GlxGetMesaProvider (void);
 
 // Write debugging output, or not
 #ifdef GLAQUA_DEBUG
@@ -74,182 +96,163 @@ extern void GlxSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs, void *
 #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);
+GLuint __glFloorLog2(GLuint val);
+void warn_func(void * p1, char *format, ...);
 
 // some prototypes
-static Bool glAquaScreenProbe(int screen);
+static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen);
+static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLcontextModes *modes);
+
 static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
                               int *nvisualp, int *ndepthp,
                               int *rootDepthp, VisualID *defaultVisp,
                               unsigned long sizes, int bitsPerRGB);
 static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
                                    void **privates);
-static __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 glAquaResetExtension(void);
+static void __glXAquaContextDestroy(__GLXcontext *baseContext);
+static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextForceCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask);
+
+static CGLPixelFormatObj makeFormat(__GLcontextModes *mode);
+
+__GLXprovider __glXMesaProvider = {
+  __glXAquaScreenProbe,
+  "Core OpenGL",
+    NULL
 };
 
-void *__glXglDDXExtensionInfo(void) {
-    return &__glDDXExtensionInfo;
+__GLXprovider *
+GlxGetMesaProvider (void)
+{
+  GLAQUA_DEBUG_MSG("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;
+};
 
-    /* set when attached */
-    xp_surface_id sid;
+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;
+  }
+
+  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 +261,134 @@ static GLboolean glAquaLoseCurrent(__GLcontext *gc)
 
 /* 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;
-
-    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))
-        {
+	GLAQUA_DEBUG_MSG("attach(%p, %p)\n", context, draw);
+    pDraw = draw->base.pDraw;
+
+    if (draw->sid == 0) {
+//        if (!quartzProcs->CreateSurface(pDraw->pScreen, pDraw->id, pDraw,
+        if (!DRICreateSurface(pDraw->pScreen, pDraw->id, pDraw,
+                                        0, &draw->sid, NULL,
+                                        surface_notify, draw))
             return;
-        }
-        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);
+    } 
+}
+
+#if 0     // unused
+static void unattach(__GLXAquaContext *context) {
+	x_list *lst;
+	GLAQUA_DEBUG_MSG("unattach\n");
+	if (context == NULL) {
+		ErrorF("Tried to unattach a null context\n");
+		return;
+	}
+    if (context->isAttached) {
+        GLAQUA_DEBUG_MSG("unattaching\n");
+
+        if (surface_hash != NULL) {
+            lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
+            lst = x_list_remove(lst, context);
+            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
+        }
+
+        CGLClearDrawable(context->ctx);
+        context->isAttached = FALSE;
+        context->sid = 0;
     }
 }
+#endif
 
-static 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;
 
-    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 +397,13 @@ static GLboolean glAquaCopyContext(__GLcontext *dst, const __GLcontext *src,
     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 +412,36 @@ static GLboolean glAquaForceCurrent(__GLcontext *gc)
 
 /* 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)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifyDestroy");
-}
-
-static void glAquaNotifySwapBuffers(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifySwapBuffers");
-}
-
-/* Dispatch table override control for external agents like libGLS */
-static struct __GLdispatchStateRec* glAquaDispatchExec(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaDispatchExec");
-    return NULL;
-}
-
-static void glAquaBeginDispatchOverride(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaBeginDispatchOverride");
-}
-
-static void glAquaEndDispatchOverride(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaEndDispatchOverride");
+static GLboolean __glXAquaDrawableSwapBuffers(__GLXdrawable *base) {
+    CGLError gl_err;
+	__GLXAquaContext * drawableCtx;
+//    GLAQUA_DEBUG_MSG("glAquaDrawableSwapBuffers(%p)\n",base);
+	
+	if(!base) {
+		ErrorF("glXAquaDrawbleSwapBuffers passed NULL\n");
+	    return GL_FALSE;
+	}
+
+    drawableCtx = (__GLXAquaContext *)base->drawGlxc;
+
+    if (drawableCtx != NULL && drawableCtx->ctx != NULL) {
+        gl_err = CGLFlushDrawable(drawableCtx->ctx);
+        if (gl_err != 0)
+            ErrorF("CGLFlushDrawable error: %s\n", CGLErrorString(gl_err));
+    }
+    return GL_TRUE;
 }
 
-static CGLPixelFormatObj makeFormat(__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 +477,12 @@ static CGLPixelFormatObj makeFormat(__GLcontextModes *mode)
         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 +509,6 @@ static CGLPixelFormatObj makeFormat(__GLcontextModes *mode)
     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 +686,15 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
 
     /* 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 +744,40 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
     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,9 +872,9 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
 
     /* 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 */
+    /* set up depth's VisualIDs */
     for (i = 0; i < ndepth; i++) {
         int numVids = 0;
         VisualID *pVids = NULL;
@@ -1022,7 +887,7 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
                 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 +896,7 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
                 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 +906,22 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
     *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 +932,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 +956,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");
@@ -1165,13 +1034,13 @@ static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
         glAquaInitVisualConfigs(); /* ensure the visual configs are setup */
 
     /*
-     * Setup the visuals supported by this particular screen.
+     * setup the visuals supported by this particular screen.
      */
     return init_visuals(nvisualp, visualp, defaultVisp,
                         *ndepthp, *depthp, *rootDepthp);
 }
 
-
+#if 0
 static void fixup_visuals(int screen)
 {
     ScreenPtr pScreen = screenInfo.screens[screen];
@@ -1204,27 +1073,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 );
@@ -1239,7 +1116,7 @@ static void init_screen_visuals(int screen)
                 pVis[j].blueMask  == modes->blueMask &&
                 !used[j]) {
 
-                    /* Set the VisualID */
+                    /* set the VisualID */
                     modes->visualID = pVis[j].vid;
 
                     /* Mark this visual used */
@@ -1261,102 +1138,63 @@ static void init_screen_visuals(int screen)
         i++;
     }
 
-    __glXFree(used);
+    free(used);
 }
 
-static Bool glAquaScreenProbe(int screen)
-{
-    ScreenPtr pScreen;
-    glAquaScreenRec *screenPriv;
+static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen) {
+  __GLXAquaScreen *screen;
+  GLAQUA_DEBUG_MSG("glXAquaScreenProbe\n");
+  if (screen == NULL) return NULL;
 
-    GLAQUA_DEBUG_MSG("glAquaScreenProbe\n");
+  screen = malloc(sizeof *screen);
 
-    /*
-     * 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;
+  __glXScreenInit(&screen->base, pScreen);
 
-    /*
-     * Set the current screen's createContext routine.  This could be
-     * wrapped by a DDX GLX context creation routine.
-     */
-    __glDDXScreenInfo.createContext = glAquaCreateContext;
+  screen->base.destroy        = __glXAquaScreenDestroy;
+  screen->base.createContext  = __glXAquaScreenCreateContext;
+  screen->base.createDrawable = __glXAquaScreenCreateDrawable;
+  screen->base.pScreen       = pScreen;
 
-    /*
-     * The ordering of the rgb compenents might have been changed by the
-     * driver after mi initialized them.
-     */
-    fixup_visuals(screen);
+  init_screen_visuals(screen);
 
-    /*
-     * Find the GLX visuals that are supported by this screen and create
-     * XMesa's visuals.
-     */
-    init_screen_visuals(screen);
-
-    /*
-     * Wrap RealizeWindow and UnrealizeWindow on this screen
-     */
-    pScreen = screenInfo.screens[screen];
-    screenPriv = &glAquaScreens[screen];
-    screenPriv->RealizeWindow = pScreen->RealizeWindow;
-    pScreen->RealizeWindow = glAquaRealizeWindow;
-    screenPriv->UnrealizeWindow = pScreen->UnrealizeWindow;
-    pScreen->UnrealizeWindow = glAquaUnrealizeWindow;
-
-    return TRUE;
+  return &screen->base;
 }
 
-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;
-
-    GLAQUA_DEBUG_MSG("glAquaSwapBuffers\n");
-
-    if (gc != NULL && gc->ctx != NULL)
-    {
-        gl_err = CGLFlushDrawable(gc->ctx);
-        if (gl_err != 0)
-            ErrorF("CGLFlushDrawable error: %s\n", CGLErrorString(gl_err));
-    }
-
-    return GL_TRUE;
-}
-
-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)
-{
-    GLAquaDrawableRec *aquaPriv = malloc(sizeof(GLAquaDrawableRec));
-    __GLdrawablePrivate *glPriv = &glxPriv->glPriv;
+static __GLXdrawable *
+__glXAquaScreenCreateDrawable(__GLXscreen *screen,
+			      DrawablePtr pDraw,
+			      XID drawId,
+			      __GLcontextModes *modes) {
+  __GLXAquaDrawable *glxPriv;
+
+  GLAQUA_DEBUG_MSG("glAquaScreenCreateDrawable(%p,%p,%d,%p)\n", context, pDraw, drawId, modes);
 
-    aquaPriv->sid = 0;
-    aquaPriv->pDraw = NULL;
+  glxPriv = xalloc(sizeof *glxPriv);
+  if (glxPriv == NULL) return NULL;
 
-    GLAQUA_DEBUG_MSG("glAquaCreateBuffer\n");
+  memset(glxPriv, 0, sizeof *glxPriv);
 
-    // replace swapBuffers (original is never called)
-    glxPriv->swapBuffers = glAquaSwapBuffers;
+  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, drawId, modes)) {
+    xfree(glxPriv);
+    return NULL;
+  }
+
+  glxPriv->base.destroy       = __glXAquaDrawableDestroy;
+  glxPriv->base.resize        = __glXAquaDrawableResize;
+  glxPriv->base.swapBuffers   = __glXAquaDrawableSwapBuffers;
+  //  glxPriv->base.copySubBuffer = __glXAquaDrawableCopySubBuffer;
 
-    // stash private data
-    glPriv->private = aquaPriv;
-    glPriv->freePrivate = glAquaDestroyDrawablePrivate;
+  return &glxPriv->base;
 }
 
 static void glAquaResetExtension(void)
@@ -1377,3 +1215,724 @@ GLuint __glFloorLog2(GLuint val)
     }
     return c;
 }
+
+void warn_func(void * p1, char *format, ...) {
+  va_list v;
+  va_start(v, format);
+  vfprintf(stderr, format, v);
+  va_end(v);
+}
+
+static void setup_dispatch_table(void) {
+  struct _glapi_table *disp=_glapi_get_dispatch();
+  _glapi_set_warning_func((_glapi_warning_func)warn_func);
+  _glapi_noop_enable_warnings(TRUE);
+
+  SET_Accum(disp, glAccum);
+  SET_ActiveStencilFaceEXT(disp, glActiveStencilFaceEXT);
+  SET_ActiveTextureARB(disp, glActiveTextureARB);
+//SET_AlphaFragmentOp1ATI(disp, glAlphaFragmentOp1EXT);   // <-- EXT -> ATI
+//SET_AlphaFragmentOp2ATI(disp, glAlphaFragmentOp2EXT);
+//SET_AlphaFragmentOp3ATI(disp, glAlphaFragmentOp3EXT);
+  SET_AlphaFunc(disp, glAlphaFunc);
+//SET_AreProgramsResidentNV(disp, glAreProgramsResidentNV);
+  SET_AreTexturesResident(disp, glAreTexturesResident); 
+  SET_ArrayElement(disp, glArrayElement);
+  SET_AttachObjectARB(disp, glAttachObjectARB);
+  SET_Begin(disp, glBegin);
+//SET_BeginFragmentShaderATI(disp, glBeginFragmentShaderEXT);   // <-- EXT -> ATI
+  SET_BeginQueryARB(disp, glBeginQueryARB);
+  SET_BindAttribLocationARB(disp, glBindAttribLocationARB);
+  SET_BindBufferARB(disp, glBindBufferARB);
+//SET_BindFragmentShaderATI(disp, glBindFragmentShaderEXT);     // <-- EXT -> ATI
+  SET_BindFramebufferEXT(disp, glBindFramebufferEXT);
+//SET_BindProgramNV(disp, glBindProgramNV);
+  SET_BindRenderbufferEXT(disp, glBindRenderbufferEXT);
+  SET_BindTexture(disp, glBindTexture);
+  SET_Bitmap(disp, glBitmap);
+  SET_BlendColor(disp, glBlendColor);
+  SET_BlendEquation(disp, glBlendEquation);
+  SET_BlendEquationSeparateEXT(disp, glBlendEquationSeparateEXT);
+  SET_BlendFunc(disp, glBlendFunc);
+  SET_BlendFuncSeparateEXT(disp, glBlendFuncSeparateEXT);
+  SET_BlitFramebufferEXT(disp, glBlitFramebufferEXT);
+  SET_BufferDataARB(disp, glBufferDataARB);
+  SET_BufferSubDataARB(disp, glBufferSubDataARB);
+  SET_CallList(disp, glCallList);
+  SET_CallLists(disp, glCallLists);
+  SET_CheckFramebufferStatusEXT(disp, glCheckFramebufferStatusEXT);
+  SET_Clear(disp, glClear);
+  SET_ClearAccum(disp, glClearAccum);
+  SET_ClearColor(disp, glClearColor);
+  SET_ClearDepth(disp, glClearDepth);
+  SET_ClearIndex(disp, glClearIndex);
+  SET_ClearStencil(disp, glClearStencil);
+  SET_ClientActiveTextureARB(disp, glClientActiveTextureARB);
+  SET_ClipPlane(disp, glClipPlane);
+  SET_Color3b(disp, glColor3b);
+  SET_Color3bv(disp, glColor3bv);
+  SET_Color3d(disp, glColor3d);
+  SET_Color3dv(disp, glColor3dv);
+  SET_Color3f(disp, glColor3f);
+  SET_Color3fv(disp, glColor3fv);
+  SET_Color3i(disp, glColor3i);
+  SET_Color3iv(disp, glColor3iv);
+  SET_Color3s(disp, glColor3s);
+  SET_Color3sv(disp, glColor3sv);
+  SET_Color3ub(disp, glColor3ub);
+  SET_Color3ubv(disp, glColor3ubv);
+  SET_Color3ui(disp, glColor3ui);
+  SET_Color3uiv(disp, glColor3uiv);
+  SET_Color3us(disp, glColor3us);
+  SET_Color3usv(disp, glColor3usv);
+  SET_Color4b(disp, glColor4b);
+  SET_Color4bv(disp, glColor4bv);
+  SET_Color4d(disp, glColor4d);
+  SET_Color4dv(disp, glColor4dv);
+  SET_Color4f(disp, glColor4f);
+  SET_Color4fv(disp, glColor4fv);
+  SET_Color4i(disp, glColor4i);
+  SET_Color4iv(disp, glColor4iv);
+  SET_Color4s(disp, glColor4s);
+  SET_Color4sv(disp, glColor4sv);
+  SET_Color4ub(disp, glColor4ub);
+  SET_Color4ubv(disp, glColor4ubv);
+  SET_Color4ui(disp, glColor4ui);
+  SET_Color4uiv(disp, glColor4uiv);
+  SET_Color4us(disp, glColor4us);
+  SET_Color4usv(disp, glColor4usv);
+//SET_ColorFragmentOp1ATI(disp, glColorFragmentOp1EXT);    // <-- EXT -> ATI
+//SET_ColorFragmentOp2ATI(disp, glColorFragmentOp2EXT);
+//SET_ColorFragmentOp3ATI(disp, glColorFragmentOp3EXT);
+  SET_ColorMask(disp, glColorMask);
+  SET_ColorMaterial(disp, glColorMaterial);
+  SET_ColorPointer(disp, glColorPointer);
+//SET_ColorPointerEXT(disp, glColorPointerEXT);
+  SET_ColorSubTable(disp, glColorSubTable);
+  SET_ColorTable(disp, glColorTable);
+  SET_ColorTableParameterfv(disp, glColorTableParameterfv);
+  SET_ColorTableParameteriv(disp, glColorTableParameteriv);
+  SET_CombinerInputNV(disp, glCombinerInputNV);
+  SET_CombinerOutputNV(disp, glCombinerOutputNV);
+  SET_CombinerParameterfNV(disp, glCombinerParameterfNV);
+  SET_CombinerParameterfvNV(disp, glCombinerParameterfvNV);
+  SET_CombinerParameteriNV(disp, glCombinerParameteriNV);
+  SET_CombinerParameterivNV(disp, glCombinerParameterivNV);
+  SET_CompileShaderARB(disp, glCompileShaderARB);
+  SET_CompressedTexImage1DARB(disp, glCompressedTexImage1DARB);
+  SET_CompressedTexImage2DARB(disp, glCompressedTexImage2DARB);
+  SET_CompressedTexImage3DARB(disp, glCompressedTexImage3DARB);
+  SET_CompressedTexSubImage1DARB(disp, glCompressedTexSubImage1DARB);
+  SET_CompressedTexSubImage2DARB(disp, glCompressedTexSubImage2DARB);
+  SET_CompressedTexSubImage3DARB(disp, glCompressedTexSubImage3DARB);
+  SET_ConvolutionFilter1D(disp, glConvolutionFilter1D);
+  SET_ConvolutionFilter2D(disp, glConvolutionFilter2D);
+  SET_ConvolutionParameterf(disp, glConvolutionParameterf);
+  SET_ConvolutionParameterfv(disp, glConvolutionParameterfv);
+  SET_ConvolutionParameteri(disp, glConvolutionParameteri);
+  SET_ConvolutionParameteriv(disp, glConvolutionParameteriv);
+  SET_CopyColorSubTable(disp, glCopyColorSubTable);
+  SET_CopyColorTable(disp, glCopyColorTable);
+  SET_CopyConvolutionFilter1D(disp, glCopyConvolutionFilter1D);
+  SET_CopyConvolutionFilter2D(disp, glCopyConvolutionFilter2D);
+  SET_CopyPixels(disp, glCopyPixels);
+  SET_CopyTexImage1D(disp, glCopyTexImage1D);
+  SET_CopyTexImage2D(disp, glCopyTexImage2D);
+  SET_CopyTexSubImage1D(disp, glCopyTexSubImage1D);
+  SET_CopyTexSubImage2D(disp, glCopyTexSubImage2D);
+  SET_CopyTexSubImage3D(disp, glCopyTexSubImage3D);
+  SET_CreateProgramObjectARB(disp, glCreateProgramObjectARB);
+  SET_CreateShaderObjectARB(disp, glCreateShaderObjectARB);
+  SET_CullFace(disp, glCullFace);
+//SET_CullParameterdvEXT(disp, glCullParameterdvEXT);
+//SET_CullParameterfvEXT(disp, glCullParameterfvEXT);
+  SET_DeleteBuffersARB(disp, glDeleteBuffersARB);
+  SET_DeleteFencesNV(disp, glDeleteFencesAPPLE);
+//SET_DeleteFragmentShaderATI(disp, glDeleteFragmentShaderEXT);      // <-- EXT -> ATI
+  SET_DeleteFramebuffersEXT(disp, glDeleteFramebuffersEXT);
+  SET_DeleteLists(disp, glDeleteLists);
+  SET_DeleteObjectARB(disp, glDeleteObjectARB);
+//SET_DeleteProgramsNV(disp, glDeleteProgramsNV);
+  SET_DeleteQueriesARB(disp, glDeleteQueriesARB);
+  SET_DeleteRenderbuffersEXT(disp, glDeleteRenderbuffersEXT);
+  SET_DeleteTextures(disp, glDeleteTextures);
+  SET_DepthBoundsEXT(disp, glDepthBoundsEXT);
+  SET_DepthFunc(disp, glDepthFunc);
+  SET_DepthMask(disp, glDepthMask);
+  SET_DepthRange(disp, glDepthRange);
+  SET_DetachObjectARB(disp, glDetachObjectARB);
+  SET_Disable(disp, glDisable);
+  SET_DisableClientState(disp, glDisableClientState);
+  SET_DisableVertexAttribArrayARB(disp, glDisableVertexAttribArrayARB);
+  SET_DrawArrays(disp, glDrawArrays);
+  SET_DrawBuffer(disp, glDrawBuffer);
+  SET_DrawBuffersARB(disp, glDrawBuffersARB);
+  SET_DrawElements(disp, glDrawElements);
+  SET_DrawPixels(disp, glDrawPixels);
+  SET_DrawRangeElements(disp, glDrawRangeElements);
+  SET_EdgeFlag(disp, glEdgeFlag);
+  SET_EdgeFlagPointer(disp, glEdgeFlagPointer);
+//SET_EdgeFlagPointerEXT(disp, glEdgeFlagPointerEXT);
+  SET_EdgeFlagv(disp, glEdgeFlagv);
+  SET_Enable(disp, glEnable);
+  SET_EnableClientState(disp, glEnableClientState);
+  SET_EnableVertexAttribArrayARB(disp, glEnableVertexAttribArrayARB);
+  SET_End(disp, glEnd);
+//SET_EndFragmentShaderATI(disp, glEndFragmentShaderEXT);        // <-- EXT -> ATI
+  SET_EndList(disp, glEndList);
+  SET_EndQueryARB(disp, glEndQueryARB);
+  SET_EvalCoord1d(disp, glEvalCoord1d);
+  SET_EvalCoord1dv(disp, glEvalCoord1dv);
+  SET_EvalCoord1f(disp, glEvalCoord1f);
+  SET_EvalCoord1fv(disp, glEvalCoord1fv);
+  SET_EvalCoord2d(disp, glEvalCoord2d);
+  SET_EvalCoord2dv(disp, glEvalCoord2dv);
+  SET_EvalCoord2f(disp, glEvalCoord2f);
+  SET_EvalCoord2fv(disp, glEvalCoord2fv);
+  SET_EvalMesh1(disp, glEvalMesh1);
+  SET_EvalMesh2(disp, glEvalMesh2);
+  SET_EvalPoint1(disp, glEvalPoint1);
+  SET_EvalPoint2(disp, glEvalPoint2);
+//SET_ExecuteProgramNV(disp, glExecuteProgramNV);
+  SET_FeedbackBuffer(disp, glFeedbackBuffer);
+  SET_FinalCombinerInputNV(disp, glFinalCombinerInputNV);
+  SET_Finish(disp, glFinish);
+  SET_FinishFenceNV(disp, glFinishFenceAPPLE);       // <-- APPLE -> NV
+  SET_Flush(disp, glFlush);
+//SET_FlushVertexArrayRangeNV(disp, glFlushVertexArrayRangeNV);
+  SET_FogCoordPointerEXT(disp, glFogCoordPointerEXT);
+  SET_FogCoorddEXT(disp, glFogCoorddEXT);
+  SET_FogCoorddvEXT(disp, glFogCoorddvEXT);
+  SET_FogCoordfEXT(disp, glFogCoordfEXT);
+  SET_FogCoordfvEXT(disp, glFogCoordfvEXT);
+  SET_Fogf(disp, glFogf);
+  SET_Fogfv(disp, glFogfv);
+  SET_Fogi(disp, glFogi);
+  SET_Fogiv(disp, glFogiv);
+  SET_FramebufferRenderbufferEXT(disp, glFramebufferRenderbufferEXT);
+  SET_FramebufferTexture1DEXT(disp, glFramebufferTexture1DEXT);
+  SET_FramebufferTexture2DEXT(disp, glFramebufferTexture2DEXT);
+  SET_FramebufferTexture3DEXT(disp, glFramebufferTexture3DEXT);
+  SET_FrontFace(disp, glFrontFace);
+  SET_Frustum(disp, glFrustum);
+  SET_GenBuffersARB(disp, glGenBuffersARB);
+  SET_GenFencesNV(disp, glGenFencesAPPLE);            // <-- APPLE -> NV
+//SET_GenFragmentShadersATI(disp, glGenFragmentShadersEXT);         // <-- EXT -> ATI
+  SET_GenFramebuffersEXT(disp, glGenFramebuffersEXT);
+  SET_GenLists(disp, glGenLists);
+//SET_GenProgramsNV(disp, glGenProgramsNV);
+  SET_GenQueriesARB(disp, glGenQueriesARB);
+  SET_GenRenderbuffersEXT(disp, glGenRenderbuffersEXT);
+  SET_GenTextures(disp, glGenTextures);
+  SET_GenerateMipmapEXT(disp, glGenerateMipmapEXT);
+  SET_GetActiveAttribARB(disp, glGetActiveAttribARB);
+  SET_GetActiveUniformARB(disp, glGetActiveUniformARB);
+  SET_GetAttachedObjectsARB(disp, glGetAttachedObjectsARB);
+  SET_GetAttribLocationARB(disp, glGetAttribLocationARB);
+  SET_GetBooleanv(disp, glGetBooleanv);
+  SET_GetBufferParameterivARB(disp, glGetBufferParameterivARB);
+  SET_GetBufferPointervARB(disp, glGetBufferPointervARB);
+  SET_GetBufferSubDataARB(disp, glGetBufferSubDataARB);
+  SET_GetClipPlane(disp, glGetClipPlane);
+  SET_GetColorTable(disp, glGetColorTable);
+  SET_GetColorTableParameterfv(disp, glGetColorTableParameterfv);
+  SET_GetColorTableParameteriv(disp, glGetColorTableParameteriv);
+  SET_GetCombinerInputParameterfvNV(disp, glGetCombinerInputParameterfvNV);
+  SET_GetCombinerInputParameterivNV(disp, glGetCombinerInputParameterivNV);
+  SET_GetCombinerOutputParameterfvNV(disp, glGetCombinerOutputParameterfvNV);
+  SET_GetCombinerOutputParameterivNV(disp, glGetCombinerOutputParameterivNV);
+  SET_GetCompressedTexImageARB(disp, glGetCompressedTexImageARB);
+  SET_GetConvolutionFilter(disp, glGetConvolutionFilter);
+  SET_GetConvolutionParameterfv(disp, glGetConvolutionParameterfv);
+  SET_GetConvolutionParameteriv(disp, glGetConvolutionParameteriv);
+  SET_GetDoublev(disp, glGetDoublev);
+  SET_GetError(disp, glGetError);
+//SET_GetFenceivNV(disp, glGetFenceivNV);
+  SET_GetFinalCombinerInputParameterfvNV(disp, glGetFinalCombinerInputParameterfvNV);
+  SET_GetFinalCombinerInputParameterivNV(disp, glGetFinalCombinerInputParameterivNV);
+  SET_GetFloatv(disp, glGetFloatv);
+  SET_GetFramebufferAttachmentParameterivEXT(disp, glGetFramebufferAttachmentParameterivEXT);
+  SET_GetHandleARB(disp, glGetHandleARB);
+  SET_GetHistogram(disp, glGetHistogram);
+  SET_GetHistogramParameterfv(disp, glGetHistogramParameterfv);
+  SET_GetHistogramParameteriv(disp, glGetHistogramParameteriv);
+  SET_GetInfoLogARB(disp, glGetInfoLogARB);
+  SET_GetIntegerv(disp, glGetIntegerv);
+  SET_GetLightfv(disp, glGetLightfv);
+  SET_GetLightiv(disp, glGetLightiv);
+  SET_GetMapdv(disp, glGetMapdv);
+  SET_GetMapfv(disp, glGetMapfv);
+  SET_GetMapiv(disp, glGetMapiv);
+  SET_GetMaterialfv(disp, glGetMaterialfv);
+  SET_GetMaterialiv(disp, glGetMaterialiv);
+  SET_GetMinmax(disp, glGetMinmax);
+  SET_GetMinmaxParameterfv(disp, glGetMinmaxParameterfv);
+  SET_GetMinmaxParameteriv(disp, glGetMinmaxParameteriv);
+  SET_GetObjectParameterfvARB(disp, glGetObjectParameterfvARB);
+  SET_GetObjectParameterivARB(disp, glGetObjectParameterivARB);
+  SET_GetPixelMapfv(disp, glGetPixelMapfv);
+  SET_GetPixelMapuiv(disp, glGetPixelMapuiv);
+  SET_GetPixelMapusv(disp, glGetPixelMapusv);
+//SET_GetPixelTexGenParameterfvSGIS(disp, glGetPixelTexGenParameterfvSGIS);
+//SET_GetPixelTexGenParameterivSGIS(disp, glGetPixelTexGenParameterivSGIS);
+  SET_GetPointerv(disp, glGetPointerv);
+  SET_GetPolygonStipple(disp, glGetPolygonStipple);
+  SET_GetProgramEnvParameterdvARB(disp, glGetProgramEnvParameterdvARB);
+  SET_GetProgramEnvParameterfvARB(disp, glGetProgramEnvParameterfvARB);
+  SET_GetProgramLocalParameterdvARB(disp, glGetProgramLocalParameterdvARB);
+  SET_GetProgramLocalParameterfvARB(disp, glGetProgramLocalParameterfvARB);
+//SET_GetProgramNamedParameterdvNV(disp, glGetProgramNamedParameterdvNV);
+//SET_GetProgramNamedParameterfvNV(disp, glGetProgramNamedParameterfvNV);
+//SET_GetProgramParameterdvNV(disp, glGetProgramParameterdvNV);
+//SET_GetProgramParameterfvNV(disp, glGetProgramParameterfvNV);
+  SET_GetProgramStringARB(disp, glGetProgramStringARB);
+//SET_GetProgramStringNV(disp, glGetProgramStringNV);
+  SET_GetProgramivARB(disp, glGetProgramivARB);
+//SET_GetProgramivNV(disp, glGetProgramivNV);
+//SET_GetQueryObjecti64vEXT(disp, glGetQueryObjecti64vEXT);
+  SET_GetQueryObjectivARB(disp, glGetQueryObjectivARB);
+//SET_GetQueryObjectui64vEXT(disp, glGetQueryObjectui64vEXT);
+  SET_GetQueryObjectuivARB(disp, glGetQueryObjectuivARB);
+  SET_GetQueryivARB(disp, glGetQueryivARB);
+  SET_GetRenderbufferParameterivEXT(disp, glGetRenderbufferParameterivEXT);
+  SET_GetSeparableFilter(disp, glGetSeparableFilter);
+  SET_GetShaderSourceARB(disp, glGetShaderSourceARB);
+  SET_GetString(disp, glGetString);
+  SET_GetTexEnvfv(disp, glGetTexEnvfv);
+  SET_GetTexEnviv(disp, glGetTexEnviv);
+  SET_GetTexGendv(disp, glGetTexGendv);
+  SET_GetTexGenfv(disp, glGetTexGenfv);
+  SET_GetTexGeniv(disp, glGetTexGeniv);
+  SET_GetTexImage(disp, glGetTexImage);
+  SET_GetTexLevelParameterfv(disp, glGetTexLevelParameterfv);
+  SET_GetTexLevelParameteriv(disp, glGetTexLevelParameteriv);
+  SET_GetTexParameterfv(disp, glGetTexParameterfv);
+  SET_GetTexParameteriv(disp, glGetTexParameteriv);
+//SET_GetTrackMatrixivNV(disp, glGetTrackMatrixivNV);
+  SET_GetUniformLocationARB(disp, glGetUniformLocationARB);
+  SET_GetUniformfvARB(disp, glGetUniformfvARB);
+  SET_GetUniformivARB(disp, glGetUniformivARB);
+//SET_GetVertexAttribPointervNV(disp, glGetVertexAttribPointervNV);
+  SET_GetVertexAttribdvARB(disp, glGetVertexAttribdvARB);
+//SET_GetVertexAttribdvNV(disp, glGetVertexAttribdvNV);
+  SET_GetVertexAttribfvARB(disp, glGetVertexAttribfvARB);
+//SET_GetVertexAttribfvNV(disp, glGetVertexAttribfvNV);
+  SET_GetVertexAttribivARB(disp, glGetVertexAttribivARB);
+//SET_GetVertexAttribivNV(disp, glGetVertexAttribivNV);
+  SET_Hint(disp, glHint);
+  SET_Histogram(disp, glHistogram);
+  SET_IndexMask(disp, glIndexMask);
+  SET_IndexPointer(disp, glIndexPointer);
+//SET_IndexPointerEXT(disp, glIndexPointerEXT);
+  SET_Indexd(disp, glIndexd);
+  SET_Indexdv(disp, glIndexdv);
+  SET_Indexf(disp, glIndexf);
+  SET_Indexfv(disp, glIndexfv);
+  SET_Indexi(disp, glIndexi);
+  SET_Indexiv(disp, glIndexiv);
+  SET_Indexs(disp, glIndexs);
+  SET_Indexsv(disp, glIndexsv);
+  SET_Indexub(disp, glIndexub);
+  SET_Indexubv(disp, glIndexubv);
+  SET_InitNames(disp, glInitNames);
+  SET_InterleavedArrays(disp, glInterleavedArrays);
+  SET_IsBufferARB(disp, glIsBufferARB);
+  SET_IsEnabled(disp, glIsEnabled);
+  SET_IsFenceNV(disp, glIsFenceAPPLE);           // <-- APPLE -> NV
+  SET_IsFramebufferEXT(disp, glIsFramebufferEXT);
+  SET_IsList(disp, glIsList);
+//SET_IsProgramNV(disp, glIsProgramNV);
+  SET_IsQueryARB(disp, glIsQueryARB);
+  SET_IsRenderbufferEXT(disp, glIsRenderbufferEXT);
+  SET_IsTexture(disp, glIsTexture);
+  SET_LightModelf(disp, glLightModelf);
+  SET_LightModelfv(disp, glLightModelfv);
+  SET_LightModeli(disp, glLightModeli);
+  SET_LightModeliv(disp, glLightModeliv);
+  SET_Lightf(disp, glLightf);
+  SET_Lightfv(disp, glLightfv);
+  SET_Lighti(disp, glLighti);
+  SET_Lightiv(disp, glLightiv);
+  SET_LineStipple(disp, glLineStipple);
+  SET_LineWidth(disp, glLineWidth);
+  SET_LinkProgramARB(disp, glLinkProgramARB);
+  SET_ListBase(disp, glListBase);
+  SET_LoadIdentity(disp, glLoadIdentity);
+  SET_LoadMatrixd(disp, glLoadMatrixd);
+  SET_LoadMatrixf(disp, glLoadMatrixf);
+  SET_LoadName(disp, glLoadName);
+//SET_LoadProgramNV(disp, glLoadProgramNV);
+  SET_LoadTransposeMatrixdARB(disp, glLoadTransposeMatrixdARB);
+  SET_LoadTransposeMatrixfARB(disp, glLoadTransposeMatrixfARB);
+  SET_LockArraysEXT(disp, glLockArraysEXT);
+  SET_LogicOp(disp, glLogicOp);
+  SET_Map1d(disp, glMap1d);
+  SET_Map1f(disp, glMap1f);
+  SET_Map2d(disp, glMap2d);
+  SET_Map2f(disp, glMap2f);
+  SET_MapBufferARB(disp, glMapBufferARB);
+  SET_MapGrid1d(disp, glMapGrid1d);
+  SET_MapGrid1f(disp, glMapGrid1f);
+  SET_MapGrid2d(disp, glMapGrid2d);
+  SET_MapGrid2f(disp, glMapGrid2f);
+  SET_Materialf(disp, glMaterialf);
+  SET_Materialfv(disp, glMaterialfv);
+  SET_Materiali(disp, glMateriali);
+  SET_Materialiv(disp, glMaterialiv);
+  SET_MatrixMode(disp, glMatrixMode);
+  SET_Minmax(disp, glMinmax);
+  SET_MultMatrixd(disp, glMultMatrixd);
+  SET_MultMatrixf(disp, glMultMatrixf);
+  SET_MultTransposeMatrixdARB(disp, glMultTransposeMatrixdARB);
+  SET_MultTransposeMatrixfARB(disp, glMultTransposeMatrixfARB);
+  SET_MultiDrawArraysEXT(disp, glMultiDrawArraysEXT);
+  SET_MultiDrawElementsEXT(disp, glMultiDrawElementsEXT);
+//SET_MultiModeDrawArraysIBM(disp, glMultiModeDrawArraysIBM);
+//SET_MultiModeDrawElementsIBM(disp, glMultiModeDrawElementsIBM);
+  SET_MultiTexCoord1dARB(disp, glMultiTexCoord1dARB);
+  SET_MultiTexCoord1dvARB(disp, glMultiTexCoord1dvARB);
+  SET_MultiTexCoord1fARB(disp, glMultiTexCoord1fARB);
+  SET_MultiTexCoord1fvARB(disp, glMultiTexCoord1fvARB);
+  SET_MultiTexCoord1iARB(disp, glMultiTexCoord1iARB);
+  SET_MultiTexCoord1ivARB(disp, glMultiTexCoord1ivARB);
+  SET_MultiTexCoord1sARB(disp, glMultiTexCoord1sARB);
+  SET_MultiTexCoord1svARB(disp, glMultiTexCoord1svARB);
+  SET_MultiTexCoord2dARB(disp, glMultiTexCoord2dARB);
+  SET_MultiTexCoord2dvARB(disp, glMultiTexCoord2dvARB);
+  SET_MultiTexCoord2fARB(disp, glMultiTexCoord2fARB);
+  SET_MultiTexCoord2fvARB(disp, glMultiTexCoord2fvARB);
+  SET_MultiTexCoord2iARB(disp, glMultiTexCoord2iARB);
+  SET_MultiTexCoord2ivARB(disp, glMultiTexCoord2ivARB);
+  SET_MultiTexCoord2sARB(disp, glMultiTexCoord2sARB);
+  SET_MultiTexCoord2svARB(disp, glMultiTexCoord2svARB);
+  SET_MultiTexCoord3dARB(disp, glMultiTexCoord3dARB);
+  SET_MultiTexCoord3dvARB(disp, glMultiTexCoord3dvARB);
+  SET_MultiTexCoord3fARB(disp, glMultiTexCoord3fARB);
+  SET_MultiTexCoord3fvARB(disp, glMultiTexCoord3fvARB);
+  SET_MultiTexCoord3iARB(disp, glMultiTexCoord3iARB);
+  SET_MultiTexCoord3ivARB(disp, glMultiTexCoord3ivARB);
+  SET_MultiTexCoord3sARB(disp, glMultiTexCoord3sARB);
+  SET_MultiTexCoord3svARB(disp, glMultiTexCoord3svARB);
+  SET_MultiTexCoord4dARB(disp, glMultiTexCoord4dARB);
+  SET_MultiTexCoord4dvARB(disp, glMultiTexCoord4dvARB);
+  SET_MultiTexCoord4fARB(disp, glMultiTexCoord4fARB);
+  SET_MultiTexCoord4fvARB(disp, glMultiTexCoord4fvARB);
+  SET_MultiTexCoord4iARB(disp, glMultiTexCoord4iARB);
+  SET_MultiTexCoord4ivARB(disp, glMultiTexCoord4ivARB);
+  SET_MultiTexCoord4sARB(disp, glMultiTexCoord4sARB);
+  SET_MultiTexCoord4svARB(disp, glMultiTexCoord4svARB);
+  SET_NewList(disp, glNewList);
+  SET_Normal3b(disp, glNormal3b);
+  SET_Normal3bv(disp, glNormal3bv);
+  SET_Normal3d(disp, glNormal3d);
+  SET_Normal3dv(disp, glNormal3dv);
+  SET_Normal3f(disp, glNormal3f);
+  SET_Normal3fv(disp, glNormal3fv);
+  SET_Normal3i(disp, glNormal3i);
+  SET_Normal3iv(disp, glNormal3iv);
+  SET_Normal3s(disp, glNormal3s);
+  SET_Normal3sv(disp, glNormal3sv);
+  SET_NormalPointer(disp, glNormalPointer);
+//SET_NormalPointerEXT(disp, glNormalPointerEXT);
+  SET_Ortho(disp, glOrtho);
+//SET_PassTexCoordATI(disp, glPassTexCoordEXT);         // <-- EXT -> ATI
+  SET_PassThrough(disp, glPassThrough);
+  SET_PixelMapfv(disp, glPixelMapfv);
+  SET_PixelMapuiv(disp, glPixelMapuiv);
+  SET_PixelMapusv(disp, glPixelMapusv);
+  SET_PixelStoref(disp, glPixelStoref);
+  SET_PixelStorei(disp, glPixelStorei);
+//SET_PixelTexGenParameterfSGIS(disp, glPixelTexGenParameterfSGIS);
+//SET_PixelTexGenParameterfvSGIS(disp, glPixelTexGenParameterfvSGIS);
+//SET_PixelTexGenParameteriSGIS(disp, glPixelTexGenParameteriSGIS);
+//SET_PixelTexGenParameterivSGIS(disp, glPixelTexGenParameterivSGIS);
+//  SET_PixelTexGenSGIX(disp, glPixelTexGenSGIX);
+  SET_PixelTransferf(disp, glPixelTransferf);
+  SET_PixelTransferi(disp, glPixelTransferi);
+  SET_PixelZoom(disp, glPixelZoom);
+  SET_PointParameterfEXT(disp, glPointParameterfARB);      // <-- ARB -> EXT
+  SET_PointParameterfvEXT(disp, glPointParameterfvARB);    // <-- ARB -> EXT
+  SET_PointParameteriNV(disp, glPointParameteriNV);
+  SET_PointParameterivNV(disp, glPointParameterivNV);
+  SET_PointSize(disp, glPointSize);
+  SET_PolygonMode(disp, glPolygonMode);
+  SET_PolygonOffset(disp, glPolygonOffset);
+//SET_PolygonOffsetEXT(disp, glPolygonOffsetEXT);
+  SET_PolygonStipple(disp, glPolygonStipple);
+  SET_PopAttrib(disp, glPopAttrib);
+  SET_PopClientAttrib(disp, glPopClientAttrib);
+  SET_PopMatrix(disp, glPopMatrix);
+  SET_PopName(disp, glPopName);
+  SET_PrioritizeTextures(disp, glPrioritizeTextures);
+  SET_ProgramEnvParameter4dARB(disp, glProgramEnvParameter4dARB);
+  SET_ProgramEnvParameter4dvARB(disp, glProgramEnvParameter4dvARB);
+  SET_ProgramEnvParameter4fARB(disp, glProgramEnvParameter4fARB);
+  SET_ProgramEnvParameter4fvARB(disp, glProgramEnvParameter4fvARB);
+  SET_ProgramLocalParameter4dARB(disp, glProgramLocalParameter4dARB);
+  SET_ProgramLocalParameter4dvARB(disp, glProgramLocalParameter4dvARB);
+  SET_ProgramLocalParameter4fARB(disp, glProgramLocalParameter4fARB);
+  SET_ProgramLocalParameter4fvARB(disp, glProgramLocalParameter4fvARB);
+//SET_ProgramNamedParameter4dNV(disp, glProgramNamedParameter4dNV);
+//SET_ProgramNamedParameter4dvNV(disp, glProgramNamedParameter4dvNV);
+//SET_ProgramNamedParameter4fNV(disp, glProgramNamedParameter4fNV);
+//SET_ProgramNamedParameter4fvNV(disp, glProgramNamedParameter4fvNV);
+//SET_ProgramParameter4dNV(disp, glProgramParameter4dNV);
+//SET_ProgramParameter4dvNV(disp, glProgramParameter4dvNV);
+//SET_ProgramParameter4fNV(disp, glProgramParameter4fNV);
+//SET_ProgramParameter4fvNV(disp, glProgramParameter4fvNV);
+//SET_ProgramParameters4dvNV(disp, glProgramParameters4dvNV);
+//SET_ProgramParameters4fvNV(disp, glProgramParameters4fvNV);
+  SET_ProgramStringARB(disp, glProgramStringARB);
+  SET_PushAttrib(disp, glPushAttrib);
+  SET_PushClientAttrib(disp, glPushClientAttrib);
+  SET_PushMatrix(disp, glPushMatrix);
+  SET_PushName(disp, glPushName);
+  SET_RasterPos2d(disp, glRasterPos2d);
+  SET_RasterPos2dv(disp, glRasterPos2dv);
+  SET_RasterPos2f(disp, glRasterPos2f);
+  SET_RasterPos2fv(disp, glRasterPos2fv);
+  SET_RasterPos2i(disp, glRasterPos2i);
+  SET_RasterPos2iv(disp, glRasterPos2iv);
+  SET_RasterPos2s(disp, glRasterPos2s);
+  SET_RasterPos2sv(disp, glRasterPos2sv);
+  SET_RasterPos3d(disp, glRasterPos3d);
+  SET_RasterPos3dv(disp, glRasterPos3dv);
+  SET_RasterPos3f(disp, glRasterPos3f);
+  SET_RasterPos3fv(disp, glRasterPos3fv);
+  SET_RasterPos3i(disp, glRasterPos3i);
+  SET_RasterPos3iv(disp, glRasterPos3iv);
+  SET_RasterPos3s(disp, glRasterPos3s);
+  SET_RasterPos3sv(disp, glRasterPos3sv);
+  SET_RasterPos4d(disp, glRasterPos4d);
+  SET_RasterPos4dv(disp, glRasterPos4dv);
+  SET_RasterPos4f(disp, glRasterPos4f);
+  SET_RasterPos4fv(disp, glRasterPos4fv);
+  SET_RasterPos4i(disp, glRasterPos4i);
+  SET_RasterPos4iv(disp, glRasterPos4iv);
+  SET_RasterPos4s(disp, glRasterPos4s);
+  SET_RasterPos4sv(disp, glRasterPos4sv);
+  SET_ReadBuffer(disp, glReadBuffer);
+  SET_ReadPixels(disp, glReadPixels);
+  SET_Rectd(disp, glRectd);
+  SET_Rectdv(disp, glRectdv);
+  SET_Rectf(disp, glRectf);
+  SET_Rectfv(disp, glRectfv);
+  SET_Recti(disp, glRecti);
+  SET_Rectiv(disp, glRectiv);
+  SET_Rects(disp, glRects);
+  SET_Rectsv(disp, glRectsv);
+  SET_RenderMode(disp, glRenderMode);
+  SET_RenderbufferStorageEXT(disp, glRenderbufferStorageEXT);
+//SET_RequestResidentProgramsNV(disp, glRequestResidentProgramsNV);
+  SET_ResetHistogram(disp, glResetHistogram);
+  SET_ResetMinmax(disp, glResetMinmax);
+//SET_ResizeBuffersMESA(disp, glResizeBuffersMESA);
+  SET_Rotated(disp, glRotated);
+  SET_Rotatef(disp, glRotatef);
+  SET_SampleCoverageARB(disp, glSampleCoverageARB);
+//SET_SampleMapATI(disp, glSampleMapEXT);       // <-- EXT -> ATI
+//SET_SampleMaskSGIS(disp, glSampleMaskSGIS);
+//SET_SamplePatternSGIS(disp, glSamplePatternSGIS);
+  SET_Scaled(disp, glScaled);
+  SET_Scalef(disp, glScalef);
+  SET_Scissor(disp, glScissor);
+  SET_SecondaryColor3bEXT(disp, glSecondaryColor3bEXT);
+  SET_SecondaryColor3bvEXT(disp, glSecondaryColor3bvEXT);
+  SET_SecondaryColor3dEXT(disp, glSecondaryColor3dEXT);
+  SET_SecondaryColor3dvEXT(disp, glSecondaryColor3dvEXT);
+  SET_SecondaryColor3fEXT(disp, glSecondaryColor3fEXT);
+  SET_SecondaryColor3fvEXT(disp, glSecondaryColor3fvEXT);
+  SET_SecondaryColor3iEXT(disp, glSecondaryColor3iEXT);
+  SET_SecondaryColor3ivEXT(disp, glSecondaryColor3ivEXT);
+  SET_SecondaryColor3sEXT(disp, glSecondaryColor3sEXT);
+  SET_SecondaryColor3svEXT(disp, glSecondaryColor3svEXT);
+  SET_SecondaryColor3ubEXT(disp, glSecondaryColor3ubEXT);
+  SET_SecondaryColor3ubvEXT(disp, glSecondaryColor3ubvEXT);
+  SET_SecondaryColor3uiEXT(disp, glSecondaryColor3uiEXT);
+  SET_SecondaryColor3uivEXT(disp, glSecondaryColor3uivEXT);
+  SET_SecondaryColor3usEXT(disp, glSecondaryColor3usEXT);
+  SET_SecondaryColor3usvEXT(disp, glSecondaryColor3usvEXT);
+  SET_SecondaryColorPointerEXT(disp, glSecondaryColorPointerEXT);
+  SET_SelectBuffer(disp, glSelectBuffer);
+  SET_SeparableFilter2D(disp, glSeparableFilter2D);
+  SET_SetFenceNV(disp, glSetFenceAPPLE);  // <-- APPLE -> NV
+//SET_SetFragmentShaderConstantATI(disp, glSetFragmentShaderConstantEXT);   // <-- EXT -> ATI
+  SET_ShadeModel(disp, glShadeModel);
+  SET_ShaderSourceARB(disp, glShaderSourceARB);
+  SET_StencilFunc(disp, glStencilFunc);
+  SET_StencilFuncSeparate(disp, glStencilFuncSeparate);
+  SET_StencilMask(disp, glStencilMask);
+  SET_StencilMaskSeparate(disp, glStencilMaskSeparate);
+  SET_StencilOp(disp, glStencilOp);
+  SET_StencilOpSeparate(disp, glStencilOpSeparate);
+  SET_TestFenceNV(disp, glTestFenceAPPLE); // <-- APPLE -> NV
+  SET_TexCoord1d(disp, glTexCoord1d);
+  SET_TexCoord1dv(disp, glTexCoord1dv);
+  SET_TexCoord1f(disp, glTexCoord1f);
+  SET_TexCoord1fv(disp, glTexCoord1fv);
+  SET_TexCoord1i(disp, glTexCoord1i);
+  SET_TexCoord1iv(disp, glTexCoord1iv);
+  SET_TexCoord1s(disp, glTexCoord1s);
+  SET_TexCoord1sv(disp, glTexCoord1sv);
+  SET_TexCoord2d(disp, glTexCoord2d);
+  SET_TexCoord2dv(disp, glTexCoord2dv);
+  SET_TexCoord2f(disp, glTexCoord2f);
+  SET_TexCoord2fv(disp, glTexCoord2fv);
+  SET_TexCoord2i(disp, glTexCoord2i);
+  SET_TexCoord2iv(disp, glTexCoord2iv);
+  SET_TexCoord2s(disp, glTexCoord2s);
+  SET_TexCoord2sv(disp, glTexCoord2sv);
+  SET_TexCoord3d(disp, glTexCoord3d);
+  SET_TexCoord3dv(disp, glTexCoord3dv);
+  SET_TexCoord3f(disp, glTexCoord3f);
+  SET_TexCoord3fv(disp, glTexCoord3fv);
+  SET_TexCoord3i(disp, glTexCoord3i);
+  SET_TexCoord3iv(disp, glTexCoord3iv);
+  SET_TexCoord3s(disp, glTexCoord3s);
+  SET_TexCoord3sv(disp, glTexCoord3sv);
+  SET_TexCoord4d(disp, glTexCoord4d);
+  SET_TexCoord4dv(disp, glTexCoord4dv);
+  SET_TexCoord4f(disp, glTexCoord4f);
+  SET_TexCoord4fv(disp, glTexCoord4fv);
+  SET_TexCoord4i(disp, glTexCoord4i);
+  SET_TexCoord4iv(disp, glTexCoord4iv);
+  SET_TexCoord4s(disp, glTexCoord4s);
+  SET_TexCoord4sv(disp, glTexCoord4sv);
+  SET_TexCoordPointer(disp, glTexCoordPointer);
+//SET_TexCoordPointerEXT(disp, glTexCoordPointerEXT);
+  SET_TexEnvf(disp, glTexEnvf);
+  SET_TexEnvfv(disp, glTexEnvfv);
+  SET_TexEnvi(disp, glTexEnvi);
+  SET_TexEnviv(disp, glTexEnviv);
+  SET_TexGend(disp, glTexGend);
+  SET_TexGendv(disp, glTexGendv);
+  SET_TexGenf(disp, glTexGenf);
+  SET_TexGenfv(disp, glTexGenfv);
+  SET_TexGeni(disp, glTexGeni);
+  SET_TexGeniv(disp, glTexGeniv);
+  SET_TexImage1D(disp, glTexImage1D);
+  SET_TexImage2D(disp, glTexImage2D);
+  SET_TexImage3D(disp, glTexImage3D);
+  SET_TexParameterf(disp, glTexParameterf);
+  SET_TexParameterfv(disp, glTexParameterfv);
+  SET_TexParameteri(disp, glTexParameteri);
+  SET_TexParameteriv(disp, glTexParameteriv);
+  SET_TexSubImage1D(disp, glTexSubImage1D);
+  SET_TexSubImage2D(disp, glTexSubImage2D);
+  SET_TexSubImage3D(disp, glTexSubImage3D);
+//SET_TrackMatrixNV(disp, glTrackMatrixNV);
+  SET_Translated(disp, glTranslated);
+  SET_Translatef(disp, glTranslatef);
+  SET_Uniform1fARB(disp, glUniform1fARB);
+  SET_Uniform1fvARB(disp, glUniform1fvARB);
+  SET_Uniform1iARB(disp, glUniform1iARB);
+  SET_Uniform1ivARB(disp, glUniform1ivARB);
+  SET_Uniform2fARB(disp, glUniform2fARB);
+  SET_Uniform2fvARB(disp, glUniform2fvARB);
+  SET_Uniform2iARB(disp, glUniform2iARB);
+  SET_Uniform2ivARB(disp, glUniform2ivARB);
+  SET_Uniform3fARB(disp, glUniform3fARB);
+  SET_Uniform3fvARB(disp, glUniform3fvARB);
+  SET_Uniform3iARB(disp, glUniform3iARB);
+  SET_Uniform3ivARB(disp, glUniform3ivARB);
+  SET_Uniform4fARB(disp, glUniform4fARB);
+  SET_Uniform4fvARB(disp, glUniform4fvARB);
+  SET_Uniform4iARB(disp, glUniform4iARB);
+  SET_Uniform4ivARB(disp, glUniform4ivARB);
+  SET_UniformMatrix2fvARB(disp, glUniformMatrix2fvARB);
+  SET_UniformMatrix3fvARB(disp, glUniformMatrix3fvARB);
+  SET_UniformMatrix4fvARB(disp, glUniformMatrix4fvARB);
+  SET_UnlockArraysEXT(disp, glUnlockArraysEXT);
+  SET_UnmapBufferARB(disp, glUnmapBufferARB);
+  SET_UseProgramObjectARB(disp, glUseProgramObjectARB);
+  SET_ValidateProgramARB(disp, glValidateProgramARB);
+  SET_Vertex2d(disp, glVertex2d);
+  SET_Vertex2dv(disp, glVertex2dv);
+  SET_Vertex2f(disp, glVertex2f);
+  SET_Vertex2fv(disp, glVertex2fv);
+  SET_Vertex2i(disp, glVertex2i);
+  SET_Vertex2iv(disp, glVertex2iv);
+  SET_Vertex2s(disp, glVertex2s);
+  SET_Vertex2sv(disp, glVertex2sv);
+  SET_Vertex3d(disp, glVertex3d);
+  SET_Vertex3dv(disp, glVertex3dv);
+  SET_Vertex3f(disp, glVertex3f);
+  SET_Vertex3fv(disp, glVertex3fv);
+  SET_Vertex3i(disp, glVertex3i);
+  SET_Vertex3iv(disp, glVertex3iv);
+  SET_Vertex3s(disp, glVertex3s);
+  SET_Vertex3sv(disp, glVertex3sv);
+  SET_Vertex4d(disp, glVertex4d);
+  SET_Vertex4dv(disp, glVertex4dv);
+  SET_Vertex4f(disp, glVertex4f);
+  SET_Vertex4fv(disp, glVertex4fv);
+  SET_Vertex4i(disp, glVertex4i);
+  SET_Vertex4iv(disp, glVertex4iv);
+  SET_Vertex4s(disp, glVertex4s);
+  SET_Vertex4sv(disp, glVertex4sv);
+//SET_VertexArrayRangeNV(disp, glVertexArrayRangeNV);
+  SET_VertexAttrib1dARB(disp, glVertexAttrib1dARB);
+  SET_VertexAttrib1dvARB(disp, glVertexAttrib1dvARB);
+  SET_VertexAttrib1fARB(disp, glVertexAttrib1fARB);
+  SET_VertexAttrib1fvARB(disp, glVertexAttrib1fvARB);
+  SET_VertexAttrib1sARB(disp, glVertexAttrib1sARB);
+  SET_VertexAttrib1svARB(disp, glVertexAttrib1svARB);
+  SET_VertexAttrib2dARB(disp, glVertexAttrib2dARB);
+  SET_VertexAttrib2dvARB(disp, glVertexAttrib2dvARB);
+  SET_VertexAttrib2fARB(disp, glVertexAttrib2fARB);
+  SET_VertexAttrib2fvARB(disp, glVertexAttrib2fvARB);
+  SET_VertexAttrib2sARB(disp, glVertexAttrib2sARB);
+  SET_VertexAttrib2svARB(disp, glVertexAttrib2svARB);
+  SET_VertexAttrib3dARB(disp, glVertexAttrib3dARB);
+  SET_VertexAttrib3dvARB(disp, glVertexAttrib3dvARB);
+  SET_VertexAttrib3fARB(disp, glVertexAttrib3fARB);
+  SET_VertexAttrib3fvARB(disp, glVertexAttrib3fvARB);
+  SET_VertexAttrib3sARB(disp, glVertexAttrib3sARB);
+  SET_VertexAttrib3svARB(disp, glVertexAttrib3svARB);
+  SET_VertexAttrib4NbvARB(disp, glVertexAttrib4NbvARB);
+  SET_VertexAttrib4NivARB(disp, glVertexAttrib4NivARB);
+  SET_VertexAttrib4NsvARB(disp, glVertexAttrib4NsvARB);
+  SET_VertexAttrib4NubARB(disp, glVertexAttrib4NubARB);
+  SET_VertexAttrib4NubvARB(disp, glVertexAttrib4NubvARB);
+  SET_VertexAttrib4NuivARB(disp, glVertexAttrib4NuivARB);
+  SET_VertexAttrib4NusvARB(disp, glVertexAttrib4NusvARB);
+  SET_VertexAttrib4bvARB(disp, glVertexAttrib4bvARB);
+  SET_VertexAttrib4dARB(disp, glVertexAttrib4dARB);
+  SET_VertexAttrib4dvARB(disp, glVertexAttrib4dvARB);
+  SET_VertexAttrib4fARB(disp, glVertexAttrib4fARB);
+  SET_VertexAttrib4fvARB(disp, glVertexAttrib4fvARB);
+  SET_VertexAttrib4ivARB(disp, glVertexAttrib4ivARB);
+  SET_VertexAttrib4sARB(disp, glVertexAttrib4sARB);
+  SET_VertexAttrib4svARB(disp, glVertexAttrib4svARB);
+  SET_VertexAttrib4ubvARB(disp, glVertexAttrib4ubvARB);
+  SET_VertexAttrib4uivARB(disp, glVertexAttrib4uivARB);
+  SET_VertexAttrib4usvARB(disp, glVertexAttrib4usvARB);
+  SET_VertexAttribPointerARB(disp, glVertexAttribPointerARB);
+  SET_VertexPointer(disp, glVertexPointer);
+//  SET_VertexPointerEXT(disp, glVertexPointerEXT);
+  SET_Viewport(disp, glViewport);
+  SET_WindowPos2dMESA(disp, glWindowPos2dARB);
+  SET_WindowPos2dvMESA(disp, glWindowPos2dvARB);
+  SET_WindowPos2fMESA(disp, glWindowPos2fARB);
+  SET_WindowPos2fvMESA(disp, glWindowPos2fvARB);
+  SET_WindowPos2iMESA(disp, glWindowPos2iARB);
+  SET_WindowPos2ivMESA(disp, glWindowPos2ivARB);
+  SET_WindowPos2sMESA(disp, glWindowPos2sARB);
+  SET_WindowPos2svMESA(disp, glWindowPos2svARB);
+  SET_WindowPos3dMESA(disp, glWindowPos3dARB);
+  SET_WindowPos3dvMESA(disp, glWindowPos3dvARB);
+  SET_WindowPos3fMESA(disp, glWindowPos3fARB);
+  SET_WindowPos3fvMESA(disp, glWindowPos3fvARB);
+  SET_WindowPos3iMESA(disp, glWindowPos3iARB);
+  SET_WindowPos3ivMESA(disp, glWindowPos3ivARB);
+  SET_WindowPos3sMESA(disp, glWindowPos3sARB);
+  SET_WindowPos3svMESA(disp, glWindowPos3svARB);
+//SET_WindowPos4dMESA(disp, glWindowPos4dMESA);
+//SET_WindowPos4dvMESA(disp, glWindowPos4dvMESA);
+//SET_WindowPos4fMESA(disp, glWindowPos4fMESA);
+//SET_WindowPos4fvMESA(disp, glWindowPos4fvMESA);
+//SET_WindowPos4iMESA(disp, glWindowPos4iMESA);
+//SET_WindowPos4ivMESA(disp, glWindowPos4ivMESA);
+//SET_WindowPos4sMESA(disp, glWindowPos4sMESA);
+//SET_WindowPos4svMESA(disp, glWindowPos4svMESA);
+}
diff --git a/configure.ac b/configure.ac
index 3b6b754..61fdc4c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -198,7 +198,7 @@ case $host_cpu in
 	ARM_VIDEO=yes
 	;;
   i*86)
-	use_x86_asm="yes"
+	use_x86_asm="no"
 	I386_VIDEO=yes
 	case $host_os in
 		*linux*)	DEFAULT_INT10=vm86 ;;
@@ -223,7 +223,7 @@ case $host_cpu in
 	BSD_ARCH_SOURCES="sparc64_video.c ioperm_noop.c"
 	;;
   x86_64*|amd64*)
-  	use_x86_asm="yes"
+  	use_x86_asm="no"
 	I386_VIDEO=yes
 	case $host_os in
 		*freebsd*)	AC_DEFINE(USE_DEV_IO, 1, [BSD /dev/io]) ;;
@@ -363,9 +363,10 @@ AC_ARG_WITH(os-name,         AS_HELP_STRING([--with-os-name=OSNAME], [Name of OS
 AC_ARG_WITH(os-vendor,       AS_HELP_STRING([--with-os-vendor=OSVENDOR], [Name of OS vendor]),
 				[ OSVENDOR="$withval" ],
 				[ OSVENDOR="" ])
+AC_ARG_VAR([MESA_SOURCE],[Path to Mesa source tree])
 AC_ARG_WITH(mesa-source,     AS_HELP_STRING([--with-mesa-source=MESA_SOURCE], [Path to Mesa source tree]),
                                 [ MESA_SOURCE="$withval" ],
-                                [ MESA_SOURCE="" ])
+                                [ MESA_SOURCE="${MESA_SOURCE}" ])
 AC_ARG_WITH(fontdir,         AS_HELP_STRING([--with-fontdir=FONTDIR], [Path to top level dir where fonts are installed (default: ${libdir}/X11/fonts)]),
                                 [ FONTDIR="$withval" ],
                                 [ FONTDIR="${libdir}/X11/fonts" ])
@@ -385,6 +386,11 @@ AC_ARG_WITH(rgb-path,         AS_HELP_STRING([--with-rgb-path=PATH], [Path to RG
 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])
@@ -401,6 +407,7 @@ AC_ARG_ENABLE(xres,           AS_HELP_STRING([--disable-xres], [Build XRes exten
 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: enabled)]), [DGA=$enableval], [DGA=yes])
 AC_ARG_ENABLE(screensaver,    AS_HELP_STRING([--disable-screensaver], [Build ScreenSaver extension (default: enabled)]), [SCREENSAVER=$enableval], [SCREENSAVER=yes])
@@ -431,11 +438,11 @@ AC_ARG_ENABLE(xfree86-utils,     AS_HELP_STRING([--enable-xfree86-utils], [Build
 
 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: no)]), [DMX=$enableval], [DMX=no])
-AC_ARG_ENABLE(xvfb,    	      AS_HELP_STRING([--enable-xvfb], [Build Xvfb server (default: no)]), [XVFB=$enableval], [XVFB=yes])
+AC_ARG_ENABLE(dmx,    	      AS_HELP_STRING([--enable-dmx], [Build DMX server (default: auto)]), [DMX=$enableval], [DMX=auto])
+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])
-AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
+AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: auto)]), [XPRINT=$enableval], [XPRINT=auto])
 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])
@@ -462,7 +469,7 @@ if test "x$SETUID" = "xauto" ; then
 	   	case $host_cpu in
 		    sparc)	SETUID="no"  ;;
 		    *)		SETUID="yes" ;;
-		esac
+		esac ;;
 	esac
 	if test "x$SETUID" = xyes; then
 		touch testfile
@@ -531,10 +538,6 @@ if test "x$XVMC" = xyes; then
 	AC_DEFINE(XvMCExtension, 1, [Build XvMC extension])
 fi
 
-AM_CONDITIONAL(DGA, [test "x$DGA" = xyes])
-if test "x$DGA" = xyes; then
-	AC_DEFINE(DGA, 1, [Support DGA extension])
-fi
 
 AM_CONDITIONAL(COMPOSITE, [test "x$COMPOSITE" = xyes])
 if test "x$COMPOSITE" = xyes; then
@@ -580,7 +583,7 @@ if test "x$GLX" = xyes && ! test "x$MESA_SOURCE" = x; then
 	PKG_CHECK_MODULES([GL], [glproto >= 1.4.8])
 	AC_SUBST(XLIB_CFLAGS)
 	AC_DEFINE(GLXEXT, 1, [Build GLX extension])
-	GLX_LIBS='$(top_builddir)/GL/glx/libglx.la $(top_builddir)/GL/mesa/libGLcore.la'
+	GLX_LIBS='$(top_builddir)/GL/apple/indirect.o $(top_builddir)/GL/glx/libglx.la'
 	test -d GL || mkdir GL
 	case $host_os in
 	  solaris*) 	
@@ -696,14 +699,6 @@ if test "x$DPMSExtension" = xyes; then
 	AC_DEFINE(DPMSExtension, 1, [Support DPMS extension])
 fi
 
-if test "x$XF86VIDMODE" = xyes; then
-	AC_DEFINE(XF86VIDMODE, 1, [Support XFree86 Video Mode extension])
-fi
-
-if test "x$XF86MISC" = xyes; then
-	AC_DEFINE(XF86MISC, 1, [Support XFree86 miscellaneous extensions])
-fi
-
 if test "x$XPRINT" = xauto; then
 	PKG_CHECK_MODULES([XPRINTPROTO], [printproto], [XPRINT=yes], [XPRINT=no])
 fi
@@ -835,7 +830,7 @@ AC_SUBST([VENDOR_STRING])
 AC_SUBST([VENDOR_STRING_SHORT])
 AC_SUBST([VENDOR_RELEASE])
 AC_SUBST([VENDOR_MAN_VERSION])
-
+AC_SUBST([XORG_DATE])
 AC_DEFINE(DDXOSINIT, 1, [Use OsVendorInit])
 AC_DEFINE(SERVER_LOCK, 1, [Use a lock to prevent multiple servers on a display])
 AC_DEFINE(SMART_SCHEDULE, 1, [Include time-based scheduler])
@@ -925,7 +920,19 @@ AC_DEFINE([SVR4],1,[Define to 1 on systems derived from System V Release 4])
 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])
 
@@ -1099,6 +1106,61 @@ dnl has it in libc), or if libdl is needed to get it.
 		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_DEFINE(ROOTLESS,1,[Build Rootless code])
+		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"
@@ -1240,11 +1302,14 @@ int main () {
 
 	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"
@@ -1257,7 +1322,7 @@ int main () {
 		;;
 	  x86_64*|amd64*)
 		case $host_os in
-		  freebsd*|kfreebsd*-gnu)
+		  darwin*|freebsd*|kfreebsd*-gnu)
 			# FreeBSD uses the system pci interface
 			;;
 		  *)
@@ -1297,7 +1362,13 @@ int main () {
 			GCC_WARNINGS="${GCC_WARNINGS} -Werror"
 		fi
 		XSERVER_CFLAGS="$GCC_WARNINGS $XSERVER_CFLAGS"
-		LD_EXPORT_SYMBOLS_FLAG="-rdynamic"
+		case $host_os in
+		  darwin*) ;; # Symbols are exported by default, no need
+		  # to do anything special. I think that the following
+		  # is wrong anyway when using libtool. Should be using
+		  # the libtool flag -export-dynamic?
+		  *)LD_EXPORT_SYMBOLS_FLAG="-rdynamic" ;;
+		esac
 	fi
 	case $host_os in
 		openbsd*)
@@ -1338,6 +1409,26 @@ int main () {
 	AC_SUBST([extdir])
 	AC_SUBST([logdir])
 fi
+
+if test "x$XF86VIDMODE" = xyes; then
+	AC_DEFINE(XF86VIDMODE, 1, [Support XFree86 Video Mode extension])
+fi
+
+if test "x$XF86MISC" = xyes; then
+	AC_DEFINE(XF86MISC, 1, [Support XFree86 miscellaneous extensions])
+fi
+# 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])
+
 AM_CONDITIONAL([XORG], [test "x$XORG" = xyes])
 AM_CONDITIONAL([XORG_BUS_LINUXPCI], [test "x$xorg_bus_linuxpci" = xyes])
 AM_CONDITIONAL([XORG_BUS_FREEBSDPCI], [test "x$xorg_bus_freebsdpci" = xyes])
@@ -1355,6 +1446,8 @@ 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]) 
 
 dnl Xprint DDX
 
@@ -1364,7 +1457,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 $XKB_LIB $XKB_STUB_LIB $XPRINT_EXTENSIONS $MI_LIB $MIEXT_DAMAGE_LIB $CWRAP_LIB $OS_LIB"
+	XPRINT_LIBS="$DIX_LIB $XPRINT_LIBS $XKB_LIB $XKB_STUB_LIB $XPRINT_EXTENSIONS $MI_LIB $MIEXT_DAMAGE_LIB $CWRAP_LIB $OS_LIB"
 	AC_SUBST([XPRINT_CFLAGS])
 	AC_SUBST([XPRINT_LIBS])
 
@@ -1409,7 +1502,6 @@ if test "x$XPRINT" = xyes; then
 fi
 AM_CONDITIONAL(XP_USE_FREETYPE, [test "x$XPRINT" = xyes && test "x$XP_USE_FREETYPE" = xyes])
 
-
 dnl XWin DDX
 
 AC_MSG_CHECKING([whether to build XWin DDX])
@@ -1595,8 +1687,11 @@ AC_DEFINE_DIR(XKM_OUTPUT_DIR, XKBOUTPUT, [Path to XKB output dir])
 
 AC_SUBST(XKB_COMPILED_DIR)
 
+AM_CONDITIONAL(DGA, [test "x$DGA" = xyes])
+if test "x$DGA" = xyes; then
+	AC_DEFINE(DGA, 1, [Support DGA extension])
+fi
 dnl and the rest of these are generic, so they're in config.h
-AC_DEFINE(XFreeXDGA, 1, [Build XDGA support])
 AC_DEFINE(XResExtension, 1, [Build XRes extension])
 
 AC_TRY_COMPILE([
@@ -1678,6 +1773,7 @@ XORG_RELEASE_VERSION
 AC_OUTPUT([
 Makefile
 GL/Makefile
+GL/apple/Makefile
 GL/glx/Makefile
 GL/mesa/Makefile
 GL/mesa/array_cache/Makefile
@@ -1710,6 +1806,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
@@ -1787,6 +1885,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/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 560cc3a..54f3f33 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -235,7 +235,6 @@ glxMesa_la_DEPENDENCIES = XDarwinApp
 endif
 
 endif
-if HAVE_X_PLUGIN
 
 xprplugindir = $(darwinappdir)/Contents/Resources/xpr.bundle/Contents/MacOS
 xprplugin_LTLIBRARIES =
@@ -259,9 +258,6 @@ xpr_la_LDFLAGS = -shrext '' -Wl,-framework,ApplicationServices \
 		-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_SOURCES =
@@ -293,10 +289,6 @@ glxAGL_la_LDFLAGS = -shrext '' \
 		-module -avoid-version -no-undefined
 glxAGL_la_DEPENDENCIES = XDarwinApp	
 
-
-
-endif
-
 man1_MANS = XDarwin.man
 
 uninstall-hook:
diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
index bc6d4fc..0d236be 100644
--- a/hw/darwin/quartz/Makefile.am
+++ b/hw/darwin/quartz/Makefile.am
@@ -5,10 +5,9 @@ AM_OBJCFLAGS = @XORG_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)
 
diff --git a/mi/miinitext.c b/mi/miinitext.c
index 8fd8c9c..fa00674 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -338,14 +338,16 @@ extern void XFree86DGAExtensionInit(INITARGS);
 #endif
 #ifdef GLXEXT
 typedef struct __GLXprovider __GLXprovider;
+#if defined(__DARWIN__) && !defined(INXQUARTZ)
+extern __GLXprovider* __DarwinglXMesaProvider;
+extern void DarwinGlxPushProvider(__GLXprovider *impl);
+extern void DarwinGlxExtensionInit(INITARGS);
+extern void DarwinGlxWrapInitVisuals(miInitVisualsProcPtr *);
+#else
 extern __GLXprovider __glXMesaProvider;
 extern void GlxPushProvider(__GLXprovider *impl);
-#ifndef __DARWIN__
 extern void GlxExtensionInit(INITARGS);
 extern void GlxWrapInitVisuals(miInitVisualsProcPtr *);
-#else
-extern void DarwinGlxExtensionInit(INITARGS);
-extern void DarwinGlxWrapInitVisuals(miInitVisualsProcPtr *);
 #endif
 #endif
 #ifdef XF86DRI
@@ -630,12 +632,12 @@ InitExtensions(argc, argv)
 #endif
 #endif
 #ifdef GLXEXT
-
+#if defined(__DARWIN__) && !defined(INXQUARTZ)
+    DarwinGlxPushProvider(__DarwinglXMesaProvider);
+    if (!noGlxExtension) DarwinGlxExtensionInit();
+#else
     GlxPushProvider(&__glXMesaProvider);
-#ifndef __DARWIN__
     if (!noGlxExtension) GlxExtensionInit();
-#else
-    if (!noGlxExtension) DarwinGlxExtensionInit();
 #endif
 #endif
 #ifdef XFIXES
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/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/connection.c b/os/connection.c
index 96ad119..fb47f3d 100644
--- a/os/connection.c
+++ b/os/connection.c
@@ -74,6 +74,7 @@ SOFTWARE.
 #define TRANS_SERVER
 #define TRANS_REOPEN
 #include <X11/Xtrans/Xtrans.h>
+#include <X11/Xtrans/Xtransint.h>
 #include <errno.h>
 #include <signal.h>
 #include <stdio.h>
@@ -670,9 +671,15 @@ ClientAuthorized(ClientPtr client,
     XID	 		auth_id;
     char	 	*reason = NULL;
     XtransConnInfo	trans_conn;
-
+    struct sockaddr     *saddr;
     priv = (OsCommPtr)client->osPrivate;
     trans_conn = priv->trans_conn;
+    saddr = (struct sockaddr *) (trans_conn->addr);
+    
+    /* Allow any client to connect without authorization on a launchd socket,
+       because it is securely created -- this prevents a race condition on launch */
+    if (saddr->sa_len > 11 && saddr->sa_family == AF_UNIX &&
+	!strncmp(saddr->sa_data, "/tmp/launch", 11))  goto done;
 
     auth_id = CheckAuthorization (proto_n, auth_proto,
 				  string_n, auth_string, client, &reason);
@@ -721,6 +728,7 @@ ClientAuthorized(ClientPtr client,
 	}
     }
     priv->auth_id = auth_id;
+done:
     priv->conn_time = 0;
 
 #ifdef XDMCP
commit 21f35c1b7c209312bc5df84787b0aa03154f1768
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sat Oct 27 04:17:29 2007 -0700

    added missing "f" flag to jump target in asm blocks
    (This sometimes prevents builds on Darwin, but is apparently
    universally incorrect.  I just work here.)

diff --git a/fb/fbpict.c b/fb/fbpict.c
index 38afbea..613e652 100644
--- a/fb/fbpict.c
+++ b/fb/fbpict.c
@@ -1443,7 +1443,7 @@ static unsigned int detectCPUFeatures(void) {
              "pop %%eax\n"
              "mov $0x0, %%edx\n"
              "xor %%ecx, %%eax\n"
-             "jz 1\n"
+             "jz 1f\n"
 
              "mov $0x00000000, %%eax\n"
 	     "push %%ebx\n"
@@ -1486,7 +1486,7 @@ static unsigned int detectCPUFeatures(void) {
                     "cpuid\n"
                     "xor %%edx, %%edx\n"
                     "cmp $0x1, %%eax\n"
-                    "jge 2\n"
+                    "jge 2f\n"
                     "mov $0x80000001, %%eax\n"
                     "cpuid\n"
                     "2:\n"
commit b79ecaba29a48fc1f3365817a7150a0824fe3683
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sat Oct 27 02:22:56 2007 -0700

    removed CVS Id tags

diff --git a/hw/darwin/XDarwin.man b/hw/darwin/XDarwin.man
index eb1b9dc..143fb7c 100644
--- a/hw/darwin/XDarwin.man
+++ b/hw/darwin/XDarwin.man
@@ -1,4 +1,3 @@
-.\" $XFree86: xc/programs/Xserver/hw/darwin/XDarwin.man,v 1.3 2001/09/23 23:02:37 torrey Exp $
 .\"
 .TH XDARWIN 1 __vendorversion__
 .SH NAME
diff --git a/hw/darwin/apple/Xquartz.man b/hw/darwin/apple/Xquartz.man
index edac30e..37a7f1a 100644
--- a/hw/darwin/apple/Xquartz.man
+++ b/hw/darwin/apple/Xquartz.man
@@ -1,5 +1,3 @@
-.\" $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
diff --git a/hw/darwin/bundle/Dutch.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/Dutch.lproj/XDarwinHelp.html.cpp
index 1113b8a..4b8e6f5 100644
--- a/hw/darwin/bundle/Dutch.lproj/XDarwinHelp.html.cpp
+++ b/hw/darwin/bundle/Dutch.lproj/XDarwinHelp.html.cpp
@@ -1,5 +1,3 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp,v 1.2 2001/11/04 07:02:28 torrey Exp $ -->
-
 <html>
 <head>
 <title>XDarwin Help</title>
diff --git a/hw/darwin/bundle/English.lproj/InfoPlist.strings.cpp b/hw/darwin/bundle/English.lproj/InfoPlist.strings.cpp
index aeb2103..268b800 100644
--- a/hw/darwin/bundle/English.lproj/InfoPlist.strings.cpp
+++ b/hw/darwin/bundle/English.lproj/InfoPlist.strings.cpp
@@ -1,5 +1,4 @@
 /* English versions of the Info.plist keys; used by most localizations. */
 /* Most of these are set in the target application settings. */
-/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/InfoPlist.strings.cpp,v 1.3 2002/07/17 01:24:55 torrey Exp $ */
 
 NSHumanReadableCopyright = __quote__ X_VENDOR_NAME X_VERSION __quote__;
diff --git a/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp
index 5996285..db33670 100644
--- a/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp
+++ b/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp
@@ -1,5 +1,3 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp,v 1.1 2001/05/21 01:42:17 torrey Exp $ -->
-
 <html>
 <head>
 <title>XDarwin Help</title>
diff --git a/hw/darwin/bundle/French.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/French.lproj/XDarwinHelp.html.cpp
index 2a14793..512416b 100644
--- a/hw/darwin/bundle/French.lproj/XDarwinHelp.html.cpp
+++ b/hw/darwin/bundle/French.lproj/XDarwinHelp.html.cpp
@@ -1,5 +1,3 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp,v 1.2 2001/11/04 07:02:28 torrey Exp $ -->
-
 <html>
 <head><META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
 <title>XDarwin Help</title>
diff --git a/hw/darwin/bundle/German.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/German.lproj/XDarwinHelp.html.cpp
index 5996285..db33670 100644
--- a/hw/darwin/bundle/German.lproj/XDarwinHelp.html.cpp
+++ b/hw/darwin/bundle/German.lproj/XDarwinHelp.html.cpp
@@ -1,5 +1,3 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp,v 1.1 2001/05/21 01:42:17 torrey Exp $ -->
-
 <html>
 <head>
 <title>XDarwin Help</title>
diff --git a/hw/darwin/bundle/Portuguese.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/Portuguese.lproj/XDarwinHelp.html.cpp
index 7ef1ba5..6800171 100644
--- a/hw/darwin/bundle/Portuguese.lproj/XDarwinHelp.html.cpp
+++ b/hw/darwin/bundle/Portuguese.lproj/XDarwinHelp.html.cpp
@@ -1,5 +1,3 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp,v 1.2 2001/11/04 07:02:28 torrey Exp $ --><html><body>
-
 <head>
 <title>XDarwin Help</title>
 </head>
diff --git a/hw/darwin/bundle/Spanish.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/Spanish.lproj/XDarwinHelp.html.cpp
index 5cd2786..a79e6f9 100644
--- a/hw/darwin/bundle/Spanish.lproj/XDarwinHelp.html.cpp
+++ b/hw/darwin/bundle/Spanish.lproj/XDarwinHelp.html.cpp
@@ -1,5 +1,3 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp,v 1.2 2001/11/04 07:02:28 torrey Exp $ -->
-
 <html>
 <head>
 <title>XDarwin Ayuda</title>
diff --git a/hw/darwin/bundle/Swedish.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/Swedish.lproj/XDarwinHelp.html.cpp
index 4210878..ab940ec 100644
--- a/hw/darwin/bundle/Swedish.lproj/XDarwinHelp.html.cpp
+++ b/hw/darwin/bundle/Swedish.lproj/XDarwinHelp.html.cpp
@@ -1,5 +1,3 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp,v 1.2 2001/11/04 07:02:28 torrey Exp $ -->
-
 <html>
 <head>
 <title>XDarwin Help</title>
diff --git a/hw/darwin/bundle/ko.lproj/XDarwinHelp.html.cpp b/hw/darwin/bundle/ko.lproj/XDarwinHelp.html.cpp
index 5996285..db33670 100644
--- a/hw/darwin/bundle/ko.lproj/XDarwinHelp.html.cpp
+++ b/hw/darwin/bundle/ko.lproj/XDarwinHelp.html.cpp
@@ -1,5 +1,3 @@
-<!-- $XFree86: xc/programs/Xserver/hw/darwin/bundle/English.lproj/XDarwinHelp.html.cpp,v 1.1 2001/05/21 01:42:17 torrey Exp $ -->
-
 <html>
 <head>
 <title>XDarwin Help</title>
diff --git a/hw/darwin/bundle/startXClients.cpp b/hw/darwin/bundle/startXClients.cpp
index 51cdb5c..f812dbf 100644
--- a/hw/darwin/bundle/startXClients.cpp
+++ b/hw/darwin/bundle/startXClients.cpp
@@ -2,8 +2,6 @@ XCOMM!/bin/sh
 
 XCOMM This script is used by XDarwin to start X clients when XDarwin is
 XCOMM launched from the Finder.
-XCOMM
-XCOMM $XFree86: $
 
 userclientrc=$HOME/.xinitrc
 sysclientrc=XINITDIR/xinitrc
diff --git a/hw/darwin/quartz/Preferences.m b/hw/darwin/quartz/Preferences.m
index eb78fd3..b5eeedd 100644
--- a/hw/darwin/quartz/Preferences.m
+++ b/hw/darwin/quartz/Preferences.m
@@ -30,7 +30,7 @@
  * sale, use or other dealings in this Software without prior written
  * 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
diff --git a/hw/darwin/quartz/XApplication.h b/hw/darwin/quartz/XApplication.h
index a2622e0..2f2b223 100644
--- a/hw/darwin/quartz/XApplication.h
+++ b/hw/darwin/quartz/XApplication.h
@@ -30,7 +30,6 @@
  * sale, use or other dealings in this Software without prior written
  * authorization.
  */
-/* $XFree86: $ */
 
 #import <Cocoa/Cocoa.h>
 
diff --git a/hw/darwin/quartz/XApplication.m b/hw/darwin/quartz/XApplication.m
index e0ee8d9..de32d38 100644
--- a/hw/darwin/quartz/XApplication.m
+++ b/hw/darwin/quartz/XApplication.m
@@ -30,7 +30,6 @@
  * sale, use or other dealings in this Software without prior written
  * authorization.
  */
-/* $XFree86: $ */
 
 #import "XApplication.h"
 
diff --git a/hw/darwin/quartz/XDarwinStartup.man b/hw/darwin/quartz/XDarwinStartup.man
index 9bf7dfa..1ad3bbc 100644
--- a/hw/darwin/quartz/XDarwinStartup.man
+++ b/hw/darwin/quartz/XDarwinStartup.man
@@ -1,4 +1,3 @@
-.\" $XFree86: xc/programs/Xserver/hw/darwin/bundle/XDarwinStartup.man,v 1.1 2002/02/05 19:16:14 torrey Exp $
 .TH XDarwinStartup 1
 .SH NAME
 XDarwinStartup - Startup program for the XDarwin X window server
diff --git a/hw/darwin/quartz/cr/XView.m b/hw/darwin/quartz/cr/XView.m
index 8bcd1a7..488f88a 100644
--- a/hw/darwin/quartz/cr/XView.m
+++ b/hw/darwin/quartz/cr/XView.m
@@ -29,7 +29,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * 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
diff --git a/hw/darwin/quartz/cr/cr.h b/hw/darwin/quartz/cr/cr.h
index 94133e4..0ebad5d 100644
--- a/hw/darwin/quartz/cr/cr.h
+++ b/hw/darwin/quartz/cr/cr.h
@@ -1,7 +1,6 @@
 /*
  * Internal definitions of the Cocoa rootless implementation
- */
-/*
+ *
  * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
@@ -26,7 +25,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86$ */
 
 #ifndef _CR_H
 #define _CR_H
diff --git a/hw/darwin/quartz/cr/crAppleWM.m b/hw/darwin/quartz/cr/crAppleWM.m
index 259c2d8..da05fed 100644
--- a/hw/darwin/quartz/cr/crAppleWM.m
+++ b/hw/darwin/quartz/cr/crAppleWM.m
@@ -1,7 +1,6 @@
 /*
  * Cocoa rootless implementation functions for AppleWM extension
- */
-/*
+ *
  * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
@@ -26,7 +25,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * 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
diff --git a/hw/darwin/quartz/cr/crFrame.m b/hw/darwin/quartz/cr/crFrame.m
index 326910b..ca1ef3d 100644
--- a/hw/darwin/quartz/cr/crFrame.m
+++ b/hw/darwin/quartz/cr/crFrame.m
@@ -1,7 +1,6 @@
 /*
  * Cocoa rootless implementation frame functions
- */
-/*
+ *
  * Copyright (c) 2001 Greg Parker. All Rights Reserved.
  * Copyright (c) 2002-2003 Torrey T. Lyons. All Rights Reserved.
  *
@@ -27,8 +26,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/cr/crFrame.m,v 1.3 2004/10/08 00:35:05 torrey 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
diff --git a/hw/darwin/quartz/cr/crScreen.m b/hw/darwin/quartz/cr/crScreen.m
index b78d1ea..9c26a76 100644
--- a/hw/darwin/quartz/cr/crScreen.m
+++ b/hw/darwin/quartz/cr/crScreen.m
@@ -1,8 +1,6 @@
-/* $XdotOrg: xc/programs/Xserver/hw/darwin/quartz/cr/crScreen.m,v 1.4 2004/08/12 20:24:36 torrey Exp $ */
 /*
  * Cocoa rootless implementation initialization
- */
-/*
+ *
  * Copyright (c) 2001 Greg Parker. All Rights Reserved.
  * Copyright (c) 2002-2004 Torrey T. Lyons. All Rights Reserved.
  *
@@ -28,7 +26,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * 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
diff --git a/hw/darwin/quartz/fullscreen/fullscreen.c b/hw/darwin/quartz/fullscreen/fullscreen.c
index ed7f4c8..2116ebd 100644
--- a/hw/darwin/quartz/fullscreen/fullscreen.c
+++ b/hw/darwin/quartz/fullscreen/fullscreen.c
@@ -25,8 +25,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/fullscreen/fullscreen.c,v 1.4 2005/07/01 22:43:08 daniels Exp $ */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/fullscreen/fullscreen.c,v 1.3 2003/11/27 01:59:53 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/fullscreen/quartzCursor.c b/hw/darwin/quartz/fullscreen/quartzCursor.c
index 60a4c4d..a5483ee 100644
--- a/hw/darwin/quartz/fullscreen/quartzCursor.c
+++ b/hw/darwin/quartz/fullscreen/quartzCursor.c
@@ -2,8 +2,6 @@
  *
  * Support for using the Quartz Window Manager cursor
  *
- **************************************************************/
-/*
  * Copyright (c) 2001-2003 Torrey T. Lyons and Greg Parker.
  *                 All Rights Reserved.
  *
@@ -29,7 +27,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCursor.c,v 1.5 2003/01/23 00:34:26 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/fullscreen/quartzCursor.h b/hw/darwin/quartz/fullscreen/quartzCursor.h
index efcc443..56a0209 100644
--- a/hw/darwin/quartz/fullscreen/quartzCursor.h
+++ b/hw/darwin/quartz/fullscreen/quartzCursor.h
@@ -2,8 +2,7 @@
  * quartzCursor.h
  *
  * External interface for Quartz hardware cursor
- */
-/*
+ *
  * Copyright (c) 2001 Torrey T. Lyons and Greg Parker.
  *                 All Rights Reserved.
  *
@@ -29,7 +28,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCursor.h,v 1.1 2002/03/28 02:21:19 torrey Exp $ */
 
 #ifndef QUARTZCURSOR_H
 #define QUARTZCURSOR_H
diff --git a/hw/darwin/quartz/keysym2ucs.c b/hw/darwin/quartz/keysym2ucs.c
index 98b8b6f..8626ebc 100644
--- a/hw/darwin/quartz/keysym2ucs.c
+++ b/hw/darwin/quartz/keysym2ucs.c
@@ -1,4 +1,4 @@
-/* $XFree86: $
+/* 
  *
  * This module converts keysym values into the corresponding ISO 10646
  * (UCS, Unicode) values.
diff --git a/hw/darwin/quartz/keysym2ucs.h b/hw/darwin/quartz/keysym2ucs.h
index c7ff6f3..e167d6a 100644
--- a/hw/darwin/quartz/keysym2ucs.h
+++ b/hw/darwin/quartz/keysym2ucs.h
@@ -1,5 +1,4 @@
-/* $XFree86: $
- *
+/* 
  * This module converts keysym values into the corresponding ISO 10646
  * (UCS, Unicode) values.
  *
diff --git a/hw/darwin/quartz/pseudoramiX.c b/hw/darwin/quartz/pseudoramiX.c
index 66b9662..5c5d342 100644
--- a/hw/darwin/quartz/pseudoramiX.c
+++ b/hw/darwin/quartz/pseudoramiX.c
@@ -32,7 +32,6 @@ shall not be used in advertising or otherwise to promote the sale, use or other
 dealings in this Software without prior written authorization from Digital
 Equipment Corporation.
 ******************************************************************/
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/pseudoramiX.c,v 1.4 2004/07/02 01:30:33 torrey Exp $ */
 
 #include "pseudoramiX.h"
 #ifdef HAVE_XORG_CONFIG_H
diff --git a/hw/darwin/quartz/pseudoramiX.h b/hw/darwin/quartz/pseudoramiX.h
index c294336..df5010d 100644
--- a/hw/darwin/quartz/pseudoramiX.h
+++ b/hw/darwin/quartz/pseudoramiX.h
@@ -1,7 +1,6 @@
 /*
  * Minimal implementation of PanoramiX/Xinerama
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/pseudoramiX.h,v 1.3 2004/07/02 01:30:33 torrey Exp $ */
 
 extern int noPseudoramiXExtension;
 
diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index baeba8f..ac555ec 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -1,10 +1,7 @@
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/quartz.c,v 1.4 2005/07/01 22:43:07 daniels Exp $ */
-/**************************************************************
+/*
  *
  * Quartz-specific support for the Darwin X Server
  *
- **************************************************************/
-/*
  * Copyright (c) 2001-2004 Greg Parker and Torrey T. Lyons.
  *                 All Rights Reserved.
  *
@@ -30,7 +27,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartz.c,v 1.16 2004/07/02 01:30:33 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/quartz.h b/hw/darwin/quartz/quartz.h
index c83579c..fa7499d 100644
--- a/hw/darwin/quartz/quartz.h
+++ b/hw/darwin/quartz/quartz.h
@@ -3,8 +3,7 @@
  *
  * External interface of the Quartz display modes seen by the generic, mode
  * independent parts of the Darwin X server.
- */
-/*
+ *
  * Copyright (c) 2001-2003 Greg Parker and Torrey T. Lyons.
  *                 All Rights Reserved.
  *
@@ -30,8 +29,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/quartz.h,v 1.4 2005/07/01 22:43:07 daniels Exp $ */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartz.h,v 1.7 2003/11/12 20:21:51 torrey Exp $ */
 
 #ifndef _QUARTZ_H
 #define _QUARTZ_H
diff --git a/hw/darwin/quartz/quartzAudio.c b/hw/darwin/quartz/quartzAudio.c
index 03f9cca..1980cd2 100644
--- a/hw/darwin/quartz/quartzAudio.c
+++ b/hw/darwin/quartz/quartzAudio.c
@@ -35,7 +35,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzAudio.c,v 1.1 2002/03/28 02:21:18 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/quartzAudio.h b/hw/darwin/quartz/quartzAudio.h
index e20c21a..c406bbc 100644
--- a/hw/darwin/quartz/quartzAudio.h
+++ b/hw/darwin/quartz/quartzAudio.h
@@ -28,7 +28,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/quartzAudio.h,v 1.2 2001/04/01 20:45:43 tsi Exp $ */
 
 #ifndef _QUARTZAUDIO_H
 #define _QUARTZAUDIO_H
diff --git a/hw/darwin/quartz/quartzCocoa.m b/hw/darwin/quartz/quartzCocoa.m
index a9c89c0..2e7b86b 100644
--- a/hw/darwin/quartz/quartzCocoa.m
+++ b/hw/darwin/quartz/quartzCocoa.m
@@ -1,4 +1,3 @@
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/quartzCocoa.m,v 1.3 2004/07/30 19:12:17 torrey Exp $ */
 /**************************************************************
  *
  * Quartz-specific support for the Darwin X Server
@@ -7,8 +6,7 @@
  * This file is separate from the parts of Quartz support
  * that use X include files to avoid symbol collisions.
  *
- **************************************************************/
-/*
+ *
  * Copyright (c) 2001-2004 Torrey T. Lyons and Greg Parker.
  *                 All Rights Reserved.
  *
@@ -34,7 +32,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * 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
diff --git a/hw/darwin/quartz/quartzCommon.h b/hw/darwin/quartz/quartzCommon.h
index 2fd79eb..f5dff66 100644
--- a/hw/darwin/quartz/quartzCommon.h
+++ b/hw/darwin/quartz/quartzCommon.h
@@ -1,4 +1,3 @@
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/quartzCommon.h,v 1.4 2005/07/01 22:43:07 daniels Exp $ */
 /*
  * quartzCommon.h
  *
@@ -32,7 +31,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCommon.h,v 1.15 2004/06/08 22:58:10 torrey Exp $ */
 
 #ifndef _QUARTZCOMMON_H
 #define _QUARTZCOMMON_H
diff --git a/hw/darwin/quartz/quartzCursor.c b/hw/darwin/quartz/quartzCursor.c
index 2f39887..a5483ee 100644
--- a/hw/darwin/quartz/quartzCursor.c
+++ b/hw/darwin/quartz/quartzCursor.c
@@ -2,8 +2,6 @@
  *
  * Support for using the Quartz Window Manager cursor
  *
- **************************************************************/
-/*
  * Copyright (c) 2001-2003 Torrey T. Lyons and Greg Parker.
  *                 All Rights Reserved.
  *
@@ -29,7 +27,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCursor.c,v 1.4 2002/11/19 23:01:30 torrey Exp $ */
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
diff --git a/hw/darwin/quartz/quartzCursor.h b/hw/darwin/quartz/quartzCursor.h
index e847f8c..56a0209 100644
--- a/hw/darwin/quartz/quartzCursor.h
+++ b/hw/darwin/quartz/quartzCursor.h
@@ -2,8 +2,7 @@
  * quartzCursor.h
  *
  * External interface for Quartz hardware cursor
- */
-/*
+ *
  * Copyright (c) 2001 Torrey T. Lyons and Greg Parker.
  *                 All Rights Reserved.
  *
@@ -29,7 +28,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/quartzCursor.h,v 1.2 2001/09/23 04:04:49 torrey Exp $ */
 
 #ifndef QUARTZCURSOR_H
 #define QUARTZCURSOR_H
diff --git a/hw/darwin/quartz/quartzKeyboard.c b/hw/darwin/quartz/quartzKeyboard.c
index d23b68e..b330793 100644
--- a/hw/darwin/quartz/quartzKeyboard.c
+++ b/hw/darwin/quartz/quartzKeyboard.c
@@ -1,6 +1,5 @@
 /*
    quartzKeyboard.c
-   $Id$
 
    Code to build a keymap using the Carbon Keyboard Layout API,
    which is supported on Mac OS X 10.2 and newer.
@@ -32,7 +31,6 @@
    promote the sale, use or other dealings in this Software without
    prior written authorization.
 */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzKeyboard.c,v 1.1 2003/11/01 08:13:08 torrey Exp $ */
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
diff --git a/hw/darwin/quartz/quartzPasteboard.c b/hw/darwin/quartz/quartzPasteboard.c
index 7ae2e33..a3536fc 100644
--- a/hw/darwin/quartz/quartzPasteboard.c
+++ b/hw/darwin/quartz/quartzPasteboard.c
@@ -29,7 +29,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/quartzPasteboard.c,v 1.3 2001/09/23 04:04:49 torrey Exp $ */
 
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
diff --git a/hw/darwin/quartz/quartzPasteboard.h b/hw/darwin/quartz/quartzPasteboard.h
index 296c52c..afcb6e5 100644
--- a/hw/darwin/quartz/quartzPasteboard.h
+++ b/hw/darwin/quartz/quartzPasteboard.h
@@ -29,7 +29,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/quartzPasteboard.h,v 1.1 2001/03/15 22:24:27 torrey Exp $ */
 
 #ifndef _QUARTZPASTEBOARD_H
 #define _QUARTZPASTEBOARD_H
@@ -42,4 +41,4 @@ char * QuartzReadCocoaPasteboard(void);	// caller must free string
 void QuartzWritePasteboard();
 void QuartzWriteCocoaPasteboard(char *text);
 
-#endif	/* _QUARTZPASTEBOARD_H */
\ No newline at end of file
+#endif	/* _QUARTZPASTEBOARD_H */
diff --git a/hw/darwin/quartz/quartzStartup.c b/hw/darwin/quartz/quartzStartup.c
index 4df8f94..f627790 100644
--- a/hw/darwin/quartz/quartzStartup.c
+++ b/hw/darwin/quartz/quartzStartup.c
@@ -2,8 +2,6 @@
  *
  * Startup code for the Quartz Darwin X Server
  *
- **************************************************************/
-/*
  * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
@@ -28,7 +26,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzStartup.c,v 1.8 2003/11/05 00:15:00 torrey Exp $ */
 
 #include <fcntl.h>
 #include <unistd.h>
diff --git a/hw/darwin/quartz/xpr/Xplugin.h b/hw/darwin/quartz/xpr/Xplugin.h
index e2e97b4..a10b1b8 100644
--- a/hw/darwin/quartz/xpr/Xplugin.h
+++ b/hw/darwin/quartz/xpr/Xplugin.h
@@ -1,5 +1,4 @@
 /* Xplugin.h -- windowing API for rootless X11 server
-   $Id$
 
    Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 
@@ -30,7 +29,6 @@
 
    Note that these interfaces are provided solely for the use of the
    X11 server. Any other uses are unsupported and strongly discouraged. */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/Xplugin.h,v 1.2 2003/05/02 00:08:49 torrey Exp $ */
 
 #ifndef XPLUGIN_H
 #define XPLUGIN_H 1
diff --git a/hw/darwin/quartz/xpr/appledri.c b/hw/darwin/quartz/xpr/appledri.c
index 329c0d8..c38157d 100644
--- a/hw/darwin/quartz/xpr/appledri.c
+++ b/hw/darwin/quartz/xpr/appledri.c
@@ -1,4 +1,3 @@
-/* $XFree86: xc/programs/Xserver/GL/dri/xf86dri.c,v 1.10 2000/12/07 20:26:14 dawes Exp $ */
 /**************************************************************************
 
 Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
diff --git a/hw/darwin/quartz/xpr/appledri.h b/hw/darwin/quartz/xpr/appledri.h
index 9c63037..c4e43be 100644
--- a/hw/darwin/quartz/xpr/appledri.h
+++ b/hw/darwin/quartz/xpr/appledri.h
@@ -1,4 +1,3 @@
-/* $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.
diff --git a/hw/darwin/quartz/xpr/appledristr.h b/hw/darwin/quartz/xpr/appledristr.h
index 36a2e89..8649fd3 100644
--- a/hw/darwin/quartz/xpr/appledristr.h
+++ b/hw/darwin/quartz/xpr/appledristr.h
@@ -1,4 +1,3 @@
-/* $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.
diff --git a/hw/darwin/quartz/xpr/dri.c b/hw/darwin/quartz/xpr/dri.c
index c788c20..70efca7 100644
--- a/hw/darwin/quartz/xpr/dri.c
+++ b/hw/darwin/quartz/xpr/dri.c
@@ -1,4 +1,3 @@
-/* $XFree86: xc/programs/Xserver/GL/dri/dri.c,v 1.34 2001/12/10 19:07:19 dawes Exp $ */
 /**************************************************************************
 
 Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
diff --git a/hw/darwin/quartz/xpr/dri.h b/hw/darwin/quartz/xpr/dri.h
index f826167..cf2638a 100644
--- a/hw/darwin/quartz/xpr/dri.h
+++ b/hw/darwin/quartz/xpr/dri.h
@@ -1,4 +1,3 @@
-/* $XFree86: xc/programs/Xserver/GL/dri/dri.h,v 1.18 2001/03/21 16:21:40 dawes Exp $ */
 /**************************************************************************
 
 Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
diff --git a/hw/darwin/quartz/xpr/dristruct.h b/hw/darwin/quartz/xpr/dristruct.h
index 0df8f18..9a3d01c 100644
--- a/hw/darwin/quartz/xpr/dristruct.h
+++ b/hw/darwin/quartz/xpr/dristruct.h
@@ -1,4 +1,3 @@
-/* $XFree86: xc/programs/Xserver/GL/dri/dristruct.h,v 1.10 2001/03/21 16:21:40 dawes Exp $ */
 /**************************************************************************
 
 Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
diff --git a/hw/darwin/quartz/xpr/x-hash.c b/hw/darwin/quartz/xpr/x-hash.c
index 0491a5a..62d1a99 100644
--- a/hw/darwin/quartz/xpr/x-hash.c
+++ b/hw/darwin/quartz/xpr/x-hash.c
@@ -1,5 +1,4 @@
 /* x-hash.c - basic hash tables
-   $Id: x-hash.c,v 1.7 2003/07/17 05:25:44 jharper Exp $
 
    Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 
@@ -27,7 +26,7 @@
    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. */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/x-hash.c,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/xpr/x-hash.h b/hw/darwin/quartz/xpr/x-hash.h
index 97d4cc4..3456dbe 100644
--- a/hw/darwin/quartz/xpr/x-hash.h
+++ b/hw/darwin/quartz/xpr/x-hash.h
@@ -1,5 +1,4 @@
 /* x-hash.h -- basic hash table class
-   $Id$
 
    Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 
@@ -27,7 +26,6 @@
    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. */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/x-hash.h,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
 
 #ifndef X_HASH_H
 #define X_HASH_H 1
diff --git a/hw/darwin/quartz/xpr/x-hook.c b/hw/darwin/quartz/xpr/x-hook.c
index 7a04967..323e373 100644
--- a/hw/darwin/quartz/xpr/x-hook.c
+++ b/hw/darwin/quartz/xpr/x-hook.c
@@ -1,5 +1,4 @@
 /* x-hook.c
-   $Id$
 
    Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
 
@@ -27,7 +26,7 @@
    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. */
-/* $XFree86: $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/xpr/x-hook.h b/hw/darwin/quartz/xpr/x-hook.h
index 0b5e038..392352d 100644
--- a/hw/darwin/quartz/xpr/x-hook.h
+++ b/hw/darwin/quartz/xpr/x-hook.h
@@ -1,5 +1,4 @@
 /* x-hook.h -- lists of function,data pairs to call.
-   $Id$
 
    Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
 
@@ -27,7 +26,6 @@
    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. */
-/* $XFree86: $ */
 
 #ifndef X_HOOK_H
 #define X_HOOK_H 1
diff --git a/hw/darwin/quartz/xpr/x-list.c b/hw/darwin/quartz/xpr/x-list.c
index c87045e..2e74ae8 100644
--- a/hw/darwin/quartz/xpr/x-list.c
+++ b/hw/darwin/quartz/xpr/x-list.c
@@ -1,5 +1,4 @@
 /* x-list.c
-   $Id: x-list.c,v 1.16 2003/07/18 00:52:19 jharper Exp $
 
    Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 
@@ -27,7 +26,7 @@
    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. */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/x-list.c,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/xpr/x-list.h b/hw/darwin/quartz/xpr/x-list.h
index 2b71070..04af024 100644
--- a/hw/darwin/quartz/xpr/x-list.h
+++ b/hw/darwin/quartz/xpr/x-list.h
@@ -1,5 +1,4 @@
 /* x-list.h -- simple list type
-   $Id: x-list.h,v 1.10 2003/07/18 00:52:19 jharper Exp $
 
    Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 
@@ -27,7 +26,6 @@
    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. */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/x-list.h,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
 
 #ifndef X_LIST_H
 #define X_LIST_H 1
diff --git a/hw/darwin/quartz/xpr/xpr.h b/hw/darwin/quartz/xpr/xpr.h
index 5b02c6d..81bb912 100644
--- a/hw/darwin/quartz/xpr/xpr.h
+++ b/hw/darwin/quartz/xpr/xpr.h
@@ -1,7 +1,6 @@
 /*
  * Xplugin rootless implementation
- */
-/*
+ *
  * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
@@ -26,8 +25,6 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/xpr/xpr.h,v 1.3 2005/07/01 22:43:08 daniels Exp $ */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xpr.h,v 1.4 2003/11/12 20:21:52 torrey Exp $ */
 
 #ifndef XPR_H
 #define XPR_H
diff --git a/hw/darwin/quartz/xpr/xprAppleWM.c b/hw/darwin/quartz/xpr/xprAppleWM.c
index 3f5af2c..e67abb6 100644
--- a/hw/darwin/quartz/xpr/xprAppleWM.c
+++ b/hw/darwin/quartz/xpr/xprAppleWM.c
@@ -1,7 +1,6 @@
 /*
  * Xplugin rootless implementation functions for AppleWM extension
- */
-/*
+ *
  * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
  * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
  *
@@ -27,7 +26,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * 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
diff --git a/hw/darwin/quartz/xpr/xprCursor.c b/hw/darwin/quartz/xpr/xprCursor.c
index 9f9abc2..570ef0b 100644
--- a/hw/darwin/quartz/xpr/xprCursor.c
+++ b/hw/darwin/quartz/xpr/xprCursor.c
@@ -2,8 +2,6 @@
  *
  * Xplugin cursor support
  *
- **************************************************************/
-/*
  * Copyright (c) 2001 Torrey T. Lyons and Greg Parker.
  * Copyright (c) 2002 Apple Computer, Inc.
  *                 All Rights Reserved.
@@ -30,7 +28,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xprCursor.c,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/xpr/xprFrame.c b/hw/darwin/quartz/xpr/xprFrame.c
index b141e62..0e3b200 100644
--- a/hw/darwin/quartz/xpr/xprFrame.c
+++ b/hw/darwin/quartz/xpr/xprFrame.c
@@ -1,7 +1,6 @@
 /*
  * Xplugin rootless implementation frame functions
- */
-/*
+ *
  * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
  * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
  *
@@ -27,8 +26,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/xpr/xprFrame.c,v 1.5 2005/07/01 22:43:08 daniels Exp $ */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xprFrame.c,v 1.4 2003/11/12 20:21:52 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/quartz/xpr/xprScreen.c b/hw/darwin/quartz/xpr/xprScreen.c
index 1aebefe..92886fc 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -1,8 +1,6 @@
-/* $XdotOrg: xserver/xorg/hw/darwin/quartz/xpr/xprScreen.c,v 1.6 2005/07/01 22:43:08 daniels Exp $ */
 /*
  * Xplugin rootless implementation screen functions
- */
-/*
+ *
  * Copyright (c) 2002 Apple Computer, Inc. All Rights Reserved.
  * Copyright (c) 2004 Torrey T. Lyons. All Rights Reserved.
  *
@@ -28,7 +26,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xprScreen.c,v 1.11 2004/07/15 18:53:25 torrey Exp $ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
diff --git a/hw/darwin/utils/README.txt b/hw/darwin/utils/README.txt
index fb6d439..1dd6479 100644
--- a/hw/darwin/utils/README.txt
+++ b/hw/darwin/utils/README.txt
@@ -105,7 +105,3 @@ The implementation of dumpkeymap is based upon information gathered on
 September 3, 1997 by Eric Sunshine <sunshine at sunshineco.com> and Paul S.
 McCarthy <zarnuk at zarnuk.com> during an effort to reverse engineer the format
 of the NeXT .keymapping file.
-
-
-
-$XFree86: xc/programs/Xserver/hw/darwin/utils/README.txt,v 1.1 2000/12/01 19:47:39 dawes Exp $
diff --git a/hw/darwin/utils/dumpkeymap.c b/hw/darwin/utils/dumpkeymap.c
index c3e66e3..6a8b8b1 100644
--- a/hw/darwin/utils/dumpkeymap.c
+++ b/hw/darwin/utils/dumpkeymap.c
@@ -1,4 +1,3 @@
-// $XFree86: dumpkeymap.c,v 1.3 2000/12/05 21:18:34 dawes Exp $
 //=============================================================================
 //
 // Copyright (C) 1999,2000 by Eric Sunshine <sunshine at sunshineco.com>
diff --git a/hw/darwin/utils/dumpkeymap.man b/hw/darwin/utils/dumpkeymap.man
index 90a2cd0..02b09e6 100644
--- a/hw/darwin/utils/dumpkeymap.man
+++ b/hw/darwin/utils/dumpkeymap.man
@@ -30,8 +30,6 @@
 //
 //=============================================================================
 //
-// $XFree86$
-//
 ..
 .ig
 //-----------------------------------------------------------------------------
commit e6253d49e07ab38ad3f25731f43cc53a8aabdd9a
Author: Ben Byer <bbyer at bbyer.local>
Date:   Sat Oct 27 01:38:31 2007 -0700

    merged the rest of Apple patches to xserver

diff --git a/hw/darwin/Makefile.am b/hw/darwin/Makefile.am
index 542bfdb..560cc3a 100644
--- a/hw/darwin/Makefile.am
+++ b/hw/darwin/Makefile.am
@@ -1,52 +1,314 @@
+noinst_LIBRARIES = libdarwinShared.a
+libdarwin_XINPUT_SRCS = darwinXinput.c
+
+AM_CFLAGS = @XORG_CFLAGS@
+INCLUDES = @XORG_INCS@ -I../../miext/rootless
+
+DEFS = @DEFS@ -DUSE_NEW_CLUT
+
+if XQUARTZ
+XQUARTZ_SUBDIRS = bundle quartz
+endif
+
+SUBDIRS = \
+	  iokit \
+	  $(XQUARTZ_SUBDIRS) \
+	  utils \
+	  .
+
+darwinappdir = /Applications/Utilities/XDarwin.app
+
+libdarwinShared_a_SOURCES = darwin.c \
+			  darwinEvents.c \
+			  darwinKeyboard.c \
+			  $(darwin_XINPUT_SRCS) 
+
+bin_PROGRAMS = 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/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 \
+		$(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
+
+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
+
+Xquartz_LDFLAGS =  \
+                 -XCClinker -Objc \
+                 -Wl,-u,_miDCInitialize \
+                 -Wl,-framework,Carbon \
+	         -L/System/Library/Frameworks/OpenGL.framework/Libraries -lGL \
+                 -Wl,-framework,OpenGL \
+                 -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
+Xquartz_OBJCFLAGS = -DINXQUARTZ -DHAS_CG_MACH_PORT -DHAS_KL_API  -DHAVE_XORG_CONFIG_H
+
+if XQUARTZ
+macosdir = $(darwinappdir)/Contents/MacOS
+
+DEFS += -DDARWIN_WITH_QUARTZ -DXFree86Server
+
+macos_PROGRAMS = 
+macos_SCRIPTS = x11app
+
+x11app:
+	cd apple && xcodebuild
+
+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)/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_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_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_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_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_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_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:
+	cd apple && xcodebuild install
+	cd launcher && xcodebuild install
+
 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 +316,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..c3b21c1 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"
@@ -79,7 +83,6 @@ int                     darwinScreenIndex = 0;
 io_connect_t            darwinParamConnect = 0;
 int                     darwinEventReadFD = -1;
 int                     darwinEventWriteFD = -1;
-int                     darwinMouseAccelChange = 1;
 int                     darwinFakeButtons = 0;
 
 // location of X11's (0,0) point in global screen coordinates
@@ -123,81 +126,16 @@ const int NUMFORMATS = sizeof(formats)/sizeof(formats[0]);
 #ifndef PRE_RELEASE
 #define PRE_RELEASE XORG_VERSION_SNAP
 #endif
+#ifndef BUILD_DATE
+#define BUILD_DATE ""
+#endif
 
 void
 DarwinPrintBanner()
 {
-#if PRE_RELEASE
-  ErrorF("\n"
-    "This is a pre-release version of the " XVENDORNAME " X11.\n"
-    "Portions of this release are based on XFree86 4.4RC2 and selected\n"
-    "files from XFree86 4.4RC3. It is not supported in any way.\n"
-    "Bugs may be filed in the bugzilla at http://bugs.freedesktop.org/.\n"
-    "Select the \"xorg\" product for bugs you find in this release.\n"
-    "Before reporting bugs in pre-release versions please check the\n"
-    "latest version in the " XVENDORNAME " \"monolithic tree\" CVS\n"
-    "repository hosted at http://www.freedesktop.org/Software/xorg/");
-#endif
-#if XORG_VERSION_SNAP > 0
-  ErrorF(".%d", XORG_VERSION_SNAP);
-#endif
-
-#if XORG_VERSION_SNAP >= 900
-  ErrorF(" (%d.%d.0 RC %d)", XORG_VERSION_MAJOR, XORG_VERSION_MINOR + 1,
-				XORG_VERSION_SNAP - 900);
-#endif
-
-#ifdef XORG_CUSTOM_VERSION
-  ErrorF(" (%s)", XF86_CUSTOM_VERSION);
-#endif
-  ErrorF("\nRelease Date: %s\n", XF86_DATE);
-  ErrorF("X Protocol Version %d, Revision %d, %s\n",
-         X_PROTOCOL, X_PROTOCOL_REVISION, XORG_RELEASE );
-  ErrorF("Build Operating System: %s %s\n", OSNAME, OSVENDOR);
-#ifdef HAS_UTSNAME
-  {
-    struct utsname name;
-
-    if (uname(&name) == 0) {
-      ErrorF("Current Operating System: %s %s %s %s %s\n",
-	name.sysname, name.nodename, name.release, name.version, name.machine);
-    }
-  }
-#endif
-#if defined(BUILD_DATE) && (BUILD_DATE > 19000000)
-  {
-    struct tm t;
-    char buf[100];
-
-    bzero(&t, sizeof(t));
-    bzero(buf, sizeof(buf));
-    t.tm_mday = BUILD_DATE % 100;
-    t.tm_mon = (BUILD_DATE / 100) % 100 - 1;
-    t.tm_year = BUILD_DATE / 10000 - 1900;
-    if (strftime(buf, sizeof(buf), "%d %B %Y", &t))
-       ErrorF("Build Date: %s\n", buf);
-  }
-#endif
-#if defined(CLOG_DATE) && (CLOG_DATE > 19000000)
-  {
-    struct tm t;
-    char buf[100];
-
-    bzero(&t, sizeof(t));
-    bzero(buf, sizeof(buf));
-    t.tm_mday = CLOG_DATE % 100;
-    t.tm_mon = (CLOG_DATE / 100) % 100 - 1;
-    t.tm_year = CLOG_DATE / 10000 - 1900;
-    if (strftime(buf, sizeof(buf), "%d %B %Y", &t))
-       ErrorF("Changelog Date: %s\n", buf);
-  }
-#endif
-#if defined(BUILDERSTRING)
-  ErrorF("%s \n",BUILDERSTRING);
-#endif
-  ErrorF("\tBefore reporting problems, check "__VENDORDWEBSUPPORT__"\n"
-	 "\tto make sure that you have the latest version.\n");
-}
+  ErrorF("X11.app starting:\n");
+  ErrorF("Xquartz server based on X.org %s, built on %s\n", XORG_RELEASE, BUILD_DATE );
+ }
 
 
 /*
@@ -349,8 +287,8 @@ static Bool DarwinAddScreen(
     dixScreenOrigins[index].x = dfb->x;
     dixScreenOrigins[index].y = dfb->y;
 
-    ErrorF("Screen %d added: %dx%d @ (%d,%d)\n",
-            index, dfb->width, dfb->height, dfb->x, dfb->y);
+    /*    ErrorF("Screen %d added: %dx%d @ (%d,%d)\n",
+	  index, dfb->width, dfb->height, dfb->x, dfb->y); */
 
     return TRUE;
 }
@@ -364,28 +302,6 @@ static Bool DarwinAddScreen(
 */
 
 /*
- * DarwinChangePointerControl
- *  Set mouse acceleration and thresholding
- *  FIXME: We currently ignore the threshold in ctrl->threshold.
- */
-static void DarwinChangePointerControl(
-    DeviceIntPtr    device,
-    PtrCtrl         *ctrl )
-{
-    kern_return_t   kr;
-    double          acceleration;
-
-    if (!darwinMouseAccelChange)
-        return;
-
-    acceleration = ctrl->num / ctrl->den;
-    kr = IOHIDSetMouseAcceleration( darwinParamConnect, acceleration );
-    if (kr != KERN_SUCCESS)
-        ErrorF( "Could not set mouse acceleration with kernel return = 0x%x.\n", kr );
-}
-
-
-/*
  * DarwinMouseProc
  *  Handle the initialization, etc. of a mouse
  */
@@ -410,7 +326,7 @@ static int DarwinMouseProc(
                         map,
                         5,   // numbuttons (4 & 5 are scroll wheel)
                         miPointerGetMotionEvents,
-                        DarwinChangePointerControl,
+		        (PtrCtrlProcPtr)NoopDDA,
                         0 );
 #ifdef XINPUT
             InitValuatorAxisStruct( pPointer,
@@ -633,8 +549,8 @@ DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo)
         for (i = 0; i < pScreenInfo->numScreens; i++) {
             dixScreenOrigins[i].x -= darwinMainScreenX;
             dixScreenOrigins[i].y -= darwinMainScreenY;
-            ErrorF("Screen %d placed at X11 coordinate (%d,%d).\n",
-                   i, dixScreenOrigins[i].x, dixScreenOrigins[i].y);
+	    /*            ErrorF("Screen %d placed at X11 coordinate (%d,%d).\n",
+			  i, dixScreenOrigins[i].x, dixScreenOrigins[i].y); */
         }
     }
 }
@@ -711,13 +627,13 @@ void OsVendorInit(void)
         if ( !tempStr ) {
             ErrorF("Could not find keymapping file %s.\n", darwinKeymapFile);
         } else {
-            ErrorF("Using keymapping provided in %s.\n", tempStr);
+	  ErrorF("Using keymapping provided in %s.\n", tempStr);
         }
         darwinKeymapFile = tempStr;
     }
 
     if ( !darwinKeymapFile ) {
-        ErrorF("Reading keymap from the system.\n");
+      //        ErrorF("Reading keymap from the system.\n");
     }
 }
 
@@ -916,7 +832,7 @@ void ddxUseMsg( void )
  */
 void ddxGiveUp( void )
 {
-    ErrorF( "Quitting XDarwin...\n" );
+    ErrorF( "Quitting Xquartz...\n" );
 
     DarwinModeGiveUp();
 }
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/darwinEvents.c b/hw/darwin/darwinEvents.c
index 6b902df..6b4f727 100644
--- a/hw/darwin/darwinEvents.c
+++ b/hw/darwin/darwinEvents.c
@@ -128,23 +128,18 @@ static void DarwinUpdateModifiers(
     int flags )         // modifier flags that have changed
 {
     xe->u.u.type = pressed;
+    if (flags & NX_COMMANDMASK) DarwinPressModifierMask(xe, COMMAND_MASK(flags));
+    if (flags & NX_CONTROLMASK) DarwinPressModifierMask(xe, CONTROL_MASK(flags));
+    if (flags & NX_ALTERNATEMASK) DarwinPressModifierMask(xe, ALTERNATE_MASK(flags));
+    if (flags & NX_SHIFTMASK)  DarwinPressModifierMask(xe, SHIFT_MASK(flags));
+    if (flags & NX_SECONDARYFNMASK) DarwinPressModifierMask(xe, NX_SECONDARYFNMASK);
     if (flags & NX_ALPHASHIFTMASK) {
+		// Alpha shift only sees KeyDown when enabled and KeyUp when disabled,
+		// but X11 wants to see a up/down pair to enable, and again to disable
+		xe->u.u.type = KeyPress;
+        DarwinPressModifierMask(xe, NX_ALPHASHIFTMASK);
+		xe->u.u.type = KeyRelease;
         DarwinPressModifierMask(xe, NX_ALPHASHIFTMASK);
-    }
-    if (flags & NX_COMMANDMASK) {
-        DarwinPressModifierMask(xe, COMMAND_MASK(flags));
-    }
-    if (flags & NX_CONTROLMASK) {
-        DarwinPressModifierMask(xe, CONTROL_MASK(flags));
-    }
-    if (flags & NX_ALTERNATEMASK) {
-        DarwinPressModifierMask(xe, ALTERNATE_MASK(flags));
-    }
-    if (flags & NX_SHIFTMASK) {
-        DarwinPressModifierMask(xe, SHIFT_MASK(flags));
-    }
-    if (flags & NX_SECONDARYFNMASK) {
-        DarwinPressModifierMask(xe, NX_SECONDARYFNMASK);
     }
 }
 
diff --git a/hw/darwin/darwinKeyboard.c b/hw/darwin/darwinKeyboard.c
index c148d96..2a10496 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 --git a/hw/darwin/iokit/xfIOKit.c b/hw/darwin/iokit/xfIOKit.c
index 95a7fb3..7f126c7 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>
 
@@ -58,7 +63,6 @@
 #include <IOKit/IOKitLib.h>
 #include <IOKit/hidsystem/IOHIDShared.h>
 #include <IOKit/graphics/IOGraphicsLib.h>
-#include <drivers/event_status_driver.h>
 
 // Define this to work around bugs in the display drivers for
 // older PowerBook G3's. If the X server starts without this
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..413d062 100644
--- a/hw/darwin/iokit/xfIOKitStartup.c
+++ b/hw/darwin/iokit/xfIOKitStartup.c
@@ -29,6 +29,10 @@
  * 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 +61,9 @@ void DarwinHandleGUI(
  */
 void DarwinGlxExtensionInit(void)
 {
-    GlxExtensionInit();
+#ifdef GLXEXT
+    	GlxExtensionInit();
+#endif
 }
 
 
@@ -67,7 +73,9 @@ void DarwinGlxExtensionInit(void)
 void DarwinGlxWrapInitVisuals(
     miInitVisualsProcPtr *procPtr)
 {
+#ifdef GLXEXT
     GlxWrapInitVisuals(procPtr);
+#endif
 }
 
 
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..3ad4898 100644
--- a/hw/darwin/quartz/XDarwinStartup.c
+++ b/hw/darwin/quartz/XDarwinStartup.c
@@ -38,6 +38,9 @@
  * dealings in this Software without prior written authorization from
  * Torrey T. Lyons.
  */
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 
 #include <unistd.h>
 #include <stdio.h>
@@ -48,7 +51,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 +127,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..0587415 100644
--- a/hw/darwin/quartz/XServer.m
+++ b/hw/darwin/quartz/XServer.m
@@ -34,20 +34,20 @@
  * sale, use or other dealings in this Software without prior written
  * authorization.
  */
-/* $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 +830,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 6db036f..78cf9df 100644
--- a/hw/darwin/quartz/applewm.c
+++ b/hw/darwin/quartz/applewm.c
@@ -1,6 +1,6 @@
 /**************************************************************************
 
-Copyright (c) 2002 Apple Computer, Inc. All Rights Reserved.
+Copyright (c) 2002-2007 Apple Inc. All Rights Reserved.
 Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
 
 Permission is hereby granted, free of charge, to any person obtaining a
@@ -24,7 +24,9 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 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 THE SOFTWARE.
 #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)                      \
@@ -443,9 +445,11 @@ ProcAppleWMSetWindowMenu(
                 break;
         }
     }
-
+#ifdef INXQUARTZ
+    X11ApplicationSetWindowMenu (nitems, items, shortcuts);
+#else
     QuartzSetWindowMenu (nitems, items, shortcuts);
-
+#endif
     free(items);
     free(shortcuts);
 
@@ -460,10 +464,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);
 }
 
@@ -474,8 +480,11 @@ ProcAppleWMSetFrontProcess(
 {
     REQUEST_SIZE_MATCH(xAppleWMSetFrontProcessReq);
 
+#ifdef INXQUARTZ
+    X11ApplicationSetFrontProcess();
+#else
     QuartzMessageMainThread(kQuartzSetFrontProcess, NULL, 0);
-
+#endif
     return (client->noClientException);
 }
 
@@ -517,9 +526,12 @@ ProcAppleWMSetCanQuit(
 
     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/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..326910b 100644
--- a/hw/darwin/quartz/cr/crFrame.m
+++ b/hw/darwin/quartz/cr/crFrame.m
@@ -27,9 +27,11 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-/* $XdotOrg: xc/programs/Xserver/hw/darwin/quartz/cr/crFrame.m,v 1.2 2004/04/23 19:15:51 eich Exp $ */
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/cr/crFrame.m,v 1.3 2004/10/08 00:35:05 torrey 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/fullscreen.c b/hw/darwin/quartz/fullscreen/fullscreen.c
index a4881f9..ed7f4c8 100644
--- a/hw/darwin/quartz/fullscreen/fullscreen.c
+++ b/hw/darwin/quartz/fullscreen/fullscreen.c
@@ -25,7 +25,11 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/fullscreen/fullscreen.c,v 1.4 2005/07/01 22:43:08 daniels Exp $ */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/fullscreen/fullscreen.c,v 1.3 2003/11/27 01:59:53 torrey Exp $ */
+#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..60a4c4d 100644
--- a/hw/darwin/quartz/fullscreen/quartzCursor.c
+++ b/hw/darwin/quartz/fullscreen/quartzCursor.c
@@ -29,7 +29,10 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCursor.c,v 1.5 2003/01/23 00:34:26 torrey Exp $ */
+#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/fullscreen/quartzCursor.h b/hw/darwin/quartz/fullscreen/quartzCursor.h
index 57fac68..efcc443 100644
--- a/hw/darwin/quartz/fullscreen/quartzCursor.h
+++ b/hw/darwin/quartz/fullscreen/quartzCursor.h
@@ -29,6 +29,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCursor.h,v 1.1 2002/03/28 02:21:19 torrey Exp $ */
 
 #ifndef QUARTZCURSOR_H
 #define QUARTZCURSOR_H
diff --git a/hw/darwin/quartz/pseudoramiX.c b/hw/darwin/quartz/pseudoramiX.c
index ab57827..66b9662 100644
--- a/hw/darwin/quartz/pseudoramiX.c
+++ b/hw/darwin/quartz/pseudoramiX.c
@@ -32,15 +32,21 @@ shall not be used in advertising or otherwise to promote the sale, use or other
 dealings in this Software without prior written authorization from Digital
 Equipment Corporation.
 ******************************************************************/
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/pseudoramiX.c,v 1.4 2004/07/02 01:30:33 torrey Exp $ */
 
 #include "pseudoramiX.h"
-
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "extnsionst.h"
 #include "dixstruct.h"
 #include "window.h"
 #include <X11/extensions/panoramiXproto.h>
 #include "globals.h"
 
+extern int noPseudoramiXExtension;
+extern int noPanoramiXExtension;
+
 extern int ProcPanoramiXQueryVersion (ClientPtr client);
 
 static void PseudoramiXResetProc(ExtensionEntry *extEntry);
diff --git a/hw/darwin/quartz/pseudoramiX.h b/hw/darwin/quartz/pseudoramiX.h
index df5010d..c294336 100644
--- a/hw/darwin/quartz/pseudoramiX.h
+++ b/hw/darwin/quartz/pseudoramiX.h
@@ -1,6 +1,7 @@
 /*
  * Minimal implementation of PanoramiX/Xinerama
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/pseudoramiX.h,v 1.3 2004/07/02 01:30:33 torrey Exp $ */
 
 extern int noPseudoramiXExtension;
 
diff --git a/hw/darwin/quartz/quartz.c b/hw/darwin/quartz/quartz.c
index 36a8bea..baeba8f 100644
--- a/hw/darwin/quartz/quartz.c
+++ b/hw/darwin/quartz/quartz.c
@@ -1,3 +1,4 @@
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/quartz.c,v 1.4 2005/07/01 22:43:07 daniels Exp $ */
 /**************************************************************
  *
  * Quartz-specific support for the Darwin X Server
@@ -29,14 +30,17 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartz.c,v 1.16 2004/07/02 01:30:33 torrey Exp $ */
+#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
@@ -158,8 +162,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)
         quartzProcs->InitInput(argc, argv);
@@ -272,7 +279,9 @@ static void QuartzHide(void)
         }
     }
     quartzServerVisible = FALSE;
+#ifndef INXQUARTZ
     QuartzMessageMainThread(kQuartzServerHidden, NULL, 0);
+#endif
 }
 
 
diff --git a/hw/darwin/quartz/quartz.h b/hw/darwin/quartz/quartz.h
index f1b36b6..c83579c 100644
--- a/hw/darwin/quartz/quartz.h
+++ b/hw/darwin/quartz/quartz.h
@@ -30,6 +30,8 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/quartz.h,v 1.4 2005/07/01 22:43:07 daniels Exp $ */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartz.h,v 1.7 2003/11/12 20:21:51 torrey Exp $ */
 
 #ifndef _QUARTZ_H
 #define _QUARTZ_H
diff --git a/hw/darwin/quartz/quartzAudio.c b/hw/darwin/quartz/quartzAudio.c
index b477b03..03f9cca 100644
--- a/hw/darwin/quartz/quartzAudio.c
+++ b/hw/darwin/quartz/quartzAudio.c
@@ -35,7 +35,10 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzAudio.c,v 1.1 2002/03/28 02:21:18 torrey Exp $ */
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzCommon.h"
 #include "quartzAudio.h"
 
@@ -44,6 +47,7 @@
 
 #include "inputstr.h"
 #include <X11/extensions/XI.h>
+#include <assert.h>
 
 void NSBeep();
 
diff --git a/hw/darwin/quartz/quartzAudio.h b/hw/darwin/quartz/quartzAudio.h
index c406bbc..e20c21a 100644
--- a/hw/darwin/quartz/quartzAudio.h
+++ b/hw/darwin/quartz/quartzAudio.h
@@ -28,6 +28,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/quartzAudio.h,v 1.2 2001/04/01 20:45:43 tsi Exp $ */
 
 #ifndef _QUARTZAUDIO_H
 #define _QUARTZAUDIO_H
diff --git a/hw/darwin/quartz/quartzCocoa.m b/hw/darwin/quartz/quartzCocoa.m
index 3cb191f..a9c89c0 100644
--- a/hw/darwin/quartz/quartzCocoa.m
+++ b/hw/darwin/quartz/quartzCocoa.m
@@ -1,4 +1,4 @@
-/* $XdotOrg: xc/programs/Xserver/hw/darwin/quartz/quartzCocoa.m,v 1.2 2004/04/23 19:15:17 eich Exp $ */
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/quartzCocoa.m,v 1.3 2004/07/30 19:12:17 torrey Exp $ */
 /**************************************************************
  *
  * Quartz-specific support for the Darwin X Server
@@ -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"
 
@@ -44,14 +47,16 @@
 
 #include <Cocoa/Cocoa.h>
 
+#ifndef INXQUARTZ
 #import "Preferences.h"
+#endif
 #include "pseudoramiX.h"
 
 extern void FatalError(const char *, ...);
 extern char *display;
 extern int noPanoramiXExtension;
 
-
+#ifndef INXQUARTZ
 /*
  * QuartzReadPreferences
  *  Read the user preferences from the Cocoa front end.
@@ -97,7 +102,7 @@ void QuartzReadPreferences(void)
 
     darwinDesiredDepth = [Preferences depth] - 1;
 }
-
+#endif
 
 /*
  * QuartzWriteCocoaPasteboard
@@ -162,6 +167,7 @@ char *QuartzReadCocoaPasteboard(void)
 int QuartzFSUseQDCursor(
     int depth)  // screen depth
 {
+#ifndef INXQUARTZ
     switch ([Preferences useQDCursor]) {
         case qdCursor_Always:
             return TRUE;
@@ -173,6 +179,7 @@ int QuartzFSUseQDCursor(
             else
                 return FALSE;
     }
+#endif
     return TRUE;
 }
 
diff --git a/hw/darwin/quartz/quartzCommon.h b/hw/darwin/quartz/quartzCommon.h
index f5dff66..2fd79eb 100644
--- a/hw/darwin/quartz/quartzCommon.h
+++ b/hw/darwin/quartz/quartzCommon.h
@@ -1,3 +1,4 @@
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/quartzCommon.h,v 1.4 2005/07/01 22:43:07 daniels Exp $ */
 /*
  * quartzCommon.h
  *
@@ -31,6 +32,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCommon.h,v 1.15 2004/06/08 22:58:10 torrey Exp $ */
 
 #ifndef _QUARTZCOMMON_H
 #define _QUARTZCOMMON_H
diff --git a/hw/darwin/quartz/quartzCursor.c b/hw/darwin/quartz/quartzCursor.c
index e2333e2..2f39887 100644
--- a/hw/darwin/quartz/quartzCursor.c
+++ b/hw/darwin/quartz/quartzCursor.c
@@ -29,7 +29,11 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzCursor.c,v 1.4 2002/11/19 23:01:30 torrey Exp $ */
 
+#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..e847f8c 100644
--- a/hw/darwin/quartz/quartzCursor.h
+++ b/hw/darwin/quartz/quartzCursor.h
@@ -29,6 +29,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/quartzCursor.h,v 1.2 2001/09/23 04:04:49 torrey Exp $ */
 
 #ifndef QUARTZCURSOR_H
 #define QUARTZCURSOR_H
@@ -36,6 +37,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..d23b68e 100644
--- a/hw/darwin/quartz/quartzKeyboard.c
+++ b/hw/darwin/quartz/quartzKeyboard.c
@@ -32,14 +32,18 @@
    promote the sale, use or other dealings in this Software without
    prior written authorization.
 */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzKeyboard.c,v 1.1 2003/11/01 08:13:08 torrey Exp $ */
 
+#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
@@ -214,35 +218,44 @@ Bool
 DarwinModeReadSystemKeymap (darwinKeyboardInfo *info)
 {
     KeyboardLayoutRef key_layout;
-    const void *chr_data;
+    const void *chr_data = NULL;
     int num_keycodes = NUM_KEYCODES;
     UInt32 keyboard_type = 0;
     int is_uchr, i, j;
     OSStatus err;
     KeySym *k;
 
-    KLGetCurrentKeyboardLayout (&key_layout);
-    KLGetKeyboardLayoutProperty (key_layout, kKLuchrData, &chr_data);
-
-    if (chr_data != NULL)
-    {
-        is_uchr = 1;
-        keyboard_type = LMGetKbdType ();
-    }
-    else
-    {
-        KLGetKeyboardLayoutProperty (key_layout, kKLKCHRData, &chr_data);
-
-        if (chr_data == NULL)
-        {
-            ErrorF ( "Couldn't get uchr or kchr resource\n");
-            return FALSE;
-        }
-
-        is_uchr = 0;
-        num_keycodes = 128;
-    }    
-
+    TISInputSourceRef currentKeyLayoutRef = TISCopyCurrentKeyboardLayoutInputSource();
+	if (currentKeyLayoutRef)
+	{
+		CFDataRef currentKeyLayoutDataRef = (CFDataRef )TISGetInputSourceProperty(currentKeyLayoutRef, kTISPropertyUnicodeKeyLayoutData);
+		if (currentKeyLayoutDataRef)
+			chr_data = CFDataGetBytePtr(currentKeyLayoutDataRef);
+	}
+	
+	if(chr_data == NULL) {
+		KLGetCurrentKeyboardLayout (&key_layout);
+		KLGetKeyboardLayoutProperty (key_layout, kKLuchrData, &chr_data);
+
+		if (chr_data != NULL)
+		{
+			is_uchr = 1;
+			keyboard_type = LMGetKbdType ();
+		}
+		else
+		{
+			KLGetKeyboardLayoutProperty (key_layout, kKLKCHRData, &chr_data);
+
+			if (chr_data == NULL)
+			{
+				ErrorF ( "Couldn't get uchr or kchr resource\n");
+				return FALSE;
+			}
+
+			is_uchr = 0;
+			num_keycodes = 128;
+		}    
+	}
 
     /* Scan the keycode range for the Unicode character that each
        key produces in the four shift states. Then convert that to
@@ -366,6 +379,7 @@ DarwinModeReadSystemKeymap (darwinKeyboardInfo *info)
             }
         }
     }
+	if(currentKeyLayoutRef)	CFRelease(currentKeyLayoutRef);
 
     return TRUE;
 }
diff --git a/hw/darwin/quartz/quartzPasteboard.c b/hw/darwin/quartz/quartzPasteboard.c
index e92fe5c..7ae2e33 100644
--- a/hw/darwin/quartz/quartzPasteboard.c
+++ b/hw/darwin/quartz/quartzPasteboard.c
@@ -29,7 +29,11 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/quartzPasteboard.c,v 1.3 2001/09/23 04:04:49 torrey Exp $ */
 
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "quartzPasteboard.h"
 
 #include <X11/Xatom.h>
diff --git a/hw/darwin/quartz/quartzPasteboard.h b/hw/darwin/quartz/quartzPasteboard.h
index afcb6e5..296c52c 100644
--- a/hw/darwin/quartz/quartzPasteboard.h
+++ b/hw/darwin/quartz/quartzPasteboard.h
@@ -29,6 +29,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/bundle/quartzPasteboard.h,v 1.1 2001/03/15 22:24:27 torrey Exp $ */
 
 #ifndef _QUARTZPASTEBOARD_H
 #define _QUARTZPASTEBOARD_H
@@ -41,4 +42,4 @@ char * QuartzReadCocoaPasteboard(void);	// caller must free string
 void QuartzWritePasteboard();
 void QuartzWriteCocoaPasteboard(char *text);
 
-#endif	/* _QUARTZPASTEBOARD_H */
+#endif	/* _QUARTZPASTEBOARD_H */
\ No newline at end of file
diff --git a/hw/darwin/quartz/quartzStartup.c b/hw/darwin/quartz/quartzStartup.c
index 277e593..4df8f94 100644
--- a/hw/darwin/quartz/quartzStartup.c
+++ b/hw/darwin/quartz/quartzStartup.c
@@ -28,6 +28,7 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/quartzStartup.c,v 1.8 2003/11/05 00:15:00 torrey Exp $ */
 
 #include <fcntl.h>
 #include <unistd.h>
@@ -37,21 +38,35 @@
 #include "quartz.h"
 #include "opaque.h"
 #include "micmap.h"
-
-int NSApplicationMain(int argc, char *argv[]);
-
+#include <assert.h>
 char **envpGlobal;      // argcGlobal and argvGlobal
                         // are from dix/globals.c
 
+
+#ifndef INXQUARTZ
+int NSApplicationMain(int argc, char *argv[]);
+
 // GLX bundle function pointers
+void * __DarwinglXMesaProvider = NULL;
+typedef void (*GlxPushProviderPtr)(void *);
+GlxPushProviderPtr GlxPushProvider = NULL;
 typedef void (*GlxExtensionInitPtr)(void); 
-static GlxExtensionInitPtr GlxExtensionInit = NULL;
-
 typedef void (*GlxWrapInitVisualsPtr)(miInitVisualsProcPtr *);
-static GlxWrapInitVisualsPtr GlxWrapInitVisuals = NULL;
-
 typedef Bool (*QuartzModeBundleInitPtr)(void);
-
+static GlxExtensionInitPtr GlxExtensionInit = NULL;
+static GlxWrapInitVisualsPtr GlxWrapInitVisuals = NULL;
+#else
+void X11ControllerMain(int argc, char *argv[],
+		       void (*server_thread) (void *), void *server_arg);
+void GlxExtensionInit(void);
+void GlxWrapInitVisuals(miInitVisualsProcPtr *procPtr);
+
+static void server_thread (void *arg) {
+  extern int main(int argc, char **argv, char **envp);
+  
+  exit (main (argcGlobal, argvGlobal, envpGlobal));
+}
+#endif
 
 /*
  * DarwinHandleGUI
@@ -71,7 +86,9 @@ void DarwinHandleGUI(
     int         fd[2];
 
     if (been_here) {
+#ifndef INXQUARTZ      
         QuartzReadPreferences();
+#endif
         return;
     }
     been_here = TRUE;
@@ -106,11 +123,17 @@ void DarwinHandleGUI(
         }
     }
 
+#ifndef INXQUARTZ
     main_exit = NSApplicationMain(argc, argv);
+#else
+    extern void _InitHLTB(void);
+    
+    _InitHLTB();
+    X11ControllerMain(argc, argv, server_thread, NULL);
+#endif
     exit(main_exit);
 }
 
-
 /*
  * QuartzLoadDisplayBundle
  *  Try to load the appropriate bundle containing the back end display code.
@@ -118,6 +141,7 @@ void DarwinHandleGUI(
 Bool QuartzLoadDisplayBundle(
     const char *dpyBundleName)
 {
+#ifndef INXQUARTZ
     CFBundleRef mainBundle;
     CFStringRef bundleName;
     CFURLRef    bundleURL;
@@ -164,7 +188,7 @@ Bool QuartzLoadDisplayBundle(
     // Release the CF objects
     CFRelease(bundleName);
     CFRelease(bundleURL);
-
+#endif
     return TRUE;
 }
 
@@ -186,7 +210,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,12 +237,20 @@ static void LoadGlxBundle(void)
     }
 
     // Find the GLX init functions
+
+#ifndef INXQUARTZ
+    __DarwinglXMesaProvider = (void *) CFBundleGetDataPointerForName(
+			       glxBundle, CFSTR("__glXMesaProvider"));
+
+    GlxPushProvider = (void *) CFBundleGetFunctionPointerForName(
+                                glxBundle, CFSTR("GlxPushProvider"));
+
     GlxExtensionInit = (void *) CFBundleGetFunctionPointerForName(
                                 glxBundle, CFSTR("GlxExtensionInit"));
 
     GlxWrapInitVisuals = (void *) CFBundleGetFunctionPointerForName(
                                 glxBundle, CFSTR("GlxWrapInitVisuals"));
-
+#endif
     if (!GlxExtensionInit || !GlxWrapInitVisuals) {
         FatalError("Could not initialize GLX bundle.");
     }
@@ -233,11 +265,25 @@ static void LoadGlxBundle(void)
  * DarwinGlxExtensionInit
  *  Initialize the GLX extension.
  */
-void DarwinGlxExtensionInit(void)
+void DarwinGlxPushProvider(void *impl)
 {
+#ifndef INXQUARTZ
     if (!GlxExtensionInit)
         LoadGlxBundle();
+#endif
+    GlxPushProvider(impl);
+}
 
+/*
+ * DarwinGlxExtensionInit
+ *  Initialize the GLX extension.
+ */
+void DarwinGlxExtensionInit(void)
+{
+#ifndef INXQUARTZ
+    if (!GlxExtensionInit)
+        LoadGlxBundle();
+#endif
     GlxExtensionInit();
 }
 
@@ -248,9 +294,10 @@ void DarwinGlxExtensionInit(void)
 void DarwinGlxWrapInitVisuals(
     miInitVisualsProcPtr *procPtr)
 {
+#ifdef INXQUARTZ
     if (!GlxWrapInitVisuals)
         LoadGlxBundle();
-
+#endif
     GlxWrapInitVisuals(procPtr);
 }
 
diff --git a/hw/darwin/quartz/xpr/Xplugin.h b/hw/darwin/quartz/xpr/Xplugin.h
index fb6842c..e2e97b4 100644
--- a/hw/darwin/quartz/xpr/Xplugin.h
+++ b/hw/darwin/quartz/xpr/Xplugin.h
@@ -30,6 +30,7 @@
 
    Note that these interfaces are provided solely for the use of the
    X11 server. Any other uses are unsupported and strongly discouraged. */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/Xplugin.h,v 1.2 2003/05/02 00:08:49 torrey Exp $ */
 
 #ifndef XPLUGIN_H
 #define XPLUGIN_H 1
diff --git a/hw/darwin/quartz/xpr/appledri.c b/hw/darwin/quartz/xpr/appledri.c
index 6d9bae1..329c0d8 100644
--- a/hw/darwin/quartz/xpr/appledri.c
+++ b/hw/darwin/quartz/xpr/appledri.c
@@ -1,3 +1,4 @@
+/* $XFree86: xc/programs/Xserver/GL/dri/xf86dri.c,v 1.10 2000/12/07 20:26:14 dawes Exp $ */
 /**************************************************************************
 
 Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
@@ -35,6 +36,9 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  *
  */
 
+#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/dri.c b/hw/darwin/quartz/xpr/dri.c
index 9aeaaa5..c788c20 100644
--- a/hw/darwin/quartz/xpr/dri.c
+++ b/hw/darwin/quartz/xpr/dri.c
@@ -1,3 +1,4 @@
+/* $XFree86: xc/programs/Xserver/GL/dri/dri.c,v 1.34 2001/12/10 19:07:19 dawes Exp $ */
 /**************************************************************************
 
 Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
@@ -34,8 +35,17 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  *
  */
 
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+#ifdef XFree86LOADER
+#include "xf86.h"
+#include "xf86_ansic.h"
+#else
 #include <sys/time.h>
 #include <unistd.h>
+#endif
+#include <dix-config.h>
 
 #define NEED_REPLIES
 #define NEED_EVENTS
@@ -234,7 +244,7 @@ DRIFinishScreenInit(ScreenPtr pScreen)
     pDRIPriv->wrap.ClipNotify = pScreen->ClipNotify;
     pScreen->ClipNotify = DRIClipNotify;
 
-    ErrorF("[DRI] screen %d installation complete\n", pScreen->myNum);
+    //    ErrorF("[DRI] screen %d installation complete\n", pScreen->myNum);
 
     return TRUE;
 }
diff --git a/hw/darwin/quartz/xpr/dri.h b/hw/darwin/quartz/xpr/dri.h
index cf2638a..f826167 100644
--- a/hw/darwin/quartz/xpr/dri.h
+++ b/hw/darwin/quartz/xpr/dri.h
@@ -1,3 +1,4 @@
+/* $XFree86: xc/programs/Xserver/GL/dri/dri.h,v 1.18 2001/03/21 16:21:40 dawes Exp $ */
 /**************************************************************************
 
 Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
diff --git a/hw/darwin/quartz/xpr/dristruct.h b/hw/darwin/quartz/xpr/dristruct.h
index 9a3d01c..0df8f18 100644
--- a/hw/darwin/quartz/xpr/dristruct.h
+++ b/hw/darwin/quartz/xpr/dristruct.h
@@ -1,3 +1,4 @@
+/* $XFree86: xc/programs/Xserver/GL/dri/dristruct.h,v 1.10 2001/03/21 16:21:40 dawes Exp $ */
 /**************************************************************************
 
 Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
diff --git a/hw/darwin/quartz/xpr/x-hash.c b/hw/darwin/quartz/xpr/x-hash.c
index a7024b2..0491a5a 100644
--- a/hw/darwin/quartz/xpr/x-hash.c
+++ b/hw/darwin/quartz/xpr/x-hash.c
@@ -1,5 +1,5 @@
 /* x-hash.c - basic hash tables
-   $Id$
+   $Id: x-hash.c,v 1.7 2003/07/17 05:25:44 jharper Exp $
 
    Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 
@@ -27,7 +27,10 @@
    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. */
-
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/x-hash.c,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
+#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-hash.h b/hw/darwin/quartz/xpr/x-hash.h
index 5d4f7f9..97d4cc4 100644
--- a/hw/darwin/quartz/xpr/x-hash.h
+++ b/hw/darwin/quartz/xpr/x-hash.h
@@ -27,6 +27,7 @@
    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. */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/x-hash.h,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
 
 #ifndef X_HASH_H
 #define X_HASH_H 1
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..c87045e 100644
--- a/hw/darwin/quartz/xpr/x-list.c
+++ b/hw/darwin/quartz/xpr/x-list.c
@@ -1,5 +1,5 @@
 /* x-list.c
-   $Id$
+   $Id: x-list.c,v 1.16 2003/07/18 00:52:19 jharper Exp $
 
    Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 
@@ -27,7 +27,10 @@
    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. */
-
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/x-list.c,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
+#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/x-list.h b/hw/darwin/quartz/xpr/x-list.h
index bd55a53..2b71070 100644
--- a/hw/darwin/quartz/xpr/x-list.h
+++ b/hw/darwin/quartz/xpr/x-list.h
@@ -1,5 +1,5 @@
 /* x-list.h -- simple list type
-   $Id$
+   $Id: x-list.h,v 1.10 2003/07/18 00:52:19 jharper Exp $
 
    Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 
@@ -27,6 +27,7 @@
    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. */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/x-list.h,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
 
 #ifndef X_LIST_H
 #define X_LIST_H 1
diff --git a/hw/darwin/quartz/xpr/xpr.h b/hw/darwin/quartz/xpr/xpr.h
index 73a88c0..5b02c6d 100644
--- a/hw/darwin/quartz/xpr/xpr.h
+++ b/hw/darwin/quartz/xpr/xpr.h
@@ -26,6 +26,8 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/xpr/xpr.h,v 1.3 2005/07/01 22:43:08 daniels Exp $ */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xpr.h,v 1.4 2003/11/12 20:21:52 torrey Exp $ */
 
 #ifndef XPR_H
 #define XPR_H
diff --git a/hw/darwin/quartz/xpr/xprAppleWM.c b/hw/darwin/quartz/xpr/xprAppleWM.c
index 21746f6..3f5af2c 100644
--- a/hw/darwin/quartz/xpr/xprAppleWM.c
+++ b/hw/darwin/quartz/xpr/xprAppleWM.c
@@ -27,9 +27,12 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * 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 "xpr.h"
-#include "applewmExt.h"
+#include "quartz/applewmExt.h"
 #include "rootless.h"
 #include "Xplugin.h"
 #include <X11/X.h>
diff --git a/hw/darwin/quartz/xpr/xprCursor.c b/hw/darwin/quartz/xpr/xprCursor.c
index cb949da..9f9abc2 100644
--- a/hw/darwin/quartz/xpr/xprCursor.c
+++ b/hw/darwin/quartz/xpr/xprCursor.c
@@ -30,8 +30,11 @@
  * 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 "quartzCommon.h"
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xprCursor.c,v 1.1 2003/04/30 23:15:42 torrey Exp $ */
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+#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 ed02d4b..b141e62 100644
--- a/hw/darwin/quartz/xpr/xprFrame.c
+++ b/hw/darwin/quartz/xpr/xprFrame.c
@@ -27,13 +27,17 @@
  * holders shall not be used in advertising or otherwise to promote the sale,
  * use or other dealings in this Software without prior written authorization.
  */
-
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/xpr/xprFrame.c,v 1.5 2005/07/01 22:43:08 daniels Exp $ */
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xprFrame.c,v 1.4 2003/11/12 20:21:52 torrey Exp $ */
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "xpr.h"
 #include "rootlessCommon.h"
 #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 1755ca6..1aebefe 100644
--- a/hw/darwin/quartz/xpr/xprScreen.c
+++ b/hw/darwin/quartz/xpr/xprScreen.c
@@ -1,3 +1,4 @@
+/* $XdotOrg: xserver/xorg/hw/darwin/quartz/xpr/xprScreen.c,v 1.6 2005/07/01 22:43:08 daniels Exp $ */
 /*
  * Xplugin rootless implementation screen functions
  */
@@ -27,18 +28,21 @@
  * 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 "quartzCommon.h"
-#include "quartz.h"
+/* $XFree86: xc/programs/Xserver/hw/darwin/quartz/xpr/xprScreen.c,v 1.11 2004/07/15 18:53:25 torrey Exp $ */
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+#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"
@@ -179,15 +183,15 @@ xprAddPseudoramiXScreens(int *x, int *y, int *width, int *height)
 
         frame = displayScreenBounds(dpy);
 
-        ErrorF("PseudoramiX screen %d added: %dx%d @ (%d,%d).\n", i,
+	/*        ErrorF("PseudoramiX screen %d added: %dx%d @ (%d,%d).\n", i,
                (int)frame.size.width, (int)frame.size.height,
-               (int)frame.origin.x, (int)frame.origin.y);
+               (int)frame.origin.x, (int)frame.origin.y); */
 
         frame.origin.x -= unionRect.origin.x;
         frame.origin.y -= unionRect.origin.y;
 
-        ErrorF("PseudoramiX screen %d placed at X11 coordinate (%d,%d).\n",
-               i, (int)frame.origin.x, (int)frame.origin.y);
+	/*        ErrorF("PseudoramiX screen %d placed at X11 coordinate (%d,%d).\n",
+		  i, (int)frame.origin.x, (int)frame.origin.y); */
 
         PseudoramiXAddScreen(frame.origin.x, frame.origin.y,
                              frame.size.width, frame.size.height);
@@ -206,7 +210,7 @@ xprDisplayInit(void)
 {
     CGDisplayCount displayCount;
 
-    ErrorF("Display mode: Rootless Quartz -- Xplugin implementation\n");
+    //    ErrorF("Display mode: Rootless Quartz -- Xplugin implementation\n");
 
     CGGetActiveDisplayList(0, NULL, &displayCount);
 
diff --git a/hw/darwin/utils/dumpkeymap.c b/hw/darwin/utils/dumpkeymap.c
index d2eeca5..c3e66e3 100644
--- a/hw/darwin/utils/dumpkeymap.c
+++ b/hw/darwin/utils/dumpkeymap.c
@@ -1,3 +1,4 @@
+// $XFree86: dumpkeymap.c,v 1.3 2000/12/05 21:18:34 dawes Exp $
 //=============================================================================
 //
 // Copyright (C) 1999,2000 by Eric Sunshine <sunshine at sunshineco.com>
@@ -143,7 +144,7 @@
 #include <string.h>
 #include <sys/stat.h>
 #if !defined(DUMPKEYMAP_FILE_ONLY)
-#include <drivers/event_status_driver.h>
+#include "event_status_driver.h"
 #endif
 
 #define PROG_NAME "dumpkeymap"
commit d300f631fc4a1ab17fe336c607aa53006061818f
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Fri Oct 26 15:40:35 2007 -0700

    added missing file from Apple version of 7.2

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/Localizable.strings b/hw/darwin/apple/English.lproj/Localizable.strings
new file mode 100644
index 0000000..c83b085
Binary files /dev/null and b/hw/darwin/apple/English.lproj/Localizable.strings 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..66f1f6b
--- /dev/null
+++ b/hw/darwin/apple/Info.plist
@@ -0,0 +1,35 @@
+<?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>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>x11a</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..d770e61
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..a47e4d1
--- /dev/null
+++ b/hw/darwin/apple/X11.xcodeproj/project.pbxproj
@@ -0,0 +1,344 @@
+// !$*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 */; };
+		52D9C0ED0BCDDF6B00CD2AFC /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 52D9C0EB0BCDDF6B00CD2AFC /* Localizable.strings */; };
+/* 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; };
+		52D9C0EC0BCDDF6B00CD2AFC /* English */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/Localizable.strings; sourceTree = "<group>"; };
+		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 = (
+				52D9C0EB0BCDDF6B00CD2AFC /* Localizable.strings */,
+				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 */,
+				52D9C0ED0BCDDF6B00CD2AFC /* Localizable.strings 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>";
+		};
+		52D9C0EB0BCDDF6B00CD2AFC /* Localizable.strings */ = {
+			isa = PBXVariantGroup;
+			children = (
+				52D9C0EC0BCDDF6B00CD2AFC /* English */,
+			);
+			name = Localizable.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",
+					"-lxcb",
+					"-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",
+					"-lxcb",
+					"-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",
+					"-lxcb",
+					"-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..fb153e7
--- /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 "org.x.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..9ae470e
--- /dev/null
+++ b/hw/darwin/apple/X11Application.m
@@ -0,0 +1,1131 @@
+/* X11Application.m -- subclass of NSApplication to multiplex events
+ 
+ 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 "/usr/X11/lib/X11/xserver/Xquartz.plist"
+
+int X11EnableKeyEquivalents = TRUE;
+int quartzHasRoot = FALSE, quartzEnableRootless = TRUE;
+
+extern int darwinFakeButtons;
+extern Bool enable_stereo; 
+
+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.2",
+					 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];
+				if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
+			}
+			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..cc039b1
--- /dev/null
+++ b/hw/darwin/apple/X11Controller.m
@@ -0,0 +1,748 @@
+/* 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 *argv[5];
+  int child1, child2 = 0;
+  int status;
+	
+  argv[0] = "/usr/bin/login";
+  argv[1] = "-fp";
+  argv[2] = getlogin();
+  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 ((CFStringRef)NSLocalizedString(@"Mac Help", no comment), 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..34cbcba
--- /dev/null
+++ b/hw/darwin/apple/bundle-main.c
@@ -0,0 +1,914 @@
+/* bundle-main.c -- X server launcher
+ 
+ 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 <xcb/xcb.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/bin/quartz-wm"
+#define DEFAULT_XINITRC "/usr/X11/lib/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];
+    xcb_connection_t *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); */
+    conn = xcb_connect(buf, NULL);
+
+    if (conn == NULL)
+		return FALSE;
+	
+    //    _XDisconnectDisplay (conn);
+    xcb_disconnect(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 --git a/hw/darwin/bundle/Dutch.lproj/Localizable.strings b/hw/darwin/bundle/Dutch.lproj/Localizable.strings
index 6abd910..4fe16b3 100644
Binary files a/hw/darwin/bundle/Dutch.lproj/Localizable.strings and b/hw/darwin/bundle/Dutch.lproj/Localizable.strings differ
diff --git a/hw/darwin/bundle/Dutch.lproj/Makefile.am b/hw/darwin/bundle/Dutch.lproj/Makefile.am
new file mode 100644
index 0000000..49a3ec5
--- /dev/null
+++ b/hw/darwin/bundle/Dutch.lproj/Makefile.am
@@ -0,0 +1,39 @@
+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 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' | iconv -t UTF-16 > $@
+
+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/English.lproj/Localizable.strings b/hw/darwin/bundle/English.lproj/Localizable.strings
index 2c25c1d..f2e8e3c 100644
Binary files a/hw/darwin/bundle/English.lproj/Localizable.strings and b/hw/darwin/bundle/English.lproj/Localizable.strings differ
diff --git a/hw/darwin/bundle/English.lproj/Makefile.am b/hw/darwin/bundle/English.lproj/Makefile.am
new file mode 100644
index 0000000..8d6f7e5
--- /dev/null
+++ b/hw/darwin/bundle/English.lproj/Makefile.am
@@ -0,0 +1,39 @@
+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' | iconv -t UTF-16 > $@
+
+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 \
+	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..4dca934
--- /dev/null
+++ b/hw/darwin/bundle/French.lproj/Makefile.am
@@ -0,0 +1,41 @@
+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' | iconv -t UTF-16 > $@
+
+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..fcb5dd2
--- /dev/null
+++ b/hw/darwin/bundle/German.lproj/Makefile.am
@@ -0,0 +1,39 @@
+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 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' | iconv -t UTF-16 > $@
+
+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..7e17708
--- /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.X11</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleName</key>
+	<string>XDarwin</string>
+	<key>CFBundlePackageType</key>
+	<string>APPL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>2.0.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..8d891ed
--- /dev/null
+++ b/hw/darwin/bundle/Japanese.lproj/Makefile.am
@@ -0,0 +1,40 @@
+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' | iconv -t UTF-16 > $@
+
+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..540649c
--- /dev/null
+++ b/hw/darwin/bundle/Portuguese.lproj/Makefile.am
@@ -0,0 +1,39 @@
+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' | iconv -t UTF-16 > $@
+
+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..978ac35
--- /dev/null
+++ b/hw/darwin/bundle/Spanish.lproj/Makefile.am
@@ -0,0 +1,39 @@
+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' | iconv -t UTF-16 > $@
+
+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..3cf542c
--- /dev/null
+++ b/hw/darwin/bundle/Swedish.lproj/Makefile.am
@@ -0,0 +1,39 @@
+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' | iconv -t UTF-16 > $@
+
+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..a5462ff
--- /dev/null
+++ b/hw/darwin/bundle/ko.lproj/Makefile.am
@@ -0,0 +1,40 @@
+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' | iconv -t UTF-16 > $@
+
+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/iokit/Makefile.am b/hw/darwin/iokit/Makefile.am
new file mode 100644
index 0000000..77227d7
--- /dev/null
+++ b/hw/darwin/iokit/Makefile.am
@@ -0,0 +1,17 @@
+noinst_LIBRARIES = libiokit.a
+
+AM_CFLAGS = @XORG_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/launcher/Info.plist b/hw/darwin/launcher/Info.plist
new file mode 100644
index 0000000..b5385b6
--- /dev/null
+++ b/hw/darwin/launcher/Info.plist
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//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>CFBundleExecutable</key>
+	<string>X11</string>
+	<key>CFBundleGetInfoString</key>
+	<string>2.0, Copyright © 2003-2007, Apple Inc.</string>
+	<key>CFBundleIconFile</key>
+	<string>X11.icns</string>
+	<key>CFBundleIdentifier</key>
+	<string>org.x.X11_launcher</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>x11l</string>
+	<key>LSUIElement</key>
+	<string>1</string>
+	<key>NSHumanReadableCopyright</key>
+	<string>Copyright © 2007, Apple Inc.</string>
+</dict>
+</plist>
diff --git a/hw/darwin/launcher/X11.icns b/hw/darwin/launcher/X11.icns
new file mode 100644
index 0000000..d770e61
Binary files /dev/null and b/hw/darwin/launcher/X11.icns differ
diff --git a/hw/darwin/launcher/X11.xcodeproj/project.pbxproj b/hw/darwin/launcher/X11.xcodeproj/project.pbxproj
new file mode 100644
index 0000000..f82552a
--- /dev/null
+++ b/hw/darwin/launcher/X11.xcodeproj/project.pbxproj
@@ -0,0 +1,297 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 42;
+	objects = {
+
+/* Begin PBXBuildFile section */
+		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 */; };
+		527F24370B5D9D89007840A7 /* Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 527F24260B5D938C007840A7 /* Info.plist */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXFileReference section */
+		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; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		527F241E0B5D938C007840A7 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				527F241F0B5D938C007840A7 /* CoreFoundation.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 */,
+			);
+			name = Resources;
+			sourceTree = "<group>";
+		};
+		20286C32FDCF999611CA2CEA /* External Frameworks and Libraries */ = {
+			isa = PBXGroup;
+			children = (
+				50F4F0A7039D6ACA0E82C0CB /* CoreFoundation.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 */,
+				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 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",
+					"-lxcb",
+					"-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 = "";
+				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",
+					"-lxcb",
+					"-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/launcher/bundle-main.c b/hw/darwin/launcher/bundle-main.c
new file mode 100644
index 0000000..988c04f
--- /dev/null
+++ b/hw/darwin/launcher/bundle-main.c
@@ -0,0 +1,79 @@
+/* main.c -- X application launcher
+ 
+ Copyright (c) 2007 Apple Inc.
+ 
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation files
+ (the "Software"), 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 <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+#include <CoreFoundation/CoreFoundation.h>
+
+#define DEFAULT_APP "/usr/X11/bin/xterm"
+
+int main (int argc, char **argv) {
+  char *command = DEFAULT_APP;
+  const char *newargv[5];
+  int child;
+  
+
+	CFPropertyListRef PlistRef = CFPreferencesCopyAppValue(CFSTR("app_to_run"),
+									kCFPreferencesCurrentApplication);
+	
+	if ((PlistRef == NULL) || (CFGetTypeID(PlistRef) != CFStringGetTypeID())) {
+		CFPreferencesSetAppValue(CFSTR("app_to_run"), CFSTR(DEFAULT_APP), 
+								 kCFPreferencesCurrentApplication);
+		CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
+	} else {
+		int len = CFStringGetLength((CFStringRef)PlistRef)+1;
+		command = (char *) malloc(len);
+		CFStringGetCString((CFStringRef)PlistRef, command, len,  kCFStringEncodingASCII);
+		fprintf(stderr, "command=%s\n", command);
+	}
+	
+	if (PlistRef) CFRelease(PlistRef);
+	
+	newargv[0] = "/usr/bin/login";
+	newargv[1] = "-fp";
+	newargv[2] = getlogin();
+	newargv[3] = command;
+	newargv[4] = NULL;
+
+    child = fork();
+	
+    switch (child) {
+    case -1:				/* error */
+      perror ("fork");
+      return EXIT_FAILURE;		
+    case 0:				    /* child */
+      execvp (newargv[0], (char **const) newargv);
+      perror ("Couldn't exec");
+      _exit (1);
+   }
+	
+    return 0;
+}
diff --git a/hw/darwin/quartz/Makefile.am b/hw/darwin/quartz/Makefile.am
new file mode 100644
index 0000000..bc6d4fc
--- /dev/null
+++ b/hw/darwin/quartz/Makefile.am
@@ -0,0 +1,57 @@
+noinst_LIBRARIES = libXQuartz.a
+
+AM_CFLAGS = @XORG_CFLAGS@
+AM_OBJCFLAGS = @XORG_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/cr/Makefile.am b/hw/darwin/quartz/cr/Makefile.am
new file mode 100644
index 0000000..abfac99
--- /dev/null
+++ b/hw/darwin/quartz/cr/Makefile.am
@@ -0,0 +1,21 @@
+noinst_LIBRARIES = libcr.a
+AM_CFLAGS =  @XORG_CFLAGS@
+AM_OBJCFLAGS =  @XORG_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/fullscreen/Makefile.am b/hw/darwin/quartz/fullscreen/Makefile.am
new file mode 100644
index 0000000..37c767c
--- /dev/null
+++ b/hw/darwin/quartz/fullscreen/Makefile.am
@@ -0,0 +1,9 @@
+noinst_LIBRARIES = libfullscreen.a
+AM_CFLAGS = @XORG_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/xpr/Makefile.am b/hw/darwin/quartz/xpr/Makefile.am
new file mode 100644
index 0000000..980c7a4
--- /dev/null
+++ b/hw/darwin/quartz/xpr/Makefile.am
@@ -0,0 +1,30 @@
+noinst_LIBRARIES = libxpr.a
+AM_CFLAGS =  @XORG_CFLAGS@
+INCLUDES = @XORG_INCS@ \
+	   -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../.. \
+	   -I$(top_srcdir)/miext/rootless \
+	   -I$(top_srcdir)/miext/rootless/safeAlpha \
+	   -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.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/utils/Makefile.am b/hw/darwin/utils/Makefile.am
new file mode 100644
index 0000000..92bf151
--- /dev/null
+++ b/hw/darwin/utils/Makefile.am
@@ -0,0 +1,12 @@
+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/hw/darwin/utils/event_status_driver.h b/hw/darwin/utils/event_status_driver.h
new file mode 100644
index 0000000..8948f33
--- /dev/null
+++ b/hw/darwin/utils/event_status_driver.h
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ * 
+ * The contents of this file constitute Original Code as defined in and
+ * are subject to the Apple Public Source License Version 1.1 (the
+ * "License").  You may not use this file except in compliance with the
+ * License.  Please obtain a copy of the License at
+ * http://www.apple.com/publicsource and read it before using this file.
+ * 
+ * This Original Code and all software distributed under the License are
+ * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ * 
+ * @APPLE_LICENSE_HEADER_END@
+ */
+/******************************************************************************
+	event_status_driver.h
+	API for the events status driver.
+	This file contains public API.
+	mpaque 11Oct91
+	
+	Copyright 1991 NeXT Computer, Inc.
+	
+	Modified:
+	
+******************************************************************************/
+
+#ifndef _DRIVERS_EVENT_STATUS_DRIVER_
+#define _DRIVERS_EVENT_STATUS_DRIVER_
+
+__BEGIN_DECLS
+
+#include <mach/port.h>
+#include <IOKit/hidsystem/IOLLEvent.h>
+#include <IOKit/hidsystem/IOHIDTypes.h>
+#include <AvailabilityMacros.h> 
+
+/*
+ * Event System Handle:
+ *
+ * Information used by the system between calls to NXOpenEventSystem and
+ * NXCloseEventSystem.  The application should not
+ * access any of the elements of this structure.
+ */
+typedef mach_port_t NXEventHandle;
+
+/* Open and Close */
+NXEventHandle NXOpenEventStatus(void);
+void NXCloseEventStatus(NXEventHandle handle);
+
+/* Status */
+extern NXEventSystemInfoType NXEventSystemInfo(NXEventHandle handle,
+				char *flavor,
+				int *evs_info,
+				unsigned int *evs_info_cnt);
+/* Keyboard */
+extern void NXSetKeyRepeatInterval(NXEventHandle handle, double seconds);
+extern double NXKeyRepeatInterval(NXEventHandle handle);
+extern void NXSetKeyRepeatThreshold(NXEventHandle handle, double threshold);
+extern double NXKeyRepeatThreshold(NXEventHandle handle);
+extern void NXResetKeyboard(NXEventHandle handle);
+
+/* Mouse */
+extern void NXSetClickTime(NXEventHandle handle, double seconds);
+extern double NXClickTime(NXEventHandle handle);
+extern void NXSetClickSpace(NXEventHandle handle, _NXSize_ *area);
+extern void NXGetClickSpace(NXEventHandle handle, _NXSize_ *area);
+extern void NXResetMouse(NXEventHandle handle);
+
+/* DEPRECATED API */
+
+/* NXIdleTime has been deprecated as this API does not take into account
+   events posted through the CG API set.  Instead, we strongly encourage 
+   developers to make use of the CGSSecondsSinceLastInputEvent API. */
+extern double NXIdleTime(NXEventHandle handle)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+/* These methods are NOT supported.   */
+extern NXKeyMapping *NXSetKeyMapping(NXEventHandle h, NXKeyMapping *keymap)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern int NXKeyMappingLength(NXEventHandle handle)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern NXKeyMapping *NXGetKeyMapping(NXEventHandle h, NXKeyMapping *keymap)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+/* These methods are NOT supported and will return NULL values.   */
+extern void NXSetMouseScaling(NXEventHandle handle, NXMouseScaling *scaling)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern void NXGetMouseScaling(NXEventHandle handle, NXMouseScaling *scaling)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern void NXSetAutoDimThreshold(NXEventHandle handle, double seconds)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern double NXAutoDimThreshold(NXEventHandle handle)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern double NXAutoDimTime(NXEventHandle handle)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern void NXSetAutoDimState(NXEventHandle handle, boolean_t dimmed)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern boolean_t NXAutoDimState(NXEventHandle handle)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern void NXSetAutoDimBrightness(NXEventHandle handle, double level)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern double NXAutoDimBrightness(NXEventHandle handle)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern void NXSetScreenBrightness(NXEventHandle handle, double level)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+extern double NXScreenBrightness(NXEventHandle handle)
+AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
+
+/* END DEPRECATED API */
+
+__END_DECLS
+
+#endif /*_DRIVERS_EVENT_STATUS_DRIVER_ */
+
commit a5b49a19f96c956b270323e9e91e1cb1045a90f8
Author: Ben Byer <bbyer at bbyer.apple.com>
Date:   Fri Oct 26 14:10:03 2007 -0700

    added Apple-specific defaults to configure.ac

diff --git a/configure.ac b/configure.ac
index 073edf7..3b6b754 100644
--- a/configure.ac
+++ b/configure.ac
@@ -424,18 +424,18 @@ AC_ARG_ENABLE(evi,            AS_HELP_STRING([--disable-evi], [Build Extended-Vi
 AC_ARG_ENABLE(multibuffer,    AS_HELP_STRING([--enable-multibuffer], [Build Multibuffer extension (default: disabled)]), [MULTIBUFFER=$enableval], [MULTIBUFFER=no])
 AC_ARG_ENABLE(fontcache,      AS_HELP_STRING([--enable-fontcache], [Build FontCache extension (default: disabled)]), [FONTCACHE=$enableval], [FONTCACHE=no])
 AC_ARG_ENABLE(dbe,            AS_HELP_STRING([--disable-dbe], [Build DBE extension (default: enabled)]), [DBE=$enableval], [DBE=yes])
-AC_ARG_ENABLE(xf86bigfont,    AS_HELP_STRING([--disable-xf86bigfont], [Build XF86 Big Font extension (default: enabled)]), [XF86BIGFONT=$enableval], [XF86BIGFONT=yes])
+AC_ARG_ENABLE(xf86bigfont,    AS_HELP_STRING([--enable-xf86bigfont], [Build XF86 Big Font extension (default: disabled)]), [XF86BIGFONT=$enableval], [XF86BIGFONT=no])
 AC_ARG_ENABLE(dpms,           AS_HELP_STRING([--disable-dpms], [Build DPMS extension (default: enabled)]), [DPMSExtension=$enableval], [DPMSExtension=yes])
 AC_ARG_ENABLE(xinput,         AS_HELP_STRING([--disable-xinput], [Build XInput Extension (default: enabled)]), [XINPUT=$enableval], [XINPUT=yes])
 AC_ARG_ENABLE(xfree86-utils,     AS_HELP_STRING([--enable-xfree86-utils], [Build xfree86 DDX utilities (default: enabled)]), [XF86UTILS=$enableval], [XF86UTILS=yes])
 
 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(xvfb,    	      AS_HELP_STRING([--enable-xvfb], [Build Xvfb server (default: yes)]), [XVFB=$enableval], [XVFB=yes])
+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: no)]), [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])
-AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: auto)]), [XPRINT=$enableval], [XPRINT=auto])
+AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
 AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (default: no)]), [XGL=$enableval], [XGL=no])
 AC_ARG_ENABLE(xglx,           AS_HELP_STRING([--enable-xglx], [Build Xglx xgl module (default: no)]), [XGLX=$enableval], [XGLX=no])
 AC_ARG_ENABLE(xegl,           AS_HELP_STRING([--enable-xegl], [Build Xegl xgl module (default: no)]), [XEGL=$enableval], [XEGL=no])
commit 96c637350d1117d18a10ca3de40814b506c8ffc3
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 e379633..35f1aa9 100644
--- a/hw/xfree86/Makefile.am
+++ b/hw/xfree86/Makefile.am
@@ -17,7 +17,7 @@ SUBDIRS = common ddc dummylib i2c x86emu int10 fbdevhw os-support parser rac \
 
 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
commit 12505d9c0a45d855fa85a4e5d4892b3cc590e945
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Wed Feb 14 18:13:15 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 a939687..073edf7 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1736,6 +1736,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 f05308d..e379633 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 7cfff47..3b36f55 100644
--- a/hw/xfree86/ddc/Makefile.am
+++ b/hw/xfree86/ddc/Makefile.am
@@ -1,9 +1,8 @@
 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
 
 INCLUDES = $(XORG_INCS) -I$(srcdir)/../i2c
diff --git a/hw/xfree86/ddc/ddcProperty.c b/hw/xfree86/ddc/ddcProperty.c
index a1650bc..c68dd08 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"
 
 /*
  * xf86Mode.c should have a some more DisplayModePtr list handling.
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, int *errmaj, int *errmin)
     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 cbf4f65..f7c0434 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 0306723..0a89d08 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 $(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, const char *module,
 
     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, const char *module,
 
     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, ModuleDescPtr parent)
     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 char *path, const char **subdirlist,
     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 *modname, PatternPtr patterns)
 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 69e11d5..2d1b887 100644
--- a/hw/xfree86/loader/xf86sym.c
+++ b/hw/xfree86/loader/xf86sym.c
@@ -90,6 +90,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__) && \
@@ -1171,4 +1178,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)
commit d1170fee8a24f6fb9c6c2ff2a1d845adc37729ff
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.
    
    (cherry picked from commit 81aa7f059d3cfd8d28420b7932b8ff7e06d67979)

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;
commit f8fd7f23cf3c49ed863a18dd8324eb10d2c86a8b
Author: Eric Anholt <eric at anholt.net>
Date:   Wed Feb 14 10:39:46 2007 -0800

    Mark sync when UploadToScreen succeeds in exaGlyphs().
    
    (cherry picked from commit a5f19c5150a7b3dc2ff3ad759ee1a6ab0ad8925c)

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 */
commit c328513b36633b7100c7ca3dd7a6682c2b1f2051
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.
    (cherry picked from 8274ea6aa97b06a56b7468c3908894c0ff72b687 commit)

diff --git a/damageext/damageext.c b/damageext/damageext.c
index d13c67b..a27ca22 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;
commit 967865393c08f53c70da9c8cd2824978f2601aa4
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Wed Jan 24 20:20:48 2007 -0800

    Plug memory leak in doLoadModule()
    (cherry picked from cf7ca9d09cba14d107152a5179de38e5ef7bd784 commit)

diff --git a/hw/xfree86/loader/loadmod.c b/hw/xfree86/loader/loadmod.c
index 12f5dc9..ec0f181 100644
--- a/hw/xfree86/loader/loadmod.c
+++ b/hw/xfree86/loader/loadmod.c
@@ -903,7 +903,7 @@ doLoadModule(const char *module, const char *path, const char **subdirlist,
      * check the elements in the path
      */
     if (PathIsAbsolute(module))
-	xstrdup(module);
+	found = xstrdup(module);
     path_elem = pathlist;
     while (!found && *path_elem != NULL) {
 	found = FindModule(m, *path_elem, subdirlist, patterns);
commit 46e3ed88ccc738e6b99d0fc957617b4345392237
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Thu Jan 18 15:31:53 2007 -0800

    Make xf1bpp build correctly with compilers that don't support -include
    (cherry picked from 0f0c321adf2850b3d7aafe281362bfe424cb0ca1 commit)

diff --git a/hw/xfree86/xf1bpp/Makefile.am b/hw/xfree86/xf1bpp/Makefile.am
index e7c873a..6d510d1 100644
--- a/hw/xfree86/xf1bpp/Makefile.am
+++ b/hw/xfree86/xf1bpp/Makefile.am
@@ -27,128 +27,156 @@ libxf1bppgen_a_SOURCES = \
         mfbtileC.c \
         mfbtileG.c
 
-DISTCLEANFILES = $(libxf1bppgen_a_SOURCES)
-
 libxf1bppmfb_a_SOURCES = \
-        $(top_srcdir)/mfb/maskbits.c \
-        $(top_srcdir)/mfb/mfbbitblt.c \
-        $(top_srcdir)/mfb/mfbbres.c \
-        $(top_srcdir)/mfb/mfbbresd.c \
-        $(top_srcdir)/mfb/mfbbstore.c \
-        $(top_srcdir)/mfb/mfbclip.c \
-        $(top_srcdir)/mfb/mfbcmap.c \
-        $(top_srcdir)/mfb/mfbfillarc.c \
-        $(top_srcdir)/mfb/mfbfillrct.c \
-        $(top_srcdir)/mfb/mfbfillsp.c \
-        $(top_srcdir)/mfb/mfbfont.c \
-        $(top_srcdir)/mfb/mfbgc.c \
-        $(top_srcdir)/mfb/mfbgetsp.c \
-        $(top_srcdir)/mfb/mfbhrzvert.c \
-        $(top_srcdir)/mfb/mfbimage.c \
-        $(top_srcdir)/mfb/mfbline.c \
-        $(top_srcdir)/mfb/mfbmisc.c \
-        $(top_srcdir)/mfb/mfbpixmap.c \
-        $(top_srcdir)/mfb/mfbpntwin.c \
-        $(top_srcdir)/mfb/mfbpolypnt.c \
-        $(top_srcdir)/mfb/mfbpushpxl.c \
-        $(top_srcdir)/mfb/mfbscrclse.c \
-        $(top_srcdir)/mfb/mfbscrinit.c \
-        $(top_srcdir)/mfb/mfbsetsp.c \
-        $(top_srcdir)/mfb/mfbwindow.c \
-        $(top_srcdir)/mfb/mfbzerarc.c \
-        mfbmodule.c
+        maskbits.c \
+        mfbbitblt.c \
+        mfbbres.c \
+        mfbbresd.c \
+        mfbbstore.c \
+        mfbclip.c \
+        mfbcmap.c \
+        mfbfillarc.c \
+        mfbfillrct.c \
+        mfbfillsp.c \
+        mfbfont.c \
+        mfbgc.c \
+        mfbgetsp.c \
+        mfbhrzvert.c \
+        mfbimage.c \
+        mfbline.c \
+        mfbmisc.c \
+        mfbpixmap.c \
+        mfbpntwin.c \
+        mfbpolypnt.c \
+        mfbpushpxl.c \
+        mfbscrclse.c \
+        mfbscrinit.c \
+        mfbsetsp.c \
+        mfbwindow.c \
+        mfbzerarc.c
+
+BUILT_SOURCES = $(libxf1bppgen_a_SOURCES) $(libxf1bppgen_a_SOURCES)
 
-libxf1bpp_la_SOURCES = $(libxf1bppmfb_a_SOURCES) $(libxf1bppgen_a_SOURCES)
+libxf1bpp_la_SOURCES = $(libxf1bppmfb_a_SOURCES) $(libxf1bppgen_a_SOURCES) \
+        mfbmodule.c
 
-AM_CFLAGS = -DXF86MONO -include mfbmap.h $(DIX_CFLAGS) $(XORG_CFLAGS)
+AM_CFLAGS = -DXF86MONO $(DIX_CFLAGS) $(XORG_CFLAGS)
 INCLUDES = $(XORG_INCS) -I$(top_srcdir)/mfb
 
 mfbseg.c:
 	echo "#define POLYSEGMENT" > $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbline.c\"" >> $@
 mfbpgbwht.c:
 	echo "#define MFBPOLYGLYPHBLT xf1bppPolyGlyphBltWhite" > $@
 	echo "#define OPEQ |=" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbplygblt.c\"" >> $@
 mfbpgbblak.c:
 	echo "#define MFBPOLYGLYPHBLT xf1bppPolyGlyphBltBlack" > $@
 	echo "#define OPEQ &=~" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbplygblt.c\"" >> $@
 mfbpgbinv.c:
 	echo "#define MFBPOLYGLYPHBLT xf1bppPolyGlyphBltInvert" > $@
 	echo "#define OPEQ ^=" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbplygblt.c\"" >> $@
 mfbigbwht.c:
 	echo "#define MFBIMAGEGLYPHBLT xf1bppImageGlyphBltWhite" > $@
 	echo "#define OPEQ |=" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbimggblt.c\"" >> $@
 mfbigbblak.c:
 	echo "#define MFBIMAGEGLYPHBLT xf1bppImageGlyphBltBlack" > $@
 	echo "#define OPEQ &=~" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbimggblt.c\"" >> $@
 mfbpawhite.c:
 	echo "#define MFBSOLIDFILLAREA xf1bppSolidWhiteArea" > $@
 	echo "#define MFBSTIPPLEFILLAREA xf1bppStippleWhiteArea" >> $@
 	echo "#define OPEQ |=" >> $@
 	echo "#define EQWHOLEWORD =~0" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbpntarea.c\"" >> $@
 mfbpablack.c:
 	echo "#define MFBSOLIDFILLAREA xf1bppSolidBlackArea" > $@
 	echo "#define MFBSTIPPLEFILLAREA xf1bppStippleBlackArea" >> $@
 	echo "#define OPEQ &=~" >> $@
 	echo "#define EQWHOLEWORD =0" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbpntarea.c\"" >> $@
 mfbpainv.c:
 	echo "#define MFBSOLIDFILLAREA xf1bppSolidInvertArea" > $@
 	echo "#define MFBSTIPPLEFILLAREA xf1bppStippleInvertArea" >> $@
 	echo "#define OPEQ ^=" >> $@
 	echo "#define EQWHOLEWORD ^=~0" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbpntarea.c\"" >> $@
 mfbtewhite.c:
 	echo "#define OP" > $@
 	echo "#define CLIPTETEXT xf1bppImageGlyphBltWhite" >> $@
 	echo "#define MFBTEGLYPHBLT xf1bppTEGlyphBltWhite" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbtegblt.c\"" >> $@
 mfbteblack.c:
 	echo "#define OP ~" > $@
 	echo "#define CLIPTETEXT xf1bppImageGlyphBltBlack" >> $@
 	echo "#define MFBTEGLYPHBLT xf1bppTEGlyphBltBlack" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbtegblt.c\"" >> $@
 mfbplywhite.c:
 	echo "#define MFBFILLPOLY1RECT xf1bppFillPolyWhite" > $@
 	echo "#define OPEQ |=" >> $@
 	echo "#define EQWHOLEWORD =~0" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbply1rct.c\"" >> $@
 mfbplyblack.c:
 	echo "#define MFBFILLPOLY1RECT xf1bppFillPolyBlack" > $@
 	echo "#define OPEQ &=~" >> $@
 	echo "#define EQWHOLEWORD =0" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbply1rct.c\"" >> $@
 mfbplyinv.c:
 	echo "#define MFBFILLPOLY1RECT xf1bppFillPolyInvert" > $@
 	echo "#define OPEQ ^=" >> $@
 	echo "#define EQWHOLEWORD ^=~0" >> $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbply1rct.c\"" >> $@
 mfbbltC.c:
 	echo "#define MROP Mcopy" > $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbblt.c\"" >> $@
 mfbbltX.c:
 	echo "#define MROP Mxor" > $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbblt.c\"" >> $@
 mfbbltCI.c:
 	echo "#define MROP McopyInverted" > $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbblt.c\"" >> $@
 mfbbltO.c:
 	echo "#define MROP Mor" > $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbblt.c\"" >> $@
 mfbbltG.c:
 	echo "#define MROP M0" > $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbblt.c\"" >> $@
 mfbtileC.c:
 	echo "#define MROP Mcopy" > $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbtile.c\"" >> $@
 mfbtileG.c:
 	echo "#define MRop M0" > $@
+	echo "#include \"mfbmap.h\"" >> $@
 	echo "#include \"$(top_srcdir)/mfb/mfbtile.c\"" >> $@
 
+$(libxf1bppmfb_a_SOURCES):
+	for i in $(libxf1bppmfb_a_SOURCES) ; do \
+		echo "#include \"mfbmap.h\"" > $$i ; \
+		echo "#include \"$(top_srcdir)/mfb/$$i\"" >> $$i ; \
+	done
+
+
 EXTRA_DIST = mfbmap.sh mfbunmap.sh 
commit ed1778cfb2135ee4d21949d8f724e24699bb5e94
Author: Eric Anholt <eric at anholt.net>
Date:   Mon Feb 12 16:08:00 2007 -0800

    Merge EXA updates up to commit cf5b29d75dad7c74543f49f010c817623a3df747.
    
    This is EXA version 2.1, including the damagetrack work.

diff --git a/exa/exa.c b/exa/exa.c
index b490653..e9f42df 100644
--- a/exa/exa.c
+++ b/exa/exa.c
@@ -32,6 +32,10 @@
 #include <dix-config.h>
 #endif
 
+#ifdef MITSHM
+#include "shmint.h"
+#endif
+
 #include <stdlib.h>
 
 #include "exa_priv.h"
@@ -118,17 +122,77 @@ exaGetDrawablePixmap(DrawablePtr pDrawable)
 }	
 
 /**
+ * Sets the offsets to add to coordinates to make them address the same bits in
+ * the backing drawable. These coordinates are nonzero only for redirected
+ * windows.
+ */
+static void
+exaGetDrawableDeltas (DrawablePtr pDrawable, PixmapPtr pPixmap,
+		      int *xp, int *yp)
+{
+#ifdef COMPOSITE
+    if (pDrawable->type == DRAWABLE_WINDOW) {
+	*xp = -pPixmap->screen_x;
+	*yp = -pPixmap->screen_y;
+	return;
+    }
+#endif
+
+    *xp = 0;
+    *yp = 0;
+}
+
+/**
+ * exaPixmapDirty() marks a pixmap as dirty, allowing for
+ * optimizations in pixmap migration when no changes have occurred.
+ */
+void
+exaPixmapDirty (PixmapPtr pPix, int x1, int y1, int x2, int y2)
+{
+    ExaPixmapPriv(pPix);
+    BoxRec box;
+    RegionPtr pDamageReg;
+    RegionRec region;
+
+    if (!pExaPixmap)
+	return;
+	
+    box.x1 = max(x1, 0);
+    box.y1 = max(y1, 0);
+    box.x2 = min(x2, pPix->drawable.width);
+    box.y2 = min(y2, pPix->drawable.height);
+
+    if (box.x1 >= box.x2 || box.y1 >= box.y2)
+	return;
+
+    pDamageReg = DamageRegion(pExaPixmap->pDamage);
+
+    REGION_INIT(pScreen, &region, &box, 1);
+    REGION_UNION(pScreen, pDamageReg, pDamageReg, &region);
+    REGION_UNINIT(pScreen, &region);
+}
+
+/**
  * exaDrawableDirty() marks a pixmap backing a drawable as dirty, allowing for
  * optimizations in pixmap migration when no changes have occurred.
  */
 void
-exaDrawableDirty (DrawablePtr pDrawable)
+exaDrawableDirty (DrawablePtr pDrawable, int x1, int y1, int x2, int y2)
 {
-    ExaPixmapPrivPtr pExaPixmap;
+    PixmapPtr pPix = exaGetDrawablePixmap(pDrawable);
+    int xoff, yoff;
 
-    pExaPixmap = ExaGetPixmapPriv(exaGetDrawablePixmap (pDrawable));
-    if (pExaPixmap != NULL)
-	pExaPixmap->dirty = TRUE;
+    x1 = max(x1, pDrawable->x);
+    y1 = max(y1, pDrawable->y);
+    x2 = min(x2, pDrawable->x + pDrawable->width);
+    y2 = min(y2, pDrawable->y + pDrawable->height);
+
+    if (x1 >= x2 || y1 >= y2)
+	return;
+
+    exaGetDrawableDeltas(pDrawable, pPix, &xoff, &yoff);
+
+    exaPixmapDirty(pPix, x1 + xoff, y1 + yoff, x2 + xoff, y2 + yoff);
 }
 
 static Bool
@@ -149,6 +213,7 @@ exaDestroyPixmap (PixmapPtr pPixmap)
 	    pPixmap->devPrivate.ptr = pExaPixmap->sys_ptr;
 	    pPixmap->devKind = pExaPixmap->sys_pitch;
 	}
+	REGION_UNINIT(pPixmap->drawable.pScreen, &pExaPixmap->validReg);
     }
     return fbDestroyPixmap (pPixmap);
 }
@@ -216,7 +281,20 @@ exaCreatePixmap(ScreenPtr pScreen, int w, int h, int depth)
 	return NULL;
     }
 
-    pExaPixmap->dirty = FALSE;
+    /* Set up damage tracking */
+    pExaPixmap->pDamage = DamageCreate (NULL, NULL, DamageReportNone, TRUE,
+					pScreen, pPixmap);
+
+    if (pExaPixmap->pDamage == NULL) {
+	fbDestroyPixmap (pPixmap);
+	return NULL;
+    }
+
+    DamageRegister (&pPixmap->drawable, pExaPixmap->pDamage);
+    DamageSetReportAfterOp (pExaPixmap->pDamage, TRUE);
+
+    /* None of the pixmap bits are valid initially */
+    REGION_NULL(pScreen, &pExaPixmap->validReg);
 
     return pPixmap;
 }
@@ -261,32 +339,14 @@ exaDrawableIsOffscreen (DrawablePtr pDrawable)
 /**
  * Returns the pixmap which backs a drawable, and the offsets to add to
  * coordinates to make them address the same bits in the backing drawable.
- * These coordinates are nonzero only for redirected windows.
  */
 PixmapPtr
 exaGetOffscreenPixmap (DrawablePtr pDrawable, int *xp, int *yp)
 {
-    PixmapPtr	pPixmap;
-    int		x, y;
+    PixmapPtr	pPixmap = exaGetDrawablePixmap (pDrawable);
+
+    exaGetDrawableDeltas (pDrawable, pPixmap, xp, yp);
 
-    if (pDrawable->type == DRAWABLE_WINDOW) {
-	pPixmap = (*pDrawable->pScreen->GetWindowPixmap) ((WindowPtr) pDrawable);
-#ifdef COMPOSITE
-	x = -pPixmap->screen_x;
-	y = -pPixmap->screen_y;
-#else
-	x = 0;
-	y = 0;
-#endif
-    }
-    else
-    {
-	pPixmap = (PixmapPtr) pDrawable;
-	x = 0;
-	y = 0;
-    }
-    *xp = x;
-    *yp = y;
     if (exaPixmapIsOffscreen (pPixmap))
 	return pPixmap;
     else
@@ -334,8 +394,7 @@ exaPrepareAccess(DrawablePtr pDrawable, int index)
 /**
  * exaFinishAccess() is EXA's wrapper for the driver's FinishAccess() handler.
  *
- * It deals with marking drawables as dirty, and calling the driver's
- * FinishAccess() only if necessary.
+ * It deals with calling the driver's FinishAccess() only if necessary.
  */
 void
 exaFinishAccess(DrawablePtr pDrawable, int index)
@@ -345,9 +404,6 @@ exaFinishAccess(DrawablePtr pDrawable, int index)
     PixmapPtr	    pPixmap;
     ExaPixmapPrivPtr pExaPixmap;
 
-    if (index == EXA_PREPARE_DEST)
-	exaDrawableDirty (pDrawable);
-
     pPixmap = exaGetDrawablePixmap (pDrawable);
 
     pExaPixmap = ExaGetPixmapPriv(pPixmap);
@@ -373,7 +429,7 @@ exaFinishAccess(DrawablePtr pDrawable, int index)
  * accelerated or may sync the card and fall back to fb.
  */
 static void
-exaValidateGC (GCPtr pGC, Mask changes, DrawablePtr pDrawable)
+exaValidateGC (GCPtr pGC, unsigned long changes, DrawablePtr pDrawable)
 {
     /* fbValidateGC will do direct access to pixmaps if the tiling has changed.
      * Preempt fbValidateGC by doing its work and masking the change out, so
@@ -404,6 +460,7 @@ exaValidateGC (GCPtr pGC, Mask changes, DrawablePtr pDrawable)
 		exaPrepareAccess(&pOldTile->drawable, EXA_PREPARE_SRC);
 		pNewTile = fb24_32ReformatTile (pOldTile,
 						pDrawable->bitsPerPixel);
+		exaPixmapDirty(pNewTile, 0, 0, pNewTile->drawable.width, pNewTile->drawable.height);
 		exaFinishAccess(&pOldTile->drawable, EXA_PREPARE_SRC);
 	    }
 	    if (pNewTile)
@@ -419,9 +476,14 @@ exaValidateGC (GCPtr pGC, Mask changes, DrawablePtr pDrawable)
 	if (!pGC->tileIsPixel && FbEvenTile (pGC->tile.pixmap->drawable.width *
 					     pDrawable->bitsPerPixel))
 	{
-	    exaPrepareAccess(&pGC->tile.pixmap->drawable, EXA_PREPARE_SRC);
+	    /* XXX This fixes corruption with tiled pixmaps, but may just be a
+	     * workaround for broken drivers
+	     */
+	    exaMoveOutPixmap(pGC->tile.pixmap);
 	    fbPadPixmap (pGC->tile.pixmap);
-	    exaFinishAccess(&pGC->tile.pixmap->drawable, EXA_PREPARE_SRC);
+	    exaPixmapDirty(pGC->tile.pixmap, 0, 0,
+			   pGC->tile.pixmap->drawable.width,
+			   pGC->tile.pixmap->drawable.height);
 	}
 	/* Mask out the GCTile change notification, now that we've done FB's
 	 * job for it.
@@ -560,7 +622,7 @@ exaDriverInit (ScreenPtr		pScreen,
 
     pScreen->devPrivates[exaScreenPrivateIndex].ptr = (pointer) pExaScr;
 
-    pExaScr->migration = ExaMigrationSmart;
+    pExaScr->migration = ExaMigrationAlways;
 
     exaDDXDriverInit(pScreen);
 
@@ -610,6 +672,13 @@ exaDriverInit (ScreenPtr		pScreen,
     miDisableCompositeWrapper(pScreen);
 #endif
 
+#ifdef MITSHM
+    /* Re-register with the MI funcs, which don't allow shared pixmaps.
+     * Shared pixmaps are almost always a performance loss for us, but this
+     * still allows for SHM PutImage.
+     */
+    ShmRegisterFuncs(pScreen, NULL);
+#endif
     /*
      * Hookup offscreen pixmaps
      */
diff --git a/exa/exa.h b/exa/exa.h
index 96465a7..bf723f7 100644
--- a/exa/exa.h
+++ b/exa/exa.h
@@ -39,7 +39,7 @@
 #include "fb.h"
 
 #define EXA_VERSION_MAJOR   2
-#define EXA_VERSION_MINOR   0
+#define EXA_VERSION_MINOR   1
 #define EXA_VERSION_RELEASE 0
 
 typedef struct _ExaOffscreenArea ExaOffscreenArea;
@@ -73,8 +73,8 @@ struct _ExaOffscreenArea {
 typedef struct _ExaDriver {
     /**
      * exa_major and exa_minor should be set by the driver to the version of
-     * EXA which the driver was compiled for (or configures itself at runtime to
-     * support).  This allows EXA to extend the structure for new features
+     * EXA which the driver was compiled for (or configures itself at runtime
+     * to support).  This allows EXA to extend the structure for new features
      * without breaking ABI for drivers compiled against older versions.
      */
     int exa_major, exa_minor;
@@ -716,6 +716,12 @@ exaGetPixmapSize(PixmapPtr pPix);
 void
 exaEnableDisableFBAccess (int index, Bool enable);
 
+void
+exaMoveInPixmap (PixmapPtr pPixmap);
+
+void
+exaMoveOutPixmap (PixmapPtr pPixmap);
+
 /**
  * Returns TRUE if the given planemask covers all the significant bits in the
  * pixel values for pDrawable.
diff --git a/exa/exa_accel.c b/exa/exa_accel.c
index bc77a40..6fa481a 100644
--- a/exa/exa_accel.c
+++ b/exa/exa_accel.c
@@ -20,6 +20,11 @@
  * 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.
+ *
+ * Authors:
+ *    Eric Anholt <eric at anholt.net>
+ *    Michel Dänzer <michel at tungstengraphics.com>
+ *
  */
 
 #ifdef HAVE_DIX_CONFIG_H
@@ -49,12 +54,12 @@ exaFillSpans(DrawablePtr pDrawable, GCPtr pGC, int n,
 
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = FALSE;
-    pixmaps[0].pPix = exaGetDrawablePixmap (pDrawable);
+    pixmaps[0].pPix = pPixmap = exaGetDrawablePixmap (pDrawable);
 
     if (pExaScr->swappedOut ||
 	pGC->fillStyle != FillSolid ||
-	pDrawable->width > pExaScr->info->maxX ||
-	pDrawable->height > pExaScr->info->maxY)
+	pPixmap->drawable.width > pExaScr->info->maxX ||
+	pPixmap->drawable.height > pExaScr->info->maxY)
     {
 	exaDoMigration (pixmaps, 1, FALSE);
 	ExaCheckFillSpans (pDrawable, pGC, n, ppt, pwidth, fSorted);
@@ -104,6 +109,8 @@ exaFillSpans(DrawablePtr pDrawable, GCPtr pGC, int n,
 	    (*pExaScr->info->Solid) (pPixmap,
 				     fullX1 + off_x, fullY1 + off_y,
 				     fullX2 + off_x, fullY1 + 1 + off_y);
+	    exaPixmapDirty (pPixmap, fullX1 + off_x, fullY1 + off_y,
+			    fullX2 + off_x, fullY1 + 1 + off_y);
 	}
 	else
 	{
@@ -118,17 +125,19 @@ exaFillSpans(DrawablePtr pDrawable, GCPtr pGC, int n,
 		    partX2 = pbox->x2;
 		    if (partX2 > fullX2)
 			partX2 = fullX2;
-		    if (partX2 > partX1)
+		    if (partX2 > partX1) {
 			(*pExaScr->info->Solid) (pPixmap,
 						 partX1 + off_x, fullY1 + off_y,
 						 partX2 + off_x, fullY1 + 1 + off_y);
+			exaPixmapDirty (pPixmap, partX1 + off_x, fullY1 + off_y,
+					partX2 + off_x, fullY1 + 1 + off_y);
+		    }
 		}
 		pbox++;
 	    }
 	}
     }
     (*pExaScr->info->DoneSolid) (pPixmap);
-    exaDrawableDirty (pDrawable);
     exaMarkSync(pScreen);
 }
 
@@ -222,8 +231,8 @@ exaPutImage (DrawablePtr pDrawable, GCPtr pGC, int depth, int x, int y,
 
 	    exaFinishAccess(pDrawable, EXA_PREPARE_DEST);
 	}
+	exaPixmapDirty(pPix, x1 + xoff, y1 + yoff, x2 + xoff, y2 + yoff);
     }
-    exaDrawableDirty(pDrawable);
 
     return;
 
@@ -351,11 +360,12 @@ exaCopyNtoNTwoDir (DrawablePtr pSrcDrawable, DrawablePtr pDstDrawable,
 				       dst_off_y + pbox->y1 + i,
 				       pbox->x2 - pbox->x1, 1);
 	}
+	exaPixmapDirty(pDstPixmap, dst_off_x + pbox->x1, dst_off_y + pbox->y1,
+		       dst_off_x + pbox->x2, dst_off_y + pbox->y2);
     }
     if (dirsetup != 0)
 	pExaScr->info->DoneCopy(pDstPixmap);
     exaMarkSync(pDstDrawable->pScreen);
-    exaDrawableDirty(pDstDrawable);
     return TRUE;
 }
 
@@ -380,19 +390,19 @@ exaCopyNtoN (DrawablePtr    pSrcDrawable,
 
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = FALSE;
-    pixmaps[0].pPix = exaGetDrawablePixmap (pDstDrawable);
+    pixmaps[0].pPix = pDstPixmap = exaGetDrawablePixmap (pDstDrawable);
     pixmaps[1].as_dst = FALSE;
     pixmaps[1].as_src = TRUE;
-    pixmaps[1].pPix = exaGetDrawablePixmap (pSrcDrawable);
+    pixmaps[1].pPix = pSrcPixmap = exaGetDrawablePixmap (pSrcDrawable);
 
     /* Respect maxX/maxY in a trivial way: don't set up drawing when we might
      * violate the limits.  The proper solution would be a temporary pixmap
      * adjusted so that the drawing happened within limits.
      */
-    if (pSrcDrawable->width > pExaScr->info->maxX ||
-	pSrcDrawable->height > pExaScr->info->maxY ||
-	pDstDrawable->width > pExaScr->info->maxX ||
-	pDstDrawable->height > pExaScr->info->maxY)
+    if (pSrcPixmap->drawable.width > pExaScr->info->maxX ||
+	pSrcPixmap->drawable.height > pExaScr->info->maxY ||
+	pDstPixmap->drawable.width > pExaScr->info->maxX ||
+	pDstPixmap->drawable.height > pExaScr->info->maxY)
     {
 	exaDoMigration (pixmaps, 2, FALSE);
 	goto fallback;
@@ -401,7 +411,8 @@ exaCopyNtoN (DrawablePtr    pSrcDrawable,
     }
 
     /* Mixed directions must be handled specially if the card is lame */
-    if (pExaScr->info->flags & EXA_TWO_BITBLT_DIRECTIONS && (dx*dy) < 0) {
+    if (pExaScr->info->flags & EXA_TWO_BITBLT_DIRECTIONS &&
+	reverse != upsidedown) {
 	if (!exaCopyNtoNTwoDir(pSrcDrawable, pDstDrawable, pGC, pbox, nbox,
 			       dx, dy))
 	    goto fallback;
@@ -411,7 +422,7 @@ exaCopyNtoN (DrawablePtr    pSrcDrawable,
     if ((pSrcPixmap = exaGetOffscreenPixmap (pSrcDrawable, &src_off_x, &src_off_y)) &&
 	(pDstPixmap = exaGetOffscreenPixmap (pDstDrawable, &dst_off_x, &dst_off_y)) &&
 	(*pExaScr->info->PrepareCopy) (pSrcPixmap, pDstPixmap,
-				       dx, dy,
+				       reverse ? -1 : 1, upsidedown ? -1 : 1,
 				       pGC ? pGC->alu : GXcopy,
 				       pGC ? pGC->planemask : FB_ALLONES))
     {
@@ -423,11 +434,13 @@ exaCopyNtoN (DrawablePtr    pSrcDrawable,
 				    pbox->x1 + dst_off_x, pbox->y1 + dst_off_y,
 				    pbox->x2 - pbox->x1,
 				    pbox->y2 - pbox->y1);
+	    exaPixmapDirty (pDstPixmap,
+			    pbox->x1 + dst_off_x, pbox->y1 + dst_off_y,
+			    pbox->x2 + dst_off_x, pbox->y2 + dst_off_y);
 	    pbox++;
 	}
 	(*pExaScr->info->DoneCopy) (pDstPixmap);
 	exaMarkSync(pDstDrawable->pScreen);
-	exaDrawableDirty (pDstDrawable);
 	return;
     }
 
@@ -442,6 +455,11 @@ fallback:
 		bitplane, closure);
     exaFinishAccess (pSrcDrawable, EXA_PREPARE_SRC);
     exaFinishAccess (pDstDrawable, EXA_PREPARE_DEST);
+    while (nbox--)
+    {
+	exaDrawableDirty (pDstDrawable, pbox->x1, pbox->y1, pbox->x2, pbox->y2);
+	pbox++;
+    }
 }
 
 RegionPtr
@@ -621,12 +639,12 @@ exaPolyFillRect(DrawablePtr pDrawable,
 
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = FALSE;
-    pixmaps[0].pPix = exaGetDrawablePixmap (pDrawable);
+    pixmaps[0].pPix = pPixmap = exaGetDrawablePixmap (pDrawable);
  
     if (pExaScr->swappedOut ||
 	pGC->fillStyle != FillSolid ||
-	pDrawable->width > pExaScr->info->maxX ||
-	pDrawable->height > pExaScr->info->maxY)
+	pPixmap->drawable.width > pExaScr->info->maxX ||
+	pPixmap->drawable.height > pExaScr->info->maxY)
     {
 	exaDoMigration (pixmaps, 1, FALSE);
 	ExaCheckPolyFillRect (pDrawable, pGC, nrect, prect);
@@ -681,6 +699,8 @@ exaPolyFillRect(DrawablePtr pDrawable,
 	    (*pExaScr->info->Solid) (pPixmap,
 				     fullX1 + xoff, fullY1 + yoff,
 				     fullX2 + xoff, fullY2 + yoff);
+	    exaPixmapDirty (pPixmap, fullX1 + xoff, fullY1 + yoff,
+			    fullX2 + xoff, fullY2 + yoff);
 	}
 	else
 	{
@@ -706,15 +726,17 @@ exaPolyFillRect(DrawablePtr pDrawable,
 
 		pbox++;
 
-		if (partX1 < partX2 && partY1 < partY2)
+		if (partX1 < partX2 && partY1 < partY2) {
 		    (*pExaScr->info->Solid) (pPixmap,
 					     partX1 + xoff, partY1 + yoff,
 					     partX2 + xoff, partY2 + yoff);
+		    exaPixmapDirty (pPixmap, partX1 + xoff, partY1 + yoff,
+				    partX2 + xoff, partY2 + yoff);
+		}
 	    }
 	}
     }
     (*pExaScr->info->DoneSolid) (pPixmap);
-    exaDrawableDirty (pDrawable);
     exaMarkSync(pDrawable->pScreen);
 }
 
@@ -735,14 +757,15 @@ exaSolidBoxClipped (DrawablePtr	pDrawable,
     int		xoff, yoff;
     int		partX1, partX2, partY1, partY2;
     ExaMigrationRec pixmaps[1];
+    Bool	fallback = FALSE;
 
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = FALSE;
-    pixmaps[0].pPix = exaGetDrawablePixmap (pDrawable);
- 
+    pixmaps[0].pPix = pPixmap = exaGetDrawablePixmap (pDrawable);
+
     if (pExaScr->swappedOut ||
-	pDrawable->width > pExaScr->info->maxX ||
-	pDrawable->height > pExaScr->info->maxY)
+	pPixmap->drawable.width > pExaScr->info->maxX ||
+	pPixmap->drawable.height > pExaScr->info->maxY)
     {
 	exaDoMigration (pixmaps, 1, FALSE);
 	goto fallback;
@@ -750,19 +773,21 @@ exaSolidBoxClipped (DrawablePtr	pDrawable,
 	exaDoMigration (pixmaps, 1, TRUE);
     }
 
-    if (!(pPixmap = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff)) ||
+    pPixmap = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff);
+
+    if (!pPixmap ||
 	!(*pExaScr->info->PrepareSolid) (pPixmap, GXcopy, pm, fg))
     {
 fallback:
 	EXA_FALLBACK(("to %p (%c)\n", pDrawable,
 		      exaDrawableLocation(pDrawable)));
+	fallback = TRUE;
 	exaPrepareAccess (pDrawable, EXA_PREPARE_DEST);
 	fg = fbReplicatePixel (fg, pDrawable->bitsPerPixel);
 	fbSolidBoxClipped (pDrawable, pClip, x1, y1, x2, y2,
 			   fbAnd (GXcopy, fg, pm),
 			   fbXor (GXcopy, fg, pm));
 	exaFinishAccess (pDrawable, EXA_PREPARE_DEST);
-	return;
     }
     for (nbox = REGION_NUM_RECTS(pClip), pbox = REGION_RECTS(pClip);
 	 nbox--;
@@ -790,12 +815,20 @@ fallback:
 	if (partY2 <= partY1)
 	    continue;
 
-	(*pExaScr->info->Solid) (pPixmap,
-				 partX1 + xoff, partY1 + yoff,
-				 partX2 + xoff, partY2 + yoff);
+	if (!fallback) {
+	    (*pExaScr->info->Solid) (pPixmap,
+				     partX1 + xoff, partY1 + yoff,
+				     partX2 + xoff, partY2 + yoff);
+	    exaPixmapDirty (pPixmap, partX1 + xoff, partY1 + yoff,
+			    partX2 + xoff, partY2 + yoff);
+	} else
+	    exaDrawableDirty (pDrawable, partX1, partY1, partX2, partY2);
     }
+
+    if (fallback)
+	return;
+
     (*pExaScr->info->DoneSolid) (pPixmap);
-    exaDrawableDirty (pDrawable);
     exaMarkSync(pDrawable->pScreen);
 }
 
@@ -908,12 +941,17 @@ exaImageGlyphBlt (DrawablePtr	pDrawable,
 			  pPriv->fg,
 			  gx + dstXoff,
 			  gHeight);
+		exaDrawableDirty (pDrawable, gx, gy, gx + gWidth, gy + gHeight);
 	    }
 	    else
 	    {
+		RegionPtr pClip = fbGetCompositeClip(pGC);
+		int nbox;
+		BoxPtr pbox;
+
 		gStride = GLYPHWIDTHBYTESPADDED(pci) / sizeof (FbStip);
 		fbPutXYImage (pDrawable,
-			      fbGetCompositeClip(pGC),
+			      pClip,
 			      pPriv->fg,
 			      pPriv->bg,
 			      pPriv->pm,
@@ -927,6 +965,18 @@ exaImageGlyphBlt (DrawablePtr	pDrawable,
 			      (FbStip *) pglyph,
 			      gStride,
 			      0);
+
+		for (nbox = REGION_NUM_RECTS(pClip), pbox = REGION_RECTS(pClip);
+		     nbox--; pbox++) {
+		    int x1 = max(gx, pbox->x1), x2 = min(gx + gWidth, pbox->x2);
+		    int y1 = max(gy, pbox->y1), y2 = min(gy + gHeight, pbox->y2);
+
+		    if (x1 >= x2 || y1 >= y2)
+			continue;
+
+		    exaDrawableDirty (pDrawable, gx, gy, gx + gWidth,
+				      gy + gHeight);
+		}
 	    }
 	}
 	x += pci->metrics.characterWidth;
@@ -994,13 +1044,15 @@ exaFillRegionSolid (DrawablePtr	pDrawable,
     PixmapPtr pPixmap;
     int xoff, yoff;
     ExaMigrationRec pixmaps[1];
+    int nbox = REGION_NUM_RECTS (pRegion);
+    BoxPtr pBox = REGION_RECTS (pRegion);
 
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = FALSE;
-    pixmaps[0].pPix = exaGetDrawablePixmap (pDrawable);
+    pixmaps[0].pPix = pPixmap = exaGetDrawablePixmap (pDrawable);
  
-    if (pDrawable->width > pExaScr->info->maxX ||
-	pDrawable->height > pExaScr->info->maxY)
+    if (pPixmap->drawable.width > pExaScr->info->maxX ||
+	pPixmap->drawable.height > pExaScr->info->maxY)
     {
 	exaDoMigration (pixmaps, 1, FALSE);
 	goto fallback;
@@ -1011,19 +1063,17 @@ exaFillRegionSolid (DrawablePtr	pDrawable,
     if ((pPixmap = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff)) &&
 	(*pExaScr->info->PrepareSolid) (pPixmap, GXcopy, FB_ALLONES, pixel))
     {
-	int	nbox = REGION_NUM_RECTS (pRegion);
-	BoxPtr	pBox = REGION_RECTS (pRegion);
-
 	while (nbox--)
 	{
 	    (*pExaScr->info->Solid) (pPixmap,
 				     pBox->x1 + xoff, pBox->y1 + yoff,
 				     pBox->x2 + xoff, pBox->y2 + yoff);
+	    exaPixmapDirty (pPixmap, pBox->x1 + xoff, pBox->y1 + yoff,
+			    pBox->x2 + xoff, pBox->y2 + yoff);
 	    pBox++;
 	}
 	(*pExaScr->info->DoneSolid) (pPixmap);
 	exaMarkSync(pDrawable->pScreen);
-	exaDrawableDirty (pDrawable);
     }
     else
     {
@@ -1034,6 +1084,11 @@ fallback:
 	fbFillRegionSolid (pDrawable, pRegion, 0,
 			   fbReplicatePixel (pixel, pDrawable->bitsPerPixel));
 	exaFinishAccess (pDrawable, EXA_PREPARE_DEST);
+	while (nbox--)
+	{
+	    exaDrawableDirty (pDrawable, pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+	    pBox++;
+	}
     }
 }
 
@@ -1047,9 +1102,11 @@ exaFillRegionTiled (DrawablePtr	pDrawable,
 {
     ExaScreenPriv(pDrawable->pScreen);
     PixmapPtr pPixmap;
-    int xoff, yoff;
+    int xoff, yoff, tileXoff, tileYoff;
     int tileWidth, tileHeight;
     ExaMigrationRec pixmaps[2];
+    int nbox = REGION_NUM_RECTS (pRegion);
+    BoxPtr pBox = REGION_RECTS (pRegion);
 
     tileWidth = pTile->drawable.width;
     tileHeight = pTile->drawable.height;
@@ -1064,13 +1121,13 @@ exaFillRegionTiled (DrawablePtr	pDrawable,
 
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = FALSE;
-    pixmaps[0].pPix = exaGetDrawablePixmap (pDrawable);
+    pixmaps[0].pPix = pPixmap = exaGetDrawablePixmap (pDrawable);
     pixmaps[1].as_dst = FALSE;
     pixmaps[1].as_src = TRUE;
     pixmaps[1].pPix = pTile;
 
-    if (pDrawable->width > pExaScr->info->maxX ||
-	pDrawable->height > pExaScr->info->maxY ||
+    if (pPixmap->drawable.width > pExaScr->info->maxX ||
+	pPixmap->drawable.height > pExaScr->info->maxY ||
 	tileWidth > pExaScr->info->maxX ||
 	tileHeight > pExaScr->info->maxY)
     {
@@ -1081,18 +1138,16 @@ exaFillRegionTiled (DrawablePtr	pDrawable,
     }
 
     pPixmap = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff);
+
     if (!pPixmap)
 	goto fallback;
 
     if (!exaPixmapIsOffscreen(pTile))
 	goto fallback;
 
-    if ((*pExaScr->info->PrepareCopy) (pTile, pPixmap, 0, 0, GXcopy,
+    if ((*pExaScr->info->PrepareCopy) (exaGetOffscreenPixmap((DrawablePtr)pTile, &tileXoff, &tileYoff), pPixmap, 0, 0, GXcopy,
 				       FB_ALLONES))
     {
-	int nbox = REGION_NUM_RECTS (pRegion);
-	BoxPtr pBox = REGION_RECTS (pRegion);
-
 	while (nbox--)
 	{
 	    int height = pBox->y2 - pBox->y1;
@@ -1118,7 +1173,7 @@ exaFillRegionTiled (DrawablePtr	pDrawable,
 		    width -= w;
 
 		    (*pExaScr->info->Copy) (pPixmap,
-					    tileX, tileY,
+					    tileX + tileXoff, tileY + tileYoff,
 					    dstX + xoff, dstY + yoff,
 					    w, h);
 		    dstX += w;
@@ -1127,11 +1182,12 @@ exaFillRegionTiled (DrawablePtr	pDrawable,
 		dstY += h;
 		tileY = 0;
 	    }
+	    exaPixmapDirty (pPixmap, pBox->x1 + xoff, pBox->y1 + yoff,
+			    pBox->x2 + xoff, pBox->y2 + yoff);
 	    pBox++;
 	}
 	(*pExaScr->info->DoneCopy) (pPixmap);
 	exaMarkSync(pDrawable->pScreen);
-	exaDrawableDirty (pDrawable);
 	return;
     }
 
@@ -1144,6 +1200,11 @@ fallback:
     fbFillRegionTiled (pDrawable, pRegion, pTile);
     exaFinishAccess ((DrawablePtr)pTile, EXA_PREPARE_SRC);
     exaFinishAccess (pDrawable, EXA_PREPARE_DEST);
+    while (nbox--)
+    {
+	exaDrawableDirty (pDrawable, pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+	pBox++;
+    }
 }
 
 void
diff --git a/exa/exa_migration.c b/exa/exa_migration.c
index 06a4b93..eedc5fd 100644
--- a/exa/exa_migration.c
+++ b/exa/exa_migration.c
@@ -22,6 +22,7 @@
  *
  * Authors:
  *    Eric Anholt <eric at anholt.net>
+ *    Michel Dänzer <michel at tungstengraphics.com>
  *
  */
 
@@ -58,6 +59,27 @@ exaPixmapIsPinned (PixmapPtr pPix)
 }
 
 /**
+ * The fallback path for UTS/DFS failing is to just memcpy.  exaCopyDirtyToSys
+ * and exaCopyDirtyToFb both needed to do this loop.
+ */
+static void
+exaMemcpyBox (PixmapPtr pPixmap, BoxPtr pbox, CARD8 *src, int src_pitch,
+	      CARD8 *dst, int dst_pitch)
+ {
+    int i, cpp = pPixmap->drawable.bitsPerPixel / 8;
+    int bytes = (pbox->x2 - pbox->x1) * cpp;
+
+    src += pbox->y1 * src_pitch + pbox->x1 * cpp;
+    dst += pbox->y1 * dst_pitch + pbox->x1 * cpp;
+
+    for (i = pbox->y2 - pbox->y1; i; i--) {
+	memcpy (dst, src, bytes);
+	src += src_pitch;
+	dst += dst_pitch;
+    }
+}
+ 
+/**
  * Returns TRUE if the pixmap is dirty (has been modified in its current
  * location compared to the other), or lacks a private for tracking
  * dirtiness.
@@ -67,7 +89,8 @@ exaPixmapIsDirty (PixmapPtr pPix)
 {
     ExaPixmapPriv (pPix);
 
-    return pExaPixmap == NULL || pExaPixmap->dirty == TRUE;
+    return pExaPixmap == NULL ||
+	REGION_NOTEMPTY (pScreen, DamageRegion(pExaPixmap->pDamage));
 }
 
 /**
@@ -98,54 +121,62 @@ exaCopyDirtyToSys (PixmapPtr pPixmap)
 {
     ExaScreenPriv (pPixmap->drawable.pScreen);
     ExaPixmapPriv (pPixmap);
+    RegionPtr pRegion = DamageRegion (pExaPixmap->pDamage);
     CARD8 *save_ptr;
     int save_pitch;
-
-    if (!pExaPixmap->dirty)
-	return;
+    BoxPtr pBox = REGION_RECTS(pRegion);
+    int nbox = REGION_NUM_RECTS(pRegion);
+    Bool do_sync = FALSE;
 
     save_ptr = pPixmap->devPrivate.ptr;
     save_pitch = pPixmap->devKind;
     pPixmap->devPrivate.ptr = pExaPixmap->fb_ptr;
     pPixmap->devKind = pExaPixmap->fb_pitch;
 
-    if (pExaScr->info->DownloadFromScreen == NULL ||
-	!pExaScr->info->DownloadFromScreen (pPixmap,
-					    0,
-					    0,
-					    pPixmap->drawable.width,
-					    pPixmap->drawable.height,
-					    pExaPixmap->sys_ptr,
-					    pExaPixmap->sys_pitch))
-    {
-	char *src, *dst;
-	int src_pitch, dst_pitch, i, bytes;
-
-	exaPrepareAccess(&pPixmap->drawable, EXA_PREPARE_SRC);
-
-	dst = pExaPixmap->sys_ptr;
-	dst_pitch = pExaPixmap->sys_pitch;
-	src = pExaPixmap->fb_ptr;
-	src_pitch = pExaPixmap->fb_pitch;
-	bytes = src_pitch < dst_pitch ? src_pitch : dst_pitch;
-
-	for (i = 0; i < pPixmap->drawable.height; i++) {
-	    memcpy (dst, src, bytes);
-	    dst += dst_pitch;
-	    src += src_pitch;
+    while (nbox--) {
+	pBox->x1 = max(pBox->x1, 0);
+	pBox->y1 = max(pBox->y1, 0);
+	pBox->x2 = min(pBox->x2, pPixmap->drawable.width);
+	pBox->y2 = min(pBox->y2, pPixmap->drawable.height);
+
+	if (pBox->x1 >= pBox->x2 || pBox->y1 >= pBox->y2)
+	    continue;
+
+	if (pExaScr->info->DownloadFromScreen == NULL ||
+	    !pExaScr->info->DownloadFromScreen (pPixmap,
+						pBox->x1, pBox->y1,
+						pBox->x2 - pBox->x1,
+						pBox->y2 - pBox->y1,
+						pExaPixmap->sys_ptr
+						+ pBox->y1 * pExaPixmap->sys_pitch
+						+ pBox->x1 * pPixmap->drawable.bitsPerPixel / 8,
+						pExaPixmap->sys_pitch))
+	{
+	    exaPrepareAccess(&pPixmap->drawable, EXA_PREPARE_SRC);
+	    exaMemcpyBox (pPixmap, pBox,
+			  pExaPixmap->fb_ptr, pExaPixmap->fb_pitch,
+			  pExaPixmap->sys_ptr, pExaPixmap->sys_pitch);
+	    exaFinishAccess(&pPixmap->drawable, EXA_PREPARE_SRC);
 	}
-	exaFinishAccess(&pPixmap->drawable, EXA_PREPARE_SRC);
+	else
+	    do_sync = TRUE;
+
+	pBox++;
     }
 
     /* Make sure the bits have actually landed, since we don't necessarily sync
      * when accessing pixmaps in system memory.
      */
-    exaWaitSync (pPixmap->drawable.pScreen);
+    if (do_sync)
+	exaWaitSync (pPixmap->drawable.pScreen);
 
     pPixmap->devPrivate.ptr = save_ptr;
     pPixmap->devKind = save_pitch;
 
-    pExaPixmap->dirty = FALSE;
+    /* The previously damaged bits are now no longer damaged but valid */
+    REGION_UNION(pPixmap->drawable.pScreen,
+		 &pExaPixmap->validReg, &pExaPixmap->validReg, pRegion);
+    DamageEmpty (pExaPixmap->pDamage);
 }
 
 /**
@@ -158,49 +189,59 @@ exaCopyDirtyToFb (PixmapPtr pPixmap)
 {
     ExaScreenPriv (pPixmap->drawable.pScreen);
     ExaPixmapPriv (pPixmap);
+    RegionPtr pRegion = DamageRegion (pExaPixmap->pDamage);
     CARD8 *save_ptr;
     int save_pitch;
-
-    if (!pExaPixmap->dirty)
-	return;
+    BoxPtr pBox = REGION_RECTS(pRegion);
+    int nbox = REGION_NUM_RECTS(pRegion);
+    Bool do_sync = FALSE;
 
     save_ptr = pPixmap->devPrivate.ptr;
     save_pitch = pPixmap->devKind;
     pPixmap->devPrivate.ptr = pExaPixmap->fb_ptr;
     pPixmap->devKind = pExaPixmap->fb_pitch;
 
-    if (pExaScr->info->UploadToScreen == NULL ||
-	!pExaScr->info->UploadToScreen (pPixmap,
-					0,
-					0,
-					pPixmap->drawable.width,
-					pPixmap->drawable.height,
-					pExaPixmap->sys_ptr,
-					pExaPixmap->sys_pitch))
-    {
-	char *src, *dst;
-	int src_pitch, dst_pitch, i, bytes;
-
-	exaPrepareAccess(&pPixmap->drawable, EXA_PREPARE_DEST);
-
-	dst = pExaPixmap->fb_ptr;
-	dst_pitch = pExaPixmap->fb_pitch;
-	src = pExaPixmap->sys_ptr;
-	src_pitch = pExaPixmap->sys_pitch;
-	bytes = src_pitch < dst_pitch ? src_pitch : dst_pitch;
-
-	for (i = 0; i < pPixmap->drawable.height; i++) {
-	    memcpy (dst, src, bytes);
-	    dst += dst_pitch;
-	    src += src_pitch;
+    while (nbox--) {
+	pBox->x1 = max(pBox->x1, 0);
+	pBox->y1 = max(pBox->y1, 0);
+	pBox->x2 = min(pBox->x2, pPixmap->drawable.width);
+	pBox->y2 = min(pBox->y2, pPixmap->drawable.height);
+
+	if (pBox->x1 >= pBox->x2 || pBox->y1 >= pBox->y2)
+	    continue;
+
+	if (pExaScr->info->UploadToScreen == NULL ||
+	    !pExaScr->info->UploadToScreen (pPixmap,
+					    pBox->x1, pBox->y1,
+					    pBox->x2 - pBox->x1,
+					    pBox->y2 - pBox->y1,
+					    pExaPixmap->sys_ptr
+					    + pBox->y1 * pExaPixmap->sys_pitch
+					    + pBox->x1 * pPixmap->drawable.bitsPerPixel / 8,
+					    pExaPixmap->sys_pitch))
+	{
+	    exaPrepareAccess(&pPixmap->drawable, EXA_PREPARE_DEST);
+	    exaMemcpyBox (pPixmap, pBox,
+			  pExaPixmap->sys_ptr, pExaPixmap->sys_pitch,
+			  pExaPixmap->fb_ptr, pExaPixmap->fb_pitch);
+	    exaFinishAccess(&pPixmap->drawable, EXA_PREPARE_DEST);
 	}
-	exaFinishAccess(&pPixmap->drawable, EXA_PREPARE_DEST);
+	else
+	    do_sync = TRUE;
+
+	pBox++;
     }
 
+    if (do_sync)
+	exaMarkSync (pPixmap->drawable.pScreen);
+
     pPixmap->devPrivate.ptr = save_ptr;
     pPixmap->devKind = save_pitch;
 
-    pExaPixmap->dirty = FALSE;
+    /* The previously damaged bits are now no longer damaged but valid */
+    REGION_UNION(pPixmap->drawable.pScreen,
+		 &pExaPixmap->validReg, &pExaPixmap->validReg, pRegion);
+    DamageEmpty (pExaPixmap->pDamage);
 }
 
 /**
@@ -208,11 +249,12 @@ exaCopyDirtyToFb (PixmapPtr pPixmap)
  * Called when the memory manager decides it's time to kick the pixmap out of
  * framebuffer entirely.
  */
-static void
+void
 exaPixmapSave (ScreenPtr pScreen, ExaOffscreenArea *area)
 {
     PixmapPtr pPixmap = area->privData;
     ExaPixmapPriv(pPixmap);
+    RegionPtr pDamageReg = DamageRegion(pExaPixmap->pDamage);
 
     DBG_MIGRATE (("Save %p (%p) (%dx%d) (%c)\n", pPixmap,
 		  (void*)(ExaGetPixmapPriv(pPixmap)->area ?
@@ -231,10 +273,9 @@ exaPixmapSave (ScreenPtr pScreen, ExaOffscreenArea *area)
     pExaPixmap->fb_ptr = NULL;
     pExaPixmap->area = NULL;
 
-    /* Mark it dirty now, to say that there is important data in the
-     * system-memory copy.
-     */
-    pExaPixmap->dirty = TRUE;
+    /* Mark all valid bits as damaged, so they'll get copied to FB next time */
+    REGION_UNION(pPixmap->drawable.pScreen, pDamageReg, pDamageReg,
+		 &pExaPixmap->validReg);
 }
 
 /**
@@ -413,32 +454,57 @@ exaMigrateTowardSys (PixmapPtr pPixmap)
  * If the pixmap has both a framebuffer and system memory copy, this function
  * asserts that both of them are the same.
  */
-static void
+static Bool
 exaAssertNotDirty (PixmapPtr pPixmap)
 {
     ExaPixmapPriv (pPixmap);
     CARD8 *dst, *src;
-    int dst_pitch, src_pitch, data_row_bytes, y;
+    RegionPtr pValidReg = &pExaPixmap->validReg;
+    int dst_pitch, src_pitch, cpp, y, nbox = REGION_NUM_RECTS(pValidReg);
+    BoxPtr pBox = REGION_RECTS(pValidReg);
+    Bool ret = TRUE;
 
     if (pExaPixmap == NULL || pExaPixmap->fb_ptr == NULL)
-	return;
+	return ret;
 
     dst = pExaPixmap->sys_ptr;
     dst_pitch = pExaPixmap->sys_pitch;
     src = pExaPixmap->fb_ptr;
     src_pitch = pExaPixmap->fb_pitch;
-    data_row_bytes = pPixmap->drawable.width *
-		     pPixmap->drawable.bitsPerPixel / 8;
+    cpp = pPixmap->drawable.bitsPerPixel / 8;
 
     exaPrepareAccess(&pPixmap->drawable, EXA_PREPARE_SRC);
-    for (y = 0; y < pPixmap->drawable.height; y++) {
-	if (memcmp(dst, src, data_row_bytes) != 0) {
-	     abort();
-	}
-	dst += dst_pitch;
-	src += src_pitch;
+    while (nbox--) {
+	    int rowbytes;
+
+	    pBox->x1 = max(pBox->x1, 0);
+	    pBox->y1 = max(pBox->y1, 0);
+	    pBox->x2 = min(pBox->x2, pPixmap->drawable.width);
+	    pBox->y2 = min(pBox->y2, pPixmap->drawable.height);
+
+	    if (pBox->x1 >= pBox->x2 || pBox->y1 >= pBox->y2)
+		continue;
+
+	    rowbytes = (pBox->x2 - pBox->x1) * cpp;
+	    src += pBox->y1 * src_pitch + pBox->x1 * cpp;
+	    dst += pBox->y1 * dst_pitch + pBox->x1 * cpp;
+
+	    for (y = pBox->y2 - pBox->y1; y; y--) {
+		if (memcmp(dst + pBox->y1 * dst_pitch + pBox->x1 * cpp,
+			   src + pBox->y1 * src_pitch + pBox->x1 * cpp,
+			   (pBox->x2 - pBox->x1) * cpp) != 0) {
+		    ret = FALSE;
+		    break;
+		}
+		src += src_pitch;
+		dst += dst_pitch;
+	    }
+	    src -= pBox->y1 * src_pitch + pBox->x1 * cpp;
+	    dst -= pBox->y1 * dst_pitch + pBox->x1 * cpp;
     }
     exaFinishAccess(&pPixmap->drawable, EXA_PREPARE_SRC);
+
+    return ret;
 }
 
 /**
@@ -462,8 +528,9 @@ exaDoMigration (ExaMigrationPtr pixmaps, int npixmaps, Bool can_accel)
      */
     if (pExaScr->checkDirtyCorrectness) {
 	for (i = 0; i < npixmaps; i++) {
-	    if (!exaPixmapIsDirty (pixmaps[i].pPix))
-		exaAssertNotDirty (pixmaps[i].pPix);
+	    if (!exaPixmapIsDirty (pixmaps[i].pPix) &&
+		!exaAssertNotDirty (pixmaps[i].pPix))
+		ErrorF("%s: Pixmap %d dirty but not marked as such!\n", __func__, i);
 	}
     }
     /* If anything is pinned in system memory, we won't be able to
diff --git a/exa/exa_offscreen.c b/exa/exa_offscreen.c
index 9e0aa5d..7708dd7 100644
--- a/exa/exa_offscreen.c
+++ b/exa/exa_offscreen.c
@@ -81,15 +81,14 @@ ExaOffscreenKickOut (ScreenPtr pScreen, ExaOffscreenArea *area)
  * @param save callback for when the area is evicted from memory
  * @param privdata private data for the save callback.
  *
- * Allocates offscreen memory from the device associated with pScreen.  size and
- * align deteremine where and how large the allocated area is, and locked will
- * mark whether it should be held in card memory.  privdata may be any pointer
- * for the save callback when the area is removed.
+ * Allocates offscreen memory from the device associated with pScreen.  size
+ * and align deteremine where and how large the allocated area is, and locked
+ * will mark whether it should be held in card memory.  privdata may be any
+ * pointer for the save callback when the area is removed.
  *
- * Note that locked areas do get evicted on VT switch, because during that time
- * all offscreen memory becomes inaccessible.  This may change in the future,
- * but drivers should be aware of this and provide a callback to mark that their
- * locked allocation was evicted, and then restore it if necessary on EnterVT.
+ * Note that locked areas do get evicted on VT switch unless the driver
+ * requested version 2.1 or newer behavior.  In that case, the save callback is
+ * still called.
  */
 ExaOffscreenArea *
 exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
@@ -256,6 +255,9 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
     return area;
 }
 
+/**
+ * Ejects all offscreen areas, and uninitializes the offscreen memory manager.
+ */
 void
 ExaOffscreenSwapOut (ScreenPtr pScreen)
 {
@@ -283,12 +285,56 @@ ExaOffscreenSwapOut (ScreenPtr pScreen)
     ExaOffscreenFini (pScreen);
 }
 
+/** Ejects all pixmaps managed by EXA. */
+static void
+ExaOffscreenEjectPixmaps (ScreenPtr pScreen)
+{
+    ExaScreenPriv (pScreen);
+
+    ExaOffscreenValidate (pScreen);
+    /* loop until a single free area spans the space */
+    for (;;)
+    {
+	ExaOffscreenArea *area;
+
+	for (area = pExaScr->info->offScreenAreas; area != NULL;
+	     area = area->next)
+	{
+	    if (area->state == ExaOffscreenRemovable &&
+		area->save == exaPixmapSave)
+	    {
+		(void) ExaOffscreenKickOut (pScreen, area);
+		ExaOffscreenValidate (pScreen);
+		break;
+	    }
+	}
+	if (area == NULL)
+	    break;
+    }
+    ExaOffscreenValidate (pScreen);
+}
+
 void
 ExaOffscreenSwapIn (ScreenPtr pScreen)
 {
     exaOffscreenInit (pScreen);
 }
 
+/**
+ * Prepares EXA for disabling of FB access, or restoring it.
+ *
+ * In version 2.1, the disabling results in pixmaps being ejected, while other
+ * allocations remain.  With this plus the prevention of migration while
+ * swappedOut is set, EXA by itself should not cause any access of the
+ * framebuffer to occur while swapped out.  Any remaining issues are the
+ * responsibility of the driver.
+ *
+ * Prior to version 2.1, all allocations, including locked ones, are ejected
+ * when access is disabled, and the allocator is torn down while swappedOut
+ * is set.  This is more drastic, and caused implementation difficulties for
+ * many drivers that could otherwise handle the lack of FB access while
+ * swapped out.
+ */
 void
 exaEnableDisableFBAccess (int index, Bool enable)
 {
@@ -296,10 +342,14 @@ exaEnableDisableFBAccess (int index, Bool enable)
     ExaScreenPriv (pScreen);
 
     if (!enable) {
-	ExaOffscreenSwapOut (pScreen);
+	if (pExaScr->info->exa_minor < 1)
+	    ExaOffscreenSwapOut (pScreen);
+	else
+	    ExaOffscreenEjectPixmaps (pScreen);
 	pExaScr->swappedOut = TRUE;
     } else {
-	ExaOffscreenSwapIn (pScreen);
+	if (pExaScr->info->exa_minor < 1)
+	    ExaOffscreenSwapIn (pScreen);
 	pExaScr->swappedOut = FALSE;
     }
 }
@@ -390,6 +440,7 @@ ExaOffscreenMarkUsed (PixmapPtr pPixmap)
 	    if (area->state == ExaOffscreenRemovable)
 		area->score = (area->score * 7) / 8;
 	}
+	iter = 0;
     }
 }
 
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index 03ee0ed..984cb66 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -51,6 +51,7 @@
 #ifdef RENDER
 #include "fbpict.h"
 #endif
+#include "damage.h"
 
 #define DEBUG_TRACE_FALL	0
 #define DEBUG_MIGRATE		0
@@ -160,16 +161,16 @@ typedef struct {
     unsigned int    fb_size;	/**< size of pixmap in framebuffer memory */
 
     /**
-     * If area is NULL, then dirty == TRUE means that the pixmap has been
-     * modified, so the contents are defined.  Used to avoid uploads of
-     * undefined data.
-     *
-     * If area is non-NULL, then dirty == TRUE means that the pixmap data at
-     * pPixmap->devPrivate.ptr (either fb_ptr or sys_ptr) has been changed
-     * compared to the copy in the other location.  This is used to avoid
-     * uploads/downloads of unmodified data.
+     * The damage record contains the areas of the pixmap's current location
+     * (framebuffer or system) that have been damaged compared to the other
+     * location.
      */
-    Bool	    dirty;
+    DamagePtr	    pDamage;
+    /**
+     * The valid region marks the valid bits of a drawable (at least, as it's
+     * derived from damage, which may be overreported).
+     */
+    RegionRec	    validReg;
 } ExaPixmapPrivRec, *ExaPixmapPrivPtr;
  
 typedef struct _ExaMigrationRec {
@@ -315,7 +316,7 @@ ExaCheckComposite (CARD8      op,
 		  CARD16     height);
 #endif
 
-/* exaoffscreen.c */
+/* exa_offscreen.c */
 void
 ExaOffscreenMarkUsed (PixmapPtr pPixmap);
 
@@ -339,7 +340,10 @@ void
 exaFinishAccess(DrawablePtr pDrawable, int index);
 
 void
-exaDrawableDirty(DrawablePtr pDrawable);
+exaPixmapDirty(PixmapPtr pPix, int x1, int y1, int x2, int y2);
+
+void
+exaDrawableDirty(DrawablePtr pDrawable, int x1, int y1, int x2, int y2);
 
 Bool
 exaDrawableIsOffscreen (DrawablePtr pDrawable);
@@ -409,9 +413,6 @@ void
 exaDoMigration (ExaMigrationPtr pixmaps, int npixmaps, Bool can_accel);
 
 void
-exaMoveInPixmap (PixmapPtr pPixmap);
-
-void
-exaMoveOutPixmap (PixmapPtr pPixmap);
+exaPixmapSave (ScreenPtr pScreen, ExaOffscreenArea *area);
 
 #endif /* EXAPRIV_H */
diff --git a/exa/exa_render.c b/exa/exa_render.c
index 9affb9f..75108a7 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -302,12 +302,12 @@ exaTryDriverSolidFill(PicturePtr	pSrc,
 	(*pExaScr->info->Solid) (pDstPix,
 				 pbox->x1 + dst_off_x, pbox->y1 + dst_off_y,
 				 pbox->x2 + dst_off_x, pbox->y2 + dst_off_y);
+	exaPixmapDirty (pDstPix, pbox->x1 + dst_off_x, pbox->y1 + dst_off_y,
+			pbox->x2 + dst_off_x, pbox->y2 + dst_off_y);
 	pbox++;
     }
-
     (*pExaScr->info->DoneSolid) (pDstPix);
     exaMarkSync(pDst->pDrawable->pScreen);
-    exaDrawableDirty (pDst->pDrawable);
 
     REGION_UNINIT(pDst->pDrawable->pScreen, &region);
     return 1;
@@ -336,16 +336,21 @@ exaTryDriverComposite(CARD8		op,
     struct _Pixmap scratch;
     ExaMigrationRec pixmaps[3];
 
+    pSrcPix = exaGetDrawablePixmap(pSrc->pDrawable);
+    pDstPix = exaGetDrawablePixmap(pDst->pDrawable);
+    if (pMask)
+	pMaskPix = exaGetDrawablePixmap(pMask->pDrawable);
+
     /* Bail if we might exceed coord limits by rendering from/to these.  We
      * should really be making some scratch pixmaps with offsets and coords
      * adjusted to deal with this, but it hasn't been done yet.
      */
-    if (pSrc->pDrawable->width > pExaScr->info->maxX ||
-	pSrc->pDrawable->height > pExaScr->info->maxY ||
-	pDst->pDrawable->width > pExaScr->info->maxX ||
-	pDst->pDrawable->height > pExaScr->info->maxY || 
-	(pMask && (pMask->pDrawable->width > pExaScr->info->maxX ||
-		   pMask->pDrawable->height > pExaScr->info->maxY)))
+    if (pSrcPix->drawable.width > pExaScr->info->maxX ||
+	pSrcPix->drawable.height > pExaScr->info->maxY ||
+	pDstPix->drawable.width > pExaScr->info->maxX ||
+	pDstPix->drawable.height > pExaScr->info->maxY || 
+	(pMask && (pMaskPix->drawable.width > pExaScr->info->maxX ||
+		   pMaskPix->drawable.height > pExaScr->info->maxY)))
     {
 	return -1;
     }
@@ -441,12 +446,12 @@ exaTryDriverComposite(CARD8		op,
 				     pbox->y1 + dst_off_y,
 				     pbox->x2 - pbox->x1,
 				     pbox->y2 - pbox->y1);
+	exaPixmapDirty (pDstPix, pbox->x1 + dst_off_x, pbox->y1 + dst_off_y,
+			pbox->x2 + dst_off_x, pbox->y2 + dst_off_y);
 	pbox++;
     }
-
     (*pExaScr->info->DoneComposite) (pDstPix);
     exaMarkSync(pDst->pDrawable->pScreen);
-    exaDrawableDirty (pDst->pDrawable);
 
     REGION_UNINIT(pDst->pDrawable->pScreen, &region);
     return 1;
@@ -705,16 +710,19 @@ void
 exaRasterizeTrapezoid (PicturePtr pPicture, xTrapezoid  *trap,
 		       int x_off, int y_off)
 {
+    DrawablePtr pDraw = pPicture->pDrawable;
     ExaMigrationRec pixmaps[1];
 
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = TRUE;
-    pixmaps[0].pPix = exaGetDrawablePixmap (pPicture->pDrawable);
+    pixmaps[0].pPix = exaGetDrawablePixmap (pDraw);
     exaDoMigration(pixmaps, 1, FALSE);
 
-    exaPrepareAccess(pPicture->pDrawable, EXA_PREPARE_DEST);
+    exaPrepareAccess(pDraw, EXA_PREPARE_DEST);
     fbRasterizeTrapezoid(pPicture, trap, x_off, y_off);
-    exaFinishAccess(pPicture->pDrawable, EXA_PREPARE_DEST);
+    exaDrawableDirty(pDraw, pDraw->x, pDraw->y,
+		     pDraw->x + pDraw->width, pDraw->y + pDraw->height);
+    exaFinishAccess(pDraw, EXA_PREPARE_DEST);
 }
 
 /**
@@ -725,16 +733,19 @@ void
 exaAddTriangles (PicturePtr pPicture, INT16 x_off, INT16 y_off, int ntri,
 		 xTriangle *tris)
 {
+    DrawablePtr pDraw = pPicture->pDrawable;
     ExaMigrationRec pixmaps[1];
 
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = TRUE;
-    pixmaps[0].pPix = exaGetDrawablePixmap (pPicture->pDrawable);
+    pixmaps[0].pPix = exaGetDrawablePixmap (pDraw);
     exaDoMigration(pixmaps, 1, FALSE);
 
-    exaPrepareAccess(pPicture->pDrawable, EXA_PREPARE_DEST);
+    exaPrepareAccess(pDraw, EXA_PREPARE_DEST);
     fbAddTriangles(pPicture, x_off, y_off, ntri, tris);
-    exaFinishAccess(pPicture->pDrawable, EXA_PREPARE_DEST);
+    exaDrawableDirty(pDraw, pDraw->x, pDraw->y,
+		     pDraw->x + pDraw->width, pDraw->y + pDraw->height);
+    exaFinishAccess(pDraw, EXA_PREPARE_DEST);
 }
 
 /**
@@ -1023,10 +1034,11 @@ exaGlyphs (CARD8	op,
 
 		exaCopyArea (&pScratchPixmap->drawable, &pPixmap->drawable, pGC,
 			     0, 0, glyph->info.width, glyph->info.height, 0, 0);
-	    } else {
-		exaDrawableDirty (&pPixmap->drawable);
 	    }
 
+	    exaPixmapDirty (pPixmap, 0, 0,
+			    glyph->info.width, glyph->info.height);
+
 	    if (maskFormat)
 	    {
 		exaComposite (PictOpAdd, pPicture, NULL, pMask, 0, 0, 0, 0,
diff --git a/exa/exa_unaccel.c b/exa/exa_unaccel.c
index f9df6ad..7713a08 100644
--- a/exa/exa_unaccel.c
+++ b/exa/exa_unaccel.c
@@ -200,11 +200,33 @@ ExaCheckPolyFillRect (DrawablePtr pDrawable, GCPtr pGC,
 		     int nrect, xRectangle *prect)
 {
     EXA_FALLBACK(("to %p (%c)\n", pDrawable, exaDrawableLocation(pDrawable)));
-    exaPrepareAccess (pDrawable, EXA_PREPARE_DEST);
-    exaPrepareAccessGC (pGC);
-    fbPolyFillRect (pDrawable, pGC, nrect, prect);
-    exaFinishAccessGC (pGC);
-    exaFinishAccess (pDrawable, EXA_PREPARE_DEST);
+
+    if (nrect) {
+	int x1 = max(prect->x, 0), y1 = max(prect->y, 0);
+	int x2 = min(prect->x + prect->width, pDrawable->width);
+	int y2 = min(prect->y + prect->height, pDrawable->height);
+
+	exaPrepareAccess (pDrawable, EXA_PREPARE_DEST);
+	exaPrepareAccessGC (pGC);
+	fbPolyFillRect (pDrawable, pGC, nrect, prect);
+	exaFinishAccessGC (pGC);
+	exaFinishAccess (pDrawable, EXA_PREPARE_DEST);
+
+	/* Only track bounding box of damage, as this path can degenerate to
+	 * zillions of damage boxes
+	 */
+	while (--nrect)
+	{
+	    prect++;
+	    x1 = min(x1, prect->x);
+	    x2 = max(x2, prect->x + prect->width);
+	    y1 = min(y1, prect->y);
+	    y2 = max(y2, prect->y + prect->height);
+	}
+
+	exaDrawableDirty (pDrawable, pDrawable->x + x1, pDrawable->y + y1,
+			  pDrawable->x + x2, pDrawable->y + y2);
+    }
 }
 
 void
diff --git a/hw/xfree86/exa/Makefile.am b/hw/xfree86/exa/Makefile.am
index 31682c4..9eb2e17 100644
--- a/hw/xfree86/exa/Makefile.am
+++ b/hw/xfree86/exa/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = \
 	-I$(srcdir)/../../../exa \
 	-I$(srcdir)/../../../miext/cw
 
-AM_CFLAGS = $(XORG_CFLAGS)
+AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
 libexa_la_SOURCES = \
 	examodule.c
diff --git a/hw/xfree86/exa/exa.man.pre b/hw/xfree86/exa/exa.man.pre
index ea41b90..b0eecd5 100644
--- a/hw/xfree86/exa/exa.man.pre
+++ b/hw/xfree86/exa/exa.man.pre
@@ -35,6 +35,6 @@ Default: No.
 Chooses an alternate pixmap migration heuristic, for debugging purposes.  The
 default is intended to be the best performing one for general use, though others
 may help with specific use cases.  Available options include \*qalways\*q,
-\*qgreedy\*q, and \*qsmart\*q.  Default: smart.
+\*qgreedy\*q, and \*qsmart\*q.  Default: always.
 .SH AUTHORS
 Authors include: Keith Packard, Eric Anholt, Zack Rusin, and Michel Dänzer
commit 9fbb845e8b56847ee6ff7cbb7d941f229a39c407
Author: Eric Anholt <eric at anholt.net>
Date:   Mon Jun 12 20:12:31 2006 +0200

    Provide option to report damage after operation is complete.
    (cherry picked from commit 6060b612de6b41f872d034c6130770c1d189d0a3)

diff --git a/miext/damage/damage.c b/miext/damage/damage.c
index 2e80011..cd66b54 100755
--- a/miext/damage/damage.c
+++ b/miext/damage/damage.c
@@ -113,6 +113,52 @@ getDrawableDamageRef (DrawablePtr pDrawable)
     DamagePtr	*pPrev = (DamagePtr *) \
 	    &(pWindow->devPrivates[damageWinPrivateIndex].ptr)
 
+static void
+DamageReportDamage (DamagePtr pDamage, RegionPtr pDamageRegion)
+{
+    BoxRec tmpBox;
+    RegionRec tmpRegion;
+    Bool was_empty;
+
+    switch (pDamage->damageLevel) {
+    case DamageReportRawRegion:
+	(*pDamage->damageReport) (pDamage, pDamageRegion, pDamage->closure);
+	break;
+    case DamageReportDeltaRegion:
+	REGION_NULL (pScreen, &tmpRegion);
+	REGION_SUBTRACT (pScreen, &tmpRegion, pDamageRegion, &pDamage->damage);
+	if (REGION_NOTEMPTY (pScreen, &tmpRegion)) {
+	    REGION_UNION(pScreen, &pDamage->damage, &pDamage->damage,
+			 pDamageRegion);
+	    (*pDamage->damageReport) (pDamage, &tmpRegion, pDamage->closure);
+	}
+	REGION_UNINIT(pScreen, &tmpRegion);
+	break;
+    case DamageReportBoundingBox:
+	tmpBox = *REGION_EXTENTS (pScreen, &pDamage->damage);
+	REGION_UNION(pScreen, &pDamage->damage, &pDamage->damage,
+		     pDamageRegion);
+	if (!BOX_SAME (&tmpBox, REGION_EXTENTS (pScreen, &pDamage->damage))) {
+	    (*pDamage->damageReport) (pDamage, &pDamage->damage,
+				      pDamage->closure);
+	}
+	break;
+    case DamageReportNonEmpty:
+	was_empty = !REGION_NOTEMPTY(pScreen, &pDamage->damage);
+	REGION_UNION(pScreen, &pDamage->damage, &pDamage->damage,
+		     pDamageRegion);
+	if (was_empty && REGION_NOTEMPTY(pScreen, &pDamage->damage)) {
+	    (*pDamage->damageReport) (pDamage, &pDamage->damage,
+				      pDamage->closure);
+	}
+	break;
+    case DamageReportNone:
+	REGION_UNION(pScreen, &pDamage->damage, &pDamage->damage,
+		     pDamageRegion);
+	break;
+    }
+}
+
 #if DAMAGE_DEBUG_ENABLE
 static void
 _damageDamageRegion (DrawablePtr pDrawable, RegionPtr pRegion, Bool clip, int subWindowMode, const char *where)
@@ -130,9 +176,6 @@ damageDamageRegion (DrawablePtr pDrawable, RegionPtr pRegion, Bool clip,
     RegionRec	    clippedRec;
     RegionPtr	    pDamageRegion;
     RegionRec	    pixClip;
-    Bool	    was_empty;
-    RegionRec	    tmpRegion;
-    BoxRec	    tmpBox;
     int		    draw_x, draw_y;
 #ifdef COMPOSITE
     int		    screen_x = 0, screen_y = 0;
@@ -256,41 +299,18 @@ damageDamageRegion (DrawablePtr pDrawable, RegionPtr pRegion, Bool clip,
 	 */
 	if (draw_x || draw_y)
 	    REGION_TRANSLATE (pScreen, pDamageRegion, -draw_x, -draw_y);
-	
-	switch (pDamage->damageLevel) {
-	case DamageReportRawRegion:
-	    (*pDamage->damageReport) (pDamage, pDamageRegion, pDamage->closure);
-	    break;
-	case DamageReportDeltaRegion:
-	    REGION_NULL (pScreen, &tmpRegion);
-	    REGION_SUBTRACT (pScreen, &tmpRegion, pDamageRegion, &pDamage->damage);
-	    if (REGION_NOTEMPTY (pScreen, &tmpRegion))
-	    {
-		REGION_UNION(pScreen, &pDamage->damage,
-			     &pDamage->damage, pDamageRegion);
-		(*pDamage->damageReport) (pDamage, &tmpRegion, pDamage->closure);
-	    }
-	    REGION_UNINIT(pScreen, &tmpRegion);
-	    break;
-	case DamageReportBoundingBox:
-	    tmpBox = *REGION_EXTENTS (pScreen, &pDamage->damage);
-	    REGION_UNION(pScreen, &pDamage->damage,
-			 &pDamage->damage, pDamageRegion);
-	    if (!BOX_SAME (&tmpBox, REGION_EXTENTS (pScreen, &pDamage->damage)))
-		(*pDamage->damageReport) (pDamage, &pDamage->damage, pDamage->closure);
-	    break;
-	case DamageReportNonEmpty:
-	    was_empty = !REGION_NOTEMPTY(pScreen, &pDamage->damage);
-	    REGION_UNION(pScreen, &pDamage->damage, &pDamage->damage,
-			 pDamageRegion);
-	    if (was_empty && REGION_NOTEMPTY(pScreen, &pDamage->damage))
-		(*pDamage->damageReport) (pDamage, &pDamage->damage, pDamage->closure);
-	    break;
-	case DamageReportNone:
-	    REGION_UNION(pScreen, &pDamage->damage, &pDamage->damage,
-			 pDamageRegion);
-	    break;
+
+	/* If the damage rec has been flagged to report damage after the op has
+	 * completed, then union it into the delayed damage region, which will
+	 * be used for reporting after calling down, and skip the reporting 
+	 */
+	if (!pDamage->reportAfter) {
+	    DamageReportDamage (pDamage, pDamageRegion);
+	} else {
+	    REGION_UNION(pScreen, &pDamage->pendingDamage,
+			 &pDamage->pendingDamage, pDamageRegion);
 	}
+
 	/*
 	 * translate original region back
 	 */
@@ -305,6 +325,21 @@ damageDamageRegion (DrawablePtr pDrawable, RegionPtr pRegion, Bool clip,
     REGION_UNINIT (pScreen, &clippedRec);
 }
 
+static void
+damageReportPostOp (DrawablePtr pDrawable)
+{
+    drawableDamage(pDrawable);
+
+    for (; pDamage != NULL; pDamage = pDamage->pNext)
+    {
+	if (pDamage->reportAfter) {
+	    DamageReportDamage (pDamage, &pDamage->pendingDamage);
+	    REGION_EMPTY (pScreen, &pDamage->pendingDamage);
+	}
+    }
+    
+}
+
 #if DAMAGE_DEBUG_ENABLE
 #define damageDamageBox(d,b,m) _damageDamageBox(d,b,m,__FUNCTION__)
 static void
@@ -550,6 +585,7 @@ damageComposite (CARD8      op,
 		       yDst,
 		       width,
 		       height);
+    damageReportPostOp (pDst->pDrawable);
     wrap (pScrPriv, ps, Composite, damageComposite);
 }
 
@@ -616,6 +652,7 @@ damageGlyphs (CARD8		op,
     }
     unwrap (pScrPriv, ps, Glyphs);
     (*ps->Glyphs) (op, pSrc, pDst, maskFormat, xSrc, ySrc, nlist, list, glyphs);
+    damageReportPostOp (pDst->pDrawable);
     wrap (pScrPriv, ps, Glyphs, damageGlyphs);
 }
 #endif
@@ -668,6 +705,7 @@ damageFillSpans(DrawablePtr pDrawable,
     
     (*pGC->ops->FillSpans)(pDrawable, pGC, npt, ppt, pwidth, fSorted);
 
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -715,6 +753,7 @@ damageSetSpans(DrawablePtr  pDrawable,
 	   damageDamageBox (pDrawable, &box, pGC->subWindowMode);
     }
     (*pGC->ops->SetSpans)(pDrawable, pGC, pcharsrc, ppt, pwidth, npt, fSorted);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -746,6 +785,7 @@ damagePutImage(DrawablePtr  pDrawable,
     }
     (*pGC->ops->PutImage)(pDrawable, pGC, depth, x, y, w, h,
 		leftPad, format, pImage);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -789,6 +829,7 @@ damageCopyArea(DrawablePtr   pSrc,
 
     ret = (*pGC->ops->CopyArea)(pSrc, pDst,
             pGC, srcx, srcy, width, height, dstx, dsty);
+    damageReportPostOp (pDst);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDst);
     return ret;
 }
@@ -834,6 +875,7 @@ damageCopyPlane(DrawablePtr	pSrc,
 
     ret = (*pGC->ops->CopyPlane)(pSrc, pDst,
 	       pGC, srcx, srcy, width, height, dstx, dsty, bitPlane);
+    damageReportPostOp (pDst);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDst);
     return ret;
 }
@@ -875,6 +917,7 @@ damagePolyPoint(DrawablePtr pDrawable,
 	   damageDamageBox (pDrawable, &box, pGC->subWindowMode);
     }
     (*pGC->ops->PolyPoint)(pDrawable, pGC, mode, npt, ppt);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -948,6 +991,7 @@ damagePolylines(DrawablePtr pDrawable,
 	   damageDamageBox (pDrawable, &box, pGC->subWindowMode);
     }
     (*pGC->ops->Polylines)(pDrawable, pGC, mode, npt, ppt);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1026,6 +1070,7 @@ damagePolySegment(DrawablePtr	pDrawable,
 	   damageDamageBox (pDrawable, &box, pGC->subWindowMode);
     }
     (*pGC->ops->PolySegment)(pDrawable, pGC, nSeg, pSeg);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1087,6 +1132,7 @@ damagePolyRectangle(DrawablePtr  pDrawable,
 	}
     }
     (*pGC->ops->PolyRectangle)(pDrawable, pGC, nRects, pRects);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1139,6 +1185,7 @@ damagePolyArc(DrawablePtr   pDrawable,
 	   damageDamageBox (pDrawable, &box, pGC->subWindowMode);
     }
     (*pGC->ops->PolyArc)(pDrawable, pGC, nArcs, pArcs);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1197,6 +1244,7 @@ damageFillPolygon(DrawablePtr	pDrawable,
     }
     
     (*pGC->ops->FillPolygon)(pDrawable, pGC, shape, mode, npt, ppt);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1235,6 +1283,7 @@ damagePolyFillRect(DrawablePtr	pDrawable,
 	    damageDamageBox (pDrawable, &box, pGC->subWindowMode);
     }
     (*pGC->ops->PolyFillRect)(pDrawable, pGC, nRects, pRects);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1276,6 +1325,7 @@ damagePolyFillArc(DrawablePtr	pDrawable,
 	   damageDamageBox (pDrawable, &box, pGC->subWindowMode);
     }
     (*pGC->ops->PolyFillArc)(pDrawable, pGC, nArcs, pArcs);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1386,6 +1436,7 @@ damagePolyText8(DrawablePtr pDrawable,
 		    Linear8Bit, TT_POLY8);
     else
 	x = (*pGC->ops->PolyText8)(pDrawable, pGC, x, y, count, chars);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
     return x;
 }
@@ -1406,6 +1457,7 @@ damagePolyText16(DrawablePtr	pDrawable,
 		    TT_POLY16);
     else
 	x = (*pGC->ops->PolyText16)(pDrawable, pGC, x, y, count, chars);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
     return x;
 }
@@ -1425,6 +1477,7 @@ damageImageText8(DrawablePtr	pDrawable,
 		    Linear8Bit, TT_IMAGE8);
     else
 	(*pGC->ops->ImageText8)(pDrawable, pGC, x, y, count, chars);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1444,6 +1497,7 @@ damageImageText16(DrawablePtr	pDrawable,
 		    TT_IMAGE16);
     else
 	(*pGC->ops->ImageText16)(pDrawable, pGC, x, y, count, chars);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1462,6 +1516,7 @@ damageImageGlyphBlt(DrawablePtr	    pDrawable,
 		       nglyph, ppci, TRUE, pGC->subWindowMode);
     (*pGC->ops->ImageGlyphBlt)(pDrawable, pGC, x, y, nglyph,
 					ppci, pglyphBase);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1479,6 +1534,7 @@ damagePolyGlyphBlt(DrawablePtr	pDrawable,
 		       nglyph, ppci, FALSE, pGC->subWindowMode);
     (*pGC->ops->PolyGlyphBlt)(pDrawable, pGC, x, y, nglyph,
 				ppci, pglyphBase);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1512,6 +1568,7 @@ damagePushPixels(GCPtr		pGC,
 	   damageDamageBox (pDrawable, &box, pGC->subWindowMode);
     }
     (*pGC->ops->PushPixels)(pGC, pBitMap, pDrawable, dx, dy, xOrg, yOrg);
+    damageReportPostOp (pDrawable);
     DAMAGE_GC_OP_EPILOGUE(pGC, pDrawable);
 }
 
@@ -1591,10 +1648,12 @@ damagePaintWindow(WindowPtr pWindow,
     if(what == PW_BACKGROUND) {
 	unwrap (pScrPriv, pScreen, PaintWindowBackground);
 	(*pScreen->PaintWindowBackground) (pWindow, prgn, what);
+	damageReportPostOp (&pWindow->drawable);
 	wrap (pScrPriv, pScreen, PaintWindowBackground, damagePaintWindow);
     } else {
 	unwrap (pScrPriv, pScreen, PaintWindowBorder);
 	(*pScreen->PaintWindowBorder) (pWindow, prgn, what);
+	damageReportPostOp (&pWindow->drawable);
 	wrap (pScrPriv, pScreen, PaintWindowBorder, damagePaintWindow);
     }
 }
@@ -1623,6 +1682,7 @@ damageCopyWindow(WindowPtr	pWindow,
     }
     unwrap (pScrPriv, pScreen, CopyWindow);
     (*pScreen->CopyWindow) (pWindow, ptOldOrg, prgnSrc);
+    damageReportPostOp (&pWindow->drawable);
     wrap (pScrPriv, pScreen, CopyWindow, damageCopyWindow);
 }
 
@@ -1654,6 +1714,7 @@ damageRestoreAreas (PixmapPtr	pPixmap,
     unwrap (pScrPriv, pScreen, BackingStoreFuncs.RestoreAreas);
     (*pScreen->BackingStoreFuncs.RestoreAreas) (pPixmap, prgn,
 						xorg, yorg, pWindow);
+    damageReportPostOp (&pWindow->drawable);
     wrap (pScrPriv, pScreen, BackingStoreFuncs.RestoreAreas,
 			     damageRestoreAreas);
 }
@@ -1820,12 +1881,14 @@ DamageCreate (DamageReportFunc  damageReport,
     pDamage->pNext = 0;
     pDamage->pNextWin = 0;
     REGION_NULL(pScreen, &pDamage->damage);
+    REGION_NULL(pScreen, &pDamage->pendingDamage);
     
     pDamage->damageLevel = damageLevel;
     pDamage->isInternal = isInternal;
     pDamage->closure = closure;
     pDamage->isWindow = FALSE;
     pDamage->pDrawable = 0;
+    pDamage->reportAfter = FALSE;
 
     pDamage->damageReport = damageReport;
     pDamage->damageDestroy = damageDestroy;
@@ -1909,6 +1972,7 @@ DamageDestroy (DamagePtr    pDamage)
     if (pDamage->damageDestroy)
 	(*pDamage->damageDestroy) (pDamage, pDamage->closure);
     REGION_UNINIT (pDamage->pDrawable->pScreen, &pDamage->damage);
+    REGION_UNINIT (pDamage->pDrawable->pScreen, &pDamage->pendingDamage);
     xfree (pDamage);
 }
 
@@ -1962,4 +2026,16 @@ DamageDamageRegion (DrawablePtr	pDrawable,
 		    RegionPtr	pRegion)
 {
     damageDamageRegion (pDrawable, pRegion, FALSE, -1);
+
+    /* Go back and report this damage for DamagePtrs with reportAfter set, since
+     * this call isn't part of an in-progress drawing op in the call chain and
+     * the DDX probably just wants to know about it right away.
+     */
+    damageReportPostOp (pDrawable);
+}
+
+void
+DamageSetReportAfterOp (DamagePtr pDamage, Bool reportAfter)
+{
+    pDamage->reportAfter = reportAfter;
 }
diff --git a/miext/damage/damage.h b/miext/damage/damage.h
index c760f6b..36a0654 100755
--- a/miext/damage/damage.h
+++ b/miext/damage/damage.h
@@ -81,4 +81,7 @@ void
 DamageDamageRegion (DrawablePtr	    pDrawable,
 		    const RegionPtr pRegion);
 
+void
+DamageSetReportAfterOp (DamagePtr pDamage, Bool reportAfter);
+
 #endif /* _DAMAGE_H_ */
diff --git a/miext/damage/damagestr.h b/miext/damage/damagestr.h
index 0fe9e0a..93e213f 100755
--- a/miext/damage/damagestr.h
+++ b/miext/damage/damagestr.h
@@ -48,6 +48,9 @@ typedef struct _damage {
     
     DamageReportFunc	damageReport;
     DamageDestroyFunc	damageDestroy;
+
+    Bool		reportAfter;
+    RegionRec		pendingDamage;
 } DamageRec;
 
 typedef struct _damageScrPriv {
commit fe13ebbe6960b5a23ed0dc0dd991fd5177dee483
Author: Eric Anholt <eric at anholt.net>
Date:   Fri Feb 2 12:14:40 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.
    (cherry picked from commit 4f2f3233c808fd86bf9f6c09937feda9e0b367fd)

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 1e04290..2ae9040 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -868,7 +868,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, SecurityWriteAccess);
     if (!crtc)
 	return RRErrorBase + BadRRCrtc;
commit ec1c2fc092ac18c8c0f4ef84d74869398844719d
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Feb 2 12:57:38 2007 +0200

    dmx: drop leftover __GLXdrawablePrivateRec struct.
    (cherry picked from commit cf5b29d75dad7c74543f49f010c817623a3df747)

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"
commit 8798c8cfa888521cc47173bf6db00b5724da4a54
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Tue Jan 30 19:05:20 2007 -0800

    Allow DDX to not supply a property set notification function.
    
    Check rrOutputSetProperty and only call if it isn't NULL.

diff --git a/randr/rrproperty.c b/randr/rrproperty.c
index ed01c88..03a1b5c 100644
--- a/randr/rrproperty.c
+++ b/randr/rrproperty.c
@@ -215,7 +215,7 @@ RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
 	output->properties = prop;
     }
 
-    if (!prop->is_pending) {
+    if (!prop->is_pending && pScrPriv->rrOutputSetProperty) {
 	/* What should we do in case of failure? */
 	pScrPriv->rrOutputSetProperty(output->pScreen, output,
 				      prop->propertyName, prop_value);
commit 895250181b21a76cab815b6ee2862d8a0c3a2fbf
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Tue Jan 30 18:45:44 2007 -0800

    Use old resource API in backported patch.
    
    1.2 branch doesn't have the resource lookup changes, so we need to use the
    old APIs.

diff --git a/damageext/damageext.c b/damageext/damageext.c
index 36d31e8..d13c67b 100755
--- a/damageext/damageext.c
+++ b/damageext/damageext.c
@@ -281,14 +281,10 @@ ProcDamageAdd (ClientPtr client)
     REQUEST(xDamageAddReq);
     DrawablePtr	    pDrawable;
     RegionPtr	    pRegion;
-    int		    rc;
 
     REQUEST_SIZE_MATCH(xDamageAddReq);
-    VERIFY_REGION(pRegion, stuff->region, client, DixWriteAccess);
-    rc = dixLookupDrawable(&pDrawable, stuff->drawable, client, 0,
-			   DixReadAccess);
-    if (rc != Success)
-	return rc;
+    VERIFY_REGION(pRegion, stuff->region, client, SecurityWriteAccess);
+    SECURITY_VERIFY_DRAWABLE (pDrawable, stuff->drawable, client, SecurityReadAccess);
 
     /* The region is relative to the drawable origin, so translate it out to
      * screen coordinates like damage expects.
commit f993e142d2b8c7ce27370fb2c18d2eafb6ff40ca
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Mon Jan 29 23:04:17 2007 -0800

    Make Xinearama screen information reflect CRTC rotation.
    
    (cherry picked from commit b6b855932109b4bc3454f07bef8cb079d79ca369)

diff --git a/randr/randrstr.h b/randr/randrstr.h
index 7a34b39..f86f9b5 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -548,6 +548,9 @@ Bool
 RRCrtcGammaSetSize (RRCrtcPtr	crtc,
 		    int		size);
 
+void
+RRCrtcGetScanoutSize(RRCrtcPtr crtc, int *width, int *height);
+
 /*
  * Destroy a Crtc at shutdown
  */
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 63898f8..1e04290 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -406,6 +406,32 @@ RRCrtcGammaNotify (RRCrtcPtr	crtc)
     return TRUE;    /* not much going on here */
 }
 
+/**
+ * Returns the width/height that the crtc scans out from the framebuffer
+ */
+void
+RRCrtcGetScanoutSize(RRCrtcPtr crtc, int *width, int *height)
+{
+    if (crtc->mode == NULL) {
+	*width = 0;
+	*height = 0;
+	return;
+    }
+
+    switch (crtc->rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_180:
+	*width = crtc->mode->mode.width;
+	*height = crtc->mode->mode.height;
+	break;
+    case RR_Rotate_90:
+    case RR_Rotate_270:
+	*width = crtc->mode->mode.height;
+	*height = crtc->mode->mode.width;
+	break;
+    }
+}
+
 /*
  * Set the size of the gamma table at server startup time
  */
diff --git a/randr/rrpointer.c b/randr/rrpointer.c
index 2a5ae7d..802dcb2 100644
--- a/randr/rrpointer.c
+++ b/randr/rrpointer.c
@@ -22,32 +22,6 @@
 
 #include "randrstr.h"
 
-/**
- * Returns the width/height that the crtc scans out from the framebuffer
- */
-static void
-RRCrtcGetScanoutSize(RRCrtcPtr crtc, int *width, int *height)
-{
-    if (crtc->mode == NULL) {
-	*width = 0;
-	*height = 0;
-	return;
-    }
-
-    switch (crtc->rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_180:
-	*width = crtc->mode->mode.width;
-	*height = crtc->mode->mode.height;
-	break;
-    case RR_Rotate_90:
-    case RR_Rotate_270:
-	*width = crtc->mode->mode.height;
-	*height = crtc->mode->mode.width;
-	break;
-    }
-}
-
 /*
  * When the pointer moves, check to see if the specified position is outside
  * any of theavailable CRTCs and move it to a 'sensible' place if so, where
diff --git a/randr/rrxinerama.c b/randr/rrxinerama.c
index 771ed09..63a34b5 100644
--- a/randr/rrxinerama.c
+++ b/randr/rrxinerama.c
@@ -287,10 +287,12 @@ ProcRRXineramaQueryScreens(ClientPtr client)
 	    RRCrtcPtr	crtc = pScrPriv->crtcs[i];
 	    if (RRXineramaCrtcActive (crtc))
 	    {
+	        int width, height;
+		RRCrtcGetScanoutSize (crtc, &width, &height);
 		scratch.x_org  = crtc->x;
 		scratch.y_org  = crtc->y;
-		scratch.width  = crtc->mode->mode.width;
-		scratch.height = crtc->mode->mode.height;
+		scratch.width  = width;
+		scratch.height = height;
 		if(client->swapped) {
 		    register int n;
 		    swaps(&scratch.x_org, n);
commit 72754184f1215acd2b053d476fa46142d97c8ebd
Author: Eric Anholt <eric at anholt.net>
Date:   Mon Jan 22 08:41:50 2007 +0800

    Really fix optimized render cases being hit when they shouldn't.
    
    I don't know how this define slipped in there.  Fixes
    6fdfd9dad91d7b7aa292f8c4d268dd27c34de8d3.

diff --git a/fb/fbpict.h b/fb/fbpict.h
index 179a07d..bfcb38e 100644
--- a/fb/fbpict.h
+++ b/fb/fbpict.h
@@ -105,9 +105,6 @@ fbCanGetSolid(PicturePtr pict)
     }
 }
 
-#define fbCanGetSolid(pict) \
-(pict->pDrawable != NULL && pict->pDrawable->width == 1 && pict->pDrawable->height == 1)
-
 #define fbComposeGetSolid(pict, bits, fmt) { \
     FbBits	*__bits__; \
     FbStride	__stride__; \
commit 1225a49da28dc04cc8233cfa746e1fae0024bbe1
Author: Eric Anholt <eric at anholt.net>
Date:   Thu Jan 18 14:28:01 2007 -0800

    Account for CRTC rotation in the cursor containment code.

diff --git a/randr/rrpointer.c b/randr/rrpointer.c
index c092e49..2a5ae7d 100644
--- a/randr/rrpointer.c
+++ b/randr/rrpointer.c
@@ -22,6 +22,32 @@
 
 #include "randrstr.h"
 
+/**
+ * Returns the width/height that the crtc scans out from the framebuffer
+ */
+static void
+RRCrtcGetScanoutSize(RRCrtcPtr crtc, int *width, int *height)
+{
+    if (crtc->mode == NULL) {
+	*width = 0;
+	*height = 0;
+	return;
+    }
+
+    switch (crtc->rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_180:
+	*width = crtc->mode->mode.width;
+	*height = crtc->mode->mode.height;
+	break;
+    case RR_Rotate_90:
+    case RR_Rotate_270:
+	*width = crtc->mode->mode.height;
+	*height = crtc->mode->mode.width;
+	break;
+    }
+}
+
 /*
  * When the pointer moves, check to see if the specified position is outside
  * any of theavailable CRTCs and move it to a 'sensible' place if so, where
@@ -34,11 +60,15 @@ static Bool
 RRCrtcContainsPosition (RRCrtcPtr crtc, int x, int y)
 {
     RRModePtr   mode = crtc->mode;
-    
+    int		scan_width, scan_height;
+
     if (!mode)
 	return FALSE;
-    if (crtc->x <= x && x < crtc->x + mode->mode.width &&
-	crtc->y <= y && y < crtc->y + mode->mode.height)
+
+    RRCrtcGetScanoutSize (crtc, &scan_width, &scan_height);
+
+    if (crtc->x <= x && x < crtc->x + scan_width &&
+	crtc->y <= y && y < crtc->y + scan_height)
 	return TRUE;
     return FALSE;
 }
@@ -54,28 +84,32 @@ RRPointerToNearestCrtc (ScreenPtr pScreen, int x, int y, RRCrtcPtr skip)
     RRCrtcPtr	nearest = NULL;
     int		best = 0;
     int		best_dx = 0, best_dy = 0;
-    
+
     for (c = 0; c < pScrPriv->numCrtcs; c++)
     {
 	RRCrtcPtr   crtc = pScrPriv->crtcs[c];
 	RRModePtr   mode = crtc->mode;
 	int	    dx, dy;
 	int	    dist;
+	int	    scan_width, scan_height;
 
 	if (!mode)
 	    continue;
 	if (crtc == skip)
 	    continue;
+
+	RRCrtcGetScanoutSize (crtc, &scan_width, &scan_height);
+
 	if (x < crtc->x)
 	    dx = crtc->x - x;
-	else if (x > crtc->x + mode->mode.width)
-	    dx = x - (crtc->x + mode->mode.width);
+	else if (x > crtc->x + scan_width)
+	    dx = x - (crtc->x + scan_width);
 	else
 	    dx = 0;
 	if (y < crtc->y)
 	    dy = crtc->y - x;
-	else if (y > crtc->y + mode->mode.height)
-	    dy = y - (crtc->y + mode->mode.height);
+	else if (y > crtc->y + scan_height)
+	    dy = y - (crtc->y + scan_height);
 	else
 	    dy = 0;
 	dist = dx + dy;
commit 364fb547d4d489f623cd633eaaeea00f617fd75e
Author: Eric Anholt <eric at anholt.net>
Date:   Tue Jan 16 13:01:03 2007 -0800

    When changing a non-pending property, call the screen rrOutputSetProperty hook.

diff --git a/randr/rrproperty.c b/randr/rrproperty.c
index dd1b5e0..ed01c88 100644
--- a/randr/rrproperty.c
+++ b/randr/rrproperty.c
@@ -125,6 +125,7 @@ RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
 {
     RRPropertyPtr		    prop;
     xRROutputPropertyNotifyEvent    event;
+    rrScrPrivPtr		    pScrPriv = rrGetScrPriv(output->pScreen);
     int				    sizeInBytes;
     int				    totalSize;
     pointer			    data;
@@ -213,6 +214,13 @@ RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
 	prop->next = output->properties;
 	output->properties = prop;
     }
+
+    if (!prop->is_pending) {
+	/* What should we do in case of failure? */
+	pScrPriv->rrOutputSetProperty(output->pScreen, output,
+				      prop->propertyName, prop_value);
+    }
+
     if (sendevent)
     {
 	event.type = RREventBase + RRNotify;
commit 11307c4b88244afc8b6a4dac36aa063c083b36d4
Author: Eric Anholt <eric at anholt.net>
Date:   Tue Jan 16 12:59:34 2007 -0800

    Don't forget to add the property we configure to the properties list.

diff --git a/randr/rrproperty.c b/randr/rrproperty.c
index 13e8483..dd1b5e0 100644
--- a/randr/rrproperty.c
+++ b/randr/rrproperty.c
@@ -298,6 +298,12 @@ RRConfigureOutputProperty (RROutputPtr output, Atom property,
     if (prop->valid_values)
 	xfree (prop->valid_values);
     prop->valid_values = new_values;
+
+    if (add) {
+	prop->next = output->properties;
+	output->properties = prop;
+    }
+
     return Success;
 }
 
commit 07e5c928ab9904ef21678d236b8eb5ef6419ed51
Author: Eric Anholt <eric at anholt.net>
Date:   Tue Jan 9 16:34:40 2007 -0800

    Track rename of DamagePost -> DamageAdd.

diff --git a/damageext/damageext.c b/damageext/damageext.c
index 62525f6..36d31e8 100755
--- a/damageext/damageext.c
+++ b/damageext/damageext.c
@@ -276,14 +276,14 @@ ProcDamageSubtract (ClientPtr client)
 }
 
 static int
-ProcDamagePost (ClientPtr client)
+ProcDamageAdd (ClientPtr client)
 {
-    REQUEST(xDamagePostReq);
+    REQUEST(xDamageAddReq);
     DrawablePtr	    pDrawable;
     RegionPtr	    pRegion;
     int		    rc;
 
-    REQUEST_SIZE_MATCH(xDamagePostReq);
+    REQUEST_SIZE_MATCH(xDamageAddReq);
     VERIFY_REGION(pRegion, stuff->region, client, DixWriteAccess);
     rc = dixLookupDrawable(&pDrawable, stuff->drawable, client, 0,
 			   DixReadAccess);
@@ -303,7 +303,7 @@ ProcDamagePost (ClientPtr client)
 /* Major version controls available requests */
 static const int version_requests[] = {
     X_DamageQueryVersion,	/* before client sends QueryVersion */
-    X_DamagePost,		/* Version 1 */
+    X_DamageAdd,		/* Version 1 */
 };
 
 #define NUM_VERSION_REQUESTS	(sizeof (version_requests) / sizeof (version_requests[0]))
@@ -315,7 +315,7 @@ int	(*ProcDamageVector[XDamageNumberRequests])(ClientPtr) = {
     ProcDamageDestroy,
     ProcDamageSubtract,
 /*************** Version 1.1 ****************/
-    ProcDamagePost,
+    ProcDamageAdd,
 };
 
 
@@ -385,10 +385,10 @@ SProcDamageSubtract (ClientPtr client)
 }
 
 static int
-SProcDamagePost (ClientPtr client)
+SProcDamageAdd (ClientPtr client)
 {
     register int n;
-    REQUEST(xDamagePostReq);
+    REQUEST(xDamageAddReq);
 
     swaps (&stuff->length, n);
     REQUEST_SIZE_MATCH(xDamageSubtractReq);
@@ -404,7 +404,7 @@ int	(*SProcDamageVector[XDamageNumberRequests])(ClientPtr) = {
     SProcDamageDestroy,
     SProcDamageSubtract,
 /*************** Version 1.1 ****************/
-    SProcDamagePost,
+    SProcDamageAdd,
 };
 
 static int
commit f1b95fda6ca01ff10a06e8753f66eb123d603eed
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Mon Jan 29 23:01:37 2007 -0800

    Add support for the DamagePost (XDamage 1.1) request.
    
    This makes damageproto >= 1.1 a requirement to build.
    (cherry picked from 0b73a7eb17fd848c6bdc6a65ba835aa2cbfc3cfd)

diff --git a/configure.ac b/configure.ac
index 6c0aa3a..a939687 100644
--- a/configure.ac
+++ b/configure.ac
@@ -514,7 +514,7 @@ XEXT_LIB='$(top_builddir)/Xext/libXext.la'
 XEXTXORG_LIB='$(top_builddir)/Xext/libXextbuiltin.la'
 
 dnl Core modules for most extensions, et al.
-REQUIRED_MODULES="randrproto renderproto [fixesproto >= 4.0] damageproto xcmiscproto xextproto xproto xtrans xf86miscproto xf86vidmodeproto xf86bigfontproto [scrnsaverproto >= 1.1] bigreqsproto resourceproto fontsproto inputproto xf86dgaproto [kbproto >= 1.0.3]"
+REQUIRED_MODULES="[randrproto >= 1.2] renderproto [fixesproto >= 4.0] [damageproto >= 1.1] xcmiscproto xextproto xproto xtrans xf86miscproto xf86vidmodeproto xf86bigfontproto [scrnsaverproto >= 1.1] bigreqsproto resourceproto fontsproto inputproto xf86dgaproto [kbproto >= 1.0.3]"
 REQUIRED_LIBS="xfont xau fontenc"
 
 AM_CONDITIONAL(XV, [test "x$XV" = xyes])
diff --git a/damageext/damageext.c b/damageext/damageext.c
index 225f9ec..62525f6 100755
--- a/damageext/damageext.c
+++ b/damageext/damageext.c
@@ -275,10 +275,35 @@ ProcDamageSubtract (ClientPtr client)
     return (client->noClientException);
 }
 
+static int
+ProcDamagePost (ClientPtr client)
+{
+    REQUEST(xDamagePostReq);
+    DrawablePtr	    pDrawable;
+    RegionPtr	    pRegion;
+    int		    rc;
+
+    REQUEST_SIZE_MATCH(xDamagePostReq);
+    VERIFY_REGION(pRegion, stuff->region, client, DixWriteAccess);
+    rc = dixLookupDrawable(&pDrawable, stuff->drawable, client, 0,
+			   DixReadAccess);
+    if (rc != Success)
+	return rc;
+
+    /* The region is relative to the drawable origin, so translate it out to
+     * screen coordinates like damage expects.
+     */
+    REGION_TRANSLATE(pScreen, pRegion, pDrawable->x, pDrawable->y);
+    DamageDamageRegion(pDrawable, pRegion);
+    REGION_TRANSLATE(pScreen, pRegion, -pDrawable->x, -pDrawable->y);
+
+    return (client->noClientException);
+}
+
 /* Major version controls available requests */
 static const int version_requests[] = {
     X_DamageQueryVersion,	/* before client sends QueryVersion */
-    X_DamageSubtract,		/* Version 1 */
+    X_DamagePost,		/* Version 1 */
 };
 
 #define NUM_VERSION_REQUESTS	(sizeof (version_requests) / sizeof (version_requests[0]))
@@ -289,6 +314,8 @@ int	(*ProcDamageVector[XDamageNumberRequests])(ClientPtr) = {
     ProcDamageCreate,
     ProcDamageDestroy,
     ProcDamageSubtract,
+/*************** Version 1.1 ****************/
+    ProcDamagePost,
 };
 
 
@@ -357,12 +384,27 @@ SProcDamageSubtract (ClientPtr client)
     return (*ProcDamageVector[stuff->damageReqType]) (client);
 }
 
+static int
+SProcDamagePost (ClientPtr client)
+{
+    register int n;
+    REQUEST(xDamagePostReq);
+
+    swaps (&stuff->length, n);
+    REQUEST_SIZE_MATCH(xDamageSubtractReq);
+    swapl (&stuff->drawable, n);
+    swapl (&stuff->region, n);
+    return (*ProcDamageVector[stuff->damageReqType]) (client);
+}
+
 int	(*SProcDamageVector[XDamageNumberRequests])(ClientPtr) = {
 /*************** Version 1 ******************/
     SProcDamageQueryVersion,
     SProcDamageCreate,
     SProcDamageDestroy,
     SProcDamageSubtract,
+/*************** Version 1.1 ****************/
+    SProcDamagePost,
 };
 
 static int
commit cd5fe7890d9b940b9d3e00043a6c81a10ae3db69
Author: Eric Anholt <eric at anholt.net>
Date:   Thu Jan 4 12:24:48 2007 -0800

    Keep track of how many visuals we set up for GLcore, to avoid an invalid free.
    
    The proper fix would involve actually setting up the ARGB visual for GLcore,
    but I just want the server to not crash at exit.

diff --git a/GL/mesa/X/xf86glx.c b/GL/mesa/X/xf86glx.c
index 94959d6..47c87f6 100644
--- a/GL/mesa/X/xf86glx.c
+++ b/GL/mesa/X/xf86glx.c
@@ -78,6 +78,7 @@ typedef struct __GLXMESAdrawable __GLXMESAdrawable;
 struct __GLXMESAscreen {
     __GLXscreen   base;
     int           index;
+    int		  num_vis;
     XMesaVisual  *xm_vis;
 };
 
@@ -280,7 +281,7 @@ __glXMesaScreenDestroy(__GLXscreen *screen)
     __GLXMESAscreen *mesaScreen = (__GLXMESAscreen *) screen;
     int i;
 
-    for (i = 0; i < screen->numVisuals; i++) {
+    for (i = 0; i < mesaScreen->num_vis; i++) {
 	if (mesaScreen->xm_vis[i])
 	    XMesaDestroyVisual(mesaScreen->xm_vis[i]);
     }
@@ -389,6 +390,7 @@ static void init_screen_visuals(__GLXMESAscreen *screen)
 
     xfree(used);
 
+    screen->num_vis = pScreen->numVisuals;
     screen->xm_vis = pXMesaVisual;
 }
 
commit 1a34f1966c23fbc291a56e9e747aec8eaf9ca2a4
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Mon Jan 29 22:04:07 2007 -0800

    Export API for setting allowed CRTC rotations

diff --git a/randr/randrstr.h b/randr/randrstr.h
index 136a47e..7a34b39 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -480,6 +480,12 @@ RRCrtcPtr
 RRCrtcCreate (void	*devPrivate);
 
 /*
+ * Set the allowed rotations on a CRTC
+ */
+void
+RRCrtcSetRotations (RRCrtcPtr crtc, Rotation rotations);
+
+/*
  * Attach a CRTC to a screen. Once done, this cannot be
  * undone without destroying the CRTC; it is separate from Create
  * only to allow an xf86-based driver to create objects in preinit
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 93854d5..63898f8 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -81,6 +81,15 @@ RRCrtcCreate (void	*devPrivate)
 }
 
 /*
+ * Set the allowed rotations on a CRTC
+ */
+void
+RRCrtcSetRotations (RRCrtcPtr crtc, Rotation rotations)
+{
+    crtc->rotations = rotations;
+}
+
+/*
  * Attach a Crtc to a screen. This is done as a separate step
  * so that an xf86-based driver can create CRTCs in PreInit
  * before the Screen has been created
commit ceca97cb84385da8b3178671f811af9bc61558f7
Merge: f05dd38... b9dc0ae...
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Mon Jan 29 22:03:19 2007 -0800

    Merge branch 'server-1.2' into randr-1.2-for-server-1.2

commit f05dd384d38c76dd9662933a03625dfef5b1c81f
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Sat Dec 30 21:52:22 2006 -0800

    Use RRScreenSetSizeRange in 1.0 compat. Check RRGetInfo for error.
    
    The RRScreenSizeSetRange function is used externally for 1.2 API drivers,
    but can also be used in the 1.0 compatibility code. This also ensures that
    the right changed bits are set so that clients are correctly notified when
    the range changes.
    
    RRGetInfo can return an error, use that to return BadAlloc to clients
    instead of blindly going on with various requests.

diff --git a/randr/rrinfo.c b/randr/rrinfo.c
index 85426f6..797cdb1 100644
--- a/randr/rrinfo.c
+++ b/randr/rrinfo.c
@@ -169,18 +169,7 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
 	if (height > maxHeight) maxHeight = height;
     }
 
-    if (minWidth != pScrPriv->minWidth) {
-	pScrPriv->minWidth = minWidth; pScrPriv->changed = TRUE;
-    }
-    if (maxWidth != pScrPriv->maxWidth) {
-	pScrPriv->maxWidth = maxWidth; pScrPriv->changed = TRUE;
-    }
-    if (minHeight != pScrPriv->minHeight) {
-	pScrPriv->minHeight = minHeight; pScrPriv->changed = TRUE;
-    }
-    if (maxHeight != pScrPriv->maxHeight) {
-	pScrPriv->maxHeight = maxHeight; pScrPriv->changed = TRUE;
-    }
+    RRScreenSetSizeRange (pScreen, minWidth, minHeight, maxWidth, maxHeight);
 
     /* notice current mode */
     if (newMode)
@@ -219,7 +208,6 @@ RRGetInfo (ScreenPtr pScreen)
     return TRUE;
 }
 
-#if RANDR_12_INTERFACE
 /*
  * Register the range of sizes for the screen
  */
@@ -234,12 +222,19 @@ RRScreenSetSizeRange (ScreenPtr	pScreen,
 
     if (!pScrPriv)
 	return;
+    if (pScrPriv->minWidth == minWidth && pScrPriv->minHeight == minHeight &&
+	pScrPriv->maxWidth == maxWidth && pScrPriv->maxHeight == maxHeight)
+    {
+	return;
+    }
+	
     pScrPriv->minWidth  = minWidth;
     pScrPriv->minHeight = minHeight;
     pScrPriv->maxWidth  = maxWidth;
     pScrPriv->maxHeight = maxHeight;
+    pScrPriv->changed = TRUE;
+    pScrPriv->configChanged = TRUE;
 }
-#endif
 
 #ifdef RANDR_10_INTERFACE
 static Bool
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 8ee126a..7b0fbb8 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -239,7 +239,8 @@ ProcRRGetScreenSizeRange (ClientPtr client)
     
     if (pScrPriv) 
     {
-	RRGetInfo (pScreen);
+	if (!RRGetInfo (pScreen))
+	    return BadAlloc;
 	rep.minWidth  = pScrPriv->minWidth;
 	rep.minHeight = pScrPriv->minHeight;
 	rep.maxWidth  = pScrPriv->maxWidth;
@@ -359,7 +360,8 @@ ProcRRGetScreenResources (ClientPtr client)
     rep.pad = 0;
     
     if (pScrPriv)
-	RRGetInfo (pScreen);
+	if (!RRGetInfo (pScreen))
+	    return BadAlloc;
 
     if (!pScrPriv)
     {
@@ -603,7 +605,8 @@ ProcRRGetScreenInfo (ClientPtr client)
     rep.pad = 0;
     
     if (pScrPriv)
-	RRGetInfo (pScreen);
+	if (!RRGetInfo (pScreen))
+	    return BadAlloc;
 
     output = RRFirstOutput (pScreen);
     
commit 06a4be5e7a5371881106b6f51368330a33b26401
Merge: f42e3ce... f4ef99e...
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Thu Dec 21 23:52:24 2006 -0800

    Merge branch 'server-1.2-branch' into randr-1.2-for-server-1.2

commit f42e3cea236fa0091ed398a818fc8e17b0e1b3df
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Thu Dec 21 23:50:39 2006 -0800

    Track physical screen size and send out updates when that changes.
    
    Events and internal data structures need to be updated whenever the physical
    or pixel size of the screen changes. The code was ignoring the physical
    size, so changing only that would not be registered anywhere.

diff --git a/randr/randr.c b/randr/randr.c
index 1470035..5fa9baf 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -243,6 +243,10 @@ Bool RRScreenInit(ScreenPtr pScreen)
     pScrPriv->maxWidth = pScrPriv->minWidth = pScreen->width;
     pScrPriv->maxHeight = pScrPriv->minHeight = pScreen->height;
     
+    pScrPriv->width = pScreen->width;
+    pScrPriv->height = pScreen->height;
+    pScrPriv->mmWidth = pScreen->mmWidth;
+    pScrPriv->mmHeight = pScreen->mmHeight;
 #if RANDR_12_INTERFACE
     pScrPriv->rrScreenSetSize = NULL;
     pScrPriv->rrCrtcSet = NULL;
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 88f7588..136a47e 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -224,6 +224,7 @@ typedef struct _rrScrPriv {
     CARD16		    minWidth, minHeight;
     CARD16		    maxWidth, maxHeight;
     CARD16		    width, height;	/* last known screen size */
+    CARD16		    mmWidth, mmHeight;	/* last known screen size */
 
     int			    numOutputs;
     RROutputPtr		    *outputs;
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 51957bf..8ee126a 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -158,11 +158,15 @@ RRScreenSizeNotify (ScreenPtr	pScreen)
      * pixel size
      */
     if (pScrPriv->width == pScreen->width &&
-	pScrPriv->height == pScreen->height)
+	pScrPriv->height == pScreen->height &&
+	pScrPriv->mmWidth == pScreen->mmWidth &&
+	pScrPriv->mmHeight == pScreen->mmHeight)
 	return;
     
     pScrPriv->width = pScreen->width;
     pScrPriv->height = pScreen->height;
+    pScrPriv->mmWidth = pScreen->mmWidth;
+    pScrPriv->mmHeight = pScreen->mmHeight;
     pScrPriv->changed = TRUE;
 /*    pScrPriv->sizeChanged = TRUE; */
 
commit 91396f14307537557ecd6eacf778fa091dd410c6
Merge: 612a8e6... 6dc7118...
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Wed Dec 13 01:21:53 2006 -0800

    Merge branch 'randr-1.2-for-server-1.2-origin' into randr-1.2-for-server-1.2

commit 612a8e61803da8db0e305cbb093696b8e4284572
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Wed Dec 13 01:21:32 2006 -0800

    RandR 1.2 rotation code must adjust width/height.
    
    Mode lines reflect the monitor mode, not the projected size into the frame
    buffer. Flip width/height around so that the dimensions are oriented
    correctly.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index e8a7b79..7409e96 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -698,7 +698,15 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	 */
 	if (pScrPriv->rrScreenSetSize)
 	{
-	    if (stuff->x + mode->mode.width > pScreen->width)
+	    int source_width = mode->mode.width;
+	    int	source_height = mode->mode.height;
+
+	    if (rotation == RR_Rotate_90 || rotation == RR_Rotate_270)
+	    {
+		source_width = mode->mode.height;
+		source_height = mode->mode.width;
+	    }
+	    if (stuff->x + source_width > pScreen->width)
 	    {
 		client->errorValue = stuff->x;
 		if (outputs)
@@ -706,7 +714,7 @@ ProcRRSetCrtcConfig (ClientPtr client)
 		return BadValue;
 	    }
 	    
-	    if (stuff->y + mode->mode.height > pScreen->height)
+	    if (stuff->y + source_height > pScreen->height)
 	    {
 		client->errorValue = stuff->y;
 		if (outputs)
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 76c16b0..38dbaed 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -268,7 +268,6 @@ ProcRRSetScreenSize (ClientPtr client)
     WindowPtr		pWin;
     ScreenPtr		pScreen;
     rrScrPrivPtr	pScrPriv;
-    RRCrtcPtr		crtc;
     int			i;
     
     REQUEST_SIZE_MATCH(xRRSetScreenSizeReq);
@@ -291,12 +290,26 @@ ProcRRSetScreenSize (ClientPtr client)
 	client->errorValue = stuff->height;
 	return BadValue;
     }
-    for (i = 0; i < pScrPriv->numCrtcs; i++) {
-	crtc = pScrPriv->crtcs[i];
-	if (crtc->mode &&
-	    (crtc->x + crtc->mode->mode.width > stuff->width ||
-	     crtc->y + crtc->mode->mode.height > stuff->height))
+    for (i = 0; i < pScrPriv->numCrtcs; i++) 
+    {
+	RRCrtcPtr   crtc = pScrPriv->crtcs[i];
+	RRModePtr   mode = crtc->mode;
+	if (mode)
+	{
+	    int		source_width = mode->mode.width;
+	    int		source_height = mode->mode.height;
+	    Rotation	rotation = crtc->rotation;
+
+	    if (rotation == RR_Rotate_90 || rotation == RR_Rotate_270)
+	    {
+		source_width = mode->mode.height;
+		source_height = mode->mode.width;
+	    }
+	    
+	    if (crtc->x + source_width > stuff->width ||
+		crtc->y + source_height > stuff->height)
 	    return BadMatch;
+	}
     }
     if (stuff->widthInMillimeters == 0 || stuff->heightInMillimeters == 0)
     {
commit 6dc711833d7387372012fdff1ce1df3aefa2d234
Author: Keith Packard <keithp at mandolin.keithp.com>
Date:   Wed Dec 13 00:58:54 2006 -0800

    RandR 1.0 refresh rates unscrambled. SetScreenConfig uses RRCrtcSet right.
    
    RandR 1.0 refresh rates were scrambled when working with a 1.2 driver that
    returned sizes in a mixed order. SetScreenConfig was treating RRCrtcSet as
    returning an RandR status instead of a Bool.

diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 76c16b0..0028748 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -481,62 +481,81 @@ RR10GetData (ScreenPtr pScreen, RROutputPtr output)
     RR10DataPtr	    data;
     RRScreenSizePtr size;
     int		    nmode = output->numModes;
-    int		    i, j, k;
+    int		    o, os, l, r;
     RRScreenRatePtr refresh;
     CARD16	    vRefresh;
     RRModePtr	    mode;
+    Bool	    *used;
 
     /* Make sure there is plenty of space for any combination */
     data = malloc (sizeof (RR10DataRec) + 
 		   sizeof (RRScreenSize) * nmode + 
-		   sizeof (RRScreenRate) * nmode);
+		   sizeof (RRScreenRate) * nmode +
+		   sizeof (Bool) * nmode);
     if (!data)
 	return NULL;
     size = (RRScreenSizePtr) (data + 1);
     refresh = (RRScreenRatePtr) (size + nmode);
+    used = (Bool *) (refresh + nmode);
+    memset (used, '\0', sizeof (Bool) * nmode);
     data->sizes = size;
     data->nsize = 0;
     data->nrefresh = 0;
     data->size = 0;
     data->refresh = 0;
-    for (i = 0; i < output->numModes; i++)
+    
+    /*
+     * find modes not yet listed
+     */
+    for (o = 0; o < output->numModes; o++)
     {
-	mode = output->modes[i];
-	for (j = 0; j < data->nsize; j++)
-	    if (mode->mode.width == size[j].width &&
-		mode->mode.height == size[j].height)
-		break;
-	if (j == data->nsize)
-	{
-	    size[j].id = j;
-	    size[j].width = mode->mode.width;
-	    size[j].height = mode->mode.height;
-	    if (output->mmWidth && output->mmHeight) {
-		size[j].mmWidth = output->mmWidth;
-		size[j].mmHeight = output->mmHeight;
-	    } else {
-		size[j].mmWidth = pScreen->mmWidth;
-		size[j].mmHeight = pScreen->mmHeight;
-	    }
-	    size[j].nRates = 0;
-	    size[j].pRates = &refresh[data->nrefresh];
-	    data->nsize++;
-	}
-	vRefresh = RRVerticalRefresh (&mode->mode);
-	for (k = 0; k < size[j].nRates; k++)
-	    if (vRefresh == size[j].pRates[k].rate)
-		break;
-	if (k == size[j].nRates)
-	{
-	    size[j].pRates[k].rate = vRefresh;
-	    size[j].pRates[k].mode = mode;
-	    size[j].nRates++;
-	    data->nrefresh++;
+	if (used[o]) continue;
+	
+	mode = output->modes[o];
+	
+	l = data->nsize;
+	size[l].id = data->nsize;
+	size[l].width = mode->mode.width;
+	size[l].height = mode->mode.height;
+	if (output->mmWidth && output->mmHeight) {
+	    size[l].mmWidth = output->mmWidth;
+	    size[l].mmHeight = output->mmHeight;
+	} else {
+	    size[l].mmWidth = pScreen->mmWidth;
+	    size[l].mmHeight = pScreen->mmHeight;
 	}
-	if (mode == output->crtc->mode)
+	size[l].nRates = 0;
+	size[l].pRates = &refresh[data->nrefresh];
+	data->nsize++;
+	
+	/*
+	 * Find all modes with matching size
+	 */
+	for (os = o; os < output->numModes; os++)
 	{
-	    data->size = j;
-	    data->refresh = vRefresh;
+	    mode = output->modes[os];
+	    if (mode->mode.width == size[l].width &&
+		mode->mode.height == size[l].height)
+	    {
+		vRefresh = RRVerticalRefresh (&mode->mode);
+		used[os] = TRUE;
+		
+		for (r = 0; r < size[l].nRates; r++)
+		    if (vRefresh == size[l].pRates[r].rate)
+			break;
+		if (r == size[l].nRates)
+		{
+		    size[l].pRates[r].rate = vRefresh;
+		    size[l].pRates[r].mode = mode;
+		    size[l].nRates++;
+		    data->nrefresh++;
+		}
+		if (mode == output->crtc->mode)
+		{
+		    data->size = l;
+		    data->refresh = vRefresh;
+		}
+	    }
 	}
     }
     return data;
@@ -864,22 +883,28 @@ ProcRRSetScreenConfig (ClientPtr client)
 
 	for (c = 0; c < pScrPriv->numCrtcs; c++)
 	{
-	    rep.status = RRCrtcSet (pScrPriv->crtcs[c], NULL, 0, 0, RR_Rotate_0,
-				    0, NULL);
-	    if (rep.status != Success)
+	    if (!RRCrtcSet (pScrPriv->crtcs[c], NULL, 0, 0, RR_Rotate_0,
+			    0, NULL))
+	    {
+		rep.status = RRSetConfigFailed;
+		/* XXX recover from failure */
 		goto sendReply;
+	    }
 	}
 	if (!RRScreenSizeSet (pScreen, mode->mode.width, mode->mode.height,
 			      pScreen->mmWidth, pScreen->mmHeight))
 	{
 	    rep.status = RRSetConfigFailed;
+	    /* XXX recover from failure */
 	    goto sendReply;
 	}
     }
-    
-    rep.status = RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation,
-			    1, &output);
-    
+
+    if (!RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation, 1, &output))
+	rep.status = RRSetConfigFailed;
+    else
+	rep.status = RRSetConfigSuccess;
+
     /*
      * XXX Configure other crtcs to mirror as much as possible
      */
commit 98d18a6578130adb411ca4bcc776fcb7e07f189f
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Tue Dec 12 22:59:03 2006 -0800

    RandR: config time updates when hardware config changes.
    
    The config time in the RandR protocol reflects when the hardware state has
    changed. It was getting changed anytime the driver changed the usage
    of the hardware as well.

diff --git a/randr/randr.c b/randr/randr.c
index 147df8c..1470035 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -415,7 +415,11 @@ RRTellChanged (ScreenPtr pScreen)
     if (pScrPriv->changed)
     {
 	UpdateCurrentTime ();
-	pScrPriv->lastConfigTime = currentTime;
+	if (pScrPriv->configChanged)
+	{
+	    pScrPriv->lastConfigTime = currentTime;
+	    pScrPriv->configChanged = FALSE;
+	}
 	pScrPriv->changed = FALSE;
 	WalkTree (pScreen, TellChanged, (pointer) pScreen);
 	for (i = 0; i < pScrPriv->numOutputs; i++)
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 27ede92..88f7588 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -216,11 +216,14 @@ typedef struct _rrScrPriv {
     TimeStamp		    lastSetTime;	/* last changed by client */
     TimeStamp		    lastConfigTime;	/* possible configs changed */
     RRCloseScreenProcPtr    CloseScreen;
+
     Bool		    changed;		/* some config changed */
+    Bool		    configChanged;	/* configuration changed */
+    Bool		    layoutChanged;	/* screen layout changed */
+
     CARD16		    minWidth, minHeight;
     CARD16		    maxWidth, maxHeight;
     CARD16		    width, height;	/* last known screen size */
-    Bool		    layoutChanged;	/* screen layout changed */
 
     int			    numOutputs;
     RROutputPtr		    *outputs;
@@ -619,10 +622,13 @@ ProcRRDeleteOutputMode (ClientPtr client);
 /* rroutput.c */
 
 /*
- * Notify the output of some change
+ * Notify the output of some change. configChanged indicates whether
+ * any external configuration (mode list, clones, connected status)
+ * has changed, or whether the change was strictly internal
+ * (which crtc is in use)
  */
 void
-RROutputChanged (RROutputPtr output);
+RROutputChanged (RROutputPtr output, Bool configChanged);
 
 /*
  * Create an output
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index e8a7b79..5100bda 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -136,7 +136,7 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 		break;
 	if (j == crtc->numOutputs)
 	{
-	    RROutputChanged (outputs[i]);
+	    RROutputChanged (outputs[i], FALSE);
 	    RRCrtcChanged (crtc, FALSE);
 	}
     }
@@ -151,7 +151,7 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 		break;
 	if (i == numOutputs)
 	{
-	    RROutputChanged (crtc->outputs[j]);
+	    RROutputChanged (crtc->outputs[j], FALSE);
 	    RRCrtcChanged (crtc, FALSE);
 	}
     }
diff --git a/randr/rrinfo.c b/randr/rrinfo.c
index 244b089..85426f6 100644
--- a/randr/rrinfo.c
+++ b/randr/rrinfo.c
@@ -69,6 +69,7 @@ RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
     output->modes = modes;
     output->changed = TRUE;
     pScrPriv->changed = TRUE;
+    pScrPriv->configChanged = TRUE;
     return mode;
 }
 
@@ -205,6 +206,7 @@ RRGetInfo (ScreenPtr pScreen)
     
     rotations = 0;
     pScrPriv->changed = FALSE;
+    pScrPriv->configChanged = FALSE;
     
     if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
 	return FALSE;
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 430f8bd..8007a8a 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -28,7 +28,7 @@ RESTYPE	RROutputType;
  * Notify the output of some change
  */
 void
-RROutputChanged (RROutputPtr output)
+RROutputChanged (RROutputPtr output, Bool configChanged)
 {
     ScreenPtr	pScreen = output->pScreen;
     
@@ -37,6 +37,8 @@ RROutputChanged (RROutputPtr output)
     {
 	rrScrPriv (pScreen);
 	pScrPriv->changed = TRUE;
+	if (configChanged)
+	    pScrPriv->configChanged = TRUE;
     }
 }
 
@@ -106,7 +108,7 @@ RROutputAttachScreen (RROutputPtr output, ScreenPtr pScreen)
     output->pScreen = pScreen;
     pScrPriv->outputs = outputs;
     pScrPriv->outputs[pScrPriv->numOutputs++] = output;
-    RROutputChanged (output);
+    RROutputChanged (output, FALSE);
     return TRUE;
 }
 		      
@@ -142,7 +144,7 @@ RROutputSetClones (RROutputPtr  output,
     memcpy (newClones, clones, numClones * sizeof (RROutputPtr));
     output->clones = newClones;
     output->numClones = numClones;
-    RROutputChanged (output);
+    RROutputChanged (output, TRUE);
     return TRUE;
 }
 
@@ -186,7 +188,7 @@ RROutputSetModes (RROutputPtr	output,
     output->modes = newModes;
     output->numModes = numModes;
     output->numPreferred = numPreferred;
-    RROutputChanged (output);
+    RROutputChanged (output, TRUE);
     return TRUE;
 }
 
@@ -219,7 +221,7 @@ RROutputSetCrtcs (RROutputPtr	output,
     memcpy (newCrtcs, crtcs, numCrtcs * sizeof (RRCrtcPtr));
     output->crtcs = newCrtcs;
     output->numCrtcs = numCrtcs;
-    RROutputChanged (output);
+    RROutputChanged (output, TRUE);
     return TRUE;
 }
 
@@ -229,7 +231,7 @@ RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc)
     if (output->crtc == crtc)
 	return;
     output->crtc = crtc;
-    RROutputChanged (output);
+    RROutputChanged (output, FALSE);
 }
 
 Bool
@@ -239,7 +241,7 @@ RROutputSetConnection (RROutputPtr  output,
     if (output->connection == connection)
 	return TRUE;
     output->connection = connection;
-    RROutputChanged (output);
+    RROutputChanged (output, TRUE);
     return TRUE;
 }
 
@@ -251,7 +253,7 @@ RROutputSetSubpixelOrder (RROutputPtr output,
 	return TRUE;
 
     output->subpixelOrder = subpixelOrder;
-    RROutputChanged (output);
+    RROutputChanged (output, FALSE);
     return TRUE;
 }
 
@@ -264,7 +266,7 @@ RROutputSetPhysicalSize (RROutputPtr	output,
 	return TRUE;
     output->mmWidth = mmWidth;
     output->mmHeight = mmHeight;
-    RROutputChanged (output);
+    RROutputChanged (output, FALSE);
     return TRUE;
 }
 
commit 78689d0d6630afcbcd3ce5394d12c2564a489f45
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Tue Dec 12 20:16:49 2006 -0800

    RandR mode list needs both output and crtc modes.
    
    When an output no longer reports the current mode, it must still be included
    in the list advertised by the X server. Walk the crtcs to ensure it is
    included.

diff --git a/randr/rrmode.c b/randr/rrmode.c
index a0696e1..261e1b7 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -108,12 +108,15 @@ RRModePtr *
 RRModesForScreen (ScreenPtr pScreen, int *num_ret)
 {
     rrScrPriv(pScreen);
-    int	o;
+    int	o, c;
     RRModePtr	*screen_modes;
     int		num_screen_modes = 0;
 
     screen_modes = xalloc ((num_modes ? num_modes : 1) * sizeof (RRModePtr));
     
+    /*
+     * Add modes from all outputs
+     */
     for (o = 0; o < pScrPriv->numOutputs; o++)
     {
 	RROutputPtr	output = pScrPriv->outputs[o];
@@ -129,6 +132,24 @@ RRModesForScreen (ScreenPtr pScreen, int *num_ret)
 		screen_modes[num_screen_modes++] = mode;
 	}
     }
+    /*
+     * Add modes from all crtcs. The goal is to
+     * make sure all available and active modes
+     * are visible to the client
+     */
+    for (c = 0; c < pScrPriv->numCrtcs; c++)
+    {
+	RRCrtcPtr	crtc = pScrPriv->crtcs[c];
+	RRModePtr	mode = crtc->mode;
+	int		n;
+
+	if (!mode) continue;
+	for (n = 0; n < num_screen_modes; n++)
+	    if (screen_modes[n] == mode)
+		break;
+	if (n == num_screen_modes)
+	    screen_modes[num_screen_modes++] = mode;
+    }
     *num_ret = num_screen_modes;
     return screen_modes;
 }
commit 12c9714ba7dc01bb845b299ec9213e8c2e98e3e6
Merge: 66b6358... 8049eee...
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Tue Dec 12 09:22:14 2006 -0800

    Merge branch 'server-1.2-branch' into randr-1.2-for-server-1.2

commit 66b6358a393972946f16394918db2401c51dc5ed
Author: Keith Packard <keithp at ukulele.keithp.com>
Date:   Thu Nov 30 23:16:42 2006 -0800

    RandR ListOutputProperties has nAtoms element, not nProperties
    
    Earlier RandR 1.2 encoding revisions used 8-bit nProperties field.
    Final RandR 1.2 spec uses 16-bit nAtoms field instead.

diff --git a/randr/rrproperty.c b/randr/rrproperty.c
index a47f306..13e8483 100644
--- a/randr/rrproperty.c
+++ b/randr/rrproperty.c
@@ -325,9 +325,9 @@ ProcRRListOutputProperties (ClientPtr client)
             return(BadAlloc);
 
     rep.type = X_Reply;
-    rep.nProperties = numProps;
     rep.length = (numProps * sizeof(Atom)) >> 2;
     rep.sequenceNumber = client->sequence;
+    rep.nAtoms = numProps;
     if (client->swapped) 
     {
 	int n;
commit b5e373143695ab46605bae479c37a2106e947212
Merge: 4202b23... 7c63979...
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Thu Nov 30 17:40:12 2006 -0800

    Merge branch 'server-1.2' into randr-1.2-for-server-1.2

commit 4202b23ed86405a4cebfdcf239df1b023c1d10ca
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Mon Nov 27 21:40:24 2006 -0800

    Destroying RandR crtc or output overwrites memory.
    
    RRCrtcDestroyResource and RROutputDestroyResource had matching
    bugs that would overwrite memory past the end of the storage
    of the crtc or output arrays. Oops.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 212352c..e8a7b79 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -344,7 +344,7 @@ RRCrtcDestroyResource (pointer value, XID pid)
 	    if (pScrPriv->crtcs[i] == crtc)
 	    {
 		memmove (pScrPriv->crtcs + i, pScrPriv->crtcs + i + 1,
-			 (pScrPriv->numCrtcs - (i - 1)) * sizeof (RRCrtcPtr));
+			 (pScrPriv->numCrtcs - (i + 1)) * sizeof (RRCrtcPtr));
 		--pScrPriv->numCrtcs;
 		break;
 	    }
diff --git a/randr/rroutput.c b/randr/rroutput.c
index f38f582..430f8bd 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -327,7 +327,7 @@ RROutputDestroyResource (pointer value, XID pid)
 	    if (pScrPriv->outputs[i] == output)
 	    {
 		memmove (pScrPriv->outputs + i, pScrPriv->outputs + i + 1,
-			 (pScrPriv->numOutputs - (i - 1)) * sizeof (RROutputPtr));
+			 (pScrPriv->numOutputs - (i + 1)) * sizeof (RROutputPtr));
 		--pScrPriv->numOutputs;
 		break;
 	    }
commit ec83d674167e7045d5317b179c9998e3172a26dc
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Sun Nov 26 19:31:48 2006 -0800

    Ensure RandR resource types are registered before resources are created.
    
    Now that resources can be created during server initialization, make sure
    the crtc, output and mode resource types are created before attempting to
    create associated resources.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index b81c390..212352c 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -55,6 +55,8 @@ RRCrtcCreate (void	*devPrivate)
 {
     RRCrtcPtr	crtc;
     
+    if (!RRInit())
+	return NULL;
     crtc = xalloc (sizeof (RRCrtcRec));
     if (!crtc)
 	return NULL;
diff --git a/randr/rrmode.c b/randr/rrmode.c
index 3cd9ef2..a0696e1 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -67,6 +67,9 @@ RRModeGet (xRRModeInfo	*modeInfo,
 	}
     }
 
+    if (!RRInit ())
+	return NULL;
+
     mode = xalloc (sizeof (RRModeRec) + modeInfo->nameLength + 1);
     if (!mode)
 	return NULL;
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 8b760ec..f38f582 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -51,6 +51,8 @@ RROutputCreate (const char  *name,
 {
     RROutputPtr	output;
 
+    if (!RRInit())
+	return NULL;
     output = xalloc (sizeof (RROutputRec) + nameLength + 1);
     if (!output)
 	return NULL;
commit 0626eb8e5c9fa05de6bdc9aa0c654f5148bf7cff
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Tue Nov 21 16:52:28 2006 -0800

    Allocate correct size for RRPropertyRec (oops).
    
    Neglected to change the allocation size from sizeof (PropertyRec) to
    sizeof (RRPropertyRec). Lots of fun crashes this way.

diff --git a/randr/rrproperty.c b/randr/rrproperty.c
index 5d4c865..a47f306 100644
--- a/randr/rrproperty.c
+++ b/randr/rrproperty.c
@@ -68,9 +68,10 @@ RRCreateOutputProperty (Atom property)
 {
     RRPropertyPtr   prop;
     
-    prop = (RRPropertyPtr)xalloc(sizeof(PropertyRec));
+    prop = (RRPropertyPtr)xalloc(sizeof(RRPropertyRec));
     if (!prop)
 	return NULL;
+    prop->next = NULL;
     prop->propertyName = property;
     prop->is_pending = FALSE;
     prop->range = FALSE;
commit af55c65bea40669fdc038aa34c6a1ec9ecb33e87
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Tue Nov 21 01:15:26 2006 -0800

    Change RandR property datatype to include pending/valid values.
    
    This patch tracks the protocol changes which introduce more complex
    semantics for RandR output properties including pending and valid value
    information.

diff --git a/randr/mirandr.c b/randr/mirandr.c
index 3a99bf9..0b763e1 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -64,10 +64,11 @@ miRRCrtcSetGamma (ScreenPtr	pScreen,
     return TRUE;
 }
 
-static Bool
-miRROutputSetProperty (ScreenPtr	pScreen,
-		       RROutputPtr	output,
-		       Atom	property)
+Bool
+miRROutputSetProperty (ScreenPtr	    pScreen,
+		       RROutputPtr	    output,
+		       Atom		    property,
+		       RRPropertyValuePtr   value)
 {
     return TRUE;
 }
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 19af9b9..27ede92 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -69,9 +69,11 @@ extern int (*SProcRandrVector[RRNumberRequests])(ClientPtr);
  */
 
 #define RRModeName(pMode) ((char *) (pMode + 1))
-typedef struct _rrMode	    RRModeRec, *RRModePtr;
-typedef struct _rrCrtc	    RRCrtcRec, *RRCrtcPtr;
-typedef struct _rrOutput    RROutputRec, *RROutputPtr;
+typedef struct _rrMode		RRModeRec, *RRModePtr;
+typedef struct _rrPropertyValue	RRPropertyValueRec, *RRPropertyValuePtr;
+typedef struct _rrProperty	RRPropertyRec, *RRPropertyPtr;
+typedef struct _rrCrtc		RRCrtcRec, *RRCrtcPtr;
+typedef struct _rrOutput	RROutputRec, *RROutputPtr;
 
 struct _rrMode {
     int		    refcnt;
@@ -81,6 +83,24 @@ struct _rrMode {
     Bool	    userDefined;
 };
 
+struct _rrPropertyValue {
+    Atom	    type;       /* ignored by server */
+    short	    format;     /* format of data for swapping - 8,16,32 */
+    long	    size;	/* size of data in (format/8) bytes */
+    pointer         data;	/* private to client */
+};
+
+struct _rrProperty {
+    RRPropertyPtr   next;
+    ATOM 	    propertyName;
+    Bool	    is_pending;
+    Bool	    range;
+    Bool	    immutable;
+    int		    num_valid;
+    INT32	    *valid_values;
+    RRPropertyValueRec	current, pending;
+};
+
 struct _rrCrtc {
     RRCrtc	    id;
     ScreenPtr	    pScreen;
@@ -116,7 +136,7 @@ struct _rrOutput {
     int		    numPreferred;
     RRModePtr	    *modes;
     Bool	    changed;
-    PropertyPtr	    properties;
+    RRPropertyPtr   properties;
     void	    *devPrivate;
 };
 
@@ -139,9 +159,10 @@ typedef Bool (*RRCrtcSetProcPtr) (ScreenPtr		pScreen,
 typedef Bool (*RRCrtcSetGammaProcPtr) (ScreenPtr	pScreen,
 				       RRCrtcPtr	crtc);
 
-typedef Bool (*RROutputSetPropertyProcPtr) (ScreenPtr	pScreen,
-					    RROutputPtr	output,
-					    Atom	property);
+typedef Bool (*RROutputSetPropertyProcPtr) (ScreenPtr		pScreen,
+					    RROutputPtr		output,
+					    Atom		property,
+					    RRPropertyValuePtr	value);
 
 #endif
 
@@ -363,6 +384,12 @@ miRRCrtcSet (ScreenPtr	pScreen,
 	     int	numOutput,
 	     RROutputPtr *outputs);
 
+Bool
+miRROutputSetProperty (ScreenPtr	    pScreen,
+		       RROutputPtr	    output,
+		       Atom		    property,
+		       RRPropertyValuePtr   value);
+
 /* randr.c */
 /*
  * Send all pending events
@@ -676,6 +703,12 @@ RRPointerScreenConfigured (ScreenPtr pScreen);
 void
 RRDeleteAllOutputProperties (RROutputPtr output);
 
+RRPropertyValuePtr
+RRGetOutputProperty (RROutputPtr output, Atom property, Bool pending);
+
+RRPropertyPtr
+RRQueryOutputProperty (RROutputPtr output, Atom property);
+		       
 void
 RRDeleteOutputProperty (RROutputPtr output, Atom property);
 
@@ -685,6 +718,10 @@ RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
 			pointer value, Bool sendevent);
 
 int
+RRConfigureOutputProperty (RROutputPtr output, Atom property,
+			   Bool pending, Bool range, Bool immutable,
+			   int num_values, INT32 *values);
+int
 ProcRRChangeOutputProperty (ClientPtr client);
 
 int
@@ -694,6 +731,12 @@ int
 ProcRRListOutputProperties (ClientPtr client);
 
 int
+ProcRRQueryOutputProperty (ClientPtr client);
+
+int
+ProcRRConfigureOutputProperty (ClientPtr client);
+
+int
 ProcRRDeleteOutputProperty (ClientPtr client);
 
 /* rrxinerama.c */
diff --git a/randr/rrdispatch.c b/randr/rrdispatch.c
index 49ba10b..6b61b9c 100644
--- a/randr/rrdispatch.c
+++ b/randr/rrdispatch.c
@@ -192,17 +192,19 @@ int (*ProcRandrVector[RRNumberRequests])(ClientPtr) = {
     ProcRRGetScreenResources,	/* 8 */
     ProcRRGetOutputInfo,	/* 9 */
     ProcRRListOutputProperties,	/* 10 */
-    ProcRRChangeOutputProperty,	/* 11 */
-    ProcRRDeleteOutputProperty,	/* 12 */
-    ProcRRGetOutputProperty,	/* 13 */
-    ProcRRCreateMode,		/* 14 */
-    ProcRRDestroyMode,		/* 15 */
-    ProcRRAddOutputMode,	/* 16 */
-    ProcRRDeleteOutputMode,	/* 17 */
-    ProcRRGetCrtcInfo,		/* 18 */
-    ProcRRSetCrtcConfig,	/* 19 */
-    ProcRRGetCrtcGammaSize,	/* 20 */
-    ProcRRGetCrtcGamma,		/* 21 */
-    ProcRRSetCrtcGamma,		/* 22 */
+    ProcRRQueryOutputProperty,	/* 11 */
+    ProcRRConfigureOutputProperty,  /* 12 */
+    ProcRRChangeOutputProperty,	/* 13 */
+    ProcRRDeleteOutputProperty,	/* 14 */
+    ProcRRGetOutputProperty,	/* 15 */
+    ProcRRCreateMode,		/* 16 */
+    ProcRRDestroyMode,		/* 17 */
+    ProcRRAddOutputMode,	/* 18 */
+    ProcRRDeleteOutputMode,	/* 19 */
+    ProcRRGetCrtcInfo,		/* 20 */
+    ProcRRSetCrtcConfig,	/* 21 */
+    ProcRRGetCrtcGammaSize,	/* 22 */
+    ProcRRGetCrtcGamma,		/* 23 */
+    ProcRRSetCrtcGamma,		/* 24 */
 };
 
diff --git a/randr/rrproperty.c b/randr/rrproperty.c
index 44f1f0a..5d4c865 100644
--- a/randr/rrproperty.c
+++ b/randr/rrproperty.c
@@ -33,7 +33,7 @@ RRDeliverEvent (ScreenPtr pScreen, xEvent *event, CARD32 mask)
 void
 RRDeleteAllOutputProperties (RROutputPtr output)
 {
-    PropertyPtr prop, next;
+    RRPropertyPtr prop, next;
     xRROutputPropertyNotifyEvent    event;
 
     for (prop = output->properties; prop; prop = next)
@@ -46,15 +46,58 @@ RRDeleteAllOutputProperties (RROutputPtr output)
 	event.atom = prop->propertyName;
 	event.timestamp = currentTime.milliseconds;
 	RRDeliverEvent (output->pScreen, (xEvent *) &event, RROutputPropertyNotifyMask);
-        xfree(prop->data);
+	if (prop->current.data)
+	    xfree(prop->current.data);
+	if (prop->pending.data)
+	    xfree(prop->pending.data);
         xfree(prop);
     }
 }
 
+static void
+RRInitOutputPropertyValue (RRPropertyValuePtr property_value)
+{
+    property_value->type = None;
+    property_value->format = 0;
+    property_value->size = 0;
+    property_value->data = NULL;
+}
+
+static RRPropertyPtr
+RRCreateOutputProperty (Atom property)
+{
+    RRPropertyPtr   prop;
+    
+    prop = (RRPropertyPtr)xalloc(sizeof(PropertyRec));
+    if (!prop)
+	return NULL;
+    prop->propertyName = property;
+    prop->is_pending = FALSE;
+    prop->range = FALSE;
+    prop->immutable = FALSE;
+    prop->num_valid = 0;
+    prop->valid_values = NULL;
+    RRInitOutputPropertyValue (&prop->current);
+    RRInitOutputPropertyValue (&prop->pending);
+    return prop;
+}
+
+static void
+RRDestroyOutputProperty (RRPropertyPtr prop)
+{
+    if (prop->valid_values)
+	xfree (prop->valid_values);
+    if (prop->current.data)
+	xfree(prop->current.data);
+    if (prop->pending.data)
+	xfree(prop->pending.data);
+    xfree(prop);
+}
+
 void
 RRDeleteOutputProperty (RROutputPtr output, Atom property)
 {
-    PropertyPtr	prop, *prev;
+    RRPropertyPtr	prop, *prev;
     xRROutputPropertyNotifyEvent    event;
 
     for (prev = &output->properties; (prop = *prev); prev = &(prop->next))
@@ -70,8 +113,7 @@ RRDeleteOutputProperty (RROutputPtr output, Atom property)
 	event.atom = prop->propertyName;
 	event.timestamp = currentTime.milliseconds;
 	RRDeliverEvent (output->pScreen, (xEvent *) &event, RROutputPropertyNotifyMask);
-        xfree(prop->data);
-        xfree(prop);
+	RRDestroyOutputProperty (prop);
     }
 }
 
@@ -80,96 +122,95 @@ RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
 			int format, int mode, unsigned long len,
 			pointer value, Bool sendevent)
 {
-    PropertyPtr			    prop;
+    RRPropertyPtr		    prop;
     xRROutputPropertyNotifyEvent    event;
     int				    sizeInBytes;
     int				    totalSize;
     pointer			    data;
+    RRPropertyValuePtr		    prop_value;
+    Bool			    add = FALSE;
 
     sizeInBytes = format >> 3;
     totalSize = len * sizeInBytes;
 
     /* first see if property already exists */
-
-    for (prop = output->properties; prop; prop = prop->next)
-	if (prop->propertyName == property)
-	    break;
-    
+    prop = RRQueryOutputProperty (output, property);
     if (!prop)   /* just add to list */
     {
-        prop = (PropertyPtr)xalloc(sizeof(PropertyRec));
+        prop = RRCreateOutputProperty (property);
 	if (!prop)
 	    return(BadAlloc);
-        data = (pointer)xalloc(totalSize);
-	if (!data && len)
-	{
-	    xfree(prop);
-	    return(BadAlloc);
-	}
-        prop->propertyName = property;
-        prop->type = type;
-        prop->format = format;
-        prop->data = data;
-	if (len)
-	    memmove((char *)data, (char *)value, totalSize);
-	prop->size = len;
-        prop->next = output->properties;
-        output->properties = prop;
+	add = TRUE;
+	mode = PropModeReplace;
     }
+    if (prop->is_pending)
+	prop_value = &prop->pending;
     else
+	prop_value = &prop->current;
+    
+    /* To append or prepend to a property the request format and type
+	    must match those of the already defined property.  The
+	    existing format and type are irrelevant when using the mode
+	    "PropModeReplace" since they will be written over. */
+
+    if ((format != prop_value->format) && (mode != PropModeReplace))
+	return(BadMatch);
+    if ((prop_value->type != type) && (mode != PropModeReplace))
+	return(BadMatch);
+    if (mode == PropModeReplace)
     {
-	/* To append or prepend to a property the request format and type
-		must match those of the already defined property.  The
-		existing format and type are irrelevant when using the mode
-		"PropModeReplace" since they will be written over. */
-
-        if ((format != prop->format) && (mode != PropModeReplace))
-	    return(BadMatch);
-        if ((prop->type != type) && (mode != PropModeReplace))
-            return(BadMatch);
-        if (mode == PropModeReplace)
-        {
-	    if (totalSize != prop->size * (prop->format >> 3))
-	    {
-	    	data = (pointer)xrealloc(prop->data, totalSize);
-	    	if (!data && len)
-		    return(BadAlloc);
-            	prop->data = data;
-	    }
-	    if (len)
-		memmove((char *)prop->data, (char *)value, totalSize);
-	    prop->size = len;
-    	    prop->type = type;
-	    prop->format = format;
-	}
-	else if (len == 0)
+	if (totalSize != prop_value->size * (prop_value->format >> 3))
 	{
-	    /* do nothing */
-	}
-        else if (mode == PropModeAppend)
-        {
-	    data = (pointer)xrealloc(prop->data,
-				     sizeInBytes * (len + prop->size));
-	    if (!data)
-		return(BadAlloc);
-            prop->data = data;
-	    memmove(&((char *)data)[prop->size * sizeInBytes], 
-		    (char *)value,
-		  totalSize);
-            prop->size += len;
-	}
-        else if (mode == PropModePrepend)
-        {
-            data = (pointer)xalloc(sizeInBytes * (len + prop->size));
-	    if (!data)
+	    if (prop_value->data)
+		data = (pointer)xrealloc(prop_value->data, totalSize);
+	    else
+		data = (pointer)xalloc (totalSize);
+	    if (!data && len)
+	    {
+		if (add)
+		    RRDestroyOutputProperty (prop);
 		return(BadAlloc);
-	    memmove(&((char *)data)[totalSize], (char *)prop->data, 
-		  (int)(prop->size * sizeInBytes));
-            memmove((char *)data, (char *)value, totalSize);
-	    xfree(prop->data);
-            prop->data = data;
-            prop->size += len;
+	    }
+	    prop_value->data = data;
 	}
+	if (len)
+	    memmove((char *)prop_value->data, (char *)value, totalSize);
+	prop_value->size = len;
+	prop_value->type = type;
+	prop_value->format = format;
+    }
+    else if (len == 0)
+    {
+	/* do nothing */
+    }
+    else if (mode == PropModeAppend)
+    {
+	data = (pointer)xrealloc(prop_value->data,
+				 sizeInBytes * (len + prop_value->size));
+	if (!data)
+	    return(BadAlloc);
+	prop_value->data = data;
+	memmove(&((char *)data)[prop_value->size * sizeInBytes], 
+		(char *)value,
+	      totalSize);
+	prop_value->size += len;
+    }
+    else if (mode == PropModePrepend)
+    {
+	data = (pointer)xalloc(sizeInBytes * (len + prop_value->size));
+	if (!data)
+	    return(BadAlloc);
+	memmove(&((char *)data)[totalSize], (char *)prop_value->data, 
+	      (int)(prop_value->size * sizeInBytes));
+	memmove((char *)data, (char *)value, totalSize);
+	xfree(prop_value->data);
+	prop_value->data = data;
+	prop_value->size += len;
+    }
+    if (add)
+    {
+	prop->next = output->properties;
+	output->properties = prop;
     }
     if (sendevent)
     {
@@ -184,6 +225,81 @@ RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
     return(Success);
 }
 
+RRPropertyPtr
+RRQueryOutputProperty (RROutputPtr output, Atom property)
+{
+    RRPropertyPtr   prop;
+    
+    for (prop = output->properties; prop; prop = prop->next)
+	if (prop->propertyName == property)
+	    return prop;
+    return NULL;
+}
+		       
+RRPropertyValuePtr
+RRGetOutputProperty (RROutputPtr output, Atom property, Bool pending)
+{
+    RRPropertyPtr   prop = RRQueryOutputProperty (output, property);
+
+    if (!prop)
+	return NULL;
+    if (pending && prop->is_pending)
+	return &prop->pending;
+    else
+	return &prop->current;
+}
+
+int
+RRConfigureOutputProperty (RROutputPtr output, Atom property,
+			   Bool pending, Bool range, Bool immutable,
+			   int num_values, INT32 *values)
+{
+    RRPropertyPtr   prop = RRQueryOutputProperty (output, property);
+    Bool	    add = FALSE;
+    INT32	    *new_values;
+
+    if (!prop)
+    {
+        prop = RRCreateOutputProperty (property);
+	if (!prop)
+	    return(BadAlloc);
+	add = TRUE;
+    } else if (prop->immutable && !immutable)
+	return(BadAccess);
+    
+    /*
+     * ranges must have even number of values
+     */
+    if (range && (num_values & 1))
+	return BadMatch;
+
+    new_values = xalloc (num_values * sizeof (INT32));
+    if (!new_values && num_values)
+	return BadAlloc;
+    if (num_values)
+	memcpy (new_values, values, num_values * sizeof (INT32));
+    
+    /*
+     * Property moving from pending to non-pending
+     * loses any pending values
+     */
+    if (prop->is_pending && !pending)
+    {
+	if (prop->pending.data)
+	    xfree (prop->pending.data);
+	RRInitOutputPropertyValue (&prop->pending);
+    }
+
+    prop->is_pending = pending;
+    prop->range = range;
+    prop->immutable = immutable;
+    prop->num_valid = num_values;
+    if (prop->valid_values)
+	xfree (prop->valid_values);
+    prop->valid_values = new_values;
+    return Success;
+}
+
 int
 ProcRRListOutputProperties (ClientPtr client)
 {
@@ -192,7 +308,7 @@ ProcRRListOutputProperties (ClientPtr client)
     xRRListOutputPropertiesReply    rep;
     int				    numProps = 0;
     RROutputPtr			    output;
-    PropertyPtr			    prop;
+    RRPropertyPtr			    prop;
     
     REQUEST_SIZE_MATCH(xRRListOutputPropertiesReq);
 
@@ -211,6 +327,12 @@ ProcRRListOutputProperties (ClientPtr client)
     rep.nProperties = numProps;
     rep.length = (numProps * sizeof(Atom)) >> 2;
     rep.sequenceNumber = client->sequence;
+    if (client->swapped) 
+    {
+	int n;
+	swaps (&rep.sequenceNumber, n);
+	swapl (&rep.length, n);
+    }
     temppAtoms = pAtoms;
     for (prop = output->properties; prop; prop = prop->next)
 	*temppAtoms++ = prop->propertyName;
@@ -226,6 +348,68 @@ ProcRRListOutputProperties (ClientPtr client)
 }
 
 int
+ProcRRQueryOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRQueryOutputPropertyReq);
+    xRRQueryOutputPropertyReply	    rep;
+    RROutputPtr			    output;
+    RRPropertyPtr		    prop;
+    
+    REQUEST_SIZE_MATCH(xRRQueryOutputPropertyReq);
+
+    output = LookupOutput (client, stuff->output, SecurityReadAccess);
+    
+    if (!output)
+        return RRErrorBase + BadRROutput;
+    
+    prop = RRQueryOutputProperty (output, stuff->property);
+    if (!prop)
+	return BadName;
+    
+    rep.type = X_Reply;
+    rep.length = prop->num_valid;
+    rep.sequenceNumber = client->sequence;
+    rep.pending = prop->is_pending;
+    rep.range = prop->range;
+    rep.immutable = prop->immutable;
+    if (client->swapped) 
+    {
+	int n;
+	swaps (&rep.sequenceNumber, n);
+	swapl (&rep.length, n);
+    }
+    WriteReplyToClient (client, sizeof (xRRQueryOutputPropertyReply), &rep);
+    if (prop->num_valid)
+    {
+        client->pSwapReplyFunc = (ReplySwapPtr)Swap32Write;
+        WriteSwappedDataToClient(client, prop->num_valid * sizeof(INT32),
+				 prop->valid_values);
+    }
+    return(client->noClientException);
+}
+
+int
+ProcRRConfigureOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRConfigureOutputPropertyReq);
+    RROutputPtr				output;
+    int					num_valid;
+    
+    REQUEST_SIZE_MATCH(xRRConfigureOutputPropertyReq);
+
+    output = LookupOutput (client, stuff->output, SecurityReadAccess);
+    
+    if (!output)
+        return RRErrorBase + BadRROutput;
+    
+    num_valid = stuff->length - (sizeof (xRRConfigureOutputPropertyReq) >> 2);
+    return RRConfigureOutputProperty (output, stuff->property,
+				      stuff->pending, stuff->range,
+				      FALSE, num_valid, 
+				      (INT32 *) (stuff + 1));
+}
+
+int
 ProcRRChangeOutputProperty (ClientPtr client)
 {
     REQUEST(xRRChangeOutputPropertyReq);
@@ -309,7 +493,8 @@ int
 ProcRRGetOutputProperty (ClientPtr client)
 {
     REQUEST(xRRGetOutputPropertyReq);
-    PropertyPtr			prop, *prev;
+    RRPropertyPtr			prop, *prev;
+    RRPropertyValuePtr			prop_value;
     unsigned long		n, len, ind;
     RROutputPtr			output;
     xRRGetOutputPropertyReply	reply;
@@ -356,18 +541,26 @@ ProcRRGetOutputProperty (ClientPtr client)
 	return(client->noClientException);
     }
 
+    if (prop->immutable && stuff->delete)
+	return BadAccess;
+
+    if (stuff->pending && prop->is_pending)
+	prop_value = &prop->pending;
+    else
+	prop_value = &prop->current;
+    
     /* If the request type and actual type don't match. Return the
     property information, but not the data. */
 
-    if (((stuff->type != prop->type) &&
+    if (((stuff->type != prop_value->type) &&
 	 (stuff->type != AnyPropertyType))
        )
     {
-	reply.bytesAfter = prop->size;
-	reply.format = prop->format;
+	reply.bytesAfter = prop_value->size;
+	reply.format = prop_value->format;
 	reply.length = 0;
 	reply.nItems = 0;
-	reply.propertyType = prop->type;
+	reply.propertyType = prop_value->type;
 	WriteReplyToClient(client, sizeof(xRRGetOutputPropertyReply), &reply);
 	return(client->noClientException);
     }
@@ -375,7 +568,7 @@ ProcRRGetOutputProperty (ClientPtr client)
 /*
  *  Return type, format, value to client
  */
-    n = (prop->format/8) * prop->size; /* size (bytes) of prop */
+    n = (prop_value->format/8) * prop_value->size; /* size (bytes) of prop */
     ind = stuff->longOffset << 2;        
 
    /* If longOffset is invalid such that it causes "len" to
@@ -390,10 +583,10 @@ ProcRRGetOutputProperty (ClientPtr client)
     len = min(n - ind, 4 * stuff->longLength);
 
     reply.bytesAfter = n - (ind + len);
-    reply.format = prop->format;
+    reply.format = prop_value->format;
     reply.length = (len + 3) >> 2;
-    reply.nItems = len / (prop->format / 8 );
-    reply.propertyType = prop->type;
+    reply.nItems = len / (prop_value->format / 8 );
+    reply.propertyType = prop_value->type;
 
     if (stuff->delete && (reply.bytesAfter == 0))
     {
@@ -417,14 +610,13 @@ ProcRRGetOutputProperty (ClientPtr client)
 	default: client->pSwapReplyFunc = (ReplySwapPtr)WriteToClient; break;
 	}
 	WriteSwappedDataToClient(client, len,
-				 (char *)prop->data + ind);
+				 (char *)prop_value->data + ind);
     }
 
     if (stuff->delete && (reply.bytesAfter == 0))
     { /* delete the Property */
 	*prev = prop->next;
-	xfree(prop->data);
-	xfree(prop);
+	RRDestroyOutputProperty (prop);
     }
     return(client->noClientException);
 }
diff --git a/randr/rrsdispatch.c b/randr/rrsdispatch.c
index 67af753..4a6a6e4 100644
--- a/randr/rrsdispatch.c
+++ b/randr/rrsdispatch.c
@@ -132,6 +132,26 @@ SProcRRListOutputProperties (ClientPtr client)
 }
 
 static int
+SProcRRQueryOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRQueryOutputPropertyReq);
+    
+    REQUEST_SIZE_MATCH(xRRQueryOutputPropertyReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRConfigureOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRConfigureOutputPropertyReq);
+    
+    REQUEST_SIZE_MATCH(xRRConfigureOutputPropertyReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
 SProcRRChangeOutputProperty (ClientPtr client)
 {
     REQUEST(xRRChangeOutputPropertyReq);
@@ -267,17 +287,19 @@ int (*SProcRandrVector[RRNumberRequests])(ClientPtr) = {
     SProcRRGetScreenResources,	/* 8 */
     SProcRRGetOutputInfo,	/* 9 */
     SProcRRListOutputProperties,/* 10 */
-    SProcRRChangeOutputProperty,/* 11 */
-    SProcRRDeleteOutputProperty,/* 12 */
-    SProcRRGetOutputProperty,	/* 13 */
-    SProcRRCreateMode,		/* 14 */
-    SProcRRDestroyMode,		/* 15 */
-    SProcRRAddOutputMode,	/* 16 */
-    SProcRRDeleteOutputMode,	/* 17 */
-    SProcRRGetCrtcInfo,		/* 18 */
-    SProcRRSetCrtcConfig,	/* 19 */
-    SProcRRGetCrtcGammaSize,	/* 20 */
-    SProcRRGetCrtcGamma,	/* 21 */
-    SProcRRSetCrtcGamma,	/* 22 */
+    SProcRRQueryOutputProperty,	/* 11 */
+    SProcRRConfigureOutputProperty,  /* 12 */
+    SProcRRChangeOutputProperty,/* 13 */
+    SProcRRDeleteOutputProperty,/* 14 */
+    SProcRRGetOutputProperty,	/* 15 */
+    SProcRRCreateMode,		/* 16 */
+    SProcRRDestroyMode,		/* 17 */
+    SProcRRAddOutputMode,	/* 18 */
+    SProcRRDeleteOutputMode,	/* 19 */
+    SProcRRGetCrtcInfo,		/* 20 */
+    SProcRRSetCrtcConfig,	/* 21 */
+    SProcRRGetCrtcGammaSize,	/* 22 */
+    SProcRRGetCrtcGamma,	/* 23 */
+    SProcRRSetCrtcGamma,	/* 24 */
 };
 
commit 2953ef0c049faa55e44d741f30ff0ee5510bb7be
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Fri Nov 17 09:47:58 2006 -0800

    Add mipmap.c to GL/mesa/main/Makefile to build with mesa master

diff --git a/GL/mesa/main/Makefile.am b/GL/mesa/main/Makefile.am
index 4d5b0cd..64b383d 100644
--- a/GL/mesa/main/Makefile.am
+++ b/GL/mesa/main/Makefile.am
@@ -60,6 +60,7 @@ nodist_libmain_la_SOURCES = accum.c \
                     light.c \
                     lines.c \
                     matrix.c \
+                    mipmap.c \
                     mm.c \
                     occlude.c \
                     pixel.c \
commit b5aa9eb8e6eda36856a075f4b008c33f6c706bad
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Thu Nov 16 13:50:48 2006 -0800

    Reduce calls to RRGetInfo.
    
    RRGetInfo can be expensive. Don't invoke it when quering Xinerama
    information or setting a new CRTC configuration.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index c945468..b81c390 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -632,13 +632,6 @@ ProcRRSetCrtcConfig (ClientPtr client)
     pScreen = crtc->pScreen;
     pScrPriv = rrGetScrPriv(pScreen);
     
-    if (!RRGetInfo (pScreen))
-    {
-	if (outputs)
-	    xfree (outputs);
-	return BadAlloc;
-    }
-    
     time = ClientTimeToServerTime(stuff->timestamp);
     configTime = ClientTimeToServerTime(stuff->configTimestamp);
     
diff --git a/randr/rrxinerama.c b/randr/rrxinerama.c
index a8e4b39..771ed09 100644
--- a/randr/rrxinerama.c
+++ b/randr/rrxinerama.c
@@ -260,7 +260,11 @@ ProcRRXineramaQueryScreens(ClientPtr client)
     REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
 
     if (RRXineramaScreenActive (pScreen))
-	RRGetInfo (pScreen);
+    {
+	rrScrPriv(pScreen);
+	if (pScrPriv->numCrtcs == 0 || pScrPriv->numOutputs == 0)
+	    RRGetInfo (pScreen);
+    }
     
     rep.type = X_Reply;
     rep.sequenceNumber = client->sequence;
commit 8b2a7e94a1dc2776ab2cfaaebb309be02502602a
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Thu Nov 16 09:48:33 2006 -0800

    Remove RandR output options.
    
    RandR output options are now expected to be handled by properties instead.

diff --git a/randr/mirandr.c b/randr/mirandr.c
index 3f56fe4..3a99bf9 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -52,7 +52,7 @@ miRRCrtcSet (ScreenPtr	pScreen,
 	     int	y,
 	     Rotation	rotation,
 	     int	numOutput,
-	     RROutputConfigPtr    outputs)
+	     RROutputPtr *outputs)
 {
     return TRUE;
 }
@@ -137,10 +137,6 @@ miRandRInit (ScreenPtr pScreen)
 	return FALSE;
     if (!RROutputSetCrtcs (output, &crtc, 1))
 	return FALSE;
-    if (!RROutputSetPossibleOptions (output, 0))
-	return FALSE;
-    if (!RROutputSetCurrentOptions (output, 0))
-	return FALSE;
     if (!RROutputSetConnection (output, RR_Connected))
 	return FALSE;
     RRCrtcNotify (crtc, mode, 0, 0, RR_Rotate_0, 1, &output);
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 2c3e0e7..19af9b9 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -72,7 +72,6 @@ extern int (*SProcRandrVector[RRNumberRequests])(ClientPtr);
 typedef struct _rrMode	    RRModeRec, *RRModePtr;
 typedef struct _rrCrtc	    RRCrtcRec, *RRCrtcPtr;
 typedef struct _rrOutput    RROutputRec, *RROutputPtr;
-typedef struct _rrOutputConfig	RROutputConfigRec, *RROutputConfigPtr;
 
 struct _rrMode {
     int		    refcnt;
@@ -109,8 +108,6 @@ struct _rrOutput {
     int		    mmWidth;
     int		    mmHeight;
     RRCrtcPtr	    crtc;
-    CARD32	    currentOptions;
-    CARD32	    possibleOptions;
     int		    numCrtcs;
     RRCrtcPtr	    *crtcs;
     int		    numClones;
@@ -123,11 +120,6 @@ struct _rrOutput {
     void	    *devPrivate;
 };
 
-struct _rrOutputConfig {
-    RROutputPtr	    output;
-    CARD32	    options;
-};
-
 #if RANDR_12_INTERFACE
 typedef Bool (*RRScreenSetSizeProcPtr) (ScreenPtr	pScreen,
 					CARD16		width,
@@ -142,7 +134,7 @@ typedef Bool (*RRCrtcSetProcPtr) (ScreenPtr		pScreen,
 				  int			y,
 				  Rotation		rotation,
 				  int			numOutputs,
-				  RROutputConfigPtr	outputs);
+				  RROutputPtr		*outputs);
 
 typedef Bool (*RRCrtcSetGammaProcPtr) (ScreenPtr	pScreen,
 				       RRCrtcPtr	crtc);
@@ -369,7 +361,7 @@ miRRCrtcSet (ScreenPtr	pScreen,
 	     int	y,
 	     Rotation	rotation,
 	     int	numOutput,
-	     RROutputConfigPtr    outputs);
+	     RROutputPtr *outputs);
 
 /* randr.c */
 /*
@@ -490,7 +482,7 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	   int		y,
 	   Rotation	rotation,
 	   int		numOutput,
-	   RROutputConfigPtr  outputs);
+	   RROutputPtr  *outputs);
 
 /*
  * Request that the Crtc gamma be changed
@@ -641,10 +633,6 @@ RROutputSetCrtcs (RROutputPtr	output,
 		  RRCrtcPtr	*crtcs,
 		  int		numCrtcs);
 
-Bool
-RROutputSetPossibleOptions (RROutputPtr	output,
-			    CARD32	possibleOptions);
-
 void
 RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc);
     
@@ -657,10 +645,6 @@ RROutputSetSubpixelOrder (RROutputPtr output,
 			  int	      subpixelOrder);
 
 Bool
-RROutputSetCurrentOptions (RROutputPtr output,
-			   CARD32      currentOptions);
-
-Bool
 RROutputSetPhysicalSize (RROutputPtr	output,
 			 int		mmWidth,
 			 int		mmHeight);
@@ -739,8 +723,6 @@ Query state:
 		RRScreenSetSizeRange
 		RROutputSetCrtcs
 		RROutputSetCrtc
-		RROutputSetPossibleOptions
-		RRSetCurrentOptions
 		RRModeGet
 		RROutputSetModes
 		RROutputSetConnection
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 9f7177a..c945468 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -257,7 +257,7 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	   int		y,
 	   Rotation	rotation,
 	   int		numOutputs,
-	   RROutputConfigPtr  outputs)
+	   RROutputPtr  *outputs)
 {
     ScreenPtr	pScreen = crtc->pScreen;
 
@@ -290,10 +290,10 @@ RRCrtcSet (RRCrtcPtr    crtc,
 
 	    size.width = mode->mode.width;
 	    size.height = mode->mode.height;
-	    if (outputs[0].output->mmWidth && outputs[0].output->mmHeight)
+	    if (outputs[0]->mmWidth && outputs[0]->mmHeight)
 	    {
-		size.mmWidth = outputs[0].output->mmWidth;
-		size.mmHeight = outputs[0].output->mmHeight;
+		size.mmWidth = outputs[0]->mmWidth;
+		size.mmHeight = outputs[0]->mmHeight;
 	    }
 	    else
 	    {
@@ -308,7 +308,7 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	     * Old 1.0 interface tied screen size to mode size
 	     */
 	    if (ret)
-		RRCrtcNotify (crtc, mode, x, y, rotation, 1, &outputs[0].output);
+		RRCrtcNotify (crtc, mode, x, y, rotation, 1, outputs);
 	    return ret;
 	}
 #endif
@@ -554,15 +554,15 @@ ProcRRSetCrtcConfig (ClientPtr client)
     RRCrtcPtr		    crtc;
     RRModePtr		    mode;
     int			    numOutputs;
-    RROutputConfigPtr	    outputs = NULL;
-    xRROutputConfig 	    *outputConfigs;
+    RROutputPtr		    *outputs = NULL;
+    RROutput		    *outputIds;
     TimeStamp		    configTime;
     TimeStamp		    time;
     Rotation		    rotation;
     int			    i, j;
     
     REQUEST_AT_LEAST_SIZE(xRRSetCrtcConfigReq);
-    numOutputs = (stuff->length - (SIZEOF (xRRSetCrtcConfigReq) >> 2)) >> 1;
+    numOutputs = (stuff->length - (SIZEOF (xRRSetCrtcConfigReq) >> 2));
     
     crtc = LookupIDByType (stuff->crtc, RRCrtcType);
     if (!crtc)
@@ -589,47 +589,39 @@ ProcRRSetCrtcConfig (ClientPtr client)
     }
     if (numOutputs)
     {
-	outputs = xalloc (numOutputs * sizeof (RROutputConfigRec));
+	outputs = xalloc (numOutputs * sizeof (RROutputPtr));
 	if (!outputs)
 	    return BadAlloc;
     }
     else
 	outputs = NULL;
     
-    outputConfigs = (xRROutputConfig *) (stuff + 1);
+    outputIds = (RROutput *) (stuff + 1);
     for (i = 0; i < numOutputs; i++)
     {
-	outputs[i].output = LookupIDByType (outputConfigs[i].output, RROutputType);
-	if (!outputs[i].output)
+	outputs[i] = (RROutputPtr) LookupIDByType (outputIds[i], RROutputType);
+	if (!outputs[i])
 	{
-	    client->errorValue = outputConfigs[i].output;
+	    client->errorValue = outputIds[i];
 	    if (outputs)
 		xfree (outputs);
 	    return RRErrorBase + BadRROutput;
 	}
-	outputs[i].options = outputConfigs[i].options;
-	if (outputs[i].options & ~outputs[i].output->possibleOptions)
-	{
-	    client->errorValue = outputConfigs[i].options;
-	    if (outputs)
-		xfree (outputs);
-	    return BadMatch;
-	}
 	/* validate crtc for this output */
-	for (j = 0; j < outputs[i].output->numCrtcs; j++)
-	    if (outputs[i].output->crtcs[j] == crtc)
+	for (j = 0; j < outputs[i]->numCrtcs; j++)
+	    if (outputs[i]->crtcs[j] == crtc)
 		break;
-	if (j == outputs[i].output->numCrtcs)
+	if (j == outputs[i]->numCrtcs)
 	{
 	    if (outputs)
 		xfree (outputs);
 	    return BadMatch;
 	}
 	/* validate mode for this output */
-	for (j = 0; j < outputs[i].output->numModes; j++)
-	    if (outputs[i].output->modes[j] == mode)
+	for (j = 0; j < outputs[i]->numModes; j++)
+	    if (outputs[i]->modes[j] == mode)
 		break;
-	if (j == outputs[i].output->numModes)
+	if (j == outputs[i]->numModes)
 	{
 	    if (outputs)
 		xfree (outputs);
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 102587b..8b760ec 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -65,8 +65,6 @@ RROutputCreate (const char  *name,
     output->mmWidth = 0;
     output->mmHeight = 0;
     output->crtc = NULL;
-    output->currentOptions = 0;
-    output->possibleOptions = 0;
     output->numCrtcs = 0;
     output->crtcs = NULL;
     output->numClones = 0;
@@ -223,17 +221,6 @@ RROutputSetCrtcs (RROutputPtr	output,
     return TRUE;
 }
 
-Bool
-RROutputSetPossibleOptions (RROutputPtr	output,
-			    CARD32	possibleOptions)
-{
-    if (output->possibleOptions == possibleOptions)
-	return TRUE;
-    output->possibleOptions = possibleOptions;
-    RROutputChanged (output);
-    return TRUE;
-}
-
 void
 RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc)
 {
@@ -267,17 +254,6 @@ RROutputSetSubpixelOrder (RROutputPtr output,
 }
 
 Bool
-RROutputSetCurrentOptions (RROutputPtr output,
-			   CARD32      currentOptions)
-{
-    if (output->currentOptions == currentOptions)
-	return TRUE;
-    output->currentOptions = currentOptions;
-    RROutputChanged (output);
-    return TRUE;
-}
-
-Bool
 RROutputSetPhysicalSize (RROutputPtr	output,
 			 int		mmWidth,
 			 int		mmHeight)
@@ -413,7 +389,6 @@ ProcRRGetOutputInfo (ClientPtr client)
     rep.length = OutputInfoExtra >> 2;
     rep.timestamp = pScrPriv->lastSetTime.milliseconds;
     rep.crtc = output->crtc ? output->crtc->id : None;
-    rep.currentOptions = output->currentOptions;
     rep.mmWidth = output->mmWidth;
     rep.mmHeight = output->mmHeight;
     rep.connection = output->connection;
@@ -423,7 +398,6 @@ ProcRRGetOutputInfo (ClientPtr client)
     rep.nPreferred = output->numPreferred;
     rep.nClones = output->numClones;
     rep.nameLength = output->nameLength;
-    rep.possibleOptions = output->possibleOptions;
     
     extraLen = ((output->numCrtcs + 
 		 output->numModes + 
@@ -469,15 +443,12 @@ ProcRRGetOutputInfo (ClientPtr client)
 	swapl(&rep.length, n);
 	swapl(&rep.timestamp, n);
 	swapl(&rep.crtc, n);
-	swapl(&rep.currentOptions, n);
 	swapl(&rep.mmWidth, n);
 	swapl(&rep.mmHeight, n);
 	swaps(&rep.nCrtcs, n);
 	swaps(&rep.nModes, n);
 	swaps(&rep.nClones, n);
-	swapl(&rep.possibleOptions, n);
 	swaps(&rep.nameLength, n);
-	swapl(&rep.possibleOptions, n);
     }
     WriteToClient(client, sizeof(xRRGetOutputInfoReply), (char *)&rep);
     if (extraLen)
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index d47e9d6..76c16b0 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -712,7 +712,7 @@ ProcRRSetScreenConfig (ClientPtr client)
     Rotation		    rotation;
     int			    rate;
     Bool		    has_rate;
-    RROutputConfigRec	    output;
+    RROutputPtr		    output;
     RRModePtr		    mode;
     RR10DataPtr		    pData = NULL;
     RRScreenSizePtr    	    pSize;
@@ -749,14 +749,13 @@ ProcRRSetScreenConfig (ClientPtr client)
     if (!RRGetInfo (pScreen))
 	return BadAlloc;
     
-    output.output = RRFirstOutput (pScreen);
-    if (!output.output)
+    output = RRFirstOutput (pScreen);
+    if (!output)
     {
 	time = currentTime;
 	rep.status = RRSetConfigFailed;
 	goto sendReply;
     }
-    output.options = output.output->currentOptions;
     
     /*
      * if the client's config timestamp is not the same as the last config
@@ -769,7 +768,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	goto sendReply;
     }
     
-    pData = RR10GetData (pScreen, output.output);
+    pData = RR10GetData (pScreen, output);
     if (!pData)
 	return BadAlloc;
     
@@ -805,7 +804,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	return BadValue;
     }
 
-    if ((~output.output->crtc->rotations) & rotation)
+    if ((~output->crtc->rotations) & rotation)
     {
 	/*
 	 * requested rotation or reflection not supported by screen
@@ -878,7 +877,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	}
     }
     
-    rep.status = RRCrtcSet (output.output->crtc, mode, 0, 0, stuff->rotation,
+    rep.status = RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation,
 			    1, &output);
     
     /*
commit ae9375ed6ba7d1c0353e4767bdfeda8dcdc8d5f6
Author: Keith Packard <keithp at mandolin.keithp.com>
Date:   Wed Nov 8 23:17:55 2006 -0800

    Add RRInit function to create resource types for RR objects.
    
    To allow RandR objects to be created before the screen object exists,
    the resource types must be registered with the resource database.
    A driver wishing to create RandR objects must call RRInit before doing so.
    
    Also, fix a segfault when setting Output data before it is associated with a
    screen.

diff --git a/randr/randr.c b/randr/randr.c
index 4426c47..147df8c 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -39,8 +39,7 @@
 #endif
 
 #define RR_VALIDATE
-int	RRGeneration;
-int	RRNScreens;
+static int	RRNScreens;
 
 #define wrap(priv,real,mem,func) {\
     priv->mem = real->mem; \
@@ -198,10 +197,10 @@ SRRNotifyEvent (xEvent *from,
     }
 }
 
-Bool RRScreenInit(ScreenPtr pScreen)
-{
-    rrScrPrivPtr   pScrPriv;
+static int RRGeneration;
 
+Bool RRInit (void)
+{
     if (RRGeneration != serverGeneration)
     {
 	if (!RRModeInit ())
@@ -210,9 +209,25 @@ Bool RRScreenInit(ScreenPtr pScreen)
 	    return FALSE;
 	if (!RROutputInit ())
 	    return FALSE;
+	RRGeneration = serverGeneration;
+    }
+    return TRUE;
+}
+
+static int RRScreenGeneration;
+
+Bool RRScreenInit(ScreenPtr pScreen)
+{
+    rrScrPrivPtr   pScrPriv;
+
+    if (!RRInit ())
+	return FALSE;
+
+    if (RRScreenGeneration != serverGeneration)
+    {
 	if ((rrPrivIndex = AllocateScreenPrivateIndex()) < 0)
 	    return FALSE;
-	RRGeneration = serverGeneration;
+	RRScreenGeneration = serverGeneration;
     }
 
     pScrPriv = (rrScrPrivPtr) xalloc (sizeof (rrScrPrivRec));
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 345418b..2c3e0e7 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -384,6 +384,8 @@ RRTellChanged (ScreenPtr pScreen);
 Bool
 RRGetInfo (ScreenPtr pScreen);
 
+Bool RRInit (void);
+
 Bool RRScreenInit(ScreenPtr pScreen);
 
 RROutputPtr
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 1b0ecab..102587b 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -31,10 +31,13 @@ void
 RROutputChanged (RROutputPtr output)
 {
     ScreenPtr	pScreen = output->pScreen;
-    rrScrPriv (pScreen);
-
+    
     output->changed = TRUE;
-    pScrPriv->changed = TRUE;
+    if (pScreen)
+    {
+	rrScrPriv (pScreen);
+	pScrPriv->changed = TRUE;
+    }
 }
 
 /*
@@ -335,17 +338,21 @@ RROutputDestroyResource (pointer value, XID pid)
 {
     RROutputPtr	output = (RROutputPtr) value;
     ScreenPtr	pScreen = output->pScreen;
-    rrScrPriv(pScreen);
-    int		i;
 
-    for (i = 0; i < pScrPriv->numOutputs; i++)
+    if (pScreen)
     {
-	if (pScrPriv->outputs[i] == output)
+	rrScrPriv(pScreen);
+	int		i;
+    
+	for (i = 0; i < pScrPriv->numOutputs; i++)
 	{
-	    memmove (pScrPriv->outputs + i, pScrPriv->outputs + i + 1,
-		     (pScrPriv->numOutputs - (i - 1)) * sizeof (RROutputPtr));
-	    --pScrPriv->numOutputs;
-	    break;
+	    if (pScrPriv->outputs[i] == output)
+	    {
+		memmove (pScrPriv->outputs + i, pScrPriv->outputs + i + 1,
+			 (pScrPriv->numOutputs - (i - 1)) * sizeof (RROutputPtr));
+		--pScrPriv->numOutputs;
+		break;
+	    }
 	}
     }
     if (output->modes)
@@ -481,4 +488,3 @@ ProcRRGetOutputInfo (ClientPtr client)
     
     return client->noClientException;
 }
-
commit 8d0ac835bca282283dd6394fda7416e62a1934c7
Author: Keith Packard <keithp at mandolin.keithp.com>
Date:   Wed Nov 8 21:36:35 2006 -0800

    Allow RandR objects to be created before the associated ScreenRec.
    
    xf86 drivers need to create RandR object in the PreInit stage,
    before the ScreenRec is allocated. Changing the RandR DIX code
    to permit this required the addition of functions that later associate the
    objects with the related screen.
    
    An additional change is that modes are now global, and no longer associated
    with a specific screen. This change actually makes mode management cleaner
    as there is no more per-screen list of modes to deal with.
    
    This changes the RandR 1.2 ABI/API for drivers.

diff --git a/hw/xfree86/common/Makefile.am b/hw/xfree86/common/Makefile.am
index d983ee9..2274527 100644
--- a/hw/xfree86/common/Makefile.am
+++ b/hw/xfree86/common/Makefile.am
@@ -54,7 +54,7 @@ sdk_HEADERS = compiler.h fourcc.h xf86.h xf86Module.h xf86Opt.h \
               xf86PciInfo.h xf86Priv.h xf86Privstr.h xf86Resources.h \
               xf86cmap.h xf86fbman.h xf86str.h $(XISDKINCS) \
               $(XVSDKINCS) atKeynames.h xf86Version.h xorgVersion.h \
-              xf86sbusBus.h xf86xv.h xf86xvmc.h xf86xvpriv.h
+              xf86sbusBus.h xf86xv.h xf86xvmc.h xf86xvpriv.h xf86Keymap.h
 
 DISTCLEANFILES = xf86Build.h
 CLEANFILES = $(BUILT_SOURCES)
diff --git a/randr/mirandr.c b/randr/mirandr.c
index 11c2991..3f56fe4 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -113,17 +113,24 @@ miRandRInit (ScreenPtr pScreen)
     modeInfo.height = pScreen->height;
     modeInfo.nameLength = strlen (name);
     
-    mode = RRModeGet (pScreen, &modeInfo, name);
+    mode = RRModeGet (&modeInfo, name);
     if (!mode)
 	return FALSE;
     
-    crtc = RRCrtcCreate (pScreen, NULL);
+    crtc = RRCrtcCreate (NULL);
     if (!crtc)
 	return FALSE;
+    if (!RRCrtcAttachScreen (crtc, pScreen))
+    {
+	RRCrtcDestroy (crtc);
+	return FALSE;
+    }
     
-    output = RROutputCreate (pScreen, "screen", 6, NULL);
+    output = RROutputCreate ("screen", 6, NULL);
     if (!output)
 	return FALSE;
+    if (!RROutputAttachScreen (output, pScreen))
+	return FALSE;
     if (!RROutputSetClones (output, NULL, 0))
 	return FALSE;
     if (!RROutputSetModes (output, &mode, 1, 0))
diff --git a/randr/randr.c b/randr/randr.c
index 7b39e80..4426c47 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -103,8 +103,6 @@ RRCloseScreen (int i, ScreenPtr pScreen)
 	RRCrtcDestroy (pScrPriv->crtcs[j]);
     for (j = pScrPriv->numOutputs - 1; j >= 0; j--)
 	RROutputDestroy (pScrPriv->outputs[j]);
-    for (j = pScrPriv->numModes - 1; j >= 0; j--)
-	RRModeDestroy (pScrPriv->modes[j]);
     
     xfree (pScrPriv);
     RRNScreens -= 1;	/* ok, one fewer screen with RandR running */
@@ -257,8 +255,6 @@ Bool RRScreenInit(ScreenPtr pScreen)
     
     wrap (pScrPriv, pScreen, CloseScreen, RRCloseScreen);
 
-    pScrPriv->numModes = 0;
-    pScrPriv->modes = NULL;
     pScrPriv->numOutputs = 0;
     pScrPriv->outputs = NULL;
     pScrPriv->numCrtcs = 0;
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 60877a3..345418b 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -79,7 +79,6 @@ struct _rrMode {
     xRRModeInfo	    mode;
     char	    *name;
     void	    *devPrivate;
-    ScreenPtr	    screen;
     Bool	    userDefined;
 };
 
@@ -210,10 +209,6 @@ typedef struct _rrScrPriv {
     CARD16		    width, height;	/* last known screen size */
     Bool		    layoutChanged;	/* screen layout changed */
 
-    /* modes, outputs and crtcs */
-    int			    numModes;
-    RRModePtr		    *modes;
-
     int			    numOutputs;
     RROutputPtr		    *outputs;
 
@@ -457,10 +452,17 @@ RRCrtcChanged (RRCrtcPtr crtc, Bool layoutChanged);
  * Create a CRTC
  */
 RRCrtcPtr
-RRCrtcCreate (ScreenPtr	pScreen,
-	      void	*devPrivate);
+RRCrtcCreate (void	*devPrivate);
 
 /*
+ * Attach a CRTC to a screen. Once done, this cannot be
+ * undone without destroying the CRTC; it is separate from Create
+ * only to allow an xf86-based driver to create objects in preinit
+ */
+Bool
+RRCrtcAttachScreen (RRCrtcPtr crtc, ScreenPtr pScreen);
+    
+/*
  * Notify the extension that the Crtc has been reconfigured,
  * the driver calls this whenever it has updated the mode
  */
@@ -556,8 +558,7 @@ RRClientKnowsRates (ClientPtr	pClient);
  */
 
 RRModePtr
-RRModeGet (ScreenPtr	pScreen,
-	   xRRModeInfo	*modeInfo,
+RRModeGet (xRRModeInfo	*modeInfo,
 	   const char	*name);
 
 void
@@ -571,6 +572,12 @@ void
 RRModeDestroy (RRModePtr mode);
 
 /*
+ * Return a list of modes that are valid for some output in pScreen
+ */
+RRModePtr *
+RRModesForScreen (ScreenPtr pScreen, int *num_ret);
+    
+/*
  * Initialize mode type
  */
 Bool
@@ -601,12 +608,19 @@ RROutputChanged (RROutputPtr output);
  */
 
 RROutputPtr
-RROutputCreate (ScreenPtr   pScreen,
-		const char  *name,
+RROutputCreate (const char  *name,
 		int	    nameLength,
 		void	    *devPrivate);
 
 /*
+ * Attach an output to a screen, again split from creation so
+ * xf86 DDXen can create randr resources before the ScreenRec
+ * exists
+ */
+Bool
+RROutputAttachScreen (RROutputPtr output, ScreenPtr pScreen);
+
+/*
  * Notify extension that output parameters have been changed
  */
 Bool
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 76d0b6b..9f7177a 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -32,43 +32,34 @@ void
 RRCrtcChanged (RRCrtcPtr crtc, Bool layoutChanged)
 {
     ScreenPtr	pScreen = crtc->pScreen;
-    rrScrPriv(pScreen);
 
     crtc->changed = TRUE;
-    pScrPriv->changed = TRUE;
-    /*
-     * Send ConfigureNotify on any layout change
-     */
-    if (layoutChanged)
-	pScrPriv->layoutChanged = TRUE;
+    if (pScreen)
+    {
+	rrScrPriv(pScreen);
+    
+	pScrPriv->changed = TRUE;
+	/*
+	 * Send ConfigureNotify on any layout change
+	 */
+	if (layoutChanged)
+	    pScrPriv->layoutChanged = TRUE;
+    }
 }
 
 /*
  * Create a CRTC
  */
 RRCrtcPtr
-RRCrtcCreate (ScreenPtr	pScreen,
-	      void	*devPrivate)
+RRCrtcCreate (void	*devPrivate)
 {
-    rrScrPriv (pScreen);
     RRCrtcPtr	crtc;
-    RRCrtcPtr	*crtcs;
     
     crtc = xalloc (sizeof (RRCrtcRec));
     if (!crtc)
 	return NULL;
-    if (pScrPriv->numCrtcs)
-	crtcs = xrealloc (pScrPriv->crtcs, 
-			  (pScrPriv->numCrtcs + 1) * sizeof (RRCrtcPtr));
-    else
-	crtcs = xalloc (sizeof (RRCrtcPtr));
-    if (!crtcs)
-    {
-	xfree (crtc);
-	return NULL;
-    }
     crtc->id = FakeClientID (0);
-    crtc->pScreen = pScreen;
+    crtc->pScreen = NULL;
     crtc->mode = NULL;
     crtc->x = 0;
     crtc->y = 0;
@@ -84,11 +75,37 @@ RRCrtcCreate (ScreenPtr	pScreen,
     if (!AddResource (crtc->id, RRCrtcType, (pointer) crtc))
 	return NULL;
 
+    return crtc;
+}
+
+/*
+ * Attach a Crtc to a screen. This is done as a separate step
+ * so that an xf86-based driver can create CRTCs in PreInit
+ * before the Screen has been created
+ */
+
+Bool
+RRCrtcAttachScreen (RRCrtcPtr crtc, ScreenPtr pScreen)
+{
+    rrScrPriv (pScreen);
+    RRCrtcPtr	*crtcs;
+
+    /* make space for the crtc pointer */
+    if (pScrPriv->numCrtcs)
+	crtcs = xrealloc (pScrPriv->crtcs, 
+			  (pScrPriv->numCrtcs + 1) * sizeof (RRCrtcPtr));
+    else
+	crtcs = xalloc (sizeof (RRCrtcPtr));
+    if (!crtcs)
+	return FALSE;
+    
+    /* attach the screen and crtc together */
+    crtc->pScreen = pScreen;
     pScrPriv->crtcs = crtcs;
     pScrPriv->crtcs[pScrPriv->numCrtcs++] = crtc;
 
     RRCrtcChanged (crtc, TRUE);
-    return crtc;
+    return TRUE;
 }
 
 /*
@@ -243,7 +260,6 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	   RROutputConfigPtr  outputs)
 {
     ScreenPtr	pScreen = crtc->pScreen;
-    rrScrPriv(pScreen);
 
     /* See if nothing changed */
     if (crtc->mode == mode &&
@@ -255,45 +271,49 @@ RRCrtcSet (RRCrtcPtr    crtc,
     {
 	return TRUE;
     }
-#if RANDR_12_INTERFACE
-    if (pScrPriv->rrCrtcSet)
-    {
-	return (*pScrPriv->rrCrtcSet) (pScreen, crtc, mode, x, y, 
-				       rotation, numOutputs, outputs);
-    }
-#endif
-#if RANDR_10_INTERFACE
-    if (pScrPriv->rrSetConfig)
+    if (pScreen)
     {
-	RRScreenSize	    size;
-	RRScreenRate	    rate;
-	Bool		    ret;
-
-	size.width = mode->mode.width;
-	size.height = mode->mode.height;
-	if (outputs[0].output->mmWidth && outputs[0].output->mmHeight)
+#if RANDR_12_INTERFACE
+	rrScrPriv(pScreen);
+	if (pScrPriv->rrCrtcSet)
 	{
-	    size.mmWidth = outputs[0].output->mmWidth;
-	    size.mmHeight = outputs[0].output->mmHeight;
+	    return (*pScrPriv->rrCrtcSet) (pScreen, crtc, mode, x, y, 
+					   rotation, numOutputs, outputs);
 	}
-	else
+#endif
+#if RANDR_10_INTERFACE
+	if (pScrPriv->rrSetConfig)
 	{
-	    size.mmWidth = pScreen->mmWidth;
-	    size.mmHeight = pScreen->mmHeight;
+	    RRScreenSize	    size;
+	    RRScreenRate	    rate;
+	    Bool		    ret;
+
+	    size.width = mode->mode.width;
+	    size.height = mode->mode.height;
+	    if (outputs[0].output->mmWidth && outputs[0].output->mmHeight)
+	    {
+		size.mmWidth = outputs[0].output->mmWidth;
+		size.mmHeight = outputs[0].output->mmHeight;
+	    }
+	    else
+	    {
+		size.mmWidth = pScreen->mmWidth;
+		size.mmHeight = pScreen->mmHeight;
+	    }
+	    size.nRates = 1;
+	    rate.rate = RRVerticalRefresh (&mode->mode);
+	    size.pRates = &rate;
+	    ret = (*pScrPriv->rrSetConfig) (pScreen, rotation, rate.rate, &size);
+	    /*
+	     * Old 1.0 interface tied screen size to mode size
+	     */
+	    if (ret)
+		RRCrtcNotify (crtc, mode, x, y, rotation, 1, &outputs[0].output);
+	    return ret;
 	}
-	size.nRates = 1;
-	rate.rate = RRVerticalRefresh (&mode->mode);
-	size.pRates = &rate;
-	ret = (*pScrPriv->rrSetConfig) (pScreen, rotation, rate.rate, &size);
-	/*
-	 * Old 1.0 interface tied screen size to mode size
-	 */
-	if (ret)
-	    RRCrtcNotify (crtc, mode, x, y, rotation, 1, &outputs[0].output);
-	return ret;
-    }
 #endif
-    RRTellChanged (pScreen);
+	RRTellChanged (pScreen);
+    }
     return FALSE;
 }
 
@@ -311,22 +331,26 @@ RRCrtcDestroyResource (pointer value, XID pid)
 {
     RRCrtcPtr	crtc = (RRCrtcPtr) value;
     ScreenPtr	pScreen = crtc->pScreen;
-    rrScrPriv(pScreen);
-    int		i;
 
-    for (i = 0; i < pScrPriv->numCrtcs; i++)
+    if (pScreen)
     {
-	if (pScrPriv->crtcs[i] == crtc)
+	rrScrPriv(pScreen);
+	int		i;
+    
+	for (i = 0; i < pScrPriv->numCrtcs; i++)
 	{
-	    memmove (pScrPriv->crtcs + i, pScrPriv->crtcs + i + 1,
-		     (pScrPriv->numCrtcs - (i - 1)) * sizeof (RRCrtcPtr));
-	    --pScrPriv->numCrtcs;
-	    break;
+	    if (pScrPriv->crtcs[i] == crtc)
+	    {
+		memmove (pScrPriv->crtcs + i, pScrPriv->crtcs + i + 1,
+			 (pScrPriv->numCrtcs - (i - 1)) * sizeof (RRCrtcPtr));
+		--pScrPriv->numCrtcs;
+		break;
+	    }
 	}
     }
     if (crtc->gammaRed)
 	xfree (crtc->gammaRed);
-    xfree (value);
+    xfree (crtc);
     return 1;
 }
 
@@ -343,15 +367,18 @@ RRCrtcGammaSet (RRCrtcPtr   crtc,
     Bool	ret = TRUE;
 #if RANDR_12_INTERFACE
     ScreenPtr	pScreen = crtc->pScreen;
-    rrScrPriv(pScreen);
 #endif
     
     memcpy (crtc->gammaRed, red, crtc->gammaSize * sizeof (CARD16));
     memcpy (crtc->gammaGreen, green, crtc->gammaSize * sizeof (CARD16));
     memcpy (crtc->gammaBlue, blue, crtc->gammaSize * sizeof (CARD16));
 #if RANDR_12_INTERFACE
-    if (pScrPriv->rrCrtcSetGamma)
-	ret = (*pScrPriv->rrCrtcSetGamma) (pScreen, crtc);
+    if (pScreen)
+    {
+	rrScrPriv(pScreen);
+	if (pScrPriv->rrCrtcSetGamma)
+	    ret = (*pScrPriv->rrCrtcSetGamma) (pScreen, crtc);
+    }
 #endif
     return ret;
 }
@@ -433,6 +460,9 @@ ProcRRGetCrtcInfo (ClientPtr client)
     if (!crtc)
 	return RRErrorBase + BadRRCrtc;
 
+    /* All crtcs must be associated with screens before client
+     * requests are processed
+     */
     pScreen = crtc->pScreen;
     pScrPriv = rrGetScrPriv(pScreen);
 
@@ -589,7 +619,7 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	for (j = 0; j < outputs[i].output->numCrtcs; j++)
 	    if (outputs[i].output->crtcs[j] == crtc)
 		break;
-	if (j == outputs[j].output->numCrtcs)
+	if (j == outputs[i].output->numCrtcs)
 	{
 	    if (outputs)
 		xfree (outputs);
diff --git a/randr/rrinfo.c b/randr/rrinfo.c
index e92caad..244b089 100644
--- a/randr/rrinfo.c
+++ b/randr/rrinfo.c
@@ -44,7 +44,7 @@ RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
     modeInfo.dotClock = ((CARD32) size->width * (CARD32) size->height *
 			 (CARD32) refresh);
     modeInfo.nameLength = strlen (name);
-    mode = RRModeGet (pScreen, &modeInfo, name);
+    mode = RRModeGet (&modeInfo, name);
     if (!mode)
 	return NULL;
     for (i = 0; i < output->numModes; i++)
@@ -90,12 +90,19 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
     if (pScrPriv->numOutputs == 0 &&
 	pScrPriv->numCrtcs == 0)
     {
-	crtc = RRCrtcCreate (pScreen, NULL);
+	crtc = RRCrtcCreate (NULL);
 	if (!crtc)
 	    return;
-	output = RROutputCreate (pScreen, "default", 7, NULL);
+	if (!RRCrtcAttachScreen (crtc, pScreen))
+	{
+	    RRCrtcDestroy (crtc);
+	    return;
+	}
+	output = RROutputCreate ("default", 7, NULL);
 	if (!output)
 	    return;
+	if (!RROutputAttachScreen (output, pScreen))
+	    return;
 	RROutputSetCrtcs (output, &crtc, 1);
 	RROutputSetCrtc (output, crtc);
 	RROutputSetConnection (output, RR_Connected);
@@ -206,7 +213,6 @@ RRGetInfo (ScreenPtr pScreen)
     if (pScrPriv->nSizes)
 	RRScanOldConfig (pScreen, rotations);
 #endif
-    RRModePruneUnused (pScreen);
     RRTellChanged (pScreen);
     return TRUE;
 }
diff --git a/randr/rrmode.c b/randr/rrmode.c
index fb4b5eb..3cd9ef2 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -42,19 +42,23 @@ RRModeEqual (xRRModeInfo *a, xRRModeInfo *b)
     return TRUE;
 }
 
+/*
+ * Keep a list so it's easy to find modes in the resource database.
+ */
+static int	    num_modes;
+static RRModePtr    *modes;
+
 RRModePtr
-RRModeGet (ScreenPtr	pScreen,
-	   xRRModeInfo	*modeInfo,
+RRModeGet (xRRModeInfo	*modeInfo,
 	   const char	*name)
 {
-    rrScrPriv (pScreen);
     int	i;
     RRModePtr	mode;
-    RRModePtr	*modes;
+    RRModePtr	*newModes;
 
-    for (i = 0; i < pScrPriv->numModes; i++)
+    for (i = 0; i < num_modes; i++)
     {
-	mode = pScrPriv->modes[i];
+	mode = modes[i];
 	if (RRModeEqual (&mode->mode, modeInfo) &&
 	    !memcmp (name, mode->name, modeInfo->nameLength))
 	{
@@ -71,16 +75,14 @@ RRModeGet (ScreenPtr	pScreen,
     mode->name = (char *) (mode + 1);
     memcpy (mode->name, name, modeInfo->nameLength);
     mode->name[modeInfo->nameLength] = '\0';
-    mode->screen = pScreen;
     mode->userDefined = FALSE;
 
-    if (pScrPriv->numModes)
-	modes = xrealloc (pScrPriv->modes,
-			  (pScrPriv->numModes + 1) * sizeof (RRModePtr));
+    if (num_modes)
+	newModes = xrealloc (modes, (num_modes + 1) * sizeof (RRModePtr));
     else
-	modes = xalloc (sizeof (RRModePtr));
+	newModes = xalloc (sizeof (RRModePtr));
 
-    if (!modes)
+    if (!newModes)
     {
 	xfree (mode);
 	return NULL;
@@ -89,37 +91,64 @@ RRModeGet (ScreenPtr	pScreen,
     mode->mode.id = FakeClientID(0);
     if (!AddResource (mode->mode.id, RRModeType, (pointer) mode))
 	return NULL;
+    modes = newModes;
+    modes[num_modes++] = mode;
+    
+    /*
+     * give the caller a reference to this mode
+     */
     ++mode->refcnt;
-    pScrPriv->modes = modes;
-    pScrPriv->modes[pScrPriv->numModes++] = mode;
-    pScrPriv->changed = TRUE;
     return mode;
 }
 
+RRModePtr *
+RRModesForScreen (ScreenPtr pScreen, int *num_ret)
+{
+    rrScrPriv(pScreen);
+    int	o;
+    RRModePtr	*screen_modes;
+    int		num_screen_modes = 0;
+
+    screen_modes = xalloc ((num_modes ? num_modes : 1) * sizeof (RRModePtr));
+    
+    for (o = 0; o < pScrPriv->numOutputs; o++)
+    {
+	RROutputPtr	output = pScrPriv->outputs[o];
+	int		m, n;
+
+	for (m = 0; m < output->numModes; m++)
+	{
+	    RRModePtr	mode = output->modes[m];
+	    for (n = 0; n < num_screen_modes; n++)
+		if (screen_modes[n] == mode)
+		    break;
+	    if (n == num_screen_modes)
+		screen_modes[num_screen_modes++] = mode;
+	}
+    }
+    *num_ret = num_screen_modes;
+    return screen_modes;
+}
+
 void
 RRModeDestroy (RRModePtr mode)
 {
-    ScreenPtr	    pScreen;
-    rrScrPrivPtr    pScrPriv;
     int	m;
     
     if (--mode->refcnt > 0)
 	return;
-    pScreen = mode->screen;
-    pScrPriv = rrGetScrPriv (pScreen);
-    for (m = 0; m < pScrPriv->numModes; m++)
+    for (m = 0; m < num_modes; m++)
     {
-	if (pScrPriv->modes[m] == mode)
+	if (modes[m] == mode)
 	{
-	    memmove (pScrPriv->modes + m, pScrPriv->modes + m + 1,
-		     (pScrPriv->numModes - m - 1) * sizeof (RRModePtr));
-	    pScrPriv->numModes--;
-	    if (!pScrPriv->numModes)
+	    memmove (modes + m, modes + m + 1,
+		     (num_modes - m - 1) * sizeof (RRModePtr));
+	    num_modes--;
+	    if (!num_modes)
 	    {
-		xfree (pScrPriv->modes);
-		pScrPriv->modes = NULL;
+		xfree (modes);
+		modes = NULL;
 	    }
-	    pScrPriv->changed = TRUE;
 	    break;
 	}
     }
@@ -137,6 +166,8 @@ RRModeDestroyResource (pointer value, XID pid)
 Bool
 RRModeInit (void)
 {
+    assert (num_modes == 0);
+    assert (modes == NULL);
     RRModeType = CreateNewResourceType (RRModeDestroyResource);
     if (!RRModeType)
 	return FALSE;
@@ -146,26 +177,6 @@ RRModeInit (void)
     return TRUE;
 }
 
-void
-RRModePruneUnused (ScreenPtr pScreen)
-{
-    rrScrPriv (pScreen);
-    RRModePtr	*unused, mode;
-    int		m;
-    int		num = pScrPriv->numModes;
-
-    unused = xalloc (num * sizeof (RRModePtr));
-    if (!unused)
-	return;
-    memcpy (unused, pScrPriv->modes, num * sizeof (RRModePtr));
-    for (m = 0; m < num; m++) {
-	mode = unused[m];
-	if (mode->refcnt == 1 && !mode->userDefined)
-	    FreeResource (mode->mode.id, 0);
-    }
-    xfree (unused);
-}
-
 int
 ProcRRCreateMode (ClientPtr client)
 {
@@ -205,4 +216,3 @@ ProcRRDeleteOutputMode (ClientPtr client)
     (void) stuff;
     return BadImplementation; 
 }
-
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 1f6f330..1b0ecab 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -42,30 +42,17 @@ RROutputChanged (RROutputPtr output)
  */
 
 RROutputPtr
-RROutputCreate (ScreenPtr   pScreen,
-		const char  *name,
+RROutputCreate (const char  *name,
 		int	    nameLength,
 		void	    *devPrivate)
 {
-    rrScrPriv (pScreen);
     RROutputPtr	output;
-    RROutputPtr	*outputs;
 
     output = xalloc (sizeof (RROutputRec) + nameLength + 1);
     if (!output)
 	return NULL;
-    if (pScrPriv->numOutputs)
-	outputs = xrealloc (pScrPriv->outputs, 
-			    (pScrPriv->numOutputs + 1) * sizeof (RROutputPtr));
-    else
-	outputs = xalloc (sizeof (RROutputPtr));
-    if (!outputs)
-    {
-	xfree (output);
-	return NULL;
-    }
     output->id = FakeClientID (0);
-    output->pScreen = pScreen;
+    output->pScreen = NULL;
     output->name = (char *) (output + 1);
     output->nameLength = nameLength;
     memcpy (output->name, name, nameLength);
@@ -91,12 +78,35 @@ RROutputCreate (ScreenPtr   pScreen,
     if (!AddResource (output->id, RROutputType, (pointer) output))
 	return NULL;
 
+    return output;
+}
+
+/*
+ * Attach an Output to a screen. This is done as a separate step
+ * so that an xf86-based driver can create Outputs in PreInit
+ * before the Screen has been created
+ */
+
+Bool
+RROutputAttachScreen (RROutputPtr output, ScreenPtr pScreen)
+{
+    rrScrPriv (pScreen);
+    RROutputPtr	*outputs;
+    
+    if (pScrPriv->numOutputs)
+	outputs = xrealloc (pScrPriv->outputs, 
+			    (pScrPriv->numOutputs + 1) * sizeof (RROutputPtr));
+    else
+	outputs = xalloc (sizeof (RROutputPtr));
+    if (!outputs)
+	return FALSE;
+    output->pScreen = pScreen;
     pScrPriv->outputs = outputs;
     pScrPriv->outputs[pScrPriv->numOutputs++] = output;
     RROutputChanged (output);
-    return output;
+    return TRUE;
 }
-
+		      
 /*
  * Notify extension that output parameters have been changed
  */
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 705e7d7..d47e9d6 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -360,6 +360,13 @@ ProcRRGetScreenResources (ClientPtr client)
     }
     else
     {
+	RRModePtr   *modes;
+	int	    num_modes;
+
+	modes = RRModesForScreen (pScreen, &num_modes);
+	if (!modes)
+	    return BadAlloc;
+	
 	rep.type = X_Reply;
 	rep.sequenceNumber = client->sequence;
 	rep.length = 0;
@@ -367,15 +374,15 @@ ProcRRGetScreenResources (ClientPtr client)
 	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
 	rep.nCrtcs = pScrPriv->numCrtcs;
 	rep.nOutputs = pScrPriv->numOutputs;
-	rep.nModes = pScrPriv->numModes;;
+	rep.nModes = num_modes;
 	rep.nbytesNames = 0;
 
-	for (i = 0; i < pScrPriv->numModes; i++)
-	    rep.nbytesNames += pScrPriv->modes[i]->mode.nameLength;
+	for (i = 0; i < num_modes; i++)
+	    rep.nbytesNames += modes[i]->mode.nameLength;
 
 	rep.length = (pScrPriv->numCrtcs + 
 		      pScrPriv->numOutputs + 
-		      pScrPriv->numModes * (SIZEOF(xRRModeInfo) >> 2) +
+		      num_modes * (SIZEOF(xRRModeInfo) >> 2) +
 		      ((rep.nbytesNames + 3) >> 2));
 	
 	extraLen = rep.length << 2;
@@ -383,7 +390,10 @@ ProcRRGetScreenResources (ClientPtr client)
 	{
 	    extra = xalloc (extraLen);
 	    if (!extra)
+	    {
+		xfree (modes);
 		return BadAlloc;
+	    }
 	}
 	else
 	    extra = NULL;
@@ -391,7 +401,7 @@ ProcRRGetScreenResources (ClientPtr client)
 	crtcs = (RRCrtc *) extra;
 	outputs = (RROutput *) (crtcs + pScrPriv->numCrtcs);
 	modeinfos = (xRRModeInfo *) (outputs + pScrPriv->numOutputs);
-	names = (CARD8 *) (modeinfos + pScrPriv->numModes);
+	names = (CARD8 *) (modeinfos + num_modes);
 	
 	for (i = 0; i < pScrPriv->numCrtcs; i++)
 	{
@@ -407,9 +417,10 @@ ProcRRGetScreenResources (ClientPtr client)
 		swapl (&outputs[i], n);
 	}
 	
-	for (i = 0; i < pScrPriv->numModes; i++)
+	for (i = 0; i < num_modes; i++)
 	{
-	    modeinfos[i] = pScrPriv->modes[i]->mode;
+	    RRModePtr	mode = modes[i];
+	    modeinfos[i] = mode->mode;
 	    if (client->swapped)
 	    {
 		swapl (&modeinfos[i].id, n);
@@ -426,10 +437,11 @@ ProcRRGetScreenResources (ClientPtr client)
 		swaps (&modeinfos[i].nameLength, n);
 		swapl (&modeinfos[i].modeFlags, n);
 	    }
-	    memcpy (names, pScrPriv->modes[i]->name, 
-		    pScrPriv->modes[i]->mode.nameLength);
-	    names += pScrPriv->modes[i]->mode.nameLength;
+	    memcpy (names, mode->name, 
+		    mode->mode.nameLength);
+	    names += mode->mode.nameLength;
 	}
+    	xfree (modes);
 	assert (((((char *) names - (char *) extra) + 3) >> 2) == rep.length);
     }
     
commit 45621bd215ad905e39559154d1d3dfada92e1798
Author: Eric Anholt <eric at anholt.net>
Date:   Fri Nov 3 16:36:34 2006 -0800

    Don't bump the refcnt if the new mode is NULL.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index c40dac1..76d0b6b 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -174,7 +174,8 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	if (crtc->mode)
 	    RRModeDestroy (crtc->mode);
 	crtc->mode = mode;
-	mode->refcnt++;
+	if (mode != NULL)
+	    mode->refcnt++;
 	RRCrtcChanged (crtc, TRUE);
     }
     if (x != crtc->x)
commit 354603f509ae5db9301bfeec40bed1dda8c3bc09
Author: Keith Packard <keithp at mandolin.keithp.com>
Date:   Wed Nov 1 00:29:46 2006 -0800

    Move physical size from mode to output.
    
    Modes can be shared across different sized monitors this way.
    
    Also caught some missing byteswapping and an incorrect return type.

diff --git a/randr/mirandr.c b/randr/mirandr.c
index 8d79e8a..11c2991 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -111,8 +111,6 @@ miRandRInit (ScreenPtr pScreen)
     memset (&modeInfo, '\0', sizeof (modeInfo));
     modeInfo.width = pScreen->width;
     modeInfo.height = pScreen->height;
-    modeInfo.mmWidth = pScreen->mmWidth;
-    modeInfo.mmHeight = pScreen->mmHeight;
     modeInfo.nameLength = strlen (name);
     
     mode = RRModeGet (pScreen, &modeInfo, name);
diff --git a/randr/randrstr.h b/randr/randrstr.h
index a8a9950..60877a3 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -107,6 +107,8 @@ struct _rrOutput {
     int		    nameLength;
     CARD8	    connection;
     CARD8	    subpixelOrder;
+    int		    mmWidth;
+    int		    mmHeight;
     RRCrtcPtr	    crtc;
     CARD32	    currentOptions;
     CARD32	    possibleOptions;
@@ -642,6 +644,11 @@ Bool
 RROutputSetCurrentOptions (RROutputPtr output,
 			   CARD32      currentOptions);
 
+Bool
+RROutputSetPhysicalSize (RROutputPtr	output,
+			 int		mmWidth,
+			 int		mmHeight);
+
 void
 RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output);
 
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index ee51cc2..c40dac1 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -270,8 +270,16 @@ RRCrtcSet (RRCrtcPtr    crtc,
 
 	size.width = mode->mode.width;
 	size.height = mode->mode.height;
-	size.mmWidth = mode->mode.mmWidth;
-	size.mmHeight = mode->mode.mmHeight;
+	if (outputs[0].output->mmWidth && outputs[0].output->mmHeight)
+	{
+	    size.mmWidth = outputs[0].output->mmWidth;
+	    size.mmHeight = outputs[0].output->mmHeight;
+	}
+	else
+	{
+	    size.mmWidth = pScreen->mmWidth;
+	    size.mmHeight = pScreen->mmHeight;
+	}
 	size.nRates = 1;
 	rate.rate = RRVerticalRefresh (&mode->mode);
 	size.pRates = &rate;
diff --git a/randr/rrinfo.c b/randr/rrinfo.c
index 6fd4ee5..e92caad 100644
--- a/randr/rrinfo.c
+++ b/randr/rrinfo.c
@@ -39,8 +39,6 @@ RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
     
     modeInfo.width = size->width;
     modeInfo.height = size->height;
-    modeInfo.mmWidth = size->mmWidth;
-    modeInfo.mmHeight = size->mmHeight;
     modeInfo.hTotal = size->width;
     modeInfo.vTotal = size->height;
     modeInfo.dotClock = ((CARD32) size->width * (CARD32) size->height *
diff --git a/randr/rrmode.c b/randr/rrmode.c
index 07cd0c1..fb4b5eb 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -29,8 +29,6 @@ RRModeEqual (xRRModeInfo *a, xRRModeInfo *b)
 {
     if (a->width != b->width) return FALSE;
     if (a->height != b->height) return FALSE;
-    if (a->mmWidth != b->mmWidth) return FALSE;
-    if (a->mmHeight != b->mmHeight) return FALSE;
     if (a->dotClock != b->dotClock) return FALSE;
     if (a->hSyncStart != b->hSyncStart) return FALSE;
     if (a->hSyncEnd != b->hSyncEnd) return FALSE;
diff --git a/randr/rroutput.c b/randr/rroutput.c
index fc84ec1..1f6f330 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -72,6 +72,8 @@ RROutputCreate (ScreenPtr   pScreen,
     output->name[nameLength] = '\0';
     output->connection = RR_UnknownConnection;
     output->subpixelOrder = SubPixelUnknown;
+    output->mmWidth = 0;
+    output->mmHeight = 0;
     output->crtc = NULL;
     output->currentOptions = 0;
     output->possibleOptions = 0;
@@ -262,6 +264,20 @@ RROutputSetCurrentOptions (RROutputPtr output,
     return TRUE;
 }
 
+Bool
+RROutputSetPhysicalSize (RROutputPtr	output,
+			 int		mmWidth,
+			 int		mmHeight)
+{
+    if (output->mmWidth == mmWidth && output->mmHeight == mmHeight)
+	return TRUE;
+    output->mmWidth = mmWidth;
+    output->mmHeight = mmHeight;
+    RROutputChanged (output);
+    return TRUE;
+}
+
+
 void
 RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output)
 {
@@ -381,6 +397,8 @@ ProcRRGetOutputInfo (ClientPtr client)
     rep.timestamp = pScrPriv->lastSetTime.milliseconds;
     rep.crtc = output->crtc ? output->crtc->id : None;
     rep.currentOptions = output->currentOptions;
+    rep.mmWidth = output->mmWidth;
+    rep.mmHeight = output->mmHeight;
     rep.connection = output->connection;
     rep.subpixelOrder = output->subpixelOrder;
     rep.nCrtcs = output->numCrtcs;
@@ -434,10 +452,15 @@ ProcRRGetOutputInfo (ClientPtr client)
 	swapl(&rep.length, n);
 	swapl(&rep.timestamp, n);
 	swapl(&rep.crtc, n);
+	swapl(&rep.currentOptions, n);
+	swapl(&rep.mmWidth, n);
+	swapl(&rep.mmHeight, n);
 	swaps(&rep.nCrtcs, n);
 	swaps(&rep.nModes, n);
 	swaps(&rep.nClones, n);
+	swapl(&rep.possibleOptions, n);
 	swaps(&rep.nameLength, n);
+	swapl(&rep.possibleOptions, n);
     }
     WriteToClient(client, sizeof(xRRGetOutputInfoReply), (char *)&rep);
     if (extraLen)
diff --git a/randr/rrpointer.c b/randr/rrpointer.c
index 7ba0460..c092e49 100644
--- a/randr/rrpointer.c
+++ b/randr/rrpointer.c
@@ -131,7 +131,7 @@ RRPointerScreenConfigured (ScreenPtr pScreen)
     int		x, y;
 
     if (pScreen != pCurrentScreen)
-	return FALSE;
+	return;
     GetSpritePosition (&x, &y);
     RRPointerToNearestCrtc (pScreen, x, y, NULL);
 }
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index b4d3618..705e7d7 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -126,8 +126,8 @@ RRDeliverScreenEvent (ClientPtr client, WindowPtr pWin, ScreenPtr pScreen)
 	    }
 	se.widthInPixels = mode->mode.width;
 	se.heightInPixels = mode->mode.height;
-	se.widthInMillimeters = mode->mode.mmWidth;
-	se.heightInMillimeters = mode->mode.mmHeight;
+	se.widthInMillimeters = pScreen->mmWidth;
+	se.heightInMillimeters = pScreen->mmHeight;
     }
     else
     {
@@ -415,8 +415,6 @@ ProcRRGetScreenResources (ClientPtr client)
 		swapl (&modeinfos[i].id, n);
 		swaps (&modeinfos[i].width, n);
 		swaps (&modeinfos[i].height, n);
-		swapl (&modeinfos[i].mmWidth, n);
-		swapl (&modeinfos[i].mmHeight, n);
 		swapl (&modeinfos[i].dotClock, n);
 		swaps (&modeinfos[i].hSyncStart, n);
 		swaps (&modeinfos[i].hSyncEnd, n);
@@ -501,8 +499,13 @@ RR10GetData (ScreenPtr pScreen, RROutputPtr output)
 	    size[j].id = j;
 	    size[j].width = mode->mode.width;
 	    size[j].height = mode->mode.height;
-	    size[j].mmWidth = mode->mode.mmWidth;
-	    size[j].mmHeight = mode->mode.mmHeight;
+	    if (output->mmWidth && output->mmHeight) {
+		size[j].mmWidth = output->mmWidth;
+		size[j].mmHeight = output->mmHeight;
+	    } else {
+		size[j].mmWidth = pScreen->mmWidth;
+		size[j].mmHeight = pScreen->mmHeight;
+	    }
 	    size[j].nRates = 0;
 	    size[j].pRates = &refresh[data->nrefresh];
 	    data->nsize++;
commit 368cf03d33b3d99a0b704e38d144c322cf5d791e
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Wed Oct 25 09:48:23 2006 -0700

    Merge master back in and clean up some unfinished code (closes 8745)

diff --git a/randr/mirandr.c b/randr/mirandr.c
index fab0fd1..8d79e8a 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -57,6 +57,21 @@ miRRCrtcSet (ScreenPtr	pScreen,
     return TRUE;
 }
 
+static Bool
+miRRCrtcSetGamma (ScreenPtr	pScreen,
+		  RRCrtcPtr	crtc)
+{
+    return TRUE;
+}
+
+static Bool
+miRROutputSetProperty (ScreenPtr	pScreen,
+		       RROutputPtr	output,
+		       Atom	property)
+{
+    return TRUE;
+}
+
 /*
  * This function assumes that only a single depth can be
  * displayed at a time, but that all visuals of that depth
@@ -85,7 +100,7 @@ miRandRInit (ScreenPtr pScreen)
 #if RANDR_12_INTERFACE
     pScrPriv->rrCrtcSet = miRRCrtcSet;
     pScrPriv->rrCrtcSetGamma = miRRCrtcSetGamma;
-    pScrPriv->rrOutputSetProperty = miRROutput
+    pScrPriv->rrOutputSetProperty = miRROutputSetProperty;
     
     
     RRScreenSetSizeRange (pScreen,
diff --git a/randr/randr.c b/randr/randr.c
index b422efe..7b39e80 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -42,9 +42,6 @@
 int	RRGeneration;
 int	RRNScreens;
 
-static int ProcRRDispatch (ClientPtr pClient);
-static int SProcRRDispatch (ClientPtr pClient);
-
 #define wrap(priv,real,mem,func) {\
     priv->mem = real->mem; \
     real->mem = func; \
@@ -54,6 +51,9 @@ static int SProcRRDispatch (ClientPtr pClient);
     real->mem = priv->mem; \
 }
 
+static int ProcRRDispatch (ClientPtr pClient);
+static int SProcRRDispatch (ClientPtr pClient);
+
 int	RREventBase;
 int	RRErrorBase;
 RESTYPE RRClientType, RREventType; /* resource types for event masks */
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index c662899..ee51cc2 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -280,7 +280,7 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	 * Old 1.0 interface tied screen size to mode size
 	 */
 	if (ret)
-	    RRCrtcNotify (crtc, mode, x, y, rotation, 
+	    RRCrtcNotify (crtc, mode, x, y, rotation, 1, &outputs[0].output);
 	return ret;
     }
 #endif
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 6d38e96..b4d3618 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -164,7 +164,7 @@ RRScreenSizeNotify (ScreenPtr	pScreen)
     pScrPriv->width = pScreen->width;
     pScrPriv->height = pScreen->height;
     pScrPriv->changed = TRUE;
-    pScrPriv->sizeChanged = TRUE;
+/*    pScrPriv->sizeChanged = TRUE; */
 
     RRTellChanged (pScreen);
     RRSendConfigNotify (pScreen);
@@ -850,7 +850,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 
 	for (c = 0; c < pScrPriv->numCrtcs; c++)
 	{
-	    rep.status = RRCrtcSet (pScrPriv->->crtc, NULL, 0, 0, RR_Rotate_0,
+	    rep.status = RRCrtcSet (pScrPriv->crtcs[c], NULL, 0, 0, RR_Rotate_0,
 				    0, NULL);
 	    if (rep.status != Success)
 		goto sendReply;
@@ -858,7 +858,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	if (!RRScreenSizeSet (pScreen, mode->mode.width, mode->mode.height,
 			      pScreen->mmWidth, pScreen->mmHeight))
 	{
-	    rep.status  RRSetConfigFailed;
+	    rep.status = RRSetConfigFailed;
 	    goto sendReply;
 	}
     }
diff --git a/randr/rrxinerama.c b/randr/rrxinerama.c
index 31f60cc..a8e4b39 100644
--- a/randr/rrxinerama.c
+++ b/randr/rrxinerama.c
@@ -259,6 +259,9 @@ ProcRRXineramaQueryScreens(ClientPtr client)
 
     REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
 
+    if (RRXineramaScreenActive (pScreen))
+	RRGetInfo (pScreen);
+    
     rep.type = X_Reply;
     rep.sequenceNumber = client->sequence;
     rep.number = RRXineramaScreenCount (pScreen);
commit a153871447393018b96c362282018a3e73fa84e4
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Tue Oct 24 17:23:02 2006 -0700

    Byte swap RRSelectInput enable flags.

diff --git a/randr/rrsdispatch.c b/randr/rrsdispatch.c
index bf81f8b..67af753 100644
--- a/randr/rrsdispatch.c
+++ b/randr/rrsdispatch.c
@@ -77,6 +77,7 @@ SProcRRSelectInput (ClientPtr client)
 
     swaps(&stuff->length, n);
     swapl(&stuff->window, n);
+    swaps(&stuff->enable, n);
     return (*ProcRandrVector[stuff->randrReqType]) (client);
 }
 
commit 39ecb2b10906779edee378ebf834cf84fb282885
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Fri Oct 13 17:34:53 2006 -0700

    Limit pointer to valid crtc areas. Add event swapping. Fix change tracking.
    
    Add function to keep pointer within valid crtc areas.
    Finish event delivery and swapping code.
    Separate configuration from layout changes to send correct events.

diff --git a/randr/Makefile.am b/randr/Makefile.am
index 91c4bc6..9bf0e65 100644
--- a/randr/Makefile.am
+++ b/randr/Makefile.am
@@ -15,6 +15,7 @@ librandr_la_SOURCES =	\
 	rrinfo.c	\
 	rrmode.c	\
 	rroutput.c	\
+	rrpointer.c	\
 	rrproperty.c	\
 	rrscreen.c	\
 	rrsdispatch.c	\
diff --git a/randr/mirandr.c b/randr/mirandr.c
index 918e55d..fab0fd1 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -84,6 +84,9 @@ miRandRInit (ScreenPtr pScreen)
     pScrPriv->rrGetInfo = miRRGetInfo;
 #if RANDR_12_INTERFACE
     pScrPriv->rrCrtcSet = miRRCrtcSet;
+    pScrPriv->rrCrtcSetGamma = miRRCrtcSetGamma;
+    pScrPriv->rrOutputSetProperty = miRROutput
+    
     
     RRScreenSetSizeRange (pScreen,
 			  pScreen->width, pScreen->height,
diff --git a/randr/randr.c b/randr/randr.c
index 35f9a4c..b422efe 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -130,38 +130,71 @@ SRRScreenChangeNotifyEvent(xRRScreenChangeNotifyEvent *from,
     cpswaps(from->subpixelOrder, to->subpixelOrder);
 }
 
-#if 0
 static void
-SRRMonitorChangeNotifyEvent(xRRMonitorChangeNotifyEvent *from,
-			    xRRMonitorChangeNotifyEvent *to)
+SRRCrtcChangeNotifyEvent(xRRCrtcChangeNotifyEvent *from,
+			 xRRCrtcChangeNotifyEvent *to)
 {
     to->type = from->type;
     to->subCode = from->subCode;
     cpswaps(from->sequenceNumber, to->sequenceNumber);
     cpswapl(from->timestamp, to->timestamp);
-    cpswapl(from->configTimestamp, to->configTimestamp);
-    cpswapl(from->root, to->root);
     cpswapl(from->window, to->window);
-    cpswaps(from->monitor, to->monitor);
-    cpswaps(from->modeID, to->modeID);
+    cpswapl(from->crtc, to->crtc);
+    cpswapl(from->mode, to->mode);
+    cpswapl(from->window, to->window);
     cpswaps(from->rotation, to->rotation);
-    cpswaps(from->subpixelOrder, to->subpixelOrder);
     cpswaps(from->x, to->x);
     cpswaps(from->y, to->y);
+    cpswaps(from->width, to->width);
+    cpswaps(from->height, to->height);
+}
+
+static void
+SRROutputChangeNotifyEvent(xRROutputChangeNotifyEvent *from,
+			   xRROutputChangeNotifyEvent *to)
+{
+    to->type = from->type;
+    to->subCode = from->subCode;
+    cpswaps(from->sequenceNumber, to->sequenceNumber);
+    cpswapl(from->timestamp, to->timestamp);
+    cpswapl(from->configTimestamp, to->configTimestamp);
+    cpswapl(from->window, to->window);
+    cpswapl(from->output, to->output);
+    cpswapl(from->crtc, to->crtc);
+    cpswapl(from->mode, to->mode);
+    cpswaps(from->rotation, to->rotation);
+}
+
+static void
+SRROutputPropertyNotifyEvent(xRROutputPropertyNotifyEvent *from,
+			     xRROutputPropertyNotifyEvent *to)
+{
+    to->type = from->type;
+    to->subCode = from->subCode;
+    cpswaps(from->sequenceNumber, to->sequenceNumber);
+    cpswapl(from->window, to->window);
+    cpswapl(from->output, to->output);
+    cpswapl(from->atom, to->atom);
+    cpswapl(from->timestamp, to->timestamp);
 }
-#endif
 
 static void
 SRRNotifyEvent (xEvent *from,
 		xEvent *to)
 {
     switch (from->u.u.detail) {
-#if 0
-    case RRNotify_MonitorChange:
-	SRRMonitorChangeNotifyEvent ((xRRMonitorChangeNotifyEvent *) from,
-				     (xRRMonitorChangeNotifyEvent *) to);
+    case RRNotify_CrtcChange:
+	SRRCrtcChangeNotifyEvent ((xRRCrtcChangeNotifyEvent *) from,
+				  (xRRCrtcChangeNotifyEvent *) to);
+	break;
+    case RRNotify_OutputChange:
+	SRROutputChangeNotifyEvent ((xRROutputChangeNotifyEvent *) from,
+				    (xRROutputChangeNotifyEvent *) to);
+	break;
+    case RRNotify_OutputProperty:
+	SRROutputPropertyNotifyEvent ((xRROutputPropertyNotifyEvent *) from,
+				      (xRROutputPropertyNotifyEvent *) to);
 	break;
-#endif
     default:
 	break;
     }
@@ -359,6 +392,9 @@ TellChanged (WindowPtr pWin, pointer value)
     return WT_WALKCHILDREN;
 }
 
+/*
+ * Something changed; send events and adjust pointer position
+ */
 void
 RRTellChanged (ScreenPtr pScreen)
 {
@@ -369,12 +405,18 @@ RRTellChanged (ScreenPtr pScreen)
     {
 	UpdateCurrentTime ();
 	pScrPriv->lastConfigTime = currentTime;
-	WalkTree (pScreen, TellChanged, (pointer) pScreen);
 	pScrPriv->changed = FALSE;
+	WalkTree (pScreen, TellChanged, (pointer) pScreen);
 	for (i = 0; i < pScrPriv->numOutputs; i++)
 	    pScrPriv->outputs[i]->changed = FALSE;
 	for (i = 0; i < pScrPriv->numCrtcs; i++)
 	    pScrPriv->crtcs[i]->changed = FALSE;
+	if (pScrPriv->layoutChanged)
+	{
+	    pScrPriv->layoutChanged = FALSE;
+	    RRPointerScreenConfigured (pScreen);
+	    RRSendConfigNotify (pScreen);
+	}
     }
 }
 
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 6690556..a8a9950 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -202,10 +202,11 @@ typedef struct _rrScrPriv {
     TimeStamp		    lastSetTime;	/* last changed by client */
     TimeStamp		    lastConfigTime;	/* possible configs changed */
     RRCloseScreenProcPtr    CloseScreen;
-    Bool		    changed;
+    Bool		    changed;		/* some config changed */
     CARD16		    minWidth, minHeight;
     CARD16		    maxWidth, maxHeight;
     CARD16		    width, height;	/* last known screen size */
+    Bool		    layoutChanged;	/* screen layout changed */
 
     /* modes, outputs and crtcs */
     int			    numModes;
@@ -217,6 +218,9 @@ typedef struct _rrScrPriv {
     int			    numCrtcs;
     RRCrtcPtr		    *crtcs;
 
+    /* Last known pointer position */
+    RRCrtcPtr		    pointerCrtc;
+
 #ifdef RANDR_10_INTERFACE
     /*
      * Configuration information
@@ -439,6 +443,14 @@ RRSetScreenConfig (ScreenPtr		pScreen,
 #endif					
 
 /* rrcrtc.c */
+
+/*
+ * Notify the CRTC of some change; layoutChanged indicates that
+ * some position or size element changed
+ */
+void
+RRCrtcChanged (RRCrtcPtr crtc, Bool layoutChanged);
+
 /*
  * Create a CRTC
  */
@@ -575,6 +587,13 @@ int
 ProcRRDeleteOutputMode (ClientPtr client);
 
 /* rroutput.c */
+
+/*
+ * Notify the output of some change
+ */
+void
+RROutputChanged (RROutputPtr output);
+
 /*
  * Create an output
  */
@@ -638,6 +657,13 @@ ProcRRGetOutputInfo (ClientPtr client);
 Bool
 RROutputInit (void);
     
+/* rrpointer.c */
+void
+RRPointerMoved (ScreenPtr pScreen, int x, int y);
+
+void
+RRPointerScreenConfigured (ScreenPtr pScreen);
+
 /* rrproperty.c */
 
 void
@@ -668,3 +694,79 @@ void
 RRXineramaExtensionInit(void);
 
 #endif /* _RANDRSTR_H_ */
+
+/*
+ 
+randr extension implementation structure
+
+Query state:
+    ProcRRGetScreenInfo/ProcRRGetScreenResources
+	RRGetInfo
+ 
+	    • Request configuration from driver, either 1.0 or 1.2 style
+	    • These functions only record state changes, all
+	      other actions are pended until RRTellChanged is called
+ 
+	    ->rrGetInfo
+	    1.0:
+		RRRegisterSize
+		RRRegisterRate
+		RRSetCurrentConfig
+	    1.2:
+		RRScreenSetSizeRange
+		RROutputSetCrtcs
+		RROutputSetCrtc
+		RROutputSetPossibleOptions
+		RRSetCurrentOptions
+		RRModeGet
+		RROutputSetModes
+		RROutputSetConnection
+		RROutputSetSubpixelOrder
+		RROutputSetClones
+		RRCrtcNotify
+ 
+	• Must delay scanning configuration until after ->rrGetInfo returns
+	  because some drivers will call SetCurrentConfig in the middle
+	  of the ->rrGetInfo operation.
+ 
+	1.0:
+
+	    • Scan old configuration, mirror to new structures
+ 
+	    RRScanOldConfig
+		RRCrtcCreate
+		RROutputCreate
+		RROutputSetCrtcs
+		RROutputSetCrtc
+		RROutputSetConnection
+		RROutputSetSubpixelOrder
+		RROldModeAdd	• This adds modes one-at-a-time
+		    RRModeGet
+		RRCrtcNotify
+ 
+	• send events, reset pointer if necessary
+ 
+	RRTellChanged
+	    WalkTree (sending events)
+ 
+	    • when layout has changed:
+		RRPointerScreenConfigured
+		RRSendConfigNotify
+ 
+Asynchronous state setting (1.2 only)
+    When setting state asynchronously, the driver invokes the
+    ->rrGetInfo function and then calls RRTellChanged to flush
+    the changes to the clients and reset pointer if necessary
+
+Set state
+
+    ProcRRSetScreenConfig
+	RRCrtcSet
+	    1.2:
+		->rrCrtcSet
+		    RRCrtcNotify
+	    1.0:
+		->rrSetConfig
+		RRCrtcNotify
+	    RRTellChanged
+ */
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index baefd3a..c662899 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -26,6 +26,24 @@
 RESTYPE	RRCrtcType;
 
 /*
+ * Notify the CRTC of some change
+ */
+void
+RRCrtcChanged (RRCrtcPtr crtc, Bool layoutChanged)
+{
+    ScreenPtr	pScreen = crtc->pScreen;
+    rrScrPriv(pScreen);
+
+    crtc->changed = TRUE;
+    pScrPriv->changed = TRUE;
+    /*
+     * Send ConfigureNotify on any layout change
+     */
+    if (layoutChanged)
+	pScrPriv->layoutChanged = TRUE;
+}
+
+/*
  * Create a CRTC
  */
 RRCrtcPtr
@@ -60,7 +78,7 @@ RRCrtcCreate (ScreenPtr	pScreen,
     crtc->numOutputs = 0;
     crtc->gammaSize = 0;
     crtc->gammaRed = crtc->gammaBlue = crtc->gammaGreen = NULL;
-    crtc->changed = TRUE;
+    crtc->changed = FALSE;
     crtc->devPrivate = devPrivate;
 
     if (!AddResource (crtc->id, RRCrtcType, (pointer) crtc))
@@ -68,7 +86,8 @@ RRCrtcCreate (ScreenPtr	pScreen,
 
     pScrPriv->crtcs = crtcs;
     pScrPriv->crtcs[pScrPriv->numCrtcs++] = crtc;
-    pScrPriv->changed = TRUE;
+
+    RRCrtcChanged (crtc, TRUE);
     return crtc;
 }
 
@@ -85,8 +104,6 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	      int	    numOutputs,
 	      RROutputPtr   *outputs)
 {
-    ScreenPtr	pScreen = crtc->pScreen;
-    rrScrPriv(pScreen);
     int	    i, j;
     
     /*
@@ -100,8 +117,8 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 		break;
 	if (j == crtc->numOutputs)
 	{
-	    outputs[i]->changed = TRUE;
-	    crtc->changed = TRUE;
+	    RROutputChanged (outputs[i]);
+	    RRCrtcChanged (crtc, FALSE);
 	}
     }
     /*
@@ -115,8 +132,8 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 		break;
 	if (i == numOutputs)
 	{
-	    crtc->outputs[j]->changed = TRUE;
-	    crtc->changed = TRUE;
+	    RROutputChanged (crtc->outputs[j]);
+	    RRCrtcChanged (crtc, FALSE);
 	}
     }
     /*
@@ -158,31 +175,22 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	    RRModeDestroy (crtc->mode);
 	crtc->mode = mode;
 	mode->refcnt++;
-	crtc->changed = TRUE;
+	RRCrtcChanged (crtc, TRUE);
     }
     if (x != crtc->x)
     {
 	crtc->x = x;
-	crtc->changed = TRUE;
+	RRCrtcChanged (crtc, TRUE);
     }
     if (y != crtc->y)
     {
 	crtc->y = y;
-	crtc->changed = TRUE;
+	RRCrtcChanged (crtc, TRUE);
     }
     if (rotation != crtc->rotation)
     {
 	crtc->rotation = rotation;
-	crtc->changed = TRUE;
-    }
-    /*
-     * Send events if anything changed
-     */
-    if (crtc->changed)
-    {
-	if (!pScrPriv->changed)
-	    RRSendConfigNotify (pScreen);
-	pScrPriv->changed = TRUE;
+	RRCrtcChanged (crtc, TRUE);
     }
     return TRUE;
 }
@@ -272,10 +280,11 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	 * Old 1.0 interface tied screen size to mode size
 	 */
 	if (ret)
-	    RRScreenSizeNotify (pScreen);
+	    RRCrtcNotify (crtc, mode, x, y, rotation, 
 	return ret;
     }
 #endif
+    RRTellChanged (pScreen);
     return FALSE;
 }
 
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 618ef1f..fc84ec1 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -25,6 +25,19 @@
 RESTYPE	RROutputType;
 
 /*
+ * Notify the output of some change
+ */
+void
+RROutputChanged (RROutputPtr output)
+{
+    ScreenPtr	pScreen = output->pScreen;
+    rrScrPriv (pScreen);
+
+    output->changed = TRUE;
+    pScrPriv->changed = TRUE;
+}
+
+/*
  * Create an output
  */
 
@@ -70,7 +83,7 @@ RROutputCreate (ScreenPtr   pScreen,
     output->numPreferred = 0;
     output->modes = NULL;
     output->properties = NULL;
-    output->changed = TRUE;
+    output->changed = FALSE;
     output->devPrivate = devPrivate;
     
     if (!AddResource (output->id, RROutputType, (pointer) output))
@@ -78,7 +91,7 @@ RROutputCreate (ScreenPtr   pScreen,
 
     pScrPriv->outputs = outputs;
     pScrPriv->outputs[pScrPriv->numOutputs++] = output;
-    pScrPriv->changed = TRUE;
+    RROutputChanged (output);
     return output;
 }
 
@@ -114,7 +127,7 @@ RROutputSetClones (RROutputPtr  output,
     memcpy (newClones, clones, numClones * sizeof (RROutputPtr));
     output->clones = newClones;
     output->numClones = numClones;
-    output->changed = TRUE;
+    RROutputChanged (output);
     return TRUE;
 }
 
@@ -158,7 +171,7 @@ RROutputSetModes (RROutputPtr	output,
     output->modes = newModes;
     output->numModes = numModes;
     output->numPreferred = numPreferred;
-    output->changed = TRUE;
+    RROutputChanged (output);
     return TRUE;
 }
 
@@ -191,7 +204,7 @@ RROutputSetCrtcs (RROutputPtr	output,
     memcpy (newCrtcs, crtcs, numCrtcs * sizeof (RRCrtcPtr));
     output->crtcs = newCrtcs;
     output->numCrtcs = numCrtcs;
-    output->changed = TRUE;
+    RROutputChanged (output);
     return TRUE;
 }
 
@@ -202,7 +215,7 @@ RROutputSetPossibleOptions (RROutputPtr	output,
     if (output->possibleOptions == possibleOptions)
 	return TRUE;
     output->possibleOptions = possibleOptions;
-    output->changed = TRUE;
+    RROutputChanged (output);
     return TRUE;
 }
 
@@ -212,7 +225,7 @@ RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc)
     if (output->crtc == crtc)
 	return;
     output->crtc = crtc;
-    output->changed = TRUE;
+    RROutputChanged (output);
 }
 
 Bool
@@ -222,7 +235,7 @@ RROutputSetConnection (RROutputPtr  output,
     if (output->connection == connection)
 	return TRUE;
     output->connection = connection;
-    output->changed = TRUE;
+    RROutputChanged (output);
     return TRUE;
 }
 
@@ -234,7 +247,7 @@ RROutputSetSubpixelOrder (RROutputPtr output,
 	return TRUE;
 
     output->subpixelOrder = subpixelOrder;
-    output->changed = TRUE;
+    RROutputChanged (output);
     return TRUE;
 }
 
@@ -245,13 +258,41 @@ RROutputSetCurrentOptions (RROutputPtr output,
     if (output->currentOptions == currentOptions)
 	return TRUE;
     output->currentOptions = currentOptions;
-    output->changed = TRUE;
+    RROutputChanged (output);
     return TRUE;
 }
 
 void
 RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output)
 {
+    ScreenPtr pScreen = pWin->drawable.pScreen;
+    rrScrPriv (pScreen);
+    xRROutputChangeNotifyEvent	oe;
+    RRCrtcPtr	crtc = output->crtc;
+    RRModePtr	mode = crtc ? crtc->mode : 0;
+    
+    oe.type = RRNotify + RREventBase;
+    oe.subCode = RRNotify_OutputChange;
+    oe.sequenceNumber = client->sequence;
+    oe.timestamp = pScrPriv->lastSetTime.milliseconds;
+    oe.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
+    oe.window = pWin->drawable.id;
+    oe.output = output->id;
+    if (crtc)
+    {
+	oe.crtc = crtc->id;
+	oe.mode = mode ? mode->mode.id : None;
+	oe.rotation = crtc->rotation;
+    }
+    else
+    {
+	oe.crtc = None;
+	oe.mode = None;
+	oe.rotation = RR_Rotate_0;
+    }
+    oe.connection = output->connection;
+    oe.subpixelOrder = output->subpixelOrder;
+    WriteEventsToClient (client, 1, (xEvent *) &oe);
 }
 
 /*
diff --git a/randr/rrpointer.c b/randr/rrpointer.c
new file mode 100644
index 0000000..7ba0460
--- /dev/null
+++ b/randr/rrpointer.c
@@ -0,0 +1,137 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+
+/*
+ * When the pointer moves, check to see if the specified position is outside
+ * any of theavailable CRTCs and move it to a 'sensible' place if so, where
+ * sensible is the closest monitor to the departing edge.
+ *
+ * Returns whether the position was adjusted
+ */
+
+static Bool
+RRCrtcContainsPosition (RRCrtcPtr crtc, int x, int y)
+{
+    RRModePtr   mode = crtc->mode;
+    
+    if (!mode)
+	return FALSE;
+    if (crtc->x <= x && x < crtc->x + mode->mode.width &&
+	crtc->y <= y && y < crtc->y + mode->mode.height)
+	return TRUE;
+    return FALSE;
+}
+
+/*
+ * Find the CRTC nearest the specified position, ignoring 'skip'
+ */
+static void
+RRPointerToNearestCrtc (ScreenPtr pScreen, int x, int y, RRCrtcPtr skip)
+{
+    rrScrPriv (pScreen);
+    int		c;
+    RRCrtcPtr	nearest = NULL;
+    int		best = 0;
+    int		best_dx = 0, best_dy = 0;
+    
+    for (c = 0; c < pScrPriv->numCrtcs; c++)
+    {
+	RRCrtcPtr   crtc = pScrPriv->crtcs[c];
+	RRModePtr   mode = crtc->mode;
+	int	    dx, dy;
+	int	    dist;
+
+	if (!mode)
+	    continue;
+	if (crtc == skip)
+	    continue;
+	if (x < crtc->x)
+	    dx = crtc->x - x;
+	else if (x > crtc->x + mode->mode.width)
+	    dx = x - (crtc->x + mode->mode.width);
+	else
+	    dx = 0;
+	if (y < crtc->y)
+	    dy = crtc->y - x;
+	else if (y > crtc->y + mode->mode.height)
+	    dy = y - (crtc->y + mode->mode.height);
+	else
+	    dy = 0;
+	dist = dx + dy;
+	if (!nearest || dist < best)
+	{
+	    nearest = crtc;
+	    best_dx = dx;
+	    best_dy = dy;
+	}
+    }
+    if (best_dx || best_dy)
+	(*pScreen->SetCursorPosition) (pScreen, x + best_dx, y + best_dy, TRUE);
+    pScrPriv->pointerCrtc = nearest;
+}
+
+void
+RRPointerMoved (ScreenPtr pScreen, int x, int y)
+{
+    rrScrPriv (pScreen);
+    RRCrtcPtr	pointerCrtc = pScrPriv->pointerCrtc;;
+    int	c;
+
+    /* Check last known CRTC */
+    if (pointerCrtc && RRCrtcContainsPosition (pointerCrtc, x, y))
+	return;
+    
+    /* Check all CRTCs */
+    for (c = 0; c < pScrPriv->numCrtcs; c++)
+    {
+	RRCrtcPtr   crtc = pScrPriv->crtcs[c];
+	
+	if (RRCrtcContainsPosition (crtc, x, y))
+	{
+	    /* Remember containing CRTC */
+	    pScrPriv->pointerCrtc = crtc;
+	    return;
+	}
+    }
+
+    /* None contain pointer, find nearest */
+    RRPointerToNearestCrtc (pScreen, x, y, pointerCrtc);
+}
+
+/*
+ * When the screen is reconfigured, move the pointer to the nearest
+ * CRTC
+ */
+void
+RRPointerScreenConfigured (ScreenPtr pScreen)
+{
+    WindowPtr	pRoot = GetCurrentRootWindow ();
+    ScreenPtr	pCurrentScreen = pRoot ? pRoot->drawable.pScreen : NULL;
+    int		x, y;
+
+    if (pScreen != pCurrentScreen)
+	return FALSE;
+    GetSpritePosition (&x, &y);
+    RRPointerToNearestCrtc (pScreen, x, y, NULL);
+}
diff --git a/randr/rrproperty.c b/randr/rrproperty.c
index cdafb5c..44f1f0a 100644
--- a/randr/rrproperty.c
+++ b/randr/rrproperty.c
@@ -27,6 +27,7 @@
 static void
 RRDeliverEvent (ScreenPtr pScreen, xEvent *event, CARD32 mask)
 {
+    
 }
 
 void
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 7b53f04..6d38e96 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -164,10 +164,13 @@ RRScreenSizeNotify (ScreenPtr	pScreen)
     pScrPriv->width = pScreen->width;
     pScrPriv->height = pScreen->height;
     pScrPriv->changed = TRUE;
+    pScrPriv->sizeChanged = TRUE;
 
+    RRTellChanged (pScreen);
     RRSendConfigNotify (pScreen);
     RREditConnectionInfo (pScreen);
     
+    RRPointerScreenConfigured (pScreen);
     /*
      * Fix pointer bounds and location
      */
@@ -836,9 +839,37 @@ ProcRRSetScreenConfig (ClientPtr client)
 	goto sendReply;
     }
 
+    /*
+     * If the screen size is changing, adjust all of the other outputs
+     * to fit the new size, mirroring as much as possible
+     */
+    if (mode->mode.width != pScreen->width || 
+	mode->mode.height != pScreen->height)
+    {
+	int	c;
+
+	for (c = 0; c < pScrPriv->numCrtcs; c++)
+	{
+	    rep.status = RRCrtcSet (pScrPriv->->crtc, NULL, 0, 0, RR_Rotate_0,
+				    0, NULL);
+	    if (rep.status != Success)
+		goto sendReply;
+	}
+	if (!RRScreenSizeSet (pScreen, mode->mode.width, mode->mode.height,
+			      pScreen->mmWidth, pScreen->mmHeight))
+	{
+	    rep.status  RRSetConfigFailed;
+	    goto sendReply;
+	}
+    }
+    
     rep.status = RRCrtcSet (output.output->crtc, mode, 0, 0, stuff->rotation,
 			    1, &output);
     
+    /*
+     * XXX Configure other crtcs to mirror as much as possible
+     */
+    
 sendReply:
     
     if (pData)
commit a9fb37ffde70b8d78bba6f76882ad3b6515320ce
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Thu Oct 5 22:31:35 2006 -0700

    Add preferred modes for each output. Round vrefresh. Deliver crtc events.

diff --git a/randr/mirandr.c b/randr/mirandr.c
index 7300cfe..918e55d 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -110,7 +110,7 @@ miRandRInit (ScreenPtr pScreen)
 	return FALSE;
     if (!RROutputSetClones (output, NULL, 0))
 	return FALSE;
-    if (!RROutputSetModes (output, &mode, 1))
+    if (!RROutputSetModes (output, &mode, 1, 0))
 	return FALSE;
     if (!RROutputSetCrtcs (output, &crtc, 1))
 	return FALSE;
diff --git a/randr/randr.c b/randr/randr.c
index 4ea72e5..35f9a4c 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -406,9 +406,10 @@ CARD16
 RRVerticalRefresh (xRRModeInfo *mode)
 {
     CARD32  refresh;
-    if (!mode->hTotal || !mode->vTotal)
+    CARD32  dots = mode->hTotal * mode->vTotal;
+    if (!dots)
 	return 0;
-    refresh = mode->dotClock / (mode->hTotal * mode->vTotal);
+    refresh = (mode->dotClock + dots/2) / dots;
     if (refresh > 0xffff)
 	refresh = 0xffff;
     return (CARD16) refresh;
diff --git a/randr/randrstr.h b/randr/randrstr.h
index a4e5589..6690556 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -80,6 +80,7 @@ struct _rrMode {
     char	    *name;
     void	    *devPrivate;
     ScreenPtr	    screen;
+    Bool	    userDefined;
 };
 
 struct _rrCrtc {
@@ -114,6 +115,7 @@ struct _rrOutput {
     int		    numClones;
     RROutputPtr	    *clones;
     int		    numModes;
+    int		    numPreferred;
     RRModePtr	    *modes;
     Bool	    changed;
     PropertyPtr	    properties;
@@ -144,6 +146,10 @@ typedef Bool (*RRCrtcSetProcPtr) (ScreenPtr		pScreen,
 typedef Bool (*RRCrtcSetGammaProcPtr) (ScreenPtr	pScreen,
 				       RRCrtcPtr	crtc);
 
+typedef Bool (*RROutputSetPropertyProcPtr) (ScreenPtr	pScreen,
+					    RROutputPtr	output,
+					    Atom	property);
+
 #endif
 
 typedef Bool (*RRGetInfoProcPtr) (ScreenPtr pScreen, Rotation *rotations);
@@ -187,6 +193,7 @@ typedef struct _rrScrPriv {
     RRScreenSetSizeProcPtr  rrScreenSetSize;
     RRCrtcSetProcPtr	    rrCrtcSet;
     RRCrtcSetGammaProcPtr   rrCrtcSetGamma;
+    RROutputSetPropertyProcPtr	rrOutputSetProperty;
 #endif
     
     /*
@@ -589,7 +596,8 @@ RROutputSetClones (RROutputPtr  output,
 Bool
 RROutputSetModes (RROutputPtr	output,
 		  RRModePtr	*modes,
-		  int		numModes);
+		  int		numModes,
+		  int		numPreferred);
 
 Bool
 RROutputSetCrtcs (RROutputPtr	output,
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 3108f14..baefd3a 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -88,9 +88,41 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
     ScreenPtr	pScreen = crtc->pScreen;
     rrScrPriv(pScreen);
     int	    i, j;
-    int	    prevNumOutputs = crtc->numOutputs;
     
-    if (numOutputs != prevNumOutputs)
+    /*
+     * Check to see if any of the new outputs were
+     * not in the old list and mark them as changed
+     */
+    for (i = 0; i < numOutputs; i++)
+    {
+	for (j = 0; j < crtc->numOutputs; j++)
+	    if (outputs[i] == crtc->outputs[j])
+		break;
+	if (j == crtc->numOutputs)
+	{
+	    outputs[i]->changed = TRUE;
+	    crtc->changed = TRUE;
+	}
+    }
+    /*
+     * Check to see if any of the old outputs are
+     * not in the new list and mark them as changed
+     */
+    for (j = 0; j < crtc->numOutputs; j++)
+    {
+	for (i = 0; i < numOutputs; i++)
+	    if (outputs[i] == crtc->outputs[j])
+		break;
+	if (i == numOutputs)
+	{
+	    crtc->outputs[j]->changed = TRUE;
+	    crtc->changed = TRUE;
+	}
+    }
+    /*
+     * Reallocate the crtc output array if necessary
+     */
+    if (numOutputs != crtc->numOutputs)
     {
 	RROutputPtr *newoutputs;
 	
@@ -113,28 +145,13 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	crtc->outputs = newoutputs;
 	crtc->numOutputs = numOutputs;
     }
-    for (i = 0; i < numOutputs; i++)
-    {
-	for (j = 0; j < crtc->numOutputs; j++)
-	    if (outputs[i] == crtc->outputs[j])
-		break;
-	if (j != crtc->numOutputs)
-	{
-	    outputs[i]->changed = TRUE;
-	    crtc->changed = TRUE;
-	}
-    }
-    for (j = 0; j < crtc->numOutputs; j++)
-    {
-	for (i = 0; i < numOutputs; i++)
-	    if (outputs[i] == crtc->outputs[j])
-		break;
-	if (i != numOutputs)
-	{
-	    crtc->outputs[j]->changed = TRUE;
-	    crtc->changed = TRUE;
-	}
-    }
+    /*
+     * Copy the new list of outputs into the crtc
+     */
+    memcpy (crtc->outputs, outputs, numOutputs * sizeof (RROutputPtr));
+    /*
+     * Update remaining crtc fields
+     */
     if (mode != crtc->mode)
     {
 	if (crtc->mode)
@@ -158,6 +175,9 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	crtc->rotation = rotation;
 	crtc->changed = TRUE;
     }
+    /*
+     * Send events if anything changed
+     */
     if (crtc->changed)
     {
 	if (!pScrPriv->changed)
@@ -170,7 +190,35 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 void
 RRDeliverCrtcEvent (ClientPtr client, WindowPtr pWin, RRCrtcPtr crtc)
 {
-    
+    ScreenPtr pScreen = pWin->drawable.pScreen;
+    rrScrPriv (pScreen);
+    xRRCrtcChangeNotifyEvent	ce;
+    RRModePtr	mode = crtc->mode;
+    
+    ce.type = RRNotify + RREventBase;
+    ce.subCode = RRNotify_CrtcChange;
+    ce.sequenceNumber = client->sequence;
+    ce.timestamp = pScrPriv->lastSetTime.milliseconds;
+    ce.window = pWin->drawable.id;
+    ce.crtc = crtc->id;
+    ce.rotation = crtc->rotation;
+    if (mode)
+    {
+	ce.mode = mode->mode.id;
+	ce.x = crtc->x;
+	ce.y = crtc->y;
+	ce.width = mode->mode.width;
+	ce.height = mode->mode.height;
+    }
+    else
+    {
+	ce.mode = None;
+	ce.x = 0;
+	ce.y = 0;
+	ce.width = 0;
+	ce.height = 0;
+    }
+    WriteEventsToClient (client, 1, (xEvent *) &ce);
 }
 
 /*
@@ -381,7 +429,7 @@ ProcRRGetCrtcInfo (ClientPtr client)
     rep.y = crtc->y;
     rep.width = mode ? mode->mode.width : 0;
     rep.height = mode ? mode->mode.height : 0;
-    rep.mode = mode->mode.id;
+    rep.mode = mode ? mode->mode.id : 0;
     rep.rotation = crtc->rotation;
     rep.rotations = crtc->rotations;
     rep.nOutput = crtc->numOutputs;
@@ -572,30 +620,30 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	goto sendReply;
     }
     
-    if (mode)
-    {
+    /*
+     * Validate requested rotation
+     */
+    rotation = (Rotation) stuff->rotation;
+
+    /* test the rotation bits only! */
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_90:
+    case RR_Rotate_180:
+    case RR_Rotate_270:
+	break;
+    default:
 	/*
-	 * Validate requested rotation
+	 * Invalid rotation
 	 */
-	rotation = (Rotation) stuff->rotation;
-    
-	/* test the rotation bits only! */
-	switch (rotation & 0xf) {
-	case RR_Rotate_0:
-	case RR_Rotate_90:
-	case RR_Rotate_180:
-	case RR_Rotate_270:
-	    break;
-	default:
-	    /*
-	     * Invalid rotation
-	     */
-	    client->errorValue = stuff->rotation;
-	    if (outputs)
-		xfree (outputs);
-	    return BadValue;
-	}
-    
+	client->errorValue = stuff->rotation;
+	if (outputs)
+	    xfree (outputs);
+	return BadValue;
+    }
+
+    if (mode)
+    {
 	if ((~crtc->rotations) & rotation)
 	{
 	    /*
diff --git a/randr/rrmode.c b/randr/rrmode.c
index 3a67486..07cd0c1 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -41,7 +41,6 @@ RRModeEqual (xRRModeInfo *a, xRRModeInfo *b)
     if (a->vTotal != b->vTotal) return FALSE;
     if (a->nameLength != b->nameLength) return FALSE;
     if (a->modeFlags != b->modeFlags) return FALSE;
-    if (a->origin != b->origin) return FALSE;
     return TRUE;
 }
 
@@ -75,6 +74,7 @@ RRModeGet (ScreenPtr	pScreen,
     memcpy (mode->name, name, modeInfo->nameLength);
     mode->name[modeInfo->nameLength] = '\0';
     mode->screen = pScreen;
+    mode->userDefined = FALSE;
 
     if (pScrPriv->numModes)
 	modes = xrealloc (pScrPriv->modes,
@@ -162,7 +162,7 @@ RRModePruneUnused (ScreenPtr pScreen)
     memcpy (unused, pScrPriv->modes, num * sizeof (RRModePtr));
     for (m = 0; m < num; m++) {
 	mode = unused[m];
-	if (mode->refcnt == 1 && mode->mode.origin != RRModeOriginUser)
+	if (mode->refcnt == 1 && !mode->userDefined)
 	    FreeResource (mode->mode.id, 0);
     }
     xfree (unused);
diff --git a/randr/rroutput.c b/randr/rroutput.c
index b252d7d..618ef1f 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -67,6 +67,7 @@ RROutputCreate (ScreenPtr   pScreen,
     output->numClones = 0;
     output->clones = NULL;
     output->numModes = 0;
+    output->numPreferred = 0;
     output->modes = NULL;
     output->properties = NULL;
     output->changed = TRUE;
@@ -120,12 +121,13 @@ RROutputSetClones (RROutputPtr  output,
 Bool
 RROutputSetModes (RROutputPtr	output,
 		  RRModePtr	*modes,
-		  int		numModes)
+		  int		numModes,
+		  int		numPreferred)
 {
     RRModePtr	*newModes;
     int		i;
 
-    if (numModes == output->numModes)
+    if (numModes == output->numModes && numPreferred == output->numPreferred)
     {
 	for (i = 0; i < numModes; i++)
 	    if (output->modes[i] != modes[i])
@@ -155,6 +157,7 @@ RROutputSetModes (RROutputPtr	output,
     memcpy (newModes, modes, numModes * sizeof (RRModePtr));
     output->modes = newModes;
     output->numModes = numModes;
+    output->numPreferred = numPreferred;
     output->changed = TRUE;
     return TRUE;
 }
@@ -341,10 +344,10 @@ ProcRRGetOutputInfo (ClientPtr client)
     rep.subpixelOrder = output->subpixelOrder;
     rep.nCrtcs = output->numCrtcs;
     rep.nModes = output->numModes;
+    rep.nPreferred = output->numPreferred;
     rep.nClones = output->numClones;
     rep.nameLength = output->nameLength;
     rep.possibleOptions = output->possibleOptions;
-    rep.pad1 = 42;
     
     extraLen = ((output->numCrtcs + 
 		 output->numModes + 
commit 0f37ee35a8edb8de442e4de050607f041f39d7a5
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Tue Oct 3 21:06:11 2006 -0700

    Add mode origins and output options. Fix memmoves in resource free funcs.
    
    Output options and mode origins both affected driver ABI.  memmove mistakes
    were causing 'Freeing resource which isn't there' messages.
    
    Prune unused non-user defined modes from available list now.

diff --git a/randr/mirandr.c b/randr/mirandr.c
index bcc8e0f..7300cfe 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -52,7 +52,7 @@ miRRCrtcSet (ScreenPtr	pScreen,
 	     int	y,
 	     Rotation	rotation,
 	     int	numOutput,
-	     RROutputPtr    *outputs)
+	     RROutputConfigPtr    outputs)
 {
     return TRUE;
 }
@@ -114,6 +114,10 @@ miRandRInit (ScreenPtr pScreen)
 	return FALSE;
     if (!RROutputSetCrtcs (output, &crtc, 1))
 	return FALSE;
+    if (!RROutputSetPossibleOptions (output, 0))
+	return FALSE;
+    if (!RROutputSetCurrentOptions (output, 0))
+	return FALSE;
     if (!RROutputSetConnection (output, RR_Connected))
 	return FALSE;
     RRCrtcNotify (crtc, mode, 0, 0, RR_Rotate_0, 1, &output);
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 0b8c61e..a4e5589 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -72,12 +72,14 @@ extern int (*SProcRandrVector[RRNumberRequests])(ClientPtr);
 typedef struct _rrMode	    RRModeRec, *RRModePtr;
 typedef struct _rrCrtc	    RRCrtcRec, *RRCrtcPtr;
 typedef struct _rrOutput    RROutputRec, *RROutputPtr;
+typedef struct _rrOutputConfig	RROutputConfigRec, *RROutputConfigPtr;
 
 struct _rrMode {
     int		    refcnt;
     xRRModeInfo	    mode;
     char	    *name;
     void	    *devPrivate;
+    ScreenPtr	    screen;
 };
 
 struct _rrCrtc {
@@ -105,6 +107,8 @@ struct _rrOutput {
     CARD8	    connection;
     CARD8	    subpixelOrder;
     RRCrtcPtr	    crtc;
+    CARD32	    currentOptions;
+    CARD32	    possibleOptions;
     int		    numCrtcs;
     RRCrtcPtr	    *crtcs;
     int		    numClones;
@@ -116,6 +120,11 @@ struct _rrOutput {
     void	    *devPrivate;
 };
 
+struct _rrOutputConfig {
+    RROutputPtr	    output;
+    CARD32	    options;
+};
+
 #if RANDR_12_INTERFACE
 typedef Bool (*RRScreenSetSizeProcPtr) (ScreenPtr	pScreen,
 					CARD16		width,
@@ -130,7 +139,7 @@ typedef Bool (*RRCrtcSetProcPtr) (ScreenPtr		pScreen,
 				  int			y,
 				  Rotation		rotation,
 				  int			numOutputs,
-				  RROutputPtr		*outputs);
+				  RROutputConfigPtr	outputs);
 
 typedef Bool (*RRCrtcSetGammaProcPtr) (ScreenPtr	pScreen,
 				       RRCrtcPtr	crtc);
@@ -352,7 +361,7 @@ miRRCrtcSet (ScreenPtr	pScreen,
 	     int	y,
 	     Rotation	rotation,
 	     int	numOutput,
-	     RROutputPtr    *outputs);
+	     RROutputConfigPtr    outputs);
 
 /* randr.c */
 /*
@@ -440,7 +449,7 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	      int	    x,
 	      int	    y,
 	      Rotation	    rotation,
-	      int	    numOutput,
+	      int	    numOutputs,
 	      RROutputPtr   *outputs);
 
 void
@@ -456,7 +465,7 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	   int		y,
 	   Rotation	rotation,
 	   int		numOutput,
-	   RROutputPtr  *outputs);
+	   RROutputConfigPtr  outputs);
 
 /*
  * Request that the Crtc gamma be changed
@@ -530,6 +539,9 @@ RRModeGet (ScreenPtr	pScreen,
 	   xRRModeInfo	*modeInfo,
 	   const char	*name);
 
+void
+RRModePruneUnused (ScreenPtr pScreen);
+
 /*
  * Destroy a mode.
  */
@@ -584,6 +596,10 @@ RROutputSetCrtcs (RROutputPtr	output,
 		  RRCrtcPtr	*crtcs,
 		  int		numCrtcs);
 
+Bool
+RROutputSetPossibleOptions (RROutputPtr	output,
+			    CARD32	possibleOptions);
+
 void
 RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc);
     
@@ -595,6 +611,10 @@ Bool
 RROutputSetSubpixelOrder (RROutputPtr output,
 			  int	      subpixelOrder);
 
+Bool
+RROutputSetCurrentOptions (RROutputPtr output,
+			   CARD32      currentOptions);
+
 void
 RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output);
 
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 77cba29..3108f14 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -92,25 +92,25 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
     
     if (numOutputs != prevNumOutputs)
     {
-	RROutputPtr *outputs;
+	RROutputPtr *newoutputs;
 	
 	if (numOutputs)
 	{
 	    if (crtc->numOutputs)
-		outputs = xrealloc (crtc->outputs,
+		newoutputs = xrealloc (crtc->outputs,
 				    numOutputs * sizeof (RROutputPtr));
 	    else
-		outputs = xalloc (numOutputs * sizeof (RROutputPtr));
-	    if (!outputs)
+		newoutputs = xalloc (numOutputs * sizeof (RROutputPtr));
+	    if (!newoutputs)
 		return FALSE;
 	}
 	else
 	{
 	    if (crtc->outputs)
 		xfree (crtc->outputs);
-	    outputs = NULL;
+	    newoutputs = NULL;
 	}
-	crtc->outputs = outputs;
+	crtc->outputs = newoutputs;
 	crtc->numOutputs = numOutputs;
     }
     for (i = 0; i < numOutputs; i++)
@@ -183,7 +183,7 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	   int		y,
 	   Rotation	rotation,
 	   int		numOutputs,
-	   RROutputPtr  *outputs)
+	   RROutputConfigPtr  outputs)
 {
     ScreenPtr	pScreen = crtc->pScreen;
     rrScrPriv(pScreen);
@@ -252,7 +252,7 @@ RRCrtcDestroyResource (pointer value, XID pid)
     {
 	if (pScrPriv->crtcs[i] == crtc)
 	{
-	    memmove (pScrPriv->crtcs, pScrPriv->crtcs + 1,
+	    memmove (pScrPriv->crtcs + i, pScrPriv->crtcs + i + 1,
 		     (pScrPriv->numCrtcs - (i - 1)) * sizeof (RRCrtcPtr));
 	    --pScrPriv->numCrtcs;
 	    break;
@@ -458,15 +458,15 @@ ProcRRSetCrtcConfig (ClientPtr client)
     RRCrtcPtr		    crtc;
     RRModePtr		    mode;
     int			    numOutputs;
-    RROutputPtr		    *outputs = NULL;
-    RROutput		    *outputIds;
+    RROutputConfigPtr	    outputs = NULL;
+    xRROutputConfig 	    *outputConfigs;
     TimeStamp		    configTime;
     TimeStamp		    time;
     Rotation		    rotation;
     int			    i, j;
     
     REQUEST_AT_LEAST_SIZE(xRRSetCrtcConfigReq);
-    numOutputs = stuff->length - (SIZEOF (xRRSetCrtcConfigReq) >> 2);
+    numOutputs = (stuff->length - (SIZEOF (xRRSetCrtcConfigReq) >> 2)) >> 1;
     
     crtc = LookupIDByType (stuff->crtc, RRCrtcType);
     if (!crtc)
@@ -493,39 +493,47 @@ ProcRRSetCrtcConfig (ClientPtr client)
     }
     if (numOutputs)
     {
-	outputs = xalloc (numOutputs * sizeof (RROutputPtr));
+	outputs = xalloc (numOutputs * sizeof (RROutputConfigRec));
 	if (!outputs)
 	    return BadAlloc;
     }
     else
 	outputs = NULL;
     
-    outputIds = (RROutput *) (stuff + 1);
+    outputConfigs = (xRROutputConfig *) (stuff + 1);
     for (i = 0; i < numOutputs; i++)
     {
-	outputs[i] = LookupIDByType (outputIds[i], RROutputType);
-	if (!outputs[i])
+	outputs[i].output = LookupIDByType (outputConfigs[i].output, RROutputType);
+	if (!outputs[i].output)
 	{
-	    client->errorValue = outputIds[i];
+	    client->errorValue = outputConfigs[i].output;
 	    if (outputs)
 		xfree (outputs);
 	    return RRErrorBase + BadRROutput;
 	}
+	outputs[i].options = outputConfigs[i].options;
+	if (outputs[i].options & ~outputs[i].output->possibleOptions)
+	{
+	    client->errorValue = outputConfigs[i].options;
+	    if (outputs)
+		xfree (outputs);
+	    return BadMatch;
+	}
 	/* validate crtc for this output */
-	for (j = 0; j < outputs[i]->numCrtcs; j++)
-	    if (outputs[i]->crtcs[j] == crtc)
+	for (j = 0; j < outputs[i].output->numCrtcs; j++)
+	    if (outputs[i].output->crtcs[j] == crtc)
 		break;
-	if (j == outputs[j]->numCrtcs)
+	if (j == outputs[j].output->numCrtcs)
 	{
 	    if (outputs)
 		xfree (outputs);
 	    return BadMatch;
 	}
 	/* validate mode for this output */
-	for (j = 0; j < outputs[i]->numModes; j++)
-	    if (outputs[i]->modes[j] == mode)
+	for (j = 0; j < outputs[i].output->numModes; j++)
+	    if (outputs[i].output->modes[j] == mode)
 		break;
-	if (j == outputs[i]->numModes)
+	if (j == outputs[i].output->numModes)
 	{
 	    if (outputs)
 		xfree (outputs);
diff --git a/randr/rrinfo.c b/randr/rrinfo.c
index 491ac21..6fd4ee5 100644
--- a/randr/rrinfo.c
+++ b/randr/rrinfo.c
@@ -208,6 +208,7 @@ RRGetInfo (ScreenPtr pScreen)
     if (pScrPriv->nSizes)
 	RRScanOldConfig (pScreen, rotations);
 #endif
+    RRModePruneUnused (pScreen);
     RRTellChanged (pScreen);
     return TRUE;
 }
diff --git a/randr/rrmode.c b/randr/rrmode.c
index 23ac530..3a67486 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -24,6 +24,27 @@
 
 RESTYPE	RRModeType;
 
+static Bool
+RRModeEqual (xRRModeInfo *a, xRRModeInfo *b)
+{
+    if (a->width != b->width) return FALSE;
+    if (a->height != b->height) return FALSE;
+    if (a->mmWidth != b->mmWidth) return FALSE;
+    if (a->mmHeight != b->mmHeight) return FALSE;
+    if (a->dotClock != b->dotClock) return FALSE;
+    if (a->hSyncStart != b->hSyncStart) return FALSE;
+    if (a->hSyncEnd != b->hSyncEnd) return FALSE;
+    if (a->hTotal != b->hTotal) return FALSE;
+    if (a->hSkew != b->hSkew) return FALSE;
+    if (a->vSyncStart != b->vSyncStart) return FALSE;
+    if (a->vSyncEnd != b->vSyncEnd) return FALSE;
+    if (a->vTotal != b->vTotal) return FALSE;
+    if (a->nameLength != b->nameLength) return FALSE;
+    if (a->modeFlags != b->modeFlags) return FALSE;
+    if (a->origin != b->origin) return FALSE;
+    return TRUE;
+}
+
 RRModePtr
 RRModeGet (ScreenPtr	pScreen,
 	   xRRModeInfo	*modeInfo,
@@ -37,8 +58,7 @@ RRModeGet (ScreenPtr	pScreen,
     for (i = 0; i < pScrPriv->numModes; i++)
     {
 	mode = pScrPriv->modes[i];
-	modeInfo->id = mode->mode.id;
-	if (!memcmp (modeInfo, &mode->mode, sizeof (xRRModeInfo)) &&
+	if (RRModeEqual (&mode->mode, modeInfo) &&
 	    !memcmp (name, mode->name, modeInfo->nameLength))
 	{
 	    ++mode->refcnt;
@@ -54,6 +74,7 @@ RRModeGet (ScreenPtr	pScreen,
     mode->name = (char *) (mode + 1);
     memcpy (mode->name, name, modeInfo->nameLength);
     mode->name[modeInfo->nameLength] = '\0';
+    mode->screen = pScreen;
 
     if (pScrPriv->numModes)
 	modes = xrealloc (pScrPriv->modes,
@@ -80,8 +101,31 @@ RRModeGet (ScreenPtr	pScreen,
 void
 RRModeDestroy (RRModePtr mode)
 {
+    ScreenPtr	    pScreen;
+    rrScrPrivPtr    pScrPriv;
+    int	m;
+    
     if (--mode->refcnt > 0)
 	return;
+    pScreen = mode->screen;
+    pScrPriv = rrGetScrPriv (pScreen);
+    for (m = 0; m < pScrPriv->numModes; m++)
+    {
+	if (pScrPriv->modes[m] == mode)
+	{
+	    memmove (pScrPriv->modes + m, pScrPriv->modes + m + 1,
+		     (pScrPriv->numModes - m - 1) * sizeof (RRModePtr));
+	    pScrPriv->numModes--;
+	    if (!pScrPriv->numModes)
+	    {
+		xfree (pScrPriv->modes);
+		pScrPriv->modes = NULL;
+	    }
+	    pScrPriv->changed = TRUE;
+	    break;
+	}
+    }
+    
     xfree (mode);
 }
 
@@ -104,6 +148,26 @@ RRModeInit (void)
     return TRUE;
 }
 
+void
+RRModePruneUnused (ScreenPtr pScreen)
+{
+    rrScrPriv (pScreen);
+    RRModePtr	*unused, mode;
+    int		m;
+    int		num = pScrPriv->numModes;
+
+    unused = xalloc (num * sizeof (RRModePtr));
+    if (!unused)
+	return;
+    memcpy (unused, pScrPriv->modes, num * sizeof (RRModePtr));
+    for (m = 0; m < num; m++) {
+	mode = unused[m];
+	if (mode->refcnt == 1 && mode->mode.origin != RRModeOriginUser)
+	    FreeResource (mode->mode.id, 0);
+    }
+    xfree (unused);
+}
+
 int
 ProcRRCreateMode (ClientPtr client)
 {
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 90b2b98..b252d7d 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -60,6 +60,8 @@ RROutputCreate (ScreenPtr   pScreen,
     output->connection = RR_UnknownConnection;
     output->subpixelOrder = SubPixelUnknown;
     output->crtc = NULL;
+    output->currentOptions = 0;
+    output->possibleOptions = 0;
     output->numCrtcs = 0;
     output->crtcs = NULL;
     output->numClones = 0;
@@ -190,6 +192,17 @@ RROutputSetCrtcs (RROutputPtr	output,
     return TRUE;
 }
 
+Bool
+RROutputSetPossibleOptions (RROutputPtr	output,
+			    CARD32	possibleOptions)
+{
+    if (output->possibleOptions == possibleOptions)
+	return TRUE;
+    output->possibleOptions = possibleOptions;
+    output->changed = TRUE;
+    return TRUE;
+}
+
 void
 RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc)
 {
@@ -222,6 +235,17 @@ RROutputSetSubpixelOrder (RROutputPtr output,
     return TRUE;
 }
 
+Bool
+RROutputSetCurrentOptions (RROutputPtr output,
+			   CARD32      currentOptions)
+{
+    if (output->currentOptions == currentOptions)
+	return TRUE;
+    output->currentOptions = currentOptions;
+    output->changed = TRUE;
+    return TRUE;
+}
+
 void
 RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output)
 {
@@ -248,7 +272,7 @@ RROutputDestroyResource (pointer value, XID pid)
     {
 	if (pScrPriv->outputs[i] == output)
 	{
-	    memmove (pScrPriv->outputs, pScrPriv->outputs + 1,
+	    memmove (pScrPriv->outputs + i, pScrPriv->outputs + i + 1,
 		     (pScrPriv->numOutputs - (i - 1)) * sizeof (RROutputPtr));
 	    --pScrPriv->numOutputs;
 	    break;
@@ -280,6 +304,8 @@ RROutputInit (void)
     return TRUE;
 }
 
+#define OutputInfoExtra	(SIZEOF(xRRGetOutputInfoReply) - 32)
+				
 int
 ProcRRGetOutputInfo (ClientPtr client)
 {
@@ -307,24 +333,27 @@ ProcRRGetOutputInfo (ClientPtr client)
 
     rep.type = X_Reply;
     rep.sequenceNumber = client->sequence;
-    rep.length = 0;
+    rep.length = OutputInfoExtra >> 2;
     rep.timestamp = pScrPriv->lastSetTime.milliseconds;
     rep.crtc = output->crtc ? output->crtc->id : None;
+    rep.currentOptions = output->currentOptions;
     rep.connection = output->connection;
     rep.subpixelOrder = output->subpixelOrder;
     rep.nCrtcs = output->numCrtcs;
     rep.nModes = output->numModes;
     rep.nClones = output->numClones;
     rep.nameLength = output->nameLength;
+    rep.possibleOptions = output->possibleOptions;
+    rep.pad1 = 42;
     
-    rep.length = (output->numCrtcs + 
-		  output->numModes + 
-		  output->numClones +
-		  ((rep.nameLength + 3) >> 2));
+    extraLen = ((output->numCrtcs + 
+		 output->numModes + 
+		 output->numClones +
+		 ((rep.nameLength + 3) >> 2)) << 2);
 
-    extraLen = rep.length << 2;
     if (extraLen)
     {
+	rep.length += extraLen >> 2;
 	extra = xalloc (extraLen);
 	if (!extra)
 	    return BadAlloc;
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index e382540..7b53f04 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -372,7 +372,7 @@ ProcRRGetScreenResources (ClientPtr client)
 
 	rep.length = (pScrPriv->numCrtcs + 
 		      pScrPriv->numOutputs + 
-		      pScrPriv->numModes * 10 +
+		      pScrPriv->numModes * (SIZEOF(xRRModeInfo) >> 2) +
 		      ((rep.nbytesNames + 3) >> 2));
 	
 	extraLen = rep.length << 2;
@@ -429,7 +429,7 @@ ProcRRGetScreenResources (ClientPtr client)
 		    pScrPriv->modes[i]->mode.nameLength);
 	    names += pScrPriv->modes[i]->mode.nameLength;
 	}
-	assert ((names + 3 >> 3) == rep.length);
+	assert (((((char *) names - (char *) extra) + 3) >> 2) == rep.length);
     }
     
     if (client->swapped) {
@@ -694,7 +694,7 @@ ProcRRSetScreenConfig (ClientPtr client)
     Rotation		    rotation;
     int			    rate;
     Bool		    has_rate;
-    RROutputPtr		    output;
+    RROutputConfigRec	    output;
     RRModePtr		    mode;
     RR10DataPtr		    pData = NULL;
     RRScreenSizePtr    	    pSize;
@@ -731,13 +731,14 @@ ProcRRSetScreenConfig (ClientPtr client)
     if (!RRGetInfo (pScreen))
 	return BadAlloc;
     
-    output = RRFirstOutput (pScreen);
-    if (!output)
+    output.output = RRFirstOutput (pScreen);
+    if (!output.output)
     {
 	time = currentTime;
 	rep.status = RRSetConfigFailed;
 	goto sendReply;
     }
+    output.options = output.output->currentOptions;
     
     /*
      * if the client's config timestamp is not the same as the last config
@@ -750,7 +751,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	goto sendReply;
     }
     
-    pData = RR10GetData (pScreen, output);
+    pData = RR10GetData (pScreen, output.output);
     if (!pData)
 	return BadAlloc;
     
@@ -786,7 +787,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	return BadValue;
     }
 
-    if ((~output->crtc->rotations) & rotation)
+    if ((~output.output->crtc->rotations) & rotation)
     {
 	/*
 	 * requested rotation or reflection not supported by screen
@@ -835,7 +836,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	goto sendReply;
     }
 
-    rep.status = RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation,
+    rep.status = RRCrtcSet (output.output->crtc, mode, 0, 0, stuff->rotation,
 			    1, &output);
     
 sendReply:
commit f7dcf3a6d482d4934ff7ba33826adf725103470b
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Thu Sep 21 09:52:04 2006 -0700

    When no mode is specified, don't validate mode-specific parameters.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index ebb2540..77cba29 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -564,64 +564,67 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	goto sendReply;
     }
     
-    /*
-     * Validate requested rotation
-     */
-    rotation = (Rotation) stuff->rotation;
-
-    /* test the rotation bits only! */
-    switch (rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_90:
-    case RR_Rotate_180:
-    case RR_Rotate_270:
-	break;
-    default:
-	/*
-	 * Invalid rotation
-	 */
-	client->errorValue = stuff->rotation;
-	if (outputs)
-	    xfree (outputs);
-	return BadValue;
-    }
-
-    if ((~crtc->rotations) & rotation)
+    if (mode)
     {
 	/*
-	 * requested rotation or reflection not supported by screen
+	 * Validate requested rotation
 	 */
-	client->errorValue = stuff->rotation;
-	if (outputs)
-	    xfree (outputs);
-	return BadMatch;
-    }
-
-#ifdef RANDR_12_INTERFACE
-    /*
-     * Check screen size bounds if the DDX provides a 1.2 interface
-     * for setting screen size. Else, assume the CrtcSet sets
-     * the size along with the mode
-     */
-    if (pScrPriv->rrScreenSetSize)
-    {
-	if (stuff->x + mode->mode.width > pScreen->width)
-	{
-	    client->errorValue = stuff->x;
+	rotation = (Rotation) stuff->rotation;
+    
+	/* test the rotation bits only! */
+	switch (rotation & 0xf) {
+	case RR_Rotate_0:
+	case RR_Rotate_90:
+	case RR_Rotate_180:
+	case RR_Rotate_270:
+	    break;
+	default:
+	    /*
+	     * Invalid rotation
+	     */
+	    client->errorValue = stuff->rotation;
 	    if (outputs)
 		xfree (outputs);
 	    return BadValue;
 	}
-	
-	if (stuff->y + mode->mode.height > pScreen->height)
+    
+	if ((~crtc->rotations) & rotation)
 	{
-	    client->errorValue = stuff->y;
+	    /*
+	     * requested rotation or reflection not supported by screen
+	     */
+	    client->errorValue = stuff->rotation;
 	    if (outputs)
 		xfree (outputs);
-	    return BadValue;
+	    return BadMatch;
+	}
+    
+#ifdef RANDR_12_INTERFACE
+	/*
+	 * Check screen size bounds if the DDX provides a 1.2 interface
+	 * for setting screen size. Else, assume the CrtcSet sets
+	 * the size along with the mode
+	 */
+	if (pScrPriv->rrScreenSetSize)
+	{
+	    if (stuff->x + mode->mode.width > pScreen->width)
+	    {
+		client->errorValue = stuff->x;
+		if (outputs)
+		    xfree (outputs);
+		return BadValue;
+	    }
+	    
+	    if (stuff->y + mode->mode.height > pScreen->height)
+	    {
+		client->errorValue = stuff->y;
+		if (outputs)
+		    xfree (outputs);
+		return BadValue;
+	    }
 	}
-    }
 #endif
+    }
     
     /*
      * Make sure the requested set-time is not older than
commit 817a82faaf61c481eb0874475a2e05f339c7fed1
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Wed Sep 20 22:43:05 2006 -0700

    Steal Xinerama code from SiS driver. Add missing files.
    
    Provide a Xinerama implementation when DIX version isn't enabled. This
    version exposes each crtc as a separate 'screen' and reports the size of
    that patch. The extension also sends ConfigureNotify events to the root
    window whenever crtcs change so that applications will re-fetch xinerama
    information. This actually works for metacity.

diff --git a/randr/Makefile.am b/randr/Makefile.am
index a28ead0..91c4bc6 100644
--- a/randr/Makefile.am
+++ b/randr/Makefile.am
@@ -17,4 +17,5 @@ librandr_la_SOURCES =	\
 	rroutput.c	\
 	rrproperty.c	\
 	rrscreen.c	\
-	rrsdispatch.c
+	rrsdispatch.c	\
+	rrxinerama.c
diff --git a/randr/randr.c b/randr/randr.c
index 5f54dea..4ea72e5 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -311,7 +311,7 @@ RRExtensionInit (void)
     EventSwapVector[RREventBase + RRNotify] = (EventSwapPtr)
 	SRRNotifyEvent;
 
-    return;
+    RRXineramaExtensionInit();
 }
 
 static int
diff --git a/randr/randrstr.h b/randr/randrstr.h
index e459452..0b8c61e 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -305,6 +305,12 @@ RRScreenSizeSet (ScreenPtr  pScreen,
 		 CARD32	    mmHeight);
 
 /*
+ * Send ConfigureNotify event to root window when 'something' happens
+ */
+void
+RRSendConfigNotify (ScreenPtr pScreen);
+    
+/*
  * screen dispatch
  */
 int 
@@ -629,4 +635,8 @@ ProcRRListOutputProperties (ClientPtr client);
 int
 ProcRRDeleteOutputProperty (ClientPtr client);
 
+/* rrxinerama.c */
+void
+RRXineramaExtensionInit(void);
+
 #endif /* _RANDRSTR_H_ */
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index dfa9ca6..ebb2540 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -111,6 +111,7 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	    outputs = NULL;
 	}
 	crtc->outputs = outputs;
+	crtc->numOutputs = numOutputs;
     }
     for (i = 0; i < numOutputs; i++)
     {
@@ -158,7 +159,11 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	crtc->changed = TRUE;
     }
     if (crtc->changed)
+    {
+	if (!pScrPriv->changed)
+	    RRSendConfigNotify (pScreen);
 	pScrPriv->changed = TRUE;
+    }
     return TRUE;
 }
 
diff --git a/randr/rrinfo.c b/randr/rrinfo.c
new file mode 100644
index 0000000..491ac21
--- /dev/null
+++ b/randr/rrinfo.c
@@ -0,0 +1,337 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+
+#ifdef RANDR_10_INTERFACE
+static RRModePtr
+RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
+{
+    ScreenPtr	pScreen = output->pScreen;
+    rrScrPriv(pScreen);
+    xRRModeInfo	modeInfo;
+    char	name[100];
+    RRModePtr	mode;
+    int		i;
+    RRModePtr   *modes;
+    
+    memset (&modeInfo, '\0', sizeof (modeInfo));
+    sprintf (name, "%dx%d", size->width, size->height);
+    
+    modeInfo.width = size->width;
+    modeInfo.height = size->height;
+    modeInfo.mmWidth = size->mmWidth;
+    modeInfo.mmHeight = size->mmHeight;
+    modeInfo.hTotal = size->width;
+    modeInfo.vTotal = size->height;
+    modeInfo.dotClock = ((CARD32) size->width * (CARD32) size->height *
+			 (CARD32) refresh);
+    modeInfo.nameLength = strlen (name);
+    mode = RRModeGet (pScreen, &modeInfo, name);
+    if (!mode)
+	return NULL;
+    for (i = 0; i < output->numModes; i++)
+	if (output->modes[i] == mode)
+	{
+	    RRModeDestroy (mode);
+	    return mode;
+	}
+    
+    if (output->numModes)
+	modes = xrealloc (output->modes, 
+			  (output->numModes + 1) * sizeof (RRModePtr));
+    else
+	modes = xalloc (sizeof (RRModePtr));
+    if (!modes)
+    {
+	RRModeDestroy (mode);
+	FreeResource (mode->mode.id, 0);
+	return NULL;
+    }
+    modes[output->numModes++] = mode;
+    output->modes = modes;
+    output->changed = TRUE;
+    pScrPriv->changed = TRUE;
+    return mode;
+}
+
+static void
+RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
+{
+    rrScrPriv(pScreen);
+    RROutputPtr	output;
+    RRCrtcPtr	crtc;
+    RRModePtr	mode, newMode = NULL;
+    int		i;
+    CARD16	minWidth = MAXSHORT, minHeight = MAXSHORT;
+    CARD16	maxWidth = 0, maxHeight = 0;
+    
+    /*
+     * First time through, create a crtc and output and hook
+     * them together
+     */
+    if (pScrPriv->numOutputs == 0 &&
+	pScrPriv->numCrtcs == 0)
+    {
+	crtc = RRCrtcCreate (pScreen, NULL);
+	if (!crtc)
+	    return;
+	output = RROutputCreate (pScreen, "default", 7, NULL);
+	if (!output)
+	    return;
+	RROutputSetCrtcs (output, &crtc, 1);
+	RROutputSetCrtc (output, crtc);
+	RROutputSetConnection (output, RR_Connected);
+#ifdef RENDER
+	RROutputSetSubpixelOrder (output, PictureGetSubpixelOrder (pScreen));
+#endif
+    }
+
+    output = RRFirstOutput (pScreen);
+    if (!output)
+	return;
+    crtc = output->crtc;
+
+    /* check rotations */
+    if (rotations != crtc->rotations)
+    {
+        crtc->rotations = rotations;
+	crtc->changed = TRUE;
+	pScrPriv->changed = TRUE;
+    }
+	
+    /* regenerate mode list */
+    for (i = 0; i < pScrPriv->nSizes; i++)
+    {
+	RRScreenSizePtr	size = &pScrPriv->pSizes[i];
+	int		r;
+
+	if (size->nRates)
+	{
+	    for (r = 0; r < size->nRates; r++)
+	    {
+		mode = RROldModeAdd (output, size, size->pRates[r].rate);
+		if (i == pScrPriv->size && 
+		    size->pRates[r].rate == pScrPriv->rate)
+		{
+		    newMode = mode;
+		}
+	    }
+	    xfree (size->pRates);
+	}
+	else
+	{
+	    mode = RROldModeAdd (output, size, 0);
+	    if (i == pScrPriv->size)
+		newMode = mode;
+	}
+    }
+    if (pScrPriv->nSizes)
+	xfree (pScrPriv->pSizes);
+    pScrPriv->pSizes = NULL;
+    pScrPriv->nSizes = 0;
+	    
+    /* find size bounds */
+    for (i = 0; i < output->numModes; i++) 
+    {
+	RRModePtr   mode = output->modes[i];
+        CARD16	    width = mode->mode.width;
+        CARD16	    height = mode->mode.height;
+	
+	if (width < minWidth) minWidth = width;
+	if (width > maxWidth) maxWidth = width;
+	if (height < minHeight) minHeight = height;
+	if (height > maxHeight) maxHeight = height;
+    }
+
+    if (minWidth != pScrPriv->minWidth) {
+	pScrPriv->minWidth = minWidth; pScrPriv->changed = TRUE;
+    }
+    if (maxWidth != pScrPriv->maxWidth) {
+	pScrPriv->maxWidth = maxWidth; pScrPriv->changed = TRUE;
+    }
+    if (minHeight != pScrPriv->minHeight) {
+	pScrPriv->minHeight = minHeight; pScrPriv->changed = TRUE;
+    }
+    if (maxHeight != pScrPriv->maxHeight) {
+	pScrPriv->maxHeight = maxHeight; pScrPriv->changed = TRUE;
+    }
+
+    /* notice current mode */
+    if (newMode)
+	RRCrtcNotify (output->crtc, newMode, 0, 0, pScrPriv->rotation,
+		      1, &output);
+}
+#endif
+
+/*
+ * Poll the driver for changed information
+ */
+Bool
+RRGetInfo (ScreenPtr pScreen)
+{
+    rrScrPriv (pScreen);
+    Rotation	    rotations;
+    int		    i;
+
+    for (i = 0; i < pScrPriv->numOutputs; i++)
+	pScrPriv->outputs[i]->changed = FALSE;
+    for (i = 0; i < pScrPriv->numCrtcs; i++)
+	pScrPriv->crtcs[i]->changed = FALSE;
+    
+    rotations = 0;
+    pScrPriv->changed = FALSE;
+    
+    if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
+	return FALSE;
+
+#if RANDR_10_INTERFACE
+    if (pScrPriv->nSizes)
+	RRScanOldConfig (pScreen, rotations);
+#endif
+    RRTellChanged (pScreen);
+    return TRUE;
+}
+
+#if RANDR_12_INTERFACE
+/*
+ * Register the range of sizes for the screen
+ */
+void
+RRScreenSetSizeRange (ScreenPtr	pScreen,
+		      CARD16	minWidth,
+		      CARD16	minHeight,
+		      CARD16	maxWidth,
+		      CARD16	maxHeight)
+{
+    rrScrPriv (pScreen);
+
+    if (!pScrPriv)
+	return;
+    pScrPriv->minWidth  = minWidth;
+    pScrPriv->minHeight = minHeight;
+    pScrPriv->maxWidth  = maxWidth;
+    pScrPriv->maxHeight = maxHeight;
+}
+#endif
+
+#ifdef RANDR_10_INTERFACE
+static Bool
+RRScreenSizeMatches (RRScreenSizePtr  a,
+		   RRScreenSizePtr  b)
+{
+    if (a->width != b->width)
+	return FALSE;
+    if (a->height != b->height)
+	return FALSE;
+    if (a->mmWidth != b->mmWidth)
+	return FALSE;
+    if (a->mmHeight != b->mmHeight)
+	return FALSE;
+    return TRUE;
+}
+
+RRScreenSizePtr
+RRRegisterSize (ScreenPtr	    pScreen,
+		short		    width, 
+		short		    height,
+		short		    mmWidth,
+		short		    mmHeight)
+{
+    rrScrPriv (pScreen);
+    int		    i;
+    RRScreenSize    tmp;
+    RRScreenSizePtr pNew;
+
+    if (!pScrPriv)
+	return 0;
+    
+    tmp.id = 0;
+    tmp.width = width;
+    tmp.height= height;
+    tmp.mmWidth = mmWidth;
+    tmp.mmHeight = mmHeight;
+    tmp.pRates = 0;
+    tmp.nRates = 0;
+    for (i = 0; i < pScrPriv->nSizes; i++)
+	if (RRScreenSizeMatches (&tmp, &pScrPriv->pSizes[i]))
+	    return &pScrPriv->pSizes[i];
+    pNew = xrealloc (pScrPriv->pSizes,
+		     (pScrPriv->nSizes + 1) * sizeof (RRScreenSize));
+    if (!pNew)
+	return 0;
+    pNew[pScrPriv->nSizes++] = tmp;
+    pScrPriv->pSizes = pNew;
+    return &pNew[pScrPriv->nSizes-1];
+}
+
+Bool RRRegisterRate (ScreenPtr		pScreen,
+		     RRScreenSizePtr	pSize,
+		     int		rate)
+{
+    rrScrPriv(pScreen);
+    int		    i;
+    RRScreenRatePtr pNew, pRate;
+
+    if (!pScrPriv)
+	return FALSE;
+    
+    for (i = 0; i < pSize->nRates; i++)
+	if (pSize->pRates[i].rate == rate)
+	    return TRUE;
+
+    pNew = xrealloc (pSize->pRates,
+		     (pSize->nRates + 1) * sizeof (RRScreenRate));
+    if (!pNew)
+	return FALSE;
+    pRate = &pNew[pSize->nRates++];
+    pRate->rate = rate;
+    pSize->pRates = pNew;
+    return TRUE;
+}
+
+Rotation
+RRGetRotation(ScreenPtr pScreen)
+{
+    RROutputPtr	output = RRFirstOutput (pScreen);
+
+    if (!output)
+	return RR_Rotate_0;
+
+    return output->crtc->rotation;
+}
+
+void
+RRSetCurrentConfig (ScreenPtr		pScreen,
+		    Rotation		rotation,
+		    int			rate,
+		    RRScreenSizePtr	pSize)
+{
+    rrScrPriv (pScreen);
+
+    if (!pScrPriv)
+	return;
+    pScrPriv->size = pSize - pScrPriv->pSizes;
+    pScrPriv->rotation = rotation;
+    pScrPriv->rate = rate;
+}
+#endif
diff --git a/randr/rrproperty.c b/randr/rrproperty.c
new file mode 100644
index 0000000..cdafb5c
--- /dev/null
+++ b/randr/rrproperty.c
@@ -0,0 +1,430 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+#include "propertyst.h"
+#include "swaprep.h"
+
+static void
+RRDeliverEvent (ScreenPtr pScreen, xEvent *event, CARD32 mask)
+{
+}
+
+void
+RRDeleteAllOutputProperties (RROutputPtr output)
+{
+    PropertyPtr prop, next;
+    xRROutputPropertyNotifyEvent    event;
+
+    for (prop = output->properties; prop; prop = next)
+    {
+	next = prop->next;
+	event.type = RREventBase + RRNotify;
+	event.subCode = RRNotify_OutputProperty;
+	event.output = output->id;
+	event.state = PropertyDelete;
+	event.atom = prop->propertyName;
+	event.timestamp = currentTime.milliseconds;
+	RRDeliverEvent (output->pScreen, (xEvent *) &event, RROutputPropertyNotifyMask);
+        xfree(prop->data);
+        xfree(prop);
+    }
+}
+
+void
+RRDeleteOutputProperty (RROutputPtr output, Atom property)
+{
+    PropertyPtr	prop, *prev;
+    xRROutputPropertyNotifyEvent    event;
+
+    for (prev = &output->properties; (prop = *prev); prev = &(prop->next))
+	if (prop->propertyName == property)
+	    break;
+    if (prop)
+    {
+	*prev = prop->next;
+	event.type = RREventBase + RRNotify;
+	event.subCode = RRNotify_OutputProperty;
+	event.output = output->id;
+	event.state = PropertyDelete;
+	event.atom = prop->propertyName;
+	event.timestamp = currentTime.milliseconds;
+	RRDeliverEvent (output->pScreen, (xEvent *) &event, RROutputPropertyNotifyMask);
+        xfree(prop->data);
+        xfree(prop);
+    }
+}
+
+int
+RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
+			int format, int mode, unsigned long len,
+			pointer value, Bool sendevent)
+{
+    PropertyPtr			    prop;
+    xRROutputPropertyNotifyEvent    event;
+    int				    sizeInBytes;
+    int				    totalSize;
+    pointer			    data;
+
+    sizeInBytes = format >> 3;
+    totalSize = len * sizeInBytes;
+
+    /* first see if property already exists */
+
+    for (prop = output->properties; prop; prop = prop->next)
+	if (prop->propertyName == property)
+	    break;
+    
+    if (!prop)   /* just add to list */
+    {
+        prop = (PropertyPtr)xalloc(sizeof(PropertyRec));
+	if (!prop)
+	    return(BadAlloc);
+        data = (pointer)xalloc(totalSize);
+	if (!data && len)
+	{
+	    xfree(prop);
+	    return(BadAlloc);
+	}
+        prop->propertyName = property;
+        prop->type = type;
+        prop->format = format;
+        prop->data = data;
+	if (len)
+	    memmove((char *)data, (char *)value, totalSize);
+	prop->size = len;
+        prop->next = output->properties;
+        output->properties = prop;
+    }
+    else
+    {
+	/* To append or prepend to a property the request format and type
+		must match those of the already defined property.  The
+		existing format and type are irrelevant when using the mode
+		"PropModeReplace" since they will be written over. */
+
+        if ((format != prop->format) && (mode != PropModeReplace))
+	    return(BadMatch);
+        if ((prop->type != type) && (mode != PropModeReplace))
+            return(BadMatch);
+        if (mode == PropModeReplace)
+        {
+	    if (totalSize != prop->size * (prop->format >> 3))
+	    {
+	    	data = (pointer)xrealloc(prop->data, totalSize);
+	    	if (!data && len)
+		    return(BadAlloc);
+            	prop->data = data;
+	    }
+	    if (len)
+		memmove((char *)prop->data, (char *)value, totalSize);
+	    prop->size = len;
+    	    prop->type = type;
+	    prop->format = format;
+	}
+	else if (len == 0)
+	{
+	    /* do nothing */
+	}
+        else if (mode == PropModeAppend)
+        {
+	    data = (pointer)xrealloc(prop->data,
+				     sizeInBytes * (len + prop->size));
+	    if (!data)
+		return(BadAlloc);
+            prop->data = data;
+	    memmove(&((char *)data)[prop->size * sizeInBytes], 
+		    (char *)value,
+		  totalSize);
+            prop->size += len;
+	}
+        else if (mode == PropModePrepend)
+        {
+            data = (pointer)xalloc(sizeInBytes * (len + prop->size));
+	    if (!data)
+		return(BadAlloc);
+	    memmove(&((char *)data)[totalSize], (char *)prop->data, 
+		  (int)(prop->size * sizeInBytes));
+            memmove((char *)data, (char *)value, totalSize);
+	    xfree(prop->data);
+            prop->data = data;
+            prop->size += len;
+	}
+    }
+    if (sendevent)
+    {
+	event.type = RREventBase + RRNotify;
+	event.subCode = RRNotify_OutputProperty;
+	event.output = output->id;
+	event.state = PropertyNewValue;
+	event.atom = prop->propertyName;
+	event.timestamp = currentTime.milliseconds;
+	RRDeliverEvent (output->pScreen, (xEvent *) &event, RROutputPropertyNotifyMask);
+    }
+    return(Success);
+}
+
+int
+ProcRRListOutputProperties (ClientPtr client)
+{
+    REQUEST(xRRListOutputPropertiesReq);
+    Atom			    *pAtoms = NULL, *temppAtoms;
+    xRRListOutputPropertiesReply    rep;
+    int				    numProps = 0;
+    RROutputPtr			    output;
+    PropertyPtr			    prop;
+    
+    REQUEST_SIZE_MATCH(xRRListOutputPropertiesReq);
+
+    output = LookupOutput (client, stuff->output, SecurityReadAccess);
+    
+    if (!output)
+        return RRErrorBase + BadRROutput;
+
+    for (prop = output->properties; prop; prop = prop->next)
+	numProps++;
+    if (numProps)
+        if(!(pAtoms = (Atom *)ALLOCATE_LOCAL(numProps * sizeof(Atom))))
+            return(BadAlloc);
+
+    rep.type = X_Reply;
+    rep.nProperties = numProps;
+    rep.length = (numProps * sizeof(Atom)) >> 2;
+    rep.sequenceNumber = client->sequence;
+    temppAtoms = pAtoms;
+    for (prop = output->properties; prop; prop = prop->next)
+	*temppAtoms++ = prop->propertyName;
+
+    WriteReplyToClient(client, sizeof(xRRListOutputPropertiesReply), &rep);
+    if (numProps)
+    {
+        client->pSwapReplyFunc = (ReplySwapPtr)Swap32Write;
+        WriteSwappedDataToClient(client, numProps * sizeof(Atom), pAtoms);
+        DEALLOCATE_LOCAL(pAtoms);
+    }
+    return(client->noClientException);
+}
+
+int
+ProcRRChangeOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRChangeOutputPropertyReq);
+    RROutputPtr	    output;
+    char	    format, mode;
+    unsigned long   len;
+    int		    sizeInBytes;
+    int		    totalSize;
+    int		    err;
+
+    REQUEST_AT_LEAST_SIZE(xRRChangeOutputPropertyReq);
+    UpdateCurrentTime();
+    format = stuff->format;
+    mode = stuff->mode;
+    if ((mode != PropModeReplace) && (mode != PropModeAppend) &&
+	(mode != PropModePrepend))
+    {
+	client->errorValue = mode;
+	return BadValue;
+    }
+    if ((format != 8) && (format != 16) && (format != 32))
+    {
+	client->errorValue = format;
+        return BadValue;
+    }
+    len = stuff->nUnits;
+    if (len > ((0xffffffff - sizeof(xChangePropertyReq)) >> 2))
+	return BadLength;
+    sizeInBytes = format>>3;
+    totalSize = len * sizeInBytes;
+    REQUEST_FIXED_SIZE(xRRChangeOutputPropertyReq, totalSize);
+
+    output = LookupOutput (client, stuff->output, SecurityWriteAccess);
+    if (!output)
+	return RRErrorBase + BadRROutput;
+    
+    if (!ValidAtom(stuff->property))
+    {
+	client->errorValue = stuff->property;
+	return(BadAtom);
+    }
+    if (!ValidAtom(stuff->type))
+    {
+	client->errorValue = stuff->type;
+	return(BadAtom);
+    }
+
+    err = RRChangeOutputProperty(output, stuff->property,
+				 stuff->type, (int)format,
+				 (int)mode, len, (pointer)&stuff[1], TRUE);
+    if (err != Success)
+	return err;
+    else
+	return client->noClientException;
+}
+
+int
+ProcRRDeleteOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRDeleteOutputPropertyReq);
+    RROutputPtr	output;
+              
+    REQUEST_SIZE_MATCH(xRRDeleteOutputPropertyReq);
+    UpdateCurrentTime();
+    output = LookupOutput (client, stuff->output, SecurityWriteAccess);
+    if (!output)
+        return RRErrorBase + BadRROutput;
+    
+    if (!ValidAtom(stuff->property))
+    {
+	client->errorValue = stuff->property;
+	return (BadAtom);
+    }
+
+
+    RRDeleteOutputProperty(output, stuff->property);
+    return client->noClientException;
+}
+
+int
+ProcRRGetOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRGetOutputPropertyReq);
+    PropertyPtr			prop, *prev;
+    unsigned long		n, len, ind;
+    RROutputPtr			output;
+    xRRGetOutputPropertyReply	reply;
+
+    REQUEST_SIZE_MATCH(xRRGetOutputPropertyReq);
+    if (stuff->delete)
+	UpdateCurrentTime();
+    output = LookupOutput (client, stuff->output, 
+			   stuff->delete ? SecurityWriteAccess :
+			   SecurityReadAccess);
+    if (!output)
+	return RRErrorBase + BadRROutput;
+
+    if (!ValidAtom(stuff->property))
+    {
+	client->errorValue = stuff->property;
+	return(BadAtom);
+    }
+    if ((stuff->delete != xTrue) && (stuff->delete != xFalse))
+    {
+	client->errorValue = stuff->delete;
+	return(BadValue);
+    }
+    if ((stuff->type != AnyPropertyType) && !ValidAtom(stuff->type))
+    {
+	client->errorValue = stuff->type;
+	return(BadAtom);
+    }
+
+    for (prev = &output->properties; (prop = *prev); prev = &prop->next)
+	if (prop->propertyName == stuff->property) 
+	    break;
+
+    reply.type = X_Reply;
+    reply.sequenceNumber = client->sequence;
+    if (!prop) 
+    {
+	reply.nItems = 0;
+	reply.length = 0;
+	reply.bytesAfter = 0;
+	reply.propertyType = None;
+	reply.format = 0;
+	WriteReplyToClient(client, sizeof(xRRGetOutputPropertyReply), &reply);
+	return(client->noClientException);
+    }
+
+    /* If the request type and actual type don't match. Return the
+    property information, but not the data. */
+
+    if (((stuff->type != prop->type) &&
+	 (stuff->type != AnyPropertyType))
+       )
+    {
+	reply.bytesAfter = prop->size;
+	reply.format = prop->format;
+	reply.length = 0;
+	reply.nItems = 0;
+	reply.propertyType = prop->type;
+	WriteReplyToClient(client, sizeof(xRRGetOutputPropertyReply), &reply);
+	return(client->noClientException);
+    }
+
+/*
+ *  Return type, format, value to client
+ */
+    n = (prop->format/8) * prop->size; /* size (bytes) of prop */
+    ind = stuff->longOffset << 2;        
+
+   /* If longOffset is invalid such that it causes "len" to
+	    be negative, it's a value error. */
+
+    if (n < ind)
+    {
+	client->errorValue = stuff->longOffset;
+	return BadValue;
+    }
+
+    len = min(n - ind, 4 * stuff->longLength);
+
+    reply.bytesAfter = n - (ind + len);
+    reply.format = prop->format;
+    reply.length = (len + 3) >> 2;
+    reply.nItems = len / (prop->format / 8 );
+    reply.propertyType = prop->type;
+
+    if (stuff->delete && (reply.bytesAfter == 0))
+    {
+	xRROutputPropertyNotifyEvent    event;
+
+	event.type = RREventBase + RRNotify;
+	event.subCode = RRNotify_OutputProperty;
+	event.output = output->id;
+	event.state = PropertyDelete;
+	event.atom = prop->propertyName;
+	event.timestamp = currentTime.milliseconds;
+	RRDeliverEvent (output->pScreen, (xEvent *) &event, RROutputPropertyNotifyMask);
+    }
+
+    WriteReplyToClient(client, sizeof(xGenericReply), &reply);
+    if (len)
+    {
+	switch (reply.format) {
+	case 32: client->pSwapReplyFunc = (ReplySwapPtr)CopySwap32Write; break;
+	case 16: client->pSwapReplyFunc = (ReplySwapPtr)CopySwap16Write; break;
+	default: client->pSwapReplyFunc = (ReplySwapPtr)WriteToClient; break;
+	}
+	WriteSwappedDataToClient(client, len,
+				 (char *)prop->data + ind);
+    }
+
+    if (stuff->delete && (reply.bytesAfter == 0))
+    { /* delete the Property */
+	*prev = prop->next;
+	xfree(prop->data);
+	xfree(prop);
+    }
+    return(client->noClientException);
+}
+
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index e59947b..e382540 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -69,7 +69,7 @@ RREditConnectionInfo (ScreenPtr pScreen)
     root->mmHeight = pScreen->mmHeight;
 }
 
-static void
+void
 RRSendConfigNotify (ScreenPtr pScreen)
 {
     WindowPtr	pWin = WindowTable[pScreen->myNum];
diff --git a/randr/rrxinerama.c b/randr/rrxinerama.c
new file mode 100644
index 0000000..31f60cc
--- /dev/null
+++ b/randr/rrxinerama.c
@@ -0,0 +1,424 @@
+/*
+ * 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.
+ */
+/*
+ * This Xinerama implementation comes from the SiS driver which has
+ * the following notice:
+ */
+/* 
+ * SiS driver main code
+ *
+ * Copyright (C) 2001-2005 by Thomas Winischhofer, Vienna, Austria.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1) Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2) Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3) The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Author: Thomas Winischhofer <thomas at winischhofer.net>
+ *	- driver entirely rewritten since 2001, only basic structure taken from
+ *	  old code (except sis_dri.c, sis_shadow.c, sis_accel.c and parts of
+ *	  sis_dga.c; these were mostly taken over; sis_dri.c was changed for
+ *	  new versions of the DRI layer)
+ *
+ * This notice covers the entire driver code unless indicated otherwise.
+ *
+ * Formerly based on code which was
+ * 	     Copyright (C) 1998, 1999 by Alan Hourihane, Wigan, England.
+ * 	     Written by:
+ *           Alan Hourihane <alanh at fairlite.demon.co.uk>,
+ *           Mike Chapman <mike at paranoia.com>,
+ *           Juanjo Santamarta <santamarta at ctv.es>,
+ *           Mitani Hiroshi <hmitani at drl.mei.co.jp>,
+ *           David Thomas <davtom at dream.org.uk>.
+ */
+
+#include "randrstr.h"
+#include "swaprep.h"
+#include <X11/extensions/panoramiXproto.h>
+
+#define RR_XINERAMA_MAJOR_VERSION   1
+#define RR_XINERAMA_MINOR_VERSION   1
+
+/* Xinerama is not multi-screen capable; just report about screen 0 */
+#define RR_XINERAMA_SCREEN  0
+
+static int ProcRRXineramaQueryVersion(ClientPtr client);
+static int ProcRRXineramaGetState(ClientPtr client);
+static int ProcRRXineramaGetScreenCount(ClientPtr client);
+static int ProcRRXineramaGetScreenSize(ClientPtr client);
+static int ProcRRXineramaIsActive(ClientPtr client);
+static int ProcRRXineramaQueryScreens(ClientPtr client);
+static int SProcRRXineramaDispatch(ClientPtr client);
+
+/* Proc */
+
+int
+ProcRRXineramaQueryVersion(ClientPtr client)
+{
+    xPanoramiXQueryVersionReply	  rep;
+    register int		  n;
+
+    REQUEST_SIZE_MATCH(xPanoramiXQueryVersionReq);
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.majorVersion = RR_XINERAMA_MAJOR_VERSION;
+    rep.minorVersion = RR_XINERAMA_MINOR_VERSION;
+    if(client->swapped) {
+        swaps(&rep.sequenceNumber, n);
+        swapl(&rep.length, n);
+        swaps(&rep.majorVersion, n);
+        swaps(&rep.minorVersion, n);
+    }
+    WriteToClient(client, sizeof(xPanoramiXQueryVersionReply), (char *)&rep);
+    return (client->noClientException);
+}
+
+int
+ProcRRXineramaGetState(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetStateReq);
+    WindowPtr			pWin;
+    xPanoramiXGetStateReply	rep;
+    register int		n;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    Bool			active = FALSE;
+
+    REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
+    pWin = LookupWindow(stuff->window, client);
+    if(!pWin) return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    if (pScrPriv)
+    {
+	/* XXX do we need more than this? */
+	active = TRUE;
+    }
+
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.state = active;
+    if(client->swapped) {
+       swaps (&rep.sequenceNumber, n);
+       swapl (&rep.length, n);
+       swaps (&rep.state, n);
+    }
+    WriteToClient(client, sizeof(xPanoramiXGetStateReply), (char *)&rep);
+    return client->noClientException;
+}
+
+static Bool
+RRXineramaScreenActive (ScreenPtr pScreen)
+{
+    return rrGetScrPriv(pScreen) != NULL;
+}
+
+static Bool
+RRXineramaCrtcActive (RRCrtcPtr crtc)
+{
+    return crtc->mode != NULL && crtc->numOutputs > 0;
+}
+
+static int
+RRXineramaScreenCount (ScreenPtr pScreen)
+{
+    int	i, n;
+    
+    n = 0;
+    if (RRXineramaScreenActive (pScreen))
+    {
+	rrScrPriv(pScreen);
+	for (i = 0; i < pScrPriv->numCrtcs; i++)
+	    if (RRXineramaCrtcActive (pScrPriv->crtcs[i]))
+		n++;
+    }
+    return n;
+}
+
+int
+ProcRRXineramaGetScreenCount(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetScreenCountReq);
+    WindowPtr				pWin;
+    xPanoramiXGetScreenCountReply	rep;
+    register int			n;
+
+    REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
+    pWin = LookupWindow(stuff->window, client);
+    if(!pWin) return BadWindow;
+    
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.ScreenCount = RRXineramaScreenCount (pWin->drawable.pScreen);
+    if(client->swapped) {
+       swaps(&rep.sequenceNumber, n);
+       swapl(&rep.length, n);
+       swaps(&rep.ScreenCount, n);
+    }
+    WriteToClient(client, sizeof(xPanoramiXGetScreenCountReply), (char *)&rep);
+    return client->noClientException;
+}
+
+int
+ProcRRXineramaGetScreenSize(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetScreenSizeReq);
+    WindowPtr				pWin, pRoot;
+    ScreenPtr				pScreen;
+    xPanoramiXGetScreenSizeReply	rep;
+    register int			n;
+
+    REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
+    pWin = LookupWindow (stuff->window, client);
+    if(!pWin)  return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pRoot = WindowTable[pScreen->myNum];
+    
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.width  = pRoot->drawable.width;
+    rep.height = pRoot->drawable.height;
+    if(client->swapped) {
+       swaps(&rep.sequenceNumber, n);
+       swapl(&rep.length, n);
+       swaps(&rep.width, n);
+       swaps(&rep.height, n);
+    }
+    WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply), (char *)&rep);
+    return client->noClientException;
+}
+
+int
+ProcRRXineramaIsActive(ClientPtr client)
+{
+    xXineramaIsActiveReply	rep;
+
+    REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
+	
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.state = RRXineramaScreenActive (screenInfo.screens[RR_XINERAMA_SCREEN]);
+    if(client->swapped) {
+	register int n;
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.state, n);
+    }
+    WriteToClient(client, sizeof(xXineramaIsActiveReply), (char *) &rep);
+    return client->noClientException;
+}
+
+int
+ProcRRXineramaQueryScreens(ClientPtr client)
+{
+    xXineramaQueryScreensReply	rep;
+    ScreenPtr	pScreen = screenInfo.screens[RR_XINERAMA_SCREEN];
+
+    REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
+
+    rep.type = X_Reply;
+    rep.sequenceNumber = client->sequence;
+    rep.number = RRXineramaScreenCount (pScreen);
+    rep.length = rep.number * sz_XineramaScreenInfo >> 2;
+    if(client->swapped) {
+	register int n;
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.number, n);
+    }
+    WriteToClient(client, sizeof(xXineramaQueryScreensReply), (char *)&rep);
+
+    if(rep.number) {
+	rrScrPriv(pScreen);
+	xXineramaScreenInfo scratch;
+	int i;
+
+	for(i = 0; i < pScrPriv->numCrtcs; i++) {
+	    RRCrtcPtr	crtc = pScrPriv->crtcs[i];
+	    if (RRXineramaCrtcActive (crtc))
+	    {
+		scratch.x_org  = crtc->x;
+		scratch.y_org  = crtc->y;
+		scratch.width  = crtc->mode->mode.width;
+		scratch.height = crtc->mode->mode.height;
+		if(client->swapped) {
+		    register int n;
+		    swaps(&scratch.x_org, n);
+		    swaps(&scratch.y_org, n);
+		    swaps(&scratch.width, n);
+		    swaps(&scratch.height, n);
+		}
+		WriteToClient(client, sz_XineramaScreenInfo, (char *)&scratch);
+	    }
+	}
+    }
+
+    return client->noClientException;
+}
+
+static int
+ProcRRXineramaDispatch(ClientPtr client)
+{
+    REQUEST(xReq);
+    switch (stuff->data) {
+	case X_PanoramiXQueryVersion:
+	     return ProcRRXineramaQueryVersion(client);
+	case X_PanoramiXGetState:
+	     return ProcRRXineramaGetState(client);
+	case X_PanoramiXGetScreenCount:
+	     return ProcRRXineramaGetScreenCount(client);
+	case X_PanoramiXGetScreenSize:
+	     return ProcRRXineramaGetScreenSize(client);
+	case X_XineramaIsActive:
+	     return ProcRRXineramaIsActive(client);
+	case X_XineramaQueryScreens:
+	     return ProcRRXineramaQueryScreens(client);
+    }
+    return BadRequest;
+}
+
+/* SProc */
+
+static int
+SProcRRXineramaQueryVersion (ClientPtr client)
+{
+    REQUEST(xPanoramiXQueryVersionReq);
+    register int n;
+    swaps(&stuff->length,n);
+    REQUEST_SIZE_MATCH (xPanoramiXQueryVersionReq);
+    return ProcRRXineramaQueryVersion(client);
+}
+
+static int
+SProcRRXineramaGetState(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetStateReq);
+    register int n;
+    swaps (&stuff->length, n);
+    REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
+    return ProcRRXineramaGetState(client);
+}
+
+static int
+SProcRRXineramaGetScreenCount(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetScreenCountReq);
+    register int n;
+    swaps (&stuff->length, n);
+    REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
+    return ProcRRXineramaGetScreenCount(client);
+}
+
+static int
+SProcRRXineramaGetScreenSize(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetScreenSizeReq);
+    register int n;
+    swaps (&stuff->length, n);
+    REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
+    return ProcRRXineramaGetScreenSize(client);
+}
+
+static int
+SProcRRXineramaIsActive(ClientPtr client)
+{
+    REQUEST(xXineramaIsActiveReq);
+    register int n;
+    swaps (&stuff->length, n);
+    REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
+    return ProcRRXineramaIsActive(client);
+}
+
+static int
+SProcRRXineramaQueryScreens(ClientPtr client)
+{
+    REQUEST(xXineramaQueryScreensReq);
+    register int n;
+    swaps (&stuff->length, n);
+    REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
+    return ProcRRXineramaQueryScreens(client);
+}
+
+int
+SProcRRXineramaDispatch(ClientPtr client)
+{
+    REQUEST(xReq);
+    switch (stuff->data) {
+	case X_PanoramiXQueryVersion:
+	     return SProcRRXineramaQueryVersion(client);
+	case X_PanoramiXGetState:
+	     return SProcRRXineramaGetState(client);
+	case X_PanoramiXGetScreenCount:
+	     return SProcRRXineramaGetScreenCount(client);
+	case X_PanoramiXGetScreenSize:
+	     return SProcRRXineramaGetScreenSize(client);
+	case X_XineramaIsActive:
+	     return SProcRRXineramaIsActive(client);
+	case X_XineramaQueryScreens:
+	     return SProcRRXineramaQueryScreens(client);
+    }
+    return BadRequest;
+}
+
+static void
+RRXineramaResetProc(ExtensionEntry* extEntry)
+{
+}
+
+void
+RRXineramaExtensionInit(void)
+{
+#ifdef PANORAMIX
+    if(!noPanoramiXExtension)
+	return;
+#endif
+
+    (void) AddExtension(PANORAMIX_PROTOCOL_NAME, 0,0,
+			ProcRRXineramaDispatch,
+			SProcRRXineramaDispatch,
+			RRXineramaResetProc,
+			StandardMinorOpcode);
+}
commit 3516e85b45441715bacda81fcae3b8a786d75f06
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Wed Sep 20 19:42:34 2006 -0700

    RRSetCrtcConfig status fix. RRGetScreenResources timestamp fix.
    
    RRSetCrtcConfig was returning the wrong status values.
    RRGetScreenResources was always returning currentTime.

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 90d609e..dfa9ca6 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -628,8 +628,13 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	goto sendReply;
     }
 
-    rep.status = RRCrtcSet (crtc, mode, stuff->x, stuff->y,
-			    rotation, numOutputs, outputs);
+    if (!RRCrtcSet (crtc, mode, stuff->x, stuff->y,
+		   rotation, numOutputs, outputs))
+    {
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    rep.status = RRSetConfigSuccess;
     
 sendReply:
     if (outputs)
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 617ae41..e59947b 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -360,8 +360,8 @@ ProcRRGetScreenResources (ClientPtr client)
 	rep.type = X_Reply;
 	rep.sequenceNumber = client->sequence;
 	rep.length = 0;
-	rep.timestamp = currentTime.milliseconds;
-	rep.configTimestamp = currentTime.milliseconds;
+	rep.timestamp = pScrPriv->lastSetTime.milliseconds;
+	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
 	rep.nCrtcs = pScrPriv->numCrtcs;
 	rep.nOutputs = pScrPriv->numOutputs;
 	rep.nModes = pScrPriv->numModes;;
commit a0f59b53794bd0d655fc2042c6196b27a033f85a
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Wed Sep 20 13:15:20 2006 -0700

    typo

diff --git a/randr/rroutput.c b/randr/rroutput.c
index a4f5a66..90b2b98 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -194,7 +194,7 @@ void
 RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc)
 {
     if (output->crtc == crtc)
-	return TRUE;
+	return;
     output->crtc = crtc;
     output->changed = TRUE;
 }
commit b851c3e35e407d966c10572f7594c0cb4a106d8e
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Wed Sep 20 13:14:53 2006 -0700

    When setting output state, leave output unchanged when setting to current.

diff --git a/randr/randrstr.h b/randr/randrstr.h
index 8027262..e459452 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -77,6 +77,7 @@ struct _rrMode {
     int		    refcnt;
     xRRModeInfo	    mode;
     char	    *name;
+    void	    *devPrivate;
 };
 
 struct _rrCrtc {
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 3d4c163..a4f5a66 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -88,7 +88,16 @@ RROutputSetClones (RROutputPtr  output,
 		   int		numClones)
 {
     RROutputPtr	*newClones;
+    int		i;
 
+    if (numClones == output->numClones)
+    {
+	for (i = 0; i < numClones; i++)
+	    if (output->clones[i] != clones[i])
+		break;
+	if (i == numClones)
+	    return TRUE;
+    }
     if (numClones)
     {
 	newClones = xalloc (numClones * sizeof (RROutputPtr));
@@ -112,6 +121,20 @@ RROutputSetModes (RROutputPtr	output,
 		  int		numModes)
 {
     RRModePtr	*newModes;
+    int		i;
+
+    if (numModes == output->numModes)
+    {
+	for (i = 0; i < numModes; i++)
+	    if (output->modes[i] != modes[i])
+		break;
+	if (i == numModes)
+	{
+	    for (i = 0; i < numModes; i++)
+		RRModeDestroy (modes[i]);
+	    return TRUE;
+	}
+    }
 
     if (numModes)
     {
@@ -122,7 +145,11 @@ RROutputSetModes (RROutputPtr	output,
     else
 	newModes = NULL;
     if (output->modes)
+    {
+	for (i = 0; i < output->numModes; i++)
+	    RRModeDestroy (output->modes[i]);
 	xfree (output->modes);
+    }
     memcpy (newModes, modes, numModes * sizeof (RRModePtr));
     output->modes = newModes;
     output->numModes = numModes;
@@ -136,7 +163,16 @@ RROutputSetCrtcs (RROutputPtr	output,
 		  int		numCrtcs)
 {
     RRCrtcPtr	*newCrtcs;
+    int		i;
 
+    if (numCrtcs == output->numCrtcs)
+    {
+	for (i = 0; i < numCrtcs; i++)
+	    if (output->crtcs[i] != crtcs[i])
+		break;
+	if (i == numCrtcs)
+	    return TRUE;
+    }
     if (numCrtcs)
     {
 	newCrtcs = xalloc (numCrtcs * sizeof (RRCrtcPtr));
@@ -157,6 +193,8 @@ RROutputSetCrtcs (RROutputPtr	output,
 void
 RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc)
 {
+    if (output->crtc == crtc)
+	return TRUE;
     output->crtc = crtc;
     output->changed = TRUE;
 }
@@ -165,6 +203,8 @@ Bool
 RROutputSetConnection (RROutputPtr  output,
 		       CARD8	    connection)
 {
+    if (output->connection == connection)
+	return TRUE;
     output->connection = connection;
     output->changed = TRUE;
     return TRUE;
@@ -174,6 +214,9 @@ Bool
 RROutputSetSubpixelOrder (RROutputPtr output,
 			  int	      subpixelOrder)
 {
+    if (output->subpixelOrder == subpixelOrder)
+	return TRUE;
+
     output->subpixelOrder = subpixelOrder;
     output->changed = TRUE;
     return TRUE;
commit f133e72d82e625683c96200ffde890cdbb5d4b10
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Wed Sep 20 12:05:52 2006 -0700

    Avoid calling xalloc(0). Change rrScreenSizeSet to rrScreenSetSize.

diff --git a/randr/randr.c b/randr/randr.c
index 5f6ef62..5f54dea 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -198,7 +198,7 @@ Bool RRScreenInit(ScreenPtr pScreen)
     pScrPriv->maxHeight = pScrPriv->minHeight = pScreen->height;
     
 #if RANDR_12_INTERFACE
-    pScrPriv->rrScreenSizeSet = NULL;
+    pScrPriv->rrScreenSetSize = NULL;
     pScrPriv->rrCrtcSet = NULL;
     pScrPriv->rrCrtcSetGamma = NULL;
 #endif
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 26c1806..8027262 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -174,7 +174,7 @@ typedef struct _rrScrPriv {
 #endif
     RRGetInfoProcPtr	    rrGetInfo;
 #if RANDR_12_INTERFACE
-    RRScreenSetSizeProcPtr  rrScreenSizeSet;
+    RRScreenSetSizeProcPtr  rrScreenSetSize;
     RRCrtcSetProcPtr	    rrCrtcSet;
     RRCrtcSetGammaProcPtr   rrCrtcSetGamma;
 #endif
@@ -521,7 +521,7 @@ RRClientKnowsRates (ClientPtr	pClient);
 RRModePtr
 RRModeGet (ScreenPtr	pScreen,
 	   xRRModeInfo	*modeInfo,
-	   char		*name);
+	   const char	*name);
 
 /*
  * Destroy a mode.
@@ -555,7 +555,7 @@ ProcRRDeleteOutputMode (ClientPtr client);
 
 RROutputPtr
 RROutputCreate (ScreenPtr   pScreen,
-		char	    *name,
+		const char  *name,
 		int	    nameLength,
 		void	    *devPrivate);
 
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index c55e088..90d609e 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -94,13 +94,22 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
     {
 	RROutputPtr *outputs;
 	
-	if (crtc->numOutputs)
-	    outputs = xrealloc (crtc->outputs,
-				numOutputs * sizeof (RROutputPtr));
+	if (numOutputs)
+	{
+	    if (crtc->numOutputs)
+		outputs = xrealloc (crtc->outputs,
+				    numOutputs * sizeof (RROutputPtr));
+	    else
+		outputs = xalloc (numOutputs * sizeof (RROutputPtr));
+	    if (!outputs)
+		return FALSE;
+	}
 	else
-	    outputs = xalloc (numOutputs * sizeof (RROutputPtr));
-	if (!outputs)
-	    return FALSE;
+	{
+	    if (crtc->outputs)
+		xfree (crtc->outputs);
+	    outputs = NULL;
+	}
 	crtc->outputs = outputs;
     }
     for (i = 0; i < numOutputs; i++)
@@ -300,9 +309,14 @@ RRCrtcGammaSetSize (RRCrtcPtr	crtc,
 
     if (size == crtc->gammaSize)
 	return TRUE;
-    gamma = xalloc (size * 3 * sizeof (CARD16));
-    if (!gamma)
-	return FALSE;
+    if (size)
+    {
+	gamma = xalloc (size * 3 * sizeof (CARD16));
+	if (!gamma)
+	    return FALSE;
+    }
+    else
+	gamma = NULL;
     if (crtc->gammaRed)
 	xfree (crtc->gammaRed);
     crtc->gammaRed = gamma;
@@ -376,9 +390,14 @@ ProcRRGetCrtcInfo (ClientPtr client)
     rep.length = rep.nOutput + rep.nPossibleOutput;
 
     extraLen = rep.length << 2;
-    extra = xalloc (extraLen);
-    if (!extra)
-	return BadAlloc;
+    if (extraLen)
+    {
+	extra = xalloc (extraLen);
+	if (!extra)
+	    return BadAlloc;
+    }
+    else
+	extra = NULL;
 
     outputs = (RROutput *) extra;
     possible = (RROutput *) (outputs + rep.nOutput);
@@ -467,9 +486,14 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	if (numOutputs == 0)
 	    return BadMatch;
     }
-    outputs = xalloc (numOutputs * sizeof (RROutputPtr));
-    if (!outputs)
-	return BadAlloc;
+    if (numOutputs)
+    {
+	outputs = xalloc (numOutputs * sizeof (RROutputPtr));
+	if (!outputs)
+	    return BadAlloc;
+    }
+    else
+	outputs = NULL;
     
     outputIds = (RROutput *) (stuff + 1);
     for (i = 0; i < numOutputs; i++)
@@ -574,7 +598,7 @@ ProcRRSetCrtcConfig (ClientPtr client)
      * for setting screen size. Else, assume the CrtcSet sets
      * the size along with the mode
      */
-    if (pScrPriv->rrScreenSizeSet)
+    if (pScrPriv->rrScreenSetSize)
     {
 	if (stuff->x + mode->mode.width > pScreen->width)
 	{
diff --git a/randr/rrmode.c b/randr/rrmode.c
index ab0ea18..23ac530 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -27,7 +27,7 @@ RESTYPE	RRModeType;
 RRModePtr
 RRModeGet (ScreenPtr	pScreen,
 	   xRRModeInfo	*modeInfo,
-	   char		*name)
+	   const char	*name)
 {
     rrScrPriv (pScreen);
     int	i;
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 07dabad..3d4c163 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -30,7 +30,7 @@ RESTYPE	RROutputType;
 
 RROutputPtr
 RROutputCreate (ScreenPtr   pScreen,
-		char	    *name,
+		const char  *name,
 		int	    nameLength,
 		void	    *devPrivate)
 {
@@ -89,9 +89,14 @@ RROutputSetClones (RROutputPtr  output,
 {
     RROutputPtr	*newClones;
 
-    newClones = xalloc (numClones * sizeof (RROutputPtr));
-    if (!newClones)
-	return FALSE;
+    if (numClones)
+    {
+	newClones = xalloc (numClones * sizeof (RROutputPtr));
+	if (!newClones)
+	    return FALSE;
+    }
+    else
+	newClones = NULL;
     if (output->clones)
 	xfree (output->clones);
     memcpy (newClones, clones, numClones * sizeof (RROutputPtr));
@@ -108,9 +113,14 @@ RROutputSetModes (RROutputPtr	output,
 {
     RRModePtr	*newModes;
 
-    newModes = xalloc (numModes * sizeof (RRModePtr));
-    if (!newModes)
-	return FALSE;
+    if (numModes)
+    {
+	newModes = xalloc (numModes * sizeof (RRModePtr));
+	if (!newModes)
+	    return FALSE;
+    }
+    else
+	newModes = NULL;
     if (output->modes)
 	xfree (output->modes);
     memcpy (newModes, modes, numModes * sizeof (RRModePtr));
@@ -127,9 +137,14 @@ RROutputSetCrtcs (RROutputPtr	output,
 {
     RRCrtcPtr	*newCrtcs;
 
-    newCrtcs = xalloc (numCrtcs * sizeof (RRCrtcPtr));
-    if (!newCrtcs)
-	return FALSE;
+    if (numCrtcs)
+    {
+	newCrtcs = xalloc (numCrtcs * sizeof (RRCrtcPtr));
+	if (!newCrtcs)
+	    return FALSE;
+    }
+    else
+	newCrtcs = NULL;
     if (output->crtcs)
 	xfree (output->crtcs);
     memcpy (newCrtcs, crtcs, numCrtcs * sizeof (RRCrtcPtr));
@@ -265,9 +280,14 @@ ProcRRGetOutputInfo (ClientPtr client)
 		  ((rep.nameLength + 3) >> 2));
 
     extraLen = rep.length << 2;
-    extra = xalloc (extraLen);
-    if (!extra)
-	return BadAlloc;
+    if (extraLen)
+    {
+	extra = xalloc (extraLen);
+	if (!extra)
+	    return BadAlloc;
+    }
+    else
+	extra = NULL;
 
     crtcs = (RRCrtc *) extra;
     modes = (RRMode *) (crtcs + output->numCrtcs);
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 58d5152..617ae41 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -187,9 +187,9 @@ RRScreenSizeSet (ScreenPtr  pScreen,
     rrScrPriv(pScreen);
 
 #if RANDR_12_INTERFACE
-    if (pScrPriv->rrScreenSizeSet)
+    if (pScrPriv->rrScreenSetSize)
     {
-	return (*pScrPriv->rrScreenSizeSet) (pScreen,
+	return (*pScrPriv->rrScreenSetSize) (pScreen,
 					     width, height,
 					     mmWidth, mmHeight);
     }
@@ -376,9 +376,14 @@ ProcRRGetScreenResources (ClientPtr client)
 		      ((rep.nbytesNames + 3) >> 2));
 	
 	extraLen = rep.length << 2;
-	extra = xalloc (extraLen);
-	if (!extra)
-	    return BadAlloc;
+	if (extraLen)
+	{
+	    extra = xalloc (extraLen);
+	    if (!extra)
+		return BadAlloc;
+	}
+	else
+	    extra = NULL;
 
 	crtcs = (RRCrtc *) extra;
 	outputs = (RROutput *) (crtcs + pScrPriv->numCrtcs);
@@ -595,12 +600,18 @@ ProcRRGetScreenInfo (ClientPtr client)
 	extraLen = (rep.nSizes * sizeof (xScreenSizes) +
 		    rep.nrateEnts * sizeof (CARD16));
 
-	extra = (CARD8 *) xalloc (extraLen);
-	if (!extra)
+	if (extraLen)
 	{
-	    xfree (pData);
-	    return BadAlloc;
+	    extra = (CARD8 *) xalloc (extraLen);
+	    if (!extra)
+	    {
+		xfree (pData);
+		return BadAlloc;
+	    }
 	}
+	else
+	    extra = NULL;
+
 	/*
 	 * First comes the size information
 	 */
commit cd63e82aa51d941564012a8d8242ebe29b087373
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Tue Sep 19 22:48:54 2006 -0700

    Split out 1.0-style info and new property routines to their own files.

diff --git a/randr/Makefile.am b/randr/Makefile.am
index 0a73557..a28ead0 100644
--- a/randr/Makefile.am
+++ b/randr/Makefile.am
@@ -12,7 +12,9 @@ librandr_la_SOURCES =	\
 	randrstr.h	\
 	rrcrtc.c	\
 	rrdispatch.c	\
+	rrinfo.c	\
 	rrmode.c	\
 	rroutput.c	\
+	rrproperty.c	\
 	rrscreen.c	\
 	rrsdispatch.c
diff --git a/randr/mirandr.c b/randr/mirandr.c
index a57a157..bcc8e0f 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -108,11 +108,13 @@ miRandRInit (ScreenPtr pScreen)
     output = RROutputCreate (pScreen, "screen", 6, NULL);
     if (!output)
 	return FALSE;
-    if (!RROutputSet (output, 
-		      NULL, 0,  /* clones */
-		      &mode, 1, /* modes */
-		      &crtc, 1, /* crtcs */
-		      RR_Connected))
+    if (!RROutputSetClones (output, NULL, 0))
+	return FALSE;
+    if (!RROutputSetModes (output, &mode, 1))
+	return FALSE;
+    if (!RROutputSetCrtcs (output, &crtc, 1))
+	return FALSE;
+    if (!RROutputSetConnection (output, RR_Connected))
 	return FALSE;
     RRCrtcNotify (crtc, mode, 0, 0, RR_Rotate_0, 1, &output);
 #endif
diff --git a/randr/randr.c b/randr/randr.c
index beddb50..5f6ef62 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -198,7 +198,9 @@ Bool RRScreenInit(ScreenPtr pScreen)
     pScrPriv->maxHeight = pScrPriv->minHeight = pScreen->height;
     
 #if RANDR_12_INTERFACE
-    pScrPriv->rrCrtcSet = 0;
+    pScrPriv->rrScreenSizeSet = NULL;
+    pScrPriv->rrCrtcSet = NULL;
+    pScrPriv->rrCrtcSetGamma = NULL;
 #endif
 #if RANDR_10_INTERFACE    
     pScrPriv->rrSetConfig = 0;
@@ -400,196 +402,6 @@ RRFirstOutput (ScreenPtr pScreen)
     return NULL;
 }
 
-#ifdef RANDR_10_INTERFACE
-static RRModePtr
-RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
-{
-    ScreenPtr	pScreen = output->pScreen;
-    rrScrPriv(pScreen);
-    xRRModeInfo	modeInfo;
-    char	name[100];
-    RRModePtr	mode;
-    int		i;
-    RRModePtr   *modes;
-    
-    memset (&modeInfo, '\0', sizeof (modeInfo));
-    sprintf (name, "%dx%d", size->width, size->height);
-    
-    modeInfo.width = size->width;
-    modeInfo.height = size->height;
-    modeInfo.mmWidth = size->mmWidth;
-    modeInfo.mmHeight = size->mmHeight;
-    modeInfo.hTotal = size->width;
-    modeInfo.vTotal = size->height;
-    modeInfo.dotClock = ((CARD32) size->width * (CARD32) size->width *
-			 (CARD32) refresh);
-    modeInfo.nameLength = strlen (name);
-    mode = RRModeGet (pScreen, &modeInfo, name);
-    if (!mode)
-	return NULL;
-    for (i = 0; i < output->numModes; i++)
-	if (output->modes[i] == mode)
-	{
-	    RRModeDestroy (mode);
-	    return mode;
-	}
-    
-    if (output->numModes)
-	modes = xrealloc (output->modes, 
-			  (output->numModes + 1) * sizeof (RRModePtr));
-    else
-	modes = xalloc (sizeof (RRModePtr));
-    if (!modes)
-    {
-	RRModeDestroy (mode);
-	FreeResource (mode->mode.id, 0);
-	return NULL;
-    }
-    modes[output->numModes++] = mode;
-    output->modes = modes;
-    output->changed = TRUE;
-    pScrPriv->changed = TRUE;
-    return mode;
-}
-
-static void
-RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
-{
-    rrScrPriv(pScreen);
-    RROutputPtr	output;
-    RRCrtcPtr	crtc;
-    RRModePtr	mode, newMode = NULL;
-    int		i;
-    CARD16	minWidth = MAXSHORT, minHeight = MAXSHORT;
-    CARD16	maxWidth = 0, maxHeight = 0;
-    
-    /*
-     * First time through, create a crtc and output and hook
-     * them together
-     */
-    if (pScrPriv->numOutputs == 0 &&
-	pScrPriv->numCrtcs == 0)
-    {
-	crtc = RRCrtcCreate (pScreen, NULL);
-	if (!crtc)
-	    return;
-	output = RROutputCreate (pScreen, "default", 7, NULL);
-	if (!output)
-	    return;
-	RROutputSetCrtcs (output, &crtc, 1);
-	RROutputSetCrtc (output, crtc);
-	RROutputSetConnection (output, RR_Connected);
-#ifdef RENDER
-	RROutputSetSubpixelOrder (output, PictureGetSubpixelOrder (pScreen));
-#endif
-    }
-
-    output = RRFirstOutput (pScreen);
-    if (!output)
-	return;
-    crtc = output->crtc;
-
-    /* check rotations */
-    if (rotations != crtc->rotations)
-    {
-        crtc->rotations = rotations;
-	crtc->changed = TRUE;
-	pScrPriv->changed = TRUE;
-    }
-	
-    /* regenerate mode list */
-    for (i = 0; i < pScrPriv->nSizes; i++)
-    {
-	RRScreenSizePtr	size = &pScrPriv->pSizes[i];
-	int		r;
-
-	if (size->nRates)
-	{
-	    for (r = 0; r < size->nRates; r++)
-	    {
-		mode = RROldModeAdd (output, size, size->pRates[r].rate);
-		if (i == pScrPriv->size && 
-		    size->pRates[r].rate == pScrPriv->rate)
-		{
-		    newMode = mode;
-		}
-	    }
-	    xfree (size->pRates);
-	}
-	else
-	{
-	    mode = RROldModeAdd (output, size, 0);
-	    if (i == pScrPriv->size)
-		newMode = mode;
-	}
-    }
-    if (pScrPriv->nSizes)
-	xfree (pScrPriv->pSizes);
-    pScrPriv->pSizes = NULL;
-    pScrPriv->nSizes = 0;
-	    
-    /* find size bounds */
-    for (i = 0; i < output->numModes; i++) 
-    {
-	RRModePtr   mode = output->modes[i];
-        CARD16	    width = mode->mode.width;
-        CARD16	    height = mode->mode.height;
-	
-	if (width < minWidth) minWidth = width;
-	if (width > maxWidth) maxWidth = width;
-	if (height < minHeight) minHeight = height;
-	if (height > maxHeight) maxHeight = height;
-    }
-
-    if (minWidth != pScrPriv->minWidth) {
-	pScrPriv->minWidth = minWidth; pScrPriv->changed = TRUE;
-    }
-    if (maxWidth != pScrPriv->maxWidth) {
-	pScrPriv->maxWidth = maxWidth; pScrPriv->changed = TRUE;
-    }
-    if (minHeight != pScrPriv->minHeight) {
-	pScrPriv->minHeight = minHeight; pScrPriv->changed = TRUE;
-    }
-    if (maxHeight != pScrPriv->maxHeight) {
-	pScrPriv->maxHeight = maxHeight; pScrPriv->changed = TRUE;
-    }
-
-    /* notice current mode */
-    if (newMode)
-	RRCrtcNotify (output->crtc, newMode, 0, 0, pScrPriv->rotation,
-		      1, &output);
-}
-#endif
-
-/*
- * Poll the driver for changed information
- */
-Bool
-RRGetInfo (ScreenPtr pScreen)
-{
-    rrScrPriv (pScreen);
-    Rotation	    rotations;
-    int		    i;
-
-    for (i = 0; i < pScrPriv->numOutputs; i++)
-	pScrPriv->outputs[i]->changed = FALSE;
-    for (i = 0; i < pScrPriv->numCrtcs; i++)
-	pScrPriv->crtcs[i]->changed = FALSE;
-    
-    rotations = 0;
-    pScrPriv->changed = FALSE;
-    
-    if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
-	return FALSE;
-
-#if RANDR_10_INTERFACE
-    if (pScrPriv->nSizes)
-	RRScanOldConfig (pScreen, rotations);
-#endif
-    RRTellChanged (pScreen);
-    return TRUE;
-}
-
 CARD16
 RRVerticalRefresh (xRRModeInfo *mode)
 {
@@ -602,83 +414,6 @@ RRVerticalRefresh (xRRModeInfo *mode)
     return (CARD16) refresh;
 }
 
-#if 0
-int
-RRSetScreenConfig (ScreenPtr		pScreen,
-		   Rotation		rotation,
-		   int			rate,
-		   RRScreenSizePtr	pSize)
-{
-    rrScrPrivPtr	    pScrPriv;
-    RRMonitorPtr	    pMonitor;
-    short		    oldWidth, oldHeight;
-    RRModePtr		    pMode;
-    int			    status;
-
-    pScrPriv = rrGetScrPriv(pScreen);
-    
-    if (!pScrPriv)
-	return BadImplementation;
-    
-    pMonitor = pScrPriv->pMonitors;
-    if (!pMonitor)
-	return BadImplementation;
-
-    oldWidth = pScreen->width;
-    oldHeight = pScreen->height;
-    
-    if (!RRGetInfo (pScreen))
-	return BadAlloc;
-    
-    /*
-     * Validate requested rotation
-     */
-
-    /* test the rotation bits only! */
-    switch (rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_90:
-    case RR_Rotate_180:
-    case RR_Rotate_270:
-	break;
-    default:
-	/*
-	 * Invalid rotation
-	 */
-	return BadValue;
-    }
-
-    if ((~pScrPriv->rotations) & rotation)
-    {
-	/*
-	 * requested rotation or reflection not supported by screen
-	 */
-	return BadMatch;
-    }
-
-    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
-    {
-	if (pMode->mode.width == pSize->width &&
-	    pMode->mode.height == pSize->height &&
-	    pMode->mode.widthInMillimeters == pSize->mmWidth &&
-	    pMode->mode.heightInMillimeters == pSize->mmHeight &&
-	    (RRVerticalRefresh (&pMode->mode) == rate || rate == 0))
-	{
-	    break;
-	}
-    }
-    if (!pMode)
-	return BadValue;
-    
-    status = RRMonitorSetMode (pScreen, pMonitor, pMode, 0, 0, 
-			       rotation, currentTime);
-    
-    if (status != RRSetConfigSuccess)
-	return BadImplementation;
-    return Success;
-}
-#endif
-
 static int
 ProcRRDispatch (ClientPtr client)
 {
@@ -697,126 +432,3 @@ SProcRRDispatch (ClientPtr client)
     return (*SProcRandrVector[stuff->data]) (client);
 }
 
-#if RANDR_12_INTERFACE
-/*
- * Register the range of sizes for the screen
- */
-void
-RRScreenSetSizeRange (ScreenPtr	pScreen,
-		      CARD16	minWidth,
-		      CARD16	minHeight,
-		      CARD16	maxWidth,
-		      CARD16	maxHeight)
-{
-    rrScrPriv (pScreen);
-
-    if (!pScrPriv)
-	return;
-    pScrPriv->minWidth  = minWidth;
-    pScrPriv->minHeight = minHeight;
-    pScrPriv->maxWidth  = maxWidth;
-    pScrPriv->maxHeight = maxHeight;
-}
-#endif
-
-#ifdef RANDR_10_INTERFACE
-static Bool
-RRScreenSizeMatches (RRScreenSizePtr  a,
-		   RRScreenSizePtr  b)
-{
-    if (a->width != b->width)
-	return FALSE;
-    if (a->height != b->height)
-	return FALSE;
-    if (a->mmWidth != b->mmWidth)
-	return FALSE;
-    if (a->mmHeight != b->mmHeight)
-	return FALSE;
-    return TRUE;
-}
-
-RRScreenSizePtr
-RRRegisterSize (ScreenPtr	    pScreen,
-		short		    width, 
-		short		    height,
-		short		    mmWidth,
-		short		    mmHeight)
-{
-    rrScrPriv (pScreen);
-    int		    i;
-    RRScreenSize    tmp;
-    RRScreenSizePtr pNew;
-
-    if (!pScrPriv)
-	return 0;
-    
-    tmp.id = 0;
-    tmp.width = width;
-    tmp.height= height;
-    tmp.mmWidth = mmWidth;
-    tmp.mmHeight = mmHeight;
-    tmp.pRates = 0;
-    tmp.nRates = 0;
-    for (i = 0; i < pScrPriv->nSizes; i++)
-	if (RRScreenSizeMatches (&tmp, &pScrPriv->pSizes[i]))
-	    return &pScrPriv->pSizes[i];
-    pNew = xrealloc (pScrPriv->pSizes,
-		     (pScrPriv->nSizes + 1) * sizeof (RRScreenSize));
-    if (!pNew)
-	return 0;
-    pNew[pScrPriv->nSizes++] = tmp;
-    pScrPriv->pSizes = pNew;
-    return &pNew[pScrPriv->nSizes-1];
-}
-
-Bool RRRegisterRate (ScreenPtr		pScreen,
-		     RRScreenSizePtr	pSize,
-		     int		rate)
-{
-    rrScrPriv(pScreen);
-    int		    i;
-    RRScreenRatePtr pNew, pRate;
-
-    if (!pScrPriv)
-	return FALSE;
-    
-    for (i = 0; i < pSize->nRates; i++)
-	if (pSize->pRates[i].rate == rate)
-	    return TRUE;
-
-    pNew = xrealloc (pSize->pRates,
-		     (pSize->nRates + 1) * sizeof (RRScreenRate));
-    if (!pNew)
-	return FALSE;
-    pRate = &pNew[pSize->nRates++];
-    pRate->rate = rate;
-    pSize->pRates = pNew;
-    return TRUE;
-}
-
-Rotation
-RRGetRotation(ScreenPtr pScreen)
-{
-    RROutputPtr	output = RRFirstOutput (pScreen);
-
-    if (!output)
-	return RR_Rotate_0;
-
-    return output->crtc->rotation;
-}
-
-void
-RRSetCurrentConfig (ScreenPtr		pScreen,
-		    Rotation		rotation,
-		    int			rate,
-		    RRScreenSizePtr	pSize)
-{
-    rrScrPriv (pScreen);
-
-    if (!pScrPriv)
-	return;
-    pScrPriv->size = pSize - pScrPriv->pSizes;
-    pScrPriv->rotation = rotation;
-    pScrPriv->rate = rate;
-}
-#endif
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 682ebbf..26c1806 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -53,7 +53,7 @@
 
 /* required for ABI compatibility for now */
 #define RANDR_10_INTERFACE 1
-/* #define RANDR_12_INTERFACE 1 */
+#define RANDR_12_INTERFACE 1
 
 typedef XID	RRMode;
 typedef XID	RROutput;
@@ -89,6 +89,10 @@ struct _rrCrtc {
     Bool	    changed;
     int		    numOutputs;
     RROutputPtr	    *outputs;
+    int		    gammaSize;
+    CARD16	    *gammaRed;
+    CARD16	    *gammaBlue;
+    CARD16	    *gammaGreen;
     void	    *devPrivate;
 };
 
@@ -107,11 +111,12 @@ struct _rrOutput {
     int		    numModes;
     RRModePtr	    *modes;
     Bool	    changed;
+    PropertyPtr	    properties;
     void	    *devPrivate;
 };
 
 #if RANDR_12_INTERFACE
-typedef Bool (*RRScreentSizeSetProcPtr) (ScreenPtr	pScreen,
+typedef Bool (*RRScreenSetSizeProcPtr) (ScreenPtr	pScreen,
 					CARD16		width,
 					CARD16		height,
 					CARD32		mmWidth,
@@ -125,6 +130,10 @@ typedef Bool (*RRCrtcSetProcPtr) (ScreenPtr		pScreen,
 				  Rotation		rotation,
 				  int			numOutputs,
 				  RROutputPtr		*outputs);
+
+typedef Bool (*RRCrtcSetGammaProcPtr) (ScreenPtr	pScreen,
+				       RRCrtcPtr	crtc);
+
 #endif
 
 typedef Bool (*RRGetInfoProcPtr) (ScreenPtr pScreen, Rotation *rotations);
@@ -167,6 +176,7 @@ typedef struct _rrScrPriv {
 #if RANDR_12_INTERFACE
     RRScreenSetSizeProcPtr  rrScreenSizeSet;
     RRCrtcSetProcPtr	    rrCrtcSet;
+    RRCrtcSetGammaProcPtr   rrCrtcSetGamma;
 #endif
     
     /*
@@ -245,6 +255,16 @@ extern RESTYPE	RRClientType, RREventType; /* resource types for event masks */
 extern int	RRClientPrivateIndex;
 extern RESTYPE	RRCrtcType, RRModeType, RROutputType;
 
+#define LookupOutput(client,id,a) ((RROutputPtr) \
+				   (SecurityLookupIDByType (client, id, \
+							    RROutputType, a)))
+#define LookupCrtc(client,id,a) ((RRCrtcPtr) \
+				 (SecurityLookupIDByType (client, id, \
+							  RRCrtcType, a)))
+#define LookupMode(client,id,a) ((RRModePtr) \
+				 (SecurityLookupIDByType (client, id, \
+							  RRModeType, a)))
+
 #define GetRRClient(pClient)    ((RRClientPtr) (pClient)->devPrivates[RRClientPrivateIndex].ptr)
 #define rrClientPriv(pClient)	RRClientPtr pRRClient = GetRRClient(pClient)
 
@@ -284,6 +304,24 @@ RRScreenSizeSet (ScreenPtr  pScreen,
 		 CARD32	    mmHeight);
 
 /*
+ * screen dispatch
+ */
+int 
+ProcRRGetScreenSizeRange (ClientPtr client);
+
+int
+ProcRRSetScreenSize (ClientPtr client);
+
+int
+ProcRRGetScreenResources (ClientPtr client);
+
+int
+ProcRRSetScreenConfig (ClientPtr client);
+
+int
+ProcRRGetScreenInfo (ClientPtr client);
+
+/*
  * Deliver a ScreenNotify event
  */
 void
@@ -414,6 +452,33 @@ RRCrtcSet (RRCrtcPtr    crtc,
 	   RROutputPtr  *outputs);
 
 /*
+ * Request that the Crtc gamma be changed
+ */
+
+Bool
+RRCrtcGammaSet (RRCrtcPtr   crtc,
+		CARD16	    *red,
+		CARD16	    *green,
+		CARD16	    *blue);
+
+/*
+ * Notify the extension that the Crtc gamma has been changed
+ * The driver calls this whenever it has changed the gamma values
+ * in the RRCrtcRec
+ */
+
+Bool
+RRCrtcGammaNotify (RRCrtcPtr	crtc);
+
+/*
+ * Set the size of the gamma table at server startup time
+ */
+
+Bool
+RRCrtcGammaSetSize (RRCrtcPtr	crtc,
+		    int		size);
+
+/*
  * Destroy a Crtc at shutdown
  */
 void
@@ -425,6 +490,25 @@ RRCrtcDestroy (RRCrtcPtr crtc);
 Bool
 RRCrtcInit (void);
 
+/*
+ * Crtc dispatch
+ */
+
+int
+ProcRRGetCrtcInfo (ClientPtr client);
+
+int
+ProcRRSetCrtcConfig (ClientPtr client);
+
+int
+ProcRRGetCrtcGammaSize (ClientPtr client);
+
+int
+ProcRRGetCrtcGamma (ClientPtr client);
+
+int
+ProcRRSetCrtcGamma (ClientPtr client);
+
 /* rrdispatch.c */
 Bool
 RRClientKnowsRates (ClientPtr	pClient);
@@ -452,6 +536,18 @@ RRModeDestroy (RRModePtr mode);
 Bool
 RRModeInit (void);
     
+int
+ProcRRCreateMode (ClientPtr client);
+
+int
+ProcRRDestroyMode (ClientPtr client);
+
+int
+ProcRRAddOutputMode (ClientPtr client);
+
+int
+ProcRRDeleteOutputMode (ClientPtr client);
+
 /* rroutput.c */
 /*
  * Create an output
@@ -498,10 +594,38 @@ RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output);
 void
 RROutputDestroy (RROutputPtr	output);
 
+int
+ProcRRGetOutputInfo (ClientPtr client);
+
 /*
  * Initialize output type
  */
 Bool
 RROutputInit (void);
     
+/* rrproperty.c */
+
+void
+RRDeleteAllOutputProperties (RROutputPtr output);
+
+void
+RRDeleteOutputProperty (RROutputPtr output, Atom property);
+
+int
+RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
+			int format, int mode, unsigned long len,
+			pointer value, Bool sendevent);
+
+int
+ProcRRChangeOutputProperty (ClientPtr client);
+
+int
+ProcRRGetOutputProperty (ClientPtr client);
+
+int
+ProcRRListOutputProperties (ClientPtr client);
+
+int
+ProcRRDeleteOutputProperty (ClientPtr client);
+
 #endif /* _RANDRSTR_H_ */
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index d1328e7..c55e088 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -21,6 +21,7 @@
  */
 
 #include "randrstr.h"
+#include "swaprep.h"
 
 RESTYPE	RRCrtcType;
 
@@ -57,6 +58,8 @@ RRCrtcCreate (ScreenPtr	pScreen,
     crtc->rotations = RR_Rotate_0;
     crtc->outputs = NULL;
     crtc->numOutputs = 0;
+    crtc->gammaSize = 0;
+    crtc->gammaRed = crtc->gammaBlue = crtc->gammaGreen = NULL;
     crtc->changed = TRUE;
     crtc->devPrivate = devPrivate;
 
@@ -241,11 +244,75 @@ RRCrtcDestroyResource (pointer value, XID pid)
 	    break;
 	}
     }
-    free (value);
+    if (crtc->gammaRed)
+	xfree (crtc->gammaRed);
+    xfree (value);
     return 1;
 }
 
 /*
+ * Request that the Crtc gamma be changed
+ */
+
+Bool
+RRCrtcGammaSet (RRCrtcPtr   crtc,
+		CARD16	    *red,
+		CARD16	    *green,
+		CARD16	    *blue)
+{
+    Bool	ret = TRUE;
+#if RANDR_12_INTERFACE
+    ScreenPtr	pScreen = crtc->pScreen;
+    rrScrPriv(pScreen);
+#endif
+    
+    memcpy (crtc->gammaRed, red, crtc->gammaSize * sizeof (CARD16));
+    memcpy (crtc->gammaGreen, green, crtc->gammaSize * sizeof (CARD16));
+    memcpy (crtc->gammaBlue, blue, crtc->gammaSize * sizeof (CARD16));
+#if RANDR_12_INTERFACE
+    if (pScrPriv->rrCrtcSetGamma)
+	ret = (*pScrPriv->rrCrtcSetGamma) (pScreen, crtc);
+#endif
+    return ret;
+}
+
+/*
+ * Notify the extension that the Crtc gamma has been changed
+ * The driver calls this whenever it has changed the gamma values
+ * in the RRCrtcRec
+ */
+
+Bool
+RRCrtcGammaNotify (RRCrtcPtr	crtc)
+{
+    return TRUE;    /* not much going on here */
+}
+
+/*
+ * Set the size of the gamma table at server startup time
+ */
+
+Bool
+RRCrtcGammaSetSize (RRCrtcPtr	crtc,
+		    int		size)
+{
+    CARD16  *gamma;
+
+    if (size == crtc->gammaSize)
+	return TRUE;
+    gamma = xalloc (size * 3 * sizeof (CARD16));
+    if (!gamma)
+	return FALSE;
+    if (crtc->gammaRed)
+	xfree (crtc->gammaRed);
+    crtc->gammaRed = gamma;
+    crtc->gammaGreen = gamma + size;
+    crtc->gammaBlue = gamma + size*2;
+    crtc->gammaSize = size;
+    return TRUE;
+}
+
+/*
  * Initialize crtc type
  */
 Bool
@@ -259,3 +326,395 @@ RRCrtcInit (void)
 #endif
     return TRUE;
 }
+
+int
+ProcRRGetCrtcInfo (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcInfoReq);;
+    xRRGetCrtcInfoReply	rep;
+    RRCrtcPtr			crtc;
+    CARD8			*extra;
+    unsigned long		extraLen;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    RRModePtr			mode;
+    RROutput			*outputs;
+    RROutput			*possible;
+    int				i, j, k, n;
+    
+    REQUEST_SIZE_MATCH(xRRGetCrtcInfoReq);
+    crtc = LookupCrtc(client, stuff->crtc, SecurityReadAccess);
+
+    if (!crtc)
+	return RRErrorBase + BadRRCrtc;
+
+    pScreen = crtc->pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+
+    mode = crtc->mode;
+    
+    rep.type = X_Reply;
+    rep.status = RRSetConfigSuccess;
+    rep.sequenceNumber = client->sequence;
+    rep.length = 0;
+    rep.timestamp = pScrPriv->lastSetTime.milliseconds;
+    rep.x = crtc->x;
+    rep.y = crtc->y;
+    rep.width = mode ? mode->mode.width : 0;
+    rep.height = mode ? mode->mode.height : 0;
+    rep.mode = mode->mode.id;
+    rep.rotation = crtc->rotation;
+    rep.rotations = crtc->rotations;
+    rep.nOutput = crtc->numOutputs;
+    k = 0;
+    for (i = 0; i < pScrPriv->numOutputs; i++)
+	for (j = 0; j < pScrPriv->outputs[i]->numCrtcs; j++)
+	    if (pScrPriv->outputs[i]->crtcs[j] == crtc)
+		k++;
+    rep.nPossibleOutput = k;
+    
+    rep.length = rep.nOutput + rep.nPossibleOutput;
+
+    extraLen = rep.length << 2;
+    extra = xalloc (extraLen);
+    if (!extra)
+	return BadAlloc;
+
+    outputs = (RROutput *) extra;
+    possible = (RROutput *) (outputs + rep.nOutput);
+    
+    for (i = 0; i < crtc->numOutputs; i++)
+    {
+	outputs[i] = crtc->outputs[i]->id;
+	if (client->swapped)
+	    swapl (&outputs[i], n);
+    }
+    k = 0;
+    for (i = 0; i < pScrPriv->numOutputs; i++)
+	for (j = 0; j < pScrPriv->outputs[i]->numCrtcs; j++)
+	    if (pScrPriv->outputs[i]->crtcs[j] == crtc)
+	    {
+		possible[k] = pScrPriv->outputs[i]->id;
+		if (client->swapped)
+		    swapl (&possible[k], n);
+		k++;
+	    }
+    
+    if (client->swapped) {
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.timestamp, n);
+	swaps(&rep.x, n);
+	swaps(&rep.y, n);
+	swaps(&rep.width, n);
+	swaps(&rep.height, n);
+	swapl(&rep.mode, n);
+	swaps(&rep.rotation, n);
+	swaps(&rep.rotations, n);
+	swaps(&rep.nOutput, n);
+	swaps(&rep.nPossibleOutput, n);
+    }
+    WriteToClient(client, sizeof(xRRGetCrtcInfoReply), (char *)&rep);
+    if (extraLen)
+    {
+	WriteToClient (client, extraLen, (char *) extra);
+	xfree (extra);
+    }
+    
+    return client->noClientException;
+}
+
+int
+ProcRRSetCrtcConfig (ClientPtr client)
+{
+    REQUEST(xRRSetCrtcConfigReq);
+    xRRSetCrtcConfigReply   rep;
+    ScreenPtr		    pScreen;
+    rrScrPrivPtr	    pScrPriv;
+    RRCrtcPtr		    crtc;
+    RRModePtr		    mode;
+    int			    numOutputs;
+    RROutputPtr		    *outputs = NULL;
+    RROutput		    *outputIds;
+    TimeStamp		    configTime;
+    TimeStamp		    time;
+    Rotation		    rotation;
+    int			    i, j;
+    
+    REQUEST_AT_LEAST_SIZE(xRRSetCrtcConfigReq);
+    numOutputs = stuff->length - (SIZEOF (xRRSetCrtcConfigReq) >> 2);
+    
+    crtc = LookupIDByType (stuff->crtc, RRCrtcType);
+    if (!crtc)
+    {
+	client->errorValue = stuff->crtc;
+	return RRErrorBase + BadRRCrtc;
+    }
+    if (stuff->mode == None)
+    {
+	mode = NULL;
+	if (numOutputs > 0)
+	    return BadMatch;
+    }
+    else
+    {
+	mode = LookupIDByType (stuff->mode, RRModeType);
+	if (!mode)
+	{
+	    client->errorValue = stuff->mode;
+	    return RRErrorBase + BadRRMode;
+	}
+	if (numOutputs == 0)
+	    return BadMatch;
+    }
+    outputs = xalloc (numOutputs * sizeof (RROutputPtr));
+    if (!outputs)
+	return BadAlloc;
+    
+    outputIds = (RROutput *) (stuff + 1);
+    for (i = 0; i < numOutputs; i++)
+    {
+	outputs[i] = LookupIDByType (outputIds[i], RROutputType);
+	if (!outputs[i])
+	{
+	    client->errorValue = outputIds[i];
+	    if (outputs)
+		xfree (outputs);
+	    return RRErrorBase + BadRROutput;
+	}
+	/* validate crtc for this output */
+	for (j = 0; j < outputs[i]->numCrtcs; j++)
+	    if (outputs[i]->crtcs[j] == crtc)
+		break;
+	if (j == outputs[j]->numCrtcs)
+	{
+	    if (outputs)
+		xfree (outputs);
+	    return BadMatch;
+	}
+	/* validate mode for this output */
+	for (j = 0; j < outputs[i]->numModes; j++)
+	    if (outputs[i]->modes[j] == mode)
+		break;
+	if (j == outputs[i]->numModes)
+	{
+	    if (outputs)
+		xfree (outputs);
+	    return BadMatch;
+	}
+    }
+
+    pScreen = crtc->pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    
+    if (!RRGetInfo (pScreen))
+    {
+	if (outputs)
+	    xfree (outputs);
+	return BadAlloc;
+    }
+    
+    time = ClientTimeToServerTime(stuff->timestamp);
+    configTime = ClientTimeToServerTime(stuff->configTimestamp);
+    
+    if (!pScrPriv)
+    {
+	time = currentTime;
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    
+    /*
+     * if the client's config timestamp is not the same as the last config
+     * timestamp, then the config information isn't up-to-date and
+     * can't even be validated
+     */
+    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
+    {
+	rep.status = RRSetConfigInvalidConfigTime;
+	goto sendReply;
+    }
+    
+    /*
+     * Validate requested rotation
+     */
+    rotation = (Rotation) stuff->rotation;
+
+    /* test the rotation bits only! */
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_90:
+    case RR_Rotate_180:
+    case RR_Rotate_270:
+	break;
+    default:
+	/*
+	 * Invalid rotation
+	 */
+	client->errorValue = stuff->rotation;
+	if (outputs)
+	    xfree (outputs);
+	return BadValue;
+    }
+
+    if ((~crtc->rotations) & rotation)
+    {
+	/*
+	 * requested rotation or reflection not supported by screen
+	 */
+	client->errorValue = stuff->rotation;
+	if (outputs)
+	    xfree (outputs);
+	return BadMatch;
+    }
+
+#ifdef RANDR_12_INTERFACE
+    /*
+     * Check screen size bounds if the DDX provides a 1.2 interface
+     * for setting screen size. Else, assume the CrtcSet sets
+     * the size along with the mode
+     */
+    if (pScrPriv->rrScreenSizeSet)
+    {
+	if (stuff->x + mode->mode.width > pScreen->width)
+	{
+	    client->errorValue = stuff->x;
+	    if (outputs)
+		xfree (outputs);
+	    return BadValue;
+	}
+	
+	if (stuff->y + mode->mode.height > pScreen->height)
+	{
+	    client->errorValue = stuff->y;
+	    if (outputs)
+		xfree (outputs);
+	    return BadValue;
+	}
+    }
+#endif
+    
+    /*
+     * Make sure the requested set-time is not older than
+     * the last set-time
+     */
+    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
+    {
+	rep.status = RRSetConfigInvalidTime;
+	goto sendReply;
+    }
+
+    rep.status = RRCrtcSet (crtc, mode, stuff->x, stuff->y,
+			    rotation, numOutputs, outputs);
+    
+sendReply:
+    if (outputs)
+	xfree (outputs);
+    
+    rep.type = X_Reply;
+    /* rep.status has already been filled in */
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.newTimestamp = pScrPriv->lastConfigTime.milliseconds;
+
+    if (client->swapped) 
+    {
+	int n;
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swapl(&rep.newTimestamp, n);
+    }
+    WriteToClient(client, sizeof(xRRSetCrtcConfigReply), (char *)&rep);
+    
+    return client->noClientException;
+}
+
+int
+ProcRRGetCrtcGammaSize (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcGammaSizeReq);
+    xRRGetCrtcGammaSizeReply	reply;
+    RRCrtcPtr			crtc;
+    int				n;
+
+    REQUEST_SIZE_MATCH(xRRGetCrtcGammaSizeReq);
+    crtc = LookupCrtc (client, stuff->crtc, SecurityReadAccess);
+    if (!crtc)
+	return RRErrorBase + BadRRCrtc;
+    
+    reply.type = X_Reply;
+    reply.sequenceNumber = client->sequence;
+    reply.length = 0;
+    reply.size = crtc->gammaSize;
+    if (client->swapped) {
+	swaps (&reply.sequenceNumber, n);
+	swapl (&reply.length, n);
+	swaps (&reply.size, n);
+    }
+    WriteToClient (client, sizeof (xRRGetCrtcGammaSizeReply), (char *) &reply);
+    return client->noClientException;
+}
+
+int
+ProcRRGetCrtcGamma (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcGammaReq);
+    xRRGetCrtcGammaReply	reply;
+    RRCrtcPtr			crtc;
+    int				n;
+    unsigned long		len;
+    
+    REQUEST_SIZE_MATCH(xRRGetCrtcGammaReq);
+    crtc = LookupCrtc (client, stuff->crtc, SecurityReadAccess);
+    if (!crtc)
+	return RRErrorBase + BadRRCrtc;
+    
+    len = crtc->gammaSize * 3 * 2;
+    
+    reply.type = X_Reply;
+    reply.sequenceNumber = client->sequence;
+    reply.length = (len + 3) >> 2;
+    reply.size = crtc->gammaSize;
+    if (client->swapped) {
+	swaps (&reply.sequenceNumber, n);
+	swapl (&reply.length, n);
+	swaps (&reply.size, n);
+    }
+    WriteToClient (client, sizeof (xRRGetCrtcGammaReply), (char *) &reply);
+    if (crtc->gammaSize)
+    {
+	client->pSwapReplyFunc = (ReplySwapPtr)CopySwap16Write;
+	WriteSwappedDataToClient (client, len, (char *) crtc->gammaRed);
+    }
+    return client->noClientException;
+}
+
+int
+ProcRRSetCrtcGamma (ClientPtr client)
+{
+    REQUEST(xRRSetCrtcGammaReq);
+    RRCrtcPtr			crtc;
+    unsigned long		len;
+    CARD16			*red, *green, *blue;
+    
+    REQUEST_SIZE_MATCH(xRRSetCrtcGammaReq);
+    crtc = LookupCrtc (client, stuff->crtc, SecurityWriteAccess);
+    if (!crtc)
+	return RRErrorBase + BadRRCrtc;
+    
+    len = client->req_len - (sizeof (xRRSetCrtcGammaReq) >> 2);
+    if (len < (stuff->size * 3 + 1) >> 1)
+	return BadLength;
+
+    if (stuff->size != crtc->gammaSize)
+	return BadMatch;
+    
+    red = (CARD16 *) (stuff + 1);
+    green = red + crtc->gammaSize;
+    blue = green + crtc->gammaSize;
+    
+    RRCrtcGammaSet (crtc, red, green, blue);
+
+    return Success;
+}
+
diff --git a/randr/rrdispatch.c b/randr/rrdispatch.c
index aca0e54..49ba10b 100644
--- a/randr/rrdispatch.c
+++ b/randr/rrdispatch.c
@@ -31,79 +31,6 @@ RRClientKnowsRates (ClientPtr	pClient)
 	    (pRRClient->major_version == 1 && pRRClient->minor_version >= 1));
 }
 
-typedef struct _RR10Data {
-    RRScreenSizePtr sizes;
-    int		    nsize;
-    int		    nrefresh;
-    int		    size;
-    CARD16	    refresh;
-} RR10DataRec, *RR10DataPtr;
-
-/*
- * Convert 1.2 monitor data into 1.0 screen data
- */
-static RR10DataPtr
-RR10GetData (ScreenPtr pScreen, RROutputPtr output)
-{
-    RR10DataPtr	    data;
-    RRScreenSizePtr size;
-    int		    nmode = output->numModes;
-    int		    i, j, k;
-    RRScreenRatePtr refresh;
-    CARD16	    vRefresh;
-    RRModePtr	    mode;
-
-    /* Make sure there is plenty of space for any combination */
-    data = malloc (sizeof (RR10DataRec) + 
-		   sizeof (RRScreenSize) * nmode + 
-		   sizeof (RRScreenRate) * nmode);
-    if (!data)
-	return NULL;
-    size = (RRScreenSizePtr) (data + 1);
-    refresh = (RRScreenRatePtr) (size + nmode);
-    data->sizes = size;
-    data->nsize = 0;
-    data->nrefresh = 0;
-    data->size = 0;
-    data->refresh = 0;
-    for (i = 0; i < output->numModes; i++)
-    {
-	mode = output->modes[i];
-	for (j = 0; j < data->nsize; j++)
-	    if (mode->mode.width == size[j].width &&
-		mode->mode.height == size[j].height)
-		break;
-	if (j == data->nsize)
-	{
-	    size[j].id = j;
-	    size[j].width = mode->mode.width;
-	    size[j].height = mode->mode.height;
-	    size[j].mmWidth = mode->mode.mmWidth;
-	    size[j].mmHeight = mode->mode.mmHeight;
-	    size[j].nRates = 0;
-	    size[j].pRates = &refresh[data->nrefresh];
-	    data->nsize++;
-	}
-	vRefresh = RRVerticalRefresh (&mode->mode);
-	for (k = 0; k < size[j].nRates; k++)
-	    if (vRefresh == size[j].pRates[k].rate)
-		break;
-	if (k == size[j].nRates)
-	{
-	    size[j].pRates[k].rate = vRefresh;
-	    size[j].pRates[k].mode = mode;
-	    size[j].nRates++;
-	    data->nrefresh++;
-	}
-	if (mode == output->crtc->mode)
-	{
-	    data->size = j;
-	    data->refresh = vRefresh;
-	}
-    }
-    return data;
-}
-
 static int
 ProcRRQueryVersion (ClientPtr client)
 {
@@ -135,341 +62,6 @@ ProcRRQueryVersion (ClientPtr client)
 }
 
 static int
-ProcRRGetScreenInfo (ClientPtr client)
-{
-    REQUEST(xRRGetScreenInfoReq);
-    xRRGetScreenInfoReply   rep;
-    WindowPtr	    	    pWin;
-    int			    n;
-    ScreenPtr		    pScreen;
-    rrScrPrivPtr	    pScrPriv;
-    CARD8		    *extra;
-    unsigned long	    extraLen;
-    RROutputPtr		    output;
-
-    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    rep.pad = 0;
-    
-    if (pScrPriv)
-	RRGetInfo (pScreen);
-
-    output = RRFirstOutput (pScreen);
-    
-    if (!pScrPriv || !output)
-    {
-	rep.type = X_Reply;
-	rep.setOfRotations = RR_Rotate_0;;
-	rep.sequenceNumber = client->sequence;
-	rep.length = 0;
-	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
-	rep.timestamp = currentTime.milliseconds;
-	rep.configTimestamp = currentTime.milliseconds;
-	rep.nSizes = 0;
-	rep.sizeID = 0;
-	rep.rotation = RR_Rotate_0;
-	rep.rate = 0;
-	rep.nrateEnts = 0;
-	extra = 0;
-	extraLen = 0;
-    }
-    else
-    {
-	int			i, j;
-	xScreenSizes		*size;
-	CARD16			*rates;
-	CARD8			*data8;
-	Bool			has_rate = RRClientKnowsRates (client);
-	RR10DataPtr		pData;
-	RRScreenSizePtr		pSize;
-    
-	pData = RR10GetData (pScreen, output);
-	if (!pData)
-	    return BadAlloc;
-	
-	rep.type = X_Reply;
-	rep.setOfRotations = output->crtc->rotations;
-	rep.sequenceNumber = client->sequence;
-	rep.length = 0;
-	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
-	rep.timestamp = pScrPriv->lastSetTime.milliseconds;
-	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
-	rep.rotation = output->crtc->rotation;
-	rep.nSizes = pData->nsize;
-        rep.nrateEnts = pData->nrefresh + pData->nsize;
-	rep.sizeID = pData->size;
-	rep.rate = pData->refresh;
-
-	extraLen = (rep.nSizes * sizeof (xScreenSizes) +
-		    rep.nrateEnts * sizeof (CARD16));
-
-	extra = (CARD8 *) xalloc (extraLen);
-	if (!extra)
-	{
-	    xfree (pData);
-	    return BadAlloc;
-	}
-	/*
-	 * First comes the size information
-	 */
-	size = (xScreenSizes *) extra;
-	rates = (CARD16 *) (size + rep.nSizes);
-	for (i = 0; i < pData->nsize; i++)
-	{
-	    pSize = &pData->sizes[i];
-	    size->widthInPixels = pSize->width;
-	    size->heightInPixels = pSize->height;
-	    size->widthInMillimeters = pSize->mmWidth;
-	    size->heightInMillimeters = pSize->mmHeight;
-	    if (client->swapped)
-	    {
-	        swaps (&size->widthInPixels, n);
-	        swaps (&size->heightInPixels, n);
-	        swaps (&size->widthInMillimeters, n);
-	        swaps (&size->heightInMillimeters, n);
-	    }
-	    size++;
-	    if (has_rate)
-	    {
-		*rates = pSize->nRates;
-		if (client->swapped)
-		{
-		    swaps (rates, n);
-		}
-		rates++;
-		for (j = 0; j < pSize->nRates; j++)
-		{
-		    *rates = pSize->pRates[j].rate;
-		    if (client->swapped)
-		    {
-			swaps (rates, n);
-		    }
-		    rates++;
-		}
-	    }
-	}
-        xfree (pData);
-	
-	data8 = (CARD8 *) rates;
-
-	if (data8 - (CARD8 *) extra != extraLen)
-	    FatalError ("RRGetScreenInfo bad extra len %ld != %ld\n",
-			(unsigned long)(data8 - (CARD8 *) extra), extraLen);
-	rep.length =  (extraLen + 3) >> 2;
-    }
-    if (client->swapped) {
-	swaps(&rep.sequenceNumber, n);
-	swapl(&rep.length, n);
-	swapl(&rep.timestamp, n);
-	swaps(&rep.rotation, n);
-	swaps(&rep.nSizes, n);
-	swaps(&rep.sizeID, n);
-	swaps(&rep.rate, n);
-	swaps(&rep.nrateEnts, n);
-    }
-    WriteToClient(client, sizeof(xRRGetScreenInfoReply), (char *)&rep);
-    if (extraLen)
-    {
-	WriteToClient (client, extraLen, (char *) extra);
-	xfree (extra);
-    }
-    return (client->noClientException);
-}
-
-static int
-ProcRRSetScreenConfig (ClientPtr client)
-{
-    REQUEST(xRRSetScreenConfigReq);
-    xRRSetScreenConfigReply rep;
-    DrawablePtr		    pDraw;
-    int			    n;
-    ScreenPtr		    pScreen;
-    rrScrPrivPtr	    pScrPriv;
-    TimeStamp		    configTime;
-    TimeStamp		    time;
-    int			    i;
-    Rotation		    rotation;
-    int			    rate;
-    Bool		    has_rate;
-    RROutputPtr		    output;
-    RRModePtr		    mode;
-    RR10DataPtr		    pData = NULL;
-    RRScreenSizePtr    	    pSize;
-    
-    UpdateCurrentTime ();
-
-    if (RRClientKnowsRates (client))
-    {
-	REQUEST_SIZE_MATCH (xRRSetScreenConfigReq);
-	has_rate = TRUE;
-    }
-    else
-    {
-	REQUEST_SIZE_MATCH (xRR1_0SetScreenConfigReq);
-	has_rate = FALSE;
-    }
-    
-    SECURITY_VERIFY_DRAWABLE(pDraw, stuff->drawable, client,
-			     SecurityWriteAccess);
-
-    pScreen = pDraw->pScreen;
-
-    pScrPriv = rrGetScrPriv(pScreen);
-    
-    time = ClientTimeToServerTime(stuff->timestamp);
-    configTime = ClientTimeToServerTime(stuff->configTimestamp);
-    
-    if (!pScrPriv)
-    {
-	time = currentTime;
-	rep.status = RRSetConfigFailed;
-	goto sendReply;
-    }
-    if (!RRGetInfo (pScreen))
-	return BadAlloc;
-    
-    output = RRFirstOutput (pScreen);
-    if (!output)
-    {
-	time = currentTime;
-	rep.status = RRSetConfigFailed;
-	goto sendReply;
-    }
-    
-    /*
-     * if the client's config timestamp is not the same as the last config
-     * timestamp, then the config information isn't up-to-date and
-     * can't even be validated
-     */
-    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
-    {
-	rep.status = RRSetConfigInvalidConfigTime;
-	goto sendReply;
-    }
-    
-    pData = RR10GetData (pScreen, output);
-    if (!pData)
-	return BadAlloc;
-    
-    if (stuff->sizeID >= pData->nsize)
-    {
-	/*
-	 * Invalid size ID
-	 */
-	client->errorValue = stuff->sizeID;
-	xfree (pData);
-	return BadValue;
-    }
-    pSize = &pData->sizes[stuff->sizeID];
-    
-    /*
-     * Validate requested rotation
-     */
-    rotation = (Rotation) stuff->rotation;
-
-    /* test the rotation bits only! */
-    switch (rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_90:
-    case RR_Rotate_180:
-    case RR_Rotate_270:
-	break;
-    default:
-	/*
-	 * Invalid rotation
-	 */
-	client->errorValue = stuff->rotation;
-	xfree (pData);
-	return BadValue;
-    }
-
-    if ((~output->crtc->rotations) & rotation)
-    {
-	/*
-	 * requested rotation or reflection not supported by screen
-	 */
-	client->errorValue = stuff->rotation;
-	xfree (pData);
-	return BadMatch;
-    }
-
-    /*
-     * Validate requested refresh
-     */
-    if (has_rate)
-	rate = (int) stuff->rate;
-    else
-	rate = 0;
-
-    if (rate)
-    {
-	for (i = 0; i < pSize->nRates; i++)
-	{
-	    if (pSize->pRates[i].rate == rate)
-		break;
-	}
-	if (i == pSize->nRates)
-	{
-	    /*
-	     * Invalid rate
-	     */
-	    client->errorValue = rate;
-	    xfree (pData);
-	    return BadValue;
-	}
-	mode = pSize->pRates[i].mode;
-    }
-    else
-	mode = pSize->pRates[0].mode;
-    
-    /*
-     * Make sure the requested set-time is not older than
-     * the last set-time
-     */
-    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
-    {
-	rep.status = RRSetConfigInvalidTime;
-	goto sendReply;
-    }
-
-    rep.status = RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation,
-			    1, &output);
-    
-sendReply:
-    
-    if (pData)
-	xfree (pData);
-
-    rep.type = X_Reply;
-    /* rep.status has already been filled in */
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-
-    rep.newTimestamp = pScrPriv->lastSetTime.milliseconds;
-    rep.newConfigTimestamp = pScrPriv->lastConfigTime.milliseconds;
-    rep.root = WindowTable[pDraw->pScreen->myNum]->drawable.id;
-
-    if (client->swapped) 
-    {
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-	swapl(&rep.newTimestamp, n);
-	swapl(&rep.newConfigTimestamp, n);
-	swapl(&rep.root, n);
-    }
-    WriteToClient(client, sizeof(xRRSetScreenConfigReply), (char *)&rep);
-
-    return (client->noClientException);
-}
-
-static int
 ProcRRSelectInput (ClientPtr client)
 {
     REQUEST(xRRSelectInputReq);
@@ -584,633 +176,6 @@ ProcRRSelectInput (ClientPtr client)
     return Success;
 }
 
-/*
- * Retrieve valid screen size range
- */
-static int 
-ProcRRGetScreenSizeRange (ClientPtr client)
-{
-    REQUEST(xRRGetScreenSizeRangeReq);
-    xRRGetScreenSizeRangeReply	rep;
-    WindowPtr			pWin;
-    ScreenPtr			pScreen;
-    rrScrPrivPtr		pScrPriv;
-    
-    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    
-    rep.type = X_Reply;
-    rep.pad = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.length = 0;
-    
-    if (pScrPriv) 
-    {
-	RRGetInfo (pScreen);
-	rep.minWidth  = pScrPriv->minWidth;
-	rep.minHeight = pScrPriv->minHeight;
-	rep.maxWidth  = pScrPriv->maxWidth;
-	rep.maxHeight = pScrPriv->maxHeight;
-    }
-    else
-    {
-	rep.maxWidth  = rep.minWidth  = pScreen->width;
-	rep.maxHeight = rep.minHeight = pScreen->height;
-    }
-    if (client->swapped) 
-    {
-	int n;
-	
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-	swaps(&rep.minWidth, n);
-	swaps(&rep.minHeight, n);
-	swaps(&rep.maxWidth, n);
-	swaps(&rep.maxHeight, n);
-    }
-    WriteToClient(client, sizeof(xRRGetScreenSizeRangeReply), (char *)&rep);
-    return (client->noClientException);
-}
-
-static int ProcRRSetScreenSize (ClientPtr client)
-{
-    REQUEST(xRRSetScreenSizeReq);
-    WindowPtr		pWin;
-    ScreenPtr		pScreen;
-    rrScrPrivPtr	pScrPriv;
-    RRCrtcPtr		crtc;
-    int			i;
-    
-    REQUEST_SIZE_MATCH(xRRSetScreenSizeReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    if (stuff->width < pScrPriv->minWidth || pScrPriv->maxWidth < stuff->width)
-    {
-	client->errorValue = stuff->width;
-	return BadValue;
-    }
-    if (stuff->height < pScrPriv->minHeight || 
-	pScrPriv->maxHeight < stuff->height)
-    {
-	client->errorValue = stuff->height;
-	return BadValue;
-    }
-    for (i = 0; i < pScrPriv->numCrtcs; i++) {
-	crtc = pScrPriv->crtcs[i];
-	if (crtc->mode &&
-	    (crtc->x + crtc->mode->mode.width > stuff->width ||
-	     crtc->y + crtc->mode->mode.height > stuff->height))
-	    return BadMatch;
-    }
-    if (stuff->widthInMillimeters == 0 || stuff->heightInMillimeters == 0)
-    {
-	client->errorValue = 0;
-	return BadValue;
-    }
-    if (!RRScreenSizeSet (pScreen, 
-			  stuff->width, stuff->height,
-			  stuff->widthInMillimeters,
-			  stuff->heightInMillimeters))
-    {
-	return BadMatch;
-    }
-    return Success;
-}
-
-static int
-ProcRRGetScreenResources (ClientPtr client)
-{
-    REQUEST(xRRGetScreenResourcesReq);
-    xRRGetScreenResourcesReply  rep;
-    WindowPtr			pWin;
-    ScreenPtr			pScreen;
-    rrScrPrivPtr		pScrPriv;
-    CARD8			*extra;
-    unsigned long		extraLen;
-    int				i;
-    RRCrtc			*crtcs;
-    RROutput			*outputs;
-    xRRModeInfo			*modeinfos;
-    CARD8			*names;
-    int				n;
-    
-    REQUEST_SIZE_MATCH(xRRGetScreenResourcesReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-    
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    rep.pad = 0;
-    
-    if (pScrPriv)
-	RRGetInfo (pScreen);
-
-    if (!pScrPriv)
-    {
-	rep.type = X_Reply;
-	rep.sequenceNumber = client->sequence;
-	rep.length = 0;
-	rep.timestamp = currentTime.milliseconds;
-	rep.configTimestamp = currentTime.milliseconds;
-	rep.nCrtcs = 0;
-	rep.nOutputs = 0;
-	rep.nModes = 0;
-	rep.nbytesNames = 0;
-	extra = NULL;
-	extraLen = 0;
-    }
-    else
-    {
-	rep.type = X_Reply;
-	rep.sequenceNumber = client->sequence;
-	rep.length = 0;
-	rep.timestamp = currentTime.milliseconds;
-	rep.configTimestamp = currentTime.milliseconds;
-	rep.nCrtcs = pScrPriv->numCrtcs;
-	rep.nOutputs = pScrPriv->numOutputs;
-	rep.nModes = pScrPriv->numModes;;
-	rep.nbytesNames = 0;
-
-	for (i = 0; i < pScrPriv->numModes; i++)
-	    rep.nbytesNames += pScrPriv->modes[i]->mode.nameLength;
-
-	rep.length = (pScrPriv->numCrtcs + 
-		      pScrPriv->numOutputs + 
-		      pScrPriv->numModes * 10 +
-		      ((rep.nbytesNames + 3) >> 2));
-	
-	extraLen = rep.length << 2;
-	extra = xalloc (extraLen);
-	if (!extra)
-	    return BadAlloc;
-
-	crtcs = (RRCrtc *) extra;
-	outputs = (RROutput *) (crtcs + pScrPriv->numCrtcs);
-	modeinfos = (xRRModeInfo *) (outputs + pScrPriv->numOutputs);
-	names = (CARD8 *) (modeinfos + pScrPriv->numModes);
-	
-	for (i = 0; i < pScrPriv->numCrtcs; i++)
-	{
-	    crtcs[i] = pScrPriv->crtcs[i]->id;
-	    if (client->swapped)
-		swapl (&crtcs[i], n);
-	}
-	
-	for (i = 0; i < pScrPriv->numOutputs; i++)
-	{
-	    outputs[i] = pScrPriv->outputs[i]->id;
-	    if (client->swapped)
-		swapl (&outputs[i], n);
-	}
-	
-	for (i = 0; i < pScrPriv->numModes; i++)
-	{
-	    modeinfos[i] = pScrPriv->modes[i]->mode;
-	    if (client->swapped)
-	    {
-		swapl (&modeinfos[i].id, n);
-		swaps (&modeinfos[i].width, n);
-		swaps (&modeinfos[i].height, n);
-		swapl (&modeinfos[i].mmWidth, n);
-		swapl (&modeinfos[i].mmHeight, n);
-		swapl (&modeinfos[i].dotClock, n);
-		swaps (&modeinfos[i].hSyncStart, n);
-		swaps (&modeinfos[i].hSyncEnd, n);
-		swaps (&modeinfos[i].hTotal, n);
-		swaps (&modeinfos[i].hSkew, n);
-		swaps (&modeinfos[i].vSyncStart, n);
-		swaps (&modeinfos[i].vSyncEnd, n);
-		swaps (&modeinfos[i].vTotal, n);
-		swaps (&modeinfos[i].nameLength, n);
-		swapl (&modeinfos[i].modeFlags, n);
-	    }
-	    memcpy (names, pScrPriv->modes[i]->name, 
-		    pScrPriv->modes[i]->mode.nameLength);
-	    names += pScrPriv->modes[i]->mode.nameLength;
-	}
-	assert ((names + 3 >> 3) == rep.length);
-    }
-    
-    if (client->swapped) {
-	swaps(&rep.sequenceNumber, n);
-	swapl(&rep.length, n);
-	swapl(&rep.timestamp, n);
-	swapl(&rep.configTimestamp, n);
-	swaps(&rep.nCrtcs, n);
-	swaps(&rep.nOutputs, n);
-	swaps(&rep.nModes, n);
-	swaps(&rep.nbytesNames, n);
-    }
-    WriteToClient(client, sizeof(xRRGetScreenResourcesReply), (char *)&rep);
-    if (extraLen)
-    {
-	WriteToClient (client, extraLen, (char *) extra);
-	xfree (extra);
-    }
-    return client->noClientException;
-}
-
-static int
-ProcRRGetOutputInfo (ClientPtr client)
-{
-    REQUEST(xRRGetOutputInfoReq);;
-    xRRGetOutputInfoReply	rep;
-    RROutputPtr			output;
-    CARD8			*extra;
-    unsigned long		extraLen;
-    ScreenPtr			pScreen;
-    rrScrPrivPtr		pScrPriv;
-    RRCrtc			*crtcs;
-    RRMode			*modes;
-    RROutput			*clones;
-    char			*name;
-    int				i, n;
-    
-    REQUEST_SIZE_MATCH(xRRGetOutputInfoReq);
-    output = (RROutputPtr)SecurityLookupIDByType(client, stuff->output, 
-						 RROutputType, 
-						 SecurityReadAccess);
-
-    if (!output)
-	return RRErrorBase + BadRROutput;
-
-    pScreen = output->pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-
-    rep.type = X_Reply;
-    rep.sequenceNumber = client->sequence;
-    rep.length = 0;
-    rep.timestamp = pScrPriv->lastSetTime.milliseconds;
-    rep.crtc = output->crtc ? output->crtc->id : None;
-    rep.connection = output->connection;
-    rep.subpixelOrder = output->subpixelOrder;
-    rep.nCrtcs = output->numCrtcs;
-    rep.nModes = output->numModes;
-    rep.nClones = output->numClones;
-    rep.nameLength = output->nameLength;
-    
-    rep.length = (output->numCrtcs + 
-		  output->numModes + 
-		  output->numClones +
-		  ((rep.nameLength + 3) >> 2));
-
-    extraLen = rep.length << 2;
-    extra = xalloc (extraLen);
-    if (!extra)
-	return BadAlloc;
-
-    crtcs = (RRCrtc *) extra;
-    modes = (RRMode *) (crtcs + output->numCrtcs);
-    clones = (RROutput *) (modes + output->numModes);
-    name = (char *) (clones + output->numClones);
-    
-    for (i = 0; i < output->numCrtcs; i++)
-    {
-	crtcs[i] = output->crtcs[i]->id;
-	if (client->swapped)
-	    swapl (&crtcs[i], n);
-    }
-    for (i = 0; i < output->numModes; i++)
-    {
-	modes[i] = output->modes[i]->mode.id;
-	if (client->swapped)
-	    swapl (&modes[i], n);
-    }
-    for (i = 0; i < output->numClones; i++)
-    {
-	clones[i] = output->clones[i]->id;
-	if (client->swapped)
-	    swapl (&clones[i], n);
-    }
-    memcpy (name, output->name, output->nameLength);
-    if (client->swapped) {
-	swaps(&rep.sequenceNumber, n);
-	swapl(&rep.length, n);
-	swapl(&rep.timestamp, n);
-	swapl(&rep.crtc, n);
-	swaps(&rep.nCrtcs, n);
-	swaps(&rep.nModes, n);
-	swaps(&rep.nClones, n);
-	swaps(&rep.nameLength, n);
-    }
-    WriteToClient(client, sizeof(xRRGetOutputInfoReply), (char *)&rep);
-    if (extraLen)
-    {
-	WriteToClient (client, extraLen, (char *) extra);
-	xfree (extra);
-    }
-    
-    return client->noClientException;
-}
-
-static int
-ProcRRListOutputProperties (ClientPtr client)
-{
-    REQUEST(xRRListOutputPropertiesReq);
-    
-    REQUEST_SIZE_MATCH(xRRListOutputPropertiesReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRChangeOutputProperty (ClientPtr client)
-{
-    REQUEST(xRRChangeOutputPropertyReq);
-    
-    REQUEST_SIZE_MATCH(xRRChangeOutputPropertyReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRDeleteOutputProperty (ClientPtr client)
-{
-    REQUEST(xRRDeleteOutputPropertyReq);
-    
-    REQUEST_SIZE_MATCH(xRRDeleteOutputPropertyReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRGetOutputProperty (ClientPtr client)
-{
-    REQUEST(xRRGetOutputPropertyReq);
-    
-    REQUEST_SIZE_MATCH(xRRGetOutputPropertyReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRCreateMode (ClientPtr client)
-{
-    REQUEST(xRRCreateModeReq);
-    
-    REQUEST_SIZE_MATCH(xRRCreateModeReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRDestroyMode (ClientPtr client)
-{
-    REQUEST(xRRDestroyModeReq);
-    
-    REQUEST_SIZE_MATCH(xRRDestroyModeReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRAddOutputMode (ClientPtr client)
-{
-    REQUEST(xRRAddOutputModeReq);
-    
-    REQUEST_SIZE_MATCH(xRRAddOutputModeReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRDeleteOutputMode (ClientPtr client)
-{
-    REQUEST(xRRDeleteOutputModeReq);
-    
-    REQUEST_SIZE_MATCH(xRRDeleteOutputModeReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRGetCrtcInfo (ClientPtr client)
-{
-    REQUEST(xRRGetCrtcInfoReq);
-    
-    REQUEST_SIZE_MATCH(xRRGetCrtcInfoReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRSetCrtcConfig (ClientPtr client)
-{
-    REQUEST(xRRSetCrtcConfigReq);
-    xRRSetCrtcConfigReply   rep;
-    ScreenPtr		    pScreen;
-    rrScrPrivPtr	    pScrPriv;
-    RRCrtcPtr		    crtc;
-    RRModePtr		    mode;
-    int			    numOutputs;
-    RROutputPtr		    *outputs = NULL;
-    RROutput		    *outputIds;
-    TimeStamp		    configTime;
-    TimeStamp		    time;
-    Rotation		    rotation;
-    int			    i, j;
-    
-    REQUEST_AT_LEAST_SIZE(xRRSetCrtcConfigReq);
-    numOutputs = stuff->length - (SIZEOF (xRRSetCrtcConfigReq) >> 2);
-    
-    crtc = LookupIDByType (stuff->crtc, RRCrtcType);
-    if (!crtc)
-    {
-	client->errorValue = stuff->crtc;
-	return RRErrorBase + BadRRCrtc;
-    }
-    if (stuff->mode == None)
-    {
-	mode = NULL;
-	if (numOutputs > 0)
-	    return BadMatch;
-    }
-    else
-    {
-	mode = LookupIDByType (stuff->mode, RRModeType);
-	if (!mode)
-	{
-	    client->errorValue = stuff->mode;
-	    return RRErrorBase + BadRRMode;
-	}
-	if (numOutputs == 0)
-	    return BadMatch;
-    }
-    outputs = xalloc (numOutputs * sizeof (RROutputPtr));
-    if (!outputs)
-	return BadAlloc;
-    
-    outputIds = (RROutput *) (stuff + 1);
-    for (i = 0; i < numOutputs; i++)
-    {
-	outputs[i] = LookupIDByType (outputIds[i], RROutputType);
-	if (!outputs[i])
-	{
-	    client->errorValue = outputIds[i];
-	    return RRErrorBase + BadRROutput;
-	}
-	/* validate crtc for this output */
-	for (j = 0; j < outputs[i]->numCrtcs; j++)
-	    if (outputs[i]->crtcs[j] == crtc)
-		break;
-	if (j == outputs[j]->numCrtcs)
-	    return BadMatch;
-	/* validate mode for this output */
-	for (j = 0; j < outputs[i]->numModes; j++)
-	    if (outputs[i]->modes[j] == mode)
-		break;
-	if (j == outputs[j]->numModes)
-	    return BadMatch;
-    }
-
-    pScreen = crtc->pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    
-    time = ClientTimeToServerTime(stuff->timestamp);
-    configTime = ClientTimeToServerTime(stuff->configTimestamp);
-    
-    if (!pScrPriv)
-    {
-	time = currentTime;
-	rep.status = RRSetConfigFailed;
-	goto sendReply;
-    }
-    if (!RRGetInfo (pScreen))
-	return BadAlloc;
-    
-    /*
-     * if the client's config timestamp is not the same as the last config
-     * timestamp, then the config information isn't up-to-date and
-     * can't even be validated
-     */
-    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
-    {
-	rep.status = RRSetConfigInvalidConfigTime;
-	goto sendReply;
-    }
-    
-    /*
-     * Validate requested rotation
-     */
-    rotation = (Rotation) stuff->rotation;
-
-    /* test the rotation bits only! */
-    switch (rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_90:
-    case RR_Rotate_180:
-    case RR_Rotate_270:
-	break;
-    default:
-	/*
-	 * Invalid rotation
-	 */
-	client->errorValue = stuff->rotation;
-	return BadValue;
-    }
-
-    if ((~crtc->rotations) & rotation)
-    {
-	/*
-	 * requested rotation or reflection not supported by screen
-	 */
-	client->errorValue = stuff->rotation;
-	return BadMatch;
-    }
-
-    if (stuff->x + mode->mode.width > pScreen->width)
-    {
-	client->errorValue = stuff->x;
-	return BadValue;
-    }
-    
-    if (stuff->y + mode->mode.height > pScreen->height)
-    {
-	client->errorValue = stuff->y;
-	return BadValue;
-    }
-    
-    /*
-     * Make sure the requested set-time is not older than
-     * the last set-time
-     */
-    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
-    {
-	rep.status = RRSetConfigInvalidTime;
-	goto sendReply;
-    }
-
-    rep.status = RRCrtcSet (crtc, mode, stuff->x, stuff->y,
-			    rotation, numOutputs, outputs);
-    
-sendReply:
-    if (outputs)
-	xfree (outputs);
-    
-    rep.type = X_Reply;
-    /* rep.status has already been filled in */
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.newTimestamp = pScrPriv->lastConfigTime.milliseconds;
-
-    if (client->swapped) 
-    {
-	int n;
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-	swapl(&rep.newTimestamp, n);
-    }
-    WriteToClient(client, sizeof(xRRSetCrtcConfigReply), (char *)&rep);
-    
-    return client->noClientException;
-}
-
-static int
-ProcRRGetCrtcGammaSize (ClientPtr client)
-{
-    REQUEST(xRRGetCrtcGammaSizeReq);
-    
-    REQUEST_SIZE_MATCH(xRRGetCrtcGammaSizeReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRGetCrtcGamma (ClientPtr client)
-{
-    REQUEST(xRRGetCrtcGammaReq);
-    
-    REQUEST_SIZE_MATCH(xRRGetCrtcGammaReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
-static int
-ProcRRSetCrtcGamma (ClientPtr client)
-{
-    REQUEST(xRRSetCrtcGammaReq);
-    
-    REQUEST_SIZE_MATCH(xRRSetCrtcGammaReq);
-    (void) stuff;
-    return BadImplementation; 
-}
-
 int (*ProcRandrVector[RRNumberRequests])(ClientPtr) = {
     ProcRRQueryVersion,	/* 0 */
 /* we skip 1 to make old clients fail pretty immediately */
diff --git a/randr/rrmode.c b/randr/rrmode.c
index 4e44e7d..ab0ea18 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -103,3 +103,44 @@ RRModeInit (void)
 #endif
     return TRUE;
 }
+
+int
+ProcRRCreateMode (ClientPtr client)
+{
+    REQUEST(xRRCreateModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRCreateModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+int
+ProcRRDestroyMode (ClientPtr client)
+{
+    REQUEST(xRRDestroyModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRDestroyModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+int
+ProcRRAddOutputMode (ClientPtr client)
+{
+    REQUEST(xRRAddOutputModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRAddOutputModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+int
+ProcRRDeleteOutputMode (ClientPtr client)
+{
+    REQUEST(xRRDeleteOutputModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRDeleteOutputModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 4780023..07dabad 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -66,6 +66,7 @@ RROutputCreate (ScreenPtr   pScreen,
     output->clones = NULL;
     output->numModes = 0;
     output->modes = NULL;
+    output->properties = NULL;
     output->changed = TRUE;
     output->devPrivate = devPrivate;
     
@@ -201,12 +202,13 @@ RROutputDestroyResource (pointer value, XID pid)
 	xfree (output->crtcs);
     if (output->clones)
 	xfree (output->clones);
+    RRDeleteAllOutputProperties (output);
     xfree (output);
     return 1;
 }
 
 /*
- * Initialize crtc type
+ * Initialize output type
  */
 Bool
 RROutputInit (void)
@@ -219,3 +221,95 @@ RROutputInit (void)
 #endif
     return TRUE;
 }
+
+int
+ProcRRGetOutputInfo (ClientPtr client)
+{
+    REQUEST(xRRGetOutputInfoReq);;
+    xRRGetOutputInfoReply	rep;
+    RROutputPtr			output;
+    CARD8			*extra;
+    unsigned long		extraLen;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    RRCrtc			*crtcs;
+    RRMode			*modes;
+    RROutput			*clones;
+    char			*name;
+    int				i, n;
+    
+    REQUEST_SIZE_MATCH(xRRGetOutputInfoReq);
+    output = LookupOutput(client, stuff->output, SecurityReadAccess);
+
+    if (!output)
+	return RRErrorBase + BadRROutput;
+
+    pScreen = output->pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+
+    rep.type = X_Reply;
+    rep.sequenceNumber = client->sequence;
+    rep.length = 0;
+    rep.timestamp = pScrPriv->lastSetTime.milliseconds;
+    rep.crtc = output->crtc ? output->crtc->id : None;
+    rep.connection = output->connection;
+    rep.subpixelOrder = output->subpixelOrder;
+    rep.nCrtcs = output->numCrtcs;
+    rep.nModes = output->numModes;
+    rep.nClones = output->numClones;
+    rep.nameLength = output->nameLength;
+    
+    rep.length = (output->numCrtcs + 
+		  output->numModes + 
+		  output->numClones +
+		  ((rep.nameLength + 3) >> 2));
+
+    extraLen = rep.length << 2;
+    extra = xalloc (extraLen);
+    if (!extra)
+	return BadAlloc;
+
+    crtcs = (RRCrtc *) extra;
+    modes = (RRMode *) (crtcs + output->numCrtcs);
+    clones = (RROutput *) (modes + output->numModes);
+    name = (char *) (clones + output->numClones);
+    
+    for (i = 0; i < output->numCrtcs; i++)
+    {
+	crtcs[i] = output->crtcs[i]->id;
+	if (client->swapped)
+	    swapl (&crtcs[i], n);
+    }
+    for (i = 0; i < output->numModes; i++)
+    {
+	modes[i] = output->modes[i]->mode.id;
+	if (client->swapped)
+	    swapl (&modes[i], n);
+    }
+    for (i = 0; i < output->numClones; i++)
+    {
+	clones[i] = output->clones[i]->id;
+	if (client->swapped)
+	    swapl (&clones[i], n);
+    }
+    memcpy (name, output->name, output->nameLength);
+    if (client->swapped) {
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.timestamp, n);
+	swapl(&rep.crtc, n);
+	swaps(&rep.nCrtcs, n);
+	swaps(&rep.nModes, n);
+	swaps(&rep.nClones, n);
+	swaps(&rep.nameLength, n);
+    }
+    WriteToClient(client, sizeof(xRRGetOutputInfoReply), (char *)&rep);
+    if (extraLen)
+    {
+	WriteToClient (client, extraLen, (char *) extra);
+	xfree (extra);
+    }
+    
+    return client->noClientException;
+}
+
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 47ba12d..58d5152 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -203,3 +203,654 @@ RRScreenSizeSet (ScreenPtr  pScreen,
     return FALSE;
 }
 
+/*
+ * Retrieve valid screen size range
+ */
+int 
+ProcRRGetScreenSizeRange (ClientPtr client)
+{
+    REQUEST(xRRGetScreenSizeRangeReq);
+    xRRGetScreenSizeRangeReply	rep;
+    WindowPtr			pWin;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    
+    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    
+    rep.type = X_Reply;
+    rep.pad = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.length = 0;
+    
+    if (pScrPriv) 
+    {
+	RRGetInfo (pScreen);
+	rep.minWidth  = pScrPriv->minWidth;
+	rep.minHeight = pScrPriv->minHeight;
+	rep.maxWidth  = pScrPriv->maxWidth;
+	rep.maxHeight = pScrPriv->maxHeight;
+    }
+    else
+    {
+	rep.maxWidth  = rep.minWidth  = pScreen->width;
+	rep.maxHeight = rep.minHeight = pScreen->height;
+    }
+    if (client->swapped) 
+    {
+	int n;
+	
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swaps(&rep.minWidth, n);
+	swaps(&rep.minHeight, n);
+	swaps(&rep.maxWidth, n);
+	swaps(&rep.maxHeight, n);
+    }
+    WriteToClient(client, sizeof(xRRGetScreenSizeRangeReply), (char *)&rep);
+    return (client->noClientException);
+}
+
+int
+ProcRRSetScreenSize (ClientPtr client)
+{
+    REQUEST(xRRSetScreenSizeReq);
+    WindowPtr		pWin;
+    ScreenPtr		pScreen;
+    rrScrPrivPtr	pScrPriv;
+    RRCrtcPtr		crtc;
+    int			i;
+    
+    REQUEST_SIZE_MATCH(xRRSetScreenSizeReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    if (stuff->width < pScrPriv->minWidth || pScrPriv->maxWidth < stuff->width)
+    {
+	client->errorValue = stuff->width;
+	return BadValue;
+    }
+    if (stuff->height < pScrPriv->minHeight || 
+	pScrPriv->maxHeight < stuff->height)
+    {
+	client->errorValue = stuff->height;
+	return BadValue;
+    }
+    for (i = 0; i < pScrPriv->numCrtcs; i++) {
+	crtc = pScrPriv->crtcs[i];
+	if (crtc->mode &&
+	    (crtc->x + crtc->mode->mode.width > stuff->width ||
+	     crtc->y + crtc->mode->mode.height > stuff->height))
+	    return BadMatch;
+    }
+    if (stuff->widthInMillimeters == 0 || stuff->heightInMillimeters == 0)
+    {
+	client->errorValue = 0;
+	return BadValue;
+    }
+    if (!RRScreenSizeSet (pScreen, 
+			  stuff->width, stuff->height,
+			  stuff->widthInMillimeters,
+			  stuff->heightInMillimeters))
+    {
+	return BadMatch;
+    }
+    return Success;
+}
+
+int
+ProcRRGetScreenResources (ClientPtr client)
+{
+    REQUEST(xRRGetScreenResourcesReq);
+    xRRGetScreenResourcesReply  rep;
+    WindowPtr			pWin;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    CARD8			*extra;
+    unsigned long		extraLen;
+    int				i;
+    RRCrtc			*crtcs;
+    RROutput			*outputs;
+    xRRModeInfo			*modeinfos;
+    CARD8			*names;
+    int				n;
+    
+    REQUEST_SIZE_MATCH(xRRGetScreenResourcesReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+    
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    rep.pad = 0;
+    
+    if (pScrPriv)
+	RRGetInfo (pScreen);
+
+    if (!pScrPriv)
+    {
+	rep.type = X_Reply;
+	rep.sequenceNumber = client->sequence;
+	rep.length = 0;
+	rep.timestamp = currentTime.milliseconds;
+	rep.configTimestamp = currentTime.milliseconds;
+	rep.nCrtcs = 0;
+	rep.nOutputs = 0;
+	rep.nModes = 0;
+	rep.nbytesNames = 0;
+	extra = NULL;
+	extraLen = 0;
+    }
+    else
+    {
+	rep.type = X_Reply;
+	rep.sequenceNumber = client->sequence;
+	rep.length = 0;
+	rep.timestamp = currentTime.milliseconds;
+	rep.configTimestamp = currentTime.milliseconds;
+	rep.nCrtcs = pScrPriv->numCrtcs;
+	rep.nOutputs = pScrPriv->numOutputs;
+	rep.nModes = pScrPriv->numModes;;
+	rep.nbytesNames = 0;
+
+	for (i = 0; i < pScrPriv->numModes; i++)
+	    rep.nbytesNames += pScrPriv->modes[i]->mode.nameLength;
+
+	rep.length = (pScrPriv->numCrtcs + 
+		      pScrPriv->numOutputs + 
+		      pScrPriv->numModes * 10 +
+		      ((rep.nbytesNames + 3) >> 2));
+	
+	extraLen = rep.length << 2;
+	extra = xalloc (extraLen);
+	if (!extra)
+	    return BadAlloc;
+
+	crtcs = (RRCrtc *) extra;
+	outputs = (RROutput *) (crtcs + pScrPriv->numCrtcs);
+	modeinfos = (xRRModeInfo *) (outputs + pScrPriv->numOutputs);
+	names = (CARD8 *) (modeinfos + pScrPriv->numModes);
+	
+	for (i = 0; i < pScrPriv->numCrtcs; i++)
+	{
+	    crtcs[i] = pScrPriv->crtcs[i]->id;
+	    if (client->swapped)
+		swapl (&crtcs[i], n);
+	}
+	
+	for (i = 0; i < pScrPriv->numOutputs; i++)
+	{
+	    outputs[i] = pScrPriv->outputs[i]->id;
+	    if (client->swapped)
+		swapl (&outputs[i], n);
+	}
+	
+	for (i = 0; i < pScrPriv->numModes; i++)
+	{
+	    modeinfos[i] = pScrPriv->modes[i]->mode;
+	    if (client->swapped)
+	    {
+		swapl (&modeinfos[i].id, n);
+		swaps (&modeinfos[i].width, n);
+		swaps (&modeinfos[i].height, n);
+		swapl (&modeinfos[i].mmWidth, n);
+		swapl (&modeinfos[i].mmHeight, n);
+		swapl (&modeinfos[i].dotClock, n);
+		swaps (&modeinfos[i].hSyncStart, n);
+		swaps (&modeinfos[i].hSyncEnd, n);
+		swaps (&modeinfos[i].hTotal, n);
+		swaps (&modeinfos[i].hSkew, n);
+		swaps (&modeinfos[i].vSyncStart, n);
+		swaps (&modeinfos[i].vSyncEnd, n);
+		swaps (&modeinfos[i].vTotal, n);
+		swaps (&modeinfos[i].nameLength, n);
+		swapl (&modeinfos[i].modeFlags, n);
+	    }
+	    memcpy (names, pScrPriv->modes[i]->name, 
+		    pScrPriv->modes[i]->mode.nameLength);
+	    names += pScrPriv->modes[i]->mode.nameLength;
+	}
+	assert ((names + 3 >> 3) == rep.length);
+    }
+    
+    if (client->swapped) {
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.timestamp, n);
+	swapl(&rep.configTimestamp, n);
+	swaps(&rep.nCrtcs, n);
+	swaps(&rep.nOutputs, n);
+	swaps(&rep.nModes, n);
+	swaps(&rep.nbytesNames, n);
+    }
+    WriteToClient(client, sizeof(xRRGetScreenResourcesReply), (char *)&rep);
+    if (extraLen)
+    {
+	WriteToClient (client, extraLen, (char *) extra);
+	xfree (extra);
+    }
+    return client->noClientException;
+}
+
+typedef struct _RR10Data {
+    RRScreenSizePtr sizes;
+    int		    nsize;
+    int		    nrefresh;
+    int		    size;
+    CARD16	    refresh;
+} RR10DataRec, *RR10DataPtr;
+
+/*
+ * Convert 1.2 monitor data into 1.0 screen data
+ */
+static RR10DataPtr
+RR10GetData (ScreenPtr pScreen, RROutputPtr output)
+{
+    RR10DataPtr	    data;
+    RRScreenSizePtr size;
+    int		    nmode = output->numModes;
+    int		    i, j, k;
+    RRScreenRatePtr refresh;
+    CARD16	    vRefresh;
+    RRModePtr	    mode;
+
+    /* Make sure there is plenty of space for any combination */
+    data = malloc (sizeof (RR10DataRec) + 
+		   sizeof (RRScreenSize) * nmode + 
+		   sizeof (RRScreenRate) * nmode);
+    if (!data)
+	return NULL;
+    size = (RRScreenSizePtr) (data + 1);
+    refresh = (RRScreenRatePtr) (size + nmode);
+    data->sizes = size;
+    data->nsize = 0;
+    data->nrefresh = 0;
+    data->size = 0;
+    data->refresh = 0;
+    for (i = 0; i < output->numModes; i++)
+    {
+	mode = output->modes[i];
+	for (j = 0; j < data->nsize; j++)
+	    if (mode->mode.width == size[j].width &&
+		mode->mode.height == size[j].height)
+		break;
+	if (j == data->nsize)
+	{
+	    size[j].id = j;
+	    size[j].width = mode->mode.width;
+	    size[j].height = mode->mode.height;
+	    size[j].mmWidth = mode->mode.mmWidth;
+	    size[j].mmHeight = mode->mode.mmHeight;
+	    size[j].nRates = 0;
+	    size[j].pRates = &refresh[data->nrefresh];
+	    data->nsize++;
+	}
+	vRefresh = RRVerticalRefresh (&mode->mode);
+	for (k = 0; k < size[j].nRates; k++)
+	    if (vRefresh == size[j].pRates[k].rate)
+		break;
+	if (k == size[j].nRates)
+	{
+	    size[j].pRates[k].rate = vRefresh;
+	    size[j].pRates[k].mode = mode;
+	    size[j].nRates++;
+	    data->nrefresh++;
+	}
+	if (mode == output->crtc->mode)
+	{
+	    data->size = j;
+	    data->refresh = vRefresh;
+	}
+    }
+    return data;
+}
+
+int
+ProcRRGetScreenInfo (ClientPtr client)
+{
+    REQUEST(xRRGetScreenInfoReq);
+    xRRGetScreenInfoReply   rep;
+    WindowPtr	    	    pWin;
+    int			    n;
+    ScreenPtr		    pScreen;
+    rrScrPrivPtr	    pScrPriv;
+    CARD8		    *extra;
+    unsigned long	    extraLen;
+    RROutputPtr		    output;
+
+    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    rep.pad = 0;
+    
+    if (pScrPriv)
+	RRGetInfo (pScreen);
+
+    output = RRFirstOutput (pScreen);
+    
+    if (!pScrPriv || !output)
+    {
+	rep.type = X_Reply;
+	rep.setOfRotations = RR_Rotate_0;;
+	rep.sequenceNumber = client->sequence;
+	rep.length = 0;
+	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
+	rep.timestamp = currentTime.milliseconds;
+	rep.configTimestamp = currentTime.milliseconds;
+	rep.nSizes = 0;
+	rep.sizeID = 0;
+	rep.rotation = RR_Rotate_0;
+	rep.rate = 0;
+	rep.nrateEnts = 0;
+	extra = 0;
+	extraLen = 0;
+    }
+    else
+    {
+	int			i, j;
+	xScreenSizes		*size;
+	CARD16			*rates;
+	CARD8			*data8;
+	Bool			has_rate = RRClientKnowsRates (client);
+	RR10DataPtr		pData;
+	RRScreenSizePtr		pSize;
+    
+	pData = RR10GetData (pScreen, output);
+	if (!pData)
+	    return BadAlloc;
+	
+	rep.type = X_Reply;
+	rep.setOfRotations = output->crtc->rotations;
+	rep.sequenceNumber = client->sequence;
+	rep.length = 0;
+	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
+	rep.timestamp = pScrPriv->lastSetTime.milliseconds;
+	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
+	rep.rotation = output->crtc->rotation;
+	rep.nSizes = pData->nsize;
+        rep.nrateEnts = pData->nrefresh + pData->nsize;
+	rep.sizeID = pData->size;
+	rep.rate = pData->refresh;
+
+	extraLen = (rep.nSizes * sizeof (xScreenSizes) +
+		    rep.nrateEnts * sizeof (CARD16));
+
+	extra = (CARD8 *) xalloc (extraLen);
+	if (!extra)
+	{
+	    xfree (pData);
+	    return BadAlloc;
+	}
+	/*
+	 * First comes the size information
+	 */
+	size = (xScreenSizes *) extra;
+	rates = (CARD16 *) (size + rep.nSizes);
+	for (i = 0; i < pData->nsize; i++)
+	{
+	    pSize = &pData->sizes[i];
+	    size->widthInPixels = pSize->width;
+	    size->heightInPixels = pSize->height;
+	    size->widthInMillimeters = pSize->mmWidth;
+	    size->heightInMillimeters = pSize->mmHeight;
+	    if (client->swapped)
+	    {
+	        swaps (&size->widthInPixels, n);
+	        swaps (&size->heightInPixels, n);
+	        swaps (&size->widthInMillimeters, n);
+	        swaps (&size->heightInMillimeters, n);
+	    }
+	    size++;
+	    if (has_rate)
+	    {
+		*rates = pSize->nRates;
+		if (client->swapped)
+		{
+		    swaps (rates, n);
+		}
+		rates++;
+		for (j = 0; j < pSize->nRates; j++)
+		{
+		    *rates = pSize->pRates[j].rate;
+		    if (client->swapped)
+		    {
+			swaps (rates, n);
+		    }
+		    rates++;
+		}
+	    }
+	}
+        xfree (pData);
+	
+	data8 = (CARD8 *) rates;
+
+	if (data8 - (CARD8 *) extra != extraLen)
+	    FatalError ("RRGetScreenInfo bad extra len %ld != %ld\n",
+			(unsigned long)(data8 - (CARD8 *) extra), extraLen);
+	rep.length =  (extraLen + 3) >> 2;
+    }
+    if (client->swapped) {
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.timestamp, n);
+	swaps(&rep.rotation, n);
+	swaps(&rep.nSizes, n);
+	swaps(&rep.sizeID, n);
+	swaps(&rep.rate, n);
+	swaps(&rep.nrateEnts, n);
+    }
+    WriteToClient(client, sizeof(xRRGetScreenInfoReply), (char *)&rep);
+    if (extraLen)
+    {
+	WriteToClient (client, extraLen, (char *) extra);
+	xfree (extra);
+    }
+    return (client->noClientException);
+}
+
+int
+ProcRRSetScreenConfig (ClientPtr client)
+{
+    REQUEST(xRRSetScreenConfigReq);
+    xRRSetScreenConfigReply rep;
+    DrawablePtr		    pDraw;
+    int			    n;
+    ScreenPtr		    pScreen;
+    rrScrPrivPtr	    pScrPriv;
+    TimeStamp		    configTime;
+    TimeStamp		    time;
+    int			    i;
+    Rotation		    rotation;
+    int			    rate;
+    Bool		    has_rate;
+    RROutputPtr		    output;
+    RRModePtr		    mode;
+    RR10DataPtr		    pData = NULL;
+    RRScreenSizePtr    	    pSize;
+    
+    UpdateCurrentTime ();
+
+    if (RRClientKnowsRates (client))
+    {
+	REQUEST_SIZE_MATCH (xRRSetScreenConfigReq);
+	has_rate = TRUE;
+    }
+    else
+    {
+	REQUEST_SIZE_MATCH (xRR1_0SetScreenConfigReq);
+	has_rate = FALSE;
+    }
+    
+    SECURITY_VERIFY_DRAWABLE(pDraw, stuff->drawable, client,
+			     SecurityWriteAccess);
+
+    pScreen = pDraw->pScreen;
+
+    pScrPriv = rrGetScrPriv(pScreen);
+    
+    time = ClientTimeToServerTime(stuff->timestamp);
+    configTime = ClientTimeToServerTime(stuff->configTimestamp);
+    
+    if (!pScrPriv)
+    {
+	time = currentTime;
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    if (!RRGetInfo (pScreen))
+	return BadAlloc;
+    
+    output = RRFirstOutput (pScreen);
+    if (!output)
+    {
+	time = currentTime;
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    
+    /*
+     * if the client's config timestamp is not the same as the last config
+     * timestamp, then the config information isn't up-to-date and
+     * can't even be validated
+     */
+    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
+    {
+	rep.status = RRSetConfigInvalidConfigTime;
+	goto sendReply;
+    }
+    
+    pData = RR10GetData (pScreen, output);
+    if (!pData)
+	return BadAlloc;
+    
+    if (stuff->sizeID >= pData->nsize)
+    {
+	/*
+	 * Invalid size ID
+	 */
+	client->errorValue = stuff->sizeID;
+	xfree (pData);
+	return BadValue;
+    }
+    pSize = &pData->sizes[stuff->sizeID];
+    
+    /*
+     * Validate requested rotation
+     */
+    rotation = (Rotation) stuff->rotation;
+
+    /* test the rotation bits only! */
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_90:
+    case RR_Rotate_180:
+    case RR_Rotate_270:
+	break;
+    default:
+	/*
+	 * Invalid rotation
+	 */
+	client->errorValue = stuff->rotation;
+	xfree (pData);
+	return BadValue;
+    }
+
+    if ((~output->crtc->rotations) & rotation)
+    {
+	/*
+	 * requested rotation or reflection not supported by screen
+	 */
+	client->errorValue = stuff->rotation;
+	xfree (pData);
+	return BadMatch;
+    }
+
+    /*
+     * Validate requested refresh
+     */
+    if (has_rate)
+	rate = (int) stuff->rate;
+    else
+	rate = 0;
+
+    if (rate)
+    {
+	for (i = 0; i < pSize->nRates; i++)
+	{
+	    if (pSize->pRates[i].rate == rate)
+		break;
+	}
+	if (i == pSize->nRates)
+	{
+	    /*
+	     * Invalid rate
+	     */
+	    client->errorValue = rate;
+	    xfree (pData);
+	    return BadValue;
+	}
+	mode = pSize->pRates[i].mode;
+    }
+    else
+	mode = pSize->pRates[0].mode;
+    
+    /*
+     * Make sure the requested set-time is not older than
+     * the last set-time
+     */
+    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
+    {
+	rep.status = RRSetConfigInvalidTime;
+	goto sendReply;
+    }
+
+    rep.status = RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation,
+			    1, &output);
+    
+sendReply:
+    
+    if (pData)
+	xfree (pData);
+
+    rep.type = X_Reply;
+    /* rep.status has already been filled in */
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+
+    rep.newTimestamp = pScrPriv->lastSetTime.milliseconds;
+    rep.newConfigTimestamp = pScrPriv->lastConfigTime.milliseconds;
+    rep.root = WindowTable[pDraw->pScreen->myNum]->drawable.id;
+
+    if (client->swapped) 
+    {
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swapl(&rep.newTimestamp, n);
+	swapl(&rep.newConfigTimestamp, n);
+	swapl(&rep.root, n);
+    }
+    WriteToClient(client, sizeof(xRRSetScreenConfigReply), (char *)&rep);
+
+    return (client->noClientException);
+}
+
commit 7f9b59d80deb08b8427fdd1b6346390387725137
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Tue Sep 19 00:46:27 2006 -0700

    RRGetScreenResources and RRGetOutputInfo are working now.
    
    Removed separate id field in RRModeRec.
    Pull screen subpixel order from Render extension.
    Implement RGetScreenResources and RRGetOutputInfo

diff --git a/randr/randr.c b/randr/randr.c
index 926e32f..beddb50 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -442,7 +442,7 @@ RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
     if (!modes)
     {
 	RRModeDestroy (mode);
-	FreeResource (mode->id, 0);
+	FreeResource (mode->mode.id, 0);
 	return NULL;
     }
     modes[output->numModes++] = mode;
@@ -479,6 +479,9 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
 	RROutputSetCrtcs (output, &crtc, 1);
 	RROutputSetCrtc (output, crtc);
 	RROutputSetConnection (output, RR_Connected);
+#ifdef RENDER
+	RROutputSetSubpixelOrder (output, PictureGetSubpixelOrder (pScreen));
+#endif
     }
 
     output = RRFirstOutput (pScreen);
diff --git a/randr/randrstr.h b/randr/randrstr.h
index a7f91b7..682ebbf 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -74,7 +74,6 @@ typedef struct _rrCrtc	    RRCrtcRec, *RRCrtcPtr;
 typedef struct _rrOutput    RROutputRec, *RROutputPtr;
 
 struct _rrMode {
-    RRMode	    id;
     int		    refcnt;
     xRRModeInfo	    mode;
     char	    *name;
@@ -489,6 +488,10 @@ Bool
 RROutputSetConnection (RROutputPtr  output,
 		       CARD8	    connection);
 
+Bool
+RROutputSetSubpixelOrder (RROutputPtr output,
+			  int	      subpixelOrder);
+
 void
 RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output);
 
diff --git a/randr/rrdispatch.c b/randr/rrdispatch.c
index 279acfd..aca0e54 100644
--- a/randr/rrdispatch.c
+++ b/randr/rrdispatch.c
@@ -694,20 +694,229 @@ static int
 ProcRRGetScreenResources (ClientPtr client)
 {
     REQUEST(xRRGetScreenResourcesReq);
+    xRRGetScreenResourcesReply  rep;
+    WindowPtr			pWin;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    CARD8			*extra;
+    unsigned long		extraLen;
+    int				i;
+    RRCrtc			*crtcs;
+    RROutput			*outputs;
+    xRRModeInfo			*modeinfos;
+    CARD8			*names;
+    int				n;
     
     REQUEST_SIZE_MATCH(xRRGetScreenResourcesReq);
-    (void) stuff;
-    return BadImplementation; 
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+    
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    rep.pad = 0;
+    
+    if (pScrPriv)
+	RRGetInfo (pScreen);
+
+    if (!pScrPriv)
+    {
+	rep.type = X_Reply;
+	rep.sequenceNumber = client->sequence;
+	rep.length = 0;
+	rep.timestamp = currentTime.milliseconds;
+	rep.configTimestamp = currentTime.milliseconds;
+	rep.nCrtcs = 0;
+	rep.nOutputs = 0;
+	rep.nModes = 0;
+	rep.nbytesNames = 0;
+	extra = NULL;
+	extraLen = 0;
+    }
+    else
+    {
+	rep.type = X_Reply;
+	rep.sequenceNumber = client->sequence;
+	rep.length = 0;
+	rep.timestamp = currentTime.milliseconds;
+	rep.configTimestamp = currentTime.milliseconds;
+	rep.nCrtcs = pScrPriv->numCrtcs;
+	rep.nOutputs = pScrPriv->numOutputs;
+	rep.nModes = pScrPriv->numModes;;
+	rep.nbytesNames = 0;
+
+	for (i = 0; i < pScrPriv->numModes; i++)
+	    rep.nbytesNames += pScrPriv->modes[i]->mode.nameLength;
+
+	rep.length = (pScrPriv->numCrtcs + 
+		      pScrPriv->numOutputs + 
+		      pScrPriv->numModes * 10 +
+		      ((rep.nbytesNames + 3) >> 2));
+	
+	extraLen = rep.length << 2;
+	extra = xalloc (extraLen);
+	if (!extra)
+	    return BadAlloc;
+
+	crtcs = (RRCrtc *) extra;
+	outputs = (RROutput *) (crtcs + pScrPriv->numCrtcs);
+	modeinfos = (xRRModeInfo *) (outputs + pScrPriv->numOutputs);
+	names = (CARD8 *) (modeinfos + pScrPriv->numModes);
+	
+	for (i = 0; i < pScrPriv->numCrtcs; i++)
+	{
+	    crtcs[i] = pScrPriv->crtcs[i]->id;
+	    if (client->swapped)
+		swapl (&crtcs[i], n);
+	}
+	
+	for (i = 0; i < pScrPriv->numOutputs; i++)
+	{
+	    outputs[i] = pScrPriv->outputs[i]->id;
+	    if (client->swapped)
+		swapl (&outputs[i], n);
+	}
+	
+	for (i = 0; i < pScrPriv->numModes; i++)
+	{
+	    modeinfos[i] = pScrPriv->modes[i]->mode;
+	    if (client->swapped)
+	    {
+		swapl (&modeinfos[i].id, n);
+		swaps (&modeinfos[i].width, n);
+		swaps (&modeinfos[i].height, n);
+		swapl (&modeinfos[i].mmWidth, n);
+		swapl (&modeinfos[i].mmHeight, n);
+		swapl (&modeinfos[i].dotClock, n);
+		swaps (&modeinfos[i].hSyncStart, n);
+		swaps (&modeinfos[i].hSyncEnd, n);
+		swaps (&modeinfos[i].hTotal, n);
+		swaps (&modeinfos[i].hSkew, n);
+		swaps (&modeinfos[i].vSyncStart, n);
+		swaps (&modeinfos[i].vSyncEnd, n);
+		swaps (&modeinfos[i].vTotal, n);
+		swaps (&modeinfos[i].nameLength, n);
+		swapl (&modeinfos[i].modeFlags, n);
+	    }
+	    memcpy (names, pScrPriv->modes[i]->name, 
+		    pScrPriv->modes[i]->mode.nameLength);
+	    names += pScrPriv->modes[i]->mode.nameLength;
+	}
+	assert ((names + 3 >> 3) == rep.length);
+    }
+    
+    if (client->swapped) {
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.timestamp, n);
+	swapl(&rep.configTimestamp, n);
+	swaps(&rep.nCrtcs, n);
+	swaps(&rep.nOutputs, n);
+	swaps(&rep.nModes, n);
+	swaps(&rep.nbytesNames, n);
+    }
+    WriteToClient(client, sizeof(xRRGetScreenResourcesReply), (char *)&rep);
+    if (extraLen)
+    {
+	WriteToClient (client, extraLen, (char *) extra);
+	xfree (extra);
+    }
+    return client->noClientException;
 }
 
 static int
 ProcRRGetOutputInfo (ClientPtr client)
 {
     REQUEST(xRRGetOutputInfoReq);;
+    xRRGetOutputInfoReply	rep;
+    RROutputPtr			output;
+    CARD8			*extra;
+    unsigned long		extraLen;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    RRCrtc			*crtcs;
+    RRMode			*modes;
+    RROutput			*clones;
+    char			*name;
+    int				i, n;
     
     REQUEST_SIZE_MATCH(xRRGetOutputInfoReq);
-    (void) stuff;
-    return BadImplementation; 
+    output = (RROutputPtr)SecurityLookupIDByType(client, stuff->output, 
+						 RROutputType, 
+						 SecurityReadAccess);
+
+    if (!output)
+	return RRErrorBase + BadRROutput;
+
+    pScreen = output->pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+
+    rep.type = X_Reply;
+    rep.sequenceNumber = client->sequence;
+    rep.length = 0;
+    rep.timestamp = pScrPriv->lastSetTime.milliseconds;
+    rep.crtc = output->crtc ? output->crtc->id : None;
+    rep.connection = output->connection;
+    rep.subpixelOrder = output->subpixelOrder;
+    rep.nCrtcs = output->numCrtcs;
+    rep.nModes = output->numModes;
+    rep.nClones = output->numClones;
+    rep.nameLength = output->nameLength;
+    
+    rep.length = (output->numCrtcs + 
+		  output->numModes + 
+		  output->numClones +
+		  ((rep.nameLength + 3) >> 2));
+
+    extraLen = rep.length << 2;
+    extra = xalloc (extraLen);
+    if (!extra)
+	return BadAlloc;
+
+    crtcs = (RRCrtc *) extra;
+    modes = (RRMode *) (crtcs + output->numCrtcs);
+    clones = (RROutput *) (modes + output->numModes);
+    name = (char *) (clones + output->numClones);
+    
+    for (i = 0; i < output->numCrtcs; i++)
+    {
+	crtcs[i] = output->crtcs[i]->id;
+	if (client->swapped)
+	    swapl (&crtcs[i], n);
+    }
+    for (i = 0; i < output->numModes; i++)
+    {
+	modes[i] = output->modes[i]->mode.id;
+	if (client->swapped)
+	    swapl (&modes[i], n);
+    }
+    for (i = 0; i < output->numClones; i++)
+    {
+	clones[i] = output->clones[i]->id;
+	if (client->swapped)
+	    swapl (&clones[i], n);
+    }
+    memcpy (name, output->name, output->nameLength);
+    if (client->swapped) {
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.timestamp, n);
+	swapl(&rep.crtc, n);
+	swaps(&rep.nCrtcs, n);
+	swaps(&rep.nModes, n);
+	swaps(&rep.nClones, n);
+	swaps(&rep.nameLength, n);
+    }
+    WriteToClient(client, sizeof(xRRGetOutputInfoReply), (char *)&rep);
+    if (extraLen)
+    {
+	WriteToClient (client, extraLen, (char *) extra);
+	xfree (extra);
+    }
+    
+    return client->noClientException;
 }
 
 static int
diff --git a/randr/rrmode.c b/randr/rrmode.c
index 52585d9..4e44e7d 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -37,6 +37,7 @@ RRModeGet (ScreenPtr	pScreen,
     for (i = 0; i < pScrPriv->numModes; i++)
     {
 	mode = pScrPriv->modes[i];
+	modeInfo->id = mode->mode.id;
 	if (!memcmp (modeInfo, &mode->mode, sizeof (xRRModeInfo)) &&
 	    !memcmp (name, mode->name, modeInfo->nameLength))
 	{
@@ -66,8 +67,8 @@ RRModeGet (ScreenPtr	pScreen,
 	return NULL;
     }
 
-    mode->id = FakeClientID(0);
-    if (!AddResource (mode->id, RRModeType, (pointer) mode))
+    mode->mode.id = FakeClientID(0);
+    if (!AddResource (mode->mode.id, RRModeType, (pointer) mode))
 	return NULL;
     ++mode->refcnt;
     pScrPriv->modes = modes;
diff --git a/randr/rroutput.c b/randr/rroutput.c
index ba5bcb4..4780023 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -154,6 +154,15 @@ RROutputSetConnection (RROutputPtr  output,
     return TRUE;
 }
 
+Bool
+RROutputSetSubpixelOrder (RROutputPtr output,
+			  int	      subpixelOrder)
+{
+    output->subpixelOrder = subpixelOrder;
+    output->changed = TRUE;
+    return TRUE;
+}
+
 void
 RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output)
 {
commit 0b22ab2f492c3a4a2ebab99f0da25f92e06117c3
Author: Keith Packard <keithp at guitar.keithp.com>
Date:   Mon Sep 18 12:18:22 2006 -0700

    RandR working with old clients and old API.

diff --git a/randr/randr.c b/randr/randr.c
index 63d471c..926e32f 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -477,6 +477,7 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
 	if (!output)
 	    return;
 	RROutputSetCrtcs (output, &crtc, 1);
+	RROutputSetCrtc (output, crtc);
 	RROutputSetConnection (output, RR_Connected);
     }
 
@@ -552,8 +553,8 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
 
     /* notice current mode */
     if (newMode)
-	RRCrtcSet (output->crtc, newMode, 0, 0, pScrPriv->rotation,
-		   1, &output);
+	RRCrtcNotify (output->crtc, newMode, 0, 0, pScrPriv->rotation,
+		      1, &output);
 }
 #endif
 
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 3346157..a7f91b7 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -482,6 +482,9 @@ RROutputSetCrtcs (RROutputPtr	output,
 		  RRCrtcPtr	*crtcs,
 		  int		numCrtcs);
 
+void
+RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc);
+    
 Bool
 RROutputSetConnection (RROutputPtr  output,
 		       CARD8	    connection);
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index d343c3a..d1328e7 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -59,7 +59,13 @@ RRCrtcCreate (ScreenPtr	pScreen,
     crtc->numOutputs = 0;
     crtc->changed = TRUE;
     crtc->devPrivate = devPrivate;
+
+    if (!AddResource (crtc->id, RRCrtcType, (pointer) crtc))
+	return NULL;
+
+    pScrPriv->crtcs = crtcs;
     pScrPriv->crtcs[pScrPriv->numCrtcs++] = crtc;
+    pScrPriv->changed = TRUE;
     return crtc;
 }
 
@@ -165,6 +171,16 @@ RRCrtcSet (RRCrtcPtr    crtc,
     ScreenPtr	pScreen = crtc->pScreen;
     rrScrPriv(pScreen);
 
+    /* See if nothing changed */
+    if (crtc->mode == mode &&
+	crtc->x == x &&
+	crtc->y == y &&
+	crtc->rotation == rotation &&
+	crtc->numOutputs == numOutputs &&
+	!memcmp (crtc->outputs, outputs, numOutputs * sizeof (RROutputPtr)))
+    {
+	return TRUE;
+    }
 #if RANDR_12_INTERFACE
     if (pScrPriv->rrCrtcSet)
     {
diff --git a/randr/rrdispatch.c b/randr/rrdispatch.c
index acf6298..279acfd 100644
--- a/randr/rrdispatch.c
+++ b/randr/rrdispatch.c
@@ -824,7 +824,7 @@ ProcRRSetCrtcConfig (ClientPtr client)
     if (!crtc)
     {
 	client->errorValue = stuff->crtc;
-	return RRErrorBase + BadCrtc;
+	return RRErrorBase + BadRRCrtc;
     }
     if (stuff->mode == None)
     {
@@ -838,7 +838,7 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	if (!mode)
 	{
 	    client->errorValue = stuff->mode;
-	    return RRErrorBase + BadMode;
+	    return RRErrorBase + BadRRMode;
 	}
 	if (numOutputs == 0)
 	    return BadMatch;
@@ -854,7 +854,7 @@ ProcRRSetCrtcConfig (ClientPtr client)
 	if (!outputs[i])
 	{
 	    client->errorValue = outputIds[i];
-	    return RRErrorBase + BadOutput;
+	    return RRErrorBase + BadRROutput;
 	}
 	/* validate crtc for this output */
 	for (j = 0; j < outputs[i]->numCrtcs; j++)
diff --git a/randr/rrmode.c b/randr/rrmode.c
index 3a9d556..52585d9 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -32,6 +32,7 @@ RRModeGet (ScreenPtr	pScreen,
     rrScrPriv (pScreen);
     int	i;
     RRModePtr	mode;
+    RRModePtr	*modes;
 
     for (i = 0; i < pScrPriv->numModes; i++)
     {
@@ -43,16 +44,34 @@ RRModeGet (ScreenPtr	pScreen,
 	    return mode;
 	}
     }
+
     mode = xalloc (sizeof (RRModeRec) + modeInfo->nameLength + 1);
+    if (!mode)
+	return NULL;
     mode->refcnt = 1;
     mode->mode = *modeInfo;
     mode->name = (char *) (mode + 1);
     memcpy (mode->name, name, modeInfo->nameLength);
     mode->name[modeInfo->nameLength] = '\0';
+
+    if (pScrPriv->numModes)
+	modes = xrealloc (pScrPriv->modes,
+			  (pScrPriv->numModes + 1) * sizeof (RRModePtr));
+    else
+	modes = xalloc (sizeof (RRModePtr));
+
+    if (!modes)
+    {
+	xfree (mode);
+	return NULL;
+    }
+
     mode->id = FakeClientID(0);
     if (!AddResource (mode->id, RRModeType, (pointer) mode))
 	return NULL;
     ++mode->refcnt;
+    pScrPriv->modes = modes;
+    pScrPriv->modes[pScrPriv->numModes++] = mode;
     pScrPriv->changed = TRUE;
     return mode;
 }
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 6b67f19..ba5bcb4 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -56,6 +56,7 @@ RROutputCreate (ScreenPtr   pScreen,
     output->name = (char *) (output + 1);
     output->nameLength = nameLength;
     memcpy (output->name, name, nameLength);
+    output->name[nameLength] = '\0';
     output->connection = RR_UnknownConnection;
     output->subpixelOrder = SubPixelUnknown;
     output->crtc = NULL;
@@ -67,7 +68,13 @@ RROutputCreate (ScreenPtr   pScreen,
     output->modes = NULL;
     output->changed = TRUE;
     output->devPrivate = devPrivate;
+    
+    if (!AddResource (output->id, RROutputType, (pointer) output))
+	return NULL;
+
+    pScrPriv->outputs = outputs;
     pScrPriv->outputs[pScrPriv->numOutputs++] = output;
+    pScrPriv->changed = TRUE;
     return output;
 }
 
@@ -89,6 +96,7 @@ RROutputSetClones (RROutputPtr  output,
     memcpy (newClones, clones, numClones * sizeof (RROutputPtr));
     output->clones = newClones;
     output->numClones = numClones;
+    output->changed = TRUE;
     return TRUE;
 }
 
@@ -107,6 +115,7 @@ RROutputSetModes (RROutputPtr	output,
     memcpy (newModes, modes, numModes * sizeof (RRModePtr));
     output->modes = newModes;
     output->numModes = numModes;
+    output->changed = TRUE;
     return TRUE;
 }
 
@@ -125,14 +134,23 @@ RROutputSetCrtcs (RROutputPtr	output,
     memcpy (newCrtcs, crtcs, numCrtcs * sizeof (RRCrtcPtr));
     output->crtcs = newCrtcs;
     output->numCrtcs = numCrtcs;
+    output->changed = TRUE;
     return TRUE;
 }
 
+void
+RROutputSetCrtc (RROutputPtr output, RRCrtcPtr crtc)
+{
+    output->crtc = crtc;
+    output->changed = TRUE;
+}
+
 Bool
 RROutputSetConnection (RROutputPtr  output,
 		       CARD8	    connection)
 {
     output->connection = connection;
+    output->changed = TRUE;
     return TRUE;
 }
 
commit db4576798e0012f0558f3faac10cbb26a2fbec34
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Sun Sep 17 23:03:23 2006 -0700

    Split out RandR dispatch code from randr.c to rr*dispatch.c.
    
    More disassembly to ease ongoing development.

diff --git a/randr/Makefile.am b/randr/Makefile.am
index 868786e..0a73557 100644
--- a/randr/Makefile.am
+++ b/randr/Makefile.am
@@ -11,6 +11,8 @@ librandr_la_SOURCES =	\
 	randr.c		\
 	randrstr.h	\
 	rrcrtc.c	\
+	rrdispatch.c	\
 	rrmode.c	\
 	rroutput.c	\
-	rrscreen.c
+	rrscreen.c	\
+	rrsdispatch.c
diff --git a/randr/randr.c b/randr/randr.c
index 2305b60..63d471c 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -42,10 +42,8 @@
 int	RRGeneration;
 int	RRNScreens;
 
-static int ProcRRQueryVersion (ClientPtr pClient);
 static int ProcRRDispatch (ClientPtr pClient);
 static int SProcRRDispatch (ClientPtr pClient);
-static int SProcRRQueryVersion (ClientPtr pClient);
 
 #define wrap(priv,real,mem,func) {\
     priv->mem = real->mem; \
@@ -56,57 +54,13 @@ static int SProcRRQueryVersion (ClientPtr pClient);
     real->mem = priv->mem; \
 }
 
-#if 0
-static CARD8	RRReqCode;
-static int	RRErrBase;
-#endif
 int	RREventBase;
-static RESTYPE ClientType, EventType; /* resource types for event masks */
-static int	RRClientPrivateIndex;
-
-typedef struct _RRTimes {
-    TimeStamp	setTime;
-    TimeStamp	configTime;
-} RRTimesRec, *RRTimesPtr;
-
-typedef struct _RRClient {
-    int		major_version;
-    int		minor_version;
-/*  RRTimesRec	times[0]; */
-} RRClientRec, *RRClientPtr;
-
-/*
- * each window has a list of clients requesting
- * RRNotify events.  Each client has a resource
- * for each window it selects RRNotify input for,
- * this resource is used to delete the RRNotifyRec
- * entry from the per-window queue.
- */
-
-typedef struct _RREvent *RREventPtr;
-
-typedef struct _RREvent {
-    RREventPtr  next;
-    ClientPtr	client;
-    WindowPtr	window;
-    XID		clientResource;
-    int		mask;
-} RREventRec;
+int	RRErrorBase;
+RESTYPE RRClientType, RREventType; /* resource types for event masks */
+int	RRClientPrivateIndex;
 
 int	rrPrivIndex = -1;
 
-#define GetRRClient(pClient)    ((RRClientPtr) (pClient)->devPrivates[RRClientPrivateIndex].ptr)
-#define rrClientPriv(pClient)	RRClientPtr pRRClient = GetRRClient(pClient)
-
-static Bool
-RRClientKnowsRates (ClientPtr	pClient)
-{
-    rrClientPriv(pClient);
-
-    return (pRRClient->major_version > 1 ||
-	    (pRRClient->major_version == 1 && pRRClient->minor_version >= 1));
-}
-
 static void
 RRClientCallback (CallbackListPtr	*list,
 		  pointer		closure,
@@ -289,7 +243,7 @@ RRFreeClient (pointer data, XID id)
 
     pRREvent = (RREventPtr) data;
     pWin = pRREvent->window;
-    pHead = (RREventPtr *) LookupIDByType(pWin->drawable.id, EventType);
+    pHead = (RREventPtr *) LookupIDByType(pWin->drawable.id, RREventType);
     if (pHead) {
 	pPrev = 0;
 	for (pCur = *pHead; pCur && pCur != pRREvent; pCur=pCur->next)
@@ -315,7 +269,7 @@ RRFreeEvents (pointer data, XID id)
     pHead = (RREventPtr *) data;
     for (pCur = *pHead; pCur; pCur = pNext) {
 	pNext = pCur->next;
-	FreeResource (pCur->clientResource, ClientType);
+	FreeResource (pCur->clientResource, RRClientType);
 	xfree ((pointer) pCur);
     }
     xfree ((pointer) pHead);
@@ -337,38 +291,26 @@ RRExtensionInit (void)
     if (!AddCallback (&ClientStateCallback, RRClientCallback, 0))
 	return;
 
-    ClientType = CreateNewResourceType(RRFreeClient);
-    if (!ClientType)
+    RRClientType = CreateNewResourceType(RRFreeClient);
+    if (!RRClientType)
 	return;
-    EventType = CreateNewResourceType(RRFreeEvents);
-    if (!EventType)
+    RREventType = CreateNewResourceType(RRFreeEvents);
+    if (!RREventType)
 	return;
     extEntry = AddExtension (RANDR_NAME, RRNumberEvents, RRNumberErrors,
 			     ProcRRDispatch, SProcRRDispatch,
 			     RRResetProc, StandardMinorOpcode);
     if (!extEntry)
 	return;
-#if 0
-    RRReqCode = (CARD8) extEntry->base;
-    RRErrBase = extEntry->errorBase;
-#endif
+    RRErrorBase = extEntry->errorBase;
     RREventBase = extEntry->eventBase;
     EventSwapVector[RREventBase + RRScreenChangeNotify] = (EventSwapPtr) 
-      SRRScreenChangeNotifyEvent;
+	SRRScreenChangeNotifyEvent;
     EventSwapVector[RREventBase + RRNotify] = (EventSwapPtr)
 	SRRNotifyEvent;
 
     return;
 }
-static void
-DeliverCrtcEvent (ClientPtr client, WindowPtr pWin, RRCrtcPtr crtc)
-{
-}
-
-static void
-DeliverOutputEvent (ClientPtr client, WindowPtr pWin, RROutputPtr output)
-{
-}
 
 static int
 TellChanged (WindowPtr pWin, pointer value)
@@ -379,7 +321,7 @@ TellChanged (WindowPtr pWin, pointer value)
     rrScrPriv(pScreen);
     int				i;
 
-    pHead = (RREventPtr *) LookupIDByType (pWin->drawable.id, EventType);
+    pHead = (RREventPtr *) LookupIDByType (pWin->drawable.id, RREventType);
     if (!pHead)
 	return WT_WALKCHILDREN;
 
@@ -398,7 +340,7 @@ TellChanged (WindowPtr pWin, pointer value)
 	    {
 		RRCrtcPtr   crtc = pScrPriv->crtcs[i];
 		if (crtc->changed)
-		    DeliverCrtcEvent (client, pWin, crtc);
+		    RRDeliverCrtcEvent (client, pWin, crtc);
 	    }
 	}
 	
@@ -408,7 +350,7 @@ TellChanged (WindowPtr pWin, pointer value)
 	    {
 		RROutputPtr   output = pScrPriv->outputs[i];
 		if (output->changed)
-		    DeliverOutputEvent (client, pWin, output);
+		    RRDeliverOutputEvent (client, pWin, output);
 	    }
 	}
     }
@@ -438,7 +380,7 @@ RRTellChanged (ScreenPtr pScreen)
  * Return the first output which is connected to an active CRTC
  * Used in emulating 1.0 behaviour
  */
-static RROutputPtr
+RROutputPtr
 RRFirstOutput (ScreenPtr pScreen)
 {
     rrScrPriv(pScreen);
@@ -459,7 +401,6 @@ RRFirstOutput (ScreenPtr pScreen)
 }
 
 #ifdef RANDR_10_INTERFACE
-
 static RRModePtr
 RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
 {
@@ -515,13 +456,31 @@ static void
 RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
 {
     rrScrPriv(pScreen);
-    RROutputPtr	output = RRFirstOutput (pScreen);
+    RROutputPtr	output;
     RRCrtcPtr	crtc;
     RRModePtr	mode, newMode = NULL;
     int		i;
     CARD16	minWidth = MAXSHORT, minHeight = MAXSHORT;
     CARD16	maxWidth = 0, maxHeight = 0;
     
+    /*
+     * First time through, create a crtc and output and hook
+     * them together
+     */
+    if (pScrPriv->numOutputs == 0 &&
+	pScrPriv->numCrtcs == 0)
+    {
+	crtc = RRCrtcCreate (pScreen, NULL);
+	if (!crtc)
+	    return;
+	output = RROutputCreate (pScreen, "default", 7, NULL);
+	if (!output)
+	    return;
+	RROutputSetCrtcs (output, &crtc, 1);
+	RROutputSetConnection (output, RR_Connected);
+    }
+
+    output = RRFirstOutput (pScreen);
     if (!output)
 	return;
     crtc = output->crtc;
@@ -601,7 +560,7 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
 /*
  * Poll the driver for changed information
  */
-static Bool
+Bool
 RRGetInfo (ScreenPtr pScreen)
 {
     rrScrPriv (pScreen);
@@ -627,44 +586,6 @@ RRGetInfo (ScreenPtr pScreen)
     return TRUE;
 }
 
-static int
-ProcRRQueryVersion (ClientPtr client)
-{
-    xRRQueryVersionReply rep;
-    register int n;
-    REQUEST(xRRQueryVersionReq);
-    rrClientPriv(client);
-
-    REQUEST_SIZE_MATCH(xRRQueryVersionReq);
-    pRRClient->major_version = stuff->majorVersion;
-    pRRClient->minor_version = stuff->minorVersion;
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-    /*
-     * Report the current version; the current
-     * spec says they're all compatible after 1.0
-     */
-    rep.majorVersion = RANDR_MAJOR;
-    rep.minorVersion = RANDR_MINOR;
-    if (client->swapped) {
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-	swapl(&rep.majorVersion, n);
-	swapl(&rep.minorVersion, n);
-    }
-    WriteToClient(client, sizeof(xRRQueryVersionReply), (char *)&rep);
-    return (client->noClientException);
-}
-
-typedef struct _RR10Data {
-    RRScreenSizePtr sizes;
-    int		    nsize;
-    int		    nrefresh;
-    int		    size;
-    CARD16	    refresh;
-} RR10DataRec, *RR10DataPtr;
-
 CARD16
 RRVerticalRefresh (xRRModeInfo *mode)
 {
@@ -677,411 +598,6 @@ RRVerticalRefresh (xRRModeInfo *mode)
     return (CARD16) refresh;
 }
 
-/*
- * Convert 1.2 monitor data into 1.0 screen data
- */
-static RR10DataPtr
-RR10GetData (ScreenPtr pScreen, RROutputPtr output)
-{
-    RR10DataPtr	    data;
-    RRScreenSizePtr size;
-    int		    nmode = output->numModes;
-    int		    i, j, k;
-    RRScreenRatePtr refresh;
-    CARD16	    vRefresh;
-    RRModePtr	    mode;
-
-    /* Make sure there is plenty of space for any combination */
-    data = malloc (sizeof (RR10DataRec) + 
-		   sizeof (RRScreenSize) * nmode + 
-		   sizeof (RRScreenRate) * nmode);
-    if (!data)
-	return NULL;
-    size = (RRScreenSizePtr) (data + 1);
-    refresh = (RRScreenRatePtr) (size + nmode);
-    data->sizes = size;
-    data->nsize = 0;
-    data->nrefresh = 0;
-    data->size = 0;
-    data->refresh = 0;
-    for (i = 0; i < output->numModes; i++)
-    {
-	mode = output->modes[i];
-	for (j = 0; j < data->nsize; j++)
-	    if (mode->mode.width == size[j].width &&
-		mode->mode.height == size[j].height)
-		break;
-	if (j == data->nsize)
-	{
-	    size[j].id = j;
-	    size[j].width = mode->mode.width;
-	    size[j].height = mode->mode.height;
-	    size[j].mmWidth = mode->mode.mmWidth;
-	    size[j].mmHeight = mode->mode.mmHeight;
-	    size[j].nRates = 0;
-	    size[j].pRates = &refresh[data->nrefresh];
-	    data->nsize++;
-	}
-	vRefresh = RRVerticalRefresh (&mode->mode);
-	for (k = 0; k < size[j].nRates; k++)
-	    if (vRefresh == size[j].pRates[k].rate)
-		break;
-	if (k == size[j].nRates)
-	{
-	    size[j].pRates[k].rate = vRefresh;
-	    size[j].pRates[k].mode = mode;
-	    size[j].nRates++;
-	    data->nrefresh++;
-	}
-	if (mode == output->crtc->mode)
-	{
-	    data->size = j;
-	    data->refresh = vRefresh;
-	}
-    }
-    return data;
-}
-
-static int
-ProcRRGetScreenInfo (ClientPtr client)
-{
-    REQUEST(xRRGetScreenInfoReq);
-    xRRGetScreenInfoReply   rep;
-    WindowPtr	    	    pWin;
-    int			    n;
-    ScreenPtr		    pScreen;
-    rrScrPrivPtr	    pScrPriv;
-    CARD8		    *extra;
-    unsigned long	    extraLen;
-    RROutputPtr		    output;
-
-    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    rep.pad = 0;
-    
-    if (pScrPriv)
-	RRGetInfo (pScreen);
-
-    output = RRFirstOutput (pScreen);
-    
-    if (!pScrPriv || !output)
-    {
-	rep.type = X_Reply;
-	rep.setOfRotations = RR_Rotate_0;;
-	rep.sequenceNumber = client->sequence;
-	rep.length = 0;
-	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
-	rep.timestamp = currentTime.milliseconds;
-	rep.configTimestamp = currentTime.milliseconds;
-	rep.nSizes = 0;
-	rep.sizeID = 0;
-	rep.rotation = RR_Rotate_0;
-	rep.rate = 0;
-	rep.nrateEnts = 0;
-	extra = 0;
-	extraLen = 0;
-    }
-    else
-    {
-	int			i, j;
-	xScreenSizes		*size;
-	CARD16			*rates;
-	CARD8			*data8;
-	Bool			has_rate = RRClientKnowsRates (client);
-	RR10DataPtr		pData;
-	RRScreenSizePtr		pSize;
-    
-	pData = RR10GetData (pScreen, output);
-	if (!pData)
-	    return BadAlloc;
-	
-	rep.type = X_Reply;
-	rep.setOfRotations = output->crtc->rotations;
-	rep.sequenceNumber = client->sequence;
-	rep.length = 0;
-	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
-	rep.timestamp = pScrPriv->lastSetTime.milliseconds;
-	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
-	rep.rotation = output->crtc->rotation;
-	rep.nSizes = pData->nsize;
-        rep.nrateEnts = pData->nrefresh + pData->nsize;
-	rep.sizeID = pData->size;
-	rep.rate = pData->refresh;
-
-	extraLen = (rep.nSizes * sizeof (xScreenSizes) +
-		    rep.nrateEnts * sizeof (CARD16));
-
-	extra = (CARD8 *) xalloc (extraLen);
-	if (!extra)
-	{
-	    xfree (pData);
-	    return BadAlloc;
-	}
-	/*
-	 * First comes the size information
-	 */
-	size = (xScreenSizes *) extra;
-	rates = (CARD16 *) (size + rep.nSizes);
-	for (i = 0; i < pData->nsize; i++)
-	{
-	    pSize = &pData->sizes[i];
-	    size->widthInPixels = pSize->width;
-	    size->heightInPixels = pSize->height;
-	    size->widthInMillimeters = pSize->mmWidth;
-	    size->heightInMillimeters = pSize->mmHeight;
-	    if (client->swapped)
-	    {
-	        swaps (&size->widthInPixels, n);
-	        swaps (&size->heightInPixels, n);
-	        swaps (&size->widthInMillimeters, n);
-	        swaps (&size->heightInMillimeters, n);
-	    }
-	    size++;
-	    if (has_rate)
-	    {
-		*rates = pSize->nRates;
-		if (client->swapped)
-		{
-		    swaps (rates, n);
-		}
-		rates++;
-		for (j = 0; j < pSize->nRates; j++)
-		{
-		    *rates = pSize->pRates[j].rate;
-		    if (client->swapped)
-		    {
-			swaps (rates, n);
-		    }
-		    rates++;
-		}
-	    }
-	}
-        xfree (pData);
-	
-	data8 = (CARD8 *) rates;
-
-	if (data8 - (CARD8 *) extra != extraLen)
-	    FatalError ("RRGetScreenInfo bad extra len %ld != %ld\n",
-			(unsigned long)(data8 - (CARD8 *) extra), extraLen);
-	rep.length =  (extraLen + 3) >> 2;
-    }
-    if (client->swapped) {
-	swaps(&rep.sequenceNumber, n);
-	swapl(&rep.length, n);
-	swapl(&rep.timestamp, n);
-	swaps(&rep.rotation, n);
-	swaps(&rep.nSizes, n);
-	swaps(&rep.sizeID, n);
-	swaps(&rep.rate, n);
-	swaps(&rep.nrateEnts, n);
-    }
-    WriteToClient(client, sizeof(xRRGetScreenInfoReply), (char *)&rep);
-    if (extraLen)
-    {
-	WriteToClient (client, extraLen, (char *) extra);
-	xfree (extra);
-    }
-    return (client->noClientException);
-}
-
-#if 0
-    return RRSetConfigSuccess;
-}
-#endif
-
-static int
-ProcRRSetScreenConfig (ClientPtr client)
-{
-    REQUEST(xRRSetScreenConfigReq);
-    xRRSetScreenConfigReply rep;
-    DrawablePtr		    pDraw;
-    int			    n;
-    ScreenPtr		    pScreen;
-    rrScrPrivPtr	    pScrPriv;
-    TimeStamp		    configTime;
-    TimeStamp		    time;
-    int			    i;
-    Rotation		    rotation;
-    int			    rate;
-    Bool		    has_rate;
-    RROutputPtr		    output;
-    RRModePtr		    mode;
-    RR10DataPtr		    pData = NULL;
-    RRScreenSizePtr    	    pSize;
-    
-    UpdateCurrentTime ();
-
-    if (RRClientKnowsRates (client))
-    {
-	REQUEST_SIZE_MATCH (xRRSetScreenConfigReq);
-	has_rate = TRUE;
-    }
-    else
-    {
-	REQUEST_SIZE_MATCH (xRR1_0SetScreenConfigReq);
-	has_rate = FALSE;
-    }
-    
-    SECURITY_VERIFY_DRAWABLE(pDraw, stuff->drawable, client,
-			     SecurityWriteAccess);
-
-    pScreen = pDraw->pScreen;
-
-    pScrPriv = rrGetScrPriv(pScreen);
-    
-    time = ClientTimeToServerTime(stuff->timestamp);
-    configTime = ClientTimeToServerTime(stuff->configTimestamp);
-    
-    if (!pScrPriv)
-    {
-	time = currentTime;
-	rep.status = RRSetConfigFailed;
-	goto sendReply;
-    }
-    if (!RRGetInfo (pScreen))
-	return BadAlloc;
-    
-    output = RRFirstOutput (pScreen);
-    if (!output)
-    {
-	time = currentTime;
-	rep.status = RRSetConfigFailed;
-	goto sendReply;
-    }
-    
-    /*
-     * if the client's config timestamp is not the same as the last config
-     * timestamp, then the config information isn't up-to-date and
-     * can't even be validated
-     */
-    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
-    {
-	rep.status = RRSetConfigInvalidConfigTime;
-	goto sendReply;
-    }
-    
-    pData = RR10GetData (pScreen, output);
-    if (!pData)
-	return BadAlloc;
-    
-    if (stuff->sizeID >= pData->nsize)
-    {
-	/*
-	 * Invalid size ID
-	 */
-	client->errorValue = stuff->sizeID;
-	xfree (pData);
-	return BadValue;
-    }
-    pSize = &pData->sizes[stuff->sizeID];
-    
-    /*
-     * Validate requested rotation
-     */
-    rotation = (Rotation) stuff->rotation;
-
-    /* test the rotation bits only! */
-    switch (rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_90:
-    case RR_Rotate_180:
-    case RR_Rotate_270:
-	break;
-    default:
-	/*
-	 * Invalid rotation
-	 */
-	client->errorValue = stuff->rotation;
-	xfree (pData);
-	return BadValue;
-    }
-
-    if ((~output->crtc->rotations) & rotation)
-    {
-	/*
-	 * requested rotation or reflection not supported by screen
-	 */
-	client->errorValue = stuff->rotation;
-	xfree (pData);
-	return BadMatch;
-    }
-
-    /*
-     * Validate requested refresh
-     */
-    if (has_rate)
-	rate = (int) stuff->rate;
-    else
-	rate = 0;
-
-    if (rate)
-    {
-	for (i = 0; i < pSize->nRates; i++)
-	{
-	    if (pSize->pRates[i].rate == rate)
-		break;
-	}
-	if (i == pSize->nRates)
-	{
-	    /*
-	     * Invalid rate
-	     */
-	    client->errorValue = rate;
-	    xfree (pData);
-	    return BadValue;
-	}
-	mode = pSize->pRates[i].mode;
-    }
-    else
-	mode = pSize->pRates[0].mode;
-    
-    /*
-     * Make sure the requested set-time is not older than
-     * the last set-time
-     */
-    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
-    {
-	rep.status = RRSetConfigInvalidTime;
-	goto sendReply;
-    }
-
-    rep.status = RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation,
-			    1, &output);
-    
-sendReply:
-    
-    if (pData)
-	xfree (pData);
-
-    rep.type = X_Reply;
-    /* rep.status has already been filled in */
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-
-    rep.newTimestamp = pScrPriv->lastSetTime.milliseconds;
-    rep.newConfigTimestamp = pScrPriv->lastConfigTime.milliseconds;
-    rep.root = WindowTable[pDraw->pScreen->myNum]->drawable.id;
-
-    if (client->swapped) 
-    {
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-	swapl(&rep.newTimestamp, n);
-	swapl(&rep.newConfigTimestamp, n);
-	swapl(&rep.root, n);
-    }
-    WriteToClient(client, sizeof(xRRSetScreenConfigReply), (char *)&rep);
-
-    return (client->noClientException);
-}
-
 #if 0
 int
 RRSetScreenConfig (ScreenPtr		pScreen,
@@ -1160,478 +676,6 @@ RRSetScreenConfig (ScreenPtr		pScreen,
 #endif
 
 static int
-ProcRRSelectInput (ClientPtr client)
-{
-    REQUEST(xRRSelectInputReq);
-    rrClientPriv(client);
-    RRTimesPtr	pTimes;
-    WindowPtr	pWin;
-    RREventPtr	pRREvent, *pHead;
-    XID		clientResource;
-
-    REQUEST_SIZE_MATCH(xRRSelectInputReq);
-    pWin = SecurityLookupWindow (stuff->window, client, SecurityWriteAccess);
-    if (!pWin)
-	return BadWindow;
-    pHead = (RREventPtr *)SecurityLookupIDByType(client,
-						 pWin->drawable.id, EventType,
-						 SecurityWriteAccess);
-
-    if (stuff->enable & (RRScreenChangeNotifyMask|
-			 RRCrtcChangeNotifyMask|
-			 RROutputChangeNotifyMask)) 
-    {
-	ScreenPtr	pScreen = pWin->drawable.pScreen;
-	rrScrPriv	(pScreen);
-
-	pRREvent = NULL;
-	if (pHead) 
-	{
-	    /* check for existing entry. */
-	    for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next)
-		if (pRREvent->client == client)
-		    break;
-	}
-
-	if (!pRREvent)
-	{
-	    /* build the entry */
-	    pRREvent = (RREventPtr) xalloc (sizeof (RREventRec));
-	    if (!pRREvent)
-		return BadAlloc;
-	    pRREvent->next = 0;
-	    pRREvent->client = client;
-	    pRREvent->window = pWin;
-	    pRREvent->mask = stuff->enable;
-	    /*
-	     * add a resource that will be deleted when
-	     * the client goes away
-	     */
-	    clientResource = FakeClientID (client->index);
-	    pRREvent->clientResource = clientResource;
-	    if (!AddResource (clientResource, ClientType, (pointer)pRREvent))
-		return BadAlloc;
-	    /*
-	     * create a resource to contain a pointer to the list
-	     * of clients selecting input.  This must be indirect as
-	     * the list may be arbitrarily rearranged which cannot be
-	     * done through the resource database.
-	     */
-	    if (!pHead)
-	    {
-		pHead = (RREventPtr *) xalloc (sizeof (RREventPtr));
-		if (!pHead ||
-		    !AddResource (pWin->drawable.id, EventType, (pointer)pHead))
-		{
-		    FreeResource (clientResource, RT_NONE);
-		    return BadAlloc;
-		}
-		*pHead = 0;
-	    }
-	    pRREvent->next = *pHead;
-	    *pHead = pRREvent;
-	}
-	/*
-	 * Now see if the client needs an event
-	 */
-	if (pScrPriv && (pRREvent->mask & RRScreenChangeNotifyMask))
-	{
-	    pTimes = &((RRTimesPtr) (pRRClient + 1))[pScreen->myNum];
-	    if (CompareTimeStamps (pTimes->setTime, 
-				   pScrPriv->lastSetTime) != 0 ||
-		CompareTimeStamps (pTimes->configTime, 
-				   pScrPriv->lastConfigTime) != 0)
-	    {
-		RRDeliverScreenEvent (client, pWin, pScreen);
-	    }
-	}
-    }
-    else if (stuff->enable == 0) 
-    {
-	/* delete the interest */
-	if (pHead) {
-	    RREventPtr pNewRREvent = 0;
-	    for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next) {
-		if (pRREvent->client == client)
-		    break;
-		pNewRREvent = pRREvent;
-	    }
-	    if (pRREvent) {
-		FreeResource (pRREvent->clientResource, ClientType);
-		if (pNewRREvent)
-		    pNewRREvent->next = pRREvent->next;
-		else
-		    *pHead = pRREvent->next;
-		xfree (pRREvent);
-	    }
-	}
-    }
-    else 
-    {
-	client->errorValue = stuff->enable;
-	return BadValue;
-    }
-    return Success;
-}
-
-/*
- * Retrieve valid screen size range
- */
-static int ProcRRGetScreenSizeRange (ClientPtr client)
-{
-    REQUEST(xRRGetScreenSizeRangeReq);
-    xRRGetScreenSizeRangeReply	rep;
-    WindowPtr			pWin;
-    ScreenPtr			pScreen;
-    rrScrPrivPtr		pScrPriv;
-    
-    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    
-    rep.type = X_Reply;
-    rep.pad = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.length = 0;
-    
-    if (pScrPriv) 
-    {
-	RRGetInfo (pScreen);
-	rep.minWidth  = pScrPriv->minWidth;
-	rep.minHeight = pScrPriv->minHeight;
-	rep.maxWidth  = pScrPriv->maxWidth;
-	rep.maxHeight = pScrPriv->maxHeight;
-    }
-    else
-    {
-	rep.maxWidth  = rep.minWidth  = pScreen->width;
-	rep.maxHeight = rep.minHeight = pScreen->height;
-    }
-    if (client->swapped) 
-    {
-	int n;
-	
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-	swaps(&rep.minWidth, n);
-	swaps(&rep.minHeight, n);
-	swaps(&rep.maxWidth, n);
-	swaps(&rep.maxHeight, n);
-    }
-    WriteToClient(client, sizeof(xRRGetScreenSizeRangeReply), (char *)&rep);
-    return (client->noClientException);
-}
-
-static int ProcRRSetScreenSize (ClientPtr client)
-{
-    REQUEST(xRRSetScreenSizeReq);
-    WindowPtr		pWin;
-    ScreenPtr		pScreen;
-    rrScrPrivPtr	pScrPriv;
-    RRCrtcPtr		crtc;
-    int			i;
-    
-    REQUEST_SIZE_MATCH(xRRSetScreenSizeReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    if (stuff->width < pScrPriv->minWidth || pScrPriv->maxWidth < stuff->width)
-    {
-	client->errorValue = stuff->width;
-	return BadValue;
-    }
-    if (stuff->height < pScrPriv->minHeight || 
-	pScrPriv->maxHeight < stuff->height)
-    {
-	client->errorValue = stuff->height;
-	return BadValue;
-    }
-    for (i = 0; i < pScrPriv->numCrtcs; i++) {
-	crtc = pScrPriv->crtcs[i];
-	if (crtc->mode &&
-	    (crtc->x + crtc->mode->mode.width > stuff->width ||
-	     crtc->y + crtc->mode->mode.height > stuff->height))
-	    return BadMatch;
-    }
-    if (stuff->widthInMillimeters == 0 || stuff->heightInMillimeters == 0)
-    {
-	client->errorValue = 0;
-	return BadValue;
-    }
-    if (!RRScreenSizeSet (pScreen, 
-			  stuff->width, stuff->height,
-			  stuff->widthInMillimeters,
-			  stuff->heightInMillimeters))
-    {
-	return BadMatch;
-    }
-    return Success;
-}
-
-#if 0
-static int ProcRRGetMonitorInfo (ClientPtr client)
-{
-    REQUEST(xRRGetMonitorInfoReq);
-    xRRGetMonitorInfoReply	rep;
-    WindowPtr			pWin;
-    ScreenPtr			pScreen;
-    rrScrPrivPtr		pScrPriv;
-    RRMonitorPtr		pMonitor;
-    RRModePtr			pMode;
-    int				extraLen;
-    CARD8			*extra;
-    xRRMonitorInfo		*monitor;
-    xRRMonitorMode		*mode;
-    CARD8			*names;
-    
-    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    rep.type = X_Reply;
-    rep.pad = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.numMonitors = 0;
-    rep.numModes = 0;
-    rep.sizeNames = 0;
-    if (!pScrPriv)
-    {
-	extraLen = 0;
-	extra = NULL;
-    }
-    else
-    {
-	int i, m, b;
-	for (pMonitor = pScrPriv->pMonitors; pMonitor; pMonitor = pMonitor->next)
-	{
-	    rep.numMonitors++;
-	    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
-	    {
-		rep.numModes++;
-		rep.sizeNames += (1 + pMode->mode.nameLength);
-	    }
-	}
-	extraLen = (rep.numMonitors * sizeof (xRRMonitorInfo) +
-		    rep.numModes * sizeof (xRRMonitorMode) +
-		    rep.sizeNames + 3) & ~3;
-	extra = (CARD8 *) xalloc (extraLen);
-	if (!extra)
-	    return BadAlloc;
-	monitor = (xRRMonitorInfo *) extra;
-	mode = (xRRMonitorMode *) (monitor + rep.numMonitors);
-	names = (CARD8 *) (mode + rep.numModes);
-	i = 0;
-	m = 0;
-	b = 0;
-	for (pMonitor = pScrPriv->pMonitors; pMonitor; pMonitor = pMonitor->next)
-	{
-	    monitor[i].timestamp = pScrPriv->lastSetTime;
-	    monitor[i].configTimestamp = pScrPriv->lastConfigTime;
-	    monitor[i].x = pMonitor->x;
-	    monitor[i].y = pMonitor->y;
-	    monitor[i].rotation = pMonitor->rotation;
-	    monitor[i].mode = pMonitor->pMode->id;
-	    monitor[i].defaultMode = 0;	/* XXX */
-	    monitor[i].rotations = pMonitor->rotations;
-	    monitor[i].firstMode = m;
-	    monitor[i].numModes = 0;
-	    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
-	    {
-		monitor[i].numModes++;
-		mode[m] = pMode->mode;
-		names[b] = pMode->mode.nameLength;
-		b++;
-		memcpy (names + b, (char *) (pMode + 1), 
-			pMode->mode.nameLength);
-		b += pMode->mode.nameLength;
-		m++;
-	    }
-	    i++;
-	}
-	if ((char *) (names + ((b + 3) & ~3)) != (char *) extra + extraLen)
-	    FatalError ("RRGetMonitorInfo length mismatch\n");
-    }
-    rep.length = extraLen >> 2;
-    
-    WriteToClient(client, sizeof(xRRGetMonitorInfoReply), (char *)&rep);
-    if (extraLen)
-    {
-	WriteToClient (client, extraLen, (char *) extra);
-	xfree (extra);
-    }
-    
-    if (extra)
-	xfree (extra);
-    return (client->noClientException);
-}
-
-static int ProcRRAddMonitorMode (ClientPtr client)
-{
-    return BadImplementation;
-}
-
-static int ProcRRDeleteMonitorMode (ClientPtr client)
-{
-    return BadImplementation;
-}
-
-static int ProcRRSetMonitorConfig (ClientPtr client)
-{
-    REQUEST(xRRSetMonitorConfigReq);
-    xRRSetMonitorConfigReply	rep;
-    WindowPtr			pWin;
-    ScreenPtr			pScreen;
-    rrScrPrivPtr		pScrPriv;
-    RRMonitorPtr		pMonitor;
-    RRModePtr			pMode;
-    TimeStamp		    configTime;
-    TimeStamp		    time;
-    Rotation		    rotation;
-    
-    REQUEST_SIZE_MATCH(xRRSetScreenConfigReq);
-    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
-					   SecurityReadAccess);
-
-    if (!pWin)
-	return BadWindow;
-
-    pScreen = pWin->drawable.pScreen;
-    pScrPriv = rrGetScrPriv(pScreen);
-    
-    time = ClientTimeToServerTime(stuff->timestamp);
-    configTime = ClientTimeToServerTime(stuff->configTimestamp);
-    
-    if (!pScrPriv)
-    {
-	time = currentTime;
-	rep.status = RRSetConfigFailed;
-	goto sendReply;
-    }
-    if (!RRGetInfo (pScreen))
-	return BadAlloc;
-    
-    /*
-     * if the client's config timestamp is not the same as the last config
-     * timestamp, then the config information isn't up-to-date and
-     * can't even be validated
-     */
-    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
-    {
-	rep.status = RRSetConfigInvalidConfigTime;
-	goto sendReply;
-    }
-    
-    for (pMonitor = pScrPriv->pMonitors; pMonitor; pMonitor = pMonitor->next)
-    {
-	if (pMonitor->id == stuff->monitorIndex)
-	    break;
-    }
-    if (!pMonitor)
-    {
-	client->errorValue = stuff->monitorIndex;
-	return BadValue;
-    }
-    
-    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
-    {
-	if (pMode->id == stuff->modeIndex)
-	    break;
-    }
-    if (!pMode)
-    {
-	client->errorValue = stuff->modeIndex;
-	return BadValue;
-    }
-    
-    /*
-     * Validate requested rotation
-     */
-    rotation = (Rotation) stuff->rotation;
-
-    /* test the rotation bits only! */
-    switch (rotation & 0xf) {
-    case RR_Rotate_0:
-    case RR_Rotate_90:
-    case RR_Rotate_180:
-    case RR_Rotate_270:
-	break;
-    default:
-	/*
-	 * Invalid rotation
-	 */
-	client->errorValue = stuff->rotation;
-	return BadValue;
-    }
-
-    if ((~pMonitor->rotations) & rotation)
-    {
-	/*
-	 * requested rotation or reflection not supported by screen
-	 */
-	client->errorValue = stuff->rotation;
-	return BadMatch;
-    }
-
-    if (stuff->x + pMode->mode.width > pScreen->width)
-    {
-	client->errorValue = stufff
-	stuff->y + pMode->mode.height > pScreen
-    /*
-     * Make sure the requested set-time is not older than
-     * the last set-time
-     */
-    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
-    {
-	rep.status = RRSetConfigInvalidTime;
-	goto sendReply;
-    }
-
-    rep.status = RRMonitorSetMode (pScreen, pMonitor, 
-				   pMode, stuff->x, stuff->y, rotation, time);
-    
-    return client->noClientException;
-}
-#endif
-
-int (*ProcRandrVector[RRNumberRequests])(ClientPtr) = {
-    ProcRRQueryVersion,	/* 0 */
-/* we skip 1 to make old clients fail pretty immediately */
-    NULL,			/* 1 ProcRandrOldGetScreenInfo */
-/* V1.0 apps share the same set screen config request id */
-    ProcRRSetScreenConfig,	/* 2 */
-    NULL,			/* 3 ProcRandrOldScreenChangeSelectInput */
-/* 3 used to be ScreenChangeSelectInput; deprecated */
-    ProcRRSelectInput,		/* 4 */
-    ProcRRGetScreenInfo,    	/* 5 */
-/* V1.2 additions */
-#if 0
-    ProcRRGetScreenSizeRange,	/* 6 */
-    ProcRRSetScreenSize,	/* 7 */
-    ProcRRGetMonitorInfo,	/* 8 */
-    ProcRRAddMonitorMode,	/* 9 */
-    ProcRRDeleteMonitorMode,	/* 10 */
-    ProcRRSetMonitorConfig,	/* 11 */
-#endif
-};
-
-
-static int
 ProcRRDispatch (ClientPtr client)
 {
     REQUEST(xReq);
@@ -1641,81 +685,12 @@ ProcRRDispatch (ClientPtr client)
 }
 
 static int
-SProcRRQueryVersion (ClientPtr client)
-{
-    register int n;
-    REQUEST(xRRQueryVersionReq);
-
-    swaps(&stuff->length, n);
-    swapl(&stuff->majorVersion, n);
-    swapl(&stuff->minorVersion, n);
-    return ProcRRQueryVersion(client);
-}
-
-static int
-SProcRRGetScreenInfo (ClientPtr client)
-{
-    register int n;
-    REQUEST(xRRGetScreenInfoReq);
-
-    swaps(&stuff->length, n);
-    swapl(&stuff->window, n);
-    return ProcRRGetScreenInfo(client);
-}
-
-static int
-SProcRRSetScreenConfig (ClientPtr client)
-{
-    register int n;
-    REQUEST(xRRSetScreenConfigReq);
-
-    if (RRClientKnowsRates (client))
-    {
-	REQUEST_SIZE_MATCH (xRRSetScreenConfigReq);
-	swaps (&stuff->rate, n);
-    }
-    else
-    {
-	REQUEST_SIZE_MATCH (xRR1_0SetScreenConfigReq);
-    }
-    
-    swaps(&stuff->length, n);
-    swapl(&stuff->drawable, n);
-    swapl(&stuff->timestamp, n);
-    swaps(&stuff->sizeID, n);
-    swaps(&stuff->rotation, n);
-    return ProcRRSetScreenConfig(client);
-}
-
-static int
-SProcRRSelectInput (ClientPtr client)
-{
-    register int n;
-    REQUEST(xRRSelectInputReq);
-
-    swaps(&stuff->length, n);
-    swapl(&stuff->window, n);
-    return ProcRRSelectInput(client);
-}
-
-
-static int
 SProcRRDispatch (ClientPtr client)
 {
     REQUEST(xReq);
-    switch (stuff->data)
-    {
-    case X_RRQueryVersion:
-	return SProcRRQueryVersion(client);
-    case X_RRSetScreenConfig:
-        return SProcRRSetScreenConfig(client);
-    case X_RRSelectInput:
-        return SProcRRSelectInput(client);
-    case X_RRGetScreenInfo:
-        return SProcRRGetScreenInfo(client);
-    default:
+    if (stuff->data >= RRNumberRequests || !ProcRandrVector[stuff->data])
 	return BadRequest;
-    }
+    return (*SProcRandrVector[stuff->data]) (client);
 }
 
 #if RANDR_12_INTERFACE
@@ -1741,7 +716,6 @@ RRScreenSetSizeRange (ScreenPtr	pScreen,
 #endif
 
 #ifdef RANDR_10_INTERFACE
-
 static Bool
 RRScreenSizeMatches (RRScreenSizePtr  a,
 		   RRScreenSizePtr  b)
diff --git a/randr/randrstr.h b/randr/randrstr.h
index f323660..3346157 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -59,8 +59,11 @@ typedef XID	RRMode;
 typedef XID	RROutput;
 typedef XID	RRCrtc;
 
-extern int	RREventBase;
+extern int	RREventBase, RRErrorBase;
 
+extern int (*ProcRandrVector[RRNumberRequests])(ClientPtr);
+extern int (*SProcRandrVector[RRNumberRequests])(ClientPtr);
+    
 /*
  * Modeline for a monitor. Name follows directly after this struct
  */
@@ -101,7 +104,7 @@ struct _rrOutput {
     int		    numCrtcs;
     RRCrtcPtr	    *crtcs;
     int		    numClones;
-    RROutputPtr	    *outputs;
+    RROutputPtr	    *clones;
     int		    numModes;
     RRModePtr	    *modes;
     Bool	    changed;
@@ -210,6 +213,42 @@ extern int rrPrivIndex;
 #define rrScrPriv(pScr)	rrScrPrivPtr    pScrPriv = rrGetScrPriv(pScr)
 #define SetRRScreen(s,p) ((s)->devPrivates[rrPrivIndex].ptr = (pointer) (p))
 
+/*
+ * each window has a list of clients requesting
+ * RRNotify events.  Each client has a resource
+ * for each window it selects RRNotify input for,
+ * this resource is used to delete the RRNotifyRec
+ * entry from the per-window queue.
+ */
+
+typedef struct _RREvent *RREventPtr;
+
+typedef struct _RREvent {
+    RREventPtr  next;
+    ClientPtr	client;
+    WindowPtr	window;
+    XID		clientResource;
+    int		mask;
+} RREventRec;
+
+typedef struct _RRTimes {
+    TimeStamp	setTime;
+    TimeStamp	configTime;
+} RRTimesRec, *RRTimesPtr;
+
+typedef struct _RRClient {
+    int		major_version;
+    int		minor_version;
+/*  RRTimesRec	times[0]; */
+} RRClientRec, *RRClientPtr;
+
+extern RESTYPE	RRClientType, RREventType; /* resource types for event masks */
+extern int	RRClientPrivateIndex;
+extern RESTYPE	RRCrtcType, RRModeType, RROutputType;
+
+#define GetRRClient(pClient)    ((RRClientPtr) (pClient)->devPrivates[RRClientPrivateIndex].ptr)
+#define rrClientPriv(pClient)	RRClientPtr pRRClient = GetRRClient(pClient)
+
 /* Initialize the extension */
 void
 RRExtensionInit (void);
@@ -278,8 +317,17 @@ miRRCrtcSet (ScreenPtr	pScreen,
 void
 RRTellChanged (ScreenPtr pScreen);
 
+/*
+ * Poll the driver for changed information
+ */
+Bool
+RRGetInfo (ScreenPtr pScreen);
+
 Bool RRScreenInit(ScreenPtr pScreen);
 
+RROutputPtr
+RRFirstOutput (ScreenPtr pScreen);
+
 Rotation
 RRGetRotation (ScreenPtr pScreen);
 
@@ -338,13 +386,6 @@ RRCrtcPtr
 RRCrtcCreate (ScreenPtr	pScreen,
 	      void	*devPrivate);
 
-
-/*
- * Use this value for any num parameter to indicate that
- * the related data are unchanged
- */
-#define RR_NUM_UNCHANGED    -1
-
 /*
  * Notify the extension that the Crtc has been reconfigured,
  * the driver calls this whenever it has updated the mode
@@ -358,6 +399,9 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
 	      int	    numOutput,
 	      RROutputPtr   *outputs);
 
+void
+RRDeliverCrtcEvent (ClientPtr client, WindowPtr pWin, RRCrtcPtr crtc);
+    
 /*
  * Request that the Crtc be reconfigured
  */
@@ -382,6 +426,10 @@ RRCrtcDestroy (RRCrtcPtr crtc);
 Bool
 RRCrtcInit (void);
 
+/* rrdispatch.c */
+Bool
+RRClientKnowsRates (ClientPtr	pClient);
+
 /* rrmode.c */
 /*
  * Find, and if necessary, create a mode
@@ -439,6 +487,9 @@ RROutputSetConnection (RROutputPtr  output,
 		       CARD8	    connection);
 
 void
+RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output);
+
+void
 RROutputDestroy (RROutputPtr	output);
 
 /*
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index cc5b24d..d343c3a 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -22,7 +22,7 @@
 
 #include "randrstr.h"
 
-static RESTYPE	CrtcType;
+RESTYPE	RRCrtcType;
 
 /*
  * Create a CRTC
@@ -144,6 +144,12 @@ RRCrtcNotify (RRCrtcPtr	    crtc,
     return TRUE;
 }
 
+void
+RRDeliverCrtcEvent (ClientPtr client, WindowPtr pWin, RRCrtcPtr crtc)
+{
+    
+}
+
 /*
  * Request that the Crtc be reconfigured
  */
@@ -216,6 +222,7 @@ RRCrtcDestroyResource (pointer value, XID pid)
 	    memmove (pScrPriv->crtcs, pScrPriv->crtcs + 1,
 		     (pScrPriv->numCrtcs - (i - 1)) * sizeof (RRCrtcPtr));
 	    --pScrPriv->numCrtcs;
+	    break;
 	}
     }
     free (value);
@@ -228,11 +235,11 @@ RRCrtcDestroyResource (pointer value, XID pid)
 Bool
 RRCrtcInit (void)
 {
-    CrtcType = CreateNewResourceType (RRCrtcDestroyResource);
-    if (!CrtcType)
+    RRCrtcType = CreateNewResourceType (RRCrtcDestroyResource);
+    if (!RRCrtcType)
 	return FALSE;
 #ifdef XResExtension
-	RegisterResourceName (CrtcType, "CRTC");
+	RegisterResourceName (RRCrtcType, "CRTC");
 #endif
     return TRUE;
 }
diff --git a/randr/rrdispatch.c b/randr/rrdispatch.c
new file mode 100644
index 0000000..acf6298
--- /dev/null
+++ b/randr/rrdispatch.c
@@ -0,0 +1,1034 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+
+Bool
+RRClientKnowsRates (ClientPtr	pClient)
+{
+    rrClientPriv(pClient);
+
+    return (pRRClient->major_version > 1 ||
+	    (pRRClient->major_version == 1 && pRRClient->minor_version >= 1));
+}
+
+typedef struct _RR10Data {
+    RRScreenSizePtr sizes;
+    int		    nsize;
+    int		    nrefresh;
+    int		    size;
+    CARD16	    refresh;
+} RR10DataRec, *RR10DataPtr;
+
+/*
+ * Convert 1.2 monitor data into 1.0 screen data
+ */
+static RR10DataPtr
+RR10GetData (ScreenPtr pScreen, RROutputPtr output)
+{
+    RR10DataPtr	    data;
+    RRScreenSizePtr size;
+    int		    nmode = output->numModes;
+    int		    i, j, k;
+    RRScreenRatePtr refresh;
+    CARD16	    vRefresh;
+    RRModePtr	    mode;
+
+    /* Make sure there is plenty of space for any combination */
+    data = malloc (sizeof (RR10DataRec) + 
+		   sizeof (RRScreenSize) * nmode + 
+		   sizeof (RRScreenRate) * nmode);
+    if (!data)
+	return NULL;
+    size = (RRScreenSizePtr) (data + 1);
+    refresh = (RRScreenRatePtr) (size + nmode);
+    data->sizes = size;
+    data->nsize = 0;
+    data->nrefresh = 0;
+    data->size = 0;
+    data->refresh = 0;
+    for (i = 0; i < output->numModes; i++)
+    {
+	mode = output->modes[i];
+	for (j = 0; j < data->nsize; j++)
+	    if (mode->mode.width == size[j].width &&
+		mode->mode.height == size[j].height)
+		break;
+	if (j == data->nsize)
+	{
+	    size[j].id = j;
+	    size[j].width = mode->mode.width;
+	    size[j].height = mode->mode.height;
+	    size[j].mmWidth = mode->mode.mmWidth;
+	    size[j].mmHeight = mode->mode.mmHeight;
+	    size[j].nRates = 0;
+	    size[j].pRates = &refresh[data->nrefresh];
+	    data->nsize++;
+	}
+	vRefresh = RRVerticalRefresh (&mode->mode);
+	for (k = 0; k < size[j].nRates; k++)
+	    if (vRefresh == size[j].pRates[k].rate)
+		break;
+	if (k == size[j].nRates)
+	{
+	    size[j].pRates[k].rate = vRefresh;
+	    size[j].pRates[k].mode = mode;
+	    size[j].nRates++;
+	    data->nrefresh++;
+	}
+	if (mode == output->crtc->mode)
+	{
+	    data->size = j;
+	    data->refresh = vRefresh;
+	}
+    }
+    return data;
+}
+
+static int
+ProcRRQueryVersion (ClientPtr client)
+{
+    xRRQueryVersionReply rep;
+    register int n;
+    REQUEST(xRRQueryVersionReq);
+    rrClientPriv(client);
+
+    REQUEST_SIZE_MATCH(xRRQueryVersionReq);
+    pRRClient->major_version = stuff->majorVersion;
+    pRRClient->minor_version = stuff->minorVersion;
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    /*
+     * Report the current version; the current
+     * spec says they're all compatible after 1.0
+     */
+    rep.majorVersion = RANDR_MAJOR;
+    rep.minorVersion = RANDR_MINOR;
+    if (client->swapped) {
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swapl(&rep.majorVersion, n);
+	swapl(&rep.minorVersion, n);
+    }
+    WriteToClient(client, sizeof(xRRQueryVersionReply), (char *)&rep);
+    return (client->noClientException);
+}
+
+static int
+ProcRRGetScreenInfo (ClientPtr client)
+{
+    REQUEST(xRRGetScreenInfoReq);
+    xRRGetScreenInfoReply   rep;
+    WindowPtr	    	    pWin;
+    int			    n;
+    ScreenPtr		    pScreen;
+    rrScrPrivPtr	    pScrPriv;
+    CARD8		    *extra;
+    unsigned long	    extraLen;
+    RROutputPtr		    output;
+
+    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    rep.pad = 0;
+    
+    if (pScrPriv)
+	RRGetInfo (pScreen);
+
+    output = RRFirstOutput (pScreen);
+    
+    if (!pScrPriv || !output)
+    {
+	rep.type = X_Reply;
+	rep.setOfRotations = RR_Rotate_0;;
+	rep.sequenceNumber = client->sequence;
+	rep.length = 0;
+	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
+	rep.timestamp = currentTime.milliseconds;
+	rep.configTimestamp = currentTime.milliseconds;
+	rep.nSizes = 0;
+	rep.sizeID = 0;
+	rep.rotation = RR_Rotate_0;
+	rep.rate = 0;
+	rep.nrateEnts = 0;
+	extra = 0;
+	extraLen = 0;
+    }
+    else
+    {
+	int			i, j;
+	xScreenSizes		*size;
+	CARD16			*rates;
+	CARD8			*data8;
+	Bool			has_rate = RRClientKnowsRates (client);
+	RR10DataPtr		pData;
+	RRScreenSizePtr		pSize;
+    
+	pData = RR10GetData (pScreen, output);
+	if (!pData)
+	    return BadAlloc;
+	
+	rep.type = X_Reply;
+	rep.setOfRotations = output->crtc->rotations;
+	rep.sequenceNumber = client->sequence;
+	rep.length = 0;
+	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
+	rep.timestamp = pScrPriv->lastSetTime.milliseconds;
+	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
+	rep.rotation = output->crtc->rotation;
+	rep.nSizes = pData->nsize;
+        rep.nrateEnts = pData->nrefresh + pData->nsize;
+	rep.sizeID = pData->size;
+	rep.rate = pData->refresh;
+
+	extraLen = (rep.nSizes * sizeof (xScreenSizes) +
+		    rep.nrateEnts * sizeof (CARD16));
+
+	extra = (CARD8 *) xalloc (extraLen);
+	if (!extra)
+	{
+	    xfree (pData);
+	    return BadAlloc;
+	}
+	/*
+	 * First comes the size information
+	 */
+	size = (xScreenSizes *) extra;
+	rates = (CARD16 *) (size + rep.nSizes);
+	for (i = 0; i < pData->nsize; i++)
+	{
+	    pSize = &pData->sizes[i];
+	    size->widthInPixels = pSize->width;
+	    size->heightInPixels = pSize->height;
+	    size->widthInMillimeters = pSize->mmWidth;
+	    size->heightInMillimeters = pSize->mmHeight;
+	    if (client->swapped)
+	    {
+	        swaps (&size->widthInPixels, n);
+	        swaps (&size->heightInPixels, n);
+	        swaps (&size->widthInMillimeters, n);
+	        swaps (&size->heightInMillimeters, n);
+	    }
+	    size++;
+	    if (has_rate)
+	    {
+		*rates = pSize->nRates;
+		if (client->swapped)
+		{
+		    swaps (rates, n);
+		}
+		rates++;
+		for (j = 0; j < pSize->nRates; j++)
+		{
+		    *rates = pSize->pRates[j].rate;
+		    if (client->swapped)
+		    {
+			swaps (rates, n);
+		    }
+		    rates++;
+		}
+	    }
+	}
+        xfree (pData);
+	
+	data8 = (CARD8 *) rates;
+
+	if (data8 - (CARD8 *) extra != extraLen)
+	    FatalError ("RRGetScreenInfo bad extra len %ld != %ld\n",
+			(unsigned long)(data8 - (CARD8 *) extra), extraLen);
+	rep.length =  (extraLen + 3) >> 2;
+    }
+    if (client->swapped) {
+	swaps(&rep.sequenceNumber, n);
+	swapl(&rep.length, n);
+	swapl(&rep.timestamp, n);
+	swaps(&rep.rotation, n);
+	swaps(&rep.nSizes, n);
+	swaps(&rep.sizeID, n);
+	swaps(&rep.rate, n);
+	swaps(&rep.nrateEnts, n);
+    }
+    WriteToClient(client, sizeof(xRRGetScreenInfoReply), (char *)&rep);
+    if (extraLen)
+    {
+	WriteToClient (client, extraLen, (char *) extra);
+	xfree (extra);
+    }
+    return (client->noClientException);
+}
+
+static int
+ProcRRSetScreenConfig (ClientPtr client)
+{
+    REQUEST(xRRSetScreenConfigReq);
+    xRRSetScreenConfigReply rep;
+    DrawablePtr		    pDraw;
+    int			    n;
+    ScreenPtr		    pScreen;
+    rrScrPrivPtr	    pScrPriv;
+    TimeStamp		    configTime;
+    TimeStamp		    time;
+    int			    i;
+    Rotation		    rotation;
+    int			    rate;
+    Bool		    has_rate;
+    RROutputPtr		    output;
+    RRModePtr		    mode;
+    RR10DataPtr		    pData = NULL;
+    RRScreenSizePtr    	    pSize;
+    
+    UpdateCurrentTime ();
+
+    if (RRClientKnowsRates (client))
+    {
+	REQUEST_SIZE_MATCH (xRRSetScreenConfigReq);
+	has_rate = TRUE;
+    }
+    else
+    {
+	REQUEST_SIZE_MATCH (xRR1_0SetScreenConfigReq);
+	has_rate = FALSE;
+    }
+    
+    SECURITY_VERIFY_DRAWABLE(pDraw, stuff->drawable, client,
+			     SecurityWriteAccess);
+
+    pScreen = pDraw->pScreen;
+
+    pScrPriv = rrGetScrPriv(pScreen);
+    
+    time = ClientTimeToServerTime(stuff->timestamp);
+    configTime = ClientTimeToServerTime(stuff->configTimestamp);
+    
+    if (!pScrPriv)
+    {
+	time = currentTime;
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    if (!RRGetInfo (pScreen))
+	return BadAlloc;
+    
+    output = RRFirstOutput (pScreen);
+    if (!output)
+    {
+	time = currentTime;
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    
+    /*
+     * if the client's config timestamp is not the same as the last config
+     * timestamp, then the config information isn't up-to-date and
+     * can't even be validated
+     */
+    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
+    {
+	rep.status = RRSetConfigInvalidConfigTime;
+	goto sendReply;
+    }
+    
+    pData = RR10GetData (pScreen, output);
+    if (!pData)
+	return BadAlloc;
+    
+    if (stuff->sizeID >= pData->nsize)
+    {
+	/*
+	 * Invalid size ID
+	 */
+	client->errorValue = stuff->sizeID;
+	xfree (pData);
+	return BadValue;
+    }
+    pSize = &pData->sizes[stuff->sizeID];
+    
+    /*
+     * Validate requested rotation
+     */
+    rotation = (Rotation) stuff->rotation;
+
+    /* test the rotation bits only! */
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_90:
+    case RR_Rotate_180:
+    case RR_Rotate_270:
+	break;
+    default:
+	/*
+	 * Invalid rotation
+	 */
+	client->errorValue = stuff->rotation;
+	xfree (pData);
+	return BadValue;
+    }
+
+    if ((~output->crtc->rotations) & rotation)
+    {
+	/*
+	 * requested rotation or reflection not supported by screen
+	 */
+	client->errorValue = stuff->rotation;
+	xfree (pData);
+	return BadMatch;
+    }
+
+    /*
+     * Validate requested refresh
+     */
+    if (has_rate)
+	rate = (int) stuff->rate;
+    else
+	rate = 0;
+
+    if (rate)
+    {
+	for (i = 0; i < pSize->nRates; i++)
+	{
+	    if (pSize->pRates[i].rate == rate)
+		break;
+	}
+	if (i == pSize->nRates)
+	{
+	    /*
+	     * Invalid rate
+	     */
+	    client->errorValue = rate;
+	    xfree (pData);
+	    return BadValue;
+	}
+	mode = pSize->pRates[i].mode;
+    }
+    else
+	mode = pSize->pRates[0].mode;
+    
+    /*
+     * Make sure the requested set-time is not older than
+     * the last set-time
+     */
+    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
+    {
+	rep.status = RRSetConfigInvalidTime;
+	goto sendReply;
+    }
+
+    rep.status = RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation,
+			    1, &output);
+    
+sendReply:
+    
+    if (pData)
+	xfree (pData);
+
+    rep.type = X_Reply;
+    /* rep.status has already been filled in */
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+
+    rep.newTimestamp = pScrPriv->lastSetTime.milliseconds;
+    rep.newConfigTimestamp = pScrPriv->lastConfigTime.milliseconds;
+    rep.root = WindowTable[pDraw->pScreen->myNum]->drawable.id;
+
+    if (client->swapped) 
+    {
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swapl(&rep.newTimestamp, n);
+	swapl(&rep.newConfigTimestamp, n);
+	swapl(&rep.root, n);
+    }
+    WriteToClient(client, sizeof(xRRSetScreenConfigReply), (char *)&rep);
+
+    return (client->noClientException);
+}
+
+static int
+ProcRRSelectInput (ClientPtr client)
+{
+    REQUEST(xRRSelectInputReq);
+    rrClientPriv(client);
+    RRTimesPtr	pTimes;
+    WindowPtr	pWin;
+    RREventPtr	pRREvent, *pHead;
+    XID		clientResource;
+
+    REQUEST_SIZE_MATCH(xRRSelectInputReq);
+    pWin = SecurityLookupWindow (stuff->window, client, SecurityWriteAccess);
+    if (!pWin)
+	return BadWindow;
+    pHead = (RREventPtr *)SecurityLookupIDByType(client,
+						 pWin->drawable.id, RREventType,
+						 SecurityWriteAccess);
+
+    if (stuff->enable & (RRScreenChangeNotifyMask|
+			 RRCrtcChangeNotifyMask|
+			 RROutputChangeNotifyMask)) 
+    {
+	ScreenPtr	pScreen = pWin->drawable.pScreen;
+	rrScrPriv	(pScreen);
+
+	pRREvent = NULL;
+	if (pHead) 
+	{
+	    /* check for existing entry. */
+	    for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next)
+		if (pRREvent->client == client)
+		    break;
+	}
+
+	if (!pRREvent)
+	{
+	    /* build the entry */
+	    pRREvent = (RREventPtr) xalloc (sizeof (RREventRec));
+	    if (!pRREvent)
+		return BadAlloc;
+	    pRREvent->next = 0;
+	    pRREvent->client = client;
+	    pRREvent->window = pWin;
+	    pRREvent->mask = stuff->enable;
+	    /*
+	     * add a resource that will be deleted when
+	     * the client goes away
+	     */
+	    clientResource = FakeClientID (client->index);
+	    pRREvent->clientResource = clientResource;
+	    if (!AddResource (clientResource, RRClientType, (pointer)pRREvent))
+		return BadAlloc;
+	    /*
+	     * create a resource to contain a pointer to the list
+	     * of clients selecting input.  This must be indirect as
+	     * the list may be arbitrarily rearranged which cannot be
+	     * done through the resource database.
+	     */
+	    if (!pHead)
+	    {
+		pHead = (RREventPtr *) xalloc (sizeof (RREventPtr));
+		if (!pHead ||
+		    !AddResource (pWin->drawable.id, RREventType, (pointer)pHead))
+		{
+		    FreeResource (clientResource, RT_NONE);
+		    return BadAlloc;
+		}
+		*pHead = 0;
+	    }
+	    pRREvent->next = *pHead;
+	    *pHead = pRREvent;
+	}
+	/*
+	 * Now see if the client needs an event
+	 */
+	if (pScrPriv && (pRREvent->mask & RRScreenChangeNotifyMask))
+	{
+	    pTimes = &((RRTimesPtr) (pRRClient + 1))[pScreen->myNum];
+	    if (CompareTimeStamps (pTimes->setTime, 
+				   pScrPriv->lastSetTime) != 0 ||
+		CompareTimeStamps (pTimes->configTime, 
+				   pScrPriv->lastConfigTime) != 0)
+	    {
+		RRDeliverScreenEvent (client, pWin, pScreen);
+	    }
+	}
+    }
+    else if (stuff->enable == 0) 
+    {
+	/* delete the interest */
+	if (pHead) {
+	    RREventPtr pNewRREvent = 0;
+	    for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next) {
+		if (pRREvent->client == client)
+		    break;
+		pNewRREvent = pRREvent;
+	    }
+	    if (pRREvent) {
+		FreeResource (pRREvent->clientResource, RRClientType);
+		if (pNewRREvent)
+		    pNewRREvent->next = pRREvent->next;
+		else
+		    *pHead = pRREvent->next;
+		xfree (pRREvent);
+	    }
+	}
+    }
+    else 
+    {
+	client->errorValue = stuff->enable;
+	return BadValue;
+    }
+    return Success;
+}
+
+/*
+ * Retrieve valid screen size range
+ */
+static int 
+ProcRRGetScreenSizeRange (ClientPtr client)
+{
+    REQUEST(xRRGetScreenSizeRangeReq);
+    xRRGetScreenSizeRangeReply	rep;
+    WindowPtr			pWin;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    
+    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    
+    rep.type = X_Reply;
+    rep.pad = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.length = 0;
+    
+    if (pScrPriv) 
+    {
+	RRGetInfo (pScreen);
+	rep.minWidth  = pScrPriv->minWidth;
+	rep.minHeight = pScrPriv->minHeight;
+	rep.maxWidth  = pScrPriv->maxWidth;
+	rep.maxHeight = pScrPriv->maxHeight;
+    }
+    else
+    {
+	rep.maxWidth  = rep.minWidth  = pScreen->width;
+	rep.maxHeight = rep.minHeight = pScreen->height;
+    }
+    if (client->swapped) 
+    {
+	int n;
+	
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swaps(&rep.minWidth, n);
+	swaps(&rep.minHeight, n);
+	swaps(&rep.maxWidth, n);
+	swaps(&rep.maxHeight, n);
+    }
+    WriteToClient(client, sizeof(xRRGetScreenSizeRangeReply), (char *)&rep);
+    return (client->noClientException);
+}
+
+static int ProcRRSetScreenSize (ClientPtr client)
+{
+    REQUEST(xRRSetScreenSizeReq);
+    WindowPtr		pWin;
+    ScreenPtr		pScreen;
+    rrScrPrivPtr	pScrPriv;
+    RRCrtcPtr		crtc;
+    int			i;
+    
+    REQUEST_SIZE_MATCH(xRRSetScreenSizeReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    if (stuff->width < pScrPriv->minWidth || pScrPriv->maxWidth < stuff->width)
+    {
+	client->errorValue = stuff->width;
+	return BadValue;
+    }
+    if (stuff->height < pScrPriv->minHeight || 
+	pScrPriv->maxHeight < stuff->height)
+    {
+	client->errorValue = stuff->height;
+	return BadValue;
+    }
+    for (i = 0; i < pScrPriv->numCrtcs; i++) {
+	crtc = pScrPriv->crtcs[i];
+	if (crtc->mode &&
+	    (crtc->x + crtc->mode->mode.width > stuff->width ||
+	     crtc->y + crtc->mode->mode.height > stuff->height))
+	    return BadMatch;
+    }
+    if (stuff->widthInMillimeters == 0 || stuff->heightInMillimeters == 0)
+    {
+	client->errorValue = 0;
+	return BadValue;
+    }
+    if (!RRScreenSizeSet (pScreen, 
+			  stuff->width, stuff->height,
+			  stuff->widthInMillimeters,
+			  stuff->heightInMillimeters))
+    {
+	return BadMatch;
+    }
+    return Success;
+}
+
+static int
+ProcRRGetScreenResources (ClientPtr client)
+{
+    REQUEST(xRRGetScreenResourcesReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetScreenResourcesReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRGetOutputInfo (ClientPtr client)
+{
+    REQUEST(xRRGetOutputInfoReq);;
+    
+    REQUEST_SIZE_MATCH(xRRGetOutputInfoReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRListOutputProperties (ClientPtr client)
+{
+    REQUEST(xRRListOutputPropertiesReq);
+    
+    REQUEST_SIZE_MATCH(xRRListOutputPropertiesReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRChangeOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRChangeOutputPropertyReq);
+    
+    REQUEST_SIZE_MATCH(xRRChangeOutputPropertyReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRDeleteOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRDeleteOutputPropertyReq);
+    
+    REQUEST_SIZE_MATCH(xRRDeleteOutputPropertyReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRGetOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRGetOutputPropertyReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetOutputPropertyReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRCreateMode (ClientPtr client)
+{
+    REQUEST(xRRCreateModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRCreateModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRDestroyMode (ClientPtr client)
+{
+    REQUEST(xRRDestroyModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRDestroyModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRAddOutputMode (ClientPtr client)
+{
+    REQUEST(xRRAddOutputModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRAddOutputModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRDeleteOutputMode (ClientPtr client)
+{
+    REQUEST(xRRDeleteOutputModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRDeleteOutputModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRGetCrtcInfo (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcInfoReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetCrtcInfoReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRSetCrtcConfig (ClientPtr client)
+{
+    REQUEST(xRRSetCrtcConfigReq);
+    xRRSetCrtcConfigReply   rep;
+    ScreenPtr		    pScreen;
+    rrScrPrivPtr	    pScrPriv;
+    RRCrtcPtr		    crtc;
+    RRModePtr		    mode;
+    int			    numOutputs;
+    RROutputPtr		    *outputs = NULL;
+    RROutput		    *outputIds;
+    TimeStamp		    configTime;
+    TimeStamp		    time;
+    Rotation		    rotation;
+    int			    i, j;
+    
+    REQUEST_AT_LEAST_SIZE(xRRSetCrtcConfigReq);
+    numOutputs = stuff->length - (SIZEOF (xRRSetCrtcConfigReq) >> 2);
+    
+    crtc = LookupIDByType (stuff->crtc, RRCrtcType);
+    if (!crtc)
+    {
+	client->errorValue = stuff->crtc;
+	return RRErrorBase + BadCrtc;
+    }
+    if (stuff->mode == None)
+    {
+	mode = NULL;
+	if (numOutputs > 0)
+	    return BadMatch;
+    }
+    else
+    {
+	mode = LookupIDByType (stuff->mode, RRModeType);
+	if (!mode)
+	{
+	    client->errorValue = stuff->mode;
+	    return RRErrorBase + BadMode;
+	}
+	if (numOutputs == 0)
+	    return BadMatch;
+    }
+    outputs = xalloc (numOutputs * sizeof (RROutputPtr));
+    if (!outputs)
+	return BadAlloc;
+    
+    outputIds = (RROutput *) (stuff + 1);
+    for (i = 0; i < numOutputs; i++)
+    {
+	outputs[i] = LookupIDByType (outputIds[i], RROutputType);
+	if (!outputs[i])
+	{
+	    client->errorValue = outputIds[i];
+	    return RRErrorBase + BadOutput;
+	}
+	/* validate crtc for this output */
+	for (j = 0; j < outputs[i]->numCrtcs; j++)
+	    if (outputs[i]->crtcs[j] == crtc)
+		break;
+	if (j == outputs[j]->numCrtcs)
+	    return BadMatch;
+	/* validate mode for this output */
+	for (j = 0; j < outputs[i]->numModes; j++)
+	    if (outputs[i]->modes[j] == mode)
+		break;
+	if (j == outputs[j]->numModes)
+	    return BadMatch;
+    }
+
+    pScreen = crtc->pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    
+    time = ClientTimeToServerTime(stuff->timestamp);
+    configTime = ClientTimeToServerTime(stuff->configTimestamp);
+    
+    if (!pScrPriv)
+    {
+	time = currentTime;
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    if (!RRGetInfo (pScreen))
+	return BadAlloc;
+    
+    /*
+     * if the client's config timestamp is not the same as the last config
+     * timestamp, then the config information isn't up-to-date and
+     * can't even be validated
+     */
+    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
+    {
+	rep.status = RRSetConfigInvalidConfigTime;
+	goto sendReply;
+    }
+    
+    /*
+     * Validate requested rotation
+     */
+    rotation = (Rotation) stuff->rotation;
+
+    /* test the rotation bits only! */
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_90:
+    case RR_Rotate_180:
+    case RR_Rotate_270:
+	break;
+    default:
+	/*
+	 * Invalid rotation
+	 */
+	client->errorValue = stuff->rotation;
+	return BadValue;
+    }
+
+    if ((~crtc->rotations) & rotation)
+    {
+	/*
+	 * requested rotation or reflection not supported by screen
+	 */
+	client->errorValue = stuff->rotation;
+	return BadMatch;
+    }
+
+    if (stuff->x + mode->mode.width > pScreen->width)
+    {
+	client->errorValue = stuff->x;
+	return BadValue;
+    }
+    
+    if (stuff->y + mode->mode.height > pScreen->height)
+    {
+	client->errorValue = stuff->y;
+	return BadValue;
+    }
+    
+    /*
+     * Make sure the requested set-time is not older than
+     * the last set-time
+     */
+    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
+    {
+	rep.status = RRSetConfigInvalidTime;
+	goto sendReply;
+    }
+
+    rep.status = RRCrtcSet (crtc, mode, stuff->x, stuff->y,
+			    rotation, numOutputs, outputs);
+    
+sendReply:
+    if (outputs)
+	xfree (outputs);
+    
+    rep.type = X_Reply;
+    /* rep.status has already been filled in */
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.newTimestamp = pScrPriv->lastConfigTime.milliseconds;
+
+    if (client->swapped) 
+    {
+	int n;
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swapl(&rep.newTimestamp, n);
+    }
+    WriteToClient(client, sizeof(xRRSetCrtcConfigReply), (char *)&rep);
+    
+    return client->noClientException;
+}
+
+static int
+ProcRRGetCrtcGammaSize (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcGammaSizeReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetCrtcGammaSizeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRGetCrtcGamma (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcGammaReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetCrtcGammaReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+ProcRRSetCrtcGamma (ClientPtr client)
+{
+    REQUEST(xRRSetCrtcGammaReq);
+    
+    REQUEST_SIZE_MATCH(xRRSetCrtcGammaReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+int (*ProcRandrVector[RRNumberRequests])(ClientPtr) = {
+    ProcRRQueryVersion,	/* 0 */
+/* we skip 1 to make old clients fail pretty immediately */
+    NULL,			/* 1 ProcRandrOldGetScreenInfo */
+/* V1.0 apps share the same set screen config request id */
+    ProcRRSetScreenConfig,	/* 2 */
+    NULL,			/* 3 ProcRandrOldScreenChangeSelectInput */
+/* 3 used to be ScreenChangeSelectInput; deprecated */
+    ProcRRSelectInput,		/* 4 */
+    ProcRRGetScreenInfo,    	/* 5 */
+/* V1.2 additions */
+    ProcRRGetScreenSizeRange,	/* 6 */
+    ProcRRSetScreenSize,	/* 7 */
+    ProcRRGetScreenResources,	/* 8 */
+    ProcRRGetOutputInfo,	/* 9 */
+    ProcRRListOutputProperties,	/* 10 */
+    ProcRRChangeOutputProperty,	/* 11 */
+    ProcRRDeleteOutputProperty,	/* 12 */
+    ProcRRGetOutputProperty,	/* 13 */
+    ProcRRCreateMode,		/* 14 */
+    ProcRRDestroyMode,		/* 15 */
+    ProcRRAddOutputMode,	/* 16 */
+    ProcRRDeleteOutputMode,	/* 17 */
+    ProcRRGetCrtcInfo,		/* 18 */
+    ProcRRSetCrtcConfig,	/* 19 */
+    ProcRRGetCrtcGammaSize,	/* 20 */
+    ProcRRGetCrtcGamma,		/* 21 */
+    ProcRRSetCrtcGamma,		/* 22 */
+};
+
diff --git a/randr/rrmode.c b/randr/rrmode.c
index 1eb53c3..3a9d556 100644
--- a/randr/rrmode.c
+++ b/randr/rrmode.c
@@ -22,7 +22,7 @@
 
 #include "randrstr.h"
 
-static RESTYPE	ModeType;
+RESTYPE	RRModeType;
 
 RRModePtr
 RRModeGet (ScreenPtr	pScreen,
@@ -50,7 +50,7 @@ RRModeGet (ScreenPtr	pScreen,
     memcpy (mode->name, name, modeInfo->nameLength);
     mode->name[modeInfo->nameLength] = '\0';
     mode->id = FakeClientID(0);
-    if (!AddResource (mode->id, ModeType, (pointer) mode))
+    if (!AddResource (mode->id, RRModeType, (pointer) mode))
 	return NULL;
     ++mode->refcnt;
     pScrPriv->changed = TRUE;
@@ -75,11 +75,11 @@ RRModeDestroyResource (pointer value, XID pid)
 Bool
 RRModeInit (void)
 {
-    ModeType = CreateNewResourceType (RRModeDestroyResource);
-    if (!ModeType)
+    RRModeType = CreateNewResourceType (RRModeDestroyResource);
+    if (!RRModeType)
 	return FALSE;
 #ifdef XResExtension
-    RegisterResourceName (ModeType, "MODE");
+    RegisterResourceName (RRModeType, "MODE");
 #endif
     return TRUE;
 }
diff --git a/randr/rroutput.c b/randr/rroutput.c
index c7e7995..6b67f19 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -22,7 +22,124 @@
 
 #include "randrstr.h"
 
-static RESTYPE	OutputType;
+RESTYPE	RROutputType;
+
+/*
+ * Create an output
+ */
+
+RROutputPtr
+RROutputCreate (ScreenPtr   pScreen,
+		char	    *name,
+		int	    nameLength,
+		void	    *devPrivate)
+{
+    rrScrPriv (pScreen);
+    RROutputPtr	output;
+    RROutputPtr	*outputs;
+
+    output = xalloc (sizeof (RROutputRec) + nameLength + 1);
+    if (!output)
+	return NULL;
+    if (pScrPriv->numOutputs)
+	outputs = xrealloc (pScrPriv->outputs, 
+			    (pScrPriv->numOutputs + 1) * sizeof (RROutputPtr));
+    else
+	outputs = xalloc (sizeof (RROutputPtr));
+    if (!outputs)
+    {
+	xfree (output);
+	return NULL;
+    }
+    output->id = FakeClientID (0);
+    output->pScreen = pScreen;
+    output->name = (char *) (output + 1);
+    output->nameLength = nameLength;
+    memcpy (output->name, name, nameLength);
+    output->connection = RR_UnknownConnection;
+    output->subpixelOrder = SubPixelUnknown;
+    output->crtc = NULL;
+    output->numCrtcs = 0;
+    output->crtcs = NULL;
+    output->numClones = 0;
+    output->clones = NULL;
+    output->numModes = 0;
+    output->modes = NULL;
+    output->changed = TRUE;
+    output->devPrivate = devPrivate;
+    pScrPriv->outputs[pScrPriv->numOutputs++] = output;
+    return output;
+}
+
+/*
+ * Notify extension that output parameters have been changed
+ */
+Bool
+RROutputSetClones (RROutputPtr  output,
+		   RROutputPtr  *clones,
+		   int		numClones)
+{
+    RROutputPtr	*newClones;
+
+    newClones = xalloc (numClones * sizeof (RROutputPtr));
+    if (!newClones)
+	return FALSE;
+    if (output->clones)
+	xfree (output->clones);
+    memcpy (newClones, clones, numClones * sizeof (RROutputPtr));
+    output->clones = newClones;
+    output->numClones = numClones;
+    return TRUE;
+}
+
+Bool
+RROutputSetModes (RROutputPtr	output,
+		  RRModePtr	*modes,
+		  int		numModes)
+{
+    RRModePtr	*newModes;
+
+    newModes = xalloc (numModes * sizeof (RRModePtr));
+    if (!newModes)
+	return FALSE;
+    if (output->modes)
+	xfree (output->modes);
+    memcpy (newModes, modes, numModes * sizeof (RRModePtr));
+    output->modes = newModes;
+    output->numModes = numModes;
+    return TRUE;
+}
+
+Bool
+RROutputSetCrtcs (RROutputPtr	output,
+		  RRCrtcPtr	*crtcs,
+		  int		numCrtcs)
+{
+    RRCrtcPtr	*newCrtcs;
+
+    newCrtcs = xalloc (numCrtcs * sizeof (RRCrtcPtr));
+    if (!newCrtcs)
+	return FALSE;
+    if (output->crtcs)
+	xfree (output->crtcs);
+    memcpy (newCrtcs, crtcs, numCrtcs * sizeof (RRCrtcPtr));
+    output->crtcs = newCrtcs;
+    output->numCrtcs = numCrtcs;
+    return TRUE;
+}
+
+Bool
+RROutputSetConnection (RROutputPtr  output,
+		       CARD8	    connection)
+{
+    output->connection = connection;
+    return TRUE;
+}
+
+void
+RRDeliverOutputEvent(ClientPtr client, WindowPtr pWin, RROutputPtr output)
+{
+}
 
 /*
  * Destroy a Output at shutdown
@@ -36,7 +153,28 @@ RROutputDestroy (RROutputPtr crtc)
 static int
 RROutputDestroyResource (pointer value, XID pid)
 {
-    free (value);
+    RROutputPtr	output = (RROutputPtr) value;
+    ScreenPtr	pScreen = output->pScreen;
+    rrScrPriv(pScreen);
+    int		i;
+
+    for (i = 0; i < pScrPriv->numOutputs; i++)
+    {
+	if (pScrPriv->outputs[i] == output)
+	{
+	    memmove (pScrPriv->outputs, pScrPriv->outputs + 1,
+		     (pScrPriv->numOutputs - (i - 1)) * sizeof (RROutputPtr));
+	    --pScrPriv->numOutputs;
+	    break;
+	}
+    }
+    if (output->modes)
+	xfree (output->modes);
+    if (output->crtcs)
+	xfree (output->crtcs);
+    if (output->clones)
+	xfree (output->clones);
+    xfree (output);
     return 1;
 }
 
@@ -46,11 +184,11 @@ RROutputDestroyResource (pointer value, XID pid)
 Bool
 RROutputInit (void)
 {
-    OutputType = CreateNewResourceType (RROutputDestroyResource);
-    if (!OutputType)
+    RROutputType = CreateNewResourceType (RROutputDestroyResource);
+    if (!RROutputType)
 	return FALSE;
 #ifdef XResExtension
-	RegisterResourceName (OutputType, "OUTPUT");
+	RegisterResourceName (RROutputType, "OUTPUT");
 #endif
     return TRUE;
 }
diff --git a/randr/rrsdispatch.c b/randr/rrsdispatch.c
new file mode 100644
index 0000000..bf81f8b
--- /dev/null
+++ b/randr/rrsdispatch.c
@@ -0,0 +1,282 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+
+static int
+SProcRRQueryVersion (ClientPtr client)
+{
+    register int n;
+    REQUEST(xRRQueryVersionReq);
+
+    swaps(&stuff->length, n);
+    swapl(&stuff->majorVersion, n);
+    swapl(&stuff->minorVersion, n);
+    return (*ProcRandrVector[stuff->randrReqType]) (client);
+}
+
+static int
+SProcRRGetScreenInfo (ClientPtr client)
+{
+    register int n;
+    REQUEST(xRRGetScreenInfoReq);
+
+    swaps(&stuff->length, n);
+    swapl(&stuff->window, n);
+    return (*ProcRandrVector[stuff->randrReqType]) (client);
+}
+
+static int
+SProcRRSetScreenConfig (ClientPtr client)
+{
+    register int n;
+    REQUEST(xRRSetScreenConfigReq);
+
+    if (RRClientKnowsRates (client))
+    {
+	REQUEST_SIZE_MATCH (xRRSetScreenConfigReq);
+	swaps (&stuff->rate, n);
+    }
+    else
+    {
+	REQUEST_SIZE_MATCH (xRR1_0SetScreenConfigReq);
+    }
+    
+    swaps(&stuff->length, n);
+    swapl(&stuff->drawable, n);
+    swapl(&stuff->timestamp, n);
+    swaps(&stuff->sizeID, n);
+    swaps(&stuff->rotation, n);
+    return (*ProcRandrVector[stuff->randrReqType]) (client);
+}
+
+static int
+SProcRRSelectInput (ClientPtr client)
+{
+    register int n;
+    REQUEST(xRRSelectInputReq);
+
+    swaps(&stuff->length, n);
+    swapl(&stuff->window, n);
+    return (*ProcRandrVector[stuff->randrReqType]) (client);
+}
+
+static int
+SProcRRGetScreenSizeRange (ClientPtr client)
+{
+    REQUEST(xRRGetScreenSizeRangeReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetScreenSizeRangeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRSetScreenSize (ClientPtr client)
+{
+    REQUEST(xRRSetScreenSizeReq);
+    
+    REQUEST_SIZE_MATCH(xRRSetScreenSizeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRGetScreenResources (ClientPtr client)
+{
+    REQUEST(xRRGetScreenResourcesReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetScreenResourcesReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRGetOutputInfo (ClientPtr client)
+{
+    REQUEST(xRRGetOutputInfoReq);;
+    
+    REQUEST_SIZE_MATCH(xRRGetOutputInfoReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRListOutputProperties (ClientPtr client)
+{
+    REQUEST(xRRListOutputPropertiesReq);
+    
+    REQUEST_SIZE_MATCH(xRRListOutputPropertiesReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRChangeOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRChangeOutputPropertyReq);
+    
+    REQUEST_SIZE_MATCH(xRRChangeOutputPropertyReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRDeleteOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRDeleteOutputPropertyReq);
+    
+    REQUEST_SIZE_MATCH(xRRDeleteOutputPropertyReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRGetOutputProperty (ClientPtr client)
+{
+    REQUEST(xRRGetOutputPropertyReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetOutputPropertyReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRCreateMode (ClientPtr client)
+{
+    REQUEST(xRRCreateModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRCreateModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRDestroyMode (ClientPtr client)
+{
+    REQUEST(xRRDestroyModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRDestroyModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRAddOutputMode (ClientPtr client)
+{
+    REQUEST(xRRAddOutputModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRAddOutputModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRDeleteOutputMode (ClientPtr client)
+{
+    REQUEST(xRRDeleteOutputModeReq);
+    
+    REQUEST_SIZE_MATCH(xRRDeleteOutputModeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRGetCrtcInfo (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcInfoReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetCrtcInfoReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRSetCrtcConfig (ClientPtr client)
+{
+    REQUEST(xRRSetCrtcConfigReq);
+    
+    REQUEST_SIZE_MATCH(xRRSetCrtcConfigReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRGetCrtcGammaSize (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcGammaSizeReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetCrtcGammaSizeReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRGetCrtcGamma (ClientPtr client)
+{
+    REQUEST(xRRGetCrtcGammaReq);
+    
+    REQUEST_SIZE_MATCH(xRRGetCrtcGammaReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+static int
+SProcRRSetCrtcGamma (ClientPtr client)
+{
+    REQUEST(xRRSetCrtcGammaReq);
+    
+    REQUEST_SIZE_MATCH(xRRSetCrtcGammaReq);
+    (void) stuff;
+    return BadImplementation; 
+}
+
+int (*SProcRandrVector[RRNumberRequests])(ClientPtr) = {
+    SProcRRQueryVersion,	/* 0 */
+/* we skip 1 to make old clients fail pretty immediately */
+    NULL,			/* 1 SProcRandrOldGetScreenInfo */
+/* V1.0 apps share the same set screen config request id */
+    SProcRRSetScreenConfig,	/* 2 */
+    NULL,			/* 3 SProcRandrOldScreenChangeSelectInput */
+/* 3 used to be ScreenChangeSelectInput; deprecated */
+    SProcRRSelectInput,		/* 4 */
+    SProcRRGetScreenInfo,    	/* 5 */
+/* V1.2 additions */
+    SProcRRGetScreenSizeRange,	/* 6 */
+    SProcRRSetScreenSize,	/* 7 */
+    SProcRRGetScreenResources,	/* 8 */
+    SProcRRGetOutputInfo,	/* 9 */
+    SProcRRListOutputProperties,/* 10 */
+    SProcRRChangeOutputProperty,/* 11 */
+    SProcRRDeleteOutputProperty,/* 12 */
+    SProcRRGetOutputProperty,	/* 13 */
+    SProcRRCreateMode,		/* 14 */
+    SProcRRDestroyMode,		/* 15 */
+    SProcRRAddOutputMode,	/* 16 */
+    SProcRRDeleteOutputMode,	/* 17 */
+    SProcRRGetCrtcInfo,		/* 18 */
+    SProcRRSetCrtcConfig,	/* 19 */
+    SProcRRGetCrtcGammaSize,	/* 20 */
+    SProcRRGetCrtcGamma,	/* 21 */
+    SProcRRSetCrtcGamma,	/* 22 */
+};
+
commit cbb587582e7669dfa18fdf3bba476bf8f07b4543
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Sat Sep 16 23:21:37 2006 -0700

    Split RandR implementation into separate files.
    
    RandR is getting too big to live in one file; split into one file per object
    type (crtc, mode, screen), leaving the rest of the code in randr.c.
    
    Code is slowly approaching the point where it will drop-in as a replacement
    for the old 1.0 implementation.

diff --git a/randr/Makefile.am b/randr/Makefile.am
index bd30aed..868786e 100644
--- a/randr/Makefile.am
+++ b/randr/Makefile.am
@@ -9,4 +9,8 @@ endif
 librandr_la_SOURCES =	\
 	mirandr.c	\
 	randr.c		\
-	randrstr.h
+	randrstr.h	\
+	rrcrtc.c	\
+	rrmode.c	\
+	rroutput.c	\
+	rrscreen.c
diff --git a/randr/mirandr.c b/randr/mirandr.c
index 5aea38d..a57a157 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -70,16 +70,19 @@ Bool
 miRandRInit (ScreenPtr pScreen)
 {
     rrScrPrivPtr    pScrPriv;
+#if RANDR_12_INTERFACE
     RRModePtr	mode;
     RRCrtcPtr	crtc;
     RROutputPtr	output;
     xRRModeInfo modeInfo;
     char	name[64];
+#endif
     
     if (!RRScreenInit (pScreen))
 	return FALSE;
     pScrPriv = rrGetScrPriv(pScreen);
     pScrPriv->rrGetInfo = miRRGetInfo;
+#if RANDR_12_INTERFACE
     pScrPriv->rrCrtcSet = miRRCrtcSet;
     
     RRScreenSetSizeRange (pScreen,
@@ -111,7 +114,7 @@ miRandRInit (ScreenPtr pScreen)
 		      &crtc, 1, /* crtcs */
 		      RR_Connected))
 	return FALSE;
-    if (!RRCrtcSet (crtc, mode, 0, 0, RR_Rotate_0, 1, &output))
-	return FALSE;
+    RRCrtcNotify (crtc, mode, 0, 0, RR_Rotate_0, 1, &output);
+#endif
     return TRUE;
 }
diff --git a/randr/randr.c b/randr/randr.c
index e34b82c..2305b60 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -31,25 +31,7 @@
 #include <dix-config.h>
 #endif
 
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "misc.h"
-#include "os.h"
-#include "dixstruct.h"
-#include "resource.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "extnsionst.h"
-#include "servermd.h"
-#include <X11/extensions/randr.h>
-#include <X11/extensions/randrproto.h>
 #include "randrstr.h"
-#ifdef RENDER
-#include <X11/extensions/render.h> 	/* we share subpixel order information */
-#include "picturestr.h"
-#endif
-#include <X11/Xfuncproto.h>
 
 /* From render.h */
 #ifndef SubPixelUnknown
@@ -60,8 +42,6 @@
 int	RRGeneration;
 int	RRNScreens;
 
-static RESTYPE	    ModeType, CrtcType, OutputType;
-
 static int ProcRRQueryVersion (ClientPtr pClient);
 static int ProcRRDispatch (ClientPtr pClient);
 static int SProcRRDispatch (ClientPtr pClient);
@@ -80,7 +60,7 @@ static int SProcRRQueryVersion (ClientPtr pClient);
 static CARD8	RRReqCode;
 static int	RRErrBase;
 #endif
-static int	RREventBase;
+int	RREventBase;
 static RESTYPE ClientType, EventType; /* resource types for event masks */
 static int	RRClientPrivateIndex;
 
@@ -233,50 +213,21 @@ SRRNotifyEvent (xEvent *from,
     }
 }
 
-static int
-RRModeDestroyResource (pointer value, XID pid)
-{
-    RRModeDestroy ((RRModePtr) value);
-    return 1;
-}
-
-static int
-RRCrtcDestroyResource (pointer value, XID pid)
-{
-    RRCrtcDestroy ((RRCrtcPtr) value);
-    return 1;
-}
-
-static int
-RROutputDestroyResource (pointer value, XID pid)
-{
-    RROutputDestroy ((RROutputPtr) value);
-    return 1;
-}
-
 Bool RRScreenInit(ScreenPtr pScreen)
 {
     rrScrPrivPtr   pScrPriv;
 
     if (RRGeneration != serverGeneration)
     {
-	ModeType = CreateNewResourceType (RRModeDestroyResource);
-	if (!ModeType)
+	if (!RRModeInit ())
 	    return FALSE;
-	CrtcType = CreateNewResourceType (RRCrtcDestroyResource);
-	if (!ModeType)
+	if (!RRCrtcInit ())
 	    return FALSE;
-	OutputType = CreateNewResourceType (RROutputDestroyResource);
-	if (!ModeType)
+	if (!RROutputInit ())
 	    return FALSE;
 	if ((rrPrivIndex = AllocateScreenPrivateIndex()) < 0)
 	    return FALSE;
 	RRGeneration = serverGeneration;
-#ifdef XResExtension
-	RegisterResourceName (ModeType, "MODE");
-	RegisterResourceName (CrtcType, "CRTC");
-	RegisterResourceName (OutputType, "OUTPUT");
-#endif
     }
 
     pScrPriv = (rrScrPrivPtr) xalloc (sizeof (rrScrPrivRec));
@@ -288,14 +239,23 @@ Bool RRScreenInit(ScreenPtr pScreen)
     /*
      * Calling function best set these function vectors
      */
-    pScrPriv->rrCrtcSet = 0;
     pScrPriv->rrGetInfo = 0;
     pScrPriv->maxWidth = pScrPriv->minWidth = pScreen->width;
     pScrPriv->maxHeight = pScrPriv->minHeight = pScreen->height;
-#ifdef RANDR_SCREEN_INTERFACE    
+    
+#if RANDR_12_INTERFACE
+    pScrPriv->rrCrtcSet = 0;
+#endif
+#if RANDR_10_INTERFACE    
     pScrPriv->rrSetConfig = 0;
+    pScrPriv->rotations = RR_Rotate_0;
     pScrPriv->reqWidth = pScreen->width;
     pScrPriv->reqHeight = pScreen->height;
+    pScrPriv->nSizes = 0;
+    pScrPriv->pSizes = NULL;
+    pScrPriv->rotation = RR_Rotate_0;
+    pScrPriv->rate = 0;
+    pScrPriv->size = 0;
 #endif
     
     /*
@@ -400,61 +360,6 @@ RRExtensionInit (void)
 
     return;
 }
-		
-static void
-DeliverScreenEvent (ClientPtr client, WindowPtr pWin, ScreenPtr pScreen)
-{
-    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);
-    se.timestamp = pScrPriv->lastSetTime.milliseconds;
-    se.sequenceNumber = client->sequence;
-    se.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
-    se.root =  pRoot->drawable.id;
-    se.window = pWin->drawable.id;
-#ifdef RENDER
-    se.subpixelOrder = PictureGetSubpixelOrder (pScreen);
-#else
-    se.subpixelOrder = SubPixelUnknown;
-#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 = mode->mode.mmWidth;
-	se.heightInMillimeters = mode->mode.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;
-    }    
-    WriteEventsToClient (client, 1, (xEvent *) &se);
-}
-
 static void
 DeliverCrtcEvent (ClientPtr client, WindowPtr pWin, RRCrtcPtr crtc)
 {
@@ -485,7 +390,7 @@ TellChanged (WindowPtr pWin, pointer value)
 	    continue;
 
 	if (pRREvent->mask & RRScreenChangeNotifyMask)
-	    DeliverScreenEvent (client, pWin, pScreen);
+	    RRDeliverScreenEvent (client, pWin, pScreen);
 	
 	if (pRREvent->mask & RRCrtcChangeNotifyMask)
 	{
@@ -529,47 +434,6 @@ RRTellChanged (ScreenPtr pScreen)
     }
 }
 
-RRModePtr
-RRModeGet (ScreenPtr	pScreen,
-	   xRRModeInfo	*modeInfo,
-	   char		*name)
-{
-    rrScrPriv (pScreen);
-    int	i;
-    RRModePtr	mode;
-
-    for (i = 0; i < pScrPriv->numModes; i++)
-    {
-	mode = pScrPriv->modes[i];
-	if (!memcmp (modeInfo, &mode->mode, sizeof (xRRModeInfo)) &&
-	    !memcmp (name, mode->name, modeInfo->nameLength))
-	{
-	    ++mode->refcnt;
-	    return mode;
-	}
-    }
-    mode = xalloc (sizeof (RRModeRec) + modeInfo->nameLength + 1);
-    mode->refcnt = 1;
-    mode->mode = *modeInfo;
-    mode->name = (char *) (mode + 1);
-    memcpy (mode->name, name, modeInfo->nameLength);
-    mode->name[modeInfo->nameLength] = '\0';
-    mode->id = FakeClientID(0);
-    if (!AddResource (mode->id, ModeType, (pointer) mode))
-	return NULL;
-    ++mode->refcnt;
-    pScrPriv->changed = TRUE;
-    return mode;
-}
-
-void
-RRModeDestroy (RRModePtr mode)
-{
-    if (--mode->refcnt > 0)
-	return;
-    xfree (mode);
-}
-
 /*
  * Return the first output which is connected to an active CRTC
  * Used in emulating 1.0 behaviour
@@ -594,11 +458,13 @@ RRFirstOutput (ScreenPtr pScreen)
     return NULL;
 }
 
-#ifdef RANDR_SCREEN_INTERFACE
+#ifdef RANDR_10_INTERFACE
 
-static Bool
+static RRModePtr
 RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
 {
+    ScreenPtr	pScreen = output->pScreen;
+    rrScrPriv(pScreen);
     xRRModeInfo	modeInfo;
     char	name[100];
     RRModePtr	mode;
@@ -617,12 +483,15 @@ RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
     modeInfo.dotClock = ((CARD32) size->width * (CARD32) size->width *
 			 (CARD32) refresh);
     modeInfo.nameLength = strlen (name);
-    mode = RRModeGet (output->pScreen, &modeInfo, name);
+    mode = RRModeGet (pScreen, &modeInfo, name);
     if (!mode)
-	return FALSE;
+	return NULL;
     for (i = 0; i < output->numModes; i++)
 	if (output->modes[i] == mode)
-	    return TRUE;
+	{
+	    RRModeDestroy (mode);
+	    return mode;
+	}
     
     if (output->numModes)
 	modes = xrealloc (output->modes, 
@@ -630,11 +499,16 @@ RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
     else
 	modes = xalloc (sizeof (RRModePtr));
     if (!modes)
-	return FALSE;
+    {
+	RRModeDestroy (mode);
+	FreeResource (mode->id, 0);
+	return NULL;
+    }
     modes[output->numModes++] = mode;
     output->modes = modes;
     output->changed = TRUE;
-    return TRUE;
+    pScrPriv->changed = TRUE;
+    return mode;
 }
 
 static void
@@ -643,6 +517,7 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
     rrScrPriv(pScreen);
     RROutputPtr	output = RRFirstOutput (pScreen);
     RRCrtcPtr	crtc;
+    RRModePtr	mode, newMode = NULL;
     int		i;
     CARD16	minWidth = MAXSHORT, minHeight = MAXSHORT;
     CARD16	maxWidth = 0, maxHeight = 0;
@@ -666,11 +541,29 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
 	int		r;
 
 	if (size->nRates)
+	{
 	    for (r = 0; r < size->nRates; r++)
-		RROldModeAdd (output, size, size->pRates[r].rate);
+	    {
+		mode = RROldModeAdd (output, size, size->pRates[r].rate);
+		if (i == pScrPriv->size && 
+		    size->pRates[r].rate == pScrPriv->rate)
+		{
+		    newMode = mode;
+		}
+	    }
+	    xfree (size->pRates);
+	}
 	else
-	    RROldModeAdd (output, size, 0);
+	{
+	    mode = RROldModeAdd (output, size, 0);
+	    if (i == pScrPriv->size)
+		newMode = mode;
+	}
     }
+    if (pScrPriv->nSizes)
+	xfree (pScrPriv->pSizes);
+    pScrPriv->pSizes = NULL;
+    pScrPriv->nSizes = 0;
 	    
     /* find size bounds */
     for (i = 0; i < output->numModes; i++) 
@@ -697,9 +590,17 @@ RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
     if (maxHeight != pScrPriv->maxHeight) {
 	pScrPriv->maxHeight = maxHeight; pScrPriv->changed = TRUE;
     }
+
+    /* notice current mode */
+    if (newMode)
+	RRCrtcSet (output->crtc, newMode, 0, 0, pScrPriv->rotation,
+		   1, &output);
 }
 #endif
 
+/*
+ * Poll the driver for changed information
+ */
 static Bool
 RRGetInfo (ScreenPtr pScreen)
 {
@@ -718,7 +619,7 @@ RRGetInfo (ScreenPtr pScreen)
     if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
 	return FALSE;
 
-#if RANDR_SCREEN_INTERFACE
+#if RANDR_10_INTERFACE
     if (pScrPriv->nSizes)
 	RRScanOldConfig (pScreen, rotations);
 #endif
@@ -726,27 +627,6 @@ RRGetInfo (ScreenPtr pScreen)
     return TRUE;
 }
 
-static void
-RRSendConfigNotify (ScreenPtr pScreen)
-{
-    WindowPtr	pWin = WindowTable[pScreen->myNum];
-    xEvent	event;
-
-    event.u.u.type = ConfigureNotify;
-    event.u.configureNotify.window = pWin->drawable.id;
-    event.u.configureNotify.aboveSibling = None;
-    event.u.configureNotify.x = 0;
-    event.u.configureNotify.y = 0;
-
-    /* XXX xinerama stuff ? */
-    
-    event.u.configureNotify.width = pWin->drawable.width;
-    event.u.configureNotify.height = pWin->drawable.height;
-    event.u.configureNotify.borderWidth = wBorderWidth (pWin);
-    event.u.configureNotify.override = pWin->overrideRedirect;
-    DeliverEvents(pWin, &event, 1, NullWindow);
-}
-
 static int
 ProcRRQueryVersion (ClientPtr client)
 {
@@ -777,50 +657,6 @@ ProcRRQueryVersion (ClientPtr client)
     return (client->noClientException);
 }
 
-
-extern char	*ConnectionInfo;
-
-static int padlength[4] = {0, 3, 2, 1};
-
-static void
-RREditConnectionInfo (ScreenPtr pScreen)
-{
-    xConnSetup	    *connSetup;
-    char	    *vendor;
-    xPixmapFormat   *formats;
-    xWindowRoot	    *root;
-    xDepth	    *depth;
-    xVisualType	    *visual;
-    int		    screen = 0;
-    int		    d;
-
-    connSetup = (xConnSetup *) ConnectionInfo;
-    vendor = (char *) connSetup + sizeof (xConnSetup);
-    formats = (xPixmapFormat *) ((char *) vendor +
-				 connSetup->nbytesVendor +
-				 padlength[connSetup->nbytesVendor & 3]);
-    root = (xWindowRoot *) ((char *) formats +
-			    sizeof (xPixmapFormat) * screenInfo.numPixmapFormats);
-    while (screen != pScreen->myNum)
-    {
-	depth = (xDepth *) ((char *) root + 
-			    sizeof (xWindowRoot));
-	for (d = 0; d < root->nDepths; d++)
-	{
-	    visual = (xVisualType *) ((char *) depth +
-				      sizeof (xDepth));
-	    depth = (xDepth *) ((char *) visual +
-				depth->nVisuals * sizeof (xVisualType));
-	}
-	root = (xWindowRoot *) ((char *) depth);
-	screen++;
-    }
-    root->pixWidth = pScreen->width;
-    root->pixHeight = pScreen->height;
-    root->mmWidth = pScreen->mmWidth;
-    root->mmHeight = pScreen->mmHeight;
-}
-
 typedef struct _RR10Data {
     RRScreenSizePtr sizes;
     int		    nsize;
@@ -829,7 +665,7 @@ typedef struct _RR10Data {
     CARD16	    refresh;
 } RR10DataRec, *RR10DataPtr;
 
-static CARD16
+CARD16
 RRVerticalRefresh (xRRModeInfo *mode)
 {
     CARD32  refresh;
@@ -1056,94 +892,6 @@ ProcRRGetScreenInfo (ClientPtr client)
 }
 
 #if 0
-static int
-RRMonitorSetMode (ScreenPtr pScreen, RRMonitorPtr pMonitor, 
-		  RRModePtr pMode, int x, int y, Rotation rotation,
-		  TimeStamp time)
-{
-    rrScrPriv(pScreen);
-    short   oldWidth, oldHeight;
-    
-    oldWidth = pScreen->width;
-    oldHeight = pScreen->height;
-    
-    /*
-     * call out to ddx routine to effect the change
-     */
-    if (pScrPriv->rrSetScreenSize && pScrPriv->rrSetMode)
-    {
-	xScreenSizes	oldSize;
-	if (!(*pScrPriv->rrSetMode) (pScreen, 0, NULL, 0, 0, RR_Rotate_0))
-	    return RRSetConfigFailed;
-	oldSize.widthInPixels = pScreen->width;
-	oldSize.heightInPixels = pScreen->width;
-	oldSize.widthInMillimeters = pScreen->mmWidth;
-	oldSize.heightInMillimeters = pScreen->mmHeight;
-	if (!(*pScrPriv->rrSetScreenSize) (pScreen,
-					   pMode->mode.width,
-					   pMode->mode.height,
-					   pMode->mode.widthInMillimeters,
-					   pMode->mode.heightInMillimeters))
-	{
-	    (void) (*pScrPriv->rrSetMode) (pScreen, 0, pMonitor->pMode,
-					   pMonitor->x, pMonitor->y,
-					   pMonitor->rotation);
-	    return RRSetConfigFailed;
-	}
-	if (!(*pScrPriv->rrSetMode) (pScreen, 0, pMode, 0, 0, rotation))
-	{
-	    (void) (*pScrPriv->rrSetScreenSize) (pScreen,
-						 oldSize.widthInPixels,
-						 oldSize.heightInPixels,
-						 oldSize.widthInMillimeters,
-						 oldSize.heightInMillimeters);
-	    (void) (*pScrPriv->rrSetMode) (pScreen, 0, pMonitor->pMode,
-					   pMonitor->x, pMonitor->y,
-					   pMonitor->rotation);
-	    return RRSetConfigFailed;
-	}
-    }
-#ifdef RANDR_SCREEN_INTERFACE
-    else if (pScrPriv->rrSetConfig)
-    {
-	int rate = RRVerticalRefresh (&pMode->mode);
-	RRScreenSizeRec	size;
-
-	size.width = pMode->mode.width;
-	size.height = pMode->mode.height;
-	size.mmWidth = pMode->mode.widthInMillimeters;
-	size.mmHeight = pMode->mode.heightInMillimeters;
-	if (!(*pScrPriv->rrSetConfig) (pScreen, rotation, rate, &size))
-	    return RRSetConfigFailed;
-    }
-#endif
-    else
-	return RRSetConfigFailed;
-    
-    /*
-     * set current extension configuration pointers
-     */
-    RRSetCurrentMode (pMonitor, pMode, 0, 0, rotation);
-    
-    /*
-     * Deliver ScreenChangeNotify events whenever
-     * the configuration is updated
-     */
-    WalkTree (pScreen, TellChanged, (pointer) pScreen);
-    
-    /*
-     * Deliver ConfigureNotify events when root changes
-     * pixel size
-     */
-    if (oldWidth != pScreen->width || oldHeight != pScreen->height)
-	RRSendConfigNotify (pScreen);
-    RREditConnectionInfo (pScreen);
-    
-    /*
-     * Fix pointer bounds and location
-     */
-    ScreenRestructured (pScreen);
-    pScrPriv->lastSetTime = time;
     return RRSetConfigSuccess;
 }
 #endif
@@ -1411,36 +1159,6 @@ RRSetScreenConfig (ScreenPtr		pScreen,
 }
 #endif
 
-static Bool
-RRSetScreenSize (ScreenPtr pScreen,
-		 CARD16 width, CARD16 height,
-		 CARD16 widthInMillimeters, CARD16 heightInMillimeters)
-{
-    rrScrPriv(pScreen);
-    
-    if (pScrPriv->rrScreenSetSize) 
-    {
-	return (*pScrPriv->rrScreenSetSize) (pScreen, width, height,
-					     widthInMillimeters,
-					     heightInMillimeters);
-    }
-#ifdef RANDR_SCREEN_INTERFACE
-    else
-    {
-	/* Pend the size change until we get the set mode request.
-	 * Yes, this is 'illegal', but the best we can do until
-	 * drivers are updated
-	 */
-	pScrPriv->reqWidth = width;
-	pScrPriv->reqHeight = height;
-	pScreen->mmWidth = widthInMillimeters;
-	pScreen->mmHeight = heightInMillimeters;
-	return TRUE;
-    }
-#endif
-    return FALSE;
-}
-
 static int
 ProcRRSelectInput (ClientPtr client)
 {
@@ -1524,7 +1242,7 @@ ProcRRSelectInput (ClientPtr client)
 		CompareTimeStamps (pTimes->configTime, 
 				   pScrPriv->lastConfigTime) != 0)
 	    {
-		DeliverScreenEvent (client, pWin, pScreen);
+		RRDeliverScreenEvent (client, pWin, pScreen);
 	    }
 	}
     }
@@ -1651,7 +1369,7 @@ static int ProcRRSetScreenSize (ClientPtr client)
 	client->errorValue = 0;
 	return BadValue;
     }
-    if (!RRSetScreenSize (pScreen, 
+    if (!RRScreenSizeSet (pScreen, 
 			  stuff->width, stuff->height,
 			  stuff->widthInMillimeters,
 			  stuff->heightInMillimeters))
@@ -2000,6 +1718,7 @@ SProcRRDispatch (ClientPtr client)
     }
 }
 
+#if RANDR_12_INTERFACE
 /*
  * Register the range of sizes for the screen
  */
@@ -2019,8 +1738,9 @@ RRScreenSetSizeRange (ScreenPtr	pScreen,
     pScrPriv->maxWidth  = maxWidth;
     pScrPriv->maxHeight = maxHeight;
 }
+#endif
 
-#ifdef RANDR_SCREEN_INTERFACE
+#ifdef RANDR_10_INTERFACE
 
 static Bool
 RRScreenSizeMatches (RRScreenSizePtr  a,
@@ -2052,6 +1772,7 @@ RRRegisterSize (ScreenPtr	    pScreen,
     if (!pScrPriv)
 	return 0;
     
+    tmp.id = 0;
     tmp.width = width;
     tmp.height= height;
     tmp.mmWidth = mmWidth;
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 1694523..f323660 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -32,15 +32,35 @@
 #ifndef _RANDRSTR_H_
 #define _RANDRSTR_H_
 
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include "misc.h"
+#include "os.h"
+#include "dixstruct.h"
+#include "resource.h"
+#include "scrnintstr.h"
+#include "windowstr.h"
+#include "pixmapstr.h"
+#include "extnsionst.h"
+#include "servermd.h"
+#include <X11/extensions/randr.h>
 #include <X11/extensions/randrproto.h>
+#ifdef RENDER
+#include <X11/extensions/render.h> 	/* we share subpixel order information */
+#include "picturestr.h"
+#endif
+#include <X11/Xfuncproto.h>
 
 /* required for ABI compatibility for now */
-#define RANDR_SCREEN_INTERFACE 1
+#define RANDR_10_INTERFACE 1
+/* #define RANDR_12_INTERFACE 1 */
 
 typedef XID	RRMode;
 typedef XID	RROutput;
 typedef XID	RRCrtc;
 
+extern int	RREventBase;
+
 /*
  * Modeline for a monitor. Name follows directly after this struct
  */
@@ -64,9 +84,9 @@ struct _rrCrtc {
     int		    x, y;
     Rotation	    rotation;
     Rotation	    rotations;
-    int		    numPossibleOutputs;
-    RROutputPtr	    *possibleOutputs;
     Bool	    changed;
+    int		    numOutputs;
+    RROutputPtr	    *outputs;
     void	    *devPrivate;
 };
 
@@ -88,11 +108,12 @@ struct _rrOutput {
     void	    *devPrivate;
 };
 
-typedef Bool (*RRScreenSetSizeProcPtr) (ScreenPtr	pScreen,
+#if RANDR_12_INTERFACE
+typedef Bool (*RRScreentSizeSetProcPtr) (ScreenPtr	pScreen,
 					CARD16		width,
 					CARD16		height,
-					CARD32		widthInMM,
-					CARD32		heightInMM);
+					CARD32		mmWidth,
+					CARD32		mmHeight);
 					
 typedef Bool (*RRCrtcSetProcPtr) (ScreenPtr		pScreen,
 				  RRCrtcPtr		crtc,
@@ -100,8 +121,9 @@ typedef Bool (*RRCrtcSetProcPtr) (ScreenPtr		pScreen,
 				  int			x,
 				  int			y,
 				  Rotation		rotation,
-				  int			numOutput,
+				  int			numOutputs,
 				  RROutputPtr		*outputs);
+#endif
 
 typedef Bool (*RRGetInfoProcPtr) (ScreenPtr pScreen, Rotation *rotations);
 typedef Bool (*RRCloseScreenProcPtr) ( int i, ScreenPtr pscreen);
@@ -121,7 +143,7 @@ typedef struct _rrScreenSize {
     RRScreenRatePtr pRates;
 } RRScreenSize, *RRScreenSizePtr;
 
-#ifdef RANDR_SCREEN_INTERFACE
+#ifdef RANDR_10_INTERFACE
 
 typedef Bool (*RRSetConfigProcPtr) (ScreenPtr		pScreen,
 				    Rotation		rotation,
@@ -136,12 +158,14 @@ typedef struct _rrScrPriv {
      * 'public' part of the structure; DDXen fill this in
      * as they initialize
      */
-#ifdef RANDR_SCREEN_INTERFACE
+#if RANDR_10_INTERFACE
     RRSetConfigProcPtr	    rrSetConfig;
 #endif
     RRGetInfoProcPtr	    rrGetInfo;
-    RRScreenSetSizeProcPtr  rrScreenSetSize;
+#if RANDR_12_INTERFACE
+    RRScreenSetSizeProcPtr  rrScreenSizeSet;
     RRCrtcSetProcPtr	    rrCrtcSet;
+#endif
     
     /*
      * Private part of the structure; not considered part of the ABI
@@ -152,6 +176,7 @@ typedef struct _rrScrPriv {
     Bool		    changed;
     CARD16		    minWidth, minHeight;
     CARD16		    maxWidth, maxHeight;
+    CARD16		    width, height;	/* last known screen size */
 
     /* modes, outputs and crtcs */
     int			    numModes;
@@ -163,7 +188,7 @@ typedef struct _rrScrPriv {
     int			    numCrtcs;
     RRCrtcPtr		    *crtcs;
 
-#ifdef RANDR_SCREEN_INTERFACE
+#ifdef RANDR_10_INTERFACE
     /*
      * Configuration information
      */
@@ -173,7 +198,6 @@ typedef struct _rrScrPriv {
     int			    nSizes;
     RRScreenSizePtr	    pSizes;
     
-    RRScreenSizePtr	    pSize;
     Rotation		    rotation;
     int			    rate;
     int			    size;
@@ -190,6 +214,7 @@ extern int rrPrivIndex;
 void
 RRExtensionInit (void);
 
+#ifdef RANDR_12_INTERFACE
 /*
  * Set the range of sizes for the screen
  */
@@ -199,89 +224,34 @@ RRScreenSetSizeRange (ScreenPtr	pScreen,
 		      CARD16	minHeight,
 		      CARD16	maxWidth,
 		      CARD16	maxHeight);
+#endif
 
+/* rrscreen.c */
 /*
- * Create a CRTC
- */
-RRCrtcPtr
-RRCrtcCreate (ScreenPtr	pScreen,
-	      void	*devPrivate);
-
-
-/*
- * Use this value for any num parameter to indicate that
- * the related data are unchanged
- */
-#define RR_NUM_UNCHANGED    -1
-
-/*
- * Notify the extension that the Crtc has been reconfigured
- */
-Bool
-RRCrtcSet (RRCrtcPtr	crtc,
-	   RRModePtr	mode,
-	   int		x,
-	   int		y,
-	   Rotation	rotation,
-	   int		numOutput,
-	   RROutputPtr	*outputs);
-
-/*
- * Destroy a Crtc at shutdown
- */
-void
-RRCrtcDestroy (RRCrtcPtr crtc);
-
-/*
- * Find, and if necessary, create a mode
- */
-
-RRModePtr
-RRModeGet (ScreenPtr	pScreen,
-	   xRRModeInfo	*modeInfo,
-	   char		*name);
-
-/*
- * Destroy a mode.
+ * Notify the extension that the screen size has been changed.
+ * The driver is responsible for calling this whenever it has changed
+ * the size of the screen
  */
-
 void
-RRModeDestroy (RRModePtr mode);
+RRScreenSizeNotify (ScreenPtr	pScreen);
 
 /*
- * Create an output
+ * Request that the screen be resized
  */
-
-RROutputPtr
-RROutputCreate (ScreenPtr   pScreen,
-		char	    *name,
-		int	    nameLength,
-		void	    *devPrivate);
+Bool
+RRScreenSizeSet (ScreenPtr  pScreen,
+		 CARD16	    width,
+		 CARD16	    height,
+		 CARD32	    mmWidth,
+		 CARD32	    mmHeight);
 
 /*
- * Notify extension that output parameters have been changed
+ * Deliver a ScreenNotify event
  */
-Bool
-RROutputSet (RROutputPtr    output,
-	     RROutputPtr    *clones,
-	     int	    numClones,
-	     RRModePtr	    *modes,
-	     int	    numModes,
-	     RRCrtcPtr	    *crtcs,
-	     int	    numCrtcs,
-	     CARD8	    connection);
-
 void
-RROutputDestroy (RROutputPtr	output);
-
-void
-RRTellChanged (ScreenPtr pScreen);
-
-Bool RRScreenInit(ScreenPtr pScreen);
-
-Rotation
-RRGetRotation (ScreenPtr pScreen);
-
+RRDeliverScreenEvent (ClientPtr client, WindowPtr pWin, ScreenPtr pScreen);
+    
+/* mirandr.c */
 Bool
 miRandRInit (ScreenPtr pScreen);
 
@@ -301,7 +271,22 @@ miRRCrtcSet (ScreenPtr	pScreen,
 	     int	numOutput,
 	     RROutputPtr    *outputs);
 
-#ifdef RANDR_SCREEN_INTERFACE					
+/* randr.c */
+/*
+ * Send all pending events
+ */
+void
+RRTellChanged (ScreenPtr pScreen);
+
+Bool RRScreenInit(ScreenPtr pScreen);
+
+Rotation
+RRGetRotation (ScreenPtr pScreen);
+
+CARD16
+RRVerticalRefresh (xRRModeInfo *mode);
+
+#ifdef RANDR_10_INTERFACE					
 /*
  * This is the old interface, deprecated but left
  * around for compatibility
@@ -344,4 +329,122 @@ RRSetScreenConfig (ScreenPtr		pScreen,
 		   RRScreenSizePtr	pSize);
 
 #endif					
+
+/* rrcrtc.c */
+/*
+ * Create a CRTC
+ */
+RRCrtcPtr
+RRCrtcCreate (ScreenPtr	pScreen,
+	      void	*devPrivate);
+
+
+/*
+ * Use this value for any num parameter to indicate that
+ * the related data are unchanged
+ */
+#define RR_NUM_UNCHANGED    -1
+
+/*
+ * Notify the extension that the Crtc has been reconfigured,
+ * the driver calls this whenever it has updated the mode
+ */
+Bool
+RRCrtcNotify (RRCrtcPtr	    crtc,
+	      RRModePtr	    mode,
+	      int	    x,
+	      int	    y,
+	      Rotation	    rotation,
+	      int	    numOutput,
+	      RROutputPtr   *outputs);
+
+/*
+ * Request that the Crtc be reconfigured
+ */
+Bool
+RRCrtcSet (RRCrtcPtr    crtc,
+	   RRModePtr	mode,
+	   int		x,
+	   int		y,
+	   Rotation	rotation,
+	   int		numOutput,
+	   RROutputPtr  *outputs);
+
+/*
+ * Destroy a Crtc at shutdown
+ */
+void
+RRCrtcDestroy (RRCrtcPtr crtc);
+
+/*
+ * Initialize crtc type
+ */
+Bool
+RRCrtcInit (void);
+
+/* rrmode.c */
+/*
+ * Find, and if necessary, create a mode
+ */
+
+RRModePtr
+RRModeGet (ScreenPtr	pScreen,
+	   xRRModeInfo	*modeInfo,
+	   char		*name);
+
+/*
+ * Destroy a mode.
+ */
+
+void
+RRModeDestroy (RRModePtr mode);
+
+/*
+ * Initialize mode type
+ */
+Bool
+RRModeInit (void);
+    
+/* rroutput.c */
+/*
+ * Create an output
+ */
+
+RROutputPtr
+RROutputCreate (ScreenPtr   pScreen,
+		char	    *name,
+		int	    nameLength,
+		void	    *devPrivate);
+
+/*
+ * Notify extension that output parameters have been changed
+ */
+Bool
+RROutputSetClones (RROutputPtr  output,
+		   RROutputPtr  *clones,
+		   int		numClones);
+
+Bool
+RROutputSetModes (RROutputPtr	output,
+		  RRModePtr	*modes,
+		  int		numModes);
+
+Bool
+RROutputSetCrtcs (RROutputPtr	output,
+		  RRCrtcPtr	*crtcs,
+		  int		numCrtcs);
+
+Bool
+RROutputSetConnection (RROutputPtr  output,
+		       CARD8	    connection);
+
+void
+RROutputDestroy (RROutputPtr	output);
+
+/*
+ * Initialize output type
+ */
+Bool
+RROutputInit (void);
+    
 #endif /* _RANDRSTR_H_ */
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
new file mode 100644
index 0000000..cc5b24d
--- /dev/null
+++ b/randr/rrcrtc.c
@@ -0,0 +1,238 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+
+static RESTYPE	CrtcType;
+
+/*
+ * Create a CRTC
+ */
+RRCrtcPtr
+RRCrtcCreate (ScreenPtr	pScreen,
+	      void	*devPrivate)
+{
+    rrScrPriv (pScreen);
+    RRCrtcPtr	crtc;
+    RRCrtcPtr	*crtcs;
+    
+    crtc = xalloc (sizeof (RRCrtcRec));
+    if (!crtc)
+	return NULL;
+    if (pScrPriv->numCrtcs)
+	crtcs = xrealloc (pScrPriv->crtcs, 
+			  (pScrPriv->numCrtcs + 1) * sizeof (RRCrtcPtr));
+    else
+	crtcs = xalloc (sizeof (RRCrtcPtr));
+    if (!crtcs)
+    {
+	xfree (crtc);
+	return NULL;
+    }
+    crtc->id = FakeClientID (0);
+    crtc->pScreen = pScreen;
+    crtc->mode = NULL;
+    crtc->x = 0;
+    crtc->y = 0;
+    crtc->rotation = RR_Rotate_0;
+    crtc->rotations = RR_Rotate_0;
+    crtc->outputs = NULL;
+    crtc->numOutputs = 0;
+    crtc->changed = TRUE;
+    crtc->devPrivate = devPrivate;
+    pScrPriv->crtcs[pScrPriv->numCrtcs++] = crtc;
+    return crtc;
+}
+
+/*
+ * Notify the extension that the Crtc has been reconfigured,
+ * the driver calls this whenever it has updated the mode
+ */
+Bool
+RRCrtcNotify (RRCrtcPtr	    crtc,
+	      RRModePtr	    mode,
+	      int	    x,
+	      int	    y,
+	      Rotation	    rotation,
+	      int	    numOutputs,
+	      RROutputPtr   *outputs)
+{
+    ScreenPtr	pScreen = crtc->pScreen;
+    rrScrPriv(pScreen);
+    int	    i, j;
+    int	    prevNumOutputs = crtc->numOutputs;
+    
+    if (numOutputs != prevNumOutputs)
+    {
+	RROutputPtr *outputs;
+	
+	if (crtc->numOutputs)
+	    outputs = xrealloc (crtc->outputs,
+				numOutputs * sizeof (RROutputPtr));
+	else
+	    outputs = xalloc (numOutputs * sizeof (RROutputPtr));
+	if (!outputs)
+	    return FALSE;
+	crtc->outputs = outputs;
+    }
+    for (i = 0; i < numOutputs; i++)
+    {
+	for (j = 0; j < crtc->numOutputs; j++)
+	    if (outputs[i] == crtc->outputs[j])
+		break;
+	if (j != crtc->numOutputs)
+	{
+	    outputs[i]->changed = TRUE;
+	    crtc->changed = TRUE;
+	}
+    }
+    for (j = 0; j < crtc->numOutputs; j++)
+    {
+	for (i = 0; i < numOutputs; i++)
+	    if (outputs[i] == crtc->outputs[j])
+		break;
+	if (i != numOutputs)
+	{
+	    crtc->outputs[j]->changed = TRUE;
+	    crtc->changed = TRUE;
+	}
+    }
+    if (mode != crtc->mode)
+    {
+	if (crtc->mode)
+	    RRModeDestroy (crtc->mode);
+	crtc->mode = mode;
+	mode->refcnt++;
+	crtc->changed = TRUE;
+    }
+    if (x != crtc->x)
+    {
+	crtc->x = x;
+	crtc->changed = TRUE;
+    }
+    if (y != crtc->y)
+    {
+	crtc->y = y;
+	crtc->changed = TRUE;
+    }
+    if (rotation != crtc->rotation)
+    {
+	crtc->rotation = rotation;
+	crtc->changed = TRUE;
+    }
+    if (crtc->changed)
+	pScrPriv->changed = TRUE;
+    return TRUE;
+}
+
+/*
+ * Request that the Crtc be reconfigured
+ */
+Bool
+RRCrtcSet (RRCrtcPtr    crtc,
+	   RRModePtr	mode,
+	   int		x,
+	   int		y,
+	   Rotation	rotation,
+	   int		numOutputs,
+	   RROutputPtr  *outputs)
+{
+    ScreenPtr	pScreen = crtc->pScreen;
+    rrScrPriv(pScreen);
+
+#if RANDR_12_INTERFACE
+    if (pScrPriv->rrCrtcSet)
+    {
+	return (*pScrPriv->rrCrtcSet) (pScreen, crtc, mode, x, y, 
+				       rotation, numOutputs, outputs);
+    }
+#endif
+#if RANDR_10_INTERFACE
+    if (pScrPriv->rrSetConfig)
+    {
+	RRScreenSize	    size;
+	RRScreenRate	    rate;
+	Bool		    ret;
+
+	size.width = mode->mode.width;
+	size.height = mode->mode.height;
+	size.mmWidth = mode->mode.mmWidth;
+	size.mmHeight = mode->mode.mmHeight;
+	size.nRates = 1;
+	rate.rate = RRVerticalRefresh (&mode->mode);
+	size.pRates = &rate;
+	ret = (*pScrPriv->rrSetConfig) (pScreen, rotation, rate.rate, &size);
+	/*
+	 * Old 1.0 interface tied screen size to mode size
+	 */
+	if (ret)
+	    RRScreenSizeNotify (pScreen);
+	return ret;
+    }
+#endif
+    return FALSE;
+}
+
+/*
+ * Destroy a Crtc at shutdown
+ */
+void
+RRCrtcDestroy (RRCrtcPtr crtc)
+{
+    FreeResource (crtc->id, 0);
+}
+
+static int
+RRCrtcDestroyResource (pointer value, XID pid)
+{
+    RRCrtcPtr	crtc = (RRCrtcPtr) value;
+    ScreenPtr	pScreen = crtc->pScreen;
+    rrScrPriv(pScreen);
+    int		i;
+
+    for (i = 0; i < pScrPriv->numCrtcs; i++)
+    {
+	if (pScrPriv->crtcs[i] == crtc)
+	{
+	    memmove (pScrPriv->crtcs, pScrPriv->crtcs + 1,
+		     (pScrPriv->numCrtcs - (i - 1)) * sizeof (RRCrtcPtr));
+	    --pScrPriv->numCrtcs;
+	}
+    }
+    free (value);
+    return 1;
+}
+
+/*
+ * Initialize crtc type
+ */
+Bool
+RRCrtcInit (void)
+{
+    CrtcType = CreateNewResourceType (RRCrtcDestroyResource);
+    if (!CrtcType)
+	return FALSE;
+#ifdef XResExtension
+	RegisterResourceName (CrtcType, "CRTC");
+#endif
+    return TRUE;
+}
diff --git a/randr/rrmode.c b/randr/rrmode.c
new file mode 100644
index 0000000..1eb53c3
--- /dev/null
+++ b/randr/rrmode.c
@@ -0,0 +1,85 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+
+static RESTYPE	ModeType;
+
+RRModePtr
+RRModeGet (ScreenPtr	pScreen,
+	   xRRModeInfo	*modeInfo,
+	   char		*name)
+{
+    rrScrPriv (pScreen);
+    int	i;
+    RRModePtr	mode;
+
+    for (i = 0; i < pScrPriv->numModes; i++)
+    {
+	mode = pScrPriv->modes[i];
+	if (!memcmp (modeInfo, &mode->mode, sizeof (xRRModeInfo)) &&
+	    !memcmp (name, mode->name, modeInfo->nameLength))
+	{
+	    ++mode->refcnt;
+	    return mode;
+	}
+    }
+    mode = xalloc (sizeof (RRModeRec) + modeInfo->nameLength + 1);
+    mode->refcnt = 1;
+    mode->mode = *modeInfo;
+    mode->name = (char *) (mode + 1);
+    memcpy (mode->name, name, modeInfo->nameLength);
+    mode->name[modeInfo->nameLength] = '\0';
+    mode->id = FakeClientID(0);
+    if (!AddResource (mode->id, ModeType, (pointer) mode))
+	return NULL;
+    ++mode->refcnt;
+    pScrPriv->changed = TRUE;
+    return mode;
+}
+
+void
+RRModeDestroy (RRModePtr mode)
+{
+    if (--mode->refcnt > 0)
+	return;
+    xfree (mode);
+}
+
+static int
+RRModeDestroyResource (pointer value, XID pid)
+{
+    RRModeDestroy ((RRModePtr) value);
+    return 1;
+}
+
+Bool
+RRModeInit (void)
+{
+    ModeType = CreateNewResourceType (RRModeDestroyResource);
+    if (!ModeType)
+	return FALSE;
+#ifdef XResExtension
+    RegisterResourceName (ModeType, "MODE");
+#endif
+    return TRUE;
+}
diff --git a/randr/rroutput.c b/randr/rroutput.c
new file mode 100644
index 0000000..c7e7995
--- /dev/null
+++ b/randr/rroutput.c
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+
+static RESTYPE	OutputType;
+
+/*
+ * Destroy a Output at shutdown
+ */
+void
+RROutputDestroy (RROutputPtr crtc)
+{
+    FreeResource (crtc->id, 0);
+}
+
+static int
+RROutputDestroyResource (pointer value, XID pid)
+{
+    free (value);
+    return 1;
+}
+
+/*
+ * Initialize crtc type
+ */
+Bool
+RROutputInit (void)
+{
+    OutputType = CreateNewResourceType (RROutputDestroyResource);
+    if (!OutputType)
+	return FALSE;
+#ifdef XResExtension
+	RegisterResourceName (OutputType, "OUTPUT");
+#endif
+    return TRUE;
+}
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
new file mode 100644
index 0000000..47ba12d
--- /dev/null
+++ b/randr/rrscreen.c
@@ -0,0 +1,205 @@
+/*
+ * 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.
+ */
+
+#include "randrstr.h"
+
+extern char	*ConnectionInfo;
+
+static int padlength[4] = {0, 3, 2, 1};
+
+/*
+ * Edit connection information block so that new clients
+ * see the current screen size on connect
+ */
+static void
+RREditConnectionInfo (ScreenPtr pScreen)
+{
+    xConnSetup	    *connSetup;
+    char	    *vendor;
+    xPixmapFormat   *formats;
+    xWindowRoot	    *root;
+    xDepth	    *depth;
+    xVisualType	    *visual;
+    int		    screen = 0;
+    int		    d;
+
+    connSetup = (xConnSetup *) ConnectionInfo;
+    vendor = (char *) connSetup + sizeof (xConnSetup);
+    formats = (xPixmapFormat *) ((char *) vendor +
+				 connSetup->nbytesVendor +
+				 padlength[connSetup->nbytesVendor & 3]);
+    root = (xWindowRoot *) ((char *) formats +
+			    sizeof (xPixmapFormat) * screenInfo.numPixmapFormats);
+    while (screen != pScreen->myNum)
+    {
+	depth = (xDepth *) ((char *) root + 
+			    sizeof (xWindowRoot));
+	for (d = 0; d < root->nDepths; d++)
+	{
+	    visual = (xVisualType *) ((char *) depth +
+				      sizeof (xDepth));
+	    depth = (xDepth *) ((char *) visual +
+				depth->nVisuals * sizeof (xVisualType));
+	}
+	root = (xWindowRoot *) ((char *) depth);
+	screen++;
+    }
+    root->pixWidth = pScreen->width;
+    root->pixHeight = pScreen->height;
+    root->mmWidth = pScreen->mmWidth;
+    root->mmHeight = pScreen->mmHeight;
+}
+
+static void
+RRSendConfigNotify (ScreenPtr pScreen)
+{
+    WindowPtr	pWin = WindowTable[pScreen->myNum];
+    xEvent	event;
+
+    event.u.u.type = ConfigureNotify;
+    event.u.configureNotify.window = pWin->drawable.id;
+    event.u.configureNotify.aboveSibling = None;
+    event.u.configureNotify.x = 0;
+    event.u.configureNotify.y = 0;
+
+    /* XXX xinerama stuff ? */
+    
+    event.u.configureNotify.width = pWin->drawable.width;
+    event.u.configureNotify.height = pWin->drawable.height;
+    event.u.configureNotify.borderWidth = wBorderWidth (pWin);
+    event.u.configureNotify.override = pWin->overrideRedirect;
+    DeliverEvents(pWin, &event, 1, NullWindow);
+}
+
+void
+RRDeliverScreenEvent (ClientPtr client, WindowPtr pWin, ScreenPtr pScreen)
+{
+    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);
+    se.timestamp = pScrPriv->lastSetTime.milliseconds;
+    se.sequenceNumber = client->sequence;
+    se.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
+    se.root =  pRoot->drawable.id;
+    se.window = pWin->drawable.id;
+#ifdef RENDER
+    se.subpixelOrder = PictureGetSubpixelOrder (pScreen);
+#else
+    se.subpixelOrder = SubPixelUnknown;
+#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 = mode->mode.mmWidth;
+	se.heightInMillimeters = mode->mode.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;
+    }    
+    WriteEventsToClient (client, 1, (xEvent *) &se);
+}
+
+/*
+ * Notify the extension that the screen size has been changed.
+ * The driver is responsible for calling this whenever it has changed
+ * the size of the screen
+ */
+void
+RRScreenSizeNotify (ScreenPtr	pScreen)
+{
+    rrScrPriv(pScreen);
+    /*
+     * Deliver ConfigureNotify events when root changes
+     * pixel size
+     */
+    if (pScrPriv->width == pScreen->width &&
+	pScrPriv->height == pScreen->height)
+	return;
+    
+    pScrPriv->width = pScreen->width;
+    pScrPriv->height = pScreen->height;
+    pScrPriv->changed = TRUE;
+
+    RRSendConfigNotify (pScreen);
+    RREditConnectionInfo (pScreen);
+    
+    /*
+     * Fix pointer bounds and location
+     */
+    ScreenRestructured (pScreen);
+}
+
+/*
+ * Request that the screen be resized
+ */
+Bool
+RRScreenSizeSet (ScreenPtr  pScreen,
+		 CARD16	    width,
+		 CARD16	    height,
+		 CARD32	    mmWidth,
+		 CARD32	    mmHeight)
+{
+    rrScrPriv(pScreen);
+
+#if RANDR_12_INTERFACE
+    if (pScrPriv->rrScreenSizeSet)
+    {
+	return (*pScrPriv->rrScreenSizeSet) (pScreen,
+					     width, height,
+					     mmWidth, mmHeight);
+    }
+#endif
+#if RANDR_10_INTERFACE
+    if (pScrPriv->rrSetConfig)
+    {
+	return TRUE;	/* can't set size separately */
+    }
+#endif
+    return FALSE;
+}
+
commit d7f1f286b7b034827956c857f8f2effbc161e5b2
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Sat Sep 16 21:44:42 2006 -0700

    Start moving to new randr 1.2 definition

diff --git a/randr/mirandr.c b/randr/mirandr.c
index e152133..5aea38d 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -34,51 +34,9 @@
 #include "randrstr.h"
 #include <stdio.h>
 
-/*
- * This function assumes that only a single depth can be
- * displayed at a time, but that all visuals of that depth
- * can be displayed simultaneously.  It further assumes that
- * only a single size is available.  Hardware providing
- * additional capabilties should use different code.
- * XXX what to do here....
- */
-
 Bool
 miRRGetInfo (ScreenPtr pScreen, Rotation *rotations)
 {
-    int	i;
-    Bool setConfig = FALSE;
-    RRMonitorPtr pMonitor;
-    
-    pMonitor = RRRegisterMonitor (pScreen, NULL, RR_Rotate_0);
-    for (i = 0; i < pScreen->numDepths; i++)
-    {
-	if (pScreen->allowedDepths[i].numVids)
-	{
-	    xRRMonitorMode		rrMode;
-	    RRModePtr			pMode;
-	    char			name[64];
-
-	    sprintf (name, "%dx%d", pScreen->width, pScreen->height);
-	    memset (&rrMode, '\0', sizeof (rrMode));
-	    rrMode.width = pScreen->width;
-	    rrMode.height = pScreen->height;
-	    rrMode.widthInMillimeters = pScreen->mmWidth;
-	    rrMode.heightInMillimeters = pScreen->mmHeight;
-	    rrMode.nameLength = strlen (name);
-	    pMonitor = RRRegisterMonitor (pScreen, NULL, RR_Rotate_0);
-	    pMode = RRRegisterMode (pMonitor,
-				    &rrMode,
-				    name);
-	    if (!pMode)
-		return FALSE;
-	    if (!setConfig)
-	    {
-		RRSetCurrentMode (pMonitor, pMode, 0, 0, RR_Rotate_0);
-		setConfig = TRUE;
-	    }
-	}
-    }
     return TRUE;
 }
 
@@ -87,26 +45,73 @@ miRRGetInfo (ScreenPtr pScreen, Rotation *rotations)
  * different here
  */
 Bool
-miRRSetMode (ScreenPtr	pScreen,
-	     int	monitor,
-	     RRModePtr	pMode,
+miRRCrtcSet (ScreenPtr	pScreen,
+	     RRCrtcPtr	crtc,
+	     RRModePtr	mode,
 	     int	x,
 	     int	y,
-	     Rotation	rotation)
+	     Rotation	rotation,
+	     int	numOutput,
+	     RROutputPtr    *outputs)
 {
     return TRUE;
 }
 
+/*
+ * This function assumes that only a single depth can be
+ * displayed at a time, but that all visuals of that depth
+ * can be displayed simultaneously.  It further assumes that
+ * only a single size is available.  Hardware providing
+ * additional capabilties should use different code.
+ * XXX what to do here....
+ */
 
 Bool
 miRandRInit (ScreenPtr pScreen)
 {
-    rrScrPrivPtr    rp;
+    rrScrPrivPtr    pScrPriv;
+    RRModePtr	mode;
+    RRCrtcPtr	crtc;
+    RROutputPtr	output;
+    xRRModeInfo modeInfo;
+    char	name[64];
     
     if (!RRScreenInit (pScreen))
 	return FALSE;
-    rp = rrGetScrPriv(pScreen);
-    rp->rrGetInfo = miRRGetInfo;
-    rp->rrSetMode = miRRSetMode;
+    pScrPriv = rrGetScrPriv(pScreen);
+    pScrPriv->rrGetInfo = miRRGetInfo;
+    pScrPriv->rrCrtcSet = miRRCrtcSet;
+    
+    RRScreenSetSizeRange (pScreen,
+			  pScreen->width, pScreen->height,
+			  pScreen->width, pScreen->height);
+
+    sprintf (name, "%dx%d", pScreen->width, pScreen->height);
+    memset (&modeInfo, '\0', sizeof (modeInfo));
+    modeInfo.width = pScreen->width;
+    modeInfo.height = pScreen->height;
+    modeInfo.mmWidth = pScreen->mmWidth;
+    modeInfo.mmHeight = pScreen->mmHeight;
+    modeInfo.nameLength = strlen (name);
+    
+    mode = RRModeGet (pScreen, &modeInfo, name);
+    if (!mode)
+	return FALSE;
+    
+    crtc = RRCrtcCreate (pScreen, NULL);
+    if (!crtc)
+	return FALSE;
+    
+    output = RROutputCreate (pScreen, "screen", 6, NULL);
+    if (!output)
+	return FALSE;
+    if (!RROutputSet (output, 
+		      NULL, 0,  /* clones */
+		      &mode, 1, /* modes */
+		      &crtc, 1, /* crtcs */
+		      RR_Connected))
+	return FALSE;
+    if (!RRCrtcSet (crtc, mode, 0, 0, RR_Rotate_0, 1, &output))
+	return FALSE;
     return TRUE;
 }
diff --git a/randr/randr.c b/randr/randr.c
index 58d8f17..e34b82c 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -60,6 +60,8 @@
 int	RRGeneration;
 int	RRNScreens;
 
+static RESTYPE	    ModeType, CrtcType, OutputType;
+
 static int ProcRRQueryVersion (ClientPtr pClient);
 static int ProcRRDispatch (ClientPtr pClient);
 static int SProcRRDispatch (ClientPtr pClient);
@@ -160,21 +162,16 @@ static Bool
 RRCloseScreen (int i, ScreenPtr pScreen)
 {
     rrScrPriv(pScreen);
-    RRMonitorPtr    pMonitor;
+    int		    j;
 
     unwrap (pScrPriv, pScreen, CloseScreen);
-    while ((pMonitor = pScrPriv->pMonitors))
-    {
-	RRModePtr   pMode;
-	
-	pScrPriv->pMonitors = pMonitor->next;
-	while ((pMode = pMonitor->pModes))
-	{
-	    pMonitor->pModes = pMode->next;
-	    xfree (pMode);
-	}
-	xfree (pMonitor);
-    }
+    for (j = pScrPriv->numCrtcs - 1; j >= 0; j--)
+	RRCrtcDestroy (pScrPriv->crtcs[j]);
+    for (j = pScrPriv->numOutputs - 1; j >= 0; j--)
+	RROutputDestroy (pScrPriv->outputs[j]);
+    for (j = pScrPriv->numModes - 1; j >= 0; j--)
+	RRModeDestroy (pScrPriv->modes[j]);
+    
     xfree (pScrPriv);
     RRNScreens -= 1;	/* ok, one fewer screen with RandR running */
     return (*pScreen->CloseScreen) (i, pScreen);    
@@ -199,6 +196,7 @@ SRRScreenChangeNotifyEvent(xRRScreenChangeNotifyEvent *from,
     cpswaps(from->subpixelOrder, to->subpixelOrder);
 }
 
+#if 0
 static void
 SRRMonitorChangeNotifyEvent(xRRMonitorChangeNotifyEvent *from,
 			    xRRMonitorChangeNotifyEvent *to)
@@ -217,30 +215,68 @@ SRRMonitorChangeNotifyEvent(xRRMonitorChangeNotifyEvent *from,
     cpswaps(from->x, to->x);
     cpswaps(from->y, to->y);
 }
+#endif
 
 static void
 SRRNotifyEvent (xEvent *from,
 		xEvent *to)
 {
     switch (from->u.u.detail) {
+#if 0
     case RRNotify_MonitorChange:
 	SRRMonitorChangeNotifyEvent ((xRRMonitorChangeNotifyEvent *) from,
 				     (xRRMonitorChangeNotifyEvent *) to);
 	break;
+#endif
     default:
 	break;
     }
 }
 
+static int
+RRModeDestroyResource (pointer value, XID pid)
+{
+    RRModeDestroy ((RRModePtr) value);
+    return 1;
+}
+
+static int
+RRCrtcDestroyResource (pointer value, XID pid)
+{
+    RRCrtcDestroy ((RRCrtcPtr) value);
+    return 1;
+}
+
+static int
+RROutputDestroyResource (pointer value, XID pid)
+{
+    RROutputDestroy ((RROutputPtr) value);
+    return 1;
+}
+
 Bool RRScreenInit(ScreenPtr pScreen)
 {
     rrScrPrivPtr   pScrPriv;
 
     if (RRGeneration != serverGeneration)
     {
+	ModeType = CreateNewResourceType (RRModeDestroyResource);
+	if (!ModeType)
+	    return FALSE;
+	CrtcType = CreateNewResourceType (RRCrtcDestroyResource);
+	if (!ModeType)
+	    return FALSE;
+	OutputType = CreateNewResourceType (RROutputDestroyResource);
+	if (!ModeType)
+	    return FALSE;
 	if ((rrPrivIndex = AllocateScreenPrivateIndex()) < 0)
 	    return FALSE;
 	RRGeneration = serverGeneration;
+#ifdef XResExtension
+	RegisterResourceName (ModeType, "MODE");
+	RegisterResourceName (CrtcType, "CRTC");
+	RegisterResourceName (OutputType, "OUTPUT");
+#endif
     }
 
     pScrPriv = (rrScrPrivPtr) xalloc (sizeof (rrScrPrivRec));
@@ -252,10 +288,14 @@ Bool RRScreenInit(ScreenPtr pScreen)
     /*
      * Calling function best set these function vectors
      */
-    pScrPriv->rrSetMode = 0;
+    pScrPriv->rrCrtcSet = 0;
     pScrPriv->rrGetInfo = 0;
+    pScrPriv->maxWidth = pScrPriv->minWidth = pScreen->width;
+    pScrPriv->maxHeight = pScrPriv->minHeight = pScreen->height;
 #ifdef RANDR_SCREEN_INTERFACE    
     pScrPriv->rrSetConfig = 0;
+    pScrPriv->reqWidth = pScreen->width;
+    pScrPriv->reqHeight = pScreen->height;
 #endif
     
     /*
@@ -268,7 +308,12 @@ Bool RRScreenInit(ScreenPtr pScreen)
     
     wrap (pScrPriv, pScreen, CloseScreen, RRCloseScreen);
 
-    pScrPriv->pMonitors = NULL;
+    pScrPriv->numModes = 0;
+    pScrPriv->modes = NULL;
+    pScrPriv->numOutputs = 0;
+    pScrPriv->outputs = NULL;
+    pScrPriv->numCrtcs = 0;
+    pScrPriv->crtcs = NULL;
     
     RRNScreens += 1;	/* keep count of screens that implement randr */
     return TRUE;
@@ -356,18 +401,77 @@ RRExtensionInit (void)
     return;
 }
 		
+static void
+DeliverScreenEvent (ClientPtr client, WindowPtr pWin, ScreenPtr pScreen)
+{
+    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);
+    se.timestamp = pScrPriv->lastSetTime.milliseconds;
+    se.sequenceNumber = client->sequence;
+    se.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
+    se.root =  pRoot->drawable.id;
+    se.window = pWin->drawable.id;
+#ifdef RENDER
+    se.subpixelOrder = PictureGetSubpixelOrder (pScreen);
+#else
+    se.subpixelOrder = SubPixelUnknown;
+#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 = mode->mode.mmWidth;
+	se.heightInMillimeters = mode->mode.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;
+    }    
+    WriteEventsToClient (client, 1, (xEvent *) &se);
+}
+
+static void
+DeliverCrtcEvent (ClientPtr client, WindowPtr pWin, RRCrtcPtr crtc)
+{
+}
+
+static void
+DeliverOutputEvent (ClientPtr client, WindowPtr pWin, RROutputPtr output)
+{
+}
+
 static int
 TellChanged (WindowPtr pWin, pointer value)
 {
     RREventPtr			*pHead, pRREvent;
     ClientPtr			client;
-    xRRScreenChangeNotifyEvent	se;
-    xRRMonitorChangeNotifyEvent	me;
     ScreenPtr			pScreen = pWin->drawable.pScreen;
     rrScrPriv(pScreen);
-    RRModePtr			pMode;
-    RRMonitorPtr		pMonitor;
-    WindowPtr			pRoot = WindowTable[pScreen->myNum];
     int				i;
 
     pHead = (RREventPtr *) LookupIDByType (pWin->drawable.id, EventType);
@@ -380,192 +484,245 @@ TellChanged (WindowPtr pWin, pointer value)
 	if (client == serverClient || client->clientGone)
 	    continue;
 
-	if (pRREvent->mask & RRMonitorChangeNotifyMask)
+	if (pRREvent->mask & RRScreenChangeNotifyMask)
+	    DeliverScreenEvent (client, pWin, pScreen);
+	
+	if (pRREvent->mask & RRCrtcChangeNotifyMask)
 	{
-	    me.type = RRNotify + RREventBase;
-	    me.subCode = RRNotify_MonitorChange;
-	    me.timestamp = pScrPriv->lastSetTime.milliseconds;
-	    me.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
-	    me.root =  pRoot->drawable.id;
-	    me.window = pWin->drawable.id;
-#ifdef RENDER
-	    me.subpixelOrder = PictureGetSubpixelOrder (pScreen);
-#else
-	    me.subpixelOrder = SubPixelUnknown;
-#endif
-	    for (pMonitor = pScrPriv->pMonitors, i = 0; 
-		 pMonitor; 
-		 pMonitor = pMonitor->next, i++)
+	    for (i = 0; i < pScrPriv->numCrtcs; i++)
 	    {
-		me.monitor = i;
-		if (pMonitor->pMode) {
-		    me.modeID = pMonitor->pMode->id;
-		    me.rotation = pMonitor->rotation;
-		    me.x = pMonitor->x;
-		    me.y = pMonitor->y;
-		} else {
-		    me.modeID = 0xffff;
-		    me.rotation = RR_Rotate_0;
-		    me.x = 0;
-		    me.y = 0;
-		}
-		WriteEventsToClient (client, 1, (xEvent *) &me);
+		RRCrtcPtr   crtc = pScrPriv->crtcs[i];
+		if (crtc->changed)
+		    DeliverCrtcEvent (client, pWin, crtc);
 	    }
 	}
-	if ((pRREvent->mask & RRScreenChangeNotifyMask) &&
-	    (pMonitor = pScrPriv->pMonitors))
+	
+	if (pRREvent->mask & RROutputChangeNotifyMask)
 	{
-	    se.type = RRScreenChangeNotify + RREventBase;
-	    se.rotation = (CARD8) pMonitor->rotation;
-	    se.timestamp = pScrPriv->lastSetTime.milliseconds;
-	    se.sequenceNumber = client->sequence;
-	    se.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
-	    se.root =  pRoot->drawable.id;
-	    se.window = pWin->drawable.id;
-#ifdef RENDER
-	    se.subpixelOrder = PictureGetSubpixelOrder (pScreen);
-#else
-	    se.subpixelOrder = SubPixelUnknown;
-#endif
-
-	    pMonitor = &pScrPriv->pMonitors[0];
-	    se.sequenceNumber = client->sequence;
-	    if (pMonitor->pMode) 
+	    for (i = 0; i < pScrPriv->numOutputs; i++)
 	    {
-		pMode = pMonitor->pMode;
-		se.sizeID = pMode->id;
-		se.widthInPixels = pMode->mode.width;
-		se.heightInPixels = pMode->mode.height;
-		se.widthInMillimeters = pMode->mode.widthInMillimeters;
-		se.heightInMillimeters = pMode->mode.heightInMillimeters;
+		RROutputPtr   output = pScrPriv->outputs[i];
+		if (output->changed)
+		    DeliverOutputEvent (client, pWin, output);
 	    }
-	    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;
-	    }    
-	    WriteEventsToClient (client, 1, (xEvent *) &se);
 	}
     }
     return WT_WALKCHILDREN;
 }
 
-static void
-RRFreeMode (RRModePtr pMode)
+void
+RRTellChanged (ScreenPtr pScreen)
 {
-    xfree (pMode);
+    rrScrPriv (pScreen);
+    int i;
+    
+    if (pScrPriv->changed)
+    {
+	UpdateCurrentTime ();
+	pScrPriv->lastConfigTime = currentTime;
+	WalkTree (pScreen, TellChanged, (pointer) pScreen);
+	pScrPriv->changed = FALSE;
+	for (i = 0; i < pScrPriv->numOutputs; i++)
+	    pScrPriv->outputs[i]->changed = FALSE;
+	for (i = 0; i < pScrPriv->numCrtcs; i++)
+	    pScrPriv->crtcs[i]->changed = FALSE;
+    }
 }
 
-static void
-RRFreeModes (RRModePtr pHead)
+RRModePtr
+RRModeGet (ScreenPtr	pScreen,
+	   xRRModeInfo	*modeInfo,
+	   char		*name)
 {
-    RRModePtr	pMode;
-    while ((pMode = pHead)) 
+    rrScrPriv (pScreen);
+    int	i;
+    RRModePtr	mode;
+
+    for (i = 0; i < pScrPriv->numModes; i++)
     {
-	pHead = pMode->next;
-	RRFreeMode (pMode);
+	mode = pScrPriv->modes[i];
+	if (!memcmp (modeInfo, &mode->mode, sizeof (xRRModeInfo)) &&
+	    !memcmp (name, mode->name, modeInfo->nameLength))
+	{
+	    ++mode->refcnt;
+	    return mode;
+	}
     }
+    mode = xalloc (sizeof (RRModeRec) + modeInfo->nameLength + 1);
+    mode->refcnt = 1;
+    mode->mode = *modeInfo;
+    mode->name = (char *) (mode + 1);
+    memcpy (mode->name, name, modeInfo->nameLength);
+    mode->name[modeInfo->nameLength] = '\0';
+    mode->id = FakeClientID(0);
+    if (!AddResource (mode->id, ModeType, (pointer) mode))
+	return NULL;
+    ++mode->refcnt;
+    pScrPriv->changed = TRUE;
+    return mode;
 }
 
-static void
-RRFreeMonitor (RRMonitorPtr pMonitor)
+void
+RRModeDestroy (RRModePtr mode)
 {
-    RRFreeModes (pMonitor->pModes);
-    xfree (pMonitor);
+    if (--mode->refcnt > 0)
+	return;
+    xfree (mode);
 }
 
-
-static Bool
-RRGetInfo (ScreenPtr pScreen)
+/*
+ * Return the first output which is connected to an active CRTC
+ * Used in emulating 1.0 behaviour
+ */
+static RROutputPtr
+RRFirstOutput (ScreenPtr pScreen)
 {
-    rrScrPriv (pScreen);
-    Bool	    changed;
-    Rotation	    rotations;
-    RRMonitorPtr    pMonitor, *pPrevMon;
-    RRModePtr	    pMode, *pPrevMode;
-    int		    monitorid;
-
-    for (pMonitor = pScrPriv->pMonitors; pMonitor; pMonitor = pMonitor->next)
+    rrScrPriv(pScreen);
+    RROutputPtr		    output;
+    int	i, j;
+    
+    for (i = 0; i < pScrPriv->numCrtcs; i++)
     {
-	pMonitor->oldReferenced = TRUE;
-	pMonitor->referenced = FALSE;
-	pMonitor->pMode = NULL;
-	for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
+	RRCrtcPtr   crtc = pScrPriv->crtcs[i];
+	for (j = 0; j < pScrPriv->numOutputs; j++)
 	{
-	    pMode->oldReferenced = TRUE;
-	    pMode->referenced = FALSE;
+	    output = pScrPriv->outputs[j];
+	    if (output->crtc == crtc)
+		return output;
 	}
     }
-    rotations = 0;
-    if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
+    return NULL;
+}
+
+#ifdef RANDR_SCREEN_INTERFACE
+
+static Bool
+RROldModeAdd (RROutputPtr output, RRScreenSizePtr size, int refresh)
+{
+    xRRModeInfo	modeInfo;
+    char	name[100];
+    RRModePtr	mode;
+    int		i;
+    RRModePtr   *modes;
+    
+    memset (&modeInfo, '\0', sizeof (modeInfo));
+    sprintf (name, "%dx%d", size->width, size->height);
+    
+    modeInfo.width = size->width;
+    modeInfo.height = size->height;
+    modeInfo.mmWidth = size->mmWidth;
+    modeInfo.mmHeight = size->mmHeight;
+    modeInfo.hTotal = size->width;
+    modeInfo.vTotal = size->height;
+    modeInfo.dotClock = ((CARD32) size->width * (CARD32) size->width *
+			 (CARD32) refresh);
+    modeInfo.nameLength = strlen (name);
+    mode = RRModeGet (output->pScreen, &modeInfo, name);
+    if (!mode)
+	return FALSE;
+    for (i = 0; i < output->numModes; i++)
+	if (output->modes[i] == mode)
+	    return TRUE;
+    
+    if (output->numModes)
+	modes = xrealloc (output->modes, 
+			  (output->numModes + 1) * sizeof (RRModePtr));
+    else
+	modes = xalloc (sizeof (RRModePtr));
+    if (!modes)
 	return FALSE;
+    modes[output->numModes++] = mode;
+    output->modes = modes;
+    output->changed = TRUE;
+    return TRUE;
+}
 
-    changed = FALSE;
+static void
+RRScanOldConfig (ScreenPtr pScreen, Rotation rotations)
+{
+    rrScrPriv(pScreen);
+    RROutputPtr	output = RRFirstOutput (pScreen);
+    RRCrtcPtr	crtc;
+    int		i;
+    CARD16	minWidth = MAXSHORT, minHeight = MAXSHORT;
+    CARD16	maxWidth = 0, maxHeight = 0;
     
-    /* Old GetInfo clients return rotations here */
-    if (rotations && pScrPriv->pMonitors) {
-	/*
-	 * Check whether anything changed and simultaneously generate
-	 * the protocol id values for the objects
-	 */
-	if (rotations != pScrPriv->pMonitors->rotations)
-	{
-	    pScrPriv->pMonitors->rotations = rotations;
-	    changed = TRUE;
-	}
+    if (!output)
+	return;
+    crtc = output->crtc;
+
+    /* check rotations */
+    if (rotations != crtc->rotations)
+    {
+        crtc->rotations = rotations;
+	crtc->changed = TRUE;
+	pScrPriv->changed = TRUE;
     }
 	
-    /*
-     * Walk monitor and mode lists looking for updates
-     */
-    monitorid = 0;
-    for (pPrevMon = &pScrPriv->pMonitors; (pMonitor = *pPrevMon);)
+    /* regenerate mode list */
+    for (i = 0; i < pScrPriv->nSizes; i++)
     {
-	int modeid = 0;
-	
-	if (pMonitor->referenced)
-	{
-	    pMonitor->id = monitorid++;
-	    if (!pMonitor->oldReferenced)
-		changed = TRUE;
-	    for (pPrevMode = &pMonitor->pModes; (pMode = *pPrevMode);)
-	    {
-		if (pMode->referenced)
-		{
-		    pMode->id = modeid++;
-		    if (!pMode->oldReferenced)
-			changed = TRUE;
-		    pPrevMode = &pMode->next;
-		}
-		else
-		{
-		    *pPrevMode = pMode->next;
-		    changed = TRUE;
-		    RRFreeMode (pMode);
-		}
-	    }
-	    pPrevMon = &pMonitor->next;
-	}
+	RRScreenSizePtr	size = &pScrPriv->pSizes[i];
+	int		r;
+
+	if (size->nRates)
+	    for (r = 0; r < size->nRates; r++)
+		RROldModeAdd (output, size, size->pRates[r].rate);
 	else
-	{
-	    *pPrevMon = pMonitor->next;
-	    changed = TRUE;
-	    RRFreeMonitor (pMonitor);
-	}
+	    RROldModeAdd (output, size, 0);
     }
-    if (changed)
+	    
+    /* find size bounds */
+    for (i = 0; i < output->numModes; i++) 
     {
-	UpdateCurrentTime ();
-	pScrPriv->lastConfigTime = currentTime;
-	WalkTree (pScreen, TellChanged, (pointer) pScreen);
+	RRModePtr   mode = output->modes[i];
+        CARD16	    width = mode->mode.width;
+        CARD16	    height = mode->mode.height;
+	
+	if (width < minWidth) minWidth = width;
+	if (width > maxWidth) maxWidth = width;
+	if (height < minHeight) minHeight = height;
+	if (height > maxHeight) maxHeight = height;
+    }
+
+    if (minWidth != pScrPriv->minWidth) {
+	pScrPriv->minWidth = minWidth; pScrPriv->changed = TRUE;
+    }
+    if (maxWidth != pScrPriv->maxWidth) {
+	pScrPriv->maxWidth = maxWidth; pScrPriv->changed = TRUE;
+    }
+    if (minHeight != pScrPriv->minHeight) {
+	pScrPriv->minHeight = minHeight; pScrPriv->changed = TRUE;
     }
+    if (maxHeight != pScrPriv->maxHeight) {
+	pScrPriv->maxHeight = maxHeight; pScrPriv->changed = TRUE;
+    }
+}
+#endif
+
+static Bool
+RRGetInfo (ScreenPtr pScreen)
+{
+    rrScrPriv (pScreen);
+    Rotation	    rotations;
+    int		    i;
+
+    for (i = 0; i < pScrPriv->numOutputs; i++)
+	pScrPriv->outputs[i]->changed = FALSE;
+    for (i = 0; i < pScrPriv->numCrtcs; i++)
+	pScrPriv->crtcs[i]->changed = FALSE;
+    
+    rotations = 0;
+    pScrPriv->changed = FALSE;
+    
+    if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
+	return FALSE;
+
+#if RANDR_SCREEN_INTERFACE
+    if (pScrPriv->nSizes)
+	RRScanOldConfig (pScreen, rotations);
+#endif
+    RRTellChanged (pScreen);
     return TRUE;
 }
 
@@ -664,17 +821,6 @@ RREditConnectionInfo (ScreenPtr pScreen)
     root->mmHeight = pScreen->mmHeight;
 }
 
-static int
-RRNumModes (RRMonitorPtr pMonitor)
-{
-    int	n = 0;
-    RRModePtr	pMode;
-
-    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
-	n++;
-    return n;
-}
-
 typedef struct _RR10Data {
     RRScreenSizePtr sizes;
     int		    nsize;
@@ -684,7 +830,7 @@ typedef struct _RR10Data {
 } RR10DataRec, *RR10DataPtr;
 
 static CARD16
-RRVerticalRefresh (xRRMonitorMode *mode)
+RRVerticalRefresh (xRRModeInfo *mode)
 {
     CARD32  refresh;
     if (!mode->hTotal || !mode->vTotal)
@@ -699,61 +845,61 @@ RRVerticalRefresh (xRRMonitorMode *mode)
  * Convert 1.2 monitor data into 1.0 screen data
  */
 static RR10DataPtr
-RR10GetData (ScreenPtr pScreen, RRMonitorPtr pMonitor)
+RR10GetData (ScreenPtr pScreen, RROutputPtr output)
 {
     RR10DataPtr	    data;
     RRScreenSizePtr size;
-    int		    nmode = RRNumModes (pMonitor);
-    int		    i;
-    int		    j;
-    RRRefreshPtr    refresh;
+    int		    nmode = output->numModes;
+    int		    i, j, k;
+    RRScreenRatePtr refresh;
     CARD16	    vRefresh;
-    RRModePtr	    pMode;
+    RRModePtr	    mode;
 
     /* Make sure there is plenty of space for any combination */
     data = malloc (sizeof (RR10DataRec) + 
-		   sizeof (RRScreenSizeRec) * nmode + 
-		   sizeof (RRRefreshRec) * nmode);
+		   sizeof (RRScreenSize) * nmode + 
+		   sizeof (RRScreenRate) * nmode);
     if (!data)
 	return NULL;
     size = (RRScreenSizePtr) (data + 1);
-    refresh = (RRRefreshPtr) (size + nmode);
+    refresh = (RRScreenRatePtr) (size + nmode);
     data->sizes = size;
     data->nsize = 0;
     data->nrefresh = 0;
     data->size = 0;
     data->refresh = 0;
-    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
+    for (i = 0; i < output->numModes; i++)
     {
-	for (i = 0; i < data->nsize; i++)
-	    if (pMode->mode.width == size[i].width &&
-		pMode->mode.height == size[i].height)
+	mode = output->modes[i];
+	for (j = 0; j < data->nsize; j++)
+	    if (mode->mode.width == size[j].width &&
+		mode->mode.height == size[j].height)
 		break;
-	if (i == data->nsize)
+	if (j == data->nsize)
 	{
-	    size[i].id = i;
-	    size[i].width = pMode->mode.width;
-	    size[i].height = pMode->mode.height;
-	    size[i].mmWidth = pMode->mode.widthInMillimeters;
-	    size[i].mmHeight = pMode->mode.heightInMillimeters;
-	    size[i].nrefresh = 0;
-	    size[i].refresh = &refresh[data->nrefresh];
+	    size[j].id = j;
+	    size[j].width = mode->mode.width;
+	    size[j].height = mode->mode.height;
+	    size[j].mmWidth = mode->mode.mmWidth;
+	    size[j].mmHeight = mode->mode.mmHeight;
+	    size[j].nRates = 0;
+	    size[j].pRates = &refresh[data->nrefresh];
 	    data->nsize++;
 	}
-	vRefresh = RRVerticalRefresh (&pMode->mode);
-	for (j = 0; j < size[i].nrefresh; j++)
-	    if (vRefresh == size[i].refresh[j].refresh)
+	vRefresh = RRVerticalRefresh (&mode->mode);
+	for (k = 0; k < size[j].nRates; k++)
+	    if (vRefresh == size[j].pRates[k].rate)
 		break;
-	if (j == size[i].nrefresh)
+	if (k == size[j].nRates)
 	{
-	    size[i].refresh[j].refresh = vRefresh;
-	    size[i].refresh[j].pMode = pMode;
-	    size[i].nrefresh++;
+	    size[j].pRates[k].rate = vRefresh;
+	    size[j].pRates[k].mode = mode;
+	    size[j].nRates++;
 	    data->nrefresh++;
 	}
-	if (pMode == pMonitor->pMode)
+	if (mode == output->crtc->mode)
 	{
-	    data->size = i;
+	    data->size = j;
 	    data->refresh = vRefresh;
 	}
     }
@@ -771,6 +917,7 @@ ProcRRGetScreenInfo (ClientPtr client)
     rrScrPrivPtr	    pScrPriv;
     CARD8		    *extra;
     unsigned long	    extraLen;
+    RROutputPtr		    output;
 
     REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
     pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
@@ -786,7 +933,9 @@ ProcRRGetScreenInfo (ClientPtr client)
     if (pScrPriv)
 	RRGetInfo (pScreen);
 
-    if (!pScrPriv && !pScrPriv->pMonitors)
+    output = RRFirstOutput (pScreen);
+    
+    if (!pScrPriv || !output)
     {
 	rep.type = X_Reply;
 	rep.setOfRotations = RR_Rotate_0;;
@@ -805,7 +954,6 @@ ProcRRGetScreenInfo (ClientPtr client)
     }
     else
     {
-	RRMonitorPtr		pMonitor = pScrPriv->pMonitors;
 	int			i, j;
 	xScreenSizes		*size;
 	CARD16			*rates;
@@ -814,18 +962,18 @@ ProcRRGetScreenInfo (ClientPtr client)
 	RR10DataPtr		pData;
 	RRScreenSizePtr		pSize;
     
-	pData = RR10GetData (pScreen, pMonitor);
+	pData = RR10GetData (pScreen, output);
 	if (!pData)
 	    return BadAlloc;
 	
 	rep.type = X_Reply;
-	rep.setOfRotations = pMonitor->rotations;
+	rep.setOfRotations = output->crtc->rotations;
 	rep.sequenceNumber = client->sequence;
 	rep.length = 0;
 	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
 	rep.timestamp = pScrPriv->lastSetTime.milliseconds;
 	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
-	rep.rotation = pMonitor->rotation;
+	rep.rotation = output->crtc->rotation;
 	rep.nSizes = pData->nsize;
         rep.nrateEnts = pData->nrefresh + pData->nsize;
 	rep.sizeID = pData->size;
@@ -862,15 +1010,15 @@ ProcRRGetScreenInfo (ClientPtr client)
 	    size++;
 	    if (has_rate)
 	    {
-		*rates = pSize->nrefresh;
+		*rates = pSize->nRates;
 		if (client->swapped)
 		{
 		    swaps (rates, n);
 		}
 		rates++;
-		for (j = 0; j < pSize->nrefresh; j++)
+		for (j = 0; j < pSize->nRates; j++)
 		{
-		    *rates = pSize->refresh[j].refresh;
+		    *rates = pSize->pRates[j].rate;
 		    if (client->swapped)
 		    {
 			swaps (rates, n);
@@ -907,6 +1055,7 @@ ProcRRGetScreenInfo (ClientPtr client)
     return (client->noClientException);
 }
 
+#if 0
 static int
 RRMonitorSetMode (ScreenPtr pScreen, RRMonitorPtr pMonitor, 
 		  RRModePtr pMode, int x, int y, Rotation rotation,
@@ -997,6 +1146,7 @@ RRMonitorSetMode (ScreenPtr pScreen, RRMonitorPtr pMonitor,
     pScrPriv->lastSetTime = time;
     return RRSetConfigSuccess;
 }
+#endif
 
 static int
 ProcRRSetScreenConfig (ClientPtr client)
@@ -1013,8 +1163,8 @@ ProcRRSetScreenConfig (ClientPtr client)
     Rotation		    rotation;
     int			    rate;
     Bool		    has_rate;
-    RRMonitorPtr	    pMonitor;
-    RRModePtr		    pMode;
+    RROutputPtr		    output;
+    RRModePtr		    mode;
     RR10DataPtr		    pData = NULL;
     RRScreenSizePtr    	    pSize;
     
@@ -1050,8 +1200,8 @@ ProcRRSetScreenConfig (ClientPtr client)
     if (!RRGetInfo (pScreen))
 	return BadAlloc;
     
-    pMonitor = pScrPriv->pMonitors;
-    if (!pMonitor)
+    output = RRFirstOutput (pScreen);
+    if (!output)
     {
 	time = currentTime;
 	rep.status = RRSetConfigFailed;
@@ -1069,7 +1219,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	goto sendReply;
     }
     
-    pData = RR10GetData (pScreen, pMonitor);
+    pData = RR10GetData (pScreen, output);
     if (!pData)
 	return BadAlloc;
     
@@ -1105,7 +1255,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	return BadValue;
     }
 
-    if ((~pMonitor->rotations) & rotation)
+    if ((~output->crtc->rotations) & rotation)
     {
 	/*
 	 * requested rotation or reflection not supported by screen
@@ -1125,12 +1275,12 @@ ProcRRSetScreenConfig (ClientPtr client)
 
     if (rate)
     {
-	for (i = 0; i < pSize->nrefresh; i++)
+	for (i = 0; i < pSize->nRates; i++)
 	{
-	    if (pSize->refresh[i].refresh == rate)
+	    if (pSize->pRates[i].rate == rate)
 		break;
 	}
-	if (i == pSize->nrefresh)
+	if (i == pSize->nRates)
 	{
 	    /*
 	     * Invalid rate
@@ -1139,10 +1289,10 @@ ProcRRSetScreenConfig (ClientPtr client)
 	    xfree (pData);
 	    return BadValue;
 	}
-	pMode = pSize->refresh[i].pMode;
+	mode = pSize->pRates[i].mode;
     }
     else
-	pMode = pSize->refresh[0].pMode;
+	mode = pSize->pRates[0].mode;
     
     /*
      * Make sure the requested set-time is not older than
@@ -1154,7 +1304,8 @@ ProcRRSetScreenConfig (ClientPtr client)
 	goto sendReply;
     }
 
-    rep.status = RRMonitorSetMode (pScreen, pMonitor, pMode, 0, 0, rotation, time);
+    rep.status = RRCrtcSet (output->crtc, mode, 0, 0, stuff->rotation,
+			    1, &output);
     
 sendReply:
     
@@ -1183,6 +1334,7 @@ sendReply:
     return (client->noClientException);
 }
 
+#if 0
 int
 RRSetScreenConfig (ScreenPtr		pScreen,
 		   Rotation		rotation,
@@ -1252,10 +1404,42 @@ RRSetScreenConfig (ScreenPtr		pScreen,
     
     status = RRMonitorSetMode (pScreen, pMonitor, pMode, 0, 0, 
 			       rotation, currentTime);
+    
     if (status != RRSetConfigSuccess)
 	return BadImplementation;
     return Success;
 }
+#endif
+
+static Bool
+RRSetScreenSize (ScreenPtr pScreen,
+		 CARD16 width, CARD16 height,
+		 CARD16 widthInMillimeters, CARD16 heightInMillimeters)
+{
+    rrScrPriv(pScreen);
+    
+    if (pScrPriv->rrScreenSetSize) 
+    {
+	return (*pScrPriv->rrScreenSetSize) (pScreen, width, height,
+					     widthInMillimeters,
+					     heightInMillimeters);
+    }
+#ifdef RANDR_SCREEN_INTERFACE
+    else
+    {
+	/* Pend the size change until we get the set mode request.
+	 * Yes, this is 'illegal', but the best we can do until
+	 * drivers are updated
+	 */
+	pScrPriv->reqWidth = width;
+	pScrPriv->reqHeight = height;
+	pScreen->mmWidth = widthInMillimeters;
+	pScreen->mmHeight = heightInMillimeters;
+	return TRUE;
+    }
+#endif
+    return FALSE;
+}
 
 static int
 ProcRRSelectInput (ClientPtr client)
@@ -1264,7 +1448,7 @@ ProcRRSelectInput (ClientPtr client)
     rrClientPriv(client);
     RRTimesPtr	pTimes;
     WindowPtr	pWin;
-    RREventPtr	pRREvent, pNewRREvent, *pHead;
+    RREventPtr	pRREvent, *pHead;
     XID		clientResource;
 
     REQUEST_SIZE_MATCH(xRRSelectInputReq);
@@ -1275,58 +1459,64 @@ ProcRRSelectInput (ClientPtr client)
 						 pWin->drawable.id, EventType,
 						 SecurityWriteAccess);
 
-    if (stuff->enable & (RRScreenChangeNotifyMask)) 
+    if (stuff->enable & (RRScreenChangeNotifyMask|
+			 RRCrtcChangeNotifyMask|
+			 RROutputChangeNotifyMask)) 
     {
 	ScreenPtr	pScreen = pWin->drawable.pScreen;
 	rrScrPriv	(pScreen);
 
+	pRREvent = NULL;
 	if (pHead) 
 	{
 	    /* check for existing entry. */
 	    for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next)
 		if (pRREvent->client == client)
-		    return Success;
+		    break;
 	}
 
-	/* build the entry */
-	pNewRREvent = (RREventPtr) xalloc (sizeof (RREventRec));
-	if (!pNewRREvent)
-	    return BadAlloc;
-	pNewRREvent->next = 0;
-	pNewRREvent->client = client;
-	pNewRREvent->window = pWin;
-	pNewRREvent->mask = stuff->enable;
-	/*
-	 * add a resource that will be deleted when
-	 * the client goes away
-	 */
-	clientResource = FakeClientID (client->index);
-	pNewRREvent->clientResource = clientResource;
-	if (!AddResource (clientResource, ClientType, (pointer)pNewRREvent))
-	    return BadAlloc;
-	/*
-	 * create a resource to contain a pointer to the list
-	 * of clients selecting input.  This must be indirect as
-	 * the list may be arbitrarily rearranged which cannot be
-	 * done through the resource database.
-	 */
-	if (!pHead)
+	if (!pRREvent)
 	{
-	    pHead = (RREventPtr *) xalloc (sizeof (RREventPtr));
-	    if (!pHead ||
-		!AddResource (pWin->drawable.id, EventType, (pointer)pHead))
-	    {
-		FreeResource (clientResource, RT_NONE);
+	    /* build the entry */
+	    pRREvent = (RREventPtr) xalloc (sizeof (RREventRec));
+	    if (!pRREvent)
 		return BadAlloc;
+	    pRREvent->next = 0;
+	    pRREvent->client = client;
+	    pRREvent->window = pWin;
+	    pRREvent->mask = stuff->enable;
+	    /*
+	     * add a resource that will be deleted when
+	     * the client goes away
+	     */
+	    clientResource = FakeClientID (client->index);
+	    pRREvent->clientResource = clientResource;
+	    if (!AddResource (clientResource, ClientType, (pointer)pRREvent))
+		return BadAlloc;
+	    /*
+	     * create a resource to contain a pointer to the list
+	     * of clients selecting input.  This must be indirect as
+	     * the list may be arbitrarily rearranged which cannot be
+	     * done through the resource database.
+	     */
+	    if (!pHead)
+	    {
+		pHead = (RREventPtr *) xalloc (sizeof (RREventPtr));
+		if (!pHead ||
+		    !AddResource (pWin->drawable.id, EventType, (pointer)pHead))
+		{
+		    FreeResource (clientResource, RT_NONE);
+		    return BadAlloc;
+		}
+		*pHead = 0;
 	    }
-	    *pHead = 0;
+	    pRREvent->next = *pHead;
+	    *pHead = pRREvent;
 	}
-	pNewRREvent->next = *pHead;
-	*pHead = pNewRREvent;
 	/*
 	 * Now see if the client needs an event
 	 */
-	if (pScrPriv)
+	if (pScrPriv && (pRREvent->mask & RRScreenChangeNotifyMask))
 	{
 	    pTimes = &((RRTimesPtr) (pRRClient + 1))[pScreen->myNum];
 	    if (CompareTimeStamps (pTimes->setTime, 
@@ -1334,15 +1524,15 @@ ProcRRSelectInput (ClientPtr client)
 		CompareTimeStamps (pTimes->configTime, 
 				   pScrPriv->lastConfigTime) != 0)
 	    {
-		TellChanged (pWin, (pointer) pScreen);
+		DeliverScreenEvent (client, pWin, pScreen);
 	    }
 	}
     }
-    else if (stuff->enable == xFalse) 
+    else if (stuff->enable == 0) 
     {
 	/* delete the interest */
 	if (pHead) {
-	    pNewRREvent = 0;
+	    RREventPtr pNewRREvent = 0;
 	    for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next) {
 		if (pRREvent->client == client)
 		    break;
@@ -1366,36 +1556,340 @@ ProcRRSelectInput (ClientPtr client)
     return Success;
 }
 
-
-static int ProcRRGetScreenSizeRange (ClientPtr pClient)
+/*
+ * Retrieve valid screen size range
+ */
+static int ProcRRGetScreenSizeRange (ClientPtr client)
 {
-    return BadImplementation;
+    REQUEST(xRRGetScreenSizeRangeReq);
+    xRRGetScreenSizeRangeReply	rep;
+    WindowPtr			pWin;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    
+    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    
+    rep.type = X_Reply;
+    rep.pad = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.length = 0;
+    
+    if (pScrPriv) 
+    {
+	RRGetInfo (pScreen);
+	rep.minWidth  = pScrPriv->minWidth;
+	rep.minHeight = pScrPriv->minHeight;
+	rep.maxWidth  = pScrPriv->maxWidth;
+	rep.maxHeight = pScrPriv->maxHeight;
+    }
+    else
+    {
+	rep.maxWidth  = rep.minWidth  = pScreen->width;
+	rep.maxHeight = rep.minHeight = pScreen->height;
+    }
+    if (client->swapped) 
+    {
+	int n;
+	
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swaps(&rep.minWidth, n);
+	swaps(&rep.minHeight, n);
+	swaps(&rep.maxWidth, n);
+	swaps(&rep.maxHeight, n);
+    }
+    WriteToClient(client, sizeof(xRRGetScreenSizeRangeReply), (char *)&rep);
+    return (client->noClientException);
 }
 
-static int ProcRRSetScreenSize (ClientPtr pClient)
+static int ProcRRSetScreenSize (ClientPtr client)
 {
-    return BadImplementation;
+    REQUEST(xRRSetScreenSizeReq);
+    WindowPtr		pWin;
+    ScreenPtr		pScreen;
+    rrScrPrivPtr	pScrPriv;
+    RRCrtcPtr		crtc;
+    int			i;
+    
+    REQUEST_SIZE_MATCH(xRRSetScreenSizeReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    if (stuff->width < pScrPriv->minWidth || pScrPriv->maxWidth < stuff->width)
+    {
+	client->errorValue = stuff->width;
+	return BadValue;
+    }
+    if (stuff->height < pScrPriv->minHeight || 
+	pScrPriv->maxHeight < stuff->height)
+    {
+	client->errorValue = stuff->height;
+	return BadValue;
+    }
+    for (i = 0; i < pScrPriv->numCrtcs; i++) {
+	crtc = pScrPriv->crtcs[i];
+	if (crtc->mode &&
+	    (crtc->x + crtc->mode->mode.width > stuff->width ||
+	     crtc->y + crtc->mode->mode.height > stuff->height))
+	    return BadMatch;
+    }
+    if (stuff->widthInMillimeters == 0 || stuff->heightInMillimeters == 0)
+    {
+	client->errorValue = 0;
+	return BadValue;
+    }
+    if (!RRSetScreenSize (pScreen, 
+			  stuff->width, stuff->height,
+			  stuff->widthInMillimeters,
+			  stuff->heightInMillimeters))
+    {
+	return BadMatch;
+    }
+    return Success;
 }
 
-static int ProcRRGetMonitorInfo (ClientPtr pClient)
+#if 0
+static int ProcRRGetMonitorInfo (ClientPtr client)
 {
-    return BadImplementation;
+    REQUEST(xRRGetMonitorInfoReq);
+    xRRGetMonitorInfoReply	rep;
+    WindowPtr			pWin;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    RRMonitorPtr		pMonitor;
+    RRModePtr			pMode;
+    int				extraLen;
+    CARD8			*extra;
+    xRRMonitorInfo		*monitor;
+    xRRMonitorMode		*mode;
+    CARD8			*names;
+    
+    REQUEST_SIZE_MATCH(xRRGetScreenInfoReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    rep.type = X_Reply;
+    rep.pad = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.numMonitors = 0;
+    rep.numModes = 0;
+    rep.sizeNames = 0;
+    if (!pScrPriv)
+    {
+	extraLen = 0;
+	extra = NULL;
+    }
+    else
+    {
+	int i, m, b;
+	for (pMonitor = pScrPriv->pMonitors; pMonitor; pMonitor = pMonitor->next)
+	{
+	    rep.numMonitors++;
+	    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
+	    {
+		rep.numModes++;
+		rep.sizeNames += (1 + pMode->mode.nameLength);
+	    }
+	}
+	extraLen = (rep.numMonitors * sizeof (xRRMonitorInfo) +
+		    rep.numModes * sizeof (xRRMonitorMode) +
+		    rep.sizeNames + 3) & ~3;
+	extra = (CARD8 *) xalloc (extraLen);
+	if (!extra)
+	    return BadAlloc;
+	monitor = (xRRMonitorInfo *) extra;
+	mode = (xRRMonitorMode *) (monitor + rep.numMonitors);
+	names = (CARD8 *) (mode + rep.numModes);
+	i = 0;
+	m = 0;
+	b = 0;
+	for (pMonitor = pScrPriv->pMonitors; pMonitor; pMonitor = pMonitor->next)
+	{
+	    monitor[i].timestamp = pScrPriv->lastSetTime;
+	    monitor[i].configTimestamp = pScrPriv->lastConfigTime;
+	    monitor[i].x = pMonitor->x;
+	    monitor[i].y = pMonitor->y;
+	    monitor[i].rotation = pMonitor->rotation;
+	    monitor[i].mode = pMonitor->pMode->id;
+	    monitor[i].defaultMode = 0;	/* XXX */
+	    monitor[i].rotations = pMonitor->rotations;
+	    monitor[i].firstMode = m;
+	    monitor[i].numModes = 0;
+	    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
+	    {
+		monitor[i].numModes++;
+		mode[m] = pMode->mode;
+		names[b] = pMode->mode.nameLength;
+		b++;
+		memcpy (names + b, (char *) (pMode + 1), 
+			pMode->mode.nameLength);
+		b += pMode->mode.nameLength;
+		m++;
+	    }
+	    i++;
+	}
+	if ((char *) (names + ((b + 3) & ~3)) != (char *) extra + extraLen)
+	    FatalError ("RRGetMonitorInfo length mismatch\n");
+    }
+    rep.length = extraLen >> 2;
+    
+    WriteToClient(client, sizeof(xRRGetMonitorInfoReply), (char *)&rep);
+    if (extraLen)
+    {
+	WriteToClient (client, extraLen, (char *) extra);
+	xfree (extra);
+    }
+    
+    if (extra)
+	xfree (extra);
+    return (client->noClientException);
 }
 
-static int ProcRRAddMonitorMode (ClientPtr pClient)
+static int ProcRRAddMonitorMode (ClientPtr client)
 {
     return BadImplementation;
 }
 
-static int ProcRRDeleteMonitorMode (ClientPtr pClient)
+static int ProcRRDeleteMonitorMode (ClientPtr client)
 {
     return BadImplementation;
 }
 
-static int ProcRRSetMonitorConfig (ClientPtr pClient)
+static int ProcRRSetMonitorConfig (ClientPtr client)
 {
-    return BadImplementation;
+    REQUEST(xRRSetMonitorConfigReq);
+    xRRSetMonitorConfigReply	rep;
+    WindowPtr			pWin;
+    ScreenPtr			pScreen;
+    rrScrPrivPtr		pScrPriv;
+    RRMonitorPtr		pMonitor;
+    RRModePtr			pMode;
+    TimeStamp		    configTime;
+    TimeStamp		    time;
+    Rotation		    rotation;
+    
+    REQUEST_SIZE_MATCH(xRRSetScreenConfigReq);
+    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
+					   SecurityReadAccess);
+
+    if (!pWin)
+	return BadWindow;
+
+    pScreen = pWin->drawable.pScreen;
+    pScrPriv = rrGetScrPriv(pScreen);
+    
+    time = ClientTimeToServerTime(stuff->timestamp);
+    configTime = ClientTimeToServerTime(stuff->configTimestamp);
+    
+    if (!pScrPriv)
+    {
+	time = currentTime;
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    if (!RRGetInfo (pScreen))
+	return BadAlloc;
+    
+    /*
+     * if the client's config timestamp is not the same as the last config
+     * timestamp, then the config information isn't up-to-date and
+     * can't even be validated
+     */
+    if (CompareTimeStamps (configTime, pScrPriv->lastConfigTime) != 0)
+    {
+	rep.status = RRSetConfigInvalidConfigTime;
+	goto sendReply;
+    }
+    
+    for (pMonitor = pScrPriv->pMonitors; pMonitor; pMonitor = pMonitor->next)
+    {
+	if (pMonitor->id == stuff->monitorIndex)
+	    break;
+    }
+    if (!pMonitor)
+    {
+	client->errorValue = stuff->monitorIndex;
+	return BadValue;
+    }
+    
+    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
+    {
+	if (pMode->id == stuff->modeIndex)
+	    break;
+    }
+    if (!pMode)
+    {
+	client->errorValue = stuff->modeIndex;
+	return BadValue;
+    }
+    
+    /*
+     * Validate requested rotation
+     */
+    rotation = (Rotation) stuff->rotation;
+
+    /* test the rotation bits only! */
+    switch (rotation & 0xf) {
+    case RR_Rotate_0:
+    case RR_Rotate_90:
+    case RR_Rotate_180:
+    case RR_Rotate_270:
+	break;
+    default:
+	/*
+	 * Invalid rotation
+	 */
+	client->errorValue = stuff->rotation;
+	return BadValue;
+    }
+
+    if ((~pMonitor->rotations) & rotation)
+    {
+	/*
+	 * requested rotation or reflection not supported by screen
+	 */
+	client->errorValue = stuff->rotation;
+	return BadMatch;
+    }
+
+    if (stuff->x + pMode->mode.width > pScreen->width)
+    {
+	client->errorValue = stufff
+	stuff->y + pMode->mode.height > pScreen
+    /*
+     * Make sure the requested set-time is not older than
+     * the last set-time
+     */
+    if (CompareTimeStamps (time, pScrPriv->lastSetTime) < 0)
+    {
+	rep.status = RRSetConfigInvalidTime;
+	goto sendReply;
+    }
+
+    rep.status = RRMonitorSetMode (pScreen, pMonitor, 
+				   pMode, stuff->x, stuff->y, rotation, time);
+    
+    return client->noClientException;
 }
+#endif
 
 int (*ProcRandrVector[RRNumberRequests])(ClientPtr) = {
     ProcRRQueryVersion,	/* 0 */
@@ -1408,12 +1902,14 @@ int (*ProcRandrVector[RRNumberRequests])(ClientPtr) = {
     ProcRRSelectInput,		/* 4 */
     ProcRRGetScreenInfo,    	/* 5 */
 /* V1.2 additions */
+#if 0
     ProcRRGetScreenSizeRange,	/* 6 */
     ProcRRSetScreenSize,	/* 7 */
     ProcRRGetMonitorInfo,	/* 8 */
     ProcRRAddMonitorMode,	/* 9 */
     ProcRRDeleteMonitorMode,	/* 10 */
     ProcRRSetMonitorConfig,	/* 11 */
+#endif
 };
 
 
@@ -1505,113 +2001,42 @@ SProcRRDispatch (ClientPtr client)
 }
 
 /*
- * Register a monitor for a screen. identifier is a unique identifier
- * for the monitors of a particular screen.
+ * Register the range of sizes for the screen
  */
-RRMonitorPtr
-RRRegisterMonitor (ScreenPtr		pScreen,
-		   void			*identifier,
-		   Rotation		rotations)
+void
+RRScreenSetSizeRange (ScreenPtr	pScreen,
+		      CARD16	minWidth,
+		      CARD16	minHeight,
+		      CARD16	maxWidth,
+		      CARD16	maxHeight)
 {
     rrScrPriv (pScreen);
-    RRMonitorPtr    pMonitor, *pPrev, *pInsert;
 
-    pInsert = NULL;
-    for (pPrev = &pScrPriv->pMonitors; (pMonitor = *pPrev); 
-	 pPrev = &(pMonitor)->next)
-    {
-	if (pMonitor->identifier == identifier) 
-	{
-	    pMonitor->referenced = TRUE;
-	    return pMonitor;
-	}
-	if (!pMonitor->referenced)
-	    pInsert = pPrev;
-    }
-    if (!pInsert)
-	pInsert = pPrev;
-    
-    /*
-     * New monitor, add before the first unreferenced monitor
-     */
-    pMonitor = xalloc (sizeof (RRMonitor));
-    if (!pMonitor)
-	return NULL;
-    pMonitor->pScreen = pScreen;
-    pMonitor->pModes = NULL;
-    pMonitor->identifier = identifier;
-    pMonitor->referenced = TRUE;
-    pMonitor->oldReferenced = FALSE;
-    pMonitor->rotations = RR_Rotate_0;
-    
-    pMonitor->pMode = NULL;
-    pMonitor->x = 0;
-    pMonitor->y = 0;
-    pMonitor->rotation = RR_Rotate_0;
-    pMonitor->next = *pInsert;
-    *pInsert = pMonitor;
-    return pMonitor;
+    if (!pScrPriv)
+	return;
+    pScrPriv->minWidth  = minWidth;
+    pScrPriv->minHeight = minHeight;
+    pScrPriv->maxWidth  = maxWidth;
+    pScrPriv->maxHeight = maxHeight;
 }
 
-/*
- * Register a mode for a monitor
- */
-
-RRModePtr
-RRRegisterMode (RRMonitorPtr	pMonitor,
-		xRRMonitorMode	*pModeline,
-		char		*name)
-{
-    RRModePtr	pMode, *pPrev, *pInsert = NULL;
-
-    /*
-     * Find existing mode with same modeline and name
-     */
-    for (pPrev = &pMonitor->pModes; (pMode = *pPrev); pPrev = &(pMode->next))
-    {
-	if (!memcmp (&pMode->mode, pModeline, sizeof (xRRMonitorMode)) &&
-	    pMode->mode.nameLength == pModeline->nameLength &&
-	    !memcmp (RRModeName(pMode), name, pModeline->nameLength))
-	{
-	    pMode->referenced = TRUE;
-	    return pMode;
-	}
-	if (!pMode->referenced)
-	    pInsert = pPrev;
-    }
-
-    if (!pInsert)
-	pInsert = pPrev;
-    
-    /*
-     * Create a new mode, inserting before the first unreferenced mode
-     */
-    pMode = xalloc (sizeof (RRMode) + pModeline->nameLength + 1);
-    pMode->referenced = TRUE;
-    pMode->oldReferenced = FALSE;
-    pMode->mode = *pModeline;
-    memcpy (RRModeName (pMode), name, pModeline->nameLength);
-    RRModeName(pMode)[pModeline->nameLength] = '\0';
-    pMode->next = *pInsert;
-    *pInsert = pMode;
-    return pMode;
-}
+#ifdef RANDR_SCREEN_INTERFACE
 
-void
-RRSetCurrentMode (RRMonitorPtr	pMonitor,
-		  RRModePtr	pMode,
-		  int		x,
-		  int		y,
-		  Rotation	rotation)
+static Bool
+RRScreenSizeMatches (RRScreenSizePtr  a,
+		   RRScreenSizePtr  b)
 {
-    pMonitor->pMode = pMode;
-    pMonitor->x = x;
-    pMonitor->y = y;
-    pMonitor->rotation = rotation;
+    if (a->width != b->width)
+	return FALSE;
+    if (a->height != b->height)
+	return FALSE;
+    if (a->mmWidth != b->mmWidth)
+	return FALSE;
+    if (a->mmHeight != b->mmHeight)
+	return FALSE;
+    return TRUE;
 }
 
-#ifdef RANDR_SCREEN_INTERFACE
-
 RRScreenSizePtr
 RRRegisterSize (ScreenPtr	    pScreen,
 		short		    width, 
@@ -1620,50 +2045,29 @@ RRRegisterSize (ScreenPtr	    pScreen,
 		short		    mmHeight)
 {
     rrScrPriv (pScreen);
-    xRRMonitorMode  tmp;
-    RRMonitorPtr    pMonitor;
-    RRModePtr	    pMode, *pPrev;
-    char	    name[100];
+    int		    i;
+    RRScreenSize    tmp;
+    RRScreenSizePtr pNew;
 
     if (!pScrPriv)
-	return NULL;
-    pMonitor = pScrPriv->pMonitors;
-    if (!pMonitor)
-    {
-	pMonitor = RRRegisterMonitor (pScreen, NULL, RR_Rotate_0);
-	if (!pMonitor)
-	    return NULL;
-    }
-    pMonitor->referenced = TRUE;
+	return 0;
     
-    for (pPrev = &pMonitor->pModes; (pMode = *pPrev); pPrev = &(pMode->next))
-	if (pMode->mode.width == width &&
-	    pMode->mode.height == height &&
-	    pMode->mode.widthInMillimeters == mmWidth &&
-	    pMode->mode.heightInMillimeters == mmHeight)
-	{
-	    pMode->referenced =TRUE;
-	    return (void *) pMode;
-	}
-    memset (&tmp, '\0', sizeof (xRRMonitorMode));
-    memset (name, '\0', sizeof (name));
-    sprintf (name, "%dx%d", width, height);
     tmp.width = width;
     tmp.height= height;
-    tmp.widthInMillimeters = mmWidth;
-    tmp.heightInMillimeters = mmHeight;
-    tmp.nameLength = strlen (name) + 10;    /* leave space for refresh */
-    pMode = RRRegisterMode (pMonitor, &tmp, name);
-    return (void *) pMode;
-}
-
-static Bool
-RRModesMatchSize (RRModePtr a, RRModePtr b)
-{
-    return (a->mode.width == a->mode.width &&
-	    a->mode.height == b->mode.height &&
-	    a->mode.widthInMillimeters == b->mode.widthInMillimeters &&
-	    a->mode.heightInMillimeters == b->mode.heightInMillimeters);
+    tmp.mmWidth = mmWidth;
+    tmp.mmHeight = mmHeight;
+    tmp.pRates = 0;
+    tmp.nRates = 0;
+    for (i = 0; i < pScrPriv->nSizes; i++)
+	if (RRScreenSizeMatches (&tmp, &pScrPriv->pSizes[i]))
+	    return &pScrPriv->pSizes[i];
+    pNew = xrealloc (pScrPriv->pSizes,
+		     (pScrPriv->nSizes + 1) * sizeof (RRScreenSize));
+    if (!pNew)
+	return 0;
+    pNew[pScrPriv->nSizes++] = tmp;
+    pScrPriv->pSizes = pNew;
+    return &pNew[pScrPriv->nSizes-1];
 }
 
 Bool RRRegisterRate (ScreenPtr		pScreen,
@@ -1671,77 +2075,35 @@ Bool RRRegisterRate (ScreenPtr		pScreen,
 		     int		rate)
 {
     rrScrPriv(pScreen);
-    RRMonitorPtr    pMonitor;
-    RRModePtr	    pSizeMode = (RRModePtr) pSize;
-    RRModePtr	    pMode, *pPrev;
-    CARD16	    width = pSizeMode->mode.width;
-    CARD16	    height = pSizeMode->mode.height;
-    char	    name[100];
-    xRRMonitorMode  modeLine;
+    int		    i;
+    RRScreenRatePtr pNew, pRate;
 
     if (!pScrPriv)
 	return FALSE;
     
-    pMonitor = pScrPriv->pMonitors;
-    if (!pMonitor)
-	return FALSE;
+    for (i = 0; i < pSize->nRates; i++)
+	if (pSize->pRates[i].rate == rate)
+	    return TRUE;
 
-    for (pPrev = &pMonitor->pModes; (pMode = *pPrev); pPrev = &pMode->next)
-    {
-	if (RRModesMatchSize (pMode, pSizeMode))
-	{
-	    if (pMode->mode.dotClock == 0)
-	    {
-		/*
-		 * First refresh for this size; reprogram this mode
-		 * with the right refresh.
-		 */
-		pMode->mode.hSyncStart = width;
-		pMode->mode.hSyncEnd = width;
-		pMode->mode.hTotal = width;
-		pMode->mode.hSkew = 0;
-		pMode->mode.vSyncStart = height;
-		pMode->mode.vSyncEnd = height;
-		pMode->mode.vTotal = height;
-		pMode->mode.dotClock = width * height * rate;
-		sprintf ((char *) (pMode + 1), "%dx%d@%d", width, height, rate);
-		pMode->mode.modeFlags = 0;
-		pMode->mode.nameLength = strlen ((char *) (pMode + 1));
-		pMode->referenced = TRUE;
-		return TRUE;
-	    }
-	    else if (rate == RRVerticalRefresh (&pMode->mode))
-	    {
-		pMode->referenced = TRUE;
-		return TRUE;
-	    }
-	}
-    }
-    
-    sprintf (name, "%dx%d@%d", pSizeMode->mode.width, pSizeMode->mode.height,
-	     rate);
-    modeLine = pSizeMode->mode;
-    modeLine.dotClock = rate * modeLine.vTotal * modeLine.hTotal;
-    modeLine.nameLength = strlen (name);
-    pMode = RRRegisterMode (pMonitor, &modeLine, name);
-    if (!pMode)
+    pNew = xrealloc (pSize->pRates,
+		     (pSize->nRates + 1) * sizeof (RRScreenRate));
+    if (!pNew)
 	return FALSE;
+    pRate = &pNew[pSize->nRates++];
+    pRate->rate = rate;
+    pSize->pRates = pNew;
     return TRUE;
 }
 
 Rotation
 RRGetRotation(ScreenPtr pScreen)
 {
-    rrScrPriv (pScreen);
-    RRMonitorPtr    pMonitor;
+    RROutputPtr	output = RRFirstOutput (pScreen);
 
-    if (!pScrPriv)
+    if (!output)
 	return RR_Rotate_0;
 
-    pMonitor = pScrPriv->pMonitors;
-    if (!pMonitor)
-	return RR_Rotate_0;
-    return pMonitor->rotation;
+    return output->crtc->rotation;
 }
 
 void
@@ -1751,25 +2113,11 @@ RRSetCurrentConfig (ScreenPtr		pScreen,
 		    RRScreenSizePtr	pSize)
 {
     rrScrPriv (pScreen);
-    RRMonitorPtr    pMonitor;
-    RRModePtr	    pMode;
-    RRModePtr	    pSizeMode = (RRModePtr) pSize;
 
     if (!pScrPriv)
 	return;
-    pMonitor = pScrPriv->pMonitors;
-    if (!pMonitor)
-	return;
-
-    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
-    {
-	if (RRModesMatchSize (pMode, pSizeMode) && 
-	    RRVerticalRefresh (&pMode->mode) == rate)
-	    break;
-    }
-    if (!pMode)
-	return;
-    
-    RRSetCurrentMode (pMonitor, pMode, 0, 0, rotation);
+    pScrPriv->size = pSize - pScrPriv->pSizes;
+    pScrPriv->rotation = rotation;
+    pScrPriv->rate = rate;
 }
 #endif
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 3610274..1694523 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -34,71 +34,94 @@
 
 #include <X11/extensions/randrproto.h>
 
+/* required for ABI compatibility for now */
 #define RANDR_SCREEN_INTERFACE 1
 
+typedef XID	RRMode;
+typedef XID	RROutput;
+typedef XID	RRCrtc;
+
 /*
  * Modeline for a monitor. Name follows directly after this struct
  */
 
 #define RRModeName(pMode) ((char *) (pMode + 1))
-
-typedef struct _rrMode {
-    struct _rrMode  *next;
-    Bool	    referenced;
-    Bool	    oldReferenced;
-    int		    id;
-    xRRMonitorMode  mode;
-} RRMode, *RRModePtr;
-
-typedef struct _rrMonitor {
-    struct _rrMonitor	*next;
+typedef struct _rrMode	    RRModeRec, *RRModePtr;
+typedef struct _rrCrtc	    RRCrtcRec, *RRCrtcPtr;
+typedef struct _rrOutput    RROutputRec, *RROutputPtr;
+
+struct _rrMode {
+    RRMode	    id;
+    int		    refcnt;
+    xRRModeInfo	    mode;
+    char	    *name;
+};
+
+struct _rrCrtc {
+    RRCrtc	    id;
     ScreenPtr	    pScreen;
-    RRModePtr	    pModes;
-    void	    *identifier;    /* made unique by DDX */
-    int		    id;		    /* index in list of monitors */
-    Bool	    referenced;
-    Bool	    oldReferenced;
-    Rotation	    rotations;
-    
-    /*
-     * Current state
-     */
-    RRModePtr	    pMode;
+    RRModePtr	    mode;
     int		    x, y;
     Rotation	    rotation;
-} RRMonitor, *RRMonitorPtr;
-
-typedef Bool (*RRSetScreenSizeProcPtr) (ScreenPtr	pScreen,
+    Rotation	    rotations;
+    int		    numPossibleOutputs;
+    RROutputPtr	    *possibleOutputs;
+    Bool	    changed;
+    void	    *devPrivate;
+};
+
+struct _rrOutput {
+    RROutput	    id;
+    ScreenPtr	    pScreen;
+    char	    *name;
+    int		    nameLength;
+    CARD8	    connection;
+    CARD8	    subpixelOrder;
+    RRCrtcPtr	    crtc;
+    int		    numCrtcs;
+    RRCrtcPtr	    *crtcs;
+    int		    numClones;
+    RROutputPtr	    *outputs;
+    int		    numModes;
+    RRModePtr	    *modes;
+    Bool	    changed;
+    void	    *devPrivate;
+};
+
+typedef Bool (*RRScreenSetSizeProcPtr) (ScreenPtr	pScreen,
 					CARD16		width,
 					CARD16		height,
 					CARD32		widthInMM,
 					CARD32		heightInMM);
 					
-typedef Bool (*RRSetModeProcPtr) (ScreenPtr		pScreen,
-				  int			monitor,
-				  RRModePtr		pMode,
+typedef Bool (*RRCrtcSetProcPtr) (ScreenPtr		pScreen,
+				  RRCrtcPtr		crtc,
+				  RRModePtr		mode,
 				  int			x,
 				  int			y,
-				  Rotation		rotation);
+				  Rotation		rotation,
+				  int			numOutput,
+				  RROutputPtr		*outputs);
 
 typedef Bool (*RRGetInfoProcPtr) (ScreenPtr pScreen, Rotation *rotations);
 typedef Bool (*RRCloseScreenProcPtr) ( int i, ScreenPtr pscreen);
 
-
-#ifdef RANDR_SCREEN_INTERFACE
-
+/* These are for 1.0 compatibility */
+ 
 typedef struct _rrRefresh {
-    CARD16	    refresh;
-    RRModePtr	    pMode;
-} RRRefreshRec, *RRRefreshPtr;
+    CARD16	    rate;
+    RRModePtr	    mode;
+} RRScreenRate, *RRScreenRatePtr;
 
 typedef struct _rrScreenSize {
     int		    id;
     short	    width, height;
     short	    mmWidth, mmHeight;
-    int		    nrefresh;
-    RRRefreshPtr    refresh;
-} RRScreenSizeRec, *RRScreenSizePtr;
+    int		    nRates;
+    RRScreenRatePtr pRates;
+} RRScreenSize, *RRScreenSizePtr;
+
+#ifdef RANDR_SCREEN_INTERFACE
 
 typedef Bool (*RRSetConfigProcPtr) (ScreenPtr		pScreen,
 				    Rotation		rotation,
@@ -117,8 +140,8 @@ typedef struct _rrScrPriv {
     RRSetConfigProcPtr	    rrSetConfig;
 #endif
     RRGetInfoProcPtr	    rrGetInfo;
-    RRSetScreenSizeProcPtr  rrSetScreenSize;
-    RRSetModeProcPtr	    rrSetMode;
+    RRScreenSetSizeProcPtr  rrScreenSetSize;
+    RRCrtcSetProcPtr	    rrCrtcSet;
     
     /*
      * Private part of the structure; not considered part of the ABI
@@ -126,20 +149,34 @@ typedef struct _rrScrPriv {
     TimeStamp		    lastSetTime;	/* last changed by client */
     TimeStamp		    lastConfigTime;	/* possible configs changed */
     RRCloseScreenProcPtr    CloseScreen;
+    Bool		    changed;
+    CARD16		    minWidth, minHeight;
+    CARD16		    maxWidth, maxHeight;
 
-    /*
-     * monitor data
-     */
-    RRMonitorPtr	    pMonitors;
+    /* modes, outputs and crtcs */
+    int			    numModes;
+    RRModePtr		    *modes;
+
+    int			    numOutputs;
+    RROutputPtr		    *outputs;
+
+    int			    numCrtcs;
+    RRCrtcPtr		    *crtcs;
 
 #ifdef RANDR_SCREEN_INTERFACE
     /*
      * Configuration information
      */
     Rotation		    rotations;
+    CARD16		    reqWidth, reqHeight;
     
-
+    int			    nSizes;
+    RRScreenSizePtr	    pSizes;
+    
+    RRScreenSizePtr	    pSize;
     Rotation		    rotation;
+    int			    rate;
+    int			    size;
 #endif
 } rrScrPrivRec, *rrScrPrivPtr;
 
@@ -154,33 +191,91 @@ void
 RRExtensionInit (void);
 
 /*
- * Then, register a monitor with the screen
+ * Set the range of sizes for the screen
+ */
+void
+RRScreenSetSizeRange (ScreenPtr	pScreen,
+		      CARD16	minWidth,
+		      CARD16	minHeight,
+		      CARD16	maxWidth,
+		      CARD16	maxHeight);
+
+/*
+ * Create a CRTC
+ */
+RRCrtcPtr
+RRCrtcCreate (ScreenPtr	pScreen,
+	      void	*devPrivate);
+
+
+/*
+ * Use this value for any num parameter to indicate that
+ * the related data are unchanged
  */
+#define RR_NUM_UNCHANGED    -1
 
-RRMonitorPtr
-RRRegisterMonitor (ScreenPtr		pScreen,
-		   void			*identifier,
-		   Rotation		rotations);
+/*
+ * Notify the extension that the Crtc has been reconfigured
+ */
+Bool
+RRCrtcSet (RRCrtcPtr	crtc,
+	   RRModePtr	mode,
+	   int		x,
+	   int		y,
+	   Rotation	rotation,
+	   int		numOutput,
+	   RROutputPtr	*outputs);
+
+/*
+ * Destroy a Crtc at shutdown
+ */
+void
+RRCrtcDestroy (RRCrtcPtr crtc);
 
 /*
- * Next, register the list of modes with the monitor
+ * Find, and if necessary, create a mode
  */
 
 RRModePtr
-RRRegisterMode (RRMonitorPtr	pMonitor,
-		xRRMonitorMode	*pMode,
-		char		*name);
+RRModeGet (ScreenPtr	pScreen,
+	   xRRModeInfo	*modeInfo,
+	   char		*name);
+
+/*
+ * Destroy a mode.
+ */
+
+void
+RRModeDestroy (RRModePtr mode);
 
 /*
- * Finally, set the current configuration of each monitor
+ * Create an output
  */
 
+RROutputPtr
+RROutputCreate (ScreenPtr   pScreen,
+		char	    *name,
+		int	    nameLength,
+		void	    *devPrivate);
+
+/*
+ * Notify extension that output parameters have been changed
+ */
+Bool
+RROutputSet (RROutputPtr    output,
+	     RROutputPtr    *clones,
+	     int	    numClones,
+	     RRModePtr	    *modes,
+	     int	    numModes,
+	     RRCrtcPtr	    *crtcs,
+	     int	    numCrtcs,
+	     CARD8	    connection);
+
+void
+RROutputDestroy (RROutputPtr	output);
+
 void
-RRSetCurrentMode (RRMonitorPtr	pMonitor,
-		  RRModePtr	pMode,
-		  int		x,
-		  int		y,
-		  Rotation	rotation);
+RRTellChanged (ScreenPtr pScreen);
 
 Bool RRScreenInit(ScreenPtr pScreen);
 
@@ -197,12 +292,14 @@ Bool
 miRRGetScreenInfo (ScreenPtr pScreen);
 
 Bool
-miRRSetMode (ScreenPtr	pScreen,
-	     int	monitor,
-	     RRModePtr	pMode,
+miRRCrtcSet (ScreenPtr	pScreen,
+	     RRCrtcPtr	crtc,
+	     RRModePtr	mode,
 	     int	x,
 	     int	y,
-	     Rotation	rotation);
+	     Rotation	rotation,
+	     int	numOutput,
+	     RROutputPtr    *outputs);
 
 #ifdef RANDR_SCREEN_INTERFACE					
 /*
@@ -225,9 +322,6 @@ Bool RRRegisterRate (ScreenPtr		pScreen,
 		     RRScreenSizePtr	pSize,
 		     int		rate);
 
-Bool RRRegisterRotation (ScreenPtr	pScreen,
-			 Rotation	rotation);
-
 /*
  * Finally, set the current configuration of the screen
  */
@@ -238,17 +332,16 @@ RRSetCurrentConfig (ScreenPtr		pScreen,
 		    int			rate,
 		    RRScreenSizePtr	pSize);
 
+Bool RRScreenInit (ScreenPtr pScreen);
+
+Rotation
+RRGetRotation (ScreenPtr pScreen);
+
 int
 RRSetScreenConfig (ScreenPtr		pScreen,
 		   Rotation		rotation,
 		   int			rate,
 		   RRScreenSizePtr	pSize);
 
-Bool
-miRRSetConfig (ScreenPtr	pScreen,
-	       Rotation		rotation,
-	       int		rate,
-	       RRScreenSizePtr	size);
-
 #endif					
 #endif /* _RANDRSTR_H_ */
commit fbaeb0b2a1e0ad29b8d284045a9a60cd873f2edb
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Mon Jul 17 14:43:07 2006 -0400

    Successful legacy RandR API/Protocol emulation for query.
    
    These changes clean up minor errors to make it possible to list the
    available modes for a monitor using legacy APIs in both the X server DDX and
    RandR protocol. Setting modes is untested, so it probably doesn't work.

diff --git a/randr/randr.c b/randr/randr.c
index 4a5cd4e..58d8f17 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -542,6 +542,7 @@ RRGetInfo (ScreenPtr pScreen)
 		    pMode->id = modeid++;
 		    if (!pMode->oldReferenced)
 			changed = TRUE;
+		    pPrevMode = &pMode->next;
 		}
 		else
 		{
@@ -550,6 +551,7 @@ RRGetInfo (ScreenPtr pScreen)
 		    RRFreeMode (pMode);
 		}
 	    }
+	    pPrevMon = &pMonitor->next;
 	}
 	else
 	{
@@ -716,6 +718,7 @@ RR10GetData (ScreenPtr pScreen, RRMonitorPtr pMonitor)
 	return NULL;
     size = (RRScreenSizePtr) (data + 1);
     refresh = (RRRefreshPtr) (size + nmode);
+    data->sizes = size;
     data->nsize = 0;
     data->nrefresh = 0;
     data->size = 0;
@@ -728,6 +731,7 @@ RR10GetData (ScreenPtr pScreen, RRMonitorPtr pMonitor)
 		break;
 	if (i == data->nsize)
 	{
+	    size[i].id = i;
 	    size[i].width = pMode->mode.width;
 	    size[i].height = pMode->mode.height;
 	    size[i].mmWidth = pMode->mode.widthInMillimeters;
@@ -823,7 +827,7 @@ ProcRRGetScreenInfo (ClientPtr client)
 	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
 	rep.rotation = pMonitor->rotation;
 	rep.nSizes = pData->nsize;
-        rep.nrateEnts = pData->nrefresh;
+        rep.nrateEnts = pData->nrefresh + pData->nsize;
 	rep.sizeID = pData->size;
 	rep.rate = pData->refresh;
 
@@ -904,6 +908,97 @@ ProcRRGetScreenInfo (ClientPtr client)
 }
 
 static int
+RRMonitorSetMode (ScreenPtr pScreen, RRMonitorPtr pMonitor, 
+		  RRModePtr pMode, int x, int y, Rotation rotation,
+		  TimeStamp time)
+{
+    rrScrPriv(pScreen);
+    short   oldWidth, oldHeight;
+    
+    oldWidth = pScreen->width;
+    oldHeight = pScreen->height;
+    
+    /*
+     * call out to ddx routine to effect the change
+     */
+    if (pScrPriv->rrSetScreenSize && pScrPriv->rrSetMode)
+    {
+	xScreenSizes	oldSize;
+	if (!(*pScrPriv->rrSetMode) (pScreen, 0, NULL, 0, 0, RR_Rotate_0))
+	    return RRSetConfigFailed;
+	oldSize.widthInPixels = pScreen->width;
+	oldSize.heightInPixels = pScreen->width;
+	oldSize.widthInMillimeters = pScreen->mmWidth;
+	oldSize.heightInMillimeters = pScreen->mmHeight;
+	if (!(*pScrPriv->rrSetScreenSize) (pScreen,
+					   pMode->mode.width,
+					   pMode->mode.height,
+					   pMode->mode.widthInMillimeters,
+					   pMode->mode.heightInMillimeters))
+	{
+	    (void) (*pScrPriv->rrSetMode) (pScreen, 0, pMonitor->pMode,
+					   pMonitor->x, pMonitor->y,
+					   pMonitor->rotation);
+	    return RRSetConfigFailed;
+	}
+	if (!(*pScrPriv->rrSetMode) (pScreen, 0, pMode, 0, 0, rotation))
+	{
+	    (void) (*pScrPriv->rrSetScreenSize) (pScreen,
+						 oldSize.widthInPixels,
+						 oldSize.heightInPixels,
+						 oldSize.widthInMillimeters,
+						 oldSize.heightInMillimeters);
+	    (void) (*pScrPriv->rrSetMode) (pScreen, 0, pMonitor->pMode,
+					   pMonitor->x, pMonitor->y,
+					   pMonitor->rotation);
+	    return RRSetConfigFailed;
+	}
+    }
+#ifdef RANDR_SCREEN_INTERFACE
+    else if (pScrPriv->rrSetConfig)
+    {
+	int rate = RRVerticalRefresh (&pMode->mode);
+	RRScreenSizeRec	size;
+
+	size.width = pMode->mode.width;
+	size.height = pMode->mode.height;
+	size.mmWidth = pMode->mode.widthInMillimeters;
+	size.mmHeight = pMode->mode.heightInMillimeters;
+	if (!(*pScrPriv->rrSetConfig) (pScreen, rotation, rate, &size))
+	    return RRSetConfigFailed;
+    }
+#endif
+    else
+	return RRSetConfigFailed;
+    
+    /*
+     * set current extension configuration pointers
+     */
+    RRSetCurrentMode (pMonitor, pMode, 0, 0, rotation);
+    
+    /*
+     * Deliver ScreenChangeNotify events whenever
+     * the configuration is updated
+     */
+    WalkTree (pScreen, TellChanged, (pointer) pScreen);
+    
+    /*
+     * Deliver ConfigureNotify events when root changes
+     * pixel size
+     */
+    if (oldWidth != pScreen->width || oldHeight != pScreen->height)
+	RRSendConfigNotify (pScreen);
+    RREditConnectionInfo (pScreen);
+    
+    /*
+     * Fix pointer bounds and location
+     */
+    ScreenRestructured (pScreen);
+    pScrPriv->lastSetTime = time;
+    return RRSetConfigSuccess;
+}
+
+static int
 ProcRRSetScreenConfig (ClientPtr client)
 {
     REQUEST(xRRSetScreenConfigReq);
@@ -917,7 +1012,6 @@ ProcRRSetScreenConfig (ClientPtr client)
     int			    i;
     Rotation		    rotation;
     int			    rate;
-    short		    oldWidth, oldHeight;
     Bool		    has_rate;
     RRMonitorPtr	    pMonitor;
     RRModePtr		    pMode;
@@ -947,9 +1041,6 @@ ProcRRSetScreenConfig (ClientPtr client)
     time = ClientTimeToServerTime(stuff->timestamp);
     configTime = ClientTimeToServerTime(stuff->configTimestamp);
     
-    oldWidth = pScreen->width;
-    oldHeight = pScreen->height;
-    
     if (!pScrPriv)
     {
 	time = currentTime;
@@ -1063,90 +1154,7 @@ ProcRRSetScreenConfig (ClientPtr client)
 	goto sendReply;
     }
 
-    /*
-     * call out to ddx routine to effect the change
-     */
-    if (pScrPriv->rrSetScreenSize && pScrPriv->rrSetMode)
-    {
-	xScreenSizes	oldSize;
-	if (!(*pScrPriv->rrSetMode) (pScreen, 0, NULL, 0, 0, RR_Rotate_0))
-	    goto fail;
-	oldSize.widthInPixels = pScreen->width;
-	oldSize.heightInPixels = pScreen->width;
-	oldSize.widthInMillimeters = pScreen->mmWidth;
-	oldSize.heightInMillimeters = pScreen->mmHeight;
-	if (!(*pScrPriv->rrSetScreenSize) (pScreen,
-					   pMode->mode.width,
-					   pMode->mode.height,
-					   pMode->mode.widthInMillimeters,
-					   pMode->mode.heightInMillimeters))
-	{
-	    (void) (*pScrPriv->rrSetMode) (pScreen, 0, pMonitor->pMode,
-					   pMonitor->x, pMonitor->y,
-					   pMonitor->rotation);
-	    goto fail;
-	}
-	if (!(*pScrPriv->rrSetMode) (pScreen, 0, pMode, 0, 0, rotation))
-	{
-	    (void) (*pScrPriv->rrSetScreenSize) (pScreen,
-						 oldSize.widthInPixels,
-						 oldSize.heightInPixels,
-						 oldSize.widthInMillimeters,
-						 oldSize.heightInMillimeters);
-	    (void) (*pScrPriv->rrSetMode) (pScreen, 0, pMonitor->pMode,
-					   pMonitor->x, pMonitor->y,
-					   pMonitor->rotation);
-	    goto fail;
-	}
-    }
-#ifdef RANDR_SCREEN_INTERFACE
-    else if (pScrPriv->rrSetConfig)
-    {
-	if (!(*pScrPriv->rrSetConfig) (pScreen, rotation, rate, pSize))
-	{
-	    goto fail;
-	}
-    }
-#endif
-    else
-    {
-fail:	;
-	/*
-	 * unknown DDX failure, report to client
-	 */
-	rep.status = RRSetConfigFailed;
-	goto sendReply;
-    }
-    
-    /*
-     * set current extension configuration pointers
-     */
-    RRSetCurrentMode (pMonitor, pMode, 0, 0, rotation);
-    
-    /*
-     * Deliver ScreenChangeNotify events whenever
-     * the configuration is updated
-     */
-    WalkTree (pScreen, TellChanged, (pointer) pScreen);
-    
-    /*
-     * Deliver ConfigureNotify events when root changes
-     * pixel size
-     */
-    if (oldWidth != pScreen->width || oldHeight != pScreen->height)
-	RRSendConfigNotify (pScreen);
-    RREditConnectionInfo (pScreen);
-    
-    /*
-     * Fix pointer bounds and location
-     */
-    ScreenRestructured (pScreen);
-    pScrPriv->lastSetTime = time;
-    
-    /*
-     * Report Success
-     */
-    rep.status = RRSetConfigSuccess;
+    rep.status = RRMonitorSetMode (pScreen, pMonitor, pMode, 0, 0, rotation, time);
     
 sendReply:
     
@@ -1182,11 +1190,20 @@ RRSetScreenConfig (ScreenPtr		pScreen,
 		   RRScreenSizePtr	pSize)
 {
     rrScrPrivPtr	    pScrPriv;
-    int			    i;
+    RRMonitorPtr	    pMonitor;
     short		    oldWidth, oldHeight;
+    RRModePtr		    pMode;
+    int			    status;
 
     pScrPriv = rrGetScrPriv(pScreen);
     
+    if (!pScrPriv)
+	return BadImplementation;
+    
+    pMonitor = pScrPriv->pMonitors;
+    if (!pMonitor)
+	return BadImplementation;
+
     oldWidth = pScreen->width;
     oldHeight = pScreen->height;
     
@@ -1219,61 +1236,24 @@ RRSetScreenConfig (ScreenPtr		pScreen,
 	return BadMatch;
     }
 
-    /*
-     * Validate requested refresh
-     */
-    if (rate)
+    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
     {
-	for (i = 0; i < pSize->nRates; i++)
-	{
-	    RRScreenRatePtr pRate = &pSize->pRates[i];
-	    if (pRate->referenced && pRate->rate == rate)
-		break;
-	}
-	if (i == pSize->nRates)
+	if (pMode->mode.width == pSize->width &&
+	    pMode->mode.height == pSize->height &&
+	    pMode->mode.widthInMillimeters == pSize->mmWidth &&
+	    pMode->mode.heightInMillimeters == pSize->mmHeight &&
+	    (RRVerticalRefresh (&pMode->mode) == rate || rate == 0))
 	{
-	    /*
-	     * Invalid rate
-	     */
-	    return BadValue;
+	    break;
 	}
     }
-
-    /*
-     * call out to ddx routine to effect the change
-     */
-    if (!(*pScrPriv->rrSetConfig) (pScreen, rotation, rate,
-				   pSize))
-    {
-	/*
-	 * unknown DDX failure, report to client
-	 */
-        return BadImplementation;
-    }
-    
-    /*
-     * set current extension configuration pointers
-     */
-    RRSetCurrentMode (pMonitor, pMode, 0, 0, rotation);
-    
-    /*
-     * Deliver ScreenChangeNotify events whenever
-     * the configuration is updated
-     */
-    WalkTree (pScreen, TellChanged, (pointer) pScreen);
-    
-    /*
-     * Deliver ConfigureNotify events when root changes
-     * pixel size
-     */
-    if (oldWidth != pScreen->width || oldHeight != pScreen->height)
-	RRSendConfigNotify (pScreen);
-    RREditConnectionInfo (pScreen);
+    if (!pMode)
+	return BadValue;
     
-    /*
-     * Fix pointer bounds and location
-     */
-    ScreenRestructured (pScreen);
+    status = RRMonitorSetMode (pScreen, pMonitor, pMode, 0, 0, 
+			       rotation, currentTime);
+    if (status != RRSetConfigSuccess)
+	return BadImplementation;
     return Success;
 }
 
@@ -1387,23 +1367,63 @@ ProcRRSelectInput (ClientPtr client)
 }
 
 
+static int ProcRRGetScreenSizeRange (ClientPtr pClient)
+{
+    return BadImplementation;
+}
+
+static int ProcRRSetScreenSize (ClientPtr pClient)
+{
+    return BadImplementation;
+}
+
+static int ProcRRGetMonitorInfo (ClientPtr pClient)
+{
+    return BadImplementation;
+}
+
+static int ProcRRAddMonitorMode (ClientPtr pClient)
+{
+    return BadImplementation;
+}
+
+static int ProcRRDeleteMonitorMode (ClientPtr pClient)
+{
+    return BadImplementation;
+}
+
+static int ProcRRSetMonitorConfig (ClientPtr pClient)
+{
+    return BadImplementation;
+}
+
+int (*ProcRandrVector[RRNumberRequests])(ClientPtr) = {
+    ProcRRQueryVersion,	/* 0 */
+/* we skip 1 to make old clients fail pretty immediately */
+    NULL,			/* 1 ProcRandrOldGetScreenInfo */
+/* V1.0 apps share the same set screen config request id */
+    ProcRRSetScreenConfig,	/* 2 */
+    NULL,			/* 3 ProcRandrOldScreenChangeSelectInput */
+/* 3 used to be ScreenChangeSelectInput; deprecated */
+    ProcRRSelectInput,		/* 4 */
+    ProcRRGetScreenInfo,    	/* 5 */
+/* V1.2 additions */
+    ProcRRGetScreenSizeRange,	/* 6 */
+    ProcRRSetScreenSize,	/* 7 */
+    ProcRRGetMonitorInfo,	/* 8 */
+    ProcRRAddMonitorMode,	/* 9 */
+    ProcRRDeleteMonitorMode,	/* 10 */
+    ProcRRSetMonitorConfig,	/* 11 */
+};
+
+
 static int
 ProcRRDispatch (ClientPtr client)
 {
     REQUEST(xReq);
-    switch (stuff->data)
-    {
-    case X_RRQueryVersion:
-	return ProcRRQueryVersion(client);
-    case X_RRSetScreenConfig:
-        return ProcRRSetScreenConfig(client);
-    case X_RRSelectInput:
-        return ProcRRSelectInput(client);
-    case X_RRGetScreenInfo:
-        return ProcRRGetScreenInfo(client);
-    default:
+    if (stuff->data >= RRNumberRequests || !ProcRandrVector[stuff->data])
 	return BadRequest;
-    }
+    return (*ProcRandrVector[stuff->data]) (client);
 }
 
 static int
@@ -1609,7 +1629,12 @@ RRRegisterSize (ScreenPtr	    pScreen,
 	return NULL;
     pMonitor = pScrPriv->pMonitors;
     if (!pMonitor)
-	return NULL;
+    {
+	pMonitor = RRRegisterMonitor (pScreen, NULL, RR_Rotate_0);
+	if (!pMonitor)
+	    return NULL;
+    }
+    pMonitor->referenced = TRUE;
     
     for (pPrev = &pMonitor->pModes; (pMode = *pPrev); pPrev = &(pMode->next))
 	if (pMode->mode.width == width &&
commit 10b0c7d5e49329b59b1fe66bbeb12fa4371dbaab
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Mon Jul 17 01:21:11 2006 -0400

    RandR: New data structure, old API. At least it compiles now

diff --git a/randr/mirandr.c b/randr/mirandr.c
index 7bef02d..e152133 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -65,11 +65,11 @@ miRRGetInfo (ScreenPtr pScreen, Rotation *rotations)
 	    rrMode.height = pScreen->height;
 	    rrMode.widthInMillimeters = pScreen->mmWidth;
 	    rrMode.heightInMillimeters = pScreen->mmHeight;
-	    pMonitor = RRRegisterMonitor (pScreen, RR_Rotate_0);
+	    rrMode.nameLength = strlen (name);
+	    pMonitor = RRRegisterMonitor (pScreen, NULL, RR_Rotate_0);
 	    pMode = RRRegisterMode (pMonitor,
 				    &rrMode,
-				    name,
-				    strlen (name));
+				    name);
 	    if (!pMode)
 		return FALSE;
 	    if (!setConfig)
@@ -90,6 +90,8 @@ Bool
 miRRSetMode (ScreenPtr	pScreen,
 	     int	monitor,
 	     RRModePtr	pMode,
+	     int	x,
+	     int	y,
 	     Rotation	rotation)
 {
     return TRUE;
diff --git a/randr/randr.c b/randr/randr.c
index 1a9624a..4a5cd4e 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -163,12 +163,12 @@ RRCloseScreen (int i, ScreenPtr pScreen)
     RRMonitorPtr    pMonitor;
 
     unwrap (pScrPriv, pScreen, CloseScreen);
-    while (pMonitor = pScrPriv->pMonitors) 
+    while ((pMonitor = pScrPriv->pMonitors))
     {
 	RRModePtr   pMode;
 	
 	pScrPriv->pMonitors = pMonitor->next;
-	while (pMode = pMonitor->pModes) 
+	while ((pMode = pMonitor->pModes))
 	{
 	    pMonitor->pModes = pMode->next;
 	    xfree (pMode);
@@ -218,6 +218,20 @@ SRRMonitorChangeNotifyEvent(xRRMonitorChangeNotifyEvent *from,
     cpswaps(from->y, to->y);
 }
 
+static void
+SRRNotifyEvent (xEvent *from,
+		xEvent *to)
+{
+    switch (from->u.u.detail) {
+    case RRNotify_MonitorChange:
+	SRRMonitorChangeNotifyEvent ((xRRMonitorChangeNotifyEvent *) from,
+				     (xRRMonitorChangeNotifyEvent *) to);
+	break;
+    default:
+	break;
+    }
+}
+
 Bool RRScreenInit(ScreenPtr pScreen)
 {
     rrScrPrivPtr   pScrPriv;
@@ -336,6 +350,8 @@ RRExtensionInit (void)
     RREventBase = extEntry->eventBase;
     EventSwapVector[RREventBase + RRScreenChangeNotify] = (EventSwapPtr) 
       SRRScreenChangeNotifyEvent;
+    EventSwapVector[RREventBase + RRNotify] = (EventSwapPtr)
+	SRRNotifyEvent;
 
     return;
 }
@@ -349,8 +365,8 @@ TellChanged (WindowPtr pWin, pointer value)
     xRRMonitorChangeNotifyEvent	me;
     ScreenPtr			pScreen = pWin->drawable.pScreen;
     rrScrPriv(pScreen);
-    RRMonitorPtr		pMonitor = pScrPriv->pMonitors;
     RRModePtr			pMode;
+    RRMonitorPtr		pMonitor;
     WindowPtr			pRoot = WindowTable[pScreen->myNum];
     int				i;
 
@@ -364,7 +380,7 @@ TellChanged (WindowPtr pWin, pointer value)
 	if (client == serverClient || client->clientGone)
 	    continue;
 
-	if (pRREvent->mask & RRMonitorChangeNotifyMask)) 
+	if (pRREvent->mask & RRMonitorChangeNotifyMask)
 	{
 	    me.type = RRNotify + RREventBase;
 	    me.subCode = RRNotify_MonitorChange;
@@ -377,12 +393,13 @@ TellChanged (WindowPtr pWin, pointer value)
 #else
 	    me.subpixelOrder = SubPixelUnknown;
 #endif
-	    for (i = 0; i < pScrPriv->nMonitors; i++) 
+	    for (pMonitor = pScrPriv->pMonitors, i = 0; 
+		 pMonitor; 
+		 pMonitor = pMonitor->next, i++)
 	    {
-		pMonitor = &pScrPriv->pMonitors[i];
 		me.monitor = i;
-		if (pMonitor->mode >= 0) {
-		    me.modeID = pMonitor->pMode[pMonitor->mode].id;
+		if (pMonitor->pMode) {
+		    me.modeID = pMonitor->pMode->id;
 		    me.rotation = pMonitor->rotation;
 		    me.x = pMonitor->x;
 		    me.y = pMonitor->y;
@@ -396,10 +413,10 @@ TellChanged (WindowPtr pWin, pointer value)
 	    }
 	}
 	if ((pRREvent->mask & RRScreenChangeNotifyMask) &&
-	    pScrPriv->nMonitors > 0)
+	    (pMonitor = pScrPriv->pMonitors))
 	{
 	    se.type = RRScreenChangeNotify + RREventBase;
-	    se.rotation = (CARD8) pScrPriv->rotation;
+	    se.rotation = (CARD8) pMonitor->rotation;
 	    se.timestamp = pScrPriv->lastSetTime.milliseconds;
 	    se.sequenceNumber = client->sequence;
 	    se.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
@@ -413,14 +430,14 @@ TellChanged (WindowPtr pWin, pointer value)
 
 	    pMonitor = &pScrPriv->pMonitors[0];
 	    se.sequenceNumber = client->sequence;
-	    if (pMonitor->mode >= 0) 
+	    if (pMonitor->pMode) 
 	    {
-		pMode = &pMonitor->pModes[pMonitor->mode];
+		pMode = pMonitor->pMode;
 		se.sizeID = pMode->id;
-		se.widthInPixels = pMode->width;
-		se.heightInPixels = pMode->height;
-		se.widthInMillimeters = pMode->mmWidth;
-		se.heightInMillimeters = pMode->mmHeight;
+		se.widthInPixels = pMode->mode.width;
+		se.heightInPixels = pMode->mode.height;
+		se.widthInMillimeters = pMode->mode.widthInMillimeters;
+		se.heightInMillimeters = pMode->mode.heightInMillimeters;
 	    }
 	    else
 	    {
@@ -440,70 +457,107 @@ TellChanged (WindowPtr pWin, pointer value)
     return WT_WALKCHILDREN;
 }
 
+static void
+RRFreeMode (RRModePtr pMode)
+{
+    xfree (pMode);
+}
+
+static void
+RRFreeModes (RRModePtr pHead)
+{
+    RRModePtr	pMode;
+    while ((pMode = pHead)) 
+    {
+	pHead = pMode->next;
+	RRFreeMode (pMode);
+    }
+}
+
+static void
+RRFreeMonitor (RRMonitorPtr pMonitor)
+{
+    RRFreeModes (pMonitor->pModes);
+    xfree (pMonitor);
+}
+
+
 static Bool
 RRGetInfo (ScreenPtr pScreen)
 {
     rrScrPriv (pScreen);
-    int		    m, s, n;
     Bool	    changed;
     Rotation	    rotations;
-    RRMonitorPtr    pMonitor;
-    RRModePtr	    pMode;
+    RRMonitorPtr    pMonitor, *pPrevMon;
+    RRModePtr	    pMode, *pPrevMode;
+    int		    monitorid;
 
-    for (m = 0; m < pScrPriv->nMonitors; m++)
+    for (pMonitor = pScrPriv->pMonitors; pMonitor; pMonitor = pMonitor->next)
     {
-	pMonitor = &pScrPriv->pMonitors[m];
-	pMonitor->oldReferenced = pMonitor->referenced;
+	pMonitor->oldReferenced = TRUE;
 	pMonitor->referenced = FALSE;
-	for (s = 0; s < pMonitor->nModes; s++)
+	pMonitor->pMode = NULL;
+	for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
 	{
-	    pMode = &pSize->pModes[s];
-	    pMode->oldReferenced = pMode->referenced;
+	    pMode->oldReferenced = TRUE;
 	    pMode->referenced = FALSE;
 	}
     }
-    changed = FALSE;
-
     rotations = 0;
     if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
 	return FALSE;
+
+    changed = FALSE;
     
     /* Old GetInfo clients return rotations here */
-    if (rotations && pScrPriv->nMonitors) {
+    if (rotations && pScrPriv->pMonitors) {
 	/*
 	 * Check whether anything changed and simultaneously generate
 	 * the protocol id values for the objects
 	 */
-	if (rotations != pScrPriv->pMonitors[i].rotations)
+	if (rotations != pScrPriv->pMonitors->rotations)
 	{
-	    pScrPriv->pMonitors[i].rotations = rotations;
+	    pScrPriv->pMonitors->rotations = rotations;
 	    changed = TRUE;
 	}
     }
 	
-    n = 0;
-    for (m = 0; m < pScrPriv->nMonitors; m++)
+    /*
+     * Walk monitor and mode lists looking for updates
+     */
+    monitorid = 0;
+    for (pPrevMon = &pScrPriv->pMonitors; (pMonitor = *pPrevMon);)
     {
 	int modeid = 0;
 	
-	pMonitor = &pScrPriv->pMonitors[m];
-	if (pMonitor->oldReferenced != pMonitor->referenced)
-	    changed = TRUE;
 	if (pMonitor->referenced)
 	{
-	    for (s = 0; s < pMonitor->nModes; s++)
+	    pMonitor->id = monitorid++;
+	    if (!pMonitor->oldReferenced)
+		changed = TRUE;
+	    for (pPrevMode = &pMonitor->pModes; (pMode = *pPrevMode);)
 	    {
-		pMode = &pMonitor->pModes[s];
-		if (pMode->oldReferenced != pMode->referenced)
-		    changed = TRUE;
 		if (pMode->referenced)
+		{
 		    pMode->id = modeid++;
+		    if (!pMode->oldReferenced)
+			changed = TRUE;
+		}
+		else
+		{
+		    *pPrevMode = pMode->next;
+		    changed = TRUE;
+		    RRFreeMode (pMode);
+		}
 	    }
-	    n++;
 	}
-	pMonitor->nModesInUse = modeid;
+	else
+	{
+	    *pPrevMon = pMonitor->next;
+	    changed = TRUE;
+	    RRFreeMonitor (pMonitor);
+	}
     }
-    pScrPriv->nMonitorsInUse = n;
     if (changed)
     {
 	UpdateCurrentTime ();
@@ -548,6 +602,10 @@ ProcRRQueryVersion (ClientPtr client)
     rep.type = X_Reply;
     rep.length = 0;
     rep.sequenceNumber = client->sequence;
+    /*
+     * Report the current version; the current
+     * spec says they're all compatible after 1.0
+     */
     rep.majorVersion = RANDR_MAJOR;
     rep.minorVersion = RANDR_MINOR;
     if (client->swapped) {
@@ -605,6 +663,100 @@ RREditConnectionInfo (ScreenPtr pScreen)
 }
 
 static int
+RRNumModes (RRMonitorPtr pMonitor)
+{
+    int	n = 0;
+    RRModePtr	pMode;
+
+    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
+	n++;
+    return n;
+}
+
+typedef struct _RR10Data {
+    RRScreenSizePtr sizes;
+    int		    nsize;
+    int		    nrefresh;
+    int		    size;
+    CARD16	    refresh;
+} RR10DataRec, *RR10DataPtr;
+
+static CARD16
+RRVerticalRefresh (xRRMonitorMode *mode)
+{
+    CARD32  refresh;
+    if (!mode->hTotal || !mode->vTotal)
+	return 0;
+    refresh = mode->dotClock / (mode->hTotal * mode->vTotal);
+    if (refresh > 0xffff)
+	refresh = 0xffff;
+    return (CARD16) refresh;
+}
+
+/*
+ * Convert 1.2 monitor data into 1.0 screen data
+ */
+static RR10DataPtr
+RR10GetData (ScreenPtr pScreen, RRMonitorPtr pMonitor)
+{
+    RR10DataPtr	    data;
+    RRScreenSizePtr size;
+    int		    nmode = RRNumModes (pMonitor);
+    int		    i;
+    int		    j;
+    RRRefreshPtr    refresh;
+    CARD16	    vRefresh;
+    RRModePtr	    pMode;
+
+    /* Make sure there is plenty of space for any combination */
+    data = malloc (sizeof (RR10DataRec) + 
+		   sizeof (RRScreenSizeRec) * nmode + 
+		   sizeof (RRRefreshRec) * nmode);
+    if (!data)
+	return NULL;
+    size = (RRScreenSizePtr) (data + 1);
+    refresh = (RRRefreshPtr) (size + nmode);
+    data->nsize = 0;
+    data->nrefresh = 0;
+    data->size = 0;
+    data->refresh = 0;
+    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
+    {
+	for (i = 0; i < data->nsize; i++)
+	    if (pMode->mode.width == size[i].width &&
+		pMode->mode.height == size[i].height)
+		break;
+	if (i == data->nsize)
+	{
+	    size[i].width = pMode->mode.width;
+	    size[i].height = pMode->mode.height;
+	    size[i].mmWidth = pMode->mode.widthInMillimeters;
+	    size[i].mmHeight = pMode->mode.heightInMillimeters;
+	    size[i].nrefresh = 0;
+	    size[i].refresh = &refresh[data->nrefresh];
+	    data->nsize++;
+	}
+	vRefresh = RRVerticalRefresh (&pMode->mode);
+	for (j = 0; j < size[i].nrefresh; j++)
+	    if (vRefresh == size[i].refresh[j].refresh)
+		break;
+	if (j == size[i].nrefresh)
+	{
+	    size[i].refresh[j].refresh = vRefresh;
+	    size[i].refresh[j].pMode = pMode;
+	    size[i].nrefresh++;
+	    data->nrefresh++;
+	}
+	if (pMode == pMonitor->pMode)
+	{
+	    data->size = i;
+	    data->refresh = vRefresh;
+	}
+    }
+    return data;
+}
+
+static int
 ProcRRGetScreenInfo (ClientPtr client)
 {
     REQUEST(xRRGetScreenInfoReq);
@@ -626,7 +778,11 @@ ProcRRGetScreenInfo (ClientPtr client)
     pScreen = pWin->drawable.pScreen;
     pScrPriv = rrGetScrPriv(pScreen);
     rep.pad = 0;
-    if (!pScrPriv)
+    
+    if (pScrPriv)
+	RRGetInfo (pScreen);
+
+    if (!pScrPriv && !pScrPriv->pMonitors)
     {
 	rep.type = X_Reply;
 	rep.setOfRotations = RR_Rotate_0;;
@@ -645,94 +801,82 @@ ProcRRGetScreenInfo (ClientPtr client)
     }
     else
     {
+	RRMonitorPtr		pMonitor = pScrPriv->pMonitors;
 	int			i, j;
 	xScreenSizes		*size;
 	CARD16			*rates;
 	CARD8			*data8;
 	Bool			has_rate = RRClientKnowsRates (client);
+	RR10DataPtr		pData;
+	RRScreenSizePtr		pSize;
     
-	RRGetInfo (pScreen);
-
+	pData = RR10GetData (pScreen, pMonitor);
+	if (!pData)
+	    return BadAlloc;
+	
 	rep.type = X_Reply;
-	rep.setOfRotations = pScrPriv->rotations;
+	rep.setOfRotations = pMonitor->rotations;
 	rep.sequenceNumber = client->sequence;
 	rep.length = 0;
 	rep.root = WindowTable[pWin->drawable.pScreen->myNum]->drawable.id;
 	rep.timestamp = pScrPriv->lastSetTime.milliseconds;
 	rep.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
-	rep.rotation = pScrPriv->rotation;
-	rep.nSizes = pScrPriv->nSizesInUse;
-	rep.rate = pScrPriv->rate;
-        rep.nrateEnts = 0;
-	if (has_rate)
-	{
-	    for (i = 0; i < pScrPriv->nSizes; i++)
-	    {
-		RRScreenSizePtr pSize = &pScrPriv->pSizes[i];
-		if (pSize->referenced)
-		{
-		    rep.nrateEnts += (1 + pSize->nRatesInUse);
-		}
-	    }
-	}
-
-	if (pScrPriv->size >= 0)
-	    rep.sizeID = pScrPriv->pSizes[pScrPriv->size].id;
-	else
-	    return BadImplementation;
+	rep.rotation = pMonitor->rotation;
+	rep.nSizes = pData->nsize;
+        rep.nrateEnts = pData->nrefresh;
+	rep.sizeID = pData->size;
+	rep.rate = pData->refresh;
 
 	extraLen = (rep.nSizes * sizeof (xScreenSizes) +
 		    rep.nrateEnts * sizeof (CARD16));
 
 	extra = (CARD8 *) xalloc (extraLen);
 	if (!extra)
+	{
+	    xfree (pData);
 	    return BadAlloc;
+	}
 	/*
 	 * First comes the size information
 	 */
 	size = (xScreenSizes *) extra;
 	rates = (CARD16 *) (size + rep.nSizes);
-	for (i = 0; i < pScrPriv->nSizes; i++)
+	for (i = 0; i < pData->nsize; i++)
 	{
-	    RRScreenSizePtr pSize = &pScrPriv->pSizes[i];
-	    if (pSize->referenced)
+	    pSize = &pData->sizes[i];
+	    size->widthInPixels = pSize->width;
+	    size->heightInPixels = pSize->height;
+	    size->widthInMillimeters = pSize->mmWidth;
+	    size->heightInMillimeters = pSize->mmHeight;
+	    if (client->swapped)
+	    {
+	        swaps (&size->widthInPixels, n);
+	        swaps (&size->heightInPixels, n);
+	        swaps (&size->widthInMillimeters, n);
+	        swaps (&size->heightInMillimeters, n);
+	    }
+	    size++;
+	    if (has_rate)
 	    {
-		size->widthInPixels = pSize->width;
-		size->heightInPixels = pSize->height;
-		size->widthInMillimeters = pSize->mmWidth;
-		size->heightInMillimeters = pSize->mmHeight;
+		*rates = pSize->nrefresh;
 		if (client->swapped)
 		{
-		    swaps (&size->widthInPixels, n);
-		    swaps (&size->heightInPixels, n);
-		    swaps (&size->widthInMillimeters, n);
-		    swaps (&size->heightInMillimeters, n);
+		    swaps (rates, n);
 		}
-		size++;
-		if (has_rate)
+		rates++;
+		for (j = 0; j < pSize->nrefresh; j++)
 		{
-		    *rates = pSize->nRatesInUse;
+		    *rates = pSize->refresh[j].refresh;
 		    if (client->swapped)
 		    {
 			swaps (rates, n);
 		    }
 		    rates++;
-		    for (j = 0; j < pSize->nRates; j++)
-		    {
-			RRScreenRatePtr	pRate = &pSize->pRates[j];
-			if (pRate->referenced)
-			{
-			    *rates = pRate->rate;
-			    if (client->swapped)
-			    {
-				swaps (rates, n);
-			    }
-			    rates++;
-			}
-		    }
 		}
 	    }
 	}
+        xfree (pData);
+	
 	data8 = (CARD8 *) rates;
 
 	if (data8 - (CARD8 *) extra != extraLen)
@@ -770,13 +914,16 @@ ProcRRSetScreenConfig (ClientPtr client)
     rrScrPrivPtr	    pScrPriv;
     TimeStamp		    configTime;
     TimeStamp		    time;
-    RRScreenSizePtr	    pSize;
     int			    i;
     Rotation		    rotation;
     int			    rate;
     short		    oldWidth, oldHeight;
     Bool		    has_rate;
-
+    RRMonitorPtr	    pMonitor;
+    RRModePtr		    pMode;
+    RR10DataPtr		    pData = NULL;
+    RRScreenSizePtr    	    pSize;
+    
     UpdateCurrentTime ();
 
     if (RRClientKnowsRates (client))
@@ -812,6 +959,14 @@ ProcRRSetScreenConfig (ClientPtr client)
     if (!RRGetInfo (pScreen))
 	return BadAlloc;
     
+    pMonitor = pScrPriv->pMonitors;
+    if (!pMonitor)
+    {
+	time = currentTime;
+	rep.status = RRSetConfigFailed;
+	goto sendReply;
+    }
+    
     /*
      * if the client's config timestamp is not the same as the last config
      * timestamp, then the config information isn't up-to-date and
@@ -823,26 +978,20 @@ ProcRRSetScreenConfig (ClientPtr client)
 	goto sendReply;
     }
     
-    /*
-     * Search for the requested size
-     */
-    pSize = 0;
-    for (i = 0; i < pScrPriv->nSizes; i++)
-    {
-	pSize = &pScrPriv->pSizes[i];
-	if (pSize->referenced && pSize->id == stuff->sizeID)
-	{
-	    break;
-	}
-    }
-    if (i == pScrPriv->nSizes)
+    pData = RR10GetData (pScreen, pMonitor);
+    if (!pData)
+	return BadAlloc;
+    
+    if (stuff->sizeID >= pData->nsize)
     {
 	/*
 	 * Invalid size ID
 	 */
 	client->errorValue = stuff->sizeID;
+	xfree (pData);
 	return BadValue;
     }
+    pSize = &pData->sizes[stuff->sizeID];
     
     /*
      * Validate requested rotation
@@ -861,15 +1010,17 @@ ProcRRSetScreenConfig (ClientPtr client)
 	 * Invalid rotation
 	 */
 	client->errorValue = stuff->rotation;
+	xfree (pData);
 	return BadValue;
     }
 
-    if ((~pScrPriv->rotations) & rotation)
+    if ((~pMonitor->rotations) & rotation)
     {
 	/*
 	 * requested rotation or reflection not supported by screen
 	 */
 	client->errorValue = stuff->rotation;
+	xfree (pData);
 	return BadMatch;
     }
 
@@ -883,21 +1034,24 @@ ProcRRSetScreenConfig (ClientPtr client)
 
     if (rate)
     {
-	for (i = 0; i < pSize->nRates; i++)
+	for (i = 0; i < pSize->nrefresh; i++)
 	{
-	    RRScreenRatePtr pRate = &pSize->pRates[i];
-	    if (pRate->referenced && pRate->rate == rate)
+	    if (pSize->refresh[i].refresh == rate)
 		break;
 	}
-	if (i == pSize->nRates)
+	if (i == pSize->nrefresh)
 	{
 	    /*
 	     * Invalid rate
 	     */
 	    client->errorValue = rate;
+	    xfree (pData);
 	    return BadValue;
 	}
+	pMode = pSize->refresh[i].pMode;
     }
+    else
+	pMode = pSize->refresh[0].pMode;
     
     /*
      * Make sure the requested set-time is not older than
@@ -912,9 +1066,51 @@ ProcRRSetScreenConfig (ClientPtr client)
     /*
      * call out to ddx routine to effect the change
      */
-    if (!(*pScrPriv->rrSetConfig) (pScreen, rotation, rate,
-				   pSize))
+    if (pScrPriv->rrSetScreenSize && pScrPriv->rrSetMode)
+    {
+	xScreenSizes	oldSize;
+	if (!(*pScrPriv->rrSetMode) (pScreen, 0, NULL, 0, 0, RR_Rotate_0))
+	    goto fail;
+	oldSize.widthInPixels = pScreen->width;
+	oldSize.heightInPixels = pScreen->width;
+	oldSize.widthInMillimeters = pScreen->mmWidth;
+	oldSize.heightInMillimeters = pScreen->mmHeight;
+	if (!(*pScrPriv->rrSetScreenSize) (pScreen,
+					   pMode->mode.width,
+					   pMode->mode.height,
+					   pMode->mode.widthInMillimeters,
+					   pMode->mode.heightInMillimeters))
+	{
+	    (void) (*pScrPriv->rrSetMode) (pScreen, 0, pMonitor->pMode,
+					   pMonitor->x, pMonitor->y,
+					   pMonitor->rotation);
+	    goto fail;
+	}
+	if (!(*pScrPriv->rrSetMode) (pScreen, 0, pMode, 0, 0, rotation))
+	{
+	    (void) (*pScrPriv->rrSetScreenSize) (pScreen,
+						 oldSize.widthInPixels,
+						 oldSize.heightInPixels,
+						 oldSize.widthInMillimeters,
+						 oldSize.heightInMillimeters);
+	    (void) (*pScrPriv->rrSetMode) (pScreen, 0, pMonitor->pMode,
+					   pMonitor->x, pMonitor->y,
+					   pMonitor->rotation);
+	    goto fail;
+	}
+    }
+#ifdef RANDR_SCREEN_INTERFACE
+    else if (pScrPriv->rrSetConfig)
+    {
+	if (!(*pScrPriv->rrSetConfig) (pScreen, rotation, rate, pSize))
+	{
+	    goto fail;
+	}
+    }
+#endif
+    else
     {
+fail:	;
 	/*
 	 * unknown DDX failure, report to client
 	 */
@@ -925,7 +1121,7 @@ ProcRRSetScreenConfig (ClientPtr client)
     /*
      * set current extension configuration pointers
      */
-    RRSetCurrentConfig (pScreen, rotation, rate, pSize);
+    RRSetCurrentMode (pMonitor, pMode, 0, 0, rotation);
     
     /*
      * Deliver ScreenChangeNotify events whenever
@@ -954,6 +1150,9 @@ ProcRRSetScreenConfig (ClientPtr client)
     
 sendReply:
     
+    if (pData)
+	xfree (pData);
+
     rep.type = X_Reply;
     /* rep.status has already been filled in */
     rep.length = 0;
@@ -1055,7 +1254,7 @@ RRSetScreenConfig (ScreenPtr		pScreen,
     /*
      * set current extension configuration pointers
      */
-    RRSetCurrentConfig (pScreen, rotation, rate, pSize);
+    RRSetCurrentMode (pMonitor, pMode, 0, 0, rotation);
     
     /*
      * Deliver ScreenChangeNotify events whenever
@@ -1075,7 +1274,6 @@ RRSetScreenConfig (ScreenPtr		pScreen,
      * Fix pointer bounds and location
      */
     ScreenRestructured (pScreen);
-    
     return Success;
 }
 
@@ -1286,22 +1484,114 @@ SProcRRDispatch (ClientPtr client)
     }
 }
 
+/*
+ * Register a monitor for a screen. identifier is a unique identifier
+ * for the monitors of a particular screen.
+ */
+RRMonitorPtr
+RRRegisterMonitor (ScreenPtr		pScreen,
+		   void			*identifier,
+		   Rotation		rotations)
+{
+    rrScrPriv (pScreen);
+    RRMonitorPtr    pMonitor, *pPrev, *pInsert;
 
-static Bool
-RRScreenSizeMatches (RRScreenSizePtr  a,
-		   RRScreenSizePtr  b)
+    pInsert = NULL;
+    for (pPrev = &pScrPriv->pMonitors; (pMonitor = *pPrev); 
+	 pPrev = &(pMonitor)->next)
+    {
+	if (pMonitor->identifier == identifier) 
+	{
+	    pMonitor->referenced = TRUE;
+	    return pMonitor;
+	}
+	if (!pMonitor->referenced)
+	    pInsert = pPrev;
+    }
+    if (!pInsert)
+	pInsert = pPrev;
+    
+    /*
+     * New monitor, add before the first unreferenced monitor
+     */
+    pMonitor = xalloc (sizeof (RRMonitor));
+    if (!pMonitor)
+	return NULL;
+    pMonitor->pScreen = pScreen;
+    pMonitor->pModes = NULL;
+    pMonitor->identifier = identifier;
+    pMonitor->referenced = TRUE;
+    pMonitor->oldReferenced = FALSE;
+    pMonitor->rotations = RR_Rotate_0;
+    
+    pMonitor->pMode = NULL;
+    pMonitor->x = 0;
+    pMonitor->y = 0;
+    pMonitor->rotation = RR_Rotate_0;
+    pMonitor->next = *pInsert;
+    *pInsert = pMonitor;
+    return pMonitor;
+}
+
+/*
+ * Register a mode for a monitor
+ */
+
+RRModePtr
+RRRegisterMode (RRMonitorPtr	pMonitor,
+		xRRMonitorMode	*pModeline,
+		char		*name)
 {
-    if (a->width != b->width)
-	return FALSE;
-    if (a->height != b->height)
-	return FALSE;
-    if (a->mmWidth != b->mmWidth)
-	return FALSE;
-    if (a->mmHeight != b->mmHeight)
-	return FALSE;
-    return TRUE;
+    RRModePtr	pMode, *pPrev, *pInsert = NULL;
+
+    /*
+     * Find existing mode with same modeline and name
+     */
+    for (pPrev = &pMonitor->pModes; (pMode = *pPrev); pPrev = &(pMode->next))
+    {
+	if (!memcmp (&pMode->mode, pModeline, sizeof (xRRMonitorMode)) &&
+	    pMode->mode.nameLength == pModeline->nameLength &&
+	    !memcmp (RRModeName(pMode), name, pModeline->nameLength))
+	{
+	    pMode->referenced = TRUE;
+	    return pMode;
+	}
+	if (!pMode->referenced)
+	    pInsert = pPrev;
+    }
+
+    if (!pInsert)
+	pInsert = pPrev;
+    
+    /*
+     * Create a new mode, inserting before the first unreferenced mode
+     */
+    pMode = xalloc (sizeof (RRMode) + pModeline->nameLength + 1);
+    pMode->referenced = TRUE;
+    pMode->oldReferenced = FALSE;
+    pMode->mode = *pModeline;
+    memcpy (RRModeName (pMode), name, pModeline->nameLength);
+    RRModeName(pMode)[pModeline->nameLength] = '\0';
+    pMode->next = *pInsert;
+    *pInsert = pMode;
+    return pMode;
+}
+
+void
+RRSetCurrentMode (RRMonitorPtr	pMonitor,
+		  RRModePtr	pMode,
+		  int		x,
+		  int		y,
+		  Rotation	rotation)
+{
+    pMonitor->pMode = pMode;
+    pMonitor->x = x;
+    pMonitor->y = y;
+    pMonitor->rotation = rotation;
 }
 
+#ifdef RANDR_SCREEN_INTERFACE
+
 RRScreenSizePtr
 RRRegisterSize (ScreenPtr	    pScreen,
 		short		    width, 
@@ -1310,36 +1600,45 @@ RRRegisterSize (ScreenPtr	    pScreen,
 		short		    mmHeight)
 {
     rrScrPriv (pScreen);
-    int		    i;
-    RRScreenSize    tmp;
-    RRScreenSizePtr pNew;
+    xRRMonitorMode  tmp;
+    RRMonitorPtr    pMonitor;
+    RRModePtr	    pMode, *pPrev;
+    char	    name[100];
 
     if (!pScrPriv)
-	return 0;
+	return NULL;
+    pMonitor = pScrPriv->pMonitors;
+    if (!pMonitor)
+	return NULL;
     
-    tmp.id = -1;
-    tmp.width = width;
-    tmp.height= height;
-    tmp.mmWidth = mmWidth;
-    tmp.mmHeight = mmHeight;
-    tmp.pRates = 0;
-    tmp.nRates = 0;
-    tmp.nRatesInUse = 0;
-    tmp.referenced = TRUE;
-    tmp.oldReferenced = FALSE;
-    for (i = 0; i < pScrPriv->nSizes; i++)
-	if (RRScreenSizeMatches (&tmp, &pScrPriv->pSizes[i]))
+    for (pPrev = &pMonitor->pModes; (pMode = *pPrev); pPrev = &(pMode->next))
+	if (pMode->mode.width == width &&
+	    pMode->mode.height == height &&
+	    pMode->mode.widthInMillimeters == mmWidth &&
+	    pMode->mode.heightInMillimeters == mmHeight)
 	{
-	    pScrPriv->pSizes[i].referenced = TRUE;
-	    return &pScrPriv->pSizes[i];
+	    pMode->referenced =TRUE;
+	    return (void *) pMode;
 	}
-    pNew = xrealloc (pScrPriv->pSizes,
-		     (pScrPriv->nSizes + 1) * sizeof (RRScreenSize));
-    if (!pNew)
-	return 0;
-    pNew[pScrPriv->nSizes++] = tmp;
-    pScrPriv->pSizes = pNew;
-    return &pNew[pScrPriv->nSizes-1];
+    memset (&tmp, '\0', sizeof (xRRMonitorMode));
+    memset (name, '\0', sizeof (name));
+    sprintf (name, "%dx%d", width, height);
+    tmp.width = width;
+    tmp.height= height;
+    tmp.widthInMillimeters = mmWidth;
+    tmp.heightInMillimeters = mmHeight;
+    tmp.nameLength = strlen (name) + 10;    /* leave space for refresh */
+    pMode = RRRegisterMode (pMonitor, &tmp, name);
+    return (void *) pMode;
+}
+
+static Bool
+RRModesMatchSize (RRModePtr a, RRModePtr b)
+{
+    return (a->mode.width == a->mode.width &&
+	    a->mode.height == b->mode.height &&
+	    a->mode.widthInMillimeters == b->mode.widthInMillimeters &&
+	    a->mode.heightInMillimeters == b->mode.heightInMillimeters);
 }
 
 Bool RRRegisterRate (ScreenPtr		pScreen,
@@ -1347,31 +1646,61 @@ Bool RRRegisterRate (ScreenPtr		pScreen,
 		     int		rate)
 {
     rrScrPriv(pScreen);
-    int		    i;
-    RRScreenRatePtr pNew, pRate;
+    RRMonitorPtr    pMonitor;
+    RRModePtr	    pSizeMode = (RRModePtr) pSize;
+    RRModePtr	    pMode, *pPrev;
+    CARD16	    width = pSizeMode->mode.width;
+    CARD16	    height = pSizeMode->mode.height;
+    char	    name[100];
+    xRRMonitorMode  modeLine;
 
     if (!pScrPriv)
 	return FALSE;
     
-    for (i = 0; i < pSize->nRates; i++)
+    pMonitor = pScrPriv->pMonitors;
+    if (!pMonitor)
+	return FALSE;
+
+    for (pPrev = &pMonitor->pModes; (pMode = *pPrev); pPrev = &pMode->next)
     {
-	pRate = &pSize->pRates[i];
-	if (pRate->rate == rate)
+	if (RRModesMatchSize (pMode, pSizeMode))
 	{
-	    pRate->referenced = TRUE;
-	    return TRUE;
+	    if (pMode->mode.dotClock == 0)
+	    {
+		/*
+		 * First refresh for this size; reprogram this mode
+		 * with the right refresh.
+		 */
+		pMode->mode.hSyncStart = width;
+		pMode->mode.hSyncEnd = width;
+		pMode->mode.hTotal = width;
+		pMode->mode.hSkew = 0;
+		pMode->mode.vSyncStart = height;
+		pMode->mode.vSyncEnd = height;
+		pMode->mode.vTotal = height;
+		pMode->mode.dotClock = width * height * rate;
+		sprintf ((char *) (pMode + 1), "%dx%d@%d", width, height, rate);
+		pMode->mode.modeFlags = 0;
+		pMode->mode.nameLength = strlen ((char *) (pMode + 1));
+		pMode->referenced = TRUE;
+		return TRUE;
+	    }
+	    else if (rate == RRVerticalRefresh (&pMode->mode))
+	    {
+		pMode->referenced = TRUE;
+		return TRUE;
+	    }
 	}
     }
-
-    pNew = xrealloc (pSize->pRates,
-		     (pSize->nRates + 1) * sizeof (RRScreenRate));
-    if (!pNew)
+    
+    sprintf (name, "%dx%d@%d", pSizeMode->mode.width, pSizeMode->mode.height,
+	     rate);
+    modeLine = pSizeMode->mode;
+    modeLine.dotClock = rate * modeLine.vTotal * modeLine.hTotal;
+    modeLine.nameLength = strlen (name);
+    pMode = RRRegisterMode (pMonitor, &modeLine, name);
+    if (!pMode)
 	return FALSE;
-    pRate = &pNew[pSize->nRates++];
-    pRate->rate = rate;
-    pRate->referenced = TRUE;
-    pRate->oldReferenced = FALSE;
-    pSize->pRates = pNew;
     return TRUE;
 }
 
@@ -1379,11 +1708,15 @@ Rotation
 RRGetRotation(ScreenPtr pScreen)
 {
     rrScrPriv (pScreen);
+    RRMonitorPtr    pMonitor;
 
     if (!pScrPriv)
 	return RR_Rotate_0;
 
-    return pScrPriv->rotation;
+    pMonitor = pScrPriv->pMonitors;
+    if (!pMonitor)
+	return RR_Rotate_0;
+    return pMonitor->rotation;
 }
 
 void
@@ -1393,11 +1726,25 @@ RRSetCurrentConfig (ScreenPtr		pScreen,
 		    RRScreenSizePtr	pSize)
 {
     rrScrPriv (pScreen);
+    RRMonitorPtr    pMonitor;
+    RRModePtr	    pMode;
+    RRModePtr	    pSizeMode = (RRModePtr) pSize;
 
     if (!pScrPriv)
 	return;
+    pMonitor = pScrPriv->pMonitors;
+    if (!pMonitor)
+	return;
 
-    pScrPriv->rotation = rotation;
-    pScrPriv->size = pSize - pScrPriv->pSizes;
-    pScrPriv->rate = rate;
+    for (pMode = pMonitor->pModes; pMode; pMode = pMode->next)
+    {
+	if (RRModesMatchSize (pMode, pSizeMode) && 
+	    RRVerticalRefresh (&pMode->mode) == rate)
+	    break;
+    }
+    if (!pMode)
+	return;
+    
+    RRSetCurrentMode (pMonitor, pMode, 0, 0, rotation);
 }
+#endif
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 07c6c37..3610274 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -34,11 +34,19 @@
 
 #include <X11/extensions/randrproto.h>
 
+#define RANDR_SCREEN_INTERFACE 1
+
+/*
+ * Modeline for a monitor. Name follows directly after this struct
+ */
+
+#define RRModeName(pMode) ((char *) (pMode + 1))
+
 typedef struct _rrMode {
     struct _rrMode  *next;
-    int		    id;
     Bool	    referenced;
     Bool	    oldReferenced;
+    int		    id;
     xRRMonitorMode  mode;
 } RRMode, *RRModePtr;
 
@@ -47,12 +55,15 @@ typedef struct _rrMonitor {
     ScreenPtr	    pScreen;
     RRModePtr	    pModes;
     void	    *identifier;    /* made unique by DDX */
+    int		    id;		    /* index in list of monitors */
     Bool	    referenced;
+    Bool	    oldReferenced;
+    Rotation	    rotations;
     
     /*
      * Current state
      */
-    int		    mode;
+    RRModePtr	    pMode;
     int		    x, y;
     Rotation	    rotation;
 } RRMonitor, *RRMonitorPtr;
@@ -76,7 +87,18 @@ typedef Bool (*RRCloseScreenProcPtr) ( int i, ScreenPtr pscreen);
 
 #ifdef RANDR_SCREEN_INTERFACE
 
-typedef void *RRScreenSizePtr;
+typedef struct _rrRefresh {
+    CARD16	    refresh;
+    RRModePtr	    pMode;
+} RRRefreshRec, *RRRefreshPtr;
+
+typedef struct _rrScreenSize {
+    int		    id;
+    short	    width, height;
+    short	    mmWidth, mmHeight;
+    int		    nrefresh;
+    RRRefreshPtr    refresh;
+} RRScreenSizeRec, *RRScreenSizePtr;
 
 typedef Bool (*RRSetConfigProcPtr) (ScreenPtr		pScreen,
 				    Rotation		rotation,
@@ -87,12 +109,23 @@ typedef Bool (*RRSetConfigProcPtr) (ScreenPtr		pScreen,
 	
 
 typedef struct _rrScrPriv {
-    RRSetModeProcPtr	    rrSetMode;
+    /*
+     * 'public' part of the structure; DDXen fill this in
+     * as they initialize
+     */
+#ifdef RANDR_SCREEN_INTERFACE
+    RRSetConfigProcPtr	    rrSetConfig;
+#endif
     RRGetInfoProcPtr	    rrGetInfo;
-    RRCloseScreenProcPtr    CloseScreen;
+    RRSetScreenSizeProcPtr  rrSetScreenSize;
+    RRSetModeProcPtr	    rrSetMode;
     
+    /*
+     * Private part of the structure; not considered part of the ABI
+     */
     TimeStamp		    lastSetTime;	/* last changed by client */
     TimeStamp		    lastConfigTime;	/* possible configs changed */
+    RRCloseScreenProcPtr    CloseScreen;
 
     /*
      * monitor data
@@ -105,7 +138,6 @@ typedef struct _rrScrPriv {
      */
     Rotation		    rotations;
     
-    RRSetConfigProcPtr	    rrSetConfig;
 
     Rotation		    rotation;
 #endif
@@ -137,8 +169,7 @@ RRRegisterMonitor (ScreenPtr		pScreen,
 RRModePtr
 RRRegisterMode (RRMonitorPtr	pMonitor,
 		xRRMonitorMode	*pMode,
-		char		*name,
-		int		nameLength);
+		char		*name);
 
 /*
  * Finally, set the current configuration of each monitor
@@ -147,6 +178,8 @@ RRRegisterMode (RRMonitorPtr	pMonitor,
 void
 RRSetCurrentMode (RRMonitorPtr	pMonitor,
 		  RRModePtr	pMode,
+		  int		x,
+		  int		y,
 		  Rotation	rotation);
 
 Bool RRScreenInit(ScreenPtr pScreen);
@@ -167,6 +200,8 @@ Bool
 miRRSetMode (ScreenPtr	pScreen,
 	     int	monitor,
 	     RRModePtr	pMode,
+	     int	x,
+	     int	y,
 	     Rotation	rotation);
 
 #ifdef RANDR_SCREEN_INTERFACE					
commit dc89ecf5b51ecd2bf5ab61b8e6a28b1fff3bc38b
Author: Keith Packard <keithp at neko.keithp.com>
Date:   Sat Jul 1 19:46:38 2006 -0700

    Preliminary RandR 1.2 work

diff --git a/randr/mirandr.c b/randr/mirandr.c
index 0954028..7bef02d 100644
--- a/randr/mirandr.c
+++ b/randr/mirandr.c
@@ -1,36 +1,36 @@
 /*
- *
- * Copyright © 2000, Compaq Computer Corporation, 
- * Copyright © 2002, Hewlett Packard, Inc.
+ * Copyright © 2000 Compaq Computer Corporation
+ * Copyright © 2002 Hewlett-Packard Company
+ * Copyright © 2006 Intel Corporation
  *
  * 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 Compaq or HP not be used in advertising
- * or publicity pertaining to distribution of the software without specific,
- * written prior permission.  HP makes no representations about the
- * suitability of this software for any purpose.  It is provided "as is"
- * without express or implied warranty.
+ * 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.
  *
- * HP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL HP
- * 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.
+ * 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.
  *
- * Author:  Jim Gettys, HP Labs, Hewlett-Packard, Inc.
+ * Author:  Jim Gettys, Hewlett-Packard Company, Inc.
+ *	    Keith Packard, Intel Corporation
  */
 
-
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
 
 #include "scrnintstr.h"
 #include "mi.h"
-#include <X11/extensions/randr.h>
 #include "randrstr.h"
 #include <stdio.h>
 
@@ -48,26 +48,35 @@ miRRGetInfo (ScreenPtr pScreen, Rotation *rotations)
 {
     int	i;
     Bool setConfig = FALSE;
+    RRMonitorPtr pMonitor;
     
-    *rotations = RR_Rotate_0;
+    pMonitor = RRRegisterMonitor (pScreen, NULL, RR_Rotate_0);
     for (i = 0; i < pScreen->numDepths; i++)
     {
 	if (pScreen->allowedDepths[i].numVids)
 	{
-		RRScreenSizePtr		pSize;
+	    xRRMonitorMode		rrMode;
+	    RRModePtr			pMode;
+	    char			name[64];
 
-		pSize = RRRegisterSize (pScreen,
-					pScreen->width,
-					pScreen->height,
-					pScreen->mmWidth,
-					pScreen->mmHeight);
-		if (!pSize)
-		    return FALSE;
-		if (!setConfig)
-		{
-		    RRSetCurrentConfig (pScreen, RR_Rotate_0, 0, pSize);
-		    setConfig = TRUE;
-		}
+	    sprintf (name, "%dx%d", pScreen->width, pScreen->height);
+	    memset (&rrMode, '\0', sizeof (rrMode));
+	    rrMode.width = pScreen->width;
+	    rrMode.height = pScreen->height;
+	    rrMode.widthInMillimeters = pScreen->mmWidth;
+	    rrMode.heightInMillimeters = pScreen->mmHeight;
+	    pMonitor = RRRegisterMonitor (pScreen, RR_Rotate_0);
+	    pMode = RRRegisterMode (pMonitor,
+				    &rrMode,
+				    name,
+				    strlen (name));
+	    if (!pMode)
+		return FALSE;
+	    if (!setConfig)
+	    {
+		RRSetCurrentMode (pMonitor, pMode, 0, 0, RR_Rotate_0);
+		setConfig = TRUE;
+	    }
 	}
     }
     return TRUE;
@@ -78,10 +87,10 @@ miRRGetInfo (ScreenPtr pScreen, Rotation *rotations)
  * different here
  */
 Bool
-miRRSetConfig (ScreenPtr	pScreen,
-	       Rotation		rotation,
-	       int		rate,
-	       RRScreenSizePtr	pSize)
+miRRSetMode (ScreenPtr	pScreen,
+	     int	monitor,
+	     RRModePtr	pMode,
+	     Rotation	rotation)
 {
     return TRUE;
 }
@@ -96,6 +105,6 @@ miRandRInit (ScreenPtr pScreen)
 	return FALSE;
     rp = rrGetScrPriv(pScreen);
     rp->rrGetInfo = miRRGetInfo;
-    rp->rrSetConfig = miRRSetConfig;
+    rp->rrSetMode = miRRSetMode;
     return TRUE;
 }
diff --git a/randr/randr.c b/randr/randr.c
index 946aad3..1a9624a 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -1,29 +1,30 @@
 /*
- *
- * Copyright © 2000, Compaq Computer Corporation, 
- * Copyright © 2002, Hewlett Packard, Inc.
+ * Copyright © 2000 Compaq Computer Corporation
+ * Copyright © 2002 Hewlett-Packard Company
+ * Copyright © 2006 Intel Corporation
  *
  * 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 Compaq or HP not be used in advertising
- * or publicity pertaining to distribution of the software without specific,
- * written prior permission.  HP makes no representations about the
- * suitability of this software for any purpose.  It is provided "as is"
- * without express or implied warranty.
+ * 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.
  *
- * HP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL HP
- * 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.
+ * 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.
  *
- * Author:  Jim Gettys, HP Labs, Hewlett-Packard, Inc.
+ * Author:  Jim Gettys, Hewlett-Packard Company, Inc.
+ *	    Keith Packard, Intel Corporation
  */
 
-
 #define NEED_REPLIES
 #define NEED_EVENTS
 #ifdef HAVE_DIX_CONFIG_H
@@ -159,10 +160,21 @@ static Bool
 RRCloseScreen (int i, ScreenPtr pScreen)
 {
     rrScrPriv(pScreen);
+    RRMonitorPtr    pMonitor;
 
     unwrap (pScrPriv, pScreen, CloseScreen);
-    if (pScrPriv->pSizes)
-	xfree (pScrPriv->pSizes);
+    while (pMonitor = pScrPriv->pMonitors) 
+    {
+	RRModePtr   pMode;
+	
+	pScrPriv->pMonitors = pMonitor->next;
+	while (pMode = pMonitor->pModes) 
+	{
+	    pMonitor->pModes = pMode->next;
+	    xfree (pMode);
+	}
+	xfree (pMonitor);
+    }
     xfree (pScrPriv);
     RRNScreens -= 1;	/* ok, one fewer screen with RandR running */
     return (*pScreen->CloseScreen) (i, pScreen);    
@@ -187,6 +199,25 @@ SRRScreenChangeNotifyEvent(xRRScreenChangeNotifyEvent *from,
     cpswaps(from->subpixelOrder, to->subpixelOrder);
 }
 
+static void
+SRRMonitorChangeNotifyEvent(xRRMonitorChangeNotifyEvent *from,
+			    xRRMonitorChangeNotifyEvent *to)
+{
+    to->type = from->type;
+    to->subCode = from->subCode;
+    cpswaps(from->sequenceNumber, to->sequenceNumber);
+    cpswapl(from->timestamp, to->timestamp);
+    cpswapl(from->configTimestamp, to->configTimestamp);
+    cpswapl(from->root, to->root);
+    cpswapl(from->window, to->window);
+    cpswaps(from->monitor, to->monitor);
+    cpswaps(from->modeID, to->modeID);
+    cpswaps(from->rotation, to->rotation);
+    cpswaps(from->subpixelOrder, to->subpixelOrder);
+    cpswaps(from->x, to->x);
+    cpswaps(from->y, to->y);
+}
+
 Bool RRScreenInit(ScreenPtr pScreen)
 {
     rrScrPrivPtr   pScrPriv;
@@ -207,8 +238,12 @@ Bool RRScreenInit(ScreenPtr pScreen)
     /*
      * Calling function best set these function vectors
      */
-    pScrPriv->rrSetConfig = 0;
+    pScrPriv->rrSetMode = 0;
     pScrPriv->rrGetInfo = 0;
+#ifdef RANDR_SCREEN_INTERFACE    
+    pScrPriv->rrSetConfig = 0;
+#endif
+    
     /*
      * This value doesn't really matter -- any client must call
      * GetScreenInfo before reading it which will automatically update
@@ -219,14 +254,7 @@ Bool RRScreenInit(ScreenPtr pScreen)
     
     wrap (pScrPriv, pScreen, CloseScreen, RRCloseScreen);
 
-    pScrPriv->rotations = RR_Rotate_0;
-    
-    pScrPriv->nSizes = 0;
-    pScrPriv->nSizesInUse = 0;
-    pScrPriv->pSizes = 0;
-    
-    pScrPriv->rotation = RR_Rotate_0;
-    pScrPriv->size = -1;
+    pScrPriv->pMonitors = NULL;
     
     RRNScreens += 1;	/* keep count of screens that implement randr */
     return TRUE;
@@ -318,55 +346,96 @@ TellChanged (WindowPtr pWin, pointer value)
     RREventPtr			*pHead, pRREvent;
     ClientPtr			client;
     xRRScreenChangeNotifyEvent	se;
+    xRRMonitorChangeNotifyEvent	me;
     ScreenPtr			pScreen = pWin->drawable.pScreen;
     rrScrPriv(pScreen);
-    RRScreenSizePtr		pSize;
+    RRMonitorPtr		pMonitor = pScrPriv->pMonitors;
+    RRModePtr			pMode;
     WindowPtr			pRoot = WindowTable[pScreen->myNum];
+    int				i;
 
     pHead = (RREventPtr *) LookupIDByType (pWin->drawable.id, EventType);
     if (!pHead)
 	return WT_WALKCHILDREN;
 
-    se.type = RRScreenChangeNotify + RREventBase;
-    se.rotation = (CARD8) pScrPriv->rotation;
-    se.timestamp = pScrPriv->lastSetTime.milliseconds;
-    se.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
-    se.root =  pRoot->drawable.id;
-    se.window = pWin->drawable.id;
-#ifdef RENDER
-    se.subpixelOrder = PictureGetSubpixelOrder (pScreen);
-#else
-    se.subpixelOrder = SubPixelUnknown;
-#endif
-    if (pScrPriv->size >= 0)
-    {
-	pSize = &pScrPriv->pSizes[pScrPriv->size];
-	se.sizeID = pSize->id;
-	se.widthInPixels = pSize->width;
-	se.heightInPixels = pSize->height;
-	se.widthInMillimeters = pSize->mmWidth;
-	se.heightInMillimeters = pSize->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;
-    }    
     for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next) 
     {
 	client = pRREvent->client;
 	if (client == serverClient || client->clientGone)
 	    continue;
-	se.sequenceNumber = client->sequence;
-	if(pRREvent->mask & RRScreenChangeNotifyMask)
-	  WriteEventsToClient (client, 1, (xEvent *) &se);
+
+	if (pRREvent->mask & RRMonitorChangeNotifyMask)) 
+	{
+	    me.type = RRNotify + RREventBase;
+	    me.subCode = RRNotify_MonitorChange;
+	    me.timestamp = pScrPriv->lastSetTime.milliseconds;
+	    me.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
+	    me.root =  pRoot->drawable.id;
+	    me.window = pWin->drawable.id;
+#ifdef RENDER
+	    me.subpixelOrder = PictureGetSubpixelOrder (pScreen);
+#else
+	    me.subpixelOrder = SubPixelUnknown;
+#endif
+	    for (i = 0; i < pScrPriv->nMonitors; i++) 
+	    {
+		pMonitor = &pScrPriv->pMonitors[i];
+		me.monitor = i;
+		if (pMonitor->mode >= 0) {
+		    me.modeID = pMonitor->pMode[pMonitor->mode].id;
+		    me.rotation = pMonitor->rotation;
+		    me.x = pMonitor->x;
+		    me.y = pMonitor->y;
+		} else {
+		    me.modeID = 0xffff;
+		    me.rotation = RR_Rotate_0;
+		    me.x = 0;
+		    me.y = 0;
+		}
+		WriteEventsToClient (client, 1, (xEvent *) &me);
+	    }
+	}
+	if ((pRREvent->mask & RRScreenChangeNotifyMask) &&
+	    pScrPriv->nMonitors > 0)
+	{
+	    se.type = RRScreenChangeNotify + RREventBase;
+	    se.rotation = (CARD8) pScrPriv->rotation;
+	    se.timestamp = pScrPriv->lastSetTime.milliseconds;
+	    se.sequenceNumber = client->sequence;
+	    se.configTimestamp = pScrPriv->lastConfigTime.milliseconds;
+	    se.root =  pRoot->drawable.id;
+	    se.window = pWin->drawable.id;
+#ifdef RENDER
+	    se.subpixelOrder = PictureGetSubpixelOrder (pScreen);
+#else
+	    se.subpixelOrder = SubPixelUnknown;
+#endif
+
+	    pMonitor = &pScrPriv->pMonitors[0];
+	    se.sequenceNumber = client->sequence;
+	    if (pMonitor->mode >= 0) 
+	    {
+		pMode = &pMonitor->pModes[pMonitor->mode];
+		se.sizeID = pMode->id;
+		se.widthInPixels = pMode->width;
+		se.heightInPixels = pMode->height;
+		se.widthInMillimeters = pMode->mmWidth;
+		se.heightInMillimeters = pMode->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;
+	    }    
+	    WriteEventsToClient (client, 1, (xEvent *) &se);
+	}
     }
     return WT_WALKCHILDREN;
 }
@@ -375,59 +444,66 @@ static Bool
 RRGetInfo (ScreenPtr pScreen)
 {
     rrScrPriv (pScreen);
-    int		    i, j, k, l;
+    int		    m, s, n;
     Bool	    changed;
     Rotation	    rotations;
-    RRScreenSizePtr pSize;
-    RRScreenRatePtr pRate;
+    RRMonitorPtr    pMonitor;
+    RRModePtr	    pMode;
 
-    for (i = 0; i < pScrPriv->nSizes; i++)
+    for (m = 0; m < pScrPriv->nMonitors; m++)
     {
-	pSize = &pScrPriv->pSizes[i];
-	pSize->oldReferenced = pSize->referenced;
-	pSize->referenced = FALSE;
-	for (k = 0; k < pSize->nRates; k++)
+	pMonitor = &pScrPriv->pMonitors[m];
+	pMonitor->oldReferenced = pMonitor->referenced;
+	pMonitor->referenced = FALSE;
+	for (s = 0; s < pMonitor->nModes; s++)
 	{
-	    pRate = &pSize->pRates[k];
-	    pRate->oldReferenced = pRate->referenced;
-	    pRate->referenced = FALSE;
+	    pMode = &pSize->pModes[s];
+	    pMode->oldReferenced = pMode->referenced;
+	    pMode->referenced = FALSE;
 	}
     }
-    if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
-	return FALSE;
-
     changed = FALSE;
 
-    /*
-     * Check whether anything changed and simultaneously generate
-     * the protocol id values for the objects
-     */
-    if (rotations != pScrPriv->rotations)
-    {
-	pScrPriv->rotations = rotations;
-	changed = TRUE;
+    rotations = 0;
+    if (!(*pScrPriv->rrGetInfo) (pScreen, &rotations))
+	return FALSE;
+    
+    /* Old GetInfo clients return rotations here */
+    if (rotations && pScrPriv->nMonitors) {
+	/*
+	 * Check whether anything changed and simultaneously generate
+	 * the protocol id values for the objects
+	 */
+	if (rotations != pScrPriv->pMonitors[i].rotations)
+	{
+	    pScrPriv->pMonitors[i].rotations = rotations;
+	    changed = TRUE;
+	}
     }
-
-    j = 0;
-    for (i = 0; i < pScrPriv->nSizes; i++)
+	
+    n = 0;
+    for (m = 0; m < pScrPriv->nMonitors; m++)
     {
-	pSize = &pScrPriv->pSizes[i];
-	if (pSize->oldReferenced != pSize->referenced)
+	int modeid = 0;
+	
+	pMonitor = &pScrPriv->pMonitors[m];
+	if (pMonitor->oldReferenced != pMonitor->referenced)
 	    changed = TRUE;
-	if (pSize->referenced)
-	    pSize->id = j++;
-	l = 0;
-	for (k = 0; k < pSize->nRates; k++)
+	if (pMonitor->referenced)
 	{
-	    pRate = &pSize->pRates[k];
-	    if (pRate->oldReferenced != pRate->referenced)
-		changed = TRUE;
-	    if (pRate->referenced)
-		l++;
+	    for (s = 0; s < pMonitor->nModes; s++)
+	    {
+		pMode = &pMonitor->pModes[s];
+		if (pMode->oldReferenced != pMode->referenced)
+		    changed = TRUE;
+		if (pMode->referenced)
+		    pMode->id = modeid++;
+	    }
+	    n++;
 	}
-	pSize->nRatesInUse = l;
+	pMonitor->nModesInUse = modeid;
     }
-    pScrPriv->nSizesInUse = j;
+    pScrPriv->nMonitorsInUse = n;
     if (changed)
     {
 	UpdateCurrentTime ();
@@ -1241,6 +1317,7 @@ RRRegisterSize (ScreenPtr	    pScreen,
     if (!pScrPriv)
 	return 0;
     
+    tmp.id = -1;
     tmp.width = width;
     tmp.height= height;
     tmp.mmWidth = mmWidth;
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 27ab61a..07c6c37 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -1,24 +1,28 @@
 /*
- *
  * Copyright © 2000 Compaq Computer Corporation
+ * Copyright © 2002 Hewlett-Packard Company
+ * Copyright © 2006 Intel Corporation
  *
  * 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 Compaq not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Compaq makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
+ * 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.
  *
- * COMPAQ DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL COMPAQ BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * 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.
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THIS SOFTWARE.
+ *
+ * Author:  Jim Gettys, Hewlett-Packard Company, Inc.
+ *	    Keith Packard, Intel Corporation
  */
 
 #ifdef HAVE_DIX_CONFIG_H
@@ -28,56 +32,83 @@
 #ifndef _RANDRSTR_H_
 #define _RANDRSTR_H_
 
-#include <X11/extensions/randr.h>
-
-typedef struct _rrScreenRate {
-    int		    rate;
-    Bool	    referenced;
-    Bool	    oldReferenced;
-} RRScreenRate, *RRScreenRatePtr;
+#include <X11/extensions/randrproto.h>
 
-typedef struct _rrScreenSize {
+typedef struct _rrMode {
+    struct _rrMode  *next;
     int		    id;
-    short	    width, height;
-    short	    mmWidth, mmHeight;
-    RRScreenRatePtr pRates;
-    int		    nRates;
-    int		    nRatesInUse;
     Bool	    referenced;
     Bool	    oldReferenced;
-} RRScreenSize, *RRScreenSizePtr;
+    xRRMonitorMode  mode;
+} RRMode, *RRModePtr;
+
+typedef struct _rrMonitor {
+    struct _rrMonitor	*next;
+    ScreenPtr	    pScreen;
+    RRModePtr	    pModes;
+    void	    *identifier;    /* made unique by DDX */
+    Bool	    referenced;
+    
+    /*
+     * Current state
+     */
+    int		    mode;
+    int		    x, y;
+    Rotation	    rotation;
+} RRMonitor, *RRMonitorPtr;
+
+typedef Bool (*RRSetScreenSizeProcPtr) (ScreenPtr	pScreen,
+					CARD16		width,
+					CARD16		height,
+					CARD32		widthInMM,
+					CARD32		heightInMM);
+					
+typedef Bool (*RRSetModeProcPtr) (ScreenPtr		pScreen,
+				  int			monitor,
+				  RRModePtr		pMode,
+				  int			x,
+				  int			y,
+				  Rotation		rotation);
+
+typedef Bool (*RRGetInfoProcPtr) (ScreenPtr pScreen, Rotation *rotations);
+typedef Bool (*RRCloseScreenProcPtr) ( int i, ScreenPtr pscreen);
+
+
+#ifdef RANDR_SCREEN_INTERFACE
+
+typedef void *RRScreenSizePtr;
 
 typedef Bool (*RRSetConfigProcPtr) (ScreenPtr		pScreen,
 				    Rotation		rotation,
 				    int			rate,
 				    RRScreenSizePtr	pSize);
 
-typedef Bool (*RRGetInfoProcPtr) (ScreenPtr pScreen, Rotation *rotations);
-typedef Bool (*RRCloseScreenProcPtr) ( int i, ScreenPtr pscreen);
+#endif
 	
+
 typedef struct _rrScrPriv {
-    RRSetConfigProcPtr	    rrSetConfig;
+    RRSetModeProcPtr	    rrSetMode;
     RRGetInfoProcPtr	    rrGetInfo;
+    RRCloseScreenProcPtr    CloseScreen;
     
     TimeStamp		    lastSetTime;	/* last changed by client */
     TimeStamp		    lastConfigTime;	/* possible configs changed */
-    RRCloseScreenProcPtr    CloseScreen;
 
     /*
+     * monitor data
+     */
+    RRMonitorPtr	    pMonitors;
+
+#ifdef RANDR_SCREEN_INTERFACE
+    /*
      * Configuration information
      */
     Rotation		    rotations;
     
-    int			    nSizes;
-    int			    nSizesInUse;
-    RRScreenSizePtr	    pSizes;
+    RRSetConfigProcPtr	    rrSetConfig;
 
-    /*
-     * Current state
-     */
     Rotation		    rotation;
-    int			    size;
-    int			    rate;
+#endif
 } rrScrPrivRec, *rrScrPrivPtr;
 
 extern int rrPrivIndex;
@@ -91,6 +122,60 @@ void
 RRExtensionInit (void);
 
 /*
+ * Then, register a monitor with the screen
+ */
+
+RRMonitorPtr
+RRRegisterMonitor (ScreenPtr		pScreen,
+		   void			*identifier,
+		   Rotation		rotations);
+
+/*
+ * Next, register the list of modes with the monitor
+ */
+
+RRModePtr
+RRRegisterMode (RRMonitorPtr	pMonitor,
+		xRRMonitorMode	*pMode,
+		char		*name,
+		int		nameLength);
+
+/*
+ * Finally, set the current configuration of each monitor
+ */
+
+void
+RRSetCurrentMode (RRMonitorPtr	pMonitor,
+		  RRModePtr	pMode,
+		  Rotation	rotation);
+
+Bool RRScreenInit(ScreenPtr pScreen);
+
+Rotation
+RRGetRotation (ScreenPtr pScreen);
+
+Bool
+miRandRInit (ScreenPtr pScreen);
+
+Bool
+miRRGetInfo (ScreenPtr pScreen, Rotation *rotations);
+
+Bool
+miRRGetScreenInfo (ScreenPtr pScreen);
+
+Bool
+miRRSetMode (ScreenPtr	pScreen,
+	     int	monitor,
+	     RRModePtr	pMode,
+	     Rotation	rotation);
+
+#ifdef RANDR_SCREEN_INTERFACE					
+/*
+ * This is the old interface, deprecated but left
+ * around for compatibility
+ */
+
+/*
  * Then, register the specific size with the screen
  */
 
@@ -105,6 +190,9 @@ Bool RRRegisterRate (ScreenPtr		pScreen,
 		     RRScreenSizePtr	pSize,
 		     int		rate);
 
+Bool RRRegisterRotation (ScreenPtr	pScreen,
+			 Rotation	rotation);
+
 /*
  * Finally, set the current configuration of the screen
  */
@@ -115,11 +203,6 @@ RRSetCurrentConfig (ScreenPtr		pScreen,
 		    int			rate,
 		    RRScreenSizePtr	pSize);
 
-Bool RRScreenInit(ScreenPtr pScreen);
-
-Rotation
-RRGetRotation (ScreenPtr pScreen);
-
 int
 RRSetScreenConfig (ScreenPtr		pScreen,
 		   Rotation		rotation,
@@ -127,18 +210,10 @@ RRSetScreenConfig (ScreenPtr		pScreen,
 		   RRScreenSizePtr	pSize);
 
 Bool
-miRandRInit (ScreenPtr pScreen);
-
-Bool
-miRRGetInfo (ScreenPtr pScreen, Rotation *rotations);
-
-Bool
 miRRSetConfig (ScreenPtr	pScreen,
 	       Rotation		rotation,
 	       int		rate,
 	       RRScreenSizePtr	size);
 
-Bool
-miRRGetScreenInfo (ScreenPtr pScreen);
-
+#endif					
 #endif /* _RANDRSTR_H_ */


More information about the xorg-commit mailing list