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