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