New test.
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms.X11Internal / X11Display.cs
1 // a copy of this software and associated documentation files (the
2 // "Software"), to deal in the Software without restriction, including
3 // without limitation the rights to use, copy, modify, merge, publish,
4 // distribute, sublicense, and/or sell copies of the Software, and to
5 // permit persons to whom the Software is furnished to do so, subject to
6 // the following conditions:
7 // 
8 // The above copyright notice and this permission notice shall be
9 // included in all copies or substantial portions of the Software.
10 // 
11 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
15 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
16 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
17 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18 //
19 // Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
20 //
21 //
22
23 using System;
24 using System.Collections;
25 using System.Diagnostics;
26 using System.Drawing;
27 using System.Drawing.Drawing2D;
28 using System.Drawing.Imaging;
29 using System.IO;
30 using System.Net;
31 using System.Net.Sockets;
32 using System.Reflection;
33 using System.Runtime.InteropServices;
34 using System.Text;
35 using System.Threading;
36 using System.Windows.Forms;
37 // Only do the poll when building with mono for now
38 #if __MonoCS__
39 using Mono.Unix.Native;
40 #endif
41
42 namespace System.Windows.Forms.X11Internal {
43
44         internal class X11Display {
45
46                 IntPtr display; /* our X handle */
47
48                 // XXX internal because X11Hwnd needs them
49                 internal IntPtr CustomVisual;    // Visual for window creation
50                 internal IntPtr CustomColormap;  // Colormap for window creation
51
52                 X11Keyboard Keyboard;
53                 internal X11Dnd Dnd; // XXX X11Hwnd needs it to enable Dnd
54                 bool detectable_key_auto_repeat;
55
56                 X11Atoms atoms;
57                 X11RootHwnd root_hwnd;
58                 X11Hwnd foster_hwnd;
59
60                 // Clipboard
61                 IntPtr          ClipMagic;
62                 ClipboardStruct Clipboard; // Our clipboard
63
64                 // Focus tracking
65                 internal X11Hwnd ActiveWindow;
66                 X11Hwnd FocusWindow;
67
68                 // Modality support
69                 Stack ModalWindows; // Stack of our modal windows
70
71                 // Caret
72                 CaretStruct Caret;
73
74                 // mouse hover message generation
75                 // XXX internal because X11Atoms needs to access it..
76                 internal HoverStruct HoverState;
77
78                 // double click message generation
79                 ClickStruct ClickPending;
80                 int DoubleClickInterval; // msec; max interval between clicks to count as double click
81
82                 // Support for mouse grab
83                 GrabStruct Grab;
84
85                 // Cursors
86                 IntPtr LastCursorWindow; // The last window we set the cursor on
87                 IntPtr LastCursorHandle; // The handle that was last set on LastCursorWindow
88                 IntPtr OverrideCursorHandle; // The cursor that is set to override any other cursors
89
90                 // State
91                 Point MousePosition;     // Last position of mouse, in screen coords
92                 MouseButtons MouseState; // Last state of mouse buttons
93
94                 XErrorHandler   ErrorHandler;           // Error handler delegate
95                 bool            ErrorExceptions;        // Throw exceptions on X errors
96
97                 Thread event_thread; // the background thread that just watches our X socket
98
99 #if __MonoCS__
100                 Pollfd[] pollfds;
101 #endif
102
103                 public X11Display (IntPtr display)
104                 {
105                         if (display == IntPtr.Zero) {
106                                 throw new ArgumentNullException("Display",
107                                                         "Could not open display (X-Server required. Check you DISPLAY environment variable)");
108                         }
109
110                         this.display = display;
111
112                         // Debugging support
113                         if (Environment.GetEnvironmentVariable ("MONO_XSYNC") != null) {
114                                 Xlib.XSynchronize (display, true);
115                         }
116
117                         if (Environment.GetEnvironmentVariable ("MONO_XEXCEPTIONS") != null) {
118                                 ErrorExceptions = true;
119                         }
120
121                         atoms = new X11Atoms (this);
122
123                         DoubleClickInterval = 500;
124
125                         HoverState.Interval = 500;
126                         HoverState.Timer = new Timer();
127                         HoverState.Timer.Enabled = false;
128                         HoverState.Timer.Interval = HoverState.Interval;
129                         HoverState.Timer.Tick += new EventHandler(MouseHover);
130                         HoverState.Size = new Size(4, 4);
131                         HoverState.X = -1;
132                         HoverState.Y = -1;
133
134                         ActiveWindow = null;
135                         FocusWindow = null;
136                         ModalWindows = new Stack(3);
137
138                         MouseState = MouseButtons.None;
139                         MousePosition = new Point(0, 0);
140
141                         Caret.Timer = new Timer();
142                         Caret.Timer.Interval = 500;             // FIXME - where should this number come from?
143                         Caret.Timer.Tick += new EventHandler(CaretCallback);
144
145                         // XXX multiscreen work here
146                         root_hwnd = new X11RootHwnd (this, Xlib.XRootWindow (display, DefaultScreen));
147
148                         // XXX do we need a per-screen foster parent?
149                         // Create the foster parent
150                         foster_hwnd = new X11Hwnd (this,
151                                                    Xlib.XCreateSimpleWindow (display, root_hwnd.WholeWindow,
152                                                                              0, 0, 1, 1, 4, UIntPtr.Zero, UIntPtr.Zero));
153
154 #if __MonoCS__
155                         pollfds = new Pollfd [1];
156                         pollfds [0] = new Pollfd ();
157                         pollfds [0].fd = Xlib.XConnectionNumber (display);
158                         pollfds [0].events = PollEvents.POLLIN;
159 #endif
160
161                         Keyboard = new X11Keyboard(display, foster_hwnd.Handle);
162                         Dnd = new X11Dnd (display);
163
164                         ErrorExceptions = false;
165
166                         // Handle any upcoming errors
167                         ErrorHandler = new XErrorHandler (HandleError);
168                         Xlib.XSetErrorHandler (ErrorHandler);
169
170                         X11DesktopColors.Initialize(); // XXX we need to figure out how to make this display specific?
171
172                         // Disable keyboard autorepeat
173                         try {
174                                 Xlib.XkbSetDetectableAutoRepeat (display, true, IntPtr.Zero);
175                                 detectable_key_auto_repeat = true;
176                         } catch {
177                                 Console.Error.WriteLine ("Could not disable keyboard auto repeat, will attempt to disable manually.");
178                                 detectable_key_auto_repeat = false;
179                         }
180
181                         // we re-set our error handler here, X11DesktopColor stuff might have stolen it (gtk does)
182                         Xlib.XSetErrorHandler (ErrorHandler);
183
184                         // create our event thread (just sits on the X socket waiting for events)
185                         event_thread = new Thread (new ThreadStart (XEventThread));
186                         event_thread.IsBackground = true;
187                         event_thread.Start ();
188                 }
189
190                 #region Callbacks
191                 private void MouseHover(object sender, EventArgs e)
192                 {
193                         HoverState.Timer.Enabled = false;
194
195                         if (HoverState.Window != IntPtr.Zero) {
196                                 X11Hwnd hwnd = (X11Hwnd)Hwnd.GetObjectFromWindow (HoverState.Window);
197                                 if (hwnd != null) {
198                                         XEvent xevent = new XEvent ();
199
200                                         xevent.type = XEventName.ClientMessage;
201                                         xevent.ClientMessageEvent.display = display;
202                                         xevent.ClientMessageEvent.window = HoverState.Window;
203                                         xevent.ClientMessageEvent.message_type = HoverState.Atom;
204                                         xevent.ClientMessageEvent.format = 32;
205                                         xevent.ClientMessageEvent.ptr1 = (IntPtr) (HoverState.Y << 16 | HoverState.X);
206
207                                         hwnd.Queue.Enqueue (xevent);
208                                 }
209                         }
210                 }
211
212                 private void CaretCallback (object sender, EventArgs e)
213                 {
214                         if (Caret.Paused) {
215                                 return;
216                         }
217                         Caret.On = !Caret.On;
218
219                         Xlib.XDrawLine (display, Caret.Hwnd, Caret.gc, Caret.X, Caret.Y, Caret.X, Caret.Y + Caret.Height);
220                 }
221
222                 internal string WhereString ()
223                 {
224                         StackTrace      stack;
225                         StackFrame      frame;
226                         string          newline;
227                         string          unknown;
228                         StringBuilder   sb;
229                         MethodBase      method;
230
231                         newline = String.Format("{0}\t {1} ", Environment.NewLine, Locale.GetText("at"));
232                         unknown = Locale.GetText("<unknown method>");
233                         sb = new StringBuilder();
234                         stack = new StackTrace(true);
235
236                         for (int i = 0; i < stack.FrameCount; i++) {
237                                 frame = stack.GetFrame (i);
238                                 sb.Append(newline);
239
240                                 method = frame.GetMethod();
241                                 if (method != null) {
242                                         if (frame.GetFileLineNumber() != 0)
243                                                 sb.AppendFormat ("{0}.{1} () [{2}:{3}]",
244                                                                  method.DeclaringType.FullName, method.Name,
245                                                                  Path.GetFileName(frame.GetFileName()), frame.GetFileLineNumber());
246                                         else
247                                                 sb.AppendFormat ("{0}.{1} ()", method.DeclaringType.FullName, method.Name);
248                                 } else { 
249                                         sb.Append(unknown);
250                                 }
251                         }
252                         return sb.ToString();
253                 }
254
255                 private int HandleError (IntPtr display, ref XErrorEvent error_event)
256                 {
257                         if (ErrorExceptions)
258                                 throw new X11Exception (error_event.display, error_event.resourceid,
259                                                         error_event.serial, error_event.error_code,
260                                                         error_event.request_code, error_event.minor_code);
261                         else
262                                 Console.WriteLine ("X11 Error encountered: {0}{1}\n",
263                                                    X11Exception.GetMessage(error_event.display, error_event.resourceid,
264                                                                            error_event.serial, error_event.error_code,
265                                                                            error_event.request_code, error_event.minor_code),
266                                                    WhereString());
267                         return 0;
268                 }
269                 #endregion      // Callbacks
270
271                 private void ShowCaret()
272                 {
273                         if ((Caret.gc == IntPtr.Zero) || Caret.On) {
274                                 return;
275                         }
276                         Caret.On = true;
277
278                         Xlib.XDrawLine (display, Caret.Window, Caret.gc, Caret.X, Caret.Y, Caret.X, Caret.Y + Caret.Height);
279                 }
280
281                 private void HideCaret()
282                 {
283                         if ((Caret.gc == IntPtr.Zero) || !Caret.On) {
284                                 return;
285                         }
286                         Caret.On = false;
287
288                         Xlib.XDrawLine (display, Caret.Window, Caret.gc, Caret.X, Caret.Y, Caret.X, Caret.Y + Caret.Height);
289                 }
290
291                 public void CaretVisible (IntPtr handle, bool visible)
292                 {
293                         if (Caret.Hwnd == handle) {
294                                 if (visible) {
295                                         if (!Caret.Visible) {
296                                                 Caret.Visible = true;
297                                                 ShowCaret();
298                                                 Caret.Timer.Start();
299                                         }
300                                 } else {
301                                         Caret.Visible = false;
302                                         Caret.Timer.Stop();
303                                         HideCaret();
304                                 }
305                         }
306                 }
307
308                 public void AudibleAlert ()
309                 {
310                         Xlib.XBell (display, 0);
311                 }
312
313                 public void Flush ()
314                 {
315                         Xlib.XFlush (display);
316                 }
317
318                 public void Close ()
319                 {
320                         // XXX shut down the event_thread
321                         Xlib.XCloseDisplay (display);
322                 }
323
324                 public IntPtr XGetParent(IntPtr handle)
325                 {
326                         IntPtr  Root;
327                         IntPtr  Parent;
328                         IntPtr  Children;
329                         int     ChildCount;
330
331                         Xlib.XQueryTree (display, handle, out Root, out Parent, out Children, out ChildCount);
332
333                         if (Children!=IntPtr.Zero) {
334                                 Xlib.XFree(Children);
335                         }
336
337                         return Parent;
338                 }
339
340                 public bool SystrayAdd(IntPtr handle, string tip, Icon icon, out ToolTip tt)
341                 {
342                         IntPtr SystrayMgrWindow;
343
344                         Xlib.XGrabServer (display);
345                         SystrayMgrWindow = Xlib.XGetSelectionOwner (display, Atoms._NET_SYSTEM_TRAY_S);
346                         Xlib.XUngrabServer (display);
347
348                         if (SystrayMgrWindow != IntPtr.Zero) {
349                                 XSizeHints size_hints;
350                                 X11Hwnd hwnd;
351
352                                 hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
353 #if DriverDebug
354                                 Console.WriteLine("Adding Systray Whole:{0:X}, Client:{1:X}",
355                                                   hwnd.WholeWindow.ToInt32(), hwnd.ClientWindow.ToInt32());
356 #endif
357
358                                 // Oh boy.
359                                 if (hwnd.ClientWindow != hwnd.WholeWindow) {
360                                         Xlib.XDestroyWindow (display, hwnd.ClientWindow);
361                                         hwnd.ClientWindow = hwnd.WholeWindow;
362
363                                         try {
364                                                 hwnd.Queue.Lock ();
365
366                                                 /* by virtue of the way the tests are ordered when determining if it's PAINT
367                                                    or NCPAINT, ClientWindow == WholeWindow will always be PAINT.  So, if we're
368                                                    waiting on an nc_expose, drop it and remove the hwnd from the list (unless
369                                                    there's a pending expose). */
370                                                 hwnd.PendingNCExpose = false;
371                                         }
372                                         finally {
373                                                 hwnd.Queue.Unlock ();
374                                         }
375                                 }
376
377                                 size_hints = new XSizeHints();
378
379                                 size_hints.flags = (IntPtr)(XSizeHintsFlags.PMinSize | XSizeHintsFlags.PMaxSize | XSizeHintsFlags.PBaseSize);
380
381                                 size_hints.min_width = 24;
382                                 size_hints.min_height = 24;
383                                 size_hints.max_width = 24;
384                                 size_hints.max_height = 24;
385                                 size_hints.base_width = 24;
386                                 size_hints.base_height = 24;
387
388                                 Xlib.XSetWMNormalHints (display, hwnd.WholeWindow, ref size_hints);
389
390                                 int[] atoms = new int[2];
391                                 atoms [0] = 1;                  // Version 1
392                                 atoms [1] = 1;                  // we want to be mapped
393
394                                 // This line cost me 3 days...
395                                 Xlib.XChangeProperty (display,
396                                                       hwnd.WholeWindow, Atoms._XEMBED_INFO, Atoms._XEMBED_INFO, 32,
397                                                       PropertyMode.Replace, atoms, 2);
398
399                                 // Need to pick some reasonable defaults
400                                 tt = new ToolTip();
401                                 tt.AutomaticDelay = 100;
402                                 tt.InitialDelay = 250;
403                                 tt.ReshowDelay = 250;
404                                 tt.ShowAlways = true;
405
406                                 if ((tip != null) && (tip != string.Empty)) {
407                                         tt.SetToolTip(Control.FromHandle(handle), tip);
408                                         tt.Active = true;
409                                 } else {
410                                         tt.Active = false;
411                                 }
412
413                                 SendNetClientMessage (SystrayMgrWindow,
414                                                       Atoms._NET_SYSTEM_TRAY_OPCODE,
415                                                       IntPtr.Zero,
416                                                       (IntPtr)SystrayRequest.SYSTEM_TRAY_REQUEST_DOCK,
417                                                       hwnd.WholeWindow);
418
419                                 return true;
420                         }
421
422                         tt = null;
423                         return false;
424                 }
425
426                 public bool SystrayChange (IntPtr handle, string tip, Icon icon, ref ToolTip tt)
427                 {
428                         Control control;
429
430                         control = Control.FromHandle(handle);
431                         if (control != null && tt != null) {
432                                 tt.SetToolTip(control, tip);
433                                 tt.Active = true;
434                                 return true;
435                         } else {
436                                 return false;
437                         }
438                 }
439
440                 public void SystrayRemove(IntPtr handle, ref ToolTip tt)
441                 {
442 #if GTKSOCKET_SUPPORTS_REPARENTING
443                         X11Hwnd hwnd;
444
445                         hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
446
447                         /* in the XEMBED spec, it mentions 3 ways for a client window to break the protocol with the embedder.
448                          * 1. The embedder can unmap the window and reparent to the root window (we should probably handle this...)
449                          * 2. The client can reparent its window out of the embedder window.
450                          * 3. The client can destroy its window.
451                          *
452                          * this call to SetParent is case 2, but in
453                          * the spec it also mentions that gtk doesn't
454                          * support this at present.  Looking at HEAD
455                          * gtksocket-x11.c jives with this statement.
456                          *
457                          * so we can't reparent.  we have to destroy.
458                          */
459                         SetParent(hwnd.WholeWindow, FosterParent);
460 #else
461                         Control control = Control.FromHandle(handle);
462                         if (control is NotifyIcon.NotifyIconWindow)
463                                 ((NotifyIcon.NotifyIconWindow)control).InternalRecreateHandle ();
464 #endif
465
466                         // The caller can now re-dock it later...
467                         if (tt != null) {
468                                 tt.Dispose();
469                                 tt = null;
470                         }
471                 }
472
473                 public void ResetMouseHover (X11Hwnd hovering)
474                 {
475                         HoverState.Timer.Enabled = hovering != null;
476                         HoverState.X = MousePosition.X;
477                         HoverState.Y = MousePosition.Y;
478                         HoverState.Window = hovering == null ? IntPtr.Zero : hovering.Handle;
479                 }
480
481                 public void ShowCursor (bool show)
482                 {
483                         ;       // FIXME - X11 doesn't 'hide' the cursor. we could create an empty cursor
484                 }
485
486                 public void SetModal (X11Hwnd hwnd, bool Modal)
487                 {
488                         if (Modal) {
489                                 ModalWindows.Push(hwnd);
490                         } else {
491                                 // XXX do we need to pop until the
492                                 // hwnd is off the stack?  or just the
493                                 // most recently pushed hwnd?
494                                 if (ModalWindows.Contains(hwnd)) {
495                                         ModalWindows.Pop();
496                                 }
497
498                                 if (ModalWindows.Count > 0) {
499                                         X11Hwnd top_hwnd = (X11Hwnd)ModalWindows.Peek();
500                                         top_hwnd.Activate();
501                                 }
502                         }
503                 }
504
505                 public bool SupportsTransparency ()
506                 {
507                         // compiz adds _NET_WM_WINDOW_OPACITY to _NET_SUPPORTED on the root window, check for that
508                         return ((IList)root_hwnd._NET_SUPPORTED).Contains (Atoms._NET_WM_WINDOW_OPACITY);
509                 }
510
511                 public void SendAsyncMethod (AsyncMethodData method)
512                 {
513                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(method.Handle);
514                         XEvent xevent = new XEvent ();
515
516                         xevent.type = XEventName.ClientMessage;
517                         xevent.ClientMessageEvent.display = display;
518                         xevent.ClientMessageEvent.window = method.Handle;
519                         xevent.ClientMessageEvent.message_type = Atoms.AsyncAtom;
520                         xevent.ClientMessageEvent.format = 32;
521                         xevent.ClientMessageEvent.ptr1 = (IntPtr) GCHandle.Alloc (method);
522
523                         hwnd.Queue.Enqueue (xevent);
524                 }
525
526                 delegate IntPtr WndProcDelegate (IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam);
527
528                 public IntPtr SendMessage (IntPtr handle, Msg message, IntPtr wParam, IntPtr lParam)
529                 {
530                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
531                         if (hwnd == null)
532                                 return IntPtr.Zero;
533
534                         if (hwnd.Queue.Thread != Thread.CurrentThread) {
535                                 AsyncMethodResult       result;
536                                 AsyncMethodData         data;
537
538                                 result = new AsyncMethodResult ();
539                                 data = new AsyncMethodData ();
540
541                                 data.Handle = hwnd.Handle;
542                                 data.Method = new WndProcDelegate (NativeWindow.WndProc);
543                                 data.Args = new object[] { hwnd.Handle, message, wParam, lParam };
544                                 data.Result = result;
545                                 
546                                 SendAsyncMethod (data);
547 #if DriverDebug || DriverDebugThreads
548                                 Console.WriteLine ("Sending {0} message across.", message);
549 #endif
550
551                                 return IntPtr.Zero;
552                         }
553                         else {
554                                 return NativeWindow.WndProc (hwnd.Handle, message, wParam, lParam);
555                         }
556                 }
557
558                 // FIXME - I think this should just enqueue directly
559                 public bool PostMessage (IntPtr handle, Msg message, IntPtr wparam, IntPtr lparam)
560                 {
561                         XEvent xevent = new XEvent ();
562                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
563
564                         xevent.type = XEventName.ClientMessage;
565                         xevent.ClientMessageEvent.display = display;
566
567                         if (hwnd != null) {
568                                 xevent.ClientMessageEvent.window = hwnd.WholeWindow;
569                         } else {
570                                 xevent.ClientMessageEvent.window = IntPtr.Zero;
571                         }
572
573                         xevent.ClientMessageEvent.message_type = Atoms.PostAtom;
574                         xevent.ClientMessageEvent.format = 32;
575                         xevent.ClientMessageEvent.ptr1 = handle;
576                         xevent.ClientMessageEvent.ptr2 = (IntPtr) message;
577                         xevent.ClientMessageEvent.ptr3 = wparam;
578                         xevent.ClientMessageEvent.ptr4 = lparam;
579
580                         hwnd.Queue.Enqueue (xevent);
581
582                         return true;
583                 }
584
585                 public void SendNetWMMessage (IntPtr window, IntPtr message_type, IntPtr l0, IntPtr l1, IntPtr l2)
586                 {
587                         XEvent  xev;
588
589                         xev = new XEvent();
590                         xev.ClientMessageEvent.type = XEventName.ClientMessage;
591                         xev.ClientMessageEvent.send_event = true;
592                         xev.ClientMessageEvent.window = window;
593                         xev.ClientMessageEvent.message_type = message_type;
594                         xev.ClientMessageEvent.format = 32;
595                         xev.ClientMessageEvent.ptr1 = l0;
596                         xev.ClientMessageEvent.ptr2 = l1;
597                         xev.ClientMessageEvent.ptr3 = l2;
598
599                         Xlib.XSendEvent (display, root_hwnd.Handle, false,
600                                          new IntPtr ((int) (EventMask.SubstructureRedirectMask | EventMask.SubstructureNotifyMask)), ref xev);
601                 }
602
603                 public void SendNetClientMessage (IntPtr window, IntPtr message_type, IntPtr l0, IntPtr l1, IntPtr l2)
604                 {
605                         XEvent  xev;
606
607                         xev = new XEvent();
608                         xev.ClientMessageEvent.type = XEventName.ClientMessage;
609                         xev.ClientMessageEvent.send_event = true;
610                         xev.ClientMessageEvent.window = window;
611                         xev.ClientMessageEvent.message_type = message_type;
612                         xev.ClientMessageEvent.format = 32;
613                         xev.ClientMessageEvent.ptr1 = l0;
614                         xev.ClientMessageEvent.ptr2 = l1;
615                         xev.ClientMessageEvent.ptr3 = l2;
616
617                         Xlib.XSendEvent (display, window, false, new IntPtr ((int)EventMask.NoEventMask), ref xev);
618                 }
619
620                 public bool TranslateMessage (ref MSG msg)
621                 {
622                         return Keyboard.TranslateMessage (ref msg);
623                 }
624
625                 public IntPtr DispatchMessage (ref MSG msg)
626                 {
627                         return NativeWindow.WndProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
628                 }
629
630                 private void QueryPointer (IntPtr w, out IntPtr root, out IntPtr child,
631                                            out int root_x, out int root_y, out int child_x, out int child_y,
632                                            out int mask)
633                 {
634                         /* this code was written with the help of
635                            glance at gdk.  I never would have realized we
636                            needed a loop in order to traverse down in the
637                            hierarchy.  I would have assumed you'd get the
638                            most deeply nested child and have to do
639                            XQueryTree to move back up the hierarchy..
640                            stupid me, of course. */
641                         IntPtr c;
642
643                         Xlib.XGrabServer (display);
644
645                         Xlib.XQueryPointer (display, w, out root, out c,
646                                             out root_x, out root_y, out child_x, out child_y,
647                                             out mask);
648
649                         if (root != w)
650                                 c = root;
651
652                         IntPtr child_last = IntPtr.Zero;
653                         while (c != IntPtr.Zero) {
654                                 child_last = c;
655                                 Xlib.XQueryPointer (display, c, out root, out c,
656                                                     out root_x, out root_y, out child_x, out child_y,
657                                                     out mask);
658                         }
659
660                         Xlib.XUngrabServer (display);
661
662                         child = child_last;
663                 }
664
665                 public void SetCursorPos (int x, int y)
666                 {
667                         IntPtr root, child;
668                         int root_x, root_y, child_x, child_y, mask;
669
670                         /* we need to do a
671                          * QueryPointer before warping
672                          * because if the warp is on
673                          * the RootWindow, the x/y are
674                          * relative to the current
675                          * mouse position
676                          */
677                         QueryPointer (RootWindow.Handle,
678                                       out root,
679                                       out child,
680                                       out root_x, out root_y,
681                                       out child_x, out child_y,
682                                       out mask);
683
684                         Xlib.XWarpPointer (display, IntPtr.Zero, IntPtr.Zero, 0, 0, 0, 0, x - root_x, y - root_y);
685
686                         Xlib.XFlush (display);
687
688                         /* then we need to a
689                          * QueryPointer after warping
690                          * to manually generate a
691                          * motion event for the window
692                          * we move into.
693                          */
694                         QueryPointer (RootWindow.Handle,
695                                       out root,
696                                       out child,
697                                       out root_x, out root_y,
698                                       out child_x, out child_y,
699                                       out mask);
700
701                         X11Hwnd child_hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(child);
702                         if (child_hwnd == null)
703                                 return;
704
705                         XEvent xevent = new XEvent ();
706
707                         xevent.type = XEventName.MotionNotify;
708                         xevent.MotionEvent.display = display;
709                         xevent.MotionEvent.window = child_hwnd.Handle;
710                         xevent.MotionEvent.root = RootWindow.Handle;
711                         xevent.MotionEvent.x = child_x;
712                         xevent.MotionEvent.y = child_y;
713                         xevent.MotionEvent.x_root = root_x;
714                         xevent.MotionEvent.y_root = root_y;
715                         xevent.MotionEvent.state = mask;
716
717                         child_hwnd.Queue.Enqueue (xevent);
718                 }
719
720                 public void SetFocus (X11Hwnd new_focus)
721                 {
722                         if (new_focus == FocusWindow)
723                                 return;
724
725                         X11Hwnd prev_focus = FocusWindow;
726                         FocusWindow = new_focus;
727
728                         if (prev_focus != null)
729                                 SendMessage (prev_focus.Handle, Msg.WM_KILLFOCUS,
730                                              FocusWindow == null ? IntPtr.Zero : FocusWindow.Handle, IntPtr.Zero);
731                         if (FocusWindow != null)
732                                 SendMessage (FocusWindow.Handle, Msg.WM_SETFOCUS,
733                                              prev_focus == null ? IntPtr.Zero : prev_focus.Handle, IntPtr.Zero);
734
735                         //XSetInputFocus(DisplayHandle, Hwnd.ObjectFromHandle(handle).ClientWindow, RevertTo.None, IntPtr.Zero);
736                 }
737
738                 public IntPtr DefineCursor (Bitmap bitmap, Bitmap mask, Color cursor_pixel, Color mask_pixel, int xHotSpot, int yHotSpot)
739                 {
740                         IntPtr  cursor;
741                         Bitmap  cursor_bitmap;
742                         Bitmap  cursor_mask;
743                         Byte[]  cursor_bits;
744                         Byte[]  mask_bits;
745                         Color   c_pixel;
746                         Color   m_pixel;
747                         int     width;
748                         int     height;
749                         IntPtr  cursor_pixmap;
750                         IntPtr  mask_pixmap;
751                         XColor  fg;
752                         XColor  bg;
753                         bool    and;
754                         bool    xor;
755
756                         if (Xlib.XQueryBestCursor (display, RootWindow.Handle, bitmap.Width, bitmap.Height, out width, out height) == 0) {
757                                 return IntPtr.Zero;
758                         }
759
760                         // Win32 only allows creation cursors of a certain size
761                         if ((bitmap.Width != width) || (bitmap.Width != height)) {
762                                 cursor_bitmap = new Bitmap(bitmap, new Size(width, height));
763                                 cursor_mask = new Bitmap(mask, new Size(width, height));
764                         } else {
765                                 cursor_bitmap = bitmap;
766                                 cursor_mask = mask;
767                         }
768
769                         width = cursor_bitmap.Width;
770                         height = cursor_bitmap.Height;
771
772                         cursor_bits = new Byte[(width / 8) * height];
773                         mask_bits = new Byte[(width / 8) * height];
774
775                         for (int y = 0; y < height; y++) {
776                                 for (int x = 0; x < width; x++) {
777                                         c_pixel = cursor_bitmap.GetPixel(x, y);
778                                         m_pixel = cursor_mask.GetPixel(x, y);
779
780                                         and = c_pixel == cursor_pixel;
781                                         xor = m_pixel == mask_pixel;
782
783                                         if (!and && !xor) {
784                                                 // Black
785                                                 // cursor_bits[y * width / 8 + x / 8] &= (byte)~((1 << (x % 8)));       // The bit already is 0
786                                                 mask_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
787                                         } else if (and && !xor) {
788                                                 // White
789                                                 cursor_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
790                                                 mask_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
791 #if notneeded
792                                         } else if (and && !xor) {
793                                                 // Screen
794                                         } else if (and && xor) {
795                                                 // Inverse Screen
796
797                                                 // X11 doesn't know the 'reverse screen' concept, so we'll treat them the same
798                                                 // we want both to be 0 so nothing to be done
799                                                 //cursor_bits[y * width / 8 + x / 8] &= (byte)~((1 << (x % 8)));
800                                                 //mask_bits[y * width / 8 + x / 8] |= (byte)(01 << (x % 8));
801 #endif
802                                         }
803                                 }
804                         }
805
806                         cursor_pixmap = Xlib.XCreatePixmapFromBitmapData (display, RootWindow.Handle,
807                                                                           cursor_bits, width, height, (IntPtr)1, (IntPtr)0, 1);
808                         mask_pixmap = Xlib.XCreatePixmapFromBitmapData (display, RootWindow.Handle,
809                                                                         mask_bits, width, height, (IntPtr)1, (IntPtr)0, 1);
810                         fg = new XColor();
811                         bg = new XColor();
812
813                         fg.pixel = Xlib.XWhitePixel (display, DefaultScreen);
814                         fg.red = (ushort)65535;
815                         fg.green = (ushort)65535;
816                         fg.blue = (ushort)65535;
817
818                         bg.pixel = Xlib.XBlackPixel (display, DefaultScreen);
819
820                         cursor = Xlib.XCreatePixmapCursor (display, cursor_pixmap, mask_pixmap, ref fg, ref bg, xHotSpot, yHotSpot);
821
822                         Xlib.XFreePixmap (display, cursor_pixmap);
823                         Xlib.XFreePixmap (display, mask_pixmap);
824
825                         return cursor;
826                 }
827
828                 public IntPtr DefineStdCursor (StdCursor id)
829                 {
830                         CursorFontShape shape;
831
832                         // FIXME - define missing shapes
833
834                         switch (id) {
835                         case StdCursor.AppStarting:
836                                 shape = CursorFontShape.XC_watch;
837                                 break;
838
839                         case StdCursor.Arrow:
840                                 shape = CursorFontShape.XC_top_left_arrow;
841                                 break;
842
843                         case StdCursor.Cross:
844                                 shape = CursorFontShape.XC_crosshair;
845                                 break;
846
847                         case StdCursor.Default:
848                                 shape = CursorFontShape.XC_top_left_arrow;
849                                 break;
850
851                         case StdCursor.Hand:
852                                 shape = CursorFontShape.XC_hand1;
853                                 break;
854
855                         case StdCursor.Help:
856                                 shape = CursorFontShape.XC_question_arrow;
857                                 break;
858                         
859                         case StdCursor.HSplit:
860                                 shape = CursorFontShape.XC_sb_v_double_arrow; 
861                                 break;
862
863                         case StdCursor.IBeam:
864                                 shape = CursorFontShape.XC_xterm; 
865                                 break;
866
867                         case StdCursor.No:
868                                 shape = CursorFontShape.XC_circle; 
869                                 break;
870
871                         case StdCursor.NoMove2D:
872                                 shape = CursorFontShape.XC_fleur; 
873                                 break;
874
875                         case StdCursor.NoMoveHoriz:
876                                 shape = CursorFontShape.XC_fleur; 
877                                 break;
878
879                         case StdCursor.NoMoveVert:
880                                 shape = CursorFontShape.XC_fleur; 
881                                 break;
882
883                         case StdCursor.PanEast:
884                                 shape = CursorFontShape.XC_fleur; 
885                                 break;
886
887                         case StdCursor.PanNE:
888                                 shape = CursorFontShape.XC_fleur; 
889                                 break;
890
891                         case StdCursor.PanNorth:
892                                 shape = CursorFontShape.XC_fleur; 
893                                 break;
894
895                         case StdCursor.PanNW:
896                                 shape = CursorFontShape.XC_fleur; 
897                                 break;
898
899                         case StdCursor.PanSE:
900                                 shape = CursorFontShape.XC_fleur; 
901                                 break;
902
903                         case StdCursor.PanSouth:
904                                 shape = CursorFontShape.XC_fleur; 
905                                 break;
906
907                         case StdCursor.PanSW:
908                                 shape = CursorFontShape.XC_fleur; 
909                                 break;
910
911                         case StdCursor.PanWest:
912                                 shape = CursorFontShape.XC_sizing; 
913                                 break;
914
915                         case StdCursor.SizeAll:
916                                 shape = CursorFontShape.XC_fleur; 
917                                 break;
918
919                         case StdCursor.SizeNESW:
920                                 shape = CursorFontShape.XC_top_right_corner; 
921                                 break;
922
923                         case StdCursor.SizeNS:
924                                 shape = CursorFontShape.XC_sb_v_double_arrow;
925                                 break;
926
927                         case StdCursor.SizeNWSE:
928                                 shape = CursorFontShape.XC_top_left_corner; 
929                                 break;
930
931                         case StdCursor.SizeWE:
932                                 shape = CursorFontShape.XC_sb_h_double_arrow; 
933                                 break;
934
935                         case StdCursor.UpArrow:
936                                 shape = CursorFontShape.XC_center_ptr; 
937                                 break;
938
939                         case StdCursor.VSplit:
940                                 shape = CursorFontShape.XC_sb_h_double_arrow;
941                                 break;
942
943                         case StdCursor.WaitCursor:
944                                 shape = CursorFontShape.XC_watch; 
945                                 break;
946
947                         default:
948                                 return IntPtr.Zero;
949                         }
950
951                         return Xlib.XCreateFontCursor (display, shape);
952                 }
953
954                 // XXX this should take an X11Hwnd.
955                 public void CreateCaret (IntPtr handle, int width, int height)
956                 {
957                         XGCValues gc_values;
958                         X11Hwnd hwnd;
959
960                         hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
961
962                         if (Caret.Hwnd != IntPtr.Zero)
963                                 DestroyCaret(Caret.Hwnd);
964
965                         Caret.Hwnd = handle;
966                         Caret.Window = hwnd.ClientWindow;
967                         Caret.Width = width;
968                         Caret.Height = height;
969                         Caret.Visible = false;
970                         Caret.On = false;
971
972                         gc_values = new XGCValues();
973                         gc_values.line_width = width;
974
975                         Caret.gc = Xlib.XCreateGC (display, Caret.Window, new IntPtr ((int)GCFunction.GCLineWidth), ref gc_values);
976                         if (Caret.gc == IntPtr.Zero) {
977                                 Caret.Hwnd = IntPtr.Zero;
978                                 return;
979                         }
980
981                         Xlib.XSetFunction (display, Caret.gc, GXFunction.GXinvert);
982                 }
983
984
985                 // XXX this should take an X11Hwnd.
986                 public void DestroyCaret (IntPtr handle)
987                 {
988                         if (Caret.Hwnd == handle) {
989                                 if (Caret.Visible == true) {
990                                         Caret.Timer.Stop ();
991                                 }
992                                 if (Caret.gc != IntPtr.Zero) {
993                                         Xlib.XFreeGC (display, Caret.gc);
994                                         Caret.gc = IntPtr.Zero;
995                                 }
996                                 Caret.Hwnd = IntPtr.Zero;
997                                 Caret.Visible = false;
998                                 Caret.On = false;
999                         }
1000                 }
1001
1002                 public void SetCaretPos (IntPtr handle, int x, int y)
1003                 {
1004                         if (Caret.Hwnd == handle) {
1005                                 Caret.Timer.Stop();
1006                                 HideCaret();
1007
1008                                 Caret.X = x;
1009                                 Caret.Y = y;
1010
1011                                 if (Caret.Visible == true) {
1012                                         ShowCaret();
1013                                         Caret.Timer.Start();
1014                                 }
1015                         }
1016                 }
1017
1018                 public void DestroyCursor (IntPtr cursor)
1019                 {
1020                         Xlib.XFreeCursor (display, cursor);
1021                 }
1022
1023                 private void AccumulateDestroyedHandles (Control c, ArrayList list)
1024                 {
1025                         if (c != null) {
1026                                 Control[] controls = c.child_controls.GetAllControls ();
1027
1028                                 if (c.IsHandleCreated && !c.IsDisposed) {
1029                                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(c.Handle);
1030
1031 #if DriverDebug || DriverDebugDestroy
1032                                         Console.WriteLine (" + adding {0} to the list of zombie windows", XplatUI.Window (hwnd.Handle));
1033                                         Console.WriteLine (" + parent X window is {0:X}", XGetParent (hwnd.WholeWindow).ToInt32());
1034 #endif
1035
1036                                         list.Add (hwnd);
1037                                         CleanupCachedWindows (hwnd);
1038                                         hwnd.zombie = true;
1039                                 }
1040
1041                                 for (int  i = 0; i < controls.Length; i ++) {
1042                                         AccumulateDestroyedHandles (controls[i], list);
1043                                 }
1044                         }
1045                         
1046                 }
1047
1048                 void CleanupCachedWindows (X11Hwnd hwnd)
1049                 {
1050                         if (ActiveWindow == hwnd) {
1051                                 SendMessage (hwnd.ClientWindow, Msg.WM_ACTIVATE, (IntPtr)WindowActiveFlags.WA_INACTIVE, IntPtr.Zero);
1052                                 ActiveWindow = null;
1053                         }
1054
1055                         if (FocusWindow == hwnd) {
1056                                 SendMessage (hwnd.ClientWindow, Msg.WM_KILLFOCUS, IntPtr.Zero, IntPtr.Zero);
1057                                 FocusWindow = null;
1058                         }
1059
1060                         if (Grab.Hwnd == hwnd.Handle) {
1061                                 Grab.Hwnd = IntPtr.Zero;
1062                                 Grab.Confined = false;
1063                         }
1064
1065                         DestroyCaret (hwnd.Handle);
1066                 }
1067
1068
1069                 public void DestroyWindow (X11Hwnd hwnd)
1070                 {
1071                         CleanupCachedWindows (hwnd);
1072
1073                         ArrayList windows = new ArrayList ();
1074
1075                         AccumulateDestroyedHandles (Control.ControlNativeWindow.ControlFromHandle(hwnd.Handle), windows);
1076
1077                         hwnd.DestroyWindow ();
1078
1079                         foreach (X11Hwnd h in windows) {
1080                                 SendMessage (h.Handle, Msg.WM_DESTROY, IntPtr.Zero, IntPtr.Zero);
1081                         }
1082                 }
1083
1084                 public X11Hwnd GetActiveWindow ()
1085                 {
1086                         IntPtr  actual_atom;
1087                         int     actual_format;
1088                         IntPtr  nitems;
1089                         IntPtr  bytes_after;
1090                         IntPtr  prop = IntPtr.Zero;
1091                         IntPtr  active = IntPtr.Zero;
1092
1093                         Xlib.XGetWindowProperty (display, RootWindow.Handle,
1094                                                  Atoms._NET_ACTIVE_WINDOW, IntPtr.Zero, new IntPtr (1), false,
1095                                                  Atoms.XA_WINDOW, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1096
1097                         if (((long)nitems > 0) && (prop != IntPtr.Zero)) {
1098                                 active = (IntPtr)Marshal.ReadInt32(prop);
1099                                 Xlib.XFree(prop);
1100                         }
1101
1102                         return (X11Hwnd)Hwnd.GetObjectFromWindow(active);
1103                 }
1104
1105                 public void SetActiveWindow (X11Hwnd new_active_window)
1106                 {
1107                         if (new_active_window != ActiveWindow) {
1108                                 if (ActiveWindow != null)
1109                                         PostMessage (ActiveWindow.Handle, Msg.WM_ACTIVATE,
1110                                                      (IntPtr)WindowActiveFlags.WA_INACTIVE, IntPtr.Zero);
1111
1112                                 ActiveWindow = new_active_window;
1113
1114                                 if (ActiveWindow != null)
1115                                         PostMessage (ActiveWindow.Handle, Msg.WM_ACTIVATE,
1116                                                      (IntPtr)WindowActiveFlags.WA_ACTIVE, IntPtr.Zero);
1117                         }
1118
1119                         if (ModalWindows.Count > 0) {
1120                                 // Modality handling, if we are modal and the new active window is one
1121                                 // of ours but not the modal one, switch back to the modal window
1122
1123                                 if (ActiveWindow != null &&
1124                                     NativeWindow.FindWindow (ActiveWindow.Handle) != null) {
1125                                         if (ActiveWindow != (X11Hwnd)ModalWindows.Peek())
1126                                                 ((X11Hwnd)ModalWindows.Peek()).Activate ();
1127                                 }
1128                         }
1129                 }
1130
1131                 public void GetDisplaySize (out Size size)
1132                 {
1133                         XWindowAttributes attributes = new XWindowAttributes();
1134
1135                         // FIXME - use _NET_WM messages instead?
1136                         Xlib.XGetWindowAttributes (display, RootWindow.Handle, ref attributes);
1137
1138                         size = new Size(attributes.width, attributes.height);
1139                 }
1140
1141                 // XXX this method doesn't really fit well anywhere in the backend
1142                 public SizeF GetAutoScaleSize (Font font)
1143                 {
1144                         Graphics        g;
1145                         float           width;
1146                         string          magic_string = "The quick brown fox jumped over the lazy dog.";
1147                         double          magic_number = 44.549996948242189; // XXX my god, where did this number come from?
1148
1149                         g = Graphics.FromHwnd (FosterParent.Handle);
1150
1151                         width = (float) (g.MeasureString (magic_string, font).Width / magic_number);
1152                         return new SizeF(width, font.Height);
1153                 }
1154
1155                 public void GetCursorPos (X11Hwnd hwnd, out int x, out int y)
1156                 {
1157                         IntPtr  use_handle;
1158                         IntPtr  root;
1159                         IntPtr  child;
1160                         int     root_x;
1161                         int     root_y;
1162                         int     win_x;
1163                         int     win_y;
1164                         int     keys_buttons;
1165
1166                         if (hwnd != null)
1167                                 use_handle = hwnd.Handle;
1168                         else
1169                                 use_handle = RootWindow.Handle;
1170
1171                         QueryPointer (use_handle, out root, out child, out root_x, out root_y, out win_x, out win_y, out keys_buttons);
1172
1173                         if (hwnd != null) {
1174                                 x = win_x;
1175                                 y = win_y;
1176                         } else {
1177                                 x = root_x;
1178                                 y = root_y;
1179                         }
1180                 }
1181
1182                 public IntPtr GetFocus ()
1183                 {
1184                         return FocusWindow.Handle;
1185                 }
1186
1187                 public IntPtr GetMousewParam (int Delta)
1188                 {
1189                         int     result = 0;
1190
1191                         if ((MouseState & MouseButtons.Left) != 0) {
1192                                 result |= (int)MsgButtons.MK_LBUTTON;
1193                         }
1194
1195                         if ((MouseState & MouseButtons.Middle) != 0) {
1196                                 result |= (int)MsgButtons.MK_MBUTTON;
1197                         }
1198
1199                         if ((MouseState & MouseButtons.Right) != 0) {
1200                                 result |= (int)MsgButtons.MK_RBUTTON;
1201                         }
1202
1203                         Keys mods = ModifierKeys;
1204                         if ((mods & Keys.Control) != 0) {
1205                                 result |= (int)MsgButtons.MK_CONTROL;
1206                         }
1207
1208                         if ((mods & Keys.Shift) != 0) {
1209                                 result |= (int)MsgButtons.MK_SHIFT;
1210                         }
1211
1212                         result |= Delta << 16;
1213
1214                         return (IntPtr)result;
1215                 }
1216
1217                 public void GrabInfo (out IntPtr handle, out bool GrabConfined, out Rectangle GrabArea)
1218                 {
1219                         handle = Grab.Hwnd;
1220                         GrabConfined = Grab.Confined;
1221                         GrabArea = Grab.Area;
1222                 }
1223
1224                 public void GrabWindow (X11Hwnd hwnd, X11Hwnd confine_to)
1225                 {
1226                         IntPtr  confine_to_window;
1227
1228                         confine_to_window = IntPtr.Zero;
1229
1230                         if (confine_to != null) {
1231                                 Console.WriteLine (Environment.StackTrace);
1232
1233                                 XWindowAttributes attributes = new XWindowAttributes();
1234
1235                                 Xlib.XGetWindowAttributes (display, confine_to.ClientWindow, ref attributes);
1236
1237                                 Grab.Area.X = attributes.x;
1238                                 Grab.Area.Y = attributes.y;
1239                                 Grab.Area.Width = attributes.width;
1240                                 Grab.Area.Height = attributes.height;
1241                                 Grab.Confined = true;
1242                                 confine_to_window = confine_to.ClientWindow;
1243                         }
1244
1245                         Grab.Hwnd = hwnd.ClientWindow;
1246
1247                         Xlib.XGrabPointer (display, hwnd.ClientWindow, false, 
1248                                            EventMask.ButtonPressMask | EventMask.ButtonMotionMask |
1249                                            EventMask.ButtonReleaseMask | EventMask.PointerMotionMask,
1250                                            GrabMode.GrabModeAsync, GrabMode.GrabModeAsync, confine_to_window, IntPtr.Zero, IntPtr.Zero);
1251                 }
1252
1253                 public void UngrabWindow (X11Hwnd hwnd)
1254                 {
1255                         Xlib.XUngrabPointer (display, IntPtr.Zero);
1256                         Xlib.XFlush (display);
1257
1258                         // XXX make sure hwnd is what should have the grab and throw if not
1259                         Grab.Hwnd = IntPtr.Zero;
1260                         Grab.Confined = false;
1261                 }
1262
1263                 private void TranslatePropertyToClipboard (IntPtr property)
1264                 {
1265                         IntPtr actual_atom;
1266                         int actual_format;
1267                         IntPtr nitems;
1268                         IntPtr bytes_after;
1269                         IntPtr prop = IntPtr.Zero;
1270
1271                         Clipboard.Item = null;
1272
1273                         Xlib.XGetWindowProperty (display, FosterParent.Handle,
1274                                                  property, IntPtr.Zero, new IntPtr (0x7fffffff), true,
1275                                                  Atoms.AnyPropertyType, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1276
1277                         if ((long)nitems > 0) {
1278                                 if (property == Atoms.XA_STRING) {
1279                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
1280                                 } else if (property == Atoms.XA_BITMAP) {
1281                                         // FIXME - convert bitmap to image
1282                                 } else if (property == Atoms.XA_PIXMAP) {
1283                                         // FIXME - convert pixmap to image
1284                                 } else if (property == Atoms.OEMTEXT) {
1285                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
1286                                 } else if (property == Atoms.UNICODETEXT) {
1287                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
1288                                 }
1289
1290                                 Xlib.XFree(prop);
1291                         }
1292                 }
1293
1294                 // XXX should we be using @handle instead of Atoms.CLIPBOARD here?
1295                 public int[] ClipboardAvailableFormats (IntPtr handle)
1296                 {
1297                         // XXX deal with the updatemessagequeue stuff
1298 #if true
1299                         return new int[0];
1300 #else
1301                         DataFormats.Format f;
1302                         int[] result;
1303
1304                         f = DataFormats.Format.List;
1305
1306                         if (Xlib.XGetSelectionOwner (display, Atoms.CLIPBOARD) == IntPtr.Zero) {
1307                                 return null;
1308                         }
1309
1310                         Clipboard.Formats = new ArrayList();
1311
1312                         while (f != null) {
1313                                 Xlib.XConvertSelection (display, Atoms.CLIPBOARD, (IntPtr)f.Id, (IntPtr)f.Id, FosterParent.Handle, IntPtr.Zero);
1314
1315                                 Clipboard.Enumerating = true;
1316                                 while (Clipboard.Enumerating) {
1317                                         UpdateMessageQueue(null);
1318                                 }
1319                                 f = f.Next;
1320                         }
1321
1322                         result = new int[Clipboard.Formats.Count];
1323
1324                         for (int i = 0; i < Clipboard.Formats.Count; i++) {
1325                                 result[i] = ((IntPtr)Clipboard.Formats[i]).ToInt32 ();
1326                         }
1327
1328                         Clipboard.Formats = null;
1329                         return result;
1330 #endif
1331                 }
1332
1333                 public void ClipboardClose (IntPtr handle)
1334                 {
1335                         if (handle != ClipMagic) {
1336                                 throw new ArgumentException("handle is not a valid clipboard handle");
1337                         }
1338                         return;
1339                 }
1340
1341                 public int ClipboardGetID (IntPtr handle, string format)
1342                 {
1343                         if (handle != ClipMagic) {
1344                                 throw new ArgumentException("handle is not a valid clipboard handle");
1345                         }
1346
1347                         if (format == "Text" ) return Atoms.XA_STRING.ToInt32();
1348                         else if (format == "Bitmap" ) return Atoms.XA_BITMAP.ToInt32();
1349                         //else if (format == "MetaFilePict" ) return 3;
1350                         //else if (format == "SymbolicLink" ) return 4;
1351                         //else if (format == "DataInterchangeFormat" ) return 5;
1352                         //else if (format == "Tiff" ) return 6;
1353                         else if (format == "OEMText" ) return Atoms.OEMTEXT.ToInt32();
1354                         else if (format == "DeviceIndependentBitmap" ) return Atoms.XA_PIXMAP.ToInt32();
1355                         else if (format == "Palette" ) return Atoms.XA_COLORMAP.ToInt32();      // Useless
1356                         //else if (format == "PenData" ) return 10;
1357                         //else if (format == "RiffAudio" ) return 11;
1358                         //else if (format == "WaveAudio" ) return 12;
1359                         else if (format == "UnicodeText" ) return Atoms.UNICODETEXT.ToInt32();
1360                         //else if (format == "EnhancedMetafile" ) return 14;
1361                         //else if (format == "FileDrop" ) return 15;
1362                         //else if (format == "Locale" ) return 16;
1363
1364                         return Xlib.XInternAtom (display, format, false).ToInt32();
1365                 }
1366
1367                 public IntPtr ClipboardOpen (bool primary_selection)
1368                 {
1369                         if (!primary_selection)
1370                                 ClipMagic = Atoms.CLIPBOARD;
1371                         else
1372                                 ClipMagic = Atoms.PRIMARY;
1373
1374                         return ClipMagic;
1375                 }
1376
1377                 // XXX @converter?
1378                 public object ClipboardRetrieve (IntPtr handle, int type, XplatUI.ClipboardToObject converter)
1379                 {
1380                         // XXX deal with the UpdateMessageQueue stuff
1381 #if true
1382                         return null;
1383 #else
1384                         Xlib.XConvertSelection (display, handle, (IntPtr)type, (IntPtr)type, FosterParent, IntPtr.Zero);
1385
1386                         Clipboard.Retrieving = true;
1387                         while (Clipboard.Retrieving) {
1388                                 UpdateMessageQueue(null);
1389                         }
1390
1391                         return Clipboard.Item;
1392 #endif
1393                 }
1394
1395                 public void ClipboardStore (IntPtr handle, object obj, int type, XplatUI.ObjectToClipboard converter)
1396                 {
1397                         Clipboard.Item = obj;
1398                         Clipboard.Type = type;
1399                         Clipboard.Converter = converter;
1400
1401                         if (obj != null) {
1402                                 Xlib.XSetSelectionOwner (display, Atoms.CLIPBOARD, FosterParent.Handle, IntPtr.Zero);
1403                         } else {
1404                                 // Clearing the selection
1405                                 Xlib.XSetSelectionOwner (display, Atoms.CLIPBOARD, IntPtr.Zero, IntPtr.Zero);
1406                         }
1407                 }
1408
1409
1410                 public PaintEventArgs PaintEventStart (IntPtr handle, bool client)
1411                 {
1412                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
1413
1414                         if (Caret.Visible == true) {
1415                                 Caret.Paused = true;
1416                                 HideCaret();
1417                         }
1418
1419                         return hwnd.PaintEventStart (client);
1420                 }
1421
1422                 public void PaintEventEnd (IntPtr handle, bool client)
1423                 {
1424                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
1425
1426                         hwnd.PaintEventEnd (client);
1427
1428                         if (Caret.Visible == true) {
1429                                 ShowCaret();
1430                                 Caret.Paused = false;
1431                         }
1432                 }
1433
1434                 public void SetCursor (IntPtr handle, IntPtr cursor)
1435                 {
1436                         Hwnd    hwnd;
1437
1438                         if (OverrideCursorHandle == IntPtr.Zero) {
1439                                 if ((LastCursorWindow == handle) && (LastCursorHandle == cursor))
1440                                         return;
1441
1442                                 LastCursorHandle = cursor;
1443                                 LastCursorWindow = handle;
1444
1445                                 hwnd = Hwnd.ObjectFromHandle(handle);
1446                                 if (cursor != IntPtr.Zero)
1447                                         Xlib.XDefineCursor (display, hwnd.whole_window, cursor);
1448                                 else
1449                                         Xlib.XUndefineCursor (display, hwnd.whole_window);
1450                                 Xlib.XFlush (display);
1451                         }
1452                         else {
1453                                 hwnd = Hwnd.ObjectFromHandle(handle);
1454                                 Xlib.XDefineCursor (display, hwnd.whole_window, OverrideCursorHandle);
1455                         }
1456                 }
1457
1458                 public DragDropEffects StartDrag (IntPtr handle, object data,
1459                                                   DragDropEffects allowed_effects)
1460                 {
1461                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle (handle);
1462
1463                         if (hwnd == null)
1464                                 throw new ArgumentException ("Attempt to begin drag from invalid window handle (" + handle.ToInt32 () + ").");
1465
1466                         return Dnd.StartDrag (hwnd.ClientWindow, data, allowed_effects);
1467                 }
1468
1469                 public X11Atoms Atoms {
1470                         get { return atoms; }
1471                 }
1472
1473                 public int CurrentTimestamp {
1474                         get {
1475                                 TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
1476
1477                                 return (int) t.TotalSeconds;
1478                         }
1479                 }
1480
1481                 public Size CursorSize {
1482                         get {
1483                                 int     x;
1484                                 int     y;
1485
1486                                 if (Xlib.XQueryBestCursor (display, RootWindow.Handle, 32, 32, out x, out y) != 0) {
1487                                         return new Size (x, y);
1488                                 } else {
1489                                         return new Size (16, 16);
1490                                 }
1491                         }
1492                 } 
1493
1494                 public IntPtr Handle {
1495                         get { return display; }
1496                 }
1497
1498                 public Size IconSize {
1499                         get {
1500                                 IntPtr          list;
1501                                 XIconSize       size;
1502                                 int             count;
1503
1504                                 if (Xlib.XGetIconSizes (display, RootWindow.Handle, out list, out count) != 0) {
1505                                         long            current;
1506                                         int             largest;
1507
1508                                         current = (long)list;
1509                                         largest = 0;
1510
1511                                         size = new XIconSize();
1512
1513                                         for (int i = 0; i < count; i++) {
1514                                                 size = (XIconSize)Marshal.PtrToStructure((IntPtr)current, size.GetType());
1515                                                 current += Marshal.SizeOf(size);
1516
1517                                                 // Look for our preferred size
1518                                                 if (size.min_width == 32) {
1519                                                         Xlib.XFree(list);
1520                                                         return new Size(32, 32);
1521                                                 }
1522
1523                                                 if (size.max_width == 32) {
1524                                                         Xlib.XFree(list);
1525                                                         return new Size(32, 32);
1526                                                 }
1527
1528                                                 if (size.min_width < 32 && size.max_width > 32) {
1529                                                         int     x;
1530
1531                                                         // check if we can fit one
1532                                                         x = size.min_width;
1533                                                         while (x < size.max_width) {
1534                                                                 x += size.width_inc;
1535                                                                 if (x == 32) {
1536                                                                         Xlib.XFree(list);
1537                                                                         return new Size(32, 32);
1538                                                                 }
1539                                                         }
1540                                                 }
1541
1542                                                 if (largest < size.max_width) {
1543                                                         largest = size.max_width;
1544                                                 }
1545                                         }
1546
1547                                         // We didn't find a match or we wouldn't be here
1548                                         return new Size(largest, largest);
1549
1550                                 } else {
1551                                         return new Size(32, 32);
1552                                 }
1553                         }
1554                 } 
1555
1556                 public int KeyboardSpeed {
1557                         get {
1558                                 //
1559                                 // A lot harder: need to do:
1560                                 // XkbQueryExtension(0x08051008, 0xbfffdf4c, 0xbfffdf50, 0xbfffdf54, 0xbfffdf58)       = 1
1561                                 // XkbAllocKeyboard(0x08051008, 0xbfffdf4c, 0xbfffdf50, 0xbfffdf54, 0xbfffdf58)        = 0x080517a8
1562                                 // XkbGetControls(0x08051008, 1, 0x080517a8, 0xbfffdf54, 0xbfffdf58)                   = 0
1563                                 //
1564                                 // And from that we can tell the repetition rate
1565                                 //
1566                                 // Notice, the values must map to:
1567                                 //   [0, 31] which maps to 2.5 to 30 repetitions per second.
1568                                 //
1569                                 return 0;
1570                         }
1571                 }
1572
1573                 public int KeyboardDelay {
1574                         get {
1575                                 //
1576                                 // Return values must range from 0 to 4, 0 meaning 250ms,
1577                                 // and 4 meaning 1000 ms.
1578                                 //
1579                                 return 1; // ie, 500 ms
1580                         }
1581                 } 
1582
1583                 public int DefaultScreen {
1584                         get { return Xlib.XDefaultScreen (display); }
1585                 }
1586
1587                 public IntPtr DefaultColormap {
1588                         // XXX multiscreen
1589                         get { return Xlib.XDefaultColormap (display, DefaultScreen); }
1590                 }
1591
1592                 public Keys ModifierKeys {
1593                         get { return Keyboard.ModifierKeys; }
1594                 }
1595
1596                 public IntPtr OverrideCursor {
1597                         get { return OverrideCursorHandle; }
1598                         set { OverrideCursorHandle = value; }
1599                 }
1600
1601                 public X11RootHwnd RootWindow {
1602                         get { return root_hwnd; }
1603                 }
1604
1605                 public Size SmallIconSize {
1606                         get {
1607                                 IntPtr          list;
1608                                 XIconSize       size;
1609                                 int             count;
1610
1611                                 if (Xlib.XGetIconSizes (display, RootWindow.Handle, out list, out count) != 0) {
1612                                         long            current;
1613                                         int             smallest;
1614
1615                                         current = (long)list;
1616                                         smallest = 0;
1617
1618                                         size = new XIconSize();
1619
1620                                         for (int i = 0; i < count; i++) {
1621                                                 size = (XIconSize)Marshal.PtrToStructure((IntPtr)current, size.GetType());
1622                                                 current += Marshal.SizeOf(size);
1623
1624                                                 // Look for our preferred size
1625                                                 if (size.min_width == 16) {
1626                                                         Xlib.XFree(list);
1627                                                         return new Size(16, 16);
1628                                                 }
1629
1630                                                 if (size.max_width == 16) {
1631                                                         Xlib.XFree(list);
1632                                                         return new Size(16, 16);
1633                                                 }
1634
1635                                                 if (size.min_width < 16 && size.max_width > 16) {
1636                                                         int     x;
1637
1638                                                         // check if we can fit one
1639                                                         x = size.min_width;
1640                                                         while (x < size.max_width) {
1641                                                                 x += size.width_inc;
1642                                                                 if (x == 16) {
1643                                                                         Xlib.XFree(list);
1644                                                                         return new Size(16, 16);
1645                                                                 }
1646                                                         }
1647                                                 }
1648
1649                                                 if (smallest == 0 || smallest > size.min_width) {
1650                                                         smallest = size.min_width;
1651                                                 }
1652                                         }
1653
1654                                         // We didn't find a match or we wouldn't be here
1655                                         return new Size(smallest, smallest);
1656
1657                                 } else {
1658                                         return new Size(16, 16);
1659                                 }
1660                         }
1661                 } 
1662
1663                 public X11Hwnd FosterParent {
1664                         get { return foster_hwnd; }
1665                 }
1666
1667                 public int MouseHoverTime {
1668                         get { return HoverState.Interval; }
1669                 }
1670
1671                 public Rectangle WorkingArea {
1672                         get {
1673                                 IntPtr actual_atom;
1674                                 int actual_format;
1675                                 IntPtr nitems;
1676                                 IntPtr bytes_after;
1677                                 IntPtr prop = IntPtr.Zero;
1678                                 int width;
1679                                 int height;
1680                                 int current_desktop;
1681                                 int x;
1682                                 int y;
1683
1684                                 Xlib.XGetWindowProperty (display, RootWindow.Handle, 
1685                                                          Atoms._NET_CURRENT_DESKTOP, IntPtr.Zero, new IntPtr(1), false, Atoms.XA_CARDINAL,
1686                                                          out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1687
1688                                 if ((long)nitems < 1) {
1689                                         goto failsafe;
1690                                 }
1691
1692                                 current_desktop = Marshal.ReadIntPtr(prop, 0).ToInt32();
1693                                 Xlib.XFree(prop);
1694
1695                                 Xlib.XGetWindowProperty (display, RootWindow.Handle,
1696                                                          Atoms._NET_WORKAREA, IntPtr.Zero, new IntPtr (256), false, Atoms.XA_CARDINAL,
1697                                                          out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1698
1699                                 if ((long)nitems < 4 * current_desktop) {
1700                                         goto failsafe;
1701                                 }
1702
1703                                 x = Marshal.ReadIntPtr(prop, IntPtr.Size * 4 * current_desktop).ToInt32();
1704                                 y = Marshal.ReadIntPtr(prop, IntPtr.Size * 4 * current_desktop + IntPtr.Size).ToInt32();
1705                                 width = Marshal.ReadIntPtr(prop, IntPtr.Size * 4 * current_desktop + IntPtr.Size * 2).ToInt32();
1706                                 height = Marshal.ReadIntPtr(prop, IntPtr.Size * 4 * current_desktop + IntPtr.Size * 3).ToInt32();
1707                                 Xlib.XFree(prop);
1708
1709                                 return new Rectangle(x, y, width, height);
1710
1711                         failsafe:
1712                                 XWindowAttributes attributes = new XWindowAttributes();
1713
1714                                 Xlib.XGetWindowAttributes (display, RootWindow.Handle, ref attributes);
1715
1716                                 return new Rectangle(0, 0, attributes.width, attributes.height);
1717                         }
1718                 }
1719
1720                 private void XEventThread ()
1721                 {
1722                         while (true) {
1723 #if __MonoCS__
1724                                 Syscall.poll (pollfds, 1U, -1);
1725
1726                                 while (Xlib.XPending (display) > 0) {
1727 #endif
1728                                         XEvent xevent = new XEvent ();
1729                                         Xlib.XNextEvent (display, ref xevent);
1730
1731                                         X11Hwnd hwnd = (X11Hwnd)Hwnd.GetObjectFromWindow(xevent.AnyEvent.window);
1732                                         if (hwnd != null)
1733                                                 hwnd.EnqueueEvent (xevent);
1734 #if __MonoCS__
1735                                 }
1736 #endif
1737                         }
1738                 }
1739
1740                 private void RedirectMsgToEnabledAncestor (X11Hwnd hwnd, MSG msg, IntPtr window,
1741                                                            ref int event_x, ref int event_y)
1742                 {
1743                         int x, y;
1744
1745                         IntPtr dummy;
1746                         msg.hwnd = hwnd.EnabledHwnd;
1747                         Xlib.XTranslateCoordinates (display, window,
1748                                                     Hwnd.ObjectFromHandle(msg.hwnd).ClientWindow,
1749                                                     event_x, event_y,
1750                                                     out x, out y, out dummy);
1751                         event_x = x;
1752                         event_y = y;
1753                         msg.lParam = (IntPtr)(MousePosition.Y << 16 | MousePosition.X);
1754                 }
1755
1756
1757                 // This is called from the thread owning the corresponding X11ThreadQueue
1758                 [MonoTODO("Implement filtering")]
1759                 public bool GetMessage (object queue_id, ref MSG msg, IntPtr handle, int wFilterMin, int wFilterMax)
1760                 {
1761                         X11ThreadQueue queue = (X11ThreadQueue)queue_id;
1762                         XEvent xevent;
1763                         bool client;
1764                         bool got_xevent;
1765                         X11Hwnd hwnd;
1766
1767                         do {
1768                         ProcessNextMessage:
1769                                 got_xevent = queue.Dequeue (out xevent);
1770
1771                                 if (got_xevent) {
1772                                         hwnd = (X11Hwnd)Hwnd.GetObjectFromWindow (xevent.AnyEvent.window);
1773
1774                                         // Handle messages for windows that are already or are about to be destroyed.
1775
1776                                         // we need a special block for this because unless we remove the hwnd from the paint
1777                                         // queue it will always stay there (since we don't handle the expose), and we'll
1778                                         // effectively loop infinitely trying to repaint a non-existant window.
1779                                         if (hwnd != null && hwnd.zombie && xevent.type == XEventName.Expose) {
1780                                                 hwnd.PendingExpose = hwnd.PendingNCExpose = false;
1781                                                 goto ProcessNextMessage;
1782                                         }
1783
1784                                         // We need to make sure we only allow DestroyNotify events through for zombie
1785                                         // hwnds, since much of the event handling code makes requests using the hwnd's
1786                                         // ClientWindow, and that'll result in BadWindow errors if there's some lag
1787                                         // between the XDestroyWindow call and the DestroyNotify event.
1788                                         if (hwnd == null || hwnd.zombie) {
1789                                                 #if DriverDebug || DriverDebugDestroy
1790                                                 Console.WriteLine("GetMessage(): Got message {0} for non-existent or already destroyed window {1:X}",
1791                                                                   xevent.type, xevent.AnyEvent.window.ToInt32());
1792                                                 #endif
1793                                                 goto ProcessNextMessage;
1794                                         }
1795
1796                                         client = hwnd.ClientWindow == xevent.AnyEvent.window;
1797
1798                                         msg.hwnd = hwnd.Handle;
1799
1800                                         switch (xevent.type) {
1801                                         case XEventName.KeyPress:
1802                                                 Keyboard.KeyEvent (FocusWindow.Handle, xevent, ref msg);
1803                                                 return true;
1804
1805                                         case XEventName.KeyRelease:
1806                                                 Keyboard.KeyEvent (FocusWindow.Handle, xevent, ref msg);
1807                                                 return true;
1808
1809                                         case XEventName.ButtonPress: {
1810                                                 switch(xevent.ButtonEvent.button) {
1811                                                 case 1:
1812                                                         MouseState |= MouseButtons.Left;
1813                                                         if (client) {
1814                                                                 msg.message = Msg.WM_LBUTTONDOWN;
1815                                                         } else {
1816                                                                 msg.message = Msg.WM_NCLBUTTONDOWN;
1817                                                                 hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1818                                                         }
1819                                                         // TODO: For WM_NCLBUTTONDOWN wParam specifies a hit-test value not the virtual keys down
1820                                                         msg.wParam=GetMousewParam(0);
1821                                                         break;
1822
1823                                                 case 2:
1824                                                         MouseState |= MouseButtons.Middle;
1825                                                         if (client) {
1826                                                                 msg.message = Msg.WM_MBUTTONDOWN;
1827                                                         } else {
1828                                                                 msg.message = Msg.WM_NCMBUTTONDOWN;
1829                                                                 hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1830                                                         }
1831                                                         msg.wParam=GetMousewParam(0);
1832                                                         break;
1833
1834                                                 case 3:
1835                                                         MouseState |= MouseButtons.Right;
1836                                                         if (client) {
1837                                                                 msg.message = Msg.WM_RBUTTONDOWN;
1838                                                         } else {
1839                                                                 msg.message = Msg.WM_NCRBUTTONDOWN;
1840                                                                 hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1841                                                         }
1842                                                         msg.wParam=GetMousewParam(0);
1843                                                         break;
1844
1845                                                 case 4:
1846                                                         msg.hwnd = FocusWindow.Handle;
1847                                                         msg.message=Msg.WM_MOUSEWHEEL;
1848                                                         msg.wParam=GetMousewParam(120);
1849                                                         break;
1850
1851                                                 case 5:
1852                                                         msg.hwnd = FocusWindow.Handle;
1853                                                         msg.message=Msg.WM_MOUSEWHEEL;
1854                                                         msg.wParam=GetMousewParam(-120);
1855                                                         break;
1856                                                 }
1857
1858                                                 msg.lParam=(IntPtr) (xevent.ButtonEvent.y << 16 | xevent.ButtonEvent.x);
1859                                                 MousePosition.X = xevent.ButtonEvent.x;
1860                                                 MousePosition.Y = xevent.ButtonEvent.y;
1861
1862                                                 if (!hwnd.Enabled) {
1863                                                         RedirectMsgToEnabledAncestor (hwnd, msg, xevent.AnyEvent.window,
1864                                                                                       ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1865                                                 }
1866
1867                                                 if (Grab.Hwnd != IntPtr.Zero)
1868                                                         msg.hwnd = Grab.Hwnd;
1869
1870                                                 if (ClickPending.Pending &&
1871                                                     ((((long)xevent.ButtonEvent.time - ClickPending.Time) < DoubleClickInterval) &&
1872                                                      (msg.wParam == ClickPending.wParam) &&
1873                                                      (msg.lParam == ClickPending.lParam) &&
1874                                                      (msg.message == ClickPending.Message))) {
1875                                                         // Looks like a genuine double click, clicked twice on the same spot with the same keys
1876                                                         switch(xevent.ButtonEvent.button) {
1877                                                         case 1:
1878                                                                 msg.message = client ? Msg.WM_LBUTTONDBLCLK : Msg.WM_NCLBUTTONDBLCLK;
1879                                                                 break;
1880
1881                                                         case 2:
1882                                                                 msg.message = client ? Msg.WM_MBUTTONDBLCLK : Msg.WM_NCMBUTTONDBLCLK;
1883                                                                 break;
1884
1885                                                         case 3:
1886                                                                 msg.message = client ? Msg.WM_RBUTTONDBLCLK : Msg.WM_NCRBUTTONDBLCLK;
1887                                                                 break;
1888                                                         }
1889
1890                                                         ClickPending.Pending = false;
1891
1892                                                 }
1893                                                 else {
1894                                                         ClickPending.Pending = true;
1895                                                         ClickPending.Hwnd = msg.hwnd;
1896                                                         ClickPending.Message = msg.message;
1897                                                         ClickPending.wParam = msg.wParam;
1898                                                         ClickPending.lParam = msg.lParam;
1899                                                         ClickPending.Time = (long)xevent.ButtonEvent.time;
1900                                                 }
1901
1902                                                 return true;
1903                                         }
1904
1905                                         case XEventName.ButtonRelease:
1906                                                 if (Dnd.InDrag()) {
1907                                                         Dnd.HandleButtonRelease (ref xevent);
1908                                                         return true;
1909                                                 }
1910
1911                                                 switch(xevent.ButtonEvent.button) {
1912                                                 case 1:
1913                                                         if (client) {
1914                                                                 msg.message = Msg.WM_LBUTTONUP;
1915                                                         } else {
1916                                                                 msg.message = Msg.WM_NCLBUTTONUP;
1917                                                                 hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1918                                                         }
1919                                                         MouseState &= ~MouseButtons.Left;
1920                                                         msg.wParam=GetMousewParam(0);
1921                                                         break;
1922
1923                                                 case 2:
1924                                                         if (client) {
1925                                                                 msg.message = Msg.WM_MBUTTONUP;
1926                                                         } else {
1927                                                                 msg.message = Msg.WM_NCMBUTTONUP;
1928                                                                 hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1929                                                         }
1930                                                         MouseState &= ~MouseButtons.Middle;
1931                                                         msg.wParam=GetMousewParam(0);
1932                                                         break;
1933
1934                                                 case 3:
1935                                                         if (client) {
1936                                                                 msg.message = Msg.WM_RBUTTONUP;
1937                                                         } else {
1938                                                                 msg.message = Msg.WM_NCRBUTTONUP;
1939                                                                 hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1940                                                         }
1941                                                         MouseState &= ~MouseButtons.Right;
1942                                                         msg.wParam=GetMousewParam(0);
1943                                                         break;
1944
1945                                                 case 4:
1946                                                         goto ProcessNextMessage;
1947
1948                                                 case 5:
1949                                                         goto ProcessNextMessage;
1950                                                 }
1951
1952                                                 if (!hwnd.Enabled) {
1953                                                         RedirectMsgToEnabledAncestor (hwnd, msg, xevent.AnyEvent.window,
1954                                                                                       ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1955                                                 }
1956
1957                                                 if (Grab.Hwnd != IntPtr.Zero)
1958                                                         msg.hwnd = Grab.Hwnd;
1959
1960                                                 msg.lParam=(IntPtr) (xevent.ButtonEvent.y << 16 | xevent.ButtonEvent.x);
1961                                                 MousePosition.X = xevent.ButtonEvent.x;
1962                                                 MousePosition.Y = xevent.ButtonEvent.y;
1963                                                 return true;
1964
1965                                         case XEventName.MotionNotify:
1966                                                 /* XXX move the compression stuff here */
1967
1968                                                 if (client) {
1969                                                         #if DriverDebugExtra
1970                                                         Console.WriteLine("GetMessage(): Window {0:X} MotionNotify x={1} y={2}",
1971                                                                           client ? hwnd.ClientWindow.ToInt32() : hwnd.WholeWindow.ToInt32(),
1972                                                                           xevent.MotionEvent.x, xevent.MotionEvent.y);
1973                                                         #endif
1974
1975                                                         if (Dnd.HandleMotionNotify (ref xevent))
1976                                                                 goto ProcessNextMessage;
1977
1978                                                         if (Grab.Hwnd != IntPtr.Zero)
1979                                                                 msg.hwnd = Grab.Hwnd;
1980                                                         else
1981                                                                 NativeWindow.WndProc(msg.hwnd, Msg.WM_SETCURSOR, msg.hwnd, (IntPtr)HitTest.HTCLIENT);
1982
1983                                                         msg.message = Msg.WM_MOUSEMOVE;
1984                                                         msg.wParam = GetMousewParam(0);
1985                                                         msg.lParam = (IntPtr) (xevent.MotionEvent.y << 16 | xevent.MotionEvent.x & 0xFFFF);
1986
1987                                                         if (!hwnd.Enabled) {
1988                                                                 RedirectMsgToEnabledAncestor (hwnd, msg, xevent.AnyEvent.window,
1989                                                                                               ref xevent.MotionEvent.x, ref xevent.MotionEvent.y);
1990                                                         }
1991
1992                                                         MousePosition.X = xevent.MotionEvent.x;
1993                                                         MousePosition.Y = xevent.MotionEvent.y;
1994
1995                                                         if ((HoverState.Timer.Enabled) &&
1996                                                             (((MousePosition.X + HoverState.Size.Width) < HoverState.X) ||
1997                                                              ((MousePosition.X - HoverState.Size.Width) > HoverState.X) ||
1998                                                              ((MousePosition.Y + HoverState.Size.Height) < HoverState.Y) ||
1999                                                              ((MousePosition.Y - HoverState.Size.Height) > HoverState.Y))) {
2000
2001                                                                 HoverState.Timer.Stop();
2002                                                                 HoverState.Timer.Start();
2003                                                                 HoverState.X = MousePosition.X;
2004                                                                 HoverState.Y = MousePosition.Y;
2005                                                         }
2006                                                 }
2007                                                 else {
2008                                                         HitTest ht;
2009                                                         IntPtr dummy;
2010                                                         int screen_x;
2011                                                         int screen_y;
2012
2013                                                         #if DriverDebugExtra
2014                                                         Console.WriteLine("GetMessage(): non-client area {0:X} MotionNotify x={1} y={2}",
2015                                                                           client ? hwnd.ClientWindow.ToInt32() : hwnd.WholeWindow.ToInt32(),
2016                                                                           xevent.MotionEvent.x, xevent.MotionEvent.y);
2017                                                         #endif
2018                                                         msg.message = Msg.WM_NCMOUSEMOVE;
2019
2020                                                         if (!hwnd.Enabled) {
2021                                                                 RedirectMsgToEnabledAncestor (hwnd, msg, xevent.AnyEvent.window,
2022                                                                                               ref xevent.MotionEvent.x, ref xevent.MotionEvent.y);
2023                                                         }
2024
2025                                                         // The hit test is sent in screen coordinates
2026                                                         Xlib.XTranslateCoordinates (display, xevent.AnyEvent.window, RootWindow.Handle,
2027                                                                                     xevent.MotionEvent.x, xevent.MotionEvent.y,
2028                                                                                     out screen_x, out screen_y, out dummy);
2029
2030                                                         msg.lParam = (IntPtr) (screen_y << 16 | screen_x & 0xFFFF);
2031                                                         ht = (HitTest)NativeWindow.WndProc (hwnd.ClientWindow, Msg.WM_NCHITTEST,
2032                                                                                             IntPtr.Zero, msg.lParam).ToInt32 ();
2033                                                         NativeWindow.WndProc(hwnd.ClientWindow, Msg.WM_SETCURSOR, msg.hwnd, (IntPtr)ht);
2034
2035                                                         MousePosition.X = xevent.MotionEvent.x;
2036                                                         MousePosition.Y = xevent.MotionEvent.y;
2037                                                 }
2038
2039                                                 return true;
2040
2041                                         case XEventName.EnterNotify:
2042                                                 if (!hwnd.Enabled)
2043                                                         goto ProcessNextMessage;
2044
2045                                                 if (xevent.CrossingEvent.mode != NotifyMode.NotifyNormal)
2046                                                         goto ProcessNextMessage;
2047
2048                                                 msg.message = Msg.WM_MOUSE_ENTER;
2049                                                 HoverState.X = xevent.CrossingEvent.x;
2050                                                 HoverState.Y = xevent.CrossingEvent.y;
2051                                                 HoverState.Timer.Enabled = true;
2052                                                 HoverState.Window = xevent.CrossingEvent.window;
2053
2054                                                 return true;
2055
2056                                         case XEventName.LeaveNotify:
2057                                                 if (!hwnd.Enabled)
2058                                                         goto ProcessNextMessage;
2059
2060                                                 if ((xevent.CrossingEvent.mode != NotifyMode.NotifyNormal) ||
2061                                                     (xevent.CrossingEvent.window != hwnd.ClientWindow))
2062                                                         goto ProcessNextMessage;
2063
2064                                                 msg.message=Msg.WM_MOUSE_LEAVE;
2065                                                 HoverState.Timer.Enabled = false;
2066                                                 HoverState.Window = IntPtr.Zero;
2067
2068                                                 return true;
2069
2070                                         case XEventName.ReparentNotify:
2071                                                 if (hwnd.parent == null) {      // Toplevel
2072                                                         if ((xevent.ReparentEvent.parent != IntPtr.Zero) && (xevent.ReparentEvent.window == hwnd.WholeWindow)) {
2073                                                                 // We need to adjust x/y
2074                                                                 // This sucks ass, part 2
2075                                                                 // Every WM does the reparenting of toplevel windows different, so there's
2076                                                                 // no standard way of getting our adjustment considering frames/decorations
2077                                                                 // The code below is needed for metacity. KDE doesn't works just fine without this
2078                                                                 int     dummy_int;
2079                                                                 IntPtr  dummy_ptr;
2080                                                                 int     new_x;
2081                                                                 int     new_y;
2082                                                                 int     frame_left;
2083                                                                 int     frame_top;
2084
2085                                                                 hwnd.Reparented = true;
2086
2087                                                                 Xlib.XGetGeometry(display, XGetParent(hwnd.WholeWindow),
2088                                                                                   out dummy_ptr, out new_x, out new_y,
2089                                                                                   out dummy_int, out dummy_int, out dummy_int, out dummy_int);
2090                                                                 hwnd.FrameExtents(out frame_left, out frame_top);
2091                                                                 if ((frame_left != 0) && (frame_top != 0) && (new_x != frame_left) && (new_y != frame_top)) {
2092                                                                         hwnd.x = new_x;
2093                                                                         hwnd.y = new_y;
2094                                                                         hwnd.whacky_wm = true;
2095                                                                 }
2096
2097                                                                 if (hwnd.opacity != 0xffffffff) {
2098                                                                         IntPtr opacity;
2099
2100                                                                         opacity = (IntPtr)(Int32)hwnd.opacity;
2101                                                                         Xlib.XChangeProperty (display, XGetParent(hwnd.WholeWindow),
2102                                                                                               Atoms._NET_WM_WINDOW_OPACITY, Atoms.XA_CARDINAL, 32,
2103                                                                                               PropertyMode.Replace, ref opacity, 1);
2104                                                                 }
2105                                                                 SendMessage(msg.hwnd, Msg.WM_WINDOWPOSCHANGED, msg.wParam, msg.lParam);
2106                                                                 goto ProcessNextMessage;
2107                                                         } else {
2108                                                                 hwnd.Reparented = false;
2109                                                                 goto ProcessNextMessage;
2110                                                         }
2111                                                 }
2112                                                 goto ProcessNextMessage;
2113
2114                                         case XEventName.ConfigureNotify:
2115                                                 hwnd.AddConfigureNotify (xevent);
2116                                                 goto ProcessNextMessage;
2117
2118                                         case XEventName.FocusIn:
2119                                                 // We received focus. We use X11 focus only to know if the app window does or does not have focus
2120                                                 // We do not track the actual focussed window via it. Instead, this is done via FocusWindow internally
2121                                                 // Receiving focus means we've gotten activated and therefore we need to let the actual FocusWindow know 
2122                                                 // about it having focus again
2123                                                 if (xevent.FocusChangeEvent.detail != NotifyDetail.NotifyNonlinear)
2124                                                         goto ProcessNextMessage;
2125
2126                                                 if (FocusWindow == null) {
2127                                                         Control c = Control.FromHandle (hwnd.ClientWindow);
2128                                                         if (c == null)
2129                                                                 goto ProcessNextMessage;
2130                                                         Form form = c.FindForm ();
2131                                                         if (form == null)
2132                                                                 goto ProcessNextMessage;
2133                                                         ActiveWindow = (X11Hwnd)Hwnd.ObjectFromHandle (form.Handle);
2134                                                         SendMessage (ActiveWindow.Handle, Msg.WM_ACTIVATE, (IntPtr) WindowActiveFlags.WA_ACTIVE, IntPtr.Zero);
2135                                                         goto ProcessNextMessage;
2136                                                 }
2137                                                 Keyboard.FocusIn(FocusWindow.Handle);
2138                                                 SendMessage(FocusWindow.Handle, Msg.WM_SETFOCUS, IntPtr.Zero, IntPtr.Zero);
2139                                                 goto ProcessNextMessage;
2140
2141                                         case XEventName.FocusOut:
2142                                                 // Se the comment for our FocusIn handler
2143                                                 if (xevent.FocusChangeEvent.detail != NotifyDetail.NotifyNonlinear)
2144                                                         goto ProcessNextMessage;
2145
2146                                                 if (FocusWindow == null)
2147                                                         goto ProcessNextMessage;
2148
2149                                                 Keyboard.FocusOut(FocusWindow.Handle);
2150
2151                                                 while (Keyboard.ResetKeyState(FocusWindow.Handle, ref msg))
2152                                                         SendMessage(FocusWindow.Handle, msg.message, msg.wParam, msg.lParam);
2153
2154                                                 SendMessage(FocusWindow.Handle, Msg.WM_KILLFOCUS, IntPtr.Zero, IntPtr.Zero);
2155                                                 goto ProcessNextMessage;
2156
2157                                         case XEventName.Expose:
2158                                                 hwnd.AddExpose (client,
2159                                                                 xevent.ExposeEvent.x, xevent.ExposeEvent.y,
2160                                                                 xevent.ExposeEvent.width, xevent.ExposeEvent.height);
2161                                                 goto ProcessNextMessage;
2162                                                 
2163                                         case XEventName.DestroyNotify:
2164
2165                                                 // This is a bit tricky, we don't receive our own DestroyNotify, we only get those for our children
2166                                                 hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(xevent.DestroyWindowEvent.window);
2167
2168                                                 // We may get multiple for the same window, act only one the first (when Hwnd still knows about it)
2169                                                 if ((hwnd != null) && (hwnd.ClientWindow == xevent.DestroyWindowEvent.window)) {
2170                                                         CleanupCachedWindows (hwnd);
2171
2172                                                         #if DriverDebugDestroy
2173                                                         Console.WriteLine("Received X11 Destroy Notification for {0}", XplatUI.Window(hwnd.ClientWindow));
2174                                                         #endif
2175
2176                                                         msg.hwnd = hwnd.ClientWindow;
2177                                                         msg.message=Msg.WM_DESTROY;
2178                                                         hwnd.Dispose();
2179                                                 }
2180                                                 else
2181                                                         goto ProcessNextMessage;
2182
2183                                                 return true;
2184
2185                                         case XEventName.ClientMessage:
2186                                                 if (Dnd.HandleClientMessage (ref xevent))
2187                                                         goto ProcessNextMessage;
2188
2189                                                 if (xevent.ClientMessageEvent.message_type == Atoms.AsyncAtom) {
2190                                                         XplatUIDriverSupport.ExecuteClientMessage((GCHandle)xevent.ClientMessageEvent.ptr1);
2191                                                         goto ProcessNextMessage;
2192                                                 }
2193
2194                                                 if (xevent.ClientMessageEvent.message_type == HoverState.Atom) {
2195                                                         msg.message = Msg.WM_MOUSEHOVER;
2196                                                         msg.wParam = GetMousewParam(0);
2197                                                         msg.lParam = (IntPtr) (xevent.ClientMessageEvent.ptr1);
2198                                                         return true;
2199                                                 }
2200
2201                                                 if (xevent.ClientMessageEvent.message_type == Atoms.PostAtom) {
2202                                                         msg.hwnd = xevent.ClientMessageEvent.ptr1;
2203                                                         msg.message = (Msg) xevent.ClientMessageEvent.ptr2.ToInt32 ();
2204                                                         msg.wParam = xevent.ClientMessageEvent.ptr3;
2205                                                         msg.lParam = xevent.ClientMessageEvent.ptr4;
2206                                                         return true;
2207                                                 }
2208
2209                                                 if (xevent.ClientMessageEvent.message_type == Atoms._XEMBED) {
2210                                                         #if DriverDebugXEmbed
2211                                                         Console.WriteLine("GOT EMBED MESSAGE {0:X}, detail {1:X}",
2212                                                                           xevent.ClientMessageEvent.ptr2.ToInt32(), xevent.ClientMessageEvent.ptr3.ToInt32());
2213                                                         #endif
2214
2215                                                         if (xevent.ClientMessageEvent.ptr2.ToInt32() == (int)XEmbedMessage.EmbeddedNotify) {
2216                                                                 XSizeHints hints = new XSizeHints();
2217                                                                 IntPtr dummy;
2218
2219                                                                 Xlib.XGetWMNormalHints (display, hwnd.WholeWindow, ref hints, out dummy);
2220
2221                                                                 hwnd.width = hints.max_width;
2222                                                                 hwnd.height = hints.max_height;
2223                                                                 hwnd.ClientRect = Rectangle.Empty;
2224                                                                 SendMessage(msg.hwnd, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
2225                                                         }
2226                                                 }
2227
2228                                                 if (xevent.ClientMessageEvent.message_type == Atoms.WM_PROTOCOLS) {
2229                                                         if (xevent.ClientMessageEvent.ptr1 == Atoms.WM_DELETE_WINDOW) {
2230                                                                 msg.message = Msg.WM_CLOSE;
2231                                                                 return true;
2232                                                         }
2233
2234                                                         // We should not get this, but I'll leave the code in case we need it in the future
2235                                                         if (xevent.ClientMessageEvent.ptr1 == Atoms.WM_TAKE_FOCUS) {
2236                                                                 goto ProcessNextMessage;
2237                                                         }
2238                                                 }
2239                                                 goto ProcessNextMessage;
2240
2241                                         case XEventName.PropertyNotify:
2242                                                 // The Hwnd's themselves handle this
2243                                                 hwnd.PropertyChanged (xevent);
2244                                                 goto ProcessNextMessage;
2245                                         }
2246                                 }
2247
2248                         } while (got_xevent);
2249
2250                         queue.CheckTimers ();
2251
2252                         while (queue.Configure.Count > 0) {
2253                                 xevent = queue.Configure.Dequeue ();
2254
2255                                 hwnd = (X11Hwnd)Hwnd.GetObjectFromWindow (xevent.AnyEvent.window);
2256                                 if (hwnd == null || hwnd.zombie)
2257                                         continue;
2258
2259                                 hwnd.HandleConfigureNotify (xevent);
2260                         }
2261
2262                         /* now that we've handled X events, handle any pending paint and configure events */
2263                         
2264                         while (queue.Paint.Count > 0) {
2265                                 xevent = queue.Paint.Dequeue ();
2266
2267                                 hwnd = (X11Hwnd)Hwnd.GetObjectFromWindow (xevent.AnyEvent.window);
2268                                 if (hwnd == null || hwnd.zombie)
2269                                         continue;
2270
2271                                 client = hwnd.ClientWindow == xevent.AnyEvent.window;
2272
2273                                 if (queue.PostQuitState || !hwnd.Mapped) {
2274                                         try {
2275                                                 hwnd.Queue.Lock ();
2276                                                 hwnd.PendingExpose = hwnd.PendingNCExpose = false;
2277                                                 continue;
2278                                         }
2279                                         finally {
2280                                                 hwnd.Queue.Unlock ();
2281                                         }
2282                                 }
2283
2284                                 // XXX these should really be error conditions.  if we
2285                                 // have an expose event in the queue, there should be
2286                                 // one pending.
2287                                 try {
2288                                         hwnd.Queue.Lock ();
2289                                         if (client && !hwnd.PendingExpose) {
2290                                                 Console.WriteLine ("client expose but no expose pending");
2291                                                 continue;
2292                                         }
2293                                         else if (!client && !hwnd.PendingNCExpose) {
2294                                                 Console.WriteLine ("non-client expose but no expose pending");
2295                                                 continue;
2296                                         }
2297                                 }
2298                                 finally {
2299                                         hwnd.Queue.Unlock ();
2300                                 }
2301
2302                                 msg.hwnd = hwnd.Handle;
2303
2304                                 if (client) {
2305 #if DriverDebugExtra
2306                                         Console.WriteLine("GetMessage(): Window {0:X} Exposed area {1},{2} {3}x{4}",
2307                                                           hwnd.client_window.ToInt32(),
2308                                                           xevent.ExposeEvent.x, xevent.ExposeEvent.y,
2309                                                           xevent.ExposeEvent.width, xevent.ExposeEvent.height);
2310 #endif
2311                                         msg.message = Msg.WM_PAINT;
2312                                 }
2313                                 else {
2314                                         Graphics g;
2315
2316                                         switch (hwnd.border_style) {
2317                                         case FormBorderStyle.Fixed3D:
2318                                                 g = Graphics.FromHwnd(hwnd.WholeWindow);
2319                                                 ControlPaint.DrawBorder3D(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height),
2320                                                                           Border3DStyle.Sunken);
2321                                                 g.Dispose();
2322                                                 break;
2323
2324                                         case FormBorderStyle.FixedSingle:
2325                                                 g = Graphics.FromHwnd(hwnd.WholeWindow);
2326                                                 ControlPaint.DrawBorder(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height),
2327                                                                         Color.Black, ButtonBorderStyle.Solid);
2328                                                 g.Dispose();
2329                                                 break;
2330                                         }
2331                                         #if DriverDebugExtra
2332                                         Console.WriteLine("GetMessage(): Window {0:X} Exposed non-client area {1},{2} {3}x{4}",
2333                                                           hwnd.ClientWindow.ToInt32(),
2334                                                           xevent.ExposeEvent.x, xevent.ExposeEvent.y,
2335                                                           xevent.ExposeEvent.width, xevent.ExposeEvent.height);
2336                                         #endif
2337
2338                                         Rectangle rect = new Rectangle (xevent.ExposeEvent.x, xevent.ExposeEvent.y,
2339                                                                                 xevent.ExposeEvent.width, xevent.ExposeEvent.height);
2340                                         Region region = new Region (rect);
2341                                         IntPtr hrgn = region.GetHrgn (null); // Graphics object isn't needed
2342                                         msg.message = Msg.WM_NCPAINT;
2343                                         msg.wParam = hrgn == IntPtr.Zero ? (IntPtr)1 : hrgn;
2344                                         msg.refobject = region;
2345                                 }
2346
2347                                 return true;
2348                         }
2349
2350                         if (!queue.PostQuitState) {
2351                                 msg.hwnd= IntPtr.Zero;
2352                                 msg.message = Msg.WM_ENTERIDLE;
2353                                 return true;
2354                         }
2355
2356                         // We reset ourselves so GetMessage can be called again
2357                         queue.PostQuitState = false;
2358
2359                         return false;
2360                 }
2361
2362                 [MonoTODO("Implement filtering and PM_NOREMOVE")]
2363                 public bool PeekMessage (object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, uint flags)
2364                 {
2365                         X11ThreadQueue queue = (X11ThreadQueue) queue_id;
2366                         bool    pending;
2367
2368                         if ((flags & (uint)PeekMessageFlags.PM_REMOVE) == 0) {
2369                                 throw new NotImplementedException("PeekMessage PM_NOREMOVE is not implemented yet");    // FIXME - Implement PM_NOREMOVE flag
2370                         }
2371
2372                         try {
2373                                 queue.Lock ();
2374                                 pending = false;
2375                                 if (queue.CountUnlocked > 0)
2376                                         pending = true;
2377                         }
2378                         catch {
2379                                 return false;
2380                         }
2381                         finally {
2382                                 queue.Unlock ();
2383                         }
2384
2385                         queue.CheckTimers ();
2386
2387                         if (!pending)
2388                                 return false;
2389
2390                         return GetMessage(queue_id, ref msg, hWnd, wFilterMin, wFilterMax);
2391                 }
2392
2393                 public void DoEvents (X11ThreadQueue queue)
2394                 {
2395                         MSG     msg = new MSG ();
2396
2397                         if (OverrideCursorHandle != IntPtr.Zero)
2398                                 OverrideCursorHandle = IntPtr.Zero;
2399
2400                         queue.DispatchIdle = false;
2401
2402                         while (PeekMessage(queue, ref msg, IntPtr.Zero, 0, 0, (uint)PeekMessageFlags.PM_REMOVE)) {
2403                                 TranslateMessage (ref msg);
2404                                 DispatchMessage (ref msg);
2405                         }
2406
2407                         queue.DispatchIdle = true;
2408                 }
2409         }
2410 }