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