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"
20 #include "wx/radiobut.h"
24 #include "wx/osx/private.h"
27 #include "wx/evtloop.h"
33 #if wxUSE_DRAG_AND_DROP
38 #include "wx/tooltip.h"
41 #include <objc/objc-runtime.h>
43 // Get the window with the focus
45 NSView* wxOSXGetViewFromResponder( NSResponder* responder )
48 if ( [responder isKindOfClass:[NSTextView class]] )
50 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
51 if ( [delegate isKindOfClass:[NSTextField class] ] )
54 view = (NSView*) responder;
58 if ( [responder isKindOfClass:[NSView class]] )
59 view = (NSView*) responder;
64 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
66 NSView* focusedView = nil;
67 if ( keyWindow != nil )
68 focusedView = wxOSXGetViewFromResponder([keyWindow firstResponder]);
73 WXWidget wxWidgetImpl::FindFocus()
75 return GetFocusedViewInWindow( [NSApp keyWindow] );;
78 wxWidgetImpl* wxWidgetImpl::FindBestFromWXWidget(WXWidget control)
80 wxWidgetImpl* impl = FindFromWXWidget(control);
82 // NSScrollViews can have their subviews like NSClipView
83 // therefore check and use the NSScrollView peer in that case
84 if ( impl == NULL && [[control superview] isKindOfClass:[NSScrollView class]])
85 impl = FindFromWXWidget([control superview]);
91 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
95 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
96 wxRect bounds(x,y,w,h);
97 NSView* sv = (window->GetParent()->GetHandle() );
99 return wxToNSRect( sv, bounds );
102 @interface wxNSView : NSView
105 NSTrackingRectTag _lastToolTipTrackTag;
106 id _lastToolTipOwner;
113 @interface NSView(PossibleMethods)
114 - (void)setTitle:(NSString *)aString;
115 - (void)setStringValue:(NSString *)aString;
116 - (void)setIntValue:(int)anInt;
117 - (void)setFloatValue:(float)aFloat;
118 - (void)setDoubleValue:(double)aDouble;
122 - (void)setMinValue:(double)aDouble;
123 - (void)setMaxValue:(double)aDouble;
128 - (void)setEnabled:(BOOL)flag;
130 - (void)setImage:(NSImage *)image;
131 - (void)setControlSize:(NSControlSize)size;
133 - (void)setFont:(NSFont *)fontObject;
137 - (void)setTarget:(id)anObject;
138 - (void)setAction:(SEL)aSelector;
139 - (void)setDoubleAction:(SEL)aSelector;
140 - (void)setBackgroundColor:(NSColor*)aColor;
141 - (void)setOpaque:(BOOL)opaque;
142 - (void)setTextColor:(NSColor *)color;
143 - (void)setImagePosition:(NSCellImagePosition)aPosition;
146 // The following code is a combination of the code listed here:
147 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
148 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
149 // and the code here:
150 // http://inquisitivecocoa.com/category/objective-c/
151 @interface NSEvent (OsGuiUtilsAdditions)
152 - (NSString*) charactersIgnoringModifiersIncludingShift;
155 @implementation NSEvent (OsGuiUtilsAdditions)
156 - (NSString*) charactersIgnoringModifiersIncludingShift {
157 // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
158 // differently than AppKit.
159 NSString* c = [self charactersIgnoringModifiers];
160 if ([c length] == 1) {
161 unichar codepoint = [c characterAtIndex:0];
162 if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
166 // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
167 // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
168 // which hints the OS to use Latin characters where possible, which is generally what we want.
169 NSString* result = @"";
170 TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
171 CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
172 CFRelease(currentKeyboard);
174 // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
177 const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
178 if (keyboardLayout) {
179 UInt32 deadKeyState = 0;
180 UniCharCount maxStringLength = 255;
181 UniCharCount actualStringLength = 0;
182 UniChar unicodeString[maxStringLength];
184 OSStatus status = UCKeyTranslate(keyboardLayout,
187 cmdKey >> 8, // force the Command key to "on"
189 kUCKeyTranslateNoDeadKeysMask,
196 result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
202 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
206 if ([event type] != NSFlagsChanged)
208 NSString* s = [event charactersIgnoringModifiersIncludingShift];
209 // backspace char reports as delete w/modifiers for some reason
212 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
214 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
218 switch ( [s characterAtIndex:0] )
225 case NSUpArrowFunctionKey :
228 case NSDownArrowFunctionKey :
231 case NSLeftArrowFunctionKey :
234 case NSRightArrowFunctionKey :
237 case NSInsertFunctionKey :
240 case NSDeleteFunctionKey :
243 case NSHomeFunctionKey :
246 // case NSBeginFunctionKey :
247 // retval = WXK_BEGIN;
249 case NSEndFunctionKey :
252 case NSPageUpFunctionKey :
255 case NSPageDownFunctionKey :
256 retval = WXK_PAGEDOWN;
258 case NSHelpFunctionKey :
262 int intchar = [s characterAtIndex: 0];
263 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
264 retval = WXK_F1 + (intchar - NSF1FunctionKey );
265 else if ( intchar > 0 && intchar < 32 )
273 // Some keys don't seem to have constants. The code mimics the approach
274 // taken by WebKit. See:
275 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
276 switch( [event keyCode] )
281 retval = WXK_CONTROL;
285 retval = WXK_CAPITAL;
288 case 56: // Left Shift
289 case 60: // Right Shift
294 case 61: // Right Alt
298 case 59: // Left Ctrl
299 case 62: // Right Ctrl
300 retval = WXK_RAW_CONTROL;
314 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
315 // WXK_NUMPAD constants, but for the CHAR event we want to use the
316 // standard ascii values
317 if ( eventType != wxEVT_CHAR )
319 switch( [event keyCode] )
322 retval = WXK_NUMPAD_DIVIDE;
325 retval = WXK_NUMPAD_MULTIPLY;
328 retval = WXK_NUMPAD_SUBTRACT;
331 retval = WXK_NUMPAD_ADD;
334 retval = WXK_NUMPAD_ENTER;
337 retval = WXK_NUMPAD_DECIMAL;
340 retval = WXK_NUMPAD0;
343 retval = WXK_NUMPAD1;
346 retval = WXK_NUMPAD2;
349 retval = WXK_NUMPAD3;
352 retval = WXK_NUMPAD4;
355 retval = WXK_NUMPAD5;
358 retval = WXK_NUMPAD6;
361 retval = WXK_NUMPAD7;
364 retval = WXK_NUMPAD8;
367 retval = WXK_NUMPAD9;
370 //retval = [event keyCode];
377 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
379 UInt32 modifiers = [nsEvent modifierFlags] ;
380 int eventType = [nsEvent type];
382 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
383 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
384 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
385 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
387 wxevent.m_rawCode = [nsEvent keyCode];
388 wxevent.m_rawFlags = modifiers;
390 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
393 if ( eventType != NSFlagsChanged )
395 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
398 // if charString is set, it did not come from key up / key down
399 wxevent.SetEventType( wxEVT_CHAR );
400 chars = wxCFStringRef::AsString(charString);
404 chars = wxCFStringRef::AsString(nschars);
408 int aunichar = chars.Length() > 0 ? chars[0] : 0;
411 if (wxevent.GetEventType() != wxEVT_CHAR)
413 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
417 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
420 wxevent.SetEventType( wxEVT_KEY_UP ) ;
422 case NSFlagsChanged :
426 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
429 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
432 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
434 case WXK_RAW_CONTROL:
435 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
446 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
447 keyval = wxToupper( aunichar ) ;
453 // OS X generates events with key codes in Unicode private use area for
454 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
455 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
456 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
457 // WXK_NONE for "non characters" so explicitly exclude them.
459 // We only exclude the private use area inside the Basic Multilingual Plane
460 // as key codes beyond it don't seem to be currently used.
461 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
462 wxevent.m_uniChar = aunichar;
464 wxevent.m_keyCode = keyval;
466 wxWindowMac* peer = GetWXPeer();
469 wxevent.SetEventObject(peer);
470 wxevent.SetId(peer->GetId()) ;
474 UInt32 g_lastButton = 0 ;
475 bool g_lastButtonWasFakeRight = false ;
477 // better scroll wheel support
478 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
480 @interface NSEvent (DeviceDelta)
481 - (CGFloat)deviceDeltaX;
482 - (CGFloat)deviceDeltaY;
485 - (BOOL)hasPreciseScrollingDeltas;
486 - (CGFloat)scrollingDeltaX;
487 - (CGFloat)scrollingDeltaY;
490 void wxWidgetCocoaImpl::SetupCoordinates(wxCoord &x, wxCoord &y, NSEvent* nsEvent)
492 NSPoint locationInWindow = [nsEvent locationInWindow];
494 // adjust coordinates for the window of the target view
495 if ( [nsEvent window] != [m_osxView window] )
497 if ( [nsEvent window] != nil )
498 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
500 if ( [m_osxView window] != nil )
501 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
504 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
505 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
507 x = locationInViewWX.x;
508 y = locationInViewWX.y;
512 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
514 int eventType = [nsEvent type];
515 UInt32 modifiers = [nsEvent modifierFlags] ;
517 SetupCoordinates(wxevent.m_x, wxevent.m_y, nsEvent);
519 // these parameters are not given for all events
520 UInt32 button = [nsEvent buttonNumber];
521 UInt32 clickCount = 0;
523 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
524 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
525 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
526 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
527 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
529 UInt32 mouseChord = 0;
533 case NSLeftMouseDown :
534 case NSLeftMouseDragged :
537 case NSRightMouseDown :
538 case NSRightMouseDragged :
541 case NSOtherMouseDown :
542 case NSOtherMouseDragged :
547 // a control click is interpreted as a right click
548 bool thisButtonIsFakeRight = false ;
549 if ( button == 0 && (modifiers & NSControlKeyMask) )
552 thisButtonIsFakeRight = true ;
555 // otherwise we report double clicks by connecting a left click with a ctrl-left click
556 if ( clickCount > 1 && button != g_lastButton )
559 // we must make sure that our synthetic 'right' button corresponds in
560 // mouse down, moved and mouse up, and does not deliver a right down and left up
563 case NSLeftMouseDown :
564 case NSRightMouseDown :
565 case NSOtherMouseDown :
566 g_lastButton = button ;
567 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
574 g_lastButtonWasFakeRight = false ;
576 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
577 button = g_lastButton ;
579 // Adjust the chord mask to remove the primary button and add the
580 // secondary button. It is possible that the secondary button is
581 // already pressed, e.g. on a mouse connected to a laptop, but this
582 // possibility is ignored here:
583 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
584 mouseChord = ((mouseChord & ~1U) | 2U);
587 wxevent.m_leftDown = true ;
589 wxevent.m_rightDown = true ;
591 wxevent.m_middleDown = true ;
593 // translate into wx types
596 case NSLeftMouseDown :
597 case NSRightMouseDown :
598 case NSOtherMouseDown :
599 clickCount = [nsEvent clickCount];
603 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
607 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
611 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
620 case NSRightMouseUp :
621 case NSOtherMouseUp :
622 clickCount = [nsEvent clickCount];
626 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
630 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
634 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
647 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
649 if ( UMAGetSystemVersion() >= 0x1070 )
651 if ( [nsEvent hasPreciseScrollingDeltas] )
653 deltaX = [nsEvent scrollingDeltaX];
654 deltaY = [nsEvent scrollingDeltaY];
658 deltaX = [nsEvent scrollingDeltaX] * 10;
659 deltaY = [nsEvent scrollingDeltaY] * 10;
664 const EventRef cEvent = (EventRef) [nsEvent eventRef];
665 // see http://developer.apple.com/qa/qa2005/qa1453.html
666 // for more details on why we have to look for the exact type
668 bool isMouseScrollEvent = false;
670 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
672 if ( isMouseScrollEvent )
674 deltaX = [nsEvent deviceDeltaX];
675 deltaY = [nsEvent deviceDeltaY];
679 deltaX = ([nsEvent deltaX] * 10);
680 deltaY = ([nsEvent deltaY] * 10);
684 wxevent.m_wheelDelta = 10;
685 wxevent.m_linesPerAction = 1;
686 wxevent.m_columnsPerAction = 1;
688 if ( fabs(deltaX) > fabs(deltaY) )
690 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
691 wxevent.m_wheelRotation = (int)deltaX;
695 wxevent.m_wheelRotation = (int)deltaY;
701 case NSMouseEntered :
702 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
705 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
707 case NSLeftMouseDragged :
708 case NSRightMouseDragged :
709 case NSOtherMouseDragged :
711 wxevent.SetEventType( wxEVT_MOTION ) ;
717 wxevent.m_clickCount = clickCount;
718 wxWindowMac* peer = GetWXPeer();
721 wxevent.SetEventObject(peer);
722 wxevent.SetId(peer->GetId()) ;
726 @implementation wxNSView
730 static BOOL initialized = NO;
734 wxOSXCocoaClassAddWXMethods( self );
738 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
739 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
743 - (void)_sendToolTipMouseExited
745 // Nothing matters except window, trackingNumber, and userData.
746 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
747 location:NSMakePoint(0, 0)
750 windowNumber:[[self window] windowNumber]
753 trackingNumber:_lastToolTipTrackTag
754 userData:_lastUserData];
755 [_lastToolTipOwner mouseExited:fakeEvent];
758 - (void)_sendToolTipMouseEntered
760 // Nothing matters except window, trackingNumber, and userData.
761 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
762 location:NSMakePoint(0, 0)
765 windowNumber:[[self window] windowNumber]
768 trackingNumber:_lastToolTipTrackTag
769 userData:_lastUserData];
770 [_lastToolTipOwner mouseEntered:fakeEvent];
773 - (void)setToolTip:(NSString *)string;
779 [self _sendToolTipMouseExited];
782 [super setToolTip:string];
784 [self _sendToolTipMouseEntered];
790 [self _sendToolTipMouseExited];
791 [super setToolTip:nil];
797 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
799 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
802 _lastUserData = data;
803 _lastToolTipOwner = owner;
804 _lastToolTipTrackTag = tag;
809 - (void)removeTrackingRect:(NSTrackingRectTag)tag
811 if (tag == _lastToolTipTrackTag)
813 _lastUserData = NULL;
814 _lastToolTipOwner = nil;
815 _lastToolTipTrackTag = 0;
817 [super removeTrackingRect:tag];
820 #if wxOSX_USE_NATIVE_FLIPPED
827 - (BOOL) canBecomeKeyView
829 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
830 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
831 return viewimpl->GetWXPeer()->AcceptsFocus();
841 #if wxUSE_DRAG_AND_DROP
843 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
844 // for details on the NSPasteboard -> PasteboardRef conversion
846 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
848 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
850 return NSDragOperationNone;
852 return impl->draggingEntered(sender, self, _cmd);
855 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
857 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
861 return impl->draggingExited(sender, self, _cmd);
864 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
866 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
868 return NSDragOperationNone;
870 return impl->draggingUpdated(sender, self, _cmd);
873 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
875 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
877 return NSDragOperationNone;
879 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
884 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
886 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
890 impl->mouseEvent(event, self, _cmd);
893 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
895 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
899 impl->cursorUpdate(event, self, _cmd);
902 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
904 // This is needed to support click through, otherwise the first click on a window
905 // will not do anything unless it is the active window already.
909 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
911 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
915 impl->keyEvent(event, self, _cmd);
918 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
920 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
924 impl->insertText(text, self, _cmd);
927 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
929 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
933 return impl->performKeyEquivalent(event, self, _cmd);
936 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
938 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
942 return impl->acceptsFirstResponder(self, _cmd);
945 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
947 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
951 return impl->becomeFirstResponder(self, _cmd);
954 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
956 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
960 return impl->resignFirstResponder(self, _cmd);
963 #if !wxOSX_USE_NATIVE_FLIPPED
965 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
967 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
971 return impl->isFlipped(self, _cmd) ? YES:NO;
976 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
978 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
980 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
985 // OS X starts a NSUIHeartBeatThread for animating the default button in a
986 // dialog. This causes a drawRect of the active dialog from outside the
987 // main UI thread. This causes an occasional crash since the wx drawing
988 // objects (like wxPen) are not thread safe.
990 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
991 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
992 if ( !wxThread::IsMain() )
994 if ( impl->IsUserPane() )
996 wxWindow* win = impl->GetWXPeer();
997 if ( win->UseBgCol() )
1000 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1001 CGContextSaveGState( context );
1003 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
1004 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1005 CGContextFillRect( context, r );
1007 CGContextRestoreGState( context );
1012 // just call the superclass handler, we don't need any custom wx drawing
1013 // here and it seems to work fine:
1014 wxOSX_DrawRectHandlerPtr
1015 superimpl = (wxOSX_DrawRectHandlerPtr)
1016 [[self superclass] instanceMethodForSelector:_cmd];
1017 superimpl(self, _cmd, rect);
1022 #endif // wxUSE_THREADS
1024 return impl->drawRect(&rect, self, _cmd);
1027 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
1029 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1033 impl->controlAction(self, _cmd, sender);
1036 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
1038 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1042 impl->controlDoubleAction(self, _cmd, sender);
1045 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1047 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1048 NSPasteboard *pboard = [sender draggingPasteboard];
1049 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1051 wxWindow* wxpeer = GetWXPeer();
1052 if ( wxpeer == NULL )
1053 return NSDragOperationNone;
1055 wxDropTarget* target = wxpeer->GetDropTarget();
1056 if ( target == NULL )
1057 return NSDragOperationNone;
1059 wxDragResult result = wxDragNone;
1060 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1061 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1063 if ( sourceDragMask & NSDragOperationLink )
1064 result = wxDragLink;
1065 else if ( sourceDragMask & NSDragOperationCopy )
1066 result = wxDragCopy;
1067 else if ( sourceDragMask & NSDragOperationMove )
1068 result = wxDragMove;
1070 PasteboardRef pboardRef;
1071 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1072 target->SetCurrentDragPasteboard(pboardRef);
1073 result = target->OnEnter(pt.x, pt.y, result);
1074 CFRelease(pboardRef);
1076 NSDragOperation nsresult = NSDragOperationNone;
1080 nsresult = NSDragOperationLink;
1082 nsresult = NSDragOperationMove;
1084 nsresult = NSDragOperationCopy;
1091 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1093 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1094 NSPasteboard *pboard = [sender draggingPasteboard];
1096 wxWindow* wxpeer = GetWXPeer();
1097 if ( wxpeer == NULL )
1100 wxDropTarget* target = wxpeer->GetDropTarget();
1101 if ( target == NULL )
1104 PasteboardRef pboardRef;
1105 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1106 target->SetCurrentDragPasteboard(pboardRef);
1108 CFRelease(pboardRef);
1111 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1113 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1114 NSPasteboard *pboard = [sender draggingPasteboard];
1115 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1117 wxWindow* wxpeer = GetWXPeer();
1118 if ( wxpeer == NULL )
1119 return NSDragOperationNone;
1121 wxDropTarget* target = wxpeer->GetDropTarget();
1122 if ( target == NULL )
1123 return NSDragOperationNone;
1125 wxDragResult result = wxDragNone;
1126 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1127 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1129 if ( sourceDragMask & NSDragOperationLink )
1130 result = wxDragLink;
1131 else if ( sourceDragMask & NSDragOperationCopy )
1132 result = wxDragCopy;
1133 else if ( sourceDragMask & NSDragOperationMove )
1134 result = wxDragMove;
1136 PasteboardRef pboardRef;
1137 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1138 target->SetCurrentDragPasteboard(pboardRef);
1139 result = target->OnDragOver(pt.x, pt.y, result);
1140 CFRelease(pboardRef);
1142 NSDragOperation nsresult = NSDragOperationNone;
1146 nsresult = NSDragOperationLink;
1148 nsresult = NSDragOperationMove;
1150 nsresult = NSDragOperationCopy;
1157 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1159 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1161 NSPasteboard *pboard = [sender draggingPasteboard];
1162 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1164 wxWindow* wxpeer = GetWXPeer();
1165 wxDropTarget* target = wxpeer->GetDropTarget();
1166 wxDragResult result = wxDragNone;
1167 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1168 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1170 if ( sourceDragMask & NSDragOperationLink )
1171 result = wxDragLink;
1172 else if ( sourceDragMask & NSDragOperationCopy )
1173 result = wxDragCopy;
1174 else if ( sourceDragMask & NSDragOperationMove )
1175 result = wxDragMove;
1177 PasteboardRef pboardRef;
1178 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1179 target->SetCurrentDragPasteboard(pboardRef);
1181 if (target->OnDrop(pt.x, pt.y))
1182 result = target->OnData(pt.x, pt.y, result);
1184 CFRelease(pboardRef);
1186 return result != wxDragNone;
1189 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1191 // we are getting moved events for all windows in the hierarchy, not something wx expects
1192 // therefore we only handle it for the deepest child in the hierarchy
1193 if ( [event type] == NSMouseMoved )
1195 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1196 if ( hitview == NULL || hitview != slf)
1200 if ( !DoHandleMouseEvent(event) )
1202 // for plain NSView mouse events would propagate to parents otherwise
1203 // scrollwheel events have to be propagated if not handled in all cases
1204 if (!IsUserPane() || [event type] == NSScrollWheel )
1206 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1207 superimpl(slf, (SEL)_cmd, event);
1209 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1210 // only trigger if at this moment the mouse is already up
1211 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1213 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1214 SetupMouseEvent(wxevent , event) ;
1215 wxevent.SetEventType(wxEVT_LEFT_UP);
1217 GetWXPeer()->HandleWindowEvent(wxevent);
1223 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1225 if ( !SetupCursor(event) )
1227 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1228 superimpl(slf, (SEL)_cmd, event);
1232 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1234 extern wxCursor gGlobalCursor;
1236 if ( gGlobalCursor.IsOk() )
1238 gGlobalCursor.MacInstall();
1243 wxWindow* cursorTarget = GetWXPeer();
1245 SetupCoordinates(x, y, event);
1246 wxPoint cursorPoint( x , y ) ;
1248 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1250 // at least in GTK cursor events are not propagated either ...
1252 cursorTarget = NULL;
1254 cursorTarget = cursorTarget->GetParent() ;
1256 cursorPoint += cursorTarget->GetPosition();
1260 return cursorTarget != NULL;
1264 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1266 if ( [event type] == NSKeyDown )
1268 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1269 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1270 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1273 m_lastKeyDownEvent = event;
1276 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1278 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1279 superimpl(slf, (SEL)_cmd, event);
1281 m_lastKeyDownEvent = NULL;
1284 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1286 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1288 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1289 superimpl(slf, (SEL)_cmd, text);
1294 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1296 bool handled = false;
1298 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1299 SetupKeyEvent( wxevent, event );
1301 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1302 // walk up the ancestors ourselves but let cocoa do it
1304 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1307 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1309 wxCommandEvent command_event( wxEVT_MENU, command );
1310 command_event.SetEventObject( wxevent.GetEventObject() );
1311 handled = handler->ProcessEvent( command_event );
1315 // accelerators can also be used with buttons, try them too
1316 command_event.SetEventType(wxEVT_BUTTON);
1317 handled = handler->ProcessEvent( command_event );
1323 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1324 return superimpl(slf, (SEL)_cmd, event);
1329 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1332 return m_wxPeer->AcceptsFocus();
1335 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1336 return superimpl(slf, (SEL)_cmd);
1340 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1342 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1343 // get the current focus before running becomeFirstResponder
1344 NSView* otherView = FindFocus();
1346 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1347 BOOL r = superimpl(slf, (SEL)_cmd);
1350 DoNotifyFocusEvent( true, otherWindow );
1356 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1358 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1359 BOOL r = superimpl(slf, (SEL)_cmd);
1361 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
1362 NSView* otherView = wxOSXGetViewFromResponder(responder);
1364 wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
1366 // It doesn't make sense to notify about the loss of focus if it's the same
1367 // control in the end, and just a different subview
1368 if ( otherWindow == this )
1371 // NSTextViews have an editor as true responder, therefore the might get the
1372 // resign notification if their editor takes over, don't trigger any event then
1373 if ( r && !m_hasEditor)
1375 DoNotifyFocusEvent( false, otherWindow );
1380 #if !wxOSX_USE_NATIVE_FLIPPED
1382 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1389 #define OSX_DEBUG_DRAWING 0
1391 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1393 // preparing the update region
1397 // since adding many rects to a region is a costly process, by default use the bounding rect
1399 const NSRect *rects;
1401 [slf getRectsBeingDrawn:&rects count:&count];
1402 for ( int i = 0 ; i < count ; ++i )
1404 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1407 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1410 wxWindow* wxpeer = GetWXPeer();
1412 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1414 // as this update region is in native window locals we must adapt it to wx window local
1415 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1418 // Restrict the update region to the shape of the window, if any, and also
1419 // remember the region that we need to clear later.
1420 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1421 const bool isTopLevel = tlwParent == wxpeer;
1423 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1426 clearRgn = updateRgn;
1428 int xoffset = 0, yoffset = 0;
1429 wxRegion rgn = tlwParent->GetShape();
1430 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1431 rgn.Offset( xoffset, yoffset );
1432 updateRgn.Intersect(rgn);
1436 // Exclude the window shape from the region to be cleared below.
1437 rgn.Xor(wxpeer->GetSize());
1438 clearRgn.Intersect(rgn);
1442 wxpeer->GetUpdateRegion() = updateRgn;
1444 // setting up the drawing context
1446 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1447 CGContextSaveGState( context );
1449 #if OSX_DEBUG_DRAWING
1450 CGContextBeginPath( context );
1451 CGContextMoveToPoint(context, 0, 0);
1452 NSRect bounds = [slf bounds];
1453 CGContextAddLineToPoint(context, 10, 0);
1454 CGContextMoveToPoint(context, 0, 0);
1455 CGContextAddLineToPoint(context, 0, 10);
1456 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1457 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1458 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1459 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1460 CGContextClosePath( context );
1461 CGContextStrokePath(context);
1464 if ( ![slf isFlipped] )
1466 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1467 CGContextScaleCTM( context, 1, -1 );
1470 wxpeer->MacSetCGContextRef( context );
1472 bool handled = wxpeer->MacDoRedraw( 0 );
1473 CGContextRestoreGState( context );
1475 CGContextSaveGState( context );
1479 SEL _cmd = @selector(drawRect:);
1480 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1481 superimpl(slf, _cmd, *(NSRect*)rect);
1482 CGContextRestoreGState( context );
1483 CGContextSaveGState( context );
1485 // as we called restore above, we have to flip again if necessary
1486 if ( ![slf isFlipped] )
1488 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1489 CGContextScaleCTM( context, 1, -1 );
1494 // We also need to explicitly draw the part of the top level window
1495 // outside of its region with transparent colour to ensure that it is
1496 // really transparent.
1497 if ( clearRgn.IsOk() )
1499 wxMacCGContextStateSaver saveState(context);
1500 wxWindowDC dc(wxpeer);
1501 dc.SetBackground(wxBrush(wxTransparentColour));
1502 dc.SetDeviceClippingRegion(clearRgn);
1506 #if wxUSE_GRAPHICS_CONTEXT
1507 // If the window shape is defined by a path, stroke the path to show
1508 // the window border.
1509 const wxGraphicsPath& path = tlwParent->GetShapePath();
1510 if ( !path.IsNull() )
1512 CGContextSetLineWidth(context, 1);
1513 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1514 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1515 CGContextStrokePath(context);
1517 #endif // wxUSE_GRAPHICS_CONTEXT
1520 wxpeer->MacPaintChildrenBorders();
1521 wxpeer->MacSetCGContextRef( NULL );
1522 CGContextRestoreGState( context );
1525 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1527 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1530 wxpeer->OSXSimulateFocusEvents();
1531 wxpeer->OSXHandleClicked(0);
1535 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1539 void wxWidgetCocoaImpl::controlTextDidChange()
1541 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1544 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1545 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1546 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1548 tc->SendTextUpdatedEventIfAllowed();
1550 cb->SendTextUpdatedEventIfAllowed();
1553 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1560 #if OBJC_API_VERSION >= 2
1562 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1563 class_addMethod(c, s, i, t );
1567 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1568 { s, (char*) t, i },
1572 void wxOSXCocoaClassAddWXMethods(Class c)
1575 #if OBJC_API_VERSION < 2
1576 static objc_method wxmethods[] =
1580 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1581 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1582 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1584 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1585 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1586 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1588 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1591 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1592 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1594 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1596 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1597 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1598 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1600 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1603 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1604 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1606 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1608 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1610 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1611 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1612 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1614 #if !wxOSX_USE_NATIVE_FLIPPED
1615 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1617 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1619 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1620 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1622 #if wxUSE_DRAG_AND_DROP
1623 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1624 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1625 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1626 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1629 #if OBJC_API_VERSION < 2
1631 static int method_count = WXSIZEOF( wxmethods );
1632 static objc_method_list *wxmethodlist = NULL;
1633 if ( wxmethodlist == NULL )
1635 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1636 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1637 wxmethodlist->method_count = method_count;
1638 wxmethodlist->obsolete = 0;
1640 class_addMethods( c, wxmethodlist );
1645 // C++ implementation class
1648 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1650 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1651 wxWidgetImpl( peer, isRootControl, isUserPane )
1656 // check if the user wants to create the control initially hidden
1657 if ( !peer->IsShown() )
1658 SetVisibility(false);
1660 // gc aware handling
1662 CFRetain(m_osxView);
1663 [m_osxView release];
1666 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1671 void wxWidgetCocoaImpl::Init()
1674 #if !wxOSX_USE_NATIVE_FLIPPED
1677 m_lastKeyDownEvent = NULL;
1678 m_hasEditor = false;
1681 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1683 RemoveAssociations( this );
1685 if ( !IsRootControl() )
1687 NSView *sv = [m_osxView superview];
1689 [m_osxView removeFromSuperview];
1691 // gc aware handling
1693 CFRelease(m_osxView);
1696 bool wxWidgetCocoaImpl::IsVisible() const
1698 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1701 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1703 [m_osxView setHidden:(visible ? NO:YES)];
1706 // ----------------------------------------------------------------------------
1707 // window animation stuff
1708 // ----------------------------------------------------------------------------
1710 // define a delegate used to refresh the window during animation
1711 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1717 - (id)init:(wxWindow *)win;
1721 // NSAnimationDelegate methods
1722 - (void)animationDidEnd:(NSAnimation*)animation;
1723 - (void)animation:(NSAnimation*)animation
1724 didReachProgressMark:(NSAnimationProgress)progress;
1727 @implementation wxNSAnimationDelegate
1729 - (id)init:(wxWindow *)win
1731 self = [super init];
1744 - (void)animation:(NSAnimation*)animation
1745 didReachProgressMark:(NSAnimationProgress)progress
1747 wxUnusedVar(animation);
1748 wxUnusedVar(progress);
1750 m_win->SendSizeEvent();
1753 - (void)animationDidEnd:(NSAnimation*)animation
1755 wxUnusedVar(animation);
1763 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1765 wxShowEffect effect,
1768 // create the dictionary describing the animation to perform on this view
1770 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1771 NSMutableDictionary * const
1772 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1773 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1775 // determine the start and end rectangles assuming we're hiding the window
1776 const wxRect rectOrig = win->GetRect();
1784 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1785 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1786 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1787 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1788 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1789 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1790 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1791 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1792 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1793 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1794 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1795 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1800 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1801 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1805 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1806 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1807 rectEnd.x = rectStart.GetRight();
1811 case wxSHOW_EFFECT_ROLL_TO_TOP:
1812 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1816 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1817 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1818 rectEnd.y = rectStart.GetBottom();
1822 case wxSHOW_EFFECT_EXPAND:
1823 rectEnd.x = rectStart.x + rectStart.width / 2;
1824 rectEnd.y = rectStart.y + rectStart.height / 2;
1829 case wxSHOW_EFFECT_BLEND:
1830 [dict setObject:(show ? NSViewAnimationFadeInEffect
1831 : NSViewAnimationFadeOutEffect)
1832 forKey:NSViewAnimationEffectKey];
1835 case wxSHOW_EFFECT_NONE:
1836 case wxSHOW_EFFECT_MAX:
1837 wxFAIL_MSG( "unexpected animation effect" );
1841 wxFAIL_MSG( "unknown animation effect" );
1847 // we need to restore it to the original rectangle instead of making it
1849 wxSwap(rectStart, rectEnd);
1851 // and as the window is currently hidden, we need to show it for the
1852 // animation to be visible at all (but don't restore it at its full
1853 // rectangle as it shouldn't appear immediately)
1854 win->SetSize(rectStart);
1858 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1859 ? [(NSView *)viewOrWin superview]
1861 const NSRect rStart = wxToNSRect(parentView, rectStart);
1862 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1864 [dict setObject:[NSValue valueWithRect:rStart]
1865 forKey:NSViewAnimationStartFrameKey];
1866 [dict setObject:[NSValue valueWithRect:rEnd]
1867 forKey:NSViewAnimationEndFrameKey];
1869 // create an animation using the values in the above dictionary
1870 NSViewAnimation * const
1871 anim = [[NSViewAnimation alloc]
1872 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1876 // what is a good default duration? Windows uses 200ms, Web frameworks
1877 // use anything from 250ms to 1s... choose something in the middle
1881 [anim setDuration:timeout/1000.]; // duration is in seconds here
1883 // if the window being animated changes its layout depending on its size
1884 // (which is almost always the case) we need to redo it during animation
1886 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1887 // controls in wxInfoBar visibly jump around)
1888 const int NUM_LAYOUTS = 20;
1889 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1890 [anim addProgressMark:f];
1892 wxNSAnimationDelegate * const
1893 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1894 [anim setDelegate:animDelegate];
1895 [anim startAnimation];
1897 // Cocoa is capable of doing animation asynchronously or even from separate
1898 // thread but wx API doesn't provide any way to be notified about the
1899 // animation end and without this we really must ensure that the window has
1900 // the expected (i.e. the same as if a simple Show() had been used) size
1901 // when we return, so block here until the animation finishes
1903 // notice that because the default animation mode is NSAnimationBlocking,
1904 // no user input events ought to be processed from here
1906 wxEventLoopGuarantor ensureEventLoopExistence;
1907 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1908 while ( ![animDelegate isDone] )
1914 // NSViewAnimation is smart enough to hide the NSView being animated at
1915 // the end but we also must ensure that it's hidden for wx too
1918 // and we must also restore its size because it isn't expected to
1919 // change just because the window was hidden
1920 win->SetSize(rectOrig);
1924 // refresh it once again after the end to ensure that everything is in
1926 win->SendSizeEvent();
1929 [anim setDelegate:nil];
1930 [animDelegate release];
1936 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1937 wxShowEffect effect,
1940 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1943 /* note that the drawing order between siblings is not defined under 10.4 */
1944 /* only starting from 10.5 the subview order is respected */
1946 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1947 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1948 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1949 * expects a function returning the new non-enum NSComparsionResult.
1950 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1952 #if defined(NSINTEGER_DEFINED)
1953 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1955 typedef int CocoaWindowCompareFunctionResult;
1958 class CocoaWindowCompareContext
1960 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1962 CocoaWindowCompareContext(); // Not implemented
1963 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1966 // Cocoa sorts subviews in-place.. make a copy
1967 m_subviews = [subviews copy];
1970 ~CocoaWindowCompareContext()
1971 { // release the copy
1972 [m_subviews release];
1975 { return m_target; }
1978 { return m_subviews; }
1980 /* Helper function that returns the comparison based off of the original ordering */
1981 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1983 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1984 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1985 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1986 // likely compare higher than the other view which is reasonable considering the only way that
1987 // can happen is if the subview was added after our call to subviews but before the call to
1988 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1989 // that case should never occur anyway because that would imply a multi-threaded GUI call
1990 // which is a big no-no with Cocoa.
1992 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1993 NSComparisonResult result = (firstI < secondI)
1994 ? NSOrderedAscending /* -1 */
1995 : (firstI > secondI)
1996 ? NSOrderedDescending /* 1 */
1997 : NSOrderedSame /* 0 */;
2002 /* The subview we are trying to Raise or Lower */
2004 /* A copy of the original array of subviews */
2005 NSArray *m_subviews;
2008 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2009 * the target view is always higher than every other view. When comparing two views neither of
2010 * which is the target, it returns the correct response based on the original ordering
2012 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2014 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2015 // first should be ordered higher
2016 if(first==compareContext->target())
2017 return NSOrderedDescending;
2018 // second should be ordered higher
2019 if(second==compareContext->target())
2020 return NSOrderedAscending;
2021 return compareContext->CompareUsingOriginalOrdering(first,second);
2024 void wxWidgetCocoaImpl::Raise()
2026 NSView* nsview = m_osxView;
2028 NSView *superview = [nsview superview];
2029 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2031 [superview sortSubviewsUsingFunction:
2032 CocoaRaiseWindowCompareFunction
2033 context: &compareContext];
2037 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2038 * the target view is always lower than every other view. When comparing two views neither of
2039 * which is the target, it returns the correct response based on the original ordering
2041 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2043 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2044 // first should be ordered lower
2045 if(first==compareContext->target())
2046 return NSOrderedAscending;
2047 // second should be ordered lower
2048 if(second==compareContext->target())
2049 return NSOrderedDescending;
2050 return compareContext->CompareUsingOriginalOrdering(first,second);
2053 void wxWidgetCocoaImpl::Lower()
2055 NSView* nsview = m_osxView;
2057 NSView *superview = [nsview superview];
2058 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2060 [superview sortSubviewsUsingFunction:
2061 CocoaLowerWindowCompareFunction
2062 context: &compareContext];
2065 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2070 // We should do something like this, but it wasn't working in 10.4.
2071 if (GetNeedsDisplay() )
2075 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2076 NSSize offset = NSMakeSize((float)dx, (float)dy);
2077 [m_osxView scrollRect:r by:offset];
2081 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2083 wxWindowMac* parent = GetWXPeer()->GetParent();
2084 // under Cocoa we might have a contentView in the wxParent to which we have to
2085 // adjust the coordinates
2086 if (parent && [m_osxView superview] != parent->GetHandle() )
2088 int cx = 0,cy = 0,cw = 0,ch = 0;
2089 if ( parent->GetPeer() )
2091 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2096 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2097 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2098 [m_osxView setFrame:r];
2099 [[m_osxView superview] setNeedsDisplayInRect:r];
2102 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2104 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2108 // under Cocoa we might have a contentView in the wxParent to which we have to
2109 // adjust the coordinates
2110 wxWindowMac* parent = GetWXPeer()->GetParent();
2111 if (parent && [m_osxView superview] != parent->GetHandle() )
2113 int cx = 0,cy = 0,cw = 0,ch = 0;
2114 if ( parent->GetPeer() )
2116 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2123 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2125 NSRect rect = [m_osxView frame];
2126 width = (int)rect.size.width;
2127 height = (int)rect.size.height;
2130 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2132 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2134 NSView* cv = [m_osxView contentView];
2136 NSRect bounds = [m_osxView bounds];
2137 NSRect rect = [cv frame];
2139 int y = (int)rect.origin.y;
2140 int x = (int)rect.origin.x;
2141 if ( ![ m_osxView isFlipped ] )
2142 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2145 width = (int)rect.size.width;
2146 height = (int)rect.size.height;
2151 GetSize( width, height );
2155 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2158 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2160 [m_osxView setNeedsDisplay:YES];
2163 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2165 return [m_osxView needsDisplay];
2168 bool wxWidgetCocoaImpl::CanFocus() const
2170 return [m_osxView canBecomeKeyView] == YES;
2173 bool wxWidgetCocoaImpl::HasFocus() const
2175 return ( FindFocus() == m_osxView );
2178 bool wxWidgetCocoaImpl::SetFocus()
2183 // TODO remove if no issues arise: should not raise the window, only assign focus
2184 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2185 [[m_osxView window] makeFirstResponder: m_osxView] ;
2189 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2191 [m_osxView unregisterDraggedTypes];
2193 if ( target == NULL )
2196 wxDataObject* dobj = target->GetDataObject();
2200 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2201 dobj->AddSupportedTypes(typesarray);
2202 NSView* targetView = m_osxView;
2203 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2204 targetView = [(NSScrollView*) m_osxView documentView];
2206 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2207 CFRelease(typesarray);
2211 void wxWidgetCocoaImpl::RemoveFromParent()
2213 [m_osxView removeFromSuperview];
2216 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2218 NSView* container = parent->GetWXWidget() ;
2219 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2220 [container addSubview:m_osxView];
2222 if( m_wxPeer->IsFrozen() )
2223 [[m_osxView window] disableFlushWindow];
2226 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2228 NSView* targetView = m_osxView;
2229 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2230 targetView = [(NSScrollView*) m_osxView documentView];
2232 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2234 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2235 green:(CGFloat) (col.Green() / 255.0)
2236 blue:(CGFloat) (col.Blue() / 255.0)
2237 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2241 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2243 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2245 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2247 [m_osxView setOpaque: opaque];
2253 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2255 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2257 wxCFStringRef cf( title , encoding );
2258 [m_osxView setTitle:cf.AsNSString()];
2260 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2262 wxCFStringRef cf( title , encoding );
2263 [m_osxView setStringValue:cf.AsNSString()];
2268 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2270 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2271 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2272 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2275 wxInt32 wxWidgetCocoaImpl::GetValue() const
2277 return [(NSControl*)m_osxView intValue];
2280 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2282 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2284 [m_osxView setIntValue:v];
2286 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2288 [m_osxView setFloatValue:(double)v];
2290 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2292 [m_osxView setDoubleValue:(double)v];
2296 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2298 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2300 [m_osxView setMinValue:(double)v];
2304 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2306 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2308 [m_osxView setMaxValue:(double)v];
2312 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2314 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2316 return (int)[m_osxView minValue];
2321 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2323 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2325 return (int)[m_osxView maxValue];
2330 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2334 // TODO: how to create a wxBitmap from NSImage?
2336 if ( [m_osxView respondsToSelector:@selector(image:)] )
2337 bmp = [m_osxView image];
2343 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2345 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2348 [m_osxView setImage:bitmap.GetNSImage()];
2350 [m_osxView setImage:nil];
2352 [m_osxView setNeedsDisplay:YES];
2356 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2358 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2360 NSCellImagePosition pos;
2380 wxFAIL_MSG( "invalid image position" );
2384 [m_osxView setImagePosition:pos];
2388 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2390 // implementation in subclass
2393 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2395 r->x = r->y = r->width = r->height = 0;
2397 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2399 NSRect former = [m_osxView frame];
2400 [m_osxView sizeToFit];
2401 NSRect best = [m_osxView frame];
2402 [m_osxView setFrame:former];
2403 r->width = (int)best.size.width;
2404 r->height = (int)best.size.height;
2408 bool wxWidgetCocoaImpl::IsEnabled() const
2410 NSView* targetView = m_osxView;
2411 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2412 targetView = [(NSScrollView*) m_osxView documentView];
2414 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2415 return [targetView isEnabled];
2419 void wxWidgetCocoaImpl::Enable( bool enable )
2421 NSView* targetView = m_osxView;
2422 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2423 targetView = [(NSScrollView*) m_osxView documentView];
2425 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2426 [targetView setEnabled:enable];
2429 void wxWidgetCocoaImpl::PulseGauge()
2433 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2437 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2439 NSControlSize size = NSRegularControlSize;
2443 case wxWINDOW_VARIANT_NORMAL :
2444 size = NSRegularControlSize;
2447 case wxWINDOW_VARIANT_SMALL :
2448 size = NSSmallControlSize;
2451 case wxWINDOW_VARIANT_MINI :
2452 size = NSMiniControlSize;
2455 case wxWINDOW_VARIANT_LARGE :
2456 size = NSRegularControlSize;
2460 wxFAIL_MSG(wxT("unexpected window variant"));
2463 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2464 [m_osxView setControlSize:size];
2465 else if ([m_osxView respondsToSelector:@selector(cell)])
2467 id cell = [(id)m_osxView cell];
2468 if ([cell respondsToSelector:@selector(setControlSize:)])
2469 [cell setControlSize:size];
2472 // we need to propagate this to inner views as well
2473 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2475 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2477 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2478 [targetView setControlSize:size];
2479 else if ([targetView respondsToSelector:@selector(cell)])
2481 id cell = [(id)targetView cell];
2482 if ([cell respondsToSelector:@selector(setControlSize:)])
2483 [cell setControlSize:size];
2488 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2490 NSView* targetView = m_osxView;
2491 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2492 targetView = [(NSScrollView*) m_osxView documentView];
2494 if ([targetView respondsToSelector:@selector(setFont:)])
2495 [targetView setFont: font.OSXGetNSFont()];
2496 if ([targetView respondsToSelector:@selector(setTextColor:)])
2497 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2498 green:(CGFloat) (col.Green() / 255.0)
2499 blue:(CGFloat) (col.Blue() / 255.0)
2500 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2503 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2507 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2508 [m_osxView setToolTip: cf.AsNSString()];
2512 [m_osxView setToolTip:nil];
2516 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2518 WXWidget c = control ? control : (WXWidget) m_osxView;
2519 wxWidgetImpl::Associate( c, this ) ;
2520 if ([c respondsToSelector:@selector(setAction:)])
2523 if ( dynamic_cast<wxRadioButton*>(GetWXPeer()) )
2525 // everything already set up
2528 [c setAction: @selector(controlAction:)];
2530 if ([c respondsToSelector:@selector(setDoubleAction:)])
2532 [c setDoubleAction: @selector(controlDoubleAction:)];
2536 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2537 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2538 [m_osxView addTrackingArea: area];
2542 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2544 wxKeyEvent wxevent(wxEVT_CHAR);
2545 SetupKeyEvent( wxevent, event, text );
2547 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2550 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2552 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2553 SetupKeyEvent( wxevent, event );
2555 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2556 // the key is pressed, not when it's released (the type of wxevent is
2557 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2558 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2560 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2561 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2562 && !eventHook.IsNextEventAllowed() )
2566 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2568 // this will fire higher level events, like insertText, to help
2569 // us handle EVT_CHAR, etc.
2573 if ( [event type] == NSKeyDown)
2575 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2577 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2579 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2580 wxKeyEvent wxevent2(wxevent) ;
2581 wxevent2.SetEventType(wxEVT_CHAR);
2582 SetupKeyEvent( wxevent2, event );
2583 wxevent2.m_keyCode = keycode;
2584 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2586 else if (wxevent.CmdDown())
2588 wxKeyEvent wxevent2(wxevent) ;
2589 wxevent2.SetEventType(wxEVT_CHAR);
2590 SetupKeyEvent( wxevent2, event );
2591 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2595 if ( IsUserPane() && !wxevent.CmdDown() )
2597 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2598 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2600 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2610 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2612 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2613 SetupMouseEvent(wxevent , event) ;
2614 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2616 (void)SetupCursor(event);
2621 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2623 wxWindow* thisWindow = GetWXPeer();
2624 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2626 thisWindow->MacInvalidateBorders();
2629 if ( receivedFocus )
2631 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2632 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2633 thisWindow->HandleWindowEvent(eventFocus);
2636 if ( thisWindow->GetCaret() )
2637 thisWindow->GetCaret()->OnSetFocus();
2640 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2641 event.SetEventObject(thisWindow);
2643 event.SetWindow(otherWindow->GetWXPeer());
2644 thisWindow->HandleWindowEvent(event) ;
2646 else // !receivedFocus
2649 if ( thisWindow->GetCaret() )
2650 thisWindow->GetCaret()->OnKillFocus();
2653 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2655 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2656 event.SetEventObject(thisWindow);
2658 event.SetWindow(otherWindow->GetWXPeer());
2659 thisWindow->HandleWindowEvent(event) ;
2663 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2667 NSPoint location = [NSEvent mouseLocation];
2668 location = [[m_osxView window] convertScreenToBase:location];
2669 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2671 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2673 [(NSCursor*)cursor.GetHCURSOR() set];
2678 void wxWidgetCocoaImpl::CaptureMouse()
2680 // TODO remove if we don't get into problems with cursor settings
2681 // [[m_osxView window] disableCursorRects];
2684 void wxWidgetCocoaImpl::ReleaseMouse()
2686 // TODO remove if we don't get into problems with cursor settings
2687 // [[m_osxView window] enableCursorRects];
2690 #if !wxOSX_USE_NATIVE_FLIPPED
2692 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2694 m_isFlipped = flipped;
2699 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2703 [[m_osxView window] enableFlushWindow];
2704 [m_osxView setNeedsDisplay:YES];
2708 [[m_osxView window] disableFlushWindow];
2715 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2716 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2717 long WXUNUSED(style), long WXUNUSED(extraStyle))
2719 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2720 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2722 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2726 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2728 NSWindow* tlw = now->GetWXWindow();
2730 wxWidgetCocoaImpl* c = NULL;
2731 if ( now->IsNativeWindowWrapper() )
2733 NSView* cv = [tlw contentView];
2734 c = new wxWidgetCocoaImpl( now, cv, true );
2737 // increase ref count, because the impl destructor will decrement it again
2739 if ( !now->IsShown() )
2745 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2746 c = new wxWidgetCocoaImpl( now, v, true );
2747 c->InstallEventHandler();
2748 [tlw setContentView:v];