1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/window.mm
3 // Purpose: widgets (non tlw) for cocoa
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
15 #include "wx/dcclient.h"
18 #include "wx/textctrl.h"
19 #include "wx/combobox.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* GetViewFromResponder( 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 = GetViewFromResponder([keyWindow firstResponder]);
72 WXWidget wxWidgetImpl::FindFocus()
74 return GetFocusedViewInWindow( [NSApp keyWindow] );
77 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
81 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
82 wxRect bounds(x,y,w,h);
83 NSView* sv = (window->GetParent()->GetHandle() );
85 return wxToNSRect( sv, bounds );
88 @interface wxNSView : NSView
91 NSTrackingRectTag _lastToolTipTrackTag;
99 @interface NSView(PossibleMethods)
100 - (void)setTitle:(NSString *)aString;
101 - (void)setStringValue:(NSString *)aString;
102 - (void)setIntValue:(int)anInt;
103 - (void)setFloatValue:(float)aFloat;
104 - (void)setDoubleValue:(double)aDouble;
108 - (void)setMinValue:(double)aDouble;
109 - (void)setMaxValue:(double)aDouble;
114 - (void)setEnabled:(BOOL)flag;
116 - (void)setImage:(NSImage *)image;
117 - (void)setControlSize:(NSControlSize)size;
119 - (void)setFont:(NSFont *)fontObject;
123 - (void)setTarget:(id)anObject;
124 - (void)setAction:(SEL)aSelector;
125 - (void)setDoubleAction:(SEL)aSelector;
126 - (void)setBackgroundColor:(NSColor*)aColor;
127 - (void)setOpaque:(BOOL)opaque;
128 - (void)setTextColor:(NSColor *)color;
129 - (void)setImagePosition:(NSCellImagePosition)aPosition;
132 // The following code is a combination of the code listed here:
133 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
134 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
135 // and the code here:
136 // http://inquisitivecocoa.com/category/objective-c/
137 @interface NSEvent (OsGuiUtilsAdditions)
138 - (NSString*) charactersIgnoringModifiersIncludingShift;
141 @implementation NSEvent (OsGuiUtilsAdditions)
142 - (NSString*) charactersIgnoringModifiersIncludingShift {
143 // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
144 // differently than AppKit.
145 NSString* c = [self charactersIgnoringModifiers];
146 if ([c length] == 1) {
147 unichar codepoint = [c characterAtIndex:0];
148 if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
152 // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
153 // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
154 // which hints the OS to use Latin characters where possible, which is generally what we want.
155 NSString* result = @"";
156 TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
157 CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
158 CFRelease(currentKeyboard);
160 // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
163 const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
164 if (keyboardLayout) {
165 UInt32 deadKeyState = 0;
166 UniCharCount maxStringLength = 255;
167 UniCharCount actualStringLength = 0;
168 UniChar unicodeString[maxStringLength];
170 OSStatus status = UCKeyTranslate(keyboardLayout,
173 cmdKey >> 8, // force the Command key to "on"
175 kUCKeyTranslateNoDeadKeysMask,
182 result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
188 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
192 if ([event type] != NSFlagsChanged)
194 NSString* s = [event charactersIgnoringModifiersIncludingShift];
195 // backspace char reports as delete w/modifiers for some reason
198 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
200 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
204 switch ( [s characterAtIndex:0] )
211 case NSUpArrowFunctionKey :
214 case NSDownArrowFunctionKey :
217 case NSLeftArrowFunctionKey :
220 case NSRightArrowFunctionKey :
223 case NSInsertFunctionKey :
226 case NSDeleteFunctionKey :
229 case NSHomeFunctionKey :
232 // case NSBeginFunctionKey :
233 // retval = WXK_BEGIN;
235 case NSEndFunctionKey :
238 case NSPageUpFunctionKey :
241 case NSPageDownFunctionKey :
242 retval = WXK_PAGEDOWN;
244 case NSHelpFunctionKey :
248 int intchar = [s characterAtIndex: 0];
249 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
250 retval = WXK_F1 + (intchar - NSF1FunctionKey );
251 else if ( intchar > 0 && intchar < 32 )
259 // Some keys don't seem to have constants. The code mimics the approach
260 // taken by WebKit. See:
261 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
262 switch( [event keyCode] )
267 retval = WXK_CONTROL;
271 retval = WXK_CAPITAL;
274 case 56: // Left Shift
275 case 60: // Right Shift
280 case 61: // Right Alt
284 case 59: // Left Ctrl
285 case 62: // Right Ctrl
286 retval = WXK_RAW_CONTROL;
300 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
301 // WXK_NUMPAD constants, but for the CHAR event we want to use the
302 // standard ascii values
303 if ( eventType != wxEVT_CHAR )
305 switch( [event keyCode] )
308 retval = WXK_NUMPAD_DIVIDE;
311 retval = WXK_NUMPAD_MULTIPLY;
314 retval = WXK_NUMPAD_SUBTRACT;
317 retval = WXK_NUMPAD_ADD;
320 retval = WXK_NUMPAD_ENTER;
323 retval = WXK_NUMPAD_DECIMAL;
326 retval = WXK_NUMPAD0;
329 retval = WXK_NUMPAD1;
332 retval = WXK_NUMPAD2;
335 retval = WXK_NUMPAD3;
338 retval = WXK_NUMPAD4;
341 retval = WXK_NUMPAD5;
344 retval = WXK_NUMPAD6;
347 retval = WXK_NUMPAD7;
350 retval = WXK_NUMPAD8;
353 retval = WXK_NUMPAD9;
356 //retval = [event keyCode];
363 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
365 UInt32 modifiers = [nsEvent modifierFlags] ;
366 int eventType = [nsEvent type];
368 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
369 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
370 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
371 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
373 wxevent.m_rawCode = [nsEvent keyCode];
374 wxevent.m_rawFlags = modifiers;
376 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
379 if ( eventType != NSFlagsChanged )
381 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
384 // if charString is set, it did not come from key up / key down
385 wxevent.SetEventType( wxEVT_CHAR );
386 chars = wxCFStringRef::AsString(charString);
390 chars = wxCFStringRef::AsString(nschars);
394 int aunichar = chars.Length() > 0 ? chars[0] : 0;
397 if (wxevent.GetEventType() != wxEVT_CHAR)
399 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
403 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
406 wxevent.SetEventType( wxEVT_KEY_UP ) ;
408 case NSFlagsChanged :
412 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
415 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
418 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
420 case WXK_RAW_CONTROL:
421 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
432 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
433 keyval = wxToupper( aunichar ) ;
439 // OS X generates events with key codes in Unicode private use area for
440 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
441 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
442 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
443 // WXK_NONE for "non characters" so explicitly exclude them.
445 // We only exclude the private use area inside the Basic Multilingual Plane
446 // as key codes beyond it don't seem to be currently used.
447 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
448 wxevent.m_uniChar = aunichar;
450 wxevent.m_keyCode = keyval;
452 wxWindowMac* peer = GetWXPeer();
455 wxevent.SetEventObject(peer);
456 wxevent.SetId(peer->GetId()) ;
460 UInt32 g_lastButton = 0 ;
461 bool g_lastButtonWasFakeRight = false ;
463 // better scroll wheel support
464 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
466 @interface NSEvent (DeviceDelta)
467 - (CGFloat)deviceDeltaX;
468 - (CGFloat)deviceDeltaY;
471 - (BOOL)hasPreciseScrollingDeltas;
472 - (CGFloat)scrollingDeltaX;
473 - (CGFloat)scrollingDeltaY;
476 void wxWidgetCocoaImpl::SetupCoordinates(wxCoord &x, wxCoord &y, NSEvent* nsEvent)
478 NSPoint locationInWindow = [nsEvent locationInWindow];
480 // adjust coordinates for the window of the target view
481 if ( [nsEvent window] != [m_osxView window] )
483 if ( [nsEvent window] != nil )
484 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
486 if ( [m_osxView window] != nil )
487 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
490 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
491 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
493 x = locationInViewWX.x;
494 y = locationInViewWX.y;
498 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
500 int eventType = [nsEvent type];
501 UInt32 modifiers = [nsEvent modifierFlags] ;
503 SetupCoordinates(wxevent.m_x, wxevent.m_y, nsEvent);
505 // these parameters are not given for all events
506 UInt32 button = [nsEvent buttonNumber];
507 UInt32 clickCount = 0;
509 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
510 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
511 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
512 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
513 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
515 UInt32 mouseChord = 0;
519 case NSLeftMouseDown :
520 case NSLeftMouseDragged :
523 case NSRightMouseDown :
524 case NSRightMouseDragged :
527 case NSOtherMouseDown :
528 case NSOtherMouseDragged :
533 // a control click is interpreted as a right click
534 bool thisButtonIsFakeRight = false ;
535 if ( button == 0 && (modifiers & NSControlKeyMask) )
538 thisButtonIsFakeRight = true ;
541 // otherwise we report double clicks by connecting a left click with a ctrl-left click
542 if ( clickCount > 1 && button != g_lastButton )
545 // we must make sure that our synthetic 'right' button corresponds in
546 // mouse down, moved and mouse up, and does not deliver a right down and left up
549 case NSLeftMouseDown :
550 case NSRightMouseDown :
551 case NSOtherMouseDown :
552 g_lastButton = button ;
553 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
560 g_lastButtonWasFakeRight = false ;
562 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
563 button = g_lastButton ;
565 // Adjust the chord mask to remove the primary button and add the
566 // secondary button. It is possible that the secondary button is
567 // already pressed, e.g. on a mouse connected to a laptop, but this
568 // possibility is ignored here:
569 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
570 mouseChord = ((mouseChord & ~1U) | 2U);
573 wxevent.m_leftDown = true ;
575 wxevent.m_rightDown = true ;
577 wxevent.m_middleDown = true ;
579 // translate into wx types
582 case NSLeftMouseDown :
583 case NSRightMouseDown :
584 case NSOtherMouseDown :
585 clickCount = [nsEvent clickCount];
589 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
593 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
597 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
606 case NSRightMouseUp :
607 case NSOtherMouseUp :
608 clickCount = [nsEvent clickCount];
612 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
616 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
620 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
633 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
635 if ( UMAGetSystemVersion() >= 0x1070 )
637 if ( [nsEvent hasPreciseScrollingDeltas] )
639 deltaX = [nsEvent scrollingDeltaX];
640 deltaY = [nsEvent scrollingDeltaY];
644 deltaX = [nsEvent scrollingDeltaX] * 10;
645 deltaY = [nsEvent scrollingDeltaY] * 10;
650 const EventRef cEvent = (EventRef) [nsEvent eventRef];
651 // see http://developer.apple.com/qa/qa2005/qa1453.html
652 // for more details on why we have to look for the exact type
654 bool isMouseScrollEvent = false;
656 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
658 if ( isMouseScrollEvent )
660 deltaX = [nsEvent deviceDeltaX];
661 deltaY = [nsEvent deviceDeltaY];
665 deltaX = ([nsEvent deltaX] * 10);
666 deltaY = ([nsEvent deltaY] * 10);
670 wxevent.m_wheelDelta = 10;
671 wxevent.m_linesPerAction = 1;
673 if ( fabs(deltaX) > fabs(deltaY) )
675 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
676 wxevent.m_wheelRotation = (int)deltaX;
680 wxevent.m_wheelRotation = (int)deltaY;
686 case NSMouseEntered :
687 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
690 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
692 case NSLeftMouseDragged :
693 case NSRightMouseDragged :
694 case NSOtherMouseDragged :
696 wxevent.SetEventType( wxEVT_MOTION ) ;
702 wxevent.m_clickCount = clickCount;
703 wxWindowMac* peer = GetWXPeer();
706 wxevent.SetEventObject(peer);
707 wxevent.SetId(peer->GetId()) ;
711 @implementation wxNSView
715 static BOOL initialized = NO;
719 wxOSXCocoaClassAddWXMethods( self );
723 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
724 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
728 - (void)_sendToolTipMouseExited
730 // Nothing matters except window, trackingNumber, and userData.
731 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
732 location:NSMakePoint(0, 0)
735 windowNumber:[[self window] windowNumber]
738 trackingNumber:_lastToolTipTrackTag
739 userData:_lastUserData];
740 [_lastToolTipOwner mouseExited:fakeEvent];
743 - (void)_sendToolTipMouseEntered
745 // Nothing matters except window, trackingNumber, and userData.
746 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
747 location:NSMakePoint(0, 0)
750 windowNumber:[[self window] windowNumber]
753 trackingNumber:_lastToolTipTrackTag
754 userData:_lastUserData];
755 [_lastToolTipOwner mouseEntered:fakeEvent];
758 - (void)setToolTip:(NSString *)string;
764 [self _sendToolTipMouseExited];
767 [super setToolTip:string];
769 [self _sendToolTipMouseEntered];
775 [self _sendToolTipMouseExited];
776 [super setToolTip:nil];
782 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
784 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
787 _lastUserData = data;
788 _lastToolTipOwner = owner;
789 _lastToolTipTrackTag = tag;
794 - (void)removeTrackingRect:(NSTrackingRectTag)tag
796 if (tag == _lastToolTipTrackTag)
798 _lastUserData = NULL;
799 _lastToolTipOwner = nil;
800 _lastToolTipTrackTag = 0;
802 [super removeTrackingRect:tag];
805 #if wxOSX_USE_NATIVE_FLIPPED
812 - (BOOL) canBecomeKeyView
814 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
815 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
816 return viewimpl->GetWXPeer()->AcceptsFocus();
826 #if wxUSE_DRAG_AND_DROP
828 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
829 // for details on the NSPasteboard -> PasteboardRef conversion
831 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
833 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
835 return NSDragOperationNone;
837 return impl->draggingEntered(sender, self, _cmd);
840 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
842 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
846 return impl->draggingExited(sender, self, _cmd);
849 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
851 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
853 return NSDragOperationNone;
855 return impl->draggingUpdated(sender, self, _cmd);
858 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
860 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
862 return NSDragOperationNone;
864 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
869 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
871 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
875 impl->mouseEvent(event, self, _cmd);
878 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
880 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
884 impl->cursorUpdate(event, self, _cmd);
887 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
889 // This is needed to support click through, otherwise the first click on a window
890 // will not do anything unless it is the active window already.
894 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
896 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
900 impl->keyEvent(event, self, _cmd);
903 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
905 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
909 impl->insertText(text, self, _cmd);
912 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
914 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
918 return impl->performKeyEquivalent(event, self, _cmd);
921 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
923 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
927 return impl->acceptsFirstResponder(self, _cmd);
930 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
932 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
936 return impl->becomeFirstResponder(self, _cmd);
939 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
941 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
945 return impl->resignFirstResponder(self, _cmd);
948 #if !wxOSX_USE_NATIVE_FLIPPED
950 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
952 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
956 return impl->isFlipped(self, _cmd) ? YES:NO;
961 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
963 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
965 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
970 // OS X starts a NSUIHeartBeatThread for animating the default button in a
971 // dialog. This causes a drawRect of the active dialog from outside the
972 // main UI thread. This causes an occasional crash since the wx drawing
973 // objects (like wxPen) are not thread safe.
975 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
976 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
977 if ( !wxThread::IsMain() )
979 if ( impl->IsUserPane() )
981 wxWindow* win = impl->GetWXPeer();
982 if ( win->UseBgCol() )
985 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
986 CGContextSaveGState( context );
988 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
989 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
990 CGContextFillRect( context, r );
992 CGContextRestoreGState( context );
997 // just call the superclass handler, we don't need any custom wx drawing
998 // here and it seems to work fine:
999 wxOSX_DrawRectHandlerPtr
1000 superimpl = (wxOSX_DrawRectHandlerPtr)
1001 [[self superclass] instanceMethodForSelector:_cmd];
1002 superimpl(self, _cmd, rect);
1007 #endif // wxUSE_THREADS
1009 return impl->drawRect(&rect, self, _cmd);
1012 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
1014 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1018 impl->controlAction(self, _cmd, sender);
1021 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
1023 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1027 impl->controlDoubleAction(self, _cmd, sender);
1030 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1032 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1033 NSPasteboard *pboard = [sender draggingPasteboard];
1034 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1036 wxWindow* wxpeer = GetWXPeer();
1037 if ( wxpeer == NULL )
1038 return NSDragOperationNone;
1040 wxDropTarget* target = wxpeer->GetDropTarget();
1041 if ( target == NULL )
1042 return NSDragOperationNone;
1044 wxDragResult result = wxDragNone;
1045 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1046 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1048 if ( sourceDragMask & NSDragOperationLink )
1049 result = wxDragLink;
1050 else if ( sourceDragMask & NSDragOperationCopy )
1051 result = wxDragCopy;
1052 else if ( sourceDragMask & NSDragOperationMove )
1053 result = wxDragMove;
1055 PasteboardRef pboardRef;
1056 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1057 target->SetCurrentDragPasteboard(pboardRef);
1058 result = target->OnEnter(pt.x, pt.y, result);
1059 CFRelease(pboardRef);
1061 NSDragOperation nsresult = NSDragOperationNone;
1065 nsresult = NSDragOperationLink;
1067 nsresult = NSDragOperationMove;
1069 nsresult = NSDragOperationCopy;
1076 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1078 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1079 NSPasteboard *pboard = [sender draggingPasteboard];
1081 wxWindow* wxpeer = GetWXPeer();
1082 if ( wxpeer == NULL )
1085 wxDropTarget* target = wxpeer->GetDropTarget();
1086 if ( target == NULL )
1089 PasteboardRef pboardRef;
1090 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1091 target->SetCurrentDragPasteboard(pboardRef);
1093 CFRelease(pboardRef);
1096 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1098 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1099 NSPasteboard *pboard = [sender draggingPasteboard];
1100 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1102 wxWindow* wxpeer = GetWXPeer();
1103 if ( wxpeer == NULL )
1104 return NSDragOperationNone;
1106 wxDropTarget* target = wxpeer->GetDropTarget();
1107 if ( target == NULL )
1108 return NSDragOperationNone;
1110 wxDragResult result = wxDragNone;
1111 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1112 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1114 if ( sourceDragMask & NSDragOperationLink )
1115 result = wxDragLink;
1116 else if ( sourceDragMask & NSDragOperationCopy )
1117 result = wxDragCopy;
1118 else if ( sourceDragMask & NSDragOperationMove )
1119 result = wxDragMove;
1121 PasteboardRef pboardRef;
1122 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1123 target->SetCurrentDragPasteboard(pboardRef);
1124 result = target->OnDragOver(pt.x, pt.y, result);
1125 CFRelease(pboardRef);
1127 NSDragOperation nsresult = NSDragOperationNone;
1131 nsresult = NSDragOperationLink;
1133 nsresult = NSDragOperationMove;
1135 nsresult = NSDragOperationCopy;
1142 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1144 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1146 NSPasteboard *pboard = [sender draggingPasteboard];
1147 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1149 wxWindow* wxpeer = GetWXPeer();
1150 wxDropTarget* target = wxpeer->GetDropTarget();
1151 wxDragResult result = wxDragNone;
1152 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1153 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1155 if ( sourceDragMask & NSDragOperationLink )
1156 result = wxDragLink;
1157 else if ( sourceDragMask & NSDragOperationCopy )
1158 result = wxDragCopy;
1159 else if ( sourceDragMask & NSDragOperationMove )
1160 result = wxDragMove;
1162 PasteboardRef pboardRef;
1163 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1164 target->SetCurrentDragPasteboard(pboardRef);
1166 if (target->OnDrop(pt.x, pt.y))
1167 result = target->OnData(pt.x, pt.y, result);
1169 CFRelease(pboardRef);
1171 return result != wxDragNone;
1174 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1175 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1176 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1177 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1179 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1181 if ( !DoHandleMouseEvent(event) )
1183 // for plain NSView mouse events would propagate to parents otherwise
1186 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1187 superimpl(slf, (SEL)_cmd, event);
1189 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1190 // only trigger if at this moment the mouse is already up
1191 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1193 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1194 SetupMouseEvent(wxevent , event) ;
1195 wxevent.SetEventType(wxEVT_LEFT_UP);
1197 GetWXPeer()->HandleWindowEvent(wxevent);
1203 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1205 if ( !SetupCursor(event) )
1207 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1208 superimpl(slf, (SEL)_cmd, event);
1212 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1214 extern wxCursor gGlobalCursor;
1216 if ( gGlobalCursor.IsOk() )
1218 gGlobalCursor.MacInstall();
1223 wxWindow* cursorTarget = GetWXPeer();
1225 SetupCoordinates(x, y, event);
1226 wxPoint cursorPoint( x , y ) ;
1228 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1230 cursorTarget = cursorTarget->GetParent() ;
1232 cursorPoint += cursorTarget->GetPosition();
1235 return cursorTarget != NULL;
1239 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1241 if ( [event type] == NSKeyDown )
1243 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1244 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1245 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1248 m_lastKeyDownEvent = event;
1251 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1253 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1254 superimpl(slf, (SEL)_cmd, event);
1256 m_lastKeyDownEvent = NULL;
1259 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1261 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1263 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1264 superimpl(slf, (SEL)_cmd, text);
1269 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1271 bool handled = false;
1273 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1274 SetupKeyEvent( wxevent, event );
1276 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1277 // walk up the ancestors ourselves but let cocoa do it
1279 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1282 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1284 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1285 command_event.SetEventObject( wxevent.GetEventObject() );
1286 handled = handler->ProcessEvent( command_event );
1290 // accelerators can also be used with buttons, try them too
1291 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1292 handled = handler->ProcessEvent( command_event );
1298 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1299 return superimpl(slf, (SEL)_cmd, event);
1304 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1307 return m_wxPeer->AcceptsFocus();
1310 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1311 return superimpl(slf, (SEL)_cmd);
1315 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1317 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1318 // get the current focus before running becomeFirstResponder
1319 NSView* otherView = FindFocus();
1321 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1322 BOOL r = superimpl(slf, (SEL)_cmd);
1325 DoNotifyFocusEvent( true, otherWindow );
1331 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1333 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1334 BOOL r = superimpl(slf, (SEL)_cmd);
1335 // get the current focus after running resignFirstResponder
1336 // note that this value isn't reliable, it might return the same view that
1338 NSView* otherView = FindFocus();
1339 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1341 // It doesn't make sense to notify about the loss of focus if we're not
1342 // really losing it and the window which has just gained focus is the same
1343 // one as this window itself. Of course, this should never happen in the
1344 // first place but somehow it does in wxGrid code and without this check we
1345 // enter into an infinite recursion, see #12267.
1346 if ( otherWindow == this )
1349 // NSTextViews have an editor as true responder, therefore the might get the
1350 // resign notification if their editor takes over, don't trigger any event then
1351 if ( r && !m_hasEditor)
1353 DoNotifyFocusEvent( false, otherWindow );
1358 #if !wxOSX_USE_NATIVE_FLIPPED
1360 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1367 #define OSX_DEBUG_DRAWING 0
1369 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1371 // preparing the update region
1375 // since adding many rects to a region is a costly process, by default use the bounding rect
1377 const NSRect *rects;
1379 [slf getRectsBeingDrawn:&rects count:&count];
1380 for ( int i = 0 ; i < count ; ++i )
1382 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1385 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1388 wxWindow* wxpeer = GetWXPeer();
1390 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1392 // as this update region is in native window locals we must adapt it to wx window local
1393 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1396 // Restrict the update region to the shape of the window, if any, and also
1397 // remember the region that we need to clear later.
1398 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1399 const bool isTopLevel = tlwParent == wxpeer;
1401 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1404 clearRgn = updateRgn;
1406 int xoffset = 0, yoffset = 0;
1407 wxRegion rgn = tlwParent->GetShape();
1408 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1409 rgn.Offset( xoffset, yoffset );
1410 updateRgn.Intersect(rgn);
1414 // Exclude the window shape from the region to be cleared below.
1415 rgn.Xor(wxpeer->GetSize());
1416 clearRgn.Intersect(rgn);
1420 wxpeer->GetUpdateRegion() = updateRgn;
1422 // setting up the drawing context
1424 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1425 CGContextSaveGState( context );
1427 #if OSX_DEBUG_DRAWING
1428 CGContextBeginPath( context );
1429 CGContextMoveToPoint(context, 0, 0);
1430 NSRect bounds = [slf bounds];
1431 CGContextAddLineToPoint(context, 10, 0);
1432 CGContextMoveToPoint(context, 0, 0);
1433 CGContextAddLineToPoint(context, 0, 10);
1434 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1435 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1436 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1437 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1438 CGContextClosePath( context );
1439 CGContextStrokePath(context);
1442 if ( ![slf isFlipped] )
1444 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1445 CGContextScaleCTM( context, 1, -1 );
1448 wxpeer->MacSetCGContextRef( context );
1450 bool handled = wxpeer->MacDoRedraw( 0 );
1451 CGContextRestoreGState( context );
1453 CGContextSaveGState( context );
1457 SEL _cmd = @selector(drawRect:);
1458 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1459 superimpl(slf, _cmd, *(NSRect*)rect);
1460 CGContextRestoreGState( context );
1461 CGContextSaveGState( context );
1463 // as we called restore above, we have to flip again if necessary
1464 if ( ![slf isFlipped] )
1466 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1467 CGContextScaleCTM( context, 1, -1 );
1472 // We also need to explicitly draw the part of the top level window
1473 // outside of its region with transparent colour to ensure that it is
1474 // really transparent.
1475 if ( clearRgn.IsOk() )
1477 wxMacCGContextStateSaver saveState(context);
1478 wxWindowDC dc(wxpeer);
1479 dc.SetBackground(wxBrush(wxTransparentColour));
1480 dc.SetDeviceClippingRegion(clearRgn);
1484 #if wxUSE_GRAPHICS_CONTEXT
1485 // If the window shape is defined by a path, stroke the path to show
1486 // the window border.
1487 const wxGraphicsPath& path = tlwParent->GetShapePath();
1488 if ( !path.IsNull() )
1490 CGContextSetLineWidth(context, 1);
1491 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1492 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1493 CGContextStrokePath(context);
1495 #endif // wxUSE_GRAPHICS_CONTEXT
1498 wxpeer->MacPaintChildrenBorders();
1499 wxpeer->MacSetCGContextRef( NULL );
1500 CGContextRestoreGState( context );
1503 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1505 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1508 wxpeer->OSXSimulateFocusEvents();
1509 wxpeer->OSXHandleClicked(0);
1513 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1517 void wxWidgetCocoaImpl::controlTextDidChange()
1519 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1522 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1523 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1524 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1526 tc->SendTextUpdatedEventIfAllowed();
1528 cb->SendTextUpdatedEventIfAllowed();
1531 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1538 #if OBJC_API_VERSION >= 2
1540 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1541 class_addMethod(c, s, i, t );
1545 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1546 { s, (char*) t, i },
1550 void wxOSXCocoaClassAddWXMethods(Class c)
1553 #if OBJC_API_VERSION < 2
1554 static objc_method wxmethods[] =
1558 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1559 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1560 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1562 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1563 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1564 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1566 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1568 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1569 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1570 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1572 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1574 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1575 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1576 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1578 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1580 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1581 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1582 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1584 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1586 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1588 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1589 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1592 #if !wxOSX_USE_NATIVE_FLIPPED
1593 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1595 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1597 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1598 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1600 #if wxUSE_DRAG_AND_DROP
1601 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1603 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1604 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1607 #if OBJC_API_VERSION < 2
1609 static int method_count = WXSIZEOF( wxmethods );
1610 static objc_method_list *wxmethodlist = NULL;
1611 if ( wxmethodlist == NULL )
1613 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1614 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1615 wxmethodlist->method_count = method_count;
1616 wxmethodlist->obsolete = 0;
1618 class_addMethods( c, wxmethodlist );
1623 // C++ implementation class
1626 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1628 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1629 wxWidgetImpl( peer, isRootControl, isUserPane )
1634 // check if the user wants to create the control initially hidden
1635 if ( !peer->IsShown() )
1636 SetVisibility(false);
1638 // gc aware handling
1640 CFRetain(m_osxView);
1641 [m_osxView release];
1644 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1649 void wxWidgetCocoaImpl::Init()
1652 #if !wxOSX_USE_NATIVE_FLIPPED
1655 m_lastKeyDownEvent = NULL;
1656 m_hasEditor = false;
1659 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1661 RemoveAssociations( this );
1663 if ( !IsRootControl() )
1665 NSView *sv = [m_osxView superview];
1667 [m_osxView removeFromSuperview];
1669 // gc aware handling
1671 CFRelease(m_osxView);
1674 bool wxWidgetCocoaImpl::IsVisible() const
1676 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1679 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1681 [m_osxView setHidden:(visible ? NO:YES)];
1684 // ----------------------------------------------------------------------------
1685 // window animation stuff
1686 // ----------------------------------------------------------------------------
1688 // define a delegate used to refresh the window during animation
1689 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1695 - (id)init:(wxWindow *)win;
1699 // NSAnimationDelegate methods
1700 - (void)animationDidEnd:(NSAnimation*)animation;
1701 - (void)animation:(NSAnimation*)animation
1702 didReachProgressMark:(NSAnimationProgress)progress;
1705 @implementation wxNSAnimationDelegate
1707 - (id)init:(wxWindow *)win
1709 self = [super init];
1722 - (void)animation:(NSAnimation*)animation
1723 didReachProgressMark:(NSAnimationProgress)progress
1725 wxUnusedVar(animation);
1726 wxUnusedVar(progress);
1728 m_win->SendSizeEvent();
1729 m_win->MacOnInternalSize();
1732 - (void)animationDidEnd:(NSAnimation*)animation
1734 wxUnusedVar(animation);
1742 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1744 wxShowEffect effect,
1747 // create the dictionary describing the animation to perform on this view
1749 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1750 NSMutableDictionary * const
1751 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1752 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1754 // determine the start and end rectangles assuming we're hiding the window
1755 const wxRect rectOrig = win->GetRect();
1763 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1764 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1765 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1766 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1767 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1768 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1769 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1770 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1771 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1772 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1773 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1774 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1779 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1780 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1784 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1785 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1786 rectEnd.x = rectStart.GetRight();
1790 case wxSHOW_EFFECT_ROLL_TO_TOP:
1791 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1795 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1796 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1797 rectEnd.y = rectStart.GetBottom();
1801 case wxSHOW_EFFECT_EXPAND:
1802 rectEnd.x = rectStart.x + rectStart.width / 2;
1803 rectEnd.y = rectStart.y + rectStart.height / 2;
1808 case wxSHOW_EFFECT_BLEND:
1809 [dict setObject:(show ? NSViewAnimationFadeInEffect
1810 : NSViewAnimationFadeOutEffect)
1811 forKey:NSViewAnimationEffectKey];
1814 case wxSHOW_EFFECT_NONE:
1815 case wxSHOW_EFFECT_MAX:
1816 wxFAIL_MSG( "unexpected animation effect" );
1820 wxFAIL_MSG( "unknown animation effect" );
1826 // we need to restore it to the original rectangle instead of making it
1828 wxSwap(rectStart, rectEnd);
1830 // and as the window is currently hidden, we need to show it for the
1831 // animation to be visible at all (but don't restore it at its full
1832 // rectangle as it shouldn't appear immediately)
1833 win->SetSize(rectStart);
1837 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1838 ? [(NSView *)viewOrWin superview]
1840 const NSRect rStart = wxToNSRect(parentView, rectStart);
1841 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1843 [dict setObject:[NSValue valueWithRect:rStart]
1844 forKey:NSViewAnimationStartFrameKey];
1845 [dict setObject:[NSValue valueWithRect:rEnd]
1846 forKey:NSViewAnimationEndFrameKey];
1848 // create an animation using the values in the above dictionary
1849 NSViewAnimation * const
1850 anim = [[NSViewAnimation alloc]
1851 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1855 // what is a good default duration? Windows uses 200ms, Web frameworks
1856 // use anything from 250ms to 1s... choose something in the middle
1860 [anim setDuration:timeout/1000.]; // duration is in seconds here
1862 // if the window being animated changes its layout depending on its size
1863 // (which is almost always the case) we need to redo it during animation
1865 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1866 // controls in wxInfoBar visibly jump around)
1867 const int NUM_LAYOUTS = 20;
1868 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1869 [anim addProgressMark:f];
1871 wxNSAnimationDelegate * const
1872 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1873 [anim setDelegate:animDelegate];
1874 [anim startAnimation];
1876 // Cocoa is capable of doing animation asynchronously or even from separate
1877 // thread but wx API doesn't provide any way to be notified about the
1878 // animation end and without this we really must ensure that the window has
1879 // the expected (i.e. the same as if a simple Show() had been used) size
1880 // when we return, so block here until the animation finishes
1882 // notice that because the default animation mode is NSAnimationBlocking,
1883 // no user input events ought to be processed from here
1885 wxEventLoopGuarantor ensureEventLoopExistence;
1886 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1887 while ( ![animDelegate isDone] )
1893 // NSViewAnimation is smart enough to hide the NSView being animated at
1894 // the end but we also must ensure that it's hidden for wx too
1897 // and we must also restore its size because it isn't expected to
1898 // change just because the window was hidden
1899 win->SetSize(rectOrig);
1903 // refresh it once again after the end to ensure that everything is in
1905 win->SendSizeEvent();
1906 win->MacOnInternalSize();
1909 [anim setDelegate:nil];
1910 [animDelegate release];
1916 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1917 wxShowEffect effect,
1920 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1923 /* note that the drawing order between siblings is not defined under 10.4 */
1924 /* only starting from 10.5 the subview order is respected */
1926 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1927 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1928 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1929 * expects a function returning the new non-enum NSComparsionResult.
1930 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1932 #if defined(NSINTEGER_DEFINED)
1933 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1935 typedef int CocoaWindowCompareFunctionResult;
1938 class CocoaWindowCompareContext
1940 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1942 CocoaWindowCompareContext(); // Not implemented
1943 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1946 // Cocoa sorts subviews in-place.. make a copy
1947 m_subviews = [subviews copy];
1950 ~CocoaWindowCompareContext()
1951 { // release the copy
1952 [m_subviews release];
1955 { return m_target; }
1958 { return m_subviews; }
1960 /* Helper function that returns the comparison based off of the original ordering */
1961 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1963 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1964 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1965 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1966 // likely compare higher than the other view which is reasonable considering the only way that
1967 // can happen is if the subview was added after our call to subviews but before the call to
1968 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1969 // that case should never occur anyway because that would imply a multi-threaded GUI call
1970 // which is a big no-no with Cocoa.
1972 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1973 NSComparisonResult result = (firstI < secondI)
1974 ? NSOrderedAscending /* -1 */
1975 : (firstI > secondI)
1976 ? NSOrderedDescending /* 1 */
1977 : NSOrderedSame /* 0 */;
1982 /* The subview we are trying to Raise or Lower */
1984 /* A copy of the original array of subviews */
1985 NSArray *m_subviews;
1988 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1989 * the target view is always higher than every other view. When comparing two views neither of
1990 * which is the target, it returns the correct response based on the original ordering
1992 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1994 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1995 // first should be ordered higher
1996 if(first==compareContext->target())
1997 return NSOrderedDescending;
1998 // second should be ordered higher
1999 if(second==compareContext->target())
2000 return NSOrderedAscending;
2001 return compareContext->CompareUsingOriginalOrdering(first,second);
2004 void wxWidgetCocoaImpl::Raise()
2006 NSView* nsview = m_osxView;
2008 NSView *superview = [nsview superview];
2009 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2011 [superview sortSubviewsUsingFunction:
2012 CocoaRaiseWindowCompareFunction
2013 context: &compareContext];
2017 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2018 * the target view is always lower than every other view. When comparing two views neither of
2019 * which is the target, it returns the correct response based on the original ordering
2021 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2023 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2024 // first should be ordered lower
2025 if(first==compareContext->target())
2026 return NSOrderedAscending;
2027 // second should be ordered lower
2028 if(second==compareContext->target())
2029 return NSOrderedDescending;
2030 return compareContext->CompareUsingOriginalOrdering(first,second);
2033 void wxWidgetCocoaImpl::Lower()
2035 NSView* nsview = m_osxView;
2037 NSView *superview = [nsview superview];
2038 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2040 [superview sortSubviewsUsingFunction:
2041 CocoaLowerWindowCompareFunction
2042 context: &compareContext];
2045 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2050 // We should do something like this, but it wasn't working in 10.4.
2051 if (GetNeedsDisplay() )
2055 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2056 NSSize offset = NSMakeSize((float)dx, (float)dy);
2057 [m_osxView scrollRect:r by:offset];
2061 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2063 wxWindowMac* parent = GetWXPeer()->GetParent();
2064 // under Cocoa we might have a contentView in the wxParent to which we have to
2065 // adjust the coordinates
2066 if (parent && [m_osxView superview] != parent->GetHandle() )
2068 int cx = 0,cy = 0,cw = 0,ch = 0;
2069 if ( parent->GetPeer() )
2071 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2076 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2077 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2078 [m_osxView setFrame:r];
2079 [[m_osxView superview] setNeedsDisplayInRect:r];
2082 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2084 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2088 // under Cocoa we might have a contentView in the wxParent to which we have to
2089 // adjust the coordinates
2090 wxWindowMac* parent = GetWXPeer()->GetParent();
2091 if (parent && [m_osxView superview] != parent->GetHandle() )
2093 int cx = 0,cy = 0,cw = 0,ch = 0;
2094 if ( parent->GetPeer() )
2096 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2103 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2105 NSRect rect = [m_osxView frame];
2106 width = (int)rect.size.width;
2107 height = (int)rect.size.height;
2110 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2112 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2114 NSView* cv = [m_osxView contentView];
2116 NSRect bounds = [m_osxView bounds];
2117 NSRect rect = [cv frame];
2119 int y = (int)rect.origin.y;
2120 int x = (int)rect.origin.x;
2121 if ( ![ m_osxView isFlipped ] )
2122 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2125 width = (int)rect.size.width;
2126 height = (int)rect.size.height;
2131 GetSize( width, height );
2135 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2138 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2140 [m_osxView setNeedsDisplay:YES];
2143 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2145 return [m_osxView needsDisplay];
2148 bool wxWidgetCocoaImpl::CanFocus() const
2150 return [m_osxView canBecomeKeyView] == YES;
2153 bool wxWidgetCocoaImpl::HasFocus() const
2155 return ( FindFocus() == m_osxView );
2158 bool wxWidgetCocoaImpl::SetFocus()
2163 // TODO remove if no issues arise: should not raise the window, only assign focus
2164 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2165 [[m_osxView window] makeFirstResponder: m_osxView] ;
2169 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2171 [m_osxView unregisterDraggedTypes];
2173 if ( target == NULL )
2176 wxDataObject* dobj = target->GetDataObject();
2180 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2181 dobj->AddSupportedTypes(typesarray);
2182 NSView* targetView = m_osxView;
2183 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2184 targetView = [(NSScrollView*) m_osxView documentView];
2186 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2187 CFRelease(typesarray);
2191 void wxWidgetCocoaImpl::RemoveFromParent()
2193 [m_osxView removeFromSuperview];
2196 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2198 NSView* container = parent->GetWXWidget() ;
2199 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2200 [container addSubview:m_osxView];
2202 if( m_wxPeer->IsFrozen() )
2203 [[m_osxView window] disableFlushWindow];
2206 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2208 NSView* targetView = m_osxView;
2209 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2210 targetView = [(NSScrollView*) m_osxView documentView];
2212 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2214 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2215 green:(CGFloat) (col.Green() / 255.0)
2216 blue:(CGFloat) (col.Blue() / 255.0)
2217 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2221 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2223 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2225 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2227 [m_osxView setOpaque: opaque];
2233 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2235 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2237 wxCFStringRef cf( title , encoding );
2238 [m_osxView setTitle:cf.AsNSString()];
2240 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2242 wxCFStringRef cf( title , encoding );
2243 [m_osxView setStringValue:cf.AsNSString()];
2248 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2250 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2251 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2252 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2255 wxInt32 wxWidgetCocoaImpl::GetValue() const
2257 return [(NSControl*)m_osxView intValue];
2260 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2262 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2264 [m_osxView setIntValue:v];
2266 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2268 [m_osxView setFloatValue:(double)v];
2270 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2272 [m_osxView setDoubleValue:(double)v];
2276 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2278 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2280 [m_osxView setMinValue:(double)v];
2284 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2286 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2288 [m_osxView setMaxValue:(double)v];
2292 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2294 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2296 return (int)[m_osxView minValue];
2301 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2303 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2305 return (int)[m_osxView maxValue];
2310 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2314 // TODO: how to create a wxBitmap from NSImage?
2316 if ( [m_osxView respondsToSelector:@selector(image:)] )
2317 bmp = [m_osxView image];
2323 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2325 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2328 [m_osxView setImage:bitmap.GetNSImage()];
2330 [m_osxView setImage:nil];
2332 [m_osxView setNeedsDisplay:YES];
2336 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2338 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2340 NSCellImagePosition pos;
2360 wxFAIL_MSG( "invalid image position" );
2364 [m_osxView setImagePosition:pos];
2368 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2370 // implementation in subclass
2373 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2375 r->x = r->y = r->width = r->height = 0;
2377 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2379 NSRect former = [m_osxView frame];
2380 [m_osxView sizeToFit];
2381 NSRect best = [m_osxView frame];
2382 [m_osxView setFrame:former];
2383 r->width = (int)best.size.width;
2384 r->height = (int)best.size.height;
2388 bool wxWidgetCocoaImpl::IsEnabled() const
2390 NSView* targetView = m_osxView;
2391 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2392 targetView = [(NSScrollView*) m_osxView documentView];
2394 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2395 return [targetView isEnabled];
2399 void wxWidgetCocoaImpl::Enable( bool enable )
2401 NSView* targetView = m_osxView;
2402 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2403 targetView = [(NSScrollView*) m_osxView documentView];
2405 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2406 [targetView setEnabled:enable];
2409 void wxWidgetCocoaImpl::PulseGauge()
2413 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2417 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2419 NSControlSize size = NSRegularControlSize;
2423 case wxWINDOW_VARIANT_NORMAL :
2424 size = NSRegularControlSize;
2427 case wxWINDOW_VARIANT_SMALL :
2428 size = NSSmallControlSize;
2431 case wxWINDOW_VARIANT_MINI :
2432 size = NSMiniControlSize;
2435 case wxWINDOW_VARIANT_LARGE :
2436 size = NSRegularControlSize;
2440 wxFAIL_MSG(wxT("unexpected window variant"));
2443 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2444 [m_osxView setControlSize:size];
2445 else if ([m_osxView respondsToSelector:@selector(cell)])
2447 id cell = [(id)m_osxView cell];
2448 if ([cell respondsToSelector:@selector(setControlSize:)])
2449 [cell setControlSize:size];
2452 // we need to propagate this to inner views as well
2453 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2455 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2457 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2458 [targetView setControlSize:size];
2459 else if ([targetView respondsToSelector:@selector(cell)])
2461 id cell = [(id)targetView cell];
2462 if ([cell respondsToSelector:@selector(setControlSize:)])
2463 [cell setControlSize:size];
2468 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2470 NSView* targetView = m_osxView;
2471 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2472 targetView = [(NSScrollView*) m_osxView documentView];
2474 if ([targetView respondsToSelector:@selector(setFont:)])
2475 [targetView setFont: font.OSXGetNSFont()];
2476 if ([targetView respondsToSelector:@selector(setTextColor:)])
2477 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2478 green:(CGFloat) (col.Green() / 255.0)
2479 blue:(CGFloat) (col.Blue() / 255.0)
2480 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2483 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2487 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2488 [m_osxView setToolTip: cf.AsNSString()];
2492 [m_osxView setToolTip:nil];
2496 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2498 WXWidget c = control ? control : (WXWidget) m_osxView;
2499 wxWidgetImpl::Associate( c, this ) ;
2500 if ([c respondsToSelector:@selector(setAction:)])
2503 [c setAction: @selector(controlAction:)];
2504 if ([c respondsToSelector:@selector(setDoubleAction:)])
2506 [c setDoubleAction: @selector(controlDoubleAction:)];
2510 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2511 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2512 [m_osxView addTrackingArea: area];
2516 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2518 wxKeyEvent wxevent(wxEVT_CHAR);
2519 SetupKeyEvent( wxevent, event, text );
2521 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2524 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2526 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2527 SetupKeyEvent( wxevent, event );
2529 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2530 // the key is pressed, not when it's released (the type of wxevent is
2531 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2532 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2534 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2535 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2536 && !eventHook.IsNextEventAllowed() )
2540 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2542 // this will fire higher level events, like insertText, to help
2543 // us handle EVT_CHAR, etc.
2547 if ( [event type] == NSKeyDown)
2549 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2551 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2553 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2554 wxKeyEvent wxevent2(wxevent) ;
2555 wxevent2.SetEventType(wxEVT_CHAR);
2556 SetupKeyEvent( wxevent2, event );
2557 wxevent2.m_keyCode = keycode;
2558 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2560 else if (wxevent.CmdDown())
2562 wxKeyEvent wxevent2(wxevent) ;
2563 wxevent2.SetEventType(wxEVT_CHAR);
2564 SetupKeyEvent( wxevent2, event );
2565 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2569 if ( IsUserPane() && !wxevent.CmdDown() )
2571 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2572 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2574 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2584 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2586 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2587 SetupMouseEvent(wxevent , event) ;
2588 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2590 (void)SetupCursor(event);
2595 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2597 wxWindow* thisWindow = GetWXPeer();
2598 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2600 thisWindow->MacInvalidateBorders();
2603 if ( receivedFocus )
2605 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2606 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2607 thisWindow->HandleWindowEvent(eventFocus);
2610 if ( thisWindow->GetCaret() )
2611 thisWindow->GetCaret()->OnSetFocus();
2614 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2615 event.SetEventObject(thisWindow);
2617 event.SetWindow(otherWindow->GetWXPeer());
2618 thisWindow->HandleWindowEvent(event) ;
2620 else // !receivedFocus
2623 if ( thisWindow->GetCaret() )
2624 thisWindow->GetCaret()->OnKillFocus();
2627 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2629 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2630 event.SetEventObject(thisWindow);
2632 event.SetWindow(otherWindow->GetWXPeer());
2633 thisWindow->HandleWindowEvent(event) ;
2637 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2641 NSPoint location = [NSEvent mouseLocation];
2642 location = [[m_osxView window] convertScreenToBase:location];
2643 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2645 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2647 [(NSCursor*)cursor.GetHCURSOR() set];
2652 void wxWidgetCocoaImpl::CaptureMouse()
2654 // TODO remove if we don't get into problems with cursor settings
2655 // [[m_osxView window] disableCursorRects];
2658 void wxWidgetCocoaImpl::ReleaseMouse()
2660 // TODO remove if we don't get into problems with cursor settings
2661 // [[m_osxView window] enableCursorRects];
2664 #if !wxOSX_USE_NATIVE_FLIPPED
2666 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2668 m_isFlipped = flipped;
2673 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2677 [[m_osxView window] enableFlushWindow];
2678 [m_osxView setNeedsDisplay:YES];
2682 [[m_osxView window] disableFlushWindow];
2689 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2690 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2691 long WXUNUSED(style), long WXUNUSED(extraStyle))
2693 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2694 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2696 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2700 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2702 NSWindow* tlw = now->GetWXWindow();
2704 wxWidgetCocoaImpl* c = NULL;
2705 if ( now->IsNativeWindowWrapper() )
2707 NSView* cv = [tlw contentView];
2708 c = new wxWidgetCocoaImpl( now, cv, true );
2711 // increase ref count, because the impl destructor will decrement it again
2713 if ( !now->IsShown() )
2719 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2720 c = new wxWidgetCocoaImpl( now, v, true );
2721 c->InstallEventHandler();
2722 [tlw setContentView:v];