2010-02-03 Carlos Alberto Cortez <calberto.cortez@gmail.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / XplatUICarbon.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-2007 Novell, Inc.
21 //
22 // Authors:
23 //      Geoff Norton  <gnorton@novell.com>
24 //
25 //
26
27 using System;
28 using System.Threading;
29 using System.Drawing;
30 using System.ComponentModel;
31 using System.Collections;
32 using System.Diagnostics;
33 using System.Runtime.InteropServices;
34
35 using Carbon = System.Windows.Forms.CarbonInternal;
36
37 /// Carbon Version
38 namespace System.Windows.Forms {
39         internal delegate Rectangle [] HwndDelegate (IntPtr handle);
40
41         internal class XplatUICarbon : XplatUIDriver {
42                 #region Local Variables
43                 // General driver variables
44                 private static XplatUICarbon Instance;
45                 private static int RefCount;
46                 private static bool themes_enabled;
47
48                 // Internal members available to the event handler sub-system
49                 internal static IntPtr FocusWindow;
50                 internal static IntPtr ActiveWindow;
51                 internal static IntPtr ReverseWindow;
52                 internal static IntPtr CaretWindow;
53
54                 internal static Hwnd MouseHwnd;
55
56                 internal static MouseButtons MouseState;
57                 internal static Carbon.Hover Hover;
58
59                 internal static HwndDelegate HwndDelegate = new HwndDelegate (GetClippingRectangles);
60                 // Instance members
61                 internal Point mouse_position;
62
63                 // Event handlers
64                 internal Carbon.ApplicationHandler ApplicationHandler;
65                 internal Carbon.ControlHandler ControlHandler;
66                 internal Carbon.HIObjectHandler HIObjectHandler;
67                 internal Carbon.KeyboardHandler KeyboardHandler;
68                 internal Carbon.MouseHandler MouseHandler;
69                 internal Carbon.WindowHandler WindowHandler;
70                 
71                 // Carbon Specific
72                 internal static GrabStruct Grab;
73                 internal static Carbon.Caret Caret;
74                 private static Carbon.Dnd Dnd;
75                 private static Hashtable WindowMapping;
76                 private static Hashtable HandleMapping;
77                 private static IntPtr FosterParent;
78                 private static IntPtr Subclass;
79                 private static int MenuBarHeight;
80                 internal static ArrayList UtilityWindows;
81
82                 // Message loop
83                 private static Queue MessageQueue;
84                 private static bool GetMessageResult;
85
86                 private static bool ReverseWindowMapped;
87
88                 // Timers
89                 private ArrayList TimerList;
90                 private static bool in_doevents;
91                 
92                 static readonly object instancelock = new object ();
93                 static readonly object queuelock = new object ();
94                 
95                 // Event Handlers
96                 internal override event EventHandler Idle;
97                 #endregion
98                 
99                 #region Constructors
100                 private XplatUICarbon() {
101
102                         RefCount = 0;
103                         TimerList = new ArrayList ();
104                         in_doevents = false;
105                         MessageQueue = new Queue ();
106                         
107                         Initialize ();
108                 }
109
110                 ~XplatUICarbon() {
111                         // FIXME: Clean up the FosterParent here.
112                 }
113                 #endregion
114
115                 #region Singleton specific code
116                 public static XplatUICarbon GetInstance() {
117                         lock (instancelock) {
118                                 if (Instance == null) {
119                                         Instance = new XplatUICarbon ();
120                                 }
121                                 RefCount++;
122                         }
123                         return Instance;
124                 }
125
126                 public int Reference {
127                         get {
128                                 return RefCount;
129                         }
130                 }
131                 #endregion
132                 
133                 #region Internal methods
134                 internal void AddExpose (Hwnd hwnd, bool client, Carbon.HIRect rect) {
135                         AddExpose (hwnd, client, (int) rect.origin.x, (int) rect.origin.y, (int) rect.size.width, (int) rect.size.height);
136                 }
137                 
138                 internal void AddExpose (Hwnd hwnd, bool client, Rectangle rect) {
139                         AddExpose (hwnd, client, (int) rect.X, (int) rect.Y, (int) rect.Width, (int) rect.Height);
140                 }
141
142                 internal void FlushQueue () {
143                         CheckTimers (DateTime.UtcNow);
144                         lock (queuelock) {
145                                 while (MessageQueue.Count > 0) {
146                                         object queueobj = MessageQueue.Dequeue ();
147                                         if (queueobj is GCHandle) {
148                                                 XplatUIDriverSupport.ExecuteClientMessage((GCHandle)queueobj);
149                                         } else {
150                                                 MSG msg = (MSG)queueobj;
151                                                 NativeWindow.WndProc (msg.hwnd, msg.message, msg.wParam, msg.lParam);
152                                         }
153                                 }
154                         }
155                 }
156
157                 internal static Rectangle [] GetClippingRectangles (IntPtr handle) {
158                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
159
160                         if (hwnd == null)
161                                 return null;
162                         if (hwnd.Handle != handle)
163                                 return new Rectangle [] {hwnd.ClientRect};
164
165                         return (Rectangle []) hwnd.GetClippingRectangles ().ToArray (typeof (Rectangle));
166                 }
167
168                 internal IntPtr GetMousewParam(int Delta) {
169                         int      result = 0;
170
171                         if ((MouseState & MouseButtons.Left) != 0) {
172                                 result |= (int)MsgButtons.MK_LBUTTON;
173                         }
174
175                         if ((MouseState & MouseButtons.Middle) != 0) {
176                                 result |= (int)MsgButtons.MK_MBUTTON;
177                         }
178
179                         if ((MouseState & MouseButtons.Right) != 0) {
180                                 result |= (int)MsgButtons.MK_RBUTTON;
181                         }
182
183                         Keys mods = ModifierKeys;
184                         if ((mods & Keys.Control) != 0) {
185                                 result |= (int)MsgButtons.MK_CONTROL;
186                         }
187
188                         if ((mods & Keys.Shift) != 0) {
189                                 result |= (int)MsgButtons.MK_SHIFT;
190                         }
191
192                         result |= Delta << 16;
193
194                         return (IntPtr)result;
195                 }
196
197                 internal IntPtr HandleToWindow (IntPtr handle) {
198                         if (HandleMapping [handle] != null)
199                                 return (IntPtr) HandleMapping [handle];
200                         return IntPtr.Zero;
201                 }
202
203                 internal void Initialize () {
204                         // Initialize the event handlers        
205                         Carbon.EventHandler.Driver = this;
206                         ApplicationHandler = new Carbon.ApplicationHandler (this);
207                         ControlHandler = new Carbon.ControlHandler (this);
208                         HIObjectHandler = new Carbon.HIObjectHandler (this);
209                         KeyboardHandler = new Carbon.KeyboardHandler (this);
210                         MouseHandler = new Carbon.MouseHandler (this);
211                         WindowHandler = new Carbon.WindowHandler (this);
212                         
213                         // Initilize the mouse controls
214                         Hover.Interval = 500;
215                         Hover.Timer = new Timer ();
216                         Hover.Timer.Enabled = false;
217                         Hover.Timer.Interval = Hover.Interval;
218                         Hover.Timer.Tick += new EventHandler (HoverCallback);
219                         Hover.X = -1;
220                         Hover.Y = -1;
221                         MouseState = MouseButtons.None;
222                         mouse_position = Point.Empty;
223                                 
224                         // Initialize the Caret
225                         Caret.Timer = new Timer ();
226                         Caret.Timer.Interval = 500;
227                         Caret.Timer.Tick += new EventHandler (CaretCallback);
228
229                         // Initialize the D&D
230                         Dnd = new Carbon.Dnd (); 
231                         
232                         // Initialize the Carbon Specific stuff
233                         WindowMapping = new Hashtable ();
234                         HandleMapping = new Hashtable ();
235                         UtilityWindows = new ArrayList ();
236                         
237                         // Initialize the FosterParent
238                         Carbon.Rect rect = new Carbon.Rect ();
239                         SetRect (ref rect, (short)0, (short)0, (short)0, (short)0);
240                         Carbon.ProcessSerialNumber psn = new Carbon.ProcessSerialNumber();
241
242                         GetCurrentProcess( ref psn );
243                         TransformProcessType (ref psn, 1);
244                         SetFrontProcess (ref psn);
245
246                         HIObjectRegisterSubclass (__CFStringMakeConstantString ("com.novell.mwfview"), __CFStringMakeConstantString ("com.apple.hiview"), 0, Carbon.EventHandler.EventHandlerDelegate, (uint)Carbon.EventHandler.HIObjectEvents.Length, Carbon.EventHandler.HIObjectEvents, IntPtr.Zero, ref Subclass);
247
248                         Carbon.EventHandler.InstallApplicationHandler ();
249
250                         CreateNewWindow (Carbon.WindowClass.kDocumentWindowClass, Carbon.WindowAttributes.kWindowStandardHandlerAttribute | Carbon.WindowAttributes.kWindowCloseBoxAttribute | Carbon.WindowAttributes.kWindowFullZoomAttribute | Carbon.WindowAttributes.kWindowCollapseBoxAttribute | Carbon.WindowAttributes.kWindowResizableAttribute | Carbon.WindowAttributes.kWindowCompositingAttribute, ref rect, ref FosterParent);
251                         
252                         CreateNewWindow (Carbon.WindowClass.kOverlayWindowClass, Carbon.WindowAttributes.kWindowNoUpdatesAttribute | Carbon.WindowAttributes.kWindowNoActivatesAttribute, ref rect, ref ReverseWindow);
253                         CreateNewWindow (Carbon.WindowClass.kOverlayWindowClass, Carbon.WindowAttributes.kWindowNoUpdatesAttribute | Carbon.WindowAttributes.kWindowNoActivatesAttribute, ref rect, ref CaretWindow);
254                         
255                         // Get some values about bar heights
256                         Carbon.Rect structRect = new Carbon.Rect ();
257                         Carbon.Rect contentRect = new Carbon.Rect ();
258                         GetWindowBounds (FosterParent, 32, ref structRect);
259                         GetWindowBounds (FosterParent, 33, ref contentRect);
260                         
261                         MenuBarHeight = GetMBarHeight ();
262                         
263                         // Focus
264                         FocusWindow = IntPtr.Zero;
265                         
266                         // Message loop
267                         GetMessageResult = true;
268                         
269                         ReverseWindowMapped = false;
270                 }
271                 
272                 internal void PerformNCCalc(Hwnd hwnd) {
273                         XplatUIWin32.NCCALCSIZE_PARAMS  ncp;
274                         IntPtr ptr;
275                         Rectangle rect;
276
277                         rect = new Rectangle (0, 0, hwnd.Width, hwnd.Height);
278
279                         ncp = new XplatUIWin32.NCCALCSIZE_PARAMS();
280                         ptr = Marshal.AllocHGlobal(Marshal.SizeOf(ncp));
281
282                         ncp.rgrc1.left = rect.Left;
283                         ncp.rgrc1.top = rect.Top;
284                         ncp.rgrc1.right = rect.Right;
285                         ncp.rgrc1.bottom = rect.Bottom;
286
287                         Marshal.StructureToPtr(ncp, ptr, true);
288                         NativeWindow.WndProc(hwnd.client_window, Msg.WM_NCCALCSIZE, (IntPtr)1, ptr);
289                         ncp = (XplatUIWin32.NCCALCSIZE_PARAMS)Marshal.PtrToStructure(ptr, typeof(XplatUIWin32.NCCALCSIZE_PARAMS));
290                         Marshal.FreeHGlobal(ptr);
291
292
293                         rect = new Rectangle(ncp.rgrc1.left, ncp.rgrc1.top, ncp.rgrc1.right - ncp.rgrc1.left, ncp.rgrc1.bottom - ncp.rgrc1.top);
294                         hwnd.ClientRect = rect;
295
296                         rect = TranslateClientRectangleToQuartzClientRectangle (hwnd);
297
298                         if (hwnd.visible) {
299                                 Carbon.HIRect r = new Carbon.HIRect (rect.X, rect.Y, rect.Width, rect.Height);
300                                 HIViewSetFrame (hwnd.client_window, ref r);
301                         }
302         
303                         AddExpose (hwnd, false, 0, 0, hwnd.Width, hwnd.Height);
304                 }
305                 
306                 internal void ScreenToClient(IntPtr handle, ref Carbon.QDPoint point) {
307                         int x = (int) point.x;
308                         int y = (int) point.y;
309
310                         ScreenToClient (handle, ref x, ref y);
311
312                         point.x = (short) x;
313                         point.y = (short) y;
314                 }
315                 
316                 internal static Rectangle TranslateClientRectangleToQuartzClientRectangle (Hwnd hwnd) {
317                         return TranslateClientRectangleToQuartzClientRectangle (hwnd, Control.FromHandle (hwnd.Handle));
318                 }
319
320                 internal static Rectangle TranslateClientRectangleToQuartzClientRectangle (Hwnd hwnd, Control ctrl) {
321                         /* From XplatUIX11
322                          * If this is a form with no window manager, X is handling all the border and caption painting
323                          * so remove that from the area (since the area we set of the window here is the part of the window 
324                          * we're painting in only)
325                          */
326                         Rectangle rect = hwnd.ClientRect;
327                         Form form = ctrl as Form;
328                         CreateParams cp = null;
329
330                         if (form != null)
331                                 cp = form.GetCreateParams ();
332
333                         if (form != null && (form.window_manager == null || cp.IsSet (WindowExStyles.WS_EX_TOOLWINDOW))) {
334                                 Hwnd.Borders borders = Hwnd.GetBorders (cp, null);
335                                 Rectangle qrect = rect;
336                                 
337                                 qrect.Y -= borders.top;
338                                 qrect.X -= borders.left;
339                                 qrect.Width += borders.left + borders.right;
340                                 qrect.Height += borders.top + borders.bottom;
341                                 
342                                 rect = qrect;
343                         }
344                         
345                         if (rect.Width < 1 || rect.Height < 1) {
346                                 rect.Width = 1;
347                                 rect.Height = 1;
348                                 rect.X = -5;
349                                 rect.Y = -5;
350                         }
351                         
352                         return rect;
353                 }
354
355                 internal static Size TranslateWindowSizeToQuartzWindowSize (CreateParams cp) {
356                         return TranslateWindowSizeToQuartzWindowSize (cp, new Size (cp.Width, cp.Height));
357                 }
358
359                 internal static Size TranslateWindowSizeToQuartzWindowSize (CreateParams cp, Size size) {
360                         /* From XplatUIX11
361                          * If this is a form with no window manager, X is handling all the border and caption painting
362                          * so remove that from the area (since the area we set of the window here is the part of the window 
363                          * we're painting in only)
364                          */
365                         Form form = cp.control as Form;
366                         if (form != null && (form.window_manager == null || cp.IsSet (WindowExStyles.WS_EX_TOOLWINDOW))) {
367                                 Hwnd.Borders borders = Hwnd.GetBorders (cp, null);
368                                 Size qsize = size;
369
370                                 qsize.Width -= borders.left + borders.right;
371                                 qsize.Height -= borders.top + borders.bottom; 
372                                 
373                                 size = qsize;
374                         }
375
376                         if (size.Height == 0)
377                                 size.Height = 1;
378                         if (size.Width == 0)
379                                 size.Width = 1;
380                         return size;
381                 }
382                         
383                 internal static Size TranslateQuartzWindowSizeToWindowSize (CreateParams cp, int width, int height) {
384                         /* From XplatUIX11
385                          * If this is a form with no window manager, X is handling all the border and caption painting
386                          * so remove that from the area (since the area we set of the window here is the part of the window 
387                          * we're painting in only)
388                          */
389                         Size size = new Size (width, height);
390                         Form form = cp.control as Form;
391                         if (form != null && (form.window_manager == null || cp.IsSet (WindowExStyles.WS_EX_TOOLWINDOW))) {
392                                 Hwnd.Borders borders = Hwnd.GetBorders (cp, null);
393                                 Size qsize = size;
394
395                                 qsize.Width += borders.left + borders.right;
396                                 qsize.Height += borders.top + borders.bottom;
397                                 
398                                 size = qsize;
399                         }
400
401                         return size;
402                 }
403                 #endregion
404                 
405                 #region Callbacks
406                 private void CaretCallback (object sender, EventArgs e) {
407                         if (Caret.Paused) {
408                                 return;
409                         }
410
411                         if (!Caret.On) {
412                                 ShowCaret ();
413                         } else {
414                                 HideCaret ();
415                         }
416                 }
417                 
418                 private void HoverCallback (object sender, EventArgs e) {
419                         if ((Hover.X == mouse_position.X) && (Hover.Y == mouse_position.Y)) {
420                                 MSG msg = new MSG ();
421                                 msg.hwnd = Hover.Hwnd;
422                                 msg.message = Msg.WM_MOUSEHOVER;
423                                 msg.wParam = GetMousewParam (0);
424                                 msg.lParam = (IntPtr)((ushort)Hover.X << 16 | (ushort)Hover.X);
425                                 EnqueueMessage (msg);
426                         }
427                 }
428                 #endregion
429                 
430                 #region Private Methods
431                 private Point ConvertScreenPointToClient (IntPtr handle, Point point) {
432                         Point converted_point = new Point ();
433                         Carbon.Rect window_bounds = new Carbon.Rect ();
434                         Carbon.CGPoint native_point = new Carbon.CGPoint ();
435
436                         GetWindowBounds (HIViewGetWindow (handle), 32, ref window_bounds);
437                         
438                         native_point.x = (point.X - window_bounds.left);
439                         native_point.y = (point.Y - window_bounds.top);
440
441                         HIViewConvertPoint (ref native_point, IntPtr.Zero, handle);
442
443                         converted_point.X = (int)native_point.x;
444                         converted_point.Y = (int)native_point.y;
445
446                         return converted_point;
447                 }
448                 
449                 private Point ConvertClientPointToScreen (IntPtr handle, Point point) {
450                         Point converted_point = new Point ();
451                         Carbon.Rect window_bounds = new Carbon.Rect ();
452                         Carbon.CGPoint native_point = new Carbon.CGPoint ();
453
454                         GetWindowBounds (HIViewGetWindow (handle), 32, ref window_bounds);
455                         
456                         native_point.x = point.X;
457                         native_point.y = point.Y;
458
459                         HIViewConvertPoint (ref native_point, handle, IntPtr.Zero);
460
461                         converted_point.X = (int)(native_point.x + window_bounds.left);
462                         converted_point.Y = (int)(native_point.y + window_bounds.top);
463
464                         return converted_point;
465                 }
466
467                 private double NextTimeout () {
468                         DateTime now = DateTime.UtcNow;
469                         int timeout = 0x7FFFFFF;
470                         lock (TimerList) {
471                                 foreach (Timer timer in TimerList) {
472                                         int next = (int) (timer.Expires - now).TotalMilliseconds;
473                                         if (next < 0)
474                                                 return 0;
475                                         if (next < timeout)
476                                                 timeout = next;
477                                 }
478                         }
479                         if (timeout < Timer.Minimum)
480                                 timeout = Timer.Minimum;
481
482                         return (double)((double)timeout/1000);
483                 }
484                 
485                 private void CheckTimers (DateTime now) {
486                         lock (TimerList) {
487                                 int count = TimerList.Count;
488                                 if (count == 0)
489                                         return;
490                                 for (int i = 0; i < TimerList.Count; i++) {
491                                         Timer timer = (Timer) TimerList [i];
492                                         if (timer.Enabled && timer.Expires <= now) {
493                                                 // Timer ticks:
494                                                 //  - Before MainForm.OnLoad if DoEvents () is called.
495                                                 //  - After MainForm.OnLoad if not.
496                                                 //
497                                                 if (in_doevents ||
498                                                     (Application.MWFThread.Current.Context != null && 
499                                                      Application.MWFThread.Current.Context.MainForm != null && 
500                                                      Application.MWFThread.Current.Context.MainForm.IsLoaded)) {
501                                                         timer.FireTick ();
502                                                         timer.Update (now);
503                                                 }
504                                         }
505                                 }
506                         }
507                 }
508                 
509                 private void WaitForHwndMessage (Hwnd hwnd, Msg message) {
510                         MSG msg = new MSG ();
511
512                         bool done = false;
513                         do {
514                                 if (GetMessage(null, ref msg, IntPtr.Zero, 0, 0)) {
515                                         if ((Msg)msg.message == Msg.WM_QUIT) {
516                                                 PostQuitMessage (0);
517                                                 done = true;
518                                         }
519                                         else {
520                                                 if (msg.hwnd == hwnd.Handle) {
521                                                         if ((Msg)msg.message == message)
522                                                                 break;
523                                                         else if ((Msg)msg.message == Msg.WM_DESTROY)
524                                                                 done = true;
525                                                 }
526
527                                                 TranslateMessage (ref msg);
528                                                 DispatchMessage (ref msg);
529                                         }
530                                 }
531                         } while (!done);
532                 }
533
534                 private void SendParentNotify(IntPtr child, Msg cause, int x, int y) {
535                         Hwnd hwnd;
536                         
537                         if (child == IntPtr.Zero) {
538                                 return;
539                         }
540                         
541                         hwnd = Hwnd.GetObjectFromWindow (child);
542                         
543                         if (hwnd == null) {
544                                 return;
545                         }
546                         
547                         if (hwnd.Handle == IntPtr.Zero) {
548                                 return;
549                         }
550                         
551                         if (ExStyleSet ((int) hwnd.initial_ex_style, WindowExStyles.WS_EX_NOPARENTNOTIFY)) {
552                                 return;
553                         }
554                         
555                         if (hwnd.Parent == null) {
556                                 return;
557                         }
558                         
559                         if (hwnd.Parent.Handle == IntPtr.Zero) {
560                                 return;
561                         }
562
563                         if (cause == Msg.WM_CREATE || cause == Msg.WM_DESTROY) {
564                                 SendMessage(hwnd.Parent.Handle, Msg.WM_PARENTNOTIFY, Control.MakeParam((int)cause, 0), child);
565                         } else {
566                                 SendMessage(hwnd.Parent.Handle, Msg.WM_PARENTNOTIFY, Control.MakeParam((int)cause, 0), Control.MakeParam(x, y));
567                         }
568                         
569                         SendParentNotify (hwnd.Parent.Handle, cause, x, y);
570                 }
571
572                 private bool StyleSet (int s, WindowStyles ws) {
573                         return (s & (int)ws) == (int)ws;
574                 }
575
576                 private bool ExStyleSet (int ex, WindowExStyles exws) {
577                         return (ex & (int)exws) == (int)exws;
578                 }
579
580                 private void DeriveStyles(int Style, int ExStyle, out FormBorderStyle border_style, out bool border_static, out TitleStyle title_style, out int caption_height, out int tool_caption_height) {
581
582                         caption_height = 0;
583                         tool_caption_height = 0;
584                         border_static = false;
585
586                         if (StyleSet (Style, WindowStyles.WS_CHILD)) {
587                                 if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_CLIENTEDGE)) {
588                                         border_style = FormBorderStyle.Fixed3D;
589                                 } else if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_STATICEDGE)) {
590                                         border_style = FormBorderStyle.Fixed3D;
591                                         border_static = true;
592                                 } else if (!StyleSet (Style, WindowStyles.WS_BORDER)) {
593                                         border_style = FormBorderStyle.None;
594                                 } else {
595                                         border_style = FormBorderStyle.FixedSingle;
596                                 }
597                                 title_style = TitleStyle.None;
598                                 
599                                 if (StyleSet (Style, WindowStyles.WS_CAPTION)) {
600                                         caption_height = 0;
601                                         if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
602                                                 title_style = TitleStyle.Tool;
603                                         } else {
604                                                 title_style = TitleStyle.Normal;
605                                         }
606                                 }
607
608                                 if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_MDICHILD)) {
609                                         caption_height = 0;
610
611                                         if (StyleSet (Style, WindowStyles.WS_OVERLAPPEDWINDOW) ||
612                                                 ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
613                                                 border_style = (FormBorderStyle) 0xFFFF;
614                                         } else {
615                                                 border_style = FormBorderStyle.None;
616                                         }
617                                 }
618
619                         } else {
620                                 title_style = TitleStyle.None;
621                                 if (StyleSet (Style, WindowStyles.WS_CAPTION)) {
622                                         if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
623                                                 title_style = TitleStyle.Tool;
624                                         } else {
625                                                 title_style = TitleStyle.Normal;
626                                         }
627                                 }
628
629                                 border_style = FormBorderStyle.None;
630
631                                 if (StyleSet (Style, WindowStyles.WS_THICKFRAME)) {
632                                         if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
633                                                 border_style = FormBorderStyle.SizableToolWindow;
634                                         } else {
635                                                 border_style = FormBorderStyle.Sizable;
636                                         }
637                                 } else {
638                                         if (StyleSet (Style, WindowStyles.WS_CAPTION)) {
639                                                 if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_CLIENTEDGE)) {
640                                                         border_style = FormBorderStyle.Fixed3D;
641                                                 } else if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_STATICEDGE)) {
642                                                         border_style = FormBorderStyle.Fixed3D;
643                                                         border_static = true;
644                                                 } else if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_DLGMODALFRAME)) {
645                                                         border_style = FormBorderStyle.FixedDialog;
646                                                 } else if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
647                                                         border_style = FormBorderStyle.FixedToolWindow;
648                                                 } else if (StyleSet (Style, WindowStyles.WS_BORDER)) {
649                                                         border_style = FormBorderStyle.FixedSingle;
650                                                 }
651                                         } else {
652                                                 if (StyleSet (Style, WindowStyles.WS_BORDER)) {
653                                                         border_style = FormBorderStyle.FixedSingle;
654                                                 }
655                                         }
656                                 }
657                         }
658                 }
659                 
660                 private void SetHwndStyles(Hwnd hwnd, CreateParams cp) {
661                         DeriveStyles(cp.Style, cp.ExStyle, out hwnd.border_style, out hwnd.border_static, out hwnd.title_style, out hwnd.caption_height, out hwnd.tool_caption_height);
662                 }
663                 
664                 private void ShowCaret () {
665                         if (Caret.On)
666                                 return;
667                         Caret.On = true;
668                         ShowWindow (CaretWindow);
669                         Graphics g = Graphics.FromHwnd (HIViewGetRoot (CaretWindow));
670
671                         g.FillRectangle (new SolidBrush (Color.Black), new Rectangle (0, 0, Caret.Width, Caret.Height));
672
673                         g.Dispose ();
674                 }
675
676                 private void HideCaret () {
677                         if (!Caret.On)
678                                 return;
679                         Caret.On = false;
680                         HideWindow (CaretWindow);
681                 }
682                 
683                 private void AccumulateDestroyedHandles (Control c, ArrayList list) {
684                         if (c != null) {
685                                 Control[] controls = c.Controls.GetAllControls ();
686
687                                 if (c.IsHandleCreated && !c.IsDisposed) {
688                                         Hwnd hwnd = Hwnd.ObjectFromHandle(c.Handle);
689
690                                         list.Add (hwnd);
691                                         CleanupCachedWindows (hwnd);
692                                 }
693
694                                 for (int  i = 0; i < controls.Length; i ++) {
695                                         AccumulateDestroyedHandles (controls[i], list);
696                                 }
697                         }
698                         
699                 }
700
701                 private void CleanupCachedWindows (Hwnd hwnd) {
702                         if (ActiveWindow == hwnd.Handle) {
703                                 SendMessage(hwnd.client_window, Msg.WM_ACTIVATE, (IntPtr)WindowActiveFlags.WA_INACTIVE, IntPtr.Zero);
704                                 ActiveWindow = IntPtr.Zero;
705                         }
706
707                         if (FocusWindow == hwnd.Handle) {
708                                 SendMessage(hwnd.client_window, Msg.WM_KILLFOCUS, IntPtr.Zero, IntPtr.Zero);
709                                 FocusWindow = IntPtr.Zero;
710                         }
711
712                         if (Grab.Hwnd == hwnd.Handle) {
713                                 Grab.Hwnd = IntPtr.Zero;
714                                 Grab.Confined = false;
715                         }
716
717                         DestroyCaret (hwnd.Handle);
718                 }
719
720                 private void AddExpose (Hwnd hwnd, bool client, int x, int y, int width, int height) {
721                         // Don't waste time
722                         if ((hwnd == null) || (x > hwnd.Width) || (y > hwnd.Height) || ((x + width) < 0) || ((y + height) < 0)) {
723                                 return;
724                         }
725
726                         // Keep the invalid area as small as needed
727                         if ((x + width) > hwnd.width) {
728                                 width = hwnd.width - x;
729                         }
730
731                         if ((y + height) > hwnd.height) {
732                                 height = hwnd.height - y;
733                         }
734
735                         if (client) {
736                                 hwnd.AddInvalidArea(x, y, width, height);
737                                 if (!hwnd.expose_pending && hwnd.visible) {
738                                         MSG msg = new MSG ();
739                                         msg.message = Msg.WM_PAINT;
740                                         msg.hwnd = hwnd.Handle;
741                                         EnqueueMessage (msg);
742                                         hwnd.expose_pending = true;
743                                 }
744                         } else {
745                                 hwnd.AddNcInvalidArea (x, y, width, height);
746                                 if (!hwnd.nc_expose_pending && hwnd.visible) {
747                                         MSG msg = new MSG ();
748                                         Region rgn = new Region (hwnd.Invalid);
749                                         IntPtr hrgn = rgn.GetHrgn (null); // Graphics object isn't needed
750                                         msg.message = Msg.WM_NCPAINT;
751                                         msg.wParam = hrgn == IntPtr.Zero ? (IntPtr)1 : hrgn;
752                                         msg.refobject = rgn;
753                                         msg.hwnd = hwnd.Handle;
754                                         EnqueueMessage (msg);
755                                         hwnd.nc_expose_pending = true;
756
757                                 }
758                         }
759                 }
760                 #endregion 
761
762                 #region Public Methods
763                 internal void EnqueueMessage (MSG msg) {
764                         lock (queuelock) {
765                                 MessageQueue.Enqueue (msg);
766                         }
767                 }
768
769                 internal override void RaiseIdle (EventArgs e)
770                 {
771                         if (Idle != null)
772                                 Idle (this, e);
773                 }
774
775                 internal override IntPtr InitializeDriver() {
776                         return IntPtr.Zero;
777                 }
778
779                 internal override void ShutdownDriver(IntPtr token) {
780                 }
781
782                 internal override void EnableThemes() {
783                         themes_enabled = true;
784                 }
785
786                 internal override void Activate(IntPtr handle) {
787                         if (ActiveWindow != IntPtr.Zero) {
788                                 ActivateWindow (HIViewGetWindow (ActiveWindow), false);
789                         }
790                         ActivateWindow (HIViewGetWindow (handle), true);
791                         ActiveWindow = handle;
792                 }
793
794                 internal override void AudibleAlert(AlertType alert) {
795                         AlertSoundPlay ();
796                 }
797
798                 internal override void BeginMoveResize (IntPtr handle) {
799                 }
800
801                 internal override void CaretVisible (IntPtr hwnd, bool visible) {
802                         if (Caret.Hwnd == hwnd) {
803                                 if (visible) {
804                                         if (Caret.Visible < 1) {
805                                                 Caret.Visible++;
806                                                 Caret.On = false;
807                                                 if (Caret.Visible == 1) {
808                                                         ShowCaret ();
809                                                         Caret.Timer.Start ();
810                                                 }
811                                         }
812                                 } else {
813                                         Caret.Visible--;
814                                         if (Caret.Visible == 0) {
815                                                 Caret.Timer.Stop ();
816                                                 HideCaret ();
817                                         }
818                                 }
819                         }
820                 }
821                 
822                 internal override bool CalculateWindowRect(ref Rectangle ClientRect, CreateParams cp, Menu menu, out Rectangle WindowRect) {
823                         WindowRect = Hwnd.GetWindowRectangle (cp, menu, ClientRect);
824                         return true;
825                 }
826
827                 internal override void ClientToScreen(IntPtr handle, ref int x, ref int y) {
828                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
829
830                         Point point = ConvertClientPointToScreen (hwnd.ClientWindow, new Point (x, y));
831
832                         x = point.X;
833                         y = point.Y;
834                 }
835                 
836                 internal override void MenuToScreen(IntPtr handle, ref int x, ref int y) {
837                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
838
839                         Point point = ConvertClientPointToScreen (hwnd.ClientWindow, new Point (x, y));
840
841                         x = point.X;
842                         y = point.Y;
843                 }
844
845                 internal override int[] ClipboardAvailableFormats(IntPtr handle) {
846                         ArrayList list = new ArrayList ();
847                         DataFormats.Format f = DataFormats.Format.List;
848
849                         while (f != null) {
850                                 list.Add (f.Id);
851                                 f = f.Next;
852                         }
853
854                         return (int [])list.ToArray (typeof (int));
855                 }
856
857                 internal override void ClipboardClose(IntPtr handle) {
858                 }
859
860                 //TODO: Map our internal formats to the right os code where we can
861                 internal override int ClipboardGetID(IntPtr handle, string format) {
862                         return (int)__CFStringMakeConstantString (format);
863                 }
864
865                 internal override IntPtr ClipboardOpen(bool primary_selection) {
866                         if (primary_selection)
867                                 return Carbon.Pasteboard.Primary;
868                         return Carbon.Pasteboard.Application;
869                 }
870
871                 internal override object ClipboardRetrieve(IntPtr handle, int type, XplatUI.ClipboardToObject converter) {
872                         return Carbon.Pasteboard.Retrieve (handle, type);
873                 }
874
875                 internal override void ClipboardStore(IntPtr handle, object obj, int type, XplatUI.ObjectToClipboard converter) {
876                         Carbon.Pasteboard.Store (handle, obj, type);
877                 }
878                 
879                 internal override void CreateCaret (IntPtr hwnd, int width, int height) {
880                         if (Caret.Hwnd != IntPtr.Zero)
881                                 DestroyCaret (Caret.Hwnd);
882
883                         Caret.Hwnd = hwnd;
884                         Caret.Width = width;
885                         Caret.Height = height;
886                         Caret.Visible = 0;
887                         Caret.On = false;
888                 }
889                 
890                 internal override IntPtr CreateWindow(CreateParams cp) {
891                         Hwnd hwnd;
892                         Hwnd parent_hwnd = null;
893                         int X;
894                         int Y;
895                         int Width;
896                         int Height;
897                         IntPtr ParentHandle;
898                         IntPtr WindowHandle;
899                         IntPtr WholeWindow;
900                         IntPtr ClientWindow;
901                         IntPtr WholeWindowTracking;
902                         IntPtr ClientWindowTracking;
903
904                         hwnd = new Hwnd ();
905
906                         X = cp.X;
907                         Y = cp.Y;
908                         Width = cp.Width;
909                         Height = cp.Height;
910                         ParentHandle = IntPtr.Zero;
911                         WindowHandle = IntPtr.Zero;
912                         WholeWindow = IntPtr.Zero;
913                         ClientWindow = IntPtr.Zero;
914                         WholeWindowTracking = IntPtr.Zero;
915                         ClientWindowTracking = IntPtr.Zero;
916
917                         if (Width < 1) Width = 1;       
918                         if (Height < 1) Height = 1;     
919
920                         if (cp.Parent != IntPtr.Zero) {
921                                 parent_hwnd = Hwnd.ObjectFromHandle (cp.Parent);
922                                 ParentHandle = parent_hwnd.client_window;
923                         } else {
924                                 if (StyleSet (cp.Style, WindowStyles.WS_CHILD)) {
925                                         HIViewFindByID (HIViewGetRoot (FosterParent), new Carbon.HIViewID (Carbon.EventHandler.kEventClassWindow, 1), ref ParentHandle);
926                                 }
927                         }
928
929                         Point next;
930                         if (cp.control is Form) {
931                                 next = Hwnd.GetNextStackedFormLocation (cp, parent_hwnd);
932                                 X = next.X;
933                                 Y = next.Y;
934                         }
935
936                         hwnd.x = X;
937                         hwnd.y = Y;
938                         hwnd.width = Width;
939                         hwnd.height = Height;
940                         hwnd.Parent = Hwnd.ObjectFromHandle (cp.Parent);
941                         hwnd.initial_style = cp.WindowStyle;
942                         hwnd.initial_ex_style = cp.WindowExStyle;
943                         hwnd.visible = false;
944
945                         if (StyleSet (cp.Style, WindowStyles.WS_DISABLED)) {
946                                 hwnd.enabled = false;
947                         }
948
949                         ClientWindow = IntPtr.Zero;
950
951                         Size QWindowSize = TranslateWindowSizeToQuartzWindowSize (cp);
952                         Rectangle QClientRect = TranslateClientRectangleToQuartzClientRectangle (hwnd, cp.control);
953
954                         SetHwndStyles(hwnd, cp);
955 /* FIXME */
956                         if (ParentHandle == IntPtr.Zero) {
957                                 IntPtr WindowView = IntPtr.Zero;
958                                 IntPtr GrowBox = IntPtr.Zero;
959                                 Carbon.WindowClass windowklass = Carbon.WindowClass.kOverlayWindowClass;
960                                 Carbon.WindowAttributes attributes = Carbon.WindowAttributes.kWindowCompositingAttribute | Carbon.WindowAttributes.kWindowStandardHandlerAttribute;
961                                 if (StyleSet (cp.Style, WindowStyles.WS_MINIMIZEBOX)) {
962                                         attributes |= Carbon.WindowAttributes.kWindowCollapseBoxAttribute;
963                                 }
964                                 if (StyleSet (cp.Style, WindowStyles.WS_MAXIMIZEBOX)) {
965                                         attributes |= Carbon.WindowAttributes.kWindowResizableAttribute | Carbon.WindowAttributes.kWindowHorizontalZoomAttribute | Carbon.WindowAttributes.kWindowVerticalZoomAttribute;
966                                 }
967                                 if (StyleSet (cp.Style, WindowStyles.WS_SYSMENU)) {
968                                         attributes |= Carbon.WindowAttributes.kWindowCloseBoxAttribute;
969                                 }
970                                 if (StyleSet (cp.Style, WindowStyles.WS_CAPTION)) {
971                                         windowklass = Carbon.WindowClass.kDocumentWindowClass;
972                                 }
973                                 if (hwnd.border_style == FormBorderStyle.FixedToolWindow) {
974                                         windowklass = Carbon.WindowClass.kUtilityWindowClass;
975                                 } else if (hwnd.border_style == FormBorderStyle.SizableToolWindow) {
976                                         attributes |= Carbon.WindowAttributes.kWindowResizableAttribute;
977                                         windowklass = Carbon.WindowClass.kUtilityWindowClass;
978                                 }
979                                 if (windowklass == Carbon.WindowClass.kOverlayWindowClass) {
980                                         attributes = Carbon.WindowAttributes.kWindowCompositingAttribute | Carbon.WindowAttributes.kWindowStandardHandlerAttribute;
981                                 }
982                                 attributes |= Carbon.WindowAttributes.kWindowLiveResizeAttribute;
983
984                                 Carbon.Rect rect = new Carbon.Rect ();
985                                 if (StyleSet (cp.Style, WindowStyles.WS_POPUP)) {
986                                         SetRect (ref rect, (short)X, (short)(Y), (short)(X + QWindowSize.Width), (short)(Y + QWindowSize.Height));
987                                 } else {
988                                         SetRect (ref rect, (short)X, (short)(Y + MenuBarHeight), (short)(X + QWindowSize.Width), (short)(Y + MenuBarHeight + QWindowSize.Height));
989                                 }
990
991                                 CreateNewWindow (windowklass, attributes, ref rect, ref WindowHandle);
992
993                                 Carbon.EventHandler.InstallWindowHandler (WindowHandle);
994                                 HIViewFindByID (HIViewGetRoot (WindowHandle), new Carbon.HIViewID (Carbon.EventHandler.kEventClassWindow, 1), ref WindowView);
995                                 HIViewFindByID (HIViewGetRoot (WindowHandle), new Carbon.HIViewID (Carbon.EventHandler.kEventClassWindow, 7), ref GrowBox);
996                                 HIGrowBoxViewSetTransparent (GrowBox, true);
997                                 SetAutomaticControlDragTrackingEnabledForWindow (WindowHandle, true);
998                                 ParentHandle = WindowView;
999                         }
1000
1001                         HIObjectCreate (__CFStringMakeConstantString ("com.novell.mwfview"), 0, ref WholeWindow);
1002                         HIObjectCreate (__CFStringMakeConstantString ("com.novell.mwfview"), 0, ref ClientWindow);
1003
1004                         Carbon.EventHandler.InstallControlHandler (WholeWindow);
1005                         Carbon.EventHandler.InstallControlHandler (ClientWindow);
1006
1007                         // Enable embedding on controls
1008                         HIViewChangeFeatures (WholeWindow, 1<<1, 0);
1009                         HIViewChangeFeatures (ClientWindow, 1<<1, 0);
1010
1011                         HIViewNewTrackingArea (WholeWindow, IntPtr.Zero, (UInt64)WholeWindow, ref WholeWindowTracking);
1012                         HIViewNewTrackingArea (ClientWindow, IntPtr.Zero, (UInt64)ClientWindow, ref ClientWindowTracking);
1013                         Carbon.HIRect WholeRect;
1014                         if (WindowHandle != IntPtr.Zero) {
1015                                 WholeRect = new Carbon.HIRect (0, 0, QWindowSize.Width, QWindowSize.Height);
1016                         } else {
1017                                 WholeRect = new Carbon.HIRect (X, Y, QWindowSize.Width, QWindowSize.Height);
1018                         }
1019                         Carbon.HIRect ClientRect = new Carbon.HIRect (QClientRect.X, QClientRect.Y, QClientRect.Width, QClientRect.Height);
1020                         HIViewSetFrame (WholeWindow, ref WholeRect);
1021                         HIViewSetFrame (ClientWindow, ref ClientRect);
1022
1023                         HIViewAddSubview (ParentHandle, WholeWindow);
1024                         HIViewAddSubview (WholeWindow, ClientWindow);
1025
1026                         hwnd.WholeWindow = WholeWindow;
1027                         hwnd.ClientWindow = ClientWindow;
1028
1029                         if (WindowHandle != IntPtr.Zero) {
1030                                 WindowMapping [hwnd.Handle] = WindowHandle;
1031                                 HandleMapping [WindowHandle] = hwnd.Handle;
1032                                 if (hwnd.border_style == FormBorderStyle.FixedToolWindow || hwnd.border_style == FormBorderStyle.SizableToolWindow) {
1033                                         UtilityWindows.Add (WindowHandle);
1034                                 }
1035                         }
1036
1037                         // Allow dnd on controls
1038                         Dnd.SetAllowDrop (hwnd, true);
1039
1040                         Text (hwnd.Handle, cp.Caption);
1041                         
1042                         SendMessage (hwnd.Handle, Msg.WM_CREATE, (IntPtr)1, IntPtr.Zero /* XXX unused */);
1043                         SendParentNotify (hwnd.Handle, Msg.WM_CREATE, int.MaxValue, int.MaxValue);
1044
1045                         if (StyleSet (cp.Style, WindowStyles.WS_VISIBLE)) {
1046                                 if (WindowHandle != IntPtr.Zero) {
1047                                         if (Control.FromHandle(hwnd.Handle) is Form) {
1048                                                 Form f = Control.FromHandle(hwnd.Handle) as Form;
1049                                                 if (f.WindowState == FormWindowState.Normal) {
1050                                                         SendMessage(hwnd.Handle, Msg.WM_SHOWWINDOW, (IntPtr)1, IntPtr.Zero);
1051                                                 }
1052                                         }
1053                                         ShowWindow (WindowHandle);
1054                                         WaitForHwndMessage (hwnd, Msg.WM_SHOWWINDOW);
1055                                 }
1056                                 HIViewSetVisible (WholeWindow, true);
1057                                 HIViewSetVisible (ClientWindow, true);
1058                                 hwnd.visible = true;
1059                                 if (!(Control.FromHandle(hwnd.Handle) is Form)) {
1060                                         SendMessage(hwnd.Handle, Msg.WM_SHOWWINDOW, (IntPtr)1, IntPtr.Zero);
1061                                 }
1062                         }
1063
1064                         if (StyleSet (cp.Style, WindowStyles.WS_MINIMIZE)) {
1065                                 SetWindowState(hwnd.Handle, FormWindowState.Minimized);
1066                         } else if (StyleSet (cp.Style, WindowStyles.WS_MAXIMIZE)) {
1067                                 SetWindowState(hwnd.Handle, FormWindowState.Maximized);
1068                         }
1069
1070                         return hwnd.Handle;
1071                 }
1072
1073                 internal override IntPtr CreateWindow(IntPtr Parent, int X, int Y, int Width, int Height) {
1074                         CreateParams create_params = new CreateParams();
1075
1076                         create_params.Caption = "";
1077                         create_params.X = X;
1078                         create_params.Y = Y;
1079                         create_params.Width = Width;
1080                         create_params.Height = Height;
1081
1082                         create_params.ClassName=XplatUI.DefaultClassName;
1083                         create_params.ClassStyle = 0;
1084                         create_params.ExStyle=0;
1085                         create_params.Parent=IntPtr.Zero;
1086                         create_params.Param=0;
1087
1088                         return CreateWindow(create_params);
1089                 }
1090
1091                 internal override Bitmap DefineStdCursorBitmap (StdCursor id) {
1092                         return Carbon.Cursor.DefineStdCursorBitmap (id);
1093                 }
1094
1095                 internal override IntPtr DefineCursor (Bitmap bitmap, Bitmap mask, Color cursor_pixel, Color mask_pixel, int xHotSpot, int yHotSpot) {
1096                         return Carbon.Cursor.DefineCursor (bitmap, mask, cursor_pixel, mask_pixel, xHotSpot, yHotSpot);
1097                 }
1098                 
1099                 internal override IntPtr DefineStdCursor (StdCursor id) {
1100                         return Carbon.Cursor.DefineStdCursor (id);
1101                 }
1102                 
1103                 internal override IntPtr DefWndProc(ref Message msg) {
1104                         Hwnd hwnd = Hwnd.ObjectFromHandle (msg.HWnd);
1105                         switch ((Msg)msg.Msg) {
1106                                 case Msg.WM_IME_COMPOSITION:
1107                                         string s = KeyboardHandler.ComposedString;
1108                                         foreach (char c in s)
1109                                                 SendMessage (msg.HWnd, Msg.WM_IME_CHAR, (IntPtr) c, msg.LParam);
1110                                         break;
1111                                 case Msg.WM_IME_CHAR:
1112                                         // On Windows API it sends two WM_CHAR messages for each byte, but
1113                                         // I wonder if it is worthy to emulate it (also no idea how to 
1114                                         // reconstruct those bytes into chars).
1115                                         SendMessage (msg.HWnd, Msg.WM_CHAR, msg.WParam, msg.LParam);
1116                                         return IntPtr.Zero;
1117                                 case Msg.WM_QUIT: {
1118                                         if (WindowMapping [hwnd.Handle] != null)
1119
1120                                                 Exit ();
1121                                         break;
1122                                 }
1123                                 case Msg.WM_PAINT: {
1124                                         hwnd.expose_pending = false;
1125                                         break;
1126                                 }
1127                                 case Msg.WM_NCPAINT: {
1128                                         hwnd.nc_expose_pending = false;
1129                                         break;
1130                                 }  
1131                                 case Msg.WM_NCCALCSIZE: {
1132                                         if (msg.WParam == (IntPtr)1) {
1133                                                 XplatUIWin32.NCCALCSIZE_PARAMS ncp;
1134                                                 ncp = (XplatUIWin32.NCCALCSIZE_PARAMS)Marshal.PtrToStructure (msg.LParam, typeof (XplatUIWin32.NCCALCSIZE_PARAMS));
1135
1136                                                 // Add all the stuff X is supposed to draw.
1137                                                 Control ctrl = Control.FromHandle (hwnd.Handle);
1138                                                 if (ctrl != null) {
1139                                                         Hwnd.Borders rect = Hwnd.GetBorders (ctrl.GetCreateParams (), null);
1140
1141                                                         ncp.rgrc1.top += rect.top;
1142                                                         ncp.rgrc1.bottom -= rect.bottom;
1143                                                         ncp.rgrc1.left += rect.left;
1144                                                         ncp.rgrc1.right -= rect.right;
1145
1146                                                         Marshal.StructureToPtr (ncp, msg.LParam, true);
1147                                                 }
1148                                         }
1149                                         break;
1150                                 }
1151                                 case Msg.WM_SETCURSOR: {
1152                                         // Pass to parent window first
1153                                         while ((hwnd.parent != null) && (msg.Result == IntPtr.Zero)) {
1154                                                 hwnd = hwnd.parent;
1155                                                 msg.Result = NativeWindow.WndProc(hwnd.Handle, Msg.WM_SETCURSOR, msg.HWnd, msg.LParam);
1156                                         }
1157
1158                                         if (msg.Result == IntPtr.Zero) {
1159                                                 IntPtr handle;
1160
1161                                                 switch((HitTest)(msg.LParam.ToInt32() & 0xffff)) {
1162                                                         case HitTest.HTBOTTOM:          handle = Cursors.SizeNS.handle; break;
1163                                                         case HitTest.HTBORDER:          handle = Cursors.SizeNS.handle; break;
1164                                                         case HitTest.HTBOTTOMLEFT:      handle = Cursors.SizeNESW.handle; break;
1165                                                         case HitTest.HTBOTTOMRIGHT:     handle = Cursors.SizeNWSE.handle; break;
1166                                                         case HitTest.HTERROR:           if ((msg.LParam.ToInt32() >> 16) == (int)Msg.WM_LBUTTONDOWN) {
1167                                                                                                 //FIXME: AudibleAlert();
1168                                                                                         }
1169                                                                                         handle = Cursors.Default.handle;
1170                                                                                         break;
1171
1172                                                         case HitTest.HTHELP:            handle = Cursors.Help.handle; break;
1173                                                         case HitTest.HTLEFT:            handle = Cursors.SizeWE.handle; break;
1174                                                         case HitTest.HTRIGHT:           handle = Cursors.SizeWE.handle; break;
1175                                                         case HitTest.HTTOP:             handle = Cursors.SizeNS.handle; break;
1176                                                         case HitTest.HTTOPLEFT:         handle = Cursors.SizeNWSE.handle; break;
1177                                                         case HitTest.HTTOPRIGHT:        handle = Cursors.SizeNESW.handle; break;
1178
1179                                                         #if SameAsDefault
1180                                                         case HitTest.HTGROWBOX:
1181                                                         case HitTest.HTSIZE:
1182                                                         case HitTest.HTZOOM:
1183                                                         case HitTest.HTVSCROLL:
1184                                                         case HitTest.HTSYSMENU:
1185                                                         case HitTest.HTREDUCE:
1186                                                         case HitTest.HTNOWHERE:
1187                                                         case HitTest.HTMAXBUTTON:
1188                                                         case HitTest.HTMINBUTTON:
1189                                                         case HitTest.HTMENU:
1190                                                         case HitTest.HSCROLL:
1191                                                         case HitTest.HTBOTTOM:
1192                                                         case HitTest.HTCAPTION:
1193                                                         case HitTest.HTCLIENT:
1194                                                         case HitTest.HTCLOSE:
1195                                                         #endif
1196                                                         default: handle = Cursors.Default.handle; break;
1197                                                 }
1198                                                 SetCursor(msg.HWnd, handle);
1199                                         }
1200                                         return (IntPtr)1;
1201                                 }
1202                         }
1203                         return IntPtr.Zero;
1204                 }
1205
1206                 internal override void DestroyCaret (IntPtr hwnd) {
1207                         if (Caret.Hwnd == hwnd) {
1208                                 if (Caret.Visible == 1) {
1209                                         Caret.Timer.Stop ();
1210                                         HideCaret ();
1211                                 }
1212                                 Caret.Hwnd = IntPtr.Zero;
1213                                 Caret.Visible = 0;
1214                                 Caret.On = false;
1215                         }
1216                 }
1217                 
1218                 [MonoTODO]
1219                 internal override void DestroyCursor(IntPtr cursor) {
1220                         throw new NotImplementedException ();
1221                 }
1222         
1223                 internal override void DestroyWindow(IntPtr handle) {
1224                         Hwnd    hwnd;
1225
1226                         hwnd = Hwnd.ObjectFromHandle(handle);
1227
1228                         if (hwnd == null) {
1229                                 return;
1230                         }
1231
1232                         SendParentNotify (hwnd.Handle, Msg.WM_DESTROY, int.MaxValue, int.MaxValue);
1233                                 
1234                         CleanupCachedWindows (hwnd);
1235
1236                         ArrayList windows = new ArrayList ();
1237
1238                         AccumulateDestroyedHandles (Control.ControlNativeWindow.ControlFromHandle(hwnd.Handle), windows);
1239
1240
1241                         foreach (Hwnd h in windows) {
1242                                 SendMessage (h.Handle, Msg.WM_DESTROY, IntPtr.Zero, IntPtr.Zero);
1243                                 h.zombie = true;
1244                         }
1245
1246                         // TODO: This is crashing swf-messageboxes
1247                         /*
1248                         if (false && hwnd.whole_window != IntPtr.Zero)
1249                                 CFRelease (hwnd.whole_window);
1250                         if (false && hwnd.client_window != IntPtr.Zero)
1251                                 CFRelease (hwnd.client_window);
1252                         */
1253
1254                         if (WindowMapping [hwnd.Handle] != null) { 
1255                                 DisposeWindow ((IntPtr)(WindowMapping [hwnd.Handle]));
1256                                 WindowMapping.Remove (hwnd.Handle);
1257                         }
1258                 }
1259
1260                 internal override IntPtr DispatchMessage(ref MSG msg) {
1261                         return NativeWindow.WndProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
1262                 }
1263                 
1264                 internal override void DoEvents() {
1265                         MSG     msg = new MSG ();
1266
1267                         in_doevents = true;
1268                         while (PeekMessage (null, ref msg, IntPtr.Zero, 0, 0, (uint)PeekMessageFlags.PM_REMOVE)) {
1269                                 TranslateMessage (ref msg);
1270                                 DispatchMessage (ref msg);
1271                         }
1272                         in_doevents = false;
1273
1274                 }
1275
1276                 internal override void EnableWindow(IntPtr handle, bool Enable) {
1277                         //Like X11 we need not do anything here
1278                 }
1279
1280                 internal override void EndLoop(Thread thread) {
1281                 }
1282
1283                 internal void Exit () {
1284                         GetMessageResult = false;
1285                 }
1286                 
1287                 internal override IntPtr GetActive() {
1288                         return ActiveWindow;
1289                 }
1290
1291                 internal override Region GetClipRegion(IntPtr hwnd) {
1292                         return null;
1293                 }
1294
1295                 [MonoTODO]
1296                 internal override void GetCursorInfo(IntPtr cursor, out int width, out int height, out int hotspot_x, out int hotspot_y) {
1297                         width = 12;
1298                         height = 12;
1299                         hotspot_x = 0;
1300                         hotspot_y = 0;
1301                 }
1302                 
1303                 internal override void GetDisplaySize(out Size size) {
1304                         Carbon.HIRect bounds = CGDisplayBounds (CGMainDisplayID ());
1305                         size = new Size ((int)bounds.size.width, (int)bounds.size.height);
1306                 }
1307
1308                 internal override IntPtr GetParent(IntPtr handle) {
1309                         Hwnd    hwnd;
1310
1311                         hwnd = Hwnd.ObjectFromHandle(handle);
1312                         if (hwnd != null && hwnd.Parent != null) {
1313                                 return hwnd.Parent.Handle;
1314                         }
1315                         return IntPtr.Zero;
1316                 }
1317
1318                 internal override IntPtr GetPreviousWindow(IntPtr handle) {
1319                         return HIViewGetPreviousView(handle);
1320                 }
1321                 
1322                 internal override void GetCursorPos(IntPtr handle, out int x, out int y) {
1323                         Carbon.QDPoint pt = new Carbon.QDPoint ();
1324                         GetGlobalMouse (ref pt);
1325                         x = pt.x;
1326                         y = pt.y;
1327                 }
1328
1329                 internal override IntPtr GetFocus() {
1330                         return FocusWindow;
1331                 }
1332
1333                 
1334                 internal override bool GetFontMetrics(Graphics g, Font font, out int ascent, out int descent) {
1335                         FontFamily ff = font.FontFamily;
1336                         ascent = ff.GetCellAscent (font.Style);
1337                         descent = ff.GetCellDescent (font.Style);
1338                         return true;
1339                 }
1340                 
1341                 internal override Point GetMenuOrigin(IntPtr handle) {
1342                         Hwnd hwnd;
1343
1344                         hwnd = Hwnd.ObjectFromHandle(handle);
1345
1346                         if (hwnd != null) {
1347                                 return hwnd.MenuOrigin;
1348                         }
1349                         return Point.Empty;
1350                 }
1351
1352                 internal override bool GetMessage(object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax) {
1353                         IntPtr evtRef = IntPtr.Zero;
1354                         IntPtr target = GetEventDispatcherTarget();
1355                         CheckTimers (DateTime.UtcNow);
1356                         ReceiveNextEvent (0, IntPtr.Zero, 0, true, ref evtRef);
1357                         if (evtRef != IntPtr.Zero && target != IntPtr.Zero) {
1358                                 SendEventToEventTarget (evtRef, target);
1359                                 ReleaseEvent (evtRef);
1360                         }
1361                         
1362                         lock (queuelock) {
1363                                 loop:
1364
1365                                 if (MessageQueue.Count <= 0) {
1366                                         if (Idle != null) 
1367                                                 Idle (this, EventArgs.Empty);
1368                                         else if (TimerList.Count == 0) {
1369                                                 ReceiveNextEvent (0, IntPtr.Zero, 0.15, true, ref evtRef);
1370                                                 if (evtRef != IntPtr.Zero && target != IntPtr.Zero) {
1371                                                         SendEventToEventTarget (evtRef, target);
1372                                                         ReleaseEvent (evtRef);
1373                                                 }
1374                                         } else {
1375                                                 ReceiveNextEvent (0, IntPtr.Zero, NextTimeout (), true, ref evtRef);
1376                                                 if (evtRef != IntPtr.Zero && target != IntPtr.Zero) {
1377                                                         SendEventToEventTarget (evtRef, target);
1378                                                         ReleaseEvent (evtRef);
1379                                                 }
1380                                         }
1381                                         msg.hwnd = IntPtr.Zero;
1382                                         msg.message = Msg.WM_ENTERIDLE;
1383                                         return GetMessageResult;
1384                                 }
1385                                 object queueobj = MessageQueue.Dequeue ();
1386                                 if (queueobj is GCHandle) {
1387                                         XplatUIDriverSupport.ExecuteClientMessage((GCHandle)queueobj);
1388                                         goto loop;
1389                                 } else {
1390                                         msg = (MSG)queueobj;
1391                                 }
1392                         }
1393                         return GetMessageResult;
1394                 }
1395                 
1396                 [MonoTODO]
1397                 internal override bool GetText(IntPtr handle, out string text) {
1398                         throw new NotImplementedException ();
1399                 }
1400                 
1401                 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) {
1402                         Hwnd            hwnd;
1403
1404                         hwnd = Hwnd.ObjectFromHandle(handle);
1405
1406                         if (hwnd != null) {
1407                                 x = hwnd.x;
1408                                 y = hwnd.y;
1409                                 width = hwnd.width;
1410                                 height = hwnd.height;
1411
1412                                 PerformNCCalc(hwnd);
1413
1414                                 client_width = hwnd.ClientRect.Width;
1415                                 client_height = hwnd.ClientRect.Height;
1416
1417                                 return;
1418                         }
1419
1420                         // Should we throw an exception or fail silently?
1421                         // throw new ArgumentException("Called with an invalid window handle", "handle");
1422
1423                         x = 0;
1424                         y = 0;
1425                         width = 0;
1426                         height = 0;
1427                         client_width = 0;
1428                         client_height = 0;
1429                 }
1430                 
1431                 internal override FormWindowState GetWindowState(IntPtr hwnd) {
1432                         IntPtr window = HIViewGetWindow (hwnd);
1433
1434                         if (IsWindowCollapsed (window))
1435                                 return FormWindowState.Minimized;
1436                         if (IsWindowInStandardState (window, IntPtr.Zero, IntPtr.Zero))
1437                                 return FormWindowState.Maximized;
1438
1439                         return FormWindowState.Normal;
1440                 }
1441                 
1442                 internal override void GrabInfo(out IntPtr handle, out bool GrabConfined, out Rectangle GrabArea) {
1443                         handle = Grab.Hwnd;
1444                         GrabConfined = Grab.Confined;
1445                         GrabArea = Grab.Area;
1446                 }
1447                 
1448                 internal override void GrabWindow(IntPtr handle, IntPtr confine_to_handle) {
1449                         Grab.Hwnd = handle;
1450                         Grab.Confined = confine_to_handle != IntPtr.Zero;
1451                         /* FIXME: Set the Grab.Area */
1452                 }
1453                 
1454                 internal override void UngrabWindow(IntPtr hwnd) {
1455                         bool was_grabbed = Grab.Hwnd != IntPtr.Zero;
1456
1457                         Grab.Hwnd = IntPtr.Zero;
1458                         Grab.Confined = false;
1459
1460                         if (was_grabbed) {
1461                                 // lparam should be the handle to the window gaining the mouse capture,
1462                                 // but we dont have that information like X11.
1463                                 // Also only generate WM_CAPTURECHANGED if the window actually was grabbed.
1464                                 SendMessage (hwnd, Msg.WM_CAPTURECHANGED, IntPtr.Zero, IntPtr.Zero);
1465                         }
1466                 }
1467                 
1468                 internal override void HandleException(Exception e) {
1469                         StackTrace st = new StackTrace(e);
1470                         Console.WriteLine("Exception '{0}'", e.Message+st.ToString());
1471                         Console.WriteLine("{0}{1}", e.Message, st.ToString());
1472                 }
1473                 
1474                 internal override void Invalidate (IntPtr handle, Rectangle rc, bool clear) {
1475                         Hwnd hwnd;
1476
1477                         hwnd = Hwnd.ObjectFromHandle(handle);
1478
1479                         if (clear) {
1480                                 AddExpose (hwnd, true, hwnd.X, hwnd.Y, hwnd.Width, hwnd.Height);
1481                         } else {
1482                                 AddExpose (hwnd, true, rc.X, rc.Y, rc.Width, rc.Height);
1483                         } 
1484                 }
1485
1486                 internal override void InvalidateNC (IntPtr handle)
1487                 {
1488                         Hwnd hwnd;
1489
1490                         hwnd = Hwnd.ObjectFromHandle(handle);
1491
1492                         AddExpose (hwnd, false, 0, 0, hwnd.Width, hwnd.Height); 
1493                 }
1494                 
1495                 internal override bool IsEnabled(IntPtr handle) {
1496                         return Hwnd.ObjectFromHandle(handle).Enabled;
1497                 }
1498                 
1499                 internal override bool IsVisible(IntPtr handle) {
1500                         return Hwnd.ObjectFromHandle(handle).visible;
1501                 }
1502                 
1503                 internal override void KillTimer(Timer timer) {
1504                         lock (TimerList) {
1505                                 TimerList.Remove(timer);
1506                         }
1507                 }
1508
1509
1510                 internal override void OverrideCursor(IntPtr cursor) {
1511                 }
1512
1513                 internal override PaintEventArgs PaintEventStart(ref Message msg, IntPtr handle, bool client) {
1514                         PaintEventArgs  paint_event;
1515                         Hwnd            hwnd;
1516                         Hwnd            paint_hwnd; 
1517                         
1518                         hwnd = Hwnd.ObjectFromHandle(msg.HWnd);
1519                         if (msg.HWnd == handle) {
1520                                 paint_hwnd = hwnd;
1521                         } else {
1522                                 paint_hwnd = Hwnd.ObjectFromHandle (handle);
1523                         }
1524                         
1525                         if (Caret.Visible == 1) {
1526                                 Caret.Paused = true;
1527                                 HideCaret();
1528                         }
1529
1530                         Graphics dc;
1531
1532                         if (client) {
1533                                 dc = Graphics.FromHwnd (paint_hwnd.client_window);
1534
1535                                 Region clip_region = new Region ();
1536                                 clip_region.MakeEmpty();
1537
1538                                 foreach (Rectangle r in hwnd.ClipRectangles) {
1539                                         clip_region.Union (r);
1540                                 }
1541
1542                                 if (hwnd.UserClip != null) {
1543                                         clip_region.Intersect(hwnd.UserClip);
1544                                 }
1545
1546                                 // FIXME: Clip region is hosed
1547                                 dc.Clip = clip_region;
1548                                 paint_event = new PaintEventArgs(dc, hwnd.Invalid);
1549                                 hwnd.expose_pending = false;
1550                                 hwnd.ClearInvalidArea();
1551
1552                                 hwnd.drawing_stack.Push (paint_event);
1553                                 hwnd.drawing_stack.Push (dc);
1554                         } else {
1555                                 dc = Graphics.FromHwnd (paint_hwnd.whole_window);
1556
1557                                 if (!hwnd.nc_invalid.IsEmpty) {
1558                                         // FIXME: Clip region is hosed
1559                                         dc.SetClip (hwnd.nc_invalid);
1560                                         paint_event = new PaintEventArgs(dc, hwnd.nc_invalid);
1561                                 } else {
1562                                         paint_event = new PaintEventArgs(dc, new Rectangle(0, 0, hwnd.width, hwnd.height));
1563                                 }
1564                                 hwnd.nc_expose_pending = false;
1565                                 hwnd.ClearNcInvalidArea ();
1566
1567                                 hwnd.drawing_stack.Push (paint_event);
1568                                 hwnd.drawing_stack.Push (dc);
1569                         }
1570
1571                         return paint_event;
1572                 }
1573                 
1574                 internal override void PaintEventEnd(ref Message msg, IntPtr handle, bool client) {
1575                         Hwnd    hwnd;
1576
1577                         hwnd = Hwnd.ObjectFromHandle(handle);
1578
1579                         // FIXME: Pop is causing invalid stack ops sometimes; race condition?
1580                         try {
1581                                 Graphics dc = (Graphics)hwnd.drawing_stack.Pop();
1582                                 dc.Flush ();
1583                                 dc.Dispose ();
1584                         
1585                                 PaintEventArgs pe = (PaintEventArgs)hwnd.drawing_stack.Pop();
1586                                 pe.SetGraphics (null);
1587                                 pe.Dispose ();  
1588                         } catch {}
1589
1590                         if (Caret.Visible == 1) {
1591                                 ShowCaret();
1592                                 Caret.Paused = false;
1593                         }
1594                 }
1595                 
1596                 internal override bool PeekMessage(Object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, uint flags) {
1597                         IntPtr evtRef = IntPtr.Zero;
1598                         IntPtr target = GetEventDispatcherTarget();
1599                         CheckTimers (DateTime.UtcNow);
1600                         ReceiveNextEvent (0, IntPtr.Zero, 0, true, ref evtRef);
1601                         if (evtRef != IntPtr.Zero && target != IntPtr.Zero) {
1602                                 SendEventToEventTarget (evtRef, target);
1603                                 ReleaseEvent (evtRef);
1604                         }
1605                         
1606                         lock (queuelock) {
1607                                 if (MessageQueue.Count <= 0) {
1608                                         return false;
1609                                 } else {
1610                                         object queueobj;
1611                                         if (flags == (uint)PeekMessageFlags.PM_REMOVE)
1612                                                 queueobj = MessageQueue.Dequeue ();
1613                                         else
1614                                                 queueobj = MessageQueue.Peek ();
1615
1616                                         if (queueobj is GCHandle) {
1617                                                 XplatUIDriverSupport.ExecuteClientMessage((GCHandle)queueobj);
1618                                                 return false;
1619                                         }
1620                                         msg = (MSG)queueobj;
1621                                         return true;
1622                                 }
1623                         }
1624                 }
1625
1626                 internal override bool PostMessage (IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam) {
1627                         MSG msg = new MSG();
1628                         msg.hwnd = hwnd;
1629                         msg.message = message;
1630                         msg.wParam = wParam;
1631                         msg.lParam = lParam;
1632                         EnqueueMessage (msg);
1633                         return true;
1634                 }
1635
1636                 internal override void PostQuitMessage(int exitCode) {
1637                         PostMessage (FosterParent, Msg.WM_QUIT, IntPtr.Zero, IntPtr.Zero);
1638                 }
1639
1640                 internal override void RequestAdditionalWM_NCMessages(IntPtr hwnd, bool hover, bool leave) {
1641                 }
1642
1643                 internal override void RequestNCRecalc(IntPtr handle) {
1644                         Hwnd hwnd;
1645
1646                         hwnd = Hwnd.ObjectFromHandle(handle);
1647
1648                         if (hwnd == null) {
1649                                 return;
1650                         }
1651
1652                         PerformNCCalc(hwnd);
1653                         SendMessage(handle, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
1654                         InvalidateNC(handle);
1655                 }
1656
1657                 [MonoTODO]              
1658                 internal override void ResetMouseHover(IntPtr handle) {
1659                         throw new NotImplementedException();
1660                 }
1661
1662                 internal override void ScreenToClient(IntPtr handle, ref int x, ref int y) {
1663                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1664
1665                         Point point = ConvertScreenPointToClient (hwnd.ClientWindow, new Point (x, y));
1666
1667                         x = point.X;
1668                         y = point.Y;
1669                 }
1670
1671                 internal override void ScreenToMenu(IntPtr handle, ref int x, ref int y) {
1672                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1673
1674                         Point point = ConvertScreenPointToClient (hwnd.WholeWindow, new Point (x, y));
1675
1676                         x = point.X;
1677                         y = point.Y;
1678                 }
1679
1680                 internal override void ScrollWindow(IntPtr handle, Rectangle area, int XAmount, int YAmount, bool clear) {
1681                         /*
1682                          * This used to use a HIViewScrollRect but this causes issues with the fact that we dont coalesce
1683                          * updates properly with our short-circuiting of the window manager.  For now we'll do a less
1684                          * efficient invalidation of the entire handle which appears to fix the problem
1685                          * see bug #381084
1686                          */
1687                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1688                         Invalidate (handle, new Rectangle (0, 0, hwnd.Width, hwnd.Height), false);
1689                 }
1690                 
1691                 
1692                 internal override void ScrollWindow(IntPtr handle, int XAmount, int YAmount, bool clear) {
1693                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1694                         Invalidate (handle, new Rectangle (0, 0, hwnd.Width, hwnd.Height), false);
1695                 }
1696                 
1697                 [MonoTODO]
1698                 internal override void SendAsyncMethod (AsyncMethodData method) {
1699                         // Fake async
1700                         lock (queuelock) {
1701                                 MessageQueue.Enqueue (GCHandle.Alloc (method));
1702                         }
1703                 }
1704
1705                 [MonoTODO]
1706                 internal override IntPtr SendMessage (IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam) {
1707                         return NativeWindow.WndProc(hwnd, message, wParam, lParam);
1708                 }
1709                 
1710                 internal override int SendInput(IntPtr hwnd, Queue keys) {
1711                         return 0;
1712                 }
1713
1714
1715                 internal override void SetCaretPos (IntPtr hwnd, int x, int y) {
1716                         if (hwnd != IntPtr.Zero && hwnd == Caret.Hwnd) {
1717                                 Caret.X = x;
1718                                 Caret.Y = y;
1719                                 ClientToScreen (hwnd, ref x, ref y);
1720                                 SizeWindow (new Rectangle (x, y, Caret.Width, Caret.Height), CaretWindow);
1721                                 Caret.Timer.Stop ();
1722                                 HideCaret ();
1723                                 if (Caret.Visible == 1) {
1724                                         ShowCaret ();
1725                                         Caret.Timer.Start ();
1726                                 }
1727                         }
1728                 }
1729
1730                 internal override void SetClipRegion(IntPtr hwnd, Region region) {
1731                         throw new NotImplementedException();
1732                 }
1733                 
1734                 internal override void SetCursor(IntPtr window, IntPtr cursor) {
1735                         Hwnd hwnd = Hwnd.ObjectFromHandle (window);
1736
1737                         hwnd.Cursor = cursor;
1738                 }
1739                 
1740                 internal override void SetCursorPos(IntPtr handle, int x, int y) {
1741                         CGDisplayMoveCursorToPoint (CGMainDisplayID (), new Carbon.CGPoint (x, y));
1742                 }
1743                 
1744                 internal override void SetFocus(IntPtr handle) {
1745                         if (FocusWindow != IntPtr.Zero) {
1746                                 PostMessage(FocusWindow, Msg.WM_KILLFOCUS, handle, IntPtr.Zero);
1747                         }
1748                         PostMessage(handle, Msg.WM_SETFOCUS, FocusWindow, IntPtr.Zero);
1749                         FocusWindow = handle;
1750                 }
1751
1752                 internal override void SetIcon(IntPtr handle, Icon icon) {
1753                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1754
1755                         // FIXME: we need to map the icon for active window switches
1756                         if (WindowMapping [hwnd.Handle] != null) {
1757                                 if (icon == null) { 
1758                                         RestoreApplicationDockTileImage ();
1759                                 } else {
1760                                         Bitmap          bitmap;
1761                                         int             size;
1762                                         IntPtr[]        data;
1763                                         int             index;
1764         
1765                                         bitmap = new Bitmap (128, 128);
1766                                         using (Graphics g = Graphics.FromImage (bitmap)) {
1767                                                 g.DrawImage (icon.ToBitmap (), 0, 0, 128, 128);
1768                                         }
1769                                         index = 0;
1770                                         size = bitmap.Width * bitmap.Height;
1771                                         data = new IntPtr[size];
1772         
1773                                         for (int y = 0; y < bitmap.Height; y++) {
1774                                                 for (int x = 0; x < bitmap.Width; x++) {
1775                                                         int pixel = bitmap.GetPixel (x, y).ToArgb ();
1776                                                         if (BitConverter.IsLittleEndian) {
1777                                                                 byte a = (byte) ((pixel >> 24) & 0xFF);
1778                                                                 byte r = (byte) ((pixel >> 16) & 0xFF);
1779                                                                 byte g = (byte) ((pixel >> 8) & 0xFF);
1780                                                                 byte b = (byte) (pixel & 0xFF);
1781                                                                 data[index++] = (IntPtr)(a + (r << 8) + (g << 16) + (b << 24));
1782                                                         } else {
1783                                                                 data[index++] = (IntPtr)pixel;
1784                                                         }
1785                                                 }
1786                                         }
1787
1788                                         IntPtr provider = CGDataProviderCreateWithData (IntPtr.Zero, data, size*4, IntPtr.Zero);
1789                                         IntPtr image = CGImageCreate (128, 128, 8, 32, 4*128, CGColorSpaceCreateDeviceRGB (), 4, provider, IntPtr.Zero, 0, 0);
1790                                         SetApplicationDockTileImage (image);
1791                                 }
1792                         }
1793                 }
1794
1795                 
1796                 internal override void SetModal(IntPtr handle, bool Modal) {
1797                         IntPtr hWnd = HIViewGetWindow (Hwnd.ObjectFromHandle (handle).WholeWindow);
1798                         if (Modal)
1799                                 BeginAppModalStateForWindow (hWnd);
1800                         else
1801                                 EndAppModalStateForWindow (hWnd);
1802                         return;
1803                 }
1804
1805                 internal override IntPtr SetParent(IntPtr handle, IntPtr parent) {
1806                         IntPtr ParentHandle = IntPtr.Zero;
1807                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1808                         
1809                         hwnd.Parent = Hwnd.ObjectFromHandle (parent);
1810                         if (HIViewGetSuperview (hwnd.whole_window) != IntPtr.Zero) {
1811                                 HIViewRemoveFromSuperview (hwnd.whole_window);
1812                         }
1813                         if (hwnd.parent == null)
1814                                 HIViewFindByID (HIViewGetRoot (FosterParent), new Carbon.HIViewID (Carbon.EventHandler.kEventClassWindow, 1), ref ParentHandle);
1815                         HIViewAddSubview (hwnd.parent == null ? ParentHandle : hwnd.Parent.client_window, hwnd.whole_window);
1816                         HIViewPlaceInSuperviewAt (hwnd.whole_window, hwnd.X, hwnd.Y);
1817                         HIViewAddSubview (hwnd.whole_window, hwnd.client_window);
1818                         HIViewPlaceInSuperviewAt (hwnd.client_window, hwnd.ClientRect.X, hwnd.ClientRect.Y);
1819                         
1820                         return IntPtr.Zero;
1821                 }
1822                 
1823                 internal override void SetTimer (Timer timer) {
1824                         lock (TimerList) {
1825                                 TimerList.Add (timer);
1826                         }
1827                 }
1828                 
1829                 internal override bool SetTopmost(IntPtr hWnd, bool Enabled) {
1830                         HIViewSetZOrder (hWnd, 1, IntPtr.Zero);
1831                         return true;
1832                 }
1833                 
1834                 internal override bool SetOwner(IntPtr hWnd, IntPtr hWndOwner) {
1835                         // TODO: Set window owner. 
1836                         return true;
1837                 }
1838                 
1839                 internal override bool SetVisible(IntPtr handle, bool visible, bool activate) {
1840                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1841                         object window = WindowMapping [hwnd.Handle];
1842                         if (window != null)
1843                                 if (visible)
1844                                         ShowWindow ((IntPtr)window);
1845                                 else
1846                                         HideWindow ((IntPtr)window);
1847                         
1848                         if (visible)
1849                                 SendMessage(handle, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
1850                                         
1851                         HIViewSetVisible (hwnd.whole_window, visible);
1852                         HIViewSetVisible (hwnd.client_window, visible);
1853
1854                         hwnd.visible = visible;
1855                         hwnd.Mapped = true;
1856                         return true;
1857                 }
1858                 
1859                 internal override void SetAllowDrop (IntPtr handle, bool value) {
1860                         // Like X11 we allow drop on al windows and filter in our handler
1861                 }
1862
1863                 internal override DragDropEffects StartDrag (IntPtr handle, object data, DragDropEffects allowed_effects) {
1864                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1865                         
1866                         if (hwnd == null)
1867                                 throw new ArgumentException ("Attempt to begin drag from invalid window handle (" + handle.ToInt32 () + ").");
1868
1869                         return Dnd.StartDrag (hwnd.client_window, data, allowed_effects);
1870                 }
1871
1872                 internal override void SetBorderStyle(IntPtr handle, FormBorderStyle border_style) {
1873                         Form form = Control.FromHandle (handle) as Form;
1874                         if (form != null && form.window_manager == null && (border_style == FormBorderStyle.FixedToolWindow ||
1875                                 border_style == FormBorderStyle.SizableToolWindow)) {
1876                                 form.window_manager = new ToolWindowManager (form);
1877                         }
1878
1879                         RequestNCRecalc(handle);
1880                 }
1881
1882                 internal override void SetMenu(IntPtr handle, Menu menu) {
1883                         Hwnd    hwnd;
1884
1885                         hwnd = Hwnd.ObjectFromHandle(handle);
1886                         hwnd.menu = menu;
1887
1888                         RequestNCRecalc(handle);
1889                 }
1890                 
1891                 internal override void SetWindowMinMax(IntPtr handle, Rectangle maximized, Size min, Size max) {
1892                 }
1893
1894                 internal override void SetWindowPos(IntPtr handle, int x, int y, int width, int height) {
1895                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1896
1897                         if (hwnd == null) {
1898                                 return;
1899                         }
1900
1901                         // Win32 automatically changes negative width/height to 0.
1902                         if (width < 0)
1903                                 width = 0;
1904                         if (height < 0)
1905                                 height = 0;
1906                                 
1907                         // X requires a sanity check for width & height; otherwise it dies
1908                         if (hwnd.zero_sized && width > 0 && height > 0) {
1909                                 if (hwnd.visible) {
1910                                         HIViewSetVisible(hwnd.WholeWindow, true);
1911                                 }
1912                                 hwnd.zero_sized = false;
1913                         }
1914
1915                         if ((width < 1) || (height < 1)) {
1916                                 hwnd.zero_sized = true;
1917                                 HIViewSetVisible(hwnd.WholeWindow, false);
1918                         }
1919
1920                         // Save a server roundtrip (and prevent a feedback loop)
1921                         if ((hwnd.x == x) && (hwnd.y == y) && (hwnd.width == width) && (hwnd.height == height)) {
1922                                 return;
1923                         }
1924
1925                         if (!hwnd.zero_sized) {
1926                                 hwnd.x = x;
1927                                 hwnd.y = y;
1928                                 hwnd.width = width;
1929                                 hwnd.height = height;
1930                                 SendMessage(hwnd.client_window, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
1931
1932                                 Control ctrl = Control.FromHandle (handle);
1933                                 CreateParams cp = ctrl.GetCreateParams ();
1934                                 Size TranslatedSize = TranslateWindowSizeToQuartzWindowSize (cp, new Size (width, height));
1935                                 Carbon.Rect rect = new Carbon.Rect ();
1936
1937                                 if (WindowMapping [hwnd.Handle] != null) {
1938                                         if (StyleSet (cp.Style, WindowStyles.WS_POPUP)) {
1939                                                 SetRect (ref rect, (short)x, (short)y, (short)(x+TranslatedSize.Width), (short)(y+TranslatedSize.Height));
1940                                         } else {
1941                                                 SetRect (ref rect, (short)x, (short)(y+MenuBarHeight), (short)(x+TranslatedSize.Width), (short)(y+MenuBarHeight+TranslatedSize.Height));
1942                                         }
1943                                         SetWindowBounds ((IntPtr) WindowMapping [hwnd.Handle], 33, ref rect);
1944                                         Carbon.HIRect frame_rect = new Carbon.HIRect (0, 0, TranslatedSize.Width, TranslatedSize.Height);
1945                                         HIViewSetFrame (hwnd.whole_window, ref frame_rect);
1946                                         SetCaretPos (Caret.Hwnd, Caret.X, Caret.Y);
1947                                 } else {
1948                                         Carbon.HIRect frame_rect = new Carbon.HIRect (x, y, TranslatedSize.Width, TranslatedSize.Height);
1949                                         HIViewSetFrame (hwnd.whole_window, ref frame_rect);
1950                                 }
1951                                 PerformNCCalc(hwnd);
1952                         }
1953
1954                         hwnd.x = x;
1955                         hwnd.y = y;
1956                         hwnd.width = width;
1957                         hwnd.height = height;
1958                 }
1959                 
1960                 internal override void SetWindowState(IntPtr handle, FormWindowState state) {
1961                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1962                         IntPtr window = HIViewGetWindow (handle);
1963
1964                         switch (state) {
1965                                 case FormWindowState.Minimized: {
1966                                         CollapseWindow (window, true);
1967                                         break;
1968                                 }
1969                                 case FormWindowState.Normal: {
1970                                         ZoomWindow (window, 7, false);
1971                                         break;
1972                                 }
1973                                 case FormWindowState.Maximized: {
1974                                         Form form = Control.FromHandle (hwnd.Handle) as Form;
1975                                         if (form != null && form.FormBorderStyle == FormBorderStyle.None) {
1976                                                 Carbon.Rect rect = new Carbon.Rect ();
1977                                                 Carbon.HIRect bounds = CGDisplayBounds (CGMainDisplayID ());
1978                                                 SetRect (ref rect, (short)0, (short)0, (short)bounds.size.width, (short)bounds.size.height);
1979                                                 SetWindowBounds ((IntPtr) WindowMapping [hwnd.Handle], 33, ref rect);
1980                                                 HIViewSetFrame (hwnd.whole_window, ref bounds);
1981                                         } else {
1982                                                 ZoomWindow (window, 8, false);
1983                                         }
1984                                         break;
1985                                 }
1986                         }
1987                 }
1988                 
1989                 internal override void SetWindowStyle(IntPtr handle, CreateParams cp) {
1990                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1991                         SetHwndStyles(hwnd, cp);
1992                         
1993                         if (WindowMapping [hwnd.Handle] != null) {
1994                                 Carbon.WindowAttributes attributes = Carbon.WindowAttributes.kWindowCompositingAttribute | Carbon.WindowAttributes.kWindowStandardHandlerAttribute;
1995                                 if ((cp.Style & ((int)WindowStyles.WS_MINIMIZEBOX)) != 0) { 
1996                                         attributes |= Carbon.WindowAttributes.kWindowCollapseBoxAttribute;
1997                                 }
1998                                 if ((cp.Style & ((int)WindowStyles.WS_MAXIMIZEBOX)) != 0) {
1999                                         attributes |= Carbon.WindowAttributes.kWindowResizableAttribute | Carbon.WindowAttributes.kWindowHorizontalZoomAttribute | Carbon.WindowAttributes.kWindowVerticalZoomAttribute;
2000                                 }
2001                                 if ((cp.Style & ((int)WindowStyles.WS_SYSMENU)) != 0) {
2002                                         attributes |= Carbon.WindowAttributes.kWindowCloseBoxAttribute;
2003                                 }
2004                                 if ((cp.ExStyle & ((int)WindowExStyles.WS_EX_TOOLWINDOW)) != 0) {
2005                                         attributes = Carbon.WindowAttributes.kWindowStandardHandlerAttribute | Carbon.WindowAttributes.kWindowCompositingAttribute;
2006                                 }
2007                                 attributes |= Carbon.WindowAttributes.kWindowLiveResizeAttribute;
2008
2009                                 Carbon.WindowAttributes outAttributes = Carbon.WindowAttributes.kWindowNoAttributes;
2010                                 GetWindowAttributes ((IntPtr)WindowMapping [hwnd.Handle], ref outAttributes);
2011                                 ChangeWindowAttributes ((IntPtr)WindowMapping [hwnd.Handle], attributes, outAttributes);
2012                         }
2013                 }
2014
2015                 internal override void SetWindowTransparency(IntPtr handle, double transparency, Color key) {
2016                 }
2017
2018                 internal override double GetWindowTransparency(IntPtr handle)
2019                 {
2020                         return 1.0;
2021                 }
2022
2023                 internal override TransparencySupport SupportsTransparency() {
2024                         return TransparencySupport.None;
2025                 }
2026                 
2027                 internal override bool SetZOrder(IntPtr handle, IntPtr after_handle, bool Top, bool Bottom) {
2028                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
2029                         
2030                         if (Top) {
2031                                 HIViewSetZOrder (hwnd.whole_window, 2, IntPtr.Zero);
2032                                 return true;
2033                         } else if (!Bottom) {
2034                                 Hwnd after_hwnd = Hwnd.ObjectFromHandle (after_handle);
2035                                 HIViewSetZOrder (hwnd.whole_window, 2, (after_handle == IntPtr.Zero ? IntPtr.Zero : after_hwnd.whole_window));
2036                         } else {
2037                                 HIViewSetZOrder (hwnd.whole_window, 1, IntPtr.Zero);
2038                                 return true;
2039                         }
2040                         return false;
2041                 }
2042
2043                 internal override void ShowCursor(bool show) {
2044                         if (show)
2045                                 CGDisplayShowCursor (CGMainDisplayID ());
2046                         else
2047                                 CGDisplayHideCursor (CGMainDisplayID ());
2048                 }
2049
2050                 internal override object StartLoop(Thread thread) {
2051                         return new object ();
2052                 }
2053                 
2054                 [MonoTODO]
2055                 internal override bool SystrayAdd(IntPtr hwnd, string tip, Icon icon, out ToolTip tt) {
2056                         throw new NotImplementedException();
2057                 }
2058
2059                 [MonoTODO]
2060                 internal override bool SystrayChange(IntPtr hwnd, string tip, Icon icon, ref ToolTip tt) {
2061                         throw new NotImplementedException();
2062                 }
2063
2064                 [MonoTODO]
2065                 internal override void SystrayRemove(IntPtr hwnd, ref ToolTip tt) {
2066                         throw new NotImplementedException();
2067                 }
2068
2069 #if NET_2_0
2070                 [MonoTODO]
2071                 internal override void SystrayBalloon(IntPtr hwnd, int timeout, string title, string text, ToolTipIcon icon)
2072                 {
2073                         throw new NotImplementedException ();
2074                 }
2075 #endif
2076                 
2077                 internal override bool Text(IntPtr handle, string text) {
2078                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
2079                         if (WindowMapping [hwnd.Handle] != null) {
2080                                 SetWindowTitleWithCFString ((IntPtr)(WindowMapping [hwnd.Handle]), __CFStringMakeConstantString (text));
2081                         }
2082                         SetControlTitleWithCFString (hwnd.whole_window, __CFStringMakeConstantString (text));
2083                         SetControlTitleWithCFString (hwnd.client_window, __CFStringMakeConstantString (text));
2084                         return true;
2085                 }
2086                 
2087                 internal override void UpdateWindow(IntPtr handle) {
2088                         Hwnd    hwnd;
2089
2090                         hwnd = Hwnd.ObjectFromHandle(handle);
2091
2092                         if (!hwnd.visible || !HIViewIsVisible (handle)) {
2093                                 return;
2094                         }
2095
2096                         SendMessage(handle, Msg.WM_PAINT, IntPtr.Zero, IntPtr.Zero);
2097                 }
2098                 
2099                 internal override bool TranslateMessage(ref MSG msg) {
2100                         return Carbon.EventHandler.TranslateMessage (ref msg);
2101                 }
2102                 
2103                 #region Reversible regions
2104                 /* 
2105                  * Quartz has no concept of XOR drawing due to its compositing nature
2106                  * We fake this by mapping a overlay window on the first draw and mapping it on the second.
2107                  * This has some issues with it because its POSSIBLE for ControlPaint.DrawReversible* to actually
2108                  * reverse two regions at once.  We dont do this in MWF, but this behaviour woudn't work.
2109                  * We could in theory cache the Rectangle/Color combination to handle this behaviour.
2110                  *
2111                  * PROBLEMS: This has some flicker / banding
2112                  */
2113                 internal void SizeWindow (Rectangle rect, IntPtr window) {
2114                         Carbon.Rect qrect = new Carbon.Rect ();
2115
2116                         SetRect (ref qrect, (short)rect.X, (short)rect.Y, (short)(rect.X+rect.Width), (short)(rect.Y+rect.Height));
2117
2118                         SetWindowBounds (window, 33, ref qrect);
2119                 }
2120
2121                 internal override void DrawReversibleLine(Point start, Point end, Color backColor) {
2122 //                      throw new NotImplementedException();
2123                 }
2124
2125                 internal override void FillReversibleRectangle (Rectangle rectangle, Color backColor) {
2126 //                      throw new NotImplementedException();
2127                 }
2128
2129                 internal override void DrawReversibleFrame (Rectangle rectangle, Color backColor, FrameStyle style) {
2130 //                      throw new NotImplementedException();
2131                 }
2132
2133                 internal override void DrawReversibleRectangle(IntPtr handle, Rectangle rect, int line_width) {
2134                         Rectangle size_rect = rect;
2135                         int new_x = 0;
2136                         int new_y = 0;
2137
2138                         if (ReverseWindowMapped) {
2139                                 HideWindow (ReverseWindow);
2140                                 ReverseWindowMapped = false;
2141                         } else {
2142                                 ClientToScreen(handle, ref new_x, ref new_y);
2143
2144                                 size_rect.X += new_x;
2145                                 size_rect.Y += new_y;
2146
2147                                 SizeWindow (size_rect, ReverseWindow);
2148                                 ShowWindow (ReverseWindow);
2149
2150                                 rect.X = 0;
2151                                 rect.Y = 0;
2152                                 rect.Width -= 1;
2153                                 rect.Height -= 1;
2154
2155                                 Graphics g = Graphics.FromHwnd (HIViewGetRoot (ReverseWindow));
2156
2157                                 for (int i = 0; i < line_width; i++) {
2158                                         g.DrawRectangle (ThemeEngine.Current.ResPool.GetPen (Color.Black), rect);
2159                                         rect.X += 1;
2160                                         rect.Y += 1;
2161                                         rect.Width -= 1;
2162                                         rect.Height -= 1;
2163                                 }
2164         
2165                                 g.Flush ();
2166                                 g.Dispose ();
2167                                 
2168                                 ReverseWindowMapped = true;
2169                         }
2170                 }
2171                 #endregion
2172
2173                 internal override SizeF GetAutoScaleSize(Font font) {
2174                         Graphics        g;
2175                         float           width;
2176                         string          magic_string = "The quick brown fox jumped over the lazy dog.";
2177                         double          magic_number = 44.549996948242189;
2178
2179                         g = Graphics.FromImage (new Bitmap (1, 1));
2180
2181                         width = (float) (g.MeasureString (magic_string, font).Width / magic_number);
2182                         return new SizeF(width, font.Height);
2183                 }
2184
2185                 internal override Point MousePosition {
2186                         get {
2187                                 return mouse_position;
2188                         }
2189                 }
2190                 #endregion
2191                 
2192                 #region System information
2193                 internal override int KeyboardSpeed { get{ throw new NotImplementedException(); } } 
2194                 internal override int KeyboardDelay { get{ throw new NotImplementedException(); } } 
2195
2196                 internal override int CaptionHeight {
2197                         get {
2198                                 return 19;
2199                         }
2200                 }
2201
2202                 internal override  Size CursorSize { get{ throw new NotImplementedException(); } }
2203                 internal override  bool DragFullWindows { get{ throw new NotImplementedException(); } }
2204                 internal override  Size DragSize {
2205                         get {
2206                                 return new Size(4, 4);
2207                         }
2208                 }
2209
2210                 internal override  Size FrameBorderSize {
2211                         get {
2212                                 return new Size (2, 2);
2213                         }
2214                 }
2215
2216                 internal override  Size IconSize { get{ throw new NotImplementedException(); } }
2217                 internal override  Size MaxWindowTrackSize { get{ throw new NotImplementedException(); } }
2218                 internal override bool MenuAccessKeysUnderlined {
2219                         get {
2220                                 return false;
2221                         }
2222                 }
2223                 internal override Size MinimizedWindowSpacingSize { get{ throw new NotImplementedException(); } }
2224
2225                 internal override Size MinimumWindowSize {
2226                         get {
2227                                 return new Size(110, 22);
2228                         }
2229                 }
2230
2231                 internal override Keys ModifierKeys {
2232                         get {
2233                                 return KeyboardHandler.ModifierKeys;
2234                         }
2235                 }
2236                 internal override Size SmallIconSize { get{ throw new NotImplementedException(); } }
2237                 internal override int MouseButtonCount { get{ throw new NotImplementedException(); } }
2238                 internal override bool MouseButtonsSwapped { get{ throw new NotImplementedException(); } }
2239                 internal override bool MouseWheelPresent { get{ throw new NotImplementedException(); } }
2240
2241                 internal override MouseButtons MouseButtons {
2242                         get {
2243                                 return MouseState;
2244                         }
2245                 }
2246
2247                 internal override Rectangle VirtualScreen {
2248                         get {
2249                                 return WorkingArea;
2250                         }
2251                 }
2252
2253                 internal override Rectangle WorkingArea { 
2254                         get { 
2255                                 Carbon.HIRect bounds = CGDisplayBounds (CGMainDisplayID ());
2256                                 return new Rectangle ((int)bounds.origin.x, (int)bounds.origin.y, (int)bounds.size.width, (int)bounds.size.height);
2257                         }
2258                 }
2259                 internal override bool ThemesEnabled {
2260                         get {
2261                                 return XplatUICarbon.themes_enabled;
2262                         }
2263                 }
2264  
2265
2266                 #endregion
2267                 
2268                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2269                 extern static int HIViewConvertPoint (ref Carbon.CGPoint point, IntPtr pView, IntPtr cView);
2270                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2271                 extern static int HIViewChangeFeatures (IntPtr aView, ulong bitsin, ulong bitsout);
2272                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2273                 extern static int HIViewFindByID (IntPtr rootWnd, Carbon.HIViewID id, ref IntPtr outPtr);
2274                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2275                 extern static int HIGrowBoxViewSetTransparent (IntPtr GrowBox, bool transparency);
2276                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2277                 extern static IntPtr HIViewGetRoot (IntPtr hWnd);
2278                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2279                 extern static int HIObjectCreate (IntPtr cfStr, uint what, ref IntPtr hwnd);
2280                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2281                 extern static int HIObjectRegisterSubclass (IntPtr classid, IntPtr superclassid, uint options, Carbon.EventDelegate upp, uint count, Carbon.EventTypeSpec [] list, IntPtr state, ref IntPtr cls);
2282                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2283                 extern static int HIViewPlaceInSuperviewAt (IntPtr view, float x, float y);
2284                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2285                 extern static int HIViewAddSubview (IntPtr parentHnd, IntPtr childHnd);
2286                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2287                 extern static IntPtr HIViewGetPreviousView (IntPtr aView);
2288                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2289                 extern static IntPtr HIViewGetSuperview (IntPtr aView);
2290                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2291                 extern static int HIViewRemoveFromSuperview (IntPtr aView);
2292                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2293                 extern static int HIViewSetVisible (IntPtr vHnd, bool visible);
2294                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2295                 extern static bool HIViewIsVisible (IntPtr vHnd);
2296                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2297                 extern static int HIViewGetBounds (IntPtr vHnd, ref Carbon.HIRect r);
2298                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2299                 extern static int HIViewScrollRect (IntPtr vHnd, ref Carbon.HIRect rect, float x, float y);
2300                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2301                 extern static int HIViewSetZOrder (IntPtr hWnd, int cmd, IntPtr oHnd);
2302                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2303                 extern static int HIViewNewTrackingArea (IntPtr inView, IntPtr inShape, UInt64 inID, ref IntPtr outRef);
2304                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2305                 extern static IntPtr HIViewGetWindow (IntPtr aView);
2306                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2307                 extern static int HIViewSetFrame (IntPtr view_handle, ref Carbon.HIRect bounds);
2308                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2309                 internal extern static int HIViewSetNeedsDisplayInRect (IntPtr view_handle, ref Carbon.HIRect rect, bool needs_display);
2310                 
2311                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2312                 extern static void SetRect (ref Carbon.Rect r, short left, short top, short right, short bottom);
2313                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2314                 static extern int ActivateWindow (IntPtr windowHnd, bool inActivate);
2315                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2316                 static extern bool IsWindowActive (IntPtr windowHnd);
2317                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2318                 static extern int SetAutomaticControlDragTrackingEnabledForWindow (IntPtr window, bool enabled);
2319
2320                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2321                 extern static IntPtr GetEventDispatcherTarget ();
2322                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2323                 extern static int SendEventToEventTarget (IntPtr evt, IntPtr target);
2324                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2325                 extern static int ReleaseEvent (IntPtr evt);
2326                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2327                 extern static int ReceiveNextEvent (uint evtCount, IntPtr evtTypes, double timeout, bool processEvt, ref IntPtr evt);
2328
2329                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2330                 extern static bool IsWindowCollapsed (IntPtr hWnd);
2331                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2332                 extern static bool IsWindowInStandardState (IntPtr hWnd, IntPtr a, IntPtr b);
2333                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2334                 extern static void CollapseWindow (IntPtr hWnd, bool collapse);
2335                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2336                 extern static void ZoomWindow (IntPtr hWnd, short partCode, bool front);
2337                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2338                 extern static int GetWindowAttributes (IntPtr hWnd, ref Carbon.WindowAttributes outAttributes);
2339                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2340                 extern static int ChangeWindowAttributes (IntPtr hWnd, Carbon.WindowAttributes inAttributes, Carbon.WindowAttributes outAttributes);
2341                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2342                 internal extern static int GetGlobalMouse (ref Carbon.QDPoint outData);
2343                 
2344                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2345                 extern static int BeginAppModalStateForWindow (IntPtr window);
2346                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2347                 extern static int EndAppModalStateForWindow (IntPtr window);
2348                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2349                 extern static int CreateNewWindow (Carbon.WindowClass klass, Carbon.WindowAttributes attributes, ref Carbon.Rect r, ref IntPtr window);
2350                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2351                 extern static int DisposeWindow (IntPtr wHnd);
2352                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2353                 internal extern static int ShowWindow (IntPtr wHnd);
2354                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2355                 internal extern static int HideWindow (IntPtr wHnd);
2356                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2357                 internal extern static bool IsWindowVisible (IntPtr wHnd);
2358                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2359                 extern static int SetWindowBounds (IntPtr wHnd, uint reg, ref Carbon.Rect rect);
2360                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2361                 extern static int GetWindowBounds (IntPtr wHnd, uint reg, ref Carbon.Rect rect);
2362
2363                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2364                 extern static int SetControlTitleWithCFString (IntPtr hWnd, IntPtr titleCFStr);
2365                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2366                 extern static int SetWindowTitleWithCFString (IntPtr hWnd, IntPtr titleCFStr);
2367                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2368                 internal extern static IntPtr __CFStringMakeConstantString (string cString);
2369                 
2370                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2371                 internal extern static int CFRelease (IntPtr wHnd);
2372                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2373                 extern static short GetMBarHeight ();
2374                 
2375                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2376                 extern static void AlertSoundPlay ();
2377
2378                 #region Cursor imports
2379                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2380                 extern static Carbon.HIRect CGDisplayBounds (IntPtr displayID);
2381                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2382                 extern static IntPtr CGMainDisplayID ();
2383                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2384                 extern static void CGDisplayShowCursor (IntPtr display);
2385                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2386                 extern static void CGDisplayHideCursor (IntPtr display);
2387                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2388                 extern static void CGDisplayMoveCursorToPoint (IntPtr display, Carbon.CGPoint point);
2389                 #endregion
2390
2391                 #region Process imports
2392                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2393                 extern static int GetCurrentProcess (ref Carbon.ProcessSerialNumber psn);
2394                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2395                 extern static int TransformProcessType (ref Carbon.ProcessSerialNumber psn, uint type);
2396                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2397                 extern static int SetFrontProcess (ref Carbon.ProcessSerialNumber psn);
2398                 #endregion
2399
2400                 #region Dock tile imports
2401                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2402                 extern static IntPtr CGColorSpaceCreateDeviceRGB();
2403                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2404                 extern static IntPtr CGDataProviderCreateWithData (IntPtr info, IntPtr [] data, int size, IntPtr releasefunc);
2405                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2406                 extern static IntPtr CGImageCreate (int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow, IntPtr colorspace, uint bitmapInfo, IntPtr provider, IntPtr decode, int shouldInterpolate, int intent);
2407                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2408                 extern static void SetApplicationDockTileImage(IntPtr imageRef);
2409                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2410                 extern static void RestoreApplicationDockTileImage();
2411                 #endregion
2412         }
2413 }