2006-04-29 Peter Dennis Bartok <pbartok@novell.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / XplatUIX11.cs
1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
8 // 
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 // 
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 //
20 // Copyright (c) 2004-2006 Novell, Inc.
21 //
22 // Authors:
23 //      Peter Bartok    pbartok@novell.com
24 //
25 //
26
27 // NOTE:
28 //      This driver understands the following environment variables: (Set the var to enable feature)
29 //
30 //      MONO_XEXCEPTIONS        = throw an exception when a X11 error is encountered;
31 //                                by default a message is displayed but execution continues
32 //
33 //      MONO_XSYNC              = perform all X11 commands synchronous; this is slower but
34 //                                helps in debugging errors
35 //
36
37 // NOT COMPLETE
38
39 // define to log Window handles and relationships to stdout
40 #undef DriverDebug
41
42 // Extra detailed debug
43 #undef  DriverDebugExtra
44 #undef DriverDebugParent
45 #undef DriverDebugCreate
46 #undef DriverDebugDestroy
47
48 using System;
49 using System.ComponentModel;
50 using System.Collections;
51 using System.Diagnostics;
52 using System.Drawing;
53 using System.Drawing.Drawing2D;
54 using System.Drawing.Imaging;
55 using System.IO;
56 using System.Net;
57 using System.Net.Sockets;
58 using System.Reflection;
59 using System.Runtime.InteropServices;
60 using System.Text;
61 using System.Threading;
62
63 // Only do the poll when building with mono for now
64 #if __MonoCS__
65 using Mono.Unix.Native;
66 #endif
67
68 /// X11 Version
69 namespace System.Windows.Forms {
70         internal class XplatUIX11 : XplatUIDriver {
71                 #region Local Variables
72                 // General
73                 static volatile XplatUIX11      Instance;
74                 private static int              RefCount;
75                 private static object           XlibLock;               // Our locking object
76                 private static bool             ThemesEnabled;
77
78                 // General X11
79                 private static IntPtr           DisplayHandle;          // X11 handle to display
80                 private static int              ScreenNo;               // Screen number used
81                 private static IntPtr           DefaultColormap;        // Colormap for screen
82                 private static IntPtr           CustomVisual;           // Visual for window creation
83                 private static IntPtr           CustomColormap;         // Colormap for window creation
84                 private static IntPtr           RootWindow;             // Handle of the root window for the screen/display
85                 private static IntPtr           FosterParent;           // Container to hold child windows until their parent exists
86                 private static XErrorHandler    ErrorHandler;           // Error handler delegate
87                 private static bool             ErrorExceptions;        // Throw exceptions on X errors
88                 private static bool             PostQuitState;          // True if we've got an pending exit
89
90                 // Clipboard
91                 private static IntPtr           ClipMagic = new IntPtr(27051977);
92                 private static ClipboardStruct  Clipboard;              // Our clipboard
93
94                 // Communication
95                 private static IntPtr           PostAtom;               // PostMessage atom
96                 private static IntPtr           AsyncAtom;              // Support for async messages
97
98                 // Message Loop
99                 private static Hashtable        MessageQueues;          // Holds our thread-specific XEventQueues
100                 #if __MonoCS__                                          //
101                 private static Pollfd[]         pollfds;                // For watching the X11 socket
102                 #endif                                                  //
103                 private static X11Keyboard      Keyboard;               //
104                 private static X11Dnd           Dnd;
105                 private static Socket           listen;                 //
106                 private static Socket           wake;                   //
107                 private static Socket           wake_receive;           //
108                 private static byte[]           network_buffer;         //
109
110
111                 // Focus tracking
112                 private static IntPtr           ActiveWindow;           // Handle of the active window
113                 private static IntPtr           FocusWindow;            // Handle of the window with keyboard focus (if any)
114
115                 // Modality support
116                 private static Stack            ModalWindows;           // Stack of our modal windows
117
118                 // Systray
119                 private static IntPtr           SystrayMgrWindow;       // Handle of the Systray Manager window
120
121                 // Cursors
122                 private static IntPtr           LastCursorWindow;       // The last window we set the cursor on
123                 private static IntPtr           LastCursorHandle;       // The handle that was last set on LastCursorWindow
124                 private static IntPtr           OverrideCursorHandle;   // The cursor that is set to override any other cursors
125
126                 // Caret
127                 private static CaretStruct      Caret;                  //
128
129                 // Support for Window Styles
130                 private static IntPtr[]         NetAtoms;               // All atoms we know
131
132                 // mouse hover message generation
133                 private static HoverStruct      HoverState;             //
134
135                 // double click message generation
136                 private static ClickStruct      ClickPending;           //
137
138                 // Support for mouse grab
139                 private static GrabStruct       Grab;                   //
140
141                 // State
142                 private static Point            MousePosition;          // Last position of mouse, in screen coords
143                 internal static MouseButtons    MouseState;             // Last state of mouse buttons
144
145                 // Timers
146                 private static ArrayList        TimerList;              // Holds SWF.Timers
147
148                 // 'Constants'
149                 private static int              DoubleClickInterval;    // msec; max interval between clicks to count as double click
150
151                 const EventMask SelectInputMask = EventMask.ButtonPressMask | 
152                                                   EventMask.ButtonReleaseMask | 
153                                                   EventMask.KeyPressMask | 
154                                                   EventMask.KeyReleaseMask | 
155                                                   EventMask.EnterWindowMask | 
156                                                   EventMask.LeaveWindowMask |
157                                                   EventMask.ExposureMask |
158                                                   EventMask.FocusChangeMask |
159                                                   EventMask.PointerMotionMask | 
160                                                   EventMask.VisibilityChangeMask |
161                                                   EventMask.SubstructureNotifyMask |
162                                                   EventMask.StructureNotifyMask;
163
164                 static readonly object lockobj = new object ();
165
166                 #endregion      // Local Variables
167                 #region Constructors
168                 private XplatUIX11() {
169                         // Handle singleton stuff first
170                         RefCount = 0;
171
172                         // Now regular initialization
173                         XlibLock = new object ();
174                         MessageQueues = new Hashtable(7);
175                         TimerList = new ArrayList ();
176                         XInitThreads();
177
178                         ErrorExceptions = false;
179
180                         // X11 Initialization
181                         SetDisplay(XOpenDisplay(IntPtr.Zero));
182                         X11DesktopColors.Initialize();
183
184                         // Handle any upcoming errors; we re-set it here, X11DesktopColor stuff might have stolen it (gtk does)
185                         ErrorHandler = new XErrorHandler(HandleError);
186                         XSetErrorHandler(ErrorHandler);
187                 }
188                 #endregion      // Constructors
189
190                 #region Singleton Specific Code
191                 public static XplatUIX11 GetInstance() {
192                         lock (lockobj) {
193                                 if (Instance == null) {
194                                         Instance=new XplatUIX11();
195                                 }
196                                 RefCount++;
197                         }
198                         return Instance;
199                 }
200
201                 public int Reference {
202                         get {
203                                 return RefCount;
204                         }
205                 }
206                 #endregion
207
208                 #region Internal Properties
209                 internal static IntPtr Display {
210                         get {
211                                 return DisplayHandle;
212                         }
213
214                         set {
215                                 XplatUIX11.GetInstance().SetDisplay(value);
216                         }
217                 }
218
219                 internal static int Screen {
220                         get {
221                                 return ScreenNo;
222                         }
223
224                         set {
225                                 ScreenNo = value;
226                         }
227                 }
228
229                 internal static IntPtr RootWindowHandle {
230                         get {
231                                 return RootWindow;
232                         }
233
234                         set {
235                                 RootWindow = value;
236                         }
237                 }
238
239                 internal static IntPtr Visual {
240                         get {
241                                 return CustomVisual;
242                         }
243
244                         set {
245                                 CustomVisual = value;
246                         }
247                 }
248
249                 internal static IntPtr ColorMap {
250                         get {
251                                 return CustomColormap;
252                         }
253
254                         set {
255                                 CustomColormap = value;
256                         }
257                 }
258                 #endregion
259
260                 #region XExceptionClass
261                 internal class XException : ApplicationException {
262                         IntPtr          Display;
263                         IntPtr          ResourceID;
264                         IntPtr          Serial;
265                         XRequest        RequestCode;
266                         byte            ErrorCode;
267                         byte            MinorCode;
268
269                         public XException(IntPtr Display, IntPtr ResourceID, IntPtr Serial, byte ErrorCode, XRequest RequestCode, byte MinorCode) {
270                                 this.Display = Display;
271                                 this.ResourceID = ResourceID;
272                                 this.Serial = Serial;
273                                 this.RequestCode = RequestCode;
274                                 this.ErrorCode = ErrorCode;
275                                 this.MinorCode = MinorCode;
276                         }
277
278                         public override string Message {
279                                 get {
280                                         return GetMessage(Display, ResourceID, Serial, ErrorCode, RequestCode, MinorCode);
281                                 }
282                         }
283
284                         public static string GetMessage(IntPtr Display, IntPtr ResourceID, IntPtr Serial, byte ErrorCode, XRequest RequestCode, byte MinorCode) {
285                                 StringBuilder   sb;
286                                 string          x_error_text;
287                                 string          error;
288                                 string          hwnd_text;
289                                 string          control_text;
290                                 Hwnd            hwnd;
291                                 Control         c;
292
293                                 sb = new StringBuilder(160);
294                                 XGetErrorText(Display, ErrorCode, sb, sb.Capacity);
295                                 x_error_text = sb.ToString();
296                                 hwnd = Hwnd.ObjectFromHandle(ResourceID);
297                                 if (hwnd != null) {
298                                         hwnd_text = hwnd.ToString();
299                                         c = Control.FromHandle(hwnd.Handle);
300                                         if (c != null) {
301                                                 control_text = c.ToString();
302                                         } else {
303                                                 control_text = String.Format("<handle {0:X} non-existant>", hwnd.Handle);
304                                         }
305                                 } else {
306                                         hwnd_text = "<null>";
307                                         control_text = "<null>";
308                                 }
309
310
311                                 error = String.Format("\n  Error: {0}\n  Request:     {1:D} ({2})\n  Resource ID: 0x{3:X}\n  Serial:      {4}\n  Hwnd:        {5}\n  Control:     {6}", x_error_text, RequestCode, RequestCode, ResourceID.ToInt32(), Serial, hwnd_text, control_text);
312                                 return error;
313                         }
314                 }
315                 #endregion      // XExceptionClass
316
317                 #region Internal Methods
318                 internal void SetDisplay(IntPtr display_handle) {
319                         if (display_handle != IntPtr.Zero) {
320                                 Hwnd    hwnd;
321
322                                 if ((DisplayHandle != IntPtr.Zero) && (FosterParent != IntPtr.Zero)) {
323                                         hwnd = Hwnd.ObjectFromHandle(FosterParent);
324                                         XDestroyWindow(DisplayHandle, FosterParent);
325                                         hwnd.Dispose();
326                                 }
327
328                                 if (DisplayHandle != IntPtr.Zero) {
329                                         XCloseDisplay(DisplayHandle);
330                                 }
331
332                                 DisplayHandle=display_handle;
333
334                                 // We need to tell System.Drawing our DisplayHandle. FromHdcInternal has
335                                 // been hacked to do this for us.
336                                 Graphics.FromHdcInternal (DisplayHandle);
337
338                                 // Debugging support
339                                 if (Environment.GetEnvironmentVariable ("MONO_XSYNC") != null) {
340                                         XSynchronize(DisplayHandle, true);
341                                 }
342
343                                 if (Environment.GetEnvironmentVariable ("MONO_XEXCEPTIONS") != null) {
344                                         ErrorExceptions = true;
345                                 }
346
347                                 // Generic X11 setup
348                                 ScreenNo = XDefaultScreen(DisplayHandle);
349                                 RootWindow = XRootWindow(DisplayHandle, ScreenNo);
350                                 DefaultColormap = XDefaultColormap(DisplayHandle, ScreenNo);
351
352                                 // Create the foster parent
353                                 FosterParent=XCreateSimpleWindow(DisplayHandle, RootWindow, 0, 0, 1, 1, 4, UIntPtr.Zero, UIntPtr.Zero);
354                                 if (FosterParent==IntPtr.Zero) {
355                                         Console.WriteLine("XplatUIX11 Constructor failed to create FosterParent");
356                                 }
357
358                                 hwnd = new Hwnd();
359                                 hwnd.Queue = ThreadQueue(Thread.CurrentThread);
360                                 hwnd.WholeWindow = FosterParent;
361                                 hwnd.ClientWindow = FosterParent;
362
363                                 // For sleeping on the X11 socket
364                                 listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
365                                 IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 0);
366                                 listen.Bind(ep);
367                                 listen.Listen(1);
368
369                                 // To wake up when a timer is ready
370                                 network_buffer = new byte[10];
371
372                                 wake = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
373                                 wake.Connect(listen.LocalEndPoint);
374                                 wake_receive = listen.Accept();
375
376                                 #if __MonoCS__
377                                 pollfds = new Pollfd [2];
378                                 pollfds [0] = new Pollfd ();
379                                 pollfds [0].fd = XConnectionNumber (DisplayHandle);
380                                 pollfds [0].events = PollEvents.POLLIN;
381
382                                 pollfds [1] = new Pollfd ();
383                                 pollfds [1].fd = wake_receive.Handle.ToInt32 ();
384                                 pollfds [1].events = PollEvents.POLLIN;
385                                 #endif
386
387                                 Keyboard = new X11Keyboard(DisplayHandle, FosterParent);
388                                 Dnd = new X11Dnd (DisplayHandle);
389
390                                 PostQuitState = false;
391
392                                 DoubleClickInterval = 500;
393
394                                 HoverState.Interval = 500;
395                                 HoverState.Timer = new Timer();
396                                 HoverState.Timer.Enabled = false;
397                                 HoverState.Timer.Interval = HoverState.Interval;
398                                 HoverState.Timer.Tick += new EventHandler(MouseHover);
399                                 HoverState.Size = new Size(4, 4);
400                                 HoverState.X = -1;
401                                 HoverState.Y = -1;
402
403                                 ActiveWindow = IntPtr.Zero;
404                                 FocusWindow = IntPtr.Zero;
405                                 ModalWindows = new Stack(3);
406
407                                 MouseState = MouseButtons.None;
408                                 MousePosition = new Point(0, 0);
409
410                                 Caret.Timer = new Timer();
411                                 Caret.Timer.Interval = 500;             // FIXME - where should this number come from?
412                                 Caret.Timer.Tick += new EventHandler(CaretCallback);
413
414                                 SetupAtoms();
415
416                                 // Grab atom changes off the root window to catch certain WM events
417                                 XSelectInput(DisplayHandle, RootWindow, new IntPtr ((int)EventMask.PropertyChangeMask));
418
419                                 // Handle any upcoming errors
420                                 ErrorHandler = new XErrorHandler(HandleError);
421                                 XSetErrorHandler(ErrorHandler);
422                         } else {
423                                 throw new ArgumentNullException("Display", "Could not open display (X-Server required. Check you DISPLAY environment variable)");
424                         }
425                 }
426
427                 internal static void Where() {
428                         Console.WriteLine("Here: {0}\n", WhereString());
429                 }
430
431                 internal static string WhereString() {
432                         StackTrace      stack;
433                         StackFrame      frame;
434                         string          newline;
435                         string          unknown;
436                         StringBuilder   sb;
437                         MethodBase      method;
438
439                         newline = String.Format("{0}\t {1} ", Environment.NewLine, Locale.GetText("at"));
440                         unknown = Locale.GetText("<unknown method>");
441                         sb = new StringBuilder();
442                         stack = new StackTrace(true);
443
444                         for (int i = 0; i < stack.FrameCount; i++) {
445                                 frame = stack.GetFrame(i);
446                                 sb.Append(newline);
447
448                                 method = frame.GetMethod();
449                                 if (method != null) {
450                                         #if not
451                                                 sb.AppendFormat(frame.ToString());
452                                         #endif
453                                         if (frame.GetFileLineNumber() != 0) {
454                                                 sb.AppendFormat("{0}.{1} () [{2}:{3}]", method.DeclaringType.FullName, method.Name, Path.GetFileName(frame.GetFileName()), frame.GetFileLineNumber());
455                                         } else {
456                                                 sb.AppendFormat("{0}.{1} ()", method.DeclaringType.FullName, method.Name);
457                                         }
458                                 } else { 
459                                         sb.Append(unknown);
460                                 }
461                         }
462                         return sb.ToString();
463                 }
464                 #endregion      // Internal Methods
465
466                 #region Private Methods
467                 private static void SetupAtoms() {
468                         NetAtoms = new IntPtr[(int)NA.LAST_NET_ATOM];
469
470                         NetAtoms[(int)NA.WM_PROTOCOLS] = XInternAtom(DisplayHandle, "WM_PROTOCOLS", false);
471                         NetAtoms[(int)NA.WM_DELETE_WINDOW] = XInternAtom(DisplayHandle, "WM_DELETE_WINDOW", false);
472                         NetAtoms[(int)NA.WM_TAKE_FOCUS] = XInternAtom(DisplayHandle, "WM_TAKE_FOCUS", false);
473
474                         NetAtoms[(int)NA._NET_SUPPORTED] = XInternAtom(DisplayHandle, "_NET_SUPPORTED", false);
475                         NetAtoms[(int)NA._NET_CLIENT_LIST] = XInternAtom(DisplayHandle, "_NET_CLIENT_LIST", false);
476                         NetAtoms[(int)NA._NET_NUMBER_OF_DESKTOPS] = XInternAtom(DisplayHandle, "_NET_NUMBER_OF_DESKTOPS", false);
477                         NetAtoms[(int)NA._NET_DESKTOP_GEOMETRY] = XInternAtom(DisplayHandle, "_NET_DESKTOP_GEOMETRY", false);
478                         NetAtoms[(int)NA._NET_DESKTOP_VIEWPORT] = XInternAtom(DisplayHandle, "_NET_DESKTOP_VIEWPORT", false);
479                         NetAtoms[(int)NA._NET_CURRENT_DESKTOP] = XInternAtom(DisplayHandle, "_NET_CURRENT_DESKTOP", false);
480                         NetAtoms[(int)NA._NET_DESKTOP_NAMES] = XInternAtom(DisplayHandle, "_NET_DESKTOP_NAMES", false);
481                         NetAtoms[(int)NA._NET_ACTIVE_WINDOW] = XInternAtom(DisplayHandle, "_NET_ACTIVE_WINDOW", false);
482                         NetAtoms[(int)NA._NET_WORKAREA] = XInternAtom(DisplayHandle, "_NET_WORKAREA", false);
483                         NetAtoms[(int)NA._NET_SUPPORTING_WM_CHECK] = XInternAtom(DisplayHandle, "_NET_SUPPORTING_WM_CHECK", false);
484                         NetAtoms[(int)NA._NET_VIRTUAL_ROOTS] = XInternAtom(DisplayHandle, "_NET_VIRTUAL_ROOTS", false);
485                         NetAtoms[(int)NA._NET_DESKTOP_LAYOUT] = XInternAtom(DisplayHandle, "_NET_DESKTOP_LAYOUT", false);
486                         NetAtoms[(int)NA._NET_SHOWING_DESKTOP] = XInternAtom(DisplayHandle, "_NET_SHOWING_DESKTOP", false);
487
488                         NetAtoms[(int)NA._NET_CLOSE_WINDOW] = XInternAtom(DisplayHandle, "_NET_CLOSE_WINDOW", false);
489                         NetAtoms[(int)NA._NET_MOVERESIZE_WINDOW] = XInternAtom(DisplayHandle, "_NET_MOVERESIZE_WINDOW", false);
490                         NetAtoms[(int)NA._NET_WM_MOVERESIZE] = XInternAtom(DisplayHandle, "_NET_WM_MOVERESIZE", false);
491                         NetAtoms[(int)NA._NET_RESTACK_WINDOW] = XInternAtom(DisplayHandle, "_NET_RESTACK_WINDOW", false);
492                         NetAtoms[(int)NA._NET_REQUEST_FRAME_EXTENTS] = XInternAtom(DisplayHandle, "_NET_REQUEST_FRAME_EXTENTS", false);
493
494                         NetAtoms[(int)NA._NET_WM_NAME] = XInternAtom(DisplayHandle, "_NET_WM_NAME", false);
495                         NetAtoms[(int)NA._NET_WM_VISIBLE_NAME] = XInternAtom(DisplayHandle, "_NET_WM_VISIBLE_NAME", false);
496                         NetAtoms[(int)NA._NET_WM_ICON_NAME] = XInternAtom(DisplayHandle, "_NET_WM_ICON_NAME", false);
497                         NetAtoms[(int)NA._NET_WM_VISIBLE_ICON_NAME] = XInternAtom(DisplayHandle, "_NET_WM_VISIBLE_ICON_NAME", false);
498                         NetAtoms[(int)NA._NET_WM_DESKTOP] = XInternAtom(DisplayHandle, "_NET_WM_DESKTOP", false);
499                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE", false);
500                         NetAtoms[(int)NA._NET_WM_STATE] = XInternAtom(DisplayHandle, "_NET_WM_STATE", false);
501                         NetAtoms[(int)NA._NET_WM_ALLOWED_ACTIONS] = XInternAtom(DisplayHandle, "_NET_WM_ALLOWED_ACTIONS", false);
502                         NetAtoms[(int)NA._NET_WM_STRUT] = XInternAtom(DisplayHandle, "_NET_WM_STRUT", false);
503                         NetAtoms[(int)NA._NET_WM_STRUT_PARTIAL] = XInternAtom(DisplayHandle, "_NET_WM_STRUT_PARTIAL", false);
504                         NetAtoms[(int)NA._NET_WM_ICON_GEOMETRY] = XInternAtom(DisplayHandle, "_NET_WM_ICON_GEOMETRY", false);
505                         NetAtoms[(int)NA._NET_WM_ICON] = XInternAtom(DisplayHandle, "_NET_WM_ICON", false);
506                         NetAtoms[(int)NA._NET_WM_PID] = XInternAtom(DisplayHandle, "_NET_WM_PID", false);
507                         NetAtoms[(int)NA._NET_WM_HANDLED_ICONS] = XInternAtom(DisplayHandle, "_NET_WM_HANDLED_ICONS", false);
508                         NetAtoms[(int)NA._NET_WM_USER_TIME] = XInternAtom(DisplayHandle, "_NET_WM_USER_TIME", false);
509                         NetAtoms[(int)NA._NET_FRAME_EXTENTS] = XInternAtom(DisplayHandle, "_NET_FRAME_EXTENTS", false);
510
511                         NetAtoms[(int)NA._NET_WM_PING] = XInternAtom(DisplayHandle, "_NET_WM_PING", false);
512                         NetAtoms[(int)NA._NET_WM_SYNC_REQUEST] = XInternAtom(DisplayHandle, "_NET_WM_SYNC_REQUEST", false);
513
514                         NetAtoms[(int)NA._NET_SYSTEM_TRAY_S] = XInternAtom(DisplayHandle, "_NET_SYSTEM_TRAY_S" + ScreenNo.ToString(), false);
515                         NetAtoms[(int)NA._NET_SYSTEM_TRAY_OPCODE] = XInternAtom(DisplayHandle, "_NET_SYSTEM_TRAY_OPCODE", false);
516                         NetAtoms[(int)NA._NET_SYSTEM_TRAY_ORIENTATION] = XInternAtom(DisplayHandle, "_NET_SYSTEM_TRAY_ORIENTATION", false);
517
518                         NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_HORZ] = XInternAtom(DisplayHandle, "_NET_WM_STATE_MAXIMIZED_HORZ", false);
519                         NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_VERT] = XInternAtom(DisplayHandle, "_NET_WM_STATE_MAXIMIZED_VERT", false);
520                         NetAtoms[(int)NA._NET_WM_STATE_HIDDEN] = XInternAtom(DisplayHandle, "_NET_WM_STATE_HIDDEN", false);
521
522                         NetAtoms[(int)NA._XEMBED] = XInternAtom(DisplayHandle, "_XEMBED", false);
523                         NetAtoms[(int)NA._XEMBED_INFO] = XInternAtom(DisplayHandle, "_XEMBED_INFO", false);
524
525                         NetAtoms[(int)NA._MOTIF_WM_HINTS] = XInternAtom(DisplayHandle, "_MOTIF_WM_HINTS", false);
526
527                         NetAtoms[(int)NA._NET_WM_STATE_NO_TASKBAR] = XInternAtom(DisplayHandle, "_NET_WM_STATE_NO_TASKBAR", false);
528                         NetAtoms[(int)NA._NET_WM_STATE_ABOVE] = XInternAtom(DisplayHandle, "_NET_WM_STATE_ABOVE", false);
529                         NetAtoms[(int)NA._NET_WM_STATE_MODAL] = XInternAtom(DisplayHandle, "_NET_WM_STATE_MODAL", false);
530                         NetAtoms[(int)NA._NET_WM_CONTEXT_HELP] = XInternAtom(DisplayHandle, "_NET_WM_CONTEXT_HELP", false);
531                         NetAtoms[(int)NA._NET_WM_WINDOW_OPACITY] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_OPACITY", false);
532
533                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_DESKTOP] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE_DESKTOP", false);
534                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_DOCK] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE_DOCK", false);
535                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_TOOLBAR] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE_TOOLBAR", false);
536                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_MENU] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE_MENU", false);
537                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_UTILITY] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE_UTILITY", false);
538                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_DIALOG] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE_DIALOG", false);
539                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_SPLASH] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE_SPLASH", false);
540                         NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_NORMAL] = XInternAtom(DisplayHandle, "_NET_WM_WINDOW_TYPE_NORMAL", false);
541
542                         // Clipboard support
543                         NetAtoms[(int)NA.CLIPBOARD] = XInternAtom (DisplayHandle, "CLIPBOARD", false);
544                         NetAtoms[(int)NA.DIB] = (IntPtr)Atom.XA_PIXMAP;
545                         NetAtoms[(int)NA.OEMTEXT] = XInternAtom(DisplayHandle, "COMPOUND_TEXT", false);
546                         NetAtoms[(int)NA.UNICODETEXT] = XInternAtom(DisplayHandle, "UTF8_STRING", false);
547                         NetAtoms[(int)NA.TARGETS] = XInternAtom(DisplayHandle, "TARGETS", false);
548
549                         // Special Atoms
550                         AsyncAtom = XInternAtom(DisplayHandle, "_SWF_AsyncAtom", false);
551                         PostAtom = XInternAtom (DisplayHandle, "_SWF_PostMessageAtom", false);
552                         HoverState.Atom = XInternAtom(DisplayHandle, "_SWF_HoverAtom", false);
553                 }
554
555                 private void GetSystrayManagerWindow() {
556                         XGrabServer(DisplayHandle);
557                         SystrayMgrWindow = XGetSelectionOwner(DisplayHandle, NetAtoms[(int)NA._NET_SYSTEM_TRAY_S]);
558                         XUngrabServer(DisplayHandle);
559                         XFlush(DisplayHandle);
560                 }
561
562                 private void SendNetWMMessage(IntPtr window, IntPtr message_type, IntPtr l0, IntPtr l1, IntPtr l2) {
563                         XEvent  xev;
564
565                         xev = new XEvent();
566                         xev.ClientMessageEvent.type = XEventName.ClientMessage;
567                         xev.ClientMessageEvent.send_event = true;
568                         xev.ClientMessageEvent.window = window;
569                         xev.ClientMessageEvent.message_type = message_type;
570                         xev.ClientMessageEvent.format = 32;
571                         xev.ClientMessageEvent.ptr1 = l0;
572                         xev.ClientMessageEvent.ptr2 = l1;
573                         xev.ClientMessageEvent.ptr3 = l2;
574                         XSendEvent(DisplayHandle, RootWindow, false, new IntPtr ((int) (EventMask.SubstructureRedirectMask | EventMask.SubstructureNotifyMask)), ref xev);
575                 }
576
577                 private void SendNetClientMessage(IntPtr window, IntPtr message_type, IntPtr l0, IntPtr l1, IntPtr l2) {
578                         XEvent  xev;
579
580                         xev = new XEvent();
581                         xev.ClientMessageEvent.type = XEventName.ClientMessage;
582                         xev.ClientMessageEvent.send_event = true;
583                         xev.ClientMessageEvent.window = window;
584                         xev.ClientMessageEvent.message_type = message_type;
585                         xev.ClientMessageEvent.format = 32;
586                         xev.ClientMessageEvent.ptr1 = l0;
587                         xev.ClientMessageEvent.ptr2 = l1;
588                         xev.ClientMessageEvent.ptr3 = l2;
589                         XSendEvent(DisplayHandle, window, false, new IntPtr ((int)EventMask.NoEventMask), ref xev);
590                 }
591
592                 private void DeriveStyles(int Style, int ExStyle, out FormBorderStyle border_style, out TitleStyle title_style, out int caption_height, out int tool_caption_height) {
593
594                         // Only MDI windows get caption_heights
595                         caption_height = 0;
596                         tool_caption_height = 19;
597
598                         if ((Style & (int) WindowStyles.WS_CHILD) != 0) {
599                                 if ((ExStyle & (int) WindowExStyles.WS_EX_CLIENTEDGE) != 0) {
600                                         border_style = FormBorderStyle.Fixed3D;
601                                 } else if ((Style & (int) WindowStyles.WS_BORDER) == 0) {
602                                         border_style = FormBorderStyle.None;
603                                 } else {
604                                         border_style = FormBorderStyle.FixedSingle;
605                                 }
606                                 title_style = TitleStyle.None;
607
608                                 if ((ExStyle & (int) WindowExStyles.WS_EX_MDICHILD) != 0) {
609                                         caption_height = 26;
610
611                                         if ((Style & (int)WindowStyles.WS_CAPTION) != 0) {
612                                                 if ((ExStyle & (int)WindowExStyles.WS_EX_TOOLWINDOW) != 0) {
613                                                         title_style = TitleStyle.Tool;
614                                                 } else {
615                                                         title_style = TitleStyle.Normal;
616                                                 }
617                                         }
618
619                                         if ((Style & (int) WindowStyles.WS_OVERLAPPEDWINDOW) != 0 ||
620                                                         (ExStyle & (int) WindowExStyles.WS_EX_TOOLWINDOW) != 0) {
621                                                 border_style = (FormBorderStyle) 0xFFFF;
622                                         } else {
623                                                 border_style = FormBorderStyle.None;
624                                         }
625                                 }
626
627                         } else {
628                                 title_style = TitleStyle.None;
629                                 if ((Style & (int)WindowStyles.WS_CAPTION) != 0) {
630                                         if ((ExStyle & (int)WindowExStyles.WS_EX_TOOLWINDOW) != 0) {
631                                                 title_style = TitleStyle.Tool;
632                                         } else {
633                                                 title_style = TitleStyle.Normal;
634                                         }
635                                 }
636
637                                 border_style = FormBorderStyle.None;
638
639                                 if ((Style & (int)WindowStyles.WS_THICKFRAME) != 0) {
640                                         if ((ExStyle & (int)WindowExStyles.WS_EX_TOOLWINDOW) != 0) {
641                                                 border_style = FormBorderStyle.SizableToolWindow;
642                                         } else {
643                                                 border_style = FormBorderStyle.Sizable;
644                                         }
645                                 } else {
646                                         if ((ExStyle & (int)WindowExStyles.WS_EX_CLIENTEDGE) != 0) {
647                                                 border_style = FormBorderStyle.Fixed3D;
648                                         } else if ((ExStyle & (int)WindowExStyles.WS_EX_DLGMODALFRAME) != 0) {
649                                                 border_style = FormBorderStyle.FixedDialog;
650                                         } else if ((ExStyle & (int)WindowExStyles.WS_EX_TOOLWINDOW) != 0) {
651                                                 border_style = FormBorderStyle.FixedToolWindow;
652                                         } else if ((Style & (int)WindowStyles.WS_BORDER) != 0) {
653                                                 border_style = FormBorderStyle.Sizable;
654                                         } else {
655                                                 border_style = FormBorderStyle.None;
656                                         }
657                                 }
658                         }
659                 }
660
661                 private void SetHwndStyles(Hwnd hwnd, CreateParams cp) {
662                         DeriveStyles(cp.Style, cp.ExStyle, out hwnd.border_style, out hwnd.title_style, out hwnd.caption_height, out hwnd.tool_caption_height);
663                 }
664
665                 private void SetWMStyles(Hwnd hwnd, CreateParams cp) {
666                         MotifWmHints            mwmHints;
667                         MotifFunctions          functions;
668                         MotifDecorations        decorations;
669                         int                     atom_count;
670                         Rectangle               client_rect;
671                         bool                    transient;
672
673                         // Child windows don't need WM window styles
674                         if ((cp.Style & (int)WindowStyles.WS_CHILDWINDOW) != 0) {
675                                 return;
676                         }
677
678                         transient = false;
679
680                         mwmHints = new MotifWmHints();
681                         functions = 0;
682                         decorations = 0;
683
684                         mwmHints.flags = (IntPtr)(MotifFlags.Functions | MotifFlags.Decorations);
685                         mwmHints.functions = (IntPtr)0;
686                         mwmHints.decorations = (IntPtr)0;
687
688                         if ((cp.Style & (int)WindowStyles.WS_CAPTION) != 0) {
689                                 functions |= MotifFunctions.Move;
690                                 decorations |= MotifDecorations.Title | MotifDecorations.Menu;
691                         }
692
693                         if ((cp.Style & ((int)WindowStyles.WS_THICKFRAME)) != 0) {
694                                 functions |= MotifFunctions.Move | MotifFunctions.Resize;
695                                 decorations |= MotifDecorations.Border | MotifDecorations.ResizeH;
696                         }
697                         if ((cp.Style & ((int)WindowStyles.WS_MINIMIZEBOX)) != 0) {
698                                 functions |= MotifFunctions.Minimize;
699                                 decorations |= MotifDecorations.Minimize;
700                         }
701
702                         if ((cp.Style & ((int)WindowStyles.WS_MAXIMIZEBOX)) != 0) {
703                                 functions |= MotifFunctions.Maximize;
704                                 decorations |= MotifDecorations.Maximize;
705                         }
706
707                         if ((cp.Style & ((int)WindowStyles.WS_SYSMENU)) != 0) {
708                                 functions |= MotifFunctions.Close;
709                         }
710
711                         if ((cp.ExStyle & ((int)WindowExStyles.WS_EX_DLGMODALFRAME)) != 0) {
712                                 decorations |= MotifDecorations.Border;
713                         }
714
715                         if ((cp.Style & ((int)WindowStyles.WS_DLGFRAME)) != 0) {
716                                 decorations |= MotifDecorations.Border;
717                         }
718
719                         if ((cp.Style & ((int)WindowStyles.WS_BORDER)) != 0) {
720                                 decorations |= MotifDecorations.Border;
721                         }
722
723                         if ((cp.ExStyle & ((int)WindowExStyles.WS_EX_TOOLWINDOW)) != 0) {
724                                 functions = 0;
725                                 decorations = 0;
726                         }
727
728                         if ((functions & MotifFunctions.Resize) == 0) {
729                                 hwnd.fixed_size = true;
730                                 XplatUI.SetWindowMinMax(hwnd.Handle, new Rectangle(cp.X, cp.Y, cp.Width, cp.Height), new Size(cp.Width, cp.Height), new Size(cp.Width, cp.Height));
731                         } else {
732                                 hwnd.fixed_size = false;
733                         }
734
735                         mwmHints.functions = (IntPtr)functions;
736                         mwmHints.decorations = (IntPtr)decorations;
737
738                         client_rect = hwnd.ClientRect;
739                         lock (XlibLock) {
740                                 XChangeProperty(DisplayHandle, hwnd.whole_window, NetAtoms[(int)NA._MOTIF_WM_HINTS], NetAtoms[(int)NA._MOTIF_WM_HINTS], 32, PropertyMode.Replace, ref mwmHints, 5);
741
742                                 if (((cp.Style & (int)WindowStyles.WS_POPUP) != 0)  && (hwnd.parent != null) && (hwnd.parent.whole_window != IntPtr.Zero)) {
743                                         transient = true;
744                                         XSetTransientForHint(DisplayHandle, hwnd.whole_window, hwnd.parent.whole_window);
745                                 } else if ((cp.ExStyle & (int)WindowExStyles.WS_EX_APPWINDOW) == 0) {
746                                         transient = true;
747                                         XSetTransientForHint(DisplayHandle, hwnd.whole_window, FosterParent);
748                                 }
749                                 XMoveResizeWindow(DisplayHandle, hwnd.client_window, client_rect.X, client_rect.Y, client_rect.Width, client_rect.Height);
750
751                                 int[] atoms = new int[8];
752                                 atom_count = 0;
753
754                                 if ((cp.ExStyle & ((int)WindowExStyles.WS_EX_TOOLWINDOW)) != 0) {
755                                         atoms[atom_count++] = NetAtoms[(int)NA._NET_WM_STATE_NO_TASKBAR].ToInt32();
756                                 }
757                                 XChangeProperty(DisplayHandle, hwnd.whole_window, NetAtoms[(int)NA._NET_WM_STATE], (IntPtr)Atom.XA_ATOM, 32, PropertyMode.Replace, atoms, atom_count);
758
759                                 if (transient) {
760                                         atom_count = 0;
761                                         if ((cp.ExStyle & ((int)WindowExStyles.WS_EX_TOOLWINDOW)) != 0) {
762                                                 atoms[atom_count++] = atoms[atom_count++] = NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_TOOLBAR].ToInt32();
763                                         } else if (decorations == 0) {
764                                                 atoms[atom_count++] = atoms[atom_count++] = NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_DOCK].ToInt32();
765                                         } else {
766                                                 atoms[atom_count++] = atoms[atom_count++] = NetAtoms[(int)NA._NET_WM_WINDOW_TYPE_DIALOG].ToInt32();
767                                         }
768                                         XChangeProperty(DisplayHandle, hwnd.whole_window, NetAtoms[(int)NA._NET_WM_WINDOW_TYPE], (IntPtr)Atom.XA_ATOM, 32, PropertyMode.Replace, atoms, atom_count);
769                                 }
770
771                                 atom_count = 0;
772                                 IntPtr[] atom_ptrs = new IntPtr[2];
773
774                                 atom_ptrs[atom_count++] = NetAtoms[(int)NA.WM_DELETE_WINDOW];
775                                 if ((cp.ExStyle & (int)WindowExStyles.WS_EX_CONTEXTHELP) != 0) {
776                                         atom_ptrs[atom_count++] = NetAtoms[(int)NA._NET_WM_CONTEXT_HELP];
777                                 }
778
779                                 XSetWMProtocols(DisplayHandle, hwnd.whole_window, atom_ptrs, atom_count);
780                         }
781                 }
782
783                 private void SetIcon(Hwnd hwnd, Icon icon) {
784                         Bitmap          bitmap;
785                         int             size;
786                         IntPtr[]        data;
787                         int             index;
788
789                         bitmap = icon.ToBitmap();
790                         index = 0;
791                         size = bitmap.Width * bitmap.Height + 2;
792                         data = new IntPtr[size];
793
794                         data[index++] = (IntPtr)bitmap.Width;
795                         data[index++] = (IntPtr)bitmap.Height;
796
797                         for (int y = 0; y < bitmap.Height; y++) {
798                                 for (int x = 0; x < bitmap.Width; x++) {
799                                         data[index++] = (IntPtr)bitmap.GetPixel(x, y).ToArgb();
800                                 }
801                         }
802
803                         XChangeProperty(DisplayHandle, hwnd.whole_window, NetAtoms[(int)NA._NET_WM_ICON], (IntPtr)Atom.XA_CARDINAL, 32, PropertyMode.Replace, data, size);
804                 }
805
806                 private IntPtr ImageToPixmap(Image image) {
807                         return IntPtr.Zero;
808                 }
809
810                 private void WakeupMain () {
811                         wake.Send (new byte [] { 0xFF });
812                 }
813
814                 private XEventQueue ThreadQueue(Thread thread) {
815                         XEventQueue     queue;
816
817                         queue = (XEventQueue)MessageQueues[thread];
818                         if (queue == null) {
819                                 queue = new XEventQueue(thread);
820                                 MessageQueues[thread] = queue;
821                         }
822
823                         return queue;
824                 }
825
826                 private void TranslatePropertyToClipboard(IntPtr property) {
827                         IntPtr                  actual_atom;
828                         int                     actual_format;
829                         IntPtr                  nitems;
830                         IntPtr                  bytes_after;
831                         IntPtr                  prop = IntPtr.Zero;
832
833                         Clipboard.Item = null;
834
835                         XGetWindowProperty(DisplayHandle, FosterParent, property, IntPtr.Zero, new IntPtr (0x7fffffff), true, (IntPtr)Atom.AnyPropertyType, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
836
837                         if ((long)nitems > 0) {
838                                 if (property == (IntPtr)Atom.XA_STRING) {
839                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
840                                 } else if (property == (IntPtr)Atom.XA_BITMAP) {
841                                         // FIXME - convert bitmap to image
842                                 } else if (property == (IntPtr)Atom.XA_PIXMAP) {
843                                         // FIXME - convert pixmap to image
844                                 } else if (property == NetAtoms[(int)NA.OEMTEXT]) {
845                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
846                                 } else if (property == NetAtoms[(int)NA.UNICODETEXT]) {
847                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
848                                 }
849
850                                 XFree(prop);
851                         }
852                 }
853
854                 private void AddExpose (Hwnd hwnd, bool client, int x, int y, int width, int height) {
855                         // Don't waste time
856                         if (hwnd == null) {     
857                                 return;
858                         }
859
860                         if (client) {
861                                 hwnd.AddInvalidArea(x, y, width, height);
862                                 if (!hwnd.expose_pending) {
863                                         if (!hwnd.nc_expose_pending) {
864                                                 hwnd.Queue.Paint.Enqueue(hwnd);
865                                         }
866                                         hwnd.expose_pending = true;
867                                 }
868                         } else {
869                                 hwnd.AddNcInvalidArea (x, y, width, height);
870                                 
871                                 if (!hwnd.nc_expose_pending) {
872                                         if (!hwnd.expose_pending) {
873                                                 hwnd.Queue.Paint.Enqueue(hwnd);
874                                         }
875                                         hwnd.nc_expose_pending = true;
876                                 }
877                         }
878                 }
879
880                 private void InvalidateWholeWindow(IntPtr handle) {
881                         Hwnd    hwnd;
882
883                         hwnd = Hwnd.ObjectFromHandle(handle);
884
885                         InvalidateWholeWindow(handle, new Rectangle(0, 0, hwnd.Width, hwnd.Height));
886                 }
887
888                 private void InvalidateWholeWindow(IntPtr handle, Rectangle rectangle) {
889                         Hwnd    hwnd;
890
891                         hwnd = Hwnd.ObjectFromHandle(handle);
892
893                         AddExpose (hwnd, false, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
894                 }
895
896                 private void WholeToScreen(IntPtr handle, ref int x, ref int y) {
897                         int     dest_x_return;
898                         int     dest_y_return;
899                         IntPtr  child;
900                         Hwnd    hwnd;
901
902                         hwnd = Hwnd.ObjectFromHandle(handle);
903
904                         lock (XlibLock) {
905                                 XTranslateCoordinates(DisplayHandle, hwnd.whole_window, RootWindow, x, y, out dest_x_return, out dest_y_return, out child);
906                         }
907
908                         x = dest_x_return;
909                         y = dest_y_return;
910                 }
911
912                 private void AbsoluteGeometry(IntPtr window, out int ret_x, out int ret_y, out int width, out int height) {
913                         IntPtr  root;
914                         IntPtr  win;
915                         IntPtr  parent;
916                         IntPtr  children;
917                         int     x;
918                         int     y;
919                         int     w;
920                         int     h;
921                         int     absX;
922                         int     absY;
923                         int     b;
924                         int     d;
925                         int     nchildren;
926
927                         absX = 0;
928                         absY = 0;
929                         win = window;
930                         width = 0;
931                         height = 0;
932                         do {
933                                 XGetGeometry(DisplayHandle, win, out root, out x, out y, out w, out h, out b, out d);
934                                 if (win == window) {
935                                         width = w;
936                                         height = h;
937                                 }
938                                 absX += x;
939                                 absY += y;
940                                 if (XQueryTree(DisplayHandle, win, out root, out parent,  out children, out nchildren) == 0) {
941                                         break;
942                                 }
943
944                                 if (children != IntPtr.Zero) {
945                                         XFree(children);
946                                 }
947                                 win = parent;
948                         } while (win != root);
949
950                         ret_x = absX;
951                         ret_y = absY;
952
953 //Console.WriteLine("Absolute pos for window {0} = {1},{2} {3}x{4}", XplatUI.Window(window), ret_x, ret_y, width, height);
954                 }
955
956                 private void FrameExtents(IntPtr window, out int left, out int top) {
957                         IntPtr                  actual_atom;
958                         int                     actual_format;
959                         IntPtr                  nitems;
960                         IntPtr                  bytes_after;
961                         IntPtr                  prop = IntPtr.Zero;
962
963                         XGetWindowProperty(DisplayHandle, window, NetAtoms[(int)NA._NET_FRAME_EXTENTS], IntPtr.Zero, new IntPtr (16), false, (IntPtr)Atom.XA_CARDINAL, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
964                         if (((long)nitems == 4) && (prop != IntPtr.Zero)) {
965                                 left = Marshal.ReadIntPtr(prop, 0).ToInt32();
966                                 //right = Marshal.ReadIntPtr(prop, IntPtr.Size).ToInt32();
967                                 top = Marshal.ReadIntPtr(prop, IntPtr.Size * 2).ToInt32();
968                                 //bottom = Marshal.ReadIntPtr(prop, IntPtr.Size * 3).ToInt32();
969                         } else {
970                                 left = 0;
971                                 top = 0;
972                         }
973
974                         if (prop != IntPtr.Zero) {
975                                 XFree(prop);
976                         }
977                         return;
978                 }
979
980                 private void AddConfigureNotify (XEvent xevent) {
981                         Hwnd    hwnd;
982
983                         hwnd = Hwnd.GetObjectFromWindow(xevent.ConfigureEvent.window);
984
985                         // Don't waste time
986                         if (hwnd == null) {
987                                 return;
988                         }
989
990                         if (xevent.ConfigureEvent.window == hwnd.whole_window) {
991                                 if (!hwnd.reparented) {
992                                         hwnd.x = xevent.ConfigureEvent.x;
993                                         hwnd.y = xevent.ConfigureEvent.y;
994                                 } else {
995                                         // This sucks ass, part 1
996                                         // Every WM does the ConfigureEvents of toplevel windows different, so there's
997                                         // no standard way of getting our adjustment. 
998                                         // The code below is needed for KDE and FVWM, the 'whacky_wm' part is for metacity
999                                         // Several other WMs do their decorations different yet again and we fail to deal 
1000                                         // with that, since I couldn't find any frigging commonality between them.
1001                                         // The only sane WM seems to be KDE
1002
1003                                         if (!xevent.ConfigureEvent.send_event) {
1004                                                 IntPtr  dummy_ptr;
1005
1006                                                 XTranslateCoordinates(DisplayHandle, hwnd.whole_window, RootWindow, -xevent.ConfigureEvent.x, -xevent.ConfigureEvent.y, out hwnd.x, out hwnd.y, out dummy_ptr);
1007                                         } else {
1008                                                 // This is a synthetic event, coordinates are in root space
1009                                                 hwnd.x = xevent.ConfigureEvent.x;
1010                                                 hwnd.y = xevent.ConfigureEvent.y;
1011                                                 if (hwnd.whacky_wm) {
1012                                                         int frame_left;
1013                                                         int frame_top;
1014
1015                                                         FrameExtents(hwnd.whole_window, out frame_left, out frame_top);
1016                                                         hwnd.x -= frame_left;
1017                                                         hwnd.y -= frame_top;
1018                                                 }
1019                                         }
1020                                 }
1021                                 hwnd.width = xevent.ConfigureEvent.width;
1022                                 hwnd.height = xevent.ConfigureEvent.height;
1023
1024                                 if (!hwnd.configure_pending) {
1025                                         hwnd.Queue.Enqueue(xevent);
1026                                         hwnd.configure_pending = true;
1027                                 }
1028                         }
1029                         // We drop configure events for Client windows
1030                 }
1031
1032                 private void ShowCaret() {
1033                         if ((Caret.gc == IntPtr.Zero) || Caret.On) {
1034                                 return;
1035                         }
1036                         Caret.On = true;
1037
1038                         lock (XlibLock) {
1039                                 XDrawLine(DisplayHandle, Caret.Window, Caret.gc, Caret.X, Caret.Y, Caret.X, Caret.Y + Caret.Height);
1040                         }
1041                 }
1042
1043                 private void HideCaret() {
1044                         if ((Caret.gc == IntPtr.Zero) || !Caret.On) {
1045                                 return;
1046                         }
1047                         Caret.On = false;
1048
1049                         lock (XlibLock) {
1050                                 XDrawLine(DisplayHandle, Caret.Window, Caret.gc, Caret.X, Caret.Y, Caret.X, Caret.Y + Caret.Height);
1051                         }
1052                 }
1053
1054                 private int NextTimeout (DateTime now) {
1055                         int timeout = Int32.MaxValue; 
1056                         lock (TimerList) {
1057                                 foreach (Timer timer in TimerList) {
1058                                         int next = (int) (timer.Expires - now).TotalMilliseconds;
1059                                         if (next < 0) {
1060                                                 return 0; // Have a timer that has already expired
1061                                         }
1062
1063                                         if (next < timeout) {
1064                                                 timeout = next;
1065                                         }
1066                                 }
1067                         }
1068                         if (timeout < Timer.Minimum) {
1069                                 timeout = Timer.Minimum;
1070                         }
1071
1072                         if (timeout > 1000)
1073                                 timeout = 1000;
1074                         return timeout;
1075                 }
1076
1077                 private void CheckTimers (DateTime now) {
1078                         lock (TimerList) {
1079                                 int count;
1080
1081                                 count = TimerList.Count;
1082
1083                                 if (count == 0) {
1084                                         return;
1085                                 }
1086
1087                                 for (int i = 0; i < TimerList.Count; i++) {
1088                                         Timer timer;
1089
1090                                         timer = (Timer) TimerList[i];
1091
1092                                         if (timer.Enabled && timer.Expires <= now) {
1093                                                 timer.Update (now);
1094                                                 timer.FireTick ();
1095                                         }
1096                                 }
1097                         }
1098                 }
1099
1100                 private void MapWindow(Hwnd hwnd, WindowType windows) {
1101                         hwnd.mapped = true;
1102                         if ((windows & WindowType.Whole) != 0) {
1103                                 XMapWindow(DisplayHandle, hwnd.whole_window);
1104                         }
1105                         if ((windows & WindowType.Client) != 0) {
1106                                 XMapWindow(DisplayHandle, hwnd.client_window);
1107                         }
1108                 }
1109
1110                 private void UnmapWindow(Hwnd hwnd, WindowType windows) {
1111                         hwnd.mapped = false;
1112                         if ((windows & WindowType.Whole) != 0) {
1113                                 XUnmapWindow(DisplayHandle, hwnd.whole_window);
1114                         }
1115                         if ((windows & WindowType.Client) != 0) {
1116                                 XUnmapWindow(DisplayHandle, hwnd.client_window);
1117                         }
1118                 }
1119
1120                 private void UpdateMessageQueue (XEventQueue queue) {
1121                         DateTime        now;
1122                         int             pending;
1123                         Hwnd            hwnd;
1124
1125                         now = DateTime.Now;
1126
1127                         lock (XlibLock) {
1128                                 pending = XPending (DisplayHandle);
1129                         }
1130
1131                         if (pending == 0) {
1132                                 if (Idle != null) {
1133                                         Idle (this, EventArgs.Empty);
1134                                 }
1135
1136                                 lock (XlibLock) {
1137                                         pending = XPending (DisplayHandle);
1138                                 }
1139                         }
1140
1141                         if (pending == 0) {
1142                                 int     timeout;
1143
1144                                 if ((queue != null) && (queue.Paint.Count > 0)) {
1145                                         return;
1146                                 }
1147
1148                                 timeout = NextTimeout (now);
1149                                 if (timeout > 0) {
1150                                         #if __MonoCS__
1151                                         Syscall.poll (pollfds, (uint) pollfds.Length, timeout);
1152                                         // Clean out buffer, so we're not busy-looping on the same data
1153                                         if (pollfds[1].revents != 0) {
1154                                                 wake_receive.Receive(network_buffer, 0, 1, SocketFlags.None);
1155                                         }
1156                                         #endif
1157                                         lock (XlibLock) {
1158                                                 pending = XPending (DisplayHandle);
1159                                         }
1160                                 }
1161                         }
1162
1163                         CheckTimers (now);
1164
1165                         if (pending == 0) {
1166                                 lock (XlibLock) {
1167                                         pending = XPending (DisplayHandle);
1168                                 }
1169                         }
1170
1171                         while (pending > 0) {
1172                                 XEvent xevent = new XEvent ();
1173
1174                                 lock (XlibLock) {
1175                                         XNextEvent (DisplayHandle, ref xevent);
1176
1177                                         if (xevent.AnyEvent.type == XEventName.KeyPress) {
1178                                                 if (XFilterEvent(ref xevent, FosterParent)) {
1179                                                         continue;
1180                                                 }
1181                                         }
1182                                 }
1183 //Console.WriteLine("Got x event {0}", xevent);
1184
1185                                 hwnd = Hwnd.GetObjectFromWindow(xevent.AnyEvent.window);
1186                                 if (hwnd == null) {
1187                                         pending = XPending (DisplayHandle);
1188                                         continue;
1189                                 }
1190                                 switch (xevent.type) {
1191                                         case XEventName.Expose:
1192                                                 AddExpose (hwnd, xevent.ExposeEvent.window == hwnd.ClientWindow, xevent.ExposeEvent.x, xevent.ExposeEvent.y, xevent.ExposeEvent.width, xevent.ExposeEvent.height);
1193                                                 break;
1194
1195                                         case XEventName.SelectionClear: {
1196                                                 // Should we do something?
1197                                                 break;
1198                                         }
1199
1200                                         case XEventName.SelectionRequest: {
1201                                                 if (Dnd.HandleSelectionRequestEvent (ref xevent))
1202                                                         break;
1203                                                 XEvent sel_event;
1204
1205                                                 sel_event = new XEvent();
1206                                                 sel_event.SelectionEvent.type = XEventName.SelectionNotify;
1207                                                 sel_event.SelectionEvent.send_event = true;
1208                                                 sel_event.SelectionEvent.display = DisplayHandle;
1209                                                 sel_event.SelectionEvent.selection = xevent.SelectionRequestEvent.selection;
1210                                                 sel_event.SelectionEvent.target = xevent.SelectionRequestEvent.target;
1211                                                 sel_event.SelectionEvent.requestor = xevent.SelectionRequestEvent.requestor;
1212                                                 sel_event.SelectionEvent.time = xevent.SelectionRequestEvent.time;
1213                                                 sel_event.SelectionEvent.property = IntPtr.Zero;
1214
1215                                                 // Seems that some apps support asking for supported types
1216                                                 if (xevent.SelectionEvent.target == NetAtoms[(int)NA.TARGETS]) {
1217                                                         int[]   atoms;
1218                                                         int     atom_count;
1219
1220                                                         atoms = new int[5];
1221                                                         atom_count = 0;
1222
1223                                                         if (Clipboard.Item is String) {
1224                                                                 atoms[atom_count++] = (int)Atom.XA_STRING;
1225                                                                 atoms[atom_count++] = (int)NetAtoms[(int)NA.OEMTEXT];
1226                                                                 atoms[atom_count++] = (int)NetAtoms[(int)NA.UNICODETEXT];
1227                                                         } else if (Clipboard.Item is Image) {
1228                                                                 atoms[atom_count++] = (int)Atom.XA_PIXMAP;
1229                                                                 atoms[atom_count++] = (int)Atom.XA_BITMAP;
1230                                                         } else {
1231                                                                 // FIXME - handle other types
1232                                                         }
1233
1234                                                         XChangeProperty(DisplayHandle, xevent.SelectionEvent.requestor, (IntPtr)xevent.SelectionRequestEvent.property, (IntPtr)xevent.SelectionRequestEvent.target, 32, PropertyMode.Replace, atoms, atom_count);
1235                                                 } else if (Clipboard.Item is string) {
1236                                                         IntPtr  buffer;
1237                                                         int     buflen;
1238
1239                                                         buflen = 0;
1240
1241                                                         if (xevent.SelectionRequestEvent.target == (IntPtr)Atom.XA_STRING) {
1242                                                                 Byte[] bytes;
1243
1244                                                                 bytes = new ASCIIEncoding().GetBytes((string)Clipboard.Item);
1245                                                                 buffer = Marshal.AllocHGlobal(bytes.Length);
1246                                                                 buflen = bytes.Length;
1247
1248                                                                 for (int i = 0; i < buflen; i++) {
1249                                                                         Marshal.WriteByte(buffer, i, bytes[i]);
1250                                                                 }
1251                                                         } else if (xevent.SelectionRequestEvent.target == NetAtoms[(int)NA.OEMTEXT]) {
1252                                                                 // FIXME - this should encode into ISO2022
1253                                                                 buffer = Marshal.StringToHGlobalAnsi((string)Clipboard.Item);
1254                                                                 while (Marshal.ReadByte(buffer, buflen) != 0) {
1255                                                                         buflen++;
1256                                                                 }
1257                                                         } else if (xevent.SelectionRequestEvent.target == NetAtoms[(int)NA.UNICODETEXT]) {
1258                                                                 buffer = Marshal.StringToHGlobalAnsi((string)Clipboard.Item);
1259                                                                 while (Marshal.ReadByte(buffer, buflen) != 0) {
1260                                                                         buflen++;
1261                                                                 }
1262                                                         } else {
1263                                                                 buffer = IntPtr.Zero;
1264                                                         }
1265
1266                                                         if (buffer != IntPtr.Zero) {
1267                                                                 XChangeProperty(DisplayHandle, xevent.SelectionRequestEvent.requestor, (IntPtr)xevent.SelectionRequestEvent.property, (IntPtr)xevent.SelectionRequestEvent.target, 8, PropertyMode.Replace, buffer, buflen);
1268                                                                 sel_event.SelectionEvent.property = xevent.SelectionRequestEvent.property;
1269                                                                 Marshal.FreeHGlobal(buffer);
1270                                                         }
1271                                                 } else if (Clipboard.Item is Image) {
1272                                                         if (xevent.SelectionEvent.target == (IntPtr)Atom.XA_PIXMAP) {
1273                                                                 // FIXME - convert image and store as property
1274                                                         } else if (xevent.SelectionEvent.target == (IntPtr)Atom.XA_PIXMAP) {
1275                                                                 // FIXME - convert image and store as property
1276                                                         }
1277                                                 }
1278
1279                                                 XSendEvent(DisplayHandle, xevent.SelectionRequestEvent.requestor, false, new IntPtr ((int)EventMask.NoEventMask), ref sel_event);
1280                                                 break;
1281                                         }
1282
1283                                         case XEventName.SelectionNotify: {
1284                                                 if (Clipboard.Enumerating) {
1285                                                         Clipboard.Enumerating = false;
1286                                                         if (xevent.SelectionEvent.property != IntPtr.Zero) {
1287                                                                 XDeleteProperty(DisplayHandle, FosterParent, (IntPtr)xevent.SelectionEvent.property);
1288                                                                 if (!Clipboard.Formats.Contains(xevent.SelectionEvent.property)) {
1289                                                                         Clipboard.Formats.Add(xevent.SelectionEvent.property);
1290                                                                         #if DriverDebugExtra
1291                                                                                 Console.WriteLine("Got supported clipboard atom format: {0}", xevent.SelectionEvent.property);
1292                                                                         #endif
1293                                                                 }
1294                                                         }
1295                                                 } else if (Clipboard.Retrieving) {
1296                                                         Clipboard.Retrieving = false;
1297                                                         if (xevent.SelectionEvent.property != IntPtr.Zero) {
1298                                                                 TranslatePropertyToClipboard(xevent.SelectionEvent.property);
1299                                                         } else {
1300                                                                 Clipboard.Item = null;
1301                                                         }
1302                                                 } else {
1303                                                         Dnd.HandleSelectionNotifyEvent (ref xevent);
1304                                                 }
1305                                                 break;
1306                                         }
1307
1308                                         case XEventName.MapNotify: {
1309                                                 if (hwnd.client_window == xevent.MapEvent.window) {
1310                                                         hwnd.mapped = true;
1311                                                 }
1312                                                 break;
1313                                         }
1314
1315                                         case XEventName.UnmapNotify: {
1316                                                 if (hwnd.client_window == xevent.MapEvent.window) {
1317                                                         hwnd.mapped = false;
1318                                                 }
1319                                                 break;
1320                                         }
1321
1322                                         case XEventName.KeyPress:
1323                                         case XEventName.KeyRelease:
1324                                         case XEventName.ButtonPress:
1325                                         case XEventName.ButtonRelease:
1326                                         case XEventName.MotionNotify:
1327                                         case XEventName.EnterNotify:
1328                                         case XEventName.LeaveNotify:
1329                                         case XEventName.CreateNotify:
1330                                         case XEventName.DestroyNotify:
1331                                         case XEventName.FocusIn:
1332                                         case XEventName.FocusOut:
1333                                         case XEventName.ClientMessage:
1334                                         case XEventName.ReparentNotify:
1335                                                 hwnd.Queue.Enqueue (xevent);
1336                                                 break;
1337
1338                                         case XEventName.ConfigureNotify:
1339                                                 AddConfigureNotify(xevent);
1340                                                 break;
1341
1342                                         case XEventName.PropertyNotify:
1343                                                 if (xevent.PropertyEvent.atom == NetAtoms[(int)NA._NET_ACTIVE_WINDOW]) {
1344                                                         IntPtr  actual_atom;
1345                                                         int     actual_format;
1346                                                         IntPtr  nitems;
1347                                                         IntPtr  bytes_after;
1348                                                         IntPtr  prop = IntPtr.Zero;
1349                                                         IntPtr  prev_active;;
1350
1351                                                         prev_active = ActiveWindow;
1352                                                         XGetWindowProperty(DisplayHandle, RootWindow, NetAtoms[(int)NA._NET_ACTIVE_WINDOW], IntPtr.Zero, new IntPtr (1), false, (IntPtr)Atom.XA_WINDOW, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1353                                                         if (((long)nitems > 0) && (prop != IntPtr.Zero)) {
1354                                                                 ActiveWindow = Hwnd.GetHandleFromWindow((IntPtr)Marshal.ReadInt32(prop));
1355                                                                 XFree(prop);
1356
1357                                                                 if (prev_active != ActiveWindow) {
1358                                                                         if (prev_active != IntPtr.Zero) {
1359                                                                                 PostMessage(prev_active, Msg.WM_ACTIVATE, (IntPtr)WindowActiveFlags.WA_INACTIVE, IntPtr.Zero);
1360                                                                         }
1361                                                                         if (ActiveWindow != IntPtr.Zero) {
1362                                                                                 PostMessage(ActiveWindow, Msg.WM_ACTIVATE, (IntPtr)WindowActiveFlags.WA_ACTIVE, IntPtr.Zero);
1363                                                                         }
1364                                                                 }
1365                                                                 if (ModalWindows.Count == 0) {
1366                                                                         break;
1367                                                                 } else {
1368                                                                         // Modality handling, if we are modal and the new active window is one
1369                                                                         // of ours but not the modal one, switch back to the modal window
1370
1371                                                                         if (NativeWindow.FindWindow(ActiveWindow) != null) {
1372                                                                                 if (ActiveWindow != (IntPtr)ModalWindows.Peek()) {
1373                                                                                         Activate((IntPtr)ModalWindows.Peek());
1374                                                                                 }
1375                                                                         }
1376                                                                         break;
1377                                                                 }
1378                                                         }
1379                                                 }
1380                                                 break;
1381
1382                                 }
1383
1384                                 lock (XlibLock) {
1385                                         pending = XPending (DisplayHandle);
1386                                 }
1387                         }
1388                 }
1389
1390                 private IntPtr GetMousewParam(int Delta) {
1391                         int     result = 0;
1392
1393                         if ((MouseState & MouseButtons.Left) != 0) {
1394                                 result |= (int)MsgButtons.MK_LBUTTON;
1395                         }
1396
1397                         if ((MouseState & MouseButtons.Middle) != 0) {
1398                                 result |= (int)MsgButtons.MK_MBUTTON;
1399                         }
1400
1401                         if ((MouseState & MouseButtons.Right) != 0) {
1402                                 result |= (int)MsgButtons.MK_RBUTTON;
1403                         }
1404
1405                         Keys mods = ModifierKeys;
1406                         if ((mods & Keys.Control) != 0) {
1407                                 result |= (int)MsgButtons.MK_CONTROL;
1408                         }
1409
1410                         if ((mods & Keys.Shift) != 0) {
1411                                 result |= (int)MsgButtons.MK_SHIFT;
1412                         }
1413
1414                         result |= Delta << 16;
1415
1416                         return (IntPtr)result;
1417                 }
1418                 private IntPtr XGetParent(IntPtr handle) {
1419                         IntPtr  Root;
1420                         IntPtr  Parent;
1421                         IntPtr  Children;
1422                         int     ChildCount;
1423
1424                         lock (XlibLock) {
1425                                 XQueryTree(DisplayHandle, handle, out Root, out Parent, out Children, out ChildCount);
1426                         }
1427
1428                         if (Children!=IntPtr.Zero) {
1429                                 lock (XlibLock) {
1430                                         XFree(Children);
1431                                 }
1432                         }
1433                         return Parent;
1434                 }
1435
1436                 private int HandleError(IntPtr display, ref XErrorEvent error_event) {
1437                         if (ErrorExceptions) {
1438                                 throw new XException(error_event.display, error_event.resourceid, error_event.serial, error_event.error_code, error_event.request_code, error_event.minor_code);
1439                         } else {
1440                                 Console.WriteLine("X11 Error encountered: {0}{1}\n", XException.GetMessage(error_event.display, error_event.resourceid, error_event.serial, error_event.error_code, error_event.request_code, error_event.minor_code), WhereString());
1441                         }
1442                         return 0;
1443                 }
1444
1445                 private void SendWMDestroyMessages(Control c) {
1446                         Hwnd            hwnd;
1447                         int             i;
1448                         Control[]       controls;
1449
1450                         if (c != null) {
1451                                 controls = c.child_controls.GetAllControls ();
1452
1453                                 if (c.IsHandleCreated && !c.IsDisposed) {
1454                                         #if DriverDebugDestroy
1455                                                 Console.WriteLine("Destroying {0}, child of {1}", XplatUI.Window(c.Handle), (c.Parent != null) ? XplatUI.Window(c.Parent.Handle) : "<none>");
1456                                         #endif
1457
1458                                         hwnd = Hwnd.ObjectFromHandle(c.Handle);
1459                                         SendMessage(c.Handle, Msg.WM_DESTROY, IntPtr.Zero, IntPtr.Zero);
1460                                 }
1461
1462                                 for (i = 0; i < controls.Length; i++) {
1463                                         SendWMDestroyMessages(controls[i]);
1464                                         if (controls[i].IsHandleCreated) {
1465                                                 hwnd = Hwnd.ObjectFromHandle(controls[i].Handle);
1466                                                 if (hwnd != null) {
1467                                                         hwnd.Dispose();
1468                                                 }
1469                                         }
1470                                 }
1471                         }
1472                 }
1473
1474                 private void PerformNCCalc(Hwnd hwnd) {
1475                         XplatUIWin32.NCCALCSIZE_PARAMS  ncp;
1476                         IntPtr                          ptr;
1477                         Rectangle                       rect;
1478
1479                         rect = hwnd.DefaultClientRect;
1480
1481                         ncp = new XplatUIWin32.NCCALCSIZE_PARAMS();
1482                         ptr = Marshal.AllocHGlobal(Marshal.SizeOf(ncp));
1483
1484                         ncp.rgrc1.left = rect.Left;
1485                         ncp.rgrc1.top = rect.Top;
1486                         ncp.rgrc1.right = rect.Right;
1487                         ncp.rgrc1.bottom = rect.Bottom;
1488
1489                         Marshal.StructureToPtr(ncp, ptr, true);
1490                         NativeWindow.WndProc(hwnd.client_window, Msg.WM_NCCALCSIZE, (IntPtr)1, ptr);
1491                         ncp = (XplatUIWin32.NCCALCSIZE_PARAMS)Marshal.PtrToStructure(ptr, typeof(XplatUIWin32.NCCALCSIZE_PARAMS));
1492                         Marshal.FreeHGlobal(ptr);
1493
1494                         // FIXME - debug this with Menus, need to set hwnd.ClientRect
1495
1496                         rect = new Rectangle(ncp.rgrc1.left, ncp.rgrc1.top, ncp.rgrc1.right - ncp.rgrc1.left, ncp.rgrc1.bottom - ncp.rgrc1.top);
1497
1498                         if (hwnd.visible) {
1499                                 XMoveResizeWindow(DisplayHandle, hwnd.client_window, rect.X, rect.Y, rect.Width, rect.Height);
1500                         }
1501                 }
1502                 #endregion      // Private Methods
1503
1504                 #region Callbacks
1505                 private void MouseHover(object sender, EventArgs e) {
1506                         XEvent  xevent;
1507                         Hwnd    hwnd;
1508
1509                         HoverState.Timer.Enabled = false;
1510
1511                         if (HoverState.Window != IntPtr.Zero) {
1512                                 hwnd = Hwnd.GetObjectFromWindow(HoverState.Window);
1513                                 if (hwnd != null) {
1514                                         xevent = new XEvent ();
1515
1516                                         xevent.type = XEventName.ClientMessage;
1517                                         xevent.ClientMessageEvent.display = DisplayHandle;
1518                                         xevent.ClientMessageEvent.window = HoverState.Window;
1519                                         xevent.ClientMessageEvent.message_type = HoverState.Atom;
1520                                         xevent.ClientMessageEvent.format = 32;
1521                                         xevent.ClientMessageEvent.ptr1 = (IntPtr) (HoverState.Y << 16 | HoverState.X);
1522
1523                                         hwnd.Queue.EnqueueLocked (xevent);
1524
1525                                         WakeupMain ();
1526                                 }
1527                         }
1528                 }
1529
1530                 private void CaretCallback(object sender, EventArgs e) {
1531                         if (Caret.Paused) {
1532                                 return;
1533                         }
1534                         Caret.On = !Caret.On;
1535
1536                         XDrawLine(DisplayHandle, Caret.Hwnd, Caret.gc, Caret.X, Caret.Y, Caret.X, Caret.Y + Caret.Height);
1537                 }
1538                 #endregion      // Callbacks
1539
1540                 #region Public Properties
1541
1542                 internal override int Caption {
1543                         get {
1544                                 return 19;
1545                         }
1546                 }
1547
1548                 internal override  Size CursorSize {
1549                         get {
1550                                 int     x;
1551                                 int     y;
1552
1553                                 if (XQueryBestCursor(DisplayHandle, RootWindow, 32, 32, out x, out y) != 0) {
1554                                         return new Size(x, y);
1555                                 } else {
1556                                         return new Size(16, 16);
1557                                 }
1558                         }
1559                 } 
1560
1561                 internal override  bool DragFullWindows {
1562                         get {
1563                                 return true;
1564                         }
1565                 } 
1566
1567                 internal override  Size DragSize {
1568                         get {
1569                                 return new Size(4, 4);
1570                         }
1571                 } 
1572
1573                 internal override  Size FrameBorderSize { 
1574                         get {
1575                                 throw new NotImplementedException(); 
1576                         }
1577                 }
1578
1579                 internal override  Size IconSize {
1580                         get {
1581                                 IntPtr          list;
1582                                 XIconSize       size;
1583                                 int             count;
1584
1585                                 if (XGetIconSizes(DisplayHandle, RootWindow, out list, out count) != 0) {
1586                                         long            current;
1587                                         int             largest;
1588
1589                                         current = (long)list;
1590                                         largest = 0;
1591
1592                                         size = new XIconSize();
1593
1594                                         for (int i = 0; i < count; i++) {
1595                                                 size = (XIconSize)Marshal.PtrToStructure((IntPtr)current, size.GetType());
1596                                                 current += Marshal.SizeOf(size);
1597
1598                                                 // Look for our preferred size
1599                                                 if (size.min_width == 32) {
1600                                                         XFree(list);
1601                                                         return new Size(32, 32);
1602                                                 }
1603
1604                                                 if (size.max_width == 32) {
1605                                                         XFree(list);
1606                                                         return new Size(32, 32);
1607                                                 }
1608
1609                                                 if (size.min_width < 32 && size.max_width > 32) {
1610                                                         int     x;
1611
1612                                                         // check if we can fit one
1613                                                         x = size.min_width;
1614                                                         while (x < size.max_width) {
1615                                                                 x += size.width_inc;
1616                                                                 if (x == 32) {
1617                                                                         XFree(list);
1618                                                                         return new Size(32, 32);
1619                                                                 }
1620                                                         }
1621                                                 }
1622
1623                                                 if (largest < size.max_width) {
1624                                                         largest = size.max_width;
1625                                                 }
1626                                         }
1627
1628                                         // We didn't find a match or we wouldn't be here
1629                                         return new Size(largest, largest);
1630
1631                                 } else {
1632                                         return new Size(32, 32);
1633                                 }
1634                         }
1635                 } 
1636
1637                 internal override int KeyboardSpeed {
1638                         get{
1639                                 //
1640                                 // A lot harder: need to do:
1641                                 // XkbQueryExtension(0x08051008, 0xbfffdf4c, 0xbfffdf50, 0xbfffdf54, 0xbfffdf58)       = 1
1642                                 // XkbAllocKeyboard(0x08051008, 0xbfffdf4c, 0xbfffdf50, 0xbfffdf54, 0xbfffdf58)        = 0x080517a8
1643                                 // XkbGetControls(0x08051008, 1, 0x080517a8, 0xbfffdf54, 0xbfffdf58)                   = 0
1644                                 //
1645                                 // And from that we can tell the repetition rate
1646                                 //
1647                                 // Notice, the values must map to:
1648                                 //   [0, 31] which maps to 2.5 to 30 repetitions per second.
1649                                 //
1650                                 return 0;
1651                         }
1652                 }
1653
1654                 internal override int KeyboardDelay {
1655                         get {
1656                                 //
1657                                 // Return values must range from 0 to 4, 0 meaning 250ms,
1658                                 // and 4 meaning 1000 ms.
1659                                 //
1660                                 return 1; // ie, 500 ms
1661                         }
1662                 } 
1663
1664                 internal override  Size MaxWindowTrackSize {
1665                         get {
1666                                 return new Size (WorkingArea.Width, WorkingArea.Height);
1667                         }
1668                 } 
1669
1670                 internal override  Size MinimizedWindowSize {
1671                         get {
1672                                 return new Size(1, 1);
1673                         }
1674                 } 
1675
1676                 internal override  Size MinimizedWindowSpacingSize {
1677                         get {
1678                                 return new Size(1, 1);
1679                         }
1680                 } 
1681
1682                 internal override  Size MinimumWindowSize {
1683                         get {
1684                                 return new Size(1, 1);
1685                         }
1686                 } 
1687
1688                 internal override  Size MinWindowTrackSize {
1689                         get {
1690                                 return new Size(1, 1);
1691                         }
1692                 }
1693
1694                 internal override Keys ModifierKeys {
1695                         get {
1696                                 return Keyboard.ModifierKeys;
1697                         }
1698                 }
1699
1700                 internal override  Size SmallIconSize {
1701                         get {
1702                                 IntPtr          list;
1703                                 XIconSize       size;
1704                                 int             count;
1705
1706                                 if (XGetIconSizes(DisplayHandle, RootWindow, out list, out count) != 0) {
1707                                         long            current;
1708                                         int             smallest;
1709
1710                                         current = (long)list;
1711                                         smallest = 0;
1712
1713                                         size = new XIconSize();
1714
1715                                         for (int i = 0; i < count; i++) {
1716                                                 size = (XIconSize)Marshal.PtrToStructure((IntPtr)current, size.GetType());
1717                                                 current += Marshal.SizeOf(size);
1718
1719                                                 // Look for our preferred size
1720                                                 if (size.min_width == 16) {
1721                                                         XFree(list);
1722                                                         return new Size(16, 16);
1723                                                 }
1724
1725                                                 if (size.max_width == 16) {
1726                                                         XFree(list);
1727                                                         return new Size(16, 16);
1728                                                 }
1729
1730                                                 if (size.min_width < 16 && size.max_width > 16) {
1731                                                         int     x;
1732
1733                                                         // check if we can fit one
1734                                                         x = size.min_width;
1735                                                         while (x < size.max_width) {
1736                                                                 x += size.width_inc;
1737                                                                 if (x == 16) {
1738                                                                         XFree(list);
1739                                                                         return new Size(16, 16);
1740                                                                 }
1741                                                         }
1742                                                 }
1743
1744                                                 if (smallest == 0 || smallest > size.min_width) {
1745                                                         smallest = size.min_width;
1746                                                 }
1747                                         }
1748
1749                                         // We didn't find a match or we wouldn't be here
1750                                         return new Size(smallest, smallest);
1751
1752                                 } else {
1753                                         return new Size(16, 16);
1754                                 }
1755                         }
1756                 } 
1757
1758                 internal override  int MouseButtonCount {
1759                         get {
1760                                 return 3;
1761                         }
1762                 } 
1763
1764                 internal override  bool MouseButtonsSwapped {
1765                         get {
1766                                 return false;   // FIXME - how to detect?
1767                         }
1768                 } 
1769
1770                 internal override Size MouseHoverSize {
1771                         get {
1772                                 return new Size (1, 1);
1773                         }
1774                 }
1775
1776                 internal override int MouseHoverTime {
1777                         get {
1778                                 return HoverState.Interval;
1779                         }
1780                 }
1781
1782
1783
1784                 internal override  bool MouseWheelPresent {
1785                         get {
1786                                 return true;    // FIXME - how to detect?
1787                         }
1788                 } 
1789
1790                 internal override  Rectangle VirtualScreen {
1791                         get {
1792                                 return WorkingArea;
1793                         }
1794                 } 
1795
1796                 internal override  Rectangle WorkingArea {
1797                         get {
1798                                 IntPtr                  actual_atom;
1799                                 int                     actual_format;
1800                                 IntPtr                  nitems;
1801                                 IntPtr                  bytes_after;
1802                                 IntPtr                  prop = IntPtr.Zero;
1803                                 int                     width;
1804                                 int                     height;
1805
1806                                 XGetWindowProperty(DisplayHandle, RootWindow, NetAtoms[(int)NA._NET_DESKTOP_GEOMETRY], IntPtr.Zero, new IntPtr (256), false, (IntPtr)Atom.XA_CARDINAL, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1807                                 if (((long)nitems == 2) && (prop != IntPtr.Zero) && IntPtr.Size == 4) {
1808                                         width = Marshal.ReadIntPtr(prop, 0).ToInt32();
1809                                         height = Marshal.ReadIntPtr(prop, IntPtr.Size).ToInt32();
1810
1811                                         XFree(prop);
1812                                         return new Rectangle(0, 0, width, height);
1813                                 } else {
1814                                         XWindowAttributes       attributes=new XWindowAttributes();
1815
1816                                         lock (XlibLock) {
1817                                                 XGetWindowAttributes(DisplayHandle, XRootWindow(DisplayHandle, 0), ref attributes);
1818                                         }
1819
1820                                         return new Rectangle(0, 0, attributes.width, attributes.height);
1821                                 }
1822                         }
1823                 } 
1824                 #endregion      // Public properties
1825
1826                 #region Public Static Methods
1827                 internal override IntPtr InitializeDriver() {
1828                         lock (this) {
1829                                 if (DisplayHandle==IntPtr.Zero) {
1830                                         SetDisplay(XOpenDisplay(IntPtr.Zero));
1831                                 }
1832                         }
1833                         return IntPtr.Zero;
1834                 }
1835
1836                 internal override void ShutdownDriver(IntPtr token) {
1837                         lock (this) {
1838                                 if (DisplayHandle!=IntPtr.Zero) {
1839                                         XCloseDisplay(DisplayHandle);
1840                                         DisplayHandle=IntPtr.Zero;
1841                                 }
1842                         }
1843                 }
1844
1845                 internal override void EnableThemes() {
1846                         ThemesEnabled = true;
1847                 }
1848
1849
1850                 internal override void Activate(IntPtr handle) {
1851                         Hwnd hwnd;
1852
1853                         hwnd = Hwnd.ObjectFromHandle(handle);
1854
1855                         if (hwnd != null) lock (XlibLock) {
1856                                 SendNetWMMessage(hwnd.whole_window, NetAtoms[(int)NA._NET_ACTIVE_WINDOW], IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
1857                                 //XRaiseWindow(DisplayHandle, handle);
1858                         }
1859                         return;
1860                 }
1861
1862                 internal override void AudibleAlert() {
1863                         XBell(DisplayHandle, 0);
1864                         return;
1865                 }
1866
1867
1868                 internal override void CaretVisible(IntPtr handle, bool visible) {
1869                         if (Caret.Hwnd == handle) {
1870                                 if (visible) {
1871                                         if (!Caret.Visible) {
1872                                                 Caret.Visible = true;
1873                                                 ShowCaret();
1874                                                 Caret.Timer.Start();
1875                                         }
1876                                 } else {
1877                                         Caret.Visible = false;
1878                                         Caret.Timer.Stop();
1879                                         HideCaret();
1880                                 }
1881                         }
1882                 }
1883
1884                 internal override bool CalculateWindowRect(ref Rectangle ClientRect, int Style, int ExStyle, Menu menu, out Rectangle WindowRect) {
1885                         FormBorderStyle border_style;
1886                         TitleStyle      title_style;
1887                         int caption_height;
1888                         int tool_caption_height;
1889
1890                         DeriveStyles(Style, ExStyle, out border_style, out title_style,
1891                                 out caption_height, out tool_caption_height);
1892
1893                         WindowRect = Hwnd.GetWindowRectangle(border_style, menu, title_style,
1894                                         caption_height, tool_caption_height,
1895                                         ClientRect);
1896                         return true;
1897                 }
1898
1899                 internal override void ClientToScreen(IntPtr handle, ref int x, ref int y) {
1900                         int     dest_x_return;
1901                         int     dest_y_return;
1902                         IntPtr  child;
1903                         Hwnd    hwnd;
1904
1905                         hwnd = Hwnd.ObjectFromHandle(handle);
1906
1907                         lock (XlibLock) {
1908                                 XTranslateCoordinates(DisplayHandle, hwnd.client_window, RootWindow, x, y, out dest_x_return, out dest_y_return, out child);
1909                         }
1910
1911                         x = dest_x_return;
1912                         y = dest_y_return;
1913                 }
1914
1915                 internal override int[] ClipboardAvailableFormats(IntPtr handle) {
1916                         DataFormats.Format      f;
1917                         int[]                   result;
1918
1919                         f = DataFormats.Format.List;
1920
1921                         if (XGetSelectionOwner(DisplayHandle, NetAtoms[(int)NA.CLIPBOARD]) == IntPtr.Zero) {
1922                                 return null;
1923                         }
1924
1925                         Clipboard.Formats = new ArrayList();
1926
1927                         while (f != null) {
1928                                 XConvertSelection(DisplayHandle, NetAtoms[(int)NA.CLIPBOARD], (IntPtr)f.Id, (IntPtr)f.Id, FosterParent, IntPtr.Zero);
1929
1930                                 Clipboard.Enumerating = true;
1931                                 while (Clipboard.Enumerating) {
1932                                         UpdateMessageQueue(null);
1933                                 }
1934                                 f = f.Next;
1935                         }
1936
1937                         result = new int[Clipboard.Formats.Count];
1938
1939                         for (int i = 0; i < Clipboard.Formats.Count; i++) {
1940                                 result[i] = (int)Clipboard.Formats[i];
1941                         }
1942
1943                         Clipboard.Formats = null;
1944                         return result;
1945                 }
1946
1947                 internal override void ClipboardClose(IntPtr handle) {
1948                         if (handle != ClipMagic) {
1949                                 throw new ArgumentException("handle is not a valid clipboard handle");
1950                         }
1951                         return;
1952                 }
1953
1954                 internal override int ClipboardGetID(IntPtr handle, string format) {
1955                         if (handle != ClipMagic) {
1956                                 throw new ArgumentException("handle is not a valid clipboard handle");
1957                         }
1958
1959                         if (format == "Text" ) return (int)Atom.XA_STRING;
1960                         else if (format == "Bitmap" ) return (int)Atom.XA_BITMAP;
1961                         //else if (format == "MetaFilePict" ) return 3;
1962                         //else if (format == "SymbolicLink" ) return 4;
1963                         //else if (format == "DataInterchangeFormat" ) return 5;
1964                         //else if (format == "Tiff" ) return 6;
1965                         else if (format == "OEMText" ) return XInternAtom(DisplayHandle, "COMPOUND_TEXT", false).ToInt32();
1966                         else if (format == "DeviceIndependentBitmap" ) return (int)Atom.XA_PIXMAP;
1967                         else if (format == "Palette" ) return (int)Atom.XA_COLORMAP;    // Useless
1968                         //else if (format == "PenData" ) return 10;
1969                         //else if (format == "RiffAudio" ) return 11;
1970                         //else if (format == "WaveAudio" ) return 12;
1971                         else if (format == "UnicodeText" ) return XInternAtom(DisplayHandle, "UTF8_STRING", false).ToInt32();
1972                         //else if (format == "EnhancedMetafile" ) return 14;
1973                         //else if (format == "FileDrop" ) return 15;
1974                         //else if (format == "Locale" ) return 16;
1975
1976                         return XInternAtom(DisplayHandle, format, false).ToInt32();
1977                 }
1978
1979                 internal override IntPtr ClipboardOpen() {
1980                         return ClipMagic;
1981                 }
1982
1983                 internal override object ClipboardRetrieve(IntPtr handle, int type, XplatUI.ClipboardToObject converter) {
1984                         XConvertSelection(DisplayHandle, NetAtoms[(int)NA.CLIPBOARD], (IntPtr)type, (IntPtr)type, FosterParent, IntPtr.Zero);
1985
1986                         Clipboard.Retrieving = true;
1987                         while (Clipboard.Retrieving) {
1988                                 UpdateMessageQueue(null);
1989                         }
1990
1991                         return Clipboard.Item;
1992                 }
1993
1994                 internal override void ClipboardStore(IntPtr handle, object obj, int type, XplatUI.ObjectToClipboard converter) {
1995                         Clipboard.Item = obj;
1996                         Clipboard.Type = type;
1997                         Clipboard.Converter = converter;
1998
1999                         if (obj != null) {
2000                                 XSetSelectionOwner(DisplayHandle, NetAtoms[(int)NA.CLIPBOARD], FosterParent, IntPtr.Zero);
2001                         } else {
2002                                 // Clearing the selection
2003                                 XSetSelectionOwner(DisplayHandle, NetAtoms[(int)NA.CLIPBOARD], IntPtr.Zero, IntPtr.Zero);
2004                         }
2005                 }
2006
2007                 internal override void CreateCaret(IntPtr handle, int width, int height) {
2008                         XGCValues       gc_values;
2009                         Hwnd            hwnd;
2010
2011                         hwnd = Hwnd.ObjectFromHandle(handle);
2012
2013                         if (Caret.Hwnd != IntPtr.Zero) {
2014                                 DestroyCaret(Caret.Hwnd);
2015                         }
2016
2017                         Caret.Hwnd = handle;
2018                         Caret.Window = hwnd.client_window;
2019                         Caret.Width = width;
2020                         Caret.Height = height;
2021                         Caret.Visible = false;
2022                         Caret.On = false;
2023
2024                         gc_values = new XGCValues();
2025                         gc_values.line_width = width;
2026
2027                         Caret.gc = XCreateGC(DisplayHandle, Caret.Window, new IntPtr ((int)GCFunction.GCLineWidth), ref gc_values);
2028                         if (Caret.gc == IntPtr.Zero) {
2029                                 Caret.Hwnd = IntPtr.Zero;
2030                                 return;
2031                         }
2032
2033                         XSetFunction(DisplayHandle, Caret.gc, GXFunction.GXinvert);
2034                 }
2035
2036                 internal override IntPtr CreateWindow(CreateParams cp) {
2037                         XSetWindowAttributes    Attributes;
2038                         Hwnd                    hwnd;
2039                         int                     X;
2040                         int                     Y;
2041                         int                     Width;
2042                         int                     Height;
2043                         IntPtr                  ParentHandle;
2044                         IntPtr                  WholeWindow;
2045                         IntPtr                  ClientWindow;
2046                         Rectangle               ClientRect;
2047                         SetWindowValuemask      ValueMask;
2048
2049
2050                         hwnd = new Hwnd();
2051
2052                         Attributes = new XSetWindowAttributes();
2053                         X = cp.X;
2054                         Y = cp.Y;
2055                         Width = cp.Width;
2056                         Height = cp.Height;
2057
2058                         if (Width<1) Width=1;
2059                         if (Height<1) Height=1;
2060
2061                         if (cp.Parent != IntPtr.Zero) {
2062                                 ParentHandle = Hwnd.ObjectFromHandle(cp.Parent).client_window;
2063                         } else {
2064                                 if ((cp.Style & (int)WindowStyles.WS_CHILD) != 0) {
2065                                         // We need to use our foster parent window until this poor child gets it's parent assigned
2066                                         ParentHandle=FosterParent;
2067                                 } else if ((cp.Style & (int)WindowStyles.WS_POPUP) != 0) {
2068                                         ParentHandle=RootWindow;
2069                                 } else {
2070                                         // Default position on screen, if window manager doesn't place us somewhere else
2071                                         if (X<1) X = 50;
2072                                         if (Y<1) Y = 50;
2073                                         ParentHandle=RootWindow;
2074                                 }
2075                         }
2076
2077                         ValueMask = SetWindowValuemask.BitGravity | SetWindowValuemask.WinGravity;
2078
2079                         Attributes.bit_gravity = Gravity.NorthWestGravity;
2080                         Attributes.win_gravity = Gravity.NorthWestGravity;
2081
2082                         // Save what's under the toolwindow
2083                         if ((cp.ExStyle & (int)WindowExStyles.WS_EX_TOOLWINDOW) != 0) {
2084                                 Attributes.save_under = true;
2085                                 ValueMask |= SetWindowValuemask.SaveUnder;
2086                         }
2087
2088
2089                         // If we're a popup without caption we override the WM
2090                         if ((cp.Style & ((int)WindowStyles.WS_POPUP)) != 0) {
2091                                 if ((cp.Style & (int)WindowStyles.WS_CAPTION) == 0) {
2092                                         Attributes.override_redirect = true;
2093                                         ValueMask |= SetWindowValuemask.OverrideRedirect;
2094                                 }
2095                         }
2096
2097                         hwnd.x = X;
2098                         hwnd.y = Y;
2099                         hwnd.width = Width;
2100                         hwnd.height = Height;
2101                         hwnd.parent = Hwnd.ObjectFromHandle(cp.Parent);
2102
2103                         if ((cp.Style & ((int)WindowStyles.WS_DISABLED)) != 0) {
2104                                 hwnd.enabled = false;
2105                         }
2106
2107                         ClientRect = hwnd.ClientRect;
2108                         ClientWindow = IntPtr.Zero;
2109
2110                         lock (XlibLock) {
2111                                 WholeWindow = XCreateWindow(DisplayHandle, ParentHandle, X, Y, Width, Height, 0, (int)CreateWindowArgs.CopyFromParent, (int)CreateWindowArgs.InputOutput, IntPtr.Zero, new UIntPtr ((uint)ValueMask), ref Attributes);
2112                                 if (WholeWindow != IntPtr.Zero) {
2113                                         ValueMask &= ~(SetWindowValuemask.OverrideRedirect | SetWindowValuemask.SaveUnder);
2114
2115                                         if (CustomVisual != IntPtr.Zero && CustomColormap != IntPtr.Zero) {
2116                                                 ValueMask = SetWindowValuemask.ColorMap;
2117                                                 Attributes.colormap = CustomColormap;
2118                                         }
2119                                         ClientWindow = XCreateWindow(DisplayHandle, WholeWindow, ClientRect.X, ClientRect.Y, ClientRect.Width, ClientRect.Height, 0, (int)CreateWindowArgs.CopyFromParent, (int)CreateWindowArgs.InputOutput, CustomVisual, new UIntPtr ((uint)ValueMask), ref Attributes);
2120                                 }
2121                         }
2122
2123                         if ((WholeWindow == IntPtr.Zero) || (ClientWindow == IntPtr.Zero)) {
2124                                 throw new Exception("Could not create X11 windows");
2125                         }
2126
2127                         hwnd.Queue = ThreadQueue(Thread.CurrentThread);
2128                         hwnd.WholeWindow = WholeWindow;
2129                         hwnd.ClientWindow = ClientWindow;
2130
2131                         #if DriverDebug || DriverDebugCreate
2132                                 Console.WriteLine("Created window {0:X} / {1:X} parent {2:X}, Style {3}, ExStyle {4}", ClientWindow.ToInt32(), WholeWindow.ToInt32(), hwnd.parent != null ? hwnd.parent.Handle.ToInt32() : 0, (WindowStyles)cp.Style, (WindowExStyles)cp.ExStyle);
2133                         #endif
2134
2135                         if ((cp.Style & (int)WindowStyles.WS_CHILD) == 0) {
2136                                 if ((X != unchecked((int)0x80000000)) && (Y != unchecked((int)0x80000000))) {
2137                                         XSizeHints      hints;
2138
2139                                         hints = new XSizeHints();
2140                                         hints.x = X;
2141                                         hints.y = Y;
2142                                         hints.flags = (IntPtr)XSizeHintsFlags.USPosition;
2143                                         XSetWMNormalHints(DisplayHandle, WholeWindow, ref hints);
2144                                 }
2145                         }
2146
2147                         lock (XlibLock) {
2148                                 XSelectInput(DisplayHandle, hwnd.whole_window, new IntPtr ((int)SelectInputMask));
2149                                 XSelectInput(DisplayHandle, hwnd.client_window, new IntPtr ((int)SelectInputMask));
2150
2151                                 if ((cp.Style & (int)WindowStyles.WS_VISIBLE) != 0) {
2152                                         MapWindow(hwnd, WindowType.Both);
2153                                         hwnd.visible = true;
2154                                 }
2155                         }
2156
2157                         if ((cp.ExStyle & (int)WindowExStyles.WS_EX_TOPMOST) != 0) {
2158                                 XSetTransientForHint (DisplayHandle, hwnd.whole_window, RootWindow);
2159                         } else if ((cp.ExStyle & (int)WindowExStyles.WS_EX_APPWINDOW) == 0) {
2160                                 XSetTransientForHint (DisplayHandle, hwnd.whole_window, FosterParent);
2161                         }
2162
2163                         SetWMStyles(hwnd, cp);
2164
2165                         if ((cp.Style & (int)WindowStyles.WS_MINIMIZE) != 0) {
2166                                 SetWindowState(hwnd.Handle, FormWindowState.Minimized);
2167                         } else if ((cp.Style & (int)WindowStyles.WS_MAXIMIZE) != 0) {
2168                                 SetWindowState(hwnd.Handle, FormWindowState.Maximized);
2169                         }
2170
2171                         // for now make all windows dnd enabled
2172                         Dnd.SetAllowDrop (hwnd, true);
2173
2174                         // Set caption/window title
2175                         Text(hwnd.Handle, cp.Caption);
2176
2177                         return hwnd.Handle;
2178                 }
2179
2180                 internal override IntPtr CreateWindow(IntPtr Parent, int X, int Y, int Width, int Height) {
2181                         CreateParams create_params = new CreateParams();
2182
2183                         create_params.Caption = "";
2184                         create_params.X = X;
2185                         create_params.Y = Y;
2186                         create_params.Width = Width;
2187                         create_params.Height = Height;
2188
2189                         create_params.ClassName=XplatUI.DefaultClassName;
2190                         create_params.ClassStyle = 0;
2191                         create_params.ExStyle=0;
2192                         create_params.Parent=IntPtr.Zero;
2193                         create_params.Param=0;
2194
2195                         return CreateWindow(create_params);
2196                 }
2197
2198                 internal override IntPtr DefineCursor(Bitmap bitmap, Bitmap mask, Color cursor_pixel, Color mask_pixel, int xHotSpot, int yHotSpot) {
2199                         IntPtr  cursor;
2200                         Bitmap  cursor_bitmap;
2201                         Bitmap  cursor_mask;
2202                         Byte[]  cursor_bits;
2203                         Byte[]  mask_bits;
2204                         Color   c_pixel;
2205                         Color   m_pixel;
2206                         int     width;
2207                         int     height;
2208                         IntPtr  cursor_pixmap;
2209                         IntPtr  mask_pixmap;
2210                         XColor  fg;
2211                         XColor  bg;
2212                         bool    and;
2213                         bool    xor;
2214
2215                         if (XQueryBestCursor(DisplayHandle, RootWindow, bitmap.Width, bitmap.Height, out width, out height) == 0) {
2216                                 return IntPtr.Zero;
2217                         }
2218
2219                         // Win32 only allows creation cursors of a certain size
2220                         if ((bitmap.Width != width) || (bitmap.Width != height)) {
2221                                 cursor_bitmap = new Bitmap(bitmap, new Size(width, height));
2222                                 cursor_mask = new Bitmap(mask, new Size(width, height));
2223                         } else {
2224                                 cursor_bitmap = bitmap;
2225                                 cursor_mask = mask;
2226                         }
2227
2228                         width = cursor_bitmap.Width;
2229                         height = cursor_bitmap.Height;
2230
2231                         cursor_bits = new Byte[(width / 8) * height];
2232                         mask_bits = new Byte[(width / 8) * height];
2233
2234                         for (int y = 0; y < height; y++) {
2235                                 for (int x = 0; x < width; x++) {
2236                                         c_pixel = cursor_bitmap.GetPixel(x, y);
2237                                         m_pixel = cursor_mask.GetPixel(x, y);
2238
2239                                         and = c_pixel == cursor_pixel;
2240                                         xor = m_pixel == mask_pixel;
2241
2242                                         if (!and && !xor) {
2243                                                 // Black
2244                                                 // cursor_bits[y * width / 8 + x / 8] &= (byte)~((1 << (x % 8)));       // The bit already is 0
2245                                                 mask_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
2246                                         } else if (and && !xor) {
2247                                                 // White
2248                                                 cursor_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
2249                                                 mask_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
2250 #if notneeded
2251                                         } else if (and && !xor) {
2252                                                 // Screen
2253                                         } else if (and && xor) {
2254                                                 // Inverse Screen
2255
2256                                                 // X11 doesn't know the 'reverse screen' concept, so we'll treat them the same
2257                                                 // we want both to be 0 so nothing to be done
2258                                                 //cursor_bits[y * width / 8 + x / 8] &= (byte)~((1 << (x % 8)));
2259                                                 //mask_bits[y * width / 8 + x / 8] |= (byte)(01 << (x % 8));
2260 #endif
2261                                         }
2262                                 }
2263                         }
2264
2265                         cursor_pixmap = XCreatePixmapFromBitmapData(DisplayHandle, RootWindow, cursor_bits, width, height, (IntPtr)1, (IntPtr)0, 1);
2266                         mask_pixmap = XCreatePixmapFromBitmapData(DisplayHandle, RootWindow, mask_bits, width, height, (IntPtr)1, (IntPtr)0, 1);
2267                         fg = new XColor();
2268                         bg = new XColor();
2269
2270                         fg.pixel = XWhitePixel(DisplayHandle, ScreenNo);
2271                         fg.red = (ushort)65535;
2272                         fg.green = (ushort)65535;
2273                         fg.blue = (ushort)65535;
2274
2275                         bg.pixel = XBlackPixel(DisplayHandle, ScreenNo);
2276
2277                         cursor = XCreatePixmapCursor(DisplayHandle, cursor_pixmap, mask_pixmap, ref fg, ref bg, xHotSpot, yHotSpot);
2278
2279                         XFreePixmap(DisplayHandle, cursor_pixmap);
2280                         XFreePixmap(DisplayHandle, mask_pixmap);
2281
2282                         return cursor;
2283                 }
2284
2285                 internal override IntPtr DefineStdCursor(StdCursor id) {
2286                         CursorFontShape shape;
2287                         IntPtr          cursor;
2288
2289                         // FIXME - define missing shapes
2290
2291                         switch (id) {
2292                                 case StdCursor.AppStarting: {
2293                                         shape = CursorFontShape.XC_watch;
2294                                         break;
2295                                 }
2296
2297                                 case StdCursor.Arrow: {
2298                                         return IntPtr.Zero;
2299                                 }
2300
2301                                 case StdCursor.Cross: {
2302                                         shape = CursorFontShape.XC_crosshair;
2303                                         break;
2304                                 }
2305
2306                                 case StdCursor.Default: {
2307                                         return IntPtr.Zero;
2308                                 }
2309
2310                                 case StdCursor.Hand: {
2311                                         shape = CursorFontShape.XC_hand1;
2312                                         break;
2313                                 }
2314
2315                                 case StdCursor.Help: {
2316                                         shape = CursorFontShape.XC_question_arrow;
2317                                         break;
2318                                 }
2319
2320                                 case StdCursor.HSplit: {
2321                                         shape = CursorFontShape.XC_sb_v_double_arrow; 
2322                                         break;
2323                                 }
2324
2325                                 case StdCursor.IBeam: {
2326                                         shape = CursorFontShape.XC_xterm; 
2327                                         break;
2328                                 }
2329
2330                                 case StdCursor.No: {
2331                                         shape = CursorFontShape.XC_circle; 
2332                                         break;
2333                                 }
2334
2335                                 case StdCursor.NoMove2D: {
2336                                         shape = CursorFontShape.XC_fleur; 
2337                                         break;
2338                                 }
2339
2340                                 case StdCursor.NoMoveHoriz: {
2341                                         shape = CursorFontShape.XC_fleur; 
2342                                         break;
2343                                 }
2344
2345                                 case StdCursor.NoMoveVert: {
2346                                         shape = CursorFontShape.XC_fleur; 
2347                                         break;
2348                                 }
2349
2350                                 case StdCursor.PanEast: {
2351                                         shape = CursorFontShape.XC_fleur; 
2352                                         break;
2353                                 }
2354
2355                                 case StdCursor.PanNE: {
2356                                         shape = CursorFontShape.XC_fleur; 
2357                                         break;
2358                                 }
2359
2360                                 case StdCursor.PanNorth: {
2361                                         shape = CursorFontShape.XC_fleur; 
2362                                         break;
2363                                 }
2364
2365                                 case StdCursor.PanNW: {
2366                                         shape = CursorFontShape.XC_fleur; 
2367                                         break;
2368                                 }
2369
2370                                 case StdCursor.PanSE: {
2371                                         shape = CursorFontShape.XC_fleur; 
2372                                         break;
2373                                 }
2374
2375                                 case StdCursor.PanSouth: {
2376                                         shape = CursorFontShape.XC_fleur; 
2377                                         break;
2378                                 }
2379
2380                                 case StdCursor.PanSW: {
2381                                         shape = CursorFontShape.XC_fleur; 
2382                                         break;
2383                                 }
2384
2385                                 case StdCursor.PanWest: {
2386                                         shape = CursorFontShape.XC_sizing; 
2387                                         break;
2388                                 }
2389
2390                                 case StdCursor.SizeAll: {
2391                                         shape = CursorFontShape.XC_fleur; 
2392                                         break;
2393                                 }
2394
2395                                 case StdCursor.SizeNESW: {
2396                                         shape = CursorFontShape.XC_top_right_corner; 
2397                                         break;
2398                                 }
2399
2400                                 case StdCursor.SizeNS: {
2401                                         shape = CursorFontShape.XC_sb_v_double_arrow;
2402                                         break;
2403                                 }
2404
2405                                 case StdCursor.SizeNWSE: {
2406                                         shape = CursorFontShape.XC_top_left_corner; 
2407                                         break;
2408                                 }
2409
2410                                 case StdCursor.SizeWE: {
2411                                         shape = CursorFontShape.XC_sb_h_double_arrow; 
2412                                         break;
2413                                 }
2414
2415                                 case StdCursor.UpArrow: {
2416                                         shape = CursorFontShape.XC_center_ptr; 
2417                                         break;
2418                                 }
2419
2420                                 case StdCursor.VSplit: {
2421                                         shape = CursorFontShape.XC_sb_h_double_arrow;
2422                                         break;
2423                                 }
2424
2425                                 case StdCursor.WaitCursor: {
2426                                         shape = CursorFontShape.XC_watch; 
2427                                         break;
2428                                 }
2429
2430                                 default: {
2431                                         return IntPtr.Zero;
2432                                 }
2433                         }
2434
2435                         lock (XlibLock) {
2436                                 cursor = XCreateFontCursor(DisplayHandle, shape);
2437                         }
2438                         return cursor;
2439                 }
2440
2441                 internal override IntPtr DefWndProc(ref Message msg) {
2442                         switch ((Msg)msg.Msg) {
2443                                 case Msg.WM_PAINT: {
2444                                         Hwnd hwnd;
2445
2446                                         hwnd = Hwnd.GetObjectFromWindow(msg.HWnd);
2447                                         if (hwnd != null) {
2448                                                 hwnd.expose_pending = false;
2449                                         }
2450
2451                                         return IntPtr.Zero;
2452                                 }
2453
2454                                 case Msg.WM_NCPAINT: {
2455                                         Hwnd hwnd;
2456
2457                                         hwnd = Hwnd.GetObjectFromWindow(msg.HWnd);
2458                                         if (hwnd != null) {
2459                                                 hwnd.nc_expose_pending = false;
2460                                         }
2461
2462                                         return IntPtr.Zero;
2463                                 }
2464
2465                                 case Msg.WM_SETCURSOR: {
2466                                         Hwnd    hwnd;
2467
2468                                         hwnd = Hwnd.GetObjectFromWindow(msg.HWnd);
2469                                         if (hwnd == null)
2470                                                 break; // not sure how this happens, but it does
2471
2472                                         // Pass to parent window first
2473                                         while ((hwnd.parent != null) && (msg.Result == IntPtr.Zero)) {
2474                                                 hwnd = hwnd.parent;
2475                                                 NativeWindow.WndProc(hwnd.Handle, Msg.WM_SETCURSOR, msg.HWnd, msg.LParam);
2476                                         }
2477
2478                                         if (msg.Result == IntPtr.Zero) {
2479                                                 IntPtr handle;
2480
2481                                                 switch((HitTest)(msg.LParam.ToInt32() & 0xffff)) {
2482                                                         case HitTest.HTBOTTOM:          handle = Cursors.SizeNS.handle; break;
2483                                                         case HitTest.HTBORDER:          handle = Cursors.SizeNS.handle; break;
2484                                                         case HitTest.HTBOTTOMLEFT:      handle = Cursors.SizeNESW.handle; break;
2485                                                         case HitTest.HTBOTTOMRIGHT:     handle = Cursors.SizeNWSE.handle; break;
2486                                                         case HitTest.HTERROR:           if ((msg.LParam.ToInt32() >> 16) == (int)Msg.WM_LBUTTONDOWN) {
2487                                                                                                 AudibleAlert();
2488                                                                                         }
2489                                                                                         handle = Cursors.Default.handle;
2490                                                                                         break;
2491
2492                                                         case HitTest.HTHELP:            handle = Cursors.Help.handle; break;
2493                                                         case HitTest.HTLEFT:            handle = Cursors.SizeWE.handle; break;
2494                                                         case HitTest.HTRIGHT:           handle = Cursors.SizeWE.handle; break;
2495                                                         case HitTest.HTTOP:             handle = Cursors.SizeNS.handle; break;
2496                                                         case HitTest.HTTOPLEFT:         handle = Cursors.SizeNWSE.handle; break;
2497                                                         case HitTest.HTTOPRIGHT:        handle = Cursors.SizeNESW.handle; break;
2498
2499                                                         #if SameAsDefault
2500                                                         case HitTest.HTGROWBOX:
2501                                                         case HitTest.HTSIZE:
2502                                                         case HitTest.HTZOOM:
2503                                                         case HitTest.HTVSCROLL:
2504                                                         case HitTest.HTSYSMENU:
2505                                                         case HitTest.HTREDUCE:
2506                                                         case HitTest.HTNOWHERE:
2507                                                         case HitTest.HTMAXBUTTON:
2508                                                         case HitTest.HTMINBUTTON:
2509                                                         case HitTest.HTMENU:
2510                                                         case HitTest.HSCROLL:
2511                                                         case HitTest.HTBOTTOM:
2512                                                         case HitTest.HTCAPTION:
2513                                                         case HitTest.HTCLIENT:
2514                                                         case HitTest.HTCLOSE:
2515                                                         #endif
2516                                                         default: handle = Cursors.Default.handle; break;
2517                                                 }
2518                                                 SetCursor(msg.HWnd, handle);
2519                                         }
2520                                         return (IntPtr)1;
2521                                 }
2522                         }
2523                         return IntPtr.Zero;
2524                 }
2525
2526                 internal override void DestroyCaret(IntPtr handle) {
2527                         if (Caret.Hwnd == handle) {
2528                                 if (Caret.Visible == true) {
2529                                         Caret.Timer.Stop();
2530                                         HideCaret();
2531                                 }
2532                                 if (Caret.gc != IntPtr.Zero) {
2533                                         XFreeGC(DisplayHandle, Caret.gc);
2534                                         Caret.gc = IntPtr.Zero;
2535                                 }
2536                                 Caret.Hwnd = IntPtr.Zero;
2537                                 Caret.Visible = false;
2538                                 Caret.On = false;
2539                         }
2540                 }
2541
2542                 private void DestroyCaretInternal() {
2543                         if (Caret.Visible == true) {
2544                                 Caret.Timer.Stop();
2545                         }
2546                         if (Caret.gc != IntPtr.Zero) {
2547                                 XFreeGC(DisplayHandle, Caret.gc);
2548                                 Caret.gc = IntPtr.Zero;
2549                         }
2550                         Caret.Hwnd = IntPtr.Zero;
2551                         Caret.Visible = false;
2552                         Caret.On = false;
2553                 }
2554
2555                 internal override void DestroyCursor(IntPtr cursor) {
2556                         lock (XlibLock) {
2557                                 XFreeCursor(DisplayHandle, cursor);
2558                         }
2559                 }
2560
2561                 internal override void DestroyWindow(IntPtr handle) {
2562                         Hwnd    hwnd;
2563
2564                         hwnd = Hwnd.ObjectFromHandle(handle);
2565
2566                         if (hwnd == null) {
2567                                 #if DriverDebug || DriverDebugDestroy
2568                                         Console.WriteLine("window {0:X} already destroyed", handle.ToInt32());
2569                                 #endif
2570                                 return;
2571                         }
2572
2573                         #if DriverDebug || DriverDebugDestroy
2574                                 Console.WriteLine("Destroying window {0:X}", handle.ToInt32());
2575                         #endif
2576
2577                         // Make sure if the caret is in the window, that we destroy the caret, too
2578                         if (Caret.Hwnd == hwnd.client_window) {
2579                                 DestroyCaret(handle);
2580                         }
2581
2582
2583                         SendWMDestroyMessages(Control.ControlNativeWindow.ControlFromHandle(hwnd.Handle));
2584
2585                         lock (XlibLock) {
2586                                 if (hwnd.client_window != IntPtr.Zero) {
2587                                         XDestroyWindow(DisplayHandle, hwnd.client_window);
2588                                 }
2589
2590                                 if ((hwnd.whole_window != IntPtr.Zero) && (hwnd.whole_window != hwnd.client_window)) {
2591                                         XDestroyWindow(DisplayHandle, hwnd.whole_window);
2592                                 }
2593                         }
2594                         hwnd.Dispose();
2595                 }
2596
2597                 internal override IntPtr DispatchMessage(ref MSG msg) {
2598                         return NativeWindow.WndProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
2599                 }
2600
2601                 internal override void DrawReversibleRectangle(IntPtr handle, Rectangle rect, int line_width) {
2602                         Hwnd            hwnd;
2603                         XGCValues       gc_values;
2604                         IntPtr          gc;
2605
2606                         hwnd = Hwnd.ObjectFromHandle(handle);
2607
2608                         gc_values = new XGCValues();
2609
2610                         gc_values.subwindow_mode = GCSubwindowMode.IncludeInferiors;
2611                         gc_values.line_width = line_width;
2612                         gc_values.foreground = XBlackPixel(DisplayHandle, ScreenNo);
2613
2614                         // This logic will give us true rubber bands: (libsx, SANE_XOR)
2615                         //mask = foreground ^ background; 
2616                         //XSetForeground(DisplayHandle, gc, 0xffffffff);
2617                         //XSetBackground(DisplayHandle, gc, background);
2618                         //XSetFunction(DisplayHandle,   gc, GXxor);
2619                         //XSetPlaneMask(DisplayHandle,  gc, mask);
2620
2621
2622                         gc = XCreateGC(DisplayHandle, hwnd.client_window, new IntPtr ((int) (GCFunction.GCSubwindowMode | GCFunction.GCLineWidth | GCFunction.GCForeground)), ref gc_values);
2623                         uint foreground;
2624                         uint background;
2625
2626                         Control control;
2627                         control = Control.FromHandle(handle);
2628
2629                         XColor xcolor = new XColor();
2630
2631                         xcolor.red = (ushort)(control.ForeColor.R * 257);
2632                         xcolor.green = (ushort)(control.ForeColor.G * 257);
2633                         xcolor.blue = (ushort)(control.ForeColor.B * 257);
2634                         XAllocColor(DisplayHandle, DefaultColormap, ref xcolor);
2635                         foreground = (uint)xcolor.pixel.ToInt32();
2636
2637                         xcolor.red = (ushort)(control.BackColor.R * 257);
2638                         xcolor.green = (ushort)(control.BackColor.G * 257);
2639                         xcolor.blue = (ushort)(control.BackColor.B * 257);
2640                         XAllocColor(DisplayHandle, DefaultColormap, ref xcolor);
2641                         background = (uint)xcolor.pixel.ToInt32();
2642
2643                         uint mask = foreground ^ background; 
2644
2645                         XSetForeground(DisplayHandle, gc, (UIntPtr)0xffffffff);
2646                         XSetBackground(DisplayHandle, gc, (UIntPtr)background);
2647                         XSetFunction(DisplayHandle,   gc, GXFunction.GXxor);
2648                         XSetPlaneMask(DisplayHandle,  gc, (IntPtr)mask);
2649
2650                         if ((rect.Width > 0) && (rect.Height > 0)) {
2651                                 XDrawRectangle(DisplayHandle, hwnd.client_window, gc, rect.Left, rect.Top, rect.Width, rect.Height);
2652                         } else {
2653                                 if (rect.Width > 0) {
2654                                         XDrawLine(DisplayHandle, hwnd.client_window, gc, rect.X, rect.Y, rect.Right, rect.Y);
2655                                 } else {
2656                                         XDrawLine(DisplayHandle, hwnd.client_window, gc, rect.X, rect.Y, rect.X, rect.Bottom);
2657                                 }
2658                         }
2659                         XFreeGC(DisplayHandle, gc);
2660                 }
2661
2662                 internal override void DoEvents() {
2663                         MSG     msg = new MSG ();
2664                         Object  queue_id;
2665
2666                         if (OverrideCursorHandle != IntPtr.Zero) {
2667                                 OverrideCursorHandle = IntPtr.Zero;
2668                         }
2669
2670                         queue_id = (Object)ThreadQueue(Thread.CurrentThread);
2671
2672                         while (PeekMessage(queue_id, ref msg, IntPtr.Zero, 0, 0, (uint)PeekMessageFlags.PM_REMOVE)) {
2673                                 TranslateMessage (ref msg);
2674                                 DispatchMessage (ref msg);
2675                         }
2676                 }
2677
2678                 internal override void EnableWindow(IntPtr handle, bool Enable) {
2679                         Hwnd    hwnd;
2680
2681                         hwnd = Hwnd.ObjectFromHandle(handle);
2682                         if (hwnd != null) {
2683                                 hwnd.Enabled = Enable;
2684                         }
2685                 }
2686
2687                 internal override void EndLoop(Thread thread) {
2688                         // This is where we one day will shut down the loop for the thread
2689                 }
2690
2691
2692                 internal override IntPtr GetActive() {
2693                         IntPtr  actual_atom;
2694                         int     actual_format;
2695                         IntPtr  nitems;
2696                         IntPtr  bytes_after;
2697                         IntPtr  prop = IntPtr.Zero;
2698                         IntPtr  active = IntPtr.Zero;
2699
2700                         XGetWindowProperty(DisplayHandle, RootWindow, NetAtoms[(int)NA._NET_ACTIVE_WINDOW], IntPtr.Zero, new IntPtr (1), false, (IntPtr)Atom.XA_WINDOW, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
2701                         if (((long)nitems > 0) && (prop != IntPtr.Zero)) {
2702                                 active = (IntPtr)Marshal.ReadInt32(prop);
2703                                 XFree(prop);
2704                         }
2705
2706                         if (active != IntPtr.Zero) {
2707                                 Hwnd    hwnd;
2708
2709                                 hwnd = Hwnd.GetObjectFromWindow(active);
2710                                 if (hwnd != null) {
2711                                         active = hwnd.Handle;
2712                                 } else {
2713                                         active = IntPtr.Zero;
2714                                 }
2715                         }
2716                         return active;
2717                 }
2718
2719                 internal override void GetCursorInfo(IntPtr cursor, out int width, out int height, out int hotspot_x, out int hotspot_y) {
2720                         width = 20;
2721                         height = 20;
2722                         hotspot_x = 0;
2723                         hotspot_y = 0;
2724                 }
2725
2726                 internal override void GetDisplaySize(out Size size) {
2727                         XWindowAttributes       attributes=new XWindowAttributes();
2728
2729                         lock (XlibLock) {
2730                                 // FIXME - use _NET_WM messages instead?
2731                                 XGetWindowAttributes(DisplayHandle, XRootWindow(DisplayHandle, 0), ref attributes);
2732                         }
2733
2734                         size = new Size(attributes.width, attributes.height);
2735                 }
2736
2737                 internal override SizeF GetAutoScaleSize(Font font) {
2738                         Graphics        g;
2739                         float           width;
2740                         string          magic_string = "The quick brown fox jumped over the lazy dog.";
2741                         double          magic_number = 44.549996948242189;
2742
2743                         g = Graphics.FromHwnd(FosterParent);
2744
2745                         width = (float) (g.MeasureString (magic_string, font).Width / magic_number);
2746                         return new SizeF(width, font.Height);
2747                 }
2748
2749                 internal override IntPtr GetParent(IntPtr handle) {
2750                         Hwnd    hwnd;
2751
2752                         hwnd = Hwnd.ObjectFromHandle(handle);
2753                         if (hwnd != null && hwnd.parent != null) {
2754                                 return hwnd.parent.Handle;
2755                         }
2756                         return IntPtr.Zero;
2757                 }
2758
2759                 internal override void GetCursorPos(IntPtr handle, out int x, out int y) {
2760                         IntPtr  use_handle;
2761                         IntPtr  root;
2762                         IntPtr  child;
2763                         int     root_x;
2764                         int     root_y;
2765                         int     win_x;
2766                         int     win_y;
2767                         int     keys_buttons;
2768
2769                         if (handle != IntPtr.Zero) {
2770                                 use_handle = Hwnd.ObjectFromHandle(handle).client_window;
2771                         } else {
2772                                 use_handle = RootWindow;
2773                         }
2774
2775                         lock (XlibLock) {
2776                                 XQueryPointer(DisplayHandle, use_handle, out root, out child, out root_x, out root_y, out win_x, out win_y, out keys_buttons);
2777                         }
2778
2779                         if (handle != IntPtr.Zero) {
2780                                 x = win_x;
2781                                 y = win_y;
2782                         } else {
2783                                 x = root_x;
2784                                 y = root_y;
2785                         }
2786                 }
2787
2788                 internal override bool GetFontMetrics(Graphics g, Font font, out int ascent, out int descent) {
2789                         return GetFontMetrics(g.GetHdc(), font.ToHfont(), out ascent, out descent);
2790                 }
2791
2792                 internal override Point GetMenuOrigin(IntPtr handle) {
2793                         Hwnd    hwnd;
2794
2795                         hwnd = Hwnd.ObjectFromHandle(handle);
2796
2797                         if (hwnd != null) {
2798                                 return hwnd.MenuOrigin;
2799                         }
2800                         return Point.Empty;
2801                 }
2802
2803                 [MonoTODO("Implement filtering")]
2804                 internal override bool GetMessage(Object queue_id, ref MSG msg, IntPtr handle, int wFilterMin, int wFilterMax) {
2805                         XEvent  xevent;
2806                         bool    client;
2807                         Hwnd    hwnd;
2808
2809                         ProcessNextMessage:
2810
2811                         if (((XEventQueue)queue_id).Count > 0) {
2812                                 xevent = (XEvent) ((XEventQueue)queue_id).Dequeue ();
2813                         } else {
2814                                 UpdateMessageQueue ((XEventQueue)queue_id);
2815
2816                                 if (((XEventQueue)queue_id).Count > 0) {
2817                                         xevent = (XEvent) ((XEventQueue)queue_id).Dequeue ();
2818                                 } else if (((XEventQueue)queue_id).Paint.Count > 0) {
2819                                         xevent = ((XEventQueue)queue_id).Paint.Dequeue();
2820                                 } else {
2821                                         if (!PostQuitState) {
2822                                                 msg.hwnd= IntPtr.Zero;
2823                                                 msg.message = Msg.WM_ENTERIDLE;
2824                                                 return true;
2825                                         }
2826
2827                                         // We reset ourselves so GetMessage can be called again
2828                                         PostQuitState = false;
2829
2830                                         return false;
2831                                 }
2832                         }
2833
2834                         hwnd = Hwnd.GetObjectFromWindow(xevent.AnyEvent.window);
2835
2836                         // Handle messages for windows that are already or are about to be destroyed
2837                         if (hwnd == null) {
2838                                 #if DriverDebug
2839                                         Console.WriteLine("GetMessage(): Got message {0} for non-existent or already destroyed window {1:X}", xevent.type, xevent.AnyEvent.window.ToInt32());
2840                                 #endif
2841                                 goto ProcessNextMessage;
2842                         }
2843
2844                         if (hwnd.client_window == xevent.AnyEvent.window) {
2845                                 client = true;
2846                                 //Console.WriteLine("Client message, sending to window {0:X}", msg.hwnd.ToInt32());
2847                         } else {
2848                                 client = false;
2849                                 //Console.WriteLine("Non-Client message, sending to window {0:X}", msg.hwnd.ToInt32());
2850                         }
2851
2852                         msg.hwnd = hwnd.Handle;
2853
2854                         //
2855                         // If you add a new event to this switch make sure to add it in
2856                         // UpdateMessage also unless it is not coming through the X event system.
2857                         //
2858                         switch(xevent.type) {
2859                                 case XEventName.KeyPress: {
2860                                         Keyboard.KeyEvent (FocusWindow, xevent, ref msg);
2861                                         break;
2862                                 }
2863
2864                                 case XEventName.KeyRelease: {
2865                                         Keyboard.KeyEvent (FocusWindow, xevent, ref msg);
2866                                         break;
2867                                 }
2868
2869                                 case XEventName.ButtonPress: {
2870                                         switch(xevent.ButtonEvent.button) {
2871                                                 case 1: {
2872                                                         MouseState |= MouseButtons.Left;
2873                                                         if (client) {
2874                                                                 msg.message = Msg.WM_LBUTTONDOWN;
2875                                                         } else {
2876                                                                 msg.message = Msg.WM_NCLBUTTONDOWN;
2877                                                                 WholeToScreen (msg.hwnd, ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
2878                                                         }
2879                                                         // TODO: For WM_NCLBUTTONDOWN wParam specifies a hit-test value not the virtual keys down
2880                                                         msg.wParam=GetMousewParam(0);
2881                                                         break;
2882                                                 }
2883
2884                                                 case 2: {
2885                                                         MouseState |= MouseButtons.Middle;
2886                                                         if (client) {
2887                                                                 msg.message = Msg.WM_MBUTTONDOWN;
2888                                                         } else {
2889                                                                 msg.message = Msg.WM_NCMBUTTONDOWN;
2890                                                                 WholeToScreen (msg.hwnd, ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
2891                                                         }
2892                                                         msg.wParam=GetMousewParam(0);
2893                                                         break;
2894                                                 }
2895
2896                                                 case 3: {
2897                                                         MouseState |= MouseButtons.Right;
2898                                                         if (client) {
2899                                                                 msg.message = Msg.WM_RBUTTONDOWN;
2900                                                         } else {
2901                                                                 msg.message = Msg.WM_NCRBUTTONDOWN;
2902                                                                 WholeToScreen (msg.hwnd, ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
2903                                                         }
2904                                                         msg.wParam=GetMousewParam(0);
2905                                                         break;
2906                                                 }
2907
2908                                                 case 4: {
2909                                                         msg.message=Msg.WM_MOUSEWHEEL;
2910                                                         msg.wParam=GetMousewParam(120);
2911                                                         break;
2912                                                 }
2913
2914                                                 case 5: {
2915                                                         msg.message=Msg.WM_MOUSEWHEEL;
2916                                                         msg.wParam=GetMousewParam(-120);
2917                                                         break;
2918                                                 }
2919
2920                                         }
2921
2922                                         msg.lParam=(IntPtr) (xevent.ButtonEvent.y << 16 | xevent.ButtonEvent.x);
2923                                         MousePosition.X = xevent.ButtonEvent.x;
2924                                         MousePosition.Y = xevent.ButtonEvent.y;
2925
2926                                         if (!hwnd.Enabled) {
2927                                                 IntPtr dummy;
2928
2929                                                 msg.hwnd = hwnd.EnabledHwnd;
2930                                                 XTranslateCoordinates(DisplayHandle, xevent.AnyEvent.window, Hwnd.ObjectFromHandle(msg.hwnd).ClientWindow, xevent.ButtonEvent.x, xevent.ButtonEvent.y, out xevent.ButtonEvent.x, out xevent.ButtonEvent.y, out dummy);
2931                                                 msg.lParam = (IntPtr)(MousePosition.Y << 16 | MousePosition.X);
2932                                         }
2933
2934                                         if (Grab.Hwnd != IntPtr.Zero) {
2935                                                 msg.hwnd = Grab.Hwnd;
2936                                         }
2937
2938                                         if (!ClickPending.Pending) {
2939                                                 ClickPending.Pending = true;
2940                                                 ClickPending.Hwnd = msg.hwnd;
2941                                                 ClickPending.Message = msg.message;
2942                                                 ClickPending.wParam = msg.wParam;
2943                                                 ClickPending.lParam = msg.lParam;
2944                                                 ClickPending.Time = (long)xevent.ButtonEvent.time;
2945                                         } else {
2946                                                 if ((((long)xevent.ButtonEvent.time - ClickPending.Time) < DoubleClickInterval) && (msg.wParam == ClickPending.wParam) && (msg.lParam == ClickPending.lParam) && (msg.message == ClickPending.Message)) {
2947                                                         // Looks like a genuine double click, clicked twice on the same spot with the same keys
2948                                                         switch(xevent.ButtonEvent.button) {
2949                                                                 case 1: {
2950                                                                         msg.message = client ? Msg.WM_LBUTTONDBLCLK : Msg.WM_NCLBUTTONDBLCLK;
2951                                                                         break;
2952                                                                 }
2953
2954                                                                 case 2: {
2955                                                                         msg.message = client ? Msg.WM_MBUTTONDBLCLK : Msg.WM_NCMBUTTONDBLCLK;
2956                                                                         break;
2957                                                                 }
2958
2959                                                                 case 3: {
2960                                                                         msg.message = client ? Msg.WM_RBUTTONDBLCLK : Msg.WM_NCRBUTTONDBLCLK;
2961                                                                         break;
2962                                                                 }
2963                                                         }
2964                                                 }
2965                                                 ClickPending.Pending = false;
2966                                         }
2967
2968                                         break;
2969                                 }
2970
2971                                 case XEventName.ButtonRelease: {
2972                                         if (Dnd.InDrag()) {
2973                                                 Dnd.HandleButtonRelease (ref xevent);
2974                                                 break;
2975                                         }
2976
2977                                         switch(xevent.ButtonEvent.button) {
2978                                                 case 1: {
2979                                                         MouseState &= ~MouseButtons.Left;
2980                                                         if (client) {
2981                                                                 msg.message = Msg.WM_LBUTTONUP;
2982                                                         } else {
2983                                                                 msg.message = Msg.WM_NCLBUTTONUP;
2984                                                                 WholeToScreen (msg.hwnd, ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
2985                                                         }
2986                                                         msg.wParam=GetMousewParam(0);
2987                                                         break;
2988                                                 }
2989
2990                                                 case 2: {
2991                                                         MouseState &= ~MouseButtons.Middle;
2992                                                         if (client) {
2993                                                                 msg.message = Msg.WM_MBUTTONUP;
2994                                                         } else {
2995                                                                 msg.message = Msg.WM_NCMBUTTONUP;
2996                                                                 WholeToScreen (msg.hwnd, ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
2997                                                         }
2998                                                         msg.wParam=GetMousewParam(0);
2999                                                         break;
3000                                                 }
3001
3002                                                 case 3: {
3003                                                         MouseState &= ~MouseButtons.Right;
3004                                                         if (client) {
3005                                                                 msg.message = Msg.WM_RBUTTONUP;
3006                                                         } else {
3007                                                                 msg.message = Msg.WM_NCRBUTTONUP;
3008                                                                 WholeToScreen (msg.hwnd, ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
3009                                                         }
3010                                                         msg.wParam=GetMousewParam(0);
3011                                                         break;
3012                                                 }
3013
3014                                                 case 4: {
3015                                                         goto ProcessNextMessage;
3016                                                 }
3017
3018                                                 case 5: {
3019                                                         goto ProcessNextMessage;
3020                                                 }
3021                                         }
3022
3023                                         if (!hwnd.Enabled) {
3024                                                 IntPtr dummy;
3025
3026                                                 msg.hwnd = hwnd.EnabledHwnd;
3027                                                 XTranslateCoordinates(DisplayHandle, xevent.AnyEvent.window, Hwnd.ObjectFromHandle(msg.hwnd).ClientWindow, xevent.ButtonEvent.x, xevent.ButtonEvent.y, out xevent.ButtonEvent.x, out xevent.ButtonEvent.y, out dummy);
3028                                                 msg.lParam = (IntPtr)(MousePosition.Y << 16 | MousePosition.X);
3029                                         }
3030
3031                                         if (Grab.Hwnd != IntPtr.Zero) {
3032                                                 msg.hwnd = Grab.Hwnd;
3033                                         }
3034
3035                                         msg.lParam=(IntPtr) (xevent.ButtonEvent.y << 16 | xevent.ButtonEvent.x);
3036                                         MousePosition.X = xevent.ButtonEvent.x;
3037                                         MousePosition.Y = xevent.ButtonEvent.y;
3038                                         break;
3039                                 }
3040
3041                                 case XEventName.MotionNotify: {
3042                                         if (client) {
3043                                                 #if DriverDebugExtra
3044                                                         Console.WriteLine("GetMessage(): Window {0:X} MotionNotify x={1} y={2}", client ? hwnd.client_window.ToInt32() : hwnd.whole_window.ToInt32(), xevent.MotionEvent.x, xevent.MotionEvent.y);
3045                                                 #endif
3046
3047                                                 if (Dnd.HandleMotionNotify (ref xevent))
3048                                                         goto ProcessNextMessage;
3049                                                 if (Grab.Hwnd != IntPtr.Zero) {
3050                                                         msg.hwnd = Grab.Hwnd;
3051                                                 } else {
3052                                                         NativeWindow.WndProc(msg.hwnd, Msg.WM_SETCURSOR, msg.hwnd, (IntPtr)HitTest.HTCLIENT);
3053                                                 }
3054
3055                                                 msg.message = Msg.WM_MOUSEMOVE;
3056                                                 msg.wParam = GetMousewParam(0);
3057                                                 msg.lParam = (IntPtr) (xevent.MotionEvent.y << 16 | xevent.MotionEvent.x & 0xFFFF);
3058
3059                                                 if (!hwnd.Enabled) {
3060                                                         IntPtr dummy;
3061
3062                                                         msg.hwnd = hwnd.EnabledHwnd;
3063                                                         XTranslateCoordinates(DisplayHandle, xevent.AnyEvent.window, Hwnd.ObjectFromHandle(msg.hwnd).ClientWindow, xevent.MotionEvent.x, xevent.MotionEvent.y, out xevent.MotionEvent.x, out xevent.MotionEvent.y, out dummy);
3064                                                         msg.lParam = (IntPtr)(MousePosition.Y << 16 | MousePosition.X);
3065                                                 }
3066
3067                                                 MousePosition.X = xevent.MotionEvent.x;
3068                                                 MousePosition.Y = xevent.MotionEvent.y;
3069
3070                                                 if ((HoverState.Timer.Enabled) &&
3071                                                     (((MousePosition.X + HoverState.Size.Width) < HoverState.X) ||
3072                                                     ((MousePosition.X - HoverState.Size.Width) > HoverState.X) ||
3073                                                     ((MousePosition.Y + HoverState.Size.Height) < HoverState.Y) ||
3074                                                     ((MousePosition.Y - HoverState.Size.Height) > HoverState.Y))) {
3075                                                         HoverState.Timer.Stop();
3076                                                         HoverState.Timer.Start();
3077                                                         HoverState.X = MousePosition.X;
3078                                                         HoverState.Y = MousePosition.Y;
3079                                                 }
3080
3081                                                 break;
3082                                         } else {
3083                                                 HitTest ht;
3084                                                 IntPtr dummy;
3085                                                 int screen_x;
3086                                                 int screen_y;
3087
3088                                                 #if DriverDebugExtra
3089                                                         Console.WriteLine("GetMessage(): non-client area {0:X} MotionNotify x={1} y={2}", client ? hwnd.client_window.ToInt32() : hwnd.whole_window.ToInt32(), xevent.MotionEvent.x, xevent.MotionEvent.y);
3090                                                 #endif
3091                                                 msg.message = Msg.WM_NCMOUSEMOVE;
3092
3093                                                 if (!hwnd.Enabled) {
3094                                                         msg.hwnd = hwnd.EnabledHwnd;
3095                                                         XTranslateCoordinates(DisplayHandle, xevent.AnyEvent.window, Hwnd.ObjectFromHandle(msg.hwnd).ClientWindow, xevent.MotionEvent.x, xevent.MotionEvent.y, out xevent.MotionEvent.x, out xevent.MotionEvent.y, out dummy);
3096                                                         msg.lParam = (IntPtr)(MousePosition.Y << 16 | MousePosition.X);
3097                                                 }
3098
3099                                                 // The hit test is sent in screen coordinates
3100                                                 XTranslateCoordinates (DisplayHandle, hwnd.client_window, RootWindow,
3101                                                                 xevent.MotionEvent.x, xevent.MotionEvent.y,
3102                                                                 out screen_x, out screen_y, out dummy);
3103
3104                                                 msg.lParam = (IntPtr) (screen_y << 16 | screen_x & 0xFFFF);
3105                                                 ht = (HitTest)NativeWindow.WndProc (hwnd.client_window, Msg.WM_NCHITTEST,
3106                                                                 IntPtr.Zero, msg.lParam).ToInt32 ();
3107                                                 NativeWindow.WndProc(hwnd.client_window, Msg.WM_SETCURSOR, msg.hwnd, (IntPtr)ht);
3108
3109                                                 MousePosition.X = xevent.MotionEvent.x;
3110                                                 MousePosition.Y = xevent.MotionEvent.y;
3111                                         }
3112
3113                                         break;
3114                                 }
3115
3116                                 case XEventName.EnterNotify: {
3117                                         if (!hwnd.Enabled) {
3118                                                 goto ProcessNextMessage;
3119                                         }
3120                                         if (xevent.CrossingEvent.mode != NotifyMode.NotifyNormal) {
3121                                                 goto ProcessNextMessage;
3122                                         }
3123                                         msg.message = Msg.WM_MOUSE_ENTER;
3124                                         HoverState.X = xevent.CrossingEvent.x;
3125                                         HoverState.Y = xevent.CrossingEvent.y;
3126                                         HoverState.Timer.Enabled = true;
3127                                         HoverState.Window = xevent.CrossingEvent.window;
3128                                         break;
3129                                 }
3130
3131                                 case XEventName.LeaveNotify: {
3132                                         if (!hwnd.Enabled) {
3133                                                 goto ProcessNextMessage;
3134                                         }
3135                                         if ((xevent.CrossingEvent.mode != NotifyMode.NotifyNormal) || (xevent.CrossingEvent.window != hwnd.client_window)) {
3136                                                 goto ProcessNextMessage;
3137                                         }
3138                                         msg.message=Msg.WM_MOUSE_LEAVE;
3139                                         HoverState.Timer.Enabled = false;
3140                                         HoverState.Window = IntPtr.Zero;
3141                                         break;
3142                                 }
3143
3144                                 #if later
3145                                 case XEventName.CreateNotify: {
3146                                         if (client && (xevent.ConfigureEvent.xevent == xevent.ConfigureEvent.window)) {
3147                                                 msg.message = WM_CREATE;
3148                                                 // Set up CreateStruct
3149                                         } else {
3150                                                 goto ProcessNextMessage;
3151                                         }
3152                                         break;
3153                                 }
3154                                 #endif
3155
3156
3157                                 case XEventName.ReparentNotify: {
3158                                         if (hwnd.parent == null) {      // Toplevel
3159                                                 if ((xevent.ReparentEvent.parent != IntPtr.Zero) && (xevent.ReparentEvent.window == hwnd.whole_window)) {
3160                                                         // We need to adjust x/y
3161                                                         // This sucks ass, part 2
3162                                                         // Every WM does the reparenting of toplevel windows different, so there's
3163                                                         // no standard way of getting our adjustment considering frames/decorations
3164                                                         // The code below is needed for metacity. KDE doesn't works just fine without this
3165                                                         int     dummy_int;
3166                                                         IntPtr  dummy_ptr;
3167                                                         int     new_x;
3168                                                         int     new_y;
3169                                                         int     frame_left;
3170                                                         int     frame_top;
3171
3172                                                         hwnd.Reparented = true;
3173
3174                                                         XGetGeometry(DisplayHandle, XGetParent(hwnd.whole_window), out dummy_ptr, out new_x, out new_y, out dummy_int, out dummy_int, out dummy_int, out dummy_int);
3175                                                         FrameExtents(hwnd.whole_window, out frame_left, out frame_top);
3176                                                         if ((frame_left != 0) && (frame_top != 0) && (new_x != frame_left) && (new_y != frame_top)) {
3177                                                                 hwnd.x = new_x;
3178                                                                 hwnd.y = new_y;
3179                                                                 hwnd.whacky_wm = true;
3180                                                         }
3181
3182                                                         msg.message = Msg.WM_WINDOWPOSCHANGED;
3183                                                         if (hwnd.opacity != 0xffffffff) {
3184                                                                 IntPtr opacity;
3185
3186                                                                 opacity = (IntPtr)hwnd.opacity;
3187                                                                 XChangeProperty(DisplayHandle, XGetParent(hwnd.whole_window), NetAtoms[(int)NA._NET_WM_WINDOW_OPACITY], (IntPtr)Atom.XA_CARDINAL, 32, PropertyMode.Replace, ref opacity, 1);
3188                                                         }
3189                                                         return true;
3190                                                 } else {
3191                                                         hwnd.Reparented = false;
3192                                                         goto ProcessNextMessage;
3193                                                 }
3194                                         }
3195                                         goto ProcessNextMessage;
3196                                 }
3197
3198                                 case XEventName.ConfigureNotify: {
3199                                         if (PostQuitState || !client && (xevent.ConfigureEvent.xevent == xevent.ConfigureEvent.window)) {       // Ignore events for children (SubstructureNotify) and client areas
3200                                                 #if DriverDebugExtra
3201                                                         Console.WriteLine("GetMessage(): Window {0:X} ConfigureNotify x={1} y={2} width={3} height={4}", hwnd.client_window.ToInt32(), xevent.ConfigureEvent.x, xevent.ConfigureEvent.y, xevent.ConfigureEvent.width, xevent.ConfigureEvent.height);
3202                                                 #endif
3203                                                 msg.message = Msg.WM_WINDOWPOSCHANGED;
3204                                                 hwnd.configure_pending = false;
3205
3206                                                 // We need to adjust our client window to track the resize of whole_window
3207                                                 PerformNCCalc(hwnd);
3208                                         } else {
3209                                                 goto ProcessNextMessage;
3210                                         }
3211
3212                                         msg.lParam=IntPtr.Zero;         // FIXME - Generate LPWINDOWPOS structure and pass on
3213                                         break;
3214                                 }
3215
3216                                 case XEventName.FocusIn: {
3217                                         // We received focus. We use X11 focus only to know if the app window does or does not have focus
3218                                         // We do not track the actual focussed window via it. Instead, this is done via FocusWindow internally
3219                                         // Receiving focus means we've gotten activated and therefore we need to let the actual FocusWindow know 
3220                                         // about it having focus again
3221                                         if (xevent.FocusChangeEvent.detail != NotifyDetail.NotifyNonlinear) {
3222                                                 goto ProcessNextMessage;
3223                                         }
3224                                         Keyboard.FocusIn(FocusWindow);
3225                                         SendMessage(FocusWindow, Msg.WM_SETFOCUS, IntPtr.Zero, IntPtr.Zero);
3226                                         goto ProcessNextMessage;
3227                                 }
3228
3229                                 case XEventName.FocusOut: {
3230                                         // Se the comment for our FocusIn handler
3231                                         if (xevent.FocusChangeEvent.detail != NotifyDetail.NotifyNonlinear) {
3232                                                 goto ProcessNextMessage;
3233                                         }
3234                                         Keyboard.FocusOut(FocusWindow);
3235
3236                                         while (Keyboard.ResetKeyState(FocusWindow, ref msg)) {
3237                                                 SendMessage(FocusWindow, msg.message, msg.wParam, msg.lParam);
3238                                         }
3239
3240                                         SendMessage(FocusWindow, Msg.WM_KILLFOCUS, IntPtr.Zero, IntPtr.Zero);
3241                                         goto ProcessNextMessage;
3242                                 }
3243
3244                                 case XEventName.Expose: {
3245                                         if (PostQuitState || !hwnd.Mapped) {
3246                                                 if (client) {
3247                                                         hwnd.expose_pending = false;
3248                                                 } else {
3249                                                         hwnd.nc_expose_pending = false;
3250                                                 }
3251                                                 goto ProcessNextMessage;
3252                                         }
3253
3254                                         if (client) {
3255                                                 if (!hwnd.expose_pending) {
3256                                                         goto ProcessNextMessage;
3257                                                 }
3258                                         } else {
3259                                                 if (!hwnd.nc_expose_pending) {
3260                                                         goto ProcessNextMessage;
3261                                                 }
3262
3263                                                 switch (hwnd.border_style) {
3264                                                         case FormBorderStyle.Fixed3D: {
3265                                                                 Graphics g;
3266
3267                                                                 g = Graphics.FromHwnd(hwnd.whole_window);
3268                                                                 ControlPaint.DrawBorder3D(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height), Border3DStyle.Sunken);
3269                                                                 g.Dispose();
3270                                                                 break;
3271                                                         }
3272
3273                                                         case FormBorderStyle.FixedSingle: {
3274                                                                 Graphics g;
3275
3276                                                                 g = Graphics.FromHwnd(hwnd.whole_window);
3277                                                                 ControlPaint.DrawBorder(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height), Color.Black, ButtonBorderStyle.Solid);
3278                                                                 g.Dispose();
3279                                                                 break;
3280                                                         }
3281                                                 }
3282                                                 #if DriverDebugExtra
3283                                                         Console.WriteLine("GetMessage(): Window {0:X} Exposed non-client area {1},{2} {3}x{4}", hwnd.client_window.ToInt32(), xevent.ExposeEvent.x, xevent.ExposeEvent.y, xevent.ExposeEvent.width, xevent.ExposeEvent.height);
3284                                                 #endif
3285
3286                                                 Rectangle rect = new Rectangle (xevent.ExposeEvent.x, xevent.ExposeEvent.y, xevent.ExposeEvent.width, xevent.ExposeEvent.height);
3287                                                 Region region = new Region (rect);
3288                                                 IntPtr hrgn = region.GetHrgn (null); // Graphics object isn't needed
3289                                                 msg.message = Msg.WM_NCPAINT;
3290                                                 msg.wParam = hrgn;
3291                                                 break;
3292                                         }
3293                                         #if DriverDebugExtra
3294                                                 Console.WriteLine("GetMessage(): Window {0:X} Exposed area {1},{2} {3}x{4}", hwnd.client_window.ToInt32(), xevent.ExposeEvent.x, xevent.ExposeEvent.y, xevent.ExposeEvent.width, xevent.ExposeEvent.height);
3295                                         #endif
3296                                         if (Caret.Visible == true) {
3297                                                 Caret.Paused = true;
3298                                                 HideCaret();
3299                                         }
3300
3301                                         if (Caret.Visible == true) {
3302                                                 ShowCaret();
3303                                                 Caret.Paused = false;
3304                                         }
3305                                         msg.message = Msg.WM_PAINT;
3306                                         break;
3307                                 }
3308
3309                                 case XEventName.DestroyNotify: {
3310
3311                                         // This is a bit tricky, we don't receive our own DestroyNotify, we only get those for our children
3312                                         hwnd = Hwnd.ObjectFromHandle(xevent.DestroyWindowEvent.window);
3313
3314                                         // We may get multiple for the same window, act only one the first (when Hwnd still knows about it)
3315                                         if ((hwnd != null) && (hwnd.client_window == xevent.DestroyWindowEvent.window)) {
3316                                                 if (Caret.Window == hwnd.client_window) {
3317                                                         DestroyCaretInternal();
3318                                                 }
3319
3320                                                 #if DriverDebugDestroy
3321                                                         Console.WriteLine("Received X11 Destroy Notification for {0}", XplatUI.Window(hwnd.client_window));
3322                                                 #endif
3323
3324                                                 msg.hwnd = hwnd.client_window;
3325                                                 msg.message=Msg.WM_DESTROY;
3326                                                 hwnd.Dispose();
3327
3328                                                 #if DriverDebug
3329                                                         Console.WriteLine("Got DestroyNotify on Window {0:X}", msg.hwnd.ToInt32());
3330                                                 #endif
3331                                         } else {
3332                                                 goto ProcessNextMessage;
3333                                         }
3334
3335                                         break;
3336                                 }
3337
3338                                 case XEventName.ClientMessage: {
3339                                         if (Dnd.HandleClientMessage (ref xevent)) {
3340                                                 goto ProcessNextMessage;
3341                                         }
3342
3343                                         if (xevent.ClientMessageEvent.message_type == AsyncAtom) {
3344                                                 XplatUIDriverSupport.ExecuteClientMessage((GCHandle)xevent.ClientMessageEvent.ptr1);
3345                                                 goto ProcessNextMessage;
3346                                         }
3347
3348                                         if (xevent.ClientMessageEvent.message_type == HoverState.Atom) {
3349                                                 msg.message = Msg.WM_MOUSEHOVER;
3350                                                 msg.wParam = GetMousewParam(0);
3351                                                 msg.lParam = (IntPtr) (xevent.ClientMessageEvent.ptr1);
3352                                                 return true;
3353                                         }
3354
3355                                         if (xevent.ClientMessageEvent.message_type == (IntPtr)PostAtom) {
3356                                                 msg.hwnd = xevent.ClientMessageEvent.ptr1;
3357                                                 msg.message = (Msg) xevent.ClientMessageEvent.ptr2.ToInt32 ();
3358                                                 msg.wParam = xevent.ClientMessageEvent.ptr3;
3359                                                 msg.lParam = xevent.ClientMessageEvent.ptr4;
3360                                                 return true;
3361                                         }
3362
3363                                         #if dontcare
3364                                         if  (xevent.ClientMessageEvent.message_type == NetAtoms[(int)NA._XEMBED]) {
3365                                                 Console.WriteLine("GOT EMBED MESSAGE {0:X}", xevent.ClientMessageEvent.ptr2.ToInt32());
3366                                                 break;
3367                                         }
3368                                         #endif
3369
3370                                         if  (xevent.ClientMessageEvent.message_type == NetAtoms[(int)NA.WM_PROTOCOLS]) {
3371                                                 if (xevent.ClientMessageEvent.ptr1 == NetAtoms[(int)NA.WM_DELETE_WINDOW]) {
3372                                                         msg.message = Msg.WM_CLOSE;
3373                                                         Graphics.FromHdcInternal (IntPtr.Zero);
3374                                                         return true;
3375                                                 }
3376
3377                                                 // We should not get this, but I'll leave the code in case we need it in the future
3378                                                 if (xevent.ClientMessageEvent.ptr1 == NetAtoms[(int)NA.WM_TAKE_FOCUS]) {
3379                                                         goto ProcessNextMessage;
3380                                                 }
3381                                         }
3382                                         goto ProcessNextMessage;
3383                                 }
3384
3385                                 case XEventName.TimerNotify: {
3386                                         xevent.TimerNotifyEvent.handler (this, EventArgs.Empty);
3387                                         goto ProcessNextMessage;
3388                                 }
3389                                         
3390                                 default: {
3391                                         goto ProcessNextMessage;
3392                                 }
3393                         }
3394
3395                         return true;
3396                 }
3397
3398                 internal override bool GetText(IntPtr handle, out string text) {
3399                         IntPtr  textptr;
3400
3401                         textptr = IntPtr.Zero;
3402
3403                         lock (XlibLock) {
3404                                 // FIXME - use _NET properties
3405                                 XFetchName(DisplayHandle, Hwnd.ObjectFromHandle(handle).whole_window, ref textptr);
3406                         }
3407                         if (textptr != IntPtr.Zero) {
3408                                 text = Marshal.PtrToStringAnsi(textptr);
3409                                 XFree(textptr);
3410                                 return true;
3411                         } else {
3412                                 text = "";
3413                                 return false;
3414                         }
3415                 }
3416
3417                 internal override void GetWindowPos(IntPtr handle, bool is_toplevel, out int x, out int y, out int width, out int height, out int client_width, out int client_height) {
3418                         Hwnd            hwnd;
3419                         Rectangle       rect;
3420
3421                         hwnd = Hwnd.ObjectFromHandle(handle);
3422
3423                         if (hwnd != null) {
3424                                 x = hwnd.x;
3425                                 y = hwnd.y;
3426                                 width = hwnd.width;
3427                                 height = hwnd.height;
3428
3429                                 rect = Hwnd.GetClientRectangle(hwnd.border_style, hwnd.menu, hwnd.title_style, hwnd.caption_height, hwnd.tool_caption_height, width, height);
3430
3431                                 client_width = rect.Width;
3432                                 client_height = rect.Height;
3433
3434                                 return;
3435                         }
3436
3437                         // Should we throw an exception or fail silently?
3438                         // throw new ArgumentException("Called with an invalid window handle", "handle");
3439
3440                         x = 0;
3441                         y = 0;
3442                         width = 0;
3443                         height = 0;
3444                         client_width = 0;
3445                         client_height = 0;
3446                 }
3447
3448                 internal override FormWindowState GetWindowState(IntPtr handle) {
3449                         IntPtr                  actual_atom;
3450                         int                     actual_format;
3451                         IntPtr                  nitems;
3452                         IntPtr                  bytes_after;
3453                         IntPtr                  prop = IntPtr.Zero;
3454                         IntPtr                  atom;
3455                         int                     maximized;
3456                         bool                    minimized;
3457                         XWindowAttributes       attributes;
3458                         Hwnd                    hwnd;
3459
3460                         hwnd = Hwnd.ObjectFromHandle(handle);
3461
3462                         maximized = 0;
3463                         minimized = false;
3464                         XGetWindowProperty(DisplayHandle, hwnd.whole_window, NetAtoms[(int)NA._NET_WM_STATE], IntPtr.Zero, new IntPtr (256), false, (IntPtr)Atom.XA_ATOM, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
3465                         if (((long)nitems > 0) && (prop != IntPtr.Zero)) {
3466                                 for (int i = 0; i < (long)nitems; i++) {
3467                                         atom = (IntPtr)Marshal.ReadInt32(prop, i * 4);
3468                                         if ((atom == NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_HORZ]) || (atom == NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_VERT])) {
3469                                                 maximized++;
3470                                         } else if (atom == NetAtoms[(int)NA._NET_WM_STATE_HIDDEN]) {
3471                                                 minimized = true;
3472                                         }
3473                                 }
3474                                 XFree(prop);
3475                         }
3476
3477                         if (minimized) {
3478                                 return FormWindowState.Minimized;
3479                         } else if (maximized == 2) {
3480                                 return FormWindowState.Maximized;
3481                         }
3482
3483                         attributes = new XWindowAttributes();
3484                         XGetWindowAttributes(DisplayHandle, handle, ref attributes);
3485                         if (attributes.map_state == MapState.IsUnmapped) {
3486                                 throw new NotSupportedException("Cannot retrieve the state of an unmapped window");
3487                         }
3488
3489
3490                         return FormWindowState.Normal;
3491                 }
3492
3493                 internal override void GrabInfo(out IntPtr handle, out bool GrabConfined, out Rectangle GrabArea) {
3494                         handle = Grab.Hwnd;
3495                         GrabConfined = Grab.Confined;
3496                         GrabArea = Grab.Area;
3497                 }
3498
3499                 internal override void GrabWindow(IntPtr handle, IntPtr confine_to_handle) {
3500                         Hwnd    hwnd;
3501                         IntPtr  confine_to_window;
3502
3503                         confine_to_window = IntPtr.Zero;
3504
3505                         if (confine_to_handle != IntPtr.Zero) {
3506                                 XWindowAttributes       attributes = new XWindowAttributes();
3507
3508                                 hwnd = Hwnd.ObjectFromHandle(confine_to_handle);
3509
3510                                 lock (XlibLock) {
3511                                         XGetWindowAttributes(DisplayHandle, hwnd.client_window, ref attributes);
3512                                 }
3513                                 Grab.Area.X = attributes.x;
3514                                 Grab.Area.Y = attributes.y;
3515                                 Grab.Area.Width = attributes.width;
3516                                 Grab.Area.Height = attributes.height;
3517                                 Grab.Confined = true;
3518                                 confine_to_window = hwnd.client_window;
3519                         }
3520
3521                         Grab.Hwnd = handle;
3522
3523                         hwnd = Hwnd.ObjectFromHandle(handle);
3524
3525                         lock (XlibLock) {
3526                                 XGrabPointer(DisplayHandle, hwnd.client_window, false, 
3527                                         EventMask.ButtonPressMask | EventMask.ButtonMotionMask |
3528                                         EventMask.ButtonReleaseMask | EventMask.PointerMotionMask,
3529                                         GrabMode.GrabModeAsync, GrabMode.GrabModeAsync, confine_to_window, IntPtr.Zero, IntPtr.Zero);
3530                         }
3531                 }
3532
3533                 internal override void UngrabWindow(IntPtr hwnd) {
3534                         lock (XlibLock) {
3535                                 XUngrabPointer(DisplayHandle, IntPtr.Zero);
3536                                 XFlush(DisplayHandle);
3537                         }
3538                         Grab.Hwnd = IntPtr.Zero;
3539                         Grab.Confined = false;
3540                 }
3541
3542                 internal override void HandleException(Exception e) {
3543                         StackTrace st = new StackTrace(e, true);
3544                         Console.WriteLine("Exception '{0}'", e.Message+st.ToString());
3545                         Console.WriteLine("{0}{1}", e.Message, st.ToString());
3546                 }
3547
3548                 internal override void Invalidate(IntPtr handle, Rectangle rc, bool clear) {
3549                         Hwnd    hwnd;
3550
3551                         hwnd = Hwnd.ObjectFromHandle(handle);
3552
3553                         if (clear) {
3554                                 AddExpose (hwnd, true, hwnd.X, hwnd.Y, hwnd.Width, hwnd.Height);
3555                         } else {
3556                                 AddExpose (hwnd, true, rc.X, rc.Y, rc.Width, rc.Height);
3557                         }
3558                 }
3559
3560                 internal override bool IsEnabled(IntPtr handle) {
3561                         return Hwnd.ObjectFromHandle(handle).Enabled;
3562                 }
3563                 
3564                 internal override bool IsVisible(IntPtr handle) {
3565                         return Hwnd.ObjectFromHandle(handle).visible;
3566                 }
3567
3568                 internal override void KillTimer(Timer timer) {
3569                         lock (TimerList) {
3570                                 TimerList.Remove(timer);
3571                         }
3572                 }
3573
3574                 internal override void MenuToScreen(IntPtr handle, ref int x, ref int y) {
3575                         int     dest_x_return;
3576                         int     dest_y_return;
3577                         IntPtr  child;
3578                         Hwnd    hwnd;
3579
3580                         hwnd = Hwnd.ObjectFromHandle(handle);
3581
3582                         lock (XlibLock) {
3583                                 XTranslateCoordinates(DisplayHandle, hwnd.whole_window, RootWindow, x, y, out dest_x_return, out dest_y_return, out child);
3584                         }
3585
3586                         x = dest_x_return;
3587                         y = dest_y_return;
3588                 }
3589
3590                 internal override void OverrideCursor(IntPtr cursor) {
3591                         OverrideCursorHandle = cursor;
3592                 }
3593
3594                 internal override PaintEventArgs PaintEventStart(IntPtr handle, bool client) {
3595                         PaintEventArgs  paint_event;
3596                         Hwnd            hwnd;
3597
3598                         hwnd = Hwnd.ObjectFromHandle(handle);
3599
3600                         if (Caret.Visible == true) {
3601                                 Caret.Paused = true;
3602                                 HideCaret();
3603                         }
3604                         
3605                         if (client) {
3606                                 hwnd.client_dc = Graphics.FromHwnd (hwnd.client_window);
3607                                 hwnd.client_dc.SetClip(hwnd.invalid);
3608                                 paint_event = new PaintEventArgs(hwnd.client_dc, hwnd.invalid);
3609                                 hwnd.expose_pending = false;
3610
3611                                 return paint_event;
3612                         } else {
3613                                 hwnd.non_client_dc = Graphics.FromHwnd (hwnd.whole_window);
3614
3615                                 if (!hwnd.nc_invalid.IsEmpty) {
3616                                         hwnd.non_client_dc.SetClip (hwnd.nc_invalid);
3617                                         paint_event = new PaintEventArgs(hwnd.non_client_dc, hwnd.nc_invalid);
3618                                 } else {
3619                                         paint_event = new PaintEventArgs(hwnd.non_client_dc, new Rectangle(0, 0, hwnd.width, hwnd.height));
3620                                 }
3621                                 hwnd.nc_expose_pending = false;
3622
3623                                 return paint_event;
3624                         }
3625                 }
3626
3627                 internal override void PaintEventEnd(IntPtr handle, bool client) {
3628                         Hwnd    hwnd;
3629
3630                         hwnd = Hwnd.ObjectFromHandle(handle);
3631
3632                         if (client) {
3633                                 hwnd.ClearInvalidArea();
3634
3635                                 hwnd.client_dc.Flush();
3636                                 hwnd.client_dc.Dispose();
3637                                 hwnd.client_dc = null;
3638                         } else {
3639                                 hwnd.ClearNcInvalidArea ();
3640
3641                                 hwnd.non_client_dc.Flush ();
3642                                 hwnd.non_client_dc.Dispose ();
3643                                 hwnd.non_client_dc = null;
3644                         }
3645
3646                         
3647
3648                         if (Caret.Visible == true) {
3649                                 ShowCaret();
3650                                 Caret.Paused = false;
3651                         }
3652                 }
3653
3654                 [MonoTODO("Implement filtering and PM_NOREMOVE")]
3655                 internal override bool PeekMessage(Object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, uint flags) {
3656                         bool    pending;
3657
3658                         if ((flags & (uint)PeekMessageFlags.PM_REMOVE) == 0) {
3659                                 throw new NotImplementedException("PeekMessage PM_NOREMOVE is not implemented yet");    // FIXME - Implement PM_NOREMOVE flag
3660                         }
3661
3662                         pending = false;
3663                         if (((XEventQueue)queue_id).Count > 0) {
3664                                 pending = true;
3665                         } else {
3666                                 // Only call UpdateMessageQueue if real events are pending 
3667                                 // otherwise we go to sleep on the socket
3668                                 if (XPending(DisplayHandle) != 0) {
3669                                         UpdateMessageQueue((XEventQueue)queue_id);
3670                                         pending = true;
3671                                 } else if (((XEventQueue)queue_id).Paint.Count > 0) {
3672                                         pending = true;
3673                                 }
3674                         }
3675
3676                         CheckTimers(DateTime.Now);
3677
3678                         if (!pending) {
3679                                 return false;
3680                         }
3681                         return GetMessage(queue_id, ref msg, hWnd, wFilterMin, wFilterMax);
3682                 }
3683
3684                 // FIXME - I think this should just enqueue directly
3685                 internal override bool PostMessage (IntPtr handle, Msg message, IntPtr wparam, IntPtr lparam) {
3686                         XEvent xevent = new XEvent ();
3687                         Hwnd hwnd = Hwnd.ObjectFromHandle(handle);
3688
3689                         xevent.type = XEventName.ClientMessage;
3690                         xevent.ClientMessageEvent.display = DisplayHandle;
3691
3692                         if (hwnd != null) {
3693                                 xevent.ClientMessageEvent.window = hwnd.whole_window;
3694                         } else {
3695                                 xevent.ClientMessageEvent.window = IntPtr.Zero;
3696                         }
3697
3698                         xevent.ClientMessageEvent.message_type = (IntPtr) PostAtom;
3699                         xevent.ClientMessageEvent.format = 32;
3700                         xevent.ClientMessageEvent.ptr1 = handle;
3701                         xevent.ClientMessageEvent.ptr2 = (IntPtr) message;
3702                         xevent.ClientMessageEvent.ptr3 = wparam;
3703                         xevent.ClientMessageEvent.ptr4 = lparam;
3704
3705                         hwnd.Queue.Enqueue (xevent);
3706
3707                         return true;
3708                 }
3709
3710                 internal override void PostQuitMessage(int exitCode) {
3711                         XFlush(DisplayHandle);
3712                         PostQuitState = true;
3713
3714                         // Remove our display handle from S.D
3715                         Graphics.FromHdcInternal (IntPtr.Zero);
3716                 }
3717
3718                 internal override void RequestNCRecalc(IntPtr handle) {
3719                         Hwnd                            hwnd;
3720
3721                         hwnd = Hwnd.ObjectFromHandle(handle);
3722
3723                         if (hwnd == null) {
3724                                 return;
3725                         }
3726
3727                         PerformNCCalc(hwnd);
3728                         SendMessage(handle, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
3729                         InvalidateWholeWindow(handle);
3730                 }
3731
3732                 internal override void ResetMouseHover(IntPtr handle) {
3733                         Hwnd    hwnd;
3734
3735                         hwnd = Hwnd.ObjectFromHandle(handle);
3736                         if (hwnd == null) {
3737                                 return;
3738                         }
3739
3740                         HoverState.Timer.Enabled = true;
3741                         HoverState.X = MousePosition.X;
3742                         HoverState.Y = MousePosition.Y;
3743                         HoverState.Window = handle;
3744                 }
3745
3746
3747                 internal override void ScreenToClient(IntPtr handle, ref int x, ref int y) {
3748                         int     dest_x_return;
3749                         int     dest_y_return;
3750                         IntPtr  child;
3751                         Hwnd    hwnd;
3752
3753                         hwnd = Hwnd.ObjectFromHandle(handle);
3754
3755                         lock (XlibLock) {
3756                                 XTranslateCoordinates (DisplayHandle, RootWindow, hwnd.client_window, x, y, out dest_x_return, out dest_y_return, out child);
3757                         }
3758
3759                         x = dest_x_return;
3760                         y = dest_y_return;
3761                 }
3762
3763                 internal override void ScreenToMenu(IntPtr handle, ref int x, ref int y) {
3764                         int     dest_x_return;
3765                         int     dest_y_return;
3766                         IntPtr  child;
3767                         Hwnd    hwnd;
3768
3769                         hwnd = Hwnd.ObjectFromHandle(handle);
3770
3771                         lock (XlibLock) {
3772                                 XTranslateCoordinates (DisplayHandle, RootWindow, hwnd.whole_window, x, y, out dest_x_return, out dest_y_return, out child);
3773                         }
3774
3775                         x = dest_x_return;
3776                         y = dest_y_return;
3777                 }
3778
3779                 internal override void ScrollWindow(IntPtr handle, Rectangle area, int XAmount, int YAmount, bool with_children) {
3780                         Hwnd            hwnd;
3781                         IntPtr          gc;
3782                         XGCValues       gc_values;
3783
3784                         hwnd = Hwnd.ObjectFromHandle(handle);
3785
3786                         if (hwnd.invalid != Rectangle.Empty) {
3787                                 // BIG FAT WARNING. This only works with how we use this function right now
3788                                 // where we basically still scroll the whole window, but work around areas
3789                                 // that are covered by our children
3790
3791                                 hwnd.invalid.X += XAmount;
3792                                 hwnd.invalid.Y += YAmount;
3793
3794                                 if (hwnd.invalid.X < 0) {
3795                                         hwnd.invalid.Width += hwnd.invalid.X;
3796                                         hwnd.invalid.X =0;
3797                                 }
3798
3799                                 if (hwnd.invalid.Y < 0) {
3800                                         hwnd.invalid.Height += hwnd.invalid.Y;
3801                                         hwnd.invalid.Y =0;
3802                                 }
3803                         }
3804
3805                         gc_values = new XGCValues();
3806
3807                         if (with_children) {
3808                                 gc_values.subwindow_mode = GCSubwindowMode.IncludeInferiors;
3809                         }
3810
3811                         gc = XCreateGC(DisplayHandle, hwnd.client_window, IntPtr.Zero, ref gc_values);
3812
3813                         XCopyArea(DisplayHandle, hwnd.client_window, hwnd.client_window, gc, area.X - XAmount, area.Y - YAmount, area.Width, area.Height, area.X, area.Y);
3814
3815                         // Generate an expose for the area exposed by the horizontal scroll
3816                         // We don't use AddExpose since we're 
3817                         if (XAmount > 0) {
3818                                 AddExpose(hwnd, true, area.X, area.Y, XAmount, area.Height);
3819                         } else if (XAmount < 0) {
3820                                 AddExpose(hwnd, true, XAmount + area.X + area.Width, area.Y, -XAmount, area.Height);
3821                         }
3822
3823                         // Generate an expose for the area exposed by the vertical scroll
3824                         if (YAmount > 0) {
3825                                 AddExpose(hwnd, true, area.X, area.Y, area.Width, YAmount);
3826                         } else if (YAmount < 0) {
3827                                 AddExpose(hwnd, true, area.X, YAmount + area.Y + area.Height, area.Width, -YAmount);
3828                         }
3829                         XFreeGC(DisplayHandle, gc);
3830
3831 //                      UpdateWindow(handle);
3832                 }
3833
3834                 internal override void ScrollWindow(IntPtr handle, int XAmount, int YAmount, bool with_children) {
3835                         Hwnd    hwnd;
3836
3837                         hwnd = Hwnd.GetObjectFromWindow(handle);
3838
3839                         ScrollWindow(handle, hwnd.ClientRect, XAmount, YAmount, with_children);
3840                 }
3841
3842                 internal override void SendAsyncMethod (AsyncMethodData method) {
3843                         Hwnd    hwnd;
3844                         XEvent  xevent = new XEvent ();
3845
3846                         hwnd = Hwnd.ObjectFromHandle(FosterParent);
3847
3848                         xevent.type = XEventName.ClientMessage;
3849                         xevent.ClientMessageEvent.display = DisplayHandle;
3850                         xevent.ClientMessageEvent.window = FosterParent;
3851                         xevent.ClientMessageEvent.message_type = (IntPtr)AsyncAtom;
3852                         xevent.ClientMessageEvent.format = 32;
3853                         xevent.ClientMessageEvent.ptr1 = (IntPtr) GCHandle.Alloc (method);
3854
3855                         hwnd.Queue.EnqueueLocked (xevent);
3856
3857                         WakeupMain ();
3858                 }
3859
3860                 internal override IntPtr SendMessage (IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam) {
3861                         return NativeWindow.WndProc(hwnd, message, wParam, lParam);
3862                 }
3863
3864                 internal override void SetAllowDrop (IntPtr handle, bool value)
3865                 {
3866                         // We allow drop on all windows
3867                 }
3868
3869                 internal override DragDropEffects StartDrag (IntPtr handle, object data,
3870                                 DragDropEffects allowed_effects)
3871                 {
3872                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
3873
3874                         if (hwnd == null)
3875                                 throw new ArgumentException ("Attempt to begin drag from invalid window handle (" + handle.ToInt32 () + ").");
3876
3877                         return Dnd.StartDrag (hwnd.client_window, data, allowed_effects);
3878                 }
3879
3880                 internal override void SetBorderStyle(IntPtr handle, FormBorderStyle border_style) {
3881                         Hwnd    hwnd;
3882
3883                         hwnd = Hwnd.ObjectFromHandle(handle);
3884
3885                         hwnd.border_style = border_style;
3886                         RequestNCRecalc(handle);
3887                 }
3888
3889                 internal override void SetCaretPos(IntPtr handle, int x, int y) {
3890                         if (Caret.Hwnd == handle) {
3891                                 Caret.Timer.Stop();
3892                                 HideCaret();
3893
3894                                 Caret.X = x;
3895                                 Caret.Y = y;
3896
3897                                 if (Caret.Visible == true) {
3898                                         ShowCaret();
3899                                         Caret.Timer.Start();
3900                                 }
3901                         }
3902                 }
3903
3904                 internal override void SetCursor(IntPtr handle, IntPtr cursor) {
3905                         Hwnd    hwnd;
3906
3907                         if (OverrideCursorHandle == IntPtr.Zero) {
3908                                 if ((LastCursorWindow == handle) && (LastCursorHandle == cursor)) {
3909                                         return;
3910                                 }
3911
3912                                 LastCursorHandle = cursor;
3913                                 LastCursorWindow = handle;
3914
3915                                 hwnd = Hwnd.ObjectFromHandle(handle);
3916                                 lock (XlibLock) {
3917                                         if (cursor != IntPtr.Zero) {
3918                                                 XDefineCursor(DisplayHandle, hwnd.whole_window, cursor);
3919                                         } else {
3920                                                 XUndefineCursor(DisplayHandle, hwnd.whole_window);
3921                                         }
3922                                 }
3923                                 return;
3924                         }
3925
3926                         hwnd = Hwnd.ObjectFromHandle(handle);
3927                         lock (XlibLock) {
3928                                 XDefineCursor(DisplayHandle, hwnd.whole_window, OverrideCursorHandle);
3929                         }
3930                 }
3931
3932                 internal override void SetCursorPos(IntPtr handle, int x, int y) {
3933                         if (handle == IntPtr.Zero) {
3934                                 lock (XlibLock) {
3935                                         XWarpPointer(DisplayHandle, IntPtr.Zero, IntPtr.Zero, 0, 0, 0, 0, x, y);
3936                                 }
3937                                 return;
3938                         } else {
3939                                 Hwnd    hwnd;
3940
3941                                 hwnd = Hwnd.ObjectFromHandle(handle);
3942                                 lock (XlibLock) {
3943                                         XWarpPointer(DisplayHandle, IntPtr.Zero, hwnd.client_window, 0, 0, 0, 0, x, y);
3944                                 }
3945                                 return;
3946                         }
3947                 }
3948
3949                 internal override void SetFocus(IntPtr handle) {
3950                         Hwnd    hwnd;
3951
3952                         hwnd = Hwnd.ObjectFromHandle(handle);
3953
3954                         if (hwnd.client_window == FocusWindow) {
3955                                 return;
3956                         }
3957
3958                         SendMessage(hwnd.client_window, Msg.WM_SETFOCUS, FocusWindow, IntPtr.Zero);
3959                         if (FocusWindow != IntPtr.Zero) {
3960                                 SendMessage(FocusWindow, Msg.WM_KILLFOCUS, hwnd.client_window, IntPtr.Zero);
3961                         }
3962                         FocusWindow = hwnd.client_window;
3963
3964                         //XSetInputFocus(DisplayHandle, Hwnd.ObjectFromHandle(handle).client_window, RevertTo.None, IntPtr.Zero);
3965                 }
3966
3967                 internal override void SetIcon(IntPtr handle, Icon icon) {
3968                         Hwnd    hwnd;
3969
3970                         hwnd = Hwnd.ObjectFromHandle(handle);
3971                         if (hwnd != null) {
3972                                 SetIcon(hwnd, icon);
3973                         }
3974                 }
3975
3976                 internal override void SetMenu(IntPtr handle, Menu menu) {
3977                         Hwnd    hwnd;
3978
3979                         hwnd = Hwnd.ObjectFromHandle(handle);
3980                         hwnd.menu = menu;
3981
3982                         RequestNCRecalc(handle);
3983                 }
3984
3985                 internal override void SetModal(IntPtr handle, bool Modal) {
3986                         if (Modal) {
3987                                 ModalWindows.Push(handle);
3988                         } else {
3989                                 if (ModalWindows.Contains(handle)) {
3990                                         ModalWindows.Pop();
3991                                 }
3992                                 if (ModalWindows.Count > 0) {
3993                                         Activate((IntPtr)ModalWindows.Peek());
3994                                 }
3995                         }
3996                 }
3997
3998                 internal override IntPtr SetParent(IntPtr handle, IntPtr parent) {
3999                         Hwnd    hwnd;
4000
4001                         hwnd = Hwnd.ObjectFromHandle(handle);
4002                         hwnd.parent = Hwnd.ObjectFromHandle(parent);
4003
4004                         lock (XlibLock) {
4005                                 #if DriverDebug || DriverDebugParent
4006                                         Console.WriteLine("Parent for window {0} = {1}", XplatUI.Window(hwnd.Handle), XplatUI.Window(hwnd.parent != null ? hwnd.parent.Handle : IntPtr.Zero));
4007                                 #endif
4008                                 XReparentWindow(DisplayHandle, hwnd.whole_window, hwnd.parent.client_window, hwnd.x, hwnd.y);
4009                         }
4010
4011                         return IntPtr.Zero;
4012                 }
4013
4014                 internal override void SetTimer (Timer timer) {
4015                         lock (TimerList) {
4016                                 TimerList.Add(timer);
4017                         }
4018                         WakeupMain ();
4019                 }
4020
4021                 internal override bool SetTopmost(IntPtr handle, IntPtr handle_owner, bool enabled) {
4022                         Hwnd    hwnd;
4023                         Hwnd    hwnd_owner;
4024
4025                         hwnd = Hwnd.ObjectFromHandle(handle);
4026
4027                         if (handle_owner != IntPtr.Zero) {
4028                                 hwnd_owner = Hwnd.ObjectFromHandle(handle_owner);
4029                         } else {
4030                                 hwnd_owner = null;
4031                         }
4032
4033                         if (enabled) {
4034                                 lock (XlibLock) {
4035                                         if (hwnd_owner != null) {
4036                                                 XSetTransientForHint(DisplayHandle, hwnd.whole_window, hwnd_owner.whole_window);
4037                                         } else {
4038                                                 XSetTransientForHint(DisplayHandle, hwnd.whole_window, RootWindow);
4039                                         }
4040                                 }
4041                         } else {
4042                                 lock (XlibLock) {
4043                                         XDeleteProperty(DisplayHandle, hwnd.whole_window, (IntPtr)Atom.XA_WM_TRANSIENT_FOR);
4044                                 }
4045                         }
4046                         return true;
4047                 }
4048
4049                 internal override bool SetVisible(IntPtr handle, bool visible) {
4050                         Hwnd    hwnd;
4051
4052                         hwnd = Hwnd.ObjectFromHandle(handle);
4053                         hwnd.visible = visible;
4054
4055                         lock (XlibLock) {
4056                                 if (visible) {
4057                                         if (Control.FromHandle(handle) is Form) {
4058                                                 FormWindowState s;
4059
4060                                                 s = ((Form)Control.FromHandle(handle)).WindowState;
4061
4062                                                 MapWindow(hwnd, WindowType.Both);
4063
4064                                                 switch(s) {
4065                                                         case FormWindowState.Minimized: SetWindowState(handle, FormWindowState.Minimized); break;
4066                                                         case FormWindowState.Maximized: SetWindowState(handle, FormWindowState.Maximized); break;
4067                                                 }
4068
4069                                         } else {
4070                                                 MapWindow(hwnd, WindowType.Both);
4071                                         }
4072                                         SendMessage(handle, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
4073                                 } else {
4074                                         UnmapWindow(hwnd, WindowType.Whole);
4075                                 }
4076                         }
4077                         return true;
4078                 }
4079
4080                 internal override void SetWindowMinMax(IntPtr handle, Rectangle maximized, Size min, Size max) {
4081                         Hwnd            hwnd;
4082                         XSizeHints      hints;
4083
4084                         hwnd = Hwnd.ObjectFromHandle(handle);
4085                         if (hwnd == null) {
4086                                 return;
4087                         }
4088
4089                         hints = new XSizeHints();
4090                         if ((min != Size.Empty) && (min.Width > 0) && (min.Height > 0)) {
4091                                 hints.flags = (IntPtr)((int)hints.flags | (int)XSizeHintsFlags.PMinSize);
4092                                 hints.min_width = min.Width;
4093                                 hints.min_height = min.Height;
4094                         }
4095
4096                         if ((max != Size.Empty) && (max.Width > 0) && (max.Height > 0)) {
4097                                 hints.flags = (IntPtr)((int)hints.flags | (int)XSizeHintsFlags.PMaxSize);
4098                                 hints.max_width = max.Width;
4099                                 hints.max_height = max.Height;
4100                         }
4101
4102                         if (hints.flags != IntPtr.Zero) {
4103                                 XSetWMNormalHints(DisplayHandle, hwnd.whole_window, ref hints);
4104                         }
4105
4106                         if ((maximized != Rectangle.Empty) && (maximized.Width > 0) && (maximized.Height > 0)) {
4107                                 hints.flags = (IntPtr)XSizeHintsFlags.PPosition;
4108                                 hints.x = maximized.X;
4109                                 hints.y = maximized.Y;
4110                                 hints.width = maximized.Width;
4111                                 hints.height = maximized.Height;
4112
4113                                 // Metacity does not seem to follow this constraint for maximized (zoomed) windows
4114                                 XSetZoomHints(DisplayHandle, hwnd.whole_window, ref hints);
4115                         }
4116                 }
4117
4118
4119                 internal override void SetWindowPos(IntPtr handle, int x, int y, int width, int height) {
4120                         Hwnd            hwnd;
4121                         Rectangle       client_rect;
4122
4123                         hwnd = Hwnd.ObjectFromHandle(handle);
4124
4125                         // X requires a sanity check for width & height; otherwise it dies
4126                         if (hwnd.zero_sized && width > 0 && height > 0) {
4127                                 if (hwnd.visible) {
4128                                         MapWindow(hwnd, WindowType.Whole);
4129                                 }
4130                                 hwnd.zero_sized = false;
4131                         }
4132
4133                         if ((width < 1) || (height < 1)) {
4134                                 hwnd.zero_sized = true;
4135                                 UnmapWindow(hwnd, WindowType.Whole);
4136                         }
4137
4138                         client_rect = Hwnd.GetClientRectangle(hwnd.border_style, hwnd.menu, hwnd.title_style, hwnd.caption_height, hwnd.tool_caption_height, width, height);
4139
4140                         // Save a server roundtrip (and prevent a feedback loop)
4141                         if ((hwnd.x == x) && (hwnd.y == y) && 
4142                                 (hwnd.width == width) && (hwnd.height == height) &&
4143                                 (hwnd.ClientRect == client_rect)) {
4144                                 return;
4145                         }
4146
4147                         if (!hwnd.zero_sized) {
4148
4149                                 if (hwnd.fixed_size) {
4150                                         SetWindowMinMax(handle, Rectangle.Empty, new Size(width, height), new Size(width, height));
4151                                 }
4152
4153                                 lock (XlibLock) {
4154                                         XMoveResizeWindow(DisplayHandle, hwnd.whole_window, x, y, width, height);
4155                                         XMoveResizeWindow(DisplayHandle, hwnd.client_window, client_rect.X, client_rect.Y, client_rect.Width, client_rect.Height);
4156                                 }
4157                         }
4158
4159                         // Prevent an old queued ConfigureNotify from setting our width with outdated data, set it now
4160                         hwnd.width = width;
4161                         hwnd.height = height;
4162                 }
4163
4164                 internal override void SetWindowState(IntPtr handle, FormWindowState state) {
4165                         FormWindowState current_state;
4166                         Hwnd            hwnd;
4167
4168                         hwnd = Hwnd.ObjectFromHandle(handle);
4169
4170                         try {
4171                                 current_state = GetWindowState(handle);
4172                         }
4173                         catch (NotSupportedException) {
4174                                 current_state = (FormWindowState)(-1);
4175                         }
4176
4177                         if (current_state == state) {
4178                                 return;
4179                         }
4180
4181                         switch(state) {
4182                                 case FormWindowState.Normal: {
4183                                         lock (XlibLock) {
4184                                                 if (current_state == FormWindowState.Minimized) {
4185                                                         MapWindow(hwnd, WindowType.Both);
4186                                                 } else if (current_state == FormWindowState.Maximized) {
4187                                                         SendNetWMMessage(hwnd.whole_window, NetAtoms[(int)NA._NET_WM_STATE], (IntPtr)2 /* toggle */, NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_HORZ], NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_VERT]);
4188                                                 }
4189                                         }
4190                                         Activate(handle);
4191                                         return;
4192                                 }
4193
4194                                 case FormWindowState.Minimized: {
4195                                         lock (XlibLock) {
4196                                                 if (current_state == FormWindowState.Maximized) {
4197                                                         SendNetWMMessage(hwnd.whole_window, NetAtoms[(int)NA._NET_WM_STATE], (IntPtr)2 /* toggle */, NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_HORZ], NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_VERT]);
4198                                                 }
4199                                                 XIconifyWindow(DisplayHandle, hwnd.whole_window, ScreenNo);
4200                                         }
4201                                         return;
4202                                 }
4203
4204                                 case FormWindowState.Maximized: {
4205                                         lock (XlibLock) {
4206                                                 if (current_state == FormWindowState.Minimized) {
4207                                                         MapWindow(hwnd, WindowType.Both);
4208                                                 }
4209
4210                                                 SendNetWMMessage(hwnd.whole_window, NetAtoms[(int)NA._NET_WM_STATE], (IntPtr)1 /* Add */, NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_HORZ], NetAtoms[(int)NA._NET_WM_STATE_MAXIMIZED_VERT]);
4211                                         }
4212                                         Activate(handle);
4213                                         return;
4214                                 }
4215                         }
4216                 }
4217
4218                 internal override void SetWindowStyle(IntPtr handle, CreateParams cp) {
4219                         Hwnd    hwnd;
4220
4221                         hwnd = Hwnd.ObjectFromHandle(handle);
4222                         SetHwndStyles(hwnd, cp);
4223                         SetWMStyles(hwnd, cp);
4224                 }
4225
4226                 internal override void SetWindowTransparency(IntPtr handle, double transparency, Color key) {
4227                         Hwnd    hwnd;
4228                         IntPtr  opacity;
4229
4230                         hwnd = Hwnd.ObjectFromHandle(handle);
4231
4232                         if (hwnd == null) {
4233                                 return;
4234                         }
4235
4236                         hwnd.opacity = (uint)(0xffffffff * transparency);
4237                         opacity = (IntPtr)hwnd.opacity;
4238
4239                         if (hwnd.reparented) {
4240                                 XChangeProperty(DisplayHandle, XGetParent(hwnd.whole_window), NetAtoms[(int)NA._NET_WM_WINDOW_OPACITY], (IntPtr)Atom.XA_CARDINAL, 32, PropertyMode.Replace, ref opacity, 1);
4241                         }
4242                 }
4243
4244                 internal override bool SetZOrder(IntPtr handle, IntPtr after_handle, bool top, bool bottom) {
4245                         Hwnd    hwnd = Hwnd.ObjectFromHandle(handle);
4246
4247                         if (top) {
4248                                 lock (XlibLock) {
4249                                         XRaiseWindow(DisplayHandle, hwnd.whole_window);
4250                                 }
4251                                 return true;
4252                         } else if (!bottom) {
4253                                 Hwnd    after_hwnd = null;
4254
4255                                 if (after_handle != IntPtr.Zero) {
4256                                         after_hwnd = Hwnd.ObjectFromHandle(after_handle);
4257                                 }
4258
4259                                 XWindowChanges  values = new XWindowChanges();
4260
4261                                 if (after_hwnd == null) {
4262                                         throw new ArgumentNullException("after_handle", "Need sibling to adjust z-order");
4263                                 }
4264                                 values.sibling = after_hwnd.whole_window;
4265                                 values.stack_mode = StackMode.Below;
4266
4267                                 lock (XlibLock) {
4268                                         XConfigureWindow(DisplayHandle, hwnd.whole_window, ChangeWindowFlags.CWStackMode | ChangeWindowFlags.CWSibling, ref values);
4269                                 }
4270                         } else {
4271                                 // Bottom
4272                                 lock (XlibLock) {
4273                                         XLowerWindow(DisplayHandle, hwnd.whole_window);
4274                                 }
4275                                 return true;
4276                         }
4277                         return false;
4278                 }
4279
4280                 internal override void ShowCursor(bool show) {
4281                         ;       // FIXME - X11 doesn't 'hide' the cursor. we could create an empty cursor
4282                 }
4283
4284                 internal override object StartLoop(Thread thread) {
4285                         return (Object) ThreadQueue(thread);
4286                 }
4287
4288                 internal override bool SupportsTransparency() {
4289                         // We need to check if the x compositing manager is running
4290                         return true;
4291                 }
4292
4293                 internal override bool SystrayAdd(IntPtr handle, string tip, Icon icon, out ToolTip tt) {
4294                         GetSystrayManagerWindow();
4295
4296                         if (SystrayMgrWindow != IntPtr.Zero) {
4297                                 XSizeHints      size_hints;
4298                                 Hwnd            hwnd;
4299
4300                                 hwnd = Hwnd.ObjectFromHandle(handle);
4301                                 #if DriverDebug
4302                                         Console.WriteLine("Adding Systray Whole:{0:X}, Client:{1:X}", hwnd.whole_window.ToInt32(), hwnd.client_window.ToInt32());
4303                                 #endif
4304
4305                                 UnmapWindow(hwnd, WindowType.Whole);
4306
4307                                 // Oh boy.
4308                                 XDestroyWindow(DisplayHandle, hwnd.client_window);
4309                                 hwnd.client_window = hwnd.whole_window;
4310
4311                                 size_hints = new XSizeHints();
4312
4313                                 size_hints.flags = (IntPtr)(XSizeHintsFlags.PMinSize | XSizeHintsFlags.PMaxSize | XSizeHintsFlags.PBaseSize);
4314                                 size_hints.min_width = icon.Width;
4315                                 size_hints.min_height = icon.Height;
4316
4317                                 size_hints.max_width = icon.Width;
4318                                 size_hints.max_height = icon.Height;
4319
4320                                 size_hints.base_width = icon.Width;
4321                                 size_hints.base_height = icon.Height;
4322                                 XSetWMNormalHints(DisplayHandle, hwnd.whole_window, ref size_hints);
4323
4324                                 int[] atoms = new int[2];
4325                                 atoms [0] = 1;                  // Version 1
4326                                 atoms [1] = 0;                  // We're not mapped
4327
4328                                 // This line cost me 3 days...
4329                                 XChangeProperty(DisplayHandle, hwnd.whole_window, NetAtoms[(int)NA._XEMBED_INFO], NetAtoms[(int)NA._XEMBED_INFO], 32, PropertyMode.Replace, atoms, 2);
4330
4331                                 // Need to pick some reasonable defaults
4332                                 tt = new ToolTip();
4333                                 tt.AutomaticDelay = 100;
4334                                 tt.InitialDelay = 250;
4335                                 tt.ReshowDelay = 250;
4336                                 tt.ShowAlways = true;
4337
4338                                 if ((tip != null) && (tip != string.Empty)) {
4339                                         tt.SetToolTip(Control.FromHandle(handle), tip);
4340                                         tt.Active = true;
4341                                 } else {
4342                                         tt.Active = false;
4343                                 }
4344
4345                                 // Make sure the window exists
4346                                 XSync(DisplayHandle, hwnd.whole_window);
4347
4348                                 SendNetClientMessage(SystrayMgrWindow, NetAtoms[(int)NA._NET_SYSTEM_TRAY_OPCODE], IntPtr.Zero, (IntPtr)SystrayRequest.SYSTEM_TRAY_REQUEST_DOCK, hwnd.whole_window);
4349                                 return true;
4350                         }
4351                         tt = null;
4352                         return false;
4353                 }
4354
4355                 internal override bool SystrayChange(IntPtr handle, string tip, Icon icon, ref ToolTip tt) {
4356                         Control control;
4357
4358                         control = Control.FromHandle(handle);
4359                         if (control != null && tt != null) {
4360                                 tt.SetToolTip(control, tip);
4361                                 tt.Active = true;
4362                                 return true;
4363                         } else {
4364                                 return false;
4365                         }
4366                 }
4367
4368                 internal override void SystrayRemove(IntPtr handle, ref ToolTip tt) {
4369                         Hwnd    hwnd;
4370
4371                         hwnd = Hwnd.ObjectFromHandle(handle);
4372
4373                         UnmapWindow(hwnd, WindowType.Whole);
4374                         SetParent(hwnd.whole_window, FosterParent);
4375
4376                         // The caller can now re-dock it later...
4377                         if (tt != null) {
4378                                 tt.Dispose();
4379                                 tt = null;
4380                         }
4381                 }
4382
4383                 internal override bool Text(IntPtr handle, string text) {
4384                         lock (XlibLock) {
4385                                 // FIXME - use _NET properties
4386                                 XStoreName(DisplayHandle, Hwnd.ObjectFromHandle(handle).whole_window, text);
4387                         }
4388                         return true;
4389                 }
4390
4391                 internal override bool TranslateMessage(ref MSG msg) {
4392                         return Keyboard.TranslateMessage (ref msg);
4393                 }
4394
4395                 internal override void UpdateWindow(IntPtr handle) {
4396                         Hwnd    hwnd;
4397
4398                         hwnd = Hwnd.ObjectFromHandle(handle);
4399
4400                         if (!hwnd.visible || !hwnd.expose_pending) {
4401                                 return;
4402                         }
4403
4404                         SendMessage(handle, Msg.WM_PAINT, IntPtr.Zero, IntPtr.Zero);
4405                         hwnd.Queue.Paint.Remove(hwnd);
4406                 }
4407
4408                 private bool WindowIsMapped(IntPtr handle) {
4409                         XWindowAttributes attributes;
4410
4411                         attributes = new XWindowAttributes();
4412                         XGetWindowAttributes(DisplayHandle, handle, ref attributes);
4413                         if (attributes.map_state == MapState.IsUnmapped) {
4414                                 return false;
4415                         }
4416                         return true;
4417                 }
4418
4419                 #endregion      // Public Static Methods
4420
4421                 #region Events
4422                 internal override event EventHandler Idle;
4423                 #endregion      // Events
4424
4425                 #region X11 Imports
4426                 [DllImport ("libX11", EntryPoint="XOpenDisplay")]
4427                 internal extern static IntPtr XOpenDisplay(IntPtr display);
4428                 [DllImport ("libX11", EntryPoint="XCloseDisplay")]
4429                 internal extern static int XCloseDisplay(IntPtr display);                                                   
4430                 [DllImport ("libX11", EntryPoint="XSynchronize")]
4431                 internal extern static IntPtr XSynchronize(IntPtr display, bool onoff);
4432
4433                 [DllImport ("libX11", EntryPoint="XCreateWindow")]
4434                 internal extern static IntPtr XCreateWindow(IntPtr display, IntPtr parent, int x, int y, int width, int height, int border_width, int depth, int xclass, IntPtr visual, UIntPtr valuemask, ref XSetWindowAttributes attributes);
4435                 [DllImport ("libX11", EntryPoint="XCreateSimpleWindow")]
4436                 internal extern static IntPtr XCreateSimpleWindow(IntPtr display, IntPtr parent, int x, int y, int width, int height, int border_width, UIntPtr border, UIntPtr background);
4437                 [DllImport ("libX11", EntryPoint="XMapWindow")]
4438                 internal extern static int XMapWindow(IntPtr display, IntPtr window);
4439                 [DllImport ("libX11", EntryPoint="XUnmapWindow")]
4440                 internal extern static int XUnmapWindow(IntPtr display, IntPtr window);
4441                 [DllImport ("libX11", EntryPoint="XMapSubwindows")]
4442                 internal extern static int XMapSubindows(IntPtr display, IntPtr window);
4443                 [DllImport ("libX11", EntryPoint="XUnmapSubwindows")]
4444                 internal extern static int XUnmapSubwindows(IntPtr display, IntPtr window);
4445                 [DllImport ("libX11", EntryPoint="XRootWindow")]
4446                 internal extern static IntPtr XRootWindow(IntPtr display, int screen_number);
4447                 [DllImport ("libX11", EntryPoint="XNextEvent")]
4448                 internal extern static IntPtr XNextEvent(IntPtr display, ref XEvent xevent);
4449                 [DllImport ("libX11")]
4450                 internal extern static int XConnectionNumber (IntPtr diplay);
4451                 [DllImport ("libX11")]
4452                 internal extern static int XPending (IntPtr diplay);
4453                 [DllImport ("libX11", EntryPoint="XSelectInput")]
4454                 internal extern static IntPtr XSelectInput(IntPtr display, IntPtr window, IntPtr mask);
4455
4456                 [DllImport ("libX11", EntryPoint="XDestroyWindow")]
4457                 internal extern static int XDestroyWindow(IntPtr display, IntPtr window);
4458
4459                 [DllImport ("libX11", EntryPoint="XReparentWindow")]
4460                 internal extern static int XReparentWindow(IntPtr display, IntPtr window, IntPtr parent, int x, int y);
4461                 [DllImport ("libX11", EntryPoint="XMoveResizeWindow")]
4462                 internal extern static int XMoveResizeWindow(IntPtr display, IntPtr window, int x, int y, int width, int height);
4463
4464                 [DllImport ("libX11", EntryPoint="XResizeWindow")]
4465                 internal extern static int XResizeWindow(IntPtr display, IntPtr window, int width, int height);
4466
4467                 [DllImport ("libX11", EntryPoint="XGetWindowAttributes")]
4468                 internal extern static int XGetWindowAttributes(IntPtr display, IntPtr window, ref XWindowAttributes attributes);
4469
4470                 [DllImport ("libX11", EntryPoint="XFlush")]
4471                 internal extern static int XFlush(IntPtr display);
4472
4473                 [DllImport ("libX11", EntryPoint="XSetWMName")]
4474                 internal extern static int XSetWMName(IntPtr display, IntPtr window, ref XTextProperty text_prop);
4475
4476                 [DllImport ("libX11", EntryPoint="XStoreName")]
4477                 internal extern static int XStoreName(IntPtr display, IntPtr window, string window_name);
4478
4479                 [DllImport ("libX11", EntryPoint="XFetchName")]
4480                 internal extern static int XFetchName(IntPtr display, IntPtr window, ref IntPtr window_name);
4481
4482                 [DllImport ("libX11", EntryPoint="XSendEvent")]
4483                 internal extern static int XSendEvent(IntPtr display, IntPtr window, bool propagate, IntPtr event_mask, ref XEvent send_event);
4484
4485                 [DllImport ("libX11", EntryPoint="XQueryTree")]
4486                 internal extern static int XQueryTree(IntPtr display, IntPtr window, out IntPtr root_return, out IntPtr parent_return, out IntPtr children_return, out int nchildren_return);
4487
4488                 [DllImport ("libX11", EntryPoint="XFree")]
4489                 internal extern static int XFree(IntPtr data);
4490
4491                 [DllImport ("libX11", EntryPoint="XRaiseWindow")]
4492                 internal extern static int XRaiseWindow(IntPtr display, IntPtr window);
4493
4494                 [DllImport ("libX11", EntryPoint="XLowerWindow")]
4495                 internal extern static uint XLowerWindow(IntPtr display, IntPtr window);
4496
4497                 [DllImport ("libX11", EntryPoint="XConfigureWindow")]
4498                 internal extern static uint XConfigureWindow(IntPtr display, IntPtr window, ChangeWindowFlags value_mask, ref XWindowChanges values);
4499
4500                 [DllImport ("libX11", EntryPoint="XInternAtom")]
4501                 internal extern static IntPtr XInternAtom(IntPtr display, string atom_name, bool only_if_exists);
4502
4503                 [DllImport ("libX11", EntryPoint="XSetWMProtocols")]
4504                 internal extern static int XSetWMProtocols(IntPtr display, IntPtr window, IntPtr[] protocols, int count);
4505
4506                 [DllImport ("libX11", EntryPoint="XGrabPointer")]
4507                 internal extern static int XGrabPointer(IntPtr display, IntPtr window, bool owner_events, EventMask event_mask, GrabMode pointer_mode, GrabMode keyboard_mode, IntPtr confine_to, IntPtr cursor, IntPtr timestamp);
4508
4509                 [DllImport ("libX11", EntryPoint="XUngrabPointer")]
4510                 internal extern static int XUngrabPointer(IntPtr display, IntPtr timestamp);
4511
4512                 [DllImport ("libX11", EntryPoint="XQueryPointer")]
4513                 internal extern static bool XQueryPointer(IntPtr display, IntPtr window, out IntPtr root, out IntPtr child, out int root_x, out int root_y, out int win_x, out int win_y, out int keys_buttons);
4514
4515                 [DllImport ("libX11", EntryPoint="XTranslateCoordinates")]
4516                 internal extern static bool XTranslateCoordinates (IntPtr display, IntPtr src_w, IntPtr dest_w, int src_x, int src_y, out int intdest_x_return,  out int dest_y_return, out IntPtr child_return);
4517
4518                 [DllImport ("libX11", EntryPoint="XGetGeometry")]
4519                 internal extern static bool XGetGeometry(IntPtr display, IntPtr window, out IntPtr root, out int x, out int y, out int width, out int height, out int border_width, out int depth);
4520
4521                 [DllImport ("libX11", EntryPoint="XGetGeometry")]
4522                 internal extern static bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, out int x, out int y, out int width, out int height, IntPtr border_width, IntPtr depth);
4523
4524                 [DllImport ("libX11", EntryPoint="XGetGeometry")]
4525                 internal extern static bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, out int x, out int y, IntPtr width, IntPtr height, IntPtr border_width, IntPtr depth);
4526
4527                 [DllImport ("libX11", EntryPoint="XGetGeometry")]
4528                 internal extern static bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, IntPtr x, IntPtr y, out int width, out int height, IntPtr border_width, IntPtr depth);
4529
4530                 [DllImport ("libX11", EntryPoint="XWarpPointer")]
4531                 internal extern static uint XWarpPointer(IntPtr display, IntPtr src_w, IntPtr dest_w, int src_x, int src_y, uint src_width, uint src_height, int dest_x, int dest_y);
4532
4533                 [DllImport ("libX11", EntryPoint="XClearWindow")]
4534                 internal extern static int XClearWindow(IntPtr display, IntPtr window);
4535
4536                 [DllImport ("libX11", EntryPoint="XClearArea")]
4537                 internal extern static int XClearArea(IntPtr display, IntPtr window, int x, int y, int width, int height, bool exposures);
4538
4539                 // Colormaps
4540                 [DllImport ("libX11", EntryPoint="XDefaultScreenOfDisplay")]
4541                 internal extern static IntPtr XDefaultScreenOfDisplay(IntPtr display);
4542
4543                 [DllImport ("libX11", EntryPoint="XScreenNumberOfScreen")]
4544                 internal extern static int XScreenNumberOfScreen(IntPtr display, IntPtr Screen);
4545
4546                 [DllImport ("libX11", EntryPoint="XDefaultVisual")]
4547                 internal extern static IntPtr XDefaultVisual(IntPtr display, int screen_number);
4548
4549                 [DllImport ("libX11", EntryPoint="XDefaultDepth")]
4550                 internal extern static uint XDefaultDepth(IntPtr display, int screen_number);
4551
4552                 [DllImport ("libX11", EntryPoint="XDefaultScreen")]
4553                 internal extern static int XDefaultScreen(IntPtr display);
4554
4555                 [DllImport ("libX11", EntryPoint="XDefaultColormap")]
4556                 internal extern static IntPtr XDefaultColormap(IntPtr display, int screen_number);
4557
4558                 [DllImport ("libX11", EntryPoint="XLookupColor")]
4559                 internal extern static int XLookupColor(IntPtr display, IntPtr Colormap, string Coloranem, ref XColor exact_def_color, ref XColor screen_def_color);
4560
4561                 [DllImport ("libX11", EntryPoint="XAllocColor")]
4562                 internal extern static int XAllocColor(IntPtr display, IntPtr Colormap, ref XColor colorcell_def);
4563
4564                 [DllImport ("libX11", EntryPoint="XSetTransientForHint")]
4565                 internal extern static int XSetTransientForHint(IntPtr display, IntPtr window, IntPtr prop_window);
4566
4567                 [DllImport ("libX11", EntryPoint="XChangeProperty")]
4568                 internal extern static int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, ref MotifWmHints data, int nelements);
4569
4570                 [DllImport ("libX11", EntryPoint="XChangeProperty")]
4571                 internal extern static int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, ref uint value, int nelements);
4572
4573                 [DllImport ("libX11", EntryPoint="XChangeProperty")]
4574                 internal extern static int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, ref IntPtr value, int nelements);
4575
4576                 [DllImport ("libX11", EntryPoint="XChangeProperty")]
4577                 internal extern static int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, uint[] data, int nelements);
4578
4579                 [DllImport ("libX11", EntryPoint="XChangeProperty")]
4580                 internal extern static int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, int[] data, int nelements);
4581
4582                 [DllImport ("libX11", EntryPoint="XChangeProperty")]
4583                 internal extern static int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, IntPtr[] data, int nelements);
4584
4585                 [DllImport ("libX11", EntryPoint="XChangeProperty")]
4586                 internal extern static int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, IntPtr atoms, int nelements);
4587
4588                 [DllImport ("libX11", EntryPoint="XChangeProperty", CharSet=CharSet.Ansi)]
4589                 internal extern static int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, string text, int text_length);
4590
4591                 [DllImport ("libX11", EntryPoint="XDeleteProperty")]
4592                 internal extern static int XDeleteProperty(IntPtr display, IntPtr window, IntPtr property);
4593
4594                 [DllImport ("gdiplus", EntryPoint="GetFontMetrics")]
4595                 internal extern static bool GetFontMetrics(IntPtr graphicsObject, IntPtr nativeObject, out int ascent, out int descent);
4596
4597                 // Drawing
4598                 [DllImport ("libX11", EntryPoint="XCreateGC")]
4599                 internal extern static IntPtr XCreateGC(IntPtr display, IntPtr window, IntPtr valuemask, ref XGCValues values);
4600
4601                 [DllImport ("libX11", EntryPoint="XFreeGC")]
4602                 internal extern static int XFreeGC(IntPtr display, IntPtr gc);
4603
4604                 [DllImport ("libX11", EntryPoint="XSetFunction")]
4605                 internal extern static int XSetFunction(IntPtr display, IntPtr gc, GXFunction function);
4606
4607                 [DllImport ("libX11", EntryPoint="XDrawLine")]
4608                 internal extern static int XDrawLine(IntPtr display, IntPtr drawable, IntPtr gc, int x1, int y1, int x2, int y2);
4609
4610                 [DllImport ("libX11", EntryPoint="XDrawRectangle")]
4611                 internal extern static int XDrawRectangle(IntPtr display, IntPtr drawable, IntPtr gc, int x1, int y1, int width, int height);
4612
4613                 [DllImport ("libX11", EntryPoint="XSetWindowBackground")]
4614                 internal extern static int XSetWindowBackground(IntPtr display, IntPtr window, IntPtr background);
4615
4616                 [DllImport ("libX11", EntryPoint="XCopyArea")]
4617                 internal extern static int XCopyArea(IntPtr display, IntPtr src, IntPtr dest, IntPtr gc, int src_x, int src_y, int width, int height, int dest_x, int dest_y);
4618
4619                 [DllImport ("libX11", EntryPoint="XGetWindowProperty")]
4620                 internal extern static int XGetWindowProperty(IntPtr display, IntPtr window, IntPtr atom, IntPtr long_offset, IntPtr long_length, bool delete, IntPtr req_type, out IntPtr actual_type, out int actual_format, out IntPtr nitems, out IntPtr bytes_after, ref IntPtr prop);
4621
4622                 [DllImport ("libX11", EntryPoint="XSetInputFocus")]
4623                 internal extern static int XSetInputFocus(IntPtr display, IntPtr window, RevertTo revert_to, IntPtr time);
4624
4625                 [DllImport ("libX11", EntryPoint="XIconifyWindow")]
4626                 internal extern static int XIconifyWindow(IntPtr display, IntPtr window, int screen_number);
4627
4628                 [DllImport ("libX11", EntryPoint="XDefineCursor")]
4629                 internal extern static int XDefineCursor(IntPtr display, IntPtr window, IntPtr cursor);
4630
4631                 [DllImport ("libX11", EntryPoint="XUndefineCursor")]
4632                 internal extern static int XUndefineCursor(IntPtr display, IntPtr window);
4633
4634                 [DllImport ("libX11", EntryPoint="XFreeCursor")]
4635                 internal extern static int XFreeCursor(IntPtr display, IntPtr cursor);
4636
4637                 [DllImport ("libX11", EntryPoint="XCreateFontCursor")]
4638                 internal extern static IntPtr XCreateFontCursor(IntPtr display, CursorFontShape shape);
4639
4640                 [DllImport ("libX11", EntryPoint="XCreatePixmapCursor")]
4641                 internal extern static IntPtr XCreatePixmapCursor(IntPtr display, IntPtr source, IntPtr mask, ref XColor foreground_color, ref XColor background_color, int x_hot, int y_hot);
4642
4643                 [DllImport ("libX11", EntryPoint="XCreatePixmapFromBitmapData")]
4644                 internal extern static IntPtr XCreatePixmapFromBitmapData(IntPtr display, IntPtr drawable, byte[] data, int width, int height, IntPtr fg, IntPtr bg, int depth);
4645
4646                 [DllImport ("libX11", EntryPoint="XFreePixmap")]
4647                 internal extern static IntPtr XFreePixmap(IntPtr display, IntPtr pixmap);
4648
4649                 [DllImport ("libX11", EntryPoint="XQueryBestCursor")]
4650                 internal extern static int XQueryBestCursor(IntPtr display, IntPtr drawable, int width, int height, out int best_width, out int best_height);
4651
4652                 [DllImport ("libX11", EntryPoint="XWhitePixel")]
4653                 internal extern static IntPtr XWhitePixel(IntPtr display, int screen_no);
4654
4655                 [DllImport ("libX11", EntryPoint="XBlackPixel")]
4656                 internal extern static IntPtr XBlackPixel(IntPtr display, int screen_no);
4657
4658                 [DllImport ("libX11", EntryPoint="XGrabServer")]
4659                 internal extern static void XGrabServer(IntPtr display);
4660
4661                 [DllImport ("libX11", EntryPoint="XUngrabServer")]
4662                 internal extern static void XUngrabServer(IntPtr display);
4663
4664                 [DllImport ("libX11", EntryPoint="XSetWMNormalHints")]
4665                 internal extern static void XSetWMNormalHints(IntPtr display, IntPtr window, ref XSizeHints hints);
4666
4667                 [DllImport ("libX11", EntryPoint="XSetZoomHints")]
4668                 internal extern static void XSetZoomHints(IntPtr display, IntPtr window, ref XSizeHints hints);
4669
4670                 [DllImport ("libX11", EntryPoint="XSetWMHints")]
4671                 internal extern static void XSetWMHints(IntPtr display, IntPtr window, ref XWMHints wmhints);
4672
4673                 [DllImport ("libX11", EntryPoint="XSync")]
4674                 internal extern static void XSync(IntPtr display, IntPtr window);
4675
4676                 [DllImport ("libX11", EntryPoint="XGetIconSizes")]
4677                 internal extern static int XGetIconSizes(IntPtr display, IntPtr window, out IntPtr size_list, out int count);
4678
4679                 [DllImport ("libX11", EntryPoint="XSetErrorHandler")]
4680                 internal extern static IntPtr XSetErrorHandler(XErrorHandler error_handler);
4681
4682                 [DllImport ("libX11", EntryPoint="XGetErrorText")]
4683                 internal extern static IntPtr XGetErrorText(IntPtr display, byte code, StringBuilder buffer, int length);
4684
4685                 [DllImport ("libX11", EntryPoint="XInitThreads")]
4686                 internal extern static int XInitThreads();
4687
4688                 [DllImport ("libX11", EntryPoint="XConvertSelection")]
4689                 internal extern static int XConvertSelection(IntPtr display, IntPtr selection, IntPtr target, IntPtr property, IntPtr requestor, IntPtr time);
4690
4691                 [DllImport ("libX11", EntryPoint="XGetSelectionOwner")]
4692                 internal extern static IntPtr XGetSelectionOwner(IntPtr display, IntPtr selection);
4693
4694                 [DllImport ("libX11", EntryPoint="XSetSelectionOwner")]
4695                 internal extern static int XSetSelectionOwner(IntPtr display, IntPtr selection, IntPtr owner, IntPtr time);
4696
4697                 [DllImport ("libX11", EntryPoint="XSetPlaneMask")]
4698                 internal extern static int XSetPlaneMask(IntPtr display, IntPtr gc, IntPtr mask);
4699
4700                 [DllImport ("libX11", EntryPoint="XSetForeground")]
4701                 internal extern static int XSetForeground(IntPtr display, IntPtr gc, UIntPtr foreground);
4702
4703                 [DllImport ("libX11", EntryPoint="XSetBackground")]
4704                 internal extern static int XSetBackground(IntPtr display, IntPtr gc, UIntPtr background);
4705
4706                 [DllImport ("libX11", EntryPoint="XBell")]
4707                 internal extern static int XBell(IntPtr display, int percent);
4708
4709                 [DllImport ("libX11", EntryPoint="XChangeActivePointerGrab")]
4710                 internal extern static int XChangeActivePointerGrab (IntPtr display, EventMask event_mask, IntPtr cursor, IntPtr time);
4711
4712                 [DllImport ("libX11", EntryPoint="XFilterEvent")]
4713                 internal extern static bool XFilterEvent(ref XEvent xevent, IntPtr window);
4714                 #endregion
4715         }
4716 }