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