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