adding a more extensive version to arrive at the impl when given a native control...
[wxWidgets.git] / src / osx / cocoa / window.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/osx/cocoa/window.mm
3 // Purpose:     widgets (non tlw) for cocoa
4 // Author:      Stefan Csomor
5 // Modified by:
6 // Created:     2008-06-20
7 // RCS-ID:      $Id$
8 // Copyright:   (c) Stefan Csomor
9 // Licence:     wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #ifndef WX_PRECOMP
15     #include "wx/dcclient.h"
16     #include "wx/frame.h"
17     #include "wx/log.h"
18     #include "wx/textctrl.h"
19     #include "wx/combobox.h"
20 #endif
21
22 #ifdef __WXMAC__
23     #include "wx/osx/private.h"
24 #endif
25
26 #include "wx/evtloop.h"
27
28 #if wxUSE_CARET
29     #include "wx/caret.h"
30 #endif
31
32 #if wxUSE_DRAG_AND_DROP
33     #include "wx/dnd.h"
34 #endif
35
36 #if wxUSE_TOOLTIPS
37     #include "wx/tooltip.h"
38 #endif
39
40 #include <objc/objc-runtime.h>
41
42 // Get the window with the focus
43
44 NSView* GetViewFromResponder( NSResponder* responder )
45 {
46     NSView* view = nil;
47     if ( [responder isKindOfClass:[NSTextView class]] )
48     {
49         NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50         if ( [delegate isKindOfClass:[NSTextField class] ] )
51             view = delegate;
52         else
53             view =  (NSView*) responder;
54     }
55     else
56     {
57         if ( [responder isKindOfClass:[NSView class]] )
58             view = (NSView*) responder;
59     }
60     return view;
61 }
62
63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
64 {
65     NSView* focusedView = nil;
66     if ( keyWindow != nil )
67         focusedView = GetViewFromResponder([keyWindow firstResponder]);
68
69     return focusedView;
70 }
71
72 WXWidget wxWidgetImpl::FindFocus()
73 {
74     return GetFocusedViewInWindow( [NSApp keyWindow] );;
75 }
76
77 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 = GetViewFromResponder(responder);
1366
1367     wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1368     
1369     // NSScrollViews can have their subviews like NSClipView getting focus
1370     // therefore check and use the NSScrollView peer in that case
1371     if ( otherWindow == NULL && [[otherView superview] isKindOfClass:[NSScrollView class]])
1372         otherWindow = FindFromWXWidget([otherView superview]);
1373     
1374     // It doesn't make sense to notify about the loss of focus if it's the same
1375     // control in the end, and just a different subview
1376     if ( otherWindow == this )
1377         return r;
1378     
1379     // NSTextViews have an editor as true responder, therefore the might get the
1380     // resign notification if their editor takes over, don't trigger any event then
1381     if ( r && !m_hasEditor)
1382     {
1383         DoNotifyFocusEvent( false, otherWindow );
1384     }
1385     return r;
1386 }
1387
1388 #if !wxOSX_USE_NATIVE_FLIPPED
1389
1390 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1391 {
1392     return m_isFlipped;
1393 }
1394
1395 #endif
1396
1397 #define OSX_DEBUG_DRAWING 0
1398
1399 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1400 {
1401     // preparing the update region
1402     
1403     wxRegion updateRgn;
1404
1405     // since adding many rects to a region is a costly process, by default use the bounding rect
1406 #if 0
1407     const NSRect *rects;
1408     NSInteger count;
1409     [slf getRectsBeingDrawn:&rects count:&count];
1410     for ( int i = 0 ; i < count ; ++i )
1411     {
1412         updateRgn.Union(wxFromNSRect(slf, rects[i]));
1413     }
1414 #else
1415     updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1416 #endif
1417     
1418     wxWindow* wxpeer = GetWXPeer();
1419
1420     if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1421     {
1422         // as this update region is in native window locals we must adapt it to wx window local
1423         updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1424     }
1425     
1426     // Restrict the update region to the shape of the window, if any, and also
1427     // remember the region that we need to clear later.
1428     wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1429     const bool isTopLevel = tlwParent == wxpeer;
1430     wxRegion clearRgn;
1431     if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1432     {
1433         if ( isTopLevel )
1434             clearRgn = updateRgn;
1435
1436         int xoffset = 0, yoffset = 0;
1437         wxRegion rgn = tlwParent->GetShape();
1438         wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1439         rgn.Offset( xoffset, yoffset );
1440         updateRgn.Intersect(rgn);
1441
1442         if ( isTopLevel )
1443         {
1444             // Exclude the window shape from the region to be cleared below.
1445             rgn.Xor(wxpeer->GetSize());
1446             clearRgn.Intersect(rgn);
1447         }
1448     }
1449     
1450     wxpeer->GetUpdateRegion() = updateRgn;
1451
1452     // setting up the drawing context
1453     
1454     CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1455     CGContextSaveGState( context );
1456     
1457 #if OSX_DEBUG_DRAWING
1458     CGContextBeginPath( context );
1459     CGContextMoveToPoint(context, 0, 0);
1460     NSRect bounds = [slf bounds];
1461     CGContextAddLineToPoint(context, 10, 0);
1462     CGContextMoveToPoint(context, 0, 0);
1463     CGContextAddLineToPoint(context, 0, 10);
1464     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1465     CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1466     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1467     CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1468     CGContextClosePath( context );
1469     CGContextStrokePath(context);
1470 #endif
1471     
1472     if ( ![slf isFlipped] )
1473     {
1474         CGContextTranslateCTM( context, 0,  [m_osxView bounds].size.height );
1475         CGContextScaleCTM( context, 1, -1 );
1476     }
1477     
1478     wxpeer->MacSetCGContextRef( context );
1479
1480     bool handled = wxpeer->MacDoRedraw( 0 );
1481     CGContextRestoreGState( context );
1482
1483     CGContextSaveGState( context );
1484     if ( !handled )
1485     {
1486         // call super
1487         SEL _cmd = @selector(drawRect:);
1488         wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1489         superimpl(slf, _cmd, *(NSRect*)rect);
1490         CGContextRestoreGState( context );
1491         CGContextSaveGState( context );
1492     }
1493     // as we called restore above, we have to flip again if necessary
1494     if ( ![slf isFlipped] )
1495     {
1496         CGContextTranslateCTM( context, 0,  [m_osxView bounds].size.height );
1497         CGContextScaleCTM( context, 1, -1 );
1498     }
1499
1500     if ( isTopLevel )
1501     {
1502         // We also need to explicitly draw the part of the top level window
1503         // outside of its region with transparent colour to ensure that it is
1504         // really transparent.
1505         if ( clearRgn.IsOk() )
1506         {
1507             wxMacCGContextStateSaver saveState(context);
1508             wxWindowDC dc(wxpeer);
1509             dc.SetBackground(wxBrush(wxTransparentColour));
1510             dc.SetDeviceClippingRegion(clearRgn);
1511             dc.Clear();
1512         }
1513
1514 #if wxUSE_GRAPHICS_CONTEXT
1515         // If the window shape is defined by a path, stroke the path to show
1516         // the window border.
1517         const wxGraphicsPath& path = tlwParent->GetShapePath();
1518         if ( !path.IsNull() )
1519         {
1520             CGContextSetLineWidth(context, 1);
1521             CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1522             CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1523             CGContextStrokePath(context);
1524         }
1525 #endif // wxUSE_GRAPHICS_CONTEXT
1526     }
1527
1528     wxpeer->MacPaintChildrenBorders();
1529     wxpeer->MacSetCGContextRef( NULL );
1530     CGContextRestoreGState( context );
1531 }
1532
1533 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1534 {
1535     wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1536     if ( wxpeer )
1537     {
1538         wxpeer->OSXSimulateFocusEvents();
1539         wxpeer->OSXHandleClicked(0);
1540     }
1541 }
1542
1543 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1544 {
1545 }
1546
1547 void wxWidgetCocoaImpl::controlTextDidChange()
1548 {
1549     wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1550     if ( wxpeer ) 
1551     {
1552         // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1553         wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1554         wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1555         if ( tc )
1556             tc->SendTextUpdatedEventIfAllowed();
1557         else if ( cb )
1558             cb->SendTextUpdatedEventIfAllowed();
1559         else 
1560         {
1561             wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1562         }
1563     }
1564 }
1565
1566 //
1567
1568 #if OBJC_API_VERSION >= 2
1569
1570 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1571     class_addMethod(c, s, i, t );
1572
1573 #else
1574
1575 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1576     { s, (char*) t, i },
1577
1578 #endif
1579
1580 void wxOSXCocoaClassAddWXMethods(Class c)
1581 {
1582
1583 #if OBJC_API_VERSION < 2
1584     static objc_method wxmethods[] =
1585     {
1586 #endif
1587
1588     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1589     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1590     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1591
1592     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1593     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1594     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1595
1596     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1597
1598     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1599     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1600     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1601     
1602     wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1603
1604     wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1605     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1606     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1607
1608     wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1609
1610     wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1611     wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1612     wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1613
1614     wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1615
1616     wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1617
1618     wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1619     wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1620     wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1621
1622 #if !wxOSX_USE_NATIVE_FLIPPED
1623     wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1624 #endif
1625     wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1626
1627     wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1628     wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1629
1630 #if wxUSE_DRAG_AND_DROP
1631     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1632     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1633     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1634     wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1635 #endif
1636
1637 #if OBJC_API_VERSION < 2
1638     } ;
1639     static int method_count = WXSIZEOF( wxmethods );
1640     static objc_method_list *wxmethodlist = NULL;
1641     if ( wxmethodlist == NULL )
1642     {
1643         wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1644         memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1645         wxmethodlist->method_count = method_count;
1646         wxmethodlist->obsolete = 0;
1647     }
1648     class_addMethods( c, wxmethodlist );
1649 #endif
1650 }
1651
1652 //
1653 // C++ implementation class
1654 //
1655
1656 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1657
1658 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1659     wxWidgetImpl( peer, isRootControl, isUserPane )
1660 {
1661     Init();
1662     m_osxView = w;
1663
1664     // check if the user wants to create the control initially hidden
1665     if ( !peer->IsShown() )
1666         SetVisibility(false);
1667
1668     // gc aware handling
1669     if ( m_osxView )
1670         CFRetain(m_osxView);
1671     [m_osxView release];
1672 }
1673
1674 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1675 {
1676     Init();
1677 }
1678
1679 void wxWidgetCocoaImpl::Init()
1680 {
1681     m_osxView = NULL;
1682 #if !wxOSX_USE_NATIVE_FLIPPED
1683     m_isFlipped = true;
1684 #endif
1685     m_lastKeyDownEvent = NULL;
1686     m_hasEditor = false;
1687 }
1688
1689 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1690 {
1691     RemoveAssociations( this );
1692
1693     if ( !IsRootControl() )
1694     {
1695         NSView *sv = [m_osxView superview];
1696         if ( sv != nil )
1697             [m_osxView removeFromSuperview];
1698     }
1699     // gc aware handling
1700     if ( m_osxView )
1701         CFRelease(m_osxView);
1702 }
1703
1704 bool wxWidgetCocoaImpl::IsVisible() const
1705 {
1706     return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1707 }
1708
1709 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1710 {
1711     [m_osxView setHidden:(visible ? NO:YES)];
1712 }
1713
1714 // ----------------------------------------------------------------------------
1715 // window animation stuff
1716 // ----------------------------------------------------------------------------
1717
1718 // define a delegate used to refresh the window during animation
1719 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1720 {
1721     wxWindow *m_win;
1722     bool m_isDone;
1723 }
1724
1725 - (id)init:(wxWindow *)win;
1726
1727 - (bool)isDone;
1728
1729 // NSAnimationDelegate methods
1730 - (void)animationDidEnd:(NSAnimation*)animation;
1731 - (void)animation:(NSAnimation*)animation
1732         didReachProgressMark:(NSAnimationProgress)progress;
1733 @end
1734
1735 @implementation wxNSAnimationDelegate
1736
1737 - (id)init:(wxWindow *)win
1738 {
1739     self = [super init];
1740
1741     m_win = win;
1742     m_isDone = false;
1743
1744     return self;
1745 }
1746
1747 - (bool)isDone
1748 {
1749     return m_isDone;
1750 }
1751
1752 - (void)animation:(NSAnimation*)animation
1753         didReachProgressMark:(NSAnimationProgress)progress
1754 {
1755     wxUnusedVar(animation);
1756     wxUnusedVar(progress);
1757
1758     m_win->SendSizeEvent();
1759 }
1760
1761 - (void)animationDidEnd:(NSAnimation*)animation
1762 {
1763     wxUnusedVar(animation);
1764     m_isDone = true;
1765 }
1766
1767 @end
1768
1769 /* static */
1770 bool
1771 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1772                                               bool show,
1773                                               wxShowEffect effect,
1774                                               unsigned timeout)
1775 {
1776     // create the dictionary describing the animation to perform on this view
1777     NSObject * const
1778         viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1779     NSMutableDictionary * const
1780         dict = [NSMutableDictionary dictionaryWithCapacity:4];
1781     [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1782
1783     // determine the start and end rectangles assuming we're hiding the window
1784     const wxRect rectOrig = win->GetRect();
1785     wxRect rectStart,
1786            rectEnd;
1787     rectStart =
1788     rectEnd = rectOrig;
1789
1790     if ( show )
1791     {
1792         if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1793                 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1794             effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1795         else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1796                     effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1797             effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1798         else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1799                     effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1800             effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1801         else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1802                     effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1803             effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1804     }
1805
1806     switch ( effect )
1807     {
1808         case wxSHOW_EFFECT_ROLL_TO_LEFT:
1809         case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1810             rectEnd.width = 0;
1811             break;
1812
1813         case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1814         case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1815             rectEnd.x = rectStart.GetRight();
1816             rectEnd.width = 0;
1817             break;
1818
1819         case wxSHOW_EFFECT_ROLL_TO_TOP:
1820         case wxSHOW_EFFECT_SLIDE_TO_TOP:
1821             rectEnd.height = 0;
1822             break;
1823
1824         case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1825         case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1826             rectEnd.y = rectStart.GetBottom();
1827             rectEnd.height = 0;
1828             break;
1829
1830         case wxSHOW_EFFECT_EXPAND:
1831             rectEnd.x = rectStart.x + rectStart.width / 2;
1832             rectEnd.y = rectStart.y + rectStart.height / 2;
1833             rectEnd.width =
1834             rectEnd.height = 0;
1835             break;
1836
1837         case wxSHOW_EFFECT_BLEND:
1838             [dict setObject:(show ? NSViewAnimationFadeInEffect
1839                                   : NSViewAnimationFadeOutEffect)
1840                   forKey:NSViewAnimationEffectKey];
1841             break;
1842
1843         case wxSHOW_EFFECT_NONE:
1844         case wxSHOW_EFFECT_MAX:
1845             wxFAIL_MSG( "unexpected animation effect" );
1846             return false;
1847
1848         default:
1849             wxFAIL_MSG( "unknown animation effect" );
1850             return false;
1851     };
1852
1853     if ( show )
1854     {
1855         // we need to restore it to the original rectangle instead of making it
1856         // disappear
1857         wxSwap(rectStart, rectEnd);
1858
1859         // and as the window is currently hidden, we need to show it for the
1860         // animation to be visible at all (but don't restore it at its full
1861         // rectangle as it shouldn't appear immediately)
1862         win->SetSize(rectStart);
1863         win->Show();
1864     }
1865
1866     NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1867                                     ? [(NSView *)viewOrWin superview]
1868                                     : nil;
1869     const NSRect rStart = wxToNSRect(parentView, rectStart);
1870     const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1871
1872     [dict setObject:[NSValue valueWithRect:rStart]
1873           forKey:NSViewAnimationStartFrameKey];
1874     [dict setObject:[NSValue valueWithRect:rEnd]
1875           forKey:NSViewAnimationEndFrameKey];
1876
1877     // create an animation using the values in the above dictionary
1878     NSViewAnimation * const
1879         anim = [[NSViewAnimation alloc]
1880                 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1881
1882     if ( !timeout )
1883     {
1884         // what is a good default duration? Windows uses 200ms, Web frameworks
1885         // use anything from 250ms to 1s... choose something in the middle
1886         timeout = 500;
1887     }
1888
1889     [anim setDuration:timeout/1000.];   // duration is in seconds here
1890
1891     // if the window being animated changes its layout depending on its size
1892     // (which is almost always the case) we need to redo it during animation
1893     //
1894     // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1895     // controls in wxInfoBar visibly jump around)
1896     const int NUM_LAYOUTS = 20;
1897     for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1898         [anim addProgressMark:f];
1899
1900     wxNSAnimationDelegate * const
1901         animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1902     [anim setDelegate:animDelegate];
1903     [anim startAnimation];
1904
1905     // Cocoa is capable of doing animation asynchronously or even from separate
1906     // thread but wx API doesn't provide any way to be notified about the
1907     // animation end and without this we really must ensure that the window has
1908     // the expected (i.e. the same as if a simple Show() had been used) size
1909     // when we return, so block here until the animation finishes
1910     //
1911     // notice that because the default animation mode is NSAnimationBlocking,
1912     // no user input events ought to be processed from here
1913     {
1914         wxEventLoopGuarantor ensureEventLoopExistence;
1915         wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1916         while ( ![animDelegate isDone] )
1917             loop->Dispatch();
1918     }
1919
1920     if ( !show )
1921     {
1922         // NSViewAnimation is smart enough to hide the NSView being animated at
1923         // the end but we also must ensure that it's hidden for wx too
1924         win->Hide();
1925
1926         // and we must also restore its size because it isn't expected to
1927         // change just because the window was hidden
1928         win->SetSize(rectOrig);
1929     }
1930     else
1931     {
1932         // refresh it once again after the end to ensure that everything is in
1933         // place
1934         win->SendSizeEvent();
1935     }
1936
1937     [anim setDelegate:nil];
1938     [animDelegate release];
1939     [anim release];
1940
1941     return true;
1942 }
1943
1944 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1945                                        wxShowEffect effect,
1946                                        unsigned timeout)
1947 {
1948     return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1949 }
1950
1951 /* note that the drawing order between siblings is not defined under 10.4 */
1952 /* only starting from 10.5 the subview order is respected */
1953
1954 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1955  * NSInteger post-Leopard.  Pre-Leopard the Cocoa toolkit expects a function
1956  * returning int and not NSComparisonResult.  Post-Leopard the Cocoa toolkit
1957  * expects a function returning the new non-enum NSComparsionResult.
1958  * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1959  */
1960 #if defined(NSINTEGER_DEFINED)
1961 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1962 #else
1963 typedef int CocoaWindowCompareFunctionResult;
1964 #endif
1965
1966 class CocoaWindowCompareContext
1967 {
1968     wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1969 public:
1970     CocoaWindowCompareContext(); // Not implemented
1971     CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1972     {
1973         m_target = target;
1974         // Cocoa sorts subviews in-place.. make a copy
1975         m_subviews = [subviews copy];
1976     }
1977     
1978     ~CocoaWindowCompareContext()
1979     {   // release the copy
1980         [m_subviews release];
1981     }
1982     NSView* target()
1983     {   return m_target; }
1984     
1985     NSArray* subviews()
1986     {   return m_subviews; }
1987     
1988     /* Helper function that returns the comparison based off of the original ordering */
1989     CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1990     {
1991         NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1992         NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1993         // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1994         // likely compare higher than the other view which is reasonable considering the only way that
1995         // can happen is if the subview was added after our call to subviews but before the call to
1996         // sortSubviewsUsingFunction:context:.  Thus we don't bother checking.  Particularly because
1997         // that case should never occur anyway because that would imply a multi-threaded GUI call
1998         // which is a big no-no with Cocoa.
1999                 
2000         // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
2001         NSComparisonResult result = (firstI < secondI)
2002                 ?   NSOrderedAscending /* -1 */
2003                 :   (firstI > secondI)
2004                 ?   NSOrderedDescending /* 1 */
2005                 :   NSOrderedSame /* 0 */;
2006                 
2007         return result;
2008     }
2009 private:
2010     /* The subview we are trying to Raise or Lower */
2011     NSView *m_target;
2012     /* A copy of the original array of subviews */
2013     NSArray *m_subviews;
2014 };
2015
2016 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2017  * the target view is always higher than every other view.  When comparing two views neither of
2018  * which is the target, it returns the correct response based on the original ordering
2019  */
2020 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2021 {
2022     CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2023     // first should be ordered higher
2024     if(first==compareContext->target())
2025         return NSOrderedDescending;
2026     // second should be ordered higher
2027     if(second==compareContext->target())
2028         return NSOrderedAscending;
2029     return compareContext->CompareUsingOriginalOrdering(first,second);
2030 }
2031
2032 void wxWidgetCocoaImpl::Raise()
2033 {
2034         NSView* nsview = m_osxView;
2035         
2036     NSView *superview = [nsview superview];
2037     CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2038         
2039     [superview sortSubviewsUsingFunction:
2040          CocoaRaiseWindowCompareFunction
2041                                                                  context: &compareContext];
2042         
2043 }
2044
2045 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2046  * the target view is always lower than every other view.  When comparing two views neither of
2047  * which is the target, it returns the correct response based on the original ordering
2048  */
2049 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2050 {
2051     CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2052     // first should be ordered lower
2053     if(first==compareContext->target())
2054         return NSOrderedAscending;
2055     // second should be ordered lower
2056     if(second==compareContext->target())
2057         return NSOrderedDescending;
2058     return compareContext->CompareUsingOriginalOrdering(first,second);
2059 }
2060
2061 void wxWidgetCocoaImpl::Lower()
2062 {
2063         NSView* nsview = m_osxView;
2064         
2065     NSView *superview = [nsview superview];
2066     CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2067         
2068     [superview sortSubviewsUsingFunction:
2069          CocoaLowerWindowCompareFunction
2070                                                                  context: &compareContext];
2071 }
2072
2073 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2074 {
2075 #if 1
2076     SetNeedsDisplay() ;
2077 #else
2078     // We should do something like this, but it wasn't working in 10.4.
2079     if (GetNeedsDisplay() )
2080     {
2081         SetNeedsDisplay() ;
2082     }
2083     NSRect r = wxToNSRect( [m_osxView superview], *rect );
2084     NSSize offset = NSMakeSize((float)dx, (float)dy);
2085     [m_osxView scrollRect:r by:offset];
2086 #endif
2087 }
2088
2089 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2090 {
2091     wxWindowMac* parent = GetWXPeer()->GetParent();
2092     // under Cocoa we might have a contentView in the wxParent to which we have to
2093     // adjust the coordinates
2094     if (parent && [m_osxView superview] != parent->GetHandle() )
2095     {
2096         int cx = 0,cy = 0,cw = 0,ch = 0;
2097         if ( parent->GetPeer() )
2098         {
2099             parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2100             x -= cx;
2101             y -= cy;
2102         }
2103     }
2104     [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2105     NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2106     [m_osxView setFrame:r];
2107     [[m_osxView superview] setNeedsDisplayInRect:r];
2108 }
2109
2110 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2111 {
2112     wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2113     x = r.GetLeft();
2114     y = r.GetTop();
2115     
2116     // under Cocoa we might have a contentView in the wxParent to which we have to
2117     // adjust the coordinates
2118     wxWindowMac* parent = GetWXPeer()->GetParent();
2119     if (parent && [m_osxView superview] != parent->GetHandle() )
2120     {
2121         int cx = 0,cy = 0,cw = 0,ch = 0;
2122         if ( parent->GetPeer() )
2123         {
2124             parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2125             x += cx;
2126             y += cy;
2127         }
2128     }
2129 }
2130
2131 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2132 {
2133     NSRect rect = [m_osxView frame];
2134     width = (int)rect.size.width;
2135     height = (int)rect.size.height;
2136 }
2137
2138 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2139 {
2140     if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2141     {
2142         NSView* cv = [m_osxView contentView];
2143
2144         NSRect bounds = [m_osxView bounds];
2145         NSRect rect = [cv frame];
2146
2147         int y = (int)rect.origin.y;
2148         int x = (int)rect.origin.x;
2149         if ( ![ m_osxView isFlipped ] )
2150             y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2151         left = x;
2152         top = y;
2153         width = (int)rect.size.width;
2154         height = (int)rect.size.height;
2155     }
2156     else
2157     {
2158         left = top = 0;
2159         GetSize( width, height );
2160     }
2161 }
2162
2163 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2164 {
2165     if ( where )
2166         [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2167     else
2168         [m_osxView setNeedsDisplay:YES];
2169 }
2170
2171 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2172 {
2173     return [m_osxView needsDisplay];
2174 }
2175
2176 bool wxWidgetCocoaImpl::CanFocus() const
2177 {
2178     return [m_osxView canBecomeKeyView] == YES;
2179 }
2180
2181 bool wxWidgetCocoaImpl::HasFocus() const
2182 {
2183     return ( FindFocus() == m_osxView );
2184 }
2185
2186 bool wxWidgetCocoaImpl::SetFocus()
2187 {
2188     if ( !CanFocus() )
2189         return false;
2190
2191     // TODO remove if no issues arise: should not raise the window, only assign focus
2192     //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2193     [[m_osxView window] makeFirstResponder: m_osxView] ;
2194     return true;
2195 }
2196
2197 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2198 {
2199     [m_osxView unregisterDraggedTypes];
2200     
2201     if ( target == NULL )
2202         return;
2203     
2204     wxDataObject* dobj = target->GetDataObject();
2205     
2206     if( dobj )
2207     {
2208         CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2209         dobj->AddSupportedTypes(typesarray);
2210         NSView* targetView = m_osxView;
2211         if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2212             targetView = [(NSScrollView*) m_osxView documentView];
2213
2214         [targetView registerForDraggedTypes:(NSArray*)typesarray];
2215         CFRelease(typesarray);
2216     }
2217 }
2218
2219 void wxWidgetCocoaImpl::RemoveFromParent()
2220 {
2221     [m_osxView removeFromSuperview];
2222 }
2223
2224 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2225 {
2226     NSView* container = parent->GetWXWidget() ;
2227     wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2228     [container addSubview:m_osxView];
2229     
2230     if( m_wxPeer->IsFrozen() )
2231         [[m_osxView window] disableFlushWindow];
2232 }
2233
2234 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2235 {
2236     NSView* targetView = m_osxView;
2237     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2238         targetView = [(NSScrollView*) m_osxView documentView];
2239
2240     if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2241     {
2242         [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2243                                                                 green:(CGFloat) (col.Green() / 255.0)
2244                                                                  blue:(CGFloat) (col.Blue() / 255.0)
2245                                                                 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2246     }
2247 }
2248
2249 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2250 {
2251     BOOL opaque = ( style == wxBG_STYLE_PAINT );
2252     
2253     if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2254     {
2255         [m_osxView setOpaque: opaque];
2256     }
2257     
2258     return true ;
2259 }
2260
2261 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2262 {
2263     if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2264     {
2265         wxCFStringRef cf( title , encoding );
2266         [m_osxView setTitle:cf.AsNSString()];
2267     }
2268     else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2269     {
2270         wxCFStringRef cf( title , encoding );
2271         [m_osxView setStringValue:cf.AsNSString()];
2272     }
2273 }
2274
2275
2276 void  wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2277 {
2278     NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2279     p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2280     *pt = wxFromNSPoint( to->GetWXWidget(), p );
2281 }
2282
2283 wxInt32 wxWidgetCocoaImpl::GetValue() const
2284 {
2285     return [(NSControl*)m_osxView intValue];
2286 }
2287
2288 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2289 {
2290     if (  [m_osxView respondsToSelector:@selector(setIntValue:)] )
2291     {
2292         [m_osxView setIntValue:v];
2293     }
2294     else if (  [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2295     {
2296         [m_osxView setFloatValue:(double)v];
2297     }
2298     else if (  [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2299     {
2300         [m_osxView setDoubleValue:(double)v];
2301     }
2302 }
2303
2304 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2305 {
2306     if (  [m_osxView respondsToSelector:@selector(setMinValue:)] )
2307     {
2308         [m_osxView setMinValue:(double)v];
2309     }
2310 }
2311
2312 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2313 {
2314     if (  [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2315     {
2316         [m_osxView setMaxValue:(double)v];
2317     }
2318 }
2319
2320 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2321 {
2322     if (  [m_osxView respondsToSelector:@selector(minValue)] )
2323     {
2324         return (int)[m_osxView minValue];
2325     }
2326     return 0;
2327 }
2328
2329 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2330 {
2331     if (  [m_osxView respondsToSelector:@selector(maxValue)] )
2332     {
2333         return (int)[m_osxView maxValue];
2334     }
2335     return 0;
2336 }
2337
2338 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2339 {
2340     wxBitmap bmp;
2341
2342     // TODO: how to create a wxBitmap from NSImage?
2343 #if 0
2344     if ( [m_osxView respondsToSelector:@selector(image:)] )
2345         bmp = [m_osxView image];
2346 #endif
2347
2348     return bmp;
2349 }
2350
2351 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2352 {
2353     if (  [m_osxView respondsToSelector:@selector(setImage:)] )
2354     {
2355         if (bitmap.IsOk())
2356             [m_osxView setImage:bitmap.GetNSImage()];
2357         else
2358             [m_osxView setImage:nil];
2359
2360         [m_osxView setNeedsDisplay:YES];
2361     }
2362 }
2363
2364 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2365 {
2366     if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2367     {
2368         NSCellImagePosition pos;
2369         switch ( dir )
2370         {
2371             case wxLEFT:
2372                 pos = NSImageLeft;
2373                 break;
2374
2375             case wxRIGHT:
2376                 pos = NSImageRight;
2377                 break;
2378
2379             case wxTOP:
2380                 pos = NSImageAbove;
2381                 break;
2382
2383             case wxBOTTOM:
2384                 pos = NSImageBelow;
2385                 break;
2386
2387             default:
2388                 wxFAIL_MSG( "invalid image position" );
2389                 pos = NSNoImage;
2390         }
2391
2392         [m_osxView setImagePosition:pos];
2393     }
2394 }
2395
2396 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2397 {
2398     // implementation in subclass
2399 }
2400
2401 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2402 {
2403     r->x = r->y = r->width = r->height = 0;
2404
2405     if (  [m_osxView respondsToSelector:@selector(sizeToFit)] )
2406     {
2407         NSRect former = [m_osxView frame];
2408         [m_osxView sizeToFit];
2409         NSRect best = [m_osxView frame];
2410         [m_osxView setFrame:former];
2411         r->width = (int)best.size.width;
2412         r->height = (int)best.size.height;
2413     }
2414 }
2415
2416 bool wxWidgetCocoaImpl::IsEnabled() const
2417 {
2418     NSView* targetView = m_osxView;
2419     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2420         targetView = [(NSScrollView*) m_osxView documentView];
2421
2422     if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2423         return [targetView isEnabled];
2424     return true;
2425 }
2426
2427 void wxWidgetCocoaImpl::Enable( bool enable )
2428 {
2429     NSView* targetView = m_osxView;
2430     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2431         targetView = [(NSScrollView*) m_osxView documentView];
2432
2433     if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2434         [targetView setEnabled:enable];
2435 }
2436
2437 void wxWidgetCocoaImpl::PulseGauge()
2438 {
2439 }
2440
2441 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2442 {
2443 }
2444
2445 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2446 {
2447     NSControlSize size = NSRegularControlSize;
2448
2449     switch ( variant )
2450     {
2451         case wxWINDOW_VARIANT_NORMAL :
2452             size = NSRegularControlSize;
2453             break ;
2454
2455         case wxWINDOW_VARIANT_SMALL :
2456             size = NSSmallControlSize;
2457             break ;
2458
2459         case wxWINDOW_VARIANT_MINI :
2460             size = NSMiniControlSize;
2461             break ;
2462
2463         case wxWINDOW_VARIANT_LARGE :
2464             size = NSRegularControlSize;
2465             break ;
2466
2467         default:
2468             wxFAIL_MSG(wxT("unexpected window variant"));
2469             break ;
2470     }
2471     if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2472         [m_osxView setControlSize:size];
2473     else if ([m_osxView respondsToSelector:@selector(cell)])
2474     {
2475         id cell = [(id)m_osxView cell];
2476         if ([cell respondsToSelector:@selector(setControlSize:)])
2477             [cell setControlSize:size];
2478     }
2479
2480     // we need to propagate this to inner views as well
2481     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2482     {
2483         NSView* targetView = [(NSScrollView*) m_osxView documentView];
2484     
2485         if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2486             [targetView setControlSize:size];
2487         else if ([targetView respondsToSelector:@selector(cell)])
2488         {
2489             id cell = [(id)targetView cell];
2490             if ([cell respondsToSelector:@selector(setControlSize:)])
2491                 [cell setControlSize:size];
2492         }
2493     }
2494 }
2495
2496 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2497 {
2498     NSView* targetView = m_osxView;
2499     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2500         targetView = [(NSScrollView*) m_osxView documentView];
2501
2502     if ([targetView respondsToSelector:@selector(setFont:)])
2503         [targetView setFont: font.OSXGetNSFont()];
2504     if ([targetView respondsToSelector:@selector(setTextColor:)])
2505         [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2506                                                                  green:(CGFloat) (col.Green() / 255.0)
2507                                                                   blue:(CGFloat) (col.Blue() / 255.0)
2508                                                                  alpha:(CGFloat) (col.Alpha() / 255.0)]];
2509 }
2510
2511 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2512 {
2513     if ( tooltip )
2514     {
2515         wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2516         [m_osxView setToolTip: cf.AsNSString()];
2517     }
2518     else 
2519     {
2520         [m_osxView setToolTip:nil];
2521     }
2522 }
2523
2524 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2525 {
2526     WXWidget c =  control ? control : (WXWidget) m_osxView;
2527     wxWidgetImpl::Associate( c, this ) ;
2528     if ([c respondsToSelector:@selector(setAction:)])
2529     {
2530         [c setTarget: c];
2531         [c setAction: @selector(controlAction:)];
2532         if ([c respondsToSelector:@selector(setDoubleAction:)])
2533         {
2534             [c setDoubleAction: @selector(controlDoubleAction:)];
2535         }
2536
2537     }
2538     NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2539     NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2540     [m_osxView addTrackingArea: area];
2541     [area release];
2542  }
2543
2544 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2545 {
2546     wxKeyEvent wxevent(wxEVT_CHAR);
2547     SetupKeyEvent( wxevent, event, text );
2548
2549     return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2550 }
2551
2552 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2553 {
2554     wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2555     SetupKeyEvent( wxevent, event );
2556
2557     // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2558     // the key is pressed, not when it's released (the type of wxevent is
2559     // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2560     if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2561     {
2562         wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2563         if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2564                 && !eventHook.IsNextEventAllowed() )
2565             return true;
2566     }
2567
2568     bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2569
2570     // this will fire higher level events, like insertText, to help
2571     // us handle EVT_CHAR, etc.
2572
2573     if ( !result )
2574     {
2575         if ( [event type] == NSKeyDown)
2576         {
2577             long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2578             
2579             if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2580             {
2581                 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2582                 wxKeyEvent wxevent2(wxevent) ;
2583                 wxevent2.SetEventType(wxEVT_CHAR);
2584                 SetupKeyEvent( wxevent2, event );
2585                 wxevent2.m_keyCode = keycode;
2586                 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2587             }
2588             else if (wxevent.CmdDown())
2589             {
2590                 wxKeyEvent wxevent2(wxevent) ;
2591                 wxevent2.SetEventType(wxEVT_CHAR);
2592                 SetupKeyEvent( wxevent2, event );
2593                 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2594             }
2595             else
2596             {
2597                 if ( IsUserPane() && !wxevent.CmdDown() )
2598                 {
2599                     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2600                         [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2601                     else
2602                         [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2603                     result = true;
2604                 }
2605             }
2606         }
2607     }
2608
2609     return result;
2610 }
2611
2612 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2613 {
2614     wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2615     SetupMouseEvent(wxevent , event) ;
2616     bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2617     
2618     (void)SetupCursor(event);
2619
2620     return result;
2621 }
2622
2623 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2624 {
2625     wxWindow* thisWindow = GetWXPeer();
2626     if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2627     {
2628         thisWindow->MacInvalidateBorders();
2629     }
2630
2631     if ( receivedFocus )
2632     {
2633         wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2634         wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2635         thisWindow->HandleWindowEvent(eventFocus);
2636
2637 #if wxUSE_CARET
2638         if ( thisWindow->GetCaret() )
2639             thisWindow->GetCaret()->OnSetFocus();
2640 #endif
2641
2642         wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2643         event.SetEventObject(thisWindow);
2644         if (otherWindow)
2645             event.SetWindow(otherWindow->GetWXPeer());
2646         thisWindow->HandleWindowEvent(event) ;
2647     }
2648     else // !receivedFocus
2649     {
2650 #if wxUSE_CARET
2651         if ( thisWindow->GetCaret() )
2652             thisWindow->GetCaret()->OnKillFocus();
2653 #endif
2654
2655         wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2656
2657         wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2658         event.SetEventObject(thisWindow);
2659         if (otherWindow)
2660             event.SetWindow(otherWindow->GetWXPeer());
2661         thisWindow->HandleWindowEvent(event) ;
2662     }
2663 }
2664
2665 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2666 {
2667     if ( !wxIsBusy() )
2668     {
2669         NSPoint location = [NSEvent mouseLocation];
2670         location = [[m_osxView window] convertScreenToBase:location];
2671         NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2672
2673         if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2674         {
2675             [(NSCursor*)cursor.GetHCURSOR() set];
2676         }
2677     }
2678 }
2679
2680 void wxWidgetCocoaImpl::CaptureMouse()
2681 {
2682     // TODO remove if we don't get into problems with cursor settings
2683     //    [[m_osxView window] disableCursorRects];
2684 }
2685
2686 void wxWidgetCocoaImpl::ReleaseMouse()
2687 {
2688     // TODO remove if we don't get into problems with cursor settings
2689     //    [[m_osxView window] enableCursorRects];
2690 }
2691
2692 #if !wxOSX_USE_NATIVE_FLIPPED
2693
2694 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2695 {
2696     m_isFlipped = flipped;
2697 }
2698
2699 #endif
2700
2701 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2702 {
2703     if ( enabled )
2704     {
2705         [[m_osxView window] enableFlushWindow];
2706         [m_osxView setNeedsDisplay:YES];
2707     }
2708     else
2709     {
2710         [[m_osxView window] disableFlushWindow];
2711     }
2712 }
2713 //
2714 // Factory methods
2715 //
2716
2717 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2718     wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2719     long WXUNUSED(style), long WXUNUSED(extraStyle))
2720 {
2721     NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2722     wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2723
2724     wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2725     return c;
2726 }
2727
2728 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2729 {
2730     NSWindow* tlw = now->GetWXWindow();
2731     
2732     wxWidgetCocoaImpl* c = NULL;
2733     if ( now->IsNativeWindowWrapper() )
2734     {
2735         NSView* cv = [tlw contentView];
2736         c = new wxWidgetCocoaImpl( now, cv, true );
2737         if ( cv != nil )
2738         {
2739             // increase ref count, because the impl destructor will decrement it again
2740             CFRetain(cv);
2741             if ( !now->IsShown() )
2742                 [cv setHidden:NO];
2743         }
2744     }
2745     else
2746     {
2747         wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2748         c = new wxWidgetCocoaImpl( now, v, true );
2749         c->InstallEventHandler();
2750         [tlw setContentView:v];
2751     }
2752     return c;
2753 }