* X11Display.cs: port over jackson's XplatUIX11.cs fix for DND
[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 TransparencySupport 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) ? TransparencySupport.GetSet : TransparencySupport.None;
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                 public int SendInput (IntPtr handle, Queue keys) {
559                         if (handle == IntPtr.Zero)
560                                 return 0;
561
562                         int count = keys.Count;
563                         Hwnd hwnd = Hwnd.ObjectFromHandle(handle);
564
565                         while (keys.Count > 0) {
566                         
567                                 MSG msg = (MSG)keys.Dequeue();
568
569                                 XEvent xevent = new XEvent ();
570
571                                 xevent.type = (msg.message == Msg.WM_KEYUP ? XEventName.KeyRelease : XEventName.KeyPress);
572                                 xevent.KeyEvent.display = display;
573
574                                 if (hwnd != null) {
575                                         xevent.KeyEvent.window = hwnd.whole_window;
576                                 } else {
577                                         xevent.KeyEvent.window = IntPtr.Zero;
578                                 }
579
580                                 xevent.KeyEvent.keycode = Keyboard.ToKeycode((int)msg.wParam);
581
582                                 hwnd.Queue.EnqueueLocked (xevent);
583                         }
584                         return count;
585                 }
586
587                 // FIXME - I think this should just enqueue directly
588                 public bool PostMessage (IntPtr handle, Msg message, IntPtr wparam, IntPtr lparam)
589                 {
590                         XEvent xevent = new XEvent ();
591                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
592
593                         xevent.type = XEventName.ClientMessage;
594                         xevent.ClientMessageEvent.display = display;
595
596                         if (hwnd != null) {
597                                 xevent.ClientMessageEvent.window = hwnd.WholeWindow;
598                         } else {
599                                 xevent.ClientMessageEvent.window = IntPtr.Zero;
600                         }
601
602                         xevent.ClientMessageEvent.message_type = Atoms.PostAtom;
603                         xevent.ClientMessageEvent.format = 32;
604                         xevent.ClientMessageEvent.ptr1 = handle;
605                         xevent.ClientMessageEvent.ptr2 = (IntPtr) message;
606                         xevent.ClientMessageEvent.ptr3 = wparam;
607                         xevent.ClientMessageEvent.ptr4 = lparam;
608
609                         hwnd.Queue.Enqueue (xevent);
610
611                         return true;
612                 }
613
614                 public void SendNetWMMessage (IntPtr window, IntPtr message_type, IntPtr l0, IntPtr l1, IntPtr l2)
615                 {
616                         XEvent  xev;
617
618                         xev = new XEvent();
619                         xev.ClientMessageEvent.type = XEventName.ClientMessage;
620                         xev.ClientMessageEvent.send_event = true;
621                         xev.ClientMessageEvent.window = window;
622                         xev.ClientMessageEvent.message_type = message_type;
623                         xev.ClientMessageEvent.format = 32;
624                         xev.ClientMessageEvent.ptr1 = l0;
625                         xev.ClientMessageEvent.ptr2 = l1;
626                         xev.ClientMessageEvent.ptr3 = l2;
627
628                         Xlib.XSendEvent (display, root_hwnd.Handle, false,
629                                          new IntPtr ((int) (EventMask.SubstructureRedirectMask | EventMask.SubstructureNotifyMask)), ref xev);
630                 }
631
632                 public void SendNetClientMessage (IntPtr window, IntPtr message_type, IntPtr l0, IntPtr l1, IntPtr l2)
633                 {
634                         XEvent  xev;
635
636                         xev = new XEvent();
637                         xev.ClientMessageEvent.type = XEventName.ClientMessage;
638                         xev.ClientMessageEvent.send_event = true;
639                         xev.ClientMessageEvent.window = window;
640                         xev.ClientMessageEvent.message_type = message_type;
641                         xev.ClientMessageEvent.format = 32;
642                         xev.ClientMessageEvent.ptr1 = l0;
643                         xev.ClientMessageEvent.ptr2 = l1;
644                         xev.ClientMessageEvent.ptr3 = l2;
645
646                         Xlib.XSendEvent (display, window, false, new IntPtr ((int)EventMask.NoEventMask), ref xev);
647                 }
648
649                 public bool TranslateMessage (ref MSG msg)
650                 {
651                         return Keyboard.TranslateMessage (ref msg);
652                 }
653
654                 public IntPtr DispatchMessage (ref MSG msg)
655                 {
656                         return NativeWindow.WndProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
657                 }
658
659                 private void QueryPointer (IntPtr w, out IntPtr root, out IntPtr child,
660                                            out int root_x, out int root_y, out int child_x, out int child_y,
661                                            out int mask)
662                 {
663                         /* this code was written with the help of
664                            glance at gdk.  I never would have realized we
665                            needed a loop in order to traverse down in the
666                            hierarchy.  I would have assumed you'd get the
667                            most deeply nested child and have to do
668                            XQueryTree to move back up the hierarchy..
669                            stupid me, of course. */
670                         IntPtr c;
671
672                         //                      Xlib.XGrabServer (display);
673
674                         Xlib.XQueryPointer (display, w, out root, out c,
675                                             out root_x, out root_y, out child_x, out child_y,
676                                             out mask);
677
678                         if (root != w)
679                                 c = root;
680
681                         IntPtr child_last = IntPtr.Zero;
682                         while (c != IntPtr.Zero) {
683                                 child_last = c;
684                                 Xlib.XQueryPointer (display, c, out root, out c,
685                                                     out root_x, out root_y, out child_x, out child_y,
686                                                     out mask);
687                         }
688
689                         //                      Xlib.XUngrabServer (display);
690
691                         child = child_last;
692                 }
693
694                 public void SetCursorPos (int x, int y)
695                 {
696                         IntPtr root, child;
697                         int root_x, root_y, child_x, child_y, mask;
698
699                         /* we need to do a
700                          * QueryPointer before warping
701                          * because if the warp is on
702                          * the RootWindow, the x/y are
703                          * relative to the current
704                          * mouse position
705                          */
706                         QueryPointer (RootWindow.Handle,
707                                       out root,
708                                       out child,
709                                       out root_x, out root_y,
710                                       out child_x, out child_y,
711                                       out mask);
712
713                         Xlib.XWarpPointer (display, IntPtr.Zero, IntPtr.Zero, 0, 0, 0, 0, x - root_x, y - root_y);
714
715                         Xlib.XFlush (display);
716
717                         /* then we need to a
718                          * QueryPointer after warping
719                          * to manually generate a
720                          * motion event for the window
721                          * we move into.
722                          */
723                         QueryPointer (RootWindow.Handle,
724                                       out root,
725                                       out child,
726                                       out root_x, out root_y,
727                                       out child_x, out child_y,
728                                       out mask);
729
730                         X11Hwnd child_hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(child);
731                         if (child_hwnd == null)
732                                 return;
733
734                         XEvent xevent = new XEvent ();
735
736                         xevent.type = XEventName.MotionNotify;
737                         xevent.MotionEvent.display = display;
738                         xevent.MotionEvent.window = child_hwnd.Handle;
739                         xevent.MotionEvent.root = RootWindow.Handle;
740                         xevent.MotionEvent.x = child_x;
741                         xevent.MotionEvent.y = child_y;
742                         xevent.MotionEvent.x_root = root_x;
743                         xevent.MotionEvent.y_root = root_y;
744                         xevent.MotionEvent.state = mask;
745
746                         child_hwnd.Queue.Enqueue (xevent);
747                 }
748
749                 public void SetFocus (X11Hwnd new_focus)
750                 {
751                         if (new_focus == FocusWindow)
752                                 return;
753
754                         X11Hwnd prev_focus = FocusWindow;
755                         FocusWindow = new_focus;
756
757                         if (prev_focus != null)
758                                 SendMessage (prev_focus.Handle, Msg.WM_KILLFOCUS,
759                                              FocusWindow == null ? IntPtr.Zero : FocusWindow.Handle, IntPtr.Zero);
760                         if (FocusWindow != null)
761                                 SendMessage (FocusWindow.Handle, Msg.WM_SETFOCUS,
762                                              prev_focus == null ? IntPtr.Zero : prev_focus.Handle, IntPtr.Zero);
763
764                         //XSetInputFocus(DisplayHandle, Hwnd.ObjectFromHandle(handle).ClientWindow, RevertTo.None, IntPtr.Zero);
765                 }
766
767                 public IntPtr DefineCursor (Bitmap bitmap, Bitmap mask, Color cursor_pixel, Color mask_pixel, int xHotSpot, int yHotSpot)
768                 {
769                         IntPtr  cursor;
770                         Bitmap  cursor_bitmap;
771                         Bitmap  cursor_mask;
772                         Byte[]  cursor_bits;
773                         Byte[]  mask_bits;
774                         Color   c_pixel;
775                         Color   m_pixel;
776                         int     width;
777                         int     height;
778                         IntPtr  cursor_pixmap;
779                         IntPtr  mask_pixmap;
780                         XColor  fg;
781                         XColor  bg;
782                         bool    and;
783                         bool    xor;
784
785                         if (Xlib.XQueryBestCursor (display, RootWindow.Handle, bitmap.Width, bitmap.Height, out width, out height) == 0) {
786                                 return IntPtr.Zero;
787                         }
788
789                         // Win32 only allows creation cursors of a certain size
790                         if ((bitmap.Width != width) || (bitmap.Width != height)) {
791                                 cursor_bitmap = new Bitmap(bitmap, new Size(width, height));
792                                 cursor_mask = new Bitmap(mask, new Size(width, height));
793                         } else {
794                                 cursor_bitmap = bitmap;
795                                 cursor_mask = mask;
796                         }
797
798                         width = cursor_bitmap.Width;
799                         height = cursor_bitmap.Height;
800
801                         cursor_bits = new Byte[(width / 8) * height];
802                         mask_bits = new Byte[(width / 8) * height];
803
804                         for (int y = 0; y < height; y++) {
805                                 for (int x = 0; x < width; x++) {
806                                         c_pixel = cursor_bitmap.GetPixel(x, y);
807                                         m_pixel = cursor_mask.GetPixel(x, y);
808
809                                         and = c_pixel == cursor_pixel;
810                                         xor = m_pixel == mask_pixel;
811
812                                         if (!and && !xor) {
813                                                 // Black
814                                                 // cursor_bits[y * width / 8 + x / 8] &= (byte)~((1 << (x % 8)));       // The bit already is 0
815                                                 mask_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
816                                         } else if (and && !xor) {
817                                                 // White
818                                                 cursor_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
819                                                 mask_bits[y * width / 8 + x / 8] |= (byte)(1 << (x % 8));
820 #if notneeded
821                                         } else if (and && !xor) {
822                                                 // Screen
823                                         } else if (and && xor) {
824                                                 // Inverse Screen
825
826                                                 // X11 doesn't know the 'reverse screen' concept, so we'll treat them the same
827                                                 // we want both to be 0 so nothing to be done
828                                                 //cursor_bits[y * width / 8 + x / 8] &= (byte)~((1 << (x % 8)));
829                                                 //mask_bits[y * width / 8 + x / 8] |= (byte)(01 << (x % 8));
830 #endif
831                                         }
832                                 }
833                         }
834
835                         cursor_pixmap = Xlib.XCreatePixmapFromBitmapData (display, RootWindow.Handle,
836                                                                           cursor_bits, width, height, (IntPtr)1, (IntPtr)0, 1);
837                         mask_pixmap = Xlib.XCreatePixmapFromBitmapData (display, RootWindow.Handle,
838                                                                         mask_bits, width, height, (IntPtr)1, (IntPtr)0, 1);
839                         fg = new XColor();
840                         bg = new XColor();
841
842                         fg.pixel = Xlib.XWhitePixel (display, DefaultScreen);
843                         fg.red = (ushort)65535;
844                         fg.green = (ushort)65535;
845                         fg.blue = (ushort)65535;
846
847                         bg.pixel = Xlib.XBlackPixel (display, DefaultScreen);
848
849                         cursor = Xlib.XCreatePixmapCursor (display, cursor_pixmap, mask_pixmap, ref fg, ref bg, xHotSpot, yHotSpot);
850
851                         Xlib.XFreePixmap (display, cursor_pixmap);
852                         Xlib.XFreePixmap (display, mask_pixmap);
853
854                         return cursor;
855                 }
856
857                 public IntPtr DefineStdCursor (StdCursor id)
858                 {
859                         CursorFontShape shape;
860
861                         // FIXME - define missing shapes
862
863                         switch (id) {
864                         case StdCursor.AppStarting:
865                                 shape = CursorFontShape.XC_watch;
866                                 break;
867
868                         case StdCursor.Arrow:
869                                 shape = CursorFontShape.XC_top_left_arrow;
870                                 break;
871
872                         case StdCursor.Cross:
873                                 shape = CursorFontShape.XC_crosshair;
874                                 break;
875
876                         case StdCursor.Default:
877                                 shape = CursorFontShape.XC_top_left_arrow;
878                                 break;
879
880                         case StdCursor.Hand:
881                                 shape = CursorFontShape.XC_hand1;
882                                 break;
883
884                         case StdCursor.Help:
885                                 shape = CursorFontShape.XC_question_arrow;
886                                 break;
887                         
888                         case StdCursor.HSplit:
889                                 shape = CursorFontShape.XC_sb_v_double_arrow; 
890                                 break;
891
892                         case StdCursor.IBeam:
893                                 shape = CursorFontShape.XC_xterm; 
894                                 break;
895
896                         case StdCursor.No:
897                                 shape = CursorFontShape.XC_circle; 
898                                 break;
899
900                         case StdCursor.NoMove2D:
901                                 shape = CursorFontShape.XC_fleur; 
902                                 break;
903
904                         case StdCursor.NoMoveHoriz:
905                                 shape = CursorFontShape.XC_fleur; 
906                                 break;
907
908                         case StdCursor.NoMoveVert:
909                                 shape = CursorFontShape.XC_fleur; 
910                                 break;
911
912                         case StdCursor.PanEast:
913                                 shape = CursorFontShape.XC_fleur; 
914                                 break;
915
916                         case StdCursor.PanNE:
917                                 shape = CursorFontShape.XC_fleur; 
918                                 break;
919
920                         case StdCursor.PanNorth:
921                                 shape = CursorFontShape.XC_fleur; 
922                                 break;
923
924                         case StdCursor.PanNW:
925                                 shape = CursorFontShape.XC_fleur; 
926                                 break;
927
928                         case StdCursor.PanSE:
929                                 shape = CursorFontShape.XC_fleur; 
930                                 break;
931
932                         case StdCursor.PanSouth:
933                                 shape = CursorFontShape.XC_fleur; 
934                                 break;
935
936                         case StdCursor.PanSW:
937                                 shape = CursorFontShape.XC_fleur; 
938                                 break;
939
940                         case StdCursor.PanWest:
941                                 shape = CursorFontShape.XC_sizing; 
942                                 break;
943
944                         case StdCursor.SizeAll:
945                                 shape = CursorFontShape.XC_fleur; 
946                                 break;
947
948                         case StdCursor.SizeNESW:
949                                 shape = CursorFontShape.XC_top_right_corner; 
950                                 break;
951
952                         case StdCursor.SizeNS:
953                                 shape = CursorFontShape.XC_sb_v_double_arrow;
954                                 break;
955
956                         case StdCursor.SizeNWSE:
957                                 shape = CursorFontShape.XC_top_left_corner; 
958                                 break;
959
960                         case StdCursor.SizeWE:
961                                 shape = CursorFontShape.XC_sb_h_double_arrow; 
962                                 break;
963
964                         case StdCursor.UpArrow:
965                                 shape = CursorFontShape.XC_center_ptr; 
966                                 break;
967
968                         case StdCursor.VSplit:
969                                 shape = CursorFontShape.XC_sb_h_double_arrow;
970                                 break;
971
972                         case StdCursor.WaitCursor:
973                                 shape = CursorFontShape.XC_watch; 
974                                 break;
975
976                         default:
977                                 return IntPtr.Zero;
978                         }
979
980                         return Xlib.XCreateFontCursor (display, shape);
981                 }
982
983                 // XXX this should take an X11Hwnd.
984                 public void CreateCaret (IntPtr handle, int width, int height)
985                 {
986                         XGCValues gc_values;
987                         X11Hwnd hwnd;
988
989                         hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
990
991                         if (Caret.Hwnd != IntPtr.Zero)
992                                 DestroyCaret(Caret.Hwnd);
993
994                         Caret.Hwnd = handle;
995                         Caret.Window = hwnd.ClientWindow;
996                         Caret.Width = width;
997                         Caret.Height = height;
998                         Caret.Visible = false;
999                         Caret.On = false;
1000
1001                         gc_values = new XGCValues();
1002                         gc_values.line_width = width;
1003
1004                         Caret.gc = Xlib.XCreateGC (display, Caret.Window, new IntPtr ((int)GCFunction.GCLineWidth), ref gc_values);
1005                         if (Caret.gc == IntPtr.Zero) {
1006                                 Caret.Hwnd = IntPtr.Zero;
1007                                 return;
1008                         }
1009
1010                         Xlib.XSetFunction (display, Caret.gc, GXFunction.GXinvert);
1011                 }
1012
1013
1014                 // XXX this should take an X11Hwnd.
1015                 public void DestroyCaret (IntPtr handle)
1016                 {
1017                         if (Caret.Hwnd == handle) {
1018                                 if (Caret.Visible == true) {
1019                                         Caret.Timer.Stop ();
1020                                 }
1021                                 if (Caret.gc != IntPtr.Zero) {
1022                                         Xlib.XFreeGC (display, Caret.gc);
1023                                         Caret.gc = IntPtr.Zero;
1024                                 }
1025                                 Caret.Hwnd = IntPtr.Zero;
1026                                 Caret.Visible = false;
1027                                 Caret.On = false;
1028                         }
1029                 }
1030
1031                 public void SetCaretPos (IntPtr handle, int x, int y)
1032                 {
1033                         if (Caret.Hwnd == handle) {
1034                                 Caret.Timer.Stop();
1035                                 HideCaret();
1036
1037                                 Caret.X = x;
1038                                 Caret.Y = y;
1039
1040                                 if (Caret.Visible == true) {
1041                                         ShowCaret();
1042                                         Caret.Timer.Start();
1043                                 }
1044                         }
1045                 }
1046
1047                 public void DestroyCursor (IntPtr cursor)
1048                 {
1049                         Xlib.XFreeCursor (display, cursor);
1050                 }
1051
1052                 private void AccumulateDestroyedHandles (Control c, ArrayList list)
1053                 {
1054                         if (c != null) {
1055                                 Control[] controls = c.Controls.GetAllControls ();
1056
1057                                 if (c.IsHandleCreated && !c.IsDisposed) {
1058                                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(c.Handle);
1059
1060 #if DriverDebug || DriverDebugDestroy
1061                                         Console.WriteLine (" + adding {0} to the list of zombie windows", XplatUI.Window (hwnd.Handle));
1062                                         Console.WriteLine (" + parent X window is {0:X}", XGetParent (hwnd.WholeWindow).ToInt32());
1063 #endif
1064
1065                                         list.Add (hwnd);
1066                                         CleanupCachedWindows (hwnd);
1067                                         hwnd.zombie = true;
1068                                 }
1069
1070                                 for (int  i = 0; i < controls.Length; i ++) {
1071                                         AccumulateDestroyedHandles (controls[i], list);
1072                                 }
1073                         }
1074                         
1075                 }
1076
1077                 void CleanupCachedWindows (X11Hwnd hwnd)
1078                 {
1079                         if (ActiveWindow == hwnd) {
1080                                 SendMessage (hwnd.ClientWindow, Msg.WM_ACTIVATE, (IntPtr)WindowActiveFlags.WA_INACTIVE, IntPtr.Zero);
1081                                 ActiveWindow = null;
1082                         }
1083
1084                         if (FocusWindow == hwnd) {
1085                                 SendMessage (hwnd.ClientWindow, Msg.WM_KILLFOCUS, IntPtr.Zero, IntPtr.Zero);
1086                                 FocusWindow = null;
1087                         }
1088
1089                         if (Grab.Hwnd == hwnd.Handle) {
1090                                 Grab.Hwnd = IntPtr.Zero;
1091                                 Grab.Confined = false;
1092                         }
1093
1094                         DestroyCaret (hwnd.Handle);
1095                 }
1096
1097
1098                 public void DestroyWindow (X11Hwnd hwnd)
1099                 {
1100                         CleanupCachedWindows (hwnd);
1101
1102                         ArrayList windows = new ArrayList ();
1103
1104                         AccumulateDestroyedHandles (Control.ControlNativeWindow.ControlFromHandle(hwnd.Handle), windows);
1105
1106                         hwnd.DestroyWindow ();
1107
1108                         foreach (X11Hwnd h in windows) {
1109                                 SendMessage (h.Handle, Msg.WM_DESTROY, IntPtr.Zero, IntPtr.Zero);
1110                         }
1111                 }
1112
1113                 public X11Hwnd GetActiveWindow ()
1114                 {
1115                         IntPtr  actual_atom;
1116                         int     actual_format;
1117                         IntPtr  nitems;
1118                         IntPtr  bytes_after;
1119                         IntPtr  prop = IntPtr.Zero;
1120                         IntPtr  active = IntPtr.Zero;
1121
1122                         Xlib.XGetWindowProperty (display, RootWindow.Handle,
1123                                                  Atoms._NET_ACTIVE_WINDOW, IntPtr.Zero, new IntPtr (1), false,
1124                                                  Atoms.XA_WINDOW, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1125
1126                         if (((long)nitems > 0) && (prop != IntPtr.Zero)) {
1127                                 active = (IntPtr)Marshal.ReadInt32(prop);
1128                                 Xlib.XFree(prop);
1129                         }
1130
1131                         return (X11Hwnd)Hwnd.GetObjectFromWindow(active);
1132                 }
1133
1134                 public void SetActiveWindow (X11Hwnd new_active_window)
1135                 {
1136                         if (new_active_window != ActiveWindow) {
1137                                 if (ActiveWindow != null)
1138                                         PostMessage (ActiveWindow.Handle, Msg.WM_ACTIVATE,
1139                                                      (IntPtr)WindowActiveFlags.WA_INACTIVE, IntPtr.Zero);
1140
1141                                 ActiveWindow = new_active_window;
1142
1143                                 if (ActiveWindow != null)
1144                                         PostMessage (ActiveWindow.Handle, Msg.WM_ACTIVATE,
1145                                                      (IntPtr)WindowActiveFlags.WA_ACTIVE, IntPtr.Zero);
1146                         }
1147
1148                         if (ModalWindows.Count > 0) {
1149                                 // Modality handling, if we are modal and the new active window is one
1150                                 // of ours but not the modal one, switch back to the modal window
1151
1152                                 if (ActiveWindow != null &&
1153                                     NativeWindow.FindWindow (ActiveWindow.Handle) != null) {
1154                                         if (ActiveWindow != (X11Hwnd)ModalWindows.Peek())
1155                                                 ((X11Hwnd)ModalWindows.Peek()).Activate ();
1156                                 }
1157                         }
1158                 }
1159
1160                 public void GetDisplaySize (out Size size)
1161                 {
1162                         XWindowAttributes attributes = new XWindowAttributes();
1163
1164                         // FIXME - use _NET_WM messages instead?
1165                         Xlib.XGetWindowAttributes (display, RootWindow.Handle, ref attributes);
1166
1167                         size = new Size(attributes.width, attributes.height);
1168                 }
1169
1170                 // XXX this method doesn't really fit well anywhere in the backend
1171                 public SizeF GetAutoScaleSize (Font font)
1172                 {
1173                         Graphics        g;
1174                         float           width;
1175                         string          magic_string = "The quick brown fox jumped over the lazy dog.";
1176                         double          magic_number = 44.549996948242189; // XXX my god, where did this number come from?
1177
1178                         g = Graphics.FromHwnd (FosterParent.Handle);
1179
1180                         width = (float) (g.MeasureString (magic_string, font).Width / magic_number);
1181                         return new SizeF(width, font.Height);
1182                 }
1183
1184                 public void GetCursorPos (X11Hwnd hwnd, out int x, out int y)
1185                 {
1186                         IntPtr  use_handle;
1187                         IntPtr  root;
1188                         IntPtr  child;
1189                         int     root_x;
1190                         int     root_y;
1191                         int     win_x;
1192                         int     win_y;
1193                         int     keys_buttons;
1194
1195                         if (hwnd != null)
1196                                 use_handle = hwnd.Handle;
1197                         else
1198                                 use_handle = RootWindow.Handle;
1199
1200                         QueryPointer (use_handle, out root, out child, out root_x, out root_y, out win_x, out win_y, out keys_buttons);
1201
1202                         if (hwnd != null) {
1203                                 x = win_x;
1204                                 y = win_y;
1205                         } else {
1206                                 x = root_x;
1207                                 y = root_y;
1208                         }
1209                 }
1210
1211                 public IntPtr GetFocus ()
1212                 {
1213                         return FocusWindow.Handle;
1214                 }
1215
1216                 public IntPtr GetMousewParam (int Delta)
1217                 {
1218                         int     result = 0;
1219
1220                         if ((MouseState & MouseButtons.Left) != 0) {
1221                                 result |= (int)MsgButtons.MK_LBUTTON;
1222                         }
1223
1224                         if ((MouseState & MouseButtons.Middle) != 0) {
1225                                 result |= (int)MsgButtons.MK_MBUTTON;
1226                         }
1227
1228                         if ((MouseState & MouseButtons.Right) != 0) {
1229                                 result |= (int)MsgButtons.MK_RBUTTON;
1230                         }
1231
1232                         Keys mods = ModifierKeys;
1233                         if ((mods & Keys.Control) != 0) {
1234                                 result |= (int)MsgButtons.MK_CONTROL;
1235                         }
1236
1237                         if ((mods & Keys.Shift) != 0) {
1238                                 result |= (int)MsgButtons.MK_SHIFT;
1239                         }
1240
1241                         result |= Delta << 16;
1242
1243                         return (IntPtr)result;
1244                 }
1245
1246                 public void GrabInfo (out IntPtr handle, out bool GrabConfined, out Rectangle GrabArea)
1247                 {
1248                         handle = Grab.Hwnd;
1249                         GrabConfined = Grab.Confined;
1250                         GrabArea = Grab.Area;
1251                 }
1252
1253                 public void GrabWindow (X11Hwnd hwnd, X11Hwnd confine_to)
1254                 {
1255                         IntPtr  confine_to_window;
1256
1257                         confine_to_window = IntPtr.Zero;
1258
1259                         if (confine_to != null) {
1260                                 Console.WriteLine (Environment.StackTrace);
1261
1262                                 XWindowAttributes attributes = new XWindowAttributes();
1263
1264                                 Xlib.XGetWindowAttributes (display, confine_to.ClientWindow, ref attributes);
1265
1266                                 Grab.Area.X = attributes.x;
1267                                 Grab.Area.Y = attributes.y;
1268                                 Grab.Area.Width = attributes.width;
1269                                 Grab.Area.Height = attributes.height;
1270                                 Grab.Confined = true;
1271                                 confine_to_window = confine_to.ClientWindow;
1272                         }
1273
1274                         Grab.Hwnd = hwnd.ClientWindow;
1275
1276                         Xlib.XGrabPointer (display, hwnd.ClientWindow, false, 
1277                                            EventMask.ButtonPressMask | EventMask.ButtonMotionMask |
1278                                            EventMask.ButtonReleaseMask | EventMask.PointerMotionMask,
1279                                            GrabMode.GrabModeAsync, GrabMode.GrabModeAsync, confine_to_window, IntPtr.Zero, IntPtr.Zero);
1280                 }
1281
1282                 public void UngrabWindow (X11Hwnd hwnd)
1283                 {
1284                         Xlib.XUngrabPointer (display, IntPtr.Zero);
1285                         Xlib.XFlush (display);
1286
1287                         // XXX make sure hwnd is what should have the grab and throw if not
1288                         Grab.Hwnd = IntPtr.Zero;
1289                         Grab.Confined = false;
1290                 }
1291
1292 #if notyet
1293                 private void TranslatePropertyToClipboard (IntPtr property)
1294                 {
1295                         IntPtr actual_atom;
1296                         int actual_format;
1297                         IntPtr nitems;
1298                         IntPtr bytes_after;
1299                         IntPtr prop = IntPtr.Zero;
1300
1301                         Clipboard.Item = null;
1302
1303                         Xlib.XGetWindowProperty (display, FosterParent.Handle,
1304                                                  property, IntPtr.Zero, new IntPtr (0x7fffffff), true,
1305                                                  Atoms.AnyPropertyType, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1306
1307                         if ((long)nitems > 0) {
1308                                 if (property == Atoms.XA_STRING) {
1309                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
1310                                 } else if (property == Atoms.XA_BITMAP) {
1311                                         // FIXME - convert bitmap to image
1312                                 } else if (property == Atoms.XA_PIXMAP) {
1313                                         // FIXME - convert pixmap to image
1314                                 } else if (property == Atoms.OEMTEXT) {
1315                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
1316                                 } else if (property == Atoms.UNICODETEXT) {
1317                                         Clipboard.Item = Marshal.PtrToStringAnsi(prop);
1318                                 }
1319
1320                                 Xlib.XFree(prop);
1321                         }
1322                 }
1323 #endif
1324
1325                 // XXX should we be using @handle instead of Atoms.CLIPBOARD here?
1326                 public int[] ClipboardAvailableFormats (IntPtr handle)
1327                 {
1328                         // XXX deal with the updatemessagequeue stuff
1329 #if true
1330                         return new int[0];
1331 #else
1332                         DataFormats.Format f;
1333                         int[] result;
1334
1335                         f = DataFormats.Format.List;
1336
1337                         if (Xlib.XGetSelectionOwner (display, Atoms.CLIPBOARD) == IntPtr.Zero) {
1338                                 return null;
1339                         }
1340
1341                         Clipboard.Formats = new ArrayList();
1342
1343                         while (f != null) {
1344                                 Xlib.XConvertSelection (display, Atoms.CLIPBOARD, (IntPtr)f.Id, (IntPtr)f.Id, FosterParent.Handle, IntPtr.Zero);
1345
1346                                 Clipboard.Enumerating = true;
1347                                 while (Clipboard.Enumerating) {
1348                                         UpdateMessageQueue(null);
1349                                 }
1350                                 f = f.Next;
1351                         }
1352
1353                         result = new int[Clipboard.Formats.Count];
1354
1355                         for (int i = 0; i < Clipboard.Formats.Count; i++) {
1356                                 result[i] = ((IntPtr)Clipboard.Formats[i]).ToInt32 ();
1357                         }
1358
1359                         Clipboard.Formats = null;
1360                         return result;
1361 #endif
1362                 }
1363
1364                 public void ClipboardClose (IntPtr handle)
1365                 {
1366                         if (handle != ClipMagic) {
1367                                 throw new ArgumentException("handle is not a valid clipboard handle");
1368                         }
1369                         return;
1370                 }
1371
1372                 public int ClipboardGetID (IntPtr handle, string format)
1373                 {
1374                         if (handle != ClipMagic) {
1375                                 throw new ArgumentException("handle is not a valid clipboard handle");
1376                         }
1377
1378                         if (format == "Text" ) return Atoms.XA_STRING.ToInt32();
1379                         else if (format == "Bitmap" ) return Atoms.XA_BITMAP.ToInt32();
1380                         //else if (format == "MetaFilePict" ) return 3;
1381                         //else if (format == "SymbolicLink" ) return 4;
1382                         //else if (format == "DataInterchangeFormat" ) return 5;
1383                         //else if (format == "Tiff" ) return 6;
1384                         else if (format == "OEMText" ) return Atoms.OEMTEXT.ToInt32();
1385                         else if (format == "DeviceIndependentBitmap" ) return Atoms.XA_PIXMAP.ToInt32();
1386                         else if (format == "Palette" ) return Atoms.XA_COLORMAP.ToInt32();      // Useless
1387                         //else if (format == "PenData" ) return 10;
1388                         //else if (format == "RiffAudio" ) return 11;
1389                         //else if (format == "WaveAudio" ) return 12;
1390                         else if (format == "UnicodeText" ) return Atoms.UNICODETEXT.ToInt32();
1391                         //else if (format == "EnhancedMetafile" ) return 14;
1392                         //else if (format == "FileDrop" ) return 15;
1393                         //else if (format == "Locale" ) return 16;
1394
1395                         return Xlib.XInternAtom (display, format, false).ToInt32();
1396                 }
1397
1398                 public IntPtr ClipboardOpen (bool primary_selection)
1399                 {
1400                         if (!primary_selection)
1401                                 ClipMagic = Atoms.CLIPBOARD;
1402                         else
1403                                 ClipMagic = Atoms.PRIMARY;
1404
1405                         return ClipMagic;
1406                 }
1407
1408                 // XXX @converter?
1409                 public object ClipboardRetrieve (IntPtr handle, int type, XplatUI.ClipboardToObject converter)
1410                 {
1411                         // XXX deal with the UpdateMessageQueue stuff
1412 #if true
1413                         return null;
1414 #else
1415                         Xlib.XConvertSelection (display, handle, (IntPtr)type, (IntPtr)type, FosterParent, IntPtr.Zero);
1416
1417                         Clipboard.Retrieving = true;
1418                         while (Clipboard.Retrieving) {
1419                                 UpdateMessageQueue(null);
1420                         }
1421
1422                         return Clipboard.Item;
1423 #endif
1424                 }
1425
1426                 public void ClipboardStore (IntPtr handle, object obj, int type, XplatUI.ObjectToClipboard converter)
1427                 {
1428                         Clipboard.Item = obj;
1429                         Clipboard.Type = type;
1430                         Clipboard.Converter = converter;
1431
1432                         if (obj != null) {
1433                                 Xlib.XSetSelectionOwner (display, Atoms.CLIPBOARD, FosterParent.Handle, IntPtr.Zero);
1434                         } else {
1435                                 // Clearing the selection
1436                                 Xlib.XSetSelectionOwner (display, Atoms.CLIPBOARD, IntPtr.Zero, IntPtr.Zero);
1437                         }
1438                 }
1439
1440
1441                 public PaintEventArgs PaintEventStart (IntPtr handle, bool client)
1442                 {
1443                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
1444
1445                         if (Caret.Visible == true) {
1446                                 Caret.Paused = true;
1447                                 HideCaret();
1448                         }
1449
1450                         return hwnd.PaintEventStart (client);
1451                 }
1452
1453                 public void PaintEventEnd (IntPtr handle, bool client)
1454                 {
1455                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(handle);
1456
1457                         hwnd.PaintEventEnd (client);
1458
1459                         if (Caret.Visible == true) {
1460                                 ShowCaret();
1461                                 Caret.Paused = false;
1462                         }
1463                 }
1464
1465                 public void SetCursor (IntPtr handle, IntPtr cursor)
1466                 {
1467                         Hwnd    hwnd;
1468
1469                         if (OverrideCursorHandle == IntPtr.Zero) {
1470                                 if ((LastCursorWindow == handle) && (LastCursorHandle == cursor))
1471                                         return;
1472
1473                                 LastCursorHandle = cursor;
1474                                 LastCursorWindow = handle;
1475
1476                                 hwnd = Hwnd.ObjectFromHandle(handle);
1477                                 if (cursor != IntPtr.Zero)
1478                                         Xlib.XDefineCursor (display, hwnd.whole_window, cursor);
1479                                 else
1480                                         Xlib.XUndefineCursor (display, hwnd.whole_window);
1481                                 Xlib.XFlush (display);
1482                         }
1483                         else {
1484                                 hwnd = Hwnd.ObjectFromHandle(handle);
1485                                 Xlib.XDefineCursor (display, hwnd.whole_window, OverrideCursorHandle);
1486                         }
1487                 }
1488
1489                 public DragDropEffects StartDrag (IntPtr handle, object data,
1490                                                   DragDropEffects allowed_effects)
1491                 {
1492                         X11Hwnd hwnd = (X11Hwnd)Hwnd.ObjectFromHandle (handle);
1493
1494                         if (hwnd == null)
1495                                 throw new ArgumentException ("Attempt to begin drag from invalid window handle (" + handle.ToInt32 () + ").");
1496
1497                         return Dnd.StartDrag (hwnd.ClientWindow, data, allowed_effects);
1498                 }
1499
1500                 public X11Atoms Atoms {
1501                         get { return atoms; }
1502                 }
1503
1504                 public int CurrentTimestamp {
1505                         get {
1506                                 TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
1507
1508                                 return (int) t.TotalSeconds;
1509                         }
1510                 }
1511
1512                 public Size CursorSize {
1513                         get {
1514                                 int     x;
1515                                 int     y;
1516
1517                                 if (Xlib.XQueryBestCursor (display, RootWindow.Handle, 32, 32, out x, out y) != 0) {
1518                                         return new Size (x, y);
1519                                 } else {
1520                                         return new Size (16, 16);
1521                                 }
1522                         }
1523                 } 
1524
1525                 public IntPtr Handle {
1526                         get { return display; }
1527                 }
1528
1529                 public Size IconSize {
1530                         get {
1531                                 IntPtr          list;
1532                                 XIconSize       size;
1533                                 int             count;
1534
1535                                 if (Xlib.XGetIconSizes (display, RootWindow.Handle, out list, out count) != 0) {
1536                                         long            current;
1537                                         int             largest;
1538
1539                                         current = (long)list;
1540                                         largest = 0;
1541
1542                                         size = new XIconSize();
1543
1544                                         for (int i = 0; i < count; i++) {
1545                                                 size = (XIconSize)Marshal.PtrToStructure((IntPtr)current, size.GetType());
1546                                                 current += Marshal.SizeOf(size);
1547
1548                                                 // Look for our preferred size
1549                                                 if (size.min_width == 32) {
1550                                                         Xlib.XFree(list);
1551                                                         return new Size(32, 32);
1552                                                 }
1553
1554                                                 if (size.max_width == 32) {
1555                                                         Xlib.XFree(list);
1556                                                         return new Size(32, 32);
1557                                                 }
1558
1559                                                 if (size.min_width < 32 && size.max_width > 32) {
1560                                                         int     x;
1561
1562                                                         // check if we can fit one
1563                                                         x = size.min_width;
1564                                                         while (x < size.max_width) {
1565                                                                 x += size.width_inc;
1566                                                                 if (x == 32) {
1567                                                                         Xlib.XFree(list);
1568                                                                         return new Size(32, 32);
1569                                                                 }
1570                                                         }
1571                                                 }
1572
1573                                                 if (largest < size.max_width) {
1574                                                         largest = size.max_width;
1575                                                 }
1576                                         }
1577
1578                                         // We didn't find a match or we wouldn't be here
1579                                         return new Size(largest, largest);
1580
1581                                 } else {
1582                                         return new Size(32, 32);
1583                                 }
1584                         }
1585                 } 
1586
1587                 public int KeyboardSpeed {
1588                         get {
1589                                 //
1590                                 // A lot harder: need to do:
1591                                 // XkbQueryExtension(0x08051008, 0xbfffdf4c, 0xbfffdf50, 0xbfffdf54, 0xbfffdf58)       = 1
1592                                 // XkbAllocKeyboard(0x08051008, 0xbfffdf4c, 0xbfffdf50, 0xbfffdf54, 0xbfffdf58)        = 0x080517a8
1593                                 // XkbGetControls(0x08051008, 1, 0x080517a8, 0xbfffdf54, 0xbfffdf58)                   = 0
1594                                 //
1595                                 // And from that we can tell the repetition rate
1596                                 //
1597                                 // Notice, the values must map to:
1598                                 //   [0, 31] which maps to 2.5 to 30 repetitions per second.
1599                                 //
1600                                 return 0;
1601                         }
1602                 }
1603
1604                 public int KeyboardDelay {
1605                         get {
1606                                 //
1607                                 // Return values must range from 0 to 4, 0 meaning 250ms,
1608                                 // and 4 meaning 1000 ms.
1609                                 //
1610                                 return 1; // ie, 500 ms
1611                         }
1612                 } 
1613
1614                 public int DefaultScreen {
1615                         get { return Xlib.XDefaultScreen (display); }
1616                 }
1617
1618                 public IntPtr DefaultColormap {
1619                         // XXX multiscreen
1620                         get { return Xlib.XDefaultColormap (display, DefaultScreen); }
1621                 }
1622
1623                 public Keys ModifierKeys {
1624                         get { return Keyboard.ModifierKeys; }
1625                 }
1626
1627                 public IntPtr OverrideCursor {
1628                         get { return OverrideCursorHandle; }
1629                         set { OverrideCursorHandle = value; }
1630                 }
1631
1632                 public X11RootHwnd RootWindow {
1633                         get { return root_hwnd; }
1634                 }
1635
1636                 public Size SmallIconSize {
1637                         get {
1638                                 IntPtr          list;
1639                                 XIconSize       size;
1640                                 int             count;
1641
1642                                 if (Xlib.XGetIconSizes (display, RootWindow.Handle, out list, out count) != 0) {
1643                                         long            current;
1644                                         int             smallest;
1645
1646                                         current = (long)list;
1647                                         smallest = 0;
1648
1649                                         size = new XIconSize();
1650
1651                                         for (int i = 0; i < count; i++) {
1652                                                 size = (XIconSize)Marshal.PtrToStructure((IntPtr)current, size.GetType());
1653                                                 current += Marshal.SizeOf(size);
1654
1655                                                 // Look for our preferred size
1656                                                 if (size.min_width == 16) {
1657                                                         Xlib.XFree(list);
1658                                                         return new Size(16, 16);
1659                                                 }
1660
1661                                                 if (size.max_width == 16) {
1662                                                         Xlib.XFree(list);
1663                                                         return new Size(16, 16);
1664                                                 }
1665
1666                                                 if (size.min_width < 16 && size.max_width > 16) {
1667                                                         int     x;
1668
1669                                                         // check if we can fit one
1670                                                         x = size.min_width;
1671                                                         while (x < size.max_width) {
1672                                                                 x += size.width_inc;
1673                                                                 if (x == 16) {
1674                                                                         Xlib.XFree(list);
1675                                                                         return new Size(16, 16);
1676                                                                 }
1677                                                         }
1678                                                 }
1679
1680                                                 if (smallest == 0 || smallest > size.min_width) {
1681                                                         smallest = size.min_width;
1682                                                 }
1683                                         }
1684
1685                                         // We didn't find a match or we wouldn't be here
1686                                         return new Size(smallest, smallest);
1687
1688                                 } else {
1689                                         return new Size(16, 16);
1690                                 }
1691                         }
1692                 } 
1693
1694                 public X11Hwnd FosterParent {
1695                         get { return foster_hwnd; }
1696                 }
1697
1698                 public int MouseHoverTime {
1699                         get { return HoverState.Interval; }
1700                 }
1701
1702                 public Rectangle WorkingArea {
1703                         get {
1704                                 IntPtr actual_atom;
1705                                 int actual_format;
1706                                 IntPtr nitems;
1707                                 IntPtr bytes_after;
1708                                 IntPtr prop = IntPtr.Zero;
1709                                 int width;
1710                                 int height;
1711                                 int current_desktop;
1712                                 int x;
1713                                 int y;
1714
1715                                 Xlib.XGetWindowProperty (display, RootWindow.Handle, 
1716                                                          Atoms._NET_CURRENT_DESKTOP, IntPtr.Zero, new IntPtr(1), false, Atoms.XA_CARDINAL,
1717                                                          out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1718
1719                                 if ((long)nitems < 1) {
1720                                         goto failsafe;
1721                                 }
1722
1723                                 current_desktop = Marshal.ReadIntPtr(prop, 0).ToInt32();
1724                                 Xlib.XFree(prop);
1725
1726                                 Xlib.XGetWindowProperty (display, RootWindow.Handle,
1727                                                          Atoms._NET_WORKAREA, IntPtr.Zero, new IntPtr (256), false, Atoms.XA_CARDINAL,
1728                                                          out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
1729
1730                                 if ((long)nitems < 4 * current_desktop) {
1731                                         goto failsafe;
1732                                 }
1733
1734                                 x = Marshal.ReadIntPtr(prop, IntPtr.Size * 4 * current_desktop).ToInt32();
1735                                 y = Marshal.ReadIntPtr(prop, IntPtr.Size * 4 * current_desktop + IntPtr.Size).ToInt32();
1736                                 width = Marshal.ReadIntPtr(prop, IntPtr.Size * 4 * current_desktop + IntPtr.Size * 2).ToInt32();
1737                                 height = Marshal.ReadIntPtr(prop, IntPtr.Size * 4 * current_desktop + IntPtr.Size * 3).ToInt32();
1738                                 Xlib.XFree(prop);
1739
1740                                 return new Rectangle(x, y, width, height);
1741
1742                         failsafe:
1743                                 XWindowAttributes attributes = new XWindowAttributes();
1744
1745                                 Xlib.XGetWindowAttributes (display, RootWindow.Handle, ref attributes);
1746
1747                                 return new Rectangle(0, 0, attributes.width, attributes.height);
1748                         }
1749                 }
1750
1751                 private void XEventThread ()
1752                 {
1753                         while (true) {
1754 #if __MonoCS__
1755                                 Syscall.poll (pollfds, 1U, -1);
1756
1757                                 while (Xlib.XPending (display) > 0) {
1758 #endif
1759                                         XEvent xevent = new XEvent ();
1760                                         Xlib.XNextEvent (display, ref xevent);
1761
1762                                         // this is kind of a gross place to put this, but we don't know about the
1763                                         // key repeat state in X11ThreadQueue, nor to we want the queue code calling
1764                                         // XPeekEvent.
1765                                         if (!detectable_key_auto_repeat &&
1766                                             xevent.type == XEventName.KeyRelease &&
1767                                             Xlib.XPending (display) > 0) {
1768
1769                                                 XEvent nextevent = new XEvent ();
1770                                                 Xlib.XPeekEvent (display, ref nextevent);
1771
1772                                                 if (nextevent.type == XEventName.KeyPress &&
1773                                                     nextevent.KeyEvent.keycode == xevent.KeyEvent.keycode &&
1774                                                     nextevent.KeyEvent.time == xevent.KeyEvent.time) {
1775                                                         continue;
1776                                                 }
1777                                         }
1778
1779                                         X11Hwnd hwnd = (X11Hwnd)Hwnd.GetObjectFromWindow(xevent.AnyEvent.window);
1780                                         if (hwnd != null)
1781                                                 hwnd.Queue.Enqueue (xevent);
1782 #if __MonoCS__
1783                                 }
1784 #endif
1785                         }
1786                 }
1787
1788                 private void RedirectMsgToEnabledAncestor (X11Hwnd hwnd, MSG msg, IntPtr window,
1789                                                            ref int event_x, ref int event_y)
1790                 {
1791                         int x, y;
1792
1793                         IntPtr dummy;
1794                         msg.hwnd = hwnd.EnabledHwnd;
1795                         Xlib.XTranslateCoordinates (display, window,
1796                                                     Hwnd.ObjectFromHandle(msg.hwnd).ClientWindow,
1797                                                     event_x, event_y,
1798                                                     out x, out y, out dummy);
1799                         event_x = x;
1800                         event_y = y;
1801                         msg.lParam = (IntPtr)(MousePosition.Y << 16 | MousePosition.X);
1802                 }
1803
1804
1805                 // This is called from the thread owning the corresponding X11ThreadQueue
1806                 [MonoTODO("Implement filtering")]
1807                 public bool GetMessage (object queue_id, ref MSG msg, IntPtr handle, int wFilterMin, int wFilterMax)
1808                 {
1809                         X11ThreadQueue queue = (X11ThreadQueue)queue_id;
1810                         XEvent xevent;
1811                         bool client;
1812                         bool got_xevent = false;
1813
1814                         X11Hwnd hwnd;
1815
1816                 ProcessNextMessage:
1817                         do {
1818                                 got_xevent = queue.Dequeue (out xevent);
1819
1820                                 if (!got_xevent) {
1821 #if spew
1822                                         Console.WriteLine (">");
1823                                         Console.Out.Flush ();
1824 #endif
1825                                         break;
1826                                 }
1827
1828 #if spew
1829                                 Console.Write ("-");
1830                                 Console.Out.Flush ();
1831 #endif
1832
1833                                 hwnd = (X11Hwnd)Hwnd.GetObjectFromWindow (xevent.AnyEvent.window);
1834
1835                                 // Handle messages for windows that are already or are about to be destroyed.
1836
1837                                 // we need a special block for this because unless we remove the hwnd from the paint
1838                                 // queue it will always stay there (since we don't handle the expose), and we'll
1839                                 // effectively loop infinitely trying to repaint a non-existant window.
1840                                 if (hwnd != null && hwnd.zombie && xevent.type == XEventName.Expose) {
1841                                         hwnd.PendingExpose = hwnd.PendingNCExpose = false;
1842                                         goto ProcessNextMessage;
1843                                 }
1844
1845                                 // We need to make sure we only allow DestroyNotify events through for zombie
1846                                 // hwnds, since much of the event handling code makes requests using the hwnd's
1847                                 // ClientWindow, and that'll result in BadWindow errors if there's some lag
1848                                 // between the XDestroyWindow call and the DestroyNotify event.
1849                                 if (hwnd == null || hwnd.zombie) {
1850 #if DriverDebug || DriverDebugDestroy
1851                                         Console.WriteLine("GetMessage(): Got message {0} for non-existent or already destroyed window {1:X}",
1852                                                           xevent.type, xevent.AnyEvent.window.ToInt32());
1853 #endif
1854                                         goto ProcessNextMessage;
1855                                 }
1856
1857                                 client = hwnd.ClientWindow == xevent.AnyEvent.window;
1858
1859                                 msg.hwnd = hwnd.Handle;
1860
1861                                 switch (xevent.type) {
1862                                 case XEventName.KeyPress:
1863                                         Keyboard.KeyEvent (FocusWindow.Handle, xevent, ref msg);
1864                                         return true;
1865
1866                                 case XEventName.KeyRelease:
1867                                         Keyboard.KeyEvent (FocusWindow.Handle, xevent, ref msg);
1868                                         return true;
1869
1870                                 case XEventName.ButtonPress: {
1871                                         switch(xevent.ButtonEvent.button) {
1872                                         case 1:
1873                                                 MouseState |= MouseButtons.Left;
1874                                                 if (client) {
1875                                                         msg.message = Msg.WM_LBUTTONDOWN;
1876                                                 } else {
1877                                                         msg.message = Msg.WM_NCLBUTTONDOWN;
1878                                                         hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1879                                                 }
1880                                                 // TODO: For WM_NCLBUTTONDOWN wParam specifies a hit-test value not the virtual keys down
1881                                                 msg.wParam=GetMousewParam(0);
1882                                                 break;
1883
1884                                         case 2:
1885                                                 MouseState |= MouseButtons.Middle;
1886                                                 if (client) {
1887                                                         msg.message = Msg.WM_MBUTTONDOWN;
1888                                                 } else {
1889                                                         msg.message = Msg.WM_NCMBUTTONDOWN;
1890                                                         hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1891                                                 }
1892                                                 msg.wParam=GetMousewParam(0);
1893                                                 break;
1894
1895                                         case 3:
1896                                                 MouseState |= MouseButtons.Right;
1897                                                 if (client) {
1898                                                         msg.message = Msg.WM_RBUTTONDOWN;
1899                                                 } else {
1900                                                         msg.message = Msg.WM_NCRBUTTONDOWN;
1901                                                         hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1902                                                 }
1903                                                 msg.wParam=GetMousewParam(0);
1904                                                 break;
1905
1906                                         case 4:
1907                                                 msg.hwnd = FocusWindow.Handle;
1908                                                 msg.message=Msg.WM_MOUSEWHEEL;
1909                                                 msg.wParam=GetMousewParam(120);
1910                                                 break;
1911
1912                                         case 5:
1913                                                 msg.hwnd = FocusWindow.Handle;
1914                                                 msg.message=Msg.WM_MOUSEWHEEL;
1915                                                 msg.wParam=GetMousewParam(-120);
1916                                                 break;
1917                                         }
1918
1919                                         msg.lParam=(IntPtr) (xevent.ButtonEvent.y << 16 | xevent.ButtonEvent.x);
1920                                         MousePosition.X = xevent.ButtonEvent.x;
1921                                         MousePosition.Y = xevent.ButtonEvent.y;
1922
1923                                         if (!hwnd.Enabled) {
1924                                                 RedirectMsgToEnabledAncestor (hwnd, msg, xevent.AnyEvent.window,
1925                                                                               ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1926                                         }
1927
1928                                         if (Grab.Hwnd != IntPtr.Zero)
1929                                                 msg.hwnd = Grab.Hwnd;
1930
1931                                         if (ClickPending.Pending &&
1932                                             ((((long)xevent.ButtonEvent.time - ClickPending.Time) < DoubleClickInterval) &&
1933                                              (msg.wParam == ClickPending.wParam) &&
1934                                              (msg.lParam == ClickPending.lParam) &&
1935                                              (msg.message == ClickPending.Message))) {
1936                                                 // Looks like a genuine double click, clicked twice on the same spot with the same keys
1937                                                 switch(xevent.ButtonEvent.button) {
1938                                                 case 1:
1939                                                         msg.message = client ? Msg.WM_LBUTTONDBLCLK : Msg.WM_NCLBUTTONDBLCLK;
1940                                                         break;
1941
1942                                                 case 2:
1943                                                         msg.message = client ? Msg.WM_MBUTTONDBLCLK : Msg.WM_NCMBUTTONDBLCLK;
1944                                                         break;
1945
1946                                                 case 3:
1947                                                         msg.message = client ? Msg.WM_RBUTTONDBLCLK : Msg.WM_NCRBUTTONDBLCLK;
1948                                                         break;
1949                                                 }
1950
1951                                                 ClickPending.Pending = false;
1952
1953                                         }
1954                                         else {
1955                                                 ClickPending.Pending = true;
1956                                                 ClickPending.Hwnd = msg.hwnd;
1957                                                 ClickPending.Message = msg.message;
1958                                                 ClickPending.wParam = msg.wParam;
1959                                                 ClickPending.lParam = msg.lParam;
1960                                                 ClickPending.Time = (long)xevent.ButtonEvent.time;
1961                                         }
1962
1963                                         return true;
1964                                 }
1965
1966                                 case XEventName.ButtonRelease:
1967                                         if (Dnd.InDrag()) {
1968                                                 Dnd.HandleButtonRelease (ref xevent);
1969                                                 // Don't return here, so that the BUTTONUP message can get through
1970                                         }
1971
1972                                         switch(xevent.ButtonEvent.button) {
1973                                         case 1:
1974                                                 if (client) {
1975                                                         msg.message = Msg.WM_LBUTTONUP;
1976                                                 } else {
1977                                                         msg.message = Msg.WM_NCLBUTTONUP;
1978                                                         hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1979                                                 }
1980                                                 MouseState &= ~MouseButtons.Left;
1981                                                 msg.wParam=GetMousewParam(0);
1982                                                 break;
1983
1984                                         case 2:
1985                                                 if (client) {
1986                                                         msg.message = Msg.WM_MBUTTONUP;
1987                                                 } else {
1988                                                         msg.message = Msg.WM_NCMBUTTONUP;
1989                                                         hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
1990                                                 }
1991                                                 MouseState &= ~MouseButtons.Middle;
1992                                                 msg.wParam=GetMousewParam(0);
1993                                                 break;
1994
1995                                         case 3:
1996                                                 if (client) {
1997                                                         msg.message = Msg.WM_RBUTTONUP;
1998                                                 } else {
1999                                                         msg.message = Msg.WM_NCRBUTTONUP;
2000                                                         hwnd.MenuToScreen (ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
2001                                                 }
2002                                                 MouseState &= ~MouseButtons.Right;
2003                                                 msg.wParam=GetMousewParam(0);
2004                                                 break;
2005
2006                                         case 4:
2007                                                 goto ProcessNextMessage;
2008
2009                                         case 5:
2010                                                 goto ProcessNextMessage;
2011                                         }
2012
2013                                         if (!hwnd.Enabled) {
2014                                                 RedirectMsgToEnabledAncestor (hwnd, msg, xevent.AnyEvent.window,
2015                                                                               ref xevent.ButtonEvent.x, ref xevent.ButtonEvent.y);
2016                                         }
2017
2018                                         if (Grab.Hwnd != IntPtr.Zero)
2019                                                 msg.hwnd = Grab.Hwnd;
2020
2021                                         msg.lParam=(IntPtr) (xevent.ButtonEvent.y << 16 | xevent.ButtonEvent.x);
2022                                         MousePosition.X = xevent.ButtonEvent.x;
2023                                         MousePosition.Y = xevent.ButtonEvent.y;
2024                                         return true;
2025
2026                                 case XEventName.MotionNotify:
2027                                         /* XXX move the compression stuff here */
2028
2029                                         if (client) {
2030 #if DriverDebugExtra
2031                                                 Console.WriteLine("GetMessage(): Window {0:X} MotionNotify x={1} y={2}",
2032                                                                   client ? hwnd.ClientWindow.ToInt32() : hwnd.WholeWindow.ToInt32(),
2033                                                                   xevent.MotionEvent.x, xevent.MotionEvent.y);
2034 #endif
2035
2036                                                 if (Dnd.HandleMotionNotify (ref xevent))
2037                                                         goto ProcessNextMessage;
2038
2039                                                 if (Grab.Hwnd != IntPtr.Zero)
2040                                                         msg.hwnd = Grab.Hwnd;
2041                                                 else
2042                                                         NativeWindow.WndProc(msg.hwnd, Msg.WM_SETCURSOR, msg.hwnd, (IntPtr)HitTest.HTCLIENT);
2043
2044                                                 msg.message = Msg.WM_MOUSEMOVE;
2045                                                 msg.wParam = GetMousewParam(0);
2046                                                 msg.lParam = (IntPtr) (xevent.MotionEvent.y << 16 | xevent.MotionEvent.x & 0xFFFF);
2047
2048                                                 if (!hwnd.Enabled) {
2049                                                         RedirectMsgToEnabledAncestor (hwnd, msg, xevent.AnyEvent.window,
2050                                                                                       ref xevent.MotionEvent.x, ref xevent.MotionEvent.y);
2051                                                 }
2052
2053                                                 MousePosition.X = xevent.MotionEvent.x;
2054                                                 MousePosition.Y = xevent.MotionEvent.y;
2055
2056                                                 if ((HoverState.Timer.Enabled) &&
2057                                                     (((MousePosition.X + HoverState.Size.Width) < HoverState.X) ||
2058                                                      ((MousePosition.X - HoverState.Size.Width) > HoverState.X) ||
2059                                                      ((MousePosition.Y + HoverState.Size.Height) < HoverState.Y) ||
2060                                                      ((MousePosition.Y - HoverState.Size.Height) > HoverState.Y))) {
2061
2062                                                         HoverState.Timer.Stop();
2063                                                         HoverState.Timer.Start();
2064                                                         HoverState.X = MousePosition.X;
2065                                                         HoverState.Y = MousePosition.Y;
2066                                                 }
2067                                         }
2068                                         else {
2069                                                 HitTest ht;
2070                                                 IntPtr dummy;
2071                                                 int screen_x;
2072                                                 int screen_y;
2073
2074                                                 #if DriverDebugExtra
2075                                                 Console.WriteLine("GetMessage(): non-client area {0:X} MotionNotify x={1} y={2}",
2076                                                                   client ? hwnd.ClientWindow.ToInt32() : hwnd.WholeWindow.ToInt32(),
2077                                                                   xevent.MotionEvent.x, xevent.MotionEvent.y);
2078                                                 #endif
2079                                                 msg.message = Msg.WM_NCMOUSEMOVE;
2080
2081                                                 if (!hwnd.Enabled) {
2082                                                         RedirectMsgToEnabledAncestor (hwnd, msg, xevent.AnyEvent.window,
2083                                                                                       ref xevent.MotionEvent.x, ref xevent.MotionEvent.y);
2084                                                 }
2085
2086                                                 // The hit test is sent in screen coordinates
2087                                                 Xlib.XTranslateCoordinates (display, xevent.AnyEvent.window, RootWindow.Handle,
2088                                                                             xevent.MotionEvent.x, xevent.MotionEvent.y,
2089                                                                             out screen_x, out screen_y, out dummy);
2090
2091                                                 msg.lParam = (IntPtr) (screen_y << 16 | screen_x & 0xFFFF);
2092                                                 ht = (HitTest)NativeWindow.WndProc (hwnd.ClientWindow, Msg.WM_NCHITTEST,
2093                                                                                     IntPtr.Zero, msg.lParam).ToInt32 ();
2094                                                 NativeWindow.WndProc(hwnd.ClientWindow, Msg.WM_SETCURSOR, msg.hwnd, (IntPtr)ht);
2095
2096                                                 MousePosition.X = xevent.MotionEvent.x;
2097                                                 MousePosition.Y = xevent.MotionEvent.y;
2098                                         }
2099
2100                                         return true;
2101
2102                                 case XEventName.EnterNotify:
2103                                         if (!hwnd.Enabled)
2104                                                 goto ProcessNextMessage;
2105
2106                                         if (xevent.CrossingEvent.mode != NotifyMode.NotifyNormal)
2107                                                 goto ProcessNextMessage;
2108
2109                                         msg.message = Msg.WM_MOUSE_ENTER;
2110                                         HoverState.X = xevent.CrossingEvent.x;
2111                                         HoverState.Y = xevent.CrossingEvent.y;
2112                                         HoverState.Timer.Enabled = true;
2113                                         HoverState.Window = xevent.CrossingEvent.window;
2114
2115                                         return true;
2116
2117                                 case XEventName.LeaveNotify:
2118                                         if (!hwnd.Enabled)
2119                                                 goto ProcessNextMessage;
2120
2121                                         if ((xevent.CrossingEvent.mode != NotifyMode.NotifyNormal) ||
2122                                             (xevent.CrossingEvent.window != hwnd.ClientWindow))
2123                                                 goto ProcessNextMessage;
2124
2125                                         msg.message=Msg.WM_MOUSE_LEAVE;
2126                                         HoverState.Timer.Enabled = false;
2127                                         HoverState.Window = IntPtr.Zero;
2128
2129                                         return true;
2130
2131                                 case XEventName.ReparentNotify:
2132                                         if (hwnd.parent == null) {      // Toplevel
2133                                                 if ((xevent.ReparentEvent.parent != IntPtr.Zero) && (xevent.ReparentEvent.window == hwnd.WholeWindow)) {
2134                                                         // We need to adjust x/y
2135                                                         // This sucks ass, part 2
2136                                                         // Every WM does the reparenting of toplevel windows different, so there's
2137                                                         // no standard way of getting our adjustment considering frames/decorations
2138                                                         // The code below is needed for metacity. KDE doesn't works just fine without this
2139                                                         int     dummy_int;
2140                                                         IntPtr  dummy_ptr;
2141                                                         int     new_x;
2142                                                         int     new_y;
2143                                                         int     frame_left;
2144                                                         int     frame_top;
2145
2146                                                         hwnd.Reparented = true;
2147
2148                                                         Xlib.XGetGeometry(display, XGetParent(hwnd.WholeWindow),
2149                                                                           out dummy_ptr, out new_x, out new_y,
2150                                                                           out dummy_int, out dummy_int, out dummy_int, out dummy_int);
2151                                                         hwnd.FrameExtents(out frame_left, out frame_top);
2152                                                         if ((frame_left != 0) && (frame_top != 0) && (new_x != frame_left) && (new_y != frame_top)) {
2153                                                                 hwnd.x = new_x;
2154                                                                 hwnd.y = new_y;
2155                                                                 hwnd.whacky_wm = true;
2156                                                         }
2157
2158                                                         if (hwnd.opacity != 0xffffffff) {
2159                                                                 IntPtr opacity;
2160
2161                                                                 opacity = (IntPtr)(Int32)hwnd.opacity;
2162                                                                 Xlib.XChangeProperty (display, XGetParent(hwnd.WholeWindow),
2163                                                                                       Atoms._NET_WM_WINDOW_OPACITY, Atoms.XA_CARDINAL, 32,
2164                                                                                       PropertyMode.Replace, ref opacity, 1);
2165                                                         }
2166                                                         SendMessage(msg.hwnd, Msg.WM_WINDOWPOSCHANGED, msg.wParam, msg.lParam);
2167                                                         goto ProcessNextMessage;
2168                                                 } else {
2169                                                         hwnd.Reparented = false;
2170                                                         goto ProcessNextMessage;
2171                                                 }
2172                                         }
2173                                         goto ProcessNextMessage;
2174
2175                                 case XEventName.ConfigureNotify:
2176                                         hwnd.HandleConfigureNotify (xevent);
2177                                         goto ProcessNextMessage;
2178
2179                                 case XEventName.FocusIn:
2180                                         // We received focus. We use X11 focus only to know if the app window does or does not have focus
2181                                         // We do not track the actual focussed window via it. Instead, this is done via FocusWindow internally
2182                                         // Receiving focus means we've gotten activated and therefore we need to let the actual FocusWindow know 
2183                                         // about it having focus again
2184                                         if (xevent.FocusChangeEvent.detail != NotifyDetail.NotifyNonlinear)
2185                                                 goto ProcessNextMessage;
2186
2187                                         if (FocusWindow == null) {
2188                                                 Control c = Control.FromHandle (hwnd.ClientWindow);
2189                                                 if (c == null)
2190                                                         goto ProcessNextMessage;
2191                                                 Form form = c.FindForm ();
2192                                                 if (form == null)
2193                                                         goto ProcessNextMessage;
2194                                                 X11Hwnd new_active = (X11Hwnd)Hwnd.ObjectFromHandle (form.Handle);
2195                                                 if (ActiveWindow != new_active) {
2196                                                         ActiveWindow = new_active;
2197                                                         SendMessage (ActiveWindow.Handle, Msg.WM_ACTIVATE, (IntPtr) WindowActiveFlags.WA_ACTIVE, IntPtr.Zero);
2198                                                 }
2199                                                 goto ProcessNextMessage;
2200                                         }
2201                                         Keyboard.FocusIn(FocusWindow.Handle);
2202                                         SendMessage(FocusWindow.Handle, Msg.WM_SETFOCUS, IntPtr.Zero, IntPtr.Zero);
2203                                         goto ProcessNextMessage;
2204
2205                                 case XEventName.FocusOut:
2206                                         // Se the comment for our FocusIn handler
2207                                         if (xevent.FocusChangeEvent.detail != NotifyDetail.NotifyNonlinear)
2208                                                 goto ProcessNextMessage;
2209
2210                                         if (FocusWindow == null)
2211                                                 goto ProcessNextMessage;
2212
2213                                         Keyboard.FocusOut(FocusWindow.Handle);
2214
2215                                         while (Keyboard.ResetKeyState(FocusWindow.Handle, ref msg))
2216                                                 SendMessage(FocusWindow.Handle, msg.message, msg.wParam, msg.lParam);
2217
2218                                         SendMessage(FocusWindow.Handle, Msg.WM_KILLFOCUS, IntPtr.Zero, IntPtr.Zero);
2219                                         goto ProcessNextMessage;
2220
2221                                 case XEventName.Expose:
2222                                         if (queue.PostQuitState || !hwnd.Mapped) {
2223                                                 hwnd.PendingExpose = hwnd.PendingNCExpose = false;
2224                                                 continue;
2225                                         }
2226
2227                                         msg.hwnd = hwnd.Handle;
2228
2229                                         if (client) {
2230 #if DriverDebugExtra
2231                                                 Console.WriteLine("GetMessage(): Window {0:X} Exposed area {1},{2} {3}x{4}",
2232                                                                   hwnd.client_window.ToInt32(),
2233                                                                   xevent.ExposeEvent.x, xevent.ExposeEvent.y,
2234                                                                   xevent.ExposeEvent.width, xevent.ExposeEvent.height);
2235 #endif
2236                                                 msg.message = Msg.WM_PAINT;
2237                                         }
2238                                         else {
2239                                                 Graphics g;
2240
2241                                                 switch (hwnd.border_style) {
2242                                                 case FormBorderStyle.Fixed3D:
2243                                                         g = Graphics.FromHwnd(hwnd.WholeWindow);
2244                                                         ControlPaint.DrawBorder3D(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height),
2245                                                                                   Border3DStyle.Sunken);
2246                                                         g.Dispose();
2247                                                         break;
2248
2249                                                 case FormBorderStyle.FixedSingle:
2250                                                         g = Graphics.FromHwnd(hwnd.WholeWindow);
2251                                                         ControlPaint.DrawBorder(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height),
2252                                                                                 Color.Black, ButtonBorderStyle.Solid);
2253                                                         g.Dispose();
2254                                                 break;
2255                                                 }
2256 #if DriverDebugExtra
2257                                                 Console.WriteLine("GetMessage(): Window {0:X} Exposed non-client area {1},{2} {3}x{4}",
2258                                                                   hwnd.ClientWindow.ToInt32(),
2259                                                                   xevent.ExposeEvent.x, xevent.ExposeEvent.y,
2260                                                                   xevent.ExposeEvent.width, xevent.ExposeEvent.height);
2261 #endif
2262
2263                                                 Rectangle rect = new Rectangle (xevent.ExposeEvent.x, xevent.ExposeEvent.y,
2264                                                                                 xevent.ExposeEvent.width, xevent.ExposeEvent.height);
2265                                                 Region region = new Region (rect);
2266                                                 IntPtr hrgn = region.GetHrgn (null); // Graphics object isn't needed
2267                                                 msg.message = Msg.WM_NCPAINT;
2268                                                 msg.wParam = hrgn == IntPtr.Zero ? (IntPtr)1 : hrgn;
2269                                                 msg.refobject = region;
2270                                         }
2271
2272                                         return true;
2273                                                 
2274                                 case XEventName.DestroyNotify:
2275
2276                                         // This is a bit tricky, we don't receive our own DestroyNotify, we only get those for our children
2277                                         hwnd = (X11Hwnd)Hwnd.ObjectFromHandle(xevent.DestroyWindowEvent.window);
2278
2279                                         // We may get multiple for the same window, act only one the first (when Hwnd still knows about it)
2280                                         if ((hwnd != null) && (hwnd.ClientWindow == xevent.DestroyWindowEvent.window)) {
2281                                                 CleanupCachedWindows (hwnd);
2282
2283                                                 #if DriverDebugDestroy
2284                                                 Console.WriteLine("Received X11 Destroy Notification for {0}", XplatUI.Window(hwnd.ClientWindow));
2285                                                 #endif
2286
2287                                                 msg.hwnd = hwnd.ClientWindow;
2288                                                 msg.message=Msg.WM_DESTROY;
2289                                                 hwnd.Dispose();
2290                                         }
2291                                         else
2292                                                 goto ProcessNextMessage;
2293
2294                                         return true;
2295
2296                                 case XEventName.ClientMessage:
2297                                         if (Dnd.HandleClientMessage (ref xevent))
2298                                                 goto ProcessNextMessage;
2299
2300                                         if (xevent.ClientMessageEvent.message_type == Atoms.AsyncAtom) {
2301                                                 XplatUIDriverSupport.ExecuteClientMessage((GCHandle)xevent.ClientMessageEvent.ptr1);
2302                                                 goto ProcessNextMessage;
2303                                         }
2304
2305                                         if (xevent.ClientMessageEvent.message_type == HoverState.Atom) {
2306                                                 msg.message = Msg.WM_MOUSEHOVER;
2307                                                 msg.wParam = GetMousewParam(0);
2308                                                 msg.lParam = (IntPtr) (xevent.ClientMessageEvent.ptr1);
2309                                                 return true;
2310                                         }
2311
2312                                         if (xevent.ClientMessageEvent.message_type == Atoms.PostAtom) {
2313                                                 msg.hwnd = xevent.ClientMessageEvent.ptr1;
2314                                                 msg.message = (Msg) xevent.ClientMessageEvent.ptr2.ToInt32 ();
2315                                                 msg.wParam = xevent.ClientMessageEvent.ptr3;
2316                                                 msg.lParam = xevent.ClientMessageEvent.ptr4;
2317                                                 return true;
2318                                         }
2319
2320                                         if (xevent.ClientMessageEvent.message_type == Atoms._XEMBED) {
2321 #if DriverDebugXEmbed
2322                                                 Console.WriteLine("GOT EMBED MESSAGE {0:X}, detail {1:X}",
2323                                                                   xevent.ClientMessageEvent.ptr2.ToInt32(), xevent.ClientMessageEvent.ptr3.ToInt32());
2324 #endif
2325
2326                                                 if (xevent.ClientMessageEvent.ptr2.ToInt32() == (int)XEmbedMessage.EmbeddedNotify) {
2327                                                         XSizeHints hints = new XSizeHints();
2328                                                         IntPtr dummy;
2329
2330                                                         Xlib.XGetWMNormalHints (display, hwnd.WholeWindow, ref hints, out dummy);
2331
2332                                                         hwnd.width = hints.max_width;
2333                                                         hwnd.height = hints.max_height;
2334                                                         hwnd.ClientRect = Rectangle.Empty;
2335                                                         SendMessage(msg.hwnd, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
2336                                                 }
2337                                         }
2338
2339                                         if (xevent.ClientMessageEvent.message_type == Atoms.WM_PROTOCOLS) {
2340                                                 if (xevent.ClientMessageEvent.ptr1 == Atoms.WM_DELETE_WINDOW) {
2341                                                         msg.message = Msg.WM_CLOSE;
2342                                                         return true;
2343                                                 }
2344
2345                                                 // We should not get this, but I'll leave the code in case we need it in the future
2346                                                 if (xevent.ClientMessageEvent.ptr1 == Atoms.WM_TAKE_FOCUS) {
2347                                                         goto ProcessNextMessage;
2348                                                 }
2349                                         }
2350                                         goto ProcessNextMessage;
2351
2352                                 case XEventName.PropertyNotify:
2353                                         // The Hwnd's themselves handle this
2354                                         hwnd.PropertyChanged (xevent);
2355                                         goto ProcessNextMessage;
2356                                 }
2357                         } while (true);
2358
2359 #if notyet
2360                         // XXX need to figure out how to post
2361                         // WM_ENTERIDLE only in specific conditions
2362                         // (we've handled some input events)
2363                         if (!queue.PostQuitState) {
2364                                 msg.hwnd= IntPtr.Zero;
2365                                 msg.message = Msg.WM_ENTERIDLE;
2366                                 return true;
2367                         }
2368 #else
2369                         goto ProcessNextMessage;
2370 #endif
2371
2372                         // We reset ourselves so GetMessage can be called again
2373                         queue.PostQuitState = false;
2374
2375                         return false;
2376                 }
2377
2378                 [MonoTODO("Implement filtering and PM_NOREMOVE")]
2379                 public bool PeekMessage (object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, uint flags)
2380                 {
2381                         X11ThreadQueue queue = (X11ThreadQueue) queue_id;
2382                         bool    pending;
2383
2384                         if ((flags & (uint)PeekMessageFlags.PM_REMOVE) == 0) {
2385                                 throw new NotImplementedException("PeekMessage PM_NOREMOVE is not implemented yet");    // FIXME - Implement PM_NOREMOVE flag
2386                         }
2387
2388                         try {
2389                                 queue.Lock ();
2390                                 pending = false;
2391                                 if (queue.CountUnlocked > 0)
2392                                         pending = true;
2393                         }
2394                         catch {
2395                                 return false;
2396                         }
2397                         finally {
2398                                 queue.Unlock ();
2399                         }
2400
2401                         queue.CheckTimers ();
2402
2403                         if (!pending)
2404                                 return false;
2405
2406                         return GetMessage(queue_id, ref msg, hWnd, wFilterMin, wFilterMax);
2407                 }
2408
2409                 public void DoEvents (X11ThreadQueue queue)
2410                 {
2411                         MSG     msg = new MSG ();
2412
2413                         if (OverrideCursorHandle != IntPtr.Zero)
2414                                 OverrideCursorHandle = IntPtr.Zero;
2415
2416                         queue.DispatchIdle = false;
2417
2418                         while (PeekMessage(queue, ref msg, IntPtr.Zero, 0, 0, (uint)PeekMessageFlags.PM_REMOVE)) {
2419                                 TranslateMessage (ref msg);
2420                                 DispatchMessage (ref msg);
2421                         }
2422
2423                         queue.DispatchIdle = true;
2424                 }
2425
2426                 // double buffering support
2427                 public void CreateOffscreenDrawable (IntPtr handle,
2428                                                      int width, int height,
2429                                                      out object offscreen_drawable)
2430                 {
2431                         IntPtr root_out;
2432                         int x_out, y_out, width_out, height_out, border_width_out, depth_out;
2433
2434                         Xlib.XGetGeometry (display, handle,
2435                                            out root_out,
2436                                            out x_out, out y_out,
2437                                            out width_out, out height_out,
2438                                            out border_width_out, out depth_out);
2439
2440                         IntPtr pixmap = Xlib.XCreatePixmap (display, handle, width, height, depth_out);
2441
2442                         offscreen_drawable = pixmap;
2443                 }
2444
2445                 public void DestroyOffscreenDrawable (object offscreen_drawable)
2446                 {
2447                         Xlib.XFreePixmap (display, (IntPtr)offscreen_drawable);
2448                 }
2449
2450                 public Graphics GetOffscreenGraphics (object offscreen_drawable)
2451                 {
2452                         return Graphics.FromHwnd ((IntPtr) offscreen_drawable);
2453                 }
2454
2455                 public void BlitFromOffscreen (IntPtr dest_handle,
2456                                                Graphics dest_dc,
2457                                                object offscreen_drawable,
2458                                                Graphics offscreen_dc,
2459                                                Rectangle r)
2460                 {
2461                         XGCValues gc_values;
2462                         IntPtr gc;
2463
2464                         gc_values = new XGCValues();
2465
2466                         gc = Xlib.XCreateGC (display, dest_handle, IntPtr.Zero, ref gc_values);
2467
2468                         Xlib.XCopyArea (display, (IntPtr)offscreen_drawable, dest_handle,
2469                                         gc, r.X, r.Y, r.Width, r.Height, r.X, r.Y);
2470
2471                         Xlib.XFreeGC (display, gc);
2472                 }
2473
2474
2475                 // reversible screen-level drawing
2476                 IntPtr GetReversibleScreenGC (Color backColor)
2477                 {
2478                         XGCValues       gc_values;
2479                         IntPtr          gc;
2480                         uint pixel;
2481
2482                         XColor xcolor = new XColor();
2483                         xcolor.red = (ushort)(backColor.R * 257);
2484                         xcolor.green = (ushort)(backColor.G * 257);
2485                         xcolor.blue = (ushort)(backColor.B * 257);
2486                         Xlib.XAllocColor (display, DefaultColormap, ref xcolor);
2487                         pixel = (uint)xcolor.pixel.ToInt32();
2488
2489
2490                         gc_values = new XGCValues();
2491
2492                         gc_values.subwindow_mode = GCSubwindowMode.IncludeInferiors;
2493                         gc_values.foreground = (IntPtr)pixel;
2494
2495                         gc = Xlib.XCreateGC (display, RootWindow.Handle, new IntPtr ((int) (GCFunction.GCSubwindowMode | GCFunction.GCForeground)), ref gc_values);
2496                         Xlib.XSetForeground (display, gc, (UIntPtr)pixel);
2497                         Xlib.XSetFunction (display,   gc, GXFunction.GXxor);
2498
2499                         return gc;
2500                 }
2501
2502                 public void DrawReversibleLine (Point start, Point end, Color backColor)
2503                 {
2504                         IntPtr gc = GetReversibleScreenGC (backColor);
2505
2506                         Xlib.XDrawLine (display, RootWindow.Handle, gc, start.X, start.Y, end.X, end.Y);
2507
2508                         Xlib.XFreeGC (display, gc);
2509                 }
2510
2511                 public void FillReversibleRectangle (Rectangle rectangle, Color backColor)
2512                 {
2513                         IntPtr gc = GetReversibleScreenGC (backColor);
2514
2515                         if (rectangle.Width < 0) {
2516                                 rectangle.X += rectangle.Width;
2517                                 rectangle.Width = -rectangle.Width;
2518                         }
2519                         if (rectangle.Height < 0) {
2520                                 rectangle.Y += rectangle.Height;
2521                                 rectangle.Height = -rectangle.Height;
2522                         }
2523
2524                         Xlib.XFillRectangle (display, RootWindow.Handle, gc, rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height);
2525
2526                         Xlib.XFreeGC (display, gc);
2527                 }
2528
2529                 public void DrawReversibleFrame (Rectangle rectangle, Color backColor, FrameStyle style)
2530                 {
2531                         IntPtr gc = GetReversibleScreenGC (backColor);
2532
2533                         if (rectangle.Width < 0) {
2534                                 rectangle.X += rectangle.Width;
2535                                 rectangle.Width = -rectangle.Width;
2536                         }
2537                         if (rectangle.Height < 0) {
2538                                 rectangle.Y += rectangle.Height;
2539                                 rectangle.Height = -rectangle.Height;
2540                         }
2541
2542                         int line_width = 1;
2543                         GCLineStyle line_style = GCLineStyle.LineSolid;
2544                         GCCapStyle cap_style = GCCapStyle.CapButt;
2545                         GCJoinStyle join_style = GCJoinStyle.JoinMiter;
2546
2547                         switch (style) {
2548                         case FrameStyle.Dashed:
2549                                 line_style = GCLineStyle.LineOnOffDash;
2550                                 break;
2551                         case FrameStyle.Thick:
2552                                 line_width = 2;
2553                                 break;
2554                         }
2555
2556                         Xlib.XSetLineAttributes (display, gc, line_width, line_style, cap_style, join_style);
2557
2558                         Xlib.XDrawRectangle (display, RootWindow.Handle, gc, rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height);
2559
2560                         Xlib.XFreeGC (display, gc);
2561                 }
2562         }
2563 }