Added MacInternalOnSize() to allow windows to resize themselves independently of...
[wxWidgets.git] / src / osx / cocoa / window.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/osx/cocoa/window.mm
3 // Purpose:     widgets (non tlw) for cocoa
4 // Author:      Stefan Csomor
5 // Modified by:
6 // Created:     2008-06-20
7 // RCS-ID:      $Id$
8 // Copyright:   (c) Stefan Csomor
9 // Licence:     wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #ifndef WX_PRECOMP
15     #include "wx/dcclient.h"
16     #include "wx/frame.h"
17     #include "wx/log.h"
18     #include "wx/textctrl.h"
19     #include "wx/combobox.h"
20 #endif
21
22 #ifdef __WXMAC__
23     #include "wx/osx/private.h"
24 #endif
25
26 #include "wx/evtloop.h"
27
28 #if wxUSE_CARET
29     #include "wx/caret.h"
30 #endif
31
32 #if wxUSE_DRAG_AND_DROP
33     #include "wx/dnd.h"
34 #endif
35
36 #if wxUSE_TOOLTIPS
37     #include "wx/tooltip.h"
38 #endif
39
40 #include <objc/objc-runtime.h>
41
42 // Get the window with the focus
43
44 NSView* GetViewFromResponder( NSResponder* responder )
45 {
46     NSView* view = nil;
47     if ( [responder isKindOfClass:[NSTextView class]] )
48     {
49         NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50         if ( [delegate isKindOfClass:[NSTextField class] ] )
51             view = delegate;
52         else
53             view =  (NSView*) responder;
54     }
55     else
56     {
57         if ( [responder isKindOfClass:[NSView class]] )
58             view = (NSView*) responder;
59     }
60     return view;
61 }
62
63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
64 {
65     NSView* focusedView = nil;
66     if ( keyWindow != nil )
67         focusedView = GetViewFromResponder([keyWindow firstResponder]);
68
69     return focusedView;
70 }
71
72 WXWidget wxWidgetImpl::FindFocus()
73 {
74     return GetFocusedViewInWindow( [NSApp keyWindow] );
75 }
76
77 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
78 {
79     int x, y, w, h ;
80
81     window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
82     wxRect bounds(x,y,w,h);
83     NSView* sv = (window->GetParent()->GetHandle() );
84
85     return wxToNSRect( sv, bounds );
86 }
87
88 @interface wxNSView : NSView
89 {
90     NSTrackingRectTag rectTag;
91 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
92     NSTrackingArea* _trackingArea;
93 #endif
94 }
95
96 // the tracking tag is needed to track mouse enter / exit events
97 - (void) setTrackingTag: (NSTrackingRectTag)tag;
98 - (NSTrackingRectTag) trackingTag;
99 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
100 // under 10.5 we can also track mouse moved events on non-focused windows if
101 // we use the new NSTrackingArea APIs. 
102 - (void) updateTrackingArea;
103 - (NSTrackingArea*) trackingArea;
104 #endif
105 @end // wxNSView
106
107 @interface NSView(PossibleMethods)
108 - (void)setTitle:(NSString *)aString;
109 - (void)setStringValue:(NSString *)aString;
110 - (void)setIntValue:(int)anInt;
111 - (void)setFloatValue:(float)aFloat;
112 - (void)setDoubleValue:(double)aDouble;
113
114 - (double)minValue;
115 - (double)maxValue;
116 - (void)setMinValue:(double)aDouble;
117 - (void)setMaxValue:(double)aDouble;
118
119 - (void)sizeToFit;
120
121 - (BOOL)isEnabled;
122 - (void)setEnabled:(BOOL)flag;
123
124 - (void)setImage:(NSImage *)image;
125 - (void)setControlSize:(NSControlSize)size;
126
127 - (void)setFont:(NSFont *)fontObject;
128
129 - (id)contentView;
130
131 - (void)setTarget:(id)anObject;
132 - (void)setAction:(SEL)aSelector;
133 - (void)setDoubleAction:(SEL)aSelector;
134 - (void)setBackgroundColor:(NSColor*)aColor;
135 - (void)setOpaque:(BOOL)opaque;
136 - (void)setTextColor:(NSColor *)color;
137 - (void)setImagePosition:(NSCellImagePosition)aPosition;
138 @end
139
140 // in case we want to use the native tooltip callbacks
141
142 #if 0
143
144 @interface NSView(wxToolTip)
145 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)userData;
146 @end
147
148 @implementation NSView(wxToolTip)
149
150 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)userData {
151     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( view );
152     if (impl == NULL)
153         return nil;
154     
155     return @"Tag";
156 }
157 @end
158
159 #endif
160
161 // The following code is a combination of the code listed here:
162 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
163 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
164 // and the code here:
165 // http://inquisitivecocoa.com/category/objective-c/
166 @interface NSEvent (OsGuiUtilsAdditions)
167 - (NSString*) charactersIgnoringModifiersIncludingShift;
168 @end
169
170 @implementation NSEvent (OsGuiUtilsAdditions)
171 - (NSString*) charactersIgnoringModifiersIncludingShift {
172     // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
173     // differently than AppKit.
174     NSString* c = [self charactersIgnoringModifiers];
175     if ([c length] == 1) {
176         unichar codepoint = [c characterAtIndex:0];
177         if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
178             return c;
179         }
180     }
181     // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
182     // modifiers attached.  Actually, that's not quite accurate; we attach the Command modifier
183     // which hints the OS to use Latin characters where possible, which is generally what we want.
184     NSString* result = @"";
185     TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
186     CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
187     CFRelease(currentKeyboard);
188     if (uchr == NULL) {
189         // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
190         return c;
191     }
192     const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
193     if (keyboardLayout) {
194         UInt32 deadKeyState = 0;
195         UniCharCount maxStringLength = 255;
196         UniCharCount actualStringLength = 0;
197         UniChar unicodeString[maxStringLength];
198         
199         OSStatus status = UCKeyTranslate(keyboardLayout,
200                                          [self keyCode],
201                                          kUCKeyActionDown,
202                                          cmdKey >> 8,         // force the Command key to "on"
203                                          LMGetKbdType(),
204                                          kUCKeyTranslateNoDeadKeysMask,
205                                          &deadKeyState,
206                                          maxStringLength,
207                                          &actualStringLength,
208                                          unicodeString);
209         
210         if(status == noErr)
211             result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
212     }
213     return result;
214 }
215 @end
216
217 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
218 {
219     long retval = 0;
220
221     if ([event type] != NSFlagsChanged)
222     {
223         NSString* s = [event charactersIgnoringModifiersIncludingShift];
224         // backspace char reports as delete w/modifiers for some reason
225         if ([s length] == 1)
226         {
227             if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
228             {
229                 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
230             }
231             else
232             {
233                 switch ( [s characterAtIndex:0] )
234                 {
235                     // backspace key
236                     case 0x7F :
237                     case 8 :
238                         retval = WXK_BACK;
239                         break;
240                     case NSUpArrowFunctionKey :
241                         retval = WXK_UP;
242                         break;
243                     case NSDownArrowFunctionKey :
244                         retval = WXK_DOWN;
245                         break;
246                     case NSLeftArrowFunctionKey :
247                         retval = WXK_LEFT;
248                         break;
249                     case NSRightArrowFunctionKey :
250                         retval = WXK_RIGHT;
251                         break;
252                     case NSInsertFunctionKey  :
253                         retval = WXK_INSERT;
254                         break;
255                     case NSDeleteFunctionKey  :
256                         retval = WXK_DELETE;
257                         break;
258                     case NSHomeFunctionKey  :
259                         retval = WXK_HOME;
260                         break;
261             //        case NSBeginFunctionKey  :
262             //            retval = WXK_BEGIN;
263             //            break;
264                     case NSEndFunctionKey  :
265                         retval = WXK_END;
266                         break;
267                     case NSPageUpFunctionKey  :
268                         retval = WXK_PAGEUP;
269                         break;
270                    case NSPageDownFunctionKey  :
271                         retval = WXK_PAGEDOWN;
272                         break;
273                    case NSHelpFunctionKey  :
274                         retval = WXK_HELP;
275                         break;
276                     default:
277                         int intchar = [s characterAtIndex: 0];
278                         if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
279                             retval = WXK_F1 + (intchar - NSF1FunctionKey );
280                         else if ( intchar > 0 && intchar < 32 )
281                             retval = intchar;
282                         break;
283                 }
284             }
285         }
286     }
287
288     // Some keys don't seem to have constants. The code mimics the approach
289     // taken by WebKit. See:
290     // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
291     switch( [event keyCode] )
292     {
293         // command key
294         case 54:
295         case 55:
296             retval = WXK_CONTROL;
297             break;
298         // caps locks key
299         case 57: // Capslock
300             retval = WXK_CAPITAL;
301             break;
302         // shift key
303         case 56: // Left Shift
304         case 60: // Right Shift
305             retval = WXK_SHIFT;
306             break;
307         // alt key
308         case 58: // Left Alt
309         case 61: // Right Alt
310             retval = WXK_ALT;
311             break;
312         // ctrl key
313         case 59: // Left Ctrl
314         case 62: // Right Ctrl
315             retval = WXK_RAW_CONTROL;
316             break;
317         // clear key
318         case 71:
319             retval = WXK_CLEAR;
320             break;
321         // tab key
322         case 48:
323             retval = WXK_TAB;
324             break;
325
326         case 75: // /
327             retval = WXK_NUMPAD_DIVIDE;
328             break;
329         case 67: // *
330             retval = WXK_NUMPAD_MULTIPLY;
331             break;
332         case 78: // -
333             retval = WXK_NUMPAD_SUBTRACT;
334             break;
335         case 69: // +
336             retval = WXK_NUMPAD_ADD;
337             break;
338         case 76: // Enter
339             retval = WXK_NUMPAD_ENTER;
340             break;
341         case 65: // .
342             retval = WXK_NUMPAD_DECIMAL;
343             break;
344         case 82: // 0
345             retval = WXK_NUMPAD0;
346             break;
347         case 83: // 1
348             retval = WXK_NUMPAD1;
349             break;
350         case 84: // 2
351             retval = WXK_NUMPAD2;
352             break;
353         case 85: // 3
354             retval = WXK_NUMPAD3;
355             break;
356         case 86: // 4
357             retval = WXK_NUMPAD4;
358             break;
359         case 87: // 5
360             retval = WXK_NUMPAD5;
361             break;
362         case 88: // 6
363             retval = WXK_NUMPAD6;
364             break;
365         case 89: // 7
366             retval = WXK_NUMPAD7;
367             break;
368         case 91: // 8
369             retval = WXK_NUMPAD8;
370             break;
371         case 92: // 9
372             retval = WXK_NUMPAD9;
373             break;
374         default:
375             //retval = [event keyCode];
376             break;
377     }
378     return retval;
379 }
380
381 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
382 {
383     UInt32 modifiers = [nsEvent modifierFlags] ;
384     int eventType = [nsEvent type];
385
386     wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
387     wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
388     wxevent.m_altDown = modifiers & NSAlternateKeyMask;
389     wxevent.m_controlDown = modifiers & NSCommandKeyMask;
390
391     wxevent.m_rawCode = [nsEvent keyCode];
392     wxevent.m_rawFlags = modifiers;
393
394     wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
395
396     wxString chars;
397     if ( eventType != NSFlagsChanged )
398     {
399         NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
400         if ( charString )
401         {
402             // if charString is set, it did not come from key up / key down
403             wxevent.SetEventType( wxEVT_CHAR );
404             chars = wxCFStringRef::AsString(charString);
405         }
406         else if ( nschars )
407         {
408             chars = wxCFStringRef::AsString(nschars);
409         }
410     }
411
412     int aunichar = chars.Length() > 0 ? chars[0] : 0;
413     long keyval = 0;
414
415     if (wxevent.GetEventType() != wxEVT_CHAR)
416     {
417         keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
418         switch (eventType)
419         {
420             case NSKeyDown :
421                 wxevent.SetEventType( wxEVT_KEY_DOWN )  ;
422                 break;
423             case NSKeyUp :
424                 wxevent.SetEventType( wxEVT_KEY_UP )  ;
425                 break;
426             case NSFlagsChanged :
427                 switch (keyval)
428                 {
429                     case WXK_CONTROL:
430                         wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
431                         break;
432                     case WXK_SHIFT:
433                         wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
434                         break;
435                     case WXK_ALT:
436                         wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
437                         break;
438                     case WXK_RAW_CONTROL:
439                         wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
440                         break;
441                 }
442                 break;
443             default :
444                 break ;
445         }
446     }
447
448     if ( !keyval )
449     {
450         if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
451             keyval = wxToupper( aunichar ) ;
452         else
453             keyval = aunichar;
454     }
455
456 #if wxUSE_UNICODE
457     // OS X generates events with key codes in Unicode private use area for
458     // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
459     // and function keys (WXK_F2 is U+F705). We don't want to use them as the
460     // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
461     // WXK_NONE for "non characters" so explicitly exclude them.
462     //
463     // We only exclude the private use area inside the Basic Multilingual Plane
464     // as key codes beyond it don't seem to be currently used.
465     if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
466         wxevent.m_uniChar = aunichar;
467 #endif
468     wxevent.m_keyCode = keyval;
469
470     wxWindowMac* peer = GetWXPeer();
471     if ( peer )
472     {
473         wxevent.SetEventObject(peer);
474         wxevent.SetId(peer->GetId()) ;
475     }
476 }
477
478 UInt32 g_lastButton = 0 ;
479 bool g_lastButtonWasFakeRight = false ;
480
481 // better scroll wheel support 
482 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
483
484 @interface NSEvent (DeviceDelta)
485 - (CGFloat)deviceDeltaX;
486 - (CGFloat)deviceDeltaY;
487 @end
488
489 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
490 {
491     int eventType = [nsEvent type];
492     UInt32 modifiers = [nsEvent modifierFlags] ;
493
494     NSPoint locationInWindow = [nsEvent locationInWindow];
495     
496     // adjust coordinates for the window of the target view
497     if ( [nsEvent window] != [m_osxView window] )
498     {
499         if ( [nsEvent window] != nil )
500             locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
501
502         if ( [m_osxView window] != nil )
503             locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
504     }
505
506     NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
507     wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
508
509     // these parameters are not given for all events
510     UInt32 button = [nsEvent buttonNumber];
511     UInt32 clickCount = 0;
512
513     wxevent.m_x = locationInViewWX.x;
514     wxevent.m_y = locationInViewWX.y;
515     wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
516     wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
517     wxevent.m_altDown = modifiers & NSAlternateKeyMask;
518     wxevent.m_controlDown = modifiers & NSCommandKeyMask;
519     wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
520
521     UInt32 mouseChord = 0;
522
523     switch (eventType)
524     {
525         case NSLeftMouseDown :
526         case NSLeftMouseDragged :
527             mouseChord = 1U;
528             break;
529         case NSRightMouseDown :
530         case NSRightMouseDragged :
531             mouseChord = 2U;
532             break;
533         case NSOtherMouseDown :
534         case NSOtherMouseDragged :
535             mouseChord = 4U;
536             break;
537     }
538
539     // a control click is interpreted as a right click
540     bool thisButtonIsFakeRight = false ;
541     if ( button == 0 && (modifiers & NSControlKeyMask) )
542     {
543         button = 1 ;
544         thisButtonIsFakeRight = true ;
545     }
546
547     // otherwise we report double clicks by connecting a left click with a ctrl-left click
548     if ( clickCount > 1 && button != g_lastButton )
549         clickCount = 1 ;
550
551     // we must make sure that our synthetic 'right' button corresponds in
552     // mouse down, moved and mouse up, and does not deliver a right down and left up
553     switch (eventType)
554     {
555         case NSLeftMouseDown :
556         case NSRightMouseDown :
557         case NSOtherMouseDown :
558             g_lastButton = button ;
559             g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
560             break;
561      }
562
563     if ( button == 0 )
564     {
565         g_lastButton = 0 ;
566         g_lastButtonWasFakeRight = false ;
567     }
568     else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
569         button = g_lastButton ;
570
571     // Adjust the chord mask to remove the primary button and add the
572     // secondary button.  It is possible that the secondary button is
573     // already pressed, e.g. on a mouse connected to a laptop, but this
574     // possibility is ignored here:
575     if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
576         mouseChord = ((mouseChord & ~1U) | 2U);
577
578     if(mouseChord & 1U)
579                 wxevent.m_leftDown = true ;
580     if(mouseChord & 2U)
581                 wxevent.m_rightDown = true ;
582     if(mouseChord & 4U)
583                 wxevent.m_middleDown = true ;
584
585     // translate into wx types
586     switch (eventType)
587     {
588         case NSLeftMouseDown :
589         case NSRightMouseDown :
590         case NSOtherMouseDown :
591             clickCount = [nsEvent clickCount];
592             switch ( button )
593             {
594                 case 0 :
595                     wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN )  ;
596                     break ;
597
598                 case 1 :
599                     wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
600                     break ;
601
602                 case 2 :
603                     wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
604                     break ;
605
606                 default:
607                     break ;
608             }
609             break ;
610
611         case NSLeftMouseUp :
612         case NSRightMouseUp :
613         case NSOtherMouseUp :
614             clickCount = [nsEvent clickCount];
615             switch ( button )
616             {
617                 case 0 :
618                     wxevent.SetEventType( wxEVT_LEFT_UP )  ;
619                     break ;
620
621                 case 1 :
622                     wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
623                     break ;
624
625                 case 2 :
626                     wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
627                     break ;
628
629                 default:
630                     break ;
631             }
632             break ;
633
634      case NSScrollWheel :
635         {
636             float deltaX = 0.0;
637             float deltaY = 0.0;
638
639             wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
640
641             // see http://developer.apple.com/qa/qa2005/qa1453.html
642             // for more details on why we have to look for the exact type
643             
644             const EventRef cEvent = (EventRef) [nsEvent eventRef];
645             bool isMouseScrollEvent = false;
646             if ( cEvent )
647                 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
648                 
649             if ( isMouseScrollEvent )
650             {
651                 deltaX = [nsEvent deviceDeltaX];
652                 deltaY = [nsEvent deviceDeltaY];
653             }
654             else
655             {
656                 deltaX = ([nsEvent deltaX] * 10);
657                 deltaY = ([nsEvent deltaY] * 10);
658             }
659             
660             wxevent.m_wheelDelta = 10;
661             wxevent.m_linesPerAction = 1;
662                 
663             if ( fabs(deltaX) > fabs(deltaY) )
664             {
665                 wxevent.m_wheelAxis = 1;
666                 wxevent.m_wheelRotation = (int)deltaX;
667             }
668             else
669             {
670                 wxevent.m_wheelRotation = (int)deltaY;
671             }
672
673         }
674         break ;
675
676         case NSMouseEntered :
677             wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
678             break;
679         case NSMouseExited :
680             wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
681             break;
682         case NSLeftMouseDragged :
683         case NSRightMouseDragged :
684         case NSOtherMouseDragged :
685         case NSMouseMoved :
686             wxevent.SetEventType( wxEVT_MOTION ) ;
687             break;
688         default :
689             break ;
690     }
691
692     wxevent.m_clickCount = clickCount;
693     wxWindowMac* peer = GetWXPeer();
694     if ( peer )
695     {
696         wxevent.SetEventObject(peer);
697         wxevent.SetId(peer->GetId()) ;
698     }
699 }
700
701 @implementation wxNSView
702
703 + (void)initialize
704 {
705     static BOOL initialized = NO;
706     if (!initialized)
707     {
708         initialized = YES;
709         wxOSXCocoaClassAddWXMethods( self );
710     }
711 }
712
713 - (void) setTrackingTag: (NSTrackingRectTag)tag
714 {
715     rectTag = tag;
716 }
717
718 - (NSTrackingRectTag) trackingTag
719 {
720     return rectTag;
721 }
722
723 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
724 - (void) updateTrackingArea
725 {
726     if (_trackingArea)
727     {
728         [self removeTrackingArea: _trackingArea];
729         [_trackingArea release];
730     }
731     
732     NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
733         
734     NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
735     [self addTrackingArea: area];
736
737     _trackingArea = area;
738 }
739
740 - (NSTrackingArea*) trackingArea
741 {
742     return _trackingArea;
743 }
744 #endif
745 @end // wxNSView
746
747 //
748 // event handlers
749 //
750
751 #if wxUSE_DRAG_AND_DROP
752
753 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
754 // for details on the NSPasteboard -> PasteboardRef conversion
755
756 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
757 {
758     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
759     if (impl == NULL)
760         return NSDragOperationNone;
761
762     return impl->draggingEntered(sender, self, _cmd);
763 }
764
765 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
766 {
767     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
768     if (impl == NULL)
769         return ;
770
771     return impl->draggingExited(sender, self, _cmd);
772 }
773
774 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
775 {
776     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
777     if (impl == NULL)
778         return NSDragOperationNone;
779
780     return impl->draggingUpdated(sender, self, _cmd);
781 }
782
783 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
784 {
785     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
786     if (impl == NULL)
787         return NSDragOperationNone;
788
789     return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
790 }
791
792 #endif
793
794 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
795 {
796     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
797     if (impl == NULL)
798         return;
799
800     impl->mouseEvent(event, self, _cmd);
801 }
802
803 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
804 {
805     // This is needed to support click through, otherwise the first click on a window
806     // will not do anything unless it is the active window already.
807     return YES;
808 }
809
810 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
811 {
812     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
813     if (impl == NULL)
814         return;
815
816     impl->keyEvent(event, self, _cmd);
817 }
818
819 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
820 {
821     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
822     if (impl == NULL)
823         return;
824
825     impl->insertText(text, self, _cmd);
826 }
827
828 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
829 {
830     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
831     if (impl == NULL)
832         return NO;
833
834     return impl->performKeyEquivalent(event, self, _cmd);
835 }
836
837 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
838 {
839     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
840     if (impl == NULL)
841         return NO;
842
843     return impl->acceptsFirstResponder(self, _cmd);
844 }
845
846 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
847 {
848     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
849     if (impl == NULL)
850         return NO;
851
852     return impl->becomeFirstResponder(self, _cmd);
853 }
854
855 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
856 {
857     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
858     if (impl == NULL)
859         return NO;
860
861     return impl->resignFirstResponder(self, _cmd);
862 }
863
864 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
865 {
866     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
867     if (impl == NULL)
868         return;
869
870     impl->resetCursorRects(self, _cmd);
871 }
872
873 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
874 {
875     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
876     if (impl == NULL)
877         return NO;
878
879     return impl->isFlipped(self, _cmd) ? YES:NO;
880 }
881
882 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
883
884 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
885 {
886     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
887     if (impl == NULL)
888         return;
889
890 #ifdef wxUSE_THREADS
891     // OS X starts a NSUIHeartBeatThread for animating the default button in a
892     // dialog. This causes a drawRect of the active dialog from outside the
893     // main UI thread. This causes an occasional crash since the wx drawing
894     // objects (like wxPen) are not thread safe.
895     //
896     // Notice that NSUIHeartBeatThread seems to be undocumented and doing
897     // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
898     if ( !wxThread::IsMain() )
899     {
900         if ( impl->IsUserPane() )
901         {
902             wxWindow* win = impl->GetWXPeer();
903             if ( win->UseBgCol() )
904             {
905                 
906                 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
907                 CGContextSaveGState( context );
908
909                 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
910                 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
911                 CGContextFillRect( context, r );
912
913                 CGContextRestoreGState( context );
914             }
915         }
916         else 
917         {
918             // just call the superclass handler, we don't need any custom wx drawing
919             // here and it seems to work fine:
920             wxOSX_DrawRectHandlerPtr
921             superimpl = (wxOSX_DrawRectHandlerPtr)
922             [[self superclass] instanceMethodForSelector:_cmd];
923             superimpl(self, _cmd, rect);
924         }
925
926       return;
927     }
928 #endif // wxUSE_THREADS
929
930     return impl->drawRect(&rect, self, _cmd);
931 }
932
933 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
934 {
935     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
936     if (impl == NULL)
937         return;
938
939     impl->controlAction(self, _cmd, sender);
940 }
941
942 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
943 {
944     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
945     if (impl == NULL)
946         return;
947
948     impl->controlDoubleAction(self, _cmd, sender);
949 }
950
951 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
952 {
953     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
954     NSPasteboard *pboard = [sender draggingPasteboard];
955     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
956
957     wxWindow* wxpeer = GetWXPeer();
958     if ( wxpeer == NULL )
959         return NSDragOperationNone;
960
961     wxDropTarget* target = wxpeer->GetDropTarget();
962     if ( target == NULL )
963         return NSDragOperationNone;
964
965     wxDragResult result = wxDragNone;
966     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
967     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
968
969     if ( sourceDragMask & NSDragOperationLink )
970         result = wxDragLink;
971     else if ( sourceDragMask & NSDragOperationCopy )
972         result = wxDragCopy;
973     else if ( sourceDragMask & NSDragOperationMove )
974         result = wxDragMove;
975
976     PasteboardRef pboardRef;
977     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
978     target->SetCurrentDragPasteboard(pboardRef);
979     result = target->OnEnter(pt.x, pt.y, result);
980     CFRelease(pboardRef);
981
982     NSDragOperation nsresult = NSDragOperationNone;
983     switch (result )
984     {
985         case wxDragLink:
986             nsresult = NSDragOperationLink;
987         case wxDragMove:
988             nsresult = NSDragOperationMove;
989         case wxDragCopy:
990             nsresult = NSDragOperationCopy;
991         default :
992             break;
993     }
994     return nsresult;
995 }
996
997 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
998 {
999     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1000     NSPasteboard *pboard = [sender draggingPasteboard];
1001
1002     wxWindow* wxpeer = GetWXPeer();
1003     if ( wxpeer == NULL )
1004         return;
1005
1006     wxDropTarget* target = wxpeer->GetDropTarget();
1007     if ( target == NULL )
1008         return;
1009
1010     PasteboardRef pboardRef;
1011     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1012     target->SetCurrentDragPasteboard(pboardRef);
1013     target->OnLeave();
1014     CFRelease(pboardRef);
1015  }
1016
1017 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1018 {
1019     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1020     NSPasteboard *pboard = [sender draggingPasteboard];
1021     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1022
1023     wxWindow* wxpeer = GetWXPeer();
1024     if ( wxpeer == NULL )
1025         return NSDragOperationNone;
1026
1027     wxDropTarget* target = wxpeer->GetDropTarget();
1028     if ( target == NULL )
1029         return NSDragOperationNone;
1030
1031     wxDragResult result = wxDragNone;
1032     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1033     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1034
1035     if ( sourceDragMask & NSDragOperationLink )
1036         result = wxDragLink;
1037     else if ( sourceDragMask & NSDragOperationCopy )
1038         result = wxDragCopy;
1039     else if ( sourceDragMask & NSDragOperationMove )
1040         result = wxDragMove;
1041     
1042     PasteboardRef pboardRef;
1043     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1044     target->SetCurrentDragPasteboard(pboardRef);
1045     result = target->OnDragOver(pt.x, pt.y, result);
1046     CFRelease(pboardRef);
1047
1048     NSDragOperation nsresult = NSDragOperationNone;
1049     switch (result )
1050     {
1051         case wxDragLink:
1052             nsresult = NSDragOperationLink;
1053         case wxDragMove:
1054             nsresult = NSDragOperationMove;
1055         case wxDragCopy:
1056             nsresult = NSDragOperationCopy;
1057         default :
1058             break;
1059     }
1060     return nsresult;
1061 }
1062
1063 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1064 {
1065     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1066
1067     NSPasteboard *pboard = [sender draggingPasteboard];
1068     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1069
1070     wxWindow* wxpeer = GetWXPeer();
1071     wxDropTarget* target = wxpeer->GetDropTarget();
1072     wxDragResult result = wxDragNone;
1073     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1074     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1075
1076     if ( sourceDragMask & NSDragOperationLink )
1077         result = wxDragLink;
1078     else if ( sourceDragMask & NSDragOperationCopy )
1079         result = wxDragCopy;
1080     else if ( sourceDragMask & NSDragOperationMove )
1081         result = wxDragMove;
1082
1083     PasteboardRef pboardRef;
1084     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1085     target->SetCurrentDragPasteboard(pboardRef);
1086
1087     if (target->OnDrop(pt.x, pt.y))
1088         result = target->OnData(pt.x, pt.y, result);
1089
1090     CFRelease(pboardRef);
1091
1092     return result != wxDragNone;
1093 }
1094
1095 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1096 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1097 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1098 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1099 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
1100
1101 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1102 {
1103     if ( !DoHandleMouseEvent(event) )
1104     {
1105         // for plain NSView mouse events would propagate to parents otherwise
1106         if (!IsUserPane())
1107         {
1108             wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1109             superimpl(slf, (SEL)_cmd, event);
1110             
1111             // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1112             
1113             if ( [ event type]  == NSLeftMouseDown )
1114             {
1115                 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1116                 SetupMouseEvent(wxevent , event) ;
1117                 wxevent.SetEventType(wxEVT_LEFT_UP);
1118                 
1119                 GetWXPeer()->HandleWindowEvent(wxevent);
1120             }
1121         }
1122     }
1123 }
1124
1125 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1126 {
1127     if ( [event type] == NSKeyDown )
1128     {
1129         // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically, 
1130         // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1131         if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1132             return;
1133     
1134         m_lastKeyDownEvent = event;
1135     }
1136     
1137     if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1138     {
1139         wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1140         superimpl(slf, (SEL)_cmd, event);
1141     }
1142     m_lastKeyDownEvent = NULL;
1143 }
1144
1145 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1146 {
1147     if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1148     {
1149         wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1150         superimpl(slf, (SEL)_cmd, text);
1151     }
1152 }
1153
1154
1155 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1156 {
1157     bool handled = false;
1158     
1159     wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1160     SetupKeyEvent( wxevent, event );
1161    
1162     // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1163     // walk up the ancestors ourselves but let cocoa do it
1164     
1165     int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1166     if (command != -1)
1167     {
1168         wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1169         
1170         wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1171         command_event.SetEventObject( wxevent.GetEventObject() );
1172         handled = handler->ProcessEvent( command_event );
1173         
1174         if ( !handled )
1175         {
1176             // accelerators can also be used with buttons, try them too
1177             command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1178             handled = handler->ProcessEvent( command_event );
1179         }
1180     }
1181     
1182     if ( !handled )
1183     {
1184         wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1185         return superimpl(slf, (SEL)_cmd, event);
1186     }
1187     return YES;
1188 }
1189
1190 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1191 {
1192     if ( IsUserPane() )
1193         return m_wxPeer->AcceptsFocus();
1194     else
1195     {
1196         wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1197         return superimpl(slf, (SEL)_cmd);
1198     }
1199 }
1200
1201 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1202 {
1203     wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1204     // get the current focus before running becomeFirstResponder
1205     NSView* otherView = FindFocus();
1206
1207     wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1208     BOOL r = superimpl(slf, (SEL)_cmd);
1209     if ( r )
1210     {
1211         DoNotifyFocusEvent( true, otherWindow );
1212     }
1213
1214     return r;
1215 }
1216
1217 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1218 {
1219     wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1220     BOOL r = superimpl(slf, (SEL)_cmd);
1221     // get the current focus after running resignFirstResponder
1222     // note that this value isn't reliable, it might return the same view that
1223     // is resigning
1224     NSView* otherView = FindFocus();
1225     wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1226
1227     // It doesn't make sense to notify about the loss of focus if we're not
1228     // really losing it and the window which has just gained focus is the same
1229     // one as this window itself. Of course, this should never happen in the
1230     // first place but somehow it does in wxGrid code and without this check we
1231     // enter into an infinite recursion, see #12267.
1232     if ( otherWindow == this )
1233         return r;
1234
1235     // NSTextViews have an editor as true responder, therefore the might get the
1236     // resign notification if their editor takes over, don't trigger any event then
1237     if ( r && !m_hasEditor)
1238     {
1239         DoNotifyFocusEvent( false, otherWindow );
1240     }
1241     return r;
1242 }
1243
1244 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1245 {
1246     wxWindow* wxpeer = GetWXPeer();
1247     if ( wxpeer )
1248     {
1249         NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1250         if (cursor == NULL)
1251         {
1252             wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1253             superimpl(slf, (SEL)_cmd);
1254         }
1255         else
1256         {
1257             [slf addCursorRect: [slf bounds]
1258                 cursor: cursor];
1259         }
1260     }
1261 }
1262
1263 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1264 {
1265     return m_isFlipped;
1266 }
1267
1268
1269 #define OSX_DEBUG_DRAWING 0
1270
1271 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1272 {
1273     // preparing the update region
1274     
1275     wxRegion updateRgn;
1276     const NSRect *rects;
1277     NSInteger count;
1278
1279     [slf getRectsBeingDrawn:&rects count:&count];
1280     for ( int i = 0 ; i < count ; ++i )
1281     {
1282         updateRgn.Union(wxFromNSRect(slf, rects[i]));
1283     }
1284
1285     wxWindow* wxpeer = GetWXPeer();
1286
1287     if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1288     {
1289         // as this update region is in native window locals we must adapt it to wx window local
1290         updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1291     }
1292     
1293     // Restrict the update region to the shape of the window, if any, and also
1294     // remember the region that we need to clear later.
1295     wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1296     const bool isTopLevel = tlwParent == wxpeer;
1297     wxRegion clearRgn;
1298     if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1299     {
1300         if ( isTopLevel )
1301             clearRgn = updateRgn;
1302
1303         int xoffset = 0, yoffset = 0;
1304         wxRegion rgn = tlwParent->GetShape();
1305         wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1306         rgn.Offset( xoffset, yoffset );
1307         updateRgn.Intersect(rgn);
1308
1309         if ( isTopLevel )
1310         {
1311             // Exclude the window shape from the region to be cleared below.
1312             rgn.Xor(wxpeer->GetSize());
1313             clearRgn.Intersect(rgn);
1314         }
1315     }
1316     
1317     wxpeer->GetUpdateRegion() = updateRgn;
1318
1319     // setting up the drawing context
1320     
1321     CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1322     CGContextSaveGState( context );
1323     
1324 #if OSX_DEBUG_DRAWING
1325     CGContextBeginPath( context );
1326     CGContextMoveToPoint(context, 0, 0);
1327     NSRect bounds = [slf bounds];
1328     CGContextAddLineToPoint(context, 10, 0);
1329     CGContextMoveToPoint(context, 0, 0);
1330     CGContextAddLineToPoint(context, 0, 10);
1331     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1332     CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1333     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1334     CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1335     CGContextClosePath( context );
1336     CGContextStrokePath(context);
1337 #endif
1338     
1339     if ( !m_isFlipped )
1340     {
1341         CGContextTranslateCTM( context, 0,  [m_osxView bounds].size.height );
1342         CGContextScaleCTM( context, 1, -1 );
1343     }
1344     
1345     wxpeer->MacSetCGContextRef( context );
1346
1347     bool handled = wxpeer->MacDoRedraw( 0 );
1348     CGContextRestoreGState( context );
1349
1350     CGContextSaveGState( context );
1351     if ( !handled )
1352     {
1353         // call super
1354         SEL _cmd = @selector(drawRect:);
1355         wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1356         superimpl(slf, _cmd, *(NSRect*)rect);
1357         CGContextRestoreGState( context );
1358         CGContextSaveGState( context );
1359     }
1360     // as we called restore above, we have to flip again if necessary
1361     if ( !m_isFlipped )
1362     {
1363         CGContextTranslateCTM( context, 0,  [m_osxView bounds].size.height );
1364         CGContextScaleCTM( context, 1, -1 );
1365     }
1366
1367     if ( isTopLevel )
1368     {
1369         // We also need to explicitly draw the part of the top level window
1370         // outside of its region with transparent colour to ensure that it is
1371         // really transparent.
1372         if ( clearRgn.IsOk() )
1373         {
1374             wxMacCGContextStateSaver saveState(context);
1375             wxWindowDC dc(wxpeer);
1376             dc.SetBackground(wxBrush(wxTransparentColour));
1377             dc.SetDeviceClippingRegion(clearRgn);
1378             dc.Clear();
1379         }
1380
1381 #if wxUSE_GRAPHICS_CONTEXT
1382         // If the window shape is defined by a path, stroke the path to show
1383         // the window border.
1384         const wxGraphicsPath& path = tlwParent->GetShapePath();
1385         if ( !path.IsNull() )
1386         {
1387             CGContextSetLineWidth(context, 1);
1388             CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1389             CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1390             CGContextStrokePath(context);
1391         }
1392 #endif // wxUSE_GRAPHICS_CONTEXT
1393     }
1394
1395     wxpeer->MacPaintChildrenBorders();
1396     wxpeer->MacSetCGContextRef( NULL );
1397     CGContextRestoreGState( context );
1398 }
1399
1400 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1401 {
1402     wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1403     if ( wxpeer )
1404         wxpeer->OSXHandleClicked(0);
1405 }
1406
1407 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1408 {
1409 }
1410
1411 void wxWidgetCocoaImpl::controlTextDidChange()
1412 {
1413     wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1414     if ( wxpeer ) 
1415     {
1416         // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1417         wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1418         wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1419         if ( tc )
1420             tc->SendTextUpdatedEventIfAllowed();
1421         else if ( cb )
1422             cb->SendTextUpdatedEventIfAllowed();
1423         else 
1424         {
1425             wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1426         }
1427     }
1428 }
1429
1430 //
1431
1432 #if OBJC_API_VERSION >= 2
1433
1434 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1435     class_addMethod(c, s, i, t );
1436
1437 #else
1438
1439 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1440     { s, (char*) t, i },
1441
1442 #endif
1443
1444 void wxOSXCocoaClassAddWXMethods(Class c)
1445 {
1446
1447 #if OBJC_API_VERSION < 2
1448     static objc_method wxmethods[] =
1449     {
1450 #endif
1451
1452     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1453     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1454     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1455
1456     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1457     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1458     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1459
1460     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1461
1462     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1463     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1464     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1465     
1466     wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1467
1468     wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1469     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1470     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1471
1472     wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1473     wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1474     wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1475
1476     wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1477
1478     wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1479
1480     wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1481     wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1482     wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1483     wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1484
1485     wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1486     wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1487
1488     wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1489     wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1490
1491 #if wxUSE_DRAG_AND_DROP
1492     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1493     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1494     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1495     wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1496 #endif
1497
1498 #if OBJC_API_VERSION < 2
1499     } ;
1500     static int method_count = WXSIZEOF( wxmethods );
1501     static objc_method_list *wxmethodlist = NULL;
1502     if ( wxmethodlist == NULL )
1503     {
1504         wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1505         memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1506         wxmethodlist->method_count = method_count;
1507         wxmethodlist->obsolete = 0;
1508     }
1509     class_addMethods( c, wxmethodlist );
1510 #endif
1511 }
1512
1513 //
1514 // C++ implementation class
1515 //
1516
1517 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1518
1519 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1520     wxWidgetImpl( peer, isRootControl, isUserPane )
1521 {
1522     Init();
1523     m_osxView = w;
1524
1525     // check if the user wants to create the control initially hidden
1526     if ( !peer->IsShown() )
1527         SetVisibility(false);
1528
1529     // gc aware handling
1530     if ( m_osxView )
1531         CFRetain(m_osxView);
1532     [m_osxView release];
1533 }
1534
1535 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1536 {
1537     Init();
1538 }
1539
1540 void wxWidgetCocoaImpl::Init()
1541 {
1542     m_osxView = NULL;
1543     m_isFlipped = true;
1544     m_lastKeyDownEvent = NULL;
1545     m_hasEditor = false;
1546 }
1547
1548 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1549 {
1550     RemoveAssociations( this );
1551
1552     if ( !IsRootControl() )
1553     {
1554         NSView *sv = [m_osxView superview];
1555         if ( sv != nil )
1556             [m_osxView removeFromSuperview];
1557     }
1558     // gc aware handling
1559     if ( m_osxView )
1560         CFRelease(m_osxView);
1561 }
1562
1563 bool wxWidgetCocoaImpl::IsVisible() const
1564 {
1565     return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1566 }
1567
1568 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1569 {
1570     [m_osxView setHidden:(visible ? NO:YES)];
1571 }
1572
1573 // ----------------------------------------------------------------------------
1574 // window animation stuff
1575 // ----------------------------------------------------------------------------
1576
1577 // define a delegate used to refresh the window during animation
1578 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1579 {
1580     wxWindow *m_win;
1581     bool m_isDone;
1582 }
1583
1584 - (id)init:(wxWindow *)win;
1585
1586 - (bool)isDone;
1587
1588 // NSAnimationDelegate methods
1589 - (void)animationDidEnd:(NSAnimation*)animation;
1590 - (void)animation:(NSAnimation*)animation
1591         didReachProgressMark:(NSAnimationProgress)progress;
1592 @end
1593
1594 @implementation wxNSAnimationDelegate
1595
1596 - (id)init:(wxWindow *)win
1597 {
1598     self = [super init];
1599
1600     m_win = win;
1601     m_isDone = false;
1602
1603     return self;
1604 }
1605
1606 - (bool)isDone
1607 {
1608     return m_isDone;
1609 }
1610
1611 - (void)animation:(NSAnimation*)animation
1612         didReachProgressMark:(NSAnimationProgress)progress
1613 {
1614     wxUnusedVar(animation);
1615     wxUnusedVar(progress);
1616
1617     m_win->SendSizeEvent();
1618     m_win->MacOnInternalSize();
1619 }
1620
1621 - (void)animationDidEnd:(NSAnimation*)animation
1622 {
1623     wxUnusedVar(animation);
1624     m_isDone = true;
1625 }
1626
1627 @end
1628
1629 /* static */
1630 bool
1631 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1632                                               bool show,
1633                                               wxShowEffect effect,
1634                                               unsigned timeout)
1635 {
1636     // create the dictionary describing the animation to perform on this view
1637     NSObject * const
1638         viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1639     NSMutableDictionary * const
1640         dict = [NSMutableDictionary dictionaryWithCapacity:4];
1641     [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1642
1643     // determine the start and end rectangles assuming we're hiding the window
1644     const wxRect rectOrig = win->GetRect();
1645     wxRect rectStart,
1646            rectEnd;
1647     rectStart =
1648     rectEnd = rectOrig;
1649
1650     if ( show )
1651     {
1652         if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1653                 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1654             effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1655         else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1656                     effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1657             effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1658         else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1659                     effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1660             effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1661         else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1662                     effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1663             effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1664     }
1665
1666     switch ( effect )
1667     {
1668         case wxSHOW_EFFECT_ROLL_TO_LEFT:
1669         case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1670             rectEnd.width = 0;
1671             break;
1672
1673         case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1674         case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1675             rectEnd.x = rectStart.GetRight();
1676             rectEnd.width = 0;
1677             break;
1678
1679         case wxSHOW_EFFECT_ROLL_TO_TOP:
1680         case wxSHOW_EFFECT_SLIDE_TO_TOP:
1681             rectEnd.height = 0;
1682             break;
1683
1684         case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1685         case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1686             rectEnd.y = rectStart.GetBottom();
1687             rectEnd.height = 0;
1688             break;
1689
1690         case wxSHOW_EFFECT_EXPAND:
1691             rectEnd.x = rectStart.x + rectStart.width / 2;
1692             rectEnd.y = rectStart.y + rectStart.height / 2;
1693             rectEnd.width =
1694             rectEnd.height = 0;
1695             break;
1696
1697         case wxSHOW_EFFECT_BLEND:
1698             [dict setObject:(show ? NSViewAnimationFadeInEffect
1699                                   : NSViewAnimationFadeOutEffect)
1700                   forKey:NSViewAnimationEffectKey];
1701             break;
1702
1703         case wxSHOW_EFFECT_NONE:
1704         case wxSHOW_EFFECT_MAX:
1705             wxFAIL_MSG( "unexpected animation effect" );
1706             return false;
1707
1708         default:
1709             wxFAIL_MSG( "unknown animation effect" );
1710             return false;
1711     };
1712
1713     if ( show )
1714     {
1715         // we need to restore it to the original rectangle instead of making it
1716         // disappear
1717         wxSwap(rectStart, rectEnd);
1718
1719         // and as the window is currently hidden, we need to show it for the
1720         // animation to be visible at all (but don't restore it at its full
1721         // rectangle as it shouldn't appear immediately)
1722         win->SetSize(rectStart);
1723         win->Show();
1724     }
1725
1726     NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1727                                     ? [(NSView *)viewOrWin superview]
1728                                     : nil;
1729     const NSRect rStart = wxToNSRect(parentView, rectStart);
1730     const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1731
1732     [dict setObject:[NSValue valueWithRect:rStart]
1733           forKey:NSViewAnimationStartFrameKey];
1734     [dict setObject:[NSValue valueWithRect:rEnd]
1735           forKey:NSViewAnimationEndFrameKey];
1736
1737     // create an animation using the values in the above dictionary
1738     NSViewAnimation * const
1739         anim = [[NSViewAnimation alloc]
1740                 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1741
1742     if ( !timeout )
1743     {
1744         // what is a good default duration? Windows uses 200ms, Web frameworks
1745         // use anything from 250ms to 1s... choose something in the middle
1746         timeout = 500;
1747     }
1748
1749     [anim setDuration:timeout/1000.];   // duration is in seconds here
1750
1751     // if the window being animated changes its layout depending on its size
1752     // (which is almost always the case) we need to redo it during animation
1753     //
1754     // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1755     // controls in wxInfoBar visibly jump around)
1756     const int NUM_LAYOUTS = 20;
1757     for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1758         [anim addProgressMark:f];
1759
1760     wxNSAnimationDelegate * const
1761         animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1762     [anim setDelegate:animDelegate];
1763     [anim startAnimation];
1764
1765     // Cocoa is capable of doing animation asynchronously or even from separate
1766     // thread but wx API doesn't provide any way to be notified about the
1767     // animation end and without this we really must ensure that the window has
1768     // the expected (i.e. the same as if a simple Show() had been used) size
1769     // when we return, so block here until the animation finishes
1770     //
1771     // notice that because the default animation mode is NSAnimationBlocking,
1772     // no user input events ought to be processed from here
1773     {
1774         wxEventLoopGuarantor ensureEventLoopExistence;
1775         wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1776         while ( ![animDelegate isDone] )
1777             loop->Dispatch();
1778     }
1779
1780     if ( !show )
1781     {
1782         // NSViewAnimation is smart enough to hide the NSView being animated at
1783         // the end but we also must ensure that it's hidden for wx too
1784         win->Hide();
1785
1786         // and we must also restore its size because it isn't expected to
1787         // change just because the window was hidden
1788         win->SetSize(rectOrig);
1789     }
1790     else
1791     {
1792         // refresh it once again after the end to ensure that everything is in
1793         // place
1794         win->SendSizeEvent();
1795         win->MacOnInternalSize();
1796     }
1797
1798     [anim setDelegate:nil];
1799     [animDelegate release];
1800     [anim release];
1801
1802     return true;
1803 }
1804
1805 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1806                                        wxShowEffect effect,
1807                                        unsigned timeout)
1808 {
1809     return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1810 }
1811
1812 /* note that the drawing order between siblings is not defined under 10.4 */
1813 /* only starting from 10.5 the subview order is respected */
1814
1815 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1816  * NSInteger post-Leopard.  Pre-Leopard the Cocoa toolkit expects a function
1817  * returning int and not NSComparisonResult.  Post-Leopard the Cocoa toolkit
1818  * expects a function returning the new non-enum NSComparsionResult.
1819  * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1820  */
1821 #if defined(NSINTEGER_DEFINED)
1822 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1823 #else
1824 typedef int CocoaWindowCompareFunctionResult;
1825 #endif
1826
1827 class CocoaWindowCompareContext
1828 {
1829     wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1830 public:
1831     CocoaWindowCompareContext(); // Not implemented
1832     CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1833     {
1834         m_target = target;
1835         // Cocoa sorts subviews in-place.. make a copy
1836         m_subviews = [subviews copy];
1837     }
1838     
1839     ~CocoaWindowCompareContext()
1840     {   // release the copy
1841         [m_subviews release];
1842     }
1843     NSView* target()
1844     {   return m_target; }
1845     
1846     NSArray* subviews()
1847     {   return m_subviews; }
1848     
1849     /* Helper function that returns the comparison based off of the original ordering */
1850     CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1851     {
1852         NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1853         NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1854         // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1855         // likely compare higher than the other view which is reasonable considering the only way that
1856         // can happen is if the subview was added after our call to subviews but before the call to
1857         // sortSubviewsUsingFunction:context:.  Thus we don't bother checking.  Particularly because
1858         // that case should never occur anyway because that would imply a multi-threaded GUI call
1859         // which is a big no-no with Cocoa.
1860                 
1861         // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1862         NSComparisonResult result = (firstI < secondI)
1863                 ?   NSOrderedAscending /* -1 */
1864                 :   (firstI > secondI)
1865                 ?   NSOrderedDescending /* 1 */
1866                 :   NSOrderedSame /* 0 */;
1867                 
1868         return result;
1869     }
1870 private:
1871     /* The subview we are trying to Raise or Lower */
1872     NSView *m_target;
1873     /* A copy of the original array of subviews */
1874     NSArray *m_subviews;
1875 };
1876
1877 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1878  * the target view is always higher than every other view.  When comparing two views neither of
1879  * which is the target, it returns the correct response based on the original ordering
1880  */
1881 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1882 {
1883     CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1884     // first should be ordered higher
1885     if(first==compareContext->target())
1886         return NSOrderedDescending;
1887     // second should be ordered higher
1888     if(second==compareContext->target())
1889         return NSOrderedAscending;
1890     return compareContext->CompareUsingOriginalOrdering(first,second);
1891 }
1892
1893 void wxWidgetCocoaImpl::Raise()
1894 {
1895         NSView* nsview = m_osxView;
1896         
1897     NSView *superview = [nsview superview];
1898     CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1899         
1900     [superview sortSubviewsUsingFunction:
1901          CocoaRaiseWindowCompareFunction
1902                                                                  context: &compareContext];
1903         
1904 }
1905
1906 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
1907  * the target view is always lower than every other view.  When comparing two views neither of
1908  * which is the target, it returns the correct response based on the original ordering
1909  */
1910 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
1911 {
1912     CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1913     // first should be ordered lower
1914     if(first==compareContext->target())
1915         return NSOrderedAscending;
1916     // second should be ordered lower
1917     if(second==compareContext->target())
1918         return NSOrderedDescending;
1919     return compareContext->CompareUsingOriginalOrdering(first,second);
1920 }
1921
1922 void wxWidgetCocoaImpl::Lower()
1923 {
1924         NSView* nsview = m_osxView;
1925         
1926     NSView *superview = [nsview superview];
1927     CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1928         
1929     [superview sortSubviewsUsingFunction:
1930          CocoaLowerWindowCompareFunction
1931                                                                  context: &compareContext];
1932 }
1933
1934 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1935 {
1936 #if 1
1937     SetNeedsDisplay() ;
1938 #else
1939     // We should do something like this, but it wasn't working in 10.4.
1940     if (GetNeedsDisplay() )
1941     {
1942         SetNeedsDisplay() ;
1943     }
1944     NSRect r = wxToNSRect( [m_osxView superview], *rect );
1945     NSSize offset = NSMakeSize((float)dx, (float)dy);
1946     [m_osxView scrollRect:r by:offset];
1947 #endif
1948 }
1949
1950 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1951 {
1952     wxWindowMac* parent = GetWXPeer()->GetParent();
1953     // under Cocoa we might have a contentView in the wxParent to which we have to
1954     // adjust the coordinates
1955     if (parent && [m_osxView superview] != parent->GetHandle() )
1956     {
1957         int cx = 0,cy = 0,cw = 0,ch = 0;
1958         if ( parent->GetPeer() )
1959         {
1960             parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1961             x -= cx;
1962             y -= cy;
1963         }
1964     }
1965     [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1966     NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1967     [m_osxView setFrame:r];
1968     [[m_osxView superview] setNeedsDisplayInRect:r];
1969
1970     wxNSView* wxview = (wxNSView*)m_osxView;
1971 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1972     if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1973         [wxview updateTrackingArea]; 
1974 #else
1975     if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1976     {
1977         if ( [wxview trackingTag] )
1978             [wxview removeTrackingRect: [wxview trackingTag]];
1979
1980         [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1981     }
1982 #endif
1983 }
1984
1985 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1986 {
1987     wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1988     x = r.GetLeft();
1989     y = r.GetTop();
1990     
1991     // under Cocoa we might have a contentView in the wxParent to which we have to
1992     // adjust the coordinates
1993     wxWindowMac* parent = GetWXPeer()->GetParent();
1994     if (parent && [m_osxView superview] != parent->GetHandle() )
1995     {
1996         int cx = 0,cy = 0,cw = 0,ch = 0;
1997         if ( parent->GetPeer() )
1998         {
1999             parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2000             x += cx;
2001             y += cy;
2002         }
2003     }
2004 }
2005
2006 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2007 {
2008     NSRect rect = [m_osxView frame];
2009     width = (int)rect.size.width;
2010     height = (int)rect.size.height;
2011 }
2012
2013 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2014 {
2015     if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2016     {
2017         NSView* cv = [m_osxView contentView];
2018
2019         NSRect bounds = [m_osxView bounds];
2020         NSRect rect = [cv frame];
2021
2022         int y = (int)rect.origin.y;
2023         int x = (int)rect.origin.x;
2024         if ( ![ m_osxView isFlipped ] )
2025             y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2026         left = x;
2027         top = y;
2028         width = (int)rect.size.width;
2029         height = (int)rect.size.height;
2030     }
2031     else
2032     {
2033         left = top = 0;
2034         GetSize( width, height );
2035     }
2036 }
2037
2038 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2039 {
2040     if ( where )
2041         [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2042     else
2043         [m_osxView setNeedsDisplay:YES];
2044 }
2045
2046 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2047 {
2048     return [m_osxView needsDisplay];
2049 }
2050
2051 bool wxWidgetCocoaImpl::CanFocus() const
2052 {
2053     return [m_osxView canBecomeKeyView] == YES;
2054 }
2055
2056 bool wxWidgetCocoaImpl::HasFocus() const
2057 {
2058     return ( FindFocus() == m_osxView );
2059 }
2060
2061 bool wxWidgetCocoaImpl::SetFocus()
2062 {
2063     if ( !CanFocus() )
2064         return false;
2065
2066     // TODO remove if no issues arise: should not raise the window, only assign focus
2067     //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2068     [[m_osxView window] makeFirstResponder: m_osxView] ;
2069     return true;
2070 }
2071
2072
2073 void wxWidgetCocoaImpl::RemoveFromParent()
2074 {
2075     [m_osxView removeFromSuperview];
2076 }
2077
2078 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2079 {
2080     NSView* container = parent->GetWXWidget() ;
2081     wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2082     [container addSubview:m_osxView];
2083 }
2084
2085 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2086 {
2087     NSView* targetView = m_osxView;
2088     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2089         targetView = [(NSScrollView*) m_osxView documentView];
2090
2091     if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2092     {
2093         [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2094                                                                 green:(CGFloat) (col.Green() / 255.0)
2095                                                                  blue:(CGFloat) (col.Blue() / 255.0)
2096                                                                 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2097     }
2098 }
2099
2100 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2101 {
2102     BOOL opaque = ( style == wxBG_STYLE_PAINT );
2103     
2104     if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2105     {
2106         [m_osxView setOpaque: opaque];
2107     }
2108     
2109     return true ;
2110 }
2111
2112 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2113 {
2114     if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2115     {
2116         wxCFStringRef cf( title , encoding );
2117         [m_osxView setTitle:cf.AsNSString()];
2118     }
2119     else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2120     {
2121         wxCFStringRef cf( title , encoding );
2122         [m_osxView setStringValue:cf.AsNSString()];
2123     }
2124 }
2125
2126
2127 void  wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2128 {
2129     NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2130     p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2131     *pt = wxFromNSPoint( to->GetWXWidget(), p );
2132 }
2133
2134 wxInt32 wxWidgetCocoaImpl::GetValue() const
2135 {
2136     return [(NSControl*)m_osxView intValue];
2137 }
2138
2139 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2140 {
2141     if (  [m_osxView respondsToSelector:@selector(setIntValue:)] )
2142     {
2143         [m_osxView setIntValue:v];
2144     }
2145     else if (  [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2146     {
2147         [m_osxView setFloatValue:(double)v];
2148     }
2149     else if (  [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2150     {
2151         [m_osxView setDoubleValue:(double)v];
2152     }
2153 }
2154
2155 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2156 {
2157     if (  [m_osxView respondsToSelector:@selector(setMinValue:)] )
2158     {
2159         [m_osxView setMinValue:(double)v];
2160     }
2161 }
2162
2163 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2164 {
2165     if (  [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2166     {
2167         [m_osxView setMaxValue:(double)v];
2168     }
2169 }
2170
2171 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2172 {
2173     if (  [m_osxView respondsToSelector:@selector(minValue)] )
2174     {
2175         return (int)[m_osxView minValue];
2176     }
2177     return 0;
2178 }
2179
2180 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2181 {
2182     if (  [m_osxView respondsToSelector:@selector(maxValue)] )
2183     {
2184         return (int)[m_osxView maxValue];
2185     }
2186     return 0;
2187 }
2188
2189 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2190 {
2191     wxBitmap bmp;
2192
2193     // TODO: how to create a wxBitmap from NSImage?
2194 #if 0
2195     if ( [m_osxView respondsToSelector:@selector(image:)] )
2196         bmp = [m_osxView image];
2197 #endif
2198
2199     return bmp;
2200 }
2201
2202 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2203 {
2204     if (  [m_osxView respondsToSelector:@selector(setImage:)] )
2205     {
2206         if (bitmap.IsOk())
2207             [m_osxView setImage:bitmap.GetNSImage()];
2208         else
2209             [m_osxView setImage:nil];
2210
2211         [m_osxView setNeedsDisplay:YES];
2212     }
2213 }
2214
2215 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2216 {
2217     if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2218     {
2219         NSCellImagePosition pos;
2220         switch ( dir )
2221         {
2222             case wxLEFT:
2223                 pos = NSImageLeft;
2224                 break;
2225
2226             case wxRIGHT:
2227                 pos = NSImageRight;
2228                 break;
2229
2230             case wxTOP:
2231                 pos = NSImageAbove;
2232                 break;
2233
2234             case wxBOTTOM:
2235                 pos = NSImageBelow;
2236                 break;
2237
2238             default:
2239                 wxFAIL_MSG( "invalid image position" );
2240                 pos = NSNoImage;
2241         }
2242
2243         [m_osxView setImagePosition:pos];
2244     }
2245 }
2246
2247 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2248 {
2249     // implementation in subclass
2250 }
2251
2252 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2253 {
2254     r->x = r->y = r->width = r->height = 0;
2255
2256     if (  [m_osxView respondsToSelector:@selector(sizeToFit)] )
2257     {
2258         NSRect former = [m_osxView frame];
2259         [m_osxView sizeToFit];
2260         NSRect best = [m_osxView frame];
2261         [m_osxView setFrame:former];
2262         r->width = (int)best.size.width;
2263         r->height = (int)best.size.height;
2264     }
2265 }
2266
2267 bool wxWidgetCocoaImpl::IsEnabled() const
2268 {
2269     NSView* targetView = m_osxView;
2270     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2271         targetView = [(NSScrollView*) m_osxView documentView];
2272
2273     if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2274         return [targetView isEnabled];
2275     return true;
2276 }
2277
2278 void wxWidgetCocoaImpl::Enable( bool enable )
2279 {
2280     NSView* targetView = m_osxView;
2281     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2282         targetView = [(NSScrollView*) m_osxView documentView];
2283
2284     if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2285         [targetView setEnabled:enable];
2286 }
2287
2288 void wxWidgetCocoaImpl::PulseGauge()
2289 {
2290 }
2291
2292 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2293 {
2294 }
2295
2296 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2297 {
2298     NSControlSize size = NSRegularControlSize;
2299
2300     switch ( variant )
2301     {
2302         case wxWINDOW_VARIANT_NORMAL :
2303             size = NSRegularControlSize;
2304             break ;
2305
2306         case wxWINDOW_VARIANT_SMALL :
2307             size = NSSmallControlSize;
2308             break ;
2309
2310         case wxWINDOW_VARIANT_MINI :
2311             size = NSMiniControlSize;
2312             break ;
2313
2314         case wxWINDOW_VARIANT_LARGE :
2315             size = NSRegularControlSize;
2316             break ;
2317
2318         default:
2319             wxFAIL_MSG(wxT("unexpected window variant"));
2320             break ;
2321     }
2322     if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2323         [m_osxView setControlSize:size];
2324     else if ([m_osxView respondsToSelector:@selector(cell)])
2325     {
2326         id cell = [(id)m_osxView cell];
2327         if ([cell respondsToSelector:@selector(setControlSize:)])
2328             [cell setControlSize:size];
2329     }
2330 }
2331
2332 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2333 {
2334     if ([m_osxView respondsToSelector:@selector(setFont:)])
2335         [m_osxView setFont: font.OSXGetNSFont()];
2336     if ([m_osxView respondsToSelector:@selector(setTextColor:)])
2337         [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2338                                                                  green:(CGFloat) (col.Green() / 255.0)
2339                                                                   blue:(CGFloat) (col.Blue() / 255.0)
2340                                                                  alpha:(CGFloat) (col.Alpha() / 255.0)]];
2341 }
2342
2343 NSToolTipTag tt = 0;
2344
2345 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2346 {
2347     if (tooltip)
2348     {
2349         /*
2350         if ( tt != 0 )
2351         {
2352             [m_osxView removeToolTip:tt];
2353             tt = 0;
2354         }
2355          */
2356         wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2357         [m_osxView setToolTip: cf.AsNSString()];
2358         // tt = [m_osxView addToolTipRect:[m_osxView bounds] owner:m_osxView userData:nil];
2359     }
2360     else 
2361     {
2362         if ( tt != 0 )
2363         {
2364             [m_osxView removeToolTip:tt];
2365             tt = 0;
2366         }
2367     }
2368
2369 }
2370
2371 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2372 {
2373     WXWidget c =  control ? control : (WXWidget) m_osxView;
2374     wxWidgetImpl::Associate( c, this ) ;
2375     if ([c respondsToSelector:@selector(setAction:)])
2376     {
2377         [c setTarget: c];
2378         [c setAction: @selector(controlAction:)];
2379         if ([c respondsToSelector:@selector(setDoubleAction:)])
2380         {
2381             [c setDoubleAction: @selector(controlDoubleAction:)];
2382         }
2383
2384     }
2385 }
2386
2387 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2388 {
2389     wxKeyEvent wxevent(wxEVT_CHAR);
2390     SetupKeyEvent( wxevent, event, text );
2391
2392     return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2393 }
2394
2395 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2396 {
2397     wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2398     SetupKeyEvent( wxevent, event );
2399
2400     // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2401     // the key is pressed, not when it's released (the type of wxevent is
2402     // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2403     if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2404     {
2405         wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2406         if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2407                 && !eventHook.IsNextEventAllowed() )
2408             return true;
2409     }
2410
2411     bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2412
2413     // this will fire higher level events, like insertText, to help
2414     // us handle EVT_CHAR, etc.
2415
2416     if ( !result )
2417     {
2418         if ( IsUserPane() && [event type] == NSKeyDown)
2419         {
2420             long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2421             
2422             if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2423             {
2424                 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2425                 wxKeyEvent wxevent2(wxevent) ;
2426                 wxevent2.SetEventType(wxEVT_CHAR);
2427                 wxevent2.m_keyCode = keycode;
2428                 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2429             }
2430             else
2431             {
2432                 if ( !wxevent.CmdDown() )
2433                 {
2434                     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2435                         [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2436                     else
2437                         [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2438                     result = true;
2439                 }
2440             }
2441         }
2442     }
2443
2444     return result;
2445 }
2446
2447 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2448 {
2449     wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2450     SetupMouseEvent(wxevent , event) ;
2451
2452     return GetWXPeer()->HandleWindowEvent(wxevent);
2453 }
2454
2455 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2456 {
2457     wxWindow* thisWindow = GetWXPeer();
2458     if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2459     {
2460         thisWindow->MacInvalidateBorders();
2461     }
2462
2463     if ( receivedFocus )
2464     {
2465         wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2466         wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2467         thisWindow->HandleWindowEvent(eventFocus);
2468
2469 #if wxUSE_CARET
2470         if ( thisWindow->GetCaret() )
2471             thisWindow->GetCaret()->OnSetFocus();
2472 #endif
2473
2474         wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2475         event.SetEventObject(thisWindow);
2476         if (otherWindow)
2477             event.SetWindow(otherWindow->GetWXPeer());
2478         thisWindow->HandleWindowEvent(event) ;
2479     }
2480     else // !receivedFocuss
2481     {
2482 #if wxUSE_CARET
2483         if ( thisWindow->GetCaret() )
2484             thisWindow->GetCaret()->OnKillFocus();
2485 #endif
2486
2487         wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2488
2489         wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2490         event.SetEventObject(thisWindow);
2491         if (otherWindow)
2492             event.SetWindow(otherWindow->GetWXPeer());
2493         thisWindow->HandleWindowEvent(event) ;
2494     }
2495 }
2496
2497 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2498 {
2499     if ( !wxIsBusy() )
2500     {
2501         NSPoint location = [NSEvent mouseLocation];
2502         location = [[m_osxView window] convertScreenToBase:location];
2503         NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2504
2505         if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2506         {
2507             [(NSCursor*)cursor.GetHCURSOR() set];
2508         }
2509     }
2510     [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2511 }
2512
2513 void wxWidgetCocoaImpl::CaptureMouse()
2514 {
2515     [[m_osxView window] disableCursorRects];
2516 }
2517
2518 void wxWidgetCocoaImpl::ReleaseMouse()
2519 {
2520     [[m_osxView window] enableCursorRects];
2521 }
2522
2523 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2524 {
2525     m_isFlipped = flipped;
2526 }
2527
2528 //
2529 // Factory methods
2530 //
2531
2532 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2533     wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2534     long WXUNUSED(style), long WXUNUSED(extraStyle))
2535 {
2536     NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2537     wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2538
2539     // temporary hook for dnd
2540     [v registerForDraggedTypes:[NSArray arrayWithObjects:
2541         NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2542
2543     wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2544     return c;
2545 }
2546
2547 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2548 {
2549     NSWindow* tlw = now->GetWXWindow();
2550     
2551     wxWidgetCocoaImpl* c = NULL;
2552     if ( now->IsNativeWindowWrapper() )
2553     {
2554         NSView* cv = [tlw contentView];
2555         c = new wxWidgetCocoaImpl( now, cv, true );
2556         // increase ref count, because the impl destructor will decrement it again
2557         CFRetain(cv);
2558         if ( !now->IsShown() )
2559             [cv setHidden:NO];
2560         
2561     }
2562     else
2563     {
2564         wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2565         c = new wxWidgetCocoaImpl( now, v, true );
2566         c->InstallEventHandler();
2567         [tlw setContentView:v];
2568     }
2569     return c;
2570 }