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