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 NSView(PossibleMethods)
113 - (void)setTitle:(NSString *)aString;
114 - (void)setStringValue:(NSString *)aString;
115 - (void)setIntValue:(int)anInt;
116 - (void)setFloatValue:(float)aFloat;
117 - (void)setDoubleValue:(double)aDouble;
121 - (void)setMinValue:(double)aDouble;
122 - (void)setMaxValue:(double)aDouble;
127 - (void)setEnabled:(BOOL)flag;
129 - (void)setImage:(NSImage *)image;
130 - (void)setControlSize:(NSControlSize)size;
132 - (void)setFont:(NSFont *)fontObject;
136 - (void)setTarget:(id)anObject;
137 - (void)setAction:(SEL)aSelector;
138 - (void)setDoubleAction:(SEL)aSelector;
139 - (void)setBackgroundColor:(NSColor*)aColor;
140 - (void)setOpaque:(BOOL)opaque;
141 - (void)setTextColor:(NSColor *)color;
142 - (void)setImagePosition:(NSCellImagePosition)aPosition;
145 // The following code is a combination of the code listed here:
146 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
147 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
148 // and the code here:
149 // http://inquisitivecocoa.com/category/objective-c/
150 @interface NSEvent (OsGuiUtilsAdditions)
151 - (NSString*) charactersIgnoringModifiersIncludingShift;
154 @implementation NSEvent (OsGuiUtilsAdditions)
155 - (NSString*) charactersIgnoringModifiersIncludingShift {
156 // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
157 // differently than AppKit.
158 NSString* c = [self charactersIgnoringModifiers];
159 if ([c length] == 1) {
160 unichar codepoint = [c characterAtIndex:0];
161 if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
165 // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
166 // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
167 // which hints the OS to use Latin characters where possible, which is generally what we want.
168 NSString* result = @"";
169 TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
170 CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
171 CFRelease(currentKeyboard);
173 // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
176 const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
177 if (keyboardLayout) {
178 UInt32 deadKeyState = 0;
179 UniCharCount maxStringLength = 255;
180 UniCharCount actualStringLength = 0;
181 UniChar unicodeString[maxStringLength];
183 OSStatus status = UCKeyTranslate(keyboardLayout,
186 cmdKey >> 8, // force the Command key to "on"
188 kUCKeyTranslateNoDeadKeysMask,
195 result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
201 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
205 if ([event type] != NSFlagsChanged)
207 NSString* s = [event charactersIgnoringModifiersIncludingShift];
208 // backspace char reports as delete w/modifiers for some reason
211 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
213 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
217 switch ( [s characterAtIndex:0] )
224 case NSUpArrowFunctionKey :
227 case NSDownArrowFunctionKey :
230 case NSLeftArrowFunctionKey :
233 case NSRightArrowFunctionKey :
236 case NSInsertFunctionKey :
239 case NSDeleteFunctionKey :
242 case NSHomeFunctionKey :
245 // case NSBeginFunctionKey :
246 // retval = WXK_BEGIN;
248 case NSEndFunctionKey :
251 case NSPageUpFunctionKey :
254 case NSPageDownFunctionKey :
255 retval = WXK_PAGEDOWN;
257 case NSHelpFunctionKey :
261 int intchar = [s characterAtIndex: 0];
262 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
263 retval = WXK_F1 + (intchar - NSF1FunctionKey );
264 else if ( intchar > 0 && intchar < 32 )
272 // Some keys don't seem to have constants. The code mimics the approach
273 // taken by WebKit. See:
274 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
275 switch( [event keyCode] )
280 retval = WXK_CONTROL;
284 retval = WXK_CAPITAL;
287 case 56: // Left Shift
288 case 60: // Right Shift
293 case 61: // Right Alt
297 case 59: // Left Ctrl
298 case 62: // Right Ctrl
299 retval = WXK_RAW_CONTROL;
313 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
314 // WXK_NUMPAD constants, but for the CHAR event we want to use the
315 // standard ascii values
316 if ( eventType != wxEVT_CHAR )
318 switch( [event keyCode] )
321 retval = WXK_NUMPAD_DIVIDE;
324 retval = WXK_NUMPAD_MULTIPLY;
327 retval = WXK_NUMPAD_SUBTRACT;
330 retval = WXK_NUMPAD_ADD;
333 retval = WXK_NUMPAD_ENTER;
336 retval = WXK_NUMPAD_DECIMAL;
339 retval = WXK_NUMPAD0;
342 retval = WXK_NUMPAD1;
345 retval = WXK_NUMPAD2;
348 retval = WXK_NUMPAD3;
351 retval = WXK_NUMPAD4;
354 retval = WXK_NUMPAD5;
357 retval = WXK_NUMPAD6;
360 retval = WXK_NUMPAD7;
363 retval = WXK_NUMPAD8;
366 retval = WXK_NUMPAD9;
369 //retval = [event keyCode];
376 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
378 UInt32 modifiers = [nsEvent modifierFlags] ;
379 int eventType = [nsEvent type];
381 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
382 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
383 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
384 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
386 wxevent.m_rawCode = [nsEvent keyCode];
387 wxevent.m_rawFlags = modifiers;
389 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
392 if ( eventType != NSFlagsChanged )
394 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
397 // if charString is set, it did not come from key up / key down
398 wxevent.SetEventType( wxEVT_CHAR );
399 chars = wxCFStringRef::AsString(charString);
403 chars = wxCFStringRef::AsString(nschars);
407 int aunichar = chars.Length() > 0 ? chars[0] : 0;
410 if (wxevent.GetEventType() != wxEVT_CHAR)
412 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
416 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
419 wxevent.SetEventType( wxEVT_KEY_UP ) ;
421 case NSFlagsChanged :
425 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
428 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
431 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
433 case WXK_RAW_CONTROL:
434 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
445 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
446 keyval = wxToupper( aunichar ) ;
452 // OS X generates events with key codes in Unicode private use area for
453 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
454 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
455 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
456 // WXK_NONE for "non characters" so explicitly exclude them.
458 // We only exclude the private use area inside the Basic Multilingual Plane
459 // as key codes beyond it don't seem to be currently used.
460 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
461 wxevent.m_uniChar = aunichar;
463 wxevent.m_keyCode = keyval;
465 wxWindowMac* peer = GetWXPeer();
468 wxevent.SetEventObject(peer);
469 wxevent.SetId(peer->GetId()) ;
473 UInt32 g_lastButton = 0 ;
474 bool g_lastButtonWasFakeRight = false ;
476 // better scroll wheel support
477 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
479 @interface NSEvent (DeviceDelta)
480 - (CGFloat)deviceDeltaX;
481 - (CGFloat)deviceDeltaY;
484 - (BOOL)hasPreciseScrollingDeltas;
485 - (CGFloat)scrollingDeltaX;
486 - (CGFloat)scrollingDeltaY;
489 void wxWidgetCocoaImpl::SetupCoordinates(wxCoord &x, wxCoord &y, NSEvent* nsEvent)
491 NSPoint locationInWindow = [nsEvent locationInWindow];
493 // adjust coordinates for the window of the target view
494 if ( [nsEvent window] != [m_osxView window] )
496 if ( [nsEvent window] != nil )
497 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
499 if ( [m_osxView window] != nil )
500 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
503 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
504 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
506 x = locationInViewWX.x;
507 y = locationInViewWX.y;
511 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
513 int eventType = [nsEvent type];
514 UInt32 modifiers = [nsEvent modifierFlags] ;
516 SetupCoordinates(wxevent.m_x, wxevent.m_y, nsEvent);
518 // these parameters are not given for all events
519 UInt32 button = [nsEvent buttonNumber];
520 UInt32 clickCount = 0;
522 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
523 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
524 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
525 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
526 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
528 UInt32 mouseChord = 0;
532 case NSLeftMouseDown :
533 case NSLeftMouseDragged :
536 case NSRightMouseDown :
537 case NSRightMouseDragged :
540 case NSOtherMouseDown :
541 case NSOtherMouseDragged :
546 // a control click is interpreted as a right click
547 bool thisButtonIsFakeRight = false ;
548 if ( button == 0 && (modifiers & NSControlKeyMask) )
551 thisButtonIsFakeRight = true ;
554 // otherwise we report double clicks by connecting a left click with a ctrl-left click
555 if ( clickCount > 1 && button != g_lastButton )
558 // we must make sure that our synthetic 'right' button corresponds in
559 // mouse down, moved and mouse up, and does not deliver a right down and left up
562 case NSLeftMouseDown :
563 case NSRightMouseDown :
564 case NSOtherMouseDown :
565 g_lastButton = button ;
566 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
573 g_lastButtonWasFakeRight = false ;
575 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
576 button = g_lastButton ;
578 // Adjust the chord mask to remove the primary button and add the
579 // secondary button. It is possible that the secondary button is
580 // already pressed, e.g. on a mouse connected to a laptop, but this
581 // possibility is ignored here:
582 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
583 mouseChord = ((mouseChord & ~1U) | 2U);
586 wxevent.m_leftDown = true ;
588 wxevent.m_rightDown = true ;
590 wxevent.m_middleDown = true ;
592 // translate into wx types
595 case NSLeftMouseDown :
596 case NSRightMouseDown :
597 case NSOtherMouseDown :
598 clickCount = [nsEvent clickCount];
602 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
606 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
610 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
619 case NSRightMouseUp :
620 case NSOtherMouseUp :
621 clickCount = [nsEvent clickCount];
625 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
629 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
633 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
646 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
648 if ( UMAGetSystemVersion() >= 0x1070 )
650 if ( [nsEvent hasPreciseScrollingDeltas] )
652 deltaX = [nsEvent scrollingDeltaX];
653 deltaY = [nsEvent scrollingDeltaY];
657 deltaX = [nsEvent scrollingDeltaX] * 10;
658 deltaY = [nsEvent scrollingDeltaY] * 10;
663 const EventRef cEvent = (EventRef) [nsEvent eventRef];
664 // see http://developer.apple.com/qa/qa2005/qa1453.html
665 // for more details on why we have to look for the exact type
667 bool isMouseScrollEvent = false;
669 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
671 if ( isMouseScrollEvent )
673 deltaX = [nsEvent deviceDeltaX];
674 deltaY = [nsEvent deviceDeltaY];
678 deltaX = ([nsEvent deltaX] * 10);
679 deltaY = ([nsEvent deltaY] * 10);
683 wxevent.m_wheelDelta = 10;
684 wxevent.m_linesPerAction = 1;
685 wxevent.m_columnsPerAction = 1;
687 if ( fabs(deltaX) > fabs(deltaY) )
689 // wx conventions for horizontal are inverted from vertical (originating from native msw behavior)
690 // right and up are positive values, left and down are negative values, while on OSX right and down
691 // are negative and left and up are positive.
692 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
693 wxevent.m_wheelRotation = -(int)deltaX;
697 wxevent.m_wheelRotation = (int)deltaY;
703 case NSMouseEntered :
704 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
707 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
709 case NSLeftMouseDragged :
710 case NSRightMouseDragged :
711 case NSOtherMouseDragged :
713 wxevent.SetEventType( wxEVT_MOTION ) ;
719 wxevent.m_clickCount = clickCount;
720 wxWindowMac* peer = GetWXPeer();
723 wxevent.SetEventObject(peer);
724 wxevent.SetId(peer->GetId()) ;
728 @implementation wxNSView
732 static BOOL initialized = NO;
736 wxOSXCocoaClassAddWXMethods( self );
740 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
741 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
745 - (void)_sendToolTipMouseExited
747 // Nothing matters except window, trackingNumber, and userData.
748 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
749 location:NSMakePoint(0, 0)
752 windowNumber:[[self window] windowNumber]
755 trackingNumber:_lastToolTipTrackTag
756 userData:_lastUserData];
757 [_lastToolTipOwner mouseExited:fakeEvent];
760 - (void)_sendToolTipMouseEntered
762 // Nothing matters except window, trackingNumber, and userData.
763 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
764 location:NSMakePoint(0, 0)
767 windowNumber:[[self window] windowNumber]
770 trackingNumber:_lastToolTipTrackTag
771 userData:_lastUserData];
772 [_lastToolTipOwner mouseEntered:fakeEvent];
775 - (void)setToolTip:(NSString *)string;
781 [self _sendToolTipMouseExited];
784 [super setToolTip:string];
786 [self _sendToolTipMouseEntered];
792 [self _sendToolTipMouseExited];
793 [super setToolTip:nil];
799 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
801 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
804 _lastUserData = data;
805 _lastToolTipOwner = owner;
806 _lastToolTipTrackTag = tag;
811 - (void)removeTrackingRect:(NSTrackingRectTag)tag
813 if (tag == _lastToolTipTrackTag)
815 _lastUserData = NULL;
816 _lastToolTipOwner = nil;
817 _lastToolTipTrackTag = 0;
819 [super removeTrackingRect:tag];
822 #if wxOSX_USE_NATIVE_FLIPPED
829 - (BOOL) canBecomeKeyView
831 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
832 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
833 return viewimpl->GetWXPeer()->AcceptsFocus();
843 #if wxUSE_DRAG_AND_DROP
845 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
846 // for details on the NSPasteboard -> PasteboardRef conversion
848 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
850 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
852 return NSDragOperationNone;
854 return impl->draggingEntered(sender, self, _cmd);
857 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
859 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
863 return impl->draggingExited(sender, self, _cmd);
866 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
868 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
870 return NSDragOperationNone;
872 return impl->draggingUpdated(sender, self, _cmd);
875 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
877 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
879 return NSDragOperationNone;
881 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
886 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
888 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
892 impl->mouseEvent(event, self, _cmd);
895 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
897 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
901 impl->cursorUpdate(event, self, _cmd);
904 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
906 // This is needed to support click through, otherwise the first click on a window
907 // will not do anything unless it is the active window already.
911 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
913 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
917 impl->keyEvent(event, self, _cmd);
920 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
922 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
926 impl->insertText(text, self, _cmd);
929 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
931 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
935 return impl->performKeyEquivalent(event, self, _cmd);
938 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
940 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
944 return impl->acceptsFirstResponder(self, _cmd);
947 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
949 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
953 return impl->becomeFirstResponder(self, _cmd);
956 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
958 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
962 return impl->resignFirstResponder(self, _cmd);
965 #if !wxOSX_USE_NATIVE_FLIPPED
967 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
969 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
973 return impl->isFlipped(self, _cmd) ? YES:NO;
978 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
980 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
982 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
987 // OS X starts a NSUIHeartBeatThread for animating the default button in a
988 // dialog. This causes a drawRect of the active dialog from outside the
989 // main UI thread. This causes an occasional crash since the wx drawing
990 // objects (like wxPen) are not thread safe.
992 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
993 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
994 if ( !wxThread::IsMain() )
996 if ( impl->IsUserPane() )
998 wxWindow* win = impl->GetWXPeer();
999 if ( win->UseBgCol() )
1002 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1003 CGContextSaveGState( context );
1005 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
1006 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1007 CGContextFillRect( context, r );
1009 CGContextRestoreGState( context );
1014 // just call the superclass handler, we don't need any custom wx drawing
1015 // here and it seems to work fine:
1016 wxOSX_DrawRectHandlerPtr
1017 superimpl = (wxOSX_DrawRectHandlerPtr)
1018 [[self superclass] instanceMethodForSelector:_cmd];
1019 superimpl(self, _cmd, rect);
1024 #endif // wxUSE_THREADS
1026 return impl->drawRect(&rect, self, _cmd);
1029 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
1031 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1035 impl->controlAction(self, _cmd, sender);
1038 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
1040 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1044 impl->controlDoubleAction(self, _cmd, sender);
1047 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1049 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1050 NSPasteboard *pboard = [sender draggingPasteboard];
1051 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1053 wxWindow* wxpeer = GetWXPeer();
1054 if ( wxpeer == NULL )
1055 return NSDragOperationNone;
1057 wxDropTarget* target = wxpeer->GetDropTarget();
1058 if ( target == NULL )
1059 return NSDragOperationNone;
1061 wxDragResult result = wxDragNone;
1062 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1063 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1065 if ( sourceDragMask & NSDragOperationLink )
1066 result = wxDragLink;
1067 else if ( sourceDragMask & NSDragOperationCopy )
1068 result = wxDragCopy;
1069 else if ( sourceDragMask & NSDragOperationMove )
1070 result = wxDragMove;
1072 PasteboardRef pboardRef;
1073 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1074 target->SetCurrentDragPasteboard(pboardRef);
1075 result = target->OnEnter(pt.x, pt.y, result);
1076 CFRelease(pboardRef);
1078 NSDragOperation nsresult = NSDragOperationNone;
1082 nsresult = NSDragOperationLink;
1084 nsresult = NSDragOperationMove;
1086 nsresult = NSDragOperationCopy;
1093 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1095 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1096 NSPasteboard *pboard = [sender draggingPasteboard];
1098 wxWindow* wxpeer = GetWXPeer();
1099 if ( wxpeer == NULL )
1102 wxDropTarget* target = wxpeer->GetDropTarget();
1103 if ( target == NULL )
1106 PasteboardRef pboardRef;
1107 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1108 target->SetCurrentDragPasteboard(pboardRef);
1110 CFRelease(pboardRef);
1113 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1115 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1116 NSPasteboard *pboard = [sender draggingPasteboard];
1117 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1119 wxWindow* wxpeer = GetWXPeer();
1120 if ( wxpeer == NULL )
1121 return NSDragOperationNone;
1123 wxDropTarget* target = wxpeer->GetDropTarget();
1124 if ( target == NULL )
1125 return NSDragOperationNone;
1127 wxDragResult result = wxDragNone;
1128 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1129 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1131 if ( sourceDragMask & NSDragOperationLink )
1132 result = wxDragLink;
1133 else if ( sourceDragMask & NSDragOperationCopy )
1134 result = wxDragCopy;
1135 else if ( sourceDragMask & NSDragOperationMove )
1136 result = wxDragMove;
1138 PasteboardRef pboardRef;
1139 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1140 target->SetCurrentDragPasteboard(pboardRef);
1141 result = target->OnDragOver(pt.x, pt.y, result);
1142 CFRelease(pboardRef);
1144 NSDragOperation nsresult = NSDragOperationNone;
1148 nsresult = NSDragOperationLink;
1150 nsresult = NSDragOperationMove;
1152 nsresult = NSDragOperationCopy;
1159 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1161 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1163 NSPasteboard *pboard = [sender draggingPasteboard];
1164 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1166 wxWindow* wxpeer = GetWXPeer();
1167 wxDropTarget* target = wxpeer->GetDropTarget();
1168 wxDragResult result = wxDragNone;
1169 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1170 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1172 if ( sourceDragMask & NSDragOperationLink )
1173 result = wxDragLink;
1174 else if ( sourceDragMask & NSDragOperationCopy )
1175 result = wxDragCopy;
1176 else if ( sourceDragMask & NSDragOperationMove )
1177 result = wxDragMove;
1179 PasteboardRef pboardRef;
1180 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1181 target->SetCurrentDragPasteboard(pboardRef);
1183 if (target->OnDrop(pt.x, pt.y))
1184 result = target->OnData(pt.x, pt.y, result);
1186 CFRelease(pboardRef);
1188 return result != wxDragNone;
1191 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1193 // we are getting moved events for all windows in the hierarchy, not something wx expects
1194 // therefore we only handle it for the deepest child in the hierarchy
1195 if ( [event type] == NSMouseMoved )
1197 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1198 if ( hitview == NULL || hitview != slf)
1202 if ( !DoHandleMouseEvent(event) )
1204 // for plain NSView mouse events would propagate to parents otherwise
1205 // scrollwheel events have to be propagated if not handled in all cases
1206 if (!IsUserPane() || [event type] == NSScrollWheel )
1208 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1209 superimpl(slf, (SEL)_cmd, event);
1211 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1212 // only trigger if at this moment the mouse is already up
1213 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1215 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1216 SetupMouseEvent(wxevent , event) ;
1217 wxevent.SetEventType(wxEVT_LEFT_UP);
1219 GetWXPeer()->HandleWindowEvent(wxevent);
1225 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1227 if ( !SetupCursor(event) )
1229 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1230 superimpl(slf, (SEL)_cmd, event);
1234 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1236 extern wxCursor gGlobalCursor;
1238 if ( gGlobalCursor.IsOk() )
1240 gGlobalCursor.MacInstall();
1245 wxWindow* cursorTarget = GetWXPeer();
1247 SetupCoordinates(x, y, event);
1248 wxPoint cursorPoint( x , y ) ;
1250 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1252 // at least in GTK cursor events are not propagated either ...
1254 cursorTarget = NULL;
1256 cursorTarget = cursorTarget->GetParent() ;
1258 cursorPoint += cursorTarget->GetPosition();
1262 return cursorTarget != NULL;
1266 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1268 if ( [event type] == NSKeyDown )
1270 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1271 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1272 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1275 m_lastKeyDownEvent = event;
1278 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1280 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1281 superimpl(slf, (SEL)_cmd, event);
1283 m_lastKeyDownEvent = NULL;
1286 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1288 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1290 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1291 superimpl(slf, (SEL)_cmd, text);
1296 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1298 bool handled = false;
1300 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1301 SetupKeyEvent( wxevent, event );
1303 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1304 // walk up the ancestors ourselves but let cocoa do it
1306 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1309 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1311 wxCommandEvent command_event( wxEVT_MENU, command );
1312 command_event.SetEventObject( wxevent.GetEventObject() );
1313 handled = handler->ProcessEvent( command_event );
1317 // accelerators can also be used with buttons, try them too
1318 command_event.SetEventType(wxEVT_BUTTON);
1319 handled = handler->ProcessEvent( command_event );
1325 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1326 return superimpl(slf, (SEL)_cmd, event);
1331 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1334 return m_wxPeer->AcceptsFocus();
1337 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1338 return superimpl(slf, (SEL)_cmd);
1342 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1344 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1345 // get the current focus before running becomeFirstResponder
1346 NSView* otherView = FindFocus();
1348 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1349 BOOL r = superimpl(slf, (SEL)_cmd);
1352 DoNotifyFocusEvent( true, otherWindow );
1358 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1360 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1361 BOOL r = superimpl(slf, (SEL)_cmd);
1363 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
1364 NSView* otherView = wxOSXGetViewFromResponder(responder);
1366 wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
1368 // It doesn't make sense to notify about the loss of focus if it's the same
1369 // control in the end, and just a different subview
1370 if ( otherWindow == this )
1373 // NSTextViews have an editor as true responder, therefore the might get the
1374 // resign notification if their editor takes over, don't trigger any event then
1375 if ( r && !m_hasEditor)
1377 DoNotifyFocusEvent( false, otherWindow );
1382 #if !wxOSX_USE_NATIVE_FLIPPED
1384 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1391 #define OSX_DEBUG_DRAWING 0
1393 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1395 // preparing the update region
1399 // since adding many rects to a region is a costly process, by default use the bounding rect
1401 const NSRect *rects;
1403 [slf getRectsBeingDrawn:&rects count:&count];
1404 for ( int i = 0 ; i < count ; ++i )
1406 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1409 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1412 wxWindow* wxpeer = GetWXPeer();
1414 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1416 // as this update region is in native window locals we must adapt it to wx window local
1417 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1420 // Restrict the update region to the shape of the window, if any, and also
1421 // remember the region that we need to clear later.
1422 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1423 const bool isTopLevel = tlwParent == wxpeer;
1425 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1428 clearRgn = updateRgn;
1430 int xoffset = 0, yoffset = 0;
1431 wxRegion rgn = tlwParent->GetShape();
1432 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1433 rgn.Offset( xoffset, yoffset );
1434 updateRgn.Intersect(rgn);
1438 // Exclude the window shape from the region to be cleared below.
1439 rgn.Xor(wxpeer->GetSize());
1440 clearRgn.Intersect(rgn);
1444 wxpeer->GetUpdateRegion() = updateRgn;
1446 // setting up the drawing context
1448 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1449 CGContextSaveGState( context );
1451 #if OSX_DEBUG_DRAWING
1452 CGContextBeginPath( context );
1453 CGContextMoveToPoint(context, 0, 0);
1454 NSRect bounds = [slf bounds];
1455 CGContextAddLineToPoint(context, 10, 0);
1456 CGContextMoveToPoint(context, 0, 0);
1457 CGContextAddLineToPoint(context, 0, 10);
1458 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1459 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1460 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1461 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1462 CGContextClosePath( context );
1463 CGContextStrokePath(context);
1466 if ( ![slf isFlipped] )
1468 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1469 CGContextScaleCTM( context, 1, -1 );
1472 wxpeer->MacSetCGContextRef( context );
1474 bool handled = wxpeer->MacDoRedraw( 0 );
1475 CGContextRestoreGState( context );
1477 CGContextSaveGState( context );
1481 SEL _cmd = @selector(drawRect:);
1482 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1483 superimpl(slf, _cmd, *(NSRect*)rect);
1484 CGContextRestoreGState( context );
1485 CGContextSaveGState( context );
1487 // as we called restore above, we have to flip again if necessary
1488 if ( ![slf isFlipped] )
1490 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1491 CGContextScaleCTM( context, 1, -1 );
1496 // We also need to explicitly draw the part of the top level window
1497 // outside of its region with transparent colour to ensure that it is
1498 // really transparent.
1499 if ( clearRgn.IsOk() )
1501 wxMacCGContextStateSaver saveState(context);
1502 wxWindowDC dc(wxpeer);
1503 dc.SetBackground(wxBrush(wxTransparentColour));
1504 dc.SetDeviceClippingRegion(clearRgn);
1508 #if wxUSE_GRAPHICS_CONTEXT
1509 // If the window shape is defined by a path, stroke the path to show
1510 // the window border.
1511 const wxGraphicsPath& path = tlwParent->GetShapePath();
1512 if ( !path.IsNull() )
1514 CGContextSetLineWidth(context, 1);
1515 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1516 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1517 CGContextStrokePath(context);
1519 #endif // wxUSE_GRAPHICS_CONTEXT
1522 wxpeer->MacPaintChildrenBorders();
1523 wxpeer->MacSetCGContextRef( NULL );
1524 CGContextRestoreGState( context );
1527 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1529 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1532 wxpeer->OSXSimulateFocusEvents();
1533 wxpeer->OSXHandleClicked(0);
1537 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1541 void wxWidgetCocoaImpl::controlTextDidChange()
1543 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1546 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1547 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1548 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1550 tc->SendTextUpdatedEventIfAllowed();
1552 cb->SendTextUpdatedEventIfAllowed();
1555 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1562 #if OBJC_API_VERSION >= 2
1564 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1565 class_addMethod(c, s, i, t );
1569 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1570 { s, (char*) t, i },
1574 void wxOSXCocoaClassAddWXMethods(Class c)
1577 #if OBJC_API_VERSION < 2
1578 static objc_method wxmethods[] =
1582 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1583 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1584 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1586 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1587 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1588 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1592 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1593 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1594 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1596 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1598 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1599 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1600 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1604 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1605 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1606 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1608 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1610 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1612 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1613 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1614 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1616 #if !wxOSX_USE_NATIVE_FLIPPED
1617 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1619 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1621 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1622 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1624 #if wxUSE_DRAG_AND_DROP
1625 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1626 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1627 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1628 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1631 #if OBJC_API_VERSION < 2
1633 static int method_count = WXSIZEOF( wxmethods );
1634 static objc_method_list *wxmethodlist = NULL;
1635 if ( wxmethodlist == NULL )
1637 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1638 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1639 wxmethodlist->method_count = method_count;
1640 wxmethodlist->obsolete = 0;
1642 class_addMethods( c, wxmethodlist );
1647 // C++ implementation class
1650 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1652 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1653 wxWidgetImpl( peer, isRootControl, isUserPane )
1658 // check if the user wants to create the control initially hidden
1659 if ( !peer->IsShown() )
1660 SetVisibility(false);
1662 // gc aware handling
1664 CFRetain(m_osxView);
1665 [m_osxView release];
1668 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1673 void wxWidgetCocoaImpl::Init()
1676 #if !wxOSX_USE_NATIVE_FLIPPED
1679 m_lastKeyDownEvent = NULL;
1680 m_hasEditor = false;
1683 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1685 RemoveAssociations( this );
1687 if ( !IsRootControl() )
1689 NSView *sv = [m_osxView superview];
1691 [m_osxView removeFromSuperview];
1693 // gc aware handling
1695 CFRelease(m_osxView);
1698 bool wxWidgetCocoaImpl::IsVisible() const
1700 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1703 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1705 [m_osxView setHidden:(visible ? NO:YES)];
1708 double wxWidgetCocoaImpl::GetContentScaleFactor() const
1710 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
1711 NSWindow* tlw = [m_osxView window];
1712 if ( [ tlw respondsToSelector:@selector(backingScaleFactor) ] )
1713 return [tlw backingScaleFactor];
1719 // ----------------------------------------------------------------------------
1720 // window animation stuff
1721 // ----------------------------------------------------------------------------
1723 // define a delegate used to refresh the window during animation
1724 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1730 - (id)init:(wxWindow *)win;
1734 // NSAnimationDelegate methods
1735 - (void)animationDidEnd:(NSAnimation*)animation;
1736 - (void)animation:(NSAnimation*)animation
1737 didReachProgressMark:(NSAnimationProgress)progress;
1740 @implementation wxNSAnimationDelegate
1742 - (id)init:(wxWindow *)win
1744 self = [super init];
1757 - (void)animation:(NSAnimation*)animation
1758 didReachProgressMark:(NSAnimationProgress)progress
1760 wxUnusedVar(animation);
1761 wxUnusedVar(progress);
1763 m_win->SendSizeEvent();
1766 - (void)animationDidEnd:(NSAnimation*)animation
1768 wxUnusedVar(animation);
1776 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1778 wxShowEffect effect,
1781 // create the dictionary describing the animation to perform on this view
1783 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1784 NSMutableDictionary * const
1785 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1786 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1788 // determine the start and end rectangles assuming we're hiding the window
1789 const wxRect rectOrig = win->GetRect();
1797 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1798 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1799 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1800 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1801 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1802 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1803 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1804 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1805 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1806 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1807 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1808 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1813 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1814 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1818 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1819 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1820 rectEnd.x = rectStart.GetRight();
1824 case wxSHOW_EFFECT_ROLL_TO_TOP:
1825 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1829 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1830 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1831 rectEnd.y = rectStart.GetBottom();
1835 case wxSHOW_EFFECT_EXPAND:
1836 rectEnd.x = rectStart.x + rectStart.width / 2;
1837 rectEnd.y = rectStart.y + rectStart.height / 2;
1842 case wxSHOW_EFFECT_BLEND:
1843 [dict setObject:(show ? NSViewAnimationFadeInEffect
1844 : NSViewAnimationFadeOutEffect)
1845 forKey:NSViewAnimationEffectKey];
1848 case wxSHOW_EFFECT_NONE:
1849 case wxSHOW_EFFECT_MAX:
1850 wxFAIL_MSG( "unexpected animation effect" );
1854 wxFAIL_MSG( "unknown animation effect" );
1860 // we need to restore it to the original rectangle instead of making it
1862 wxSwap(rectStart, rectEnd);
1864 // and as the window is currently hidden, we need to show it for the
1865 // animation to be visible at all (but don't restore it at its full
1866 // rectangle as it shouldn't appear immediately)
1867 win->SetSize(rectStart);
1871 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1872 ? [(NSView *)viewOrWin superview]
1874 const NSRect rStart = wxToNSRect(parentView, rectStart);
1875 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1877 [dict setObject:[NSValue valueWithRect:rStart]
1878 forKey:NSViewAnimationStartFrameKey];
1879 [dict setObject:[NSValue valueWithRect:rEnd]
1880 forKey:NSViewAnimationEndFrameKey];
1882 // create an animation using the values in the above dictionary
1883 NSViewAnimation * const
1884 anim = [[NSViewAnimation alloc]
1885 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1889 // what is a good default duration? Windows uses 200ms, Web frameworks
1890 // use anything from 250ms to 1s... choose something in the middle
1894 [anim setDuration:timeout/1000.]; // duration is in seconds here
1896 // if the window being animated changes its layout depending on its size
1897 // (which is almost always the case) we need to redo it during animation
1899 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1900 // controls in wxInfoBar visibly jump around)
1901 const int NUM_LAYOUTS = 20;
1902 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1903 [anim addProgressMark:f];
1905 wxNSAnimationDelegate * const
1906 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1907 [anim setDelegate:animDelegate];
1908 [anim startAnimation];
1910 // Cocoa is capable of doing animation asynchronously or even from separate
1911 // thread but wx API doesn't provide any way to be notified about the
1912 // animation end and without this we really must ensure that the window has
1913 // the expected (i.e. the same as if a simple Show() had been used) size
1914 // when we return, so block here until the animation finishes
1916 // notice that because the default animation mode is NSAnimationBlocking,
1917 // no user input events ought to be processed from here
1919 wxEventLoopGuarantor ensureEventLoopExistence;
1920 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1921 while ( ![animDelegate isDone] )
1927 // NSViewAnimation is smart enough to hide the NSView being animated at
1928 // the end but we also must ensure that it's hidden for wx too
1931 // and we must also restore its size because it isn't expected to
1932 // change just because the window was hidden
1933 win->SetSize(rectOrig);
1937 // refresh it once again after the end to ensure that everything is in
1939 win->SendSizeEvent();
1942 [anim setDelegate:nil];
1943 [animDelegate release];
1949 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1950 wxShowEffect effect,
1953 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1956 /* note that the drawing order between siblings is not defined under 10.4 */
1957 /* only starting from 10.5 the subview order is respected */
1959 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1960 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1961 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1962 * expects a function returning the new non-enum NSComparsionResult.
1963 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1965 #if defined(NSINTEGER_DEFINED)
1966 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1968 typedef int CocoaWindowCompareFunctionResult;
1971 class CocoaWindowCompareContext
1973 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1975 CocoaWindowCompareContext(); // Not implemented
1976 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1979 // Cocoa sorts subviews in-place.. make a copy
1980 m_subviews = [subviews copy];
1983 ~CocoaWindowCompareContext()
1984 { // release the copy
1985 [m_subviews release];
1988 { return m_target; }
1991 { return m_subviews; }
1993 /* Helper function that returns the comparison based off of the original ordering */
1994 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1996 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1997 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1998 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1999 // likely compare higher than the other view which is reasonable considering the only way that
2000 // can happen is if the subview was added after our call to subviews but before the call to
2001 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
2002 // that case should never occur anyway because that would imply a multi-threaded GUI call
2003 // which is a big no-no with Cocoa.
2005 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
2006 NSComparisonResult result = (firstI < secondI)
2007 ? NSOrderedAscending /* -1 */
2008 : (firstI > secondI)
2009 ? NSOrderedDescending /* 1 */
2010 : NSOrderedSame /* 0 */;
2015 /* The subview we are trying to Raise or Lower */
2017 /* A copy of the original array of subviews */
2018 NSArray *m_subviews;
2021 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2022 * the target view is always higher than every other view. When comparing two views neither of
2023 * which is the target, it returns the correct response based on the original ordering
2025 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2027 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2028 // first should be ordered higher
2029 if(first==compareContext->target())
2030 return NSOrderedDescending;
2031 // second should be ordered higher
2032 if(second==compareContext->target())
2033 return NSOrderedAscending;
2034 return compareContext->CompareUsingOriginalOrdering(first,second);
2037 void wxWidgetCocoaImpl::Raise()
2039 NSView* nsview = m_osxView;
2041 NSView *superview = [nsview superview];
2042 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2044 [superview sortSubviewsUsingFunction:
2045 CocoaRaiseWindowCompareFunction
2046 context: &compareContext];
2050 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2051 * the target view is always lower than every other view. When comparing two views neither of
2052 * which is the target, it returns the correct response based on the original ordering
2054 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2056 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2057 // first should be ordered lower
2058 if(first==compareContext->target())
2059 return NSOrderedAscending;
2060 // second should be ordered lower
2061 if(second==compareContext->target())
2062 return NSOrderedDescending;
2063 return compareContext->CompareUsingOriginalOrdering(first,second);
2066 void wxWidgetCocoaImpl::Lower()
2068 NSView* nsview = m_osxView;
2070 NSView *superview = [nsview superview];
2071 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2073 [superview sortSubviewsUsingFunction:
2074 CocoaLowerWindowCompareFunction
2075 context: &compareContext];
2078 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2083 // We should do something like this, but it wasn't working in 10.4.
2084 if (GetNeedsDisplay() )
2088 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2089 NSSize offset = NSMakeSize((float)dx, (float)dy);
2090 [m_osxView scrollRect:r by:offset];
2094 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2096 wxWindowMac* parent = GetWXPeer()->GetParent();
2097 // under Cocoa we might have a contentView in the wxParent to which we have to
2098 // adjust the coordinates
2099 if (parent && [m_osxView superview] != parent->GetHandle() )
2101 int cx = 0,cy = 0,cw = 0,ch = 0;
2102 if ( parent->GetPeer() )
2104 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2109 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2110 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2111 [m_osxView setFrame:r];
2112 [[m_osxView superview] setNeedsDisplayInRect:r];
2115 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2117 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2121 // under Cocoa we might have a contentView in the wxParent to which we have to
2122 // adjust the coordinates
2123 wxWindowMac* parent = GetWXPeer()->GetParent();
2124 if (parent && [m_osxView superview] != parent->GetHandle() )
2126 int cx = 0,cy = 0,cw = 0,ch = 0;
2127 if ( parent->GetPeer() )
2129 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2136 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2138 NSRect rect = [m_osxView frame];
2139 width = (int)rect.size.width;
2140 height = (int)rect.size.height;
2143 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2145 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2147 NSView* cv = [m_osxView contentView];
2149 NSRect bounds = [m_osxView bounds];
2150 NSRect rect = [cv frame];
2152 int y = (int)rect.origin.y;
2153 int x = (int)rect.origin.x;
2154 if ( ![ m_osxView isFlipped ] )
2155 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2158 width = (int)rect.size.width;
2159 height = (int)rect.size.height;
2164 GetSize( width, height );
2168 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2171 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2173 [m_osxView setNeedsDisplay:YES];
2176 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2178 return [m_osxView needsDisplay];
2181 bool wxWidgetCocoaImpl::CanFocus() const
2183 return [m_osxView canBecomeKeyView] == YES;
2186 bool wxWidgetCocoaImpl::HasFocus() const
2188 return ( FindFocus() == m_osxView );
2191 bool wxWidgetCocoaImpl::SetFocus()
2196 // TODO remove if no issues arise: should not raise the window, only assign focus
2197 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2198 [[m_osxView window] makeFirstResponder: m_osxView] ;
2202 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2204 [m_osxView unregisterDraggedTypes];
2206 if ( target == NULL )
2209 wxDataObject* dobj = target->GetDataObject();
2213 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2214 dobj->AddSupportedTypes(typesarray);
2215 NSView* targetView = m_osxView;
2216 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2217 targetView = [(NSScrollView*) m_osxView documentView];
2219 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2220 CFRelease(typesarray);
2224 void wxWidgetCocoaImpl::RemoveFromParent()
2226 [m_osxView removeFromSuperview];
2229 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2231 NSView* container = parent->GetWXWidget() ;
2232 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2233 [container addSubview:m_osxView];
2235 if( m_wxPeer->IsFrozen() )
2236 [[m_osxView window] disableFlushWindow];
2239 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2241 NSView* targetView = m_osxView;
2242 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2243 targetView = [(NSScrollView*) m_osxView documentView];
2245 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2247 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2248 green:(CGFloat) (col.Green() / 255.0)
2249 blue:(CGFloat) (col.Blue() / 255.0)
2250 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2254 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2256 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2258 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2260 [m_osxView setOpaque: opaque];
2266 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2268 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2270 wxCFStringRef cf( title , encoding );
2271 [m_osxView setTitle:cf.AsNSString()];
2273 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2275 wxCFStringRef cf( title , encoding );
2276 [m_osxView setStringValue:cf.AsNSString()];
2281 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2283 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2284 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2285 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2288 wxInt32 wxWidgetCocoaImpl::GetValue() const
2290 return [(NSControl*)m_osxView intValue];
2293 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2295 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2297 [m_osxView setIntValue:v];
2299 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2301 [m_osxView setFloatValue:(double)v];
2303 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2305 [m_osxView setDoubleValue:(double)v];
2309 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2311 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2313 [m_osxView setMinValue:(double)v];
2317 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2319 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2321 [m_osxView setMaxValue:(double)v];
2325 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2327 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2329 return (int)[m_osxView minValue];
2334 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2336 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2338 return (int)[m_osxView maxValue];
2343 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2347 // TODO: how to create a wxBitmap from NSImage?
2349 if ( [m_osxView respondsToSelector:@selector(image:)] )
2350 bmp = [m_osxView image];
2356 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2358 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2361 [m_osxView setImage:bitmap.GetNSImage()];
2363 [m_osxView setImage:nil];
2365 [m_osxView setNeedsDisplay:YES];
2369 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2371 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2373 NSCellImagePosition pos;
2393 wxFAIL_MSG( "invalid image position" );
2397 [m_osxView setImagePosition:pos];
2401 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2403 // implementation in subclass
2406 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2408 r->x = r->y = r->width = r->height = 0;
2410 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2412 NSRect former = [m_osxView frame];
2413 [m_osxView sizeToFit];
2414 NSRect best = [m_osxView frame];
2415 [m_osxView setFrame:former];
2416 r->width = (int)best.size.width;
2417 r->height = (int)best.size.height;
2421 bool wxWidgetCocoaImpl::IsEnabled() const
2423 NSView* targetView = m_osxView;
2424 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2425 targetView = [(NSScrollView*) m_osxView documentView];
2427 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2428 return [targetView isEnabled];
2432 void wxWidgetCocoaImpl::Enable( bool enable )
2434 NSView* targetView = m_osxView;
2435 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2436 targetView = [(NSScrollView*) m_osxView documentView];
2438 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2439 [targetView setEnabled:enable];
2442 void wxWidgetCocoaImpl::PulseGauge()
2446 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2450 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2452 NSControlSize size = NSRegularControlSize;
2456 case wxWINDOW_VARIANT_NORMAL :
2457 size = NSRegularControlSize;
2460 case wxWINDOW_VARIANT_SMALL :
2461 size = NSSmallControlSize;
2464 case wxWINDOW_VARIANT_MINI :
2465 size = NSMiniControlSize;
2468 case wxWINDOW_VARIANT_LARGE :
2469 size = NSRegularControlSize;
2473 wxFAIL_MSG(wxT("unexpected window variant"));
2476 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2477 [m_osxView setControlSize:size];
2478 else if ([m_osxView respondsToSelector:@selector(cell)])
2480 id cell = [(id)m_osxView cell];
2481 if ([cell respondsToSelector:@selector(setControlSize:)])
2482 [cell setControlSize:size];
2485 // we need to propagate this to inner views as well
2486 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2488 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2490 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2491 [targetView setControlSize:size];
2492 else if ([targetView respondsToSelector:@selector(cell)])
2494 id cell = [(id)targetView cell];
2495 if ([cell respondsToSelector:@selector(setControlSize:)])
2496 [cell setControlSize:size];
2501 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2503 NSView* targetView = m_osxView;
2504 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2505 targetView = [(NSScrollView*) m_osxView documentView];
2507 if ([targetView respondsToSelector:@selector(setFont:)])
2508 [targetView setFont: font.OSXGetNSFont()];
2509 if ([targetView respondsToSelector:@selector(setTextColor:)])
2510 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2511 green:(CGFloat) (col.Green() / 255.0)
2512 blue:(CGFloat) (col.Blue() / 255.0)
2513 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2516 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2520 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2521 [m_osxView setToolTip: cf.AsNSString()];
2525 [m_osxView setToolTip:nil];
2529 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2531 WXWidget c = control ? control : (WXWidget) m_osxView;
2532 wxWidgetImpl::Associate( c, this ) ;
2533 if ([c respondsToSelector:@selector(setAction:)])
2536 if ( dynamic_cast<wxRadioButton*>(GetWXPeer()) )
2538 // everything already set up
2541 [c setAction: @selector(controlAction:)];
2543 if ([c respondsToSelector:@selector(setDoubleAction:)])
2545 [c setDoubleAction: @selector(controlDoubleAction:)];
2549 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2550 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2551 [m_osxView addTrackingArea: area];
2555 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2557 wxKeyEvent wxevent(wxEVT_CHAR);
2558 SetupKeyEvent( wxevent, event, text );
2560 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2563 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2565 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2566 SetupKeyEvent( wxevent, event );
2568 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2569 // the key is pressed, not when it's released (the type of wxevent is
2570 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2571 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2573 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2574 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2575 && !eventHook.IsNextEventAllowed() )
2579 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2581 // this will fire higher level events, like insertText, to help
2582 // us handle EVT_CHAR, etc.
2586 if ( [event type] == NSKeyDown)
2588 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2590 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2592 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2593 wxKeyEvent wxevent2(wxevent) ;
2594 wxevent2.SetEventType(wxEVT_CHAR);
2595 SetupKeyEvent( wxevent2, event );
2596 wxevent2.m_keyCode = keycode;
2597 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2599 else if (wxevent.CmdDown())
2601 wxKeyEvent wxevent2(wxevent) ;
2602 wxevent2.SetEventType(wxEVT_CHAR);
2603 SetupKeyEvent( wxevent2, event );
2604 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2608 if ( IsUserPane() && !wxevent.CmdDown() )
2610 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2611 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2613 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2623 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2625 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2626 SetupMouseEvent(wxevent , event) ;
2627 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2629 (void)SetupCursor(event);
2634 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2636 wxWindow* thisWindow = GetWXPeer();
2637 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2639 thisWindow->MacInvalidateBorders();
2642 if ( receivedFocus )
2644 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2645 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2646 thisWindow->HandleWindowEvent(eventFocus);
2649 if ( thisWindow->GetCaret() )
2650 thisWindow->GetCaret()->OnSetFocus();
2653 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2654 event.SetEventObject(thisWindow);
2656 event.SetWindow(otherWindow->GetWXPeer());
2657 thisWindow->HandleWindowEvent(event) ;
2659 else // !receivedFocus
2662 if ( thisWindow->GetCaret() )
2663 thisWindow->GetCaret()->OnKillFocus();
2666 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2668 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2669 event.SetEventObject(thisWindow);
2671 event.SetWindow(otherWindow->GetWXPeer());
2672 thisWindow->HandleWindowEvent(event) ;
2676 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2680 NSPoint location = [NSEvent mouseLocation];
2681 location = [[m_osxView window] convertScreenToBase:location];
2682 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2684 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2686 [(NSCursor*)cursor.GetHCURSOR() set];
2691 void wxWidgetCocoaImpl::CaptureMouse()
2693 // TODO remove if we don't get into problems with cursor settings
2694 // [[m_osxView window] disableCursorRects];
2697 void wxWidgetCocoaImpl::ReleaseMouse()
2699 // TODO remove if we don't get into problems with cursor settings
2700 // [[m_osxView window] enableCursorRects];
2703 #if !wxOSX_USE_NATIVE_FLIPPED
2705 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2707 m_isFlipped = flipped;
2712 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2716 [[m_osxView window] enableFlushWindow];
2717 [m_osxView setNeedsDisplay:YES];
2721 [[m_osxView window] disableFlushWindow];
2728 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2729 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2730 long WXUNUSED(style), long WXUNUSED(extraStyle))
2732 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2733 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2735 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2739 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2741 NSWindow* tlw = now->GetWXWindow();
2743 wxWidgetCocoaImpl* c = NULL;
2744 if ( now->IsNativeWindowWrapper() )
2746 NSView* cv = [tlw contentView];
2747 c = new wxWidgetCocoaImpl( now, cv, true );
2750 // increase ref count, because the impl destructor will decrement it again
2752 if ( !now->IsShown() )
2758 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2759 c = new wxWidgetCocoaImpl( now, v, true );
2760 c->InstallEventHandler();
2761 [tlw setContentView:v];