* TreeView.cs: Don't draw the selected node when we lose
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / XplatUIOSX.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 Novell, Inc.
21 //
22 // Authors:
23 //      Geoff Norton  <gnorton@customerdna.com>
24 //
25 //
26
27 // This really doesn't work at all; please dont file bugs on it yet.
28
29 // MAJOR TODO:
30 //  Fix clipping of children
31 //  Wire up keyboard
32
33 using System;
34 using System.Threading;
35 using System.Drawing;
36 using System.ComponentModel;
37 using System.Collections;
38 using System.Diagnostics;
39 using System.Runtime.InteropServices;
40
41 /// OSX Version
42 namespace System.Windows.Forms {
43
44         // The Carbon Event callback delegate
45         delegate int CarbonEventDelegate (IntPtr inCallRef, IntPtr inEvent, IntPtr userData);
46
47         internal class XplatUIOSX : XplatUIDriver {
48                 
49                 #region Local Variables
50                 
51                 // General driver variables
52                 private static XplatUIOSX Instance;
53                 private static int RefCount;
54                 private static bool ThemesEnabled;
55                 private static IntPtr FocusWindow;
56
57                 // Mouse 
58                 private static MouseButtons MouseState;
59                 private static Point MousePosition;
60                 private static Hwnd MouseWindow;
61                 
62                 // OSX Specific
63                 private static GrabStruct Grab;
64                 private static OSXCaret Caret;
65                 private static OSXHover Hover;
66                 private CarbonEventDelegate CarbonEventHandler;
67                 private static Hashtable WindowMapping;
68                 private static Hashtable WindowBackgrounds;
69                 private static Hwnd GrabWindowHwnd;
70                 private static IntPtr FosterParent;
71                 private static int TitleBarHeight;
72                 private static int MenuBarHeight;
73                 private static EventTypeSpec [] viewEvents = new EventTypeSpec [] {
74                                                                         new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlSetFocusPart), 
75                                                                         new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlClick), 
76                                                                         new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlContextualMenuClick), 
77                                                                         new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlTrack), 
78                                                                         new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlSimulateHit), 
79                                                                         new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlBoundsChanged), 
80                                                                         new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlDraw) 
81                                                                         };
82                 private static EventTypeSpec [] windowEvents = new EventTypeSpec[] {
83                                                                         //new EventTypeSpec (OSXConstants.kEventClassMouse, OSXConstants.kEventMouseEntered),
84                                                                         //new EventTypeSpec (OSXConstants.kEventClassMouse, OSXConstants.kEventMouseExited),
85                                                                         new EventTypeSpec (OSXConstants.kEventClassMouse, OSXConstants.kEventMouseMoved),
86                                                                         //new EventTypeSpec (OSXConstants.kEventClassMouse, OSXConstants.kEventMouseDragged),
87                                                                         //new EventTypeSpec (OSXConstants.kEventClassMouse, OSXConstants.kEventMouseWheelMoved),
88                                                                         new EventTypeSpec (OSXConstants.kEventClassWindow, OSXConstants.kEventWindowBoundsChanged),
89                                                                         new EventTypeSpec (OSXConstants.kEventClassWindow, OSXConstants.kEventWindowClose),
90                                                                         new EventTypeSpec (OSXConstants.kEventClassKeyboard, OSXConstants.kEventRawKeyDown),
91                                                                         new EventTypeSpec (OSXConstants.kEventClassKeyboard, OSXConstants.kEventRawKeyRepeat),
92                                                                         new EventTypeSpec (OSXConstants.kEventClassKeyboard, OSXConstants.kEventRawKeyUp)
93                                                                         };
94                                                                         
95                 
96                 // Message loop
97                 private static Queue MessageQueue;
98                 private static bool GetMessageResult;
99
100                 // Timers
101                 private ArrayList TimerList;
102                 
103                 static readonly object lockobj = new object ();
104                 
105                 // Event Handlers
106                 internal override event EventHandler Idle;
107
108                 #endregion
109                 
110                 #region Constructors
111                 private XplatUIOSX() {
112
113                         RefCount = 0;
114                         TimerList = new ArrayList ();
115                         MessageQueue = new Queue ();
116                         
117                         Initialize ();
118                 }
119
120                 ~XplatUIOSX() {
121                         // FIXME: Clean up the FosterParent here.
122                 }
123
124                 #endregion
125
126                 #region Singleton specific code
127                 
128                 public static XplatUIOSX GetInstance() {
129                         lock (lockobj) {
130                                 if (Instance == null) {
131                                         Instance = new XplatUIOSX ();
132                                 }
133                                 RefCount++;
134                         }
135                         return Instance;
136                 }
137
138                 public int Reference {
139                         get {
140                                 return RefCount;
141                         }
142                 }
143                 
144                 #endregion
145                 
146                 #region Internal methods
147                 
148                 internal void Initialize () {
149
150                         // Initialize the Event Handler delegate
151                         CarbonEventHandler = new CarbonEventDelegate (EventCallback);
152                         
153                         // Initilize the mouse controls
154                         Hover.Interval = 500;
155                         Hover.Timer = new Timer ();
156                         Hover.Timer.Enabled = false;
157                         Hover.Timer.Interval = Hover.Interval;
158                         Hover.Timer.Tick += new EventHandler (HoverCallback);
159                         Hover.X = -1;
160                         Hover.Y = -1;
161                         MouseState = MouseButtons.None;
162                         MousePosition = Point.Empty;
163                                 
164                         // Initialize the Caret
165                         Caret.Timer = new Timer ();
166                         Caret.Timer.Interval = 500;
167                         Caret.Timer.Tick += new EventHandler (CaretCallback);
168                         
169                         // Initialize the OSX Specific stuff
170                         WindowMapping = new Hashtable ();
171                         WindowBackgrounds = new Hashtable ();
172                         
173                         // Initialize the FosterParent
174                         IntPtr rect = IntPtr.Zero;
175                         SetRect (ref rect, (short)0, (short)0, (short)0, (short)0);
176                         CheckError (CreateNewWindow (WindowClass.kDocumentWindowClass, WindowAttributes.kWindowStandardHandlerAttribute | WindowAttributes.kWindowCloseBoxAttribute | WindowAttributes.kWindowFullZoomAttribute | WindowAttributes.kWindowCollapseBoxAttribute | WindowAttributes.kWindowResizableAttribute | WindowAttributes.kWindowCompositingAttribute, ref rect, ref FosterParent), "CreateFosterParent ()");
177                         
178                         // Get some values about bar heights
179                         Rect structRect = new Rect ();
180                         Rect contentRect = new Rect ();
181                         CheckError (GetWindowBounds (FosterParent, 32, ref structRect), "GetWindowBounds ()");
182                         CheckError (GetWindowBounds (FosterParent, 33, ref contentRect), "GetWindowBounds ()");
183                         
184                         TitleBarHeight = Math.Abs(structRect.top - contentRect.top);
185                         MenuBarHeight = GetMBarHeight ();
186                         
187                         // Focus
188                         FocusWindow = IntPtr.Zero;
189                         
190                         // Message loop
191                         GetMessageResult = true;
192                 }
193                 
194                 #endregion
195                 
196                 #region Private methods
197                 #endregion
198                 
199                 #region Callbacks
200                 
201                 private void CaretCallback (object sender, EventArgs e) {
202                         if (Caret.Paused) {
203                                 return;
204                         }
205
206                         if (!Caret.On) {
207                                 ShowCaret ();
208                         } else {
209                                 HideCaret ();
210                         }
211                 }
212                 
213                 private void HoverCallback (object sender, EventArgs e) {
214                         if ((Hover.X == MousePosition.X) && (Hover.Y == MousePosition.Y)) {
215                                 MSG msg = new MSG ();
216                                 msg.hwnd = Hover.Hwnd;
217                                 msg.message = Msg.WM_MOUSEHOVER;
218                                 msg.wParam = GetMousewParam (0);
219                                 msg.lParam = (IntPtr)((ushort)Hover.X << 16 | (ushort)Hover.X);
220                                 MessageQueue.Enqueue (msg);
221                         }
222                 }
223                 
224                 internal int EventCallback (IntPtr inCallRef, IntPtr inEvent, IntPtr handle) {
225                         uint eventClass = GetEventClass (inEvent);
226                         uint eventKind = GetEventKind (inEvent);
227                         int retVal = 0;
228                         lock (MessageQueue) {
229                                 switch (eventClass) {
230                                         // keyboard
231                                         case OSXConstants.kEventClassKeyboard: {
232                                                 retVal = ProcessKeyboardEvent (inEvent, eventKind, handle);
233                                                 break;
234                                         }
235                                         //window
236                                         case OSXConstants.kEventClassWindow: {
237                                                 retVal = ProcessWindowEvent (inEvent, eventKind, handle);
238                                                 break;
239                                         }
240                                         // mouse
241                                         case OSXConstants.kEventClassMouse: {
242                                                 retVal = ProcessMouseEvent (inEvent, eventKind, handle);
243                                                 break;
244                                         }
245                                         // control
246                                         case OSXConstants.kEventClassControl: {
247                                                 retVal = ProcessControlEvent (inEvent, eventKind, handle);
248                                                 break;
249                                         }
250                                         default: {
251                                                 Console.WriteLine ("WARNING: Unhandled eventClass {0}", eventClass);
252                                                 break;
253                                         }
254                                 }
255                         }
256                         
257                         return retVal;
258                 }
259
260                 #endregion
261                 
262                 #region Private Methods
263                 
264                 // This sucks write a real driver
265                 private int ProcessKeyboardEvent (IntPtr inEvent, uint eventKind, IntPtr handle) {
266                         MSG msg = new MSG ();
267                         byte charCode = 0x00;
268                         GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamKeyMacCharCodes, OSXConstants.EventParamType.typeChar, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (byte)), IntPtr.Zero, ref charCode);
269                         IntPtr cntrl = IntPtr.Zero;
270                         CheckError (GetKeyboardFocus (handle, ref cntrl), "GetKeyboardFocus()");
271                         msg.hwnd = cntrl;
272                         msg.lParam = IntPtr.Zero;
273                         switch (charCode) {
274                                 case 28:
275                                         charCode = 0x25;
276                                         break;
277                                 case 29:
278                                         charCode = 0x27;
279                                         break;
280                                 case 30:
281                                         charCode = 0x26;
282                                         break;
283                                 case 31:
284                                         charCode = 0x28;
285                                         break;
286                         }
287                         msg.wParam = (IntPtr)charCode;
288                         switch (eventKind) {
289                                 // keydown
290                                 case OSXConstants.kEventRawKeyDown: {
291                                         msg.message = Msg.WM_KEYDOWN;
292                                         break;
293                                 }
294                                 // repeat
295                                 case OSXConstants.kEventRawKeyRepeat: {
296                                         msg.message = Msg.WM_KEYDOWN;
297                                         break;
298                                 }
299                                 // keyup
300                                 case OSXConstants.kEventRawKeyUp: {
301                                         msg.message = Msg.WM_KEYUP;
302                                         break;
303                                 }
304                         }
305                         MessageQueue.Enqueue (msg);
306                         return -9874;
307                 }
308
309                 private int ProcessWindowEvent (IntPtr inEvent, uint eventKind, IntPtr handle) {
310                         MSG msg = new MSG ();
311                         switch (eventKind) {
312                                 // Someone closed a window
313                                 case OSXConstants.kEventWindowClose: {
314                                         // This is our real window; so we have to post to the corresponding view
315                                         // FIXME: Should we doublehash the table to get the real window handle without this loop?
316                                         IDictionaryEnumerator e = WindowMapping.GetEnumerator ();
317                                         while (e.MoveNext ()) {
318                                                 if ((IntPtr)e.Value == handle) {
319                                                         NativeWindow.WndProc((IntPtr)e.Key, Msg.WM_DESTROY, IntPtr.Zero, IntPtr.Zero);
320                                                 }
321                                         }
322                                         return 0;
323                                 }
324                                 case OSXConstants.kEventWindowBoundsChanged: {
325                                         // This is our real window; so we have to resize the corresponding view as well
326                                         // FIXME: Should we doublehash the table to get the real window handle without this loop?
327                                         
328                                         IDictionaryEnumerator e = WindowMapping.GetEnumerator ();
329                                         while (e.MoveNext ()) {
330                                                 if ((IntPtr)e.Value == handle) {
331                                                         Hwnd hwnd = Hwnd.ObjectFromHandle ((IntPtr) e.Key);
332                                                         // Get the bounds of the window
333                                                         Rect bounds = new Rect ();
334                                                         CheckError (GetWindowBounds (handle, 33, ref bounds), "GetWindowBounds ()");
335                                                         HIRect r = new HIRect ();
336                                                         
337                                                         // Get our frame for the Handle
338                                                         CheckError (HIViewGetFrame (hwnd.Handle, ref r), "HIViewGetFrame ()");
339                                                         r.size.width = bounds.right-bounds.left;
340                                                         r.size.height = bounds.bottom-bounds.top;
341                                                         // Set the view to the new size
342                                                 CheckError (HIViewSetFrame (hwnd.WholeWindow, ref r), "HIViewSetFrame ()");
343                                                 
344                                                 // Update the hwnd internal size representation
345                                                         hwnd.x = (int)r.origin.x;
346                                                         hwnd.y = (int)r.origin.y;
347                                                         hwnd.width = (int)r.size.width;
348                                                         hwnd.height = (int)r.size.height;
349                                                         Rectangle client_rect = hwnd.ClientRect;
350                                                         
351                                                         r.size.width = client_rect.Width;
352                                                         r.size.height = client_rect.Height;
353                                                         r.origin.x = client_rect.X;
354                                                         r.origin.y = client_rect.Y;
355                                                         
356                                                         // Update the client area too
357                                                         CheckError (HIViewSetFrame (hwnd.ClientWindow, ref r));
358                                                         
359                                                         // Add the message to the queue
360                                                         msg.message = Msg.WM_WINDOWPOSCHANGED;
361                                                         msg.hwnd = hwnd.Handle;
362                                                         msg.wParam = IntPtr.Zero;
363                                                         msg.lParam = IntPtr.Zero;
364                                                         MessageQueue.Enqueue (msg);
365                                                         
366                                                         return 0;
367                                                 }
368                                         }
369                                         break;
370                                 }
371                         }
372                         return -9874;
373                 }
374                                 
375                 private int ProcessMouseEvent (IntPtr inEvent, uint eventKind, IntPtr handle) {
376                         MSG msg = new MSG ();           
377                         
378                         switch (eventKind) {
379                                 case OSXConstants.kEventMouseMoved: {
380                                         // Where is the mouse in global coordinates
381                                         QDPoint pt = new QDPoint ();
382                                         GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamMouseLocation, OSXConstants.EventParamType.typeQDPoint, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (QDPoint)), IntPtr.Zero, ref pt);
383                                         
384                                         // Where is the mouse in the window
385                                         Rect window_bounds = new Rect ();
386                                         GetWindowBounds (handle, 33, ref window_bounds);
387                                         CGPoint window_pt = new CGPoint ((short) (pt.x - window_bounds.left), (short) (pt.y - window_bounds.top));
388                                         
389                                         IntPtr window_handle = IntPtr.Zero;
390                                         HIViewFindByID (HIViewGetRoot (handle), new HIViewID (OSXConstants.kEventClassWindow, 1), ref window_handle);
391                                         
392                                         // Determine which control was hit
393                                         IntPtr view_handle = IntPtr.Zero;
394                                         HIViewGetSubviewHit (window_handle, ref window_pt, true, ref view_handle);
395                                         
396                                         // Convert the point to view local coordinates
397                                         HIViewConvertPoint (ref window_pt, window_handle, view_handle);
398                                         
399                                         Hwnd hwnd = Hwnd.ObjectFromHandle (view_handle);
400                                         
401                                         if (hwnd == null)
402                                                 return -9874;
403                                                 
404                                         // Generate the message
405                                         msg.hwnd = hwnd.Handle;
406                                         msg.message = Msg.WM_MOUSEMOVE;
407                                         msg.lParam = (IntPtr) ((ushort)window_pt.y << 16 | (ushort)window_pt.x);
408                                         msg.wParam = GetMousewParam (0);
409                                         MousePosition.X = (int)window_pt.x;
410                                         MousePosition.Y = (int)window_pt.y;
411                                         
412                                         Hover.Hwnd = msg.hwnd;
413                                         Hover.Timer.Enabled = true;
414                                         MessageQueue.Enqueue (msg);
415                                         return -9874;
416                                 }
417                         }
418                         return -9874;
419                 }
420                                         
421                 private int ProcessControlEvent (IntPtr inEvent, uint eventKind, IntPtr handle) {
422                         GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamDirectObject, OSXConstants.EventParamType.typeControlRef, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (IntPtr)), IntPtr.Zero, ref handle);
423                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
424                         MSG msg = new MSG ();
425                                         
426                         switch (eventKind) {
427                                 case OSXConstants.kEventControlDraw: {
428                                         
429                                         if(!hwnd.visible || !HIViewIsVisible (handle))
430                                                 return 0;
431
432                                         /*
433                                         IntPtr rgnhandle = IntPtr.Zero;
434                                         GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamRgnHandle, OSXConstants.EventParamType.typeQDRgnHandle, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (IntPtr)), IntPtr.Zero, ref rgnhandle);
435                                         IntPtr duprgn = NewRgn ();
436                                         CopyRgn (rgnhandle, duprgn);
437                                         ClipRegions [hwnd.Handle] = duprgn;             
438                                         */
439                                         
440                                         // Get the dirty area
441                                         HIRect bounds = new HIRect ();
442                                         HIViewGetBounds (handle, ref bounds); 
443                                         
444                                         bool client = (hwnd.ClientWindow == handle ? true : false);
445                                         
446                                         if (!client && bounds.origin.x >= hwnd.ClientRect.X && bounds.origin.y >= hwnd.ClientRect.Y) {
447                                                 // This is a paint on WholeWindow inside the clientRect; we can safely discard this
448                                                 return 0;
449                                         }
450                                         
451                                         hwnd.AddInvalidArea ((int)bounds.origin.x, (int)bounds.origin.y, (int)bounds.size.width, (int)bounds.size.height);
452                                         if (WindowBackgrounds [hwnd] != null) {
453                                                 Color c = (Color)WindowBackgrounds [hwnd];
454                                                 IntPtr contextref = IntPtr.Zero;
455                                                 GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamCGContextRef, OSXConstants.EventParamType.typeCGContextRef, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (IntPtr)), IntPtr.Zero, ref contextref);
456                                                 CGContextSetRGBFillColor (contextref, (float)c.R/255, (float)c.G/255, (float)c.B/255, (float)c.A/255);
457                                                 CGContextFillRect (contextref, bounds);
458                                         }
459                                         
460                                         // Add a paint to the queue
461                                         msg.hwnd = hwnd.Handle;
462                                         msg.message = Msg.WM_PAINT;
463                                         msg.wParam = IntPtr.Zero;
464                                         msg.lParam = IntPtr.Zero;
465                                         MessageQueue.Enqueue (msg);
466                         
467                                         return 0;
468                                 }
469                                 case OSXConstants.kEventControlBoundsChanged: {
470                                         // This can happen before our HWND is created so we need to check to make sure its not null
471                                         if (hwnd != null) {
472                                                 // Get the bounds
473                                                 HIRect bounds = new HIRect ();
474                                                 HIViewGetFrame (handle, ref bounds); 
475                                                 // Update the hwnd size
476                                                 hwnd.x = (int)bounds.origin.x;
477                                                 hwnd.y = (int)bounds.origin.y;
478                                                 hwnd.width = (int)bounds.size.width;
479                                                 hwnd.height = (int)bounds.size.height;
480                                                 
481                                                 // TODO: Do we need to send a paint here or does BoundsChanged make a ControlDraw for the exposed area?
482                                         }                                                       
483                                         return 0;
484                                 }
485                                 case OSXConstants.kEventControlTrack: {
486                                         // get the point that was hit
487                                         QDPoint point = new QDPoint ();
488                                         CheckError (GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamMouseLocation, OSXConstants.EventParamType.typeQDPoint, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (QDPoint)), IntPtr.Zero, ref point), "GetEventParameter() MouseLocation");
489                                         MouseTrackingResult mousestatus = MouseTrackingResult.kMouseTrackingMouseDown;
490                                         IntPtr modifiers = IntPtr.Zero;
491                                         
492                                         while (mousestatus != MouseTrackingResult.kMouseTrackingMouseUp) {
493                                                 CheckTimers (DateTime.Now);
494                                                 if (mousestatus == MouseTrackingResult.kMouseTrackingMouseDragged) {
495                                                         QDPoint realpoint = point;
496                                                         int x = point.x;
497                                                         int y = point.y;
498                                                         ScreenToClient (hwnd.Handle, ref x, ref y);
499                                                         realpoint.x = (short)x;
500                                                         realpoint.y = (short)y;
501                                                         NativeWindow.WndProc (hwnd.Handle, Msg.WM_MOUSEMOVE, GetMousewParam (0), (IntPtr) ((ushort)realpoint.y << 16 | (ushort)realpoint.x));
502                                                 }
503                                                 // Process the rest of the event queue
504                                                 while (MessageQueue.Count > 0) {
505                                                         msg = (MSG)MessageQueue.Dequeue ();
506                                                         NativeWindow.WndProc (msg.hwnd, msg.message, msg.wParam, msg.lParam);
507                                                 }
508                                                 TrackMouseLocationWithOptions ((IntPtr)(-1), 0, 0.01, ref point, ref modifiers, ref mousestatus);
509                                         }
510                                         
511                                         msg.hwnd = hwnd.Handle;
512                                         
513                                         bool client = (hwnd.ClientWindow == handle ? true : false);
514                                         
515                                         int wparam = (int)GetMousewParam (0);
516                                         switch (MouseState) {
517                                                 case MouseButtons.Left:
518                                                         MouseState &= ~MouseButtons.Left;
519                                                         msg.message = (client ? Msg.WM_LBUTTONUP : Msg.WM_NCLBUTTONUP);
520                                                         wparam &= (int)MsgButtons.MK_LBUTTON;
521                                                         break;
522                                                 case MouseButtons.Middle:
523                                                         MouseState &= ~MouseButtons.Middle;
524                                                         msg.message = (client ? Msg.WM_MBUTTONUP : Msg.WM_NCMBUTTONUP);
525                                                         wparam &= (int)MsgButtons.MK_MBUTTON;
526                                                         break;
527                                                 case MouseButtons.Right:
528                                                         MouseState &= ~MouseButtons.Right;
529                                                         msg.message = (client ? Msg.WM_RBUTTONUP : Msg.WM_NCRBUTTONUP);
530                                                         wparam &= (int)MsgButtons.MK_RBUTTON;
531                                                         break;
532                                         }
533                                         int x2 = point.x;
534                                         int y2 = point.y;
535                                         ScreenToClient (hwnd.Handle, ref x2, ref y2);
536                                         point.x = (short)x2;
537                                         point.y = (short)y2;
538
539                                         msg.wParam = (IntPtr)wparam;
540                                                 
541                                         msg.lParam = (IntPtr) ((ushort)point.y << 16 | (ushort)point.x);
542                                         MousePosition.X = (int)point.x;
543                                         MousePosition.Y = (int)point.y;
544                                         //NativeWindow.WndProc (msg.hwnd, msg.message, msg.lParam, msg.wParam);
545                                         MessageQueue.Enqueue (msg);
546                                         
547                                         IntPtr window = GetControlOwner (hwnd.Handle);
548                                         SetKeyboardFocus (window, hwnd.Handle, 1);
549                                         
550                                         return 0;
551                                 }
552                                 case OSXConstants.kEventControlContextualMenuClick:
553                                 case OSXConstants.kEventControlClick: {
554                                         // get the point that was hit
555                                         QDPoint point = new QDPoint ();
556                                         CheckError (GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamMouseLocation, OSXConstants.EventParamType.typeQDPoint, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (QDPoint)), IntPtr.Zero, ref point), "GetEventParameter() MouseLocation");
557                                         QDPoint trackpoint = point;
558                                         int x = point.x;
559                                         int y = point.y;
560                                         ScreenToClient (hwnd.Handle, ref x, ref y);
561                                         point.x = (short)x;
562                                         point.y = (short)y;
563                                         
564                                         // which button was pressed?
565                                         ushort button = 0;
566                                         GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamMouseButton, OSXConstants.EventParamType.typeMouseButton, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (ushort)), IntPtr.Zero, ref button);
567                                         if (button == 2) {
568                                                 point.x = (short)MousePosition.X;
569                                                 point.y = (short)MousePosition.Y;
570                                         }
571                                         
572                                         msg.hwnd = hwnd.Handle;
573                                         
574                                         bool client = (hwnd.ClientWindow == handle ? true : false);
575                                         
576                                         int wparam = (int)GetMousewParam (0);
577                                         switch (button) {
578                                                 case 1:
579                                                         MouseState |= MouseButtons.Left;
580                                                         msg.message = (client ? Msg.WM_LBUTTONDOWN : Msg.WM_NCLBUTTONDOWN);
581                                                         wparam |= (int)MsgButtons.MK_LBUTTON;
582                                                         break;
583                                                 case 2:
584                                                         MouseState |= MouseButtons.Right;
585                                                         msg.message = (client ? Msg.WM_RBUTTONDOWN : Msg.WM_NCRBUTTONDOWN);
586                                                         wparam |= (int)MsgButtons.MK_RBUTTON;
587                                                         break;
588                                                 case 3:
589                                                         MouseState |= MouseButtons.Middle;
590                                                         msg.message = (client ? Msg.WM_MBUTTONDOWN : Msg.WM_NCMBUTTONDOWN);
591                                                         wparam |= (int)MsgButtons.MK_MBUTTON;
592                                                         break;
593                                         }
594                                         msg.wParam = (IntPtr)wparam;
595                                                 
596                                         msg.lParam = (IntPtr) ((ushort)point.y << 16 | (ushort)point.x);
597                                         MousePosition.X = (int)point.x;
598                                         MousePosition.Y = (int)point.y;
599                                         NativeWindow.WndProc (msg.hwnd, msg.message, msg.wParam, msg.lParam);
600                                         
601                                         TrackControl (handle, trackpoint, IntPtr.Zero);
602                                         return 0;
603                                 }
604                                 case OSXConstants.kEventControlSetFocusPart: {
605                                         // This handles setting focus
606                                         short pcode = 1;
607                                         GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamControlPart, OSXConstants.EventParamType.typeControlPartCode, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (short)), IntPtr.Zero, ref pcode);
608                                         switch (pcode) {
609                                                 case 0:
610                                                 case -1:
611                                                 case -2:
612                                                         pcode = 0;
613                                                         break;
614                                         }
615                                         SetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamControlPart, OSXConstants.EventParamType.typeControlPartCode, (uint)Marshal.SizeOf (typeof (short)), ref pcode);
616                                         return 0;
617                                 }
618                         }
619                         return -9874;
620                 }
621                 private IntPtr GetMousewParam(int Delta) {
622                         int     result = 0;
623
624                         if ((MouseState & MouseButtons.Left) != 0) {
625                                 result |= (int)MsgButtons.MK_LBUTTON;
626                         }
627
628                         if ((MouseState & MouseButtons.Middle) != 0) {
629                                 result |= (int)MsgButtons.MK_MBUTTON;
630                         }
631
632                         if ((MouseState & MouseButtons.Right) != 0) {
633                                 result |= (int)MsgButtons.MK_RBUTTON;
634                         }
635
636                         return (IntPtr)result;
637                 }
638
639                 private double NextTimeout ()
640                 {
641                         DateTime now = DateTime.Now;
642                         int timeout = 0x7FFFFFF;
643                         lock (TimerList) {
644                                 foreach (Timer timer in TimerList) {
645                                         int next = (int) (timer.Expires - now).TotalMilliseconds;
646                                         if (next < 0)
647                                                 return 0;
648                                         if (next < timeout)
649                                                 timeout = next;
650                                 }
651                         }
652                         if (timeout < Timer.Minimum)
653                                 timeout = Timer.Minimum;
654
655                         return (double)((double)timeout/1000);
656                 }
657                 
658                 private void CheckTimers (DateTime now)
659                 {
660                         lock (TimerList) {
661                                 int count = TimerList.Count;
662                                 if (count == 0)
663                                         return;
664                                 for (int i = 0; i < TimerList.Count; i++) {
665                                         Timer timer = (Timer) TimerList [i];
666                                         if (timer.Enabled && timer.Expires <= now) {
667                                                 timer.FireTick ();
668                                                 timer.Update (now);
669                                         }
670                                 }
671                         }
672                 }
673
674                 internal void InvertCaret () {
675                         IntPtr window = GetControlOwner (Caret.Hwnd);
676                         SetPortWindowPort (window);
677                         Rect r = new Rect ();
678                         GetWindowPortBounds (window, ref r);
679                         r.top += (short)Caret.Y;
680                         r.left += (short)Caret.X;
681                         r.bottom = (short)(r.top + Caret.Height);
682                         r.right = (short)(r.left + Caret.Width);
683                         InvertRect (ref r);
684                 }
685                 
686                 private void SetHwndStyles(Hwnd hwnd, CreateParams cp) {
687                         throw new NotImplementedException();
688                 }
689                 
690                 internal void ShowCaret () {
691                         if (Caret.On)
692                                 return;
693                         Caret.On = true;
694                         InvertCaret ();
695                 }
696
697                 internal void HideCaret () {
698                         if (!Caret.On)
699                                 return;
700                         Caret.On = false;
701                         InvertCaret ();
702                 }
703                 
704                 internal void InstallTracking (Hwnd hwnd) {
705                         // This is currently not used
706                         
707                         /*
708                         if (hwnd.client_region_ptr != IntPtr.Zero) {
709                                 ReleaseMouseTrackingRegion (hwnd.client_region_ptr);
710                                 hwnd.client_region_ptr = IntPtr.Zero;
711                         }
712                         if (hwnd.whole_region_ptr != IntPtr.Zero) {
713                                 ReleaseMouseTrackingRegion (hwnd.whole_region_ptr);
714                                 hwnd.whole_region_ptr = IntPtr.Zero;
715                         }
716                         // Setup the new track region
717                         if (hwnd.visible) {
718                                 HIRect client_bounds = new HIRect ();   
719                                 HIViewGetBounds (hwnd.client_window, ref client_bounds);
720                                 HIViewConvertRect (ref client_bounds, hwnd.client_window, IntPtr.Zero);
721                         
722                                 IntPtr rgn = NewRgn ();
723                                 SetRectRgn (rgn, (short)client_bounds.origin.x, (short)client_bounds.origin.y, (short)(client_bounds.origin.x+hwnd.ClientRect.Width), (short)(client_bounds.origin.y+hwnd.ClientRect.Height));
724                                 CreateMouseTrackingRegion (GetControlOwner (hwnd.client_window), rgn, IntPtr.Zero, 0, hwnd.client_region_id, hwnd.client_window, IntPtr.Zero, ref hwnd.client_region_ptr);
725                                 Console.WriteLine (hwnd.ClientRect);
726                                 Console.WriteLine ("Created a mouse trcaking region on the client window @ {0}x{1} {2}x{3}", (short)client_bounds.origin.x, (short)client_bounds.origin.y, (short)(client_bounds.origin.x+hwnd.ClientRect.Width), (short)(client_bounds.origin.y+hwnd.ClientRect.Height));
727                                 if (hwnd.ClientRect.X > 0 && hwnd.ClientRect.Y > 0) {
728                                         HIRect window_bounds = new HIRect ();
729                                         HIViewGetBounds (hwnd.whole_window, ref window_bounds);
730                                         HIViewConvertRect (ref window_bounds, hwnd.whole_window, IntPtr.Zero);
731                                         rgn = NewRgn ();
732                                         SetRectRgn (rgn, (short)window_bounds.origin.x, (short)window_bounds.origin.y, (short)(window_bounds.origin.x+hwnd.ClientRect.X), (short)(window_bounds.origin.y+hwnd.ClientRect.Y));
733                                         CreateMouseTrackingRegion (GetControlOwner (hwnd.whole_window), rgn, IntPtr.Zero, 0, hwnd.whole_region_id, hwnd.whole_window, IntPtr.Zero, ref hwnd.whole_region_ptr);
734                                         Console.WriteLine ("Created a mouse trcaking region on the whole window @ {0}x{1} {2}x{3}", (short)window_bounds.origin.x, (short)window_bounds.origin.y, (short)(window_bounds.origin.x+hwnd.ClientRect.X), (short)(window_bounds.origin.y+hwnd.ClientRect.Y));
735                                 }
736                         }
737                         */
738                 }
739
740                 internal void CheckError (int result, string error) {
741                         if (result != 0)
742                                 throw new Exception ("XplatUIOSX.cs::" + error + "() Carbon subsystem threw an error: " + result);
743                 }
744
745                 internal void CheckError (int result) {
746                         if (result != 0)
747                                 throw new Exception ("XplatUIOSX.cs::Carbon subsystem threw an error: " + result);
748                 }
749
750                 #endregion 
751                 
752                 #region Public Methods
753
754                 internal override IntPtr InitializeDriver() {
755                         return IntPtr.Zero;
756                 }
757
758                 internal override void ShutdownDriver(IntPtr token) {
759                 }
760
761                 internal override void EnableThemes() {
762                         ThemesEnabled = true;
763                 }
764
765                 internal override void Activate(IntPtr handle) {
766                         ActivateWindow (GetControlOwner (handle), true);
767                 }
768                 
769                 internal override void CaretVisible (IntPtr hwnd, bool visible) {
770                         if (Caret.Hwnd == hwnd) {
771                                 if (visible) {
772                                         if (Caret.Visible < 1) {
773                                                 Caret.Visible++;
774                                                 Caret.On = false;
775                                                 if (Caret.Visible == 1) {
776                                                         ShowCaret ();
777                                                         Caret.Timer.Start ();
778                                                 }
779                                         }
780                                 } else {
781                                         Caret.Visible--;
782                                         if (Caret.Visible == 0) {
783                                                 Caret.Timer.Stop ();
784                                                 HideCaret ();
785                                         }
786                                 }
787                         }
788                 }
789                 
790                 internal override bool CalculateWindowRect(IntPtr hWnd, ref Rectangle ClientRect, int Style, int ExStyle, IntPtr MenuHandle, out Rectangle WindowRect) {
791                         FormBorderStyle border_style;
792                         TitleStyle      title_style;
793
794                         title_style = TitleStyle.None;
795                         if ((Style & (int)WindowStyles.WS_CAPTION) != 0) {
796                                 if ((ExStyle & (int)WindowStyles.WS_EX_TOOLWINDOW) != 0) {
797                                         title_style = TitleStyle.Tool;
798                                 } else {
799                                         title_style = TitleStyle.Normal;
800                                 }
801                         }
802
803                         border_style = FormBorderStyle.None;
804                         if ((ExStyle & (int)WindowStyles.WS_EX_WINDOWEDGE) != 0) {
805                                 if ((ExStyle & (int)WindowStyles.WS_EX_TOOLWINDOW) != 0) {
806                                         if ((Style & (int)WindowStyles.WS_THICKFRAME) != 0) {
807                                                 border_style = FormBorderStyle.SizableToolWindow;
808                                         } else {
809                                                 border_style = FormBorderStyle.FixedToolWindow;
810                                         }
811                                 } else if ((ExStyle & (int)WindowStyles.WS_EX_DLGMODALFRAME) != 0) {
812                                         border_style = FormBorderStyle.FixedDialog;
813                                 } else if ((ExStyle & (int)WindowStyles.WS_THICKFRAME) != 0) {
814                                         border_style = FormBorderStyle.Sizable;
815                                 } else {
816                                         border_style = FormBorderStyle.FixedSingle;
817                                 }
818                         } else {
819                                 border_style = FormBorderStyle.Fixed3D;
820                         }
821
822                         WindowRect = Hwnd.GetWindowRectangle(border_style, MenuHandle, title_style, ClientRect);
823
824                         return true;
825                 }
826                 
827                 internal override void ClientToScreen(IntPtr handle, ref int x, ref int y) {
828                         CGPoint pt = new CGPoint ();
829                         Rect wBounds = new Rect ();
830                         Hwnd    hwnd;
831
832                         hwnd = Hwnd.ObjectFromHandle(handle);
833
834                         pt.x = x;
835                         pt.y = y;
836
837                         GetWindowBounds (GetControlOwner (hwnd.client_window), 32, ref wBounds);
838                         HIViewConvertPoint (ref pt, handle, IntPtr.Zero);
839
840                         x = (int)(pt.x+wBounds.left);
841                         y = (int)(pt.y+wBounds.top);
842                 }
843
844                 internal override int[] ClipboardAvailableFormats(IntPtr handle) {
845                         return null;
846                 }
847
848                 internal override void ClipboardClose(IntPtr handle) {
849                         throw new NotImplementedException();
850                 }
851
852                 internal override int ClipboardGetID(IntPtr handle, string format) {
853                         return 0;
854                 }
855
856                 internal override IntPtr ClipboardOpen() {
857                         throw new NotImplementedException();
858                 }
859
860                 internal override object ClipboardRetrieve(IntPtr handle, int id, XplatUI.ClipboardToObject converter) {
861                         throw new NotImplementedException();
862                 }
863
864                 internal override void ClipboardStore(IntPtr handle, object obj, int type, XplatUI.ObjectToClipboard converter) {
865                         throw new NotImplementedException();
866                 }
867                 
868                 internal override void CreateCaret (IntPtr hwnd, int width, int height) {
869                         if (Caret.Hwnd != IntPtr.Zero)
870                                 DestroyCaret (Caret.Hwnd);
871
872                         Caret.Hwnd = hwnd;
873                         Caret.Width = width;
874                         Caret.Height = height;
875                         Caret.Visible = 0;
876                         Caret.On = false;
877                 }
878                 
879                 internal override IntPtr CreateWindow(CreateParams cp) {
880                         IntPtr windowHnd = IntPtr.Zero;
881                         IntPtr parentHnd = cp.Parent;
882                         bool realWindow = false;
883                         Rectangle clientRect;
884                         Hwnd hwnd = new Hwnd ();
885                         
886                         SetHwndStyles (hwnd, cp);
887                         
888                         if (parentHnd == IntPtr.Zero) {
889                                 if ((cp.Style & (int)(WindowStyles.WS_CHILD))!=0) {
890                                         // This is a child view that is going to be parentless;
891                                         realWindow = false;
892                                         CheckError (HIViewFindByID (HIViewGetRoot (FosterParent), new HIViewID (OSXConstants.kEventClassWindow, 1), ref parentHnd), "HIViewFindByID ()");
893                                 } else if ((cp.Style & (int)(WindowStyles.WS_POPUP))!=0) {
894                                         // This is a popup window that will be real.
895                                         if (cp.X < 1) cp.X = 0;
896                                         if (cp.Y < 1) cp.Y = 0;
897                                         realWindow = true;
898                                 } else {
899                                         // This is a real root window too
900                                         if (cp.X < 1) cp.X = 0;
901                                         if (cp.Y < 1) cp.Y = 0;
902                                         realWindow = true;
903                                 }
904                         } else {
905                                 realWindow = false;
906                         }
907
908                         if (realWindow) {
909                                 WindowClass windowklass = WindowClass.kOverlayWindowClass;
910                                 WindowAttributes attributes = WindowAttributes.kWindowCompositingAttribute | WindowAttributes.kWindowStandardHandlerAttribute;
911                                 if ((cp.Style & ((int)WindowStyles.WS_MINIMIZEBOX)) != 0) { 
912                                         attributes |= WindowAttributes.kWindowCollapseBoxAttribute;
913                                 }
914                                 if ((cp.Style & ((int)WindowStyles.WS_MAXIMIZEBOX)) != 0) {
915                                         attributes |= WindowAttributes.kWindowResizableAttribute | WindowAttributes.kWindowHorizontalZoomAttribute | WindowAttributes.kWindowVerticalZoomAttribute;
916                                 }
917                                 if ((cp.Style & ((int)WindowStyles.WS_SYSMENU)) != 0) {
918                                         attributes |= WindowAttributes.kWindowCloseBoxAttribute;
919                                 }
920                                 if ((cp.ExStyle & ((int)WindowStyles.WS_EX_TOOLWINDOW)) != 0) {
921                                         attributes = WindowAttributes.kWindowStandardHandlerAttribute | WindowAttributes.kWindowCompositingAttribute;
922                                 }
923                                 if ((cp.Style & ((int)WindowStyles.WS_CAPTION)) != 0) {
924                                         windowklass = WindowClass.kDocumentWindowClass;
925                                 }
926                                         
927                                 IntPtr rect = IntPtr.Zero;
928                                 IntPtr viewHnd = IntPtr.Zero;
929                                 SetRect (ref rect, (short)cp.X, (short)(cp.Y + MenuBarHeight + TitleBarHeight), (short)(cp.Width+cp.X), (short)(cp.Height+cp.Y+MenuBarHeight+TitleBarHeight));
930                                 CheckError (CreateNewWindow (windowklass, attributes, ref rect, ref windowHnd), "CreateNewWindow ()");
931
932                                 CheckError (InstallEventHandler (GetWindowEventTarget (windowHnd), CarbonEventHandler, (uint)windowEvents.Length, windowEvents, windowHnd, IntPtr.Zero), "InstallEventHandler ()");
933                                 CheckError (HIViewFindByID (HIViewGetRoot (windowHnd), new HIViewID (OSXConstants.kEventClassWindow, 1), ref viewHnd), "HIViewFindByID ()");
934                                 parentHnd = viewHnd;
935                         }
936                         hwnd.X = cp.X;
937                         hwnd.Y = cp.Y;
938                         hwnd.Width = cp.Width;
939                         hwnd.Height = cp.Height;
940                         hwnd.Parent = Hwnd.ObjectFromHandle (cp.Parent);
941                         hwnd.visible = false;
942                         clientRect = hwnd.ClientRect;
943                         
944                         HIRect r = new HIRect (0, 0, cp.Width, cp.Height);
945                         CheckError (HIObjectCreate (__CFStringMakeConstantString ("com.apple.hiview"), 0, ref hwnd.whole_window), "HIObjectCreate ()");
946                         CheckError (InstallEventHandler (GetControlEventTarget (hwnd.whole_window), CarbonEventHandler, (uint)viewEvents.Length, viewEvents, hwnd.whole_window, IntPtr.Zero), "InstallEventHandler ()");
947                         CheckError (HIViewChangeFeatures (hwnd.whole_window, 1 << 1, 0), "HIViewChangeFeatures ()");
948                         CheckError (HIViewSetFrame (hwnd.whole_window, ref r), "HIViewSetFrame ()");
949                         hwnd.WholeWindow = hwnd.whole_window;
950                         
951                         r = new HIRect (0, 0, clientRect.Width, clientRect.Height);
952                         CheckError (HIObjectCreate (__CFStringMakeConstantString ("com.apple.hiview"), 0, ref hwnd.client_window), "HIObjectCreate ()");
953                         CheckError (InstallEventHandler (GetControlEventTarget (hwnd.client_window), CarbonEventHandler, (uint)viewEvents.Length, viewEvents, hwnd.client_window, IntPtr.Zero), "InstallEventHandler ()");
954                         CheckError (HIViewChangeFeatures (hwnd.client_window, 1 << 1, 0), "HIViewChangeFeatures ()");
955                         CheckError (HIViewSetFrame (hwnd.client_window, ref r), "HIViewSetFrame ()");
956                         hwnd.ClientWindow = hwnd.client_window;
957                         
958                         CheckError (HIViewAddSubview (hwnd.whole_window, hwnd.client_window));
959                         CheckError (HIViewPlaceInSuperviewAt (hwnd.client_window, clientRect.X, clientRect.Y));
960                         
961                         if (parentHnd != IntPtr.Zero && parentHnd != hwnd.WholeWindow) {
962                                 CheckError (HIViewAddSubview (parentHnd, hwnd.whole_window), "HIViewAddSubview ()");
963                                 CheckError (HIViewPlaceInSuperviewAt (hwnd.whole_window, cp.X, cp.Y), "HIPlaceInSuperviewAt ()");
964                                 if ((cp.Style & (int)(WindowStyles.WS_VISIBLE))!=0) {
965                                         CheckError (HIViewSetVisible (hwnd.whole_window, true), "HIViewSetVisible ()");
966                                         CheckError (HIViewSetVisible (hwnd.client_window, true), "HIViewSetVisible ()");
967                                         hwnd.visible = true;
968                                 } else {
969                                         CheckError (HIViewSetVisible (hwnd.whole_window, false), "HIViewSetVisible ()");
970                                         CheckError (HIViewSetVisible (hwnd.client_window, false), "HIViewSetVisible ()");
971                                         hwnd.visible = false;
972                                 }
973                         }
974                         if (realWindow) {
975                                 WindowMapping [hwnd.Handle] = windowHnd;
976                                 if ((cp.Style & (int)(WindowStyles.WS_VISIBLE))!=0) {
977                                         CheckError (ShowWindow (windowHnd));
978                                         CheckError (HIViewSetVisible (hwnd.whole_window, true), "HIViewSetVisible ()");
979                                         CheckError (HIViewSetVisible (hwnd.client_window, true), "HIViewSetVisible ()");
980                                         hwnd.visible = true;
981                                 }
982                                 if ((cp.Style & (int)(WindowStyles.WS_POPUP))!=0) {
983                                         CheckError (HIViewSetVisible (hwnd.whole_window, true), "HIViewSetVisible ()");
984                                         CheckError (HIViewSetVisible (hwnd.client_window, true), "HIViewSetVisible ()");
985                                         hwnd.visible = true;
986                                 }
987                         }       
988                         
989                         return hwnd.Handle;
990                 }
991
992                 internal override IntPtr CreateWindow(IntPtr Parent, int X, int Y, int Width, int Height) {
993                         CreateParams create_params = new CreateParams();
994
995                         create_params.Caption = "";
996                         create_params.X = X;
997                         create_params.Y = Y;
998                         create_params.Width = Width;
999                         create_params.Height = Height;
1000
1001                         create_params.ClassName=XplatUI.DefaultClassName;
1002                         create_params.ClassStyle = 0;
1003                         create_params.ExStyle=0;
1004                         create_params.Parent=IntPtr.Zero;
1005                         create_params.Param=0;
1006
1007                         return CreateWindow(create_params);
1008                 }
1009
1010                 [MonoTODO]
1011                 internal override IntPtr DefineCursor(Bitmap bitmap, Bitmap mask, Color cursor_pixel, Color mask_pixel, int xHotSpot, int yHotSpot) {
1012                         throw new NotImplementedException ();
1013                 }
1014                 
1015                 [MonoTODO]
1016                 internal override IntPtr DefineStdCursor(StdCursor id) {
1017                         switch (id) {
1018                                 case StdCursor.AppStarting:
1019                                         return (IntPtr)ThemeCursor.kThemeSpinningCursor;
1020                                 case StdCursor.Arrow:
1021                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1022                                 case StdCursor.Cross:
1023                                         return (IntPtr)ThemeCursor.kThemeCrossCursor;
1024                                 case StdCursor.Default:
1025                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1026                                 case StdCursor.Hand:
1027                                         return (IntPtr)ThemeCursor.kThemeOpenHandCursor;
1028                                 case StdCursor.Help:
1029                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1030                                 case StdCursor.HSplit:
1031                                         return (IntPtr)ThemeCursor.kThemeResizeLeftRightCursor;
1032                                 case StdCursor.IBeam:
1033                                         return (IntPtr)ThemeCursor.kThemeIBeamCursor;
1034                                 case StdCursor.No:
1035                                         return (IntPtr)ThemeCursor.kThemeNotAllowedCursor;
1036                                 case StdCursor.NoMove2D:
1037                                         return (IntPtr)ThemeCursor.kThemeNotAllowedCursor;
1038                                 case StdCursor.NoMoveHoriz:
1039                                         return (IntPtr)ThemeCursor.kThemeNotAllowedCursor;
1040                                 case StdCursor.NoMoveVert:
1041                                         return (IntPtr)ThemeCursor.kThemeNotAllowedCursor;
1042                                 case StdCursor.PanEast:
1043                                         return (IntPtr)ThemeCursor.kThemeResizeRightCursor;
1044                                 case StdCursor.PanNE:
1045                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1046                                 case StdCursor.PanNorth:
1047                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1048                                 case StdCursor.PanNW:
1049                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1050                                 case StdCursor.PanSE:
1051                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1052                                 case StdCursor.PanSouth:
1053                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1054                                 case StdCursor.PanSW:
1055                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1056                                 case StdCursor.PanWest:
1057                                         return (IntPtr)ThemeCursor.kThemeResizeLeftCursor;
1058                                 case StdCursor.SizeAll:
1059                                         return (IntPtr)ThemeCursor.kThemeResizeLeftRightCursor;
1060                                 case StdCursor.SizeNESW:
1061                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1062                                 case StdCursor.SizeNS:
1063                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1064                                 case StdCursor.SizeNWSE:
1065                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1066                                 case StdCursor.SizeWE:
1067                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1068                                 case StdCursor.UpArrow:
1069                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1070                                 case StdCursor.VSplit:
1071                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1072                                 case StdCursor.WaitCursor:
1073                                         return (IntPtr)ThemeCursor.kThemeSpinningCursor;
1074                                 default:
1075                                         return (IntPtr)ThemeCursor.kThemeArrowCursor;
1076                         }
1077                 }
1078                 
1079                 internal override IntPtr DefWndProc(ref Message msg) {
1080                         Hwnd hwnd = Hwnd.ObjectFromHandle (msg.HWnd);
1081                         switch ((Msg)msg.Msg) {
1082                                 case Msg.WM_DESTROY: {
1083                                         if (WindowMapping [hwnd.Handle] != null)
1084
1085                                                 XplatUI.Exit ();
1086                                         break;
1087                                 }
1088                         }
1089                         return IntPtr.Zero;
1090                 }
1091
1092                 internal override void DestroyCaret (IntPtr hwnd) {
1093                         if (Caret.Hwnd == hwnd) {
1094                                 if (Caret.Visible == 1) {
1095                                         Caret.Timer.Stop ();
1096                                         HideCaret ();
1097                                 }
1098                                 Caret.Hwnd = IntPtr.Zero;
1099                                 Caret.Visible = 0;
1100                                 Caret.On = false;
1101                         }
1102                 }
1103                 
1104                 [MonoTODO]
1105                 internal override void DestroyCursor(IntPtr cursor) {
1106                         throw new NotImplementedException ();
1107                 }
1108         
1109                 internal override void DestroyWindow(IntPtr handle) {
1110                         Hwnd    hwnd;
1111
1112                         hwnd = Hwnd.ObjectFromHandle(handle);
1113                         
1114                         if ((hwnd.whole_window != IntPtr.Zero) && HIViewGetSuperview (hwnd.whole_window) != IntPtr.Zero)
1115                                 CheckError (HIViewRemoveFromSuperview (handle), "HIViewRemoveFromSuperview ()");
1116
1117                         if (WindowMapping [hwnd.Handle] != null) {
1118                                 DisposeWindow ((IntPtr)(WindowMapping [hwnd.Handle]));
1119                         }
1120                         CFRelease (hwnd.ClientWindow);
1121                         CFRelease (hwnd.WholeWindow);
1122                 }
1123
1124                 internal override IntPtr DispatchMessage(ref MSG msg) {
1125                         return NativeWindow.WndProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
1126                 }
1127                 
1128                 internal override void DoEvents() {
1129                 }
1130
1131                 internal override void EnableWindow(IntPtr handle, bool Enable) {
1132                         //Like X11 we need not do anything here
1133                 }
1134
1135                 internal override void Exit() {
1136                         GetMessageResult = false;
1137                         ExitToShell ();
1138                 }
1139                 
1140                 internal override IntPtr GetActive() {
1141                         foreach (DictionaryEntry entry in WindowMapping)
1142                                 if (IsWindowActive ((IntPtr)(entry.Value)))
1143                                         return (IntPtr)(entry.Key);
1144
1145                         return IntPtr.Zero;
1146                 }
1147                 
1148                 [MonoTODO]
1149                 internal override void GetCursorInfo(IntPtr cursor, out int width, out int height, out int hotspot_x, out int hotspot_y) {
1150                         throw new NotImplementedException ();
1151                 }
1152                 
1153                 internal override void GetDisplaySize(out Size size) {
1154                         HIRect bounds = CGDisplayBounds (CGMainDisplayID ());
1155                         size = new Size ((int)bounds.size.width, (int)bounds.size.height);
1156                 }
1157
1158                 internal override IntPtr GetParent(IntPtr handle) {
1159                         Hwnd    hwnd;
1160
1161                         hwnd = Hwnd.ObjectFromHandle(handle);
1162                         if (hwnd != null && hwnd.parent != null) {
1163                                 return hwnd.parent.Handle;
1164                         }
1165                         return IntPtr.Zero;
1166                 }
1167                 
1168                 internal override void GetCursorPos(IntPtr handle, out int x, out int y) {
1169                         QDPoint pt = new QDPoint ();
1170                         GetGlobalMouse (ref pt);
1171                         x = pt.x;
1172                         y = pt.y;
1173                 }
1174                 
1175                 internal override bool GetFontMetrics(Graphics g, Font font, out int ascent, out int descent) {
1176                         return GetFontMetrics(g.GetHdc(), font.ToHfont(), out ascent, out descent);
1177                 }
1178                 
1179                 [MonoTODO]
1180                 internal override Graphics GetMenuDC(IntPtr hwnd, IntPtr ncpaint_region) {
1181                         throw new NotImplementedException();
1182                 }
1183                 
1184                 [MonoTODO]
1185                 internal override Point GetMenuOrigin(IntPtr hwnd) {
1186                         throw new NotImplementedException();
1187                 }
1188
1189                 internal override bool GetMessage(ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax) {
1190                         IntPtr evtRef = IntPtr.Zero;
1191                         IntPtr target = GetEventDispatcherTarget();
1192                         CheckTimers (DateTime.Now);
1193                         ReceiveNextEvent (0, IntPtr.Zero, 0, true, ref evtRef);
1194                         if (evtRef != IntPtr.Zero && target != IntPtr.Zero) {
1195                                 SendEventToEventTarget (evtRef, target);
1196                                 ReleaseEvent (evtRef);
1197                         }
1198                         
1199                         lock (MessageQueue) {
1200                                 if (MessageQueue.Count <= 0) {
1201                                         if (Idle != null) 
1202                                                 Idle (this, EventArgs.Empty);
1203                                         else if (TimerList.Count == 0) {
1204                                                 ReceiveNextEvent (0, IntPtr.Zero, Convert.ToDouble ("0." + Timer.Minimum), true, ref evtRef);
1205                                                 if (evtRef != IntPtr.Zero && target != IntPtr.Zero) {
1206                                                         SendEventToEventTarget (evtRef, target);
1207                                                         ReleaseEvent (evtRef);
1208                                                 }
1209                                         } else {
1210                                                 ReceiveNextEvent (0, IntPtr.Zero, NextTimeout (), true, ref evtRef);
1211                                                 if (evtRef != IntPtr.Zero && target != IntPtr.Zero) {
1212                                                         SendEventToEventTarget (evtRef, target);
1213                                                         ReleaseEvent (evtRef);
1214                                                 }
1215                                         }
1216                                         msg.hwnd = IntPtr.Zero;
1217                                         msg.message = Msg.WM_ENTERIDLE;
1218                                         return GetMessageResult;
1219                                 }
1220                                 msg = (MSG) MessageQueue.Dequeue ();
1221                         }
1222                         return GetMessageResult;
1223                 }
1224                 
1225                 [MonoTODO]
1226                 internal override bool GetText(IntPtr handle, out string text) {
1227                         throw new NotImplementedException ();
1228                 }
1229                 
1230                 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) {
1231                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1232                         Rectangle rect = hwnd.ClientRect;
1233                         
1234                         x = hwnd.x;
1235                         y = hwnd.y;
1236                         width = hwnd.width;
1237                         height = hwnd.height;
1238
1239                         client_width = rect.Width;
1240                         client_height = rect.Height;
1241                 }
1242                 
1243                 internal override FormWindowState GetWindowState(IntPtr hwnd) {
1244                         IntPtr window = GetControlOwner (hwnd);
1245
1246                         if (IsWindowCollapsed (window))
1247                                 return FormWindowState.Minimized;
1248                         if (IsWindowInStandardState (window, IntPtr.Zero, IntPtr.Zero))
1249                                 return FormWindowState.Maximized;
1250
1251                         return FormWindowState.Normal;
1252                 }
1253                 
1254                 internal override void GrabInfo(out IntPtr handle, out bool GrabConfined, out Rectangle GrabArea) {
1255                         handle = Grab.Hwnd;
1256                         GrabConfined = Grab.Confined;
1257                         GrabArea = Grab.Area;
1258                 }
1259                 
1260                 internal override void GrabWindow(IntPtr handle, IntPtr confine_to_handle) {
1261                         GrabWindowHwnd = Hwnd.ObjectFromHandle (handle);
1262                 }
1263                 
1264                 internal override void UngrabWindow(IntPtr hwnd) {
1265                         GrabWindowHwnd = null;
1266                         Grab.Hwnd = IntPtr.Zero;
1267                         Grab.Confined = false;
1268                 }
1269                 
1270                 internal override void HandleException(Exception e) {
1271                         StackTrace st = new StackTrace(e);
1272                         Console.WriteLine("Exception '{0}'", e.Message+st.ToString());
1273                         Console.WriteLine("{0}{1}", e.Message, st.ToString());
1274                 }
1275                 
1276                 internal override void Invalidate (IntPtr handle, Rectangle rc, bool clear) {
1277                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1278                         
1279                         if (hwnd.visible && HIViewIsVisible (handle)) {
1280                                 MSG msg = new MSG ();
1281                                 msg.hwnd = hwnd.Handle;
1282                                 msg.wParam = IntPtr.Zero;
1283                                 msg.lParam = IntPtr.Zero;
1284                                 msg.message = Msg.WM_PAINT;
1285                                 MessageQueue.Enqueue (msg);
1286                                 // This is currently causing some graphics corruption
1287                                 //hwnd.AddInvalidArea (rc.X, rc.Y, rc.Width, rc.Height);
1288                                 hwnd.AddInvalidArea (0, 0, hwnd.ClientRect.Width, hwnd.ClientRect.Height);
1289                                 hwnd.expose_pending = true;
1290                         }
1291                 }
1292                 
1293                 internal override bool IsVisible(IntPtr handle) {
1294                         return Hwnd.ObjectFromHandle(handle).visible;
1295                 }
1296                 
1297                 internal override void KillTimer(Timer timer) {
1298                         lock (TimerList) {
1299                                 TimerList.Remove(timer);
1300                         }
1301                 }
1302                 
1303                 internal override void MenuToScreen(IntPtr handle, ref int x, ref int y) {
1304                         CGPoint pt = new CGPoint ();
1305                         Rect wBounds = new Rect ();
1306                         Hwnd    hwnd;
1307
1308                         hwnd = Hwnd.ObjectFromHandle(handle);
1309
1310                         pt.x = x;
1311                         pt.y = y;
1312
1313                         GetWindowBounds (GetControlOwner (hwnd.whole_window), 32, ref wBounds);
1314                         HIViewConvertPoint (ref pt, handle, IntPtr.Zero);
1315
1316                         x = (int)(pt.x+wBounds.left);
1317                         y = (int)(pt.y+wBounds.top);
1318                 }
1319
1320                 [MonoTODO]
1321                 internal override void OverrideCursor(IntPtr cursor) {
1322                         throw new NotImplementedException ();
1323                 }
1324
1325                 internal override PaintEventArgs PaintEventStart(IntPtr handle, bool client) {
1326                         PaintEventArgs  paint_event;
1327                         Hwnd            hwnd;
1328
1329                         hwnd = Hwnd.ObjectFromHandle(handle);
1330
1331                         if (Caret.Visible == 1) {
1332                                 Caret.Paused = true;
1333                                 HideCaret();
1334                         }
1335
1336                         hwnd.client_dc  = Graphics.FromHwnd (hwnd.client_window);
1337                         paint_event = new PaintEventArgs(hwnd.client_dc, hwnd.invalid);
1338                         
1339                         return paint_event;
1340                 }
1341                 
1342                 internal override void PaintEventEnd(IntPtr handle, bool client) {
1343                         Hwnd    hwnd;
1344
1345                         hwnd = Hwnd.ObjectFromHandle(handle);
1346
1347                         hwnd.ClearInvalidArea();
1348
1349                         hwnd.client_dc.Flush();
1350                         hwnd.client_dc.Dispose();
1351                         hwnd.client_dc = null;
1352                         hwnd.expose_pending = false;
1353                         
1354                         if (Caret.Visible == 1) {
1355                                 ShowCaret();
1356                                 Caret.Paused = false;
1357                         }
1358                 }
1359                 
1360                 internal override bool PeekMessage(ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, uint flags) {
1361                         Console.WriteLine("XplatUIOSX.PeekMessage");
1362                         return true;
1363                 }
1364
1365                 public static void PostMessage (IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam) {
1366                         MSG msg = new MSG();
1367                         msg.hwnd = hwnd;
1368                         msg.message = message;
1369                         msg.wParam = wParam;
1370                         msg.lParam = lParam;
1371                         MessageQueue.Enqueue (msg);
1372                 }
1373                 
1374                 [MonoTODO]
1375                 internal override void ReleaseMenuDC(IntPtr hwnd, Graphics dc) {
1376                         throw new NotImplementedException();
1377                 }
1378                 
1379                 internal override void ScreenToClient(IntPtr handle, ref int x, ref int y) {
1380                         CGPoint pt = new CGPoint ();
1381                         Rect wBounds = new Rect ();
1382
1383                         GetWindowBounds (GetControlOwner (handle), 32, ref wBounds);
1384                         pt.x = (x-wBounds.left);
1385                         pt.y = (y-wBounds.top);
1386                         HIViewConvertPoint (ref pt, IntPtr.Zero, handle);
1387
1388                         x = (int)pt.x;
1389                         y = (int)pt.y;
1390                 }
1391
1392                 [MonoTODO]
1393                 internal override void ScreenToMenu(IntPtr handle, ref int x, ref int y) {
1394                         CGPoint pt = new CGPoint ();
1395                         Rect wBounds = new Rect ();
1396
1397                         GetWindowBounds (GetControlOwner (handle), 32, ref wBounds);
1398                         pt.x = (x-wBounds.left);
1399                         pt.y = (y-wBounds.top);
1400                         HIViewConvertPoint (ref pt, IntPtr.Zero, handle);
1401
1402                         x = (int)pt.x;
1403                         y = (int)pt.y;
1404                 }
1405
1406                 internal override void ScrollWindow(IntPtr handle, Rectangle area, int XAmount, int YAmount, bool clear) {
1407                         //IntPtr rect = IntPtr.Zero;
1408                         //HIRect vBounds = new HIRect ();
1409                    
1410             Hwnd hwnd = Hwnd.ObjectFromHandle(handle);
1411           
1412                         /*
1413                         if (hwnd.invalid != Rectangle.Empty) {
1414                                 // BIG FAT WARNING. This only works with how we use this function right now
1415                                 // where we basically still scroll the whole window, but work around areas
1416                                 // that are covered by our children
1417
1418                                 hwnd.invalid.X += XAmount;
1419                                 hwnd.invalid.Y += YAmount;
1420
1421                                 if (hwnd.invalid.X < 0) {
1422                                         hwnd.invalid.Width += hwnd.invalid.X;
1423                                         hwnd.invalid.X =0;
1424                                 }
1425
1426                                 if (hwnd.invalid.Y < 0) {
1427                                         hwnd.invalid.Height += hwnd.invalid.Y;
1428                                         hwnd.invalid.Y =0;
1429                                 }
1430                         }*/
1431                         
1432                         HIRect scrollrect = new HIRect ();
1433                         scrollrect.origin.x = area.X;
1434                         scrollrect.origin.y = area.Y;
1435                         scrollrect.size.width = area.Width;
1436                         scrollrect.size.height = area.Height;
1437                         HIViewScrollRect (hwnd.Handle, ref scrollrect, (float)XAmount, (float)-YAmount);
1438                         /*
1439             HIViewGetBounds (hwnd.client_window, ref vBounds);
1440                         HIViewConvertRect (ref vBounds, hwnd.client_window, IntPtr.Zero);
1441                         SetRect (ref rect, (short)(vBounds.origin.x+area.X), (short)(vBounds.origin.y-TitleBarHeight+area.Y), (short)(vBounds.origin.x+area.Width), (short)(vBounds.origin.y+area.Height-TitleBarHeight));
1442                         ScrollRect (ref rect, (short)XAmount, (short)-YAmount, IntPtr.Zero);
1443                         */
1444                         // Generate an expose for the area exposed by the horizontal scroll
1445                         /*
1446                         if (XAmount > 0) {
1447                                 hwnd.AddInvalidArea (area.X, area.Y, XAmount, area.Height);
1448                         } else if (XAmount < 0) {
1449                                 hwnd.AddInvalidArea (XAmount + area.X + area.Width, area.Y, -XAmount, area.Height);
1450                         }
1451
1452                         // Generate an expose for the area exposed by the vertical scroll
1453                         if (YAmount > 0) {
1454                                 hwnd.AddInvalidArea (area.X, area.Y, area.Width, YAmount);
1455                         } else if (YAmount < 0) {
1456                                 hwnd.AddInvalidArea (area.X, YAmount + area.Y + area.Height, area.Width, -YAmount);
1457                         }
1458                         
1459                         UpdateWindow (handle);
1460                         */
1461                 }
1462                 
1463                 
1464                 internal override void ScrollWindow(IntPtr hwnd, int XAmount, int YAmount, bool clear) {
1465                         throw new NotImplementedException("");
1466                 }
1467                 
1468                 [MonoTODO]
1469                 internal override void SendAsyncMethod (AsyncMethodData method) {
1470                         throw new NotImplementedException ();
1471                 }
1472                 
1473                 internal override void SetCaretPos (IntPtr hwnd, int x, int y) {
1474                         if (Caret.Hwnd == hwnd) {
1475                                 CGPoint cpt = new CGPoint ();
1476                                 cpt.x = x;
1477                                 cpt.y = y;
1478                                 HIViewConvertPoint (ref cpt, hwnd, IntPtr.Zero);
1479                                 Caret.Timer.Stop ();
1480                                 HideCaret ();
1481                                 Caret.X = (int)cpt.x;
1482                                 Caret.Y = (int)cpt.y-23;
1483                                 if (Caret.Visible == 1) {
1484                                         ShowCaret ();
1485                                         Caret.Timer.Start ();
1486                                 }
1487                         }
1488                 }
1489                 
1490                 internal override void SetCursor(IntPtr window, IntPtr cursor) {
1491                         SetThemeCursor ((uint) cursor);
1492                 }
1493                 
1494                 internal override void SetCursorPos(IntPtr handle, int x, int y) {
1495                         CGDisplayMoveCursorToPoint (CGMainDisplayID (), new CGPoint (x, y));
1496                 }
1497                 
1498                 internal override void SetFocus(IntPtr handle) {
1499                         if (FocusWindow != IntPtr.Zero) {
1500                                 PostMessage(FocusWindow, Msg.WM_KILLFOCUS, handle, IntPtr.Zero);
1501                         }
1502                         PostMessage(handle, Msg.WM_SETFOCUS, FocusWindow, IntPtr.Zero);
1503                         FocusWindow = handle;
1504                 }
1505
1506                 [MonoTODO]
1507                 internal override void SetIcon(IntPtr handle, Icon icon) {
1508                         throw new NotImplementedException();
1509                 }
1510
1511                 
1512                 internal override void SetModal(IntPtr handle, bool Modal) {
1513                         IntPtr hWnd = GetControlOwner (Hwnd.ObjectFromHandle (handle).WholeWindow);
1514                         if (Modal)
1515                                 BeginAppModalStateForWindow (hWnd);
1516                         else
1517                                 EndAppModalStateForWindow (hWnd);
1518                         return;
1519                 }
1520
1521                 internal override IntPtr SetParent(IntPtr handle, IntPtr parent) {
1522                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1523                         
1524                         hwnd.parent = Hwnd.ObjectFromHandle (parent);
1525                         if (HIViewGetSuperview (hwnd.whole_window) != IntPtr.Zero) {
1526                                 CheckError (HIViewRemoveFromSuperview (hwnd.whole_window), "HIViewRemoveFromSuperview ()");
1527                         }
1528                         CheckError (HIViewAddSubview (hwnd.parent.client_window, hwnd.whole_window));
1529                         CheckError (HIViewAddSubview (hwnd.whole_window, hwnd.client_window));
1530                         HIViewPlaceInSuperviewAt (hwnd.client_window, hwnd.ClientRect.X, hwnd.ClientRect.Y);
1531                         
1532                         return IntPtr.Zero;
1533                 }
1534                 
1535                 internal override void SetTimer (Timer timer) {
1536                         lock (TimerList) {
1537                                 TimerList.Add (timer);
1538                         }
1539                 }
1540                 
1541                 internal override bool SetTopmost(IntPtr hWnd, IntPtr hWndOwner, bool Enabled) {
1542                         HIViewSetZOrder (hWnd, 1, IntPtr.Zero);
1543                         return true;
1544                 }
1545                 
1546                 
1547                 internal override bool SetVisible(IntPtr handle, bool visible) {
1548                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1549                         object window = WindowMapping [hwnd.Handle];
1550                         if (window != null)
1551                                 if (visible)
1552                                         ShowWindow ((IntPtr)window);
1553                                 else
1554                                         HideWindow ((IntPtr)window);
1555                                         
1556                         HIViewSetVisible (hwnd.whole_window, visible);
1557                         HIViewSetVisible (hwnd.client_window, visible);
1558                         hwnd.visible = visible;
1559                         return true;
1560                 }
1561                 
1562                 internal override void SetBorderStyle(IntPtr handle, FormBorderStyle border_style) {
1563                         Hwnd    hwnd;
1564
1565                         hwnd = Hwnd.ObjectFromHandle(handle);
1566                         hwnd.border_style = border_style;
1567
1568                         // FIXME - do we need to trigger some resize?
1569                 }
1570
1571                 internal override void SetMenu(IntPtr handle, IntPtr menu_handle) {
1572                         Hwnd    hwnd;
1573
1574                         hwnd = Hwnd.ObjectFromHandle(handle);
1575                         hwnd.menu_handle = menu_handle;
1576
1577                         // FIXME - do we need to trigger some resize?
1578                 }
1579                 
1580                 internal override void SetWindowPos(IntPtr handle, int x, int y, int width, int height) {
1581                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1582                         Rectangle client_rect = Hwnd.GetClientRectangle(hwnd.border_style, hwnd.menu_handle, hwnd.title_style, width, height);
1583
1584                         // Save a server roundtrip (and prevent a feedback loop)
1585                         if ((hwnd.x == x) && (hwnd.y == y) && (hwnd.width == width) && (hwnd.height == height)) {
1586                                 return;
1587                         }
1588
1589
1590                         if (WindowMapping [hwnd.Handle] != null) {
1591                                 if (y <= MenuBarHeight+TitleBarHeight) {
1592                                         y+=MenuBarHeight+TitleBarHeight;
1593                                 }
1594                                 IntPtr rect = IntPtr.Zero;
1595                                 SetRect (ref rect, (short)x, (short)y, (short)(x+width), (short)(y+height));
1596                                 CheckError (SetWindowBounds ((IntPtr) WindowMapping [hwnd.Handle], 33, ref rect), "SetWindowBounds ()");
1597                                 HIRect r = new HIRect (0, 0, width, height);
1598                                 CheckError (HIViewSetFrame (hwnd.whole_window, ref r), "HIViewSetFrame ()");
1599                                 r = new HIRect (client_rect.X, client_rect.Y, client_rect.X+client_rect.Width, client_rect.Y+client_rect.Height);
1600                                 CheckError (HIViewSetFrame (hwnd.client_window, ref r), "HIViewSetFrame ()");
1601                         } else {
1602                                 HIRect r = new HIRect (x, y, width, height);
1603                                 CheckError (HIViewSetFrame (hwnd.whole_window, ref r), "HIViewSetFrame ()");
1604                                 r = new HIRect (client_rect.X, client_rect.Y, client_rect.X+client_rect.Width, client_rect.Y+client_rect.Height);
1605                                 CheckError (HIViewSetFrame (hwnd.client_window, ref r), "HIViewSetFrame ()");
1606                         }                       
1607                 }
1608                 
1609                 internal override void SetWindowState(IntPtr hwnd, FormWindowState state) {
1610                         IntPtr window = GetControlOwner (hwnd);
1611
1612                         switch (state) {
1613                                 case FormWindowState.Minimized: {
1614                                         CollapseWindow (window, true);
1615                                         break;
1616                                 }
1617                                 case FormWindowState.Normal: {
1618                                         ZoomWindow (window, 7, false);
1619                                         break;
1620                                 }
1621                                 case FormWindowState.Maximized: {
1622                                         ZoomWindow (window, 8, false);
1623                                         break;
1624                                 }
1625                         }
1626                 }
1627                 
1628                 internal override void SetWindowStyle(IntPtr handle, CreateParams cp) {
1629                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1630                         SetHwndStyles(hwnd, cp);
1631                         
1632                         if (WindowMapping [hwnd.Handle] != null) {
1633                                 WindowAttributes attributes = WindowAttributes.kWindowCompositingAttribute | WindowAttributes.kWindowStandardHandlerAttribute;
1634                                 if ((cp.Style & ((int)WindowStyles.WS_MINIMIZEBOX)) != 0) { 
1635                                         attributes |= WindowAttributes.kWindowCollapseBoxAttribute;
1636                                 }
1637                                 if ((cp.Style & ((int)WindowStyles.WS_MAXIMIZEBOX)) != 0) {
1638                                         attributes |= WindowAttributes.kWindowResizableAttribute | WindowAttributes.kWindowHorizontalZoomAttribute | WindowAttributes.kWindowVerticalZoomAttribute;
1639                                 }
1640                                 if ((cp.Style & ((int)WindowStyles.WS_SYSMENU)) != 0) {
1641                                         attributes |= WindowAttributes.kWindowCloseBoxAttribute;
1642                                 }
1643                                 if ((cp.ExStyle & ((int)WindowStyles.WS_EX_TOOLWINDOW)) != 0) {
1644                                         attributes = WindowAttributes.kWindowStandardHandlerAttribute | WindowAttributes.kWindowCompositingAttribute;
1645                                 }
1646
1647                                 WindowAttributes outAttributes = WindowAttributes.kWindowNoAttributes;
1648                                 GetWindowAttributes ((IntPtr)WindowMapping [hwnd.Handle], ref outAttributes);
1649                                 ChangeWindowAttributes ((IntPtr)WindowMapping [hwnd.Handle], attributes, outAttributes);
1650                         }
1651                 }
1652                 
1653                 internal override bool SetZOrder(IntPtr handle, IntPtr after_handle, bool Top, bool Bottom) {
1654                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1655                         
1656                         if (Top) {
1657                                 HIViewSetZOrder (hwnd.whole_window, 2, IntPtr.Zero);
1658                                 return true;
1659                         } else if (!Bottom) {
1660                                 Hwnd after_hwnd = Hwnd.ObjectFromHandle (after_handle);
1661                                 HIViewSetZOrder (hwnd.whole_window, 2, after_hwnd.whole_window);
1662                         } else {
1663                                 HIViewSetZOrder (hwnd.whole_window, 1, IntPtr.Zero);
1664                                 return true;
1665                         }
1666                         return false;
1667                 }
1668
1669                 internal override void ShowCursor(bool show) {
1670                         if (show)
1671                                 CGDisplayShowCursor (CGMainDisplayID ());
1672                         else
1673                                 CGDisplayHideCursor (CGMainDisplayID ());
1674                 }
1675                 
1676                 [MonoTODO]
1677                 internal override bool SystrayAdd(IntPtr hwnd, string tip, Icon icon, out ToolTip tt) {
1678                         throw new NotImplementedException();
1679                 }
1680
1681                 [MonoTODO]
1682                 internal override bool SystrayChange(IntPtr hwnd, string tip, Icon icon, ref ToolTip tt) {
1683                         throw new NotImplementedException();
1684                 }
1685
1686                 [MonoTODO]
1687                 internal override void SystrayRemove(IntPtr hwnd, ref ToolTip tt) {
1688                         throw new NotImplementedException();
1689                 }
1690                 
1691                 internal override bool Text(IntPtr handle, string text) {
1692                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1693                         if (WindowMapping [hwnd.Handle] != null) {
1694                                 CheckError (SetWindowTitleWithCFString ((IntPtr)(WindowMapping [hwnd.Handle]), __CFStringMakeConstantString (text)));
1695                         }
1696                         CheckError (SetControlTitleWithCFString (hwnd.whole_window, __CFStringMakeConstantString (text)));
1697                         CheckError (SetControlTitleWithCFString (hwnd.client_window, __CFStringMakeConstantString (text)));
1698                         return true;
1699                 }
1700                 
1701                 internal override void UpdateWindow(IntPtr handle) {
1702                         Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
1703                         
1704                         if (hwnd.visible && HIViewIsVisible (handle) && !hwnd.expose_pending) {
1705                                 MSG msg = new MSG ();
1706                                 msg.message = Msg.WM_PAINT;
1707                                 msg.hwnd = hwnd.Handle;
1708                                 msg.lParam = IntPtr.Zero;
1709                                 msg.wParam = IntPtr.Zero;
1710                                 MessageQueue.Enqueue (msg);
1711                         }
1712                 }
1713                 
1714                 internal override bool TranslateMessage(ref MSG msg) {
1715                         bool res = false;
1716                         Hwnd hwnd = Hwnd.ObjectFromHandle (msg.hwnd);
1717                                         
1718                         switch (msg.message) {
1719                                 case Msg.WM_MOUSEMOVE: {
1720                                         // We're grabbed
1721                                         if (GrabWindowHwnd != null) {
1722                                                 if (GrabWindowHwnd.Handle != hwnd.Handle) {
1723                                                         return false;
1724                                                 }
1725                                         } else {
1726                                                 if (MouseWindow != null) {
1727                                                         if (MouseWindow.Handle != hwnd.Handle) {
1728                                                                 PostMessage (MouseWindow.Handle, Msg.WM_MOUSE_LEAVE, IntPtr.Zero, IntPtr.Zero);
1729                                                                 PostMessage (hwnd.Handle, Msg.WM_MOUSE_ENTER, IntPtr.Zero, IntPtr.Zero);
1730                                                                 MouseWindow = hwnd;
1731                                                         }
1732                                                 } else {
1733                                                         MouseWindow = hwnd;
1734                                                 }
1735                                         }
1736                                         break;
1737                                 }
1738                                 case Msg.WM_SETFOCUS: {
1739                                         break;   
1740                                 }                                       
1741                                 
1742                         }
1743                         
1744                         // This is a hideous temporary keyboard hack to bind some keys  
1745                         if (msg.message >= Msg.WM_KEYFIRST && msg.message <= Msg.WM_KEYLAST)
1746                                 res = true;
1747
1748                         if (msg.message != Msg.WM_KEYDOWN && msg.message != Msg.WM_SYSKEYDOWN)
1749                                 return res;
1750
1751                         if ((int)msg.wParam >= (int)'0' && (int)msg.wParam <= (int)'z') {
1752                                 Msg message;
1753                                 message = Msg.WM_CHAR;
1754                                 PostMessage (msg.hwnd, message, msg.wParam, msg.lParam);
1755                         }
1756                         return true;
1757                 }
1758                 
1759                 internal override void DrawReversibleRectangle(IntPtr handle, Rectangle rect, int line_width) {
1760                         throw new NotImplementedException();
1761                 }
1762
1763                 [MonoTODO]
1764                 internal override SizeF GetAutoScaleSize(Font font) {
1765                         throw new NotImplementedException();
1766                 }
1767                 #endregion
1768                 
1769                 #region System information
1770                 internal override int KeyboardSpeed { get{ throw new NotImplementedException(); } } 
1771                 internal override int KeyboardDelay { get{ throw new NotImplementedException(); } } 
1772
1773                 internal override  int Caption { get{ throw new NotImplementedException(); } }
1774                 internal override  Size CursorSize { get{ throw new NotImplementedException(); } }
1775                 internal override  bool DragFullWindows { get{ throw new NotImplementedException(); } }
1776                 internal override  Size DragSize { get{ throw new NotImplementedException(); } }
1777                 internal override  Size FrameBorderSize { get{ throw new NotImplementedException(); } }
1778                 internal override  Size IconSize { get{ throw new NotImplementedException(); } }
1779                 internal override  Size MaxWindowTrackSize { get{ throw new NotImplementedException(); } }
1780                 internal override  Size MinimizedWindowSize { get{ throw new NotImplementedException(); } }
1781                 internal override  Size MinimizedWindowSpacingSize { get{ throw new NotImplementedException(); } }
1782                 internal override  Size MinimumWindowSize { get{ throw new NotImplementedException(); } }
1783                 internal override  Size MinWindowTrackSize { get{ throw new NotImplementedException(); } }
1784                 internal override  Size SmallIconSize { get{ throw new NotImplementedException(); } }
1785                 internal override  int MouseButtonCount { get{ throw new NotImplementedException(); } }
1786                 internal override  bool MouseButtonsSwapped { get{ throw new NotImplementedException(); } }
1787                 internal override  bool MouseWheelPresent { get{ throw new NotImplementedException(); } }
1788                 internal override  Rectangle VirtualScreen { get{ throw new NotImplementedException(); } }
1789                 internal override  Rectangle WorkingArea { 
1790                         get { 
1791                                 HIRect bounds = CGDisplayBounds (CGMainDisplayID ());
1792                                 return new Rectangle ((int)bounds.origin.x, (int)bounds.origin.y, (int)bounds.size.width, (int)bounds.size.height);
1793                         }
1794                 }
1795                 #endregion
1796                 
1797                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1798                 internal static extern int HIViewSetNeedsDisplayInRegion (IntPtr view, IntPtr rgn, bool needsDisplay);
1799                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1800                 internal static extern int HIViewGetSubviewHit (IntPtr contentView, ref CGPoint point, bool tval, ref IntPtr outPtr);
1801                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1802                 internal static extern int HIViewGetViewForMouseEvent (IntPtr inView, IntPtr inEvent, ref IntPtr outView);
1803                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1804                 internal static extern int HIViewConvertPoint (ref CGPoint point, IntPtr pView, IntPtr cView);
1805                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1806                 internal static extern int HIViewChangeFeatures (IntPtr aView, ulong bitsin, ulong bitsout);
1807                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1808                 internal static extern int HIViewFindByID (IntPtr rootWnd, HIViewID id, ref IntPtr outPtr);
1809                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1810                 internal static extern IntPtr HIViewGetRoot (IntPtr hWnd);
1811                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1812                 internal static extern int HIObjectCreate (IntPtr cfStr, uint what, ref IntPtr hwnd);
1813                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1814                 internal static extern int HIViewSetNeedsDisplay (IntPtr viewHnd, bool update);
1815                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1816                 internal static extern int HIViewGetFrame (IntPtr viewHnd, ref HIRect rect);
1817                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1818                 internal static extern int HIViewSetFrame (IntPtr viewHnd, ref HIRect rect);
1819                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1820                 internal static extern int HIViewPlaceInSuperviewAt (IntPtr view, float x, float y);
1821                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1822                 internal static extern int HIViewAddSubview (IntPtr parentHnd, IntPtr childHnd);
1823                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1824                 internal static extern IntPtr HIViewGetNextView (IntPtr aView);
1825                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1826                 internal static extern IntPtr HIViewGetPreviousView (IntPtr aView);
1827                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1828                 internal static extern IntPtr HIViewGetFirstSubview (IntPtr aView);
1829                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1830                 internal static extern IntPtr HIViewGetSuperview (IntPtr aView);
1831                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1832                 internal static extern int HIViewRemoveFromSuperview (IntPtr aView);
1833                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1834                 internal static extern int HIViewSetVisible (IntPtr vHnd, bool visible);
1835                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1836                 internal static extern bool HIViewIsVisible (IntPtr vHnd);
1837                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1838                 internal static extern int HIViewGetBounds (IntPtr vHnd, ref HIRect r);
1839                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1840                 internal static extern int HIViewScrollRect (IntPtr vHnd, ref HIRect rect, float x, float y);
1841                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1842                 internal static extern int HIViewScrollRect (IntPtr vHnd, IntPtr rect, float x, float y);
1843                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1844                 internal static extern int HIViewSetZOrder (IntPtr hWnd, int cmd, IntPtr oHnd);
1845                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1846                 internal static extern int HIViewSetBoundsOrigin (IntPtr vHnd, float x, float y);
1847                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1848                 internal static extern int HIViewConvertRect (ref HIRect r, IntPtr a, IntPtr b);
1849                 
1850                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1851                 internal static extern void ScrollRect (ref IntPtr r, short dh, short dv, IntPtr rgnHandle);
1852                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1853                 internal static extern void SetRect (ref IntPtr r, short left, short top, short right, short bottom);
1854
1855                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1856                 static extern int CreateEvent (IntPtr allocator, uint classid, uint kind, double when, uint attributes, ref IntPtr outEvent);
1857                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1858                 static extern int InstallEventHandler (IntPtr window, CarbonEventDelegate handlerProc, uint numtypes, EventTypeSpec [] typeList, IntPtr userData, IntPtr handlerRef);
1859                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1860                 internal static extern IntPtr GetControlOwner (IntPtr aView);
1861                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1862                 static extern int ActivateWindow (IntPtr windowHnd, bool inActivate);
1863                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1864                 static extern bool IsWindowActive (IntPtr windowHnd);
1865                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1866                 static extern int SetKeyboardFocus (IntPtr windowHdn, IntPtr cntrlHnd, short partcode);
1867                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1868                 static extern int GetKeyboardFocus (IntPtr handle, ref IntPtr cntrl);
1869
1870                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1871                 internal static extern IntPtr GetWindowEventTarget (IntPtr window);
1872                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1873                 internal static extern IntPtr GetControlEventTarget (IntPtr aControl);
1874                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1875                 internal static extern IntPtr GetEventDispatcherTarget ();
1876                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1877                 internal static extern int SendEventToEventTarget (IntPtr evt, IntPtr target);
1878                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1879                 internal static extern int ReleaseEvent (IntPtr evt);
1880                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1881                 internal static extern int ReceiveNextEvent (uint evtCount, IntPtr evtTypes, double timeout, bool processEvt, ref IntPtr evt);
1882                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1883                 static extern uint GetEventClass (IntPtr eventRef);
1884                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1885                 static extern uint GetEventKind (IntPtr eventRef);
1886                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1887                 static extern int GetEventParameter (IntPtr evt, OSXConstants.EventParamName inName, OSXConstants.EventParamType inType, IntPtr outActualType, uint bufSize, IntPtr outActualSize, ref byte outData);
1888                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1889                 static extern int GetEventParameter (IntPtr evt, OSXConstants.EventParamName inName, OSXConstants.EventParamType inType, IntPtr outActualType, uint bufSize, IntPtr outActualSize, ref IntPtr outData);
1890                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1891                 static extern int GetEventParameter (IntPtr evt, OSXConstants.EventParamName inName, OSXConstants.EventParamType inType, IntPtr outActualType, uint bufSize, IntPtr outActualSize, ref ushort outData);
1892                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1893                 static extern int GetEventParameter (IntPtr evt, OSXConstants.EventParamName inName, OSXConstants.EventParamType inType, IntPtr outActualType, uint bufSize, IntPtr outActualSize, ref short outData);
1894                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1895                 static extern int GetEventParameter (IntPtr evt, OSXConstants.EventParamName inName, OSXConstants.EventParamType inType, IntPtr outActualType, uint bufSize, IntPtr outActualSize, ref QDPoint outData);
1896                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1897                 static extern int SetEventParameter (IntPtr evt, OSXConstants.EventParamName inName, OSXConstants.EventParamType inType, uint bufSize, ref short outData);
1898                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1899                 static extern int SetEventParameter (IntPtr evt, OSXConstants.EventParamName inName, OSXConstants.EventParamType inType, uint bufSize, ref IntPtr outData);
1900
1901                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1902                 internal static extern void CGContextFlush (IntPtr cgc);
1903                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1904                 internal static extern int CGContextFillRect (IntPtr cgc, HIRect r);
1905                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1906                 internal static extern CGAffineTransform CGContextGetTextMatrix (IntPtr cgContext);
1907                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1908                 internal static extern int CGContextSetTextMatrix (IntPtr cgContext, CGAffineTransform ctm);
1909                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1910                 internal static extern int CGContextSetRGBFillColor (IntPtr cgContext, float r, float g, float b, float alpha);
1911                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1912                 internal static extern int CGContextSetRGBStrokeColor (IntPtr cgContext, float r, float g, float b, float alpha);
1913                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1914                 internal static extern int CGContextSetTextDrawingMode (IntPtr cgContext, int drawingMode);
1915                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1916                 internal static extern int CGContextSelectFont (IntPtr cgContext, string fontName, float size, int textEncoding);
1917                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1918                 internal static extern int CGContextShowTextAtPoint (IntPtr cgContext, float x, float y, string text, int length);
1919                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1920                 internal static extern int CGContextClipToRect (IntPtr cgContext, HIRect clip);
1921                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1922                 internal static extern void CreateCGContextForPort (IntPtr port, ref IntPtr cgc);
1923                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1924                 internal static extern bool IsWindowCollapsed (IntPtr hWnd);
1925                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1926                 internal static extern bool IsWindowInStandardState (IntPtr hWnd, IntPtr a, IntPtr b);
1927                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1928                 internal static extern void CollapseWindow (IntPtr hWnd, bool collapse);
1929                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1930                 internal static extern void ZoomWindow (IntPtr hWnd, short partCode, bool front);
1931                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1932                 internal static extern int GetWindowAttributes (IntPtr hWnd, ref WindowAttributes outAttributes);
1933                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1934                 internal static extern int ChangeWindowAttributes (IntPtr hWnd, WindowAttributes inAttributes, WindowAttributes outAttributes);
1935                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1936                 internal static extern IntPtr GetWindowPort (IntPtr hWnd);
1937                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1938                 static extern int SetPortWindowPort (IntPtr hWnd);
1939                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1940                 static extern int GetGlobalMouse (ref QDPoint outData);
1941                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1942                 static extern int GlobalToLocal (ref QDPoint outData);
1943                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1944                 static extern int LocalToGlobal (ref QDPoint outData);
1945                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1946                 static extern int TrackControl (IntPtr handle, QDPoint point, IntPtr data);
1947                 
1948                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1949                 internal static extern int BeginAppModalStateForWindow (IntPtr window);
1950                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1951                 internal static extern int EndAppModalStateForWindow (IntPtr window);
1952                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1953                 internal static extern int CreateNewWindow (WindowClass klass, WindowAttributes attributes, ref IntPtr r, ref IntPtr window);
1954                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1955                 internal static extern int DisposeWindow (IntPtr wHnd);
1956                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1957                 internal static extern int ShowWindow (IntPtr wHnd);
1958                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1959                 internal static extern int HideWindow (IntPtr wHnd);
1960                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1961                 internal static extern int SetWindowBounds (IntPtr wHnd, uint reg, ref IntPtr rect);
1962                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1963                 internal static extern int GetWindowPortBounds (IntPtr wHnd, ref Rect rect);
1964                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1965                 internal static extern int GetWindowBounds (IntPtr wHnd, uint reg, ref Rect rect);
1966                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1967                 internal static extern int InvertRect (ref Rect r);
1968
1969                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1970                 internal static extern int SetControlTitleWithCFString (IntPtr hWnd, IntPtr titleCFStr);
1971                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1972                 internal static extern int SetWindowTitleWithCFString (IntPtr hWnd, IntPtr titleCFStr);
1973                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1974                 internal static extern IntPtr __CFStringMakeConstantString (string cString);
1975                 
1976                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1977                 internal static extern void CGContextRestoreGState (IntPtr ctx);
1978                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1979                 internal static extern void CGContextSaveGState (IntPtr ctx);
1980                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1981                 internal static extern void CGContextTranslateCTM (IntPtr ctx, double tx, double ty);
1982                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1983                 internal static extern void CGContextScaleCTM (IntPtr ctx, double tx, double ty);
1984
1985                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1986                 static extern int SetWindowContentColor (IntPtr hWnd, ref RGBColor backColor);
1987                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1988                 static extern int TrackMouseLocationWithOptions (IntPtr port, int options, double eventtimeout, ref QDPoint point, ref IntPtr modifier, ref MouseTrackingResult status);
1989                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1990                 static extern int CreateMouseTrackingRegion (IntPtr windowref, IntPtr rgn, IntPtr clip, int options, MouseTrackingRegionID rid, IntPtr refcon, IntPtr evttargetref, ref IntPtr mousetrackref);
1991                 [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1992                 static extern int ReleaseMouseTrackingRegion (IntPtr region_handle);
1993                 
1994                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1995                 internal static extern int CFRelease (IntPtr wHnd);
1996                 
1997                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
1998                 internal extern static IntPtr NewRgn ();
1999                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2000                 internal extern static void CopyRgn (IntPtr srcrgn, IntPtr destrgn);
2001                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2002                 internal extern static void SetRectRgn (IntPtr rgn, short left, short top, short right, short bottom);
2003                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2004                 internal extern static void DisposeRgn (IntPtr rgn);
2005                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2006                 internal extern static void ExitToShell ();
2007                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2008                 internal extern static short GetMBarHeight ();
2009                 
2010                 #region Cursor imports
2011                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2012                 internal extern static HIRect CGDisplayBounds (IntPtr displayID);
2013                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2014                 internal extern static IntPtr CGMainDisplayID ();
2015                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2016                 internal extern static void CGDisplayShowCursor (IntPtr display);
2017                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2018                 internal extern static void CGDisplayHideCursor (IntPtr display);
2019                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2020                 internal extern static void CGDisplayMoveCursorToPoint (IntPtr display, CGPoint point);
2021                 [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
2022                 internal extern static void SetThemeCursor (uint inCursor);
2023                 #endregion
2024
2025                 [DllImport ("gdiplus", EntryPoint="GetFontMetrics")]
2026                 internal extern static bool GetFontMetrics(IntPtr graphicsObject, IntPtr nativeObject, out int ascent, out int descent);
2027         }
2028
2029 }