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