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