1 /////////////////////////////////////////////////////////////////////////////
 
   2 // Name:        src/osx/cocoa/window.mm
 
   3 // Purpose:     widgets (non tlw) for cocoa
 
   4 // Author:      Stefan Csomor
 
   7 // Copyright:   (c) Stefan Csomor
 
   8 // Licence:     wxWindows licence
 
   9 /////////////////////////////////////////////////////////////////////////////
 
  11 #include "wx/wxprec.h"
 
  14     #include "wx/dcclient.h"
 
  17     #include "wx/textctrl.h"
 
  18     #include "wx/combobox.h"
 
  19     #include "wx/radiobut.h"
 
  23     #include "wx/osx/private.h"
 
  26 #include "wx/evtloop.h"
 
  32 #if wxUSE_DRAG_AND_DROP
 
  37     #include "wx/tooltip.h"
 
  40 #include <objc/objc-runtime.h>
 
  42 // Get the window with the focus
 
  44 NSView* wxOSXGetViewFromResponder( NSResponder* responder )
 
  47     if ( [responder isKindOfClass:[NSTextView class]] )
 
  49         NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
 
  50         if ( [delegate isKindOfClass:[NSTextField class] ] )
 
  53             view =  (NSView*) responder;
 
  57         if ( [responder isKindOfClass:[NSView class]] )
 
  58             view = (NSView*) responder;
 
  63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
 
  65     NSView* focusedView = nil;
 
  66     if ( keyWindow != nil )
 
  67         focusedView = wxOSXGetViewFromResponder([keyWindow firstResponder]);
 
  72 WXWidget wxWidgetImpl::FindFocus()
 
  74     return GetFocusedViewInWindow( [NSApp keyWindow] );;
 
  77 wxWidgetImpl* wxWidgetImpl::FindBestFromWXWidget(WXWidget control)
 
  79     wxWidgetImpl* impl = FindFromWXWidget(control);
 
  81     // NSScrollViews can have their subviews like NSClipView
 
  82     // therefore check and use the NSScrollView peer in that case
 
  83     if ( impl == NULL && [[control superview] isKindOfClass:[NSScrollView class]])
 
  84         impl = FindFromWXWidget([control superview]);
 
  90 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
 
  94     window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
 
  95     wxRect bounds(x,y,w,h);
 
  96     NSView* sv = (window->GetParent()->GetHandle() );
 
  98     return wxToNSRect( sv, bounds );
 
 101 @interface wxNSView : NSView
 
 104     NSTrackingRectTag   _lastToolTipTrackTag;
 
 105     id              _lastToolTipOwner;
 
 112 @interface wxNSView(TextInput) <NSTextInputClient>
 
 114 - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange;
 
 115 - (void)doCommandBySelector:(SEL)aSelector;
 
 116 - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange;
 
 118 - (NSRange)selectedRange;
 
 119 - (NSRange)markedRange;
 
 120 - (BOOL)hasMarkedText;
 
 121 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange;
 
 122 - (NSArray*)validAttributesForMarkedText;
 
 123 - (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange;
 
 124 - (NSUInteger)characterIndexForPoint:(NSPoint)aPoint;
 
 128 @interface NSView(PossibleMethods)
 
 129 - (void)setTitle:(NSString *)aString;
 
 130 - (void)setStringValue:(NSString *)aString;
 
 131 - (void)setIntValue:(int)anInt;
 
 132 - (void)setFloatValue:(float)aFloat;
 
 133 - (void)setDoubleValue:(double)aDouble;
 
 137 - (void)setMinValue:(double)aDouble;
 
 138 - (void)setMaxValue:(double)aDouble;
 
 143 - (void)setEnabled:(BOOL)flag;
 
 145 - (void)setImage:(NSImage *)image;
 
 146 - (void)setControlSize:(NSControlSize)size;
 
 148 - (void)setFont:(NSFont *)fontObject;
 
 152 - (void)setTarget:(id)anObject;
 
 153 - (void)setAction:(SEL)aSelector;
 
 154 - (void)setDoubleAction:(SEL)aSelector;
 
 155 - (void)setBackgroundColor:(NSColor*)aColor;
 
 156 - (void)setOpaque:(BOOL)opaque;
 
 157 - (void)setTextColor:(NSColor *)color;
 
 158 - (void)setImagePosition:(NSCellImagePosition)aPosition;
 
 161 // The following code is a combination of the code listed here:
 
 162 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
 
 163 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
 
 164 // and the code here:
 
 165 // http://inquisitivecocoa.com/category/objective-c/
 
 166 @interface NSEvent (OsGuiUtilsAdditions)
 
 167 - (NSString*) charactersIgnoringModifiersIncludingShift;
 
 170 @implementation NSEvent (OsGuiUtilsAdditions)
 
 171 - (NSString*) charactersIgnoringModifiersIncludingShift {
 
 172     // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
 
 173     // differently than AppKit.
 
 174     NSString* c = [self charactersIgnoringModifiers];
 
 175     if ([c length] == 1) {
 
 176         unichar codepoint = [c characterAtIndex:0];
 
 177         if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
 
 181     // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
 
 182     // modifiers attached.  Actually, that's not quite accurate; we attach the Command modifier
 
 183     // which hints the OS to use Latin characters where possible, which is generally what we want.
 
 184     NSString* result = @"";
 
 185     TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
 
 186     CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
 
 187     CFRelease(currentKeyboard);
 
 189         // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
 
 192     const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
 
 193     if (keyboardLayout) {
 
 194         UInt32 deadKeyState = 0;
 
 195         UniCharCount maxStringLength = 255;
 
 196         UniCharCount actualStringLength = 0;
 
 197         UniChar unicodeString[maxStringLength];
 
 199         OSStatus status = UCKeyTranslate(keyboardLayout,
 
 202                                          cmdKey >> 8,         // force the Command key to "on"
 
 204                                          kUCKeyTranslateNoDeadKeysMask,
 
 211             result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
 
 217 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
 
 221     if ([event type] != NSFlagsChanged)
 
 223         NSString* s = [event charactersIgnoringModifiersIncludingShift];
 
 224         // backspace char reports as delete w/modifiers for some reason
 
 227             if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
 
 229                 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
 
 233                 switch ( [s characterAtIndex:0] )
 
 240                     case NSUpArrowFunctionKey :
 
 243                     case NSDownArrowFunctionKey :
 
 246                     case NSLeftArrowFunctionKey :
 
 249                     case NSRightArrowFunctionKey :
 
 252                     case NSInsertFunctionKey  :
 
 255                     case NSDeleteFunctionKey  :
 
 258                     case NSHomeFunctionKey  :
 
 261             //        case NSBeginFunctionKey  :
 
 262             //            retval = WXK_BEGIN;
 
 264                     case NSEndFunctionKey  :
 
 267                     case NSPageUpFunctionKey  :
 
 270                    case NSPageDownFunctionKey  :
 
 271                         retval = WXK_PAGEDOWN;
 
 273                    case NSHelpFunctionKey  :
 
 277                         int intchar = [s characterAtIndex: 0];
 
 278                         if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
 
 279                             retval = WXK_F1 + (intchar - NSF1FunctionKey );
 
 280                         else if ( intchar > 0 && intchar < 32 )
 
 288     // Some keys don't seem to have constants. The code mimics the approach
 
 289     // taken by WebKit. See:
 
 290     // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
 
 291     switch( [event keyCode] )
 
 296             retval = WXK_CONTROL;
 
 300             retval = WXK_CAPITAL;
 
 303         case 56: // Left Shift
 
 304         case 60: // Right Shift
 
 309         case 61: // Right Alt
 
 313         case 59: // Left Ctrl
 
 314         case 62: // Right Ctrl
 
 315             retval = WXK_RAW_CONTROL;
 
 329     // Check for NUMPAD keys.  For KEY_UP/DOWN events we need to use the
 
 330     // WXK_NUMPAD constants, but for the CHAR event we want to use the
 
 331     // standard ascii values
 
 332     if ( eventType != wxEVT_CHAR )
 
 334         switch( [event keyCode] )
 
 337                 retval = WXK_NUMPAD_DIVIDE;
 
 340                 retval = WXK_NUMPAD_MULTIPLY;
 
 343                 retval = WXK_NUMPAD_SUBTRACT;
 
 346                 retval = WXK_NUMPAD_ADD;
 
 349                 retval = WXK_NUMPAD_ENTER;
 
 352                 retval = WXK_NUMPAD_DECIMAL;
 
 355                 retval = WXK_NUMPAD0;
 
 358                 retval = WXK_NUMPAD1;
 
 361                 retval = WXK_NUMPAD2;
 
 364                 retval = WXK_NUMPAD3;
 
 367                 retval = WXK_NUMPAD4;
 
 370                 retval = WXK_NUMPAD5;
 
 373                 retval = WXK_NUMPAD6;
 
 376                 retval = WXK_NUMPAD7;
 
 379                 retval = WXK_NUMPAD8;
 
 382                 retval = WXK_NUMPAD9;
 
 385                 //retval = [event keyCode];
 
 392 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
 
 394     UInt32 modifiers = [nsEvent modifierFlags] ;
 
 395     int eventType = [nsEvent type];
 
 397     wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
 
 398     wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
 
 399     wxevent.m_altDown = modifiers & NSAlternateKeyMask;
 
 400     wxevent.m_controlDown = modifiers & NSCommandKeyMask;
 
 402     wxevent.m_rawCode = [nsEvent keyCode];
 
 403     wxevent.m_rawFlags = modifiers;
 
 405     wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
 
 408     if ( eventType != NSFlagsChanged )
 
 410         NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
 
 413             // if charString is set, it did not come from key up / key down
 
 414             wxevent.SetEventType( wxEVT_CHAR );
 
 415             chars = wxCFStringRef::AsString(charString);
 
 419             chars = wxCFStringRef::AsString(nschars);
 
 423     int aunichar = chars.Length() > 0 ? chars[0] : 0;
 
 426     if (wxevent.GetEventType() != wxEVT_CHAR)
 
 428         keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
 
 432                 wxevent.SetEventType( wxEVT_KEY_DOWN )  ;
 
 435                 wxevent.SetEventType( wxEVT_KEY_UP )  ;
 
 437             case NSFlagsChanged :
 
 441                         wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
 
 444                         wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
 
 447                         wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
 
 449                     case WXK_RAW_CONTROL:
 
 450                         wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
 
 461         if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
 
 462             keyval = wxToupper( aunichar ) ;
 
 468     // OS X generates events with key codes in Unicode private use area for
 
 469     // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
 
 470     // and function keys (WXK_F2 is U+F705). We don't want to use them as the
 
 471     // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
 
 472     // WXK_NONE for "non characters" so explicitly exclude them.
 
 474     // We only exclude the private use area inside the Basic Multilingual Plane
 
 475     // as key codes beyond it don't seem to be currently used.
 
 476     if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
 
 477         wxevent.m_uniChar = aunichar;
 
 479     wxevent.m_keyCode = keyval;
 
 481     wxWindowMac* peer = GetWXPeer();
 
 484         wxevent.SetEventObject(peer);
 
 485         wxevent.SetId(peer->GetId()) ;
 
 489 UInt32 g_lastButton = 0 ;
 
 490 bool g_lastButtonWasFakeRight = false ;
 
 492 // better scroll wheel support 
 
 493 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
 
 495 @interface NSEvent (DeviceDelta)
 
 496 - (CGFloat)deviceDeltaX;
 
 497 - (CGFloat)deviceDeltaY;
 
 500 - (BOOL)hasPreciseScrollingDeltas;
 
 501 - (CGFloat)scrollingDeltaX;
 
 502 - (CGFloat)scrollingDeltaY;
 
 505 void wxWidgetCocoaImpl::SetupCoordinates(wxCoord &x, wxCoord &y, NSEvent* nsEvent)
 
 507     NSPoint locationInWindow = [nsEvent locationInWindow];
 
 509     // adjust coordinates for the window of the target view
 
 510     if ( [nsEvent window] != [m_osxView window] )
 
 512         if ( [nsEvent window] != nil )
 
 513             locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
 
 515         if ( [m_osxView window] != nil )
 
 516             locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
 
 519     NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
 
 520     wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
 
 522     x = locationInViewWX.x;
 
 523     y = locationInViewWX.y;
 
 527 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
 
 529     int eventType = [nsEvent type];
 
 530     UInt32 modifiers = [nsEvent modifierFlags] ;
 
 532     SetupCoordinates(wxevent.m_x, wxevent.m_y, nsEvent);
 
 534     // these parameters are not given for all events
 
 535     UInt32 button = [nsEvent buttonNumber];
 
 536     UInt32 clickCount = 0;
 
 538     wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
 
 539     wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
 
 540     wxevent.m_altDown = modifiers & NSAlternateKeyMask;
 
 541     wxevent.m_controlDown = modifiers & NSCommandKeyMask;
 
 542     wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
 
 544     UInt32 mouseChord = 0;
 
 548         case NSLeftMouseDown :
 
 549         case NSLeftMouseDragged :
 
 552         case NSRightMouseDown :
 
 553         case NSRightMouseDragged :
 
 556         case NSOtherMouseDown :
 
 557         case NSOtherMouseDragged :
 
 562     // a control click is interpreted as a right click
 
 563     bool thisButtonIsFakeRight = false ;
 
 564     if ( button == 0 && (modifiers & NSControlKeyMask) )
 
 567         thisButtonIsFakeRight = true ;
 
 570     // otherwise we report double clicks by connecting a left click with a ctrl-left click
 
 571     if ( clickCount > 1 && button != g_lastButton )
 
 574     // we must make sure that our synthetic 'right' button corresponds in
 
 575     // mouse down, moved and mouse up, and does not deliver a right down and left up
 
 578         case NSLeftMouseDown :
 
 579         case NSRightMouseDown :
 
 580         case NSOtherMouseDown :
 
 581             g_lastButton = button ;
 
 582             g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
 
 589         g_lastButtonWasFakeRight = false ;
 
 591     else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
 
 592         button = g_lastButton ;
 
 594     // Adjust the chord mask to remove the primary button and add the
 
 595     // secondary button.  It is possible that the secondary button is
 
 596     // already pressed, e.g. on a mouse connected to a laptop, but this
 
 597     // possibility is ignored here:
 
 598     if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
 
 599         mouseChord = ((mouseChord & ~1U) | 2U);
 
 602                 wxevent.m_leftDown = true ;
 
 604                 wxevent.m_rightDown = true ;
 
 606                 wxevent.m_middleDown = true ;
 
 608     // translate into wx types
 
 611         case NSLeftMouseDown :
 
 612         case NSRightMouseDown :
 
 613         case NSOtherMouseDown :
 
 614             clickCount = [nsEvent clickCount];
 
 618                     wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN )  ;
 
 622                     wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
 
 626                     wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
 
 635         case NSRightMouseUp :
 
 636         case NSOtherMouseUp :
 
 637             clickCount = [nsEvent clickCount];
 
 641                     wxevent.SetEventType( wxEVT_LEFT_UP )  ;
 
 645                     wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
 
 649                     wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
 
 662             wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
 
 664             if ( UMAGetSystemVersion() >= 0x1070 )
 
 666                 if ( [nsEvent hasPreciseScrollingDeltas] )
 
 668                     deltaX = [nsEvent scrollingDeltaX];
 
 669                     deltaY = [nsEvent scrollingDeltaY];
 
 673                     deltaX = [nsEvent scrollingDeltaX] * 10;
 
 674                     deltaY = [nsEvent scrollingDeltaY] * 10;
 
 679                 const EventRef cEvent = (EventRef) [nsEvent eventRef];
 
 680                 // see http://developer.apple.com/qa/qa2005/qa1453.html
 
 681                 // for more details on why we have to look for the exact type
 
 683                 bool isMouseScrollEvent = false;
 
 685                     isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
 
 687                 if ( isMouseScrollEvent )
 
 689                     deltaX = [nsEvent deviceDeltaX];
 
 690                     deltaY = [nsEvent deviceDeltaY];
 
 694                     deltaX = ([nsEvent deltaX] * 10);
 
 695                     deltaY = ([nsEvent deltaY] * 10);
 
 699             wxevent.m_wheelDelta = 10;
 
 700             wxevent.m_linesPerAction = 1;
 
 701             wxevent.m_columnsPerAction = 1;
 
 703             if ( fabs(deltaX) > fabs(deltaY) )
 
 705                 // wx conventions for horizontal are inverted from vertical (originating from native msw behavior)
 
 706                 // right and up are positive values, left and down are negative values, while on OSX right and down
 
 707                 // are negative and left and up are positive.
 
 708                 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
 
 709                 wxevent.m_wheelRotation = -(int)deltaX;
 
 713                 wxevent.m_wheelRotation = (int)deltaY;
 
 719         case NSMouseEntered :
 
 720             wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
 
 723             wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
 
 725         case NSLeftMouseDragged :
 
 726         case NSRightMouseDragged :
 
 727         case NSOtherMouseDragged :
 
 729             wxevent.SetEventType( wxEVT_MOTION ) ;
 
 735     wxevent.m_clickCount = clickCount;
 
 736     wxWindowMac* peer = GetWXPeer();
 
 739         wxevent.SetEventObject(peer);
 
 740         wxevent.SetId(peer->GetId()) ;
 
 744 @implementation wxNSView
 
 748     static BOOL initialized = NO;
 
 752         wxOSXCocoaClassAddWXMethods( self );
 
 756 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle 
 
 757  * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
 
 761 - (void)_sendToolTipMouseExited
 
 763     // Nothing matters except window, trackingNumber, and userData.
 
 764     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
 
 765                                                 location:NSMakePoint(0, 0)
 
 768                                             windowNumber:[[self window] windowNumber]
 
 771                                           trackingNumber:_lastToolTipTrackTag
 
 772                                                 userData:_lastUserData];
 
 773     [_lastToolTipOwner mouseExited:fakeEvent];
 
 776 - (void)_sendToolTipMouseEntered
 
 778     // Nothing matters except window, trackingNumber, and userData.
 
 779     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
 
 780                                                 location:NSMakePoint(0, 0)
 
 783                                             windowNumber:[[self window] windowNumber]
 
 786                                           trackingNumber:_lastToolTipTrackTag
 
 787                                                 userData:_lastUserData];
 
 788     [_lastToolTipOwner mouseEntered:fakeEvent];
 
 791 - (void)setToolTip:(NSString *)string;
 
 797             [self _sendToolTipMouseExited];
 
 800         [super setToolTip:string];
 
 802         [self _sendToolTipMouseEntered];
 
 808             [self _sendToolTipMouseExited];
 
 809             [super setToolTip:nil];
 
 815 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
 
 817     NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
 
 820         _lastUserData = data;
 
 821         _lastToolTipOwner = owner;
 
 822         _lastToolTipTrackTag = tag;
 
 827 - (void)removeTrackingRect:(NSTrackingRectTag)tag
 
 829     if (tag == _lastToolTipTrackTag) 
 
 831         _lastUserData = NULL;
 
 832         _lastToolTipOwner = nil;
 
 833         _lastToolTipTrackTag = 0;
 
 835     [super removeTrackingRect:tag];
 
 838 #if wxOSX_USE_NATIVE_FLIPPED
 
 845 - (BOOL) canBecomeKeyView
 
 847     wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
 848     if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
 
 849         return viewimpl->GetWXPeer()->AcceptsFocus();
 
 855 // We need to adopt NSTextInputClient protocol in order to interpretKeyEvents: to work.
 
 856 // Currently, only insertText:(replacementRange:) is
 
 857 // implemented here, and the rest of the methods are stubs.
 
 858 // It is hoped that someday IME-related functionality is implemented in
 
 859 // wxWidgets and the methods of this protocol are fully working.
 
 861 @implementation wxNSView(TextInput)
 
 863 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text);
 
 865 - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange
 
 867     wxOSX_insertText(self, @selector(insertText:), aString);
 
 870 - (void)doCommandBySelector:(SEL)aSelector
 
 872     // these are already caught in the keyEvent handler
 
 875 - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
 
 883 - (NSRange)selectedRange
 
 885     return NSMakeRange(NSNotFound, 0);
 
 888 - (NSRange)markedRange
 
 890     return NSMakeRange(NSNotFound, 0);
 
 893 - (BOOL)hasMarkedText
 
 898 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
 
 903 - (NSArray*)validAttributesForMarkedText
 
 908 - (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
 
 910     return NSMakeRect(0, 0, 0, 0);
 
 912 - (NSUInteger)characterIndexForPoint:(NSPoint)aPoint
 
 917 @end // wxNSView(TextInput)
 
 924 #if wxUSE_DRAG_AND_DROP
 
 926 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
 
 927 // for details on the NSPasteboard -> PasteboardRef conversion
 
 929 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
 
 931     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
 933         return NSDragOperationNone;
 
 935     return impl->draggingEntered(sender, self, _cmd);
 
 938 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
 
 940     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
 944     return impl->draggingExited(sender, self, _cmd);
 
 947 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
 
 949     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
 951         return NSDragOperationNone;
 
 953     return impl->draggingUpdated(sender, self, _cmd);
 
 956 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
 
 958     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
 960         return NSDragOperationNone;
 
 962     return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
 
 967 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
 
 969     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
 973     impl->mouseEvent(event, self, _cmd);
 
 976 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
 
 978     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
 982     impl->cursorUpdate(event, self, _cmd);
 
 985 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
 
 987     // This is needed to support click through, otherwise the first click on a window
 
 988     // will not do anything unless it is the active window already.
 
 992 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
 
 994     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
 998     impl->keyEvent(event, self, _cmd);
 
1001 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
 
1003     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1007     impl->insertText(text, self, _cmd);
 
1010 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
 
1012     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1016     return impl->performKeyEquivalent(event, self, _cmd);
 
1019 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
 
1021     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1025     return impl->acceptsFirstResponder(self, _cmd);
 
1028 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
 
1030     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1034     return impl->becomeFirstResponder(self, _cmd);
 
1037 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
 
1039     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1043     return impl->resignFirstResponder(self, _cmd);
 
1046 #if !wxOSX_USE_NATIVE_FLIPPED
 
1048 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
 
1050     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1054     return impl->isFlipped(self, _cmd) ? YES:NO;
 
1059 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
 
1061 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
 
1063     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1068     // OS X starts a NSUIHeartBeatThread for animating the default button in a
 
1069     // dialog. This causes a drawRect of the active dialog from outside the
 
1070     // main UI thread. This causes an occasional crash since the wx drawing
 
1071     // objects (like wxPen) are not thread safe.
 
1073     // Notice that NSUIHeartBeatThread seems to be undocumented and doing
 
1074     // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
 
1075     if ( !wxThread::IsMain() )
 
1077         if ( impl->IsUserPane() )
 
1079             wxWindow* win = impl->GetWXPeer();
 
1080             if ( win->UseBgCol() )
 
1083                 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
 
1084                 CGContextSaveGState( context );
 
1086                 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
 
1087                 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
 
1088                 CGContextFillRect( context, r );
 
1090                 CGContextRestoreGState( context );
 
1095             // just call the superclass handler, we don't need any custom wx drawing
 
1096             // here and it seems to work fine:
 
1097             wxOSX_DrawRectHandlerPtr
 
1098             superimpl = (wxOSX_DrawRectHandlerPtr)
 
1099             [[self superclass] instanceMethodForSelector:_cmd];
 
1100             superimpl(self, _cmd, rect);
 
1105 #endif // wxUSE_THREADS
 
1107     return impl->drawRect(&rect, self, _cmd);
 
1110 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
 
1112     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1116     impl->controlAction(self, _cmd, sender);
 
1119 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
 
1121     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
 
1125     impl->controlDoubleAction(self, _cmd, sender);
 
1128 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
 
1130     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
 
1131     NSPasteboard *pboard = [sender draggingPasteboard];
 
1132     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
 
1134     wxWindow* wxpeer = GetWXPeer();
 
1135     if ( wxpeer == NULL )
 
1136         return NSDragOperationNone;
 
1138     wxDropTarget* target = wxpeer->GetDropTarget();
 
1139     if ( target == NULL )
 
1140         return NSDragOperationNone;
 
1142     wxDragResult result = wxDragNone;
 
1143     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
 
1144     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
 
1146     if ( sourceDragMask & NSDragOperationLink )
 
1147         result = wxDragLink;
 
1148     else if ( sourceDragMask & NSDragOperationCopy )
 
1149         result = wxDragCopy;
 
1150     else if ( sourceDragMask & NSDragOperationMove )
 
1151         result = wxDragMove;
 
1153     PasteboardRef pboardRef;
 
1154     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
 
1155     target->SetCurrentDragPasteboard(pboardRef);
 
1156     result = target->OnEnter(pt.x, pt.y, result);
 
1157     CFRelease(pboardRef);
 
1159     NSDragOperation nsresult = NSDragOperationNone;
 
1163             nsresult = NSDragOperationLink;
 
1165             nsresult = NSDragOperationMove;
 
1167             nsresult = NSDragOperationCopy;
 
1174 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
 
1176     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
 
1177     NSPasteboard *pboard = [sender draggingPasteboard];
 
1179     wxWindow* wxpeer = GetWXPeer();
 
1180     if ( wxpeer == NULL )
 
1183     wxDropTarget* target = wxpeer->GetDropTarget();
 
1184     if ( target == NULL )
 
1187     PasteboardRef pboardRef;
 
1188     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
 
1189     target->SetCurrentDragPasteboard(pboardRef);
 
1191     CFRelease(pboardRef);
 
1194 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
 
1196     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
 
1197     NSPasteboard *pboard = [sender draggingPasteboard];
 
1198     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
 
1200     wxWindow* wxpeer = GetWXPeer();
 
1201     if ( wxpeer == NULL )
 
1202         return NSDragOperationNone;
 
1204     wxDropTarget* target = wxpeer->GetDropTarget();
 
1205     if ( target == NULL )
 
1206         return NSDragOperationNone;
 
1208     wxDragResult result = wxDragNone;
 
1209     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
 
1210     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
 
1212     if ( sourceDragMask & NSDragOperationLink )
 
1213         result = wxDragLink;
 
1214     else if ( sourceDragMask & NSDragOperationCopy )
 
1215         result = wxDragCopy;
 
1216     else if ( sourceDragMask & NSDragOperationMove )
 
1217         result = wxDragMove;
 
1219     PasteboardRef pboardRef;
 
1220     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
 
1221     target->SetCurrentDragPasteboard(pboardRef);
 
1222     result = target->OnDragOver(pt.x, pt.y, result);
 
1223     CFRelease(pboardRef);
 
1225     NSDragOperation nsresult = NSDragOperationNone;
 
1229             nsresult = NSDragOperationLink;
 
1231             nsresult = NSDragOperationMove;
 
1233             nsresult = NSDragOperationCopy;
 
1240 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
 
1242     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
 
1244     NSPasteboard *pboard = [sender draggingPasteboard];
 
1245     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
 
1247     wxWindow* wxpeer = GetWXPeer();
 
1248     wxDropTarget* target = wxpeer->GetDropTarget();
 
1249     wxDragResult result = wxDragNone;
 
1250     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
 
1251     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
 
1253     if ( sourceDragMask & NSDragOperationLink )
 
1254         result = wxDragLink;
 
1255     else if ( sourceDragMask & NSDragOperationCopy )
 
1256         result = wxDragCopy;
 
1257     else if ( sourceDragMask & NSDragOperationMove )
 
1258         result = wxDragMove;
 
1260     PasteboardRef pboardRef;
 
1261     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
 
1262     target->SetCurrentDragPasteboard(pboardRef);
 
1264     if (target->OnDrop(pt.x, pt.y))
 
1265         result = target->OnData(pt.x, pt.y, result);
 
1267     CFRelease(pboardRef);
 
1269     return result != wxDragNone;
 
1272 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
 
1274     // we are getting moved events for all windows in the hierarchy, not something wx expects
 
1275     // therefore we only handle it for the deepest child in the hierarchy
 
1276     if ( [event type] == NSMouseMoved )
 
1278         NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
 
1279         if ( hitview == NULL || hitview != slf)
 
1283     if ( !DoHandleMouseEvent(event) )
 
1285         // for plain NSView mouse events would propagate to parents otherwise
 
1286         // scrollwheel events have to be propagated if not handled in all cases
 
1287         if (!IsUserPane() || [event type] == NSScrollWheel )
 
1289             wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
 
1290             superimpl(slf, (SEL)_cmd, event);
 
1292             // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
 
1293             // only trigger if at this moment the mouse is already up
 
1294             if ( [ event type]  == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
 
1296                 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
 
1297                 SetupMouseEvent(wxevent , event) ;
 
1298                 wxevent.SetEventType(wxEVT_LEFT_UP);
 
1300                 GetWXPeer()->HandleWindowEvent(wxevent);
 
1306 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
 
1308     if ( !SetupCursor(event) )
 
1310         wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
 
1311             superimpl(slf, (SEL)_cmd, event);
 
1315 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
 
1317     extern wxCursor gGlobalCursor;
 
1319     if ( gGlobalCursor.IsOk() )
 
1321         gGlobalCursor.MacInstall();
 
1326         wxWindow* cursorTarget = GetWXPeer();
 
1328         SetupCoordinates(x, y, event);
 
1329         wxPoint cursorPoint( x , y ) ;
 
1331         while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
 
1333             // at least in GTK cursor events are not propagated either ...
 
1335             cursorTarget = NULL;
 
1337             cursorTarget = cursorTarget->GetParent() ;
 
1339                 cursorPoint += cursorTarget->GetPosition();
 
1343         return cursorTarget != NULL;
 
1347 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
 
1349     if ( [event type] == NSKeyDown )
 
1351         // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically, 
 
1352         // therefore we call the menubar directly here, exit if the menu is handling the shortcut
 
1353         if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
 
1356         m_lastKeyDownEvent = event;
 
1359     if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
 
1361         wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
 
1362         superimpl(slf, (SEL)_cmd, event);
 
1364     m_lastKeyDownEvent = NULL;
 
1367 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
 
1369     if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
 
1371         wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
 
1372         superimpl(slf, (SEL)_cmd, text);
 
1377 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
 
1379     bool handled = false;
 
1381     wxKeyEvent wxevent(wxEVT_KEY_DOWN);
 
1382     SetupKeyEvent( wxevent, event );
 
1384     // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
 
1385     // walk up the ancestors ourselves but let cocoa do it
 
1387     int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
 
1390         wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
 
1392         wxCommandEvent command_event( wxEVT_MENU, command );
 
1393         command_event.SetEventObject( wxevent.GetEventObject() );
 
1394         handled = handler->ProcessEvent( command_event );
 
1398             // accelerators can also be used with buttons, try them too
 
1399             command_event.SetEventType(wxEVT_BUTTON);
 
1400             handled = handler->ProcessEvent( command_event );
 
1406         wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
 
1407         return superimpl(slf, (SEL)_cmd, event);
 
1412 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
 
1415         return m_wxPeer->AcceptsFocus();
 
1418         wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
 
1419         return superimpl(slf, (SEL)_cmd);
 
1423 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
 
1425     wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
 
1426     // get the current focus before running becomeFirstResponder
 
1427     NSView* otherView = FindFocus();
 
1429     wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
 
1430     BOOL r = superimpl(slf, (SEL)_cmd);
 
1433         DoNotifyFocusEvent( true, otherWindow );
 
1439 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
 
1441     wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
 
1442     BOOL r = superimpl(slf, (SEL)_cmd);
 
1444     NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
 
1445     NSView* otherView = wxOSXGetViewFromResponder(responder);
 
1447     wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
 
1449     // It doesn't make sense to notify about the loss of focus if it's the same
 
1450     // control in the end, and just a different subview
 
1451     if ( otherWindow == this )
 
1454     // NSTextViews have an editor as true responder, therefore the might get the
 
1455     // resign notification if their editor takes over, don't trigger any event then
 
1456     if ( r && !m_hasEditor)
 
1458         DoNotifyFocusEvent( false, otherWindow );
 
1463 #if !wxOSX_USE_NATIVE_FLIPPED
 
1465 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
 
1472 #define OSX_DEBUG_DRAWING 0
 
1474 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
 
1476     // preparing the update region
 
1480     // since adding many rects to a region is a costly process, by default use the bounding rect
 
1482     const NSRect *rects;
 
1484     [slf getRectsBeingDrawn:&rects count:&count];
 
1485     for ( int i = 0 ; i < count ; ++i )
 
1487         updateRgn.Union(wxFromNSRect(slf, rects[i]));
 
1490     updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
 
1493     wxWindow* wxpeer = GetWXPeer();
 
1495     if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
 
1497         // as this update region is in native window locals we must adapt it to wx window local
 
1498         updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
 
1501     // Restrict the update region to the shape of the window, if any, and also
 
1502     // remember the region that we need to clear later.
 
1503     wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
 
1504     const bool isTopLevel = tlwParent == wxpeer;
 
1506     if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
 
1509             clearRgn = updateRgn;
 
1511         int xoffset = 0, yoffset = 0;
 
1512         wxRegion rgn = tlwParent->GetShape();
 
1513         wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
 
1514         rgn.Offset( xoffset, yoffset );
 
1515         updateRgn.Intersect(rgn);
 
1519             // Exclude the window shape from the region to be cleared below.
 
1520             rgn.Xor(wxpeer->GetSize());
 
1521             clearRgn.Intersect(rgn);
 
1525     wxpeer->GetUpdateRegion() = updateRgn;
 
1527     // setting up the drawing context
 
1529     CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
 
1530     CGContextSaveGState( context );
 
1532 #if OSX_DEBUG_DRAWING
 
1533     CGContextBeginPath( context );
 
1534     CGContextMoveToPoint(context, 0, 0);
 
1535     NSRect bounds = [slf bounds];
 
1536     CGContextAddLineToPoint(context, 10, 0);
 
1537     CGContextMoveToPoint(context, 0, 0);
 
1538     CGContextAddLineToPoint(context, 0, 10);
 
1539     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
 
1540     CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
 
1541     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
 
1542     CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
 
1543     CGContextClosePath( context );
 
1544     CGContextStrokePath(context);
 
1547     if ( ![slf isFlipped] )
 
1549         CGContextTranslateCTM( context, 0,  [m_osxView bounds].size.height );
 
1550         CGContextScaleCTM( context, 1, -1 );
 
1553     wxpeer->MacSetCGContextRef( context );
 
1555     bool handled = wxpeer->MacDoRedraw( 0 );
 
1556     CGContextRestoreGState( context );
 
1558     CGContextSaveGState( context );
 
1562         SEL _cmd = @selector(drawRect:);
 
1563         wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
 
1564         superimpl(slf, _cmd, *(NSRect*)rect);
 
1565         CGContextRestoreGState( context );
 
1566         CGContextSaveGState( context );
 
1568     // as we called restore above, we have to flip again if necessary
 
1569     if ( ![slf isFlipped] )
 
1571         CGContextTranslateCTM( context, 0,  [m_osxView bounds].size.height );
 
1572         CGContextScaleCTM( context, 1, -1 );
 
1577         // We also need to explicitly draw the part of the top level window
 
1578         // outside of its region with transparent colour to ensure that it is
 
1579         // really transparent.
 
1580         if ( clearRgn.IsOk() )
 
1582             wxMacCGContextStateSaver saveState(context);
 
1583             wxWindowDC dc(wxpeer);
 
1584             dc.SetBackground(wxBrush(wxTransparentColour));
 
1585             dc.SetDeviceClippingRegion(clearRgn);
 
1589 #if wxUSE_GRAPHICS_CONTEXT
 
1590         // If the window shape is defined by a path, stroke the path to show
 
1591         // the window border.
 
1592         const wxGraphicsPath& path = tlwParent->GetShapePath();
 
1593         if ( !path.IsNull() )
 
1595             CGContextSetLineWidth(context, 1);
 
1596             CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
 
1597             CGContextAddPath(context, (CGPathRef) path.GetNativePath());
 
1598             CGContextStrokePath(context);
 
1600 #endif // wxUSE_GRAPHICS_CONTEXT
 
1603     wxpeer->MacPaintChildrenBorders();
 
1604     wxpeer->MacSetCGContextRef( NULL );
 
1605     CGContextRestoreGState( context );
 
1608 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
 
1610     wxWindow* wxpeer = (wxWindow*) GetWXPeer();
 
1613         wxpeer->OSXSimulateFocusEvents();
 
1614         wxpeer->OSXHandleClicked(0);
 
1618 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
 
1622 void wxWidgetCocoaImpl::controlTextDidChange()
 
1624     wxWindow* wxpeer = (wxWindow*)GetWXPeer();
 
1627         // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
 
1628         wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
 
1629         wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
 
1631             tc->SendTextUpdatedEventIfAllowed();
 
1633             cb->SendTextUpdatedEventIfAllowed();
 
1636             wxFAIL_MSG("Unexpected class for controlTextDidChange event");
 
1643 #if OBJC_API_VERSION >= 2
 
1645 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
 
1646     class_addMethod(c, s, i, t );
 
1650 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
 
1651     { s, (char*) t, i },
 
1655 void wxOSXCocoaClassAddWXMethods(Class c)
 
1658 #if OBJC_API_VERSION < 2
 
1659     static objc_method wxmethods[] =
 
1663     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1664     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1665     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1667     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1668     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1669     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1671     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1673     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1674     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1675     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1677     wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
 
1679     wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1680     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1681     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
 
1683     wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
 
1685     wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
 
1686     wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
 
1687     wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
 
1689     wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
 
1691     wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
 
1693     wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
 
1694     wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
 
1695     wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
 
1697 #if !wxOSX_USE_NATIVE_FLIPPED
 
1698     wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
 
1700     wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
 
1702     wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
 
1703     wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
 
1705 #if wxUSE_DRAG_AND_DROP
 
1706     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
 
1707     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
 
1708     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
 
1709     wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
 
1712 #if OBJC_API_VERSION < 2
 
1714     static int method_count = WXSIZEOF( wxmethods );
 
1715     static objc_method_list *wxmethodlist = NULL;
 
1716     if ( wxmethodlist == NULL )
 
1718         wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
 
1719         memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
 
1720         wxmethodlist->method_count = method_count;
 
1721         wxmethodlist->obsolete = 0;
 
1723     class_addMethods( c, wxmethodlist );
 
1728 // C++ implementation class
 
1731 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
 
1733 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
 
1734     wxWidgetImpl( peer, isRootControl, isUserPane )
 
1739     // check if the user wants to create the control initially hidden
 
1740     if ( !peer->IsShown() )
 
1741         SetVisibility(false);
 
1743     // gc aware handling
 
1745         CFRetain(m_osxView);
 
1746     [m_osxView release];
 
1749 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
 
1754 void wxWidgetCocoaImpl::Init()
 
1757 #if !wxOSX_USE_NATIVE_FLIPPED
 
1760     m_lastKeyDownEvent = NULL;
 
1761     m_hasEditor = false;
 
1764 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
 
1766     RemoveAssociations( this );
 
1768     if ( !IsRootControl() )
 
1770         NSView *sv = [m_osxView superview];
 
1772             [m_osxView removeFromSuperview];
 
1774     // gc aware handling
 
1776         CFRelease(m_osxView);
 
1779 bool wxWidgetCocoaImpl::IsVisible() const
 
1781     return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
 
1784 void wxWidgetCocoaImpl::SetVisibility( bool visible )
 
1786     [m_osxView setHidden:(visible ? NO:YES)];
 
1789 double wxWidgetCocoaImpl::GetContentScaleFactor() const
 
1791 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
 
1792     NSWindow* tlw = [m_osxView window];
 
1793     if ( [ tlw respondsToSelector:@selector(backingScaleFactor) ] )
 
1794         return [tlw backingScaleFactor];
 
1800 // ----------------------------------------------------------------------------
 
1801 // window animation stuff
 
1802 // ----------------------------------------------------------------------------
 
1804 // define a delegate used to refresh the window during animation
 
1805 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
 
1811 - (id)init:(wxWindow *)win;
 
1815 // NSAnimationDelegate methods
 
1816 - (void)animationDidEnd:(NSAnimation*)animation;
 
1817 - (void)animation:(NSAnimation*)animation
 
1818         didReachProgressMark:(NSAnimationProgress)progress;
 
1821 @implementation wxNSAnimationDelegate
 
1823 - (id)init:(wxWindow *)win
 
1825     self = [super init];
 
1838 - (void)animation:(NSAnimation*)animation
 
1839         didReachProgressMark:(NSAnimationProgress)progress
 
1841     wxUnusedVar(animation);
 
1842     wxUnusedVar(progress);
 
1844     m_win->SendSizeEvent();
 
1847 - (void)animationDidEnd:(NSAnimation*)animation
 
1849     wxUnusedVar(animation);
 
1857 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
 
1859                                               wxShowEffect effect,
 
1862     // create the dictionary describing the animation to perform on this view
 
1864         viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
 
1865     NSMutableDictionary * const
 
1866         dict = [NSMutableDictionary dictionaryWithCapacity:4];
 
1867     [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
 
1869     // determine the start and end rectangles assuming we're hiding the window
 
1870     const wxRect rectOrig = win->GetRect();
 
1878         if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
 
1879                 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
 
1880             effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
 
1881         else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
 
1882                     effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
 
1883             effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
 
1884         else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
 
1885                     effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
 
1886             effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
 
1887         else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
 
1888                     effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
 
1889             effect = wxSHOW_EFFECT_ROLL_TO_TOP;
 
1894         case wxSHOW_EFFECT_ROLL_TO_LEFT:
 
1895         case wxSHOW_EFFECT_SLIDE_TO_LEFT:
 
1899         case wxSHOW_EFFECT_ROLL_TO_RIGHT:
 
1900         case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
 
1901             rectEnd.x = rectStart.GetRight();
 
1905         case wxSHOW_EFFECT_ROLL_TO_TOP:
 
1906         case wxSHOW_EFFECT_SLIDE_TO_TOP:
 
1910         case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
 
1911         case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
 
1912             rectEnd.y = rectStart.GetBottom();
 
1916         case wxSHOW_EFFECT_EXPAND:
 
1917             rectEnd.x = rectStart.x + rectStart.width / 2;
 
1918             rectEnd.y = rectStart.y + rectStart.height / 2;
 
1923         case wxSHOW_EFFECT_BLEND:
 
1924             [dict setObject:(show ? NSViewAnimationFadeInEffect
 
1925                                   : NSViewAnimationFadeOutEffect)
 
1926                   forKey:NSViewAnimationEffectKey];
 
1929         case wxSHOW_EFFECT_NONE:
 
1930         case wxSHOW_EFFECT_MAX:
 
1931             wxFAIL_MSG( "unexpected animation effect" );
 
1935             wxFAIL_MSG( "unknown animation effect" );
 
1941         // we need to restore it to the original rectangle instead of making it
 
1943         wxSwap(rectStart, rectEnd);
 
1945         // and as the window is currently hidden, we need to show it for the
 
1946         // animation to be visible at all (but don't restore it at its full
 
1947         // rectangle as it shouldn't appear immediately)
 
1948         win->SetSize(rectStart);
 
1952     NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
 
1953                                     ? [(NSView *)viewOrWin superview]
 
1955     const NSRect rStart = wxToNSRect(parentView, rectStart);
 
1956     const NSRect rEnd = wxToNSRect(parentView, rectEnd);
 
1958     [dict setObject:[NSValue valueWithRect:rStart]
 
1959           forKey:NSViewAnimationStartFrameKey];
 
1960     [dict setObject:[NSValue valueWithRect:rEnd]
 
1961           forKey:NSViewAnimationEndFrameKey];
 
1963     // create an animation using the values in the above dictionary
 
1964     NSViewAnimation * const
 
1965         anim = [[NSViewAnimation alloc]
 
1966                 initWithViewAnimations:[NSArray arrayWithObject:dict]];
 
1970         // what is a good default duration? Windows uses 200ms, Web frameworks
 
1971         // use anything from 250ms to 1s... choose something in the middle
 
1975     [anim setDuration:timeout/1000.];   // duration is in seconds here
 
1977     // if the window being animated changes its layout depending on its size
 
1978     // (which is almost always the case) we need to redo it during animation
 
1980     // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
 
1981     // controls in wxInfoBar visibly jump around)
 
1982     const int NUM_LAYOUTS = 20;
 
1983     for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
 
1984         [anim addProgressMark:f];
 
1986     wxNSAnimationDelegate * const
 
1987         animDelegate = [[wxNSAnimationDelegate alloc] init:win];
 
1988     [anim setDelegate:animDelegate];
 
1989     [anim startAnimation];
 
1991     // Cocoa is capable of doing animation asynchronously or even from separate
 
1992     // thread but wx API doesn't provide any way to be notified about the
 
1993     // animation end and without this we really must ensure that the window has
 
1994     // the expected (i.e. the same as if a simple Show() had been used) size
 
1995     // when we return, so block here until the animation finishes
 
1997     // notice that because the default animation mode is NSAnimationBlocking,
 
1998     // no user input events ought to be processed from here
 
2000         wxEventLoopGuarantor ensureEventLoopExistence;
 
2001         wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
 
2002         while ( ![animDelegate isDone] )
 
2008         // NSViewAnimation is smart enough to hide the NSView being animated at
 
2009         // the end but we also must ensure that it's hidden for wx too
 
2012         // and we must also restore its size because it isn't expected to
 
2013         // change just because the window was hidden
 
2014         win->SetSize(rectOrig);
 
2018         // refresh it once again after the end to ensure that everything is in
 
2020         win->SendSizeEvent();
 
2023     [anim setDelegate:nil];
 
2024     [animDelegate release];
 
2030 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
 
2031                                        wxShowEffect effect,
 
2034     return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
 
2037 /* note that the drawing order between siblings is not defined under 10.4 */
 
2038 /* only starting from 10.5 the subview order is respected */
 
2040 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
 
2041  * NSInteger post-Leopard.  Pre-Leopard the Cocoa toolkit expects a function
 
2042  * returning int and not NSComparisonResult.  Post-Leopard the Cocoa toolkit
 
2043  * expects a function returning the new non-enum NSComparsionResult.
 
2044  * Hence we create a typedef named CocoaWindowCompareFunctionResult.
 
2046 #if defined(NSINTEGER_DEFINED)
 
2047 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
 
2049 typedef int CocoaWindowCompareFunctionResult;
 
2052 class CocoaWindowCompareContext
 
2054     wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
 
2056     CocoaWindowCompareContext(); // Not implemented
 
2057     CocoaWindowCompareContext(NSView *target, NSArray *subviews)
 
2060         // Cocoa sorts subviews in-place.. make a copy
 
2061         m_subviews = [subviews copy];
 
2064     ~CocoaWindowCompareContext()
 
2065     {   // release the copy
 
2066         [m_subviews release];
 
2069     {   return m_target; }
 
2072     {   return m_subviews; }
 
2074     /* Helper function that returns the comparison based off of the original ordering */
 
2075     CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
 
2077         NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
 
2078         NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
 
2079         // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
 
2080         // likely compare higher than the other view which is reasonable considering the only way that
 
2081         // can happen is if the subview was added after our call to subviews but before the call to
 
2082         // sortSubviewsUsingFunction:context:.  Thus we don't bother checking.  Particularly because
 
2083         // that case should never occur anyway because that would imply a multi-threaded GUI call
 
2084         // which is a big no-no with Cocoa.
 
2086         // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
 
2087         NSComparisonResult result = (firstI < secondI)
 
2088                 ?   NSOrderedAscending /* -1 */
 
2089                 :   (firstI > secondI)
 
2090                 ?   NSOrderedDescending /* 1 */
 
2091                 :   NSOrderedSame /* 0 */;
 
2096     /* The subview we are trying to Raise or Lower */
 
2098     /* A copy of the original array of subviews */
 
2099     NSArray *m_subviews;
 
2102 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
 
2103  * the target view is always higher than every other view.  When comparing two views neither of
 
2104  * which is the target, it returns the correct response based on the original ordering
 
2106 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
 
2108     CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
 
2109     // first should be ordered higher
 
2110     if(first==compareContext->target())
 
2111         return NSOrderedDescending;
 
2112     // second should be ordered higher
 
2113     if(second==compareContext->target())
 
2114         return NSOrderedAscending;
 
2115     return compareContext->CompareUsingOriginalOrdering(first,second);
 
2118 void wxWidgetCocoaImpl::Raise()
 
2120         NSView* nsview = m_osxView;
 
2122     NSView *superview = [nsview superview];
 
2123     CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
 
2125     [superview sortSubviewsUsingFunction:
 
2126          CocoaRaiseWindowCompareFunction
 
2127                                                                  context: &compareContext];
 
2131 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
 
2132  * the target view is always lower than every other view.  When comparing two views neither of
 
2133  * which is the target, it returns the correct response based on the original ordering
 
2135 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
 
2137     CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
 
2138     // first should be ordered lower
 
2139     if(first==compareContext->target())
 
2140         return NSOrderedAscending;
 
2141     // second should be ordered lower
 
2142     if(second==compareContext->target())
 
2143         return NSOrderedDescending;
 
2144     return compareContext->CompareUsingOriginalOrdering(first,second);
 
2147 void wxWidgetCocoaImpl::Lower()
 
2149         NSView* nsview = m_osxView;
 
2151     NSView *superview = [nsview superview];
 
2152     CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
 
2154     [superview sortSubviewsUsingFunction:
 
2155          CocoaLowerWindowCompareFunction
 
2156                                                                  context: &compareContext];
 
2159 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
 
2164     // We should do something like this, but it wasn't working in 10.4.
 
2165     if (GetNeedsDisplay() )
 
2169     NSRect r = wxToNSRect( [m_osxView superview], *rect );
 
2170     NSSize offset = NSMakeSize((float)dx, (float)dy);
 
2171     [m_osxView scrollRect:r by:offset];
 
2175 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
 
2177     wxWindowMac* parent = GetWXPeer()->GetParent();
 
2178     // under Cocoa we might have a contentView in the wxParent to which we have to
 
2179     // adjust the coordinates
 
2180     if (parent && [m_osxView superview] != parent->GetHandle() )
 
2182         int cx = 0,cy = 0,cw = 0,ch = 0;
 
2183         if ( parent->GetPeer() )
 
2185             parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
 
2190     [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
 
2191     NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
 
2192     [m_osxView setFrame:r];
 
2193     [[m_osxView superview] setNeedsDisplayInRect:r];
 
2196 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
 
2198     wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
 
2202     // under Cocoa we might have a contentView in the wxParent to which we have to
 
2203     // adjust the coordinates
 
2204     wxWindowMac* parent = GetWXPeer()->GetParent();
 
2205     if (parent && [m_osxView superview] != parent->GetHandle() )
 
2207         int cx = 0,cy = 0,cw = 0,ch = 0;
 
2208         if ( parent->GetPeer() )
 
2210             parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
 
2217 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
 
2219     NSRect rect = [m_osxView frame];
 
2220     width = (int)rect.size.width;
 
2221     height = (int)rect.size.height;
 
2224 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
 
2226     if ( [m_osxView respondsToSelector:@selector(contentView) ] )
 
2228         NSView* cv = [m_osxView contentView];
 
2230         NSRect bounds = [m_osxView bounds];
 
2231         NSRect rect = [cv frame];
 
2233         int y = (int)rect.origin.y;
 
2234         int x = (int)rect.origin.x;
 
2235         if ( ![ m_osxView isFlipped ] )
 
2236             y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
 
2239         width = (int)rect.size.width;
 
2240         height = (int)rect.size.height;
 
2245         GetSize( width, height );
 
2249 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
 
2252         [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
 
2254         [m_osxView setNeedsDisplay:YES];
 
2257 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
 
2259     return [m_osxView needsDisplay];
 
2262 bool wxWidgetCocoaImpl::CanFocus() const
 
2264     return [m_osxView canBecomeKeyView] == YES;
 
2267 bool wxWidgetCocoaImpl::HasFocus() const
 
2269     return ( FindFocus() == m_osxView );
 
2272 bool wxWidgetCocoaImpl::SetFocus()
 
2277     // TODO remove if no issues arise: should not raise the window, only assign focus
 
2278     //[[m_osxView window] makeKeyAndOrderFront:nil] ;
 
2279     [[m_osxView window] makeFirstResponder: m_osxView] ;
 
2283 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
 
2285     [m_osxView unregisterDraggedTypes];
 
2287     if ( target == NULL )
 
2290     wxDataObject* dobj = target->GetDataObject();
 
2294         CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
 
2295         dobj->AddSupportedTypes(typesarray);
 
2296         NSView* targetView = m_osxView;
 
2297         if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
 
2298             targetView = [(NSScrollView*) m_osxView documentView];
 
2300         [targetView registerForDraggedTypes:(NSArray*)typesarray];
 
2301         CFRelease(typesarray);
 
2305 void wxWidgetCocoaImpl::RemoveFromParent()
 
2307     [m_osxView removeFromSuperview];
 
2310 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
 
2312     NSView* container = parent->GetWXWidget() ;
 
2313     wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
 
2314     [container addSubview:m_osxView];
 
2316     if( m_wxPeer->IsFrozen() )
 
2317         [[m_osxView window] disableFlushWindow];
 
2320 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
 
2322     NSView* targetView = m_osxView;
 
2323     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
 
2324         targetView = [(NSScrollView*) m_osxView documentView];
 
2326     if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
 
2328         [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
 
2329                                                                 green:(CGFloat) (col.Green() / 255.0)
 
2330                                                                  blue:(CGFloat) (col.Blue() / 255.0)
 
2331                                                                 alpha:(CGFloat) (col.Alpha() / 255.0)]];
 
2335 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
 
2337     BOOL opaque = ( style == wxBG_STYLE_PAINT );
 
2339     if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
 
2341         [m_osxView setOpaque: opaque];
 
2347 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
 
2349     if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
 
2351         wxCFStringRef cf( title , encoding );
 
2352         [m_osxView setTitle:cf.AsNSString()];
 
2354     else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
 
2356         wxCFStringRef cf( title , encoding );
 
2357         [m_osxView setStringValue:cf.AsNSString()];
 
2362 void  wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
 
2364     NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
 
2365     p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
 
2366     *pt = wxFromNSPoint( to->GetWXWidget(), p );
 
2369 wxInt32 wxWidgetCocoaImpl::GetValue() const
 
2371     return [(NSControl*)m_osxView intValue];
 
2374 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
 
2376     if (  [m_osxView respondsToSelector:@selector(setIntValue:)] )
 
2378         [m_osxView setIntValue:v];
 
2380     else if (  [m_osxView respondsToSelector:@selector(setFloatValue:)] )
 
2382         [m_osxView setFloatValue:(double)v];
 
2384     else if (  [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
 
2386         [m_osxView setDoubleValue:(double)v];
 
2390 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
 
2392     if (  [m_osxView respondsToSelector:@selector(setMinValue:)] )
 
2394         [m_osxView setMinValue:(double)v];
 
2398 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
 
2400     if (  [m_osxView respondsToSelector:@selector(setMaxValue:)] )
 
2402         [m_osxView setMaxValue:(double)v];
 
2406 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
 
2408     if (  [m_osxView respondsToSelector:@selector(minValue)] )
 
2410         return (int)[m_osxView minValue];
 
2415 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
 
2417     if (  [m_osxView respondsToSelector:@selector(maxValue)] )
 
2419         return (int)[m_osxView maxValue];
 
2424 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
 
2428     // TODO: how to create a wxBitmap from NSImage?
 
2430     if ( [m_osxView respondsToSelector:@selector(image:)] )
 
2431         bmp = [m_osxView image];
 
2437 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
 
2439     if (  [m_osxView respondsToSelector:@selector(setImage:)] )
 
2442             [m_osxView setImage:bitmap.GetNSImage()];
 
2444             [m_osxView setImage:nil];
 
2446         [m_osxView setNeedsDisplay:YES];
 
2450 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
 
2452     if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
 
2454         NSCellImagePosition pos;
 
2474                 wxFAIL_MSG( "invalid image position" );
 
2478         [m_osxView setImagePosition:pos];
 
2482 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
 
2484     // implementation in subclass
 
2487 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
 
2489     r->x = r->y = r->width = r->height = 0;
 
2491     if (  [m_osxView respondsToSelector:@selector(sizeToFit)] )
 
2493         NSRect former = [m_osxView frame];
 
2494         [m_osxView sizeToFit];
 
2495         NSRect best = [m_osxView frame];
 
2496         [m_osxView setFrame:former];
 
2497         r->width = (int)best.size.width;
 
2498         r->height = (int)best.size.height;
 
2502 bool wxWidgetCocoaImpl::IsEnabled() const
 
2504     NSView* targetView = m_osxView;
 
2505     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
 
2506         targetView = [(NSScrollView*) m_osxView documentView];
 
2508     if ( [targetView respondsToSelector:@selector(isEnabled) ] )
 
2509         return [targetView isEnabled];
 
2513 void wxWidgetCocoaImpl::Enable( bool enable )
 
2515     NSView* targetView = m_osxView;
 
2516     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
 
2517         targetView = [(NSScrollView*) m_osxView documentView];
 
2519     if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
 
2520         [targetView setEnabled:enable];
 
2523 void wxWidgetCocoaImpl::PulseGauge()
 
2527 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
 
2531 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
 
2533     NSControlSize size = NSRegularControlSize;
 
2537         case wxWINDOW_VARIANT_NORMAL :
 
2538             size = NSRegularControlSize;
 
2541         case wxWINDOW_VARIANT_SMALL :
 
2542             size = NSSmallControlSize;
 
2545         case wxWINDOW_VARIANT_MINI :
 
2546             size = NSMiniControlSize;
 
2549         case wxWINDOW_VARIANT_LARGE :
 
2550             size = NSRegularControlSize;
 
2554             wxFAIL_MSG(wxT("unexpected window variant"));
 
2557     if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
 
2558         [m_osxView setControlSize:size];
 
2559     else if ([m_osxView respondsToSelector:@selector(cell)])
 
2561         id cell = [(id)m_osxView cell];
 
2562         if ([cell respondsToSelector:@selector(setControlSize:)])
 
2563             [cell setControlSize:size];
 
2566     // we need to propagate this to inner views as well
 
2567     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
 
2569         NSView* targetView = [(NSScrollView*) m_osxView documentView];
 
2571         if ( [targetView respondsToSelector:@selector(setControlSize:)] )
 
2572             [targetView setControlSize:size];
 
2573         else if ([targetView respondsToSelector:@selector(cell)])
 
2575             id cell = [(id)targetView cell];
 
2576             if ([cell respondsToSelector:@selector(setControlSize:)])
 
2577                 [cell setControlSize:size];
 
2582 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
 
2584     NSView* targetView = m_osxView;
 
2585     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
 
2586         targetView = [(NSScrollView*) m_osxView documentView];
 
2588     if ([targetView respondsToSelector:@selector(setFont:)])
 
2589         [targetView setFont: font.OSXGetNSFont()];
 
2590     if ([targetView respondsToSelector:@selector(setTextColor:)])
 
2591         [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
 
2592                                                                  green:(CGFloat) (col.Green() / 255.0)
 
2593                                                                   blue:(CGFloat) (col.Blue() / 255.0)
 
2594                                                                  alpha:(CGFloat) (col.Alpha() / 255.0)]];
 
2597 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
 
2601         wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
 
2602         [m_osxView setToolTip: cf.AsNSString()];
 
2606         [m_osxView setToolTip:nil];
 
2610 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
 
2612     WXWidget c =  control ? control : (WXWidget) m_osxView;
 
2613     wxWidgetImpl::Associate( c, this ) ;
 
2614     if ([c respondsToSelector:@selector(setAction:)])
 
2617         if ( dynamic_cast<wxRadioButton*>(GetWXPeer()) )
 
2619             // everything already set up
 
2622             [c setAction: @selector(controlAction:)];
 
2624         if ([c respondsToSelector:@selector(setDoubleAction:)])
 
2626             [c setDoubleAction: @selector(controlDoubleAction:)];
 
2630     NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
 
2631     NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
 
2632     [m_osxView addTrackingArea: area];
 
2636 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
 
2638     bool result = false;
 
2640     for (NSUInteger i = 0; i < [text length]; ++i)
 
2642         wxKeyEvent wxevent(wxEVT_CHAR);
 
2643         unichar c = [text characterAtIndex:i];
 
2644         SetupKeyEvent( wxevent, event, [NSString stringWithCharacters:&c length:1]);
 
2646         result = GetWXPeer()->OSXHandleKeyEvent(wxevent) || result;
 
2652 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
 
2654     wxKeyEvent wxevent(wxEVT_KEY_DOWN);
 
2655     SetupKeyEvent( wxevent, event );
 
2657     // Generate wxEVT_CHAR_HOOK before sending any other events but only when
 
2658     // the key is pressed, not when it's released (the type of wxevent is
 
2659     // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
 
2660     if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
 
2662         wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
 
2663         if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
 
2664                 && !eventHook.IsNextEventAllowed() )
 
2668     bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
 
2670     // this will fire higher level events, like insertText, to help
 
2671     // us handle EVT_CHAR, etc.
 
2675         if ( [event type] == NSKeyDown)
 
2677             long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
 
2679             if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
 
2681                 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
 
2682                 wxKeyEvent wxevent2(wxevent) ;
 
2683                 wxevent2.SetEventType(wxEVT_CHAR);
 
2684                 SetupKeyEvent( wxevent2, event );
 
2685                 wxevent2.m_keyCode = keycode;
 
2686                 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
 
2688             else if (wxevent.CmdDown())
 
2690                 wxKeyEvent wxevent2(wxevent) ;
 
2691                 wxevent2.SetEventType(wxEVT_CHAR);
 
2692                 SetupKeyEvent( wxevent2, event );
 
2693                 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
 
2697                 if ( IsUserPane() && !wxevent.CmdDown() )
 
2699                     if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
 
2700                         [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
 
2702                         [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
 
2712 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
 
2714     wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
 
2715     SetupMouseEvent(wxevent , event) ;
 
2716     bool result = GetWXPeer()->HandleWindowEvent(wxevent);
 
2718     (void)SetupCursor(event);
 
2723 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
 
2725     wxWindow* thisWindow = GetWXPeer();
 
2726     if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
 
2728         thisWindow->MacInvalidateBorders();
 
2731     if ( receivedFocus )
 
2733         wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
 
2734         wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
 
2735         thisWindow->HandleWindowEvent(eventFocus);
 
2738         if ( thisWindow->GetCaret() )
 
2739             thisWindow->GetCaret()->OnSetFocus();
 
2742         wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
 
2743         event.SetEventObject(thisWindow);
 
2745             event.SetWindow(otherWindow->GetWXPeer());
 
2746         thisWindow->HandleWindowEvent(event) ;
 
2748     else // !receivedFocus
 
2751         if ( thisWindow->GetCaret() )
 
2752             thisWindow->GetCaret()->OnKillFocus();
 
2755         wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
 
2757         wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
 
2758         event.SetEventObject(thisWindow);
 
2760             event.SetWindow(otherWindow->GetWXPeer());
 
2761         thisWindow->HandleWindowEvent(event) ;
 
2765 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
 
2769         NSPoint location = [NSEvent mouseLocation];
 
2770         location = [[m_osxView window] convertScreenToBase:location];
 
2771         NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
 
2773         if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
 
2775             [(NSCursor*)cursor.GetHCURSOR() set];
 
2780 void wxWidgetCocoaImpl::CaptureMouse()
 
2782     // TODO remove if we don't get into problems with cursor settings
 
2783     //    [[m_osxView window] disableCursorRects];
 
2786 void wxWidgetCocoaImpl::ReleaseMouse()
 
2788     // TODO remove if we don't get into problems with cursor settings
 
2789     //    [[m_osxView window] enableCursorRects];
 
2792 #if !wxOSX_USE_NATIVE_FLIPPED
 
2794 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
 
2796     m_isFlipped = flipped;
 
2801 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
 
2805         [[m_osxView window] enableFlushWindow];
 
2806         [m_osxView setNeedsDisplay:YES];
 
2810         [[m_osxView window] disableFlushWindow];
 
2817 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
 
2818     wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
 
2819     long WXUNUSED(style), long WXUNUSED(extraStyle))
 
2821     NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
 
2822     wxNSView* v = [[wxNSView alloc] initWithFrame:r];
 
2824     wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
 
2828 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
 
2830     NSWindow* tlw = now->GetWXWindow();
 
2832     wxWidgetCocoaImpl* c = NULL;
 
2833     if ( now->IsNativeWindowWrapper() )
 
2835         NSView* cv = [tlw contentView];
 
2836         c = new wxWidgetCocoaImpl( now, cv, true );
 
2839             // increase ref count, because the impl destructor will decrement it again
 
2841             if ( !now->IsShown() )
 
2847         wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
 
2848         c = new wxWidgetCocoaImpl( now, v, true );
 
2849         c->InstallEventHandler();
 
2850         [tlw setContentView:v];