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