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* 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 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
690 wxevent.m_wheelRotation = (int)deltaX;
694 wxevent.m_wheelRotation = (int)deltaY;
700 case NSMouseEntered :
701 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
704 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
706 case NSLeftMouseDragged :
707 case NSRightMouseDragged :
708 case NSOtherMouseDragged :
710 wxevent.SetEventType( wxEVT_MOTION ) ;
716 wxevent.m_clickCount = clickCount;
717 wxWindowMac* peer = GetWXPeer();
720 wxevent.SetEventObject(peer);
721 wxevent.SetId(peer->GetId()) ;
725 @implementation wxNSView
729 static BOOL initialized = NO;
733 wxOSXCocoaClassAddWXMethods( self );
737 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
738 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
742 - (void)_sendToolTipMouseExited
744 // Nothing matters except window, trackingNumber, and userData.
745 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
746 location:NSMakePoint(0, 0)
749 windowNumber:[[self window] windowNumber]
752 trackingNumber:_lastToolTipTrackTag
753 userData:_lastUserData];
754 [_lastToolTipOwner mouseExited:fakeEvent];
757 - (void)_sendToolTipMouseEntered
759 // Nothing matters except window, trackingNumber, and userData.
760 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
761 location:NSMakePoint(0, 0)
764 windowNumber:[[self window] windowNumber]
767 trackingNumber:_lastToolTipTrackTag
768 userData:_lastUserData];
769 [_lastToolTipOwner mouseEntered:fakeEvent];
772 - (void)setToolTip:(NSString *)string;
778 [self _sendToolTipMouseExited];
781 [super setToolTip:string];
783 [self _sendToolTipMouseEntered];
789 [self _sendToolTipMouseExited];
790 [super setToolTip:nil];
796 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
798 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
801 _lastUserData = data;
802 _lastToolTipOwner = owner;
803 _lastToolTipTrackTag = tag;
808 - (void)removeTrackingRect:(NSTrackingRectTag)tag
810 if (tag == _lastToolTipTrackTag)
812 _lastUserData = NULL;
813 _lastToolTipOwner = nil;
814 _lastToolTipTrackTag = 0;
816 [super removeTrackingRect:tag];
819 #if wxOSX_USE_NATIVE_FLIPPED
826 - (BOOL) canBecomeKeyView
828 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
829 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
830 return viewimpl->GetWXPeer()->AcceptsFocus();
840 #if wxUSE_DRAG_AND_DROP
842 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
843 // for details on the NSPasteboard -> PasteboardRef conversion
845 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
847 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
849 return NSDragOperationNone;
851 return impl->draggingEntered(sender, self, _cmd);
854 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
856 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
860 return impl->draggingExited(sender, self, _cmd);
863 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
865 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
867 return NSDragOperationNone;
869 return impl->draggingUpdated(sender, self, _cmd);
872 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
874 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
876 return NSDragOperationNone;
878 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
883 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
885 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
889 impl->mouseEvent(event, self, _cmd);
892 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
894 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
898 impl->cursorUpdate(event, self, _cmd);
901 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
903 // This is needed to support click through, otherwise the first click on a window
904 // will not do anything unless it is the active window already.
908 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
910 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
914 impl->keyEvent(event, self, _cmd);
917 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
919 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
923 impl->insertText(text, self, _cmd);
926 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
928 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
932 return impl->performKeyEquivalent(event, self, _cmd);
935 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
937 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
941 return impl->acceptsFirstResponder(self, _cmd);
944 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
946 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
950 return impl->becomeFirstResponder(self, _cmd);
953 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
955 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
959 return impl->resignFirstResponder(self, _cmd);
962 #if !wxOSX_USE_NATIVE_FLIPPED
964 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
966 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
970 return impl->isFlipped(self, _cmd) ? YES:NO;
975 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
977 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
979 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
984 // OS X starts a NSUIHeartBeatThread for animating the default button in a
985 // dialog. This causes a drawRect of the active dialog from outside the
986 // main UI thread. This causes an occasional crash since the wx drawing
987 // objects (like wxPen) are not thread safe.
989 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
990 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
991 if ( !wxThread::IsMain() )
993 if ( impl->IsUserPane() )
995 wxWindow* win = impl->GetWXPeer();
996 if ( win->UseBgCol() )
999 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1000 CGContextSaveGState( context );
1002 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
1003 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1004 CGContextFillRect( context, r );
1006 CGContextRestoreGState( context );
1011 // just call the superclass handler, we don't need any custom wx drawing
1012 // here and it seems to work fine:
1013 wxOSX_DrawRectHandlerPtr
1014 superimpl = (wxOSX_DrawRectHandlerPtr)
1015 [[self superclass] instanceMethodForSelector:_cmd];
1016 superimpl(self, _cmd, rect);
1021 #endif // wxUSE_THREADS
1023 return impl->drawRect(&rect, self, _cmd);
1026 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
1028 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1032 impl->controlAction(self, _cmd, sender);
1035 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
1037 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1041 impl->controlDoubleAction(self, _cmd, sender);
1044 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1046 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1047 NSPasteboard *pboard = [sender draggingPasteboard];
1048 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1050 wxWindow* wxpeer = GetWXPeer();
1051 if ( wxpeer == NULL )
1052 return NSDragOperationNone;
1054 wxDropTarget* target = wxpeer->GetDropTarget();
1055 if ( target == NULL )
1056 return NSDragOperationNone;
1058 wxDragResult result = wxDragNone;
1059 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1060 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1062 if ( sourceDragMask & NSDragOperationLink )
1063 result = wxDragLink;
1064 else if ( sourceDragMask & NSDragOperationCopy )
1065 result = wxDragCopy;
1066 else if ( sourceDragMask & NSDragOperationMove )
1067 result = wxDragMove;
1069 PasteboardRef pboardRef;
1070 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1071 target->SetCurrentDragPasteboard(pboardRef);
1072 result = target->OnEnter(pt.x, pt.y, result);
1073 CFRelease(pboardRef);
1075 NSDragOperation nsresult = NSDragOperationNone;
1079 nsresult = NSDragOperationLink;
1081 nsresult = NSDragOperationMove;
1083 nsresult = NSDragOperationCopy;
1090 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1092 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1093 NSPasteboard *pboard = [sender draggingPasteboard];
1095 wxWindow* wxpeer = GetWXPeer();
1096 if ( wxpeer == NULL )
1099 wxDropTarget* target = wxpeer->GetDropTarget();
1100 if ( target == NULL )
1103 PasteboardRef pboardRef;
1104 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1105 target->SetCurrentDragPasteboard(pboardRef);
1107 CFRelease(pboardRef);
1110 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1112 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1113 NSPasteboard *pboard = [sender draggingPasteboard];
1114 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1116 wxWindow* wxpeer = GetWXPeer();
1117 if ( wxpeer == NULL )
1118 return NSDragOperationNone;
1120 wxDropTarget* target = wxpeer->GetDropTarget();
1121 if ( target == NULL )
1122 return NSDragOperationNone;
1124 wxDragResult result = wxDragNone;
1125 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1126 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1128 if ( sourceDragMask & NSDragOperationLink )
1129 result = wxDragLink;
1130 else if ( sourceDragMask & NSDragOperationCopy )
1131 result = wxDragCopy;
1132 else if ( sourceDragMask & NSDragOperationMove )
1133 result = wxDragMove;
1135 PasteboardRef pboardRef;
1136 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1137 target->SetCurrentDragPasteboard(pboardRef);
1138 result = target->OnDragOver(pt.x, pt.y, result);
1139 CFRelease(pboardRef);
1141 NSDragOperation nsresult = NSDragOperationNone;
1145 nsresult = NSDragOperationLink;
1147 nsresult = NSDragOperationMove;
1149 nsresult = NSDragOperationCopy;
1156 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1158 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1160 NSPasteboard *pboard = [sender draggingPasteboard];
1161 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1163 wxWindow* wxpeer = GetWXPeer();
1164 wxDropTarget* target = wxpeer->GetDropTarget();
1165 wxDragResult result = wxDragNone;
1166 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1167 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1169 if ( sourceDragMask & NSDragOperationLink )
1170 result = wxDragLink;
1171 else if ( sourceDragMask & NSDragOperationCopy )
1172 result = wxDragCopy;
1173 else if ( sourceDragMask & NSDragOperationMove )
1174 result = wxDragMove;
1176 PasteboardRef pboardRef;
1177 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1178 target->SetCurrentDragPasteboard(pboardRef);
1180 if (target->OnDrop(pt.x, pt.y))
1181 result = target->OnData(pt.x, pt.y, result);
1183 CFRelease(pboardRef);
1185 return result != wxDragNone;
1188 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1190 // we are getting moved events for all windows in the hierarchy, not something wx expects
1191 // therefore we only handle it for the deepest child in the hierarchy
1192 if ( [event type] == NSMouseMoved )
1194 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1195 if ( hitview == NULL || hitview != slf)
1199 if ( !DoHandleMouseEvent(event) )
1201 // for plain NSView mouse events would propagate to parents otherwise
1202 // scrollwheel events have to be propagated if not handled in all cases
1203 if (!IsUserPane() || [event type] == NSScrollWheel )
1205 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1206 superimpl(slf, (SEL)_cmd, event);
1208 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1209 // only trigger if at this moment the mouse is already up
1210 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1212 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1213 SetupMouseEvent(wxevent , event) ;
1214 wxevent.SetEventType(wxEVT_LEFT_UP);
1216 GetWXPeer()->HandleWindowEvent(wxevent);
1222 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1224 if ( !SetupCursor(event) )
1226 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1227 superimpl(slf, (SEL)_cmd, event);
1231 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1233 extern wxCursor gGlobalCursor;
1235 if ( gGlobalCursor.IsOk() )
1237 gGlobalCursor.MacInstall();
1242 wxWindow* cursorTarget = GetWXPeer();
1244 SetupCoordinates(x, y, event);
1245 wxPoint cursorPoint( x , y ) ;
1247 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1249 // at least in GTK cursor events are not propagated either ...
1251 cursorTarget = NULL;
1253 cursorTarget = cursorTarget->GetParent() ;
1255 cursorPoint += cursorTarget->GetPosition();
1259 return cursorTarget != NULL;
1263 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1265 if ( [event type] == NSKeyDown )
1267 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1268 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1269 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1272 m_lastKeyDownEvent = event;
1275 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1277 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1278 superimpl(slf, (SEL)_cmd, event);
1280 m_lastKeyDownEvent = NULL;
1283 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1285 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1287 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1288 superimpl(slf, (SEL)_cmd, text);
1293 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1295 bool handled = false;
1297 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1298 SetupKeyEvent( wxevent, event );
1300 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1301 // walk up the ancestors ourselves but let cocoa do it
1303 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1306 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1308 wxCommandEvent command_event( wxEVT_MENU, command );
1309 command_event.SetEventObject( wxevent.GetEventObject() );
1310 handled = handler->ProcessEvent( command_event );
1314 // accelerators can also be used with buttons, try them too
1315 command_event.SetEventType(wxEVT_BUTTON);
1316 handled = handler->ProcessEvent( command_event );
1322 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1323 return superimpl(slf, (SEL)_cmd, event);
1328 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1331 return m_wxPeer->AcceptsFocus();
1334 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1335 return superimpl(slf, (SEL)_cmd);
1339 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1341 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1342 // get the current focus before running becomeFirstResponder
1343 NSView* otherView = FindFocus();
1345 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1346 BOOL r = superimpl(slf, (SEL)_cmd);
1349 DoNotifyFocusEvent( true, otherWindow );
1355 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1357 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1358 BOOL r = superimpl(slf, (SEL)_cmd);
1360 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
1361 NSView* otherView = wxOSXGetViewFromResponder(responder);
1363 wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
1365 // It doesn't make sense to notify about the loss of focus if it's the same
1366 // control in the end, and just a different subview
1367 if ( otherWindow == this )
1370 // NSTextViews have an editor as true responder, therefore the might get the
1371 // resign notification if their editor takes over, don't trigger any event then
1372 if ( r && !m_hasEditor)
1374 DoNotifyFocusEvent( false, otherWindow );
1379 #if !wxOSX_USE_NATIVE_FLIPPED
1381 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1388 #define OSX_DEBUG_DRAWING 0
1390 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1392 // preparing the update region
1396 // since adding many rects to a region is a costly process, by default use the bounding rect
1398 const NSRect *rects;
1400 [slf getRectsBeingDrawn:&rects count:&count];
1401 for ( int i = 0 ; i < count ; ++i )
1403 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1406 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1409 wxWindow* wxpeer = GetWXPeer();
1411 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1413 // as this update region is in native window locals we must adapt it to wx window local
1414 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1417 // Restrict the update region to the shape of the window, if any, and also
1418 // remember the region that we need to clear later.
1419 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1420 const bool isTopLevel = tlwParent == wxpeer;
1422 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1425 clearRgn = updateRgn;
1427 int xoffset = 0, yoffset = 0;
1428 wxRegion rgn = tlwParent->GetShape();
1429 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1430 rgn.Offset( xoffset, yoffset );
1431 updateRgn.Intersect(rgn);
1435 // Exclude the window shape from the region to be cleared below.
1436 rgn.Xor(wxpeer->GetSize());
1437 clearRgn.Intersect(rgn);
1441 wxpeer->GetUpdateRegion() = updateRgn;
1443 // setting up the drawing context
1445 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1446 CGContextSaveGState( context );
1448 #if OSX_DEBUG_DRAWING
1449 CGContextBeginPath( context );
1450 CGContextMoveToPoint(context, 0, 0);
1451 NSRect bounds = [slf bounds];
1452 CGContextAddLineToPoint(context, 10, 0);
1453 CGContextMoveToPoint(context, 0, 0);
1454 CGContextAddLineToPoint(context, 0, 10);
1455 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1456 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1457 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1458 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1459 CGContextClosePath( context );
1460 CGContextStrokePath(context);
1463 if ( ![slf isFlipped] )
1465 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1466 CGContextScaleCTM( context, 1, -1 );
1469 wxpeer->MacSetCGContextRef( context );
1471 bool handled = wxpeer->MacDoRedraw( 0 );
1472 CGContextRestoreGState( context );
1474 CGContextSaveGState( context );
1478 SEL _cmd = @selector(drawRect:);
1479 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1480 superimpl(slf, _cmd, *(NSRect*)rect);
1481 CGContextRestoreGState( context );
1482 CGContextSaveGState( context );
1484 // as we called restore above, we have to flip again if necessary
1485 if ( ![slf isFlipped] )
1487 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1488 CGContextScaleCTM( context, 1, -1 );
1493 // We also need to explicitly draw the part of the top level window
1494 // outside of its region with transparent colour to ensure that it is
1495 // really transparent.
1496 if ( clearRgn.IsOk() )
1498 wxMacCGContextStateSaver saveState(context);
1499 wxWindowDC dc(wxpeer);
1500 dc.SetBackground(wxBrush(wxTransparentColour));
1501 dc.SetDeviceClippingRegion(clearRgn);
1505 #if wxUSE_GRAPHICS_CONTEXT
1506 // If the window shape is defined by a path, stroke the path to show
1507 // the window border.
1508 const wxGraphicsPath& path = tlwParent->GetShapePath();
1509 if ( !path.IsNull() )
1511 CGContextSetLineWidth(context, 1);
1512 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1513 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1514 CGContextStrokePath(context);
1516 #endif // wxUSE_GRAPHICS_CONTEXT
1519 wxpeer->MacPaintChildrenBorders();
1520 wxpeer->MacSetCGContextRef( NULL );
1521 CGContextRestoreGState( context );
1524 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1526 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1529 wxpeer->OSXSimulateFocusEvents();
1530 wxpeer->OSXHandleClicked(0);
1534 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1538 void wxWidgetCocoaImpl::controlTextDidChange()
1540 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1543 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1544 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1545 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1547 tc->SendTextUpdatedEventIfAllowed();
1549 cb->SendTextUpdatedEventIfAllowed();
1552 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1559 #if OBJC_API_VERSION >= 2
1561 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1562 class_addMethod(c, s, i, t );
1566 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1567 { s, (char*) t, i },
1571 void wxOSXCocoaClassAddWXMethods(Class c)
1574 #if OBJC_API_VERSION < 2
1575 static objc_method wxmethods[] =
1579 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1580 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1581 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1583 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1584 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1585 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1587 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1589 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1591 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1593 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1595 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1596 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1597 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1599 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1601 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1603 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1605 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1607 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1609 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1610 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1611 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1613 #if !wxOSX_USE_NATIVE_FLIPPED
1614 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1616 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1618 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1619 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1621 #if wxUSE_DRAG_AND_DROP
1622 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1623 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1624 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1625 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1628 #if OBJC_API_VERSION < 2
1630 static int method_count = WXSIZEOF( wxmethods );
1631 static objc_method_list *wxmethodlist = NULL;
1632 if ( wxmethodlist == NULL )
1634 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1635 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1636 wxmethodlist->method_count = method_count;
1637 wxmethodlist->obsolete = 0;
1639 class_addMethods( c, wxmethodlist );
1644 // C++ implementation class
1647 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1649 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1650 wxWidgetImpl( peer, isRootControl, isUserPane )
1655 // check if the user wants to create the control initially hidden
1656 if ( !peer->IsShown() )
1657 SetVisibility(false);
1659 // gc aware handling
1661 CFRetain(m_osxView);
1662 [m_osxView release];
1665 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1670 void wxWidgetCocoaImpl::Init()
1673 #if !wxOSX_USE_NATIVE_FLIPPED
1676 m_lastKeyDownEvent = NULL;
1677 m_hasEditor = false;
1680 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1682 RemoveAssociations( this );
1684 if ( !IsRootControl() )
1686 NSView *sv = [m_osxView superview];
1688 [m_osxView removeFromSuperview];
1690 // gc aware handling
1692 CFRelease(m_osxView);
1695 bool wxWidgetCocoaImpl::IsVisible() const
1697 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1700 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1702 [m_osxView setHidden:(visible ? NO:YES)];
1705 // ----------------------------------------------------------------------------
1706 // window animation stuff
1707 // ----------------------------------------------------------------------------
1709 // define a delegate used to refresh the window during animation
1710 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1716 - (id)init:(wxWindow *)win;
1720 // NSAnimationDelegate methods
1721 - (void)animationDidEnd:(NSAnimation*)animation;
1722 - (void)animation:(NSAnimation*)animation
1723 didReachProgressMark:(NSAnimationProgress)progress;
1726 @implementation wxNSAnimationDelegate
1728 - (id)init:(wxWindow *)win
1730 self = [super init];
1743 - (void)animation:(NSAnimation*)animation
1744 didReachProgressMark:(NSAnimationProgress)progress
1746 wxUnusedVar(animation);
1747 wxUnusedVar(progress);
1749 m_win->SendSizeEvent();
1752 - (void)animationDidEnd:(NSAnimation*)animation
1754 wxUnusedVar(animation);
1762 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1764 wxShowEffect effect,
1767 // create the dictionary describing the animation to perform on this view
1769 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1770 NSMutableDictionary * const
1771 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1772 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1774 // determine the start and end rectangles assuming we're hiding the window
1775 const wxRect rectOrig = win->GetRect();
1783 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1784 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1785 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1786 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1787 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1788 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1789 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1790 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1791 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1792 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1793 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1794 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1799 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1800 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1804 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1805 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1806 rectEnd.x = rectStart.GetRight();
1810 case wxSHOW_EFFECT_ROLL_TO_TOP:
1811 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1815 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1816 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1817 rectEnd.y = rectStart.GetBottom();
1821 case wxSHOW_EFFECT_EXPAND:
1822 rectEnd.x = rectStart.x + rectStart.width / 2;
1823 rectEnd.y = rectStart.y + rectStart.height / 2;
1828 case wxSHOW_EFFECT_BLEND:
1829 [dict setObject:(show ? NSViewAnimationFadeInEffect
1830 : NSViewAnimationFadeOutEffect)
1831 forKey:NSViewAnimationEffectKey];
1834 case wxSHOW_EFFECT_NONE:
1835 case wxSHOW_EFFECT_MAX:
1836 wxFAIL_MSG( "unexpected animation effect" );
1840 wxFAIL_MSG( "unknown animation effect" );
1846 // we need to restore it to the original rectangle instead of making it
1848 wxSwap(rectStart, rectEnd);
1850 // and as the window is currently hidden, we need to show it for the
1851 // animation to be visible at all (but don't restore it at its full
1852 // rectangle as it shouldn't appear immediately)
1853 win->SetSize(rectStart);
1857 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1858 ? [(NSView *)viewOrWin superview]
1860 const NSRect rStart = wxToNSRect(parentView, rectStart);
1861 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1863 [dict setObject:[NSValue valueWithRect:rStart]
1864 forKey:NSViewAnimationStartFrameKey];
1865 [dict setObject:[NSValue valueWithRect:rEnd]
1866 forKey:NSViewAnimationEndFrameKey];
1868 // create an animation using the values in the above dictionary
1869 NSViewAnimation * const
1870 anim = [[NSViewAnimation alloc]
1871 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1875 // what is a good default duration? Windows uses 200ms, Web frameworks
1876 // use anything from 250ms to 1s... choose something in the middle
1880 [anim setDuration:timeout/1000.]; // duration is in seconds here
1882 // if the window being animated changes its layout depending on its size
1883 // (which is almost always the case) we need to redo it during animation
1885 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1886 // controls in wxInfoBar visibly jump around)
1887 const int NUM_LAYOUTS = 20;
1888 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1889 [anim addProgressMark:f];
1891 wxNSAnimationDelegate * const
1892 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1893 [anim setDelegate:animDelegate];
1894 [anim startAnimation];
1896 // Cocoa is capable of doing animation asynchronously or even from separate
1897 // thread but wx API doesn't provide any way to be notified about the
1898 // animation end and without this we really must ensure that the window has
1899 // the expected (i.e. the same as if a simple Show() had been used) size
1900 // when we return, so block here until the animation finishes
1902 // notice that because the default animation mode is NSAnimationBlocking,
1903 // no user input events ought to be processed from here
1905 wxEventLoopGuarantor ensureEventLoopExistence;
1906 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1907 while ( ![animDelegate isDone] )
1913 // NSViewAnimation is smart enough to hide the NSView being animated at
1914 // the end but we also must ensure that it's hidden for wx too
1917 // and we must also restore its size because it isn't expected to
1918 // change just because the window was hidden
1919 win->SetSize(rectOrig);
1923 // refresh it once again after the end to ensure that everything is in
1925 win->SendSizeEvent();
1928 [anim setDelegate:nil];
1929 [animDelegate release];
1935 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1936 wxShowEffect effect,
1939 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1942 /* note that the drawing order between siblings is not defined under 10.4 */
1943 /* only starting from 10.5 the subview order is respected */
1945 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1946 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1947 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1948 * expects a function returning the new non-enum NSComparsionResult.
1949 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1951 #if defined(NSINTEGER_DEFINED)
1952 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1954 typedef int CocoaWindowCompareFunctionResult;
1957 class CocoaWindowCompareContext
1959 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1961 CocoaWindowCompareContext(); // Not implemented
1962 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1965 // Cocoa sorts subviews in-place.. make a copy
1966 m_subviews = [subviews copy];
1969 ~CocoaWindowCompareContext()
1970 { // release the copy
1971 [m_subviews release];
1974 { return m_target; }
1977 { return m_subviews; }
1979 /* Helper function that returns the comparison based off of the original ordering */
1980 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1982 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1983 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1984 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1985 // likely compare higher than the other view which is reasonable considering the only way that
1986 // can happen is if the subview was added after our call to subviews but before the call to
1987 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1988 // that case should never occur anyway because that would imply a multi-threaded GUI call
1989 // which is a big no-no with Cocoa.
1991 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1992 NSComparisonResult result = (firstI < secondI)
1993 ? NSOrderedAscending /* -1 */
1994 : (firstI > secondI)
1995 ? NSOrderedDescending /* 1 */
1996 : NSOrderedSame /* 0 */;
2001 /* The subview we are trying to Raise or Lower */
2003 /* A copy of the original array of subviews */
2004 NSArray *m_subviews;
2007 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2008 * the target view is always higher than every other view. When comparing two views neither of
2009 * which is the target, it returns the correct response based on the original ordering
2011 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2013 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2014 // first should be ordered higher
2015 if(first==compareContext->target())
2016 return NSOrderedDescending;
2017 // second should be ordered higher
2018 if(second==compareContext->target())
2019 return NSOrderedAscending;
2020 return compareContext->CompareUsingOriginalOrdering(first,second);
2023 void wxWidgetCocoaImpl::Raise()
2025 NSView* nsview = m_osxView;
2027 NSView *superview = [nsview superview];
2028 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2030 [superview sortSubviewsUsingFunction:
2031 CocoaRaiseWindowCompareFunction
2032 context: &compareContext];
2036 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2037 * the target view is always lower than every other view. When comparing two views neither of
2038 * which is the target, it returns the correct response based on the original ordering
2040 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2042 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2043 // first should be ordered lower
2044 if(first==compareContext->target())
2045 return NSOrderedAscending;
2046 // second should be ordered lower
2047 if(second==compareContext->target())
2048 return NSOrderedDescending;
2049 return compareContext->CompareUsingOriginalOrdering(first,second);
2052 void wxWidgetCocoaImpl::Lower()
2054 NSView* nsview = m_osxView;
2056 NSView *superview = [nsview superview];
2057 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2059 [superview sortSubviewsUsingFunction:
2060 CocoaLowerWindowCompareFunction
2061 context: &compareContext];
2064 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2069 // We should do something like this, but it wasn't working in 10.4.
2070 if (GetNeedsDisplay() )
2074 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2075 NSSize offset = NSMakeSize((float)dx, (float)dy);
2076 [m_osxView scrollRect:r by:offset];
2080 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2082 wxWindowMac* parent = GetWXPeer()->GetParent();
2083 // under Cocoa we might have a contentView in the wxParent to which we have to
2084 // adjust the coordinates
2085 if (parent && [m_osxView superview] != parent->GetHandle() )
2087 int cx = 0,cy = 0,cw = 0,ch = 0;
2088 if ( parent->GetPeer() )
2090 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2095 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2096 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2097 [m_osxView setFrame:r];
2098 [[m_osxView superview] setNeedsDisplayInRect:r];
2101 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2103 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2107 // under Cocoa we might have a contentView in the wxParent to which we have to
2108 // adjust the coordinates
2109 wxWindowMac* parent = GetWXPeer()->GetParent();
2110 if (parent && [m_osxView superview] != parent->GetHandle() )
2112 int cx = 0,cy = 0,cw = 0,ch = 0;
2113 if ( parent->GetPeer() )
2115 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2122 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2124 NSRect rect = [m_osxView frame];
2125 width = (int)rect.size.width;
2126 height = (int)rect.size.height;
2129 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2131 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2133 NSView* cv = [m_osxView contentView];
2135 NSRect bounds = [m_osxView bounds];
2136 NSRect rect = [cv frame];
2138 int y = (int)rect.origin.y;
2139 int x = (int)rect.origin.x;
2140 if ( ![ m_osxView isFlipped ] )
2141 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2144 width = (int)rect.size.width;
2145 height = (int)rect.size.height;
2150 GetSize( width, height );
2154 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2157 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2159 [m_osxView setNeedsDisplay:YES];
2162 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2164 return [m_osxView needsDisplay];
2167 bool wxWidgetCocoaImpl::CanFocus() const
2169 return [m_osxView canBecomeKeyView] == YES;
2172 bool wxWidgetCocoaImpl::HasFocus() const
2174 return ( FindFocus() == m_osxView );
2177 bool wxWidgetCocoaImpl::SetFocus()
2182 // TODO remove if no issues arise: should not raise the window, only assign focus
2183 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2184 [[m_osxView window] makeFirstResponder: m_osxView] ;
2188 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2190 [m_osxView unregisterDraggedTypes];
2192 if ( target == NULL )
2195 wxDataObject* dobj = target->GetDataObject();
2199 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2200 dobj->AddSupportedTypes(typesarray);
2201 NSView* targetView = m_osxView;
2202 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2203 targetView = [(NSScrollView*) m_osxView documentView];
2205 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2206 CFRelease(typesarray);
2210 void wxWidgetCocoaImpl::RemoveFromParent()
2212 [m_osxView removeFromSuperview];
2215 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2217 NSView* container = parent->GetWXWidget() ;
2218 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2219 [container addSubview:m_osxView];
2221 if( m_wxPeer->IsFrozen() )
2222 [[m_osxView window] disableFlushWindow];
2225 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2227 NSView* targetView = m_osxView;
2228 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2229 targetView = [(NSScrollView*) m_osxView documentView];
2231 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2233 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2234 green:(CGFloat) (col.Green() / 255.0)
2235 blue:(CGFloat) (col.Blue() / 255.0)
2236 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2240 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2242 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2244 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2246 [m_osxView setOpaque: opaque];
2252 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2254 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2256 wxCFStringRef cf( title , encoding );
2257 [m_osxView setTitle:cf.AsNSString()];
2259 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2261 wxCFStringRef cf( title , encoding );
2262 [m_osxView setStringValue:cf.AsNSString()];
2267 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2269 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2270 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2271 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2274 wxInt32 wxWidgetCocoaImpl::GetValue() const
2276 return [(NSControl*)m_osxView intValue];
2279 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2281 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2283 [m_osxView setIntValue:v];
2285 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2287 [m_osxView setFloatValue:(double)v];
2289 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2291 [m_osxView setDoubleValue:(double)v];
2295 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2297 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2299 [m_osxView setMinValue:(double)v];
2303 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2305 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2307 [m_osxView setMaxValue:(double)v];
2311 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2313 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2315 return (int)[m_osxView minValue];
2320 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2322 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2324 return (int)[m_osxView maxValue];
2329 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2333 // TODO: how to create a wxBitmap from NSImage?
2335 if ( [m_osxView respondsToSelector:@selector(image:)] )
2336 bmp = [m_osxView image];
2342 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2344 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2347 [m_osxView setImage:bitmap.GetNSImage()];
2349 [m_osxView setImage:nil];
2351 [m_osxView setNeedsDisplay:YES];
2355 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2357 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2359 NSCellImagePosition pos;
2379 wxFAIL_MSG( "invalid image position" );
2383 [m_osxView setImagePosition:pos];
2387 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2389 // implementation in subclass
2392 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2394 r->x = r->y = r->width = r->height = 0;
2396 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2398 NSRect former = [m_osxView frame];
2399 [m_osxView sizeToFit];
2400 NSRect best = [m_osxView frame];
2401 [m_osxView setFrame:former];
2402 r->width = (int)best.size.width;
2403 r->height = (int)best.size.height;
2407 bool wxWidgetCocoaImpl::IsEnabled() const
2409 NSView* targetView = m_osxView;
2410 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2411 targetView = [(NSScrollView*) m_osxView documentView];
2413 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2414 return [targetView isEnabled];
2418 void wxWidgetCocoaImpl::Enable( bool enable )
2420 NSView* targetView = m_osxView;
2421 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2422 targetView = [(NSScrollView*) m_osxView documentView];
2424 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2425 [targetView setEnabled:enable];
2428 void wxWidgetCocoaImpl::PulseGauge()
2432 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2436 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2438 NSControlSize size = NSRegularControlSize;
2442 case wxWINDOW_VARIANT_NORMAL :
2443 size = NSRegularControlSize;
2446 case wxWINDOW_VARIANT_SMALL :
2447 size = NSSmallControlSize;
2450 case wxWINDOW_VARIANT_MINI :
2451 size = NSMiniControlSize;
2454 case wxWINDOW_VARIANT_LARGE :
2455 size = NSRegularControlSize;
2459 wxFAIL_MSG(wxT("unexpected window variant"));
2462 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2463 [m_osxView setControlSize:size];
2464 else if ([m_osxView respondsToSelector:@selector(cell)])
2466 id cell = [(id)m_osxView cell];
2467 if ([cell respondsToSelector:@selector(setControlSize:)])
2468 [cell setControlSize:size];
2471 // we need to propagate this to inner views as well
2472 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2474 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2476 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2477 [targetView setControlSize:size];
2478 else if ([targetView respondsToSelector:@selector(cell)])
2480 id cell = [(id)targetView cell];
2481 if ([cell respondsToSelector:@selector(setControlSize:)])
2482 [cell setControlSize:size];
2487 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2489 NSView* targetView = m_osxView;
2490 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2491 targetView = [(NSScrollView*) m_osxView documentView];
2493 if ([targetView respondsToSelector:@selector(setFont:)])
2494 [targetView setFont: font.OSXGetNSFont()];
2495 if ([targetView respondsToSelector:@selector(setTextColor:)])
2496 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2497 green:(CGFloat) (col.Green() / 255.0)
2498 blue:(CGFloat) (col.Blue() / 255.0)
2499 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2502 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2506 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2507 [m_osxView setToolTip: cf.AsNSString()];
2511 [m_osxView setToolTip:nil];
2515 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2517 WXWidget c = control ? control : (WXWidget) m_osxView;
2518 wxWidgetImpl::Associate( c, this ) ;
2519 if ([c respondsToSelector:@selector(setAction:)])
2522 if ( dynamic_cast<wxRadioButton*>(GetWXPeer()) )
2524 // everything already set up
2527 [c setAction: @selector(controlAction:)];
2529 if ([c respondsToSelector:@selector(setDoubleAction:)])
2531 [c setDoubleAction: @selector(controlDoubleAction:)];
2535 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2536 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2537 [m_osxView addTrackingArea: area];
2541 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2543 wxKeyEvent wxevent(wxEVT_CHAR);
2544 SetupKeyEvent( wxevent, event, text );
2546 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2549 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2551 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2552 SetupKeyEvent( wxevent, event );
2554 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2555 // the key is pressed, not when it's released (the type of wxevent is
2556 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2557 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2559 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2560 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2561 && !eventHook.IsNextEventAllowed() )
2565 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2567 // this will fire higher level events, like insertText, to help
2568 // us handle EVT_CHAR, etc.
2572 if ( [event type] == NSKeyDown)
2574 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2576 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2578 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2579 wxKeyEvent wxevent2(wxevent) ;
2580 wxevent2.SetEventType(wxEVT_CHAR);
2581 SetupKeyEvent( wxevent2, event );
2582 wxevent2.m_keyCode = keycode;
2583 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2585 else if (wxevent.CmdDown())
2587 wxKeyEvent wxevent2(wxevent) ;
2588 wxevent2.SetEventType(wxEVT_CHAR);
2589 SetupKeyEvent( wxevent2, event );
2590 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2594 if ( IsUserPane() && !wxevent.CmdDown() )
2596 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2597 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2599 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2609 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2611 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2612 SetupMouseEvent(wxevent , event) ;
2613 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2615 (void)SetupCursor(event);
2620 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2622 wxWindow* thisWindow = GetWXPeer();
2623 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2625 thisWindow->MacInvalidateBorders();
2628 if ( receivedFocus )
2630 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2631 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2632 thisWindow->HandleWindowEvent(eventFocus);
2635 if ( thisWindow->GetCaret() )
2636 thisWindow->GetCaret()->OnSetFocus();
2639 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2640 event.SetEventObject(thisWindow);
2642 event.SetWindow(otherWindow->GetWXPeer());
2643 thisWindow->HandleWindowEvent(event) ;
2645 else // !receivedFocus
2648 if ( thisWindow->GetCaret() )
2649 thisWindow->GetCaret()->OnKillFocus();
2652 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2654 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2655 event.SetEventObject(thisWindow);
2657 event.SetWindow(otherWindow->GetWXPeer());
2658 thisWindow->HandleWindowEvent(event) ;
2662 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2666 NSPoint location = [NSEvent mouseLocation];
2667 location = [[m_osxView window] convertScreenToBase:location];
2668 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2670 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2672 [(NSCursor*)cursor.GetHCURSOR() set];
2677 void wxWidgetCocoaImpl::CaptureMouse()
2679 // TODO remove if we don't get into problems with cursor settings
2680 // [[m_osxView window] disableCursorRects];
2683 void wxWidgetCocoaImpl::ReleaseMouse()
2685 // TODO remove if we don't get into problems with cursor settings
2686 // [[m_osxView window] enableCursorRects];
2689 #if !wxOSX_USE_NATIVE_FLIPPED
2691 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2693 m_isFlipped = flipped;
2698 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2702 [[m_osxView window] enableFlushWindow];
2703 [m_osxView setNeedsDisplay:YES];
2707 [[m_osxView window] disableFlushWindow];
2714 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2715 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2716 long WXUNUSED(style), long WXUNUSED(extraStyle))
2718 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2719 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2721 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2725 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2727 NSWindow* tlw = now->GetWXWindow();
2729 wxWidgetCocoaImpl* c = NULL;
2730 if ( now->IsNativeWindowWrapper() )
2732 NSView* cv = [tlw contentView];
2733 c = new wxWidgetCocoaImpl( now, cv, true );
2736 // increase ref count, because the impl destructor will decrement it again
2738 if ( !now->IsShown() )
2744 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2745 c = new wxWidgetCocoaImpl( now, v, true );
2746 c->InstallEventHandler();
2747 [tlw setContentView:v];